ladrillosjs 1.0.2 → 2.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +533 -105
  2. package/dist/cache/functionCache.d.ts +15 -0
  3. package/dist/cache/index.d.ts +16 -0
  4. package/dist/core/componentParser.d.ts +29 -0
  5. package/dist/core/componentSource.d.ts +12 -0
  6. package/dist/core/css/cssParser.d.ts +3 -0
  7. package/dist/core/eventBus.d.ts +41 -0
  8. package/dist/core/html/htmlRenderer.d.ts +18 -0
  9. package/dist/core/html/htmlparser.d.ts +16 -0
  10. package/dist/core/js/scriptParser.d.ts +3 -0
  11. package/dist/core/main.d.ts +4 -26
  12. package/dist/core/webcomponent.d.ts +2 -2
  13. package/dist/index-CXHidyhO.js +8 -0
  14. package/dist/index-CXHidyhO.js.map +1 -0
  15. package/dist/index-VkDZJVOR.mjs +361 -0
  16. package/dist/index-VkDZJVOR.mjs.map +1 -0
  17. package/dist/index.d.ts +56 -6
  18. package/dist/ladrillosjs.cjs.js +2 -1
  19. package/dist/ladrillosjs.cjs.js.map +1 -0
  20. package/dist/ladrillosjs.es.js +12 -4
  21. package/dist/ladrillosjs.es.js.map +1 -0
  22. package/dist/ladrillosjs.umd.js +76 -18
  23. package/dist/ladrillosjs.umd.js.map +1 -0
  24. package/dist/types/LadrilloTypes.d.ts +47 -14
  25. package/dist/utils/logger.d.ts +14 -11
  26. package/dist/utils/regex.d.ts +2 -0
  27. package/dist/webcomponent-CJ3lZBZb.mjs +703 -0
  28. package/dist/webcomponent-CJ3lZBZb.mjs.map +1 -0
  29. package/dist/webcomponent-i9W7LUiv.js +70 -0
  30. package/dist/webcomponent-i9W7LUiv.js.map +1 -0
  31. package/package.json +8 -4
  32. package/dist/core/store.d.ts +0 -6
  33. package/dist/index-D_dHFObN.mjs +0 -215
  34. package/dist/index-X9YN_DbT.js +0 -3
  35. package/dist/utils/stringify.d.ts +0 -7
  36. package/dist/webcomponent-Cga3h8cx.js +0 -16
  37. package/dist/webcomponent-UTcwAakf.mjs +0 -769
@@ -1,769 +0,0 @@
1
- var q = (m) => {
2
- throw TypeError(m);
3
- };
4
- var J = (m, b, y) => b.has(m) || q("Cannot " + y);
5
- var P = (m, b, y) => b.has(m) ? q("Cannot add the same private member more than once") : b instanceof WeakSet ? b.add(m) : b.set(m, y);
6
- var j = (m, b, y) => (J(m, b, "access private method"), y);
7
- var H = (m, b, y) => new Promise((x, B) => {
8
- var O = (E) => {
9
- try {
10
- T(y.next(E));
11
- } catch (F) {
12
- B(F);
13
- }
14
- }, L = (E) => {
15
- try {
16
- T(y.throw(E));
17
- } catch (F) {
18
- B(F);
19
- }
20
- }, T = (E) => E.done ? x(E.value) : Promise.resolve(E.value).then(O, L);
21
- T((y = y.apply(m, b)).next());
22
- });
23
- import { l as w } from "./index-D_dHFObN.mjs";
24
- function D(m, b) {
25
- return JSON.stringify(
26
- m,
27
- (y, x) => typeof x == "string" ? x.replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r") : x,
28
- b
29
- ).replace(/"/g, """);
30
- }
31
- const G = (m, b) => {
32
- var E, Z;
33
- const { tagName: y, template: x, scripts: B, externalScripts: O, style: L } = m, W = class W extends HTMLElement {
34
- constructor() {
35
- super(), b && this.attachShadow({ mode: "open" }), this.root = b ? this.shadowRoot : document, this.stringify = D;
36
- const t = {};
37
- this.state = new Proxy(t, {
38
- set: (n, e, s) => (n[e] = s, this._render(), !0)
39
- }), this._bindings = [], this._eventBindings = [], this._conditionals = [], this._initObservers();
40
- }
41
- // Invoked when the custom element is first connected to the document's DOM.
42
- connectedCallback() {
43
- this._loadTemplate(), this._loadStyles(), this._initializeStateFromAttributes(), this._loadScript(), this._setupTwoWayBindings();
44
- }
45
- // Invoked when the custom element is disconnected from the document's DOM.
46
- disconnectedCallback() {
47
- this.observer.disconnect(), this._eventBindings.forEach(({ element: t, event: n, listener: e }) => {
48
- t.removeEventListener(n, e);
49
- }), this._eventBindings = [];
50
- }
51
- _initObservers() {
52
- this.observer = this._createObserver(
53
- (t) => {
54
- t.forEach((n) => {
55
- if (n.type === "attributes") {
56
- const e = n.attributeName, s = this.getAttribute(e);
57
- this._handleAttributeChange(e, s);
58
- }
59
- });
60
- },
61
- this,
62
- { attributes: !0, attributeOldValue: !0 }
63
- ), this.elementObserver = this._createObserver(
64
- (t) => {
65
- for (const n of t)
66
- if (n.attributeName === "contenteditable") {
67
- const e = (
68
- /** @type {HTMLElement} */
69
- n.target
70
- );
71
- e.isContentEditable && e.hasAttribute("data-bind") && this._bindTwoWayForElement(e);
72
- }
73
- },
74
- this.root,
75
- {
76
- attributes: !0,
77
- subtree: !0,
78
- attributeFilter: ["contenteditable"]
79
- }
80
- );
81
- }
82
- // creates a MutationObserver and binds it to the target element
83
- _createObserver(t, n, e) {
84
- const s = new MutationObserver(t.bind(this));
85
- return s.observe(n, e), s;
86
- }
87
- // Invoked when attributes are changed.
88
- _handleAttributeChange(t, n) {
89
- var s;
90
- if (t) {
91
- const i = "this.state.";
92
- t.startsWith(i) && (t = t.slice(i.length));
93
- }
94
- const e = j(s = W, E, Z).call(s, n);
95
- this.state[t] = e, this._render();
96
- }
97
- // sets template to innerHTML or shadowRoot.innerHTML
98
- _loadTemplate() {
99
- b ? this.shadowRoot.innerHTML = x : this.innerHTML = x, this._scanBindings();
100
- }
101
- // scans the template for bindings and event handlers
102
- // and stores them in this._bindings and this._eventBindings
103
- _scanBindings() {
104
- const t = document.createTreeWalker(
105
- this.root,
106
- NodeFilter.SHOW_TEXT,
107
- null,
108
- !1
109
- );
110
- let n;
111
- for (; n = t.nextNode(); ) {
112
- const e = [...n.textContent.matchAll(/{([^}]+)}/g)];
113
- if (e.length) {
114
- const s = e.map(([, i]) => ({
115
- node: n,
116
- template: n.textContent,
117
- key: i.trim()
118
- }));
119
- this._bindings.push(s);
120
- }
121
- }
122
- this.root.querySelectorAll("*").forEach((e) => {
123
- Array.from(e.attributes).forEach((s) => {
124
- const i = [...s.value.matchAll(/{([^}]+)}/g)];
125
- i.length && i.forEach(([, r]) => {
126
- this._bindings.push({
127
- element: e,
128
- attrName: s.name,
129
- template: s.value,
130
- key: r.trim()
131
- });
132
- });
133
- });
134
- }), this._getEventBindings(), this._scanConditionals();
135
- }
136
- // scans the template for event handlers and stores them in this._eventBindings
137
- // e.g. onclick="handleClick"
138
- _getEventBindings() {
139
- this.root.querySelectorAll("*").forEach((t) => {
140
- Array.from(t.attributes).forEach((n) => {
141
- if (!n.name.startsWith("on")) return;
142
- const e = n.name.slice(2), s = n.value.trim();
143
- t.removeAttribute(n.name);
144
- let i;
145
- const r = s.trim();
146
- if (/^\([^)]*\)\s*=>/.test(r))
147
- try {
148
- const c = new Function("event", `return (${r});`).call(this);
149
- i = (u) => c(u);
150
- } catch (l) {
151
- w.error(
152
- `Error parsing inline arrow function handler: ${r}`,
153
- l
154
- ), i = () => {
155
- };
156
- }
157
- else r.includes("(") && r.includes(")") ? i = (l) => {
158
- try {
159
- const c = r.match(
160
- /^([a-zA-Z_$][0-9a-zA-Z_$]*)\s*\((.*)\)$/
161
- );
162
- if (c) {
163
- const [, u, S] = c, N = this[u] || this.state[u];
164
- if (typeof N == "function") {
165
- let A = [];
166
- if (S.trim())
167
- try {
168
- A = new Function(
169
- "event",
170
- `return [${S}]`
171
- ).call(this, l);
172
- } catch (k) {
173
- w.error(
174
- `Error parsing arguments for ${u}:`,
175
- k
176
- ), A = [];
177
- }
178
- return N.apply(this, A);
179
- } else
180
- w.warn(
181
- `Function "${u}" not found in component context. Available functions:`,
182
- Object.keys(this).filter((A) => typeof this[A] == "function").concat(
183
- Object.keys(this.state).filter(
184
- (A) => typeof this.state[A] == "function"
185
- )
186
- )
187
- );
188
- } else
189
- new Function("event", r).call(this, l);
190
- } catch (c) {
191
- w.error(
192
- `Error executing inline event handler: ${r}`,
193
- c
194
- );
195
- }
196
- } : i = (l) => {
197
- const c = this[r];
198
- if (typeof c == "function")
199
- try {
200
- return c.call(this, l);
201
- } catch (u) {
202
- w.error(
203
- `Error executing event handler method: ${r}`,
204
- u
205
- );
206
- }
207
- else
208
- w.warn(
209
- `Event handler method "${r}" not found on component. Available methods on 'this':`,
210
- Object.keys(this).filter((u) => typeof this[u] == "function")
211
- );
212
- };
213
- t.addEventListener(e, i), this._eventBindings.push({
214
- key: s,
215
- element: t,
216
- event: e,
217
- listener: i
218
- });
219
- });
220
- });
221
- }
222
- // scans the template for conditional elements and stores them in this._conditionals
223
- // e.g. data-if, data-else-if, data-else
224
- _scanConditionals() {
225
- this._conditionals = [];
226
- const t = Array.from(
227
- this.root.querySelectorAll("[data-if], [data-else-if], [data-else]")
228
- );
229
- let n = [];
230
- t.forEach((e) => {
231
- const s = e.hasAttribute("data-if");
232
- s && n.length && (this._conditionals.push(n), n = []);
233
- const i = s ? "if" : e.hasAttribute("data-else-if") ? "else-if" : "else", r = i === "else" ? null : e.getAttribute(i === "if" ? "data-if" : "data-else-if"), l = document.createComment(`ladrillos-${i}`);
234
- e.parentNode.insertBefore(l, e), e.remove(), n.push({ el: e, type: i, expr: r, placeholder: l });
235
- }), n.length && this._conditionals.push(n);
236
- }
237
- // loads the styles into the shadowRoot or document head
238
- _loadStyles() {
239
- if (!L) return;
240
- const t = document.createElement("style");
241
- t.textContent = L, b ? this.root.appendChild(t) : this.root.head.appendChild(t);
242
- }
243
- // loads the external scripts and inline scripts
244
- // and binds them to the component context
245
- _loadScript() {
246
- return H(this, null, function* () {
247
- var t;
248
- for (const n of O) {
249
- const e = new URL(n.src, import.meta.url).href;
250
- if (n.type === "module" && (n != null && n.bind))
251
- try {
252
- const s = yield import(e);
253
- typeof s.default == "function" ? s.default.call(this) : typeof s.init == "function" ? s.init.call(this) : w.error(
254
- `Module ${n.src} does not export a default function or init function.`
255
- );
256
- } catch (s) {
257
- w.error(`Failed to load component module ${n.src}`, s);
258
- }
259
- else n != null && n.bind ? yield fetch(e).then((s) => s.text()).then(
260
- (s) => this._processScriptText(
261
- s.replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gm, "").trim()
262
- )
263
- ) : yield this._injectScriptTag(n.src, n.type);
264
- }
265
- for (const n of B)
266
- if (n.type === "module") {
267
- const e = document.createElement("script");
268
- e.type = "module", e.textContent = n.content, ((t = this.shadowRoot) != null ? t : this).appendChild(e);
269
- } else
270
- this._processScriptText(n.content);
271
- this._render();
272
- });
273
- }
274
- // injects a script tag into the document head
275
- // and returns a promise that resolves when the script is loaded
276
- _injectScriptTag(t, n) {
277
- return new Promise((e, s) => {
278
- const i = document.createElement("script");
279
- i.src = t, n && (i.type = n), i.onload = e, i.onerror = s, document.head.appendChild(i);
280
- });
281
- }
282
- // initializes the state from the attributes
283
- _initializeStateFromAttributes() {
284
- this.getAttributeNames().forEach((t) => {
285
- const n = this.getAttribute(t);
286
- this._handleAttributeChange(t, n);
287
- });
288
- }
289
- /**
290
- * Set a nested value on this.state and re-render.
291
- * @param {string} path dot-delimited path
292
- * @param {*} value
293
- */
294
- _setNestedState(t, n) {
295
- const e = t.split(".");
296
- let s = this.state;
297
- for (let i = 0; i < e.length - 1; i++) {
298
- const r = e[i];
299
- (typeof s[r] != "object" || s[r] === null) && (s[r] = {}), s = s[r];
300
- }
301
- s[e[e.length - 1]] = n, this._render();
302
- }
303
- _bindTwoWayForElement(t) {
304
- const n = t.getAttribute("data-bind"), e = t.isContentEditable, s = "value" in t, i = e || s ? "input" : "change", r = () => {
305
- const S = e ? t.innerText : s ? t.value : t.textContent;
306
- this._setNestedState(n, S);
307
- };
308
- t.addEventListener(i, r), this._eventBindings.push({ element: t, event: i, listener: r });
309
- const l = s ? "value" : void 0, c = s ? t.getAttribute("value") || `{${n}}` : e ? t.innerHTML : t.textContent;
310
- this._bindings.push({ element: t, key: n, attrName: l, template: c });
311
- const u = s ? t.value : e ? t.innerText : t.textContent;
312
- this._setNestedState(n, u);
313
- }
314
- // sets up two-way bindings for editable elements
315
- // e.g. <input data-bind="name" value="{name}">
316
- _setupTwoWayBindings() {
317
- const t = this.root.querySelectorAll("[data-bind]"), n = {}, e = (s, i, r) => {
318
- const l = i.split(".");
319
- let c = s;
320
- for (let u = 0; u < l.length - 1; u++) {
321
- const S = l[u];
322
- (typeof c[S] != "object" || c[S] === null) && (c[S] = {}), c = c[S];
323
- }
324
- c[l[l.length - 1]] = r;
325
- };
326
- t.forEach((s) => {
327
- const i = s.getAttribute("data-bind"), r = s.isContentEditable, l = "value" in s, c = r ? s.innerText.trim() : l ? s.value : s.textContent.trim();
328
- e(n, i, c);
329
- }), this.setState(n), t.forEach((s) => {
330
- this._bindTwoWayForElement(s);
331
- });
332
- }
333
- // renders the component by replacing the bindings with their values
334
- // and executing the event handlers
335
- _render() {
336
- this._applyConditionals(), this._bindings.forEach((t) => {
337
- const n = Array.isArray(t) ? t : [t], { node: e, template: s } = n[0];
338
- if (!e) return;
339
- const i = {};
340
- n.forEach(({ key: c }) => {
341
- var u;
342
- i[c] = (u = this.state[c]) != null ? u : "";
343
- });
344
- const r = this._renderTemplate(s, i);
345
- if (/<[a-z][\s\S]*>/i.test(r)) {
346
- const c = document.createRange().createContextualFragment(r);
347
- e.nodeType === Node.TEXT_NODE ? e.replaceWith(c) : e.innerHTML = r;
348
- } else
349
- e == null || e.nodeType, Node.TEXT_NODE, e.textContent = r;
350
- }), this._bindings.filter((t) => t.element).forEach(({ element: t, attrName: n, template: e, key: s }) => {
351
- var l;
352
- const i = (l = s.split(".").reduce((c, u) => c == null ? void 0 : c[u], this.state)) != null ? l : "", r = new RegExp(`\\{\\s*${s}\\s*\\}`, "g");
353
- t.setAttribute(n, e.replace(r, i));
354
- }), this.root.querySelectorAll("[data-bind]").forEach((t) => {
355
- var s;
356
- const e = (s = t.getAttribute("data-bind").split(".").reduce((i, r) => i == null ? void 0 : i[r], this.state)) != null ? s : "";
357
- t.isContentEditable ? t.innerText !== e && (t.innerText = e) : "value" in t ? t.value !== e && (t.value = e) : t.textContent !== e && (t.textContent = e);
358
- });
359
- }
360
- // applies the conditionals to the elements
361
- _applyConditionals() {
362
- this._conditionals.forEach((t) => {
363
- let n = !1;
364
- t.forEach(({ el: e, type: s, expr: i, placeholder: r }) => {
365
- let l = !1;
366
- if (s === "else")
367
- l = !n;
368
- else
369
- try {
370
- l = Function(
371
- "state",
372
- `with(state){return(${i})}`
373
- )(this.state);
374
- } catch (c) {
375
- l = !1;
376
- }
377
- l && !n ? (!e.isConnected && r.parentNode && r.parentNode.insertBefore(e, r.nextSibling), r.remove(), n = !0) : e.isConnected && e.parentNode && (e.parentNode.insertBefore(r, e), e.remove());
378
- });
379
- });
380
- }
381
- // replaces the template with the data values
382
- // e.g. {name} => "John Doe"
383
- _renderTemplate(t, n) {
384
- return t.replace(/\{\s*([-\w.]+)\s*}/g, (e, s) => {
385
- let i = s.split(".").reduce((r, l) => r == null ? void 0 : r[l], this.state);
386
- if (typeof i == "function")
387
- try {
388
- i = i.call(this);
389
- } catch (r) {
390
- i = "";
391
- }
392
- return i != null ? i : "";
393
- });
394
- }
395
- /**
396
- * 1. Identifies top-level function declarations (e.g., `function foo(){}` or `const foo = ()=>{}`).
397
- * 2. Identifies top-level variable declarations (e.g., `const bar = 123;`).
398
- * 3. Renames function parameters that conflict with bound variables to avoid shadowing.
399
- * 4. Transforms increment/decrement operations on bound variables to use this.state
400
- * 5. Transforms references to attribute-based state variables
401
- * 6. Replaces renamed parameter references with unique names
402
- * 7. Appends assignments to `this` for bound functions (e.g., `this.foo = foo;`).
403
- * 8. Appends initialization for `this.state` for bound variables if not already set in state (e.g., `if(typeof this.state.bar === 'undefined') this.state.bar = bar;`).
404
- * 9. Executes the combined script in the component's context (`this`).
405
- */
406
- _processScriptText(t) {
407
- const n = /* @__PURE__ */ new Set(), e = /* @__PURE__ */ new Set(), s = /* @__PURE__ */ new Set(), i = /* @__PURE__ */ new Map(), r = (o) => `__param_${o}_${Math.random().toString(36).substr(2, 9)}`, l = (o, $) => {
408
- let f = !1, a = !1, h = !1, g = !1;
409
- for (let d = 0; d < $; d++) {
410
- const p = o[d];
411
- if (g) {
412
- g = !1;
413
- continue;
414
- }
415
- if (p === "\\") {
416
- g = !0;
417
- continue;
418
- }
419
- p === "'" && !a && !h ? f = !f : p === '"' && !f && !h ? a = !a : p === "`" && !f && !a && (h = !h);
420
- }
421
- return f || a || h;
422
- }, c = (o, $, f) => {
423
- let a = o;
424
- const h = [];
425
- let g;
426
- for ($.lastIndex = 0; (g = $.exec(a)) !== null; )
427
- h.push({
428
- index: g.index,
429
- length: g[0].length,
430
- originalContent: g[0],
431
- groups: g.slice(1)
432
- });
433
- for (let d = h.length - 1; d >= 0; d--) {
434
- const p = h[d];
435
- if (!l(a, p.index)) {
436
- const _ = f(
437
- p.originalContent,
438
- ...p.groups,
439
- p.index,
440
- a
441
- );
442
- a = a.substring(0, p.index) + _ + a.substring(p.index + p.length);
443
- }
444
- }
445
- return a;
446
- };
447
- Object.keys(this.state).forEach((o) => {
448
- this._isBound(o) && s.add(o);
449
- });
450
- let u = t;
451
- u = c(
452
- u,
453
- /\b(function\s+\w+\s*|const\s+\w+\s*=\s*|let\s+\w+\s*=\s*|var\s+\w+\s*=\s*)*\(([^)]*)\)\s*=>/g,
454
- (o, $, f) => {
455
- if (!f || !f.trim()) return o;
456
- const a = f.split(",").map((d) => d.trim()).filter((d) => d);
457
- let h = !1;
458
- const g = a.map((d) => {
459
- const p = d.split("=")[0].trim().replace(/[{}[\]]/g, "");
460
- if (this._isBound(p)) {
461
- h = !0;
462
- const _ = r(p);
463
- return i.set(p, _), d.replace(p, _);
464
- }
465
- return d;
466
- });
467
- return h ? o.replace(f, g.join(", ")) : o;
468
- }
469
- ), u = c(
470
- u,
471
- /\bfunction\s+(\w+)\s*\(([^)]*)\)/g,
472
- (o, $, f) => {
473
- if (!f || !f.trim()) return o;
474
- const a = f.split(",").map((d) => d.trim()).filter((d) => d);
475
- let h = !1;
476
- const g = a.map((d) => {
477
- const p = d.split("=")[0].trim().replace(/[{}[\]]/g, "");
478
- if (this._isBound(p)) {
479
- h = !0;
480
- const _ = r(p);
481
- return i.set(p, _), d.replace(p, _);
482
- }
483
- return d;
484
- });
485
- return h ? o.replace(f, g.join(", ")) : o;
486
- }
487
- );
488
- const A = /\bfunction\s+([a-zA-Z_$][0-9a-zA-Z_$]*)\s*\(/g;
489
- let k;
490
- for (; (k = A.exec(t)) !== null; )
491
- n.add(k[1]);
492
- const I = /\b(const|let|var)\s+([a-zA-Z_$][0-9a-zA-Z_$]*)\s*=/g;
493
- for (; (k = I.exec(t)) !== null; )
494
- n.add(k[2]);
495
- n.forEach((o) => {
496
- this._isBound(o) && (new RegExp(
497
- `\\b${o}\\s*=\\s*(?:function|\\([^)]*\\)\\s*=>|[^=]+=>)`,
498
- "g"
499
- ).test(t) || new RegExp(`\\bfunction\\s+${o}\\s*\\(`).test(t) || e.add(o));
500
- }), (/* @__PURE__ */ new Set([
501
- ...e,
502
- ...s
503
- ])).forEach((o) => {
504
- u = c(
505
- u,
506
- new RegExp(`(^|\\W)(\\+\\+|\\-\\-)\\s*${o}\\b`, "g"),
507
- (f, a, h) => `${a}${h}this.state.${o}`
508
- ), u = c(
509
- u,
510
- new RegExp(`\\b${o}\\s*(\\+\\+|\\-\\-)(?!\\.)`, "g"),
511
- (f, a) => `this.state.${o}${a}`
512
- ), u = c(
513
- u,
514
- new RegExp(
515
- `(^|\\W)${o}\\s*([+\\-*/%&|^]|<<|>>|>>>)?=(?!=)`,
516
- "g"
517
- ),
518
- (f, a, h, g, d) => {
519
- const p = g + a.length;
520
- let _ = d.substring(
521
- Math.max(0, p - 10),
522
- p
523
- );
524
- return /\b(const|let|var)\s+$/.test(_) ? f : `${a}this.state.${o} ${h || ""}=`;
525
- }
526
- );
527
- const $ = new RegExp(
528
- `\\b${o}\\b(?!\\s*[+\\-*/%&|^]?=)`,
529
- "g"
530
- );
531
- u = c(
532
- u,
533
- $,
534
- (f, a, h) => {
535
- if (h.substring(
536
- Math.max(0, a - 11),
537
- a
538
- ).endsWith("this.state."))
539
- return f;
540
- const d = h.substring(
541
- Math.max(0, a - 20),
542
- a
543
- ), p = h.substring(
544
- a + f.length,
545
- Math.min(
546
- h.length,
547
- a + f.length + 10
548
- )
549
- );
550
- if (/[{,]\s*$/.test(d) && /^\s*:/.test(p) || i.has(o) && h.substring(
551
- Math.max(0, a - 50),
552
- a
553
- ).match(
554
- /([+\-*/%&|^]|<<|>>|>>>)?=\s*[^=]*$/
555
- ) || [
556
- "break",
557
- "case",
558
- "catch",
559
- "class",
560
- "const",
561
- "continue",
562
- "debugger",
563
- "default",
564
- "delete",
565
- "do",
566
- "else",
567
- "export",
568
- "extends",
569
- "finally",
570
- "for",
571
- "function",
572
- "if",
573
- "import",
574
- "in",
575
- "instanceof",
576
- "let",
577
- "new",
578
- "return",
579
- "super",
580
- "switch",
581
- "this",
582
- "throw",
583
- "try",
584
- "typeof",
585
- "var",
586
- "void",
587
- "while",
588
- "with",
589
- "yield"
590
- ].includes(f))
591
- return f;
592
- const v = h.lastIndexOf(`
593
- `, a) + 1, M = h.substring(v, a);
594
- if (/\b(?:const|let|var)\s+$/.test(M) || a > 0 && h[a - 1] === ".")
595
- return f;
596
- let R = a + f.length;
597
- for (; R < h.length && /\s/.test(h[R]); )
598
- R++;
599
- return R < h.length && h[R] === "(" ? f : `this.state.${o}`;
600
- }
601
- );
602
- }), i.forEach((o, $) => {
603
- const f = new RegExp(`\\b${$}\\b`, "g");
604
- u = c(
605
- u,
606
- f,
607
- (a, h, g) => {
608
- const d = g.substring(0, h);
609
- if (d.includes(o)) {
610
- let p = 0, _ = -1;
611
- for (let v = d.length - 1; v >= 0; v--)
612
- if (d[v] === "}") p++;
613
- else if (d[v] === "{" && (p--, p < 0)) {
614
- _ = v;
615
- break;
616
- }
617
- if (_ !== -1) {
618
- const v = d.substring(0, _);
619
- if (v.substring(
620
- Math.max(0, v.lastIndexOf("(", _))
621
- ).includes(o)) {
622
- if (g.substring(
623
- Math.max(0, h - 11),
624
- h
625
- ).endsWith("this.state."))
626
- return a;
627
- const V = g.substring(
628
- h + a.length,
629
- Math.min(g.length, h + a.length + 20)
630
- );
631
- return /^\s*([+\-*/%&|^]|<<|>>|>>>)?=(?!=)/.test(V) ? a : o;
632
- }
633
- }
634
- }
635
- return a;
636
- }
637
- );
638
- });
639
- let C = "";
640
- n.size > 0 && (C = `
641
-
642
- // --- Auto-processed by LadrillosJS Framework ---
643
- `, n.forEach((o) => {
644
- C += `if (this._isBound('${o}')) {
645
- `, C += ` if (typeof ${o} === 'function') {
646
- `, C += ` try { this.${o} = ${o}; } catch(e) { console.warn('LadrillosJS: Failed to assign function ${o} to component context.', e); }
647
- `, C += ` } else if (typeof ${o} !== 'undefined' && ${e.has(
648
- o
649
- )}) {
650
- `, C += ` if(typeof this.state.${o} === 'undefined') { try { this.state.${o} = ${o}; } catch(e) { console.warn('LadrillosJS: Failed to initialize state for ${o} from script.', e); } }
651
- `, C += ` }
652
- `, C += `}
653
- `;
654
- }));
655
- const z = u + C;
656
- try {
657
- new Function(z).call(this);
658
- } catch (o) {
659
- w.error("Error executing component script:", o), console.error(
660
- `LadrillosJS: Error executing component script. Processed script was:
661
- ---
662
- ` + z + `
663
- ---
664
- Error details:`,
665
- o
666
- );
667
- }
668
- }
669
- // evaluates the expression in the context of the component
670
- // and returns the result. If it fails, it tries to find the last arrow body
671
- _evalExpression(t, n, e, s) {
672
- try {
673
- return new Function(`return (${t});`).call(this);
674
- } catch (i) {
675
- let r, l;
676
- for (; r = e.exec(n); )
677
- if (this._functions.set(s, r[0]), l = r[1].trim(), l)
678
- try {
679
- return new Function(`${l}`).bind(this);
680
- } catch (c) {
681
- return w.error(c), l;
682
- }
683
- return t;
684
- }
685
- }
686
- // checks if the variable is bound in the template or event handlers
687
- // e.g. {name} or onclick="handleClick"
688
- // or data-bind="name" or value="{name}"
689
- // or if it's an attribute that exists in state
690
- _isBound(t) {
691
- if (t in this.state)
692
- return !0;
693
- const n = this._eventBindings.some((i) => {
694
- if (!i.key) return !1;
695
- if (i.key === t) return !0;
696
- const r = i.key.match(
697
- /^([a-zA-Z_$][0-9a-zA-Z_$]*)\s*\(/
698
- );
699
- return r && r[1] === t;
700
- }), e = this._bindings.some((i) => Array.isArray(i) ? i.some((r) => r.key === t || r.key.startsWith(t + ".")) : i.key === t || i.key.startsWith(t + ".")), s = this._conditionals.some(
701
- (i) => i.some(({ expr: r }) => {
702
- if (!r) return !1;
703
- const l = t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
704
- return new RegExp(`\\b${l}\\b`).test(r);
705
- })
706
- );
707
- return n || e || s;
708
- }
709
- // --- public APIs
710
- /**
711
- * Dispatch a custom event from the component.
712
- *
713
- * @param {string} name Event name
714
- * @param {*} [detail] Payload; defaults to full component state
715
- */
716
- emit(t, n) {
717
- const e = n != null ? n : this.state;
718
- this.dispatchEvent(
719
- new CustomEvent(t, {
720
- detail: e,
721
- bubbles: !0,
722
- composed: !0
723
- })
724
- );
725
- }
726
- /**
727
- * Listen for a custom event from the component.
728
- * @param {string} name Event name
729
- * @param {function} handler Callback function to handle the event
730
- */
731
- listen(t, n) {
732
- const e = (s) => n(s.detail);
733
- document.addEventListener(t, e), this._eventBindings.push({
734
- element: document,
735
- event: t,
736
- listener: e
737
- });
738
- }
739
- /**
740
- * Set the component state and re-render the component.
741
- * This method merges the new state with the existing state.
742
- * It does not replace the entire state object.
743
- * @param {*} partial
744
- */
745
- setState(t) {
746
- Object.assign(this.state, t), this._render();
747
- }
748
- querySelector(t) {
749
- return this.root.querySelector(t);
750
- }
751
- querySelectorAll(t) {
752
- return this.root.querySelectorAll(t);
753
- }
754
- };
755
- E = new WeakSet(), Z = function(t) {
756
- if (t === "") return null;
757
- if (t !== "undefined")
758
- try {
759
- return JSON.parse(t);
760
- } catch (n) {
761
- return t;
762
- }
763
- }, P(W, E);
764
- let T = W;
765
- customElements.define(y, T), w.log(`Web component defined: <${y}></${y}>`);
766
- };
767
- export {
768
- G as defineWebComponent
769
- };