@xaendar/compiler 0.9.30 → 0.9.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/compiler.js +11 -11
- package/package.json +3 -3
package/dist/compiler.js
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
import{indent as U,slice as
|
|
1
|
+
import{indent as U,slice as lr}from"@xaendar/common";var g=(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))(g||{});var N=class e{parent;_identifiers=new Map;_unresolvableIdentifiers=new Map;constructor(n,t){if(n instanceof e?this.parent=n:t=n,t?.length)for(let r=0;r<t.length;r++){let o=t[r];typeof o=="string"?this._identifiers.set(o,"value"):this._identifiers.set(o[0],o[1])}}addIdentifier(n,t="value"){if(this.hasIdentifier(n))throw new Error(`Identifier "${n}" is already declared in this scope.`);this._identifiers.set(n,t)}addUnresolvableIdentifier(n,t="value"){if(this.hasIdentifier(n))throw new Error(`Identifier "${n}" is already declared in this scope.`);this._unresolvableIdentifiers.set(n,t)}removeIdentifier(n){this._identifiers.delete(n)}removeUnresolvabledIdentifier(n){this._unresolvableIdentifiers.delete(n)}hasIdentifier(n){return this._identifiers.has(n)||(this.parent?.hasIdentifier(n)??!1)}getIdentifierKind(n){return this._identifiers.get(n)??this.parent?.getIdentifierKind(n)}hasUnresolvableIdentifier(n){return this._unresolvableIdentifiers.has(n)||(this.parent?.hasUnresolvableIdentifier(n)??!1)}getUnresolvableIdentifierKind(n){return this._unresolvableIdentifiers.get(n)??this.parent?.getUnresolvableIdentifierKind(n)}};import{indent as G}from"@xaendar/common";import{slice as Ge}from"@xaendar/common";import{forEachChild as Ue,isIdentifier as Ve,isPropertyAccessExpression as nr,isPropertyAssignment as or}from"typescript";var ir=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"]),Z="root";function x(e,n,t){return He(e,e,n,sr(t))}function He(e,n,t,r){if(Ve(e)&&Ke(e,n)){let a=e.text;if(r.skipResolution)return{expression:a};if(t.hasUnresolvableIdentifier(a))return{expression:a,reactive:t.getUnresolvableIdentifierKind(a)==="signal"};if(t.hasIdentifier(a)){let c=t.getIdentifierKind(a),p=`context.get('${a}')`;return c==="signal"?{expression:`${p}()`,reactive:!0}:{expression:p,reactive:!1}}return r.resolver?{expression:`${r.resolver}.${a}`}:{expression:a}}if(!We(e,n))return{expression:e.getText()};let o=e.getSourceFile().text,i={expression:""},s=e.getStart();return Ue(e,a=>{let{expression:c,reactive:p}=He(a,e,t,r);i={expression:`${i.expression}${Ge(o,s,a.getStart())}${c}`,reactive:i.reactive||p},s=a.getEnd()}),{expression:`${i.expression}${Ge(o,s,e.getEnd())}`,reactive:i.reactive}}function We(e,n){if(Ve(e)&&Ke(e,n))return!0;let t=!1;return Ue(e,r=>{t||(t=We(r,e))}),t}function Ke(e,n){return!(nr(n)&&n.name===e||or(n)&&n.name===e||ir.has(e.text)||!e.text)}function qe(e,n,t){return xe(e.tagName,n,t)}function he(e="text",n,t){return xe(e,n,t)}function P(e,n,t){return xe(e,n,t)}function xe(e,n,t){return(n!==Z?`${n}__${e}${t}`:`${e}${t}`).replace(/-/g,"_")}function sr(e){return{resolver:e?.resolver??"this",skipResolution:e?.skipResolution??!1}}function Qe(e,n,t,r,o){let i=ar(e.attributes,r),s=pr(e.events,r),a=qe(e,n,t),c=e.tagName,p={code:[],functionsToProcess:new Map};switch(c){case"svg":p.code.push("context.createElement = createSVGElement");break;case"math":p.code.push("context.createElement = createMATHMLElement")}switch(p.code.push(`const ${a} = _renderElement(${n}, context, ${o}, '${c}',`),i.length?p.code.push(...G(["[",...G(i),"],"])):p.code[p.code.length-1]=`${p.code[p.code.length-1]} [],`,s.length?p.code.push(...G(["[",...G(s),"]"]),");"):p.code[p.code.length-1]=`${p.code[p.code.length-1]} []);`,c){case"svg":case"math":p.code.push("context.createElement = createElement")}return e.children.length&&(p.functionsToProcess.set(`${a}Children`,{fn:{node:e,parentNode:a,context:r,precode:cr(c)},args:[a,"parentContext"]}),p.code.push(`this.${a}Children(${a}, context);`)),p}function ar(e,n){return e?.map(({name:t,value:r})=>{if(typeof r=="string")return`{ name: '${t}', value: () => '${r}', setter: bindAttribute },`;{let{expression:o,reactive:i}=x(r.expression,n);return`{ name: '${t}', value: () => ${o}, setter: ${i?"bindReactiveAttribute":"bindAttribute"} },`}})}function pr(e,n){n.addUnresolvableIdentifier("$event");let t=e.map(r=>{let o=!1,i=r.parameters.map(a=>{let c=x(a,n).expression;return!o&&c==="$event"?(o=!0,`($event) => ${c},`):`() => ${c},`}),s=["{",...G([`name: '${r.name}',`,`handler: '${r.handler}',`,"parameters: ["])];return i.length?s.push(...G([...G(i),"]"]),"},"):(s[s.length-1]=`${s[s.length-1]}]`,s.push("},")),s}).flat();return n.removeIdentifier("$event"),t}function cr(e){switch(e){case"svg":return"context.createElement = createSVGElement;";case"math":return"context.createElement = createMATHMLElement;";default:return""}}function Xe(e,n,t,r){let o={code:[],functionsToProcess:new Map},i=e.iterableSource,s=r.hasIdentifier(i)?i:`this.${i}`,a=he("items",n,t),c=he("i",n,t),p=ee(e,"$index"),u=ee(e,"$first"),d=ee(e,"$last"),f=ee(e,"$even"),y=ee(e,"$odd"),b=new N(r);b.addIdentifier(e.itemAlias);let w=[p,u,d,f,y];for(let E=0;E<w.length;E++)b.addUnresolvableIdentifier(w[E],"signal");let S=P("for",n,t);return o.functionsToProcess.set(S,{fn:{precode:`const { vars, update } = _iterationVariables(context, ${a}, ${c}, '${e.itemAlias}', {
|
|
2
2
|
$index: '${p}',
|
|
3
3
|
$first: '${u}',
|
|
4
4
|
$last: '${d}',
|
|
5
5
|
$even: '${f}',
|
|
6
6
|
$odd: '${y}'
|
|
7
7
|
});
|
|
8
|
-
const { ${e.itemAlias}, ${p}, ${u}, ${d}, ${f}, ${y} } = vars;`,node:e,parentNode:S,context:b,anchor:"anchor",isForBody:!0},args:[S,"parentContext",a,c,"anchor"]}),o.code.push(`_for(${n}, context, () => ${s}, (${e.itemAlias}, ${p}) => ${x(e.trackExpression,b,{skipResolution:!0}).expression}, this.${S}.bind(this));`),o}function ee(e,n){return e.implicitAliases.get(n)??n}import{indent as K}from"@xaendar/common";function je(e,n,t,r){let o=new N(r),i={code:[],functionsToProcess:new Map};i.code.push(`_if(${n}, context, [`);let s=P("if",n,t);i.code.push(...K(["{",...K([`condition: () => ${x(e.conditionNode,r).expression},`,`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 p=new N(r),u=P("elseIf",n,`${t}_${c}`),d=a.conditionNode;i.code.push(...K(["{",...K([`condition: () => ${x(d,r).expression},`,`block: this.${u}.bind(this)`]),"},"])),i.functionsToProcess.set(u,{fn:{node:a,parentNode:n,context:p,anchor:"anchor"},args:[n,"parentContext","anchor"]}),a=a.alternate,c++}if(a){let p=new N(r),u=P("else",n,t);i.code.push(...K(["{",...K([`block: this.${u}.bind(this)`]),"},"])),i.functionsToProcess.set(u,{fn:{node:a,parentNode:n,context:p,anchor:"anchor"},args:[n,"parentContext","anchor"]})}return i.code.push("]);"),i}import{indent as ze}from"@xaendar/common";function Ye(e,n,t,r){let o={code:[],functionsToProcess:new Map};o.code.push(`_switch(${n}, context, () => ${x(e.expression,r).expression}, [`);let i=e.children;for(let s=0;s<i.length;s++){let a=i[s],c=new N(r),p=a.condition?P("case",n,`${t}_${s}`):P("default",n,t);o.functionsToProcess.set(p,{fn:{node:a,parentNode:p,context:c},args:[p,"parentContext","anchor"]});let u=`this.${p}.bind(this)`;o.code.push(...ze(["{",...ze([`condition: ${a.condition?`[${a.condition.join(", ")}]`:"null"},`,`block: ${u}`]),"},"]))}return o.code.push("])"),o}function Ee(e,n,t,r){return{code:[`${e.type===3?`_renderLiteralText(${n}, context, '${e.value}');`:`_renderText(${n}, context, () => ${x(e.expression,r).expression});`}`]}}function Je(e,n,t,r){}var oe=class{constructor(n,t){this._input=n;this._ast=t}_input;_ast;_nodeToProcess=new Map;_states={3:Ee,4:Ee,0:Qe,5:je,8:Xe,9:Ye,11:Je};generate(n,t){let r=o=>{if(o)for(let[i,s]of o.entries())this._nodeToProcess.set(i,s)};try{this._nodeToProcess.clear();let o=new N;for(let s=0;s<t.length;s++)o.addUnresolvableIdentifier(t[s]
|
|
8
|
+
const { ${e.itemAlias}, ${p}, ${u}, ${d}, ${f}, ${y} } = vars;`,node:e,parentNode:S,context:b,anchor:"anchor",isForBody:!0},args:[S,"parentContext",a,c,"anchor"]}),o.code.push(`_for(${n}, context, () => ${s}, (${e.itemAlias}, ${p}) => ${x(e.trackExpression,b,{skipResolution:!0}).expression}, this.${S}.bind(this));`),o}function ee(e,n){return e.implicitAliases.get(n)??n}import{indent as K}from"@xaendar/common";function je(e,n,t,r){let o=new N(r),i={code:[],functionsToProcess:new Map};i.code.push(`_if(${n}, context, [`);let s=P("if",n,t);i.code.push(...K(["{",...K([`condition: () => ${x(e.conditionNode,r).expression},`,`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 p=new N(r),u=P("elseIf",n,`${t}_${c}`),d=a.conditionNode;i.code.push(...K(["{",...K([`condition: () => ${x(d,r).expression},`,`block: this.${u}.bind(this)`]),"},"])),i.functionsToProcess.set(u,{fn:{node:a,parentNode:n,context:p,anchor:"anchor"},args:[n,"parentContext","anchor"]}),a=a.alternate,c++}if(a){let p=new N(r),u=P("else",n,t);i.code.push(...K(["{",...K([`block: this.${u}.bind(this)`]),"},"])),i.functionsToProcess.set(u,{fn:{node:a,parentNode:n,context:p,anchor:"anchor"},args:[n,"parentContext","anchor"]})}return i.code.push("]);"),i}import{indent as ze}from"@xaendar/common";function Ye(e,n,t,r){let o={code:[],functionsToProcess:new Map};o.code.push(`_switch(${n}, context, () => ${x(e.expression,r).expression}, [`);let i=e.children;for(let s=0;s<i.length;s++){let a=i[s],c=new N(r),p=a.condition?P("case",n,`${t}_${s}`):P("default",n,t);o.functionsToProcess.set(p,{fn:{node:a,parentNode:p,context:c},args:[p,"parentContext","anchor"]});let u=`this.${p}.bind(this)`;o.code.push(...ze(["{",...ze([`condition: ${a.condition?`[${a.condition.join(", ")}]`:"null"},`,`block: ${u}`]),"},"]))}return o.code.push("])"),o}function Ee(e,n,t,r){return{code:[`${e.type===3?`_renderLiteralText(${n}, context, '${e.value}');`:`_renderText(${n}, context, () => ${x(e.expression,r).expression});`}`]}}function Je(e,n,t,r){}var oe=class{constructor(n,t){this._input=n;this._ast=t}_input;_ast;_nodeToProcess=new Map;_states={3:Ee,4:Ee,0:Qe,5:je,8:Xe,9:Ye,11:Je};generate(n,t){let r=o=>{if(o)for(let[i,s]of o.entries())this._nodeToProcess.set(i,s)};try{this._nodeToProcess.clear();let o=new N;for(let s=0;s<t.length;s++)o.addUnresolvableIdentifier(`this.${t[s]}`,"signal");let i=["_render() {",...U([`const ${Z} = this._root;`,"const context = new Context(this, { createElement: document.createElement.bind(document), get: () => undefined });"])];n&&i.push(U(`${Z}.adoptedStyleSheets = [${n}];`));for(let s=0;s<this._ast.length;s++){let a=this._processNode(this._ast[s],Z,s.toString(),o,null);if(a){let{code:c,functionsToProcess:p}=a;r(p),i.push(...U(c))}}i.push(...U(["return context;"]),"}");for(let[s,a]of this._nodeToProcess.entries()){let{node:c,parentNode:p,context:u,precode:d,anchor:f}=a.fn;i.push(`
|
|
9
9
|
${s}(${a.args?.join(", ")}) {`,...U(["const context = new Context(this, parentContext);"])),d&&i.push(U(d)),i.push(...U([...c.children.map((y,b)=>{let w=this._processNode(y,p,b.toString(),u,f??null);if(w){let{code:S,functionsToProcess:E}=w;return r(E),S}return""}).flat(),a.fn.isForBody?"return { context, update };":"return context;"]),"}")}return i.join(`
|
|
10
10
|
`)}catch(o){let i=o,{start:s,end:a}=i.cause;throw new Error(`[Generator] ${i.message}
|
|
11
|
-
----> ${
|
|
12
|
-
Found character ${e.currentChar.value}`}let s=i?39:34;for(;t;)e.peek()===s?(e.advance(),t=!1,o={state:"text",tokens:[{type:23,parts:[r]}]}):(e.advance(),r=`${r}${e.currentChar.value}`);return o}function lt(e,n){let t=!0,r="",o=e.currentChar.index+1,i={state:"import-path",tokens:[]};if(e.skipSpaces(),e.advance(),e.currentChar.code!==123)throw"Expected { after @import";for(;t;)switch(e.peek()){case 32:e.skipSpaces(),r&&e.peek()!==44&&e.peek()!==125&&(r=`${r}`);break;case 44:ct(i,e,r,o),r="",o=e.currentChar.index+1;break;case 125:ct(i,e,r,o),t=!1;break;default:e.advance(),r=`${r}${e.currentChar.value}`}return i}function ct(e,n,t,r){let o=n.currentChar.index+1;n.advance(),e.tokens.push({type:22,parts:[t],span:{start:r,end:o}})}function mt(e,n){let t=!0,r="",o=1,i;for(;t;)switch(e.peek()){case 123:o++,r=ye(e,r);break;case 125:if(o--,o===0){e.advance(),r=r.trimEnd();let s=n.history.pop(),a;switch(s){case"attribute":if(e.peek()!==34)throw`Interpolation must end with double quotes '"', found '${String.fromCharCode(e.peek())}'`;e.advance(),a="tag-body";break;case"text":a="text";break;default:throw`Unexpected state '${s}' after interpolation expression`}i={state:a,tokens:[{type:11,parts:[r]}],popState:!0},t=!1}else r=ye(e,r);break;default:r=ye(e,r)}return i}function ye(e,n){return e.advance(1),`${n}${e.currentChar.value}`}function ut(e,n){let t=!0,r="`",o;for(e.advance();t;)switch(e.peek()){case 96:if(r=ft(e,r),e.peek()===125){e.advance();let i=n.history.pop(),s;switch(i){case"attribute":if(e.peek()!==34)throw`Attribute interpolation expression must end with double quotes '"', found '${String.fromCharCode(e.peek())}'`;e.advance(),s="tag-body";break;case"text":s="text";break;default:throw`Unexpected state '${i}' after interpolation literal`}o={state:s,tokens:[{type:10,parts:[r]}],popState:!0},t=!1}else r=`${r}${e.currentChar.value}`;break;default:r=ft(e,r)}return o}function ft(e,n){return e.advance(),`${n}${e.currentChar.value}`}function dt(e,n){return e.advance(),e.skipSpaces(),e.peek()===96?{state:"interpolation-literal"}:{state:"interpolation-expression"}}function Tt(e,n){let t=!0,r;for(;t;)switch(e.peek()){case 64:r={state:"event"},t=!1;break;case 32:e.skipSpaces();break;case 62:case 47:r={state:"tag-open-end"},t=!1;break;default:r={state:"attribute"},t=!1}return r}function ht(e,n){let t=!0,r="",o;for(e.advance(2),e.skipSpaces();t;)switch(e.peek()){case 62:if(!r)throw"Tag close name cannot be empty";e.advance(),o={state:"text",tokens:[{type:4,parts:[r]}]},t=!1;break;case 32:throw"Tag close name cannot contain spaces";default:e.advance(),r=`${r}${e.currentChar.value}`}return o}function xt(e,n){let t;if(e.peek()===62)e.advance(),t={state:"text",tokens:[{type:3,parts:[]}]};else{e.advance();let r=e.peek();if(r===62)e.advance(),t={state:"text",tokens:[{type:2,parts:[]}]};else throw`Unexpected character '${String.fromCharCode(r)}' after '/': expected '>' to close self-closing tag`}return t}function Et(e,n){let t=!0,r="",o;for(e.advance(),e.skipSpaces();t;)switch(e.peek()){case 32:case 47:case 62:if(!r)throw"Tag name cannot be empty ";o={state:"tag-body",tokens:[{type:1,parts:[r]}]},t=!1;break;default:e.advance(),r=`${r}${e.currentChar.value}`}return o}function Ct(e){return/\S/.test(e)}function gt(e,n){let t=!0,r="",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:n.history[n.history.length-1]==="flow-control-block"?(e.advance(),o={state:"text",tokens:[{type:21}],popState:!0},t=!1):(e.advance(),r=`${r}${e.currentChar.value}`);break;case 10:case 13:e.advance();break;default:e.advance(),r=`${r}${e.currentChar.value}`}return o.tokens??=Ct(r)?[{type:0,parts:[r]}]:void 0,o}import{slice as
|
|
13
|
-
`&&n.push(r+1);return n}};var pe=class extends D{_currentChar={code:0,index:-1,value:""};get currentChar(){return this._currentChar}_peekCache=new Map;constructor(n){super(n)}advance(n=1){if(n<1)throw`${n} is not a valid value. Please enter a number equal or greater than 1`;let t=this._currentChar.index+n;if(t>=this.input.length)this._currentChar.code=0,this._currentChar.index=-1,this._currentChar.value="",this.throwEOFError();else{for(let r=this._currentChar.index+1;r<=t;r++)this._peekCache.delete(r);this._currentChar.index=t,this._currentChar.value=this.input[t],this._currentChar.code=this.input.charCodeAt(t)}}peekMatch(n,t){if(typeof n=="string"){let i=this.peek(n.length);for(let s=0;s<n.length;s++)if(i[s]!==n.charCodeAt(s))return!1;return!0}let r=this._currentChar.index+1,o=
|
|
14
|
-
---> ${y}${b}${w}`}}return this._tokens}withTokenSpans(n,t){return n.map(r=>({...r,span:r.span??t}))}};import{slice as
|
|
15
|
-
`,"");return{node:o}}function kt(e,n,t){if(!
|
|
16
|
-
---> ${
|
|
11
|
+
----> ${lr(this._input,s,a)}`)}}_processNode(n,t,r,o,i){let s=this._states[n.type];if(!s)throw new Error(`No transition function for ASTNode of type ${g[n.type]}`,{cause:n.span});return s(n,t,r,o,i)}};import{slice as Le,Stack as Tr}from"@xaendar/common";var T=(m=>(m[m.TEXT=0]="TEXT",m[m.TAG_OPEN_NAME=1]="TAG_OPEN_NAME",m[m.TAG_SELF_CLOSE=2]="TAG_SELF_CLOSE",m[m.TAG_OPEN_END=3]="TAG_OPEN_END",m[m.TAG_CLOSE_NAME=4]="TAG_CLOSE_NAME",m[m.ATTRIBUTE=5]="ATTRIBUTE",m[m.ATTRIBUTE_VALUE=6]="ATTRIBUTE_VALUE",m[m.EVENT=7]="EVENT",m[m.EVENT_HANDLER=8]="EVENT_HANDLER",m[m.EVENT_PARAMETER=9]="EVENT_PARAMETER",m[m.INTERPOLATION_LITERAL=10]="INTERPOLATION_LITERAL",m[m.INTERPOLATION_EXPRESSION=11]="INTERPOLATION_EXPRESSION",m[m.IF=12]="IF",m[m.FOR=13]="FOR",m[m.ELSE=14]="ELSE",m[m.ELSE_IF=15]="ELSE_IF",m[m.SWITCH=16]="SWITCH",m[m.CASE=17]="CASE",m[m.DEFAULT=18]="DEFAULT",m[m.CONDITION=19]="CONDITION",m[m.BLOCK_OPEN=20]="BLOCK_OPEN",m[m.BLOCK_CLOSE=21]="BLOCK_CLOSE",m[m.IMPORT=22]="IMPORT",m[m.IMPORT_PATH=23]="IMPORT_PATH",m[m.EOF=24]="EOF",m))(T||{});function Ze(e,n){let t=!0,r="",o;for(;t;)e.peek()===34?(e.advance(),t=!1,o={state:"tag-body",tokens:[{type:6,parts:[r]}],popState:!0}):(e.advance(),r=`${r}${e.currentChar.value}`);return o}function et(e,n){let t=!0,r="",o;for(;t;)switch(e.peek()){case 32:e.advance(),t=!1,o={state:"tag-body",tokens:[{type:5,parts:[r]}]};break;case 62:case 47:t=!1,o={state:"tag-body",tokens:[{type:5,parts:[r]}]};break;case 61:if(!r)throw new Error("Attribute cannot start with '='");if(e.advance(),e.peek()!==34)throw`Attribute value must start with double quotes '"'`;e.advance(),t=!1,o={state:e.peek()===123?"interpolation":"attribute-value",pushState:!0,tokens:[{type:5,parts:[r]}]};break;case 34:case 39:if(!r)throw new Error(`Attribute cannot start with ' or "`);default:e.advance(),r=`${r}${e.currentChar.value}`}return o}function ie(e,n){if(e.skipSpaces(),e.peek()!==40)throw`Expected '(' but got '${String.fromCharCode(e.peek())}'`;e.advance();let t="",r=1;for(;r>0;)switch(e.peek()){case 40:r++,t=ge(e,t);break;case 41:if(r--,!r){e.advance();break}t=ge(e,t);break;default:t=ge(e,t)}return t}function ge(e,n){return e.advance(),`${n}${e.currentChar.value}`}function tt(e,n){let t=ie(e,n);return e.skipSpaces(),{state:e.peekMatch("@case")?"flow-control":"flow-control-block",tokens:[{type:19,parts:[t]}],popState:!0}}function rt(e,n){return{state:"flow-control-block",tokens:[{type:19,parts:[ie(e,n)]}],popState:!0}}function nt(e,n){let t=!0,r="",o;for(;t;)switch(e.peek()){case 32:throw"No spaces are allowed in event handler name";case 40:if(!r)throw"Event handler cannot be empty";let i="parameter";e.advance(),e.peekMatch(')"')&&(i="tag-body",e.advance(2)),o={state:i,tokens:[{type:8,parts:[r]}]},t=!1;break;default:e.advance(),r=`${r}${e.currentChar.value}`}return o}function ot(e,n){let t=!0,r="",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:r=Ne(e,r),o?(o===e.currentChar.value||o==="["&&e.currentChar.value==="]"||o==="{"&&e.currentChar.value==="}")&&(o=""):o=e.currentChar.value;break;case 44:if(o)r=Ne(e,r);else{let a=e.currentChar.index+1;s.tokens.push({type:9,parts:[r],span:{start:i,end:a}}),e.advance(),e.skipSpaces(),r="",i=e.currentChar.index+1}break;case 41:if(e.advance(),e.peek()!==34)throw"Event must be included in Double Quotes";if(e.advance(),!o){let a=e.currentChar.index+1;s.tokens.push({type:9,parts:[r],span:{start:i,end:a}}),t=!1;break}r=`${r}${e.currentChar.value}`;break;default:r=Ne(e,r)}return s}function Ne(e,n){return e.advance(),`${n}${e.currentChar.value}`}function it(e,n){let t=!0,r="",o;for(e.advance();t;)switch(e.peek()){case 32:throw"No spaces are allowed in event name";case 61:if(!r)throw"Event name cannot be empty";if(e.advance(),e.peek()!==34)throw"Event handler must be included in Double Quotes";e.advance(),o={state:"event-handler",tokens:[{type:7,parts:[r]}]},t=!1;break;default:e.advance(),r=`${r}${e.currentChar.value}`}return o}function st(e,n){let t;if(e.advance(),e.peekMatch("for "))e.advance(4),t={state:"flow-control-condition",tokens:[{type:13}],pushState:!0};else if(e.peekMatch("if "))e.advance(2),t={state:"flow-control-condition",tokens:[{type:12}],pushState:!0};else if(e.peekMatch("else if "))e.advance(8),t={state:"flow-control-condition",tokens:[{type:15}],pushState:!0};else if(e.peekMatch("else "))e.advance(5),t={state:"flow-control-block",tokens:[{type:14}]};else if(e.peekMatch("switch "))e.advance(7),t={state:"flow-control-condition",tokens:[{type:16}],pushState:!0};else if(e.peekMatch("case "))e.advance(5),t={state:"case-flow-control-condition",tokens:[{type:17}],pushState:!0};else if(e.peekMatch("default "))e.advance(8),t={state:"flow-control-block",tokens:[{type:18}]};else if(e.peekMatch("import "))e.advance(7),t={state:"import"};else throw"Unknown flow-control keyword";return t}function at(e,n){if(e.skipSpaces(),e.peek()!==123)throw`Expected '{' but got '${String.fromCharCode(e.peek())}'`;return e.advance(),{state:"text",tokens:[{type:20}],pushState:!0}}function pt(e,n){let t=!0,r="",o,i=!1;if(e.skipSpaces(),!e.peekMatch("from"))throw"Expected 'from' keyword after import list";switch(e.advance(4),e.skipSpaces(),e.advance(),e.currentChar.code){case 39:i=!0;break;case 34:break;default:throw`Import statement must start with ' or ".
|
|
12
|
+
Found character ${e.currentChar.value}`}let s=i?39:34;for(;t;)e.peek()===s?(e.advance(),t=!1,o={state:"text",tokens:[{type:23,parts:[r]}]}):(e.advance(),r=`${r}${e.currentChar.value}`);return o}function lt(e,n){let t=!0,r="",o=e.currentChar.index+1,i={state:"import-path",tokens:[]};if(e.skipSpaces(),e.advance(),e.currentChar.code!==123)throw"Expected { after @import";for(;t;)switch(e.peek()){case 32:e.skipSpaces(),r&&e.peek()!==44&&e.peek()!==125&&(r=`${r}`);break;case 44:ct(i,e,r,o),r="",o=e.currentChar.index+1;break;case 125:ct(i,e,r,o),t=!1;break;default:e.advance(),r=`${r}${e.currentChar.value}`}return i}function ct(e,n,t,r){let o=n.currentChar.index+1;n.advance(),e.tokens.push({type:22,parts:[t],span:{start:r,end:o}})}function mt(e,n){let t=!0,r="",o=1,i;for(;t;)switch(e.peek()){case 123:o++,r=ye(e,r);break;case 125:if(o--,o===0){e.advance(),r=r.trimEnd();let s=n.history.pop(),a;switch(s){case"attribute":if(e.peek()!==34)throw`Interpolation must end with double quotes '"', found '${String.fromCharCode(e.peek())}'`;e.advance(),a="tag-body";break;case"text":a="text";break;default:throw`Unexpected state '${s}' after interpolation expression`}i={state:a,tokens:[{type:11,parts:[r]}],popState:!0},t=!1}else r=ye(e,r);break;default:r=ye(e,r)}return i}function ye(e,n){return e.advance(1),`${n}${e.currentChar.value}`}function ut(e,n){let t=!0,r="`",o;for(e.advance();t;)switch(e.peek()){case 96:if(r=ft(e,r),e.peek()===125){e.advance();let i=n.history.pop(),s;switch(i){case"attribute":if(e.peek()!==34)throw`Attribute interpolation expression must end with double quotes '"', found '${String.fromCharCode(e.peek())}'`;e.advance(),s="tag-body";break;case"text":s="text";break;default:throw`Unexpected state '${i}' after interpolation literal`}o={state:s,tokens:[{type:10,parts:[r]}],popState:!0},t=!1}else r=`${r}${e.currentChar.value}`;break;default:r=ft(e,r)}return o}function ft(e,n){return e.advance(),`${n}${e.currentChar.value}`}function dt(e,n){return e.advance(),e.skipSpaces(),e.peek()===96?{state:"interpolation-literal"}:{state:"interpolation-expression"}}function Tt(e,n){let t=!0,r;for(;t;)switch(e.peek()){case 64:r={state:"event"},t=!1;break;case 32:e.skipSpaces();break;case 62:case 47:r={state:"tag-open-end"},t=!1;break;default:r={state:"attribute"},t=!1}return r}function ht(e,n){let t=!0,r="",o;for(e.advance(2),e.skipSpaces();t;)switch(e.peek()){case 62:if(!r)throw"Tag close name cannot be empty";e.advance(),o={state:"text",tokens:[{type:4,parts:[r]}]},t=!1;break;case 32:throw"Tag close name cannot contain spaces";default:e.advance(),r=`${r}${e.currentChar.value}`}return o}function xt(e,n){let t;if(e.peek()===62)e.advance(),t={state:"text",tokens:[{type:3,parts:[]}]};else{e.advance();let r=e.peek();if(r===62)e.advance(),t={state:"text",tokens:[{type:2,parts:[]}]};else throw`Unexpected character '${String.fromCharCode(r)}' after '/': expected '>' to close self-closing tag`}return t}function Et(e,n){let t=!0,r="",o;for(e.advance(),e.skipSpaces();t;)switch(e.peek()){case 32:case 47:case 62:if(!r)throw"Tag name cannot be empty ";o={state:"tag-body",tokens:[{type:1,parts:[r]}]},t=!1;break;default:e.advance(),r=`${r}${e.currentChar.value}`}return o}function Ct(e){return/\S/.test(e)}function gt(e,n){let t=!0,r="",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:n.history[n.history.length-1]==="flow-control-block"?(e.advance(),o={state:"text",tokens:[{type:21}],popState:!0},t=!1):(e.advance(),r=`${r}${e.currentChar.value}`);break;case 10:case 13:e.advance();break;default:e.advance(),r=`${r}${e.currentChar.value}`}return o.tokens??=Ct(r)?[{type:0,parts:[r]}]:void 0,o}import{slice as dr}from"@xaendar/common";var D=class{constructor(n){this.input=n}input;getPositionFromCharacterIndex(n){let t=this.getLineStarts(),r=0,o=t.length-1;for(;r<o;){let a=Math.ceil((r+o)/2);t[a]<=n?r=a:o=a-1}let i=r,s=n-t[i];return`[Ln ${i+1}, Col ${s+1}]`}getLineStarts(){let n=[0],t=this.input;for(let r=0;r<t.length;r++)t[r]===`
|
|
13
|
+
`&&n.push(r+1);return n}};var pe=class extends D{_currentChar={code:0,index:-1,value:""};get currentChar(){return this._currentChar}_peekCache=new Map;constructor(n){super(n)}advance(n=1){if(n<1)throw`${n} is not a valid value. Please enter a number equal or greater than 1`;let t=this._currentChar.index+n;if(t>=this.input.length)this._currentChar.code=0,this._currentChar.index=-1,this._currentChar.value="",this.throwEOFError();else{for(let r=this._currentChar.index+1;r<=t;r++)this._peekCache.delete(r);this._currentChar.index=t,this._currentChar.value=this.input[t],this._currentChar.code=this.input.charCodeAt(t)}}peekMatch(n,t){if(typeof n=="string"){let i=this.peek(n.length);for(let s=0;s<n.length;s++)if(i[s]!==n.charCodeAt(s))return!1;return!0}let r=this._currentChar.index+1,o=dr(this.input,r,r+t);return n.test(o)}peek(n,t){let r=this._peekCache,o=typeof n=="number"?n:1,i=(typeof n=="object"?n:t)?.offset??0;return o===1?this.peekOneChar(this._currentChar.index+i+1,r):this.peekMany(o+i,r)}skipSpaces(){for(;this.peek()===32||this.peek()===10||this.peek()===13;)this.advance()}peekMany(n,t){let r=new Array,o=this._currentChar.index+1;for(let i=o;i<o+n;i++)r.push(this.peekOneChar(i,t));return r}peekOneChar(n,t){if(t.has(n))return t.get(n);n>=this.input.length&&this.throwEOFError();let r=this.input.charCodeAt(n);return t.set(n,r),r}throwEOFError(){throw new Error("",{cause:0})}};var ce=class{constructor(n){this._input=n;this._cursor=new pe(this._input)}_input;_cursor;_state="text";_stack=new Tr;_tokens=new Array;_states={text:gt,"tag-open-name":Et,"tag-body":Tt,"tag-open-end":xt,"tag-close":ht,attribute:et,"attribute-value":Ze,event:it,"event-handler":nt,parameter:ot,"flow-control":st,"flow-control-condition":rt,"case-flow-control-condition":tt,"flow-control-block":at,interpolation:dt,"interpolation-expression":mt,"interpolation-literal":ut,import:lt,"import-path":pt};tokenize(){let n=!1,t=this._cursor,r=-1;for(;!n;)try{r=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 p=t.currentChar.index+1;this._tokens.push(...this.withTokenSpans(s,{start:r,end:p}))}c&&this._stack.push(this._state),a&&this._stack.pop(),this._state=i}catch(o){let i=o instanceof Error;if(i&&o.cause===0)n=!0;else{let a=r,c=r,p=!1;for(;!p;){let E=this._input.charCodeAt(c);E===10||E===13||a-c>15&&E===32?(a=c+1,p=!0):c--}let u=t.currentChar.index,d=u<=r?u+2:u+1,f=d;for(c=f,p=!1;!p;){let E=this._input.charCodeAt(c);E===10||E===13||c-f>15&&E===32?(f=c-1,p=!0):c++}let y=Le(this._input,a,r).replace(/^\s+/,""),b=`\x1B[4m${Le(this._input,r,d)}\x1B[0m`,w=Le(this._input,d+1,f).replace(/\s+$/,""),S=i?o.message:o;throw`${t.getPositionFromCharacterIndex(d+1)} - ${S}
|
|
14
|
+
---> ${y}${b}${w}`}}return this._tokens}withTokenSpans(n,t){return n.map(r=>({...r,span:r.span??t}))}};import{slice as Rr}from"@xaendar/common";var le=class extends D{constructor(t,r){super(t);this._tokens=r}_tokens;_currentToken={value:{type:24},index:-1};getCurrentToken(){return this._currentToken}advance(t=1){if(t<1)throw`${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:24},this._currentToken.index=-1):(this._currentToken.index=r,this._currentToken.value=this._tokens[r])}peek(t,r){let o=typeof t=="number"?t:1,i=(typeof t=="object"?t:r)?.offset??0;return o===1?this.peekOneToken(this._currentToken.index+i+1):this.peekMany(o+i)}peekMany(t){let r=new Array,o=this._currentToken.index+1;for(let i=o;i<o+t;i++)r.push(this.peekOneToken(i));return r}peekOneToken(t){return t<this._tokens.length?this._tokens[t]:{type:24}}};import{ScriptTarget as hr,SyntaxKind as l,createSourceFile as xr,forEachChild as Er}from"typescript";function R(e){let n="const x = ",o=xr("expression.ts",`${n}${e}`,hr.ESNext,!0).statements[0].declarationList.declarations[0].initializer,i=new Array;if(kt(o,n.length,i),i.length)throw i.reduce((s,a)=>`${s}${a.message}
|
|
15
|
+
`,"");return{node:o}}function kt(e,n,t){if(!Cr(e))throw gr(e);if(Er(e,r=>kt(r,n,t)),t.length)throw t[0].message}function Cr(e){switch(e.kind){case l.StringLiteral:case l.NumericLiteral:case l.BigIntLiteral:case l.TrueKeyword:case l.FalseKeyword:case l.NullKeyword:case l.UndefinedKeyword:case l.Identifier:case l.PropertyAccessExpression:case l.ElementAccessExpression:case l.CallExpression:case l.BinaryExpression:case l.EqualsEqualsToken:case l.EqualsEqualsEqualsToken:case l.ExclamationEqualsToken:case l.ExclamationEqualsEqualsToken:case l.LessThanToken:case l.LessThanEqualsToken:case l.GreaterThanToken:case l.GreaterThanEqualsToken:case l.PlusToken:case l.MinusToken:case l.AsteriskToken:case l.SlashToken:case l.PercentToken:case l.AsteriskAsteriskToken:case l.AmpersandAmpersandToken:case l.BarBarToken:case l.QuestionQuestionToken:case l.QuestionDotToken:case l.QuestionToken:case l.ColonToken:case l.AmpersandToken:case l.BarToken:case l.CaretToken:case l.LessThanLessThanToken:case l.GreaterThanGreaterThanToken:case l.GreaterThanGreaterThanGreaterThanToken:case l.InstanceOfKeyword:case l.InKeyword:case l.PrefixUnaryExpression:case l.PostfixUnaryExpression:case l.TypeOfExpression:case l.VoidExpression:case l.ConditionalExpression:case l.ParenthesizedExpression:case l.TemplateExpression:case l.NoSubstitutionTemplateLiteral:case l.TemplateHead:case l.TemplateMiddle:case l.TemplateTail:case l.TemplateSpan:case l.ArrayLiteralExpression:case l.ObjectLiteralExpression:case l.PropertyAssignment:case l.ShorthandPropertyAssignment:case l.SpreadAssignment:case l.SpreadElement:case l.TaggedTemplateExpression:case l.SyntaxList:return!0;default:return!1}}function gr(e){switch(e.kind){case l.AwaitExpression:return"'await' is not allowed inside template expressions.";case l.YieldExpression:return"'yield' is not allowed inside template expressions.";case l.NewExpression:return"'new' is not allowed inside template expressions.";case l.ArrowFunction:case l.FunctionExpression:return"Function expressions are not allowed inside template expressions.";case l.BinaryExpression:return kr(e.operatorToken.kind)?"Assignments are not allowed inside template expressions. Use @const to declare local template variables instead.":`'${l[e.kind]}' is not allowed inside template expressions.`;default:return`'${l[e.kind]}' is not allowed inside template expressions.`}}function kr(e){return e>=l.FirstAssignment&&e<=l.LastAssignment}function te(e,n,t){let r=t.span.start;return e.advance(),{type:4,expression:R(t.parts[0]).node,span:{start:r,end:e.getCurrentToken().value.span.end}}}function Nt(e,n,t){let r=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:r,end:e.getCurrentToken().value.span.end}};if(i.type===11||i.type===10){let s=te(e,n,i);return{type:1,name:o,value:s,span:{start:r,end:e.getCurrentToken().value.span.end}}}if(i.type!==6)throw`Attribute value missing for ${o} in: ${o}`;return e.advance(),{type:1,name:o,value:i.parts[0],span:{start:r,end:e.getCurrentToken().value.span.end}}}function yt(e,n,t){let r=t.span.start;e.advance();let o=t.parts[0],i=e.peek();if(i.type!==8)throw`Invalid event format for ${o}`;e.advance();let s=e.getCurrentToken().value.span.end,a=new Array;for(;e.peek().type===9;)e.advance(),a.push(R(e.getCurrentToken().value.parts[0]).node),s=e.getCurrentToken().value.span.end;return{type:2,name:o,handler:i.parts[0],parameters:a,span:{start:r,end:s}}}function At(e,n,t){e.advance();let r=t.parts[0],o=new Array,i=new Array,s=!0;for(;s;){let p=e.peek();switch(p.type){case 5:o.push(Nt(e,n,p));break;case 7:i.push(yt(e,n,p));break;default:s=!1}}let a=e.peek().type;switch(a){case 3:e.advance();break;case 2:return e.advance(),{type:0,tagName:r,attributes:o,events:i,children:[]};default:throw new Error(`Unexpected State ${a}`)}let c=new Array;for(;!Nr(e,r);){let p=n();p&&c.push(p)}return e.advance(),{type:0,tagName:r,attributes:o,events:i,children:c}}function Nr(e,n){let t=e.peek();switch(t.type){case 24:throw new Error(`Expected closing tag ${n} while file is over`);case 4:let r=t.parts[0];if(r===n)return!0;throw`Expected closing tag ${n}, found ${r}`;default:return!1}}import{slice as re}from"@xaendar/common";import{createSourceFile as yr,isExpressionStatement as Ar,isIdentifier as Ir,ScriptTarget as Lr}from"typescript";function B(e,n){let t=new Array;for(;e.peek().type!==21;){let r=n();r&&t.push(r)}return e.advance(),t}function It(e,n,t){e.advance();let r=e.peek();if(r.type!==19)throw`Expected CONDITION after FOR, got ${T[r.type]}`;let o=vr(r.parts[0],0);e.advance(2);let i=B(e,n);return{type:8,...o,children:i}}function vr(e,n){let t=br(e);if(t.length<2)throw'@for requires at least "item of iterable; track expr".';let r=t[0].trim(),o=r.indexOf(" of ");if(o===-1)throw'@for expression must be in the form "item of iterable".';let i=re(r,0,o).trim(),s=re(r,o+4).trim();if(!Lt(i))throw`'${i}' is not a valid item alias.`;let a=R(s),c=t[1].trim();if(!c.startsWith("track "))throw'Second section of @for must start with "track".';let p=re(c,6).trim(),u=R(p),d=new Map;if(t.length>=3&&t[2]!==void 0){let f=t[2].trim(),y=n+e.indexOf(t[2]);Sr(f,y,d)}return{itemAlias:i,iterableExpression:a.node,iterableSource:s,trackExpression:u.node,trackSource:p,implicitAliases:d}}function Sr(e,n,t){let r=e.split(","),o=0,i=new Set(["$index","$last","$first","$even","$odd"]);for(let s=0;s<r.length;s++){let a=r[s],c=a.trim(),p=c.indexOf("=");if(p===-1)throw`Invalid alias declaration '${c}'. Expected '$implicit = alias'.`;o+=a.length+1;let u=re(c,0,p).trim(),d=re(c,p+1).trim();if(!(y=>i.has(y))(d))throw`'${d}' is not a known implicit variable. Known variables: ${[...i].join(", ")}.`;if(o+=a.length+1,!Lt(u))throw`'${u}' is not a valid alias identifier.`;if(o+=a.length+1,t.has(d))throw`'${d}' is already aliased in this @for expression.`;t.set(d,u),o+=a.length+1}}function br(e){let n=new Array,t="",r=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==="{"){r++,t+=s;continue}if(s===")"||s==="]"||s==="}"){r--,t+=s;continue}if(s===";"&&r===0){n.push(t),t="";continue}t+=s}}return t.trim().length&&n.push(t),n}function Lt(e){if(!e.length)return!1;let t=yr("__id.ts",e,Lr.ESNext,!1).statements[0];return!!t&&Ar(t)&&Ir(t.expression)&&t.expression.text===e}function vt(e,n,t){return St(e,n,t)}function _r(e,n,t){switch(t.type){case 15:return St(e,n,t);case 14:let r=t.span.start;e.advance(2);let o=B(e,n);return{type:6,children:o,span:{start:r,end:e.getCurrentToken().value.span.end}}}}function St(e,n,t){let r=t.span.start;e.advance();let o=e.peek();if(o.type!==19)throw`Expected CONDITION after ${T[t.type]}, got ${T[o.type]}`;e.advance(2);let i=o.parts[0],s=R(i),a=B(e,n),c=null,p=e.peek();return(p.type===15||p.type===14)&&(c=_r(e,n,p)),{type:t.type===12?5:7,condition:i,conditionNode:s.node,children:a,alternate:c,span:{start:r,end:e.getCurrentToken().value.span.end}}}function bt(e,n,t){let r=new Array;for(;e.peek().type===22;){e.advance();let o=e.getCurrentToken().value.parts[0],i=Or(o);r.push(i)}return e.advance(),{type:11,specifiers:r,path:e.getCurrentToken().value.parts[0]}}function Or(e){let n=e.trim(),t=n.match(/^\*\s+as\s+([A-Za-z_$][\w$]*)$/);if(t)return{imported:"*",local:t[1]};let r=n.match(/^default\s+as\s+([A-Za-z_$][\w$]*)$/);if(r)return{imported:"default",local:r[1]};let o=n.match(/^([A-Za-z_$][\w$]*)(?:\s+as\s+([A-Za-z_$][\w$]*))?$/);if(o)return{imported:o[1],local:o[2]??o[1]};throw`Invalid import specifier "${e}".`}function _t(e,n,t){e.advance();let r=e.peek();if(r.type!==19)throw`Expected CONDITION after SWITCH, got ${T[r.type]}`;let o=R(r.parts[0]).node;e.advance(2);let i=new Array;for(;e.peek().type!==21;){let s=e.peek();switch(s.type){case 17:let a=s.span.start,c=new Array;do{e.advance();let f=e.peek();if(f.type!==19)throw"Expected CONDITION after CASE";c.push(f.parts[0]),e.advance()}while(e.peek().type!==20);e.advance();let p=B(e,n);i.push({type:10,condition:c,children:p,span:{start:a,end:e.getCurrentToken().value.span.end}});break;case 18:let u=s.span.start;e.advance(2);let d=B(e,n);i.push({type:10,condition:null,children:d,span:{start:u,end:e.getCurrentToken().value.span.end}});break}}return e.advance(),{type:9,expression:o,children:i}}function Ot(e,n,t){return e.advance(),{type:3,value:t.parts[0]}}var me=class{constructor(n,t){this._input=n;this._cursor=new le(this._input,t)}_input;_cursor;_states={0:Ot,11:te,10:te,1:At,12:vt,13:It,16:_t,22:bt};thrown=!1;parse(){let n=new Array;for(;this._cursor.peek().type!==24;){let t=this.parseNode();t&&n.push(t)}return n}parseNode(){let n=this._cursor.peek();if(n.type===24)return;let t=n.span.start;try{let r=this._states[n.type];if(!r)throw`No transition function for token of type ${T[n.type]}`;let o=r(this._cursor,this.parseNode.bind(this),n),i=this._cursor.getCurrentToken().value,s="span"in i?i.span.end:n.span.end;return{...o,span:o.span??{start:t,end:s}}}catch(r){if(this.thrown)throw r;this.thrown=!0;let o=r instanceof Error?r.message:r,i=this._cursor.peek(),s=i.type!==24?i.span.end:void 0;throw`${this._cursor.getPositionFromCharacterIndex(t+1)} - ${o}
|
|
16
|
+
---> ${Rr(this._input,t,s)}`}}};import{slice as on}from"@xaendar/common";var z=class extends N{_imports=new Array;addImport(n){this._imports.push(n)}getImportBySelector(n){return this._imports.find(t=>t.type==="component"&&t.selectors.includes(n))}};function I(e,n){return{text:e,span:n}}function L(...e){let n="",t=new Array;for(let r of e)if(typeof r=="string")n=`${n}${r}`;else{let o=n.length;n=`${n}${r.text}`,t.push({columnStart:o,columnEnd:n.length,original:r.span})}return t.length?{text:n,mappings:t}:{text:n}}function h(e){return{text:e}}function v(e){return e.map(n=>({text:" ".repeat(2)+n.text,mappings:n.mappings?.map(t=>({...t,columnStart:t.columnStart+2,columnEnd:t.columnEnd+2}))}))}function Rt(e,n,t){let r=new Array;if($r(e.tagName)){let i=t.getImportBySelector(e.tagName);if(!i)throw new Error(`${e.tagName} selector is not associated to any WebComponent imported in the template`,{cause:e.span});r.push(...wr(e,i,t))}else r.push(...Fr(e,t));let o=e.children;for(let i=0;i<o.length;i++)r.push(...n(o[i],t));return r}function wr(e,n,t){let r=new Array,o=new Set(n.properties.entries().filter(([a,c])=>c.required).map(([a])=>a)),i=e.attributes;for(let a=0;a<i.length;a++){let{name:c,value:p}=i[a],u=n.properties.get(c);u&&(o.delete(c),r.push(h("{"),...v(typeof p=="object"?[L("(",I(x(p.expression,t,{resolver:"root"}).expression,p.span),`) satisfies ${u.type};`)]:[h("let x!: string;"),L(I(`x satisfies ${u.type};`,i[a].span))]),h("}")))}if(o.size)throw new Error(`${e.tagName} is missing the following required properties:
|
|
17
17
|
\u25CF ${Array.from(o.values()).join(`
|
|
18
|
-
\u25CF `)}`,{cause:e.span});let s=e.events;for(let a=0;a<s.length;a++){let{name:c,handler:p,parameters:u}=s[a],d=n.events.get(c);if(!d)throw new Error(`Unknown event "${c}" on <${e.tagName}> (${n.className} has no @Event with this name).`,{cause:e.span});let f=new N(t);f.addUnresolvableIdentifier("$event");let y=u.map(b=>x(b,f,{resolver:"root"}).expression).join(", ");r.push(h("{")),d.type!=="void"&&r.push(...v([h(`let $event!: CustomEvent<${d.type}>;`)])),r.push(...v([L(I(`root.${p}(${y});`,s[a].span))])),r.push(h("}"))}return r}function
|
|
18
|
+
\u25CF `)}`,{cause:e.span});let s=e.events;for(let a=0;a<s.length;a++){let{name:c,handler:p,parameters:u}=s[a],d=n.events.get(c);if(!d)throw new Error(`Unknown event "${c}" on <${e.tagName}> (${n.className} has no @Event with this name).`,{cause:e.span});let f=new N(t);f.addUnresolvableIdentifier("$event");let y=u.map(b=>x(b,f,{resolver:"root"}).expression).join(", ");r.push(h("{")),d.type!=="void"&&r.push(...v([h(`let $event!: CustomEvent<${d.type}>;`)])),r.push(...v([L(I(`root.${p}(${y});`,s[a].span))])),r.push(h("}"))}return r}function Fr(e,n){let t=new Array,r=e.attributes;for(let i=0;i<r.length;i++){let{value:s}=r[i];typeof s!="string"&&t.push(L(I(`${x(s.expression,n,{resolver:"root"}).expression};`,s.span)))}let o=e.events;for(let i=0;i<o.length;i++){let{handler:s,parameters:a}=o[i],c=new N(n);c.addUnresolvableIdentifier("$event");let p=a.map(u=>x(u,c,{resolver:"root"}).expression).join(", ");t.push(L(I(`root.${s}(${p});`,o[i].span)))}return t}function $r(e){return/^[a-z][a-z0-9._\-]*-[a-z0-9._\-]*$/.test(e)}function wt(e,n,t){let r=new z(t),o=ne(e,"$index"),i=ne(e,"$first"),s=ne(e,"$last"),a=ne(e,"$even"),c=ne(e,"$odd");r.addUnresolvableIdentifier(e.itemAlias);let p=[o,i,s,a,c];for(let d=0;d<p.length;d++)r.addUnresolvableIdentifier(p[d],"signal");let u=new Array;return u.push(L(`for (const ${e.itemAlias} of root.`,I(e.iterableSource,e.span),") {")),u.push(...v([h(`let ${o}!: Signal<number>;`),h(`let ${i}!: Signal<boolean>;`),h(`let ${s}!: Signal<boolean>;`),h(`let ${a}!: Signal<boolean>;`),h(`let ${c}!: Signal<boolean>;`),L(I(`${x(e.trackExpression,r).expression};`,e.span)),...e.children.flatMap(d=>n(d,r))])),u.push(h("}")),u}function ne(e,n){return e.implicitAliases.get(n)??n}function Ft(e,n,t){let r=new Array,o=x(e.conditionNode,t,{resolver:"root"});r.push(L("if (",I(o.expression,e.span),") {")),r.push(...v(e.children.flatMap(s=>n(s,t)))),r.push(h("}"));let i=e.alternate;for(;i?.type===7;){let s=x(i.conditionNode,t,{resolver:"root"});r.push(L("else if (",I(s.expression,i.span),") {")),r.push(...v(i.children.flatMap(a=>n(a,t)))),r.push(h("}")),i=i.alternate}return i&&(r.push(h("else {")),r.push(...v(i.children.flatMap(s=>n(s,t)))),r.push(h("}"))),r}function $t(e,n,t){let{expression:r}=x(e.expression,t,{resolver:"root"}),o=[L("switch (",I(r,e.span),") {")],i=e.children;for(let s=0;s<i.length;s++){let a=i[s],c=a.condition;if(c?.length)for(let p=0;p<c.length;p++)o.push(h(` case ${c[p]}:`));else o.push(h(" default:"));o.push(...v(v([...a.children.flatMap(p=>n(p,t)),h("break;")])))}return o.push(h("}")),o}function ve(e,n,t){return e.type===4?[L(I(`${x(e.expression,t,{resolver:"root"}).expression};`,e.span))]:[]}import{slice as Ur}from"@xaendar/common";import{existsSync as Se}from"fs";import{readFile as Vr}from"fs/promises";import{resolve as Hr}from"path";import{createSourceFile as Wr,getNameOfDeclaration as Mt,isArrayLiteralExpression as Kr,isCallExpression as ue,isDecorator as qr,isIdentifier as H,isObjectLiteralExpression as Dt,isPropertyAccessExpression as Qr,isPropertyAssignment as Bt,isPropertyDeclaration as _e,isStringLiteral as be,isTypeReferenceNode as Xr,ScriptTarget as jr,SyntaxKind as zr}from"typescript";import{getDecorators as Pr,isCallExpression as Mr,isClassDeclaration as Dr,isIdentifier as Pt,isPropertyAccessExpression as Br}from"typescript";function fe(e,n){let t=0,r,o=e.statements;for(;t<o.length&&!r;){let i=o[t];if(Dr(i)&&i.name?.text===n){let s=Gr(i);s&&(r={klass:i,decorator:s})}t++}return r}function Gr(e){let n=Pr(e);if(!n?.length)return;let t=0,r;for(;t<n.length&&!r;){let o=n[t];if(!Mr(o.expression)){t++;continue}let i=o.expression.expression;Pt(i)&&i.text==="WebComponent"&&(r=o),Br(i)&&Pt(i.name)&&i.name.text==="WebComponent"&&(r=o),t++}return r}async function Gt(e,n,t=process.cwd()){let r=Yr(e,t);if(!r)return;let o=await Vr(r,"utf8"),i=Wr(r,o,jr.Latest,!0),s,a=0,c=fe(i,n);if(!c)return;let{klass:p,decorator:u}=c,d=en(u);if(!d?.length)return;let f=new Map,y=new Map,b=p.members;for(let S=0;S<b.length;S++){let E=b[S];if(!_e(E))continue;let we=E.modifiers??[],Fe=!1,$e=Array.from(we).find(_=>{let M=Jr(_);return Fe=!!M.required,M.decorator});if($e){let _=Mt(E);if(_&&H(_)){let M=_.text,W=rn(_,M,$e,Fe);if(W){let m=W.alias??M,Me=f.get(m);if(!Me)f.set(m,W);else{let{start:De,end:tr}=Me.span,{line:rr,character:Be}=i.getLineAndCharacterOfPosition(De);throw`Failed to extract metadata from an imported component in the template - ${r}
|
|
19
19
|
[Ln ${rr+1}, Col ${Be+1}] - A property identified by name ${m} was already defined
|
|
20
|
-
---> ${
|
|
20
|
+
---> ${Ur(o,De-Be,tr)}`}}}continue}let Pe=Array.from(we).find(_=>Zr(_));if(Pe){let _=Mt(E),M=_&&H(_)?_.text:void 0;if(M){let W=nn(Pe);W&&y.set(M,W)}}}let w=new Map;return f.entries().forEach(([S,E])=>w.set(S,{name:E.name,required:E.required,type:E.type,alias:E.alias})),s={type:"component",className:n,selectors:d,properties:w,events:y},s}function Yr(e,n){if(e.startsWith(".")){let t=Hr(n,e);if(Se(`${t}.ts`))return t+".ts";if(Se(`${t}/index.ts`))return`${t}/index.ts`;if(Se(t))return t}}function Jr(e){if(!qr(e))return{decorator:!1};let n=e.expression;if(!ue(n))return{decorator:!1};let t=n.expression;return H(t)&&t.text==="Property"?{decorator:!0}:Qr(t)&&H(t.expression)&&t.expression.text==="Property"&&t.name.text==="required"?{decorator:!0,required:!0}:{decorator:!1}}function Zr(e){if(e.kind!==zr.Decorator)return!1;let n=ue(e.expression)?e.expression.expression:e.expression;return H(n)&&n.text==="Event"}function en(e){try{let n=e.expression;if(!ue(n))return[];let t=n.arguments;if(t.length===0)return[];let r=t[0];if(!r||!Dt(r))return[];let o=Array.from(r.properties).find(i=>Bt(i)&&H(i.name)&&i.name.text==="selector");return tn(o.initializer)}catch{return[]}}function tn(e){return be(e)?[e.text]:Kr(e)?e.elements?.filter(n=>be(n)).map(n=>n.text):[]}function rn(e,n,t,r){let o=t.expression,i={name:n,required:r,type:_e(t.parent)?Ut(t.parent.type):"any",span:{start:e.getStart(),end:e.getEnd()}};if(ue(o)){let s=o.arguments,c=(s.length?s.find(p=>Dt(p)):void 0)?.properties?.find(p=>Bt(p)&&H(p.name)&&p.name.text==="alias");if(c&&be(c.initializer)){let p=c.initializer;i.alias=p.text,i.span={start:p.getStart(),end:p.getEnd()}}}return i}function nn(e){let n={type:"void"};return _e(e.parent)&&(n.type=Ut(e.parent.type,!0)),n}function Ut(e,n=!1){let t=n?"void":"any";if(!e||!Xr(e))return t;let r=e.typeArguments;return!r||r.length===0?t:r[0].getText()}var de=class{constructor(n,t){this._input=n;this._ast=t}_input;_ast;_context=new z;_states={3:ve,4:ve,0:Rt,5:Ft,8:wt,9:$t,11:()=>[]};async populateImportMetadata(n){let t=this._ast.filter(r=>r.type===11);await Promise.all(t.flatMap(r=>r.specifiers.filter(({imported:o})=>o!=="*").map(async({imported:o,local:i})=>{let s=o==="default"?i:o,a=await Gt(r.path,s,n);a&&this._context.addImport(a)})))}async generate(n){try{await this.populateImportMetadata(n);let t=this._ast.flatMap(o=>this._processNode(o,this._context)),r=[h("function typeCheck() {"),...v(t),h("}")];return{text:r.map(o=>o.text).join(`
|
|
21
21
|
`),mappingTable:this.buildMappingTable(r)}}catch(t){let r,o;if(t instanceof Error){let i=t.cause;o=i&&typeof i=="object"&&"start"in i&&"end"in i?i:void 0,r=t.message}else r=t;throw o?`${new D(this._input).getPositionFromCharacterIndex(o.start+1)} - ${r}
|
|
22
|
-
---> ${
|
|
22
|
+
---> ${on(this._input,o.start,o.end)}}`:r}}buildMappingTable(n){let t=new Map;return n.forEach((r,o)=>{r.mappings&&t.set(o,r.mappings)}),t}_processNode=(n,t)=>{let r=this._states[n.type];if(!r)throw new Error(`No transition function for ASTNode of type ${g[n.type]}`,{cause:n.span});return r(n,this._processNode,t)}};async function vp(e,n){let t=new ce(e).tokenize(),r=new me(e,t).parse();if(!("baseDir"in n||"cssVariableName"in n))throw"CssVariableName or BaseDir must be specified";let{baseDir:o,cssVariableName:i,signals:s}=n;return i&&o&&s?{javascript:Vt(e,r,i,s),typescript:await Ht(e,r,o)}:o?await Ht(e,r,o):Vt(e,r,i,s)}function Vt(e,n,t,r){return new oe(e,n).generate(t,r)}async function Ht(e,n,t){return await new de(e,n).generate(t)}function bp(e,n){let t=e.get(n.line);if(t){let r=t.find(o=>n.character>=o.columnStart&&n.character<o.columnEnd);return r?r.original:t.reduce((o,i)=>{let s=Math.min(Math.abs(n.character-i.columnStart),Math.abs(n.character-i.columnEnd)),a=Math.min(Math.abs(n.character-o.columnStart),Math.abs(n.character-o.columnEnd));return s<a?i:o}).original}}import{existsSync as Wt,readFileSync as Kt}from"fs";import{dirname as Re,isAbsolute as sn,join as Y,resolve as qt}from"path";import{ScriptTarget as Qt,SyntaxKind as an,createSourceFile as Xt,forEachChild as jt,isCallExpression as pn,isClassDeclaration as cn,isIdentifier as J,isImportDeclaration as zt,isNamedImports as ln,isNamespaceImport as mn,isPropertyAccessExpression as fn,isPropertyDeclaration as un,isQualifiedName as dn,isStringLiteralLike as Yt,isTypeReferenceNode as Tn}from"typescript";var hn=new Set(["@xaendar/core/signals"]);function Wp(e,n,t){let r=Xt(t,e,Qt.Latest,!0),o=fe(r,n);if(!o)return[];let i=o.klass,s=Jt(r,i,Re(t),new Set([qt(t)])),a=Zt(r),c=er(i,a);return[...s,...c]}function Jt(e,n,t,r){let o=xn(n);if(!o)return[];let i=En(e,o);if(!i||!Yt(i.moduleSpecifier))return[];let s=Cn(i.moduleSpecifier.text,t);if(!s||r.has(s))return[];r.add(s);let a;try{a=Kt(s,"utf-8")}catch{return[]}let c=Xt(s,a,Qt.Latest,!0),p=Nn(c,o);if(!p)return[];let u=Zt(c),d=er(p,u);return[...Jt(c,p,Re(s),r),...d]}function xn(e){let n=e.heritageClauses;if(n)for(let t=0;t<n.length;t++){let r=n[t];if(r.token===an.ExtendsKeyword){let o=r.types[0].expression;if(J(o))return o.text}}}function En(e,n){let t=0,r,o=e.statements;for(;t<o.length&&!r;){let i=o[t];if(zt(i)){let s=i.importClause?.namedBindings;(s&&ln(s)?s.elements.find(a=>a.name.text===n):i.importClause?.name?.text===n)&&(r=i)}t++}return r}function Cn(e,n){if(e.startsWith(".")||sn(e)){let a=qt(n,e);return Te([`${a}.d.ts`,Y(a,"index.d.ts")])}let t=gn(e,n);if(!t)return;let r;try{r=JSON.parse(Kt(Y(t,"package.json"),"utf-8"))}catch{return}let o=r.types??r.typings;if(o){let a=Te([Y(t,o)]);if(a)return a}let i=kn(r.exports),s=i!==void 0?Oe(i):void 0;if(s){let a=Te([Y(t,s)]);if(a)return a}return Te([Y(t,"index.d.ts")])}function Te(e){return e.find(Wt)}function gn(e,n){let t=n,r;for(;!r&&t;){let o=Y(t,"node_modules",e);if(Wt(o))return o;let i=Re(t);t=i===t?"":i}return r}function kn(e){if(e==null)return;if(typeof e=="string"||Array.isArray(e))return e;let n=Object.keys(e);return n.length&&n.every(r=>r.startsWith("."))?e["."]:e}function Oe(e){if(!(e==null||typeof e=="string")){if(Array.isArray(e)){for(let n of e){let t=Oe(n);if(t)return t}return}if(typeof e.types=="string")return e.types;for(let n of Object.values(e)){let t=Oe(n);if(t)return t}}}function Nn(e,n){let t;return jt(e,r=>{!t&&cn(r)&&r.name?.text===n&&(t=r)}),t}function Zt(e){let n=new Set,t=new Set;return jt(e,r=>{if(!zt(r)||!Yt(r.moduleSpecifier)||!hn.has(r.moduleSpecifier.text))return;let o=r.importClause?.namedBindings;if(o)if(mn(o))t.add(o.name.text);else for(let i of o.elements)n.add(i.name.text)}),{named:n,namespaces:t}}function er(e,n){let t=new Array;for(let r of e.members)un(r)&&J(r.name)&&yn(r,n)&&t.push(r.name.text,"signal");return t}function yn(e,n){return e.initializer&&pn(e.initializer)?An(e.initializer.expression,n):e.type&&Tn(e.type)?In(e.type.typeName,n):!1}function An(e,n){return J(e)?n.named.has(e.text):fn(e)&&J(e.expression)?n.namespaces.has(e.expression.text):!1}function In(e,n){return J(e)?n.named.has(e.text):dn(e)&&J(e.left)?n.namespaces.has(e.left.text):!1}export{D as Cursor,vp as compile,Wp as extractSignalMembers,bp as resolveTemplateSpan};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xaendar/compiler",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.31",
|
|
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.9.
|
|
17
|
-
"@xaendar/types": "0.9.
|
|
16
|
+
"@xaendar/common": "0.9.31",
|
|
17
|
+
"@xaendar/types": "0.9.31",
|
|
18
18
|
"typescript": "^6.0.3",
|
|
19
19
|
"type-fest": "^5.9.0"
|
|
20
20
|
}
|