mutorjs 1.3.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -1,16 +1,1463 @@
1
- import{readFileSync as we}from"fs";import{copyFile as be,mkdir as Re,readdir as fe,readFile as Pe,writeFile as Se}from"fs/promises";import{extname as he,join as ee}from"path";function Z(e,r){return`${" ".repeat(e+r+1)}^`}var d=class e extends Error{constructor(t){super(t);this.name="MutorError";Object.setPrototypeOf(this,e.prototype)}},M=class e extends d{constructor(t,i,o,c,f){let m=i.toString().length+2,s=`${t}
2
-
3
- `;s+=`at ${f}:${i}:${c+1}
4
- `,i>1&&(s+=`${(i-1).toString().padStart(m-2)} | ...
5
- `),s+=`${i} | ${o}
6
- `,s+=Z(c,m);super(s);this.name="MutorCompilerError";Object.setPrototypeOf(this,e.prototype)}};var te=new Set(["for","if","else","true","false","null","undefined","end","in","of"]),B=new Set(["::","||","??","&&","**","^","|","&","!","-","%","+","*","/",">","<",">=","<=","==","!=",">>","<<",".","?.","(",")","[","]",",",":","?"]);var re=new Set(["==","!="]),V=new Set([">","<",">=","<="]);var ne=new Set(["+","-"]),oe=new Set(["*","/","%"]),se=new Set([".","?.","[","::"]),ie=new Set(["-","+","!"]),ae={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},S={build:{include:new Set([".html",".txt"]),exclude:new Set(["node_modules",".git"])},autoEscape:!0,allowedProps:new Set,forbiddenProps:new Set(["__proto__","constructor","prototype"]),allowFnCalls:!1,delimiters:{closingTag:"}}",openingTag:"{{",openingTagEscape:"\\",whitespaceTrim:"~",commentTag:"#"},keepOpeningTagEscapeDelimiter:!1,cache:{active:!0,maxSize:50*1024*1024}},ce={JSON:{stringify(e){try{return JSON.stringify(e)}catch{throw new d("JSON.stringify failed: invalid value")}},parse(e){if(typeof e!="string")throw new d("JSON.parse expects a string");try{return JSON.parse(e)}catch{throw new d("JSON.parse failed: invalid JSON string")}}},Object:{keys(e){if(!e||typeof e!="object")throw new d("Object.keys expects an object");return Object.keys(e)},values(e){if(!e||typeof e!="object")throw new d("Object.values expects an object");return Object.values(e)},entries(e){if(!e||typeof e!="object")throw new d("Object.entries expects an object");return Object.entries(e)},hasOwn(e,r){if(!e||typeof e!="object")throw new d("Object.hasOwn expects an object");return Object.hasOwn(e,r)},freeze(e){if(!e||typeof e!="object")throw new d("Object.freeze expects an object");return Object.freeze(e)},seal(e){if(!e||typeof e!="object")throw new d("Object.seal expects an object");return Object.seal(e)},fromEntries(e){if(!Array.isArray(e))throw new d("Object.fromEntries expects an array");return Object.fromEntries(e)}},Array:{isArray(e){return Array.isArray(e)},from(e){return Array.from(e)}},Number:{isFinite(e){return Number.isFinite(e)},isNaN(e){return Number.isNaN(e)},parseInt(e,r=10){return Number.parseInt(e,r)},parseFloat(e){return Number.parseFloat(e)}},String:{fromCharCode(...e){return String.fromCharCode(...e)}},Math:{abs(e){return Math.abs(e)},floor(e){return Math.floor(e)},ceil(e){return Math.ceil(e)},round(e){return Math.round(e)},max(...e){return Math.max(...e)},min(...e){return Math.min(...e)},random(){return Math.random()}},Date:{now(){return Date.now()},parse(e){if(typeof e!="string")throw new d("Date.parse expects a string");return Date.parse(e)}},Boolean:{valueOf(e){return!!e}}};function F(e){return typeof e!="string"?e:/[&<>"']/.test(e)?e.replace(/[&<>"']/g,r=>ae[r]):e}import{dirname as _e,isAbsolute as ye,resolve as pe}from"path";function T(e,...r){let t=ye(e)?e:pe(process.cwd(),e);if(r.length){let i=_e(t);return pe(i,...r)}return t}function D(e,r,t){if(t.has(e)&&!r.has(e))throw new d(`Forbidden property access. Access to this computed property "${e}" is forbidden.`);return e}var L="object",le=Symbol("__mutor_safe_context");function j(e){if(!e||typeof e!==L||le in e)return e;let r=new WeakSet;function t(o,c=""){if(!o||typeof o!==L||r.has(o))return o;r.add(o);let f=Object.getPrototypeOf(o);if(f&&f!==Object.prototype&&f!==Array.prototype)throw new d(`Unsafe prototype detected at ${c||"root"}`);if(Array.isArray(o)){for(let s=0;s<o.length;s++)o[s]=t(o[s],`${c}[${s}]`);return o}if(o instanceof Map){for(let[s,p]of o.entries())typeof s===L&&t(s,`${c}.mapKey`),o.set(s,t(p,`${c}.mapValue`));return o}if(o instanceof Set){let s=new Set;for(let p of o.values())s.add(t(p,c));o.clear();for(let p of s)o.add(p);return o}let m=Object.getOwnPropertyDescriptors(o);for(let s of Object.keys(m)){let p=m[s];if(p.get||p.set)throw new d(`Getter/setter not allowed: ${c}.${s}`);let _=o[s];_&&typeof _===L&&(o[s]=t(_,`${c}.${s}`))}return o}let i=t(e);return i&&typeof i===L&&Object.defineProperty(i,le,{value:!0,enumerable:!1,writable:!1,configurable:!1}),i}function U(e){return e.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$/g,"\\$")}function W(e,r){let i=e.slice(0,r).split(`
7
- `).length,o=e.lastIndexOf(`
8
- `,r-1)+1;return{line:i,lineIndex:o}}function Y(e,r,t){let i=e.indexOf(`
9
- `,r);return{line:e.slice(r,i===-1?void 0:i),pos:t-r}}function z(e,r){let{scope:t,forbiddenProps:i,allowedProps:o}=r;function c(a){return t.includes(a)?a:`ctx.${a}`}function f(a){switch(a.type){case 17:return"}";case 5:return a.value;case 4:return`\`${/\$/.test(a.value)?a.value.replaceAll("$","\\$"):a.value}\``;case 10:return a.true?"true":"false";case 12:return"null";case 11:return"undefined";case 7:return c(a.value);case 9:return`(${f(a.expr)})`;case 2:return`${a.operator}${f(a.expr)}`;case 0:return`${f(a.left)} ${a.operator} ${f(a.right)}`;case 1:return`${f(a.condition)} ? ${f(a.left)} : ${f(a.right)}`;case 8:return s(a);case 3:return p(a);case 6:return m(a);case 13:return _(a);case 16:return"} else {";case 14:return y(a);case 15:return b(a);default:throw new d(`Unsupported expression type: ${a.type}`)}}function m(a){if(a.left.type!==7)throw{message:"Invalid usage of namespace operator.",pos:a.pos};return`namespaces.${a.left.value}.${a.right.value}`}function s(a){let E=f(a.left);if(a.bracketNotation){let h=f(a.right),O=a.optional?"?.":"";return a.right.type===4||a.right.type===5?`${E}${O}[${h}]`:`${E}${O}[validateComputedProps(${h}, allowedProps, forbiddenProps)]`}else{let h=a.right.value,O=a.optional?"?.":".";if(i.has(h)&&!o.has(h))throw{message:"Forbidden property access.",pos:a.right.pos};return`${E}${O}${h}`}}function p(a){let E=f(a.expr),h=a.optional?"?.":"",O=a.args.map(P=>f(P)).join(", ");return`${E}${h}(${O})`}function _(a){let{iterable:E,loopType:h,variable:O}=a;return`for(const ${O} ${h===1?"in":"of"} ${z(E,r)}){`}function y(a){let{condition:E}=a;return`if(${z(E,r)}){`}function b(a){let{condition:E}=a;return`}else if(${z(E,r)}){`}return f(e)}function G(e){switch(e){case 0:return"identifier";case 1:return"keyword";case 2:return"number";case 4:return"operator";case 3:return"string"}}function H(e,r){let t=0,i=!1;function o(n,l){let u=e[t],C=e[e.length-1];if(!u)throw{message:`Unexpected end of expression. Expected ${l?`'${l}'`:`${n===0?"an":"a"} ${G(n)}`}.`,pos:C.pos+C.value.length-1};if(u.type!==n)throw{message:`Unexpected token type. Expected ${l?`'${l}'`:G(n)} but got ${G(u.type)} instead.`,pos:u.pos};if(l!==void 0&&u.value!==l)throw{message:`Unexpected token '${u?.value}'. Expected ${n===0?"an":"a"} ${G(n)} instead.`,pos:u.pos};return e[t++]}function c(){let n=e[t-1].pos,l=o(0).value,u;try{u=o(1,"in")}catch{u=o(1,"of")}let C=u.value==="in"?1:0,v=w();return{type:13,loopType:C,iterable:v,variable:l,pos:n}}function f(){let n=w();return{condition:n,pos:n.pos,type:14}}function m(){let n=e[t-1].pos;try{return o(1,"if"),{...f(),type:15,pos:n}}catch{return{type:16,pos:n}}}function s(){let n=[];if(e[t]?.type===4&&e[t]?.value===")")return n;for(n.push(w());e[t]?.type===4&&e[t]?.value===","&&e[t]?.value!==")";)t++,n.push(w());return n}function p(){let n=e[t++];if(n?.type===2)return{type:5,value:n.value,pos:n.pos};if(n?.type===3)return{type:4,value:n.value,pos:n.pos};if(n?.type===1){if(n.value==="for"&&t===1)return c();if(n.value==="true"||n.value==="false")return{type:10,true:n.value==="true",pos:n.pos};if(n.value==="undefined")return{type:11,pos:n.pos};if(n.value==="null")return{type:12,pos:n.pos};if(n.value==="end"&&e.length===1)return{type:17,pos:n.pos};if(n.value==="if"&&t===1)return f();if(n.value==="else"&&t===1)return m()}if(n?.type===0)return{type:7,value:n.value,pos:n.pos};if(n?.type===4&&n.value==="("){let l=w();return o(4,")"),{type:9,expr:l,pos:n.pos}}if(n?.type===4&&ie.has(n.value)){let l=n.value,u=w();return{type:2,operator:l,expr:u,pos:n.pos}}throw t>e.length?{message:"Unexpected end of expression.",pos:e[e.length-1].pos}:{message:`Unexpected token '${n?.value}'.`,pos:n.pos}}function _(){let n=p();for(;e[t];){let l=e[t];if(l?.type===4&&l?.value==="("){if(t++,!i&&!r.allowFnCalls)throw{message:"Function calls are not allowed.",pos:e[t-1].pos};let u=s();o(4,")"),n={type:3,expr:n,args:u,pos:e[t-1].pos}}else if(l?.type===4&&l?.value==="?."&&e[t+1]?.type===4&&e[t+1]?.value==="("){if(t++,t++,!i&&!r.allowFnCalls)throw{message:"Function calls are not allowed.",pos:e[t-1].pos};let u=s();o(4,")"),n={type:3,expr:n,args:u,optional:!0,pos:e[t-1].pos}}else if(l?.type===4&&se.has(l?.value)){let u=l?.value==="::",C=l?.value==="[",v=l?.value==="?.";if(t++,u&&(e[t-2]?.type!==0||e[t]?.type!==0))throw{message:`Invalid namespaces access. Expected syntax <IDENTIFIER>::<IDENTIFIER>, but got '${e[t-2]?.value}::${e[t]?.value}' instead.`,pos:e[t]?.pos};if(u){i=!0;let R=p();n={type:6,left:n,right:R,pos:e[t-1].pos}}else if(C){let R=w();o(4,"]"),n={type:8,right:R,left:n,bracketNotation:!0,pos:e[t-1].pos}}else if(v)if(e[t]?.type===4&&e[t]?.value==="["){t++;let R=w();o(4,"]"),n={type:8,left:n,right:R,bracketNotation:!0,optional:!0,pos:e[t-1].pos}}else{let R=p();n={type:8,left:n,right:R,optional:!0,pos:e[t-1].pos}}else{let R=p();n={type:8,left:n,right:R,pos:e[t-1].pos}}}else break}return i=!1,n}function y(){let n=_();for(;e[t]?.type===4&&oe.has(e[t]?.value);){let l=e[t++].value,u=_();n={type:0,left:n,right:u,operator:l,pos:e[t-1].pos}}return n}function b(){let n=y();for(;e[t]?.type===4&&ne.has(e[t]?.value);){let l=e[t++].value,u=y();n={type:0,left:n,right:u,operator:l,pos:e[t-1].pos}}return n}function a(){let n=b();for(;e[t]?.type===4&&V.has(e[t]?.value);){let l=e[t++].value,u=b();n={type:0,left:n,right:u,operator:l,pos:e[t-1].pos}}return n}function E(){let n=a();for(;e[t]?.type===4&&V.has(e[t]?.value);){let l=e[t++].value,u=a();n={type:0,left:n,right:u,operator:l,pos:e[t-1].pos}}return n}function h(){let n=E();for(;e[t]?.type===4&&re.has(e[t]?.value);){let l=e[t++].value,u=E();n={type:0,left:n,right:u,operator:l,pos:e[t-1].pos}}return n}function O(){let n=P();for(;e[t]?.type===4&&e[t]?.value==="||";){let l=e[t++].value,u=P();n={type:0,left:n,right:u,operator:l,pos:e[t-1].pos}}return n}function P(){let n=$();for(;e[t]?.type===4&&e[t]?.value==="&&";){let l=e[t++].value,u=$();n={type:0,left:n,right:u,operator:l,pos:e[t-1].pos}}return n}function $(){let n=h();for(;e[t]?.type===4&&e[t]?.value==="??";){let l=e[t++].value,u=h();n={type:0,left:n,right:u,operator:l,pos:e[t-1].pos}}return n}function w(){let n=O();if(e[t]?.type!==4||e[t]?.value!=="?")return n;t++;let l=w();o(4,":");let u=w();return{type:1,left:l,right:u,condition:n,pos:e[t-1].pos}}return w()}function Q(e,{delimiters:r}){let t=`${r.openingTag}${r.whitespaceTrim}`,i=`${r.whitespaceTrim}${r.closingTag}`,o=e.startsWith(t),c=e.endsWith(i),f=e.startsWith(o?t+r.commentTag:r.openingTag+r.commentTag);if(f)return{isComment:f,leftTrim:o,rightTrim:c};let m=e.slice(o?t.length:r.openingTag.length,e.length-(c?i.length:r.closingTag.length)),s=m.trim(),p=s.startsWith("for")||s.startsWith("if")||s.startsWith("else"),_=s.startsWith("for")||s.startsWith("if"),y=s==="end",b=s.startsWith("for");return{leftTrim:o,rightTrim:c,inner:m,isBlock:p,isBlockEnd:y,hasContext:b,requiresBlockClose:_}}function X(e){let r=0,t="",i=[];function o(){let s="";if(/[a-zA-Z$_]/.test(t)){let p=r;for(;/[a-zA-Z$_0-9]/.test(e[p])&&p<e.length;)s+=e[p],p++;i.push({type:te.has(s)?1:0,value:s,pos:r}),r=p,t=e[r]}}function c(){let s="";if(t==='"'||t==="'"||t==="`"){let p=r+1;for(;e[p]!==t&&p<e.length;)s+=e[p],p++;if(p>e.length)throw{pos:r,message:"Found string without closing quote."};i.push({type:3,value:s,pos:r}),r=p}}function f(){if(/[0-9]/.test(t)){let s=r,p="";for(;/[0-9.oxe]/.test(e[s])&&s<e.length;)p+=e[s],s++;let _=Number(p);if(Number.isNaN(_))throw{pos:r,message:"Found invalid number literal."};i.push({type:2,value:`${_}`,pos:r}),r=s-1,t=e[r]}}function m(){let s=`${t}${e[r+1]}`;if(B.has(s)){i.push({type:4,value:s,pos:r}),r++;return}if(B.has(t)){i.push({type:4,value:t,pos:r});return}}for(;r<e.length;){if(t=e[r],f(),o(),c(),m(),!/[a-zA-Z$_0-9\s\t\r\n'"`]/.test(t)&&!B.has(t)&&!B.has(e[r-1]+t))throw{message:`Unexpected token '${t}' in expression.`,pos:r};r++}return i}function k(e,r,t){let i=[],o=[],{delimiters:c,keepOpeningTagEscapeDelimiter:f,allowFnCalls:m,allowedProps:s,forbiddenProps:p,autoEscape:_}=r,y=!1,b=0,a='let acc="";';for(;b<e.length;){let O=function(){let g=h,N=0;for(;g>=c.openingTagEscape.length&&e.slice(g-c.openingTagEscape.length,g)===c.openingTagEscape;)N++,g-=c.openingTagEscape.length;return N%2===1};var E=O;let h=e.indexOf(c.openingTag,b);if(h===-1){let g=e.slice(b);y&&(g=g.trimStart()),g&&(a+=`acc+=\`${U(g)}\`;`);break}if(O()){let g=e.slice(b,f?h+c.openingTagEscape.length+1:h-c.openingTag.length+1);y&&(g=g.trimStart(),y=!1),a+=`acc+=\`${U(g)}\`;`,f||(a+=`acc+=\`${c.openingTag}\`;`),b=h+c.openingTag.length;continue}let P=e.indexOf(c.closingTag,h);if(P===-1){let{line:g,lineIndex:N}=W(e,h),{line:x,pos:I}=Y(e,N,h);throw new M("No closing tag found.",g,x,I,t.path)}let $=e.slice(h,P+c.closingTag.length),{inner:w,leftTrim:q,rightTrim:n,isBlock:l,isBlockEnd:u,hasContext:C,requiresBlockClose:v,isComment:R}=Q($,{delimiters:c}),A=e.slice(b,h);A&&(y&&(A=A.trimStart()),q&&(A=A.trimEnd()),A&&(a+=`acc+=\`${U(A)}\`;`)),y=!1,b=P+c.closingTag.length;try{if(!R){let g=X(w),N=H(g,{allowFnCalls:m});if(l&&v&&C?(i.push(N.variable),o.push({type:0,pos:h})):l&&v&&!C&&o.push({type:1,pos:h}),u){let I=o.pop();if(I?.type===0&&i.pop(),I===void 0)throw{message:"Unexpected end of block",pos:h}}let x=z(N,{allowedProps:s,forbiddenProps:p,scope:i});l||u?a+=x:a+=_&&!x.startsWith("namespaces.Mutor.include")?`acc+=escapeFn(${x});`:`acc+=${x};`}n&&(y=!0)}catch(g){let{message:N,pos:x}=g,{line:I,lineIndex:de}=W(e,h),{line:me,pos:ge}=Y(e,de,h);throw new M(N,I,me,ge+x+(q?c.openingTag.length+c.whitespaceTrim.length:c.openingTag.length),t.path)}}if(o.length){let h=o.pop()?.pos,{line:O,lineIndex:P}=W(e,h),{line:$,pos:w}=Y(e,P,h);throw new M("Unclosed block detected.",O,$,w+c.openingTag.length,t.path)}return a+="return acc;",new Function("ctx","namespaces","allowedProps","forbiddenProps","escapeFn","validateComputedProps",a)}var K=class{constructor(r={}){this.__currentRenderedPath="";this.__includeStack=new Set;this.__cacheSize=0;this.__config={...S};this.__compiledTemplatesMap=new Map;this.__currentContext=null;this.__namespaces={...ce,Mutor:{include:(r,t)=>{if(this.__includeStack.has(r))throw new d(`Circular include detected:
10
- ${Array.from(this.__includeStack).join(`
11
- `)}
12
- ${r}`);try{return this.__includeStack.add(r),this.renderComponent(r,t??this.__currentContext)}finally{this.__includeStack.delete(r)}}}};this.addConfig(r),Object.defineProperty(this.__namespaces.Mutor,"$$context",{get:()=>this.__currentContext})}addConfig(r){let{autoEscape:t,delimiters:i,allowedProps:o,forbiddenProps:c,keepOpeningTagEscapeDelimiter:f,allowFnCalls:m,cache:s,build:p}=r;return this.__config={build:{include:new Set([...p?.include||S.build.include]),exclude:new Set([...S.build.exclude,...p?.exclude||[]])},autoEscape:t===!0?!0:t!==!1,allowedProps:o||S.allowedProps,allowFnCalls:!!m,cache:{...S.cache,...s||{}},forbiddenProps:new Set([...S.forbiddenProps,...c||[]]),keepOpeningTagEscapeDelimiter:f===!0?!0:f!==!1,delimiters:{...S.delimiters,...i||{}}},this.__config}restoreDefaultConfig(){this.__config={...S}}compile(r){return k(r,this.__config,{path:this.__currentRenderedPath||"anonymous"})}render(r,t){let i=this.__currentContext;i!==t&&(this.__currentContext=t);let o=this.compile(r)(j(t),this.__namespaces,this.__config.allowedProps,this.__config.forbiddenProps,F,D);return this.__currentContext=i,o}renderComponent(r,t){if(!this.__compiledTemplatesMap.has(r))throw new d(`No template exists with the identifier '${r}'`);let i=this.__currentRenderedPath,o=this.__currentContext,c=this.__compiledTemplatesMap.get(r);this.__currentContext=t,this.__currentRenderedPath=r;let f=c.fn(j(t),this.__namespaces,this.__config.allowedProps,this.__config.forbiddenProps,F,D);return this.__currentContext=o,this.__currentRenderedPath=i,f}registerComponent(r,t){let i=t.length*2+500;if(this.__cacheSize+i>this.__config.cache.maxSize&&!this.createEntrySpaceForTemplate(i))throw new d(`The template for the component '${r}' is too large. Consider increasing 'cache.maxSize' in the config`);this.__cacheSize+=t.length*2+500,this.__compiledTemplatesMap.set(r,{fn:this.compile(t),size:i})}reset(){this.__config={...S},this.__compiledTemplatesMap.clear(),this.__currentContext=null,this.__cacheSize=0}createEntrySpaceForTemplate(r){if(this.__cacheSize+r<this.__config.cache.maxSize)return!0;if(r>this.__config.cache.maxSize)return!1;let t=this.__compiledTemplatesMap.entries().next().value;if(t){let[i,o]=t;this.__compiledTemplatesMap.delete(i),this.__cacheSize-=o.size}return this.createEntrySpaceForTemplate(r)}getDiagnostics(){let r=this.__config.cache.maxSize;return{bytesUsed:this.__cacheSize,bytesMax:r,readableUsed:`${(this.__cacheSize/1024/1024).toFixed(2)} MB`,readableMax:`${(r/1024/1024).toFixed(2)} MB`,totalEntries:this.__compiledTemplatesMap.size,percentFull:r>0?Math.min(100,Math.round(this.__cacheSize/r*100)):0,avgTemplateSize:this.__compiledTemplatesMap.size>0?Math.round(this.__cacheSize/this.__compiledTemplatesMap.size):0}}};var J=class extends K{constructor(r={}){super(r),this.__namespaces.Mutor.include=(t,i)=>{let o=T(this.__currentRenderedPath,t);if(this.__includeStack.has(o))throw new d(`Circular include detected:
13
- ${Array.from(this.__includeStack).join(`
14
- `)}
15
- ${o}`);try{return this.__includeStack.add(o),this.renderFile(o,i??this.__currentContext)}finally{this.__includeStack.delete(o)}}}renderFile(r,t){let i=T(r),o,c=this.__currentContext,f=this.__currentRenderedPath;if(this.__currentContext=t,this.__currentRenderedPath=r,this.__config.cache.active&&this.__compiledTemplatesMap.has(i))o=this.__compiledTemplatesMap.get(i).fn;else{let s=we(i,"utf-8");if(o=this.compile(s),this.__config.cache.active){let p=s.length*2+500;this.__cacheSize+p>this.__config.cache.maxSize?this.createEntrySpaceForTemplate(p)&&(this.__compiledTemplatesMap.set(i,{fn:o,size:p}),this.__cacheSize+=p):(this.__compiledTemplatesMap.set(i,{fn:o,size:p}),this.__cacheSize+=p)}}let m=o(j(t),this.__namespaces,this.__config.allowedProps,this.__config.forbiddenProps,F,D);return this.__currentContext=c,this.__currentRenderedPath=f,m}async buildDir(r,t,i){let o=T(t),c=T(r);await Re(o,{recursive:!0});let f=await fe(c,{withFileTypes:!0});await Promise.all(f.map(async m=>{let s=ee(c,m.name),p=ee(o,m.name);if(this.__config.build.exclude.has(m.name))return;if(m.isDirectory())return this.buildDir(s,p,i);let _=he(s);if(this.__config.build.include.has(_)){let y=this.renderFile(s,i);await Se(p,y,"utf-8")}else return await be(s,p)}))}async compileDir(r){let t=T(r),i=await fe(t,{withFileTypes:!0});await Promise.all(i.map(async o=>{let c=ee(t,o.name);if(this.__config.build.exclude.has(o.name))return;if(o.isDirectory())return this.compileDir(c);let f=he(c);if(this.__config.build.include.has(f))try{let m=await Pe(c,"utf-8");this.registerComponent(c,m)}catch{}}))}};var $t=J;export{$t as default};
1
+ // src/core/mutor.server.ts
2
+ import { readFileSync } from "fs";
3
+ import {
4
+ copyFile,
5
+ mkdir,
6
+ readdir,
7
+ readFile,
8
+ writeFile
9
+ } from "fs/promises";
10
+ import { extname, join } from "path";
11
+
12
+ // src/utils/construct-pointer.ts
13
+ function constructPointer(pos, offset) {
14
+ return `${" ".repeat(pos + offset + 1)}^`;
15
+ }
16
+
17
+ // src/core/error.ts
18
+ var MutorError = class _MutorError extends Error {
19
+ constructor(message) {
20
+ super(message);
21
+ this.name = "MutorError";
22
+ Object.setPrototypeOf(this, _MutorError.prototype);
23
+ }
24
+ };
25
+ var MutorCompilerError = class _MutorCompilerError extends MutorError {
26
+ constructor(message, line, lineText, column, file) {
27
+ const gutterWidth = line.toString().length + 2;
28
+ let report = `${message}
29
+
30
+ `;
31
+ report += `at ${file}:${line}:${column + 1}
32
+ `;
33
+ if (line > 1) {
34
+ report += `${(line - 1).toString().padStart(gutterWidth - 2)} | ...
35
+ `;
36
+ }
37
+ report += `${line} | ${lineText}
38
+ `;
39
+ report += constructPointer(column, gutterWidth);
40
+ super(report);
41
+ this.name = "MutorCompilerError";
42
+ Object.setPrototypeOf(this, _MutorCompilerError.prototype);
43
+ }
44
+ };
45
+
46
+ // src/core/constants.ts
47
+ var keywords = /* @__PURE__ */ new Set([
48
+ "for",
49
+ "if",
50
+ "else",
51
+ "true",
52
+ "false",
53
+ "null",
54
+ "undefined",
55
+ "end",
56
+ "in",
57
+ "of"
58
+ ]);
59
+ var operators = /* @__PURE__ */ new Set([
60
+ "::",
61
+ // Namespace access
62
+ "||",
63
+ // Or
64
+ "??",
65
+ // Nullish coalesce
66
+ "&&",
67
+ // And
68
+ "**",
69
+ // Power
70
+ "^",
71
+ // Bitwise XOr
72
+ "|",
73
+ // Bitwise Or
74
+ "&",
75
+ // Bitwise And
76
+ "!",
77
+ // Not
78
+ "-",
79
+ // Minus
80
+ "%",
81
+ // Modulus
82
+ "+",
83
+ // Plus
84
+ "*",
85
+ // Times
86
+ "/",
87
+ // Divide
88
+ ">",
89
+ // Greater than
90
+ "<",
91
+ // Less than
92
+ ">=",
93
+ // Greater or equal
94
+ "<=",
95
+ // Less or equal
96
+ "==",
97
+ // Strict equal
98
+ "!=",
99
+ // Strict not equal
100
+ ">>",
101
+ // Bitwise right shift
102
+ "<<",
103
+ // Bitwise left shift
104
+ ".",
105
+ // Property acess
106
+ "?.",
107
+ // Optional property access
108
+ "(",
109
+ // Open parentheses
110
+ ")",
111
+ // Close parentheses
112
+ "[",
113
+ // Square open parentheses
114
+ "]",
115
+ // Square close parentheses
116
+ ",",
117
+ // Comma
118
+ ":",
119
+ // Column
120
+ "?"
121
+ // Ternary operator
122
+ ]);
123
+ var equalityOperators = /* @__PURE__ */ new Set(["==", "!="]);
124
+ var comparisonOperators = /* @__PURE__ */ new Set([">", "<", ">=", "<="]);
125
+ var additiveOperators = /* @__PURE__ */ new Set(["+", "-"]);
126
+ var multiplicativeOperators = /* @__PURE__ */ new Set(["*", "/", "%"]);
127
+ var propertyAccessOperators = /* @__PURE__ */ new Set([".", "?.", "[", "::"]);
128
+ var unaryOperators = /* @__PURE__ */ new Set(["-", "+", "!"]);
129
+ var ESCAPE_MAP = {
130
+ "&": "&amp;",
131
+ "<": "&lt;",
132
+ ">": "&gt;",
133
+ '"': "&quot;",
134
+ "'": "&#39;"
135
+ };
136
+ var defaultConfig = {
137
+ build: {
138
+ include: /* @__PURE__ */ new Set([".html", ".txt"]),
139
+ exclude: /* @__PURE__ */ new Set(["node_modules", ".git"])
140
+ },
141
+ autoEscape: true,
142
+ allowedProps: /* @__PURE__ */ new Set(),
143
+ forbiddenProps: /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]),
144
+ allowFnCalls: false,
145
+ delimiters: {
146
+ closingTag: "}}",
147
+ openingTag: "{{",
148
+ openingTagEscape: "\\",
149
+ whitespaceTrim: "~",
150
+ commentTag: "#"
151
+ },
152
+ keepOpeningTagEscapeDelimiter: false,
153
+ cache: {
154
+ active: true,
155
+ maxSize: 50 * 1024 * 1024
156
+ // 50MB
157
+ }
158
+ };
159
+ var namespaces = {
160
+ JSON: {
161
+ stringify(value) {
162
+ try {
163
+ return JSON.stringify(value);
164
+ } catch {
165
+ throw new MutorError("JSON.stringify failed: invalid value");
166
+ }
167
+ },
168
+ parse(str) {
169
+ if (typeof str !== "string") {
170
+ throw new MutorError("JSON.parse expects a string");
171
+ }
172
+ try {
173
+ return JSON.parse(str);
174
+ } catch {
175
+ throw new MutorError("JSON.parse failed: invalid JSON string");
176
+ }
177
+ }
178
+ },
179
+ Object: {
180
+ keys(obj) {
181
+ if (!obj || typeof obj !== "object") {
182
+ throw new MutorError("Object.keys expects an object");
183
+ }
184
+ return Object.keys(obj);
185
+ },
186
+ values(obj) {
187
+ if (!obj || typeof obj !== "object") {
188
+ throw new MutorError("Object.values expects an object");
189
+ }
190
+ return Object.values(obj);
191
+ },
192
+ entries(obj) {
193
+ if (!obj || typeof obj !== "object") {
194
+ throw new MutorError("Object.entries expects an object");
195
+ }
196
+ return Object.entries(obj);
197
+ },
198
+ hasOwn(obj, key) {
199
+ if (!obj || typeof obj !== "object") {
200
+ throw new MutorError("Object.hasOwn expects an object");
201
+ }
202
+ return Object.hasOwn(obj, key);
203
+ },
204
+ freeze(obj) {
205
+ if (!obj || typeof obj !== "object") {
206
+ throw new MutorError("Object.freeze expects an object");
207
+ }
208
+ return Object.freeze(obj);
209
+ },
210
+ seal(obj) {
211
+ if (!obj || typeof obj !== "object") {
212
+ throw new MutorError("Object.seal expects an object");
213
+ }
214
+ return Object.seal(obj);
215
+ },
216
+ fromEntries(entries) {
217
+ if (!Array.isArray(entries)) {
218
+ throw new MutorError("Object.fromEntries expects an array");
219
+ }
220
+ return Object.fromEntries(entries);
221
+ }
222
+ },
223
+ Array: {
224
+ isArray(value) {
225
+ return Array.isArray(value);
226
+ },
227
+ from(value) {
228
+ return Array.from(value);
229
+ }
230
+ },
231
+ Number: {
232
+ isFinite(value) {
233
+ return Number.isFinite(value);
234
+ },
235
+ isNaN(value) {
236
+ return Number.isNaN(value);
237
+ },
238
+ parseInt(value, radix = 10) {
239
+ return Number.parseInt(value, radix);
240
+ },
241
+ parseFloat(value) {
242
+ return Number.parseFloat(value);
243
+ }
244
+ },
245
+ String: {
246
+ fromCharCode(...args) {
247
+ return String.fromCharCode(...args);
248
+ }
249
+ },
250
+ Math: {
251
+ abs(x) {
252
+ return Math.abs(x);
253
+ },
254
+ floor(x) {
255
+ return Math.floor(x);
256
+ },
257
+ ceil(x) {
258
+ return Math.ceil(x);
259
+ },
260
+ round(x) {
261
+ return Math.round(x);
262
+ },
263
+ max(...args) {
264
+ return Math.max(...args);
265
+ },
266
+ min(...args) {
267
+ return Math.min(...args);
268
+ },
269
+ random() {
270
+ return Math.random();
271
+ }
272
+ },
273
+ Date: {
274
+ now() {
275
+ return Date.now();
276
+ },
277
+ parse(str) {
278
+ if (typeof str !== "string") {
279
+ throw new MutorError("Date.parse expects a string");
280
+ }
281
+ return Date.parse(str);
282
+ }
283
+ },
284
+ Boolean: {
285
+ valueOf(value) {
286
+ return Boolean(value);
287
+ }
288
+ }
289
+ };
290
+
291
+ // src/utils/escape-fn.ts
292
+ function escapeFn(e) {
293
+ if (typeof e !== "string") return e;
294
+ return /[&<>"']/.test(e) ? e.replace(/[&<>"']/g, (char) => ESCAPE_MAP[char]) : e;
295
+ }
296
+
297
+ // src/utils/to-absolute-path.ts
298
+ import { dirname, isAbsolute, resolve } from "path";
299
+ function toAbsolutePath(basePath, ...relativePaths) {
300
+ const absoluteBase = isAbsolute(basePath) ? basePath : resolve(process.cwd(), basePath);
301
+ if (relativePaths.length) {
302
+ const baseDir = dirname(absoluteBase);
303
+ return resolve(baseDir, ...relativePaths);
304
+ }
305
+ return absoluteBase;
306
+ }
307
+
308
+ // src/utils/validate-computed-prop.ts
309
+ function validateComputedProp(r, allowedProps, forbiddenProps) {
310
+ if (forbiddenProps.has(r) && !allowedProps.has(r)) {
311
+ throw new MutorError(
312
+ `Forbidden property access. Access to this computed property "${r}" is forbidden.`
313
+ );
314
+ }
315
+ return r;
316
+ }
317
+
318
+ // src/utils/validate-context.ts
319
+ var OBJECT = "object";
320
+ var MUTOR_SAFE = /* @__PURE__ */ Symbol("__mutor_safe_context");
321
+ function validateContext(ctx) {
322
+ if (!ctx || typeof ctx !== OBJECT) {
323
+ return ctx;
324
+ }
325
+ if (MUTOR_SAFE in ctx) {
326
+ return ctx;
327
+ }
328
+ const seen = /* @__PURE__ */ new WeakSet();
329
+ function walk(value, path = "") {
330
+ if (!value || typeof value !== OBJECT) return value;
331
+ if (seen.has(value)) return value;
332
+ seen.add(value);
333
+ const proto = Object.getPrototypeOf(value);
334
+ if (proto && proto !== Object.prototype && proto !== Array.prototype) {
335
+ throw new MutorError(`Unsafe prototype detected at ${path || "root"}`);
336
+ }
337
+ if (Array.isArray(value)) {
338
+ for (let i = 0; i < value.length; i++) {
339
+ value[i] = walk(value[i], `${path}[${i}]`);
340
+ }
341
+ return value;
342
+ }
343
+ if (value instanceof Map) {
344
+ for (const [k, v] of value.entries()) {
345
+ if (typeof k === OBJECT) walk(k, `${path}.mapKey`);
346
+ value.set(k, walk(v, `${path}.mapValue`));
347
+ }
348
+ return value;
349
+ }
350
+ if (value instanceof Set) {
351
+ const next = /* @__PURE__ */ new Set();
352
+ for (const v of value.values()) {
353
+ next.add(walk(v, path));
354
+ }
355
+ value.clear();
356
+ for (const v of next) value.add(v);
357
+ return value;
358
+ }
359
+ const descriptors = Object.getOwnPropertyDescriptors(value);
360
+ for (const key of Object.keys(descriptors)) {
361
+ const desc = descriptors[key];
362
+ if (desc.get || desc.set) {
363
+ throw new MutorError(`Getter/setter not allowed: ${path}.${key}`);
364
+ }
365
+ const prop = value[key];
366
+ if (prop && typeof prop === OBJECT) {
367
+ value[key] = walk(prop, `${path}.${key}`);
368
+ }
369
+ }
370
+ return value;
371
+ }
372
+ const safeData = walk(ctx);
373
+ if (safeData && typeof safeData === OBJECT) {
374
+ Object.defineProperty(safeData, MUTOR_SAFE, {
375
+ value: true,
376
+ enumerable: false,
377
+ writable: false,
378
+ configurable: false
379
+ });
380
+ }
381
+ return safeData;
382
+ }
383
+
384
+ // src/utils/escape-raw-text.ts
385
+ function escapeRawText(text) {
386
+ return text.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$/g, "\\$");
387
+ }
388
+
389
+ // src/utils/get-line-and-column-nums.ts
390
+ function getLineAndColumnNumbers(str, idx) {
391
+ const lines = str.slice(0, idx).split("\n");
392
+ const line = lines.length;
393
+ const lineIndex = str.lastIndexOf("\n", idx - 1) + 1;
394
+ return { line, lineIndex };
395
+ }
396
+
397
+ // src/utils/get-line-snapshot.ts
398
+ function getLineSnapshot(str, lineIdx, idx) {
399
+ const nextNewlineIdx = str.indexOf("\n", lineIdx);
400
+ const line = str.slice(
401
+ lineIdx,
402
+ nextNewlineIdx === -1 ? void 0 : nextNewlineIdx
403
+ );
404
+ return { line, pos: idx - lineIdx };
405
+ }
406
+
407
+ // src/core/build.ts
408
+ function build(ast, context) {
409
+ const { scope, forbiddenProps, allowedProps } = context;
410
+ function prefixWithCtx(ident) {
411
+ return scope.includes(ident) ? ident : `ctx.${ident}`;
412
+ }
413
+ function buildExpr(expr) {
414
+ switch (expr.type) {
415
+ case 17 /* END */:
416
+ return "}";
417
+ case 5 /* NUMBER */:
418
+ return expr.value;
419
+ case 4 /* STRING */:
420
+ return `\`${/\$/.test(expr.value) ? expr.value.replaceAll("$", "\\$") : expr.value}\``;
421
+ case 10 /* BOOLEAN */:
422
+ return expr.true ? "true" : "false";
423
+ case 12 /* NULL */:
424
+ return "null";
425
+ case 11 /* UNDEFINED */:
426
+ return "undefined";
427
+ case 7 /* IDENT */:
428
+ return prefixWithCtx(expr.value);
429
+ case 9 /* GROUP */:
430
+ return `(${buildExpr(expr.expr)})`;
431
+ case 2 /* UNARY */:
432
+ return `${expr.operator}${buildExpr(expr.expr)}`;
433
+ case 0 /* BINARY */:
434
+ return `${buildExpr(expr.left)} ${expr.operator} ${buildExpr(expr.right)}`;
435
+ case 1 /* TERNARY */:
436
+ return `${buildExpr(expr.condition)} ? ${buildExpr(expr.left)} : ${buildExpr(expr.right)}`;
437
+ case 8 /* PROP_ACCESS */:
438
+ return buildPropAccess(expr);
439
+ case 3 /* CALL */:
440
+ return buildCall(expr);
441
+ case 6 /* NAMESPACE */:
442
+ return buildNamespace(expr);
443
+ case 13 /* FOR */:
444
+ return buildForLoop(expr);
445
+ case 16 /* ELSE */:
446
+ return "} else {";
447
+ case 14 /* IF */:
448
+ return buildIfBlock(expr);
449
+ case 15 /* ELSE_IF */:
450
+ return buildElseIfBlock(expr);
451
+ default:
452
+ throw new MutorError(
453
+ `Unsupported expression type: ${expr.type}`
454
+ );
455
+ }
456
+ }
457
+ function buildNamespace(expr) {
458
+ if (expr.left.type !== 7 /* IDENT */) {
459
+ throw {
460
+ message: "Invalid usage of namespace operator.",
461
+ pos: expr.pos
462
+ };
463
+ }
464
+ return `namespaces.${expr.left.value}.${expr.right.value}`;
465
+ }
466
+ function buildPropAccess(expr) {
467
+ const left = buildExpr(expr.left);
468
+ if (expr.bracketNotation) {
469
+ const right = buildExpr(expr.right);
470
+ const optionalChain = expr.optional ? "?." : "";
471
+ return expr.right.type === 4 /* STRING */ || expr.right.type === 5 /* NUMBER */ ? `${left}${optionalChain}[${right}]` : `${left}${optionalChain}[validateComputedProps(${right}, allowedProps, forbiddenProps)]`;
472
+ } else {
473
+ const propName = expr.right.value;
474
+ const optionalChain = expr.optional ? "?." : ".";
475
+ if (forbiddenProps.has(propName) && !allowedProps.has(propName)) {
476
+ throw { message: "Forbidden property access.", pos: expr.right.pos };
477
+ }
478
+ return `${left}${optionalChain}${propName}`;
479
+ }
480
+ }
481
+ function buildCall(expr) {
482
+ const func = buildExpr(expr.expr);
483
+ const optionalChain = expr.optional ? "?." : "";
484
+ const args = expr.args.map((arg) => buildExpr(arg)).join(", ");
485
+ return `${func}${optionalChain}(${args})`;
486
+ }
487
+ function buildForLoop(expr) {
488
+ const { iterable, loopType, variable } = expr;
489
+ return `for(const ${variable} ${loopType === 1 /* IN */ ? "in" : "of"} ${build(iterable, context)}){`;
490
+ }
491
+ function buildIfBlock(expr) {
492
+ const { condition } = expr;
493
+ return `if(${build(condition, context)}){`;
494
+ }
495
+ function buildElseIfBlock(expr) {
496
+ const { condition } = expr;
497
+ return `}else if(${build(condition, context)}){`;
498
+ }
499
+ return buildExpr(ast);
500
+ }
501
+
502
+ // src/utils/get-token-type-words.ts
503
+ function getTokenTypeWords(type) {
504
+ switch (type) {
505
+ case 0 /* IDENT */:
506
+ return "identifier";
507
+ case 1 /* KEYWORD */:
508
+ return "keyword";
509
+ case 2 /* NUMBER */:
510
+ return "number";
511
+ case 4 /* OPERATOR */:
512
+ return "operator";
513
+ case 3 /* STRING */:
514
+ return "string";
515
+ }
516
+ }
517
+
518
+ // src/core/generate-ast.ts
519
+ function generateAst(tokens, config) {
520
+ let cursor = 0, generatingNamespace = false;
521
+ function expectOrThrow(type, value) {
522
+ const token = tokens[cursor];
523
+ const lastToken = tokens[tokens.length - 1];
524
+ if (!token) {
525
+ throw {
526
+ message: `Unexpected end of expression. Expected ${value ? `'${value}'` : `${type === 0 /* IDENT */ ? "an" : "a"} ${getTokenTypeWords(type)}`}.`,
527
+ pos: lastToken.pos + lastToken.value.length - 1
528
+ };
529
+ }
530
+ if (token.type !== type) {
531
+ throw {
532
+ message: `Unexpected token type. Expected ${value ? `'${value}'` : getTokenTypeWords(type)} but got ${getTokenTypeWords(token.type)} instead.`,
533
+ pos: token.pos
534
+ };
535
+ }
536
+ if (value !== void 0 && token.value !== value) {
537
+ throw {
538
+ message: `Unexpected token '${token?.value}'. Expected ${type === 0 /* IDENT */ ? "an" : "a"} ${getTokenTypeWords(type)} instead.`,
539
+ pos: token.pos
540
+ };
541
+ }
542
+ return tokens[cursor++];
543
+ }
544
+ function parseForLoop() {
545
+ const pos = tokens[cursor - 1].pos;
546
+ const variable = expectOrThrow(0 /* IDENT */).value;
547
+ let token;
548
+ try {
549
+ token = expectOrThrow(1 /* KEYWORD */, "in");
550
+ } catch {
551
+ token = expectOrThrow(1 /* KEYWORD */, "of");
552
+ }
553
+ const loopType = token.value === "in" ? 1 /* IN */ : 0 /* OF */;
554
+ const iterable = parseTernaryExpr();
555
+ return { type: 13 /* FOR */, loopType, iterable, variable, pos };
556
+ }
557
+ function parseIfExpression() {
558
+ const condition = parseTernaryExpr();
559
+ return { condition, pos: condition.pos, type: 14 /* IF */ };
560
+ }
561
+ function parseElseExpression() {
562
+ const pos = tokens[cursor - 1].pos;
563
+ try {
564
+ expectOrThrow(1 /* KEYWORD */, "if");
565
+ return { ...parseIfExpression(), type: 15 /* ELSE_IF */, pos };
566
+ } catch {
567
+ return { type: 16 /* ELSE */, pos };
568
+ }
569
+ }
570
+ function extractFnArgs() {
571
+ const args = [];
572
+ const emptyArgs = tokens[cursor]?.type === 4 /* OPERATOR */ && tokens[cursor]?.value === ")";
573
+ if (emptyArgs) {
574
+ return args;
575
+ }
576
+ args.push(parseTernaryExpr());
577
+ while (tokens[cursor]?.type === 4 /* OPERATOR */ && tokens[cursor]?.value === "," && tokens[cursor]?.value !== ")") {
578
+ cursor++;
579
+ args.push(parseTernaryExpr());
580
+ }
581
+ return args;
582
+ }
583
+ function parsePrimaryExpr() {
584
+ const token = tokens[cursor++];
585
+ if (token?.type === 2 /* NUMBER */) {
586
+ return { type: 5 /* NUMBER */, value: token.value, pos: token.pos };
587
+ }
588
+ if (token?.type === 3 /* STRING */) {
589
+ return { type: 4 /* STRING */, value: token.value, pos: token.pos };
590
+ }
591
+ if (token?.type === 1 /* KEYWORD */) {
592
+ if (token.value === "for" && cursor === 1) {
593
+ return parseForLoop();
594
+ }
595
+ if (token.value === "true" || token.value === "false") {
596
+ return {
597
+ type: 10 /* BOOLEAN */,
598
+ true: token.value === "true",
599
+ pos: token.pos
600
+ };
601
+ }
602
+ if (token.value === "undefined") {
603
+ return { type: 11 /* UNDEFINED */, pos: token.pos };
604
+ }
605
+ if (token.value === "null") {
606
+ return { type: 12 /* NULL */, pos: token.pos };
607
+ }
608
+ if (token.value === "end" && tokens.length === 1) {
609
+ return { type: 17 /* END */, pos: token.pos };
610
+ }
611
+ if (token.value === "if" && cursor === 1) {
612
+ return parseIfExpression();
613
+ }
614
+ if (token.value === "else" && cursor === 1) {
615
+ return parseElseExpression();
616
+ }
617
+ }
618
+ if (token?.type === 0 /* IDENT */) {
619
+ return { type: 7 /* IDENT */, value: token.value, pos: token.pos };
620
+ }
621
+ if (token?.type === 4 /* OPERATOR */ && token.value === "(") {
622
+ const expr = parseTernaryExpr();
623
+ expectOrThrow(4 /* OPERATOR */, ")");
624
+ return { type: 9 /* GROUP */, expr, pos: token.pos };
625
+ }
626
+ if (token?.type === 4 /* OPERATOR */ && unaryOperators.has(token.value)) {
627
+ const operator = token.value;
628
+ const expr = parseTernaryExpr();
629
+ return { type: 2 /* UNARY */, operator, expr, pos: token.pos };
630
+ }
631
+ if (cursor > tokens.length) {
632
+ throw {
633
+ message: `Unexpected end of expression.`,
634
+ pos: tokens[tokens.length - 1].pos
635
+ };
636
+ }
637
+ throw {
638
+ message: `Unexpected token '${token?.value}'.`,
639
+ pos: token.pos
640
+ };
641
+ }
642
+ function parsePropertyAccess() {
643
+ let left = parsePrimaryExpr();
644
+ while (tokens[cursor]) {
645
+ const token = tokens[cursor];
646
+ if (token?.type === 4 /* OPERATOR */ && token?.value === "(") {
647
+ cursor++;
648
+ if (!generatingNamespace && !config.allowFnCalls) {
649
+ throw {
650
+ message: "Function calls are not allowed.",
651
+ pos: tokens[cursor - 1].pos
652
+ };
653
+ }
654
+ const args = extractFnArgs();
655
+ expectOrThrow(4 /* OPERATOR */, ")");
656
+ left = {
657
+ type: 3 /* CALL */,
658
+ expr: left,
659
+ args,
660
+ pos: tokens[cursor - 1].pos
661
+ };
662
+ } else if (token?.type === 4 /* OPERATOR */ && token?.value === "?." && tokens[cursor + 1]?.type === 4 /* OPERATOR */ && tokens[cursor + 1]?.value === "(") {
663
+ cursor++;
664
+ cursor++;
665
+ if (!generatingNamespace && !config.allowFnCalls) {
666
+ throw {
667
+ message: "Function calls are not allowed.",
668
+ pos: tokens[cursor - 1].pos
669
+ };
670
+ }
671
+ const args = extractFnArgs();
672
+ expectOrThrow(4 /* OPERATOR */, ")");
673
+ left = {
674
+ type: 3 /* CALL */,
675
+ expr: left,
676
+ args,
677
+ optional: true,
678
+ pos: tokens[cursor - 1].pos
679
+ };
680
+ } else if (token?.type === 4 /* OPERATOR */ && propertyAccessOperators.has(token?.value)) {
681
+ const isNamespace = token?.value === "::";
682
+ const isBracketNotation = token?.value === "[";
683
+ const isOptional = token?.value === "?.";
684
+ cursor++;
685
+ if (isNamespace && (tokens[cursor - 2]?.type !== 0 /* IDENT */ || tokens[cursor]?.type !== 0 /* IDENT */)) {
686
+ throw {
687
+ message: `Invalid namespaces access. Expected syntax <IDENTIFIER>::<IDENTIFIER>, but got '${tokens[cursor - 2]?.value}::${tokens[cursor]?.value}' instead.`,
688
+ pos: tokens[cursor]?.pos
689
+ };
690
+ }
691
+ if (isNamespace) {
692
+ generatingNamespace = true;
693
+ const right = parsePrimaryExpr();
694
+ left = {
695
+ type: 6 /* NAMESPACE */,
696
+ left,
697
+ right,
698
+ pos: tokens[cursor - 1].pos
699
+ };
700
+ } else if (isBracketNotation) {
701
+ const right = parseTernaryExpr();
702
+ expectOrThrow(4 /* OPERATOR */, "]");
703
+ left = {
704
+ type: 8 /* PROP_ACCESS */,
705
+ right,
706
+ left,
707
+ bracketNotation: true,
708
+ pos: tokens[cursor - 1].pos
709
+ };
710
+ } else if (isOptional) {
711
+ if (tokens[cursor]?.type === 4 /* OPERATOR */ && tokens[cursor]?.value === "[") {
712
+ cursor++;
713
+ const right = parseTernaryExpr();
714
+ expectOrThrow(4 /* OPERATOR */, "]");
715
+ left = {
716
+ type: 8 /* PROP_ACCESS */,
717
+ left,
718
+ right,
719
+ bracketNotation: true,
720
+ optional: true,
721
+ pos: tokens[cursor - 1].pos
722
+ };
723
+ } else {
724
+ const right = parsePrimaryExpr();
725
+ left = {
726
+ type: 8 /* PROP_ACCESS */,
727
+ left,
728
+ right,
729
+ optional: true,
730
+ pos: tokens[cursor - 1].pos
731
+ };
732
+ }
733
+ } else {
734
+ const right = parsePrimaryExpr();
735
+ left = {
736
+ type: 8 /* PROP_ACCESS */,
737
+ left,
738
+ right,
739
+ pos: tokens[cursor - 1].pos
740
+ };
741
+ }
742
+ } else {
743
+ break;
744
+ }
745
+ }
746
+ generatingNamespace = false;
747
+ return left;
748
+ }
749
+ function parseMultiplicativeExpr() {
750
+ let left = parsePropertyAccess();
751
+ while (tokens[cursor]?.type === 4 /* OPERATOR */ && multiplicativeOperators.has(tokens[cursor]?.value)) {
752
+ const operator = tokens[cursor++].value;
753
+ const right = parsePropertyAccess();
754
+ left = {
755
+ type: 0 /* BINARY */,
756
+ left,
757
+ right,
758
+ operator,
759
+ pos: tokens[cursor - 1].pos
760
+ };
761
+ }
762
+ return left;
763
+ }
764
+ function parseAdditiveExpr() {
765
+ let left = parseMultiplicativeExpr();
766
+ while (tokens[cursor]?.type === 4 /* OPERATOR */ && additiveOperators.has(tokens[cursor]?.value)) {
767
+ const operator = tokens[cursor++].value;
768
+ const right = parseMultiplicativeExpr();
769
+ left = {
770
+ type: 0 /* BINARY */,
771
+ left,
772
+ right,
773
+ operator,
774
+ pos: tokens[cursor - 1].pos
775
+ };
776
+ }
777
+ return left;
778
+ }
779
+ function parseBitwiseExpr() {
780
+ let left = parseAdditiveExpr();
781
+ while (tokens[cursor]?.type === 4 /* OPERATOR */ && comparisonOperators.has(tokens[cursor]?.value)) {
782
+ const operator = tokens[cursor++].value;
783
+ const right = parseAdditiveExpr();
784
+ left = {
785
+ type: 0 /* BINARY */,
786
+ left,
787
+ right,
788
+ operator,
789
+ pos: tokens[cursor - 1].pos
790
+ };
791
+ }
792
+ return left;
793
+ }
794
+ function parseComparisonExpr() {
795
+ let left = parseBitwiseExpr();
796
+ while (tokens[cursor]?.type === 4 /* OPERATOR */ && comparisonOperators.has(tokens[cursor]?.value)) {
797
+ const operator = tokens[cursor++].value;
798
+ const right = parseBitwiseExpr();
799
+ left = {
800
+ type: 0 /* BINARY */,
801
+ left,
802
+ right,
803
+ operator,
804
+ pos: tokens[cursor - 1].pos
805
+ };
806
+ }
807
+ return left;
808
+ }
809
+ function parseEqualityExpr() {
810
+ let left = parseComparisonExpr();
811
+ while (tokens[cursor]?.type === 4 /* OPERATOR */ && equalityOperators.has(tokens[cursor]?.value)) {
812
+ const operator = tokens[cursor++].value;
813
+ const right = parseComparisonExpr();
814
+ left = {
815
+ type: 0 /* BINARY */,
816
+ left,
817
+ right,
818
+ operator,
819
+ pos: tokens[cursor - 1].pos
820
+ };
821
+ }
822
+ return left;
823
+ }
824
+ function parseLogicalOrExpr() {
825
+ let left = parseLogicalAndExpr();
826
+ while (tokens[cursor]?.type === 4 /* OPERATOR */ && tokens[cursor]?.value === "||") {
827
+ const operator = tokens[cursor++].value;
828
+ const right = parseLogicalAndExpr();
829
+ left = {
830
+ type: 0 /* BINARY */,
831
+ left,
832
+ right,
833
+ operator,
834
+ pos: tokens[cursor - 1].pos
835
+ };
836
+ }
837
+ return left;
838
+ }
839
+ function parseLogicalAndExpr() {
840
+ let left = parseNullishCoalesceExpr();
841
+ while (tokens[cursor]?.type === 4 /* OPERATOR */ && tokens[cursor]?.value === "&&") {
842
+ const operator = tokens[cursor++].value;
843
+ const right = parseNullishCoalesceExpr();
844
+ left = {
845
+ type: 0 /* BINARY */,
846
+ left,
847
+ right,
848
+ operator,
849
+ pos: tokens[cursor - 1].pos
850
+ };
851
+ }
852
+ return left;
853
+ }
854
+ function parseNullishCoalesceExpr() {
855
+ let left = parseEqualityExpr();
856
+ while (tokens[cursor]?.type === 4 /* OPERATOR */ && tokens[cursor]?.value === "??") {
857
+ const operator = tokens[cursor++].value;
858
+ const right = parseEqualityExpr();
859
+ left = {
860
+ type: 0 /* BINARY */,
861
+ left,
862
+ right,
863
+ operator,
864
+ pos: tokens[cursor - 1].pos
865
+ };
866
+ }
867
+ return left;
868
+ }
869
+ function parseTernaryExpr() {
870
+ const condition = parseLogicalOrExpr();
871
+ if (tokens[cursor]?.type !== 4 /* OPERATOR */ || tokens[cursor]?.value !== "?") {
872
+ return condition;
873
+ }
874
+ cursor++;
875
+ const left = parseTernaryExpr();
876
+ expectOrThrow(4 /* OPERATOR */, ":");
877
+ const right = parseTernaryExpr();
878
+ return {
879
+ type: 1 /* TERNARY */,
880
+ left,
881
+ right,
882
+ condition,
883
+ pos: tokens[cursor - 1].pos
884
+ };
885
+ }
886
+ const ast = parseTernaryExpr();
887
+ return ast;
888
+ }
889
+
890
+ // src/core/parse.ts
891
+ function parse(templateBlock, { delimiters }) {
892
+ const openingTagWithWhitespaceCtrl = `${delimiters.openingTag}${delimiters.whitespaceTrim}`;
893
+ const closingTagWithWhitespaceCtrl = `${delimiters.whitespaceTrim}${delimiters.closingTag}`;
894
+ const leftTrim = templateBlock.startsWith(openingTagWithWhitespaceCtrl);
895
+ const rightTrim = templateBlock.endsWith(closingTagWithWhitespaceCtrl);
896
+ const isComment = templateBlock.startsWith(
897
+ leftTrim ? openingTagWithWhitespaceCtrl + delimiters.commentTag : delimiters.openingTag + delimiters.commentTag
898
+ );
899
+ if (isComment) {
900
+ return { isComment, leftTrim, rightTrim };
901
+ }
902
+ const inner = templateBlock.slice(
903
+ leftTrim ? openingTagWithWhitespaceCtrl.length : delimiters.openingTag.length,
904
+ templateBlock.length - (rightTrim ? closingTagWithWhitespaceCtrl.length : delimiters.closingTag.length)
905
+ );
906
+ const trimmed = inner.trim();
907
+ const isBlock = trimmed.startsWith("for") || trimmed.startsWith("if") || trimmed.startsWith("else");
908
+ const requiresBlockClose = trimmed.startsWith("for") || trimmed.startsWith("if");
909
+ const isBlockEnd = trimmed === "end";
910
+ const hasContext = trimmed.startsWith("for");
911
+ return {
912
+ leftTrim,
913
+ rightTrim,
914
+ inner,
915
+ isBlock,
916
+ isBlockEnd,
917
+ hasContext,
918
+ requiresBlockClose
919
+ };
920
+ }
921
+
922
+ // src/core/tokenize.ts
923
+ function tokenize(expr) {
924
+ let cursor = 0, char = "";
925
+ const tokens = [];
926
+ function accumulateKeywordOrIdentifier() {
927
+ let buffer = "";
928
+ if (/[a-zA-Z$_]/.test(char)) {
929
+ let j = cursor;
930
+ while (/[a-zA-Z$_0-9]/.test(expr[j]) && j < expr.length) {
931
+ buffer += expr[j];
932
+ j++;
933
+ }
934
+ tokens.push({
935
+ type: keywords.has(buffer) ? 1 /* KEYWORD */ : 0 /* IDENT */,
936
+ value: buffer,
937
+ pos: cursor
938
+ });
939
+ cursor = j;
940
+ char = expr[cursor];
941
+ }
942
+ }
943
+ function accumulateStr() {
944
+ let buffer = "";
945
+ if (char === '"' || char === "'" || char === "`") {
946
+ let j = cursor + 1;
947
+ while (expr[j] !== char && j < expr.length) {
948
+ buffer += expr[j];
949
+ j++;
950
+ }
951
+ if (j > expr.length) {
952
+ throw { pos: cursor, message: `Found string without closing quote.` };
953
+ }
954
+ tokens.push({ type: 3 /* STRING */, value: buffer, pos: cursor });
955
+ cursor = j;
956
+ }
957
+ }
958
+ function accumulateNumber() {
959
+ if (/[0-9]/.test(char)) {
960
+ let j = cursor, buffer = "";
961
+ while (/[0-9.oxe]/.test(expr[j]) && j < expr.length) {
962
+ buffer += expr[j];
963
+ j++;
964
+ }
965
+ const numVal = Number(buffer);
966
+ const isNan = Number.isNaN(numVal);
967
+ if (isNan) {
968
+ throw { pos: cursor, message: "Found invalid number literal." };
969
+ }
970
+ tokens.push({ type: 2 /* NUMBER */, value: `${numVal}`, pos: cursor });
971
+ cursor = j - 1;
972
+ char = expr[cursor];
973
+ }
974
+ }
975
+ function accumulateOperator() {
976
+ const op = `${char}${expr[cursor + 1]}`;
977
+ if (operators.has(op)) {
978
+ tokens.push({ type: 4 /* OPERATOR */, value: op, pos: cursor });
979
+ cursor++;
980
+ return;
981
+ }
982
+ if (operators.has(char)) {
983
+ tokens.push({ type: 4 /* OPERATOR */, value: char, pos: cursor });
984
+ return;
985
+ }
986
+ }
987
+ while (cursor < expr.length) {
988
+ char = expr[cursor];
989
+ accumulateNumber();
990
+ accumulateKeywordOrIdentifier();
991
+ accumulateStr();
992
+ accumulateOperator();
993
+ if (!/[a-zA-Z$_0-9\s\t\r\n'"`]/.test(char) && !operators.has(char) && !operators.has(expr[cursor - 1] + char)) {
994
+ throw {
995
+ message: `Unexpected token '${char}' in expression.`,
996
+ pos: cursor
997
+ };
998
+ }
999
+ cursor++;
1000
+ }
1001
+ return tokens;
1002
+ }
1003
+
1004
+ // src/core/compile.ts
1005
+ function compile(src, config, meta) {
1006
+ const scope = [];
1007
+ const blockOpeningStack = [];
1008
+ const {
1009
+ delimiters,
1010
+ keepOpeningTagEscapeDelimiter,
1011
+ allowFnCalls,
1012
+ allowedProps,
1013
+ forbiddenProps,
1014
+ autoEscape
1015
+ } = config;
1016
+ let trimNext = false, cursor = 0, body = `let acc="";`;
1017
+ while (cursor < src.length) {
1018
+ let isEscaped2 = function() {
1019
+ let j = templateOpenTagIdx, count = 0;
1020
+ while (j >= delimiters.openingTagEscape.length && src.slice(j - delimiters.openingTagEscape.length, j) === delimiters.openingTagEscape) {
1021
+ count++;
1022
+ j -= delimiters.openingTagEscape.length;
1023
+ }
1024
+ return count % 2 === 1;
1025
+ };
1026
+ var isEscaped = isEscaped2;
1027
+ const templateOpenTagIdx = src.indexOf(delimiters.openingTag, cursor);
1028
+ if (templateOpenTagIdx === -1) {
1029
+ let lastChunk = src.slice(cursor);
1030
+ if (trimNext) lastChunk = lastChunk.trimStart();
1031
+ if (lastChunk) body += `acc+=\`${escapeRawText(lastChunk)}\`;`;
1032
+ break;
1033
+ }
1034
+ if (isEscaped2()) {
1035
+ let escapedChunk = src.slice(
1036
+ cursor,
1037
+ keepOpeningTagEscapeDelimiter ? templateOpenTagIdx + delimiters.openingTagEscape.length + 1 : templateOpenTagIdx - delimiters.openingTag.length + 1
1038
+ );
1039
+ if (trimNext) {
1040
+ escapedChunk = escapedChunk.trimStart();
1041
+ trimNext = false;
1042
+ }
1043
+ body += `acc+=\`${escapeRawText(escapedChunk)}\`;`;
1044
+ if (!keepOpeningTagEscapeDelimiter)
1045
+ body += `acc+=\`${delimiters.openingTag}\`;`;
1046
+ cursor = templateOpenTagIdx + delimiters.openingTag.length;
1047
+ continue;
1048
+ }
1049
+ const templateEndTagIdx = src.indexOf(
1050
+ delimiters.closingTag,
1051
+ templateOpenTagIdx
1052
+ );
1053
+ if (templateEndTagIdx === -1) {
1054
+ const { line, lineIndex } = getLineAndColumnNumbers(
1055
+ src,
1056
+ templateOpenTagIdx
1057
+ );
1058
+ const { line: lineText, pos } = getLineSnapshot(
1059
+ src,
1060
+ lineIndex,
1061
+ templateOpenTagIdx
1062
+ );
1063
+ throw new MutorCompilerError(
1064
+ "No closing tag found.",
1065
+ line,
1066
+ lineText,
1067
+ pos,
1068
+ meta.path
1069
+ );
1070
+ }
1071
+ const template = src.slice(
1072
+ templateOpenTagIdx,
1073
+ templateEndTagIdx + delimiters.closingTag.length
1074
+ );
1075
+ const {
1076
+ inner,
1077
+ leftTrim,
1078
+ rightTrim,
1079
+ isBlock,
1080
+ isBlockEnd,
1081
+ hasContext,
1082
+ requiresBlockClose,
1083
+ isComment
1084
+ } = parse(template, { delimiters });
1085
+ let rawText = src.slice(cursor, templateOpenTagIdx);
1086
+ if (rawText) {
1087
+ if (trimNext) {
1088
+ rawText = rawText.trimStart();
1089
+ }
1090
+ if (leftTrim) {
1091
+ rawText = rawText.trimEnd();
1092
+ }
1093
+ if (rawText) {
1094
+ body += `acc+=\`${escapeRawText(rawText)}\`;`;
1095
+ }
1096
+ }
1097
+ trimNext = false;
1098
+ cursor = templateEndTagIdx + delimiters.closingTag.length;
1099
+ try {
1100
+ if (!isComment) {
1101
+ const tokens = tokenize(inner);
1102
+ const ast = generateAst(tokens, { allowFnCalls });
1103
+ if (isBlock && requiresBlockClose && hasContext) {
1104
+ scope.push(ast.variable);
1105
+ blockOpeningStack.push({
1106
+ type: 0 /* LOOP */,
1107
+ pos: templateOpenTagIdx
1108
+ });
1109
+ } else if (isBlock && requiresBlockClose && !hasContext) {
1110
+ blockOpeningStack.push({
1111
+ type: 1 /* NON_LOOP */,
1112
+ pos: templateOpenTagIdx
1113
+ });
1114
+ }
1115
+ if (isBlockEnd) {
1116
+ const lastBlockOpened = blockOpeningStack.pop();
1117
+ if (lastBlockOpened?.type === 0 /* LOOP */) scope.pop();
1118
+ if (lastBlockOpened === void 0)
1119
+ throw {
1120
+ message: "Unexpected end of block",
1121
+ pos: templateOpenTagIdx
1122
+ };
1123
+ }
1124
+ const js = build(ast, { allowedProps, forbiddenProps, scope });
1125
+ if (isBlock || isBlockEnd) {
1126
+ body += js;
1127
+ } else {
1128
+ body += autoEscape && !js.startsWith("namespaces.Mutor.include") ? `acc+=escapeFn(${js});` : `acc+=${js};`;
1129
+ }
1130
+ }
1131
+ if (rightTrim) trimNext = true;
1132
+ } catch (e) {
1133
+ const { message, pos: relPos } = e;
1134
+ const { line, lineIndex } = getLineAndColumnNumbers(
1135
+ src,
1136
+ templateOpenTagIdx
1137
+ );
1138
+ const { line: lineText, pos } = getLineSnapshot(
1139
+ src,
1140
+ lineIndex,
1141
+ templateOpenTagIdx
1142
+ );
1143
+ throw new MutorCompilerError(
1144
+ message,
1145
+ line,
1146
+ lineText,
1147
+ pos + relPos + (leftTrim ? delimiters.openingTag.length + delimiters.whitespaceTrim.length : delimiters.openingTag.length),
1148
+ meta.path
1149
+ );
1150
+ }
1151
+ }
1152
+ if (blockOpeningStack.length) {
1153
+ const lastPos = blockOpeningStack.pop()?.pos;
1154
+ const { line, lineIndex } = getLineAndColumnNumbers(src, lastPos);
1155
+ const { line: lineText, pos } = getLineSnapshot(src, lineIndex, lastPos);
1156
+ throw new MutorCompilerError(
1157
+ "Unclosed block detected.",
1158
+ line,
1159
+ lineText,
1160
+ pos + delimiters.openingTag.length,
1161
+ meta.path
1162
+ );
1163
+ }
1164
+ body += `return acc;`;
1165
+ return new Function(
1166
+ "ctx",
1167
+ "namespaces",
1168
+ "allowedProps",
1169
+ "forbiddenProps",
1170
+ "escapeFn",
1171
+ "validateComputedProps",
1172
+ body
1173
+ );
1174
+ }
1175
+
1176
+ // src/core/mutor.ts
1177
+ var Mutor = class {
1178
+ constructor(config = {}) {
1179
+ this.__currentRenderedPath = "";
1180
+ this.__includeStack = /* @__PURE__ */ new Set();
1181
+ this.__cacheSize = 0;
1182
+ this.__config = { ...defaultConfig };
1183
+ this.__compiledTemplatesMap = /* @__PURE__ */ new Map();
1184
+ this.__currentContext = null;
1185
+ this.__namespaces = {
1186
+ ...namespaces,
1187
+ Mutor: {
1188
+ include: (path, ctx) => {
1189
+ if (this.__includeStack.has(path)) {
1190
+ throw new MutorError(
1191
+ `Circular include detected:
1192
+ ${Array.from(this.__includeStack).join("\n")}
1193
+ ${path}`
1194
+ );
1195
+ }
1196
+ try {
1197
+ this.__includeStack.add(path);
1198
+ return this.renderComponent(path, ctx ?? this.__currentContext);
1199
+ } finally {
1200
+ this.__includeStack.delete(path);
1201
+ }
1202
+ }
1203
+ }
1204
+ };
1205
+ this.addConfig(config);
1206
+ Object.defineProperty(this.__namespaces.Mutor, "$$context", {
1207
+ get: () => {
1208
+ return this.__currentContext;
1209
+ }
1210
+ });
1211
+ }
1212
+ addConfig(conf) {
1213
+ const {
1214
+ autoEscape,
1215
+ delimiters: overrideDelimeters,
1216
+ allowedProps,
1217
+ forbiddenProps,
1218
+ keepOpeningTagEscapeDelimiter,
1219
+ allowFnCalls,
1220
+ cache,
1221
+ build: build2
1222
+ } = conf;
1223
+ this.__config = {
1224
+ build: {
1225
+ include: /* @__PURE__ */ new Set([...build2?.include || defaultConfig.build.include]),
1226
+ exclude: /* @__PURE__ */ new Set([
1227
+ ...defaultConfig.build.exclude,
1228
+ ...build2?.exclude || []
1229
+ ])
1230
+ },
1231
+ autoEscape: autoEscape === true ? true : autoEscape !== false,
1232
+ allowedProps: allowedProps || defaultConfig.allowedProps,
1233
+ allowFnCalls: !!allowFnCalls,
1234
+ cache: { ...defaultConfig.cache, ...cache || {} },
1235
+ forbiddenProps: /* @__PURE__ */ new Set([
1236
+ ...defaultConfig.forbiddenProps,
1237
+ ...forbiddenProps || []
1238
+ ]),
1239
+ keepOpeningTagEscapeDelimiter: keepOpeningTagEscapeDelimiter === true ? true : keepOpeningTagEscapeDelimiter !== false,
1240
+ delimiters: {
1241
+ ...defaultConfig.delimiters,
1242
+ ...overrideDelimeters || {}
1243
+ }
1244
+ };
1245
+ return this.__config;
1246
+ }
1247
+ restoreDefaultConfig() {
1248
+ this.__config = { ...defaultConfig };
1249
+ }
1250
+ compile(template) {
1251
+ return compile(template, this.__config, {
1252
+ path: this.__currentRenderedPath || "anonymous"
1253
+ });
1254
+ }
1255
+ render(template, context) {
1256
+ const prevContext = this.__currentContext;
1257
+ if (prevContext !== context) {
1258
+ this.__currentContext = context;
1259
+ }
1260
+ const result = this.compile(template)(
1261
+ validateContext(context),
1262
+ this.__namespaces,
1263
+ this.__config.allowedProps,
1264
+ this.__config.forbiddenProps,
1265
+ escapeFn,
1266
+ validateComputedProp
1267
+ );
1268
+ this.__currentContext = prevContext;
1269
+ return result;
1270
+ }
1271
+ renderComponent(identifier, context) {
1272
+ if (!this.__compiledTemplatesMap.has(identifier)) {
1273
+ throw new MutorError(
1274
+ `No template exists with the identifier '${identifier}'`
1275
+ );
1276
+ }
1277
+ const prevRenderComponentIdentifier = this.__currentRenderedPath;
1278
+ const prevContext = this.__currentContext;
1279
+ const compiled = this.__compiledTemplatesMap.get(identifier);
1280
+ this.__currentContext = context;
1281
+ this.__currentRenderedPath = identifier;
1282
+ const result = compiled.fn(
1283
+ validateContext(context),
1284
+ this.__namespaces,
1285
+ this.__config.allowedProps,
1286
+ this.__config.forbiddenProps,
1287
+ escapeFn,
1288
+ validateComputedProp
1289
+ );
1290
+ this.__currentContext = prevContext;
1291
+ this.__currentRenderedPath = prevRenderComponentIdentifier;
1292
+ return result;
1293
+ }
1294
+ registerComponent(identifier, template) {
1295
+ const templateSize = template.length * 2 + 500;
1296
+ if (this.__cacheSize + templateSize > this.__config.cache.maxSize) {
1297
+ if (!this.createEntrySpaceForTemplate(templateSize)) {
1298
+ throw new MutorError(
1299
+ `The template for the component '${identifier}' is too large. Consider increasing 'cache.maxSize' in the config`
1300
+ );
1301
+ }
1302
+ }
1303
+ this.__cacheSize += template.length * 2 + 500;
1304
+ this.__compiledTemplatesMap.set(identifier, {
1305
+ fn: this.compile(template),
1306
+ size: templateSize
1307
+ });
1308
+ }
1309
+ reset() {
1310
+ this.__config = { ...defaultConfig };
1311
+ this.__compiledTemplatesMap.clear();
1312
+ this.__currentContext = null;
1313
+ this.__cacheSize = 0;
1314
+ }
1315
+ createEntrySpaceForTemplate(targetSize) {
1316
+ if (this.__cacheSize + targetSize < this.__config.cache.maxSize) {
1317
+ return true;
1318
+ }
1319
+ if (targetSize > this.__config.cache.maxSize) {
1320
+ return false;
1321
+ }
1322
+ const firstEntry = this.__compiledTemplatesMap.entries().next().value;
1323
+ if (firstEntry) {
1324
+ const [oldestKey, oldestData] = firstEntry;
1325
+ this.__compiledTemplatesMap.delete(oldestKey);
1326
+ this.__cacheSize -= oldestData.size;
1327
+ }
1328
+ return this.createEntrySpaceForTemplate(targetSize);
1329
+ }
1330
+ getDiagnostics() {
1331
+ const maxSize = this.__config.cache.maxSize;
1332
+ return {
1333
+ bytesUsed: this.__cacheSize,
1334
+ bytesMax: maxSize,
1335
+ readableUsed: `${(this.__cacheSize / 1024 / 1024).toFixed(2)} MB`,
1336
+ readableMax: `${(maxSize / 1024 / 1024).toFixed(2)} MB`,
1337
+ totalEntries: this.__compiledTemplatesMap.size,
1338
+ percentFull: maxSize > 0 ? Math.min(100, Math.round(this.__cacheSize / maxSize * 100)) : 0,
1339
+ avgTemplateSize: this.__compiledTemplatesMap.size > 0 ? Math.round(this.__cacheSize / this.__compiledTemplatesMap.size) : 0
1340
+ };
1341
+ }
1342
+ };
1343
+
1344
+ // src/core/mutor.server.ts
1345
+ var Mutor2 = class extends Mutor {
1346
+ constructor(config = {}) {
1347
+ super(config);
1348
+ this.__namespaces.Mutor.include = (path, context) => {
1349
+ const resolvedPath = toAbsolutePath(this.__currentRenderedPath, path);
1350
+ if (this.__includeStack.has(resolvedPath)) {
1351
+ throw new MutorError(
1352
+ `Circular include detected:
1353
+ ${Array.from(this.__includeStack).join("\n")}
1354
+ ${resolvedPath}`
1355
+ );
1356
+ }
1357
+ try {
1358
+ this.__includeStack.add(resolvedPath);
1359
+ return this.renderFile(resolvedPath, context ?? this.__currentContext);
1360
+ } finally {
1361
+ this.__includeStack.delete(resolvedPath);
1362
+ }
1363
+ };
1364
+ }
1365
+ renderFile(path, context) {
1366
+ const absolutePath = toAbsolutePath(path);
1367
+ let compiled;
1368
+ const prevContext = this.__currentContext;
1369
+ const prevRenderComponentIdentifier = this.__currentRenderedPath;
1370
+ this.__currentContext = context;
1371
+ this.__currentRenderedPath = path;
1372
+ if (this.__config.cache.active && this.__compiledTemplatesMap.has(absolutePath)) {
1373
+ compiled = this.__compiledTemplatesMap.get(absolutePath).fn;
1374
+ } else {
1375
+ const template = readFileSync(absolutePath, "utf-8");
1376
+ compiled = this.compile(template);
1377
+ if (this.__config.cache.active) {
1378
+ const templateSize = template.length * 2 + 500;
1379
+ if (this.__cacheSize + templateSize > this.__config.cache.maxSize) {
1380
+ if (this.createEntrySpaceForTemplate(templateSize)) {
1381
+ this.__compiledTemplatesMap.set(absolutePath, {
1382
+ fn: compiled,
1383
+ size: templateSize
1384
+ });
1385
+ this.__cacheSize += templateSize;
1386
+ }
1387
+ } else {
1388
+ this.__compiledTemplatesMap.set(absolutePath, {
1389
+ fn: compiled,
1390
+ size: templateSize
1391
+ });
1392
+ this.__cacheSize += templateSize;
1393
+ }
1394
+ }
1395
+ }
1396
+ const result = compiled(
1397
+ validateContext(context),
1398
+ this.__namespaces,
1399
+ this.__config.allowedProps,
1400
+ this.__config.forbiddenProps,
1401
+ escapeFn,
1402
+ validateComputedProp
1403
+ );
1404
+ this.__currentContext = prevContext;
1405
+ this.__currentRenderedPath = prevRenderComponentIdentifier;
1406
+ return result;
1407
+ }
1408
+ async buildDir(src, destination, context) {
1409
+ const absoluteDestinationPath = toAbsolutePath(destination);
1410
+ const absoluteSrcPath = toAbsolutePath(src);
1411
+ await mkdir(absoluteDestinationPath, { recursive: true });
1412
+ const entries = await readdir(absoluteSrcPath, { withFileTypes: true });
1413
+ await Promise.all(
1414
+ entries.map(async (entry) => {
1415
+ const srcPath = join(absoluteSrcPath, entry.name);
1416
+ const destinationPath = join(absoluteDestinationPath, entry.name);
1417
+ if (this.__config.build.exclude.has(entry.name)) {
1418
+ return;
1419
+ }
1420
+ if (entry.isDirectory()) {
1421
+ return this.buildDir(srcPath, destinationPath, context);
1422
+ }
1423
+ const extension = extname(srcPath);
1424
+ if (this.__config.build.include.has(extension)) {
1425
+ const rendered = this.renderFile(srcPath, context);
1426
+ await writeFile(destinationPath, rendered, "utf-8");
1427
+ } else {
1428
+ return await copyFile(srcPath, destinationPath);
1429
+ }
1430
+ })
1431
+ );
1432
+ }
1433
+ async compileDir(src) {
1434
+ const absolutePath = toAbsolutePath(src);
1435
+ const entries = await readdir(absolutePath, { withFileTypes: true });
1436
+ await Promise.all(
1437
+ entries.map(async (entry) => {
1438
+ const absoluteSrcPath = join(absolutePath, entry.name);
1439
+ if (this.__config.build.exclude.has(entry.name)) {
1440
+ return;
1441
+ }
1442
+ if (entry.isDirectory()) {
1443
+ return this.compileDir(absoluteSrcPath);
1444
+ }
1445
+ const extension = extname(absoluteSrcPath);
1446
+ if (this.__config.build.include.has(extension)) {
1447
+ try {
1448
+ const template = await readFile(absoluteSrcPath, "utf-8");
1449
+ this.registerComponent(absoluteSrcPath, template);
1450
+ } catch {
1451
+ }
1452
+ }
1453
+ })
1454
+ );
1455
+ }
1456
+ };
1457
+
1458
+ // src/server.ts
1459
+ var server_default = Mutor2;
1460
+ export {
1461
+ server_default as default
1462
+ };
16
1463
  //# sourceMappingURL=server.js.map