buntic 0.3.0 → 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/LICENSE +1 -1
- package/README.md +39 -39
- package/dist/cli.js +1362 -189
- package/dist/config.d.ts +5 -5
- package/dist/index.d.ts +6 -5
- package/dist/index.js +1389 -201
- package/dist/router/routes.d.ts +1 -1
- package/dist/runtime.d.ts +8 -9
- package/dist/server/dev-helpers.d.ts +1 -1
- package/dist/storage/oras/adapter.d.ts +2 -2
- package/dist/template/block-scanner.d.ts +28 -0
- package/dist/template/directives.d.ts +17 -8
- package/dist/template/engine.d.ts +2 -1
- package/dist/template/errors.d.ts +58 -0
- package/dist/template/expressions.d.ts +16 -0
- package/dist/template/scoped-css.d.ts +1 -1
- package/dist/types.d.ts +1 -1
- package/dist/utils/html.d.ts +1 -1
- package/dist/utils/logger.d.ts +1 -1
- package/package.json +7 -7
- package/templates/blank/_gitignore +2 -2
- package/templates/blank/{bustatic.config.ts → buntic.config.ts} +2 -2
- package/templates/blank/src/pages/index.html +2 -2
- package/templates/blank/tsconfig.json +4 -9
- package/templates/simple/README.md +6 -6
- package/templates/simple/_gitignore +2 -2
- package/templates/simple/{bustatic.config.ts → buntic.config.ts} +2 -2
- package/templates/simple/src/components/footer.html +1 -1
- package/templates/simple/src/data/site.json +3 -3
- package/templates/simple/src/pages/about.html +1 -1
- package/templates/simple/src/pages/contact.html +1 -1
- package/templates/simple/tsconfig.json +4 -9
- package/templates/skills/{bustatic → buntic}/SKILL.md +83 -43
- package/templates/skills/{bustatic → buntic}/examples/README.md +4 -4
package/dist/index.js
CHANGED
|
@@ -22,7 +22,7 @@ function getPackageRoot() {
|
|
|
22
22
|
if (existsSync(pkgPath)) {
|
|
23
23
|
try {
|
|
24
24
|
const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
|
|
25
|
-
if (
|
|
25
|
+
if (pkg?.name === "buntic") {
|
|
26
26
|
return current;
|
|
27
27
|
}
|
|
28
28
|
} catch {}
|
|
@@ -48,10 +48,10 @@ function getSelfEntryPath() {
|
|
|
48
48
|
}
|
|
49
49
|
return distEntry;
|
|
50
50
|
}
|
|
51
|
-
function
|
|
51
|
+
function hasLocalBunticPackage(startDir) {
|
|
52
52
|
let current = resolve(startDir);
|
|
53
53
|
while (true) {
|
|
54
|
-
if (existsSync(join(current, "node_modules", "
|
|
54
|
+
if (existsSync(join(current, "node_modules", "buntic", "package.json"))) {
|
|
55
55
|
return true;
|
|
56
56
|
}
|
|
57
57
|
const parent = dirname(current);
|
|
@@ -61,27 +61,23 @@ function hasLocalBustaticPackage(startDir) {
|
|
|
61
61
|
current = parent;
|
|
62
62
|
}
|
|
63
63
|
}
|
|
64
|
-
function
|
|
64
|
+
function registerBunticModuleResolver(projectDir) {
|
|
65
65
|
if (resolverRegistered)
|
|
66
66
|
return;
|
|
67
|
-
if (projectDir &&
|
|
67
|
+
if (projectDir && hasLocalBunticPackage(projectDir))
|
|
68
68
|
return;
|
|
69
69
|
resolverRegistered = true;
|
|
70
70
|
const selfEntry = getSelfEntryPath();
|
|
71
71
|
Bun.plugin({
|
|
72
|
-
name: "
|
|
72
|
+
name: "buntic-global-self-resolver",
|
|
73
73
|
setup(build) {
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
});
|
|
82
|
-
};
|
|
83
|
-
registerAlias("bun-bustatic");
|
|
84
|
-
registerAlias("bustatic");
|
|
74
|
+
build.module("buntic", async () => {
|
|
75
|
+
const mod = await import(selfEntry);
|
|
76
|
+
return {
|
|
77
|
+
exports: { ...mod },
|
|
78
|
+
loader: "object"
|
|
79
|
+
};
|
|
80
|
+
});
|
|
85
81
|
}
|
|
86
82
|
});
|
|
87
83
|
}
|
|
@@ -102,7 +98,7 @@ function copyDeclarationFiles(srcDir, destDir) {
|
|
|
102
98
|
}
|
|
103
99
|
function syncProjectTypes(projectRoot) {
|
|
104
100
|
const absRoot = resolve(projectRoot);
|
|
105
|
-
if (
|
|
101
|
+
if (hasLocalBunticPackage(absRoot)) {
|
|
106
102
|
return false;
|
|
107
103
|
}
|
|
108
104
|
const pkgRoot = getPackageRoot();
|
|
@@ -112,17 +108,17 @@ function syncProjectTypes(projectRoot) {
|
|
|
112
108
|
if (pkg?.version)
|
|
113
109
|
version = pkg.version;
|
|
114
110
|
} catch {}
|
|
115
|
-
const
|
|
116
|
-
const typesDir = join(
|
|
111
|
+
const bunticDir = join(absRoot, ".buntic");
|
|
112
|
+
const typesDir = join(bunticDir, "types");
|
|
117
113
|
const typesEntry = join(typesDir, "index.d.ts");
|
|
118
|
-
const versionMarkerPath = join(
|
|
114
|
+
const versionMarkerPath = join(bunticDir, ".types-version");
|
|
119
115
|
const distDir = join(pkgRoot, "dist");
|
|
120
116
|
const hasBuiltTypes = existsSync(join(distDir, "index.d.ts"));
|
|
121
117
|
const expectedMarker = `${version}:${hasBuiltTypes ? "dist" : "src"}`;
|
|
122
118
|
if (existsSync(typesEntry) && existsSync(versionMarkerPath) && readFileSync(versionMarkerPath, "utf8").trim() === expectedMarker) {
|
|
123
119
|
return false;
|
|
124
120
|
}
|
|
125
|
-
mkdirSync(
|
|
121
|
+
mkdirSync(bunticDir, { recursive: true });
|
|
126
122
|
if (existsSync(typesDir)) {
|
|
127
123
|
rmSync(typesDir, { recursive: true, force: true });
|
|
128
124
|
}
|
|
@@ -131,7 +127,7 @@ function syncProjectTypes(projectRoot) {
|
|
|
131
127
|
copyDeclarationFiles(distDir, typesDir);
|
|
132
128
|
} else {
|
|
133
129
|
const srcIndex = join(pkgRoot, "src", "index.ts").replace(/\\/g, "/");
|
|
134
|
-
writeFileSync(typesEntry, `// Auto-generated by
|
|
130
|
+
writeFileSync(typesEntry, `// Auto-generated by Buntic (source dev fallback).
|
|
135
131
|
export * from "${srcIndex}";
|
|
136
132
|
`, "utf8");
|
|
137
133
|
}
|
|
@@ -139,10 +135,8 @@ export * from "${srcIndex}";
|
|
|
139
135
|
`, "utf8");
|
|
140
136
|
return true;
|
|
141
137
|
}
|
|
142
|
-
var resolverRegistered = false
|
|
143
|
-
var init_runtime =
|
|
144
|
-
PACKAGE_NAMES = new Set(["buntic", "bun-bustatic", "bustatic"]);
|
|
145
|
-
});
|
|
138
|
+
var resolverRegistered = false;
|
|
139
|
+
var init_runtime = () => {};
|
|
146
140
|
|
|
147
141
|
// src/config.ts
|
|
148
142
|
import { resolve as resolve2, join as join2, dirname as dirname2, basename } from "path";
|
|
@@ -154,13 +148,13 @@ function findProjectRoot(cliTarget, startCwd = process.cwd()) {
|
|
|
154
148
|
if (cliTarget && cliTarget !== ".") {
|
|
155
149
|
const target = resolve2(startCwd, cliTarget);
|
|
156
150
|
if (!existsSync2(target)) {
|
|
157
|
-
throw new Error(`[
|
|
151
|
+
throw new Error(`[Buntic] Specified project directory does not exist: "${target}"`);
|
|
158
152
|
}
|
|
159
153
|
return target;
|
|
160
154
|
}
|
|
161
155
|
let current = resolve2(startCwd);
|
|
162
156
|
while (true) {
|
|
163
|
-
const hasConfig = existsSync2(join2(current, "
|
|
157
|
+
const hasConfig = existsSync2(join2(current, "buntic.config.ts")) || existsSync2(join2(current, "buntic.config.js")) || existsSync2(join2(current, "buntic.config.json"));
|
|
164
158
|
if (hasConfig) {
|
|
165
159
|
return current;
|
|
166
160
|
}
|
|
@@ -181,27 +175,27 @@ function findProjectRoot(cliTarget, startCwd = process.cwd()) {
|
|
|
181
175
|
}
|
|
182
176
|
current = parent;
|
|
183
177
|
}
|
|
184
|
-
throw new Error(`[
|
|
178
|
+
throw new Error(`[Buntic Error]: Could not find a Buntic project root.
|
|
185
179
|
` + ` Searched in: ${startCwd} (and parent directories)
|
|
186
180
|
|
|
187
181
|
` + `\uD83D\uDC49 How to fix this:
|
|
188
182
|
` + ` 1. Ensure you have a "pages/" or "src/pages/" directory with at least one .html file.
|
|
189
183
|
` + ` 2. Or pass the project path explicitly:
|
|
190
|
-
` + ` $
|
|
191
|
-
` + ` 3. Or create a "
|
|
184
|
+
` + ` $ buntic dev <directory> (e.g. buntic dev examples/simple)
|
|
185
|
+
` + ` 3. Or create a "buntic.config.ts" / "buntic.config.json" configuration file (or run "buntic init").`);
|
|
192
186
|
}
|
|
193
187
|
async function resolveConfig(cliRootDir = ".", overrides = {}) {
|
|
194
188
|
const root = findProjectRoot(cliRootDir);
|
|
195
189
|
let userConfig = {};
|
|
196
|
-
const tsConfigPath = join2(root, "
|
|
197
|
-
const jsConfigPath = join2(root, "
|
|
198
|
-
const jsonConfigPath = join2(root, "
|
|
190
|
+
const tsConfigPath = join2(root, "buntic.config.ts");
|
|
191
|
+
const jsConfigPath = join2(root, "buntic.config.js");
|
|
192
|
+
const jsonConfigPath = join2(root, "buntic.config.json");
|
|
199
193
|
if (existsSync2(tsConfigPath)) {
|
|
200
|
-
|
|
194
|
+
registerBunticModuleResolver(root);
|
|
201
195
|
const mod = await import(tsConfigPath);
|
|
202
196
|
userConfig = mod.default || mod;
|
|
203
197
|
} else if (existsSync2(jsConfigPath)) {
|
|
204
|
-
|
|
198
|
+
registerBunticModuleResolver(root);
|
|
205
199
|
const mod = await import(jsConfigPath);
|
|
206
200
|
userConfig = mod.default || mod;
|
|
207
201
|
} else if (existsSync2(jsonConfigPath)) {
|
|
@@ -234,7 +228,7 @@ async function resolveConfig(cliRootDir = ".", overrides = {}) {
|
|
|
234
228
|
dataDir: resolve2(root, merged.dataDir ?? pickDir("data")),
|
|
235
229
|
publicDir: resolve2(root, merged.publicDir ?? pickDir("public", true)),
|
|
236
230
|
storageDir: resolve2(root, merged.storageDir ?? pickDir("storage")),
|
|
237
|
-
cacheDir: resolve2(root, merged.cacheDir ?? ".
|
|
231
|
+
cacheDir: resolve2(root, merged.cacheDir ?? ".buntic/cache/images"),
|
|
238
232
|
outDir: resolve2(root, merged.outDir ?? "dist"),
|
|
239
233
|
port: merged.port ?? 3000,
|
|
240
234
|
minify: merged.minify ?? true,
|
|
@@ -314,10 +308,10 @@ function getErrorMessage(err) {
|
|
|
314
308
|
return String(err);
|
|
315
309
|
}
|
|
316
310
|
}
|
|
317
|
-
function logWarn(message, label = "
|
|
311
|
+
function logWarn(message, label = "Buntic Warning") {
|
|
318
312
|
console.warn(`\x1B[33m\u26A0 [${label}]\x1B[0m ${message}`);
|
|
319
313
|
}
|
|
320
|
-
function logError(message, err, label = "
|
|
314
|
+
function logError(message, err, label = "Buntic Error") {
|
|
321
315
|
if (err !== undefined) {
|
|
322
316
|
console.error(`\x1B[31m[${label}]\x1B[0m ${message}:`, getErrorMessage(err));
|
|
323
317
|
} else {
|
|
@@ -325,6 +319,183 @@ function logError(message, err, label = "Bustatic Error") {
|
|
|
325
319
|
}
|
|
326
320
|
}
|
|
327
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
|
+
|
|
328
499
|
// src/template/web-components.ts
|
|
329
500
|
import { basename as basename2, extname, dirname as dirname3, join as join3 } from "path";
|
|
330
501
|
function pascalToKebab(pascal) {
|
|
@@ -370,13 +541,13 @@ class WebComponentRegistry {
|
|
|
370
541
|
const expectedTag = filenameToTagName(filePath);
|
|
371
542
|
if (!expectedTag) {
|
|
372
543
|
if (content && /(?:customElements\.define|@customElement)\s*\(\s*["']([a-z0-9-]+)["']/i.test(content)) {
|
|
373
|
-
console.warn(`\x1B[33m\u26A0 [
|
|
544
|
+
console.warn(`\x1B[33m\u26A0 [Buntic Warning]\x1B[0m Web Component file "${filePath}" does not match naming convention (must be hyphenated kebab-case like "my-button.ts" or PascalCase like "MyButton.ts"). Registration skipped.`);
|
|
374
545
|
}
|
|
375
546
|
return [];
|
|
376
547
|
}
|
|
377
548
|
const validation = this.validateTagName(expectedTag);
|
|
378
549
|
if (!validation.valid) {
|
|
379
|
-
console.warn(`\x1B[33m\u26A0 [
|
|
550
|
+
console.warn(`\x1B[33m\u26A0 [Buntic Warning]\x1B[0m Skipping invalid Custom Element tag "${expectedTag}" in ${filePath}: ${validation.reason}`);
|
|
380
551
|
return [];
|
|
381
552
|
}
|
|
382
553
|
if (content) {
|
|
@@ -387,13 +558,13 @@ class WebComponentRegistry {
|
|
|
387
558
|
declaredTags.add(match[1].toLowerCase());
|
|
388
559
|
}
|
|
389
560
|
if (declaredTags.size > 1) {
|
|
390
|
-
console.warn(`\x1B[33m\u26A0 [
|
|
561
|
+
console.warn(`\x1B[33m\u26A0 [Buntic Warning]\x1B[0m File "${filePath}" declares multiple Custom Elements (${Array.from(declaredTags).map((t) => `<${t}>`).join(", ")}). Buntic strictly enforces 1 Web Component per file. File skipped.`);
|
|
391
562
|
return [];
|
|
392
563
|
}
|
|
393
564
|
if (declaredTags.size === 1) {
|
|
394
565
|
const declaredTag = Array.from(declaredTags)[0];
|
|
395
566
|
if (declaredTag !== expectedTag) {
|
|
396
|
-
console.warn(`\x1B[33m\u26A0 [
|
|
567
|
+
console.warn(`\x1B[33m\u26A0 [Buntic Warning]\x1B[0m Tag "<${declaredTag}>" in "${filePath}" does not match filename. Expected tag "<${expectedTag}>" for file "${basename2(filePath)}". Registration skipped.`);
|
|
397
568
|
return [];
|
|
398
569
|
}
|
|
399
570
|
}
|
|
@@ -405,7 +576,7 @@ class WebComponentRegistry {
|
|
|
405
576
|
conflictFiles.push(filePath);
|
|
406
577
|
}
|
|
407
578
|
this.conflicts.set(expectedTag, conflictFiles);
|
|
408
|
-
console.warn(`\x1B[33m\u26A0 [
|
|
579
|
+
console.warn(`\x1B[33m\u26A0 [Buntic Collision Warning]\x1B[0m Tag "<${expectedTag}>" in ${filePath} conflicts with definition in ${existingFile}.`);
|
|
409
580
|
return [];
|
|
410
581
|
}
|
|
411
582
|
this.tagToFile.set(expectedTag, filePath);
|
|
@@ -462,7 +633,7 @@ ${c.files.map((f) => ` - ${f}`).join(`
|
|
|
462
633
|
`)}`).join(`
|
|
463
634
|
|
|
464
635
|
`);
|
|
465
|
-
throw new Error(`[
|
|
636
|
+
throw new Error(`[Buntic Conflict Error]: Tag collision detected between Web Components:
|
|
466
637
|
${details}
|
|
467
638
|
|
|
468
639
|
` + `\uD83D\uDC49 Each Custom Element tag must be uniquely defined.`);
|
|
@@ -1214,7 +1385,7 @@ async function resolvePageCss(options) {
|
|
|
1214
1385
|
} catch {
|
|
1215
1386
|
cssContent = await Bun.file(cssFilePath).text();
|
|
1216
1387
|
}
|
|
1217
|
-
const styleBlock = `<style id="
|
|
1388
|
+
const styleBlock = `<style id="__buntic_global">
|
|
1218
1389
|
${cssContent}
|
|
1219
1390
|
</style>`;
|
|
1220
1391
|
result = replaceLiteral(result, fullTag, styleBlock);
|
|
@@ -1222,15 +1393,15 @@ ${cssContent}
|
|
|
1222
1393
|
}
|
|
1223
1394
|
}
|
|
1224
1395
|
const headMatch = result.match(/<head[\s\S]*?<\/head>/i);
|
|
1225
|
-
const headHasGlobalStyle = headMatch ? headMatch[0].includes('id="
|
|
1396
|
+
const headHasGlobalStyle = headMatch ? headMatch[0].includes('id="__buntic_global"') : false;
|
|
1226
1397
|
if (!hadManualGlobalLink && !headHasGlobalStyle && globalCssContent) {
|
|
1227
|
-
const globalTag = ` <style id="
|
|
1398
|
+
const globalTag = ` <style id="__buntic_global">
|
|
1228
1399
|
${globalCssContent}
|
|
1229
1400
|
</style>`;
|
|
1230
1401
|
result = injectIntoHead(result, globalTag, "prepend");
|
|
1231
1402
|
}
|
|
1232
1403
|
if (hasScopedRules) {
|
|
1233
|
-
const scopedTag = ` <style id="
|
|
1404
|
+
const scopedTag = ` <style id="__buntic_scoped">
|
|
1234
1405
|
${scopedCssText}
|
|
1235
1406
|
</style>`;
|
|
1236
1407
|
result = injectIntoHead(result, scopedTag, "append");
|
|
@@ -1314,6 +1485,159 @@ var init_env = __esm(() => {
|
|
|
1314
1485
|
RESERVED_NAMESPACES = new Set(["params", "props", "env"]);
|
|
1315
1486
|
});
|
|
1316
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
|
+
|
|
1317
1641
|
// src/template/data-loader.ts
|
|
1318
1642
|
import { existsSync as existsSync5, readdirSync as readdirSync2 } from "fs";
|
|
1319
1643
|
import { join as join7 } from "path";
|
|
@@ -1349,8 +1673,15 @@ async function loadGlobalData(config, vfs) {
|
|
|
1349
1673
|
if (isJson) {
|
|
1350
1674
|
try {
|
|
1351
1675
|
data[key] = await vfs.readJson(fullPath);
|
|
1352
|
-
} catch {
|
|
1353
|
-
|
|
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
|
+
});
|
|
1354
1685
|
}
|
|
1355
1686
|
} else if (isModule) {
|
|
1356
1687
|
try {
|
|
@@ -1370,7 +1701,7 @@ async function loadGlobalData(config, vfs) {
|
|
|
1370
1701
|
}
|
|
1371
1702
|
}
|
|
1372
1703
|
} catch (err) {
|
|
1373
|
-
if (err instanceof Error && err.message.includes("[
|
|
1704
|
+
if (err instanceof BunticTemplateError || err instanceof Error && err.message.includes("[Buntic Error]")) {
|
|
1374
1705
|
throw err;
|
|
1375
1706
|
}
|
|
1376
1707
|
}
|
|
@@ -1378,15 +1709,16 @@ async function loadGlobalData(config, vfs) {
|
|
|
1378
1709
|
}
|
|
1379
1710
|
var init_data_loader = __esm(() => {
|
|
1380
1711
|
init_env();
|
|
1712
|
+
init_errors();
|
|
1381
1713
|
});
|
|
1382
1714
|
|
|
1383
|
-
// src/template/
|
|
1715
|
+
// src/template/expressions.ts
|
|
1384
1716
|
function isTruthy(val) {
|
|
1385
1717
|
if (val === undefined || val === null || val === false || val === "")
|
|
1386
1718
|
return false;
|
|
1387
1719
|
if (Array.isArray(val) && val.length === 0)
|
|
1388
1720
|
return false;
|
|
1389
|
-
if (typeof val === "number" && isNaN(val))
|
|
1721
|
+
if (typeof val === "number" && Number.isNaN(val))
|
|
1390
1722
|
return false;
|
|
1391
1723
|
return true;
|
|
1392
1724
|
}
|
|
@@ -1396,36 +1728,613 @@ function getNestedValue(obj, path) {
|
|
|
1396
1728
|
const parts = path.split(".");
|
|
1397
1729
|
let cur = obj;
|
|
1398
1730
|
for (const part of parts) {
|
|
1399
|
-
if (
|
|
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
|
+
}
|
|
1400
1753
|
return;
|
|
1754
|
+
}
|
|
1755
|
+
if (!Object.prototype.hasOwnProperty.call(cur, part)) {
|
|
1756
|
+
return;
|
|
1757
|
+
}
|
|
1401
1758
|
cur = cur[part];
|
|
1402
1759
|
}
|
|
1403
1760
|
return cur;
|
|
1404
1761
|
}
|
|
1405
|
-
function
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
const
|
|
1411
|
-
if (
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
}
|
|
1415
|
-
|
|
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
|
|
1416
2073
|
});
|
|
1417
|
-
|
|
1418
|
-
|
|
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);
|
|
1419
2325
|
if (!isTruthy(val))
|
|
1420
2326
|
return "";
|
|
1421
|
-
const attrs = `${before} ${after}`.trim().replace(/\s+/g, " ");
|
|
2327
|
+
const attrs = `${before ?? ""} ${after ?? ""}`.trim().replace(/\s+/g, " ");
|
|
1422
2328
|
return attrs ? `<${tag} ${attrs} />` : `<${tag} />`;
|
|
1423
2329
|
});
|
|
1424
|
-
res = res.replace(/<([a-zA-Z0-9_-]+)
|
|
1425
|
-
const
|
|
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);
|
|
1426
2335
|
if (!isTruthy(val))
|
|
1427
2336
|
return "";
|
|
1428
|
-
const attrs = `${before} ${after}`.trim().replace(/\s+/g, " ");
|
|
2337
|
+
const attrs = `${before ?? ""} ${after ?? ""}`.trim().replace(/\s+/g, " ");
|
|
1429
2338
|
return attrs ? `<${tag} ${attrs}>${content}</${tag}>` : `<${tag}>${content}</${tag}>`;
|
|
1430
2339
|
});
|
|
1431
2340
|
return res;
|
|
@@ -1441,9 +2350,15 @@ function interpolateTemplate(html, context) {
|
|
|
1441
2350
|
return match;
|
|
1442
2351
|
});
|
|
1443
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
|
+
});
|
|
1444
2359
|
|
|
1445
2360
|
// src/template/dsd-renderer.ts
|
|
1446
|
-
import { relative as
|
|
2361
|
+
import { relative as relative4 } from "path";
|
|
1447
2362
|
function hasScriptWithSrc(html, srcPath) {
|
|
1448
2363
|
const cleanSrc = srcPath.replace(/^\/+/, "");
|
|
1449
2364
|
const scriptRegex = /<script\b[^>]*\bsrc=["']([^"']+)["'][^>]*>/gi;
|
|
@@ -1475,7 +2390,7 @@ async function resolveWebComponentsInHtml(options) {
|
|
|
1475
2390
|
if (globalRoot.root) {
|
|
1476
2391
|
if (config.cssStrategy === "inline") {
|
|
1477
2392
|
const globalCss = await cssGraph.flattenCss(globalRoot.root, vfs);
|
|
1478
|
-
globalCssBlock = `<style data-
|
|
2393
|
+
globalCssBlock = `<style data-buntic="global">
|
|
1479
2394
|
${globalCss.trim()}
|
|
1480
2395
|
</style>`;
|
|
1481
2396
|
} else if (globalRoot.relativeRoot) {
|
|
@@ -1504,7 +2419,7 @@ ${globalCss.trim()}
|
|
|
1504
2419
|
continue;
|
|
1505
2420
|
}
|
|
1506
2421
|
vfs.registry.markTagUsed(tag);
|
|
1507
|
-
const rel =
|
|
2422
|
+
const rel = relative4(config.root, scriptPath).replace(/\\/g, "/");
|
|
1508
2423
|
const publicSrc = rel.startsWith("/") ? rel : `/${rel}`;
|
|
1509
2424
|
if (!injectedPaths.has(publicSrc) && !hasScriptWithSrc(result, publicSrc)) {
|
|
1510
2425
|
injectedPaths.add(publicSrc);
|
|
@@ -1548,14 +2463,19 @@ ${siblingCss.trim()}
|
|
|
1548
2463
|
} catch {
|
|
1549
2464
|
rawHtml = await Bun.file(triad.htmlPath).text();
|
|
1550
2465
|
}
|
|
2466
|
+
const originalRawHtml = rawHtml;
|
|
1551
2467
|
rawHtml = await resolveComponentsFn(rawHtml, context, triad.htmlPath);
|
|
1552
|
-
rawHtml = resolveConditionals(rawHtml, context
|
|
2468
|
+
rawHtml = resolveConditionals(rawHtml, context, {
|
|
2469
|
+
filePath: triad.htmlPath,
|
|
2470
|
+
source: originalRawHtml,
|
|
2471
|
+
projectRoot: config.root
|
|
2472
|
+
});
|
|
1553
2473
|
rawHtml = interpolateTemplate(rawHtml, context);
|
|
1554
2474
|
if (rawHtml.includes("<style") && rawHtml.includes("scoped")) {
|
|
1555
2475
|
const extracted = extractScopedStyles(rawHtml, scopeRegistry);
|
|
1556
2476
|
rawHtml = extracted.html;
|
|
1557
2477
|
if (extracted.scopedRules.length > 0) {
|
|
1558
|
-
scopedDsdCssBlock = `<style data-
|
|
2478
|
+
scopedDsdCssBlock = `<style data-buntic="dsd-scoped">
|
|
1559
2479
|
${extracted.scopedRules.join(`
|
|
1560
2480
|
|
|
1561
2481
|
`)}
|
|
@@ -1603,12 +2523,13 @@ ${templateTag}`;
|
|
|
1603
2523
|
return result;
|
|
1604
2524
|
}
|
|
1605
2525
|
var init_dsd_renderer = __esm(() => {
|
|
2526
|
+
init_directives();
|
|
1606
2527
|
init_scoped_css();
|
|
1607
2528
|
init_web_components();
|
|
1608
2529
|
});
|
|
1609
2530
|
|
|
1610
2531
|
// src/template/svg-component.ts
|
|
1611
|
-
import { relative as
|
|
2532
|
+
import { relative as relative5 } from "path";
|
|
1612
2533
|
async function attachSiblingCssIfPresent(options) {
|
|
1613
2534
|
const { templateHtml, templatePath, siblingCssPath, kindLabel, config, vfs, cssGraph } = options;
|
|
1614
2535
|
if (!vfs.hasFile(siblingCssPath)) {
|
|
@@ -1627,8 +2548,8 @@ async function attachSiblingCssIfPresent(options) {
|
|
|
1627
2548
|
if (withScopedCss !== null) {
|
|
1628
2549
|
return withScopedCss;
|
|
1629
2550
|
}
|
|
1630
|
-
const relTarget =
|
|
1631
|
-
const relCss =
|
|
2551
|
+
const relTarget = relative5(config.root, templatePath);
|
|
2552
|
+
const relCss = relative5(config.root, siblingCssPath);
|
|
1632
2553
|
logWarn(`${kindLabel} "${relTarget}" has a sibling CSS file ("${relCss}"), but does not have a single root element. Scoped styles were not applied.`);
|
|
1633
2554
|
return templateHtml;
|
|
1634
2555
|
}
|
|
@@ -1694,7 +2615,7 @@ function isIgnoredPath(filePathOrName) {
|
|
|
1694
2615
|
const normalized = filePathOrName.replace(/\\/g, "/");
|
|
1695
2616
|
const segments = normalized.split("/");
|
|
1696
2617
|
for (const seg of segments) {
|
|
1697
|
-
if (seg === "node_modules" || seg === ".git" || seg === ".agents" || seg === "dist" || seg.startsWith(".
|
|
2618
|
+
if (seg === "node_modules" || seg === ".git" || seg === ".agents" || seg === "dist" || seg.startsWith(".buntic")) {
|
|
1698
2619
|
return true;
|
|
1699
2620
|
}
|
|
1700
2621
|
}
|
|
@@ -1904,7 +2825,7 @@ var init_vfs = __esm(() => {
|
|
|
1904
2825
|
|
|
1905
2826
|
// src/template/engine.ts
|
|
1906
2827
|
import { existsSync as existsSync7 } from "fs";
|
|
1907
|
-
import { extname as extname3, relative as
|
|
2828
|
+
import { extname as extname3, relative as relative6 } from "path";
|
|
1908
2829
|
|
|
1909
2830
|
class TemplateEngine {
|
|
1910
2831
|
config;
|
|
@@ -1954,8 +2875,8 @@ class TemplateEngine {
|
|
|
1954
2875
|
await this.cssGraph.analyze(this.vfs);
|
|
1955
2876
|
const globalRoot = this.cssGraph.getGlobalRoot();
|
|
1956
2877
|
if (globalRoot.conflicts.length > 1) {
|
|
1957
|
-
const relConflicts = globalRoot.conflicts.map((c) =>
|
|
1958
|
-
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.`, "
|
|
2878
|
+
const relConflicts = globalRoot.conflicts.map((c) => relative6(this.config.root, c));
|
|
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");
|
|
1959
2880
|
}
|
|
1960
2881
|
let processedHtml = pageHtml;
|
|
1961
2882
|
if (currentFile && currentFile.endsWith(".html")) {
|
|
@@ -1972,7 +2893,7 @@ class TemplateEngine {
|
|
|
1972
2893
|
let composed = await this.resolveLayout(processedHtml, context, currentFile);
|
|
1973
2894
|
composed = await this.resolveEach(composed, context, currentFile);
|
|
1974
2895
|
composed = await this.resolveComponents(composed, context, currentFile);
|
|
1975
|
-
composed = this.resolveConditionals(composed, context);
|
|
2896
|
+
composed = this.resolveConditionals(composed, context, currentFile, pageHtml);
|
|
1976
2897
|
composed = this.interpolate(composed, context);
|
|
1977
2898
|
composed = await this.resolveWebComponents(composed, context);
|
|
1978
2899
|
composed = await this.resolveCss(composed, currentFile);
|
|
@@ -2014,6 +2935,16 @@ class TemplateEngine {
|
|
|
2014
2935
|
resolveFilePath(rawSrc, currentFile, defaultDir) {
|
|
2015
2936
|
return this.vfs.resolvePath(rawSrc, currentFile, defaultDir);
|
|
2016
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
|
+
}
|
|
2017
2948
|
async resolveLayout(html, context, currentFile) {
|
|
2018
2949
|
const layoutMatch = html.match(/<layout\s+src=["']([^"']+)["'][^>]*>([\s\S]*?)<\/layout>/i);
|
|
2019
2950
|
if (!layoutMatch) {
|
|
@@ -2023,7 +2954,24 @@ class TemplateEngine {
|
|
|
2023
2954
|
const innerContent = layoutMatch[2];
|
|
2024
2955
|
const layoutFilePath = this.resolveFilePath(layoutRawSrc, currentFile, this.config.layoutsDir);
|
|
2025
2956
|
if (!this.vfs.hasFile(layoutFilePath) && !existsSync7(layoutFilePath)) {
|
|
2026
|
-
|
|
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
|
+
});
|
|
2027
2975
|
}
|
|
2028
2976
|
const layoutTemplate = await this.vfs.readText(layoutFilePath);
|
|
2029
2977
|
let resolvedInner = await this.resolveEach(innerContent, context, currentFile);
|
|
@@ -2059,34 +3007,143 @@ class TemplateEngine {
|
|
|
2059
3007
|
}
|
|
2060
3008
|
async resolveEach(html, context, currentFile, depth = 0) {
|
|
2061
3009
|
if (depth > 10) {
|
|
2062
|
-
console.warn("[
|
|
3010
|
+
console.warn("[Buntic] Maximum <each> recursion depth (10) reached.");
|
|
2063
3011
|
return html;
|
|
2064
3012
|
}
|
|
2065
|
-
const
|
|
2066
|
-
let match;
|
|
2067
|
-
const matches = [];
|
|
2068
|
-
while ((match = eachRegex.exec(html)) !== null) {
|
|
2069
|
-
matches.push({ fullMatch: match[0], attrString: match[1], inner: match[2] });
|
|
2070
|
-
}
|
|
3013
|
+
const matches = findTopLevelBlocks(html, ["each"]);
|
|
2071
3014
|
if (matches.length === 0)
|
|
2072
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
|
+
};
|
|
2073
3038
|
let result = html;
|
|
2074
3039
|
for (const item of matches) {
|
|
2075
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
|
+
}
|
|
2076
3053
|
let items;
|
|
3054
|
+
let resolvedFilePath;
|
|
2077
3055
|
if (attrs.src) {
|
|
2078
3056
|
const filePath = this.resolveFilePath(attrs.src, currentFile, this.config.dataDir);
|
|
3057
|
+
resolvedFilePath = filePath;
|
|
2079
3058
|
if (!this.vfs.hasFile(filePath) && !existsSync7(filePath)) {
|
|
2080
|
-
|
|
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
|
+
});
|
|
2081
3105
|
}
|
|
2082
|
-
items = await this.vfs.readJson(filePath);
|
|
2083
3106
|
} else if (attrs.in) {
|
|
2084
3107
|
items = getNestedValue(context, attrs.in);
|
|
2085
3108
|
} else {
|
|
2086
|
-
|
|
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;
|
|
2087
3122
|
}
|
|
2088
3123
|
if (!Array.isArray(items)) {
|
|
2089
|
-
|
|
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;
|
|
2090
3147
|
}
|
|
2091
3148
|
const renderedItems = [];
|
|
2092
3149
|
for (const entry of items) {
|
|
@@ -2103,9 +3160,9 @@ class TemplateEngine {
|
|
|
2103
3160
|
itemContext.item = entry;
|
|
2104
3161
|
itemContext.this = entry;
|
|
2105
3162
|
}
|
|
2106
|
-
let rendered = await this.resolveEach(
|
|
3163
|
+
let rendered = await this.resolveEach(loopTemplate, itemContext, currentFile, depth + 1);
|
|
2107
3164
|
rendered = await this.resolveComponents(rendered, itemContext, currentFile, depth + 1);
|
|
2108
|
-
rendered = this.resolveConditionals(rendered, itemContext);
|
|
3165
|
+
rendered = this.resolveConditionals(rendered, itemContext, currentFile, originalSourceForFile);
|
|
2109
3166
|
rendered = this.interpolate(rendered, itemContext);
|
|
2110
3167
|
renderedItems.push(rendered);
|
|
2111
3168
|
}
|
|
@@ -2116,7 +3173,7 @@ class TemplateEngine {
|
|
|
2116
3173
|
}
|
|
2117
3174
|
async resolveComponents(html, context, currentFile, depth = 0) {
|
|
2118
3175
|
if (depth > 10) {
|
|
2119
|
-
console.warn("[
|
|
3176
|
+
console.warn("[Buntic] Maximum component recursion depth (10) reached. Check for circular component includes.");
|
|
2120
3177
|
return html;
|
|
2121
3178
|
}
|
|
2122
3179
|
const componentRegex = /<component\s+([^>]+?)(?:\s*\/>|>(.*?)<\/component>)/gis;
|
|
@@ -2125,11 +3182,15 @@ class TemplateEngine {
|
|
|
2125
3182
|
while ((match = componentRegex.exec(html)) !== null) {
|
|
2126
3183
|
const props = parseHtmlAttributes(match[1]);
|
|
2127
3184
|
if (props.src) {
|
|
3185
|
+
const fullMatch = match[0];
|
|
3186
|
+
const openTagEnd = fullMatch.indexOf(">");
|
|
2128
3187
|
matches.push({
|
|
2129
|
-
fullMatch
|
|
3188
|
+
fullMatch,
|
|
3189
|
+
openTag: openTagEnd !== -1 ? fullMatch.slice(0, openTagEnd + 1) : fullMatch,
|
|
2130
3190
|
children: match[2] ? match[2].trim() : "",
|
|
2131
3191
|
src: props.src,
|
|
2132
|
-
props
|
|
3192
|
+
props,
|
|
3193
|
+
index: match.index
|
|
2133
3194
|
});
|
|
2134
3195
|
}
|
|
2135
3196
|
}
|
|
@@ -2139,7 +3200,23 @@ class TemplateEngine {
|
|
|
2139
3200
|
for (const item of matches) {
|
|
2140
3201
|
const compPath = this.resolveFilePath(item.src, currentFile, this.config.componentsDir);
|
|
2141
3202
|
if (!this.vfs.hasFile(compPath) && !existsSync7(compPath)) {
|
|
2142
|
-
|
|
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
|
+
});
|
|
2143
3220
|
}
|
|
2144
3221
|
const ext = extname3(compPath).toLowerCase();
|
|
2145
3222
|
if (ext === ".ts" || ext === ".js" || ext === ".tsx" || ext === ".jsx") {
|
|
@@ -2150,7 +3227,11 @@ class TemplateEngine {
|
|
|
2150
3227
|
children: item.children,
|
|
2151
3228
|
context,
|
|
2152
3229
|
currentFile,
|
|
2153
|
-
depth
|
|
3230
|
+
depth,
|
|
3231
|
+
snippet: item.fullMatch,
|
|
3232
|
+
openTag: item.openTag,
|
|
3233
|
+
offset: item.index,
|
|
3234
|
+
sourceHtml: html
|
|
2154
3235
|
});
|
|
2155
3236
|
result = replaceLiteral(result, item.fullMatch, replacement);
|
|
2156
3237
|
continue;
|
|
@@ -2166,9 +3247,9 @@ class TemplateEngine {
|
|
|
2166
3247
|
result = replaceLiteral(result, item.fullMatch, svgContent);
|
|
2167
3248
|
continue;
|
|
2168
3249
|
}
|
|
2169
|
-
|
|
2170
|
-
compTemplate = await attachSiblingCssIfPresent({
|
|
2171
|
-
templateHtml:
|
|
3250
|
+
const rawCompTemplate = await this.vfs.readText(compPath);
|
|
3251
|
+
let compTemplate = await attachSiblingCssIfPresent({
|
|
3252
|
+
templateHtml: rawCompTemplate,
|
|
2172
3253
|
templatePath: compPath,
|
|
2173
3254
|
siblingCssPath: compPath.replace(/\.html$/, ".css"),
|
|
2174
3255
|
kindLabel: "Component",
|
|
@@ -2179,7 +3260,7 @@ class TemplateEngine {
|
|
|
2179
3260
|
const compContext = { ...context, ...item.props };
|
|
2180
3261
|
compTemplate = compTemplate.replace(/<slot\s*>\s*<\/slot>/gi, () => item.children);
|
|
2181
3262
|
compTemplate = compTemplate.replace(/<slot\s*\/>/gi, () => item.children);
|
|
2182
|
-
compTemplate = this.resolveConditionals(compTemplate, compContext);
|
|
3263
|
+
compTemplate = this.resolveConditionals(compTemplate, compContext, compPath, rawCompTemplate);
|
|
2183
3264
|
compTemplate = this.interpolate(compTemplate, compContext);
|
|
2184
3265
|
compTemplate = await this.resolveComponents(compTemplate, compContext, compPath, depth + 1);
|
|
2185
3266
|
result = replaceLiteral(result, item.fullMatch, compTemplate);
|
|
@@ -2187,7 +3268,19 @@ class TemplateEngine {
|
|
|
2187
3268
|
return result;
|
|
2188
3269
|
}
|
|
2189
3270
|
async renderWebComponentAlias(options) {
|
|
2190
|
-
const {
|
|
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;
|
|
2191
3284
|
let tag = this.vfs.registry.getTagsForFile(compPath)[0];
|
|
2192
3285
|
if (!tag) {
|
|
2193
3286
|
let code;
|
|
@@ -2203,20 +3296,38 @@ class TemplateEngine {
|
|
|
2203
3296
|
tag = filenameToTagName(compPath) || undefined;
|
|
2204
3297
|
}
|
|
2205
3298
|
if (!tag) {
|
|
2206
|
-
|
|
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
|
+
});
|
|
2207
3314
|
}
|
|
2208
3315
|
const attrEntries = Object.entries(props).filter(([k]) => k !== "src");
|
|
2209
3316
|
const attrString = attrEntries.length > 0 ? " " + attrEntries.map(([k, v]) => `${k}="${v}"`).join(" ") : "";
|
|
2210
3317
|
let innerChildren = children;
|
|
2211
3318
|
if (innerChildren) {
|
|
2212
3319
|
innerChildren = await this.resolveComponents(innerChildren, context, currentFile, depth + 1);
|
|
2213
|
-
innerChildren = this.resolveConditionals(innerChildren, context);
|
|
3320
|
+
innerChildren = this.resolveConditionals(innerChildren, context, currentFile, sourceHtml);
|
|
2214
3321
|
innerChildren = this.interpolate(innerChildren, context);
|
|
2215
3322
|
}
|
|
2216
3323
|
return innerChildren ? `<${tag}${attrString}>${innerChildren}</${tag}>` : `<${tag}${attrString}></${tag}>`;
|
|
2217
3324
|
}
|
|
2218
|
-
resolveConditionals(html, context) {
|
|
2219
|
-
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
|
+
});
|
|
2220
3331
|
}
|
|
2221
3332
|
interpolate(html, context) {
|
|
2222
3333
|
return interpolateTemplate(html, context);
|
|
@@ -2226,7 +3337,9 @@ var init_engine = __esm(() => {
|
|
|
2226
3337
|
init_css_graph();
|
|
2227
3338
|
init_css_resolver();
|
|
2228
3339
|
init_data_loader();
|
|
3340
|
+
init_directives();
|
|
2229
3341
|
init_dsd_renderer();
|
|
3342
|
+
init_errors();
|
|
2230
3343
|
init_scoped_css();
|
|
2231
3344
|
init_svg_component();
|
|
2232
3345
|
init_vfs();
|
|
@@ -2235,13 +3348,13 @@ var init_engine = __esm(() => {
|
|
|
2235
3348
|
|
|
2236
3349
|
// src/utils/paths.ts
|
|
2237
3350
|
import { existsSync as existsSync8, readdirSync as readdirSync4, statSync as statSync3 } from "fs";
|
|
2238
|
-
import { dirname as dirname7, join as join9, relative as
|
|
3351
|
+
import { dirname as dirname7, join as join9, relative as relative7, resolve as resolve6, sep } from "path";
|
|
2239
3352
|
function isPathInside(baseDir, targetPath) {
|
|
2240
3353
|
const absBase = resolve6(baseDir);
|
|
2241
3354
|
const absTarget = resolve6(targetPath);
|
|
2242
3355
|
if (absTarget === absBase)
|
|
2243
3356
|
return true;
|
|
2244
|
-
const rel =
|
|
3357
|
+
const rel = relative7(absBase, absTarget);
|
|
2245
3358
|
return rel !== "" && !rel.startsWith("..") && !rel.startsWith(sep) && !/^[a-zA-Z]:/.test(rel);
|
|
2246
3359
|
}
|
|
2247
3360
|
function resolveLocalAssetPath(config, src, fromFile) {
|
|
@@ -2283,7 +3396,7 @@ function walkFiles(dir, options = {}) {
|
|
|
2283
3396
|
} else if (stat.isFile()) {
|
|
2284
3397
|
if (options.filter && !options.filter(full, entry))
|
|
2285
3398
|
continue;
|
|
2286
|
-
results.push(relativeToBase ?
|
|
3399
|
+
results.push(relativeToBase ? relative7(baseDir, full).replace(/\\/g, "/") : full);
|
|
2287
3400
|
}
|
|
2288
3401
|
}
|
|
2289
3402
|
return results;
|
|
@@ -2291,7 +3404,7 @@ function walkFiles(dir, options = {}) {
|
|
|
2291
3404
|
var init_paths = () => {};
|
|
2292
3405
|
|
|
2293
3406
|
// src/router/routes.ts
|
|
2294
|
-
import { join as join10, relative as
|
|
3407
|
+
import { join as join10, relative as relative8, sep as sep2 } from "path";
|
|
2295
3408
|
import { existsSync as existsSync9 } from "fs";
|
|
2296
3409
|
function extractRouteTokens(routePattern) {
|
|
2297
3410
|
const matches = routePattern.match(/\[([a-zA-Z0-9_-]+)\]/g);
|
|
@@ -2384,15 +3497,15 @@ function validateRouteParams(requiredTokens, params, loaderPath) {
|
|
|
2384
3497
|
for (const token of requiredTokens) {
|
|
2385
3498
|
const rawVal = params[token];
|
|
2386
3499
|
if (rawVal === undefined || rawVal === null) {
|
|
2387
|
-
throw new Error(`[
|
|
3500
|
+
throw new Error(`[Buntic Error]: Missing required route parameter "${token}" in loader "${loaderPath}".
|
|
2388
3501
|
Provided parameters: ${JSON.stringify(params)}`);
|
|
2389
3502
|
}
|
|
2390
3503
|
const strVal = String(rawVal).trim();
|
|
2391
3504
|
if (strVal === "") {
|
|
2392
|
-
throw new Error(`[
|
|
3505
|
+
throw new Error(`[Buntic Error]: Route parameter "${token}" in loader "${loaderPath}" cannot be an empty string.`);
|
|
2393
3506
|
}
|
|
2394
3507
|
if (/[\/\\?#\0]/.test(strVal)) {
|
|
2395
|
-
throw new Error(`[
|
|
3508
|
+
throw new Error(`[Buntic Error]: Route parameter "${token}" with value "${strVal}" in "${loaderPath}" contains invalid characters (/ \\ ? #).`);
|
|
2396
3509
|
}
|
|
2397
3510
|
cleanParams[token] = strVal;
|
|
2398
3511
|
}
|
|
@@ -2439,7 +3552,7 @@ function buildCleanUrl(patternRelPath, params) {
|
|
|
2439
3552
|
}
|
|
2440
3553
|
function registerRouteOrThrow(urlRegistry, urlPath, sourceDesc) {
|
|
2441
3554
|
if (urlRegistry.has(urlPath)) {
|
|
2442
|
-
throw new Error(`[
|
|
3555
|
+
throw new Error(`[Buntic Collision Error]: Duplicate route generated for "${urlPath}".
|
|
2443
3556
|
- First generated by: ${urlRegistry.get(urlPath)}
|
|
2444
3557
|
- Conflicting with: ${sourceDesc}`);
|
|
2445
3558
|
}
|
|
@@ -2452,7 +3565,7 @@ async function resolveStaticRoute(options) {
|
|
|
2452
3565
|
try {
|
|
2453
3566
|
loaderResult = await executeStaticLoader(loaderPath, globalData, { cacheBust });
|
|
2454
3567
|
} catch (err) {
|
|
2455
|
-
logError(`Error executing loader "${
|
|
3568
|
+
logError(`Error executing loader "${relative8(config.root, loaderPath)}"`, err);
|
|
2456
3569
|
throw err;
|
|
2457
3570
|
}
|
|
2458
3571
|
}
|
|
@@ -2483,10 +3596,10 @@ async function resolveDynamicRoutes(options) {
|
|
|
2483
3596
|
} = options;
|
|
2484
3597
|
if (!loaderPath) {
|
|
2485
3598
|
const expected = relPattern.replace(/\.html$/, ".data.ts");
|
|
2486
|
-
throw new Error(`[
|
|
3599
|
+
throw new Error(`[Buntic Error]: Dynamic page "${relPattern}" contains parameter(s) [${tokens.join(", ")}], but no co-located loader was found.
|
|
2487
3600
|
` + `\uD83D\uDC49 Create "${expected}" exporting a default async function or getStaticPaths().`);
|
|
2488
3601
|
}
|
|
2489
|
-
const relLoader =
|
|
3602
|
+
const relLoader = relative8(config.root, loaderPath);
|
|
2490
3603
|
let mod;
|
|
2491
3604
|
try {
|
|
2492
3605
|
const importPath = cacheBust ? `${loaderPath}?t=${Date.now()}` : loaderPath;
|
|
@@ -2497,7 +3610,7 @@ async function resolveDynamicRoutes(options) {
|
|
|
2497
3610
|
}
|
|
2498
3611
|
const handler = mod.default ?? mod.getStaticPaths;
|
|
2499
3612
|
if (typeof handler !== "function") {
|
|
2500
|
-
throw new Error(`[
|
|
3613
|
+
throw new Error(`[Buntic Error]: Loader "${relLoader}" must export a default function ("export default async function") or "getStaticPaths".`);
|
|
2501
3614
|
}
|
|
2502
3615
|
const basePattern = relPattern.split(sep2).join("/").replace(/\.html$/, "");
|
|
2503
3616
|
const lastSlash = basePattern.lastIndexOf("/");
|
|
@@ -2514,7 +3627,7 @@ async function resolveDynamicRoutes(options) {
|
|
|
2514
3627
|
throw err;
|
|
2515
3628
|
}
|
|
2516
3629
|
if (!Array.isArray(pathsResult)) {
|
|
2517
|
-
throw new Error(`[
|
|
3630
|
+
throw new Error(`[Buntic Error]: Dynamic loader "${relLoader}" must return an Array of path objects ({ params, props }). Received: ${typeof pathsResult}.`);
|
|
2518
3631
|
}
|
|
2519
3632
|
if (pathsResult.length === 0) {
|
|
2520
3633
|
logWarn(`Dynamic loader "${relLoader}" returned 0 paths. No pages generated for "${relPattern}".`);
|
|
@@ -2524,7 +3637,7 @@ async function resolveDynamicRoutes(options) {
|
|
|
2524
3637
|
for (let i = 0;i < pathsResult.length; i++) {
|
|
2525
3638
|
const item = pathsResult[i];
|
|
2526
3639
|
if (!item || typeof item !== "object" || !item.params || typeof item.params !== "object") {
|
|
2527
|
-
throw new Error(`[
|
|
3640
|
+
throw new Error(`[Buntic Error]: Item at index ${i} in loader "${relLoader}" must be an object with a "params" property.
|
|
2528
3641
|
Received: ${JSON.stringify(item)}`);
|
|
2529
3642
|
}
|
|
2530
3643
|
const cleanParams = validateRouteParams(tokens, item.params, relLoader);
|
|
@@ -2553,7 +3666,7 @@ async function resolveAllRoutes(config, globalData, options) {
|
|
|
2553
3666
|
const routes = [];
|
|
2554
3667
|
const urlRegistry = new Map;
|
|
2555
3668
|
for (const templatePath of htmlFiles) {
|
|
2556
|
-
const relPattern =
|
|
3669
|
+
const relPattern = relative8(config.pagesDir, templatePath);
|
|
2557
3670
|
const isDynamic = isDynamicPattern(relPattern);
|
|
2558
3671
|
const tokens = extractRouteTokens(relPattern);
|
|
2559
3672
|
const loaderPath = findCoLocatedLoader(templatePath);
|
|
@@ -2850,15 +3963,15 @@ class StorageManager {
|
|
|
2850
3963
|
const available = this.getAvailableStorages();
|
|
2851
3964
|
if (!targetStorage) {
|
|
2852
3965
|
if (available.length === 0) {
|
|
2853
|
-
throw new Error(`[
|
|
3966
|
+
throw new Error(`[Buntic Error] No storage loaders found in "${this.config.storageDir}".
|
|
2854
3967
|
` + `\uD83D\uDC49 Create a storage loader (e.g. "${join12(this.config.storageDir, "s3.ts")}") to handle key "${key}".`);
|
|
2855
3968
|
}
|
|
2856
|
-
throw new Error(`[
|
|
2857
|
-
` + `\uD83D\uDC49 Specify storage="..." in your tag or set "defaultStorage" in
|
|
3969
|
+
throw new Error(`[Buntic Error] Multiple storage loaders detected ([${available.join(", ")}]), but no storage name was specified for key "${key}".
|
|
3970
|
+
` + `\uD83D\uDC49 Specify storage="..." in your tag or set "defaultStorage" in buntic.config.ts.`);
|
|
2858
3971
|
}
|
|
2859
3972
|
const storage = this.storages.get(targetStorage);
|
|
2860
3973
|
if (!storage) {
|
|
2861
|
-
throw new Error(`[
|
|
3974
|
+
throw new Error(`[Buntic Error] Storage loader "${targetStorage}" not found in "${this.config.storageDir}".
|
|
2862
3975
|
Available storages: [${available.join(", ")}]`);
|
|
2863
3976
|
}
|
|
2864
3977
|
try {
|
|
@@ -2872,7 +3985,7 @@ class StorageManager {
|
|
|
2872
3985
|
}
|
|
2873
3986
|
async function normalizeStorageResult(result, key, storageName) {
|
|
2874
3987
|
if (!result) {
|
|
2875
|
-
throw new Error(`[
|
|
3988
|
+
throw new Error(`[Buntic Error] Storage loader "${storageName}" returned null/undefined for key "${key}".`);
|
|
2876
3989
|
}
|
|
2877
3990
|
if (result instanceof Response) {
|
|
2878
3991
|
const arrayBuf = await result.arrayBuffer();
|
|
@@ -2926,7 +4039,7 @@ async function normalizeStorageResult(result, key, storageName) {
|
|
|
2926
4039
|
bytes: new Uint8Array(result)
|
|
2927
4040
|
};
|
|
2928
4041
|
}
|
|
2929
|
-
throw new Error(`[
|
|
4042
|
+
throw new Error(`[Buntic Error] Unsupported return type from storage loader "${storageName}" for key "${key}".
|
|
2930
4043
|
Expected Uint8Array, ArrayBuffer, Response, BunFile or { bytes, etag?, contentType? }. Received: ${typeof result}`);
|
|
2931
4044
|
}
|
|
2932
4045
|
var init_loader = () => {};
|
|
@@ -2964,7 +4077,7 @@ class PhotoProcessor {
|
|
|
2964
4077
|
const key = attrs.key;
|
|
2965
4078
|
const storage = attrs.storage;
|
|
2966
4079
|
if (!src && !key) {
|
|
2967
|
-
throw new Error(`[
|
|
4080
|
+
throw new Error(`[Buntic Error] <photo> tag must have a "src" (for local files) or a "key" (for remote storage) in "${templatePath}".
|
|
2968
4081
|
` + ` Found: ${match.fullMatch}`);
|
|
2969
4082
|
}
|
|
2970
4083
|
const widths = attrs.widths ? attrs.widths.split(",").map((w) => parseInt(w.trim(), 10)).filter((w) => !isNaN(w) && w > 0) : undefined;
|
|
@@ -3004,7 +4117,7 @@ class PhotoProcessor {
|
|
|
3004
4117
|
}
|
|
3005
4118
|
const localPath = resolveLocalAssetPath(this.config, src, templatePath);
|
|
3006
4119
|
if (!existsSync12(localPath)) {
|
|
3007
|
-
throw new Error(`[
|
|
4120
|
+
throw new Error(`[Buntic Error] Local image file "${src}" referenced in <photo> not found.
|
|
3008
4121
|
` + ` Looked in: "${localPath}"
|
|
3009
4122
|
` + ` Referenced in: "${templatePath}"`);
|
|
3010
4123
|
}
|
|
@@ -3128,7 +4241,7 @@ class SeoMetadataEngine {
|
|
|
3128
4241
|
imgHeight = processed.height;
|
|
3129
4242
|
}
|
|
3130
4243
|
} catch (err) {
|
|
3131
|
-
logWarn(`Failed to process social image in "${templatePath}": ${getErrorMessage(err)}`, "
|
|
4244
|
+
logWarn(`Failed to process social image in "${templatePath}": ${getErrorMessage(err)}`, "Buntic SEO Warning");
|
|
3132
4245
|
}
|
|
3133
4246
|
}
|
|
3134
4247
|
const metaTags = this.generateMetaTagsHtml({
|
|
@@ -3426,7 +4539,7 @@ var init_feeds = () => {};
|
|
|
3426
4539
|
|
|
3427
4540
|
// src/builder/collisions.ts
|
|
3428
4541
|
import { existsSync as existsSync17 } from "fs";
|
|
3429
|
-
import { join as join17, relative as
|
|
4542
|
+
import { join as join17, relative as relative9 } from "path";
|
|
3430
4543
|
function getDirectoryFiles(dir, baseDir = dir) {
|
|
3431
4544
|
return walkFiles(dir, {
|
|
3432
4545
|
baseDir,
|
|
@@ -3441,7 +4554,7 @@ function detectPublicCollisions(config, routes) {
|
|
|
3441
4554
|
const collisions = [];
|
|
3442
4555
|
const routeOutputMap = new Map;
|
|
3443
4556
|
for (const route of routes) {
|
|
3444
|
-
const relOut =
|
|
4557
|
+
const relOut = relative9(config.outDir, route.outputFilePath).replace(/\\/g, "/");
|
|
3445
4558
|
routeOutputMap.set(relOut, route);
|
|
3446
4559
|
}
|
|
3447
4560
|
for (const relFile of publicFiles) {
|
|
@@ -3449,23 +4562,23 @@ function detectPublicCollisions(config, routes) {
|
|
|
3449
4562
|
const route = routeOutputMap.get(relFile);
|
|
3450
4563
|
collisions.push({
|
|
3451
4564
|
type: "route",
|
|
3452
|
-
publicPath:
|
|
3453
|
-
conflictWith:
|
|
4565
|
+
publicPath: relative9(config.root, join17(config.publicDir, relFile)),
|
|
4566
|
+
conflictWith: relative9(config.root, route.templateFilePath),
|
|
3454
4567
|
outputPath: relFile
|
|
3455
4568
|
});
|
|
3456
4569
|
}
|
|
3457
4570
|
if (relFile.startsWith("assets/images/") || relFile === "assets/images") {
|
|
3458
4571
|
collisions.push({
|
|
3459
4572
|
type: "reserved-dir",
|
|
3460
|
-
publicPath:
|
|
3461
|
-
conflictWith: "assets/images/ (Reserved for
|
|
4573
|
+
publicPath: relative9(config.root, join17(config.publicDir, relFile)),
|
|
4574
|
+
conflictWith: "assets/images/ (Reserved for Buntic <photo> image optimization)",
|
|
3462
4575
|
outputPath: relFile
|
|
3463
4576
|
});
|
|
3464
4577
|
} else if (relFile.startsWith("assets/seo/") || relFile === "assets/seo") {
|
|
3465
4578
|
collisions.push({
|
|
3466
4579
|
type: "reserved-dir",
|
|
3467
|
-
publicPath:
|
|
3468
|
-
conflictWith: "assets/seo/ (Reserved for
|
|
4580
|
+
publicPath: relative9(config.root, join17(config.publicDir, relFile)),
|
|
4581
|
+
conflictWith: "assets/seo/ (Reserved for Buntic <seo> social cards)",
|
|
3469
4582
|
outputPath: relFile
|
|
3470
4583
|
});
|
|
3471
4584
|
}
|
|
@@ -3483,7 +4596,7 @@ function assertNoPublicCollisions(config, routes) {
|
|
|
3483
4596
|
return ` - Public file "${c.publicPath}" conflicts with reserved internal path "${c.conflictWith}".`;
|
|
3484
4597
|
}).join(`
|
|
3485
4598
|
`);
|
|
3486
|
-
throw new Error(`[
|
|
4599
|
+
throw new Error(`[Buntic Collision Error]: Conflict detected between public/ files and build output:
|
|
3487
4600
|
` + details + `
|
|
3488
4601
|
|
|
3489
4602
|
\uD83D\uDC49 Action: Remove or rename conflicting files in "public/" or adjust page routes in "pages/".`);
|
|
@@ -3494,7 +4607,7 @@ var init_collisions = __esm(() => {
|
|
|
3494
4607
|
|
|
3495
4608
|
// src/builder/builder.ts
|
|
3496
4609
|
import { cpSync as cpSync2, existsSync as existsSync18, mkdirSync as mkdirSync3, rmSync as rmSync3 } from "fs";
|
|
3497
|
-
import { dirname as dirname9, join as join18, relative as
|
|
4610
|
+
import { dirname as dirname9, join as join18, relative as relative10 } from "path";
|
|
3498
4611
|
|
|
3499
4612
|
class Builder {
|
|
3500
4613
|
config;
|
|
@@ -3515,17 +4628,17 @@ class Builder {
|
|
|
3515
4628
|
this.engine.assertNoWebComponentConflicts();
|
|
3516
4629
|
this.engine.clearUsedWebComponents();
|
|
3517
4630
|
if (!existsSync18(this.config.pagesDir)) {
|
|
3518
|
-
throw new Error(`[
|
|
4631
|
+
throw new Error(`[Buntic] Pages directory not found at: ${this.config.pagesDir}`);
|
|
3519
4632
|
}
|
|
3520
4633
|
const globalData = await this.engine.loadData();
|
|
3521
4634
|
const routes = await resolveAllRoutes(this.config, globalData);
|
|
3522
4635
|
if (routes.length === 0) {
|
|
3523
|
-
console.warn(`[
|
|
4636
|
+
console.warn(`[Buntic] No HTML pages found in: ${this.config.pagesDir}`);
|
|
3524
4637
|
return { success: true, pagesCount: 0, outputFiles: [], durationMs: 0 };
|
|
3525
4638
|
}
|
|
3526
4639
|
assertNoPublicCollisions(this.config, routes);
|
|
3527
4640
|
this.prepareEmptyDir(this.config.outDir);
|
|
3528
|
-
const stagingDir = join18(this.config.root, ".
|
|
4641
|
+
const stagingDir = join18(this.config.root, ".buntic-staging");
|
|
3529
4642
|
this.prepareEmptyDir(stagingDir);
|
|
3530
4643
|
try {
|
|
3531
4644
|
const stagedEntrypoints = await this.stagePages(routes, stagingDir);
|
|
@@ -3572,7 +4685,7 @@ class Builder {
|
|
|
3572
4685
|
}
|
|
3573
4686
|
}
|
|
3574
4687
|
}
|
|
3575
|
-
const relStagedPath =
|
|
4688
|
+
const relStagedPath = relative10(this.config.outDir, route.outputFilePath);
|
|
3576
4689
|
const stagedPath = join18(stagingDir, relStagedPath);
|
|
3577
4690
|
mkdirSync3(dirname9(stagedPath), { recursive: true });
|
|
3578
4691
|
rendered = this.normalizeRootPaths(rendered, stagedPath, stagingDir);
|
|
@@ -3598,7 +4711,7 @@ class Builder {
|
|
|
3598
4711
|
for (const log of buildResult.logs) {
|
|
3599
4712
|
console.error(log);
|
|
3600
4713
|
}
|
|
3601
|
-
throw new Error("[
|
|
4714
|
+
throw new Error("[Buntic] Bun.build bundling failed.");
|
|
3602
4715
|
}
|
|
3603
4716
|
return buildResult.outputs.map((o) => o.path);
|
|
3604
4717
|
}
|
|
@@ -3650,25 +4763,25 @@ class Builder {
|
|
|
3650
4763
|
warnUnusedWebComponents() {
|
|
3651
4764
|
const unused = this.engine.getUnusedWebComponents();
|
|
3652
4765
|
for (const item of unused) {
|
|
3653
|
-
logWarn(`Web Component "<${item.tag}>" (${
|
|
4766
|
+
logWarn(`Web Component "<${item.tag}>" (${relative10(this.config.root, item.file)}) is registered but not used in any page.`);
|
|
3654
4767
|
}
|
|
3655
4768
|
}
|
|
3656
4769
|
normalizeRootPaths(html, stagedFilePath, stagingDir) {
|
|
3657
4770
|
const fromDir = dirname9(stagedFilePath);
|
|
3658
4771
|
return html.replace(/(href|src)=["']\/([^"']+)["']/gi, (match, attr, path) => {
|
|
3659
|
-
if (path.startsWith("/") || path.startsWith("http:") || path.startsWith("https:") || path.startsWith("
|
|
4772
|
+
if (path.startsWith("/") || path.startsWith("http:") || path.startsWith("https:") || path.startsWith("_buntic") || path.startsWith("assets/images/") || path.startsWith("assets/seo/")) {
|
|
3660
4773
|
return match;
|
|
3661
4774
|
}
|
|
3662
4775
|
const targetInRoot = join18(this.config.root, path);
|
|
3663
4776
|
if (existsSync18(targetInRoot)) {
|
|
3664
|
-
let rel =
|
|
4777
|
+
let rel = relative10(fromDir, targetInRoot);
|
|
3665
4778
|
if (!rel.startsWith("."))
|
|
3666
4779
|
rel = "./" + rel;
|
|
3667
4780
|
return `${attr}="${rel}"`;
|
|
3668
4781
|
}
|
|
3669
4782
|
const targetInSrc = join18(this.config.root, "src", path);
|
|
3670
4783
|
if (existsSync18(targetInSrc)) {
|
|
3671
|
-
let rel =
|
|
4784
|
+
let rel = relative10(fromDir, targetInSrc);
|
|
3672
4785
|
if (!rel.startsWith("."))
|
|
3673
4786
|
rel = "./" + rel;
|
|
3674
4787
|
return `${attr}="${rel}"`;
|
|
@@ -3676,7 +4789,7 @@ class Builder {
|
|
|
3676
4789
|
if (stagingDir) {
|
|
3677
4790
|
const targetInStaging = join18(stagingDir, path);
|
|
3678
4791
|
if (existsSync18(targetInStaging)) {
|
|
3679
|
-
let rel =
|
|
4792
|
+
let rel = relative10(fromDir, targetInStaging);
|
|
3680
4793
|
if (!rel.startsWith("."))
|
|
3681
4794
|
rel = "./" + rel;
|
|
3682
4795
|
return `${attr}="${rel}"`;
|
|
@@ -3818,10 +4931,82 @@ function getMimeType(path) {
|
|
|
3818
4931
|
return "text/plain; charset=utf-8";
|
|
3819
4932
|
return "application/octet-stream";
|
|
3820
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
|
+
}
|
|
3821
4948
|
function renderErrorResponse(title, err) {
|
|
3822
4949
|
const safeTitle = escapeHtml(title);
|
|
3823
4950
|
const safeMsg = escapeHtml(getErrorMessage(err));
|
|
3824
|
-
|
|
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, {
|
|
3825
5010
|
status: 500,
|
|
3826
5011
|
headers: { "Content-Type": "text/html; charset=utf-8" }
|
|
3827
5012
|
});
|
|
@@ -3838,7 +5023,7 @@ function renderNotFoundResponse(pathname, routes) {
|
|
|
3838
5023
|
<!doctype html>
|
|
3839
5024
|
<html>
|
|
3840
5025
|
<head>
|
|
3841
|
-
<title>404 - Not Found |
|
|
5026
|
+
<title>404 - Not Found | Buntic Dev</title>
|
|
3842
5027
|
<style>
|
|
3843
5028
|
body { font-family: system-ui, -apple-system, sans-serif; background: #0f172a; color: #f8fafc; padding: 3rem; }
|
|
3844
5029
|
.card { max-width: 650px; margin: 0 auto; background: #1e293b; padding: 2rem; border-radius: 12px; border: 1px solid #334155; }
|
|
@@ -3864,13 +5049,13 @@ function renderNotFoundResponse(pathname, routes) {
|
|
|
3864
5049
|
});
|
|
3865
5050
|
}
|
|
3866
5051
|
var LIVE_RELOAD_SCRIPT = `
|
|
3867
|
-
<script id="
|
|
5052
|
+
<script id="__buntic_live_reload">
|
|
3868
5053
|
(() => {
|
|
3869
5054
|
const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
|
|
3870
|
-
const ws = new WebSocket(\`\${protocol}//\${location.host}/
|
|
5055
|
+
const ws = new WebSocket(\`\${protocol}//\${location.host}/_buntic/ws\`);
|
|
3871
5056
|
ws.onmessage = (event) => {
|
|
3872
5057
|
if (event.data === 'reload') {
|
|
3873
|
-
console.log('[
|
|
5058
|
+
console.log('[buntic] Change detected. Reloading...');
|
|
3874
5059
|
location.reload();
|
|
3875
5060
|
}
|
|
3876
5061
|
};
|
|
@@ -3885,6 +5070,7 @@ var init_dev_helpers = __esm(() => {
|
|
|
3885
5070
|
init_feeds();
|
|
3886
5071
|
init_robots();
|
|
3887
5072
|
init_sitemap();
|
|
5073
|
+
init_errors();
|
|
3888
5074
|
init_paths();
|
|
3889
5075
|
});
|
|
3890
5076
|
|
|
@@ -3903,9 +5089,9 @@ function startDevServer(config) {
|
|
|
3903
5089
|
const collisions = detectPublicCollisions(config, routes);
|
|
3904
5090
|
for (const c of collisions) {
|
|
3905
5091
|
if (c.type === "route") {
|
|
3906
|
-
logWarn(`Public file "${c.publicPath}" conflicts with page template "${c.conflictWith}" (both resolve to "${c.outputPath}").`, "
|
|
5092
|
+
logWarn(`Public file "${c.publicPath}" conflicts with page template "${c.conflictWith}" (both resolve to "${c.outputPath}").`, "Buntic Collision Warning");
|
|
3907
5093
|
} else {
|
|
3908
|
-
logWarn(`Public file "${c.publicPath}" conflicts with reserved internal path "${c.conflictWith}".`, "
|
|
5094
|
+
logWarn(`Public file "${c.publicPath}" conflicts with reserved internal path "${c.conflictWith}".`, "Buntic Collision Warning");
|
|
3909
5095
|
}
|
|
3910
5096
|
}
|
|
3911
5097
|
} catch {}
|
|
@@ -3952,7 +5138,7 @@ function startDevServer(config) {
|
|
|
3952
5138
|
} catch {
|
|
3953
5139
|
return new Response("Bad Request", { status: 400 });
|
|
3954
5140
|
}
|
|
3955
|
-
if (pathname === "/
|
|
5141
|
+
if (pathname === "/_buntic/ws") {
|
|
3956
5142
|
if (srv.upgrade(req))
|
|
3957
5143
|
return;
|
|
3958
5144
|
return new Response("WebSocket upgrade failed", { status: 400 });
|
|
@@ -3998,7 +5184,7 @@ function startDevServer(config) {
|
|
|
3998
5184
|
seoEngine
|
|
3999
5185
|
});
|
|
4000
5186
|
} catch (err) {
|
|
4001
|
-
return renderErrorResponse("[
|
|
5187
|
+
return renderErrorResponse("[Buntic Template Error]", err);
|
|
4002
5188
|
}
|
|
4003
5189
|
}
|
|
4004
5190
|
try {
|
|
@@ -4019,7 +5205,7 @@ function startDevServer(config) {
|
|
|
4019
5205
|
});
|
|
4020
5206
|
}
|
|
4021
5207
|
} catch (err) {
|
|
4022
|
-
return renderErrorResponse("[
|
|
5208
|
+
return renderErrorResponse("[Buntic Dynamic Route Error]", err);
|
|
4023
5209
|
}
|
|
4024
5210
|
if (engine.generatedPageStyles.has(pathname)) {
|
|
4025
5211
|
const css = engine.generatedPageStyles.get(pathname);
|
|
@@ -4070,6 +5256,7 @@ var init_dev = __esm(() => {
|
|
|
4070
5256
|
// src/index.ts
|
|
4071
5257
|
init_config();
|
|
4072
5258
|
init_engine();
|
|
5259
|
+
init_errors();
|
|
4073
5260
|
init_env();
|
|
4074
5261
|
init_routes();
|
|
4075
5262
|
init_cache();
|
|
@@ -4669,7 +5856,7 @@ class OrasClient {
|
|
|
4669
5856
|
const title = layer.annotations?.[ANNOTATIONS.TITLE] || layer.digest.replace("sha256:", "");
|
|
4670
5857
|
const outPath = join13(options.outdir, title);
|
|
4671
5858
|
if (!isPathInside(options.outdir, outPath) || outPath === join13(options.outdir)) {
|
|
4672
|
-
throw new Error(`[
|
|
5859
|
+
throw new Error(`[Buntic Security Error] Unsafe OCI layer title "${title}" escapes output directory "${options.outdir}".`);
|
|
4673
5860
|
}
|
|
4674
5861
|
const res = await this.getBlobStream(ref, layer.digest);
|
|
4675
5862
|
if (!res.body) {
|
|
@@ -4742,7 +5929,7 @@ function createOrasStorage(options) {
|
|
|
4742
5929
|
ref.tag = defaultTag;
|
|
4743
5930
|
}
|
|
4744
5931
|
if (ref.repository !== ref.repository.toLowerCase()) {
|
|
4745
|
-
console.warn(`\x1B[33m\u26A0 [
|
|
5932
|
+
console.warn(`\x1B[33m\u26A0 [Buntic ORAS Warning]\x1B[0m OCI repository names must be lowercase. Converting "${ref.repository}" to "${ref.repository.toLowerCase()}".`);
|
|
4746
5933
|
ref.repository = ref.repository.toLowerCase();
|
|
4747
5934
|
}
|
|
4748
5935
|
const artifact = await client.getArtifactStream(ref, ref.subpath);
|
|
@@ -4789,7 +5976,7 @@ function copyTemplateDirectory(srcDir, destDir) {
|
|
|
4789
5976
|
function initProject(options = {}) {
|
|
4790
5977
|
const templateName = options.template || "blank";
|
|
4791
5978
|
if (!AVAILABLE_TEMPLATES.includes(templateName)) {
|
|
4792
|
-
throw new Error(`[
|
|
5979
|
+
throw new Error(`[Buntic] Unknown template "${options.template}". Available templates: ${AVAILABLE_TEMPLATES.join(", ")}.`);
|
|
4793
5980
|
}
|
|
4794
5981
|
const targetDir = resolve8(process.cwd(), options.targetDir || ".");
|
|
4795
5982
|
const includeSkills = options.includeSkills ?? true;
|
|
@@ -4797,22 +5984,22 @@ function initProject(options = {}) {
|
|
|
4797
5984
|
const pkgRoot = getPackageRoot();
|
|
4798
5985
|
const templateDir = join21(pkgRoot, "templates", templateName);
|
|
4799
5986
|
if (!existsSync21(templateDir)) {
|
|
4800
|
-
throw new Error(`[
|
|
5987
|
+
throw new Error(`[Buntic] Template directory not found: "${templateDir}"`);
|
|
4801
5988
|
}
|
|
4802
5989
|
if (existsSync21(targetDir) && !force) {
|
|
4803
5990
|
const existingEntries = readdirSync6(targetDir).filter((name) => name !== ".git" && name !== ".DS_Store");
|
|
4804
5991
|
if (existingEntries.length > 0) {
|
|
4805
|
-
throw new Error(`[
|
|
4806
|
-
` + ` Pass a new directory name (e.g. "
|
|
5992
|
+
throw new Error(`[Buntic] Target directory "${targetDir}" is not empty.
|
|
5993
|
+
` + ` Pass a new directory name (e.g. "buntic init my-site") or use --force to initialize anyway.`);
|
|
4807
5994
|
}
|
|
4808
5995
|
}
|
|
4809
5996
|
mkdirSync4(targetDir, { recursive: true });
|
|
4810
5997
|
let filesCopied = copyTemplateDirectory(templateDir, targetDir);
|
|
4811
5998
|
let skillsDir = null;
|
|
4812
5999
|
if (includeSkills) {
|
|
4813
|
-
const srcSkillsDir = join21(pkgRoot, "templates", "skills", "
|
|
6000
|
+
const srcSkillsDir = join21(pkgRoot, "templates", "skills", "buntic");
|
|
4814
6001
|
if (existsSync21(srcSkillsDir)) {
|
|
4815
|
-
skillsDir = join21(targetDir, ".agents", "skills", "
|
|
6002
|
+
skillsDir = join21(targetDir, ".agents", "skills", "buntic");
|
|
4816
6003
|
filesCopied += copyTemplateDirectory(srcSkillsDir, skillsDir);
|
|
4817
6004
|
}
|
|
4818
6005
|
}
|
|
@@ -4834,14 +6021,14 @@ init_builder();
|
|
|
4834
6021
|
init_dev();
|
|
4835
6022
|
init_cache();
|
|
4836
6023
|
import { existsSync as existsSync22, rmSync as rmSync4 } from "fs";
|
|
4837
|
-
import { relative as
|
|
6024
|
+
import { relative as relative11 } from "path";
|
|
4838
6025
|
init_runtime();
|
|
4839
6026
|
async function runCLI(args) {
|
|
4840
|
-
|
|
6027
|
+
registerBunticModuleResolver();
|
|
4841
6028
|
const command = args[0] || "help";
|
|
4842
6029
|
if (command === "--version" || command === "-v") {
|
|
4843
6030
|
const pkg = await Bun.file(`${getPackageRoot()}/package.json`).json();
|
|
4844
|
-
console.log(`
|
|
6031
|
+
console.log(`buntic v${pkg.version}`);
|
|
4845
6032
|
return;
|
|
4846
6033
|
}
|
|
4847
6034
|
if (command === "help" || command === "--help" || command === "-h") {
|
|
@@ -4897,27 +6084,27 @@ async function runCLI(args) {
|
|
|
4897
6084
|
includeSkills,
|
|
4898
6085
|
force
|
|
4899
6086
|
});
|
|
4900
|
-
const relTarget =
|
|
6087
|
+
const relTarget = relative11(process.cwd(), result.targetDir) || ".";
|
|
4901
6088
|
console.log(`
|
|
4902
|
-
\u26A1 \x1B[36m[
|
|
6089
|
+
\u26A1 \x1B[36m[Buntic]\x1B[0m Initialized new project (\x1B[33m${result.template}\x1B[0m) in: \x1B[32m${result.targetDir}\x1B[0m`);
|
|
4903
6090
|
console.log(` \u2714 Created ${result.filesCopied} file(s) (no package.json required)`);
|
|
4904
6091
|
if (result.skillsDir) {
|
|
4905
|
-
console.log(` \u2714 Installed
|
|
6092
|
+
console.log(` \u2714 Installed Buntic agent skill in .agents/skills/buntic`);
|
|
4906
6093
|
}
|
|
4907
|
-
console.log(` \u2714 Generated TypeScript definitions in .
|
|
6094
|
+
console.log(` \u2714 Generated TypeScript definitions in .buntic/types/`);
|
|
4908
6095
|
console.log(`
|
|
4909
6096
|
\x1B[1mNext steps:\x1B[0m`);
|
|
4910
6097
|
if (relTarget !== ".") {
|
|
4911
6098
|
console.log(` cd ${relTarget}`);
|
|
4912
6099
|
}
|
|
4913
|
-
console.log(`
|
|
6100
|
+
console.log(` buntic dev
|
|
4914
6101
|
`);
|
|
4915
6102
|
return;
|
|
4916
6103
|
}
|
|
4917
6104
|
if (command === "clean") {
|
|
4918
6105
|
const config = await resolveConfig(targetDir);
|
|
4919
6106
|
console.log(`
|
|
4920
|
-
\uD83E\uDDF9 \x1B[36m[
|
|
6107
|
+
\uD83E\uDDF9 \x1B[36m[Buntic]\x1B[0m Cleaning build and cache directories for: \x1B[33m${config.root}\x1B[0m`);
|
|
4921
6108
|
if (existsSync22(config.outDir)) {
|
|
4922
6109
|
rmSync4(config.outDir, { recursive: true, force: true });
|
|
4923
6110
|
console.log(` \u2714 Removed ${config.outDir}`);
|
|
@@ -4938,14 +6125,14 @@ async function runCLI(args) {
|
|
|
4938
6125
|
console.log(`\x1B[32m\u2714\x1B[0m Cache cleaned.`);
|
|
4939
6126
|
}
|
|
4940
6127
|
console.log(`
|
|
4941
|
-
\uD83D\uDE80 \x1B[36m[
|
|
6128
|
+
\uD83D\uDE80 \x1B[36m[Buntic]\x1B[0m Starting dev server for: \x1B[33m${config.root}\x1B[0m`);
|
|
4942
6129
|
const devInstance = startDevServer(config);
|
|
4943
6130
|
console.log(` \u279C Local: \x1B[32mhttp://localhost:${devInstance.port}/\x1B[0m`);
|
|
4944
6131
|
console.log(` \u279C Live reload enabled via WebSockets.
|
|
4945
6132
|
`);
|
|
4946
6133
|
process.on("SIGINT", () => {
|
|
4947
6134
|
console.log(`
|
|
4948
|
-
\x1B[33m[
|
|
6135
|
+
\x1B[33m[Buntic]\x1B[0m Shutting down server...`);
|
|
4949
6136
|
devInstance.stop();
|
|
4950
6137
|
process.exit(0);
|
|
4951
6138
|
});
|
|
@@ -4953,7 +6140,7 @@ async function runCLI(args) {
|
|
|
4953
6140
|
const config = await resolveConfig(targetDir, { outDir });
|
|
4954
6141
|
syncProjectTypes(config.root);
|
|
4955
6142
|
console.log(`
|
|
4956
|
-
\uD83D\uDCE6 \x1B[36m[
|
|
6143
|
+
\uD83D\uDCE6 \x1B[36m[Buntic]\x1B[0m Building static site for: \x1B[33m${config.root}\x1B[0m`);
|
|
4957
6144
|
const builder = new Builder(config);
|
|
4958
6145
|
const result = await builder.build({ cleanCache });
|
|
4959
6146
|
console.log(`\x1B[32m\u2714\x1B[0m Successfully built ${result.pagesCount} page(s) in ${result.durationMs}ms`);
|
|
@@ -4973,21 +6160,21 @@ async function runCLI(args) {
|
|
|
4973
6160
|
}
|
|
4974
6161
|
function printHelp() {
|
|
4975
6162
|
console.log(`
|
|
4976
|
-
\x1B[
|
|
6163
|
+
\x1B[1mBuntic\x1B[0m - Lightweight zero-dependency static site generator for Bun
|
|
4977
6164
|
|
|
4978
6165
|
\x1B[1mUSAGE:\x1B[0m
|
|
4979
|
-
|
|
6166
|
+
buntic <command> [directory] [options]
|
|
4980
6167
|
|
|
4981
6168
|
\x1B[1mCOMMANDS:\x1B[0m
|
|
4982
|
-
init [dir] Initialize a new
|
|
6169
|
+
init [dir] Initialize a new Buntic project (zero package.json)
|
|
4983
6170
|
dev [dir] Start the development server with live reload
|
|
4984
6171
|
build [dir] Build the static site for production into dist/
|
|
4985
|
-
clean [dir] Remove dist/ and .
|
|
6172
|
+
clean [dir] Remove dist/ and .buntic/cache/ directories
|
|
4986
6173
|
help Show this help message
|
|
4987
6174
|
|
|
4988
6175
|
\x1B[1mOPTIONS:\x1B[0m
|
|
4989
6176
|
-t, --template <name> Template for init: ${AVAILABLE_TEMPLATES.join(", ")} (default: blank)
|
|
4990
|
-
--no-skills Skip installing agent skills in .agents/skills/
|
|
6177
|
+
--no-skills Skip installing agent skills in .agents/skills/buntic
|
|
4991
6178
|
-f, --force Allow init in a non-empty directory
|
|
4992
6179
|
-p, --port <port> Port to run dev server on (default: 3000)
|
|
4993
6180
|
-o, --outdir <dir> Output directory for build (default: dist)
|
|
@@ -4996,13 +6183,13 @@ function printHelp() {
|
|
|
4996
6183
|
-h, --help Show help
|
|
4997
6184
|
|
|
4998
6185
|
\x1B[1mEXAMPLES:\x1B[0m
|
|
4999
|
-
$
|
|
5000
|
-
$
|
|
5001
|
-
$
|
|
5002
|
-
$
|
|
5003
|
-
$
|
|
5004
|
-
$
|
|
5005
|
-
$
|
|
6186
|
+
$ buntic init mi-sitio
|
|
6187
|
+
$ buntic init mi-sitio --template simple
|
|
6188
|
+
$ buntic dev
|
|
6189
|
+
$ buntic dev my-site --port 8080
|
|
6190
|
+
$ buntic build
|
|
6191
|
+
$ buntic build my-site --outdir ./public_html --clean-cache
|
|
6192
|
+
$ buntic clean
|
|
5006
6193
|
`);
|
|
5007
6194
|
}
|
|
5008
6195
|
|
|
@@ -5025,6 +6212,7 @@ export {
|
|
|
5025
6212
|
AssetCache,
|
|
5026
6213
|
AuthManager,
|
|
5027
6214
|
Builder,
|
|
6215
|
+
BunticTemplateError,
|
|
5028
6216
|
ImageProcessor,
|
|
5029
6217
|
OrasClient,
|
|
5030
6218
|
PhotoProcessor,
|
|
@@ -5056,7 +6244,7 @@ export {
|
|
|
5056
6244
|
parseEnvContent,
|
|
5057
6245
|
parseOciReference,
|
|
5058
6246
|
parseWwwAuthenticate,
|
|
5059
|
-
|
|
6247
|
+
registerBunticModuleResolver,
|
|
5060
6248
|
resolveAllRoutes,
|
|
5061
6249
|
resolveConfig,
|
|
5062
6250
|
runCLI,
|