@xaendar/compiler 0.8.0 → 0.9.1

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.
Files changed (2) hide show
  1. package/dist/compiler.js +17 -14
  2. package/package.json +3 -3
package/dist/compiler.js CHANGED
@@ -1,16 +1,19 @@
1
- import{indent as P}from"@xaendar/common";var E=(l=>(l[l.Element=0]="Element",l[l.Text=1]="Text",l[l.Interpolation=2]="Interpolation",l[l.If=3]="If",l[l.Else=4]="Else",l[l.ElseIf=5]="ElseIf",l[l.For=6]="For",l[l.Switch=7]="Switch",l[l.Case=8]="Case",l[l.Import=9]="Import",l))(E||{});var x=class{constructor(t=[],r){this._parent=r;for(let o of t)typeof o=="string"?this._identifiers.set(o,"value"):this._identifiers.set(o[0],o[1])}_parent;_identifiers=new Map;_unresolvableIdentifiers=new Array;addIdentifier(t,r="value"){if(this.hasIdentifier(t))throw new Error(`Identifier "${t}" is already declared in this scope.`);this._identifiers.set(t,r)}addUnresolvableIdentifier(t){if(this.hasIdentifier(t))throw new Error(`Identifier "${t}" is already declared in this scope.`);this._unresolvableIdentifiers.push(t)}removeIdentifier(t){this._identifiers.delete(t)}removeUnresolvabledIdentifier(t){this._unresolvableIdentifiers=this._unresolvableIdentifiers.filter(r=>r!==t)}hasIdentifier(t){return this._identifiers.has(t)||(this._parent?.hasIdentifier(t)??!1)}getIdentifierKind(t){return this._identifiers.get(t)??this._parent?.getIdentifierKind(t)}hasUnresolvableIdentifier(t){return this._unresolvableIdentifiers.includes(t)||(this._parent?.hasUnresolvableIdentifier(t)??!1)}};import{indent as b}from"@xaendar/common";import{forEachChild as Ie,isIdentifier as ge,isPropertyAccessExpression as Lt,isPropertyAssignment as yt}from"typescript";var vt=new Set(["undefined","NaN","Infinity","globalThis","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape","Object","Function","Boolean","Symbol","Error","AggregateError","EvalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError","SuppressedError","InternalError","Number","BigInt","Math","Date","Temporal","String","RegExp","Array","TypedArray","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","BigInt64Array","BigUint64Array","Float16Array","Float32Array","Float64Array","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Atomics","JSON","WeakRef","FinalizationRegistry","Iterator","AsyncIterator","Promise","GeneratorFunction","AsyncGeneratorFunction","Generator","AsyncGenerator","AsyncFunction","DisposableStack","AsyncDisposableStack","Reflect","Proxy","Intl","WebAssembly","window","document","navigator","location","history","screen","console","performance","crypto","fetch","alert","confirm","prompt","setTimeout","setInterval","clearTimeout","clearInterval","requestAnimationFrame","cancelAnimationFrame","queueMicrotask","structuredClone","URL","URLSearchParams","FormData","Headers","Request","Response","AbortController","AbortSignal","CustomEvent","Event","EventTarget","MutationObserver","IntersectionObserver","ResizeObserver","PerformanceObserver","Worker","SharedWorker","ServiceWorker","Blob","File","FileReader","ReadableStream","WritableStream","TransformStream","TextEncoder","TextDecoder","ImageData","Canvas","Storage","localStorage","sessionStorage","indexedDB","WebSocket","XMLHttpRequest","HTMLElement","HTMLInputElement","HTMLButtonElement","HTMLFormElement","HTMLAnchorElement","HTMLImageElement","HTMLVideoElement","HTMLAudioElement","HTMLCanvasElement","HTMLSelectElement","HTMLTextAreaElement","HTMLDivElement","HTMLSpanElement","HTMLParagraphElement","HTMLHeadingElement","HTMLTableElement","HTMLTableRowElement","HTMLTableCellElement","HTMLUListElement","HTMLOListElement","HTMLLIElement","HTMLLabelElement","HTMLDialogElement","HTMLDetailsElement","HTMLSlotElement","HTMLTemplateElement","SVGElement","SVGSVGElement","Element","Node","NodeList","DocumentFragment","ShadowRoot","Document","Window"]),V="root";function d(e,t,r){return Ae(e,e,t,Ot(r))}function Ae(e,t,r,o){if(ge(e)&&ye(e,t)){let a=e.text;if(r?.hasUnresolvableIdentifier(a)||o.skipResolution)return a;if(r){let c=_t(a,r);if(c)return c}return o.resolver?`${o.resolver}.${a}`:a}if(!Le(e,t))return e.getText();let n=e.getSourceFile().text,i="",s=e.getStart();return Ie(e,a=>{i=`${i}${n.slice(s,a.getStart())}${Ae(a,e,r,o)}`,s=a.getEnd()}),`${i}${n.slice(s,e.getEnd())}`}function _t(e,t){if(t.hasIdentifier(e)){let r=t.getIdentifierKind(e),o=`context.get('${e}')`;return r==="signal"?`${o}()`:o}}function Le(e,t){if(ge(e)&&ye(e,t))return!0;let r=!1;return Ie(e,o=>{r||(r=Le(o,e))}),r}function ye(e,t){return!(Lt(t)&&t.name===e||yt(t)&&t.name===e||vt.has(e.text)||!e.text)}function ve(e,t,r){return pe(e.tagName,t,r)}function ae(e="text",t,r){return pe(e,t,r)}function R(e,t,r){return pe(e,t,r)}function pe(e,t,r){return(t!==V?`${t}__${e}${r}`:`${e}${r}`).replace(/-/g,"_")}function Ot(e){return{skipResolution:e?.skipResolution??!1,resolver:e?.resolver??"this"}}function _e(e,t,r,o,n){let i=Rt(e.attributes,o),s=St(e.events,o),a=ve(e,t,r),c=e.tagName,m={code:[],functionsToProcess:new Map};switch(c){case"svg":m.code.push("context.createElement = createSVGElement");break;case"math":m.code.push("context.createElement = createMATHMLElement")}switch(m.code.push(`const ${a} = _renderElement(${t}, context, ${n}, '${c}',`),i.length?m.code.push(...b(["[",...b(i),"],"])):m.code[m.code.length-1]=`${m.code[m.code.length-1]} [],`,s.length?m.code.push(...b(["[",...b(s),"]"]),");"):m.code[m.code.length-1]=`${m.code[m.code.length-1]} []);`,c){case"svg":case"math":m.code.push("context.createElement = createElement")}return e.children.length&&(m.functionsToProcess.set(`${a}Children`,{fn:{node:e,parentNode:a,context:o,precode:wt(c)},args:[a,"parentContext"]}),m.code.push(`this.${a}Children(${a}, context);`)),m}function Rt(e,t){return e?.map(({name:r,value:o})=>{let n=typeof o=="string";return`{ name: '${r}', value: () => ${n?`'${o}'`:d(o.expression,t)}, literal: ${n} },`})}function St(e,t){t.addUnresolvableIdentifier("$event");let r=e.map(o=>{let n=!1,i=o.parameters.map(a=>{let c=d(a,t);return!n&&c==="$event"?(n=!0,`($event) => ${c},`):`() => ${c},`}),s=["{",...b([`name: '${o.name}',`,`handler: '${o.handler}',`,"parameters: ["])];return i.length?s.push(...b([...b(i),"]"]),"},"):(s[s.length-1]=`${s[s.length-1]}]`,s.push("},")),s}).flat();return t.removeIdentifier("$event"),r}function wt(e){switch(e){case"svg":return"context.createElement = createSVGElement;";case"math":return"context.createElement = createMATHMLElement;";default:return""}}function Oe(e,t,r,o){let n={code:[],functionsToProcess:new Map},i=e.iterableSource,s=o.hasIdentifier(i)?i:`this.${i}`,a=ae("items",t,r),c=ae("i",t,r),m=U(e,"$index"),l=U(e,"$first"),h=U(e,"$last"),k=U(e,"$even"),I=U(e,"$odd"),g=new x([e.itemAlias,[m,"signal"],[l,"signal"],[h,"signal"],[k,"signal"],[I,"signal"]],o),O=R("for",t,r);return n.functionsToProcess.set(O,{fn:{precode:`const { vars, update } = _iterationVariables(context, ${a}, ${c}, '${e.itemAlias}', {
1
+ import{indent as P,slice as bt}from"@xaendar/common";var h=(f=>(f[f.Element=0]="Element",f[f.Attribute=1]="Attribute",f[f.Event=2]="Event",f[f.Text=3]="Text",f[f.Interpolation=4]="Interpolation",f[f.If=5]="If",f[f.Else=6]="Else",f[f.ElseIf=7]="ElseIf",f[f.For=8]="For",f[f.Switch=9]="Switch",f[f.Case=10]="Case",f[f.Import=11]="Import",f))(h||{});var C=class{constructor(r=[],t){this.parent=t;for(let n of r)typeof n=="string"?this._identifiers.set(n,"value"):this._identifiers.set(n[0],n[1])}parent;_identifiers=new Map;_unresolvableIdentifiers=new Array;addIdentifier(r,t="value"){if(this.hasIdentifier(r))throw new Error(`Identifier "${r}" is already declared in this scope.`);this._identifiers.set(r,t)}addUnresolvableIdentifier(r){if(this.hasIdentifier(r))throw new Error(`Identifier "${r}" is already declared in this scope.`);this._unresolvableIdentifiers.push(r)}removeIdentifier(r){this._identifiers.delete(r)}removeUnresolvabledIdentifier(r){this._unresolvableIdentifiers=this._unresolvableIdentifiers.filter(t=>t!==r)}hasIdentifier(r){return this._identifiers.has(r)||(this.parent?.hasIdentifier(r)??!1)}getIdentifierKind(r){return this._identifiers.get(r)??this.parent?.getIdentifierKind(r)}hasUnresolvableIdentifier(r){return this._unresolvableIdentifiers.includes(r)||(this.parent?.hasUnresolvableIdentifier(r)??!1)}};import{indent as $}from"@xaendar/common";import{forEachChild as ge,isIdentifier as Ae,isPropertyAccessExpression as yt,isPropertyAssignment as Lt}from"typescript";var vt=new Set(["undefined","NaN","Infinity","globalThis","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape","Object","Function","Boolean","Symbol","Error","AggregateError","EvalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError","SuppressedError","InternalError","Number","BigInt","Math","Date","Temporal","String","RegExp","Array","TypedArray","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","BigInt64Array","BigUint64Array","Float16Array","Float32Array","Float64Array","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Atomics","JSON","WeakRef","FinalizationRegistry","Iterator","AsyncIterator","Promise","GeneratorFunction","AsyncGeneratorFunction","Generator","AsyncGenerator","AsyncFunction","DisposableStack","AsyncDisposableStack","Reflect","Proxy","Intl","WebAssembly","window","document","navigator","location","history","screen","console","performance","crypto","fetch","alert","confirm","prompt","setTimeout","setInterval","clearTimeout","clearInterval","requestAnimationFrame","cancelAnimationFrame","queueMicrotask","structuredClone","URL","URLSearchParams","FormData","Headers","Request","Response","AbortController","AbortSignal","CustomEvent","Event","EventTarget","MutationObserver","IntersectionObserver","ResizeObserver","PerformanceObserver","Worker","SharedWorker","ServiceWorker","Blob","File","FileReader","ReadableStream","WritableStream","TransformStream","TextEncoder","TextDecoder","ImageData","Canvas","Storage","localStorage","sessionStorage","indexedDB","WebSocket","XMLHttpRequest","HTMLElement","HTMLInputElement","HTMLButtonElement","HTMLFormElement","HTMLAnchorElement","HTMLImageElement","HTMLVideoElement","HTMLAudioElement","HTMLCanvasElement","HTMLSelectElement","HTMLTextAreaElement","HTMLDivElement","HTMLSpanElement","HTMLParagraphElement","HTMLHeadingElement","HTMLTableElement","HTMLTableRowElement","HTMLTableCellElement","HTMLUListElement","HTMLOListElement","HTMLLIElement","HTMLLabelElement","HTMLDialogElement","HTMLDetailsElement","HTMLSlotElement","HTMLTemplateElement","SVGElement","SVGSVGElement","Element","Node","NodeList","DocumentFragment","ShadowRoot","Document","Window"]),U="root";function T(e,r,t){return Ie(e,e,r,St(t))}function Ie(e,r,t,n){if(Ae(e)&&Le(e,r)){let a=e.text;if(t?.hasUnresolvableIdentifier(a)||n.skipResolution)return a;if(t){let c=_t(a,t);if(c)return c}return n.resolver?`${n.resolver}.${a}`:a}if(!ye(e,r))return e.getText();let o=e.getSourceFile().text,i="",s=e.getStart();return ge(e,a=>{i=`${i}${o.slice(s,a.getStart())}${Ie(a,e,t,n)}`,s=a.getEnd()}),`${i}${o.slice(s,e.getEnd())}`}function _t(e,r){if(r.hasIdentifier(e)){let t=r.getIdentifierKind(e),n=`context.get('${e}')`;return t==="signal"?`${n}()`:n}}function ye(e,r){if(Ae(e)&&Le(e,r))return!0;let t=!1;return ge(e,n=>{t||(t=ye(n,e))}),t}function Le(e,r){return!(yt(r)&&r.name===e||Lt(r)&&r.name===e||vt.has(e.text)||!e.text)}function ve(e,r,t){return ce(e.tagName,r,t)}function pe(e="text",r,t){return ce(e,r,t)}function O(e,r,t){return ce(e,r,t)}function ce(e,r,t){return(r!==U?`${r}__${e}${t}`:`${e}${t}`).replace(/-/g,"_")}function St(e){return{skipResolution:e?.skipResolution??!1,resolver:e?.resolver??"this"}}function _e(e,r,t,n,o){let i=Ot(e.attributes,n),s=wt(e.events,n),a=ve(e,r,t),c=e.tagName,m={code:[],functionsToProcess:new Map};switch(c){case"svg":m.code.push("context.createElement = createSVGElement");break;case"math":m.code.push("context.createElement = createMATHMLElement")}switch(m.code.push(`const ${a} = _renderElement(${r}, context, ${o}, '${c}',`),i.length?m.code.push(...$(["[",...$(i),"],"])):m.code[m.code.length-1]=`${m.code[m.code.length-1]} [],`,s.length?m.code.push(...$(["[",...$(s),"]"]),");"):m.code[m.code.length-1]=`${m.code[m.code.length-1]} []);`,c){case"svg":case"math":m.code.push("context.createElement = createElement")}return e.children.length&&(m.functionsToProcess.set(`${a}Children`,{fn:{node:e,parentNode:a,context:n,precode:Rt(c)},args:[a,"parentContext"]}),m.code.push(`this.${a}Children(${a}, context);`)),m}function Ot(e,r){return e?.map(({name:t,value:n})=>{let o=typeof n=="string";return`{ name: '${t}', value: () => ${o?`'${n}'`:T(n.expression,r)}, literal: ${o} },`})}function wt(e,r){r.addUnresolvableIdentifier("$event");let t=e.map(n=>{let o=!1,i=n.parameters.map(a=>{let c=T(a,r);return!o&&c==="$event"?(o=!0,`($event) => ${c},`):`() => ${c},`}),s=["{",...$([`name: '${n.name}',`,`handler: '${n.handler}',`,"parameters: ["])];return i.length?s.push(...$([...$(i),"]"]),"},"):(s[s.length-1]=`${s[s.length-1]}]`,s.push("},")),s}).flat();return r.removeIdentifier("$event"),t}function Rt(e){switch(e){case"svg":return"context.createElement = createSVGElement;";case"math":return"context.createElement = createMATHMLElement;";default:return""}}function Se(e,r,t,n){let o={code:[],functionsToProcess:new Map},i=e.iterableSource,s=n.hasIdentifier(i)?i:`this.${i}`,a=pe("items",r,t),c=pe("i",r,t),m=V(e,"$index"),d=V(e,"$first"),x=V(e,"$last"),f=V(e,"$even"),A=V(e,"$odd"),I=new C([e.itemAlias,[m,"signal"],[d,"signal"],[x,"signal"],[f,"signal"],[A,"signal"]],n),S=O("for",r,t);return o.functionsToProcess.set(S,{fn:{precode:`const { vars, update } = _iterationVariables(context, ${a}, ${c}, '${e.itemAlias}', {
2
2
  $index: '${m}',
3
- $first: '${l}',
4
- $last: '${h}',
5
- $even: '${k}',
6
- $odd: '${I}'
3
+ $first: '${d}',
4
+ $last: '${x}',
5
+ $even: '${f}',
6
+ $odd: '${A}'
7
7
  });
8
- const { ${e.itemAlias}, ${m}, ${l}, ${h}, ${k}, ${I} } = vars;`,node:e,parentNode:O,context:g,anchor:"anchor",isForBody:!0},args:[O,"parentContext",a,c,"anchor"]}),n.code.push(`_for(${t}, context, () => ${s}, ${e.itemAlias} => ${d(e.trackExpression,g,{skipResolution:!0})}, this.${O}.bind(this));`),n}function U(e,t){return e.implicitAliases.get(t)??t}import{indent as M}from"@xaendar/common";function Re(e,t,r,o){let n=new x([],o),i={code:[],functionsToProcess:new Map};i.code.push(`_if(${t}, context, [`);let s=R("if",t,r);i.code.push(...M(["{",...M([`condition: () => ${d(e.conditionNode,o)},`,`block: this.${s}.bind(this)`]),"},"])),i.functionsToProcess.set(s,{fn:{node:e,parentNode:s,context:n,anchor:"anchor"},args:[s,"parentContext","anchor"]});let a=e.alternate,c=0;for(;a?.type===5;){let m=new x([],o),l=R("elseIf",t,`${r}_${c}`),h=a.conditionNode;i.code.push(...M(["{",...M([`condition: () => ${d(h,o)},`,`block: this.${l}.bind(this)`]),"},"])),i.functionsToProcess.set(l,{fn:{node:a,parentNode:t,context:m,anchor:"anchor"},args:[t,"parentContext","anchor"]}),a=a.alternate,c++}if(a){let m=new x([],o),l=R("else",t,r);i.code.push(...M(["{",...M([`block: this.${l}.bind(this)`]),"},"])),i.functionsToProcess.set(l,{fn:{node:a,parentNode:t,context:m,anchor:"anchor"},args:[t,"parentContext","anchor"]})}return i.code.push("]);"),i}import{indent as Se}from"@xaendar/common";function we(e,t,r,o){let n={code:[],functionsToProcess:new Map};return n.code.push(`_switch(${t}, context, () => ${d(e.expression,o)}, [`),e.children.forEach((i,s)=>{let a=new x([],o),c=i.condition?R("case",t,`${r}_${s}`):R("default",t,r);n.functionsToProcess.set(c,{fn:{node:i,parentNode:c,context:a},args:[c,"parentContext","anchor"]});let m=`this.${c}.bind(this)`;n.code.push(...Se(["{",...Se([`condition: ${i.condition?`[${i.condition.join(", ")}]`:"null"},`,`block: ${m}`]),"},"]))}),n.code.push("])"),n}function ce(e,t,r,o){return{code:[`${e.type===1?`_renderLiteralText(${t}, context, '${e.value}');`:`_renderText(${t}, context, () => ${d(e.expression,o)});`}`]}}function Fe(e,t,r,o){}var Q=class{constructor(t){this._ast=t}_ast;_nodeToProcess=new Map;_states={1:ce,2:ce,0:_e,3:Re,6:Oe,7:we,9:Fe};generate(t){this._nodeToProcess.clear();let r=new x,o=["_render() {",...P([`const ${V} = this._root;`,"const context = new Context(this, { createElement: document.createElement.bind(document), get: () => undefined });"])];t&&o.push(P(`${V}.adoptedStyleSheets = [${t}];`));for(let n=0;n<this._ast.length;n++){let i=this._processNode(this._ast[n],V,n.toString(),r,null);if(i){let{code:s,functionsToProcess:a}=i;a?.forEach((c,m)=>this._nodeToProcess.set(m,c)),o.push(...P(s))}}o.push(...P(["return context;"]),"}");for(let[n,i]of this._nodeToProcess.entries()){let{node:s,parentNode:a,context:c,precode:m,anchor:l}=i.fn;o.push(`
9
- ${n}(${i.args?.join(", ")}) {`,...P(["const context = new Context(this, parentContext);"])),m&&o.push(P(m)),o.push(...P([...s.children.map((h,k)=>{let I=this._processNode(h,a,k.toString(),c,l??null);if(I){let{code:g,functionsToProcess:O}=I;return O?.forEach((X,z)=>this._nodeToProcess.set(z,X)),g}return""}).flat(),i.fn.isForBody?"return { context, update };":"return context;"]),"}")}return o.join(`
10
- `)}_processNode(t,r,o,n,i){let s=this._states[t.type];if(!s)throw new Error(`[Generator] No transition function for token type ${E[t.type]}`);return s(t,r,o,n,i)}};import{Stack as Mt}from"@xaendar/common";var u=(f=>(f[f.TEXT=0]="TEXT",f[f.TAG_OPEN_NAME=1]="TAG_OPEN_NAME",f[f.TAG_SELF_CLOSE=2]="TAG_SELF_CLOSE",f[f.TAG_OPEN_END=3]="TAG_OPEN_END",f[f.TAG_CLOSE_NAME=4]="TAG_CLOSE_NAME",f[f.ATTRIBUTE=5]="ATTRIBUTE",f[f.ATTRIBUTE_VALUE=6]="ATTRIBUTE_VALUE",f[f.EVENT=7]="EVENT",f[f.EVENT_PAREMETER=8]="EVENT_PAREMETER",f[f.INTERPOLATION_LITERAL=9]="INTERPOLATION_LITERAL",f[f.INTERPOLATION_EXPRESSION=10]="INTERPOLATION_EXPRESSION",f[f.IF=11]="IF",f[f.FOR=12]="FOR",f[f.ELSE=13]="ELSE",f[f.ELSE_IF=14]="ELSE_IF",f[f.SWITCH=15]="SWITCH",f[f.CASE=16]="CASE",f[f.DEFAULT=17]="DEFAULT",f[f.CONDITION=18]="CONDITION",f[f.BLOCK_OPEN=19]="BLOCK_OPEN",f[f.BLOCK_CLOSE=20]="BLOCK_CLOSE",f[f.IMPORT=21]="IMPORT",f[f.IMPORT_PATH=22]="IMPORT_PATH",f[f.EOF=23]="EOF",f))(u||{});function be(e,t){let r=!0,o="",n;for(;r;)e.peek()===34?(e.advance(),r=!1,n={state:"tag-body",tokens:[{type:6,parts:[o]}],popState:!0}):(e.advance(),o=`${o}${e.currentChar.value}`);return n}function Pe(e,t){let r=!0,o="",n;for(;r;)switch(e.peek()){case 32:e.advance(),r=!1,n={state:"tag-body",tokens:[{type:5,parts:[o]}]};break;case 61:if(e.advance(),e.peek()!==34){let{row:s,column:a}=e.position;throw new Error(`Attribute value must start with double quotes '"'.Row ${s} Col ${a}`)}e.advance(),r=!1,n={state:e.peek()===123?"interpolation":"attribute-value",pushState:!0,tokens:[{type:5,parts:[o]}]};break;default:e.advance(),o=`${o}${e.currentChar.value}`}return n}function j(e,t){if(e.skipSpaces(),e.peek()!==40)throw new Error(`Expected '(' but got '${String.fromCharCode(e.peek())}' at row ${e.position.row}, col ${e.position.column}`);e.advance();let r="",o=1;for(;o>0;)switch(e.peek()){case 40:o++,r=me(e,r);break;case 41:if(o--,!o){e.advance();break}r=me(e,r);break;default:r=me(e,r)}return r}function me(e,t){return e.advance(),`${t}${e.currentChar.value}`}function $e(e,t){let r=j(e,t);return e.skipSpaces(),{state:e.peekMatch("@case")?"flow-control":"flow-control-block",tokens:[{type:18,parts:[r]}],popState:!0}}function Me(e,t){return{state:"flow-control-block",tokens:[{type:18,parts:[j(e,t)]}],popState:!0}}function Be(e,t){let r=!0,o="",n="",i={state:"tag-body",tokens:[]};for(;r;)switch(e.peek()){case 91:case 93:case 123:case 125:case 34:case 39:case 40:o=le(e,o),n?(n===e.currentChar.value||n==="["&&e.currentChar.value==="]"||n==="{"&&e.currentChar.value==="}")&&(n=""):n=e.currentChar.value;break;case 44:n?o=le(e,o):(i.tokens.push({type:8,parts:[o]}),e.advance(),e.skipSpaces(),o="");break;case 41:e.advance(),n||(i.tokens.push({type:8,parts:[o]}),r=!1);default:o=le(e,o)}return i}function le(e,t){return e.advance(),`${t}${e.currentChar.value}`}function De(e,t){let r=!0,o="",n;for(e.advance();r;)switch(e.peek()){case 32:case 47:case 62:n={state:"tag-body"},r=!1;break;case 40:let i="parameter";e.advance(),e.skipSpaces(),e.peek()===41&&(i="tag-body",e.advance(2)),n={state:i,tokens:[{type:7,parts:[o]}]},r=!1;break;default:e.advance(),o=`${o}${e.currentChar.value}`}return n}function Ge(e,t){let r;return e.advance(),e.peekMatch("for ")?(e.advance(4),r={state:"flow-control-condition",tokens:[{type:12}],pushState:!0}):e.peekMatch("if ")?(e.advance(2),r={state:"flow-control-condition",tokens:[{type:11}],pushState:!0}):e.peekMatch("else if ")?(e.advance(8),r={state:"flow-control-condition",tokens:[{type:14}],pushState:!0}):e.peekMatch("else ")?(e.advance(5),r={state:"flow-control-block",tokens:[{type:13}]}):e.peekMatch("switch ")?(e.advance(7),r={state:"flow-control-condition",tokens:[{type:15}],pushState:!0}):e.peekMatch("case ")?(e.advance(5),r={state:"case-flow-control-condition",tokens:[{type:16}],pushState:!0}):e.peekMatch("default ")?(e.advance(8),r={state:"flow-control-block",tokens:[{type:17}]}):e.peekMatch("import ")&&(e.advance(7),r={state:"import"}),r}function Ve(e,t){if(e.skipSpaces(),e.peek()!==123)throw new Error(`Expected '{' but got '${String.fromCharCode(e.peek())}' at row ${e.position.row}, col ${e.position.column}`);return e.advance(),{state:"text",tokens:[{type:19}],pushState:!0}}function Ue(e,t){let r=!0,o="",n,i=!1;if(e.skipSpaces(),!e.peekMatch("from"))throw new Error(`Expected from keywork after list of imports at ${e.currentChar}`);switch(e.advance(4),e.skipSpaces(),e.advance(),e.currentChar.code){case 39:i=!0;break;case 34:break;default:throw new Error(`Import statement must start with ' or ".
11
- Found character ${e.currentChar.value} at ${e.formattedPosition}`)}let s=i?39:34;for(;r;)e.peek()===s?(e.advance(),r=!1,n={state:"text",tokens:[{type:22,parts:[o]}]}):(e.advance(),o=`${o}${e.currentChar.value}`);return n}function Ke(e,t){let r=!0,o="",n={state:"import-path",tokens:[]};if(e.skipSpaces(),e.advance(),e.currentChar.code!==123)throw new Error(`Expected { after @import at ${e.formattedPosition}`);for(;r;)switch(e.peek()){case 32:e.skipSpaces(),o&&e.peek()!==44&&e.peek()!==125&&(o=`${o} `);break;case 44:He(n,e,o),o="";break;case 125:He(n,e,o),r=!1;break;default:e.advance(),o=`${o}${e.currentChar.value}`}return n}function He(e,t,r){t.advance(),e.tokens.push({type:21,parts:[r]})}function We(e,t){let r=!0,o="",n=1,i;for(;r;)switch(e.peek()){case 123:n++,o=fe(e,o);break;case 125:if(n--,n===0){e.advance(),o=o.trimEnd();let s=t.history.pop(),a;switch(s){case"attribute":if(e.peek()!==34)throw new Error(`Interpolation must end with double quotes '"' Found ${String.fromCharCode(e.peek())} at ${e.formattedPosition}`);e.advance(),a="tag-body";break;case"text":a="text"}i={state:a,tokens:[{type:10,parts:[o]}],popState:!0},r=!1}else o=fe(e,o);break;default:o=fe(e,o)}return i}function fe(e,t){return e.advance(1),`${t}${e.currentChar.value}`}function Xe(e,t){let r=!0,o="`",n;for(e.advance();r;)switch(e.peek()){case 96:if(o=qe(e,o),e.peek()===125){e.advance();let i=t.history.pop(),s;switch(i){case"attribute":if(e.peek()!==34)throw new Error(`Attribute interpolation expression must end with double quotes at ${e.formattedPosition}`);e.advance(),s="tag-body";break;case"text":s="text"}n={state:s,tokens:[{type:9,parts:[o]}],popState:!0},r=!1}else o=`${o}${e.currentChar.value}`;break;default:o=qe(e,o)}return n}function qe(e,t){return e.advance(),`${t}${e.currentChar.value}`}function ze(e,t){return e.advance(),e.skipSpaces(),e.peek()===96?{state:"interpolation-literal"}:{state:"interpolation-expression"}}function Qe(e,t){let r=!0,o;for(;r;)switch(e.peek()){case 64:o={state:"event"},r=!1;break;case 32:e.skipSpaces();break;case 62:case 47:o={state:"tag-open-end"},r=!1;break;default:o={state:"attribute"},r=!1}return o}function je(e,t){let r=!0,o="",n;for(e.advance(2),e.skipSpaces();r;)switch(e.peek()){case 62:e.advance(),n={state:"text",tokens:[{type:4,parts:[o]}]},r=!1;break;case 32:throw new Error("Tag Close Name cannot contains spaces");default:e.advance(),o=`${o}${e.currentChar.value}`}return n}function Ye(e,t){let r;if(e.peek()===62)e.advance(),r={state:"text",tokens:[{type:3,parts:[]}]};else{e.advance();let o=e.peek();if(o===62)e.advance(),r={state:"text",tokens:[{type:2,parts:[]}]};else throw new Error(`Unexpected character ${o} for closing tag.
12
- Expected />
13
- Read of /${String.fromCharCode(o)} at ${e.formattedPosition}`)}return r}function Ze(e,t){let r=!0,o="",n;for(e.advance(),e.skipSpaces();r;)switch(e.peek()){case 32:case 47:case 62:n={state:"tag-body",tokens:[{type:1,parts:[o]}]},r=!1;break;default:e.advance(),o=`${o}${e.currentChar.value}`}return n}function Je(e){return/\S/.test(e)}function et(e,t){let r=!0,o="",n;for(;r;)switch(e.peek()){case 60:n={state:e.peek(1,{offset:1})===47?"tag-close":"tag-open-name"},r=!1;break;case 123:n={state:"interpolation",pushState:!0},r=!1;break;case 64:n={state:"flow-control"},r=!1;break;case 125:t.history[t.history.length-1]==="flow-control-block"?(e.advance(),n={state:"text",tokens:[{type:20}],popState:!0},r=!1):(e.advance(),o=`${o}${e.currentChar.value}`);break;case 10:case 13:e.advance();break;default:e.advance(),o=`${o}${e.currentChar.value}`}return n.tokens??=Je(o)?[{type:0,parts:[o]}]:void 0,n}var re=class{constructor(t){this.input=t}input;_currentChar={code:0,index:-1,value:""};get currentChar(){return this._currentChar}_peekCache=new Map;_position={row:0,column:0};get position(){return this._position}get formattedPosition(){return`[Ln ${this._position.row}, Col ${this._position.column}]`}advance(t=1){if(t<1)throw new Error(`${t} is not a valid value. Please enter a number equal or greater than 1`);let r=this._currentChar.index+t;r>=this.input.length?(this._currentChar.code=0,this._currentChar.index=-1,this._currentChar.value="",this.throwEOFError()):([10,13].includes(this._currentChar.code)?(this._position.row++,this._position.column=0):this._position.column++,this._currentChar.index=r,this._currentChar.value=this.input[r],this._currentChar.code=this.input.charCodeAt(r))}peekMatch(t,r){if(typeof t=="string"){let i=this.peek(t.length);for(let s=0;s<t.length;s++)if(i[s]!==t.charCodeAt(s))return!1;return!0}let o=this._currentChar.index+1,n=this.input.slice(o,o+r);return t.test(n)}peek(t,r){let o=this._peekCache,n=typeof t=="number"?t:1,i=(typeof t=="object"?t:r)?.offset??0;return n===1?this.peekOneChar(this._currentChar.index+i+1,o):this.peekMany(n+i,o)}skipSpaces(){for(;this.peek()===32||this.peek()===10||this.peek()===13;)this.advance()}peekMany(t,r){let o=new Array,n=this._currentChar.index+1;for(let i=n;i<n+t;i++)o.push(this.peekOneChar(i,r));return o}peekOneChar(t,r){if(r.has(t))return r.get(t);t>=this.input.length&&this.throwEOFError();let o=this.input.charCodeAt(t);return r.set(t,o),o}throwEOFError(){throw new Error("",{cause:0})}};var oe=class{constructor(t){this.input=t;this._cursor=new re(this.input)}input;_cursor;_state="text";_stack=new Mt;_tokens=new Array;_states={text:et,"tag-open-name":Ze,"tag-body":Qe,"tag-open-end":Ye,"tag-close":je,attribute:Pe,"attribute-value":be,event:De,parameter:Be,"flow-control":Ge,"flow-control-condition":Me,"case-flow-control-condition":$e,"flow-control-block":Ve,interpolation:ze,"interpolation-expression":We,"interpolation-literal":Xe,import:Ke,"import-path":Ue};tokenize(){let t=!1;for(;!t;)try{let r=this._states[this._state],{state:o,tokens:n,popState:i,pushState:s}=r(this._cursor,{history:this._stack.values,tokens:[...this._tokens]});n?.length&&this._tokens.push(...n),s&&this._stack.push(this._state),i&&this._stack.pop(),this._state=o}catch(r){if(r.cause===0)t=!0;else throw console.log(`Something went wrong while computing state ${this._state} at ${this._cursor.formattedPosition}`),r}return this._tokens}};var ne=class{constructor(t){this._tokens=t}_tokens;_currentToken={value:{type:23},index:-1};getCurrentToken(){return this._currentToken}advance(t=1){if(t<1)throw new Error(`${t} is not a valid value. Please enter a number equal or greater than 1`);let r=this._currentToken.index+t;r>=this._tokens.length?(this._currentToken.value={type:23},this._currentToken.index=-1):(this._currentToken.index=r,this._currentToken.value=this._tokens[r])}peek(t,r){let o=typeof t=="number"?t:1,n=(typeof t=="object"?t:r)?.offset??0;return o===1?this.peekOneToken(this._currentToken.index+n+1):this.peekMany(o+n)}peekMany(t){let r=new Array,o=this._currentToken.index+1;for(let n=o;n<o+t;n++)r.push(this.peekOneToken(n));return r}peekOneToken(t){return t<this._tokens.length?this._tokens[t]:{type:23}}};import{ScriptTarget as Bt,SyntaxKind as p,createSourceFile as Dt,forEachChild as Gt}from"typescript";function y(e){let t="const x = ",n=Dt("expression.ts",`${t}${e}`,Bt.ESNext,!0).statements[0].declarationList.declarations[0].initializer,i=new Array;if(tt(n,t.length,i),i.length)throw new Error(i.reduce((s,a)=>`${s}${a.message}
14
- `,""));return{node:n}}function tt(e,t,r){if(!Vt(e))throw new Error(Ut(e));if(Gt(e,o=>tt(o,t,r)),r.length)throw new Error(r[0].message)}function Vt(e){switch(e.kind){case p.StringLiteral:case p.NumericLiteral:case p.BigIntLiteral:case p.TrueKeyword:case p.FalseKeyword:case p.NullKeyword:case p.UndefinedKeyword:case p.Identifier:case p.PropertyAccessExpression:case p.ElementAccessExpression:case p.CallExpression:case p.BinaryExpression:case p.EqualsEqualsToken:case p.EqualsEqualsEqualsToken:case p.ExclamationEqualsToken:case p.ExclamationEqualsEqualsToken:case p.LessThanToken:case p.LessThanEqualsToken:case p.GreaterThanToken:case p.GreaterThanEqualsToken:case p.PlusToken:case p.MinusToken:case p.AsteriskToken:case p.SlashToken:case p.PercentToken:case p.AsteriskAsteriskToken:case p.AmpersandAmpersandToken:case p.BarBarToken:case p.QuestionQuestionToken:case p.QuestionDotToken:case p.QuestionToken:case p.ColonToken:case p.AmpersandToken:case p.BarToken:case p.CaretToken:case p.LessThanLessThanToken:case p.GreaterThanGreaterThanToken:case p.GreaterThanGreaterThanGreaterThanToken:case p.InstanceOfKeyword:case p.InKeyword:case p.PrefixUnaryExpression:case p.PostfixUnaryExpression:case p.TypeOfExpression:case p.VoidExpression:case p.ConditionalExpression:case p.ParenthesizedExpression:case p.TemplateExpression:case p.NoSubstitutionTemplateLiteral:case p.TemplateHead:case p.TemplateMiddle:case p.TemplateTail:case p.TemplateSpan:case p.ArrayLiteralExpression:case p.ObjectLiteralExpression:case p.PropertyAssignment:case p.ShorthandPropertyAssignment:case p.SpreadAssignment:case p.SpreadElement:case p.TaggedTemplateExpression:case p.SyntaxList:return!0;default:return!1}}function Ut(e){switch(e.kind){case p.AwaitExpression:return"'await' is not allowed inside template expressions.";case p.YieldExpression:return"'yield' is not allowed inside template expressions.";case p.NewExpression:return"'new' is not allowed inside template expressions.";case p.ArrowFunction:case p.FunctionExpression:return"Function expressions are not allowed inside template expressions.";case p.BinaryExpression:return Ht(e.operatorToken.kind)?"Assignments are not allowed inside template expressions. Use @const to declare local template variables instead.":`'${p[e.kind]}' is not allowed inside template expressions.`;default:return`'${p[e.kind]}' is not allowed inside template expressions.`}}function Ht(e){return e>=p.FirstAssignment&&e<=p.LastAssignment}function K(e,t,r){return e.advance(),{type:2,expression:y(r.parts[0]).node}}function rt(e,t,r){e.advance();let o=r.parts[0],n=e.peek();if(n.type===5||n.type===4||n.type===7)return{name:o,value:"true"};if(n.type===10||n.type===9)return{name:o,value:K(e,t,n)};if(n.type!==6)throw new Error(`[Parser] Attribute value missing for ${o} in: ${o}`);return e.advance(),{name:o,value:n.parts[0]}}function ot(e,t,r){e.advance();let o=r.parts[0],[n,i]=o.split("=");if(!n||!i)throw new Error(`[Parser] Invalid event format: ${o}`);let s=new Array;for(;e.peek().type===8;)e.advance(),s.push(y(e.getCurrentToken().value.parts[0]).node);return{name:n,handler:i.replace(/^[""]|[""]$/g,""),parameters:s}}function nt(e,t,r){e.advance();let o=r.parts[0],n=new Array,i=new Array,s=!0;for(;s;){let c=e.peek();switch(c.type){case 5:n.push(rt(e,t,c));break;case 7:i.push(ot(e,t,c));break;default:s=!1}}if(e.peek().type===3&&e.advance(),e.peek().type===2)return e.advance(),{type:0,tagName:o,attributes:n,events:i,children:[]};let a=new Array;for(;!Kt(e,o);){let c=t();c&&a.push(c)}return e.advance(),{type:0,tagName:o,attributes:n,events:i,children:a}}function Kt(e,t){let r=e.peek();return r.type===4&&r.parts[0]===t}import{createSourceFile as Wt,isExpressionStatement as qt,isIdentifier as Xt,ScriptTarget as zt}from"typescript";function w(e,t){let r=new Array;for(;e.peek().type!==20;){let o=t();o&&r.push(o)}return e.advance(),r}function it(e,t,r){e.advance();let o=e.peek();if(o.type!==18)throw new Error(`[Parser] Expected CONDITION after FOR, got ${u[o.type]}`);let n=Qt(o.parts[0],0);e.advance(2);let i=w(e,t);return{type:6,...n,children:i}}function Qt(e,t){let r=Yt(e);if(r.length<2)throw new Error('[Parser] @for requires at least "item of iterable; track expr".');let o=r[0].trim(),n=o.indexOf(" of ");if(n===-1)throw new Error('[Parser] @for expression must be in the form "item of iterable".');let i=o.slice(0,n).trim(),s=o.slice(n+4).trim();if(!st(i))throw new Error(`[Parser] '${i}' is not a valid item alias.`);let a=y(s),c=r[1].trim();if(!c.startsWith("track "))throw new Error('[Parser] Second section of @for must start with "track".');let m=c.slice(6).trim(),l=y(m),h=new Map;if(r.length>=3&&r[2]!==void 0){let k=r[2].trim(),I=t+e.indexOf(r[2]);jt(k,I,h)}return{itemAlias:i,iterableExpression:a.node,iterableSource:s,trackExpression:l.node,trackSource:m,implicitAliases:h}}function jt(e,t,r){let o=e.split(","),n=0,i=new Set(["$index","$last","$first","$even","$odd"]);for(let s of o){let a=s.trim(),c=a.indexOf("=");if(c===-1)throw new Error(`[Parser] Invalid alias declaration '${a}'. Expected '$implicit = alias'.`);n+=s.length+1;let m=a.slice(0,c).trim(),l=a.slice(c+1).trim();if(!(k=>i.has(k))(l))throw new Error(`[Parser] '${l}' is not a known implicit variable. Known variables: ${[...i].join(", ")}.`);if(n+=s.length+1,!st(m))throw new Error(`[Parser] '${m}' is not a valid alias identifier.`);if(n+=s.length+1,r.has(l))throw new Error(`[Parser] '${l}' is already aliased in this @for expression.`);r.set(l,m),n+=s.length+1}}function Yt(e){let t=new Array,r="",o=0,n;for(let i=0;i<e.length;i++){let s=e[i];if(!(!r&&s===" ")){if(n){r+=s,s===n&&e[i-1]!=="\\"&&(n=null);continue}if(s==='"'||s==="'"||s==="`"){n=s,r+=s;continue}if(s==="("||s==="["||s==="{"){o++,r+=s;continue}if(s===")"||s==="]"||s==="}"){o--,r+=s;continue}if(s===";"&&o===0){t.push(r),r="";continue}r+=s}}return r.trim().length&&t.push(r),t}function st(e){if(!e.length)return!1;let r=Wt("__id.ts",e,zt.ESNext,!1).statements[0];return!!r&&qt(r)&&Xt(r.expression)&&r.expression.text===e}function at(e,t,r){return pt(e,t,r)}function Zt(e,t,r){switch(r.type){case 14:return pt(e,t,r);case 13:e.advance(2);let o=w(e,t);return{type:4,children:o}}}function pt(e,t,r){e.advance();let o=e.peek();if(o.type!==18)throw new Error(`[Parser] Expected CONDITION after ${u[r.type]}, got ${u[o.type]}`);e.advance(2);let n=o.parts[0],i=y(n),s=w(e,t);return{type:r.type===11?3:5,condition:n,conditionNode:i.node,children:s,alternate:Zt(e,t,e.peek())}}function ct(e,t,r){let o=new Array;for(;e.peek().type===21;){e.advance();let n=e.getCurrentToken().value.parts[0],i=Jt(n);o.push(i)}return e.advance(),{type:9,specifiers:o,path:e.getCurrentToken().value.parts[0]}}function Jt(e){let t=e.trim(),r=t.match(/^\*\s+as\s+([A-Za-z_$][\w$]*)$/);if(r)return{imported:"*",local:r[1]};let o=t.match(/^default\s+as\s+([A-Za-z_$][\w$]*)$/);if(o)return{imported:"default",local:o[1]};let n=t.match(/^([A-Za-z_$][\w$]*)(?:\s+as\s+([A-Za-z_$][\w$]*))?$/);if(n)return{imported:n[1],local:n[2]??n[1]};throw new Error(`[Parser] Invalid import specifier "${e}".`)}function mt(e,t,r){e.advance();let o=e.peek();if(o.type!==18)throw new Error(`[Parser] Expected CONDITION after SWITCH, got ${u[o.type]}`);let n=y(o.parts[0]).node;e.advance(2);let i=new Array;for(;e.peek().type!==20;)switch(e.peek().type){case 16:let a=new Array;do{e.advance();let c=e.peek();if(c.type!==18)throw new Error("[Parser] Expected CONDITION after CASE");a.push(c.parts[0]),e.advance()}while(e.peek().type!==19);e.advance(),i.push({type:8,condition:a,children:w(e,t)});break;case 17:e.advance(2),i.push({type:8,condition:null,children:w(e,t)});break}return e.advance(),{type:7,expression:n,children:i}}function lt(e,t,r){return e.advance(),{type:1,value:r.parts[0]}}var ie=class{_cursor;_states={0:lt,10:K,9:K,1:nt,11:at,12:it,15:mt,21:ct};constructor(t){this._cursor=new ne(t)}parse(){let t=new Array;for(;this._cursor.peek().type!==23;){let r=this.parseNode();r&&t.push(r)}return t}parseNode(){let t=this._cursor.peek();if(t.type===23)return;let r=this._states[t.type];if(!r)throw new Error(`[Parser] No transition function for token type ${u[t.type]}`);return r(this._cursor,this.parseNode.bind(this),t)}};import{indent as Ar}from"@xaendar/common";var D=class extends x{_imports=new Array;addImport(t){this._imports.push(t)}getImportBySelector(t){return this._imports.find(r=>r.type==="component"&&r.selectors.includes(t))}};import{indent as Te}from"@xaendar/common";function ft(e,t,r){let o=new Array;if(nr(e.tagName)){let n=r.getImportBySelector(e.tagName);if(!n)throw new Error(`[Type Checker] ${e.tagName} selector is not associated to any WebComponent imported in the template`);o.push(...er(e,n,r))}else o.push(...or(e,r));return e.children.forEach(n=>o.push(...t(n,r))),o}function er(e,t,r){let o=new Array,n=new Set(t.properties.filter(i=>i.required).map(i=>i.alias??i.name));if(e.attributes.forEach(({name:i,value:s})=>{let a=tr(t,i);a&&(n.delete(a.alias??a.name),o.push("{",...Te(typeof s=="object"?[`(${d(s.expression,r,{resolver:"root"})}) satisfies ${a.type};`]:["let x!: string",`x satisfies ${a.type};`]),"}"))}),n.size)throw new Error(`[Type Checker] ${e.tagName} is missing the following required properties: ${Array.from(n.values()).join(`
15
- `)}`);return e.events.forEach(({name:i,handler:s,parameters:a})=>{let c=rr(t,i);if(!c)throw new Error(`[Type Checker] Unknown event "${i}" on <${e.tagName}> (${t.className} has no @Event with this name).`);let m=new x([],r);m.addUnresolvableIdentifier("$event");let l=a.map(h=>d(h,m,{resolver:"root"})).join(", ");o.push("{"),c.type!=="void"&&o.push(Te(`let $event!: CustomEvent<${c.type}>;`)),o.push(Te(`root.${s}(${l});`),"}")}),o}function tr(e,t){return e.properties.find(r=>(r.alias??r.name)===t)}function rr(e,t){return e.events.find(r=>r.name===t)}function or(e,t){let r=new Array;return e.attributes.forEach(({value:o})=>{typeof o!="string"&&r.push(`${d(o.expression,t,{resolver:"root"})};`)}),e.events.forEach(({handler:o,parameters:n})=>{let i=new x([],t);i.addUnresolvableIdentifier("$event");let s=n.map(a=>d(a,i,{resolver:"root"})).join(", ");r.push(`root.${o}(${s});`)}),r}function nr(e){return/^[a-z][a-z0-9._\-]*-[a-z0-9._\-]*$/.test(e)}import{indent as ir}from"@xaendar/common";function ut(e,t,r){let o=new D([],r),n=W(e,"$index"),i=W(e,"$first"),s=W(e,"$last"),a=W(e,"$even"),c=W(e,"$odd");[n,i,s,a,c,e.itemAlias].forEach(l=>o.addUnresolvableIdentifier(l));let m=new Array;return m.push(`for (const ${e.itemAlias} of root.${e.iterableSource}) {`),m.push(...ir([`let ${n}!: number;`,`let ${i}!: boolean;`,`let ${s}!: boolean;`,`let ${a}!: boolean;`,`let ${c}!: boolean;`,`${d(e.trackExpression,r,{skipResolution:!0})};`,...e.children.flatMap(l=>t(l,o))])),m.push("}"),m}function W(e,t){return e.implicitAliases.get(t)??t}import{indent as xe}from"@xaendar/common";function dt(e,t,r){let o=new Array,n=d(e.conditionNode,r,{resolver:"root"});o.push(`if (${n}) {`),o.push(...xe(e.children.flatMap(s=>t(s,r)))),o.push("}");let i=e.alternate;for(;i?.type===5;){let s=d(i.conditionNode,r,{resolver:"root"});o.push(`else if (${s}) {`),o.push(...xe(i.children.flatMap(a=>t(a,r)))),o.push("}"),i=i.alternate}return i&&(o.push("else {"),o.push(...xe(i.children.flatMap(s=>t(s,r)))),o.push("}")),o}function xt(e,t,r){let o=e.path,n=Tt(o),i=new Array;for(let s of e.specifiers){let{imported:a,local:c}=s;switch(a){case"*":i.push(`let ${c}!: typeof import('${n}');`);break;case"default":i.push(`let ${c}!: typeof import('${n}')['default'];`);break;default:let m=Tt(a);i.push(`let ${c}!: typeof import('${n}')['${m}'];`);break}}return i}function Tt(e){return e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}import{indent as ht}from"@xaendar/common";function Et(e,t,r){let n=[`switch (${d(e.expression,r,{resolver:"root"})}) {`];return e.children.forEach(i=>{i.condition?.length?i.condition.forEach(s=>n.push(` case ${s}:`)):n.push(" default:"),n.push(...ht(ht([...i.children.flatMap(s=>t(s,r)),"break;"])))}),n.push("}"),n}function he(e,t,r){return e.type===2?[`${d(e.expression,r,{resolver:"root"})};`]:[]}import{existsSync as Ee}from"fs";import{readFile as sr}from"fs/promises";import{resolve as ar}from"path";import{createSourceFile as pr,forEachChild as cr,getNameOfDeclaration as Ct,isArrayLiteralExpression as mr,isCallExpression as q,isClassDeclaration as lr,isDecorator as fr,isIdentifier as F,isObjectLiteralExpression as kt,isPropertyAccessExpression as ur,isPropertyAssignment as Nt,isPropertyDeclaration as ke,isStringLiteral as Ce,isTypeReferenceNode as dr,ScriptTarget as Tr,SyntaxKind as It}from"typescript";async function gt(e,t,r=process.cwd()){try{let o=xr(e,r);if(!o)return;let n=await sr(o,"utf8"),i=pr(o,n,Tr.Latest,!0),s;return cr(i,a=>{if(!s&&lr(a)){let c=a.name?.text;if(c!==t)return;let m=a.modifiers??[],l=Array.from(m).find(g=>hr(g));if(!l)return;let h=kr(l);if(!h?.length)return;let k=new Array,I=new Array;a.members.forEach(g=>{if(!ke(g))return;let O=g.modifiers??[],X=!1,z=Array.from(O).find(A=>{let S=Er(A);return X=!!S.required,S.decorator});if(z){let A=Ct(g),S=A&&F(A)?A.text:void 0;if(S){let G=Ir(S,z,X);G&&k.push(G)}return}let Ne=Array.from(O).find(A=>Cr(A));if(Ne){let A=Ct(g),S=A&&F(A)?A.text:void 0;if(S){let G=gr(S,Ne);G&&I.push(G)}}}),s={type:"component",className:c,selectors:h,properties:k,events:I}}}),s}catch(o){console.error(`Failed to extract component metadata from ${e}:`,o);return}}function xr(e,t){if(e.startsWith(".")){let r=ar(t,e);if(Ee(`${r}.ts`))return r+".ts";if(Ee(`${r}/index.ts`))return`${r}/index.ts`;if(Ee(r))return r}}function hr(e){if(e.kind!==It.Decorator)return!1;let t=q(e.expression)?e.expression.expression:e.expression;return F(t)&&t.text==="WebComponent"}function Er(e){if(!fr(e))return{decorator:!1};let t=e.expression;if(!q(t))return{decorator:!1};let r=t.expression;return F(r)&&r.text==="Property"?{decorator:!0}:ur(r)&&F(r.expression)&&r.expression.text==="Property"&&r.name.text==="required"?{decorator:!0,required:!0}:{decorator:!1}}function Cr(e){if(e.kind!==It.Decorator)return!1;let t=q(e.expression)?e.expression.expression:e.expression;return F(t)&&t.text==="Event"}function kr(e){try{let t=e.expression;if(!q(t))return[];let r=t.arguments;if(r.length===0)return[];let o=r[0];if(!o||!kt(o))return[];let n=Array.from(o.properties).find(i=>Nt(i)&&F(i.name)&&i.name.text==="selector");return Nr(n.initializer)}catch{return[]}}function Nr(e){return Ce(e)?[e.text]:mr(e)?e.elements?.filter(t=>Ce(t)).map(t=>t.text):[]}function Ir(e,t,r){let o=t.expression,n={name:e,required:r,type:ke(t.parent)?At(t.parent.type):"any"};if(q(o)){let i=o.arguments,a=(i.length?i.find(c=>kt(c)):void 0)?.properties?.find(c=>Nt(c)&&F(c.name)&&c.name.text==="alias");a&&Ce(a.initializer)&&(n.alias=a.initializer.text)}return n}function gr(e,t){let r={name:e,type:"void"};return ke(t.parent)&&(r.type=At(t.parent.type,!0)),r}function At(e,t=!1){let r=t?"void":"any";if(!e||!dr(e))return r;let o=e.typeArguments;return!o||o.length===0?r:o[0].getText()}var se=class{constructor(t){this._ast=t}_ast;_context=new D;_states={1:he,2:he,0:ft,3:dt,6:ut,7:Et,9:xt};async populateImportMetadata(t){let r=this._ast.filter(o=>o.type===9);await Promise.all(r.flatMap(o=>o.specifiers.filter(({imported:n})=>n!=="*").map(async({imported:n,local:i})=>{let s=n==="default"?i:n,a=await gt(o.path,s,t);a&&this._context.addImport(a)})))}async generate(t){await this.populateImportMetadata(t);let r=this._ast.flatMap(o=>this._processNode(o,this._context));return["function typeCheck() {",...Ar(r),"}"].join(`
16
- `)}_processNode=(t,r)=>{let o=this._states[t.type];if(!o)throw new Error(`[Type Checker] No transition function for token type ${E[t.type]}`);return o(t,this._processNode,r)}};async function ea(e,t,r){let o=new oe(e).tokenize(),n=new ie(o).parse();return{javascript:new Q(n).generate(r),typescript:await new se(n).generate(t)}}export{ea as compile};
8
+ const { ${e.itemAlias}, ${m}, ${d}, ${x}, ${f}, ${A} } = vars;`,node:e,parentNode:S,context:I,anchor:"anchor",isForBody:!0},args:[S,"parentContext",a,c,"anchor"]}),o.code.push(`_for(${r}, context, () => ${s}, ${e.itemAlias} => ${T(e.trackExpression,I,{skipResolution:!0})}, this.${S}.bind(this));`),o}function V(e,r){return e.implicitAliases.get(r)??r}import{indent as M}from"@xaendar/common";function Oe(e,r,t,n){let o=new C([],n),i={code:[],functionsToProcess:new Map};i.code.push(`_if(${r}, context, [`);let s=O("if",r,t);i.code.push(...M(["{",...M([`condition: () => ${T(e.conditionNode,n)},`,`block: this.${s}.bind(this)`]),"},"])),i.functionsToProcess.set(s,{fn:{node:e,parentNode:s,context:o,anchor:"anchor"},args:[s,"parentContext","anchor"]});let a=e.alternate,c=0;for(;a?.type===7;){let m=new C([],n),d=O("elseIf",r,`${t}_${c}`),x=a.conditionNode;i.code.push(...M(["{",...M([`condition: () => ${T(x,n)},`,`block: this.${d}.bind(this)`]),"},"])),i.functionsToProcess.set(d,{fn:{node:a,parentNode:r,context:m,anchor:"anchor"},args:[r,"parentContext","anchor"]}),a=a.alternate,c++}if(a){let m=new C([],n),d=O("else",r,t);i.code.push(...M(["{",...M([`block: this.${d}.bind(this)`]),"},"])),i.functionsToProcess.set(d,{fn:{node:a,parentNode:r,context:m,anchor:"anchor"},args:[r,"parentContext","anchor"]})}return i.code.push("]);"),i}import{indent as we}from"@xaendar/common";function Re(e,r,t,n){let o={code:[],functionsToProcess:new Map};return o.code.push(`_switch(${r}, context, () => ${T(e.expression,n)}, [`),e.children.forEach((i,s)=>{let a=new C([],n),c=i.condition?O("case",r,`${t}_${s}`):O("default",r,t);o.functionsToProcess.set(c,{fn:{node:i,parentNode:c,context:a},args:[c,"parentContext","anchor"]});let m=`this.${c}.bind(this)`;o.code.push(...we(["{",...we([`condition: ${i.condition?`[${i.condition.join(", ")}]`:"null"},`,`block: ${m}`]),"},"]))}),o.code.push("])"),o}function me(e,r,t,n){return{code:[`${e.type===3?`_renderLiteralText(${r}, context, '${e.value}');`:`_renderText(${r}, context, () => ${T(e.expression,n)});`}`]}}function be(e,r,t,n){}var Q=class{constructor(r,t){this._input=r;this._ast=t}_input;_ast;_nodeToProcess=new Map;_states={3:me,4:me,0:_e,5:Oe,8:Se,9:Re,11:be};generate(r){try{this._nodeToProcess.clear();let t=new C,n=["_render() {",...P([`const ${U} = this._root;`,"const context = new Context(this, { createElement: document.createElement.bind(document), get: () => undefined });"])];r&&n.push(P(`${U}.adoptedStyleSheets = [${r}];`));for(let o=0;o<this._ast.length;o++){let i=this._processNode(this._ast[o],U,o.toString(),t,null);if(i){let{code:s,functionsToProcess:a}=i;a?.forEach((c,m)=>this._nodeToProcess.set(m,c)),n.push(...P(s))}}n.push(...P(["return context;"]),"}");for(let[o,i]of this._nodeToProcess.entries()){let{node:s,parentNode:a,context:c,precode:m,anchor:d}=i.fn;n.push(`
9
+ ${o}(${i.args?.join(", ")}) {`,...P(["const context = new Context(this, parentContext);"])),m&&n.push(P(m)),n.push(...P([...s.children.map((x,f)=>{let A=this._processNode(x,a,f.toString(),c,d??null);if(A){let{code:I,functionsToProcess:S}=A;return S?.forEach((X,z)=>this._nodeToProcess.set(z,X)),I}return""}).flat(),i.fn.isForBody?"return { context, update };":"return context;"]),"}")}return n.join(`
10
+ `)}catch(t){let n=t,{start:o,end:i}=n.cause;throw new Error(`[Generator] ${n.message}
11
+ ${bt(this._input,o,i)}`)}}_processNode(r,t,n,o,i){let s=this._states[r.type];if(!s)throw new Error(`No transition function for token type ${h[r.type]}`,{cause:r.span});return s(r,t,n,o,i)}};import{slice as Bt,Stack as Dt}from"@xaendar/common";var u=(l=>(l[l.TEXT=0]="TEXT",l[l.TAG_OPEN_NAME=1]="TAG_OPEN_NAME",l[l.TAG_SELF_CLOSE=2]="TAG_SELF_CLOSE",l[l.TAG_OPEN_END=3]="TAG_OPEN_END",l[l.TAG_CLOSE_NAME=4]="TAG_CLOSE_NAME",l[l.ATTRIBUTE=5]="ATTRIBUTE",l[l.ATTRIBUTE_VALUE=6]="ATTRIBUTE_VALUE",l[l.EVENT=7]="EVENT",l[l.EVENT_PAREMETER=8]="EVENT_PAREMETER",l[l.INTERPOLATION_LITERAL=9]="INTERPOLATION_LITERAL",l[l.INTERPOLATION_EXPRESSION=10]="INTERPOLATION_EXPRESSION",l[l.IF=11]="IF",l[l.FOR=12]="FOR",l[l.ELSE=13]="ELSE",l[l.ELSE_IF=14]="ELSE_IF",l[l.SWITCH=15]="SWITCH",l[l.CASE=16]="CASE",l[l.DEFAULT=17]="DEFAULT",l[l.CONDITION=18]="CONDITION",l[l.BLOCK_OPEN=19]="BLOCK_OPEN",l[l.BLOCK_CLOSE=20]="BLOCK_CLOSE",l[l.IMPORT=21]="IMPORT",l[l.IMPORT_PATH=22]="IMPORT_PATH",l[l.EOF=23]="EOF",l))(u||{});function Fe(e,r){let t=!0,n="",o;for(;t;)e.peek()===34?(e.advance(),t=!1,o={state:"tag-body",tokens:[{type:6,parts:[n]}],popState:!0}):(e.advance(),n=`${n}${e.currentChar.value}`);return o}function $e(e,r){let t=!0,n="",o;for(;t;)switch(e.peek()){case 32:e.advance(),t=!1,o={state:"tag-body",tokens:[{type:5,parts:[n]}]};break;case 62:case 47:t=!1,o={state:"tag-body",tokens:[{type:5,parts:[n]}]};break;case 61:if(e.advance(),e.peek()!==34)throw new Error(`Attribute value must start with double quotes '"' at ${e.formattedPosition}`);e.advance(),t=!1,o={state:e.peek()===123?"interpolation":"attribute-value",pushState:!0,tokens:[{type:5,parts:[n]}]};break;default:e.advance(),n=`${n}${e.currentChar.value}`}return o}function j(e,r){if(e.skipSpaces(),e.peek()!==40)throw new Error(`Expected '(' but got '${String.fromCharCode(e.peek())}' at row ${e.position.row}, col ${e.position.column}`);e.advance();let t="",n=1;for(;n>0;)switch(e.peek()){case 40:n++,t=le(e,t);break;case 41:if(n--,!n){e.advance();break}t=le(e,t);break;default:t=le(e,t)}return t}function le(e,r){return e.advance(),`${r}${e.currentChar.value}`}function Pe(e,r){let t=j(e,r);return e.skipSpaces(),{state:e.peekMatch("@case")?"flow-control":"flow-control-block",tokens:[{type:18,parts:[t]}],popState:!0}}function Me(e,r){return{state:"flow-control-block",tokens:[{type:18,parts:[j(e,r)]}],popState:!0}}function Be(e,r){let t=!0,n="",o="",i=e.currentChar.index+1,s={state:"tag-body",tokens:[]};for(;t;)switch(e.peek()){case 91:case 93:case 123:case 125:case 34:case 39:case 40:n=Y(e,n),o?(o===e.currentChar.value||o==="["&&e.currentChar.value==="]"||o==="{"&&e.currentChar.value==="}")&&(o=""):o=e.currentChar.value;break;case 44:if(o)n=Y(e,n);else{let a=e.currentChar.index+1;s.tokens.push({type:8,parts:[n],span:{start:i,end:a}}),e.advance(),e.skipSpaces(),n="",i=e.currentChar.index+1}break;case 41:if(!o){let a=e.currentChar.index+1;s.tokens.push({type:8,parts:[n],span:{start:i,end:a}}),t=!1;break}n=Y(e,n);break;default:n=Y(e,n)}return s}function Y(e,r){return e.advance(),`${r}${e.currentChar.value}`}function De(e,r){let t=!0,n="",o;for(e.advance();t;)switch(e.peek()){case 32:case 47:case 62:o={state:"tag-body"},t=!1;break;case 40:if(!n)throw new Error(`Event name cannot be empty at ${e.formattedPosition}`);let i="parameter";e.advance(),e.skipSpaces(),e.peek()===41&&(i="tag-body",e.advance(2)),o={state:i,tokens:[{type:7,parts:[n]}]},t=!1;break;default:e.advance(),n=`${n}${e.currentChar.value}`}return o}function Ge(e,r){let t;if(e.advance(),e.peekMatch("for "))e.advance(4),t={state:"flow-control-condition",tokens:[{type:12}],pushState:!0};else if(e.peekMatch("if "))e.advance(2),t={state:"flow-control-condition",tokens:[{type:11}],pushState:!0};else if(e.peekMatch("else if "))e.advance(8),t={state:"flow-control-condition",tokens:[{type:14}],pushState:!0};else if(e.peekMatch("else "))e.advance(5),t={state:"flow-control-block",tokens:[{type:13}]};else if(e.peekMatch("switch "))e.advance(7),t={state:"flow-control-condition",tokens:[{type:15}],pushState:!0};else if(e.peekMatch("case "))e.advance(5),t={state:"case-flow-control-condition",tokens:[{type:16}],pushState:!0};else if(e.peekMatch("default "))e.advance(8),t={state:"flow-control-block",tokens:[{type:17}]};else if(e.peekMatch("import "))e.advance(7),t={state:"import"};else throw new Error(`Unknown flow-control keyword at ${e.formattedPosition}`);return t}function Ue(e,r){if(e.skipSpaces(),e.peek()!==123)throw new Error(`Expected '{' but got '${String.fromCharCode(e.peek())}' at ${e.formattedPosition}`);return e.advance(),{state:"text",tokens:[{type:19}],pushState:!0}}function Ve(e,r){let t=!0,n="",o,i=!1;if(e.skipSpaces(),!e.peekMatch("from"))throw new Error(`Expected 'from' keyword after import list at ${e.formattedPosition}`);switch(e.advance(4),e.skipSpaces(),e.advance(),e.currentChar.code){case 39:i=!0;break;case 34:break;default:throw new Error(`Import statement must start with ' or ".
12
+ Found character ${e.currentChar.value} at ${e.formattedPosition}`)}let s=i?39:34;for(;t;)e.peek()===s?(e.advance(),t=!1,o={state:"text",tokens:[{type:22,parts:[n]}]}):(e.advance(),n=`${n}${e.currentChar.value}`);return o}function We(e,r){let t=!0,n="",o=e.currentChar.index+1,i={state:"import-path",tokens:[]};if(e.skipSpaces(),e.advance(),e.currentChar.code!==123)throw new Error(`Expected { after @import at ${e.formattedPosition}`);for(;t;)switch(e.peek()){case 32:e.skipSpaces(),n&&e.peek()!==44&&e.peek()!==125&&(n=`${n} `);break;case 44:He(i,e,n,o),n="",o=e.currentChar.index+1;break;case 125:He(i,e,n,o),t=!1;break;default:e.advance(),n=`${n}${e.currentChar.value}`}return i}function He(e,r,t,n){let o=r.currentChar.index+1;r.advance(),e.tokens.push({type:21,parts:[t],span:{start:n,end:o}})}function Ke(e,r){let t=!0,n="",o=1,i;for(;t;)switch(e.peek()){case 123:o++,n=fe(e,n);break;case 125:if(o--,o===0){e.advance(),n=n.trimEnd();let s=r.history.pop(),a;switch(s){case"attribute":if(e.peek()!==34)throw new Error(`Interpolation must end with double quotes '"', found '${String.fromCharCode(e.peek())}' at ${e.formattedPosition}`);e.advance(),a="tag-body";break;case"text":a="text";break;default:throw new Error(`Unexpected state '${s}' after interpolation expression at ${e.formattedPosition}`)}i={state:a,tokens:[{type:10,parts:[n]}],popState:!0},t=!1}else n=fe(e,n);break;default:n=fe(e,n)}return i}function fe(e,r){return e.advance(1),`${r}${e.currentChar.value}`}function Xe(e,r){let t=!0,n="`",o;for(e.advance();t;)switch(e.peek()){case 96:if(n=qe(e,n),e.peek()===125){e.advance();let i=r.history.pop(),s;switch(i){case"attribute":if(e.peek()!==34)throw new Error(`Attribute interpolation expression must end with double quotes '"', found '${String.fromCharCode(e.peek())}' at ${e.formattedPosition}`);e.advance(),s="tag-body";break;case"text":s="text";break;default:throw new Error(`Unexpected state '${i}' after interpolation literal at ${e.formattedPosition}`)}o={state:s,tokens:[{type:9,parts:[n]}],popState:!0},t=!1}else n=`${n}${e.currentChar.value}`;break;default:n=qe(e,n)}return o}function qe(e,r){return e.advance(),`${r}${e.currentChar.value}`}function ze(e,r){return e.advance(),e.skipSpaces(),e.peek()===96?{state:"interpolation-literal"}:{state:"interpolation-expression"}}function Qe(e,r){let t=!0,n;for(;t;)switch(e.peek()){case 64:n={state:"event"},t=!1;break;case 32:e.skipSpaces();break;case 62:case 47:n={state:"tag-open-end"},t=!1;break;default:n={state:"attribute"},t=!1}return n}function je(e,r){let t=!0,n="",o;for(e.advance(2),e.skipSpaces();t;)switch(e.peek()){case 62:if(!n)throw new Error(`Tag close name cannot be empty at ${e.formattedPosition}`);e.advance(),o={state:"text",tokens:[{type:4,parts:[n]}]},t=!1;break;case 32:throw new Error(`Tag close name cannot contain spaces at ${e.formattedPosition}`);default:e.advance(),n=`${n}${e.currentChar.value}`}return o}function Ye(e,r){let t;if(e.peek()===62)e.advance(),t={state:"text",tokens:[{type:3,parts:[]}]};else{e.advance();let n=e.peek();if(n===62)e.advance(),t={state:"text",tokens:[{type:2,parts:[]}]};else throw new Error(`Unexpected character '${String.fromCharCode(n)}' after '/': expected '>' to close self-closing tag at ${e.formattedPosition}`)}return t}function Ze(e,r){let t=!0,n="",o;for(e.advance(),e.skipSpaces();t;)switch(e.peek()){case 32:case 47:case 62:if(!n)throw new Error(`Tag name cannot be empty at ${e.formattedPosition}`);o={state:"tag-body",tokens:[{type:1,parts:[n]}]},t=!1;break;default:e.advance(),n=`${n}${e.currentChar.value}`}return o}function Je(e){return/\S/.test(e)}function et(e,r){let t=!0,n="",o;for(;t;)switch(e.peek()){case 60:o={state:e.peek(1,{offset:1})===47?"tag-close":"tag-open-name"},t=!1;break;case 123:o={state:"interpolation",pushState:!0},t=!1;break;case 64:o={state:"flow-control"},t=!1;break;case 125:r.history[r.history.length-1]==="flow-control-block"?(e.advance(),o={state:"text",tokens:[{type:20}],popState:!0},t=!1):(e.advance(),n=`${n}${e.currentChar.value}`);break;case 10:case 13:e.advance();break;default:e.advance(),n=`${n}${e.currentChar.value}`}return o.tokens??=Je(n)?[{type:0,parts:[n]}]:void 0,o}var ne=class{constructor(r){this.input=r}input;_currentChar={code:0,index:-1,value:""};get currentChar(){return this._currentChar}_peekCache=new Map;_position={row:0,column:0};get position(){return this._position}get formattedPosition(){return`[Ln ${this._position.row}, Col ${this._position.column}]`}advance(r=1){if(r<1)throw new Error(`${r} is not a valid value. Please enter a number equal or greater than 1`);let t=this._currentChar.index+r;t>=this.input.length?(this._currentChar.code=0,this._currentChar.index=-1,this._currentChar.value="",this.throwEOFError()):([10,13].includes(this._currentChar.code)?(this._position.row++,this._position.column=0):this._position.column++,this._currentChar.index=t,this._currentChar.value=this.input[t],this._currentChar.code=this.input.charCodeAt(t))}peekMatch(r,t){if(typeof r=="string"){let i=this.peek(r.length);for(let s=0;s<r.length;s++)if(i[s]!==r.charCodeAt(s))return!1;return!0}let n=this._currentChar.index+1,o=this.input.slice(n,n+t);return r.test(o)}peek(r,t){let n=this._peekCache,o=typeof r=="number"?r:1,i=(typeof r=="object"?r:t)?.offset??0;return o===1?this.peekOneChar(this._currentChar.index+i+1,n):this.peekMany(o+i,n)}skipSpaces(){for(;this.peek()===32||this.peek()===10||this.peek()===13;)this.advance()}peekMany(r,t){let n=new Array,o=this._currentChar.index+1;for(let i=o;i<o+r;i++)n.push(this.peekOneChar(i,t));return n}peekOneChar(r,t){if(t.has(r))return t.get(r);r>=this.input.length&&this.throwEOFError();let n=this.input.charCodeAt(r);return t.set(r,n),n}throwEOFError(){throw new Error("",{cause:0})}};var oe=class{constructor(r){this._input=r;this._cursor=new ne(this._input)}_input;_cursor;_state="text";_stack=new Dt;_tokens=new Array;_states={text:et,"tag-open-name":Ze,"tag-body":Qe,"tag-open-end":Ye,"tag-close":je,attribute:$e,"attribute-value":Fe,event:De,parameter:Be,"flow-control":Ge,"flow-control-condition":Me,"case-flow-control-condition":Pe,"flow-control-block":Ue,interpolation:ze,"interpolation-expression":Ke,"interpolation-literal":Xe,import:We,"import-path":Ve};tokenize(){let r=!1,t=this._cursor,n=-1;for(;!r;)try{n=t.currentChar.index+1;let o=this._states[this._state],{state:i,tokens:s,popState:a,pushState:c}=o(t,{history:this._stack.values,tokens:[...this._tokens]});if(s?.length){let m=t.currentChar.index+1;this._tokens.push(...this.withTokenSpans(s,{start:n,end:m}))}c&&this._stack.push(this._state),a&&this._stack.pop(),this._state=i}catch(o){let i=o;if(i.cause===0)r=!0;else throw new Error(`[Lexer] ${i.message}
13
+ ${Bt(this._input,n,t.currentChar.index+1)}
14
+ at ${t.formattedPosition}`)}return this._tokens}throwError(r){throw new Error(`[Lexer] ${r}`)}withTokenSpans(r,t){return r.map(n=>({...n,span:n.span??t}))}};import{slice as rr}from"@xaendar/common";var ie=class{constructor(r){this._tokens=r}_tokens;_currentToken={value:{type:23},index:-1};getCurrentToken(){return this._currentToken}advance(r=1){if(r<1)throw new Error(`${r} is not a valid value. Please enter a number equal or greater than 1`);let t=this._currentToken.index+r;t>=this._tokens.length?(this._currentToken.value={type:23},this._currentToken.index=-1):(this._currentToken.index=t,this._currentToken.value=this._tokens[t])}peek(r,t){let n=typeof r=="number"?r:1,o=(typeof r=="object"?r:t)?.offset??0;return n===1?this.peekOneToken(this._currentToken.index+o+1):this.peekMany(n+o)}peekMany(r){let t=new Array,n=this._currentToken.index+1;for(let o=n;o<n+r;o++)t.push(this.peekOneToken(o));return t}peekOneToken(r){return r<this._tokens.length?this._tokens[r]:{type:23}}};import{ScriptTarget as Gt,SyntaxKind as p,createSourceFile as Ut,forEachChild as Vt}from"typescript";function v(e){let r="const x = ",o=Ut("expression.ts",`${r}${e}`,Gt.ESNext,!0).statements[0].declarationList.declarations[0].initializer,i=new Array;if(tt(o,r.length,i),i.length)throw new Error(i.reduce((s,a)=>`${s}${a.message}
15
+ `,""));return{node:o}}function tt(e,r,t){if(!Ht(e))throw new Error(Wt(e));if(Vt(e,n=>tt(n,r,t)),t.length)throw new Error(t[0].message)}function Ht(e){switch(e.kind){case p.StringLiteral:case p.NumericLiteral:case p.BigIntLiteral:case p.TrueKeyword:case p.FalseKeyword:case p.NullKeyword:case p.UndefinedKeyword:case p.Identifier:case p.PropertyAccessExpression:case p.ElementAccessExpression:case p.CallExpression:case p.BinaryExpression:case p.EqualsEqualsToken:case p.EqualsEqualsEqualsToken:case p.ExclamationEqualsToken:case p.ExclamationEqualsEqualsToken:case p.LessThanToken:case p.LessThanEqualsToken:case p.GreaterThanToken:case p.GreaterThanEqualsToken:case p.PlusToken:case p.MinusToken:case p.AsteriskToken:case p.SlashToken:case p.PercentToken:case p.AsteriskAsteriskToken:case p.AmpersandAmpersandToken:case p.BarBarToken:case p.QuestionQuestionToken:case p.QuestionDotToken:case p.QuestionToken:case p.ColonToken:case p.AmpersandToken:case p.BarToken:case p.CaretToken:case p.LessThanLessThanToken:case p.GreaterThanGreaterThanToken:case p.GreaterThanGreaterThanGreaterThanToken:case p.InstanceOfKeyword:case p.InKeyword:case p.PrefixUnaryExpression:case p.PostfixUnaryExpression:case p.TypeOfExpression:case p.VoidExpression:case p.ConditionalExpression:case p.ParenthesizedExpression:case p.TemplateExpression:case p.NoSubstitutionTemplateLiteral:case p.TemplateHead:case p.TemplateMiddle:case p.TemplateTail:case p.TemplateSpan:case p.ArrayLiteralExpression:case p.ObjectLiteralExpression:case p.PropertyAssignment:case p.ShorthandPropertyAssignment:case p.SpreadAssignment:case p.SpreadElement:case p.TaggedTemplateExpression:case p.SyntaxList:return!0;default:return!1}}function Wt(e){switch(e.kind){case p.AwaitExpression:return"'await' is not allowed inside template expressions.";case p.YieldExpression:return"'yield' is not allowed inside template expressions.";case p.NewExpression:return"'new' is not allowed inside template expressions.";case p.ArrowFunction:case p.FunctionExpression:return"Function expressions are not allowed inside template expressions.";case p.BinaryExpression:return Kt(e.operatorToken.kind)?"Assignments are not allowed inside template expressions. Use @const to declare local template variables instead.":`'${p[e.kind]}' is not allowed inside template expressions.`;default:return`'${p[e.kind]}' is not allowed inside template expressions.`}}function Kt(e){return e>=p.FirstAssignment&&e<=p.LastAssignment}function W(e,r,t){let n=t.span.start;return e.advance(),{type:4,expression:v(t.parts[0]).node,span:{start:n,end:e.getCurrentToken().value.span.end}}}function rt(e,r,t){let n=t.span.start;e.advance();let o=t.parts[0],i=e.peek();if(i.type===5||i.type===4||i.type===7)return{type:1,name:o,value:"true",span:{start:n,end:e.getCurrentToken().value.span.end}};if(i.type===10||i.type===9){let s=W(e,r,i);return{type:1,name:o,value:s,span:{start:n,end:e.getCurrentToken().value.span.end}}}if(i.type!==6)throw new Error(`Attribute value missing for ${o} in: ${o}`);return e.advance(),{type:1,name:o,value:i.parts[0],span:{start:n,end:e.getCurrentToken().value.span.end}}}function nt(e,r,t){let n=t.span.start;e.advance();let o=t.parts[0],[i,s]=o.split("=");if(!i||!s)throw new Error(`Invalid event format: ${o}`);let a=new Array;for(;e.peek().type===8;)e.advance(),a.push(v(e.getCurrentToken().value.parts[0]).node);return{type:2,name:i,handler:s.replace(/^[""]|[""]$/g,""),parameters:a,span:{start:n,end:e.getCurrentToken().value.span.end}}}function ot(e,r,t){e.advance();let n=t.parts[0],o=new Array,i=new Array,s=!0;for(;s;){let c=e.peek();switch(c.type){case 5:o.push(rt(e,r,c));break;case 7:i.push(nt(e,r,c));break;default:s=!1}}if(e.peek().type===3&&e.advance(),e.peek().type===2)return e.advance(),{type:0,tagName:n,attributes:o,events:i,children:[]};let a=new Array;for(;!qt(e,n);){let c=r();c&&a.push(c)}return e.advance(),{type:0,tagName:n,attributes:o,events:i,children:a}}function qt(e,r){let t=e.peek();return t.type===4&&t.parts[0]===r}import{createSourceFile as Xt,isExpressionStatement as zt,isIdentifier as Qt,ScriptTarget as jt}from"typescript";function b(e,r){let t=new Array;for(;e.peek().type!==20;){let n=r();n&&t.push(n)}return e.advance(),t}function it(e,r,t){e.advance();let n=e.peek();if(n.type!==18)throw new Error(`Expected CONDITION after FOR, got ${u[n.type]}`);let o=Yt(n.parts[0],0);e.advance(2);let i=b(e,r);return{type:8,...o,children:i}}function Yt(e,r){let t=Jt(e);if(t.length<2)throw new Error('@for requires at least "item of iterable; track expr".');let n=t[0].trim(),o=n.indexOf(" of ");if(o===-1)throw new Error('@for expression must be in the form "item of iterable".');let i=n.slice(0,o).trim(),s=n.slice(o+4).trim();if(!st(i))throw new Error(`'${i}' is not a valid item alias.`);let a=v(s),c=t[1].trim();if(!c.startsWith("track "))throw new Error('Second section of @for must start with "track".');let m=c.slice(6).trim(),d=v(m),x=new Map;if(t.length>=3&&t[2]!==void 0){let f=t[2].trim(),A=r+e.indexOf(t[2]);Zt(f,A,x)}return{itemAlias:i,iterableExpression:a.node,iterableSource:s,trackExpression:d.node,trackSource:m,implicitAliases:x}}function Zt(e,r,t){let n=e.split(","),o=0,i=new Set(["$index","$last","$first","$even","$odd"]);for(let s of n){let a=s.trim(),c=a.indexOf("=");if(c===-1)throw new Error(`Invalid alias declaration '${a}'. Expected '$implicit = alias'.`);o+=s.length+1;let m=a.slice(0,c).trim(),d=a.slice(c+1).trim();if(!(f=>i.has(f))(d))throw new Error(`'${d}' is not a known implicit variable. Known variables: ${[...i].join(", ")}.`);if(o+=s.length+1,!st(m))throw new Error(`'${m}' is not a valid alias identifier.`);if(o+=s.length+1,t.has(d))throw new Error(`'${d}' is already aliased in this @for expression.`);t.set(d,m),o+=s.length+1}}function Jt(e){let r=new Array,t="",n=0,o;for(let i=0;i<e.length;i++){let s=e[i];if(!(!t&&s===" ")){if(o){t+=s,s===o&&e[i-1]!=="\\"&&(o=null);continue}if(s==='"'||s==="'"||s==="`"){o=s,t+=s;continue}if(s==="("||s==="["||s==="{"){n++,t+=s;continue}if(s===")"||s==="]"||s==="}"){n--,t+=s;continue}if(s===";"&&n===0){r.push(t),t="";continue}t+=s}}return t.trim().length&&r.push(t),r}function st(e){if(!e.length)return!1;let t=Xt("__id.ts",e,jt.ESNext,!1).statements[0];return!!t&&zt(t)&&Qt(t.expression)&&t.expression.text===e}function at(e,r,t){return pt(e,r,t)}function er(e,r,t){switch(t.type){case 14:return pt(e,r,t);case 13:let n=t.span.start;e.advance(2);let o=b(e,r);return{type:6,children:o,span:{start:n,end:e.getCurrentToken().value.span.end}}}}function pt(e,r,t){let n=t.span.start;e.advance();let o=e.peek();if(o.type!==18)throw new Error(`Expected CONDITION after ${u[t.type]}, got ${u[o.type]}`);e.advance(2);let i=o.parts[0],s=v(i),a=b(e,r),c=null,m=e.peek();return(m.type===14||m.type===13)&&(c=er(e,r,m)),{type:t.type===11?5:7,condition:i,conditionNode:s.node,children:a,alternate:c,span:{start:n,end:e.getCurrentToken().value.span.end}}}function ct(e,r,t){let n=new Array;for(;e.peek().type===21;){e.advance();let o=e.getCurrentToken().value.parts[0],i=tr(o);n.push(i)}return e.advance(),{type:11,specifiers:n,path:e.getCurrentToken().value.parts[0]}}function tr(e){let r=e.trim(),t=r.match(/^\*\s+as\s+([A-Za-z_$][\w$]*)$/);if(t)return{imported:"*",local:t[1]};let n=r.match(/^default\s+as\s+([A-Za-z_$][\w$]*)$/);if(n)return{imported:"default",local:n[1]};let o=r.match(/^([A-Za-z_$][\w$]*)(?:\s+as\s+([A-Za-z_$][\w$]*))?$/);if(o)return{imported:o[1],local:o[2]??o[1]};throw new Error(`Invalid import specifier "${e}".`)}function mt(e,r,t){e.advance();let n=e.peek();if(n.type!==18)throw new Error(`Expected CONDITION after SWITCH, got ${u[n.type]}`);let o=v(n.parts[0]).node;e.advance(2);let i=new Array;for(;e.peek().type!==20;){let s=e.peek();switch(s.type){case 16:let a=s.span.start,c=new Array;do{e.advance();let f=e.peek();if(f.type!==18)throw new Error("Expected CONDITION after CASE");c.push(f.parts[0]),e.advance()}while(e.peek().type!==19);e.advance();let m=b(e,r);i.push({type:10,condition:c,children:m,span:{start:a,end:e.getCurrentToken().value.span.end}});break;case 17:let d=s.span.start;e.advance(2);let x=b(e,r);i.push({type:10,condition:null,children:x,span:{start:d,end:e.getCurrentToken().value.span.end}});break}}return e.advance(),{type:9,expression:o,children:i}}function lt(e,r,t){return e.advance(),{type:3,value:t.parts[0]}}var se=class{constructor(r,t){this._input=r;this._cursor=new ie(t)}_input;_cursor;_states={0:lt,10:W,9:W,1:ot,11:at,12:it,15:mt,21:ct};parse(){try{let r=new Array;for(;this._cursor.peek().type!==23;){let t=this.parseNode();t&&r.push(t)}return r}catch(r){let t=r,n=this._cursor.peek();throw new Error(`[Parser] ${t.message}
16
+ ${rr(this._input,n.span.start,n.span.end)}`)}}parseNode(){let r=this._cursor.peek();if(r.type===23)return;let t=r.span.start,n=this._states[r.type];if(!n)throw new Error(`No transition function for token type ${u[r.type]}`);let o=n(this._cursor,this.parseNode.bind(this),r),i=this._cursor.getCurrentToken().value,s="span"in i?i.span.end:r.span.end;return{...o,span:o.span??{start:t,end:s}}}};import{indent as vr,slice as _r}from"@xaendar/common";var D=class extends C{_imports=new Array;addImport(r){this._imports.push(r)}getImportBySelector(r){return this._imports.find(t=>t.type==="component"&&t.selectors.includes(r))}};import{indent as Te}from"@xaendar/common";function ft(e,r,t){let n=new Array;if(ar(e.tagName)){let o=t.getImportBySelector(e.tagName);if(!o)throw new Error(`${e.tagName} selector is not associated to any WebComponent imported in the template`,{cause:e.span});n.push(...nr(e,o,t))}else n.push(...sr(e,t));return e.children.forEach(o=>n.push(...r(o,t))),n}function nr(e,r,t){let n=new Array,o=new Set(r.properties.filter(i=>i.required).map(i=>i.alias??i.name));if(e.attributes.forEach(({name:i,value:s})=>{let a=or(r,i);a&&(o.delete(a.alias??a.name),n.push("{",...Te(typeof s=="object"?[`(${T(s.expression,t,{resolver:"root"})}) satisfies ${a.type};`]:["let x!: string",`x satisfies ${a.type};`]),"}"))}),o.size)throw new Error(`${e.tagName} is missing the following required properties: ${Array.from(o.values()).join(`
17
+ `)}`,{cause:e.span});return e.events.forEach(({name:i,handler:s,parameters:a})=>{let c=ir(r,i);if(!c)throw new Error(`Unknown event "${i}" on <${e.tagName}> (${r.className} has no @Event with this name).`,{cause:e.span});let m=new C([],t);m.addUnresolvableIdentifier("$event");let d=a.map(x=>T(x,m,{resolver:"root"})).join(", ");n.push("{"),c.type!=="void"&&n.push(Te(`let $event!: CustomEvent<${c.type}>;`)),n.push(Te(`root.${s}(${d});`),"}")}),n}function or(e,r){return e.properties.find(t=>(t.alias??t.name)===r)}function ir(e,r){return e.events.find(t=>t.name===r)}function sr(e,r){let t=new Array;return e.attributes.forEach(({value:n})=>{typeof n!="string"&&t.push(`${T(n.expression,r,{resolver:"root"})};`)}),e.events.forEach(({handler:n,parameters:o})=>{let i=new C([],r);i.addUnresolvableIdentifier("$event");let s=o.map(a=>T(a,i,{resolver:"root"})).join(", ");t.push(`root.${n}(${s});`)}),t}function ar(e){return/^[a-z][a-z0-9._\-]*-[a-z0-9._\-]*$/.test(e)}import{indent as pr}from"@xaendar/common";function ut(e,r,t){let n=new D([],t),o=K(e,"$index"),i=K(e,"$first"),s=K(e,"$last"),a=K(e,"$even"),c=K(e,"$odd");[o,i,s,a,c,e.itemAlias].forEach(d=>n.addUnresolvableIdentifier(d));let m=new Array;return m.push(`for (const ${e.itemAlias} of root.${e.iterableSource}) {`),m.push(...pr([`let ${o}!: number;`,`let ${i}!: boolean;`,`let ${s}!: boolean;`,`let ${a}!: boolean;`,`let ${c}!: boolean;`,`${T(e.trackExpression,t,{skipResolution:!0})};`,...e.children.flatMap(d=>r(d,n))])),m.push("}"),m}function K(e,r){return e.implicitAliases.get(r)??r}import{indent as xe}from"@xaendar/common";function dt(e,r,t){let n=new Array,o=T(e.conditionNode,t,{resolver:"root"});n.push(`if (${o}) {`),n.push(...xe(e.children.flatMap(s=>r(s,t)))),n.push("}");let i=e.alternate;for(;i?.type===7;){let s=T(i.conditionNode,t,{resolver:"root"});n.push(`else if (${s}) {`),n.push(...xe(i.children.flatMap(a=>r(a,t)))),n.push("}"),i=i.alternate}return i&&(n.push("else {"),n.push(...xe(i.children.flatMap(s=>r(s,t)))),n.push("}")),n}function xt(e,r,t){let n=e.path,o=Tt(n),i=new Array;for(let s of e.specifiers){let{imported:a,local:c}=s;switch(a){case"*":i.push(`let ${c}!: typeof import('${o}');`);break;case"default":i.push(`let ${c}!: typeof import('${o}')['default'];`);break;default:let m=Tt(a);i.push(`let ${c}!: typeof import('${o}')['${m}'];`);break}}return i}function Tt(e){return e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}import{indent as ht}from"@xaendar/common";function Et(e,r,t){let o=[`switch (${T(e.expression,t,{resolver:"root"})}) {`];return e.children.forEach(i=>{i.condition?.length?i.condition.forEach(s=>o.push(` case ${s}:`)):o.push(" default:"),o.push(...ht(ht([...i.children.flatMap(s=>r(s,t)),"break;"])))}),o.push("}"),o}function he(e,r,t){return e.type===4?[`${T(e.expression,t,{resolver:"root"})};`]:[]}import{existsSync as Ee}from"fs";import{readFile as cr}from"fs/promises";import{resolve as mr}from"path";import{createSourceFile as lr,forEachChild as fr,getNameOfDeclaration as Ct,isArrayLiteralExpression as ur,isCallExpression as q,isClassDeclaration as dr,isDecorator as Tr,isIdentifier as F,isObjectLiteralExpression as kt,isPropertyAccessExpression as xr,isPropertyAssignment as Nt,isPropertyDeclaration as ke,isStringLiteral as Ce,isTypeReferenceNode as hr,ScriptTarget as Er,SyntaxKind as gt}from"typescript";async function At(e,r,t=process.cwd()){try{let n=Cr(e,t);if(!n)return;let o=await cr(n,"utf8"),i=lr(n,o,Er.Latest,!0),s;return fr(i,a=>{if(!s&&dr(a)){let c=a.name?.text;if(c!==r)return;let m=a.modifiers??[],d=Array.from(m).find(I=>kr(I));if(!d)return;let x=Ar(d);if(!x?.length)return;let f=new Array,A=new Array;a.members.forEach(I=>{if(!ke(I))return;let S=I.modifiers??[],X=!1,z=Array.from(S).find(y=>{let R=Nr(y);return X=!!R.required,R.decorator});if(z){let y=Ct(I),R=y&&F(y)?y.text:void 0;if(R){let G=yr(R,z,X);G&&f.push(G)}return}let Ne=Array.from(S).find(y=>gr(y));if(Ne){let y=Ct(I),R=y&&F(y)?y.text:void 0;if(R){let G=Lr(R,Ne);G&&A.push(G)}}}),s={type:"component",className:c,selectors:x,properties:f,events:A}}}),s}catch(n){console.error(`Failed to extract component metadata from ${e}:`,n);return}}function Cr(e,r){if(e.startsWith(".")){let t=mr(r,e);if(Ee(`${t}.ts`))return t+".ts";if(Ee(`${t}/index.ts`))return`${t}/index.ts`;if(Ee(t))return t}}function kr(e){if(e.kind!==gt.Decorator)return!1;let r=q(e.expression)?e.expression.expression:e.expression;return F(r)&&r.text==="WebComponent"}function Nr(e){if(!Tr(e))return{decorator:!1};let r=e.expression;if(!q(r))return{decorator:!1};let t=r.expression;return F(t)&&t.text==="Property"?{decorator:!0}:xr(t)&&F(t.expression)&&t.expression.text==="Property"&&t.name.text==="required"?{decorator:!0,required:!0}:{decorator:!1}}function gr(e){if(e.kind!==gt.Decorator)return!1;let r=q(e.expression)?e.expression.expression:e.expression;return F(r)&&r.text==="Event"}function Ar(e){try{let r=e.expression;if(!q(r))return[];let t=r.arguments;if(t.length===0)return[];let n=t[0];if(!n||!kt(n))return[];let o=Array.from(n.properties).find(i=>Nt(i)&&F(i.name)&&i.name.text==="selector");return Ir(o.initializer)}catch{return[]}}function Ir(e){return Ce(e)?[e.text]:ur(e)?e.elements?.filter(r=>Ce(r)).map(r=>r.text):[]}function yr(e,r,t){let n=r.expression,o={name:e,required:t,type:ke(r.parent)?It(r.parent.type):"any"};if(q(n)){let i=n.arguments,a=(i.length?i.find(c=>kt(c)):void 0)?.properties?.find(c=>Nt(c)&&F(c.name)&&c.name.text==="alias");a&&Ce(a.initializer)&&(o.alias=a.initializer.text)}return o}function Lr(e,r){let t={name:e,type:"void"};return ke(r.parent)&&(t.type=It(r.parent.type,!0)),t}function It(e,r=!1){let t=r?"void":"any";if(!e||!hr(e))return t;let n=e.typeArguments;return!n||n.length===0?t:n[0].getText()}var ae=class{constructor(r,t){this._input=r;this._ast=t}_input;_ast;_context=new D;_states={3:he,4:he,0:ft,5:dt,8:ut,9:Et,11:xt};async populateImportMetadata(r){let t=this._ast.filter(n=>n.type===11);await Promise.all(t.flatMap(n=>n.specifiers.filter(({imported:o})=>o!=="*").map(async({imported:o,local:i})=>{let s=o==="default"?i:o,a=await At(n.path,s,r);a&&this._context.addImport(a)})))}async generate(r){try{await this.populateImportMetadata(r);let t=this._ast.flatMap(n=>this._processNode(n,this._context));return["function typeCheck() {",...vr(t),"}"].join(`
18
+ `)}catch(t){let n=t,{start:o,end:i}=n.cause;throw new Error(`[Type Checker] ${n.message}
19
+ ${_r(this._input,o,i)}`)}}_processNode=(r,t)=>{let n=this._states[r.type];if(!n)throw new Error(`No transition function for token type ${h[r.type]}`,{cause:r.span});return n(r,this._processNode,t)}};async function aa(e,r,t){let n=new oe(e).tokenize(),o=new se(e,n).parse();return{javascript:new Q(e,o).generate(t),typescript:await new ae(e,o).generate(r)}}export{aa as compile};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xaendar/compiler",
3
- "version": "0.8.0",
3
+ "version": "0.9.1",
4
4
  "description": "A library for transpiling Xaendar Templates into JavaScript code",
5
5
  "author": "Kaitenjo",
6
6
  "license": "MIT",
@@ -13,8 +13,8 @@
13
13
  },
14
14
  "main": "./dist/compiler.js",
15
15
  "dependencies": {
16
- "@xaendar/common": "0.8.0",
17
- "@xaendar/types": "0.8.0",
16
+ "@xaendar/common": "0.9.1",
17
+ "@xaendar/types": "0.9.1",
18
18
  "typescript": "^6.0.3"
19
19
  }
20
20
  }