@luxalgo/vela-pinets 0.2.7 → 0.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1306,7 +1306,8 @@ function preparePine(source, instanceId, defaultProps, propsVisibility = "all")
1306
1306
  const inputs = mapInputs(scanned.getInputsMeta());
1307
1307
  const props = propsFor(scanned, defaultProps, propsVisibility);
1308
1308
  const overlay = /overlay\s*[:=]\s*true/.test(source);
1309
- const title = source.match(/(?:indicator|strategy)\(\s*["']([^"']+)["']/)?.[1] ?? "Indicator";
1309
+ const declared = /^\s*(?:indicator|strategy)\s*\(\s*(?:title\s*=\s*)?(["'])((?:\\.|(?!\1).)*)\1/m.exec(source)?.[2];
1310
+ const title = declared?.replace(/\\(.)/g, "$1").trim() || "Indicator";
1310
1311
  const reactsToViewport = /chart\.(left|right)_visible_bar(_time)?\b/.test(source);
1311
1312
  return { language: "pine", inputs, ...props.length > 0 ? { props } : {}, meta: { title, overlay }, reactsToViewport, token: { source, instanceId } };
1312
1313
  }
@@ -1386,11 +1387,12 @@ function tfMinutesFor(tf) {
1386
1387
  return null;
1387
1388
  }
1388
1389
  function sessionCloser(bars, tf, syminfo) {
1390
+ const si = typeof syminfo === "object" && syminfo != null ? syminfo : null;
1389
1391
  const tfMin = tfMinutesFor(tf);
1390
- const regular = sessionSpan(syminfo?.session);
1391
- const tz = typeof syminfo?.timezone === "string" ? syminfo.timezone : null;
1392
+ const regular = sessionSpan(si?.session);
1393
+ const tz = typeof si?.timezone === "string" ? si.timezone : null;
1392
1394
  if (tfMin == null || regular == null || tz == null || bars.length === 0) return null;
1393
- const extended = sessionSpan(syminfo?.session_extended);
1395
+ const extended = sessionSpan(si?.session_extended);
1394
1396
  let active = regular;
1395
1397
  if (extended) {
1396
1398
  for (const b of bars) {
@@ -1664,7 +1666,7 @@ var PineEngine = class {
1664
1666
  };
1665
1667
 
1666
1668
  // inline-worker:D:\Projects\LuxAlgo-Vela\repos\Vela-pinets\src\pinets-worker\worker.ts
1667
- var worker_default = '"use strict";(()=>{var yc=Object.defineProperty;var gc=(t,e,n)=>e in t?yc(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var ia=(t,e,n)=>gc(t,typeof e!="symbol"?e+"":e,n);function _c(t){return e=>new q(e.array.map(n=>Math.abs(n)),e.type,t)}function xc(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)}}function bc(t){return(e,n)=>{let r=e.array,i=0,s=r.length-1;for(;i<=s;){let a=Math.floor((i+s)/2),o=r[a];if(o===n)return a;o<n?i=a+1:s=a-1}return-1}}function wc(t){return(e,n)=>{let r=e.array,i=0,s=r.length;for(;i<s;){let a=Math.floor((i+s)/2);r[a]<n?i=a+1:s=a}return i<r.length&&r[i]===n?i:i-1}}function vc(t){return(e,n)=>{let r=e.array,i=0,s=r.length;for(;i<s;){let a=Math.floor((i+s)/2);r[a]<=n?i=a+1:s=a}return i>0&&r[i-1]===n?i-1:i}}function Ec(t){return e=>{e.array.length=0}}function Sc(t){return(e,n)=>(e.array.push(...n.array),e)}function Cc(t){return e=>new q([...e.array],e.type,t)}function Nc(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]),x=Number(s[f]);!isNaN(m)&&m!==null&&m!==void 0&&!isNaN(x)&&x!==null&&x!==void 0&&(a+=m,o+=x,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]),x=Number(s[f]);p+=(m-u)*(x-h)}let d=r?l:l-1;return d<=0?NaN:t.precision(p/d)}}function kc(t){return e=>e.array.every(n=>!isNaN(n)&&n)}function Ic(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 it(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 qn(t,e){if(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 Ac(t){return(e,n,r=0,i)=>{let s=e.array.length,a=i!==void 0?Math.min(i,s):s;for(let o=r;o<a;o++){if(!qn(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.`);e.array[o]=typeof n=="number"?t.precision(n):n}}}function Tc(t){return e=>e.array.length>0?e.array[0]:t.NA}function Dc(t){return(e,n)=>(n<0&&(n=e.array.length+n),n<0||n>=e.array.length?(t.warn(`Index ${n} is out of bounds, array size is ${e.array.length}.`,"array.get"),NaN):e.array[n])}function Mc(t){return(e,n)=>e.array.includes(n)}function Pc(t){return(e,n)=>typeof n=="number"&&n!==n?e.array.findIndex(r=>typeof r=="number"&&r!==r):e.array.indexOf(n)}function Rc(t){return(e,n,r)=>{if(!qn(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.`);if(n<0&&(n=e.array.length+n),n<0||n>e.array.length){t.warn(`Index ${n} is out of bounds, array size is ${e.array.length}.`,"array.insert");return}e.array.splice(n,0,r)}}function Fc(t){return(e,n=",")=>e.array.join(n)}function Bc(t){return e=>e.array.length>0?e.array[e.array.length-1]:t.NA}function Lc(t){return(e,n)=>e.array.lastIndexOf(n)}function Oc(t){return(e,n=0)=>{let r=e.array;if(r.length===0)return t.NA;if(n===0){let i=r[0];for(let s=1;s<r.length;s++)r[s]>i&&(i=r[s]);return i??t.NA}return[...r].sort((i,s)=>s-i)[n]??t.NA}}function Vc(t){return e=>{let n=e.array;if(n.length===0)return NaN;let r=new Array(n.length);for(let s=0;s<n.length;s++)r[s]=n[s];r.sort((s,a)=>s-a);let i=Math.floor(r.length/2);return r.length%2!==0?r[i]:(r[i-1]+r[i])/2}}function jc(t){return(e,n=0)=>{let r=e.array;if(r.length===0)return t.NA;if(n===0){let i=r[0];for(let s=1;s<r.length;s++)r[s]<i&&(i=r[s]);return i??t.NA}return[...r].sort((i,s)=>i-s)[n]??t.NA}}function $c(t){return e=>{if(e.array.length===0)return NaN;let n=new Map,r=0;for(let s of e.array){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[0]}}function Wc(t){return(e,n)=>{let r=e.array,i=r.length;if(i===0)return NaN;let s=new Array(i);for(let c=0;c<i;c++){let u=Number(r[c]);if(isNaN(u)||u===null||u===void 0)return NaN;s[c]=u}s.sort((c,u)=>c-u),n<0&&(n=0),n>100&&(n=100);let a=n/100*i-.5;if(a<=0)return t.precision(s[0]);if(a>=i-1)return t.precision(s[i-1]);let o=Math.floor(a),l=a-o;return t.precision(s[o]*(1-l)+s[o+1]*l)}}function Uc(t){return(e,n)=>{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),n<0&&(n=0),n>100&&(n=100);let a=Math.ceil(n/100*i);return a<=0?s[0]:a>s.length?NaN:s[a-1]}}function qc(t){return(e,n)=>{if(e.array.length===0)return NaN;let r=Math.floor(n);if(r<0||r>=e.array.length)return NaN;let i=Number(e.array[r]);if(isNaN(i)||i===null||i===void 0)return NaN;let s=0;for(let o of e.array){let l=Number(o);!isNaN(l)&&l!==null&&l!==void 0&&l<i&&s++}let a=e.array.length-1;return a<=0?NaN:s/a*100}}function zc(t){return e=>e.array.pop()}function Kc(t){return(e,n)=>{if(!qn(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 Hc(t){return e=>t.precision(t.pine.array.max(e)-t.pine.array.min(e))}function Gc(t){return(e,n)=>(n<0&&(n=e.array.length+n),n<0||n>=e.array.length?(t.warn(`Index ${n} is out of bounds, array size is ${e.array.length}.`,"array.remove"),NaN):e.array.splice(n,1)[0])}function Yc(t){return e=>{e.array.reverse()}}function Zc(t){return(e,n,r)=>{if(!qn(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.`);if(n<0&&(n=e.array.length+n),n<0||n>=e.array.length){t.warn(`Index ${n} is out of bounds, array size is ${e.array.length}.`,"array.set");return}e.array[n]=typeof r=="number"?t.precision(r):r}}function Xc(t){return e=>e.array.shift()}function Qc(t){return e=>e.array.length}function Jc(t){return(e,n,r)=>{let i=r!==void 0?r:void 0;return new q(e.array.slice(n,i),e.type,t)}}function eu(t){return e=>e.array.some(n=>!isNaN(n)&&n)}var yn=(t=>(t[t.ascending=1]="ascending",t[t.descending=0]="descending",t))(yn||{}),$a=(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))($a||{}),Wa=(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))(Wa||{}),Ua=(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))(Ua||{}),qa=(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))(qa||{}),za=(t=>(t.abovebar="AboveBar",t.belowbar="BelowBar",t.absolute="Absolute",t.bottom="Bottom",t.top="Top",t))(za||{}),Ka=(t=>(t.auto="auto",t.tiny="tiny",t.small="small",t.normal="normal",t.large="large",t.huge="huge",t))(Ka||{}),Ha=(t=>(t.inherit="inherit",t.mintick="mintick",t.percent="percent",t.price="price",t.volume="volume",t))(Ha||{}),tu=(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))(tu||{}),Ga=(t=>(t.gaps_on="gaps_on",t.gaps_off="gaps_off",t.lookahead_on="lookahead_on",t.lookahead_off="lookahead_off",t))(Ga||{}),Ya=(t=>(t.bar_index="bi",t.bar_time="bt",t))(Ya||{}),Za=(t=>(t.price="pr",t.abovebar="ab",t.belowbar="bl",t))(Za||{}),Xa=(t=>(t.left="l",t.right="r",t.both="b",t.none="n",t))(Xa||{}),Qa=(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))(Qa||{}),Ja=(t=>(t.family_default="default",t.family_monospace="monospace",t))(Ja||{}),eo=(t=>(t.none="none",t.splits="splits",t.dividends="dividends",t))(eo||{}),to=(t=>(t.inherit="inherit",t.off="off",t.on="on",t))(to||{}),no=(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))(no||{}),ro=(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))(ro||{}),io=(t=>(t.denominator="splits_denominator",t.numerator="splits_numerator",t))(io||{}),so=(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))(so||{}),ao=(t=>(t.left="left",t.none="none",t.right="right",t))(ao||{}),oo=(t=>(t.inherit="inherit",t.off="off",t.on="on",t))(oo||{}),nu={order:yn,currency:$a,dayofweek:Wa,display:Ua,shape:qa,location:za,size:Ka,format:Ha,barmerge:Ga,xloc:Ya,yloc:Za,extend:Xa,text:Qa,font:Ja,adjustment:eo,backadjustment:to,earnings:no,dividends:ro,splits:io,position:so,scale:ao,settlement_as_close:oo};function ru(t){return(e,n=yn.ascending)=>{e.array.sort((r,i)=>{let s=isNaN(r)?1/0:r,a=isNaN(i)?1/0:i;return n===yn.ascending?s-a:a-s})}}function iu(t){return(e,n=yn.ascending)=>{let r=e.array.map((i,s)=>s);return r.sort((i,s)=>{let a=isNaN(e.array[i])?1/0:e.array[i],o=isNaN(e.array[s])?1/0:e.array[s];return n===yn.ascending?a-o:o-a}),new q(r,z.int,t)}}function su(t){return e=>{let n=t.array.avg(e),r=t.array.stdev(e);return isNaN(r)?new q(e.array.map(()=>NaN),z.int,t):r===0?new q(e.array.map(()=>1),z.int,t):new q(e.array.map(i=>(i-n)/r),z.int,t)}}function au(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?0:t.precision(Math.sqrt(c)))}}function ou(t){return e=>t.precision(e.array.reduce((n,r)=>{let i=Number(r);return isNaN(i)?n:n+i},0))}function lu(t){return(e,n)=>{if(!qn(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 cu(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 uu=Object.defineProperty,pu=(t,e,n)=>e in t?uu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Y=(t,e,n)=>pu(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,Y(this,"_abs"),Y(this,"_avg"),Y(this,"_binary_search"),Y(this,"_binary_search_leftmost"),Y(this,"_binary_search_rightmost"),Y(this,"_clear"),Y(this,"_concat"),Y(this,"_copy"),Y(this,"_covariance"),Y(this,"_every"),Y(this,"_fill"),Y(this,"_first"),Y(this,"_get"),Y(this,"_includes"),Y(this,"_indexof"),Y(this,"_insert"),Y(this,"_join"),Y(this,"_last"),Y(this,"_lastindexof"),Y(this,"_max"),Y(this,"_median"),Y(this,"_min"),Y(this,"_mode"),Y(this,"_percentile_linear_interpolation"),Y(this,"_percentile_nearest_rank"),Y(this,"_percentrank"),Y(this,"_pop"),Y(this,"_push"),Y(this,"_range"),Y(this,"_remove"),Y(this,"_reverse"),Y(this,"_set"),Y(this,"_shift"),Y(this,"_size"),Y(this,"_slice"),Y(this,"_some"),Y(this,"_sort"),Y(this,"_sort_indices"),Y(this,"_standardize"),Y(this,"_stdev"),Y(this,"_sum"),Y(this,"_unshift"),Y(this,"_variance"),this._abs=_c(this.context),this._avg=xc(this.context),this._binary_search=bc(this.context),this._binary_search_leftmost=wc(this.context),this._binary_search_rightmost=vc(this.context),this._clear=Ec(this.context),this._concat=Sc(this.context),this._copy=Cc(this.context),this._covariance=Nc(this.context),this._every=kc(this.context),this._fill=Ac(this.context),this._first=Tc(this.context),this._get=Dc(this.context),this._includes=Mc(this.context),this._indexof=Pc(this.context),this._insert=Rc(this.context),this._join=Fc(this.context),this._last=Bc(this.context),this._lastindexof=Lc(this.context),this._max=Oc(this.context),this._median=Vc(this.context),this._min=jc(this.context),this._mode=$c(this.context),this._percentile_linear_interpolation=Wc(this.context),this._percentile_nearest_rank=Uc(this.context),this._percentrank=qc(this.context),this._pop=zc(this.context),this._push=Kc(this.context),this._range=Hc(this.context),this._remove=Gc(this.context),this._reverse=Yc(this.context),this._set=Zc(this.context),this._shift=Xc(this.context),this._size=Qc(this.context),this._slice=Jc(this.context),this._some=eu(this.context),this._sort=ru(this.context),this._sort_indices=iu(this.context),this._standardize=su(this.context),this._stdev=au(this.context),this._sum=ou(this.context),this._unshift=lu(this.context),this._variance=cu(this.context)}toString(){return"["+this.array.toString().replace(/,/g,", ")+"]"}[Symbol.iterator](){return this.array[Symbol.iterator]()}abs(...e){return this._abs(this,...e)}avg(...e){return this._avg(this,...e)}binary_search(...e){return this._binary_search(this,...e)}binary_search_leftmost(...e){return this._binary_search_leftmost(this,...e)}binary_search_rightmost(...e){return this._binary_search_rightmost(this,...e)}clear(...e){return this._clear(this,...e)}concat(...e){return this._concat(this,...e)}copy(...e){return this._copy(this,...e)}covariance(...e){return this._covariance(this,...e)}every(...e){return this._every(this,...e)}fill(...e){return this._fill(this,...e)}first(...e){return this._first(this,...e)}get(...e){return this._get(this,...e)}includes(...e){return this._includes(this,...e)}indexof(...e){return this._indexof(this,...e)}insert(...e){return this._insert(this,...e)}join(...e){return this._join(this,...e)}last(...e){return this._last(this,...e)}lastindexof(...e){return this._lastindexof(this,...e)}max(...e){return this._max(this,...e)}median(...e){return this._median(this,...e)}min(...e){return this._min(this,...e)}mode(...e){return this._mode(this,...e)}percentile_linear_interpolation(...e){return this._percentile_linear_interpolation(this,...e)}percentile_nearest_rank(...e){return this._percentile_nearest_rank(this,...e)}percentrank(...e){return this._percentrank(this,...e)}pop(...e){return this._pop(this,...e)}push(...e){return this._push(this,...e)}range(...e){return this._range(this,...e)}remove(...e){return this._remove(this,...e)}reverse(...e){return this._reverse(this,...e)}set(...e){return this._set(this,...e)}shift(...e){return this._shift(this,...e)}size(...e){return this._size(this,...e)}slice(...e){return this._slice(this,...e)}some(...e){return this._some(this,...e)}sort(...e){return this._sort(this,...e)}sort_indices(...e){return this._sort_indices(this,...e)}standardize(...e){return this._standardize(this,...e)}stdev(...e){return this._stdev(this,...e)}sum(...e){return this._sum(this,...e)}unshift(...e){return this._unshift(this,...e)}variance(...e){return this._variance(this,...e)}};function hu(t){return(...e)=>new q([...e],Ic(e),t)}function du(t){return(e,n)=>{let r=typeof e=="number"&&e>0&&!isNaN(e)?Math.floor(e):0;if(n===void 0){let i=r?Array(r).fill(0):[];return new q(i,z.any,t)}return new q(Array(r).fill(t.precision(n||0)),it(n||0),t)}}function fu(t){return(e=0,n=!1)=>{let r=typeof e=="number"&&e>0&&!isNaN(e)?Math.floor(e):0;return new q(Array(r).fill(n),z.bool,t)}}function mu(t){return(e=0,n=null)=>{let r=typeof e=="number"&&e>0&&!isNaN(e)?Math.floor(e):0;return new q(Array(r).fill(n),z.box,t)}}function yu(t){return(e=0,n=null)=>{let r=typeof e=="number"&&e>0&&!isNaN(e)?Math.floor(e):0;return new q(Array(r).fill(n),z.color,t)}}function gu(t){return(e=0,n=NaN)=>{let r=typeof e=="number"&&e>0&&!isNaN(e)?Math.floor(e):0;return new q(Array(r).fill(t.precision(n)),z.float,t)}}function _u(t){return(e=0,n=0)=>{let r=typeof e=="number"&&e>0&&!isNaN(e)?Math.floor(e):0;return new q(Array(r).fill(t.precision(n)),z.int,t)}}function xu(t){return(e=0,n=null)=>{let r=typeof e=="number"&&e>0&&!isNaN(e)?Math.floor(e):0;return new q(Array(r).fill(n),z.label,t)}}function bu(t){return(e=0,n=null)=>{let r=typeof e=="number"&&e>0&&!isNaN(e)?Math.floor(e):0;return new q(Array(r).fill(n),z.line,t)}}function wu(t){return(e=0,n=null)=>{let r=typeof e=="number"&&e>0&&!isNaN(e)?Math.floor(e):0;return new q(Array(r).fill(n),z.linefill,t)}}function vu(t){return(e=0,n="")=>{let r=typeof e=="number"&&e>0&&!isNaN(e)?Math.floor(e):0;return new q(Array(r).fill(n),z.string,t)}}function Eu(t){return(e=0,n=null)=>{let r=typeof e=="number"&&e>0&&!isNaN(e)?Math.floor(e):0;return new q(Array(r).fill(n),z.table,t)}}var y=class t{constructor(e,n=0){this.data=e,this.offset=n}get(e){let n=this.offset+e;Number.isInteger(n)||(n=Math.trunc(n));let r=this.data.length-1-n;return r<0||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){return e instanceof t?e:Array.isArray(e)?new t(e):e!=null&&typeof e=="object"&&"__value"in e&&e.__value instanceof t?e.__value:new t([e])}};function Su(t){return(e,n=0)=>y.from(e).get(n)}var _i=class{constructor(e){this.context=e,this.abs=(n,...r)=>n.abs(...r),this.avg=(n,...r)=>n.avg(...r),this.binary_search=(n,...r)=>n.binary_search(...r),this.binary_search_leftmost=(n,...r)=>n.binary_search_leftmost(...r),this.binary_search_rightmost=(n,...r)=>n.binary_search_rightmost(...r),this.clear=(n,...r)=>n.clear(...r),this.concat=(n,...r)=>n.concat(...r),this.copy=(n,...r)=>n.copy(...r),this.covariance=(n,...r)=>n.covariance(...r),this.every=(n,...r)=>n.every(...r),this.fill=(n,...r)=>n.fill(...r),this.first=(n,...r)=>n.first(...r),this.from=hu(e),this.get=(n,...r)=>n.get(...r),this.includes=(n,...r)=>n.includes(...r),this.indexof=(n,...r)=>n.indexof(...r),this.insert=(n,...r)=>n.insert(...r),this.join=(n,...r)=>n.join(...r),this.last=(n,...r)=>n.last(...r),this.lastindexof=(n,...r)=>n.lastindexof(...r),this.max=(n,...r)=>n.max(...r),this.median=(n,...r)=>n.median(...r),this.min=(n,...r)=>n.min(...r),this.mode=(n,...r)=>n.mode(...r),this.new=du(e),this.new_bool=fu(e),this.new_box=mu(e),this.new_color=yu(e),this.new_float=gu(e),this.new_int=_u(e),this.new_label=xu(e),this.new_line=bu(e),this.new_linefill=wu(e),this.new_string=vu(e),this.new_table=Eu(e),this.param=Su(),this.percentile_linear_interpolation=(n,...r)=>n.percentile_linear_interpolation(...r),this.percentile_nearest_rank=(n,...r)=>n.percentile_nearest_rank(...r),this.percentrank=(n,...r)=>n.percentrank(...r),this.pop=(n,...r)=>n.pop(...r),this.push=(n,...r)=>n.push(...r),this.range=(n,...r)=>n.range(...r),this.remove=(n,...r)=>n.remove(...r),this.reverse=(n,...r)=>n.reverse(...r),this.set=(n,...r)=>n.set(...r),this.shift=(n,...r)=>n.shift(...r),this.size=(n,...r)=>n.size(...r),this.slice=(n,...r)=>n.slice(...r),this.some=(n,...r)=>n.some(...r),this.sort=(n,...r)=>n.sort(...r),this.sort_indices=(n,...r)=>n.sort_indices(...r),this.standardize=(n,...r)=>n.standardize(...r),this.stdev=(n,...r)=>n.stdev(...r),this.sum=(n,...r)=>n.sum(...r),this.unshift=(n,...r)=>n.unshift(...r),this.variance=(n,...r)=>n.variance(...r)}};function Cu(t){return e=>{e.map.clear()}}function Nu(t){return(e,n)=>e.map.has(n)}function ku(t){return e=>{let n=new hr(t);return n.map=new Map(e.map),n}}function Iu(t){return(e,n)=>{let r=e.map.get(n);return r===void 0?NaN:r}}function Au(t){return e=>{let n=Array.from(e.map.keys()),r=it(n[0]);return new q(n,r,t)}}function Tu(t){return(e,n,r)=>{let i=e.map.get(n);return e.map.set(n,r),i===void 0?NaN:i}}function Du(t){return(e,n)=>{for(let[r,i]of n.map)e.map.set(r,i)}}function Mu(t){return(e,n)=>{let r=e.map.get(n);return e.map.delete(n)?r:NaN}}function Pu(t){return e=>e.map.size}function Ru(t){return e=>{let n=Array.from(e.map.values()),r=it(n[0]);return new q(n,r,t)}}var Fu=Object.defineProperty,Bu=(t,e,n)=>e in t?Fu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ot=(t,e,n)=>Bu(t,typeof e!="symbol"?e+"":e,n),hr=class{constructor(e){this.context=e,ot(this,"map"),ot(this,"_clear"),ot(this,"_contains"),ot(this,"_copy"),ot(this,"_get"),ot(this,"_keys"),ot(this,"_put"),ot(this,"_put_all"),ot(this,"_remove"),ot(this,"_size"),ot(this,"_values"),this.map=new Map,this._clear=Cu(this.context),this._contains=Nu(this.context),this._copy=ku(this.context),this._get=Iu(this.context),this._keys=Au(this.context),this._put=Tu(this.context),this._put_all=Du(this.context),this._remove=Mu(this.context),this._size=Pu(this.context),this._values=Ru(this.context)}toString(){return`PineMapObject(${this.map.size})`}clear(...e){return this._clear(this,...e)}contains(...e){return this._contains(this,...e)}copy(...e){return this._copy(this,...e)}get(...e){return this._get(this,...e)}keys(...e){return this._keys(this,...e)}put(...e){return this._put(this,...e)}put_all(...e){return this._put_all(this,...e)}remove(...e){return this._remove(this,...e)}size(...e){return this._size(this,...e)}values(...e){return this._values(this,...e)}};function Lu(t){return()=>new hr(t)}function Ou(t){return(e,n=0)=>y.from(e).get(n)}var xi=class{constructor(e){this.context=e,this.clear=(n,...r)=>n.clear(...r),this.contains=(n,...r)=>n.contains(...r),this.copy=(n,...r)=>n.copy(...r),this.get=(n,...r)=>n.get(...r),this.keys=(n,...r)=>n.keys(...r),this.new=Lu(e),this.param=Ou(),this.put=(n,...r)=>n.put(...r),this.put_all=(n,...r)=>n.put_all(...r),this.remove=(n,...r)=>n.remove(...r),this.size=(n,...r)=>n.size(...r),this.values=(n,...r)=>n.values(...r)}};function Vu(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 y&&(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 y&&(c=c.get(0)),e.matrix[l].splice(o,0,c)}}}function ju(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 y){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 y&&(u=u.get(0)),l.push(u)}else l.push(NaN);e.matrix.splice(o,0,l)}}function $u(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 Wu(t){return(e,n)=>{let r=e.matrix.length,i=r>0?e.matrix[0].length:0;if(n<0||n>=i){t.warn(`Column index ${n} is out of bounds, matrix has ${i} columns.`,"matrix.col");let o=r>0?it(e.matrix[0][0]):"float";return new q([],o,t)}let s=[];for(let o=0;o<r;o++)s.push(e.matrix[o][n]);let a=it(s[0]);return new q(s,a,t)}}function Uu(t){return e=>e.matrix.length===0?0:e.matrix[0].length}function qu(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 zu(t){return e=>{let n=e.matrix.length,r=n>0?e.matrix[0].length:0,i=new ne(n,r,NaN,t);return i.matrix=e.matrix.map(s=>[...s]),i}}function Ku(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 Hu(t){return e=>{let n=e.matrix.length,r=n>0?e.matrix[0].length:0;return n!==r?NaN:Ku(e.matrix)}}function Gu(t){return(e,n)=>{let r=e.matrix.length;if(r===0)return new ne(0,0,NaN,t);let i=e.matrix[0].length,s=new ne(r,i,NaN,t);if(n instanceof ne)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 Yu(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 Zu(t){return e=>{let n=e.matrix.length,r=n>0?e.matrix[0].length:0;if(n!==r){let a=it(e.matrix[0][0]);return new q([],a,t)}let i=Yu(e.matrix),s=it(i[0]);return new q(i,s,t)}}function Xu(t){return e=>{let n=e.matrix.length,r=n>0?e.matrix[0].length:0;if(n!==r)return new ne(0,0,NaN,t);let i=new ne(n,r,0,t);for(let s=0;s<n;s++)i.matrix[s][s]=1;return i}}function Qu(t){return e=>{let n=e.matrix.length;return n===0?0:n*e.matrix[0].length}}function Ju(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 ep(t){return(e,n,r)=>{let i=e.matrix.length,s=i>0?e.matrix[0].length:0;if(n<0||n>=i)return t.warn(`Row index ${n} is out of bounds, matrix has ${i} rows.`,"matrix.get"),NaN;if(r<0||r>=s)return t.warn(`Column index ${r} is out of bounds, matrix has ${s} columns.`,"matrix.get"),NaN;let a=e.matrix[n][r];return a===void 0?NaN:a}}function ar(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 tp(t){return e=>{let n=e.matrix.length,r=n>0?e.matrix[0].length:0;if(n!==r)return new ne(n,r,NaN,t);let i=ar(e.matrix),s=new ne(n,r,NaN,t);return s.matrix=i,s}}function np(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 rp(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 ip(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 sp(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 ap(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 op(t){return e=>{let n=e.matrix.length;if(n===0)return!1;let r=e.matrix[0].length;return n===r}}function lp(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 cp(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 up(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 pp(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 hp(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 ne(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 dp(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 fp(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 mp(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 yp(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 gp(t){return(e,n)=>{let r=e.matrix.length,i=r>0?e.matrix[0].length:0;if(n instanceof ne){let s=n.matrix.length,a=s>0?n.matrix[0].length:0;if(i!==s)return new ne(0,0,NaN,t);let o=new ne(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 ne(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 _p(t){return e=>{let n=e.matrix.length;if(n===0)return new ne(0,0,NaN,t);let r=e.matrix[0].length;if(n===r){let u=ar(e.matrix),h=new ne(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 x=0;x<p;x++){m[x]=new Array(f).fill(0);for(let b=0;b<d;b++){let w=u[x][b];if(w!==0)for(let E=0;E<f;E++)m[x][E]+=w*h[b][E]}}return m},a=e.matrix,o=i(a),l;if(n>r){let u=s(o,a),h=ar(u);l=s(h,o)}else{let u=s(a,o),h=ar(u);l=s(o,h)}let c=new ne(r,n,NaN,t);return c.matrix=l,c}}function xp(t){return(e,n)=>{let r=e.matrix.length,i=r>0?e.matrix[0].length:0;if(r!==i)return new ne(0,0,NaN,t);let s=new ne(r,i,0,t);for(let l=0;l<r;l++)s.matrix[l][l]=1;let a=new ne(r,i,NaN,t);for(let l=0;l<r;l++)a.matrix[l]=[...e.matrix[l]];let o=Math.floor(n);if(o<0)return new ne(r,i,NaN,t);for(;o>0;){if(o%2===1){let c=new ne(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 ne(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 bp(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 wp(t){return(e,n)=>{let r=e.matrix.length;if(r===0){let a=it(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=it(i[0]);return new q(i,s,t)}}function vp(t){return(e,n)=>{let r=e.matrix.splice(n,1),i=it(r[0][0]);return new q(r[0]||[],i,t)}}function Ep(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 Sp(t){return e=>{e.matrix.reverse();for(let n of e.matrix)n.reverse()}}function Cp(t){return(e,n)=>{let r=e.matrix.length;if(n<0||n>=r){t.warn(`Row index ${n} is out of bounds, matrix has ${r} rows.`,"matrix.row");let s=r>0?it(e.matrix[0][0]):"float";return new q([],s,t)}let i=it(e.matrix[n][0]);return new q([...e.matrix[n]],i,t)}}function Np(t){return e=>e.matrix.length}function kp(t){return(e,n,r,i)=>{let s=e.matrix.length,a=s>0?e.matrix[0].length:0;if(n<0||n>=s){t.warn(`Row index ${n} is out of bounds, matrix has ${s} rows.`,"matrix.set");return}if(r<0||r>=a){t.warn(`Column index ${r} is out of bounds, matrix has ${a} columns.`,"matrix.set");return}e.matrix[n][r]=i}}function Ip(t){return(e,n=0,r="asc")=>{e.matrix.length!==0&&e.matrix.sort((i,s)=>{let a=i[n],o=s[n];return a<o?r==="asc"?-1:1:a>o?r==="asc"?1:-1:0})}}function Ap(t){return(e,n,r,i,s)=>{let a=r-n,o=s-i,l=new ne(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 Tp(t){return(e,n)=>{let r=e.matrix.length;if(r===0)return new ne(0,0,NaN,t);let i=e.matrix[0].length,s=new ne(r,i,NaN,t);if(n instanceof ne)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 Dp(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 Mp(t){return(e,n,r)=>{let i=e.matrix[n];e.matrix[n]=e.matrix[r],e.matrix[r]=i}}function Pp(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 Rp(t){return e=>{let n=e.matrix.length;if(n===0)return new ne(0,0,NaN,t);let r=e.matrix[0].length,i=new ne(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 Fp=Object.defineProperty,Bp=(t,e,n)=>e in t?Fp(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,U=(t,e,n)=>Bp(t,typeof e!="symbol"?e+"":e,n),ne=class{constructor(e=0,n=0,r=NaN,i){if(this.context=i,U(this,"matrix"),U(this,"_add_col"),U(this,"_add_row"),U(this,"_avg"),U(this,"_col"),U(this,"_columns"),U(this,"_concat"),U(this,"_copy"),U(this,"_det"),U(this,"_diff"),U(this,"_eigenvalues"),U(this,"_eigenvectors"),U(this,"_elements_count"),U(this,"_fill"),U(this,"_get"),U(this,"_inv"),U(this,"_is_antidiagonal"),U(this,"_is_antisymmetric"),U(this,"_is_binary"),U(this,"_is_diagonal"),U(this,"_is_identity"),U(this,"_is_square"),U(this,"_is_stochastic"),U(this,"_is_symmetric"),U(this,"_is_triangular"),U(this,"_is_zero"),U(this,"_kron"),U(this,"_max"),U(this,"_median"),U(this,"_min"),U(this,"_mode"),U(this,"_mult"),U(this,"_pinv"),U(this,"_pow"),U(this,"_rank"),U(this,"_remove_col"),U(this,"_remove_row"),U(this,"_reshape"),U(this,"_reverse"),U(this,"_row"),U(this,"_rows"),U(this,"_set"),U(this,"_sort"),U(this,"_submatrix"),U(this,"_sum"),U(this,"_swap_columns"),U(this,"_swap_rows"),U(this,"_trace"),U(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=Vu(this.context),this._add_row=ju(this.context),this._avg=$u(this.context),this._col=Wu(this.context),this._columns=Uu(this.context),this._concat=qu(this.context),this._copy=zu(this.context),this._det=Hu(this.context),this._diff=Gu(this.context),this._eigenvalues=Zu(this.context),this._eigenvectors=Xu(this.context),this._elements_count=Qu(this.context),this._fill=Ju(this.context),this._get=ep(this.context),this._inv=tp(this.context),this._is_antidiagonal=np(this.context),this._is_antisymmetric=rp(this.context),this._is_binary=ip(this.context),this._is_diagonal=sp(this.context),this._is_identity=ap(this.context),this._is_square=op(this.context),this._is_stochastic=lp(this.context),this._is_symmetric=cp(this.context),this._is_triangular=up(this.context),this._is_zero=pp(this.context),this._kron=hp(this.context),this._max=dp(this.context),this._median=fp(this.context),this._min=mp(this.context),this._mode=yp(this.context),this._mult=gp(this.context),this._pinv=_p(this.context),this._pow=xp(this.context),this._rank=bp(this.context),this._remove_col=wp(this.context),this._remove_row=vp(this.context),this._reshape=Ep(this.context),this._reverse=Sp(this.context),this._row=Cp(this.context),this._rows=Np(this.context),this._set=kp(this.context),this._sort=Ip(this.context),this._submatrix=Ap(this.context),this._sum=Tp(this.context),this._swap_columns=Dp(this.context),this._swap_rows=Mp(this.context),this._trace=Pp(this.context),this._transpose=Rp(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,...e)}add_row(...e){return this._add_row(this,...e)}avg(...e){return this._avg(this,...e)}col(...e){return this._col(this,...e)}columns(...e){return this._columns(this,...e)}concat(...e){return this._concat(this,...e)}copy(...e){return this._copy(this,...e)}det(...e){return this._det(this,...e)}diff(...e){return this._diff(this,...e)}eigenvalues(...e){return this._eigenvalues(this,...e)}eigenvectors(...e){return this._eigenvectors(this,...e)}elements_count(...e){return this._elements_count(this,...e)}fill(...e){return this._fill(this,...e)}get(...e){return this._get(this,...e)}inv(...e){return this._inv(this,...e)}is_antidiagonal(...e){return this._is_antidiagonal(this,...e)}is_antisymmetric(...e){return this._is_antisymmetric(this,...e)}is_binary(...e){return this._is_binary(this,...e)}is_diagonal(...e){return this._is_diagonal(this,...e)}is_identity(...e){return this._is_identity(this,...e)}is_square(...e){return this._is_square(this,...e)}is_stochastic(...e){return this._is_stochastic(this,...e)}is_symmetric(...e){return this._is_symmetric(this,...e)}is_triangular(...e){return this._is_triangular(this,...e)}is_zero(...e){return this._is_zero(this,...e)}kron(...e){return this._kron(this,...e)}max(...e){return this._max(this,...e)}median(...e){return this._median(this,...e)}min(...e){return this._min(this,...e)}mode(...e){return this._mode(this,...e)}mult(...e){return this._mult(this,...e)}pinv(...e){return this._pinv(this,...e)}pow(...e){return this._pow(this,...e)}rank(...e){return this._rank(this,...e)}remove_col(...e){return this._remove_col(this,...e)}remove_row(...e){return this._remove_row(this,...e)}reshape(...e){return this._reshape(this,...e)}reverse(...e){return this._reverse(this,...e)}row(...e){return this._row(this,...e)}rows(...e){return this._rows(this,...e)}set(...e){return this._set(this,...e)}sort(...e){return this._sort(this,...e)}submatrix(...e){return this._submatrix(this,...e)}sum(...e){return this._sum(this,...e)}swap_columns(...e){return this._swap_columns(this,...e)}swap_rows(...e){return this._swap_rows(this,...e)}trace(...e){return this._trace(this,...e)}transpose(...e){return this._transpose(this,...e)}};function lt(t){return(e,n,r)=>new ne(e,n,r,t)}function Lp(t){return(e,n=0)=>y.from(e).get(n)}var bi=class{constructor(e){this.context=e,this.add_col=(n,...r)=>n.add_col(...r),this.add_row=(n,...r)=>n.add_row(...r),this.avg=(n,...r)=>n.avg(...r),this.col=(n,...r)=>n.col(...r),this.columns=(n,...r)=>n.columns(...r),this.concat=(n,...r)=>n.concat(...r),this.copy=(n,...r)=>n.copy(...r),this.det=(n,...r)=>n.det(...r),this.diff=(n,...r)=>n.diff(...r),this.eigenvalues=(n,...r)=>n.eigenvalues(...r),this.eigenvectors=(n,...r)=>n.eigenvectors(...r),this.elements_count=(n,...r)=>n.elements_count(...r),this.fill=(n,...r)=>n.fill(...r),this.get=(n,...r)=>n.get(...r),this.inv=(n,...r)=>n.inv(...r),this.is_antidiagonal=(n,...r)=>n.is_antidiagonal(...r),this.is_antisymmetric=(n,...r)=>n.is_antisymmetric(...r),this.is_binary=(n,...r)=>n.is_binary(...r),this.is_diagonal=(n,...r)=>n.is_diagonal(...r),this.is_identity=(n,...r)=>n.is_identity(...r),this.is_square=(n,...r)=>n.is_square(...r),this.is_stochastic=(n,...r)=>n.is_stochastic(...r),this.is_symmetric=(n,...r)=>n.is_symmetric(...r),this.is_triangular=(n,...r)=>n.is_triangular(...r),this.is_zero=(n,...r)=>n.is_zero(...r),this.kron=(n,...r)=>n.kron(...r),this.max=(n,...r)=>n.max(...r),this.median=(n,...r)=>n.median(...r),this.min=(n,...r)=>n.min(...r),this.mode=(n,...r)=>n.mode(...r),this.mult=(n,...r)=>n.mult(...r),this.new=lt(e),this.param=Lp(),this.pinv=(n,...r)=>n.pinv(...r),this.pow=(n,...r)=>n.pow(...r),this.rank=(n,...r)=>n.rank(...r),this.remove_col=(n,...r)=>n.remove_col(...r),this.remove_row=(n,...r)=>n.remove_row(...r),this.reshape=(n,...r)=>n.reshape(...r),this.reverse=(n,...r)=>n.reverse(...r),this.row=(n,...r)=>n.row(...r),this.rows=(n,...r)=>n.rows(...r),this.set=(n,...r)=>n.set(...r),this.sort=(n,...r)=>n.sort(...r),this.submatrix=(n,...r)=>n.submatrix(...r),this.sum=(n,...r)=>n.sum(...r),this.swap_columns=(n,...r)=>n.swap_columns(...r),this.swap_rows=(n,...r)=>n.swap_rows(...r),this.trace=(n,...r)=>n.trace(...r),this.transpose=(n,...r)=>n.transpose(...r),this.new_float=lt(e),this.new_int=lt(e),this.new_string=lt(e),this.new_bool=lt(e),this.new_color=lt(e),this.new_line=lt(e),this.new_label=lt(e),this.new_box=lt(e),this.new_linefill=lt(e),this.new_table=lt(e)}},Op=Object.defineProperty,Vp=(t,e,n)=>e in t?Op(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,jp=(t,e,n)=>Vp(t,typeof e!="symbol"?e+"":e,n),wi=class{constructor(e){this.context=e,jp(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}},$p=Object.defineProperty,Wp=(t,e,n)=>e in t?$p(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,oi=(t,e,n)=>Wp(t,typeof e!="symbol"?e+"":e,n),Oe=class t{constructor(e,n,r){oi(this,"time"),oi(this,"index"),oi(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 Up(t){return typeof t=="object"&&t&&(t.title!==void 0||t._plotKey!==void 0)&&t.data!==void 0&&t.options!==void 0}var sa={series:t=>t instanceof y||typeof t=="number"||typeof t=="string"||typeof t=="boolean",string:t=>typeof t=="string",color:t=>typeof t=="string"||t===null||typeof t=="number"&&isNaN(t)||t instanceof y,number:t=>typeof t=="number",boolean:t=>typeof t=="boolean",array:t=>Array.isArray(t),object:t=>typeof t=="object",point:t=>t instanceof Oe,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 y)&&!(t instanceof Oe)&&!Up(t)};function ht(t){let e=t[t.length-1];if(e&&typeof e=="object"&&"__callsiteId"in e)return t.pop().__callsiteId}function ce(t,e,n,r){Array.isArray(e)&&typeof e[0]=="string"&&(e=[e]);let i={},s={},a=new Array(e.length).fill(!0);for(let o=0;o<t.length;o++){let l=t[o];if(sa.remaining_options(l)){s=l;break}let c=e.map((u,h)=>a[h]?u[o]:void 0);for(let u=0;u<c.length;u++){let h=c[u];if(h===void 0){a[u]=!1;continue}let p=n[h];if(typeof l=="number"&&isNaN(l)&&(p==="number"||p==="series"))i[h]=l;else{let d=sa[n[h]];typeof d=="function"&&d(l)?i[h]=l:a[u]=!1}}}return{...i,...s,...r}}var qp=/^(\\d{2})(\\d{2})-(\\d{2})(\\d{2})$/;function zp(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(qp);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 Kp(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 Hp=Object.defineProperty,Gp=(t,e,n)=>e in t?Hp(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Yp=(t,e,n)=>Gp(t,typeof e!="symbol"?e+"":e,n),dr=class extends Error{constructor(e,n){super(e),Yp(this,"method"),this.name="PineRuntimeError",this.method=n}},Zp=Object.defineProperty,Xp=(t,e,n)=>e in t?Zp(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,fr=(t,e,n)=>Xp(t,typeof e!="symbol"?e+"":e,n);function vi(t){if(!t)return"";let e=t.trim().toUpperCase();return e==="1D"||e==="D"?"D":e==="1W"||e==="W"?"W":e==="1M"||e==="M"?"M":e}function Ei(t,e){let n=Qp(e);if(e==="M"){let o=new Date(t);return Date.UTC(o.getUTCFullYear(),o.getUTCMonth(),1)}if(e==="W"){let o=new Date(t),l=o.getUTCDay(),c=l===0?6:l-1;return Date.UTC(o.getUTCFullYear(),o.getUTCMonth(),o.getUTCDate()-c)}if(e==="D"||n>=1440)return Math.floor(t/864e5)*864e5;let r=n*6e4,i=Math.floor(t/864e5)*864e5,s=t-i,a=Math.floor(s/r)*r;return i+a}function Qp(t){if(t==="D")return 1440;if(t==="W")return 10080;if(t==="M")return 43200;let e=parseInt(t,10);return isNaN(e)?1440:e}function jt(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 Jp(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 eh=[["timeframe"],["timeframe","bars_back"],["timeframe","session","bars_back"],["timeframe","session","bars_back","timeframe_bars_back"],["timeframe","session","timezone","bars_back","timeframe_bars_back"]],th={timeframe:"string",session:"string",timezone:"string",bars_back:"number",timeframe_bars_back:"number"},mr=class{constructor(e,n="openTime"){fr(this,"context"),fr(this,"dataField"),this.context=e,this.dataField=n}get __value(){return this.context.data[this.dataField]}param(e,n=0){return y.from(e).get(n)}any(...e){let n=e.map(p=>p instanceof y?p.get(0):p),r=ce(n,eh,th),i=r.bars_back??0,s=r.timeframe||"",a=this.context.data[this.dataField],o=y.from(a).get(i);if(isNaN(o)||o==null)return NaN;let l=this.context.timeframe||"",c=vi(s),u=vi(l),h;if(!c||c===u?h=o:h=Ei(o,c),r.session!==void 0&&r.session!==""){let p=r.timezone||this.context.pine?.syminfo?.timezone||"UTC";return this._isInSession(h,r.session,p)?h:NaN}return h}_isInSession(e,n,r){let i=zp(n);if(!i)throw new dr(`Invalid session specification: "${n}"`,"time");let s=jt(e,r),a=s.hour*60+s.minute;return Kp(i,a,s.dayOfWeek)}},nh=[[],["time"],["time","timezone"]],rh={time:"number",timezone:"string"},xt=class{constructor(e,n){fr(this,"context"),fr(this,"extractor"),this.context=e,this.extractor=n}get __value(){let e=y.from(this.context.data.openTime).get(0);if(isNaN(e))return NaN;let n=this.context.pine?.syminfo?.timezone||"UTC",r=jt(e,n);return this.extractor(r)}param(e,n=0){return y.from(e).get(n)}any(...e){let n=e.map(o=>o instanceof y?o.get(0):o);if(n.length===0)return this.__value;let r=ce(n,nh,rh),i=r.time;if(i===void 0||isNaN(i))return NaN;let s=r.timezone||this.context.pine?.syminfo?.timezone||"UTC",a=jt(i,s);return this.extractor(a)}},Ft={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=>Jp(t.year,t.month,t.day),year:t=>t.year},ih=Object.defineProperty,sh=(t,e,n)=>e in t?ih(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,aa=(t,e,n)=>sh(t,typeof e!="symbol"?e+"":e,n),Si=class{constructor(e){this.context=e,aa(this,"regular","regular"),aa(this,"extended","extended")}get _timezone(){return this.context.pine?.syminfo?.timezone||"UTC"}_dayKey(e){let n=jt(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}},ah=Object.defineProperty,oh=(t,e,n)=>e in t?ah(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,lh=(t,e,n)=>oh(t,typeof e!="symbol"?e+"":e,n),Lt=class t{constructor(e,n,r){this._definition=e,this.context=n,lh(this,"_udt");for(let i in e)this[i]=e[i];this._udt=r}get __def__(){return this._definition}copy(){return new t(this.__def__,this.context,this._udt)}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(",")+"}"}}};function k(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 lo=Object.defineProperty,ch=Object.getOwnPropertyDescriptor,uh=(t,e,n)=>e in t?lo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,co=(t,e,n,r)=>{for(var i=r>1?void 0:r?ch(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&&lo(e,n,i),i},fn=(t,e,n)=>uh(t,typeof e!="symbol"?e+"":e,n),ph=[["dateString"],["year","month","day","hour","minute","second"],["timezone","year","month","day","hour","minute","second"]],hh={dateString:"string",timezone:"string",year:"number",month:"number",day:"number",hour:"number",minute:"number",second:"number"},dh=["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"],fh={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 mh(t){return ce(t,dh,fh)}var Ze=class t{get __value(){return NaN}param(e,n=0){return y.from(e).get(n)}any(e){if(e instanceof t)return!0;let n=y.from(e).get(0);return n instanceof t||n==null?!0:typeof n=="number"?n!==n:!1}},an={freq_all:"alert.freq_all",freq_once_per_bar:"alert.freq_once_per_bar",freq_once_per_bar_close:"alert.freq_once_per_bar_close"},yr=class{constructor(e){this.context=e,fn(this,"_firedKeys",new Set),fn(this,"_fallbackCounter",0),fn(this,"_fallbackLastExecTick",-1)}get freq_all(){return an.freq_all}get freq_once_per_bar(){return an.freq_once_per_bar}get freq_once_per_bar_close(){return an.freq_once_per_bar_close}param(e,n,r){return y.from(e).get(0)}any(e,n,r){let i=y.from(e).get(0),s=n?y.from(n).get(0):an.freq_once_per_bar,a;if(r&&typeof r=="object"&&r.__callsiteId)a=r.__callsiteId;else{let u=this.context._execTick||0;u!==this._fallbackLastExecTick&&(this._fallbackCounter=0,this._fallbackLastExecTick=u),a=`alert_${this._fallbackCounter++}`}let o=this.context.idx,l=this.context.pine?.barstate?.isrealtime??o===this.context.length-1;if((this.context._alertMode||"realtime")==="realtime"&&!l)return;let c=`${a}:${o}`;if(s===an.freq_once_per_bar){if(this._firedKeys.has(c))return;this._firedKeys.add(c)}else if(s===an.freq_once_per_bar_close){if(!(this.context.pine?.barstate?.isconfirmed??!0)||this._firedKeys.has(c))return;this._firedKeys.add(c)}this.context.alerts.push({type:"alert",id:a,message:i,freq:s,bar_index:o,time:this.context.data.openTime?.data?.[o]??0})}};co([k],yr.prototype,"any",1);var gr=class{constructor(e){this.context=e,fn(this,"_acCounter",0),fn(this,"_acLastExecTick",-1),fn(this,"_acFiredKeys",new Set)}extractPlotOptions(e){let n={};for(let r in e)n[r]=y.from(e[r]).get(0);return n}indicator(...e){let n=e.map(s=>s instanceof y?s.get(0):s),r=mh(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}get bar_index(){return this.context.idx}na(e){let n=y.from(e).get(0);return n==null||typeof n=="number"&&isNaN(n)}nz(e,n=0){let r=y.from(e).get(0),i=y.from(n).get(0);return r==null||typeof r=="number"&&isNaN(r)?i:r}fixnan(e){let n=y.from(e);for(let r=0;r<n.length;r++){let i=n.get(r);if(!isNaN(i))return i}return NaN}alertcondition(e,n,r){let i=y.from(e).get(0),s=this.context.idx,a=this.context._execTick||0;a!==this._acLastExecTick&&(this._acCounter=0,this._acLastExecTick=a);let o=`alertcondition_${this._acCounter++}`;if(!i)return;let l=this.context.pine?.barstate?.isrealtime??s===this.context.length-1;if((this.context._alertMode||"realtime")==="realtime"&&!l)return;let c=`${o}:${s}`;if(this._acFiredKeys.has(c))return;this._acFiredKeys.add(c);let u=n?y.from(n).get(0):"",h=r?y.from(r).get(0):"";this.context.alerts.push({type:"alertcondition",id:o,title:u,message:h,bar_index:s,time:this.context.data.openTime?.data?.[s]??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 y?i.get(0):i),r=ce(n,ph,hh);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())){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=E=>parseInt(c.find(v=>v.type===E)?.value||"0",10),h=u("year"),p=u("month"),d=u("day"),f=u("hour");f===24&&(f=0);let m=u("minute"),x=u("second"),b=new Date(Date.UTC(h,p-1,d,f,m,x));h>=0&&h<100&&b.setUTCFullYear(h);let w=b.getTime()-l.getTime();return l.getTime()-w}bool(e){let n=y.from(e).get(0);return!isNaN(n)&&n!==0}int(e){let n=y.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=y.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){return y.from(e).get(0).toString()}Type(e){let n=Object.keys(e),r={};for(let s of n){let a=e[s];a instanceof y&&(a=a.data),Array.isArray(a)&&(a[0],r[s]=a[1])}let i={new:function(...s){let a={},o=null;if(s.length>0){let l=s[s.length-1];if(l&&typeof l=="object"&&!(l instanceof y)&&!Array.isArray(l)&&!(l instanceof Lt)){let c=Object.keys(l);c.length>0&&c.some(u=>n.includes(u))&&(o=l,s=s.slice(0,-1))}}for(let l=0;l<n.length;l++){let c=n[l];o&&c in o?a[c]=o[c]:l<s.length?a[c]=s[l]:c in r&&(a[c]=y.from(r[c]).get(0))}return new Lt(a,this.context,i)},copy:function(s){return new Lt(s.__def__,this.context,i)},_fieldDefaults:r,_definitionKeys:n};return i}};co([k],gr.prototype,"alertcondition",1);function Ht(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 yh(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 xe={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 uo(t){if(typeof t!="string")return null;let e=t.trim(),n=e.startsWith("color.")?e.slice(6):e;return Object.prototype.hasOwnProperty.call(xe,n)&&(e=xe[n]),Ht(e)}function Ci(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 gh(t){let e=uo(t);return e?Ci(e[0],e[1],e[2],e[3]):t}function gt(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 Ni=class{constructor(e){this.context=e}any(e){let n=y.from(e).get(0);return typeof n=="number"&&isNaN(n)?null:n}param(e,n=0){return y.from(e).get(n)}new(e,n){if(e=gt(e),!e||typeof e!="string")return e;if(typeof n=="number"&&isNaN(n)&&(n=void 0),e.startsWith("#")){let r=e.slice(1),i=r.length===8?r.slice(0,6):r;return n!=null?`#${i}${Math.round(255/100*(100-n)).toString(16).padStart(2,"0").toUpperCase()}`:`#${r}`}else{let r=xe[e];if(r)return n!=null?`#${r.slice(1)}${Math.round(255/100*(100-n)).toString(16).padStart(2,"0").toUpperCase()}`:r;let i=e.match(/rgba?\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)(?:\\s*,\\s*([\\d.]+))?\\s*\\)/);if(i){let s=i[1],a=i[2],o=i[3];if(n!=null){let l=parseInt(s).toString(16).padStart(2,"0"),c=parseInt(a).toString(16).padStart(2,"0"),u=parseInt(o).toString(16).padStart(2,"0"),h=Math.round(255/100*(100-n)).toString(16).padStart(2,"0").toUpperCase();return`#${l}${c}${u}${h}`}return e}return n!=null?`rgba(${e}, ${(100-n)/100})`:e}}rgb(e,n,r,i){return typeof i=="number"&&isNaN(i)&&(i=void 0),i!=null?`rgba(${e}, ${n}, ${r}, ${(100-i)/100})`:`rgb(${e}, ${n}, ${r})`}from_gradient(e,n,r,i,s){if(e=gt(e),n=gt(n),r=gt(r),i=gt(i),s=gt(s),e==null||typeof e=="number"&&isNaN(e)||n==null||typeof n=="number"&&isNaN(n)||r==null||typeof r=="number"&&isNaN(r)||i==null||typeof i=="number"&&isNaN(i)||s==null||typeof s=="number"&&isNaN(s))return;let a=0;r!==n&&(a=(e-n)/(r-n)),a=Math.max(0,Math.min(1,a));let o=Ht(typeof i=="string"?i:"#000000")||[0,0,0,1],l=Ht(typeof s=="string"?s:"#FFFFFF")||[255,255,255,1],c=o[0]+(l[0]-o[0])*a,u=o[1]+(l[1]-o[1])*a,h=o[2]+(l[2]-o[2])*a,p=o[3]+(l[3]-o[3])*a;return yh(c,u,h,p)}r(e){if(e=gt(e),!e||typeof e!="string")return NaN;let n=Ht(e);return n?n[0]:NaN}g(e){if(e=gt(e),!e||typeof e!="string")return NaN;let n=Ht(e);return n?n[1]:NaN}b(e){if(e=gt(e),!e||typeof e!="string")return NaN;let n=Ht(e);return n?n[2]:NaN}t(e){if(e=gt(e),!e||typeof e!="string")return NaN;let n=Ht(e);return n?Math.round(100-n[3]*100):NaN}aqua(){return xe.aqua}black(){return xe.black}blue(){return xe.blue}fuchsia(){return xe.fuchsia}gray(){return xe.gray}green(){return xe.green}lime(){return xe.lime}maroon(){return xe.maroon}navy(){return xe.navy}olive(){return xe.olive}orange(){return xe.orange}purple(){return xe.purple}red(){return xe.red}silver(){return xe.silver}teal(){return xe.teal}white(){return xe.white}yellow(){return xe.yellow}},_s=new Set(["open","high","low","close","hl2","hlc3","ohlc4","hlcc4","volume"]);function po(t,e){if(!_s.has(e))return;let n=t?.data?.[e];if(n!=null)return y.from(n).get(0)}var _h=[["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"]],xh={defval:"primitive",title:"string",tooltip:"string",inline:"string",group:"string",display:"string",confirm:"boolean",options:"array",minval:"number",maxval:"number",step:"number"};function Ke(t){let e,n=t[t.length-1];n&&typeof n=="object"&&Object.prototype.hasOwnProperty.call(n,"__varId")&&(e=n.__varId,t=t.slice(0,-1));let r=ce(t,_h,xh);return e!==void 0&&(r.__varId=e),r}function Xe(t,e){return 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 bh(t){return(...e)=>{let n=Ke(e),r=Xe(t,n);if(typeof r=="string"&&typeof n.defval=="number"){let i=po(t,r);if(i!==void 0)return i}return r}}function wh(t){return(...e)=>{let n=Ke(e);return Xe(t,n)}}function vh(t){return(...e)=>{let n=Ke(e);return Xe(t,n)}}function Eh(t){return(...e)=>{let n=Ke(e);return Xe(t,n)}}function Sh(t){return(...e)=>{let n=Ke(e);return Xe(t,n)}}function Ch(t){return(...e)=>{let n=Ke(e);return Xe(t,n)}}function Nh(t){return(e,n=0)=>y.from(e).get(n)}function kh(t){return(...e)=>{let n=Ke(e);return Xe(t,n)}}function Ih(t){return(...e)=>{let n=Ke(e);return Xe(t,n)}}function Ah(t){return(...e)=>{let n=Ke(e),r=Xe(t,n);if(typeof r=="string"){let i=po(t,r);return i!==void 0?i:n.defval}return r}}function Th(t){return(...e)=>{let n=Ke(e);return Xe(t,n)}}function Dh(t){return(...e)=>{let n=Ke(e);return Xe(t,n)}}function Mh(t){return(...e)=>{let n=Ke(e);return Xe(t,n)}}function Ph(t){return(...e)=>{let n=Ke(e);return Xe(t,n)}}function Rh(t){return(...e)=>Ke(e).defval}var Fh=Object.defineProperty,Bh=(t,e,n)=>e in t?Fh(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Be=(t,e,n)=>Bh(t,typeof e!="symbol"?e+"":e,n),Lh={any:bh,bool:wh,color:vh,enum:Eh,float:Sh,int:Ch,param:Nh,price:kh,session:Ih,source:Ah,string:Th,symbol:Dh,text_area:Mh,time:Ph,timeframe:Rh},ki=class{constructor(e){this.context=e,Be(this,"any"),Be(this,"bool"),Be(this,"color"),Be(this,"enum"),Be(this,"float"),Be(this,"int"),Be(this,"param"),Be(this,"price"),Be(this,"session"),Be(this,"source"),Be(this,"string"),Be(this,"symbol"),Be(this,"text_area"),Be(this,"time"),Be(this,"timeframe"),Object.entries(Lh).forEach(([n,r])=>{this[n]=r(e)})}};function Oh(t){return e=>Math.abs(y.from(e).get(0))}function Vh(t){return e=>Math.acos(y.from(e).get(0))}function jh(t){return e=>Math.asin(y.from(e).get(0))}function $h(t){return e=>Math.atan(y.from(e).get(0))}function Wh(t){return(...e)=>{let n=e.map(r=>y.from(r).get(0));return n.reduce((r,i)=>r+i,0)/n.length}}function Uh(t){return e=>Math.ceil(y.from(e).get(0))}function qh(t){return e=>Math.cos(y.from(e).get(0))}function zh(t){return()=>Math.E}function Kh(t){return e=>Math.exp(y.from(e).get(0))}function Hh(t){return e=>Math.floor(y.from(e).get(0))}function Gh(t){return e=>Math.log(y.from(e).get(0))}function Yh(t){return e=>Math.log(y.from(e).get(0))}function Zh(t){return e=>Math.log10(y.from(e).get(0))}function Xh(t){return(...e)=>{let n=e.map(r=>y.from(r).get(0));return Math.max(...n)}}function Qh(t){return(...e)=>{let n=e.map(r=>y.from(r).get(0));return Math.min(...n)}}function Jh(t){return(e,n,r)=>typeof e=="string"?e:e instanceof y?n?new y(e.data,e.offset+n):e:!Array.isArray(e)&&typeof e=="object"?e:(t.params[r]||(t.params[r]=[]),Array.isArray(e)?new y(e,n||0):(t.params[r].length===0?t.params[r].push(e):t.params[r][t.params[r].length-1]=e,new y(t.params[r],n||0)))}function ed(t){return()=>1.618033988749895}function td(t){return()=>Math.PI}function nd(t){return(e,n)=>Math.pow(y.from(e).get(0),y.from(n).get(0))}function rd(t){return()=>Math.random()}function li(t){return t!==t?NaN:Math.sign(t)*Math.round(Math.abs(t))}function id(t){return(e,n)=>{let r=y.from(e).get(0);if(n==null)return li(r);let i=y.from(n).get(0);if(i===0)return li(r);let s=Math.pow(10,i);return li(r*s)/s}}function sd(t){return e=>t.precision(Math.round(y.from(e).get(0)/t.pine.syminfo.mintick)*t.pine.syminfo.mintick)}function ad(t){return()=>.6180339887498948}function od(t){return e=>Math.sign(y.from(e).get(0))}function ld(t){return e=>Math.sin(y.from(e).get(0))}function cd(t){return e=>Math.sqrt(y.from(e).get(0))}function ud(t){return(e,n)=>{let r=y.from(n).get(0),i=y.from(e),s=0;for(let a=0;a<r;a++){let o=i.get(a);s+=o}return s}}function pd(t){return e=>Math.tan(y.from(e).get(0))}function hd(t){return e=>{let n=y.from(e).get(0);return n==null||Number.isNaN(n)?NaN:n*(180/Math.PI)}}function dd(t){return e=>{let n=y.from(e).get(0);return n==null||Number.isNaN(n)?NaN:n*(Math.PI/180)}}function fd(t){return(e,n)=>{let r=y.from(e).get(0),i=y.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 md(t){return(e,n)=>{let r=y.from(e).get(0),i=y.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 yd(t){return(e,n)=>{let r=y.from(e).get(0),i=y.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 gd(t){return(e,n)=>{let r=y.from(e).get(0),i=y.from(n).get(0);return typeof r!="number"||typeof i!="number"?r/i:isNaN(r)||isNaN(i)?NaN:Math.trunc(r/i)}}function _d(t){return(e,n)=>{let r=y.from(e).get(0),i=y.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 xd(t){return(e,n)=>{let r=y.from(e).get(0),i=y.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 bd(t){return(e,n)=>{let r=y.from(e).get(0),i=y.from(n).get(0);return typeof r=="number"&&typeof i=="number"?isNaN(r)||isNaN(i)?NaN:Math.abs(r-i)>=1e-10:r!==i}}var wd=Object.defineProperty,vd=(t,e,n)=>e in t?wd(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Z=(t,e,n)=>vd(t,typeof e!="symbol"?e+"":e,n),Ed={abs:Oh,acos:Vh,asin:jh,atan:$h,avg:Wh,ceil:Uh,cos:qh,e:zh,exp:Kh,floor:Hh,ln:Gh,log:Yh,log10:Zh,max:Xh,min:Qh,param:Jh,phi:ed,pi:td,pow:nd,random:rd,round:id,round_to_mintick:sd,rphi:ad,sign:od,sin:ld,sqrt:cd,sum:ud,tan:pd,todegrees:hd,toradians:dd,__eq:fd,__ge:md,__gt:yd,__idiv:gd,__le:_d,__lt:xd,__neq:bd},Ii=class{constructor(e){this.context=e,Z(this,"_cache",{}),Z(this,"abs"),Z(this,"acos"),Z(this,"asin"),Z(this,"atan"),Z(this,"avg"),Z(this,"ceil"),Z(this,"cos"),Z(this,"e"),Z(this,"exp"),Z(this,"floor"),Z(this,"ln"),Z(this,"log"),Z(this,"log10"),Z(this,"max"),Z(this,"min"),Z(this,"param"),Z(this,"phi"),Z(this,"pi"),Z(this,"pow"),Z(this,"random"),Z(this,"round"),Z(this,"round_to_mintick"),Z(this,"rphi"),Z(this,"sign"),Z(this,"sin"),Z(this,"sqrt"),Z(this,"sum"),Z(this,"tan"),Z(this,"todegrees"),Z(this,"toradians"),Z(this,"__eq"),Z(this,"__ge"),Z(this,"__gt"),Z(this,"__idiv"),Z(this,"__le"),Z(this,"__lt"),Z(this,"__neq"),Object.entries(Ed).forEach(([n,r])=>{this[n]=r(e)})}};function Sd(t){return(e,n,r)=>{t.params[r]||(t.params[r]=[]);let i;if(e instanceof y)i=e.get(n||0);else if(Array.isArray(e)){let s=e.some(o=>o instanceof y),a=e.every(o=>!(o instanceof y)&&!Array.isArray(o));(s||a)&&e.length>=1?i=e.map(o=>o instanceof y?o.get(0):o):i=y.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]}}var Cd=new Set(["heikinashi","standard"]);function jn(t){if(typeof t!="string")return{symbol:t,modifier:null};let e=t.lastIndexOf(";");if(e<=0||e===t.length-1)return{symbol:t,modifier:null};let n=t.slice(e+1).toLowerCase();return Cd.has(n)?{symbol:t.slice(0,e),modifier:n}:{symbol:t,modifier:null}}function Ot(t){return jn(t).symbol}function Ai(t,e){return`${Ot(t)};${e}`}var gn=["1","3","5","15","30","45","60","120","180","240","D","W","M"],Zn={"1m":"1","3m":"3","5m":"5","15m":"15","30m":"30","45m":"45","1h":"60","2h":"120","3h":"180","4h":"240","1d":"D","1w":"W","1M":"M"};function _r(t){if(gn.includes(t))return t;if(Zn[t])return Zn[t];let e=t.toLowerCase();if(Zn[e])return Zn[e];let n=t.toUpperCase();return gn.includes(n)?n:t}function oa(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 la(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){let l=s&&e>s;if(a&&i)for(let c=0;c<n.length;c++){if(n[c]>=t&&n[c]<e)return c;if(n[c]>=e)break}if(l&&i&&!a)for(let c=0;c<n.length;c++){if(n[c]>=t&&n[c]<e)return c;if(n[c]>=e)break}return o}if(r[o]<t)break}return-1}var ca=[["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"]],Nd={symbol:"series",timeframe:"series",expression:"any",gaps:"series",lookahead:"series",ignore_invalid_symbol:"series",currency:"series",calc_bars_count:"series"};function xs(t){return Array.isArray(t)&&t.length===2&&typeof t[1]=="string"}function kd(t,e){return t.map(n=>xs(n)?(e.push(n[1]),n[0]):(e.push(void 0),n))}function on(t){return xs(t)?t[0]:t}function Id(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(xs(r))return r[1]}function Ti(t){return t==null||typeof t!="object"?t:"__value"in t?t.__value:t instanceof y?t.get(0):Array.isArray(t)?t.map(Ti):t}function Ad(t){return async(...e)=>{let n=[],r=kd(e,n),i=ce(r,ca,Nd),s=on(i.symbol),a=on(i.timeframe),o=on(i.expression),l=on(i.gaps),c=on(i.lookahead),u=s instanceof y?s.get(0):s,h=typeof t.tickerId=="string"&&t.tickerId.includes(":")?t.tickerId.split(":")[1]:t.tickerId,p=typeof h=="string"?jn(h):{symbol:h,modifier:null},d=p.modifier==="standard"?null:p.modifier,f=u===""?t.tickerId:u,m=typeof f=="string"&&f.includes(":")?f.split(":")[1]:f,x=a instanceof y?a.get(0):a,b=x===""?t.timeframe:typeof x=="string"?x:String(x??""),w=o,E=Id("expression",ca,n,i.expression),v=l,I=c,C=v===!0||v==="gaps_on",T=I===!0||I==="lookahead_on",O=(()=>{let Ae=on(i.calc_bars_count);return typeof Ae=="number"&&Ae>0?Ae:void 0})();if(t.isSecondaryContext){let Ae=Ti(w);return Array.isArray(Ae)?[Ae]:Ae}let N=gn.indexOf(_r(t.timeframe)),j=gn.indexOf(_r(b));if(N==-1||j==-1)throw new Error("Invalid timeframe");let D=typeof m=="string"?jn(m):{symbol:m,modifier:null},W=D.modifier==="standard"?null:D.modifier,R=!m||m===""||D.symbol===p.symbol&&W===d;if(N===j&&R){let Ae=Ti(w);return Array.isArray(Ae)?[Ae]:Ae}let P=N>j,H=y.from(t.data.openTime).get(0),te=y.from(t.data.closeTime).get(0),ve=t.idx===t.length-1&&te>Date.now(),ae=`${m}_${b}_${E}`,Fe=`${ae}_prevIdx`;if(t.cache[ae]){let Ae=t.cache[ae];t.dataVersion>Ae.dataVersion&&(await Ae.pineTS.updateTail(Ae.context),Ae.dataVersion=t.dataVersion);let Cn=Ae.context,Yn=P?la(H,te,Cn.data.openTime.data,Cn.data.closeTime.data,T,t.eDate,C):oa(H,te,Cn.data.openTime.data,Cn.data.closeTime.data,T,ve);if(Yn==-1)return NaN;let sn=Cn.params[E][Yn];if(!P&&C){let ra=t.cache[Fe];return ra!==void 0&&ra===Yn?NaN:(t.cache[Fe]=Yn,Array.isArray(sn)?[sn]:sn)}return Array.isArray(sn)?[sn]:sn}let Sn=1e3*60*60*24*30,ea=t.sDate||(t.marketData?.length>0?t.marketData[0].openTime:void 0),dc=O?void 0:ea?ea-Sn:void 0,fc=(t.marketData?.length>0?t.marketData[t.marketData.length-1].closeTime:0)||t.eDate||Date.now(),Gn=new Ut(t.source,m,b,O,dc,fc);Gn.markAsSecondary();let ta=typeof E=="string"?E:"",mc=ta.match(/p\\d+$/)?.[0]??ta,na=t._ltfTruncatedBodies?.[mc],rn=na?await Gn.runPretranspiled(na):await Gn.run(t.pineTSCode);t.cache[ae]={pineTS:Gn,context:rn,dataVersion:t.dataVersion};let si=P?la(H,te,rn.data.openTime.data,rn.data.closeTime.data,T,t.eDate,C):oa(H,te,rn.data.openTime.data,rn.data.closeTime.data,T,ve);if(si==-1)return NaN;let ai=rn.params[E][si];return!P&&C?(t.cache[Fe]=si,NaN):Array.isArray(ai)?[ai]:ai}}var ua=[["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"]],Td={symbol:"series",timeframe:"series",expression:"any",ignore_invalid_symbol:"series",currency:"series",ignore_invalid_timeframe:"series",calc_bars_count:"series"};function bs(t){return Array.isArray(t)&&t.length===2&&typeof t[1]=="string"}function Dd(t,e){return t.map(n=>bs(n)?(e.push(n[1]),n[0]):(e.push(void 0),n))}function ln(t){return bs(t)?t[0]:t}function Md(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(bs(r))return r[1]}function cn(t){return typeof t=="number"?z.float:typeof t=="boolean"?z.bool:typeof t=="string"?z.string:z.any}var ho={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 Di(t,e){if(!(t instanceof y))return null;let n=e?.data;if(!n)return null;for(let r of Object.keys(ho))if(t===n[r])return r;return null}function Pd(t,e){if(t instanceof y&&(t=t.get(0)),!(t instanceof Lt))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=Di(a,e);if(o===null)return null;i.push(o)}return{kind:"udt",builtinNames:i,fieldNames:r,udt:n}}function Rd(t,e){if(t===void 0)return null;if(Array.isArray(t)){let r=[];for(let i of t){let s=Di(i,e);if(s===null)return null;r.push(s)}return r.length>0?{kind:"tuple",builtinNames:r}:null}let n=Di(t,e);return n!==null?{kind:"series",builtinNames:[n]}:Pd(t,e)}async function pa(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 Ut(t.source,e,n,r,a,o);l.markAsSecondary(),await l.ready();let c=l.openTime,u=l.closeTime,h=l.data,p=i.builtinNames.map(f=>ho[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(x=>{let b={};for(let w=0;w<f.length;w++)b[f[w]]=p[w](x);return new Lt(b,t,m)})}return{data:{openTime:{data:c},closeTime:{data:u}},params:{[s]:d}}}function Fd(t){return async(...e)=>{let n=[],r=Dd(e,n),i=ce(r,ua,Td),s=ln(i.symbol),a=ln(i.timeframe),o=ln(i.expression),l=s instanceof y?s.get(0):s,c=l===""?t.tickerId:l,u=typeof c=="string"&&c.includes(":")?c.split(":")[1]:c,h=a instanceof y?a.get(0):a,p=h===""?t.timeframe:typeof h=="string"?h:String(h??""),d=o,f=Md("expression",ua,n,i.expression);ln(i.ignore_invalid_symbol);let m=ln(i.ignore_invalid_timeframe),x=(()=>{let P=ln(i.calc_bars_count);return typeof P=="number"&&P>0?P:void 0})();if(t.isSecondaryContext)return Array.isArray(d)?[d.map(P=>new q([P],cn(P),t))]:new q([d],cn(d),t);let b=gn.indexOf(_r(t.timeframe)),w=gn.indexOf(_r(p));if(b===-1||w===-1){if(m)return NaN;throw new Error("Invalid timeframe")}if(w>b){if(m)return NaN;throw new Error(`Timeframe ${p} is not lower than or equal to chart timeframe ${t.timeframe}`)}if(w===b)return Array.isArray(d)?[d.map(P=>new q([P],cn(P),t))]:new q([d],cn(d),t);let E=`${u}_${p}_${f}_lower`,v=t._requestParamSources?.[f],I=Rd(v,t);if(!t.cache[E])if(I!==null){let P=await pa(t,u,p,x,I,f);t.cache[E]={pineTS:null,context:P,dataVersion:t.dataVersion,_fastPath:!0,_fastPathArgs:{builtinExpr:I}}}else{let P=t.sDate||(t.marketData?.length>0?t.marketData[0].openTime:void 0),H=(t.marketData?.length>0?t.marketData[t.marketData.length-1].closeTime:0)||t.eDate||Date.now(),te=new Ut(t.source,u,p,x,P,H);te.markAsSecondary();let ve=typeof f=="string"?f:"",ae=ve.match(/p\\d+$/)?.[0]??ve,Fe=t._ltfTruncatedBodies?.[ae],Sn;Fe?Sn=await te.runPretranspiled(Fe):Sn=await te.run(t.pineTSCode),t.cache[E]={pineTS:te,context:Sn,dataVersion:t.dataVersion}}let C=t.cache[E];if(t.dataVersion>C.dataVersion)if(C._fastPath){let P=await pa(t,u,p,x,C._fastPathArgs.builtinExpr,f);C.context=P,C.dataVersion=t.dataVersion}else await C.pineTS.updateTail(C.context),C.dataVersion=t.dataVersion;let T=C.context,O=y.from(t.data.openTime).get(0),N=y.from(t.data.closeTime).get(0),j=T.data.openTime.data,D=T.data.closeTime.data,W=T.params[f];if(!W)return Array.isArray(d)?[d.map(()=>new q([],z.float,t))]:new q([],z.float,t);let R=[];for(let P=0;P<j.length;P++){let H=j[P];if(!(D[P]<=O)){if(H>=N)break;H>=O&&H<N&&R.push(W[P])}}if(R.length>0&&Array.isArray(R[0])){let P=R[0].length,H=[];for(let te=0;te<P;te++){let ve=R.map(Fe=>Fe[te]),ae=ve.length>0?cn(ve[0]):z.float;H.push(new q(ve,ae,t))}return[H]}else{let P=R.length>0?cn(R[0]):z.float;return new q(R,P,t)}}}var Bd=Object.defineProperty,Ld=(t,e,n)=>e in t?Bd(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Xn=(t,e,n)=>Ld(t,typeof e!="symbol"?e+"":e,n),Od={param:Sd,security:Ad,security_lower_tf:Fd},Mi=class{constructor(e){this.context=e,Xn(this,"_cache",{}),Xn(this,"param"),Xn(this,"security"),Xn(this,"security_lower_tf"),Object.entries(Od).forEach(([n,r])=>{this[n]=r(e)})}};function Vd(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 jd(t){return(e,n,r,i,s)=>{let a=y.from(n).get(0),o=y.from(r).get(0),l=y.from(i).get(0);t.taState||(t.taState={});let c=s||`alma_${a}_${o}_${l}`;if(!t.taState[c]){let m=o*(a-1),x=a/l,b=[],w=0;for(let E=0;E<a;E++){let v=Math.exp(-Math.pow(E-m,2)/(2*x*x));b.push(v),w+=v}for(let E=0;E<b.length;E++)b[E]/=w;t.taState[c]={lastIdx:-1,prevWindow:[],prevCallCount:0,currentWindow:[],currentCallCount:0,weights:b}}let u=t.taState[c];t.idx>u.lastIdx&&(u.lastIdx>=0&&(u.prevWindow=[...u.currentWindow],u.prevCallCount=u.currentCallCount),u.lastIdx=t.idx);let h=y.from(e).get(0),p=[...u.prevWindow];for(p.unshift(h);p.length>a;)p.pop();let d=u.prevCallCount+1;if(p.length<a&&(d>=a||t.idx>=a-1)){let m=y.from(e);for(;p.length<a;)p.push(m.get(p.length))}if(u.currentWindow=p,u.currentCallCount=d,p.length<a)return NaN;let f=0;for(let m=0;m<a;m++)f+=u.weights[m]*p[a-1-m];return t.precision(f)}}function $d(t){return(e,n)=>{let r=y.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,x=Math.abs(a-c),b=Math.abs(o-c);u=Math.max(m,x,b)}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 Wd(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=y.from(e).get(0),a=i.prevLastTrueIndex;return s&&(a=t.idx),i.currentLastTrueIndex=a,a===null?NaN:t.idx-a}}function Ud(t){return(e,n,r,i)=>{let s=y.from(n).get(0),a=y.from(r).get(0);t.taState||(t.taState={});let o=i||`bb_${s}_${a}`;t.taState[o]||(t.taState[o]={lastIdx:-1,prevWindow:[],prevSum:0,currentWindow:[],currentSum:0});let l=t.taState[o];t.idx>l.lastIdx&&(l.lastIdx>=0&&(l.prevWindow=[...l.currentWindow],l.prevSum=l.currentSum),l.lastIdx=t.idx);let c=y.from(e).get(0);if(isNaN(c))return l.currentWindow=[...l.prevWindow],l.currentSum=l.prevSum,[[NaN,NaN,NaN]];let u=[...l.prevWindow],h=l.prevSum;for(u.unshift(c),h+=c;u.length>s;){let b=u.pop();h-=b}if(u.length<s&&t.idx>=s-1){let b=y.from(e);for(;u.length<s;){let w=b.get(u.length);if(isNaN(w))break;u.push(w),h+=w}}if(l.currentWindow=u,l.currentSum=h,u.length<s)return[[NaN,NaN,NaN]];let p=h/s,d=0;for(let b=0;b<s;b++)d+=Math.pow(u[b]-p,2);let f=Math.sqrt(d/s),m=p+a*f,x=p-a*f;return[[t.precision(p),t.precision(m),t.precision(x)]]}}function qd(t){return(e,n,r,i)=>{let s=y.from(n).get(0),a=y.from(r).get(0);t.taState||(t.taState={});let o=i||`bbw_${s}_${a}`;t.taState[o]||(t.taState[o]={lastIdx:-1,prevWindow:[],prevSum:0,currentWindow:[],currentSum:0});let l=t.taState[o];t.idx>l.lastIdx&&(l.lastIdx>=0&&(l.prevWindow=[...l.currentWindow],l.prevSum=l.currentSum),l.lastIdx=t.idx);let c=y.from(e).get(0);if(isNaN(c))return l.currentWindow=[...l.prevWindow],l.currentSum=l.prevSum,NaN;let u=[...l.prevWindow],h=l.prevSum;for(u.unshift(c),h+=c;u.length>s;){let w=u.pop();h-=w}if(u.length<s&&t.idx>=s-1){let w=y.from(e);for(;u.length<s;){let E=w.get(u.length);if(isNaN(E))break;u.push(E),h+=E}}if(l.currentWindow=u,l.currentSum=h,u.length<s)return NaN;let p=h/s,d=0;for(let w=0;w<s;w++){let E=u[w]-p;d+=E*E}let f=d/s,m=Math.sqrt(f),x=a*m;if(p===0)return t.precision(0);let b=2*x/p*100;return t.precision(b)}}function zd(t){return(e,n,r)=>{let i=y.from(n).get(0);t.taState||(t.taState={});let s=r||`cci_${i}`;t.taState[s]||(t.taState[s]={lastIdx:-1,prevWindow:[],prevSum:0,prevCallCount:0,currentWindow:[],currentSum:0,currentCallCount:0});let a=t.taState[s];t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevWindow=[...a.currentWindow],a.prevSum=a.currentSum,a.prevCallCount=a.currentCallCount),a.lastIdx=t.idx);let o=y.from(e).get(0);if(isNaN(o))return NaN;let l=[...a.prevWindow],c=a.prevSum;for(l.unshift(o),c+=o;l.length>i;){let m=l.pop();c-=m}let u=a.prevCallCount+1;if(l.length<i&&(u>=i||t.idx>=i-1)){let m=y.from(e);for(;l.length<i;){let x=m.get(l.length);if(isNaN(x))break;l.push(x),c+=x}}if(a.currentWindow=l,a.currentSum=c,a.currentCallCount=u,l.length<i)return NaN;let h=c/i,p=0;for(let m=0;m<i;m++)p+=Math.abs(l[m]-h);let d=p/i;if(d===0)return 0;let f=(o-h)/(.015*d);return t.precision(f)}}function Kd(t){return(e,n=1,r)=>{typeof n=="string"&&(r=n,n=1);let i=y.from(n).get(0);t.taState||(t.taState={});let s=r||`change_${i}`;t.taState[s]||(t.taState[s]={lastIdx:-1,prevWindow:[],prevCallCount:0,currentWindow:[],currentCallCount:0});let a=t.taState[s];t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevWindow=[...a.currentWindow],a.prevCallCount=a.currentCallCount),a.lastIdx=t.idx);let o=y.from(e).get(0),l=[...a.prevWindow];for(l.unshift(o);l.length>i+1;)l.pop();let c=a.prevCallCount+1;if(l.length<i+1&&(c>=i+1||t.idx>=i)){let h=y.from(e);for(;l.length<i+1;)l.push(h.get(l.length))}if(a.currentWindow=l,a.currentCallCount=c,l.length<=i)return NaN;let u=o-l[i];return t.precision(u)}}function Hd(t){return(e,n,r)=>{let i=y.from(n).get(0);t.taState||(t.taState={});let s=r||`cmo_${i}`;t.taState[s]||(t.taState[s]={lastIdx:-1,prevGainsWindow:[],prevLossesWindow:[],prevGainsSum:0,prevLossesSum:0,currentGainsWindow:[],currentLossesWindow:[],currentGainsSum:0,currentLossesSum:0});let a=t.taState[s];t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevGainsWindow=[...a.currentGainsWindow],a.prevLossesWindow=[...a.currentLossesWindow],a.prevGainsSum=a.currentGainsSum,a.prevLossesSum=a.currentLossesSum),a.lastIdx=t.idx);let o=y.from(e).get(0),l=y.from(e).get(1);if(isNaN(o)||isNaN(l))return NaN;let c=o-l,u=c>=0?c:0,h=c>=0?0:-c,p=[...a.prevGainsWindow],d=[...a.prevLossesWindow],f=a.prevGainsSum,m=a.prevLossesSum;if(p.unshift(u),d.unshift(h),f+=u,m+=h,p.length<i)return a.currentGainsWindow=p,a.currentLossesWindow=d,a.currentGainsSum=f,a.currentLossesSum=m,NaN;if(p.length>i){let w=p.pop(),E=d.pop();f-=w,m-=E}a.currentGainsWindow=p,a.currentLossesWindow=d,a.currentGainsSum=f,a.currentLossesSum=m;let x=f+m;if(x===0)return t.precision(0);let b=100*(f-m)/x;return t.precision(b)}}function Gd(t){return(e,n,r)=>{let i=y.from(n).get(0),s=y.from(e),a=0,o=!1;for(let u=0;u<i;u++){let h=s.get(u);if(isNaN(h)){o=!0;break}a+=h}if(o)return NaN;let l=0;for(let u=0;u<i;u++){let h=s.get(u);l+=h*(u+1)}if(a===0)return NaN;let c=-l/a;return t.precision(c)}}function Yd(t){return(e,n,r,i)=>{let s=y.from(r).get(0),a=y.from(e),o=y.from(n);if(t.idx<s-1)return NaN;let l=0,c=0,u=0,h=0,p=0,d=0;for(let w=0;w<s;w++){let E=a.get(w),v=o.get(w);isNaN(E)||isNaN(v)||(l+=E,c+=v,u+=E*v,h+=E*E,p+=v*v,d++)}if(d<2)return NaN;let f=d*u-l*c,m=d*h-l*l,x=d*p-c*c;if(m<=0||x<=0)return t.precision(0);let b=f/Math.sqrt(m*x);return t.precision(b)}}function Zd(t){return(e,n,r)=>{let i=y.from(e),s=y.from(n),a=i.get(0),o=s.get(0),l=i.get(1),c=s.get(1);if(isNaN(a)||isNaN(o)||isNaN(l)||isNaN(c))return!1;let u=a>o&&l<=c,h=a<o&&l>=c;return u||h}}function Xd(t){return(e,n)=>{let r=y.from(e),i=y.from(n),s=r.get(0),a=i.get(0),o=r.get(1),l=i.get(1);return o<=l&&s>a}}function Qd(t){return(e,n)=>{let r=y.from(e),i=y.from(n),s=r.get(0),a=i.get(0),o=r.get(1),l=i.get(1);return o>=l&&s<a}}function Jd(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=y.from(e).get(0);if(isNaN(s))return i.currentCumulativeSum=i.prevCumulativeSum,t.precision(i.prevCumulativeSum);let a=i.prevCumulativeSum+s;return i.currentCumulativeSum=a,t.precision(a)}}function ef(t){return(e,n,r)=>{let i=y.from(n).get(0);t.taState||(t.taState={});let s=r||`dev_${i}`;t.taState[s]||(t.taState[s]={lastIdx:-1,prevWindow:[],prevSum:0,prevCallCount:0,currentWindow:[],currentSum:0,currentCallCount:0});let a=t.taState[s];t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevWindow=[...a.currentWindow],a.prevSum=a.currentSum,a.prevCallCount=a.currentCallCount),a.lastIdx=t.idx);let o=y.from(e).get(0)||0,l=[...a.prevWindow],c=a.prevSum;for(l.unshift(o),c+=o;l.length>i;){let f=l.pop();c-=f}let u=a.prevCallCount+1;if(l.length<i&&(u>=i||t.idx>=i-1)){let f=y.from(e);for(;l.length<i;){let m=f.get(l.length);l.push(m),c+=m}}if(a.currentWindow=l,a.currentSum=c,a.currentCallCount=u,l.length<i)return NaN;let h=c/i,p=0;for(let f=0;f<i;f++)p+=Math.abs(l[f]-h);let d=p/i;return t.precision(d)}}function tf(t){return(e,n,r)=>{let i=y.from(e).get(0),s=y.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,x=p-c,b=m>x&&m>0?m:0,w=x>m&&x>0?x:0,E=o.prevInitCount,v=o.prevTrInitSum,I=o.prevPlusInitSum,C=o.prevMinusInitSum,T=o.prevSmoothedTR,O=o.prevSmoothedPlus,N=o.prevSmoothedMinus;if(E++,E<=i)v+=f,I+=b,C+=w,E===i&&(T=v/i,O=I/i,N=C/i);else{let ae=1/i;T=ae*f+(1-ae)*T,O=ae*b+(1-ae)*O,N=ae*w+(1-ae)*N}if(o.currentInitCount=E,o.currentTrInitSum=v,o.currentPlusInitSum=I,o.currentMinusInitSum=C,o.currentSmoothedTR=T,o.currentSmoothedPlus=O,o.currentSmoothedMinus=N,E<i)return[[NaN,NaN,NaN]];let j=T===0?0:100*O/T,D=T===0?0:100*N/T,W=j+D,R=W===0?0:100*Math.abs(j-D)/W,P=o.prevAdxInitCount,H=o.prevDxInitSum,te=o.prevADX,ve=NaN;if(P++,P<=s)H+=R,P===s&&(te=H/s,ve=te);else{let ae=1/s;te=ae*R+(1-ae)*te,ve=te}return o.currentAdxInitCount=P,o.currentDxInitSum=H,o.currentADX=te,[[t.precision(j),t.precision(D),t.precision(ve)]]}}function nf(t){return(e,n,r)=>{let i=y.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=y.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 rf(t){return(e,n,r)=>{let i=y.from(n).get(0),s=y.from(e);for(let a=0;a<i;a++){let o=s.get(a),l=s.get(a+1);if(isNaN(o)||isNaN(l)||o>=l)return!1}return!0}}function sf(t){return(e,n,r)=>{typeof n=="string"&&r===void 0&&(r=n,n=e,e=t.data.high);let i=y.from(n).get(0);t.taState||(t.taState={});let s=r||`highest_${i}`;t.taState[s]||(t.taState[s]={lastIdx:-1,prevWindow:[],prevCallCount:0,currentWindow:[],currentCallCount:0});let a=t.taState[s];t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevWindow=[...a.currentWindow],a.prevCallCount=a.currentCallCount),a.lastIdx=t.idx);let o=y.from(e).get(0),l=[...a.prevWindow];for(l.unshift(o);l.length>i;)l.pop();let c=a.prevCallCount+1;if(l.length<i&&(c>=i||t.idx>=i-1)){let p=y.from(e);for(;l.length<i;)l.push(p.get(l.length))}if(a.currentWindow=l,a.currentCallCount=c,l.length<i)return NaN;let u=l.filter(p=>!isNaN(p)&&p!==void 0);if(u.length===0)return NaN;let h=Math.max(...u);return t.precision(h)}}function af(t){return(e,n,r)=>{let i=y.from(n).get(0),s=y.from(e);if(t.idx<i-1)return NaN;let a=-1/0,o=NaN;for(let l=0;l<i;l++){let c=s.get(l);isNaN(c)||(isNaN(o)||c>a)&&(a=c,o=-l)}return o}}function of(t){return(e,n,r)=>{let i=y.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);if(isNaN(l)||isNaN(c))return NaN;t.taState||(t.taState={});let u=r||`hma_raw_${i}`;t.taState[u]||(t.taState[u]={lastIdx:-1,prevValues:[],currentValues:[]});let h=t.taState[u];t.idx>h.lastIdx&&(h.lastIdx>=0&&(h.prevValues=[...h.currentValues]),h.lastIdx=t.idx);let p=2*l-c,d=[...h.prevValues];d.unshift(p),d.length>a+1&&d.pop(),h.currentValues=d;let f=r?`${r}_hma_final`:`hma_final_${i}`;t.taState[f]||(t.taState[f]={lastIdx:-1,prevWindow:[],currentWindow:[]});let m=t.taState[f];t.idx>m.lastIdx&&(m.lastIdx>=0&&(m.prevWindow=[...m.currentWindow]),m.lastIdx=t.idx);let x=[...m.prevWindow];if(x.unshift(p),x.length<a)return m.currentWindow=x,NaN;for(;x.length>a;)x.pop();m.currentWindow=x;let b=0,w=0;for(let v=0;v<a;v++){let I=a-v;b+=x[v]*I,w+=I}let E=b/w;return t.precision(E)}}function lf(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)*s;if(a===0)return t.precision(0);let o=(2*n-r-i)/a;return t.precision(o)}}function cf(t){return(e,n,r,i,s)=>{let a=y.from(n).get(0),o=y.from(r).get(0),l=!0;typeof i=="string"?s=i:i!==void 0&&(l=y.from(i).get(0));let c,u=t.get(t.data.high,0),h=t.get(t.data.low,0);if(l){let v=t.get(t.data.close,1);isNaN(v)?c=NaN:c=Math.max(u-h,Math.abs(u-v),Math.abs(h-v))}else c=u-h;let p=y.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=(v,I,C,T)=>{if(isNaN(C))return Object.assign(I,v),I.prevEma!==null?I.prevEma:NaN;let O=v.initCount,N=v.initSum,j=v.prevEma;if(O<T){if(N+=C,O++,I.initSum=N,I.initCount=O,I.prevEma=j,O===T){let R=N/T;return I.prevEma=R,R}return NaN}let D=2/(T+1),W=C*D+j*(1-D);return I.prevEma=W,I.initSum=N,I.initCount=O,W},x=m(f.basisState,f.currentBasisState,p,a),b=m(f.rangeState,f.currentRangeState,c,a);if(isNaN(x)||isNaN(b))return[[NaN,NaN,NaN]];let w=x+b*o,E=x-b*o;return[[t.precision(x),t.precision(w),t.precision(E)]]}}function uf(t){return(e,n,r,i,s)=>{let a=y.from(n).get(0),o=y.from(r).get(0),l=!0;typeof i=="string"?s=i:i!==void 0&&(l=y.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=(E,v,I,C)=>{if(isNaN(I))return Object.assign(v,E),v.prevEma!==null?v.prevEma:NaN;let T=E.initCount,O=E.initSum,N=E.prevEma;if(T<C){if(O+=I,T++,v.initSum=O,v.initCount=T,v.prevEma=N,T===C){let W=O/C;return v.prevEma=W,W}return NaN}let j=2/(C+1),D=I*j+N*(1-j);return v.prevEma=D,v.initSum=O,v.initCount=T,D},p,d=t.get(t.data.high,0),f=t.get(t.data.low,0);if(l){let E=t.get(t.data.close,1);isNaN(E)?p=NaN:p=Math.max(d-f,Math.abs(d-E),Math.abs(f-E))}else p=d-f;let m=y.from(e).get(0),x=h(u.basisState,u.currentBasisState,m,a),b=h(u.rangeState,u.currentRangeState,p,a);if(isNaN(x)||isNaN(b))return NaN;if(x===0)return t.precision(0);let w=2*b*o/x;return t.precision(w)}}function pf(t){return(e,n,r,i)=>{let s=y.from(n).get(0),a=y.from(r).get(0);t.taState||(t.taState={});let o=i||`linreg_${s}_${a}`;t.taState[o]||(t.taState[o]={lastIdx:-1,prevWindow:[],prevCallCount:0,currentWindow:[],currentCallCount:0});let l=t.taState[o];t.idx>l.lastIdx&&(l.lastIdx>=0&&(l.prevWindow=[...l.currentWindow],l.prevCallCount=l.currentCallCount),l.lastIdx=t.idx);let c=y.from(e).get(0),u=[...l.prevWindow];for(u.unshift(c);u.length>s;)u.pop();let h=l.prevCallCount+1;if(u.length<s&&(h>=s||t.idx>=s-1)){let v=y.from(e);for(;u.length<s;)u.push(v.get(u.length))}if(l.currentWindow=u,l.currentCallCount=h,u.length<s)return NaN;let p=0,d=0,f=0,m=0,x=s;for(let v=0;v<s;v++){let I=s-1-v,C=u[v];p+=I,d+=C,f+=I*C,m+=I*I}let b=x*m-p*p;if(b===0)return NaN;let w=(x*f-p*d)/b,E=(d-w*p)/x+w*(s-1-a);return t.precision(E)}}function hf(t){return(e,n,r)=>{typeof n=="string"&&r===void 0&&(r=n,n=e,e=t.data.low);let i=y.from(n).get(0);t.taState||(t.taState={});let s=r||`lowest_${i}`;t.taState[s]||(t.taState[s]={lastIdx:-1,prevWindow:[],prevCallCount:0,currentWindow:[],currentCallCount:0});let a=t.taState[s];t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevWindow=[...a.currentWindow],a.prevCallCount=a.currentCallCount),a.lastIdx=t.idx);let o=y.from(e).get(0),l=[...a.prevWindow];for(l.unshift(o);l.length>i;)l.pop();let c=a.prevCallCount+1;if(l.length<i&&(c>=i||t.idx>=i-1)){let p=y.from(e);for(;l.length<i;)l.push(p.get(l.length))}if(a.currentWindow=l,a.currentCallCount=c,l.length<i)return NaN;let u=l.filter(p=>!isNaN(p)&&p!==void 0);if(u.length===0)return NaN;let h=Math.min(...u);return t.precision(h)}}function df(t){return(e,n,r)=>{let i=y.from(n).get(0),s=y.from(e);if(t.idx<i-1)return NaN;let a=1/0,o=NaN;for(let l=0;l<i;l++){let c=s.get(l);isNaN(c)||(isNaN(o)||c<a)&&(a=c,o=-l)}return o}}function ff(t){return(e,n,r,i,s)=>{let a=y.from(n).get(0),o=y.from(r).get(0),l=y.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 x=NaN;isNaN(m)||(x=t.pine.ta.ema(m,l,p));let b=NaN;return!isNaN(m)&&!isNaN(x)&&(b=m-x),[[t.precision(m),t.precision(x),t.precision(b)]]}}function mf(t){return(e,n,r)=>{let i=y.from(n).get(0);t.taState||(t.taState={});let s=r||`median_${i}`;t.taState[s]||(t.taState[s]={lastIdx:-1,prevWindow:[],prevCallCount:0,currentWindow:[],currentCallCount:0});let a=t.taState[s];t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevWindow=[...a.currentWindow],a.prevCallCount=a.currentCallCount),a.lastIdx=t.idx);let o=y.from(e).get(0),l=[...a.prevWindow];for(l.unshift(o);l.length>i;)l.pop();let c=a.prevCallCount+1;if(l.length<i&&(c>=i||t.idx>=i-1)){let d=y.from(e);for(;l.length<i;)l.push(d.get(l.length))}if(a.currentWindow=l,a.currentCallCount=c,l.length<i)return NaN;let u=l.slice().sort((d,f)=>d-f),h=Math.floor(i/2),p=i%2===0?(u[h-1]+u[h])/2:u[h];return t.precision(p)}}function yf(t){return(e,n,r)=>{let i=y.from(n).get(0);t.taState||(t.taState={});let s=r||`mfi_${i}`;t.taState[s]||(t.taState[s]={lastIdx:-1,prevUpperWindow:[],prevLowerWindow:[],prevUpperSum:0,prevLowerSum:0,currentUpperWindow:[],currentLowerWindow:[],currentUpperSum:0,currentLowerSum:0});let a=t.taState[s];t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevUpperWindow=[...a.currentUpperWindow],a.prevLowerWindow=[...a.currentLowerWindow],a.prevUpperSum=a.currentUpperSum,a.prevLowerSum=a.currentLowerSum),a.lastIdx=t.idx);let o=y.from(e).get(0),l=y.from(e).get(1),c=t.get(t.data.volume,0);if(isNaN(o)||isNaN(c))return NaN;let u=isNaN(l)?NaN:o-l,h=c*(u<=0?0:o),p=c*(u>=0?0:o),d=[...a.prevUpperWindow],f=[...a.prevLowerWindow],m=a.prevUpperSum,x=a.prevLowerSum;if(d.unshift(h),f.unshift(p),m+=h,x+=p,d.length<i)return a.currentUpperWindow=d,a.currentLowerWindow=f,a.currentUpperSum=m,a.currentLowerSum=x,NaN;if(d.length>i){let w=d.pop(),E=f.pop();m-=w,x-=E}if(a.currentUpperWindow=d,a.currentLowerWindow=f,a.currentUpperSum=m,a.currentLowerSum=x,x===0)return t.precision(100);if(m===0)return t.precision(0);let b=100-100/(1+m/x);return t.precision(b)}}function gf(t){return(e,n,r)=>{let i=y.from(n).get(0),s=y.from(e);if(t.idx<i-1)return NaN;let a=new Map;for(let c=0;c<i;c++){let u=s.get(c);isNaN(u)||a.set(u,(a.get(u)||0)+1)}if(a.size===0)return NaN;let o=NaN,l=-1;for(let[c,u]of a.entries())u>l?(l=u,o=c):u===l&&c<o&&(o=c);return o}}function _f(t){return(e,n,r)=>{let i=y.from(n).get(0);return t.pine.ta.change(e,i,r)}}function xf(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 bf(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 wf(t){return(e,n,r)=>e instanceof y?n?new y(e.data,e.offset+n):e:(t.params[r]||(t.params[r]=[]),Array.isArray(e)?new y(e,n||0):(t.params[r].length===0?t.params[r].push(e):t.params[r][t.params[r].length-1]=e,new y(t.params[r],n||0)))}function vf(t){return(e,n,r,i)=>{let s=y.from(n).get(0),a=y.from(r).get(0),o=y.from(e);if(t.idx<s-1)return NaN;let l=[];for(let f=0;f<s;f++){let m=o.get(f);if(isNaN(m))return NaN;l.push(m)}l.sort((f,m)=>f-m);let c=a/100*s-.5;c<0&&(c=0),c>s-1&&(c=s-1);let u=Math.floor(c),h=Math.ceil(c);if(u===h)return t.precision(l[u]);let p=c-u,d=l[u]+p*(l[h]-l[u]);return t.precision(d)}}function Ef(t){return(e,n,r,i)=>{let s=y.from(n).get(0),a=y.from(r).get(0),o=y.from(e);if(t.idx<s-1)return NaN;let l=[];for(let u=0;u<s;u++){let h=o.get(u);isNaN(h)||l.push(h)}if(l.length===0)return NaN;l.sort((u,h)=>u-h);let c=Math.ceil(a/100*l.length)-1;return c<0&&(c=0),c>=l.length&&(c=l.length-1),t.precision(l[c])}}function Sf(t){return(e,n,r)=>{let i=y.from(n).get(0),s=y.from(e);if(t.idx<i)return NaN;let a=s.get(0);if(isNaN(a))return NaN;let o=0,l=0;for(let c=1;c<=i;c++){let u=s.get(c);isNaN(u)||(l++,u<=a&&o++)}return l===0?NaN:t.precision(o/l*100)}}function Cf(t,e,n){let r=new Array(t.length).fill(NaN);for(let i=e+n;i<t.length;i++){let s=t[i-n],a=!0;for(let o=1;o<=e;o++)if(t[i-n-o]>=s){a=!1;break}if(a){for(let o=1;o<=n;o++)if(t[i-n+o]>=s){a=!1;break}}a&&(r[i]=s)}return r}function Nf(t){return(e,n,r,i)=>{typeof r=="string"&&(r=n,n=e,e=t.data.high);let s=y.from(n).get(0),a=y.from(r).get(0),o=y.from(e).toArray(),l=Cf(o,s,a),c=t.idx;return t.precision(l[c])}}function kf(t,e,n){let r=new Array(t.length).fill(NaN);for(let i=e+n;i<t.length;i++){let s=t[i-n],a=!0;for(let o=1;o<=e;o++)if(t[i-n-o]<=s){a=!1;break}if(a){for(let o=1;o<=n;o++)if(t[i-n+o]<=s){a=!1;break}}a&&(r[i]=s)}return r}function If(t){return(e,n,r,i)=>{typeof r=="string"&&(r=n,n=e,e=t.data.low);let s=y.from(n).get(0),a=y.from(r).get(0),o=y.from(e).toArray(),l=kf(o,s,a),c=t.idx;return t.precision(l[c])}}function Af(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 Tf(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 Df(t){return(e,n,r)=>{let i=t.pine.ta.highest(e,n,(r||"range")+"_h"),s=t.pine.ta.lowest(e,n,(r||"range")+"_l");return isNaN(i)||isNaN(s)?NaN:t.precision(i-s)}}function Mf(t){return(e,n,r)=>{let i=y.from(n).get(0),s=y.from(e);for(let a=0;a<i;a++){let o=s.get(a),l=s.get(a+1);if(isNaN(o)||isNaN(l)||o<=l)return!1}return!0}}function Pf(t){return(e,n,r)=>{let i=y.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=y.from(e).get(0)||0,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 Rf(t){return(e,n,r)=>{let i=y.from(n).get(0);t.taState||(t.taState={});let s=r||`roc_${i}`;t.taState[s]||(t.taState[s]={lastIdx:-1,prevWindow:[],prevCallCount:0,currentWindow:[],currentCallCount:0});let a=t.taState[s];t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevWindow=[...a.currentWindow],a.prevCallCount=a.currentCallCount),a.lastIdx=t.idx);let o=y.from(e).get(0),l=[...a.prevWindow];for(l.unshift(o);l.length>i+1;)l.pop();let c=a.prevCallCount+1;if(l.length<i+1&&(c>=i+1||t.idx>=i)){let p=y.from(e);for(;l.length<i+1;)l.push(p.get(l.length))}if(a.currentWindow=l,a.currentCallCount=c,l.length<=i)return NaN;let u=l[i],h=(o-u)/u*100;return t.precision(h)}}function Ff(t){return(e,n,r)=>{let i=y.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,prevInitGains:[],prevInitLosses:[],currentPrevValue:null,currentAvgGain:0,currentAvgLoss:0,currentInitGains:[],currentInitLosses:[]});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.prevInitGains=[...a.currentInitGains],a.prevInitLosses=[...a.currentInitLosses]),a.lastIdx=t.idx);let o=y.from(e).get(0);if(o==null||isNaN(o))return NaN;let l=a.prevPrevValue;if(l===null||isNaN(l))return a.currentPrevValue=o,a.currentInitGains=[...a.prevInitGains],a.currentInitLosses=[...a.prevInitLosses],a.currentAvgGain=a.prevAvgGain,a.currentAvgLoss=a.prevAvgLoss,NaN;let c=a.prevAvgGain,u=a.prevAvgLoss,h=[...a.prevInitGains],p=[...a.prevInitLosses],d=o-l,f=d>0?d:0,m=d<0?-d:0;if(h.length<i){if(h.push(f),p.push(m),a.currentInitGains=h,a.currentInitLosses=p,a.currentPrevValue=o,h.length===i){c=h.reduce((w,E)=>w+E,0)/i,u=p.reduce((w,E)=>w+E,0)/i,a.currentAvgGain=c,a.currentAvgLoss=u;let b=u===0?100:100-100/(1+c/u);return t.precision(b)}return NaN}c=(c*(i-1)+f)/i,u=(u*(i-1)+m)/i,a.currentAvgGain=c,a.currentAvgLoss=u,a.currentPrevValue=o;let x=u===0?100:100-100/(1+c/u);return t.precision(x)}}function Bf(t){return(e,n,r,i)=>{let s=y.from(e).get(0),a=y.from(n).get(0),o=y.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),x=t.get(t.data.low,0),b=t.get(t.data.close,0),w=t.get(t.data.close,1),E=t.get(t.data.high,1),v=t.get(t.data.low,1),I=t.get(t.data.high,2),C=t.get(t.data.low,2);if(isNaN(m)||isNaN(x)||isNaN(b))return c.currentResult=u,c.currentMaxMin=h,c.currentAcceleration=p,c.currentIsBelow=d,c.currentBarIndex=f,NaN;let T=!1;return f===1&&(b>w?(d=!0,h=m,u=v):(d=!1,h=x,u=E),T=!0,p=s),f>=1&&(u=u+p*(h-u),d?u>x&&(T=!0,d=!1,u=Math.max(m,h),h=x,p=s):u<m&&(T=!0,d=!0,u=Math.min(x,h),h=m,p=s),T||(d?m>h&&(h=m,p=Math.min(p+a,o)):x<h&&(h=x,p=Math.min(p+a,o))),d?(u=Math.min(u,v),f>1&&(u=Math.min(u,C))):(u=Math.max(u,E),f>1&&(u=Math.max(u,I)))),f++,c.currentResult=u,c.currentMaxMin=h,c.currentAcceleration=p,c.currentIsBelow=d,c.currentBarIndex=f,f<=1?NaN:t.precision(u)}}function Lf(t){return(e,n,r)=>{let i=y.from(n).get(0);t.taState||(t.taState={});let s=r||`sma_${i}`;t.taState[s]||(t.taState[s]={lastIdx:-1,prevWindow:[],prevSum:0,prevCallCount:0,currentWindow:[],currentSum:0,currentCallCount:0});let a=t.taState[s];t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevWindow=[...a.currentWindow],a.prevSum=a.currentSum,a.prevCallCount=a.currentCallCount),a.lastIdx=t.idx);let o=y.from(e).get(0),l=[...a.prevWindow];for(l.unshift(o);l.length>i;)l.pop();let c=a.prevCallCount+1,u=!1;if(l.length<i&&(c>=i||t.idx>=i-1)){let m=y.from(e);for(;l.length<i;)l.push(m.get(l.length));u=!0}let h,p=o==null||Number.isNaN(o),d=!Number.isNaN(a.prevSum)&&!p&&!u;if(d){let m=a.prevSum+o;if(a.prevWindow.length>=i){let x=a.prevWindow[a.prevWindow.length-1];x==null||Number.isNaN(x)?d=!1:m-=x}d&&(h=m)}if(!d){h=0;let m=!1;for(let x of l){if(x==null||Number.isNaN(x)){m=!0;break}h+=x}m&&(h=NaN)}if(a.currentWindow=l,a.currentSum=h,a.currentCallCount=c,l.length<i)return NaN;let f=h/i;return t.precision(f)}}function Of(t){return(e,n,r=!0,i)=>{let s=y.from(n).get(0),a=y.from(r).get(0);t.taState||(t.taState={});let o=i||`stdev_${s}_${a}`;t.taState[o]||(t.taState[o]={lastIdx:-1,prevWindow:[],prevSum:0,prevCallCount:0,currentWindow:[],currentSum:0,currentCallCount:0});let l=t.taState[o];t.idx>l.lastIdx&&(l.lastIdx>=0&&(l.prevWindow=[...l.currentWindow],l.prevSum=l.currentSum,l.prevCallCount=l.currentCallCount),l.lastIdx=t.idx);let c=y.from(e).get(0);if(c==null||isNaN(c))return NaN;let u=[...l.prevWindow],h=l.prevSum;for(u.unshift(c),h+=c;u.length>s;){let b=u.pop();h-=b}let p=l.prevCallCount+1;if(u.length<s&&(p>=s||t.idx>=s-1)){let b=y.from(e);for(;u.length<s;){let w=b.get(u.length);if(w==null||isNaN(w))break;u.push(w),h+=w}}if(l.currentWindow=u,l.currentSum=h,l.currentCallCount=p,u.length<s)return NaN;let d=h/s,f=0;for(let b=0;b<s;b++)f+=Math.pow(u[b]-d,2);let m=a?s:s-1,x=Math.sqrt(f/m);return t.precision(x)}}function Vf(t){return(e,n,r,i,s)=>{let a=y.from(i).get(0);t.taState||(t.taState={});let o=s||`stoch_${a}`;t.taState[o]||(t.taState[o]={lastIdx:-1,prevHighWindow:[],prevLowWindow:[],currentHighWindow:[],currentLowWindow:[]});let l=t.taState[o];t.idx>l.lastIdx&&(l.lastIdx>=0&&(l.prevHighWindow=[...l.currentHighWindow],l.prevLowWindow=[...l.currentLowWindow]),l.lastIdx=t.idx);let c=y.from(e).get(0),u=y.from(n).get(0),h=y.from(r).get(0);if(isNaN(c)||isNaN(u)||isNaN(h))return l.currentHighWindow=[...l.prevHighWindow],l.currentLowWindow=[...l.prevLowWindow],NaN;let p=[...l.prevHighWindow],d=[...l.prevLowWindow];if(p.unshift(u),d.unshift(h),p.length>a&&(p.pop(),d.pop()),l.currentHighWindow=p,l.currentLowWindow=d,p.length<a)return NaN;let f=p[0],m=d[0];for(let w=1;w<a;w++)p[w]>f&&(f=p[w]),d[w]<m&&(m=d[w]);let x=f-m;if(x===0)return NaN;let b=100*(c-m)/x;return t.precision(b)}}function jf(t){return(e,n,r)=>{let i=y.from(e).get(0),s=y.from(n).get(0);t.taState||(t.taState={});let a=r||`supertrend_${i}_${s}`;t.taState[a]||(t.taState[a]={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 o=t.taState[a];t.idx>o.lastIdx&&(o.lastIdx>=0&&(o.prevTrSum=o.currentTrSum,o.prevAtrValue=o.currentAtrValue,o.prevAtrCount=o.currentAtrCount,o.prevLowerBand=o.currentLowerBand,o.prevUpperBand=o.currentUpperBand,o.prevSuperTrend=o.currentSuperTrend,o.prevDirection=o.currentDirection),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]];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=o.prevAtrCount,m=o.prevTrSum,x=o.prevAtrValue;f++,f<=s?(m+=d,f===s&&(x=m/s)):x=(x*(s-1)+d)/s;let b=x;if(o.currentAtrCount=f,o.currentTrSum=m,o.currentAtrValue=x,isNaN(b))return[[NaN,NaN]];let w=h+i*b,E=h-i*b,v=isNaN(o.prevLowerBand)?0:o.prevLowerBand,I=isNaN(o.prevUpperBand)?0:o.prevUpperBand;isNaN(o.prevLowerBand)||E>v||p<v||(E=v),isNaN(o.prevUpperBand)||w<I||p>I||(w=I);let C,T,O=o.prevSuperTrend;return f===s?C=1:O===o.prevUpperBand?C=u>w?-1:1:C=u<E?1:-1,T=C===-1?E:w,o.currentLowerBand=E,o.currentUpperBand=w,o.currentSuperTrend=T,o.currentDirection=C,[[t.precision(T),C]]}}function $f(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]={lastIdx:-1,prevWindow:[],currentWindow:[]});let a=t.taState[s];t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevWindow=[...a.currentWindow]),a.lastIdx=t.idx);let o=y.from(e).get(0),l=[...a.prevWindow];for(l.unshift(o);l.length>4;)l.pop();if(l.length<4&&t.idx>=3){let u=y.from(e);for(;l.length<4;)l.push(u.get(l.length))}if(a.currentWindow=l,l.length<4)return NaN;let c=0;for(let u=0;u<4;u++)c+=r[u]*l[3-u];return c/=i,t.precision(c)}}function Wf(t){return(e,n)=>{let r=!0;typeof e=="string"||e!==void 0&&(r=y.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 Uf(t){return(e,n,r,i)=>{let s=y.from(n).get(0),a=y.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=y.from(e).get(0);if(isNaN(c))return 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),x=l.prevEma1PcCount,b=l.prevEma1PcSum,w=l.prevEma1PcValue;x++,x<=a?(b+=u,x===a&&(w=b/a)):w=u*p+w*(1-p);let E=l.prevEma1AbsCount,v=l.prevEma1AbsSum,I=l.prevEma1AbsValue;if(E++,E<=a?(v+=h,E===a&&(I=v/a)):I=h*f+I*(1-f),isNaN(w)||isNaN(I))return l.currentEma1PcCount=x,l.currentEma1PcSum=b,l.currentEma1PcValue=w,l.currentEma1AbsCount=E,l.currentEma1AbsSum=v,l.currentEma1AbsValue=I,NaN;let C=l.prevEma2PcCount,T=l.prevEma2PcSum,O=l.prevEma2PcValue;C++,C<=s?(T+=w,C===s&&(O=T/s)):O=w*d+O*(1-d);let N=l.prevEma2AbsCount,j=l.prevEma2AbsSum,D=l.prevEma2AbsValue;if(N++,N<=s?(j+=I,N===s&&(D=j/s)):D=I*m+D*(1-m),l.currentEma1PcCount=x,l.currentEma1PcSum=b,l.currentEma1PcValue=w,l.currentEma1AbsCount=E,l.currentEma1AbsSum=v,l.currentEma1AbsValue=I,l.currentEma2PcCount=C,l.currentEma2PcSum=T,l.currentEma2PcValue=O,l.currentEma2AbsCount=N,l.currentEma2AbsSum=j,l.currentEma2AbsValue=D,isNaN(O)||isNaN(D))return NaN;if(D===0)return t.precision(0);let W=O/D;return t.precision(W)}}function qf(t){return(e,n,r,i)=>{t.taState||(t.taState={});let s=i||"valuewhen";t.taState[s]||(t.taState[s]={lastIdx:-1,prevValues:[],currentValues:[]});let a=t.taState[s];t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevValues=[...a.currentValues]),a.lastIdx=t.idx);let o=y.from(e).get(0),l=y.from(n).get(0),c=y.from(r).get(0),u=[...a.prevValues];if(o&&u.push(l),a.currentValues=u,isNaN(c)||c<0)return NaN;let h=u.length-1-c;if(h<0)return NaN;let p=u[h];return typeof p=="number"?t.precision(p):p}}function zf(t){return(e,n,r)=>{let i=y.from(n).get(0);t.taState||(t.taState={});let s=r||`variance_${i}`;t.taState[s]||(t.taState[s]={lastIdx:-1,prevWindow:[],prevCallCount:0,currentWindow:[],currentCallCount:0});let a=t.taState[s];t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevWindow=[...a.currentWindow],a.prevCallCount=a.currentCallCount),a.lastIdx=t.idx);let o=y.from(e).get(0),l=[...a.prevWindow];for(l.unshift(o);l.length>i;)l.pop();let c=a.prevCallCount+1;if(l.length<i&&(c>=i||t.idx>=i-1)){let f=y.from(e);for(;l.length<i;)l.push(f.get(l.length))}if(a.currentWindow=l,a.currentCallCount=c,l.length<i)return NaN;let u=0,h=0;for(let f=0;f<i;f++)u+=l[f],h+=l[f]*l[f];let p=u/i,d=h/i-p*p;return t.precision(d)}}function Kf(t){return(e,n)=>{t.taState||(t.taState={});let r=n||"vwap";t.taState[r]||(t.taState[r]={lastIdx:-1,prevCumulativePV:0,prevCumulativeVolume:0,prevLastSessionDate:null,currentCumulativePV:0,currentCumulativeVolume:0,currentLastSessionDate:null});let i=t.taState[r];t.idx>i.lastIdx&&(i.lastIdx>=0&&(i.prevCumulativePV=i.currentCumulativePV,i.prevCumulativeVolume=i.currentCumulativeVolume,i.prevLastSessionDate=i.currentLastSessionDate),i.lastIdx=t.idx);let s=y.from(e).get(0),a=y.from(t.data.volume).get(0),o=y.from(t.data.openTime).get(0),l=t.pine?.syminfo?.timezone||"UTC",c=jt(o,l),u=`${c.year}-${String(c.month).padStart(2,"0")}-${String(c.day).padStart(2,"0")}`,h=i.prevCumulativePV,p=i.prevCumulativeVolume,d=i.prevLastSessionDate;if(d!==u&&(h=0,p=0,d=u),h+=s*a,p+=a,i.currentCumulativePV=h,i.currentCumulativeVolume=p,i.currentLastSessionDate=d,p===0)return NaN;let f=h/p;return t.precision(f)}}function Hf(t){return(e,n,r)=>{let i=y.from(n).get(0);t.taState||(t.taState={});let s=r||`vwma_${i}`;t.taState[s]||(t.taState[s]={lastIdx:-1,prevWindow:[],prevVolumeWindow:[],currentWindow:[],currentVolumeWindow:[]});let a=t.taState[s];t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevWindow=[...a.currentWindow],a.prevVolumeWindow=[...a.currentVolumeWindow]),a.lastIdx=t.idx);let o=y.from(e).get(0),l=t.get(t.data.volume,0),c=[...a.prevWindow],u=[...a.prevVolumeWindow];for(c.unshift(o),u.unshift(l);c.length>i;)c.pop(),u.pop();if(c.length<i&&t.idx>=i-1){let f=y.from(e),m=y.from(t.data.volume);for(;c.length<i;)c.push(f.get(c.length)),u.push(m.get(u.length))}if(a.currentWindow=c,a.currentVolumeWindow=u,c.length<i)return NaN;let h=0,p=0;for(let f=0;f<i;f++)h+=c[f]*u[f],p+=u[f];let d=h/p;return t.precision(d)}}function Gf(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)}}function Yf(t){return(e,n,r)=>{let i=y.from(n).get(0);t.taState||(t.taState={});let s=r||`wma_${i}`;t.taState[s]||(t.taState[s]={lastIdx:-1,prevWindow:[],prevCallCount:0,currentWindow:[],currentCallCount:0});let a=t.taState[s];t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevWindow=[...a.currentWindow],a.prevCallCount=a.currentCallCount),a.lastIdx=t.idx);let o=y.from(e).get(0),l=[...a.prevWindow];for(l.unshift(o);l.length>i;)l.pop();let c=a.prevCallCount+1;if(l.length<i&&(c>=i||t.idx>=i-1)){let d=y.from(e);for(;l.length<i;)l.push(d.get(l.length))}if(a.currentWindow=l,a.currentCallCount=c,l.length<i)return NaN;let u=0,h=0;for(let d=0;d<i;d++){let f=i-d;u+=l[d]*f,h+=f}let p=u/h;return t.precision(p)}}function Zf(t){return(e,n)=>{let r=y.from(e).get(0);t.taState||(t.taState={});let i=n||`wpr_${r}`;t.taState[i]||(t.taState[i]={lastIdx:-1,prevHighWindow:[],prevLowWindow:[],currentHighWindow:[],currentLowWindow:[]});let s=t.taState[i];t.idx>s.lastIdx&&(s.lastIdx>=0&&(s.prevHighWindow=[...s.currentHighWindow],s.prevLowWindow=[...s.currentLowWindow]),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 s.currentHighWindow=[...s.prevHighWindow],s.currentLowWindow=[...s.prevLowWindow],NaN;let c=[...s.prevHighWindow],u=[...s.prevLowWindow];if(c.unshift(a),u.unshift(o),c.length>r&&(c.pop(),u.pop()),s.currentHighWindow=c,s.currentLowWindow=u,c.length<r)return NaN;let h=c[0],p=u[0];for(let m=1;m<r;m++)c[m]>h&&(h=c[m]),u[m]<p&&(p=u[m]);let d=h-p;if(d===0)return t.precision(0);let f=(h-l)/d*-100;return t.precision(f)}}function Xf(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 Qf=Object.defineProperty,Jf=(t,e,n)=>e in t?Qf(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,F=(t,e,n)=>Jf(t,typeof e!="symbol"?e+"":e,n),em={accdist:Vd,alma:jd,atr:$d,barssince:Wd,bb:Ud,bbw:qd,cci:zd,change:Kd,cmo:Hd,cog:Gd,correlation:Yd,cross:Zd,crossover:Xd,crossunder:Qd,cum:Jd,dev:ef,dmi:tf,ema:nf,falling:rf,highest:sf,highestbars:af,hma:of,iii:lf,kc:cf,kcw:uf,linreg:pf,lowest:hf,lowestbars:df,macd:ff,median:mf,mfi:yf,mode:gf,mom:_f,nvi:xf,obv:bf,param:wf,percentile_linear_interpolation:vf,percentile_nearest_rank:Ef,percentrank:Sf,pivothigh:Nf,pivotlow:If,pvi:Af,pvt:Tf,range:Df,rising:Mf,rma:Pf,roc:Rf,rsi:Ff,sar:Bf,sma:Lf,stdev:Of,stoch:Vf,supertrend:jf,swma:$f,tr:Wf,tsi:Uf,valuewhen:qf,variance:zf,vwap:Kf,vwma:Hf,wad:Gf,wma:Yf,wpr:Zf,wvad:Xf},Pi=class{constructor(e){this.context=e,F(this,"accdist"),F(this,"alma"),F(this,"atr"),F(this,"barssince"),F(this,"bb"),F(this,"bbw"),F(this,"cci"),F(this,"change"),F(this,"cmo"),F(this,"cog"),F(this,"correlation"),F(this,"cross"),F(this,"crossover"),F(this,"crossunder"),F(this,"cum"),F(this,"dev"),F(this,"dmi"),F(this,"ema"),F(this,"falling"),F(this,"highest"),F(this,"highestbars"),F(this,"hma"),F(this,"iii"),F(this,"kc"),F(this,"kcw"),F(this,"linreg"),F(this,"lowest"),F(this,"lowestbars"),F(this,"macd"),F(this,"median"),F(this,"mfi"),F(this,"mode"),F(this,"mom"),F(this,"nvi"),F(this,"obv"),F(this,"param"),F(this,"percentile_linear_interpolation"),F(this,"percentile_nearest_rank"),F(this,"percentrank"),F(this,"pivothigh"),F(this,"pivotlow"),F(this,"pvi"),F(this,"pvt"),F(this,"range"),F(this,"rising"),F(this,"rma"),F(this,"roc"),F(this,"rsi"),F(this,"sar"),F(this,"sma"),F(this,"stdev"),F(this,"stoch"),F(this,"supertrend"),F(this,"swma"),F(this,"tr"),F(this,"tsi"),F(this,"valuewhen"),F(this,"variance"),F(this,"vwap"),F(this,"vwma"),F(this,"wad"),F(this,"wma"),F(this,"wpr"),F(this,"wvad"),Object.entries(em).forEach(([n,r])=>{this[n]=r(e)})}};function tm(t){if(t.length===0)return{};if(typeof t[0]=="object"&&t[0]!==null)return t[0];let e={};typeof t[0]=="string"&&(e.title=t[0]);let n=null;for(let r=1;r<t.length;r++){let i=t[r];typeof i=="string"?e.shorttitle===void 0&&(e.shorttitle=i):typeof i=="object"&&i!==null&&(n=i)}return n&&Object.assign(e,n),e}function In(t,e,n){if(!n||n<=0||!Number.isFinite(t)||t===e)return t;let r=t/n,i=1e-9;return t>e?Math.ceil(r-i)*n:Math.floor(r+i)*n}function xr(t,e,n,r){return Math.abs(t)*e*r*n/100}function nm(t,e){let n=t.strategy,r=t.pine?.syminfo?.pointvalue??1,i=0;for(let s of zr(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 rm(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+=xr(s.size,e,a,r)}return i}function ws(t,e,n,r){let i=t.strategy,s=i.config.default_qty_type||"fixed",a=i.config.default_qty_value||1;typeof s=="function"&&(s=s()),typeof a=="function"&&(a=a());let o=1e6,l=u=>Math.floor(u*o)/o;if(e!=null)return l(Math.abs(e));let c;switch(s){case"fixed":c=a;break;case"cash":c=a/r;break;case"percent_of_equity":{c=i.equity*a/100/r;break}default:c=a}return l(c)}function im(t){if(!t.strategy)return;let e=t.strategy,{pending_orders:n}=e,r=y.from(t.data.open).get(0),i=y.from(t.data.high).get(0),s=y.from(t.data.low).get(0),a=y.from(t.data.close).get(0),o=y.from(t.data.openTime).get(0),l=t.pine?.syminfo?.pointvalue??1;for(let c of e.opentrades){let u=Math.abs(c.size),h=c.size>0,p=c.commission??0,d=h?(c.entry_price-s)*u*l:(i-c.entry_price)*u*l,f=h?(i-c.entry_price)*u*l:(c.entry_price-s)*u*l,m=Math.max(0,d)+p,x=Math.max(0,f-p);m>(c.max_drawdown??0)&&(c.max_drawdown=m),x>(c.max_runup??0)&&(c.max_runup=x)}br(t,r);for(let c of n){if(c.status!=="pending"||(c.category??"entry")==="exit"||c.bar>=t.idx)continue;let u=!1,h=r;switch(c.type){case"market":u=!0,h=r;break;case"limit":if(c.limit!==void 0){let p=Vt(c.direction);(p===1&&s<=c.limit||p===-1&&i>=c.limit)&&(u=!0,h=c.limit)}break;case"stop":if(c.stop!==void 0){let p=Vt(c.direction);(p===1&&i>=c.stop||p===-1&&s<=c.stop)&&(u=!0,h=c.stop)}break}if(u){if(am(e,c)){c.status="cancelled";continue}let p=Vt(c.direction);h=Ri(t,p,h);let d=p===1?e.config.margin_long??100:e.config.margin_short??100;{let f=e.position_size,m=Math.sign(f),x=m!==0&&m!==p,b=x?Math.max(0,c.qty-Math.abs(f)):c.qty;if(b>0){let w=t.pine?.syminfo?.pointvalue??1,E=0;m===p&&(E=rm(t,r));let v=e.equity-E;if(xr(b,h,d,w)>v){let I=Math.min(Math.abs(f),c.qty);x&&I>0?(Zt(t,I,h,o,{exitId:c.id,exitComment:c.comment}),c.status="filled",c.fill_price=h,c.fill_bar=t.idx,c.fill_time=o):c.status="cancelled";continue}}}lm(t,c,h,o),c.status="filled",c.fill_price=h,c.fill_bar=t.idx,c.fill_time=o}}e.pending_orders=n.filter(c=>c.status==="pending"),br(t,a),xm(t)}function Vt(t){return typeof t=="number"?t:t==="long"?1:t==="short"?-1:0}function fo(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 Ri(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 mo(t){let e=Math.abs(t.position_size);e>t.max_contracts_held_all&&(t.max_contracts_held_all=e),t.position_size>t.max_contracts_held_long&&(t.max_contracts_held_long=t.position_size),-t.position_size>t.max_contracts_held_short&&(t.max_contracts_held_short=-t.position_size)}function sm(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}function am(t,e){if(t.risk_halted)return!0;let n=t.risk_rules,r=e.direction;if(n.allow_entry_in&&(n.allow_entry_in==="long"&&r===-1||n.allow_entry_in==="short"&&r===1))return!0;if(n.max_position_size!==void 0){let i=t.position_size+r*e.qty;if(Math.abs(i)>n.max_position_size)return!0}return!1}function om(t){if(t.risk_halted)return;let e=t.risk_rules;if(e.max_drawdown){let n=e.max_drawdown.type==="percent_of_equity"?e.max_drawdown.value/100*t.equity_peak:e.max_drawdown.value;if(t.max_drawdown>=n){t.risk_halted=!0;return}}if(e.max_intraday_loss){let n=e.max_intraday_loss.type==="percent_of_equity"?e.max_intraday_loss.value/100*t.initial_capital:e.max_intraday_loss.value;if(t.grossloss>=n){t.risk_halted=!0;return}}if(e.max_cons_loss_days){let n=0;for(let r=t.closedtrades.length-1;r>=0&&(t.closedtrades[r].profit??0)<0;r--)n++;n>=e.max_cons_loss_days.count&&(t.risk_halted=!0)}}function Qn(t,e,n,r,i,s,a,o){let l=t.strategy,c=l.opentrades.length+l.closedtrades.length,u=l.config.commission_type??"percent",h=o&&u==="cash_per_order",p=fo(t,l,r,i),d=h?p/2:p,f={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:d,max_drawdown:0,max_runup:0,status:"open"};l.opentrades.push(f),l._first_entry_price===void 0&&(l._first_entry_price=i),(l._ledger_entries??(l._ledger_entries=[])).push({entry_id:e,entry_price:i,entry_time:s,entry_bar_index:t.idx,entry_comment:f.entry_comment,qty:r,commission:d}),d>0&&(l.netprofit-=d,l.grossloss+=d);let m=y.from(t.data.high).get(0),x=y.from(t.data.low).get(0),b=t.pine?.syminfo?.mintick??.01,w=n===1?x:m,E=n===1?m:x;for(let N of l.pending_orders){if((N.category??"entry")!=="exit"||N.from_entry&&N.from_entry!==e)continue;let j;N.stop!==void 0?j=N.stop:N.loss!==void 0&&(j=n===1?i-N.loss*b:i+N.loss*b);let D;N.limit!==void 0?D=N.limit:N.profit!==void 0&&(D=n===1?i+N.profit*b:i-N.profit*b),n===1?(j!==void 0&&j>w&&(w=j),D!==void 0&&D<E&&(E=D)):(j!==void 0&&j<w&&(w=j),D!==void 0&&D>E&&(E=D))}let v=t.pine?.syminfo?.pointvalue??1,I=n===1?(i-w)*r*v:(w-i)*r*v,C=n===1?(E-i)*r*v:(i-E)*r*v;f.max_drawdown=Math.max(0,I)+d,f.max_runup=Math.max(0,C-d);let T=l.position_size,O=T+f.size;if(T===0)l.position_size=O,l.position_avg_price=i,l.position_entry_name=e;else if(Math.sign(T)===Math.sign(O)){let N=Math.abs(T)*l.position_avg_price+r*i,j=Math.abs(O);l.position_avg_price=N/j,l.position_size=O}mo(l)}function lm(t,e,n,r){let i=t.strategy,s=Vt(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(Zt(t,l,n,r,{exitId:e.id,exitComment:e.comment,isImplicitReversal:u}),c>0){let h=e._base_qty;h!==void 0&&c>h+1e-9?(Qn(t,e.id,s,h,n,r,e.comment,!0),Qn(t,e.id,s,c-h,n,r,e.comment,!0)):Qn(t,e.id,s,c,n,r,e.comment,!0)}}else Qn(t,e.id,s,e.qty,n,r,e.comment)}function cm(t,e,n){let r=[],i=n,s=t._ledger_entries??[];for(let a of s){if(i<=1e-9)break;if(a.entry_id!==e.entry_id||a.qty<=1e-9)continue;let o=Math.min(a.qty,i),l=a.qty>0?a.commission*(o/a.qty):0;r.push({qty:o,entry_price:a.entry_price,entry_time:a.entry_time,entry_bar_index:a.entry_bar_index,entry_comment:a.entry_comment,commission:l}),a.qty-=o,a.commission-=l,i-=o}if(t._ledger_entries=s.filter(a=>a.qty>1e-9),i>1e-9){let a=Math.abs(e.size);r.push({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:a>0?(e.commission??0)*(i/a):0})}return r}function Zt(t,e,n,r,i){let s=t.strategy,a=t.pine?.syminfo?.pointvalue??1,o=e,l=[...s.opentrades];s.opentrades=[];for(let p of l){if(o<=0){s.opentrades.push(p);continue}let d=Math.abs(p.size),f=Math.min(d,o),m=Math.sign(p.size),x=b=>{let w=s.config.commission_type??"percent",E=i?.isImplicitReversal&&w==="cash_per_order",v=fo(t,s,b,n),I=E?v/2:v,C=cm(s,p,b);for(let T of C){let O=I*(T.qty/b),N=(m===1?n-T.entry_price:T.entry_price-n)*T.qty*a,j={id:`trade_${s.opentrades.length+s.closedtrades.length+l.length}`,entry_id:p.entry_id,entry_comment:T.entry_comment,entry_price:T.entry_price,_bracket_entry:p._bracket_entry,entry_bar_index:T.entry_bar_index,entry_time:T.entry_time,size:m*T.qty,commission:T.commission+O,max_drawdown:p.max_drawdown,max_runup:p.max_runup,status:"closed",exit_price:n,exit_bar_index:t.idx,exit_time:r,exit_id:i?.exitId??p.exit_id,exit_comment:i?.exitComment??p.exit_comment,profit:N-T.commission-O};i?.triggerKind==="loss"&&(j.max_runup=0),i?.triggerKind==="profit"&&(j.max_drawdown=T.commission),s.netprofit+=N-O,s.grossloss-=T.commission,j.profit>0?(s.grossprofit+=j.profit,s.wintrades++,s.wintrades_total_profit+=j.profit):j.profit<0?(s.grossloss+=Math.abs(j.profit),s.losstrades++,s.losstrades_total_loss+=Math.abs(j.profit)):s.eventrades++,s.closedtrades.push(j)}};if(f>=d-1e-9)p.status="closed",p.exit_price=n,p.exit_bar_index=t.idx,p.exit_time=r,x(d),o-=f;else{x(f);let b=(p.commission??0)*(f/d);p.size=m*(d-f),p.commission=(p.commission??0)-b,s.opentrades.push(p),o=0}}om(s);let c=s.position_size,u=Math.sign(c)*e,h=c-u;if(Math.abs(h)<1e-9&&(h=0),s.position_size=h,mo(s),h===0)s.position_avg_price=NaN,s.position_entry_name="";else if(s.opentrades.length>0){let p=0,d=0;for(let f of zr(s))p+=f.qty*f.entry_price,d+=f.qty;s.position_avg_price=p/d,s.position_entry_name=s.opentrades[0].entry_id}}function zr(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 br(t,e){let n=t.strategy,r=t.pine?.syminfo?.pointvalue??1,i=0;for(let s of zr(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 um(t,e,n){let r=t.strategy,i=t.pine?.syminfo?.pointvalue??1,s=r.initial_capital+r.netprofit,a=0;for(let f of zr(r))a+=f.commission;let o=s+a;o>r.equity_peak&&(r.equity_peak=o),s<r.equity_trough&&(r.equity_trough=s);let l=r.position_size,c=r.position_avg_price,u=0,h=0;if(l!==0&&Number.isFinite(c)){let f=l>0?n:e,m=l>0?e:n;u=l*(c-f)*i,h=l*(m-c)*i}let p=r.equity_peak-s+u;if(p>r.max_drawdown&&(r.max_drawdown=p,r.equity_at_drawdown_peak=r.equity_peak,r.equity_peak>0)){let f=100*p/r.equity_peak;f>r.max_drawdown_percent_value&&(r.max_drawdown_percent_value=f)}let d=s-r.equity_trough+h;if(d>r.max_runup&&(r.max_runup=d,r.equity_at_runup_peak=s+h,r.equity_at_runup_peak>0)){let f=100*d/r.equity_at_runup_peak;f>r.max_runup_percent_value&&(r.max_runup_percent_value=f)}}function ha(t,e,n,r,i,s,a){let o=t.strategy;if(a!==void 0){let p=[],d=[];for(let m of o.opentrades)m.id===a?p.push(m):d.push(m);if(p.length===0)return;let f=Math.abs(p[0].size);o.opentrades=[...p,...d],Zt(t,Math.min(n,f),r,i,s);return}if(!e||e===""){Zt(t,n,r,i,s);return}let l=[],c=[];for(let p of o.opentrades)p.entry_id===e?l.push(p):c.push(p);let u=l.reduce((p,d)=>p+Math.abs(d.size),0);if(u===0)return;let h=Math.min(n,u);o.opentrades=[...l,...c],Zt(t,h,r,i,s)}function pm(t,e="intrabar"){if(!t.strategy)return;let n=t.strategy;if(n.pending_orders.length===0)return;let r=y.from(t.data.open).get(0),i=y.from(t.data.high).get(0),s=y.from(t.data.low).get(0),a=y.from(t.data.close).get(0),o=y.from(t.data.openTime).get(0),l=t.pine?.syminfo?.mintick??.01;for(let c of n.pending_orders){if(c.status!=="pending"||(c.category??"entry")!=="exit")continue;let u=n.opentrades.filter(D=>!c.from_entry||D.entry_id===c.from_entry);if(c._intended_trade_ids){let D=new Set(c._intended_trade_ids);u=u.filter(W=>D.has(W.id))}if(u.length===0){e==="intrabar"&&(c.status="cancelled");continue}let h=u.reduce((D,W)=>D+Math.abs(W.size),0),p=Math.sign(u[0].size);if(c.type==="market"&&c.profit===void 0&&c.loss===void 0&&c.limit===void 0&&c.stop===void 0&&c.trail_price===void 0&&c.trail_points===void 0){if(e==="open"||c.bar>=t.idx)continue;let D=c.immediately?a:r;D=Ri(t,-p,D);let W=h;c.qty&&c.qty>0?W=Math.min(c.qty,h):c.qty_percent&&c.qty_percent>0&&(W=h*(c.qty_percent/100)),ha(t,c.from_entry,W,D,o,{exitId:c.id,exitComment:c.comment}),c.status="filled",c.fill_price=D,c.fill_bar=t.idx,c.fill_time=o;continue}let d=0;for(let D of u)d+=Math.abs(D.size)*D.entry_price;let f=d/h,m=p===1,x=c.limit,b=c.stop;c._isPersistent||(b!==void 0&&((m?b<f:b>f)||(b=void 0)),x!==void 0&&((m?x>f:x<f)||(x=void 0))),c._attachedAtReversal&&!c._isPersistent&&(c.limit!==void 0&&(x=void 0),c.stop!==void 0&&(b=void 0));let w=!1;if(e==="intrabar"&&!c.trail_armed&&(c.trail_price!==void 0||c.trail_points!==void 0)){let D;c.trail_price!==void 0?D=c.trail_price:c.trail_points!==void 0&&(D=m?f+c.trail_points*l:f-c.trail_points*l),D!==void 0&&(m?i>=D:s<=D)&&(c.trail_armed=!0,c.trail_peak=m?i:s,w=!0)}let E=Math.abs(i-r)<=Math.abs(r-s),v=m?E:!E,I=[],C=[],T=n._mc_exit_lock,O=T&&T.bar===t.idx;for(let D of u){if(O&&D.id!==T.tradeId)continue;let W=D._bracket_entry??D.entry_price,R=Math.abs(D.size),P=x;P===void 0&&c.profit!==void 0&&(P=m?W+c.profit*l:W-c.profit*l);let H=b;H===void 0&&c.loss!==void 0&&(H=m?W-c.loss*l:W+c.loss*l);let te=P!==void 0&&(e==="open"?m?r>=P:r<=P:m?i>=P:s<=P),ve=H!==void 0&&(e==="open"?m?r<=H:r>=H:m?s<=H:i>=H),ae=null;if(te&&ve?ae=v?"profit":"loss":te?ae="profit":ve&&(ae="loss"),ae==="loss"){let Fe=m?r<=H:r>=H;!m&&Fe&&D.entry_bar_index===t.idx?te&&(ae="profit"):C.push({qty:R,price:Fe?r:H,kind:"loss",tradeId:D.id})}if(ae==="profit"){let Fe=m?r>=P:r<=P;I.push({qty:R,price:Fe?r:P,kind:"profit",tradeId:D.id})}}I.sort((D,W)=>m?D.price-W.price:W.price-D.price),C.sort((D,W)=>m?W.price-D.price:D.price-W.price);let N=null;if(e==="intrabar"&&!O&&c.trail_armed&&c.trail_offset!==void 0){let D=()=>{m?c.trail_peak=Math.max(c.trail_peak??-1/0,i):c.trail_peak=Math.min(c.trail_peak??1/0,s)},W=()=>m?c.trail_peak-c.trail_offset*l:c.trail_peak+c.trail_offset*l,R=P=>{N={qty:1/0,price:P,kind:"trailing"}};if(w){let P=W();v?(m?s<=P:i>=P)&&R(P):(m?a<=P:a>=P)&&R(P)}else if(v){D();let P=W();(m?s<=P:i>=P)&&R(P)}else{let P=W();if(m?s<=P:i>=P)R(P);else{D();let H=W();(m?a<=H:a>=H)&&R(H)}}}let j=v?[...I,...C,...N?[N]:[]]:[...C,...N?[N]:[],...I];if(j.length>0){let D=h;c.qty&&c.qty>0?D=Math.min(c.qty,h):c.qty_percent&&c.qty_percent>0&&(D=h*(c.qty_percent/100));let W=()=>n.opentrades.filter(H=>!c.from_entry||H.entry_id===c.from_entry).reduce((H,te)=>H+Math.abs(te.size),0),R=NaN,P=!1;for(let H of j){if(D<=1e-9)break;let te=W();if(te<=1e-9)break;let ve=Math.min(H.qty===1/0?te:H.qty,D,te),ae=Ri(t,-p,H.price),Fe=H.kind==="profit"?c.comment_profit??c.comment:H.kind==="loss"?c.comment_loss??c.comment:c.comment_trailing??c.comment;ha(t,c.from_entry,ve,ae,o,{triggerKind:H.kind,exitId:c.id,exitComment:Fe},H.tradeId),D-=ve,R=ae,P=!0}P&&(W()<=1e-9||D<=1e-9)&&(c.status="filled",c.fill_price=R,c.fill_bar=t.idx,c.fill_time=o)}}n.pending_orders=n.pending_orders.filter(c=>c.status==="pending"),br(t,a)}function hm(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)&&(Zt(t,Math.min(n.qty,Math.abs(e.position_size)),n.price,n.time,{exitId:"Margin call",exitComment:"Margin call"}),Math.abs(e.position_size)>1e-9))){for(let r of e.pending_orders)r.status==="pending"&&(r.category??"entry")==="entry"&&!r._isReversalEntry&&Vt(r.direction)===n.dir&&(r.status="cancelled");e.pending_orders=e.pending_orders.filter(r=>r.status==="pending")}}function dm(t){let e=t.strategy,n=Math.sign(e?.position_size??0);if(n===0)return!1;let r=y.from(t.data.open).get(0),i=y.from(t.data.high).get(0),s=y.from(t.data.low).get(0),a=Math.abs(i-r)<=Math.abs(r-s);return n===1?!a:a}function ci(t,e="extreme"){let n=t.strategy;if(!n||n.opentrades.length===0)return;let r=Math.sign(n.position_size);if(r===0)return;let i=r===1?n.config.margin_long??100:n.config.margin_short??100,s=y.from(t.data.open).get(0),a=y.from(t.data.high).get(0),o=y.from(t.data.low).get(0),l=y.from(t.data.close).get(0),c=y.from(t.data.openTime).get(0),u=t.pine?.syminfo?.pointvalue??1,h=e==="open"?s:e==="close"?l:r===1?o:a,p=Math.abs(n.position_size),d=nm(t,h),f=xr(p,h,i,u);if(d<f){let m=f-d,x=i/100,b=m/(h*u*x),w=Math.min(p,4*b),E=[...n.opentrades],v=E[0],I=Math.abs(v.size),C=v.entry_price;if(Zt(t,w,h,c,{exitId:"Margin call",exitComment:"Margin call"}),e==="extreme"&&w>=I-1e-9&&Math.abs(n.position_size)>1e-9){let O=xr(I,h,i,u),N=I*(h-C)*r*u,j=m-O+N;if(j>0){let D=y.from(t.data.close).get(0),W=(P=>Math.trunc(P*1e6)/1e6)(j/(h*u*x)),R=Math.min(Math.abs(n.position_size),4*W);R>1e-9&&(n._pending_close_mc={qty:R,price:D,time:c,dir:r})}}let T=E.find(O=>O.status==="open");n._mc_exit_lock={bar:t.idx,tradeId:T?.id??null}}}function fm(t){if(!t.strategy)return;let e=t.strategy,n=y.from(t.data.high).get(0),r=y.from(t.data.low).get(0),i=y.from(t.data.close).get(0);br(t,i),um(t,n,r);let s=y.from(t.data.openTime).get(0);if(Number.isFinite(s)){let a=new Date(s),o=a.getUTCFullYear()*12+a.getUTCMonth(),l=e._monthly_equity??(e._monthly_equity=[]);e._last_month_key===o&&l.length>0?l[l.length-1]=e.equity:(l.push(e.equity),e._last_month_key=o)}}function mm(t){let e=t?.strategy;if(!e)return;e.cagr=gm(t),_m(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 ym=1440*60*1e3;function gm(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)/ym;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 _m(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 xm(t){t.strategy}function bm(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,...e,...t._propOverrides??{}},r=n.initial_capital;t.strategy={config:n,opentrades:[],closedtrades:[],pending_orders:[],position_size:0,position_avg_price:NaN,position_entry_name:"",initial_capital:r,account_currency:n.currency||"USD",equity:r,netprofit:0,grossprofit:0,grossloss:0,openprofit:0,max_drawdown:0,max_runup:0,equity_peak:r,equity_trough:r,equity_at_runup_peak:r,equity_at_drawdown_peak:r,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,_exit_call_history:new Map,_exit_fallback_counter:0,_exit_fallback_last_bar:-1}}function An(t){if(Array.isArray(t))return t.map(An);if(t instanceof Map){let e=new Map;return t.forEach((n,r)=>e.set(r,An(n))),e}if(t!==null&&typeof t=="object"){let e={};for(let n of Object.keys(t))e[n]=An(t[n]);return e}return t}function wm(t){if(!t)return null;let e={};for(let n of Object.keys(t))n==="config"||n==="closedtrades"||(e[n]=An(t[n]));return{fields:e,closedtradesLength:t.closedtrades.length}}function vm(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]=An(e.fields[n])}}function Em(t){return(...e)=>{let n=tm(e);return t.strategy?t.strategy.config={...t.strategy.config,...n,...t._propOverrides??{}}:bm(t,n),t.strategy.config}}var Sm=[["id","direction","qty","limit","stop","oca_name","oca_type","comment","alert_message","disable_alert"]],Cm={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 Nm(t){return(...e)=>{if(!t.strategy)throw new Error("strategy.order() called before strategy() declaration");let n=ce(e,Sm,Cm),r=w=>w==null||typeof w=="string"||typeof w=="number"||typeof w=="boolean"?w:typeof w=="function"?w():w instanceof y?w.get(0):Array.isArray(w)?w[w.length-1]:typeof w=="object"&&w.get!==void 0?w.get(0):w,i=r(n.id),s=r(n.direction),a=r(n.qty),o=r(n.limit),l=r(n.stop),c=r(n.oca_name),u=r(n.oca_type),h=r(n.comment),p=Vt(s),d=y.from(t.data.close).get(0),f=ws(t,a,p,d),m="market";o!==void 0&&l!==void 0?m="stop-limit":o!==void 0?m="limit":l!==void 0&&(m="stop");let x=y.from(t.data.openTime).get(0),b={id:i,direction:p,qty:f,type:m,limit:o,stop:l,bar:t.idx,time:x,status:"pending",oca_name:c,oca_type:u,comment:h};return t.strategy.pending_orders.push(b),b}}function km(t){return(e,n)=>y.from(e).get(n||0)}function Im(t){return()=>{let e=(t.strategy?.opentrades??[]).slice(),n=p=>e[Number(p)],r=()=>{let p=t.marketData;return Array.isArray(p)&&t.idx>=0&&t.idx<p.length?p[t.idx]?.close??NaN:NaN},i={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",x=f?.commission_value??0;if(!x)return 0;let b=Math.abs(p.size);switch(m){case"percent":return b*d*s*(x/100);case"cash_per_contract":return b*x;case"cash_per_order":return x;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 NaN;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 NaN;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??NaN,i.commission=p=>n(p)?.commission??NaN,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=c!==100||u!==100;if(!l||l.opentrades.length===0||!h)i.capital_held=NaN;else{let p=0;for(let d of l.opentrades){let f=Math.abs(d.size)*d.entry_price,m=d.size>0?c:u;p+=f*(m/100)}i.capital_held=p}return i}}function Am(t){return()=>{let e=(t.strategy?.closedtrades??[]).slice(),n=a=>e[Number(a)],r={valueOf(){return e.length},toString(){return String(e.length)},[Symbol.toPrimitive](){return e.length}},i=t.pine?.syminfo?.pointvalue??1,s=a=>{let o=Math.abs(a.size)*a.entry_price*i,l=(a.commission??0)/2;return o+l};return r.profit=a=>n(a)?.profit??NaN,r.profit_percent=a=>{let o=n(a);if(!o||o.profit===void 0)return NaN;let l=s(o);return l>0?100*o.profit/l:NaN},r.size=a=>n(a)?.size??NaN,r.commission=a=>n(a)?.commission??NaN,r.entry_price=a=>n(a)?.entry_price??NaN,r.entry_bar_index=a=>n(a)?.entry_bar_index??NaN,r.entry_id=a=>n(a)?.entry_id??"",r.entry_comment=a=>n(a)?.entry_comment??n(a)?.entry_id??"",r.entry_time=a=>n(a)?.entry_time??NaN,r.exit_price=a=>n(a)?.exit_price??NaN,r.exit_bar_index=a=>n(a)?.exit_bar_index??NaN,r.exit_id=a=>n(a)?.exit_id??"",r.exit_comment=a=>n(a)?.exit_comment??n(a)?.exit_id??"",r.exit_time=a=>n(a)?.exit_time??NaN,r.max_drawdown=a=>n(a)?.max_drawdown??0,r.max_drawdown_percent=a=>{let o=n(a);if(!o||!o.max_drawdown)return 0;let l=s(o);return l>0?100*o.max_drawdown/l:0},r.max_runup=a=>n(a)?.max_runup??0,r.max_runup_percent=a=>{let o=n(a);if(!o||!o.max_runup)return 0;let l=s(o);return l>0?100*o.max_runup/l:0},r.first_index=0,r}}function Tm(t){return()=>t.strategy?.netprofit??0}function Dm(t){return()=>t.strategy?.position_size??0}function Mm(t){return()=>{let e=t.strategy;return!e||e.position_size===0?NaN:e.position_avg_price}}function Pm(t){return()=>t.strategy?.equity??t.strategy?.config?.initial_capital??1e4}function Rm(t){return()=>"long"}function Fm(t){return()=>"short"}function Bm(t){return()=>"cash"}function Lm(t){return()=>"percent_of_equity"}function Om(t){return()=>"fixed"}function Vm(t){return()=>t.strategy?.openprofit??0}function jm(t){return()=>{let e=t.strategy;return!e||!e.initial_capital?0:100*e.openprofit/e.initial_capital}}function $m(t){return()=>{let e=t.strategy;return!e||!e.initial_capital?0:100*e.netprofit/e.initial_capital}}function Wm(t){return()=>t.strategy?.grossprofit??0}function Um(t){return()=>{let e=t.strategy;return!e||!e.initial_capital?0:100*e.grossprofit/e.initial_capital}}function qm(t){return()=>t.strategy?.grossloss??0}function zm(t){return()=>{let e=t.strategy;return!e||!e.initial_capital?0:100*e.grossloss/e.initial_capital}}function Km(t){return()=>t.strategy?.wintrades??0}function Hm(t){return()=>t.strategy?.losstrades??0}function Gm(t){return()=>t.strategy?.eventrades??0}function Ym(t){return()=>{let e=t.strategy;return!e||!e.closedtrades||e.closedtrades.length===0?NaN:e.netprofit/e.closedtrades.length}}function Zm(t){return()=>{let e=t.strategy;if(!e||!e.closedtrades||e.closedtrades.length===0)return NaN;let n=0;for(let r of e.closedtrades){let i=Math.abs(r.size)*r.entry_price;i>0&&(n+=100*(r.profit??0)/i)}return n/e.closedtrades.length}}function Xm(t){return()=>{let e=t.strategy;return!e||e.wintrades===0?NaN:e.wintrades_total_profit/e.wintrades}}function Qm(t){return()=>{let e=t.strategy;if(!e||e.wintrades===0)return NaN;let n=0;for(let r of e.closedtrades)if((r.profit??0)>0){let i=Math.abs(r.size)*r.entry_price;i>0&&(n+=100*(r.profit??0)/i)}return n/e.wintrades}}function Jm(t){return()=>{let e=t.strategy;return!e||e.losstrades===0?NaN:e.losstrades_total_loss/e.losstrades}}function ey(t){return()=>{let e=t.strategy;if(!e||e.losstrades===0)return NaN;let n=0;for(let r of e.closedtrades)if((r.profit??0)<0){let i=Math.abs(r.size)*r.entry_price;i>0&&(n+=100*(r.profit??0)/i)}return n/e.losstrades}}function ty(t){return()=>t.strategy?.max_drawdown??0}function ny(t){return()=>{let e=t.strategy;return e?e.max_drawdown_percent_value??0:0}}function ry(t){return()=>t.strategy?.max_runup??0}function iy(t){return()=>{let e=t.strategy;return e?e.max_runup_percent_value??0:0}}function sy(t){return()=>t.strategy?.max_contracts_held_all??0}function ay(t){return()=>t.strategy?.max_contracts_held_long??0}function oy(t){return()=>t.strategy?.max_contracts_held_short??0}function ly(t){return()=>t.strategy?.position_entry_name??""}function cy(t){return()=>t.strategy?.initial_capital??0}function uy(t){return()=>t.strategy?.account_currency??"USD"}function py(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>=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;return r===1?Math.floor(c/u)*u:Math.ceil(c/u)*u}}var hy=[["id","direction","qty","limit","stop","oca_name","oca_type","comment","alert_message","disable_alert"]],dy={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 fy(t){return(...e)=>{if(!t.strategy)throw new Error("strategy.entry() called before strategy() declaration");let n=ce(e,hy,dy),r=N=>N==null||typeof N=="string"||typeof N=="number"||typeof N=="boolean"?N:typeof N=="function"?N():N instanceof y?N.get(0):Array.isArray(N)?N[N.length-1]:typeof N=="object"&&N.get!==void 0?N.get(0):N,i=r(n.id),s=r(n.direction),a=r(n.qty),o=r(n.limit),l=r(n.stop),c=r(n.oca_name),u=r(n.oca_type),h=r(n.comment),p=Vt(s),d=t.strategy,f=d.position_size;for(let N of d.pending_orders)N.bar===t.idx&&N.category==="entry"&&N.type==="market"&&(f+=Vt(N.direction)*N.qty);if(Math.sign(f)===p&&f!==0&&sm(d,p))return;let m=y.from(t.data.close).get(0),x=ws(t,a,p,m),b=f!==0&&Math.sign(f)!==p,w=b?Math.abs(f)+x:x,E="market";o!==void 0&&l!==void 0?E="stop-limit":o!==void 0?E="limit":l!==void 0&&(E="stop");let v=t.pine?.syminfo?.mintick??0,I=o!==void 0?In(o,m,v):void 0,C=l!==void 0?In(l,m,v):void 0,T=y.from(t.data.openTime).get(0),O={id:i,direction:p,qty:w,type:E,limit:I,stop:C,bar:t.idx,time:T,status:"pending",category:"entry",oca_name:c,oca_type:u,comment:h,_isReversalEntry:b,_base_qty:x};d.pending_orders.push(O)}}var my=[["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"]],yy={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 gy(t){return(...e)=>{if(!t.strategy)throw new Error("strategy.exit() called before strategy() declaration");let n=ht(e);if(n===void 0){let R=t.strategy;R._exit_fallback_last_bar!==t.idx&&(R._exit_fallback_counter=0,R._exit_fallback_last_bar=t.idx),n=`exit_raw_${R._exit_fallback_counter++}`}let r=ce(e,my,yy),i=R=>R==null||typeof R=="string"||typeof R=="number"||typeof R=="boolean"?R:typeof R=="function"?R():R instanceof y?R.get(0):Array.isArray(R)?R[R.length-1]:typeof R=="object"&&R.get!==void 0?R.get(0):R,s=i(r.id),a=i(r.from_entry),o=i(r.qty),l=i(r.qty_percent),c=i(r.profit),u=i(r.limit),h=i(r.loss),p=i(r.stop),d=i(r.trail_price),f=i(r.trail_points),m=i(r.trail_offset),x=t.pine?.syminfo?.mintick??0,b=y.from(t.data.close).get(0),w=u!==void 0?In(u,b,x):void 0,E=p!==void 0?In(p,b,x):void 0,v=d!==void 0?In(d,b,x):void 0,I=a??"",C=!!(I?t.strategy.pending_orders.find(R=>R.category==="entry"&&R.id===I&&R.status==="pending"):t.strategy.pending_orders.find(R=>R.category==="entry"&&R.status==="pending"))?._isReversalEntry,T=t.strategy._exit_call_history,O=T.get(n),N=O!==void 0&&O===t.idx-1;T.set(n,t.idx);let j={id:s??"exit",direction:0,qty:o!==void 0?Math.abs(Number(o)):0,qty_percent:l,type:"market",bar:t.idx,time:y.from(t.data.openTime).get(0),status:"pending",category:"exit",from_entry:I,profit:c,loss:h,limit:w,stop:E,trail_price:v,trail_points:f,trail_offset:m,oca_name:i(r.oca_name),comment:i(r.comment),comment_profit:i(r.comment_profit),comment_loss:i(r.comment_loss),comment_trailing:i(r.comment_trailing),alert_message:i(r.alert_message),alert_profit:i(r.alert_profit),alert_loss:i(r.alert_loss),alert_trailing:i(r.alert_trailing),disable_alert:i(r.disable_alert),trail_armed:!1,trail_peak:NaN,_attachedAtReversal:C,_isPersistent:N,_callsiteId:n},D=j.id,W=t.strategy.pending_orders;for(let R=W.length-1;R>=0;R--){let P=W[R];P.category==="exit"&&P.id===D&&(P.from_entry??"")===(j.from_entry??"")&&P.status==="pending"&&(P.trail_armed&&(j.trail_armed=!0,j.trail_peak=P.trail_peak),W.splice(R,1))}W.push(j)}}var _y=[["id","comment","qty","qty_percent","alert_message","immediately","disable_alert"]],xy={id:"string",comment:"string",qty:"series",qty_percent:"series",alert_message:"string",immediately:"boolean",disable_alert:"boolean"};function by(t){return(...e)=>{if(!t.strategy)throw new Error("strategy.close() called before strategy() declaration");let n=ce(e,_y,xy),r=n.id;if(r==null||!t.strategy.opentrades.some(o=>o.entry_id===r))return;let i=o=>(o.category??"entry")==="exit"&&(o.profit!==void 0||o.loss!==void 0||o.limit!==void 0||o.stop!==void 0||o.trail_price!==void 0||o.trail_points!==void 0),s=t.strategy.pending_orders;for(let o of s)i(o)&&(o.from_entry??"")===r&&o.status==="pending"&&(o.status="cancelled");t.strategy.pending_orders=s.filter(o=>o.status==="pending");let a={id:`close_${r}`,direction:0,qty:0,type:"market",bar:t.idx,time:y.from(t.data.openTime).get(0),status:"pending",category:"exit",from_entry:r,qty_percent:n.qty_percent,comment:n.comment,alert_message:n.alert_message,immediately:n.immediately===!0,disable_alert:n.disable_alert,_intended_trade_ids:t.strategy.opentrades.filter(o=>o.entry_id===r).map(o=>o.id)};n.qty!==void 0&&(a.qty=Math.abs(Number(n.qty))),t.strategy.pending_orders.push(a)}}var wy=[["comment","alert_message","immediately","disable_alert"]],vy={comment:"string",alert_message:"string",immediately:"boolean",disable_alert:"boolean"};function Ey(t){return(...e)=>{if(!t.strategy)throw new Error("strategy.close_all() called before strategy() declaration");let n=ce(e,wy,vy);if(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_all",direction:0,qty:0,type:"market",bar:t.idx,time:y.from(t.data.openTime).get(0),status:"pending",category:"exit",from_entry:"",comment:n.comment,alert_message:n.alert_message,immediately:n.immediately===!0,disable_alert:n.disable_alert,_intended_trade_ids:t.strategy.opentrades.map(a=>a.id)};t.strategy.pending_orders.push(s)}}var Sy=[["id","immediately"]],Cy={id:"string",immediately:"boolean"};function Ny(t){return(...e)=>{if(!t.strategy)throw new Error("strategy.cancel() called before strategy() declaration");let n=ce(e,Sy,Cy).id;n!=null&&(t.strategy.pending_orders=t.strategy.pending_orders.filter(r=>!(r.status==="pending"&&r.id===n)))}}function ky(t){return()=>{if(!t.strategy)throw new Error("strategy.cancel_all() called before strategy() declaration");t.strategy.pending_orders=t.strategy.pending_orders.filter(e=>!(e.status==="pending"&&(e.category??"entry")==="entry"))}}function Iy(t){return{allow_entry_in:e=>{t.strategy&&(t.strategy.risk_rules.allow_entry_in=e)},max_cons_loss_days:(e,n)=>{t.strategy&&(t.strategy.risk_rules.max_cons_loss_days={count:e,alert_message:n})},max_drawdown:(e,n,r)=>{t.strategy&&(t.strategy.risk_rules.max_drawdown={value:e,type:n})},max_intraday_filled_orders:(e,n)=>{t.strategy&&(t.strategy.risk_rules.max_intraday_filled_orders={count:e,alert_message:n})},max_intraday_loss:(e,n,r)=>{t.strategy&&(t.strategy.risk_rules.max_intraday_loss={value:e,type:n})},max_position_size:e=>{t.strategy&&(t.strategy.risk_rules.max_position_size=e)}}}function Ay(t){return e=>{let n=t.strategy,r=t.pine?.syminfo?.currency,i=n?.account_currency??"USD";return r&&r!==i?NaN:e}}function Ty(t){return e=>{let n=t.strategy,r=t.pine?.syminfo?.currency,i=n?.account_currency??"USD";return r&&r!==i?NaN:e}}function Dy(t){return e=>t.strategy?ws(t,void 0,1,e):0}var My={any:Em,order:Nm,param:km,opentrades:Im,closedtrades:Am,netprofit:Tm,position_size:Dm,position_avg_price:Mm,equity:Pm,long:Rm,short:Fm,cash:Bm,percent_of_equity:Lm,fixed:Om,openprofit:Vm,openprofit_percent:jm,netprofit_percent:$m,grossprofit:Wm,grossprofit_percent:Um,grossloss:qm,grossloss_percent:zm,wintrades:Km,losstrades:Hm,eventrades:Gm,avg_trade:Ym,avg_trade_percent:Zm,avg_winning_trade:Xm,avg_winning_trade_percent:Qm,avg_losing_trade:Jm,avg_losing_trade_percent:ey,max_drawdown:ty,max_drawdown_percent:ny,max_runup:ry,max_runup_percent:iy,max_contracts_held_all:sy,max_contracts_held_long:ay,max_contracts_held_short:oy,position_entry_name:ly,initial_capital:cy,account_currency:uy,margin_liquidation_price:py,entry:fy,exit:gy,close:by,close_all:Ey,cancel:Ny,cancel_all:ky,convert_to_account:Ay,convert_to_symbol:Ty,default_entry_qty:Dy},Py={long:"long",short:"short",all:"all"},Ry={none:"none",cancel:"cancel",reduce:"reduce"},Fy={percent:"percent",cash_per_order:"cash_per_order",cash_per_contract:"cash_per_contract"},Fi=class{constructor(e){this.context=e,Object.entries(My).forEach(([r,i])=>{this[r]=i(e)}),this.direction=()=>Py,this.oca=()=>Ry,this.commission=()=>Fy;let n=Iy(e);this.risk=()=>n}};function By(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=jt(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 Ly(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 Bi=class{constructor(e){this.context=e}logFormat(e,...n){return e.replace(/{(\\d+)}/g,(r,i)=>n[i])}param(e,n=0,r){return y.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=By(e,n);return Ly(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)}`)}},Li=class{constructor(e){this.context=e}param(e,n=0,r){return y.from(e).get(n)}error(e){let n=y.from(e).get(0);throw new dr(typeof n=="string"?n:String(n??""),"runtime.error")}},Oy=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Vy=["January","February","March","April","May","June","July","August","September","October","November","December"],jy=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],$y=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],He=(t,e)=>String(t).padStart(e,"0"),Oi=class{constructor(e){this.context=e}param(e,n=0,r){return y.from(e).get(n)}tostring(e,n){if(typeof e!="number"||isNaN(e)||!n)return String(e);if(n==="mintick"){let i=this.context.pine?.syminfo?.mintick||.01,s=Math.max(0,-Math.floor(Math.log10(i)));return e.toFixed(s)}if(n==="integer")return String(Math.round(e));if(n==="percent")return(e*100).toFixed(2)+"%";if(n==="price"){let i=this.context.pine?.syminfo?.mintick||.01,s=Math.max(0,-Math.floor(Math.log10(i)));return e.toFixed(s)}if(n==="volume")return String(Math.round(e));let r=n.indexOf(".");if(r>=0){let i=n.substring(r+1).length;return e.toFixed(i)}return n.includes("#")||n.includes("0")?String(Math.round(e)):String(e)}tonumber(e){return Number(e)}lower(e){return String(e).toLowerCase()}upper(e){return String(e).toUpperCase()}trim(e){return String(e).trim()}repeat(e,n,r=""){return Array(n).fill(e).join(r||"")}replace_all(e,n,r){return String(e).replaceAll(n,r)}replace(e,n,r,i=0){let s=String(e),a=String(n),o=String(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 String(e).includes(n)}endswith(e,n){return String(e).endsWith(n)}startswith(e,n){return String(e).startsWith(n)}pos(e,n){let r=String(e).indexOf(n);return r===-1?NaN:r}length(e){return String(e).length}match(e,n){return String(e).match(new RegExp(n))}split(e,n){return new q(String(e).split(n),z.string,this.context)}substring(e,n,r){return String(e).substring(n,r)}format_time(e,n="yyyy-MM-dd\'T\'HH:mm:ssZ",r){if(e==null||typeof e=="number"&&isNaN(e))return"NaN";let i=Number(e),s=r||this.context.pine?.syminfo?.timezone||"UTC",a=jt(i,s),o=Date.UTC(a.year,a.month-1,a.day,a.hour,a.minute,a.second),l=Math.round((o-i)/6e4),c=Date.UTC(a.year,0,1),u=Math.floor((o-c)/864e5)+1,h=a.hour%12===0?12:a.hour%12,p="",d=0;for(;d<n.length;){let f=n[d];if(f==="\'"){if(n[d+1]==="\'"){p+="\'",d+=2;continue}let m=n.indexOf("\'",d+1);if(m===-1){p+=n.substring(d+1);break}p+=n.substring(d+1,m),d=m+1;continue}if(f>="a"&&f<="z"||f>="A"&&f<="Z"){let m=1;for(;n[d+m]===f;)m++;switch(d+=m,f){case"y":p+=m===2?He(a.year%100,2):m>=4?He(a.year,4):String(a.year);break;case"M":m>=4?p+=Vy[a.month-1]:m===3?p+=Oy[a.month-1]:m===2?p+=He(a.month,2):p+=String(a.month);break;case"d":p+=m===2?He(a.day,2):String(a.day);break;case"D":p+=m>=3?He(u,3):m===2?He(u,2):String(u);break;case"E":p+=m>=4?$y[a.dayOfWeek]:jy[a.dayOfWeek];break;case"a":p+=a.hour<12?"AM":"PM";break;case"h":p+=m===2?He(h,2):String(h);break;case"H":p+=m===2?He(a.hour,2):String(a.hour);break;case"m":p+=m===2?He(a.minute,2):String(a.minute);break;case"s":p+=m===2?He(a.second,2):String(a.second);break;case"S":{let x=i-Math.floor(i/1e3)*1e3;p+=He(x,3).substring(0,m);break}case"Z":{let x=l>=0?"+":"-",b=Math.abs(l);p+=`${x}${He(Math.floor(b/60),2)}${He(b%60,2)}`;break}default:p+=f.repeat(m)}continue}p+=f,d++}return p}format(e,...n){return e.replace(/\\{(\\d+)(?:,number,([^}]+))?\\}/g,(r,i,s)=>{let a=n[i];return s&&typeof a=="number"&&!isNaN(a)?this.tostring(a,s):String(a)})}},Wy=Object.defineProperty,Uy=(t,e,n)=>e in t?Wy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,qy=(t,e,n)=>Uy(t,typeof e!="symbol"?e+"":e,n),Jn={"1m":"1","3m":"3","5m":"5","15m":"15","30m":"30","45m":"45","1h":"60","2h":"120","3h":"180","4h":"240","1d":"D","1w":"W","1M":"M"};function da(t){if(!t||/^\\d+$/.test(t))return t;if(Jn[t])return Jn[t];let e=t.toLowerCase();if(Jn[e])return Jn[e];if(t.length===1){let r=t.toUpperCase();if(["D","W","M","S"].includes(r))return r}let n=t.slice(-1).toUpperCase();if(["D","W","M","S"].includes(n)){let r=parseInt(t);if(!isNaN(r))return r+n}return t}var Vi=class{constructor(e){this.context=e,qy(this,"_normalized",null)}param(e,n=0,r){return y.from(e).get(n)}get normalized(){return this._normalized===null&&(this._normalized=da(this.context.timeframe)),this._normalized}get unit(){return this.normalized.slice(-1).toUpperCase()}get main_period(){return this.normalized}get period(){return this.normalized}get multiplier(){let e=parseInt(this.normalized);return isNaN(e)?1:e}get isdwm(){return["D","W","M"].includes(this.unit)}get isdaily(){return this.unit==="D"}get isweekly(){return this.unit==="W"}get ismonthly(){return this.unit==="M"}get isseconds(){return this.unit==="S"}get isminutes(){return/^\\d+$/.test(this.normalized)}get isintraday(){return!this.isdwm}change(e){let n=typeof e=="function"?e():e,r=n instanceof y?n.get(0):n,i=vi(r||"");if(!i)return!1;let s=y.from(this.context.data.openTime).get(0),a=y.from(this.context.data.openTime).get(1);if(isNaN(s)||isNaN(a))return!1;let o=Ei(s,i),l=Ei(a,i);return o!==l}from_seconds(e){return e<60?Math.ceil(e/5)*5+"S":e<3600*24?Math.ceil(e/60):e<=3600*24*7*52?e%(3600*24*7)===0?Math.ceil(e/604800)+"W":Math.ceil(e/(3600*24))+"D":"12M"}in_seconds(e){e==null?e=this.normalized:e=da(e);let n=e.slice(-1).toUpperCase(),r=parseInt(e);return n==="S"?isNaN(r)?1:r:n==="D"?(isNaN(r)?1:r)*60*60*24:n==="W"?(isNaN(r)?1:r)*60*60*24*7:n==="M"?(isNaN(r)?1:r)*60*60*24*30:isNaN(r)?0:r*60}},zy=Object.defineProperty,Ky=Object.getOwnPropertyDescriptor,bt=(t,e,n,r)=>{for(var i=r>1?void 0:r?Ky(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&&zy(e,n,i),i},Hy=["series","title","color","linewidth","style","trackprice","histbase","offset","join","editable","show_last","display","format","precision","force_overlay"],Gy=["series","title","char","location","color","offset","text","textcolor","editable","size","show_last","display","format","precision","force_overlay"],Yy={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"},Zy=["series","title","style","location","color","offset","text","textcolor","editable","size","show_last","display","format","precision","force_overlay"],Xy=["series","title","colorup","colordown","offset","minheight","maxheight","editable","show_last","display","format","precision","force_overlay"],Qy=["open","high","low","close","title","color","editable","show_last","display","format","precision","force_overlay"],Jy=["open","high","low","close","title","color","wickcolor","editable","show_last","bordercolor","display","format","precision","force_overlay"],fa=["color","offset","editable","show_last","title","display","force_overlay"],eg=["price","title","color","linestyle","linewidth","editable","display"],tg=["plot1","plot2","color","title","editable","show_last","fillgaps","display"],ng={series:"series",title:"string",color:"color",linewidth:"number",style:"string",trackprice:"boolean",histbase:"number",offset:"number",join:"bool",editable:"boolean",show_last:"number",display:"string",format:"string",precision:"number",force_overlay:"boolean"},rg={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"},ig={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"},sg={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"},ag={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"},ma={color:"color",offset:"number",editable:"boolean",show_last:"number",title:"string",display:"string",force_overlay:"boolean"},og={price:"series",title:"string",color:"color",linestyle:"string",linewidth:"number",editable:"boolean",display:"string"},lg={plot1:"object",plot2:"object",color:"color",title:"string",editable:"boolean",show_last:"number",fillgaps:"boolean",display:"string"},dt=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]=y.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 y.from(e).get(n)}plotchar(...e){let n=ht(e),r=ce(e,Gy,Yy),{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=y.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=ht(e),r=ce(e,Hy,ng),{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=y.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=ht(e),r=ce(e,Zy,rg),{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=y.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=ht(e),r=ce(e,Xy,ig),{series:i,title:s,...a}=r,o=y.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=ht(e),r=ce(e,Qy,sg),{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=[y.from(i).get(0),y.from(s).get(0),y.from(a).get(0),y.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=ht(e),r=ce(e,Jy,ag),{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=[y.from(i).get(0),y.from(s).get(0),y.from(a).get(0),y.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=ht(e),r=ce(e,fa,ma),{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=ht(e),r=ce(e,fa,ma),{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]}};bt([k],dt.prototype,"plotchar",1),bt([k],dt.prototype,"any",1),bt([k],dt.prototype,"plotshape",1),bt([k],dt.prototype,"plotarrow",1),bt([k],dt.prototype,"plotbar",1),bt([k],dt.prototype,"plotcandle",1),bt([k],dt.prototype,"bgcolor",1),bt([k],dt.prototype,"barcolor",1);var wr=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 y.from(e).get(n)}any(...e){let n=ht(e),r=ce(e,eg,og),{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)}};bt([k],wr.prototype,"any",1);var vr=class{constructor(e){this.context=e}param(e,n=0,r){return y.from(e).get(n)}any(...e){let n=ht(e),r=e.length>=6&&typeof e[2]=="number",i=!r&&e.length>=3&&e[2]!==null&&typeof e[2]=="object"&&"top_value"in e[2]?e[2]:null;if(r||i!==null){let s=e[0],a=e[1],o=i?y.from(i.top_value).get(0):e[2],l=i?y.from(i.bottom_value).get(0):e[3],c=i?y.from(i.top_color).get(0):e[4],u=i?y.from(i.bottom_color).get(0):e[5],h=i?i.title||void 0:e.length>6&&typeof e[6]=="string"?e[6]:void 0,p=s?._plotKey||s?.title,d=a?._plotKey||a?.title,f=h||"fill",m=this.context.plots[f];m&&n&&m._callsiteId!==n&&(f=n),this.context.plots[f]||(this.context.plots[f]={title:h||"Fill",plot1:p,plot2:d,data:[],options:{plot1:p,plot2:d,style:"fill",gradient:!0},_plotKey:f,_callsiteId:n}),this.context.plots[f].data.push({time:this.context.marketData[this.context.idx].openTime,value:null,options:{top_value:o,bottom_value:l,top_color:c,bottom_color:u}})}else{let s=ce(e,tg,lg),{plot1:a,plot2:o,color:l,title:c,editable:u,show_last:h,fillgaps:p,display:d}=s,f=c||"fill",m=this.context.plots[f];m&&n&&m._callsiteId!==n&&(f=n);let x=y.from(l).get(0);if(!this.context.plots[f]){let b=a?._plotKey||a?.title,w=o?._plotKey||o?.title;this.context.plots[f]={title:c||"Fill",plot1:b,plot2:w,data:[],options:{plot1:b,plot2:w,color:x,editable:u,show_last:h,fillgaps:p,display:d,style:"fill"},_plotKey:f,_callsiteId:n}}this.context.plots[f].data.push({time:this.context.marketData[this.context.idx].openTime,value:null,options:{color:x}})}}};bt([k],vr.prototype,"any",1);var cg=Object.defineProperty,ug=(t,e,n)=>e in t?cg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,pg=(t,e,n)=>ug(t,typeof e!="symbol"?e+"":e,n),ji=class{constructor(e){this.context=e,pg(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 Oe(r(i),r(s),r(a)??NaN)},from_index(i,s){return new Oe(void 0,r(i),r(s))},from_time(i,s){return new Oe(r(i),void 0,r(s))},copy(i){return i.copy()},now(i){let s=n.idx,a=n.marketData[s]?.openTime;return new Oe(a,s,r(i))}}}param(e,n=0,r){return y.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}},hg=Object.defineProperty,dg=(t,e,n)=>e in t?hg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Te=(t,e,n)=>dg(t,typeof e!="symbol"?e+"":e,n),fg=0,Tn=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){Te(this,"id"),Te(this,"x"),Te(this,"y"),Te(this,"text"),Te(this,"xloc"),Te(this,"yloc"),Te(this,"color"),Te(this,"style"),Te(this,"textcolor"),Te(this,"size"),Te(this,"textalign"),Te(this,"tooltip"),Te(this,"text_font_family"),Te(this,"force_overlay"),Te(this,"_deleted"),Te(this,"_helper"),Te(this,"_createdAtBar",-1),this.id=fg++,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._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){this._helper?this._helper.set_xloc(this,e):this._deleted||(this.xloc=e)}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._deleted||(this.text_font_family=e)}get_x(){return this.x}get_y(){return this.y}get_text(){return this.text}delete(){this._deleted=!0}copy(){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)}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,_deleted:this._deleted}}},yo=Object.defineProperty,mg=Object.getOwnPropertyDescriptor,yg=(t,e,n)=>e in t?yo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Me=(t,e,n,r)=>{for(var i=r>1?void 0:r?mg(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&&yo(e,n,i),i},gg=(t,e,n)=>yg(t,typeof e!="symbol"?e+"":e,n),_g=[["x","y","text","xloc","yloc","color","style","textcolor","size","textalign","tooltip","text_font_family","force_overlay"],["point","text","xloc","yloc","color","style","textcolor","size","textalign","tooltip","text_font_family","force_overlay"]],xg={x:"number",y:"number",text:"string",xloc:"string",yloc:"string",color:"color",style:"string",textcolor:"color",size:"string",textalign:"string",tooltip:"string",text_font_family:"string",force_overlay:"boolean",point:"point"},Ee=class{constructor(e){this.context=e,gg(this,"_labels",[])}param(e,n=0,r){return y.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 Ze)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){let f=new Tn(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);return f._helper=this,f._createdAtBar=this.context.idx,this._labels.push(f),this._enforceMaxCount(),f}_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=ce(e,_g,xg),r,i,s=n.xloc;if(n.point instanceof Oe){let a=n.point,o=a.index!==void 0&&!(typeof a.index=="number"&&isNaN(a.index)),l=a.time!==void 0&&!(typeof a.time=="number"&&isNaN(a.time));o?(r=a.index,s=s||"bi"):l?(r=a.time,s=s||"bt"):(r=0,s=s||"bi"),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)}any(...e){if(e.length===1){let n=e[0];if(n==null||n instanceof Ze||typeof n=="number"&&isNaN(n))return null;if(n instanceof Tn)return n;if(n instanceof y){let r=n.get(0);if(r==null||typeof r=="number"&&isNaN(r))return null;if(r instanceof Tn)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_xloc(e,n){e&&!e._deleted&&(e.xloc=n)}set_yloc(e,n){e&&!e._deleted&&(e.yloc=n)}set_point(e,n){if(e&&!e._deleted&&n){let r=n.index!==void 0&&!(typeof n.index=="number"&&isNaN(n.index)),i=n.time!==void 0&&!(typeof n.time=="number"&&isNaN(n.time));r?(e.x=n.index,e.xloc="bi"):i&&(e.x=n.time,e.xloc="bt"),e.y=n.price}}get_x(e){return e?e.x:NaN}get_y(e){return e?e.y:NaN}get_text(e){return e?e.text:""}copy(e){if(!e)return;let n=e.copy();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"}};Me([k],Ee.prototype,"new",1),Me([k],Ee.prototype,"set_x",1),Me([k],Ee.prototype,"set_y",1),Me([k],Ee.prototype,"set_xy",1),Me([k],Ee.prototype,"set_text",1),Me([k],Ee.prototype,"set_color",1),Me([k],Ee.prototype,"set_textcolor",1),Me([k],Ee.prototype,"set_size",1),Me([k],Ee.prototype,"set_style",1),Me([k],Ee.prototype,"set_textalign",1),Me([k],Ee.prototype,"set_tooltip",1),Me([k],Ee.prototype,"set_xloc",1),Me([k],Ee.prototype,"set_yloc",1),Me([k],Ee.prototype,"set_point",1),Me([k],Ee.prototype,"copy",1),Me([k],Ee.prototype,"delete",1);var bg=Object.defineProperty,wg=(t,e,n)=>e in t?bg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,$e=(t,e,n)=>wg(t,typeof e!="symbol"?e+"":e,n),vg=0,Dn=class t{constructor(e,n,r,i,s="bi",a="none",o="",l="style_solid",c=1,u=!1){$e(this,"id"),$e(this,"x1"),$e(this,"y1"),$e(this,"x2"),$e(this,"y2"),$e(this,"xloc"),$e(this,"extend"),$e(this,"color"),$e(this,"style"),$e(this,"width"),$e(this,"force_overlay"),$e(this,"_deleted"),$e(this,"_helper"),$e(this,"_createdAtBar",-1),this.id=vg++,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.x1}get_y1(){return this.y1}get_x2(){return this.x2}get_y2(){return this.y2}get_price(e){return this._helper?this._helper.get_price(this,e):NaN}delete(){this._deleted=!0}copy(){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}}},go=Object.defineProperty,Eg=Object.getOwnPropertyDescriptor,Sg=(t,e,n)=>e in t?go(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Pe=(t,e,n,r)=>{for(var i=r>1?void 0:r?Eg(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&&go(e,n,i),i},Cg=(t,e,n)=>Sg(t,typeof e!="symbol"?e+"":e,n),Ng=[["x1","y1","x2","y2","xloc","extend","color","style","width","force_overlay"],["first_point","second_point","xloc","extend","color","style","width","force_overlay"]],kg={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"},Se=class{constructor(e){this.context=e,Cg(this,"_lines",[])}param(e,n=0,r){return y.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){let n=e.index!==void 0&&!(typeof e.index=="number"&&isNaN(e.index)),r=e.time!==void 0&&!(typeof e.time=="number"&&isNaN(e.time));return n?{x:e.index,xloc:"bi"}:r?{x:e.time,xloc:"bt"}:{x:0,xloc:"bi"}}_resolve(e){return e==null?e:e instanceof Ze?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 Dn(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=ce(e,Ng,kg),r,i,s,a,o=n.xloc;if(n.first_point instanceof Oe){let l=n.first_point,c=n.second_point,u=this._resolvePoint(l);r=u.x,i=l.price,o=o||u.xloc,c instanceof Oe?(s=this._resolvePoint(c).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 Ze||typeof n=="number"&&isNaN(n))return null;if(n instanceof Dn)return n;if(n instanceof y){let r=n.get(0);if(r==null||typeof r=="number"&&isNaN(r))return null;if(r instanceof Dn)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){if(e&&!e._deleted&&n){let r=this._resolvePoint(n);e.x1=r.x,e.y1=n.price,e.xloc=r.xloc}}set_second_point(e,n){if(e&&!e._deleted&&n){let r=this._resolvePoint(n);e.x2=r.x,e.y2=n.price,e.xloc=r.xloc}}get_x1(e){return e?e.x1:NaN}get_y1(e){return e?e.y1:NaN}get_x2(e){return e?e.x2:NaN}get_y2(e){return e?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.copy();return n._helper=this,n._createdAtBar=this.context.idx,this._lines.push(n),this._enforceMaxCount(),n}delete(e){e&&(e._deleted=!0)}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"}};Pe([k],Se.prototype,"new",1),Pe([k],Se.prototype,"set_x1",1),Pe([k],Se.prototype,"set_y1",1),Pe([k],Se.prototype,"set_x2",1),Pe([k],Se.prototype,"set_y2",1),Pe([k],Se.prototype,"set_xy1",1),Pe([k],Se.prototype,"set_xy2",1),Pe([k],Se.prototype,"set_color",1),Pe([k],Se.prototype,"set_width",1),Pe([k],Se.prototype,"set_style",1),Pe([k],Se.prototype,"set_extend",1),Pe([k],Se.prototype,"set_xloc",1),Pe([k],Se.prototype,"set_first_point",1),Pe([k],Se.prototype,"set_second_point",1),Pe([k],Se.prototype,"copy",1),Pe([k],Se.prototype,"delete",1);var Ig=Object.defineProperty,Ag=(t,e,n)=>e in t?Ig(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,me=(t,e,n)=>Ag(t,typeof e!="symbol"?e+"":e,n),Tg=0,Mn=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",x="wrap_none",b="default",w="format_none",E=!1){me(this,"id"),me(this,"left"),me(this,"top"),me(this,"right"),me(this,"bottom"),me(this,"xloc"),me(this,"extend"),me(this,"border_color"),me(this,"border_style"),me(this,"border_width"),me(this,"bgcolor"),me(this,"text"),me(this,"text_color"),me(this,"text_size"),me(this,"text_halign"),me(this,"text_valign"),me(this,"text_wrap"),me(this,"text_font_family"),me(this,"text_formatting"),me(this,"force_overlay"),me(this,"_deleted"),me(this,"_helper"),me(this,"_createdAtBar",-1),this.id=Tg++,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=x,this.text_font_family=b,this.text_formatting=w,this.force_overlay=E,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.left}get_right(){return this.right}get_top(){return this.top}get_bottom(){return 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 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)}},_o=Object.defineProperty,Dg=Object.getOwnPropertyDescriptor,Mg=(t,e,n)=>e in t?_o(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ue=(t,e,n,r)=>{for(var i=r>1?void 0:r?Dg(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&&_o(e,n,i),i},Pg=(t,e,n)=>Mg(t,typeof e!="symbol"?e+"":e,n),Rg=[["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"]],Fg={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:"string",text_color:"color",text_halign:"string",text_valign:"string",text_wrap:"string",text_font_family:"string",force_overlay:"boolean"},le=class{constructor(e){this.context=e,Pg(this,"_boxes",[])}param(e,n=0,r){return y.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){let n=e.index!==void 0&&!(typeof e.index=="number"&&isNaN(e.index)),r=e.time!==void 0&&!(typeof e.time=="number"&&isNaN(e.time));return n?{x:e.index,xloc:"bi"}:r?{x:e.time,xloc:"bt"}:{x:0,xloc:"bi"}}_resolve(e){return e==null?e:e instanceof Ze?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",x="wrap_none",b="default",w="format_none",E=!1){let v=new Mn(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(x)||"wrap_none",this._resolve(b)||"default",this._resolve(w)||"format_none",E);return v._helper=this,v._createdAtBar=this.context.idx,this._boxes.push(v),this._enforceMaxCount(),v}_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=ce(e,Rg,Fg),r,i,s,a,o=n.xloc;if(n.top_left instanceof Oe){let l=n.top_left,c=n.bottom_right,u=this._resolvePoint(l);r=u.x,i=l.price,o=o||u.xloc,c instanceof Oe?(s=this._resolvePoint(c).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 Ze||typeof n=="number"&&isNaN(n))return null;if(n instanceof Mn)return n;if(n instanceof y){let r=n.get(0);if(r==null||typeof r=="number"&&isNaN(r))return null;if(r instanceof Mn)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){if(e&&!e._deleted&&n){let r=this._resolvePoint(n);e.left=r.x,e.top=n.price,e.xloc=r.xloc}}set_bottom_right_point(e,n){if(e&&!e._deleted&&n){let r=this._resolvePoint(n);e.right=r.x,e.bottom=n.price,e.xloc=r.xloc}}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.left:NaN}get_right(e){return e?e.right:NaN}get_top(e){return e?e.top:NaN}get_bottom(e){return e?e.bottom:NaN}copy(e){if(!e)return;let n=e.copy();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()}};ue([k],le.prototype,"new",1),ue([k],le.prototype,"set_left",1),ue([k],le.prototype,"set_right",1),ue([k],le.prototype,"set_top",1),ue([k],le.prototype,"set_bottom",1),ue([k],le.prototype,"set_lefttop",1),ue([k],le.prototype,"set_rightbottom",1),ue([k],le.prototype,"set_top_left_point",1),ue([k],le.prototype,"set_bottom_right_point",1),ue([k],le.prototype,"set_xloc",1),ue([k],le.prototype,"set_bgcolor",1),ue([k],le.prototype,"set_border_color",1),ue([k],le.prototype,"set_border_width",1),ue([k],le.prototype,"set_border_style",1),ue([k],le.prototype,"set_extend",1),ue([k],le.prototype,"set_text",1),ue([k],le.prototype,"set_text_color",1),ue([k],le.prototype,"set_text_size",1),ue([k],le.prototype,"set_text_halign",1),ue([k],le.prototype,"set_text_valign",1),ue([k],le.prototype,"set_text_wrap",1),ue([k],le.prototype,"set_text_font_family",1),ue([k],le.prototype,"set_text_formatting",1),ue([k],le.prototype,"copy",1),ue([k],le.prototype,"delete",1);var Bg=Object.defineProperty,Lg=(t,e,n)=>e in t?Bg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,un=(t,e,n)=>Lg(t,typeof e!="symbol"?e+"":e,n),Og=0,Er=class{constructor(e,n,r){un(this,"id"),un(this,"line1"),un(this,"line2"),un(this,"color"),un(this,"_deleted"),un(this,"_createdAtBar",-1),this.id=Og++,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){this._deleted||(typeof e=="function"&&(e=e()),e&&typeof e=="object"&&Array.isArray(e.data)&&typeof e.get=="function"&&(e=e.get(0)),this.color=e||"")}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}}},xo=Object.defineProperty,Vg=Object.getOwnPropertyDescriptor,jg=(t,e,n)=>e in t?xo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ui=(t,e,n,r)=>{for(var i=r>1?void 0:r?Vg(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&&xo(e,n,i),i},$g=(t,e,n)=>jg(t,typeof e!="symbol"?e+"":e,n),mn=class{constructor(e){this.context=e,$g(this,"_linefills",[])}param(e,n=0,r){return y.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 Ze?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),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 Er(i,s,o);return l._createdAtBar=this.context.idx,this._linefills.push(l),l}any(...e){if(e.length===1){let n=e[0];return n==null||n instanceof Ze||typeof n=="number"&&isNaN(n)?null:n instanceof Er?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)}get all(){return this._linefills.filter(e=>!e._deleted)}rollbackFromBar(e){this._linefills=this._linefills.filter(n=>n._createdAtBar<e),this.syncToPlot()}};ui([k],mn.prototype,"new",1),ui([k],mn.prototype,"set_color",1),ui([k],mn.prototype,"delete",1);var Wg=Object.defineProperty,Ug=(t,e,n)=>e in t?Wg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Je=(t,e,n)=>Ug(t,typeof e!="symbol"?e+"":e,n),qg=0,Pn=class{constructor(e,n=!1,r=!1,i="bi",s="#2962ff",a="",o="style_solid",l=1,c=!1){Je(this,"id"),Je(this,"points"),Je(this,"curved"),Je(this,"closed"),Je(this,"xloc"),Je(this,"line_color"),Je(this,"fill_color"),Je(this,"line_style"),Je(this,"line_width"),Je(this,"force_overlay"),Je(this,"_deleted"),Je(this,"_createdAtBar",-1),this.id=qg++,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}}},bo=Object.defineProperty,zg=Object.getOwnPropertyDescriptor,Kg=(t,e,n)=>e in t?bo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ya=(t,e,n,r)=>{for(var i=r>1?void 0:r?zg(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&&bo(e,n,i),i},Hg=(t,e,n)=>Kg(t,typeof e!="symbol"?e+"":e,n),$n=class{constructor(e){this.context=e,Hg(this,"_polylines",[])}param(e,n=0,r){return y.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 Ze?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 Oe):[]}new(...e){let n,r=!1,i=!1,s="bi",a="#2962ff",o="",l="style_solid",c=1,u=!1,h=(b,w)=>Object.prototype.hasOwnProperty.call(b,w),p=b=>{h(b,"curved")&&(r=b.curved),h(b,"closed")&&(i=b.closed),h(b,"xloc")&&(s=b.xloc),h(b,"line_color")&&(a=b.line_color),h(b,"fill_color")&&(o=b.fill_color),h(b,"line_style")&&(l=b.line_style),h(b,"line_width")&&(c=b.line_width),h(b,"force_overlay")&&(u=b.force_overlay)},d=e.length>=1?e[e.length-1]:null,f=e.length>=2&&d&&typeof d=="object"&&!Array.isArray(d)&&!(d instanceof y)&&!(d instanceof Oe);if(e.length===1&&d&&typeof d=="object"&&!Array.isArray(d)&&"points"in d)n=d.points,p(d);else{let b=f?e.slice(0,-1):e;n=b[0],b.length>1&&(r=b[1]),b.length>2&&(i=b[2]),b.length>3&&(s=b[3]),b.length>4&&(a=b[4]),b.length>5&&(o=b[5]),b.length>6&&(l=b[6]),b.length>7&&(c=b[7]),b.length>8&&(u=b[8]),f&&p(d)}let m=this._extractPoints(n),x=new Pn(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 x._createdAtBar=this.context.idx,this._polylines.push(x),this._enforceMaxCount(),x}_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 Ze||typeof n=="number"&&isNaN(n))return null;if(n instanceof Pn)return n;if(n instanceof y){let r=n.get(0);if(r==null||typeof r=="number"&&isNaN(r))return null;if(r instanceof Pn)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()}};ya([k],$n.prototype,"new",1),ya([k],$n.prototype,"delete",1);var Gg=Object.defineProperty,Yg=(t,e,n)=>e in t?Gg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,We=(t,e,n)=>Yg(t,typeof e!="symbol"?e+"":e,n),Zg=0,Sr=class{constructor(e="top_right",n=1,r=1,i="",s="",a=0,o="",l=0,c=!1){We(this,"id"),We(this,"position"),We(this,"columns"),We(this,"rows"),We(this,"bgcolor"),We(this,"frame_color"),We(this,"frame_width"),We(this,"border_color"),We(this,"border_width"),We(this,"force_overlay"),We(this,"_deleted"),We(this,"cells"),We(this,"merges"),We(this,"_helper"),this.id=Zg++,this.position=e,this.columns=n,this.rows=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=[],this.cells=[];for(let u=0;u<r;u++){this.cells[u]=[];for(let h=0;h<n;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(n<0||n>=this.rows||e<0||e>=this.columns)return;let i=this.cells[n][e];if(i&&i._merged&&i._merge_parent){let[a,o]=i._merge_parent;if(a===e&&o===n)i._merged=!1,i._merge_parent=void 0;else{this.setCell(a,o,r);return}}let s=i||this._defaultCell();Object.assign(s,r),this.cells[n][e]=s}getCell(e,n){return n<0||n>=this.rows||e<0||e>=this.columns?null:this.cells[n][e]}clearCell(e,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)}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",_merged:!1,_merge_parent:null}}},wo=Object.defineProperty,Xg=Object.getOwnPropertyDescriptor,Qg=(t,e,n)=>e in t?wo(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?Xg(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&&wo(e,n,i),i},Jg=(t,e,n)=>Qg(t,typeof e!="symbol"?e+"":e,n),he=class{constructor(e){this.context=e,Jg(this,"_tables",[])}param(e,n=0,r){return y.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,h=e[e.length-1];if(h&&typeof h=="object"&&!Array.isArray(h)&&("bgcolor"in h||"frame_color"in h||"border_color"in h||"position"in h||"columns"in h||"rows"in h)){let d=h,f=e.slice(0,-1);n=f[0]??d.position??n,r=f[1]??d.columns??r,i=f[2]??d.rows??i,s=d.bgcolor??s,a=d.frame_color??a,o=d.frame_width??o,l=d.border_color??l,c=d.border_width??c,u=d.force_overlay??u}else 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 p=new Sr(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 p._setHelper(this),this._tables.push(p),p}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 Sr?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=e[e.length-1];if(m&&typeof m=="object"&&!Array.isArray(m)&&("text"in m||"bgcolor"in m||"text_color"in m||"text_size"in m||"text_halign"in m||"tooltip"in m||"column"in m||"row"in m||"height"in m||"width"in m||"text_valign"in m||"text_font_family"in m)){let E=m,v=e.slice(0,-1);n=v[0],r=v.length>1?v[1]:E.column??0,i=v.length>2?v[2]:E.row??0,s=v[3]??E.text??s,a=v[4]??E.width??a,o=v[5]??E.height??o,l=v[6]??E.text_color??l,c=v[7]??E.text_halign??c,u=v[8]??E.text_valign??u,h=v[9]??E.text_size??h,p=v[10]??E.bgcolor??p,d=v[11]??E.tooltip??d,f=v[12]??E.text_font_family??f}else 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;let x=this._resolve(n);if(!x||x._deleted)return;let b=this._resolve(r)??0,w=this._resolve(i)??0;x.setCell(b,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"})}delete(e){e&&(e._deleted=!0)}clear(...e){let n,r,i,s,a,o=e[e.length-1];if(o&&typeof o=="object"&&!Array.isArray(o)&&("start_column"in o||"start_row"in o||"end_column"in o)){let d=o;n=e[0],r=e.length>2?e[1]:d.start_column??0,i=e.length>3?e[2]:d.start_row??0,s=d.end_column??(e.length>4?e[3]:r),a=d.end_row??(e.length>5?e[4]:i)}else n=e[0],r=e[1]??0,i=e[2]??0,s=e[3]??r,a=e[4]??i;let l=this._resolve(n);if(!l||l._deleted)return;let c=this._resolve(r)??0,u=this._resolve(i)??0,h=this._resolve(s)??c,p=this._resolve(a)??u;for(let d=u;d<=p;d++)for(let f=c;f<=h;f++)l.clearCell(f,d)}merge_cells(...e){let n,r,i,s,a,o=e[e.length-1];if(o&&typeof o=="object"&&!Array.isArray(o)&&("start_column"in o||"start_row"in o||"end_column"in o)){let d=o;n=e[0],r=e.length>2?e[1]:d.start_column??0,i=e.length>3?e[2]:d.start_row??0,s=d.end_column??(e.length>4?e[3]:0),a=d.end_row??(e.length>5?e[4]:0)}else n=e[0],r=e[1]??0,i=e[2]??0,s=e[3]??0,a=e[4]??0;let l=this._resolve(n);if(!l||l._deleted)return;let c=this._resolve(r)??0,u=this._resolve(i)??0,h=this._resolve(s)??0,p=this._resolve(a)??0;for(let d=u;d<=p;d++)for(let f=c;f<=h;f++)d===u&&f===c||l.setCell(f,d,{_merged:!0,_merge_parent:[c,u]});l.merges.push({startCol:c,startRow:u,endCol:h,endRow:p})}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)}set_position(e,n){let r=this._resolve(e);!r||r._deleted||(r.position=this._resolve(n)||r.position)}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([k],he.prototype,"new",1),ge([k],he.prototype,"cell",1),ge([k],he.prototype,"delete",1),ge([k],he.prototype,"clear",1),ge([k],he.prototype,"merge_cells",1),ge([k],he.prototype,"cell_set_text",1),ge([k],he.prototype,"cell_set_bgcolor",1),ge([k],he.prototype,"cell_set_text_color",1),ge([k],he.prototype,"cell_set_text_size",1),ge([k],he.prototype,"cell_set_height",1),ge([k],he.prototype,"cell_set_width",1),ge([k],he.prototype,"cell_set_tooltip",1),ge([k],he.prototype,"cell_set_text_halign",1),ge([k],he.prototype,"cell_set_text_valign",1),ge([k],he.prototype,"cell_set_text_font_family",1),ge([k],he.prototype,"set_position",1),ge([k],he.prototype,"set_bgcolor",1),ge([k],he.prototype,"set_border_color",1),ge([k],he.prototype,"set_border_width",1),ge([k],he.prototype,"set_frame_color",1),ge([k],he.prototype,"set_frame_width",1);var $i=class{constructor(e){this.context=e}param(e,n=0,r){return typeof e=="string"?e:y.from(e).get(n)}inherit(e,n){let r=this._coerce(e),i=Ot(this._coerce(n)),{modifier:s}=jn(r);return s&&s!=="standard"?Ai(i,s):i}new(e,n,r,i,s,a){let o=this._coerce(e),l=this._coerce(n);return o?l?`${o}:${l}`:o:l}modify(e,n,r,i,s){return this._coerce(e)}standard(e){return e==null?Ot(this.context?.pine?.syminfo?.tickerid||this.context?.tickerId||""):Ot(this._coerce(e))}heikinashi(e){return Ai(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 y){let n=e.get(0);return n==null?"":String(n)}return typeof e=="number"&&isNaN(e)?"":String(e)}},e_=Object.defineProperty,t_=(t,e,n)=>e in t?e_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,G=(t,e,n)=>t_(t,typeof e!="symbol"?e+"":e,n),Wi=class or{constructor({marketData:e,source:n,tickerId:r,timeframe:i,limit:s,sDate:a,eDate:o,fullContext:l,inputs:c}){G(this,"data",{open:new y([]),high:new y([]),low:new y([]),close:new y([]),volume:new y([]),hl2:new y([]),hlc3:new y([]),ohlc4:new y([]),hlcc4:new y([]),bar_index:new y([])}),G(this,"indicator"),G(this,"cache",{}),G(this,"taState",{}),G(this,"strategy"),G(this,"isSecondaryContext",!1),G(this,"chartTimezone",null),G(this,"chartStyle","standard"),G(this,"dataVersion",0),G(this,"__maxLoops",5e5),G(this,"NA",NaN),G(this,"warnings",[]),G(this,"alerts",[]),G(this,"_alertMode","realtime"),G(this,"_propOverrides",{}),G(this,"_execTick",0),G(this,"lang"),G(this,"length",0),G(this,"_drawingHelpers",[]),G(this,"pine"),G(this,"idx",0),G(this,"params",{}),G(this,"const",{}),G(this,"var",{}),G(this,"let",{}),G(this,"lctx",new Map),G(this,"result"),G(this,"plots",{}),G(this,"marketData"),G(this,"source"),G(this,"tickerId"),G(this,"timeframe",""),G(this,"limit"),G(this,"sDate"),G(this,"eDate"),G(this,"fullContext"),G(this,"viewportLeft"),G(this,"viewportRight"),G(this,"pineTSCode"),G(this,"inputs",{}),G(this,"_callStack",[]),G(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 gr(this),h={Type:u.Type.bind(u),na:new Ze,nz:u.nz.bind(u),indicator:u.indicator.bind(u),fixnan:u.fixnan.bind(u),alertcondition:u.alertcondition.bind(u),alert:new yr(this),error:u.error.bind(u),max_bars_back:u.max_bars_back.bind(u),timestamp:u.timestamp.bind(u),time:new mr(this,"openTime"),time_close:new mr(this,"closeTime"),dayofmonth:new xt(this,Ft.dayofmonth),dayofweek:new xt(this,Ft.dayofweek),hour:new xt(this,Ft.hour),minute:new xt(this,Ft.minute),month:new xt(this,Ft.month),second:new xt(this,Ft.second),weekofyear:new xt(this,Ft.weekofyear),year:new xt(this,Ft.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 ki(this),ta:new Pi(this),math:new Ii(this),request:new Mi(this),array:new _i(this),map:new xi(this),matrix:new bi(this),ticker:new $i(this),strategy:new Fi(this),syminfo:null,timeframe:new Vi(this),barstate:new wi(this),session:new Si(this),get bar_index(){return p.data.bar_index},get last_bar_index(){let N=p.marketData;return Array.isArray(N)&&N.length>0?N.length-1:p.data.close.length-1},get last_bar_time(){let N=p.marketData;return Array.isArray(N)&&N.length>0?N[N.length-1].openTime:p.data.openTime.get(0)},get timenow(){return new Date().getTime()},get time_tradingday(){let N=y.from(p.data.closeTime).get(0);if(isNaN(N))return NaN;let j=p.pine?.syminfo?.timezone||"UTC",D=jt(N,j);return Date.UTC(D.year,D.month-1,D.day,0,0,0)},get inputs(){return p.inputs},log:new Bi(this),runtime:new Li(this),str:new Oi(this),...h,...nu};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 dt(this),m=new wr(this),x=new vr(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(x,["any","param"],"fill");let b=new ji(this);this.pine.chart={param:b.param.bind(b),bg_color:b.bg_color.bind(b),fg_color:b.fg_color.bind(b),get is_standard(){return b.is_standard()},get is_heikinashi(){return b.is_heikinashi()},get is_kagi(){return b.is_kagi()},get is_linebreak(){return b.is_linebreak()},get is_pnf(){return b.is_pnf()},get is_range(){return b.is_range()},get is_renko(){return b.is_renko()},point:b.point,get left_visible_bar_time(){if(p.viewportLeft!==void 0)return p.viewportLeft;let N=p.marketData;return Array.isArray(N)&&N.length>0?N[0].openTime:NaN},get right_visible_bar_time(){if(p.viewportRight!==void 0)return p.viewportRight;let N=p.marketData;return Array.isArray(N)&&N.length>0?N[N.length-1].openTime:NaN}};let w=new Ee(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_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:()=>w.all});let E=new Se(this);this.bindContextObject(E,["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:()=>E.all});let v=new le(this);this.bindContextObject(v,["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:()=>v.all});let I=new mn(this);this.bindContextObject(I,["any","new","param","set_color","get_line1","get_line2","delete"],"linefill"),Object.defineProperty(this.pine.linefill,"all",{get:()=>I.all});let C=new $n(this);this.bindContextObject(C,["any","new","param","delete"],"polyline"),Object.defineProperty(this.pine.polyline,"all",{get:()=>C.all});let T=new he(this);this.bindContextObject(T,["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","set_position","set_bgcolor","set_border_color","set_border_width","set_frame_color","set_frame_width"],"table"),Object.defineProperty(this.pine.table,"all",{get:()=>T.all}),this._drawingHelpers=[w,E,v,I,C,T];let O=new Ni(this);this.bindContextObject(O,["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;for(let s of n)typeof e[s]=="function"?i[s]=e[s].bind(e):i[s]=e[s]}init(e,n,r=0){let i;return n instanceof y?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 y?(e.data[e.data.length-1]=i,e):Array.isArray(e)?(e[e.length-1]=i,new y(e)):new y([i]):new y([i])}initVar(e,n){if(e)return e;if(typeof n=="function"&&(n=n()),n instanceof Lt){let i=n.__def__;for(let s in i)typeof n[s]=="function"&&(n[s]=n[s]())}let r;return n instanceof y?r=n.get(0):Array.isArray(n)?Array.isArray(n[0])?r=n[0]:r=this.precision(n[n.length-1]):r=this.precision(n),new y([r])}precision(e,n=10){let r=n===10?or.PRECISION_EPSILON:10**n;return typeof e=="number"?Math.round(e*r)/r:e}param(e,n,r){return typeof e=="string"?e:e instanceof y?n?new y(e.data,e.offset+n):e:!Array.isArray(e)&&typeof e=="object"?e:(this.params[r]||(this.params[r]=[]),Array.isArray(e)?new y(e,n||0):(this.params[r].length===0?this.params[r].push(e):this.params[r][this.params[r].length-1]=e,new y(this.params[r],n||0)))}get(e,n){if(typeof n=="number"&&!Number.isInteger(n)&&(n=Math.trunc(n)),e instanceof y)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 y){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}entries(e){return e==null?[].entries():Array.isArray(e.array)?e.array.entries():e.map instanceof Map?e.map.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}call(e,n,...r){this.pushId(n);try{return e(...r)}finally{this.popId()}}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}`;or._deprecationWarningsShown.has(r)||(or._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`))}};G(Wi,"_deprecationWarningsShown",new Set),G(Wi,"PRECISION_EPSILON",10**10);var _n=Wi,n_=[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],vo=[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],r_="\\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",Eo="\\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",pi={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"},hi="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",i_={5:hi,"5module":hi+" export import",6:hi+" const class extends export import super"},So=/^in(stanceof)?$/,s_=new RegExp("["+Eo+"]"),a_=new RegExp("["+Eo+r_+"]");function Ui(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 Nt(t,e){return t<65?t===36:t<91?!0:t<97?t===95:t<123?!0:t<=65535?t>=170&&s_.test(String.fromCharCode(t)):e===!1?!1:Ui(t,vo)}function $t(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&&a_.test(String.fromCharCode(t)):e===!1?!1:Ui(t,vo)||Ui(t,n_)}var J=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 et(t,e){return new J(t,{beforeExpr:!0,binop:e})}var tt={beforeExpr:!0},Ue={startsExpr:!0},vs={};function Q(t,e){return e===void 0&&(e={}),e.keyword=t,vs[t]=new J(t,e)}var g={num:new J("num",Ue),regexp:new J("regexp",Ue),string:new J("string",Ue),name:new J("name",Ue),privateId:new J("privateId",Ue),eof:new J("eof"),bracketL:new J("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new J("]"),braceL:new J("{",{beforeExpr:!0,startsExpr:!0}),braceR:new J("}"),parenL:new J("(",{beforeExpr:!0,startsExpr:!0}),parenR:new J(")"),comma:new J(",",tt),semi:new J(";",tt),colon:new J(":",tt),dot:new J("."),question:new J("?",tt),questionDot:new J("?."),arrow:new J("=>",tt),template:new J("template"),invalidTemplate:new J("invalidTemplate"),ellipsis:new J("...",tt),backQuote:new J("`",Ue),dollarBraceL:new J("${",{beforeExpr:!0,startsExpr:!0}),eq:new J("=",{beforeExpr:!0,isAssign:!0}),assign:new J("_=",{beforeExpr:!0,isAssign:!0}),incDec:new J("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new J("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:et("||",1),logicalAND:et("&&",2),bitwiseOR:et("|",3),bitwiseXOR:et("^",4),bitwiseAND:et("&",5),equality:et("==/!=/===/!==",6),relational:et("</>/<=/>=",7),bitShift:et("<</>>/>>>",8),plusMin:new J("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:et("%",10),star:et("*",10),slash:et("/",10),starstar:new J("**",{beforeExpr:!0}),coalesce:et("??",1),_break:Q("break"),_case:Q("case",tt),_catch:Q("catch"),_continue:Q("continue"),_debugger:Q("debugger"),_default:Q("default",tt),_do:Q("do",{isLoop:!0,beforeExpr:!0}),_else:Q("else",tt),_finally:Q("finally"),_for:Q("for",{isLoop:!0}),_function:Q("function",Ue),_if:Q("if"),_return:Q("return",tt),_switch:Q("switch"),_throw:Q("throw",tt),_try:Q("try"),_var:Q("var"),_const:Q("const"),_while:Q("while",{isLoop:!0}),_with:Q("with"),_new:Q("new",{beforeExpr:!0,startsExpr:!0}),_this:Q("this",Ue),_super:Q("super",Ue),_class:Q("class",Ue),_extends:Q("extends",tt),_export:Q("export"),_import:Q("import",Ue),_null:Q("null",Ue),_true:Q("true",Ue),_false:Q("false",Ue),_in:Q("in",{beforeExpr:!0,binop:7}),_instanceof:Q("instanceof",{beforeExpr:!0,binop:7}),_typeof:Q("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:Q("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:Q("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},ze=/\\r\\n?|\\n|\\u2028|\\u2029/,o_=new RegExp(ze.source,"g");function xn(t){return t===10||t===13||t===8232||t===8233}function Co(t,e,n){n===void 0&&(n=t.length);for(var r=e;r<n;r++){var i=t.charCodeAt(r);if(xn(i))return r<n-1&&i===13&&t.charCodeAt(r+1)===10?r+2:r+1}return-1}var No=/[\\u1680\\u2000-\\u200a\\u202f\\u205f\\u3000\\ufeff]/,Re=/(?:\\s|\\/\\/.*|\\/\\*[^]*?\\*\\/)*/g,ko=Object.prototype,l_=ko.hasOwnProperty,c_=ko.toString,bn=Object.hasOwn||(function(t,e){return l_.call(t,e)}),ga=Array.isArray||(function(t){return c_.call(t)==="[object Array]"}),_a=Object.create(null);function Bt(t){return _a[t]||(_a[t]=new RegExp("^(?:"+t.replace(/ /g,"|")+")$"))}function Mt(t){return t<=65535?String.fromCharCode(t):(t-=65536,String.fromCharCode((t>>10)+55296,(t&1023)+56320))}var u_=/(?:[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF])/,Wn=function(t,e){this.line=t,this.column=e};Wn.prototype.offset=function(t){return new Wn(this.line,this.column+t)};var Kr=function(t,e,n){this.start=e,this.end=n,t.sourceFile!==null&&(this.source=t.sourceFile)};function Io(t,e){for(var n=1,r=0;;){var i=Co(t,r,e);if(i<0)return new Wn(n,e-r);++n,r=i}}var qi={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},xa=!1;function p_(t){var e={};for(var n in qi)e[n]=t&&bn(t,n)?t[n]:qi[n];if(e.ecmaVersion==="latest"?e.ecmaVersion=1e8:e.ecmaVersion==null?(!xa&&typeof console=="object"&&console.warn&&(xa=!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),ga(e.onToken)){var r=e.onToken;e.onToken=function(i){return r.push(i)}}if(ga(e.onComment)&&(e.onComment=h_(e,e.onComment)),e.sourceType==="commonjs"&&e.allowAwaitOutsideFunction)throw new Error("Cannot use allowAwaitOutsideFunction with sourceType: commonjs");return e}function h_(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 Kr(this,a,o)),t.ranges&&(l.range=[i,s]),e.push(l)}}var Xt=1,Jt=2,Es=4,Ao=8,Ss=16,To=32,Hr=64,Do=128,en=256,zn=512,Mo=1024,Gr=Xt|Jt|en;function Cs(t,e){return Jt|(t?Es:0)|(e?Ao:0)}var Cr=0,Ns=1,Rt=2,Po=3,Ro=4,Fo=5,Ie=function(t,e,n){this.options=t=p_(t),this.sourceFile=t.sourceFile,this.keywords=Bt(i_[t.ecmaVersion>=6?6:t.sourceType==="module"?"5module":5]);var r="";t.allowReserved!==!0&&(r=pi[t.ecmaVersion>=6?6:t.ecmaVersion===5?5:3],t.sourceType==="module"&&(r+=" await")),this.reservedWords=Bt(r);var i=(r?r+" ":"")+pi.strict;this.reservedWordsStrict=Bt(i),this.reservedWordsStrictBind=Bt(i+" "+pi.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(ze).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=g.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"?Jt:Xt),this.regexpState=null,this.privateNameStack=[]},st={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}};Ie.prototype.parse=function(){var t=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(t)};st.inFunction.get=function(){return(this.currentVarScope().flags&Jt)>0};st.inGenerator.get=function(){return(this.currentVarScope().flags&Ao)>0};st.inAsync.get=function(){return(this.currentVarScope().flags&Es)>0};st.canAwait.get=function(){for(var t=this.scopeStack.length-1;t>=0;t--){var e=this.scopeStack[t],n=e.flags;if(n&(en|zn))return!1;if(n&Jt)return(n&Es)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction};st.allowReturn.get=function(){return!!(this.inFunction||this.options.allowReturnOutsideFunction&&this.currentVarScope().flags&Xt)};st.allowSuper.get=function(){var t=this.currentThisScope(),e=t.flags;return(e&Hr)>0||this.options.allowSuperOutsideMethod};st.allowDirectSuper.get=function(){return(this.currentThisScope().flags&Do)>0};st.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())};st.allowNewDotTarget.get=function(){for(var t=this.scopeStack.length-1;t>=0;t--){var e=this.scopeStack[t],n=e.flags;if(n&(en|zn)||n&Jt&&!(n&Ss))return!0}return!1};st.allowUsing.get=function(){var t=this.currentScope(),e=t.flags;return!(e&Mo||!this.inModule&&e&Xt)};st.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&en)>0};Ie.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};Ie.parse=function(t,e){return new this(e,t).parse()};Ie.parseExpressionAt=function(t,e,n){var r=new this(n,t,e);return r.nextToken(),r.parseExpression()};Ie.tokenizer=function(t,e){return new this(e,t)};Object.defineProperties(Ie.prototype,st);var je=Ie.prototype,d_=/^(?:\'((?:\\\\[^]|[^\'\\\\])*?)\'|"((?:\\\\[^]|[^"\\\\])*?)")/;je.strictDirective=function(t){if(this.options.ecmaVersion<5)return!1;for(;;){Re.lastIndex=t,t+=Re.exec(this.input)[0].length;var e=d_.exec(this.input.slice(t));if(!e)return!1;if((e[1]||e[2])==="use strict"){Re.lastIndex=t+e[0].length;var n=Re.exec(this.input),r=n.index+n[0].length,i=this.input.charAt(r);return i===";"||i==="}"||ze.test(n[0])&&!(/[(`.[+\\-/*%<>=,?^&]/.test(i)||i==="!"&&this.input.charAt(r+1)==="=")}t+=e[0].length,Re.lastIndex=t,t+=Re.exec(this.input)[0].length,this.input[t]===";"&&t++}};je.eat=function(t){return this.type===t?(this.next(),!0):!1};je.isContextual=function(t){return this.type===g.name&&this.value===t&&!this.containsEsc};je.eatContextual=function(t){return this.isContextual(t)?(this.next(),!0):!1};je.expectContextual=function(t){this.eatContextual(t)||this.unexpected()};je.canInsertSemicolon=function(){return this.type===g.eof||this.type===g.braceR||ze.test(this.input.slice(this.lastTokEnd,this.start))};je.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0};je.semicolon=function(){!this.eat(g.semi)&&!this.insertSemicolon()&&this.unexpected()};je.afterTrailingComma=function(t,e){if(this.type===t)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),e||this.next(),!0};je.expect=function(t){this.eat(t)||this.unexpected()};je.unexpected=function(t){this.raise(t??this.start,"Unexpected token")};var Yr=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};je.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")}};je.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")};je.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")};je.isSimpleAssignTarget=function(t){return t.type==="ParenthesizedExpression"?this.isSimpleAssignTarget(t.expression):t.type==="Identifier"||t.type==="MemberExpression"};var L=Ie.prototype;L.parseTopLevel=function(t){var e=Object.create(null);for(t.body||(t.body=[]);this.type!==g.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 ks={kind:"loop"},f_={kind:"switch"};L.isLet=function(t){if(this.options.ecmaVersion<6||!this.isContextual("let"))return!1;Re.lastIndex=this.pos;var e=Re.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(Nt(r)){var i=n;do n+=r<=65535?1:2;while($t(r=this.fullCharCodeAt(n)));if(r===92)return!0;var s=this.input.slice(i,n);if(!So.test(s))return!0}return!1};L.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;Re.lastIndex=this.pos;var t=Re.exec(this.input),e=this.pos+t[0].length,n;return!ze.test(this.input.slice(this.pos,e))&&this.input.slice(e,e+8)==="function"&&(e+8===this.input.length||!($t(n=this.fullCharCodeAt(e+8))||n===92))};L.isUsingKeyword=function(t,e){if(this.options.ecmaVersion<17||!this.isContextual(t?"await":"using"))return!1;Re.lastIndex=this.pos;var n=Re.exec(this.input),r=this.pos+n[0].length;if(ze.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||$t(s=this.fullCharCodeAt(i))||s===92)return!1;Re.lastIndex=i;var a=Re.exec(this.input);if(r=i+a[0].length,a&&ze.test(this.input.slice(i,r)))return!1}var o=this.fullCharCodeAt(r);if(!Nt(o)&&o!==92)return!1;var l=r;do r+=o<=65535?1:2;while($t(o=this.fullCharCodeAt(r)));if(o===92)return!0;var c=this.input.slice(l,r);return!(So.test(c)||e&&c==="of")};L.isAwaitUsing=function(t){return this.isUsingKeyword(!0,t)};L.isUsing=function(t){return this.isUsingKeyword(!1,t)};L.parseStatement=function(t,e,n){var r=this.type,i=this.startNode(),s;switch(this.isLet(t)&&(r=g._var,s="let"),r){case g._break:case g._continue:return this.parseBreakContinueStatement(i,r.keyword);case g._debugger:return this.parseDebuggerStatement(i);case g._do:return this.parseDoStatement(i);case g._for:return this.parseForStatement(i);case g._function:return t&&(this.strict||t!=="if"&&t!=="label")&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(i,!1,!t);case g._class:return t&&this.unexpected(),this.parseClass(i,!0);case g._if:return this.parseIfStatement(i);case g._return:return this.parseReturnStatement(i);case g._switch:return this.parseSwitchStatement(i);case g._throw:return this.parseThrowStatement(i);case g._try:return this.parseTryStatement(i);case g._const:case g._var:return s=s||this.value,t&&s!=="var"&&this.unexpected(),this.parseVarStatement(i,s);case g._while:return this.parseWhileStatement(i);case g._with:return this.parseWithStatement(i);case g.braceL:return this.parseBlock(!0,i);case g.semi:return this.parseEmptyStatement(i);case g._export:case g._import:if(this.options.ecmaVersion>10&&r===g._import){Re.lastIndex=this.pos;var a=Re.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===g._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===g.name&&h.type==="Identifier"&&this.eat(g.colon)?this.parseLabeledStatement(i,u,h,t):this.parseExpressionStatement(i,h)}};L.parseBreakContinueStatement=function(t,e){var n=e==="break";this.next(),this.eat(g.semi)||this.insertSemicolon()?t.label=null:this.type!==g.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")};L.parseDebuggerStatement=function(t){return this.next(),this.semicolon(),this.finishNode(t,"DebuggerStatement")};L.parseDoStatement=function(t){return this.next(),this.labels.push(ks),t.body=this.parseStatement("do"),this.labels.pop(),this.expect(g._while),t.test=this.parseParenExpression(),this.options.ecmaVersion>=6?this.eat(g.semi):this.semicolon(),this.finishNode(t,"DoWhileStatement")};L.parseForStatement=function(t){this.next();var e=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(ks),this.enterScope(0),this.expect(g.parenL),this.type===g.semi)return e>-1&&this.unexpected(e),this.parseFor(t,null);var n=this.isLet();if(this.type===g._var||this.type===g._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 Yr,h=this.start,p=e>-1?this.parseExprSubscripts(u,"await"):this.parseExpression(!0,u);return this.type===g._in||(a=this.options.ecmaVersion>=6&&this.isContextual("of"))?(e>-1?(this.type===g._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))};L.parseForAfterInit=function(t,e,n){return(this.type===g._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&e.declarations.length===1?(this.options.ecmaVersion>=9&&(this.type===g._in?n>-1&&this.unexpected(n):t.await=n>-1),this.parseForIn(t,e)):(n>-1&&this.unexpected(n),this.parseFor(t,e))};L.parseFunctionStatement=function(t,e,n){return this.next(),this.parseFunction(t,Rn|(n?0:zi),!1,e)};L.parseIfStatement=function(t){return this.next(),t.test=this.parseParenExpression(),t.consequent=this.parseStatement("if"),t.alternate=this.eat(g._else)?this.parseStatement("if"):null,this.finishNode(t,"IfStatement")};L.parseReturnStatement=function(t){return this.allowReturn||this.raise(this.start,"\'return\' outside of function"),this.next(),this.eat(g.semi)||this.insertSemicolon()?t.argument=null:(t.argument=this.parseExpression(),this.semicolon()),this.finishNode(t,"ReturnStatement")};L.parseSwitchStatement=function(t){this.next(),t.discriminant=this.parseParenExpression(),t.cases=[],this.expect(g.braceL),this.labels.push(f_),this.enterScope(Mo);for(var e,n=!1;this.type!==g.braceR;)if(this.type===g._case||this.type===g._default){var r=this.type===g._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(g.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")};L.parseThrowStatement=function(t){return this.next(),ze.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 m_=[];L.parseCatchClauseParam=function(){var t=this.parseBindingAtom(),e=t.type==="Identifier";return this.enterScope(e?To:0),this.checkLValPattern(t,e?Ro:Rt),this.expect(g.parenR),t};L.parseTryStatement=function(t){if(this.next(),t.block=this.parseBlock(),t.handler=null,this.type===g._catch){var e=this.startNode();this.next(),this.eat(g.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(g._finally)?this.parseBlock():null,!t.handler&&!t.finalizer&&this.raise(t.start,"Missing catch or finally clause"),this.finishNode(t,"TryStatement")};L.parseVarStatement=function(t,e,n){return this.next(),this.parseVar(t,!1,e,n),this.semicolon(),this.finishNode(t,"VariableDeclaration")};L.parseWhileStatement=function(t){return this.next(),t.test=this.parseParenExpression(),this.labels.push(ks),t.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(t,"WhileStatement")};L.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")};L.parseEmptyStatement=function(t){return this.next(),this.finishNode(t,"EmptyStatement")};L.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===g._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")};L.parseExpressionStatement=function(t,e){return t.expression=e,this.semicolon(),this.finishNode(t,"ExpressionStatement")};L.parseBlock=function(t,e,n){for(t===void 0&&(t=!0),e===void 0&&(e=this.startNode()),e.body=[],this.expect(g.braceL),t&&this.enterScope(0);this.type!==g.braceR;){var r=this.parseStatement(null);e.body.push(r)}return n&&(this.strict=!1),this.next(),t&&this.exitScope(),this.finishNode(e,"BlockStatement")};L.parseFor=function(t,e){return t.init=e,this.expect(g.semi),t.test=this.type===g.semi?null:this.parseExpression(),this.expect(g.semi),t.update=this.type===g.parenR?null:this.parseExpression(),this.expect(g.parenR),t.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(t,"ForStatement")};L.parseForIn=function(t,e){var n=this.type===g._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(g.parenR),t.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(t,n?"ForInStatement":"ForOfStatement")};L.parseVar=function(t,e,n,r){for(t.declarations=[],t.kind=n;;){var i=this.startNode();if(this.parseVarId(i,n),this.eat(g.eq)?i.init=this.parseMaybeAssign(e):!r&&n==="const"&&!(this.type===g._in||this.options.ecmaVersion>=6&&this.isContextual("of"))?this.unexpected():!r&&(n==="using"||n==="await using")&&this.options.ecmaVersion>=17&&this.type!==g._in&&!this.isContextual("of")?this.raise(this.lastTokEnd,"Missing initializer in "+n+" declaration"):!r&&i.id.type!=="Identifier"&&!(e&&(this.type===g._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(g.comma))break}return t};L.parseVarId=function(t,e){t.id=e==="using"||e==="await using"?this.parseIdent():this.parseBindingAtom(),this.checkLValPattern(t.id,e==="var"?Ns:Rt,!1)};var Rn=1,zi=2,Bo=4;L.parseFunction=function(t,e,n,r,i){this.initFunction(t),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!r)&&(this.type===g.star&&e&zi&&this.unexpected(),t.generator=this.eat(g.star)),this.options.ecmaVersion>=8&&(t.async=!!r),e&Rn&&(t.id=e&Bo&&this.type!==g.name?null:this.parseIdent(),t.id&&!(e&zi)&&this.checkLValSimple(t.id,this.strict||t.generator||t.async?this.treatFunctionsAsVar?Ns:Rt:Po));var s=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(Cs(t.async,t.generator)),e&Rn||(t.id=this.type===g.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&Rn?"FunctionDeclaration":"FunctionExpression")};L.parseFunctionParams=function(t){this.expect(g.parenL),t.params=this.parseBindingList(g.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()};L.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(g.braceL);this.type!==g.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"&&y_(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")};L.parseClassElement=function(t){if(this.eat(g.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(g.braceL))return this.parseClassStaticBlock(n),n;this.isClassElementNameStart()||this.type===g.star?o=!0:r="static"}if(n.static=o,!r&&e>=8&&this.eatContextual("async")&&((this.isClassElementNameStart()||this.type===g.star)&&!this.canInsertSemicolon()?s=!0:r="async"),!r&&(e>=9||!s)&&this.eat(g.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===g.parenL||a!=="method"||i||s){var c=!n.static&&Nr(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};L.isClassElementNameStart=function(){return this.type===g.name||this.type===g.privateId||this.type===g.num||this.type===g.string||this.type===g.bracketL||this.type.keyword};L.parseClassElementName=function(t){this.type===g.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)};L.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&&Nr(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")};L.parseClassField=function(t){return Nr(t,"constructor")?this.raise(t.key.start,"Classes can\'t have a field named \'constructor\'"):t.static&&Nr(t,"prototype")&&this.raise(t.key.start,"Classes can\'t have a static field named \'prototype\'"),this.eat(g.eq)?(this.enterScope(zn|Hr),t.value=this.parseMaybeAssign(),this.exitScope()):t.value=null,this.semicolon(),this.finishNode(t,"PropertyDefinition")};L.parseClassStaticBlock=function(t){t.body=[];var e=this.labels;for(this.labels=[],this.enterScope(en|Hr);this.type!==g.braceR;){var n=this.parseStatement(null);t.body.push(n)}return this.next(),this.exitScope(),this.labels=e,this.finishNode(t,"StaticBlock")};L.parseClassId=function(t,e){this.type===g.name?(t.id=this.parseIdent(),e&&this.checkLValSimple(t.id,Rt,!1)):(e===!0&&this.unexpected(),t.id=null)};L.parseClassSuper=function(t){t.superClass=this.eat(g._extends)?this.parseExprSubscripts(null,!1):null};L.enterClassBody=function(){var t={declared:Object.create(null),used:[]};return this.privateNameStack.push(t),t.declared};L.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];bn(e,a.name)||(i?i.used.push(a):this.raiseRecoverable(a.start,"Private field \'#"+a.name+"\' must be declared in an enclosing class"))}};function y_(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 Nr(t,e){var n=t.computed,r=t.key;return!n&&(r.type==="Identifier"&&r.name===e||r.type==="Literal"&&r.value===e)}L.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!==g.string&&this.unexpected(),t.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(t.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(t,"ExportAllDeclaration")};L.parseExport=function(t,e){if(this.next(),this.eat(g.star))return this.parseExportAllDeclaration(t,e);if(this.eat(g._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!==g.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")};L.parseExportDeclaration=function(t){return this.parseStatement(null)};L.parseExportDefaultDeclaration=function(){var t;if(this.type===g._function||(t=this.isAsyncFunction())){var e=this.startNode();return this.next(),t&&this.next(),this.parseFunction(e,Rn|Bo,!1,t)}else if(this.type===g._class){var n=this.startNode();return this.parseClass(n,"nullableID")}else{var r=this.parseMaybeAssign();return this.semicolon(),r}};L.checkExport=function(t,e,n){t&&(typeof e!="string"&&(e=e.type==="Identifier"?e.name:e.value),bn(t,e)&&this.raiseRecoverable(n,"Duplicate export \'"+e+"\'"),t[e]=!0)};L.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)};L.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)}};L.shouldParseExportStatement=function(){return this.type.keyword==="var"||this.type.keyword==="const"||this.type.keyword==="class"||this.type.keyword==="function"||this.isLet()||this.isAsyncFunction()};L.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")};L.parseExportSpecifiers=function(t){var e=[],n=!0;for(this.expect(g.braceL);!this.eat(g.braceR);){if(n)n=!1;else if(this.expect(g.comma),this.afterTrailingComma(g.braceR))break;e.push(this.parseExportSpecifier(t))}return e};L.parseImport=function(t){return this.next(),this.type===g.string?(t.specifiers=m_,t.source=this.parseExprAtom()):(t.specifiers=this.parseImportSpecifiers(),this.expectContextual("from"),t.source=this.type===g.string?this.parseExprAtom():this.unexpected()),this.options.ecmaVersion>=16&&(t.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(t,"ImportDeclaration")};L.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,Rt),this.finishNode(t,"ImportSpecifier")};L.parseImportDefaultSpecifier=function(){var t=this.startNode();return t.local=this.parseIdent(),this.checkLValSimple(t.local,Rt),this.finishNode(t,"ImportDefaultSpecifier")};L.parseImportNamespaceSpecifier=function(){var t=this.startNode();return this.next(),this.expectContextual("as"),t.local=this.parseIdent(),this.checkLValSimple(t.local,Rt),this.finishNode(t,"ImportNamespaceSpecifier")};L.parseImportSpecifiers=function(){var t=[],e=!0;if(this.type===g.name&&(t.push(this.parseImportDefaultSpecifier()),!this.eat(g.comma)))return t;if(this.type===g.star)return t.push(this.parseImportNamespaceSpecifier()),t;for(this.expect(g.braceL);!this.eat(g.braceR);){if(e)e=!1;else if(this.expect(g.comma),this.afterTrailingComma(g.braceR))break;t.push(this.parseImportSpecifier())}return t};L.parseWithClause=function(){var t=[];if(!this.eat(g._with))return t;this.expect(g.braceL);for(var e={},n=!0;!this.eat(g.braceR);){if(n)n=!1;else if(this.expect(g.comma),this.afterTrailingComma(g.braceR))break;var r=this.parseImportAttribute(),i=r.key.type==="Identifier"?r.key.name:r.key.value;bn(e,i)&&this.raiseRecoverable(r.key.start,"Duplicate attribute key \'"+i+"\'"),e[i]=!0,t.push(r)}return t};L.parseImportAttribute=function(){var t=this.startNode();return t.key=this.type===g.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never"),this.expect(g.colon),this.type!==g.string&&this.unexpected(),t.value=this.parseExprAtom(),this.finishNode(t,"ImportAttribute")};L.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===g.string){var t=this.parseLiteral(this.value);return u_.test(t.value)&&this.raise(t.start,"An export name cannot include a lone surrogate."),t}return this.parseIdent(!0)};L.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)};L.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 at=Ie.prototype;at.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};at.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};at.parseSpread=function(t){var e=this.startNode();return this.next(),e.argument=this.parseMaybeAssign(!1,t),this.finishNode(e,"SpreadElement")};at.parseRestBinding=function(){var t=this.startNode();return this.next(),this.options.ecmaVersion===6&&this.type!==g.name&&this.unexpected(),t.argument=this.parseBindingAtom(),this.finishNode(t,"RestElement")};at.parseBindingAtom=function(){if(this.options.ecmaVersion>=6)switch(this.type){case g.bracketL:var t=this.startNode();return this.next(),t.elements=this.parseBindingList(g.bracketR,!0,!0),this.finishNode(t,"ArrayPattern");case g.braceL:return this.parseObj(!0)}return this.parseIdent()};at.parseBindingList=function(t,e,n,r){for(var i=[],s=!0;!this.eat(t);)if(s?s=!1:this.expect(g.comma),e&&this.type===g.comma)i.push(null);else{if(n&&this.afterTrailingComma(t))break;if(this.type===g.ellipsis){var a=this.parseRestBinding();this.parseBindingListItem(a),i.push(a),this.type===g.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};at.parseAssignableListItem=function(t){var e=this.parseMaybeDefault(this.start,this.startLoc);return this.parseBindingListItem(e),e};at.parseBindingListItem=function(t){return t};at.parseMaybeDefault=function(t,e,n){if(n=n||this.parseBindingAtom(),this.options.ecmaVersion<6||!this.eat(g.eq))return n;var r=this.startNodeAt(t,e);return r.left=n,r.right=this.parseMaybeAssign(),this.finishNode(r,"AssignmentPattern")};at.checkLValSimple=function(t,e,n){e===void 0&&(e=Cr);var r=e!==Cr;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===Rt&&t.name==="let"&&this.raiseRecoverable(t.start,"let is disallowed as a lexically bound name"),n&&(bn(n,t.name)&&this.raiseRecoverable(t.start,"Argument name clash"),n[t.name]=!0),e!==Fo&&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")}};at.checkLValPattern=function(t,e,n){switch(e===void 0&&(e=Cr),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)}};at.checkLValInnerPattern=function(t,e,n){switch(e===void 0&&(e=Cr),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 ct=function(t,e,n,r,i){this.token=t,this.isExpr=!!e,this.preserveSpace=!!n,this.override=r,this.generator=!!i},de={b_stat:new ct("{",!1),b_expr:new ct("{",!0),b_tmpl:new ct("${",!1),p_stat:new ct("(",!1),p_expr:new ct("(",!0),q_tmpl:new ct("`",!0,!0,function(t){return t.tryReadTemplateToken()}),f_stat:new ct("function",!1),f_expr:new ct("function",!0),f_expr_gen:new ct("function",!0,!1,null,!0),f_gen:new ct("function",!1,!1,null,!0)},wn=Ie.prototype;wn.initialContext=function(){return[de.b_stat]};wn.curContext=function(){return this.context[this.context.length-1]};wn.braceIsBlock=function(t){var e=this.curContext();return e===de.f_expr||e===de.f_stat?!0:t===g.colon&&(e===de.b_stat||e===de.b_expr)?!e.isExpr:t===g._return||t===g.name&&this.exprAllowed?ze.test(this.input.slice(this.lastTokEnd,this.start)):t===g._else||t===g.semi||t===g.eof||t===g.parenR||t===g.arrow?!0:t===g.braceL?e===de.b_stat:t===g._var||t===g._const||t===g.name?!1:!this.exprAllowed};wn.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};wn.updateContext=function(t){var e,n=this.type;n.keyword&&t===g.dot?this.exprAllowed=!1:(e=n.updateContext)?e.call(this,t):this.exprAllowed=n.beforeExpr};wn.overrideContext=function(t){this.curContext()!==t&&(this.context[this.context.length-1]=t)};g.parenR.updateContext=g.braceR.updateContext=function(){if(this.context.length===1){this.exprAllowed=!0;return}var t=this.context.pop();t===de.b_stat&&this.curContext().token==="function"&&(t=this.context.pop()),this.exprAllowed=!t.isExpr};g.braceL.updateContext=function(t){this.context.push(this.braceIsBlock(t)?de.b_stat:de.b_expr),this.exprAllowed=!0};g.dollarBraceL.updateContext=function(){this.context.push(de.b_tmpl),this.exprAllowed=!0};g.parenL.updateContext=function(t){var e=t===g._if||t===g._for||t===g._with||t===g._while;this.context.push(e?de.p_stat:de.p_expr),this.exprAllowed=!0};g.incDec.updateContext=function(){};g._function.updateContext=g._class.updateContext=function(t){t.beforeExpr&&t!==g._else&&!(t===g.semi&&this.curContext()!==de.p_stat)&&!(t===g._return&&ze.test(this.input.slice(this.lastTokEnd,this.start)))&&!((t===g.colon||t===g.braceL)&&this.curContext()===de.b_stat)?this.context.push(de.f_expr):this.context.push(de.f_stat),this.exprAllowed=!1};g.colon.updateContext=function(){this.curContext().token==="function"&&this.context.pop(),this.exprAllowed=!0};g.backQuote.updateContext=function(){this.curContext()===de.q_tmpl?this.context.pop():this.context.push(de.q_tmpl),this.exprAllowed=!1};g.star.updateContext=function(t){if(t===g._function){var e=this.context.length-1;this.context[e]===de.f_expr?this.context[e]=de.f_expr_gen:this.context[e]=de.f_gen}this.exprAllowed=!0};g.name.updateContext=function(t){var e=!1;this.options.ecmaVersion>=6&&t!==g.dot&&(this.value==="of"&&!this.exprAllowed||this.value==="yield"&&this.inGeneratorContext())&&(e=!0),this.exprAllowed=e};var K=Ie.prototype;K.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}};K.parseExpression=function(t,e){var n=this.start,r=this.startLoc,i=this.parseMaybeAssign(t,e);if(this.type===g.comma){var s=this.startNodeAt(n,r);for(s.expressions=[i];this.eat(g.comma);)s.expressions.push(this.parseMaybeAssign(t,e));return this.finishNode(s,"SequenceExpression")}return i};K.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 Yr,r=!0);var o=this.start,l=this.startLoc;(this.type===g.parenL||this.type===g.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===g.eq&&(c=this.toAssignable(c,!1,e)),r||(e.parenthesizedAssign=e.trailingComma=e.doubleProto=-1),e.shorthandAssign>=c.start&&(e.shorthandAssign=-1),this.type===g.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};K.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(g.question)){var s=this.startNodeAt(n,r);return s.test=i,s.consequent=this.parseMaybeAssign(),this.expect(g.colon),s.alternate=this.parseMaybeAssign(t),this.finishNode(s,"ConditionalExpression")}return i};K.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)};K.parseExprOp=function(t,e,n,r,i){var s=this.type.binop;if(s!=null&&(!i||this.type!==g._in)&&s>r){var a=this.type===g.logicalOR||this.type===g.logicalAND,o=this.type===g.coalesce;o&&(s=g.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===g.coalesce||o&&(this.type===g.logicalOR||this.type===g.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};K.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")};K.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===g.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"&&Lo(o.argument)?this.raiseRecoverable(o.start,"Deleting local variable in strict mode"):o.operator==="delete"&&Ki(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===g.privateId)(r||this.privateNameStack.length===0)&&this.options.checkPrivateFields&&this.unexpected(),a=this.parsePrivateIdent(),this.type!==g._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(g.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 Lo(t){return t.type==="Identifier"||t.type==="ParenthesizedExpression"&&Lo(t.expression)}function Ki(t){return t.type==="MemberExpression"&&t.property.type==="PrivateIdentifier"||t.type==="ChainExpression"&&Ki(t.expression)||t.type==="ParenthesizedExpression"&&Ki(t.expression)}K.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};K.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}};K.shouldParseAsyncArrow=function(){return!this.canInsertSemicolon()&&this.eat(g.arrow)};K.parseSubscriptAsyncArrow=function(t,e,n,r){return this.parseArrowExpression(this.startNodeAt(t,e),n,!0,r)};K.parseSubscript=function(t,e,n,r,i,s,a){var o=this.options.ecmaVersion>=11,l=o&&this.eat(g.questionDot);r&&l&&this.raise(this.lastTokStart,"Optional chaining cannot appear in the callee of new expressions");var c=this.eat(g.bracketL);if(c||l&&this.type!==g.parenL&&this.type!==g.backQuote||this.eat(g.dot)){var u=this.startNodeAt(e,n);u.object=t,c?(u.property=this.parseExpression(),this.expect(g.bracketR)):this.type===g.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(g.parenL)){var h=new Yr,p=this.yieldPos,d=this.awaitPos,f=this.awaitIdentPos;this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0;var m=this.parseExprList(g.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 x=this.startNodeAt(e,n);x.callee=t,x.arguments=m,o&&(x.optional=l),t=this.finishNode(x,"CallExpression")}else if(this.type===g.backQuote){(l||s)&&this.raise(this.start,"Optional chaining cannot appear in the tag of tagged template expressions");var b=this.startNodeAt(e,n);b.tag=t,b.quasi=this.parseTemplate({isTagged:!0}),t=this.finishNode(b,"TaggedTemplateExpression")}return t};K.parseExprAtom=function(t,e,n){this.type===g.slash&&this.readRegexp();var r,i=this.potentialArrowAt===this.start;switch(this.type){case g._super:return this.allowSuper||this.raise(this.start,"\'super\' keyword outside a method"),r=this.startNode(),this.next(),this.type===g.parenL&&!this.allowDirectSuper&&this.raise(r.start,"super() call outside constructor of a subclass"),this.type!==g.dot&&this.type!==g.bracketL&&this.type!==g.parenL&&this.unexpected(),this.finishNode(r,"Super");case g._this:return r=this.startNode(),this.next(),this.finishNode(r,"ThisExpression");case g.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(g._function))return this.overrideContext(de.f_expr),this.parseFunction(this.startNodeAt(s,a),0,!1,!0,e);if(i&&!this.canInsertSemicolon()){if(this.eat(g.arrow))return this.parseArrowExpression(this.startNodeAt(s,a),[l],!1,e);if(this.options.ecmaVersion>=8&&l.name==="async"&&this.type===g.name&&!o&&(!this.potentialArrowInForAwait||this.value!=="of"||this.containsEsc))return l=this.parseIdent(!1),(this.canInsertSemicolon()||!this.eat(g.arrow))&&this.unexpected(),this.parseArrowExpression(this.startNodeAt(s,a),[l],!0,e)}return l;case g.regexp:var c=this.value;return r=this.parseLiteral(c.value),r.regex={pattern:c.pattern,flags:c.flags},r;case g.num:case g.string:return this.parseLiteral(this.value);case g._null:case g._true:case g._false:return r=this.startNode(),r.value=this.type===g._null?null:this.type===g._true,r.raw=this.type.keyword,this.next(),this.finishNode(r,"Literal");case g.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 g.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(g.bracketR,!0,!0,t),this.finishNode(r,"ArrayExpression");case g.braceL:return this.overrideContext(de.b_expr),this.parseObj(!1,t);case g._function:return r=this.startNode(),this.next(),this.parseFunction(r,0);case g._class:return this.parseClass(this.startNode(),!1);case g._new:return this.parseNew();case g.backQuote:return this.parseTemplate();case g._import:return this.options.ecmaVersion>=11?this.parseExprImport(n):this.unexpected();default:return this.parseExprAtomDefault()}};K.parseExprAtomDefault=function(){this.unexpected()};K.parseExprImport=function(t){var e=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===g.parenL&&!t)return this.parseDynamicImport(e);if(this.type===g.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()};K.parseDynamicImport=function(t){if(this.next(),t.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(g.parenR)?t.options=null:(this.expect(g.comma),this.afterTrailingComma(g.parenR)?t.options=null:(t.options=this.parseMaybeAssign(),this.eat(g.parenR)||(this.expect(g.comma),this.afterTrailingComma(g.parenR)||this.unexpected())));else if(!this.eat(g.parenR)){var e=this.start;this.eat(g.comma)&&this.eat(g.parenR)?this.raiseRecoverable(e,"Trailing comma is not allowed in import()"):this.unexpected(e)}return this.finishNode(t,"ImportExpression")};K.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")};K.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")};K.parseParenExpression=function(){this.expect(g.parenL);var t=this.parseExpression();return this.expect(g.parenR),t};K.shouldParseArrow=function(t){return!this.canInsertSemicolon()};K.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 Yr,p=this.yieldPos,d=this.awaitPos,f;for(this.yieldPos=0,this.awaitPos=0;this.type!==g.parenR;)if(c?c=!1:this.expect(g.comma),s&&this.afterTrailingComma(g.parenR,!0)){u=!0;break}else if(this.type===g.ellipsis){f=this.start,l.push(this.parseParenItem(this.parseRestBinding())),this.type===g.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,x=this.lastTokEndLoc;if(this.expect(g.parenR),t&&this.shouldParseArrow(l)&&this.eat(g.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,x)):i=l[0]}else i=this.parseParenExpression();if(this.options.preserveParens){var b=this.startNodeAt(n,r);return b.expression=i,this.finishNode(b,"ParenthesizedExpression")}else return i};K.parseParenItem=function(t){return t};K.parseParenArrowList=function(t,e,n,r){return this.parseArrowExpression(this.startNodeAt(t,e),n,!1,r)};var g_=[];K.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===g.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(g.parenL)?t.arguments=this.parseExprList(g.parenR,this.options.ecmaVersion>=8,!1):t.arguments=g_,this.finishNode(t,"NewExpression")};K.parseTemplateElement=function(t){var e=t.isTagged,n=this.startNode();return this.type===g.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===g.backQuote,this.finishNode(n,"TemplateElement")};K.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===g.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(g.dollarBraceL),n.expressions.push(this.parseExpression()),this.expect(g.braceR),n.quasis.push(r=this.parseTemplateElement({isTagged:e}));return this.next(),this.finishNode(n,"TemplateLiteral")};K.isAsyncProp=function(t){return!t.computed&&t.key.type==="Identifier"&&t.key.name==="async"&&(this.type===g.name||this.type===g.num||this.type===g.string||this.type===g.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===g.star)&&!ze.test(this.input.slice(this.lastTokEnd,this.start))};K.parseObj=function(t,e){var n=this.startNode(),r=!0,i={};for(n.properties=[],this.next();!this.eat(g.braceR);){if(r)r=!1;else if(this.expect(g.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(g.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")};K.parseProperty=function(t,e){var n=this.startNode(),r,i,s,a;if(this.options.ecmaVersion>=9&&this.eat(g.ellipsis))return t?(n.argument=this.parseIdent(!1),this.type===g.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===g.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(g.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(g.star),this.parsePropertyName(n)):i=!1,this.parsePropertyValue(n,t,r,i,s,a,e,o),this.finishNode(n,"Property")};K.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")};K.parsePropertyValue=function(t,e,n,r,i,s,a,o){(n||r)&&this.type===g.colon&&this.unexpected(),this.eat(g.colon)?(t.value=e?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,a),t.kind="init"):this.options.ecmaVersion>=6&&this.type===g.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!==g.comma&&this.type!==g.braceR&&this.type!==g.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===g.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()};K.parsePropertyName=function(t){if(this.options.ecmaVersion>=6){if(this.eat(g.bracketL))return t.computed=!0,t.key=this.parseMaybeAssign(),this.expect(g.bracketR),t.key;t.computed=!1}return t.key=this.type===g.num||this.type===g.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never")};K.initFunction=function(t){t.id=null,this.options.ecmaVersion>=6&&(t.generator=t.expression=!1),this.options.ecmaVersion>=8&&(t.async=!1)};K.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(Cs(e,r.generator)|Hr|(n?Do:0)),this.expect(g.parenL),r.params=this.parseBindingList(g.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")};K.parseArrowExpression=function(t,e,n,r){var i=this.yieldPos,s=this.awaitPos,a=this.awaitIdentPos;return this.enterScope(Cs(n,!1)|Ss),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")};K.parseFunctionBody=function(t,e,n,r){var i=e&&this.type!==g.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,Fo),t.body=this.parseBlock(!1,void 0,a&&!s),t.expression=!1,this.adaptDirectivePrologue(t.body.body),this.labels=l}this.exitScope()};K.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};K.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,Ns,e?null:n)}};K.parseExprList=function(t,e,n,r){for(var i=[],s=!0;!this.eat(t);){if(s)s=!1;else if(this.expect(g.comma),e&&this.afterTrailingComma(t))break;var a=void 0;n&&this.type===g.comma?a=null:this.type===g.ellipsis?(a=this.parseSpread(r),r&&this.type===g.comma&&r.trailingComma<0&&(r.trailingComma=this.start)):a=this.parseMaybeAssign(!1,r),i.push(a)}return i};K.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&Gr)&&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"))}};K.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};K.parseIdentNode=function(){var t=this.startNode();return this.type===g.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=g.name):this.unexpected(),t};K.parsePrivateIdent=function(){var t=this.startNode();return this.type===g.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};K.parseYield=function(t){this.yieldPos||(this.yieldPos=this.start);var e=this.startNode();return this.next(),this.type===g.semi||this.canInsertSemicolon()||this.type!==g.star&&!this.type.startsExpr?(e.delegate=!1,e.argument=null):(e.delegate=this.eat(g.star),e.argument=this.parseMaybeAssign(t)),this.finishNode(e,"YieldExpression")};K.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 kr=Ie.prototype;kr.raise=function(t,e){var n=Io(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};kr.raiseRecoverable=kr.raise;kr.curPosition=function(){if(this.options.locations)return new Wn(this.curLine,this.pos-this.lineStart)};var qt=Ie.prototype,__=function(t){this.flags=t,this.var=[],this.lexical=[],this.functions=[]};qt.enterScope=function(t){this.scopeStack.push(new __(t))};qt.exitScope=function(){this.scopeStack.pop()};qt.treatFunctionsAsVarInScope=function(t){return t.flags&Jt||!this.inModule&&t.flags&Xt};qt.declareName=function(t,e,n){var r=!1;if(e===Rt){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&Xt&&delete this.undefinedExports[t]}else if(e===Ro){var s=this.currentScope();s.lexical.push(t)}else if(e===Po){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&To&&l.lexical[0]===t)||!this.treatFunctionsAsVarInScope(l)&&l.functions.indexOf(t)>-1){r=!0;break}if(l.var.push(t),this.inModule&&l.flags&Xt&&delete this.undefinedExports[t],l.flags&Gr)break}r&&this.raiseRecoverable(n,"Identifier \'"+t+"\' has already been declared")};qt.checkLocalExport=function(t){this.scopeStack[0].lexical.indexOf(t.name)===-1&&this.scopeStack[0].var.indexOf(t.name)===-1&&(this.undefinedExports[t.name]=t)};qt.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]};qt.currentVarScope=function(){for(var t=this.scopeStack.length-1;;t--){var e=this.scopeStack[t];if(e.flags&(Gr|zn|en))return e}};qt.currentThisScope=function(){for(var t=this.scopeStack.length-1;;t--){var e=this.scopeStack[t];if(e.flags&(Gr|zn|en)&&!(e.flags&Ss))return e}};var Zr=function(t,e,n){this.type="",this.start=e,this.end=0,t.options.locations&&(this.loc=new Kr(t,n)),t.options.directSourceFile&&(this.sourceFile=t.options.directSourceFile),t.options.ranges&&(this.range=[e,0])},Kn=Ie.prototype;Kn.startNode=function(){return new Zr(this,this.start,this.startLoc)};Kn.startNodeAt=function(t,e){return new Zr(this,t,e)};function Oo(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}Kn.finishNode=function(t,e){return Oo.call(this,t,e,this.lastTokEnd,this.lastTokEndLoc)};Kn.finishNodeAt=function(t,e,n,r){return Oo.call(this,t,e,n,r)};Kn.copyNode=function(t){var e=new Zr(this,t.start,this.startLoc);for(var n in t)e[n]=t[n];return e};var x_="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",Vo="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",jo=Vo+" Extended_Pictographic",$o=jo,Wo=$o+" EBase EComp EMod EPres ExtPict",Uo=Wo,b_=Uo,w_={9:Vo,10:jo,11:$o,12:Wo,13:Uo,14:b_},v_="Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji",E_={9:"",10:"",11:"",12:"",13:"",14:v_},ba="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",qo="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",zo=qo+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",Ko=zo+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",Ho=Ko+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",Go=Ho+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",S_=Go+" "+x_,C_={9:qo,10:zo,11:Ko,12:Ho,13:Go,14:S_},Yo={};function N_(t){var e=Yo[t]={binary:Bt(w_[t]+" "+ba),binaryOfStrings:Bt(E_[t]),nonBinary:{General_Category:Bt(ba),Script:Bt(C_[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(er=0,di=[9,10,11,12,13,14];er<di.length;er+=1)wa=di[er],N_(wa);var wa,er,di,B=Ie.prototype,Ir=function(t,e){this.parent=t,this.base=e||this};Ir.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};Ir.prototype.sibling=function(){return new Ir(this.parent,this.base)};var kt=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=Yo[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};kt.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)};kt.prototype.raise=function(t){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+t)};kt.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};kt.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};kt.prototype.current=function(t){return t===void 0&&(t=!1),this.at(this.pos,t)};kt.prototype.lookahead=function(t){return t===void 0&&(t=!1),this.at(this.nextIndex(this.pos,t),t)};kt.prototype.advance=function(t){t===void 0&&(t=!1),this.pos=this.nextIndex(this.pos,t)};kt.prototype.eat=function(t,e){return e===void 0&&(e=!1),this.current(e)===t?(this.advance(e),!0):!1};kt.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};B.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 k_(t){for(var e in t)return!0;return!1}B.validateRegExpPattern=function(t){this.regexp_pattern(t),!t.switchN&&this.options.ecmaVersion>=9&&k_(t.groupNames)&&(t.switchN=!0,this.regexp_pattern(t))};B.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")}};B.regexp_disjunction=function(t){var e=this.options.ecmaVersion>=16;for(e&&(t.branchID=new Ir(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")};B.regexp_alternative=function(t){for(;t.pos<t.source.length&&this.regexp_eatTerm(t););};B.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};B.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};B.regexp_eatQuantifier=function(t,e){return e===void 0&&(e=!1),this.regexp_eatQuantifierPrefix(t,e)?(t.eat(63),!0):!1};B.regexp_eatQuantifierPrefix=function(t,e){return t.eat(42)||t.eat(43)||t.eat(63)||this.regexp_eatBracedQuantifier(t,e)};B.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};B.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)};B.regexp_eatReverseSolidusAtomEscape=function(t){var e=t.pos;if(t.eat(92)){if(this.regexp_eatAtomEscape(t))return!0;t.pos=e}return!1};B.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};B.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};B.regexp_eatModifiers=function(t){for(var e="",n=0;(n=t.current())!==-1&&I_(n);)e+=Mt(n),t.advance();return e};function I_(t){return t===105||t===109||t===115}B.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)};B.regexp_eatInvalidBracedQuantifier=function(t){return this.regexp_eatBracedQuantifier(t,!0)&&t.raise("Nothing to repeat"),!1};B.regexp_eatSyntaxCharacter=function(t){var e=t.current();return Zo(e)?(t.lastIntValue=e,t.advance(),!0):!1};function Zo(t){return t===36||t>=40&&t<=43||t===46||t===63||t>=91&&t<=94||t>=123&&t<=125}B.regexp_eatPatternCharacters=function(t){for(var e=t.pos,n=0;(n=t.current())!==-1&&!Zo(n);)t.advance();return t.pos!==e};B.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};B.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}};B.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};B.regexp_eatRegExpIdentifierName=function(t){if(t.lastStringValue="",this.regexp_eatRegExpIdentifierStart(t)){for(t.lastStringValue+=Mt(t.lastIntValue);this.regexp_eatRegExpIdentifierPart(t);)t.lastStringValue+=Mt(t.lastIntValue);return!0}return!1};B.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),A_(r)?(t.lastIntValue=r,!0):(t.pos=e,!1)};function A_(t){return Nt(t,!0)||t===36||t===95}B.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),T_(r)?(t.lastIntValue=r,!0):(t.pos=e,!1)};function T_(t){return $t(t,!0)||t===36||t===95||t===8204||t===8205}B.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)};B.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};B.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};B.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)};B.regexp_eatCControlLetter=function(t){var e=t.pos;if(t.eat(99)){if(this.regexp_eatControlLetter(t))return!0;t.pos=e}return!1};B.regexp_eatZero=function(t){return t.current()===48&&!Xr(t.lookahead())?(t.lastIntValue=0,t.advance(),!0):!1};B.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};B.regexp_eatControlLetter=function(t){var e=t.current();return Xo(e)?(t.lastIntValue=e%32,t.advance(),!0):!1};function Xo(t){return t>=65&&t<=90||t>=97&&t<=122}B.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)&&D_(t.lastIntValue))return!0;r&&t.raise("Invalid unicode escape"),t.pos=n}return!1};function D_(t){return t>=0&&t<=1114111}B.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};B.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 Qo=0,Pt=1,rt=2;B.regexp_eatCharacterClassEscape=function(t){var e=t.current();if(M_(e))return t.lastIntValue=-1,t.advance(),Pt;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===rt&&t.raise("Invalid property name"),r;t.raise("Invalid property name")}return Qo};function M_(t){return t===100||t===68||t===115||t===83||t===119||t===87}B.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),Pt}}if(t.pos=e,this.regexp_eatLoneUnicodePropertyNameOrValue(t)){var i=t.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(t,i)}return Qo};B.regexp_validateUnicodePropertyNameAndValue=function(t,e,n){bn(t.unicodeProperties.nonBinary,e)||t.raise("Invalid property name"),t.unicodeProperties.nonBinary[e].test(n)||t.raise("Invalid property value")};B.regexp_validateUnicodePropertyNameOrValue=function(t,e){if(t.unicodeProperties.binary.test(e))return Pt;if(t.switchV&&t.unicodeProperties.binaryOfStrings.test(e))return rt;t.raise("Invalid property name")};B.regexp_eatUnicodePropertyName=function(t){var e=0;for(t.lastStringValue="";Jo(e=t.current());)t.lastStringValue+=Mt(e),t.advance();return t.lastStringValue!==""};function Jo(t){return Xo(t)||t===95}B.regexp_eatUnicodePropertyValue=function(t){var e=0;for(t.lastStringValue="";P_(e=t.current());)t.lastStringValue+=Mt(e),t.advance();return t.lastStringValue!==""};function P_(t){return Jo(t)||Xr(t)}B.regexp_eatLoneUnicodePropertyNameOrValue=function(t){return this.regexp_eatUnicodePropertyValue(t)};B.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===rt&&t.raise("Negated character class may contain strings"),!0}return!1};B.regexp_classContents=function(t){return t.current()===93?Pt:t.switchV?this.regexp_classSetExpression(t):(this.regexp_nonEmptyClassRanges(t),Pt)};B.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")}}};B.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||nl(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};B.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)};B.regexp_classSetExpression=function(t){var e=Pt,n;if(!this.regexp_eatClassSetRange(t))if(n=this.regexp_eatClassSetOperand(t)){n===rt&&(e=rt);for(var r=t.pos;t.eatChars([38,38]);){if(t.current()!==38&&(n=this.regexp_eatClassSetOperand(t))){n!==rt&&(e=Pt);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===rt&&(e=rt)}};B.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};B.regexp_eatClassSetOperand=function(t){return this.regexp_eatClassSetCharacter(t)?Pt:this.regexp_eatClassStringDisjunction(t)||this.regexp_eatNestedClass(t)};B.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===rt&&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};B.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};B.regexp_classStringDisjunctionContents=function(t){for(var e=this.regexp_classString(t);t.eat(124);)this.regexp_classString(t)===rt&&(e=rt);return e};B.regexp_classString=function(t){for(var e=0;this.regexp_eatClassSetCharacter(t);)e++;return e===1?Pt:rt};B.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()&&R_(n)||F_(n)?!1:(t.advance(),t.lastIntValue=n,!0)};function R_(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 F_(t){return t===40||t===41||t===45||t===47||t>=91&&t<=93||t>=123&&t<=125}B.regexp_eatClassSetReservedPunctuator=function(t){var e=t.current();return B_(e)?(t.lastIntValue=e,t.advance(),!0):!1};function B_(t){return t===33||t===35||t===37||t===38||t===44||t===45||t>=58&&t<=62||t===64||t===96||t===126}B.regexp_eatClassControlLetter=function(t){var e=t.current();return Xr(e)||e===95?(t.lastIntValue=e%32,t.advance(),!0):!1};B.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};B.regexp_eatDecimalDigits=function(t){var e=t.pos,n=0;for(t.lastIntValue=0;Xr(n=t.current());)t.lastIntValue=10*t.lastIntValue+(n-48),t.advance();return t.pos!==e};function Xr(t){return t>=48&&t<=57}B.regexp_eatHexDigits=function(t){var e=t.pos,n=0;for(t.lastIntValue=0;el(n=t.current());)t.lastIntValue=16*t.lastIntValue+tl(n),t.advance();return t.pos!==e};function el(t){return t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102}function tl(t){return t>=65&&t<=70?10+(t-65):t>=97&&t<=102?10+(t-97):t-48}B.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};B.regexp_eatOctalDigit=function(t){var e=t.current();return nl(e)?(t.lastIntValue=e-48,t.advance(),!0):(t.lastIntValue=0,!1)};function nl(t){return t>=48&&t<=55}B.regexp_eatFixedHexDigits=function(t,e){var n=t.pos;t.lastIntValue=0;for(var r=0;r<e;++r){var i=t.current();if(!el(i))return t.pos=n,!1;t.lastIntValue=16*t.lastIntValue+tl(i),t.advance()}return!0};var Is=function(t){this.type=t.type,this.value=t.value,this.start=t.start,this.end=t.end,t.options.locations&&(this.loc=new Kr(t,t.startLoc,t.endLoc)),t.options.ranges&&(this.range=[t.start,t.end])},X=Ie.prototype;X.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 Is(this)),this.lastTokEnd=this.end,this.lastTokStart=this.start,this.lastTokEndLoc=this.endLoc,this.lastTokStartLoc=this.startLoc,this.nextToken()};X.getToken=function(){return this.next(),new Is(this)};typeof Symbol<"u"&&(X[Symbol.iterator]=function(){var t=this;return{next:function(){var e=t.getToken();return{done:e.type===g.eof,value:e}}}});X.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(g.eof);if(t.override)return t.override(this);this.readToken(this.fullCharCodeAtPos())};X.readToken=function(t){return Nt(t,this.options.ecmaVersion>=6)||t===92?this.readWord():this.getTokenFromCode(t)};X.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};X.fullCharCodeAtPos=function(){return this.fullCharCodeAt(this.pos)};X.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=Co(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())};X.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&&!xn(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())};X.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&&No.test(String.fromCharCode(t)))++this.pos;else break e}}};X.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)};X.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(g.ellipsis)):(++this.pos,this.finishToken(g.dot))};X.readToken_slash=function(){var t=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):t===61?this.finishOp(g.assign,2):this.finishOp(g.slash,1)};X.readToken_mult_modulo_exp=function(t){var e=this.input.charCodeAt(this.pos+1),n=1,r=t===42?g.star:g.modulo;return this.options.ecmaVersion>=7&&t===42&&e===42&&(++n,r=g.starstar,e=this.input.charCodeAt(this.pos+2)),e===61?this.finishOp(g.assign,n+1):this.finishOp(r,n)};X.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(g.assign,3)}return this.finishOp(t===124?g.logicalOR:g.logicalAND,2)}return e===61?this.finishOp(g.assign,2):this.finishOp(t===124?g.bitwiseOR:g.bitwiseAND,1)};X.readToken_caret=function(){var t=this.input.charCodeAt(this.pos+1);return t===61?this.finishOp(g.assign,2):this.finishOp(g.bitwiseXOR,1)};X.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||ze.test(this.input.slice(this.lastTokEnd,this.pos)))?(this.skipLineComment(3),this.skipSpace(),this.nextToken()):this.finishOp(g.incDec,2):e===61?this.finishOp(g.assign,2):this.finishOp(g.plusMin,1)};X.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(g.assign,n+1):this.finishOp(g.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(g.relational,n))};X.readToken_eq_excl=function(t){var e=this.input.charCodeAt(this.pos+1);return e===61?this.finishOp(g.equality,this.input.charCodeAt(this.pos+2)===61?3:2):t===61&&e===62&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(g.arrow)):this.finishOp(t===61?g.eq:g.prefix,1)};X.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(g.questionDot,2)}if(e===63){if(t>=12){var r=this.input.charCodeAt(this.pos+2);if(r===61)return this.finishOp(g.assign,3)}return this.finishOp(g.coalesce,2)}}return this.finishOp(g.question,1)};X.readToken_numberSign=function(){var t=this.options.ecmaVersion,e=35;if(t>=13&&(++this.pos,e=this.fullCharCodeAtPos(),Nt(e,!0)||e===92))return this.finishToken(g.privateId,this.readWord1());this.raise(this.pos,"Unexpected character \'"+Mt(e)+"\'")};X.getTokenFromCode=function(t){switch(t){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(g.parenL);case 41:return++this.pos,this.finishToken(g.parenR);case 59:return++this.pos,this.finishToken(g.semi);case 44:return++this.pos,this.finishToken(g.comma);case 91:return++this.pos,this.finishToken(g.bracketL);case 93:return++this.pos,this.finishToken(g.bracketR);case 123:return++this.pos,this.finishToken(g.braceL);case 125:return++this.pos,this.finishToken(g.braceR);case 58:return++this.pos,this.finishToken(g.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(g.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(g.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character \'"+Mt(t)+"\'")};X.finishOp=function(t,e){var n=this.input.slice(this.pos,this.pos+e);return this.pos+=e,this.finishToken(t,n)};X.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(ze.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 kt(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(g.regexp,{pattern:i,flags:a,value:l})};X.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 L_(t,e){return e?parseInt(t,8):parseFloat(t.replace(/_/g,""))}function rl(t){return typeof BigInt!="function"?null:BigInt(t.replace(/_/g,""))}X.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=rl(this.input.slice(e,this.pos)),++this.pos):Nt(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(g.num,n)};X.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=rl(this.input.slice(e,this.pos));return++this.pos,Nt(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(g.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")),Nt(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var s=L_(this.input.slice(e,this.pos),n);return this.finishToken(g.num,s)};X.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};X.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)):(xn(r)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return e+=this.input.slice(n,this.pos++),this.finishToken(g.string,e)};var il={};X.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(t){if(t===il)this.readInvalidTemplateToken();else throw t}this.inTemplateElement=!1};X.invalidStringToken=function(t,e){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw il;this.raise(t,e)};X.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===g.template||this.type===g.invalidTemplate)?n===36?(this.pos+=2,this.finishToken(g.dollarBraceL)):(++this.pos,this.finishToken(g.backQuote)):(t+=this.input.slice(e,this.pos),this.finishToken(g.template,t));if(n===92)t+=this.input.slice(e,this.pos),t+=this.readEscapedChar(!0),e=this.pos;else if(xn(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}};X.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(g.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")};X.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 Mt(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 xn(e)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(e)}};X.readHexChar=function(t){var e=this.pos,n=this.readInt(16,t);return n===null&&this.invalidStringToken(e,"Bad character escape sequence"),n};X.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($t(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?Nt:$t)(a,r)||this.invalidStringToken(s,"Invalid Unicode escape"),t+=Mt(a),n=this.pos}else break;e=!1}return t+this.input.slice(n,this.pos)};X.readWord=function(){var t=this.readWord1(),e=g.name;return this.keywords.test(t)&&(e=vs[t]),this.finishToken(e,t)};var O_="8.16.0";Ie.acorn={Parser:Ie,version:O_,defaultOptions:qi,Position:Wn,SourceLocation:Kr,getLineInfo:Io,Node:Zr,TokenType:J,tokTypes:g,keywordTypes:vs,TokContext:ct,tokContexts:de,isIdentifierChar:$t,isIdentifierStart:Nt,Token:Is,isNewLine:xn,lineBreak:ze,lineBreakG:o_,nonASCIIwhitespace:No};function As(t,e){return Ie.parse(t,e)}var{stringify:V_}=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 tr={"||":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},ft=17,j_={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:ft,ClassExpression:ft,FunctionExpression:ft,ObjectExpression:ft,UpdateExpression:16,UnaryExpression:15,AwaitExpression:15,BinaryExpression:14,LogicalExpression:13,ConditionalExpression:4,AssignmentExpression:3,YieldExpression:2,RestElement:1};function pn(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 sl(t,e,n,r){let i=t.expressionsPrecedence[e.type];if(i===ft)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?tr[e.operator]<=tr[n.operator]:tr[e.operator]<tr[n.operator]}function nr(t,e,n,r){let{generator:i}=t;sl(t,e,n,r)?(t.write("("),i[e.type](e,t),t.write(")")):i[e.type](e,t)}function $_(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 Le(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("/*"),$_(t,a.value,n,r),t.write("*/"+r))}}function W_(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 fi(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 va,Ea,Sa,Ca,Na,ka,Ts={Program(t,e){let n=e.indent.repeat(e.indentLevel),{lineEnd:r,writeComments:i}=e;i&&t.comments!=null&&Le(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&&Le(e,l.comments,n,r),e.write(n),this[l.type](l,e),e.write(r)}i&&t.trailingComments!=null&&Le(e,t.trailingComments,n,r)},BlockStatement:ka=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&&Le(e,t.comments,s,r);let{length:o}=a;for(let l=0;l<o;l++){let c=a[l];i&&c.comments!=null&&Le(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),Le(e,t.comments,s,r),e.write(n));i&&t.trailingComments!=null&&Le(e,t.trailingComments,s,r),e.write("}"),e.indentLevel--},ClassBody:ka,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===ft||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&&Le(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&&Le(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"?fi(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:va=function(t,e){e.write(`for ${t.await?"await ":""}(`);let{left:n}=t;n.type[0]==="V"?fi(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:va,DebuggerStatement(t,e){e.write("debugger;",t)},FunctionDeclaration:Ea=function(t,e){e.write((t.async?"async ":"")+(t.generator?"function* ":"function ")+(t.id?t.id.name:""),t),pn(e,t.params),e.write(" "),this[t.body.type](t.body,e)},FunctionExpression:Ea,VariableDeclaration(t,e){fi(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===ft||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),pn(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]):pn(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:Sa=function(t,e){e.write("..."),this[t.argument.type](t.argument,e)},SpreadElement:Sa,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),nr(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){nr(e,t.tag,t),this[t.quasi.type](t.quasi,e)},ArrayExpression:Na=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:Na,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&&Le(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&&Le(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&&Le(e,t.trailingComments,s,r),e.write(n+"}")}else i?t.comments!=null?(e.write(r),Le(e,t.comments,s,r),t.trailingComments!=null&&Le(e,t.trailingComments,s,r),e.write(n+"}")):t.trailingComments!=null?(e.write(r),Le(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){pn(e,t.expressions)},UnaryExpression(t,e){if(t.prefix){let{operator:n,argument:r,argument:{type:i}}=t;e.write(n);let s=sl(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:Ca=function(t,e){let n=t.operator==="in";n&&e.write("("),nr(e,t.left,t,!1),e.write(" "+t.operator+" "),nr(e,t.right,t,!0),n&&e.write(")")},LogicalExpression:Ca,ConditionalExpression(t,e){let{test:n}=t,r=e.expressionsPrecedence[n.type];r===ft||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===ft||n<e.expressionsPrecedence.CallExpression||W_(t.callee)?(e.write("("),this[t.callee.type](t.callee,e),e.write(")")):this[t.callee.type](t.callee,e),pn(e,t.arguments)},CallExpression(t,e){let n=e.expressionsPrecedence[t.callee.type];n===ft||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("?."),pn(e,t.arguments)},ChainExpression(t,e){this[t.expression.type](t.expression,e)},MemberExpression(t,e){let n=e.expressionsPrecedence[t.object.type];n===ft||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(V_(t.value),t)},RegExpLiteral(t,e){let{regex:n}=t;e.write(`/${n.pattern}/${n.flags}`,t)}},U_={},q_=Ts,Hi=class{constructor(e){let n=e??U_;this.output="",n.output!=null?(this.output=n.output,this.write=this.writeToStream):this.output="",this.generator=n.generator!=null?n.generator:Ts,this.expressionsPrecedence=n.expressionsPrecedence!=null?n.expressionsPrecedence:j_,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 Ds(t,e){let n=new Hi(e);return n.generator[t.type](t,n),n.output}var z_=Object.defineProperty,K_=(t,e,n)=>e in t?z_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,re=(t,e,n)=>K_(t,typeof e!="symbol"?e+"":e,n),H_=new Set(["Infinity","NaN","undefined","null","true","false"]),G_=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"]),Gi=class{constructor(){re(this,"scopes",[]),re(this,"scopeTypes",[]),re(this,"scopeCounts",new Map),re(this,"contextBoundVars",new Set),re(this,"arrayPatternElements",new Set),re(this,"rootParams",new Set),re(this,"localSeriesVars",new Set),re(this,"varKinds",new Map),re(this,"loopVars",new Set),re(this,"loopVarNames",new Map),re(this,"paramIdCounter",0),re(this,"cacheIdCounter",0),re(this,"tempVarCounter",0),re(this,"taCallIdCounter",0),re(this,"userCallIdCounter",0),re(this,"plotCallIdCounter",0),re(this,"alertCallIdCounter",0),re(this,"loopGuardCounter",0),re(this,"hoistingStack",[]),re(this,"suppressHoisting",!1),re(this,"reservedNames",new Set),re(this,"userFunctions",new Set),re(this,"userMethods",new Set),re(this,"regularUserFunctions",new Set),re(this,"udtTypeNames",new Map),re(this,"udtInstances",new Map),re(this,"functionReturnTypes",new Map),re(this,"functionReturnTupleTypes",new Map),re(this,"functionParamUdtTypes",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++}`}}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)}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)}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 H_.has(e)||G_.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}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.hoistingStack[this.hoistingStack.length-1].push(e)}addOuterHoistedStatement(e){if(this.hoistingStack.length>0&&!this.suppressHoisting){let n=Math.min(1,this.hoistingStack.length-1);this.hoistingStack[n].push(e)}}getCurrentHoistingScope(){return this.hoistingStack.length===0?null:this.hoistingStack[this.hoistingStack.length-1]}setSuppressHoisting(e){this.suppressHoisting=e}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 mt(t,e,n,r,i){n||(n=A),(function s(a,o,l){var c=l||a.type;ol(n,c,a,o,s),e[c]&&e[c](a,o)})(t,r,i)}function al(t,e,n,r,i){var s=[];n||(n=A),(function a(o,l,c){var u=c||o.type,h=o!==s[s.length-1];h&&s.push(o),ol(n,u,o,l,a),e[u]&&e[u](o,l||s,s),h&&s.pop()})(t,r,i)}function Ne(t,e,n,r,i){var s=n?Y_(n,r||void 0):r;(function a(o,l,c){s[c||o.type](o,l,a)})(t,e,i)}function Y_(t,e){var n=Object.create(e||A);for(var r in t)n[r]=t[r];return n}function Ms(t,e,n){n(t,e)}function tn(t,e,n){}function ol(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 A={};A.Program=A.BlockStatement=A.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")}};A.Statement=Ms;A.EmptyStatement=tn;A.ExpressionStatement=A.ParenthesizedExpression=A.ChainExpression=function(t,e,n){return n(t.expression,e,"Expression")};A.IfStatement=function(t,e,n){n(t.test,e,"Expression"),n(t.consequent,e,"Statement"),t.alternate&&n(t.alternate,e,"Statement")};A.LabeledStatement=function(t,e,n){return n(t.body,e,"Statement")};A.BreakStatement=A.ContinueStatement=tn;A.WithStatement=function(t,e,n){n(t.object,e,"Expression"),n(t.body,e,"Statement")};A.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)}};A.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")}};A.ReturnStatement=A.YieldExpression=A.AwaitExpression=function(t,e,n){t.argument&&n(t.argument,e,"Expression")};A.ThrowStatement=A.SpreadElement=function(t,e,n){return n(t.argument,e,"Expression")};A.TryStatement=function(t,e,n){n(t.block,e,"Statement"),t.handler&&n(t.handler,e),t.finalizer&&n(t.finalizer,e,"Statement")};A.CatchClause=function(t,e,n){t.param&&n(t.param,e,"Pattern"),n(t.body,e,"Statement")};A.WhileStatement=A.DoWhileStatement=function(t,e,n){n(t.test,e,"Expression"),n(t.body,e,"Statement")};A.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")};A.ForInStatement=A.ForOfStatement=function(t,e,n){n(t.left,e,"ForInit"),n(t.right,e,"Expression"),n(t.body,e,"Statement")};A.ForInit=function(t,e,n){t.type==="VariableDeclaration"?n(t,e):n(t,e,"Expression")};A.DebuggerStatement=tn;A.FunctionDeclaration=function(t,e,n){return n(t,e,"Function")};A.VariableDeclaration=function(t,e,n){for(var r=0,i=t.declarations;r<i.length;r+=1){var s=i[r];n(s,e)}};A.VariableDeclarator=function(t,e,n){n(t.id,e,"Pattern"),t.init&&n(t.init,e,"Expression")};A.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")};A.Pattern=function(t,e,n){t.type==="Identifier"?n(t,e,"VariablePattern"):t.type==="MemberExpression"?n(t,e,"MemberPattern"):n(t,e)};A.VariablePattern=tn;A.MemberPattern=Ms;A.RestElement=function(t,e,n){return n(t.argument,e,"Pattern")};A.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")}};A.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")}};A.Expression=Ms;A.ThisExpression=A.Super=A.MetaProperty=tn;A.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")}};A.ObjectExpression=function(t,e,n){for(var r=0,i=t.properties;r<i.length;r+=1){var s=i[r];n(s,e)}};A.FunctionExpression=A.ArrowFunctionExpression=A.FunctionDeclaration;A.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")}};A.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")}};A.TemplateElement=tn;A.UnaryExpression=A.UpdateExpression=function(t,e,n){n(t.argument,e,"Expression")};A.BinaryExpression=A.LogicalExpression=function(t,e,n){n(t.left,e,"Expression"),n(t.right,e,"Expression")};A.AssignmentExpression=A.AssignmentPattern=function(t,e,n){n(t.left,e,"Pattern"),n(t.right,e,"Expression")};A.ConditionalExpression=function(t,e,n){n(t.test,e,"Expression"),n(t.consequent,e,"Expression"),n(t.alternate,e,"Expression")};A.NewExpression=A.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")}};A.MemberExpression=function(t,e,n){n(t.object,e,"Expression"),t.computed&&n(t.property,e,"Expression")};A.ExportNamedDeclaration=A.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)}};A.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)}};A.ImportAttribute=function(t,e,n){n(t.value,e,"Expression")};A.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)}};A.ImportExpression=function(t,e,n){n(t.source,e,"Expression"),t.options&&n(t.options,e,"Expression")};A.ImportSpecifier=A.ImportDefaultSpecifier=A.ImportNamespaceSpecifier=A.Identifier=A.PrivateIdentifier=A.Literal=tn;A.TaggedTemplateExpression=function(t,e,n){n(t.tag,e,"Expression"),n(t.quasi,e,"Expression")};A.ClassDeclaration=A.ClassExpression=function(t,e,n){return n(t,e,"Class")};A.Class=function(t,e,n){t.id&&n(t.id,e,"Pattern"),t.superClass&&n(t.superClass,e,"Expression"),n(t.body,e)};A.ClassBody=function(t,e,n){for(var r=0,i=t.body;r<i.length;r+=1){var s=i[r];n(s,e)}};A.MethodDefinition=A.PropertyDefinition=A.Property=function(t,e,n){t.computed&&n(t.key,e,"Expression"),t.value&&n(t.value,e,"Expression")};var ye="$",S={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){let n=this.createMemberExpression(this.createContextIdentifier(),this.createIdentifier("initVar"),!1),r=[t,e];return this.createCallExpression(n,r)},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}}},Wt=["ta","math","request","array","input","color","ticker","strategy"],yt=["hline","plot","fill","label","line","box","linefill","polyline","table","na","alert","time","time_close","dayofmonth","dayofweek","hour","minute","month","second","weekofyear","year"],Z_=["request.security","request.security_lower_tf"],X_=["chart.left_visible_bar_time","chart.right_visible_bar_time"],Ia=["plot","hline","fill","strategy.exit"],Q_=["line.new","line.copy","label.new","label.copy","polyline.new","box.new","box.copy","table.new","linefill.new"],J_=new Set([...Wt,"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","position","font","order","currency","dayofweek","adjustment","barmerge"]),Aa=new Set(["await","debugger","default","delete","extends","finally","function","implements","instanceof","interface","let","new","package","private","protected","public","static","super","throw","typeof","void","with","yield"]),ll=["open","high","low","close","volume","hl2","hlc3","ohlc4","hlcc4","openTime","closeTime"],Ps=[...Wt,"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","Type","bool","int","float","string","timeframe","syminfo","barstate","session","bar_index","last_bar_index","last_bar_time","timenow","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","barmerge","adjustment","backadjustment","earnings","dividends","splits"],e0=["na","nz","plot","plotchar","color","hline","fill"];function t0(t){let e=null,n=ye;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)})};Ne(t,{},{VariableDeclarator(d,f,m){s(d.id),d.init&&m(d.init,f)},FunctionDeclaration(d,f,m){s(d.id);for(let x of d.params)x&&x.type==="AssignmentPattern"&&x.right&&m(x.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=ll,o=Ps,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 n0(t){let e=null,n=ye;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(ll),i=new Set(Ps),s=new Set(e0),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"&&Wt.includes(c)){let h=c,p=l.id.name;h!==p&&(a.set(p,h),l.id.name=h)}}})}),a.size>0&&Ne(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 r0(t){try{let e=As(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 i0(t){return t.async=!0,Ds(t)}function s0(t){t=t.trim();let{isWrapped:e,isAsync:n,functionNode:r}=r0(t);return e&&r?n?t:i0(r):`async (context) => {\n${t}\n}`}function a0(t){Ne(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 o0(t,e){mt(t,{VariableDeclaration(r){for(let i of r.declarations)if(!(i.id?.type!=="Identifier"||!i.init)&&i.init.type==="CallExpression"&&i.init.callee?.type==="Identifier"&&i.init.callee.name==="Type"&&i.init.arguments?.length===1&&i.init.arguments[0]?.type==="ObjectExpression"){let s={};for(let a of i.init.arguments[0].properties)a.type!=="Property"||a.key?.type!=="Identifier"||(a.value?.type==="ArrayExpression"&&a.value.elements?.[0]?.type==="Literal"?s[a.key.name]=String(a.value.elements[0].value):a.value?.type==="Literal"&&(s[a.key.name]=String(a.value.value)));e.addUdtTypeName(i.id.name,s)}}});let n=!0;for(;n;)n=!1,mt(t,{FunctionDeclaration(r){if(!r.id?.name)return;let i=r.id.name;if(e.getFunctionReturnType(i)||e.getFunctionReturnTupleType(i))return;let s=l0(r.body);if(s.length===0)return;if(s.every(l=>l.type==="ArrayExpression")){let l=s[0].elements.length;if(l>0&&s.every(c=>c.elements.length===l)){let c=[],u=!0;for(let h=0;h<l;h++){let p=s.map(f=>Fn(f.elements[h],e)),d=p[0];if(!p.every(f=>f===d)){u=!1;break}c.push(d)}if(u&&c.some(h=>!!h)){e.setFunctionReturnTupleType(i,c),n=!0;return}}}let a=s.map(l=>Fn(l,e)),o=a[0];!o||!a.every(l=>l===o)||(e.setFunctionReturnType(i,o),n=!0)}});mt(t,{VariableDeclaration(r){for(let i of r.declarations)if(i.init){if(i.id?.type==="Identifier"){let s=Fn(i.init,e);s&&e.markVariableAsUdtInstance(i.id.name,s);continue}if(i.id?.type==="ArrayPattern"&&i.init.type==="CallExpression"&&i.init.callee?.type==="Identifier"){let s=e.getFunctionReturnTupleType(i.init.callee.name);if(!s)continue;i.id.elements?.forEach((a,o)=>{if(!a||a.type!=="Identifier")return;let l=s[o];l&&e.markVariableAsUdtInstance(a.name,l)})}}},ExpressionStatement(r){let i=r.expression;if(i?.type==="Literal"&&typeof i.value=="string"&&i.value.startsWith("__pineUdtVar:")){let s=i.value.match(/^__pineUdtVar:([A-Za-z_$][\\w$]*)=([A-Za-z_$][\\w$]*)$/);if(s){let[,a,o]=s;e.isUdtTypeName(o)&&e.markVariableAsUdtInstance(a,o)}}}}),mt(t,{ExpressionStatement(r){let i=r.expression;if(!i||i.type!=="AssignmentExpression"||i.operator!=="=")return;let s=i.left;if(s?.type!=="MemberExpression"||s.computed||s.property?.type!=="Identifier"||s.property.name!=="__pineParamTypes__"||s.object?.type!=="Identifier"||i.right?.type!=="ObjectExpression")return;let a=s.object.name,o=a.startsWith("$M_")?a.slice(3):a,l={};for(let c of i.right.properties){if(c.type!=="Property")continue;let u;if(c.key?.type==="Identifier"?u=c.key.name:c.key?.type==="Literal"&&typeof c.key.value=="string"&&(u=c.key.value),!u||c.value?.type!=="Literal"||typeof c.value.value!="string")continue;let h=c.value.value.split(/\\s+/).pop();e.isUdtTypeName(h)&&(l[u]=h)}Object.keys(l).length>0&&e.setFunctionParamUdtTypes(o,l)}})}function l0(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 Fn(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=Fn(t.consequent,e),r=Fn(t.alternate,e);if(n&&n===r)return n}}}function c0(t,e){mt(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===ye||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===ye||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 u0(t,e,n=!1){t.params.forEach(r=>{r.type==="Identifier"&&n&&e.addContextBoundVar(r.name,n)})}function p0(t,e){let n;return al(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.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=ye),u0(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=e.generateTempVar(),c={type:"VariableDeclaration",kind:r.kind,declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:l},init:o.init}]},u=c.declarations[0].init;u&&u.type==="CallExpression"&&(u.callee.type==="ArrowFunctionExpression"||u.callee.type==="FunctionExpression")&&mt(u.callee.body,{ReturnStatement(p){p.argument&&p.argument.type==="ArrayExpression"&&(p.argument={type:"ArrayExpression",elements:[p.argument]})}}),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:l},property:{type:"Literal",value:d},computed:!0}}]}));Object.assign(r,{type:"BlockStatement",body:[c,...h]})}})},ForStatement(r){}}),n}var h0=Object.defineProperty,d0=(t,e,n)=>e in t?h0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,f0=(t,e,n)=>d0(t,typeof e!="symbol"?e+"":e,n),m0=new Set(["bar_index","last_bar_index","time","time_close","timenow","year","month","weekofyear","dayofmonth","dayofweek","hour","minute","second"]),y0=new Set(["input.int","math.floor","math.ceil","array.size","matrix.rows","matrix.columns","str.length","timestamp","ta.barssince","ta.highestbars","ta.lowestbars"]);function g0(t){return t&&t.type==="Literal"&&typeof t.value=="number"&&Number.isInteger(t.value)&&!(typeof t.raw=="string"&&/[.eE]/.test(t.raw))}function _0(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 x0(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 Yi(t,e){return t!=="notint"&&e!=="notint"?"int":"notint"}var Zi=class{constructor(){f0(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,Yi(this.stack[r].get(e),n));return}this.stack[this.stack.length-1].set(e,Yi(n,n))}};function b0(t,e){let n=new Zi,r=x0(t);function i(a){if(!a||typeof a!="object")return"notint";switch(a.type){case"Literal":return typeof a.value=="number"&&g0(a)?"constint":"notint";case"Identifier":return m0.has(a.name)?"int":n.get(a.name)??"notint";case"UnaryExpression":return a.operator==="-"||a.operator==="+"?i(a.argument):(i(a.argument),"notint");case"BinaryExpression":{let o=i(a.left),l=i(a.right);if(a.operator==="/"){if(o==="constint"&&l==="constint"){let c=S.createMathIntDivCall(a.left,a.right);return Object.assign(a,c),"constint"}return"notint"}return a.operator==="+"||a.operator==="-"||a.operator==="*"||a.operator==="%"?o==="constint"&&l==="constint"?"constint":o!=="notint"&&l!=="notint"?"int":"notint":"notint"}case"ConditionalExpression":{i(a.test);let o=i(a.consequent),l=i(a.alternate);return Yi(o,l)}case"LogicalExpression":return i(a.left),i(a.right),"notint";case"CallExpression":{a.callee?.type==="MemberExpression"&&i(a.callee.object);for(let l of a.arguments||[])i(l);let o=_0(a.callee);return o&&y0.has(o)?"int":"notint"}case"MemberExpression":return i(a.object),a.computed&&i(a.property),"notint";case"VariableDeclaration":{for(let o of a.declarations||[]){let l=o.init?i(o.init):"notint";o.id?.type==="Identifier"&&(l==="constint"&&(a.kind==="var"||r.has(o.id.name))&&(l="int"),n.set(o.id.name,l))}return"notint"}case"AssignmentExpression":{let o=i(a.right);return a.left?.type==="Identifier"?n.assign(a.left.name,o):i(a.left),o}case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":{n.push();for(let o of a.params||[]){let l=o.type==="AssignmentPattern"?o.left:o;l?.type==="Identifier"&&n.set(l.name,"notint")}return i(a.body),n.pop(),"notint"}default:return s(a),"notint"}}function s(a){for(let o in a){if(o==="type"||o==="start"||o==="end"||o==="loc"||o==="raw")continue;let l=a[o];if(Array.isArray(l))for(let c of l)c&&typeof c.type=="string"&&i(c);else l&&typeof l.type=="string"&&i(l)}}i(t)}var Ar={type:"Identifier",name:"undefined"};function Bn(t,e){let n={type:"Identifier",name:`\'${e}\'`};if(!t.isInsideFunctionScope())return n;let[r]=t.getVariable("$$");return r?{type:"BinaryExpression",operator:"+",left:S.createMemberExpression(S.createLocalContextIdentifier(),S.createIdentifier("id")),right:n}:n}function ke(t,e){let[n,r]=e.getVariable(t);if((n.match(/^fn\\d+_/)||e.isVariableInFunctionScope(t))&&t!=="$$"){let[i]=e.getVariable("$$");if(i)return S.createLocalContextVariableReference(r,n)}return S.createContextVariableReference(r,n)}function Xi(t,e){let n=ke(t,e);return S.createGetCall(n,0)}function nn(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=S.createIdentifier(t.object.name);n._skipTransformation=!0;let r=S.createGetCall(n,t.property);Object.assign(t,r),t._indexTransformed=!0;return}if(!e.isContextBound(t.object.name)){let n=ke(t.object.name,e),r=S.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=S.createIdentifier(t.property.name);n._skipTransformation=!0,t.property=S.createGetCall(n,0)}else t.property=ke(t.property.name,e),t.property=S.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=S.createIdentifier(t.object.name);n._skipTransformation=!0;let r=S.createGetCall(n,t.property);Object.assign(t,r),t._indexTransformed=!0;return}if(e.isContextBound(t.object.name)||(t.object=ke(t.object.name,e)),t.property.type==="MemberExpression"){let n=t.property;n._indexTransformed||(nn(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=Ct(t.property,e))}function Ve(t,e){let n=S.createGetCall(S.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 Ce(t,e){if(!t._skipTransformation&&t.name!==ye){if(yt.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=S.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===ye&&["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"&&Wt.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===ye&&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=ke(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=S.createIdentifier(t.name),d=S.createGetCall(p,0);Object.assign(t,d)}return}let[c,u]=e.getVariable(t.name),h;if(l)h=S.createIdentifier(t.name);else{if(c===t.name&&!e.isContextBound(t.name))return;h=ke(t.name,e)}if(a)Object.assign(t,h);else{let p=S.createGetCall(h,0);Object.assign(t,p)}}}function _e(t,e,n){if(t.object&&t.object.type==="Identifier"&&t.object.name==="Math")return;if(t.computed&&t.object&&t.object.type==="CallExpression"&&!t._historyTransformed){t.object._transformed||we(t.object,n);let l=n.generateParamId(),c={type:"CallExpression",callee:S.createMemberExpression(S.createContextIdentifier(),S.createIdentifier("param")),arguments:[t.object,Ar,Bn(n,l)],_transformed:!0,_isParamCall:!0},u=S.createGetCall(c,t.property);u._transformed=!0,u._historyTransformed=!0,Object.assign(t,u),delete t.object,delete t.property,delete t.computed;return}if(t.object&&t.object.type==="Identifier"&&Wt.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=S.createIdentifier(t.object.name);l._skipTransformation=!0,t.object=S.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||(nn(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===ye||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"&&yt.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=S.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=S.createIdentifier(c);return p._skipTransformation=!0,p})():ke(c,n);l.object=S.createGetCall(u,t.property);let h=t.object;Object.assign(t,h),delete t.computed;return}}}function Ln(t,e){if(t.type==="Identifier"){if(yt.includes(t.name)&&e.isContextBound(t.name)){let s=t.name;return Object.assign(t,{type:"MemberExpression",object:{type:"Identifier",name:s},property:{type:"Identifier",name:"__value"},computed:!1}),delete t.name,t}if(e.isLoopVariable(t.name))return t;if(e.isRootParam(t.name)){let[s,a]=e.getVariable(t.name);return S.createContextVariableReference(a,s)}if(e.isContextBound(t.name))return t;let[n,r]=e.getVariable(t.name),i=n!==t.name;return e.isLocalSeriesVar(t.name)&&!i?t:i?ke(t.name,e):n===t.name&&!e.isContextBound(t.name)?t:ke(t.name,e)}return t}function Ct(t,e,n=""){switch(t.type){case"BinaryExpression":return lr(t,e,n);case"LogicalExpression":return cr(t,e,n);case"MemberExpression":{let r=!t.computed&&t.object.type==="Identifier"&&yt.includes(t.object.name)&&e.isContextBound(t.object.name);if(t.computed&&t.object.type==="Identifier"&&yt.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 S.createGetCall(a,t.property)}let i=t.object.type==="Identifier"&&!r?Ln(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=S.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=Ln(t,e);return r.type==="Identifier"&&(r.name==="NaN"||r.name==="undefined"||r.name==="Infinity"||r.name==="null"||r.name==="Math")?r:S.createGetCall(r,0)}case"UnaryExpression":return ur(t,e,n);case"ConditionalExpression":{let r=Ct(t.test,e,n),i=Ct(t.consequent,e,n),s=Ct(t.alternate,e,n);return{type:"ConditionalExpression",test:r,consequent:i,alternate:s,start:t.start,end:t.end}}}return t}function lr(t,e,n){let r=Ct(t.left,e,n),i=Ct(t.right,e,n),s={type:"BinaryExpression",operator:t.operator,left:r,right:i,start:t.start,end:t.end};return Ne(s,e,{CallExpression(a,o){a._transformed||we(a,o)},MemberExpression(a){_e(a,"",e)}}),s}function cr(t,e,n){let r=Ct(t.left,e,n),i=Ct(t.right,e,n),s={type:"LogicalExpression",operator:t.operator,left:r,right:i,start:t.start,end:t.end};return Ne(s,e,{CallExpression(a,o){a._transformed||we(a,o)}}),s}function mi(t,e,n){Ne(t,{parent:t,inNamespaceCall:!1},{Identifier(a,o,l){if(a.name=="NaN")return;if(yt.includes(a.name)&&e.isContextBound(a.name)){if(o.parent&&o.parent.type==="MemberExpression"&&o.parent.object===a&&!o.parent.computed)return;let u={type:"MemberExpression",object:{type:"Identifier",name:a.name},property:{type:"Identifier",name:"__value"},computed:!1},h=S.createGetCall(u,0);Object.assign(a,h),delete a.name;return}a.parent=o.parent,Ce(a,e);let c=a.parent&&a.parent.type==="BinaryExpression";(a.parent&&a.parent.type==="ConditionalExpression"||c)&&(a.type==="MemberExpression"?nn(a,e):a.type==="Identifier"&&(a.parent&&a.parent.type==="CallExpression"&&a.parent.callee&&a.parent.callee.object&&a.parent.callee.object.name===ye&&a.parent.callee.property.name==="get"||Ve(a)))},MemberExpression(a,o,l){_e(a,"",e),a.object&&l(a.object,{parent:a,inNamespaceCall:o.inNamespaceCall})},ConditionalExpression(a,o,l){let c={...o,parent:a};a.test&&l(a.test,c),a.consequent&&l(a.consequent,c),a.alternate&&l(a.alternate,c)},BinaryExpression(a,o,l){let c={...o,parent:a};l(a.left,c),l(a.right,c)},LogicalExpression(a,o,l){let c={...o,parent:a};l(a.left,c),l(a.right,c)},UnaryExpression(a,o,l){let c={...o,parent:a};l(a.argument,c)},CallExpression(a,o,l){let c=a.callee&&a.callee.type==="MemberExpression"&&a.callee.object&&a.callee.object.type==="Identifier"&&e.isContextBound(a.callee.object.name);we(a,e),a.arguments.forEach(u=>l(u,{parent:a,inNamespaceCall:c||o.inNamespaceCall}))}});let r=S.createMemberExpression(S.createIdentifier(n),S.createIdentifier("param")),i=e.generateParamId(),s={type:"CallExpression",callee:r,arguments:[t,Ar,Bn(e,i)],_transformed:!0,_isParamCall:!0};if(!e.shouldSuppressHoisting()){let a=i;e.addLocalSeriesVar(a);let o=S.createVariableDeclaration(a,s);return e.addHoistedStatement(o),S.createIdentifier(a)}return s}function ur(t,e,n){let r=Ct(t.argument,e,n),i={type:"UnaryExpression",operator:t.operator,prefix:t.prefix,argument:r,start:t.start,end:t.end};return Ne(i,e,{CallExpression(s,a){s._transformed||we(s,a)},MemberExpression(s){_e(s,"",e)}}),i}function Gt(t,e,n){switch(t?.type){case"BinaryExpression":t=lr(t,n,e);break;case"LogicalExpression":t=cr(t,n,e);break;case"ConditionalExpression":return mi(t,n,e);case"UnaryExpression":t=ur(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 c;if(n.isLocalSeriesVar(c.name)){let u=S.createIdentifier(c.name);return S.createGetCall(u,0)}return Xi(c.name,n)}return c.type==="CallExpression"?(we(c,n),c):c.type==="BinaryExpression"?lr(c,n,e):c.type==="LogicalExpression"?cr(c,n,e):c.type==="ConditionalExpression"?mi(c,n,e):c.type==="UnaryExpression"?ur(c,n,e):(c.type==="MemberExpression"&&_e(c,e,n),c)});break}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 f=t.object;for(;f.object&&f.object.type==="MemberExpression";)f=f.object;if(f.object?.type==="Identifier"&&n.isUdtInstance(f.object.name)){let m=f.object.name,x=n.isLocalSeriesVar(m)?(()=>{let b=S.createIdentifier(m);return b._skipTransformation=!0,b})():ke(m,n);return f.object=S.createGetCall(x,t.property),t.object}}if(t.object.type==="CallExpression")we(t.object,n);else if(t.object.type==="MemberExpression"){_e(t.object,"",n);let f=t.object;for(;f&&f.type==="MemberExpression"&&f.object;){if(f.object.type==="Identifier"){let m=f.object,[x]=n.getVariable(m.name);x!==m.name&&!n.isContextBound(m.name)&&!n.isRootParam(m.name)&&!n.isLoopVariable(m.name)&&!n.isLocalSeriesVar(m.name)&&!yt.includes(m.name)&&!Wt.includes(m.name)&&(f.object=Xi(m.name,n));break}f=f.object}}else t.object.type==="BinaryExpression"?t.object=lr(t.object,n,e):t.object.type==="LogicalExpression"?t.object=cr(t.object,n,e):t.object.type==="ConditionalExpression"?t.object=mi(t.object,n,e):t.object.type==="UnaryExpression"&&(t.object=ur(t.object,n,e));let c=t.object.type==="Identifier"&&n.isContextBound(t.object.name)&&!n.isRootParam(t.object.name)?t.object:Ln(t.object,n),u;t.property.type==="Identifier"&&!n.isContextBound(t.property.name)&&!n.isLoopVariable(t.property.name)?u=S.createGetCall(Ln(t.property,n),0):t.property.type==="BinaryExpression"||t.property.type==="UnaryExpression"||t.property.type==="LogicalExpression"||t.property.type==="ConditionalExpression"?u=Ct(t.property,n,e):u=t.property;let h=S.createMemberExpression(S.createIdentifier(e),S.createIdentifier("param")),p=n.generateParamId(),d={type:"CallExpression",callee:h,arguments:[c,u,Bn(n,p)],_transformed:!0,_isParamCall:!0};if(!n.shouldSuppressHoisting()){let f=p;n.addLocalSeriesVar(f);let m=S.createVariableDeclaration(f,d);return n.addHoistedStatement(m),S.createIdentifier(f)}return d}if(i){if(t.object.type==="Identifier"&&Wt.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=S.createVariableDeclaration(h,u);return n.addOuterHoistedStatement(p),Object.assign(t,S.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=ke(c,n),d=S.createGetCall(p,0);t.object=d}else if(n.isLocalSeriesVar(c)){let p=S.createIdentifier(c);p._skipTransformation=!0,t.object=S.createGetCall(p,0)}}else t.object.type==="MemberExpression"?Gt(t.object,e,n):t.object.type==="CallExpression"&&(t.object._transformed||we(t.object,n))}if(t.type==="ObjectExpression"&&(t.properties=t.properties.map(c=>c.value.name?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:S.createIdentifier(c.value.name),kind:"init",method:!1,shorthand:!1,computed:!1}:{type:"Property",key:{type:"Identifier",name:c.key.name},value:ke(c.value.name,n),kind:"init",method:!1,shorthand:!1,computed:!1}:(c.value.type!=="Literal"&&(c.value=Gt(c.value,e,n)),c))),t.type==="Identifier"){if(yt.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=S.createMemberExpression(S.createIdentifier(e),S.createIdentifier("param")),u=n.generateParamId(),h={type:"CallExpression",callee:c,arguments:[t,Ar,Bn(n,u)],_transformed:!0,_isParamCall:!0};if(!n.shouldSuppressHoisting()){let p=u;n.addLocalSeriesVar(p);let d=S.createVariableDeclaration(p,h);return n.addHoistedStatement(d),S.createIdentifier(p)}return h}}t?.type==="CallExpression"&&we(t,n);let s=S.createMemberExpression(S.createIdentifier(e),S.createIdentifier("param")),a=t.type==="Identifier"?Ln(t,n):t,o=n.generateParamId(),l={type:"CallExpression",callee:s,arguments:[a,Ar,Bn(n,o)],_transformed:!0,_isParamCall:!0};if(!n.shouldSuppressHoisting()){let c=o;n.addLocalSeriesVar(c);let u=S.createVariableDeclaration(c,l);return n.addHoistedStatement(u),S.createIdentifier(c)}return l}function kn(t){if(!t)return!1;if(cl(t))return!0;if(t.type==="MemberExpression")return kn(t.object);if(t.type==="ChainExpression")return kn(t.expression);if(t.type==="CallExpression"){let e=t.callee;if(e?.type==="MemberExpression")return kn(e.object);if(e?.type==="ChainExpression")return kn(e.expression)}return!1}function cl(t){return t?.type==="CallExpression"&&t.callee?.type==="MemberExpression"&&t.callee.object?.name==="$"&&t.callee.property?.name==="get"}function Qi(t,e,n){t&&(t.type==="Identifier"?(t.parent=e,Ce(t,n)):t.type==="MemberExpression"?Qi(t.object,t,n):t.type==="CallExpression"&&(t.callee&&t.callee.type==="MemberExpression"&&Qi(t.callee.object,t.callee,n),t._transformed||we(t,n)))}function we(t,e,n){if(t._transformed)return;t.callee&&t.callee.name,t.callee&&t.callee.type==="Identifier"&&(Wt.includes(t.callee.name)||yt.includes(t.callee.name))&&e.isContextBound(t.callee.name)&&(t.callee=S.createMemberExpression(t.callee,S.createIdentifier("any")));let r=t.callee&&t.callee.type==="MemberExpression"&&t.callee.object&&t.callee.object.type==="Identifier"&&(e.isContextBound(t.callee.object.name)||t.callee.object.name==="math"||t.callee.object.name==="ta");if(r){if(t.callee.object.name===ye&&["get","init","param"].includes(t.callee.property.name))return;let i=t.callee.object.name,s=[];t.arguments.forEach(p=>{if(p._isParamCall){s.push(p);return}s.push(Gt(p,i,e))}),t.arguments=s;let a=t.callee.property.name,o=`${i}.${a}`;if(Ia.includes(i)||Ia.includes(o)){let p=e.getNextPlotCallId();t.arguments.push({type:"ObjectExpression",properties:[{type:"Property",key:{type:"Identifier",name:"__callsiteId"},value:p,kind:"init",computed:!1,shorthand:!1}]})}if(i==="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}]}),i==="alert"){let p=e.getNextAlertCallId();t.arguments.push({type:"ObjectExpression",properties:[{type:"Property",key:{type:"Identifier",name:"__callsiteId"},value:p,kind:"init",computed:!1,shorthand:!1}]})}if(i==="ta")if(e.getCurrentScopeType()==="fn"){let p=e.getNextTACallId(),[d]=e.getVariable("$$"),f;d?f=S.createMemberExpression(S.createLocalContextIdentifier(),S.createIdentifier("id")):f=S.createLiteral("");let m={type:"BinaryExpression",operator:"+",left:f,right:p};t.arguments.push(m)}else t.arguments.push(e.getNextTACallId());let l=t.callee.property.name,c=`${i}.${l}`,u=Z_.includes(c),h=t._insideAwait===!0;if(u&&!h){let p=Object.assign({},t),d=S.createAwaitExpression(p);Object.assign(t,d)}if(!e.shouldSuppressHoisting()){let p=e.generateTempVar();e.addLocalSeriesVar(p);let d=t._insideAwait===!0,f=Object.assign({},t);d&&(f=S.createAwaitExpression(f));let m=S.createVariableDeclaration(p,f);e.addHoistedStatement(m);let x=S.createIdentifier(p);Object.assign(t,x),t._wasHoisted=!0,t._wasInsideAwait=d;return}t._transformed=!0}else if(t.callee&&t.callee.type==="Identifier"){if(t.arguments=t.arguments.map(i=>i._isParamCall?i:Gt(i,ye,e)),!e.isContextBound(t.callee.name)){let i=e.getNextUserCallId(),s=S.createMemberExpression(S.createContextIdentifier(),S.createIdentifier("call")),a=t.callee.name,o=t.callee;e.isUserMethod(a)&&!e.isRegularUserFunction(a)&&(o=S.createIdentifier(`$M_${a}`),o._skipTransformation=!0);let l=[o,i,...t.arguments];t.callee=s,t.arguments=l}t._transformed=!0}if(!r&&t.callee&&t.callee.type==="MemberExpression"){let i=t.callee.property.name,s=e.isUserFunction(i),a=t.callee.object,o=a.type==="Identifier"&&e.isLocalSeriesVar(a.name),l=a.type==="MemberExpression",c=e.isUserMethod(i),u=!!a.name&&e.isUdtInstance(a.name);if(s&&c&&!e.isContextBound(i)&&!o&&!l&&u){let h=t.callee.object;t.callee.property;let p=t.arguments.map(w=>w._isParamCall?w:Gt(w,ye,e)),d=h;h.type==="Identifier"?d=Gt(h,ye,e):h.type==="CallExpression"&&(we(h,e),d=Gt(h,ye,e));let f=S.createMemberExpression(S.createContextIdentifier(),S.createIdentifier("call")),m=e.getNextUserCallId(),x=S.createIdentifier(`$M_${i}`);x._skipTransformation=!0;let b=[x,m,d,...p];t.callee=f,t.arguments=b,t._transformed=!0;return}t.callee.object.type==="Identifier"?Ce(t.callee.object,e):Qi(t.callee.object,t.callee,e)}if(t.arguments.forEach(i=>{Ne(i,{parent:t},{Identifier(s,a,o){s.parent=a.parent,Ce(s,e);let l=s.parent&&s.parent.type==="BinaryExpression";(s.parent&&s.parent.type==="ConditionalExpression"||l)&&(s.type==="MemberExpression"?nn(s,e):s.type==="Identifier"&&(s.parent&&s.parent.type==="CallExpression"&&s.parent.callee&&s.parent.callee.object&&s.parent.callee.object.name===ye&&s.parent.callee.property.name==="get"||Ve(s)))},BinaryExpression(s,a,o){let l={...a,parent:s};o(s.left,l),o(s.right,l)},LogicalExpression(s,a,o){let l={...a,parent:s};o(s.left,l),o(s.right,l)},UnaryExpression(s,a,o){let l={...a,parent:s};o(s.argument,l)},CallExpression(s,a,o){s.callee&&s.callee.type==="MemberExpression"&&s.callee.object&&(s.callee.object.parent=s.callee,o(s.callee.object,{parent:s.callee})),s._transformed||we(s,e)},MemberExpression(s,a,o){_e(s,"",e),s.object&&o(s.object,{parent:s})}})}),t.callee&&t.callee.type==="MemberExpression"){let i=t.callee.object,s=cl(i),a=i?.type==="MemberExpression"&&kn(i);if(s||a){let o=Object.assign({},t.callee,{optional:!0});t.callee={type:"ChainExpression",expression:o},t.optional=!0}}}function Rs(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:"ThrowStatement",argument:{type:"NewExpression",callee:{type:"Identifier",name:"Error"},arguments:[{type:"Literal",value:`Loop exceeded maximum iterations (${t})`}]}},alternate:null};return{counterDecl:e,guardCheck:n}}function Tr(t,e){let n=null;if(t.left.type==="Identifier")n=ke(t.left.name,e);else if(t.left.type==="MemberExpression"&&t.left.computed){if(t.left.object.type==="Identifier"){let r=t.left.object.name,[i,s]=e.getVariable(r),a=i!==r,o=e.isContextBound(r);(a||o)&&!e.isLoopVariable(r)&&t.left.property.type==="Literal"&&t.left.property.value===0&&(n=ke(r,e))}}else if(t.left.type==="MemberExpression"&&!t.left.computed){let r=null,i=t.left;for(;i.type==="MemberExpression"&&!i.computed;){if(i.object.type==="Identifier"){r=i;break}i=i.object}if(r){let s=r.object.name,[a,o]=e.getVariable(s);if(a!==s&&!e.isLoopVariable(s)){let l=ke(s,e),c=S.createGetCall(l,0);r.object=c}else if(e.isLocalSeriesVar(s)){let l=S.createIdentifier(s);l._skipTransformation=!0,r.object=S.createGetCall(l,0)}}}if(Ne(t.right,{parent:t.right,inNamespaceCall:!1},{Identifier(r,i,s){let a=i.parent&&i.parent.type==="MemberExpression"&&!i.parent.computed&&i.parent.object===r;if(yt.includes(r.name)&&e.isContextBound(r.name)&&!a){let m={type:"MemberExpression",object:{type:"Identifier",name:r.name},property:{type:"Identifier",name:"__value"},computed:!1},x=S.createGetCall(m,0);Object.assign(r,x),delete r.name;return}r.parent=i.parent,Ce(r,e);let o=r.parent&&r.parent.type==="BinaryExpression",l=r.parent&&r.parent.type==="ConditionalExpression",c=e.isContextBound(r.name)&&!e.isRootParam(r.name),u=r.parent&&r.parent.type==="MemberExpression"&&r.parent.computed&&r.parent.object===r,h=r.parent&&r.parent._isParamCall,p=r.parent&&r.parent.type==="MemberExpression",d=r.name==="NaN",f=r.parent&&r.parent.type==="CallExpression"&&r.parent.callee&&r.parent.callee.object&&r.parent.callee.object.name===ye&&r.parent.callee.property.name==="get";(c||l||o)&&(r.type==="MemberExpression"?nn(r,e):r.type==="Identifier"&&!p&&!u&&!h&&!d&&!f&&Ve(r))},MemberExpression(r,i,s){_e(r,"",e),r.type==="CallExpression"?r.arguments.forEach(a=>s(a,{parent:r,inNamespaceCall:i.inNamespaceCall})):r.object&&s(r.object,{parent:r,inNamespaceCall:i.inNamespaceCall})},CallExpression(r,i,s){let a=r.callee&&r.callee.type==="MemberExpression"&&r.callee.object&&r.callee.object.type==="Identifier"&&e.isContextBound(r.callee.object.name);we(r,e),r.type==="CallExpression"&&(r.callee.type==="MemberExpression"&&s(r.callee,{parent:r,inNamespaceCall:a||i.inNamespaceCall}),r.arguments.forEach(o=>s(o,{parent:r,inNamespaceCall:a||i.inNamespaceCall})))}}),n){let r=t.right;if(t.operator!=="="){let s=t.operator.replace("=",""),a=S.createGetCall(n,0);r={type:"BinaryExpression",operator:s,left:a,right:t.right,start:t.start,end:t.end}}let i=S.createSetCall(n,r);t.start&&(i.start=t.start),t.end&&(i.end=t.end),Object.assign(t,i)}}function ul(t,e){t._skipTransformation||t.declarations.forEach(n=>{if(n.init?.type==="CallExpression"&&n.id?.type==="Identifier"){let p=n.init.callee;(p?.type==="MemberExpression"&&p.object?.type==="Identifier"&&p.object.name==="input"||p?.type==="Identifier"&&p.name==="input")&&(n.init._varId=n.id.name)}if(n.init&&n.init.type==="Identifier"&&yt.includes(n.init.name)&&e.isContextBound(n.init.name)){let p=n.init.name;Object.assign(n.init,{type:"MemberExpression",object:{type:"Identifier",name:p},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===ye||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===ye||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(p=>{p.key.name&&e.addContextBoundVar(p.key.name)}),n.init.object.name=ye;return}if(i){n.id.name&&e.addContextBoundVar(n.id.name),n.id.properties&&n.id.properties.forEach(p=>{p.key.name&&e.addContextBoundVar(p.key.name)}),n.init.object.object.name=ye;return}e.addVariable(n.id.name,t.kind);let a=t.kind,o=e.isArrayPatternElement(n.id.name)&&n.init&&n.init.type==="MemberExpression"&&n.init.computed;n.init&&!s&&!o&&(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)?we(n.init,e):Ne(n.init,{parent:n.init},{Identifier(p,d){p.parent=d.parent,Ce(p,e);let f=p.parent&&p.parent.type==="BinaryExpression",m=p.parent&&p.parent.type==="UnaryExpression",x=p.parent&&p.parent.type==="ConditionalExpression",b=p.parent&&p.parent.type==="CallExpression"&&p.parent.callee&&p.parent.callee.object&&p.parent.callee.object.name===ye&&p.parent.callee.property.name==="get";p.type==="Identifier"&&(f||m||x)&&!b&&Ve(p)},CallExpression(p,d,f){p.callee.type==="Identifier"&&(p.callee.parent=p),p.arguments.forEach(m=>{m.type==="Identifier"&&(m.parent=p)}),(p.callee.type==="ArrowFunctionExpression"||p.callee.type==="FunctionExpression")&&f(p.callee,{parent:p}),we(p,e),p.type==="CallExpression"&&(p.callee.type==="MemberExpression"&&f(p.callee,{parent:p}),p.arguments.forEach(m=>f(m,{parent:p})))},BinaryExpression(p,d,f){p.left.type==="Identifier"&&(p.left.parent=p),p.right.type==="Identifier"&&(p.right.parent=p),f(p.left,{parent:p}),f(p.right,{parent:p})},LogicalExpression(p,d,f){p.left.type==="Identifier"&&(p.left.parent=p),p.right.type==="Identifier"&&(p.right.parent=p),f(p.left,{parent:p}),f(p.right,{parent:p})},UnaryExpression(p,d,f){p.argument.type==="Identifier"&&(p.argument.parent=p),f(p.argument,{parent:p})},MemberExpression(p,d,f){p.object&&p.object.type==="Identifier"&&(p.object.parent=p),p.property&&p.property.type==="Identifier"&&(p.property.parent=p),_e(p,"",e),p.type==="CallExpression"?p.arguments.forEach(m=>f(m,{parent:p})):p.object&&f(p.object,{parent:p})},AwaitExpression(p,d,f){p.argument&&(p.argument._insideAwait=!0,f(p.argument,{parent:p}),p.argument.type==="Identifier"&&p.argument._wasInsideAwait&&Object.assign(p,p.argument))},ArrowFunctionExpression(p,d,f){if(p.body)if(p.body.type==="BlockStatement"){let m=[];p.body.body.forEach(x=>{e.enterHoistingScope(),f(x,{parent:p.body,insideIIFE:!0});let b=e.exitHoistingScope();m.push(...b),m.push(x)}),p.body.body=m}else f(p.body,{parent:p,insideIIFE:!0})},FunctionExpression(p,d,f){if(p.body&&p.body.type==="BlockStatement"){let m=[];p.body.body.forEach(x=>{e.enterHoistingScope(),f(x,{parent:p.body,insideIIFE:!0});let b=e.exitHoistingScope();m.push(...b),m.push(x)}),p.body.body=m}},SwitchStatement(p,d,f){p.discriminant&&(p.discriminant.parent=p,f(p.discriminant,{parent:p})),p.cases&&p.cases.forEach(m=>{m.parent=p,f(m,{parent:p})})},SwitchCase(p,d,f){if(p.test&&(p.test.parent=p,f(p.test,{parent:p})),p.consequent){let m=[];p.consequent.forEach(x=>{e.enterHoistingScope(),x.parent=p,f(x,{parent:p});let b=e.exitHoistingScope();m.push(...b),m.push(x)}),p.consequent=m}},AssignmentExpression(p,d,f){if(d.insideIIFE){if(p.left.type==="Identifier"){let[m]=e.getVariable(p.left.name);if(m===p.left.name&&!e.isContextBound(p.left.name)){f(p.right,{parent:p});return}}Tr(p,e)}}}));let l=ke(n.id.name,e),c=!o&&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||(nn(n.init.property,e),n.init.property._indexTransformed=!0)),a==="var"){let p=e.getCurrentHoistingScope();if(p){for(let d of p)if(d.type==="VariableDeclaration")for(let f of d.declarations){if(!f.init||f.init.type!=="CallExpression")continue;let m=f.init.callee;if(m?.type!=="MemberExpression")continue;let x,b=m.property?.name;if(m.object?.type==="Identifier"?x=m.object.name:m.object?.type==="MemberExpression"&&m.object.property?.name&&(x=m.object.property.name),x&&b){let w=`${x}.${b}`;Q_.includes(w)&&(f.init={type:"ArrowFunctionExpression",params:[],body:f.init,expression:!0,async:!1})}}}}let u;n.init?s||o?u=n.init:a==="var"?u=S.createInitVarCall(l,n.init):u=S.createInitCall(l,c?n.init.object:n.init,c?n.init.property:void 0):u=S.createIdentifier("undefined");let h=S.createExpressionStatement(S.createAssignmentExpression(l,u));if(o){let p=n.init.object.name,d=ke(p,e),f=n.init.property.value,m={type:"MemberExpression",object:S.createGetCall(d,0),property:{type:"Literal",value:f},computed:!0};h.expression.right=S.createCallExpression(S.createMemberExpression(S.createContextIdentifier(),S.createIdentifier("init")),[l,m])}s&&(e.pushScope("fn"),Ne(n.init.body,e,{IfStatement(p,d,f){d.pushScope("if"),p.test&&pl(p.test,d),f(p.consequent,d),p.alternate&&(d.pushScope("els"),f(p.alternate,d),d.popScope()),d.popScope()},VariableDeclaration(p,d){ul(p,d)},Identifier(p,d){Ce(p,d)},AssignmentExpression(p,d){Tr(p,d)},SwitchStatement(p,d,f){p.discriminant.parent=p,f(p.discriminant,d),p.cases.forEach(m=>{m.parent=p,f(m,d)})},SwitchCase(p,d,f){p.test&&(p.test.parent=p,f(p.test,d));let m=[];p.consequent.forEach(x=>{d.enterHoistingScope(),f(x,d);let b=d.exitHoistingScope();m.push(...b),m.push(x)}),p.consequent=m},BlockStatement(p,d,f){let m=[];p.body.forEach(x=>{d.enterHoistingScope(),f(x,d);let b=d.exitHoistingScope();m.push(...b),m.push(x)}),p.body=m}}),e.popScope()),Object.assign(t,h)})}function w0(t,e,n){if(e.setSuppressHoisting(!0),t.init&&t.init.type==="VariableDeclaration"){let s=t.init.declarations[0],a=s.id.name;e.addLoopVariable(a,a),t.init={type:"VariableDeclaration",kind:t.init.kind,declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:a},init:s.init}]},s.init&&Ne(s.init,e,{Identifier(o,l){!e.isLoopVariable(o.name)&&!o.computed&&(e.pushScope("for"),Ce(o,l),o.type==="Identifier"&&(e.isContextBound(o.name)&&o.parent&&o.parent.type==="MemberExpression"&&o.parent.object===o||(o.computed=!0,Ve(o))),e.popScope())},MemberExpression(o,l,c){e.pushScope("for"),_e(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&&Ne(t.test,e,{Identifier(s,a){!e.isLoopVariable(s.name)&&!s.computed&&(e.pushScope("for"),Ce(s,a),s.type==="Identifier"&&(e.isContextBound(s.name)&&s.parent&&s.parent.type==="MemberExpression"&&s.parent.object===s||(s.computed=!0,Ve(s))),e.popScope())},MemberExpression(s,a,o){e.pushScope("for"),_e(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&&Ne(t.update,e,{Identifier(s,a){!e.isLoopVariable(s.name)&&!s.computed&&(e.pushScope("for"),Ce(s,a),s.type==="Identifier"&&(e.isContextBound(s.name)&&s.parent&&s.parent.type==="MemberExpression"&&s.parent.object===s||(s.computed=!0,Ve(s))),e.popScope())},MemberExpression(s,a,o){e.pushScope("for"),_e(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);let r=e.getNextLoopGuardName(),i=Rs(r);if(e.addHoistedStatement(i.counterDecl),e.pushScope("for"),n(t.body,e),e.popScope(),t.body.type==="BlockStatement"&&t.body.body.unshift(i.guardCheck),t.init&&t.init.type==="VariableDeclaration"){let s=t.init.declarations[0];e.removeLoopVariable(s.id.name)}}function v0(t,e,n){e.setSuppressHoisting(!0),t.test&&Ne(t.test,e,{Identifier(s,a){s.computed||(Ce(s,a),s.type==="Identifier"&&(e.isContextBound(s.name)&&s.parent&&s.parent.type==="MemberExpression"&&s.parent.object===s||(s.computed=!0,Ve(s))))},MemberExpression(s,a,o){_e(s,"",e),s.type==="MemberExpression"&&s.object&&(s.object.type!=="Identifier"||!e.isContextBound(s.object.name))&&o(s.object,a)},CallExpression(s,a,o){if(s.callee.parent=s,o(s.callee,a),we(s,a),s.arguments)for(let l of s.arguments)o(l,a)}}),e.setSuppressHoisting(!1);let r=e.getNextLoopGuardName(),i=Rs(r);e.addHoistedStatement(i.counterDecl),e.pushScope("whl"),n(t.body,e),e.popScope(),t.body.type==="BlockStatement"&&t.body.body.unshift(i.guardCheck)}function pl(t,e){Ne(t,e,{MemberExpression(n,r,i){n.object&&n.object.type==="Identifier"&&!e.isContextBound(n.object.name)&&!n.computed&&(n.object.parent=n,i(n.object,r)),_e(n,"",e)},CallExpression(n,r){we(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";Ce(n,r),n.type==="Identifier"&&(s||a||o||l)&&(i&&i.type==="CallExpression"&&i.callee&&i.callee.object&&i.callee.object.name===ye&&i.callee.property?.name==="get"||Ve(n));let c=e.getCurrentScopeType()==="if";e.isContextBound(n.name)&&!e.isRootParam(n.name)&&c&&Ve(n)}})}function E0(t,e,n){t.test&&(e.pushScope("if"),pl(t.test,e),e.popScope()),e.pushScope("if"),n(t.consequent,e),e.popScope(),t.alternate&&(e.pushScope("els"),n(t.alternate,e),e.popScope())}function S0(t,e){let n=e.getCurrentScopeType();if(t.argument){if(t.argument.type==="ArrayExpression")t.argument.elements=t.argument.elements.map(r=>r.type==="Identifier"?e.isContextBound(r.name)&&!e.isRootParam(r.name)?S.createGetCall(r,0):Xi(r.name,e):r.type==="MemberExpression"?r.object&&r.object.type==="MemberExpression"&&r.object.object&&r.object.object.type==="Identifier"&&r.object.object.name==="$"&&r.object.property&&["const","let","var","params"].includes(r.object.property.name)?S.createGetCall(r,0):(_e(r,"",e),r):((r.type==="BinaryExpression"||r.type==="LogicalExpression"||r.type==="ConditionalExpression"||r.type==="CallExpression"||r.type==="UnaryExpression")&&Ne(r,e,{Identifier(i,s){Ce(i,s),i.type==="Identifier"&&!i._arrayAccessed&&(Ve(i),i._arrayAccessed=!0)},MemberExpression(i){_e(i,"",e)},CallExpression(i,s,a){(i.callee.type==="ArrowFunctionExpression"||i.callee.type==="FunctionExpression")&&a(i.callee,s),we(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)),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:S.createIdentifier(r.key.name),value:ke(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=ke(r.value.name,e))),r));else if(t.argument.type==="Identifier")Ce(t.argument,e),t.argument.type==="Identifier"&&Ve(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)))Ce(t.argument.object,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)&&_e(t.argument,"",e)}}if(n==="fn"){t.argument.type==="Identifier"&&e.isContextBound(t.argument.name)&&!e.isRootParam(t.argument.name)?t.argument=S.createArrayAccess(t.argument,0):t.argument.type==="MemberExpression"?t.argument.computed&&t.argument.object.type==="CallExpression"?_e(t.argument,"",e):t.argument.object.type==="Identifier"&&e.isContextBound(t.argument.object.name)&&!e.isRootParam(t.argument.object.name)?t.argument.computed?_e(t.argument,"",e):t.argument._indexTransformed||(nn(t.argument,e),t.argument._indexTransformed=!0):t.argument.computed&&t.argument.object.type==="Identifier"&&e.isLocalSeriesVar(t.argument.object.name)&&_e(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")&&Ne(t.argument,e,{Identifier(i,s){Ce(i,s),i.type==="Identifier"&&!i._arrayAccessed&&(Ve(i),i._arrayAccessed=!0)},MemberExpression(i){_e(i,"",e)},AssignmentExpression(i,s){Tr(i,s)},CallExpression(i,s,a){(i.callee.type==="ArrowFunctionExpression"||i.callee.type==="FunctionExpression")&&a(i.callee,s),we(i,s),i.type==="CallExpression"&&i.arguments.forEach(o=>a(o,s))},BinaryExpression(i,s,a){a(i.left,s),a(i.right,s)},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=S.createCallExpression(S.createMemberExpression(S.createContextIdentifier(),S.createIdentifier("precision")),[t.argument]);t.argument=r}}}function C0(t,e,n){let r=S.createVariableDeclaration("$$",S.createCallExpression(S.createMemberExpression(S.createContextIdentifier(),S.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(l=>{l.type==="Identifier"&&e.addLocalSeriesVar(l.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[l,c]of Object.entries(a))o[l]=e.getVariableUdtType(l),e.markVariableAsUdtInstance(l,c);if(n(t.body,e),t.params.forEach(l=>{l.type==="Identifier"&&e.removeLocalSeriesVar(l.name)}),a)for(let l of Object.keys(a)){e.unmarkVariableAsUdtInstance(l);let c=o[l];c!==void 0&&e.markVariableAsUdtInstance(l,c)}e.popScope()}}function N0(t){let e={...A,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;mt(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 mt(o,{AwaitExpression(){l=!0}},c),l}let s=!0,a=0;for(;s&&a<20;){s=!1,a++,mt(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=[];mt(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=[];mt(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 k0={"==":"__eq","===":"__eq","!=":"__neq","!==":"__neq","<":"__lt","<=":"__le",">":"__gt",">=":"__ge"},I0=new Set(["<","<=",">",">="]);function A0(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==="WhileStatement"||r.type==="DoWhileStatement")&&i===r.test)return!0}return!1}function T0(t){let e={...A,LineComment:()=>{}};al(t,{BinaryExpression(n,r,i){let s=k0[n.operator];if(!s||I0.has(n.operator)&&A0(n,i))return;let a=S.createMathCompareCall(s,n.left,n.right);a._transformed=!0,Object.assign(n,a)}},e)}function D0(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};Ne(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),S0(a,o)},VariableDeclaration(a,o){ul(a,o)},Identifier(a,o){Ce(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)),we(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"?(Ce(a.right,o),a.right.type==="Identifier"&&Ve(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=S.createCallExpression(S.createMemberExpression(S.createIdentifier("$"),S.createIdentifier(h),!1),[p]);Object.assign(a.right,d)}let c=o.getNextLoopGuardName(),u=Rs(c);if(o.addHoistedStatement(u.counterDecl),a.body&&l(a.body,o),a.body&&a.body.type==="BlockStatement"&&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"?(Ce(a.right,o),a.right.type==="Identifier"&&Ve(a.right)):a.right&&l(a.right,o),a.body&&l(a.body,o)},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)),_e(a,n,o)},AssignmentExpression(a,o,l){if(Tr(a,o),a.type==="CallExpression"&&a.arguments){let c=u=>{u&&(u.type==="CallExpression"&&u.callee&&(u.callee.type==="ArrowFunctionExpression"||u.callee.type==="FunctionExpression")&&l(u.callee,o),u.type==="BinaryExpression"&&(c(u.left),c(u.right)))};a.arguments.forEach(u=>c(u))}},FunctionDeclaration(a,o,l){C0(a,o,l)},ForStatement(a,o,l){w0(a,o,l)},WhileStatement(a,o,l){v0(a,o,l)},IfStatement(a,o,l){E0(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 _={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"},M0=new Set(["if","else","for","while","switch","break","continue","var","varip","type","and","or","not","to","by","in","import","export","method","extends","enum"]),P0=["==","!=","<=",">=",":=","+=","-=","*=","/=","%=","=>","//","and","or","not"],Ji=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}},R0=Object.defineProperty,F0=(t,e,n)=>e in t?R0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,_t=(t,e,n)=>F0(t,typeof e!="symbol"?e+"":e,n),es=class{constructor(e){_t(this,"source"),_t(this,"pos"),_t(this,"line"),_t(this,"column"),_t(this,"tokens"),_t(this,"indentStack"),_t(this,"atLineStart"),_t(this,"parenDepth"),_t(this,"bracketDepth"),_t(this,"braceDepth"),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(_.DEDENT,"",this.getCurrentIndent());return this.addToken(_.EOF,""),this.tokens}handleNewline(){this.parenDepth===0&&this.bracketDepth===0&&this.braceDepth===0&&(this.addToken(_.NEWLINE,`\n`),this.atLineStart=!0),this.advance(),this.line++,this.column=1}handleIndentation(){let e=0,n=0;for(this.pos;this.pos<this.source.length;){let i=this.peek();if(i===" ")n++,this.advance();else if(i===" ")e++,this.advance();else break}if(this.peek()===`\n`||this.peek()==="\\r"||this.peek()==="\\0"||(e+=Math.floor(n/4),this.isContinuationFromPrevToken()))return;let r=this.indentStack[this.indentStack.length-1];if(e>r)this.indentStack.push(e),this.addToken(_.INDENT,"",e);else if(e<r){for(;this.indentStack.length>1&&this.indentStack[this.indentStack.length-1]>e;)this.indentStack.pop(),this.addToken(_.DEDENT,"",this.indentStack[this.indentStack.length-1]);if(this.indentStack[this.indentStack.length-1]!==e)throw new Error(`Indentation error at ${this.line}:${this.column} - misaligned dedent`)}}isContinuationFromPrevToken(){for(let e=this.tokens.length-1;e>=0;e--){let n=this.tokens[e];if(!(n.type===_.NEWLINE||n.type===_.COMMENT))return n.type===_.OPERATOR?n.value!=="=>":n.type===_.COMMA||n.type===_.COLON||n.type===_.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.addToken(_.COMMENT,e.trim())}readString(){let e=this.advance(),n=this.column-1,r="";for(;this.pos<this.source.length&&this.peek()!==e;)if(this.peek()==="\\\\"){this.advance();let i=this.advance();switch(i){case"n":r+=`\n`;break;case"t":r+=" ";break;case"r":r+="\\r";break;case"\\\\":r+="\\\\";break;case e:r+=e;break;default:r+=i}}else r+=this.advance();if(this.peek()!==e)throw new Error(`Unterminated string at ${this.line}:${n}`);this.advance(),this.addToken(_.STRING,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(_.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(_.NUMBER,parseFloat(e),null,e)}readIdentifier(){this.column;let e="";for(;this.pos<this.source.length&&this.isIdentifierChar(this.peek());)e+=this.advance();M0.has(e)?this.addToken(_.KEYWORD,e):e==="true"||e==="false"?this.addToken(_.BOOLEAN,e==="true"):this.addToken(_.IDENTIFIER,e)}readOperatorOrPunctuation(){let e=this.peek(),n=this.peek(1),r=e+n;if(P0.includes(r))return this.advance(),this.advance(),this.addToken(_.OPERATOR,r),!0;if("+-*/%<>=!?".includes(e))return this.advance(),this.addToken(_.OPERATOR,e),!0;switch(e){case"(":return this.parenDepth++,this.advance(),this.addToken(_.LPAREN,e),!0;case")":return this.parenDepth--,this.advance(),this.addToken(_.RPAREN,e),!0;case"[":return this.bracketDepth++,this.advance(),this.addToken(_.LBRACKET,e),!0;case"]":return this.bracketDepth--,this.advance(),this.addToken(_.RBRACKET,e),!0;case"{":return this.braceDepth++,this.advance(),this.addToken(_.LBRACE,e),!0;case"}":return this.braceDepth--,this.advance(),this.addToken(_.RBRACE,e),!0;case",":return this.advance(),this.addToken(_.COMMA,e),!0;case".":return this.isDigit(this.peek(1))?(this.readNumber(),!0):(this.advance(),this.addToken(_.DOT,e),!0);case":":return this.advance(),this.addToken(_.COLON,e),!0;case";":return this.advance(),this.addToken(_.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 Ji(e,n,this.line,this.column,r!==null?r:this.getCurrentIndent(),i);this.tokens.push(s)}},B0=Object.defineProperty,L0=(t,e,n)=>e in t?B0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ye=(t,e,n)=>L0(t,typeof e!="symbol"?e+"":e,n),ie=class{constructor(e){this.type=e}},ts=class extends ie{constructor(e){super("Program"),this.body=e}},qe=class extends ie{constructor(e){super("ExpressionStatement"),this.expression=e}},At=(t=>(t.VAR="var",t.LET="let",t.CONST="const",t))(At||{}),ut=class extends ie{constructor(e,n="let"){super("VariableDeclaration"),this.declarations=e,this.kind=n}},nt=class extends ie{constructor(e,n,r=null){super("VariableDeclarator"),this.id=e,this.init=n,this.varType=r}},Dr=class extends ie{constructor(e,n,r,i=null){super("FunctionDeclaration"),this.id=e,this.params=n,this.body=r,this.returnType=i}},ns=class extends ie{constructor(e,n){super("TypeDefinition"),this.name=e,this.fields=n}},rs=class extends ie{constructor(e,n,r=null){super("IfStatement"),this.test=e,this.consequent=n,this.alternate=r,Ye(this,"_line")}},Mr=class extends ie{constructor(e,n,r,i){super("ForStatement"),this.init=e,this.test=n,this.update=r,this.body=i,Ye(this,"isForIn")}},is=class extends ie{constructor(e,n){super("WhileStatement"),this.test=e,this.body=n}},wt=class extends ie{constructor(e){super("BlockStatement"),this.body=e}},Pr=class extends ie{constructor(e){super("ReturnStatement"),this.argument=e}},be=class extends ie{constructor(e){super("Identifier"),this.name=e,Ye(this,"varType"),Ye(this,"returnType"),Ye(this,"isMethod")}},Tt=class extends ie{constructor(e,n=null){super("Literal"),this.value=e,this.raw=n}},pt=class extends ie{constructor(e,n,r){super("BinaryExpression"),this.operator=e,this.left=n,this.right=r}},Rr=class extends ie{constructor(e,n,r=!0){super("UnaryExpression"),this.operator=e,this.argument=n,this.prefix=r}},Yt=class extends ie{constructor(e,n,r){super("AssignmentExpression"),this.operator=e,this.left=n,this.right=r}},Fr=class extends ie{constructor(e,n,r=!1){super("UpdateExpression"),this.operator=e,this.argument=n,this.prefix=r}},ss=class extends ie{constructor(e,n){super("CallExpression"),this.callee=e,this.args=n,Ye(this,"arguments"),this.callee=e,this.arguments=n}},Br=class extends ie{constructor(e,n,r=!1){super("MemberExpression"),this.object=e,this.property=n,this.computed=r}},vt=class extends ie{constructor(e,n,r){super("ConditionalExpression"),this.test=e,this.consequent=n,this.alternate=r,Ye(this,"needsIIFE"),Ye(this,"consequentStmts"),Ye(this,"alternateStmts")}},as=class extends ie{constructor(e){super("ArrayExpression"),this.elements=e}},Lr=class extends ie{constructor(e){super("ObjectExpression"),this.properties=e}},Or=class extends ie{constructor(e,n){super("Property"),this.key=e,this.value=n,Ye(this,"kind"),Ye(this,"method"),Ye(this,"shorthand"),Ye(this,"computed"),this.kind="init",this.method=!1,this.shorthand=!1,this.computed=!1}},Vr=class extends ie{constructor(e){super("ArrayPattern"),this.elements=e}},jr=class extends ie{constructor(e,n){super("AssignmentPattern"),this.left=e,this.right=n}},os=class extends ie{constructor(e,n){super("SwitchExpression"),this.discriminant=e,this.cases=n}},ls=class extends ie{constructor(e,n,r){super("SwitchCase"),this.test=e,this.consequent=n,this.statements=r,this.statements=r}},O0=Object.defineProperty,V0=(t,e,n)=>e in t?O0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,dn=(t,e,n)=>V0(t,typeof e!="symbol"?e+"":e,n),hl=class cs{constructor(e){dn(this,"tokens"),dn(this,"pos"),dn(this,"functionNames",new Set),dn(this,"paramScopes",[]),dn(this,"noLineContinuation",!1),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}`);if(n!==null&&r.value!==n)throw new Error(`Expected \'${n}\' but got \'${r.value}\' at ${r.line}:${r.column}`);return this.advance()}expectIdentifierOrContextual(){let e=this.peek();if(e.type===_.IDENTIFIER)return this.advance();if(e.type===_.KEYWORD&&cs.CONTEXTUAL_KEYWORDS.has(e.value))return this.advance();throw new Error(`Expected ${_.IDENTIFIER} but got ${e.type} at ${e.line}:${e.column}`)}matchEx(e,n=null,r=!1){if(!r)return this.match(e,n);let i=0,s=this.peek(i);if(s.type===_.NEWLINE&&this.noLineContinuation||(s.type===_.NEWLINE&&(i++,s=this.peek(i),s.type===_.INDENT&&(i++,s=this.peek(i))),s.type!==e)||n!==null&&s.value!==n)return!1;for(let a=0;a<i;a++)this.advance();return!0}peekOperatorEx(e){let n=0,r=this.peek(n),i=!1;if(r.type===_.NEWLINE){if(this.noLineContinuation)return null;n++,r=this.peek(n),r.type===_.INDENT&&(i=!0,n++,r=this.peek(n))}if(r.type!==_.OPERATOR||!e.includes(r.value)||i&&(r.value==="+"||r.value==="-"))return null;for(let s=0;s<n;s++)this.advance();return r.value}skipNewlines(e=!1){for(;this.match(_.NEWLINE)||this.match(_.COMMENT);)this.advance();e&&this.match(_.INDENT)&&this.advance()}parse(){let e=[];for(;!this.match(_.EOF);){if(this.skipNewlines(),this.match(_.DEDENT)){this.advance();continue}if(this.match(_.EOF))break;let n=this.parseStatement();n&&e.push(n),this.skipNewlines()}return new ts(e)}parseStatement(e=!0){this.skipNewlines();let n=this.peek().line;if(this.match(_.COMMENT))return this.advance(),null;let r;if(this.match(_.KEYWORD,"enum"))r=this.parseEnumDefinition();else if(this.match(_.KEYWORD,"type"))r=this.parseTypeDefinition();else if(this.match(_.KEYWORD,"var")||this.match(_.KEYWORD,"varip"))r=this.parseVarDeclaration();else if(this.match(_.KEYWORD,"method"))r=this.parseMethodDeclaration();else if(this.isFunctionDeclaration())r=this.parseFunctionDeclaration();else if(this.match(_.KEYWORD,"if"))r=this.parseIfStatement();else if(this.match(_.KEYWORD,"for"))r=this.parseForStatement();else if(this.match(_.KEYWORD,"while"))r=this.parseWhileStatement();else if(this.match(_.KEYWORD,"break")||this.match(_.KEYWORD,"continue")){let i=this.advance().value;r=new qe(new be(i))}else this.isTupleDestructuring()?r=this.parseTupleDestructuring():this.peek().type===_.IDENTIFIER&&this.isTypedVarDeclaration()&&(r=this.parseTypedVarDeclaration());if(!r){let i=this.parseExpression();if(this.match(_.OPERATOR)){let s=this.peek().value;if(["=",":=","+=","-=","*=","/=","%="].includes(s)){this.advance(),this.skipNewlines(!0);let a=this.parseExpression();s==="="&&i.type==="Identifier"?r=new ut([new nt(i,a)],At.LET):r=new qe(new Yt(s===":="?"=":s,i,a))}else r=new qe(i)}else r=new qe(i)}if(r&&(r._line=n,e&&this.match(_.COMMA)&&this.peek().line===n)){let i=[r];for(;this.match(_.COMMA)&&this.peek().line===n;){this.advance(),this.skipNewlines(!0);let s=this.parseStatement(!1);s&&i.push(s)}return new wt(i)}return r}isFunctionDeclaration(){let e=this.pos;try{let n=0;if(this.peek(n).type===_.IDENTIFIER&&this.peek(n+1).type===_.IDENTIFIER&&n++,this.peek(n).type!==_.IDENTIFIER||(n++,this.peek(n).type!==_.LPAREN))return!1;n++;let r=1;for(;r>0&&this.peek(n).type!==_.EOF;)this.peek(n).type===_.LPAREN&&r++,this.peek(n).type===_.RPAREN&&r--,n++;for(;this.peek(n).type===_.NEWLINE;)n++;return this.peek(n).type===_.OPERATOR&&this.peek(n).value==="=>"}finally{this.pos=e}}parseTypeExpression(){let e=this.expect(_.IDENTIFIER).value;for(;this.match(_.DOT)&&this.peek(1).type===_.IDENTIFIER;)this.advance(),e+="."+this.advance().value;if(this.match(_.OPERATOR,"<")){this.advance();let n=[];for(n.push(this.parseTypeExpression());this.match(_.COMMA);)this.advance(),this.skipNewlines(),n.push(this.parseTypeExpression());return this.expect(_.OPERATOR,">"),e+"<"+n.join(", ")+">"}return this.match(_.LBRACKET)&&this.peek(1).type===_.RBRACKET?(this.advance(),this.advance(),"array<"+e+">"):e}parseEnumDefinition(){this.expect(_.KEYWORD,"enum");let e=this.expect(_.IDENTIFIER).value;this.skipNewlines(),this.expect(_.INDENT);let n=[];for(;!this.match(_.DEDENT)&&!this.match(_.EOF)&&(this.skipNewlines(),!this.match(_.DEDENT));){if(this.match(_.COMMENT)){this.advance();continue}let s=this.expectIdentifierOrContextual().value,a=null;this.match(_.OPERATOR,"=")&&(this.advance(),a=this.expect(_.STRING).value),n.push({name:s,title:a}),this.skipNewlines()}this.match(_.DEDENT)&&this.advance();let r=n.map(s=>new Or(new be(s.name),new Tt(s.title!==null?s.title:s.name))),i=new Lr(r);return new ut([new nt(new be(e),i)],At.CONST)}parseTypeDefinition(){this.expect(_.KEYWORD,"type");let e=this.expect(_.IDENTIFIER).value;this.match(_.OPERATOR,"=>")&&this.advance(),this.skipNewlines(),this.expect(_.INDENT);let n=[];for(;!this.match(_.DEDENT)&&!this.match(_.EOF)&&(this.skipNewlines(),!this.match(_.DEDENT));){let r=this.parseTypeExpression(),i=this.expectIdentifierOrContextual().value,s=null;this.match(_.OPERATOR,"=")&&(this.advance(),this.skipNewlines(),s=this.parseExpression()),n.push({type:r,name:i,defaultValue:s}),this.skipNewlines()}return this.match(_.DEDENT)&&this.advance(),new ns(e,n)}parseVarDeclaration(){let e=this.advance().value,n=null,r=null;if(this.peek().type===_.IDENTIFIER&&this.peek(1).type===_.LBRACKET&&this.peek(2).type===_.RBRACKET)n=this.advance().value,this.advance(),n+="[]",this.advance(),r=this.expectIdentifierOrContextual().value;else if(this.peek().type===_.IDENTIFIER&&(this.peek(1).type===_.DOT||this.peek(1).type===_.IDENTIFIER||this.peek(1).type===_.OPERATOR&&this.peek(1).value==="<")){for(n=this.advance().value;this.match(_.DOT)&&this.peek(1).type===_.IDENTIFIER;)this.advance(),n+="."+this.advance().value;if(this.match(_.LBRACKET)&&this.peek(1).type===_.RBRACKET)this.advance(),this.advance(),n+="[]",r=this.expectIdentifierOrContextual().value;else if(this.match(_.OPERATOR,"<")){for(this.advance(),n+="<";!this.match(_.OPERATOR,">");)if(this.match(_.IDENTIFIER))for(n+=this.advance().value;this.match(_.DOT)&&this.peek(1).type===_.IDENTIFIER;)n+=".",this.advance(),n+=this.advance().value;else if(this.match(_.COMMA))n+=this.advance().value,this.skipNewlines();else break;this.match(_.OPERATOR,">")&&(n+=">",this.advance()),r=this.expectIdentifierOrContextual().value}else r=this.expectIdentifierOrContextual().value}else if(this.peek().type===_.IDENTIFIER)r=this.advance().value;else throw new Error(`Expected identifier after ${e} at ${this.peek().line}:${this.peek().column}`);this.functionNames.has(r)&&(r=r+"_var"),this.expect(_.OPERATOR,"="),this.skipNewlines(!0);let i=this.parseExpression(),s=new be(r);n&&(s.varType=n);let a=[new nt(s,i,n)];for(;this.match(_.COMMA)&&this.peek(1).type===_.KEYWORD&&(this.peek(1).value==="var"||this.peek(1).value==="varip");){this.advance();let o=this.parseVarDeclaration();a.push(...o.declarations)}return new ut(a,e)}isTypedVarDeclaration(){let e=0;if(this.peek(e).type!==_.IDENTIFIER)return!1;for(e++;this.peek(e).type===_.DOT&&this.peek(e+1).type===_.IDENTIFIER;)e+=2;if(this.peek(e).type===_.LBRACKET&&this.peek(e+1).type===_.RBRACKET)return e+=2,this.peek(e).type!==_.IDENTIFIER?!1:(e++,this.peek(e).type===_.OPERATOR&&this.peek(e).value==="=");if(this.peek(e).type===_.OPERATOR&&this.peek(e).value==="<"){e++;let n=1;for(;n>0&&this.peek(e).type!==_.EOF;)this.peek(e).type===_.OPERATOR&&this.peek(e).value==="<"?n++:this.peek(e).type===_.OPERATOR&&this.peek(e).value===">"&&n--,e++;return this.peek(e).type!==_.IDENTIFIER?!1:(e++,this.peek(e).type===_.OPERATOR&&this.peek(e).value==="=")}if(this.peek(e).type!==_.IDENTIFIER)return!1;for(e++;this.peek(e).type===_.IDENTIFIER;)e++;return this.peek(e).type===_.OPERATOR&&this.peek(e).value==="="}parseTypedVarDeclaration(){let e=this.advance().value;for(;this.match(_.DOT)&&this.peek(1).type===_.IDENTIFIER;)this.advance(),e+="."+this.advance().value;if(this.match(_.LBRACKET)&&this.peek(1).type===_.RBRACKET)this.advance(),this.advance(),e+="[]";else if(this.match(_.OPERATOR,"<")){for(this.advance(),e+="<";!this.match(_.OPERATOR,">");)if(this.match(_.IDENTIFIER))for(e+=this.advance().value;this.match(_.DOT)&&this.peek(1).type===_.IDENTIFIER;)e+=".",this.advance(),e+=this.advance().value;else if(this.match(_.COMMA))e+=this.advance().value,this.skipNewlines();else break;this.match(_.OPERATOR,">")&&(e+=">",this.advance())}else for(;this.peek().type===_.IDENTIFIER&&this.peek(1).type===_.IDENTIFIER;)e+=" "+this.advance().value;let n=this.expectIdentifierOrContextual().value;this.functionNames.has(n)&&(n=n+"_var"),this.expect(_.OPERATOR,"="),this.skipNewlines(!0);let r=this.parseExpression(),i=new be(n);i.varType=e;let s=[new nt(i,r,e)];for(;this.match(_.COMMA)&&this.peek(1).type===_.IDENTIFIER&&this.peek(2).type===_.OPERATOR&&this.peek(2).value==="=";){this.advance(),this.skipNewlines(!0);let a=this.expectIdentifierOrContextual().value;this.functionNames.has(a)&&(a=a+"_var"),this.expect(_.OPERATOR,"="),this.skipNewlines(!0);let o=this.parseExpression(),l=new be(a);l.varType=e,s.push(new nt(l,o,e))}return new ut(s,At.LET)}parseFunctionDeclaration(){let e=null;this.peek().type===_.IDENTIFIER&&this.peek(1).type===_.IDENTIFIER&&(e=this.advance().value);let n=this.expect(_.IDENTIFIER).value;this.functionNames.add(n),this.expect(_.LPAREN);let r=[];for(;!this.match(_.RPAREN)&&(this.skipNewlines(),!this.match(_.RPAREN));){let o=null;for(;this.peek().type===_.IDENTIFIER&&this.peek(1).type===_.IDENTIFIER&&this.peek(2).type!==_.LPAREN;)o&&(o+=" "),o=(o||"")+this.advance().value;if(this.peek().type===_.IDENTIFIER&&this.peek(1).type===_.OPERATOR&&this.peek(1).value==="<"){let u=this.parseTypeExpression();o=o?o+" "+u:u}if(this.peek().type===_.IDENTIFIER&&this.peek(1).type===_.LBRACKET&&this.peek(2).type===_.RBRACKET){let u=this.parseTypeExpression();o=o?o+" "+u:u}let l=this.expectIdentifierOrContextual().value,c=new be(l);if(o&&(c.varType=o),this.match(_.OPERATOR,"=")){this.advance(),this.skipNewlines();let u=this.parseExpression();r.push(new jr(c,u))}else r.push(c);this.match(_.COMMA)&&this.advance()}this.expect(_.RPAREN),this.skipNewlines(),this.expect(_.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 be(n);return e&&(a.returnType=e),new Dr(a,r,s,e)}parseMethodDeclaration(){this.expect(_.KEYWORD,"method");let e=null;this.peek().type===_.IDENTIFIER&&this.peek(1).type===_.IDENTIFIER&&this.peek(2).type===_.LPAREN&&(e=this.advance().value);let n=this.expectIdentifierOrContextual().value;this.expect(_.LPAREN);let r=[];for(;!this.match(_.RPAREN)&&(this.skipNewlines(),!this.match(_.RPAREN));){let o=null;for(;this.peek().type===_.IDENTIFIER&&this.peek(1).type===_.IDENTIFIER&&this.peek(2).type!==_.LPAREN;)o&&(o+=" "),o=(o||"")+this.advance().value;if(this.peek().type===_.IDENTIFIER&&this.peek(1).type===_.OPERATOR&&this.peek(1).value==="<"){let u=this.parseTypeExpression();o=o?o+" "+u:u}if(this.peek().type===_.IDENTIFIER&&this.peek(1).type===_.LBRACKET&&this.peek(2).type===_.RBRACKET){let u=this.parseTypeExpression();o=o?o+" "+u:u}let l=this.expectIdentifierOrContextual().value,c=new be(l);if(o&&(c.varType=o),this.match(_.OPERATOR,"=")){this.advance(),this.skipNewlines();let u=this.parseExpression();r.push(new jr(c,u))}else r.push(c);this.match(_.COMMA)&&this.advance()}this.expect(_.RPAREN),this.skipNewlines(),this.expect(_.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 be(n);return e&&(a.returnType=e),a.isMethod=!0,new Dr(a,r,s,e)}parseFunctionBody(){let e=[];if(!this.match(_.INDENT)){let n=this.parseExpression();return new wt([new Pr(n)])}for(this.advance();!this.match(_.DEDENT)&&!this.match(_.EOF)&&(this.skipNewlines(),!this.match(_.DEDENT));){let n=this.parseStatementOrSequence();Array.isArray(n)?e.push(...n):n&&e.push(n)}return this.match(_.DEDENT)&&this.advance(),e.length>0&&this._addImplicitReturn(e),new wt(e)}_addImplicitReturn(e){let n=e[e.length-1];n.type==="ExpressionStatement"?e[e.length-1]=new Pr(n.expression):n.type==="IfStatement"&&this._addImplicitReturnToIf(n)}_addImplicitReturnToIf(e){e.consequent&&e.consequent.type==="BlockStatement"&&e.consequent.body.length>0&&this._addImplicitReturn(e.consequent.body),e.alternate&&(e.alternate.type==="IfStatement"?this._addImplicitReturnToIf(e.alternate):e.alternate.type==="BlockStatement"&&e.alternate.body.length>0&&this._addImplicitReturn(e.alternate.body))}parseStatementOrSequence(){this.pos;let e=this.peek().line;if(this.match(_.KEYWORD,"if")){let r=this.parseIfStatement();return r&&(r._line=e),r}if(this.match(_.KEYWORD,"for"))return this.parseForStatement();if(this.match(_.KEYWORD,"while"))return this.parseWhileStatement();if(this.match(_.KEYWORD,"break")||this.match(_.KEYWORD,"continue")){let r=this.advance().value;return new qe(new be(r))}if(this.match(_.KEYWORD,"var")||this.match(_.KEYWORD,"varip"))return this.parseVarDeclaration();if(this.isTupleDestructuring())return this.parseTupleDestructuring();if(this.peek().type===_.IDENTIFIER&&this.isTypedVarDeclaration()){let r=this.parseTypedVarDeclaration();if(this.match(_.COMMA)&&this.peek(1).type===_.IDENTIFIER){let i=[r];for(;this.match(_.COMMA);)if(this.advance(),this.skipNewlines(!0),this.peek().type===_.IDENTIFIER&&this.isTypedVarDeclaration())i.push(this.parseTypedVarDeclaration());else{let s=this.parseExpression();if(this.match(_.OPERATOR)){let a=this.peek().value;if(["=",":="].includes(a)){this.advance(),this.skipNewlines(!0);let o=this.parseExpression();a==="="&&s.type==="Identifier"?i.push(new ut([new nt(s,o)],At.LET)):i.push(new qe(new Yt(a===":="?"=":a,s,o)))}}break}return i}return r}let n=[];for(;;){let r=this.parseExpression();if(this.match(_.OPERATOR)){let i=this.peek().value;if(["=",":=","+=","-=","*=","/=","%="].includes(i)){this.advance(),this.skipNewlines(!0);let s=this.parseExpression();if(i==="="&&r.type==="Identifier"?n.push(new ut([new nt(r,s)],At.LET)):n.push(new qe(new Yt(i===":="?"=":i,r,s))),this.match(_.COMMA)){this.advance(),this.skipNewlines();continue}break}else{if(n.length>0)n.push(new qe(r));else return new qe(r);break}}else if(this.match(_.COMMA)){n.push(new qe(r)),this.advance(),this.skipNewlines();continue}else{if(n.length>0)n.push(new qe(r));else return new qe(r);break}}return n.length>1?n:n.length===1?n[0]:null}parseIfStatement(){this.expect(_.KEYWORD,"if");let e=this.parseExpression();this.skipNewlines();let n=this.parseBlock(),r=null;return this.skipNewlines(),this.match(_.KEYWORD,"else")&&(this.advance(),this.skipNewlines(),this.match(_.KEYWORD,"if")?r=this.parseIfStatement():r=this.parseBlock()),new rs(e,n,r)}parseForStatement(){this.expect(_.KEYWORD,"for");let e=null,n=!1;if(this.match(_.LBRACKET)){this.advance();let r=[];for(;!this.match(_.RBRACKET);)this.skipNewlines(),r.push(new be(this.expectIdentifierOrContextual().value)),this.match(_.COMMA)&&this.advance();this.expect(_.RBRACKET),e=new Vr(r),n=!0}else{let r=this.expectIdentifierOrContextual().value;e=new be(r)}if(this.match(_.KEYWORD,"in")){this.advance();let r=this.parseExpression();this.skipNewlines();let i=this.parseBlock(),s=new ut([new nt(e,r)],At.CONST),a=new Mr(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(_.OPERATOR,"=");let r=this.parseExpression();this.expect(_.KEYWORD,"to");let i=this.parseExpression(),s=null;this.match(_.KEYWORD,"by")&&(this.advance(),s=this.parseExpression()),this.skipNewlines();let a=this.parseBlock(),o=new ut([new nt(e,r)],At.LET),l=new pt("<=",r,i),c=new vt(l,new pt("<=",e,i),new pt(">=",e,i)),u;return s?u=new vt(l,new Yt("+=",e,s),new Yt("-=",e,s)):u=new vt(l,new Fr("++",e),new Fr("--",e)),new Mr(o,c,u,a)}}parseWhileStatement(){this.expect(_.KEYWORD,"while");let e=this.parseExpression();this.skipNewlines();let n=this.parseBlock();return new is(e,n)}parseBlock(){if(!this.match(_.INDENT)){let r=this.parseStatement();return new wt(r?[r]:[])}let e=this.peek().indent;this.advance();let n=[];for(;!this.match(_.EOF);){if(this.skipNewlines(),this.match(_.DEDENT)){if(this.peek().indent<e)break;this.advance();continue}if(this.match(_.EOF))break;let r=this.parseStatement();r&&n.push(r)}return this.match(_.DEDENT)&&this.peek().indent<e&&this.advance(),new wt(n)}isTupleDestructuring(){if(!this.match(_.LBRACKET))return!1;let e=1;for(;;){for(;this.peek(e).type===_.NEWLINE;)e++;if(this.peek(e).type!==_.IDENTIFIER)return!1;for(e++;this.peek(e).type===_.NEWLINE;)e++;if(this.peek(e).type===_.RBRACKET){e++;break}else if(this.peek(e).type===_.COMMA){e++;continue}else return!1}for(;this.peek(e).type===_.NEWLINE;)e++;return this.peek(e).type===_.OPERATOR&&this.peek(e).value==="="}parseTupleDestructuring(){this.expect(_.LBRACKET);let e=[];for(;!this.match(_.RBRACKET);){this.skipNewlines();let r=this.expectIdentifierOrContextual().value;this.functionNames.has(r)&&(r=r+"_var"),e.push(new be(r)),this.match(_.COMMA)&&this.advance()}this.expect(_.RBRACKET),this.skipNewlines(),this.expect(_.OPERATOR,"="),this.skipNewlines(!0);let n=this.parseExpression();return new ut([new nt(new Vr(e),n)],At.CONST)}parseExpression(){return this.parseTernary()}parseTernary(){let e=this.parseLogicalOr();if(this.matchEx(_.OPERATOR,"?",!0)){this.advance(),this.skipNewlines(!0);let n=this.parseExpression();this.matchEx(_.COLON,null,!0)?this.advance():this.expect(_.COLON),this.skipNewlines(!0);let r=this.parseExpression();return new vt(e,n,r)}return e}parseLogicalOr(){let e=this.parseLogicalAnd();for(;this.matchEx(_.KEYWORD,"or",!0)||this.peekOperatorEx(["||"]);){this.advance(),this.skipNewlines(!0);let n=this.parseLogicalAnd();e=new pt("||",e,n)}return e}parseLogicalAnd(){let e=this.parseEquality();for(;this.matchEx(_.KEYWORD,"and",!0)||this.peekOperatorEx(["&&"]);){this.advance(),this.skipNewlines(!0);let n=this.parseEquality();e=new pt("&&",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 pt(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 pt(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 pt(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 pt(n,e,r)}return e}parseUnary(){if(this.match(_.OPERATOR)){let e=this.peek().value;if(["+","-","!"].includes(e))return this.advance(),this.skipNewlines(),new Rr(e,this.parseUnary())}return this.match(_.KEYWORD,"not")?(this.advance(),this.skipNewlines(),new Rr("!",this.parseUnary())):this.parsePostfix()}parsePostfix(){let e=this.parsePrimary();for(;;)if(this.match(_.OPERATOR,"<")){let n=this.pos;this.advance();let r=1,i=!0,s="",a=new Set(["float","int","string","bool","color","line","label","box","linefill","table"]);for(;r>0&&!this.match(_.EOF);)if(this.match(_.OPERATOR,"<"))r++,this.advance();else if(this.match(_.OPERATOR,">"))r--,this.advance();else if(this.match(_.IDENTIFIER)||this.match(_.COMMA)||this.match(_.DOT))r===1&&this.match(_.IDENTIFIER)&&s===""&&(s=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")&&a.has(s)&&(e.property=new be("new_"+s)),i&&this.match(_.LPAREN)){e=this.parseCallExpression(e);continue}else{if(i)continue;break}}else if(this.match(_.LPAREN))e=this.parseCallExpression(e);else if(this.match(_.DOT)){this.advance(),this.skipNewlines();let n=this.peek();if(n.type!==_.IDENTIFIER&&n.type!==_.KEYWORD)throw new Error(`Expected property name but got ${n.type} at ${n.line}:${n.column}`);this.advance(),e=new Br(e,new be(n.value),!1)}else if(this.match(_.LBRACKET)){if(this.isTupleDestructuring())break;this.advance(),this.skipNewlines();let n=this.parseExpression();this.expect(_.RBRACKET),e=new Br(e,n,!0)}else break;return e}parseCallExpression(e){this.expect(_.LPAREN);let n=[],r=[];for(;!this.match(_.RPAREN)&&(this.skipNewlines(),!this.match(_.RPAREN));){if((this.peek().type===_.IDENTIFIER||this.peek().type===_.KEYWORD)&&this.peek(1).type===_.OPERATOR&&this.peek(1).value==="="){let i=this.advance().value;this.advance(),this.skipNewlines();let s=this.parseExpression();r.push(new Or(new be(i),s))}else n.push(this.parseExpression());this.match(_.COMMA)&&this.advance(),this.skipNewlines()}return this.expect(_.RPAREN),r.length>0&&n.push(new Lr(r)),new ss(e,n)}parsePrimary(){let e=this.peek();if(this.match(_.NUMBER)){let n=this.advance();return new Tt(n.value,n.raw)}if(this.match(_.STRING)){let n=this.advance();return new Tt(n.value)}if(this.match(_.BOOLEAN)){let n=this.advance();return new Tt(n.value)}if(this.match(_.IDENTIFIER)||e.type===_.KEYWORD&&cs.CONTEXTUAL_KEYWORDS.has(e.value)){let n=this.advance().value;return this.functionNames.has(n)&&this.peek().type!==_.LPAREN&&!this.isCurrentFunctionParam(n)&&(n=n+"_var"),new be(n)}if(this.match(_.LBRACKET))return this.parseArrayLiteral();if(this.match(_.LPAREN)){this.advance(),this.skipNewlines();let n=this.parseExpression();return this.skipNewlines(),this.expect(_.RPAREN),n}if(this.match(_.KEYWORD,"if"))return this.parseIfExpression();if(this.match(_.KEYWORD,"switch"))return this.parseSwitchExpression();if(this.match(_.KEYWORD,"for"))return this.parseForExpression();if(this.match(_.KEYWORD,"while"))return this.parseWhileExpression();throw new Error(`Unexpected token ${e.type} \'${e.value}\' at ${e.line}:${e.column}`)}parseArrayLiteral(){this.expect(_.LBRACKET);let e=[];for(;!this.match(_.RBRACKET)&&(this.skipNewlines(),!this.match(_.RBRACKET));)e.push(this.parseExpression()),this.match(_.COMMA)&&this.advance(),this.skipNewlines();return this.expect(_.RBRACKET),new as(e)}parseIfExpression(){this.expect(_.KEYWORD,"if");let e=this.parseExpression();this.skipNewlines(),this.expect(_.INDENT);let n=[];for(;!this.match(_.DEDENT)&&!this.match(_.EOF)&&(this.skipNewlines(),!this.match(_.DEDENT));){let a=this.parseStatement();a&&n.push(a)}this.advance();let r=[];if(this.match(_.KEYWORD,"else"))if(this.advance(),this.skipNewlines(),this.match(_.KEYWORD,"if")){let a=this.parseIfExpression();if(this.needsIIFE(n,r)){let o=new vt(e,new wt(n),a);return o.needsIIFE=!0,o.consequentStmts=n,o.alternateExpr=a,o}else return new vt(e,this.getBlockValue(n),a)}else{for(this.expect(_.INDENT);!this.match(_.DEDENT)&&!this.match(_.EOF)&&(this.skipNewlines(),!this.match(_.DEDENT));){let a=this.parseStatement();a&&r.push(a)}this.advance()}if(this.needsIIFE(n,r)){let a=new vt(e,new wt(n),new wt(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 vt(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(_.KEYWORD,"switch");let e=null;!this.match(_.NEWLINE)&&!this.match(_.INDENT)&&(e=this.parseExpression()),this.skipNewlines(),this.expect(_.INDENT);let n=[];for(;!this.match(_.DEDENT)&&!this.match(_.EOF)&&(this.skipNewlines(),!this.match(_.DEDENT));){let r=null;this.match(_.OPERATOR,"=>")||(r=this.parseExpression()),this.expect(_.OPERATOR,"=>"),this.skipNewlines();let i=[];if(this.match(_.INDENT)){for(this.advance();!this.match(_.DEDENT)&&!this.match(_.EOF)&&(this.skipNewlines(),!this.match(_.DEDENT));){let a=this.parseStatement();a&&i.push(a)}this.advance()}else{this.noLineContinuation=!0;let a=this.parseStatement();this.noLineContinuation=!1,a&&i.push(a)}let s=this.getBlockValue(i);n.push(new ls(r,s,i)),this.skipNewlines()}return this.advance(),new os(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)}};dn(hl,"CONTEXTUAL_KEYWORDS",new Set(["type","method","enum"]));var j0=hl,$0=Object.defineProperty,W0=(t,e,n)=>e in t?$0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,It=(t,e,n)=>W0(t,typeof e!="symbol"?e+"":e,n),U0=new Set(Ps),us=class{constructor(e={}){It(this,"indent"),It(this,"indentStr"),It(this,"output"),It(this,"sourceCode"),It(this,"sourceLines"),It(this,"lastCommentedLine"),It(this,"includeSourceComments"),It(this,"paramRenameCounter"),It(this,"functionParams"),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}generate(e){if(this.output=[],this.indent=0,this.lastCommentedLine=-1,this.functionParams=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.collectFunctionParams(e),this.renameConflictingVariables(e)}renameConflictingVariables(e){let n=new Map;this.collectConflictingVarNames(e,n),n.size>0&&this.renameVariableRefsInAST(e,n)}isReservedName(e){return!!e&&(J_.has(e)||Aa.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++}`);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==="CallExpression"){if(e.callee?.type==="Identifier"&&n.has(e.callee.name)?Aa.has(e.callee.name)&&(e.callee.name=n.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))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=[];for(let r of e.params)r.type==="Identifier"?n.push(r.name):r.type==="AssignmentPattern"&&r.left?.name&&n.push(r.left.name);this.functionParams.set(e.id.name,n)}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":return this.generateBlockStatement(e);case"TypeDefinition":return this.generateTypeDefinition(e);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 c of e.params){let u=c.type==="AssignmentPattern"?c.left.name:c.name;if(u&&U0.has(u)){let h=`${u}_$${this.paramRenameCounter++}`;r.set(u,h)}}let i=c=>c.type==="Identifier"&&c.name==="this"||c.type==="AssignmentPattern"&&c.left?.name==="this",s=new Map;if(n&&e.params.length>0&&i(e.params[0])&&s.set("this","self"),r.size>0||s.size>0){for(let c of e.params){let u=c.type==="AssignmentPattern"?c.left:c;if(u?.type==="Identifier"){let h=r.get(u.name)??s.get(u.name);h&&(u.name=h)}c.type==="AssignmentPattern"&&c.right&&(r.size>0&&this.renameParamRefsInBody(c.right,r),s.size>0&&this.renameIdentifiersInAST(c.right,s))}r.size>0&&this.renameParamRefsInBody(e.body,r),s.size>0&&this.renameIdentifiersInAST(e.body,s)}let a=n?`$M_${e.id.name}`:e.id.name;this.write("function "),this.write(a),this.write("(");let o=e.params;for(let c=0;c<o.length;c++){let u=o[c];u.type==="Identifier"?this.write(u.name):u.type==="AssignmentPattern"&&(this.write(u.left.name),this.write(" = "),this.generateExpression(u.right)),c<o.length-1&&this.write(", ")}this.write(") "),this.generateBlockStatement(e.body,!1),this.write(`\n`),n&&(this.write(this.indentStr.repeat(this.indent)),this.write(`${a}.__pineMethod__ = true;\n`));let l=[];for(let c=0;c<e.params.length;c++){let u=e.params[c],h=u.type==="AssignmentPattern"?u.left?.name:u.name;if(n&&c===0&&h==="self")continue;let p=u.type==="AssignmentPattern"?u.left?.varType:u.varType;h&&p&&l.push([h,p])}if(l.length>0){this.write(this.indentStr.repeat(this.indent));let c=l.map(([u,h])=>`${JSON.stringify(u)}: ${JSON.stringify(h)}`).join(", ");this.write(`${a}.__pineParamTypes__ = {${c}};\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.init&&i.init.type==="ConditionalExpression"&&i.init.needsIIFE){let o=i.id.type==="Identifier"?i.id.name:null;if(o){this.write(this.indentStr.repeat(this.indent)),this.write(n),this.write(" "),this.write(o),this.write(`;\n`),this.generateIfStatementWithAssignment(i.init,o);continue}}if(this.write(this.indentStr.repeat(this.indent)),this.write(n),this.write(" "),i.id.type==="Identifier")this.write(i.id.name);else if(i.id.type==="ArrayPattern"){let o=new Set;this.write("[");for(let l=0;l<i.id.elements.length;l++){let c=i.id.elements[l].name;if(o.has(c)){let u=`${c}${this.paramRenameCounter++}`;i.id.elements[l].name=u,c=u}o.add(c),this.write(c),l<i.id.elements.length-1&&this.write(", ")}this.write("]")}i.init&&(this.write(" = "),this.generateExpression(i.init)),this.write(`;\n`);let s=i.id?.varType,a=i.id?.type==="Identifier"?i.id.name:null;a&&typeof s=="string"&&/^[A-Za-z_$][\\w$]*$/.test(s)&&s[0]===s[0].toUpperCase()&&(this.write(this.indentStr.repeat(this.indent)),this.write(`"__pineUdtVar:${a}=${s}";\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];if(this.write(`${e.init.kind} `),n.id.type==="Identifier")this.write(n.id.name);else if(n.id.type==="ArrayPattern"){let r=new Set;this.write("[");for(let i=0;i<n.id.elements.length;i++){let s=n.id.elements[i].name;if(r.has(s)){let a=`${s}${this.paramRenameCounter++}`;n.id.elements[i].name=a,s=a}r.add(s),this.write(s),i<n.id.elements.length-1&&this.write(", ")}this.write("]")}this.write(" of "),this.generateExpression(n.init)}this.write(") "),this.generateBlockStatement(e.body,!1);return}if(this.write("for ("),e.init)if(e.init.type==="VariableDeclaration"){let n=e.init.declarations[0];this.write(`${e.init.kind} ${n.id.name}`),n.init&&(this.write(" = "),this.generateExpression(n.init))}else 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"&&e.raw.includes(".")&&!/[.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(" "),this.generateExpression(e.right)}generateUpdateExpression(e){e.prefix?(this.write(e.operator),this.generateExpression(e.argument)):(this.generateExpression(e.argument),this.write(e.operator))}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=n?this.functionParams.get(n):null,i=e.arguments.length>0?e.arguments[e.arguments.length-1]:null;if(i?.type==="ObjectExpression"&&r){let s=e.arguments.slice(0,-1),a=new Map;for(let u of i.properties){let h=u.key?.name||u.key?.value;h&&a.set(h,u.value)}let o=[],l=-1;for(let u=0;u<r.length;u++)u<s.length?(o.push(s[u]),l=u):a.has(r[u])?(o.push(a.get(r[u])),l=u):o.push(null);let c=o.slice(0,l+1);for(let u=0;u<c.length;u++)c[u]===null?this.write("undefined"):this.generateExpression(c[u]),u<c.length-1&&this.write(", ")}else for(let s=0;s<e.arguments.length;s++){let a=e.arguments[s];a.type==="AssignmentExpression"&&a.operator==="="?this.generateExpression(a.right):this.generateExpression(a),s<e.arguments.length-1&&this.write(", ")}this.write(")")}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`)}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{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.indent--,this.write(this.indentStr.repeat(this.indent)),this.write(`}\n`),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{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.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("})()")}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}}};function dl(t){let e=/^\\s*\\/\\/\\s*@version\\s*=\\s*(\\d+)\\s*$/im,n=t.match(e);return n&&n[1]?parseInt(n[1],10):null}function Fs(t,e={}){let n=dl(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 es(t).tokenize(),i=new j0(r).parse(),s={...e,sourceCode:t},a=new us(s).generate(i);return{success:!0,version:n,code:a,ast:i,tokens:r}}catch(r){return{success:!1,version:n,error:r.message,stack:r.stack}}}var q0=new Set(["security_lower_tf","security"]),fl=new Set(["type","loc","start","end","range","parent","leadingComments","trailingComments"]);function z0(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:q0.has(e.property.name)}function K0(t){let e=t?.arguments?.[2];return e?.type==="Identifier"&&typeof e.name=="string"?e.name:null}function H0(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]);z0(i)&&e.push({call:i,path:a});for(let o of Object.keys(i)){if(fl.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 ps(t){return t?t.type==="FunctionExpression"||t.type==="ArrowFunctionExpression"||t.type==="FunctionDeclaration":!1}function Et(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(Et(r,e,n+1)),{...t,body:s}}case"IfStatement":return r===t.test?{...t,test:Et(r,e,n+1),consequent:{type:"BlockStatement",body:[]},alternate:null}:r===t.consequent?{...t,consequent:Et(r,e,n+1),alternate:null}:r===t.alternate?{...t,alternate:Et(r,e,n+1)}:t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"ForInStatement":case"ForOfStatement":return r===t.body?{...t,body:Et(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(Et(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(Et(r,e,n+1)),{...t,consequent:s}}return t}case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":return r===t.body?{...t,body:Et(r,e,n+1)}:t;default:return t}}function G0(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 Y0(t,e,n){let r=t.body||[];for(let i=0;i<r.length;i++){let s=r[i];if(s!==n&&Z0(s,e))return i}return-1}function Z0(t,e){let n=!1,r=new WeakSet;function i(s){if(!(n||!s||typeof s!="object")&&!r.has(s)){if(r.add(s),G0(s)===e){n=!0;return}for(let a of Object.keys(s)){if(fl.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 X0(t,e){let n=-1;for(let p=1;p<e.length;p++)if(ps(e[p])){n=p;break}if(n<0)return null;let r=e[n];for(let p=n+1;p<e.length;p++)if(ps(e[p]))return null;if(r.type!=="FunctionDeclaration"||!r.id?.name)return null;let i=r.id.name,s=e.slice(n),a=Et(r,s,0),o=Y0(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 Q0(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 = ${Ds(n)}\n; return _r;`;return new Function("",r)()}function J0(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=H0(r.body);for(let{call:s,path:a}of i){let o=K0(s);if(!o||o in e)continue;let l=a.some(h=>ps(h)),c=null;if(l)c=X0(r.body,a);else{let h=Et(r.body,a,0);c=h&&h.body?h.body:[]}if(!c||c.length===0)continue;let u=Q0(r,c);e[o]=u}return e}function ex(t){if(typeof t=="function")return{code:t.toString(),version:null};{let e=dl(t);if(e===null)return{code:t,version:null};if(e>=5){let n=Fs(t);if(n.success)return{code:n.code,version:e};throw new Error(`Failed to transpile Pine Script version ${e}: ${n.error}`)}else throw new Error(`Unsupported Pine Script version ${e}. Only version 5 and above are supported.`)}}function tx(t,e={debug:!1,ln:!1}){typeof e=="boolean"&&(e={debug:e,ln:!0});let{debug:n}=e,{code:r,version:i}=ex(t),s=r;s=s0(s);let a=n?s.split(`\n`):[],o=As(s,{ecmaVersion:"latest",sourceType:"module",locations:n});a0(o),n0(o),t0(o);let l=new Gi;c0(o,l),o0(o,l);let c=p0(o,l)||"";if(i!==null&&i<6&&b0(o),D0(o,l,c,e,a),T0(o),N0(o),o.type==="Program"&&o.body.length>0){let m=o.body[0],x=m?.expression||m;x.body?.type==="BlockStatement"&&x.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=q_||Ts||void 0,h=Object.assign({},u,{LineComment(m,x){x.write("//"+m.value)}}),p=Ds(o,{generator:h,comments:n}),d=typeof process<"u"&&process?.env?.PINETS_DISABLE_LTF_SLICING==="1"?{}:J0(o),f=new Function("",`var _r = ${p}\n; return _r;`)(this);return d&&Object.keys(d).length>0&&(f._ltfSlices=d),f}var Ta={"":["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"]},nx={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"};function rx(t){if(typeof t!="string")return[];let e=Fs(t);if(!e.success||!e.ast)return[];let n=ix(e.ast),r=sx(e.ast),i=[],s=new Set;return Dt(e.ast,a=>{let o=ax(a,n,r);if(o){if(o.varId!==void 0){if(s.has(o.varId)){console.warn(`[Indicator] duplicate input variable "${o.varId}" \\u2014 first declaration wins for .input access`);return}s.add(o.varId)}i.push(o)}}),i}function ix(t){let e=new Map;return Dt(t,n=>{if(n.type==="VariableDeclaration")for(let r of n.declarations??[]){let i=r?.id?.name,s=r?.init;if(!i||!s||s.type!=="ObjectExpression"||!(s.properties??[]).every(a=>a.value?.type==="Literal"&&typeof a.value.value=="string")||s.properties.length===0)return;for(let a of s.properties)e.set(`${i}.${a.key.name}`,a.value.value)}}),e}function sx(t){let e=new Map;return Dt(t,n=>{if(n.type==="VariableDeclaration")for(let r of n.declarations??[])r?.id?.type==="Identifier"&&r.init&&!e.has(r.id.name)&&e.set(r.id.name,r.init)}),e}function ax(t,e,n){if(t.type!=="VariableDeclaration")return null;for(let r of t.declarations??[]){let i=r?.init;if(!i||i.type!=="CallExpression")continue;let s=i.callee,a=null;if(s?.type==="MemberExpression"&&s.object?.type==="Identifier"&&s.object.name==="input"&&s.property?.type==="Identifier"?a=s.property.name:s?.type==="Identifier"&&s.name==="input"&&(a=""),a===null||a!==""&&!(a==="int"||a==="float")&&!(a in Ta))continue;let o=i.arguments??[],l=o[o.length-1],c=l?.type==="ObjectExpression",u=c?o.slice(0,-1):o.slice(),h=c?l.properties??[]:[],p={};a==="int"||a==="float"?ox(u,h,p):ml(Ta[a],u,p);for(let x of h)x.type!=="Property"||!x.key?.name||(p[x.key.name]=x.value);let d={};for(let x of Object.keys(p))d[x]=pr(p[x],e,n);let f=a===""?lx(d.defval):nx[a];if(!f)continue;let m={type:f,defval:d.defval};return r.id?.type==="Identifier"&&typeof r.id.name=="string"&&(m.varId=r.id.name),d.title!==void 0&&(m.title=String(d.title)),d.tooltip!==void 0&&(m.tooltip=String(d.tooltip)),d.group!==void 0&&(m.group=String(d.group)),d.inline!==void 0&&(m.inline=String(d.inline)),d.confirm!==void 0&&(m.confirm=!!d.confirm),d.active!==void 0&&(m.active=!!d.active),d.display!==void 0&&(m.display=cx(d.display)),d.options!==void 0&&Array.isArray(d.options)&&(m.options=d.options),typeof d.minval=="number"&&(m.minval=d.minval),typeof d.maxval=="number"&&(m.maxval=d.maxval),typeof d.step=="number"&&(m.step=d.step),m}return null}function ox(t,e,n){let r=new Set(e.map(i=>i.key?.name).filter(Boolean)).has("options")||t[2]?.type==="ArrayExpression"?["defval","title","options","tooltip","inline","group","confirm","display","active"]:["defval","title","minval","maxval","step","tooltip","inline","group","confirm","display","active"];ml(r,t,n)}function ml(t,e,n){for(let r=0;r<e.length&&r<t.length;r++){let i=t[r];n[i]===void 0&&(n[i]=e[r])}}function pr(t,e,n,r=new Set){if(t!=null)switch(t.type){case"Literal":return t.value;case"Identifier":if(_s.has(t.name))return t.name;if(n?.has(t.name)&&!r.has(t.name)){r.add(t.name);let i=pr(n.get(t.name),e,n,r);if(r.delete(t.name),i!==void 0)return i}return t.name;case"MemberExpression":{let i=t.object?.type==="Identifier"?t.object.name:null,s=t.property?.type==="Identifier"?t.property.name:null;if(i&&s){let a=`${i}.${s}`;return e.has(a)?e.get(a):i==="display"?s:a}return}case"CallExpression":{let i=t.callee;if(i?.type==="MemberExpression"&&i.object?.type==="Identifier"&&i.object.name==="color"&&i.property?.type==="Identifier"){let s=i.property.name,a=(t.arguments??[]).map(l=>pr(l,e,n,r)),o=l=>Math.max(0,Math.min(1,l));if(s==="rgb"){let[l,c,u,h]=a;if(typeof l=="number"&&typeof c=="number"&&typeof u=="number"){let p=o(1-(typeof h=="number"?h:0)/100);return Ci(l,c,u,p)}}else if(s==="new"){let l=uo(a[0]),c=a[1];if(l&&typeof c=="number")return Ci(l[0],l[1],l[2],o(1-c/100))}}return}case"ArrayExpression":return(t.elements??[]).map(i=>pr(i,e,n,r));case"UnaryExpression":return t.operator==="-"&&t.argument?.type==="Literal"&&typeof t.argument.value=="number"?-t.argument.value:void 0;default:return}}function lx(t){return typeof t=="boolean"?"bool":typeof t=="number"?Number.isInteger(t)?"int":"float":typeof t=="string"?_s.has(t)?"source":t.startsWith("#")?"color":"string":null}function cx(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 Dt(t,e){if(!(!t||typeof t!="object")){if(e(t),Array.isArray(t.body))for(let n of t.body)Dt(n,e);else t.body&&Dt(t.body,e);if(Array.isArray(t.consequent))for(let n of t.consequent)Dt(n,e);else t.consequent&&Dt(t.consequent,e);if(t.alternate&&Dt(t.alternate,e),Array.isArray(t.declarations))for(let n of t.declarations)Dt(n,e)}}function yl(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 ux(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 ux(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 ${hn(e)}`);break;case"float":case"price":case"time":if(typeof e!="number"||!Number.isFinite(e))throw new TypeError(`[${n}] "${r}" expects a number; got ${hn(e)}`);break;case"bool":if(typeof e!="boolean")throw new TypeError(`[${n}] "${r}" expects a boolean; got ${hn(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 ${hn(e)}`);break}if(t.options&&!t.options.some(i=>px(i,e)))throw new RangeError(`[${n}] "${r}" value ${hn(e)} is not one of: ${t.options.map(hn).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 px(t,e){return t===e?!0:typeof t=="number"&&typeof e=="number"?Math.abs(t-e)<1e-12:!1}function hn(t){return t===null?"null":typeof t=="string"?JSON.stringify(t):String(t)}function hx(t,e){let n=new Map,r=[];for(let a of t){let o=a.varId??a.title;if(!o)continue;let l=a.title&&a.title!==o?[a.title]:void 0;n.set(o,a),r.push({key:o,type:a.type,defval:a.defval,options:a.options,minval:a.minval,maxval:a.maxval,aliases:l})}let{proxy:i,values:s}=yl(r,"Indicator.input",e,void 0,"input key");return{proxy:i,values:s,metaByKey:n}}var gl=[{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}],_l=[...gl.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"}],xl=[...gl.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 dx(t){return t==="strategy"?xl:_l}function fx(t){return typeof t=="string"?mx(t):typeof t=="function"?yx(t):{type:null,args:{}}}function mx(t){let e=Fs(t);if(!e.success||!e.ast)return{type:null,args:{}};let n=null;return $r(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:wl(i.arguments??[],bl(s.name))}))}),n??{type:null,args:{}}}function yx(t){let e;try{e=As(`(${t.toString()})`,{ecmaVersion:"latest"})}catch{return{type:null,args:{}}}let n=null;return $r(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:wl(r.arguments??[],bl(i.name))}))}),n??{type:null,args:{}}}function bl(t){return t==="strategy"?xl:_l}function wl(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]=hs(s[a])}if(i)for(let a of r.properties??[])a.type!=="Property"||!a.key?.name||(n[a.key.name]=hs(a.value));return n}function hs(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(hs);default:return}}function $r(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)$r(i,e);else r&&typeof r=="object"&&typeof r.type=="string"&&$r(r,e)}}}function gx(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}=yl(i,"Indicator.prop",n,e);return{proxy:s,values:a,propByName:r}}var _x=Object.defineProperty,xx=(t,e,n)=>e in t?_x(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ge=(t,e,n)=>xx(t,typeof e!="symbol"?e+"":e,n),Qt=class t{constructor(e,n={}){Ge(this,"source"),Ge(this,"inputs"),Ge(this,"_prepared",null),Ge(this,"_inputMeta",null),Ge(this,"_inputValues",{}),Ge(this,"_explicitOverrides",new Set),Ge(this,"_inputProxy",null),Ge(this,"_propMeta",null),Ge(this,"_propValues",{}),Ge(this,"_propProxy",null),Ge(this,"_declarationType",null),Ge(this,"_sourcePropArgs",{}),Ge(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=tx(this.source,{debug:!!e.debug,ln:e.ln}),r=bx(n),i=n._ltfSlices;return this._prepared={fn:n,inputs:this.getRuntimeInputs(),usesVisibleRange:r,ltfSlices:i},this._prepared}usesVisibleRange(){return this.prepare().usesVisibleRange}getRuntimeInputs(){let e={...this.inputs??{}};if(this._inputMeta)for(let n of this._explicitOverrides)e[n]=this._inputValues[n];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=rx(this.source);for(let n of this._inputMeta)n.type==="color"&&n.defval!==void 0&&(n.defval=gh(n.defval));let e=hx(this._inputMeta,n=>this._explicitOverrides.add(n));this._inputValues=e.values,this._inputProxy=e.proxy}_getInputProxy(){return this._ensureInputsScanned(),this._inputProxy}_ensurePropsScanned(){if(this._propMeta)return;let e=fx(this.source);this._declarationType=e.type,this._sourcePropArgs=e.args,this._propMeta=dx(e.type);let n=gx(this._propMeta,this._sourcePropArgs,r=>this._explicitPropOverrides.add(r));this._propValues=n.values,this._propProxy=n.proxy}_getPropProxy(){return this._ensurePropsScanned(),this._propProxy}};function bx(t){let e=t.toString();return X_.some(n=>{let r=n.replace(/\\./g,"\\\\.");return new RegExp(`\\\\b${r}\\\\b`).test(e)})}var wx=Object.defineProperty,vx=(t,e,n)=>e in t?wx(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,oe=(t,e,n)=>vx(t,typeof e!="symbol"?e+"":e,n),Da={1:6e4,3:18e4,5:3e5,15:9e5,30:18e5,60:36e5,120:72e5,180:108e5,240:144e5,"4H":144e5,"1D":864e5,D:864e5,"1W":6048e5,W:6048e5,"1M":30*864e5,M:30*864e5};function Ex(t){return t?Da[t]??Da[t.toUpperCase()]??864e5:864e5}var Ut=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,oe(this,"data",[]),oe(this,"open",[]),oe(this,"high",[]),oe(this,"low",[]),oe(this,"close",[]),oe(this,"volume",[]),oe(this,"hl2",[]),oe(this,"hlc3",[]),oe(this,"ohlc4",[]),oe(this,"hlcc4",[]),oe(this,"openTime",[]),oe(this,"closeTime",[]),oe(this,"_readyPromise",null),oe(this,"_ready",!1),oe(this,"_debugSettings",{ln:!1,debug:!1}),oe(this,"_transpiledCode",null),oe(this,"_currentIndicator",null),oe(this,"_isSecondaryContext",!1),oe(this,"_syminfo"),oe(this,"_chartTimezone",null),oe(this,"_maxLoops",5e5),oe(this,"_alertMode","realtime"),oe(this,"_viewportLeft"),oe(this,"_viewportRight"),oe(this,"_usesVisibleRange",!1),oe(this,"_lastRunViewport",{}),oe(this,"_lastResult",null),oe(this,"_lastPineTSCode",null),this._readyPromise=new Promise(o=>{this.loadMarketData(e,n,r,i,s,a).then(l=>{let c=l;this.data=c;let u=c.map(C=>C.open),h=c.map(C=>C.close),p=c.map(C=>C.high),d=c.map(C=>C.low),f=c.map(C=>C.volume),m=c.map(C=>(C.high+C.low+C.close)/3),x=c.map(C=>(C.high+C.low)/2),b=c.map(C=>(C.high+C.low+C.open+C.close)/4),w=c.map(C=>(C.high+C.low+C.close+C.close)/4),E=c.map(C=>C.openTime),v=Ex(this.timeframe),I=c.map(C=>C.closeTime!=null?C.closeTime:C.openTime+v);this.open=u,this.close=h,this.high=p,this.low=d,this.volume=f,this.hl2=x,this.hlc3=m,this.ohlc4=b,this.hlcc4=w,this.openTime=E,this.closeTime=I,e&&e.getSymbolInfo?e.getSymbolInfo(n).then(C=>{this._syminfo=C,this._ready=!0,o(!0)}).catch(C=>{console.warn("Failed to get symbol info, using default values:",C),this._ready=!0,o(!0)}):(this._ready=!0,o(!0))})})}get transpiledCode(){return this._transpiledCode}markAsSecondary(){this._isSecondaryContext=!0}setTimezone(e){this._chartTimezone=e}setMaxLoops(e){this._maxLoops=e}setAlertMode(e){this._alertMode=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}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=Qt.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=Qt.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],x=m&&m.closeTime<Date.now(),b=f.idx>=f.marketData.length-1;(!x||b)&&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);this._transpiledCode=e;let s=e._ltfSlices;return s&&(i._ltfTruncatedBodies=s),await this._executeIterations(i,e,this.data.length-r,this.data.length),i}async _runComplete(e,n){await this.ready(),n||(n=this.data.length);let r=e.prepare(this._debugSettings);this._usesVisibleRange=r.usesVisibleRange;let i=this._initializeContext(e.source??null,r.inputs,this._isSecondaryContext);this._transpiledCode=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);let s=e.prepare(this._debugSettings);this._usesVisibleRange=s.usesVisibleRange;let a=this._initializeContext(e.source??null,s.inputs,this._isSecondaryContext);this._transpiledCode=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),x=this._getResultLength(a.result),b=o+m;i&&b>=c&&m>1?(await this._executeIterations(a,this._transpiledCode,o,b-1),l=this._snapshotVarState(a),await this._executeIterations(a,this._transpiledCode,b-1,b)):i&&b>=c&&m===1?await this._executeIterations(a,this._transpiledCode,o,b):await this._executeIterations(a,this._transpiledCode,o,b),o+=m,yield this._createPageContext(a,x);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 _n({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]=n.closeTime}_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(e.closeTime)}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;if(i?this._restoreVarState(e,i):this._removeLastResult(e),Array.isArray(e.result))e.result.pop();else if(typeof e.result=="object"&&e.result!==null)for(let o in e.result)Array.isArray(e.result[o])&&e.result[o].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(),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}_removeLastResult(e){if(Array.isArray(e.result))e.result.pop();else if(typeof e.result=="object"&&e.result!==null)for(let i in e.result)Array.isArray(e.result[i])&&e.result[i].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();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 y?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 y){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=wm(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 y&&u&&typeof u.len=="number"&&(c.data.length>u.len&&(c.data.length=u.len),u.len>0&&u.lastVal!==void 0&&(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++})}vm(e.strategy,n.strategy)}_initializeContext(e,n={},r=!1){let i=new _n({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=this._syminfo;let s=jn(String(this.tickerId??"")).modifier;return i.chartStyle=s==="heikinashi"?"heikinashi":"standard",this._syminfo&&s==="heikinashi"&&(i.pine.syminfo={...this._syminfo,tickerid:Ai(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._propOverrides=this._currentIndicator?.getRuntimePropOverrides()??{},i.pineTSCode=e,i.isSecondaryContext=r,i.data.close=new y([]),i.data.open=new y([]),i.data.high=new y([]),i.data.low=new y([]),i.data.volume=new y([]),i.data.hl2=new y([]),i.data.hlc3=new y([]),i.data.ohlc4=new y([]),i.data.hlcc4=new y([]),i.data.openTime=new y([]),i.data.closeTime=new y([]),i.length=this.data.length,i}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){hm(e),im(e),ci(e,"open");let c=dm(e);c&&ci(e,"extreme"),pm(e,"intrabar"),c||ci(e,"extreme"),fm(e)}let o=await n(e);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 y?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 y){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&&mm(e)}},Ma={"1m":6e4,"3m":18e4,"5m":3e5,"15m":9e5,"30m":18e5,"1h":36e5,"2h":72e5,"4h":144e5,"1d":864e5,"1w":6048e5,"1M":2592e6},On={"1S":1,"5S":5,"10S":10,"15S":15,"30S":30,1:60,3:180,5:300,15:900,30:1800,45:2700,60:3600,120:7200,180:10800,240:14400,D:86400,W:604800,M:2592e3};function Vn(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 St(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=b=>parseInt(c.find(w=>w.type===b).value,10),h=u("year"),p=u("month"),d=u("day"),f=u("hour");f===24&&(f=0);let m=u("minute"),x=Date.UTC(h,p-1,d,f,m,0,0)-l;return l-x}function Pa(t,e,n,r,i=1){if(e==="24x7")return Vn(t,r,i);let s=e.split("-")[1];if(!s||s.length!==4)return Vn(t,r,i);let a=s.slice(0,2),o=s.slice(2,4),l=`${a}:${o}`,c=Ra(t,n);if(r==="second"||r==="minute"||r==="hour"){let u=t+i*{second:1e3,minute:6e4,hour:36e5}[r],h=St(c,l,n);return Math.min(u,h)}if(r==="day")return St(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=Ra(p,n);return St(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 St(m,l,n)}return Vn(t,r,i)}function Ra(t,e){return new Intl.DateTimeFormat("en-CA",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(t))}function Sx(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 Cx=["1S","5S","10S","15S","30S","1","3","5","15","30","45","60","120","180","240","D","W","M"];function Nx(t,e){if(t==="W"||t==="M")return e.has("D")?"D":null;let n=On[t];if(!n)return null;let r=Cx.filter(i=>i!=="W"&&i!=="M"&&e.has(i)&&On[i]<n&&n%On[i]===0);return r.length===0?null:r[r.length-1]}function vl(t,e){if(t==="W"||t==="M")return 1/0;let n=On[t],r=On[e];return!n||!r||r===0?1/0:n/r}function kx(t,e,n){if(t.length===0)return[];if(e==="W")return Ax(t);if(e==="M")return Tx(t);let r=vl(e,n);return Ix(t,r)}function Ix(t,e){if(t.length===0)return[];let n=[],r=[t[0]],i=Dx(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(Wr(r)),r=[]),r.push(t[a])}return r.length>0&&n.push(Wr(r)),n}function Ax(t){let e=[],n=[],r="";for(let i of t){let s=Mx(i.openTime);s!==r&&n.length>0&&(e.push(n),n=[]),r=s,n.push(i)}return n.length>0&&e.push(n),e.map(Wr)}function Tx(t){let e=[],n=[],r="";for(let i of t){let s=new Date(i.openTime),a=`${s.getUTCFullYear()}-${s.getUTCMonth()}`;a!==r&&n.length>0&&(e.push(n),n=[]),r=a,n.push(i)}return n.length>0&&e.push(n),e.map(Wr)}function Wr(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 Dx(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}function Mx(t){let e=new Date(t),n=e.getUTCDay()||7;e.setUTCDate(e.getUTCDate()+4-n);let r=new Date(Date.UTC(e.getUTCFullYear(),0,1)),i=Math.ceil(((e.getTime()-r.getTime())/864e5+1)/7);return`${e.getUTCFullYear()}-W${i}`}var Px=Object.defineProperty,Rx=(t,e,n)=>e in t?Px(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,rr=(t,e,n)=>Rx(t,typeof e!="symbol"?e+"":e,n),ir={"1s":"1S","5s":"5S","10s":"10S","15s":"15S","30s":"30S","1m":"1","3m":"3","5m":"5","15m":"15","30m":"30","45m":"45","1h":"60","2h":"120","3h":"180","4h":"240","1d":"D","1w":"W","1D":"D","1W":"W","1M":"M","4H":"240",D:"D",W:"W",M:"M"};function Fx(t){if(ir[t]!==void 0)return ir[t];let e=t.toLowerCase();return ir[e]!==void 0?ir[e]:/^\\d+$/.test(t)?t:/^\\d+S$/i.test(t)?t.toUpperCase():t}var Un=class{constructor(e){rr(this,"_configured"),rr(this,"_requiresApiKey"),rr(this,"_providerName"),rr(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){Sx(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"])}async getMarketData(e,n,r,i,s){e=Ot(e);let a=Fx(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:Nx(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=await this._getMarketDataNative(e,c,u,i,s);if(h.length===0)return[];let p=kx(h,a,c);return r&&r>0&&p.length>r?p.slice(p.length-r):p}_computeSubLimit(e,n,r){if(!r)return;let i=vl(e,n);return i===1/0?e==="W"?r*7+14:e==="M"?r*31+31:r*30:Math.ceil(r*i)+Math.ceil(i)}},Bx=Object.defineProperty,Lx=(t,e,n)=>e in t?Bx(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ur=(t,e,n)=>Lx(t,typeof e!="symbol"?e+"":e,n),yi="https://api.binance.com/api/v3",Fa="https://api.binance.us/api/v3",sr={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"},ds=class{constructor(e=300*1e3){Ur(this,"cache"),Ur(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)}},fs=class extends Un{constructor(){super({requiresApiKey:!1,providerName:"Binance"}),Ur(this,"cacheManager"),Ur(this,"activeApiUrl",null),this.cacheManager=new ds(300*1e3)}async getBaseUrl(){if(this.activeApiUrl)return this.activeApiUrl;try{let e=new AbortController,n=setTimeout(()=>e.abort(),5e3),r=await fetch(`${yi}/ping`,{signal:e.signal});if(clearTimeout(n),r.ok)return this.activeApiUrl=yi,this.activeApiUrl}catch{}try{let e=new AbortController,n=setTimeout(()=>e.abort(),5e3),r=await fetch(`${Fa}/ping`,{signal:e.signal});if(clearTimeout(n),r.ok)return this.activeApiUrl=Fa,this.activeApiUrl}catch{}return yi}async _fetchRawChunk(e,n,r,i,s){let a=sr[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=sr[n.toUpperCase()];if(!s)return console.error(`Unsupported timeframe: ${n}`),[];let a=[],o=r,l=i,c=Ma[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)break;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"])}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(!sr[n.toUpperCase()])return console.error(`Unsupported timeframe: ${n}`),[];if(this.shouldPaginate(n,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,i){if(n&&n>1e3)return!0;if(r&&i){let s=sr[e.toUpperCase()],a=Ma[s];if(a)return Math.ceil((i-r)/a)>1e3}return!1}async getSymbolInfo(e){e=Ot(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(E=>E.symbol===i):l[0];if(!c)return console.error(`Symbol ${i} not found in exchange info`),null;let u=c.filters?.find(E=>E.filterType==="PRICE_FILTER"),h=c.filters?.find(E=>E.filterType==="LOT_SIZE"),p=u?parseFloat(u.tickSize):.01,d=h?parseFloat(h.minQty):0,f=Math.round(1/p),m=c.baseAsset,x=c.quoteAsset,b=s?` ${s}`:"",w=`${m} / ${x}${b}`;return{ticker:e,tickerid:`BINANCE:${e}`,prefix:"BINANCE",root:m,description:w,type:n,main_tickerid:`BINANCE:${e}`,current_contract:s,isin:"",basecurrency:m,currency:x,timezone:"Etc/UTC",country:"",mintick:p,pricescale:f,minmove:1,pointvalue:c.contractSize||1,mincontract:d,session:"24x7",volumetype:"base",expiration_date:c.deliveryDate||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 binance.exchangeInfo:",n),null}}},Ox=Object.defineProperty,Vx=(t,e,n)=>e in t?Ox(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Nn=(t,e,n)=>Vx(t,typeof e!="symbol"?e+"":e,n),jx="https://financialmodelingprep.com",Ba=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"]),La={"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"}},Oa={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"},Va={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"},$x={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}},ms=class extends Un{constructor(e){super({requiresApiKey:!0,providerName:"FMP"}),Nn(this,"_apiKey",null),Nn(this,"_baseUrl",jx),Nn(this,"_profileCache",new Map),Nn(this,"_symbolInfoCache",new Map),Nn(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=La[a]||La[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=${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=Pa(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=${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}=$x[r]||{periodType:"minute",multiplier:1},{session:d,timezone:f}=await this._resolveSessionInfo(e);return u.map(m=>{let x=this._dateTimeStrToMs(m.date),b=Pa(x,d,f,h,p);return{openTime:x,open:m.open,high:m.high,low:m.low,close:m.close,volume:m.volume,closeTime:b,quoteAssetVolume:0,numberOfTrades:0,takerBuyBaseAssetVolume:0,takerBuyQuoteAssetVolume:0,ignore:0}})}async getSymbolInfo(e){if(this.ensureConfigured(),e=Ot(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":Oa[i]||"America/New_York",a=r==="crypto"?"24x7":r==="forex"?"0000-0000":Va[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=${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":Oa[r]||"America/New_York";return{session:i?"24x7":Va[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)&&Ba.has(e.slice(0,3))&&Ba.has(e.slice(3,6))}_isCrypto(e){return this._isForex(e)?!1:/^[A-Z]+(USD|USDT|BTC|ETH)$/.test(e)&&e.length<=15}},Wx=Object.defineProperty,Ux=(t,e,n)=>e in t?Wx(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Kt=(t,e,n)=>Ux(t,typeof e!="symbol"?e+"":e,n),qx="https://data.alpaca.markets",zx="https://paper-api.alpaca.markets/v2",Kx="https://api.alpaca.markets/v2",gi=1e4,ja={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"},Hx={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"},Gx={NASDAQ:"0930-1600",NYSE:"0930-1600",AMEX:"0930-1600",ARCA:"0930-1600",BATS:"0930-1600",OTC:"0930-1600",CRYPTO:"24x7"},Yx={Min:"minute",Hour:"hour",Day:"day",Week:"week",Month:"month"},ys=class extends Un{constructor(e){super({requiresApiKey:!0,providerName:"Alpaca"}),Kt(this,"_apiKey",null),Kt(this,"_apiSecret",null),Kt(this,"_dataUrl",qx),Kt(this,"_tradingUrl",zx),Kt(this,"_feed",null),Kt(this,"_assetCache",new Map),Kt(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=Kx)}_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||gi,gi);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,gi))),o&&c.set("page_token",o),!r&&this._feed&&c.set("feed",this._feed),`${l}?${c.toString()}`}async getSymbolInfo(e){this.ensureConfigured(),e=Ot(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":Hx[r]||"America/New_York",a=i?"24x7":Gx[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():Vn(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=St(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=St(o,h,i);l=Math.min(c,p)}else n==="week"?l=this._weeklyCloseFromCalendar(o,i):n==="month"?l=this._monthlyCloseFromCalendar(o,i):l=Vn(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 St(u,h.close,n)}let a=r.getTime()+s*864e5,o=new Date(a).toISOString().split("T")[0];return St(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 St(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 St(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=Yx[n[2]];if(i)return{periodType:i,multiplier:r}}return{periodType:"day",multiplier:1}}_resolveTimeframe(e){return ja[e.toUpperCase()]||ja[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]}},gs=class{async getMarketData(){return[]}},Zx=typeof process<"u"&&process.versions&&process.versions.node,qr=null;if(Zx)try{qr=new gs}catch{qr=null}var Kb={Binance:new fs,FMP:new ms,Alpaca:new ys,...qr?{Mock:qr}:{}};function V(t){return typeof t=="string"?t:void 0}function se(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Xx(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 Qr(t){let e=t??{},n=e.fullContext??e,r=n.indicator??n.strategy?.config??{},i={title:V(r.title)??"Indicator",overlay:r.overlay===!0,precision:se(r.precision),shorttitle:V(r.shorttitle),format:V(r.format)},s=n.plots??{},a=Object.entries(s).map(([l,c])=>{let u=c??{},h=u.options??{};return{key:l,title:V(u.title),style:V(h.style),options:h,data:Array.isArray(u.data)?Xx(u.data):[],plot1:V(u.plot1)??V(h.plot1),plot2:V(u.plot2)??V(h.plot2)}}),o=n.strategy?Qx(n.strategy):void 0;return{meta:i,plots:a,...o?{trades:o}:{}}}function Qx(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=se(s.entry_price),o=se(s.entry_time),l=se(s.size);a===void 0||o===void 0||l===void 0||l===0||e.push({id:V(s.id)??`trade_${e.length}`,entry_id:V(s.entry_id)??"",entry_price:a,entry_time:o,entry_comment:V(s.entry_comment),exit_id:V(s.exit_id),exit_price:se(s.exit_price),exit_time:se(s.exit_time),exit_comment:V(s.exit_comment),size:l,status:s.status==="closed"?"closed":"open"})}return e}var Jx={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 El(t){return t==null||t===""?"line":Jx[t]??"line"}function Jr(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*\\)$/.test(e))}function ee(t,e){return Jr(t)?t.trim():e}var Sl="#00000000";function Bs(t){let e=t.title.trim().toLowerCase().replace(/\\s+/g,"-");return`${t.instanceId}:${t.kind}:${e}#${t.ordinal}`}var Ls="#2962ff";var Os="#089981",Vs="#f23645";var eb=new Map;function M(t,e){eb.set(t,e)}function tb(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 fe(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 $=tb;M("style-candles",$(\'<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"/>\'));M("style-bars",$(\'<path d="M4.5 2.5v11M2.5 5h2M4.5 11h2"/><path d="M11.5 2.5v11M9.5 4.5h2M11.5 10.5h2"/>\'));M("style-line",$(\'<path d="M1.5 11.5 5.5 7l3 2.5 5-6"/>\'));M("style-area",$(\'<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"/>\'));M("style-baseline",$(\'<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"/>\'));M("style-heikinashi",$(\'<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"/>\'));M("indicators",$(\'<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"/>\'));M("undo",$(\'<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"/>\'));M("redo",$(\'<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"/>\'));M("objects",$(\'<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"/>\'));M("clock",$(\'<circle cx="8" cy="8" r="6.2"/><path d="M8 4.8V8l2.4 1.6"/>\'));M("calendar",$(\'<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"/>\'));M("datawindow",$(\'<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"/>\'));M("camera",$(\'<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"/>\'));M("gear",$(\'<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"/>\'));M("search",$(\'<circle cx="7" cy="7" r="4.5"/><path d="m10.5 10.5 3.5 3.5"/>\'));M("bell",$(\'<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"/>\'));M("market-open",fe(\'<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"/>\'));M("market-pre",fe(\'<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"/>\'));M("market-post",fe(\'<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"/>\'));M("market-closed",fe(\'<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"/>\'));M("market-holiday",fe(\'<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"/>\'));M("chevron-right",$(\'<path d="m6 3.5 4.5 4.5L6 12.5"/>\'));M("chevron-left",$(\'<path d="M10 3.5 5.5 8l4.5 4.5"/>\'));M("chevron-down",$(\'<path d="M3.5 6 8 10.5 12.5 6"/>\'));M("chevron-up",$(\'<path d="M3.5 10 8 5.5 12.5 10"/>\'));M("chevrons-right",$(\'<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"/>\'));M("chevrons-left",$(\'<path d="M12 3.5 7.5 8l4.5 4.5"/><path d="M7.5 3.5 3 8l4.5 4.5"/>\'));M("check",$(\'<path d="m2.8 8.4 3.4 3.4 7-7.6"/>\'));M("close",$(\'<path d="m3.8 3.8 8.4 8.4M12.2 3.8l-8.4 8.4"/>\'));M("eye",$(\'<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"/>\'));M("eye-off",$(\'<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"/>\'));M("lock",$(\'<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"/>\'));M("unlock",$(\'<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"/>\'));M("trash",$(\'<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"/>\'));M("group",$(\'<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"/>\'));M("ungroup",$(\'<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"/>\'));M("clone",$(\'<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"/>\'));M("arrow-up",$(\'<path d="M8 13.2V3M4.2 6.8 8 3l3.8 3.8"/>\'));M("arrow-down",$(\'<path d="M8 2.8V13M4.2 9.2 8 13l3.8-3.8"/>\'));M("move-vertical",$(\'<path d="M8 2.5v11M5 5.5 8 2.5l3 3M5 10.5l3 3 3-3"/>\'));M("move",$(\'<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"/>\'));M("pen",$(\'<path d="m10.8 2.2 3 3-8 8-3.6.6.6-3.6z"/><path d="m9.2 3.8 3 3"/>\'));M("wave",$(\'<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"/>\'));M("folder-plus",$(\'<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"/>\'));M("folder-minus",$(\'<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"/>\'));M("collapse",$(\'<path d="M3 8h10"/>\'));M("expand",$(\'<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"/>\'));M("maximize",$(\'<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"/>\'));M("restore",$(\'<path d="M6.2 2.5v3.7H2.5M9.8 13.5V9.8h3.7M13.5 6.2H9.8V2.5M2.5 9.8h3.7v3.7"/>\'));M("star",$(\'<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"/>\'));M("star-filled",$(\'<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"\'));M("grip",$(\'<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"\'));M("kebab",$(\'<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"\'));M("burger",$(\'<path d="M2.5 4.5h11M2.5 8h11M2.5 11.5h11"/>\'));M("reset",$(\'<rect x="6" y="6" width="4" height="4" rx="0.8"/><path d="M2.2 8a5.8 5.8 0 1 0 1.9-4.3L2.2 5.3"/><path d="M2.2 2.2v3.1h3.1"/>\'));M("pane-collapse",$(\'<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"/>\'));M("pane-expand",$(\'<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"/>\'));M("cursor",fe(\'<path d="M5 3l6 16 2-6 6-2z"/>\',\'fill="currentColor" stroke="none"\'));M("ruler",fe(\'<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"/>\'));M("magnet",fe(\'<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"/>\'));M("eraser",fe(\'<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"/>\'));M("pen-lock",fe(\'<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"/>\'));M("pen-sync",fe(\'<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"/>\'));M("brush",fe(\'<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"/>\'));M("bucket",fe(\'<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"/>\'));M("type",fe(\'<path d="M5 6V4.5h14V6"/><path d="M12 4.5v15"/><path d="M9.5 19.5h5"/>\'));M("bold",fe(\'<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"\'));M("italic",fe(\'<path d="M15 5h-5M14 19H9M14.5 5 10 19"/>\',\'stroke-width="2.2"\'));M("price-delta",fe(\'<path d="M12 4v16"/><path d="M8 8l4-4 4 4"/><path d="M8 16l4 4 4-4"/>\'));M("date-delta",fe(\'<path d="M4 12h16"/><path d="M8 8l-4 4 4 4"/><path d="M16 8l4 4-4 4"/>\'));M("bring-front",fe(\'<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"/>\'));M("send-back",fe(\'<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"/>\'));M("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>\');M("bands",fe(\'<path d="M3 6h18"/><path d="M3 18h18"/><path d="M3 12h18" stroke-dasharray="3 3"/>\'));M("dedekind",fe(\'<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"/>\'));M("sonic",fe(\'<circle cx="15" cy="12" r="4"/><circle cx="12" cy="12" r="2.5"/><path d="M8 5v14"/>\'));M("supersonic",fe(\'<circle cx="16" cy="12" r="3.5"/><path d="M6 12 15 6M6 12 15 18"/>\'));var ei=class{constructor(){ia(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),Bs({instanceId:e,kind:n,title:r,ordinal:s})}};function vn(t){let e=t.data;if(e.length===0)return[];let n=e[e.length-1]?.value;return Array.isArray(n)?n:[]}function pe(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 ti(t){let e=(V(t)??"").toLowerCase();return e==="bt"||e.includes("time")?"bar_time":"bar_index"}function Nl(t){let e=(V(t)??"none").toLowerCase();return e==="b"||e==="both"?"both":e==="l"||e==="left"?"left":e==="r"||e==="right"?"right":"none"}function $s(t){let e=(V(t)??"").toLowerCase();return e.includes("dot")?"dotted":e.includes("dash")?"dashed":"solid"}function kl(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=ee(t);return e?{color:e,invisible:!1}:{invisible:!0}}return{invisible:!0}}function js(t,e){let n=pe(t.x1),r=pe(t.y1),i=pe(t.x2),s=pe(t.y2);if(n===void 0||r===void 0||i===void 0||s===void 0)return null;let a=(V(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}=kl(t.color);return{id:e,paneId:"unrouted",xloc:ti(t.xloc),x1:n,y1:r,x2:i,y2:s,extend:Nl(t.extend),color:c,invisible:u,width:Math.max(1,pe(t.width)??1),style:$s(t.style),arrowLeft:o,arrowRight:l,overlay:t.force_overlay===!0}}function Il(t,e,n){let r=[];for(let i of vn(t)){if(i._deleted===!0)continue;let s=js(i,n.next(e,"line",String(i.id??r.length)));s&&r.push(s)}return r}function Al(t,e,n){let r=[];for(let i of vn(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=js(s,`${o}:a`),c=js(a,`${o}:b`);!l||!c||r.push({id:o,paneId:"unrouted",line1:l,line2:c,color:ee(i.color),overlay:i.force_overlay===!0})}return r}function Tl(t){return t<=0?"auto":t<=9?"tiny":t<=12?"small":t<=17?"normal":t<=28?"large":"huge"}function nb(t){if(typeof t=="number"&&Number.isFinite(t))return Tl(t);let e=(V(t)??"").toLowerCase();return e==="tiny"||e==="small"||e==="normal"||e==="large"||e==="huge"?e:"auto"}function Ws(t){let e=(V(t)??"").toLowerCase();return e==="left"||e==="right"?e:"center"}function Dl(t){let e=(V(t)??"").toLowerCase();return e==="top"||e==="bottom"?e:"center"}function Us(t){return(V(t)??"").toLowerCase().includes("mono")?"monospace":"default"}function Ml(t,e,n){let r=[];for(let i of vn(t)){if(i._deleted===!0)continue;let s=pe(i.left),a=pe(i.top),o=pe(i.right),l=pe(i.bottom);if(s===void 0||a===void 0||o===void 0||l===void 0)continue;let c=(V(i.text_formatting)??"").toLowerCase(),u=V(i.text);r.push({id:n.next(e,"box",String(i.id??r.length)),paneId:"unrouted",xloc:ti(i.xloc),left:s,top:a,right:o,bottom:l,extend:Nl(i.extend),bgColor:ee(i.bgcolor),borderColor:ee(i.border_color),borderWidth:Math.max(0,pe(i.border_width)??1),borderStyle:$s(i.border_style),text:u&&u.length>0?u:void 0,textColor:ee(i.text_color),textSize:nb(i.text_size),hAlign:Ws(i.text_halign),vAlign:Dl(i.text_valign),wrap:(V(i.text_wrap)??"").toLowerCase().includes("auto"),fontFamily:Us(i.text_font_family),bold:c.includes("bold"),italic:c.includes("italic"),overlay:i.force_overlay===!0})}return r}var rb=["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 ib(t){let e=(V(t)??"").toLowerCase().replace(/^style_/,"");return rb.includes(e)?e:"label_down"}function sb(t){let e=(V(t)??"").toLowerCase();return e==="ab"||e.includes("above")?"abovebar":e==="bl"||e.includes("below")?"belowbar":"price"}function Pl(t){if(typeof t=="number"&&Number.isFinite(t))return Tl(t);let e=(V(t)??"").toLowerCase();return e==="auto"||e==="tiny"||e==="small"||e==="large"||e==="huge"?e:"normal"}function Rl(t,e,n){let r=[];for(let i of vn(t)){if(i._deleted===!0)continue;let s=pe(i.x),a=sb(i.yloc),o=pe(i.y);if(s===void 0||a==="price"&&o===void 0)continue;let l=V(i.text),c=V(i.tooltip),{color:u,invisible:h}=kl(i.color);r.push({id:n.next(e,"label",String(i.id??r.length)),paneId:"unrouted",xloc:ti(i.xloc),x:s,y:o??0,yloc:a,text:l&&l.length>0?l:void 0,style:ib(i.style),color:u,noFill:h,textColor:ee(i.textcolor),size:Pl(i.size),textAlign:Ws(i.textalign),tooltip:c&&c.length>0?c:void 0,fontFamily:Us(i.text_font_family),overlay:i.force_overlay===!0})}return r}function Fl(t,e,n){let r=[];for(let i of vn(t)){if(i._deleted===!0)continue;let s=Array.isArray(i.points)?i.points:[],a=ti(i.xloc),o=[];for(let c of s){let u=pe(c.price),h=pe(c.index),p=pe(c.time),d=a==="bar_time"?p:h,f=a==="bar_time"?h:p,m,x;if(d!==void 0)m=d,x=a;else if(f!==void 0)m=f,x=a==="bar_time"?"bar_index":"bar_time";else continue;u!==void 0&&o.push({xloc:x,x:m,price:u})}if(o.length<2)continue;let l=(V(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:ee(i.line_color),fillColor:ee(i.fill_color),lineWidth:Math.max(1,pe(i.line_width)??1),lineStyle:$s(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 ab=["top_left","top_center","top_right","middle_left","middle_center","middle_right","bottom_left","bottom_center","bottom_right"];function ob(t){let e=(V(t)??"").toLowerCase();return ab.includes(e)?e:"top_right"}function lb(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:Pl(t)}function Cl(t){let e=pe(t);return e!==void 0&&e>0?e:void 0}function cb(t){if(!t||typeof t!="object")return null;let e=t,n=V(e.text),r=V(e.tooltip),i=(V(e.text_formatting)??"").toLowerCase();return{text:n&&n.length>0?n:void 0,textColor:ee(e.text_color),bgColor:ee(e.bgcolor),hAlign:Ws(e.text_halign),vAlign:Dl(e.text_valign),textSize:lb(e.text_size),fontFamily:Us(e.text_font_family),tooltip:r&&r.length>0?r:void 0,bold:i.includes("bold"),italic:i.includes("italic"),width:Cl(e.width),height:Cl(e.height),merged:e._merged===!0}}function ub(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=pe(i.startCol??i.start_column??i.startColumn),a=pe(i.startRow??i.start_row),o=pe(i.endCol??i.end_column??i.endColumn),l=pe(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 Bl(t,e,n){let r=[];for(let i of vn(t)){if(i._deleted===!0)continue;let a=(Array.isArray(i.cells)?i.cells:[]).map(l=>(Array.isArray(l)?l:[]).map(c=>cb(c))),o=ub(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:ob(i.position),columns:Math.max(0,Math.round(pe(i.columns)??0)),rows:Math.max(0,Math.round(pe(i.rows)??0)),bgColor:ee(i.bgcolor),frameColor:ee(i.frame_color),frameWidth:Math.max(0,pe(i.frame_width)??0),borderColor:ee(i.border_color),borderWidth:Math.max(0,pe(i.border_width)??0),cells:a,merges:o,overlay:i.force_overlay===!0})}return r}var Ll=Ls;function Ol(t,e){let n=new ei,r=[],i=[],s=[],a=[],o=[],l=[],c=[],u=[],h=[],p=[],d=[],f=[],m=new Map,x=new Set,b=[];for(let v of t.plots){let I=El(v.style),C=v.title??v.key;switch(I){case"skip":break;case"barcolor":{if(!En(v.options.display))break;let T=Hn(v.data.length,se(v.options.show_last));for(let O=T;O<v.data.length;O+=1){let N=v.data[O],j=ee(N.options?.color);j&&f.push({time:N.time,color:j})}break}case"fill":En(v.options.display)&&b.push(v);break;case"hline":{let T=bb(v,C,e,n);T&&o.push(T);break}case"background":En(v.options.display)&&a.push(...wb(v,C,e,n));break;case"drawing_line":l.push(...Il(v,e,n));break;case"drawing_box":c.push(...Ml(v,e,n));break;case"label":u.push(...Rl(v,e,n));break;case"drawing_polyline":h.push(...Fl(v,e,n));break;case"linefill":p.push(...Al(v,e,n));break;case"table":d.push(...Bl(v,e,n));break;case"markers":En(v.options.display)&&u.push(...vb(v,e,n));break;default:{let T=n.next(e,I,C);m.set(v.key,T),v.options.force_overlay===!0&&x.add(v.key),i.push(hb(I,v,T,C));let O=fb(v,C,e,n);O&&o.push(O)}}}for(let v of b){let I=v.plot1?m.get(v.plot1):void 0,C=v.plot2?m.get(v.plot2):void 0;if(!I||!C){r.push(`fill "${v.key}" references unknown plots (${v.plot1??"?"}/${v.plot2??"?"})`);continue}let T=x.has(v.plot1)&&x.has(v.plot2);s.push({id:n.next(e,"fill",v.title??v.key),paneId:"unrouted",fromSeriesId:I,toSeriesId:C,...xb(v),...T?{overlay:!0}:{}})}let w=t.trades?pb(t.trades):[];return{model:{id:e,title:t.meta.title,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 pb(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 hb(t,e,n,r){let i=se(e.options.show_last),s=e.options.force_overlay===!0?{overlay:!0}:{};if(t==="candle"||t==="bar"){let f={id:n,title:r,paneId:"unrouted",kind:t,bars:_b(e,Hn(e.data.length,i)),...s},m=mb(e);return m&&(f.barColors=m),f}let a=t,o=ee(jl(e)),l=!En(e.options.display)||!o,c=se(e.options.linewidth)??1,u=a==="line"||a==="step"||a==="area",h=gb(db(yb(e),i,u),se(e.options.offset)),p={color:o??Ll,width:c,lineStyle:$l(e.options.linestyle)??"solid"},d=se(e.options.histbase);return d!==void 0&&(a==="histogram"||a==="columns"||a==="area")&&(p.base=d),{id:n,title:r,paneId:"unrouted",kind:a,points:h,style:p,visible:!l,...s}}function En(t){let e=V(t);return e===void 0||e.includes("all")||e.includes("pane")}function Hn(t,e){return e===void 0||e<=0?0:Math.max(0,t-Math.floor(e))}function db(t,e,n){let r=Hn(t.length,e);return n&&(r-=1),r<=0?t:t.map((i,s)=>s<r?{...i,value:null}:i)}function fb(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:ee(s.options?.color)??ee(jl(t)),lineStyle:"dotted",width:se(t.options.linewidth),title:e}}return null}function mb(t){let e=!1,n=t.data.map(r=>{let i=r.options??{},s=ee(i.color),a=ee(i.wickcolor),o=ee(i.bordercolor);return!s&&!a&&!o?null:(e=!0,{color:s,wickColor:a,borderColor:o})});return e?n:void 0}function yb(t){let e=t.data.some(n=>Jr(n.options?.color));return t.data.map(n=>{let r=typeof n.value=="number"&&Number.isFinite(n.value)?n.value:null,i=ee(n.options?.color);return i?{time:n.time,value:r,color:i}:e?{time:n.time,value:r,color:Sl}:{time:n.time,value:r}})}function Vl(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 gb(t,e){if(!e)return t;let n=e*Vl(t);return n?t.map(r=>({...r,time:r.time+n})):t}function _b(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 jl(t){for(let e of t.data)if(typeof e.options?.color=="string"&&e.options.color)return e.options.color;return V(t.options.color)}function xb(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=se(o.top_value),c=se(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=>ee(s.options?.color)??null),r=new Set(n.filter(s=>s!==null)),i=n.some(s=>s===null);return r.size===0?{color:ee(t.options.color)}:r.size===1&&!i?{color:[...r][0]}:{colors:n}}function bb(t,e,n,r){if(!En(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:ee(t.options.color),lineStyle:$l(t.options.linestyle)??"dashed",title:e,width:se(t.options.linewidth)}}function $l(t){let e=V(t)?.replace(/^(hline\\.style_|plot\\.linestyle_|linestyle_|style_)/,"");return e==="solid"||e==="dashed"||e==="dotted"?e:void 0}function wb(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=Hn(a.length,se(t.options.show_last));for(;l<a.length;){let c=a[l],u=ee(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&&ee(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 vb(t,e,n){let r=se(t.options.offset),i=r?r*Vl(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?Eb(t):null,l=t.options.force_overlay===!0?{overlay:!0}:{},c=[],u=Hn(t.data.length,se(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,x=m.color!==void 0?m.color:t.options.color;if(x!==void 0&&!Jr(x))continue;let b=V(m.text)??V(t.options.text),w=b&&b.trim().length>0?b:void 0,E=a?f&&d>0?Os:Vs:void 0,v=ee(m.color)??ee(t.options.color)??E??Ll,I=s?V(m.char)??V(t.options.char)??"\\u2605":void 0;c.push({id:n.next(e,"label",`${t.key}#${c.length}`),paneId:"unrouted",xloc:"bar_time",x:p.time+i,y:f?d:0,yloc:Cb(V(m.location)??V(t.options.location)),text:I!==void 0?w!==void 0?`${I}\n${w}`:I:w,style:I!==void 0?"none":Nb(V(m.shape)??V(t.options.shape)),color:v,textColor:ee(m.textcolor)??ee(t.options.textcolor)??(I!==void 0?v:void 0),size:o!==null&&f?Sb(Math.abs(d),o):kb(V(m.size)??V(t.options.size)),textAlign:"center",fontFamily:"default",...l})}return c}function Eb(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:se(t.options.minheight)??5,maxH:se(t.options.maxheight)??100}}function Sb(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 Cb(t){let e=(t??"").toLowerCase();return e==="absolute"?"price":e==="top"?"top":e==="bottom"?"bottom":e.includes("below")?"belowbar":"abovebar"}function Nb(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 kb(t){let e=(t??"").toLowerCase();return e==="tiny"||e==="small"||e==="large"||e==="huge"||e==="normal"?e:"small"}function Ib(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 Ab(t){return t==="int"||t==="float"||t==="price"||t==="time"}var Wl={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 Tb(t){let e=t.trim().toLowerCase().replace(/^color\\./,"");return Wl[e]??t}function Db(t){if(typeof t!="string")return;let e=/^color\\.([a-z]+)$/i.exec(t.trim());return e?Wl[e[1].toLowerCase()]:void 0}function Mb(t){return(t.type==="string"||t.type==null)&&Db(t.defval)!==void 0}function Pb(t,e){if(e==="bool")return!!t;if(Ab(e))return typeof t=="number"?t:Number(t)||0;let n=typeof t=="string"?t:t==null?"":String(t);return e==="color"?Tb(n):n}function Ul(t){return t.map((e,n)=>{let r=Mb(e)?"color":Ib(e.type);return{key:e.varId??e.title??`input${n}`,title:e.title??e.varId??`Input ${n+1}`,type:r,defval:Pb(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 Rb(t){switch(t){case"int":return"int";case"float":return"float";case"bool":return"bool";default:return"string"}}function qs(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 Fb(t){let e=t.replace(/_/g," ");return e.charAt(0).toUpperCase()+e.slice(1)}function ql(t,e){let n=t.getPropsMeta(),r=t.prop;return n.filter(i=>i.mutable&&i.name).map(i=>{let s=i.name,a=Rb(i.type),o=qs(i.defval,a),l=qs(r[s]??i.defval,a),c=e?.[s],u=l!==o?l:c!==void 0?qs(c,a):o;return{key:s,title:Fb(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 zl(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 Kl=!1;function zs(){if(Kl)return;Kl=!0;let t=_n.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:E,...v}=h;d=E,f=Object.keys(v).length>0?[...p,v]:p}else d=c[13],f=p;let m=l(...f),x=h??{},b=p.length>1?p[1]:x.column??0,w=p.length>2?p[2]:x.row??0;return o(p[0],b,w,d),m})})}var Hl=["plotshape","plotchar","plotarrow"],Gl=!1;function Ks(){if(Gl)return;Gl=!0;let t=_n.prototype,e=t.bindContextObject;typeof e=="function"&&(t.bindContextObject=function(n,r,i){if(e.call(this,n,r,i),i!==void 0||!Hl.some(a=>r.includes(a)))return;let s={idx:void 0,n:0,len:0};for(let a of Hl){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 Bb(t,e,n){if(n==="none")return[];if(n==="strategy"&&t.getDeclarationType()!=="strategy")return[];let r=ql(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 Jl(t,e,n,r="all"){let i=Qt.from(t),s=Ul(i.getInputsMeta()),a=Bb(i,n,r),o=/overlay\\s*[:=]\\s*true/.test(t),l=t.match(/(?:indicator|strategy)\\(\\s*["\']([^"\']+)["\']/)?.[1]??"Indicator",c=/chart\\.(left|right)_visible_bar(_time)?\\b/.test(t);return{language:"pine",inputs:s,...a.length>0?{props:a}:{},meta:{title:l,overlay:o},reactsToViewport:c,token:{source:t,instanceId:e}}}function Gs(t,e,n,r={}){let i=JSON.stringify([n,r]);if(t.lastKey!==i||!t.lastInd){let s=new Qt(e,n);zl(s,r),t.lastInd=s,t.lastKey=i}return t.lastInd}async function ec(t){let{ind:e,bars:n,market:r,visibleRange:i,prepared:s,instanceId:a,inputs:o,props:l,fetchSeries:c}=t;zs(),Ks();let u=Ys(n,r.timeframe,r.symbolInfo),h={getMarketData:(m,x,b,w,E)=>nc(m,x,r)?Promise.resolve(u):rc(c,m,x,b,w,E,ri(r,m)),getSymbolInfo:async m=>ri(r,m)},p=new Ut(h,Zs(r),r.timeframe,u.length);await p.ready(),i&&p.setVisibleRange(i.left,i.right);let d=await p.run(e),f=typeof p.usesVisibleRange=="function"?p.usesVisibleRange():!1;return{model:tc(d,a,s,o,l??{},n[0]?.time),alerts:(d.alerts??[]).map(sc),warnings:(d.warnings??[]).map(ac),reactsToViewport:f,ctx:d}}function tc(t,e,n,r,i,s){let{model:a}=Ol(Qr(t),e);return a.inputs=n.inputs,a.inputValues={...Ql(n.inputs),...r},n.props&&(a.props=n.props,a.propValues={...Ql(n.props),...i}),s!=null&&(a.anchorTime=s),a}function Yl(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 Hs=(t,e)=>e.start<=e.end?t>=e.start&&t<e.end:t>=e.start||t<e.end,ni=new Map;function Zl(t,e){let n=`${e}:${Math.floor(t/36e5)}`,r=ni.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}ni.size>1e5&&ni.clear(),ni.set(n,r)}return Number.isNaN(r)?null:((Math.floor(t/6e4)+r)%1440+1440)%1440}function Lb(t){return t==null?null:/^\\d+$/.test(t)?Number(t):/^1?D$/i.test(t)?1440:null}function Ob(t,e,n){let r=Lb(e),i=Yl(n?.session),s=typeof n?.timezone=="string"?n.timezone:null;if(r==null||i==null||s==null||t.length===0)return null;let a=Yl(n?.session_extended),o=i;if(a)for(let l of t){let c=Zl(l.time,s);if(c!=null&&!Hs(c,i)&&Hs(c,a)){o=a;break}}return l=>{let c=Zl(l,s);if(c==null||!Hs(c,o))return null;let u=(o.end-c+1440)%1440||1440;return l+Math.min(r,u)*6e4}}function Ys(t,e,n){let r=Ob(t,e,n);return t.map(i=>{let s={openTime:i.time,open:i.open,high:i.high,low:i.low,close:i.close,volume:i.volume??0},a=r?.(i.time);return a!=null&&(s.closeTime=a),s})}function Zs(t){return t.chartStyle==="heikinashi"?`${t.symbol};heikinashi`:t.symbol}function nc(t,e,n){return(t==null||t===Zs(n))&&(e==null||e===n.timeframe)}async function rc(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 Ys(o,n,a)}function Vb(t,e,n){let r="",i=!1;return{markDirty:()=>{i=!0},getMarketData:async(s,a,o,l,c)=>{let u=e();if(!nc(s,a,u))return rc(n,s,a,o,l,c,ri(u,s));let h=Ys(t(),u.timeframe,u.symbolInfo);if(l==null)return h;let p=h.filter(m=>(m.openTime??0)>=l),d=p[p.length-1],f=d?`${p.length}|${d.openTime}|${d.close}|${d.high}|${d.low}|${d.volume}`:"";return!i&&f===r?[]:(i=!1,r=f,p)},getSymbolInfo:async s=>ri(e(),s)}}function ic(t){let e=t.bars();zs(),Ks();let n=Gs(t.cache,t.token.source,t.inputs,t.props??{}),r=e[0]?.time,i=Math.max(1,e.length),s=Vb(t.bars,t.market,t.fetchSeries),a=new Ut(s,Zs(t.market()),t.market().timeframe,i);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;try{t.onModel(tc(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?.(sc(u))),o.on("warning",u=>t.onWarning?.(ac(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 ri(t,e){let n=e&&e.split(";")[0];return n&&n!==t.symbol?Xl({symbol:n,timeframe:t.timeframe}):Xl(t)}function Xl(t){if(t.symbolInfo)return 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 Ql(t){let e={};for(let n of t)e[n.key]=n.defval;return e}function sc(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 ac(t){return{message:String(t.message??""),method:t.method,bar:Number(t.bar??0)}}var Qe=t=>se(t)??0;function oc(t){if(t==null||typeof t!="object")return;let e=t;return{position:Qe(e.position_size),avgPrice:Qe(e.position_avg_price),equity:Qe(e.equity),openPnl:Qe(e.openprofit),netPnl:Qe(e.netprofit),grossProfit:Qe(e.grossprofit),grossLoss:Qe(e.grossloss),wins:Qe(e.wintrades),losses:Qe(e.losstrades),even:Qe(e.eventrades),maxDrawdown:Qe(e.max_drawdown),maxRunup:Qe(e.max_runup),initialCapital:Qe(e.initial_capital)}}function lc(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=se(i.entry_price),a=se(i.entry_time),o=se(i.size);if(s===void 0||a===void 0||o===void 0||o===0)continue;let l=se(i.exit_price),c=se(i.exit_time);n.push({id:V(i.id)??`trade_${n.length}`,side:o>0?"long":"short",qty:Math.abs(o),entry:{id:V(i.entry_id)??"",time:a,price:s,...V(i.entry_comment)!==void 0?{comment:V(i.entry_comment)}:{}},...l!==void 0&&c!==void 0?{exit:{id:V(i.exit_id)??"",time:c,price:l,...V(i.exit_comment)!==void 0?{comment:V(i.exit_comment)}:{}}}:{},open:i.status!=="closed"})}return n}function cc(t){try{return structuredClone(t)}catch{return}}function jb(t){let e=Array.isArray(t)?t:t!=null&&typeof t=="object"&&Array.isArray(t.data)?t.data:null;return cc(e?e[e.length-1]:t)}function $b(t){return t.replace(/^glb\\d+_/,"")}function Xs(t,e){if(t)for(let[n,r]of Object.entries(t)){if(n.startsWith("_"))continue;let i=jb(r);i!==void 0&&(e[$b(n)]=i)}}function uc(t,e,n){let r=t??{},i=r.fullContext??r,s=p=>!n||n.includes(p),a=s("meta")||s("plots")?Qr(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:cc(d.value)??null})));let l={};s("variables")&&(Xs(i.const,l),Xs(i.var,l),Xs(i.let,l));let c=s("strategy")?oc(i.strategy):void 0,u=s("trades")&&i.strategy?lc(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 pc=self,De=t=>pc.postMessage(t),zt=new Map,Js=new Map,Wb=0,hc=(t,e,n)=>new Promise((r,i)=>{let s=++Wb;Js.set(s,{resolve:r,reject:i}),De({kind:"fetchSeries",reqId:s,symbol:t,timeframe:e,range:n})});function ii(t){t.chain=t.chain.then(()=>qb(t))}function Ub(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 Qs(t){t.stream?.stop(),t.stream=null,!(t.stopped||t.bars.length===0)&&(t.stream=ic({token:t.prepared.token,cache:t.cache,prepared:t.prepared,inputs:t.inputs,props:t.props,bars:()=>t.bars,market:()=>t.market,fetchSeries:hc,visibleRange:t.visibleRange,onModel:e=>{t.stopped||De({kind:"model",sessionId:t.id,model:e})},onAlert:e=>De({kind:"alert",sessionId:t.id,alert:e}),onWarning:e=>De({kind:"warning",sessionId:t.id,warning:e}),onError:e=>De({kind:"error",sessionId:t.id,message:e.message})}))}async function qb(t){if(!t.stopped)try{let e=t.prepared.token,n=await ec({ind:Gs(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:hc});if(t.stopped)return;De({kind:"reactsToViewport",sessionId:t.id,value:n.reactsToViewport});for(let r of n.alerts)De({kind:"alert",sessionId:t.id,alert:r});for(let r of n.warnings)De({kind:"warning",sessionId:t.id,warning:r});t.lastCtx=n.ctx,De({kind:"model",sessionId:t.id,model:n.model}),De({kind:"done",sessionId:t.id})}catch(e){De({kind:"error",sessionId:t.id,message:e instanceof Error?e.message:String(e)})}}pc.addEventListener("message",t=>{let e=t.data;switch(e.kind){case"prepare":try{De({kind:"prepared",reqId:e.reqId,prepared:Jl(e.source,e.instanceId,e.defaultProps,e.propsVisibility)})}catch(n){De({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};if(zt.set(n.id,n),n.mode==="live"){n.deferred||Qs(n);return}n.deferred?De({kind:"done",sessionId:n.id}):ii(n);return}case"update":{let n=zt.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||Qs(n);return}n.deferred?De({kind:"done",sessionId:n.id}):ii(n);return}case"setVisibleRange":{let n=zt.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?De({kind:"done",sessionId:n.id}):ii(n);return}case"notifyBars":{let n=zt.get(e.sessionId);if(!n||n.mode==="live")return;n.bars=e.bars,n.deferred=!1,ii(n);return}case"bars":{let n=zt.get(e.sessionId);if(!n||n.mode!=="live")return;if(e.restart){n.bars=e.bars,n.deferred=!1,Qs(n);return}for(let r of e.bars)Ub(n,r);return}case"getContext":{let n=zt.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";De({kind:"contextResult",reqId:e.reqId,snapshot:r==null?null:uc(r,i,e.select)});return}case"stop":{let n=zt.get(e.sessionId);n&&(n.stopped=!0,n.stream?.stop()),zt.delete(e.sessionId);return}case"fetchSeriesResult":{let n=Js.get(e.reqId);if(!n)return;Js.delete(e.reqId),e.error?n.reject(new Error(e.error)):n.resolve(e.bars??[]);return}}});})();\n';
1669
+ var worker_default = '"use strict";(()=>{var yc=Object.defineProperty;var gc=(t,e,n)=>e in t?yc(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var ia=(t,e,n)=>gc(t,typeof e!="symbol"?e+"":e,n);function _c(t){return e=>new q(e.array.map(n=>Math.abs(n)),e.type,t)}function xc(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)}}function bc(t){return(e,n)=>{let r=e.array,i=0,s=r.length-1;for(;i<=s;){let a=Math.floor((i+s)/2),o=r[a];if(o===n)return a;o<n?i=a+1:s=a-1}return-1}}function wc(t){return(e,n)=>{let r=e.array,i=0,s=r.length;for(;i<s;){let a=Math.floor((i+s)/2);r[a]<n?i=a+1:s=a}return i<r.length&&r[i]===n?i:i-1}}function vc(t){return(e,n)=>{let r=e.array,i=0,s=r.length;for(;i<s;){let a=Math.floor((i+s)/2);r[a]<=n?i=a+1:s=a}return i>0&&r[i-1]===n?i-1:i}}function Ec(t){return e=>{e.array.length=0}}function Sc(t){return(e,n)=>(e.array.push(...n.array),e)}function Cc(t){return e=>new q([...e.array],e.type,t)}function Nc(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]),x=Number(s[f]);!isNaN(m)&&m!==null&&m!==void 0&&!isNaN(x)&&x!==null&&x!==void 0&&(a+=m,o+=x,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]),x=Number(s[f]);p+=(m-u)*(x-h)}let d=r?l:l-1;return d<=0?NaN:t.precision(p/d)}}function kc(t){return e=>e.array.every(n=>!isNaN(n)&&n)}function Ic(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 it(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 qn(t,e){if(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 Ac(t){return(e,n,r=0,i)=>{let s=e.array.length,a=i!==void 0?Math.min(i,s):s;for(let o=r;o<a;o++){if(!qn(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.`);e.array[o]=typeof n=="number"?t.precision(n):n}}}function Tc(t){return e=>e.array.length>0?e.array[0]:t.NA}function Dc(t){return(e,n)=>(n<0&&(n=e.array.length+n),n<0||n>=e.array.length?(t.warn(`Index ${n} is out of bounds, array size is ${e.array.length}.`,"array.get"),NaN):e.array[n])}function Mc(t){return(e,n)=>e.array.includes(n)}function Pc(t){return(e,n)=>typeof n=="number"&&n!==n?e.array.findIndex(r=>typeof r=="number"&&r!==r):e.array.indexOf(n)}function Rc(t){return(e,n,r)=>{if(!qn(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.`);if(n<0&&(n=e.array.length+n),n<0||n>e.array.length){t.warn(`Index ${n} is out of bounds, array size is ${e.array.length}.`,"array.insert");return}e.array.splice(n,0,r)}}function Fc(t){return(e,n=",")=>e.array.join(n)}function Bc(t){return e=>e.array.length>0?e.array[e.array.length-1]:t.NA}function Lc(t){return(e,n)=>e.array.lastIndexOf(n)}function Oc(t){return(e,n=0)=>{let r=e.array;if(r.length===0)return t.NA;if(n===0){let i=r[0];for(let s=1;s<r.length;s++)r[s]>i&&(i=r[s]);return i??t.NA}return[...r].sort((i,s)=>s-i)[n]??t.NA}}function Vc(t){return e=>{let n=e.array;if(n.length===0)return NaN;let r=new Array(n.length);for(let s=0;s<n.length;s++)r[s]=n[s];r.sort((s,a)=>s-a);let i=Math.floor(r.length/2);return r.length%2!==0?r[i]:(r[i-1]+r[i])/2}}function jc(t){return(e,n=0)=>{let r=e.array;if(r.length===0)return t.NA;if(n===0){let i=r[0];for(let s=1;s<r.length;s++)r[s]<i&&(i=r[s]);return i??t.NA}return[...r].sort((i,s)=>i-s)[n]??t.NA}}function $c(t){return e=>{if(e.array.length===0)return NaN;let n=new Map,r=0;for(let s of e.array){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[0]}}function Wc(t){return(e,n)=>{let r=e.array,i=r.length;if(i===0)return NaN;let s=new Array(i);for(let c=0;c<i;c++){let u=Number(r[c]);if(isNaN(u)||u===null||u===void 0)return NaN;s[c]=u}s.sort((c,u)=>c-u),n<0&&(n=0),n>100&&(n=100);let a=n/100*i-.5;if(a<=0)return t.precision(s[0]);if(a>=i-1)return t.precision(s[i-1]);let o=Math.floor(a),l=a-o;return t.precision(s[o]*(1-l)+s[o+1]*l)}}function Uc(t){return(e,n)=>{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),n<0&&(n=0),n>100&&(n=100);let a=Math.ceil(n/100*i);return a<=0?s[0]:a>s.length?NaN:s[a-1]}}function qc(t){return(e,n)=>{if(e.array.length===0)return NaN;let r=Math.floor(n);if(r<0||r>=e.array.length)return NaN;let i=Number(e.array[r]);if(isNaN(i)||i===null||i===void 0)return NaN;let s=0;for(let o of e.array){let l=Number(o);!isNaN(l)&&l!==null&&l!==void 0&&l<i&&s++}let a=e.array.length-1;return a<=0?NaN:s/a*100}}function zc(t){return e=>e.array.pop()}function Kc(t){return(e,n)=>{if(!qn(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 Hc(t){return e=>t.precision(t.pine.array.max(e)-t.pine.array.min(e))}function Gc(t){return(e,n)=>(n<0&&(n=e.array.length+n),n<0||n>=e.array.length?(t.warn(`Index ${n} is out of bounds, array size is ${e.array.length}.`,"array.remove"),NaN):e.array.splice(n,1)[0])}function Yc(t){return e=>{e.array.reverse()}}function Zc(t){return(e,n,r)=>{if(!qn(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.`);if(n<0&&(n=e.array.length+n),n<0||n>=e.array.length){t.warn(`Index ${n} is out of bounds, array size is ${e.array.length}.`,"array.set");return}e.array[n]=typeof r=="number"?t.precision(r):r}}function Xc(t){return e=>e.array.shift()}function Qc(t){return e=>e.array.length}function Jc(t){return(e,n,r)=>{let i=r!==void 0?r:void 0;return new q(e.array.slice(n,i),e.type,t)}}function eu(t){return e=>e.array.some(n=>!isNaN(n)&&n)}var yn=(t=>(t[t.ascending=1]="ascending",t[t.descending=0]="descending",t))(yn||{}),$a=(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))($a||{}),Wa=(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))(Wa||{}),Ua=(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))(Ua||{}),qa=(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))(qa||{}),za=(t=>(t.abovebar="AboveBar",t.belowbar="BelowBar",t.absolute="Absolute",t.bottom="Bottom",t.top="Top",t))(za||{}),Ka=(t=>(t.auto="auto",t.tiny="tiny",t.small="small",t.normal="normal",t.large="large",t.huge="huge",t))(Ka||{}),Ha=(t=>(t.inherit="inherit",t.mintick="mintick",t.percent="percent",t.price="price",t.volume="volume",t))(Ha||{}),tu=(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))(tu||{}),Ga=(t=>(t.gaps_on="gaps_on",t.gaps_off="gaps_off",t.lookahead_on="lookahead_on",t.lookahead_off="lookahead_off",t))(Ga||{}),Ya=(t=>(t.bar_index="bi",t.bar_time="bt",t))(Ya||{}),Za=(t=>(t.price="pr",t.abovebar="ab",t.belowbar="bl",t))(Za||{}),Xa=(t=>(t.left="l",t.right="r",t.both="b",t.none="n",t))(Xa||{}),Qa=(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))(Qa||{}),Ja=(t=>(t.family_default="default",t.family_monospace="monospace",t))(Ja||{}),eo=(t=>(t.none="none",t.splits="splits",t.dividends="dividends",t))(eo||{}),to=(t=>(t.inherit="inherit",t.off="off",t.on="on",t))(to||{}),no=(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))(no||{}),ro=(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))(ro||{}),io=(t=>(t.denominator="splits_denominator",t.numerator="splits_numerator",t))(io||{}),so=(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))(so||{}),ao=(t=>(t.left="left",t.none="none",t.right="right",t))(ao||{}),oo=(t=>(t.inherit="inherit",t.off="off",t.on="on",t))(oo||{}),nu={order:yn,currency:$a,dayofweek:Wa,display:Ua,shape:qa,location:za,size:Ka,format:Ha,barmerge:Ga,xloc:Ya,yloc:Za,extend:Xa,text:Qa,font:Ja,adjustment:eo,backadjustment:to,earnings:no,dividends:ro,splits:io,position:so,scale:ao,settlement_as_close:oo};function ru(t){return(e,n=yn.ascending)=>{e.array.sort((r,i)=>{let s=isNaN(r)?1/0:r,a=isNaN(i)?1/0:i;return n===yn.ascending?s-a:a-s})}}function iu(t){return(e,n=yn.ascending)=>{let r=e.array.map((i,s)=>s);return r.sort((i,s)=>{let a=isNaN(e.array[i])?1/0:e.array[i],o=isNaN(e.array[s])?1/0:e.array[s];return n===yn.ascending?a-o:o-a}),new q(r,z.int,t)}}function su(t){return e=>{let n=t.array.avg(e),r=t.array.stdev(e);return isNaN(r)?new q(e.array.map(()=>NaN),z.int,t):r===0?new q(e.array.map(()=>1),z.int,t):new q(e.array.map(i=>(i-n)/r),z.int,t)}}function au(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?0:t.precision(Math.sqrt(c)))}}function ou(t){return e=>t.precision(e.array.reduce((n,r)=>{let i=Number(r);return isNaN(i)?n:n+i},0))}function lu(t){return(e,n)=>{if(!qn(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 cu(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 uu=Object.defineProperty,pu=(t,e,n)=>e in t?uu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Y=(t,e,n)=>pu(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,Y(this,"_abs"),Y(this,"_avg"),Y(this,"_binary_search"),Y(this,"_binary_search_leftmost"),Y(this,"_binary_search_rightmost"),Y(this,"_clear"),Y(this,"_concat"),Y(this,"_copy"),Y(this,"_covariance"),Y(this,"_every"),Y(this,"_fill"),Y(this,"_first"),Y(this,"_get"),Y(this,"_includes"),Y(this,"_indexof"),Y(this,"_insert"),Y(this,"_join"),Y(this,"_last"),Y(this,"_lastindexof"),Y(this,"_max"),Y(this,"_median"),Y(this,"_min"),Y(this,"_mode"),Y(this,"_percentile_linear_interpolation"),Y(this,"_percentile_nearest_rank"),Y(this,"_percentrank"),Y(this,"_pop"),Y(this,"_push"),Y(this,"_range"),Y(this,"_remove"),Y(this,"_reverse"),Y(this,"_set"),Y(this,"_shift"),Y(this,"_size"),Y(this,"_slice"),Y(this,"_some"),Y(this,"_sort"),Y(this,"_sort_indices"),Y(this,"_standardize"),Y(this,"_stdev"),Y(this,"_sum"),Y(this,"_unshift"),Y(this,"_variance"),this._abs=_c(this.context),this._avg=xc(this.context),this._binary_search=bc(this.context),this._binary_search_leftmost=wc(this.context),this._binary_search_rightmost=vc(this.context),this._clear=Ec(this.context),this._concat=Sc(this.context),this._copy=Cc(this.context),this._covariance=Nc(this.context),this._every=kc(this.context),this._fill=Ac(this.context),this._first=Tc(this.context),this._get=Dc(this.context),this._includes=Mc(this.context),this._indexof=Pc(this.context),this._insert=Rc(this.context),this._join=Fc(this.context),this._last=Bc(this.context),this._lastindexof=Lc(this.context),this._max=Oc(this.context),this._median=Vc(this.context),this._min=jc(this.context),this._mode=$c(this.context),this._percentile_linear_interpolation=Wc(this.context),this._percentile_nearest_rank=Uc(this.context),this._percentrank=qc(this.context),this._pop=zc(this.context),this._push=Kc(this.context),this._range=Hc(this.context),this._remove=Gc(this.context),this._reverse=Yc(this.context),this._set=Zc(this.context),this._shift=Xc(this.context),this._size=Qc(this.context),this._slice=Jc(this.context),this._some=eu(this.context),this._sort=ru(this.context),this._sort_indices=iu(this.context),this._standardize=su(this.context),this._stdev=au(this.context),this._sum=ou(this.context),this._unshift=lu(this.context),this._variance=cu(this.context)}toString(){return"["+this.array.toString().replace(/,/g,", ")+"]"}[Symbol.iterator](){return this.array[Symbol.iterator]()}abs(...e){return this._abs(this,...e)}avg(...e){return this._avg(this,...e)}binary_search(...e){return this._binary_search(this,...e)}binary_search_leftmost(...e){return this._binary_search_leftmost(this,...e)}binary_search_rightmost(...e){return this._binary_search_rightmost(this,...e)}clear(...e){return this._clear(this,...e)}concat(...e){return this._concat(this,...e)}copy(...e){return this._copy(this,...e)}covariance(...e){return this._covariance(this,...e)}every(...e){return this._every(this,...e)}fill(...e){return this._fill(this,...e)}first(...e){return this._first(this,...e)}get(...e){return this._get(this,...e)}includes(...e){return this._includes(this,...e)}indexof(...e){return this._indexof(this,...e)}insert(...e){return this._insert(this,...e)}join(...e){return this._join(this,...e)}last(...e){return this._last(this,...e)}lastindexof(...e){return this._lastindexof(this,...e)}max(...e){return this._max(this,...e)}median(...e){return this._median(this,...e)}min(...e){return this._min(this,...e)}mode(...e){return this._mode(this,...e)}percentile_linear_interpolation(...e){return this._percentile_linear_interpolation(this,...e)}percentile_nearest_rank(...e){return this._percentile_nearest_rank(this,...e)}percentrank(...e){return this._percentrank(this,...e)}pop(...e){return this._pop(this,...e)}push(...e){return this._push(this,...e)}range(...e){return this._range(this,...e)}remove(...e){return this._remove(this,...e)}reverse(...e){return this._reverse(this,...e)}set(...e){return this._set(this,...e)}shift(...e){return this._shift(this,...e)}size(...e){return this._size(this,...e)}slice(...e){return this._slice(this,...e)}some(...e){return this._some(this,...e)}sort(...e){return this._sort(this,...e)}sort_indices(...e){return this._sort_indices(this,...e)}standardize(...e){return this._standardize(this,...e)}stdev(...e){return this._stdev(this,...e)}sum(...e){return this._sum(this,...e)}unshift(...e){return this._unshift(this,...e)}variance(...e){return this._variance(this,...e)}};function hu(t){return(...e)=>new q([...e],Ic(e),t)}function du(t){return(e,n)=>{let r=typeof e=="number"&&e>0&&!isNaN(e)?Math.floor(e):0;if(n===void 0){let i=r?Array(r).fill(0):[];return new q(i,z.any,t)}return new q(Array(r).fill(t.precision(n||0)),it(n||0),t)}}function fu(t){return(e=0,n=!1)=>{let r=typeof e=="number"&&e>0&&!isNaN(e)?Math.floor(e):0;return new q(Array(r).fill(n),z.bool,t)}}function mu(t){return(e=0,n=null)=>{let r=typeof e=="number"&&e>0&&!isNaN(e)?Math.floor(e):0;return new q(Array(r).fill(n),z.box,t)}}function yu(t){return(e=0,n=null)=>{let r=typeof e=="number"&&e>0&&!isNaN(e)?Math.floor(e):0;return new q(Array(r).fill(n),z.color,t)}}function gu(t){return(e=0,n=NaN)=>{let r=typeof e=="number"&&e>0&&!isNaN(e)?Math.floor(e):0;return new q(Array(r).fill(t.precision(n)),z.float,t)}}function _u(t){return(e=0,n=0)=>{let r=typeof e=="number"&&e>0&&!isNaN(e)?Math.floor(e):0;return new q(Array(r).fill(t.precision(n)),z.int,t)}}function xu(t){return(e=0,n=null)=>{let r=typeof e=="number"&&e>0&&!isNaN(e)?Math.floor(e):0;return new q(Array(r).fill(n),z.label,t)}}function bu(t){return(e=0,n=null)=>{let r=typeof e=="number"&&e>0&&!isNaN(e)?Math.floor(e):0;return new q(Array(r).fill(n),z.line,t)}}function wu(t){return(e=0,n=null)=>{let r=typeof e=="number"&&e>0&&!isNaN(e)?Math.floor(e):0;return new q(Array(r).fill(n),z.linefill,t)}}function vu(t){return(e=0,n="")=>{let r=typeof e=="number"&&e>0&&!isNaN(e)?Math.floor(e):0;return new q(Array(r).fill(n),z.string,t)}}function Eu(t){return(e=0,n=null)=>{let r=typeof e=="number"&&e>0&&!isNaN(e)?Math.floor(e):0;return new q(Array(r).fill(n),z.table,t)}}var y=class t{constructor(e,n=0){this.data=e,this.offset=n}get(e){let n=this.offset+e;Number.isInteger(n)||(n=Math.trunc(n));let r=this.data.length-1-n;return r<0||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){return e instanceof t?e:Array.isArray(e)?new t(e):e!=null&&typeof e=="object"&&"__value"in e&&e.__value instanceof t?e.__value:new t([e])}};function Su(t){return(e,n=0)=>y.from(e).get(n)}var _i=class{constructor(e){this.context=e,this.abs=(n,...r)=>n.abs(...r),this.avg=(n,...r)=>n.avg(...r),this.binary_search=(n,...r)=>n.binary_search(...r),this.binary_search_leftmost=(n,...r)=>n.binary_search_leftmost(...r),this.binary_search_rightmost=(n,...r)=>n.binary_search_rightmost(...r),this.clear=(n,...r)=>n.clear(...r),this.concat=(n,...r)=>n.concat(...r),this.copy=(n,...r)=>n.copy(...r),this.covariance=(n,...r)=>n.covariance(...r),this.every=(n,...r)=>n.every(...r),this.fill=(n,...r)=>n.fill(...r),this.first=(n,...r)=>n.first(...r),this.from=hu(e),this.get=(n,...r)=>n.get(...r),this.includes=(n,...r)=>n.includes(...r),this.indexof=(n,...r)=>n.indexof(...r),this.insert=(n,...r)=>n.insert(...r),this.join=(n,...r)=>n.join(...r),this.last=(n,...r)=>n.last(...r),this.lastindexof=(n,...r)=>n.lastindexof(...r),this.max=(n,...r)=>n.max(...r),this.median=(n,...r)=>n.median(...r),this.min=(n,...r)=>n.min(...r),this.mode=(n,...r)=>n.mode(...r),this.new=du(e),this.new_bool=fu(e),this.new_box=mu(e),this.new_color=yu(e),this.new_float=gu(e),this.new_int=_u(e),this.new_label=xu(e),this.new_line=bu(e),this.new_linefill=wu(e),this.new_string=vu(e),this.new_table=Eu(e),this.param=Su(),this.percentile_linear_interpolation=(n,...r)=>n.percentile_linear_interpolation(...r),this.percentile_nearest_rank=(n,...r)=>n.percentile_nearest_rank(...r),this.percentrank=(n,...r)=>n.percentrank(...r),this.pop=(n,...r)=>n.pop(...r),this.push=(n,...r)=>n.push(...r),this.range=(n,...r)=>n.range(...r),this.remove=(n,...r)=>n.remove(...r),this.reverse=(n,...r)=>n.reverse(...r),this.set=(n,...r)=>n.set(...r),this.shift=(n,...r)=>n.shift(...r),this.size=(n,...r)=>n.size(...r),this.slice=(n,...r)=>n.slice(...r),this.some=(n,...r)=>n.some(...r),this.sort=(n,...r)=>n.sort(...r),this.sort_indices=(n,...r)=>n.sort_indices(...r),this.standardize=(n,...r)=>n.standardize(...r),this.stdev=(n,...r)=>n.stdev(...r),this.sum=(n,...r)=>n.sum(...r),this.unshift=(n,...r)=>n.unshift(...r),this.variance=(n,...r)=>n.variance(...r)}};function Cu(t){return e=>{e.map.clear()}}function Nu(t){return(e,n)=>e.map.has(n)}function ku(t){return e=>{let n=new hr(t);return n.map=new Map(e.map),n}}function Iu(t){return(e,n)=>{let r=e.map.get(n);return r===void 0?NaN:r}}function Au(t){return e=>{let n=Array.from(e.map.keys()),r=it(n[0]);return new q(n,r,t)}}function Tu(t){return(e,n,r)=>{let i=e.map.get(n);return e.map.set(n,r),i===void 0?NaN:i}}function Du(t){return(e,n)=>{for(let[r,i]of n.map)e.map.set(r,i)}}function Mu(t){return(e,n)=>{let r=e.map.get(n);return e.map.delete(n)?r:NaN}}function Pu(t){return e=>e.map.size}function Ru(t){return e=>{let n=Array.from(e.map.values()),r=it(n[0]);return new q(n,r,t)}}var Fu=Object.defineProperty,Bu=(t,e,n)=>e in t?Fu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ot=(t,e,n)=>Bu(t,typeof e!="symbol"?e+"":e,n),hr=class{constructor(e){this.context=e,ot(this,"map"),ot(this,"_clear"),ot(this,"_contains"),ot(this,"_copy"),ot(this,"_get"),ot(this,"_keys"),ot(this,"_put"),ot(this,"_put_all"),ot(this,"_remove"),ot(this,"_size"),ot(this,"_values"),this.map=new Map,this._clear=Cu(this.context),this._contains=Nu(this.context),this._copy=ku(this.context),this._get=Iu(this.context),this._keys=Au(this.context),this._put=Tu(this.context),this._put_all=Du(this.context),this._remove=Mu(this.context),this._size=Pu(this.context),this._values=Ru(this.context)}toString(){return`PineMapObject(${this.map.size})`}clear(...e){return this._clear(this,...e)}contains(...e){return this._contains(this,...e)}copy(...e){return this._copy(this,...e)}get(...e){return this._get(this,...e)}keys(...e){return this._keys(this,...e)}put(...e){return this._put(this,...e)}put_all(...e){return this._put_all(this,...e)}remove(...e){return this._remove(this,...e)}size(...e){return this._size(this,...e)}values(...e){return this._values(this,...e)}};function Lu(t){return()=>new hr(t)}function Ou(t){return(e,n=0)=>y.from(e).get(n)}var xi=class{constructor(e){this.context=e,this.clear=(n,...r)=>n.clear(...r),this.contains=(n,...r)=>n.contains(...r),this.copy=(n,...r)=>n.copy(...r),this.get=(n,...r)=>n.get(...r),this.keys=(n,...r)=>n.keys(...r),this.new=Lu(e),this.param=Ou(),this.put=(n,...r)=>n.put(...r),this.put_all=(n,...r)=>n.put_all(...r),this.remove=(n,...r)=>n.remove(...r),this.size=(n,...r)=>n.size(...r),this.values=(n,...r)=>n.values(...r)}};function Vu(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 y&&(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 y&&(c=c.get(0)),e.matrix[l].splice(o,0,c)}}}function ju(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 y){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 y&&(u=u.get(0)),l.push(u)}else l.push(NaN);e.matrix.splice(o,0,l)}}function $u(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 Wu(t){return(e,n)=>{let r=e.matrix.length,i=r>0?e.matrix[0].length:0;if(n<0||n>=i){t.warn(`Column index ${n} is out of bounds, matrix has ${i} columns.`,"matrix.col");let o=r>0?it(e.matrix[0][0]):"float";return new q([],o,t)}let s=[];for(let o=0;o<r;o++)s.push(e.matrix[o][n]);let a=it(s[0]);return new q(s,a,t)}}function Uu(t){return e=>e.matrix.length===0?0:e.matrix[0].length}function qu(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 zu(t){return e=>{let n=e.matrix.length,r=n>0?e.matrix[0].length:0,i=new ne(n,r,NaN,t);return i.matrix=e.matrix.map(s=>[...s]),i}}function Ku(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 Hu(t){return e=>{let n=e.matrix.length,r=n>0?e.matrix[0].length:0;return n!==r?NaN:Ku(e.matrix)}}function Gu(t){return(e,n)=>{let r=e.matrix.length;if(r===0)return new ne(0,0,NaN,t);let i=e.matrix[0].length,s=new ne(r,i,NaN,t);if(n instanceof ne)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 Yu(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 Zu(t){return e=>{let n=e.matrix.length,r=n>0?e.matrix[0].length:0;if(n!==r){let a=it(e.matrix[0][0]);return new q([],a,t)}let i=Yu(e.matrix),s=it(i[0]);return new q(i,s,t)}}function Xu(t){return e=>{let n=e.matrix.length,r=n>0?e.matrix[0].length:0;if(n!==r)return new ne(0,0,NaN,t);let i=new ne(n,r,0,t);for(let s=0;s<n;s++)i.matrix[s][s]=1;return i}}function Qu(t){return e=>{let n=e.matrix.length;return n===0?0:n*e.matrix[0].length}}function Ju(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 ep(t){return(e,n,r)=>{let i=e.matrix.length,s=i>0?e.matrix[0].length:0;if(n<0||n>=i)return t.warn(`Row index ${n} is out of bounds, matrix has ${i} rows.`,"matrix.get"),NaN;if(r<0||r>=s)return t.warn(`Column index ${r} is out of bounds, matrix has ${s} columns.`,"matrix.get"),NaN;let a=e.matrix[n][r];return a===void 0?NaN:a}}function ar(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 tp(t){return e=>{let n=e.matrix.length,r=n>0?e.matrix[0].length:0;if(n!==r)return new ne(n,r,NaN,t);let i=ar(e.matrix),s=new ne(n,r,NaN,t);return s.matrix=i,s}}function np(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 rp(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 ip(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 sp(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 ap(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 op(t){return e=>{let n=e.matrix.length;if(n===0)return!1;let r=e.matrix[0].length;return n===r}}function lp(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 cp(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 up(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 pp(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 hp(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 ne(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 dp(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 fp(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 mp(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 yp(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 gp(t){return(e,n)=>{let r=e.matrix.length,i=r>0?e.matrix[0].length:0;if(n instanceof ne){let s=n.matrix.length,a=s>0?n.matrix[0].length:0;if(i!==s)return new ne(0,0,NaN,t);let o=new ne(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 ne(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 _p(t){return e=>{let n=e.matrix.length;if(n===0)return new ne(0,0,NaN,t);let r=e.matrix[0].length;if(n===r){let u=ar(e.matrix),h=new ne(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 x=0;x<p;x++){m[x]=new Array(f).fill(0);for(let b=0;b<d;b++){let w=u[x][b];if(w!==0)for(let E=0;E<f;E++)m[x][E]+=w*h[b][E]}}return m},a=e.matrix,o=i(a),l;if(n>r){let u=s(o,a),h=ar(u);l=s(h,o)}else{let u=s(a,o),h=ar(u);l=s(o,h)}let c=new ne(r,n,NaN,t);return c.matrix=l,c}}function xp(t){return(e,n)=>{let r=e.matrix.length,i=r>0?e.matrix[0].length:0;if(r!==i)return new ne(0,0,NaN,t);let s=new ne(r,i,0,t);for(let l=0;l<r;l++)s.matrix[l][l]=1;let a=new ne(r,i,NaN,t);for(let l=0;l<r;l++)a.matrix[l]=[...e.matrix[l]];let o=Math.floor(n);if(o<0)return new ne(r,i,NaN,t);for(;o>0;){if(o%2===1){let c=new ne(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 ne(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 bp(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 wp(t){return(e,n)=>{let r=e.matrix.length;if(r===0){let a=it(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=it(i[0]);return new q(i,s,t)}}function vp(t){return(e,n)=>{let r=e.matrix.splice(n,1),i=it(r[0][0]);return new q(r[0]||[],i,t)}}function Ep(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 Sp(t){return e=>{e.matrix.reverse();for(let n of e.matrix)n.reverse()}}function Cp(t){return(e,n)=>{let r=e.matrix.length;if(n<0||n>=r){t.warn(`Row index ${n} is out of bounds, matrix has ${r} rows.`,"matrix.row");let s=r>0?it(e.matrix[0][0]):"float";return new q([],s,t)}let i=it(e.matrix[n][0]);return new q([...e.matrix[n]],i,t)}}function Np(t){return e=>e.matrix.length}function kp(t){return(e,n,r,i)=>{let s=e.matrix.length,a=s>0?e.matrix[0].length:0;if(n<0||n>=s){t.warn(`Row index ${n} is out of bounds, matrix has ${s} rows.`,"matrix.set");return}if(r<0||r>=a){t.warn(`Column index ${r} is out of bounds, matrix has ${a} columns.`,"matrix.set");return}e.matrix[n][r]=i}}function Ip(t){return(e,n=0,r="asc")=>{e.matrix.length!==0&&e.matrix.sort((i,s)=>{let a=i[n],o=s[n];return a<o?r==="asc"?-1:1:a>o?r==="asc"?1:-1:0})}}function Ap(t){return(e,n,r,i,s)=>{let a=r-n,o=s-i,l=new ne(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 Tp(t){return(e,n)=>{let r=e.matrix.length;if(r===0)return new ne(0,0,NaN,t);let i=e.matrix[0].length,s=new ne(r,i,NaN,t);if(n instanceof ne)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 Dp(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 Mp(t){return(e,n,r)=>{let i=e.matrix[n];e.matrix[n]=e.matrix[r],e.matrix[r]=i}}function Pp(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 Rp(t){return e=>{let n=e.matrix.length;if(n===0)return new ne(0,0,NaN,t);let r=e.matrix[0].length,i=new ne(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 Fp=Object.defineProperty,Bp=(t,e,n)=>e in t?Fp(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,U=(t,e,n)=>Bp(t,typeof e!="symbol"?e+"":e,n),ne=class{constructor(e=0,n=0,r=NaN,i){if(this.context=i,U(this,"matrix"),U(this,"_add_col"),U(this,"_add_row"),U(this,"_avg"),U(this,"_col"),U(this,"_columns"),U(this,"_concat"),U(this,"_copy"),U(this,"_det"),U(this,"_diff"),U(this,"_eigenvalues"),U(this,"_eigenvectors"),U(this,"_elements_count"),U(this,"_fill"),U(this,"_get"),U(this,"_inv"),U(this,"_is_antidiagonal"),U(this,"_is_antisymmetric"),U(this,"_is_binary"),U(this,"_is_diagonal"),U(this,"_is_identity"),U(this,"_is_square"),U(this,"_is_stochastic"),U(this,"_is_symmetric"),U(this,"_is_triangular"),U(this,"_is_zero"),U(this,"_kron"),U(this,"_max"),U(this,"_median"),U(this,"_min"),U(this,"_mode"),U(this,"_mult"),U(this,"_pinv"),U(this,"_pow"),U(this,"_rank"),U(this,"_remove_col"),U(this,"_remove_row"),U(this,"_reshape"),U(this,"_reverse"),U(this,"_row"),U(this,"_rows"),U(this,"_set"),U(this,"_sort"),U(this,"_submatrix"),U(this,"_sum"),U(this,"_swap_columns"),U(this,"_swap_rows"),U(this,"_trace"),U(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=Vu(this.context),this._add_row=ju(this.context),this._avg=$u(this.context),this._col=Wu(this.context),this._columns=Uu(this.context),this._concat=qu(this.context),this._copy=zu(this.context),this._det=Hu(this.context),this._diff=Gu(this.context),this._eigenvalues=Zu(this.context),this._eigenvectors=Xu(this.context),this._elements_count=Qu(this.context),this._fill=Ju(this.context),this._get=ep(this.context),this._inv=tp(this.context),this._is_antidiagonal=np(this.context),this._is_antisymmetric=rp(this.context),this._is_binary=ip(this.context),this._is_diagonal=sp(this.context),this._is_identity=ap(this.context),this._is_square=op(this.context),this._is_stochastic=lp(this.context),this._is_symmetric=cp(this.context),this._is_triangular=up(this.context),this._is_zero=pp(this.context),this._kron=hp(this.context),this._max=dp(this.context),this._median=fp(this.context),this._min=mp(this.context),this._mode=yp(this.context),this._mult=gp(this.context),this._pinv=_p(this.context),this._pow=xp(this.context),this._rank=bp(this.context),this._remove_col=wp(this.context),this._remove_row=vp(this.context),this._reshape=Ep(this.context),this._reverse=Sp(this.context),this._row=Cp(this.context),this._rows=Np(this.context),this._set=kp(this.context),this._sort=Ip(this.context),this._submatrix=Ap(this.context),this._sum=Tp(this.context),this._swap_columns=Dp(this.context),this._swap_rows=Mp(this.context),this._trace=Pp(this.context),this._transpose=Rp(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,...e)}add_row(...e){return this._add_row(this,...e)}avg(...e){return this._avg(this,...e)}col(...e){return this._col(this,...e)}columns(...e){return this._columns(this,...e)}concat(...e){return this._concat(this,...e)}copy(...e){return this._copy(this,...e)}det(...e){return this._det(this,...e)}diff(...e){return this._diff(this,...e)}eigenvalues(...e){return this._eigenvalues(this,...e)}eigenvectors(...e){return this._eigenvectors(this,...e)}elements_count(...e){return this._elements_count(this,...e)}fill(...e){return this._fill(this,...e)}get(...e){return this._get(this,...e)}inv(...e){return this._inv(this,...e)}is_antidiagonal(...e){return this._is_antidiagonal(this,...e)}is_antisymmetric(...e){return this._is_antisymmetric(this,...e)}is_binary(...e){return this._is_binary(this,...e)}is_diagonal(...e){return this._is_diagonal(this,...e)}is_identity(...e){return this._is_identity(this,...e)}is_square(...e){return this._is_square(this,...e)}is_stochastic(...e){return this._is_stochastic(this,...e)}is_symmetric(...e){return this._is_symmetric(this,...e)}is_triangular(...e){return this._is_triangular(this,...e)}is_zero(...e){return this._is_zero(this,...e)}kron(...e){return this._kron(this,...e)}max(...e){return this._max(this,...e)}median(...e){return this._median(this,...e)}min(...e){return this._min(this,...e)}mode(...e){return this._mode(this,...e)}mult(...e){return this._mult(this,...e)}pinv(...e){return this._pinv(this,...e)}pow(...e){return this._pow(this,...e)}rank(...e){return this._rank(this,...e)}remove_col(...e){return this._remove_col(this,...e)}remove_row(...e){return this._remove_row(this,...e)}reshape(...e){return this._reshape(this,...e)}reverse(...e){return this._reverse(this,...e)}row(...e){return this._row(this,...e)}rows(...e){return this._rows(this,...e)}set(...e){return this._set(this,...e)}sort(...e){return this._sort(this,...e)}submatrix(...e){return this._submatrix(this,...e)}sum(...e){return this._sum(this,...e)}swap_columns(...e){return this._swap_columns(this,...e)}swap_rows(...e){return this._swap_rows(this,...e)}trace(...e){return this._trace(this,...e)}transpose(...e){return this._transpose(this,...e)}};function lt(t){return(e,n,r)=>new ne(e,n,r,t)}function Lp(t){return(e,n=0)=>y.from(e).get(n)}var bi=class{constructor(e){this.context=e,this.add_col=(n,...r)=>n.add_col(...r),this.add_row=(n,...r)=>n.add_row(...r),this.avg=(n,...r)=>n.avg(...r),this.col=(n,...r)=>n.col(...r),this.columns=(n,...r)=>n.columns(...r),this.concat=(n,...r)=>n.concat(...r),this.copy=(n,...r)=>n.copy(...r),this.det=(n,...r)=>n.det(...r),this.diff=(n,...r)=>n.diff(...r),this.eigenvalues=(n,...r)=>n.eigenvalues(...r),this.eigenvectors=(n,...r)=>n.eigenvectors(...r),this.elements_count=(n,...r)=>n.elements_count(...r),this.fill=(n,...r)=>n.fill(...r),this.get=(n,...r)=>n.get(...r),this.inv=(n,...r)=>n.inv(...r),this.is_antidiagonal=(n,...r)=>n.is_antidiagonal(...r),this.is_antisymmetric=(n,...r)=>n.is_antisymmetric(...r),this.is_binary=(n,...r)=>n.is_binary(...r),this.is_diagonal=(n,...r)=>n.is_diagonal(...r),this.is_identity=(n,...r)=>n.is_identity(...r),this.is_square=(n,...r)=>n.is_square(...r),this.is_stochastic=(n,...r)=>n.is_stochastic(...r),this.is_symmetric=(n,...r)=>n.is_symmetric(...r),this.is_triangular=(n,...r)=>n.is_triangular(...r),this.is_zero=(n,...r)=>n.is_zero(...r),this.kron=(n,...r)=>n.kron(...r),this.max=(n,...r)=>n.max(...r),this.median=(n,...r)=>n.median(...r),this.min=(n,...r)=>n.min(...r),this.mode=(n,...r)=>n.mode(...r),this.mult=(n,...r)=>n.mult(...r),this.new=lt(e),this.param=Lp(),this.pinv=(n,...r)=>n.pinv(...r),this.pow=(n,...r)=>n.pow(...r),this.rank=(n,...r)=>n.rank(...r),this.remove_col=(n,...r)=>n.remove_col(...r),this.remove_row=(n,...r)=>n.remove_row(...r),this.reshape=(n,...r)=>n.reshape(...r),this.reverse=(n,...r)=>n.reverse(...r),this.row=(n,...r)=>n.row(...r),this.rows=(n,...r)=>n.rows(...r),this.set=(n,...r)=>n.set(...r),this.sort=(n,...r)=>n.sort(...r),this.submatrix=(n,...r)=>n.submatrix(...r),this.sum=(n,...r)=>n.sum(...r),this.swap_columns=(n,...r)=>n.swap_columns(...r),this.swap_rows=(n,...r)=>n.swap_rows(...r),this.trace=(n,...r)=>n.trace(...r),this.transpose=(n,...r)=>n.transpose(...r),this.new_float=lt(e),this.new_int=lt(e),this.new_string=lt(e),this.new_bool=lt(e),this.new_color=lt(e),this.new_line=lt(e),this.new_label=lt(e),this.new_box=lt(e),this.new_linefill=lt(e),this.new_table=lt(e)}},Op=Object.defineProperty,Vp=(t,e,n)=>e in t?Op(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,jp=(t,e,n)=>Vp(t,typeof e!="symbol"?e+"":e,n),wi=class{constructor(e){this.context=e,jp(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}},$p=Object.defineProperty,Wp=(t,e,n)=>e in t?$p(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,oi=(t,e,n)=>Wp(t,typeof e!="symbol"?e+"":e,n),Oe=class t{constructor(e,n,r){oi(this,"time"),oi(this,"index"),oi(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 Up(t){return typeof t=="object"&&t&&(t.title!==void 0||t._plotKey!==void 0)&&t.data!==void 0&&t.options!==void 0}var sa={series:t=>t instanceof y||typeof t=="number"||typeof t=="string"||typeof t=="boolean",string:t=>typeof t=="string",color:t=>typeof t=="string"||t===null||typeof t=="number"&&isNaN(t)||t instanceof y,number:t=>typeof t=="number",boolean:t=>typeof t=="boolean",array:t=>Array.isArray(t),object:t=>typeof t=="object",point:t=>t instanceof Oe,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 y)&&!(t instanceof Oe)&&!Up(t)};function ht(t){let e=t[t.length-1];if(e&&typeof e=="object"&&"__callsiteId"in e)return t.pop().__callsiteId}function ce(t,e,n,r){Array.isArray(e)&&typeof e[0]=="string"&&(e=[e]);let i={},s={},a=new Array(e.length).fill(!0);for(let o=0;o<t.length;o++){let l=t[o];if(sa.remaining_options(l)){s=l;break}let c=e.map((u,h)=>a[h]?u[o]:void 0);for(let u=0;u<c.length;u++){let h=c[u];if(h===void 0){a[u]=!1;continue}let p=n[h];if(typeof l=="number"&&isNaN(l)&&(p==="number"||p==="series"))i[h]=l;else{let d=sa[n[h]];typeof d=="function"&&d(l)?i[h]=l:a[u]=!1}}}return{...i,...s,...r}}var qp=/^(\\d{2})(\\d{2})-(\\d{2})(\\d{2})$/;function zp(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(qp);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 Kp(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 Hp=Object.defineProperty,Gp=(t,e,n)=>e in t?Hp(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Yp=(t,e,n)=>Gp(t,typeof e!="symbol"?e+"":e,n),dr=class extends Error{constructor(e,n){super(e),Yp(this,"method"),this.name="PineRuntimeError",this.method=n}},Zp=Object.defineProperty,Xp=(t,e,n)=>e in t?Zp(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,fr=(t,e,n)=>Xp(t,typeof e!="symbol"?e+"":e,n);function vi(t){if(!t)return"";let e=t.trim().toUpperCase();return e==="1D"||e==="D"?"D":e==="1W"||e==="W"?"W":e==="1M"||e==="M"?"M":e}function Ei(t,e){let n=Qp(e);if(e==="M"){let o=new Date(t);return Date.UTC(o.getUTCFullYear(),o.getUTCMonth(),1)}if(e==="W"){let o=new Date(t),l=o.getUTCDay(),c=l===0?6:l-1;return Date.UTC(o.getUTCFullYear(),o.getUTCMonth(),o.getUTCDate()-c)}if(e==="D"||n>=1440)return Math.floor(t/864e5)*864e5;let r=n*6e4,i=Math.floor(t/864e5)*864e5,s=t-i,a=Math.floor(s/r)*r;return i+a}function Qp(t){if(t==="D")return 1440;if(t==="W")return 10080;if(t==="M")return 43200;let e=parseInt(t,10);return isNaN(e)?1440:e}function jt(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 Jp(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 eh=[["timeframe"],["timeframe","bars_back"],["timeframe","session","bars_back"],["timeframe","session","bars_back","timeframe_bars_back"],["timeframe","session","timezone","bars_back","timeframe_bars_back"]],th={timeframe:"string",session:"string",timezone:"string",bars_back:"number",timeframe_bars_back:"number"},mr=class{constructor(e,n="openTime"){fr(this,"context"),fr(this,"dataField"),this.context=e,this.dataField=n}get __value(){return this.context.data[this.dataField]}param(e,n=0){return y.from(e).get(n)}any(...e){let n=e.map(p=>p instanceof y?p.get(0):p),r=ce(n,eh,th),i=r.bars_back??0,s=r.timeframe||"",a=this.context.data[this.dataField],o=y.from(a).get(i);if(isNaN(o)||o==null)return NaN;let l=this.context.timeframe||"",c=vi(s),u=vi(l),h;if(!c||c===u?h=o:h=Ei(o,c),r.session!==void 0&&r.session!==""){let p=r.timezone||this.context.pine?.syminfo?.timezone||"UTC";return this._isInSession(h,r.session,p)?h:NaN}return h}_isInSession(e,n,r){let i=zp(n);if(!i)throw new dr(`Invalid session specification: "${n}"`,"time");let s=jt(e,r),a=s.hour*60+s.minute;return Kp(i,a,s.dayOfWeek)}},nh=[[],["time"],["time","timezone"]],rh={time:"number",timezone:"string"},xt=class{constructor(e,n){fr(this,"context"),fr(this,"extractor"),this.context=e,this.extractor=n}get __value(){let e=y.from(this.context.data.openTime).get(0);if(isNaN(e))return NaN;let n=this.context.pine?.syminfo?.timezone||"UTC",r=jt(e,n);return this.extractor(r)}param(e,n=0){return y.from(e).get(n)}any(...e){let n=e.map(o=>o instanceof y?o.get(0):o);if(n.length===0)return this.__value;let r=ce(n,nh,rh),i=r.time;if(i===void 0||isNaN(i))return NaN;let s=r.timezone||this.context.pine?.syminfo?.timezone||"UTC",a=jt(i,s);return this.extractor(a)}},Ft={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=>Jp(t.year,t.month,t.day),year:t=>t.year},ih=Object.defineProperty,sh=(t,e,n)=>e in t?ih(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,aa=(t,e,n)=>sh(t,typeof e!="symbol"?e+"":e,n),Si=class{constructor(e){this.context=e,aa(this,"regular","regular"),aa(this,"extended","extended")}get _timezone(){return this.context.pine?.syminfo?.timezone||"UTC"}_dayKey(e){let n=jt(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}},ah=Object.defineProperty,oh=(t,e,n)=>e in t?ah(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,lh=(t,e,n)=>oh(t,typeof e!="symbol"?e+"":e,n),Lt=class t{constructor(e,n,r){this._definition=e,this.context=n,lh(this,"_udt");for(let i in e)this[i]=e[i];this._udt=r}get __def__(){return this._definition}copy(){return new t(this.__def__,this.context,this._udt)}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(",")+"}"}}};function k(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 lo=Object.defineProperty,ch=Object.getOwnPropertyDescriptor,uh=(t,e,n)=>e in t?lo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,co=(t,e,n,r)=>{for(var i=r>1?void 0:r?ch(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&&lo(e,n,i),i},fn=(t,e,n)=>uh(t,typeof e!="symbol"?e+"":e,n),ph=[["dateString"],["year","month","day","hour","minute","second"],["timezone","year","month","day","hour","minute","second"]],hh={dateString:"string",timezone:"string",year:"number",month:"number",day:"number",hour:"number",minute:"number",second:"number"},dh=["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"],fh={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 mh(t){return ce(t,dh,fh)}var Ze=class t{get __value(){return NaN}param(e,n=0){return y.from(e).get(n)}any(e){if(e instanceof t)return!0;let n=y.from(e).get(0);return n instanceof t||n==null?!0:typeof n=="number"?n!==n:!1}},an={freq_all:"alert.freq_all",freq_once_per_bar:"alert.freq_once_per_bar",freq_once_per_bar_close:"alert.freq_once_per_bar_close"},yr=class{constructor(e){this.context=e,fn(this,"_firedKeys",new Set),fn(this,"_fallbackCounter",0),fn(this,"_fallbackLastExecTick",-1)}get freq_all(){return an.freq_all}get freq_once_per_bar(){return an.freq_once_per_bar}get freq_once_per_bar_close(){return an.freq_once_per_bar_close}param(e,n,r){return y.from(e).get(0)}any(e,n,r){let i=y.from(e).get(0),s=n?y.from(n).get(0):an.freq_once_per_bar,a;if(r&&typeof r=="object"&&r.__callsiteId)a=r.__callsiteId;else{let u=this.context._execTick||0;u!==this._fallbackLastExecTick&&(this._fallbackCounter=0,this._fallbackLastExecTick=u),a=`alert_${this._fallbackCounter++}`}let o=this.context.idx,l=this.context.pine?.barstate?.isrealtime??o===this.context.length-1;if((this.context._alertMode||"realtime")==="realtime"&&!l)return;let c=`${a}:${o}`;if(s===an.freq_once_per_bar){if(this._firedKeys.has(c))return;this._firedKeys.add(c)}else if(s===an.freq_once_per_bar_close){if(!(this.context.pine?.barstate?.isconfirmed??!0)||this._firedKeys.has(c))return;this._firedKeys.add(c)}this.context.alerts.push({type:"alert",id:a,message:i,freq:s,bar_index:o,time:this.context.data.openTime?.data?.[o]??0})}};co([k],yr.prototype,"any",1);var gr=class{constructor(e){this.context=e,fn(this,"_acCounter",0),fn(this,"_acLastExecTick",-1),fn(this,"_acFiredKeys",new Set)}extractPlotOptions(e){let n={};for(let r in e)n[r]=y.from(e[r]).get(0);return n}indicator(...e){let n=e.map(s=>s instanceof y?s.get(0):s),r=mh(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}get bar_index(){return this.context.idx}na(e){let n=y.from(e).get(0);return n==null||typeof n=="number"&&isNaN(n)}nz(e,n=0){let r=y.from(e).get(0),i=y.from(n).get(0);return r==null||typeof r=="number"&&isNaN(r)?i:r}fixnan(e){let n=y.from(e);for(let r=0;r<n.length;r++){let i=n.get(r);if(!isNaN(i))return i}return NaN}alertcondition(e,n,r){let i=y.from(e).get(0),s=this.context.idx,a=this.context._execTick||0;a!==this._acLastExecTick&&(this._acCounter=0,this._acLastExecTick=a);let o=`alertcondition_${this._acCounter++}`;if(!i)return;let l=this.context.pine?.barstate?.isrealtime??s===this.context.length-1;if((this.context._alertMode||"realtime")==="realtime"&&!l)return;let c=`${o}:${s}`;if(this._acFiredKeys.has(c))return;this._acFiredKeys.add(c);let u=n?y.from(n).get(0):"",h=r?y.from(r).get(0):"";this.context.alerts.push({type:"alertcondition",id:o,title:u,message:h,bar_index:s,time:this.context.data.openTime?.data?.[s]??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 y?i.get(0):i),r=ce(n,ph,hh);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())){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=E=>parseInt(c.find(v=>v.type===E)?.value||"0",10),h=u("year"),p=u("month"),d=u("day"),f=u("hour");f===24&&(f=0);let m=u("minute"),x=u("second"),b=new Date(Date.UTC(h,p-1,d,f,m,x));h>=0&&h<100&&b.setUTCFullYear(h);let w=b.getTime()-l.getTime();return l.getTime()-w}bool(e){let n=y.from(e).get(0);return!isNaN(n)&&n!==0}int(e){let n=y.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=y.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){return y.from(e).get(0).toString()}Type(e){let n=Object.keys(e),r={};for(let s of n){let a=e[s];a instanceof y&&(a=a.data),Array.isArray(a)&&(a[0],r[s]=a[1])}let i={new:function(...s){let a={},o=null;if(s.length>0){let l=s[s.length-1];if(l&&typeof l=="object"&&!(l instanceof y)&&!Array.isArray(l)&&!(l instanceof Lt)){let c=Object.keys(l);c.length>0&&c.some(u=>n.includes(u))&&(o=l,s=s.slice(0,-1))}}for(let l=0;l<n.length;l++){let c=n[l];o&&c in o?a[c]=o[c]:l<s.length?a[c]=s[l]:c in r&&(a[c]=y.from(r[c]).get(0))}return new Lt(a,this.context,i)},copy:function(s){return new Lt(s.__def__,this.context,i)},_fieldDefaults:r,_definitionKeys:n};return i}};co([k],gr.prototype,"alertcondition",1);function Ht(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 yh(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 xe={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 uo(t){if(typeof t!="string")return null;let e=t.trim(),n=e.startsWith("color.")?e.slice(6):e;return Object.prototype.hasOwnProperty.call(xe,n)&&(e=xe[n]),Ht(e)}function Ci(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 gh(t){let e=uo(t);return e?Ci(e[0],e[1],e[2],e[3]):t}function gt(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 Ni=class{constructor(e){this.context=e}any(e){let n=y.from(e).get(0);return typeof n=="number"&&isNaN(n)?null:n}param(e,n=0){return y.from(e).get(n)}new(e,n){if(e=gt(e),!e||typeof e!="string")return e;if(typeof n=="number"&&isNaN(n)&&(n=void 0),e.startsWith("#")){let r=e.slice(1),i=r.length===8?r.slice(0,6):r;return n!=null?`#${i}${Math.round(255/100*(100-n)).toString(16).padStart(2,"0").toUpperCase()}`:`#${r}`}else{let r=xe[e];if(r)return n!=null?`#${r.slice(1)}${Math.round(255/100*(100-n)).toString(16).padStart(2,"0").toUpperCase()}`:r;let i=e.match(/rgba?\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)(?:\\s*,\\s*([\\d.]+))?\\s*\\)/);if(i){let s=i[1],a=i[2],o=i[3];if(n!=null){let l=parseInt(s).toString(16).padStart(2,"0"),c=parseInt(a).toString(16).padStart(2,"0"),u=parseInt(o).toString(16).padStart(2,"0"),h=Math.round(255/100*(100-n)).toString(16).padStart(2,"0").toUpperCase();return`#${l}${c}${u}${h}`}return e}return n!=null?`rgba(${e}, ${(100-n)/100})`:e}}rgb(e,n,r,i){return typeof i=="number"&&isNaN(i)&&(i=void 0),i!=null?`rgba(${e}, ${n}, ${r}, ${(100-i)/100})`:`rgb(${e}, ${n}, ${r})`}from_gradient(e,n,r,i,s){if(e=gt(e),n=gt(n),r=gt(r),i=gt(i),s=gt(s),e==null||typeof e=="number"&&isNaN(e)||n==null||typeof n=="number"&&isNaN(n)||r==null||typeof r=="number"&&isNaN(r)||i==null||typeof i=="number"&&isNaN(i)||s==null||typeof s=="number"&&isNaN(s))return;let a=0;r!==n&&(a=(e-n)/(r-n)),a=Math.max(0,Math.min(1,a));let o=Ht(typeof i=="string"?i:"#000000")||[0,0,0,1],l=Ht(typeof s=="string"?s:"#FFFFFF")||[255,255,255,1],c=o[0]+(l[0]-o[0])*a,u=o[1]+(l[1]-o[1])*a,h=o[2]+(l[2]-o[2])*a,p=o[3]+(l[3]-o[3])*a;return yh(c,u,h,p)}r(e){if(e=gt(e),!e||typeof e!="string")return NaN;let n=Ht(e);return n?n[0]:NaN}g(e){if(e=gt(e),!e||typeof e!="string")return NaN;let n=Ht(e);return n?n[1]:NaN}b(e){if(e=gt(e),!e||typeof e!="string")return NaN;let n=Ht(e);return n?n[2]:NaN}t(e){if(e=gt(e),!e||typeof e!="string")return NaN;let n=Ht(e);return n?Math.round(100-n[3]*100):NaN}aqua(){return xe.aqua}black(){return xe.black}blue(){return xe.blue}fuchsia(){return xe.fuchsia}gray(){return xe.gray}green(){return xe.green}lime(){return xe.lime}maroon(){return xe.maroon}navy(){return xe.navy}olive(){return xe.olive}orange(){return xe.orange}purple(){return xe.purple}red(){return xe.red}silver(){return xe.silver}teal(){return xe.teal}white(){return xe.white}yellow(){return xe.yellow}},_s=new Set(["open","high","low","close","hl2","hlc3","ohlc4","hlcc4","volume"]);function po(t,e){if(!_s.has(e))return;let n=t?.data?.[e];if(n!=null)return y.from(n).get(0)}var _h=[["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"]],xh={defval:"primitive",title:"string",tooltip:"string",inline:"string",group:"string",display:"string",confirm:"boolean",options:"array",minval:"number",maxval:"number",step:"number"};function Ke(t){let e,n=t[t.length-1];n&&typeof n=="object"&&Object.prototype.hasOwnProperty.call(n,"__varId")&&(e=n.__varId,t=t.slice(0,-1));let r=ce(t,_h,xh);return e!==void 0&&(r.__varId=e),r}function Xe(t,e){return 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 bh(t){return(...e)=>{let n=Ke(e),r=Xe(t,n);if(typeof r=="string"&&typeof n.defval=="number"){let i=po(t,r);if(i!==void 0)return i}return r}}function wh(t){return(...e)=>{let n=Ke(e);return Xe(t,n)}}function vh(t){return(...e)=>{let n=Ke(e);return Xe(t,n)}}function Eh(t){return(...e)=>{let n=Ke(e);return Xe(t,n)}}function Sh(t){return(...e)=>{let n=Ke(e);return Xe(t,n)}}function Ch(t){return(...e)=>{let n=Ke(e);return Xe(t,n)}}function Nh(t){return(e,n=0)=>y.from(e).get(n)}function kh(t){return(...e)=>{let n=Ke(e);return Xe(t,n)}}function Ih(t){return(...e)=>{let n=Ke(e);return Xe(t,n)}}function Ah(t){return(...e)=>{let n=Ke(e),r=Xe(t,n);if(typeof r=="string"){let i=po(t,r);return i!==void 0?i:n.defval}return r}}function Th(t){return(...e)=>{let n=Ke(e);return Xe(t,n)}}function Dh(t){return(...e)=>{let n=Ke(e);return Xe(t,n)}}function Mh(t){return(...e)=>{let n=Ke(e);return Xe(t,n)}}function Ph(t){return(...e)=>{let n=Ke(e);return Xe(t,n)}}function Rh(t){return(...e)=>Ke(e).defval}var Fh=Object.defineProperty,Bh=(t,e,n)=>e in t?Fh(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Be=(t,e,n)=>Bh(t,typeof e!="symbol"?e+"":e,n),Lh={any:bh,bool:wh,color:vh,enum:Eh,float:Sh,int:Ch,param:Nh,price:kh,session:Ih,source:Ah,string:Th,symbol:Dh,text_area:Mh,time:Ph,timeframe:Rh},ki=class{constructor(e){this.context=e,Be(this,"any"),Be(this,"bool"),Be(this,"color"),Be(this,"enum"),Be(this,"float"),Be(this,"int"),Be(this,"param"),Be(this,"price"),Be(this,"session"),Be(this,"source"),Be(this,"string"),Be(this,"symbol"),Be(this,"text_area"),Be(this,"time"),Be(this,"timeframe"),Object.entries(Lh).forEach(([n,r])=>{this[n]=r(e)})}};function Oh(t){return e=>Math.abs(y.from(e).get(0))}function Vh(t){return e=>Math.acos(y.from(e).get(0))}function jh(t){return e=>Math.asin(y.from(e).get(0))}function $h(t){return e=>Math.atan(y.from(e).get(0))}function Wh(t){return(...e)=>{let n=e.map(r=>y.from(r).get(0));return n.reduce((r,i)=>r+i,0)/n.length}}function Uh(t){return e=>Math.ceil(y.from(e).get(0))}function qh(t){return e=>Math.cos(y.from(e).get(0))}function zh(t){return()=>Math.E}function Kh(t){return e=>Math.exp(y.from(e).get(0))}function Hh(t){return e=>Math.floor(y.from(e).get(0))}function Gh(t){return e=>Math.log(y.from(e).get(0))}function Yh(t){return e=>Math.log(y.from(e).get(0))}function Zh(t){return e=>Math.log10(y.from(e).get(0))}function Xh(t){return(...e)=>{let n=e.map(r=>y.from(r).get(0));return Math.max(...n)}}function Qh(t){return(...e)=>{let n=e.map(r=>y.from(r).get(0));return Math.min(...n)}}function Jh(t){return(e,n,r)=>typeof e=="string"?e:e instanceof y?n?new y(e.data,e.offset+n):e:!Array.isArray(e)&&typeof e=="object"?e:(t.params[r]||(t.params[r]=[]),Array.isArray(e)?new y(e,n||0):(t.params[r].length===0?t.params[r].push(e):t.params[r][t.params[r].length-1]=e,new y(t.params[r],n||0)))}function ed(t){return()=>1.618033988749895}function td(t){return()=>Math.PI}function nd(t){return(e,n)=>Math.pow(y.from(e).get(0),y.from(n).get(0))}function rd(t){return()=>Math.random()}function li(t){return t!==t?NaN:Math.sign(t)*Math.round(Math.abs(t))}function id(t){return(e,n)=>{let r=y.from(e).get(0);if(n==null)return li(r);let i=y.from(n).get(0);if(i===0)return li(r);let s=Math.pow(10,i);return li(r*s)/s}}function sd(t){return e=>t.precision(Math.round(y.from(e).get(0)/t.pine.syminfo.mintick)*t.pine.syminfo.mintick)}function ad(t){return()=>.6180339887498948}function od(t){return e=>Math.sign(y.from(e).get(0))}function ld(t){return e=>Math.sin(y.from(e).get(0))}function cd(t){return e=>Math.sqrt(y.from(e).get(0))}function ud(t){return(e,n)=>{let r=y.from(n).get(0),i=y.from(e),s=0;for(let a=0;a<r;a++){let o=i.get(a);s+=o}return s}}function pd(t){return e=>Math.tan(y.from(e).get(0))}function hd(t){return e=>{let n=y.from(e).get(0);return n==null||Number.isNaN(n)?NaN:n*(180/Math.PI)}}function dd(t){return e=>{let n=y.from(e).get(0);return n==null||Number.isNaN(n)?NaN:n*(Math.PI/180)}}function fd(t){return(e,n)=>{let r=y.from(e).get(0),i=y.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 md(t){return(e,n)=>{let r=y.from(e).get(0),i=y.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 yd(t){return(e,n)=>{let r=y.from(e).get(0),i=y.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 gd(t){return(e,n)=>{let r=y.from(e).get(0),i=y.from(n).get(0);return typeof r!="number"||typeof i!="number"?r/i:isNaN(r)||isNaN(i)?NaN:Math.trunc(r/i)}}function _d(t){return(e,n)=>{let r=y.from(e).get(0),i=y.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 xd(t){return(e,n)=>{let r=y.from(e).get(0),i=y.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 bd(t){return(e,n)=>{let r=y.from(e).get(0),i=y.from(n).get(0);return typeof r=="number"&&typeof i=="number"?isNaN(r)||isNaN(i)?NaN:Math.abs(r-i)>=1e-10:r!==i}}var wd=Object.defineProperty,vd=(t,e,n)=>e in t?wd(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Z=(t,e,n)=>vd(t,typeof e!="symbol"?e+"":e,n),Ed={abs:Oh,acos:Vh,asin:jh,atan:$h,avg:Wh,ceil:Uh,cos:qh,e:zh,exp:Kh,floor:Hh,ln:Gh,log:Yh,log10:Zh,max:Xh,min:Qh,param:Jh,phi:ed,pi:td,pow:nd,random:rd,round:id,round_to_mintick:sd,rphi:ad,sign:od,sin:ld,sqrt:cd,sum:ud,tan:pd,todegrees:hd,toradians:dd,__eq:fd,__ge:md,__gt:yd,__idiv:gd,__le:_d,__lt:xd,__neq:bd},Ii=class{constructor(e){this.context=e,Z(this,"_cache",{}),Z(this,"abs"),Z(this,"acos"),Z(this,"asin"),Z(this,"atan"),Z(this,"avg"),Z(this,"ceil"),Z(this,"cos"),Z(this,"e"),Z(this,"exp"),Z(this,"floor"),Z(this,"ln"),Z(this,"log"),Z(this,"log10"),Z(this,"max"),Z(this,"min"),Z(this,"param"),Z(this,"phi"),Z(this,"pi"),Z(this,"pow"),Z(this,"random"),Z(this,"round"),Z(this,"round_to_mintick"),Z(this,"rphi"),Z(this,"sign"),Z(this,"sin"),Z(this,"sqrt"),Z(this,"sum"),Z(this,"tan"),Z(this,"todegrees"),Z(this,"toradians"),Z(this,"__eq"),Z(this,"__ge"),Z(this,"__gt"),Z(this,"__idiv"),Z(this,"__le"),Z(this,"__lt"),Z(this,"__neq"),Object.entries(Ed).forEach(([n,r])=>{this[n]=r(e)})}};function Sd(t){return(e,n,r)=>{t.params[r]||(t.params[r]=[]);let i;if(e instanceof y)i=e.get(n||0);else if(Array.isArray(e)){let s=e.some(o=>o instanceof y),a=e.every(o=>!(o instanceof y)&&!Array.isArray(o));(s||a)&&e.length>=1?i=e.map(o=>o instanceof y?o.get(0):o):i=y.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]}}var Cd=new Set(["heikinashi","standard"]);function jn(t){if(typeof t!="string")return{symbol:t,modifier:null};let e=t.lastIndexOf(";");if(e<=0||e===t.length-1)return{symbol:t,modifier:null};let n=t.slice(e+1).toLowerCase();return Cd.has(n)?{symbol:t.slice(0,e),modifier:n}:{symbol:t,modifier:null}}function Ot(t){return jn(t).symbol}function Ai(t,e){return`${Ot(t)};${e}`}var gn=["1","3","5","15","30","45","60","120","180","240","D","W","M"],Zn={"1m":"1","3m":"3","5m":"5","15m":"15","30m":"30","45m":"45","1h":"60","2h":"120","3h":"180","4h":"240","1d":"D","1w":"W","1M":"M"};function _r(t){if(gn.includes(t))return t;if(Zn[t])return Zn[t];let e=t.toLowerCase();if(Zn[e])return Zn[e];let n=t.toUpperCase();return gn.includes(n)?n:t}function oa(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 la(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){let l=s&&e>s;if(a&&i)for(let c=0;c<n.length;c++){if(n[c]>=t&&n[c]<e)return c;if(n[c]>=e)break}if(l&&i&&!a)for(let c=0;c<n.length;c++){if(n[c]>=t&&n[c]<e)return c;if(n[c]>=e)break}return o}if(r[o]<t)break}return-1}var ca=[["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"]],Nd={symbol:"series",timeframe:"series",expression:"any",gaps:"series",lookahead:"series",ignore_invalid_symbol:"series",currency:"series",calc_bars_count:"series"};function xs(t){return Array.isArray(t)&&t.length===2&&typeof t[1]=="string"}function kd(t,e){return t.map(n=>xs(n)?(e.push(n[1]),n[0]):(e.push(void 0),n))}function on(t){return xs(t)?t[0]:t}function Id(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(xs(r))return r[1]}function Ti(t){return t==null||typeof t!="object"?t:"__value"in t?t.__value:t instanceof y?t.get(0):Array.isArray(t)?t.map(Ti):t}function Ad(t){return async(...e)=>{let n=[],r=kd(e,n),i=ce(r,ca,Nd),s=on(i.symbol),a=on(i.timeframe),o=on(i.expression),l=on(i.gaps),c=on(i.lookahead),u=s instanceof y?s.get(0):s,h=typeof t.tickerId=="string"&&t.tickerId.includes(":")?t.tickerId.split(":")[1]:t.tickerId,p=typeof h=="string"?jn(h):{symbol:h,modifier:null},d=p.modifier==="standard"?null:p.modifier,f=u===""?t.tickerId:u,m=typeof f=="string"&&f.includes(":")?f.split(":")[1]:f,x=a instanceof y?a.get(0):a,b=x===""?t.timeframe:typeof x=="string"?x:String(x??""),w=o,E=Id("expression",ca,n,i.expression),v=l,I=c,C=v===!0||v==="gaps_on",T=I===!0||I==="lookahead_on",O=(()=>{let Ae=on(i.calc_bars_count);return typeof Ae=="number"&&Ae>0?Ae:void 0})();if(t.isSecondaryContext){let Ae=Ti(w);return Array.isArray(Ae)?[Ae]:Ae}let N=gn.indexOf(_r(t.timeframe)),j=gn.indexOf(_r(b));if(N==-1||j==-1)throw new Error("Invalid timeframe");let D=typeof m=="string"?jn(m):{symbol:m,modifier:null},W=D.modifier==="standard"?null:D.modifier,R=!m||m===""||D.symbol===p.symbol&&W===d;if(N===j&&R){let Ae=Ti(w);return Array.isArray(Ae)?[Ae]:Ae}let P=N>j,H=y.from(t.data.openTime).get(0),te=y.from(t.data.closeTime).get(0),ve=t.idx===t.length-1&&te>Date.now(),ae=`${m}_${b}_${E}`,Fe=`${ae}_prevIdx`;if(t.cache[ae]){let Ae=t.cache[ae];t.dataVersion>Ae.dataVersion&&(await Ae.pineTS.updateTail(Ae.context),Ae.dataVersion=t.dataVersion);let Cn=Ae.context,Yn=P?la(H,te,Cn.data.openTime.data,Cn.data.closeTime.data,T,t.eDate,C):oa(H,te,Cn.data.openTime.data,Cn.data.closeTime.data,T,ve);if(Yn==-1)return NaN;let sn=Cn.params[E][Yn];if(!P&&C){let ra=t.cache[Fe];return ra!==void 0&&ra===Yn?NaN:(t.cache[Fe]=Yn,Array.isArray(sn)?[sn]:sn)}return Array.isArray(sn)?[sn]:sn}let Sn=1e3*60*60*24*30,ea=t.sDate||(t.marketData?.length>0?t.marketData[0].openTime:void 0),dc=O?void 0:ea?ea-Sn:void 0,fc=(t.marketData?.length>0?t.marketData[t.marketData.length-1].closeTime:0)||t.eDate||Date.now(),Gn=new Ut(t.source,m,b,O,dc,fc);Gn.markAsSecondary();let ta=typeof E=="string"?E:"",mc=ta.match(/p\\d+$/)?.[0]??ta,na=t._ltfTruncatedBodies?.[mc],rn=na?await Gn.runPretranspiled(na):await Gn.run(t.pineTSCode);t.cache[ae]={pineTS:Gn,context:rn,dataVersion:t.dataVersion};let si=P?la(H,te,rn.data.openTime.data,rn.data.closeTime.data,T,t.eDate,C):oa(H,te,rn.data.openTime.data,rn.data.closeTime.data,T,ve);if(si==-1)return NaN;let ai=rn.params[E][si];return!P&&C?(t.cache[Fe]=si,NaN):Array.isArray(ai)?[ai]:ai}}var ua=[["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"]],Td={symbol:"series",timeframe:"series",expression:"any",ignore_invalid_symbol:"series",currency:"series",ignore_invalid_timeframe:"series",calc_bars_count:"series"};function bs(t){return Array.isArray(t)&&t.length===2&&typeof t[1]=="string"}function Dd(t,e){return t.map(n=>bs(n)?(e.push(n[1]),n[0]):(e.push(void 0),n))}function ln(t){return bs(t)?t[0]:t}function Md(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(bs(r))return r[1]}function cn(t){return typeof t=="number"?z.float:typeof t=="boolean"?z.bool:typeof t=="string"?z.string:z.any}var ho={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 Di(t,e){if(!(t instanceof y))return null;let n=e?.data;if(!n)return null;for(let r of Object.keys(ho))if(t===n[r])return r;return null}function Pd(t,e){if(t instanceof y&&(t=t.get(0)),!(t instanceof Lt))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=Di(a,e);if(o===null)return null;i.push(o)}return{kind:"udt",builtinNames:i,fieldNames:r,udt:n}}function Rd(t,e){if(t===void 0)return null;if(Array.isArray(t)){let r=[];for(let i of t){let s=Di(i,e);if(s===null)return null;r.push(s)}return r.length>0?{kind:"tuple",builtinNames:r}:null}let n=Di(t,e);return n!==null?{kind:"series",builtinNames:[n]}:Pd(t,e)}async function pa(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 Ut(t.source,e,n,r,a,o);l.markAsSecondary(),await l.ready();let c=l.openTime,u=l.closeTime,h=l.data,p=i.builtinNames.map(f=>ho[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(x=>{let b={};for(let w=0;w<f.length;w++)b[f[w]]=p[w](x);return new Lt(b,t,m)})}return{data:{openTime:{data:c},closeTime:{data:u}},params:{[s]:d}}}function Fd(t){return async(...e)=>{let n=[],r=Dd(e,n),i=ce(r,ua,Td),s=ln(i.symbol),a=ln(i.timeframe),o=ln(i.expression),l=s instanceof y?s.get(0):s,c=l===""?t.tickerId:l,u=typeof c=="string"&&c.includes(":")?c.split(":")[1]:c,h=a instanceof y?a.get(0):a,p=h===""?t.timeframe:typeof h=="string"?h:String(h??""),d=o,f=Md("expression",ua,n,i.expression);ln(i.ignore_invalid_symbol);let m=ln(i.ignore_invalid_timeframe),x=(()=>{let P=ln(i.calc_bars_count);return typeof P=="number"&&P>0?P:void 0})();if(t.isSecondaryContext)return Array.isArray(d)?[d.map(P=>new q([P],cn(P),t))]:new q([d],cn(d),t);let b=gn.indexOf(_r(t.timeframe)),w=gn.indexOf(_r(p));if(b===-1||w===-1){if(m)return NaN;throw new Error("Invalid timeframe")}if(w>b){if(m)return NaN;throw new Error(`Timeframe ${p} is not lower than or equal to chart timeframe ${t.timeframe}`)}if(w===b)return Array.isArray(d)?[d.map(P=>new q([P],cn(P),t))]:new q([d],cn(d),t);let E=`${u}_${p}_${f}_lower`,v=t._requestParamSources?.[f],I=Rd(v,t);if(!t.cache[E])if(I!==null){let P=await pa(t,u,p,x,I,f);t.cache[E]={pineTS:null,context:P,dataVersion:t.dataVersion,_fastPath:!0,_fastPathArgs:{builtinExpr:I}}}else{let P=t.sDate||(t.marketData?.length>0?t.marketData[0].openTime:void 0),H=(t.marketData?.length>0?t.marketData[t.marketData.length-1].closeTime:0)||t.eDate||Date.now(),te=new Ut(t.source,u,p,x,P,H);te.markAsSecondary();let ve=typeof f=="string"?f:"",ae=ve.match(/p\\d+$/)?.[0]??ve,Fe=t._ltfTruncatedBodies?.[ae],Sn;Fe?Sn=await te.runPretranspiled(Fe):Sn=await te.run(t.pineTSCode),t.cache[E]={pineTS:te,context:Sn,dataVersion:t.dataVersion}}let C=t.cache[E];if(t.dataVersion>C.dataVersion)if(C._fastPath){let P=await pa(t,u,p,x,C._fastPathArgs.builtinExpr,f);C.context=P,C.dataVersion=t.dataVersion}else await C.pineTS.updateTail(C.context),C.dataVersion=t.dataVersion;let T=C.context,O=y.from(t.data.openTime).get(0),N=y.from(t.data.closeTime).get(0),j=T.data.openTime.data,D=T.data.closeTime.data,W=T.params[f];if(!W)return Array.isArray(d)?[d.map(()=>new q([],z.float,t))]:new q([],z.float,t);let R=[];for(let P=0;P<j.length;P++){let H=j[P];if(!(D[P]<=O)){if(H>=N)break;H>=O&&H<N&&R.push(W[P])}}if(R.length>0&&Array.isArray(R[0])){let P=R[0].length,H=[];for(let te=0;te<P;te++){let ve=R.map(Fe=>Fe[te]),ae=ve.length>0?cn(ve[0]):z.float;H.push(new q(ve,ae,t))}return[H]}else{let P=R.length>0?cn(R[0]):z.float;return new q(R,P,t)}}}var Bd=Object.defineProperty,Ld=(t,e,n)=>e in t?Bd(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Xn=(t,e,n)=>Ld(t,typeof e!="symbol"?e+"":e,n),Od={param:Sd,security:Ad,security_lower_tf:Fd},Mi=class{constructor(e){this.context=e,Xn(this,"_cache",{}),Xn(this,"param"),Xn(this,"security"),Xn(this,"security_lower_tf"),Object.entries(Od).forEach(([n,r])=>{this[n]=r(e)})}};function Vd(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 jd(t){return(e,n,r,i,s)=>{let a=y.from(n).get(0),o=y.from(r).get(0),l=y.from(i).get(0);t.taState||(t.taState={});let c=s||`alma_${a}_${o}_${l}`;if(!t.taState[c]){let m=o*(a-1),x=a/l,b=[],w=0;for(let E=0;E<a;E++){let v=Math.exp(-Math.pow(E-m,2)/(2*x*x));b.push(v),w+=v}for(let E=0;E<b.length;E++)b[E]/=w;t.taState[c]={lastIdx:-1,prevWindow:[],prevCallCount:0,currentWindow:[],currentCallCount:0,weights:b}}let u=t.taState[c];t.idx>u.lastIdx&&(u.lastIdx>=0&&(u.prevWindow=[...u.currentWindow],u.prevCallCount=u.currentCallCount),u.lastIdx=t.idx);let h=y.from(e).get(0),p=[...u.prevWindow];for(p.unshift(h);p.length>a;)p.pop();let d=u.prevCallCount+1;if(p.length<a&&(d>=a||t.idx>=a-1)){let m=y.from(e);for(;p.length<a;)p.push(m.get(p.length))}if(u.currentWindow=p,u.currentCallCount=d,p.length<a)return NaN;let f=0;for(let m=0;m<a;m++)f+=u.weights[m]*p[a-1-m];return t.precision(f)}}function $d(t){return(e,n)=>{let r=y.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,x=Math.abs(a-c),b=Math.abs(o-c);u=Math.max(m,x,b)}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 Wd(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=y.from(e).get(0),a=i.prevLastTrueIndex;return s&&(a=t.idx),i.currentLastTrueIndex=a,a===null?NaN:t.idx-a}}function Ud(t){return(e,n,r,i)=>{let s=y.from(n).get(0),a=y.from(r).get(0);t.taState||(t.taState={});let o=i||`bb_${s}_${a}`;t.taState[o]||(t.taState[o]={lastIdx:-1,prevWindow:[],prevSum:0,currentWindow:[],currentSum:0});let l=t.taState[o];t.idx>l.lastIdx&&(l.lastIdx>=0&&(l.prevWindow=[...l.currentWindow],l.prevSum=l.currentSum),l.lastIdx=t.idx);let c=y.from(e).get(0);if(isNaN(c))return l.currentWindow=[...l.prevWindow],l.currentSum=l.prevSum,[[NaN,NaN,NaN]];let u=[...l.prevWindow],h=l.prevSum;for(u.unshift(c),h+=c;u.length>s;){let b=u.pop();h-=b}if(u.length<s&&t.idx>=s-1){let b=y.from(e);for(;u.length<s;){let w=b.get(u.length);if(isNaN(w))break;u.push(w),h+=w}}if(l.currentWindow=u,l.currentSum=h,u.length<s)return[[NaN,NaN,NaN]];let p=h/s,d=0;for(let b=0;b<s;b++)d+=Math.pow(u[b]-p,2);let f=Math.sqrt(d/s),m=p+a*f,x=p-a*f;return[[t.precision(p),t.precision(m),t.precision(x)]]}}function qd(t){return(e,n,r,i)=>{let s=y.from(n).get(0),a=y.from(r).get(0);t.taState||(t.taState={});let o=i||`bbw_${s}_${a}`;t.taState[o]||(t.taState[o]={lastIdx:-1,prevWindow:[],prevSum:0,currentWindow:[],currentSum:0});let l=t.taState[o];t.idx>l.lastIdx&&(l.lastIdx>=0&&(l.prevWindow=[...l.currentWindow],l.prevSum=l.currentSum),l.lastIdx=t.idx);let c=y.from(e).get(0);if(isNaN(c))return l.currentWindow=[...l.prevWindow],l.currentSum=l.prevSum,NaN;let u=[...l.prevWindow],h=l.prevSum;for(u.unshift(c),h+=c;u.length>s;){let w=u.pop();h-=w}if(u.length<s&&t.idx>=s-1){let w=y.from(e);for(;u.length<s;){let E=w.get(u.length);if(isNaN(E))break;u.push(E),h+=E}}if(l.currentWindow=u,l.currentSum=h,u.length<s)return NaN;let p=h/s,d=0;for(let w=0;w<s;w++){let E=u[w]-p;d+=E*E}let f=d/s,m=Math.sqrt(f),x=a*m;if(p===0)return t.precision(0);let b=2*x/p*100;return t.precision(b)}}function zd(t){return(e,n,r)=>{let i=y.from(n).get(0);t.taState||(t.taState={});let s=r||`cci_${i}`;t.taState[s]||(t.taState[s]={lastIdx:-1,prevWindow:[],prevSum:0,prevCallCount:0,currentWindow:[],currentSum:0,currentCallCount:0});let a=t.taState[s];t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevWindow=[...a.currentWindow],a.prevSum=a.currentSum,a.prevCallCount=a.currentCallCount),a.lastIdx=t.idx);let o=y.from(e).get(0);if(isNaN(o))return NaN;let l=[...a.prevWindow],c=a.prevSum;for(l.unshift(o),c+=o;l.length>i;){let m=l.pop();c-=m}let u=a.prevCallCount+1;if(l.length<i&&(u>=i||t.idx>=i-1)){let m=y.from(e);for(;l.length<i;){let x=m.get(l.length);if(isNaN(x))break;l.push(x),c+=x}}if(a.currentWindow=l,a.currentSum=c,a.currentCallCount=u,l.length<i)return NaN;let h=c/i,p=0;for(let m=0;m<i;m++)p+=Math.abs(l[m]-h);let d=p/i;if(d===0)return 0;let f=(o-h)/(.015*d);return t.precision(f)}}function Kd(t){return(e,n=1,r)=>{typeof n=="string"&&(r=n,n=1);let i=y.from(n).get(0);t.taState||(t.taState={});let s=r||`change_${i}`;t.taState[s]||(t.taState[s]={lastIdx:-1,prevWindow:[],prevCallCount:0,currentWindow:[],currentCallCount:0});let a=t.taState[s];t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevWindow=[...a.currentWindow],a.prevCallCount=a.currentCallCount),a.lastIdx=t.idx);let o=y.from(e).get(0),l=[...a.prevWindow];for(l.unshift(o);l.length>i+1;)l.pop();let c=a.prevCallCount+1;if(l.length<i+1&&(c>=i+1||t.idx>=i)){let h=y.from(e);for(;l.length<i+1;)l.push(h.get(l.length))}if(a.currentWindow=l,a.currentCallCount=c,l.length<=i)return NaN;let u=o-l[i];return t.precision(u)}}function Hd(t){return(e,n,r)=>{let i=y.from(n).get(0);t.taState||(t.taState={});let s=r||`cmo_${i}`;t.taState[s]||(t.taState[s]={lastIdx:-1,prevGainsWindow:[],prevLossesWindow:[],prevGainsSum:0,prevLossesSum:0,currentGainsWindow:[],currentLossesWindow:[],currentGainsSum:0,currentLossesSum:0});let a=t.taState[s];t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevGainsWindow=[...a.currentGainsWindow],a.prevLossesWindow=[...a.currentLossesWindow],a.prevGainsSum=a.currentGainsSum,a.prevLossesSum=a.currentLossesSum),a.lastIdx=t.idx);let o=y.from(e).get(0),l=y.from(e).get(1);if(isNaN(o)||isNaN(l))return NaN;let c=o-l,u=c>=0?c:0,h=c>=0?0:-c,p=[...a.prevGainsWindow],d=[...a.prevLossesWindow],f=a.prevGainsSum,m=a.prevLossesSum;if(p.unshift(u),d.unshift(h),f+=u,m+=h,p.length<i)return a.currentGainsWindow=p,a.currentLossesWindow=d,a.currentGainsSum=f,a.currentLossesSum=m,NaN;if(p.length>i){let w=p.pop(),E=d.pop();f-=w,m-=E}a.currentGainsWindow=p,a.currentLossesWindow=d,a.currentGainsSum=f,a.currentLossesSum=m;let x=f+m;if(x===0)return t.precision(0);let b=100*(f-m)/x;return t.precision(b)}}function Gd(t){return(e,n,r)=>{let i=y.from(n).get(0),s=y.from(e),a=0,o=!1;for(let u=0;u<i;u++){let h=s.get(u);if(isNaN(h)){o=!0;break}a+=h}if(o)return NaN;let l=0;for(let u=0;u<i;u++){let h=s.get(u);l+=h*(u+1)}if(a===0)return NaN;let c=-l/a;return t.precision(c)}}function Yd(t){return(e,n,r,i)=>{let s=y.from(r).get(0),a=y.from(e),o=y.from(n);if(t.idx<s-1)return NaN;let l=0,c=0,u=0,h=0,p=0,d=0;for(let w=0;w<s;w++){let E=a.get(w),v=o.get(w);isNaN(E)||isNaN(v)||(l+=E,c+=v,u+=E*v,h+=E*E,p+=v*v,d++)}if(d<2)return NaN;let f=d*u-l*c,m=d*h-l*l,x=d*p-c*c;if(m<=0||x<=0)return t.precision(0);let b=f/Math.sqrt(m*x);return t.precision(b)}}function Zd(t){return(e,n,r)=>{let i=y.from(e),s=y.from(n),a=i.get(0),o=s.get(0),l=i.get(1),c=s.get(1);if(isNaN(a)||isNaN(o)||isNaN(l)||isNaN(c))return!1;let u=a>o&&l<=c,h=a<o&&l>=c;return u||h}}function Xd(t){return(e,n)=>{let r=y.from(e),i=y.from(n),s=r.get(0),a=i.get(0),o=r.get(1),l=i.get(1);return o<=l&&s>a}}function Qd(t){return(e,n)=>{let r=y.from(e),i=y.from(n),s=r.get(0),a=i.get(0),o=r.get(1),l=i.get(1);return o>=l&&s<a}}function Jd(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=y.from(e).get(0);if(isNaN(s))return i.currentCumulativeSum=i.prevCumulativeSum,t.precision(i.prevCumulativeSum);let a=i.prevCumulativeSum+s;return i.currentCumulativeSum=a,t.precision(a)}}function ef(t){return(e,n,r)=>{let i=y.from(n).get(0);t.taState||(t.taState={});let s=r||`dev_${i}`;t.taState[s]||(t.taState[s]={lastIdx:-1,prevWindow:[],prevSum:0,prevCallCount:0,currentWindow:[],currentSum:0,currentCallCount:0});let a=t.taState[s];t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevWindow=[...a.currentWindow],a.prevSum=a.currentSum,a.prevCallCount=a.currentCallCount),a.lastIdx=t.idx);let o=y.from(e).get(0)||0,l=[...a.prevWindow],c=a.prevSum;for(l.unshift(o),c+=o;l.length>i;){let f=l.pop();c-=f}let u=a.prevCallCount+1;if(l.length<i&&(u>=i||t.idx>=i-1)){let f=y.from(e);for(;l.length<i;){let m=f.get(l.length);l.push(m),c+=m}}if(a.currentWindow=l,a.currentSum=c,a.currentCallCount=u,l.length<i)return NaN;let h=c/i,p=0;for(let f=0;f<i;f++)p+=Math.abs(l[f]-h);let d=p/i;return t.precision(d)}}function tf(t){return(e,n,r)=>{let i=y.from(e).get(0),s=y.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,x=p-c,b=m>x&&m>0?m:0,w=x>m&&x>0?x:0,E=o.prevInitCount,v=o.prevTrInitSum,I=o.prevPlusInitSum,C=o.prevMinusInitSum,T=o.prevSmoothedTR,O=o.prevSmoothedPlus,N=o.prevSmoothedMinus;if(E++,E<=i)v+=f,I+=b,C+=w,E===i&&(T=v/i,O=I/i,N=C/i);else{let ae=1/i;T=ae*f+(1-ae)*T,O=ae*b+(1-ae)*O,N=ae*w+(1-ae)*N}if(o.currentInitCount=E,o.currentTrInitSum=v,o.currentPlusInitSum=I,o.currentMinusInitSum=C,o.currentSmoothedTR=T,o.currentSmoothedPlus=O,o.currentSmoothedMinus=N,E<i)return[[NaN,NaN,NaN]];let j=T===0?0:100*O/T,D=T===0?0:100*N/T,W=j+D,R=W===0?0:100*Math.abs(j-D)/W,P=o.prevAdxInitCount,H=o.prevDxInitSum,te=o.prevADX,ve=NaN;if(P++,P<=s)H+=R,P===s&&(te=H/s,ve=te);else{let ae=1/s;te=ae*R+(1-ae)*te,ve=te}return o.currentAdxInitCount=P,o.currentDxInitSum=H,o.currentADX=te,[[t.precision(j),t.precision(D),t.precision(ve)]]}}function nf(t){return(e,n,r)=>{let i=y.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=y.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 rf(t){return(e,n,r)=>{let i=y.from(n).get(0),s=y.from(e);for(let a=0;a<i;a++){let o=s.get(a),l=s.get(a+1);if(isNaN(o)||isNaN(l)||o>=l)return!1}return!0}}function sf(t){return(e,n,r)=>{typeof n=="string"&&r===void 0&&(r=n,n=e,e=t.data.high);let i=y.from(n).get(0);t.taState||(t.taState={});let s=r||`highest_${i}`;t.taState[s]||(t.taState[s]={lastIdx:-1,prevWindow:[],prevCallCount:0,currentWindow:[],currentCallCount:0});let a=t.taState[s];t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevWindow=[...a.currentWindow],a.prevCallCount=a.currentCallCount),a.lastIdx=t.idx);let o=y.from(e).get(0),l=[...a.prevWindow];for(l.unshift(o);l.length>i;)l.pop();let c=a.prevCallCount+1;if(l.length<i&&(c>=i||t.idx>=i-1)){let p=y.from(e);for(;l.length<i;)l.push(p.get(l.length))}if(a.currentWindow=l,a.currentCallCount=c,l.length<i)return NaN;let u=l.filter(p=>!isNaN(p)&&p!==void 0);if(u.length===0)return NaN;let h=Math.max(...u);return t.precision(h)}}function af(t){return(e,n,r)=>{let i=y.from(n).get(0),s=y.from(e);if(t.idx<i-1)return NaN;let a=-1/0,o=NaN;for(let l=0;l<i;l++){let c=s.get(l);isNaN(c)||(isNaN(o)||c>a)&&(a=c,o=-l)}return o}}function of(t){return(e,n,r)=>{let i=y.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);if(isNaN(l)||isNaN(c))return NaN;t.taState||(t.taState={});let u=r||`hma_raw_${i}`;t.taState[u]||(t.taState[u]={lastIdx:-1,prevValues:[],currentValues:[]});let h=t.taState[u];t.idx>h.lastIdx&&(h.lastIdx>=0&&(h.prevValues=[...h.currentValues]),h.lastIdx=t.idx);let p=2*l-c,d=[...h.prevValues];d.unshift(p),d.length>a+1&&d.pop(),h.currentValues=d;let f=r?`${r}_hma_final`:`hma_final_${i}`;t.taState[f]||(t.taState[f]={lastIdx:-1,prevWindow:[],currentWindow:[]});let m=t.taState[f];t.idx>m.lastIdx&&(m.lastIdx>=0&&(m.prevWindow=[...m.currentWindow]),m.lastIdx=t.idx);let x=[...m.prevWindow];if(x.unshift(p),x.length<a)return m.currentWindow=x,NaN;for(;x.length>a;)x.pop();m.currentWindow=x;let b=0,w=0;for(let v=0;v<a;v++){let I=a-v;b+=x[v]*I,w+=I}let E=b/w;return t.precision(E)}}function lf(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)*s;if(a===0)return t.precision(0);let o=(2*n-r-i)/a;return t.precision(o)}}function cf(t){return(e,n,r,i,s)=>{let a=y.from(n).get(0),o=y.from(r).get(0),l=!0;typeof i=="string"?s=i:i!==void 0&&(l=y.from(i).get(0));let c,u=t.get(t.data.high,0),h=t.get(t.data.low,0);if(l){let v=t.get(t.data.close,1);isNaN(v)?c=NaN:c=Math.max(u-h,Math.abs(u-v),Math.abs(h-v))}else c=u-h;let p=y.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=(v,I,C,T)=>{if(isNaN(C))return Object.assign(I,v),I.prevEma!==null?I.prevEma:NaN;let O=v.initCount,N=v.initSum,j=v.prevEma;if(O<T){if(N+=C,O++,I.initSum=N,I.initCount=O,I.prevEma=j,O===T){let R=N/T;return I.prevEma=R,R}return NaN}let D=2/(T+1),W=C*D+j*(1-D);return I.prevEma=W,I.initSum=N,I.initCount=O,W},x=m(f.basisState,f.currentBasisState,p,a),b=m(f.rangeState,f.currentRangeState,c,a);if(isNaN(x)||isNaN(b))return[[NaN,NaN,NaN]];let w=x+b*o,E=x-b*o;return[[t.precision(x),t.precision(w),t.precision(E)]]}}function uf(t){return(e,n,r,i,s)=>{let a=y.from(n).get(0),o=y.from(r).get(0),l=!0;typeof i=="string"?s=i:i!==void 0&&(l=y.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=(E,v,I,C)=>{if(isNaN(I))return Object.assign(v,E),v.prevEma!==null?v.prevEma:NaN;let T=E.initCount,O=E.initSum,N=E.prevEma;if(T<C){if(O+=I,T++,v.initSum=O,v.initCount=T,v.prevEma=N,T===C){let W=O/C;return v.prevEma=W,W}return NaN}let j=2/(C+1),D=I*j+N*(1-j);return v.prevEma=D,v.initSum=O,v.initCount=T,D},p,d=t.get(t.data.high,0),f=t.get(t.data.low,0);if(l){let E=t.get(t.data.close,1);isNaN(E)?p=NaN:p=Math.max(d-f,Math.abs(d-E),Math.abs(f-E))}else p=d-f;let m=y.from(e).get(0),x=h(u.basisState,u.currentBasisState,m,a),b=h(u.rangeState,u.currentRangeState,p,a);if(isNaN(x)||isNaN(b))return NaN;if(x===0)return t.precision(0);let w=2*b*o/x;return t.precision(w)}}function pf(t){return(e,n,r,i)=>{let s=y.from(n).get(0),a=y.from(r).get(0);t.taState||(t.taState={});let o=i||`linreg_${s}_${a}`;t.taState[o]||(t.taState[o]={lastIdx:-1,prevWindow:[],prevCallCount:0,currentWindow:[],currentCallCount:0});let l=t.taState[o];t.idx>l.lastIdx&&(l.lastIdx>=0&&(l.prevWindow=[...l.currentWindow],l.prevCallCount=l.currentCallCount),l.lastIdx=t.idx);let c=y.from(e).get(0),u=[...l.prevWindow];for(u.unshift(c);u.length>s;)u.pop();let h=l.prevCallCount+1;if(u.length<s&&(h>=s||t.idx>=s-1)){let v=y.from(e);for(;u.length<s;)u.push(v.get(u.length))}if(l.currentWindow=u,l.currentCallCount=h,u.length<s)return NaN;let p=0,d=0,f=0,m=0,x=s;for(let v=0;v<s;v++){let I=s-1-v,C=u[v];p+=I,d+=C,f+=I*C,m+=I*I}let b=x*m-p*p;if(b===0)return NaN;let w=(x*f-p*d)/b,E=(d-w*p)/x+w*(s-1-a);return t.precision(E)}}function hf(t){return(e,n,r)=>{typeof n=="string"&&r===void 0&&(r=n,n=e,e=t.data.low);let i=y.from(n).get(0);t.taState||(t.taState={});let s=r||`lowest_${i}`;t.taState[s]||(t.taState[s]={lastIdx:-1,prevWindow:[],prevCallCount:0,currentWindow:[],currentCallCount:0});let a=t.taState[s];t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevWindow=[...a.currentWindow],a.prevCallCount=a.currentCallCount),a.lastIdx=t.idx);let o=y.from(e).get(0),l=[...a.prevWindow];for(l.unshift(o);l.length>i;)l.pop();let c=a.prevCallCount+1;if(l.length<i&&(c>=i||t.idx>=i-1)){let p=y.from(e);for(;l.length<i;)l.push(p.get(l.length))}if(a.currentWindow=l,a.currentCallCount=c,l.length<i)return NaN;let u=l.filter(p=>!isNaN(p)&&p!==void 0);if(u.length===0)return NaN;let h=Math.min(...u);return t.precision(h)}}function df(t){return(e,n,r)=>{let i=y.from(n).get(0),s=y.from(e);if(t.idx<i-1)return NaN;let a=1/0,o=NaN;for(let l=0;l<i;l++){let c=s.get(l);isNaN(c)||(isNaN(o)||c<a)&&(a=c,o=-l)}return o}}function ff(t){return(e,n,r,i,s)=>{let a=y.from(n).get(0),o=y.from(r).get(0),l=y.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 x=NaN;isNaN(m)||(x=t.pine.ta.ema(m,l,p));let b=NaN;return!isNaN(m)&&!isNaN(x)&&(b=m-x),[[t.precision(m),t.precision(x),t.precision(b)]]}}function mf(t){return(e,n,r)=>{let i=y.from(n).get(0);t.taState||(t.taState={});let s=r||`median_${i}`;t.taState[s]||(t.taState[s]={lastIdx:-1,prevWindow:[],prevCallCount:0,currentWindow:[],currentCallCount:0});let a=t.taState[s];t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevWindow=[...a.currentWindow],a.prevCallCount=a.currentCallCount),a.lastIdx=t.idx);let o=y.from(e).get(0),l=[...a.prevWindow];for(l.unshift(o);l.length>i;)l.pop();let c=a.prevCallCount+1;if(l.length<i&&(c>=i||t.idx>=i-1)){let d=y.from(e);for(;l.length<i;)l.push(d.get(l.length))}if(a.currentWindow=l,a.currentCallCount=c,l.length<i)return NaN;let u=l.slice().sort((d,f)=>d-f),h=Math.floor(i/2),p=i%2===0?(u[h-1]+u[h])/2:u[h];return t.precision(p)}}function yf(t){return(e,n,r)=>{let i=y.from(n).get(0);t.taState||(t.taState={});let s=r||`mfi_${i}`;t.taState[s]||(t.taState[s]={lastIdx:-1,prevUpperWindow:[],prevLowerWindow:[],prevUpperSum:0,prevLowerSum:0,currentUpperWindow:[],currentLowerWindow:[],currentUpperSum:0,currentLowerSum:0});let a=t.taState[s];t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevUpperWindow=[...a.currentUpperWindow],a.prevLowerWindow=[...a.currentLowerWindow],a.prevUpperSum=a.currentUpperSum,a.prevLowerSum=a.currentLowerSum),a.lastIdx=t.idx);let o=y.from(e).get(0),l=y.from(e).get(1),c=t.get(t.data.volume,0);if(isNaN(o)||isNaN(c))return NaN;let u=isNaN(l)?NaN:o-l,h=c*(u<=0?0:o),p=c*(u>=0?0:o),d=[...a.prevUpperWindow],f=[...a.prevLowerWindow],m=a.prevUpperSum,x=a.prevLowerSum;if(d.unshift(h),f.unshift(p),m+=h,x+=p,d.length<i)return a.currentUpperWindow=d,a.currentLowerWindow=f,a.currentUpperSum=m,a.currentLowerSum=x,NaN;if(d.length>i){let w=d.pop(),E=f.pop();m-=w,x-=E}if(a.currentUpperWindow=d,a.currentLowerWindow=f,a.currentUpperSum=m,a.currentLowerSum=x,x===0)return t.precision(100);if(m===0)return t.precision(0);let b=100-100/(1+m/x);return t.precision(b)}}function gf(t){return(e,n,r)=>{let i=y.from(n).get(0),s=y.from(e);if(t.idx<i-1)return NaN;let a=new Map;for(let c=0;c<i;c++){let u=s.get(c);isNaN(u)||a.set(u,(a.get(u)||0)+1)}if(a.size===0)return NaN;let o=NaN,l=-1;for(let[c,u]of a.entries())u>l?(l=u,o=c):u===l&&c<o&&(o=c);return o}}function _f(t){return(e,n,r)=>{let i=y.from(n).get(0);return t.pine.ta.change(e,i,r)}}function xf(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 bf(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 wf(t){return(e,n,r)=>e instanceof y?n?new y(e.data,e.offset+n):e:(t.params[r]||(t.params[r]=[]),Array.isArray(e)?new y(e,n||0):(t.params[r].length===0?t.params[r].push(e):t.params[r][t.params[r].length-1]=e,new y(t.params[r],n||0)))}function vf(t){return(e,n,r,i)=>{let s=y.from(n).get(0),a=y.from(r).get(0),o=y.from(e);if(t.idx<s-1)return NaN;let l=[];for(let f=0;f<s;f++){let m=o.get(f);if(isNaN(m))return NaN;l.push(m)}l.sort((f,m)=>f-m);let c=a/100*s-.5;c<0&&(c=0),c>s-1&&(c=s-1);let u=Math.floor(c),h=Math.ceil(c);if(u===h)return t.precision(l[u]);let p=c-u,d=l[u]+p*(l[h]-l[u]);return t.precision(d)}}function Ef(t){return(e,n,r,i)=>{let s=y.from(n).get(0),a=y.from(r).get(0),o=y.from(e);if(t.idx<s-1)return NaN;let l=[];for(let u=0;u<s;u++){let h=o.get(u);isNaN(h)||l.push(h)}if(l.length===0)return NaN;l.sort((u,h)=>u-h);let c=Math.ceil(a/100*l.length)-1;return c<0&&(c=0),c>=l.length&&(c=l.length-1),t.precision(l[c])}}function Sf(t){return(e,n,r)=>{let i=y.from(n).get(0),s=y.from(e);if(t.idx<i)return NaN;let a=s.get(0);if(isNaN(a))return NaN;let o=0,l=0;for(let c=1;c<=i;c++){let u=s.get(c);isNaN(u)||(l++,u<=a&&o++)}return l===0?NaN:t.precision(o/l*100)}}function Cf(t,e,n){let r=new Array(t.length).fill(NaN);for(let i=e+n;i<t.length;i++){let s=t[i-n],a=!0;for(let o=1;o<=e;o++)if(t[i-n-o]>=s){a=!1;break}if(a){for(let o=1;o<=n;o++)if(t[i-n+o]>=s){a=!1;break}}a&&(r[i]=s)}return r}function Nf(t){return(e,n,r,i)=>{typeof r=="string"&&(r=n,n=e,e=t.data.high);let s=y.from(n).get(0),a=y.from(r).get(0),o=y.from(e).toArray(),l=Cf(o,s,a),c=t.idx;return t.precision(l[c])}}function kf(t,e,n){let r=new Array(t.length).fill(NaN);for(let i=e+n;i<t.length;i++){let s=t[i-n],a=!0;for(let o=1;o<=e;o++)if(t[i-n-o]<=s){a=!1;break}if(a){for(let o=1;o<=n;o++)if(t[i-n+o]<=s){a=!1;break}}a&&(r[i]=s)}return r}function If(t){return(e,n,r,i)=>{typeof r=="string"&&(r=n,n=e,e=t.data.low);let s=y.from(n).get(0),a=y.from(r).get(0),o=y.from(e).toArray(),l=kf(o,s,a),c=t.idx;return t.precision(l[c])}}function Af(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 Tf(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 Df(t){return(e,n,r)=>{let i=t.pine.ta.highest(e,n,(r||"range")+"_h"),s=t.pine.ta.lowest(e,n,(r||"range")+"_l");return isNaN(i)||isNaN(s)?NaN:t.precision(i-s)}}function Mf(t){return(e,n,r)=>{let i=y.from(n).get(0),s=y.from(e);for(let a=0;a<i;a++){let o=s.get(a),l=s.get(a+1);if(isNaN(o)||isNaN(l)||o<=l)return!1}return!0}}function Pf(t){return(e,n,r)=>{let i=y.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=y.from(e).get(0)||0,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 Rf(t){return(e,n,r)=>{let i=y.from(n).get(0);t.taState||(t.taState={});let s=r||`roc_${i}`;t.taState[s]||(t.taState[s]={lastIdx:-1,prevWindow:[],prevCallCount:0,currentWindow:[],currentCallCount:0});let a=t.taState[s];t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevWindow=[...a.currentWindow],a.prevCallCount=a.currentCallCount),a.lastIdx=t.idx);let o=y.from(e).get(0),l=[...a.prevWindow];for(l.unshift(o);l.length>i+1;)l.pop();let c=a.prevCallCount+1;if(l.length<i+1&&(c>=i+1||t.idx>=i)){let p=y.from(e);for(;l.length<i+1;)l.push(p.get(l.length))}if(a.currentWindow=l,a.currentCallCount=c,l.length<=i)return NaN;let u=l[i],h=(o-u)/u*100;return t.precision(h)}}function Ff(t){return(e,n,r)=>{let i=y.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,prevInitGains:[],prevInitLosses:[],currentPrevValue:null,currentAvgGain:0,currentAvgLoss:0,currentInitGains:[],currentInitLosses:[]});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.prevInitGains=[...a.currentInitGains],a.prevInitLosses=[...a.currentInitLosses]),a.lastIdx=t.idx);let o=y.from(e).get(0);if(o==null||isNaN(o))return NaN;let l=a.prevPrevValue;if(l===null||isNaN(l))return a.currentPrevValue=o,a.currentInitGains=[...a.prevInitGains],a.currentInitLosses=[...a.prevInitLosses],a.currentAvgGain=a.prevAvgGain,a.currentAvgLoss=a.prevAvgLoss,NaN;let c=a.prevAvgGain,u=a.prevAvgLoss,h=[...a.prevInitGains],p=[...a.prevInitLosses],d=o-l,f=d>0?d:0,m=d<0?-d:0;if(h.length<i){if(h.push(f),p.push(m),a.currentInitGains=h,a.currentInitLosses=p,a.currentPrevValue=o,h.length===i){c=h.reduce((w,E)=>w+E,0)/i,u=p.reduce((w,E)=>w+E,0)/i,a.currentAvgGain=c,a.currentAvgLoss=u;let b=u===0?100:100-100/(1+c/u);return t.precision(b)}return NaN}c=(c*(i-1)+f)/i,u=(u*(i-1)+m)/i,a.currentAvgGain=c,a.currentAvgLoss=u,a.currentPrevValue=o;let x=u===0?100:100-100/(1+c/u);return t.precision(x)}}function Bf(t){return(e,n,r,i)=>{let s=y.from(e).get(0),a=y.from(n).get(0),o=y.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),x=t.get(t.data.low,0),b=t.get(t.data.close,0),w=t.get(t.data.close,1),E=t.get(t.data.high,1),v=t.get(t.data.low,1),I=t.get(t.data.high,2),C=t.get(t.data.low,2);if(isNaN(m)||isNaN(x)||isNaN(b))return c.currentResult=u,c.currentMaxMin=h,c.currentAcceleration=p,c.currentIsBelow=d,c.currentBarIndex=f,NaN;let T=!1;return f===1&&(b>w?(d=!0,h=m,u=v):(d=!1,h=x,u=E),T=!0,p=s),f>=1&&(u=u+p*(h-u),d?u>x&&(T=!0,d=!1,u=Math.max(m,h),h=x,p=s):u<m&&(T=!0,d=!0,u=Math.min(x,h),h=m,p=s),T||(d?m>h&&(h=m,p=Math.min(p+a,o)):x<h&&(h=x,p=Math.min(p+a,o))),d?(u=Math.min(u,v),f>1&&(u=Math.min(u,C))):(u=Math.max(u,E),f>1&&(u=Math.max(u,I)))),f++,c.currentResult=u,c.currentMaxMin=h,c.currentAcceleration=p,c.currentIsBelow=d,c.currentBarIndex=f,f<=1?NaN:t.precision(u)}}function Lf(t){return(e,n,r)=>{let i=y.from(n).get(0);t.taState||(t.taState={});let s=r||`sma_${i}`;t.taState[s]||(t.taState[s]={lastIdx:-1,prevWindow:[],prevSum:0,prevCallCount:0,currentWindow:[],currentSum:0,currentCallCount:0});let a=t.taState[s];t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevWindow=[...a.currentWindow],a.prevSum=a.currentSum,a.prevCallCount=a.currentCallCount),a.lastIdx=t.idx);let o=y.from(e).get(0),l=[...a.prevWindow];for(l.unshift(o);l.length>i;)l.pop();let c=a.prevCallCount+1,u=!1;if(l.length<i&&(c>=i||t.idx>=i-1)){let m=y.from(e);for(;l.length<i;)l.push(m.get(l.length));u=!0}let h,p=o==null||Number.isNaN(o),d=!Number.isNaN(a.prevSum)&&!p&&!u;if(d){let m=a.prevSum+o;if(a.prevWindow.length>=i){let x=a.prevWindow[a.prevWindow.length-1];x==null||Number.isNaN(x)?d=!1:m-=x}d&&(h=m)}if(!d){h=0;let m=!1;for(let x of l){if(x==null||Number.isNaN(x)){m=!0;break}h+=x}m&&(h=NaN)}if(a.currentWindow=l,a.currentSum=h,a.currentCallCount=c,l.length<i)return NaN;let f=h/i;return t.precision(f)}}function Of(t){return(e,n,r=!0,i)=>{let s=y.from(n).get(0),a=y.from(r).get(0);t.taState||(t.taState={});let o=i||`stdev_${s}_${a}`;t.taState[o]||(t.taState[o]={lastIdx:-1,prevWindow:[],prevSum:0,prevCallCount:0,currentWindow:[],currentSum:0,currentCallCount:0});let l=t.taState[o];t.idx>l.lastIdx&&(l.lastIdx>=0&&(l.prevWindow=[...l.currentWindow],l.prevSum=l.currentSum,l.prevCallCount=l.currentCallCount),l.lastIdx=t.idx);let c=y.from(e).get(0);if(c==null||isNaN(c))return NaN;let u=[...l.prevWindow],h=l.prevSum;for(u.unshift(c),h+=c;u.length>s;){let b=u.pop();h-=b}let p=l.prevCallCount+1;if(u.length<s&&(p>=s||t.idx>=s-1)){let b=y.from(e);for(;u.length<s;){let w=b.get(u.length);if(w==null||isNaN(w))break;u.push(w),h+=w}}if(l.currentWindow=u,l.currentSum=h,l.currentCallCount=p,u.length<s)return NaN;let d=h/s,f=0;for(let b=0;b<s;b++)f+=Math.pow(u[b]-d,2);let m=a?s:s-1,x=Math.sqrt(f/m);return t.precision(x)}}function Vf(t){return(e,n,r,i,s)=>{let a=y.from(i).get(0);t.taState||(t.taState={});let o=s||`stoch_${a}`;t.taState[o]||(t.taState[o]={lastIdx:-1,prevHighWindow:[],prevLowWindow:[],currentHighWindow:[],currentLowWindow:[]});let l=t.taState[o];t.idx>l.lastIdx&&(l.lastIdx>=0&&(l.prevHighWindow=[...l.currentHighWindow],l.prevLowWindow=[...l.currentLowWindow]),l.lastIdx=t.idx);let c=y.from(e).get(0),u=y.from(n).get(0),h=y.from(r).get(0);if(isNaN(c)||isNaN(u)||isNaN(h))return l.currentHighWindow=[...l.prevHighWindow],l.currentLowWindow=[...l.prevLowWindow],NaN;let p=[...l.prevHighWindow],d=[...l.prevLowWindow];if(p.unshift(u),d.unshift(h),p.length>a&&(p.pop(),d.pop()),l.currentHighWindow=p,l.currentLowWindow=d,p.length<a)return NaN;let f=p[0],m=d[0];for(let w=1;w<a;w++)p[w]>f&&(f=p[w]),d[w]<m&&(m=d[w]);let x=f-m;if(x===0)return NaN;let b=100*(c-m)/x;return t.precision(b)}}function jf(t){return(e,n,r)=>{let i=y.from(e).get(0),s=y.from(n).get(0);t.taState||(t.taState={});let a=r||`supertrend_${i}_${s}`;t.taState[a]||(t.taState[a]={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 o=t.taState[a];t.idx>o.lastIdx&&(o.lastIdx>=0&&(o.prevTrSum=o.currentTrSum,o.prevAtrValue=o.currentAtrValue,o.prevAtrCount=o.currentAtrCount,o.prevLowerBand=o.currentLowerBand,o.prevUpperBand=o.currentUpperBand,o.prevSuperTrend=o.currentSuperTrend,o.prevDirection=o.currentDirection),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]];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=o.prevAtrCount,m=o.prevTrSum,x=o.prevAtrValue;f++,f<=s?(m+=d,f===s&&(x=m/s)):x=(x*(s-1)+d)/s;let b=x;if(o.currentAtrCount=f,o.currentTrSum=m,o.currentAtrValue=x,isNaN(b))return[[NaN,NaN]];let w=h+i*b,E=h-i*b,v=isNaN(o.prevLowerBand)?0:o.prevLowerBand,I=isNaN(o.prevUpperBand)?0:o.prevUpperBand;isNaN(o.prevLowerBand)||E>v||p<v||(E=v),isNaN(o.prevUpperBand)||w<I||p>I||(w=I);let C,T,O=o.prevSuperTrend;return f===s?C=1:O===o.prevUpperBand?C=u>w?-1:1:C=u<E?1:-1,T=C===-1?E:w,o.currentLowerBand=E,o.currentUpperBand=w,o.currentSuperTrend=T,o.currentDirection=C,[[t.precision(T),C]]}}function $f(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]={lastIdx:-1,prevWindow:[],currentWindow:[]});let a=t.taState[s];t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevWindow=[...a.currentWindow]),a.lastIdx=t.idx);let o=y.from(e).get(0),l=[...a.prevWindow];for(l.unshift(o);l.length>4;)l.pop();if(l.length<4&&t.idx>=3){let u=y.from(e);for(;l.length<4;)l.push(u.get(l.length))}if(a.currentWindow=l,l.length<4)return NaN;let c=0;for(let u=0;u<4;u++)c+=r[u]*l[3-u];return c/=i,t.precision(c)}}function Wf(t){return(e,n)=>{let r=!0;typeof e=="string"||e!==void 0&&(r=y.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 Uf(t){return(e,n,r,i)=>{let s=y.from(n).get(0),a=y.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=y.from(e).get(0);if(isNaN(c))return 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),x=l.prevEma1PcCount,b=l.prevEma1PcSum,w=l.prevEma1PcValue;x++,x<=a?(b+=u,x===a&&(w=b/a)):w=u*p+w*(1-p);let E=l.prevEma1AbsCount,v=l.prevEma1AbsSum,I=l.prevEma1AbsValue;if(E++,E<=a?(v+=h,E===a&&(I=v/a)):I=h*f+I*(1-f),isNaN(w)||isNaN(I))return l.currentEma1PcCount=x,l.currentEma1PcSum=b,l.currentEma1PcValue=w,l.currentEma1AbsCount=E,l.currentEma1AbsSum=v,l.currentEma1AbsValue=I,NaN;let C=l.prevEma2PcCount,T=l.prevEma2PcSum,O=l.prevEma2PcValue;C++,C<=s?(T+=w,C===s&&(O=T/s)):O=w*d+O*(1-d);let N=l.prevEma2AbsCount,j=l.prevEma2AbsSum,D=l.prevEma2AbsValue;if(N++,N<=s?(j+=I,N===s&&(D=j/s)):D=I*m+D*(1-m),l.currentEma1PcCount=x,l.currentEma1PcSum=b,l.currentEma1PcValue=w,l.currentEma1AbsCount=E,l.currentEma1AbsSum=v,l.currentEma1AbsValue=I,l.currentEma2PcCount=C,l.currentEma2PcSum=T,l.currentEma2PcValue=O,l.currentEma2AbsCount=N,l.currentEma2AbsSum=j,l.currentEma2AbsValue=D,isNaN(O)||isNaN(D))return NaN;if(D===0)return t.precision(0);let W=O/D;return t.precision(W)}}function qf(t){return(e,n,r,i)=>{t.taState||(t.taState={});let s=i||"valuewhen";t.taState[s]||(t.taState[s]={lastIdx:-1,prevValues:[],currentValues:[]});let a=t.taState[s];t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevValues=[...a.currentValues]),a.lastIdx=t.idx);let o=y.from(e).get(0),l=y.from(n).get(0),c=y.from(r).get(0),u=[...a.prevValues];if(o&&u.push(l),a.currentValues=u,isNaN(c)||c<0)return NaN;let h=u.length-1-c;if(h<0)return NaN;let p=u[h];return typeof p=="number"?t.precision(p):p}}function zf(t){return(e,n,r)=>{let i=y.from(n).get(0);t.taState||(t.taState={});let s=r||`variance_${i}`;t.taState[s]||(t.taState[s]={lastIdx:-1,prevWindow:[],prevCallCount:0,currentWindow:[],currentCallCount:0});let a=t.taState[s];t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevWindow=[...a.currentWindow],a.prevCallCount=a.currentCallCount),a.lastIdx=t.idx);let o=y.from(e).get(0),l=[...a.prevWindow];for(l.unshift(o);l.length>i;)l.pop();let c=a.prevCallCount+1;if(l.length<i&&(c>=i||t.idx>=i-1)){let f=y.from(e);for(;l.length<i;)l.push(f.get(l.length))}if(a.currentWindow=l,a.currentCallCount=c,l.length<i)return NaN;let u=0,h=0;for(let f=0;f<i;f++)u+=l[f],h+=l[f]*l[f];let p=u/i,d=h/i-p*p;return t.precision(d)}}function Kf(t){return(e,n)=>{t.taState||(t.taState={});let r=n||"vwap";t.taState[r]||(t.taState[r]={lastIdx:-1,prevCumulativePV:0,prevCumulativeVolume:0,prevLastSessionDate:null,currentCumulativePV:0,currentCumulativeVolume:0,currentLastSessionDate:null});let i=t.taState[r];t.idx>i.lastIdx&&(i.lastIdx>=0&&(i.prevCumulativePV=i.currentCumulativePV,i.prevCumulativeVolume=i.currentCumulativeVolume,i.prevLastSessionDate=i.currentLastSessionDate),i.lastIdx=t.idx);let s=y.from(e).get(0),a=y.from(t.data.volume).get(0),o=y.from(t.data.openTime).get(0),l=t.pine?.syminfo?.timezone||"UTC",c=jt(o,l),u=`${c.year}-${String(c.month).padStart(2,"0")}-${String(c.day).padStart(2,"0")}`,h=i.prevCumulativePV,p=i.prevCumulativeVolume,d=i.prevLastSessionDate;if(d!==u&&(h=0,p=0,d=u),h+=s*a,p+=a,i.currentCumulativePV=h,i.currentCumulativeVolume=p,i.currentLastSessionDate=d,p===0)return NaN;let f=h/p;return t.precision(f)}}function Hf(t){return(e,n,r)=>{let i=y.from(n).get(0);t.taState||(t.taState={});let s=r||`vwma_${i}`;t.taState[s]||(t.taState[s]={lastIdx:-1,prevWindow:[],prevVolumeWindow:[],currentWindow:[],currentVolumeWindow:[]});let a=t.taState[s];t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevWindow=[...a.currentWindow],a.prevVolumeWindow=[...a.currentVolumeWindow]),a.lastIdx=t.idx);let o=y.from(e).get(0),l=t.get(t.data.volume,0),c=[...a.prevWindow],u=[...a.prevVolumeWindow];for(c.unshift(o),u.unshift(l);c.length>i;)c.pop(),u.pop();if(c.length<i&&t.idx>=i-1){let f=y.from(e),m=y.from(t.data.volume);for(;c.length<i;)c.push(f.get(c.length)),u.push(m.get(u.length))}if(a.currentWindow=c,a.currentVolumeWindow=u,c.length<i)return NaN;let h=0,p=0;for(let f=0;f<i;f++)h+=c[f]*u[f],p+=u[f];let d=h/p;return t.precision(d)}}function Gf(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)}}function Yf(t){return(e,n,r)=>{let i=y.from(n).get(0);t.taState||(t.taState={});let s=r||`wma_${i}`;t.taState[s]||(t.taState[s]={lastIdx:-1,prevWindow:[],prevCallCount:0,currentWindow:[],currentCallCount:0});let a=t.taState[s];t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevWindow=[...a.currentWindow],a.prevCallCount=a.currentCallCount),a.lastIdx=t.idx);let o=y.from(e).get(0),l=[...a.prevWindow];for(l.unshift(o);l.length>i;)l.pop();let c=a.prevCallCount+1;if(l.length<i&&(c>=i||t.idx>=i-1)){let d=y.from(e);for(;l.length<i;)l.push(d.get(l.length))}if(a.currentWindow=l,a.currentCallCount=c,l.length<i)return NaN;let u=0,h=0;for(let d=0;d<i;d++){let f=i-d;u+=l[d]*f,h+=f}let p=u/h;return t.precision(p)}}function Zf(t){return(e,n)=>{let r=y.from(e).get(0);t.taState||(t.taState={});let i=n||`wpr_${r}`;t.taState[i]||(t.taState[i]={lastIdx:-1,prevHighWindow:[],prevLowWindow:[],currentHighWindow:[],currentLowWindow:[]});let s=t.taState[i];t.idx>s.lastIdx&&(s.lastIdx>=0&&(s.prevHighWindow=[...s.currentHighWindow],s.prevLowWindow=[...s.currentLowWindow]),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 s.currentHighWindow=[...s.prevHighWindow],s.currentLowWindow=[...s.prevLowWindow],NaN;let c=[...s.prevHighWindow],u=[...s.prevLowWindow];if(c.unshift(a),u.unshift(o),c.length>r&&(c.pop(),u.pop()),s.currentHighWindow=c,s.currentLowWindow=u,c.length<r)return NaN;let h=c[0],p=u[0];for(let m=1;m<r;m++)c[m]>h&&(h=c[m]),u[m]<p&&(p=u[m]);let d=h-p;if(d===0)return t.precision(0);let f=(h-l)/d*-100;return t.precision(f)}}function Xf(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 Qf=Object.defineProperty,Jf=(t,e,n)=>e in t?Qf(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,F=(t,e,n)=>Jf(t,typeof e!="symbol"?e+"":e,n),em={accdist:Vd,alma:jd,atr:$d,barssince:Wd,bb:Ud,bbw:qd,cci:zd,change:Kd,cmo:Hd,cog:Gd,correlation:Yd,cross:Zd,crossover:Xd,crossunder:Qd,cum:Jd,dev:ef,dmi:tf,ema:nf,falling:rf,highest:sf,highestbars:af,hma:of,iii:lf,kc:cf,kcw:uf,linreg:pf,lowest:hf,lowestbars:df,macd:ff,median:mf,mfi:yf,mode:gf,mom:_f,nvi:xf,obv:bf,param:wf,percentile_linear_interpolation:vf,percentile_nearest_rank:Ef,percentrank:Sf,pivothigh:Nf,pivotlow:If,pvi:Af,pvt:Tf,range:Df,rising:Mf,rma:Pf,roc:Rf,rsi:Ff,sar:Bf,sma:Lf,stdev:Of,stoch:Vf,supertrend:jf,swma:$f,tr:Wf,tsi:Uf,valuewhen:qf,variance:zf,vwap:Kf,vwma:Hf,wad:Gf,wma:Yf,wpr:Zf,wvad:Xf},Pi=class{constructor(e){this.context=e,F(this,"accdist"),F(this,"alma"),F(this,"atr"),F(this,"barssince"),F(this,"bb"),F(this,"bbw"),F(this,"cci"),F(this,"change"),F(this,"cmo"),F(this,"cog"),F(this,"correlation"),F(this,"cross"),F(this,"crossover"),F(this,"crossunder"),F(this,"cum"),F(this,"dev"),F(this,"dmi"),F(this,"ema"),F(this,"falling"),F(this,"highest"),F(this,"highestbars"),F(this,"hma"),F(this,"iii"),F(this,"kc"),F(this,"kcw"),F(this,"linreg"),F(this,"lowest"),F(this,"lowestbars"),F(this,"macd"),F(this,"median"),F(this,"mfi"),F(this,"mode"),F(this,"mom"),F(this,"nvi"),F(this,"obv"),F(this,"param"),F(this,"percentile_linear_interpolation"),F(this,"percentile_nearest_rank"),F(this,"percentrank"),F(this,"pivothigh"),F(this,"pivotlow"),F(this,"pvi"),F(this,"pvt"),F(this,"range"),F(this,"rising"),F(this,"rma"),F(this,"roc"),F(this,"rsi"),F(this,"sar"),F(this,"sma"),F(this,"stdev"),F(this,"stoch"),F(this,"supertrend"),F(this,"swma"),F(this,"tr"),F(this,"tsi"),F(this,"valuewhen"),F(this,"variance"),F(this,"vwap"),F(this,"vwma"),F(this,"wad"),F(this,"wma"),F(this,"wpr"),F(this,"wvad"),Object.entries(em).forEach(([n,r])=>{this[n]=r(e)})}};function tm(t){if(t.length===0)return{};if(typeof t[0]=="object"&&t[0]!==null)return t[0];let e={};typeof t[0]=="string"&&(e.title=t[0]);let n=null;for(let r=1;r<t.length;r++){let i=t[r];typeof i=="string"?e.shorttitle===void 0&&(e.shorttitle=i):typeof i=="object"&&i!==null&&(n=i)}return n&&Object.assign(e,n),e}function In(t,e,n){if(!n||n<=0||!Number.isFinite(t)||t===e)return t;let r=t/n,i=1e-9;return t>e?Math.ceil(r-i)*n:Math.floor(r+i)*n}function xr(t,e,n,r){return Math.abs(t)*e*r*n/100}function nm(t,e){let n=t.strategy,r=t.pine?.syminfo?.pointvalue??1,i=0;for(let s of zr(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 rm(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+=xr(s.size,e,a,r)}return i}function ws(t,e,n,r){let i=t.strategy,s=i.config.default_qty_type||"fixed",a=i.config.default_qty_value||1;typeof s=="function"&&(s=s()),typeof a=="function"&&(a=a());let o=1e6,l=u=>Math.floor(u*o)/o;if(e!=null)return l(Math.abs(e));let c;switch(s){case"fixed":c=a;break;case"cash":c=a/r;break;case"percent_of_equity":{c=i.equity*a/100/r;break}default:c=a}return l(c)}function im(t){if(!t.strategy)return;let e=t.strategy,{pending_orders:n}=e,r=y.from(t.data.open).get(0),i=y.from(t.data.high).get(0),s=y.from(t.data.low).get(0),a=y.from(t.data.close).get(0),o=y.from(t.data.openTime).get(0),l=t.pine?.syminfo?.pointvalue??1;for(let c of e.opentrades){let u=Math.abs(c.size),h=c.size>0,p=c.commission??0,d=h?(c.entry_price-s)*u*l:(i-c.entry_price)*u*l,f=h?(i-c.entry_price)*u*l:(c.entry_price-s)*u*l,m=Math.max(0,d)+p,x=Math.max(0,f-p);m>(c.max_drawdown??0)&&(c.max_drawdown=m),x>(c.max_runup??0)&&(c.max_runup=x)}br(t,r);for(let c of n){if(c.status!=="pending"||(c.category??"entry")==="exit"||c.bar>=t.idx)continue;let u=!1,h=r;switch(c.type){case"market":u=!0,h=r;break;case"limit":if(c.limit!==void 0){let p=Vt(c.direction);(p===1&&s<=c.limit||p===-1&&i>=c.limit)&&(u=!0,h=c.limit)}break;case"stop":if(c.stop!==void 0){let p=Vt(c.direction);(p===1&&i>=c.stop||p===-1&&s<=c.stop)&&(u=!0,h=c.stop)}break}if(u){if(am(e,c)){c.status="cancelled";continue}let p=Vt(c.direction);h=Ri(t,p,h);let d=p===1?e.config.margin_long??100:e.config.margin_short??100;{let f=e.position_size,m=Math.sign(f),x=m!==0&&m!==p,b=x?Math.max(0,c.qty-Math.abs(f)):c.qty;if(b>0){let w=t.pine?.syminfo?.pointvalue??1,E=0;m===p&&(E=rm(t,r));let v=e.equity-E;if(xr(b,h,d,w)>v){let I=Math.min(Math.abs(f),c.qty);x&&I>0?(Zt(t,I,h,o,{exitId:c.id,exitComment:c.comment}),c.status="filled",c.fill_price=h,c.fill_bar=t.idx,c.fill_time=o):c.status="cancelled";continue}}}lm(t,c,h,o),c.status="filled",c.fill_price=h,c.fill_bar=t.idx,c.fill_time=o}}e.pending_orders=n.filter(c=>c.status==="pending"),br(t,a),xm(t)}function Vt(t){return typeof t=="number"?t:t==="long"?1:t==="short"?-1:0}function fo(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 Ri(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 mo(t){let e=Math.abs(t.position_size);e>t.max_contracts_held_all&&(t.max_contracts_held_all=e),t.position_size>t.max_contracts_held_long&&(t.max_contracts_held_long=t.position_size),-t.position_size>t.max_contracts_held_short&&(t.max_contracts_held_short=-t.position_size)}function sm(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}function am(t,e){if(t.risk_halted)return!0;let n=t.risk_rules,r=e.direction;if(n.allow_entry_in&&(n.allow_entry_in==="long"&&r===-1||n.allow_entry_in==="short"&&r===1))return!0;if(n.max_position_size!==void 0){let i=t.position_size+r*e.qty;if(Math.abs(i)>n.max_position_size)return!0}return!1}function om(t){if(t.risk_halted)return;let e=t.risk_rules;if(e.max_drawdown){let n=e.max_drawdown.type==="percent_of_equity"?e.max_drawdown.value/100*t.equity_peak:e.max_drawdown.value;if(t.max_drawdown>=n){t.risk_halted=!0;return}}if(e.max_intraday_loss){let n=e.max_intraday_loss.type==="percent_of_equity"?e.max_intraday_loss.value/100*t.initial_capital:e.max_intraday_loss.value;if(t.grossloss>=n){t.risk_halted=!0;return}}if(e.max_cons_loss_days){let n=0;for(let r=t.closedtrades.length-1;r>=0&&(t.closedtrades[r].profit??0)<0;r--)n++;n>=e.max_cons_loss_days.count&&(t.risk_halted=!0)}}function Qn(t,e,n,r,i,s,a,o){let l=t.strategy,c=l.opentrades.length+l.closedtrades.length,u=l.config.commission_type??"percent",h=o&&u==="cash_per_order",p=fo(t,l,r,i),d=h?p/2:p,f={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:d,max_drawdown:0,max_runup:0,status:"open"};l.opentrades.push(f),l._first_entry_price===void 0&&(l._first_entry_price=i),(l._ledger_entries??(l._ledger_entries=[])).push({entry_id:e,entry_price:i,entry_time:s,entry_bar_index:t.idx,entry_comment:f.entry_comment,qty:r,commission:d}),d>0&&(l.netprofit-=d,l.grossloss+=d);let m=y.from(t.data.high).get(0),x=y.from(t.data.low).get(0),b=t.pine?.syminfo?.mintick??.01,w=n===1?x:m,E=n===1?m:x;for(let N of l.pending_orders){if((N.category??"entry")!=="exit"||N.from_entry&&N.from_entry!==e)continue;let j;N.stop!==void 0?j=N.stop:N.loss!==void 0&&(j=n===1?i-N.loss*b:i+N.loss*b);let D;N.limit!==void 0?D=N.limit:N.profit!==void 0&&(D=n===1?i+N.profit*b:i-N.profit*b),n===1?(j!==void 0&&j>w&&(w=j),D!==void 0&&D<E&&(E=D)):(j!==void 0&&j<w&&(w=j),D!==void 0&&D>E&&(E=D))}let v=t.pine?.syminfo?.pointvalue??1,I=n===1?(i-w)*r*v:(w-i)*r*v,C=n===1?(E-i)*r*v:(i-E)*r*v;f.max_drawdown=Math.max(0,I)+d,f.max_runup=Math.max(0,C-d);let T=l.position_size,O=T+f.size;if(T===0)l.position_size=O,l.position_avg_price=i,l.position_entry_name=e;else if(Math.sign(T)===Math.sign(O)){let N=Math.abs(T)*l.position_avg_price+r*i,j=Math.abs(O);l.position_avg_price=N/j,l.position_size=O}mo(l)}function lm(t,e,n,r){let i=t.strategy,s=Vt(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(Zt(t,l,n,r,{exitId:e.id,exitComment:e.comment,isImplicitReversal:u}),c>0){let h=e._base_qty;h!==void 0&&c>h+1e-9?(Qn(t,e.id,s,h,n,r,e.comment,!0),Qn(t,e.id,s,c-h,n,r,e.comment,!0)):Qn(t,e.id,s,c,n,r,e.comment,!0)}}else Qn(t,e.id,s,e.qty,n,r,e.comment)}function cm(t,e,n){let r=[],i=n,s=t._ledger_entries??[];for(let a of s){if(i<=1e-9)break;if(a.entry_id!==e.entry_id||a.qty<=1e-9)continue;let o=Math.min(a.qty,i),l=a.qty>0?a.commission*(o/a.qty):0;r.push({qty:o,entry_price:a.entry_price,entry_time:a.entry_time,entry_bar_index:a.entry_bar_index,entry_comment:a.entry_comment,commission:l}),a.qty-=o,a.commission-=l,i-=o}if(t._ledger_entries=s.filter(a=>a.qty>1e-9),i>1e-9){let a=Math.abs(e.size);r.push({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:a>0?(e.commission??0)*(i/a):0})}return r}function Zt(t,e,n,r,i){let s=t.strategy,a=t.pine?.syminfo?.pointvalue??1,o=e,l=[...s.opentrades];s.opentrades=[];for(let p of l){if(o<=0){s.opentrades.push(p);continue}let d=Math.abs(p.size),f=Math.min(d,o),m=Math.sign(p.size),x=b=>{let w=s.config.commission_type??"percent",E=i?.isImplicitReversal&&w==="cash_per_order",v=fo(t,s,b,n),I=E?v/2:v,C=cm(s,p,b);for(let T of C){let O=I*(T.qty/b),N=(m===1?n-T.entry_price:T.entry_price-n)*T.qty*a,j={id:`trade_${s.opentrades.length+s.closedtrades.length+l.length}`,entry_id:p.entry_id,entry_comment:T.entry_comment,entry_price:T.entry_price,_bracket_entry:p._bracket_entry,entry_bar_index:T.entry_bar_index,entry_time:T.entry_time,size:m*T.qty,commission:T.commission+O,max_drawdown:p.max_drawdown,max_runup:p.max_runup,status:"closed",exit_price:n,exit_bar_index:t.idx,exit_time:r,exit_id:i?.exitId??p.exit_id,exit_comment:i?.exitComment??p.exit_comment,profit:N-T.commission-O};i?.triggerKind==="loss"&&(j.max_runup=0),i?.triggerKind==="profit"&&(j.max_drawdown=T.commission),s.netprofit+=N-O,s.grossloss-=T.commission,j.profit>0?(s.grossprofit+=j.profit,s.wintrades++,s.wintrades_total_profit+=j.profit):j.profit<0?(s.grossloss+=Math.abs(j.profit),s.losstrades++,s.losstrades_total_loss+=Math.abs(j.profit)):s.eventrades++,s.closedtrades.push(j)}};if(f>=d-1e-9)p.status="closed",p.exit_price=n,p.exit_bar_index=t.idx,p.exit_time=r,x(d),o-=f;else{x(f);let b=(p.commission??0)*(f/d);p.size=m*(d-f),p.commission=(p.commission??0)-b,s.opentrades.push(p),o=0}}om(s);let c=s.position_size,u=Math.sign(c)*e,h=c-u;if(Math.abs(h)<1e-9&&(h=0),s.position_size=h,mo(s),h===0)s.position_avg_price=NaN,s.position_entry_name="";else if(s.opentrades.length>0){let p=0,d=0;for(let f of zr(s))p+=f.qty*f.entry_price,d+=f.qty;s.position_avg_price=p/d,s.position_entry_name=s.opentrades[0].entry_id}}function zr(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 br(t,e){let n=t.strategy,r=t.pine?.syminfo?.pointvalue??1,i=0;for(let s of zr(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 um(t,e,n){let r=t.strategy,i=t.pine?.syminfo?.pointvalue??1,s=r.initial_capital+r.netprofit,a=0;for(let f of zr(r))a+=f.commission;let o=s+a;o>r.equity_peak&&(r.equity_peak=o),s<r.equity_trough&&(r.equity_trough=s);let l=r.position_size,c=r.position_avg_price,u=0,h=0;if(l!==0&&Number.isFinite(c)){let f=l>0?n:e,m=l>0?e:n;u=l*(c-f)*i,h=l*(m-c)*i}let p=r.equity_peak-s+u;if(p>r.max_drawdown&&(r.max_drawdown=p,r.equity_at_drawdown_peak=r.equity_peak,r.equity_peak>0)){let f=100*p/r.equity_peak;f>r.max_drawdown_percent_value&&(r.max_drawdown_percent_value=f)}let d=s-r.equity_trough+h;if(d>r.max_runup&&(r.max_runup=d,r.equity_at_runup_peak=s+h,r.equity_at_runup_peak>0)){let f=100*d/r.equity_at_runup_peak;f>r.max_runup_percent_value&&(r.max_runup_percent_value=f)}}function ha(t,e,n,r,i,s,a){let o=t.strategy;if(a!==void 0){let p=[],d=[];for(let m of o.opentrades)m.id===a?p.push(m):d.push(m);if(p.length===0)return;let f=Math.abs(p[0].size);o.opentrades=[...p,...d],Zt(t,Math.min(n,f),r,i,s);return}if(!e||e===""){Zt(t,n,r,i,s);return}let l=[],c=[];for(let p of o.opentrades)p.entry_id===e?l.push(p):c.push(p);let u=l.reduce((p,d)=>p+Math.abs(d.size),0);if(u===0)return;let h=Math.min(n,u);o.opentrades=[...l,...c],Zt(t,h,r,i,s)}function pm(t,e="intrabar"){if(!t.strategy)return;let n=t.strategy;if(n.pending_orders.length===0)return;let r=y.from(t.data.open).get(0),i=y.from(t.data.high).get(0),s=y.from(t.data.low).get(0),a=y.from(t.data.close).get(0),o=y.from(t.data.openTime).get(0),l=t.pine?.syminfo?.mintick??.01;for(let c of n.pending_orders){if(c.status!=="pending"||(c.category??"entry")!=="exit")continue;let u=n.opentrades.filter(D=>!c.from_entry||D.entry_id===c.from_entry);if(c._intended_trade_ids){let D=new Set(c._intended_trade_ids);u=u.filter(W=>D.has(W.id))}if(u.length===0){e==="intrabar"&&(c.status="cancelled");continue}let h=u.reduce((D,W)=>D+Math.abs(W.size),0),p=Math.sign(u[0].size);if(c.type==="market"&&c.profit===void 0&&c.loss===void 0&&c.limit===void 0&&c.stop===void 0&&c.trail_price===void 0&&c.trail_points===void 0){if(e==="open"||c.bar>=t.idx)continue;let D=c.immediately?a:r;D=Ri(t,-p,D);let W=h;c.qty&&c.qty>0?W=Math.min(c.qty,h):c.qty_percent&&c.qty_percent>0&&(W=h*(c.qty_percent/100)),ha(t,c.from_entry,W,D,o,{exitId:c.id,exitComment:c.comment}),c.status="filled",c.fill_price=D,c.fill_bar=t.idx,c.fill_time=o;continue}let d=0;for(let D of u)d+=Math.abs(D.size)*D.entry_price;let f=d/h,m=p===1,x=c.limit,b=c.stop;c._isPersistent||(b!==void 0&&((m?b<f:b>f)||(b=void 0)),x!==void 0&&((m?x>f:x<f)||(x=void 0))),c._attachedAtReversal&&!c._isPersistent&&(c.limit!==void 0&&(x=void 0),c.stop!==void 0&&(b=void 0));let w=!1;if(e==="intrabar"&&!c.trail_armed&&(c.trail_price!==void 0||c.trail_points!==void 0)){let D;c.trail_price!==void 0?D=c.trail_price:c.trail_points!==void 0&&(D=m?f+c.trail_points*l:f-c.trail_points*l),D!==void 0&&(m?i>=D:s<=D)&&(c.trail_armed=!0,c.trail_peak=m?i:s,w=!0)}let E=Math.abs(i-r)<=Math.abs(r-s),v=m?E:!E,I=[],C=[],T=n._mc_exit_lock,O=T&&T.bar===t.idx;for(let D of u){if(O&&D.id!==T.tradeId)continue;let W=D._bracket_entry??D.entry_price,R=Math.abs(D.size),P=x;P===void 0&&c.profit!==void 0&&(P=m?W+c.profit*l:W-c.profit*l);let H=b;H===void 0&&c.loss!==void 0&&(H=m?W-c.loss*l:W+c.loss*l);let te=P!==void 0&&(e==="open"?m?r>=P:r<=P:m?i>=P:s<=P),ve=H!==void 0&&(e==="open"?m?r<=H:r>=H:m?s<=H:i>=H),ae=null;if(te&&ve?ae=v?"profit":"loss":te?ae="profit":ve&&(ae="loss"),ae==="loss"){let Fe=m?r<=H:r>=H;!m&&Fe&&D.entry_bar_index===t.idx?te&&(ae="profit"):C.push({qty:R,price:Fe?r:H,kind:"loss",tradeId:D.id})}if(ae==="profit"){let Fe=m?r>=P:r<=P;I.push({qty:R,price:Fe?r:P,kind:"profit",tradeId:D.id})}}I.sort((D,W)=>m?D.price-W.price:W.price-D.price),C.sort((D,W)=>m?W.price-D.price:D.price-W.price);let N=null;if(e==="intrabar"&&!O&&c.trail_armed&&c.trail_offset!==void 0){let D=()=>{m?c.trail_peak=Math.max(c.trail_peak??-1/0,i):c.trail_peak=Math.min(c.trail_peak??1/0,s)},W=()=>m?c.trail_peak-c.trail_offset*l:c.trail_peak+c.trail_offset*l,R=P=>{N={qty:1/0,price:P,kind:"trailing"}};if(w){let P=W();v?(m?s<=P:i>=P)&&R(P):(m?a<=P:a>=P)&&R(P)}else if(v){D();let P=W();(m?s<=P:i>=P)&&R(P)}else{let P=W();if(m?s<=P:i>=P)R(P);else{D();let H=W();(m?a<=H:a>=H)&&R(H)}}}let j=v?[...I,...C,...N?[N]:[]]:[...C,...N?[N]:[],...I];if(j.length>0){let D=h;c.qty&&c.qty>0?D=Math.min(c.qty,h):c.qty_percent&&c.qty_percent>0&&(D=h*(c.qty_percent/100));let W=()=>n.opentrades.filter(H=>!c.from_entry||H.entry_id===c.from_entry).reduce((H,te)=>H+Math.abs(te.size),0),R=NaN,P=!1;for(let H of j){if(D<=1e-9)break;let te=W();if(te<=1e-9)break;let ve=Math.min(H.qty===1/0?te:H.qty,D,te),ae=Ri(t,-p,H.price),Fe=H.kind==="profit"?c.comment_profit??c.comment:H.kind==="loss"?c.comment_loss??c.comment:c.comment_trailing??c.comment;ha(t,c.from_entry,ve,ae,o,{triggerKind:H.kind,exitId:c.id,exitComment:Fe},H.tradeId),D-=ve,R=ae,P=!0}P&&(W()<=1e-9||D<=1e-9)&&(c.status="filled",c.fill_price=R,c.fill_bar=t.idx,c.fill_time=o)}}n.pending_orders=n.pending_orders.filter(c=>c.status==="pending"),br(t,a)}function hm(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)&&(Zt(t,Math.min(n.qty,Math.abs(e.position_size)),n.price,n.time,{exitId:"Margin call",exitComment:"Margin call"}),Math.abs(e.position_size)>1e-9))){for(let r of e.pending_orders)r.status==="pending"&&(r.category??"entry")==="entry"&&!r._isReversalEntry&&Vt(r.direction)===n.dir&&(r.status="cancelled");e.pending_orders=e.pending_orders.filter(r=>r.status==="pending")}}function dm(t){let e=t.strategy,n=Math.sign(e?.position_size??0);if(n===0)return!1;let r=y.from(t.data.open).get(0),i=y.from(t.data.high).get(0),s=y.from(t.data.low).get(0),a=Math.abs(i-r)<=Math.abs(r-s);return n===1?!a:a}function ci(t,e="extreme"){let n=t.strategy;if(!n||n.opentrades.length===0)return;let r=Math.sign(n.position_size);if(r===0)return;let i=r===1?n.config.margin_long??100:n.config.margin_short??100,s=y.from(t.data.open).get(0),a=y.from(t.data.high).get(0),o=y.from(t.data.low).get(0),l=y.from(t.data.close).get(0),c=y.from(t.data.openTime).get(0),u=t.pine?.syminfo?.pointvalue??1,h=e==="open"?s:e==="close"?l:r===1?o:a,p=Math.abs(n.position_size),d=nm(t,h),f=xr(p,h,i,u);if(d<f){let m=f-d,x=i/100,b=m/(h*u*x),w=Math.min(p,4*b),E=[...n.opentrades],v=E[0],I=Math.abs(v.size),C=v.entry_price;if(Zt(t,w,h,c,{exitId:"Margin call",exitComment:"Margin call"}),e==="extreme"&&w>=I-1e-9&&Math.abs(n.position_size)>1e-9){let O=xr(I,h,i,u),N=I*(h-C)*r*u,j=m-O+N;if(j>0){let D=y.from(t.data.close).get(0),W=(P=>Math.trunc(P*1e6)/1e6)(j/(h*u*x)),R=Math.min(Math.abs(n.position_size),4*W);R>1e-9&&(n._pending_close_mc={qty:R,price:D,time:c,dir:r})}}let T=E.find(O=>O.status==="open");n._mc_exit_lock={bar:t.idx,tradeId:T?.id??null}}}function fm(t){if(!t.strategy)return;let e=t.strategy,n=y.from(t.data.high).get(0),r=y.from(t.data.low).get(0),i=y.from(t.data.close).get(0);br(t,i),um(t,n,r);let s=y.from(t.data.openTime).get(0);if(Number.isFinite(s)){let a=new Date(s),o=a.getUTCFullYear()*12+a.getUTCMonth(),l=e._monthly_equity??(e._monthly_equity=[]);e._last_month_key===o&&l.length>0?l[l.length-1]=e.equity:(l.push(e.equity),e._last_month_key=o)}}function mm(t){let e=t?.strategy;if(!e)return;e.cagr=gm(t),_m(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 ym=1440*60*1e3;function gm(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)/ym;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 _m(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 xm(t){t.strategy}function bm(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,...e,...t._propOverrides??{}},r=n.initial_capital;t.strategy={config:n,opentrades:[],closedtrades:[],pending_orders:[],position_size:0,position_avg_price:NaN,position_entry_name:"",initial_capital:r,account_currency:n.currency||"USD",equity:r,netprofit:0,grossprofit:0,grossloss:0,openprofit:0,max_drawdown:0,max_runup:0,equity_peak:r,equity_trough:r,equity_at_runup_peak:r,equity_at_drawdown_peak:r,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,_exit_call_history:new Map,_exit_fallback_counter:0,_exit_fallback_last_bar:-1}}function An(t){if(Array.isArray(t))return t.map(An);if(t instanceof Map){let e=new Map;return t.forEach((n,r)=>e.set(r,An(n))),e}if(t!==null&&typeof t=="object"){let e={};for(let n of Object.keys(t))e[n]=An(t[n]);return e}return t}function wm(t){if(!t)return null;let e={};for(let n of Object.keys(t))n==="config"||n==="closedtrades"||(e[n]=An(t[n]));return{fields:e,closedtradesLength:t.closedtrades.length}}function vm(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]=An(e.fields[n])}}function Em(t){return(...e)=>{let n=tm(e);return t.strategy?t.strategy.config={...t.strategy.config,...n,...t._propOverrides??{}}:bm(t,n),t.strategy.config}}var Sm=[["id","direction","qty","limit","stop","oca_name","oca_type","comment","alert_message","disable_alert"]],Cm={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 Nm(t){return(...e)=>{if(!t.strategy)throw new Error("strategy.order() called before strategy() declaration");let n=ce(e,Sm,Cm),r=w=>w==null||typeof w=="string"||typeof w=="number"||typeof w=="boolean"?w:typeof w=="function"?w():w instanceof y?w.get(0):Array.isArray(w)?w[w.length-1]:typeof w=="object"&&w.get!==void 0?w.get(0):w,i=r(n.id),s=r(n.direction),a=r(n.qty),o=r(n.limit),l=r(n.stop),c=r(n.oca_name),u=r(n.oca_type),h=r(n.comment),p=Vt(s),d=y.from(t.data.close).get(0),f=ws(t,a,p,d),m="market";o!==void 0&&l!==void 0?m="stop-limit":o!==void 0?m="limit":l!==void 0&&(m="stop");let x=y.from(t.data.openTime).get(0),b={id:i,direction:p,qty:f,type:m,limit:o,stop:l,bar:t.idx,time:x,status:"pending",oca_name:c,oca_type:u,comment:h};return t.strategy.pending_orders.push(b),b}}function km(t){return(e,n)=>y.from(e).get(n||0)}function Im(t){return()=>{let e=(t.strategy?.opentrades??[]).slice(),n=p=>e[Number(p)],r=()=>{let p=t.marketData;return Array.isArray(p)&&t.idx>=0&&t.idx<p.length?p[t.idx]?.close??NaN:NaN},i={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",x=f?.commission_value??0;if(!x)return 0;let b=Math.abs(p.size);switch(m){case"percent":return b*d*s*(x/100);case"cash_per_contract":return b*x;case"cash_per_order":return x;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 NaN;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 NaN;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??NaN,i.commission=p=>n(p)?.commission??NaN,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=c!==100||u!==100;if(!l||l.opentrades.length===0||!h)i.capital_held=NaN;else{let p=0;for(let d of l.opentrades){let f=Math.abs(d.size)*d.entry_price,m=d.size>0?c:u;p+=f*(m/100)}i.capital_held=p}return i}}function Am(t){return()=>{let e=(t.strategy?.closedtrades??[]).slice(),n=a=>e[Number(a)],r={valueOf(){return e.length},toString(){return String(e.length)},[Symbol.toPrimitive](){return e.length}},i=t.pine?.syminfo?.pointvalue??1,s=a=>{let o=Math.abs(a.size)*a.entry_price*i,l=(a.commission??0)/2;return o+l};return r.profit=a=>n(a)?.profit??NaN,r.profit_percent=a=>{let o=n(a);if(!o||o.profit===void 0)return NaN;let l=s(o);return l>0?100*o.profit/l:NaN},r.size=a=>n(a)?.size??NaN,r.commission=a=>n(a)?.commission??NaN,r.entry_price=a=>n(a)?.entry_price??NaN,r.entry_bar_index=a=>n(a)?.entry_bar_index??NaN,r.entry_id=a=>n(a)?.entry_id??"",r.entry_comment=a=>n(a)?.entry_comment??n(a)?.entry_id??"",r.entry_time=a=>n(a)?.entry_time??NaN,r.exit_price=a=>n(a)?.exit_price??NaN,r.exit_bar_index=a=>n(a)?.exit_bar_index??NaN,r.exit_id=a=>n(a)?.exit_id??"",r.exit_comment=a=>n(a)?.exit_comment??n(a)?.exit_id??"",r.exit_time=a=>n(a)?.exit_time??NaN,r.max_drawdown=a=>n(a)?.max_drawdown??0,r.max_drawdown_percent=a=>{let o=n(a);if(!o||!o.max_drawdown)return 0;let l=s(o);return l>0?100*o.max_drawdown/l:0},r.max_runup=a=>n(a)?.max_runup??0,r.max_runup_percent=a=>{let o=n(a);if(!o||!o.max_runup)return 0;let l=s(o);return l>0?100*o.max_runup/l:0},r.first_index=0,r}}function Tm(t){return()=>t.strategy?.netprofit??0}function Dm(t){return()=>t.strategy?.position_size??0}function Mm(t){return()=>{let e=t.strategy;return!e||e.position_size===0?NaN:e.position_avg_price}}function Pm(t){return()=>t.strategy?.equity??t.strategy?.config?.initial_capital??1e4}function Rm(t){return()=>"long"}function Fm(t){return()=>"short"}function Bm(t){return()=>"cash"}function Lm(t){return()=>"percent_of_equity"}function Om(t){return()=>"fixed"}function Vm(t){return()=>t.strategy?.openprofit??0}function jm(t){return()=>{let e=t.strategy;return!e||!e.initial_capital?0:100*e.openprofit/e.initial_capital}}function $m(t){return()=>{let e=t.strategy;return!e||!e.initial_capital?0:100*e.netprofit/e.initial_capital}}function Wm(t){return()=>t.strategy?.grossprofit??0}function Um(t){return()=>{let e=t.strategy;return!e||!e.initial_capital?0:100*e.grossprofit/e.initial_capital}}function qm(t){return()=>t.strategy?.grossloss??0}function zm(t){return()=>{let e=t.strategy;return!e||!e.initial_capital?0:100*e.grossloss/e.initial_capital}}function Km(t){return()=>t.strategy?.wintrades??0}function Hm(t){return()=>t.strategy?.losstrades??0}function Gm(t){return()=>t.strategy?.eventrades??0}function Ym(t){return()=>{let e=t.strategy;return!e||!e.closedtrades||e.closedtrades.length===0?NaN:e.netprofit/e.closedtrades.length}}function Zm(t){return()=>{let e=t.strategy;if(!e||!e.closedtrades||e.closedtrades.length===0)return NaN;let n=0;for(let r of e.closedtrades){let i=Math.abs(r.size)*r.entry_price;i>0&&(n+=100*(r.profit??0)/i)}return n/e.closedtrades.length}}function Xm(t){return()=>{let e=t.strategy;return!e||e.wintrades===0?NaN:e.wintrades_total_profit/e.wintrades}}function Qm(t){return()=>{let e=t.strategy;if(!e||e.wintrades===0)return NaN;let n=0;for(let r of e.closedtrades)if((r.profit??0)>0){let i=Math.abs(r.size)*r.entry_price;i>0&&(n+=100*(r.profit??0)/i)}return n/e.wintrades}}function Jm(t){return()=>{let e=t.strategy;return!e||e.losstrades===0?NaN:e.losstrades_total_loss/e.losstrades}}function ey(t){return()=>{let e=t.strategy;if(!e||e.losstrades===0)return NaN;let n=0;for(let r of e.closedtrades)if((r.profit??0)<0){let i=Math.abs(r.size)*r.entry_price;i>0&&(n+=100*(r.profit??0)/i)}return n/e.losstrades}}function ty(t){return()=>t.strategy?.max_drawdown??0}function ny(t){return()=>{let e=t.strategy;return e?e.max_drawdown_percent_value??0:0}}function ry(t){return()=>t.strategy?.max_runup??0}function iy(t){return()=>{let e=t.strategy;return e?e.max_runup_percent_value??0:0}}function sy(t){return()=>t.strategy?.max_contracts_held_all??0}function ay(t){return()=>t.strategy?.max_contracts_held_long??0}function oy(t){return()=>t.strategy?.max_contracts_held_short??0}function ly(t){return()=>t.strategy?.position_entry_name??""}function cy(t){return()=>t.strategy?.initial_capital??0}function uy(t){return()=>t.strategy?.account_currency??"USD"}function py(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>=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;return r===1?Math.floor(c/u)*u:Math.ceil(c/u)*u}}var hy=[["id","direction","qty","limit","stop","oca_name","oca_type","comment","alert_message","disable_alert"]],dy={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 fy(t){return(...e)=>{if(!t.strategy)throw new Error("strategy.entry() called before strategy() declaration");let n=ce(e,hy,dy),r=N=>N==null||typeof N=="string"||typeof N=="number"||typeof N=="boolean"?N:typeof N=="function"?N():N instanceof y?N.get(0):Array.isArray(N)?N[N.length-1]:typeof N=="object"&&N.get!==void 0?N.get(0):N,i=r(n.id),s=r(n.direction),a=r(n.qty),o=r(n.limit),l=r(n.stop),c=r(n.oca_name),u=r(n.oca_type),h=r(n.comment),p=Vt(s),d=t.strategy,f=d.position_size;for(let N of d.pending_orders)N.bar===t.idx&&N.category==="entry"&&N.type==="market"&&(f+=Vt(N.direction)*N.qty);if(Math.sign(f)===p&&f!==0&&sm(d,p))return;let m=y.from(t.data.close).get(0),x=ws(t,a,p,m),b=f!==0&&Math.sign(f)!==p,w=b?Math.abs(f)+x:x,E="market";o!==void 0&&l!==void 0?E="stop-limit":o!==void 0?E="limit":l!==void 0&&(E="stop");let v=t.pine?.syminfo?.mintick??0,I=o!==void 0?In(o,m,v):void 0,C=l!==void 0?In(l,m,v):void 0,T=y.from(t.data.openTime).get(0),O={id:i,direction:p,qty:w,type:E,limit:I,stop:C,bar:t.idx,time:T,status:"pending",category:"entry",oca_name:c,oca_type:u,comment:h,_isReversalEntry:b,_base_qty:x};d.pending_orders.push(O)}}var my=[["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"]],yy={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 gy(t){return(...e)=>{if(!t.strategy)throw new Error("strategy.exit() called before strategy() declaration");let n=ht(e);if(n===void 0){let R=t.strategy;R._exit_fallback_last_bar!==t.idx&&(R._exit_fallback_counter=0,R._exit_fallback_last_bar=t.idx),n=`exit_raw_${R._exit_fallback_counter++}`}let r=ce(e,my,yy),i=R=>R==null||typeof R=="string"||typeof R=="number"||typeof R=="boolean"?R:typeof R=="function"?R():R instanceof y?R.get(0):Array.isArray(R)?R[R.length-1]:typeof R=="object"&&R.get!==void 0?R.get(0):R,s=i(r.id),a=i(r.from_entry),o=i(r.qty),l=i(r.qty_percent),c=i(r.profit),u=i(r.limit),h=i(r.loss),p=i(r.stop),d=i(r.trail_price),f=i(r.trail_points),m=i(r.trail_offset),x=t.pine?.syminfo?.mintick??0,b=y.from(t.data.close).get(0),w=u!==void 0?In(u,b,x):void 0,E=p!==void 0?In(p,b,x):void 0,v=d!==void 0?In(d,b,x):void 0,I=a??"",C=!!(I?t.strategy.pending_orders.find(R=>R.category==="entry"&&R.id===I&&R.status==="pending"):t.strategy.pending_orders.find(R=>R.category==="entry"&&R.status==="pending"))?._isReversalEntry,T=t.strategy._exit_call_history,O=T.get(n),N=O!==void 0&&O===t.idx-1;T.set(n,t.idx);let j={id:s??"exit",direction:0,qty:o!==void 0?Math.abs(Number(o)):0,qty_percent:l,type:"market",bar:t.idx,time:y.from(t.data.openTime).get(0),status:"pending",category:"exit",from_entry:I,profit:c,loss:h,limit:w,stop:E,trail_price:v,trail_points:f,trail_offset:m,oca_name:i(r.oca_name),comment:i(r.comment),comment_profit:i(r.comment_profit),comment_loss:i(r.comment_loss),comment_trailing:i(r.comment_trailing),alert_message:i(r.alert_message),alert_profit:i(r.alert_profit),alert_loss:i(r.alert_loss),alert_trailing:i(r.alert_trailing),disable_alert:i(r.disable_alert),trail_armed:!1,trail_peak:NaN,_attachedAtReversal:C,_isPersistent:N,_callsiteId:n},D=j.id,W=t.strategy.pending_orders;for(let R=W.length-1;R>=0;R--){let P=W[R];P.category==="exit"&&P.id===D&&(P.from_entry??"")===(j.from_entry??"")&&P.status==="pending"&&(P.trail_armed&&(j.trail_armed=!0,j.trail_peak=P.trail_peak),W.splice(R,1))}W.push(j)}}var _y=[["id","comment","qty","qty_percent","alert_message","immediately","disable_alert"]],xy={id:"string",comment:"string",qty:"series",qty_percent:"series",alert_message:"string",immediately:"boolean",disable_alert:"boolean"};function by(t){return(...e)=>{if(!t.strategy)throw new Error("strategy.close() called before strategy() declaration");let n=ce(e,_y,xy),r=n.id;if(r==null||!t.strategy.opentrades.some(o=>o.entry_id===r))return;let i=o=>(o.category??"entry")==="exit"&&(o.profit!==void 0||o.loss!==void 0||o.limit!==void 0||o.stop!==void 0||o.trail_price!==void 0||o.trail_points!==void 0),s=t.strategy.pending_orders;for(let o of s)i(o)&&(o.from_entry??"")===r&&o.status==="pending"&&(o.status="cancelled");t.strategy.pending_orders=s.filter(o=>o.status==="pending");let a={id:`close_${r}`,direction:0,qty:0,type:"market",bar:t.idx,time:y.from(t.data.openTime).get(0),status:"pending",category:"exit",from_entry:r,qty_percent:n.qty_percent,comment:n.comment,alert_message:n.alert_message,immediately:n.immediately===!0,disable_alert:n.disable_alert,_intended_trade_ids:t.strategy.opentrades.filter(o=>o.entry_id===r).map(o=>o.id)};n.qty!==void 0&&(a.qty=Math.abs(Number(n.qty))),t.strategy.pending_orders.push(a)}}var wy=[["comment","alert_message","immediately","disable_alert"]],vy={comment:"string",alert_message:"string",immediately:"boolean",disable_alert:"boolean"};function Ey(t){return(...e)=>{if(!t.strategy)throw new Error("strategy.close_all() called before strategy() declaration");let n=ce(e,wy,vy);if(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_all",direction:0,qty:0,type:"market",bar:t.idx,time:y.from(t.data.openTime).get(0),status:"pending",category:"exit",from_entry:"",comment:n.comment,alert_message:n.alert_message,immediately:n.immediately===!0,disable_alert:n.disable_alert,_intended_trade_ids:t.strategy.opentrades.map(a=>a.id)};t.strategy.pending_orders.push(s)}}var Sy=[["id","immediately"]],Cy={id:"string",immediately:"boolean"};function Ny(t){return(...e)=>{if(!t.strategy)throw new Error("strategy.cancel() called before strategy() declaration");let n=ce(e,Sy,Cy).id;n!=null&&(t.strategy.pending_orders=t.strategy.pending_orders.filter(r=>!(r.status==="pending"&&r.id===n)))}}function ky(t){return()=>{if(!t.strategy)throw new Error("strategy.cancel_all() called before strategy() declaration");t.strategy.pending_orders=t.strategy.pending_orders.filter(e=>!(e.status==="pending"&&(e.category??"entry")==="entry"))}}function Iy(t){return{allow_entry_in:e=>{t.strategy&&(t.strategy.risk_rules.allow_entry_in=e)},max_cons_loss_days:(e,n)=>{t.strategy&&(t.strategy.risk_rules.max_cons_loss_days={count:e,alert_message:n})},max_drawdown:(e,n,r)=>{t.strategy&&(t.strategy.risk_rules.max_drawdown={value:e,type:n})},max_intraday_filled_orders:(e,n)=>{t.strategy&&(t.strategy.risk_rules.max_intraday_filled_orders={count:e,alert_message:n})},max_intraday_loss:(e,n,r)=>{t.strategy&&(t.strategy.risk_rules.max_intraday_loss={value:e,type:n})},max_position_size:e=>{t.strategy&&(t.strategy.risk_rules.max_position_size=e)}}}function Ay(t){return e=>{let n=t.strategy,r=t.pine?.syminfo?.currency,i=n?.account_currency??"USD";return r&&r!==i?NaN:e}}function Ty(t){return e=>{let n=t.strategy,r=t.pine?.syminfo?.currency,i=n?.account_currency??"USD";return r&&r!==i?NaN:e}}function Dy(t){return e=>t.strategy?ws(t,void 0,1,e):0}var My={any:Em,order:Nm,param:km,opentrades:Im,closedtrades:Am,netprofit:Tm,position_size:Dm,position_avg_price:Mm,equity:Pm,long:Rm,short:Fm,cash:Bm,percent_of_equity:Lm,fixed:Om,openprofit:Vm,openprofit_percent:jm,netprofit_percent:$m,grossprofit:Wm,grossprofit_percent:Um,grossloss:qm,grossloss_percent:zm,wintrades:Km,losstrades:Hm,eventrades:Gm,avg_trade:Ym,avg_trade_percent:Zm,avg_winning_trade:Xm,avg_winning_trade_percent:Qm,avg_losing_trade:Jm,avg_losing_trade_percent:ey,max_drawdown:ty,max_drawdown_percent:ny,max_runup:ry,max_runup_percent:iy,max_contracts_held_all:sy,max_contracts_held_long:ay,max_contracts_held_short:oy,position_entry_name:ly,initial_capital:cy,account_currency:uy,margin_liquidation_price:py,entry:fy,exit:gy,close:by,close_all:Ey,cancel:Ny,cancel_all:ky,convert_to_account:Ay,convert_to_symbol:Ty,default_entry_qty:Dy},Py={long:"long",short:"short",all:"all"},Ry={none:"none",cancel:"cancel",reduce:"reduce"},Fy={percent:"percent",cash_per_order:"cash_per_order",cash_per_contract:"cash_per_contract"},Fi=class{constructor(e){this.context=e,Object.entries(My).forEach(([r,i])=>{this[r]=i(e)}),this.direction=()=>Py,this.oca=()=>Ry,this.commission=()=>Fy;let n=Iy(e);this.risk=()=>n}};function By(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=jt(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 Ly(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 Bi=class{constructor(e){this.context=e}logFormat(e,...n){return e.replace(/{(\\d+)}/g,(r,i)=>n[i])}param(e,n=0,r){return y.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=By(e,n);return Ly(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)}`)}},Li=class{constructor(e){this.context=e}param(e,n=0,r){return y.from(e).get(n)}error(e){let n=y.from(e).get(0);throw new dr(typeof n=="string"?n:String(n??""),"runtime.error")}},Oy=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Vy=["January","February","March","April","May","June","July","August","September","October","November","December"],jy=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],$y=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],He=(t,e)=>String(t).padStart(e,"0"),Oi=class{constructor(e){this.context=e}param(e,n=0,r){return y.from(e).get(n)}tostring(e,n){if(typeof e!="number"||isNaN(e)||!n)return String(e);if(n==="mintick"){let i=this.context.pine?.syminfo?.mintick||.01,s=Math.max(0,-Math.floor(Math.log10(i)));return e.toFixed(s)}if(n==="integer")return String(Math.round(e));if(n==="percent")return(e*100).toFixed(2)+"%";if(n==="price"){let i=this.context.pine?.syminfo?.mintick||.01,s=Math.max(0,-Math.floor(Math.log10(i)));return e.toFixed(s)}if(n==="volume")return String(Math.round(e));let r=n.indexOf(".");if(r>=0){let i=n.substring(r+1).length;return e.toFixed(i)}return n.includes("#")||n.includes("0")?String(Math.round(e)):String(e)}tonumber(e){return Number(e)}lower(e){return String(e).toLowerCase()}upper(e){return String(e).toUpperCase()}trim(e){return String(e).trim()}repeat(e,n,r=""){return Array(n).fill(e).join(r||"")}replace_all(e,n,r){return String(e).replaceAll(n,r)}replace(e,n,r,i=0){let s=String(e),a=String(n),o=String(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 String(e).includes(n)}endswith(e,n){return String(e).endsWith(n)}startswith(e,n){return String(e).startsWith(n)}pos(e,n){let r=String(e).indexOf(n);return r===-1?NaN:r}length(e){return String(e).length}match(e,n){return String(e).match(new RegExp(n))}split(e,n){return new q(String(e).split(n),z.string,this.context)}substring(e,n,r){return String(e).substring(n,r)}format_time(e,n="yyyy-MM-dd\'T\'HH:mm:ssZ",r){if(e==null||typeof e=="number"&&isNaN(e))return"NaN";let i=Number(e),s=r||this.context.pine?.syminfo?.timezone||"UTC",a=jt(i,s),o=Date.UTC(a.year,a.month-1,a.day,a.hour,a.minute,a.second),l=Math.round((o-i)/6e4),c=Date.UTC(a.year,0,1),u=Math.floor((o-c)/864e5)+1,h=a.hour%12===0?12:a.hour%12,p="",d=0;for(;d<n.length;){let f=n[d];if(f==="\'"){if(n[d+1]==="\'"){p+="\'",d+=2;continue}let m=n.indexOf("\'",d+1);if(m===-1){p+=n.substring(d+1);break}p+=n.substring(d+1,m),d=m+1;continue}if(f>="a"&&f<="z"||f>="A"&&f<="Z"){let m=1;for(;n[d+m]===f;)m++;switch(d+=m,f){case"y":p+=m===2?He(a.year%100,2):m>=4?He(a.year,4):String(a.year);break;case"M":m>=4?p+=Vy[a.month-1]:m===3?p+=Oy[a.month-1]:m===2?p+=He(a.month,2):p+=String(a.month);break;case"d":p+=m===2?He(a.day,2):String(a.day);break;case"D":p+=m>=3?He(u,3):m===2?He(u,2):String(u);break;case"E":p+=m>=4?$y[a.dayOfWeek]:jy[a.dayOfWeek];break;case"a":p+=a.hour<12?"AM":"PM";break;case"h":p+=m===2?He(h,2):String(h);break;case"H":p+=m===2?He(a.hour,2):String(a.hour);break;case"m":p+=m===2?He(a.minute,2):String(a.minute);break;case"s":p+=m===2?He(a.second,2):String(a.second);break;case"S":{let x=i-Math.floor(i/1e3)*1e3;p+=He(x,3).substring(0,m);break}case"Z":{let x=l>=0?"+":"-",b=Math.abs(l);p+=`${x}${He(Math.floor(b/60),2)}${He(b%60,2)}`;break}default:p+=f.repeat(m)}continue}p+=f,d++}return p}format(e,...n){return e.replace(/\\{(\\d+)(?:,number,([^}]+))?\\}/g,(r,i,s)=>{let a=n[i];return s&&typeof a=="number"&&!isNaN(a)?this.tostring(a,s):String(a)})}},Wy=Object.defineProperty,Uy=(t,e,n)=>e in t?Wy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,qy=(t,e,n)=>Uy(t,typeof e!="symbol"?e+"":e,n),Jn={"1m":"1","3m":"3","5m":"5","15m":"15","30m":"30","45m":"45","1h":"60","2h":"120","3h":"180","4h":"240","1d":"D","1w":"W","1M":"M"};function da(t){if(!t||/^\\d+$/.test(t))return t;if(Jn[t])return Jn[t];let e=t.toLowerCase();if(Jn[e])return Jn[e];if(t.length===1){let r=t.toUpperCase();if(["D","W","M","S"].includes(r))return r}let n=t.slice(-1).toUpperCase();if(["D","W","M","S"].includes(n)){let r=parseInt(t);if(!isNaN(r))return r+n}return t}var Vi=class{constructor(e){this.context=e,qy(this,"_normalized",null)}param(e,n=0,r){return y.from(e).get(n)}get normalized(){return this._normalized===null&&(this._normalized=da(this.context.timeframe)),this._normalized}get unit(){return this.normalized.slice(-1).toUpperCase()}get main_period(){return this.normalized}get period(){return this.normalized}get multiplier(){let e=parseInt(this.normalized);return isNaN(e)?1:e}get isdwm(){return["D","W","M"].includes(this.unit)}get isdaily(){return this.unit==="D"}get isweekly(){return this.unit==="W"}get ismonthly(){return this.unit==="M"}get isseconds(){return this.unit==="S"}get isminutes(){return/^\\d+$/.test(this.normalized)}get isintraday(){return!this.isdwm}change(e){let n=typeof e=="function"?e():e,r=n instanceof y?n.get(0):n,i=vi(r||"");if(!i)return!1;let s=y.from(this.context.data.openTime).get(0),a=y.from(this.context.data.openTime).get(1);if(isNaN(s)||isNaN(a))return!1;let o=Ei(s,i),l=Ei(a,i);return o!==l}from_seconds(e){return e<60?Math.ceil(e/5)*5+"S":e<3600*24?Math.ceil(e/60):e<=3600*24*7*52?e%(3600*24*7)===0?Math.ceil(e/604800)+"W":Math.ceil(e/(3600*24))+"D":"12M"}in_seconds(e){e==null?e=this.normalized:e=da(e);let n=e.slice(-1).toUpperCase(),r=parseInt(e);return n==="S"?isNaN(r)?1:r:n==="D"?(isNaN(r)?1:r)*60*60*24:n==="W"?(isNaN(r)?1:r)*60*60*24*7:n==="M"?(isNaN(r)?1:r)*60*60*24*30:isNaN(r)?0:r*60}},zy=Object.defineProperty,Ky=Object.getOwnPropertyDescriptor,bt=(t,e,n,r)=>{for(var i=r>1?void 0:r?Ky(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&&zy(e,n,i),i},Hy=["series","title","color","linewidth","style","trackprice","histbase","offset","join","editable","show_last","display","format","precision","force_overlay"],Gy=["series","title","char","location","color","offset","text","textcolor","editable","size","show_last","display","format","precision","force_overlay"],Yy={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"},Zy=["series","title","style","location","color","offset","text","textcolor","editable","size","show_last","display","format","precision","force_overlay"],Xy=["series","title","colorup","colordown","offset","minheight","maxheight","editable","show_last","display","format","precision","force_overlay"],Qy=["open","high","low","close","title","color","editable","show_last","display","format","precision","force_overlay"],Jy=["open","high","low","close","title","color","wickcolor","editable","show_last","bordercolor","display","format","precision","force_overlay"],fa=["color","offset","editable","show_last","title","display","force_overlay"],eg=["price","title","color","linestyle","linewidth","editable","display"],tg=["plot1","plot2","color","title","editable","show_last","fillgaps","display"],ng={series:"series",title:"string",color:"color",linewidth:"number",style:"string",trackprice:"boolean",histbase:"number",offset:"number",join:"bool",editable:"boolean",show_last:"number",display:"string",format:"string",precision:"number",force_overlay:"boolean"},rg={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"},ig={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"},sg={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"},ag={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"},ma={color:"color",offset:"number",editable:"boolean",show_last:"number",title:"string",display:"string",force_overlay:"boolean"},og={price:"series",title:"string",color:"color",linestyle:"string",linewidth:"number",editable:"boolean",display:"string"},lg={plot1:"object",plot2:"object",color:"color",title:"string",editable:"boolean",show_last:"number",fillgaps:"boolean",display:"string"},dt=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]=y.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 y.from(e).get(n)}plotchar(...e){let n=ht(e),r=ce(e,Gy,Yy),{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=y.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=ht(e),r=ce(e,Hy,ng),{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=y.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=ht(e),r=ce(e,Zy,rg),{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=y.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=ht(e),r=ce(e,Xy,ig),{series:i,title:s,...a}=r,o=y.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=ht(e),r=ce(e,Qy,sg),{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=[y.from(i).get(0),y.from(s).get(0),y.from(a).get(0),y.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=ht(e),r=ce(e,Jy,ag),{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=[y.from(i).get(0),y.from(s).get(0),y.from(a).get(0),y.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=ht(e),r=ce(e,fa,ma),{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=ht(e),r=ce(e,fa,ma),{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]}};bt([k],dt.prototype,"plotchar",1),bt([k],dt.prototype,"any",1),bt([k],dt.prototype,"plotshape",1),bt([k],dt.prototype,"plotarrow",1),bt([k],dt.prototype,"plotbar",1),bt([k],dt.prototype,"plotcandle",1),bt([k],dt.prototype,"bgcolor",1),bt([k],dt.prototype,"barcolor",1);var wr=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 y.from(e).get(n)}any(...e){let n=ht(e),r=ce(e,eg,og),{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)}};bt([k],wr.prototype,"any",1);var vr=class{constructor(e){this.context=e}param(e,n=0,r){return y.from(e).get(n)}any(...e){let n=ht(e),r=e.length>=6&&typeof e[2]=="number",i=!r&&e.length>=3&&e[2]!==null&&typeof e[2]=="object"&&"top_value"in e[2]?e[2]:null;if(r||i!==null){let s=e[0],a=e[1],o=i?y.from(i.top_value).get(0):e[2],l=i?y.from(i.bottom_value).get(0):e[3],c=i?y.from(i.top_color).get(0):e[4],u=i?y.from(i.bottom_color).get(0):e[5],h=i?i.title||void 0:e.length>6&&typeof e[6]=="string"?e[6]:void 0,p=s?._plotKey||s?.title,d=a?._plotKey||a?.title,f=h||"fill",m=this.context.plots[f];m&&n&&m._callsiteId!==n&&(f=n),this.context.plots[f]||(this.context.plots[f]={title:h||"Fill",plot1:p,plot2:d,data:[],options:{plot1:p,plot2:d,style:"fill",gradient:!0},_plotKey:f,_callsiteId:n}),this.context.plots[f].data.push({time:this.context.marketData[this.context.idx].openTime,value:null,options:{top_value:o,bottom_value:l,top_color:c,bottom_color:u}})}else{let s=ce(e,tg,lg),{plot1:a,plot2:o,color:l,title:c,editable:u,show_last:h,fillgaps:p,display:d}=s,f=c||"fill",m=this.context.plots[f];m&&n&&m._callsiteId!==n&&(f=n);let x=y.from(l).get(0);if(!this.context.plots[f]){let b=a?._plotKey||a?.title,w=o?._plotKey||o?.title;this.context.plots[f]={title:c||"Fill",plot1:b,plot2:w,data:[],options:{plot1:b,plot2:w,color:x,editable:u,show_last:h,fillgaps:p,display:d,style:"fill"},_plotKey:f,_callsiteId:n}}this.context.plots[f].data.push({time:this.context.marketData[this.context.idx].openTime,value:null,options:{color:x}})}}};bt([k],vr.prototype,"any",1);var cg=Object.defineProperty,ug=(t,e,n)=>e in t?cg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,pg=(t,e,n)=>ug(t,typeof e!="symbol"?e+"":e,n),ji=class{constructor(e){this.context=e,pg(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 Oe(r(i),r(s),r(a)??NaN)},from_index(i,s){return new Oe(void 0,r(i),r(s))},from_time(i,s){return new Oe(r(i),void 0,r(s))},copy(i){return i.copy()},now(i){let s=n.idx,a=n.marketData[s]?.openTime;return new Oe(a,s,r(i))}}}param(e,n=0,r){return y.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}},hg=Object.defineProperty,dg=(t,e,n)=>e in t?hg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Te=(t,e,n)=>dg(t,typeof e!="symbol"?e+"":e,n),fg=0,Tn=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){Te(this,"id"),Te(this,"x"),Te(this,"y"),Te(this,"text"),Te(this,"xloc"),Te(this,"yloc"),Te(this,"color"),Te(this,"style"),Te(this,"textcolor"),Te(this,"size"),Te(this,"textalign"),Te(this,"tooltip"),Te(this,"text_font_family"),Te(this,"force_overlay"),Te(this,"_deleted"),Te(this,"_helper"),Te(this,"_createdAtBar",-1),this.id=fg++,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._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){this._helper?this._helper.set_xloc(this,e):this._deleted||(this.xloc=e)}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._deleted||(this.text_font_family=e)}get_x(){return this.x}get_y(){return this.y}get_text(){return this.text}delete(){this._deleted=!0}copy(){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)}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,_deleted:this._deleted}}},yo=Object.defineProperty,mg=Object.getOwnPropertyDescriptor,yg=(t,e,n)=>e in t?yo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Me=(t,e,n,r)=>{for(var i=r>1?void 0:r?mg(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&&yo(e,n,i),i},gg=(t,e,n)=>yg(t,typeof e!="symbol"?e+"":e,n),_g=[["x","y","text","xloc","yloc","color","style","textcolor","size","textalign","tooltip","text_font_family","force_overlay"],["point","text","xloc","yloc","color","style","textcolor","size","textalign","tooltip","text_font_family","force_overlay"]],xg={x:"number",y:"number",text:"string",xloc:"string",yloc:"string",color:"color",style:"string",textcolor:"color",size:"string",textalign:"string",tooltip:"string",text_font_family:"string",force_overlay:"boolean",point:"point"},Ee=class{constructor(e){this.context=e,gg(this,"_labels",[])}param(e,n=0,r){return y.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 Ze)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){let f=new Tn(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);return f._helper=this,f._createdAtBar=this.context.idx,this._labels.push(f),this._enforceMaxCount(),f}_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=ce(e,_g,xg),r,i,s=n.xloc;if(n.point instanceof Oe){let a=n.point,o=a.index!==void 0&&!(typeof a.index=="number"&&isNaN(a.index)),l=a.time!==void 0&&!(typeof a.time=="number"&&isNaN(a.time));o?(r=a.index,s=s||"bi"):l?(r=a.time,s=s||"bt"):(r=0,s=s||"bi"),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)}any(...e){if(e.length===1){let n=e[0];if(n==null||n instanceof Ze||typeof n=="number"&&isNaN(n))return null;if(n instanceof Tn)return n;if(n instanceof y){let r=n.get(0);if(r==null||typeof r=="number"&&isNaN(r))return null;if(r instanceof Tn)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_xloc(e,n){e&&!e._deleted&&(e.xloc=n)}set_yloc(e,n){e&&!e._deleted&&(e.yloc=n)}set_point(e,n){if(e&&!e._deleted&&n){let r=n.index!==void 0&&!(typeof n.index=="number"&&isNaN(n.index)),i=n.time!==void 0&&!(typeof n.time=="number"&&isNaN(n.time));r?(e.x=n.index,e.xloc="bi"):i&&(e.x=n.time,e.xloc="bt"),e.y=n.price}}get_x(e){return e?e.x:NaN}get_y(e){return e?e.y:NaN}get_text(e){return e?e.text:""}copy(e){if(!e)return;let n=e.copy();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"}};Me([k],Ee.prototype,"new",1),Me([k],Ee.prototype,"set_x",1),Me([k],Ee.prototype,"set_y",1),Me([k],Ee.prototype,"set_xy",1),Me([k],Ee.prototype,"set_text",1),Me([k],Ee.prototype,"set_color",1),Me([k],Ee.prototype,"set_textcolor",1),Me([k],Ee.prototype,"set_size",1),Me([k],Ee.prototype,"set_style",1),Me([k],Ee.prototype,"set_textalign",1),Me([k],Ee.prototype,"set_tooltip",1),Me([k],Ee.prototype,"set_xloc",1),Me([k],Ee.prototype,"set_yloc",1),Me([k],Ee.prototype,"set_point",1),Me([k],Ee.prototype,"copy",1),Me([k],Ee.prototype,"delete",1);var bg=Object.defineProperty,wg=(t,e,n)=>e in t?bg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,$e=(t,e,n)=>wg(t,typeof e!="symbol"?e+"":e,n),vg=0,Dn=class t{constructor(e,n,r,i,s="bi",a="none",o="",l="style_solid",c=1,u=!1){$e(this,"id"),$e(this,"x1"),$e(this,"y1"),$e(this,"x2"),$e(this,"y2"),$e(this,"xloc"),$e(this,"extend"),$e(this,"color"),$e(this,"style"),$e(this,"width"),$e(this,"force_overlay"),$e(this,"_deleted"),$e(this,"_helper"),$e(this,"_createdAtBar",-1),this.id=vg++,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.x1}get_y1(){return this.y1}get_x2(){return this.x2}get_y2(){return this.y2}get_price(e){return this._helper?this._helper.get_price(this,e):NaN}delete(){this._deleted=!0}copy(){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}}},go=Object.defineProperty,Eg=Object.getOwnPropertyDescriptor,Sg=(t,e,n)=>e in t?go(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Pe=(t,e,n,r)=>{for(var i=r>1?void 0:r?Eg(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&&go(e,n,i),i},Cg=(t,e,n)=>Sg(t,typeof e!="symbol"?e+"":e,n),Ng=[["x1","y1","x2","y2","xloc","extend","color","style","width","force_overlay"],["first_point","second_point","xloc","extend","color","style","width","force_overlay"]],kg={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"},Se=class{constructor(e){this.context=e,Cg(this,"_lines",[])}param(e,n=0,r){return y.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){let n=e.index!==void 0&&!(typeof e.index=="number"&&isNaN(e.index)),r=e.time!==void 0&&!(typeof e.time=="number"&&isNaN(e.time));return n?{x:e.index,xloc:"bi"}:r?{x:e.time,xloc:"bt"}:{x:0,xloc:"bi"}}_resolve(e){return e==null?e:e instanceof Ze?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 Dn(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=ce(e,Ng,kg),r,i,s,a,o=n.xloc;if(n.first_point instanceof Oe){let l=n.first_point,c=n.second_point,u=this._resolvePoint(l);r=u.x,i=l.price,o=o||u.xloc,c instanceof Oe?(s=this._resolvePoint(c).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 Ze||typeof n=="number"&&isNaN(n))return null;if(n instanceof Dn)return n;if(n instanceof y){let r=n.get(0);if(r==null||typeof r=="number"&&isNaN(r))return null;if(r instanceof Dn)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){if(e&&!e._deleted&&n){let r=this._resolvePoint(n);e.x1=r.x,e.y1=n.price,e.xloc=r.xloc}}set_second_point(e,n){if(e&&!e._deleted&&n){let r=this._resolvePoint(n);e.x2=r.x,e.y2=n.price,e.xloc=r.xloc}}get_x1(e){return e?e.x1:NaN}get_y1(e){return e?e.y1:NaN}get_x2(e){return e?e.x2:NaN}get_y2(e){return e?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.copy();return n._helper=this,n._createdAtBar=this.context.idx,this._lines.push(n),this._enforceMaxCount(),n}delete(e){e&&(e._deleted=!0)}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"}};Pe([k],Se.prototype,"new",1),Pe([k],Se.prototype,"set_x1",1),Pe([k],Se.prototype,"set_y1",1),Pe([k],Se.prototype,"set_x2",1),Pe([k],Se.prototype,"set_y2",1),Pe([k],Se.prototype,"set_xy1",1),Pe([k],Se.prototype,"set_xy2",1),Pe([k],Se.prototype,"set_color",1),Pe([k],Se.prototype,"set_width",1),Pe([k],Se.prototype,"set_style",1),Pe([k],Se.prototype,"set_extend",1),Pe([k],Se.prototype,"set_xloc",1),Pe([k],Se.prototype,"set_first_point",1),Pe([k],Se.prototype,"set_second_point",1),Pe([k],Se.prototype,"copy",1),Pe([k],Se.prototype,"delete",1);var Ig=Object.defineProperty,Ag=(t,e,n)=>e in t?Ig(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,me=(t,e,n)=>Ag(t,typeof e!="symbol"?e+"":e,n),Tg=0,Mn=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",x="wrap_none",b="default",w="format_none",E=!1){me(this,"id"),me(this,"left"),me(this,"top"),me(this,"right"),me(this,"bottom"),me(this,"xloc"),me(this,"extend"),me(this,"border_color"),me(this,"border_style"),me(this,"border_width"),me(this,"bgcolor"),me(this,"text"),me(this,"text_color"),me(this,"text_size"),me(this,"text_halign"),me(this,"text_valign"),me(this,"text_wrap"),me(this,"text_font_family"),me(this,"text_formatting"),me(this,"force_overlay"),me(this,"_deleted"),me(this,"_helper"),me(this,"_createdAtBar",-1),this.id=Tg++,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=x,this.text_font_family=b,this.text_formatting=w,this.force_overlay=E,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.left}get_right(){return this.right}get_top(){return this.top}get_bottom(){return 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 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)}},_o=Object.defineProperty,Dg=Object.getOwnPropertyDescriptor,Mg=(t,e,n)=>e in t?_o(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ue=(t,e,n,r)=>{for(var i=r>1?void 0:r?Dg(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&&_o(e,n,i),i},Pg=(t,e,n)=>Mg(t,typeof e!="symbol"?e+"":e,n),Rg=[["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"]],Fg={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:"string",text_color:"color",text_halign:"string",text_valign:"string",text_wrap:"string",text_font_family:"string",force_overlay:"boolean"},le=class{constructor(e){this.context=e,Pg(this,"_boxes",[])}param(e,n=0,r){return y.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){let n=e.index!==void 0&&!(typeof e.index=="number"&&isNaN(e.index)),r=e.time!==void 0&&!(typeof e.time=="number"&&isNaN(e.time));return n?{x:e.index,xloc:"bi"}:r?{x:e.time,xloc:"bt"}:{x:0,xloc:"bi"}}_resolve(e){return e==null?e:e instanceof Ze?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",x="wrap_none",b="default",w="format_none",E=!1){let v=new Mn(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(x)||"wrap_none",this._resolve(b)||"default",this._resolve(w)||"format_none",E);return v._helper=this,v._createdAtBar=this.context.idx,this._boxes.push(v),this._enforceMaxCount(),v}_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=ce(e,Rg,Fg),r,i,s,a,o=n.xloc;if(n.top_left instanceof Oe){let l=n.top_left,c=n.bottom_right,u=this._resolvePoint(l);r=u.x,i=l.price,o=o||u.xloc,c instanceof Oe?(s=this._resolvePoint(c).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 Ze||typeof n=="number"&&isNaN(n))return null;if(n instanceof Mn)return n;if(n instanceof y){let r=n.get(0);if(r==null||typeof r=="number"&&isNaN(r))return null;if(r instanceof Mn)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){if(e&&!e._deleted&&n){let r=this._resolvePoint(n);e.left=r.x,e.top=n.price,e.xloc=r.xloc}}set_bottom_right_point(e,n){if(e&&!e._deleted&&n){let r=this._resolvePoint(n);e.right=r.x,e.bottom=n.price,e.xloc=r.xloc}}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.left:NaN}get_right(e){return e?e.right:NaN}get_top(e){return e?e.top:NaN}get_bottom(e){return e?e.bottom:NaN}copy(e){if(!e)return;let n=e.copy();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()}};ue([k],le.prototype,"new",1),ue([k],le.prototype,"set_left",1),ue([k],le.prototype,"set_right",1),ue([k],le.prototype,"set_top",1),ue([k],le.prototype,"set_bottom",1),ue([k],le.prototype,"set_lefttop",1),ue([k],le.prototype,"set_rightbottom",1),ue([k],le.prototype,"set_top_left_point",1),ue([k],le.prototype,"set_bottom_right_point",1),ue([k],le.prototype,"set_xloc",1),ue([k],le.prototype,"set_bgcolor",1),ue([k],le.prototype,"set_border_color",1),ue([k],le.prototype,"set_border_width",1),ue([k],le.prototype,"set_border_style",1),ue([k],le.prototype,"set_extend",1),ue([k],le.prototype,"set_text",1),ue([k],le.prototype,"set_text_color",1),ue([k],le.prototype,"set_text_size",1),ue([k],le.prototype,"set_text_halign",1),ue([k],le.prototype,"set_text_valign",1),ue([k],le.prototype,"set_text_wrap",1),ue([k],le.prototype,"set_text_font_family",1),ue([k],le.prototype,"set_text_formatting",1),ue([k],le.prototype,"copy",1),ue([k],le.prototype,"delete",1);var Bg=Object.defineProperty,Lg=(t,e,n)=>e in t?Bg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,un=(t,e,n)=>Lg(t,typeof e!="symbol"?e+"":e,n),Og=0,Er=class{constructor(e,n,r){un(this,"id"),un(this,"line1"),un(this,"line2"),un(this,"color"),un(this,"_deleted"),un(this,"_createdAtBar",-1),this.id=Og++,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){this._deleted||(typeof e=="function"&&(e=e()),e&&typeof e=="object"&&Array.isArray(e.data)&&typeof e.get=="function"&&(e=e.get(0)),this.color=e||"")}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}}},xo=Object.defineProperty,Vg=Object.getOwnPropertyDescriptor,jg=(t,e,n)=>e in t?xo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ui=(t,e,n,r)=>{for(var i=r>1?void 0:r?Vg(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&&xo(e,n,i),i},$g=(t,e,n)=>jg(t,typeof e!="symbol"?e+"":e,n),mn=class{constructor(e){this.context=e,$g(this,"_linefills",[])}param(e,n=0,r){return y.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 Ze?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),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 Er(i,s,o);return l._createdAtBar=this.context.idx,this._linefills.push(l),l}any(...e){if(e.length===1){let n=e[0];return n==null||n instanceof Ze||typeof n=="number"&&isNaN(n)?null:n instanceof Er?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)}get all(){return this._linefills.filter(e=>!e._deleted)}rollbackFromBar(e){this._linefills=this._linefills.filter(n=>n._createdAtBar<e),this.syncToPlot()}};ui([k],mn.prototype,"new",1),ui([k],mn.prototype,"set_color",1),ui([k],mn.prototype,"delete",1);var Wg=Object.defineProperty,Ug=(t,e,n)=>e in t?Wg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Je=(t,e,n)=>Ug(t,typeof e!="symbol"?e+"":e,n),qg=0,Pn=class{constructor(e,n=!1,r=!1,i="bi",s="#2962ff",a="",o="style_solid",l=1,c=!1){Je(this,"id"),Je(this,"points"),Je(this,"curved"),Je(this,"closed"),Je(this,"xloc"),Je(this,"line_color"),Je(this,"fill_color"),Je(this,"line_style"),Je(this,"line_width"),Je(this,"force_overlay"),Je(this,"_deleted"),Je(this,"_createdAtBar",-1),this.id=qg++,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}}},bo=Object.defineProperty,zg=Object.getOwnPropertyDescriptor,Kg=(t,e,n)=>e in t?bo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ya=(t,e,n,r)=>{for(var i=r>1?void 0:r?zg(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&&bo(e,n,i),i},Hg=(t,e,n)=>Kg(t,typeof e!="symbol"?e+"":e,n),$n=class{constructor(e){this.context=e,Hg(this,"_polylines",[])}param(e,n=0,r){return y.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 Ze?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 Oe):[]}new(...e){let n,r=!1,i=!1,s="bi",a="#2962ff",o="",l="style_solid",c=1,u=!1,h=(b,w)=>Object.prototype.hasOwnProperty.call(b,w),p=b=>{h(b,"curved")&&(r=b.curved),h(b,"closed")&&(i=b.closed),h(b,"xloc")&&(s=b.xloc),h(b,"line_color")&&(a=b.line_color),h(b,"fill_color")&&(o=b.fill_color),h(b,"line_style")&&(l=b.line_style),h(b,"line_width")&&(c=b.line_width),h(b,"force_overlay")&&(u=b.force_overlay)},d=e.length>=1?e[e.length-1]:null,f=e.length>=2&&d&&typeof d=="object"&&!Array.isArray(d)&&!(d instanceof y)&&!(d instanceof Oe);if(e.length===1&&d&&typeof d=="object"&&!Array.isArray(d)&&"points"in d)n=d.points,p(d);else{let b=f?e.slice(0,-1):e;n=b[0],b.length>1&&(r=b[1]),b.length>2&&(i=b[2]),b.length>3&&(s=b[3]),b.length>4&&(a=b[4]),b.length>5&&(o=b[5]),b.length>6&&(l=b[6]),b.length>7&&(c=b[7]),b.length>8&&(u=b[8]),f&&p(d)}let m=this._extractPoints(n),x=new Pn(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 x._createdAtBar=this.context.idx,this._polylines.push(x),this._enforceMaxCount(),x}_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 Ze||typeof n=="number"&&isNaN(n))return null;if(n instanceof Pn)return n;if(n instanceof y){let r=n.get(0);if(r==null||typeof r=="number"&&isNaN(r))return null;if(r instanceof Pn)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()}};ya([k],$n.prototype,"new",1),ya([k],$n.prototype,"delete",1);var Gg=Object.defineProperty,Yg=(t,e,n)=>e in t?Gg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,We=(t,e,n)=>Yg(t,typeof e!="symbol"?e+"":e,n),Zg=0,Sr=class{constructor(e="top_right",n=1,r=1,i="",s="",a=0,o="",l=0,c=!1){We(this,"id"),We(this,"position"),We(this,"columns"),We(this,"rows"),We(this,"bgcolor"),We(this,"frame_color"),We(this,"frame_width"),We(this,"border_color"),We(this,"border_width"),We(this,"force_overlay"),We(this,"_deleted"),We(this,"cells"),We(this,"merges"),We(this,"_helper"),this.id=Zg++,this.position=e,this.columns=n,this.rows=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=[],this.cells=[];for(let u=0;u<r;u++){this.cells[u]=[];for(let h=0;h<n;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(n<0||n>=this.rows||e<0||e>=this.columns)return;let i=this.cells[n][e];if(i&&i._merged&&i._merge_parent){let[a,o]=i._merge_parent;if(a===e&&o===n)i._merged=!1,i._merge_parent=void 0;else{this.setCell(a,o,r);return}}let s=i||this._defaultCell();Object.assign(s,r),this.cells[n][e]=s}getCell(e,n){return n<0||n>=this.rows||e<0||e>=this.columns?null:this.cells[n][e]}clearCell(e,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)}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",_merged:!1,_merge_parent:null}}},wo=Object.defineProperty,Xg=Object.getOwnPropertyDescriptor,Qg=(t,e,n)=>e in t?wo(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?Xg(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&&wo(e,n,i),i},Jg=(t,e,n)=>Qg(t,typeof e!="symbol"?e+"":e,n),he=class{constructor(e){this.context=e,Jg(this,"_tables",[])}param(e,n=0,r){return y.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,h=e[e.length-1];if(h&&typeof h=="object"&&!Array.isArray(h)&&("bgcolor"in h||"frame_color"in h||"border_color"in h||"position"in h||"columns"in h||"rows"in h)){let d=h,f=e.slice(0,-1);n=f[0]??d.position??n,r=f[1]??d.columns??r,i=f[2]??d.rows??i,s=d.bgcolor??s,a=d.frame_color??a,o=d.frame_width??o,l=d.border_color??l,c=d.border_width??c,u=d.force_overlay??u}else 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 p=new Sr(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 p._setHelper(this),this._tables.push(p),p}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 Sr?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=e[e.length-1];if(m&&typeof m=="object"&&!Array.isArray(m)&&("text"in m||"bgcolor"in m||"text_color"in m||"text_size"in m||"text_halign"in m||"tooltip"in m||"column"in m||"row"in m||"height"in m||"width"in m||"text_valign"in m||"text_font_family"in m)){let E=m,v=e.slice(0,-1);n=v[0],r=v.length>1?v[1]:E.column??0,i=v.length>2?v[2]:E.row??0,s=v[3]??E.text??s,a=v[4]??E.width??a,o=v[5]??E.height??o,l=v[6]??E.text_color??l,c=v[7]??E.text_halign??c,u=v[8]??E.text_valign??u,h=v[9]??E.text_size??h,p=v[10]??E.bgcolor??p,d=v[11]??E.tooltip??d,f=v[12]??E.text_font_family??f}else 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;let x=this._resolve(n);if(!x||x._deleted)return;let b=this._resolve(r)??0,w=this._resolve(i)??0;x.setCell(b,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"})}delete(e){e&&(e._deleted=!0)}clear(...e){let n,r,i,s,a,o=e[e.length-1];if(o&&typeof o=="object"&&!Array.isArray(o)&&("start_column"in o||"start_row"in o||"end_column"in o)){let d=o;n=e[0],r=e.length>2?e[1]:d.start_column??0,i=e.length>3?e[2]:d.start_row??0,s=d.end_column??(e.length>4?e[3]:r),a=d.end_row??(e.length>5?e[4]:i)}else n=e[0],r=e[1]??0,i=e[2]??0,s=e[3]??r,a=e[4]??i;let l=this._resolve(n);if(!l||l._deleted)return;let c=this._resolve(r)??0,u=this._resolve(i)??0,h=this._resolve(s)??c,p=this._resolve(a)??u;for(let d=u;d<=p;d++)for(let f=c;f<=h;f++)l.clearCell(f,d)}merge_cells(...e){let n,r,i,s,a,o=e[e.length-1];if(o&&typeof o=="object"&&!Array.isArray(o)&&("start_column"in o||"start_row"in o||"end_column"in o)){let d=o;n=e[0],r=e.length>2?e[1]:d.start_column??0,i=e.length>3?e[2]:d.start_row??0,s=d.end_column??(e.length>4?e[3]:0),a=d.end_row??(e.length>5?e[4]:0)}else n=e[0],r=e[1]??0,i=e[2]??0,s=e[3]??0,a=e[4]??0;let l=this._resolve(n);if(!l||l._deleted)return;let c=this._resolve(r)??0,u=this._resolve(i)??0,h=this._resolve(s)??0,p=this._resolve(a)??0;for(let d=u;d<=p;d++)for(let f=c;f<=h;f++)d===u&&f===c||l.setCell(f,d,{_merged:!0,_merge_parent:[c,u]});l.merges.push({startCol:c,startRow:u,endCol:h,endRow:p})}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)}set_position(e,n){let r=this._resolve(e);!r||r._deleted||(r.position=this._resolve(n)||r.position)}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([k],he.prototype,"new",1),ge([k],he.prototype,"cell",1),ge([k],he.prototype,"delete",1),ge([k],he.prototype,"clear",1),ge([k],he.prototype,"merge_cells",1),ge([k],he.prototype,"cell_set_text",1),ge([k],he.prototype,"cell_set_bgcolor",1),ge([k],he.prototype,"cell_set_text_color",1),ge([k],he.prototype,"cell_set_text_size",1),ge([k],he.prototype,"cell_set_height",1),ge([k],he.prototype,"cell_set_width",1),ge([k],he.prototype,"cell_set_tooltip",1),ge([k],he.prototype,"cell_set_text_halign",1),ge([k],he.prototype,"cell_set_text_valign",1),ge([k],he.prototype,"cell_set_text_font_family",1),ge([k],he.prototype,"set_position",1),ge([k],he.prototype,"set_bgcolor",1),ge([k],he.prototype,"set_border_color",1),ge([k],he.prototype,"set_border_width",1),ge([k],he.prototype,"set_frame_color",1),ge([k],he.prototype,"set_frame_width",1);var $i=class{constructor(e){this.context=e}param(e,n=0,r){return typeof e=="string"?e:y.from(e).get(n)}inherit(e,n){let r=this._coerce(e),i=Ot(this._coerce(n)),{modifier:s}=jn(r);return s&&s!=="standard"?Ai(i,s):i}new(e,n,r,i,s,a){let o=this._coerce(e),l=this._coerce(n);return o?l?`${o}:${l}`:o:l}modify(e,n,r,i,s){return this._coerce(e)}standard(e){return e==null?Ot(this.context?.pine?.syminfo?.tickerid||this.context?.tickerId||""):Ot(this._coerce(e))}heikinashi(e){return Ai(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 y){let n=e.get(0);return n==null?"":String(n)}return typeof e=="number"&&isNaN(e)?"":String(e)}},e_=Object.defineProperty,t_=(t,e,n)=>e in t?e_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,G=(t,e,n)=>t_(t,typeof e!="symbol"?e+"":e,n),Wi=class or{constructor({marketData:e,source:n,tickerId:r,timeframe:i,limit:s,sDate:a,eDate:o,fullContext:l,inputs:c}){G(this,"data",{open:new y([]),high:new y([]),low:new y([]),close:new y([]),volume:new y([]),hl2:new y([]),hlc3:new y([]),ohlc4:new y([]),hlcc4:new y([]),bar_index:new y([])}),G(this,"indicator"),G(this,"cache",{}),G(this,"taState",{}),G(this,"strategy"),G(this,"isSecondaryContext",!1),G(this,"chartTimezone",null),G(this,"chartStyle","standard"),G(this,"dataVersion",0),G(this,"__maxLoops",5e5),G(this,"NA",NaN),G(this,"warnings",[]),G(this,"alerts",[]),G(this,"_alertMode","realtime"),G(this,"_propOverrides",{}),G(this,"_execTick",0),G(this,"lang"),G(this,"length",0),G(this,"_drawingHelpers",[]),G(this,"pine"),G(this,"idx",0),G(this,"params",{}),G(this,"const",{}),G(this,"var",{}),G(this,"let",{}),G(this,"lctx",new Map),G(this,"result"),G(this,"plots",{}),G(this,"marketData"),G(this,"source"),G(this,"tickerId"),G(this,"timeframe",""),G(this,"limit"),G(this,"sDate"),G(this,"eDate"),G(this,"fullContext"),G(this,"viewportLeft"),G(this,"viewportRight"),G(this,"pineTSCode"),G(this,"inputs",{}),G(this,"_callStack",[]),G(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 gr(this),h={Type:u.Type.bind(u),na:new Ze,nz:u.nz.bind(u),indicator:u.indicator.bind(u),fixnan:u.fixnan.bind(u),alertcondition:u.alertcondition.bind(u),alert:new yr(this),error:u.error.bind(u),max_bars_back:u.max_bars_back.bind(u),timestamp:u.timestamp.bind(u),time:new mr(this,"openTime"),time_close:new mr(this,"closeTime"),dayofmonth:new xt(this,Ft.dayofmonth),dayofweek:new xt(this,Ft.dayofweek),hour:new xt(this,Ft.hour),minute:new xt(this,Ft.minute),month:new xt(this,Ft.month),second:new xt(this,Ft.second),weekofyear:new xt(this,Ft.weekofyear),year:new xt(this,Ft.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 ki(this),ta:new Pi(this),math:new Ii(this),request:new Mi(this),array:new _i(this),map:new xi(this),matrix:new bi(this),ticker:new $i(this),strategy:new Fi(this),syminfo:null,timeframe:new Vi(this),barstate:new wi(this),session:new Si(this),get bar_index(){return p.data.bar_index},get last_bar_index(){let N=p.marketData;return Array.isArray(N)&&N.length>0?N.length-1:p.data.close.length-1},get last_bar_time(){let N=p.marketData;return Array.isArray(N)&&N.length>0?N[N.length-1].openTime:p.data.openTime.get(0)},get timenow(){return new Date().getTime()},get time_tradingday(){let N=y.from(p.data.closeTime).get(0);if(isNaN(N))return NaN;let j=p.pine?.syminfo?.timezone||"UTC",D=jt(N,j);return Date.UTC(D.year,D.month-1,D.day,0,0,0)},get inputs(){return p.inputs},log:new Bi(this),runtime:new Li(this),str:new Oi(this),...h,...nu};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 dt(this),m=new wr(this),x=new vr(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(x,["any","param"],"fill");let b=new ji(this);this.pine.chart={param:b.param.bind(b),bg_color:b.bg_color.bind(b),fg_color:b.fg_color.bind(b),get is_standard(){return b.is_standard()},get is_heikinashi(){return b.is_heikinashi()},get is_kagi(){return b.is_kagi()},get is_linebreak(){return b.is_linebreak()},get is_pnf(){return b.is_pnf()},get is_range(){return b.is_range()},get is_renko(){return b.is_renko()},point:b.point,get left_visible_bar_time(){if(p.viewportLeft!==void 0)return p.viewportLeft;let N=p.marketData;return Array.isArray(N)&&N.length>0?N[0].openTime:NaN},get right_visible_bar_time(){if(p.viewportRight!==void 0)return p.viewportRight;let N=p.marketData;return Array.isArray(N)&&N.length>0?N[N.length-1].openTime:NaN}};let w=new Ee(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_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:()=>w.all});let E=new Se(this);this.bindContextObject(E,["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:()=>E.all});let v=new le(this);this.bindContextObject(v,["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:()=>v.all});let I=new mn(this);this.bindContextObject(I,["any","new","param","set_color","get_line1","get_line2","delete"],"linefill"),Object.defineProperty(this.pine.linefill,"all",{get:()=>I.all});let C=new $n(this);this.bindContextObject(C,["any","new","param","delete"],"polyline"),Object.defineProperty(this.pine.polyline,"all",{get:()=>C.all});let T=new he(this);this.bindContextObject(T,["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","set_position","set_bgcolor","set_border_color","set_border_width","set_frame_color","set_frame_width"],"table"),Object.defineProperty(this.pine.table,"all",{get:()=>T.all}),this._drawingHelpers=[w,E,v,I,C,T];let O=new Ni(this);this.bindContextObject(O,["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;for(let s of n)typeof e[s]=="function"?i[s]=e[s].bind(e):i[s]=e[s]}init(e,n,r=0){let i;return n instanceof y?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 y?(e.data[e.data.length-1]=i,e):Array.isArray(e)?(e[e.length-1]=i,new y(e)):new y([i]):new y([i])}initVar(e,n){if(e)return e;if(typeof n=="function"&&(n=n()),n instanceof Lt){let i=n.__def__;for(let s in i)typeof n[s]=="function"&&(n[s]=n[s]())}let r;return n instanceof y?r=n.get(0):Array.isArray(n)?Array.isArray(n[0])?r=n[0]:r=this.precision(n[n.length-1]):r=this.precision(n),new y([r])}precision(e,n=10){let r=n===10?or.PRECISION_EPSILON:10**n;return typeof e=="number"?Math.round(e*r)/r:e}param(e,n,r){return typeof e=="string"?e:e instanceof y?n?new y(e.data,e.offset+n):e:!Array.isArray(e)&&typeof e=="object"?e:(this.params[r]||(this.params[r]=[]),Array.isArray(e)?new y(e,n||0):(this.params[r].length===0?this.params[r].push(e):this.params[r][this.params[r].length-1]=e,new y(this.params[r],n||0)))}get(e,n){if(typeof n=="number"&&!Number.isInteger(n)&&(n=Math.trunc(n)),e instanceof y)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 y){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}entries(e){return e==null?[].entries():Array.isArray(e.array)?e.array.entries():e.map instanceof Map?e.map.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}call(e,n,...r){this.pushId(n);try{return e(...r)}finally{this.popId()}}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}`;or._deprecationWarningsShown.has(r)||(or._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`))}};G(Wi,"_deprecationWarningsShown",new Set),G(Wi,"PRECISION_EPSILON",10**10);var _n=Wi,n_=[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],vo=[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],r_="\\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",Eo="\\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",pi={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"},hi="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",i_={5:hi,"5module":hi+" export import",6:hi+" const class extends export import super"},So=/^in(stanceof)?$/,s_=new RegExp("["+Eo+"]"),a_=new RegExp("["+Eo+r_+"]");function Ui(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 Nt(t,e){return t<65?t===36:t<91?!0:t<97?t===95:t<123?!0:t<=65535?t>=170&&s_.test(String.fromCharCode(t)):e===!1?!1:Ui(t,vo)}function $t(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&&a_.test(String.fromCharCode(t)):e===!1?!1:Ui(t,vo)||Ui(t,n_)}var J=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 et(t,e){return new J(t,{beforeExpr:!0,binop:e})}var tt={beforeExpr:!0},Ue={startsExpr:!0},vs={};function Q(t,e){return e===void 0&&(e={}),e.keyword=t,vs[t]=new J(t,e)}var g={num:new J("num",Ue),regexp:new J("regexp",Ue),string:new J("string",Ue),name:new J("name",Ue),privateId:new J("privateId",Ue),eof:new J("eof"),bracketL:new J("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new J("]"),braceL:new J("{",{beforeExpr:!0,startsExpr:!0}),braceR:new J("}"),parenL:new J("(",{beforeExpr:!0,startsExpr:!0}),parenR:new J(")"),comma:new J(",",tt),semi:new J(";",tt),colon:new J(":",tt),dot:new J("."),question:new J("?",tt),questionDot:new J("?."),arrow:new J("=>",tt),template:new J("template"),invalidTemplate:new J("invalidTemplate"),ellipsis:new J("...",tt),backQuote:new J("`",Ue),dollarBraceL:new J("${",{beforeExpr:!0,startsExpr:!0}),eq:new J("=",{beforeExpr:!0,isAssign:!0}),assign:new J("_=",{beforeExpr:!0,isAssign:!0}),incDec:new J("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new J("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:et("||",1),logicalAND:et("&&",2),bitwiseOR:et("|",3),bitwiseXOR:et("^",4),bitwiseAND:et("&",5),equality:et("==/!=/===/!==",6),relational:et("</>/<=/>=",7),bitShift:et("<</>>/>>>",8),plusMin:new J("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:et("%",10),star:et("*",10),slash:et("/",10),starstar:new J("**",{beforeExpr:!0}),coalesce:et("??",1),_break:Q("break"),_case:Q("case",tt),_catch:Q("catch"),_continue:Q("continue"),_debugger:Q("debugger"),_default:Q("default",tt),_do:Q("do",{isLoop:!0,beforeExpr:!0}),_else:Q("else",tt),_finally:Q("finally"),_for:Q("for",{isLoop:!0}),_function:Q("function",Ue),_if:Q("if"),_return:Q("return",tt),_switch:Q("switch"),_throw:Q("throw",tt),_try:Q("try"),_var:Q("var"),_const:Q("const"),_while:Q("while",{isLoop:!0}),_with:Q("with"),_new:Q("new",{beforeExpr:!0,startsExpr:!0}),_this:Q("this",Ue),_super:Q("super",Ue),_class:Q("class",Ue),_extends:Q("extends",tt),_export:Q("export"),_import:Q("import",Ue),_null:Q("null",Ue),_true:Q("true",Ue),_false:Q("false",Ue),_in:Q("in",{beforeExpr:!0,binop:7}),_instanceof:Q("instanceof",{beforeExpr:!0,binop:7}),_typeof:Q("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:Q("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:Q("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},ze=/\\r\\n?|\\n|\\u2028|\\u2029/,o_=new RegExp(ze.source,"g");function xn(t){return t===10||t===13||t===8232||t===8233}function Co(t,e,n){n===void 0&&(n=t.length);for(var r=e;r<n;r++){var i=t.charCodeAt(r);if(xn(i))return r<n-1&&i===13&&t.charCodeAt(r+1)===10?r+2:r+1}return-1}var No=/[\\u1680\\u2000-\\u200a\\u202f\\u205f\\u3000\\ufeff]/,Re=/(?:\\s|\\/\\/.*|\\/\\*[^]*?\\*\\/)*/g,ko=Object.prototype,l_=ko.hasOwnProperty,c_=ko.toString,bn=Object.hasOwn||(function(t,e){return l_.call(t,e)}),ga=Array.isArray||(function(t){return c_.call(t)==="[object Array]"}),_a=Object.create(null);function Bt(t){return _a[t]||(_a[t]=new RegExp("^(?:"+t.replace(/ /g,"|")+")$"))}function Mt(t){return t<=65535?String.fromCharCode(t):(t-=65536,String.fromCharCode((t>>10)+55296,(t&1023)+56320))}var u_=/(?:[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF])/,Wn=function(t,e){this.line=t,this.column=e};Wn.prototype.offset=function(t){return new Wn(this.line,this.column+t)};var Kr=function(t,e,n){this.start=e,this.end=n,t.sourceFile!==null&&(this.source=t.sourceFile)};function Io(t,e){for(var n=1,r=0;;){var i=Co(t,r,e);if(i<0)return new Wn(n,e-r);++n,r=i}}var qi={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},xa=!1;function p_(t){var e={};for(var n in qi)e[n]=t&&bn(t,n)?t[n]:qi[n];if(e.ecmaVersion==="latest"?e.ecmaVersion=1e8:e.ecmaVersion==null?(!xa&&typeof console=="object"&&console.warn&&(xa=!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),ga(e.onToken)){var r=e.onToken;e.onToken=function(i){return r.push(i)}}if(ga(e.onComment)&&(e.onComment=h_(e,e.onComment)),e.sourceType==="commonjs"&&e.allowAwaitOutsideFunction)throw new Error("Cannot use allowAwaitOutsideFunction with sourceType: commonjs");return e}function h_(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 Kr(this,a,o)),t.ranges&&(l.range=[i,s]),e.push(l)}}var Xt=1,Jt=2,Es=4,Ao=8,Ss=16,To=32,Hr=64,Do=128,en=256,zn=512,Mo=1024,Gr=Xt|Jt|en;function Cs(t,e){return Jt|(t?Es:0)|(e?Ao:0)}var Cr=0,Ns=1,Rt=2,Po=3,Ro=4,Fo=5,Ie=function(t,e,n){this.options=t=p_(t),this.sourceFile=t.sourceFile,this.keywords=Bt(i_[t.ecmaVersion>=6?6:t.sourceType==="module"?"5module":5]);var r="";t.allowReserved!==!0&&(r=pi[t.ecmaVersion>=6?6:t.ecmaVersion===5?5:3],t.sourceType==="module"&&(r+=" await")),this.reservedWords=Bt(r);var i=(r?r+" ":"")+pi.strict;this.reservedWordsStrict=Bt(i),this.reservedWordsStrictBind=Bt(i+" "+pi.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(ze).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=g.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"?Jt:Xt),this.regexpState=null,this.privateNameStack=[]},st={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}};Ie.prototype.parse=function(){var t=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(t)};st.inFunction.get=function(){return(this.currentVarScope().flags&Jt)>0};st.inGenerator.get=function(){return(this.currentVarScope().flags&Ao)>0};st.inAsync.get=function(){return(this.currentVarScope().flags&Es)>0};st.canAwait.get=function(){for(var t=this.scopeStack.length-1;t>=0;t--){var e=this.scopeStack[t],n=e.flags;if(n&(en|zn))return!1;if(n&Jt)return(n&Es)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction};st.allowReturn.get=function(){return!!(this.inFunction||this.options.allowReturnOutsideFunction&&this.currentVarScope().flags&Xt)};st.allowSuper.get=function(){var t=this.currentThisScope(),e=t.flags;return(e&Hr)>0||this.options.allowSuperOutsideMethod};st.allowDirectSuper.get=function(){return(this.currentThisScope().flags&Do)>0};st.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())};st.allowNewDotTarget.get=function(){for(var t=this.scopeStack.length-1;t>=0;t--){var e=this.scopeStack[t],n=e.flags;if(n&(en|zn)||n&Jt&&!(n&Ss))return!0}return!1};st.allowUsing.get=function(){var t=this.currentScope(),e=t.flags;return!(e&Mo||!this.inModule&&e&Xt)};st.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&en)>0};Ie.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};Ie.parse=function(t,e){return new this(e,t).parse()};Ie.parseExpressionAt=function(t,e,n){var r=new this(n,t,e);return r.nextToken(),r.parseExpression()};Ie.tokenizer=function(t,e){return new this(e,t)};Object.defineProperties(Ie.prototype,st);var je=Ie.prototype,d_=/^(?:\'((?:\\\\[^]|[^\'\\\\])*?)\'|"((?:\\\\[^]|[^"\\\\])*?)")/;je.strictDirective=function(t){if(this.options.ecmaVersion<5)return!1;for(;;){Re.lastIndex=t,t+=Re.exec(this.input)[0].length;var e=d_.exec(this.input.slice(t));if(!e)return!1;if((e[1]||e[2])==="use strict"){Re.lastIndex=t+e[0].length;var n=Re.exec(this.input),r=n.index+n[0].length,i=this.input.charAt(r);return i===";"||i==="}"||ze.test(n[0])&&!(/[(`.[+\\-/*%<>=,?^&]/.test(i)||i==="!"&&this.input.charAt(r+1)==="=")}t+=e[0].length,Re.lastIndex=t,t+=Re.exec(this.input)[0].length,this.input[t]===";"&&t++}};je.eat=function(t){return this.type===t?(this.next(),!0):!1};je.isContextual=function(t){return this.type===g.name&&this.value===t&&!this.containsEsc};je.eatContextual=function(t){return this.isContextual(t)?(this.next(),!0):!1};je.expectContextual=function(t){this.eatContextual(t)||this.unexpected()};je.canInsertSemicolon=function(){return this.type===g.eof||this.type===g.braceR||ze.test(this.input.slice(this.lastTokEnd,this.start))};je.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0};je.semicolon=function(){!this.eat(g.semi)&&!this.insertSemicolon()&&this.unexpected()};je.afterTrailingComma=function(t,e){if(this.type===t)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),e||this.next(),!0};je.expect=function(t){this.eat(t)||this.unexpected()};je.unexpected=function(t){this.raise(t??this.start,"Unexpected token")};var Yr=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};je.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")}};je.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")};je.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")};je.isSimpleAssignTarget=function(t){return t.type==="ParenthesizedExpression"?this.isSimpleAssignTarget(t.expression):t.type==="Identifier"||t.type==="MemberExpression"};var L=Ie.prototype;L.parseTopLevel=function(t){var e=Object.create(null);for(t.body||(t.body=[]);this.type!==g.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 ks={kind:"loop"},f_={kind:"switch"};L.isLet=function(t){if(this.options.ecmaVersion<6||!this.isContextual("let"))return!1;Re.lastIndex=this.pos;var e=Re.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(Nt(r)){var i=n;do n+=r<=65535?1:2;while($t(r=this.fullCharCodeAt(n)));if(r===92)return!0;var s=this.input.slice(i,n);if(!So.test(s))return!0}return!1};L.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;Re.lastIndex=this.pos;var t=Re.exec(this.input),e=this.pos+t[0].length,n;return!ze.test(this.input.slice(this.pos,e))&&this.input.slice(e,e+8)==="function"&&(e+8===this.input.length||!($t(n=this.fullCharCodeAt(e+8))||n===92))};L.isUsingKeyword=function(t,e){if(this.options.ecmaVersion<17||!this.isContextual(t?"await":"using"))return!1;Re.lastIndex=this.pos;var n=Re.exec(this.input),r=this.pos+n[0].length;if(ze.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||$t(s=this.fullCharCodeAt(i))||s===92)return!1;Re.lastIndex=i;var a=Re.exec(this.input);if(r=i+a[0].length,a&&ze.test(this.input.slice(i,r)))return!1}var o=this.fullCharCodeAt(r);if(!Nt(o)&&o!==92)return!1;var l=r;do r+=o<=65535?1:2;while($t(o=this.fullCharCodeAt(r)));if(o===92)return!0;var c=this.input.slice(l,r);return!(So.test(c)||e&&c==="of")};L.isAwaitUsing=function(t){return this.isUsingKeyword(!0,t)};L.isUsing=function(t){return this.isUsingKeyword(!1,t)};L.parseStatement=function(t,e,n){var r=this.type,i=this.startNode(),s;switch(this.isLet(t)&&(r=g._var,s="let"),r){case g._break:case g._continue:return this.parseBreakContinueStatement(i,r.keyword);case g._debugger:return this.parseDebuggerStatement(i);case g._do:return this.parseDoStatement(i);case g._for:return this.parseForStatement(i);case g._function:return t&&(this.strict||t!=="if"&&t!=="label")&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(i,!1,!t);case g._class:return t&&this.unexpected(),this.parseClass(i,!0);case g._if:return this.parseIfStatement(i);case g._return:return this.parseReturnStatement(i);case g._switch:return this.parseSwitchStatement(i);case g._throw:return this.parseThrowStatement(i);case g._try:return this.parseTryStatement(i);case g._const:case g._var:return s=s||this.value,t&&s!=="var"&&this.unexpected(),this.parseVarStatement(i,s);case g._while:return this.parseWhileStatement(i);case g._with:return this.parseWithStatement(i);case g.braceL:return this.parseBlock(!0,i);case g.semi:return this.parseEmptyStatement(i);case g._export:case g._import:if(this.options.ecmaVersion>10&&r===g._import){Re.lastIndex=this.pos;var a=Re.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===g._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===g.name&&h.type==="Identifier"&&this.eat(g.colon)?this.parseLabeledStatement(i,u,h,t):this.parseExpressionStatement(i,h)}};L.parseBreakContinueStatement=function(t,e){var n=e==="break";this.next(),this.eat(g.semi)||this.insertSemicolon()?t.label=null:this.type!==g.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")};L.parseDebuggerStatement=function(t){return this.next(),this.semicolon(),this.finishNode(t,"DebuggerStatement")};L.parseDoStatement=function(t){return this.next(),this.labels.push(ks),t.body=this.parseStatement("do"),this.labels.pop(),this.expect(g._while),t.test=this.parseParenExpression(),this.options.ecmaVersion>=6?this.eat(g.semi):this.semicolon(),this.finishNode(t,"DoWhileStatement")};L.parseForStatement=function(t){this.next();var e=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(ks),this.enterScope(0),this.expect(g.parenL),this.type===g.semi)return e>-1&&this.unexpected(e),this.parseFor(t,null);var n=this.isLet();if(this.type===g._var||this.type===g._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 Yr,h=this.start,p=e>-1?this.parseExprSubscripts(u,"await"):this.parseExpression(!0,u);return this.type===g._in||(a=this.options.ecmaVersion>=6&&this.isContextual("of"))?(e>-1?(this.type===g._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))};L.parseForAfterInit=function(t,e,n){return(this.type===g._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&e.declarations.length===1?(this.options.ecmaVersion>=9&&(this.type===g._in?n>-1&&this.unexpected(n):t.await=n>-1),this.parseForIn(t,e)):(n>-1&&this.unexpected(n),this.parseFor(t,e))};L.parseFunctionStatement=function(t,e,n){return this.next(),this.parseFunction(t,Rn|(n?0:zi),!1,e)};L.parseIfStatement=function(t){return this.next(),t.test=this.parseParenExpression(),t.consequent=this.parseStatement("if"),t.alternate=this.eat(g._else)?this.parseStatement("if"):null,this.finishNode(t,"IfStatement")};L.parseReturnStatement=function(t){return this.allowReturn||this.raise(this.start,"\'return\' outside of function"),this.next(),this.eat(g.semi)||this.insertSemicolon()?t.argument=null:(t.argument=this.parseExpression(),this.semicolon()),this.finishNode(t,"ReturnStatement")};L.parseSwitchStatement=function(t){this.next(),t.discriminant=this.parseParenExpression(),t.cases=[],this.expect(g.braceL),this.labels.push(f_),this.enterScope(Mo);for(var e,n=!1;this.type!==g.braceR;)if(this.type===g._case||this.type===g._default){var r=this.type===g._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(g.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")};L.parseThrowStatement=function(t){return this.next(),ze.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 m_=[];L.parseCatchClauseParam=function(){var t=this.parseBindingAtom(),e=t.type==="Identifier";return this.enterScope(e?To:0),this.checkLValPattern(t,e?Ro:Rt),this.expect(g.parenR),t};L.parseTryStatement=function(t){if(this.next(),t.block=this.parseBlock(),t.handler=null,this.type===g._catch){var e=this.startNode();this.next(),this.eat(g.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(g._finally)?this.parseBlock():null,!t.handler&&!t.finalizer&&this.raise(t.start,"Missing catch or finally clause"),this.finishNode(t,"TryStatement")};L.parseVarStatement=function(t,e,n){return this.next(),this.parseVar(t,!1,e,n),this.semicolon(),this.finishNode(t,"VariableDeclaration")};L.parseWhileStatement=function(t){return this.next(),t.test=this.parseParenExpression(),this.labels.push(ks),t.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(t,"WhileStatement")};L.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")};L.parseEmptyStatement=function(t){return this.next(),this.finishNode(t,"EmptyStatement")};L.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===g._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")};L.parseExpressionStatement=function(t,e){return t.expression=e,this.semicolon(),this.finishNode(t,"ExpressionStatement")};L.parseBlock=function(t,e,n){for(t===void 0&&(t=!0),e===void 0&&(e=this.startNode()),e.body=[],this.expect(g.braceL),t&&this.enterScope(0);this.type!==g.braceR;){var r=this.parseStatement(null);e.body.push(r)}return n&&(this.strict=!1),this.next(),t&&this.exitScope(),this.finishNode(e,"BlockStatement")};L.parseFor=function(t,e){return t.init=e,this.expect(g.semi),t.test=this.type===g.semi?null:this.parseExpression(),this.expect(g.semi),t.update=this.type===g.parenR?null:this.parseExpression(),this.expect(g.parenR),t.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(t,"ForStatement")};L.parseForIn=function(t,e){var n=this.type===g._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(g.parenR),t.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(t,n?"ForInStatement":"ForOfStatement")};L.parseVar=function(t,e,n,r){for(t.declarations=[],t.kind=n;;){var i=this.startNode();if(this.parseVarId(i,n),this.eat(g.eq)?i.init=this.parseMaybeAssign(e):!r&&n==="const"&&!(this.type===g._in||this.options.ecmaVersion>=6&&this.isContextual("of"))?this.unexpected():!r&&(n==="using"||n==="await using")&&this.options.ecmaVersion>=17&&this.type!==g._in&&!this.isContextual("of")?this.raise(this.lastTokEnd,"Missing initializer in "+n+" declaration"):!r&&i.id.type!=="Identifier"&&!(e&&(this.type===g._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(g.comma))break}return t};L.parseVarId=function(t,e){t.id=e==="using"||e==="await using"?this.parseIdent():this.parseBindingAtom(),this.checkLValPattern(t.id,e==="var"?Ns:Rt,!1)};var Rn=1,zi=2,Bo=4;L.parseFunction=function(t,e,n,r,i){this.initFunction(t),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!r)&&(this.type===g.star&&e&zi&&this.unexpected(),t.generator=this.eat(g.star)),this.options.ecmaVersion>=8&&(t.async=!!r),e&Rn&&(t.id=e&Bo&&this.type!==g.name?null:this.parseIdent(),t.id&&!(e&zi)&&this.checkLValSimple(t.id,this.strict||t.generator||t.async?this.treatFunctionsAsVar?Ns:Rt:Po));var s=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(Cs(t.async,t.generator)),e&Rn||(t.id=this.type===g.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&Rn?"FunctionDeclaration":"FunctionExpression")};L.parseFunctionParams=function(t){this.expect(g.parenL),t.params=this.parseBindingList(g.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()};L.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(g.braceL);this.type!==g.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"&&y_(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")};L.parseClassElement=function(t){if(this.eat(g.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(g.braceL))return this.parseClassStaticBlock(n),n;this.isClassElementNameStart()||this.type===g.star?o=!0:r="static"}if(n.static=o,!r&&e>=8&&this.eatContextual("async")&&((this.isClassElementNameStart()||this.type===g.star)&&!this.canInsertSemicolon()?s=!0:r="async"),!r&&(e>=9||!s)&&this.eat(g.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===g.parenL||a!=="method"||i||s){var c=!n.static&&Nr(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};L.isClassElementNameStart=function(){return this.type===g.name||this.type===g.privateId||this.type===g.num||this.type===g.string||this.type===g.bracketL||this.type.keyword};L.parseClassElementName=function(t){this.type===g.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)};L.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&&Nr(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")};L.parseClassField=function(t){return Nr(t,"constructor")?this.raise(t.key.start,"Classes can\'t have a field named \'constructor\'"):t.static&&Nr(t,"prototype")&&this.raise(t.key.start,"Classes can\'t have a static field named \'prototype\'"),this.eat(g.eq)?(this.enterScope(zn|Hr),t.value=this.parseMaybeAssign(),this.exitScope()):t.value=null,this.semicolon(),this.finishNode(t,"PropertyDefinition")};L.parseClassStaticBlock=function(t){t.body=[];var e=this.labels;for(this.labels=[],this.enterScope(en|Hr);this.type!==g.braceR;){var n=this.parseStatement(null);t.body.push(n)}return this.next(),this.exitScope(),this.labels=e,this.finishNode(t,"StaticBlock")};L.parseClassId=function(t,e){this.type===g.name?(t.id=this.parseIdent(),e&&this.checkLValSimple(t.id,Rt,!1)):(e===!0&&this.unexpected(),t.id=null)};L.parseClassSuper=function(t){t.superClass=this.eat(g._extends)?this.parseExprSubscripts(null,!1):null};L.enterClassBody=function(){var t={declared:Object.create(null),used:[]};return this.privateNameStack.push(t),t.declared};L.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];bn(e,a.name)||(i?i.used.push(a):this.raiseRecoverable(a.start,"Private field \'#"+a.name+"\' must be declared in an enclosing class"))}};function y_(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 Nr(t,e){var n=t.computed,r=t.key;return!n&&(r.type==="Identifier"&&r.name===e||r.type==="Literal"&&r.value===e)}L.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!==g.string&&this.unexpected(),t.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(t.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(t,"ExportAllDeclaration")};L.parseExport=function(t,e){if(this.next(),this.eat(g.star))return this.parseExportAllDeclaration(t,e);if(this.eat(g._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!==g.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")};L.parseExportDeclaration=function(t){return this.parseStatement(null)};L.parseExportDefaultDeclaration=function(){var t;if(this.type===g._function||(t=this.isAsyncFunction())){var e=this.startNode();return this.next(),t&&this.next(),this.parseFunction(e,Rn|Bo,!1,t)}else if(this.type===g._class){var n=this.startNode();return this.parseClass(n,"nullableID")}else{var r=this.parseMaybeAssign();return this.semicolon(),r}};L.checkExport=function(t,e,n){t&&(typeof e!="string"&&(e=e.type==="Identifier"?e.name:e.value),bn(t,e)&&this.raiseRecoverable(n,"Duplicate export \'"+e+"\'"),t[e]=!0)};L.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)};L.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)}};L.shouldParseExportStatement=function(){return this.type.keyword==="var"||this.type.keyword==="const"||this.type.keyword==="class"||this.type.keyword==="function"||this.isLet()||this.isAsyncFunction()};L.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")};L.parseExportSpecifiers=function(t){var e=[],n=!0;for(this.expect(g.braceL);!this.eat(g.braceR);){if(n)n=!1;else if(this.expect(g.comma),this.afterTrailingComma(g.braceR))break;e.push(this.parseExportSpecifier(t))}return e};L.parseImport=function(t){return this.next(),this.type===g.string?(t.specifiers=m_,t.source=this.parseExprAtom()):(t.specifiers=this.parseImportSpecifiers(),this.expectContextual("from"),t.source=this.type===g.string?this.parseExprAtom():this.unexpected()),this.options.ecmaVersion>=16&&(t.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(t,"ImportDeclaration")};L.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,Rt),this.finishNode(t,"ImportSpecifier")};L.parseImportDefaultSpecifier=function(){var t=this.startNode();return t.local=this.parseIdent(),this.checkLValSimple(t.local,Rt),this.finishNode(t,"ImportDefaultSpecifier")};L.parseImportNamespaceSpecifier=function(){var t=this.startNode();return this.next(),this.expectContextual("as"),t.local=this.parseIdent(),this.checkLValSimple(t.local,Rt),this.finishNode(t,"ImportNamespaceSpecifier")};L.parseImportSpecifiers=function(){var t=[],e=!0;if(this.type===g.name&&(t.push(this.parseImportDefaultSpecifier()),!this.eat(g.comma)))return t;if(this.type===g.star)return t.push(this.parseImportNamespaceSpecifier()),t;for(this.expect(g.braceL);!this.eat(g.braceR);){if(e)e=!1;else if(this.expect(g.comma),this.afterTrailingComma(g.braceR))break;t.push(this.parseImportSpecifier())}return t};L.parseWithClause=function(){var t=[];if(!this.eat(g._with))return t;this.expect(g.braceL);for(var e={},n=!0;!this.eat(g.braceR);){if(n)n=!1;else if(this.expect(g.comma),this.afterTrailingComma(g.braceR))break;var r=this.parseImportAttribute(),i=r.key.type==="Identifier"?r.key.name:r.key.value;bn(e,i)&&this.raiseRecoverable(r.key.start,"Duplicate attribute key \'"+i+"\'"),e[i]=!0,t.push(r)}return t};L.parseImportAttribute=function(){var t=this.startNode();return t.key=this.type===g.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never"),this.expect(g.colon),this.type!==g.string&&this.unexpected(),t.value=this.parseExprAtom(),this.finishNode(t,"ImportAttribute")};L.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===g.string){var t=this.parseLiteral(this.value);return u_.test(t.value)&&this.raise(t.start,"An export name cannot include a lone surrogate."),t}return this.parseIdent(!0)};L.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)};L.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 at=Ie.prototype;at.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};at.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};at.parseSpread=function(t){var e=this.startNode();return this.next(),e.argument=this.parseMaybeAssign(!1,t),this.finishNode(e,"SpreadElement")};at.parseRestBinding=function(){var t=this.startNode();return this.next(),this.options.ecmaVersion===6&&this.type!==g.name&&this.unexpected(),t.argument=this.parseBindingAtom(),this.finishNode(t,"RestElement")};at.parseBindingAtom=function(){if(this.options.ecmaVersion>=6)switch(this.type){case g.bracketL:var t=this.startNode();return this.next(),t.elements=this.parseBindingList(g.bracketR,!0,!0),this.finishNode(t,"ArrayPattern");case g.braceL:return this.parseObj(!0)}return this.parseIdent()};at.parseBindingList=function(t,e,n,r){for(var i=[],s=!0;!this.eat(t);)if(s?s=!1:this.expect(g.comma),e&&this.type===g.comma)i.push(null);else{if(n&&this.afterTrailingComma(t))break;if(this.type===g.ellipsis){var a=this.parseRestBinding();this.parseBindingListItem(a),i.push(a),this.type===g.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};at.parseAssignableListItem=function(t){var e=this.parseMaybeDefault(this.start,this.startLoc);return this.parseBindingListItem(e),e};at.parseBindingListItem=function(t){return t};at.parseMaybeDefault=function(t,e,n){if(n=n||this.parseBindingAtom(),this.options.ecmaVersion<6||!this.eat(g.eq))return n;var r=this.startNodeAt(t,e);return r.left=n,r.right=this.parseMaybeAssign(),this.finishNode(r,"AssignmentPattern")};at.checkLValSimple=function(t,e,n){e===void 0&&(e=Cr);var r=e!==Cr;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===Rt&&t.name==="let"&&this.raiseRecoverable(t.start,"let is disallowed as a lexically bound name"),n&&(bn(n,t.name)&&this.raiseRecoverable(t.start,"Argument name clash"),n[t.name]=!0),e!==Fo&&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")}};at.checkLValPattern=function(t,e,n){switch(e===void 0&&(e=Cr),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)}};at.checkLValInnerPattern=function(t,e,n){switch(e===void 0&&(e=Cr),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 ct=function(t,e,n,r,i){this.token=t,this.isExpr=!!e,this.preserveSpace=!!n,this.override=r,this.generator=!!i},de={b_stat:new ct("{",!1),b_expr:new ct("{",!0),b_tmpl:new ct("${",!1),p_stat:new ct("(",!1),p_expr:new ct("(",!0),q_tmpl:new ct("`",!0,!0,function(t){return t.tryReadTemplateToken()}),f_stat:new ct("function",!1),f_expr:new ct("function",!0),f_expr_gen:new ct("function",!0,!1,null,!0),f_gen:new ct("function",!1,!1,null,!0)},wn=Ie.prototype;wn.initialContext=function(){return[de.b_stat]};wn.curContext=function(){return this.context[this.context.length-1]};wn.braceIsBlock=function(t){var e=this.curContext();return e===de.f_expr||e===de.f_stat?!0:t===g.colon&&(e===de.b_stat||e===de.b_expr)?!e.isExpr:t===g._return||t===g.name&&this.exprAllowed?ze.test(this.input.slice(this.lastTokEnd,this.start)):t===g._else||t===g.semi||t===g.eof||t===g.parenR||t===g.arrow?!0:t===g.braceL?e===de.b_stat:t===g._var||t===g._const||t===g.name?!1:!this.exprAllowed};wn.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};wn.updateContext=function(t){var e,n=this.type;n.keyword&&t===g.dot?this.exprAllowed=!1:(e=n.updateContext)?e.call(this,t):this.exprAllowed=n.beforeExpr};wn.overrideContext=function(t){this.curContext()!==t&&(this.context[this.context.length-1]=t)};g.parenR.updateContext=g.braceR.updateContext=function(){if(this.context.length===1){this.exprAllowed=!0;return}var t=this.context.pop();t===de.b_stat&&this.curContext().token==="function"&&(t=this.context.pop()),this.exprAllowed=!t.isExpr};g.braceL.updateContext=function(t){this.context.push(this.braceIsBlock(t)?de.b_stat:de.b_expr),this.exprAllowed=!0};g.dollarBraceL.updateContext=function(){this.context.push(de.b_tmpl),this.exprAllowed=!0};g.parenL.updateContext=function(t){var e=t===g._if||t===g._for||t===g._with||t===g._while;this.context.push(e?de.p_stat:de.p_expr),this.exprAllowed=!0};g.incDec.updateContext=function(){};g._function.updateContext=g._class.updateContext=function(t){t.beforeExpr&&t!==g._else&&!(t===g.semi&&this.curContext()!==de.p_stat)&&!(t===g._return&&ze.test(this.input.slice(this.lastTokEnd,this.start)))&&!((t===g.colon||t===g.braceL)&&this.curContext()===de.b_stat)?this.context.push(de.f_expr):this.context.push(de.f_stat),this.exprAllowed=!1};g.colon.updateContext=function(){this.curContext().token==="function"&&this.context.pop(),this.exprAllowed=!0};g.backQuote.updateContext=function(){this.curContext()===de.q_tmpl?this.context.pop():this.context.push(de.q_tmpl),this.exprAllowed=!1};g.star.updateContext=function(t){if(t===g._function){var e=this.context.length-1;this.context[e]===de.f_expr?this.context[e]=de.f_expr_gen:this.context[e]=de.f_gen}this.exprAllowed=!0};g.name.updateContext=function(t){var e=!1;this.options.ecmaVersion>=6&&t!==g.dot&&(this.value==="of"&&!this.exprAllowed||this.value==="yield"&&this.inGeneratorContext())&&(e=!0),this.exprAllowed=e};var K=Ie.prototype;K.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}};K.parseExpression=function(t,e){var n=this.start,r=this.startLoc,i=this.parseMaybeAssign(t,e);if(this.type===g.comma){var s=this.startNodeAt(n,r);for(s.expressions=[i];this.eat(g.comma);)s.expressions.push(this.parseMaybeAssign(t,e));return this.finishNode(s,"SequenceExpression")}return i};K.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 Yr,r=!0);var o=this.start,l=this.startLoc;(this.type===g.parenL||this.type===g.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===g.eq&&(c=this.toAssignable(c,!1,e)),r||(e.parenthesizedAssign=e.trailingComma=e.doubleProto=-1),e.shorthandAssign>=c.start&&(e.shorthandAssign=-1),this.type===g.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};K.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(g.question)){var s=this.startNodeAt(n,r);return s.test=i,s.consequent=this.parseMaybeAssign(),this.expect(g.colon),s.alternate=this.parseMaybeAssign(t),this.finishNode(s,"ConditionalExpression")}return i};K.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)};K.parseExprOp=function(t,e,n,r,i){var s=this.type.binop;if(s!=null&&(!i||this.type!==g._in)&&s>r){var a=this.type===g.logicalOR||this.type===g.logicalAND,o=this.type===g.coalesce;o&&(s=g.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===g.coalesce||o&&(this.type===g.logicalOR||this.type===g.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};K.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")};K.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===g.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"&&Lo(o.argument)?this.raiseRecoverable(o.start,"Deleting local variable in strict mode"):o.operator==="delete"&&Ki(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===g.privateId)(r||this.privateNameStack.length===0)&&this.options.checkPrivateFields&&this.unexpected(),a=this.parsePrivateIdent(),this.type!==g._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(g.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 Lo(t){return t.type==="Identifier"||t.type==="ParenthesizedExpression"&&Lo(t.expression)}function Ki(t){return t.type==="MemberExpression"&&t.property.type==="PrivateIdentifier"||t.type==="ChainExpression"&&Ki(t.expression)||t.type==="ParenthesizedExpression"&&Ki(t.expression)}K.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};K.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}};K.shouldParseAsyncArrow=function(){return!this.canInsertSemicolon()&&this.eat(g.arrow)};K.parseSubscriptAsyncArrow=function(t,e,n,r){return this.parseArrowExpression(this.startNodeAt(t,e),n,!0,r)};K.parseSubscript=function(t,e,n,r,i,s,a){var o=this.options.ecmaVersion>=11,l=o&&this.eat(g.questionDot);r&&l&&this.raise(this.lastTokStart,"Optional chaining cannot appear in the callee of new expressions");var c=this.eat(g.bracketL);if(c||l&&this.type!==g.parenL&&this.type!==g.backQuote||this.eat(g.dot)){var u=this.startNodeAt(e,n);u.object=t,c?(u.property=this.parseExpression(),this.expect(g.bracketR)):this.type===g.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(g.parenL)){var h=new Yr,p=this.yieldPos,d=this.awaitPos,f=this.awaitIdentPos;this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0;var m=this.parseExprList(g.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 x=this.startNodeAt(e,n);x.callee=t,x.arguments=m,o&&(x.optional=l),t=this.finishNode(x,"CallExpression")}else if(this.type===g.backQuote){(l||s)&&this.raise(this.start,"Optional chaining cannot appear in the tag of tagged template expressions");var b=this.startNodeAt(e,n);b.tag=t,b.quasi=this.parseTemplate({isTagged:!0}),t=this.finishNode(b,"TaggedTemplateExpression")}return t};K.parseExprAtom=function(t,e,n){this.type===g.slash&&this.readRegexp();var r,i=this.potentialArrowAt===this.start;switch(this.type){case g._super:return this.allowSuper||this.raise(this.start,"\'super\' keyword outside a method"),r=this.startNode(),this.next(),this.type===g.parenL&&!this.allowDirectSuper&&this.raise(r.start,"super() call outside constructor of a subclass"),this.type!==g.dot&&this.type!==g.bracketL&&this.type!==g.parenL&&this.unexpected(),this.finishNode(r,"Super");case g._this:return r=this.startNode(),this.next(),this.finishNode(r,"ThisExpression");case g.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(g._function))return this.overrideContext(de.f_expr),this.parseFunction(this.startNodeAt(s,a),0,!1,!0,e);if(i&&!this.canInsertSemicolon()){if(this.eat(g.arrow))return this.parseArrowExpression(this.startNodeAt(s,a),[l],!1,e);if(this.options.ecmaVersion>=8&&l.name==="async"&&this.type===g.name&&!o&&(!this.potentialArrowInForAwait||this.value!=="of"||this.containsEsc))return l=this.parseIdent(!1),(this.canInsertSemicolon()||!this.eat(g.arrow))&&this.unexpected(),this.parseArrowExpression(this.startNodeAt(s,a),[l],!0,e)}return l;case g.regexp:var c=this.value;return r=this.parseLiteral(c.value),r.regex={pattern:c.pattern,flags:c.flags},r;case g.num:case g.string:return this.parseLiteral(this.value);case g._null:case g._true:case g._false:return r=this.startNode(),r.value=this.type===g._null?null:this.type===g._true,r.raw=this.type.keyword,this.next(),this.finishNode(r,"Literal");case g.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 g.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(g.bracketR,!0,!0,t),this.finishNode(r,"ArrayExpression");case g.braceL:return this.overrideContext(de.b_expr),this.parseObj(!1,t);case g._function:return r=this.startNode(),this.next(),this.parseFunction(r,0);case g._class:return this.parseClass(this.startNode(),!1);case g._new:return this.parseNew();case g.backQuote:return this.parseTemplate();case g._import:return this.options.ecmaVersion>=11?this.parseExprImport(n):this.unexpected();default:return this.parseExprAtomDefault()}};K.parseExprAtomDefault=function(){this.unexpected()};K.parseExprImport=function(t){var e=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===g.parenL&&!t)return this.parseDynamicImport(e);if(this.type===g.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()};K.parseDynamicImport=function(t){if(this.next(),t.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(g.parenR)?t.options=null:(this.expect(g.comma),this.afterTrailingComma(g.parenR)?t.options=null:(t.options=this.parseMaybeAssign(),this.eat(g.parenR)||(this.expect(g.comma),this.afterTrailingComma(g.parenR)||this.unexpected())));else if(!this.eat(g.parenR)){var e=this.start;this.eat(g.comma)&&this.eat(g.parenR)?this.raiseRecoverable(e,"Trailing comma is not allowed in import()"):this.unexpected(e)}return this.finishNode(t,"ImportExpression")};K.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")};K.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")};K.parseParenExpression=function(){this.expect(g.parenL);var t=this.parseExpression();return this.expect(g.parenR),t};K.shouldParseArrow=function(t){return!this.canInsertSemicolon()};K.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 Yr,p=this.yieldPos,d=this.awaitPos,f;for(this.yieldPos=0,this.awaitPos=0;this.type!==g.parenR;)if(c?c=!1:this.expect(g.comma),s&&this.afterTrailingComma(g.parenR,!0)){u=!0;break}else if(this.type===g.ellipsis){f=this.start,l.push(this.parseParenItem(this.parseRestBinding())),this.type===g.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,x=this.lastTokEndLoc;if(this.expect(g.parenR),t&&this.shouldParseArrow(l)&&this.eat(g.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,x)):i=l[0]}else i=this.parseParenExpression();if(this.options.preserveParens){var b=this.startNodeAt(n,r);return b.expression=i,this.finishNode(b,"ParenthesizedExpression")}else return i};K.parseParenItem=function(t){return t};K.parseParenArrowList=function(t,e,n,r){return this.parseArrowExpression(this.startNodeAt(t,e),n,!1,r)};var g_=[];K.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===g.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(g.parenL)?t.arguments=this.parseExprList(g.parenR,this.options.ecmaVersion>=8,!1):t.arguments=g_,this.finishNode(t,"NewExpression")};K.parseTemplateElement=function(t){var e=t.isTagged,n=this.startNode();return this.type===g.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===g.backQuote,this.finishNode(n,"TemplateElement")};K.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===g.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(g.dollarBraceL),n.expressions.push(this.parseExpression()),this.expect(g.braceR),n.quasis.push(r=this.parseTemplateElement({isTagged:e}));return this.next(),this.finishNode(n,"TemplateLiteral")};K.isAsyncProp=function(t){return!t.computed&&t.key.type==="Identifier"&&t.key.name==="async"&&(this.type===g.name||this.type===g.num||this.type===g.string||this.type===g.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===g.star)&&!ze.test(this.input.slice(this.lastTokEnd,this.start))};K.parseObj=function(t,e){var n=this.startNode(),r=!0,i={};for(n.properties=[],this.next();!this.eat(g.braceR);){if(r)r=!1;else if(this.expect(g.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(g.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")};K.parseProperty=function(t,e){var n=this.startNode(),r,i,s,a;if(this.options.ecmaVersion>=9&&this.eat(g.ellipsis))return t?(n.argument=this.parseIdent(!1),this.type===g.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===g.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(g.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(g.star),this.parsePropertyName(n)):i=!1,this.parsePropertyValue(n,t,r,i,s,a,e,o),this.finishNode(n,"Property")};K.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")};K.parsePropertyValue=function(t,e,n,r,i,s,a,o){(n||r)&&this.type===g.colon&&this.unexpected(),this.eat(g.colon)?(t.value=e?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,a),t.kind="init"):this.options.ecmaVersion>=6&&this.type===g.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!==g.comma&&this.type!==g.braceR&&this.type!==g.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===g.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()};K.parsePropertyName=function(t){if(this.options.ecmaVersion>=6){if(this.eat(g.bracketL))return t.computed=!0,t.key=this.parseMaybeAssign(),this.expect(g.bracketR),t.key;t.computed=!1}return t.key=this.type===g.num||this.type===g.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never")};K.initFunction=function(t){t.id=null,this.options.ecmaVersion>=6&&(t.generator=t.expression=!1),this.options.ecmaVersion>=8&&(t.async=!1)};K.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(Cs(e,r.generator)|Hr|(n?Do:0)),this.expect(g.parenL),r.params=this.parseBindingList(g.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")};K.parseArrowExpression=function(t,e,n,r){var i=this.yieldPos,s=this.awaitPos,a=this.awaitIdentPos;return this.enterScope(Cs(n,!1)|Ss),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")};K.parseFunctionBody=function(t,e,n,r){var i=e&&this.type!==g.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,Fo),t.body=this.parseBlock(!1,void 0,a&&!s),t.expression=!1,this.adaptDirectivePrologue(t.body.body),this.labels=l}this.exitScope()};K.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};K.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,Ns,e?null:n)}};K.parseExprList=function(t,e,n,r){for(var i=[],s=!0;!this.eat(t);){if(s)s=!1;else if(this.expect(g.comma),e&&this.afterTrailingComma(t))break;var a=void 0;n&&this.type===g.comma?a=null:this.type===g.ellipsis?(a=this.parseSpread(r),r&&this.type===g.comma&&r.trailingComma<0&&(r.trailingComma=this.start)):a=this.parseMaybeAssign(!1,r),i.push(a)}return i};K.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&Gr)&&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"))}};K.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};K.parseIdentNode=function(){var t=this.startNode();return this.type===g.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=g.name):this.unexpected(),t};K.parsePrivateIdent=function(){var t=this.startNode();return this.type===g.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};K.parseYield=function(t){this.yieldPos||(this.yieldPos=this.start);var e=this.startNode();return this.next(),this.type===g.semi||this.canInsertSemicolon()||this.type!==g.star&&!this.type.startsExpr?(e.delegate=!1,e.argument=null):(e.delegate=this.eat(g.star),e.argument=this.parseMaybeAssign(t)),this.finishNode(e,"YieldExpression")};K.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 kr=Ie.prototype;kr.raise=function(t,e){var n=Io(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};kr.raiseRecoverable=kr.raise;kr.curPosition=function(){if(this.options.locations)return new Wn(this.curLine,this.pos-this.lineStart)};var qt=Ie.prototype,__=function(t){this.flags=t,this.var=[],this.lexical=[],this.functions=[]};qt.enterScope=function(t){this.scopeStack.push(new __(t))};qt.exitScope=function(){this.scopeStack.pop()};qt.treatFunctionsAsVarInScope=function(t){return t.flags&Jt||!this.inModule&&t.flags&Xt};qt.declareName=function(t,e,n){var r=!1;if(e===Rt){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&Xt&&delete this.undefinedExports[t]}else if(e===Ro){var s=this.currentScope();s.lexical.push(t)}else if(e===Po){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&To&&l.lexical[0]===t)||!this.treatFunctionsAsVarInScope(l)&&l.functions.indexOf(t)>-1){r=!0;break}if(l.var.push(t),this.inModule&&l.flags&Xt&&delete this.undefinedExports[t],l.flags&Gr)break}r&&this.raiseRecoverable(n,"Identifier \'"+t+"\' has already been declared")};qt.checkLocalExport=function(t){this.scopeStack[0].lexical.indexOf(t.name)===-1&&this.scopeStack[0].var.indexOf(t.name)===-1&&(this.undefinedExports[t.name]=t)};qt.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]};qt.currentVarScope=function(){for(var t=this.scopeStack.length-1;;t--){var e=this.scopeStack[t];if(e.flags&(Gr|zn|en))return e}};qt.currentThisScope=function(){for(var t=this.scopeStack.length-1;;t--){var e=this.scopeStack[t];if(e.flags&(Gr|zn|en)&&!(e.flags&Ss))return e}};var Zr=function(t,e,n){this.type="",this.start=e,this.end=0,t.options.locations&&(this.loc=new Kr(t,n)),t.options.directSourceFile&&(this.sourceFile=t.options.directSourceFile),t.options.ranges&&(this.range=[e,0])},Kn=Ie.prototype;Kn.startNode=function(){return new Zr(this,this.start,this.startLoc)};Kn.startNodeAt=function(t,e){return new Zr(this,t,e)};function Oo(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}Kn.finishNode=function(t,e){return Oo.call(this,t,e,this.lastTokEnd,this.lastTokEndLoc)};Kn.finishNodeAt=function(t,e,n,r){return Oo.call(this,t,e,n,r)};Kn.copyNode=function(t){var e=new Zr(this,t.start,this.startLoc);for(var n in t)e[n]=t[n];return e};var x_="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",Vo="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",jo=Vo+" Extended_Pictographic",$o=jo,Wo=$o+" EBase EComp EMod EPres ExtPict",Uo=Wo,b_=Uo,w_={9:Vo,10:jo,11:$o,12:Wo,13:Uo,14:b_},v_="Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji",E_={9:"",10:"",11:"",12:"",13:"",14:v_},ba="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",qo="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",zo=qo+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",Ko=zo+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",Ho=Ko+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",Go=Ho+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",S_=Go+" "+x_,C_={9:qo,10:zo,11:Ko,12:Ho,13:Go,14:S_},Yo={};function N_(t){var e=Yo[t]={binary:Bt(w_[t]+" "+ba),binaryOfStrings:Bt(E_[t]),nonBinary:{General_Category:Bt(ba),Script:Bt(C_[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(er=0,di=[9,10,11,12,13,14];er<di.length;er+=1)wa=di[er],N_(wa);var wa,er,di,B=Ie.prototype,Ir=function(t,e){this.parent=t,this.base=e||this};Ir.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};Ir.prototype.sibling=function(){return new Ir(this.parent,this.base)};var kt=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=Yo[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};kt.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)};kt.prototype.raise=function(t){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+t)};kt.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};kt.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};kt.prototype.current=function(t){return t===void 0&&(t=!1),this.at(this.pos,t)};kt.prototype.lookahead=function(t){return t===void 0&&(t=!1),this.at(this.nextIndex(this.pos,t),t)};kt.prototype.advance=function(t){t===void 0&&(t=!1),this.pos=this.nextIndex(this.pos,t)};kt.prototype.eat=function(t,e){return e===void 0&&(e=!1),this.current(e)===t?(this.advance(e),!0):!1};kt.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};B.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 k_(t){for(var e in t)return!0;return!1}B.validateRegExpPattern=function(t){this.regexp_pattern(t),!t.switchN&&this.options.ecmaVersion>=9&&k_(t.groupNames)&&(t.switchN=!0,this.regexp_pattern(t))};B.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")}};B.regexp_disjunction=function(t){var e=this.options.ecmaVersion>=16;for(e&&(t.branchID=new Ir(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")};B.regexp_alternative=function(t){for(;t.pos<t.source.length&&this.regexp_eatTerm(t););};B.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};B.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};B.regexp_eatQuantifier=function(t,e){return e===void 0&&(e=!1),this.regexp_eatQuantifierPrefix(t,e)?(t.eat(63),!0):!1};B.regexp_eatQuantifierPrefix=function(t,e){return t.eat(42)||t.eat(43)||t.eat(63)||this.regexp_eatBracedQuantifier(t,e)};B.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};B.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)};B.regexp_eatReverseSolidusAtomEscape=function(t){var e=t.pos;if(t.eat(92)){if(this.regexp_eatAtomEscape(t))return!0;t.pos=e}return!1};B.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};B.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};B.regexp_eatModifiers=function(t){for(var e="",n=0;(n=t.current())!==-1&&I_(n);)e+=Mt(n),t.advance();return e};function I_(t){return t===105||t===109||t===115}B.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)};B.regexp_eatInvalidBracedQuantifier=function(t){return this.regexp_eatBracedQuantifier(t,!0)&&t.raise("Nothing to repeat"),!1};B.regexp_eatSyntaxCharacter=function(t){var e=t.current();return Zo(e)?(t.lastIntValue=e,t.advance(),!0):!1};function Zo(t){return t===36||t>=40&&t<=43||t===46||t===63||t>=91&&t<=94||t>=123&&t<=125}B.regexp_eatPatternCharacters=function(t){for(var e=t.pos,n=0;(n=t.current())!==-1&&!Zo(n);)t.advance();return t.pos!==e};B.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};B.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}};B.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};B.regexp_eatRegExpIdentifierName=function(t){if(t.lastStringValue="",this.regexp_eatRegExpIdentifierStart(t)){for(t.lastStringValue+=Mt(t.lastIntValue);this.regexp_eatRegExpIdentifierPart(t);)t.lastStringValue+=Mt(t.lastIntValue);return!0}return!1};B.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),A_(r)?(t.lastIntValue=r,!0):(t.pos=e,!1)};function A_(t){return Nt(t,!0)||t===36||t===95}B.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),T_(r)?(t.lastIntValue=r,!0):(t.pos=e,!1)};function T_(t){return $t(t,!0)||t===36||t===95||t===8204||t===8205}B.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)};B.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};B.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};B.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)};B.regexp_eatCControlLetter=function(t){var e=t.pos;if(t.eat(99)){if(this.regexp_eatControlLetter(t))return!0;t.pos=e}return!1};B.regexp_eatZero=function(t){return t.current()===48&&!Xr(t.lookahead())?(t.lastIntValue=0,t.advance(),!0):!1};B.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};B.regexp_eatControlLetter=function(t){var e=t.current();return Xo(e)?(t.lastIntValue=e%32,t.advance(),!0):!1};function Xo(t){return t>=65&&t<=90||t>=97&&t<=122}B.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)&&D_(t.lastIntValue))return!0;r&&t.raise("Invalid unicode escape"),t.pos=n}return!1};function D_(t){return t>=0&&t<=1114111}B.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};B.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 Qo=0,Pt=1,rt=2;B.regexp_eatCharacterClassEscape=function(t){var e=t.current();if(M_(e))return t.lastIntValue=-1,t.advance(),Pt;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===rt&&t.raise("Invalid property name"),r;t.raise("Invalid property name")}return Qo};function M_(t){return t===100||t===68||t===115||t===83||t===119||t===87}B.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),Pt}}if(t.pos=e,this.regexp_eatLoneUnicodePropertyNameOrValue(t)){var i=t.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(t,i)}return Qo};B.regexp_validateUnicodePropertyNameAndValue=function(t,e,n){bn(t.unicodeProperties.nonBinary,e)||t.raise("Invalid property name"),t.unicodeProperties.nonBinary[e].test(n)||t.raise("Invalid property value")};B.regexp_validateUnicodePropertyNameOrValue=function(t,e){if(t.unicodeProperties.binary.test(e))return Pt;if(t.switchV&&t.unicodeProperties.binaryOfStrings.test(e))return rt;t.raise("Invalid property name")};B.regexp_eatUnicodePropertyName=function(t){var e=0;for(t.lastStringValue="";Jo(e=t.current());)t.lastStringValue+=Mt(e),t.advance();return t.lastStringValue!==""};function Jo(t){return Xo(t)||t===95}B.regexp_eatUnicodePropertyValue=function(t){var e=0;for(t.lastStringValue="";P_(e=t.current());)t.lastStringValue+=Mt(e),t.advance();return t.lastStringValue!==""};function P_(t){return Jo(t)||Xr(t)}B.regexp_eatLoneUnicodePropertyNameOrValue=function(t){return this.regexp_eatUnicodePropertyValue(t)};B.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===rt&&t.raise("Negated character class may contain strings"),!0}return!1};B.regexp_classContents=function(t){return t.current()===93?Pt:t.switchV?this.regexp_classSetExpression(t):(this.regexp_nonEmptyClassRanges(t),Pt)};B.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")}}};B.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||nl(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};B.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)};B.regexp_classSetExpression=function(t){var e=Pt,n;if(!this.regexp_eatClassSetRange(t))if(n=this.regexp_eatClassSetOperand(t)){n===rt&&(e=rt);for(var r=t.pos;t.eatChars([38,38]);){if(t.current()!==38&&(n=this.regexp_eatClassSetOperand(t))){n!==rt&&(e=Pt);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===rt&&(e=rt)}};B.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};B.regexp_eatClassSetOperand=function(t){return this.regexp_eatClassSetCharacter(t)?Pt:this.regexp_eatClassStringDisjunction(t)||this.regexp_eatNestedClass(t)};B.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===rt&&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};B.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};B.regexp_classStringDisjunctionContents=function(t){for(var e=this.regexp_classString(t);t.eat(124);)this.regexp_classString(t)===rt&&(e=rt);return e};B.regexp_classString=function(t){for(var e=0;this.regexp_eatClassSetCharacter(t);)e++;return e===1?Pt:rt};B.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()&&R_(n)||F_(n)?!1:(t.advance(),t.lastIntValue=n,!0)};function R_(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 F_(t){return t===40||t===41||t===45||t===47||t>=91&&t<=93||t>=123&&t<=125}B.regexp_eatClassSetReservedPunctuator=function(t){var e=t.current();return B_(e)?(t.lastIntValue=e,t.advance(),!0):!1};function B_(t){return t===33||t===35||t===37||t===38||t===44||t===45||t>=58&&t<=62||t===64||t===96||t===126}B.regexp_eatClassControlLetter=function(t){var e=t.current();return Xr(e)||e===95?(t.lastIntValue=e%32,t.advance(),!0):!1};B.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};B.regexp_eatDecimalDigits=function(t){var e=t.pos,n=0;for(t.lastIntValue=0;Xr(n=t.current());)t.lastIntValue=10*t.lastIntValue+(n-48),t.advance();return t.pos!==e};function Xr(t){return t>=48&&t<=57}B.regexp_eatHexDigits=function(t){var e=t.pos,n=0;for(t.lastIntValue=0;el(n=t.current());)t.lastIntValue=16*t.lastIntValue+tl(n),t.advance();return t.pos!==e};function el(t){return t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102}function tl(t){return t>=65&&t<=70?10+(t-65):t>=97&&t<=102?10+(t-97):t-48}B.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};B.regexp_eatOctalDigit=function(t){var e=t.current();return nl(e)?(t.lastIntValue=e-48,t.advance(),!0):(t.lastIntValue=0,!1)};function nl(t){return t>=48&&t<=55}B.regexp_eatFixedHexDigits=function(t,e){var n=t.pos;t.lastIntValue=0;for(var r=0;r<e;++r){var i=t.current();if(!el(i))return t.pos=n,!1;t.lastIntValue=16*t.lastIntValue+tl(i),t.advance()}return!0};var Is=function(t){this.type=t.type,this.value=t.value,this.start=t.start,this.end=t.end,t.options.locations&&(this.loc=new Kr(t,t.startLoc,t.endLoc)),t.options.ranges&&(this.range=[t.start,t.end])},X=Ie.prototype;X.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 Is(this)),this.lastTokEnd=this.end,this.lastTokStart=this.start,this.lastTokEndLoc=this.endLoc,this.lastTokStartLoc=this.startLoc,this.nextToken()};X.getToken=function(){return this.next(),new Is(this)};typeof Symbol<"u"&&(X[Symbol.iterator]=function(){var t=this;return{next:function(){var e=t.getToken();return{done:e.type===g.eof,value:e}}}});X.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(g.eof);if(t.override)return t.override(this);this.readToken(this.fullCharCodeAtPos())};X.readToken=function(t){return Nt(t,this.options.ecmaVersion>=6)||t===92?this.readWord():this.getTokenFromCode(t)};X.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};X.fullCharCodeAtPos=function(){return this.fullCharCodeAt(this.pos)};X.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=Co(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())};X.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&&!xn(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())};X.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&&No.test(String.fromCharCode(t)))++this.pos;else break e}}};X.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)};X.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(g.ellipsis)):(++this.pos,this.finishToken(g.dot))};X.readToken_slash=function(){var t=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):t===61?this.finishOp(g.assign,2):this.finishOp(g.slash,1)};X.readToken_mult_modulo_exp=function(t){var e=this.input.charCodeAt(this.pos+1),n=1,r=t===42?g.star:g.modulo;return this.options.ecmaVersion>=7&&t===42&&e===42&&(++n,r=g.starstar,e=this.input.charCodeAt(this.pos+2)),e===61?this.finishOp(g.assign,n+1):this.finishOp(r,n)};X.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(g.assign,3)}return this.finishOp(t===124?g.logicalOR:g.logicalAND,2)}return e===61?this.finishOp(g.assign,2):this.finishOp(t===124?g.bitwiseOR:g.bitwiseAND,1)};X.readToken_caret=function(){var t=this.input.charCodeAt(this.pos+1);return t===61?this.finishOp(g.assign,2):this.finishOp(g.bitwiseXOR,1)};X.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||ze.test(this.input.slice(this.lastTokEnd,this.pos)))?(this.skipLineComment(3),this.skipSpace(),this.nextToken()):this.finishOp(g.incDec,2):e===61?this.finishOp(g.assign,2):this.finishOp(g.plusMin,1)};X.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(g.assign,n+1):this.finishOp(g.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(g.relational,n))};X.readToken_eq_excl=function(t){var e=this.input.charCodeAt(this.pos+1);return e===61?this.finishOp(g.equality,this.input.charCodeAt(this.pos+2)===61?3:2):t===61&&e===62&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(g.arrow)):this.finishOp(t===61?g.eq:g.prefix,1)};X.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(g.questionDot,2)}if(e===63){if(t>=12){var r=this.input.charCodeAt(this.pos+2);if(r===61)return this.finishOp(g.assign,3)}return this.finishOp(g.coalesce,2)}}return this.finishOp(g.question,1)};X.readToken_numberSign=function(){var t=this.options.ecmaVersion,e=35;if(t>=13&&(++this.pos,e=this.fullCharCodeAtPos(),Nt(e,!0)||e===92))return this.finishToken(g.privateId,this.readWord1());this.raise(this.pos,"Unexpected character \'"+Mt(e)+"\'")};X.getTokenFromCode=function(t){switch(t){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(g.parenL);case 41:return++this.pos,this.finishToken(g.parenR);case 59:return++this.pos,this.finishToken(g.semi);case 44:return++this.pos,this.finishToken(g.comma);case 91:return++this.pos,this.finishToken(g.bracketL);case 93:return++this.pos,this.finishToken(g.bracketR);case 123:return++this.pos,this.finishToken(g.braceL);case 125:return++this.pos,this.finishToken(g.braceR);case 58:return++this.pos,this.finishToken(g.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(g.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(g.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character \'"+Mt(t)+"\'")};X.finishOp=function(t,e){var n=this.input.slice(this.pos,this.pos+e);return this.pos+=e,this.finishToken(t,n)};X.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(ze.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 kt(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(g.regexp,{pattern:i,flags:a,value:l})};X.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 L_(t,e){return e?parseInt(t,8):parseFloat(t.replace(/_/g,""))}function rl(t){return typeof BigInt!="function"?null:BigInt(t.replace(/_/g,""))}X.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=rl(this.input.slice(e,this.pos)),++this.pos):Nt(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(g.num,n)};X.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=rl(this.input.slice(e,this.pos));return++this.pos,Nt(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(g.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")),Nt(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var s=L_(this.input.slice(e,this.pos),n);return this.finishToken(g.num,s)};X.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};X.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)):(xn(r)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return e+=this.input.slice(n,this.pos++),this.finishToken(g.string,e)};var il={};X.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(t){if(t===il)this.readInvalidTemplateToken();else throw t}this.inTemplateElement=!1};X.invalidStringToken=function(t,e){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw il;this.raise(t,e)};X.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===g.template||this.type===g.invalidTemplate)?n===36?(this.pos+=2,this.finishToken(g.dollarBraceL)):(++this.pos,this.finishToken(g.backQuote)):(t+=this.input.slice(e,this.pos),this.finishToken(g.template,t));if(n===92)t+=this.input.slice(e,this.pos),t+=this.readEscapedChar(!0),e=this.pos;else if(xn(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}};X.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(g.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")};X.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 Mt(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 xn(e)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(e)}};X.readHexChar=function(t){var e=this.pos,n=this.readInt(16,t);return n===null&&this.invalidStringToken(e,"Bad character escape sequence"),n};X.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($t(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?Nt:$t)(a,r)||this.invalidStringToken(s,"Invalid Unicode escape"),t+=Mt(a),n=this.pos}else break;e=!1}return t+this.input.slice(n,this.pos)};X.readWord=function(){var t=this.readWord1(),e=g.name;return this.keywords.test(t)&&(e=vs[t]),this.finishToken(e,t)};var O_="8.16.0";Ie.acorn={Parser:Ie,version:O_,defaultOptions:qi,Position:Wn,SourceLocation:Kr,getLineInfo:Io,Node:Zr,TokenType:J,tokTypes:g,keywordTypes:vs,TokContext:ct,tokContexts:de,isIdentifierChar:$t,isIdentifierStart:Nt,Token:Is,isNewLine:xn,lineBreak:ze,lineBreakG:o_,nonASCIIwhitespace:No};function As(t,e){return Ie.parse(t,e)}var{stringify:V_}=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 tr={"||":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},ft=17,j_={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:ft,ClassExpression:ft,FunctionExpression:ft,ObjectExpression:ft,UpdateExpression:16,UnaryExpression:15,AwaitExpression:15,BinaryExpression:14,LogicalExpression:13,ConditionalExpression:4,AssignmentExpression:3,YieldExpression:2,RestElement:1};function pn(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 sl(t,e,n,r){let i=t.expressionsPrecedence[e.type];if(i===ft)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?tr[e.operator]<=tr[n.operator]:tr[e.operator]<tr[n.operator]}function nr(t,e,n,r){let{generator:i}=t;sl(t,e,n,r)?(t.write("("),i[e.type](e,t),t.write(")")):i[e.type](e,t)}function $_(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 Le(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("/*"),$_(t,a.value,n,r),t.write("*/"+r))}}function W_(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 fi(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 va,Ea,Sa,Ca,Na,ka,Ts={Program(t,e){let n=e.indent.repeat(e.indentLevel),{lineEnd:r,writeComments:i}=e;i&&t.comments!=null&&Le(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&&Le(e,l.comments,n,r),e.write(n),this[l.type](l,e),e.write(r)}i&&t.trailingComments!=null&&Le(e,t.trailingComments,n,r)},BlockStatement:ka=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&&Le(e,t.comments,s,r);let{length:o}=a;for(let l=0;l<o;l++){let c=a[l];i&&c.comments!=null&&Le(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),Le(e,t.comments,s,r),e.write(n));i&&t.trailingComments!=null&&Le(e,t.trailingComments,s,r),e.write("}"),e.indentLevel--},ClassBody:ka,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===ft||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&&Le(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&&Le(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"?fi(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:va=function(t,e){e.write(`for ${t.await?"await ":""}(`);let{left:n}=t;n.type[0]==="V"?fi(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:va,DebuggerStatement(t,e){e.write("debugger;",t)},FunctionDeclaration:Ea=function(t,e){e.write((t.async?"async ":"")+(t.generator?"function* ":"function ")+(t.id?t.id.name:""),t),pn(e,t.params),e.write(" "),this[t.body.type](t.body,e)},FunctionExpression:Ea,VariableDeclaration(t,e){fi(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===ft||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),pn(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]):pn(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:Sa=function(t,e){e.write("..."),this[t.argument.type](t.argument,e)},SpreadElement:Sa,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),nr(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){nr(e,t.tag,t),this[t.quasi.type](t.quasi,e)},ArrayExpression:Na=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:Na,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&&Le(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&&Le(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&&Le(e,t.trailingComments,s,r),e.write(n+"}")}else i?t.comments!=null?(e.write(r),Le(e,t.comments,s,r),t.trailingComments!=null&&Le(e,t.trailingComments,s,r),e.write(n+"}")):t.trailingComments!=null?(e.write(r),Le(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){pn(e,t.expressions)},UnaryExpression(t,e){if(t.prefix){let{operator:n,argument:r,argument:{type:i}}=t;e.write(n);let s=sl(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:Ca=function(t,e){let n=t.operator==="in";n&&e.write("("),nr(e,t.left,t,!1),e.write(" "+t.operator+" "),nr(e,t.right,t,!0),n&&e.write(")")},LogicalExpression:Ca,ConditionalExpression(t,e){let{test:n}=t,r=e.expressionsPrecedence[n.type];r===ft||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===ft||n<e.expressionsPrecedence.CallExpression||W_(t.callee)?(e.write("("),this[t.callee.type](t.callee,e),e.write(")")):this[t.callee.type](t.callee,e),pn(e,t.arguments)},CallExpression(t,e){let n=e.expressionsPrecedence[t.callee.type];n===ft||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("?."),pn(e,t.arguments)},ChainExpression(t,e){this[t.expression.type](t.expression,e)},MemberExpression(t,e){let n=e.expressionsPrecedence[t.object.type];n===ft||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(V_(t.value),t)},RegExpLiteral(t,e){let{regex:n}=t;e.write(`/${n.pattern}/${n.flags}`,t)}},U_={},q_=Ts,Hi=class{constructor(e){let n=e??U_;this.output="",n.output!=null?(this.output=n.output,this.write=this.writeToStream):this.output="",this.generator=n.generator!=null?n.generator:Ts,this.expressionsPrecedence=n.expressionsPrecedence!=null?n.expressionsPrecedence:j_,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 Ds(t,e){let n=new Hi(e);return n.generator[t.type](t,n),n.output}var z_=Object.defineProperty,K_=(t,e,n)=>e in t?z_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,re=(t,e,n)=>K_(t,typeof e!="symbol"?e+"":e,n),H_=new Set(["Infinity","NaN","undefined","null","true","false"]),G_=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"]),Gi=class{constructor(){re(this,"scopes",[]),re(this,"scopeTypes",[]),re(this,"scopeCounts",new Map),re(this,"contextBoundVars",new Set),re(this,"arrayPatternElements",new Set),re(this,"rootParams",new Set),re(this,"localSeriesVars",new Set),re(this,"varKinds",new Map),re(this,"loopVars",new Set),re(this,"loopVarNames",new Map),re(this,"paramIdCounter",0),re(this,"cacheIdCounter",0),re(this,"tempVarCounter",0),re(this,"taCallIdCounter",0),re(this,"userCallIdCounter",0),re(this,"plotCallIdCounter",0),re(this,"alertCallIdCounter",0),re(this,"loopGuardCounter",0),re(this,"hoistingStack",[]),re(this,"suppressHoisting",!1),re(this,"reservedNames",new Set),re(this,"userFunctions",new Set),re(this,"userMethods",new Set),re(this,"regularUserFunctions",new Set),re(this,"udtTypeNames",new Map),re(this,"udtInstances",new Map),re(this,"functionReturnTypes",new Map),re(this,"functionReturnTupleTypes",new Map),re(this,"functionParamUdtTypes",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++}`}}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)}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)}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 H_.has(e)||G_.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}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.hoistingStack[this.hoistingStack.length-1].push(e)}addOuterHoistedStatement(e){if(this.hoistingStack.length>0&&!this.suppressHoisting){let n=Math.min(1,this.hoistingStack.length-1);this.hoistingStack[n].push(e)}}getCurrentHoistingScope(){return this.hoistingStack.length===0?null:this.hoistingStack[this.hoistingStack.length-1]}setSuppressHoisting(e){this.suppressHoisting=e}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 mt(t,e,n,r,i){n||(n=A),(function s(a,o,l){var c=l||a.type;ol(n,c,a,o,s),e[c]&&e[c](a,o)})(t,r,i)}function al(t,e,n,r,i){var s=[];n||(n=A),(function a(o,l,c){var u=c||o.type,h=o!==s[s.length-1];h&&s.push(o),ol(n,u,o,l,a),e[u]&&e[u](o,l||s,s),h&&s.pop()})(t,r,i)}function Ne(t,e,n,r,i){var s=n?Y_(n,r||void 0):r;(function a(o,l,c){s[c||o.type](o,l,a)})(t,e,i)}function Y_(t,e){var n=Object.create(e||A);for(var r in t)n[r]=t[r];return n}function Ms(t,e,n){n(t,e)}function tn(t,e,n){}function ol(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 A={};A.Program=A.BlockStatement=A.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")}};A.Statement=Ms;A.EmptyStatement=tn;A.ExpressionStatement=A.ParenthesizedExpression=A.ChainExpression=function(t,e,n){return n(t.expression,e,"Expression")};A.IfStatement=function(t,e,n){n(t.test,e,"Expression"),n(t.consequent,e,"Statement"),t.alternate&&n(t.alternate,e,"Statement")};A.LabeledStatement=function(t,e,n){return n(t.body,e,"Statement")};A.BreakStatement=A.ContinueStatement=tn;A.WithStatement=function(t,e,n){n(t.object,e,"Expression"),n(t.body,e,"Statement")};A.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)}};A.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")}};A.ReturnStatement=A.YieldExpression=A.AwaitExpression=function(t,e,n){t.argument&&n(t.argument,e,"Expression")};A.ThrowStatement=A.SpreadElement=function(t,e,n){return n(t.argument,e,"Expression")};A.TryStatement=function(t,e,n){n(t.block,e,"Statement"),t.handler&&n(t.handler,e),t.finalizer&&n(t.finalizer,e,"Statement")};A.CatchClause=function(t,e,n){t.param&&n(t.param,e,"Pattern"),n(t.body,e,"Statement")};A.WhileStatement=A.DoWhileStatement=function(t,e,n){n(t.test,e,"Expression"),n(t.body,e,"Statement")};A.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")};A.ForInStatement=A.ForOfStatement=function(t,e,n){n(t.left,e,"ForInit"),n(t.right,e,"Expression"),n(t.body,e,"Statement")};A.ForInit=function(t,e,n){t.type==="VariableDeclaration"?n(t,e):n(t,e,"Expression")};A.DebuggerStatement=tn;A.FunctionDeclaration=function(t,e,n){return n(t,e,"Function")};A.VariableDeclaration=function(t,e,n){for(var r=0,i=t.declarations;r<i.length;r+=1){var s=i[r];n(s,e)}};A.VariableDeclarator=function(t,e,n){n(t.id,e,"Pattern"),t.init&&n(t.init,e,"Expression")};A.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")};A.Pattern=function(t,e,n){t.type==="Identifier"?n(t,e,"VariablePattern"):t.type==="MemberExpression"?n(t,e,"MemberPattern"):n(t,e)};A.VariablePattern=tn;A.MemberPattern=Ms;A.RestElement=function(t,e,n){return n(t.argument,e,"Pattern")};A.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")}};A.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")}};A.Expression=Ms;A.ThisExpression=A.Super=A.MetaProperty=tn;A.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")}};A.ObjectExpression=function(t,e,n){for(var r=0,i=t.properties;r<i.length;r+=1){var s=i[r];n(s,e)}};A.FunctionExpression=A.ArrowFunctionExpression=A.FunctionDeclaration;A.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")}};A.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")}};A.TemplateElement=tn;A.UnaryExpression=A.UpdateExpression=function(t,e,n){n(t.argument,e,"Expression")};A.BinaryExpression=A.LogicalExpression=function(t,e,n){n(t.left,e,"Expression"),n(t.right,e,"Expression")};A.AssignmentExpression=A.AssignmentPattern=function(t,e,n){n(t.left,e,"Pattern"),n(t.right,e,"Expression")};A.ConditionalExpression=function(t,e,n){n(t.test,e,"Expression"),n(t.consequent,e,"Expression"),n(t.alternate,e,"Expression")};A.NewExpression=A.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")}};A.MemberExpression=function(t,e,n){n(t.object,e,"Expression"),t.computed&&n(t.property,e,"Expression")};A.ExportNamedDeclaration=A.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)}};A.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)}};A.ImportAttribute=function(t,e,n){n(t.value,e,"Expression")};A.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)}};A.ImportExpression=function(t,e,n){n(t.source,e,"Expression"),t.options&&n(t.options,e,"Expression")};A.ImportSpecifier=A.ImportDefaultSpecifier=A.ImportNamespaceSpecifier=A.Identifier=A.PrivateIdentifier=A.Literal=tn;A.TaggedTemplateExpression=function(t,e,n){n(t.tag,e,"Expression"),n(t.quasi,e,"Expression")};A.ClassDeclaration=A.ClassExpression=function(t,e,n){return n(t,e,"Class")};A.Class=function(t,e,n){t.id&&n(t.id,e,"Pattern"),t.superClass&&n(t.superClass,e,"Expression"),n(t.body,e)};A.ClassBody=function(t,e,n){for(var r=0,i=t.body;r<i.length;r+=1){var s=i[r];n(s,e)}};A.MethodDefinition=A.PropertyDefinition=A.Property=function(t,e,n){t.computed&&n(t.key,e,"Expression"),t.value&&n(t.value,e,"Expression")};var ye="$",S={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){let n=this.createMemberExpression(this.createContextIdentifier(),this.createIdentifier("initVar"),!1),r=[t,e];return this.createCallExpression(n,r)},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}}},Wt=["ta","math","request","array","input","color","ticker","strategy"],yt=["hline","plot","fill","label","line","box","linefill","polyline","table","na","alert","time","time_close","dayofmonth","dayofweek","hour","minute","month","second","weekofyear","year"],Z_=["request.security","request.security_lower_tf"],X_=["chart.left_visible_bar_time","chart.right_visible_bar_time"],Ia=["plot","hline","fill","strategy.exit"],Q_=["line.new","line.copy","label.new","label.copy","polyline.new","box.new","box.copy","table.new","linefill.new"],J_=new Set([...Wt,"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","position","font","order","currency","dayofweek","adjustment","barmerge"]),Aa=new Set(["await","debugger","default","delete","extends","finally","function","implements","instanceof","interface","let","new","package","private","protected","public","static","super","throw","typeof","void","with","yield"]),ll=["open","high","low","close","volume","hl2","hlc3","ohlc4","hlcc4","openTime","closeTime"],Ps=[...Wt,"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","Type","bool","int","float","string","timeframe","syminfo","barstate","session","bar_index","last_bar_index","last_bar_time","timenow","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","barmerge","adjustment","backadjustment","earnings","dividends","splits"],e0=["na","nz","plot","plotchar","color","hline","fill"];function t0(t){let e=null,n=ye;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)})};Ne(t,{},{VariableDeclarator(d,f,m){s(d.id),d.init&&m(d.init,f)},FunctionDeclaration(d,f,m){s(d.id);for(let x of d.params)x&&x.type==="AssignmentPattern"&&x.right&&m(x.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=ll,o=Ps,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 n0(t){let e=null,n=ye;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(ll),i=new Set(Ps),s=new Set(e0),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"&&Wt.includes(c)){let h=c,p=l.id.name;h!==p&&(a.set(p,h),l.id.name=h)}}})}),a.size>0&&Ne(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 r0(t){try{let e=As(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 i0(t){return t.async=!0,Ds(t)}function s0(t){t=t.trim();let{isWrapped:e,isAsync:n,functionNode:r}=r0(t);return e&&r?n?t:i0(r):`async (context) => {\n${t}\n}`}function a0(t){Ne(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 o0(t,e){mt(t,{VariableDeclaration(r){for(let i of r.declarations)if(!(i.id?.type!=="Identifier"||!i.init)&&i.init.type==="CallExpression"&&i.init.callee?.type==="Identifier"&&i.init.callee.name==="Type"&&i.init.arguments?.length===1&&i.init.arguments[0]?.type==="ObjectExpression"){let s={};for(let a of i.init.arguments[0].properties)a.type!=="Property"||a.key?.type!=="Identifier"||(a.value?.type==="ArrayExpression"&&a.value.elements?.[0]?.type==="Literal"?s[a.key.name]=String(a.value.elements[0].value):a.value?.type==="Literal"&&(s[a.key.name]=String(a.value.value)));e.addUdtTypeName(i.id.name,s)}}});let n=!0;for(;n;)n=!1,mt(t,{FunctionDeclaration(r){if(!r.id?.name)return;let i=r.id.name;if(e.getFunctionReturnType(i)||e.getFunctionReturnTupleType(i))return;let s=l0(r.body);if(s.length===0)return;if(s.every(l=>l.type==="ArrayExpression")){let l=s[0].elements.length;if(l>0&&s.every(c=>c.elements.length===l)){let c=[],u=!0;for(let h=0;h<l;h++){let p=s.map(f=>Fn(f.elements[h],e)),d=p[0];if(!p.every(f=>f===d)){u=!1;break}c.push(d)}if(u&&c.some(h=>!!h)){e.setFunctionReturnTupleType(i,c),n=!0;return}}}let a=s.map(l=>Fn(l,e)),o=a[0];!o||!a.every(l=>l===o)||(e.setFunctionReturnType(i,o),n=!0)}});mt(t,{VariableDeclaration(r){for(let i of r.declarations)if(i.init){if(i.id?.type==="Identifier"){let s=Fn(i.init,e);s&&e.markVariableAsUdtInstance(i.id.name,s);continue}if(i.id?.type==="ArrayPattern"&&i.init.type==="CallExpression"&&i.init.callee?.type==="Identifier"){let s=e.getFunctionReturnTupleType(i.init.callee.name);if(!s)continue;i.id.elements?.forEach((a,o)=>{if(!a||a.type!=="Identifier")return;let l=s[o];l&&e.markVariableAsUdtInstance(a.name,l)})}}},ExpressionStatement(r){let i=r.expression;if(i?.type==="Literal"&&typeof i.value=="string"&&i.value.startsWith("__pineUdtVar:")){let s=i.value.match(/^__pineUdtVar:([A-Za-z_$][\\w$]*)=([A-Za-z_$][\\w$]*)$/);if(s){let[,a,o]=s;e.isUdtTypeName(o)&&e.markVariableAsUdtInstance(a,o)}}}}),mt(t,{ExpressionStatement(r){let i=r.expression;if(!i||i.type!=="AssignmentExpression"||i.operator!=="=")return;let s=i.left;if(s?.type!=="MemberExpression"||s.computed||s.property?.type!=="Identifier"||s.property.name!=="__pineParamTypes__"||s.object?.type!=="Identifier"||i.right?.type!=="ObjectExpression")return;let a=s.object.name,o=a.startsWith("$M_")?a.slice(3):a,l={};for(let c of i.right.properties){if(c.type!=="Property")continue;let u;if(c.key?.type==="Identifier"?u=c.key.name:c.key?.type==="Literal"&&typeof c.key.value=="string"&&(u=c.key.value),!u||c.value?.type!=="Literal"||typeof c.value.value!="string")continue;let h=c.value.value.split(/\\s+/).pop();e.isUdtTypeName(h)&&(l[u]=h)}Object.keys(l).length>0&&e.setFunctionParamUdtTypes(o,l)}})}function l0(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 Fn(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=Fn(t.consequent,e),r=Fn(t.alternate,e);if(n&&n===r)return n}}}function c0(t,e){mt(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===ye||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===ye||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 u0(t,e,n=!1){t.params.forEach(r=>{r.type==="Identifier"&&n&&e.addContextBoundVar(r.name,n)})}function p0(t,e){let n;return al(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.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=ye),u0(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=e.generateTempVar(),c={type:"VariableDeclaration",kind:r.kind,declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:l},init:o.init}]},u=c.declarations[0].init;u&&u.type==="CallExpression"&&(u.callee.type==="ArrowFunctionExpression"||u.callee.type==="FunctionExpression")&&mt(u.callee.body,{ReturnStatement(p){p.argument&&p.argument.type==="ArrayExpression"&&(p.argument={type:"ArrayExpression",elements:[p.argument]})}}),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:l},property:{type:"Literal",value:d},computed:!0}}]}));Object.assign(r,{type:"BlockStatement",body:[c,...h]})}})},ForStatement(r){}}),n}var h0=Object.defineProperty,d0=(t,e,n)=>e in t?h0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,f0=(t,e,n)=>d0(t,typeof e!="symbol"?e+"":e,n),m0=new Set(["bar_index","last_bar_index","time","time_close","timenow","year","month","weekofyear","dayofmonth","dayofweek","hour","minute","second"]),y0=new Set(["input.int","math.floor","math.ceil","array.size","matrix.rows","matrix.columns","str.length","timestamp","ta.barssince","ta.highestbars","ta.lowestbars"]);function g0(t){return t&&t.type==="Literal"&&typeof t.value=="number"&&Number.isInteger(t.value)&&!(typeof t.raw=="string"&&/[.eE]/.test(t.raw))}function _0(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 x0(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 Yi(t,e){return t!=="notint"&&e!=="notint"?"int":"notint"}var Zi=class{constructor(){f0(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,Yi(this.stack[r].get(e),n));return}this.stack[this.stack.length-1].set(e,Yi(n,n))}};function b0(t,e){let n=new Zi,r=x0(t);function i(a){if(!a||typeof a!="object")return"notint";switch(a.type){case"Literal":return typeof a.value=="number"&&g0(a)?"constint":"notint";case"Identifier":return m0.has(a.name)?"int":n.get(a.name)??"notint";case"UnaryExpression":return a.operator==="-"||a.operator==="+"?i(a.argument):(i(a.argument),"notint");case"BinaryExpression":{let o=i(a.left),l=i(a.right);if(a.operator==="/"){if(o==="constint"&&l==="constint"){let c=S.createMathIntDivCall(a.left,a.right);return Object.assign(a,c),"constint"}return"notint"}return a.operator==="+"||a.operator==="-"||a.operator==="*"||a.operator==="%"?o==="constint"&&l==="constint"?"constint":o!=="notint"&&l!=="notint"?"int":"notint":"notint"}case"ConditionalExpression":{i(a.test);let o=i(a.consequent),l=i(a.alternate);return Yi(o,l)}case"LogicalExpression":return i(a.left),i(a.right),"notint";case"CallExpression":{a.callee?.type==="MemberExpression"&&i(a.callee.object);for(let l of a.arguments||[])i(l);let o=_0(a.callee);return o&&y0.has(o)?"int":"notint"}case"MemberExpression":return i(a.object),a.computed&&i(a.property),"notint";case"VariableDeclaration":{for(let o of a.declarations||[]){let l=o.init?i(o.init):"notint";o.id?.type==="Identifier"&&(l==="constint"&&(a.kind==="var"||r.has(o.id.name))&&(l="int"),n.set(o.id.name,l))}return"notint"}case"AssignmentExpression":{let o=i(a.right);return a.left?.type==="Identifier"?n.assign(a.left.name,o):i(a.left),o}case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":{n.push();for(let o of a.params||[]){let l=o.type==="AssignmentPattern"?o.left:o;l?.type==="Identifier"&&n.set(l.name,"notint")}return i(a.body),n.pop(),"notint"}default:return s(a),"notint"}}function s(a){for(let o in a){if(o==="type"||o==="start"||o==="end"||o==="loc"||o==="raw")continue;let l=a[o];if(Array.isArray(l))for(let c of l)c&&typeof c.type=="string"&&i(c);else l&&typeof l.type=="string"&&i(l)}}i(t)}var Ar={type:"Identifier",name:"undefined"};function Bn(t,e){let n={type:"Identifier",name:`\'${e}\'`};if(!t.isInsideFunctionScope())return n;let[r]=t.getVariable("$$");return r?{type:"BinaryExpression",operator:"+",left:S.createMemberExpression(S.createLocalContextIdentifier(),S.createIdentifier("id")),right:n}:n}function ke(t,e){let[n,r]=e.getVariable(t);if((n.match(/^fn\\d+_/)||e.isVariableInFunctionScope(t))&&t!=="$$"){let[i]=e.getVariable("$$");if(i)return S.createLocalContextVariableReference(r,n)}return S.createContextVariableReference(r,n)}function Xi(t,e){let n=ke(t,e);return S.createGetCall(n,0)}function nn(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=S.createIdentifier(t.object.name);n._skipTransformation=!0;let r=S.createGetCall(n,t.property);Object.assign(t,r),t._indexTransformed=!0;return}if(!e.isContextBound(t.object.name)){let n=ke(t.object.name,e),r=S.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=S.createIdentifier(t.property.name);n._skipTransformation=!0,t.property=S.createGetCall(n,0)}else t.property=ke(t.property.name,e),t.property=S.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=S.createIdentifier(t.object.name);n._skipTransformation=!0;let r=S.createGetCall(n,t.property);Object.assign(t,r),t._indexTransformed=!0;return}if(e.isContextBound(t.object.name)||(t.object=ke(t.object.name,e)),t.property.type==="MemberExpression"){let n=t.property;n._indexTransformed||(nn(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=Ct(t.property,e))}function Ve(t,e){let n=S.createGetCall(S.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 Ce(t,e){if(!t._skipTransformation&&t.name!==ye){if(yt.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=S.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===ye&&["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"&&Wt.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===ye&&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=ke(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=S.createIdentifier(t.name),d=S.createGetCall(p,0);Object.assign(t,d)}return}let[c,u]=e.getVariable(t.name),h;if(l)h=S.createIdentifier(t.name);else{if(c===t.name&&!e.isContextBound(t.name))return;h=ke(t.name,e)}if(a)Object.assign(t,h);else{let p=S.createGetCall(h,0);Object.assign(t,p)}}}function _e(t,e,n){if(t.object&&t.object.type==="Identifier"&&t.object.name==="Math")return;if(t.computed&&t.object&&t.object.type==="CallExpression"&&!t._historyTransformed){t.object._transformed||we(t.object,n);let l=n.generateParamId(),c={type:"CallExpression",callee:S.createMemberExpression(S.createContextIdentifier(),S.createIdentifier("param")),arguments:[t.object,Ar,Bn(n,l)],_transformed:!0,_isParamCall:!0},u=S.createGetCall(c,t.property);u._transformed=!0,u._historyTransformed=!0,Object.assign(t,u),delete t.object,delete t.property,delete t.computed;return}if(t.object&&t.object.type==="Identifier"&&Wt.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=S.createIdentifier(t.object.name);l._skipTransformation=!0,t.object=S.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||(nn(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===ye||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"&&yt.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=S.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=S.createIdentifier(c);return p._skipTransformation=!0,p})():ke(c,n);l.object=S.createGetCall(u,t.property);let h=t.object;Object.assign(t,h),delete t.computed;return}}}function Ln(t,e){if(t.type==="Identifier"){if(yt.includes(t.name)&&e.isContextBound(t.name)){let s=t.name;return Object.assign(t,{type:"MemberExpression",object:{type:"Identifier",name:s},property:{type:"Identifier",name:"__value"},computed:!1}),delete t.name,t}if(e.isLoopVariable(t.name))return t;if(e.isRootParam(t.name)){let[s,a]=e.getVariable(t.name);return S.createContextVariableReference(a,s)}if(e.isContextBound(t.name))return t;let[n,r]=e.getVariable(t.name),i=n!==t.name;return e.isLocalSeriesVar(t.name)&&!i?t:i?ke(t.name,e):n===t.name&&!e.isContextBound(t.name)?t:ke(t.name,e)}return t}function Ct(t,e,n=""){switch(t.type){case"BinaryExpression":return lr(t,e,n);case"LogicalExpression":return cr(t,e,n);case"MemberExpression":{let r=!t.computed&&t.object.type==="Identifier"&&yt.includes(t.object.name)&&e.isContextBound(t.object.name);if(t.computed&&t.object.type==="Identifier"&&yt.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 S.createGetCall(a,t.property)}let i=t.object.type==="Identifier"&&!r?Ln(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=S.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=Ln(t,e);return r.type==="Identifier"&&(r.name==="NaN"||r.name==="undefined"||r.name==="Infinity"||r.name==="null"||r.name==="Math")?r:S.createGetCall(r,0)}case"UnaryExpression":return ur(t,e,n);case"ConditionalExpression":{let r=Ct(t.test,e,n),i=Ct(t.consequent,e,n),s=Ct(t.alternate,e,n);return{type:"ConditionalExpression",test:r,consequent:i,alternate:s,start:t.start,end:t.end}}}return t}function lr(t,e,n){let r=Ct(t.left,e,n),i=Ct(t.right,e,n),s={type:"BinaryExpression",operator:t.operator,left:r,right:i,start:t.start,end:t.end};return Ne(s,e,{CallExpression(a,o){a._transformed||we(a,o)},MemberExpression(a){_e(a,"",e)}}),s}function cr(t,e,n){let r=Ct(t.left,e,n),i=Ct(t.right,e,n),s={type:"LogicalExpression",operator:t.operator,left:r,right:i,start:t.start,end:t.end};return Ne(s,e,{CallExpression(a,o){a._transformed||we(a,o)}}),s}function mi(t,e,n){Ne(t,{parent:t,inNamespaceCall:!1},{Identifier(a,o,l){if(a.name=="NaN")return;if(yt.includes(a.name)&&e.isContextBound(a.name)){if(o.parent&&o.parent.type==="MemberExpression"&&o.parent.object===a&&!o.parent.computed)return;let u={type:"MemberExpression",object:{type:"Identifier",name:a.name},property:{type:"Identifier",name:"__value"},computed:!1},h=S.createGetCall(u,0);Object.assign(a,h),delete a.name;return}a.parent=o.parent,Ce(a,e);let c=a.parent&&a.parent.type==="BinaryExpression";(a.parent&&a.parent.type==="ConditionalExpression"||c)&&(a.type==="MemberExpression"?nn(a,e):a.type==="Identifier"&&(a.parent&&a.parent.type==="CallExpression"&&a.parent.callee&&a.parent.callee.object&&a.parent.callee.object.name===ye&&a.parent.callee.property.name==="get"||Ve(a)))},MemberExpression(a,o,l){_e(a,"",e),a.object&&l(a.object,{parent:a,inNamespaceCall:o.inNamespaceCall})},ConditionalExpression(a,o,l){let c={...o,parent:a};a.test&&l(a.test,c),a.consequent&&l(a.consequent,c),a.alternate&&l(a.alternate,c)},BinaryExpression(a,o,l){let c={...o,parent:a};l(a.left,c),l(a.right,c)},LogicalExpression(a,o,l){let c={...o,parent:a};l(a.left,c),l(a.right,c)},UnaryExpression(a,o,l){let c={...o,parent:a};l(a.argument,c)},CallExpression(a,o,l){let c=a.callee&&a.callee.type==="MemberExpression"&&a.callee.object&&a.callee.object.type==="Identifier"&&e.isContextBound(a.callee.object.name);we(a,e),a.arguments.forEach(u=>l(u,{parent:a,inNamespaceCall:c||o.inNamespaceCall}))}});let r=S.createMemberExpression(S.createIdentifier(n),S.createIdentifier("param")),i=e.generateParamId(),s={type:"CallExpression",callee:r,arguments:[t,Ar,Bn(e,i)],_transformed:!0,_isParamCall:!0};if(!e.shouldSuppressHoisting()){let a=i;e.addLocalSeriesVar(a);let o=S.createVariableDeclaration(a,s);return e.addHoistedStatement(o),S.createIdentifier(a)}return s}function ur(t,e,n){let r=Ct(t.argument,e,n),i={type:"UnaryExpression",operator:t.operator,prefix:t.prefix,argument:r,start:t.start,end:t.end};return Ne(i,e,{CallExpression(s,a){s._transformed||we(s,a)},MemberExpression(s){_e(s,"",e)}}),i}function Gt(t,e,n){switch(t?.type){case"BinaryExpression":t=lr(t,n,e);break;case"LogicalExpression":t=cr(t,n,e);break;case"ConditionalExpression":return mi(t,n,e);case"UnaryExpression":t=ur(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 c;if(n.isLocalSeriesVar(c.name)){let u=S.createIdentifier(c.name);return S.createGetCall(u,0)}return Xi(c.name,n)}return c.type==="CallExpression"?(we(c,n),c):c.type==="BinaryExpression"?lr(c,n,e):c.type==="LogicalExpression"?cr(c,n,e):c.type==="ConditionalExpression"?mi(c,n,e):c.type==="UnaryExpression"?ur(c,n,e):(c.type==="MemberExpression"&&_e(c,e,n),c)});break}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 f=t.object;for(;f.object&&f.object.type==="MemberExpression";)f=f.object;if(f.object?.type==="Identifier"&&n.isUdtInstance(f.object.name)){let m=f.object.name,x=n.isLocalSeriesVar(m)?(()=>{let b=S.createIdentifier(m);return b._skipTransformation=!0,b})():ke(m,n);return f.object=S.createGetCall(x,t.property),t.object}}if(t.object.type==="CallExpression")we(t.object,n);else if(t.object.type==="MemberExpression"){_e(t.object,"",n);let f=t.object;for(;f&&f.type==="MemberExpression"&&f.object;){if(f.object.type==="Identifier"){let m=f.object,[x]=n.getVariable(m.name);x!==m.name&&!n.isContextBound(m.name)&&!n.isRootParam(m.name)&&!n.isLoopVariable(m.name)&&!n.isLocalSeriesVar(m.name)&&!yt.includes(m.name)&&!Wt.includes(m.name)&&(f.object=Xi(m.name,n));break}f=f.object}}else t.object.type==="BinaryExpression"?t.object=lr(t.object,n,e):t.object.type==="LogicalExpression"?t.object=cr(t.object,n,e):t.object.type==="ConditionalExpression"?t.object=mi(t.object,n,e):t.object.type==="UnaryExpression"&&(t.object=ur(t.object,n,e));let c=t.object.type==="Identifier"&&n.isContextBound(t.object.name)&&!n.isRootParam(t.object.name)?t.object:Ln(t.object,n),u;t.property.type==="Identifier"&&!n.isContextBound(t.property.name)&&!n.isLoopVariable(t.property.name)?u=S.createGetCall(Ln(t.property,n),0):t.property.type==="BinaryExpression"||t.property.type==="UnaryExpression"||t.property.type==="LogicalExpression"||t.property.type==="ConditionalExpression"?u=Ct(t.property,n,e):u=t.property;let h=S.createMemberExpression(S.createIdentifier(e),S.createIdentifier("param")),p=n.generateParamId(),d={type:"CallExpression",callee:h,arguments:[c,u,Bn(n,p)],_transformed:!0,_isParamCall:!0};if(!n.shouldSuppressHoisting()){let f=p;n.addLocalSeriesVar(f);let m=S.createVariableDeclaration(f,d);return n.addHoistedStatement(m),S.createIdentifier(f)}return d}if(i){if(t.object.type==="Identifier"&&Wt.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=S.createVariableDeclaration(h,u);return n.addOuterHoistedStatement(p),Object.assign(t,S.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=ke(c,n),d=S.createGetCall(p,0);t.object=d}else if(n.isLocalSeriesVar(c)){let p=S.createIdentifier(c);p._skipTransformation=!0,t.object=S.createGetCall(p,0)}}else t.object.type==="MemberExpression"?Gt(t.object,e,n):t.object.type==="CallExpression"&&(t.object._transformed||we(t.object,n))}if(t.type==="ObjectExpression"&&(t.properties=t.properties.map(c=>c.value.name?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:S.createIdentifier(c.value.name),kind:"init",method:!1,shorthand:!1,computed:!1}:{type:"Property",key:{type:"Identifier",name:c.key.name},value:ke(c.value.name,n),kind:"init",method:!1,shorthand:!1,computed:!1}:(c.value.type!=="Literal"&&(c.value=Gt(c.value,e,n)),c))),t.type==="Identifier"){if(yt.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=S.createMemberExpression(S.createIdentifier(e),S.createIdentifier("param")),u=n.generateParamId(),h={type:"CallExpression",callee:c,arguments:[t,Ar,Bn(n,u)],_transformed:!0,_isParamCall:!0};if(!n.shouldSuppressHoisting()){let p=u;n.addLocalSeriesVar(p);let d=S.createVariableDeclaration(p,h);return n.addHoistedStatement(d),S.createIdentifier(p)}return h}}t?.type==="CallExpression"&&we(t,n);let s=S.createMemberExpression(S.createIdentifier(e),S.createIdentifier("param")),a=t.type==="Identifier"?Ln(t,n):t,o=n.generateParamId(),l={type:"CallExpression",callee:s,arguments:[a,Ar,Bn(n,o)],_transformed:!0,_isParamCall:!0};if(!n.shouldSuppressHoisting()){let c=o;n.addLocalSeriesVar(c);let u=S.createVariableDeclaration(c,l);return n.addHoistedStatement(u),S.createIdentifier(c)}return l}function kn(t){if(!t)return!1;if(cl(t))return!0;if(t.type==="MemberExpression")return kn(t.object);if(t.type==="ChainExpression")return kn(t.expression);if(t.type==="CallExpression"){let e=t.callee;if(e?.type==="MemberExpression")return kn(e.object);if(e?.type==="ChainExpression")return kn(e.expression)}return!1}function cl(t){return t?.type==="CallExpression"&&t.callee?.type==="MemberExpression"&&t.callee.object?.name==="$"&&t.callee.property?.name==="get"}function Qi(t,e,n){t&&(t.type==="Identifier"?(t.parent=e,Ce(t,n)):t.type==="MemberExpression"?Qi(t.object,t,n):t.type==="CallExpression"&&(t.callee&&t.callee.type==="MemberExpression"&&Qi(t.callee.object,t.callee,n),t._transformed||we(t,n)))}function we(t,e,n){if(t._transformed)return;t.callee&&t.callee.name,t.callee&&t.callee.type==="Identifier"&&(Wt.includes(t.callee.name)||yt.includes(t.callee.name))&&e.isContextBound(t.callee.name)&&(t.callee=S.createMemberExpression(t.callee,S.createIdentifier("any")));let r=t.callee&&t.callee.type==="MemberExpression"&&t.callee.object&&t.callee.object.type==="Identifier"&&(e.isContextBound(t.callee.object.name)||t.callee.object.name==="math"||t.callee.object.name==="ta");if(r){if(t.callee.object.name===ye&&["get","init","param"].includes(t.callee.property.name))return;let i=t.callee.object.name,s=[];t.arguments.forEach(p=>{if(p._isParamCall){s.push(p);return}s.push(Gt(p,i,e))}),t.arguments=s;let a=t.callee.property.name,o=`${i}.${a}`;if(Ia.includes(i)||Ia.includes(o)){let p=e.getNextPlotCallId();t.arguments.push({type:"ObjectExpression",properties:[{type:"Property",key:{type:"Identifier",name:"__callsiteId"},value:p,kind:"init",computed:!1,shorthand:!1}]})}if(i==="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}]}),i==="alert"){let p=e.getNextAlertCallId();t.arguments.push({type:"ObjectExpression",properties:[{type:"Property",key:{type:"Identifier",name:"__callsiteId"},value:p,kind:"init",computed:!1,shorthand:!1}]})}if(i==="ta")if(e.getCurrentScopeType()==="fn"){let p=e.getNextTACallId(),[d]=e.getVariable("$$"),f;d?f=S.createMemberExpression(S.createLocalContextIdentifier(),S.createIdentifier("id")):f=S.createLiteral("");let m={type:"BinaryExpression",operator:"+",left:f,right:p};t.arguments.push(m)}else t.arguments.push(e.getNextTACallId());let l=t.callee.property.name,c=`${i}.${l}`,u=Z_.includes(c),h=t._insideAwait===!0;if(u&&!h){let p=Object.assign({},t),d=S.createAwaitExpression(p);Object.assign(t,d)}if(!e.shouldSuppressHoisting()){let p=e.generateTempVar();e.addLocalSeriesVar(p);let d=t._insideAwait===!0,f=Object.assign({},t);d&&(f=S.createAwaitExpression(f));let m=S.createVariableDeclaration(p,f);e.addHoistedStatement(m);let x=S.createIdentifier(p);Object.assign(t,x),t._wasHoisted=!0,t._wasInsideAwait=d;return}t._transformed=!0}else if(t.callee&&t.callee.type==="Identifier"){if(t.arguments=t.arguments.map(i=>i._isParamCall?i:Gt(i,ye,e)),!e.isContextBound(t.callee.name)){let i=e.getNextUserCallId(),s=S.createMemberExpression(S.createContextIdentifier(),S.createIdentifier("call")),a=t.callee.name,o=t.callee;e.isUserMethod(a)&&!e.isRegularUserFunction(a)&&(o=S.createIdentifier(`$M_${a}`),o._skipTransformation=!0);let l=[o,i,...t.arguments];t.callee=s,t.arguments=l}t._transformed=!0}if(!r&&t.callee&&t.callee.type==="MemberExpression"){let i=t.callee.property.name,s=e.isUserFunction(i),a=t.callee.object,o=a.type==="Identifier"&&e.isLocalSeriesVar(a.name),l=a.type==="MemberExpression",c=e.isUserMethod(i),u=!!a.name&&e.isUdtInstance(a.name);if(s&&c&&!e.isContextBound(i)&&!o&&!l&&u){let h=t.callee.object;t.callee.property;let p=t.arguments.map(w=>w._isParamCall?w:Gt(w,ye,e)),d=h;h.type==="Identifier"?d=Gt(h,ye,e):h.type==="CallExpression"&&(we(h,e),d=Gt(h,ye,e));let f=S.createMemberExpression(S.createContextIdentifier(),S.createIdentifier("call")),m=e.getNextUserCallId(),x=S.createIdentifier(`$M_${i}`);x._skipTransformation=!0;let b=[x,m,d,...p];t.callee=f,t.arguments=b,t._transformed=!0;return}t.callee.object.type==="Identifier"?Ce(t.callee.object,e):Qi(t.callee.object,t.callee,e)}if(t.arguments.forEach(i=>{Ne(i,{parent:t},{Identifier(s,a,o){s.parent=a.parent,Ce(s,e);let l=s.parent&&s.parent.type==="BinaryExpression";(s.parent&&s.parent.type==="ConditionalExpression"||l)&&(s.type==="MemberExpression"?nn(s,e):s.type==="Identifier"&&(s.parent&&s.parent.type==="CallExpression"&&s.parent.callee&&s.parent.callee.object&&s.parent.callee.object.name===ye&&s.parent.callee.property.name==="get"||Ve(s)))},BinaryExpression(s,a,o){let l={...a,parent:s};o(s.left,l),o(s.right,l)},LogicalExpression(s,a,o){let l={...a,parent:s};o(s.left,l),o(s.right,l)},UnaryExpression(s,a,o){let l={...a,parent:s};o(s.argument,l)},CallExpression(s,a,o){s.callee&&s.callee.type==="MemberExpression"&&s.callee.object&&(s.callee.object.parent=s.callee,o(s.callee.object,{parent:s.callee})),s._transformed||we(s,e)},MemberExpression(s,a,o){_e(s,"",e),s.object&&o(s.object,{parent:s})}})}),t.callee&&t.callee.type==="MemberExpression"){let i=t.callee.object,s=cl(i),a=i?.type==="MemberExpression"&&kn(i);if(s||a){let o=Object.assign({},t.callee,{optional:!0});t.callee={type:"ChainExpression",expression:o},t.optional=!0}}}function Rs(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:"ThrowStatement",argument:{type:"NewExpression",callee:{type:"Identifier",name:"Error"},arguments:[{type:"Literal",value:`Loop exceeded maximum iterations (${t})`}]}},alternate:null};return{counterDecl:e,guardCheck:n}}function Tr(t,e){let n=null;if(t.left.type==="Identifier")n=ke(t.left.name,e);else if(t.left.type==="MemberExpression"&&t.left.computed){if(t.left.object.type==="Identifier"){let r=t.left.object.name,[i,s]=e.getVariable(r),a=i!==r,o=e.isContextBound(r);(a||o)&&!e.isLoopVariable(r)&&t.left.property.type==="Literal"&&t.left.property.value===0&&(n=ke(r,e))}}else if(t.left.type==="MemberExpression"&&!t.left.computed){let r=null,i=t.left;for(;i.type==="MemberExpression"&&!i.computed;){if(i.object.type==="Identifier"){r=i;break}i=i.object}if(r){let s=r.object.name,[a,o]=e.getVariable(s);if(a!==s&&!e.isLoopVariable(s)){let l=ke(s,e),c=S.createGetCall(l,0);r.object=c}else if(e.isLocalSeriesVar(s)){let l=S.createIdentifier(s);l._skipTransformation=!0,r.object=S.createGetCall(l,0)}}}if(Ne(t.right,{parent:t.right,inNamespaceCall:!1},{Identifier(r,i,s){let a=i.parent&&i.parent.type==="MemberExpression"&&!i.parent.computed&&i.parent.object===r;if(yt.includes(r.name)&&e.isContextBound(r.name)&&!a){let m={type:"MemberExpression",object:{type:"Identifier",name:r.name},property:{type:"Identifier",name:"__value"},computed:!1},x=S.createGetCall(m,0);Object.assign(r,x),delete r.name;return}r.parent=i.parent,Ce(r,e);let o=r.parent&&r.parent.type==="BinaryExpression",l=r.parent&&r.parent.type==="ConditionalExpression",c=e.isContextBound(r.name)&&!e.isRootParam(r.name),u=r.parent&&r.parent.type==="MemberExpression"&&r.parent.computed&&r.parent.object===r,h=r.parent&&r.parent._isParamCall,p=r.parent&&r.parent.type==="MemberExpression",d=r.name==="NaN",f=r.parent&&r.parent.type==="CallExpression"&&r.parent.callee&&r.parent.callee.object&&r.parent.callee.object.name===ye&&r.parent.callee.property.name==="get";(c||l||o)&&(r.type==="MemberExpression"?nn(r,e):r.type==="Identifier"&&!p&&!u&&!h&&!d&&!f&&Ve(r))},MemberExpression(r,i,s){_e(r,"",e),r.type==="CallExpression"?r.arguments.forEach(a=>s(a,{parent:r,inNamespaceCall:i.inNamespaceCall})):r.object&&s(r.object,{parent:r,inNamespaceCall:i.inNamespaceCall})},CallExpression(r,i,s){let a=r.callee&&r.callee.type==="MemberExpression"&&r.callee.object&&r.callee.object.type==="Identifier"&&e.isContextBound(r.callee.object.name);we(r,e),r.type==="CallExpression"&&(r.callee.type==="MemberExpression"&&s(r.callee,{parent:r,inNamespaceCall:a||i.inNamespaceCall}),r.arguments.forEach(o=>s(o,{parent:r,inNamespaceCall:a||i.inNamespaceCall})))}}),n){let r=t.right;if(t.operator!=="="){let s=t.operator.replace("=",""),a=S.createGetCall(n,0);r={type:"BinaryExpression",operator:s,left:a,right:t.right,start:t.start,end:t.end}}let i=S.createSetCall(n,r);t.start&&(i.start=t.start),t.end&&(i.end=t.end),Object.assign(t,i)}}function ul(t,e){t._skipTransformation||t.declarations.forEach(n=>{if(n.init?.type==="CallExpression"&&n.id?.type==="Identifier"){let p=n.init.callee;(p?.type==="MemberExpression"&&p.object?.type==="Identifier"&&p.object.name==="input"||p?.type==="Identifier"&&p.name==="input")&&(n.init._varId=n.id.name)}if(n.init&&n.init.type==="Identifier"&&yt.includes(n.init.name)&&e.isContextBound(n.init.name)){let p=n.init.name;Object.assign(n.init,{type:"MemberExpression",object:{type:"Identifier",name:p},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===ye||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===ye||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(p=>{p.key.name&&e.addContextBoundVar(p.key.name)}),n.init.object.name=ye;return}if(i){n.id.name&&e.addContextBoundVar(n.id.name),n.id.properties&&n.id.properties.forEach(p=>{p.key.name&&e.addContextBoundVar(p.key.name)}),n.init.object.object.name=ye;return}e.addVariable(n.id.name,t.kind);let a=t.kind,o=e.isArrayPatternElement(n.id.name)&&n.init&&n.init.type==="MemberExpression"&&n.init.computed;n.init&&!s&&!o&&(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)?we(n.init,e):Ne(n.init,{parent:n.init},{Identifier(p,d){p.parent=d.parent,Ce(p,e);let f=p.parent&&p.parent.type==="BinaryExpression",m=p.parent&&p.parent.type==="UnaryExpression",x=p.parent&&p.parent.type==="ConditionalExpression",b=p.parent&&p.parent.type==="CallExpression"&&p.parent.callee&&p.parent.callee.object&&p.parent.callee.object.name===ye&&p.parent.callee.property.name==="get";p.type==="Identifier"&&(f||m||x)&&!b&&Ve(p)},CallExpression(p,d,f){p.callee.type==="Identifier"&&(p.callee.parent=p),p.arguments.forEach(m=>{m.type==="Identifier"&&(m.parent=p)}),(p.callee.type==="ArrowFunctionExpression"||p.callee.type==="FunctionExpression")&&f(p.callee,{parent:p}),we(p,e),p.type==="CallExpression"&&(p.callee.type==="MemberExpression"&&f(p.callee,{parent:p}),p.arguments.forEach(m=>f(m,{parent:p})))},BinaryExpression(p,d,f){p.left.type==="Identifier"&&(p.left.parent=p),p.right.type==="Identifier"&&(p.right.parent=p),f(p.left,{parent:p}),f(p.right,{parent:p})},LogicalExpression(p,d,f){p.left.type==="Identifier"&&(p.left.parent=p),p.right.type==="Identifier"&&(p.right.parent=p),f(p.left,{parent:p}),f(p.right,{parent:p})},UnaryExpression(p,d,f){p.argument.type==="Identifier"&&(p.argument.parent=p),f(p.argument,{parent:p})},MemberExpression(p,d,f){p.object&&p.object.type==="Identifier"&&(p.object.parent=p),p.property&&p.property.type==="Identifier"&&(p.property.parent=p),_e(p,"",e),p.type==="CallExpression"?p.arguments.forEach(m=>f(m,{parent:p})):p.object&&f(p.object,{parent:p})},AwaitExpression(p,d,f){p.argument&&(p.argument._insideAwait=!0,f(p.argument,{parent:p}),p.argument.type==="Identifier"&&p.argument._wasInsideAwait&&Object.assign(p,p.argument))},ArrowFunctionExpression(p,d,f){if(p.body)if(p.body.type==="BlockStatement"){let m=[];p.body.body.forEach(x=>{e.enterHoistingScope(),f(x,{parent:p.body,insideIIFE:!0});let b=e.exitHoistingScope();m.push(...b),m.push(x)}),p.body.body=m}else f(p.body,{parent:p,insideIIFE:!0})},FunctionExpression(p,d,f){if(p.body&&p.body.type==="BlockStatement"){let m=[];p.body.body.forEach(x=>{e.enterHoistingScope(),f(x,{parent:p.body,insideIIFE:!0});let b=e.exitHoistingScope();m.push(...b),m.push(x)}),p.body.body=m}},SwitchStatement(p,d,f){p.discriminant&&(p.discriminant.parent=p,f(p.discriminant,{parent:p})),p.cases&&p.cases.forEach(m=>{m.parent=p,f(m,{parent:p})})},SwitchCase(p,d,f){if(p.test&&(p.test.parent=p,f(p.test,{parent:p})),p.consequent){let m=[];p.consequent.forEach(x=>{e.enterHoistingScope(),x.parent=p,f(x,{parent:p});let b=e.exitHoistingScope();m.push(...b),m.push(x)}),p.consequent=m}},AssignmentExpression(p,d,f){if(d.insideIIFE){if(p.left.type==="Identifier"){let[m]=e.getVariable(p.left.name);if(m===p.left.name&&!e.isContextBound(p.left.name)){f(p.right,{parent:p});return}}Tr(p,e)}}}));let l=ke(n.id.name,e),c=!o&&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||(nn(n.init.property,e),n.init.property._indexTransformed=!0)),a==="var"){let p=e.getCurrentHoistingScope();if(p){for(let d of p)if(d.type==="VariableDeclaration")for(let f of d.declarations){if(!f.init||f.init.type!=="CallExpression")continue;let m=f.init.callee;if(m?.type!=="MemberExpression")continue;let x,b=m.property?.name;if(m.object?.type==="Identifier"?x=m.object.name:m.object?.type==="MemberExpression"&&m.object.property?.name&&(x=m.object.property.name),x&&b){let w=`${x}.${b}`;Q_.includes(w)&&(f.init={type:"ArrowFunctionExpression",params:[],body:f.init,expression:!0,async:!1})}}}}let u;n.init?s||o?u=n.init:a==="var"?u=S.createInitVarCall(l,n.init):u=S.createInitCall(l,c?n.init.object:n.init,c?n.init.property:void 0):u=S.createIdentifier("undefined");let h=S.createExpressionStatement(S.createAssignmentExpression(l,u));if(o){let p=n.init.object.name,d=ke(p,e),f=n.init.property.value,m={type:"MemberExpression",object:S.createGetCall(d,0),property:{type:"Literal",value:f},computed:!0};h.expression.right=S.createCallExpression(S.createMemberExpression(S.createContextIdentifier(),S.createIdentifier("init")),[l,m])}s&&(e.pushScope("fn"),Ne(n.init.body,e,{IfStatement(p,d,f){d.pushScope("if"),p.test&&pl(p.test,d),f(p.consequent,d),p.alternate&&(d.pushScope("els"),f(p.alternate,d),d.popScope()),d.popScope()},VariableDeclaration(p,d){ul(p,d)},Identifier(p,d){Ce(p,d)},AssignmentExpression(p,d){Tr(p,d)},SwitchStatement(p,d,f){p.discriminant.parent=p,f(p.discriminant,d),p.cases.forEach(m=>{m.parent=p,f(m,d)})},SwitchCase(p,d,f){p.test&&(p.test.parent=p,f(p.test,d));let m=[];p.consequent.forEach(x=>{d.enterHoistingScope(),f(x,d);let b=d.exitHoistingScope();m.push(...b),m.push(x)}),p.consequent=m},BlockStatement(p,d,f){let m=[];p.body.forEach(x=>{d.enterHoistingScope(),f(x,d);let b=d.exitHoistingScope();m.push(...b),m.push(x)}),p.body=m}}),e.popScope()),Object.assign(t,h)})}function w0(t,e,n){if(e.setSuppressHoisting(!0),t.init&&t.init.type==="VariableDeclaration"){let s=t.init.declarations[0],a=s.id.name;e.addLoopVariable(a,a),t.init={type:"VariableDeclaration",kind:t.init.kind,declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:a},init:s.init}]},s.init&&Ne(s.init,e,{Identifier(o,l){!e.isLoopVariable(o.name)&&!o.computed&&(e.pushScope("for"),Ce(o,l),o.type==="Identifier"&&(e.isContextBound(o.name)&&o.parent&&o.parent.type==="MemberExpression"&&o.parent.object===o||(o.computed=!0,Ve(o))),e.popScope())},MemberExpression(o,l,c){e.pushScope("for"),_e(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&&Ne(t.test,e,{Identifier(s,a){!e.isLoopVariable(s.name)&&!s.computed&&(e.pushScope("for"),Ce(s,a),s.type==="Identifier"&&(e.isContextBound(s.name)&&s.parent&&s.parent.type==="MemberExpression"&&s.parent.object===s||(s.computed=!0,Ve(s))),e.popScope())},MemberExpression(s,a,o){e.pushScope("for"),_e(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&&Ne(t.update,e,{Identifier(s,a){!e.isLoopVariable(s.name)&&!s.computed&&(e.pushScope("for"),Ce(s,a),s.type==="Identifier"&&(e.isContextBound(s.name)&&s.parent&&s.parent.type==="MemberExpression"&&s.parent.object===s||(s.computed=!0,Ve(s))),e.popScope())},MemberExpression(s,a,o){e.pushScope("for"),_e(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);let r=e.getNextLoopGuardName(),i=Rs(r);if(e.addHoistedStatement(i.counterDecl),e.pushScope("for"),n(t.body,e),e.popScope(),t.body.type==="BlockStatement"&&t.body.body.unshift(i.guardCheck),t.init&&t.init.type==="VariableDeclaration"){let s=t.init.declarations[0];e.removeLoopVariable(s.id.name)}}function v0(t,e,n){e.setSuppressHoisting(!0),t.test&&Ne(t.test,e,{Identifier(s,a){s.computed||(Ce(s,a),s.type==="Identifier"&&(e.isContextBound(s.name)&&s.parent&&s.parent.type==="MemberExpression"&&s.parent.object===s||(s.computed=!0,Ve(s))))},MemberExpression(s,a,o){_e(s,"",e),s.type==="MemberExpression"&&s.object&&(s.object.type!=="Identifier"||!e.isContextBound(s.object.name))&&o(s.object,a)},CallExpression(s,a,o){if(s.callee.parent=s,o(s.callee,a),we(s,a),s.arguments)for(let l of s.arguments)o(l,a)}}),e.setSuppressHoisting(!1);let r=e.getNextLoopGuardName(),i=Rs(r);e.addHoistedStatement(i.counterDecl),e.pushScope("whl"),n(t.body,e),e.popScope(),t.body.type==="BlockStatement"&&t.body.body.unshift(i.guardCheck)}function pl(t,e){Ne(t,e,{MemberExpression(n,r,i){n.object&&n.object.type==="Identifier"&&!e.isContextBound(n.object.name)&&!n.computed&&(n.object.parent=n,i(n.object,r)),_e(n,"",e)},CallExpression(n,r){we(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";Ce(n,r),n.type==="Identifier"&&(s||a||o||l)&&(i&&i.type==="CallExpression"&&i.callee&&i.callee.object&&i.callee.object.name===ye&&i.callee.property?.name==="get"||Ve(n));let c=e.getCurrentScopeType()==="if";e.isContextBound(n.name)&&!e.isRootParam(n.name)&&c&&Ve(n)}})}function E0(t,e,n){t.test&&(e.pushScope("if"),pl(t.test,e),e.popScope()),e.pushScope("if"),n(t.consequent,e),e.popScope(),t.alternate&&(e.pushScope("els"),n(t.alternate,e),e.popScope())}function S0(t,e){let n=e.getCurrentScopeType();if(t.argument){if(t.argument.type==="ArrayExpression")t.argument.elements=t.argument.elements.map(r=>r.type==="Identifier"?e.isContextBound(r.name)&&!e.isRootParam(r.name)?S.createGetCall(r,0):Xi(r.name,e):r.type==="MemberExpression"?r.object&&r.object.type==="MemberExpression"&&r.object.object&&r.object.object.type==="Identifier"&&r.object.object.name==="$"&&r.object.property&&["const","let","var","params"].includes(r.object.property.name)?S.createGetCall(r,0):(_e(r,"",e),r):((r.type==="BinaryExpression"||r.type==="LogicalExpression"||r.type==="ConditionalExpression"||r.type==="CallExpression"||r.type==="UnaryExpression")&&Ne(r,e,{Identifier(i,s){Ce(i,s),i.type==="Identifier"&&!i._arrayAccessed&&(Ve(i),i._arrayAccessed=!0)},MemberExpression(i){_e(i,"",e)},CallExpression(i,s,a){(i.callee.type==="ArrowFunctionExpression"||i.callee.type==="FunctionExpression")&&a(i.callee,s),we(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)),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:S.createIdentifier(r.key.name),value:ke(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=ke(r.value.name,e))),r));else if(t.argument.type==="Identifier")Ce(t.argument,e),t.argument.type==="Identifier"&&Ve(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)))Ce(t.argument.object,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)&&_e(t.argument,"",e)}}if(n==="fn"){t.argument.type==="Identifier"&&e.isContextBound(t.argument.name)&&!e.isRootParam(t.argument.name)?t.argument=S.createArrayAccess(t.argument,0):t.argument.type==="MemberExpression"?t.argument.computed&&t.argument.object.type==="CallExpression"?_e(t.argument,"",e):t.argument.object.type==="Identifier"&&e.isContextBound(t.argument.object.name)&&!e.isRootParam(t.argument.object.name)?t.argument.computed?_e(t.argument,"",e):t.argument._indexTransformed||(nn(t.argument,e),t.argument._indexTransformed=!0):t.argument.computed&&t.argument.object.type==="Identifier"&&e.isLocalSeriesVar(t.argument.object.name)&&_e(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")&&Ne(t.argument,e,{Identifier(i,s){Ce(i,s),i.type==="Identifier"&&!i._arrayAccessed&&(Ve(i),i._arrayAccessed=!0)},MemberExpression(i){_e(i,"",e)},AssignmentExpression(i,s){Tr(i,s)},CallExpression(i,s,a){(i.callee.type==="ArrowFunctionExpression"||i.callee.type==="FunctionExpression")&&a(i.callee,s),we(i,s),i.type==="CallExpression"&&i.arguments.forEach(o=>a(o,s))},BinaryExpression(i,s,a){a(i.left,s),a(i.right,s)},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=S.createCallExpression(S.createMemberExpression(S.createContextIdentifier(),S.createIdentifier("precision")),[t.argument]);t.argument=r}}}function C0(t,e,n){let r=S.createVariableDeclaration("$$",S.createCallExpression(S.createMemberExpression(S.createContextIdentifier(),S.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(l=>{l.type==="Identifier"&&e.addLocalSeriesVar(l.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[l,c]of Object.entries(a))o[l]=e.getVariableUdtType(l),e.markVariableAsUdtInstance(l,c);if(n(t.body,e),t.params.forEach(l=>{l.type==="Identifier"&&e.removeLocalSeriesVar(l.name)}),a)for(let l of Object.keys(a)){e.unmarkVariableAsUdtInstance(l);let c=o[l];c!==void 0&&e.markVariableAsUdtInstance(l,c)}e.popScope()}}function N0(t){let e={...A,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;mt(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 mt(o,{AwaitExpression(){l=!0}},c),l}let s=!0,a=0;for(;s&&a<20;){s=!1,a++,mt(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=[];mt(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=[];mt(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 k0={"==":"__eq","===":"__eq","!=":"__neq","!==":"__neq","<":"__lt","<=":"__le",">":"__gt",">=":"__ge"},I0=new Set(["<","<=",">",">="]);function A0(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==="WhileStatement"||r.type==="DoWhileStatement")&&i===r.test)return!0}return!1}function T0(t){let e={...A,LineComment:()=>{}};al(t,{BinaryExpression(n,r,i){let s=k0[n.operator];if(!s||I0.has(n.operator)&&A0(n,i))return;let a=S.createMathCompareCall(s,n.left,n.right);a._transformed=!0,Object.assign(n,a)}},e)}function D0(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};Ne(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),S0(a,o)},VariableDeclaration(a,o){ul(a,o)},Identifier(a,o){Ce(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)),we(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"?(Ce(a.right,o),a.right.type==="Identifier"&&Ve(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=S.createCallExpression(S.createMemberExpression(S.createIdentifier("$"),S.createIdentifier(h),!1),[p]);Object.assign(a.right,d)}let c=o.getNextLoopGuardName(),u=Rs(c);if(o.addHoistedStatement(u.counterDecl),a.body&&l(a.body,o),a.body&&a.body.type==="BlockStatement"&&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"?(Ce(a.right,o),a.right.type==="Identifier"&&Ve(a.right)):a.right&&l(a.right,o),a.body&&l(a.body,o)},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)),_e(a,n,o)},AssignmentExpression(a,o,l){if(Tr(a,o),a.type==="CallExpression"&&a.arguments){let c=u=>{u&&(u.type==="CallExpression"&&u.callee&&(u.callee.type==="ArrowFunctionExpression"||u.callee.type==="FunctionExpression")&&l(u.callee,o),u.type==="BinaryExpression"&&(c(u.left),c(u.right)))};a.arguments.forEach(u=>c(u))}},FunctionDeclaration(a,o,l){C0(a,o,l)},ForStatement(a,o,l){w0(a,o,l)},WhileStatement(a,o,l){v0(a,o,l)},IfStatement(a,o,l){E0(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 _={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"},M0=new Set(["if","else","for","while","switch","break","continue","var","varip","type","and","or","not","to","by","in","import","export","method","extends","enum"]),P0=["==","!=","<=",">=",":=","+=","-=","*=","/=","%=","=>","//","and","or","not"],Ji=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}},R0=Object.defineProperty,F0=(t,e,n)=>e in t?R0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,_t=(t,e,n)=>F0(t,typeof e!="symbol"?e+"":e,n),es=class{constructor(e){_t(this,"source"),_t(this,"pos"),_t(this,"line"),_t(this,"column"),_t(this,"tokens"),_t(this,"indentStack"),_t(this,"atLineStart"),_t(this,"parenDepth"),_t(this,"bracketDepth"),_t(this,"braceDepth"),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(_.DEDENT,"",this.getCurrentIndent());return this.addToken(_.EOF,""),this.tokens}handleNewline(){this.parenDepth===0&&this.bracketDepth===0&&this.braceDepth===0&&(this.addToken(_.NEWLINE,`\n`),this.atLineStart=!0),this.advance(),this.line++,this.column=1}handleIndentation(){let e=0,n=0;for(this.pos;this.pos<this.source.length;){let i=this.peek();if(i===" ")n++,this.advance();else if(i===" ")e++,this.advance();else break}if(this.peek()===`\n`||this.peek()==="\\r"||this.peek()==="\\0"||(e+=Math.floor(n/4),this.isContinuationFromPrevToken()))return;let r=this.indentStack[this.indentStack.length-1];if(e>r)this.indentStack.push(e),this.addToken(_.INDENT,"",e);else if(e<r){for(;this.indentStack.length>1&&this.indentStack[this.indentStack.length-1]>e;)this.indentStack.pop(),this.addToken(_.DEDENT,"",this.indentStack[this.indentStack.length-1]);if(this.indentStack[this.indentStack.length-1]!==e)throw new Error(`Indentation error at ${this.line}:${this.column} - misaligned dedent`)}}isContinuationFromPrevToken(){for(let e=this.tokens.length-1;e>=0;e--){let n=this.tokens[e];if(!(n.type===_.NEWLINE||n.type===_.COMMENT))return n.type===_.OPERATOR?n.value!=="=>":n.type===_.COMMA||n.type===_.COLON||n.type===_.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.addToken(_.COMMENT,e.trim())}readString(){let e=this.advance(),n=this.column-1,r="";for(;this.pos<this.source.length&&this.peek()!==e;)if(this.peek()==="\\\\"){this.advance();let i=this.advance();switch(i){case"n":r+=`\n`;break;case"t":r+=" ";break;case"r":r+="\\r";break;case"\\\\":r+="\\\\";break;case e:r+=e;break;default:r+=i}}else r+=this.advance();if(this.peek()!==e)throw new Error(`Unterminated string at ${this.line}:${n}`);this.advance(),this.addToken(_.STRING,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(_.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(_.NUMBER,parseFloat(e),null,e)}readIdentifier(){this.column;let e="";for(;this.pos<this.source.length&&this.isIdentifierChar(this.peek());)e+=this.advance();M0.has(e)?this.addToken(_.KEYWORD,e):e==="true"||e==="false"?this.addToken(_.BOOLEAN,e==="true"):this.addToken(_.IDENTIFIER,e)}readOperatorOrPunctuation(){let e=this.peek(),n=this.peek(1),r=e+n;if(P0.includes(r))return this.advance(),this.advance(),this.addToken(_.OPERATOR,r),!0;if("+-*/%<>=!?".includes(e))return this.advance(),this.addToken(_.OPERATOR,e),!0;switch(e){case"(":return this.parenDepth++,this.advance(),this.addToken(_.LPAREN,e),!0;case")":return this.parenDepth--,this.advance(),this.addToken(_.RPAREN,e),!0;case"[":return this.bracketDepth++,this.advance(),this.addToken(_.LBRACKET,e),!0;case"]":return this.bracketDepth--,this.advance(),this.addToken(_.RBRACKET,e),!0;case"{":return this.braceDepth++,this.advance(),this.addToken(_.LBRACE,e),!0;case"}":return this.braceDepth--,this.advance(),this.addToken(_.RBRACE,e),!0;case",":return this.advance(),this.addToken(_.COMMA,e),!0;case".":return this.isDigit(this.peek(1))?(this.readNumber(),!0):(this.advance(),this.addToken(_.DOT,e),!0);case":":return this.advance(),this.addToken(_.COLON,e),!0;case";":return this.advance(),this.addToken(_.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 Ji(e,n,this.line,this.column,r!==null?r:this.getCurrentIndent(),i);this.tokens.push(s)}},B0=Object.defineProperty,L0=(t,e,n)=>e in t?B0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ye=(t,e,n)=>L0(t,typeof e!="symbol"?e+"":e,n),ie=class{constructor(e){this.type=e}},ts=class extends ie{constructor(e){super("Program"),this.body=e}},qe=class extends ie{constructor(e){super("ExpressionStatement"),this.expression=e}},At=(t=>(t.VAR="var",t.LET="let",t.CONST="const",t))(At||{}),ut=class extends ie{constructor(e,n="let"){super("VariableDeclaration"),this.declarations=e,this.kind=n}},nt=class extends ie{constructor(e,n,r=null){super("VariableDeclarator"),this.id=e,this.init=n,this.varType=r}},Dr=class extends ie{constructor(e,n,r,i=null){super("FunctionDeclaration"),this.id=e,this.params=n,this.body=r,this.returnType=i}},ns=class extends ie{constructor(e,n){super("TypeDefinition"),this.name=e,this.fields=n}},rs=class extends ie{constructor(e,n,r=null){super("IfStatement"),this.test=e,this.consequent=n,this.alternate=r,Ye(this,"_line")}},Mr=class extends ie{constructor(e,n,r,i){super("ForStatement"),this.init=e,this.test=n,this.update=r,this.body=i,Ye(this,"isForIn")}},is=class extends ie{constructor(e,n){super("WhileStatement"),this.test=e,this.body=n}},wt=class extends ie{constructor(e){super("BlockStatement"),this.body=e}},Pr=class extends ie{constructor(e){super("ReturnStatement"),this.argument=e}},be=class extends ie{constructor(e){super("Identifier"),this.name=e,Ye(this,"varType"),Ye(this,"returnType"),Ye(this,"isMethod")}},Tt=class extends ie{constructor(e,n=null){super("Literal"),this.value=e,this.raw=n}},pt=class extends ie{constructor(e,n,r){super("BinaryExpression"),this.operator=e,this.left=n,this.right=r}},Rr=class extends ie{constructor(e,n,r=!0){super("UnaryExpression"),this.operator=e,this.argument=n,this.prefix=r}},Yt=class extends ie{constructor(e,n,r){super("AssignmentExpression"),this.operator=e,this.left=n,this.right=r}},Fr=class extends ie{constructor(e,n,r=!1){super("UpdateExpression"),this.operator=e,this.argument=n,this.prefix=r}},ss=class extends ie{constructor(e,n){super("CallExpression"),this.callee=e,this.args=n,Ye(this,"arguments"),this.callee=e,this.arguments=n}},Br=class extends ie{constructor(e,n,r=!1){super("MemberExpression"),this.object=e,this.property=n,this.computed=r}},vt=class extends ie{constructor(e,n,r){super("ConditionalExpression"),this.test=e,this.consequent=n,this.alternate=r,Ye(this,"needsIIFE"),Ye(this,"consequentStmts"),Ye(this,"alternateStmts")}},as=class extends ie{constructor(e){super("ArrayExpression"),this.elements=e}},Lr=class extends ie{constructor(e){super("ObjectExpression"),this.properties=e}},Or=class extends ie{constructor(e,n){super("Property"),this.key=e,this.value=n,Ye(this,"kind"),Ye(this,"method"),Ye(this,"shorthand"),Ye(this,"computed"),this.kind="init",this.method=!1,this.shorthand=!1,this.computed=!1}},Vr=class extends ie{constructor(e){super("ArrayPattern"),this.elements=e}},jr=class extends ie{constructor(e,n){super("AssignmentPattern"),this.left=e,this.right=n}},os=class extends ie{constructor(e,n){super("SwitchExpression"),this.discriminant=e,this.cases=n}},ls=class extends ie{constructor(e,n,r){super("SwitchCase"),this.test=e,this.consequent=n,this.statements=r,this.statements=r}},O0=Object.defineProperty,V0=(t,e,n)=>e in t?O0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,dn=(t,e,n)=>V0(t,typeof e!="symbol"?e+"":e,n),hl=class cs{constructor(e){dn(this,"tokens"),dn(this,"pos"),dn(this,"functionNames",new Set),dn(this,"paramScopes",[]),dn(this,"noLineContinuation",!1),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}`);if(n!==null&&r.value!==n)throw new Error(`Expected \'${n}\' but got \'${r.value}\' at ${r.line}:${r.column}`);return this.advance()}expectIdentifierOrContextual(){let e=this.peek();if(e.type===_.IDENTIFIER)return this.advance();if(e.type===_.KEYWORD&&cs.CONTEXTUAL_KEYWORDS.has(e.value))return this.advance();throw new Error(`Expected ${_.IDENTIFIER} but got ${e.type} at ${e.line}:${e.column}`)}matchEx(e,n=null,r=!1){if(!r)return this.match(e,n);let i=0,s=this.peek(i);if(s.type===_.NEWLINE&&this.noLineContinuation||(s.type===_.NEWLINE&&(i++,s=this.peek(i),s.type===_.INDENT&&(i++,s=this.peek(i))),s.type!==e)||n!==null&&s.value!==n)return!1;for(let a=0;a<i;a++)this.advance();return!0}peekOperatorEx(e){let n=0,r=this.peek(n),i=!1;if(r.type===_.NEWLINE){if(this.noLineContinuation)return null;n++,r=this.peek(n),r.type===_.INDENT&&(i=!0,n++,r=this.peek(n))}if(r.type!==_.OPERATOR||!e.includes(r.value)||i&&(r.value==="+"||r.value==="-"))return null;for(let s=0;s<n;s++)this.advance();return r.value}skipNewlines(e=!1){for(;this.match(_.NEWLINE)||this.match(_.COMMENT);)this.advance();e&&this.match(_.INDENT)&&this.advance()}parse(){let e=[];for(;!this.match(_.EOF);){if(this.skipNewlines(),this.match(_.DEDENT)){this.advance();continue}if(this.match(_.EOF))break;let n=this.parseStatement();n&&e.push(n),this.skipNewlines()}return new ts(e)}parseStatement(e=!0){this.skipNewlines();let n=this.peek().line;if(this.match(_.COMMENT))return this.advance(),null;let r;if(this.match(_.KEYWORD,"enum"))r=this.parseEnumDefinition();else if(this.match(_.KEYWORD,"type"))r=this.parseTypeDefinition();else if(this.match(_.KEYWORD,"var")||this.match(_.KEYWORD,"varip"))r=this.parseVarDeclaration();else if(this.match(_.KEYWORD,"method"))r=this.parseMethodDeclaration();else if(this.isFunctionDeclaration())r=this.parseFunctionDeclaration();else if(this.match(_.KEYWORD,"if"))r=this.parseIfStatement();else if(this.match(_.KEYWORD,"for"))r=this.parseForStatement();else if(this.match(_.KEYWORD,"while"))r=this.parseWhileStatement();else if(this.match(_.KEYWORD,"break")||this.match(_.KEYWORD,"continue")){let i=this.advance().value;r=new qe(new be(i))}else this.isTupleDestructuring()?r=this.parseTupleDestructuring():this.peek().type===_.IDENTIFIER&&this.isTypedVarDeclaration()&&(r=this.parseTypedVarDeclaration());if(!r){let i=this.parseExpression();if(this.match(_.OPERATOR)){let s=this.peek().value;if(["=",":=","+=","-=","*=","/=","%="].includes(s)){this.advance(),this.skipNewlines(!0);let a=this.parseExpression();s==="="&&i.type==="Identifier"?r=new ut([new nt(i,a)],At.LET):r=new qe(new Yt(s===":="?"=":s,i,a))}else r=new qe(i)}else r=new qe(i)}if(r&&(r._line=n,e&&this.match(_.COMMA)&&this.peek().line===n)){let i=[r];for(;this.match(_.COMMA)&&this.peek().line===n;){this.advance(),this.skipNewlines(!0);let s=this.parseStatement(!1);s&&i.push(s)}return new wt(i)}return r}isFunctionDeclaration(){let e=this.pos;try{let n=0;if(this.peek(n).type===_.IDENTIFIER&&this.peek(n+1).type===_.IDENTIFIER&&n++,this.peek(n).type!==_.IDENTIFIER||(n++,this.peek(n).type!==_.LPAREN))return!1;n++;let r=1;for(;r>0&&this.peek(n).type!==_.EOF;)this.peek(n).type===_.LPAREN&&r++,this.peek(n).type===_.RPAREN&&r--,n++;for(;this.peek(n).type===_.NEWLINE;)n++;return this.peek(n).type===_.OPERATOR&&this.peek(n).value==="=>"}finally{this.pos=e}}parseTypeExpression(){let e=this.expect(_.IDENTIFIER).value;for(;this.match(_.DOT)&&this.peek(1).type===_.IDENTIFIER;)this.advance(),e+="."+this.advance().value;if(this.match(_.OPERATOR,"<")){this.advance();let n=[];for(n.push(this.parseTypeExpression());this.match(_.COMMA);)this.advance(),this.skipNewlines(),n.push(this.parseTypeExpression());return this.expect(_.OPERATOR,">"),e+"<"+n.join(", ")+">"}return this.match(_.LBRACKET)&&this.peek(1).type===_.RBRACKET?(this.advance(),this.advance(),"array<"+e+">"):e}parseEnumDefinition(){this.expect(_.KEYWORD,"enum");let e=this.expect(_.IDENTIFIER).value;this.skipNewlines(),this.expect(_.INDENT);let n=[];for(;!this.match(_.DEDENT)&&!this.match(_.EOF)&&(this.skipNewlines(),!this.match(_.DEDENT));){if(this.match(_.COMMENT)){this.advance();continue}let s=this.expectIdentifierOrContextual().value,a=null;this.match(_.OPERATOR,"=")&&(this.advance(),a=this.expect(_.STRING).value),n.push({name:s,title:a}),this.skipNewlines()}this.match(_.DEDENT)&&this.advance();let r=n.map(s=>new Or(new be(s.name),new Tt(s.title!==null?s.title:s.name))),i=new Lr(r);return new ut([new nt(new be(e),i)],At.CONST)}parseTypeDefinition(){this.expect(_.KEYWORD,"type");let e=this.expect(_.IDENTIFIER).value;this.match(_.OPERATOR,"=>")&&this.advance(),this.skipNewlines(),this.expect(_.INDENT);let n=[];for(;!this.match(_.DEDENT)&&!this.match(_.EOF)&&(this.skipNewlines(),!this.match(_.DEDENT));){let r=this.parseTypeExpression(),i=this.expectIdentifierOrContextual().value,s=null;this.match(_.OPERATOR,"=")&&(this.advance(),this.skipNewlines(),s=this.parseExpression()),n.push({type:r,name:i,defaultValue:s}),this.skipNewlines()}return this.match(_.DEDENT)&&this.advance(),new ns(e,n)}parseVarDeclaration(){let e=this.advance().value,n=null,r=null;if(this.peek().type===_.IDENTIFIER&&this.peek(1).type===_.LBRACKET&&this.peek(2).type===_.RBRACKET)n=this.advance().value,this.advance(),n+="[]",this.advance(),r=this.expectIdentifierOrContextual().value;else if(this.peek().type===_.IDENTIFIER&&(this.peek(1).type===_.DOT||this.peek(1).type===_.IDENTIFIER||this.peek(1).type===_.OPERATOR&&this.peek(1).value==="<")){for(n=this.advance().value;this.match(_.DOT)&&this.peek(1).type===_.IDENTIFIER;)this.advance(),n+="."+this.advance().value;if(this.match(_.LBRACKET)&&this.peek(1).type===_.RBRACKET)this.advance(),this.advance(),n+="[]",r=this.expectIdentifierOrContextual().value;else if(this.match(_.OPERATOR,"<")){for(this.advance(),n+="<";!this.match(_.OPERATOR,">");)if(this.match(_.IDENTIFIER))for(n+=this.advance().value;this.match(_.DOT)&&this.peek(1).type===_.IDENTIFIER;)n+=".",this.advance(),n+=this.advance().value;else if(this.match(_.COMMA))n+=this.advance().value,this.skipNewlines();else break;this.match(_.OPERATOR,">")&&(n+=">",this.advance()),r=this.expectIdentifierOrContextual().value}else r=this.expectIdentifierOrContextual().value}else if(this.peek().type===_.IDENTIFIER)r=this.advance().value;else throw new Error(`Expected identifier after ${e} at ${this.peek().line}:${this.peek().column}`);this.functionNames.has(r)&&(r=r+"_var"),this.expect(_.OPERATOR,"="),this.skipNewlines(!0);let i=this.parseExpression(),s=new be(r);n&&(s.varType=n);let a=[new nt(s,i,n)];for(;this.match(_.COMMA)&&this.peek(1).type===_.KEYWORD&&(this.peek(1).value==="var"||this.peek(1).value==="varip");){this.advance();let o=this.parseVarDeclaration();a.push(...o.declarations)}return new ut(a,e)}isTypedVarDeclaration(){let e=0;if(this.peek(e).type!==_.IDENTIFIER)return!1;for(e++;this.peek(e).type===_.DOT&&this.peek(e+1).type===_.IDENTIFIER;)e+=2;if(this.peek(e).type===_.LBRACKET&&this.peek(e+1).type===_.RBRACKET)return e+=2,this.peek(e).type!==_.IDENTIFIER?!1:(e++,this.peek(e).type===_.OPERATOR&&this.peek(e).value==="=");if(this.peek(e).type===_.OPERATOR&&this.peek(e).value==="<"){e++;let n=1;for(;n>0&&this.peek(e).type!==_.EOF;)this.peek(e).type===_.OPERATOR&&this.peek(e).value==="<"?n++:this.peek(e).type===_.OPERATOR&&this.peek(e).value===">"&&n--,e++;return this.peek(e).type!==_.IDENTIFIER?!1:(e++,this.peek(e).type===_.OPERATOR&&this.peek(e).value==="=")}if(this.peek(e).type!==_.IDENTIFIER)return!1;for(e++;this.peek(e).type===_.IDENTIFIER;)e++;return this.peek(e).type===_.OPERATOR&&this.peek(e).value==="="}parseTypedVarDeclaration(){let e=this.advance().value;for(;this.match(_.DOT)&&this.peek(1).type===_.IDENTIFIER;)this.advance(),e+="."+this.advance().value;if(this.match(_.LBRACKET)&&this.peek(1).type===_.RBRACKET)this.advance(),this.advance(),e+="[]";else if(this.match(_.OPERATOR,"<")){for(this.advance(),e+="<";!this.match(_.OPERATOR,">");)if(this.match(_.IDENTIFIER))for(e+=this.advance().value;this.match(_.DOT)&&this.peek(1).type===_.IDENTIFIER;)e+=".",this.advance(),e+=this.advance().value;else if(this.match(_.COMMA))e+=this.advance().value,this.skipNewlines();else break;this.match(_.OPERATOR,">")&&(e+=">",this.advance())}else for(;this.peek().type===_.IDENTIFIER&&this.peek(1).type===_.IDENTIFIER;)e+=" "+this.advance().value;let n=this.expectIdentifierOrContextual().value;this.functionNames.has(n)&&(n=n+"_var"),this.expect(_.OPERATOR,"="),this.skipNewlines(!0);let r=this.parseExpression(),i=new be(n);i.varType=e;let s=[new nt(i,r,e)];for(;this.match(_.COMMA)&&this.peek(1).type===_.IDENTIFIER&&this.peek(2).type===_.OPERATOR&&this.peek(2).value==="=";){this.advance(),this.skipNewlines(!0);let a=this.expectIdentifierOrContextual().value;this.functionNames.has(a)&&(a=a+"_var"),this.expect(_.OPERATOR,"="),this.skipNewlines(!0);let o=this.parseExpression(),l=new be(a);l.varType=e,s.push(new nt(l,o,e))}return new ut(s,At.LET)}parseFunctionDeclaration(){let e=null;this.peek().type===_.IDENTIFIER&&this.peek(1).type===_.IDENTIFIER&&(e=this.advance().value);let n=this.expect(_.IDENTIFIER).value;this.functionNames.add(n),this.expect(_.LPAREN);let r=[];for(;!this.match(_.RPAREN)&&(this.skipNewlines(),!this.match(_.RPAREN));){let o=null;for(;this.peek().type===_.IDENTIFIER&&this.peek(1).type===_.IDENTIFIER&&this.peek(2).type!==_.LPAREN;)o&&(o+=" "),o=(o||"")+this.advance().value;if(this.peek().type===_.IDENTIFIER&&this.peek(1).type===_.OPERATOR&&this.peek(1).value==="<"){let u=this.parseTypeExpression();o=o?o+" "+u:u}if(this.peek().type===_.IDENTIFIER&&this.peek(1).type===_.LBRACKET&&this.peek(2).type===_.RBRACKET){let u=this.parseTypeExpression();o=o?o+" "+u:u}let l=this.expectIdentifierOrContextual().value,c=new be(l);if(o&&(c.varType=o),this.match(_.OPERATOR,"=")){this.advance(),this.skipNewlines();let u=this.parseExpression();r.push(new jr(c,u))}else r.push(c);this.match(_.COMMA)&&this.advance()}this.expect(_.RPAREN),this.skipNewlines(),this.expect(_.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 be(n);return e&&(a.returnType=e),new Dr(a,r,s,e)}parseMethodDeclaration(){this.expect(_.KEYWORD,"method");let e=null;this.peek().type===_.IDENTIFIER&&this.peek(1).type===_.IDENTIFIER&&this.peek(2).type===_.LPAREN&&(e=this.advance().value);let n=this.expectIdentifierOrContextual().value;this.expect(_.LPAREN);let r=[];for(;!this.match(_.RPAREN)&&(this.skipNewlines(),!this.match(_.RPAREN));){let o=null;for(;this.peek().type===_.IDENTIFIER&&this.peek(1).type===_.IDENTIFIER&&this.peek(2).type!==_.LPAREN;)o&&(o+=" "),o=(o||"")+this.advance().value;if(this.peek().type===_.IDENTIFIER&&this.peek(1).type===_.OPERATOR&&this.peek(1).value==="<"){let u=this.parseTypeExpression();o=o?o+" "+u:u}if(this.peek().type===_.IDENTIFIER&&this.peek(1).type===_.LBRACKET&&this.peek(2).type===_.RBRACKET){let u=this.parseTypeExpression();o=o?o+" "+u:u}let l=this.expectIdentifierOrContextual().value,c=new be(l);if(o&&(c.varType=o),this.match(_.OPERATOR,"=")){this.advance(),this.skipNewlines();let u=this.parseExpression();r.push(new jr(c,u))}else r.push(c);this.match(_.COMMA)&&this.advance()}this.expect(_.RPAREN),this.skipNewlines(),this.expect(_.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 be(n);return e&&(a.returnType=e),a.isMethod=!0,new Dr(a,r,s,e)}parseFunctionBody(){let e=[];if(!this.match(_.INDENT)){let n=this.parseExpression();return new wt([new Pr(n)])}for(this.advance();!this.match(_.DEDENT)&&!this.match(_.EOF)&&(this.skipNewlines(),!this.match(_.DEDENT));){let n=this.parseStatementOrSequence();Array.isArray(n)?e.push(...n):n&&e.push(n)}return this.match(_.DEDENT)&&this.advance(),e.length>0&&this._addImplicitReturn(e),new wt(e)}_addImplicitReturn(e){let n=e[e.length-1];n.type==="ExpressionStatement"?e[e.length-1]=new Pr(n.expression):n.type==="IfStatement"&&this._addImplicitReturnToIf(n)}_addImplicitReturnToIf(e){e.consequent&&e.consequent.type==="BlockStatement"&&e.consequent.body.length>0&&this._addImplicitReturn(e.consequent.body),e.alternate&&(e.alternate.type==="IfStatement"?this._addImplicitReturnToIf(e.alternate):e.alternate.type==="BlockStatement"&&e.alternate.body.length>0&&this._addImplicitReturn(e.alternate.body))}parseStatementOrSequence(){this.pos;let e=this.peek().line;if(this.match(_.KEYWORD,"if")){let r=this.parseIfStatement();return r&&(r._line=e),r}if(this.match(_.KEYWORD,"for"))return this.parseForStatement();if(this.match(_.KEYWORD,"while"))return this.parseWhileStatement();if(this.match(_.KEYWORD,"break")||this.match(_.KEYWORD,"continue")){let r=this.advance().value;return new qe(new be(r))}if(this.match(_.KEYWORD,"var")||this.match(_.KEYWORD,"varip"))return this.parseVarDeclaration();if(this.isTupleDestructuring())return this.parseTupleDestructuring();if(this.peek().type===_.IDENTIFIER&&this.isTypedVarDeclaration()){let r=this.parseTypedVarDeclaration();if(this.match(_.COMMA)&&this.peek(1).type===_.IDENTIFIER){let i=[r];for(;this.match(_.COMMA);)if(this.advance(),this.skipNewlines(!0),this.peek().type===_.IDENTIFIER&&this.isTypedVarDeclaration())i.push(this.parseTypedVarDeclaration());else{let s=this.parseExpression();if(this.match(_.OPERATOR)){let a=this.peek().value;if(["=",":="].includes(a)){this.advance(),this.skipNewlines(!0);let o=this.parseExpression();a==="="&&s.type==="Identifier"?i.push(new ut([new nt(s,o)],At.LET)):i.push(new qe(new Yt(a===":="?"=":a,s,o)))}}break}return i}return r}let n=[];for(;;){let r=this.parseExpression();if(this.match(_.OPERATOR)){let i=this.peek().value;if(["=",":=","+=","-=","*=","/=","%="].includes(i)){this.advance(),this.skipNewlines(!0);let s=this.parseExpression();if(i==="="&&r.type==="Identifier"?n.push(new ut([new nt(r,s)],At.LET)):n.push(new qe(new Yt(i===":="?"=":i,r,s))),this.match(_.COMMA)){this.advance(),this.skipNewlines();continue}break}else{if(n.length>0)n.push(new qe(r));else return new qe(r);break}}else if(this.match(_.COMMA)){n.push(new qe(r)),this.advance(),this.skipNewlines();continue}else{if(n.length>0)n.push(new qe(r));else return new qe(r);break}}return n.length>1?n:n.length===1?n[0]:null}parseIfStatement(){this.expect(_.KEYWORD,"if");let e=this.parseExpression();this.skipNewlines();let n=this.parseBlock(),r=null;return this.skipNewlines(),this.match(_.KEYWORD,"else")&&(this.advance(),this.skipNewlines(),this.match(_.KEYWORD,"if")?r=this.parseIfStatement():r=this.parseBlock()),new rs(e,n,r)}parseForStatement(){this.expect(_.KEYWORD,"for");let e=null,n=!1;if(this.match(_.LBRACKET)){this.advance();let r=[];for(;!this.match(_.RBRACKET);)this.skipNewlines(),r.push(new be(this.expectIdentifierOrContextual().value)),this.match(_.COMMA)&&this.advance();this.expect(_.RBRACKET),e=new Vr(r),n=!0}else{let r=this.expectIdentifierOrContextual().value;e=new be(r)}if(this.match(_.KEYWORD,"in")){this.advance();let r=this.parseExpression();this.skipNewlines();let i=this.parseBlock(),s=new ut([new nt(e,r)],At.CONST),a=new Mr(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(_.OPERATOR,"=");let r=this.parseExpression();this.expect(_.KEYWORD,"to");let i=this.parseExpression(),s=null;this.match(_.KEYWORD,"by")&&(this.advance(),s=this.parseExpression()),this.skipNewlines();let a=this.parseBlock(),o=new ut([new nt(e,r)],At.LET),l=new pt("<=",r,i),c=new vt(l,new pt("<=",e,i),new pt(">=",e,i)),u;return s?u=new vt(l,new Yt("+=",e,s),new Yt("-=",e,s)):u=new vt(l,new Fr("++",e),new Fr("--",e)),new Mr(o,c,u,a)}}parseWhileStatement(){this.expect(_.KEYWORD,"while");let e=this.parseExpression();this.skipNewlines();let n=this.parseBlock();return new is(e,n)}parseBlock(){if(!this.match(_.INDENT)){let r=this.parseStatement();return new wt(r?[r]:[])}let e=this.peek().indent;this.advance();let n=[];for(;!this.match(_.EOF);){if(this.skipNewlines(),this.match(_.DEDENT)){if(this.peek().indent<e)break;this.advance();continue}if(this.match(_.EOF))break;let r=this.parseStatement();r&&n.push(r)}return this.match(_.DEDENT)&&this.peek().indent<e&&this.advance(),new wt(n)}isTupleDestructuring(){if(!this.match(_.LBRACKET))return!1;let e=1;for(;;){for(;this.peek(e).type===_.NEWLINE;)e++;if(this.peek(e).type!==_.IDENTIFIER)return!1;for(e++;this.peek(e).type===_.NEWLINE;)e++;if(this.peek(e).type===_.RBRACKET){e++;break}else if(this.peek(e).type===_.COMMA){e++;continue}else return!1}for(;this.peek(e).type===_.NEWLINE;)e++;return this.peek(e).type===_.OPERATOR&&this.peek(e).value==="="}parseTupleDestructuring(){this.expect(_.LBRACKET);let e=[];for(;!this.match(_.RBRACKET);){this.skipNewlines();let r=this.expectIdentifierOrContextual().value;this.functionNames.has(r)&&(r=r+"_var"),e.push(new be(r)),this.match(_.COMMA)&&this.advance()}this.expect(_.RBRACKET),this.skipNewlines(),this.expect(_.OPERATOR,"="),this.skipNewlines(!0);let n=this.parseExpression();return new ut([new nt(new Vr(e),n)],At.CONST)}parseExpression(){return this.parseTernary()}parseTernary(){let e=this.parseLogicalOr();if(this.matchEx(_.OPERATOR,"?",!0)){this.advance(),this.skipNewlines(!0);let n=this.parseExpression();this.matchEx(_.COLON,null,!0)?this.advance():this.expect(_.COLON),this.skipNewlines(!0);let r=this.parseExpression();return new vt(e,n,r)}return e}parseLogicalOr(){let e=this.parseLogicalAnd();for(;this.matchEx(_.KEYWORD,"or",!0)||this.peekOperatorEx(["||"]);){this.advance(),this.skipNewlines(!0);let n=this.parseLogicalAnd();e=new pt("||",e,n)}return e}parseLogicalAnd(){let e=this.parseEquality();for(;this.matchEx(_.KEYWORD,"and",!0)||this.peekOperatorEx(["&&"]);){this.advance(),this.skipNewlines(!0);let n=this.parseEquality();e=new pt("&&",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 pt(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 pt(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 pt(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 pt(n,e,r)}return e}parseUnary(){if(this.match(_.OPERATOR)){let e=this.peek().value;if(["+","-","!"].includes(e))return this.advance(),this.skipNewlines(),new Rr(e,this.parseUnary())}return this.match(_.KEYWORD,"not")?(this.advance(),this.skipNewlines(),new Rr("!",this.parseUnary())):this.parsePostfix()}parsePostfix(){let e=this.parsePrimary();for(;;)if(this.match(_.OPERATOR,"<")){let n=this.pos;this.advance();let r=1,i=!0,s="",a=new Set(["float","int","string","bool","color","line","label","box","linefill","table"]);for(;r>0&&!this.match(_.EOF);)if(this.match(_.OPERATOR,"<"))r++,this.advance();else if(this.match(_.OPERATOR,">"))r--,this.advance();else if(this.match(_.IDENTIFIER)||this.match(_.COMMA)||this.match(_.DOT))r===1&&this.match(_.IDENTIFIER)&&s===""&&(s=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")&&a.has(s)&&(e.property=new be("new_"+s)),i&&this.match(_.LPAREN)){e=this.parseCallExpression(e);continue}else{if(i)continue;break}}else if(this.match(_.LPAREN))e=this.parseCallExpression(e);else if(this.match(_.DOT)){this.advance(),this.skipNewlines();let n=this.peek();if(n.type!==_.IDENTIFIER&&n.type!==_.KEYWORD)throw new Error(`Expected property name but got ${n.type} at ${n.line}:${n.column}`);this.advance(),e=new Br(e,new be(n.value),!1)}else if(this.match(_.LBRACKET)){if(this.isTupleDestructuring())break;this.advance(),this.skipNewlines();let n=this.parseExpression();this.expect(_.RBRACKET),e=new Br(e,n,!0)}else break;return e}parseCallExpression(e){this.expect(_.LPAREN);let n=[],r=[];for(;!this.match(_.RPAREN)&&(this.skipNewlines(),!this.match(_.RPAREN));){if((this.peek().type===_.IDENTIFIER||this.peek().type===_.KEYWORD)&&this.peek(1).type===_.OPERATOR&&this.peek(1).value==="="){let i=this.advance().value;this.advance(),this.skipNewlines();let s=this.parseExpression();r.push(new Or(new be(i),s))}else n.push(this.parseExpression());this.match(_.COMMA)&&this.advance(),this.skipNewlines()}return this.expect(_.RPAREN),r.length>0&&n.push(new Lr(r)),new ss(e,n)}parsePrimary(){let e=this.peek();if(this.match(_.NUMBER)){let n=this.advance();return new Tt(n.value,n.raw)}if(this.match(_.STRING)){let n=this.advance();return new Tt(n.value)}if(this.match(_.BOOLEAN)){let n=this.advance();return new Tt(n.value)}if(this.match(_.IDENTIFIER)||e.type===_.KEYWORD&&cs.CONTEXTUAL_KEYWORDS.has(e.value)){let n=this.advance().value;return this.functionNames.has(n)&&this.peek().type!==_.LPAREN&&!this.isCurrentFunctionParam(n)&&(n=n+"_var"),new be(n)}if(this.match(_.LBRACKET))return this.parseArrayLiteral();if(this.match(_.LPAREN)){this.advance(),this.skipNewlines();let n=this.parseExpression();return this.skipNewlines(),this.expect(_.RPAREN),n}if(this.match(_.KEYWORD,"if"))return this.parseIfExpression();if(this.match(_.KEYWORD,"switch"))return this.parseSwitchExpression();if(this.match(_.KEYWORD,"for"))return this.parseForExpression();if(this.match(_.KEYWORD,"while"))return this.parseWhileExpression();throw new Error(`Unexpected token ${e.type} \'${e.value}\' at ${e.line}:${e.column}`)}parseArrayLiteral(){this.expect(_.LBRACKET);let e=[];for(;!this.match(_.RBRACKET)&&(this.skipNewlines(),!this.match(_.RBRACKET));)e.push(this.parseExpression()),this.match(_.COMMA)&&this.advance(),this.skipNewlines();return this.expect(_.RBRACKET),new as(e)}parseIfExpression(){this.expect(_.KEYWORD,"if");let e=this.parseExpression();this.skipNewlines(),this.expect(_.INDENT);let n=[];for(;!this.match(_.DEDENT)&&!this.match(_.EOF)&&(this.skipNewlines(),!this.match(_.DEDENT));){let a=this.parseStatement();a&&n.push(a)}this.advance();let r=[];if(this.match(_.KEYWORD,"else"))if(this.advance(),this.skipNewlines(),this.match(_.KEYWORD,"if")){let a=this.parseIfExpression();if(this.needsIIFE(n,r)){let o=new vt(e,new wt(n),a);return o.needsIIFE=!0,o.consequentStmts=n,o.alternateExpr=a,o}else return new vt(e,this.getBlockValue(n),a)}else{for(this.expect(_.INDENT);!this.match(_.DEDENT)&&!this.match(_.EOF)&&(this.skipNewlines(),!this.match(_.DEDENT));){let a=this.parseStatement();a&&r.push(a)}this.advance()}if(this.needsIIFE(n,r)){let a=new vt(e,new wt(n),new wt(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 vt(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(_.KEYWORD,"switch");let e=null;!this.match(_.NEWLINE)&&!this.match(_.INDENT)&&(e=this.parseExpression()),this.skipNewlines(),this.expect(_.INDENT);let n=[];for(;!this.match(_.DEDENT)&&!this.match(_.EOF)&&(this.skipNewlines(),!this.match(_.DEDENT));){let r=null;this.match(_.OPERATOR,"=>")||(r=this.parseExpression()),this.expect(_.OPERATOR,"=>"),this.skipNewlines();let i=[];if(this.match(_.INDENT)){for(this.advance();!this.match(_.DEDENT)&&!this.match(_.EOF)&&(this.skipNewlines(),!this.match(_.DEDENT));){let a=this.parseStatement();a&&i.push(a)}this.advance()}else{this.noLineContinuation=!0;let a=this.parseStatement();this.noLineContinuation=!1,a&&i.push(a)}let s=this.getBlockValue(i);n.push(new ls(r,s,i)),this.skipNewlines()}return this.advance(),new os(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)}};dn(hl,"CONTEXTUAL_KEYWORDS",new Set(["type","method","enum"]));var j0=hl,$0=Object.defineProperty,W0=(t,e,n)=>e in t?$0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,It=(t,e,n)=>W0(t,typeof e!="symbol"?e+"":e,n),U0=new Set(Ps),us=class{constructor(e={}){It(this,"indent"),It(this,"indentStr"),It(this,"output"),It(this,"sourceCode"),It(this,"sourceLines"),It(this,"lastCommentedLine"),It(this,"includeSourceComments"),It(this,"paramRenameCounter"),It(this,"functionParams"),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}generate(e){if(this.output=[],this.indent=0,this.lastCommentedLine=-1,this.functionParams=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.collectFunctionParams(e),this.renameConflictingVariables(e)}renameConflictingVariables(e){let n=new Map;this.collectConflictingVarNames(e,n),n.size>0&&this.renameVariableRefsInAST(e,n)}isReservedName(e){return!!e&&(J_.has(e)||Aa.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++}`);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==="CallExpression"){if(e.callee?.type==="Identifier"&&n.has(e.callee.name)?Aa.has(e.callee.name)&&(e.callee.name=n.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))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=[];for(let r of e.params)r.type==="Identifier"?n.push(r.name):r.type==="AssignmentPattern"&&r.left?.name&&n.push(r.left.name);this.functionParams.set(e.id.name,n)}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":return this.generateBlockStatement(e);case"TypeDefinition":return this.generateTypeDefinition(e);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 c of e.params){let u=c.type==="AssignmentPattern"?c.left.name:c.name;if(u&&U0.has(u)){let h=`${u}_$${this.paramRenameCounter++}`;r.set(u,h)}}let i=c=>c.type==="Identifier"&&c.name==="this"||c.type==="AssignmentPattern"&&c.left?.name==="this",s=new Map;if(n&&e.params.length>0&&i(e.params[0])&&s.set("this","self"),r.size>0||s.size>0){for(let c of e.params){let u=c.type==="AssignmentPattern"?c.left:c;if(u?.type==="Identifier"){let h=r.get(u.name)??s.get(u.name);h&&(u.name=h)}c.type==="AssignmentPattern"&&c.right&&(r.size>0&&this.renameParamRefsInBody(c.right,r),s.size>0&&this.renameIdentifiersInAST(c.right,s))}r.size>0&&this.renameParamRefsInBody(e.body,r),s.size>0&&this.renameIdentifiersInAST(e.body,s)}let a=n?`$M_${e.id.name}`:e.id.name;this.write("function "),this.write(a),this.write("(");let o=e.params;for(let c=0;c<o.length;c++){let u=o[c];u.type==="Identifier"?this.write(u.name):u.type==="AssignmentPattern"&&(this.write(u.left.name),this.write(" = "),this.generateExpression(u.right)),c<o.length-1&&this.write(", ")}this.write(") "),this.generateBlockStatement(e.body,!1),this.write(`\n`),n&&(this.write(this.indentStr.repeat(this.indent)),this.write(`${a}.__pineMethod__ = true;\n`));let l=[];for(let c=0;c<e.params.length;c++){let u=e.params[c],h=u.type==="AssignmentPattern"?u.left?.name:u.name;if(n&&c===0&&h==="self")continue;let p=u.type==="AssignmentPattern"?u.left?.varType:u.varType;h&&p&&l.push([h,p])}if(l.length>0){this.write(this.indentStr.repeat(this.indent));let c=l.map(([u,h])=>`${JSON.stringify(u)}: ${JSON.stringify(h)}`).join(", ");this.write(`${a}.__pineParamTypes__ = {${c}};\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.init&&i.init.type==="ConditionalExpression"&&i.init.needsIIFE){let o=i.id.type==="Identifier"?i.id.name:null;if(o){this.write(this.indentStr.repeat(this.indent)),this.write(n),this.write(" "),this.write(o),this.write(`;\n`),this.generateIfStatementWithAssignment(i.init,o);continue}}if(this.write(this.indentStr.repeat(this.indent)),this.write(n),this.write(" "),i.id.type==="Identifier")this.write(i.id.name);else if(i.id.type==="ArrayPattern"){let o=new Set;this.write("[");for(let l=0;l<i.id.elements.length;l++){let c=i.id.elements[l].name;if(o.has(c)){let u=`${c}${this.paramRenameCounter++}`;i.id.elements[l].name=u,c=u}o.add(c),this.write(c),l<i.id.elements.length-1&&this.write(", ")}this.write("]")}i.init&&(this.write(" = "),this.generateExpression(i.init)),this.write(`;\n`);let s=i.id?.varType,a=i.id?.type==="Identifier"?i.id.name:null;a&&typeof s=="string"&&/^[A-Za-z_$][\\w$]*$/.test(s)&&s[0]===s[0].toUpperCase()&&(this.write(this.indentStr.repeat(this.indent)),this.write(`"__pineUdtVar:${a}=${s}";\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];if(this.write(`${e.init.kind} `),n.id.type==="Identifier")this.write(n.id.name);else if(n.id.type==="ArrayPattern"){let r=new Set;this.write("[");for(let i=0;i<n.id.elements.length;i++){let s=n.id.elements[i].name;if(r.has(s)){let a=`${s}${this.paramRenameCounter++}`;n.id.elements[i].name=a,s=a}r.add(s),this.write(s),i<n.id.elements.length-1&&this.write(", ")}this.write("]")}this.write(" of "),this.generateExpression(n.init)}this.write(") "),this.generateBlockStatement(e.body,!1);return}if(this.write("for ("),e.init)if(e.init.type==="VariableDeclaration"){let n=e.init.declarations[0];this.write(`${e.init.kind} ${n.id.name}`),n.init&&(this.write(" = "),this.generateExpression(n.init))}else 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"&&e.raw.includes(".")&&!/[.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(" "),this.generateExpression(e.right)}generateUpdateExpression(e){e.prefix?(this.write(e.operator),this.generateExpression(e.argument)):(this.generateExpression(e.argument),this.write(e.operator))}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=n?this.functionParams.get(n):null,i=e.arguments.length>0?e.arguments[e.arguments.length-1]:null;if(i?.type==="ObjectExpression"&&r){let s=e.arguments.slice(0,-1),a=new Map;for(let u of i.properties){let h=u.key?.name||u.key?.value;h&&a.set(h,u.value)}let o=[],l=-1;for(let u=0;u<r.length;u++)u<s.length?(o.push(s[u]),l=u):a.has(r[u])?(o.push(a.get(r[u])),l=u):o.push(null);let c=o.slice(0,l+1);for(let u=0;u<c.length;u++)c[u]===null?this.write("undefined"):this.generateExpression(c[u]),u<c.length-1&&this.write(", ")}else for(let s=0;s<e.arguments.length;s++){let a=e.arguments[s];a.type==="AssignmentExpression"&&a.operator==="="?this.generateExpression(a.right):this.generateExpression(a),s<e.arguments.length-1&&this.write(", ")}this.write(")")}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`)}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{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.indent--,this.write(this.indentStr.repeat(this.indent)),this.write(`}\n`),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{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.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("})()")}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}}};function dl(t){let e=/^\\s*\\/\\/\\s*@version\\s*=\\s*(\\d+)\\s*$/im,n=t.match(e);return n&&n[1]?parseInt(n[1],10):null}function Fs(t,e={}){let n=dl(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 es(t).tokenize(),i=new j0(r).parse(),s={...e,sourceCode:t},a=new us(s).generate(i);return{success:!0,version:n,code:a,ast:i,tokens:r}}catch(r){return{success:!1,version:n,error:r.message,stack:r.stack}}}var q0=new Set(["security_lower_tf","security"]),fl=new Set(["type","loc","start","end","range","parent","leadingComments","trailingComments"]);function z0(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:q0.has(e.property.name)}function K0(t){let e=t?.arguments?.[2];return e?.type==="Identifier"&&typeof e.name=="string"?e.name:null}function H0(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]);z0(i)&&e.push({call:i,path:a});for(let o of Object.keys(i)){if(fl.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 ps(t){return t?t.type==="FunctionExpression"||t.type==="ArrowFunctionExpression"||t.type==="FunctionDeclaration":!1}function Et(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(Et(r,e,n+1)),{...t,body:s}}case"IfStatement":return r===t.test?{...t,test:Et(r,e,n+1),consequent:{type:"BlockStatement",body:[]},alternate:null}:r===t.consequent?{...t,consequent:Et(r,e,n+1),alternate:null}:r===t.alternate?{...t,alternate:Et(r,e,n+1)}:t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"ForInStatement":case"ForOfStatement":return r===t.body?{...t,body:Et(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(Et(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(Et(r,e,n+1)),{...t,consequent:s}}return t}case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":return r===t.body?{...t,body:Et(r,e,n+1)}:t;default:return t}}function G0(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 Y0(t,e,n){let r=t.body||[];for(let i=0;i<r.length;i++){let s=r[i];if(s!==n&&Z0(s,e))return i}return-1}function Z0(t,e){let n=!1,r=new WeakSet;function i(s){if(!(n||!s||typeof s!="object")&&!r.has(s)){if(r.add(s),G0(s)===e){n=!0;return}for(let a of Object.keys(s)){if(fl.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 X0(t,e){let n=-1;for(let p=1;p<e.length;p++)if(ps(e[p])){n=p;break}if(n<0)return null;let r=e[n];for(let p=n+1;p<e.length;p++)if(ps(e[p]))return null;if(r.type!=="FunctionDeclaration"||!r.id?.name)return null;let i=r.id.name,s=e.slice(n),a=Et(r,s,0),o=Y0(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 Q0(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 = ${Ds(n)}\n; return _r;`;return new Function("",r)()}function J0(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=H0(r.body);for(let{call:s,path:a}of i){let o=K0(s);if(!o||o in e)continue;let l=a.some(h=>ps(h)),c=null;if(l)c=X0(r.body,a);else{let h=Et(r.body,a,0);c=h&&h.body?h.body:[]}if(!c||c.length===0)continue;let u=Q0(r,c);e[o]=u}return e}function ex(t){if(typeof t=="function")return{code:t.toString(),version:null};{let e=dl(t);if(e===null)return{code:t,version:null};if(e>=5){let n=Fs(t);if(n.success)return{code:n.code,version:e};throw new Error(`Failed to transpile Pine Script version ${e}: ${n.error}`)}else throw new Error(`Unsupported Pine Script version ${e}. Only version 5 and above are supported.`)}}function tx(t,e={debug:!1,ln:!1}){typeof e=="boolean"&&(e={debug:e,ln:!0});let{debug:n}=e,{code:r,version:i}=ex(t),s=r;s=s0(s);let a=n?s.split(`\n`):[],o=As(s,{ecmaVersion:"latest",sourceType:"module",locations:n});a0(o),n0(o),t0(o);let l=new Gi;c0(o,l),o0(o,l);let c=p0(o,l)||"";if(i!==null&&i<6&&b0(o),D0(o,l,c,e,a),T0(o),N0(o),o.type==="Program"&&o.body.length>0){let m=o.body[0],x=m?.expression||m;x.body?.type==="BlockStatement"&&x.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=q_||Ts||void 0,h=Object.assign({},u,{LineComment(m,x){x.write("//"+m.value)}}),p=Ds(o,{generator:h,comments:n}),d=typeof process<"u"&&process?.env?.PINETS_DISABLE_LTF_SLICING==="1"?{}:J0(o),f=new Function("",`var _r = ${p}\n; return _r;`)(this);return d&&Object.keys(d).length>0&&(f._ltfSlices=d),f}var Ta={"":["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"]},nx={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"};function rx(t){if(typeof t!="string")return[];let e=Fs(t);if(!e.success||!e.ast)return[];let n=ix(e.ast),r=sx(e.ast),i=[],s=new Set;return Dt(e.ast,a=>{let o=ax(a,n,r);if(o){if(o.varId!==void 0){if(s.has(o.varId)){console.warn(`[Indicator] duplicate input variable "${o.varId}" \\u2014 first declaration wins for .input access`);return}s.add(o.varId)}i.push(o)}}),i}function ix(t){let e=new Map;return Dt(t,n=>{if(n.type==="VariableDeclaration")for(let r of n.declarations??[]){let i=r?.id?.name,s=r?.init;if(!i||!s||s.type!=="ObjectExpression"||!(s.properties??[]).every(a=>a.value?.type==="Literal"&&typeof a.value.value=="string")||s.properties.length===0)return;for(let a of s.properties)e.set(`${i}.${a.key.name}`,a.value.value)}}),e}function sx(t){let e=new Map;return Dt(t,n=>{if(n.type==="VariableDeclaration")for(let r of n.declarations??[])r?.id?.type==="Identifier"&&r.init&&!e.has(r.id.name)&&e.set(r.id.name,r.init)}),e}function ax(t,e,n){if(t.type!=="VariableDeclaration")return null;for(let r of t.declarations??[]){let i=r?.init;if(!i||i.type!=="CallExpression")continue;let s=i.callee,a=null;if(s?.type==="MemberExpression"&&s.object?.type==="Identifier"&&s.object.name==="input"&&s.property?.type==="Identifier"?a=s.property.name:s?.type==="Identifier"&&s.name==="input"&&(a=""),a===null||a!==""&&!(a==="int"||a==="float")&&!(a in Ta))continue;let o=i.arguments??[],l=o[o.length-1],c=l?.type==="ObjectExpression",u=c?o.slice(0,-1):o.slice(),h=c?l.properties??[]:[],p={};a==="int"||a==="float"?ox(u,h,p):ml(Ta[a],u,p);for(let x of h)x.type!=="Property"||!x.key?.name||(p[x.key.name]=x.value);let d={};for(let x of Object.keys(p))d[x]=pr(p[x],e,n);let f=a===""?lx(d.defval):nx[a];if(!f)continue;let m={type:f,defval:d.defval};return r.id?.type==="Identifier"&&typeof r.id.name=="string"&&(m.varId=r.id.name),d.title!==void 0&&(m.title=String(d.title)),d.tooltip!==void 0&&(m.tooltip=String(d.tooltip)),d.group!==void 0&&(m.group=String(d.group)),d.inline!==void 0&&(m.inline=String(d.inline)),d.confirm!==void 0&&(m.confirm=!!d.confirm),d.active!==void 0&&(m.active=!!d.active),d.display!==void 0&&(m.display=cx(d.display)),d.options!==void 0&&Array.isArray(d.options)&&(m.options=d.options),typeof d.minval=="number"&&(m.minval=d.minval),typeof d.maxval=="number"&&(m.maxval=d.maxval),typeof d.step=="number"&&(m.step=d.step),m}return null}function ox(t,e,n){let r=new Set(e.map(i=>i.key?.name).filter(Boolean)).has("options")||t[2]?.type==="ArrayExpression"?["defval","title","options","tooltip","inline","group","confirm","display","active"]:["defval","title","minval","maxval","step","tooltip","inline","group","confirm","display","active"];ml(r,t,n)}function ml(t,e,n){for(let r=0;r<e.length&&r<t.length;r++){let i=t[r];n[i]===void 0&&(n[i]=e[r])}}function pr(t,e,n,r=new Set){if(t!=null)switch(t.type){case"Literal":return t.value;case"Identifier":if(_s.has(t.name))return t.name;if(n?.has(t.name)&&!r.has(t.name)){r.add(t.name);let i=pr(n.get(t.name),e,n,r);if(r.delete(t.name),i!==void 0)return i}return t.name;case"MemberExpression":{let i=t.object?.type==="Identifier"?t.object.name:null,s=t.property?.type==="Identifier"?t.property.name:null;if(i&&s){let a=`${i}.${s}`;return e.has(a)?e.get(a):i==="display"?s:a}return}case"CallExpression":{let i=t.callee;if(i?.type==="MemberExpression"&&i.object?.type==="Identifier"&&i.object.name==="color"&&i.property?.type==="Identifier"){let s=i.property.name,a=(t.arguments??[]).map(l=>pr(l,e,n,r)),o=l=>Math.max(0,Math.min(1,l));if(s==="rgb"){let[l,c,u,h]=a;if(typeof l=="number"&&typeof c=="number"&&typeof u=="number"){let p=o(1-(typeof h=="number"?h:0)/100);return Ci(l,c,u,p)}}else if(s==="new"){let l=uo(a[0]),c=a[1];if(l&&typeof c=="number")return Ci(l[0],l[1],l[2],o(1-c/100))}}return}case"ArrayExpression":return(t.elements??[]).map(i=>pr(i,e,n,r));case"UnaryExpression":return t.operator==="-"&&t.argument?.type==="Literal"&&typeof t.argument.value=="number"?-t.argument.value:void 0;default:return}}function lx(t){return typeof t=="boolean"?"bool":typeof t=="number"?Number.isInteger(t)?"int":"float":typeof t=="string"?_s.has(t)?"source":t.startsWith("#")?"color":"string":null}function cx(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 Dt(t,e){if(!(!t||typeof t!="object")){if(e(t),Array.isArray(t.body))for(let n of t.body)Dt(n,e);else t.body&&Dt(t.body,e);if(Array.isArray(t.consequent))for(let n of t.consequent)Dt(n,e);else t.consequent&&Dt(t.consequent,e);if(t.alternate&&Dt(t.alternate,e),Array.isArray(t.declarations))for(let n of t.declarations)Dt(n,e)}}function yl(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 ux(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 ux(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 ${hn(e)}`);break;case"float":case"price":case"time":if(typeof e!="number"||!Number.isFinite(e))throw new TypeError(`[${n}] "${r}" expects a number; got ${hn(e)}`);break;case"bool":if(typeof e!="boolean")throw new TypeError(`[${n}] "${r}" expects a boolean; got ${hn(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 ${hn(e)}`);break}if(t.options&&!t.options.some(i=>px(i,e)))throw new RangeError(`[${n}] "${r}" value ${hn(e)} is not one of: ${t.options.map(hn).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 px(t,e){return t===e?!0:typeof t=="number"&&typeof e=="number"?Math.abs(t-e)<1e-12:!1}function hn(t){return t===null?"null":typeof t=="string"?JSON.stringify(t):String(t)}function hx(t,e){let n=new Map,r=[];for(let a of t){let o=a.varId??a.title;if(!o)continue;let l=a.title&&a.title!==o?[a.title]:void 0;n.set(o,a),r.push({key:o,type:a.type,defval:a.defval,options:a.options,minval:a.minval,maxval:a.maxval,aliases:l})}let{proxy:i,values:s}=yl(r,"Indicator.input",e,void 0,"input key");return{proxy:i,values:s,metaByKey:n}}var gl=[{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}],_l=[...gl.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"}],xl=[...gl.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 dx(t){return t==="strategy"?xl:_l}function fx(t){return typeof t=="string"?mx(t):typeof t=="function"?yx(t):{type:null,args:{}}}function mx(t){let e=Fs(t);if(!e.success||!e.ast)return{type:null,args:{}};let n=null;return $r(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:wl(i.arguments??[],bl(s.name))}))}),n??{type:null,args:{}}}function yx(t){let e;try{e=As(`(${t.toString()})`,{ecmaVersion:"latest"})}catch{return{type:null,args:{}}}let n=null;return $r(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:wl(r.arguments??[],bl(i.name))}))}),n??{type:null,args:{}}}function bl(t){return t==="strategy"?xl:_l}function wl(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]=hs(s[a])}if(i)for(let a of r.properties??[])a.type!=="Property"||!a.key?.name||(n[a.key.name]=hs(a.value));return n}function hs(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(hs);default:return}}function $r(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)$r(i,e);else r&&typeof r=="object"&&typeof r.type=="string"&&$r(r,e)}}}function gx(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}=yl(i,"Indicator.prop",n,e);return{proxy:s,values:a,propByName:r}}var _x=Object.defineProperty,xx=(t,e,n)=>e in t?_x(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ge=(t,e,n)=>xx(t,typeof e!="symbol"?e+"":e,n),Qt=class t{constructor(e,n={}){Ge(this,"source"),Ge(this,"inputs"),Ge(this,"_prepared",null),Ge(this,"_inputMeta",null),Ge(this,"_inputValues",{}),Ge(this,"_explicitOverrides",new Set),Ge(this,"_inputProxy",null),Ge(this,"_propMeta",null),Ge(this,"_propValues",{}),Ge(this,"_propProxy",null),Ge(this,"_declarationType",null),Ge(this,"_sourcePropArgs",{}),Ge(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=tx(this.source,{debug:!!e.debug,ln:e.ln}),r=bx(n),i=n._ltfSlices;return this._prepared={fn:n,inputs:this.getRuntimeInputs(),usesVisibleRange:r,ltfSlices:i},this._prepared}usesVisibleRange(){return this.prepare().usesVisibleRange}getRuntimeInputs(){let e={...this.inputs??{}};if(this._inputMeta)for(let n of this._explicitOverrides)e[n]=this._inputValues[n];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=rx(this.source);for(let n of this._inputMeta)n.type==="color"&&n.defval!==void 0&&(n.defval=gh(n.defval));let e=hx(this._inputMeta,n=>this._explicitOverrides.add(n));this._inputValues=e.values,this._inputProxy=e.proxy}_getInputProxy(){return this._ensureInputsScanned(),this._inputProxy}_ensurePropsScanned(){if(this._propMeta)return;let e=fx(this.source);this._declarationType=e.type,this._sourcePropArgs=e.args,this._propMeta=dx(e.type);let n=gx(this._propMeta,this._sourcePropArgs,r=>this._explicitPropOverrides.add(r));this._propValues=n.values,this._propProxy=n.proxy}_getPropProxy(){return this._ensurePropsScanned(),this._propProxy}};function bx(t){let e=t.toString();return X_.some(n=>{let r=n.replace(/\\./g,"\\\\.");return new RegExp(`\\\\b${r}\\\\b`).test(e)})}var wx=Object.defineProperty,vx=(t,e,n)=>e in t?wx(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,oe=(t,e,n)=>vx(t,typeof e!="symbol"?e+"":e,n),Da={1:6e4,3:18e4,5:3e5,15:9e5,30:18e5,60:36e5,120:72e5,180:108e5,240:144e5,"4H":144e5,"1D":864e5,D:864e5,"1W":6048e5,W:6048e5,"1M":30*864e5,M:30*864e5};function Ex(t){return t?Da[t]??Da[t.toUpperCase()]??864e5:864e5}var Ut=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,oe(this,"data",[]),oe(this,"open",[]),oe(this,"high",[]),oe(this,"low",[]),oe(this,"close",[]),oe(this,"volume",[]),oe(this,"hl2",[]),oe(this,"hlc3",[]),oe(this,"ohlc4",[]),oe(this,"hlcc4",[]),oe(this,"openTime",[]),oe(this,"closeTime",[]),oe(this,"_readyPromise",null),oe(this,"_ready",!1),oe(this,"_debugSettings",{ln:!1,debug:!1}),oe(this,"_transpiledCode",null),oe(this,"_currentIndicator",null),oe(this,"_isSecondaryContext",!1),oe(this,"_syminfo"),oe(this,"_chartTimezone",null),oe(this,"_maxLoops",5e5),oe(this,"_alertMode","realtime"),oe(this,"_viewportLeft"),oe(this,"_viewportRight"),oe(this,"_usesVisibleRange",!1),oe(this,"_lastRunViewport",{}),oe(this,"_lastResult",null),oe(this,"_lastPineTSCode",null),this._readyPromise=new Promise(o=>{this.loadMarketData(e,n,r,i,s,a).then(l=>{let c=l;this.data=c;let u=c.map(C=>C.open),h=c.map(C=>C.close),p=c.map(C=>C.high),d=c.map(C=>C.low),f=c.map(C=>C.volume),m=c.map(C=>(C.high+C.low+C.close)/3),x=c.map(C=>(C.high+C.low)/2),b=c.map(C=>(C.high+C.low+C.open+C.close)/4),w=c.map(C=>(C.high+C.low+C.close+C.close)/4),E=c.map(C=>C.openTime),v=Ex(this.timeframe),I=c.map(C=>C.closeTime!=null?C.closeTime:C.openTime+v);this.open=u,this.close=h,this.high=p,this.low=d,this.volume=f,this.hl2=x,this.hlc3=m,this.ohlc4=b,this.hlcc4=w,this.openTime=E,this.closeTime=I,e&&e.getSymbolInfo?e.getSymbolInfo(n).then(C=>{this._syminfo=C,this._ready=!0,o(!0)}).catch(C=>{console.warn("Failed to get symbol info, using default values:",C),this._ready=!0,o(!0)}):(this._ready=!0,o(!0))})})}get transpiledCode(){return this._transpiledCode}markAsSecondary(){this._isSecondaryContext=!0}setTimezone(e){this._chartTimezone=e}setMaxLoops(e){this._maxLoops=e}setAlertMode(e){this._alertMode=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}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=Qt.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=Qt.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],x=m&&m.closeTime<Date.now(),b=f.idx>=f.marketData.length-1;(!x||b)&&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);this._transpiledCode=e;let s=e._ltfSlices;return s&&(i._ltfTruncatedBodies=s),await this._executeIterations(i,e,this.data.length-r,this.data.length),i}async _runComplete(e,n){await this.ready(),n||(n=this.data.length);let r=e.prepare(this._debugSettings);this._usesVisibleRange=r.usesVisibleRange;let i=this._initializeContext(e.source??null,r.inputs,this._isSecondaryContext);this._transpiledCode=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);let s=e.prepare(this._debugSettings);this._usesVisibleRange=s.usesVisibleRange;let a=this._initializeContext(e.source??null,s.inputs,this._isSecondaryContext);this._transpiledCode=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),x=this._getResultLength(a.result),b=o+m;i&&b>=c&&m>1?(await this._executeIterations(a,this._transpiledCode,o,b-1),l=this._snapshotVarState(a),await this._executeIterations(a,this._transpiledCode,b-1,b)):i&&b>=c&&m===1?await this._executeIterations(a,this._transpiledCode,o,b):await this._executeIterations(a,this._transpiledCode,o,b),o+=m,yield this._createPageContext(a,x);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 _n({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]=n.closeTime}_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(e.closeTime)}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;if(i?this._restoreVarState(e,i):this._removeLastResult(e),Array.isArray(e.result))e.result.pop();else if(typeof e.result=="object"&&e.result!==null)for(let o in e.result)Array.isArray(e.result[o])&&e.result[o].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(),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}_removeLastResult(e){if(Array.isArray(e.result))e.result.pop();else if(typeof e.result=="object"&&e.result!==null)for(let i in e.result)Array.isArray(e.result[i])&&e.result[i].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();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 y?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 y){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=wm(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 y&&u&&typeof u.len=="number"&&(c.data.length>u.len&&(c.data.length=u.len),u.len>0&&u.lastVal!==void 0&&(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++})}vm(e.strategy,n.strategy)}_initializeContext(e,n={},r=!1){let i=new _n({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=this._syminfo;let s=jn(String(this.tickerId??"")).modifier;return i.chartStyle=s==="heikinashi"?"heikinashi":"standard",this._syminfo&&s==="heikinashi"&&(i.pine.syminfo={...this._syminfo,tickerid:Ai(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._propOverrides=this._currentIndicator?.getRuntimePropOverrides()??{},i.pineTSCode=e,i.isSecondaryContext=r,i.data.close=new y([]),i.data.open=new y([]),i.data.high=new y([]),i.data.low=new y([]),i.data.volume=new y([]),i.data.hl2=new y([]),i.data.hlc3=new y([]),i.data.ohlc4=new y([]),i.data.hlcc4=new y([]),i.data.openTime=new y([]),i.data.closeTime=new y([]),i.length=this.data.length,i}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){hm(e),im(e),ci(e,"open");let c=dm(e);c&&ci(e,"extreme"),pm(e,"intrabar"),c||ci(e,"extreme"),fm(e)}let o=await n(e);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 y?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 y){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&&mm(e)}},Ma={"1m":6e4,"3m":18e4,"5m":3e5,"15m":9e5,"30m":18e5,"1h":36e5,"2h":72e5,"4h":144e5,"1d":864e5,"1w":6048e5,"1M":2592e6},On={"1S":1,"5S":5,"10S":10,"15S":15,"30S":30,1:60,3:180,5:300,15:900,30:1800,45:2700,60:3600,120:7200,180:10800,240:14400,D:86400,W:604800,M:2592e3};function Vn(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 St(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=b=>parseInt(c.find(w=>w.type===b).value,10),h=u("year"),p=u("month"),d=u("day"),f=u("hour");f===24&&(f=0);let m=u("minute"),x=Date.UTC(h,p-1,d,f,m,0,0)-l;return l-x}function Pa(t,e,n,r,i=1){if(e==="24x7")return Vn(t,r,i);let s=e.split("-")[1];if(!s||s.length!==4)return Vn(t,r,i);let a=s.slice(0,2),o=s.slice(2,4),l=`${a}:${o}`,c=Ra(t,n);if(r==="second"||r==="minute"||r==="hour"){let u=t+i*{second:1e3,minute:6e4,hour:36e5}[r],h=St(c,l,n);return Math.min(u,h)}if(r==="day")return St(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=Ra(p,n);return St(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 St(m,l,n)}return Vn(t,r,i)}function Ra(t,e){return new Intl.DateTimeFormat("en-CA",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(t))}function Sx(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 Cx=["1S","5S","10S","15S","30S","1","3","5","15","30","45","60","120","180","240","D","W","M"];function Nx(t,e){if(t==="W"||t==="M")return e.has("D")?"D":null;let n=On[t];if(!n)return null;let r=Cx.filter(i=>i!=="W"&&i!=="M"&&e.has(i)&&On[i]<n&&n%On[i]===0);return r.length===0?null:r[r.length-1]}function vl(t,e){if(t==="W"||t==="M")return 1/0;let n=On[t],r=On[e];return!n||!r||r===0?1/0:n/r}function kx(t,e,n){if(t.length===0)return[];if(e==="W")return Ax(t);if(e==="M")return Tx(t);let r=vl(e,n);return Ix(t,r)}function Ix(t,e){if(t.length===0)return[];let n=[],r=[t[0]],i=Dx(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(Wr(r)),r=[]),r.push(t[a])}return r.length>0&&n.push(Wr(r)),n}function Ax(t){let e=[],n=[],r="";for(let i of t){let s=Mx(i.openTime);s!==r&&n.length>0&&(e.push(n),n=[]),r=s,n.push(i)}return n.length>0&&e.push(n),e.map(Wr)}function Tx(t){let e=[],n=[],r="";for(let i of t){let s=new Date(i.openTime),a=`${s.getUTCFullYear()}-${s.getUTCMonth()}`;a!==r&&n.length>0&&(e.push(n),n=[]),r=a,n.push(i)}return n.length>0&&e.push(n),e.map(Wr)}function Wr(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 Dx(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}function Mx(t){let e=new Date(t),n=e.getUTCDay()||7;e.setUTCDate(e.getUTCDate()+4-n);let r=new Date(Date.UTC(e.getUTCFullYear(),0,1)),i=Math.ceil(((e.getTime()-r.getTime())/864e5+1)/7);return`${e.getUTCFullYear()}-W${i}`}var Px=Object.defineProperty,Rx=(t,e,n)=>e in t?Px(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,rr=(t,e,n)=>Rx(t,typeof e!="symbol"?e+"":e,n),ir={"1s":"1S","5s":"5S","10s":"10S","15s":"15S","30s":"30S","1m":"1","3m":"3","5m":"5","15m":"15","30m":"30","45m":"45","1h":"60","2h":"120","3h":"180","4h":"240","1d":"D","1w":"W","1D":"D","1W":"W","1M":"M","4H":"240",D:"D",W:"W",M:"M"};function Fx(t){if(ir[t]!==void 0)return ir[t];let e=t.toLowerCase();return ir[e]!==void 0?ir[e]:/^\\d+$/.test(t)?t:/^\\d+S$/i.test(t)?t.toUpperCase():t}var Un=class{constructor(e){rr(this,"_configured"),rr(this,"_requiresApiKey"),rr(this,"_providerName"),rr(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){Sx(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"])}async getMarketData(e,n,r,i,s){e=Ot(e);let a=Fx(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:Nx(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=await this._getMarketDataNative(e,c,u,i,s);if(h.length===0)return[];let p=kx(h,a,c);return r&&r>0&&p.length>r?p.slice(p.length-r):p}_computeSubLimit(e,n,r){if(!r)return;let i=vl(e,n);return i===1/0?e==="W"?r*7+14:e==="M"?r*31+31:r*30:Math.ceil(r*i)+Math.ceil(i)}},Bx=Object.defineProperty,Lx=(t,e,n)=>e in t?Bx(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ur=(t,e,n)=>Lx(t,typeof e!="symbol"?e+"":e,n),yi="https://api.binance.com/api/v3",Fa="https://api.binance.us/api/v3",sr={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"},ds=class{constructor(e=300*1e3){Ur(this,"cache"),Ur(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)}},fs=class extends Un{constructor(){super({requiresApiKey:!1,providerName:"Binance"}),Ur(this,"cacheManager"),Ur(this,"activeApiUrl",null),this.cacheManager=new ds(300*1e3)}async getBaseUrl(){if(this.activeApiUrl)return this.activeApiUrl;try{let e=new AbortController,n=setTimeout(()=>e.abort(),5e3),r=await fetch(`${yi}/ping`,{signal:e.signal});if(clearTimeout(n),r.ok)return this.activeApiUrl=yi,this.activeApiUrl}catch{}try{let e=new AbortController,n=setTimeout(()=>e.abort(),5e3),r=await fetch(`${Fa}/ping`,{signal:e.signal});if(clearTimeout(n),r.ok)return this.activeApiUrl=Fa,this.activeApiUrl}catch{}return yi}async _fetchRawChunk(e,n,r,i,s){let a=sr[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=sr[n.toUpperCase()];if(!s)return console.error(`Unsupported timeframe: ${n}`),[];let a=[],o=r,l=i,c=Ma[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)break;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"])}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(!sr[n.toUpperCase()])return console.error(`Unsupported timeframe: ${n}`),[];if(this.shouldPaginate(n,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,i){if(n&&n>1e3)return!0;if(r&&i){let s=sr[e.toUpperCase()],a=Ma[s];if(a)return Math.ceil((i-r)/a)>1e3}return!1}async getSymbolInfo(e){e=Ot(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(E=>E.symbol===i):l[0];if(!c)return console.error(`Symbol ${i} not found in exchange info`),null;let u=c.filters?.find(E=>E.filterType==="PRICE_FILTER"),h=c.filters?.find(E=>E.filterType==="LOT_SIZE"),p=u?parseFloat(u.tickSize):.01,d=h?parseFloat(h.minQty):0,f=Math.round(1/p),m=c.baseAsset,x=c.quoteAsset,b=s?` ${s}`:"",w=`${m} / ${x}${b}`;return{ticker:e,tickerid:`BINANCE:${e}`,prefix:"BINANCE",root:m,description:w,type:n,main_tickerid:`BINANCE:${e}`,current_contract:s,isin:"",basecurrency:m,currency:x,timezone:"Etc/UTC",country:"",mintick:p,pricescale:f,minmove:1,pointvalue:c.contractSize||1,mincontract:d,session:"24x7",volumetype:"base",expiration_date:c.deliveryDate||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 binance.exchangeInfo:",n),null}}},Ox=Object.defineProperty,Vx=(t,e,n)=>e in t?Ox(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Nn=(t,e,n)=>Vx(t,typeof e!="symbol"?e+"":e,n),jx="https://financialmodelingprep.com",Ba=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"]),La={"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"}},Oa={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"},Va={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"},$x={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}},ms=class extends Un{constructor(e){super({requiresApiKey:!0,providerName:"FMP"}),Nn(this,"_apiKey",null),Nn(this,"_baseUrl",jx),Nn(this,"_profileCache",new Map),Nn(this,"_symbolInfoCache",new Map),Nn(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=La[a]||La[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=${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=Pa(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=${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}=$x[r]||{periodType:"minute",multiplier:1},{session:d,timezone:f}=await this._resolveSessionInfo(e);return u.map(m=>{let x=this._dateTimeStrToMs(m.date),b=Pa(x,d,f,h,p);return{openTime:x,open:m.open,high:m.high,low:m.low,close:m.close,volume:m.volume,closeTime:b,quoteAssetVolume:0,numberOfTrades:0,takerBuyBaseAssetVolume:0,takerBuyQuoteAssetVolume:0,ignore:0}})}async getSymbolInfo(e){if(this.ensureConfigured(),e=Ot(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":Oa[i]||"America/New_York",a=r==="crypto"?"24x7":r==="forex"?"0000-0000":Va[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=${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":Oa[r]||"America/New_York";return{session:i?"24x7":Va[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)&&Ba.has(e.slice(0,3))&&Ba.has(e.slice(3,6))}_isCrypto(e){return this._isForex(e)?!1:/^[A-Z]+(USD|USDT|BTC|ETH)$/.test(e)&&e.length<=15}},Wx=Object.defineProperty,Ux=(t,e,n)=>e in t?Wx(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Kt=(t,e,n)=>Ux(t,typeof e!="symbol"?e+"":e,n),qx="https://data.alpaca.markets",zx="https://paper-api.alpaca.markets/v2",Kx="https://api.alpaca.markets/v2",gi=1e4,ja={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"},Hx={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"},Gx={NASDAQ:"0930-1600",NYSE:"0930-1600",AMEX:"0930-1600",ARCA:"0930-1600",BATS:"0930-1600",OTC:"0930-1600",CRYPTO:"24x7"},Yx={Min:"minute",Hour:"hour",Day:"day",Week:"week",Month:"month"},ys=class extends Un{constructor(e){super({requiresApiKey:!0,providerName:"Alpaca"}),Kt(this,"_apiKey",null),Kt(this,"_apiSecret",null),Kt(this,"_dataUrl",qx),Kt(this,"_tradingUrl",zx),Kt(this,"_feed",null),Kt(this,"_assetCache",new Map),Kt(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=Kx)}_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||gi,gi);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,gi))),o&&c.set("page_token",o),!r&&this._feed&&c.set("feed",this._feed),`${l}?${c.toString()}`}async getSymbolInfo(e){this.ensureConfigured(),e=Ot(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":Hx[r]||"America/New_York",a=i?"24x7":Gx[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():Vn(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=St(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=St(o,h,i);l=Math.min(c,p)}else n==="week"?l=this._weeklyCloseFromCalendar(o,i):n==="month"?l=this._monthlyCloseFromCalendar(o,i):l=Vn(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 St(u,h.close,n)}let a=r.getTime()+s*864e5,o=new Date(a).toISOString().split("T")[0];return St(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 St(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 St(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=Yx[n[2]];if(i)return{periodType:i,multiplier:r}}return{periodType:"day",multiplier:1}}_resolveTimeframe(e){return ja[e.toUpperCase()]||ja[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]}},gs=class{async getMarketData(){return[]}},Zx=typeof process<"u"&&process.versions&&process.versions.node,qr=null;if(Zx)try{qr=new gs}catch{qr=null}var Kb={Binance:new fs,FMP:new ms,Alpaca:new ys,...qr?{Mock:qr}:{}};function V(t){return typeof t=="string"?t:void 0}function se(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Xx(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 Qr(t){let e=t??{},n=e.fullContext??e,r=n.indicator??n.strategy?.config??{},i={title:V(r.title)??"Indicator",overlay:r.overlay===!0,precision:se(r.precision),shorttitle:V(r.shorttitle),format:V(r.format)},s=n.plots??{},a=Object.entries(s).map(([l,c])=>{let u=c??{},h=u.options??{};return{key:l,title:V(u.title),style:V(h.style),options:h,data:Array.isArray(u.data)?Xx(u.data):[],plot1:V(u.plot1)??V(h.plot1),plot2:V(u.plot2)??V(h.plot2)}}),o=n.strategy?Qx(n.strategy):void 0;return{meta:i,plots:a,...o?{trades:o}:{}}}function Qx(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=se(s.entry_price),o=se(s.entry_time),l=se(s.size);a===void 0||o===void 0||l===void 0||l===0||e.push({id:V(s.id)??`trade_${e.length}`,entry_id:V(s.entry_id)??"",entry_price:a,entry_time:o,entry_comment:V(s.entry_comment),exit_id:V(s.exit_id),exit_price:se(s.exit_price),exit_time:se(s.exit_time),exit_comment:V(s.exit_comment),size:l,status:s.status==="closed"?"closed":"open"})}return e}var Jx={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 El(t){return t==null||t===""?"line":Jx[t]??"line"}function Jr(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*\\)$/.test(e))}function ee(t,e){return Jr(t)?t.trim():e}var Sl="#00000000";function Bs(t){let e=t.title.trim().toLowerCase().replace(/\\s+/g,"-");return`${t.instanceId}:${t.kind}:${e}#${t.ordinal}`}var Ls="#2962ff";var Os="#089981",Vs="#f23645";var eb=new Map;function M(t,e){eb.set(t,e)}function tb(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 fe(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 $=tb;M("style-candles",$(\'<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"/>\'));M("style-bars",$(\'<path d="M4.5 2.5v11M2.5 5h2M4.5 11h2"/><path d="M11.5 2.5v11M9.5 4.5h2M11.5 10.5h2"/>\'));M("style-line",$(\'<path d="M1.5 11.5 5.5 7l3 2.5 5-6"/>\'));M("style-area",$(\'<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"/>\'));M("style-baseline",$(\'<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"/>\'));M("style-heikinashi",$(\'<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"/>\'));M("indicators",$(\'<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"/>\'));M("undo",$(\'<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"/>\'));M("redo",$(\'<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"/>\'));M("objects",$(\'<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"/>\'));M("clock",$(\'<circle cx="8" cy="8" r="6.2"/><path d="M8 4.8V8l2.4 1.6"/>\'));M("calendar",$(\'<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"/>\'));M("datawindow",$(\'<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"/>\'));M("camera",$(\'<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"/>\'));M("gear",$(\'<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"/>\'));M("search",$(\'<circle cx="7" cy="7" r="4.5"/><path d="m10.5 10.5 3.5 3.5"/>\'));M("bell",$(\'<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"/>\'));M("market-open",fe(\'<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"/>\'));M("market-pre",fe(\'<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"/>\'));M("market-post",fe(\'<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"/>\'));M("market-closed",fe(\'<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"/>\'));M("market-holiday",fe(\'<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"/>\'));M("chevron-right",$(\'<path d="m6 3.5 4.5 4.5L6 12.5"/>\'));M("chevron-left",$(\'<path d="M10 3.5 5.5 8l4.5 4.5"/>\'));M("chevron-down",$(\'<path d="M3.5 6 8 10.5 12.5 6"/>\'));M("chevron-up",$(\'<path d="M3.5 10 8 5.5 12.5 10"/>\'));M("chevrons-right",$(\'<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"/>\'));M("chevrons-left",$(\'<path d="M12 3.5 7.5 8l4.5 4.5"/><path d="M7.5 3.5 3 8l4.5 4.5"/>\'));M("check",$(\'<path d="m2.8 8.4 3.4 3.4 7-7.6"/>\'));M("close",$(\'<path d="m3.8 3.8 8.4 8.4M12.2 3.8l-8.4 8.4"/>\'));M("eye",$(\'<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"/>\'));M("eye-off",$(\'<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"/>\'));M("lock",$(\'<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"/>\'));M("unlock",$(\'<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"/>\'));M("trash",$(\'<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"/>\'));M("group",$(\'<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"/>\'));M("ungroup",$(\'<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"/>\'));M("clone",$(\'<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"/>\'));M("arrow-up",$(\'<path d="M8 13.2V3M4.2 6.8 8 3l3.8 3.8"/>\'));M("arrow-down",$(\'<path d="M8 2.8V13M4.2 9.2 8 13l3.8-3.8"/>\'));M("move-vertical",$(\'<path d="M8 2.5v11M5 5.5 8 2.5l3 3M5 10.5l3 3 3-3"/>\'));M("move",$(\'<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"/>\'));M("pen",$(\'<path d="m10.8 2.2 3 3-8 8-3.6.6.6-3.6z"/><path d="m9.2 3.8 3 3"/>\'));M("wave",$(\'<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"/>\'));M("folder-plus",$(\'<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"/>\'));M("folder-minus",$(\'<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"/>\'));M("collapse",$(\'<path d="M3 8h10"/>\'));M("expand",$(\'<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"/>\'));M("plus",$(\'<path d="M8 2.8v10.4M2.8 8h10.4"/>\'));M("minus",$(\'<path d="M2.8 8h10.4"/>\'));M("maximize",$(\'<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"/>\'));M("restore",$(\'<path d="M6.2 2.5v3.7H2.5M9.8 13.5V9.8h3.7M13.5 6.2H9.8V2.5M2.5 9.8h3.7v3.7"/>\'));M("star",$(\'<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"/>\'));M("star-filled",$(\'<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"\'));M("grip",$(\'<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"\'));M("kebab",$(\'<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"\'));M("burger",$(\'<path d="M2.5 4.5h11M2.5 8h11M2.5 11.5h11"/>\'));M("reset",$(\'<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"/>\'));M("pane-collapse",$(\'<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"/>\'));M("pane-expand",$(\'<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"/>\'));M("cursor",fe(\'<path d="M5 3l6 16 2-6 6-2z"/>\',\'fill="currentColor" stroke="none"\'));M("ruler",fe(\'<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"/>\'));M("magnet",fe(\'<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"/>\'));M("eraser",fe(\'<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"/>\'));M("pen-lock",fe(\'<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"/>\'));M("pen-sync",fe(\'<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"/>\'));M("brush",fe(\'<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"/>\'));M("bucket",fe(\'<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"/>\'));M("type",fe(\'<path d="M5 6V4.5h14V6"/><path d="M12 4.5v15"/><path d="M9.5 19.5h5"/>\'));M("bold",fe(\'<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"\'));M("italic",fe(\'<path d="M15 5h-5M14 19H9M14.5 5 10 19"/>\',\'stroke-width="2.2"\'));M("price-delta",fe(\'<path d="M12 4v16"/><path d="M8 8l4-4 4 4"/><path d="M8 16l4 4 4-4"/>\'));M("date-delta",fe(\'<path d="M4 12h16"/><path d="M8 8l-4 4 4 4"/><path d="M16 8l4 4-4 4"/>\'));M("bring-front",fe(\'<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"/>\'));M("send-back",fe(\'<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"/>\'));M("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>\');M("bands",fe(\'<path d="M3 6h18"/><path d="M3 18h18"/><path d="M3 12h18" stroke-dasharray="3 3"/>\'));M("dedekind",fe(\'<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"/>\'));M("sonic",fe(\'<circle cx="15" cy="12" r="4"/><circle cx="12" cy="12" r="2.5"/><path d="M8 5v14"/>\'));M("supersonic",fe(\'<circle cx="16" cy="12" r="3.5"/><path d="M6 12 15 6M6 12 15 18"/>\'));var ei=class{constructor(){ia(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),Bs({instanceId:e,kind:n,title:r,ordinal:s})}};function vn(t){let e=t.data;if(e.length===0)return[];let n=e[e.length-1]?.value;return Array.isArray(n)?n:[]}function pe(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 ti(t){let e=(V(t)??"").toLowerCase();return e==="bt"||e.includes("time")?"bar_time":"bar_index"}function Nl(t){let e=(V(t)??"none").toLowerCase();return e==="b"||e==="both"?"both":e==="l"||e==="left"?"left":e==="r"||e==="right"?"right":"none"}function $s(t){let e=(V(t)??"").toLowerCase();return e.includes("dot")?"dotted":e.includes("dash")?"dashed":"solid"}function kl(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=ee(t);return e?{color:e,invisible:!1}:{invisible:!0}}return{invisible:!0}}function js(t,e){let n=pe(t.x1),r=pe(t.y1),i=pe(t.x2),s=pe(t.y2);if(n===void 0||r===void 0||i===void 0||s===void 0)return null;let a=(V(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}=kl(t.color);return{id:e,paneId:"unrouted",xloc:ti(t.xloc),x1:n,y1:r,x2:i,y2:s,extend:Nl(t.extend),color:c,invisible:u,width:Math.max(1,pe(t.width)??1),style:$s(t.style),arrowLeft:o,arrowRight:l,overlay:t.force_overlay===!0}}function Il(t,e,n){let r=[];for(let i of vn(t)){if(i._deleted===!0)continue;let s=js(i,n.next(e,"line",String(i.id??r.length)));s&&r.push(s)}return r}function Al(t,e,n){let r=[];for(let i of vn(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=js(s,`${o}:a`),c=js(a,`${o}:b`);!l||!c||r.push({id:o,paneId:"unrouted",line1:l,line2:c,color:ee(i.color),overlay:i.force_overlay===!0})}return r}function Tl(t){return t<=0?"auto":t<=9?"tiny":t<=12?"small":t<=17?"normal":t<=28?"large":"huge"}function nb(t){if(typeof t=="number"&&Number.isFinite(t))return Tl(t);let e=(V(t)??"").toLowerCase();return e==="tiny"||e==="small"||e==="normal"||e==="large"||e==="huge"?e:"auto"}function Ws(t){let e=(V(t)??"").toLowerCase();return e==="left"||e==="right"?e:"center"}function Dl(t){let e=(V(t)??"").toLowerCase();return e==="top"||e==="bottom"?e:"center"}function Us(t){return(V(t)??"").toLowerCase().includes("mono")?"monospace":"default"}function Ml(t,e,n){let r=[];for(let i of vn(t)){if(i._deleted===!0)continue;let s=pe(i.left),a=pe(i.top),o=pe(i.right),l=pe(i.bottom);if(s===void 0||a===void 0||o===void 0||l===void 0)continue;let c=(V(i.text_formatting)??"").toLowerCase(),u=V(i.text);r.push({id:n.next(e,"box",String(i.id??r.length)),paneId:"unrouted",xloc:ti(i.xloc),left:s,top:a,right:o,bottom:l,extend:Nl(i.extend),bgColor:ee(i.bgcolor),borderColor:ee(i.border_color),borderWidth:Math.max(0,pe(i.border_width)??1),borderStyle:$s(i.border_style),text:u&&u.length>0?u:void 0,textColor:ee(i.text_color),textSize:nb(i.text_size),hAlign:Ws(i.text_halign),vAlign:Dl(i.text_valign),wrap:(V(i.text_wrap)??"").toLowerCase().includes("auto"),fontFamily:Us(i.text_font_family),bold:c.includes("bold"),italic:c.includes("italic"),overlay:i.force_overlay===!0})}return r}var rb=["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 ib(t){let e=(V(t)??"").toLowerCase().replace(/^style_/,"");return rb.includes(e)?e:"label_down"}function sb(t){let e=(V(t)??"").toLowerCase();return e==="ab"||e.includes("above")?"abovebar":e==="bl"||e.includes("below")?"belowbar":"price"}function Pl(t){if(typeof t=="number"&&Number.isFinite(t))return Tl(t);let e=(V(t)??"").toLowerCase();return e==="auto"||e==="tiny"||e==="small"||e==="large"||e==="huge"?e:"normal"}function Rl(t,e,n){let r=[];for(let i of vn(t)){if(i._deleted===!0)continue;let s=pe(i.x),a=sb(i.yloc),o=pe(i.y);if(s===void 0||a==="price"&&o===void 0)continue;let l=V(i.text),c=V(i.tooltip),{color:u,invisible:h}=kl(i.color);r.push({id:n.next(e,"label",String(i.id??r.length)),paneId:"unrouted",xloc:ti(i.xloc),x:s,y:o??0,yloc:a,text:l&&l.length>0?l:void 0,style:ib(i.style),color:u,noFill:h,textColor:ee(i.textcolor),size:Pl(i.size),textAlign:Ws(i.textalign),tooltip:c&&c.length>0?c:void 0,fontFamily:Us(i.text_font_family),overlay:i.force_overlay===!0})}return r}function Fl(t,e,n){let r=[];for(let i of vn(t)){if(i._deleted===!0)continue;let s=Array.isArray(i.points)?i.points:[],a=ti(i.xloc),o=[];for(let c of s){let u=pe(c.price),h=pe(c.index),p=pe(c.time),d=a==="bar_time"?p:h,f=a==="bar_time"?h:p,m,x;if(d!==void 0)m=d,x=a;else if(f!==void 0)m=f,x=a==="bar_time"?"bar_index":"bar_time";else continue;u!==void 0&&o.push({xloc:x,x:m,price:u})}if(o.length<2)continue;let l=(V(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:ee(i.line_color),fillColor:ee(i.fill_color),lineWidth:Math.max(1,pe(i.line_width)??1),lineStyle:$s(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 ab=["top_left","top_center","top_right","middle_left","middle_center","middle_right","bottom_left","bottom_center","bottom_right"];function ob(t){let e=(V(t)??"").toLowerCase();return ab.includes(e)?e:"top_right"}function lb(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:Pl(t)}function Cl(t){let e=pe(t);return e!==void 0&&e>0?e:void 0}function cb(t){if(!t||typeof t!="object")return null;let e=t,n=V(e.text),r=V(e.tooltip),i=(V(e.text_formatting)??"").toLowerCase();return{text:n&&n.length>0?n:void 0,textColor:ee(e.text_color),bgColor:ee(e.bgcolor),hAlign:Ws(e.text_halign),vAlign:Dl(e.text_valign),textSize:lb(e.text_size),fontFamily:Us(e.text_font_family),tooltip:r&&r.length>0?r:void 0,bold:i.includes("bold"),italic:i.includes("italic"),width:Cl(e.width),height:Cl(e.height),merged:e._merged===!0}}function ub(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=pe(i.startCol??i.start_column??i.startColumn),a=pe(i.startRow??i.start_row),o=pe(i.endCol??i.end_column??i.endColumn),l=pe(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 Bl(t,e,n){let r=[];for(let i of vn(t)){if(i._deleted===!0)continue;let a=(Array.isArray(i.cells)?i.cells:[]).map(l=>(Array.isArray(l)?l:[]).map(c=>cb(c))),o=ub(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:ob(i.position),columns:Math.max(0,Math.round(pe(i.columns)??0)),rows:Math.max(0,Math.round(pe(i.rows)??0)),bgColor:ee(i.bgcolor),frameColor:ee(i.frame_color),frameWidth:Math.max(0,pe(i.frame_width)??0),borderColor:ee(i.border_color),borderWidth:Math.max(0,pe(i.border_width)??0),cells:a,merges:o,overlay:i.force_overlay===!0})}return r}var Ll=Ls;function Ol(t,e){let n=new ei,r=[],i=[],s=[],a=[],o=[],l=[],c=[],u=[],h=[],p=[],d=[],f=[],m=new Map,x=new Set,b=[];for(let v of t.plots){let I=El(v.style),C=v.title??v.key;switch(I){case"skip":break;case"barcolor":{if(!En(v.options.display))break;let T=Hn(v.data.length,se(v.options.show_last));for(let O=T;O<v.data.length;O+=1){let N=v.data[O],j=ee(N.options?.color);j&&f.push({time:N.time,color:j})}break}case"fill":En(v.options.display)&&b.push(v);break;case"hline":{let T=bb(v,C,e,n);T&&o.push(T);break}case"background":En(v.options.display)&&a.push(...wb(v,C,e,n));break;case"drawing_line":l.push(...Il(v,e,n));break;case"drawing_box":c.push(...Ml(v,e,n));break;case"label":u.push(...Rl(v,e,n));break;case"drawing_polyline":h.push(...Fl(v,e,n));break;case"linefill":p.push(...Al(v,e,n));break;case"table":d.push(...Bl(v,e,n));break;case"markers":En(v.options.display)&&u.push(...vb(v,e,n));break;default:{let T=n.next(e,I,C);m.set(v.key,T),v.options.force_overlay===!0&&x.add(v.key),i.push(hb(I,v,T,C));let O=fb(v,C,e,n);O&&o.push(O)}}}for(let v of b){let I=v.plot1?m.get(v.plot1):void 0,C=v.plot2?m.get(v.plot2):void 0;if(!I||!C){r.push(`fill "${v.key}" references unknown plots (${v.plot1??"?"}/${v.plot2??"?"})`);continue}let T=x.has(v.plot1)&&x.has(v.plot2);s.push({id:n.next(e,"fill",v.title??v.key),paneId:"unrouted",fromSeriesId:I,toSeriesId:C,...xb(v),...T?{overlay:!0}:{}})}let w=t.trades?pb(t.trades):[];return{model:{id:e,title:t.meta.title,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 pb(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 hb(t,e,n,r){let i=se(e.options.show_last),s=e.options.force_overlay===!0?{overlay:!0}:{};if(t==="candle"||t==="bar"){let f={id:n,title:r,paneId:"unrouted",kind:t,bars:_b(e,Hn(e.data.length,i)),...s},m=mb(e);return m&&(f.barColors=m),f}let a=t,o=ee(jl(e)),l=!En(e.options.display)||!o,c=se(e.options.linewidth)??1,u=a==="line"||a==="step"||a==="area",h=gb(db(yb(e),i,u),se(e.options.offset)),p={color:o??Ll,width:c,lineStyle:$l(e.options.linestyle)??"solid"},d=se(e.options.histbase);return d!==void 0&&(a==="histogram"||a==="columns"||a==="area")&&(p.base=d),{id:n,title:r,paneId:"unrouted",kind:a,points:h,style:p,visible:!l,...s}}function En(t){let e=V(t);return e===void 0||e.includes("all")||e.includes("pane")}function Hn(t,e){return e===void 0||e<=0?0:Math.max(0,t-Math.floor(e))}function db(t,e,n){let r=Hn(t.length,e);return n&&(r-=1),r<=0?t:t.map((i,s)=>s<r?{...i,value:null}:i)}function fb(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:ee(s.options?.color)??ee(jl(t)),lineStyle:"dotted",width:se(t.options.linewidth),title:e}}return null}function mb(t){let e=!1,n=t.data.map(r=>{let i=r.options??{},s=ee(i.color),a=ee(i.wickcolor),o=ee(i.bordercolor);return!s&&!a&&!o?null:(e=!0,{color:s,wickColor:a,borderColor:o})});return e?n:void 0}function yb(t){let e=t.data.some(n=>Jr(n.options?.color));return t.data.map(n=>{let r=typeof n.value=="number"&&Number.isFinite(n.value)?n.value:null,i=ee(n.options?.color);return i?{time:n.time,value:r,color:i}:e?{time:n.time,value:r,color:Sl}:{time:n.time,value:r}})}function Vl(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 gb(t,e){if(!e)return t;let n=e*Vl(t);return n?t.map(r=>({...r,time:r.time+n})):t}function _b(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 jl(t){for(let e of t.data)if(typeof e.options?.color=="string"&&e.options.color)return e.options.color;return V(t.options.color)}function xb(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=se(o.top_value),c=se(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=>ee(s.options?.color)??null),r=new Set(n.filter(s=>s!==null)),i=n.some(s=>s===null);return r.size===0?{color:ee(t.options.color)}:r.size===1&&!i?{color:[...r][0]}:{colors:n}}function bb(t,e,n,r){if(!En(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:ee(t.options.color),lineStyle:$l(t.options.linestyle)??"dashed",title:e,width:se(t.options.linewidth)}}function $l(t){let e=V(t)?.replace(/^(hline\\.style_|plot\\.linestyle_|linestyle_|style_)/,"");return e==="solid"||e==="dashed"||e==="dotted"?e:void 0}function wb(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=Hn(a.length,se(t.options.show_last));for(;l<a.length;){let c=a[l],u=ee(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&&ee(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 vb(t,e,n){let r=se(t.options.offset),i=r?r*Vl(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?Eb(t):null,l=t.options.force_overlay===!0?{overlay:!0}:{},c=[],u=Hn(t.data.length,se(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,x=m.color!==void 0?m.color:t.options.color;if(x!==void 0&&!Jr(x))continue;let b=V(m.text)??V(t.options.text),w=b&&b.trim().length>0?b:void 0,E=a?f&&d>0?Os:Vs:void 0,v=ee(m.color)??ee(t.options.color)??E??Ll,I=s?V(m.char)??V(t.options.char)??"\\u2605":void 0;c.push({id:n.next(e,"label",`${t.key}#${c.length}`),paneId:"unrouted",xloc:"bar_time",x:p.time+i,y:f?d:0,yloc:Cb(V(m.location)??V(t.options.location)),text:I!==void 0?w!==void 0?`${I}\n${w}`:I:w,style:I!==void 0?"none":Nb(V(m.shape)??V(t.options.shape)),color:v,textColor:ee(m.textcolor)??ee(t.options.textcolor)??(I!==void 0?v:void 0),size:o!==null&&f?Sb(Math.abs(d),o):kb(V(m.size)??V(t.options.size)),textAlign:"center",fontFamily:"default",...l})}return c}function Eb(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:se(t.options.minheight)??5,maxH:se(t.options.maxheight)??100}}function Sb(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 Cb(t){let e=(t??"").toLowerCase();return e==="absolute"?"price":e==="top"?"top":e==="bottom"?"bottom":e.includes("below")?"belowbar":"abovebar"}function Nb(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 kb(t){let e=(t??"").toLowerCase();return e==="tiny"||e==="small"||e==="large"||e==="huge"||e==="normal"?e:"small"}function Ib(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 Ab(t){return t==="int"||t==="float"||t==="price"||t==="time"}var Wl={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 Tb(t){let e=t.trim().toLowerCase().replace(/^color\\./,"");return Wl[e]??t}function Db(t){if(typeof t!="string")return;let e=/^color\\.([a-z]+)$/i.exec(t.trim());return e?Wl[e[1].toLowerCase()]:void 0}function Mb(t){return(t.type==="string"||t.type==null)&&Db(t.defval)!==void 0}function Pb(t,e){if(e==="bool")return!!t;if(Ab(e))return typeof t=="number"?t:Number(t)||0;let n=typeof t=="string"?t:t==null?"":String(t);return e==="color"?Tb(n):n}function Ul(t){return t.map((e,n)=>{let r=Mb(e)?"color":Ib(e.type);return{key:e.varId??e.title??`input${n}`,title:e.title??e.varId??`Input ${n+1}`,type:r,defval:Pb(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 Rb(t){switch(t){case"int":return"int";case"float":return"float";case"bool":return"bool";default:return"string"}}function qs(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 Fb(t){let e=t.replace(/_/g," ");return e.charAt(0).toUpperCase()+e.slice(1)}function ql(t,e){let n=t.getPropsMeta(),r=t.prop;return n.filter(i=>i.mutable&&i.name).map(i=>{let s=i.name,a=Rb(i.type),o=qs(i.defval,a),l=qs(r[s]??i.defval,a),c=e?.[s],u=l!==o?l:c!==void 0?qs(c,a):o;return{key:s,title:Fb(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 zl(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 Kl=!1;function zs(){if(Kl)return;Kl=!0;let t=_n.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:E,...v}=h;d=E,f=Object.keys(v).length>0?[...p,v]:p}else d=c[13],f=p;let m=l(...f),x=h??{},b=p.length>1?p[1]:x.column??0,w=p.length>2?p[2]:x.row??0;return o(p[0],b,w,d),m})})}var Hl=["plotshape","plotchar","plotarrow"],Gl=!1;function Ks(){if(Gl)return;Gl=!0;let t=_n.prototype,e=t.bindContextObject;typeof e=="function"&&(t.bindContextObject=function(n,r,i){if(e.call(this,n,r,i),i!==void 0||!Hl.some(a=>r.includes(a)))return;let s={idx:void 0,n:0,len:0};for(let a of Hl){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 Bb(t,e,n){if(n==="none")return[];if(n==="strategy"&&t.getDeclarationType()!=="strategy")return[];let r=ql(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 Jl(t,e,n,r="all"){let i=Qt.from(t),s=Ul(i.getInputsMeta()),a=Bb(i,n,r),o=/overlay\\s*[:=]\\s*true/.test(t),c=/^\\s*(?:indicator|strategy)\\s*\\(\\s*(?:title\\s*=\\s*)?(["\'])((?:\\\\.|(?!\\1).)*)\\1/m.exec(t)?.[2]?.replace(/\\\\(.)/g,"$1").trim()||"Indicator",u=/chart\\.(left|right)_visible_bar(_time)?\\b/.test(t);return{language:"pine",inputs:s,...a.length>0?{props:a}:{},meta:{title:c,overlay:o},reactsToViewport:u,token:{source:t,instanceId:e}}}function Gs(t,e,n,r={}){let i=JSON.stringify([n,r]);if(t.lastKey!==i||!t.lastInd){let s=new Qt(e,n);zl(s,r),t.lastInd=s,t.lastKey=i}return t.lastInd}async function ec(t){let{ind:e,bars:n,market:r,visibleRange:i,prepared:s,instanceId:a,inputs:o,props:l,fetchSeries:c}=t;zs(),Ks();let u=Ys(n,r.timeframe,r.symbolInfo),h={getMarketData:(m,x,b,w,E)=>nc(m,x,r)?Promise.resolve(u):rc(c,m,x,b,w,E,ri(r,m)),getSymbolInfo:async m=>ri(r,m)},p=new Ut(h,Zs(r),r.timeframe,u.length);await p.ready(),i&&p.setVisibleRange(i.left,i.right);let d=await p.run(e),f=typeof p.usesVisibleRange=="function"?p.usesVisibleRange():!1;return{model:tc(d,a,s,o,l??{},n[0]?.time),alerts:(d.alerts??[]).map(sc),warnings:(d.warnings??[]).map(ac),reactsToViewport:f,ctx:d}}function tc(t,e,n,r,i,s){let{model:a}=Ol(Qr(t),e);return a.inputs=n.inputs,a.inputValues={...Ql(n.inputs),...r},n.props&&(a.props=n.props,a.propValues={...Ql(n.props),...i}),s!=null&&(a.anchorTime=s),a}function Yl(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 Hs=(t,e)=>e.start<=e.end?t>=e.start&&t<e.end:t>=e.start||t<e.end,ni=new Map;function Zl(t,e){let n=`${e}:${Math.floor(t/36e5)}`,r=ni.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}ni.size>1e5&&ni.clear(),ni.set(n,r)}return Number.isNaN(r)?null:((Math.floor(t/6e4)+r)%1440+1440)%1440}function Lb(t){return t==null?null:/^\\d+$/.test(t)?Number(t):/^1?D$/i.test(t)?1440:null}function Ob(t,e,n){let r=typeof n=="object"&&n!=null?n:null,i=Lb(e),s=Yl(r?.session),a=typeof r?.timezone=="string"?r.timezone:null;if(i==null||s==null||a==null||t.length===0)return null;let o=Yl(r?.session_extended),l=s;if(o)for(let c of t){let u=Zl(c.time,a);if(u!=null&&!Hs(u,s)&&Hs(u,o)){l=o;break}}return c=>{let u=Zl(c,a);if(u==null||!Hs(u,l))return null;let h=(l.end-u+1440)%1440||1440;return c+Math.min(i,h)*6e4}}function Ys(t,e,n){let r=Ob(t,e,n);return t.map(i=>{let s={openTime:i.time,open:i.open,high:i.high,low:i.low,close:i.close,volume:i.volume??0},a=r?.(i.time);return a!=null&&(s.closeTime=a),s})}function Zs(t){return t.chartStyle==="heikinashi"?`${t.symbol};heikinashi`:t.symbol}function nc(t,e,n){return(t==null||t===Zs(n))&&(e==null||e===n.timeframe)}async function rc(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 Ys(o,n,a)}function Vb(t,e,n){let r="",i=!1;return{markDirty:()=>{i=!0},getMarketData:async(s,a,o,l,c)=>{let u=e();if(!nc(s,a,u))return rc(n,s,a,o,l,c,ri(u,s));let h=Ys(t(),u.timeframe,u.symbolInfo);if(l==null)return h;let p=h.filter(m=>(m.openTime??0)>=l),d=p[p.length-1],f=d?`${p.length}|${d.openTime}|${d.close}|${d.high}|${d.low}|${d.volume}`:"";return!i&&f===r?[]:(i=!1,r=f,p)},getSymbolInfo:async s=>ri(e(),s)}}function ic(t){let e=t.bars();zs(),Ks();let n=Gs(t.cache,t.token.source,t.inputs,t.props??{}),r=e[0]?.time,i=Math.max(1,e.length),s=Vb(t.bars,t.market,t.fetchSeries),a=new Ut(s,Zs(t.market()),t.market().timeframe,i);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;try{t.onModel(tc(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?.(sc(u))),o.on("warning",u=>t.onWarning?.(ac(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 ri(t,e){let n=e&&e.split(";")[0];return n&&n!==t.symbol?Xl({symbol:n,timeframe:t.timeframe}):Xl(t)}function Xl(t){if(t.symbolInfo)return 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 Ql(t){let e={};for(let n of t)e[n.key]=n.defval;return e}function sc(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 ac(t){return{message:String(t.message??""),method:t.method,bar:Number(t.bar??0)}}var Qe=t=>se(t)??0;function oc(t){if(t==null||typeof t!="object")return;let e=t;return{position:Qe(e.position_size),avgPrice:Qe(e.position_avg_price),equity:Qe(e.equity),openPnl:Qe(e.openprofit),netPnl:Qe(e.netprofit),grossProfit:Qe(e.grossprofit),grossLoss:Qe(e.grossloss),wins:Qe(e.wintrades),losses:Qe(e.losstrades),even:Qe(e.eventrades),maxDrawdown:Qe(e.max_drawdown),maxRunup:Qe(e.max_runup),initialCapital:Qe(e.initial_capital)}}function lc(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=se(i.entry_price),a=se(i.entry_time),o=se(i.size);if(s===void 0||a===void 0||o===void 0||o===0)continue;let l=se(i.exit_price),c=se(i.exit_time);n.push({id:V(i.id)??`trade_${n.length}`,side:o>0?"long":"short",qty:Math.abs(o),entry:{id:V(i.entry_id)??"",time:a,price:s,...V(i.entry_comment)!==void 0?{comment:V(i.entry_comment)}:{}},...l!==void 0&&c!==void 0?{exit:{id:V(i.exit_id)??"",time:c,price:l,...V(i.exit_comment)!==void 0?{comment:V(i.exit_comment)}:{}}}:{},open:i.status!=="closed"})}return n}function cc(t){try{return structuredClone(t)}catch{return}}function jb(t){let e=Array.isArray(t)?t:t!=null&&typeof t=="object"&&Array.isArray(t.data)?t.data:null;return cc(e?e[e.length-1]:t)}function $b(t){return t.replace(/^glb\\d+_/,"")}function Xs(t,e){if(t)for(let[n,r]of Object.entries(t)){if(n.startsWith("_"))continue;let i=jb(r);i!==void 0&&(e[$b(n)]=i)}}function uc(t,e,n){let r=t??{},i=r.fullContext??r,s=p=>!n||n.includes(p),a=s("meta")||s("plots")?Qr(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:cc(d.value)??null})));let l={};s("variables")&&(Xs(i.const,l),Xs(i.var,l),Xs(i.let,l));let c=s("strategy")?oc(i.strategy):void 0,u=s("trades")&&i.strategy?lc(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 pc=self,De=t=>pc.postMessage(t),zt=new Map,Js=new Map,Wb=0,hc=(t,e,n)=>new Promise((r,i)=>{let s=++Wb;Js.set(s,{resolve:r,reject:i}),De({kind:"fetchSeries",reqId:s,symbol:t,timeframe:e,range:n})});function ii(t){t.chain=t.chain.then(()=>qb(t))}function Ub(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 Qs(t){t.stream?.stop(),t.stream=null,!(t.stopped||t.bars.length===0)&&(t.stream=ic({token:t.prepared.token,cache:t.cache,prepared:t.prepared,inputs:t.inputs,props:t.props,bars:()=>t.bars,market:()=>t.market,fetchSeries:hc,visibleRange:t.visibleRange,onModel:e=>{t.stopped||De({kind:"model",sessionId:t.id,model:e})},onAlert:e=>De({kind:"alert",sessionId:t.id,alert:e}),onWarning:e=>De({kind:"warning",sessionId:t.id,warning:e}),onError:e=>De({kind:"error",sessionId:t.id,message:e.message})}))}async function qb(t){if(!t.stopped)try{let e=t.prepared.token,n=await ec({ind:Gs(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:hc});if(t.stopped)return;De({kind:"reactsToViewport",sessionId:t.id,value:n.reactsToViewport});for(let r of n.alerts)De({kind:"alert",sessionId:t.id,alert:r});for(let r of n.warnings)De({kind:"warning",sessionId:t.id,warning:r});t.lastCtx=n.ctx,De({kind:"model",sessionId:t.id,model:n.model}),De({kind:"done",sessionId:t.id})}catch(e){De({kind:"error",sessionId:t.id,message:e instanceof Error?e.message:String(e)})}}pc.addEventListener("message",t=>{let e=t.data;switch(e.kind){case"prepare":try{De({kind:"prepared",reqId:e.reqId,prepared:Jl(e.source,e.instanceId,e.defaultProps,e.propsVisibility)})}catch(n){De({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};if(zt.set(n.id,n),n.mode==="live"){n.deferred||Qs(n);return}n.deferred?De({kind:"done",sessionId:n.id}):ii(n);return}case"update":{let n=zt.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||Qs(n);return}n.deferred?De({kind:"done",sessionId:n.id}):ii(n);return}case"setVisibleRange":{let n=zt.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?De({kind:"done",sessionId:n.id}):ii(n);return}case"notifyBars":{let n=zt.get(e.sessionId);if(!n||n.mode==="live")return;n.bars=e.bars,n.deferred=!1,ii(n);return}case"bars":{let n=zt.get(e.sessionId);if(!n||n.mode!=="live")return;if(e.restart){n.bars=e.bars,n.deferred=!1,Qs(n);return}for(let r of e.bars)Ub(n,r);return}case"getContext":{let n=zt.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";De({kind:"contextResult",reqId:e.reqId,snapshot:r==null?null:uc(r,i,e.select)});return}case"stop":{let n=zt.get(e.sessionId);n&&(n.stopped=!0,n.stream?.stop()),zt.delete(e.sessionId);return}case"fetchSeriesResult":{let n=Js.get(e.reqId);if(!n)return;Js.delete(e.reqId),e.error?n.reject(new Error(e.error)):n.resolve(e.bars??[]);return}}});})();\n';
1668
1670
 
1669
1671
  // src/pinets-worker/PineWorkerEngine.ts
1670
1672
  function spawnWorker(workerUrl) {