ladrillosjs 2.0.0-beta.4.2 → 2.0.0-beta.4.4
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/core/componentParser.d.ts +9 -2
- package/dist/index-6X7blelu.js +74 -0
- package/dist/index-6X7blelu.js.map +1 -0
- package/dist/index-DE-ur4y8.mjs +758 -0
- package/dist/index-DE-ur4y8.mjs.map +1 -0
- package/dist/index.d.ts +0 -94
- package/dist/ladrillosjs.cjs.js +1 -1
- package/dist/ladrillosjs.es.js +10 -14
- package/dist/ladrillosjs.umd.js +32 -26
- package/dist/ladrillosjs.umd.js.map +1 -1
- package/dist/utils/regex.d.ts +18 -0
- package/dist/{webcomponent-BbbpAvoT.js → webcomponent-BvS1JL3O.js} +2 -2
- package/dist/webcomponent-BvS1JL3O.js.map +1 -0
- package/dist/{webcomponent-Dt-f2pQx.mjs → webcomponent-DawPaCV3.mjs} +4 -4
- package/dist/webcomponent-DawPaCV3.mjs.map +1 -0
- package/package.json +1 -1
- package/dist/index-BcPgsuUl.mjs +0 -714
- package/dist/index-BcPgsuUl.mjs.map +0 -1
- package/dist/index-FW6ZH_yR.js +0 -68
- package/dist/index-FW6ZH_yR.js.map +0 -1
- package/dist/webcomponent-BbbpAvoT.js.map +0 -1
- package/dist/webcomponent-Dt-f2pQx.mjs.map +0 -1
|
@@ -3,9 +3,10 @@ import { ExternalScriptElement, LadrillosComponent, ScriptElement } from "../typ
|
|
|
3
3
|
* Parses component HTML and extracts scripts and styles
|
|
4
4
|
* @param source - The HTML source of the component
|
|
5
5
|
* @param name - The name of the component
|
|
6
|
+
* @param componentUrl - The URL/path of the component file (used for resolving relative CSS paths)
|
|
6
7
|
* @returns Parsed component object
|
|
7
8
|
*/
|
|
8
|
-
export declare const parseComponent: (source: string, name: string) => Promise<LadrillosComponent>;
|
|
9
|
+
export declare const parseComponent: (source: string, name: string, componentUrl?: string) => Promise<LadrillosComponent>;
|
|
9
10
|
/**
|
|
10
11
|
* Parses HTML content and removes comments
|
|
11
12
|
* @param source - The HTML source to parse
|
|
@@ -24,6 +25,12 @@ export declare const extractScripts: (doc: Document) => {
|
|
|
24
25
|
/**
|
|
25
26
|
* Extracts and processes style elements from the document
|
|
26
27
|
* @param doc - The parsed document
|
|
28
|
+
* @param componentUrl - The component file URL/path (used for resolving relative CSS paths)
|
|
27
29
|
* @returns Concatenated CSS content
|
|
30
|
+
*
|
|
31
|
+
* CSS path resolution rules:
|
|
32
|
+
* - ./style.css or ../style.css → resolved relative to component location
|
|
33
|
+
* - style.css or /style.css → resolved from /public folder
|
|
34
|
+
* - http://... or https://... → used as-is (absolute URLs)
|
|
28
35
|
*/
|
|
29
|
-
export declare const extractStyles: (doc: Document) => Promise<string>;
|
|
36
|
+
export declare const extractStyles: (doc: Document, componentUrl?: string) => Promise<string>;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"use strict";var X=Object.defineProperty,Q=Object.defineProperties;var V=Object.getOwnPropertyDescriptors;var k=Object.getOwnPropertySymbols;var Y=Object.prototype.hasOwnProperty,Z=Object.prototype.propertyIsEnumerable;var z=r=>{throw TypeError(r)};var L=(r,e,t)=>e in r?X(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,f=(r,e)=>{for(var t in e||(e={}))Y.call(e,t)&&L(r,t,e[t]);if(k)for(var t of k(e))Z.call(e,t)&&L(r,t,e[t]);return r},w=(r,e)=>Q(r,V(e));var U=(r,e,t)=>e.has(r)||z("Cannot "+t);var j=(r,e,t)=>e.has(r)?z("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t);var $=(r,e,t)=>(U(r,e,"access private method"),t);var p=(r,e,t)=>new Promise((s,o)=>{var n=c=>{try{l(t.next(c))}catch(d){o(d)}},a=c=>{try{l(t.throw(c))}catch(d){o(d)}},l=c=>c.done?s(c.value):Promise.resolve(c.value).then(n,a);l((t=t.apply(r,e)).next())});const x=()=>{try{return!1}catch(r){return process.env.NODE_ENV==="development"}},i={log(r,...e){x()&&console.log(r,...e)},error(r,...e){console.error(r,...e)},warn(r,...e){x()&&console.warn(r,...e)}},h=(r,e)=>{const t=[r];return e&&(e.componentName&&t.push(`
|
|
2
|
+
Component: <${e.componentName}>`),e.componentPath&&t.push(`
|
|
3
|
+
File: ${e.componentPath}`),e.expression&&t.push(`
|
|
4
|
+
Expression: ${e.expression}`),e.attributeName&&t.push(`
|
|
5
|
+
Attribute: ${e.attributeName}`),e.eventType&&t.push(`
|
|
6
|
+
Event: ${e.eventType}`),e.elementTag&&t.push(`
|
|
7
|
+
Element: <${e.elementTag}>`),e.lineHint&&t.push(`
|
|
8
|
+
Location: ${e.lineHint}`)),t.join("")},ee=(r,e,t)=>{const s=h("⚠️ Binding Error: Failed to evaluate expression",w(f({},t),{expression:r,lineHint:(t==null?void 0:t.lineHint)||"Template binding expression"}));i.error(s),i.error(` Error details: ${e.message}`),e.stack&&console.debug(" Stack trace:",e.stack)},te=(r,e,t,s)=>{const o=h("⚠️ Event Handler Error: Failed to execute handler",w(f({},s),{eventType:r,expression:e,lineHint:(s==null?void 0:s.lineHint)||`on${r} handler`}));i.error(o),i.error(` Error details: ${t.message}`),t.stack&&console.debug(" Stack trace:",t.stack)},re=(r,e,t)=>{const s=h("⚠️ Conditional Error: Failed to evaluate condition",w(f({},t),{expression:r,lineHint:(t==null?void 0:t.lineHint)||"$if/$else-if condition"}));i.error(s),i.error(` Error details: ${e.message}`),e.stack&&console.debug(" Stack trace:",e.stack)},se=(r,e,t)=>{const s=h("⚠️ Loop Error: Failed to process loop",w(f({},t),{expression:r,lineHint:(t==null?void 0:t.lineHint)||"$for loop expression"}));i.error(s),i.error(` Error details: ${e.message}`),e.stack&&console.debug(" Stack trace:",e.stack)},T=(r,e,t)=>{const s=h("⚠️ Registration Error: Failed to register component",{componentName:r,componentPath:e});i.error(s),i.error(` Error details: ${t.message}`),t.stack&&console.debug(" Stack trace:",t.stack)},H=(r,e,t)=>{const s=h("⚠️ Fetch Error: Failed to load resource",w(f({},t),{componentPath:r}));i.error(s),i.error(` Error details: ${e.message}`)},b=(r,e)=>{const t=h(`⚠️ Parse Error: ${r}`,e);i.error(t)},oe=(r,e)=>{const t=h("⚠️ Script Error: Failed to execute component script",e);i.error(t),i.error(` Error details: ${r.message}`),r.stack&&console.debug(" Stack trace:",r.stack)},ne=(r,e,t)=>{const s=h("⚠️ Two-Way Binding Error: Failed to setup binding",w(f({},t),{expression:r,lineHint:(t==null?void 0:t.lineHint)||"$model binding"}));i.error(s),i.error(` Error details: ${e.message}`)},ie=(r,e)=>{var t;return f({componentName:(r==null?void 0:r.tagName)||((t=r==null?void 0:r.constructor)==null?void 0:t.name),componentPath:(r==null?void 0:r.sourcePath)||(r==null?void 0:r._sourcePath)},e)},m=new Map,le=25,ae=r=>{const e=m.get(r);return e&&(m.delete(r),m.set(r,e)),e},ce=(r,e)=>{if(m.has(r))m.delete(r);else if(m.size>=le){const t=m.keys().next().value;t&&m.delete(t)}m.set(r,e)},F=r=>p(null,null,function*(){if(!r)throw new Error("Path cannot be null or empty");const e=ae(r);if(e)return e;try{const t=yield fetch(r);if(!t.ok)throw new Error(`Failed to fetch component from ${r}: ${t.statusText}`);const s=yield t.text();return ce(r,s),s}catch(t){H(r,t,{componentPath:r})}}),de=r=>p(null,null,function*(){try{const e=yield fetch(r);if(!e.ok)throw new Error(`HTTP ${e.status}`);return yield e.text()}catch(e){return H(r,e),""}}),P={bindings:/{([^}]+)}/g,comments:{css:/\/\*[\s\S]*?\*\//g,html:/<!--[\s\S]*?-->/g}},pe=r=>{let e="",t=0;for(;t<r.length;){const s=r[t];if(s==='"'||s==="'"||s==="`"){const o=s;for(e+=s,t++;t<r.length;){const n=r[t];if(n==="\\")e+=n+r[t+1],t+=2;else if(n===o){e+=n,t++;break}else e+=n,t++}}else if(s==="/"&&t+1<r.length){const o=r[t+1];if(o==="/"){for(;t<r.length&&r[t]!==`
|
|
9
|
+
`;)t++;t<r.length&&r[t]===`
|
|
10
|
+
`&&(e+=`
|
|
11
|
+
`,t++)}else if(o==="*")for(t+=2;t+1<r.length;){if(r[t]==="*"&&r[t+1]==="/"){t+=2;break}r[t]===`
|
|
12
|
+
`&&(e+=`
|
|
13
|
+
`),t++}else e+=s,t++}else if(/\s/.test(s)){const o=e.trimEnd();if((o===""||o.endsWith(`
|
|
14
|
+
`)||o.endsWith(";")||o.endsWith("}"))&&r.substring(t).match(/^\s*export\s+/)){t=t+r.substring(t).match(/^\s*export\s+/)[0].length;continue}e+=s,t++}else e+=s,t++}return e},ue=new DOMParser,N=(r,e,t)=>p(null,null,function*(){const s=ge(r),{scripts:o,externalScripts:n}=he(s),a=yield ye(s,t),l=s.body.innerHTML.trim();return{tagName:e,template:l,scripts:o,externalScripts:n,styles:a}}),ge=r=>ue.parseFromString(r.replace(P.comments.html,""),"text/html"),me=r=>["/@vite/","/__vite","/webpack-dev-server","/hot-update","/__webpack_hmr","/browser-sync/","/livereload.js"].some(t=>r.includes(t)),he=r=>{var s,o;const e=[],t=[];for(const n of r.querySelectorAll("script")){if(n.src){if(me(n.src)){n.remove();continue}const a=n.hasAttribute("external");t.push({src:n.getAttribute("src")||n.src,type:(s=n.type)!=null?s:null,external:a})}else if(n.textContent){let a=n.textContent.trim();a=pe(a).trim(),e.push({content:a,type:(o=n.type)!=null?o:null})}n.remove()}return{scripts:e,externalScripts:t}},fe=(r,e)=>{if(r.startsWith("http://")||r.startsWith("https://"))return r;if(r.startsWith("./")||r.startsWith("../")){if(e)try{const t=e.endsWith("/")?e:e.substring(0,e.lastIndexOf("/")+1);return new URL(r,t).href}catch(t){return i.warn(`Failed to resolve relative CSS path "${r}" from component "${e}"`),r}return r}return r.startsWith("/")?r:"/"+r},we=r=>{const e=r.match(/const __vite__css = "((?:[^"\\]|\\.)*)"/);if(e&&e[1])return e[1].replace(/\\r\\n/g,`
|
|
15
|
+
`).replace(/\\n/g,`
|
|
16
|
+
`).replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\");const t=r.match(/export\s+default\s+"((?:[^"\\]|\\.)*)"/);return t&&t[1]?t[1].replace(/\\r\\n/g,`
|
|
17
|
+
`).replace(/\\n/g,`
|
|
18
|
+
`).replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"):r.includes("import")||r.includes("export")?(i.warn("CSS file returned JavaScript module format. CSS may not load correctly."),""):r},ye=(r,e)=>p(null,null,function*(){let t="";const s=r.querySelectorAll("style, link[rel='stylesheet']");for(const o of s){if(o.tagName==="LINK"){const a=o.getAttribute("href");if(!a)continue;const l=fe(a,e),c=yield de(l),d=we(c);d&&(t+=`
|
|
19
|
+
`+d)}else if(o.tagName==="STYLE"){const n=o;if(n.textContent){let a=n.textContent.trim();a=a.replace(P.comments.css,"").trim(),t+=`
|
|
20
|
+
`+a}}o.remove()}return t.trim()});var C,M,A;class Ce{constructor(){j(this,C);this.components={},this.lazyComponents=new Set,this.intersectionObserver=null,this.lazyLoadingInProgress=new Map,this.lazyComponentsLoaded=new Set}registerComponent(e,t,s=!0,o=!1){return p(this,null,function*(){if(this.components[e]){i.warn(`Component with name "${e}" is already registered.`);return}if(o){this.lazyComponents.add(e),$(this,C,M).call(this,e,t,s),i.log(`Component ${e} registered as lazy-loaded`);return}try{const n=yield F(t),a=yield N(n,e,t);this.components[e]={tagName:e,template:a.template,scripts:a.scripts,externalScripts:a.externalScripts,styles:a.styles,sourcePath:t,lazy:!1},i.log(`Component ${e} registered successfully`),yield $(this,C,A).call(this,e,s)}catch(n){T(e,t,n);return}})}}C=new WeakSet,M=function(e,t,s){const o=this;class n extends HTMLElement{constructor(){super(),this.loaded=!1,this.observer=null,s&&(this.attachShadow({mode:"open"}),this.shadowRoot&&(this.shadowRoot.innerHTML=`
|
|
21
|
+
<style>
|
|
22
|
+
:host { display: block; min-height: 1px; }
|
|
23
|
+
</style>
|
|
24
|
+
`))}connectedCallback(){if(!this.loaded){if(this.hasAttribute("eager")){this.loaded=!0,this.loadComponent();return}this.observer=new IntersectionObserver(l=>{l.forEach(c=>{c.isIntersecting&&!this.loaded&&(this.loaded=!0,this.loadComponent())})},{rootMargin:"100px"}),this.observer.observe(this)}}disconnectedCallback(){this.observer&&(this.observer.disconnect(),this.observer=null)}loadComponent(){return p(this,null,function*(){try{if(o.lazyComponentsLoaded.has(e)){i.log(`Component ${e} already loaded, upgrading placeholder...`),this.upgradePlaceholder();return}if(o.lazyLoadingInProgress.has(e)){i.log(`Component ${e} is already loading, waiting...`),yield o.lazyLoadingInProgress.get(e),this.upgradePlaceholder();return}const l=this.performLoad();o.lazyLoadingInProgress.set(e,l),yield l,o.lazyLoadingInProgress.delete(e),o.lazyComponentsLoaded.add(e),o.lazyComponents.delete(e),i.log(`Component ${e} lazy-loaded successfully`)}catch(l){o.lazyLoadingInProgress.delete(e),T(e,t,l)}})}performLoad(){return p(this,null,function*(){i.log(`Lazy loading component: ${e}`);const l=this.parentNode;if(this.nextSibling,!l){b(`Placeholder for ${e} has no parent node`,{componentName:e,componentPath:t});return}const c=yield F(t),d=yield N(c,e,t);i.log(`Component ${e} parsed successfully`),o.components[e]={tagName:e,template:d.template,scripts:d.scripts,externalScripts:d.externalScripts,styles:d.styles,sourcePath:t,lazy:!0};const g=`${e}-real`;i.log(`Defining real component with temp name: ${g}`);const y=o.components[e].tagName;o.components[e].tagName=g;const{defineWebComponent:S}=yield Promise.resolve().then(()=>require("./webcomponent-BvS1JL3O.js"));S(o.components[e],s),i.log(`Real component ${g} defined`),o.components[e].tagName=y,this.upgradePlaceholder()})}upgradePlaceholder(){const l=this,c=this.parentNode,d=this.nextSibling;if(!c){b(`Placeholder for ${e} has no parent node`,{componentName:e,componentPath:t});return}const g=`${e}-real`,y=document.createElement(g);for(i.log(`Created real component instance: ${g}`),Array.from(l.attributes).forEach(S=>{S.name!=="eager"&&y.setAttribute(S.name,S.value)});l.firstChild;)y.appendChild(l.firstChild);d?(c.insertBefore(y,d),i.log("Inserted real component before next sibling")):(c.appendChild(y),i.log("Appended real component to parent")),c.removeChild(l),i.log("Removed placeholder element")}}customElements.get(e)||customElements.define(e,n)},A=function(e,t){return p(this,null,function*(){const{defineWebComponent:s}=yield Promise.resolve().then(()=>require("./webcomponent-BvS1JL3O.js"));this.components[e]&&s(this.components[e],t)})};const W=new Ce;class Se{constructor(){this.listeners=new Map}emit(e,t){const s=new CustomEvent(e,{detail:t,bubbles:!0,composed:!0});document.dispatchEvent(s);const o=this.listeners.get(e);if(!o||o.size===0)return Promise.resolve();const n=[];return o.forEach(a=>{try{const l=a(t);l instanceof Promise&&n.push(l)}catch(l){i.error(`⚠️ Event Bus Error: Failed to execute listener for "${e}"`),i.error(` Error details: ${l.message}`),n.push(Promise.reject(l))}}),n.length>0?Promise.all(n).then(()=>{}):Promise.resolve()}listen(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{this.off(e,t)}}off(e,t){const s=this.listeners.get(e);s&&(s.delete(t),s.size===0&&this.listeners.delete(e))}clear(e){e?this.listeners.delete(e):this.listeners.clear()}listenerCount(e){var t,s;return(s=(t=this.listeners.get(e))==null?void 0:t.size)!=null?s:0}}const _=new Se,u={};function q(r){return p(this,null,function*(){const e=yield u.readdir(r,{withFileTypes:!0});for(const t of e){const s=u.resolve(r,t.name);if(t.isDirectory())yield q(s);else if(t.name.endsWith(".html")){let o=yield u.readFile(s,"utf-8");o=o.replace(/<script type="module">([\s\S]*?)<\/script>/g,(n,a)=>`<script>
|
|
25
|
+
(async () => {
|
|
26
|
+
try {
|
|
27
|
+
// Use a shared promise to avoid multiple components polling independently
|
|
28
|
+
if (!window.__ladrillosPromise__) {
|
|
29
|
+
if (window.ladrillosjs) {
|
|
30
|
+
// Library already loaded, resolve immediately
|
|
31
|
+
window.__ladrillosPromise__ = Promise.resolve(window.ladrillosjs);
|
|
32
|
+
} else {
|
|
33
|
+
// Set up a one-time promise that waits for library to load
|
|
34
|
+
window.__ladrillosPromise__ = new Promise((resolve) => {
|
|
35
|
+
// Quick check first
|
|
36
|
+
if (window.ladrillosjs) {
|
|
37
|
+
resolve(window.ladrillosjs);
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Use a short timeout (libraries load almost instantly)
|
|
42
|
+
const timeout = setTimeout(() => {
|
|
43
|
+
if (!window.ladrillosjs) {
|
|
44
|
+
throw new Error('LadrillosJS failed to load');
|
|
45
|
+
}
|
|
46
|
+
clearInterval(interval);
|
|
47
|
+
resolve(window.ladrillosjs);
|
|
48
|
+
}, 100);
|
|
49
|
+
|
|
50
|
+
// Fallback polling as safety net
|
|
51
|
+
const interval = setInterval(() => {
|
|
52
|
+
if (window.ladrillosjs) {
|
|
53
|
+
clearTimeout(timeout);
|
|
54
|
+
clearInterval(interval);
|
|
55
|
+
resolve(window.ladrillosjs);
|
|
56
|
+
}
|
|
57
|
+
}, 5);
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Wait for the shared promise
|
|
63
|
+
await window.__ladrillosPromise__;
|
|
64
|
+
|
|
65
|
+
// Execute the component script
|
|
66
|
+
(async () => {
|
|
67
|
+
${a.replace(/import\s+\*\s+as\s+(\w+)\s+from\s+["']ladrillosjs["']/g,"const $1 = window.ladrillosjs;").replace(/import\s+\{\s*([^}]+)\s*\}\s+from\s+["']ladrillosjs["']/g,"const { $1 } = window.ladrillosjs;").replace(/import\s+(\w+)\s+from\s+["']ladrillosjs["']/g,"const $1 = window.ladrillosjs.default;")}
|
|
68
|
+
})();
|
|
69
|
+
} catch (error) {
|
|
70
|
+
console.error('Failed to execute component module:', error);
|
|
71
|
+
}
|
|
72
|
+
})();
|
|
73
|
+
<\/script>`),yield u.writeFile(s,o)}}})}function Ee(r={}){const{src:e="components",dest:t="components",copyOnDev:s=!1,processScripts:o=!0}=r;return{name:"ladrillosjs:copy-components",apply:s?"serve":"build",generateBundle(a,l){return p(this,null,function*(){const c=u.resolve(process.cwd(),e),d=u.resolve(process.cwd(),"dist",t);if(!u.existsSync(c)){console.warn(`[ladrillosjs:copy-components] Source directory not found: ${c}`);return}try{u.existsSync(d)&&u.rmSync(d,{recursive:!0,force:!0}),u.cpSync(c,d,{recursive:!0}),console.log(`[ladrillosjs:copy-components] Copied components from ${c} to ${d}`),o&&(yield q(d),console.log(`[ladrillosjs:copy-components] Processed component scripts in ${d}`))}catch(g){throw console.error("[ladrillosjs:copy-components] Error copying components:",g),g}})}}}const R=(r,e,t,s)=>W.registerComponent(r,e,t,s),I=r=>p(null,null,function*(){yield Promise.all(r.map(({name:e,path:t,useShadowDOM:s,lazy:o})=>W.registerComponent(e,t,s,o)))}),B=(r,e)=>_.listen(r,e),D=(r,e)=>{_.emit(r,e)},ve=(r,e)=>{if(e){const t=e.tagName.toLowerCase();window.__ladrilloContexts||(window.__ladrilloContexts=new Map),window.__ladrilloContexts.set(t,{shadowRoot:r,element:e})}},v=()=>{const r=window.__ladrilloContexts;if(r&&r.size>0){const e=Array.from(r.values());return e[e.length-1]}return null},O=()=>{const r=v();return r&&r.element?r.element.state||{}:{}},E=r=>{const e=v();e&&e.setState&&e.setState(r)},G=(r,e)=>(E({[r]:e}),t=>{E({[r]:t})}),J=(r,e)=>{if(e)return e.querySelector(r);const t=v();if(t){const s=t.shadowRoot||t.element;if(s){const o=s.querySelector(r);if(o)return o}}return document.querySelector(r)},K=(r,e)=>{if(e)return e.querySelectorAll(r);const t=v();if(t){const s=t.shadowRoot||t.element;if(s){const o=s.querySelectorAll(r);if(o.length>0)return o}}return document.querySelectorAll(r)};typeof window!="undefined"&&(window.ladrillosjs={registerComponent:R,registerComponents:I},window.$listen=B,window.$emit=D,window.$querySelector=J,window.$querySelectorAll=K,window.$reactive=G,window.$setState=E,window.$getState=O);exports.$emit=D;exports.$getState=O;exports.$listen=B;exports.$querySelector=J;exports.$querySelectorAll=K;exports.$reactive=G;exports.$setState=E;exports.REGEX_PATTERNS=P;exports.__setComponentContext=ve;exports.copyComponentsPlugin=Ee;exports.createErrorContext=ie;exports.eventBus=_;exports.logBindingError=ee;exports.logConditionalError=re;exports.logEventHandlerError=te;exports.logLoopError=se;exports.logParseError=b;exports.logScriptError=oe;exports.logTwoWayBindingError=ne;exports.logger=i;exports.registerComponent=R;exports.registerComponents=I;
|
|
74
|
+
//# sourceMappingURL=index-6X7blelu.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index-6X7blelu.js","sources":["../src/utils/logger.ts","../src/utils/devErrors.ts","../src/cache/index.ts","../src/core/componentSource.ts","../src/utils/regex.ts","../src/core/componentParser.ts","../src/core/main.ts","../src/core/eventBus.ts","../__vite-browser-external","../src/vite/copyComponentsPlugin.ts","../src/index.ts"],"sourcesContent":["/**\r\n * Utility for conditional logging based on environment\r\n */\r\n\r\n// Type guard for Vite environment\r\nconst isDevelopment = (): boolean => {\r\n try {\r\n return (import.meta as any).env?.DEV === true;\r\n } catch {\r\n return process.env.NODE_ENV === 'development';\r\n }\r\n};\r\n\r\nexport const logger = {\r\n /**\r\n * Log a message only in development mode\r\n * @param message - The message to log\r\n * @param args - Additional arguments to log\r\n */\r\n log(message: string, ...args: any[]): void {\r\n if (isDevelopment()) {\r\n console.log(message, ...args);\r\n }\r\n },\r\n\r\n /**\r\n * Log an error (always logs in both dev and production)\r\n * @param message - The error message\r\n * @param args - Additional arguments to log\r\n */\r\n error(message: string, ...args: any[]): void {\r\n console.error(message, ...args);\r\n },\r\n\r\n /**\r\n * Log a warning only in development mode\r\n * @param message - The warning message\r\n * @param args - Additional arguments to log\r\n */\r\n warn(message: string, ...args: any[]): void {\r\n if (isDevelopment()) {\r\n console.warn(message, ...args);\r\n }\r\n },\r\n};\r\n","/**\r\n * Developer-friendly error handling utilities\r\n * Provides contextual error messages with component names, file paths, and code references\r\n */\r\n\r\nimport { logger } from \"./logger\";\r\n\r\nexport type ErrorContext = {\r\n componentName?: string;\r\n componentPath?: string;\r\n expression?: string;\r\n attributeName?: string;\r\n eventType?: string;\r\n elementTag?: string;\r\n lineHint?: string;\r\n};\r\n\r\nexport class LadrillosError extends Error {\r\n public readonly componentName?: string;\r\n public readonly componentPath?: string;\r\n public readonly expression?: string;\r\n public readonly context?: ErrorContext;\r\n\r\n constructor(message: string, context?: ErrorContext) {\r\n super(message);\r\n this.name = \"LadrillosError\";\r\n this.componentName = context?.componentName;\r\n this.componentPath = context?.componentPath;\r\n this.expression = context?.expression;\r\n this.context = context;\r\n\r\n // Maintain proper stack trace for where error was thrown\r\n if (Error.captureStackTrace) {\r\n Error.captureStackTrace(this, LadrillosError);\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Formats an error message with component context for developers\r\n */\r\nconst formatErrorMessage = (\r\n message: string,\r\n context?: ErrorContext\r\n): string => {\r\n const parts: string[] = [message];\r\n\r\n if (context) {\r\n if (context.componentName) {\r\n parts.push(`\\n Component: <${context.componentName}>`);\r\n }\r\n\r\n if (context.componentPath) {\r\n parts.push(`\\n File: ${context.componentPath}`);\r\n }\r\n\r\n if (context.expression) {\r\n parts.push(`\\n Expression: ${context.expression}`);\r\n }\r\n\r\n if (context.attributeName) {\r\n parts.push(`\\n Attribute: ${context.attributeName}`);\r\n }\r\n\r\n if (context.eventType) {\r\n parts.push(`\\n Event: ${context.eventType}`);\r\n }\r\n\r\n if (context.elementTag) {\r\n parts.push(`\\n Element: <${context.elementTag}>`);\r\n }\r\n\r\n if (context.lineHint) {\r\n parts.push(`\\n Location: ${context.lineHint}`);\r\n }\r\n }\r\n\r\n return parts.join(\"\");\r\n};\r\n\r\n/**\r\n * Logs a binding error with component context\r\n */\r\nexport const logBindingError = (\r\n expression: string,\r\n error: Error,\r\n context?: ErrorContext\r\n): void => {\r\n const errorMessage = formatErrorMessage(\r\n `⚠️ Binding Error: Failed to evaluate expression`,\r\n {\r\n ...context,\r\n expression,\r\n lineHint: context?.lineHint || \"Template binding expression\",\r\n }\r\n );\r\n\r\n logger.error(errorMessage);\r\n logger.error(` Error details: ${error.message}`);\r\n\r\n // Log stack trace in development for debugging\r\n if (error.stack) {\r\n console.debug(\" Stack trace:\", error.stack);\r\n }\r\n};\r\n\r\n/**\r\n * Logs an event handler error with component context\r\n */\r\nexport const logEventHandlerError = (\r\n eventType: string,\r\n handlerCode: string,\r\n error: Error,\r\n context?: ErrorContext\r\n): void => {\r\n const errorMessage = formatErrorMessage(\r\n `⚠️ Event Handler Error: Failed to execute handler`,\r\n {\r\n ...context,\r\n eventType,\r\n expression: handlerCode,\r\n lineHint: context?.lineHint || `on${eventType} handler`,\r\n }\r\n );\r\n\r\n logger.error(errorMessage);\r\n logger.error(` Error details: ${error.message}`);\r\n\r\n if (error.stack) {\r\n console.debug(\" Stack trace:\", error.stack);\r\n }\r\n};\r\n\r\n/**\r\n * Logs a conditional rendering error with component context\r\n */\r\nexport const logConditionalError = (\r\n condition: string,\r\n error: Error,\r\n context?: ErrorContext\r\n): void => {\r\n const errorMessage = formatErrorMessage(\r\n `⚠️ Conditional Error: Failed to evaluate condition`,\r\n {\r\n ...context,\r\n expression: condition,\r\n lineHint: context?.lineHint || \"$if/$else-if condition\",\r\n }\r\n );\r\n\r\n logger.error(errorMessage);\r\n logger.error(` Error details: ${error.message}`);\r\n\r\n if (error.stack) {\r\n console.debug(\" Stack trace:\", error.stack);\r\n }\r\n};\r\n\r\n/**\r\n * Logs a loop rendering error with component context\r\n */\r\nexport const logLoopError = (\r\n loopExpression: string,\r\n error: Error,\r\n context?: ErrorContext\r\n): void => {\r\n const errorMessage = formatErrorMessage(\r\n `⚠️ Loop Error: Failed to process loop`,\r\n {\r\n ...context,\r\n expression: loopExpression,\r\n lineHint: context?.lineHint || \"$for loop expression\",\r\n }\r\n );\r\n\r\n logger.error(errorMessage);\r\n logger.error(` Error details: ${error.message}`);\r\n\r\n if (error.stack) {\r\n console.debug(\" Stack trace:\", error.stack);\r\n }\r\n};\r\n\r\n/**\r\n * Logs a component registration error\r\n */\r\nexport const logRegistrationError = (\r\n componentName: string,\r\n componentPath: string,\r\n error: Error\r\n): void => {\r\n const errorMessage = formatErrorMessage(\r\n `⚠️ Registration Error: Failed to register component`,\r\n {\r\n componentName,\r\n componentPath,\r\n }\r\n );\r\n\r\n logger.error(errorMessage);\r\n logger.error(` Error details: ${error.message}`);\r\n\r\n if (error.stack) {\r\n console.debug(\" Stack trace:\", error.stack);\r\n }\r\n};\r\n\r\n/**\r\n * Logs a fetch error with context\r\n */\r\nexport const logFetchError = (\r\n url: string,\r\n error: Error,\r\n context?: ErrorContext\r\n): void => {\r\n const errorMessage = formatErrorMessage(\r\n `⚠️ Fetch Error: Failed to load resource`,\r\n {\r\n ...context,\r\n componentPath: url,\r\n }\r\n );\r\n\r\n logger.error(errorMessage);\r\n logger.error(` Error details: ${error.message}`);\r\n};\r\n\r\n/**\r\n * Logs a parsing error with context\r\n */\r\nexport const logParseError = (\r\n message: string,\r\n context?: ErrorContext\r\n): void => {\r\n const errorMessage = formatErrorMessage(\r\n `⚠️ Parse Error: ${message}`,\r\n context\r\n );\r\n\r\n logger.error(errorMessage);\r\n};\r\n\r\n/**\r\n * Logs a script execution error\r\n */\r\nexport const logScriptError = (error: Error, context?: ErrorContext): void => {\r\n const errorMessage = formatErrorMessage(\r\n `⚠️ Script Error: Failed to execute component script`,\r\n context\r\n );\r\n\r\n logger.error(errorMessage);\r\n logger.error(` Error details: ${error.message}`);\r\n\r\n if (error.stack) {\r\n console.debug(\" Stack trace:\", error.stack);\r\n }\r\n};\r\n\r\n/**\r\n * Logs a two-way binding error\r\n */\r\nexport const logTwoWayBindingError = (\r\n expression: string,\r\n error: Error,\r\n context?: ErrorContext\r\n): void => {\r\n const errorMessage = formatErrorMessage(\r\n `⚠️ Two-Way Binding Error: Failed to setup binding`,\r\n {\r\n ...context,\r\n expression,\r\n lineHint: context?.lineHint || \"$model binding\",\r\n }\r\n );\r\n\r\n logger.error(errorMessage);\r\n logger.error(` Error details: ${error.message}`);\r\n};\r\n\r\n/**\r\n * Creates an error context from component metadata\r\n */\r\nexport const createErrorContext = (\r\n component: any,\r\n additionalContext?: Partial<ErrorContext>\r\n): ErrorContext => {\r\n return {\r\n componentName: component?.tagName || component?.constructor?.name,\r\n componentPath: component?.sourcePath || component?._sourcePath,\r\n ...additionalContext,\r\n };\r\n};\r\n","const cache = new Map<string, string>();\r\nconst maxCacheSize = 25; // TODO: make configurable for developer to set\r\n\r\n/**\r\n * LRU Cache: Gets cached content and marks it as recently used\r\n * Moves the accessed item to the end of the Map (most recently used position)\r\n * This ensures frequently accessed components stay in cache longer\r\n * @param path - The file path to retrieve from cache\r\n * @returns The cached content or undefined if not found\r\n */\r\nexport const getCached = (path: string): string | undefined => {\r\n const cached = cache.get(path);\r\n if (cached) {\r\n // LRU: Move to end (most recently used position)\r\n cache.delete(path);\r\n cache.set(path, cached);\r\n }\r\n return cached;\r\n};\r\n\r\n/**\r\n * LRU Cache: Stores content with automatic eviction of least recently used items\r\n * Maintains cache size limit by removing oldest items when full\r\n * Updates existing items without affecting cache size\r\n * @param path - The file path to cache\r\n * @param content - The content to store\r\n */\r\nexport const setCache = (path: string, content: string): void => {\r\n if (cache.has(path)) {\r\n // Update existing: remove and re-add to mark as most recent\r\n cache.delete(path);\r\n } else if (cache.size >= maxCacheSize) {\r\n // Cache full: remove least recently used (first item in Map)\r\n const firstKey = cache.keys().next().value;\r\n if (firstKey) {\r\n cache.delete(firstKey);\r\n }\r\n }\r\n // Add/update as most recently used (end of Map)\r\n cache.set(path, content);\r\n};\r\n","import { getCached, setCache } from \"../cache\";\r\nimport { logger } from \"../utils/logger\";\r\nimport { logFetchError } from \"../utils/devErrors\";\r\n\r\n/**\r\n * Fetches component source with caching support\r\n * @param path - The file path to fetch\r\n * @returns The component source content\r\n */\r\nexport const fetchComponentSource = async (\r\n path: string\r\n): Promise<string | undefined> => {\r\n if (!path) {\r\n throw new Error(\"Path cannot be null or empty\");\r\n }\r\n\r\n const cached = getCached(path);\r\n if (cached) return cached;\r\n\r\n // fetch and cache\r\n try {\r\n const response = await fetch(path);\r\n\r\n if (!response.ok) {\r\n throw new Error(\r\n `Failed to fetch component from ${path}: ${response.statusText}`\r\n );\r\n }\r\n\r\n const text = await response.text();\r\n setCache(path, text);\r\n\r\n return text;\r\n } catch (error) {\r\n logFetchError(path, error as Error, { componentPath: path });\r\n }\r\n};\r\n\r\n/**\r\n * Safe fetch helper that returns empty string on error\r\n * @param url - The URL to fetch\r\n * @returns The fetched content or empty string\r\n */\r\nexport const safeFetch = async (url: string): Promise<string> => {\r\n try {\r\n const res = await fetch(url);\r\n if (!res.ok) throw new Error(`HTTP ${res.status}`);\r\n return await res.text();\r\n } catch (err) {\r\n logFetchError(url, err as Error);\r\n return \"\";\r\n }\r\n};\r\n","import { RegexPatterns } from \"../types/LadrilloTypes\";\r\n\r\nexport const REGEX_PATTERNS: RegexPatterns = {\r\n bindings: /{([^}]+)}/g,\r\n comments: {\r\n js: /\\/\\*[\\s\\S]*?\\*\\/|\\/\\/.*$/gm,\r\n css: /\\/\\*[\\s\\S]*?\\*\\//g,\r\n html: /<!--[\\s\\S]*?-->/g,\r\n },\r\n};\r\n\r\n/**\r\n * Strips single-line and multi-line comments from JavaScript code\r\n * while preserving string literals and template literals.\r\n * Also removes export statements since they can't be used in new Function().\r\n *\r\n * Handles:\r\n * - Single-quoted strings ('...')\r\n * - Double-quoted strings (\"...\")\r\n * - Template literals with backticks (backticks)\r\n * - Single-line comments (double slashes)\r\n * - Multi-line comments (slash-star pairs)\r\n * - Export statements (export const/let/function/class/default/...)\r\n * - Escaped characters within strings\r\n *\r\n * @param code - JavaScript code to strip comments from\r\n * @returns Code with comments and export statements removed, strings preserved\r\n */\r\nexport const stripComments = (code: string): string => {\r\n let result = \"\";\r\n let i = 0;\r\n\r\n while (i < code.length) {\r\n // Check for string literals\r\n const char = code[i];\r\n\r\n if (char === '\"' || char === \"'\" || char === \"`\") {\r\n // Handle string literal - preserve it entirely\r\n const quote = char;\r\n result += char;\r\n i++;\r\n\r\n while (i < code.length) {\r\n const c = code[i];\r\n\r\n if (c === \"\\\\\") {\r\n // Escaped character - preserve both the backslash and next char\r\n result += c + code[i + 1];\r\n i += 2;\r\n } else if (c === quote) {\r\n // End of string\r\n result += c;\r\n i++;\r\n break;\r\n } else {\r\n result += c;\r\n i++;\r\n }\r\n }\r\n } else if (char === \"/\" && i + 1 < code.length) {\r\n // Check for comments\r\n const nextChar = code[i + 1];\r\n\r\n if (nextChar === \"/\") {\r\n // Single-line comment - skip until end of line or end of code\r\n while (i < code.length && code[i] !== \"\\n\") {\r\n i++;\r\n }\r\n // Preserve the newline if present (maintains line structure)\r\n if (i < code.length && code[i] === \"\\n\") {\r\n result += \"\\n\";\r\n i++;\r\n }\r\n } else if (nextChar === \"*\") {\r\n // Multi-line comment - skip until */ is found\r\n i += 2; // Skip the /*\r\n while (i + 1 < code.length) {\r\n if (code[i] === \"*\" && code[i + 1] === \"/\") {\r\n i += 2;\r\n break;\r\n }\r\n // Preserve structure by keeping newlines\r\n if (code[i] === \"\\n\") {\r\n result += \"\\n\";\r\n }\r\n i++;\r\n }\r\n } else {\r\n // Regular slash, not a comment\r\n result += char;\r\n i++;\r\n }\r\n } else if (/\\s/.test(char)) {\r\n // Check for export keyword at the start of a line\r\n // Look ahead to see if this is the start of an export statement\r\n const beforeWord = result.trimEnd();\r\n const isLineStart =\r\n beforeWord === \"\" ||\r\n beforeWord.endsWith(\"\\n\") ||\r\n beforeWord.endsWith(\";\") ||\r\n beforeWord.endsWith(\"}\");\r\n\r\n if (isLineStart && code.substring(i).match(/^\\s*export\\s+/)) {\r\n // Skip the whitespace and 'export' keyword\r\n i = i + code.substring(i).match(/^\\s*export\\s+/)![0].length;\r\n continue;\r\n }\r\n\r\n result += char;\r\n i++;\r\n } else {\r\n result += char;\r\n i++;\r\n }\r\n }\r\n\r\n return result;\r\n};\r\n","import {\r\n ExternalScriptElement,\r\n LadrillosComponent,\r\n ScriptElement,\r\n} from \"../types/LadrilloTypes\";\r\nimport { REGEX_PATTERNS, stripComments } from \"../utils/regex\";\r\nimport { logger } from \"../utils/logger\";\r\nimport { safeFetch } from \"./componentSource\";\r\n\r\nconst parser = new DOMParser();\r\n\r\n/**\r\n * Parses component HTML and extracts scripts and styles\r\n * @param source - The HTML source of the component\r\n * @param name - The name of the component\r\n * @param componentUrl - The URL/path of the component file (used for resolving relative CSS paths)\r\n * @returns Parsed component object\r\n */\r\nexport const parseComponent = async (\r\n source: string,\r\n name: string,\r\n componentUrl?: string\r\n): Promise<LadrillosComponent> => {\r\n const doc = parseComponentHTML(source);\r\n const { scripts, externalScripts } = extractScripts(doc);\r\n const styles = await extractStyles(doc, componentUrl);\r\n const template = doc.body.innerHTML.trim();\r\n\r\n return {\r\n tagName: name,\r\n template,\r\n scripts,\r\n externalScripts,\r\n styles,\r\n };\r\n};\r\n\r\n/**\r\n * Parses HTML content and removes comments\r\n * @param source - The HTML source to parse\r\n * @returns Parsed DOM document\r\n */\r\nexport const parseComponentHTML = (source: string): Document => {\r\n return parser.parseFromString(\r\n source.replace(REGEX_PATTERNS.comments.html, \"\"),\r\n \"text/html\"\r\n );\r\n};\r\n\r\n/**\r\n * Checks if a script URL is a development server script that should be ignored.\r\n * Dev server scripts (Vite, Webpack HMR, etc.) are injected by the dev environment\r\n * and should not be processed as part of the component.\r\n */\r\nconst isDevServerScript = (src: string): boolean => {\r\n const devPatterns = [\r\n \"/@vite/\", // Vite dev client\r\n \"/__vite\", // Vite internal\r\n \"/webpack-dev-server\", // Webpack dev server\r\n \"/hot-update\", // Webpack HMR\r\n \"/__webpack_hmr\", // Webpack HMR\r\n \"/browser-sync/\", // Browser Sync\r\n \"/livereload.js\", // LiveReload\r\n ];\r\n\r\n return devPatterns.some((pattern) => src.includes(pattern));\r\n};\r\n\r\n/**\r\n * Extracts and processes script elements from the document\r\n * @param doc - The parsed document\r\n * @returns Object containing scripts and external scripts\r\n */\r\nexport const extractScripts = (\r\n doc: Document\r\n): {\r\n scripts: ScriptElement[];\r\n externalScripts: ExternalScriptElement[];\r\n} => {\r\n const scripts: ScriptElement[] = [];\r\n const externalScripts: ExternalScriptElement[] = [];\r\n\r\n for (const el of doc.querySelectorAll(\"script\")) {\r\n if (el.src) {\r\n // Skip dev server scripts (Vite, Webpack, etc.)\r\n if (isDevServerScript(el.src)) {\r\n el.remove();\r\n continue;\r\n }\r\n\r\n // Only mark as external if the 'external' attribute is explicitly present\r\n const isExternal = el.hasAttribute(\"external\");\r\n\r\n externalScripts.push({\r\n src: el.getAttribute(\"src\") || el.src, // Use getAttribute to preserve relative paths\r\n type: el.type ?? null,\r\n external: isExternal,\r\n });\r\n } else if (el.textContent) {\r\n let content = el.textContent.trim();\r\n // Strip comments intelligently while preserving strings and URLs\r\n // Use stripComments() instead of naive regex to handle strings with // correctly\r\n content = stripComments(content).trim();\r\n scripts.push({\r\n content,\r\n type: el.type ?? null,\r\n });\r\n }\r\n el.remove();\r\n }\r\n\r\n return { scripts, externalScripts };\r\n};\r\n\r\n/**\r\n * Resolves CSS href intelligently based on path format\r\n * - Relative paths (./style.css, ../style.css) resolve from component location\r\n * - Absolute/implicit paths (style.css, /style.css) resolve from /public folder\r\n * - Full URLs (http://, https://) pass through unchanged\r\n * @param href - The original href from link tag\r\n * @param componentUrl - The component file URL/path (used as base for relative resolution)\r\n * @returns The resolved CSS path\r\n */\r\nconst resolveCSSPath = (href: string, componentUrl?: string): string => {\r\n // Full URLs pass through unchanged\r\n if (href.startsWith(\"http://\") || href.startsWith(\"https://\")) {\r\n return href;\r\n }\r\n\r\n // Relative paths (./style.css, ../style.css) resolve from component location\r\n if (href.startsWith(\"./\") || href.startsWith(\"../\")) {\r\n if (componentUrl) {\r\n try {\r\n // Resolve relative to component URL\r\n const componentBase = componentUrl.endsWith(\"/\")\r\n ? componentUrl\r\n : componentUrl.substring(0, componentUrl.lastIndexOf(\"/\") + 1);\r\n const resolved = new URL(href, componentBase).href;\r\n return resolved;\r\n } catch (e) {\r\n logger.warn(\r\n `Failed to resolve relative CSS path \"${href}\" from component \"${componentUrl}\"`\r\n );\r\n return href;\r\n }\r\n }\r\n return href;\r\n }\r\n\r\n // Absolute paths (/style.css) or implicit public paths (style.css) resolve from /public\r\n return href.startsWith(\"/\") ? href : \"/\" + href;\r\n};\r\n\r\n/**\r\n * Extracts CSS content from various response formats\r\n * Handles:\r\n * - Vite dev server (wrapped in __vite__css variable)\r\n * - Plain CSS files (production/CDN)\r\n * - Other build tool formats\r\n */\r\nconst extractCSSFromResponse = (response: string): string => {\r\n // Check if this is a Vite HMR response (contains __vite__css)\r\n // Use a regex that properly handles escaped quotes within the string\r\n const viteMatch = response.match(/const __vite__css = \"((?:[^\"\\\\]|\\\\.)*)\"/);\r\n if (viteMatch && viteMatch[1]) {\r\n // Unescape the CSS string\r\n return viteMatch[1]\r\n .replace(/\\\\r\\\\n/g, \"\\n\")\r\n .replace(/\\\\n/g, \"\\n\")\r\n .replace(/\\\\t/g, \"\\t\")\r\n .replace(/\\\\\"/g, '\"')\r\n .replace(/\\\\\\\\/g, \"\\\\\");\r\n }\r\n\r\n // Check for other module formats (e.g., \"export default ...\")\r\n const exportMatch = response.match(/export\\s+default\\s+\"((?:[^\"\\\\]|\\\\.)*)\"/);\r\n if (exportMatch && exportMatch[1]) {\r\n return exportMatch[1]\r\n .replace(/\\\\r\\\\n/g, \"\\n\")\r\n .replace(/\\\\n/g, \"\\n\")\r\n .replace(/\\\\t/g, \"\\t\")\r\n .replace(/\\\\\"/g, '\"')\r\n .replace(/\\\\\\\\/g, \"\\\\\");\r\n }\r\n\r\n // If it looks like JavaScript (not CSS), warn and return empty\r\n if (response.includes(\"import\") || response.includes(\"export\")) {\r\n logger.warn(\r\n \"CSS file returned JavaScript module format. CSS may not load correctly.\"\r\n );\r\n return \"\";\r\n }\r\n\r\n // If not a module format, assume it's plain CSS (production or direct file)\r\n return response;\r\n};\r\n\r\n/**\r\n * Extracts and processes style elements from the document\r\n * @param doc - The parsed document\r\n * @param componentUrl - The component file URL/path (used for resolving relative CSS paths)\r\n * @returns Concatenated CSS content\r\n *\r\n * CSS path resolution rules:\r\n * - ./style.css or ../style.css → resolved relative to component location\r\n * - style.css or /style.css → resolved from /public folder\r\n * - http://... or https://... → used as-is (absolute URLs)\r\n */\r\nexport const extractStyles = async (\r\n doc: Document,\r\n componentUrl?: string\r\n): Promise<string> => {\r\n let style = \"\";\r\n\r\n // Process styles in document order (inline styles and external stylesheets)\r\n const styleElements = doc.querySelectorAll(\"style, link[rel='stylesheet']\");\r\n\r\n for (const element of styleElements) {\r\n if (element.tagName === \"LINK\") {\r\n const linkElement = element as HTMLLinkElement;\r\n const href = linkElement.getAttribute(\"href\");\r\n if (!href) continue;\r\n\r\n // Resolve CSS path intelligently\r\n const resolvedPath = resolveCSSPath(href, componentUrl);\r\n const response = await safeFetch(resolvedPath);\r\n const cssContent = extractCSSFromResponse(response);\r\n if (cssContent) {\r\n style += \"\\n\" + cssContent;\r\n }\r\n } else if (element.tagName === \"STYLE\") {\r\n const styleEl = element as HTMLStyleElement;\r\n if (styleEl.textContent) {\r\n let css = styleEl.textContent.trim();\r\n // strip CSS comments\r\n css = css.replace(REGEX_PATTERNS.comments.css, \"\").trim();\r\n style += \"\\n\" + css;\r\n }\r\n }\r\n element.remove();\r\n }\r\n\r\n return style.trim();\r\n};\r\n","import { LadrillosComponent } from \"../types/LadrilloTypes\";\r\nimport { logger } from \"../utils/logger\";\r\nimport { logRegistrationError, logParseError } from \"../utils/devErrors\";\r\nimport { fetchComponentSource } from \"./componentSource\";\r\nimport { parseComponent } from \"./componentParser\";\r\n\r\nclass Ladrillos {\r\n // properties\r\n components: Record<string, LadrillosComponent>;\r\n private lazyComponents: Set<string>;\r\n private intersectionObserver: IntersectionObserver | null;\r\n private lazyLoadingInProgress: Map<string, Promise<void>>;\r\n private lazyComponentsLoaded: Set<string>;\r\n\r\n constructor() {\r\n // Initialize the Ladrillos instance\r\n this.components = {};\r\n this.lazyComponents = new Set();\r\n this.intersectionObserver = null;\r\n this.lazyLoadingInProgress = new Map();\r\n this.lazyComponentsLoaded = new Set();\r\n }\r\n\r\n async registerComponent(\r\n name: string,\r\n path: string,\r\n useShadowDOM: boolean = true,\r\n lazy: boolean = false\r\n ): Promise<void> {\r\n if (this.components[name]) {\r\n logger.warn(`Component with name \"${name}\" is already registered.`);\r\n return;\r\n }\r\n\r\n // For lazy components, register a placeholder and defer actual loading\r\n if (lazy) {\r\n this.lazyComponents.add(name);\r\n this.#defineLazyPlaceholder(name, path, useShadowDOM);\r\n logger.log(`Component ${name} registered as lazy-loaded`);\r\n return;\r\n }\r\n\r\n try {\r\n const source = await fetchComponentSource(path);\r\n const component = await parseComponent(source!, name, path);\r\n\r\n this.components[name] = {\r\n tagName: name,\r\n template: component.template,\r\n scripts: component.scripts,\r\n externalScripts: component.externalScripts,\r\n styles: component.styles,\r\n sourcePath: path,\r\n lazy: false,\r\n };\r\n\r\n // Define the web component\r\n logger.log(`Component ${name} registered successfully`);\r\n await this.#defineWebComponent(name, useShadowDOM);\r\n } catch (error) {\r\n logRegistrationError(name, path, error as Error);\r\n return;\r\n }\r\n }\r\n\r\n /**\r\n * Defines a lazy-loading placeholder component\r\n * @param name - Component name\r\n * @param path - Component path\r\n * @param useShadowDOM - Whether to use Shadow DOM\r\n */\r\n #defineLazyPlaceholder(\r\n name: string,\r\n path: string,\r\n useShadowDOM: boolean\r\n ): void {\r\n const self = this;\r\n\r\n class LazyPlaceholder extends HTMLElement {\r\n private loaded = false;\r\n private observer: IntersectionObserver | null = null;\r\n\r\n constructor() {\r\n super();\r\n\r\n // Show a minimal loading indicator\r\n if (useShadowDOM) {\r\n this.attachShadow({ mode: \"open\" });\r\n if (this.shadowRoot) {\r\n this.shadowRoot.innerHTML = `\r\n <style>\r\n :host { display: block; min-height: 1px; }\r\n </style>\r\n `;\r\n }\r\n }\r\n }\r\n\r\n connectedCallback() {\r\n if (this.loaded) return;\r\n\r\n // Check if 'eager' attribute is present - if so, load immediately\r\n if (this.hasAttribute(\"eager\")) {\r\n this.loaded = true;\r\n this.loadComponent();\r\n return;\r\n }\r\n\r\n // Set up intersection observer for lazy loading\r\n this.observer = new IntersectionObserver(\r\n (entries) => {\r\n entries.forEach((entry) => {\r\n if (entry.isIntersecting && !this.loaded) {\r\n this.loaded = true;\r\n this.loadComponent();\r\n }\r\n });\r\n },\r\n {\r\n rootMargin: \"100px\", // Load 100px before entering viewport\r\n }\r\n );\r\n\r\n this.observer.observe(this);\r\n }\r\n\r\n disconnectedCallback() {\r\n if (this.observer) {\r\n this.observer.disconnect();\r\n this.observer = null;\r\n }\r\n }\r\n\r\n async loadComponent() {\r\n try {\r\n // Check if component is already loaded globally\r\n if (self.lazyComponentsLoaded.has(name)) {\r\n logger.log(\r\n `Component ${name} already loaded, upgrading placeholder...`\r\n );\r\n this.upgradePlaceholder();\r\n return;\r\n }\r\n\r\n // Check if loading is already in progress\r\n if (self.lazyLoadingInProgress.has(name)) {\r\n logger.log(`Component ${name} is already loading, waiting...`);\r\n await self.lazyLoadingInProgress.get(name);\r\n this.upgradePlaceholder();\r\n return;\r\n }\r\n\r\n // Start loading process\r\n const loadingPromise = this.performLoad();\r\n self.lazyLoadingInProgress.set(name, loadingPromise);\r\n\r\n await loadingPromise;\r\n\r\n // Mark as loaded and clean up\r\n self.lazyLoadingInProgress.delete(name);\r\n self.lazyComponentsLoaded.add(name);\r\n self.lazyComponents.delete(name);\r\n\r\n logger.log(`Component ${name} lazy-loaded successfully`);\r\n } catch (error) {\r\n self.lazyLoadingInProgress.delete(name);\r\n logRegistrationError(name, path, error as Error);\r\n }\r\n }\r\n\r\n async performLoad() {\r\n logger.log(`Lazy loading component: ${name}`);\r\n\r\n // Store reference to this placeholder element\r\n const placeholder = this;\r\n const parent = this.parentNode;\r\n const nextSibling = this.nextSibling;\r\n\r\n if (!parent) {\r\n logParseError(`Placeholder for ${name} has no parent node`, {\r\n componentName: name,\r\n componentPath: path,\r\n });\r\n return;\r\n }\r\n\r\n // Fetch and parse the component\r\n const source = await fetchComponentSource(path);\r\n const component = await parseComponent(source!, name, path);\r\n\r\n logger.log(`Component ${name} parsed successfully`);\r\n\r\n self.components[name] = {\r\n tagName: name,\r\n template: component.template,\r\n scripts: component.scripts,\r\n externalScripts: component.externalScripts,\r\n styles: component.styles,\r\n sourcePath: path,\r\n lazy: true,\r\n };\r\n\r\n // Create a unique temporary name for the real component\r\n const tempName = `${name}-real`;\r\n\r\n logger.log(`Defining real component with temp name: ${tempName}`);\r\n\r\n // Store original name and temporarily use temp name\r\n const originalTagName = self.components[name].tagName;\r\n self.components[name].tagName = tempName;\r\n\r\n // Import and define the real component with temp name\r\n const { defineWebComponent } = await import(\"./webcomponent\");\r\n defineWebComponent(self.components[name], useShadowDOM);\r\n\r\n logger.log(`Real component ${tempName} defined`);\r\n\r\n // Restore original tag name\r\n self.components[name].tagName = originalTagName;\r\n\r\n // Upgrade this placeholder\r\n this.upgradePlaceholder();\r\n }\r\n\r\n upgradePlaceholder() {\r\n const placeholder = this;\r\n const parent = this.parentNode;\r\n const nextSibling = this.nextSibling;\r\n\r\n if (!parent) {\r\n logParseError(`Placeholder for ${name} has no parent node`, {\r\n componentName: name,\r\n componentPath: path,\r\n });\r\n return;\r\n }\r\n\r\n const tempName = `${name}-real`;\r\n\r\n // Create instance of the real component\r\n const realComponent = document.createElement(tempName);\r\n\r\n logger.log(`Created real component instance: ${tempName}`);\r\n\r\n // Copy attributes from placeholder to real component\r\n Array.from(placeholder.attributes).forEach((attr) => {\r\n if (attr.name !== \"eager\") {\r\n // Skip the eager attribute\r\n realComponent.setAttribute(attr.name, attr.value);\r\n }\r\n });\r\n\r\n // Copy child nodes (slot content)\r\n while (placeholder.firstChild) {\r\n realComponent.appendChild(placeholder.firstChild);\r\n }\r\n\r\n // Replace placeholder in DOM\r\n if (nextSibling) {\r\n parent.insertBefore(realComponent, nextSibling);\r\n logger.log(`Inserted real component before next sibling`);\r\n } else {\r\n parent.appendChild(realComponent);\r\n logger.log(`Appended real component to parent`);\r\n }\r\n\r\n parent.removeChild(placeholder);\r\n logger.log(`Removed placeholder element`);\r\n }\r\n }\r\n\r\n // Define the placeholder component\r\n if (!customElements.get(name)) {\r\n customElements.define(name, LazyPlaceholder);\r\n }\r\n }\r\n\r\n /**\r\n * Defines the web component using the webcomponent module\r\n * @param name - Component name\r\n * @param useShadowDOM - Whether to use Shadow DOM\r\n */\r\n async #defineWebComponent(\r\n name: string,\r\n useShadowDOM: boolean\r\n ): Promise<void> {\r\n const { defineWebComponent } = await import(\"./webcomponent\");\r\n\r\n // safety check\r\n if (this.components[name]) {\r\n defineWebComponent(this.components[name], useShadowDOM);\r\n }\r\n }\r\n}\r\n\r\nexport const ladrillos = new Ladrillos();\r\n","/**\r\n * Global Event Bus for component-to-component communication\r\n * Allows components to emit events and listen to events from other components\r\n */\r\n\r\nimport { logger } from \"../utils/logger\";\r\n\r\ntype EventCallback = (data?: any) => void | Promise<void>;\r\ntype EventListeners = Map<string, Set<EventCallback>>;\r\n\r\nclass EventBus {\r\n private listeners: EventListeners = new Map();\r\n\r\n /**\r\n * Emit an event with optional data\r\n * @param eventName - The name of the event to emit\r\n * @param data - Optional data to pass to listeners\r\n * @returns Promise that resolves when all listeners have been called\r\n */\r\n emit(eventName: string, data?: any): Promise<void> {\r\n // Also dispatch as a native DOM CustomEvent so document.addEventListener works\r\n const customEvent = new CustomEvent(eventName, {\r\n detail: data,\r\n bubbles: true,\r\n composed: true,\r\n });\r\n document.dispatchEvent(customEvent);\r\n\r\n const callbacks = this.listeners.get(eventName);\r\n\r\n if (!callbacks || callbacks.size === 0) {\r\n // No listeners, resolve immediately\r\n return Promise.resolve();\r\n }\r\n\r\n // Execute all callbacks and collect promises\r\n const promises: Promise<void>[] = [];\r\n\r\n callbacks.forEach((callback) => {\r\n try {\r\n const result = callback(data);\r\n // If callback returns a promise, add it to promises array\r\n if (result instanceof Promise) {\r\n promises.push(result);\r\n }\r\n } catch (error) {\r\n logger.error(\r\n `⚠️ Event Bus Error: Failed to execute listener for \"${eventName}\"`\r\n );\r\n logger.error(` Error details: ${(error as Error).message}`);\r\n promises.push(Promise.reject(error));\r\n }\r\n });\r\n\r\n // If any callbacks returned promises, wait for all of them\r\n if (promises.length > 0) {\r\n return Promise.all(promises).then(() => undefined);\r\n }\r\n\r\n return Promise.resolve();\r\n }\r\n\r\n /**\r\n * Listen to an event\r\n * @param eventName - The name of the event to listen for\r\n * @param callback - Function to call when event is emitted\r\n * @returns Function to remove the listener\r\n */\r\n listen(eventName: string, callback: EventCallback): () => void {\r\n if (!this.listeners.has(eventName)) {\r\n this.listeners.set(eventName, new Set());\r\n }\r\n\r\n this.listeners.get(eventName)!.add(callback);\r\n\r\n // Return unsubscribe function\r\n return () => {\r\n this.off(eventName, callback);\r\n };\r\n }\r\n\r\n /**\r\n * Remove a specific event listener\r\n * @param eventName - The name of the event\r\n * @param callback - The callback to remove\r\n */\r\n off(eventName: string, callback: EventCallback): void {\r\n const callbacks = this.listeners.get(eventName);\r\n if (callbacks) {\r\n callbacks.delete(callback);\r\n // Clean up empty sets\r\n if (callbacks.size === 0) {\r\n this.listeners.delete(eventName);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Remove all listeners for an event, or all listeners if no event specified\r\n * @param eventName - Optional event name to clear listeners for\r\n */\r\n clear(eventName?: string): void {\r\n if (eventName) {\r\n this.listeners.delete(eventName);\r\n } else {\r\n this.listeners.clear();\r\n }\r\n }\r\n\r\n /**\r\n * Get count of listeners for an event\r\n * @param eventName - The event name\r\n * @returns Number of listeners\r\n */\r\n listenerCount(eventName: string): number {\r\n return this.listeners.get(eventName)?.size ?? 0;\r\n }\r\n}\r\n\r\n// Export singleton instance\r\nexport const eventBus = new EventBus();\r\n","export default {}","import { Plugin } from \"vite\";\r\nimport fs from \"fs/promises\";\r\nimport fsSync from \"fs\";\r\nimport path from \"path\";\r\n\r\nexport interface CopyComponentsOptions {\r\n /**\r\n * Source directory containing components to copy\r\n * @default 'components'\r\n */\r\n src?: string;\r\n /**\r\n * Destination directory in the dist folder\r\n * @default 'components'\r\n */\r\n dest?: string;\r\n /**\r\n * Whether to copy during development\r\n * @default false\r\n */\r\n copyOnDev?: boolean;\r\n /**\r\n * Whether to process component module scripts\r\n * @default true\r\n */\r\n processScripts?: boolean;\r\n}\r\n\r\n/**\r\n * Process component HTML files to transform module scripts\r\n */\r\nasync function processComponentScripts(dir: string): Promise<void> {\r\n const entries = await fs.readdir(dir, { withFileTypes: true });\r\n\r\n for (const entry of entries) {\r\n const filePath = path.resolve(dir, entry.name);\r\n\r\n if (entry.isDirectory()) {\r\n await processComponentScripts(filePath);\r\n } else if (entry.name.endsWith(\".html\")) {\r\n let content = await fs.readFile(filePath, \"utf-8\");\r\n\r\n // Transform module scripts to work with window scope\r\n content = content.replace(\r\n /<script type=\"module\">([\\s\\S]*?)<\\/script>/g,\r\n (match, scriptContent) => {\r\n // Transform bare module specifiers to window references\r\n let transformedCode = scriptContent\r\n .replace(\r\n /import\\s+\\*\\s+as\\s+(\\w+)\\s+from\\s+[\"']ladrillosjs[\"']/g,\r\n \"const $1 = window.ladrillosjs;\"\r\n )\r\n .replace(\r\n /import\\s+\\{\\s*([^}]+)\\s*\\}\\s+from\\s+[\"']ladrillosjs[\"']/g,\r\n \"const { $1 } = window.ladrillosjs;\"\r\n )\r\n .replace(\r\n /import\\s+(\\w+)\\s+from\\s+[\"']ladrillosjs[\"']/g,\r\n \"const $1 = window.ladrillosjs.default;\"\r\n );\r\n\r\n // Create a wrapper that uses a shared promise for library loading\r\n return `<script>\r\n(async () => {\r\n try {\r\n // Use a shared promise to avoid multiple components polling independently\r\n if (!window.__ladrillosPromise__) {\r\n if (window.ladrillosjs) {\r\n // Library already loaded, resolve immediately\r\n window.__ladrillosPromise__ = Promise.resolve(window.ladrillosjs);\r\n } else {\r\n // Set up a one-time promise that waits for library to load\r\n window.__ladrillosPromise__ = new Promise((resolve) => {\r\n // Quick check first\r\n if (window.ladrillosjs) {\r\n resolve(window.ladrillosjs);\r\n return;\r\n }\r\n \r\n // Use a short timeout (libraries load almost instantly)\r\n const timeout = setTimeout(() => {\r\n if (!window.ladrillosjs) {\r\n throw new Error('LadrillosJS failed to load');\r\n }\r\n clearInterval(interval);\r\n resolve(window.ladrillosjs);\r\n }, 100);\r\n \r\n // Fallback polling as safety net\r\n const interval = setInterval(() => {\r\n if (window.ladrillosjs) {\r\n clearTimeout(timeout);\r\n clearInterval(interval);\r\n resolve(window.ladrillosjs);\r\n }\r\n }, 5);\r\n });\r\n }\r\n }\r\n \r\n // Wait for the shared promise\r\n await window.__ladrillosPromise__;\r\n \r\n // Execute the component script\r\n (async () => {\r\n${transformedCode}\r\n })();\r\n } catch (error) {\r\n console.error('Failed to execute component module:', error);\r\n }\r\n})();\r\n</script>`;\r\n }\r\n );\r\n\r\n await fs.writeFile(filePath, content);\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Vite plugin for copying component files to the dist folder during build\r\n *\r\n * @example\r\n * ```typescript\r\n * import { defineConfig } from 'vite';\r\n * import { copyComponentsPlugin } from 'ladrillosjs/vite';\r\n *\r\n * export default defineConfig({\r\n * plugins: [\r\n * copyComponentsPlugin({\r\n * src: 'components',\r\n * dest: 'components',\r\n * copyOnDev: false,\r\n * processScripts: true\r\n * })\r\n * ]\r\n * });\r\n * ```\r\n */\r\nexport function copyComponentsPlugin(\r\n options: CopyComponentsOptions = {}\r\n): Plugin {\r\n const {\r\n src = \"components\",\r\n dest = \"components\",\r\n copyOnDev = false,\r\n processScripts = true,\r\n } = options;\r\n\r\n return {\r\n name: \"ladrillosjs:copy-components\",\r\n apply: copyOnDev ? \"serve\" : \"build\",\r\n\r\n async generateBundle(_options, bundle) {\r\n const srcDir = path.resolve(process.cwd(), src);\r\n const distDestDir = path.resolve(process.cwd(), \"dist\", dest);\r\n\r\n // Only proceed if source directory exists\r\n if (!fsSync.existsSync(srcDir)) {\r\n console.warn(\r\n `[ladrillosjs:copy-components] Source directory not found: ${srcDir}`\r\n );\r\n return;\r\n }\r\n\r\n try {\r\n // Remove existing destination directory if it exists\r\n if (fsSync.existsSync(distDestDir)) {\r\n fsSync.rmSync(distDestDir, { recursive: true, force: true });\r\n }\r\n\r\n // Copy components folder to dist\r\n fsSync.cpSync(srcDir, distDestDir, { recursive: true });\r\n console.log(\r\n `[ladrillosjs:copy-components] Copied components from ${srcDir} to ${distDestDir}`\r\n );\r\n\r\n // Process component scripts if enabled\r\n if (processScripts) {\r\n await processComponentScripts(distDestDir);\r\n console.log(\r\n `[ladrillosjs:copy-components] Processed component scripts in ${distDestDir}`\r\n );\r\n }\r\n } catch (error) {\r\n console.error(\r\n `[ladrillosjs:copy-components] Error copying components:`,\r\n error\r\n );\r\n throw error;\r\n }\r\n },\r\n };\r\n}\r\n\r\nexport default copyComponentsPlugin;\r\n","import { ladrillos } from \"./core/main.js\";\r\nimport { eventBus } from \"./core/eventBus.js\";\r\nimport { ComponentRegistration } from \"./types/LadrilloTypes.js\";\r\n\r\n// Re-export vite plugin\r\nexport {\r\n copyComponentsPlugin,\r\n type CopyComponentsOptions,\r\n} from \"./vite/index.js\";\r\n\r\ndeclare global {\r\n interface Window {\r\n ladrillosjs: {\r\n registerComponent: typeof registerComponent;\r\n registerComponents: typeof registerComponents;\r\n };\r\n $listen: typeof $listen;\r\n $emit: typeof $emit;\r\n $querySelector: typeof $querySelector;\r\n $querySelectorAll: typeof $querySelectorAll;\r\n $reactive: typeof $reactive;\r\n $setState: typeof $setState;\r\n $getState: typeof $getState;\r\n }\r\n}\r\n\r\nexport const registerComponent = (\r\n name: string,\r\n path: string,\r\n useShadowDOM?: boolean,\r\n lazy?: boolean\r\n) => ladrillos.registerComponent(name, path, useShadowDOM, lazy);\r\n\r\nexport const registerComponents = async (\r\n components: ComponentRegistration[]\r\n): Promise<void> => {\r\n await Promise.all(\r\n components.map(({ name, path, useShadowDOM, lazy }) =>\r\n ladrillos.registerComponent(name, path, useShadowDOM, lazy)\r\n )\r\n );\r\n};\r\n\r\n// Event bus helper functions\r\nexport const $listen = (event: string, callback: (data?: any) => void) => {\r\n return eventBus.listen(event, callback);\r\n};\r\n\r\nexport const $emit = (event: string, data?: any) => {\r\n eventBus.emit(event, data);\r\n};\r\n\r\n// Component context management\r\n// Maps script URLs to their component contexts for persistent association\r\nconst scriptContextMap = new Map<\r\n string,\r\n { shadowRoot?: ShadowRoot; element?: HTMLElement }\r\n>();\r\nconst activeContext: { shadowRoot?: ShadowRoot; element?: HTMLElement } | null =\r\n null;\r\n\r\n/**\r\n * Internal: Set component context for a script\r\n * Called by the framework when loading scripts from components\r\n */\r\nexport const __setComponentContext = (\r\n shadowRoot?: ShadowRoot,\r\n element?: HTMLElement\r\n) => {\r\n // Store in the global registry by component tag name\r\n if (element) {\r\n const tagName = element.tagName.toLowerCase();\r\n if (!(window as any).__ladrilloContexts) {\r\n (window as any).__ladrilloContexts = new Map();\r\n }\r\n (window as any).__ladrilloContexts.set(tagName, { shadowRoot, element });\r\n }\r\n};\r\n\r\n/**\r\n * Internal: Get component context for the current script\r\n */\r\nconst getComponentContext = () => {\r\n const registry = (window as any).__ladrilloContexts as Map<string, any>;\r\n if (registry && registry.size > 0) {\r\n // For now, return the last registered context\r\n // TODO: In the future, we could track which script belongs to which component\r\n const contexts = Array.from(registry.values());\r\n return contexts[contexts.length - 1];\r\n }\r\n return null;\r\n};\r\n\r\n/**\r\n * Get the component's reactive state\r\n * Returns a Proxy that allows direct property access to component.state\r\n * @returns Proxy to component state or empty object if no component context\r\n */\r\nexport const $getState = (): any => {\r\n const ctx = getComponentContext();\r\n if (ctx && ctx.element) {\r\n return (ctx.element as any).state || {};\r\n }\r\n return {};\r\n};\r\n\r\n/**\r\n * Set component state\r\n * @param updates - Object with state updates\r\n */\r\nexport const $setState = (updates: any) => {\r\n const ctx = getComponentContext();\r\n if (ctx && ctx.setState) {\r\n ctx.setState(updates);\r\n }\r\n};\r\n\r\n/**\r\n * Creates a reactive variable that automatically updates the component when changed.\r\n * For use in ES module scripts with the bind attribute.\r\n * @param name - The variable name (must match the binding in the template)\r\n * @param initialValue - The initial value\r\n * @returns A setter function to update the value\r\n *\r\n * @example\r\n * ```javascript\r\n * import { $reactive } from 'ladrillosjs';\r\n *\r\n * // In your module script:\r\n * const setBeers = $reactive('beers', 'loading...');\r\n *\r\n * // Later, update it:\r\n * setBeers('<card>...</card>');\r\n * ```\r\n */\r\nexport const $reactive = <T = any>(\r\n name: string,\r\n initialValue: T\r\n): ((value: T) => void) => {\r\n // Initialize the state\r\n $setState({ [name]: initialValue });\r\n\r\n // Return a setter function\r\n return (value: T) => {\r\n $setState({ [name]: value });\r\n };\r\n};\r\n\r\n// DOM query helpers with smart component context detection\r\n// Automatically searches within component context when appropriate\r\nexport const $querySelector = (\r\n selector: string,\r\n root?: Element | Document | ShadowRoot\r\n): Element | null => {\r\n if (root) {\r\n return root.querySelector(selector);\r\n }\r\n\r\n // Try to get component context\r\n const ctx = getComponentContext();\r\n if (ctx) {\r\n const searchRoot = ctx.shadowRoot || ctx.element;\r\n if (searchRoot) {\r\n const result = searchRoot.querySelector(selector);\r\n if (result) return result;\r\n }\r\n }\r\n\r\n // Fallback to document\r\n return document.querySelector(selector);\r\n};\r\n\r\nexport const $querySelectorAll = (\r\n selector: string,\r\n root?: Element | Document | ShadowRoot\r\n): NodeListOf<Element> => {\r\n if (root) {\r\n return root.querySelectorAll(selector);\r\n }\r\n\r\n // Try to get component context\r\n const ctx = getComponentContext();\r\n if (ctx) {\r\n const searchRoot = ctx.shadowRoot || ctx.element;\r\n if (searchRoot) {\r\n const result = searchRoot.querySelectorAll(selector);\r\n if (result.length > 0) return result;\r\n }\r\n }\r\n\r\n // Fallback to document\r\n return document.querySelectorAll(selector);\r\n};\r\n\r\n// for a browser‑global via <script src=\"…ladrillosjs.js\"></script>\r\nif (typeof window !== \"undefined\") {\r\n window.ladrillosjs = {\r\n registerComponent,\r\n registerComponents,\r\n };\r\n\r\n // Expose helper functions globally for non-module scripts\r\n window.$listen = $listen;\r\n window.$emit = $emit;\r\n window.$querySelector = $querySelector;\r\n window.$querySelectorAll = $querySelectorAll;\r\n window.$reactive = $reactive;\r\n window.$setState = $setState;\r\n window.$getState = $getState;\r\n}\r\n"],"names":["isDevelopment","e","logger","message","args","formatErrorMessage","context","parts","logBindingError","expression","error","errorMessage","__spreadProps","__spreadValues","logEventHandlerError","eventType","handlerCode","logConditionalError","condition","logLoopError","loopExpression","logRegistrationError","componentName","componentPath","logFetchError","url","logParseError","logScriptError","logTwoWayBindingError","createErrorContext","component","additionalContext","_a","cache","maxCacheSize","getCached","path","cached","setCache","content","firstKey","fetchComponentSource","__async","response","text","safeFetch","res","err","REGEX_PATTERNS","stripComments","code","result","i","char","quote","c","nextChar","beforeWord","parser","parseComponent","source","name","componentUrl","doc","parseComponentHTML","scripts","externalScripts","extractScripts","styles","extractStyles","template","isDevServerScript","src","pattern","el","isExternal","_b","resolveCSSPath","href","componentBase","extractCSSFromResponse","viteMatch","exportMatch","style","styleElements","element","resolvedPath","cssContent","styleEl","css","Ladrillos","__privateAdd","_Ladrillos_instances","useShadowDOM","lazy","__privateMethod","defineLazyPlaceholder_fn","defineWebComponent_fn","self","LazyPlaceholder","entries","entry","loadingPromise","parent","tempName","originalTagName","defineWebComponent","placeholder","nextSibling","realComponent","attr","ladrillos","EventBus","eventName","data","customEvent","callbacks","promises","callback","eventBus","fsSync","processComponentScripts","dir","fs","filePath","match","scriptContent","copyComponentsPlugin","options","dest","copyOnDev","processScripts","_options","bundle","srcDir","distDestDir","registerComponent","registerComponents","components","$listen","event","$emit","__setComponentContext","shadowRoot","tagName","getComponentContext","registry","contexts","$getState","ctx","$setState","updates","$reactive","initialValue","value","$querySelector","selector","root","searchRoot","$querySelectorAll"],"mappings":"u3BAKA,MAAMA,EAAgB,IAAe,CACnC,GAAI,CACF,MAAQ,EACV,OAAQC,EAAA,CACN,OAAO,QAAQ,IAAI,WAAa,aAClC,CACF,EAEaC,EAAS,CAMpB,IAAIC,KAAoBC,EAAmB,CACrCJ,KACF,QAAQ,IAAIG,EAAS,GAAGC,CAAI,CAEhC,EAOA,MAAMD,KAAoBC,EAAmB,CAC3C,QAAQ,MAAMD,EAAS,GAAGC,CAAI,CAChC,EAOA,KAAKD,K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