buntic 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -319,6 +319,183 @@ function logError(message, err, label = "Buntic Error") {
319
319
  }
320
320
  }
321
321
 
322
+ // src/template/block-scanner.ts
323
+ function isTagNameChar(ch) {
324
+ const code = ch.charCodeAt(0);
325
+ return code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122 || code === 45 || code === 95;
326
+ }
327
+ function isAsciiLetter(ch) {
328
+ const code = ch.charCodeAt(0);
329
+ return code >= 65 && code <= 90 || code >= 97 && code <= 122;
330
+ }
331
+ function findTagClose(html, start) {
332
+ const len = html.length;
333
+ let quote = null;
334
+ for (let i = start;i < len; i++) {
335
+ const ch = html[i];
336
+ if (quote) {
337
+ if (ch === quote) {
338
+ quote = null;
339
+ }
340
+ continue;
341
+ }
342
+ if (ch === '"' || ch === "'") {
343
+ quote = ch;
344
+ } else if (ch === ">") {
345
+ return i;
346
+ }
347
+ }
348
+ return -1;
349
+ }
350
+ function skipRawElement(html, start, tagName) {
351
+ const openEnd = findTagClose(html, start + 1 + tagName.length);
352
+ if (openEnd === -1)
353
+ return html.length;
354
+ const closePattern = new RegExp(`<\\/${tagName}\\s*>`, "i");
355
+ const rest = html.slice(openEnd + 1);
356
+ const closeMatch = closePattern.exec(rest);
357
+ if (!closeMatch)
358
+ return html.length;
359
+ return openEnd + 1 + closeMatch.index + closeMatch[0].length;
360
+ }
361
+ function scanBlocks(html, targetTags, nestedScopeTags) {
362
+ const results = [];
363
+ const stack = [];
364
+ const len = html.length;
365
+ let i = 0;
366
+ while (i < len) {
367
+ const lt = html.indexOf("<", i);
368
+ if (lt === -1)
369
+ break;
370
+ i = lt;
371
+ if (html.startsWith("<!--", i)) {
372
+ const commentEnd = html.indexOf("-->", i + 4);
373
+ i = commentEnd === -1 ? len : commentEnd + 3;
374
+ continue;
375
+ }
376
+ if (html[i + 1] === "!" || html[i + 1] === "?") {
377
+ const closeIdx = html.indexOf(">", i + 2);
378
+ i = closeIdx === -1 ? len : closeIdx + 1;
379
+ continue;
380
+ }
381
+ if (html[i + 1] === "/") {
382
+ let j = i + 2;
383
+ if (j < len && isAsciiLetter(html[j])) {
384
+ const nameStart = j;
385
+ while (j < len && isTagNameChar(html[j]))
386
+ j++;
387
+ const closeTag = html.slice(nameStart, j).toLowerCase();
388
+ while (j < len && /\s/.test(html[j]))
389
+ j++;
390
+ if (j < len && html[j] === ">") {
391
+ if (stack.length > 0 && stack[stack.length - 1].tag === closeTag) {
392
+ const frame = stack.pop();
393
+ if (stack.length === 0 && frame.isTarget) {
394
+ const end = j + 1;
395
+ results.push({
396
+ tag: frame.tag,
397
+ fullMatch: html.slice(frame.start, end),
398
+ openTag: frame.openTag,
399
+ attrString: frame.attrString,
400
+ inner: html.slice(frame.openTagEnd, i),
401
+ start: frame.start,
402
+ end
403
+ });
404
+ }
405
+ }
406
+ i = j + 1;
407
+ continue;
408
+ }
409
+ }
410
+ i += 2;
411
+ continue;
412
+ }
413
+ if (i + 1 < len && isAsciiLetter(html[i + 1])) {
414
+ let j = i + 1;
415
+ const nameStart = j;
416
+ while (j < len && isTagNameChar(html[j]))
417
+ j++;
418
+ const openTagName = html.slice(nameStart, j).toLowerCase();
419
+ if (j < len && !/[\s>/]/.test(html[j])) {
420
+ i = j;
421
+ continue;
422
+ }
423
+ if (openTagName === "script" || openTagName === "style") {
424
+ i = skipRawElement(html, i, openTagName);
425
+ continue;
426
+ }
427
+ const closeIdx = findTagClose(html, j);
428
+ if (closeIdx === -1) {
429
+ i = j;
430
+ continue;
431
+ }
432
+ const rawAttrs = html.slice(j, closeIdx);
433
+ const trimmedAttrs = rawAttrs.trimEnd();
434
+ const isSelfClosing = trimmedAttrs.endsWith("/");
435
+ const attrString = isSelfClosing ? trimmedAttrs.slice(0, -1).trim() : rawAttrs.trim();
436
+ if (!isSelfClosing) {
437
+ if (stack.length === 0) {
438
+ if (targetTags.has(openTagName)) {
439
+ stack.push({
440
+ tag: openTagName,
441
+ isTarget: true,
442
+ start: i,
443
+ openTagEnd: closeIdx + 1,
444
+ openTag: html.slice(i, closeIdx + 1),
445
+ attrString
446
+ });
447
+ } else if (nestedScopeTags.has(openTagName)) {
448
+ stack.push({
449
+ tag: openTagName,
450
+ isTarget: false,
451
+ start: i,
452
+ openTagEnd: closeIdx + 1,
453
+ openTag: html.slice(i, closeIdx + 1),
454
+ attrString
455
+ });
456
+ }
457
+ } else {
458
+ const topTag = stack[stack.length - 1].tag;
459
+ if (openTagName === topTag || nestedScopeTags.has(openTagName)) {
460
+ stack.push({
461
+ tag: openTagName,
462
+ isTarget: false,
463
+ start: i,
464
+ openTagEnd: closeIdx + 1,
465
+ openTag: html.slice(i, closeIdx + 1),
466
+ attrString
467
+ });
468
+ }
469
+ }
470
+ }
471
+ i = closeIdx + 1;
472
+ continue;
473
+ }
474
+ i++;
475
+ }
476
+ return results;
477
+ }
478
+ function findTopLevelBlocks(html, tagNames) {
479
+ const targetSet = new Set(tagNames.map((t) => t.toLowerCase()));
480
+ return scanBlocks(html, targetSet, targetSet);
481
+ }
482
+ function splitDirectSubBlocks(inner, allowedTags, nestedScopeTags) {
483
+ const targetSet = new Set(allowedTags.map((t) => t.toLowerCase()));
484
+ const scopeSet = new Set(nestedScopeTags.map((t) => t.toLowerCase()));
485
+ const subBlocks = scanBlocks(inner, targetSet, scopeSet);
486
+ if (subBlocks.length === 0) {
487
+ return { body: inner, subBlocks: [] };
488
+ }
489
+ let body = "";
490
+ let cursor = 0;
491
+ for (const block of subBlocks) {
492
+ body += inner.slice(cursor, block.start);
493
+ cursor = block.end;
494
+ }
495
+ body += inner.slice(cursor);
496
+ return { body, subBlocks };
497
+ }
498
+
322
499
  // src/template/web-components.ts
323
500
  import { basename as basename2, extname, dirname as dirname3, join as join3 } from "path";
324
501
  function pascalToKebab(pascal) {
@@ -1308,6 +1485,159 @@ var init_env = __esm(() => {
1308
1485
  RESERVED_NAMESPACES = new Set(["params", "props", "env"]);
1309
1486
  });
1310
1487
 
1488
+ // src/template/errors.ts
1489
+ import { relative as relative3 } from "path";
1490
+ function formatTemplatePath(filePath, projectRoot) {
1491
+ if (!filePath)
1492
+ return "";
1493
+ if (projectRoot) {
1494
+ const rel = relative3(projectRoot, filePath).replace(/\\/g, "/");
1495
+ if (rel && !rel.startsWith("..")) {
1496
+ return rel;
1497
+ }
1498
+ }
1499
+ return filePath.replace(/\\/g, "/");
1500
+ }
1501
+ function offsetToLineColumn(source, offset) {
1502
+ const clamped = Math.max(0, Math.min(offset, source.length));
1503
+ let line = 1;
1504
+ let lastNewline = -1;
1505
+ for (let i = 0;i < clamped; i++) {
1506
+ if (source.charCodeAt(i) === 10) {
1507
+ line++;
1508
+ lastNewline = i;
1509
+ }
1510
+ }
1511
+ return {
1512
+ line,
1513
+ column: clamped - lastNewline
1514
+ };
1515
+ }
1516
+ function formatCodeFrame(source, line, column = 1, endColumn, contextLines = 2) {
1517
+ const lines = source.split(/\r?\n/);
1518
+ if (lines.length === 0)
1519
+ return "";
1520
+ const targetLine = Math.max(1, Math.min(line, lines.length));
1521
+ const startLine = Math.max(1, targetLine - contextLines);
1522
+ const endLine = Math.min(lines.length, targetLine + contextLines);
1523
+ const gutterWidth = String(endLine).length;
1524
+ const output = [];
1525
+ for (let i = startLine;i <= endLine; i++) {
1526
+ const lineText = lines[i - 1] ?? "";
1527
+ const marker = i === targetLine ? ">" : " ";
1528
+ const numStr = String(i).padStart(gutterWidth, " ");
1529
+ output.push(` ${marker} ${numStr} | ${lineText}`);
1530
+ if (i === targetLine) {
1531
+ const colStart = Math.max(1, column);
1532
+ const rawPrefix = lineText.slice(0, colStart - 1);
1533
+ const caretPrefix = rawPrefix.replace(/[^\t]/g, " ");
1534
+ const maxRemaining = Math.max(1, lineText.length - (colStart - 1));
1535
+ const requestedSpan = endColumn && endColumn > colStart ? endColumn - colStart : 1;
1536
+ const caretCount = Math.max(1, Math.min(requestedSpan, maxRemaining));
1537
+ const blankNum = " ".repeat(gutterWidth);
1538
+ output.push(` ${blankNum} | ${caretPrefix}${"^".repeat(caretCount)}`);
1539
+ }
1540
+ }
1541
+ return output.join(`
1542
+ `);
1543
+ }
1544
+ function findSnippetLocation(options) {
1545
+ const { source, snippet, openTag, fallbackHtml, fallbackOffset, filePath } = options;
1546
+ const highlightTarget = openTag || snippet;
1547
+ const firstLineLength = Math.max(1, highlightTarget.split(/\r?\n/)[0].length);
1548
+ if (source) {
1549
+ let idx = snippet ? source.indexOf(snippet) : -1;
1550
+ if (idx === -1 && openTag) {
1551
+ idx = source.indexOf(openTag);
1552
+ }
1553
+ if (idx !== -1) {
1554
+ const { line, column } = offsetToLineColumn(source, idx);
1555
+ return {
1556
+ filePath,
1557
+ line,
1558
+ column,
1559
+ endColumn: column + firstLineLength,
1560
+ source
1561
+ };
1562
+ }
1563
+ }
1564
+ if (fallbackHtml) {
1565
+ let idx = fallbackOffset !== undefined && fallbackOffset >= 0 ? fallbackOffset : snippet ? fallbackHtml.indexOf(snippet) : -1;
1566
+ if (idx === -1 && openTag) {
1567
+ idx = fallbackHtml.indexOf(openTag);
1568
+ }
1569
+ if (idx !== -1) {
1570
+ const { line, column } = offsetToLineColumn(fallbackHtml, idx);
1571
+ return {
1572
+ filePath,
1573
+ line,
1574
+ column,
1575
+ endColumn: column + firstLineLength,
1576
+ source: fallbackHtml
1577
+ };
1578
+ }
1579
+ }
1580
+ return { filePath };
1581
+ }
1582
+ var BunticTemplateError;
1583
+ var init_errors = __esm(() => {
1584
+ BunticTemplateError = class BunticTemplateError extends Error {
1585
+ summary;
1586
+ filePath;
1587
+ line;
1588
+ column;
1589
+ endColumn;
1590
+ codeFrame;
1591
+ resolvedTarget;
1592
+ causeMessage;
1593
+ hint;
1594
+ constructor(options) {
1595
+ const { message, location, projectRoot, resolvedTarget, hint, cause } = options;
1596
+ const displayFile = location?.filePath ? formatTemplatePath(location.filePath, projectRoot) : undefined;
1597
+ const displayResolved = resolvedTarget ? formatTemplatePath(resolvedTarget, projectRoot) : undefined;
1598
+ const causeMsg = cause !== undefined ? getErrorMessage(cause) : undefined;
1599
+ const codeFrame = location?.source && location.line ? formatCodeFrame(location.source, location.line, location.column, location.endColumn) : undefined;
1600
+ const parts = [message];
1601
+ if (displayFile) {
1602
+ const coords = location?.line ? `:${location.line}${location.column ? `:${location.column}` : ""}` : "";
1603
+ parts.push(` File: ${displayFile}${coords}`);
1604
+ } else if (location?.line) {
1605
+ const colPart = location.column ? `, column ${location.column}` : "";
1606
+ parts.push(` Location: line ${location.line}${colPart}`);
1607
+ }
1608
+ if (displayResolved) {
1609
+ parts.push(` Resolved: ${displayResolved}`);
1610
+ }
1611
+ if (causeMsg) {
1612
+ parts.push(` Cause: ${causeMsg}`);
1613
+ }
1614
+ if (codeFrame) {
1615
+ parts.push("");
1616
+ parts.push(codeFrame);
1617
+ }
1618
+ if (hint) {
1619
+ const formattedHint = hint.split(`
1620
+ `).join(`
1621
+ `);
1622
+ parts.push("");
1623
+ parts.push(` Hint: ${formattedHint}`);
1624
+ }
1625
+ super(parts.join(`
1626
+ `));
1627
+ this.name = "BunticTemplateError";
1628
+ this.summary = message;
1629
+ this.filePath = displayFile;
1630
+ this.line = location?.line;
1631
+ this.column = location?.column;
1632
+ this.endColumn = location?.endColumn;
1633
+ this.codeFrame = codeFrame;
1634
+ this.resolvedTarget = displayResolved;
1635
+ this.causeMessage = causeMsg;
1636
+ this.hint = hint;
1637
+ }
1638
+ };
1639
+ });
1640
+
1311
1641
  // src/template/data-loader.ts
1312
1642
  import { existsSync as existsSync5, readdirSync as readdirSync2 } from "fs";
1313
1643
  import { join as join7 } from "path";
@@ -1343,8 +1673,15 @@ async function loadGlobalData(config, vfs) {
1343
1673
  if (isJson) {
1344
1674
  try {
1345
1675
  data[key] = await vfs.readJson(fullPath);
1346
- } catch {
1347
- data[key] = await Bun.file(fullPath).json();
1676
+ } catch (err) {
1677
+ const relPath = formatTemplatePath(fullPath, config.root);
1678
+ throw new BunticTemplateError({
1679
+ message: `[Buntic Error] Failed to parse global JSON data file "${relPath}"`,
1680
+ location: { filePath: fullPath },
1681
+ projectRoot: config.root,
1682
+ cause: err,
1683
+ hint: `Check that "${relPath}" contains valid JSON syntax.`
1684
+ });
1348
1685
  }
1349
1686
  } else if (isModule) {
1350
1687
  try {
@@ -1364,7 +1701,7 @@ async function loadGlobalData(config, vfs) {
1364
1701
  }
1365
1702
  }
1366
1703
  } catch (err) {
1367
- if (err instanceof Error && err.message.includes("[Buntic Error]")) {
1704
+ if (err instanceof BunticTemplateError || err instanceof Error && err.message.includes("[Buntic Error]")) {
1368
1705
  throw err;
1369
1706
  }
1370
1707
  }
@@ -1372,15 +1709,16 @@ async function loadGlobalData(config, vfs) {
1372
1709
  }
1373
1710
  var init_data_loader = __esm(() => {
1374
1711
  init_env();
1712
+ init_errors();
1375
1713
  });
1376
1714
 
1377
- // src/template/directives.ts
1715
+ // src/template/expressions.ts
1378
1716
  function isTruthy(val) {
1379
1717
  if (val === undefined || val === null || val === false || val === "")
1380
1718
  return false;
1381
1719
  if (Array.isArray(val) && val.length === 0)
1382
1720
  return false;
1383
- if (typeof val === "number" && isNaN(val))
1721
+ if (typeof val === "number" && Number.isNaN(val))
1384
1722
  return false;
1385
1723
  return true;
1386
1724
  }
@@ -1390,36 +1728,613 @@ function getNestedValue(obj, path) {
1390
1728
  const parts = path.split(".");
1391
1729
  let cur = obj;
1392
1730
  for (const part of parts) {
1393
- if (cur == null || typeof cur !== "object")
1731
+ if (!part || FORBIDDEN_PATH_KEYS.has(part))
1732
+ return;
1733
+ if (cur == null)
1734
+ return;
1735
+ if (typeof cur === "string") {
1736
+ if (part === "length") {
1737
+ cur = cur.length;
1738
+ continue;
1739
+ }
1740
+ return;
1741
+ }
1742
+ if (typeof cur !== "object")
1743
+ return;
1744
+ if (Array.isArray(cur)) {
1745
+ if (part === "length") {
1746
+ cur = cur.length;
1747
+ continue;
1748
+ }
1749
+ if (Object.prototype.hasOwnProperty.call(cur, part)) {
1750
+ cur = cur[part];
1751
+ continue;
1752
+ }
1394
1753
  return;
1754
+ }
1755
+ if (!Object.prototype.hasOwnProperty.call(cur, part)) {
1756
+ return;
1757
+ }
1395
1758
  cur = cur[part];
1396
1759
  }
1397
1760
  return cur;
1398
1761
  }
1399
- function resolveConditionals(html, context) {
1400
- let res = html.replace(/<if\s+is=["']([^"']+)["'][^>]*>([\s\S]*?)<\/if>/gi, (_match, expr, inner) => {
1401
- const val = getNestedValue(context, expr.trim());
1402
- let thenContent = inner;
1403
- let elseContent = "";
1404
- const elseMatch = inner.match(/([\s\S]*?)<else>([\s\S]*?)<\/else>/i);
1405
- if (elseMatch) {
1406
- thenContent = elseMatch[1];
1407
- elseContent = elseMatch[2];
1408
- }
1409
- return isTruthy(val) ? thenContent.trim() : elseContent.trim();
1762
+ function tokenize(input) {
1763
+ const tokens = [];
1764
+ let i = 0;
1765
+ const len = input.length;
1766
+ while (i < len) {
1767
+ const ch = input[i];
1768
+ if (/\s/.test(ch)) {
1769
+ i++;
1770
+ continue;
1771
+ }
1772
+ if (ch === "{" && input[i + 1] === "{") {
1773
+ throw new ExpressionSyntaxError(`Unexpected "{{" in expression "${input}".`, `Do not wrap expressions in "{{ }}" inside is="...". Write the expression directly, e.g. is="age >= 18".`);
1774
+ }
1775
+ if (ch === "(") {
1776
+ tokens.push({ type: "lparen", value: "(", pos: i });
1777
+ i++;
1778
+ continue;
1779
+ }
1780
+ if (ch === ")") {
1781
+ tokens.push({ type: "rparen", value: ")", pos: i });
1782
+ i++;
1783
+ continue;
1784
+ }
1785
+ const three = input.slice(i, i + 3);
1786
+ if (three === "===" || three === "!==") {
1787
+ tokens.push({ type: "op", value: three, pos: i });
1788
+ i += 3;
1789
+ continue;
1790
+ }
1791
+ const two = input.slice(i, i + 2);
1792
+ if (two === "==" || two === "!=" || two === "<=" || two === ">=" || two === "&&" || two === "||") {
1793
+ tokens.push({ type: "op", value: two, pos: i });
1794
+ i += 2;
1795
+ continue;
1796
+ }
1797
+ if (ch === "=") {
1798
+ throw new ExpressionSyntaxError(`Unexpected assignment operator "=" at position ${i + 1} in expression "${input}".`, `Use "==" or "===" to compare values.`);
1799
+ }
1800
+ if (ch === "&" || ch === "|") {
1801
+ throw new ExpressionSyntaxError(`Unexpected operator "${ch}" at position ${i + 1} in expression "${input}".`, `Use "${ch}${ch}" for logical ${ch === "&" ? "AND" : "OR"}.`);
1802
+ }
1803
+ if (ch === "<" || ch === ">" || ch === "!" || ch === "-") {
1804
+ tokens.push({ type: "op", value: ch, pos: i });
1805
+ i++;
1806
+ continue;
1807
+ }
1808
+ if (ch === "'" || ch === '"') {
1809
+ const quote = ch;
1810
+ const start = i;
1811
+ i++;
1812
+ let str = "";
1813
+ let closed = false;
1814
+ while (i < len) {
1815
+ const c = input[i];
1816
+ if (c === "\\" && i + 1 < len) {
1817
+ const next = input[i + 1];
1818
+ if (next === "n")
1819
+ str += `
1820
+ `;
1821
+ else if (next === "t")
1822
+ str += "\t";
1823
+ else if (next === "r")
1824
+ str += "\r";
1825
+ else
1826
+ str += next;
1827
+ i += 2;
1828
+ continue;
1829
+ }
1830
+ if (c === quote) {
1831
+ closed = true;
1832
+ i++;
1833
+ break;
1834
+ }
1835
+ str += c;
1836
+ i++;
1837
+ }
1838
+ if (!closed) {
1839
+ throw new ExpressionSyntaxError(`Unterminated string literal starting at position ${start + 1} in expression "${input}".`);
1840
+ }
1841
+ tokens.push({ type: "string", value: str, pos: start });
1842
+ continue;
1843
+ }
1844
+ if (/[0-9]/.test(ch)) {
1845
+ const start = i;
1846
+ let hasDot = false;
1847
+ while (i < len) {
1848
+ const c = input[i];
1849
+ if (/[0-9]/.test(c)) {
1850
+ i++;
1851
+ } else if (c === "." && !hasDot && i + 1 < len && /[0-9]/.test(input[i + 1])) {
1852
+ hasDot = true;
1853
+ i++;
1854
+ } else {
1855
+ break;
1856
+ }
1857
+ }
1858
+ const raw = input.slice(start, i);
1859
+ tokens.push({ type: "number", value: raw, numValue: Number(raw), pos: start });
1860
+ continue;
1861
+ }
1862
+ if (/[a-zA-Z_$]/.test(ch)) {
1863
+ const start = i;
1864
+ while (i < len && /[a-zA-Z0-9_$.]/.test(input[i])) {
1865
+ i++;
1866
+ }
1867
+ const raw = input.slice(start, i);
1868
+ if (raw.startsWith(".") || raw.endsWith(".") || raw.includes("..")) {
1869
+ throw new ExpressionSyntaxError(`Invalid property path "${raw}" in expression "${input}".`);
1870
+ }
1871
+ if (raw === "true" || raw === "false") {
1872
+ tokens.push({ type: "boolean", value: raw, boolValue: raw === "true", pos: start });
1873
+ } else if (raw === "null") {
1874
+ tokens.push({ type: "null", value: raw, pos: start });
1875
+ } else if (raw === "undefined") {
1876
+ tokens.push({ type: "undefined", value: raw, pos: start });
1877
+ } else {
1878
+ tokens.push({ type: "path", value: raw, pos: start });
1879
+ }
1880
+ continue;
1881
+ }
1882
+ throw new ExpressionSyntaxError(`Unexpected character "${ch}" at position ${i + 1} in expression "${input}".`);
1883
+ }
1884
+ tokens.push({ type: "eof", value: "", pos: len });
1885
+ return tokens;
1886
+ }
1887
+
1888
+ class ExpressionParser {
1889
+ tokens;
1890
+ pos = 0;
1891
+ rawInput;
1892
+ constructor(tokens, rawInput) {
1893
+ this.tokens = tokens;
1894
+ this.rawInput = rawInput;
1895
+ }
1896
+ peek() {
1897
+ return this.tokens[this.pos];
1898
+ }
1899
+ consume() {
1900
+ return this.tokens[this.pos++];
1901
+ }
1902
+ parse() {
1903
+ const node = this.parseOr();
1904
+ const trailing = this.peek();
1905
+ if (trailing.type !== "eof") {
1906
+ throw new ExpressionSyntaxError(`Unexpected token "${trailing.value}" at position ${trailing.pos + 1} in expression "${this.rawInput}".`);
1907
+ }
1908
+ return node;
1909
+ }
1910
+ parseOr() {
1911
+ let left = this.parseAnd();
1912
+ while (this.peek().type === "op" && this.peek().value === "||") {
1913
+ this.consume();
1914
+ const right = this.parseAnd();
1915
+ left = { kind: "binary", op: "||", left, right };
1916
+ }
1917
+ return left;
1918
+ }
1919
+ parseAnd() {
1920
+ let left = this.parseEquality();
1921
+ while (this.peek().type === "op" && this.peek().value === "&&") {
1922
+ this.consume();
1923
+ const right = this.parseEquality();
1924
+ left = { kind: "binary", op: "&&", left, right };
1925
+ }
1926
+ return left;
1927
+ }
1928
+ parseEquality() {
1929
+ let left = this.parseRelational();
1930
+ while (this.peek().type === "op" && (this.peek().value === "===" || this.peek().value === "!==" || this.peek().value === "==" || this.peek().value === "!=")) {
1931
+ const op = this.consume().value;
1932
+ const right = this.parseRelational();
1933
+ left = { kind: "binary", op, left, right };
1934
+ }
1935
+ return left;
1936
+ }
1937
+ parseRelational() {
1938
+ let left = this.parseUnary();
1939
+ while (this.peek().type === "op" && (this.peek().value === "<" || this.peek().value === "<=" || this.peek().value === ">" || this.peek().value === ">=")) {
1940
+ const op = this.consume().value;
1941
+ const right = this.parseUnary();
1942
+ left = { kind: "binary", op, left, right };
1943
+ }
1944
+ return left;
1945
+ }
1946
+ parseUnary() {
1947
+ const tok = this.peek();
1948
+ if (tok.type === "op" && (tok.value === "!" || tok.value === "-")) {
1949
+ this.consume();
1950
+ const operand = this.parseUnary();
1951
+ return { kind: "unary", op: tok.value, operand };
1952
+ }
1953
+ return this.parsePrimary();
1954
+ }
1955
+ parsePrimary() {
1956
+ const tok = this.peek();
1957
+ if (tok.type === "number") {
1958
+ this.consume();
1959
+ return { kind: "literal", value: tok.numValue };
1960
+ }
1961
+ if (tok.type === "string") {
1962
+ this.consume();
1963
+ return { kind: "literal", value: tok.value };
1964
+ }
1965
+ if (tok.type === "boolean") {
1966
+ this.consume();
1967
+ return { kind: "literal", value: tok.boolValue };
1968
+ }
1969
+ if (tok.type === "null") {
1970
+ this.consume();
1971
+ return { kind: "literal", value: null };
1972
+ }
1973
+ if (tok.type === "undefined") {
1974
+ this.consume();
1975
+ return { kind: "literal", value: undefined };
1976
+ }
1977
+ if (tok.type === "path") {
1978
+ this.consume();
1979
+ return { kind: "path", path: tok.value };
1980
+ }
1981
+ if (tok.type === "lparen") {
1982
+ this.consume();
1983
+ const inner = this.parseOr();
1984
+ if (this.peek().type !== "rparen") {
1985
+ throw new ExpressionSyntaxError(`Expected closing ")" in expression "${this.rawInput}".`);
1986
+ }
1987
+ this.consume();
1988
+ return inner;
1989
+ }
1990
+ throw new ExpressionSyntaxError(`Unexpected ${tok.type === "eof" ? "end of expression" : `token "${tok.value}"`} in expression "${this.rawInput}".`);
1991
+ }
1992
+ }
1993
+ function evalAst(node, context) {
1994
+ switch (node.kind) {
1995
+ case "literal":
1996
+ return node.value;
1997
+ case "path":
1998
+ return getNestedValue(context, node.path);
1999
+ case "unary": {
2000
+ const operand = evalAst(node.operand, context);
2001
+ if (node.op === "!") {
2002
+ return !isTruthy(operand);
2003
+ }
2004
+ return -Number(operand);
2005
+ }
2006
+ case "binary": {
2007
+ if (node.op === "||") {
2008
+ const left = evalAst(node.left, context);
2009
+ return isTruthy(left) ? left : evalAst(node.right, context);
2010
+ }
2011
+ if (node.op === "&&") {
2012
+ const left = evalAst(node.left, context);
2013
+ return isTruthy(left) ? evalAst(node.right, context) : left;
2014
+ }
2015
+ const left = evalAst(node.left, context);
2016
+ const right = evalAst(node.right, context);
2017
+ switch (node.op) {
2018
+ case "===":
2019
+ return left === right;
2020
+ case "!==":
2021
+ return left !== right;
2022
+ case "==":
2023
+ return left == right;
2024
+ case "!=":
2025
+ return left != right;
2026
+ case "<":
2027
+ return left < right;
2028
+ case "<=":
2029
+ return left <= right;
2030
+ case ">":
2031
+ return left > right;
2032
+ case ">=":
2033
+ return left >= right;
2034
+ default:
2035
+ return false;
2036
+ }
2037
+ }
2038
+ }
2039
+ }
2040
+ function evaluateExpression(expr, context) {
2041
+ const trimmed = expr.trim();
2042
+ if (!trimmed) {
2043
+ throw new ExpressionSyntaxError("Condition expression cannot be empty.");
2044
+ }
2045
+ const tokens = tokenize(trimmed);
2046
+ const parser = new ExpressionParser(tokens, trimmed);
2047
+ const ast = parser.parse();
2048
+ return evalAst(ast, context);
2049
+ }
2050
+ var FORBIDDEN_PATH_KEYS, ExpressionSyntaxError;
2051
+ var init_expressions = __esm(() => {
2052
+ FORBIDDEN_PATH_KEYS = new Set(["__proto__", "constructor", "prototype"]);
2053
+ ExpressionSyntaxError = class ExpressionSyntaxError extends Error {
2054
+ hint;
2055
+ constructor(message, hint) {
2056
+ super(message);
2057
+ this.name = "ExpressionSyntaxError";
2058
+ this.hint = hint;
2059
+ }
2060
+ };
2061
+ });
2062
+
2063
+ // src/template/directives.ts
2064
+ function buildError(options) {
2065
+ const { message, hint, cause, snippet, openTag, fallbackHtml, fallbackOffset, diag } = options;
2066
+ const location = findSnippetLocation({
2067
+ source: diag?.source,
2068
+ snippet,
2069
+ openTag,
2070
+ fallbackHtml,
2071
+ fallbackOffset,
2072
+ filePath: diag?.filePath
1410
2073
  });
1411
- res = res.replace(/<([a-zA-Z0-9_-]+)\s+([^>]*?)if=["']([^"']+)["']([^>]*?)\s*\/>/gi, (_m, tag, before, expr, after) => {
1412
- const val = getNestedValue(context, expr.trim());
2074
+ return new BunticTemplateError({
2075
+ message,
2076
+ location,
2077
+ projectRoot: diag?.projectRoot,
2078
+ cause,
2079
+ hint
2080
+ });
2081
+ }
2082
+ function parseFiniteNumber(raw) {
2083
+ const trimmed = raw.trim();
2084
+ if (trimmed === "")
2085
+ return null;
2086
+ const parsed = Number(trimmed);
2087
+ return Number.isFinite(parsed) ? parsed : null;
2088
+ }
2089
+ function parseAndValidateMatchers(attrs, block, fallbackHtml, diag) {
2090
+ const hasString = "string" in attrs;
2091
+ const hasNumber = "number" in attrs;
2092
+ const hasBoolean = "boolean" in attrs;
2093
+ const hasMin = "min" in attrs;
2094
+ const hasMax = "max" in attrs;
2095
+ const hasRange = hasMin || hasMax;
2096
+ const activeCategories = [hasString, hasNumber, hasBoolean, hasRange].filter(Boolean).length;
2097
+ if (activeCategories === 0) {
2098
+ return { hasMatcher: false };
2099
+ }
2100
+ if (activeCategories > 1) {
2101
+ throw buildError({
2102
+ message: `[Buntic] Conflicting value matcher attributes on <${block.tag}>.`,
2103
+ hint: `Use a single matcher type ("string", "number", "boolean") or a numeric range ("min" / "max"), not a mix of incompatible attributes.`,
2104
+ snippet: block.fullMatch,
2105
+ openTag: block.openTag,
2106
+ fallbackHtml,
2107
+ fallbackOffset: block.start,
2108
+ diag
2109
+ });
2110
+ }
2111
+ if (hasString) {
2112
+ return { hasMatcher: true, stringVal: attrs.string };
2113
+ }
2114
+ if (hasNumber) {
2115
+ const parsed = parseFiniteNumber(attrs.number);
2116
+ if (parsed === null) {
2117
+ throw buildError({
2118
+ message: `[Buntic] Invalid numeric literal "${attrs.number}" in number="..." attribute on <${block.tag}>.`,
2119
+ hint: `The "number" attribute expects a finite numeric literal (e.g. number="0" or number="42"). To compare against another variable, use an expression in is="..." (e.g. is="age === config.target").`,
2120
+ snippet: block.fullMatch,
2121
+ openTag: block.openTag,
2122
+ fallbackHtml,
2123
+ fallbackOffset: block.start,
2124
+ diag
2125
+ });
2126
+ }
2127
+ return { hasMatcher: true, numberVal: parsed };
2128
+ }
2129
+ if (hasBoolean) {
2130
+ const raw = attrs.boolean.trim();
2131
+ if (raw !== "true" && raw !== "false") {
2132
+ throw buildError({
2133
+ message: `[Buntic] Invalid boolean literal "${attrs.boolean}" in boolean="..." attribute on <${block.tag}>.`,
2134
+ hint: `The "boolean" attribute only accepts "true" or "false".`,
2135
+ snippet: block.fullMatch,
2136
+ openTag: block.openTag,
2137
+ fallbackHtml,
2138
+ fallbackOffset: block.start,
2139
+ diag
2140
+ });
2141
+ }
2142
+ return { hasMatcher: true, booleanVal: raw === "true" };
2143
+ }
2144
+ let minVal;
2145
+ let maxVal;
2146
+ if (hasMin) {
2147
+ const parsed = parseFiniteNumber(attrs.min);
2148
+ if (parsed === null) {
2149
+ throw buildError({
2150
+ message: `[Buntic] Invalid numeric literal "${attrs.min}" in min="..." attribute on <${block.tag}>.`,
2151
+ hint: `The "min" attribute expects a finite numeric literal (e.g. min="18"). To compare against another variable, use is="age >= config.minAge".`,
2152
+ snippet: block.fullMatch,
2153
+ openTag: block.openTag,
2154
+ fallbackHtml,
2155
+ fallbackOffset: block.start,
2156
+ diag
2157
+ });
2158
+ }
2159
+ minVal = parsed;
2160
+ }
2161
+ if (hasMax) {
2162
+ const parsed = parseFiniteNumber(attrs.max);
2163
+ if (parsed === null) {
2164
+ throw buildError({
2165
+ message: `[Buntic] Invalid numeric literal "${attrs.max}" in max="..." attribute on <${block.tag}>.`,
2166
+ hint: `The "max" attribute expects a finite numeric literal (e.g. max="30"). To compare against another variable, use is="age <= config.maxAge".`,
2167
+ snippet: block.fullMatch,
2168
+ openTag: block.openTag,
2169
+ fallbackHtml,
2170
+ fallbackOffset: block.start,
2171
+ diag
2172
+ });
2173
+ }
2174
+ maxVal = parsed;
2175
+ }
2176
+ if (minVal !== undefined && maxVal !== undefined && minVal > maxVal) {
2177
+ throw buildError({
2178
+ message: `[Buntic] Invalid range on <${block.tag}>: min="${minVal}" cannot be greater than max="${maxVal}".`,
2179
+ hint: `Ensure min <= max (e.g. min="${maxVal}" max="${minVal}").`,
2180
+ snippet: block.fullMatch,
2181
+ openTag: block.openTag,
2182
+ fallbackHtml,
2183
+ fallbackOffset: block.start,
2184
+ diag
2185
+ });
2186
+ }
2187
+ return { hasMatcher: true, minVal, maxVal };
2188
+ }
2189
+ function matchesValue(val, matchers) {
2190
+ if (matchers.stringVal !== undefined) {
2191
+ return typeof val === "string" && val === matchers.stringVal;
2192
+ }
2193
+ if (matchers.numberVal !== undefined) {
2194
+ return typeof val === "number" && !Number.isNaN(val) && val === matchers.numberVal;
2195
+ }
2196
+ if (matchers.booleanVal !== undefined) {
2197
+ return typeof val === "boolean" && val === matchers.booleanVal;
2198
+ }
2199
+ if (matchers.minVal !== undefined || matchers.maxVal !== undefined) {
2200
+ if (typeof val !== "number" || Number.isNaN(val)) {
2201
+ return false;
2202
+ }
2203
+ if (matchers.minVal !== undefined && val < matchers.minVal)
2204
+ return false;
2205
+ if (matchers.maxVal !== undefined && val > matchers.maxVal)
2206
+ return false;
2207
+ return true;
2208
+ }
2209
+ return false;
2210
+ }
2211
+ function evalDirectiveExpr(expr, context, snippet, openTag, fallbackHtml, fallbackOffset, diag) {
2212
+ try {
2213
+ return evaluateExpression(expr, context);
2214
+ } catch (err) {
2215
+ const hint = err instanceof ExpressionSyntaxError ? err.hint : undefined;
2216
+ throw buildError({
2217
+ message: `[Buntic] Invalid condition expression "${expr}".`,
2218
+ cause: err,
2219
+ hint: hint || `Check expression syntax (supported: paths like "a.b", literals, !, ===, !==, ==, !=, <, <=, >, >=, &&, ||, parentheses).`,
2220
+ snippet,
2221
+ openTag,
2222
+ fallbackHtml,
2223
+ fallbackOffset,
2224
+ diag
2225
+ });
2226
+ }
2227
+ }
2228
+ function evaluateDecisionBlock(block, context, fallbackHtml, diag) {
2229
+ const attrs = parseHtmlAttributes(block.attrString, "");
2230
+ if (!attrs.is || !attrs.is.trim()) {
2231
+ throw buildError({
2232
+ message: `[Buntic] <${block.tag}> tag requires an "is" attribute.`,
2233
+ hint: `Example: <${block.tag} is="condition">...</${block.tag}>.`,
2234
+ snippet: block.fullMatch,
2235
+ openTag: block.openTag,
2236
+ fallbackHtml,
2237
+ fallbackOffset: block.start,
2238
+ diag
2239
+ });
2240
+ }
2241
+ if (block.tag === "if") {
2242
+ const matchers = parseAndValidateMatchers(attrs, block, fallbackHtml, diag);
2243
+ const val = evalDirectiveExpr(attrs.is, context, block.fullMatch, block.openTag, fallbackHtml, block.start, diag);
2244
+ const passed = matchers.hasMatcher ? matchesValue(val, matchers) : isTruthy(val);
2245
+ const { body, subBlocks } = splitDirectSubBlocks(block.inner, ["else"], NESTED_DIRECTIVE_SCOPES);
2246
+ const elseBlock = subBlocks[0];
2247
+ const chosen = passed ? body.trim() : elseBlock ? elseBlock.inner.trim() : "";
2248
+ return chosen ? resolveConditionals(chosen, context, diag) : "";
2249
+ }
2250
+ if (block.tag === "unless") {
2251
+ const matchers = parseAndValidateMatchers(attrs, block, fallbackHtml, diag);
2252
+ const val = evalDirectiveExpr(attrs.is, context, block.fullMatch, block.openTag, fallbackHtml, block.start, diag);
2253
+ const condition = matchers.hasMatcher ? matchesValue(val, matchers) : isTruthy(val);
2254
+ const chosen = !condition ? block.inner.trim() : "";
2255
+ return chosen ? resolveConditionals(chosen, context, diag) : "";
2256
+ }
2257
+ const { subBlocks } = splitDirectSubBlocks(block.inner, ["case", "else", "none", "default"], NESTED_DIRECTIVE_SCOPES);
2258
+ const cases = [];
2259
+ let elseBlock;
2260
+ let noneBlock;
2261
+ let defaultBlock;
2262
+ for (const sub of subBlocks) {
2263
+ if (sub.tag === "case") {
2264
+ const caseAttrs = parseHtmlAttributes(sub.attrString, "");
2265
+ const matchers = parseAndValidateMatchers(caseAttrs, sub, block.inner, diag);
2266
+ if (!matchers.hasMatcher) {
2267
+ throw buildError({
2268
+ message: `[Buntic] <case> tag inside <match> requires a value matcher attribute.`,
2269
+ hint: `Specify one of: string="...", number="...", boolean="true|false", or min="..." / max="...".`,
2270
+ snippet: sub.fullMatch,
2271
+ openTag: sub.openTag,
2272
+ fallbackHtml: block.inner,
2273
+ fallbackOffset: sub.start,
2274
+ diag
2275
+ });
2276
+ }
2277
+ cases.push({ block: sub, matchers });
2278
+ } else if (sub.tag === "else" && !elseBlock) {
2279
+ elseBlock = sub;
2280
+ } else if (sub.tag === "none" && !noneBlock) {
2281
+ noneBlock = sub;
2282
+ } else if (sub.tag === "default" && !defaultBlock) {
2283
+ defaultBlock = sub;
2284
+ }
2285
+ }
2286
+ const val = evalDirectiveExpr(attrs.is, context, block.fullMatch, block.openTag, fallbackHtml, block.start, diag);
2287
+ let chosen = "";
2288
+ if (val === undefined || val === null) {
2289
+ const fallback = elseBlock ?? defaultBlock;
2290
+ chosen = fallback ? fallback.inner.trim() : "";
2291
+ } else {
2292
+ let matched;
2293
+ for (const c of cases) {
2294
+ if (matchesValue(val, c.matchers)) {
2295
+ matched = c.block;
2296
+ break;
2297
+ }
2298
+ }
2299
+ if (matched) {
2300
+ chosen = matched.inner.trim();
2301
+ } else {
2302
+ const fallback = noneBlock ?? defaultBlock;
2303
+ chosen = fallback ? fallback.inner.trim() : "";
2304
+ }
2305
+ }
2306
+ return chosen ? resolveConditionals(chosen, context, diag) : "";
2307
+ }
2308
+ function resolveConditionals(html, context, diag) {
2309
+ const topBlocks = findTopLevelBlocks(html, ["if", "unless", "match"]);
2310
+ let res = html;
2311
+ if (topBlocks.length > 0) {
2312
+ let rebuilt = "";
2313
+ let cursor = 0;
2314
+ for (const block of topBlocks) {
2315
+ rebuilt += html.slice(cursor, block.start);
2316
+ rebuilt += evaluateDecisionBlock(block, context, html, diag);
2317
+ cursor = block.end;
2318
+ }
2319
+ rebuilt += html.slice(cursor);
2320
+ res = rebuilt;
2321
+ }
2322
+ res = res.replace(/<([a-zA-Z0-9_-]+)((?:\s+(?:[^>"']|"[^"]*"|'[^']*')*?)?)\s+if=(?:"([^"]+)"|'([^']+)')((?:\s+(?:[^>"']|"[^"]*"|'[^']*')*)?)\s*\/>/gi, (fullMatch, tag, before, exprDouble, exprSingle, after, offset) => {
2323
+ const expr = (exprDouble ?? exprSingle ?? "").trim();
2324
+ const val = evalDirectiveExpr(expr, context, fullMatch, fullMatch, res, offset, diag);
1413
2325
  if (!isTruthy(val))
1414
2326
  return "";
1415
- const attrs = `${before} ${after}`.trim().replace(/\s+/g, " ");
2327
+ const attrs = `${before ?? ""} ${after ?? ""}`.trim().replace(/\s+/g, " ");
1416
2328
  return attrs ? `<${tag} ${attrs} />` : `<${tag} />`;
1417
2329
  });
1418
- res = res.replace(/<([a-zA-Z0-9_-]+)\s+([^>]*?)if=["']([^"']+)["']([^>]*?)>([\s\S]*?)<\/\1>/gi, (_m, tag, before, expr, after, content) => {
1419
- const val = getNestedValue(context, expr.trim());
2330
+ res = res.replace(/<([a-zA-Z0-9_-]+)((?:\s+(?:[^>"']|"[^"]*"|'[^']*')*?)?)\s+if=(?:"([^"]+)"|'([^']+)')((?:\s+(?:[^>"']|"[^"]*"|'[^']*')*)?)>([\s\S]*?)<\/\1>/gi, (fullMatch, tag, before, exprDouble, exprSingle, after, content, offset) => {
2331
+ const expr = (exprDouble ?? exprSingle ?? "").trim();
2332
+ const closeLen = tag.length + 3;
2333
+ const openTag = fullMatch.slice(0, fullMatch.length - content.length - closeLen);
2334
+ const val = evalDirectiveExpr(expr, context, fullMatch, openTag, res, offset, diag);
1420
2335
  if (!isTruthy(val))
1421
2336
  return "";
1422
- const attrs = `${before} ${after}`.trim().replace(/\s+/g, " ");
2337
+ const attrs = `${before ?? ""} ${after ?? ""}`.trim().replace(/\s+/g, " ");
1423
2338
  return attrs ? `<${tag} ${attrs}>${content}</${tag}>` : `<${tag}>${content}</${tag}>`;
1424
2339
  });
1425
2340
  return res;
@@ -1435,9 +2350,15 @@ function interpolateTemplate(html, context) {
1435
2350
  return match;
1436
2351
  });
1437
2352
  }
2353
+ var NESTED_DIRECTIVE_SCOPES;
2354
+ var init_directives = __esm(() => {
2355
+ init_errors();
2356
+ init_expressions();
2357
+ NESTED_DIRECTIVE_SCOPES = ["if", "unless", "match", "each"];
2358
+ });
1438
2359
 
1439
2360
  // src/template/dsd-renderer.ts
1440
- import { relative as relative3 } from "path";
2361
+ import { relative as relative4 } from "path";
1441
2362
  function hasScriptWithSrc(html, srcPath) {
1442
2363
  const cleanSrc = srcPath.replace(/^\/+/, "");
1443
2364
  const scriptRegex = /<script\b[^>]*\bsrc=["']([^"']+)["'][^>]*>/gi;
@@ -1498,7 +2419,7 @@ ${globalCss.trim()}
1498
2419
  continue;
1499
2420
  }
1500
2421
  vfs.registry.markTagUsed(tag);
1501
- const rel = relative3(config.root, scriptPath).replace(/\\/g, "/");
2422
+ const rel = relative4(config.root, scriptPath).replace(/\\/g, "/");
1502
2423
  const publicSrc = rel.startsWith("/") ? rel : `/${rel}`;
1503
2424
  if (!injectedPaths.has(publicSrc) && !hasScriptWithSrc(result, publicSrc)) {
1504
2425
  injectedPaths.add(publicSrc);
@@ -1542,8 +2463,13 @@ ${siblingCss.trim()}
1542
2463
  } catch {
1543
2464
  rawHtml = await Bun.file(triad.htmlPath).text();
1544
2465
  }
2466
+ const originalRawHtml = rawHtml;
1545
2467
  rawHtml = await resolveComponentsFn(rawHtml, context, triad.htmlPath);
1546
- rawHtml = resolveConditionals(rawHtml, context);
2468
+ rawHtml = resolveConditionals(rawHtml, context, {
2469
+ filePath: triad.htmlPath,
2470
+ source: originalRawHtml,
2471
+ projectRoot: config.root
2472
+ });
1547
2473
  rawHtml = interpolateTemplate(rawHtml, context);
1548
2474
  if (rawHtml.includes("<style") && rawHtml.includes("scoped")) {
1549
2475
  const extracted = extractScopedStyles(rawHtml, scopeRegistry);
@@ -1597,12 +2523,13 @@ ${templateTag}`;
1597
2523
  return result;
1598
2524
  }
1599
2525
  var init_dsd_renderer = __esm(() => {
2526
+ init_directives();
1600
2527
  init_scoped_css();
1601
2528
  init_web_components();
1602
2529
  });
1603
2530
 
1604
2531
  // src/template/svg-component.ts
1605
- import { relative as relative4 } from "path";
2532
+ import { relative as relative5 } from "path";
1606
2533
  async function attachSiblingCssIfPresent(options) {
1607
2534
  const { templateHtml, templatePath, siblingCssPath, kindLabel, config, vfs, cssGraph } = options;
1608
2535
  if (!vfs.hasFile(siblingCssPath)) {
@@ -1621,8 +2548,8 @@ async function attachSiblingCssIfPresent(options) {
1621
2548
  if (withScopedCss !== null) {
1622
2549
  return withScopedCss;
1623
2550
  }
1624
- const relTarget = relative4(config.root, templatePath);
1625
- const relCss = relative4(config.root, siblingCssPath);
2551
+ const relTarget = relative5(config.root, templatePath);
2552
+ const relCss = relative5(config.root, siblingCssPath);
1626
2553
  logWarn(`${kindLabel} "${relTarget}" has a sibling CSS file ("${relCss}"), but does not have a single root element. Scoped styles were not applied.`);
1627
2554
  return templateHtml;
1628
2555
  }
@@ -1898,7 +2825,7 @@ var init_vfs = __esm(() => {
1898
2825
 
1899
2826
  // src/template/engine.ts
1900
2827
  import { existsSync as existsSync7 } from "fs";
1901
- import { extname as extname3, relative as relative5 } from "path";
2828
+ import { extname as extname3, relative as relative6 } from "path";
1902
2829
 
1903
2830
  class TemplateEngine {
1904
2831
  config;
@@ -1948,7 +2875,7 @@ class TemplateEngine {
1948
2875
  await this.cssGraph.analyze(this.vfs);
1949
2876
  const globalRoot = this.cssGraph.getGlobalRoot();
1950
2877
  if (globalRoot.conflicts.length > 1) {
1951
- const relConflicts = globalRoot.conflicts.map((c) => relative5(this.config.root, c));
2878
+ const relConflicts = globalRoot.conflicts.map((c) => relative6(this.config.root, c));
1952
2879
  logWarn(`Multiple orphan global CSS roots detected: ${relConflicts.map((c) => `"${c}"`).join(", ")}. Please link them via @import in a single root file or co-locate them with a component/page.`, "Buntic Conflict Warning");
1953
2880
  }
1954
2881
  let processedHtml = pageHtml;
@@ -1966,7 +2893,7 @@ class TemplateEngine {
1966
2893
  let composed = await this.resolveLayout(processedHtml, context, currentFile);
1967
2894
  composed = await this.resolveEach(composed, context, currentFile);
1968
2895
  composed = await this.resolveComponents(composed, context, currentFile);
1969
- composed = this.resolveConditionals(composed, context);
2896
+ composed = this.resolveConditionals(composed, context, currentFile, pageHtml);
1970
2897
  composed = this.interpolate(composed, context);
1971
2898
  composed = await this.resolveWebComponents(composed, context);
1972
2899
  composed = await this.resolveCss(composed, currentFile);
@@ -2008,6 +2935,16 @@ class TemplateEngine {
2008
2935
  resolveFilePath(rawSrc, currentFile, defaultDir) {
2009
2936
  return this.vfs.resolvePath(rawSrc, currentFile, defaultDir);
2010
2937
  }
2938
+ async getOriginalSource(filePath, fallbackHtml) {
2939
+ if (filePath && (this.vfs.hasFile(filePath) || existsSync7(filePath))) {
2940
+ try {
2941
+ return await this.vfs.readText(filePath);
2942
+ } catch {
2943
+ return fallbackHtml;
2944
+ }
2945
+ }
2946
+ return fallbackHtml;
2947
+ }
2011
2948
  async resolveLayout(html, context, currentFile) {
2012
2949
  const layoutMatch = html.match(/<layout\s+src=["']([^"']+)["'][^>]*>([\s\S]*?)<\/layout>/i);
2013
2950
  if (!layoutMatch) {
@@ -2017,7 +2954,24 @@ class TemplateEngine {
2017
2954
  const innerContent = layoutMatch[2];
2018
2955
  const layoutFilePath = this.resolveFilePath(layoutRawSrc, currentFile, this.config.layoutsDir);
2019
2956
  if (!this.vfs.hasFile(layoutFilePath) && !existsSync7(layoutFilePath)) {
2020
- throw new Error(`[Buntic] Layout not found: "${layoutRawSrc}" at ${layoutFilePath}`);
2957
+ const originalSource = await this.getOriginalSource(currentFile, html);
2958
+ const openTag = layoutMatch[0].slice(0, layoutMatch[0].indexOf(">") + 1);
2959
+ const location = findSnippetLocation({
2960
+ source: originalSource,
2961
+ snippet: layoutMatch[0],
2962
+ openTag,
2963
+ fallbackHtml: html,
2964
+ fallbackOffset: layoutMatch.index,
2965
+ filePath: currentFile || undefined
2966
+ });
2967
+ const layoutsDirDisplay = formatTemplatePath(this.config.layoutsDir, this.config.root);
2968
+ throw new BunticTemplateError({
2969
+ message: `[Buntic] Layout not found: "${layoutRawSrc}" at ${layoutFilePath}`,
2970
+ location,
2971
+ projectRoot: this.config.root,
2972
+ resolvedTarget: layoutFilePath,
2973
+ hint: `Check that "${layoutRawSrc}" exists in "${layoutsDirDisplay}" or verify the relative path in <layout src="${layoutRawSrc}">.`
2974
+ });
2021
2975
  }
2022
2976
  const layoutTemplate = await this.vfs.readText(layoutFilePath);
2023
2977
  let resolvedInner = await this.resolveEach(innerContent, context, currentFile);
@@ -2056,31 +3010,140 @@ class TemplateEngine {
2056
3010
  console.warn("[Buntic] Maximum <each> recursion depth (10) reached.");
2057
3011
  return html;
2058
3012
  }
2059
- const eachRegex = /<each\s+([^>]+?)>([\s\S]*?)<\/each>/gis;
2060
- let match;
2061
- const matches = [];
2062
- while ((match = eachRegex.exec(html)) !== null) {
2063
- matches.push({ fullMatch: match[0], attrString: match[1], inner: match[2] });
2064
- }
3013
+ const matches = findTopLevelBlocks(html, ["each"]);
2065
3014
  if (matches.length === 0)
2066
3015
  return html;
3016
+ const locateEachItem = async (item) => {
3017
+ const originalSource = await this.getOriginalSource(currentFile, html);
3018
+ return findSnippetLocation({
3019
+ source: originalSource,
3020
+ snippet: item.fullMatch,
3021
+ openTag: item.openTag,
3022
+ fallbackHtml: html,
3023
+ fallbackOffset: item.start,
3024
+ filePath: currentFile || undefined
3025
+ });
3026
+ };
3027
+ const originalSourceForFile = currentFile && (this.vfs.hasFile(currentFile) || existsSync7(currentFile)) ? await this.getOriginalSource(currentFile, html) : undefined;
3028
+ const renderFallbackBlock = async (content) => {
3029
+ const trimmed = content.trim();
3030
+ if (!trimmed)
3031
+ return "";
3032
+ let rendered = await this.resolveEach(trimmed, context, currentFile, depth + 1);
3033
+ rendered = await this.resolveComponents(rendered, context, currentFile, depth + 1);
3034
+ rendered = this.resolveConditionals(rendered, context, currentFile, originalSourceForFile);
3035
+ rendered = this.interpolate(rendered, context);
3036
+ return rendered;
3037
+ };
2067
3038
  let result = html;
2068
3039
  for (const item of matches) {
2069
3040
  const attrs = parseHtmlAttributes(item.attrString);
3041
+ const { body: loopTemplate, subBlocks } = splitDirectSubBlocks(item.inner, ["else", "none", "default"], ["each", "if", "unless", "match"]);
3042
+ let elseBlock;
3043
+ let noneBlock;
3044
+ let defaultBlock;
3045
+ for (const sub of subBlocks) {
3046
+ if (sub.tag === "else" && !elseBlock)
3047
+ elseBlock = sub;
3048
+ else if (sub.tag === "none" && !noneBlock)
3049
+ noneBlock = sub;
3050
+ else if (sub.tag === "default" && !defaultBlock)
3051
+ defaultBlock = sub;
3052
+ }
2070
3053
  let items;
3054
+ let resolvedFilePath;
2071
3055
  if (attrs.src) {
2072
3056
  const filePath = this.resolveFilePath(attrs.src, currentFile, this.config.dataDir);
3057
+ resolvedFilePath = filePath;
2073
3058
  if (!this.vfs.hasFile(filePath) && !existsSync7(filePath)) {
2074
- throw new Error(`[Buntic] <each> data file not found: "${attrs.src}" at ${filePath}`);
3059
+ const location = await locateEachItem(item);
3060
+ const existsInContext = getNestedValue(context, attrs.src) !== undefined;
3061
+ const dataDirDisplay = formatTemplatePath(this.config.dataDir, this.config.root);
3062
+ let hint;
3063
+ if (existsInContext) {
3064
+ hint = `"${attrs.src}" is available in the template context. ` + `Use <each in="${attrs.src}"> to iterate context data, or provide a valid JSON file path (e.g. "${attrs.src}.json").`;
3065
+ } else if (!attrs.src.endsWith(".json")) {
3066
+ hint = `Use <each in="${attrs.src}"> to iterate data from context, ` + `or include the ".json" extension if loading a file from "${dataDirDisplay}" (e.g. <each src="${attrs.src}.json">).`;
3067
+ } else {
3068
+ hint = `Verify that "${attrs.src}" exists in "${dataDirDisplay}" or check the relative path.`;
3069
+ }
3070
+ throw new BunticTemplateError({
3071
+ message: `[Buntic] <each> data file not found: "${attrs.src}" at ${filePath}`,
3072
+ location,
3073
+ projectRoot: this.config.root,
3074
+ resolvedTarget: filePath,
3075
+ hint
3076
+ });
3077
+ }
3078
+ try {
3079
+ items = await this.vfs.readJson(filePath);
3080
+ } catch (err) {
3081
+ const location = await locateEachItem(item);
3082
+ const ext = extname3(filePath).toLowerCase();
3083
+ const relResolved = formatTemplatePath(filePath, this.config.root);
3084
+ const existsInContext = getNestedValue(context, attrs.src) !== undefined;
3085
+ let hint;
3086
+ if (ext && ext !== ".json") {
3087
+ if (existsInContext) {
3088
+ hint = `Resolved file "${relResolved}" has extension "${ext}", not ".json".
3089
+ ` + `"${attrs.src}" is available in template context \u2014 use <each in="${attrs.src}"> or point "src" to a .json file (e.g. <each src="${attrs.src}.json">).`;
3090
+ } else {
3091
+ hint = `Resolved file "${relResolved}" has extension "${ext}", not ".json".
3092
+ ` + `Use <each in="${attrs.src}"> to iterate data from context, or point "src" to a .json file (e.g. <each src="${attrs.src}.json">).`;
3093
+ }
3094
+ } else {
3095
+ hint = `Check that "${relResolved}" contains valid JSON syntax.`;
3096
+ }
3097
+ throw new BunticTemplateError({
3098
+ message: `[Buntic] Failed to parse JSON data file for <each src="${attrs.src}">`,
3099
+ location,
3100
+ projectRoot: this.config.root,
3101
+ resolvedTarget: filePath,
3102
+ cause: err,
3103
+ hint
3104
+ });
2075
3105
  }
2076
- items = await this.vfs.readJson(filePath);
2077
3106
  } else if (attrs.in) {
2078
3107
  items = getNestedValue(context, attrs.in);
2079
3108
  } else {
2080
- throw new Error(`[Buntic] <each> tag requires either a "src" or "in" attribute.`);
3109
+ const location = await locateEachItem(item);
3110
+ throw new BunticTemplateError({
3111
+ message: `[Buntic] <each> tag requires either a "src" or "in" attribute.`,
3112
+ location,
3113
+ projectRoot: this.config.root,
3114
+ hint: `Use <each src="data.json"> for a JSON file or <each in="items"> for a context variable.`
3115
+ });
3116
+ }
3117
+ if ((items === undefined || items === null) && (elseBlock || defaultBlock)) {
3118
+ const fallbackContent = (elseBlock ?? defaultBlock).inner;
3119
+ const renderedFallback = await renderFallbackBlock(fallbackContent);
3120
+ result = replaceLiteral(result, item.fullMatch, renderedFallback);
3121
+ continue;
2081
3122
  }
2082
3123
  if (!Array.isArray(items)) {
2083
- throw new Error(`[Buntic] <each> source "${attrs.src || attrs.in}" did not resolve to an array.`);
3124
+ const location = await locateEachItem(item);
3125
+ const receivedType = items === null ? "null" : typeof items;
3126
+ let hint;
3127
+ if (attrs.in && items === undefined) {
3128
+ const availableKeys = Object.keys(context).filter((k) => k !== "env");
3129
+ const keysNote = availableKeys.length > 0 ? ` Available top-level keys: ${availableKeys.join(", ")}.` : "";
3130
+ hint = `Context path "${attrs.in}" is undefined. Check the variable name (page loader data lives under "props.*") or add an <else> / <default> fallback inside <each>.${keysNote}`;
3131
+ } else {
3132
+ hint = `<each> expects an array, but "${attrs.src || attrs.in}" resolved to ${receivedType}.`;
3133
+ }
3134
+ throw new BunticTemplateError({
3135
+ message: `[Buntic] <each> source "${attrs.src || attrs.in}" did not resolve to an array (received ${receivedType}).`,
3136
+ location,
3137
+ projectRoot: this.config.root,
3138
+ resolvedTarget: resolvedFilePath,
3139
+ hint
3140
+ });
3141
+ }
3142
+ if (items.length === 0) {
3143
+ const fallback = noneBlock ?? defaultBlock;
3144
+ const renderedFallback = fallback ? await renderFallbackBlock(fallback.inner) : "";
3145
+ result = replaceLiteral(result, item.fullMatch, renderedFallback);
3146
+ continue;
2084
3147
  }
2085
3148
  const renderedItems = [];
2086
3149
  for (const entry of items) {
@@ -2097,9 +3160,9 @@ class TemplateEngine {
2097
3160
  itemContext.item = entry;
2098
3161
  itemContext.this = entry;
2099
3162
  }
2100
- let rendered = await this.resolveEach(item.inner, itemContext, currentFile, depth + 1);
3163
+ let rendered = await this.resolveEach(loopTemplate, itemContext, currentFile, depth + 1);
2101
3164
  rendered = await this.resolveComponents(rendered, itemContext, currentFile, depth + 1);
2102
- rendered = this.resolveConditionals(rendered, itemContext);
3165
+ rendered = this.resolveConditionals(rendered, itemContext, currentFile, originalSourceForFile);
2103
3166
  rendered = this.interpolate(rendered, itemContext);
2104
3167
  renderedItems.push(rendered);
2105
3168
  }
@@ -2119,11 +3182,15 @@ class TemplateEngine {
2119
3182
  while ((match = componentRegex.exec(html)) !== null) {
2120
3183
  const props = parseHtmlAttributes(match[1]);
2121
3184
  if (props.src) {
3185
+ const fullMatch = match[0];
3186
+ const openTagEnd = fullMatch.indexOf(">");
2122
3187
  matches.push({
2123
- fullMatch: match[0],
3188
+ fullMatch,
3189
+ openTag: openTagEnd !== -1 ? fullMatch.slice(0, openTagEnd + 1) : fullMatch,
2124
3190
  children: match[2] ? match[2].trim() : "",
2125
3191
  src: props.src,
2126
- props
3192
+ props,
3193
+ index: match.index
2127
3194
  });
2128
3195
  }
2129
3196
  }
@@ -2133,7 +3200,23 @@ class TemplateEngine {
2133
3200
  for (const item of matches) {
2134
3201
  const compPath = this.resolveFilePath(item.src, currentFile, this.config.componentsDir);
2135
3202
  if (!this.vfs.hasFile(compPath) && !existsSync7(compPath)) {
2136
- throw new Error(`[Buntic] Component not found: "${item.src}" at ${compPath}`);
3203
+ const originalSource = await this.getOriginalSource(currentFile, html);
3204
+ const location = findSnippetLocation({
3205
+ source: originalSource,
3206
+ snippet: item.fullMatch,
3207
+ openTag: item.openTag,
3208
+ fallbackHtml: html,
3209
+ fallbackOffset: item.index,
3210
+ filePath: currentFile || undefined
3211
+ });
3212
+ const compDirDisplay = formatTemplatePath(this.config.componentsDir, this.config.root);
3213
+ throw new BunticTemplateError({
3214
+ message: `[Buntic] Component not found: "${item.src}" at ${compPath}`,
3215
+ location,
3216
+ projectRoot: this.config.root,
3217
+ resolvedTarget: compPath,
3218
+ hint: `Check that "${item.src}" exists in "${compDirDisplay}" or verify the relative path in <component src="${item.src}">.`
3219
+ });
2137
3220
  }
2138
3221
  const ext = extname3(compPath).toLowerCase();
2139
3222
  if (ext === ".ts" || ext === ".js" || ext === ".tsx" || ext === ".jsx") {
@@ -2144,7 +3227,11 @@ class TemplateEngine {
2144
3227
  children: item.children,
2145
3228
  context,
2146
3229
  currentFile,
2147
- depth
3230
+ depth,
3231
+ snippet: item.fullMatch,
3232
+ openTag: item.openTag,
3233
+ offset: item.index,
3234
+ sourceHtml: html
2148
3235
  });
2149
3236
  result = replaceLiteral(result, item.fullMatch, replacement);
2150
3237
  continue;
@@ -2160,9 +3247,9 @@ class TemplateEngine {
2160
3247
  result = replaceLiteral(result, item.fullMatch, svgContent);
2161
3248
  continue;
2162
3249
  }
2163
- let compTemplate = await this.vfs.readText(compPath);
2164
- compTemplate = await attachSiblingCssIfPresent({
2165
- templateHtml: compTemplate,
3250
+ const rawCompTemplate = await this.vfs.readText(compPath);
3251
+ let compTemplate = await attachSiblingCssIfPresent({
3252
+ templateHtml: rawCompTemplate,
2166
3253
  templatePath: compPath,
2167
3254
  siblingCssPath: compPath.replace(/\.html$/, ".css"),
2168
3255
  kindLabel: "Component",
@@ -2173,7 +3260,7 @@ class TemplateEngine {
2173
3260
  const compContext = { ...context, ...item.props };
2174
3261
  compTemplate = compTemplate.replace(/<slot\s*>\s*<\/slot>/gi, () => item.children);
2175
3262
  compTemplate = compTemplate.replace(/<slot\s*\/>/gi, () => item.children);
2176
- compTemplate = this.resolveConditionals(compTemplate, compContext);
3263
+ compTemplate = this.resolveConditionals(compTemplate, compContext, compPath, rawCompTemplate);
2177
3264
  compTemplate = this.interpolate(compTemplate, compContext);
2178
3265
  compTemplate = await this.resolveComponents(compTemplate, compContext, compPath, depth + 1);
2179
3266
  result = replaceLiteral(result, item.fullMatch, compTemplate);
@@ -2181,7 +3268,19 @@ class TemplateEngine {
2181
3268
  return result;
2182
3269
  }
2183
3270
  async renderWebComponentAlias(options) {
2184
- const { compPath, rawSrc, props, children, context, currentFile, depth } = options;
3271
+ const {
3272
+ compPath,
3273
+ rawSrc,
3274
+ props,
3275
+ children,
3276
+ context,
3277
+ currentFile,
3278
+ depth,
3279
+ snippet,
3280
+ openTag,
3281
+ offset,
3282
+ sourceHtml
3283
+ } = options;
2185
3284
  let tag = this.vfs.registry.getTagsForFile(compPath)[0];
2186
3285
  if (!tag) {
2187
3286
  let code;
@@ -2197,20 +3296,38 @@ class TemplateEngine {
2197
3296
  tag = filenameToTagName(compPath) || undefined;
2198
3297
  }
2199
3298
  if (!tag) {
2200
- throw new Error(`[Buntic] Could not determine Custom Element tag name for Web Component file "${rawSrc}". ` + `Ensure the filename follows kebab-case (e.g. "my-element.ts") or PascalCase (e.g. "MyElement.ts").`);
3299
+ const originalSource = await this.getOriginalSource(currentFile, sourceHtml || "");
3300
+ const location = findSnippetLocation({
3301
+ source: originalSource,
3302
+ snippet: snippet || "",
3303
+ openTag,
3304
+ fallbackHtml: sourceHtml,
3305
+ fallbackOffset: offset,
3306
+ filePath: currentFile || undefined
3307
+ });
3308
+ throw new BunticTemplateError({
3309
+ message: `[Buntic] Could not determine Custom Element tag name for Web Component file "${rawSrc}". ` + `Ensure the filename follows kebab-case (e.g. "my-element.ts") or PascalCase (e.g. "MyElement.ts").`,
3310
+ location,
3311
+ projectRoot: this.config.root,
3312
+ resolvedTarget: compPath
3313
+ });
2201
3314
  }
2202
3315
  const attrEntries = Object.entries(props).filter(([k]) => k !== "src");
2203
3316
  const attrString = attrEntries.length > 0 ? " " + attrEntries.map(([k, v]) => `${k}="${v}"`).join(" ") : "";
2204
3317
  let innerChildren = children;
2205
3318
  if (innerChildren) {
2206
3319
  innerChildren = await this.resolveComponents(innerChildren, context, currentFile, depth + 1);
2207
- innerChildren = this.resolveConditionals(innerChildren, context);
3320
+ innerChildren = this.resolveConditionals(innerChildren, context, currentFile, sourceHtml);
2208
3321
  innerChildren = this.interpolate(innerChildren, context);
2209
3322
  }
2210
3323
  return innerChildren ? `<${tag}${attrString}>${innerChildren}</${tag}>` : `<${tag}${attrString}></${tag}>`;
2211
3324
  }
2212
- resolveConditionals(html, context) {
2213
- return resolveConditionals(html, context);
3325
+ resolveConditionals(html, context, currentFile = "", originalSource) {
3326
+ return resolveConditionals(html, context, {
3327
+ filePath: currentFile || undefined,
3328
+ source: originalSource,
3329
+ projectRoot: this.config.root
3330
+ });
2214
3331
  }
2215
3332
  interpolate(html, context) {
2216
3333
  return interpolateTemplate(html, context);
@@ -2220,7 +3337,9 @@ var init_engine = __esm(() => {
2220
3337
  init_css_graph();
2221
3338
  init_css_resolver();
2222
3339
  init_data_loader();
3340
+ init_directives();
2223
3341
  init_dsd_renderer();
3342
+ init_errors();
2224
3343
  init_scoped_css();
2225
3344
  init_svg_component();
2226
3345
  init_vfs();
@@ -2229,13 +3348,13 @@ var init_engine = __esm(() => {
2229
3348
 
2230
3349
  // src/utils/paths.ts
2231
3350
  import { existsSync as existsSync8, readdirSync as readdirSync4, statSync as statSync3 } from "fs";
2232
- import { dirname as dirname7, join as join9, relative as relative6, resolve as resolve6, sep } from "path";
3351
+ import { dirname as dirname7, join as join9, relative as relative7, resolve as resolve6, sep } from "path";
2233
3352
  function isPathInside(baseDir, targetPath) {
2234
3353
  const absBase = resolve6(baseDir);
2235
3354
  const absTarget = resolve6(targetPath);
2236
3355
  if (absTarget === absBase)
2237
3356
  return true;
2238
- const rel = relative6(absBase, absTarget);
3357
+ const rel = relative7(absBase, absTarget);
2239
3358
  return rel !== "" && !rel.startsWith("..") && !rel.startsWith(sep) && !/^[a-zA-Z]:/.test(rel);
2240
3359
  }
2241
3360
  function resolveLocalAssetPath(config, src, fromFile) {
@@ -2277,7 +3396,7 @@ function walkFiles(dir, options = {}) {
2277
3396
  } else if (stat.isFile()) {
2278
3397
  if (options.filter && !options.filter(full, entry))
2279
3398
  continue;
2280
- results.push(relativeToBase ? relative6(baseDir, full).replace(/\\/g, "/") : full);
3399
+ results.push(relativeToBase ? relative7(baseDir, full).replace(/\\/g, "/") : full);
2281
3400
  }
2282
3401
  }
2283
3402
  return results;
@@ -2285,7 +3404,7 @@ function walkFiles(dir, options = {}) {
2285
3404
  var init_paths = () => {};
2286
3405
 
2287
3406
  // src/router/routes.ts
2288
- import { join as join10, relative as relative7, sep as sep2 } from "path";
3407
+ import { join as join10, relative as relative8, sep as sep2 } from "path";
2289
3408
  import { existsSync as existsSync9 } from "fs";
2290
3409
  function extractRouteTokens(routePattern) {
2291
3410
  const matches = routePattern.match(/\[([a-zA-Z0-9_-]+)\]/g);
@@ -2446,7 +3565,7 @@ async function resolveStaticRoute(options) {
2446
3565
  try {
2447
3566
  loaderResult = await executeStaticLoader(loaderPath, globalData, { cacheBust });
2448
3567
  } catch (err) {
2449
- logError(`Error executing loader "${relative7(config.root, loaderPath)}"`, err);
3568
+ logError(`Error executing loader "${relative8(config.root, loaderPath)}"`, err);
2450
3569
  throw err;
2451
3570
  }
2452
3571
  }
@@ -2480,7 +3599,7 @@ async function resolveDynamicRoutes(options) {
2480
3599
  throw new Error(`[Buntic Error]: Dynamic page "${relPattern}" contains parameter(s) [${tokens.join(", ")}], but no co-located loader was found.
2481
3600
  ` + `\uD83D\uDC49 Create "${expected}" exporting a default async function or getStaticPaths().`);
2482
3601
  }
2483
- const relLoader = relative7(config.root, loaderPath);
3602
+ const relLoader = relative8(config.root, loaderPath);
2484
3603
  let mod;
2485
3604
  try {
2486
3605
  const importPath = cacheBust ? `${loaderPath}?t=${Date.now()}` : loaderPath;
@@ -2547,7 +3666,7 @@ async function resolveAllRoutes(config, globalData, options) {
2547
3666
  const routes = [];
2548
3667
  const urlRegistry = new Map;
2549
3668
  for (const templatePath of htmlFiles) {
2550
- const relPattern = relative7(config.pagesDir, templatePath);
3669
+ const relPattern = relative8(config.pagesDir, templatePath);
2551
3670
  const isDynamic = isDynamicPattern(relPattern);
2552
3671
  const tokens = extractRouteTokens(relPattern);
2553
3672
  const loaderPath = findCoLocatedLoader(templatePath);
@@ -3420,7 +4539,7 @@ var init_feeds = () => {};
3420
4539
 
3421
4540
  // src/builder/collisions.ts
3422
4541
  import { existsSync as existsSync17 } from "fs";
3423
- import { join as join17, relative as relative8 } from "path";
4542
+ import { join as join17, relative as relative9 } from "path";
3424
4543
  function getDirectoryFiles(dir, baseDir = dir) {
3425
4544
  return walkFiles(dir, {
3426
4545
  baseDir,
@@ -3435,7 +4554,7 @@ function detectPublicCollisions(config, routes) {
3435
4554
  const collisions = [];
3436
4555
  const routeOutputMap = new Map;
3437
4556
  for (const route of routes) {
3438
- const relOut = relative8(config.outDir, route.outputFilePath).replace(/\\/g, "/");
4557
+ const relOut = relative9(config.outDir, route.outputFilePath).replace(/\\/g, "/");
3439
4558
  routeOutputMap.set(relOut, route);
3440
4559
  }
3441
4560
  for (const relFile of publicFiles) {
@@ -3443,22 +4562,22 @@ function detectPublicCollisions(config, routes) {
3443
4562
  const route = routeOutputMap.get(relFile);
3444
4563
  collisions.push({
3445
4564
  type: "route",
3446
- publicPath: relative8(config.root, join17(config.publicDir, relFile)),
3447
- conflictWith: relative8(config.root, route.templateFilePath),
4565
+ publicPath: relative9(config.root, join17(config.publicDir, relFile)),
4566
+ conflictWith: relative9(config.root, route.templateFilePath),
3448
4567
  outputPath: relFile
3449
4568
  });
3450
4569
  }
3451
4570
  if (relFile.startsWith("assets/images/") || relFile === "assets/images") {
3452
4571
  collisions.push({
3453
4572
  type: "reserved-dir",
3454
- publicPath: relative8(config.root, join17(config.publicDir, relFile)),
4573
+ publicPath: relative9(config.root, join17(config.publicDir, relFile)),
3455
4574
  conflictWith: "assets/images/ (Reserved for Buntic <photo> image optimization)",
3456
4575
  outputPath: relFile
3457
4576
  });
3458
4577
  } else if (relFile.startsWith("assets/seo/") || relFile === "assets/seo") {
3459
4578
  collisions.push({
3460
4579
  type: "reserved-dir",
3461
- publicPath: relative8(config.root, join17(config.publicDir, relFile)),
4580
+ publicPath: relative9(config.root, join17(config.publicDir, relFile)),
3462
4581
  conflictWith: "assets/seo/ (Reserved for Buntic <seo> social cards)",
3463
4582
  outputPath: relFile
3464
4583
  });
@@ -3488,7 +4607,7 @@ var init_collisions = __esm(() => {
3488
4607
 
3489
4608
  // src/builder/builder.ts
3490
4609
  import { cpSync as cpSync2, existsSync as existsSync18, mkdirSync as mkdirSync3, rmSync as rmSync3 } from "fs";
3491
- import { dirname as dirname9, join as join18, relative as relative9 } from "path";
4610
+ import { dirname as dirname9, join as join18, relative as relative10 } from "path";
3492
4611
 
3493
4612
  class Builder {
3494
4613
  config;
@@ -3566,7 +4685,7 @@ class Builder {
3566
4685
  }
3567
4686
  }
3568
4687
  }
3569
- const relStagedPath = relative9(this.config.outDir, route.outputFilePath);
4688
+ const relStagedPath = relative10(this.config.outDir, route.outputFilePath);
3570
4689
  const stagedPath = join18(stagingDir, relStagedPath);
3571
4690
  mkdirSync3(dirname9(stagedPath), { recursive: true });
3572
4691
  rendered = this.normalizeRootPaths(rendered, stagedPath, stagingDir);
@@ -3644,7 +4763,7 @@ class Builder {
3644
4763
  warnUnusedWebComponents() {
3645
4764
  const unused = this.engine.getUnusedWebComponents();
3646
4765
  for (const item of unused) {
3647
- logWarn(`Web Component "<${item.tag}>" (${relative9(this.config.root, item.file)}) is registered but not used in any page.`);
4766
+ logWarn(`Web Component "<${item.tag}>" (${relative10(this.config.root, item.file)}) is registered but not used in any page.`);
3648
4767
  }
3649
4768
  }
3650
4769
  normalizeRootPaths(html, stagedFilePath, stagingDir) {
@@ -3655,14 +4774,14 @@ class Builder {
3655
4774
  }
3656
4775
  const targetInRoot = join18(this.config.root, path);
3657
4776
  if (existsSync18(targetInRoot)) {
3658
- let rel = relative9(fromDir, targetInRoot);
4777
+ let rel = relative10(fromDir, targetInRoot);
3659
4778
  if (!rel.startsWith("."))
3660
4779
  rel = "./" + rel;
3661
4780
  return `${attr}="${rel}"`;
3662
4781
  }
3663
4782
  const targetInSrc = join18(this.config.root, "src", path);
3664
4783
  if (existsSync18(targetInSrc)) {
3665
- let rel = relative9(fromDir, targetInSrc);
4784
+ let rel = relative10(fromDir, targetInSrc);
3666
4785
  if (!rel.startsWith("."))
3667
4786
  rel = "./" + rel;
3668
4787
  return `${attr}="${rel}"`;
@@ -3670,7 +4789,7 @@ class Builder {
3670
4789
  if (stagingDir) {
3671
4790
  const targetInStaging = join18(stagingDir, path);
3672
4791
  if (existsSync18(targetInStaging)) {
3673
- let rel = relative9(fromDir, targetInStaging);
4792
+ let rel = relative10(fromDir, targetInStaging);
3674
4793
  if (!rel.startsWith("."))
3675
4794
  rel = "./" + rel;
3676
4795
  return `${attr}="${rel}"`;
@@ -3812,10 +4931,82 @@ function getMimeType(path) {
3812
4931
  return "text/plain; charset=utf-8";
3813
4932
  return "application/octet-stream";
3814
4933
  }
4934
+ function formatCodeFrameHtml(codeFrame) {
4935
+ return codeFrame.split(`
4936
+ `).map((line) => {
4937
+ const escaped = escapeHtml(line);
4938
+ if (line.startsWith(" > ")) {
4939
+ return `<span class="error-line">${escaped}</span>`;
4940
+ }
4941
+ if (/^\s+\|\s+\^+$/.test(line)) {
4942
+ return `<span class="error-caret">${escaped}</span>`;
4943
+ }
4944
+ return escaped;
4945
+ }).join(`
4946
+ `);
4947
+ }
3815
4948
  function renderErrorResponse(title, err) {
3816
4949
  const safeTitle = escapeHtml(title);
3817
4950
  const safeMsg = escapeHtml(getErrorMessage(err));
3818
- return new Response(`<h1>${safeTitle}</h1><pre>${safeMsg}</pre>`, {
4951
+ let bodyContent;
4952
+ if (err instanceof BunticTemplateError) {
4953
+ const metaRows = [];
4954
+ if (err.filePath) {
4955
+ const coords = err.line ? `:${err.line}${err.column ? `:${err.column}` : ""}` : "";
4956
+ metaRows.push(`<div class="meta-row"><span class="meta-label">File</span><code>${escapeHtml(err.filePath + coords)}</code></div>`);
4957
+ } else if (err.line) {
4958
+ const colText = err.column ? `, column ${err.column}` : "";
4959
+ metaRows.push(`<div class="meta-row"><span class="meta-label">Location</span><code>line ${err.line}${colText}</code></div>`);
4960
+ }
4961
+ if (err.resolvedTarget) {
4962
+ metaRows.push(`<div class="meta-row"><span class="meta-label">Resolved</span><code>${escapeHtml(err.resolvedTarget)}</code></div>`);
4963
+ }
4964
+ if (err.causeMessage) {
4965
+ metaRows.push(`<div class="meta-row"><span class="meta-label">Cause</span><span class="cause-text">${escapeHtml(err.causeMessage)}</span></div>`);
4966
+ }
4967
+ const metaBlock = metaRows.length > 0 ? `<div class="meta">${metaRows.join("")}</div>` : "";
4968
+ const frameBlock = err.codeFrame ? `<pre class="code-frame">${formatCodeFrameHtml(err.codeFrame)}</pre>` : "";
4969
+ const hintBlock = err.hint ? `<div class="hint"><strong>Hint:</strong> ${escapeHtml(err.hint).replace(/\n/g, "<br>")}</div>` : "";
4970
+ bodyContent = `
4971
+ <p class="summary">${escapeHtml(err.summary)}</p>
4972
+ ${metaBlock}
4973
+ ${frameBlock}
4974
+ ${hintBlock}
4975
+ `;
4976
+ } else {
4977
+ bodyContent = `<pre class="code-frame">${safeMsg}</pre>`;
4978
+ }
4979
+ const errorHtml = `<!doctype html>
4980
+ <html>
4981
+ <head>
4982
+ <meta charset="utf-8">
4983
+ <title>${safeTitle} | Buntic Dev</title>
4984
+ <style>
4985
+ body { font-family: system-ui, -apple-system, sans-serif; background: #0f172a; color: #f8fafc; padding: 2.5rem 1.5rem; margin: 0; }
4986
+ .card { max-width: 820px; margin: 0 auto; background: #1e293b; padding: 2rem; border-radius: 12px; border: 1px solid #334155; box-shadow: 0 20px 40px rgba(0,0,0,0.35); }
4987
+ h1 { color: #f43f5e; margin: 0 0 1rem; font-size: 1.5rem; }
4988
+ .summary { font-size: 1.05rem; color: #fecdd3; margin: 0 0 1.25rem; line-height: 1.5; font-weight: 500; }
4989
+ .meta { display: flex; flex-direction: column; gap: 0.45rem; margin-bottom: 1.25rem; padding: 0.9rem 1rem; background: #0f172a; border-radius: 8px; border: 1px solid #334155; }
4990
+ .meta-row { display: flex; align-items: baseline; gap: 0.75rem; font-size: 0.92rem; flex-wrap: wrap; }
4991
+ .meta-label { color: #94a3b8; min-width: 72px; font-weight: 600; text-transform: uppercase; font-size: 0.75rem; letter-spacing: 0.04em; }
4992
+ code { color: #38bdf8; font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; font-size: 0.9rem; word-break: break-all; }
4993
+ .cause-text { color: #fda4af; font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; font-size: 0.9rem; }
4994
+ pre.code-frame { background: #020617; color: #e2e8f0; padding: 1rem 1.1rem; border-radius: 8px; border: 1px solid #334155; overflow-x: auto; font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; font-size: 0.9rem; line-height: 1.6; margin: 0 0 1.25rem; }
4995
+ .error-line { display: inline-block; min-width: 100%; background: rgba(244, 63, 94, 0.18); color: #fff1f2; font-weight: 600; }
4996
+ .error-caret { color: #f43f5e; font-weight: 700; }
4997
+ .hint { background: rgba(56, 189, 248, 0.1); border-left: 3px solid #38bdf8; padding: 0.85rem 1rem; border-radius: 0 8px 8px 0; color: #e0f2fe; font-size: 0.92rem; line-height: 1.55; }
4998
+ .hint strong { color: #38bdf8; }
4999
+ </style>
5000
+ </head>
5001
+ <body>
5002
+ <div class="card">
5003
+ <h1>${safeTitle}</h1>
5004
+ ${bodyContent}
5005
+ </div>
5006
+ ${LIVE_RELOAD_SCRIPT}
5007
+ </body>
5008
+ </html>`;
5009
+ return new Response(errorHtml, {
3819
5010
  status: 500,
3820
5011
  headers: { "Content-Type": "text/html; charset=utf-8" }
3821
5012
  });
@@ -3879,6 +5070,7 @@ var init_dev_helpers = __esm(() => {
3879
5070
  init_feeds();
3880
5071
  init_robots();
3881
5072
  init_sitemap();
5073
+ init_errors();
3882
5074
  init_paths();
3883
5075
  });
3884
5076
 
@@ -4064,6 +5256,7 @@ var init_dev = __esm(() => {
4064
5256
  // src/index.ts
4065
5257
  init_config();
4066
5258
  init_engine();
5259
+ init_errors();
4067
5260
  init_env();
4068
5261
  init_routes();
4069
5262
  init_cache();
@@ -4828,7 +6021,7 @@ init_builder();
4828
6021
  init_dev();
4829
6022
  init_cache();
4830
6023
  import { existsSync as existsSync22, rmSync as rmSync4 } from "fs";
4831
- import { relative as relative10 } from "path";
6024
+ import { relative as relative11 } from "path";
4832
6025
  init_runtime();
4833
6026
  async function runCLI(args) {
4834
6027
  registerBunticModuleResolver();
@@ -4891,7 +6084,7 @@ async function runCLI(args) {
4891
6084
  includeSkills,
4892
6085
  force
4893
6086
  });
4894
- const relTarget = relative10(process.cwd(), result.targetDir) || ".";
6087
+ const relTarget = relative11(process.cwd(), result.targetDir) || ".";
4895
6088
  console.log(`
4896
6089
  \u26A1 \x1B[36m[Buntic]\x1B[0m Initialized new project (\x1B[33m${result.template}\x1B[0m) in: \x1B[32m${result.targetDir}\x1B[0m`);
4897
6090
  console.log(` \u2714 Created ${result.filesCopied} file(s) (no package.json required)`);
@@ -5019,6 +6212,7 @@ export {
5019
6212
  AssetCache,
5020
6213
  AuthManager,
5021
6214
  Builder,
6215
+ BunticTemplateError,
5022
6216
  ImageProcessor,
5023
6217
  OrasClient,
5024
6218
  PhotoProcessor,