coffee-ahk
Version:
coffeescript -> ahk
2 lines (1 loc) • 49.7 kB
JavaScript
import{at as e,getDirname as t,glob as n,read as i,run as s,getExtname as o,getName as r,write as a}from"fire-keeper";import{compile as l}from"coffeescript";import{trim as c}from"radash";import u from"cson";import p from"iconv-lite";import d from"kleur";const h=["..","?","?.","bin?","from","func_exist","import"];class f{#e=[];next="";constructor(...e){this.reload(...e)}get first(){return this.at(0)??""}get last(){return this.at(-1)??""}get length(){return this.#e.length}get list(){return[...this.#e]}at(t){return e(this.#e,t)}isEqual(e){const t=e instanceof f?e.list:e;return this.#e.length===t.length&&this.#e.every((e,n)=>e===t[n])}pop(){return this.#e.pop()??""}push(...e){return this.#e.push(...e)}reload(e=[]){this.#e=e instanceof f?e.list:e}shift(){return this.#e.shift()??""}slice(...e){return this.#e.slice(...e)}unshift(...e){return this.#e.unshift(...e)}}class g{comment;scope;type;value;constructor(...e){if(e[0]instanceof g){const{scope:t,type:n,value:i}=e[0];return this.type=n,this.value=i,void(this.scope=new f(t))}this.type=e[0]??"void",this.value=(void 0===e[1]?e[0]:e[1])??"",this.scope=new f(e[2])}clone(){const{scope:e,type:t,value:n}=this;return new g(t,n,e)}is(e,t){return e===this.type&&(void 0===t||t===this.value)}}const _=(e,t=e.content.length-1)=>{const{content:n}=e,i=n.at(t);return i?i.is("edge","parameter-start")?t:_(e,t-1):0},m=e=>{e.last.is("bracket","}-")&&(e.last.value="}")},A=(e,t)=>{let n=e.substring(1,e.length-1);return n=n.replace(/%/g,"`%").replace(/\\b/g,"`b").replace(/\\n/g,"`n").replace(/\\r/g,"`r").replace(/\\t/g,"`t"),n=`"${n.replace(/"/g,'""')}"`,n=3===t.length?n.replace(/\s*\n\s*/g,""):n.replace(/\s*\n\s*/g," "),n},y={"new-line":e=>{const{type:t,value:n}=e;if("terminator"===t){if("\n"===n)return(e=>{const{content:t,scope:n}=e;return m(t),((e,t)=>!!["array","call","object","parameter"].includes(t.last)&&(e.last.is("sign",",")||(e.last.is("new-line")&&e.pop(),e.push("sign",",")),!0))(t,n)||t.push("new-line",e.indent.toString()),!0})(e);if(";"===n)return(e=>{const{content:t}=e;return m(t),t.push("new-line",e.indent.toString()),!0})(e)}return!1},alias:e=>{const{content:t,type:n}=e;return"@"===n?(t.push("this"),!0):"::"===n&&(t.last.is(".")&&t.pop(),t.push(".").push("prototype"),!0)},array:e=>{const{content:t,scope:n,type:i}=e;return"["===i?(n.push("array"),t.push("edge","array-start"),!0):"]"===i&&(n.pop(),t.push("edge","array-end"),!0)},boolean:e=>{const{content:t,type:n,value:i}=e;return"bool"===n&&(t.push("boolean",i),!0)},bracket:e=>{const{content:t,type:n,value:i}=e;return("("===n||")"===n)&&(t.push("bracket",i),!0)},class:e=>{const{content:t,scope:n,type:i}=e;return"class"===i?(n.next="class",t.push("class"),!0):"super"===i&&(t.push("super"),!0)},comment:e=>{const{content:t,token:n}=e;if(n.comments){const e=[];n.comments.forEach(t=>c(t.content,"\n ").split("\n").forEach(t=>e.push(t)));const{last:i}=t;return i.comment=e,!0}return!1},do:e=>{const{content:t,type:n}=e;return("do"===n||"do_iife"===n)&&(t.push("native","__mark:do__"),!0)},for:e=>{const{content:t,scope:n,type:i,value:s}=e;if("for"===i)return n.push("for"),t.push("for"),!0;if(["forin","forof"].includes(i)){const e=[],n=t.pop();e.push(n.value);if(t.last.is("sign",",")){t.pop();const n=t.pop();e.unshift(n.value)}return"forin"===i&&e.reverse(),1===e.length&&e.unshift("forin"===i?"__index_for__":"__key_for__"),t.push("identifier",e[0]).push("sign",",").push("identifier",e[1]).push("for-in",s),!0}return!1},forbidden:e=>{const{type:t}=e;if(h.includes(t))throw new Error(`ahk/forbidden: token type '${t}' is not supported in CoffeeScript→AHK transpilation.`);if("post_if"===t)throw new Error("ahk/forbidden: post-if syntax is not supported. Use standard if/else.");return!1},function:e=>{const{type:t}=e;return["->","=>"].includes(t)?((e,t)=>{const{content:n,scope:i}=e;if(n.last.is("edge","parameter-end")){if("=>"===t){const t=[...i.list,"parameter"];n.list.splice(_(e)+1,0,new g("this","this",t),new g("sign","=",t),new g("this","this",t),new g("sign",",",t))}}else n.at(-2)?.is("property","constructor")||n.push("identifier","anonymous"),i.push("parameter"),n.push("edge","parameter-start"),"=>"===t&&n.push("this").push("sign","=").push("this"),n.push("edge","parameter-end"),i.pop();return i.push("function"),!0})(e,t):"call_start"===t?(e=>{const{scope:t}=e,{next:n}=t;return t.next="",t.push("call"),t.next=n,e.content.push("edge","call-start"),!0})(e):"call_end"===t?(e=>{const{content:t,scope:n}=e,i=[t.at(-3),t.at(-2),t.at(-1)];if(i[0]?.is("identifier","Native")&&i[1]?.is("edge","call-start")&&i[2]?.is("string")){i[0].type="void",i[1].type="void",i[2].scope.pop(),i[2].type="native";const{value:e}=i[2];return i[2].value=e.substring(1,e.length-1).replace(/`%/g,"%").replace(/""/g,'"'),t.push("void","call-end"),n.pop(),!0}return t.push("edge","call-end"),n.pop(),!0})(e):"param_start"===t?(e=>{const{content:t,scope:n}=e;return t.at(-2)?.is("property","constructor")||t.push("identifier","anonymous"),n.push("parameter"),t.push("edge","parameter-start"),!0})(e):"param_end"===t&&(e=>(e.content.push("edge","parameter-end"),e.scope.pop(),!0))(e)},if:e=>{const{content:t,scope:n,type:i,value:s}=e;return"if"===i?(n.next="if",t.push("if"),"unless"===s&&t.push("logical-operator","!"),t.push("edge","expression-start"),!0):"else"===i&&("switch"===n.last?(n.push("case"),t.push("new-line",e.indent.toString()).push("if","default"),!0):(n.next="else",t.push("if","else"),!0))},indent:e=>{const{type:t}=e;return"indent"===t?((e=>{(e=>{const{content:t,scope:n}=e;return!!t.last.is("sign","=")||!!["array","call","object","parameter"].includes(n.last)})(e)||(e.indent++,(e=>{const{content:t,scope:n}=e,{last:i}=n;["case","for","function","switch"].includes(i)&&(["catch","class","else","if","while"].includes(n.next)||("case"===i&&t.push("sign",":"),t.push("edge","block-start")))})(e),(e=>{const{content:t,scope:n}=e;if(["catch","class","else"].includes(n.next)){const e=n.next;n.next="",n.push(e),t.push("edge","block-start")}if(["if","while"].includes(n.next)){t.push("edge","expression-end");const e=n.next;n.next="",n.push(e),t.push("edge","block-start")}})(e),e.content.push("new-line",e.indent.toString()))})(e),!0):"outdent"===t&&((e=>{const{content:t,scope:n}=e;t.last.is("bracket","}-")?t.last.value="}":["array","call","object","parameter"].includes(n.last)||(e.indent--,n.length&&(t.push("new-line",e.indent.toString()).push("edge","block-end"),n.pop()))})(e),!0)},indentifier:e=>{const{content:t,type:n,value:i}=e;if("identifier"===n){if("class"===t.last.type){if(!/^[A-Z]/.test(i))throw new Error(`ahk/class-case: class name '${i}' must start with an uppercase letter.`);if(e.cache.identifiers.has(i))throw new Error(`ahk/class-case: class name '${i}' conflicts with variable/function/parameter of the same name. Please rename to avoid ambiguity.`);return e.cache.classNames.add(i),t.push("identifier",i),!0}return e.cache.identifiers.add(i),t.push("identifier",i),!0}return!1},module:e=>{const{content:t,type:n}=e;return"export"===n&&(t.push("statement","export"),!0)},native:e=>{const{content:t,type:n,value:i}=e;return"js"===n&&(t.push("native",i),!0)},nil:e=>{const{content:t,type:n}=e;return!!["nan","null","undefined"].includes(n)&&(t.push("string",'""'),!0)},number:e=>{const{content:t,type:n,value:i}=e;if("number"===n){let e=i;if(i.includes("n"))throw new Error(`ahk/forbidden: 'BigInt' literal is not supported in AHK v1. Offending value: '${i}'`);if(i.includes("_")&&(e=e.replace(/_/g,"")),i.includes("e")){const[t,n]=e.split("e");e=`${t}${"0".repeat(parseInt(n,10))}`}return t.push("number",e),!0}return!1},object:e=>{const{content:t,scope:n,token:i,type:s}=e;return"{"===s?"class"===n.last&&!t.last.is("sign","=")||(t.last.is("new-line")&&i.generated&&t.pop(),n.push("object"),t.push("bracket","{"),!0):"}"===s&&("class"===n.last||(i.generated&&"number"==typeof i.origin?.indentSize?t.push("bracket","}-"):t.push("bracket","}"),n.pop()),!0)},operator:e=>{const{content:t,type:n,value:i}=e;if("+"===n)return(e=>{const{content:t,token:n}=e;if(!n.spaced){const{last:e}=t;if("math"===e.type||"negative"===e.type)return"negative"===e.type&&(e.type="math"),t.push("negative","+"),!0}return t.push("math","+"),!0})(e);if("-"===n)return(e=>{const{content:t,token:n}=e;if(!n.spaced){const{last:e}=t;if(!["identifier","math"].includes(e.type))return"negative"===e.type&&(e.type="math"),t.push("negative","-"),!0}return t.push("math","-"),!0})(e);if("++"===n)return t.push("++"),!0;if("--"===n)return t.push("--"),!0;if("**"===n)return t.push("math","**"),!0;if("&&"===n||"||"===n)return t.push("logical-operator",i),!0;if("unary"===n||"unary_math"===n)return(e=>{const{content:t,type:n,value:i}=e;return("unary"===n&&"!"===i||"unary_math"===n)&&(t.push("logical-operator","!"),!0)})(e);if("compare"===n)return t.push("compare",i),!0;if("compound_assign"===n){if("||="===i||"?="===i)throw new Error(`ahk/forbidden: compound assignment '${i}' is not supported. Only standard assignments are allowed.`);return t.push("math",i),!0}return"math"===n&&(t.push("math",i),!0)},property:e=>{const{content:t,type:n,value:i}=e;return"."===n?(t.push("."),!0):"index_start"===n?("."===t.last.type&&t.pop(),t.push("edge","index-start"),!0):"index_end"===n?(t.push("edge","index-end"),!0):"property"===n&&(["prototype","this"].includes(t.last.type)&&t.push("."),t.push("property",i),!0)},sign:e=>{const{content:t,scope:n,type:i}=e;if("..."===i){if(!["call","parameter"].includes(n.last))throw new Error(`ahk/forbidden: spread operator '...' is only allowed in function calls or parameter lists. Context: ${n.last}`);t.push("sign","...")}if("="===i){const n=t.last;if("identifier"===n.type&&e.cache.classNames.has(n.value))throw new Error(`ahk/class-case: cannot assign to class name '${n.value}'. Please use a different identifier for variables.`);return t.push("sign","="),!0}return","===i?(t.push("sign",","),!0):":"===i&&("class"===n.last?(t.push("sign","="),!0):(t.push("sign",":"),!0))},statement:e=>{const{content:t,type:n,value:i}=e;return"extends"===n?(t.push("statement","extends"),!0):"return"===n?(t.push("statement","return"),!0):"throw"===n?(t.push("statement","throw"),!0):"statement"!==n||"break"!==i&&"continue"!==i?"unary"===n&&"new"===i&&(t.push("statement","new"),!0):(t.push("statement",i),!0)},string:e=>{const{content:t,token:n,type:i,value:s}=e;return"string"===i?(t.push("string",A(s,n[1].quote??"")),!0):"interpolation_start"===i?(t.push("edge","interpolation-start"),!0):"interpolation_end"===i&&(t.push("edge","interpolation-end"),!0)},switch:e=>{const{content:t,scope:n,type:i}=e;return"switch"===i?(n.push("switch"),t.push("if","switch"),!0):"leading_when"===i&&(n.push("case"),t.push("if","case"),!0)},try:e=>{const{content:t,scope:n,type:i}=e;return"catch"===i?(n.next="catch",t.push("try","catch"),!0):"finally"===i?(t.push("try","finally"),n.push("finally"),t.push("edge","block-start"),!0):"try"===i&&(t.push("try"),n.push("try"),t.push("edge","block-start"),!0)},while:e=>{const{content:t,scope:n,type:i}=e;return"loop"===i?(n.next="while",t.push("while").push("edge","expression-start").push("boolean","true"),!0):"while"===i?(n.next="while",t.push("while").push("edge","expression-start"),!0):"until"===i&&(n.next="while",t.push("while").push("logical-operator","!").push("edge","expression-start"),!0)}},S=e=>{for(const t of Object.keys(y))if("comment"!==t&&y[t](e))break;y.comment(e)};class w{#e=[];scope;constructor(e){this.scope=e}get last(){return this.at(-1)??new g}get length(){return this.#e.length}get list(){return[...this.#e]}at(t){return e(this.#e,t)}pop(){return this.#e.pop()??new g}push(...e){const t=new g(...e);return t.scope.length||t.scope.reload(this.scope),this.#e.push(t),this}reload(e=this.#e){return this.#e=e.filter(e=>!e.is("void")),this}shift(){return this.#e.shift()??new g}unshift(...e){const t=new g(...e);return t.scope.length||t.scope.reload(this.scope),this.#e.unshift(t),this}}const v=(e,t,n,i,s=[])=>{const{content:o}=e,r=o.at(n);return r?(s.push(r),r.is("edge","index-start")&&r.scope.isEqual(t.scope)?(i.value++,v(e,t,n+1,i,s)):r.is("edge","index-end")&&r.scope.isEqual(t.scope)?(i.value--,0===i.value?[n,s]:v(e,t,n+1,i,s)):v(e,t,n+1,i,s)):(i.value=0,[n,s])},b=(e,t,n,i)=>{e.flag.isChangeIndexUsed=!0;const s=[...n],o=s[0].scope,r=new f([...o.list,"call"]);i(t,[new g("identifier",`__ci_${e.options.salt}__`,o),new g("edge","call-start",r),...s,new g("edge","call-end",r)])},C=(e,t,n)=>{const i=t[0];n(e,1===t.length?[new g(i.type,(parseFloat(i.value)+1).toString(),i.scope)]:[...t,new g("math","+",i.scope),new g("number","1",i.scope)])},k=(e,t)=>{const{content:n}=e,i=n.at(t);return i?"new-line"===i.type?parseInt(i.value,10):k(e,t-1):0},M=(t,n,i,s=[[]])=>{const{content:o}=t,r=o.at(n);if(!r)return s;const a=e(s,-1);return a?r.is("edge","array-start")?s:(r.is("sign",",")?s.push([]):a.unshift(r),i.pop(),M(t,n-1,i,s)):s},E=e=>{(e=>{const{content:t}=e,n=`__ci_${e.options.salt}__`,i={value:0},s=(t,n)=>{((e,t,n)=>{const{content:i}=e,s=i.list;s.splice(t[0],t[1]-t[0]+1,...n),i.reload(s)})(e,t,n)};let o=-1,r=t.length;for(;o<r;){o++,r=t.length;const a=t.at(o);if(!a?.is("edge","index-start"))continue;const l=t.at(o+1);if(!l)continue;if(l.is("identifier",n))continue;if(l.is("edge","index-end"))continue;const[c,u]=v(e,a,o,i),p=u.slice(1,u.length-1);let d="number";for(const e of p){if([".","identifier","property","this"].includes(e.type)){d="identifier";break}if("string"===e.type){d="string";break}}"identifier"!==d?"number"===d&&C([o+1,c-1],p,s):b(e,[o+1,c-1],p,s)}})(e),(e=>{const{content:t}=e;let n=[];const i="__array__";let s=[];t.list.forEach((o,r)=>{if(n.length&&"new-line"===o.type){const t=k(e,r-1);return n.forEach((e,r)=>s=[...s,...[["new-line",t.toString()],...n[n.length-r-1].map(e=>[e.type,e.value]),["sign","="],["identifier",i],["edge","index-start"],["number",(r+1).toString()],["edge","index-end"]].map(e=>new g(e[0],e[1],o.scope))]),n.length=0,void s.push(o)}o.is("sign","=")&&t.at(r-1)?.is("edge","array-end")?(n=M(e,r-2,s),s=s.slice(0,s.length-2),s=[...s,new g("identifier",i,o.scope),new g("sign","=",o.scope)]):s.push(o)}),t.reload(s)})(e)},W=(e,t,n)=>{const{content:i}=e;if(e.flag[t]){const t=[new g("native",'global __ci_SALT_PLACEHOLDER__ := Func("salt_1")\nsalt_1(__ipt__) {\n if __ipt__ is Number\n return __ipt__ + 1\n return __ipt__\n}',[]),new g("new-line","0",[])];t.length>0&&(t.forEach(t=>{if("string"==typeof t.value){const{value:n}=t;let i=n;i.includes("__ci_SALT_PLACEHOLDER__")&&(i=i.replace(/__ci_SALT_PLACEHOLDER__/g,`__ci_${e.options.salt??"salt"}__`)),t.value=i}}),i.reload([...t,...i.list]))}},x=["Class","Function","Native"],D=e=>{const t=(e=>{const{content:t}=e,n=new Set;return t.list.forEach((e,i)=>{if("class"!==e.type)return;const s=t.at(i+1);if(!s)throw new Error(`ahk/internal: class/count: missing identifier after class keyword (token index ${i})`);"identifier"===s.type&&n.add(s.value)}),n})(e);(e=>{e.forEach(e=>{if(x.includes(e))throw new Error(`ahk/forbidden: class name '${e}' is reserved or forbidden. See forbidden list.`)})})(t)},I=(e,t,n,i,s=[])=>{const{content:o}=e,r=o.at(n);if(!r)return s;const a=r.clone();for(let e=0;e<i.length-1;e++)a.scope.shift();if(s.push(a),!r.is("edge","block-end")||!r.scope.isEqual(i))return r.type="void",I(e,t,n+1,i,s);r.type="native",r.value=`Func("${e.options.salt}_${t}")`,s.push(new g("new-line","0",i));const l=parseInt(s[((e,t)=>{if(!Array.isArray(e))return-1;const n="function"==typeof t?t:"string"==typeof t||"number"==typeof t?e=>Boolean(e[t]):"object"==typeof t?e=>{for(const n in t)if(e[n]!==t[n])return!1;return!0}:null;if(!n)return-1;for(let t=0;t<e.length;t++)if(n(e[t],t,e))return t;return-1})(s,{type:"new-line"})].value,10)-1;return l>0&&s.forEach(e=>{if("new-line"!==e.type)return;let t=parseInt(e.value,10)-l;t<0&&(t=0),e.value=t.toString()}),s},L=(e,t=1)=>{const{content:n}=e;n.reload();const i=((e,t)=>{if(!Array.isArray(e))return-1;const n="function"==typeof t?t:"string"==typeof t||"number"==typeof t?e=>Boolean(e[t]):"object"==typeof t?e=>{for(const n in t)if(e[n]!==t[n])return!1;return!0}:null;if(!n)return-1;for(let t=e.length-1;t>=0;t--)if(n(e[t],t,e))return t;return-1})(n.list,{type:"function",value:"anonymous"});if(!~i)return;const s=n.at(i);if(!s)throw new Error(`ahk/internal: function/anonymous: missing anonymous function at expected index (content length: ${n.list.length})`);s.value=`${e.options.salt}_${t}`,I(e,t,i,[...s.scope.list,"function"]).forEach(e=>{"void"!==e.type&&n.push(e)}),L(e,t+1)},F=e=>{L(e),(e=>{const{content:t}=e,n=[];t.list.forEach(e=>{if("native"!==e.type||!e.value.startsWith("Func(")||!e.value.endsWith(")"))return void n.push(e);const t=e.scope.list;t.pop(),n.push(new g("identifier","Func",t)),n.push(new g("edge","call-start",[...t,"call"])),n.push(new g("string",e.value.slice(5,e.value.length-1),[...t,"call"])),n.push(new g("edge","call-end",[...t,"call"]))}),t.reload(n)})(e)},G=(e,t,n)=>{const{content:i}=e,s=i.at(t);return s?s.is("edge","parameter-start")&&n.scope.isEqual([...s.scope.slice(0,s.scope.length-1),"function"])?t:G(e,t-1,n):0},T=t=>{(t=>{const{content:n}=t,i=[];n.list.forEach((t,s)=>{if(i.push(t),!t.is("edge","parameter-start"))return;if(e(i,-3)?.is("property","constructor"))return void(i[i.length-2].type="void");if("class"!==t.scope.at(-1)&&("parameter"!==t.scope.at(-1)||"class"!==t.scope.at(-2)))return;const o=t.scope.list;i.push(new g("this","this",o));const r=n.at(s+1);r?.is("edge","parameter-end")||i.push(new g("sign",",",o))}),n.reload(i)})(t),(e=>{const{content:t}=e,n=[];t.list.forEach((i,s)=>{if(n.push(i),!i.is("edge","block-end"))return;if("function"!==i.scope.at(-1))return;if("class"!==i.scope.at(-2))return;const o=G(e,s,i);if(t.at(o-1)?.is("property","constructor"))return;const r=[i.scope.list];r[1]=[...r[0],"call"],n.push(new g(".",".",r[0])),n.push(new g("identifier","Bind",r[0])),n.push(new g("edge","call-start",r[1])),n.push(new g("this","this",r[1])),n.push(new g("edge","call-end",r[1]))}),t.reload(n)})(t),(e=>{const{content:t}=e;t.list.forEach(e=>{e.is("property","constructor")&&(e.value="__New")})})(t),(e=>{const{content:t}=e,n=[];t.list.forEach((e,i)=>{if(n.push(e),!e.is("super"))return;const s=t.at(i+1);if(!s?.is("edge","call-start"))return;const o=s.scope.list;n.push(new g(".",".",o),new g("property","__New",o))}),t.reload(n)})(t)},P=(e,t)=>{const n=null==e,i=null==t;return n&&i?0:n?-1:i?1:null},$=(e,t)=>{if(typeof e==typeof t&&("string"==typeof e||"number"==typeof e||"boolean"==typeof e))return e<t?-1:e>t?1:0;const n=String(e),i=String(t);return n<i?-1:n>i?1:0},R=[],j=[],N=[];let O=0;const H=()=>j,B=()=>N,K=()=>O,V=e=>{O=e},z=()=>{O=0,j.length=0,R.length=0,N.length=0},q=()=>{for(const[e,t]of((e,...t)=>{if(!Array.isArray(e))return[];if(0===t.length)return[...e];const n=t.map(e=>"function"==typeof e?e:"string"==typeof e||"number"==typeof e?t=>t[e]:()=>{});return[...e].sort((e,t)=>{for(const i of n){const n=i(e),s=i(t),o=P(n,s);if(null!==o){if(0===o)continue;return o}const r=$(n,s);if(0!==r)return r}return 0})})(R,e=>e[0]).reverse())j.splice(e,0,...t)},U=(e,t,n)=>{const{content:i}=e,s=i.at(n);return s?s.is("edge","block-end")&&s.scope.isEqual(t.scope)?n:U(e,t,n+1):0},Y=(e,t,n)=>{const i=[t.scope.slice(0,t.scope.length-1)];i[1]=[...i[0],"call"];let s=[];for(const e of N){for(const t of e)t.scope.reload(t.scope.list.join(",").replace(/^.*?parameter/u,i[1].join(",")).split(",")),s.push(t);s.push(new g("sign",",",i[1]))}s.pop(),s=[new g(".",".",i[0]),new g("identifier","Bind",i[0]),new g("edge","call-start",i[1]),...s,new g("edge","call-end",i[1])],R.push([U(e,t,n)+1,s])},X=(e,t,n,i=[])=>{const{content:s}=e,o=s.at(n);return o?o.scope.isEqual(t.scope)&&(o.is("sign",",")||o.is("edge","parameter-end"))?i:(i.push(o),X(e,t,n+1,i)):i},J=(e,t,n)=>{const{content:i}=e;if(!t.is("sign","="))return!1;if("parameter"!==t.scope.at(-1))return!1;const s=i.at(n+1);if(!s)return!1;if(!["identifier","this"].includes(s.type))return!1;const o=i.at(n-1);if(!o)return!1;if(!["identifier","this"].includes(o.type))return!1;const r=H(),a=B();return r.push(new g("void")),a.push(X(e,s,n+1)),V(a[a.length-1].length),!0},Q=new Map,Z=new Set,ee=()=>Q,te=()=>Z,ne=()=>{Z.clear(),Q.clear()},ie=(e,t,n)=>{const{content:i}=e,s=i.at(t);if(!s?.is("edge","block-end")||!s.scope.isEqual([...n.scope.slice(0,n.scope.length-1),"function"])){if(s?.is("identifier")&&!Q.get(s.value)){const e=i.at(t-1);if(!e)return;const n=i.at(t+1);if(!n)return;Q.set(s.value,e.is("for","for")||n.is("sign","=")||n.is("for-in")||"parameter"===s.scope.at(-1))}ie(e,t+1,n)}},se=(e,t,n)=>{const{content:i}=e,s=i.at(t);if(!s?.is("edge","parameter-end")||!s.scope.isEqual(n.scope)){if(s?.is("identifier")){const e=i.at(t+1);if(!e)return;(e.is("sign","=")||e.is("sign",",")||e.is("sign","...")||e.is("edge","parameter-end"))&&Z.add(s.value)}se(e,t+1,n)}},oe=(e,t)=>{const{content:n}=e,i=n.at(t);return i?.is("edge","block-start")?t:oe(e,t+1)},re=(e,t)=>{const{content:n}=e,i=n.at(t);return i?.is("edge","block-start")&&"function"===i.scope.at(-1)?[t,i.scope]:re(e,t+1)},ae=(e,t)=>{const{content:n}=e,{i:i,list:s,scope:o}=t,r=n.at(i);if(!r)return s;s.push(r);return r.is("edge","block-end")&&r.scope.isEqual(o)?s:ae(e,{i:i+1,list:s,scope:o})},le=(e,t)=>{const{content:n}=e;n.list.forEach((e,i)=>{"identifier"===e.type&&"call"===e.scope.at(-1)&&t.has(e.value)&&(n.at(i+1)?.is("edge","call-start")||(e.type="native",e.value=`Func("${e.value}")`))})},ce=e=>{(e=>{const{content:t}=e;t.list.forEach((e,n)=>{if(!e.is("edge","parameter-start"))return;const i=t.at(n-1);i?.is("identifier")&&(i.type="function")})})(e),T(e),(e=>{const{content:t}=e,n=[];t.list.forEach((i,s)=>{if(n.push(i),!i.is("edge","parameter-start"))return;if(t.at(s-1)?.is("property","__New"))return;const o=oe(e,s);ne(),se(e,s,i),ie(e,o,i);const r=ee(),a=te();r.forEach((t,s)=>{t||a.has(s)||e.cache.global.has(s)||s.startsWith("__")&&s.endsWith("__")||s[0].toLowerCase()===s[0]&&n.push(...[["identifier",s],["sign","="],["identifier",s],["sign",","]].map(e=>new g(e[0],e[1],i.scope)))})}),t.reload(n),(e=>{const{content:t}=e,n=[];t.list.forEach((e,i)=>{e.is("sign",",")&&t.at(i+1)?.is("edge","parameter-end")||n.push(e)}),t.reload(n)})(e)})(e),(e=>{const{content:t}=e,n={i:-1,scope:new f,isObjectWithoutBrackets:!1},i=[];t.list.forEach((s,o)=>{if(i.push(s),o===n.i)return n.isObjectWithoutBrackets&&i.push(new g("new-line",n.scope.length.toString(),n.scope)),void i.push(new g("statement","return",n.scope));if(!s.is("edge","parameter-start"))return;if(t.at(o-1)?.is("property","__New"))return;const[r,a]=re(e,o),l=ae(e,{i:r,list:[],scope:a}),c=l[1].is("bracket","{");l.filter(e=>e.is("new-line")&&e.scope.isEqual(a)).length>(c?1:2)||(e=>!!(e.is("for")||e.is("if")||e.is("native")&&"__mark:do__"!==e.value||e.is("statement")&&"new"!==e.value||e.is("try")||e.is("while")))(l[2])||(n.i=r+(c?0:1),n.scope=a,n.isObjectWithoutBrackets=c)}),t.reload(i)})(e),(e=>{const{content:t}=e;z(),t.list.forEach((t,n)=>{const i=H(),s=B(),o=K();return o?(V(o-1),void i.push(new g("void","",[]))):s.length&&t.is("edge","block-start")?(i.push(t),Y(e,t,n),void(s.length=0)):void(J(e,t,n)||i.push(t))}),q();const n=H();t.reload(n)})(e),F(e);const t=(e=>{const{content:t}=e,n=new Set;return t.list.forEach(e=>{e.is("function")&&n.add(e.value)}),n})(e);le(e,t),(e=>{const{content:t}=e;let n=!1;const i=[];t.list.forEach(e=>{if(n&&(e.is("new-line")||e.is("bracket","}")||e.is("bracket",")"))){n=!1;const t=[...e.scope.list,"call"];return void i.push(new g("bracket",")",e.scope),new g("edge","call-start",t),new g("edge","call-end",t),e)}e.is("native","__mark:do__")?(n=!0,i.push(new g("bracket","(",e.scope))):i.push(e)}),t.reload(i)})(e)},ue=e=>{(e=>{const{content:t}=e,n=[],i="__object__";let s=[];const o=e=>{const n=t.at(e);return n?"new-line"===n.type?parseInt(n.value,10):o(e-1):0},r=e=>{const i=t.at(e);i&&(i.is("bracket","{")||(i.is("identifier")&&n.push(i.value),s.pop(),r(e-1)))};t.list.forEach((e,a)=>{if(n.length&&"new-line"===e.type){const t=o(a-1),r=e.scope;for(let e=0;e<n.length;e++)s=[...s,new g("new-line",t.toString(),r),new g("identifier",n[n.length-e-1],r),new g("sign","=",r),new g("identifier",i,r),new g("edge","index-start",r),new g("string",`"${n[n.length-e-1]}"`,r),new g("edge","index-end",r)];return n.length=0,void s.push(e)}e.is("sign","=")&&t.at(a-1)?.is("bracket","}")?(r(a),s=[...s,new g("identifier",i,e.scope),new g("sign","=",e.scope)]):s.push(e)}),t.reload(s)})(e),(e=>{const{content:t}=e,n=[];t.list.forEach((e,i)=>{if(n.push(e),!e.is("identifier"))return;if("object"!==e.scope.at(-1))return;const s=t.at(i-1);if(!s)return;if(!s.is("bracket","{")&&!s.is("sign",","))return;const o=t.at(i+1);o&&(o.is("bracket","}")||o.is("sign",","))&&n.push(new g("sign",":",e.scope.list),new g("identifier",e.value,e.scope.list))}),t.reload(n)})(e),(e=>{const{content:t}=e,n=[];t.list.forEach((e,i)=>{if(n.push(e),!e.is("sign","="))return;const s=t.at(i+1);if(!s?.is("bracket","{"))return;const o=((e,t)=>{const n=[];let i=t,s=e.at(i);if(!s?.is("identifier"))return null;for(n.push(s.value),i++;i<e.list.length;){if(s=e.at(i),!s)return null;if(s.is("bracket","}"))break;if(!s.is("sign",","))return null;{i++;const t=e.at(i);if(!t?.is("identifier"))return null;n.push(t.value),i++}}return n})(t,i+2);if(!o)return;let r=i+2;for(;t.at(r)&&!t.at(r)?.is("bracket","}");)r++;const a=t.at(r+1);if(a&&!a.is("new-line")&&!a.is("edge"))return;const l=t.at(i+2);l&&o.forEach((e,t)=>{t>0&&n.push(new g("sign",",",l.scope.list)),n.push(new g("sign",":",l.scope.list),new g("identifier",e,l.scope.list))})}),t.reload(n)})(e)};const pe=["abstract","arguments","async","await","boolean","break","byte","case","catch","char","class","const","continue","debugger","default","delete","do","double","else","enum","eval","export","extends",!1,"final","finally","float","for","function","goto","if","implements","import","in","instanceof","int","interface","let","long","native","new",null,"package","private","promise","protected","public","return","short","static","super","switch","synchronized","this","throw","throws","transient",!0,"try","typeof","var","void","volatile","while","with","yield","any","as","bigint","keyof","never","number","object","readonly","string","symbol","type","undefined","unique","unknown","and","or","not","is","isnt","of","then","unless","until","when","yes","no","on","off","A_AhkPath","A_AhkVersion","A_AppData","A_AppDataCommon","A_AutoTrim","A_BatchLines","A_CaretX","A_CaretY","A_ComputerName","A_ControlDelay","A_Cursor","A_DD","A_DDD","A_DDDD","A_DefaultMouseSpeed","A_Desktop","A_DesktopCommon","A_DetectHiddenText","A_DetectHiddenWindows","A_EndChar","A_EventInfo","A_ExitReason","A_FormatFloat","A_FormatInteger","A_Gui","A_GuiEvent","A_GuiControl","A_GuiControlEvent","A_GuiHeight","A_GuiWidth","A_GuiX","A_GuiY","A_Hour","A_IconFile","A_IconHidden","A_IconNumber","A_IconTip","A_Index","A_IPAddress1","A_IPAddress2","A_IPAddress3","A_IPAddress4","A_Is64bitOS","A_IsAdmin","A_IsCompiled","A_IsCritical","A_IsPaused","A_IsSuspended","A_IsUnicode","A_KeyDelay","A_Language","A_LastError","A_LineFile","A_LineNumber","A_LoopField","A_LoopFileAttrib","A_LoopFileDir","A_LoopFileExt","A_LoopFileFullPath","A_LoopFileLongPath","A_LoopFileName","A_LoopFileShortName","A_LoopFileShortPath","A_LoopFileSize","A_LoopFileSizeKB","A_LoopFileSizeMB","A_LoopFileTimeAccessed","A_LoopFileTimeCreated","A_LoopFileTimeModified","A_LoopReadLine","A_LoopRegKey","A_LoopRegName","A_LoopRegSubkey","A_LoopRegTimeModified","A_LoopRegType","A_LoopRegValue","A_MDAY","A_Min","A_MM","A_MMM","A_MMMM","A_Mon","A_MouseDelay","A_MSec","A_MyDocuments","A_Now","A_NowUTC","A_NumBatchLines","A_OSType","A_OSVersion","A_PriorHotkey","A_PriorKey","A_ProgramFiles","A_Programs","A_ProgramsCommon","A_ScreenHeight","A_ScreenWidth","A_ScriptDir","A_ScriptFullPath","A_ScriptName","A_Sec","A_Space","A_StartMenu","A_StartMenuCommon","A_Startup","A_StartupCommon","A_StringCaseSense","A_Tab","A_Temp","A_ThisFunc","A_ThisHotkey","A_ThisLabel","A_ThisMenu","A_ThisMenuItem","A_ThisMenuItemPos","A_TickCount","A_TimeIdle","A_TimeIdlePhysical","A_TimeSincePriorHotkey","A_TimeSinceThisHotkey","A_TitleMatchMode","A_TitleMatchModeSpeed","A_UserName","A_WDay","A_WinDelay","A_WinDir","A_WorkingDir","A_YDay","A_YEAR","A_YWeek","A_YYYY","Abs","ACos","Asc","ASin","ATan","Ceil","Chr","Cos","Exp","Floor","GetKeyName","GetKeySC","GetKeyState","GetKeyVK","InStr","IsFunc","IsLabel","Ln","Log","LTrim","Max","Min","Mod","NumGet","NumPut","Ord","RegExMatch","RegExReplace","Round","RTrim","Sin","Sqrt","StrGet","StrLen","StrPut","StrReplace","StrSplit","SubStr","Tan","Trim","VarSetCapacity","AutoTrim","BlockInput","Break","Click","ClipWait","ComObjActive","ComObjArray","ComObjConnect","ComObjCreate","ComObjError","ComObjFlags","ComObjGet","ComObjQuery","ComObjType","ComObjValue","Continue","Control","ControlClick","ControlFocus","ControlGet","ControlGetFocus","ControlGetPos","ControlGetText","ControlMove","ControlSend","ControlSendRaw","ControlSetText","CoordMode","Critical","DetectHiddenText","DetectHiddenWindows","DllCall","Drive","DriveGet","DriveSpaceFree","Edit","Else","EnvAdd","EnvDiv","EnvGet","EnvMult","EnvSet","EnvSub","EnvUpdate","Exit","ExitApp","File","FileAppend","FileCopy","FileCopyDir","FileCreateDir","FileCreateShortcut","FileDelete","FileEncoding","FileExist","FileGetAttrib","FileGetShortcut","FileGetSize","FileGetTime","FileGetVersion","FileInstall","FileMove","FileMoveDir","FileOpen","FileRead","FileReadLine","FileRecycle","FileRecycleEmpty","FileRemoveDir","FileSelectFile","FileSelectFolder","FileSetAttrib","FileSetTime","FormatTime","Gosub","Goto","GroupActivate","GroupAdd","GroupClose","GroupDeactivate","Gui","GuiControl","GuiControlGet","Hotkey","Hotstring","If","IfEqual","IfExist","IfGreater","IfGreaterOrEqual","IfInString","IfLess","IfLessOrEqual","IfMsgBox","IfNotEqual","IfNotExist","IfNotInString","IfWinActive","IfWinExist","IfWinNotActive","IfWinNotExist","ImageSearch","IniDelete","IniRead","IniWrite","Input","InputBox","KeyHistory","KeyWait","ListHotkeys","ListLines","ListVars","Loop","Menu","MouseClick","MouseClickDrag","MouseGetPos","MouseMove","MsgBox","OnExit","OnMessage","OutputDebug","Pause","PixelGetColor","PixelSearch","PostMessage","Process","Progress","Random","RegDelete","RegRead","RegWrite","Reload","Return","Run","RunAs","RunWait","Send","SendEvent","SendInput","SendLevel","SendMessage","SendMode","SendPlay","SendRaw","SetBatchLines","SetCapsLockState","SetControlDelay","SetDefaultMouseSpeed","SetEnv","SetFormat","SetKeyDelay","SetMouseDelay","SetNumLockState","SetRegView","SetScrollLockState","SetStoreCapslockMode","SetTimer","SetTitleMatchMode","SetWinDelay","SetWorkingDir","Shutdown","Sleep","Sort","SoundBeep","SoundGet","SoundGetWaveVolume","SoundPlay","SoundSet","SoundSetWaveVolume","SplashImage","SplashTextOff","SplashTextOn","SplitPath","StatusBarGetText","StatusBarWait","StringCaseSense","StringGetPos","StringLeft","StringLen","StringLower","StringMid","StringReplace","StringRight","StringSplit","StringTrimLeft","StringTrimRight","StringUpper","Suspend","SysGet","Thread","ToolTip","Transform","TrayTip","URLDownloadToFile","WinActivate","WinActivateBottom","WinClose","WinGet","WinGetActiveStats","WinGetActiveTitle","WinGetClass","WinGetPos","WinGetText","WinGetTitle","WinHide","WinKill","WinMaximize","WinMenuSelectItem","WinMinimize","WinMinimizeAll","WinMinimizeAllUndo","WinMove","WinRestore","WinSet","WinSetTitle","WinShow","WinWait","WinWaitActive","WinWaitClose","WinWaitNotActive","Array","Buffer","Clipboard","ComObject","ComObjArray","ComObjConnect","ComObjCreate","ComObjFromPtr","ComObjQuery","ComObjType","ComObjValue","ComValue","Error","Exception","File","FileObject","Func","Gui","GuiControl","InputHook","Map","Menu","MenuBar","Object","Prototype","RegExMatchObject","String","Throw","Try","Catch","Finally","Until","While","Loop","For","Break","Continue","Return","Local","Global","Static","Super","This","Unset","Abs","ACos","ASin","ATan","ATan2","Ceil","Chr","Cos","DateAdd","DateDiff","DirCopy","DirCreate","DirDelete","DirExist","DirMove","DirSelect","DllCall","Download","DriveEject","DriveGetCapacity","DriveGetFileSystem","DriveGetLabel","DriveGetList","DriveGetSerial","DriveGetSpaceFree","DriveGetStatus","DriveGetType","DriveRetract","DriveSetLabel","EditGetCurrentCol","EditGetCurrentLine","EditGetLine","EditGetLineCount","EditGetSelectedText","EditPaste","Exp","FileAppend","FileCopy","FileCreateShortcut","FileDelete","FileEncoding","FileExist","FileGetAttrib","FileGetShortcut","FileGetSize","FileGetTime","FileGetVersion","FileInstall","FileMove","FileOpen","FileRead","FileRecycle","FileSelect","FileSetAttrib","FileSetTime","Float","Floor","Format","FormatTime","GetKeyName","GetKeySC","GetKeyState","GetKeyVK","GroupActivate","GroupAdd","GroupClose","GroupDeactivate","GuiFromHwnd","Hotkey","Hotstring","IL_Add","IL_Create","IL_Destroy","ImageSearch","IniDelete","IniRead","IniWrite","Input","InputBox","InStr","Integer","IsAlnum","IsAlpha","IsDigit","IsFloat","IsInteger","IsLabel","IsLower","IsNumber","IsObject","IsSet","IsSpace","IsTime","IsUpper","IsXDigit","KeyHistory","KeyWait","ListHotkeys","ListLines","ListVars","Ln","LoadPicture","Log","LTrim","Max","MenuFromHandle","MenuSelect","Min","Mod","MonitorGet","MonitorGetCount","MonitorGetName","MonitorGetPrimary","MonitorGetWorkArea","MouseClick","MouseClickDrag","MouseGetPos","MouseMove","MsgBox","Number","NumGet","NumPut","ObjAddRef","ObjRelease","OnClipboardChange","OnError","OnExit","OnMessage","Ord","OutputDebug","Pause","PixelGetColor","PixelSearch","PostMessage","ProcessClose","ProcessExist","ProcessGetName","ProcessGetParent","ProcessGetPath","ProcessSetPriority","ProcessWait","ProcessWaitClose","Random","RegDelete","RegDeleteKey","RegExMatch","RegExReplace","RegRead","RegWrite","Reload","Round","RTrim","Run","RunAs","RunWait","Send","SendEvent","SendInput","SendLevel","SendMessage","SendMode","SendPlay","SendText","SetCapsLockState","SetControlDelay","SetDefaultMouseSpeed","SetKeyDelay","SetMouseDelay","SetNumLockState","SetRegView","SetScrollLockState","SetStoreCapsLockMode","SetTimer","SetTitleMatchMode","SetWinDelay","SetWorkingDir","Shutdown","Sin","Sleep","Sort","SoundBeep","SoundGetInterface","SoundGetMute","SoundGetName","SoundGetVolume","SoundPlay","SoundSetMute","SoundSetVolume","SplitPath","Sqrt","StatusBarGetText","StatusBarWait","StrCompare","StrGet","StrLen","StrLower","StrPtr","StrPut","StrReplace","StrSplit","StrUpper","SubStr","Suspend","SysGet","SysGetIPAddresses","Tan","Thread","ToolTip","TraySetIcon","TrayTip","Trim","Type","VarSetStrCapacity","VerCompare","WinActivate","WinActivateBottom","WinClose","WinExist","WinGetClass","WinGetClientPos","WinGetControls","WinGetControlsHwnd","WinGetCount","WinGetExStyle","WinGetID","WinGetIDLast","WinGetList","WinGetMinMax","WinGetPID","WinGetPos","WinGetProcessName","WinGetProcessPath","WinGetStyle","WinGetText","WinGetTitle","WinGetTransColor","WinGetTransparent","WinHide","WinKill","WinMaximize","WinMinimize","WinMinimizeAll","WinMinimizeAllUndo","WinMove","WinMoveBottom","WinMoveTop","WinRedraw","WinRestore","WinSetAlwaysOnTop","WinSetEnabled","WinSetExStyle","WinSetRegion","WinSetStyle","WinSetTitle","WinSetTransColor","WinSetTransparent","WinShow","WinWait","WinWaitActive","WinWaitClose","WinWaitNotActive","If","Else","Switch","Case","Default","Include","IncludeAgain","NoEnv","NoTrayIcon","Requires","SingleInstance","UseHook","Warn","WorkingDir","A_Args","A_AhkPath","A_AhkVersion","A_AppData","A_AppDataCommon","A_CaretX","A_CaretY","A_Clipboard","A_ComputerName","A_ControlDelay","A_CoordModeCaret","A_CoordModeMenu","A_CoordModeMouse","A_CoordModePixel","A_CoordModeToolTip","A_Cursor","A_DD","A_DDD","A_DDDD","A_DefaultMouseSpeed","A_Desktop","A_DesktopCommon","A_DetectHiddenText","A_DetectHiddenWindows","A_EndChar","A_EventInfo","A_FileEncoding","A_Hour","A_IconFile","A_IconHidden","A_IconNumber","A_IconTip","A_Index","A_InitialWorkingDir","A_IPAddress1","A_IPAddress2","A_IPAddress3","A_IPAddress4","A_Is64bitOS","A_IsAdmin","A_IsCompiled","A_IsCritical","A_IsPaused","A_IsSuspended","A_KeyDelay","A_KeyDelayPlay","A_KeyDuration","A_KeyDurationPlay","A_Language","A_LastError","A_LineFile","A_LineNumber","A_LoopField","A_LoopFileAttrib","A_LoopFileDir","A_LoopFileExt","A_LoopFileFullPath","A_LoopFileName","A_LoopFileShortName","A_LoopFileShortPath","A_LoopFileSize","A_LoopFileSizeKB","A_LoopFileSizeMB","A_LoopFileTimeAccessed","A_LoopFileTimeCreated","A_LoopFileTimeModified","A_LoopReadLine","A_LoopRegKey","A_LoopRegName","A_LoopRegSubKey","A_LoopRegTimeModified","A_LoopRegType","A_LoopRegValue","A_MDAY","A_Min","A_MM","A_MMM","A_MMMM","A_Mon","A_MouseDelay","A_MouseDelayPlay","A_MSec","A_MyDocuments","A_Now","A_NowUTC","A_OSVersion","A_PriorHotkey","A_PriorKey","A_ProgramFiles","A_Programs","A_ProgramsCommon","A_PtrSize","A_RegView","A_ScreenDPI","A_ScreenHeight","A_ScreenWidth","A_ScriptDir","A_ScriptFullPath","A_ScriptHwnd","A_ScriptName","A_Sec","A_SendLevel","A_SendMode","A_Space","A_StartMenu","A_StartMenuCommon","A_Startup","A_StartupCommon","A_Tab","A_Temp","A_ThisFunc","A_ThisHotkey","A_TickCount","A_TimeIdle","A_TimeIdleKeyboard","A_TimeIdleMouse","A_TimeIdlePhysical","A_TimeSincePriorHotkey","A_TimeSinceThisHotkey","A_TitleMatchMode","A_TitleMatchModeSpeed","A_UserName","A_WDay","A_WinDelay","A_WinDir","A_WorkingDir","A_YDay","A_Year","A_YWeek","A_YYYY"].filter(e=>"string"==typeof e).map(e=>e.toLowerCase()),de=e=>{const t=e.toLowerCase();return t.startsWith("a_")||pe.includes(t)},he=e=>{const{content:t}=e;t.list.forEach((t,n)=>{((e,t)=>{const{content:n}=e,i=n.at(t),s=n.at(t+1);if(i?.is("identifier")&&s?.is("sign","=")&&de(i.value))throw new Error(`ahk/forbidden: variable name '${i.value}' is reserved or forbidden. See forbidden.json or avoid a_ prefix.`)})(e,n),((e,t)=>{const{content:n}=e,i=n.at(t),s=n.at(t-1);if(i?.is("identifier")&&(s?.is("sign",",")||s?.is("bracket","[")))for(let e=t+1;e<Math.min(t+10,n.list.length);e++){const t=n.at(e),s=n.at(e+1);if(t?.is("bracket","]")&&s?.is("sign","=")){if(de(i.value))throw new Error(`ahk/forbidden: variable name '${i.value}' is reserved or forbidden in destructuring assignment.`);break}}})(e,n),((e,t)=>{const{content:n}=e,i=n.at(t),s=n.at(t-1);if(!i?.is("identifier"))return;const o=s?.is("edge","parameter-start"),r=s?.is("sign",",")&&(()=>{for(let e=t-2;e>=Math.max(0,t-10);e--){const t=n.at(e);if(t?.is("edge","parameter-start"))return!0;if(t?.is("edge","parameter-end"))return!1}return!1})();if((o||r)&&de(i.value))throw new Error(`ahk/forbidden: parameter name '${i.value}' is reserved or forbidden in function definition.`)})(e,n)})},fe=e=>{he(e),(e=>{const{content:t}=e,n=new Set;let i=0;const s=[];t.list.forEach((e,o)=>{if(i)return void i--;if(s.push(e),!e.is("sign","="))return;const r=t.at(o-1);if(r?.is("identifier")&&!r.scope.length&&(!(o-2>=0)||t.at(o-2)?.is("new-line"))&&!n.has(r.value)){if(n.add(r.value),t.at(o+1)?.is("identifier",r.value)&&t.at(o+2)?.is("new-line"))return s.splice(s.length-2,2),void(i=2);s.splice(s.length-2,0,new g("native","global ",e.scope))}}),t.reload(s),e.cache.global=n})(e),(e=>{const{content:t}=e,n=[];t.list.forEach((e,i)=>{if(!e.is("statement","new"))return void n.push(e);const s=t.at(i+1);s?.is("identifier","Error")?s.value="Exception":n.push(e)}),t.reload(n)})(e)},ge=async e=>{var t;(e=>{const{content:t}=e;t.reload(t.list.filter((e,n)=>!((e,t,n)=>{if(!t.is("new-line"))return!1;const i=e.at(n-1);return!(!i||!i.is("bracket","(")&&!i.is("sign","="))})(t,e,n)))})(e),(e=>{const{content:t}=e,n=e=>{const i=t.at(e);return i?i.is("edge","block-start")&&"for"===i.scope.at(-1)?e:n(e+1):0},i=e=>{const n=t.at(e);if(!n)return"";if(n.is("for","for")){const n=t.at(e+1);if(!n)throw new Error(`ahk/internal: for: missing variable name after for/in keyword (token index ${e})`);return n.value}return i(e-1)},s=[];if(t.list.forEach((e,o)=>{if(!e.is("for-in","in"))return;const r=i(o);if(r.startsWith("__")&&r.endsWith("__"))return;const a=n(o),l=t.at(a+1);if(!l)throw new Error(`ahk/internal: for: missing block-start after for/in statement (token index ${a})`);const c=l.value,{scope:u}=l;s.unshift([a+1,[new g("new-line",c,u),new g("identifier",r,u),new g("sign","=",u),new g("identifier",r,u),new g("math","-",u),new g("number","1",u)]])}),s.length){const e=t.list;for(const t of s)e.splice(t[0],0,...t[1]);t.reload(e)}})(e),E(e),ue(e),fe(e),await(t=e,void W(t,"isChangeIndexUsed")),D(e),ce(e)},_e=e=>{const{i:t,it:n}=e,i=e.content.at(t+1);return i?.is("new-line")?n.value:`${n.value} `},me=e=>{let t=parseInt(e.it.value,10);return t<0&&(t=0),`\n${" ".repeat(2*t)}`};let Ae=[];const ye=()=>Ae,Se=e=>{Ae=e},we=(e,t)=>{if(!t.options.comments)return e;const{it:n}=t;if(!Ae.length)return e;if("new-line"!==n.type)return e;const i=t.content.last,s="new-line"!==i.type&&i.value?" ; ":"; ",o=me(t),r=`${s}${Ae.map(e=>c(e," #;")).join("; ")}${o}`;return Ae=[],r},ve={"array-end":"]","array-start":"[","block-end":"}","block-start":"{","call-end":")","call-start":"(","expression-end":")","expression-start":"(","index-end":"]","index-start":"[","interpolation-end":") . ","interpolation-start":" . (","parameter-end":")","parameter-start":"("},be=e=>{const t=e.content.list.map((t,n)=>{const i={...e,i:n,it:t};if(t.comment){const e=ye();Se([...e,...t.comment])}for(const e of Object.keys(Ce))if(t.type===e){const n=Ce[e],s="string"==typeof n?n.replace(/~/g,t.value):n(i);return we(s,i)}return we(t.value,i)}).join("");return t},Ce={"for-in":" in ","logical-operator":e=>{const{value:t}=e.it;return["&&","||"].includes(t)?` ${t} `:t},"new-line":me,async:"async ",await:"await ",class:"class ",compare:" ~ ",edge:e=>{const{content:t,i:n,it:i}=e,{value:s}=i;if("block-start"===s){const e=ve[s],i=t.at(n-1);return i?i.is("sign",":")?e:` ${e}`:e}if("call-start"===s){const e=t.at(n-1);if(!e)throw new Error(`ahk/internal: edge2: missing function name before call-start (token index: ${n})`);const i=c(e.value,"_");return i.startsWith(i[0].toLowerCase())?".Call(":"("}return ve[s]||s},for:"for ",identifier:e=>{const{value:t}=e.it;return e.cache.classNames.has(t)?t.replace(/[A-Z]/g,e=>String.fromCharCode(e.charCodeAt(0)+65248)):t},if:e=>{const{content:t,i:n,it:i}=e,{value:s}=i;if("case"===s)return"case ";if("default"===s)return"default";if("else"===s)return" else";if("if"===s){const e=t.at(n-1);return e?.is("if","else")?" if ":"if "}return"switch"===s?"switch ":""},math:" ~ ",negative:e=>{const{value:t}=e.it;return"-"===t?t:""},sign:e=>{const{value:t}=e.it;return[",",":"].includes(t)?_e(e):"="===t?" := ":"..."===t?"*":t},statement:e=>{const{value:t}=e.it;return"export"===t?"return ":"extends"===t?" extends ":["new","return","throw"].includes(t)?_e(e):e.it.value},super:"base",try:e=>{const{content:t,i:n,it:i}=e,{value:s}=i;if("catch"===s){const e=t.at(n+1);return e?.is("edge","block-start")?" catch":" catch "}return"finally"===s?" finally":"try"===s?"try":""},void:"",while:"while "},ke=async(e,t)=>{const n=l(e,{ast:!0}),i=new f,s=new w(i),o={cache:{global:new Set,classNames:new Set,identifiers:new Set},content:s,flag:{isChangeIndexUsed:!1},indent:0,options:t,token:void 0,scope:i,type:"",value:""};for(const e of n.tokens)o.token=e,o.token[2]={},o.type=e[0].toLowerCase(),o.value=e[1].toString(),S(o);return await ge(o),{ast:s.list,content:be(o).trim(),raw:n.tokens}},Me=new Map;let Ee="",We=0;const xe=()=>Me,De=e=>{Ee=e},Ie=()=>Ee,Le=(e=[],t=[])=>{if([...Me].forEach(n=>{const[i,{content:s,dependencies:o}]=n;o.length||(e.push(s),t.push(i),Me.delete(i))}),!Me.size)return e;for(const e of[...Me]){const[n,{dependencies:i}]=e;Me.set(n,{...e[1],dependencies:i.filter(e=>!t.includes(e))})}return Le(e,t)};var Fe=Object.freeze({__proto__:null,getCache:xe,getCacheSalt:Ie,getNextModuleId:()=>++We,setCacheSalt:De,sortModules:Le});const Ge=[".ahk",".coffee",".json",".yaml"],Te=async(e,s)=>{let o="",r=[],a="";if(s.includes(" from ")){const e=s.replace("import ","").split(" from ")[0].trim();if(a=s.split(" from ")[1].trim(),/^[\w$]+\s*,\s*{.+}$/.test(e)){const t=RegExp(/^([\w$]+)\s*,\s*{(.+)}$/).exec(e);t&&(o=t[1].trim(),r=t[2].split(",").map(e=>e.trim()).filter(Boolean))}else/^{.+}$/.test(e)?r=e.slice(1,-1).split(",").map(e=>e.trim()).filter(Boolean):e&&(o=e)}else a=s.replace("import ","").trim();const l=await(async(e,t)=>{const s=t.startsWith("."),o=Ge.some(e=>t.endsWith(e))?[t]:[`${t}.coffee`,`${t}/index.coffee`];o.forEach((t,n)=>{o[n]=s?`${e}/${t}`:`./node_modules/${t}`});const r=await n(o);if(r.length)return r[0];const a=await i(`./node_modules/${t}/package.json`);if(!a?.main)throw new Error(`ahk/file: package.json missing 'main' field for '${e}'`);const l=await n(`./node_modules/${t}/${a.main}`);if(!l.length)throw new Error(`ahk/file: resolved package main not found: '${e}'`);return l[0]})(t(e),c(a," /'\""));return{default:o,named:r,path:l}},Pe=async(e,t)=>{const n=[],i=xe(),s=Ie();for(const o of t.split("\n")){if(!o.startsWith("import ")){n.push(o);continue}const t=await Te(e,o),{default:r,named:a,path:l}=t;if(!i.has(l)){const{getNextModuleId:e}=await Promise.resolve().then(function(){return Fe});i.set(l,{content:"",dependencies:[],id:r||a.length?e():0})}const c=i.get(l)?.id??0;c&&(r&&n.push(`${r} = __${s}_module_${c}__.default`),a.length&&a.forEach(e=>{n.push(`${e} = __${s}_module_${c}__.${e.split(":")[0].trim()}`)}))}return n.join("\n")},$e=async(e,t,n,i,o,r)=>{const a=await Pe(e,t),{exportDefault:l,exportNamed:c,codeLines:u}=(e=>{const t=[],n=[],i=[],s=e.split("\n");let o=0;for(;o<s.length;){const e=s[o],r=e.trim();if(!r.startsWith("export ")){i.push(e),o++;continue}const a=/^export\s+default\s+(.+)/.exec(r);if(a){const n=RegExp(/^(\s*)/).exec(e)?.[1]??"",i=[a[1]];let r=o+1;for(;r<s.length&&(""===s[r].trim()||s[r].startsWith(`${n} `)||s[r].startsWith(`${n}\t`));)i.push(s[r].slice(n.length)),r++;t.push(i.join("\n").trim()),o=r;continue}const l=/^export\s*{(.+)}/.exec(r);l?(l[1].split(",").forEach(e=>{const t=e.trim();t&&n.push(t)}),o++):o++}return{exportDefault:t,exportNamed:n,codeLines:i}})(a),p=u.join("\n"),d=/^\s*class\s+\w+/m.test(p),h=l.length>0||c.length>0;if(d&&h)throw new Error(`ahk/file: module contains both class and export: '${e}'`);if(d&&!h)return void i.set(e,{...n,content:p,dependencies:r});const f=s(()=>{if(l.length&&c.length){const e=c.map(e=>e.includes(":")?e:`${e}: ${e}`).join(", ");return`return { default: ${l[0]}, ${e} }`}if(l.length)return`return { default: ${l[0]} }`;if(c.length){return`return { ${c.map(e=>e.includes(":")?e:`${e}: ${e}`).join(", ")} }`}return""});f&&u.push(f);const g=u.join("\n").split(/\n/u).map(e=>` ${e}`).join("\n");const _=[l.length||c.length?`__${o}_module_${n.id}__ = do ->`:"do ->",g].join("\n");i.set(e,{...n,content:_,dependencies:r})},Re=async(e,t,n,r)=>{if(t.content)return;const a=await i(e);if(!a)return void n.delete(e);const l=s(()=>a instanceof Buffer?p.decode(a,"utf8",{addBOM:!0}):"string"==typeof a?a:JSON.stringify(a)),c=o(e);let d=[];if(".coffee"===c&&(d=await(async(e,t)=>{const n=new Set;for(const i of t.split("\n")){if(!i.startsWith("import "))continue;const{path:t}=await Te(e,i);n.add(t)}return Array.from(n)})(e,l)),".ahk"!==c)if(".coffee"!==c){if(".json"!==c&&".yaml"!==c)throw new Error(`ahk/file: unsupported file type for transformation: '${e}'`);((e,t,n,i,s,o)=>{const r=u.stringify(JSON.parse(t)),a=`__${s}_module_${n.id}__ = ${r.includes("\n")?`\n${r}`:r}`;i.set(e,{...n,content:a,dependencies:o})})(e,l,t,n,r,d)}else await $e(e,l,t,n,r,d);else((e,t,n,i,s)=>{const o=["```",t,"```"].join("\n");i.set(e,{...n,content:o,dependencies:s})})(e,l,t,n,d)},je=async()=>{const e=xe(),t=Ie(),n=[...e].filter(([,e])=>!e.content);for(const[i,s]of n)await Re(i,s,e,t);[...e].some(([,e])=>!e.content)&&await je()},Ne=async(e,t)=>{let n=e;const s=".coffee";n.endsWith(s)||(n+=s);const o=await(async(e,t)=>{De(t);const n=await i(e);if(!n)throw new Error(`ahk/file: include failed, source file not found or empty: '${e}'`);const s=await Pe(e,n);return await je(),[...Le(),s].join("\n")})(n,t);if(!o)throw new Error(`ahk/file: include failed, source file not found or empty: '${n}'`);return o.replace(/\r/g,"")};const Oe=()=>{const e="0.0.68".split(".").map(Number);return[e[0],e[1],e[2]+1].join(".")},He=e=>{const t="string"!=typeof e?e.toString():e;console.log(),console.log(d.blue(((e,t,n=" ")=>{if(e.length>=t)return e;const i=t-e.length,s=Math.floor(i/2),o=i-s;return n.repeat(s)+e+n.repeat(o)})(t,80,"-")))},Be=e=>{let t=0;He(++t);for(let n=0;n<e.length;n++){const i=e[n];console.log(n,i),"new-line"===i.type&&He(++t)}He("eof")},Ke={ast:!1,coffeeAst:!1,comments:!1,metadata:!0,salt:"",save:!0,string:!1,verbose:!1},Ve=async(e,t={})=>{try{const n={...Ke,...t};return n.salt||(n.salt=Math.random().toString(32).split(".")[1].padStart(11,"0")),n.string?await qe(e,n):await ze(e,n)}catch(e){const t=e,n="-".repeat(t.message.length+4);return void console.log([n,t.message,n,t.stack,n].join("\n"))}},ze=async(e,t)=>{const i=e.endsWith(".coffee")?[e]:[e,`${e}.coffee`,`${e}/index.coffee`],[s]=(await n(i)).filter(e=>e.endsWith(".coffee"));if(!s)throw new Error(`ahk/file: invalid source '${e}'`);const o=await Ne(s,t.salt),l=await ke(o,t);return t.verbose&&(t.coffeeAst&&console.log(l.raw),Be(l.ast)),t.save&&await(async(e,t,n)=>{const{basename:i,dirname:s}=r(e),o=p.encode(n.metadata?[`; Generated by Coffee-AHK/${Oe()}`,t.content].join("\n"):t.content,"utf8",{addBOM:!0}).toString(),l=o.split("\n");for(let e=0;e<l.length;e++)if(l[e].length>200)throw new Error(`ahk/file: line too long at line ${e+1} (max 200 chars):\n${l[e].slice(0,80)}...`);await a(`${s}/${i}.ahk`,o),n.ast&&await a(`${s}/${i}.ast.json`,t.ast)})(s,l,t),l.content},qe=async(e,t)=>{const n=await ke(e,t);return t.verbose&&(t.coffeeAst&&console.log(n.raw),Be(n.ast)),n.content};export{Ve as default};