@lipsjs/lips 0.1.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +119 -85
- package/dist/lips.js +3836 -0
- package/dist/lips.js.map +28 -0
- package/dist/lips.min.js +9 -2
- package/dist/lips.min.js.map +22 -43
- package/dist/precompile.min.js +20 -0
- package/dist/precompile.min.js.map +13 -0
- package/dist/runtime.min.js +4 -0
- package/dist/runtime.min.js.map +19 -0
- package/dist/types/events.d.ts +1 -1
- package/dist/types/ir/compiler.d.ts +153 -0
- package/dist/types/ir/expression.d.ts +120 -0
- package/dist/types/ir/facade.d.ts +94 -0
- package/dist/types/ir/index.d.ts +15 -0
- package/dist/types/ir/parser.d.ts +124 -0
- package/dist/types/ir/router.d.ts +47 -0
- package/dist/types/ir/runtime.d.ts +95 -0
- package/dist/types/ir/signal.d.ts +26 -0
- package/dist/types/ir/swap.d.ts +23 -0
- package/dist/types/lips.d.ts +16 -37
- package/dist/types/precompile.d.ts +60 -0
- package/dist/types/runtime.d.ts +16 -0
- package/dist/types/stylesheet.d.ts +24 -40
- package/dist/types/types.d.ts +49 -185
- package/package.json +29 -10
- package/dist/test.component.min.js +0 -3
- package/dist/test.component.min.js.map +0 -50
- package/dist/test.stress.min.js +0 -476
- package/dist/test.stress.min.js.map +0 -50
- package/dist/types/component.d.ts +0 -107
- package/dist/types/constants.d.ts +0 -23
- package/dist/types/dws.d.ts +0 -14
- package/dist/types/iuc/index.d.ts +0 -25
- package/dist/types/iuc/tick.d.ts +0 -38
- package/dist/types/iuc.d.ts +0 -25
- package/dist/types/metrics.d.ts +0 -50
- package/dist/types/preprocess.d.ts +0 -2
- package/dist/types/signal.d.ts +0 -30
- package/dist/types/syntax/async.d.ts +0 -16
- package/dist/types/syntax/for.d.ts +0 -25
- package/dist/types/syntax/if.d.ts +0 -14
- package/dist/types/syntax/router.d.ts +0 -40
- package/dist/types/syntax/switch.d.ts +0 -16
- package/dist/types/tick.d.ts +0 -38
- package/dist/types/tps.d.ts +0 -11
- package/dist/types/uqs.d.ts +0 -37
- package/dist/types/utils.d.ts +0 -25
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
var N=Object.defineProperty;var y=(J)=>J;function E(J,K){this[J]=y.bind(null,K)}var T=(J,K)=>{for(var X in K)N(J,X,{get:K[X],enumerable:!0,configurable:!0,set:E.bind(K,X)})};var x=(J,K)=>()=>(J&&(K=J(J=0)),K);var P={};T(P,{parseTemplate:()=>G,parseSFC:()=>f});function q(J){return J.replace(/&(?:amp|lt|gt|quot|#39|nbsp);/g,(K)=>S[K])}class L{src;pos=0;lineStarts=null;diagnostics=[];constructor(J){this.src=J}locate(J){if(!this.lineStarts){this.lineStarts=[0];for(let Q=0;Q<this.src.length;Q++)if(this.src[Q]===`
|
|
2
|
+
`)this.lineStarts.push(Q+1)}let K=0,X=this.lineStarts.length-1;while(K<X){let Q=K+X+1>>1;this.lineStarts[Q]<=J?K=Q:X=Q-1}return{line:K+1,col:J-this.lineStarts[K]+1}}report(J,K,X,Q,Y=1,Z){let{line:$,col:z}=this.locate(Q);this.diagnostics.push({code:J,severity:K,message:X,hint:Z,loc:{line:$,col:z,offset:Q,length:Y}})}eof(){return this.pos>=this.src.length}peek(J=0){return this.src[this.pos+J]}startsWith(J){return this.src.startsWith(J,this.pos)}skipSpace(){while(!this.eof()&&/\s/.test(this.src[this.pos]))this.pos++}scanBalanced(J,K){let X=this.pos,Q=0;while(!this.eof()){let Y=this.src[this.pos];if(Y==="'"||Y==='"'||Y==="`"){this.pos++;while(!this.eof()&&this.src[this.pos]!==Y){if(this.src[this.pos]==="\\")this.pos++;this.pos++}this.pos++;continue}if(Q===0&&Y===J){let Z=this.src.slice(X,this.pos);return this.pos++,{content:Z,loc:{offset:X,length:Z.length}}}if(Y==="("||Y==="["||Y==="{")Q++;else if(Y===")"||Y==="]"||Y==="}"){if(Q===0&&Y!==J){this.report(K,"error",`Unbalanced '${Y}'`,this.pos),this.pos++;continue}Q--}this.pos++}return this.report(K,"error",`Unterminated — expected '${J}'`,X,this.pos-X),null}parse(){let J=[];while(!this.eof())if(J.push(...this.parseNodes([])),this.startsWith("</")){let K=this.pos;this.pos+=2;while(!this.eof()&&this.peek()!==">")this.pos++;!this.eof()&&this.pos++,this.report("LIPS-P005","error",`Stray closing tag ${this.src.slice(K,this.pos)}`,K,this.pos-K)}return{root:{t:"fragment",children:J,loc:{offset:0,length:this.src.length}},diagnostics:this.diagnostics}}parseNodes(J){let K=[];while(!this.eof()){if(this.startsWith("</"))break;let X=this.pos;if(this.peek()==="<"&&this.peek(1)!==void 0){let Q=this.parseTag(J);Q&&K.push(Q)}else{let Q=this.parseText(J);Q&&K.push(Q)}if(this.pos===X)this.pos++}return K}parseText(J){let K=this.pos,X=[],Q="";while(!this.eof()&&this.peek()!=="<"){if(this.peek()==="{"){this.pos++;let z=this.scanBalanced("}","LIPS-P007");if(z)Q&&X.push(Q),Q="",X.push({expr:z.content.trim(),loc:z.loc});continue}Q+=this.peek(),this.pos++}Q&&X.push(Q);let Y={offset:K,length:this.pos-K};if(X.some((z)=>typeof z!=="string"))return{t:"interp",parts:X.map((z)=>typeof z==="string"?q(z):z),loc:Y};let Z=X.length?X[0]:"",$=J.some((z)=>w.has(z));if(!Z||!$&&!Z.trim())return null;return{t:"text",value:q(Z),loc:Y}}parseTag(J){let K=this.pos;if(this.startsWith("<!--")){let Z=this.src.indexOf("-->",this.pos+4);if(Z===-1)return this.report("LIPS-P003","error","Unterminated comment",K,this.src.length-K),this.pos=this.src.length,null;let $=this.src.slice(this.pos+4,Z);return this.pos=Z+3,{t:"comment",value:$,loc:{offset:K,length:this.pos-K}}}if(this.startsWith("<>")){this.pos+=2;let Z=[];while(!0)if(Z.push(...this.parseNodes([...J,"#fragment"])),this.closeStatus("#fragment",K,J)!=="stray")break;return{t:"fragment",children:Z,loc:{offset:K,length:this.pos-K}}}if(this.startsWith("<{")){this.pos+=2;let Z=this.scanBalanced("}","LIPS-P008");if(!Z)return null;let $={t:"element",tag:"#dynamic",dynamicTag:{expr:Z.content.trim(),loc:Z.loc},attrs:[],children:[],selfClosed:!1,loc:{offset:K,length:0}};return this.finishTag($,J,K),$}this.pos++;let X=this.pos;while(!this.eof()&&/[A-Za-z0-9_-]/.test(this.peek()))this.pos++;let Q=this.src.slice(X,this.pos);if(!Q||!/^[A-Za-z]/.test(Q))return this.report("LIPS-P002","error","Invalid tag name",K,this.pos-K+1),{t:"text",value:"<",loc:{offset:K,length:1}};let Y={t:"element",tag:Q.toLowerCase(),attrs:[],children:[],selfClosed:!1,loc:{offset:K,length:0}};if(this.peek()==="(")if(O.has(Y.tag)){this.pos++;let Z=this.scanBalanced(")","LIPS-P012");Z&&(Y.head={expr:Z.content.trim(),loc:Z.loc})}else this.report("LIPS-P011","error",`Head expression is not allowed on <${Y.tag}>`,this.pos,1,`Only ${[...O].map((Z)=>`<${Z}(…)>`).join(", ")} take a head`);return this.finishTag(Y,J,K),Y}finishTag(J,K,X){if(this.parseAttrs(J),J.selfClosed||A.has(J.tag)){J.selfClosed=!0,J.loc={offset:X,length:this.pos-X};return}let Q=J.tag==="#dynamic"?"#dynamic":J.tag;J.children=[];while(!0)if(J.children.push(...this.parseNodes([...K,Q])),this.closeStatus(Q,X,K)!=="stray")break;J.loc={offset:X,length:this.pos-X}}closeStatus(J,K,X){if(this.eof())return this.report("LIPS-P006","error",`Unclosed <${J==="#fragment"?"":J}> — reached end of template`,K,1,`Add </${J==="#fragment"||J==="#dynamic"?"":J}>`),"eof";if(!this.startsWith("</"))return"closed";let Q=this.pos;if(this.pos+=2,this.peek()===">"){if(this.pos++,J!=="#fragment"&&J!=="#dynamic")this.report("LIPS-P004","warning",`Generic '</>' closes <${J}>`,Q,3,`Prefer </${J}>`);return"closed"}let Y=this.pos;while(!this.eof()&&/[A-Za-z0-9_-]/.test(this.peek()))this.pos++;let Z=this.src.slice(Y,this.pos).toLowerCase();if(this.skipSpace(),this.peek()===">"?this.pos++:this.report("LIPS-P001","error","Malformed closing tag",Q,this.pos-Q),Z===J)return"closed";if(X.includes(Z))return this.report("LIPS-P004","warning",`</${Z}> auto-closes <${J}>`,Q,this.pos-Q,`Add the missing </${J}> before </${Z}>`),this.pos=Q,"ancestor";return this.report("LIPS-P005","error",`Stray closing tag </${Z}> — <${J}> is open`,Q,this.pos-Q),"stray"}parseAttrs(J){while(!0){if(this.skipSpace(),this.eof()){this.report("LIPS-P001","error","Unexpected end of template inside tag",J.loc.offset);return}if(this.startsWith("/>")){this.pos+=2,J.selfClosed=!0;return}if(this.peek()===">"){this.pos++;return}let K=this.pos;if(this.startsWith("...")){this.pos+=3;let Z=this.readUnquotedValue();J.attrs.push({k:"spread",source:Z,loc:{offset:K,length:this.pos-K}});continue}if(this.peek()==="["){this.pos++;let Z=this.scanBalanced("]","LIPS-P009");if(Z){let $=Z.content.split(",").map((z)=>z.trim()).filter(Boolean);J.attrs.push({k:"args",names:$,loc:{offset:K,length:this.pos-K}})}continue}let X=!1;if(this.peek()==="!")X=!0,this.pos++;let Q=this.pos;while(!this.eof()&&/[^\s=/>()]/.test(this.peek()))this.pos++;let Y=this.src.slice(Q,this.pos);if(!Y){this.report("LIPS-P009","error",`Invalid attribute syntax at '${this.peek()}'`,this.pos),this.pos++;continue}if(this.peek()==="("){this.pos++;let Z=this.scanBalanced(")","LIPS-P010"),$=Z?Z.content.trim():"",z={offset:K,length:this.pos-K};Y.startsWith("on-")?J.attrs.push({k:"event",name:Y.slice(3),source:$,loc:z}):J.attrs.push({k:"fn",name:Y,source:$,loc:z});continue}if(this.peek()==="="){this.pos++,this.parseAttrValue(J,Y,K);continue}J.attrs.push({k:"bool",name:Y,value:!X,loc:{offset:K,length:this.pos-K}})}}parseAttrValue(J,K,X){let Q=this.peek();if(Q==='"'||Q==="'"){this.pos++;let Z=this.pos,$=[],z="";while(!this.eof()&&this.peek()!==Q){if(this.peek()==="{"){this.pos++;let B=this.scanBalanced("}","LIPS-P007");if(B)z&&$.push(z),z="",$.push({expr:B.content.trim(),loc:B.loc});continue}z+=this.peek(),this.pos++}z&&$.push(z),this.eof()?this.report("LIPS-P010","error",`Unterminated value for '${K}'`,Z,this.pos-Z):this.pos++;let U={offset:X,length:this.pos-X};$.some((B)=>typeof B!=="string")?J.attrs.push({k:"interp",name:K,parts:$.map((B)=>typeof B==="string"?q(B):B),loc:U}):J.attrs.push({k:"literal",name:K,value:q($[0]??""),loc:U});return}if(Q==="{"){this.pos++;let Z=this.scanBalanced("}","LIPS-P007");J.attrs.push({k:"expr",name:K,source:Z?Z.content.trim():"",loc:{offset:X,length:this.pos-X}});return}let Y=this.readUnquotedValue();Y?J.attrs.push({k:"expr",name:K,source:Y,loc:{offset:X,length:this.pos-X}}):this.report("LIPS-P010","error",`Missing value for attribute '${K}'`,X)}readUnquotedValue(){let J=this.pos,K=0;while(!this.eof()){let X=this.peek();if(X==="'"||X==='"'||X==="`"){this.pos++;while(!this.eof()&&this.peek()!==X){if(this.peek()==="\\")this.pos++;this.pos++}this.pos++;continue}if(K===0){if(/\s/.test(X)||X===">")break;if(X==="/"&&this.peek(1)===">")break}if(X==="("||X==="["||X==="{")K++;else if(X===")"||X==="]"||X==="}")K--;this.pos++}return this.src.slice(J,this.pos).trim()}}function G(J){return new L(J||"").parse()}function f(J){let K=b(J||""),X=(J||"").slice(0,K).trimEnd(),Q=(J||"").slice(K),Y=new L(Q).parse(),Z=X?X.split(`
|
|
3
|
+
`).length+(/\n\s*\n$/.test(J.slice(0,K))?1:0):0;return Y.diagnostics.forEach(($)=>{$.loc.line+=X?J.slice(0,K).split(`
|
|
4
|
+
`).length-1:0,$.loc.offset+=K}),{script:X,...Y}}function b(J){let K=0,X=!0;for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y==="'"||Y==='"'||Y==="`"){let Z=Y;Q++;while(Q<J.length&&J[Q]!==Z){if(J[Q]==="\\")Q++;Q++}X=!1;continue}if(Y==="/"&&J[Q+1]==="/"){while(Q<J.length&&J[Q]!==`
|
|
5
|
+
`)Q++;X=!0;continue}if(Y==="/"&&J[Q+1]==="*"){let Z=J.indexOf("*/",Q+2);Q=Z===-1?J.length:Z+1;continue}if(Y===`
|
|
6
|
+
`){X=!0;continue}if(X&&K===0&&Y==="<"&&/[A-Za-z{>!]/.test(J[Q+1]||""))return Q;if(Y==="("||Y==="["||Y==="{")K++;else if(Y===")"||Y==="]"||Y==="}")K=Math.max(0,K-1);if(!/\s/.test(Y))X=!1}return 0}var A,w,O,S;var M=x(()=>{A=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),w=new Set(["pre","textarea"]),O=new Set(["if","else-if","switch","log"]),S={"&":"&","<":"<",">":">",""":'"',"'":"'"," ":" "}});M();var v=["===","!==","...","=>","==","!=","<=",">=","&&","||","??","?.","++","--","+=","-=","*=","/=","%=","+","-","*","/","%","<",">","!","?",":",".",",","(",")","[","]","{","}","="];function k(J,K){let X=[],Q=0,Y=($)=>/[A-Za-z_$]/.test($),Z=($)=>/[A-Za-z0-9_$]/.test($);while(Q<J.length){let $=J[Q];if(/\s/.test($)){Q++;continue}if(/[0-9]/.test($)||$==="."&&/[0-9]/.test(J[Q+1])){let U=Q;while(Q<J.length&&/[0-9]/.test(J[Q]))Q++;if(J[Q]==="."){Q++;while(Q<J.length&&/[0-9]/.test(J[Q]))Q++}if(J[Q]==="e"||J[Q]==="E"){if(Q++,J[Q]==="+"||J[Q]==="-")Q++;while(Q<J.length&&/[0-9]/.test(J[Q]))Q++}X.push({t:"num",value:J.slice(U,Q),start:U,end:Q});continue}if($==="'"||$==='"'){let U=Q;Q++;let B="",F=!1;while(Q<J.length){let V=J[Q];if(V==="\\"){let D=J[Q+1],H={n:`
|
|
7
|
+
`,t:"\t",r:"\r",b:"\b",f:"\f",v:"\v","0":"\x00"};if(D==="u"){let W=J.slice(Q+2,Q+6);B+=String.fromCharCode(parseInt(W,16)||0),Q+=6}else B+=H[D]??D,Q+=2;continue}if(V===$){F=!0,Q++;break}B+=V,Q++}if(!F)K.push({code:"LIPS-E001",message:"Unterminated string literal",loc:{offset:U,length:Q-U}});X.push({t:"str",value:B,start:U,end:Q});continue}if(Y($)){let U=Q;while(Q<J.length&&Z(J[Q]))Q++;X.push({t:"id",value:J.slice(U,Q),start:U,end:Q});continue}let z=v.find((U)=>J.startsWith(U,Q));if(z==="?."&&/[0-9]/.test(J[Q+2]??""))z="?";if(z){X.push({t:"punct",value:z,start:Q,end:Q+z.length}),Q+=z.length;continue}K.push({code:"LIPS-E002",message:`Unexpected character '${$}'`,loc:{offset:Q,length:1}}),Q++}return X.push({t:"eof",value:"",start:J.length,end:J.length}),X}class R{tokens;diagnostics;pos=0;constructor(J,K){this.tokens=J;this.diagnostics=K}peek(J=0){return this.tokens[Math.min(this.pos+J,this.tokens.length-1)]}next(){return this.tokens[this.pos++]??this.tokens[this.tokens.length-1]}at(J){let K=this.peek();return K.t==="punct"&&K.value===J}eat(J){if(this.at(J))return this.pos++,!0;return!1}error(J,K,X=this.peek()){return this.diagnostics.push({code:J,message:K,loc:{offset:X.start,length:Math.max(1,X.end-X.start)}}),{t:"error"}}expect(J,K){if(!this.eat(J))this.error(K,`Expected '${J}'`)}parse(){let J=this.assign();if(this.peek().t!=="eof")this.error("LIPS-E003",`Unexpected token '${this.peek().value}' after expression`);return J}isArrowAhead(){let J=this.peek();if(J.t==="id"){let K=this.peek(1);return K.t==="punct"&&K.value==="=>"}if(J.t==="punct"&&J.value==="("){let K=0,X=0;while(!0){let Q=this.peek(X);if(Q.t==="eof")return!1;if(Q.t==="punct"&&Q.value==="(")K++;if(Q.t==="punct"&&Q.value===")"){if(K--,K===0){let Y=this.peek(X+1);return Y.t==="punct"&&Y.value==="=>"}}X++}}return!1}assign(){if(this.isArrowAhead()){let X=[];if(this.peek().t==="id")X.push(this.next().value);else{this.expect("(","LIPS-E004");while(!this.at(")")&&this.peek().t!=="eof"){let Q=this.next();if(Q.t!=="id")return this.error("LIPS-E005","Invalid arrow parameter",Q);if(X.push(Q.value),!this.eat(","))break}this.expect(")","LIPS-E004")}return this.expect("=>","LIPS-E004"),{t:"arrow",params:X,body:this.assign()}}let J=this.conditional(),K=this.peek();if(K.t==="punct"&&["=","+=","-=","*=","/=","%="].includes(K.value)){if(J.t!=="id"&&J.t!=="member")return this.error("LIPS-E006","Invalid assignment target",K);return this.next(),{t:"assign",op:K.value,target:J,value:this.assign()}}return J}conditional(){let J=this.nullish();if(this.eat("?")){let K=this.assign();return this.expect(":","LIPS-E007"),{t:"cond",test:J,cons:K,alt:this.assign()}}return J}nullish(){let J=this.or();while(this.at("??"))this.next(),J={t:"logic",op:"??",l:J,r:this.or()};return J}or(){let J=this.and();while(this.at("||"))this.next(),J={t:"logic",op:"||",l:J,r:this.and()};return J}and(){let J=this.equality();while(this.at("&&"))this.next(),J={t:"logic",op:"&&",l:J,r:this.equality()};return J}equality(){let J=this.relational();while(["===","!==","==","!="].some((K)=>this.at(K)))J={t:"bin",op:this.next().value,l:J,r:this.relational()};return J}relational(){let J=this.additive();while(["<=",">=","<",">"].some((K)=>this.at(K)))J={t:"bin",op:this.next().value,l:J,r:this.additive()};return J}additive(){let J=this.multiplicative();while(this.at("+")||this.at("-"))J={t:"bin",op:this.next().value,l:J,r:this.multiplicative()};return J}multiplicative(){let J=this.unary();while(this.at("*")||this.at("/")||this.at("%"))J={t:"bin",op:this.next().value,l:J,r:this.unary()};return J}unary(){if(this.at("!")||this.at("-")||this.at("+"))return{t:"unary",op:this.next().value,arg:this.unary()};if(this.at("++")||this.at("--")){let J=this.next().value,K=this.unary();if(K.t!=="id"&&K.t!=="member")return this.error("LIPS-E006","Invalid update target");return{t:"update",op:J,arg:K,prefix:!0}}return this.postfix()}postfix(){let J=this.callMember();if(this.at("++")||this.at("--")){let K=this.next().value;if(J.t!=="id"&&J.t!=="member")return this.error("LIPS-E006","Invalid update target");J={t:"update",op:K,arg:J,prefix:!1}}return J}callMember(){let J=this.primary();while(!0)if(this.eat(".")){let K=this.next();if(K.t!=="id")return this.error("LIPS-E008","Expected property name",K);J={t:"member",obj:J,prop:K.value,computed:!1,optional:!1}}else if(this.eat("?."))if(this.at("("))J={t:"call",callee:J,args:this.argList(),optional:!0};else if(this.eat("[")){let K=this.assign();this.expect("]","LIPS-E009"),J={t:"member",obj:J,prop:K,computed:!0,optional:!0}}else{let K=this.next();if(K.t!=="id")return this.error("LIPS-E008","Expected property name",K);J={t:"member",obj:J,prop:K.value,computed:!1,optional:!0}}else if(this.eat("[")){let K=this.assign();this.expect("]","LIPS-E009"),J={t:"member",obj:J,prop:K,computed:!0,optional:!1}}else if(this.at("("))J={t:"call",callee:J,args:this.argList(),optional:!1};else break;return J}argList(){this.expect("(","LIPS-E010");let J=[];while(!this.at(")")&&this.peek().t!=="eof")if(J.push(this.assign()),!this.eat(","))break;return this.expect(")","LIPS-E010"),J}primary(){let J=this.peek();if(J.t==="num")return this.next(),{t:"lit",v:parseFloat(J.value)};if(J.t==="str")return this.next(),{t:"lit",v:J.value};if(J.t==="id")switch(this.next(),J.value){case"true":return{t:"lit",v:!0};case"false":return{t:"lit",v:!1};case"null":return{t:"lit",v:null};case"undefined":return{t:"lit",v:void 0};case"NaN":return{t:"lit",v:NaN};case"Infinity":return{t:"lit",v:1/0};default:return{t:"id",name:J.value}}if(this.eat("(")){let K=this.assign();return this.expect(")","LIPS-E010"),K}if(this.eat("[")){let K=[];while(!this.at("]")&&this.peek().t!=="eof"){let X=this.eat("...");if(K.push({spread:X||void 0,value:this.assign()}),!this.eat(","))break}return this.expect("]","LIPS-E009"),{t:"arr",items:K}}if(this.eat("{")){let K=[];while(!this.at("}")&&this.peek().t!=="eof"){if(this.eat("..."))K.push({spread:!0,value:this.assign()});else{let X=this.next();if(X.t!=="id"&&X.t!=="str"&&X.t!=="num")return this.error("LIPS-E011","Invalid object key",X);if(this.eat(":"))K.push({key:String(X.value),value:this.assign()});else if(X.t==="id")K.push({key:X.value,value:{t:"id",name:X.value}});else return this.error("LIPS-E011","Invalid shorthand property",X)}if(!this.eat(","))break}return this.expect("}","LIPS-E011"),{t:"obj",props:K}}return this.next(),this.error("LIPS-E012",J.t==="eof"?"Unexpected end of expression":`Unexpected token '${J.value}'`,J)}}function C(J){let K=[],X=k(J,K);return{ast:new R(X,K).parse(),diagnostics:K}}var u="<!--$-->",h=new Set(["if","else-if","else","for","switch","async","let","const","log"]),g=new Set(["case","default","then","catch","loading"]),m=new Set(["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","label","legend","li","link","main","map","mark","menu","meta","meter","nav","noscript","object","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","script","section","select","slot","small","source","span","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","title","tr","track","u","ul","var","video","wbr","svg","circle","clippath","defs","ellipse","foreignobject","g","image","line","lineargradient","marker","mask","path","pattern","polygon","polyline","radialgradient","rect","stop","symbol","text","tspan","use"]),p=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),i=(J)=>J.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),l=(J)=>J.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<"),j=(J)=>J!==""&&!isNaN(Number(J));class _{src;macros;exprs=[];exprIndex=new Map;lineStarts=null;macroStack=[];diagnostics=[];constructor(J,K=new Map){this.src=J;this.macros=K}locate(J){if(!this.lineStarts){this.lineStarts=[0];for(let Q=0;Q<this.src.length;Q++)if(this.src[Q]===`
|
|
8
|
+
`)this.lineStarts.push(Q+1)}let K=0,X=this.lineStarts.length-1;while(K<X){let Q=K+X+1>>1;this.lineStarts[Q]<=J?K=Q:X=Q-1}return{line:K+1,col:J-this.lineStarts[K]+1}}report(J,K,X,Q,Y=1,Z){let{line:$,col:z}=this.locate(Q);this.diagnostics.push({code:J,severity:K,message:X,hint:Z,loc:{line:$,col:z,offset:Q,length:Y}})}expr(J,K){let X=this.exprIndex.get(J);if(X!==void 0)return X;let{diagnostics:Q}=C(J);for(let Z of Q){let $=(K?.offset??0)+Z.loc.offset;this.report(Z.code,"error",Z.message,$,Z.loc.length)}let Y=this.exprs.length;return this.exprs.push(J),this.exprIndex.set(J,Y),Y}synth(J){let K=this.exprIndex.get(J);if(K!==void 0)return K;let X=this.exprs.length;return this.exprs.push(J),this.exprIndex.set(J,X),X}concat(J){J.filter((X)=>typeof X!=="string").forEach((X)=>{let{diagnostics:Q}=C(X.expr);for(let Y of Q)this.report(Y.code,"error",Y.message,X.loc.offset+Y.loc.offset,Y.loc.length)});let K=J.map((X)=>typeof X==="string"?JSON.stringify(X):`((${X.expr})??"")`).join("+");return this.synth(K)}compInput(J){switch(J.k){case"literal":return{lit:J.value};case"bool":return{lit:J.value};case"expr":return{e:this.expr(J.source,J.loc)};case"interp":return{e:this.concat(J.parts)}}}compile(J){return{v:1,exprs:this.exprs,root:this.block(J,[])}}block(J,K){let X={html:"",scope:[...K],binds:[],blocks:[]},Q=[],Y=(Z,$,z=!1)=>{let U=0,B=!1,F=()=>{return Q.push(u),B=!1,[...$,U++]};for(let V=0;V<Z.length;V++){let D=Z[V];switch(D.t){case"text":{if(z){X.binds.push({t:"text",p:F(),e:this.synth(JSON.stringify(D.value)),i18n:1});break}if(Q.push(i(D.value)),!B)U++;B=!0;break}case"comment":{Q.push(`<!--${D.value.replace(/--/g,"- -")}-->`),B=!1,U++;break}case"interp":{let H={t:"text",p:F(),e:this.concat(D.parts)};if(z)H.i18n=1;X.binds.push(H);break}case"fragment":{Z=[...Z.slice(0,V),...D.children,...Z.slice(V+1)],V--;break}case"element":{if(h.has(D.tag)){if(this.controlBlock(D,Z,V,F(),X,K),D.tag==="if"){let H=V+1;while(H<Z.length){let W=Z[H];if(W.t==="element"&&(W.tag==="else-if"||W.tag==="else"))H++;else break}Z=[...Z.slice(0,V+1),...Z.slice(H)]}break}if(g.has(D.tag)){this.report("LIPS-C002","error",`<${D.tag}> is only valid inside its parent construct`,D.loc.offset,D.loc.length);break}if(D.tag==="#dynamic"){X.blocks.push(this.compLike(D,F(),K,"dynamic"));break}if(this.macros.has(D.tag)){let H=this.macroCall(D,F(),K);H&&X.blocks.push(H);break}if(!m.has(D.tag)){X.blocks.push(this.compLike(D,F(),K,"comp"));break}this.emitElement(D,$,U++,Q,X,Y),B=!1;break}}}};return Y(J,[]),X.html=Q.join(""),X}emitElement(J,K,X,Q,Y,Z){let $=[...K,X],z=`<${J.tag}`,U=J.attrs.some((F)=>F.k==="bool"&&F.name==="i18n"&&F.value),B=(F)=>U&&(F==="title"||F==="placeholder");for(let F of J.attrs)switch(F.k){case"literal":if(F.name==="@format"){Y.binds.push(this.formatBind($,F));break}if(F.name.startsWith("@")){Y.binds.push({t:"prop",p:$,name:F.name.slice(1),e:this.synth(JSON.stringify(F.value))});break}if(B(F.name)){Y.binds.push({t:"attr",p:$,name:F.name,e:this.synth(JSON.stringify(F.value)),i18n:1});break}z+=` ${F.name}="${l(F.value)}"`;break;case"bool":F.name!=="i18n"&&F.value&&(z+=` ${F.name}`);break;case"expr":{if(F.name==="@format"){Y.binds.push(this.formatBind($,F));break}if(F.name.startsWith("@")){Y.binds.push({t:"prop",p:$,name:F.name.slice(1),e:this.expr(F.source,F.loc)});break}let V={t:"attr",p:$,name:F.name,e:this.expr(F.source,F.loc)};if(B(F.name))V.i18n=1;Y.binds.push(V);break}case"interp":{if(F.name==="@format"){Y.binds.push(this.formatBind($,F));break}let V={t:"attr",p:$,name:F.name,e:this.concat(F.parts)};if(B(F.name))V.i18n=1;Y.binds.push(V);break}case"event":Y.binds.push({t:"event",p:$,name:F.name,e:this.synth(F.source)});break;case"spread":Y.binds.push({t:"spread",p:$,e:this.expr(F.source,F.loc)});break;case"fn":this.report("LIPS-C007","warning",`Callable attribute '${F.name}(…)' has no meaning on <${J.tag}>`,F.loc.offset,F.loc.length);break;case"args":this.report("LIPS-C008","warning",`Iterator arguments are not applicable to <${J.tag}>`,F.loc.offset,F.loc.length);break}if(p.has(J.tag)){Q.push(z+">");return}Q.push(z+">"),J.children.length&&Z(J.children,$,U),Q.push(`</${J.tag}>`)}formatBind(J,K){let X=K.k==="literal"?K.value:K.k==="expr"?K.source:K.parts.map(($)=>typeof $==="string"?$:`{${$.expr}}`).join(""),Q=X.indexOf(",");if(Q===-1)return this.report("LIPS-C012","error",'@format expects "reference, { params }"',K.loc.offset,K.loc.length),{t:"prop",p:J,name:"format",e:this.synth("({})"),ref:X.trim()};let Y=X.slice(0,Q).trim(),Z=X.slice(Q+1).trim();return{t:"prop",p:J,name:"format",e:this.expr(Z,K.loc),ref:Y}}attrsOf(J){let K=new Map,X=[];for(let Q of J.attrs)if(Q.k==="args")X.push(...Q.names);else if("name"in Q)K.set(Q.name,Q);return{byName:K,args:X}}controlBlock(J,K,X,Q,Y,Z){switch(J.tag){case"if":{let $=[{when:J.head?this.expr(J.head.expr,J.head.loc):this.missingHead(J),block:this.block(J.children,Z)}];for(let z=X+1;z<K.length;z++){let U=K[z];if(U.t!=="element")break;if(U.tag==="else-if")$.push({when:U.head?this.expr(U.head.expr,U.head.loc):this.missingHead(U),block:this.block(U.children,Z)});else if(U.tag==="else"){$.push({when:null,block:this.block(U.children,Z)});break}else break}Y.blocks.push({t:"if",p:Q,branches:$});break}case"else-if":case"else":this.report("LIPS-C001","error",`<${J.tag}> without a preceding <if>`,J.loc.offset,J.loc.length);break;case"for":{let{byName:$,args:z}=this.attrsOf(J),U=$.get("in"),B=$.get("from"),F=$.get("to"),V=$.get("by");if(!U&&!B){this.report("LIPS-C004","error","<for> requires 'in' or 'from'/'to'",J.loc.offset,J.loc.length);break}let D={t:"for",p:Q,args:z,block:this.block(J.children,[...Z,...z])};if(U&&U.k==="expr")D.of=this.expr(U.source,U.loc);if(B)D.from=this.numInput(B);if(F)D.to=this.numInput(F);if(V&&(V.k==="literal"||V.k==="expr"))D.by=V.k==="literal"?{lit:V.value}:{e:this.expr(V.source,V.loc)};Y.blocks.push(D);break}case"switch":{let $=J.head?this.expr(J.head.expr,J.head.loc):this.missingHead(J),z=[];for(let U of J.children){if(U.t!=="element")continue;if(U.tag==="case"){let{byName:B}=this.attrsOf(U),F=B.get("is");if(!F||F.k!=="literal"&&F.k!=="expr"){this.report("LIPS-C004","error","<case> requires an 'is' attribute",U.loc.offset,U.loc.length);continue}z.push({is:F.k==="literal"?{lit:F.value}:{e:this.expr(F.source,F.loc)},block:this.block(U.children,Z)})}else if(U.tag==="default")z.push({is:null,block:this.block(U.children,Z)});else this.report("LIPS-C003","error","Only <case>/<default> are valid inside <switch>",U.loc.offset,U.loc.length)}Y.blocks.push({t:"switch",p:Q,on:$,cases:z});break}case"async":{let $=J.attrs.find((U)=>U.k==="fn"&&U.name==="await");if(!$){this.report("LIPS-C004","error","<async> requires await(…)",J.loc.offset,J.loc.length);break}let z={t:"async",p:Q,awaitE:this.expr($.source,$.loc)};for(let U of J.children){if(U.t!=="element")continue;let{args:B}=this.attrsOf(U);if(U.tag==="then")z.then={args:B,block:this.block(U.children,[...Z,...B])};else if(U.tag==="catch")z.catch={args:B,block:this.block(U.children,[...Z,...B])};else if(U.tag==="loading")z.loading=this.block(U.children,Z);else this.report("LIPS-C003","error","Only <then>/<catch>/<loading> are valid inside <async>",U.loc.offset,U.loc.length)}Y.blocks.push(z);break}case"let":case"const":{let $={};for(let z of J.attrs)if(z.k==="literal"||z.k==="expr"||z.k==="interp"||z.k==="bool")$[z.name]=this.compInput(z),!Y.scope.includes(z.name)&&Y.scope.push(z.name),!Z.includes(z.name)&&Z.push(z.name);Y.blocks.push({t:"let",p:Q,const:J.tag==="const",vars:$});break}case"log":Y.blocks.push({t:"log",p:Q,e:J.head?this.synth(J.head.expr):this.missingHead(J)});break}}missingHead(J){return this.report("LIPS-C004","error",`<${J.tag}> requires a head expression: <${J.tag}( … )>`,J.loc.offset,J.loc.length),this.synth("undefined")}numInput(J){if(J.k==="literal")return{lit:j(J.value)?Number(J.value):J.value};if(J.k==="expr")return j(J.source)?{lit:Number(J.source)}:{e:this.expr(J.source,J.loc)};return{lit:void 0}}macroCall(J,K,X){let Q=this.macros.get(J.tag);if(this.macroStack.includes(Q.name))return this.report("LIPS-C009","error",`Recursive macro <${Q.name}> (${[...this.macroStack,Q.name].join(" → ")})`,J.loc.offset,J.loc.length),null;let Y={};for(let $ of J.attrs)if($.k==="literal"||$.k==="expr"||$.k==="interp"||$.k==="bool")Y[$.name]=this.compInput($);for(let $ of Q.argv)if(!($ in Y))Y[$]={lit:void 0};this.macroStack.push(Q.name);let Z=this.block(Q.children,[...X,...Q.argv]);return this.macroStack.pop(),{t:"macro",p:K,name:Q.name,vars:Y,args:Q.argv,block:Z}}compLike(J,K,X,Q){let Y={},Z=[],$=[],z=[];for(let B of J.attrs)switch(B.k){case"literal":case"bool":case"expr":case"interp":Y[B.name]=this.compInput(B);break;case"event":$.push({name:B.name,e:this.synth(B.source)});break;case"spread":Z.push(this.expr(B.source,B.loc));break;case"args":z=[...z,...B.names];break;case"fn":Y[B.name]={e:this.expr(B.source,B.loc)};break}let U=J.children.length?{args:z,block:this.block(J.children,[...X,...z])}:void 0;return Q==="comp"?{t:"comp",p:K,name:J.tag,inputs:Y,spreads:Z,events:$,contents:U}:{t:"dynamic",p:K,tag:this.expr(J.dynamicTag.expr,J.dynamicTag.loc),inputs:Y,spreads:Z,events:$,contents:U}}}function c(J,K){let X=new Map;if(!J?.trim())return X;let Q=G(J);K.push(...Q.diagnostics);for(let Y of Q.root.children){if(Y.t!=="element")continue;if(Y.tag!=="macro"){K.push({code:"LIPS-C010",severity:"warning",message:`Only <macro> definitions are allowed in the macros source — ignoring <${Y.tag}>`,loc:{line:1,col:1,offset:Y.loc.offset,length:Y.loc.length}});continue}let Z="",$=[];for(let z of Y.attrs)if(z.k==="args")$.push(...z.names);else if(z.k==="literal"&&z.name==="name")Z=z.value;if(!Z){K.push({code:"LIPS-C011",severity:"error",message:"<macro> requires a name attribute",loc:{line:1,col:1,offset:Y.loc.offset,length:Y.loc.length}});continue}X.set(Z.toLowerCase(),{name:Z,argv:$,children:Y.children})}return X}function I(J,K){let X=[],Q=c(K?.macros||"",X),Y=G(J),Z=new _(J,Q);return{ir:Z.compile(Y.root.children),diagnostics:[...X,...Y.diagnostics,...Z.diagnostics]}}function e(J){let K={macros:J.macros},{ir:X,diagnostics:Q}=I(J.default||"",K),{default:Y,macros:Z,...$}=J;return{template:{...$,ir:X},diagnostics:Q}}var d=(J)=>JSON.stringify(J);function JJ(J={}){let K=J.include||/\.lips$/,X=J.reportDiagnostics!==!1;return{name:"lips:precompile",enforce:"pre",async transform(Q,Y){if(!K.test(Y))return null;let{parseSFC:Z}=await Promise.resolve().then(() => (M(),P)),{script:$}=Z(Q),z=Q.slice($.length),{ir:U,diagnostics:B}=I(z);if(X)for(let V of B)this?.warn?.(`[lips] ${V.code} ${V.message} (${Y}:${V.loc.line}:${V.loc.col})`);let F=B.filter((V)=>V.severity==="error");if(F.length)throw Error(`[lips] ${Y}: ${F[0].message} at line ${F[0].loc.line}:${F[0].loc.col}`);return{code:`${$}
|
|
9
|
+
const __lips_ir__ = ${d(U)};
|
|
10
|
+
export default {
|
|
11
|
+
ir: __lips_ir__,
|
|
12
|
+
${/\bconst\s+state\b/.test($)?"state,":""}
|
|
13
|
+
${/\bconst\s+handler\b/.test($)?"handler,":""}
|
|
14
|
+
${/\bconst\s+_static\b/.test($)?"_static,":""}
|
|
15
|
+
${/\bconst\s+context\b/.test($)?"context,":""}
|
|
16
|
+
${/\bconst\s+stylesheet\b/.test($)?"stylesheet,":""}
|
|
17
|
+
};
|
|
18
|
+
`,map:null}}}}export{d as serializeIR,e as precompile,JJ as lipsPlugin};
|
|
19
|
+
|
|
20
|
+
//# debugId=B0ACE61EC635C72564756E2164756E21
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/ir/parser.ts", "../src/ir/compiler.ts", "../src/ir/expression.ts", "../src/precompile.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"/**\n * Phase 2 — Template parser (RFC-001 §3–4)\n *\n * A dedicated recursive-descent parser for Lips templates:\n * - owns the syntax (no innerHTML, no regex preprocessing) — immune to\n * table-context hoisting, host-parser attribute lenience, whitespace\n * corruption\n * - positioned machine-readable diagnostics with error recovery\n * (`parse` never throws; broken templates yield partial ASTs)\n * - accepts the `.lips` SFC layout (frontscript + template) per\n * RFC-001 decision #5\n *\n * Attribute value semantics (predictable, no heuristics):\n * - `name=\"text\"` → literal string\n * - `name=\"a {expr} b\"` → interpolated parts\n * - `name=expr` → expression (whitespace-free, depth-aware)\n * - `name={ expr }` → expression (braced — spaces allowed)\n * - `name` / `!name` → boolean true / false\n * - `on-click( … )` → event instruction\n * - `await( … )` etc. → callable (fn) attribute\n * - `[a, b]` → iterator argument names\n * - `...expr` → spread\n */\n\n// ------------------------------------------------------------------- shared\nexport interface Loc {\n offset: number\n length: number\n}\nexport interface TemplateDiagnostic {\n code: string\n severity: 'error' | 'warning'\n message: string\n hint?: string\n loc: { line: number, col: number, offset: number, length: number }\n}\n\nexport type ExprSlot = { expr: string, loc: Loc }\n\n// ---------------------------------------------------------------------- AST\nexport type TemplateNode =\n | ElementNode\n | FragmentNode\n | { t: 'text', value: string, loc: Loc }\n | { t: 'interp', parts: ( string | ExprSlot )[], loc: Loc }\n | { t: 'comment', value: string, loc: Loc }\n\nexport interface FragmentNode {\n t: 'fragment'\n children: TemplateNode[]\n loc: Loc\n}\nexport interface ElementNode {\n t: 'element'\n tag: string // '#dynamic' for <{expr}>\n dynamicTag?: ExprSlot\n head?: ExprSlot // <if( … )>, <switch( … )>, <log( … )>\n attrs: AttrNode[]\n children: TemplateNode[]\n selfClosed: boolean\n loc: Loc\n}\n\nexport type AttrNode =\n | { k: 'literal', name: string, value: string, loc: Loc }\n | { k: 'interp', name: string, parts: ( string | ExprSlot )[], loc: Loc }\n | { k: 'expr', name: string, source: string, loc: Loc }\n | { k: 'bool', name: string, value: boolean, loc: Loc }\n | { k: 'event', name: string, source: string, loc: Loc }\n | { k: 'fn', name: string, source: string, loc: Loc }\n | { k: 'args', names: string[], loc: Loc }\n | { k: 'spread', source: string, loc: Loc }\n\nexport interface ParseResult {\n root: FragmentNode\n diagnostics: TemplateDiagnostic[]\n}\nexport interface SFCResult extends ParseResult {\n script: string\n}\n\n// ------------------------------------------------------------------- tables\nconst VOID_ELEMENTS = new Set([\n 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',\n 'link', 'meta', 'param', 'source', 'track', 'wbr'\n])\nconst RAW_WHITESPACE_TAGS = new Set([ 'pre', 'textarea' ])\nconst HEAD_SUGAR_TAGS = new Set([ 'if', 'else-if', 'switch', 'log' ])\n\nconst NAMED_ENTITIES: Record<string, string> = {\n '&': '&', '<': '<', '>': '>', '"': '\"', ''': \"'\", ' ': ' '\n}\nfunction decodeEntities( text: string ){\n return text.replace( /&(?:amp|lt|gt|quot|#39|nbsp);/g, m => NAMED_ENTITIES[ m ] )\n}\n\n// ------------------------------------------------------------------- parser\nclass TemplateParser {\n private pos = 0\n private lineStarts: number[] | null = null\n\n readonly diagnostics: TemplateDiagnostic[] = []\n\n constructor( private src: string ){}\n\n // ---- diagnostics helpers\n private locate( offset: number ){\n if( !this.lineStarts ){\n this.lineStarts = [ 0 ]\n for( let i = 0; i < this.src.length; i++ )\n if( this.src[ i ] === '\\n' ) this.lineStarts.push( i + 1 )\n }\n\n let lo = 0, hi = this.lineStarts.length - 1\n while( lo < hi ){\n const mid = ( lo + hi + 1 ) >> 1\n this.lineStarts[ mid ] <= offset ? lo = mid : hi = mid - 1\n }\n\n return { line: lo + 1, col: offset - this.lineStarts[ lo ] + 1 }\n }\n private report( code: string, severity: 'error' | 'warning', message: string, offset: number, length = 1, hint?: string ){\n const { line, col } = this.locate( offset )\n this.diagnostics.push({ code, severity, message, hint, loc: { line, col, offset, length } })\n }\n\n // ---- scanning helpers\n private eof(){ return this.pos >= this.src.length }\n private peek( offset = 0 ){ return this.src[ this.pos + offset ] }\n private startsWith( str: string ){ return this.src.startsWith( str, this.pos ) }\n private skipSpace(){ while( !this.eof() && /\\s/.test( this.src[ this.pos ] ) ) this.pos++ }\n\n /**\n * Scan a balanced region: from an opening delimiter already\n * consumed, up to (not including) its matching closer at depth 0.\n * String literals are opaque; (), [], {} all nest.\n */\n private scanBalanced( closer: string, code: string ): { content: string, loc: Loc } | null {\n const start = this.pos\n let depth = 0\n\n while( !this.eof() ){\n const c = this.src[ this.pos ]\n\n if( c === \"'\" || c === '\"' || c === '`' ){\n this.pos++\n while( !this.eof() && this.src[ this.pos ] !== c ){\n if( this.src[ this.pos ] === '\\\\' ) this.pos++\n this.pos++\n }\n this.pos++\n continue\n }\n\n if( depth === 0 && c === closer ){\n const content = this.src.slice( start, this.pos )\n this.pos++ // consume closer\n return { content, loc: { offset: start, length: content.length } }\n }\n\n if( c === '(' || c === '[' || c === '{' ) depth++\n else if( c === ')' || c === ']' || c === '}' ){\n if( depth === 0 && c !== closer ){\n this.report( code, 'error', `Unbalanced '${c}'`, this.pos )\n this.pos++\n continue\n }\n depth--\n }\n\n this.pos++\n }\n\n this.report( code, 'error', `Unterminated — expected '${closer}'`, start, this.pos - start )\n return null\n }\n\n // ---- entry\n parse(): ParseResult {\n const children: TemplateNode[] = []\n\n while( !this.eof() ){\n children.push( ...this.parseNodes( [] ) )\n\n // Root-level stray closing tag: report, consume, resume\n if( this.startsWith('</') ){\n const closeStart = this.pos\n this.pos += 2\n while( !this.eof() && this.peek() !== '>' ) this.pos++\n !this.eof() && this.pos++\n this.report( 'LIPS-P005', 'error',\n `Stray closing tag ${this.src.slice( closeStart, this.pos )}`, closeStart, this.pos - closeStart )\n }\n }\n\n return {\n root: { t: 'fragment', children, loc: { offset: 0, length: this.src.length } },\n diagnostics: this.diagnostics\n }\n }\n\n /**\n * Parse siblings until EOF or a closing tag belonging to\n * an ancestor. `stack` holds open ancestor tag names for\n * mismatch recovery.\n */\n private parseNodes( stack: string[] ): TemplateNode[] {\n const nodes: TemplateNode[] = []\n\n while( !this.eof() ){\n if( this.startsWith('</') ) break\n\n const before = this.pos\n\n if( this.peek() === '<' && this.peek( 1 ) !== undefined ){\n const node = this.parseTag( stack )\n node && nodes.push( node )\n }\n else {\n const text = this.parseText( stack )\n text && nodes.push( text )\n }\n\n /**\n * Progress guard: recovery paths must never stall the\n * loop (e.g. a lone '<' at EOF yields no node and no\n * consumption) — force one character forward.\n */\n if( this.pos === before ) this.pos++\n }\n\n return nodes\n }\n\n // ---- text & interpolation\n private parseText( stack: string[] ): TemplateNode | null {\n const start = this.pos\n const parts: ( string | ExprSlot )[] = []\n let buffer = ''\n\n while( !this.eof() && this.peek() !== '<' ){\n if( this.peek() === '{' ){\n this.pos++ // consume '{'\n const region = this.scanBalanced( '}', 'LIPS-P007' )\n if( region ){\n buffer && parts.push( buffer )\n buffer = ''\n parts.push({ expr: region.content.trim(), loc: region.loc })\n }\n continue\n }\n\n buffer += this.peek()\n this.pos++\n }\n buffer && parts.push( buffer )\n\n const loc: Loc = { offset: start, length: this.pos - start }\n\n // Interpolated text\n if( parts.some( p => typeof p !== 'string' ) )\n return {\n t: 'interp',\n parts: parts.map( p => typeof p === 'string' ? decodeEntities( p ) : p ),\n loc\n }\n\n const raw = parts.length ? parts[0] as string : ''\n /**\n * Drop whitespace-only text except inside <pre>/<textarea>\n */\n const inRaw = stack.some( tag => RAW_WHITESPACE_TAGS.has( tag ) )\n if( !raw || ( !inRaw && !raw.trim() ) ) return null\n\n return { t: 'text', value: decodeEntities( raw ), loc }\n }\n\n // ---- tags\n private parseTag( stack: string[] ): TemplateNode | null {\n const start = this.pos\n\n // Comment\n if( this.startsWith('<!--') ){\n const end = this.src.indexOf( '-->', this.pos + 4 )\n if( end === -1 ){\n this.report( 'LIPS-P003', 'error', 'Unterminated comment', start, this.src.length - start )\n this.pos = this.src.length\n return null\n }\n const value = this.src.slice( this.pos + 4, end )\n this.pos = end + 3\n return { t: 'comment', value, loc: { offset: start, length: this.pos - start } }\n }\n\n // Fragment open <>\n if( this.startsWith('<>') ){\n this.pos += 2\n const children: TemplateNode[] = []\n\n while( true ){\n children.push( ...this.parseNodes( [ ...stack, '#fragment' ] ) )\n if( this.closeStatus( '#fragment', start, stack ) !== 'stray' ) break\n }\n\n return { t: 'fragment', children, loc: { offset: start, length: this.pos - start } }\n }\n\n // Dynamic tag <{expr} …>\n if( this.startsWith('<{') ){\n this.pos += 2\n const region = this.scanBalanced( '}', 'LIPS-P008' )\n if( !region ) return null\n\n const el: ElementNode = {\n t: 'element',\n tag: '#dynamic',\n dynamicTag: { expr: region.content.trim(), loc: region.loc },\n attrs: [],\n children: [],\n selfClosed: false,\n loc: { offset: start, length: 0 }\n }\n this.finishTag( el, stack, start )\n return el\n }\n\n // Named tag\n this.pos++ // consume '<'\n const nameStart = this.pos\n while( !this.eof() && /[A-Za-z0-9_-]/.test( this.peek() ) ) this.pos++\n const tag = this.src.slice( nameStart, this.pos )\n\n if( !tag || !/^[A-Za-z]/.test( tag ) ){\n this.report( 'LIPS-P002', 'error', 'Invalid tag name', start, this.pos - start + 1 )\n // Recovery: emit the '<' as literal text\n return { t: 'text', value: '<', loc: { offset: start, length: 1 } }\n }\n\n const el: ElementNode = {\n t: 'element',\n tag: tag.toLowerCase(),\n attrs: [],\n children: [],\n selfClosed: false,\n loc: { offset: start, length: 0 }\n }\n\n // Sugar head: <if( … )>, <else-if( … )>, <switch( … )>, <log( … )>\n if( this.peek() === '(' ){\n if( HEAD_SUGAR_TAGS.has( el.tag ) ){\n this.pos++ // consume '('\n const region = this.scanBalanced( ')', 'LIPS-P012' )\n region && ( el.head = { expr: region.content.trim(), loc: region.loc } )\n }\n else this.report( 'LIPS-P011', 'error', `Head expression is not allowed on <${el.tag}>`, this.pos,\n 1, `Only ${[ ...HEAD_SUGAR_TAGS ].map( t => `<${t}(…)>` ).join(', ')} take a head` )\n }\n\n this.finishTag( el, stack, start )\n return el\n }\n\n /** attrs → '>' | '/>' → children → closing tag */\n private finishTag( el: ElementNode, stack: string[], start: number ){\n this.parseAttrs( el )\n\n // Self closing / void\n if( el.selfClosed || VOID_ELEMENTS.has( el.tag ) ){\n el.selfClosed = true\n el.loc = { offset: start, length: this.pos - start }\n return\n }\n\n const stackName = el.tag === '#dynamic' ? '#dynamic' : el.tag\n el.children = []\n\n /**\n * Loop so a stray closing tag inside the element is\n * consumed (with a diagnostic) and children parsing\n * resumes — the element doesn't silently end early.\n */\n while( true ){\n el.children.push( ...this.parseNodes( [ ...stack, stackName ] ) )\n if( this.closeStatus( stackName, start, stack ) !== 'stray' ) break\n }\n\n el.loc = { offset: start, length: this.pos - start }\n }\n\n /**\n * Consume the closing tag for `tag`. Recovery rules:\n * - `</>` closes fragments and dynamic tags (and anything, with a warning)\n * - mismatch that matches an ancestor → auto-close (warning), leave input\n * for the ancestor to consume\n * - stray close → report, consume, caller resumes children\n * - EOF → unclosed element (error)\n */\n private closeStatus( tag: string, openOffset: number, stack: string[] ): 'closed' | 'ancestor' | 'stray' | 'eof' {\n if( this.eof() ){\n this.report( 'LIPS-P006', 'error', `Unclosed <${tag === '#fragment' ? '' : tag}> — reached end of template`, openOffset,\n 1, `Add </${tag === '#fragment' || tag === '#dynamic' ? '' : tag}>` )\n return 'eof'\n }\n\n if( !this.startsWith('</') ) return 'closed' // parseNodes stopped for another reason\n\n const closeStart = this.pos\n this.pos += 2\n\n // Generic close </>\n if( this.peek() === '>' ){\n this.pos++\n if( tag !== '#fragment' && tag !== '#dynamic' )\n this.report( 'LIPS-P004', 'warning', `Generic '</>' closes <${tag}>`, closeStart, 3, `Prefer </${tag}>` )\n return 'closed'\n }\n\n const nameStart = this.pos\n while( !this.eof() && /[A-Za-z0-9_-]/.test( this.peek() ) ) this.pos++\n const closeTag = this.src.slice( nameStart, this.pos ).toLowerCase()\n this.skipSpace()\n this.peek() === '>' ? this.pos++ : this.report( 'LIPS-P001', 'error', `Malformed closing tag`, closeStart, this.pos - closeStart )\n\n if( closeTag === tag ) return 'closed'\n\n // Mismatch: ancestor match → rewind so the ancestor consumes it\n if( stack.includes( closeTag ) ){\n this.report( 'LIPS-P004', 'warning', `</${closeTag}> auto-closes <${tag}>`, closeStart, this.pos - closeStart,\n `Add the missing </${tag}> before </${closeTag}>` )\n this.pos = closeStart\n return 'ancestor'\n }\n\n this.report( 'LIPS-P005', 'error', `Stray closing tag </${closeTag}> — <${tag}> is open`, closeStart, this.pos - closeStart )\n return 'stray'\n }\n\n // ---- attributes\n private parseAttrs( el: ElementNode ){\n while( true ){\n this.skipSpace()\n if( this.eof() ){\n this.report( 'LIPS-P001', 'error', 'Unexpected end of template inside tag', el.loc.offset )\n return\n }\n\n if( this.startsWith('/>') ){ this.pos += 2; el.selfClosed = true; return }\n if( this.peek() === '>' ){ this.pos++; return }\n\n const attrStart = this.pos\n\n // Spread: ...expr\n if( this.startsWith('...') ){\n this.pos += 3\n const source = this.readUnquotedValue()\n el.attrs.push({ k: 'spread', source, loc: { offset: attrStart, length: this.pos - attrStart } })\n continue\n }\n\n // Iterator args: [a, b]\n if( this.peek() === '[' ){\n this.pos++\n const region = this.scanBalanced( ']', 'LIPS-P009' )\n if( region ){\n const names = region.content.split(',').map( s => s.trim() ).filter( Boolean )\n el.attrs.push({ k: 'args', names, loc: { offset: attrStart, length: this.pos - attrStart } })\n }\n continue\n }\n\n // Boolean negation: !name\n let negated = false\n if( this.peek() === '!' ){ negated = true; this.pos++ }\n\n // Attribute name\n const nameStart = this.pos\n while( !this.eof() && /[^\\s=/>()]/.test( this.peek() ) ) this.pos++\n const name = this.src.slice( nameStart, this.pos )\n\n if( !name ){\n this.report( 'LIPS-P009', 'error', `Invalid attribute syntax at '${this.peek()}'`, this.pos )\n this.pos++\n continue\n }\n\n // Callable form: on-click( … ), await( … )\n if( this.peek() === '(' ){\n this.pos++\n const region = this.scanBalanced( ')', 'LIPS-P010' )\n const source = region ? region.content.trim() : ''\n const loc: Loc = { offset: attrStart, length: this.pos - attrStart }\n\n name.startsWith('on-')\n ? el.attrs.push({ k: 'event', name: name.slice( 3 ), source, loc })\n : el.attrs.push({ k: 'fn', name, source, loc })\n continue\n }\n\n // Valued: name=…\n if( this.peek() === '=' ){\n this.pos++\n this.parseAttrValue( el, name, attrStart )\n continue\n }\n\n // Bare boolean\n el.attrs.push({ k: 'bool', name, value: !negated, loc: { offset: attrStart, length: this.pos - attrStart } })\n }\n }\n\n private parseAttrValue( el: ElementNode, name: string, attrStart: number ){\n const q = this.peek()\n\n // Quoted: literal or interpolated\n if( q === '\"' || q === \"'\" ){\n this.pos++\n const valueStart = this.pos\n const parts: ( string | ExprSlot )[] = []\n let buffer = ''\n\n while( !this.eof() && this.peek() !== q ){\n if( this.peek() === '{' ){\n this.pos++\n const region = this.scanBalanced( '}', 'LIPS-P007' )\n if( region ){\n buffer && parts.push( buffer )\n buffer = ''\n parts.push({ expr: region.content.trim(), loc: region.loc })\n }\n continue\n }\n buffer += this.peek()\n this.pos++\n }\n buffer && parts.push( buffer )\n\n this.eof()\n ? this.report( 'LIPS-P010', 'error', `Unterminated value for '${name}'`, valueStart, this.pos - valueStart )\n : this.pos++ // consume quote\n\n const loc: Loc = { offset: attrStart, length: this.pos - attrStart }\n\n parts.some( p => typeof p !== 'string' )\n ? el.attrs.push({ k: 'interp', name, parts: parts.map( p => typeof p === 'string' ? decodeEntities( p ) : p ), loc })\n : el.attrs.push({ k: 'literal', name, value: decodeEntities( ( parts[0] as string ) ?? '' ), loc })\n return\n }\n\n // Braced expression: name={ expr } — spaces allowed\n if( q === '{' ){\n this.pos++\n const region = this.scanBalanced( '}', 'LIPS-P007' )\n el.attrs.push({\n k: 'expr', name,\n source: region ? region.content.trim() : '',\n loc: { offset: attrStart, length: this.pos - attrStart }\n })\n return\n }\n\n // Unquoted expression — whitespace-free, depth-aware\n const source = this.readUnquotedValue()\n source\n ? el.attrs.push({ k: 'expr', name, source, loc: { offset: attrStart, length: this.pos - attrStart } })\n : this.report( 'LIPS-P010', 'error', `Missing value for attribute '${name}'`, attrStart )\n }\n\n /** Read an unquoted value: until whitespace/'>'/'/>' at depth 0 */\n private readUnquotedValue(): string {\n const start = this.pos\n let depth = 0\n\n while( !this.eof() ){\n const c = this.peek()\n\n if( c === \"'\" || c === '\"' || c === '`' ){\n this.pos++\n while( !this.eof() && this.peek() !== c ){\n if( this.peek() === '\\\\' ) this.pos++\n this.pos++\n }\n this.pos++\n continue\n }\n\n if( depth === 0 ){\n if( /\\s/.test( c ) || c === '>' ) break\n if( c === '/' && this.peek( 1 ) === '>' ) break\n }\n\n if( c === '(' || c === '[' || c === '{' ) depth++\n else if( c === ')' || c === ']' || c === '}' ) depth--\n\n this.pos++\n }\n\n return this.src.slice( start, this.pos ).trim()\n }\n}\n\n// -------------------------------------------------------------------- API\nexport function parseTemplate( src: string ): ParseResult {\n return new TemplateParser( src || '' ).parse()\n}\n\n/**\n * `.lips` single-file component: frontscript (JS/TS) followed by the\n * template. The template starts at the first line-leading `<` that sits\n * at top-level script depth (outside strings, comments, and brackets).\n */\nexport function parseSFC( src: string ): SFCResult {\n const splitAt = findTemplateStart( src || '' )\n const script = ( src || '' ).slice( 0, splitAt ).trimEnd()\n const templateSrc = ( src || '' ).slice( splitAt )\n\n const result = new TemplateParser( templateSrc ).parse()\n /**\n * Re-anchor diagnostic lines to the full SFC source\n */\n const lineOffset = script ? script.split('\\n').length + ( /\\n\\s*\\n$/.test( src.slice( 0, splitAt ) ) ? 1 : 0 ) : 0\n result.diagnostics.forEach( d => {\n d.loc.line += script ? src.slice( 0, splitAt ).split('\\n').length - 1 : 0\n d.loc.offset += splitAt\n })\n\n return { script, ...result }\n}\n\nfunction findTemplateStart( src: string ): number {\n let\n depth = 0,\n lineStart = true\n\n for( let i = 0; i < src.length; i++ ){\n const c = src[ i ]\n\n // Strings are opaque\n if( c === \"'\" || c === '\"' || c === '`' ){\n const quote = c\n i++\n while( i < src.length && src[ i ] !== quote ){\n if( src[ i ] === '\\\\' ) i++\n i++\n }\n lineStart = false\n continue\n }\n // Comments are opaque\n if( c === '/' && src[ i + 1 ] === '/' ){\n while( i < src.length && src[ i ] !== '\\n' ) i++\n lineStart = true\n continue\n }\n if( c === '/' && src[ i + 1 ] === '*' ){\n const end = src.indexOf( '*/', i + 2 )\n i = end === -1 ? src.length : end + 1\n continue\n }\n\n if( c === '\\n' ){ lineStart = true; continue }\n\n if( lineStart && depth === 0 && c === '<' && /[A-Za-z{>!]/.test( src[ i + 1 ] || '' ) )\n return i\n\n if( c === '(' || c === '[' || c === '{' ) depth++\n else if( c === ')' || c === ']' || c === '}' ) depth = Math.max( 0, depth - 1 )\n\n if( !/\\s/.test( c ) ) lineStart = false\n }\n\n return 0 // no script section — whole source is template\n}\n",
|
|
6
|
+
"/**\n * Phase 2 — IR compiler (RFC-001 §4)\n *\n * TemplateAST → TemplateIR:\n * - static HTML skeletons per block, ready for one-time <template>\n * parsing + per-instance cloneNode\n * - integer-path bind table (childNodes index walks — no string paths)\n * - control-flow block nodes anchored by comment placeholders whose\n * paths are precomputed (the compiler simulates browser text-node\n * coalescing so paths survive the HTML round-trip)\n * - deduped expression table; every authored expression is validated\n * at compile time and its diagnostics re-anchored to template\n * line/col\n *\n * The output is JSON-serializable and deterministic — it is the\n * Modela artifact, the runtime render program, and the hot-swap\n * diff unit.\n */\n\nimport type {\n TemplateNode,\n ElementNode,\n AttrNode,\n ExprSlot,\n TemplateDiagnostic\n} from './parser'\nimport { parseTemplate } from './parser'\nimport { parseExpression } from './expression'\n\n// ------------------------------------------------------------------- types\nexport type Path = number[]\nexport type E = number\n\nexport type CompInput =\n | { e: E }\n | { lit: unknown }\n\nexport interface TemplateIR {\n v: 1\n exprs: string[]\n root: BlockIR\n}\n\nexport interface BlockIR {\n html: string\n /**\n * Scope variable names visible to this block's binds\n * (iterator args, async arm args, let/const names —\n * let names are block-scoped from block start, see RFC)\n */\n scope: string[]\n binds: BindIR[]\n blocks: ChildIR[]\n}\n\nexport type BindIR =\n | { t: 'text', p: Path, e: E, i18n?: 1 } // anchor; runtime inserts a text node after it\n | { t: 'attr', p: Path, name: string, e: E, i18n?: 1 }\n | { t: 'prop', p: Path, name: string, e: E, i18n?: 1, ref?: string } // @html / @text / @format\n | { t: 'event', p: Path, name: string, e: E } // raw instruction — runtime resolves handler form\n | { t: 'spread', p: Path, e: E }\n\nexport interface ArmIR {\n args: string[]\n block: BlockIR\n}\n\nexport type ChildIR =\n | { t: 'macro', p: Path, name: string, vars: Record<string, CompInput>, args: string[], block: BlockIR }\n | { t: 'if', p: Path, branches: { when: E | null, block: BlockIR }[] }\n | { t: 'for', p: Path, of?: E, from?: CompInput, to?: CompInput, by?: CompInput, args: string[], block: BlockIR }\n | { t: 'switch', p: Path, on: E, cases: { is: CompInput | null, block: BlockIR }[] }\n | { t: 'async', p: Path, awaitE: E, then?: ArmIR, catch?: ArmIR, loading?: BlockIR }\n | { t: 'let', p: Path, const: boolean, vars: Record<string, CompInput> }\n | { t: 'log', p: Path, e: E }\n | { t: 'comp', p: Path, name: string, inputs: Record<string, CompInput>, spreads: E[], events: { name: string, e: E }[], contents?: ArmIR }\n | { t: 'dynamic', p: Path, tag: E, inputs: Record<string, CompInput>, spreads: E[], events: { name: string, e: E }[], contents?: ArmIR }\n\nexport interface CompileResult {\n ir: TemplateIR\n diagnostics: TemplateDiagnostic[]\n}\n\nexport interface CompileOptions {\n /** `<macro [argv] name=\"X\">…</macro>` definitions, inlined at call sites */\n macros?: string\n}\n\ninterface MacroDef {\n name: string\n argv: string[]\n children: TemplateNode[]\n}\n\n// ------------------------------------------------------------------ tables\nconst ANCHOR = '<!--$-->'\n\nconst CONTROL_TAGS = new Set([ 'if', 'else-if', 'else', 'for', 'switch', 'async', 'let', 'const', 'log' ])\nconst ARM_TAGS = new Set([ 'case', 'default', 'then', 'catch', 'loading' ])\n\n/** Standard HTML + common SVG tags — anything else is a component candidate */\nconst HTML_TAGS = new Set([\n 'a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo',\n 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col',\n 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl',\n 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2',\n 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img',\n 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'menu',\n 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p',\n 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section',\n 'select', 'slot', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup',\n 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title',\n 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr',\n // SVG\n 'svg', 'circle', 'clippath', 'defs', 'ellipse', 'foreignobject', 'g', 'image', 'line',\n 'lineargradient', 'marker', 'mask', 'path', 'pattern', 'polygon', 'polyline',\n 'radialgradient', 'rect', 'stop', 'symbol', 'text', 'tspan', 'use'\n])\n\nconst VOID_ELEMENTS = new Set([\n 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',\n 'link', 'meta', 'param', 'source', 'track', 'wbr'\n])\n\n// ----------------------------------------------------------------- helpers\nconst escText = ( s: string ) => s.replace( /&/g, '&' ).replace( /</g, '<' ).replace( />/g, '>' )\nconst escAttr = ( s: string ) => s.replace( /&/g, '&' ).replace( /\"/g, '"' ).replace( /</g, '<' )\n\nconst isNumeric = ( s: string ) => s !== '' && !isNaN( Number( s ) )\n\n// ---------------------------------------------------------------- compiler\nclass Compiler {\n private exprs: string[] = []\n private exprIndex = new Map<string, E>()\n private lineStarts: number[] | null = null\n /** Guards against macros that (indirectly) call themselves */\n private macroStack: string[] = []\n\n readonly diagnostics: TemplateDiagnostic[] = []\n\n constructor( private src: string, private macros = new Map<string, MacroDef>() ){}\n\n // ---- diagnostics\n private locate( offset: number ){\n if( !this.lineStarts ){\n this.lineStarts = [ 0 ]\n for( let i = 0; i < this.src.length; i++ )\n if( this.src[ i ] === '\\n' ) this.lineStarts.push( i + 1 )\n }\n\n let lo = 0, hi = this.lineStarts.length - 1\n while( lo < hi ){\n const mid = ( lo + hi + 1 ) >> 1\n this.lineStarts[ mid ] <= offset ? lo = mid : hi = mid - 1\n }\n\n return { line: lo + 1, col: offset - this.lineStarts[ lo ] + 1 }\n }\n private report( code: string, severity: 'error' | 'warning', message: string, offset: number, length = 1, hint?: string ){\n const { line, col } = this.locate( offset )\n this.diagnostics.push({ code, severity, message, hint, loc: { line, col, offset, length } })\n }\n\n // ---- expression table\n /** Register an authored expression: validate + dedupe */\n private expr( source: string, at?: { offset: number, length?: number } ): E {\n const cached = this.exprIndex.get( source )\n if( cached !== undefined ) return cached\n\n const { diagnostics } = parseExpression( source )\n for( const d of diagnostics ){\n const offset = ( at?.offset ?? 0 ) + d.loc.offset\n this.report( d.code, 'error', d.message, offset, d.loc.length )\n }\n\n const idx = this.exprs.length\n this.exprs.push( source )\n this.exprIndex.set( source, idx )\n return idx\n }\n /** Register a synthesized expression (parts already validated) */\n private synth( source: string ): E {\n const cached = this.exprIndex.get( source )\n if( cached !== undefined ) return cached\n\n const idx = this.exprs.length\n this.exprs.push( source )\n this.exprIndex.set( source, idx )\n return idx\n }\n /**\n * Interpolation parts → one concat expression.\n * Nullish parts render '' (RFC decision #4).\n */\n private concat( parts: ( string | ExprSlot )[] ): E {\n parts\n .filter( ( p ): p is ExprSlot => typeof p !== 'string' )\n .forEach( p => {\n const { diagnostics } = parseExpression( p.expr )\n for( const d of diagnostics )\n this.report( d.code, 'error', d.message, p.loc.offset + d.loc.offset, d.loc.length )\n })\n\n const source = parts\n .map( p => typeof p === 'string' ? JSON.stringify( p ) : `((${p.expr})??\"\")` )\n .join('+')\n\n return this.synth( source )\n }\n private compInput( attr: AttrNode & { k: 'literal' | 'expr' | 'interp' | 'bool' } ): CompInput {\n switch( attr.k ){\n case 'literal': return { lit: attr.value }\n case 'bool': return { lit: attr.value }\n case 'expr': return { e: this.expr( attr.source, attr.loc ) }\n case 'interp': return { e: this.concat( attr.parts ) }\n }\n }\n\n // ---- entry\n compile( children: TemplateNode[] ): TemplateIR {\n return { v: 1, exprs: this.exprs, root: this.block( children, [] ) }\n }\n\n /**\n * Compile a node list into a BlockIR: static HTML with\n * precomputed paths for every bind/anchor. `scope` may\n * grow when <let>/<const> introduce names.\n */\n private block( children: TemplateNode[], scope: string[] ): BlockIR {\n const block: BlockIR = { html: '', scope: [ ...scope ], binds: [], blocks: [] }\n const html: string[] = []\n\n /**\n * Emit a sibling list at `path` depth. Returns nothing —\n * appends to html / block.binds / block.blocks.\n * The index simulation must match browser parsing:\n * consecutive static text coalesces into ONE node.\n */\n const emitSiblings = ( nodes: TemplateNode[], path: Path, i18nParent = false ) => {\n let index = 0\n let lastWasText = false\n\n const anchor = (): Path => {\n html.push( ANCHOR )\n lastWasText = false\n return [ ...path, index++ ]\n }\n\n for( let i = 0; i < nodes.length; i++ ){\n const node = nodes[ i ]\n\n switch( node.t ){\n case 'text': {\n /**\n * Static text under an `i18n` element still needs a\n * bind — there is nothing to translate in a skeleton.\n */\n if( i18nParent ){\n block.binds.push({ t: 'text', p: anchor(), e: this.synth( JSON.stringify( node.value ) ), i18n: 1 })\n break\n }\n\n html.push( escText( node.value ) )\n if( !lastWasText ) index++\n lastWasText = true\n break\n }\n case 'comment': {\n html.push( `<!--${node.value.replace( /--/g, '- -' )}-->` )\n lastWasText = false\n index++\n break\n }\n case 'interp': {\n const bind: BindIR = { t: 'text', p: anchor(), e: this.concat( node.parts ) }\n if( i18nParent ) bind.i18n = 1\n block.binds.push( bind )\n break\n }\n case 'fragment': {\n /**\n * Nested fragments are transparent: children emit\n * into the current index space. Rebuild sibling\n * numbering by splicing children inline.\n */\n nodes = [ ...nodes.slice( 0, i ), ...node.children, ...nodes.slice( i + 1 ) ]\n i--\n break\n }\n case 'element': {\n // Control flow → anchored child block\n if( CONTROL_TAGS.has( node.tag ) ){\n this.controlBlock( node, nodes, i, anchor(), block, scope )\n\n // if-chains consume their else-if/else siblings\n if( node.tag === 'if' ){\n let j = i + 1\n while( j < nodes.length ){\n const sib = nodes[ j ]\n if( sib.t === 'element' && ( sib.tag === 'else-if' || sib.tag === 'else' ) ) j++\n else break\n }\n nodes = [ ...nodes.slice( 0, i + 1 ), ...nodes.slice( j ) ]\n }\n break\n }\n\n // Arm tags outside their parents\n if( ARM_TAGS.has( node.tag ) ){\n this.report( 'LIPS-C002', 'error',\n `<${node.tag}> is only valid inside its parent construct`, node.loc.offset, node.loc.length )\n break\n }\n\n // Dynamic tag\n if( node.tag === '#dynamic' ){\n block.blocks.push( this.compLike( node, anchor(), scope, 'dynamic' ) )\n break\n }\n\n // Macro call → inline the definition body\n if( this.macros.has( node.tag ) ){\n const macroBlock = this.macroCall( node, anchor(), scope )\n macroBlock && block.blocks.push( macroBlock )\n break\n }\n\n // Component candidate\n if( !HTML_TAGS.has( node.tag ) ){\n block.blocks.push( this.compLike( node, anchor(), scope, 'comp' ) )\n break\n }\n\n // Plain HTML element\n this.emitElement( node, path, index++, html, block, emitSiblings )\n lastWasText = false\n break\n }\n }\n }\n }\n\n emitSiblings( children, [] )\n block.html = html.join('')\n return block\n }\n\n /** Static open tag + dynamic binds + children recursion */\n private emitElement(\n node: ElementNode,\n path: Path,\n index: number,\n html: string[],\n block: BlockIR,\n emitSiblings: ( nodes: TemplateNode[], path: Path, i18nParent?: boolean ) => void\n ){\n const p: Path = [ ...path, index ]\n let open = `<${node.tag}`\n\n /**\n * `i18n` marks an element's own text and its visual\n * attributes (title/placeholder) as translatable.\n */\n const i18n = node.attrs.some( a => a.k === 'bool' && a.name === 'i18n' && a.value )\n const translatableAttr = ( name: string ) => i18n && ( name === 'title' || name === 'placeholder' )\n\n for( const attr of node.attrs ){\n switch( attr.k ){\n case 'literal':\n if( attr.name === '@format' ){\n block.binds.push( this.formatBind( p, attr ) )\n break\n }\n if( attr.name.startsWith('@') ){\n block.binds.push({ t: 'prop', p, name: attr.name.slice( 1 ), e: this.synth( JSON.stringify( attr.value ) ) })\n break\n }\n // Literal title/placeholder under i18n must become a bind to be translated\n if( translatableAttr( attr.name ) ){\n block.binds.push({ t: 'attr', p, name: attr.name, e: this.synth( JSON.stringify( attr.value ) ), i18n: 1 })\n break\n }\n open += ` ${attr.name}=\"${escAttr( attr.value )}\"`\n break\n case 'bool':\n // `i18n` is a compiler directive, not an output attribute\n attr.name !== 'i18n' && attr.value && ( open += ` ${attr.name}` )\n break\n case 'expr': {\n if( attr.name === '@format' ){\n block.binds.push( this.formatBind( p, attr ) )\n break\n }\n if( attr.name.startsWith('@') ){\n block.binds.push({ t: 'prop', p, name: attr.name.slice( 1 ), e: this.expr( attr.source, attr.loc ) })\n break\n }\n\n const bind: BindIR = { t: 'attr', p, name: attr.name, e: this.expr( attr.source, attr.loc ) }\n if( translatableAttr( attr.name ) ) bind.i18n = 1\n block.binds.push( bind )\n break\n }\n case 'interp': {\n if( attr.name === '@format' ){\n block.binds.push( this.formatBind( p, attr ) )\n break\n }\n\n const bind: BindIR = { t: 'attr', p, name: attr.name, e: this.concat( attr.parts ) }\n if( translatableAttr( attr.name ) ) bind.i18n = 1\n block.binds.push( bind )\n break\n }\n case 'event':\n block.binds.push({ t: 'event', p, name: attr.name, e: this.synth( attr.source ) })\n break\n case 'spread':\n block.binds.push({ t: 'spread', p, e: this.expr( attr.source, attr.loc ) })\n break\n case 'fn':\n this.report( 'LIPS-C007', 'warning',\n `Callable attribute '${attr.name}(…)' has no meaning on <${node.tag}>`, attr.loc.offset, attr.loc.length )\n break\n case 'args':\n this.report( 'LIPS-C008', 'warning',\n `Iterator arguments are not applicable to <${node.tag}>`, attr.loc.offset, attr.loc.length )\n break\n }\n }\n\n if( VOID_ELEMENTS.has( node.tag ) ){\n html.push( open + '>' )\n return\n }\n\n html.push( open + '>' )\n node.children.length && emitSiblings( node.children, p, i18n )\n html.push( `</${node.tag}>` )\n }\n\n /**\n * `@format=\"reference, { params }\"` → a prop bind carrying the\n * dictionary reference plus a compiled params expression.\n */\n private formatBind( p: Path, attr: AttrNode & { k: 'literal' | 'expr' | 'interp' } ): BindIR {\n /**\n * `@format` carries a reference plus a params OBJECT, so the\n * braces are data — not interpolation. Reconstruct the raw\n * source when the parser split it into interpolation parts.\n */\n const raw = attr.k === 'literal' ? attr.value\n : attr.k === 'expr' ? attr.source\n : attr.parts.map( part => typeof part === 'string' ? part : `{${part.expr}}` ).join('')\n\n const comma = raw.indexOf(',')\n\n if( comma === -1 ){\n this.report( 'LIPS-C012', 'error',\n `@format expects \"reference, { params }\"`, attr.loc.offset, attr.loc.length )\n return { t: 'prop', p, name: 'format', e: this.synth('({})'), ref: raw.trim() }\n }\n\n const\n ref = raw.slice( 0, comma ).trim(),\n params = raw.slice( comma + 1 ).trim()\n\n return { t: 'prop', p, name: 'format', e: this.expr( params, attr.loc ), ref }\n }\n\n // ---- control-flow blocks\n private attrsOf( node: ElementNode ){\n const\n byName = new Map<string, AttrNode>(),\n args: string[] = []\n\n for( const attr of node.attrs ){\n if( attr.k === 'args' ) args.push( ...attr.names )\n else if( 'name' in attr ) byName.set( attr.name, attr )\n }\n return { byName, args }\n }\n\n private controlBlock( node: ElementNode, siblings: TemplateNode[], i: number, p: Path, block: BlockIR, scope: string[] ){\n switch( node.tag ){\n case 'if': {\n const branches: { when: E | null, block: BlockIR }[] = [{\n when: node.head ? this.expr( node.head.expr, node.head.loc ) : this.missingHead( node ),\n block: this.block( node.children, scope )\n }]\n\n for( let j = i + 1; j < siblings.length; j++ ){\n const sib = siblings[ j ]\n if( sib.t !== 'element' ) break\n\n if( sib.tag === 'else-if' )\n branches.push({\n when: sib.head ? this.expr( sib.head.expr, sib.head.loc ) : this.missingHead( sib ),\n block: this.block( sib.children, scope )\n })\n else if( sib.tag === 'else' ){\n branches.push({ when: null, block: this.block( sib.children, scope ) })\n break\n }\n else break\n }\n\n block.blocks.push({ t: 'if', p, branches })\n break\n }\n\n case 'else-if':\n case 'else':\n this.report( 'LIPS-C001', 'error', `<${node.tag}> without a preceding <if>`, node.loc.offset, node.loc.length )\n break\n\n case 'for': {\n const { byName, args } = this.attrsOf( node )\n const\n inAttr = byName.get('in'),\n fromAttr = byName.get('from'),\n toAttr = byName.get('to'),\n byAttr = byName.get('by')\n\n if( !inAttr && !fromAttr ){\n this.report( 'LIPS-C004', 'error', `<for> requires 'in' or 'from'/'to'`, node.loc.offset, node.loc.length )\n break\n }\n\n const child: ChildIR = {\n t: 'for', p, args,\n block: this.block( node.children, [ ...scope, ...args ] )\n }\n if( inAttr && inAttr.k === 'expr' ) child.of = this.expr( inAttr.source, inAttr.loc )\n if( fromAttr ) child.from = this.numInput( fromAttr )\n if( toAttr ) child.to = this.numInput( toAttr )\n if( byAttr && ( byAttr.k === 'literal' || byAttr.k === 'expr' ) )\n child.by = byAttr.k === 'literal' ? { lit: byAttr.value } : { e: this.expr( byAttr.source, byAttr.loc ) }\n\n block.blocks.push( child )\n break\n }\n\n case 'switch': {\n const on = node.head ? this.expr( node.head.expr, node.head.loc ) : this.missingHead( node )\n const cases: { is: CompInput | null, block: BlockIR }[] = []\n\n for( const child of node.children ){\n if( child.t !== 'element' ) continue\n\n if( child.tag === 'case' ){\n const { byName } = this.attrsOf( child )\n const isAttr = byName.get('is')\n\n if( !isAttr || ( isAttr.k !== 'literal' && isAttr.k !== 'expr' ) ){\n this.report( 'LIPS-C004', 'error', `<case> requires an 'is' attribute`, child.loc.offset, child.loc.length )\n continue\n }\n cases.push({\n is: isAttr.k === 'literal' ? { lit: isAttr.value } : { e: this.expr( isAttr.source, isAttr.loc ) },\n block: this.block( child.children, scope )\n })\n }\n else if( child.tag === 'default' )\n cases.push({ is: null, block: this.block( child.children, scope ) })\n else\n this.report( 'LIPS-C003', 'error', `Only <case>/<default> are valid inside <switch>`, child.loc.offset, child.loc.length )\n }\n\n block.blocks.push({ t: 'switch', p, on, cases })\n break\n }\n\n case 'async': {\n const awaitAttr = node.attrs.find( a => a.k === 'fn' && a.name === 'await' ) as ( AttrNode & { k: 'fn' } ) | undefined\n if( !awaitAttr ){\n this.report( 'LIPS-C004', 'error', `<async> requires await(…)`, node.loc.offset, node.loc.length )\n break\n }\n\n const child: ChildIR = { t: 'async', p, awaitE: this.expr( awaitAttr.source, awaitAttr.loc ) }\n\n for( const arm of node.children ){\n if( arm.t !== 'element' ) continue\n const { args } = this.attrsOf( arm )\n\n if( arm.tag === 'then' ) child.then = { args, block: this.block( arm.children, [ ...scope, ...args ] ) }\n else if( arm.tag === 'catch' ) child.catch = { args, block: this.block( arm.children, [ ...scope, ...args ] ) }\n else if( arm.tag === 'loading' ) child.loading = this.block( arm.children, scope )\n else this.report( 'LIPS-C003', 'error', `Only <then>/<catch>/<loading> are valid inside <async>`, arm.loc.offset, arm.loc.length )\n }\n\n block.blocks.push( child )\n break\n }\n\n case 'let':\n case 'const': {\n const vars: Record<string, CompInput> = {}\n\n for( const attr of node.attrs )\n if( attr.k === 'literal' || attr.k === 'expr' || attr.k === 'interp' || attr.k === 'bool' ){\n vars[ attr.name ] = this.compInput( attr )\n /**\n * RFC decision #1: let/const names are block-scoped\n * (visible to every bind of the enclosing block)\n */\n !block.scope.includes( attr.name ) && block.scope.push( attr.name )\n !scope.includes( attr.name ) && scope.push( attr.name )\n }\n\n block.blocks.push({ t: 'let', p, const: node.tag === 'const', vars })\n break\n }\n\n case 'log':\n /**\n * A log head is an argument LIST (like an event\n * instruction), not a single expression — the\n * runtime resolves it; no single-expr validation.\n */\n block.blocks.push({ t: 'log', p, e: node.head ? this.synth( node.head.expr ) : this.missingHead( node ) })\n break\n }\n }\n\n private missingHead( node: ElementNode ): E {\n this.report( 'LIPS-C004', 'error', `<${node.tag}> requires a head expression: <${node.tag}( … )>`, node.loc.offset, node.loc.length )\n return this.synth('undefined')\n }\n private numInput( attr: AttrNode ): CompInput {\n if( attr.k === 'literal' ) return { lit: isNumeric( attr.value ) ? Number( attr.value ) : attr.value }\n if( attr.k === 'expr' ) return isNumeric( attr.source ) ? { lit: Number( attr.source ) } : { e: this.expr( attr.source, attr.loc ) }\n return { lit: undefined }\n }\n\n /**\n * Macro call site → inlined block.\n *\n * Every call-site attribute becomes a block-scoped variable\n * (the macro's declared `argv` are the named ones; all of them\n * together also form `arguments` at runtime).\n */\n private macroCall( node: ElementNode, p: Path, scope: string[] ): ChildIR | null {\n const macro = this.macros.get( node.tag )!\n\n if( this.macroStack.includes( macro.name ) ){\n this.report( 'LIPS-C009', 'error',\n `Recursive macro <${macro.name}> (${[ ...this.macroStack, macro.name ].join(' → ')})`,\n node.loc.offset, node.loc.length )\n return null\n }\n\n const vars: Record<string, CompInput> = {}\n for( const attr of node.attrs )\n if( attr.k === 'literal' || attr.k === 'expr' || attr.k === 'interp' || attr.k === 'bool' )\n vars[ attr.name ] = this.compInput( attr )\n\n /**\n * Undeclared argv default to `undefined`: falsy in\n * conditions and attribute-removing like the old engine's\n * `false` sentinel, but renders as '' in text interpolation\n * per RFC decision #4 (the old engine printed \"false\").\n */\n for( const name of macro.argv )\n if( !( name in vars ) ) vars[ name ] = { lit: undefined }\n\n this.macroStack.push( macro.name )\n const block = this.block( macro.children, [ ...scope, ...macro.argv ] )\n this.macroStack.pop()\n\n return { t: 'macro', p, name: macro.name, vars, args: macro.argv, block }\n }\n\n /** Components and dynamic tags share input/event/spread shape */\n private compLike( node: ElementNode, p: Path, scope: string[], kind: 'comp' | 'dynamic' ): ChildIR {\n const\n inputs: Record<string, CompInput> = {},\n spreads: E[] = [],\n events: { name: string, e: E }[] = []\n let args: string[] = []\n\n for( const attr of node.attrs ){\n switch( attr.k ){\n case 'literal': case 'bool': case 'expr': case 'interp':\n inputs[ attr.name ] = this.compInput( attr )\n break\n case 'event':\n events.push({ name: attr.name, e: this.synth( attr.source ) })\n break\n case 'spread':\n spreads.push( this.expr( attr.source, attr.loc ) )\n break\n case 'args':\n args = [ ...args, ...attr.names ]\n break\n case 'fn':\n inputs[ attr.name ] = { e: this.expr( attr.source, attr.loc ) }\n break\n }\n }\n\n const contents: ArmIR | undefined = node.children.length\n ? { args, block: this.block( node.children, [ ...scope, ...args ] ) }\n : undefined\n\n return kind === 'comp'\n ? { t: 'comp', p, name: node.tag, inputs, spreads, events, contents }\n : { t: 'dynamic', p, tag: this.expr( node.dynamicTag!.expr, node.dynamicTag!.loc ), inputs, spreads, events, contents }\n }\n}\n\n// -------------------------------------------------------------------- API\n/** Parse `<macro [argv] name=\"X\">…</macro>` blocks into a lookup */\nfunction parseMacros( src: string, diagnostics: TemplateDiagnostic[] ){\n const macros = new Map<string, MacroDef>()\n if( !src?.trim() ) return macros\n\n const parsed = parseTemplate( src )\n diagnostics.push( ...parsed.diagnostics )\n\n for( const node of parsed.root.children ){\n if( node.t !== 'element' ) continue\n\n if( node.tag !== 'macro' ){\n diagnostics.push({\n code: 'LIPS-C010', severity: 'warning',\n message: `Only <macro> definitions are allowed in the macros source — ignoring <${node.tag}>`,\n loc: { line: 1, col: 1, offset: node.loc.offset, length: node.loc.length }\n })\n continue\n }\n\n let name = ''\n const argv: string[] = []\n for( const attr of node.attrs ){\n if( attr.k === 'args' ) argv.push( ...attr.names )\n else if( attr.k === 'literal' && attr.name === 'name' ) name = attr.value\n }\n\n if( !name ){\n diagnostics.push({\n code: 'LIPS-C011', severity: 'error',\n message: `<macro> requires a name attribute`,\n loc: { line: 1, col: 1, offset: node.loc.offset, length: node.loc.length }\n })\n continue\n }\n\n // Tag names arrive lowercased — match call sites case-insensitively\n macros.set( name.toLowerCase(), { name, argv, children: node.children })\n }\n\n return macros\n}\n\nexport function compileTemplate( src: string, options?: CompileOptions ): CompileResult {\n const diagnostics: TemplateDiagnostic[] = []\n const macros = parseMacros( options?.macros || '', diagnostics )\n\n const parsed = parseTemplate( src )\n const compiler = new Compiler( src, macros )\n const ir = compiler.compile( parsed.root.children )\n\n return { ir, diagnostics: [ ...diagnostics, ...parsed.diagnostics, ...compiler.diagnostics ] }\n}\n",
|
|
7
|
+
"/**\n * Phase 2 — Expression subsystem (RFC-001 §5)\n *\n * A dedicated parser for the template expression subset with:\n * - positioned, machine-readable diagnostics (never throws)\n * - AST-derived precise dependency paths\n * - two interchangeable executors over the same AST:\n * compiled — one Function per unique expression (trusted contexts)\n * interpreted — sandboxed AST walker (CSP / untrusted embeds)\n *\n * Grammar (expression-only, no statements):\n * literals (number, string, boolean, null, undefined), identifiers,\n * member access (incl. optional/computed), calls, unary ! - + and\n * prefix/postfix ++ --, binary arithmetic/relational/equality,\n * && || ??, ternary, arrow functions, assignment (= += -= *= /= %=),\n * array/object literals with spread.\n */\n\n// ---------------------------------------------------------------- diagnostics\nexport interface ExprDiagnostic {\n code: string\n message: string\n loc: { offset: number, length: number }\n}\n\n// ------------------------------------------------------------------------ AST\nexport type Expr =\n | { t: 'lit', v: any }\n | { t: 'id', name: string }\n | { t: 'member', obj: Expr, prop: string | Expr, computed: boolean, optional: boolean }\n | { t: 'call', callee: Expr, args: Expr[], optional: boolean }\n | { t: 'unary', op: '!' | '-' | '+', arg: Expr }\n | { t: 'update', op: '++' | '--', arg: Expr, prefix: boolean }\n | { t: 'bin', op: string, l: Expr, r: Expr }\n | { t: 'logic', op: '&&' | '||' | '??', l: Expr, r: Expr }\n | { t: 'cond', test: Expr, cons: Expr, alt: Expr }\n | { t: 'assign', op: string, target: Expr, value: Expr }\n | { t: 'arrow', params: string[], body: Expr }\n | { t: 'arr', items: { spread?: boolean, value: Expr }[] }\n | { t: 'obj', props: { key?: string, value: Expr, spread?: boolean }[] }\n | { t: 'error' }\n\n// ------------------------------------------------------------------ tokenizer\ntype Token = {\n t: 'num' | 'str' | 'id' | 'punct' | 'eof'\n value: string\n start: number\n end: number\n}\n\nconst PUNCTS = [\n '===', '!==', '...', '=>', '==', '!=', '<=', '>=', '&&', '||', '??', '?.',\n '++', '--', '+=', '-=', '*=', '/=', '%=',\n '+', '-', '*', '/', '%', '<', '>', '!', '?', ':', '.', ',', '(', ')',\n '[', ']', '{', '}', '='\n]\n\nfunction tokenize( src: string, diagnostics: ExprDiagnostic[] ): Token[] {\n const tokens: Token[] = []\n let i = 0\n\n const isIdStart = ( c: string ) => /[A-Za-z_$]/.test( c )\n const isIdChar = ( c: string ) => /[A-Za-z0-9_$]/.test( c )\n\n while( i < src.length ){\n const c = src[ i ]\n\n if( /\\s/.test( c ) ){ i++; continue }\n\n // Numbers: int, float, exponent\n if( /[0-9]/.test( c ) || ( c === '.' && /[0-9]/.test( src[ i + 1 ] ) ) ){\n const start = i\n while( i < src.length && /[0-9]/.test( src[ i ] ) ) i++\n if( src[ i ] === '.' ){ i++; while( i < src.length && /[0-9]/.test( src[ i ] ) ) i++ }\n if( src[ i ] === 'e' || src[ i ] === 'E' ){\n i++\n if( src[ i ] === '+' || src[ i ] === '-' ) i++\n while( i < src.length && /[0-9]/.test( src[ i ] ) ) i++\n }\n tokens.push({ t: 'num', value: src.slice( start, i ), start, end: i })\n continue\n }\n\n // Strings: '…' or \"…\" with escapes\n if( c === \"'\" || c === '\"' ){\n const start = i\n i++\n let value = ''\n let closed = false\n while( i < src.length ){\n const ch = src[ i ]\n if( ch === '\\\\' ){\n const next = src[ i + 1 ]\n const escapes: Record<string, string> = { n: '\\n', t: '\\t', r: '\\r', b: '\\b', f: '\\f', v: '\\v', '0': '\\0' }\n if( next === 'u' ){\n const hex = src.slice( i + 2, i + 6 )\n value += String.fromCharCode( parseInt( hex, 16 ) || 0 )\n i += 6\n }\n else {\n value += escapes[ next ] ?? next\n i += 2\n }\n continue\n }\n if( ch === c ){ closed = true; i++; break }\n value += ch\n i++\n }\n if( !closed )\n diagnostics.push({ code: 'LIPS-E001', message: 'Unterminated string literal', loc: { offset: start, length: i - start } })\n tokens.push({ t: 'str', value, start, end: i })\n continue\n }\n\n // Identifiers / keywords\n if( isIdStart( c ) ){\n const start = i\n while( i < src.length && isIdChar( src[ i ] ) ) i++\n tokens.push({ t: 'id', value: src.slice( start, i ), start, end: i })\n continue\n }\n\n // Punctuators — longest match first\n let punct = PUNCTS.find( p => src.startsWith( p, i ) )\n // `a ? .5 : b` — '?.' must not swallow a ternary before a decimal\n if( punct === '?.' && /[0-9]/.test( src[ i + 2 ] ?? '' ) )\n punct = '?'\n if( punct ){\n tokens.push({ t: 'punct', value: punct, start: i, end: i + punct.length })\n i += punct.length\n continue\n }\n\n diagnostics.push({ code: 'LIPS-E002', message: `Unexpected character '${c}'`, loc: { offset: i, length: 1 } })\n i++\n }\n\n tokens.push({ t: 'eof', value: '', start: src.length, end: src.length })\n return tokens\n}\n\n// --------------------------------------------------------------------- parser\nclass Parser {\n private pos = 0\n constructor( private tokens: Token[], private diagnostics: ExprDiagnostic[] ){}\n\n private peek( offset = 0 ){ return this.tokens[ Math.min( this.pos + offset, this.tokens.length - 1 ) ] }\n private next(){ return this.tokens[ this.pos++ ] ?? this.tokens[ this.tokens.length - 1 ] }\n private at( value: string ){ const t = this.peek(); return t.t === 'punct' && t.value === value }\n private eat( value: string ){ if( this.at( value ) ){ this.pos++; return true } return false }\n private error( code: string, message: string, token = this.peek() ): Expr {\n this.diagnostics.push({ code, message, loc: { offset: token.start, length: Math.max( 1, token.end - token.start ) } })\n return { t: 'error' }\n }\n private expect( value: string, code: string ){\n if( !this.eat( value ) )\n this.error( code, `Expected '${value}'` )\n }\n\n parse(): Expr {\n const expr = this.assign()\n if( this.peek().t !== 'eof' )\n this.error( 'LIPS-E003', `Unexpected token '${this.peek().value}' after expression` )\n return expr\n }\n\n /**\n * Arrow lookahead: '(' … ')' '=>' or IDENT '=>'\n */\n private isArrowAhead(): boolean {\n const t = this.peek()\n if( t.t === 'id' ){\n const n = this.peek( 1 )\n return n.t === 'punct' && n.value === '=>'\n }\n if( t.t === 'punct' && t.value === '(' ){\n let depth = 0, k = 0\n while( true ){\n const tok = this.peek( k )\n if( tok.t === 'eof' ) return false\n if( tok.t === 'punct' && tok.value === '(' ) depth++\n if( tok.t === 'punct' && tok.value === ')' ){\n depth--\n if( depth === 0 ){\n const after = this.peek( k + 1 )\n return after.t === 'punct' && after.value === '=>'\n }\n }\n k++\n }\n }\n return false\n }\n\n private assign(): Expr {\n // Arrow functions\n if( this.isArrowAhead() ){\n const params: string[] = []\n if( this.peek().t === 'id' )\n params.push( this.next().value )\n else {\n this.expect( '(', 'LIPS-E004' )\n while( !this.at( ')' ) && this.peek().t !== 'eof' ){\n const p = this.next()\n if( p.t !== 'id' ) return this.error( 'LIPS-E005', 'Invalid arrow parameter', p )\n params.push( p.value )\n if( !this.eat( ',' ) ) break\n }\n this.expect( ')', 'LIPS-E004' )\n }\n this.expect( '=>', 'LIPS-E004' )\n return { t: 'arrow', params, body: this.assign() }\n }\n\n const target = this.conditional()\n\n const op = this.peek()\n if( op.t === 'punct' && [ '=', '+=', '-=', '*=', '/=', '%=' ].includes( op.value ) ){\n if( target.t !== 'id' && target.t !== 'member' )\n return this.error( 'LIPS-E006', 'Invalid assignment target', op )\n this.next()\n return { t: 'assign', op: op.value, target, value: this.assign() }\n }\n\n return target\n }\n\n private conditional(): Expr {\n const test = this.nullish()\n if( this.eat( '?' ) ){\n const cons = this.assign()\n this.expect( ':', 'LIPS-E007' )\n return { t: 'cond', test, cons, alt: this.assign() }\n }\n return test\n }\n\n private nullish(): Expr {\n let l = this.or()\n while( this.at( '??' ) ){ this.next(); l = { t: 'logic', op: '??', l, r: this.or() } }\n return l\n }\n private or(): Expr {\n let l = this.and()\n while( this.at( '||' ) ){ this.next(); l = { t: 'logic', op: '||', l, r: this.and() } }\n return l\n }\n private and(): Expr {\n let l = this.equality()\n while( this.at( '&&' ) ){ this.next(); l = { t: 'logic', op: '&&', l, r: this.equality() } }\n return l\n }\n private equality(): Expr {\n let l = this.relational()\n while( [ '===', '!==', '==', '!=' ].some( op => this.at( op ) ) ){\n const op = this.next().value\n l = { t: 'bin', op, l, r: this.relational() }\n }\n return l\n }\n private relational(): Expr {\n let l = this.additive()\n while( [ '<=', '>=', '<', '>' ].some( op => this.at( op ) ) ){\n const op = this.next().value\n l = { t: 'bin', op, l, r: this.additive() }\n }\n return l\n }\n private additive(): Expr {\n let l = this.multiplicative()\n while( this.at( '+' ) || this.at( '-' ) ){\n const op = this.next().value\n l = { t: 'bin', op, l, r: this.multiplicative() }\n }\n return l\n }\n private multiplicative(): Expr {\n let l = this.unary()\n while( this.at( '*' ) || this.at( '/' ) || this.at( '%' ) ){\n const op = this.next().value\n l = { t: 'bin', op, l, r: this.unary() }\n }\n return l\n }\n private unary(): Expr {\n if( this.at( '!' ) || this.at( '-' ) || this.at( '+' ) ){\n const op = this.next().value as '!' | '-' | '+'\n return { t: 'unary', op, arg: this.unary() }\n }\n if( this.at( '++' ) || this.at( '--' ) ){\n const op = this.next().value as '++' | '--'\n const arg = this.unary()\n if( arg.t !== 'id' && arg.t !== 'member' )\n return this.error( 'LIPS-E006', 'Invalid update target' )\n return { t: 'update', op, arg, prefix: true }\n }\n return this.postfix()\n }\n private postfix(): Expr {\n let expr = this.callMember()\n if( this.at( '++' ) || this.at( '--' ) ){\n const op = this.next().value as '++' | '--'\n if( expr.t !== 'id' && expr.t !== 'member' )\n return this.error( 'LIPS-E006', 'Invalid update target' )\n expr = { t: 'update', op, arg: expr, prefix: false }\n }\n return expr\n }\n\n private callMember(): Expr {\n let expr = this.primary()\n\n while( true ){\n if( this.eat( '.' ) ){\n const prop = this.next()\n if( prop.t !== 'id' ) return this.error( 'LIPS-E008', 'Expected property name', prop )\n expr = { t: 'member', obj: expr, prop: prop.value, computed: false, optional: false }\n }\n else if( this.eat( '?.' ) ){\n if( this.at( '(' ) ){\n expr = { t: 'call', callee: expr, args: this.argList(), optional: true }\n }\n else if( this.eat( '[' ) ){\n const idx = this.assign()\n this.expect( ']', 'LIPS-E009' )\n expr = { t: 'member', obj: expr, prop: idx, computed: true, optional: true }\n }\n else {\n const prop = this.next()\n if( prop.t !== 'id' ) return this.error( 'LIPS-E008', 'Expected property name', prop )\n expr = { t: 'member', obj: expr, prop: prop.value, computed: false, optional: true }\n }\n }\n else if( this.eat( '[' ) ){\n const idx = this.assign()\n this.expect( ']', 'LIPS-E009' )\n expr = { t: 'member', obj: expr, prop: idx, computed: true, optional: false }\n }\n else if( this.at( '(' ) ){\n expr = { t: 'call', callee: expr, args: this.argList(), optional: false }\n }\n else break\n }\n\n return expr\n }\n private argList(): Expr[] {\n this.expect( '(', 'LIPS-E010' )\n const args: Expr[] = []\n while( !this.at( ')' ) && this.peek().t !== 'eof' ){\n args.push( this.assign() )\n if( !this.eat( ',' ) ) break\n }\n this.expect( ')', 'LIPS-E010' )\n return args\n }\n\n private primary(): Expr {\n const t = this.peek()\n\n if( t.t === 'num' ){ this.next(); return { t: 'lit', v: parseFloat( t.value ) } }\n if( t.t === 'str' ){ this.next(); return { t: 'lit', v: t.value } }\n\n if( t.t === 'id' ){\n this.next()\n switch( t.value ){\n case 'true': return { t: 'lit', v: true }\n case 'false': return { t: 'lit', v: false }\n case 'null': return { t: 'lit', v: null }\n case 'undefined': return { t: 'lit', v: undefined }\n case 'NaN': return { t: 'lit', v: NaN }\n case 'Infinity': return { t: 'lit', v: Infinity }\n default: return { t: 'id', name: t.value }\n }\n }\n\n if( this.eat( '(' ) ){\n const expr = this.assign()\n this.expect( ')', 'LIPS-E010' )\n return expr\n }\n\n if( this.eat( '[' ) ){\n const items: { spread?: boolean, value: Expr }[] = []\n while( !this.at( ']' ) && this.peek().t !== 'eof' ){\n const spread = this.eat( '...' )\n items.push({ spread: spread || undefined, value: this.assign() })\n if( !this.eat( ',' ) ) break\n }\n this.expect( ']', 'LIPS-E009' )\n return { t: 'arr', items }\n }\n\n if( this.eat( '{' ) ){\n const props: { key?: string, value: Expr, spread?: boolean }[] = []\n while( !this.at( '}' ) && this.peek().t !== 'eof' ){\n if( this.eat( '...' ) ){\n props.push({ spread: true, value: this.assign() })\n }\n else {\n const key = this.next()\n if( key.t !== 'id' && key.t !== 'str' && key.t !== 'num' )\n return this.error( 'LIPS-E011', 'Invalid object key', key )\n\n if( this.eat( ':' ) )\n props.push({ key: String( key.value ), value: this.assign() })\n else if( key.t === 'id' ) // shorthand { a }\n props.push({ key: key.value, value: { t: 'id', name: key.value } })\n else\n return this.error( 'LIPS-E011', 'Invalid shorthand property', key )\n }\n if( !this.eat( ',' ) ) break\n }\n this.expect( '}', 'LIPS-E011' )\n return { t: 'obj', props }\n }\n\n this.next()\n return this.error( 'LIPS-E012', t.t === 'eof' ? 'Unexpected end of expression' : `Unexpected token '${t.value}'`, t )\n }\n}\n\nexport function parseExpression( src: string ): { ast: Expr, diagnostics: ExprDiagnostic[] } {\n const diagnostics: ExprDiagnostic[] = []\n const tokens = tokenize( src, diagnostics )\n const ast = new Parser( tokens, diagnostics ).parse()\n\n return { ast, diagnostics }\n}\n\n// ------------------------------------------------------------ dep extraction\nconst METAVAR_ROOTS = new Set([ 'state', 'input', 'context', 'self', 'arguments' ])\n\n/**\n * Precise dependency paths from the AST: dotted member paths\n * rooted at metavars (up to the first computed/call boundary),\n * plus bare scope-variable reads. Arrow params shadow.\n */\nexport function extractDeps( ast: Expr, scopeNames: string[] = [] ): string[] {\n const\n deps = new Set<string>(),\n scope = new Set( scopeNames )\n\n const walk = ( node: Expr, shadow: Set<string> ) => {\n switch( node.t ){\n case 'id': {\n if( shadow.has( node.name ) ) return\n if( scope.has( node.name ) || node.name === 'arguments' ) deps.add( node.name )\n return\n }\n case 'member': {\n // Collect the static dotted chain\n const parts: string[] = []\n let cur: Expr = node\n while( cur.t === 'member' && !cur.computed && typeof cur.prop === 'string' ){\n parts.unshift( cur.prop )\n cur = cur.obj\n }\n // Computed segments: record the object chain and the index deps\n if( cur.t === 'member' ){\n walk( cur.obj, shadow )\n typeof cur.prop !== 'string' && walk( cur.prop, shadow )\n // Re-anchor: deps of the computed base were recorded above\n if( cur.obj.t === 'id' || cur.obj.t === 'member' ) { /* recorded via recursion */ }\n }\n else if( cur.t === 'id' && !shadow.has( cur.name ) ){\n if( METAVAR_ROOTS.has( cur.name ) )\n deps.add( parts.length ? `${cur.name}.${parts.join('.')}` : cur.name )\n else if( scope.has( cur.name ) )\n deps.add( cur.name )\n }\n else if( cur.t !== 'id' ) walk( cur, shadow )\n return\n }\n case 'call':\n walk( node.callee, shadow )\n node.args.forEach( a => walk( a, shadow ) )\n return\n case 'unary': walk( node.arg, shadow ); return\n case 'update': walk( node.arg, shadow ); return\n case 'bin': case 'logic': walk( node.l, shadow ); walk( node.r, shadow ); return\n case 'cond': walk( node.test, shadow ); walk( node.cons, shadow ); walk( node.alt, shadow ); return\n case 'assign': walk( node.target, shadow ); walk( node.value, shadow ); return\n case 'arrow': {\n const inner = new Set([ ...shadow, ...node.params ])\n walk( node.body, inner )\n return\n }\n case 'arr': node.items.forEach( i => walk( i.value, shadow ) ); return\n case 'obj': node.props.forEach( p => walk( p.value, shadow ) ); return\n }\n }\n\n walk( ast, new Set() )\n return [ ...deps ]\n}\n\n// -------------------------------------------------------------------- codegen\n/**\n * AST → JS source (fully parenthesized — semantics over beauty).\n * Reserved-as-parameter roots are renamed at the identifier node\n * (`static` → `__static`, `arguments` → `__args__`) — renaming in\n * codegen, never via regex on emitted source, keeps string literals\n * containing those words intact.\n */\nconst ID_RENAMES: Record<string, string> = { static: '__static', arguments: '__args__' }\n\nfunction gen( node: Expr ): string {\n switch( node.t ){\n case 'lit':\n if( typeof node.v === 'string' ) return JSON.stringify( node.v )\n if( node.v === undefined ) return 'undefined'\n if( Number.isNaN( node.v ) ) return 'NaN'\n return String( node.v )\n case 'id': return ID_RENAMES[ node.name ] ?? node.name\n case 'member': {\n const obj = gen( node.obj )\n if( node.computed ) return `(${obj})${node.optional ? '?.' : ''}[${gen( node.prop as Expr )}]`\n return `(${obj})${node.optional ? '?.' : '.'}${node.prop}`\n }\n case 'call': return `(${gen( node.callee )})${node.optional ? '?.' : ''}(${node.args.map( gen ).join(',')})`\n case 'unary': return `(${node.op}(${gen( node.arg )}))`\n case 'update': return node.prefix ? `(${node.op}${genTarget( node.arg )})` : `(${genTarget( node.arg )}${node.op})`\n case 'bin': return `((${gen( node.l )})${node.op}(${gen( node.r )}))`\n case 'logic': return `((${gen( node.l )})${node.op}(${gen( node.r )}))`\n case 'cond': return `((${gen( node.test )})?(${gen( node.cons )}):(${gen( node.alt )}))`\n case 'assign': return `(${genTarget( node.target )}${node.op}(${gen( node.value )}))`\n case 'arrow': return `((${node.params.join(',')})=>(${gen( node.body )}))`\n case 'arr': return `[${node.items.map( i => ( i.spread ? '...' : '' ) + gen( i.value ) ).join(',')}]`\n case 'obj': return `({${node.props.map( p =>\n p.spread ? `...${gen( p.value )}` : `${JSON.stringify( p.key )}:${gen( p.value )}` ).join(',')}})`\n case 'error': return 'undefined'\n }\n}\n/** Assignment/update targets must not be over-parenthesized */\nfunction genTarget( node: Expr ): string {\n if( node.t === 'id' ) return ID_RENAMES[ node.name ] ?? node.name\n if( node.t === 'member' ){\n const obj = gen( node.obj )\n return node.computed ? `${obj}[${gen( node.prop as Expr )}]` : `${obj}.${node.prop}`\n }\n return gen( node )\n}\n\n// ------------------------------------------------------------------ executors\nexport interface ExprEnv {\n state?: any\n input?: any\n context?: any\n static?: any\n self?: any\n arguments?: any\n scope?: Record<string, any>\n}\n\nexport interface CompiledExpr {\n run( env: ExprEnv ): any\n source: string\n}\n\nconst\nCOMPILE_CACHE = new Map<string, CompiledExpr>(),\nROOT_PARAMS = [ 'state', 'input', 'context', '__static', 'self' ]\n\n/**\n * Compiled mode: one Function per unique (source, scopeNames) —\n * strict-compatible, no `with`. Trusted contexts only.\n */\nexport function compileExpression( src: string, scopeNames: string[] = [] ): CompiledExpr {\n const key = `${scopeNames.join(',')}\u0000${src}`\n const cached = COMPILE_CACHE.get( key )\n if( cached ) return cached\n\n const { ast, diagnostics } = parseExpression( src )\n if( diagnostics.length )\n console.warn( `[lips-ir] expression diagnostics for \"${src}\":`, diagnostics )\n\n const\n code = `return (${gen( ast )});`,\n params = [ ...ROOT_PARAMS, '__args__', ...scopeNames ],\n fn = new Function( ...params, code )\n\n const compiled: CompiledExpr = {\n source: src,\n run( env: ExprEnv ){\n const scope = env.scope || {}\n return fn(\n env.state, env.input, env.context, env.static, env.self, env.arguments,\n ...scopeNames.map( name => scope[ name ] )\n )\n }\n }\n\n COMPILE_CACHE.set( key, compiled )\n return compiled\n}\n\n/**\n * Interpreted mode: sandboxed AST walker — only whitelisted\n * globals are reachable. CSP-safe (no eval, no Function).\n */\nconst SAFE_GLOBALS: Record<string, any> = {\n Math, JSON, Object, Array, String, Number, Boolean, Date,\n parseInt, parseFloat, isNaN, isFinite,\n encodeURIComponent, decodeURIComponent, console\n}\n\nexport function interpretExpression( ast: Expr, env: ExprEnv ): any {\n const scope = env.scope || {}\n\n const resolveId = ( name: string, locals: Record<string, any>[] ): any => {\n for( const frame of locals )\n if( name in frame ) return frame[ name ]\n\n if( name in scope ) return scope[ name ]\n\n switch( name ){\n case 'state': return env.state\n case 'input': return env.input\n case 'context': return env.context\n case 'static': return env.static\n case 'self': return env.self\n case 'arguments': return env.arguments\n }\n\n if( name in SAFE_GLOBALS ) return SAFE_GLOBALS[ name ]\n return undefined\n }\n\n const assignId = ( name: string, value: any, locals: Record<string, any>[] ) => {\n for( const frame of locals )\n if( name in frame ){ frame[ name ] = value; return value }\n scope[ name ] = value\n return value\n }\n\n const ev = ( node: Expr, locals: Record<string, any>[] ): any => {\n switch( node.t ){\n case 'lit': return node.v\n case 'id': return resolveId( node.name, locals )\n\n case 'member': {\n const obj = ev( node.obj, locals )\n if( node.optional && obj == null ) return undefined\n const prop = node.computed ? ev( node.prop as Expr, locals ) : node.prop as string\n return obj?.[ prop ]\n }\n\n case 'call': {\n // Member calls bind `this` to the object\n if( node.callee.t === 'member' ){\n const obj = ev( node.callee.obj, locals )\n if( ( node.callee.optional || node.optional ) && obj == null ) return undefined\n const prop = node.callee.computed ? ev( node.callee.prop as Expr, locals ) : node.callee.prop as string\n const fn = obj?.[ prop ]\n if( node.optional && fn == null ) return undefined\n return fn.apply( obj, node.args.map( a => ev( a, locals ) ) )\n }\n const fn = ev( node.callee, locals )\n if( node.optional && fn == null ) return undefined\n return fn( ...node.args.map( a => ev( a, locals ) ) )\n }\n\n case 'unary': {\n const v = ev( node.arg, locals )\n switch( node.op ){\n case '!': return !v\n case '-': return -v\n case '+': return +v\n }\n }\n\n case 'update': {\n const cur = ev( node.arg, locals )\n const nextVal = node.op === '++' ? cur + 1 : cur - 1\n setTarget( node.arg, nextVal, locals )\n return node.prefix ? nextVal : cur\n }\n\n case 'bin': {\n const l = ev( node.l, locals ), r = ev( node.r, locals )\n switch( node.op ){\n case '+': return l + r\n case '-': return l - r\n case '*': return l * r\n case '/': return l / r\n case '%': return l % r\n case '<': return l < r\n case '>': return l > r\n case '<=': return l <= r\n case '>=': return l >= r\n // eslint-disable-next-line eqeqeq\n case '==': return l == r\n // eslint-disable-next-line eqeqeq\n case '!=': return l != r\n case '===': return l === r\n case '!==': return l !== r\n }\n return undefined\n }\n\n case 'logic': {\n const l = ev( node.l, locals )\n switch( node.op ){\n case '&&': return l ? ev( node.r, locals ) : l\n case '||': return l ? l : ev( node.r, locals )\n case '??': return l != null ? l : ev( node.r, locals )\n }\n }\n\n case 'cond': return ev( node.test, locals ) ? ev( node.cons, locals ) : ev( node.alt, locals )\n\n case 'assign': {\n let value = ev( node.value, locals )\n if( node.op !== '=' ){\n const cur = ev( node.target, locals )\n switch( node.op ){\n case '+=': value = cur + value; break\n case '-=': value = cur - value; break\n case '*=': value = cur * value; break\n case '/=': value = cur / value; break\n case '%=': value = cur % value; break\n }\n }\n return setTarget( node.target, value, locals )\n }\n\n case 'arrow':\n return ( ...args: any[] ) => {\n const frame: Record<string, any> = {}\n node.params.forEach( ( p, k ) => frame[ p ] = args[ k ] )\n return ev( node.body, [ frame, ...locals ] )\n }\n\n case 'arr': {\n const out: any[] = []\n for( const item of node.items ){\n const v = ev( item.value, locals )\n item.spread ? out.push( ...v ) : out.push( v )\n }\n return out\n }\n\n case 'obj': {\n const out: Record<string, any> = {}\n for( const p of node.props ){\n if( p.spread ) Object.assign( out, ev( p.value, locals ) )\n else out[ p.key as string ] = ev( p.value, locals )\n }\n return out\n }\n\n case 'error': return undefined\n }\n }\n\n const setTarget = ( target: Expr, value: any, locals: Record<string, any>[] ) => {\n if( target.t === 'id' ) return assignId( target.name, value, locals )\n if( target.t === 'member' ){\n const obj = ev( target.obj, locals )\n const prop = target.computed ? ev( target.prop as Expr, locals ) : target.prop as string\n if( obj != null ) obj[ prop ] = value\n return value\n }\n return value\n }\n\n return ev( ast, [] )\n}\n",
|
|
8
|
+
"/**\n * Build-time precompilation (RFC-001 §5, §9 — Phase 3).\n *\n * Turns `{ default: '<template…>' }` into `{ ir: {…} }` ahead of time.\n * Two payoffs:\n *\n * 1. **CSP**: with `mode: 'interpreted'`, a precompiled app never\n * calls `Function`/`eval`, so it runs under `script-src` without\n * `unsafe-eval`.\n * 2. **Startup**: no parse/compile at runtime — the app boots\n * straight into cloning skeletons.\n *\n * The IR is plain JSON, so it can be emitted into a bundle, shipped\n * from a server, or stored as a Modela artifact.\n */\n\nimport { compileTemplate } from './ir/compiler'\nimport type { TemplateIR, CompileOptions } from './ir/compiler'\nimport type { TemplateDiagnostic } from './ir/parser'\n\nexport interface PrecompiledTemplate {\n ir: TemplateIR\n state?: Record<string, any>\n _static?: Record<string, any>\n context?: string[]\n handler?: Record<string, ( ...args: any[] ) => any>\n stylesheet?: string\n}\n\nexport interface PrecompileResult {\n template: PrecompiledTemplate\n diagnostics: TemplateDiagnostic[]\n}\n\n/**\n * Precompile one authoring template. Macros are inlined at this\n * point, so the `macros` source does not ship to the client.\n */\nexport function precompile( template: Record<string, any> ): PrecompileResult {\n const options: CompileOptions = { macros: template.macros }\n const { ir, diagnostics } = compileTemplate( template.default || '', options )\n\n const { default: _src, macros: _macros, ...rest } = template\n\n return { template: { ...rest, ir }, diagnostics }\n}\n\n/** Serialize an IR for embedding in generated source */\nexport const serializeIR = ( ir: TemplateIR ) => JSON.stringify( ir )\n\n// ------------------------------------------------------------ bundler glue\nexport interface PluginOptions {\n /** Files to transform (default: `.lips` single-file components) */\n include?: RegExp\n /** Emit diagnostics as build warnings (default true) */\n reportDiagnostics?: boolean\n}\n\n/**\n * Vite/Rollup plugin: compiles `.lips` single-file components into a\n * module exporting a precompiled template.\n *\n * import Card from './card.lips'\n * lips.register('card', Card) // no runtime parsing\n *\n * Kept dependency-free (duck-typed plugin object) so importing this\n * module never pulls a bundler into the runtime graph.\n */\nexport function lipsPlugin( options: PluginOptions = {} ){\n const\n include = options.include || /\\.lips$/,\n report = options.reportDiagnostics !== false\n\n return {\n name: 'lips:precompile',\n enforce: 'pre' as const,\n\n async transform( code: string, id: string ){\n if( !include.test( id ) ) return null\n\n // Lazy import: parseSFC is only needed at build time\n const { parseSFC } = await import('./ir/parser')\n const { script } = parseSFC( code )\n\n /**\n * The frontscript declares state/handler/etc.; the template\n * body is compiled to IR and merged into the default export.\n */\n const templateSrc = code.slice( script.length )\n const { ir, diagnostics } = compileTemplate( templateSrc )\n\n if( report )\n for( const d of diagnostics )\n ( this as any )?.warn?.(\n `[lips] ${d.code} ${d.message} (${id}:${d.loc.line}:${d.loc.col})` )\n\n const errors = diagnostics.filter( d => d.severity === 'error' )\n if( errors.length )\n throw new Error(\n `[lips] ${id}: ${errors[0].message} at line ${errors[0].loc.line}:${errors[0].loc.col}` )\n\n return {\n code: `${script}\nconst __lips_ir__ = ${serializeIR( ir )};\nexport default {\n ir: __lips_ir__,\n ${/\\bconst\\s+state\\b/.test( script ) ? 'state,' : ''}\n ${/\\bconst\\s+handler\\b/.test( script ) ? 'handler,' : ''}\n ${/\\bconst\\s+_static\\b/.test( script ) ? '_static,' : ''}\n ${/\\bconst\\s+context\\b/.test( script ) ? 'context,' : ''}\n ${/\\bconst\\s+stylesheet\\b/.test( script ) ? 'stylesheet,' : ''}\n};\n`,\n map: null\n }\n }\n }\n}\n"
|
|
9
|
+
],
|
|
10
|
+
"mappings": "oQA4FA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","?.","++","--","+=","-=","*=","/=","%=","+","-","*","/","%","<",">","!","?",":",".",",","(",")","[","]","{","}","="];function BJ(J,Q){let X=[],Z=0,z=(V)=>/[A-Za-z_$]/.test(V),W=(V)=>/[A-Za-z0-9_$]/.test(V);while(Z<J.length){let V=J[Z];if(/\s/.test(V)){Z++;continue}if(/[0-9]/.test(V)||V==="."&&/[0-9]/.test(J[Z+1])){let Y=Z;while(Z<J.length&&/[0-9]/.test(J[Z]))Z++;if(J[Z]==="."){Z++;while(Z<J.length&&/[0-9]/.test(J[Z]))Z++}if(J[Z]==="e"||J[Z]==="E"){if(Z++,J[Z]==="+"||J[Z]==="-")Z++;while(Z<J.length&&/[0-9]/.test(J[Z]))Z++}X.push({t:"num",value:J.slice(Y,Z),start:Y,end:Z});continue}if(V==="'"||V==='"'){let Y=Z;Z++;let $="",F=!1;while(Z<J.length){let D=J[Z];if(D==="\\"){let U=J[Z+1],K={n:`
|
|
2
|
+
`,t:"\t",r:"\r",b:"\b",f:"\f",v:"\v","0":"\x00"};if(U==="u"){let M=J.slice(Z+2,Z+6);$+=String.fromCharCode(parseInt(M,16)||0),Z+=6}else $+=K[U]??U,Z+=2;continue}if(D===V){F=!0,Z++;break}$+=D,Z++}if(!F)Q.push({code:"LIPS-E001",message:"Unterminated string literal",loc:{offset:Y,length:Z-Y}});X.push({t:"str",value:$,start:Y,end:Z});continue}if(z(V)){let Y=Z;while(Z<J.length&&W(J[Z]))Z++;X.push({t:"id",value:J.slice(Y,Z),start:Y,end:Z});continue}let q=OJ.find((Y)=>J.startsWith(Y,Z));if(q==="?."&&/[0-9]/.test(J[Z+2]??""))q="?";if(q){X.push({t:"punct",value:q,start:Z,end:Z+q.length}),Z+=q.length;continue}Q.push({code:"LIPS-E002",message:`Unexpected character '${V}'`,loc:{offset:Z,length:1}}),Z++}return X.push({t:"eof",value:"",start:J.length,end:J.length}),X}class QJ{tokens;diagnostics;pos=0;constructor(J,Q){this.tokens=J;this.diagnostics=Q}peek(J=0){return this.tokens[Math.min(this.pos+J,this.tokens.length-1)]}next(){return this.tokens[this.pos++]??this.tokens[this.tokens.length-1]}at(J){let Q=this.peek();return Q.t==="punct"&&Q.value===J}eat(J){if(this.at(J))return this.pos++,!0;return!1}error(J,Q,X=this.peek()){return this.diagnostics.push({code:J,message:Q,loc:{offset:X.start,length:Math.max(1,X.end-X.start)}}),{t:"error"}}expect(J,Q){if(!this.eat(J))this.error(Q,`Expected '${J}'`)}parse(){let J=this.assign();if(this.peek().t!=="eof")this.error("LIPS-E003",`Unexpected token '${this.peek().value}' after expression`);return J}isArrowAhead(){let J=this.peek();if(J.t==="id"){let Q=this.peek(1);return Q.t==="punct"&&Q.value==="=>"}if(J.t==="punct"&&J.value==="("){let Q=0,X=0;while(!0){let Z=this.peek(X);if(Z.t==="eof")return!1;if(Z.t==="punct"&&Z.value==="(")Q++;if(Z.t==="punct"&&Z.value===")"){if(Q--,Q===0){let z=this.peek(X+1);return z.t==="punct"&&z.value==="=>"}}X++}}return!1}assign(){if(this.isArrowAhead()){let X=[];if(this.peek().t==="id")X.push(this.next().value);else{this.expect("(","LIPS-E004");while(!this.at(")")&&this.peek().t!=="eof"){let Z=this.next();if(Z.t!=="id")return this.error("LIPS-E005","Invalid arrow parameter",Z);if(X.push(Z.value),!this.eat(","))break}this.expect(")","LIPS-E004")}return this.expect("=>","LIPS-E004"),{t:"arrow",params:X,body:this.assign()}}let J=this.conditional(),Q=this.peek();if(Q.t==="punct"&&["=","+=","-=","*=","/=","%="].includes(Q.value)){if(J.t!=="id"&&J.t!=="member")return this.error("LIPS-E006","Invalid assignment target",Q);return this.next(),{t:"assign",op:Q.value,target:J,value:this.assign()}}return J}conditional(){let J=this.nullish();if(this.eat("?")){let Q=this.assign();return this.expect(":","LIPS-E007"),{t:"cond",test:J,cons:Q,alt:this.assign()}}return J}nullish(){let J=this.or();while(this.at("??"))this.next(),J={t:"logic",op:"??",l:J,r:this.or()};return J}or(){let J=this.and();while(this.at("||"))this.next(),J={t:"logic",op:"||",l:J,r:this.and()};return J}and(){let J=this.equality();while(this.at("&&"))this.next(),J={t:"logic",op:"&&",l:J,r:this.equality()};return J}equality(){let J=this.relational();while(["===","!==","==","!="].some((Q)=>this.at(Q)))J={t:"bin",op:this.next().value,l:J,r:this.relational()};return J}relational(){let J=this.additive();while(["<=",">=","<",">"].some((Q)=>this.at(Q)))J={t:"bin",op:this.next().value,l:J,r:this.additive()};return J}additive(){let J=this.multiplicative();while(this.at("+")||this.at("-"))J={t:"bin",op:this.next().value,l:J,r:this.multiplicative()};return J}multiplicative(){let J=this.unary();while(this.at("*")||this.at("/")||this.at("%"))J={t:"bin",op:this.next().value,l:J,r:this.unary()};return J}unary(){if(this.at("!")||this.at("-")||this.at("+"))return{t:"unary",op:this.next().value,arg:this.unary()};if(this.at("++")||this.at("--")){let J=this.next().value,Q=this.unary();if(Q.t!=="id"&&Q.t!=="member")return this.error("LIPS-E006","Invalid update target");return{t:"update",op:J,arg:Q,prefix:!0}}return this.postfix()}postfix(){let J=this.callMember();if(this.at("++")||this.at("--")){let Q=this.next().value;if(J.t!=="id"&&J.t!=="member")return this.error("LIPS-E006","Invalid update target");J={t:"update",op:Q,arg:J,prefix:!1}}return J}callMember(){let J=this.primary();while(!0)if(this.eat(".")){let Q=this.next();if(Q.t!=="id")return this.error("LIPS-E008","Expected property name",Q);J={t:"member",obj:J,prop:Q.value,computed:!1,optional:!1}}else if(this.eat("?."))if(this.at("("))J={t:"call",callee:J,args:this.argList(),optional:!0};else if(this.eat("[")){let Q=this.assign();this.expect("]","LIPS-E009"),J={t:"member",obj:J,prop:Q,computed:!0,optional:!0}}else{let Q=this.next();if(Q.t!=="id")return this.error("LIPS-E008","Expected property name",Q);J={t:"member",obj:J,prop:Q.value,computed:!1,optional:!0}}else if(this.eat("[")){let Q=this.assign();this.expect("]","LIPS-E009"),J={t:"member",obj:J,prop:Q,computed:!0,optional:!1}}else if(this.at("("))J={t:"call",callee:J,args:this.argList(),optional:!1};else break;return J}argList(){this.expect("(","LIPS-E010");let J=[];while(!this.at(")")&&this.peek().t!=="eof")if(J.push(this.assign()),!this.eat(","))break;return this.expect(")","LIPS-E010"),J}primary(){let J=this.peek();if(J.t==="num")return this.next(),{t:"lit",v:parseFloat(J.value)};if(J.t==="str")return this.next(),{t:"lit",v:J.value};if(J.t==="id")switch(this.next(),J.value){case"true":return{t:"lit",v:!0};case"false":return{t:"lit",v:!1};case"null":return{t:"lit",v:null};case"undefined":return{t:"lit",v:void 0};case"NaN":return{t:"lit",v:NaN};case"Infinity":return{t:"lit",v:1/0};default:return{t:"id",name:J.value}}if(this.eat("(")){let Q=this.assign();return this.expect(")","LIPS-E010"),Q}if(this.eat("[")){let Q=[];while(!this.at("]")&&this.peek().t!=="eof"){let X=this.eat("...");if(Q.push({spread:X||void 0,value:this.assign()}),!this.eat(","))break}return this.expect("]","LIPS-E009"),{t:"arr",items:Q}}if(this.eat("{")){let Q=[];while(!this.at("}")&&this.peek().t!=="eof"){if(this.eat("..."))Q.push({spread:!0,value:this.assign()});else{let X=this.next();if(X.t!=="id"&&X.t!=="str"&&X.t!=="num")return this.error("LIPS-E011","Invalid object key",X);if(this.eat(":"))Q.push({key:String(X.value),value:this.assign()});else if(X.t==="id")Q.push({key:X.value,value:{t:"id",name:X.value}});else return this.error("LIPS-E011","Invalid shorthand property",X)}if(!this.eat(","))break}return this.expect("}","LIPS-E011"),{t:"obj",props:Q}}return this.next(),this.error("LIPS-E012",J.t==="eof"?"Unexpected end of expression":`Unexpected token '${J.value}'`,J)}}function c(J){let Q=[],X=BJ(J,Q);return{ast:new QJ(X,Q).parse(),diagnostics:Q}}var XJ={static:"__static",arguments:"__args__"};function S(J){switch(J.t){case"lit":if(typeof J.v==="string")return JSON.stringify(J.v);if(J.v===void 0)return"undefined";if(Number.isNaN(J.v))return"NaN";return String(J.v);case"id":return XJ[J.name]??J.name;case"member":{let Q=S(J.obj);if(J.computed)return`(${Q})${J.optional?"?.":""}[${S(J.prop)}]`;return`(${Q})${J.optional?"?.":"."}${J.prop}`}case"call":return`(${S(J.callee)})${J.optional?"?.":""}(${J.args.map(S).join(",")})`;case"unary":return`(${J.op}(${S(J.arg)}))`;case"update":return J.prefix?`(${J.op}${r(J.arg)})`:`(${r(J.arg)}${J.op})`;case"bin":return`((${S(J.l)})${J.op}(${S(J.r)}))`;case"logic":return`((${S(J.l)})${J.op}(${S(J.r)}))`;case"cond":return`((${S(J.test)})?(${S(J.cons)}):(${S(J.alt)}))`;case"assign":return`(${r(J.target)}${J.op}(${S(J.value)}))`;case"arrow":return`((${J.params.join(",")})=>(${S(J.body)}))`;case"arr":return`[${J.items.map((Q)=>(Q.spread?"...":"")+S(Q.value)).join(",")}]`;case"obj":return`({${J.props.map((Q)=>Q.spread?`...${S(Q.value)}`:`${JSON.stringify(Q.key)}:${S(Q.value)}`).join(",")}})`;case"error":return"undefined"}}function r(J){if(J.t==="id")return XJ[J.name]??J.name;if(J.t==="member"){let Q=S(J.obj);return J.computed?`${Q}[${S(J.prop)}]`:`${Q}.${J.prop}`}return S(J)}var e=new Map,CJ=["state","input","context","__static","self"];function ZJ(J,Q=[]){let X=`${Q.join(",")}\x00${J}`,Z=e.get(X);if(Z)return Z;let{ast:z,diagnostics:W}=c(J);if(W.length)console.warn(`[lips-ir] expression diagnostics for "${J}":`,W);let V=`return (${S(z)});`,q=[...CJ,"__args__",...Q],Y=Function(...q,V),$={source:J,run(F){let D=F.scope||{};return Y(F.state,F.input,F.context,F.static,F.self,F.arguments,...Q.map((U)=>D[U]))}};return e.set(X,$),$}var JJ={Math,JSON,Object,Array,String,Number,Boolean,Date,parseInt,parseFloat,isNaN,isFinite,encodeURIComponent,decodeURIComponent,console};function $J(J,Q){let X=Q.scope||{},Z=(q,Y)=>{for(let $ of Y)if(q in $)return $[q];if(q in X)return X[q];switch(q){case"state":return Q.state;case"input":return Q.input;case"context":return Q.context;case"static":return Q.static;case"self":return Q.self;case"arguments":return Q.arguments}if(q in JJ)return JJ[q];return},z=(q,Y,$)=>{for(let F of $)if(q in F)return F[q]=Y,Y;return X[q]=Y,Y},W=(q,Y)=>{switch(q.t){case"lit":return q.v;case"id":return Z(q.name,Y);case"member":{let $=W(q.obj,Y);if(q.optional&&$==null)return;let F=q.computed?W(q.prop,Y):q.prop;return $?.[F]}case"call":{if(q.callee.t==="member"){let F=W(q.callee.obj,Y);if((q.callee.optional||q.optional)&&F==null)return;let D=q.callee.computed?W(q.callee.prop,Y):q.callee.prop,U=F?.[D];if(q.optional&&U==null)return;return U.apply(F,q.args.map((K)=>W(K,Y)))}let $=W(q.callee,Y);if(q.optional&&$==null)return;return $(...q.args.map((F)=>W(F,Y)))}case"unary":{let $=W(q.arg,Y);switch(q.op){case"!":return!$;case"-":return-$;case"+":return+$}}case"update":{let $=W(q.arg,Y),F=q.op==="++"?$+1:$-1;return V(q.arg,F,Y),q.prefix?F:$}case"bin":{let $=W(q.l,Y),F=W(q.r,Y);switch(q.op){case"+":return $+F;case"-":return $-F;case"*":return $*F;case"/":return $/F;case"%":return $%F;case"<":return $<F;case">":return $>F;case"<=":return $<=F;case">=":return $>=F;case"==":return $==F;case"!=":return $!=F;case"===":return $===F;case"!==":return $!==F}return}case"logic":{let $=W(q.l,Y);switch(q.op){case"&&":return $?W(q.r,Y):$;case"||":return $?$:W(q.r,Y);case"??":return $!=null?$:W(q.r,Y)}}case"cond":return W(q.test,Y)?W(q.cons,Y):W(q.alt,Y);case"assign":{let $=W(q.value,Y);if(q.op!=="="){let F=W(q.target,Y);switch(q.op){case"+=":$=F+$;break;case"-=":$=F-$;break;case"*=":$=F*$;break;case"/=":$=F/$;break;case"%=":$=F%$;break}}return V(q.target,$,Y)}case"arrow":return(...$)=>{let F={};return q.params.forEach((D,U)=>F[D]=$[U]),W(q.body,[F,...Y])};case"arr":{let $=[];for(let F of q.items){let D=W(F.value,Y);F.spread?$.push(...D):$.push(D)}return $}case"obj":{let $={};for(let F of q.props)if(F.spread)Object.assign($,W(F.value,Y));else $[F.key]=W(F.value,Y);return $}case"error":return}},V=(q,Y,$)=>{if(q.t==="id")return z(q.name,Y,$);if(q.t==="member"){let F=W(q.obj,$),D=q.computed?W(q.prop,$):q.prop;if(F!=null)F[D]=Y;return Y}return Y};return W(J,[])}var _=null;function A(J){let Q=new Set,X=()=>{for(let V of[...Q])!V.disposed&&V.run()};return[()=>{if(_&&!_.disposed)Q.add(_),_.deps.add(Q);return J},(V)=>{if(Object.is(V,J))return;J=V,X()},()=>X()]}function O(J){let Q={deps:new Set,disposed:!1,run(){if(Q.disposed)return;for(let Z of Q.deps)Z.delete(Q);Q.deps.clear();let X=_;_=Q;try{J()}finally{_=X}}};return Q.run(),{dispose(){Q.disposed=!0;for(let X of Q.deps)X.delete(Q);Q.deps.clear()}}}function I(J){let Q=_;_=null;try{return J()}finally{_=Q}}var WJ=Symbol("lips.reactive");function E(J,Q=!1){if(J[WJ])return J;let X=new Map,Z=Q?new WeakMap:null,z=(Y,$)=>{let F=X.get(Y);if(!F)F=A($),X.set(Y,F);return F},W=(Y)=>Y!==null&&typeof Y==="object"&&(Array.isArray(Y)||Object.getPrototypeOf(Y)===Object.prototype),V=new Set(["push","pop","shift","unshift","splice","sort","reverse","fill","copyWithin"]),q=(Y,$)=>{if(!Q||!W(Y))return Y;let F=Z.get(Y);if(F)return F;let D=!1,U=new Proxy(Y,{get(K,M){let H=K[M];if(Array.isArray(K)&&typeof M==="string"&&V.has(M)&&typeof H==="function")return(...L)=>{D=!0;try{return H.apply(K,L)}finally{D=!1,$()}};return W(H)?q(H,$):H},set(K,M,H){return K[M]=H,!D&&$(),!0},deleteProperty(K,M){return delete K[M],!D&&$(),!0}});return Z.set(Y,U),U};return new Proxy(J,{get(Y,$){if($===WJ)return!0;if(typeof $==="string"){let F=z($,Y[$]);return q(F[0](),F[2])}return Y[$]},set(Y,$,F){return Y[$]=F,typeof $==="string"&&z($,F)[1](F),!0},has(Y,$){return $ in Y},deleteProperty(Y,$){return delete Y[$],typeof $==="string"&&X.get($)?.[1](void 0),!0}})}var g=(J,Q)=>J==null?J:("e"in J)?{$:Q[J.e]}:J,a=(J,Q)=>({...J,e:Q[J.e]});function u(J,Q){switch(J.t){case"macro":return{t:J.t,name:J.name,args:J.args,vars:Object.fromEntries(Object.entries(J.vars).map(([X,Z])=>[X,g(Z,Q)])),block:y(J.block,Q)};case"if":return{t:J.t,branches:J.branches.map((X)=>({when:X.when==null?null:Q[X.when],block:y(X.block,Q)}))};case"for":return{t:J.t,args:J.args,of:J.of===void 0?void 0:Q[J.of],from:g(J.from,Q),to:g(J.to,Q),by:g(J.by,Q),block:y(J.block,Q)};case"switch":return{t:J.t,on:Q[J.on],cases:J.cases.map((X)=>({is:X.is===null?null:g(X.is,Q),block:y(X.block,Q)}))};case"async":return{t:J.t,awaitE:Q[J.awaitE],then:J.then&&{args:J.then.args,block:y(J.then.block,Q)},catch:J.catch&&{args:J.catch.args,block:y(J.catch.block,Q)},loading:J.loading&&y(J.loading,Q)};case"let":return{t:J.t,const:J.const,vars:Object.fromEntries(Object.entries(J.vars).map(([X,Z])=>[X,g(Z,Q)]))};case"log":return{t:J.t,e:Q[J.e]};case"comp":case"dynamic":return{t:J.t,name:J.t==="comp"?J.name:void 0,tag:J.t==="dynamic"?Q[J.tag]:void 0,inputs:Object.fromEntries(Object.entries(J.inputs).map(([X,Z])=>[X,g(Z,Q)])),spreads:J.spreads.map((X)=>Q[X]),events:J.events.map((X)=>({name:X.name,e:Q[X.e]})),contents:J.contents&&{args:J.contents.args,block:y(J.contents.block,Q)}}}}var y=(J,Q)=>({html:J.html,scope:J.scope,binds:J.binds.map((X)=>a(X,Q)),blocks:J.blocks.map((X)=>u(X,Q))}),qJ=(J,Q,X,Z)=>J.t===X.t&&JSON.stringify(u(J,Q))===JSON.stringify(u(X,Z)),zJ=(J,Q,X,Z)=>JSON.stringify(J.map((z)=>a(z,Q)))===JSON.stringify(X.map((z)=>a(z,Z))),YJ=(J,Q,X,Z)=>{let z=(W,V)=>JSON.stringify(W.blocks.filter((q)=>q.t==="let").map((q)=>u(q,V)));return z(J,Q)===z(X,Z)};var GJ=Symbol("lips.slot"),AJ=(J)=>!!J&&typeof J==="object"&&J[GJ]===!0;function UJ(J){let Q=!1,X=!1,Z=(z)=>typeof J.onError==="function"?J.onError(z):console.error("[lips:ir]",z);return{onError:Z,ready(){X=!0},notifyUpdate(){if(!X||Q)return;Q=!0,queueMicrotask(()=>{Q=!1;try{typeof J.onUpdate==="function"&&J.onUpdate(),typeof J.onRender==="function"&&J.onRender()}catch(z){Z(z)}})}}}var m=[];function HJ(){for(let J=m.length-1;J>=0;J--){let Q=m[J],X=Q.node();if(X&&X.isConnected)m.splice(J,1),Q.fn()}}var FJ=new Map;function IJ(J){let Q=FJ.get(J);if(!Q)Q=c(J).ast,FJ.set(J,Q);return Q}var VJ=new WeakMap;function EJ(J){let Q=VJ.get(J);if(!Q)Q=document.createElement("template"),Q.innerHTML=J.html,VJ.set(J,Q);return Q}var f=(J)=>J.join(",");function KJ(J,Q){let X=J;for(let Z of Q)X=X.childNodes[Z];return X}function C(J){let Q=[],X=J.start;while(X){if(Q.push(X),X===J.end)break;X=X.nextSibling}return Q}function R(J,Q){let X=J.parentNode;if(!X)return;let Z=J;for(let z of Q)X.insertBefore(z,Z.nextSibling),Z=z}function MJ(J,Q,X,Z){for(let W of C(Q))if(W.nodeType===1&&!W.hasAttribute("rel"))W.setAttribute("rel",X);let z=J.createStylesheet?.(X,Z);return z?()=>z.clear():void 0}function TJ(J){for(let Q of J.bindHandles)Q.dispose();for(let Q of J.childHandles)Q.dispose()}function B(J){if(!J)return;TJ(J);for(let Q of C(J))Q.remove()}function DJ(J){let Q=[],X=0,Z=0;for(let z=0;z<J.length;z++){let W=J[z];if(W==="'"||W==='"'||W==="`"){z++;while(z<J.length&&J[z]!==W){if(J[z]==="\\")z++;z++}continue}if(W==="("||W==="["||W==="{")X++;else if(W===")"||W==="]"||W==="}")X--;else if(W===","&&X===0)Q.push(J.slice(Z,z)),Z=z+1}return Q.push(J.slice(Z)),Q.map((z)=>z.trim()).filter(Boolean)}var h=(J,Q,X)=>{X===!1||X==null?J.removeAttribute(Q):J.setAttribute(Q,X===!0?"":String(X))},x=(J,Q,X)=>Object.defineProperty(J,Q,{get:X,enumerable:!0,configurable:!0});class v{ir;options;hooks;constructor(J,Q,X){this.ir=J;this.options=Q;this.hooks=X}guarded(J){let Q=!0;return O(()=>{try{J()}catch(X){this.hooks?this.hooks.onError(X):console.error("[lips:ir]",X)}Q?Q=!1:this.hooks?.notifyUpdate()})}runner(J,Q){return this.srcRunner(this.ir.exprs[J],Q)}srcRunner(J,Q){if(this.options.mode==="interpreted"){let Z=IJ(J);return(z)=>$J(Z,z)}let X=ZJ(J,Q);return(Z)=>X.run(Z)}renderBlock(J,Q){let X=EJ(J).content.cloneNode(!0),Z=new Map,z=J.binds.map((D)=>{let U=KJ(X,D.p);return Z.set(f(D.p),U),U}),W=J.blocks.map((D)=>{let U=KJ(X,D.p);return Z.set(f(D.p),U),U}),V=document.createComment("^"),q=document.createComment("$");X.insertBefore(V,X.firstChild),X.appendChild(q);let Y=Object.create(Q.scope??null),$={...Q,scope:Y},F={start:V,end:q,block:J,exprs:this.ir.exprs,penv:Q,benv:$,pathNodes:Z,bindHandles:[],childHandles:[]};return J.blocks.forEach((D,U)=>{if(D.t!=="let")return;let K=[];for(let[M,H]of Object.entries(D.vars))if("lit"in H){let[L]=A(H.lit);x(Y,M,L)}else{let[L,G]=A(void 0);x(Y,M,L);let P=this.runner(H.e,J.scope);K.push(O(()=>G(P($))).dispose)}F.childHandles[U]={child:D,exprs:this.ir.exprs,anchor:W[U],dispose:()=>K.forEach((M)=>M())}}),F.bindHandles=J.binds.map((D,U)=>this.bindOne(D,z[U],$,J.scope)),J.blocks.forEach((D,U)=>{if(D.t==="let")return;F.childHandles[U]={child:D,exprs:this.ir.exprs,anchor:W[U],dispose:this.execBlock(D,W[U],$,J.scope)}}),F}bindOne(J,Q,X,Z,z){switch(J.t){case"text":{let W=z??document.createTextNode("");!z&&R(Q,[W]);let V=this.runner(J.e,Z),q=J.i18n?this.options.i18n:void 0,Y=this.guarded(()=>{let $=V(X),F=$==null?"":String($);W.data=q?q.translate(F):F});return{bind:J,node:Q,textNode:W,dispose:Y.dispose}}case"attr":{let W=this.runner(J.e,Z),V=J.i18n?this.options.i18n:void 0,q=this.guarded(()=>{let Y=W(X);h(Q,J.name,V&&Y!=null?V.translate(String(Y)):Y)});return{bind:J,node:Q,dispose:q.dispose}}case"prop":{let W=this.runner(J.e,Z);if(J.name==="format"){let q=J.ref||"",Y=this.guarded(()=>{let $=W(X),F=this.options.i18n?.format(q,$);Q.textContent=F==null?"":String(F)});return{bind:J,node:Q,dispose:Y.dispose}}let V=this.guarded(()=>{let q=W(X);J.name==="html"?Q.innerHTML=q==null?"":String(q):Q.textContent=q==null?"":String(q)});return{bind:J,node:Q,dispose:V.dispose}}case"event":{let W=this.eventDispatcher(this.ir.exprs[J.e],Z,X);return Q.addEventListener(J.name,W),{bind:J,node:Q,dispose:()=>Q.removeEventListener(J.name,W)}}case"spread":{let W=this.runner(J.e,Z),V=new Set,q=this.guarded(()=>{let Y=W(X)||{},$=new Set(Object.keys(Y));for(let F of V)!$.has(F)&&Q.removeAttribute(F);for(let F of $)h(Q,F,Y[F]);V=$});return{bind:J,node:Q,dispose:q.dispose}}}}swapBlock(J,Q,X,Z){if(J.block.html!==Q.html||JSON.stringify(J.block.scope)!==JSON.stringify(Q.scope)||!YJ(J.block,J.exprs,Q,this.ir.exprs))return this.rebuild(J,Q,X,Z);if(!zJ(J.block.binds,J.exprs,Q.binds,this.ir.exprs)){let z=Q.binds.map((q)=>J.pathNodes.get(f(q.p)));if(z.some((q)=>!q))return this.rebuild(J,Q,X,Z);let W=new Map;J.bindHandles.forEach((q)=>q.textNode&&W.set(f(q.bind.p),q.textNode)),J.bindHandles.forEach((q)=>q.dispose());let V=new Set;J.bindHandles=Q.binds.map((q,Y)=>{let $=f(q.p),F=q.t==="text"?W.get($):void 0;return F&&V.add($),this.bindOne(q,z[Y],J.benv,Q.scope,F)}),W.forEach((q,Y)=>!V.has(Y)&&q.remove()),X.push({kind:"binds",path:Z})}for(let z=0;z<Q.blocks.length;z++){let W=Q.blocks[z],V=J.childHandles[z];if(W.t==="let")continue;if(V&&qJ(V.child,V.exprs,W,this.ir.exprs))continue;V?.dispose(),J.childHandles[z]={child:W,exprs:this.ir.exprs,anchor:V.anchor,dispose:this.execBlock(W,V.anchor,J.benv,Q.scope)},X.push({kind:"block",path:`${Z}/${z}`})}return J.block=Q,J.exprs=this.ir.exprs,J}rebuild(J,Q,X,Z){let z=this.renderBlock(Q,J.penv);return R(J.end,C(z)),B(J),X.push({kind:"skeleton",path:Z}),z}execBlock(J,Q,X,Z){let z=[];switch(J.t){case"if":{let W=J.branches.map(($)=>$.when!=null?this.runner($.when,Z):null),V=null,q=-2,Y=O(()=>{let $=-1;for(let F=0;F<J.branches.length;F++){let D=W[F];if(!D||D(X)){$=F;break}}if($===q)return;q=$,I(()=>{if(B(V),V=null,$>=0)V=this.renderBlock(J.branches[$].block,X),R(Q,C(V))})});z.push(()=>{Y.dispose(),B(V)});break}case"switch":{let W=this.runner(J.on,Z),V=J.cases.map((F)=>F.is&&("e"in F.is)?this.runner(F.is.e,Z):null),q=null,Y=-2,$=O(()=>{let F=W(X),D=-1,U=-1;for(let K=0;K<J.cases.length;K++){let M=J.cases[K];if(M.is===null){U=K;continue}let H="lit"in M.is?M.is.lit:V[K](X);if(Array.isArray(H)?H.includes(F):H===F){D=K;break}}if(D===-1)D=U;if(D===Y)return;Y=D,I(()=>{if(B(q),q=null,D>=0)q=this.renderBlock(J.cases[D].block,X),R(Q,C(q))})});z.push(()=>{$.dispose(),B(q)});break}case"macro":{let W=Object.create(X.scope??null),V=E({});for(let[Y,$]of Object.entries(J.vars)){if("lit"in $){if(V[Y]=$.lit,J.args.includes(Y)){let[K]=A($.lit);x(W,Y,K)}continue}let F=this.runner($.e,Z),[D,U]=A(void 0);if(J.args.includes(Y))x(W,Y,D);z.push(O(()=>{let K=F(X);U(K),V[Y]=K}).dispose)}let q=this.renderBlock(J.block,{...X,arguments:V,scope:W});R(Q,C(q)),z.push(()=>B(q));break}case"for":this.execFor(J,Q,X,Z,z);break;case"async":{let W=this.runner(J.awaitE,Z),V=null,q=0,Y=(F,D)=>{if(B(V),V=null,!F)return;let U="block"in F,K=Object.create(X.scope??null);if(U&&F.args[0]!==void 0){let[M]=A(D);x(K,F.args[0],M)}V=this.renderBlock(U?F.block:F,{...X,scope:K}),R(Q,C(V))},$=O(()=>{let F=W(X),D=++q;I(()=>{J.loading?Y(J.loading):Y(void 0),Promise.resolve(F).then((U)=>D===q&&I(()=>Y(J.then,U)),(U)=>D===q&&I(()=>Y(J.catch,U)))})});z.push(()=>{q++,$.dispose(),B(V)});break}case"log":{let W=DJ(this.ir.exprs[J.e]).map((V)=>this.srcRunner(V,Z));z.push(O(()=>console.log(...W.map((V)=>V(X)))).dispose);break}case"comp":{let W=this.options.components?.[J.name];W?this.execComponent(W,J,Q,X,Z,z):this.execElement(J,Q,X,Z,z);break}case"dynamic":{let W=this.runner(J.tag,Z),V=[],q=Symbol("init"),Y=O(()=>{let $=W(X);if($===q)return;q=$,I(()=>{for(let D of V)D();if(V=[],$==null)return;if(AJ($)){let D={};for(let[K,M]of Object.entries(J.inputs))D[K]="lit"in M?M.lit:this.runner(M.e,Z)(X);let U=$.render(D);R(Q,C(U)),V.push(()=>B(U));return}let F=typeof $==="string"?this.options.components?.[$]:$&&typeof $==="object"?$.ir?$:this.options.resolveTemplate?.($):void 0;if(F)this.execComponent(F,J,Q,X,Z,V);else if(typeof $==="string")this.execElement({...J,name:$},Q,X,Z,V)})});z.push(()=>{Y.dispose();for(let $ of V)$()});break}}return()=>z.forEach((W)=>W())}execFor(J,Q,X,Z,z){let W=J.of!==void 0?this.runner(J.of,Z):null,V=J.by&&"e"in J.by?this.runner(J.by.e,Z):null,q=J.by&&"lit"in J.by?String(J.by.lit).split("."):null,Y=(K,M)=>K===void 0?void 0:("lit"in K)?K.lit:this.runner(K.e,Z)(M),$=[],F=new Map,D=()=>{if(W===null){let H=Number(Y(J.from,X)??0),L=Number(Y(J.to,X)??H),G=H<=L,P=[];for(let j=H;G?j<=L:j>=L;G?j++:j--)P.push({key:j,values:[j]});return P}let K=W(X),M=(H,L,G)=>{if(V){let P=V(X);return typeof P==="function"?P(H,G):L}if(q)return q.reduce((P,j)=>P?.[j],H);return L};if(Array.isArray(K))return K.map((H,L)=>({key:M(H,L,L),values:[H,L]}));if(K instanceof Map)return[...K.entries()].map(([H,L],G)=>({key:H,values:[H,L,G]}));if(K&&typeof K==="object")return Object.entries(K).map(([H,L],G)=>({key:H,values:[H,L,G]}));return[]},U=O(()=>{let K=D();I(()=>{let M=new Set,H=[];for(let G of K){let P=G.key;if(M.has(P))console.warn(`<for> duplicate key '${String(P)}' — falling back to positional identity`),P=`#dup:${H.length}`;M.add(P);let j=F.get(P);if(j)j.sigs.forEach(([N,T,k],b)=>{let w=G.values[b];Object.is(N(),w)&&typeof w==="object"&&w!==null?k():T(w)}),H.push(j);else{let N=Object.create(X.scope??null),T=G.values.map((w)=>A(w));J.args.forEach((w,n)=>T[n]&&x(N,w,T[n][0]));let k=this.renderBlock(J.block,{...X,scope:N}),b={key:P,sigs:T,inst:k};F.set(P,b),H.push(b)}}for(let G of $)if(!H.includes(G))F.delete(G.key),B(G.inst);let L=Q;for(let G of H){if(L.nextSibling!==G.inst.start)R(L,C(G.inst));L=G.inst.end}$=H})});z.push(()=>{U.dispose();for(let K of $)B(K.inst);$=[],F.clear()})}execComponent(J,Q,X,Z,z,W){let V=E({});for(let[G,P]of Object.entries(Q.inputs))if("lit"in P)V[G]=P.lit;else{let j=this.runner(P.e,z);W.push(O(()=>V[G]=j(Z)).dispose)}for(let G of Q.spreads){let P=this.runner(G,z);W.push(O(()=>{let j=P(Z)||{};I(()=>Object.entries(j).forEach(([N,T])=>V[N]=T))}).dispose)}if(Q.contents){let G=this,P=Q.contents,j=Z;V.renderer={[GJ]:!0,args:P.args,render(N){let T=Object.create(j.scope??null);return P.args.forEach((k)=>{let[b]=A(N?.[k]);x(T,k,b)}),G.renderBlock(P.block,{...j,scope:T})}}}let q=E({...J.state||{}},J.deep??!1),Y=new Map,$={...this.options.expose||{},state:q,input:V,static:J.statics,context:Z.context,emit(G,...P){Y.get(G)?.forEach((j)=>j(...P))},on(G,P){return Y.set(G,[...Y.get(G)||[],P]),$},off(G){return Y.delete(G),$}};J.handlers&&Object.entries(J.handlers).forEach(([G,P])=>$[G]=P.bind($)),Q.events?.forEach((G)=>{let P=this.eventDispatcher(this.ir.exprs[G.e],z,Z);$.on(G.name,P)});let F=UJ($);try{typeof $.onCreate==="function"&&$.onCreate()}catch(G){F.onError(G)}try{Object.keys(V).length&&typeof $.onInput==="function"&&$.onInput()}catch(G){F.onError(G)}let D={state:q,input:V,context:Z.context,static:J.statics,self:$,scope:void 0},K=new v(J.ir,this.options,F).renderBlock(J.ir.root,D),M=J.stylesheet?MJ(this.options,K,J.nsp||"lips",J.stylesheet):void 0;R(X,C(K)),F.ready();try{typeof $.onMount==="function"&&$.onMount(),typeof $.onRender==="function"&&$.onRender()}catch(G){F.onError(G)}let H;if(J.context?.length&&typeof $.onContext==="function"&&this.options.watchContext)H=this.options.watchContext(J.context,()=>{try{$.onContext()}catch(G){F.onError(G)}});let L=!1;if(typeof $.onAttach==="function"||typeof $.onDetach==="function")m.push({node:()=>K.start,fn:()=>{L=!0;try{typeof $.onAttach==="function"&&$.onAttach()}catch(G){F.onError(G)}}}),K.start.isConnected&&HJ();W.push(()=>{H?.(),M?.(),B(K);try{L&&typeof $.onDetach==="function"&&$.onDetach(),typeof $.onDestroy==="function"&&$.onDestroy()}catch(G){F.onError(G)}})}execElement(J,Q,X,Z,z){let W=document.createElement(J.name);for(let[V,q]of Object.entries(J.inputs))if("lit"in q)h(W,V,q.lit);else{let Y=this.runner(q.e,Z);z.push(O(()=>h(W,V,Y(X))).dispose)}for(let V of J.events){let q=this.eventDispatcher(this.ir.exprs[V.e],Z,X);W.addEventListener(V.name,q),z.push(()=>W.removeEventListener(V.name,q))}if(J.contents){let V=this.renderBlock(J.contents.block,X);W.append(...C(V)),z.push(()=>B(V))}R(Q,[W]),z.push(()=>W.remove())}eventDispatcher(J,Q,X){let Z=DJ(J);return(...z)=>I(()=>{let W=(Y)=>{let $;try{$=this.srcRunner(Y,Q)(X)}catch(F){$=void 0}if(typeof $!=="function"&&X.self&&typeof X.self[Y]==="function")$=X.self[Y];return $};if(!Z.length)return;let V=W(Z[0]);if(typeof V!=="function")return;let q=Z.slice(1).map((Y)=>this.srcRunner(Y,Q)(X));V(...q,...z)})}}function o(J,Q={},X={}){let Z=E(Q.state||{},Q.deep??!1),z=Q.input?E(Q.input,Q.deep??!1):void 0,W={state:Z,input:z,static:Q.static,...Q.expose||{}};Q.handlers&&Object.entries(Q.handlers).forEach(([K,M])=>W[K]=M.bind(W));let V={state:Z,input:z,context:Q.context,static:Q.static,self:W,scope:void 0},q=UJ(W);try{typeof W.onCreate==="function"&&W.onCreate()}catch(K){q.onError(K)}try{z&&Object.keys(z).length&&typeof W.onInput==="function"&&W.onInput()}catch(K){q.onError(K)}let Y=new v(J,X,q),$=Y.renderBlock(J.root,V);q.ready();let F=Q.stylesheet?MJ(X,$,Q.nsp||"lips",Q.stylesheet):void 0;try{typeof W.onMount==="function"&&W.onMount(),typeof W.onRender==="function"&&W.onRender()}catch(K){q.onError(K)}let D=!1,U=()=>{if(D)return;D=!0;try{typeof W.onAttach==="function"&&W.onAttach()}catch(K){q.onError(K)}};return{state:Z,self:W,get nodes(){return C($)},mount(K){if(K.append(...C($)),$.start.isConnected)U(),HJ()},swap(K){let M=[];return Y=new v(K,X,q),$=Y.swapBlock($,K.root,M,"root"),{changes:M}},dispose(){F?.(),B($);try{D&&typeof W.onDetach==="function"&&W.onDetach(),typeof W.onDestroy==="function"&&W.onDestroy()}catch(K){q.onError(K)}}}}class p{options={emit:!0};__events={};__once_events={};constructor(J){if(J)this.options=J}on(J,Q){if(!Array.isArray(this.__events[J]))this.__events[J]=[];return this.__events[J].push(Q),this}once(J,Q){if(!Array.isArray(this.__once_events[J]))this.__once_events[J]=[];return this.__once_events[J].push(Q),this}off(J,Q){if(Q){if(Array.isArray(this.__events[J]))this.__events[J]=this.__events[J].filter((X)=>X!==Q),!this.__events[J].length&&delete this.__events[J];if(Array.isArray(this.__once_events[J]))this.__once_events[J]=this.__once_events[J].filter((X)=>X!==Q),!this.__once_events[J].length&&delete this.__once_events[J]}else delete this.__events[J],delete this.__once_events[J];return this}emit(J,...Q){if(!this.options.emit)return;let X=(z)=>{if(!z||typeof z!=="object")return z;if(typeof z.toJSON==="function")return z.toJSON();if(Array.isArray(z))return z.map(X);if(z.constructor===Object||z.constructor===void 0){let W={};for(let V in z)W[V]=X(z[V]);return W}return z},Z=Q.map(X);this.__events[J]?.forEach((z)=>z(...Z)),this.__once_events[J]?.forEach((z)=>z(...Z)),delete this.__once_events[J]}}var PJ=null;class i{nsp;settings;constructor(J,Q){if(typeof J!=="string"||!J)throw Error("Undefined or invalid stylesheet namespace");this.nsp=J,this.settings=Q||{},this.settings.sheet&&this.load(this.settings)}get rel(){return`${this.settings.meta?"@":""}${this.nsp}`}get styleElement(){return document.head.querySelector(`style[rel="${this.rel}"]`)}load(J){if(this.settings=J,!J.sheet)return;if(!PJ){console.warn(`[lips] <${this.nsp}> stylesheet skipped — this build has no CSS preprocessor. `+'Use "@lipsjs/lips" (not "@lipsjs/lips/runtime") for source stylesheets.');return}let Q=this.styleElement;if(Q)return Q.setAttribute("dindex",String(Number(Q.getAttribute("dindex")||0)+1)),Q;let X=J.meta?J.sheet:`[rel="${this.nsp}"] { ${J.sheet} }`,Z;try{Z=PJ(X)}catch(W){throw Error(`Style compilation failed: ${W.message}`)}if(!Z)throw Error(`<${this.nsp}> stylesheet compilation produced no output`);let z=document.createElement("style");return z.setAttribute("rel",this.rel),z.setAttribute("dindex","0"),z.textContent=Z,J.meta?document.head.prepend(z):document.head.appendChild(z),z}clear(){let J=this.styleElement;if(!J)return;let Q=Number(J.getAttribute("dindex")||0);Q<=0?J.remove():J.setAttribute("dindex",String(Q-1))}}function d(J,Q){if(typeof J!=="string")return"";if(!Q)return J;return J.replace(/{(\w+)}/g,(X,Z)=>{return Q[Z]!==void 0?Q[Z].toString():`{${Z}}`})}var LJ=(J,Q,X,Z,z)=>{switch(J){case"plural":{if(typeof X==="string"){console.warn("Plural format value cannot be a string");return}if(Z.count===void 0){console.warn("Plural format requires <count> parameter or use * by default.");let q=X["*"];if(typeof q==="object")q=q[z||"*"];return d(q,Z)}if(typeof Z.count==="string")Z.count=Number(Z.count);let W="*";if(Z.count.toString()in X)W=Z.count.toString();let V=X[W]||X["*"];if(typeof V==="object")V=V[z||"*"];return d(V,Z)}case"condition":{if(typeof X==="string"){console.warn("Condition format value cannot be a string");return}let W;for(let V in X)try{if(Function("params",`with( params ){ return ${V}; }`)(Z||{})){W=X[V];break}}catch(q){console.warn(`Invalid <${Q}(${V})> condition expression`)}if(W===void 0)return;if(typeof W==="object")W=W[z||"*"];return d(W,Z)}case"variable":default:{let W=typeof X==="object"?X[z||"*"]:X;if(typeof W==="object"){console.warn(`Invalid <${Q}> variable variant definition`);return}return d(W,Z)}}};class l{currentLang=window.navigator.language;DICTIONARIES={};set lang(J){if(this.currentLang===J)return;this.currentLang=J}get lang(){return this.currentLang}setDictionary(J,Q){this.DICTIONARIES[J]=Q}translate(J,Q){if(Q&&this.currentLang===Q)return{text:J,lang:this.currentLang};Q=Q||this.currentLang;let[X,Z]=Q.split("-");if(this.DICTIONARIES[X]&&J in this.DICTIONARIES[X]){if(typeof this.DICTIONARIES[X][J]==="object"){let z=this.DICTIONARIES[X][J];J=z[Z||"*"]||z["*"]}else if(typeof this.DICTIONARIES[X][J]==="string")J=this.DICTIONARIES[X][J]}return{text:J,lang:Q}}format(J,Q,X){X=X||this.currentLang;let[Z,z]=X.split("-");if(!this.DICTIONARIES[Z]){console.warn(`Undefined <${X}> format dictionary`);return}if(!this.DICTIONARIES[Z][J]){console.warn(`Undefined <${X}[${J}]> format reference`);return}let W=this.DICTIONARIES[Z][J];if(typeof W==="string"){console.warn(`Invalid <${X}[${J}]> format reference. Expected object`);return}if(typeof W!=="object"||W===null||Array.isArray(W)){console.warn(`Invalid <${X}[${J}]> format value`);return}return LJ(W.type,J,W.value,Q,z)}}var t=null;var _J={};var RJ=new Set(["state","input","static","context","emit","on","once","off","node","destroy","appendTo","prependTo","replaceWith","render","swap"]);function jJ(J){if(!J)return;for(let Q of Object.keys(J))if(RJ.has(Q))throw Error(`Handler <${Q}> is a reserved component member name`);return J}class SJ extends p{lips;template;state;instance;contextWatcher;destroyed=!1;constructor(J,Q,X,Z,z,W){super();this.lips=J;this.template=X;let V=jJ(X.handler);this.state=E({...X.state||{}},!0);let q=Z?E({...Z},!0):void 0;if(this.instance=o(z,{state:this.state,input:q,context:J.getContext(),static:X._static,handlers:V,deep:!0,stylesheet:X.stylesheet,nsp:Q,expose:{emit:(Y,...$)=>this.emit(Y,...$),context:J.getContext()}},W),X.context?.length&&typeof V?.onContext==="function")this.contextWatcher=J.watchContext(X.context,()=>{try{V.onContext.call(this.instance.self)}catch(Y){console.error("[lips:ir]",Y)}});this.emit("component:mount")}get node(){return this.instance.nodes}appendTo(J){let Q=typeof J==="string"?document.querySelector(J):J;return Q&&this.instance.mount(Q),this}swap(J){return this.instance.swap(J)}destroy(){if(this.destroyed)return;this.destroyed=!0,this.contextWatcher?.(),this.instance.dispose(),this.emit("component:destroy")}}class s{config;debug;store=new Map;irCache=new WeakMap;defCache=new WeakMap;context;__root;i18n=new l;getLang;setLang;componentsProxy;constructor(J){this.config=J;this.debug=!!J?.debug,this.context=E({...J?.context||{}},!0);let[Q,X]=A(this.i18n.lang);this.getLang=Q,this.setLang=X,t&&Object.entries(_J).forEach(([z,W])=>this.register(z,W));let Z=this;this.componentsProxy=new Proxy({},{get(z,W){let V=Z.store.get(W);return V?Z.defFor(W,V):void 0},has(z,W){return Z.store.has(W)}})}register(J,Q){return this.store.set(J,Q),this}unregister(J){return this.store.delete(J),this}has(J){return this.store.has(J)}compile(J){if(J.ir)return J.ir;let Q=this.irCache.get(J);if(!Q){if(!t)throw Error("This build has no template compiler — templates must be precompiled to `ir` "+'(import from "@lipsjs/lips" instead of "@lipsjs/lips/runtime")');let X=t(J.default||"",{macros:J.macros});X.diagnostics.length&&console.warn("[lips:ir] template diagnostics —",X.diagnostics),Q=X.ir,this.irCache.set(J,Q)}return Q}defFor(J,Q){let X=this.defCache.get(Q);if(!X)X={ir:this.compile(Q),state:Q.state,statics:Q._static,context:Q.context,stylesheet:Q.stylesheet,nsp:J,handlers:jJ(Q.handler),deep:!0},this.defCache.set(Q,X);return X}render(J,Q,X){return new SJ(this,J,Q,X,this.compile(Q),{mode:this.config?.mode,components:this.componentsProxy,watchContext:(Z,z)=>this.watchContext(Z,z),resolveTemplate:(Z)=>Z&&(typeof Z.default==="string"||Z.ir)?this.defFor(Z.name||"dynamic",Z):void 0,expose:{setContext:(Z,z)=>this.setContext(Z,z)},createStylesheet:(Z,z)=>{let W=new i(Z,{sheet:z});return{clear:()=>W.clear()}},i18n:{translate:(Z)=>{return this.getLang(),this.i18n.translate(Z).text},format:(Z,z)=>{return this.getLang(),this.i18n.format(Z,z)??""}}})}root(J,Q){return this.__root=this.render("__ROOT__",J),this.__root.appendTo(Q),this.__root}setLanguage(J){this.i18n.lang=J,this.setLang(J)}getLanguage(){return this.getLang()}useTranslator(J,Q){let X=!0,{dispose:Z}=O(()=>{let z=this.getLang();if(X){X=!1;return}(J==="*"||Array.isArray(J)&&J.includes(z))&&Q(z)});return Z}getContext(){return this.context}setContext(J,Q){typeof J==="string"?this.context[J]=Q:Object.entries(J).forEach(([X,Z])=>this.context[X]=Z)}watchContext(J,Q){let X=!0,{dispose:Z}=O(()=>{J.forEach((z)=>this.context[z]),X?X=!1:Q()});return Z}useContext(J,Q){return this.watchContext(J,()=>Q(Object.fromEntries(J.map((X)=>[X,this.context[X]]))))}dispose(){this.__root?.destroy()}}var eJ=s;export{I as untrack,A as signal,o as renderIR,E as reactive,O as effect,eJ as default};
|
|
3
|
+
|
|
4
|
+
//# debugId=BD57D191358240F764756E2164756E21
|