compomint
Version:
A lightweight JavaScript component engine for building web applications with a focus on component-based architecture and template system.
3 lines (2 loc) • 45.4 kB
JavaScript
function e(e,t,n,r){return new(n||(n=Promise))(function(o,i){function l(e){try{c(r.next(e))}catch(e){i(e)}}function s(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(l,s)}c((r=r.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;const t=function(e){if(e.firstElementChild)return e.firstElementChild;const t=e.childNodes;for(let e=0,n=t.length;e<n;e++)if(t[e]instanceof Element)return t[e];return null},n=function(e){return e.childElementCount||Array.prototype.filter.call(e.childNodes||[],function(e){return e instanceof Element}).length},r=function(e){if(e.childNodes)for(let t=0;t<e.childNodes.length;t++){const n=e.childNodes[t];8===n.nodeType||3===n.nodeType&&!/\S/.test(n.nodeValue||"")?(e.removeChild(n),t--):1===n.nodeType&&r(n)}},o=function(e){if("number"==typeof e||!isNaN(Number(e)))return document.createTextNode(String(e));if("string"!=typeof e)return document.createTextNode("");try{const t="undefined"!=typeof DOMParser?new DOMParser:{parseFromString:(e,t)=>({body:{childNodes:[],firstChild:null,appendChild:()=>{},removeChild:()=>{}}})},n=t.parseFromString(e,"text/html").body;if(1===n.childNodes.length)return n.firstChild;{const e=document.createDocumentFragment();for(;n.firstChild;)e.appendChild(n.firstChild);return e}}catch(t){return document.createTextNode(e)}},i=e=>{const r=e.configs;return{rules:{style:{pattern:/(\<style id=[\s\S]+?\>[\s\S]+?\<\/style\>)/g,exec:function(e){var t;const n=document.createElement("template");n.innerHTML=e;const r=(n.content||n).querySelector("style");if(!r||!r.id)return"";const o=document.getElementById(r.id);return o&&(null===(t=o.parentNode)||void 0===t||t.removeChild(o)),document.head.appendChild(r),""}},commentArea:{pattern:/##\*([\s\S]+?)##/g,exec:function(e){return""}},preEvaluate:{pattern:/##!([\s\S]+?)##/g,exec:function(t,n){try{new Function("compomint","tmplId",t)(e,n)}catch(e){if(r.throwError)throw console.error(`Template preEvaluate error in "${n}", ${e.name}: ${e.message}`),e;console.warn(`Template preEvaluate error in "${n}", ${e.name}: ${e.message}`)}return""}},interpolate:{pattern:/##=([\s\S]+?)##/g,exec:function(e){return`';\n{let __t, interpolate=${e};\n__p+=((__t=(typeof (interpolate)=='function' ? (interpolate)() : (interpolate)))==null ? '' : String(__t) );};\n__p+='`}},escape:{pattern:/##-([\s\S]+?)##/g,exec:function(e){return`';\n{let __t, escape=${e};\n__p+=((__t=(compomint.tools.escapeHtml.escape(typeof (escape)=='function' ? (escape)() : (escape))))==null ? '' : String(__t) );};\n__p+='`}},elementProps:{pattern:/data-co-props="##:([\s\S]+?)##"/g,exec:function(e){return`';\n{const eventId = (__lazyScope.elementPropsArray.length);\n__p+='data-co-props="'+eventId+'"';\n\n__lazyScope.elementPropsArray[eventId] = ${e}};\n__p+='`},lazyExec:function(e,t,n,r){t.elementPropsArray.forEach(function(e,t){if(!e)return;const n=r.querySelector(`[data-co-props="${t}"]`);n&&(delete n.dataset.coProps,Object.keys(e).forEach(function(t){n.setAttribute(t,String(e[t]))}))})}},namedElement:{pattern:/data-co-named-element="##:([\s\S]+?)##"/g,exec:function(e){return`';\nconst eventId = (__lazyScope.namedElementArray.length);\n__p+='data-co-named-element="'+eventId+'"';\n\n__lazyScope.namedElementArray[eventId] = ${e};\n__p+='`},lazyExec:function(e,t,n,o){t.namedElementArray.forEach(function(e,t){const i=o.querySelector(`[data-co-named-element="${t}"]`);i?(delete i.dataset.coNamedElement,n[e]=i):r.debug&&console.warn(`Named element target not found for ID ${t} in template ${n.tmplId}`)})}},elementRef:{pattern:/data-co-element-ref="##:([\s\S]+?)##"/g,exec:function(e){return`';\n{const eventId = (__lazyScope.elementRefArray.length);\n__p+='data-co-element-ref="'+eventId+'"';\nvar ${e} = null;\n__lazyScope.elementRefArray[eventId] = function(target) {${e} = target;}};\n__p+='`},lazyExec:function(e,t,n,o){t.elementRefArray.forEach(function(e,t){const i=o.querySelector(`[data-co-element-ref="${t}"]`);i?(delete i.dataset.coElementRef,e.call(i,i)):r.debug&&console.warn(`Element ref target not found for ID ${t} in template ${n.tmplId}`)})}},elementLoad:{pattern:/data-co-load="##:([\s\S]+?)##"/g,exec:function(e){const t=e.split("::");return`';\n{const eventId = (__lazyScope.elementLoadArray.length);\n__p+='data-co-load="'+eventId+'"';\n__lazyScope.elementLoadArray[eventId] = {loadFunc: ${t[0]}, customData: ${t[1]}};}\n__p+='`},lazyExec:function(t,n,o,i){n.elementLoadArray.forEach(function(n,l){const s=i.querySelector(`[data-co-load="${l}"]`);if(s){delete s.dataset.coLoad;try{if("function"==typeof n.loadFunc){const r=[s,s,{data:t,element:s,customData:n.customData,component:o,compomint:e}];n.loadFunc.call(...r)}}catch(e){if(console.error(`Error executing elementLoad function for ID ${l} in template ${o.tmplId}:`,e,n.loadFunc),r.throwError)throw e}}else r.debug&&console.warn(`Element load target not found for ID ${l} in template ${o.tmplId}`)})}},event:{pattern:/data-co-event="##:([\s\S]+?)##"/g,exec:function(e){const t=e.split(":::");let n="';\n{const eventId = (__lazyScope.eventArray.length);\n__p+='data-co-event=\"'+eventId+'\"';\n";const r=[];for(let e=0,n=t.length;e<n;e++){const n=t[e].split("::");r.push(`{eventFunc: ${n[0]}, $parent: this, customData: ${n[1]}}`)}return n+=`__lazyScope.eventArray[eventId] = [${r.join(",")}];}\n__p+='`,n},lazyExec:function(e,t,n,o){const i=this,l=i.attacher;l&&t.eventArray.forEach(function(s,c){const a=o.querySelector(`[data-co-event="${c}"]`);if(a){delete a.dataset.coEvent;for(let r=0,c=s.length;r<c;r++){const c=s[r];c.eventFunc&&(Array.isArray(c.eventFunc)?c.eventFunc.forEach(function(r){l(i,e,t,n,o,a,r,c)}):l(i,e,t,n,o,a,c.eventFunc,c))}}else r.debug&&console.warn(`Event target not found for ID ${c} in template ${n.tmplId}`)})},trigger:function(e,t){const n=new Event(t,{bubbles:!0,cancelable:!0});e.dispatchEvent(n)},attacher:function(o,i,l,s,c,a,d,p){const u=o.trigger,m=t(c),f=1===n(c)?m:null;if(!d)return;const h=[a,null,{data:i,customData:p.customData,element:a,componentElement:f||(null==m?void 0:m.parentElement),component:s,compomint:e}];if("function"==typeof d){const e=function(e){e.stopPropagation(),h[1]=e;try{d.call(...h)}catch(e){if(console.error(`Error in event handler for template ${s.tmplId}:`,e,d),r.throwError)throw e}};return a.addEventListener("click",e),p.element=a,void(p.eventFunc=e)}if(y=d,"[object Object]"!==Object.prototype.toString.call(y))return;var y;const g=d,E=g.triggerName;E&&(s.trigger=s.trigger||{},s.trigger[E]={}),Object.keys(g).forEach(function(e){const t=g[e];if("load"===e){h[1]=a;try{t.call(...h)}catch(e){if(console.error(`Error in 'load' event handler for template ${s.tmplId}:`,e,t),r.throwError)throw e}return}if("namedElement"===e)return void(s[t]=a);if("triggerName"===e)return;const n=function(n){n.stopPropagation(),h[1]=n;try{t.call(...h)}catch(n){if(console.error(`Error in '${e}' event handler for template ${s.tmplId}:`,n,t),r.throwError)throw n}};a.addEventListener(e,n),p.element=a,d[e]=n,E&&u&&(s.trigger[E][e]=function(){u(a,e)})})}},element:{pattern:/##%([\s\S]+?)##/g,exec:function(e){const t=e.split("::");return`';\n{\nconst elementId = (__lazyScope.elementArray.length);\n__p+='<template data-co-tmpl-element-id="'+elementId+'"></template>';\n__lazyScope.elementArray[elementId] = {childTarget: ${t[0]}, nonblocking: ${t[1]||!1}};};\n__p+='`},lazyExec:function(e,t,n,i){t.elementArray.forEach(function(e,t){const l=e.childTarget,s=e.nonblocking,c=i.querySelector(`template[data-co-tmpl-element-id="${t}"]`);if(!c)return void(r.debug&&console.warn(`Element insertion placeholder not found for ID ${t} in template ${n.tmplId}`));if(!c.parentNode)return void(r.debug&&console.warn(`Element insertion placeholder for ID ${t} in template ${n.tmplId} has no parent.`));const a=function(){if(c&&c.parentNode)try{if(l instanceof Array){const e=document.createDocumentFragment();l.forEach(function(i){if(!i)return;const l=i.element||i;let s=null;if("string"==typeof l||"number"==typeof l)s=o(l);else if("function"==typeof l)s=o(l());else{if(!(l instanceof Node))return void(r.debug&&console.warn(`Invalid item type in element array for ID ${t}, template ${n.tmplId}:`,l));s=l}if(i.beforeAppendTo)try{i.beforeAppendTo()}catch(e){console.error("Error in beforeAppendTo (array item):",e)}s&&e.appendChild(s)}),c.parentNode.replaceChild(e,c),l.forEach(function(e){e&&e.afterAppendTo&&setTimeout(()=>{try{e.afterAppendTo()}catch(e){console.error("Error in afterAppendTo (array item):",e)}},0)})}else if("string"==typeof l||"number"==typeof l)c.parentNode.replaceChild(o(l),c);else if("function"==typeof l)c.parentNode.replaceChild(o(l()),c);else if(l&&(l.element||l)instanceof Node){const e=l,t=e.element||e;if(e.beforeAppendTo)try{e.beforeAppendTo()}catch(e){console.error("Error in beforeAppendTo:",e)}c.parentNode.replaceChild(t,c),e.afterAppendTo&&setTimeout(()=>{try{e.afterAppendTo&&e.afterAppendTo()}catch(e){console.error("Error in afterAppendTo:",e)}},0),e.tmplId&&(e.parentComponent=n)}else r.debug&&console.warn(`Invalid target for element insertion ID ${t}, template ${n.tmplId}:`,l),c.parentNode.removeChild(c)}catch(e){if(console.error(`Error during element insertion for ID ${t}, template ${n.tmplId}:`,e),r.throwError)throw e;if(c&&c.parentNode)try{c.parentNode.removeChild(c)}catch(e){}}else r.debug&&console.warn(`Placeholder for ID ${t} removed before insertion in template ${n.tmplId}.`)};void 0===s||!1===s?a():setTimeout(a,"number"==typeof s?s:0)})}},lazyEvaluate:{pattern:/###([\s\S]+?)##/g,exec:function(e){return`';\n__lazyScope.lazyEvaluateArray.push(function(data) {${e}});\n__p+='`},lazyExec:function(e,o,i,l){const s=t(l),c=1===n(l)?s:null;o.lazyEvaluateArray.forEach(function(t,n){try{t.call(c||l,e)}catch(e){if(console.error(`Error in lazyEvaluate block ${n} for template ${i.tmplId}:`,e,t),r.throwError)throw e}})}},evaluate:{pattern:/##([\s\S]+?)##/g,exec:e=>"';\n"+e+"\n__p+='"},escapeSyntax:{pattern:/#\\#([\s\S]+?)#\\#/g,exec:function(e){return`'+\n'##${e}##'+\n'`}}},keys:{dataKeyName:"data",statusKeyName:"status",componentKeyName:"component",i18nKeyName:"i18n"}}},l=typeof window,s={isServer:()=>("undefined"===l||globalThis.__SSR_ENVIRONMENT__)&&"undefined"!=typeof globalThis&&void 0!==globalThis.process&&void 0!==globalThis.process.versions&&!!globalThis.process.versions.node,isBrowser:()=>"undefined"!==l&&"undefined"!=typeof document&&!globalThis.__SSR_ENVIRONMENT__,hasDOM:()=>"undefined"!=typeof document&&"function"==typeof document.createElement,isNode:()=>void 0!==globalThis.process&&void 0!==globalThis.process.versions&&!!globalThis.process.versions.node};class c{constructor(){this.elements=new Map,this.styleCollector=[],this.scriptCollector=[]}static getInstance(){return c.instance||(c.instance=new c),c.instance}createElement(e){const t={nodeType:1,tagName:e.toUpperCase(),id:"",className:"",textContent:"",_innerHTML:"",attributes:new Map,children:[],parentNode:null,style:{},dataset:{},firstChild:null,lastChild:null,childElementCount:0,firstElementChild:null,content:null,get childNodes(){return this.children},setAttribute(e,t){this.attributes.set(e,t),"id"===e&&(this.id=t),"class"===e&&(this.className=t)},set innerHTML(e){this._innerHTML=e,this.children=[],e&&this.parseAndCreateChildren(e)},get innerHTML(){return this._innerHTML||""},parseAndCreateChildren(e){const t=/<template[^>]*?id\s*=\s*["']([^"']+)["'][^>]*?>([\s\S]*?)<\/template>/gi,n=/<script[^>]*?type\s*=\s*["']text\/template["'][^>]*?id\s*=\s*["']([^"']+)["'][^>]*?>([\s\S]*?)<\/script>/gi,r=/<script[^>]*?type\s*=\s*["']text\/compomint["'][^>]*?id\s*=\s*["']([^"']+)["'][^>]*?>([\s\S]*?)<\/script>/gi;let o;for(t.lastIndex=0;null!==(o=t.exec(e));){const e=this.createTemplateElement(o[1],o[2]);this.children.push(e),e.parentNode=this}for(n.lastIndex=0;null!==(o=n.exec(e));){const e=this.createScriptElement(o[1],o[2],"text/template");this.children.push(e),e.parentNode=this}for(r.lastIndex=0;null!==(o=r.exec(e));){const e=this.createScriptElement(o[1],o[2],"text/compomint");this.children.push(e),e.parentNode=this}},createTemplateElement(e,t){const n=c.getInstance().createElement("template");n.id=e,n.setAttribute("id",e);const r=t.replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/"/g,'"').replace(/'/g,"'");return n._innerHTML=r,n},createScriptElement(e,t,n){const r=c.getInstance().createElement("script");return r.id=e,r.setAttribute("id",e),r.setAttribute("type",n),r._innerHTML=t,r},getAttribute(e){return this.attributes.get(e)||null},appendChild(e){return this.children.push(e),e.parentNode=this,this.firstChild=this.children[0]||null,this.lastChild=this.children[this.children.length-1]||null,this.childElementCount=this.children.length,this.firstElementChild=this.children[0]||null,e},removeChild(e){const t=this.children.indexOf(e);return t>-1&&(this.children.splice(t,1),e.parentNode=null,this.firstChild=this.children[0]||null,this.lastChild=this.children[this.children.length-1]||null,this.childElementCount=this.children.length,this.firstElementChild=this.children[0]||null),e},normalize(){},querySelector(e){if(e.startsWith("#")){const t=e.substring(1);return this.findById(t)}if(e.startsWith(".")){const t=e.substring(1);return this.findByClass(t)}return this.findByTagName(e)},querySelectorAll(e){const t=[],n=e.split(",").map(e=>e.trim());for(const e of n){this.matches&&this.matches(e)&&(t.includes(this)||t.push(this));for(const n of this.children)if(n.querySelectorAll){const r=n.querySelectorAll(e);for(const e of r)t.includes(e)||t.push(e)}}return t},matches(e){const t=e.trim();if(t.startsWith("#"))return this.id===t.substring(1);if(t.startsWith("."))return this.className.includes(t.substring(1));if(t.includes("[")&&t.includes("]")){const e=t.match(/^(\w+)(?:\[|$)/);if(e){const t=e[1].toLowerCase();if(this.tagName.toLowerCase()!==t)return!1}const n=t.match(/\[([^\]]+)\]/g);if(n)for(const e of n){const t=e.slice(1,-1);if(t.includes("=")){const e=t.split("="),n=e[0].trim(),r=e[1].replace(/['"]/g,"").trim();if(this.getAttribute(n)!==r)return!1}else{const e=t.trim();if(!(null!==this.getAttribute(e)))return!1}}return!0}return this.tagName.toLowerCase()===t.toLowerCase()},findById(e){if(this.id===e)return this;for(const t of this.children){const n=t.findById&&t.findById(e);if(n)return n}return null},findByClass(e){if(this.className.includes(e))return this;for(const t of this.children){const n=t.findByClass&&t.findByClass(e);if(n)return n}return null},findByTagName(e){if(this.tagName===e.toUpperCase())return this;for(const t of this.children){const n=t.findByTagName&&t.findByTagName(e);if(n)return n}return null},toHTML(){if("template"===this.tagName.toLowerCase())return this.innerHTML?this.innerHTML:this.children.map(e=>"string"==typeof e?e:e.toHTML?e.toHTML():"").join("");let e=`<${this.tagName.toLowerCase()}`;for(const[t,n]of this.attributes)e+=` ${t}="${n}"`;if(["img","br","hr","input","meta","link"].includes(this.tagName.toLowerCase()))return e+=" />",e;if(e+=">",this.textContent)e+=this.textContent;else if(this.innerHTML)e+=this.innerHTML;else for(const t of this.children)"string"==typeof t?e+=t:t.toHTML&&(e+=t.toHTML());return e+=`</${this.tagName.toLowerCase()}>`,e}};return"template"===e.toLowerCase()&&(t.content=this.createDocumentFragment(),t.innerHTML,Object.defineProperty(t,"innerHTML",{get:function(){return this._innerHTML||""},set:function(e){if(this._innerHTML=e,this.content.children=[],e){this.parseAndCreateChildren(e);for(const e of this.children)this.content.children.push(e),e.parentNode=this.content;this.content.firstChild=this.content.children[0]||null,this.content.lastChild=this.content.children[this.content.children.length-1]||null,this.content.childElementCount=this.content.children.length,this.content.firstElementChild=this.content.children[0]||null}},configurable:!0,enumerable:!0})),t}createDocumentFragment(){return{nodeType:11,children:[],firstChild:null,lastChild:null,childElementCount:0,firstElementChild:null,get childNodes(){return this.children},appendChild(e){return this.children.push(e),e.parentNode=this,this.firstChild=this.children[0]||null,this.lastChild=this.children[this.children.length-1]||null,this.childElementCount=this.children.length,this.firstElementChild=this.children[0]||null,e},removeChild(e){const t=this.children.indexOf(e);return t>-1&&(this.children.splice(t,1),e.parentNode=null,this.firstChild=this.children[0]||null,this.lastChild=this.children[this.children.length-1]||null,this.childElementCount=this.children.length,this.firstElementChild=this.children[0]||null),e},normalize(){},querySelector(e){for(const t of this.children)if(t.querySelector){const n=t.querySelector(e);if(n)return n}return null},querySelectorAll(e){const t=[],n=e.split(",").map(e=>e.trim());for(const e of n)for(const n of this.children)if(n.querySelectorAll){const r=n.querySelectorAll(e);for(const e of r)t.includes(e)||t.push(e)}return t},toHTML(){return this.children.map(e=>"string"==typeof e?e:e.toHTML?e.toHTML():"").join("")}}}createTextNode(e){return{nodeType:3,textContent:e,toHTML(){return this.textContent}}}createComment(e){return{nodeType:8,textContent:e,toHTML(){return`\x3c!-- ${this.textContent} --\x3e`}}}collectStyle(e){this.styleCollector.push(e)}collectScript(e){this.scriptCollector.push(e)}getCollectedStyles(){return this.styleCollector.join("\n")}getCollectedScripts(){return[...this.scriptCollector]}reset(){this.styleCollector=[],this.scriptCollector=[]}}function a(){if(s.isNode()){globalThis.__SSR_ENVIRONMENT__=!0;const e=function(){const e=c.getInstance();return{createElement:t=>e.createElement(t),createDocumentFragment:()=>e.createDocumentFragment(),createTextNode:t=>e.createTextNode(t),createComment:t=>e.createComment(t),getElementById:e=>null,head:{appendChild:t=>{"STYLE"===t.tagName?e.collectStyle(t.textContent||t.innerHTML):"SCRIPT"===t.tagName&&e.collectScript(t.textContent||t.innerHTML)},removeChild:()=>{},innerHTML:""},body:{appendChild:()=>{},removeChild:()=>{},innerHTML:"",contains:()=>!1},documentElement:{lang:"en",getAttribute:function(e){return"lang"===e?this.lang:null},setAttribute:function(e,t){"lang"===e&&(this.lang=t)}}}}(),t={Node:{prototype:{}},Element:{prototype:{}},CharacterData:{prototype:{}},DocumentType:{prototype:{}},XMLHttpRequest:function(){throw new Error("XMLHttpRequest is not available in SSR environment")}};return globalThis.document=e,globalThis.window=t,void 0!==globalThis.global&&(globalThis.global.document=e,globalThis.global.window=t),globalThis.Element=class{constructor(e){this.tagName="",this.innerHTML="",this.textContent="",this.id="",this.className="",this.children=[],this.parentNode=null,e&&(this.tagName=e.toUpperCase())}},globalThis.Node=class{},globalThis.CharacterData=class{},globalThis.DocumentType=class{},globalThis.XMLHttpRequest=function(){throw new Error("XMLHttpRequest is not available in SSR environment. Use static template rendering instead.")},!0}return!1}class d{constructor(e,t={}){this.renderStartTime=0,this.compomint=e,this.options=Object.assign({renderToString:!0,hydrateOnClient:!1,generateIds:!0,preserveWhitespace:!1,lang:"en"},t),this.polyfill=c.getInstance(),this.setupEnvironment()}setupEnvironment(){s.isServer()&&(a(),this.setupSSROverrides())}setupSSROverrides(){const e=globalThis.document;e&&(e.createElement=e=>this.polyfill.createElement(e))}renderToString(t){return e(this,arguments,void 0,function*(e,t={},n={}){this.renderStartTime=Date.now();const r=Object.assign(Object.assign({},this.options),n);if(this.polyfill.reset(),n.lang){const e=globalThis.document;e&&e.documentElement&&(e.documentElement.lang=n.lang)}try{const n=this.compomint.tmplCache.get(e);if(!n||!n.sourceGenFunc)throw new Error(`Template "${e}" not found or missing sourceGenFunc`);const o=Object.assign(Object.assign({},t),{$ssr:!0,$generateIds:r.generateIds,$hydrateOnClient:r.hydrateOnClient});let i;try{i=n.sourceGenFunc.call(null,o,{},{tmplId:e},this.compomint.i18n,this.compomint,this.compomint.tmpl||{},{},!1)}catch(e){throw e}let l=("string"==typeof i?i:String(i)).trim();l=this.extractStylesAndScripts(l),n.templateText&&this.extractStylesFromTemplateText(n.templateText);const s=this.polyfill.getCollectedStyles(),c=this.polyfill.getCollectedScripts(),a=this.compomint.tools.genId(e),d={templateIds:[e],componentIds:[a],renderTime:Date.now()-this.renderStartTime};return{html:l.replace(/^(<[a-z]+)/,`$1 data-co-id="${a}" data-co-tmpl-id="${e}"`)||"",css:s,scripts:c,metadata:d}}catch(t){throw new Error(`SSR rendering failed for template "${e}": ${t}`)}})}renderMultiple(t){return e(this,arguments,void 0,function*(e,t={}){this.renderStartTime=Date.now(),this.polyfill.reset();const n=[];for(const r of e){const e=yield this.renderToString(r.id,r.data,t);n.push(e)}return{html:n.map(e=>e.html).join("\n"),css:n.map(e=>e.css).filter(Boolean).join("\n"),scripts:n.reduce((e,t)=>e.concat(t.scripts),[]),metadata:{templateIds:n.reduce((e,t)=>e.concat(t.metadata.templateIds),[]),componentIds:n.reduce((e,t)=>e.concat(t.metadata.componentIds),[]),renderTime:Date.now()-this.renderStartTime}}})}renderPage(t){return e(this,arguments,void 0,function*(e,t={},n={}){const r=yield this.renderToString(e,t),{title:o="Compomint SSR Page",meta:i=[],links:l=[],scripts:s=[],bodyClass:c="",lang:a="en"}=n;return`<!DOCTYPE html>\n<html lang="${a}">\n<head>\n <meta charset="UTF-8">\n <meta name="viewport" content="width=device-width, initial-scale=1.0">\n <title>${this.escapeHTML(o)}</title>\n ${i.map(e=>`<meta ${e.name?`name="${this.escapeHTML(e.name)}"`:""}${e.property?`property="${this.escapeHTML(e.property)}"`:""} content="${this.escapeHTML(e.content)}">`).join("\n ")}\n ${l.map(e=>`<link ${Object.keys(e).map(t=>`${t}="${this.escapeHTML(e[t])}"`).join(" ")}>`).join("\n ")}\n ${r.css?`<style>\n${r.css}\n</style>`:""}\n</head>\n<body${c?` class="${this.escapeHTML(c)}"`:""}>\n ${r.html}\n ${s.map(e=>{if(e.src){return`<script ${Object.keys(e).map(t=>`${t}="${this.escapeHTML(e[t])}"`).join(" ")}><\/script>`}return e.content?`<script>${e.content}<\/script>`:""}).join("\n ")}\n ${r.scripts.map(e=>`<script>${e}<\/script>`).join("\n ")}\n ${this.generateHydrationScript(r)}\n</body>\n</html>`})}renderComponentSSR(t,n){return e(this,void 0,void 0,function*(){const e=this.polyfill.createDocumentFragment(),r=t(n,e);return r&&"function"==typeof r.then?yield r:r})}extractHTML(e){if(!e||!e.element)return console.warn("Component or component.element is missing"),"";if("function"==typeof e.element.toHTML)return e.element.toHTML();if(11===e.element.nodeType){const t=e.element.childNodes||[];return Array.from(t).map(e=>"function"==typeof e.toHTML?e.toHTML():e.innerHTML?e.innerHTML:e.textContent?e.textContent:3===e.nodeType&&e.textContent||"").join("")}return e.element.innerHTML?e.element.innerHTML:e.element.textContent?e.element.textContent:""}generateHydrationScript(e){if(!this.options.hydrateOnClient)return"";const t={templateIds:e.metadata.templateIds,componentIds:e.metadata.componentIds,renderTime:e.metadata.renderTime};return`\n<script>\n // Compomint SSR Hydration Data\n window.__COMPOMINT_SSR__ = ${JSON.stringify(t)};\n \n // Hydration helper\n window.__COMPOMINT_HYDRATE__ = function(compomint) {\n console.log('Hydrating Compomint SSR components...', window.__COMPOMINT_SSR__);\n // Additional hydration logic can be added here\n };\n<\/script>`}escapeHTML(e){const t={"&":"&","<":"<",">":">",'"':""","'":"'"};return e.replace(/[&<>"']/g,e=>t[e]||e)}extractStylesAndScripts(e){return(e=e.replace(/<style[^>]*>([\s\S]*?)<\/style>/gi,(e,t)=>(t&&t.trim()&&this.polyfill.collectStyle(t.trim()),""))).replace(/<script[^>]*(?:src\s*=\s*["'][^"']*["'])?[^>]*>([\s\S]*?)<\/script>/gi,(e,t)=>{const n=t.trim();return n&&this.polyfill.collectScript(n),e}),e}extractStylesFromTemplateText(e){const t=e.replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/"/g,'"').replace(/'/g,"'"),n=/<style[^>]*>([\s\S]*?)<\/style>/gi;let r;for(;null!==(r=n.exec(t));){const e=r[1].trim();e&&this.polyfill.collectStyle(e)}}getStats(){return{environment:s.isServer()?"server":"client",polyfillActive:s.isServer(),lastRenderTime:this.renderStartTime?Date.now()-this.renderStartTime:0}}}function p(e,t={}){return new d(e,t)}"function"!=typeof Object.assign&&Object.defineProperty(Object,"assign",{value:function(e,...t){if(null==e)throw new TypeError("Cannot convert undefined or null to object");const n=Object(e);for(let e=0,r=t.length;e<r;e++){const r=t[e];if(null!=r)for(let e in r)Object.prototype.hasOwnProperty.call(r,e)&&(n[e]=r[e])}return n},writable:!0,configurable:!0}),["undefined"!=typeof Element?Element.prototype:{},"undefined"!=typeof CharacterData?CharacterData.prototype:{},"undefined"!=typeof DocumentType?DocumentType.prototype:{}].filter(Boolean).forEach(function(e){e&&!e.hasOwnProperty("remove")&&Object.defineProperty(e,"remove",{configurable:!0,enumerable:!0,writable:!0,value:function(){null!==this.parentNode&&this.parentNode.removeChild(this)}})}),!("undefined"!=typeof window&&window.Node&&"isConnected"in window.Node.prototype)&&"undefined"!=typeof window&&window.Node&&Object.defineProperty(window.Node.prototype,"isConnected",{get:function(){return document.body.contains(this)}});const u={},m={},f=u.tools=u.tools||{},h=u.configs=Object.assign({printExecTime:!1,debug:!1,throwError:!0},u.configs),y=u.tmplCache=u.tmplCache||new Map;y.has("anonymous")||y.set("anonymous",{elements:new Set});const g="undefined"!=typeof document&&"content"in document.createElement("template"),E=/(.)^/,b={"'":"\\'","\\":"\\\\","\r":"\\r","\n":"\\n","\t":"\\t","\u2028":"\u2028","\u2029":"\u2029","><":"><","<":"<",">":">"},T=/\>( |\n)+\<|\>( |\n)+|( |\n)+\<|\\|'|\r|\n|\t|\u2028|\u2029/g;s.isServer()?u.templateEngine=(e=>{const t=i(e),n={rules:{},keys:Object.assign({},t.keys)};return Object.keys(t.rules).forEach(e=>{"evaluate"===e&&(n.rules.element={pattern:/##%([\s\S]+?)##/g,exec:function(e){return"';\n__p+='\x3c!-- SSR: Element insertion not supported --\x3e';\n__p+='"}}),"style"!==e&&"element"!==e&&(n.rules[e]=Object.assign({},t.rules[e]))}),n.rules.element||(n.rules.element={pattern:/##%([\s\S]+?)##/g,exec:function(e){return"';\n__p+='\x3c!-- SSR: Element insertion not supported --\x3e';\n__p+='"}}),n})(u):u.templateEngine=i(u);const S=function(){const e={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`"},t=Object.keys(e).reduce((t,n)=>(t[e[n]]=n,t),{}),n=function(e){const t=function(t){return e[t]},n=`(?:${Object.keys(e).join("|").replace(/\\/g,"\\\\")})`,r=RegExp(n),o=RegExp(n,"g");return function(e){return e=null==e?"":`${e}`,r.test(e)?e.replace(o,t):e}};return{escape:n(e),unescape:n(t)}}();f.escapeHtml=S;const v=function(e){const t=[],n=[],r={},o={};return Object.keys(e).forEach(function(i){const l=e[i];if(l&&"object"==typeof l&&l.pattern instanceof RegExp&&"function"==typeof l.exec&&(t.push((l.pattern||E).source),n.push(l.exec)),l&&"object"==typeof l&&"function"==typeof l.lazyExec){const e=`${i}Array`;r[e]=l.lazyExec,o[e]=[]}}),{templateRules:e,pattern:new RegExp(t.join("|"),"g"),exec:n,lazyExecKeys:Object.keys(o),lazyExec:r,lazyScopeSeed:JSON.stringify(o)}},$=function(e){return b[e]||b[e.replace(/[ \n]/g,"")]||""},C=v(u.templateEngine.rules),_=u.template=function(e,o,i){let l=u.templateEngine,a=C;i&&(l={rules:Object.assign({},l.rules,i.rules||{}),keys:Object.assign({},l.keys,i.keys||{})},a=v(l.rules));const d=`\n/* tmplId: ${e} */\n//# sourceURL=http://tmpl//${e.split("-").join("//")}.js\n// if (__debugger) {\n// debugger;\n// }\nlet __p='';\n__p+='${function(e,t,n){h.printExecTime&&console.time(`tmpl: ${e}`);let r=0,o="";return t.replace(n.pattern,function(...i){const l=i[0],s=i[i.length-2];let c;o+=t.slice(r,s).replace(T,$);let a=null;if(i.slice(1,-2).some(function(e,t){return void 0!==e&&(c=e,a=t,!0)}),void 0!==c&&null!==a)try{o+=n.exec[a].call(n.templateRules,c,e)}catch(t){if(console.error(`Error executing template rule index ${a} for match "${c}" in template "${e}":`,t),h.throwError)throw t;o+=""}else o+=l.replace(T,$);return r=s+l.length,l}),o+=t.slice(r).replace(T,$),h.printExecTime&&console.timeEnd(`tmpl: ${e}`),o}(e,o,a)}';\nreturn __p;`;let p=null;try{p=new Function(l.keys.dataKeyName,l.keys.statusKeyName,l.keys.componentKeyName,l.keys.i18nKeyName,"compomint","tmpl","__lazyScope","__debugger",d)}catch(t){if(h.throwError){console.error(`Template compilation error in "${e}", ${t.name}: ${t.message}`);try{new Function(l.keys.dataKeyName,l.keys.statusKeyName,l.keys.componentKeyName,l.keys.i18nKeyName,"compomint","tmpl","__lazyScope","__debugger",d)}catch(e){}throw t}return()=>({})}const g=function(...o){let i,d,y,g,E;const b=o[0];b&&"object"==typeof b&&(b.$wrapperElement||b.$callback||b.$baseComponent||b.$existingElement)?(i=Object.assign({},b),d=i.$wrapperElement,delete i.$wrapperElement,y=i.$callback,delete i.$callback,g=i.$baseComponent,delete i.$baseComponent,E=i.$existingElement,delete i.$existingElement):(i=b,"function"==typeof o[1]?(d=void 0,y=o[1],g=o[2]):(d=o[1],y=o[2],g=o[3]));const T=l.keys.dataKeyName,S=l.keys.statusKeyName,v=JSON.parse(a.lazyScopeSeed),$=Object.assign(g||{},{tmplId:e,element:null,status:g&&g.status||{},replace:function(t){const n=this;n.element&&n.element instanceof Node&&n.element.parentElement?n.element.parentElement.replaceChild(t.element||t,n.element):h.debug&&console.warn(`Cannot replace template "${e}": element not in DOM.`)},remove:function(t=!1){const n=this;if(n.beforeRemove)try{n.beforeRemove()}catch(e){console.error("Error in beforeRemove:",e)}v.eventArray&&v.eventArray.forEach(function(e){e.forEach(function(e){e.element&&("function"==typeof e.eventFunc?e.element.removeEventListener("click",e.eventFunc):Object.keys(e.eventFunc).forEach(function(t){e.element.removeEventListener(t,e.eventFunc[t])}),Object.keys(e).forEach(t=>delete e[t]))})});const r=n.element instanceof Node?n.element.parentElement:null,o=n.element;if(r)if(t){const e=document.createElement("template");r.replaceChild(e,n.element),n.element=e}else r.removeChild(n.element);else h.debug&&console.warn(`Cannot remove template "${e}": element not in DOM.`);if(n.afterRemove)try{n.afterRemove()}catch(e){console.error("Error in afterRemove:",e)}return o},appendTo:function(t){const n=this;if(n.beforeAppendTo)try{n.beforeAppendTo()}catch(e){console.error("Error in beforeAppendTo:",e)}return t&&n.element instanceof Node?t.appendChild(n.element):h.debug&&console.warn(`Cannot append template "${e}": parentElement or scope.element is missing or not a Node.`),n.afterAppendTo&&setTimeout(()=>{try{n.afterAppendTo()}catch(e){console.error("Error in afterAppendTo:",e)}},0),n},release:function(){},render:function(e){return this},refresh:function(e){return this},reflash:function(e){return this}});$._id||($._id=f.genId(e)),$[T]=i,null==$[S]&&($[S]={});const C=d instanceof Element,_=document.createElement("template");h.printExecTime&&console.time(`render: ${e}`);let w=null,N=null;try{N=i?p.call(d||null,i,$[S],$,u.i18n[e],u,m,v,h.debug):`<template data-co-empty-template="${e}"></template>`}catch(t){if(h.throwError){console.error(`Runtime error during render of "${e}":`,t.message),console.debug("--- Data ---",i,"------------");try{p.call(d||null,i,$[S],$,u.i18n[e],v,!0)}catch(e){}throw t}return console.warn(`Render failed for "${e}". Returning scope with comment node.`),$.element=document.createComment(`Render Error: ${e}`),$}h.printExecTime&&console.timeEnd(`render: ${e}`),_.innerHTML=N;let A=_.content||_;if("TEMPLATE"==A.tagName&&!_.content){const e=Array.from(A.childNodes);A=document.createDocumentFragment(),e.forEach(e=>A.appendChild(e))}if(C&&d){for(;d.firstChild;)d.removeChild(d.firstChild);$.wrapperElement=d}if((A.querySelector?A.querySelector("style"):null)&&A.querySelector)if(s.isServer()){A.querySelectorAll("style").forEach(e=>{const t=e.textContent||e.innerHTML;if(t&&globalThis.document&&globalThis.document.head){c.getInstance().collectStyle(t),e.remove()}})}else{const t=document.createElement(e);try{const e=t.attachShadow({mode:"open"});for(;A.firstChild;)e.appendChild(A.firstChild);A=t}catch(t){console.error(`Failed to attach shadow DOM for template "${e}":`,t)}}if(A.firstChild&&8==A.firstChild.nodeType)w=A.firstChild;else if(1==n(A)){if(w=t(A),C&&d&&w){if($.beforeAppendTo)try{$.beforeAppendTo()}catch(e){console.error("Error in beforeAppendTo:",e)}d.appendChild(w),$.afterAppendTo&&setTimeout(()=>{try{$.afterAppendTo()}catch(e){console.error("Error in afterAppendTo:",e)}},0)}}else if(C&&d){if($.beforeAppendTo)try{$.beforeAppendTo()}catch(e){console.error("Error in beforeAppendTo:",e)}d.appendChild(A),$.afterAppendTo&&setTimeout(()=>{try{$.afterAppendTo()}catch(e){console.error("Error in afterAppendTo:",e)}},0),w=d}else w=A;if(i&&i.$props&&w instanceof Element)for(const t in i.$props)try{const e=i.$props[t];if(t.startsWith("data-")){const n=t.substring(5).replace(/-([a-z])/g,e=>e[1].toUpperCase());w.dataset[n]=String(e)}else t in w?w[t]=e:w.setAttribute(t,String(e))}catch(n){console.error(`Error applying prop "${t}" to element in template "${e}":`,n)}w instanceof Node&&w.normalize&&w.normalize(),w instanceof Node&&r(w),$.element=E||w;const x=a.lazyExec;if(i&&a.lazyExecKeys.forEach(function(t){if(v[t]&&v[t].length>0)try{x[t].call(l.rules[t.slice(0,-5)],i,v,$,A)}catch(n){if(h.throwError)throw console.error(`Error during lazy execution of "${t}" for template "${e}":`,n),n}}),f.liveReloadSupport)try{f.liveReloadSupport($)}catch(e){console.error("Error in liveReloadSupport:",e)}if(y)try{y.call(d||null,$)}catch(t){if(console.error(`Error in template callback for "${e}":`,t),h.throwError)throw t}return $.release=function(){const e=this,t=Object.getOwnPropertyNames(e),n=[S,"_id"];for(let r=0;r<t.length;r++){const o=t[r];"function"==typeof e[o]||n.includes(o)||delete e[o]}},$.render=function(e){const t=this,n=t.element,r=n instanceof Node?n.parentElement:null,o=t.wrapperElement,i=u.tmpl(t.tmplId);if(!i)return console.error(`Cannot re-render: Template function for "${t.tmplId}" not found.`),t;const l={beforeAppendTo:t.beforeAppendTo,afterAppendTo:t.afterAppendTo,beforeRemove:t.beforeRemove,afterRemove:t.afterRemove,beforeRefresh:t.beforeRefresh,afterRefresh:t.afterRefresh};if(t.beforeRemove)try{t.beforeRemove()}catch(e){console.error("Error in beforeRemove during render:",e)}let s;if(o)s=i(e,o,void 0,t);else if(r&&n instanceof Node)if(s=i(e,void 0,void 0,t),s.element instanceof Node){if(s.beforeAppendTo)try{s.beforeAppendTo()}catch(e){console.error("Error in beforeAppendTo during render:",e)}r.replaceChild(s.element,n),s.afterAppendTo&&setTimeout(()=>{try{s.afterAppendTo()}catch(e){console.error("Error in afterAppendTo during render:",e)}},0)}else h.debug&&console.warn(`Re-render of "${t.tmplId}" resulted in no element or target was missing.`);else s=i(e,void 0,void 0,t);if(t.afterRemove)try{t.afterRemove()}catch(e){console.error("Error in afterRemove during render:",e)}return Object.assign(s,l),s},$.refresh=function(e){const t=this,n=t[T];if(t.beforeRefresh)try{t.beforeRefresh()}catch(e){console.error("Error in beforeRefresh:",e)}const r=Object.assign({},n||{},e),o=t.render(r);if(t.afterRefresh)try{t.afterRefresh()}catch(e){console.error("Error in afterRefresh:",e)}return o},$.reflash=$.refresh,$};if(Object.defineProperty(g,"name",{value:`render_${e}`,writable:!1}),e){const t=h.debug?{renderingFunc:g,sourceGenFunc:p,source:S.escape(`function ${e}_source (${l.keys.dataKeyName}, ${l.keys.statusKeyName}, ${l.keys.componentKeyName}, ${l.keys.i18nKeyName}, __lazyScope, __debugger) {\n${d}\n}`),templateText:S.escape(o)}:{renderingFunc:g,sourceGenFunc:p};y.set(e,t);const n=e.split("-");if(n.length>1){const e=n[0];let r=m[e];r||(m[e]=r={});r[n.slice(1).map((e,t)=>0===t?e:e.charAt(0).toUpperCase()+e.slice(1)).join("")]=t.renderingFunc}}return g};u.remapTmpl=function(e){Object.keys(e).forEach(function(t){const n=e[t],r=y.get(t);r?(y.set(n,r),h.debug&&console.log(`Remapped template "${t}" to "${n}"`)):h.debug&&console.warn(`Cannot remap template: Old key "${t}" not found in cache.`)})},u.tmpl=function(e){const t=y.get(e);return t?t.renderingFunc:null};const w=function(e){let t;if(void 0!==e&&e instanceof Element)return e.tagName,e;if("string"!=typeof e&&(h.debug&&console.warn("safeTemplate received non-string/non-element source:",e),e=""),t=document.createElement("template"),g){const n=e.replace(/<(?!template|\/template|body|\/body|html|\/html|head|\/head|style|\/style|script|\/script|link|\/link|meta|\/meta|!--)/gi,"<");t.innerHTML=n}else{const n=e.replace(/<(?!template|\/template|body|\/body|html|\/html|head|\/head|style|\/style|script|\/script|link|\/link|meta|\/meta|!--)/gi,"<").replace(/<template/g,'<script type="template"').replace(/<\/template>/g,"<\/script>");t.innerHTML=n}return t},N=u.addTmpl=function(e,t,n){let r;return r=void 0!==t&&t&&"object"==typeof t?"_innerHTML"in t?t._innerHTML:"innerHTML"in t?t.innerHTML:String(t):String(t),r=S.unescape(r.replace(/<!---|--->/gi,"")),_(e,r,n)},A=u.addTmpls=function(e,t,n){"boolean"!=typeof t&&null==n?(n=t,t=!1):t=!!t,n||(n=u.templateEngine);const r=w(e);return(r.content||r).querySelectorAll('template[id], script[type="text/template"][id], script[type="text/compomint"][id]').forEach(e=>{const r=e.id;r&&(void 0!==e.dataset.coLoadScript?N(r,e,n)({}):N(r,e,n),t&&e.parentNode&&e.parentNode.removeChild(e))}),r};u.addTmplByUrl=function(e,t,n){n||"function"!=typeof t||(n=t,t={});const r={loadScript:!0,loadStyle:!0,loadLink:!0,templateEngine:void 0},o=Object.assign({},r,t),i=e=>{e.forEach(e=>{var t;if(e){if(e.id){const n=document.getElementById(e.id);n&&(null===(t=n.parentNode)||void 0===t||t.removeChild(n))}"SCRIPT"===e.tagName||"LINK"===e.tagName||"STYLE"===e.tagName?document.head.appendChild(e):document.body.appendChild(e)}})},l=e=>new Promise((t,n)=>{const r="string"==typeof(l=e)?{url:l,option:o}:l&&"object"==typeof l&&l.url?{url:l.url,option:Object.assign({},o,l.option)}:(console.error("Invalid import data format in addTmplByUrl:",l),null);var l;if(!r)return void t();const s=r.url,c=r.option;if(s.endsWith(".js")){const e=M("script",{async:!0,src:s});e.addEventListener("load",()=>t()),e.addEventListener("error",()=>{console.error(`Failed to load script: ${s}`),n(new Error(`Failed to load script: ${s}`))}),document.head.appendChild(e)}else if(s.endsWith(".css")){const e=M("link",{type:"text/css",rel:"stylesheet",href:s});e.addEventListener("load",()=>t()),e.addEventListener("error",()=>{console.error(`Failed to load stylesheet: ${s}`),n(new Error(`Failed to load stylesheet: ${s}`))}),document.head.appendChild(e)}else x(s,null,(e,r)=>{if(200===r||0===r)try{((e,t)=>{const n=w(e);A(n,!1,t.templateEngine);const r=n.content||n;if(t.loadLink){const e=r.querySelectorAll('link[rel="stylesheet"]');i(e)}if(t.loadStyle){const e=r.querySelectorAll("style[id]");i(e)}if(t.loadScript){const e=r.querySelectorAll('script:not([type]), script[type="text/javascript"], script[type="module"]'),t=Array.from(e).filter(e=>{let t=e.parentNode;for(;t;){if("TEMPLATE"===t.nodeName||"SCRIPT"===t.nodeName&&t.type.includes("template"))return!1;t=t.parentNode}return!0}).map(e=>{const t=document.createElement("script");return e.getAttributeNames().forEach(n=>t.setAttribute(n,e.getAttribute(n))),e.innerHTML&&(t.textContent=e.innerHTML),t});i(t)}})(e,c),t()}catch(e){console.error(`Error processing imported HTML from ${s}:`,e),n(new Error(`Error processing imported HTML from ${s}: ${e}`))}else console.error(`Failed to fetch template file: ${s} (Status: ${r})`),n(new Error(`Failed to fetch template file: ${s} (Status: ${r})`))})});if(null==e)return n?void n():Promise.resolve();const s=Array.isArray(e)?0===e.length?Promise.resolve():Promise.all(e.map(l)).then(()=>{}).catch(e=>{throw console.error("Error loading resources in addTmplByUrl:",e),e}):l(e).catch(e=>{throw console.error("Error loading resource in addTmplByUrl:",e),e});return n?void s.then(()=>n()).catch(e=>{console.error("Error in addTmplByUrl callback mode:",e),n()}):s};const x=function(e,t,n){const r=new XMLHttpRequest;r.onreadystatechange=function(){r.readyState==XMLHttpRequest.DONE&&(200==r.status||0===r.status?n(r.responseText,r.status,r):(404==r.status?console.error(`Error 404: Not Found - ${e}`):r.status>=400?console.error(`HTTP Error ${r.status} for ${e}`):console.error(`Request failed for ${e}`,r.statusText),n(null,r.status,r)))},r.onerror=function(){console.error(`Network error requesting ${e}`),n(null,0,r)},r.ontimeout=function(){console.error(`Request timed out for ${e}`),n(null,408,r)};try{const n=t&&t.method||"GET";if(r.open(n,e,!0),t){t.timeout&&(r.timeout=t.timeout);const e=t.headers;e&&Object.keys(e).forEach(t=>{r.setRequestHeader(t,e[t])}),r.send(t.body||null)}else r.send()}catch(t){console.error(`Error sending request to ${e}:`,t),n(null,0,r)}};u.i18n={},u.addI18n=function(e,t){if(!e||"string"!=typeof e||!t||"object"!=typeof t)return void console.error("Invalid arguments for addI18n:",e,t);const n=e.split(".");let r=u.i18n;const o=n.length-1;n.forEach(function(n,i){if(n)if(o===i){Object.keys(t).some(e=>Array.isArray(t[e]))?(r[n]||(r[n]=[]),Object.keys(t).filter(e=>Array.isArray(t[e])).forEach(o=>{t[o].forEach((t,o)=>{r[n][o]||(r[n][o]={}),t instanceof Object&&!Array.isArray(t)&&Object.keys(t).forEach(n=>{u.addI18n(e+"."+o+"."+n,t[n])})})})):(r[n]||(r[n]=function(n){const r=document.documentElement.lang||"en";let o=t[r];return null==o&&(o=n,h.debug&&console.warn(`i18n: Label key ["${e}"] for lang "${r}" is missing. Using default: "${n}"`)),null!=o?String(o):""}),Object.keys(t).filter(e=>t[e]instanceof Object&&!Array.isArray(t[e])).forEach(n=>{u.addI18n(e+"."+n,t[n])}))}else r[n]&&"function"!=typeof r[n]||(r[n]={}),r=r[n]})},u.addI18ns=function(e){const t=new Map;function n(e){if(t.has(e))return t.get(e);const n=e.split(".");let r=u.i18n;for(let e=0;e<n.length-1;e++)r[n[e]]||(r[n[e]]={}),r=r[n[e]];return t.set(e,r),r}function r(e){for(const t in e){const n=typeof e[t];if("string"!==n&&"number"!==n&&"boolean"!==n)return!1}return!0}!function e(t,o=""){for(const i in t){const l=t[i],s=o?o+"."+i:i;if(Array.isArray(l)){const e=n(s),t=s.split(".").pop();e[t]||(e[t]=[]);for(let n=0;n<l.length;n++){const r=l[n];if(e[t][n]||(e[t][n]={}),r&&"object"==typeof r)for(const e in r){const t=r[e];if(t&&"object"==typeof t){const r=s+"."+n+"."+e;u.addI18n(r,t)}}}}else l&&"object"==typeof l?r(l)?u.addI18n(s,l):e(l,s):u.addI18n(s,l)}}(e)};let I=0;f.genId=function(e){return I++,e+I};const L=f.applyElementProps=function(e,t){return Object.keys(t).forEach(function(n){const r=t[n],o="class"===n?"className":n;try{"style"===n&&"object"==typeof r&&null!==r?Object.assign(e.style,r):"dataset"===n&&"object"==typeof r&&null!==r?Object.assign(e.dataset,r):n.startsWith("on")&&"function"==typeof r?e[n.toLowerCase()]=r:o in e?e[o]=r:e.setAttribute(n,String(r))}catch(t){console.error(`Error setting attribute/property "${n}" on <${e.tagName}>:`,t)}}),e},M=f.genElement=function(e,t={},...n){const r=document.createElement(e);let o={};return"string"==typeof t||t instanceof Node?n.unshift(t):Array.isArray(t)?n=t.concat(n):o=t,L(r,o),n.forEach(e=>{"string"==typeof e?r.appendChild(document.createTextNode(e)):e instanceof Node&&r.appendChild(e)}),r};f.props=function(...e){if(!e||0===e.length)return"";const t=Object.assign({},...e),n=[];return Object.keys(t).forEach(function(e){const r=t[e];if(r||0===r){const t=String(r).replace(/"/g,""");n.push(`${e}="${t}"`)}}),n.join(" ")},u.ssr={isSupported:s.isServer,setupEnvironment:a,createRenderer:(e={})=>p(u,e),renderToString:(t,...n)=>e(void 0,[t,...n],void 0,function*(e,t={},n={}){const r=p(u,n);return(yield r.renderToString(e,t,n)).html}),renderPage:(t,...n)=>e(void 0,[t,...n],void 0,function*(e,t={},n={}){const r=p(u);return yield r.renderPage(e,t,n)})},s.isServer()&&a(),u.hydrate=function(){if(s.isServer())return void console.warn("Hydration cannot be run on the server.");const e=window.__COMPOMINT_SSR__;if(!e)return void(h.debug&&console.log("No SSR data found for hydration."));h.debug&&console.log("Starting Compomint hydration...",e);const{componentIds:t,initialStates:n}=e;t.forEach(e=>{var t;const r=document.querySelector(`[data-co-id="${e}"]`);if(!r)return void(h.debug&&console.warn(`Element for component ID "${e}" not found for hydration.`));const o=r.dataset.coTmplId||e.split("_")[0],i=u.tmpl(o);if(i){const l=n?n[e]:{},s=l?l.data:{};!l||l.status;const c=i(Object.assign(Object.assign(Object.assign({},l.data),s),{$baseComponent:{status:l.status,_id:e}})),a=c.element;a.dataset.coId=e,a.dataset.coTmplId=o,a.__compomint_scope__=c,null===(t=r.parentElement)||void 0===t||t.replaceChild(a,r),h.debug&&console.log(`Hydrated component "${e}" from template "${o}".`)}else h.debug&&console.warn(`Template function for "${o}" not found during hydration.`)}),delete window.__COMPOMINT_SSR__},(e=>{e("co-Ele","<##=data[0]##></##=data[0]##>###compomint.tools.applyElementProps(this, data[1]);##"),e("co-Element","##\n data.tag = data.tag || 'div';\n ##\n <##=data.tag##\n ##=data.id ? 'id=\"' + (data.id === true ? component._id : data.id) + '\"' : ''##\n data-co-props=\"##:data.props##\"\n data-co-event=\"##:data.event##\">\n ##if (typeof data.content === \"string\") {##\n ##=data.content##\n ##} else {##\n ##%data.content##\n ##}##\n </##=data.tag##>")})(N);export{u as compomint,m as tmpl};
//# sourceMappingURL=compomint.esm.min.js.map