buntic 0.0.0-stage → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +135 -2
- package/dist/assets/cache.d.ts +10 -0
- package/dist/assets/image-processor.d.ts +39 -0
- package/dist/assets/photo-tag.d.ts +19 -0
- package/dist/builder/builder.d.ts +28 -0
- package/dist/builder/collisions.d.ts +10 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +4205 -0
- package/dist/config.d.ts +11 -0
- package/dist/env.d.ts +18 -0
- package/dist/index.d.ts +30 -0
- package/dist/index.js +5060 -0
- package/dist/init.d.ts +15 -0
- package/dist/router/routes.d.ts +48 -0
- package/dist/runtime.d.ts +23 -0
- package/dist/seo/feeds.d.ts +11 -0
- package/dist/seo/metadata.d.ts +33 -0
- package/dist/seo/robots.d.ts +2 -0
- package/dist/seo/sitemap.d.ts +2 -0
- package/dist/server/dev-helpers.d.ts +29 -0
- package/dist/server/dev.d.ts +8 -0
- package/dist/storage/loader.d.ts +17 -0
- package/dist/storage/oras/adapter.d.ts +17 -0
- package/dist/storage/oras/auth.d.ts +46 -0
- package/dist/storage/oras/client.d.ts +83 -0
- package/dist/storage/oras/index.d.ts +6 -0
- package/dist/storage/oras/manifests.d.ts +42 -0
- package/dist/storage/oras/reference.d.ts +15 -0
- package/dist/storage/oras/types.d.ts +161 -0
- package/dist/template/css-graph.d.ts +49 -0
- package/dist/template/css-resolver.d.ts +19 -0
- package/dist/template/css-scoper.d.ts +12 -0
- package/dist/template/data-loader.d.ts +8 -0
- package/dist/template/directives.d.ts +13 -0
- package/dist/template/dsd-renderer.d.ts +23 -0
- package/dist/template/engine.d.ts +39 -0
- package/dist/template/html-scanner.d.ts +37 -0
- package/dist/template/scoped-css.d.ts +30 -0
- package/dist/template/svg-component.d.ts +32 -0
- package/dist/template/vfs.d.ts +57 -0
- package/dist/template/web-components.d.ts +91 -0
- package/dist/types.d.ts +152 -0
- package/dist/utils/html.d.ts +23 -0
- package/dist/utils/logger.d.ts +6 -0
- package/dist/utils/paths.d.ts +20 -0
- package/package.json +54 -4
- package/templates/blank/_gitignore +5 -0
- package/templates/blank/buntic.config.ts +15 -0
- package/templates/blank/src/layouts/main.html +14 -0
- package/templates/blank/src/pages/index.html +11 -0
- package/templates/blank/src/public/robots.txt +2 -0
- package/templates/blank/src/styles/main.css +40 -0
- package/templates/blank/tsconfig.json +21 -0
- package/templates/simple/README.md +35 -0
- package/templates/simple/_gitignore +5 -0
- package/templates/simple/buntic.config.ts +11 -0
- package/templates/simple/src/components/card.css +27 -0
- package/templates/simple/src/components/card.html +7 -0
- package/templates/simple/src/components/footer.css +14 -0
- package/templates/simple/src/components/footer.html +5 -0
- package/templates/simple/src/components/header.css +33 -0
- package/templates/simple/src/components/header.html +10 -0
- package/templates/simple/src/data/features.json +14 -0
- package/templates/simple/src/data/site.json +11 -0
- package/templates/simple/src/layouts/main.html +17 -0
- package/templates/simple/src/pages/about.html +16 -0
- package/templates/simple/src/pages/contact.html +13 -0
- package/templates/simple/src/pages/index.html +17 -0
- package/templates/simple/src/public/robots.txt +2 -0
- package/templates/simple/src/styles/main.css +67 -0
- package/templates/simple/tsconfig.json +21 -0
- package/templates/skills/buntic/SKILL.md +359 -0
- package/templates/skills/buntic/examples/README.md +177 -0
package/dist/cli.js
ADDED
|
@@ -0,0 +1,4205 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// @bun
|
|
3
|
+
|
|
4
|
+
// src/cli.ts
|
|
5
|
+
import { existsSync as existsSync22, rmSync as rmSync4 } from "fs";
|
|
6
|
+
import { relative as relative10 } from "path";
|
|
7
|
+
|
|
8
|
+
// src/config.ts
|
|
9
|
+
import { resolve as resolve2, join as join2, dirname as dirname2, basename } from "path";
|
|
10
|
+
import { existsSync as existsSync2, statSync } from "fs";
|
|
11
|
+
|
|
12
|
+
// src/runtime.ts
|
|
13
|
+
import { existsSync, mkdirSync, readdirSync, cpSync, rmSync, readFileSync, writeFileSync } from "fs";
|
|
14
|
+
import { dirname, join, resolve } from "path";
|
|
15
|
+
import { fileURLToPath } from "url";
|
|
16
|
+
var resolverRegistered = false;
|
|
17
|
+
function getPackageRoot() {
|
|
18
|
+
let current = dirname(fileURLToPath(import.meta.url));
|
|
19
|
+
while (true) {
|
|
20
|
+
const pkgPath = join(current, "package.json");
|
|
21
|
+
if (existsSync(pkgPath)) {
|
|
22
|
+
try {
|
|
23
|
+
const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
|
|
24
|
+
if (pkg?.name === "buntic") {
|
|
25
|
+
return current;
|
|
26
|
+
}
|
|
27
|
+
} catch {}
|
|
28
|
+
}
|
|
29
|
+
const parent = dirname(current);
|
|
30
|
+
if (parent === current) {
|
|
31
|
+
break;
|
|
32
|
+
}
|
|
33
|
+
current = parent;
|
|
34
|
+
}
|
|
35
|
+
return resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
|
36
|
+
}
|
|
37
|
+
function getSelfEntryPath() {
|
|
38
|
+
const pkgRoot = getPackageRoot();
|
|
39
|
+
const currentFile = fileURLToPath(import.meta.url);
|
|
40
|
+
const distEntry = join(pkgRoot, "dist", "index.js");
|
|
41
|
+
const srcEntry = join(pkgRoot, "src", "index.ts");
|
|
42
|
+
if (currentFile.startsWith(join(pkgRoot, "dist")) && existsSync(distEntry)) {
|
|
43
|
+
return distEntry;
|
|
44
|
+
}
|
|
45
|
+
if (existsSync(srcEntry)) {
|
|
46
|
+
return srcEntry;
|
|
47
|
+
}
|
|
48
|
+
return distEntry;
|
|
49
|
+
}
|
|
50
|
+
function hasLocalBunticPackage(startDir) {
|
|
51
|
+
let current = resolve(startDir);
|
|
52
|
+
while (true) {
|
|
53
|
+
if (existsSync(join(current, "node_modules", "buntic", "package.json"))) {
|
|
54
|
+
return true;
|
|
55
|
+
}
|
|
56
|
+
const parent = dirname(current);
|
|
57
|
+
if (parent === current) {
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
current = parent;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function registerBunticModuleResolver(projectDir) {
|
|
64
|
+
if (resolverRegistered)
|
|
65
|
+
return;
|
|
66
|
+
if (projectDir && hasLocalBunticPackage(projectDir))
|
|
67
|
+
return;
|
|
68
|
+
resolverRegistered = true;
|
|
69
|
+
const selfEntry = getSelfEntryPath();
|
|
70
|
+
Bun.plugin({
|
|
71
|
+
name: "buntic-global-self-resolver",
|
|
72
|
+
setup(build) {
|
|
73
|
+
build.module("buntic", async () => {
|
|
74
|
+
const mod = await import(selfEntry);
|
|
75
|
+
return {
|
|
76
|
+
exports: { ...mod },
|
|
77
|
+
loader: "object"
|
|
78
|
+
};
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
function copyDeclarationFiles(srcDir, destDir) {
|
|
84
|
+
let count = 0;
|
|
85
|
+
mkdirSync(destDir, { recursive: true });
|
|
86
|
+
for (const entry of readdirSync(srcDir, { withFileTypes: true })) {
|
|
87
|
+
const srcPath = join(srcDir, entry.name);
|
|
88
|
+
const destPath = join(destDir, entry.name);
|
|
89
|
+
if (entry.isDirectory()) {
|
|
90
|
+
count += copyDeclarationFiles(srcPath, destPath);
|
|
91
|
+
} else if (entry.isFile() && entry.name.endsWith(".d.ts")) {
|
|
92
|
+
cpSync(srcPath, destPath);
|
|
93
|
+
count++;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return count;
|
|
97
|
+
}
|
|
98
|
+
function syncProjectTypes(projectRoot) {
|
|
99
|
+
const absRoot = resolve(projectRoot);
|
|
100
|
+
if (hasLocalBunticPackage(absRoot)) {
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
const pkgRoot = getPackageRoot();
|
|
104
|
+
let version = "0.0.0";
|
|
105
|
+
try {
|
|
106
|
+
const pkg = JSON.parse(readFileSync(join(pkgRoot, "package.json"), "utf8"));
|
|
107
|
+
if (pkg?.version)
|
|
108
|
+
version = pkg.version;
|
|
109
|
+
} catch {}
|
|
110
|
+
const bunticDir = join(absRoot, ".buntic");
|
|
111
|
+
const typesDir = join(bunticDir, "types");
|
|
112
|
+
const typesEntry = join(typesDir, "index.d.ts");
|
|
113
|
+
const versionMarkerPath = join(bunticDir, ".types-version");
|
|
114
|
+
const distDir = join(pkgRoot, "dist");
|
|
115
|
+
const hasBuiltTypes = existsSync(join(distDir, "index.d.ts"));
|
|
116
|
+
const expectedMarker = `${version}:${hasBuiltTypes ? "dist" : "src"}`;
|
|
117
|
+
if (existsSync(typesEntry) && existsSync(versionMarkerPath) && readFileSync(versionMarkerPath, "utf8").trim() === expectedMarker) {
|
|
118
|
+
return false;
|
|
119
|
+
}
|
|
120
|
+
mkdirSync(bunticDir, { recursive: true });
|
|
121
|
+
if (existsSync(typesDir)) {
|
|
122
|
+
rmSync(typesDir, { recursive: true, force: true });
|
|
123
|
+
}
|
|
124
|
+
mkdirSync(typesDir, { recursive: true });
|
|
125
|
+
if (hasBuiltTypes) {
|
|
126
|
+
copyDeclarationFiles(distDir, typesDir);
|
|
127
|
+
} else {
|
|
128
|
+
const srcIndex = join(pkgRoot, "src", "index.ts").replace(/\\/g, "/");
|
|
129
|
+
writeFileSync(typesEntry, `// Auto-generated by Buntic (source dev fallback).
|
|
130
|
+
export * from "${srcIndex}";
|
|
131
|
+
`, "utf8");
|
|
132
|
+
}
|
|
133
|
+
writeFileSync(versionMarkerPath, `${expectedMarker}
|
|
134
|
+
`, "utf8");
|
|
135
|
+
return true;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// src/config.ts
|
|
139
|
+
function findProjectRoot(cliTarget, startCwd = process.cwd()) {
|
|
140
|
+
if (cliTarget && cliTarget !== ".") {
|
|
141
|
+
const target = resolve2(startCwd, cliTarget);
|
|
142
|
+
if (!existsSync2(target)) {
|
|
143
|
+
throw new Error(`[Buntic] Specified project directory does not exist: "${target}"`);
|
|
144
|
+
}
|
|
145
|
+
return target;
|
|
146
|
+
}
|
|
147
|
+
let current = resolve2(startCwd);
|
|
148
|
+
while (true) {
|
|
149
|
+
const hasConfig = existsSync2(join2(current, "buntic.config.ts")) || existsSync2(join2(current, "buntic.config.js")) || existsSync2(join2(current, "buntic.config.json"));
|
|
150
|
+
if (hasConfig) {
|
|
151
|
+
return current;
|
|
152
|
+
}
|
|
153
|
+
const srcPagesDir = join2(current, "src", "pages");
|
|
154
|
+
if (existsSync2(srcPagesDir) && statSync(srcPagesDir).isDirectory()) {
|
|
155
|
+
return current;
|
|
156
|
+
}
|
|
157
|
+
const pagesDir = join2(current, "pages");
|
|
158
|
+
if (existsSync2(pagesDir) && statSync(pagesDir).isDirectory()) {
|
|
159
|
+
if (basename(current) === "src") {
|
|
160
|
+
return dirname2(current);
|
|
161
|
+
}
|
|
162
|
+
return current;
|
|
163
|
+
}
|
|
164
|
+
const parent = dirname2(current);
|
|
165
|
+
if (parent === current) {
|
|
166
|
+
break;
|
|
167
|
+
}
|
|
168
|
+
current = parent;
|
|
169
|
+
}
|
|
170
|
+
throw new Error(`[Buntic Error]: Could not find a Buntic project root.
|
|
171
|
+
` + ` Searched in: ${startCwd} (and parent directories)
|
|
172
|
+
|
|
173
|
+
` + `\uD83D\uDC49 How to fix this:
|
|
174
|
+
` + ` 1. Ensure you have a "pages/" or "src/pages/" directory with at least one .html file.
|
|
175
|
+
` + ` 2. Or pass the project path explicitly:
|
|
176
|
+
` + ` $ buntic dev <directory> (e.g. buntic dev examples/simple)
|
|
177
|
+
` + ` 3. Or create a "buntic.config.ts" / "buntic.config.json" configuration file (or run "buntic init").`);
|
|
178
|
+
}
|
|
179
|
+
async function resolveConfig(cliRootDir = ".", overrides = {}) {
|
|
180
|
+
const root = findProjectRoot(cliRootDir);
|
|
181
|
+
let userConfig = {};
|
|
182
|
+
const tsConfigPath = join2(root, "buntic.config.ts");
|
|
183
|
+
const jsConfigPath = join2(root, "buntic.config.js");
|
|
184
|
+
const jsonConfigPath = join2(root, "buntic.config.json");
|
|
185
|
+
if (existsSync2(tsConfigPath)) {
|
|
186
|
+
registerBunticModuleResolver(root);
|
|
187
|
+
const mod = await import(tsConfigPath);
|
|
188
|
+
userConfig = mod.default || mod;
|
|
189
|
+
} else if (existsSync2(jsConfigPath)) {
|
|
190
|
+
registerBunticModuleResolver(root);
|
|
191
|
+
const mod = await import(jsConfigPath);
|
|
192
|
+
userConfig = mod.default || mod;
|
|
193
|
+
} else if (existsSync2(jsonConfigPath)) {
|
|
194
|
+
const file = Bun.file(jsonConfigPath);
|
|
195
|
+
userConfig = await file.json();
|
|
196
|
+
}
|
|
197
|
+
const merged = {
|
|
198
|
+
...userConfig,
|
|
199
|
+
...overrides
|
|
200
|
+
};
|
|
201
|
+
const hasSrcDir = existsSync2(join2(root, "src")) && statSync(join2(root, "src")).isDirectory();
|
|
202
|
+
const pickDir = (name, checkRootFirst = false) => {
|
|
203
|
+
if (checkRootFirst) {
|
|
204
|
+
if (existsSync2(join2(root, name)))
|
|
205
|
+
return name;
|
|
206
|
+
if (hasSrcDir && existsSync2(join2(root, "src", name)))
|
|
207
|
+
return join2("src", name);
|
|
208
|
+
return name;
|
|
209
|
+
}
|
|
210
|
+
if (hasSrcDir && existsSync2(join2(root, "src", name))) {
|
|
211
|
+
return join2("src", name);
|
|
212
|
+
}
|
|
213
|
+
return name;
|
|
214
|
+
};
|
|
215
|
+
return {
|
|
216
|
+
root,
|
|
217
|
+
pagesDir: resolve2(root, merged.pagesDir ?? pickDir("pages")),
|
|
218
|
+
layoutsDir: resolve2(root, merged.layoutsDir ?? pickDir("layouts")),
|
|
219
|
+
componentsDir: resolve2(root, merged.componentsDir ?? pickDir("components")),
|
|
220
|
+
dataDir: resolve2(root, merged.dataDir ?? pickDir("data")),
|
|
221
|
+
publicDir: resolve2(root, merged.publicDir ?? pickDir("public", true)),
|
|
222
|
+
storageDir: resolve2(root, merged.storageDir ?? pickDir("storage")),
|
|
223
|
+
cacheDir: resolve2(root, merged.cacheDir ?? ".buntic/cache/images"),
|
|
224
|
+
outDir: resolve2(root, merged.outDir ?? "dist"),
|
|
225
|
+
port: merged.port ?? 3000,
|
|
226
|
+
minify: merged.minify ?? true,
|
|
227
|
+
cssStrategy: merged.cssStrategy ?? "inline",
|
|
228
|
+
site: merged.site,
|
|
229
|
+
seo: merged.seo,
|
|
230
|
+
feeds: merged.feeds,
|
|
231
|
+
defaultStorage: merged.defaultStorage
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// src/builder/builder.ts
|
|
236
|
+
import { cpSync as cpSync2, existsSync as existsSync18, mkdirSync as mkdirSync3, rmSync as rmSync3 } from "fs";
|
|
237
|
+
import { dirname as dirname9, join as join17, relative as relative9 } from "path";
|
|
238
|
+
|
|
239
|
+
// src/assets/photo-tag.ts
|
|
240
|
+
import { existsSync as existsSync6, statSync as statSync4 } from "fs";
|
|
241
|
+
|
|
242
|
+
// src/assets/cache.ts
|
|
243
|
+
import { join as join3, dirname as dirname3 } from "path";
|
|
244
|
+
import { existsSync as existsSync3, mkdirSync as mkdirSync2, rmSync as rmSync2 } from "fs";
|
|
245
|
+
|
|
246
|
+
class AssetCache {
|
|
247
|
+
cacheDir;
|
|
248
|
+
constructor(cacheDir) {
|
|
249
|
+
this.cacheDir = cacheDir;
|
|
250
|
+
}
|
|
251
|
+
getCachePath(namespace, hash, ext = "webp") {
|
|
252
|
+
return join3(this.cacheDir, namespace, `${hash}.${ext}`);
|
|
253
|
+
}
|
|
254
|
+
computeHash(parts) {
|
|
255
|
+
const hasher = new Bun.CryptoHasher("sha256");
|
|
256
|
+
for (const part of parts) {
|
|
257
|
+
hasher.update(String(part ?? ""));
|
|
258
|
+
hasher.update("::");
|
|
259
|
+
}
|
|
260
|
+
return hasher.digest("hex").slice(0, 24);
|
|
261
|
+
}
|
|
262
|
+
has(namespace, hash, ext = "webp") {
|
|
263
|
+
const filePath = this.getCachePath(namespace, hash, ext);
|
|
264
|
+
return existsSync3(filePath);
|
|
265
|
+
}
|
|
266
|
+
async get(namespace, hash, ext = "webp") {
|
|
267
|
+
const filePath = this.getCachePath(namespace, hash, ext);
|
|
268
|
+
if (!existsSync3(filePath)) {
|
|
269
|
+
return null;
|
|
270
|
+
}
|
|
271
|
+
try {
|
|
272
|
+
const file = Bun.file(filePath);
|
|
273
|
+
return await file.bytes();
|
|
274
|
+
} catch {
|
|
275
|
+
return null;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
async set(namespace, hash, bytes, ext = "webp") {
|
|
279
|
+
const filePath = this.getCachePath(namespace, hash, ext);
|
|
280
|
+
mkdirSync2(dirname3(filePath), { recursive: true });
|
|
281
|
+
await Bun.write(filePath, bytes);
|
|
282
|
+
return filePath;
|
|
283
|
+
}
|
|
284
|
+
async clean() {
|
|
285
|
+
if (existsSync3(this.cacheDir)) {
|
|
286
|
+
rmSync2(this.cacheDir, { recursive: true, force: true });
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// src/assets/image-processor.ts
|
|
292
|
+
class ImageProcessor {
|
|
293
|
+
cache;
|
|
294
|
+
ramCache = new Map;
|
|
295
|
+
constructor(config) {
|
|
296
|
+
this.cache = new AssetCache(config.cacheDir);
|
|
297
|
+
}
|
|
298
|
+
async getMetadata(bytes) {
|
|
299
|
+
const img = new Bun.Image(bytes);
|
|
300
|
+
const meta = await img.metadata();
|
|
301
|
+
return {
|
|
302
|
+
width: meta.width,
|
|
303
|
+
height: meta.height,
|
|
304
|
+
format: meta.format || "unknown"
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
async processImage(options) {
|
|
308
|
+
const { bytes, namespace, keyOrPath, etagOrMtime, targetWidth } = options;
|
|
309
|
+
return this.getOrComputeVariant({
|
|
310
|
+
namespace,
|
|
311
|
+
hashParts: [
|
|
312
|
+
namespace,
|
|
313
|
+
keyOrPath,
|
|
314
|
+
etagOrMtime ?? bytes.length,
|
|
315
|
+
targetWidth ? `${targetWidth}w` : "orig",
|
|
316
|
+
"webp"
|
|
317
|
+
],
|
|
318
|
+
compute: async () => {
|
|
319
|
+
const originalMeta = await this.getMetadata(bytes);
|
|
320
|
+
let img = new Bun.Image(bytes);
|
|
321
|
+
let finalWidth = originalMeta.width;
|
|
322
|
+
let finalHeight = originalMeta.height;
|
|
323
|
+
if (targetWidth && targetWidth > 0 && targetWidth < originalMeta.width) {
|
|
324
|
+
finalWidth = targetWidth;
|
|
325
|
+
finalHeight = Math.max(1, Math.round(originalMeta.height / originalMeta.width * targetWidth));
|
|
326
|
+
img = await img.resize(finalWidth, finalHeight);
|
|
327
|
+
}
|
|
328
|
+
const webpImg = await img.webp();
|
|
329
|
+
const finalBytes = await webpImg.bytes();
|
|
330
|
+
return {
|
|
331
|
+
bytes: finalBytes,
|
|
332
|
+
width: finalWidth,
|
|
333
|
+
height: finalHeight
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
async processMultiWidths(options) {
|
|
339
|
+
const { bytes, namespace, keyOrPath, etagOrMtime, widths } = options;
|
|
340
|
+
if (!widths || widths.length === 0) {
|
|
341
|
+
const orig = await this.processImage({
|
|
342
|
+
bytes,
|
|
343
|
+
namespace,
|
|
344
|
+
keyOrPath,
|
|
345
|
+
etagOrMtime
|
|
346
|
+
});
|
|
347
|
+
return [orig];
|
|
348
|
+
}
|
|
349
|
+
const meta = await this.getMetadata(bytes);
|
|
350
|
+
const sortedWidths = Array.from(new Set(widths)).filter((w) => w > 0 && w <= meta.width).sort((a, b) => a - b);
|
|
351
|
+
if (sortedWidths.length === 0) {
|
|
352
|
+
const orig = await this.processImage({
|
|
353
|
+
bytes,
|
|
354
|
+
namespace,
|
|
355
|
+
keyOrPath,
|
|
356
|
+
etagOrMtime
|
|
357
|
+
});
|
|
358
|
+
return [orig];
|
|
359
|
+
}
|
|
360
|
+
const results = [];
|
|
361
|
+
for (const w of sortedWidths) {
|
|
362
|
+
const variant = await this.processImage({
|
|
363
|
+
bytes,
|
|
364
|
+
namespace,
|
|
365
|
+
keyOrPath,
|
|
366
|
+
etagOrMtime,
|
|
367
|
+
targetWidth: w
|
|
368
|
+
});
|
|
369
|
+
results.push(variant);
|
|
370
|
+
}
|
|
371
|
+
return results;
|
|
372
|
+
}
|
|
373
|
+
async processSocialImage(options) {
|
|
374
|
+
const { bytes, namespace, keyOrPath, etagOrMtime } = options;
|
|
375
|
+
return this.getOrComputeVariant({
|
|
376
|
+
namespace,
|
|
377
|
+
hashParts: [
|
|
378
|
+
namespace,
|
|
379
|
+
keyOrPath,
|
|
380
|
+
etagOrMtime ?? bytes.length,
|
|
381
|
+
"social-1200x630",
|
|
382
|
+
"webp"
|
|
383
|
+
],
|
|
384
|
+
compute: async () => {
|
|
385
|
+
const img = new Bun.Image(bytes);
|
|
386
|
+
const resized = await img.resize(1200, 630);
|
|
387
|
+
const webpImg = await resized.webp();
|
|
388
|
+
const finalBytes = await webpImg.bytes();
|
|
389
|
+
return {
|
|
390
|
+
bytes: finalBytes,
|
|
391
|
+
width: 1200,
|
|
392
|
+
height: 630
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
async getOrComputeVariant(options) {
|
|
398
|
+
const { namespace, hashParts, compute } = options;
|
|
399
|
+
const hash = this.cache.computeHash(hashParts);
|
|
400
|
+
const ramKey = `${namespace}:${hash}`;
|
|
401
|
+
const fromRam = this.ramCache.get(ramKey);
|
|
402
|
+
if (fromRam) {
|
|
403
|
+
return fromRam;
|
|
404
|
+
}
|
|
405
|
+
const cachedBytes = await this.cache.get(namespace, hash, "webp");
|
|
406
|
+
if (cachedBytes) {
|
|
407
|
+
try {
|
|
408
|
+
const meta = await this.getMetadata(cachedBytes);
|
|
409
|
+
const result = {
|
|
410
|
+
bytes: cachedBytes,
|
|
411
|
+
width: meta.width,
|
|
412
|
+
height: meta.height,
|
|
413
|
+
hash
|
|
414
|
+
};
|
|
415
|
+
this.ramCache.set(ramKey, result);
|
|
416
|
+
return result;
|
|
417
|
+
} catch {}
|
|
418
|
+
}
|
|
419
|
+
const computed = await compute();
|
|
420
|
+
await this.cache.set(namespace, hash, computed.bytes, "webp");
|
|
421
|
+
const result = {
|
|
422
|
+
bytes: computed.bytes,
|
|
423
|
+
width: computed.width,
|
|
424
|
+
height: computed.height,
|
|
425
|
+
hash
|
|
426
|
+
};
|
|
427
|
+
this.ramCache.set(ramKey, result);
|
|
428
|
+
return result;
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
// src/storage/loader.ts
|
|
433
|
+
import { join as join4, basename as basename2, extname } from "path";
|
|
434
|
+
import { existsSync as existsSync4, readdirSync as readdirSync2, statSync as statSync2 } from "fs";
|
|
435
|
+
|
|
436
|
+
// src/utils/logger.ts
|
|
437
|
+
function getErrorMessage(err) {
|
|
438
|
+
if (err instanceof Error)
|
|
439
|
+
return err.message;
|
|
440
|
+
if (typeof err === "string")
|
|
441
|
+
return err;
|
|
442
|
+
try {
|
|
443
|
+
return JSON.stringify(err);
|
|
444
|
+
} catch {
|
|
445
|
+
return String(err);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
function logWarn(message, label = "Buntic Warning") {
|
|
449
|
+
console.warn(`\x1B[33m\u26A0 [${label}]\x1B[0m ${message}`);
|
|
450
|
+
}
|
|
451
|
+
function logError(message, err, label = "Buntic Error") {
|
|
452
|
+
if (err !== undefined) {
|
|
453
|
+
console.error(`\x1B[31m[${label}]\x1B[0m ${message}:`, getErrorMessage(err));
|
|
454
|
+
} else {
|
|
455
|
+
console.error(`\x1B[31m[${label}]\x1B[0m ${message}`);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
// src/storage/loader.ts
|
|
460
|
+
class StorageManager {
|
|
461
|
+
config;
|
|
462
|
+
storages = new Map;
|
|
463
|
+
initialized = false;
|
|
464
|
+
constructor(config) {
|
|
465
|
+
this.config = config;
|
|
466
|
+
}
|
|
467
|
+
async init() {
|
|
468
|
+
if (this.initialized)
|
|
469
|
+
return;
|
|
470
|
+
this.storages.clear();
|
|
471
|
+
if (!existsSync4(this.config.storageDir) || !statSync2(this.config.storageDir).isDirectory()) {
|
|
472
|
+
this.initialized = true;
|
|
473
|
+
return;
|
|
474
|
+
}
|
|
475
|
+
const entries = readdirSync2(this.config.storageDir);
|
|
476
|
+
for (const entry of entries) {
|
|
477
|
+
if (entry.startsWith("."))
|
|
478
|
+
continue;
|
|
479
|
+
const ext = extname(entry);
|
|
480
|
+
if (![".ts", ".js", ".mjs"].includes(ext))
|
|
481
|
+
continue;
|
|
482
|
+
const fullPath = join4(this.config.storageDir, entry);
|
|
483
|
+
const name = basename2(entry, ext);
|
|
484
|
+
try {
|
|
485
|
+
const mod = await import(`${fullPath}?t=${Date.now()}`);
|
|
486
|
+
const loaderFn = mod.default || mod.getAsset || mod.loader;
|
|
487
|
+
if (typeof loaderFn !== "function") {
|
|
488
|
+
logWarn(`Storage loader "${entry}" in "${this.config.storageDir}" must export a default function. Skipping.`);
|
|
489
|
+
continue;
|
|
490
|
+
}
|
|
491
|
+
this.storages.set(name, {
|
|
492
|
+
name,
|
|
493
|
+
filePath: fullPath,
|
|
494
|
+
loaderFn
|
|
495
|
+
});
|
|
496
|
+
} catch (err) {
|
|
497
|
+
logError(`Failed to load storage loader "${entry}"`, err);
|
|
498
|
+
throw err;
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
this.initialized = true;
|
|
502
|
+
}
|
|
503
|
+
getAvailableStorages() {
|
|
504
|
+
return Array.from(this.storages.keys());
|
|
505
|
+
}
|
|
506
|
+
getDefaultStorageName() {
|
|
507
|
+
if (this.config.defaultStorage && this.storages.has(this.config.defaultStorage)) {
|
|
508
|
+
return this.config.defaultStorage;
|
|
509
|
+
}
|
|
510
|
+
const names = this.getAvailableStorages();
|
|
511
|
+
if (names.length === 1) {
|
|
512
|
+
return names[0];
|
|
513
|
+
}
|
|
514
|
+
return;
|
|
515
|
+
}
|
|
516
|
+
invalidate() {
|
|
517
|
+
this.initialized = false;
|
|
518
|
+
this.storages.clear();
|
|
519
|
+
}
|
|
520
|
+
async fetchAsset(key, storageName) {
|
|
521
|
+
await this.init();
|
|
522
|
+
const targetStorage = storageName || this.getDefaultStorageName();
|
|
523
|
+
const available = this.getAvailableStorages();
|
|
524
|
+
if (!targetStorage) {
|
|
525
|
+
if (available.length === 0) {
|
|
526
|
+
throw new Error(`[Buntic Error] No storage loaders found in "${this.config.storageDir}".
|
|
527
|
+
` + `\uD83D\uDC49 Create a storage loader (e.g. "${join4(this.config.storageDir, "s3.ts")}") to handle key "${key}".`);
|
|
528
|
+
}
|
|
529
|
+
throw new Error(`[Buntic Error] Multiple storage loaders detected ([${available.join(", ")}]), but no storage name was specified for key "${key}".
|
|
530
|
+
` + `\uD83D\uDC49 Specify storage="..." in your tag or set "defaultStorage" in buntic.config.ts.`);
|
|
531
|
+
}
|
|
532
|
+
const storage = this.storages.get(targetStorage);
|
|
533
|
+
if (!storage) {
|
|
534
|
+
throw new Error(`[Buntic Error] Storage loader "${targetStorage}" not found in "${this.config.storageDir}".
|
|
535
|
+
Available storages: [${available.join(", ")}]`);
|
|
536
|
+
}
|
|
537
|
+
try {
|
|
538
|
+
const rawResult = await storage.loaderFn(key);
|
|
539
|
+
return normalizeStorageResult(rawResult, key, targetStorage);
|
|
540
|
+
} catch (err) {
|
|
541
|
+
logError(`Error fetching asset "${key}" from storage "${targetStorage}"`, err);
|
|
542
|
+
throw err;
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
async function normalizeStorageResult(result, key, storageName) {
|
|
547
|
+
if (!result) {
|
|
548
|
+
throw new Error(`[Buntic Error] Storage loader "${storageName}" returned null/undefined for key "${key}".`);
|
|
549
|
+
}
|
|
550
|
+
if (result instanceof Response) {
|
|
551
|
+
const arrayBuf = await result.arrayBuffer();
|
|
552
|
+
return {
|
|
553
|
+
bytes: new Uint8Array(arrayBuf),
|
|
554
|
+
etag: result.headers.get("etag") || undefined,
|
|
555
|
+
contentType: result.headers.get("content-type") || undefined
|
|
556
|
+
};
|
|
557
|
+
}
|
|
558
|
+
if (typeof result === "object" && "bytes" in result && typeof result.bytes === "function") {
|
|
559
|
+
const fileLike = result;
|
|
560
|
+
const bytes = await fileLike.bytes();
|
|
561
|
+
let etag;
|
|
562
|
+
let contentType;
|
|
563
|
+
if (typeof fileLike.stat === "function") {
|
|
564
|
+
try {
|
|
565
|
+
const st = await fileLike.stat();
|
|
566
|
+
etag = st?.etag;
|
|
567
|
+
contentType = st?.type;
|
|
568
|
+
} catch {}
|
|
569
|
+
}
|
|
570
|
+
return {
|
|
571
|
+
bytes: bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes),
|
|
572
|
+
etag,
|
|
573
|
+
contentType
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
if (typeof result === "object" && "bytes" in result && result.bytes) {
|
|
577
|
+
const assetObj = result;
|
|
578
|
+
let bytes;
|
|
579
|
+
if (assetObj.bytes instanceof Uint8Array) {
|
|
580
|
+
bytes = assetObj.bytes;
|
|
581
|
+
} else if (assetObj.bytes instanceof ArrayBuffer) {
|
|
582
|
+
bytes = new Uint8Array(assetObj.bytes);
|
|
583
|
+
} else {
|
|
584
|
+
bytes = new Uint8Array(assetObj.bytes);
|
|
585
|
+
}
|
|
586
|
+
return {
|
|
587
|
+
bytes,
|
|
588
|
+
etag: assetObj.etag || undefined,
|
|
589
|
+
contentType: assetObj.contentType || undefined
|
|
590
|
+
};
|
|
591
|
+
}
|
|
592
|
+
if (result instanceof Uint8Array) {
|
|
593
|
+
return {
|
|
594
|
+
bytes: result
|
|
595
|
+
};
|
|
596
|
+
}
|
|
597
|
+
if (result instanceof ArrayBuffer) {
|
|
598
|
+
return {
|
|
599
|
+
bytes: new Uint8Array(result)
|
|
600
|
+
};
|
|
601
|
+
}
|
|
602
|
+
throw new Error(`[Buntic Error] Unsupported return type from storage loader "${storageName}" for key "${key}".
|
|
603
|
+
Expected Uint8Array, ArrayBuffer, Response, BunFile or { bytes, etag?, contentType? }. Received: ${typeof result}`);
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
// src/utils/html.ts
|
|
607
|
+
function escapeHtml(str) {
|
|
608
|
+
return str.replace(/&/g, "&").replace(/"/g, """).replace(/'/g, "'").replace(/</g, "<").replace(/>/g, ">");
|
|
609
|
+
}
|
|
610
|
+
function escapeXml(str) {
|
|
611
|
+
return str.replace(/&/g, "&").replace(/"/g, """).replace(/'/g, "'").replace(/</g, "<").replace(/>/g, ">");
|
|
612
|
+
}
|
|
613
|
+
function parseHtmlAttributes(attrString, booleanDefault = "true") {
|
|
614
|
+
const attrs = {};
|
|
615
|
+
const attrRegex = /([a-zA-Z0-9_\-:@]+)(?:=(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g;
|
|
616
|
+
let match;
|
|
617
|
+
while ((match = attrRegex.exec(attrString)) !== null) {
|
|
618
|
+
const key = match[1];
|
|
619
|
+
const val = match[2] ?? match[3] ?? match[4] ?? booleanDefault;
|
|
620
|
+
attrs[key] = val;
|
|
621
|
+
}
|
|
622
|
+
return attrs;
|
|
623
|
+
}
|
|
624
|
+
function replaceLiteral(source, search, replacement) {
|
|
625
|
+
return source.replace(search, () => replacement);
|
|
626
|
+
}
|
|
627
|
+
function injectIntoHead(html, snippet, fallbackPosition = "append") {
|
|
628
|
+
if (!snippet.trim()) {
|
|
629
|
+
return html;
|
|
630
|
+
}
|
|
631
|
+
if (/<\/head>/i.test(html)) {
|
|
632
|
+
return html.replace(/<\/head>/i, () => `${snippet}
|
|
633
|
+
</head>`);
|
|
634
|
+
}
|
|
635
|
+
if (/<html\b[^>]*>/i.test(html) && fallbackPosition === "prepend") {
|
|
636
|
+
return html.replace(/(<html\b[^>]*>)/i, (match) => `${match}
|
|
637
|
+
<head>
|
|
638
|
+
${snippet}
|
|
639
|
+
</head>`);
|
|
640
|
+
}
|
|
641
|
+
if (/<\/body>/i.test(html)) {
|
|
642
|
+
return html.replace(/<\/body>/i, () => `${snippet}
|
|
643
|
+
</body>`);
|
|
644
|
+
}
|
|
645
|
+
return fallbackPosition === "prepend" ? `${snippet}
|
|
646
|
+
${html}` : `${html}
|
|
647
|
+
${snippet}`;
|
|
648
|
+
}
|
|
649
|
+
function injectBeforeBodyEnd(html, snippet) {
|
|
650
|
+
if (!snippet) {
|
|
651
|
+
return html;
|
|
652
|
+
}
|
|
653
|
+
if (/<\/body>/i.test(html)) {
|
|
654
|
+
return html.replace(/<\/body>/i, () => `${snippet}</body>`);
|
|
655
|
+
}
|
|
656
|
+
return `${html}${snippet}`;
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
// src/utils/paths.ts
|
|
660
|
+
import { existsSync as existsSync5, readdirSync as readdirSync3, statSync as statSync3 } from "fs";
|
|
661
|
+
import { dirname as dirname4, join as join5, relative, resolve as resolve3, sep } from "path";
|
|
662
|
+
function isPathInside(baseDir, targetPath) {
|
|
663
|
+
const absBase = resolve3(baseDir);
|
|
664
|
+
const absTarget = resolve3(targetPath);
|
|
665
|
+
if (absTarget === absBase)
|
|
666
|
+
return true;
|
|
667
|
+
const rel = relative(absBase, absTarget);
|
|
668
|
+
return rel !== "" && !rel.startsWith("..") && !rel.startsWith(sep) && !/^[a-zA-Z]:/.test(rel);
|
|
669
|
+
}
|
|
670
|
+
function resolveLocalAssetPath(config, src, fromFile) {
|
|
671
|
+
if (src.startsWith("/")) {
|
|
672
|
+
const clean = src.slice(1);
|
|
673
|
+
const fromPublic = join5(config.publicDir, clean);
|
|
674
|
+
if (existsSync5(fromPublic)) {
|
|
675
|
+
return fromPublic;
|
|
676
|
+
}
|
|
677
|
+
const fromRoot = join5(config.root, clean);
|
|
678
|
+
if (existsSync5(fromRoot)) {
|
|
679
|
+
return fromRoot;
|
|
680
|
+
}
|
|
681
|
+
const fromSrc = join5(config.root, "src", clean);
|
|
682
|
+
if (existsSync5(fromSrc)) {
|
|
683
|
+
return fromSrc;
|
|
684
|
+
}
|
|
685
|
+
return fromRoot;
|
|
686
|
+
}
|
|
687
|
+
return resolve3(dirname4(fromFile), src);
|
|
688
|
+
}
|
|
689
|
+
function walkFiles(dir, options = {}) {
|
|
690
|
+
if (!existsSync5(dir))
|
|
691
|
+
return [];
|
|
692
|
+
const baseDir = options.baseDir ?? dir;
|
|
693
|
+
const relativeToBase = options.relativeToBase ?? false;
|
|
694
|
+
const ignoreDotfiles = options.ignoreDotfiles ?? false;
|
|
695
|
+
const results = [];
|
|
696
|
+
for (const entry of readdirSync3(dir)) {
|
|
697
|
+
if (ignoreDotfiles && entry.startsWith("."))
|
|
698
|
+
continue;
|
|
699
|
+
const full = join5(dir, entry);
|
|
700
|
+
const stat = statSync3(full);
|
|
701
|
+
if (stat.isDirectory()) {
|
|
702
|
+
results.push(...walkFiles(full, {
|
|
703
|
+
...options,
|
|
704
|
+
baseDir
|
|
705
|
+
}));
|
|
706
|
+
} else if (stat.isFile()) {
|
|
707
|
+
if (options.filter && !options.filter(full, entry))
|
|
708
|
+
continue;
|
|
709
|
+
results.push(relativeToBase ? relative(baseDir, full).replace(/\\/g, "/") : full);
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
return results;
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
// src/assets/photo-tag.ts
|
|
716
|
+
var RESERVED_PHOTO_ATTRS = new Set([
|
|
717
|
+
"src",
|
|
718
|
+
"key",
|
|
719
|
+
"storage",
|
|
720
|
+
"widths",
|
|
721
|
+
"sizes",
|
|
722
|
+
"width",
|
|
723
|
+
"height",
|
|
724
|
+
"loading",
|
|
725
|
+
"decoding",
|
|
726
|
+
"alt"
|
|
727
|
+
]);
|
|
728
|
+
|
|
729
|
+
class PhotoProcessor {
|
|
730
|
+
config;
|
|
731
|
+
imageProcessor;
|
|
732
|
+
storageManager;
|
|
733
|
+
emittedAssets = new Map;
|
|
734
|
+
constructor(config) {
|
|
735
|
+
this.config = config;
|
|
736
|
+
this.imageProcessor = new ImageProcessor(config);
|
|
737
|
+
this.storageManager = new StorageManager(config);
|
|
738
|
+
}
|
|
739
|
+
parseAttributes(attrString) {
|
|
740
|
+
return parseHtmlAttributes(attrString, "");
|
|
741
|
+
}
|
|
742
|
+
async processHtml(html, templatePath) {
|
|
743
|
+
const photoRegex = /<photo\b([^>]*?)(?:\/>|>[\s\S]*?<\/photo>|>)/gi;
|
|
744
|
+
const matches = [];
|
|
745
|
+
let m;
|
|
746
|
+
while ((m = photoRegex.exec(html)) !== null) {
|
|
747
|
+
matches.push({ fullMatch: m[0], attrString: m[1] });
|
|
748
|
+
}
|
|
749
|
+
if (matches.length === 0) {
|
|
750
|
+
return html;
|
|
751
|
+
}
|
|
752
|
+
let resultHtml = html;
|
|
753
|
+
for (const match of matches) {
|
|
754
|
+
const attrs = this.parseAttributes(match.attrString);
|
|
755
|
+
const src = attrs.src;
|
|
756
|
+
const key = attrs.key;
|
|
757
|
+
const storage = attrs.storage;
|
|
758
|
+
if (!src && !key) {
|
|
759
|
+
throw new Error(`[Buntic Error] <photo> tag must have a "src" (for local files) or a "key" (for remote storage) in "${templatePath}".
|
|
760
|
+
` + ` Found: ${match.fullMatch}`);
|
|
761
|
+
}
|
|
762
|
+
const widths = attrs.widths ? attrs.widths.split(",").map((w) => parseInt(w.trim(), 10)).filter((w) => !isNaN(w) && w > 0) : undefined;
|
|
763
|
+
const variants = await this.resolveVariants({
|
|
764
|
+
src,
|
|
765
|
+
key,
|
|
766
|
+
storage,
|
|
767
|
+
widths,
|
|
768
|
+
templatePath
|
|
769
|
+
});
|
|
770
|
+
for (const variant of variants) {
|
|
771
|
+
const outFileName = `assets/images/${variant.hash}.webp`;
|
|
772
|
+
const url = `/${outFileName}`;
|
|
773
|
+
this.emittedAssets.set(url, {
|
|
774
|
+
outputPath: outFileName,
|
|
775
|
+
url,
|
|
776
|
+
bytes: variant.bytes
|
|
777
|
+
});
|
|
778
|
+
}
|
|
779
|
+
const replacementImg = this.buildImgTag(variants, attrs, widths);
|
|
780
|
+
resultHtml = replaceLiteral(resultHtml, match.fullMatch, replacementImg);
|
|
781
|
+
}
|
|
782
|
+
return resultHtml;
|
|
783
|
+
}
|
|
784
|
+
async resolveVariants(options) {
|
|
785
|
+
const { src, key, storage, widths, templatePath } = options;
|
|
786
|
+
if (key) {
|
|
787
|
+
const asset = await this.storageManager.fetchAsset(key, storage);
|
|
788
|
+
const storageName = storage || this.storageManager.getDefaultStorageName() || "storage";
|
|
789
|
+
return this.imageProcessor.processMultiWidths({
|
|
790
|
+
bytes: asset.bytes,
|
|
791
|
+
namespace: storageName,
|
|
792
|
+
keyOrPath: key,
|
|
793
|
+
etagOrMtime: asset.etag,
|
|
794
|
+
widths
|
|
795
|
+
});
|
|
796
|
+
}
|
|
797
|
+
const localPath = resolveLocalAssetPath(this.config, src, templatePath);
|
|
798
|
+
if (!existsSync6(localPath)) {
|
|
799
|
+
throw new Error(`[Buntic Error] Local image file "${src}" referenced in <photo> not found.
|
|
800
|
+
` + ` Looked in: "${localPath}"
|
|
801
|
+
` + ` Referenced in: "${templatePath}"`);
|
|
802
|
+
}
|
|
803
|
+
const stats = statSync4(localPath);
|
|
804
|
+
const bytes = await Bun.file(localPath).bytes();
|
|
805
|
+
return this.imageProcessor.processMultiWidths({
|
|
806
|
+
bytes,
|
|
807
|
+
namespace: "local",
|
|
808
|
+
keyOrPath: localPath,
|
|
809
|
+
etagOrMtime: `${stats.mtimeMs}-${stats.size}`,
|
|
810
|
+
widths
|
|
811
|
+
});
|
|
812
|
+
}
|
|
813
|
+
buildImgTag(variants, attrs, widths) {
|
|
814
|
+
const fallbackVariant = variants[variants.length - 1];
|
|
815
|
+
const fallbackUrl = `/assets/images/${fallbackVariant.hash}.webp`;
|
|
816
|
+
const fallbackSrc = this.emittedAssets.get(fallbackUrl)?.url || fallbackUrl;
|
|
817
|
+
const widthVal = attrs.width || String(fallbackVariant.width);
|
|
818
|
+
const heightVal = attrs.height || String(fallbackVariant.height);
|
|
819
|
+
const loading = attrs.loading ?? "lazy";
|
|
820
|
+
const decoding = attrs.decoding ?? "async";
|
|
821
|
+
const alt = attrs.alt ?? "";
|
|
822
|
+
let srcsetAttr = "";
|
|
823
|
+
let sizesResult = "";
|
|
824
|
+
if (variants.length > 1 || widths && widths.length > 0) {
|
|
825
|
+
const srcsetEntries = variants.map((v) => `/assets/images/${v.hash}.webp ${v.width}w`);
|
|
826
|
+
srcsetAttr = ` srcset="${srcsetEntries.join(", ")}"`;
|
|
827
|
+
sizesResult = ` sizes="${attrs.sizes || "100vw"}"`;
|
|
828
|
+
}
|
|
829
|
+
const extraAttrsList = [];
|
|
830
|
+
for (const [k, v] of Object.entries(attrs)) {
|
|
831
|
+
if (!RESERVED_PHOTO_ATTRS.has(k)) {
|
|
832
|
+
extraAttrsList.push(v === "" ? k : `${k}="${escapeHtml(v)}"`);
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
const extraAttrs = extraAttrsList.length > 0 ? " " + extraAttrsList.join(" ") : "";
|
|
836
|
+
return `<img src="${fallbackSrc}"${srcsetAttr}${sizesResult} width="${widthVal}" height="${heightVal}" loading="${loading}" decoding="${decoding}" alt="${escapeHtml(alt)}"${extraAttrs}>`;
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
// src/router/routes.ts
|
|
841
|
+
import { join as join6, relative as relative2, sep as sep2 } from "path";
|
|
842
|
+
import { existsSync as existsSync7 } from "fs";
|
|
843
|
+
function extractRouteTokens(routePattern) {
|
|
844
|
+
const matches = routePattern.match(/\[([a-zA-Z0-9_-]+)\]/g);
|
|
845
|
+
if (!matches)
|
|
846
|
+
return [];
|
|
847
|
+
return matches.map((m) => m.slice(1, -1));
|
|
848
|
+
}
|
|
849
|
+
function isDynamicPattern(routePattern) {
|
|
850
|
+
return /\[[a-zA-Z0-9_-]+\]/.test(routePattern);
|
|
851
|
+
}
|
|
852
|
+
function findCoLocatedLoader(templateFilePath) {
|
|
853
|
+
const basePath = templateFilePath.replace(/\.html$/, "");
|
|
854
|
+
const candidates = [
|
|
855
|
+
`${basePath}.data.ts`,
|
|
856
|
+
`${basePath}.data.js`,
|
|
857
|
+
`${basePath}.data.mjs`
|
|
858
|
+
];
|
|
859
|
+
for (const cand of candidates) {
|
|
860
|
+
if (existsSync7(cand)) {
|
|
861
|
+
return cand;
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
return null;
|
|
865
|
+
}
|
|
866
|
+
async function executeStaticLoader(loaderPath, globalData, options) {
|
|
867
|
+
const importPath = options?.cacheBust ? `${loaderPath}?t=${Date.now()}` : loaderPath;
|
|
868
|
+
const mod = await import(importPath);
|
|
869
|
+
const handler = mod.default ?? mod.getStaticPaths ?? mod.loader;
|
|
870
|
+
if (typeof handler !== "function") {
|
|
871
|
+
return { props: {} };
|
|
872
|
+
}
|
|
873
|
+
const result = await handler({
|
|
874
|
+
data: globalData,
|
|
875
|
+
env: globalData.env || {}
|
|
876
|
+
});
|
|
877
|
+
if (result && typeof result === "object" && !Array.isArray(result)) {
|
|
878
|
+
const record = result;
|
|
879
|
+
if ("props" in record || "seo" in record || "feed" in record) {
|
|
880
|
+
return {
|
|
881
|
+
props: record.props || {},
|
|
882
|
+
seo: record.seo,
|
|
883
|
+
feed: record.feed
|
|
884
|
+
};
|
|
885
|
+
}
|
|
886
|
+
return { props: record };
|
|
887
|
+
}
|
|
888
|
+
return { props: {} };
|
|
889
|
+
}
|
|
890
|
+
function createPaginator(baseRouteUrl) {
|
|
891
|
+
const normalizedBase = baseRouteUrl === "/" ? "" : baseRouteUrl.replace(/\/+$/, "");
|
|
892
|
+
return function paginate(items, options) {
|
|
893
|
+
const pageSize = Math.max(1, options?.pageSize || 10);
|
|
894
|
+
const total = items.length;
|
|
895
|
+
const lastPage = Math.max(1, Math.ceil(total / pageSize));
|
|
896
|
+
const results = [];
|
|
897
|
+
for (let p = 1;p <= lastPage; p++) {
|
|
898
|
+
const start = (p - 1) * pageSize;
|
|
899
|
+
const end = start + pageSize;
|
|
900
|
+
const pageData = items.slice(start, end);
|
|
901
|
+
const currentUrl = p === 1 ? normalizedBase || "/" : `${normalizedBase}/${p}`;
|
|
902
|
+
const prevUrl = p === 1 ? null : p === 2 ? normalizedBase || "/" : `${normalizedBase}/${p - 1}`;
|
|
903
|
+
const nextUrl = p < lastPage ? `${normalizedBase}/${p + 1}` : null;
|
|
904
|
+
const pageInfo = {
|
|
905
|
+
data: pageData,
|
|
906
|
+
start,
|
|
907
|
+
end: Math.min(end, total),
|
|
908
|
+
total,
|
|
909
|
+
currentPage: p,
|
|
910
|
+
size: pageSize,
|
|
911
|
+
lastPage,
|
|
912
|
+
url: {
|
|
913
|
+
current: currentUrl,
|
|
914
|
+
prev: prevUrl,
|
|
915
|
+
next: nextUrl
|
|
916
|
+
}
|
|
917
|
+
};
|
|
918
|
+
results.push({
|
|
919
|
+
params: { page: String(p) },
|
|
920
|
+
props: {
|
|
921
|
+
...options?.props || {},
|
|
922
|
+
page: pageInfo
|
|
923
|
+
}
|
|
924
|
+
});
|
|
925
|
+
}
|
|
926
|
+
return results;
|
|
927
|
+
};
|
|
928
|
+
}
|
|
929
|
+
function validateRouteParams(requiredTokens, params, loaderPath) {
|
|
930
|
+
const cleanParams = {};
|
|
931
|
+
for (const token of requiredTokens) {
|
|
932
|
+
const rawVal = params[token];
|
|
933
|
+
if (rawVal === undefined || rawVal === null) {
|
|
934
|
+
throw new Error(`[Buntic Error]: Missing required route parameter "${token}" in loader "${loaderPath}".
|
|
935
|
+
Provided parameters: ${JSON.stringify(params)}`);
|
|
936
|
+
}
|
|
937
|
+
const strVal = String(rawVal).trim();
|
|
938
|
+
if (strVal === "") {
|
|
939
|
+
throw new Error(`[Buntic Error]: Route parameter "${token}" in loader "${loaderPath}" cannot be an empty string.`);
|
|
940
|
+
}
|
|
941
|
+
if (/[\/\\?#\0]/.test(strVal)) {
|
|
942
|
+
throw new Error(`[Buntic Error]: Route parameter "${token}" with value "${strVal}" in "${loaderPath}" contains invalid characters (/ \\ ? #).`);
|
|
943
|
+
}
|
|
944
|
+
cleanParams[token] = strVal;
|
|
945
|
+
}
|
|
946
|
+
return cleanParams;
|
|
947
|
+
}
|
|
948
|
+
function buildCleanUrl(patternRelPath, params) {
|
|
949
|
+
const isDynamic = isDynamicPattern(patternRelPath);
|
|
950
|
+
let pathStr = patternRelPath.split(sep2).join("/");
|
|
951
|
+
pathStr = pathStr.replace(/\.html$/, "");
|
|
952
|
+
const isPageParam = pathStr.endsWith("/[page]") || pathStr === "[page]";
|
|
953
|
+
const isFirstPage = String(params.page) === "1";
|
|
954
|
+
if (isPageParam && isFirstPage) {
|
|
955
|
+
if (pathStr === "[page]") {
|
|
956
|
+
pathStr = "";
|
|
957
|
+
} else {
|
|
958
|
+
pathStr = pathStr.replace(/\/\[page\]$/, "");
|
|
959
|
+
}
|
|
960
|
+
} else {
|
|
961
|
+
for (const [key, val] of Object.entries(params)) {
|
|
962
|
+
pathStr = pathStr.replaceAll(`[${key}]`, val);
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
if (pathStr === "" || pathStr === "index") {
|
|
966
|
+
return {
|
|
967
|
+
urlPath: "/",
|
|
968
|
+
relOutputPath: "index.html"
|
|
969
|
+
};
|
|
970
|
+
}
|
|
971
|
+
let cleanUrl = pathStr;
|
|
972
|
+
if (cleanUrl.endsWith("/index")) {
|
|
973
|
+
cleanUrl = cleanUrl.slice(0, -6);
|
|
974
|
+
}
|
|
975
|
+
cleanUrl = "/" + cleanUrl.replace(/^\/+|\/+$/g, "");
|
|
976
|
+
let relOutputPath;
|
|
977
|
+
if (isDynamic || isPageParam || patternRelPath.endsWith("index.html")) {
|
|
978
|
+
relOutputPath = pathStr.replace(/^\/+/, "") + "/index.html";
|
|
979
|
+
} else {
|
|
980
|
+
relOutputPath = patternRelPath.split(sep2).join("/");
|
|
981
|
+
}
|
|
982
|
+
return {
|
|
983
|
+
urlPath: cleanUrl,
|
|
984
|
+
relOutputPath
|
|
985
|
+
};
|
|
986
|
+
}
|
|
987
|
+
function registerRouteOrThrow(urlRegistry, urlPath, sourceDesc) {
|
|
988
|
+
if (urlRegistry.has(urlPath)) {
|
|
989
|
+
throw new Error(`[Buntic Collision Error]: Duplicate route generated for "${urlPath}".
|
|
990
|
+
- First generated by: ${urlRegistry.get(urlPath)}
|
|
991
|
+
- Conflicting with: ${sourceDesc}`);
|
|
992
|
+
}
|
|
993
|
+
urlRegistry.set(urlPath, sourceDesc);
|
|
994
|
+
}
|
|
995
|
+
async function resolveStaticRoute(options) {
|
|
996
|
+
const { config, templatePath, relPattern, loaderPath, globalData, cacheBust, urlRegistry } = options;
|
|
997
|
+
let loaderResult = { props: {} };
|
|
998
|
+
if (loaderPath) {
|
|
999
|
+
try {
|
|
1000
|
+
loaderResult = await executeStaticLoader(loaderPath, globalData, { cacheBust });
|
|
1001
|
+
} catch (err) {
|
|
1002
|
+
logError(`Error executing loader "${relative2(config.root, loaderPath)}"`, err);
|
|
1003
|
+
throw err;
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
const { urlPath, relOutputPath } = buildCleanUrl(relPattern, {});
|
|
1007
|
+
registerRouteOrThrow(urlRegistry, urlPath, relPattern);
|
|
1008
|
+
return {
|
|
1009
|
+
patternRelativePath: relPattern,
|
|
1010
|
+
templateFilePath: templatePath,
|
|
1011
|
+
urlPath,
|
|
1012
|
+
outputFilePath: join6(config.outDir, relOutputPath),
|
|
1013
|
+
params: {},
|
|
1014
|
+
props: loaderResult.props,
|
|
1015
|
+
isDynamic: false,
|
|
1016
|
+
seo: loaderResult.seo,
|
|
1017
|
+
feed: loaderResult.feed
|
|
1018
|
+
};
|
|
1019
|
+
}
|
|
1020
|
+
async function resolveDynamicRoutes(options) {
|
|
1021
|
+
const {
|
|
1022
|
+
config,
|
|
1023
|
+
templatePath,
|
|
1024
|
+
relPattern,
|
|
1025
|
+
tokens,
|
|
1026
|
+
loaderPath,
|
|
1027
|
+
globalData,
|
|
1028
|
+
cacheBust,
|
|
1029
|
+
urlRegistry
|
|
1030
|
+
} = options;
|
|
1031
|
+
if (!loaderPath) {
|
|
1032
|
+
const expected = relPattern.replace(/\.html$/, ".data.ts");
|
|
1033
|
+
throw new Error(`[Buntic Error]: Dynamic page "${relPattern}" contains parameter(s) [${tokens.join(", ")}], but no co-located loader was found.
|
|
1034
|
+
` + `\uD83D\uDC49 Create "${expected}" exporting a default async function or getStaticPaths().`);
|
|
1035
|
+
}
|
|
1036
|
+
const relLoader = relative2(config.root, loaderPath);
|
|
1037
|
+
let mod;
|
|
1038
|
+
try {
|
|
1039
|
+
const importPath = cacheBust ? `${loaderPath}?t=${Date.now()}` : loaderPath;
|
|
1040
|
+
mod = await import(importPath);
|
|
1041
|
+
} catch (err) {
|
|
1042
|
+
logError(`Failed to import loader "${relLoader}"`, err);
|
|
1043
|
+
throw err;
|
|
1044
|
+
}
|
|
1045
|
+
const handler = mod.default ?? mod.getStaticPaths;
|
|
1046
|
+
if (typeof handler !== "function") {
|
|
1047
|
+
throw new Error(`[Buntic Error]: Loader "${relLoader}" must export a default function ("export default async function") or "getStaticPaths".`);
|
|
1048
|
+
}
|
|
1049
|
+
const basePattern = relPattern.split(sep2).join("/").replace(/\.html$/, "");
|
|
1050
|
+
const lastSlash = basePattern.lastIndexOf("/");
|
|
1051
|
+
const baseRouteUrl = lastSlash === -1 ? "/" : "/" + basePattern.slice(0, lastSlash);
|
|
1052
|
+
let pathsResult;
|
|
1053
|
+
try {
|
|
1054
|
+
pathsResult = await handler({
|
|
1055
|
+
data: globalData,
|
|
1056
|
+
env: globalData.env || {},
|
|
1057
|
+
paginate: createPaginator(baseRouteUrl)
|
|
1058
|
+
});
|
|
1059
|
+
} catch (err) {
|
|
1060
|
+
logError(`Error executing dynamic loader "${relLoader}"`, err);
|
|
1061
|
+
throw err;
|
|
1062
|
+
}
|
|
1063
|
+
if (!Array.isArray(pathsResult)) {
|
|
1064
|
+
throw new Error(`[Buntic Error]: Dynamic loader "${relLoader}" must return an Array of path objects ({ params, props }). Received: ${typeof pathsResult}.`);
|
|
1065
|
+
}
|
|
1066
|
+
if (pathsResult.length === 0) {
|
|
1067
|
+
logWarn(`Dynamic loader "${relLoader}" returned 0 paths. No pages generated for "${relPattern}".`);
|
|
1068
|
+
return [];
|
|
1069
|
+
}
|
|
1070
|
+
const resolved = [];
|
|
1071
|
+
for (let i = 0;i < pathsResult.length; i++) {
|
|
1072
|
+
const item = pathsResult[i];
|
|
1073
|
+
if (!item || typeof item !== "object" || !item.params || typeof item.params !== "object") {
|
|
1074
|
+
throw new Error(`[Buntic Error]: Item at index ${i} in loader "${relLoader}" must be an object with a "params" property.
|
|
1075
|
+
Received: ${JSON.stringify(item)}`);
|
|
1076
|
+
}
|
|
1077
|
+
const cleanParams = validateRouteParams(tokens, item.params, relLoader);
|
|
1078
|
+
const { urlPath, relOutputPath } = buildCleanUrl(relPattern, cleanParams);
|
|
1079
|
+
const sourceDesc = `${relLoader} (params: ${JSON.stringify(cleanParams)})`;
|
|
1080
|
+
registerRouteOrThrow(urlRegistry, urlPath, sourceDesc);
|
|
1081
|
+
resolved.push({
|
|
1082
|
+
patternRelativePath: relPattern,
|
|
1083
|
+
templateFilePath: templatePath,
|
|
1084
|
+
urlPath,
|
|
1085
|
+
outputFilePath: join6(config.outDir, relOutputPath),
|
|
1086
|
+
params: cleanParams,
|
|
1087
|
+
props: item.props || {},
|
|
1088
|
+
isDynamic: true,
|
|
1089
|
+
seo: item.seo,
|
|
1090
|
+
feed: item.feed
|
|
1091
|
+
});
|
|
1092
|
+
}
|
|
1093
|
+
return resolved;
|
|
1094
|
+
}
|
|
1095
|
+
async function resolveAllRoutes(config, globalData, options) {
|
|
1096
|
+
const htmlFiles = walkFiles(config.pagesDir, {
|
|
1097
|
+
ignoreDotfiles: true,
|
|
1098
|
+
filter: (_abs, entry) => entry.endsWith(".html")
|
|
1099
|
+
});
|
|
1100
|
+
const routes = [];
|
|
1101
|
+
const urlRegistry = new Map;
|
|
1102
|
+
for (const templatePath of htmlFiles) {
|
|
1103
|
+
const relPattern = relative2(config.pagesDir, templatePath);
|
|
1104
|
+
const isDynamic = isDynamicPattern(relPattern);
|
|
1105
|
+
const tokens = extractRouteTokens(relPattern);
|
|
1106
|
+
const loaderPath = findCoLocatedLoader(templatePath);
|
|
1107
|
+
if (!isDynamic) {
|
|
1108
|
+
routes.push(await resolveStaticRoute({
|
|
1109
|
+
config,
|
|
1110
|
+
templatePath,
|
|
1111
|
+
relPattern,
|
|
1112
|
+
loaderPath,
|
|
1113
|
+
globalData,
|
|
1114
|
+
cacheBust: options?.cacheBust,
|
|
1115
|
+
urlRegistry
|
|
1116
|
+
}));
|
|
1117
|
+
} else {
|
|
1118
|
+
routes.push(...await resolveDynamicRoutes({
|
|
1119
|
+
config,
|
|
1120
|
+
templatePath,
|
|
1121
|
+
relPattern,
|
|
1122
|
+
tokens,
|
|
1123
|
+
loaderPath,
|
|
1124
|
+
globalData,
|
|
1125
|
+
cacheBust: options?.cacheBust,
|
|
1126
|
+
urlRegistry
|
|
1127
|
+
}));
|
|
1128
|
+
}
|
|
1129
|
+
}
|
|
1130
|
+
return routes;
|
|
1131
|
+
}
|
|
1132
|
+
|
|
1133
|
+
// src/seo/feeds.ts
|
|
1134
|
+
import { join as join7 } from "path";
|
|
1135
|
+
import { existsSync as existsSync8 } from "fs";
|
|
1136
|
+
function extractFeedEntries(routes, config) {
|
|
1137
|
+
const siteUrl = config.site?.url ? config.site.url.replace(/\/+$/, "") : "";
|
|
1138
|
+
const entries = [];
|
|
1139
|
+
for (const route of routes) {
|
|
1140
|
+
if (route.feed) {
|
|
1141
|
+
const feed = route.feed;
|
|
1142
|
+
const fullUrl = siteUrl ? `${siteUrl}${route.urlPath}` : route.urlPath;
|
|
1143
|
+
let dateObj;
|
|
1144
|
+
if (feed.date instanceof Date) {
|
|
1145
|
+
dateObj = feed.date;
|
|
1146
|
+
} else if (typeof feed.date === "string") {
|
|
1147
|
+
dateObj = new Date(feed.date);
|
|
1148
|
+
} else {
|
|
1149
|
+
dateObj = new Date;
|
|
1150
|
+
}
|
|
1151
|
+
entries.push({
|
|
1152
|
+
title: feed.title,
|
|
1153
|
+
description: feed.description || "",
|
|
1154
|
+
date: isNaN(dateObj.getTime()) ? new Date : dateObj,
|
|
1155
|
+
author: feed.author,
|
|
1156
|
+
url: feed.url || fullUrl
|
|
1157
|
+
});
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
entries.sort((a, b) => b.date.getTime() - a.date.getTime());
|
|
1161
|
+
const limit = config.feeds?.limit || 20;
|
|
1162
|
+
return entries.slice(0, limit);
|
|
1163
|
+
}
|
|
1164
|
+
function generateRss2Xml(routes, config) {
|
|
1165
|
+
if (config.feeds?.rss === false) {
|
|
1166
|
+
return null;
|
|
1167
|
+
}
|
|
1168
|
+
const rssFilename = typeof config.feeds?.rss === "string" ? config.feeds.rss : "rss.xml";
|
|
1169
|
+
const existingInPublic = join7(config.publicDir, rssFilename);
|
|
1170
|
+
if (existsSync8(existingInPublic)) {
|
|
1171
|
+
return null;
|
|
1172
|
+
}
|
|
1173
|
+
const entries = extractFeedEntries(routes, config);
|
|
1174
|
+
if (entries.length === 0 && !config.feeds?.rss) {
|
|
1175
|
+
return null;
|
|
1176
|
+
}
|
|
1177
|
+
const siteUrl = config.site?.url ? config.site.url.replace(/\/+$/, "") : "";
|
|
1178
|
+
const title = config.feeds?.title || config.site?.title || "Feed RSS";
|
|
1179
|
+
const description = config.feeds?.description || config.site?.description || "";
|
|
1180
|
+
const now = new Date().toUTCString();
|
|
1181
|
+
const itemsXml = entries.map((entry) => {
|
|
1182
|
+
return ` <item>
|
|
1183
|
+
<title>${escapeXml(entry.title)}</title>
|
|
1184
|
+
<link>${escapeXml(entry.url)}</link>
|
|
1185
|
+
<guid isPermaLink="true">${escapeXml(entry.url)}</guid>
|
|
1186
|
+
<pubDate>${entry.date.toUTCString()}</pubDate>
|
|
1187
|
+
<description>${escapeXml(entry.description)}</description>${entry.author ? `
|
|
1188
|
+
<author>${escapeXml(entry.author)}</author>` : ""}
|
|
1189
|
+
</item>`;
|
|
1190
|
+
});
|
|
1191
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
1192
|
+
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
|
|
1193
|
+
<channel>
|
|
1194
|
+
<title>${escapeXml(title)}</title>
|
|
1195
|
+
<link>${escapeXml(siteUrl || "/")}</link>
|
|
1196
|
+
<description>${escapeXml(description)}</description>
|
|
1197
|
+
<lastBuildDate>${now}</lastBuildDate>
|
|
1198
|
+
<atom:link href="${escapeXml(siteUrl)}/${escapeXml(rssFilename)}" rel="self" type="application/rss+xml"/>
|
|
1199
|
+
${itemsXml.join(`
|
|
1200
|
+
`)}
|
|
1201
|
+
</channel>
|
|
1202
|
+
</rss>
|
|
1203
|
+
`;
|
|
1204
|
+
}
|
|
1205
|
+
function generateAtomXml(routes, config) {
|
|
1206
|
+
if (config.feeds?.atom === false) {
|
|
1207
|
+
return null;
|
|
1208
|
+
}
|
|
1209
|
+
const atomFilename = typeof config.feeds?.atom === "string" ? config.feeds.atom : "atom.xml";
|
|
1210
|
+
const existingInPublic = join7(config.publicDir, atomFilename);
|
|
1211
|
+
if (existsSync8(existingInPublic)) {
|
|
1212
|
+
return null;
|
|
1213
|
+
}
|
|
1214
|
+
const entries = extractFeedEntries(routes, config);
|
|
1215
|
+
if (entries.length === 0 && !config.feeds?.atom) {
|
|
1216
|
+
return null;
|
|
1217
|
+
}
|
|
1218
|
+
const siteUrl = config.site?.url ? config.site.url.replace(/\/+$/, "") : "";
|
|
1219
|
+
const title = config.feeds?.title || config.site?.title || "Feed Atom";
|
|
1220
|
+
const updated = (entries[0]?.date || new Date).toISOString();
|
|
1221
|
+
const entriesXml = entries.map((entry) => {
|
|
1222
|
+
return ` <entry>
|
|
1223
|
+
<id>${escapeXml(entry.url)}</id>
|
|
1224
|
+
<title>${escapeXml(entry.title)}</title>
|
|
1225
|
+
<link href="${escapeXml(entry.url)}" rel="alternate"/>
|
|
1226
|
+
<updated>${entry.date.toISOString()}</updated>
|
|
1227
|
+
<summary>${escapeXml(entry.description)}</summary>${entry.author ? `
|
|
1228
|
+
<author><name>${escapeXml(entry.author)}</name></author>` : ""}
|
|
1229
|
+
</entry>`;
|
|
1230
|
+
});
|
|
1231
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
1232
|
+
<feed xmlns="http://www.w3.org/2005/Atom">
|
|
1233
|
+
<id>${escapeXml(siteUrl || "/")}</id>
|
|
1234
|
+
<title>${escapeXml(title)}</title>
|
|
1235
|
+
<updated>${updated}</updated>
|
|
1236
|
+
<link href="${escapeXml(siteUrl || "/")}" rel="alternate"/>
|
|
1237
|
+
<link href="${escapeXml(siteUrl)}/${escapeXml(atomFilename)}" rel="self" type="application/atom+xml"/>
|
|
1238
|
+
${entriesXml.join(`
|
|
1239
|
+
`)}
|
|
1240
|
+
</feed>
|
|
1241
|
+
`;
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1244
|
+
// src/seo/metadata.ts
|
|
1245
|
+
import { existsSync as existsSync9, statSync as statSync5 } from "fs";
|
|
1246
|
+
class SeoMetadataEngine {
|
|
1247
|
+
config;
|
|
1248
|
+
imageProcessor;
|
|
1249
|
+
storageManager;
|
|
1250
|
+
emittedAssets = new Map;
|
|
1251
|
+
constructor(config, imageProcessor, storageManager) {
|
|
1252
|
+
this.config = config;
|
|
1253
|
+
this.imageProcessor = imageProcessor || new ImageProcessor(config);
|
|
1254
|
+
this.storageManager = storageManager || new StorageManager(config);
|
|
1255
|
+
}
|
|
1256
|
+
parseSeoTag(html) {
|
|
1257
|
+
const seoRegex = /<seo\b([^>]*?)(?:\/>|>[\s\S]*?<\/seo>|>)/i;
|
|
1258
|
+
const match = seoRegex.exec(html);
|
|
1259
|
+
if (!match) {
|
|
1260
|
+
return { seo: null, cleanHtml: html };
|
|
1261
|
+
}
|
|
1262
|
+
const attrs = parseHtmlAttributes(match[1], "");
|
|
1263
|
+
const cleanHtml = html.replace(match[0], () => "");
|
|
1264
|
+
let imageConfig = attrs.image;
|
|
1265
|
+
if (attrs["image-key"] || attrs.key) {
|
|
1266
|
+
imageConfig = {
|
|
1267
|
+
key: attrs["image-key"] || attrs.key,
|
|
1268
|
+
storage: attrs["image-storage"] || attrs.storage
|
|
1269
|
+
};
|
|
1270
|
+
}
|
|
1271
|
+
const rawCard = attrs["twitter-card"] || attrs.twitterCard;
|
|
1272
|
+
const twitterCard = rawCard === "summary" || rawCard === "summary_large_image" ? rawCard : undefined;
|
|
1273
|
+
const seo = {
|
|
1274
|
+
title: attrs.title,
|
|
1275
|
+
description: attrs.description,
|
|
1276
|
+
image: imageConfig,
|
|
1277
|
+
url: attrs.url,
|
|
1278
|
+
type: attrs.type,
|
|
1279
|
+
twitterCard
|
|
1280
|
+
};
|
|
1281
|
+
return { seo, cleanHtml };
|
|
1282
|
+
}
|
|
1283
|
+
async processSeo(html, options) {
|
|
1284
|
+
const { templatePath, urlPath, routeSeo } = options;
|
|
1285
|
+
const { seo: tagSeo, cleanHtml } = this.parseSeoTag(html);
|
|
1286
|
+
const baseTitle = this.config.site?.title;
|
|
1287
|
+
const baseDescription = this.config.site?.description;
|
|
1288
|
+
const baseImage = this.config.site?.defaultOgImage;
|
|
1289
|
+
const mergedTitle = routeSeo?.title || tagSeo?.title || baseTitle;
|
|
1290
|
+
const mergedDescription = routeSeo?.description || tagSeo?.description || baseDescription;
|
|
1291
|
+
const rawImage = routeSeo?.image || tagSeo?.image || baseImage;
|
|
1292
|
+
const pageType = routeSeo?.type || tagSeo?.type || "website";
|
|
1293
|
+
const twitterCard = routeSeo?.twitterCard || tagSeo?.twitterCard || "summary_large_image";
|
|
1294
|
+
const siteBaseUrl = this.config.site?.url ? this.config.site.url.replace(/\/+$/, "") : "";
|
|
1295
|
+
const canonicalUrl = siteBaseUrl ? `${siteBaseUrl}${urlPath === "/" ? "" : urlPath}` : urlPath;
|
|
1296
|
+
let finalImageUrl;
|
|
1297
|
+
let imgWidth;
|
|
1298
|
+
let imgHeight;
|
|
1299
|
+
if (rawImage) {
|
|
1300
|
+
try {
|
|
1301
|
+
const processed = await this.resolveAndProcessSocialImage(rawImage, templatePath);
|
|
1302
|
+
if (processed) {
|
|
1303
|
+
finalImageUrl = processed.url;
|
|
1304
|
+
imgWidth = processed.width;
|
|
1305
|
+
imgHeight = processed.height;
|
|
1306
|
+
}
|
|
1307
|
+
} catch (err) {
|
|
1308
|
+
logWarn(`Failed to process social image in "${templatePath}": ${getErrorMessage(err)}`, "Buntic SEO Warning");
|
|
1309
|
+
}
|
|
1310
|
+
}
|
|
1311
|
+
const metaTags = this.generateMetaTagsHtml({
|
|
1312
|
+
title: mergedTitle,
|
|
1313
|
+
description: mergedDescription,
|
|
1314
|
+
image: finalImageUrl,
|
|
1315
|
+
imageWidth: imgWidth,
|
|
1316
|
+
imageHeight: imgHeight,
|
|
1317
|
+
url: canonicalUrl,
|
|
1318
|
+
type: pageType,
|
|
1319
|
+
twitterCard
|
|
1320
|
+
});
|
|
1321
|
+
return injectIntoHead(cleanHtml, metaTags, "prepend");
|
|
1322
|
+
}
|
|
1323
|
+
emitSocialVariant(variant, siteBaseUrl) {
|
|
1324
|
+
const outFileName = `assets/seo/${variant.hash}.webp`;
|
|
1325
|
+
const localUrl = `/${outFileName}`;
|
|
1326
|
+
this.emittedAssets.set(localUrl, {
|
|
1327
|
+
outputPath: outFileName,
|
|
1328
|
+
url: localUrl,
|
|
1329
|
+
bytes: variant.bytes
|
|
1330
|
+
});
|
|
1331
|
+
return {
|
|
1332
|
+
url: siteBaseUrl ? `${siteBaseUrl}${localUrl}` : localUrl,
|
|
1333
|
+
width: variant.width,
|
|
1334
|
+
height: variant.height
|
|
1335
|
+
};
|
|
1336
|
+
}
|
|
1337
|
+
async resolveAndProcessSocialImage(imageConfig, templatePath) {
|
|
1338
|
+
const siteBaseUrl = this.config.site?.url ? this.config.site.url.replace(/\/+$/, "") : "";
|
|
1339
|
+
let key;
|
|
1340
|
+
let storage;
|
|
1341
|
+
let src;
|
|
1342
|
+
if (typeof imageConfig === "string") {
|
|
1343
|
+
if (imageConfig.startsWith("http://") || imageConfig.startsWith("https://")) {
|
|
1344
|
+
return { url: imageConfig, width: 1200, height: 630 };
|
|
1345
|
+
}
|
|
1346
|
+
src = imageConfig;
|
|
1347
|
+
} else {
|
|
1348
|
+
key = imageConfig.key;
|
|
1349
|
+
storage = imageConfig.storage;
|
|
1350
|
+
src = imageConfig.src;
|
|
1351
|
+
}
|
|
1352
|
+
if (key) {
|
|
1353
|
+
const asset = await this.storageManager.fetchAsset(key, storage);
|
|
1354
|
+
const storageName = storage || this.storageManager.getDefaultStorageName() || "storage";
|
|
1355
|
+
const variant = await this.imageProcessor.processSocialImage({
|
|
1356
|
+
bytes: asset.bytes,
|
|
1357
|
+
namespace: storageName,
|
|
1358
|
+
keyOrPath: key,
|
|
1359
|
+
etagOrMtime: asset.etag
|
|
1360
|
+
});
|
|
1361
|
+
return this.emitSocialVariant(variant, siteBaseUrl);
|
|
1362
|
+
}
|
|
1363
|
+
if (src) {
|
|
1364
|
+
if (src.startsWith("http://") || src.startsWith("https://")) {
|
|
1365
|
+
return { url: src, width: 1200, height: 630 };
|
|
1366
|
+
}
|
|
1367
|
+
const localPath = resolveLocalAssetPath(this.config, src, templatePath);
|
|
1368
|
+
if (!existsSync9(localPath)) {
|
|
1369
|
+
return null;
|
|
1370
|
+
}
|
|
1371
|
+
const stats = statSync5(localPath);
|
|
1372
|
+
const bytes = await Bun.file(localPath).bytes();
|
|
1373
|
+
const variant = await this.imageProcessor.processSocialImage({
|
|
1374
|
+
bytes,
|
|
1375
|
+
namespace: "local",
|
|
1376
|
+
keyOrPath: localPath,
|
|
1377
|
+
etagOrMtime: `${stats.mtimeMs}-${stats.size}`
|
|
1378
|
+
});
|
|
1379
|
+
return this.emitSocialVariant(variant, siteBaseUrl);
|
|
1380
|
+
}
|
|
1381
|
+
return null;
|
|
1382
|
+
}
|
|
1383
|
+
generateMetaTagsHtml(data) {
|
|
1384
|
+
const lines = [];
|
|
1385
|
+
if (data.title) {
|
|
1386
|
+
lines.push(` <title>${escapeHtml(data.title)}</title>`);
|
|
1387
|
+
lines.push(` <meta property="og:title" content="${escapeHtml(data.title)}">`);
|
|
1388
|
+
lines.push(` <meta name="twitter:title" content="${escapeHtml(data.title)}">`);
|
|
1389
|
+
}
|
|
1390
|
+
if (data.description) {
|
|
1391
|
+
lines.push(` <meta name="description" content="${escapeHtml(data.description)}">`);
|
|
1392
|
+
lines.push(` <meta property="og:description" content="${escapeHtml(data.description)}">`);
|
|
1393
|
+
lines.push(` <meta name="twitter:description" content="${escapeHtml(data.description)}">`);
|
|
1394
|
+
}
|
|
1395
|
+
if (data.url) {
|
|
1396
|
+
lines.push(` <link rel="canonical" href="${escapeHtml(data.url)}">`);
|
|
1397
|
+
lines.push(` <meta property="og:url" content="${escapeHtml(data.url)}">`);
|
|
1398
|
+
}
|
|
1399
|
+
if (data.type) {
|
|
1400
|
+
lines.push(` <meta property="og:type" content="${escapeHtml(data.type)}">`);
|
|
1401
|
+
}
|
|
1402
|
+
if (data.image) {
|
|
1403
|
+
lines.push(` <meta property="og:image" content="${escapeHtml(data.image)}">`);
|
|
1404
|
+
if (data.imageWidth) {
|
|
1405
|
+
lines.push(` <meta property="og:image:width" content="${data.imageWidth}">`);
|
|
1406
|
+
}
|
|
1407
|
+
if (data.imageHeight) {
|
|
1408
|
+
lines.push(` <meta property="og:image:height" content="${data.imageHeight}">`);
|
|
1409
|
+
}
|
|
1410
|
+
lines.push(` <meta name="twitter:image" content="${escapeHtml(data.image)}">`);
|
|
1411
|
+
}
|
|
1412
|
+
if (data.twitterCard) {
|
|
1413
|
+
lines.push(` <meta name="twitter:card" content="${escapeHtml(data.twitterCard)}">`);
|
|
1414
|
+
}
|
|
1415
|
+
return lines.join(`
|
|
1416
|
+
`);
|
|
1417
|
+
}
|
|
1418
|
+
}
|
|
1419
|
+
|
|
1420
|
+
// src/seo/robots.ts
|
|
1421
|
+
import { join as join8 } from "path";
|
|
1422
|
+
import { existsSync as existsSync10 } from "fs";
|
|
1423
|
+
function generateRobotsTxt(config) {
|
|
1424
|
+
if (config.seo?.robots === false) {
|
|
1425
|
+
return null;
|
|
1426
|
+
}
|
|
1427
|
+
const existingInPublic = join8(config.publicDir, "robots.txt");
|
|
1428
|
+
if (existsSync10(existingInPublic)) {
|
|
1429
|
+
return null;
|
|
1430
|
+
}
|
|
1431
|
+
const siteUrl = config.site?.url ? config.site.url.replace(/\/+$/, "") : "";
|
|
1432
|
+
const robotsOpt = typeof config.seo?.robots === "object" ? config.seo.robots : {};
|
|
1433
|
+
const allows = robotsOpt.allow || ["/"];
|
|
1434
|
+
const disallows = robotsOpt.disallow || [];
|
|
1435
|
+
const lines = ["User-agent: *"];
|
|
1436
|
+
for (const allow of allows) {
|
|
1437
|
+
lines.push(`Allow: ${allow}`);
|
|
1438
|
+
}
|
|
1439
|
+
for (const disallow of disallows) {
|
|
1440
|
+
lines.push(`Disallow: ${disallow}`);
|
|
1441
|
+
}
|
|
1442
|
+
if (siteUrl && config.seo?.sitemap !== false) {
|
|
1443
|
+
lines.push("");
|
|
1444
|
+
lines.push(`Sitemap: ${siteUrl}/sitemap.xml`);
|
|
1445
|
+
}
|
|
1446
|
+
lines.push("");
|
|
1447
|
+
return lines.join(`
|
|
1448
|
+
`);
|
|
1449
|
+
}
|
|
1450
|
+
|
|
1451
|
+
// src/seo/sitemap.ts
|
|
1452
|
+
import { join as join9 } from "path";
|
|
1453
|
+
import { existsSync as existsSync11 } from "fs";
|
|
1454
|
+
function generateSitemapXml(routes, config) {
|
|
1455
|
+
if (config.seo?.sitemap === false) {
|
|
1456
|
+
return null;
|
|
1457
|
+
}
|
|
1458
|
+
const existingInPublic = join9(config.publicDir, "sitemap.xml");
|
|
1459
|
+
if (existsSync11(existingInPublic)) {
|
|
1460
|
+
return null;
|
|
1461
|
+
}
|
|
1462
|
+
const siteUrl = config.site?.url ? config.site.url.replace(/\/+$/, "") : "";
|
|
1463
|
+
if (!siteUrl) {
|
|
1464
|
+
return null;
|
|
1465
|
+
}
|
|
1466
|
+
const today = new Date().toISOString().split("T")[0];
|
|
1467
|
+
const urlsXml = routes.map((route) => {
|
|
1468
|
+
const loc = route.urlPath === "/" ? `${siteUrl}/` : `${siteUrl}${route.urlPath}`;
|
|
1469
|
+
const priority = route.urlPath === "/" ? "1.0" : "0.8";
|
|
1470
|
+
return ` <url>
|
|
1471
|
+
<loc>${escapeXml(loc)}</loc>
|
|
1472
|
+
<lastmod>${today}</lastmod>
|
|
1473
|
+
<changefreq>weekly</changefreq>
|
|
1474
|
+
<priority>${priority}</priority>
|
|
1475
|
+
</url>`;
|
|
1476
|
+
});
|
|
1477
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
1478
|
+
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
|
1479
|
+
${urlsXml.join(`
|
|
1480
|
+
`)}
|
|
1481
|
+
</urlset>
|
|
1482
|
+
`;
|
|
1483
|
+
}
|
|
1484
|
+
|
|
1485
|
+
// src/template/engine.ts
|
|
1486
|
+
import { existsSync as existsSync16 } from "fs";
|
|
1487
|
+
import { extname as extname4, relative as relative7 } from "path";
|
|
1488
|
+
|
|
1489
|
+
// src/template/css-graph.ts
|
|
1490
|
+
import { basename as basename4, dirname as dirname6, resolve as resolve4, relative as relative3, join as join11 } from "path";
|
|
1491
|
+
|
|
1492
|
+
// src/template/web-components.ts
|
|
1493
|
+
import { basename as basename3, extname as extname2, dirname as dirname5, join as join10 } from "path";
|
|
1494
|
+
var RESERVED_W3C_TAGS = new Set([
|
|
1495
|
+
"annotation-xml",
|
|
1496
|
+
"color-profile",
|
|
1497
|
+
"font-face",
|
|
1498
|
+
"font-face-src",
|
|
1499
|
+
"font-face-uri",
|
|
1500
|
+
"font-face-format",
|
|
1501
|
+
"font-face-name",
|
|
1502
|
+
"missing-glyph"
|
|
1503
|
+
]);
|
|
1504
|
+
function pascalToKebab(pascal) {
|
|
1505
|
+
return pascal.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
|
|
1506
|
+
}
|
|
1507
|
+
function kebabToPascal(kebab) {
|
|
1508
|
+
return kebab.split("-").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
|
|
1509
|
+
}
|
|
1510
|
+
function filenameToTagName(filePath) {
|
|
1511
|
+
const ext = extname2(filePath);
|
|
1512
|
+
const rawName = basename3(filePath, ext);
|
|
1513
|
+
if (rawName.includes("-")) {
|
|
1514
|
+
return rawName.toLowerCase();
|
|
1515
|
+
}
|
|
1516
|
+
if (/^[A-Z][a-zA-Z0-9]+$/.test(rawName)) {
|
|
1517
|
+
const kebab = pascalToKebab(rawName);
|
|
1518
|
+
if (kebab.includes("-")) {
|
|
1519
|
+
return kebab;
|
|
1520
|
+
}
|
|
1521
|
+
}
|
|
1522
|
+
return null;
|
|
1523
|
+
}
|
|
1524
|
+
|
|
1525
|
+
class WebComponentRegistry {
|
|
1526
|
+
tagToFile = new Map;
|
|
1527
|
+
fileToTags = new Map;
|
|
1528
|
+
conflicts = new Map;
|
|
1529
|
+
usedTags = new Set;
|
|
1530
|
+
validateTagName(tag) {
|
|
1531
|
+
if (!tag.includes("-")) {
|
|
1532
|
+
return { valid: false, reason: `Tag "${tag}" does not contain a hyphen ("-") as required by Custom Elements specification.` };
|
|
1533
|
+
}
|
|
1534
|
+
if (!/^[a-z]/.test(tag)) {
|
|
1535
|
+
return { valid: false, reason: `Tag "${tag}" must start with an ASCII lowercase letter (a-z).` };
|
|
1536
|
+
}
|
|
1537
|
+
if (RESERVED_W3C_TAGS.has(tag.toLowerCase())) {
|
|
1538
|
+
return { valid: false, reason: `Tag "${tag}" is a reserved element name in the W3C specification.` };
|
|
1539
|
+
}
|
|
1540
|
+
return { valid: true };
|
|
1541
|
+
}
|
|
1542
|
+
registerFile(filePath, content) {
|
|
1543
|
+
this.unregisterFile(filePath);
|
|
1544
|
+
const expectedTag = filenameToTagName(filePath);
|
|
1545
|
+
if (!expectedTag) {
|
|
1546
|
+
if (content && /(?:customElements\.define|@customElement)\s*\(\s*["']([a-z0-9-]+)["']/i.test(content)) {
|
|
1547
|
+
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.`);
|
|
1548
|
+
}
|
|
1549
|
+
return [];
|
|
1550
|
+
}
|
|
1551
|
+
const validation = this.validateTagName(expectedTag);
|
|
1552
|
+
if (!validation.valid) {
|
|
1553
|
+
console.warn(`\x1B[33m\u26A0 [Buntic Warning]\x1B[0m Skipping invalid Custom Element tag "${expectedTag}" in ${filePath}: ${validation.reason}`);
|
|
1554
|
+
return [];
|
|
1555
|
+
}
|
|
1556
|
+
if (content) {
|
|
1557
|
+
const defineRegex = /(?:customElements\.define|@customElement)\s*\(\s*["']([a-z0-9-]+)["']/gi;
|
|
1558
|
+
const declaredTags = new Set;
|
|
1559
|
+
let match;
|
|
1560
|
+
while ((match = defineRegex.exec(content)) !== null) {
|
|
1561
|
+
declaredTags.add(match[1].toLowerCase());
|
|
1562
|
+
}
|
|
1563
|
+
if (declaredTags.size > 1) {
|
|
1564
|
+
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.`);
|
|
1565
|
+
return [];
|
|
1566
|
+
}
|
|
1567
|
+
if (declaredTags.size === 1) {
|
|
1568
|
+
const declaredTag = Array.from(declaredTags)[0];
|
|
1569
|
+
if (declaredTag !== expectedTag) {
|
|
1570
|
+
console.warn(`\x1B[33m\u26A0 [Buntic Warning]\x1B[0m Tag "<${declaredTag}>" in "${filePath}" does not match filename. Expected tag "<${expectedTag}>" for file "${basename3(filePath)}". Registration skipped.`);
|
|
1571
|
+
return [];
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
}
|
|
1575
|
+
const existingFile = this.tagToFile.get(expectedTag);
|
|
1576
|
+
if (existingFile && existingFile !== filePath) {
|
|
1577
|
+
const conflictFiles = this.conflicts.get(expectedTag) || [existingFile];
|
|
1578
|
+
if (!conflictFiles.includes(filePath)) {
|
|
1579
|
+
conflictFiles.push(filePath);
|
|
1580
|
+
}
|
|
1581
|
+
this.conflicts.set(expectedTag, conflictFiles);
|
|
1582
|
+
console.warn(`\x1B[33m\u26A0 [Buntic Collision Warning]\x1B[0m Tag "<${expectedTag}>" in ${filePath} conflicts with definition in ${existingFile}.`);
|
|
1583
|
+
return [];
|
|
1584
|
+
}
|
|
1585
|
+
this.tagToFile.set(expectedTag, filePath);
|
|
1586
|
+
this.fileToTags.set(filePath, new Set([expectedTag]));
|
|
1587
|
+
return [expectedTag];
|
|
1588
|
+
}
|
|
1589
|
+
unregisterFile(filePath) {
|
|
1590
|
+
const tags = this.fileToTags.get(filePath) || new Set;
|
|
1591
|
+
for (const [tag, files] of this.conflicts.entries()) {
|
|
1592
|
+
if (files.includes(filePath)) {
|
|
1593
|
+
tags.add(tag);
|
|
1594
|
+
}
|
|
1595
|
+
}
|
|
1596
|
+
for (const tag of tags) {
|
|
1597
|
+
if (this.tagToFile.get(tag) === filePath) {
|
|
1598
|
+
this.tagToFile.delete(tag);
|
|
1599
|
+
}
|
|
1600
|
+
const conflictFiles = this.conflicts.get(tag);
|
|
1601
|
+
if (conflictFiles) {
|
|
1602
|
+
const updated = conflictFiles.filter((f) => f !== filePath);
|
|
1603
|
+
if (updated.length <= 1) {
|
|
1604
|
+
this.conflicts.delete(tag);
|
|
1605
|
+
if (updated.length === 1) {
|
|
1606
|
+
this.tagToFile.set(tag, updated[0]);
|
|
1607
|
+
}
|
|
1608
|
+
} else {
|
|
1609
|
+
this.conflicts.set(tag, updated);
|
|
1610
|
+
}
|
|
1611
|
+
}
|
|
1612
|
+
}
|
|
1613
|
+
this.fileToTags.delete(filePath);
|
|
1614
|
+
}
|
|
1615
|
+
findScriptForTag(tag) {
|
|
1616
|
+
return this.tagToFile.get(tag.toLowerCase());
|
|
1617
|
+
}
|
|
1618
|
+
markTagUsed(tag) {
|
|
1619
|
+
this.usedTags.add(tag.toLowerCase());
|
|
1620
|
+
}
|
|
1621
|
+
clearUsed() {
|
|
1622
|
+
this.usedTags.clear();
|
|
1623
|
+
}
|
|
1624
|
+
getConflicts() {
|
|
1625
|
+
const list = [];
|
|
1626
|
+
for (const [tag, files] of this.conflicts.entries()) {
|
|
1627
|
+
list.push({ tag, files });
|
|
1628
|
+
}
|
|
1629
|
+
return list;
|
|
1630
|
+
}
|
|
1631
|
+
assertNoConflicts() {
|
|
1632
|
+
const conflicts = this.getConflicts();
|
|
1633
|
+
if (conflicts.length > 0) {
|
|
1634
|
+
const details = conflicts.map((c) => ` \u2022 Tag "<${c.tag}>" defined in:
|
|
1635
|
+
${c.files.map((f) => ` - ${f}`).join(`
|
|
1636
|
+
`)}`).join(`
|
|
1637
|
+
|
|
1638
|
+
`);
|
|
1639
|
+
throw new Error(`[Buntic Conflict Error]: Tag collision detected between Web Components:
|
|
1640
|
+
${details}
|
|
1641
|
+
|
|
1642
|
+
` + `\uD83D\uDC49 Each Custom Element tag must be uniquely defined.`);
|
|
1643
|
+
}
|
|
1644
|
+
}
|
|
1645
|
+
getUnusedComponents() {
|
|
1646
|
+
const unused = [];
|
|
1647
|
+
for (const [tag, file] of this.tagToFile.entries()) {
|
|
1648
|
+
if (!this.usedTags.has(tag)) {
|
|
1649
|
+
unused.push({ tag, file });
|
|
1650
|
+
}
|
|
1651
|
+
}
|
|
1652
|
+
return unused;
|
|
1653
|
+
}
|
|
1654
|
+
getTagsForFile(filePath) {
|
|
1655
|
+
const set = this.fileToTags.get(filePath);
|
|
1656
|
+
return set ? Array.from(set) : [];
|
|
1657
|
+
}
|
|
1658
|
+
getAllRegisteredTags() {
|
|
1659
|
+
return Array.from(this.tagToFile.keys());
|
|
1660
|
+
}
|
|
1661
|
+
}
|
|
1662
|
+
function findTriadForScript(scriptPath, existsFn) {
|
|
1663
|
+
const tag = filenameToTagName(scriptPath);
|
|
1664
|
+
if (!tag)
|
|
1665
|
+
return null;
|
|
1666
|
+
const dir = dirname5(scriptPath);
|
|
1667
|
+
const ext = extname2(scriptPath);
|
|
1668
|
+
const rawBase = basename3(scriptPath, ext);
|
|
1669
|
+
const kebabBase = tag;
|
|
1670
|
+
const pascalBase = kebabToPascal(tag);
|
|
1671
|
+
const candidateNames = Array.from(new Set([rawBase, kebabBase, pascalBase]));
|
|
1672
|
+
let htmlPath;
|
|
1673
|
+
for (const name of candidateNames) {
|
|
1674
|
+
const candidate = join10(dir, `${name}.html`);
|
|
1675
|
+
if (existsFn(candidate)) {
|
|
1676
|
+
htmlPath = candidate;
|
|
1677
|
+
break;
|
|
1678
|
+
}
|
|
1679
|
+
}
|
|
1680
|
+
let cssPath;
|
|
1681
|
+
for (const name of candidateNames) {
|
|
1682
|
+
const candidate = join10(dir, `${name}.css`);
|
|
1683
|
+
if (existsFn(candidate)) {
|
|
1684
|
+
cssPath = candidate;
|
|
1685
|
+
break;
|
|
1686
|
+
}
|
|
1687
|
+
}
|
|
1688
|
+
return {
|
|
1689
|
+
tag,
|
|
1690
|
+
scriptPath,
|
|
1691
|
+
htmlPath,
|
|
1692
|
+
cssPath
|
|
1693
|
+
};
|
|
1694
|
+
}
|
|
1695
|
+
|
|
1696
|
+
// src/template/css-graph.ts
|
|
1697
|
+
var LOCAL_IMPORT_REGEX = /@import\s+(?:url\(['"]?|['"])([^'")]+)['"]?\)?\s*;?/gi;
|
|
1698
|
+
|
|
1699
|
+
class CssDependencyGraph {
|
|
1700
|
+
rootDir;
|
|
1701
|
+
nodes = new Map;
|
|
1702
|
+
siblingRoots = new Set;
|
|
1703
|
+
globalRootResult = null;
|
|
1704
|
+
isAnalyzed = false;
|
|
1705
|
+
constructor(rootDir) {
|
|
1706
|
+
this.rootDir = resolve4(rootDir);
|
|
1707
|
+
}
|
|
1708
|
+
invalidate() {
|
|
1709
|
+
this.nodes.clear();
|
|
1710
|
+
this.siblingRoots.clear();
|
|
1711
|
+
this.globalRootResult = null;
|
|
1712
|
+
this.isAnalyzed = false;
|
|
1713
|
+
}
|
|
1714
|
+
async analyze(vfs) {
|
|
1715
|
+
if (this.isAnalyzed)
|
|
1716
|
+
return;
|
|
1717
|
+
this.invalidate();
|
|
1718
|
+
const allFiles = vfs.getAllFiles();
|
|
1719
|
+
const publicDir = join11(this.rootDir, "public");
|
|
1720
|
+
const srcPublicDir = join11(this.rootDir, "src", "public");
|
|
1721
|
+
const cssFiles = [];
|
|
1722
|
+
for (const file of allFiles) {
|
|
1723
|
+
if (!file.endsWith(".css"))
|
|
1724
|
+
continue;
|
|
1725
|
+
if (file.startsWith(publicDir) || file.startsWith(srcPublicDir))
|
|
1726
|
+
continue;
|
|
1727
|
+
cssFiles.push(file);
|
|
1728
|
+
}
|
|
1729
|
+
for (const cssPath of cssFiles) {
|
|
1730
|
+
const isSibling = this.checkIsSiblingRoot(cssPath, vfs);
|
|
1731
|
+
if (isSibling) {
|
|
1732
|
+
this.siblingRoots.add(cssPath);
|
|
1733
|
+
}
|
|
1734
|
+
this.nodes.set(cssPath, {
|
|
1735
|
+
filePath: cssPath,
|
|
1736
|
+
relativeToRoot: relative3(this.rootDir, cssPath).replace(/\\/g, "/"),
|
|
1737
|
+
imports: [],
|
|
1738
|
+
importedBy: new Set,
|
|
1739
|
+
isSiblingRoot: isSibling
|
|
1740
|
+
});
|
|
1741
|
+
}
|
|
1742
|
+
for (const cssPath of cssFiles) {
|
|
1743
|
+
const node = this.nodes.get(cssPath);
|
|
1744
|
+
let content = "";
|
|
1745
|
+
try {
|
|
1746
|
+
content = await vfs.readText(cssPath);
|
|
1747
|
+
} catch {
|
|
1748
|
+
content = await Bun.file(cssPath).text();
|
|
1749
|
+
}
|
|
1750
|
+
const imports = this.extractLocalImports(content, cssPath, vfs);
|
|
1751
|
+
node.imports = imports;
|
|
1752
|
+
for (const imported of imports) {
|
|
1753
|
+
const importedNode = this.nodes.get(imported);
|
|
1754
|
+
if (importedNode) {
|
|
1755
|
+
importedNode.importedBy.add(cssPath);
|
|
1756
|
+
}
|
|
1757
|
+
}
|
|
1758
|
+
}
|
|
1759
|
+
for (const siblingRoot of this.siblingRoots) {
|
|
1760
|
+
const queue = [...this.nodes.get(siblingRoot).imports];
|
|
1761
|
+
const visited = new Set;
|
|
1762
|
+
while (queue.length > 0) {
|
|
1763
|
+
const current = queue.shift();
|
|
1764
|
+
if (visited.has(current))
|
|
1765
|
+
continue;
|
|
1766
|
+
visited.add(current);
|
|
1767
|
+
const node = this.nodes.get(current);
|
|
1768
|
+
if (node) {
|
|
1769
|
+
if (!node.isSiblingRoot) {
|
|
1770
|
+
node.claimedBySibling = siblingRoot;
|
|
1771
|
+
}
|
|
1772
|
+
queue.push(...node.imports);
|
|
1773
|
+
}
|
|
1774
|
+
}
|
|
1775
|
+
}
|
|
1776
|
+
this.globalRootResult = this.calculateGlobalRoot();
|
|
1777
|
+
this.isAnalyzed = true;
|
|
1778
|
+
}
|
|
1779
|
+
getGlobalRoot() {
|
|
1780
|
+
return this.globalRootResult || {
|
|
1781
|
+
root: null,
|
|
1782
|
+
relativeRoot: null,
|
|
1783
|
+
conflicts: [],
|
|
1784
|
+
hasCycle: false
|
|
1785
|
+
};
|
|
1786
|
+
}
|
|
1787
|
+
async flattenCss(entryFilePath, vfs, visited = new Set) {
|
|
1788
|
+
const absPath = resolve4(entryFilePath);
|
|
1789
|
+
if (visited.has(absPath))
|
|
1790
|
+
return "";
|
|
1791
|
+
visited.add(absPath);
|
|
1792
|
+
let rawCss = "";
|
|
1793
|
+
try {
|
|
1794
|
+
rawCss = await vfs.readText(absPath);
|
|
1795
|
+
} catch {
|
|
1796
|
+
rawCss = await Bun.file(absPath).text();
|
|
1797
|
+
}
|
|
1798
|
+
const externalImports = [];
|
|
1799
|
+
const dir = dirname6(absPath);
|
|
1800
|
+
let flattened = rawCss.replace(/@import\s+(?:url\(['"]?|['"])([^'")]+)['"]?\)?\s*;?/gi, (match, href) => {
|
|
1801
|
+
const trimmed = href.trim();
|
|
1802
|
+
if (trimmed.startsWith("http://") || trimmed.startsWith("https://") || trimmed.startsWith("//")) {
|
|
1803
|
+
externalImports.push(match.trim());
|
|
1804
|
+
return "";
|
|
1805
|
+
}
|
|
1806
|
+
const candidate = trimmed.startsWith("/") ? join11(this.rootDir, trimmed.slice(1)) : resolve4(dir, trimmed);
|
|
1807
|
+
let resolvedTarget = candidate;
|
|
1808
|
+
if (!vfs.hasFile(resolvedTarget) && vfs.hasFile(`${candidate}.css`)) {
|
|
1809
|
+
resolvedTarget = `${candidate}.css`;
|
|
1810
|
+
}
|
|
1811
|
+
return `/* __BUST_IMPORT__:${resolvedTarget} */`;
|
|
1812
|
+
});
|
|
1813
|
+
const placeholderRegex = /\/\* __BUST_IMPORT__:(.*?) \*\//g;
|
|
1814
|
+
let match;
|
|
1815
|
+
const placeholders = [];
|
|
1816
|
+
while ((match = placeholderRegex.exec(flattened)) !== null) {
|
|
1817
|
+
placeholders.push({ full: match[0], path: match[1] });
|
|
1818
|
+
}
|
|
1819
|
+
for (const item of placeholders) {
|
|
1820
|
+
if (vfs.hasFile(item.path)) {
|
|
1821
|
+
const childCss = await this.flattenCss(item.path, vfs, visited);
|
|
1822
|
+
flattened = flattened.replace(item.full, () => childCss.trim());
|
|
1823
|
+
} else {
|
|
1824
|
+
flattened = flattened.replace(item.full, () => "");
|
|
1825
|
+
}
|
|
1826
|
+
}
|
|
1827
|
+
const header = externalImports.length > 0 ? `${externalImports.join(`
|
|
1828
|
+
`)}
|
|
1829
|
+
|
|
1830
|
+
` : "";
|
|
1831
|
+
return `${header}${flattened.trim()}`;
|
|
1832
|
+
}
|
|
1833
|
+
checkIsSiblingRoot(cssPath, vfs) {
|
|
1834
|
+
const dir = dirname6(cssPath);
|
|
1835
|
+
const rawBase = basename4(cssPath, ".css");
|
|
1836
|
+
const extensions = [".html", ".svg", ".ts", ".js", ".tsx", ".jsx"];
|
|
1837
|
+
for (const ext of extensions) {
|
|
1838
|
+
if (vfs.hasFile(join11(dir, `${rawBase}${ext}`))) {
|
|
1839
|
+
return true;
|
|
1840
|
+
}
|
|
1841
|
+
}
|
|
1842
|
+
if (rawBase.includes("-")) {
|
|
1843
|
+
const pascal = kebabToPascal(rawBase);
|
|
1844
|
+
for (const ext of extensions) {
|
|
1845
|
+
if (vfs.hasFile(join11(dir, `${pascal}${ext}`))) {
|
|
1846
|
+
return true;
|
|
1847
|
+
}
|
|
1848
|
+
}
|
|
1849
|
+
}
|
|
1850
|
+
if (/^[A-Z][a-zA-Z0-9]+$/.test(rawBase)) {
|
|
1851
|
+
const kebab = pascalToKebab(rawBase);
|
|
1852
|
+
for (const ext of extensions) {
|
|
1853
|
+
if (vfs.hasFile(join11(dir, `${kebab}${ext}`))) {
|
|
1854
|
+
return true;
|
|
1855
|
+
}
|
|
1856
|
+
}
|
|
1857
|
+
}
|
|
1858
|
+
return false;
|
|
1859
|
+
}
|
|
1860
|
+
extractLocalImports(content, currentCssPath, vfs) {
|
|
1861
|
+
const imports = [];
|
|
1862
|
+
const dir = dirname6(currentCssPath);
|
|
1863
|
+
const regex = new RegExp(LOCAL_IMPORT_REGEX);
|
|
1864
|
+
let match;
|
|
1865
|
+
while ((match = regex.exec(content)) !== null) {
|
|
1866
|
+
const href = match[1].trim();
|
|
1867
|
+
if (href.startsWith("http://") || href.startsWith("https://") || href.startsWith("//")) {
|
|
1868
|
+
continue;
|
|
1869
|
+
}
|
|
1870
|
+
let candidate = href.startsWith("/") ? join11(this.rootDir, href.slice(1)) : resolve4(dir, href);
|
|
1871
|
+
if (!vfs.hasFile(candidate) && vfs.hasFile(`${candidate}.css`)) {
|
|
1872
|
+
candidate = `${candidate}.css`;
|
|
1873
|
+
}
|
|
1874
|
+
if (vfs.hasFile(candidate)) {
|
|
1875
|
+
imports.push(candidate);
|
|
1876
|
+
}
|
|
1877
|
+
}
|
|
1878
|
+
return imports;
|
|
1879
|
+
}
|
|
1880
|
+
calculateGlobalRoot() {
|
|
1881
|
+
const candidatePaths = new Set;
|
|
1882
|
+
for (const [path, node] of this.nodes.entries()) {
|
|
1883
|
+
if (!node.isSiblingRoot && !node.claimedBySibling) {
|
|
1884
|
+
candidatePaths.add(path);
|
|
1885
|
+
}
|
|
1886
|
+
}
|
|
1887
|
+
if (candidatePaths.size === 0) {
|
|
1888
|
+
return { root: null, relativeRoot: null, conflicts: [], hasCycle: false };
|
|
1889
|
+
}
|
|
1890
|
+
const zeroInDegree = [];
|
|
1891
|
+
for (const path of candidatePaths) {
|
|
1892
|
+
const node = this.nodes.get(path);
|
|
1893
|
+
let inDegree = 0;
|
|
1894
|
+
for (const importedBy of node.importedBy) {
|
|
1895
|
+
if (candidatePaths.has(importedBy)) {
|
|
1896
|
+
inDegree++;
|
|
1897
|
+
}
|
|
1898
|
+
}
|
|
1899
|
+
if (inDegree === 0) {
|
|
1900
|
+
zeroInDegree.push(path);
|
|
1901
|
+
}
|
|
1902
|
+
}
|
|
1903
|
+
if (zeroInDegree.length === 1) {
|
|
1904
|
+
const root = zeroInDegree[0];
|
|
1905
|
+
return {
|
|
1906
|
+
root,
|
|
1907
|
+
relativeRoot: relative3(this.rootDir, root).replace(/\\/g, "/"),
|
|
1908
|
+
conflicts: [],
|
|
1909
|
+
hasCycle: false
|
|
1910
|
+
};
|
|
1911
|
+
}
|
|
1912
|
+
if (zeroInDegree.length > 1) {
|
|
1913
|
+
return {
|
|
1914
|
+
root: null,
|
|
1915
|
+
relativeRoot: null,
|
|
1916
|
+
conflicts: zeroInDegree,
|
|
1917
|
+
hasCycle: false
|
|
1918
|
+
};
|
|
1919
|
+
}
|
|
1920
|
+
return {
|
|
1921
|
+
root: null,
|
|
1922
|
+
relativeRoot: null,
|
|
1923
|
+
conflicts: [],
|
|
1924
|
+
hasCycle: true
|
|
1925
|
+
};
|
|
1926
|
+
}
|
|
1927
|
+
}
|
|
1928
|
+
|
|
1929
|
+
// src/template/css-resolver.ts
|
|
1930
|
+
import { existsSync as existsSync12 } from "fs";
|
|
1931
|
+
import { dirname as dirname7, join as join12, relative as relative4, resolve as resolve5 } from "path";
|
|
1932
|
+
|
|
1933
|
+
// src/template/css-scoper.ts
|
|
1934
|
+
function transformScopedCss(css, scopeTarget, isElement = false) {
|
|
1935
|
+
const targetClass = isElement ? scopeTarget : scopeTarget.startsWith(".") ? scopeTarget : `.${scopeTarget}`;
|
|
1936
|
+
const cleanCss = css.trim().replace(/\r\n/g, `
|
|
1937
|
+
`);
|
|
1938
|
+
const transformedRules = [];
|
|
1939
|
+
const blocks = splitCssBlocks(cleanCss);
|
|
1940
|
+
for (const block of blocks) {
|
|
1941
|
+
if (block.type === "at-rule-nested") {
|
|
1942
|
+
const innerTransformed = transformScopedCss(block.body, scopeTarget, isElement);
|
|
1943
|
+
transformedRules.push(`${block.header} {
|
|
1944
|
+
${indent(innerTransformed, " ")}
|
|
1945
|
+
}`);
|
|
1946
|
+
} else if (block.type === "at-rule-leaf") {
|
|
1947
|
+
transformedRules.push(block.raw);
|
|
1948
|
+
} else if (block.type === "rule") {
|
|
1949
|
+
const scopedSelector = scopeSelectorList(block.selector, targetClass);
|
|
1950
|
+
transformedRules.push(`${scopedSelector} {
|
|
1951
|
+
${block.body}
|
|
1952
|
+
}`);
|
|
1953
|
+
}
|
|
1954
|
+
}
|
|
1955
|
+
return transformedRules.join(`
|
|
1956
|
+
|
|
1957
|
+
`);
|
|
1958
|
+
}
|
|
1959
|
+
function scopeSelectorList(selectorList, targetClass) {
|
|
1960
|
+
return splitSelectorList(selectorList).map((s) => scopeSingleSelector(s.trim(), targetClass)).filter(Boolean).join(", ");
|
|
1961
|
+
}
|
|
1962
|
+
function scopeSingleSelector(selector, targetClass) {
|
|
1963
|
+
if (!selector)
|
|
1964
|
+
return "";
|
|
1965
|
+
if (selector.includes("&") || selector.includes(":host")) {
|
|
1966
|
+
return selector.replace(/&/g, () => targetClass).replace(/:host\b/g, () => targetClass);
|
|
1967
|
+
}
|
|
1968
|
+
if (/^[>+~]/.test(selector)) {
|
|
1969
|
+
return `${targetClass} ${selector}`.replace(/\s+/g, " ");
|
|
1970
|
+
}
|
|
1971
|
+
return `${targetClass} ${selector}`;
|
|
1972
|
+
}
|
|
1973
|
+
function splitSelectorList(selectors) {
|
|
1974
|
+
const result = [];
|
|
1975
|
+
let current = "";
|
|
1976
|
+
let parenDepth = 0;
|
|
1977
|
+
for (let i = 0;i < selectors.length; i++) {
|
|
1978
|
+
const ch = selectors[i];
|
|
1979
|
+
if (ch === "(")
|
|
1980
|
+
parenDepth++;
|
|
1981
|
+
else if (ch === ")")
|
|
1982
|
+
parenDepth = Math.max(0, parenDepth - 1);
|
|
1983
|
+
if (ch === "," && parenDepth === 0) {
|
|
1984
|
+
result.push(current.trim());
|
|
1985
|
+
current = "";
|
|
1986
|
+
} else {
|
|
1987
|
+
current += ch;
|
|
1988
|
+
}
|
|
1989
|
+
}
|
|
1990
|
+
if (current.trim()) {
|
|
1991
|
+
result.push(current.trim());
|
|
1992
|
+
}
|
|
1993
|
+
return result;
|
|
1994
|
+
}
|
|
1995
|
+
function splitCssBlocks(css) {
|
|
1996
|
+
const blocks = [];
|
|
1997
|
+
let i = 0;
|
|
1998
|
+
const len = css.length;
|
|
1999
|
+
while (i < len) {
|
|
2000
|
+
while (i < len && /\s/.test(css[i]))
|
|
2001
|
+
i++;
|
|
2002
|
+
if (i >= len)
|
|
2003
|
+
break;
|
|
2004
|
+
if (css[i] === "/" && css[i + 1] === "*") {
|
|
2005
|
+
const commentEnd = css.indexOf("*/", i + 2);
|
|
2006
|
+
i = commentEnd === -1 ? len : commentEnd + 2;
|
|
2007
|
+
continue;
|
|
2008
|
+
}
|
|
2009
|
+
const headerStart = i;
|
|
2010
|
+
let braceIndex = -1;
|
|
2011
|
+
let semiIndex = -1;
|
|
2012
|
+
for (let j = i;j < len; j++) {
|
|
2013
|
+
if (css[j] === "/" && css[j + 1] === "*") {
|
|
2014
|
+
const cEnd = css.indexOf("*/", j + 2);
|
|
2015
|
+
j = cEnd === -1 ? len - 1 : cEnd + 1;
|
|
2016
|
+
continue;
|
|
2017
|
+
}
|
|
2018
|
+
if (css[j] === "{") {
|
|
2019
|
+
braceIndex = j;
|
|
2020
|
+
break;
|
|
2021
|
+
}
|
|
2022
|
+
if (css[j] === ";" && css.slice(headerStart, j).trim().startsWith("@")) {
|
|
2023
|
+
semiIndex = j;
|
|
2024
|
+
break;
|
|
2025
|
+
}
|
|
2026
|
+
}
|
|
2027
|
+
if (braceIndex === -1 && semiIndex !== -1) {
|
|
2028
|
+
const raw = css.slice(headerStart, semiIndex + 1).trim();
|
|
2029
|
+
blocks.push({
|
|
2030
|
+
type: "at-rule-leaf",
|
|
2031
|
+
header: raw,
|
|
2032
|
+
selector: "",
|
|
2033
|
+
body: "",
|
|
2034
|
+
raw
|
|
2035
|
+
});
|
|
2036
|
+
i = semiIndex + 1;
|
|
2037
|
+
continue;
|
|
2038
|
+
}
|
|
2039
|
+
if (braceIndex === -1) {
|
|
2040
|
+
break;
|
|
2041
|
+
}
|
|
2042
|
+
const header = css.slice(headerStart, braceIndex).trim();
|
|
2043
|
+
let depth = 1;
|
|
2044
|
+
const bodyStart = braceIndex + 1;
|
|
2045
|
+
let bodyEnd = -1;
|
|
2046
|
+
for (let j = bodyStart;j < len; j++) {
|
|
2047
|
+
if (css[j] === "/" && css[j + 1] === "*") {
|
|
2048
|
+
const cEnd = css.indexOf("*/", j + 2);
|
|
2049
|
+
j = cEnd === -1 ? len - 1 : cEnd + 1;
|
|
2050
|
+
continue;
|
|
2051
|
+
}
|
|
2052
|
+
if (css[j] === "{") {
|
|
2053
|
+
depth++;
|
|
2054
|
+
} else if (css[j] === "}") {
|
|
2055
|
+
depth--;
|
|
2056
|
+
if (depth === 0) {
|
|
2057
|
+
bodyEnd = j;
|
|
2058
|
+
break;
|
|
2059
|
+
}
|
|
2060
|
+
}
|
|
2061
|
+
}
|
|
2062
|
+
if (bodyEnd === -1) {
|
|
2063
|
+
bodyEnd = len;
|
|
2064
|
+
}
|
|
2065
|
+
const body = css.slice(bodyStart, bodyEnd).trim();
|
|
2066
|
+
const raw = css.slice(headerStart, bodyEnd + 1).trim();
|
|
2067
|
+
if (header.startsWith("@")) {
|
|
2068
|
+
const lower = header.toLowerCase();
|
|
2069
|
+
const isNested = lower.startsWith("@media") || lower.startsWith("@supports") || lower.startsWith("@container");
|
|
2070
|
+
blocks.push({
|
|
2071
|
+
type: isNested ? "at-rule-nested" : "at-rule-leaf",
|
|
2072
|
+
header,
|
|
2073
|
+
selector: "",
|
|
2074
|
+
body,
|
|
2075
|
+
raw
|
|
2076
|
+
});
|
|
2077
|
+
} else {
|
|
2078
|
+
blocks.push({
|
|
2079
|
+
type: "rule",
|
|
2080
|
+
header,
|
|
2081
|
+
selector: header,
|
|
2082
|
+
body,
|
|
2083
|
+
raw
|
|
2084
|
+
});
|
|
2085
|
+
}
|
|
2086
|
+
i = bodyEnd + 1;
|
|
2087
|
+
}
|
|
2088
|
+
return blocks;
|
|
2089
|
+
}
|
|
2090
|
+
function indent(text, spaces) {
|
|
2091
|
+
return text.split(`
|
|
2092
|
+
`).map((line) => line.trim() ? spaces + line : line).join(`
|
|
2093
|
+
`);
|
|
2094
|
+
}
|
|
2095
|
+
|
|
2096
|
+
// src/template/html-scanner.ts
|
|
2097
|
+
var VOID_ELEMENTS = new Set([
|
|
2098
|
+
"area",
|
|
2099
|
+
"base",
|
|
2100
|
+
"br",
|
|
2101
|
+
"col",
|
|
2102
|
+
"embed",
|
|
2103
|
+
"hr",
|
|
2104
|
+
"img",
|
|
2105
|
+
"input",
|
|
2106
|
+
"link",
|
|
2107
|
+
"meta",
|
|
2108
|
+
"param",
|
|
2109
|
+
"source",
|
|
2110
|
+
"track",
|
|
2111
|
+
"wbr"
|
|
2112
|
+
]);
|
|
2113
|
+
function createHtmlTagRegex() {
|
|
2114
|
+
return /<!--[\s\S]*?-->|<\?xml[\s\S]*?\?>|<!doctype[^>]*>|<script\b(?:[^>"']|"[^"]*"|'[^']*')*>[\s\S]*?<\/script>|<style\b(?:[^>"']|"[^"]*"|'[^']*')*>[\s\S]*?<\/style>|<\/([a-zA-Z0-9_:-]+)\s*>|<([a-zA-Z0-9_:-]+)((?:\s+[^\s"'<>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|(?:\x2f(?!>)|[^\s"'=<>`\/])+))?)*)\s*(\/?)>/gi;
|
|
2115
|
+
}
|
|
2116
|
+
function findSingleRootElement(html) {
|
|
2117
|
+
const tagRegex = createHtmlTagRegex();
|
|
2118
|
+
let match;
|
|
2119
|
+
let firstRoot = null;
|
|
2120
|
+
let depth = 0;
|
|
2121
|
+
let lastIndexChecked = 0;
|
|
2122
|
+
let rootClosedIndex = -1;
|
|
2123
|
+
while ((match = tagRegex.exec(html)) !== null) {
|
|
2124
|
+
const fullMatch = match[0];
|
|
2125
|
+
const matchStart = match.index;
|
|
2126
|
+
const matchEnd = matchStart + fullMatch.length;
|
|
2127
|
+
if (depth === 0) {
|
|
2128
|
+
const textBefore = html.slice(lastIndexChecked, matchStart).trim();
|
|
2129
|
+
if (textBefore.length > 0) {
|
|
2130
|
+
return null;
|
|
2131
|
+
}
|
|
2132
|
+
}
|
|
2133
|
+
lastIndexChecked = matchEnd;
|
|
2134
|
+
if (fullMatch.startsWith("<!--") || fullMatch.startsWith("<?xml") || /^<!doctype\b/i.test(fullMatch)) {
|
|
2135
|
+
continue;
|
|
2136
|
+
}
|
|
2137
|
+
if (/^<(?:script|style)\b/i.test(fullMatch)) {
|
|
2138
|
+
if (depth === 0) {
|
|
2139
|
+
return null;
|
|
2140
|
+
}
|
|
2141
|
+
continue;
|
|
2142
|
+
}
|
|
2143
|
+
const closingTag = match[1];
|
|
2144
|
+
const openingTag = match[2];
|
|
2145
|
+
const isSelfClosing = match[4] === "/";
|
|
2146
|
+
if (openingTag) {
|
|
2147
|
+
const lower = openingTag.toLowerCase();
|
|
2148
|
+
const isVoid = VOID_ELEMENTS.has(lower);
|
|
2149
|
+
if (depth === 0) {
|
|
2150
|
+
if (firstRoot !== null || isVoid || isSelfClosing) {
|
|
2151
|
+
return null;
|
|
2152
|
+
}
|
|
2153
|
+
firstRoot = {
|
|
2154
|
+
tag: openingTag,
|
|
2155
|
+
openTagStart: matchStart,
|
|
2156
|
+
openTagEnd: matchEnd,
|
|
2157
|
+
openTagRaw: fullMatch
|
|
2158
|
+
};
|
|
2159
|
+
depth = 1;
|
|
2160
|
+
} else if (!isVoid && !isSelfClosing) {
|
|
2161
|
+
depth++;
|
|
2162
|
+
}
|
|
2163
|
+
} else if (closingTag && depth > 0) {
|
|
2164
|
+
depth--;
|
|
2165
|
+
if (depth === 0) {
|
|
2166
|
+
rootClosedIndex = matchEnd;
|
|
2167
|
+
}
|
|
2168
|
+
}
|
|
2169
|
+
}
|
|
2170
|
+
if (depth !== 0 || !firstRoot || rootClosedIndex === -1) {
|
|
2171
|
+
return null;
|
|
2172
|
+
}
|
|
2173
|
+
const trailingText = html.slice(rootClosedIndex).trim();
|
|
2174
|
+
const trailingWithoutComments = trailingText.replace(/<!--[\s\S]*?-->/g, "").trim();
|
|
2175
|
+
if (trailingWithoutComments.length > 0) {
|
|
2176
|
+
return null;
|
|
2177
|
+
}
|
|
2178
|
+
return firstRoot;
|
|
2179
|
+
}
|
|
2180
|
+
function findParentTagOfScopedStyle(html, styleStartIdx) {
|
|
2181
|
+
const textBefore = html.slice(0, styleStartIdx);
|
|
2182
|
+
const stack = [];
|
|
2183
|
+
const tagRegex = createHtmlTagRegex();
|
|
2184
|
+
let match;
|
|
2185
|
+
while ((match = tagRegex.exec(textBefore)) !== null) {
|
|
2186
|
+
const fullTag = match[0];
|
|
2187
|
+
if (fullTag.startsWith("<!--") || fullTag.startsWith("<?xml") || /^<!doctype\b/i.test(fullTag) || /^<(?:script|style)\b/i.test(fullTag)) {
|
|
2188
|
+
continue;
|
|
2189
|
+
}
|
|
2190
|
+
const closingTag = match[1];
|
|
2191
|
+
const openingTag = match[2];
|
|
2192
|
+
const isSelfClosing = match[4] === "/";
|
|
2193
|
+
if (closingTag) {
|
|
2194
|
+
const lower = closingTag.toLowerCase();
|
|
2195
|
+
for (let s = stack.length - 1;s >= 0; s--) {
|
|
2196
|
+
if (stack[s].tag.toLowerCase() === lower) {
|
|
2197
|
+
stack.splice(s);
|
|
2198
|
+
break;
|
|
2199
|
+
}
|
|
2200
|
+
}
|
|
2201
|
+
} else if (openingTag) {
|
|
2202
|
+
const lower = openingTag.toLowerCase();
|
|
2203
|
+
if (!VOID_ELEMENTS.has(lower) && !isSelfClosing) {
|
|
2204
|
+
stack.push({
|
|
2205
|
+
tag: openingTag,
|
|
2206
|
+
start: match.index,
|
|
2207
|
+
end: match.index + fullTag.length,
|
|
2208
|
+
raw: fullTag,
|
|
2209
|
+
depth: stack.length + 1
|
|
2210
|
+
});
|
|
2211
|
+
}
|
|
2212
|
+
}
|
|
2213
|
+
}
|
|
2214
|
+
return stack.length > 0 ? stack[stack.length - 1] : null;
|
|
2215
|
+
}
|
|
2216
|
+
function addClassToOpenTag(openTag, newClass) {
|
|
2217
|
+
const classMatch = openTag.match(/class=(["'])(.*?)\1/i);
|
|
2218
|
+
if (classMatch) {
|
|
2219
|
+
const quote = classMatch[1];
|
|
2220
|
+
const existingClasses = classMatch[2].trim();
|
|
2221
|
+
if (existingClasses.split(/\s+/).includes(newClass)) {
|
|
2222
|
+
return openTag;
|
|
2223
|
+
}
|
|
2224
|
+
const updated = existingClasses ? `${existingClasses} ${newClass}` : newClass;
|
|
2225
|
+
return openTag.replace(classMatch[0], () => `class=${quote}${updated}${quote}`);
|
|
2226
|
+
}
|
|
2227
|
+
if (openTag.endsWith("/>")) {
|
|
2228
|
+
return openTag.slice(0, -2).trimEnd() + ` class="${newClass}"/>`;
|
|
2229
|
+
}
|
|
2230
|
+
return openTag.slice(0, -1).trimEnd() + ` class="${newClass}">`;
|
|
2231
|
+
}
|
|
2232
|
+
|
|
2233
|
+
// src/template/scoped-css.ts
|
|
2234
|
+
function attachSiblingScopedCss(html, cssContent) {
|
|
2235
|
+
const root = findSingleRootElement(html);
|
|
2236
|
+
if (!root)
|
|
2237
|
+
return null;
|
|
2238
|
+
const styleTag = `
|
|
2239
|
+
<style scoped>
|
|
2240
|
+
${cssContent}
|
|
2241
|
+
</style>`;
|
|
2242
|
+
return html.slice(0, root.openTagEnd) + styleTag + html.slice(root.openTagEnd);
|
|
2243
|
+
}
|
|
2244
|
+
|
|
2245
|
+
class ScopeRegistry {
|
|
2246
|
+
registry = new Map;
|
|
2247
|
+
getScopeId(cssContent) {
|
|
2248
|
+
const normalized = cssContent.trim().replace(/\r\n/g, `
|
|
2249
|
+
`);
|
|
2250
|
+
const hashNum = Bun.hash(normalized);
|
|
2251
|
+
const baseHash = "bs-" + (typeof hashNum === "bigint" ? hashNum.toString(36) : Number(hashNum).toString(36)).slice(0, 7);
|
|
2252
|
+
let candidate = baseHash;
|
|
2253
|
+
let counter = 1;
|
|
2254
|
+
while (this.registry.has(candidate)) {
|
|
2255
|
+
if (this.registry.get(candidate) === normalized) {
|
|
2256
|
+
return candidate;
|
|
2257
|
+
}
|
|
2258
|
+
candidate = `${baseHash}-${counter++}`;
|
|
2259
|
+
}
|
|
2260
|
+
this.registry.set(candidate, normalized);
|
|
2261
|
+
return candidate;
|
|
2262
|
+
}
|
|
2263
|
+
clear() {
|
|
2264
|
+
this.registry.clear();
|
|
2265
|
+
}
|
|
2266
|
+
}
|
|
2267
|
+
function extractScopedStyles(html, registry = new ScopeRegistry) {
|
|
2268
|
+
let currentHtml = html;
|
|
2269
|
+
const ruleEntries = new Map;
|
|
2270
|
+
let orderCounter = 0;
|
|
2271
|
+
const scopedTagRegex = /<style\b(?=[^>]*\s+scoped(?=[\s=>]))[^>]*>([\s\S]*?)<\/style>/i;
|
|
2272
|
+
let match;
|
|
2273
|
+
while ((match = scopedTagRegex.exec(currentHtml)) !== null) {
|
|
2274
|
+
const fullStyleBlock = match[0];
|
|
2275
|
+
const cssContent = match[1];
|
|
2276
|
+
const styleStartIndex = match.index;
|
|
2277
|
+
const parent = findParentTagOfScopedStyle(currentHtml, styleStartIndex);
|
|
2278
|
+
const depth = parent ? parent.depth : 0;
|
|
2279
|
+
const scopeClass = registry.getScopeId(cssContent);
|
|
2280
|
+
if (parent) {
|
|
2281
|
+
const updatedParentTag = addClassToOpenTag(parent.raw, scopeClass);
|
|
2282
|
+
const beforeParent = currentHtml.slice(0, parent.start);
|
|
2283
|
+
const afterParentStart = currentHtml.slice(parent.end, styleStartIndex);
|
|
2284
|
+
const afterStyle = currentHtml.slice(styleStartIndex + fullStyleBlock.length);
|
|
2285
|
+
currentHtml = beforeParent + updatedParentTag + afterParentStart + afterStyle;
|
|
2286
|
+
} else {
|
|
2287
|
+
currentHtml = currentHtml.slice(0, styleStartIndex) + currentHtml.slice(styleStartIndex + fullStyleBlock.length);
|
|
2288
|
+
}
|
|
2289
|
+
const existing = ruleEntries.get(scopeClass);
|
|
2290
|
+
if (!existing) {
|
|
2291
|
+
const transformedCss = transformScopedCss(cssContent, scopeClass);
|
|
2292
|
+
if (transformedCss.trim()) {
|
|
2293
|
+
ruleEntries.set(scopeClass, {
|
|
2294
|
+
css: transformedCss,
|
|
2295
|
+
depth,
|
|
2296
|
+
order: orderCounter++
|
|
2297
|
+
});
|
|
2298
|
+
}
|
|
2299
|
+
} else if (depth > existing.depth) {
|
|
2300
|
+
existing.depth = depth;
|
|
2301
|
+
}
|
|
2302
|
+
}
|
|
2303
|
+
const scopedRules = Array.from(ruleEntries.values()).sort((a, b) => a.depth - b.depth || a.order - b.order).map((entry) => entry.css);
|
|
2304
|
+
return {
|
|
2305
|
+
html: currentHtml,
|
|
2306
|
+
scopedRules
|
|
2307
|
+
};
|
|
2308
|
+
}
|
|
2309
|
+
|
|
2310
|
+
// src/template/css-resolver.ts
|
|
2311
|
+
async function resolvePageCss(options) {
|
|
2312
|
+
const {
|
|
2313
|
+
html,
|
|
2314
|
+
currentFile,
|
|
2315
|
+
extraScopedRules = [],
|
|
2316
|
+
config,
|
|
2317
|
+
vfs,
|
|
2318
|
+
cssGraph,
|
|
2319
|
+
scopeRegistry,
|
|
2320
|
+
generatedPageStyles
|
|
2321
|
+
} = options;
|
|
2322
|
+
const { html: cleanHtml, scopedRules } = extractScopedStyles(html, scopeRegistry);
|
|
2323
|
+
let result = cleanHtml;
|
|
2324
|
+
const allScopedRules = [...scopedRules, ...extraScopedRules];
|
|
2325
|
+
const hasScopedRules = allScopedRules.length > 0;
|
|
2326
|
+
const scopedCssText = hasScopedRules ? allScopedRules.join(`
|
|
2327
|
+
|
|
2328
|
+
`) : "";
|
|
2329
|
+
const globalRoot = cssGraph.getGlobalRoot();
|
|
2330
|
+
let globalCssContent = null;
|
|
2331
|
+
if (globalRoot.root) {
|
|
2332
|
+
globalCssContent = await cssGraph.flattenCss(globalRoot.root, vfs);
|
|
2333
|
+
}
|
|
2334
|
+
if (config.cssStrategy === "inline") {
|
|
2335
|
+
const linkRegex = /<link\s+[^>]*rel=["']stylesheet["'][^>]*>/gi;
|
|
2336
|
+
const links = Array.from(result.matchAll(linkRegex));
|
|
2337
|
+
let hadManualGlobalLink = false;
|
|
2338
|
+
for (const m of links) {
|
|
2339
|
+
const fullTag = m[0];
|
|
2340
|
+
const hrefMatch = fullTag.match(/href=["']([^"']+)["']/i);
|
|
2341
|
+
if (!hrefMatch)
|
|
2342
|
+
continue;
|
|
2343
|
+
const href = hrefMatch[1];
|
|
2344
|
+
if (href.startsWith("http://") || href.startsWith("https://") || href.startsWith("//")) {
|
|
2345
|
+
continue;
|
|
2346
|
+
}
|
|
2347
|
+
let cssFilePath = "";
|
|
2348
|
+
if (href.startsWith("/")) {
|
|
2349
|
+
const direct = join12(config.root, href.slice(1));
|
|
2350
|
+
const inSrc = join12(config.root, "src", href.slice(1));
|
|
2351
|
+
if (vfs.hasFile(direct) || existsSync12(direct)) {
|
|
2352
|
+
cssFilePath = direct;
|
|
2353
|
+
} else if (vfs.hasFile(inSrc) || existsSync12(inSrc)) {
|
|
2354
|
+
cssFilePath = inSrc;
|
|
2355
|
+
} else {
|
|
2356
|
+
cssFilePath = direct;
|
|
2357
|
+
}
|
|
2358
|
+
} else {
|
|
2359
|
+
const fromDir = currentFile ? dirname7(currentFile) : config.pagesDir;
|
|
2360
|
+
cssFilePath = resolve5(fromDir, href);
|
|
2361
|
+
}
|
|
2362
|
+
if (vfs.hasFile(cssFilePath) || existsSync12(cssFilePath)) {
|
|
2363
|
+
let cssContent = "";
|
|
2364
|
+
try {
|
|
2365
|
+
cssContent = await cssGraph.flattenCss(cssFilePath, vfs);
|
|
2366
|
+
} catch {
|
|
2367
|
+
cssContent = await Bun.file(cssFilePath).text();
|
|
2368
|
+
}
|
|
2369
|
+
const styleBlock = `<style id="__buntic_global">
|
|
2370
|
+
${cssContent}
|
|
2371
|
+
</style>`;
|
|
2372
|
+
result = replaceLiteral(result, fullTag, styleBlock);
|
|
2373
|
+
hadManualGlobalLink = true;
|
|
2374
|
+
}
|
|
2375
|
+
}
|
|
2376
|
+
const headMatch = result.match(/<head[\s\S]*?<\/head>/i);
|
|
2377
|
+
const headHasGlobalStyle = headMatch ? headMatch[0].includes('id="__buntic_global"') : false;
|
|
2378
|
+
if (!hadManualGlobalLink && !headHasGlobalStyle && globalCssContent) {
|
|
2379
|
+
const globalTag = ` <style id="__buntic_global">
|
|
2380
|
+
${globalCssContent}
|
|
2381
|
+
</style>`;
|
|
2382
|
+
result = injectIntoHead(result, globalTag, "prepend");
|
|
2383
|
+
}
|
|
2384
|
+
if (hasScopedRules) {
|
|
2385
|
+
const scopedTag = ` <style id="__buntic_scoped">
|
|
2386
|
+
${scopedCssText}
|
|
2387
|
+
</style>`;
|
|
2388
|
+
result = injectIntoHead(result, scopedTag, "append");
|
|
2389
|
+
}
|
|
2390
|
+
return result;
|
|
2391
|
+
}
|
|
2392
|
+
if (globalRoot.relativeRoot) {
|
|
2393
|
+
const globalPublicHref = `/${globalRoot.relativeRoot.replace(/\\/g, "/")}`;
|
|
2394
|
+
const withoutSrc = globalPublicHref.startsWith("/src/") ? globalPublicHref.slice(4) : globalPublicHref;
|
|
2395
|
+
if (!result.includes(globalPublicHref) && !result.includes(withoutSrc)) {
|
|
2396
|
+
const globalLink = ` <link rel="stylesheet" href="${globalPublicHref}">`;
|
|
2397
|
+
result = injectIntoHead(result, globalLink, "prepend");
|
|
2398
|
+
}
|
|
2399
|
+
}
|
|
2400
|
+
if (hasScopedRules) {
|
|
2401
|
+
let pageRelPath = currentFile ? relative4(config.pagesDir, currentFile) : "page.html";
|
|
2402
|
+
if (pageRelPath.startsWith("..") || !currentFile) {
|
|
2403
|
+
pageRelPath = "index.html";
|
|
2404
|
+
}
|
|
2405
|
+
const scopedCssRel = pageRelPath.replace(/\.html$/, ".scoped.css");
|
|
2406
|
+
const scopedPublicPath = "/" + scopedCssRel.replace(/\\/g, "/");
|
|
2407
|
+
generatedPageStyles.set(scopedPublicPath, scopedCssText);
|
|
2408
|
+
generatedPageStyles.set(scopedCssRel, scopedCssText);
|
|
2409
|
+
const linkTag = ` <link rel="stylesheet" href="${scopedPublicPath}">`;
|
|
2410
|
+
result = injectIntoHead(result, linkTag, "append");
|
|
2411
|
+
}
|
|
2412
|
+
return result;
|
|
2413
|
+
}
|
|
2414
|
+
|
|
2415
|
+
// src/template/data-loader.ts
|
|
2416
|
+
import { existsSync as existsSync14, readdirSync as readdirSync4 } from "fs";
|
|
2417
|
+
import { join as join14 } from "path";
|
|
2418
|
+
|
|
2419
|
+
// src/env.ts
|
|
2420
|
+
import { join as join13 } from "path";
|
|
2421
|
+
import { existsSync as existsSync13, readFileSync as readFileSync2 } from "fs";
|
|
2422
|
+
var RESERVED_NAMESPACES = new Set(["params", "props", "env"]);
|
|
2423
|
+
function isReservedNamespace(name) {
|
|
2424
|
+
return RESERVED_NAMESPACES.has(name);
|
|
2425
|
+
}
|
|
2426
|
+
function parseEnvContent(content) {
|
|
2427
|
+
const result = {};
|
|
2428
|
+
const lines = content.split(/\r?\n/);
|
|
2429
|
+
for (let line of lines) {
|
|
2430
|
+
line = line.trim();
|
|
2431
|
+
if (!line || line.startsWith("#"))
|
|
2432
|
+
continue;
|
|
2433
|
+
const eqIdx = line.indexOf("=");
|
|
2434
|
+
if (eqIdx === -1)
|
|
2435
|
+
continue;
|
|
2436
|
+
const key = line.slice(0, eqIdx).trim();
|
|
2437
|
+
let value = line.slice(eqIdx + 1).trim();
|
|
2438
|
+
if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
|
|
2439
|
+
value = value.slice(1, -1);
|
|
2440
|
+
value = value.replace(/\\n/g, `
|
|
2441
|
+
`).replace(/\\"/g, '"');
|
|
2442
|
+
}
|
|
2443
|
+
if (key) {
|
|
2444
|
+
result[key] = value;
|
|
2445
|
+
}
|
|
2446
|
+
}
|
|
2447
|
+
return result;
|
|
2448
|
+
}
|
|
2449
|
+
function loadPublicEnv(projectRoot) {
|
|
2450
|
+
const publicEnv = {};
|
|
2451
|
+
const publicEnvPath = join13(projectRoot, ".env.public");
|
|
2452
|
+
if (existsSync13(publicEnvPath)) {
|
|
2453
|
+
try {
|
|
2454
|
+
const content = readFileSync2(publicEnvPath, "utf-8");
|
|
2455
|
+
const parsed = parseEnvContent(content);
|
|
2456
|
+
Object.assign(publicEnv, parsed);
|
|
2457
|
+
} catch {}
|
|
2458
|
+
}
|
|
2459
|
+
for (const [key, value] of Object.entries(process.env)) {
|
|
2460
|
+
if (key.startsWith("PUBLIC_") && value !== undefined) {
|
|
2461
|
+
publicEnv[key] = value;
|
|
2462
|
+
}
|
|
2463
|
+
}
|
|
2464
|
+
return publicEnv;
|
|
2465
|
+
}
|
|
2466
|
+
|
|
2467
|
+
// src/template/data-loader.ts
|
|
2468
|
+
async function loadGlobalData(config, vfs) {
|
|
2469
|
+
const data = {};
|
|
2470
|
+
const publicEnv = loadPublicEnv(config.root);
|
|
2471
|
+
data["env"] = publicEnv;
|
|
2472
|
+
if (!existsSync14(config.dataDir)) {
|
|
2473
|
+
return data;
|
|
2474
|
+
}
|
|
2475
|
+
try {
|
|
2476
|
+
const entries = readdirSync4(config.dataDir);
|
|
2477
|
+
for (const entry of entries) {
|
|
2478
|
+
if (entry.startsWith("."))
|
|
2479
|
+
continue;
|
|
2480
|
+
let key = "";
|
|
2481
|
+
let isModule = false;
|
|
2482
|
+
let isJson = false;
|
|
2483
|
+
if (entry.endsWith(".json")) {
|
|
2484
|
+
key = entry.replace(/\.json$/, "");
|
|
2485
|
+
isJson = true;
|
|
2486
|
+
} else if ((entry.endsWith(".ts") || entry.endsWith(".js") || entry.endsWith(".mjs")) && !entry.endsWith(".d.ts")) {
|
|
2487
|
+
key = entry.replace(/\.(ts|js|mjs)$/, "");
|
|
2488
|
+
isModule = true;
|
|
2489
|
+
}
|
|
2490
|
+
if (!key)
|
|
2491
|
+
continue;
|
|
2492
|
+
if (isReservedNamespace(key)) {
|
|
2493
|
+
logWarn(`File "${entry}" in data/ conflicts with reserved namespace "${key}". File skipped.`);
|
|
2494
|
+
continue;
|
|
2495
|
+
}
|
|
2496
|
+
const fullPath = join14(config.dataDir, entry);
|
|
2497
|
+
if (isJson) {
|
|
2498
|
+
try {
|
|
2499
|
+
data[key] = await vfs.readJson(fullPath);
|
|
2500
|
+
} catch {
|
|
2501
|
+
data[key] = await Bun.file(fullPath).json();
|
|
2502
|
+
}
|
|
2503
|
+
} else if (isModule) {
|
|
2504
|
+
try {
|
|
2505
|
+
const mod = await import(fullPath);
|
|
2506
|
+
const loader = mod.default ?? mod.load ?? mod.getData;
|
|
2507
|
+
if (typeof loader === "function") {
|
|
2508
|
+
data[key] = await loader({ env: publicEnv });
|
|
2509
|
+
} else if (loader !== undefined) {
|
|
2510
|
+
data[key] = loader;
|
|
2511
|
+
} else {
|
|
2512
|
+
data[key] = mod;
|
|
2513
|
+
}
|
|
2514
|
+
} catch (err) {
|
|
2515
|
+
logError(`Failed to execute global data loader "${entry}"`, err);
|
|
2516
|
+
throw err;
|
|
2517
|
+
}
|
|
2518
|
+
}
|
|
2519
|
+
}
|
|
2520
|
+
} catch (err) {
|
|
2521
|
+
if (err instanceof Error && err.message.includes("[Buntic Error]")) {
|
|
2522
|
+
throw err;
|
|
2523
|
+
}
|
|
2524
|
+
}
|
|
2525
|
+
return data;
|
|
2526
|
+
}
|
|
2527
|
+
|
|
2528
|
+
// src/template/directives.ts
|
|
2529
|
+
function isTruthy(val) {
|
|
2530
|
+
if (val === undefined || val === null || val === false || val === "")
|
|
2531
|
+
return false;
|
|
2532
|
+
if (Array.isArray(val) && val.length === 0)
|
|
2533
|
+
return false;
|
|
2534
|
+
if (typeof val === "number" && isNaN(val))
|
|
2535
|
+
return false;
|
|
2536
|
+
return true;
|
|
2537
|
+
}
|
|
2538
|
+
function getNestedValue(obj, path) {
|
|
2539
|
+
if (!obj || !path)
|
|
2540
|
+
return;
|
|
2541
|
+
const parts = path.split(".");
|
|
2542
|
+
let cur = obj;
|
|
2543
|
+
for (const part of parts) {
|
|
2544
|
+
if (cur == null || typeof cur !== "object")
|
|
2545
|
+
return;
|
|
2546
|
+
cur = cur[part];
|
|
2547
|
+
}
|
|
2548
|
+
return cur;
|
|
2549
|
+
}
|
|
2550
|
+
function resolveConditionals(html, context) {
|
|
2551
|
+
let res = html.replace(/<if\s+is=["']([^"']+)["'][^>]*>([\s\S]*?)<\/if>/gi, (_match, expr, inner) => {
|
|
2552
|
+
const val = getNestedValue(context, expr.trim());
|
|
2553
|
+
let thenContent = inner;
|
|
2554
|
+
let elseContent = "";
|
|
2555
|
+
const elseMatch = inner.match(/([\s\S]*?)<else>([\s\S]*?)<\/else>/i);
|
|
2556
|
+
if (elseMatch) {
|
|
2557
|
+
thenContent = elseMatch[1];
|
|
2558
|
+
elseContent = elseMatch[2];
|
|
2559
|
+
}
|
|
2560
|
+
return isTruthy(val) ? thenContent.trim() : elseContent.trim();
|
|
2561
|
+
});
|
|
2562
|
+
res = res.replace(/<([a-zA-Z0-9_-]+)\s+([^>]*?)if=["']([^"']+)["']([^>]*?)\s*\/>/gi, (_m, tag, before, expr, after) => {
|
|
2563
|
+
const val = getNestedValue(context, expr.trim());
|
|
2564
|
+
if (!isTruthy(val))
|
|
2565
|
+
return "";
|
|
2566
|
+
const attrs = `${before} ${after}`.trim().replace(/\s+/g, " ");
|
|
2567
|
+
return attrs ? `<${tag} ${attrs} />` : `<${tag} />`;
|
|
2568
|
+
});
|
|
2569
|
+
res = res.replace(/<([a-zA-Z0-9_-]+)\s+([^>]*?)if=["']([^"']+)["']([^>]*?)>([\s\S]*?)<\/\1>/gi, (_m, tag, before, expr, after, content) => {
|
|
2570
|
+
const val = getNestedValue(context, expr.trim());
|
|
2571
|
+
if (!isTruthy(val))
|
|
2572
|
+
return "";
|
|
2573
|
+
const attrs = `${before} ${after}`.trim().replace(/\s+/g, " ");
|
|
2574
|
+
return attrs ? `<${tag} ${attrs}>${content}</${tag}>` : `<${tag}>${content}</${tag}>`;
|
|
2575
|
+
});
|
|
2576
|
+
return res;
|
|
2577
|
+
}
|
|
2578
|
+
function interpolateTemplate(html, context) {
|
|
2579
|
+
return html.replace(/\{\{\s*([a-zA-Z0-9_.-]+)(?:\s*\?\?\s*["']([^"']*)["'])?\s*\}\}/g, (match, key, fallback) => {
|
|
2580
|
+
const trimmed = key.trim();
|
|
2581
|
+
const val = getNestedValue(context, trimmed);
|
|
2582
|
+
if (val !== undefined && val !== null)
|
|
2583
|
+
return String(val);
|
|
2584
|
+
if (fallback !== undefined)
|
|
2585
|
+
return fallback;
|
|
2586
|
+
return match;
|
|
2587
|
+
});
|
|
2588
|
+
}
|
|
2589
|
+
|
|
2590
|
+
// src/template/dsd-renderer.ts
|
|
2591
|
+
import { relative as relative5 } from "path";
|
|
2592
|
+
function hasScriptWithSrc(html, srcPath) {
|
|
2593
|
+
const cleanSrc = srcPath.replace(/^\/+/, "");
|
|
2594
|
+
const scriptRegex = /<script\b[^>]*\bsrc=["']([^"']+)["'][^>]*>/gi;
|
|
2595
|
+
let m;
|
|
2596
|
+
while ((m = scriptRegex.exec(html)) !== null) {
|
|
2597
|
+
const existingSrc = m[1].replace(/^\/+/, "");
|
|
2598
|
+
if (existingSrc === cleanSrc || existingSrc.endsWith("/" + cleanSrc)) {
|
|
2599
|
+
return true;
|
|
2600
|
+
}
|
|
2601
|
+
}
|
|
2602
|
+
return false;
|
|
2603
|
+
}
|
|
2604
|
+
async function resolveWebComponentsInHtml(options) {
|
|
2605
|
+
const {
|
|
2606
|
+
html,
|
|
2607
|
+
context,
|
|
2608
|
+
config,
|
|
2609
|
+
vfs,
|
|
2610
|
+
cssGraph,
|
|
2611
|
+
scopeRegistry,
|
|
2612
|
+
warnedUnknownTags,
|
|
2613
|
+
resolveComponentsFn
|
|
2614
|
+
} = options;
|
|
2615
|
+
const scriptsToInject = [];
|
|
2616
|
+
const injectedPaths = new Set;
|
|
2617
|
+
let result = html;
|
|
2618
|
+
const globalRoot = cssGraph.getGlobalRoot();
|
|
2619
|
+
let globalCssBlock = "";
|
|
2620
|
+
if (globalRoot.root) {
|
|
2621
|
+
if (config.cssStrategy === "inline") {
|
|
2622
|
+
const globalCss = await cssGraph.flattenCss(globalRoot.root, vfs);
|
|
2623
|
+
globalCssBlock = `<style data-buntic="global">
|
|
2624
|
+
${globalCss.trim()}
|
|
2625
|
+
</style>`;
|
|
2626
|
+
} else if (globalRoot.relativeRoot) {
|
|
2627
|
+
const globalPublicHref = `/${globalRoot.relativeRoot.replace(/\\/g, "/")}`;
|
|
2628
|
+
globalCssBlock = `<link rel="stylesheet" href="${globalPublicHref}">`;
|
|
2629
|
+
}
|
|
2630
|
+
}
|
|
2631
|
+
let iterations = 0;
|
|
2632
|
+
const maxIterations = 10;
|
|
2633
|
+
while (iterations < maxIterations) {
|
|
2634
|
+
iterations++;
|
|
2635
|
+
const tagRegex = /<([a-z][a-z0-9]*-[a-z0-9-]*)/gi;
|
|
2636
|
+
let match;
|
|
2637
|
+
const discoveredTags = new Set;
|
|
2638
|
+
while ((match = tagRegex.exec(result)) !== null) {
|
|
2639
|
+
discoveredTags.add(match[1].toLowerCase());
|
|
2640
|
+
}
|
|
2641
|
+
let modified = false;
|
|
2642
|
+
for (const tag of discoveredTags) {
|
|
2643
|
+
const scriptPath = vfs.registry.findScriptForTag(tag);
|
|
2644
|
+
if (!scriptPath) {
|
|
2645
|
+
if (!RESERVED_W3C_TAGS.has(tag) && !warnedUnknownTags.has(tag)) {
|
|
2646
|
+
warnedUnknownTags.add(tag);
|
|
2647
|
+
logWarn(`Custom Element "<${tag}>" was found in HTML, but no matching Web Component file was found in the project.`);
|
|
2648
|
+
}
|
|
2649
|
+
continue;
|
|
2650
|
+
}
|
|
2651
|
+
vfs.registry.markTagUsed(tag);
|
|
2652
|
+
const rel = relative5(config.root, scriptPath).replace(/\\/g, "/");
|
|
2653
|
+
const publicSrc = rel.startsWith("/") ? rel : `/${rel}`;
|
|
2654
|
+
if (!injectedPaths.has(publicSrc) && !hasScriptWithSrc(result, publicSrc)) {
|
|
2655
|
+
injectedPaths.add(publicSrc);
|
|
2656
|
+
scriptsToInject.push(`<script type="module" src="${publicSrc}"></script>`);
|
|
2657
|
+
}
|
|
2658
|
+
const triad = findTriadForScript(scriptPath, (p) => vfs.hasFile(p));
|
|
2659
|
+
if (!triad || !triad.htmlPath && !triad.cssPath)
|
|
2660
|
+
continue;
|
|
2661
|
+
const elementRegex = new RegExp(`<${tag}(\\s+[^>]*?)?(\\s*\\/?)>`, "gi");
|
|
2662
|
+
let hasUnexpanded = false;
|
|
2663
|
+
result.replace(elementRegex, (fullMatch, _attrs, _selfClose, offset, fullString) => {
|
|
2664
|
+
const remainder = fullString.slice(offset + fullMatch.length).trimStart();
|
|
2665
|
+
if (!remainder.startsWith("<template") || !remainder.includes("shadowrootmode=")) {
|
|
2666
|
+
hasUnexpanded = true;
|
|
2667
|
+
}
|
|
2668
|
+
return fullMatch;
|
|
2669
|
+
});
|
|
2670
|
+
if (!hasUnexpanded)
|
|
2671
|
+
continue;
|
|
2672
|
+
let siblingCssBlock = "";
|
|
2673
|
+
if (triad.cssPath) {
|
|
2674
|
+
let siblingCss = "";
|
|
2675
|
+
try {
|
|
2676
|
+
siblingCss = await cssGraph.flattenCss(triad.cssPath, vfs);
|
|
2677
|
+
} catch {
|
|
2678
|
+
siblingCss = await Bun.file(triad.cssPath).text();
|
|
2679
|
+
}
|
|
2680
|
+
siblingCss = siblingCss.replace(/(^|[^a-zA-Z0-9_-])&(?![\w-])/g, "$1:host");
|
|
2681
|
+
if (siblingCss.trim().length > 0) {
|
|
2682
|
+
siblingCssBlock = `<style>
|
|
2683
|
+
${siblingCss.trim()}
|
|
2684
|
+
</style>`;
|
|
2685
|
+
}
|
|
2686
|
+
}
|
|
2687
|
+
let templateHtml = "<slot></slot>";
|
|
2688
|
+
let scopedDsdCssBlock = "";
|
|
2689
|
+
if (triad.htmlPath) {
|
|
2690
|
+
let rawHtml = "";
|
|
2691
|
+
try {
|
|
2692
|
+
rawHtml = await vfs.readText(triad.htmlPath);
|
|
2693
|
+
} catch {
|
|
2694
|
+
rawHtml = await Bun.file(triad.htmlPath).text();
|
|
2695
|
+
}
|
|
2696
|
+
rawHtml = await resolveComponentsFn(rawHtml, context, triad.htmlPath);
|
|
2697
|
+
rawHtml = resolveConditionals(rawHtml, context);
|
|
2698
|
+
rawHtml = interpolateTemplate(rawHtml, context);
|
|
2699
|
+
if (rawHtml.includes("<style") && rawHtml.includes("scoped")) {
|
|
2700
|
+
const extracted = extractScopedStyles(rawHtml, scopeRegistry);
|
|
2701
|
+
rawHtml = extracted.html;
|
|
2702
|
+
if (extracted.scopedRules.length > 0) {
|
|
2703
|
+
scopedDsdCssBlock = `<style data-buntic="dsd-scoped">
|
|
2704
|
+
${extracted.scopedRules.join(`
|
|
2705
|
+
|
|
2706
|
+
`)}
|
|
2707
|
+
</style>`;
|
|
2708
|
+
}
|
|
2709
|
+
}
|
|
2710
|
+
templateHtml = rawHtml.trim();
|
|
2711
|
+
}
|
|
2712
|
+
const shadowParts = [];
|
|
2713
|
+
if (globalCssBlock)
|
|
2714
|
+
shadowParts.push(globalCssBlock);
|
|
2715
|
+
if (siblingCssBlock)
|
|
2716
|
+
shadowParts.push(siblingCssBlock);
|
|
2717
|
+
if (scopedDsdCssBlock)
|
|
2718
|
+
shadowParts.push(scopedDsdCssBlock);
|
|
2719
|
+
if (templateHtml)
|
|
2720
|
+
shadowParts.push(templateHtml);
|
|
2721
|
+
const dsdContent = shadowParts.join(`
|
|
2722
|
+
`);
|
|
2723
|
+
const templateTag = `<template shadowrootmode="open">
|
|
2724
|
+
${dsdContent}
|
|
2725
|
+
</template>`;
|
|
2726
|
+
result = result.replace(elementRegex, (fullMatch, attrs, selfClose, offset, fullString) => {
|
|
2727
|
+
const isSelfClosing = selfClose && selfClose.trim() === "/";
|
|
2728
|
+
const attrStr = attrs ? ` ${attrs.trim()}` : "";
|
|
2729
|
+
const remainder = fullString.slice(offset + fullMatch.length).trimStart();
|
|
2730
|
+
if (remainder.startsWith("<template") && remainder.includes("shadowrootmode=")) {
|
|
2731
|
+
return fullMatch;
|
|
2732
|
+
}
|
|
2733
|
+
modified = true;
|
|
2734
|
+
return isSelfClosing ? `<${tag}${attrStr}>
|
|
2735
|
+
${templateTag}
|
|
2736
|
+
</${tag}>` : `<${tag}${attrStr}>
|
|
2737
|
+
${templateTag}`;
|
|
2738
|
+
});
|
|
2739
|
+
}
|
|
2740
|
+
if (!modified) {
|
|
2741
|
+
break;
|
|
2742
|
+
}
|
|
2743
|
+
}
|
|
2744
|
+
if (scriptsToInject.length > 0) {
|
|
2745
|
+
result = injectIntoHead(result, ` ${scriptsToInject.join(`
|
|
2746
|
+
`)}`, "append");
|
|
2747
|
+
}
|
|
2748
|
+
return result;
|
|
2749
|
+
}
|
|
2750
|
+
|
|
2751
|
+
// src/template/svg-component.ts
|
|
2752
|
+
import { relative as relative6 } from "path";
|
|
2753
|
+
async function attachSiblingCssIfPresent(options) {
|
|
2754
|
+
const { templateHtml, templatePath, siblingCssPath, kindLabel, config, vfs, cssGraph } = options;
|
|
2755
|
+
if (!vfs.hasFile(siblingCssPath)) {
|
|
2756
|
+
return templateHtml;
|
|
2757
|
+
}
|
|
2758
|
+
let siblingCss = "";
|
|
2759
|
+
try {
|
|
2760
|
+
siblingCss = await cssGraph.flattenCss(siblingCssPath, vfs);
|
|
2761
|
+
} catch {
|
|
2762
|
+
siblingCss = await Bun.file(siblingCssPath).text();
|
|
2763
|
+
}
|
|
2764
|
+
if (siblingCss.trim().length === 0) {
|
|
2765
|
+
return templateHtml;
|
|
2766
|
+
}
|
|
2767
|
+
const withScopedCss = attachSiblingScopedCss(templateHtml, siblingCss);
|
|
2768
|
+
if (withScopedCss !== null) {
|
|
2769
|
+
return withScopedCss;
|
|
2770
|
+
}
|
|
2771
|
+
const relTarget = relative6(config.root, templatePath);
|
|
2772
|
+
const relCss = relative6(config.root, siblingCssPath);
|
|
2773
|
+
logWarn(`${kindLabel} "${relTarget}" has a sibling CSS file ("${relCss}"), but does not have a single root element. Scoped styles were not applied.`);
|
|
2774
|
+
return templateHtml;
|
|
2775
|
+
}
|
|
2776
|
+
function mergeSvgAttributes(svgHtml, props) {
|
|
2777
|
+
const root = findSingleRootElement(svgHtml);
|
|
2778
|
+
if (!root)
|
|
2779
|
+
return svgHtml;
|
|
2780
|
+
let openTag = root.openTagRaw;
|
|
2781
|
+
for (const [key, val] of Object.entries(props)) {
|
|
2782
|
+
if (key === "class") {
|
|
2783
|
+
const classMatch = openTag.match(/\bclass=(["'])(.*?)\1/i);
|
|
2784
|
+
if (classMatch) {
|
|
2785
|
+
const quote = classMatch[1];
|
|
2786
|
+
const existingClasses = classMatch[2].trim();
|
|
2787
|
+
const combined = Array.from(new Set([...existingClasses.split(/\s+/), ...val.split(/\s+/)])).filter(Boolean).join(" ");
|
|
2788
|
+
openTag = openTag.replace(classMatch[0], () => `class=${quote}${combined}${quote}`);
|
|
2789
|
+
} else if (openTag.endsWith("/>")) {
|
|
2790
|
+
openTag = openTag.slice(0, -2).trimEnd() + ` class="${val}"/>`;
|
|
2791
|
+
} else {
|
|
2792
|
+
openTag = openTag.slice(0, -1).trimEnd() + ` class="${val}">`;
|
|
2793
|
+
}
|
|
2794
|
+
} else {
|
|
2795
|
+
const escapedKey = key.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
|
|
2796
|
+
const attrRegex = new RegExp(`\\b${escapedKey}(?:=(?:["'][^"']*["']|[^\\s>]+))?`, "i");
|
|
2797
|
+
const replacement = val === "true" ? `${key}="true"` : `${key}="${val}"`;
|
|
2798
|
+
if (attrRegex.test(openTag)) {
|
|
2799
|
+
openTag = openTag.replace(attrRegex, () => replacement);
|
|
2800
|
+
} else if (openTag.endsWith("/>")) {
|
|
2801
|
+
openTag = openTag.slice(0, -2).trimEnd() + ` ${replacement}/>`;
|
|
2802
|
+
} else {
|
|
2803
|
+
openTag = openTag.slice(0, -1).trimEnd() + ` ${replacement}>`;
|
|
2804
|
+
}
|
|
2805
|
+
}
|
|
2806
|
+
}
|
|
2807
|
+
return svgHtml.slice(0, root.openTagStart) + openTag + svgHtml.slice(root.openTagEnd);
|
|
2808
|
+
}
|
|
2809
|
+
async function renderSvgComponent(options) {
|
|
2810
|
+
const { compPath, props, config, vfs, cssGraph } = options;
|
|
2811
|
+
let svgContent = await vfs.readText(compPath);
|
|
2812
|
+
svgContent = svgContent.replace(/<\?xml[\s\S]*?\?>/gi, "").replace(/<!DOCTYPE[\s\S]*?>/gi, "").trim();
|
|
2813
|
+
const siblingCssPath = compPath.replace(/\.svg$/i, ".css");
|
|
2814
|
+
svgContent = await attachSiblingCssIfPresent({
|
|
2815
|
+
templateHtml: svgContent,
|
|
2816
|
+
templatePath: compPath,
|
|
2817
|
+
siblingCssPath,
|
|
2818
|
+
kindLabel: "SVG",
|
|
2819
|
+
config,
|
|
2820
|
+
vfs,
|
|
2821
|
+
cssGraph
|
|
2822
|
+
});
|
|
2823
|
+
const passedProps = { ...props };
|
|
2824
|
+
delete passedProps.src;
|
|
2825
|
+
return mergeSvgAttributes(svgContent, passedProps);
|
|
2826
|
+
}
|
|
2827
|
+
|
|
2828
|
+
// src/template/vfs.ts
|
|
2829
|
+
import { join as join15, resolve as resolve6, dirname as dirname8 } from "path";
|
|
2830
|
+
import { readdirSync as readdirSync5, statSync as statSync6, existsSync as existsSync15, readFileSync as readFileSync3 } from "fs";
|
|
2831
|
+
function isIgnoredPath(filePathOrName) {
|
|
2832
|
+
const normalized = filePathOrName.replace(/\\/g, "/");
|
|
2833
|
+
const segments = normalized.split("/");
|
|
2834
|
+
for (const seg of segments) {
|
|
2835
|
+
if (seg === "node_modules" || seg === ".git" || seg === ".agents" || seg === "dist" || seg.startsWith(".buntic")) {
|
|
2836
|
+
return true;
|
|
2837
|
+
}
|
|
2838
|
+
}
|
|
2839
|
+
const base = segments[segments.length - 1] || "";
|
|
2840
|
+
if (!base)
|
|
2841
|
+
return false;
|
|
2842
|
+
if (base.endsWith("~"))
|
|
2843
|
+
return true;
|
|
2844
|
+
if (/^\..*\.sw[a-z]+$/i.test(base) || /\.(swp|swo|swn|swx|swpx)$/i.test(base)) {
|
|
2845
|
+
return true;
|
|
2846
|
+
}
|
|
2847
|
+
if (/^(4913|5036|5159|5282)$/.test(base))
|
|
2848
|
+
return true;
|
|
2849
|
+
if (base.startsWith(".#") || base.startsWith("#") && base.endsWith("#")) {
|
|
2850
|
+
return true;
|
|
2851
|
+
}
|
|
2852
|
+
if (base.endsWith(".tmp") || base.endsWith(".__jb_tmp__") || base.endsWith(".__jb_old__") || base === ".DS_Store" || base === "Thumbs.db") {
|
|
2853
|
+
return true;
|
|
2854
|
+
}
|
|
2855
|
+
return false;
|
|
2856
|
+
}
|
|
2857
|
+
|
|
2858
|
+
class VirtualFileSystem {
|
|
2859
|
+
root;
|
|
2860
|
+
registry = new WebComponentRegistry;
|
|
2861
|
+
knownFiles = new Set;
|
|
2862
|
+
knownDirs = new Set;
|
|
2863
|
+
pathCache = new Map;
|
|
2864
|
+
contentCache = new Map;
|
|
2865
|
+
jsonCache = new Map;
|
|
2866
|
+
constructor(root) {
|
|
2867
|
+
this.root = resolve6(root);
|
|
2868
|
+
this.scan(this.root);
|
|
2869
|
+
}
|
|
2870
|
+
scan(dir = this.root) {
|
|
2871
|
+
if (!existsSync15(dir))
|
|
2872
|
+
return;
|
|
2873
|
+
try {
|
|
2874
|
+
const entries = readdirSync5(dir);
|
|
2875
|
+
for (const entry of entries) {
|
|
2876
|
+
if (isIgnoredPath(entry)) {
|
|
2877
|
+
continue;
|
|
2878
|
+
}
|
|
2879
|
+
const fullPath = join15(dir, entry);
|
|
2880
|
+
try {
|
|
2881
|
+
const stat = statSync6(fullPath);
|
|
2882
|
+
if (stat.isDirectory()) {
|
|
2883
|
+
this.knownDirs.add(fullPath);
|
|
2884
|
+
this.scan(fullPath);
|
|
2885
|
+
} else if (stat.isFile()) {
|
|
2886
|
+
this.knownFiles.add(fullPath);
|
|
2887
|
+
if (/\.(ts|js|tsx|jsx)$/.test(fullPath)) {
|
|
2888
|
+
try {
|
|
2889
|
+
const content = readFileSync3(fullPath, "utf-8");
|
|
2890
|
+
this.registry.registerFile(fullPath, content);
|
|
2891
|
+
} catch {
|
|
2892
|
+
this.registry.registerFile(fullPath);
|
|
2893
|
+
}
|
|
2894
|
+
}
|
|
2895
|
+
}
|
|
2896
|
+
} catch {}
|
|
2897
|
+
}
|
|
2898
|
+
} catch {}
|
|
2899
|
+
}
|
|
2900
|
+
hasFile(path) {
|
|
2901
|
+
const absPath = resolve6(path);
|
|
2902
|
+
if (this.knownFiles.has(absPath))
|
|
2903
|
+
return true;
|
|
2904
|
+
if (existsSync15(absPath) && !statSync6(absPath).isDirectory()) {
|
|
2905
|
+
this.knownFiles.add(absPath);
|
|
2906
|
+
return true;
|
|
2907
|
+
}
|
|
2908
|
+
return false;
|
|
2909
|
+
}
|
|
2910
|
+
resolvePath(rawSrc, currentFile, defaultDir) {
|
|
2911
|
+
const cacheKey = `${currentFile}::${rawSrc}::${defaultDir}`;
|
|
2912
|
+
const cached = this.pathCache.get(cacheKey);
|
|
2913
|
+
if (cached)
|
|
2914
|
+
return cached;
|
|
2915
|
+
const src = rawSrc;
|
|
2916
|
+
const srcWithHtml = src.endsWith(".html") ? src : `${src}.html`;
|
|
2917
|
+
const candidates = [];
|
|
2918
|
+
if (src.startsWith("./") || src.startsWith("../")) {
|
|
2919
|
+
const fromDir = currentFile ? dirname8(resolve6(currentFile)) : this.root;
|
|
2920
|
+
candidates.push(resolve6(fromDir, src));
|
|
2921
|
+
candidates.push(resolve6(fromDir, srcWithHtml));
|
|
2922
|
+
}
|
|
2923
|
+
if (src.startsWith("/")) {
|
|
2924
|
+
const clean = src.slice(1);
|
|
2925
|
+
candidates.push(resolve6(this.root, clean));
|
|
2926
|
+
candidates.push(resolve6(this.root, srcWithHtml.slice(1)));
|
|
2927
|
+
candidates.push(resolve6(this.root, "src", clean));
|
|
2928
|
+
candidates.push(resolve6(this.root, "src", srcWithHtml.slice(1)));
|
|
2929
|
+
}
|
|
2930
|
+
if (currentFile && !src.startsWith("/")) {
|
|
2931
|
+
const fromDir = dirname8(resolve6(currentFile));
|
|
2932
|
+
candidates.push(resolve6(fromDir, src));
|
|
2933
|
+
candidates.push(resolve6(fromDir, srcWithHtml));
|
|
2934
|
+
}
|
|
2935
|
+
candidates.push(resolve6(defaultDir, src));
|
|
2936
|
+
candidates.push(resolve6(defaultDir, srcWithHtml));
|
|
2937
|
+
candidates.push(resolve6(this.root, src));
|
|
2938
|
+
candidates.push(resolve6(this.root, srcWithHtml));
|
|
2939
|
+
for (const cand of candidates) {
|
|
2940
|
+
if (this.hasFile(cand)) {
|
|
2941
|
+
this.pathCache.set(cacheKey, cand);
|
|
2942
|
+
return cand;
|
|
2943
|
+
}
|
|
2944
|
+
}
|
|
2945
|
+
const fallback = candidates[0] || resolve6(defaultDir, srcWithHtml);
|
|
2946
|
+
this.pathCache.set(cacheKey, fallback);
|
|
2947
|
+
return fallback;
|
|
2948
|
+
}
|
|
2949
|
+
async readText(path) {
|
|
2950
|
+
const absPath = resolve6(path);
|
|
2951
|
+
const cached = this.contentCache.get(absPath);
|
|
2952
|
+
if (cached !== undefined)
|
|
2953
|
+
return cached;
|
|
2954
|
+
const content = await Bun.file(absPath).text();
|
|
2955
|
+
this.contentCache.set(absPath, content);
|
|
2956
|
+
return content;
|
|
2957
|
+
}
|
|
2958
|
+
async readJson(path) {
|
|
2959
|
+
const absPath = resolve6(path);
|
|
2960
|
+
const cached = this.jsonCache.get(absPath);
|
|
2961
|
+
if (cached !== undefined)
|
|
2962
|
+
return cached;
|
|
2963
|
+
const content = await Bun.file(absPath).json();
|
|
2964
|
+
this.jsonCache.set(absPath, content);
|
|
2965
|
+
return content;
|
|
2966
|
+
}
|
|
2967
|
+
getAllFiles() {
|
|
2968
|
+
return Array.from(this.knownFiles);
|
|
2969
|
+
}
|
|
2970
|
+
getFilesInDirectory(subDir) {
|
|
2971
|
+
const absSubDir = resolve6(subDir);
|
|
2972
|
+
const results = [];
|
|
2973
|
+
for (const file of this.knownFiles) {
|
|
2974
|
+
if (dirname8(resolve6(file)) === absSubDir) {
|
|
2975
|
+
results.push(file);
|
|
2976
|
+
}
|
|
2977
|
+
}
|
|
2978
|
+
return results;
|
|
2979
|
+
}
|
|
2980
|
+
invalidateFile(path) {
|
|
2981
|
+
if (!path) {
|
|
2982
|
+
this.clear();
|
|
2983
|
+
return;
|
|
2984
|
+
}
|
|
2985
|
+
const absPath = resolve6(path);
|
|
2986
|
+
this.contentCache.delete(absPath);
|
|
2987
|
+
this.jsonCache.delete(absPath);
|
|
2988
|
+
this.pathCache.clear();
|
|
2989
|
+
if (absPath.endsWith("~")) {
|
|
2990
|
+
const targetPath = absPath.slice(0, -1);
|
|
2991
|
+
this.contentCache.delete(targetPath);
|
|
2992
|
+
this.jsonCache.delete(targetPath);
|
|
2993
|
+
}
|
|
2994
|
+
if (isIgnoredPath(absPath)) {
|
|
2995
|
+
return;
|
|
2996
|
+
}
|
|
2997
|
+
const isScript = /\.(ts|js|tsx|jsx)$/.test(absPath);
|
|
2998
|
+
if (isScript) {
|
|
2999
|
+
this.registry.unregisterFile(absPath);
|
|
3000
|
+
}
|
|
3001
|
+
if (existsSync15(absPath)) {
|
|
3002
|
+
try {
|
|
3003
|
+
const stat = statSync6(absPath);
|
|
3004
|
+
if (stat.isDirectory()) {
|
|
3005
|
+
this.knownDirs.add(absPath);
|
|
3006
|
+
this.scan(absPath);
|
|
3007
|
+
} else if (stat.isFile()) {
|
|
3008
|
+
this.knownFiles.add(absPath);
|
|
3009
|
+
if (isScript) {
|
|
3010
|
+
try {
|
|
3011
|
+
const content = readFileSync3(absPath, "utf-8");
|
|
3012
|
+
this.registry.registerFile(absPath, content);
|
|
3013
|
+
} catch {
|
|
3014
|
+
this.registry.registerFile(absPath);
|
|
3015
|
+
}
|
|
3016
|
+
}
|
|
3017
|
+
}
|
|
3018
|
+
} catch {}
|
|
3019
|
+
} else {
|
|
3020
|
+
this.knownFiles.delete(absPath);
|
|
3021
|
+
this.knownDirs.delete(absPath);
|
|
3022
|
+
}
|
|
3023
|
+
}
|
|
3024
|
+
clearContentCache() {
|
|
3025
|
+
this.contentCache.clear();
|
|
3026
|
+
this.jsonCache.clear();
|
|
3027
|
+
this.pathCache.clear();
|
|
3028
|
+
}
|
|
3029
|
+
clear() {
|
|
3030
|
+
this.knownFiles.clear();
|
|
3031
|
+
this.knownDirs.clear();
|
|
3032
|
+
this.pathCache.clear();
|
|
3033
|
+
this.contentCache.clear();
|
|
3034
|
+
this.jsonCache.clear();
|
|
3035
|
+
this.registry = new WebComponentRegistry;
|
|
3036
|
+
this.scan(this.root);
|
|
3037
|
+
}
|
|
3038
|
+
}
|
|
3039
|
+
|
|
3040
|
+
// src/template/engine.ts
|
|
3041
|
+
class TemplateEngine {
|
|
3042
|
+
config;
|
|
3043
|
+
vfs;
|
|
3044
|
+
scopeRegistry;
|
|
3045
|
+
cssGraph;
|
|
3046
|
+
generatedPageStyles = new Map;
|
|
3047
|
+
cachedData = null;
|
|
3048
|
+
warnedUnknownTags = new Set;
|
|
3049
|
+
constructor(config) {
|
|
3050
|
+
this.config = config;
|
|
3051
|
+
this.vfs = new VirtualFileSystem(this.config.root);
|
|
3052
|
+
this.scopeRegistry = new ScopeRegistry;
|
|
3053
|
+
this.cssGraph = new CssDependencyGraph(this.config.root);
|
|
3054
|
+
}
|
|
3055
|
+
async loadData() {
|
|
3056
|
+
if (this.cachedData)
|
|
3057
|
+
return this.cachedData;
|
|
3058
|
+
this.cachedData = await loadGlobalData(this.config, this.vfs);
|
|
3059
|
+
return this.cachedData;
|
|
3060
|
+
}
|
|
3061
|
+
invalidateDataCache() {
|
|
3062
|
+
this.cachedData = null;
|
|
3063
|
+
}
|
|
3064
|
+
invalidateCache(filePath) {
|
|
3065
|
+
this.cachedData = null;
|
|
3066
|
+
this.vfs.invalidateFile(filePath);
|
|
3067
|
+
this.scopeRegistry.clear();
|
|
3068
|
+
this.cssGraph.invalidate();
|
|
3069
|
+
this.generatedPageStyles.clear();
|
|
3070
|
+
this.warnedUnknownTags.clear();
|
|
3071
|
+
}
|
|
3072
|
+
async renderPage(pageHtml, currentFile = "", pageContext) {
|
|
3073
|
+
const data = await this.loadData();
|
|
3074
|
+
const context = { ...data };
|
|
3075
|
+
if (pageContext) {
|
|
3076
|
+
if (pageContext.params !== undefined)
|
|
3077
|
+
context.params = pageContext.params;
|
|
3078
|
+
if (pageContext.props !== undefined)
|
|
3079
|
+
context.props = pageContext.props;
|
|
3080
|
+
for (const [k, v] of Object.entries(pageContext)) {
|
|
3081
|
+
if (k !== "params" && k !== "props" && k !== "env") {
|
|
3082
|
+
context[k] = v;
|
|
3083
|
+
}
|
|
3084
|
+
}
|
|
3085
|
+
}
|
|
3086
|
+
await this.cssGraph.analyze(this.vfs);
|
|
3087
|
+
const globalRoot = this.cssGraph.getGlobalRoot();
|
|
3088
|
+
if (globalRoot.conflicts.length > 1) {
|
|
3089
|
+
const relConflicts = globalRoot.conflicts.map((c) => relative7(this.config.root, c));
|
|
3090
|
+
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");
|
|
3091
|
+
}
|
|
3092
|
+
let processedHtml = pageHtml;
|
|
3093
|
+
if (currentFile && currentFile.endsWith(".html")) {
|
|
3094
|
+
processedHtml = await attachSiblingCssIfPresent({
|
|
3095
|
+
templateHtml: processedHtml,
|
|
3096
|
+
templatePath: currentFile,
|
|
3097
|
+
siblingCssPath: currentFile.replace(/\.html$/, ".css"),
|
|
3098
|
+
kindLabel: "Page",
|
|
3099
|
+
config: this.config,
|
|
3100
|
+
vfs: this.vfs,
|
|
3101
|
+
cssGraph: this.cssGraph
|
|
3102
|
+
});
|
|
3103
|
+
}
|
|
3104
|
+
let composed = await this.resolveLayout(processedHtml, context, currentFile);
|
|
3105
|
+
composed = await this.resolveEach(composed, context, currentFile);
|
|
3106
|
+
composed = await this.resolveComponents(composed, context, currentFile);
|
|
3107
|
+
composed = this.resolveConditionals(composed, context);
|
|
3108
|
+
composed = this.interpolate(composed, context);
|
|
3109
|
+
composed = await this.resolveWebComponents(composed, context);
|
|
3110
|
+
composed = await this.resolveCss(composed, currentFile);
|
|
3111
|
+
return composed;
|
|
3112
|
+
}
|
|
3113
|
+
async resolveCss(html, currentFile = "", extraScopedRules = []) {
|
|
3114
|
+
return resolvePageCss({
|
|
3115
|
+
html,
|
|
3116
|
+
currentFile,
|
|
3117
|
+
extraScopedRules,
|
|
3118
|
+
config: this.config,
|
|
3119
|
+
vfs: this.vfs,
|
|
3120
|
+
cssGraph: this.cssGraph,
|
|
3121
|
+
scopeRegistry: this.scopeRegistry,
|
|
3122
|
+
generatedPageStyles: this.generatedPageStyles
|
|
3123
|
+
});
|
|
3124
|
+
}
|
|
3125
|
+
async resolveWebComponents(html, context = {}) {
|
|
3126
|
+
return resolveWebComponentsInHtml({
|
|
3127
|
+
html,
|
|
3128
|
+
context,
|
|
3129
|
+
config: this.config,
|
|
3130
|
+
vfs: this.vfs,
|
|
3131
|
+
cssGraph: this.cssGraph,
|
|
3132
|
+
scopeRegistry: this.scopeRegistry,
|
|
3133
|
+
warnedUnknownTags: this.warnedUnknownTags,
|
|
3134
|
+
resolveComponentsFn: (raw, ctx, file) => this.resolveComponents(raw, ctx, file)
|
|
3135
|
+
});
|
|
3136
|
+
}
|
|
3137
|
+
getUnusedWebComponents() {
|
|
3138
|
+
return this.vfs.registry.getUnusedComponents();
|
|
3139
|
+
}
|
|
3140
|
+
assertNoWebComponentConflicts() {
|
|
3141
|
+
this.vfs.registry.assertNoConflicts();
|
|
3142
|
+
}
|
|
3143
|
+
clearUsedWebComponents() {
|
|
3144
|
+
this.vfs.registry.clearUsed();
|
|
3145
|
+
}
|
|
3146
|
+
resolveFilePath(rawSrc, currentFile, defaultDir) {
|
|
3147
|
+
return this.vfs.resolvePath(rawSrc, currentFile, defaultDir);
|
|
3148
|
+
}
|
|
3149
|
+
async resolveLayout(html, context, currentFile) {
|
|
3150
|
+
const layoutMatch = html.match(/<layout\s+src=["']([^"']+)["'][^>]*>([\s\S]*?)<\/layout>/i);
|
|
3151
|
+
if (!layoutMatch) {
|
|
3152
|
+
return html;
|
|
3153
|
+
}
|
|
3154
|
+
const layoutRawSrc = layoutMatch[1];
|
|
3155
|
+
const innerContent = layoutMatch[2];
|
|
3156
|
+
const layoutFilePath = this.resolveFilePath(layoutRawSrc, currentFile, this.config.layoutsDir);
|
|
3157
|
+
if (!this.vfs.hasFile(layoutFilePath) && !existsSync16(layoutFilePath)) {
|
|
3158
|
+
throw new Error(`[Buntic] Layout not found: "${layoutRawSrc}" at ${layoutFilePath}`);
|
|
3159
|
+
}
|
|
3160
|
+
const layoutTemplate = await this.vfs.readText(layoutFilePath);
|
|
3161
|
+
let resolvedInner = await this.resolveEach(innerContent, context, currentFile);
|
|
3162
|
+
resolvedInner = await this.resolveComponents(resolvedInner, context, currentFile);
|
|
3163
|
+
const layoutSlotNames = new Set;
|
|
3164
|
+
const layoutSlotRegex = /<slot\s+name=["']([^"']+)["']/gi;
|
|
3165
|
+
let sm;
|
|
3166
|
+
while ((sm = layoutSlotRegex.exec(layoutTemplate)) !== null) {
|
|
3167
|
+
layoutSlotNames.add(sm[1]);
|
|
3168
|
+
}
|
|
3169
|
+
const slots = new Map;
|
|
3170
|
+
const slotElRegex = /<([a-zA-Z0-9_-]+)\s+[^>]*slot=["']([^"']+)["'][^>]*>([\s\S]*?)<\/\1>/gi;
|
|
3171
|
+
const defaultContent = resolvedInner.replace(slotElRegex, (match, _tag, slotName, content, offset) => {
|
|
3172
|
+
if (layoutSlotNames.has(slotName) && !slots.has(slotName)) {
|
|
3173
|
+
const preceding = resolvedInner.slice(0, offset);
|
|
3174
|
+
const openCustomTags = preceding.match(/<([a-z][a-z0-9]*-[a-z0-9-]*)[^>]*>/gi) || [];
|
|
3175
|
+
const closeCustomTags = preceding.match(/<\/([a-z][a-z0-9]*-[a-z0-9-]*)[^>]*>/gi) || [];
|
|
3176
|
+
if (openCustomTags.length > closeCustomTags.length) {
|
|
3177
|
+
return match;
|
|
3178
|
+
}
|
|
3179
|
+
slots.set(slotName, content.trim());
|
|
3180
|
+
return "";
|
|
3181
|
+
}
|
|
3182
|
+
return match;
|
|
3183
|
+
}).trim();
|
|
3184
|
+
let rendered = layoutTemplate.replace(/<slot\s+name=["']([^"']+)["'][^>]*>([\s\S]*?)<\/slot>/gi, (_match, name, fallback) => slots.get(name) ?? fallback);
|
|
3185
|
+
rendered = rendered.replace(/<slot\s+name=["']([^"']+)["']\s*\/>/gi, (_match, name) => slots.get(name) ?? "");
|
|
3186
|
+
rendered = rendered.replace(/<slot\s*>\s*<\/slot>/gi, () => defaultContent);
|
|
3187
|
+
rendered = rendered.replace(/<slot\s*\/>/gi, () => defaultContent);
|
|
3188
|
+
rendered = await this.resolveEach(rendered, context, layoutFilePath);
|
|
3189
|
+
rendered = await this.resolveComponents(rendered, context, layoutFilePath);
|
|
3190
|
+
return rendered;
|
|
3191
|
+
}
|
|
3192
|
+
async resolveEach(html, context, currentFile, depth = 0) {
|
|
3193
|
+
if (depth > 10) {
|
|
3194
|
+
console.warn("[Buntic] Maximum <each> recursion depth (10) reached.");
|
|
3195
|
+
return html;
|
|
3196
|
+
}
|
|
3197
|
+
const eachRegex = /<each\s+([^>]+?)>([\s\S]*?)<\/each>/gis;
|
|
3198
|
+
let match;
|
|
3199
|
+
const matches = [];
|
|
3200
|
+
while ((match = eachRegex.exec(html)) !== null) {
|
|
3201
|
+
matches.push({ fullMatch: match[0], attrString: match[1], inner: match[2] });
|
|
3202
|
+
}
|
|
3203
|
+
if (matches.length === 0)
|
|
3204
|
+
return html;
|
|
3205
|
+
let result = html;
|
|
3206
|
+
for (const item of matches) {
|
|
3207
|
+
const attrs = parseHtmlAttributes(item.attrString);
|
|
3208
|
+
let items;
|
|
3209
|
+
if (attrs.src) {
|
|
3210
|
+
const filePath = this.resolveFilePath(attrs.src, currentFile, this.config.dataDir);
|
|
3211
|
+
if (!this.vfs.hasFile(filePath) && !existsSync16(filePath)) {
|
|
3212
|
+
throw new Error(`[Buntic] <each> data file not found: "${attrs.src}" at ${filePath}`);
|
|
3213
|
+
}
|
|
3214
|
+
items = await this.vfs.readJson(filePath);
|
|
3215
|
+
} else if (attrs.in) {
|
|
3216
|
+
items = getNestedValue(context, attrs.in);
|
|
3217
|
+
} else {
|
|
3218
|
+
throw new Error(`[Buntic] <each> tag requires either a "src" or "in" attribute.`);
|
|
3219
|
+
}
|
|
3220
|
+
if (!Array.isArray(items)) {
|
|
3221
|
+
throw new Error(`[Buntic] <each> source "${attrs.src || attrs.in}" did not resolve to an array.`);
|
|
3222
|
+
}
|
|
3223
|
+
const renderedItems = [];
|
|
3224
|
+
for (const entry of items) {
|
|
3225
|
+
let itemContext = { ...context };
|
|
3226
|
+
if (entry && typeof entry === "object" && !Array.isArray(entry)) {
|
|
3227
|
+
itemContext = { ...itemContext, ...entry };
|
|
3228
|
+
if (attrs.as) {
|
|
3229
|
+
itemContext[attrs.as] = entry;
|
|
3230
|
+
}
|
|
3231
|
+
} else {
|
|
3232
|
+
if (attrs.as) {
|
|
3233
|
+
itemContext[attrs.as] = entry;
|
|
3234
|
+
}
|
|
3235
|
+
itemContext.item = entry;
|
|
3236
|
+
itemContext.this = entry;
|
|
3237
|
+
}
|
|
3238
|
+
let rendered = await this.resolveEach(item.inner, itemContext, currentFile, depth + 1);
|
|
3239
|
+
rendered = await this.resolveComponents(rendered, itemContext, currentFile, depth + 1);
|
|
3240
|
+
rendered = this.resolveConditionals(rendered, itemContext);
|
|
3241
|
+
rendered = this.interpolate(rendered, itemContext);
|
|
3242
|
+
renderedItems.push(rendered);
|
|
3243
|
+
}
|
|
3244
|
+
result = replaceLiteral(result, item.fullMatch, renderedItems.join(`
|
|
3245
|
+
`));
|
|
3246
|
+
}
|
|
3247
|
+
return result;
|
|
3248
|
+
}
|
|
3249
|
+
async resolveComponents(html, context, currentFile, depth = 0) {
|
|
3250
|
+
if (depth > 10) {
|
|
3251
|
+
console.warn("[Buntic] Maximum component recursion depth (10) reached. Check for circular component includes.");
|
|
3252
|
+
return html;
|
|
3253
|
+
}
|
|
3254
|
+
const componentRegex = /<component\s+([^>]+?)(?:\s*\/>|>(.*?)<\/component>)/gis;
|
|
3255
|
+
const matches = [];
|
|
3256
|
+
let match;
|
|
3257
|
+
while ((match = componentRegex.exec(html)) !== null) {
|
|
3258
|
+
const props = parseHtmlAttributes(match[1]);
|
|
3259
|
+
if (props.src) {
|
|
3260
|
+
matches.push({
|
|
3261
|
+
fullMatch: match[0],
|
|
3262
|
+
children: match[2] ? match[2].trim() : "",
|
|
3263
|
+
src: props.src,
|
|
3264
|
+
props
|
|
3265
|
+
});
|
|
3266
|
+
}
|
|
3267
|
+
}
|
|
3268
|
+
if (matches.length === 0)
|
|
3269
|
+
return html;
|
|
3270
|
+
let result = html;
|
|
3271
|
+
for (const item of matches) {
|
|
3272
|
+
const compPath = this.resolveFilePath(item.src, currentFile, this.config.componentsDir);
|
|
3273
|
+
if (!this.vfs.hasFile(compPath) && !existsSync16(compPath)) {
|
|
3274
|
+
throw new Error(`[Buntic] Component not found: "${item.src}" at ${compPath}`);
|
|
3275
|
+
}
|
|
3276
|
+
const ext = extname4(compPath).toLowerCase();
|
|
3277
|
+
if (ext === ".ts" || ext === ".js" || ext === ".tsx" || ext === ".jsx") {
|
|
3278
|
+
const replacement = await this.renderWebComponentAlias({
|
|
3279
|
+
compPath,
|
|
3280
|
+
rawSrc: item.src,
|
|
3281
|
+
props: item.props,
|
|
3282
|
+
children: item.children,
|
|
3283
|
+
context,
|
|
3284
|
+
currentFile,
|
|
3285
|
+
depth
|
|
3286
|
+
});
|
|
3287
|
+
result = replaceLiteral(result, item.fullMatch, replacement);
|
|
3288
|
+
continue;
|
|
3289
|
+
}
|
|
3290
|
+
if (ext === ".svg") {
|
|
3291
|
+
const svgContent = await renderSvgComponent({
|
|
3292
|
+
compPath,
|
|
3293
|
+
props: item.props,
|
|
3294
|
+
config: this.config,
|
|
3295
|
+
vfs: this.vfs,
|
|
3296
|
+
cssGraph: this.cssGraph
|
|
3297
|
+
});
|
|
3298
|
+
result = replaceLiteral(result, item.fullMatch, svgContent);
|
|
3299
|
+
continue;
|
|
3300
|
+
}
|
|
3301
|
+
let compTemplate = await this.vfs.readText(compPath);
|
|
3302
|
+
compTemplate = await attachSiblingCssIfPresent({
|
|
3303
|
+
templateHtml: compTemplate,
|
|
3304
|
+
templatePath: compPath,
|
|
3305
|
+
siblingCssPath: compPath.replace(/\.html$/, ".css"),
|
|
3306
|
+
kindLabel: "Component",
|
|
3307
|
+
config: this.config,
|
|
3308
|
+
vfs: this.vfs,
|
|
3309
|
+
cssGraph: this.cssGraph
|
|
3310
|
+
});
|
|
3311
|
+
const compContext = { ...context, ...item.props };
|
|
3312
|
+
compTemplate = compTemplate.replace(/<slot\s*>\s*<\/slot>/gi, () => item.children);
|
|
3313
|
+
compTemplate = compTemplate.replace(/<slot\s*\/>/gi, () => item.children);
|
|
3314
|
+
compTemplate = this.resolveConditionals(compTemplate, compContext);
|
|
3315
|
+
compTemplate = this.interpolate(compTemplate, compContext);
|
|
3316
|
+
compTemplate = await this.resolveComponents(compTemplate, compContext, compPath, depth + 1);
|
|
3317
|
+
result = replaceLiteral(result, item.fullMatch, compTemplate);
|
|
3318
|
+
}
|
|
3319
|
+
return result;
|
|
3320
|
+
}
|
|
3321
|
+
async renderWebComponentAlias(options) {
|
|
3322
|
+
const { compPath, rawSrc, props, children, context, currentFile, depth } = options;
|
|
3323
|
+
let tag = this.vfs.registry.getTagsForFile(compPath)[0];
|
|
3324
|
+
if (!tag) {
|
|
3325
|
+
let code;
|
|
3326
|
+
try {
|
|
3327
|
+
code = await this.vfs.readText(compPath);
|
|
3328
|
+
} catch {
|
|
3329
|
+
code = await Bun.file(compPath).text();
|
|
3330
|
+
}
|
|
3331
|
+
const registered = this.vfs.registry.registerFile(compPath, code);
|
|
3332
|
+
tag = registered[0];
|
|
3333
|
+
}
|
|
3334
|
+
if (!tag) {
|
|
3335
|
+
tag = filenameToTagName(compPath) || undefined;
|
|
3336
|
+
}
|
|
3337
|
+
if (!tag) {
|
|
3338
|
+
throw new Error(`[Buntic] Could not determine Custom Element tag name for Web Component file "${rawSrc}". ` + `Ensure the filename follows kebab-case (e.g. "my-element.ts") or PascalCase (e.g. "MyElement.ts").`);
|
|
3339
|
+
}
|
|
3340
|
+
const attrEntries = Object.entries(props).filter(([k]) => k !== "src");
|
|
3341
|
+
const attrString = attrEntries.length > 0 ? " " + attrEntries.map(([k, v]) => `${k}="${v}"`).join(" ") : "";
|
|
3342
|
+
let innerChildren = children;
|
|
3343
|
+
if (innerChildren) {
|
|
3344
|
+
innerChildren = await this.resolveComponents(innerChildren, context, currentFile, depth + 1);
|
|
3345
|
+
innerChildren = this.resolveConditionals(innerChildren, context);
|
|
3346
|
+
innerChildren = this.interpolate(innerChildren, context);
|
|
3347
|
+
}
|
|
3348
|
+
return innerChildren ? `<${tag}${attrString}>${innerChildren}</${tag}>` : `<${tag}${attrString}></${tag}>`;
|
|
3349
|
+
}
|
|
3350
|
+
resolveConditionals(html, context) {
|
|
3351
|
+
return resolveConditionals(html, context);
|
|
3352
|
+
}
|
|
3353
|
+
interpolate(html, context) {
|
|
3354
|
+
return interpolateTemplate(html, context);
|
|
3355
|
+
}
|
|
3356
|
+
}
|
|
3357
|
+
|
|
3358
|
+
// src/builder/collisions.ts
|
|
3359
|
+
import { existsSync as existsSync17 } from "fs";
|
|
3360
|
+
import { join as join16, relative as relative8 } from "path";
|
|
3361
|
+
function getDirectoryFiles(dir, baseDir = dir) {
|
|
3362
|
+
return walkFiles(dir, {
|
|
3363
|
+
baseDir,
|
|
3364
|
+
relativeToBase: true
|
|
3365
|
+
});
|
|
3366
|
+
}
|
|
3367
|
+
function detectPublicCollisions(config, routes) {
|
|
3368
|
+
if (!existsSync17(config.publicDir)) {
|
|
3369
|
+
return [];
|
|
3370
|
+
}
|
|
3371
|
+
const publicFiles = getDirectoryFiles(config.publicDir);
|
|
3372
|
+
const collisions = [];
|
|
3373
|
+
const routeOutputMap = new Map;
|
|
3374
|
+
for (const route of routes) {
|
|
3375
|
+
const relOut = relative8(config.outDir, route.outputFilePath).replace(/\\/g, "/");
|
|
3376
|
+
routeOutputMap.set(relOut, route);
|
|
3377
|
+
}
|
|
3378
|
+
for (const relFile of publicFiles) {
|
|
3379
|
+
if (routeOutputMap.has(relFile)) {
|
|
3380
|
+
const route = routeOutputMap.get(relFile);
|
|
3381
|
+
collisions.push({
|
|
3382
|
+
type: "route",
|
|
3383
|
+
publicPath: relative8(config.root, join16(config.publicDir, relFile)),
|
|
3384
|
+
conflictWith: relative8(config.root, route.templateFilePath),
|
|
3385
|
+
outputPath: relFile
|
|
3386
|
+
});
|
|
3387
|
+
}
|
|
3388
|
+
if (relFile.startsWith("assets/images/") || relFile === "assets/images") {
|
|
3389
|
+
collisions.push({
|
|
3390
|
+
type: "reserved-dir",
|
|
3391
|
+
publicPath: relative8(config.root, join16(config.publicDir, relFile)),
|
|
3392
|
+
conflictWith: "assets/images/ (Reserved for Buntic <photo> image optimization)",
|
|
3393
|
+
outputPath: relFile
|
|
3394
|
+
});
|
|
3395
|
+
} else if (relFile.startsWith("assets/seo/") || relFile === "assets/seo") {
|
|
3396
|
+
collisions.push({
|
|
3397
|
+
type: "reserved-dir",
|
|
3398
|
+
publicPath: relative8(config.root, join16(config.publicDir, relFile)),
|
|
3399
|
+
conflictWith: "assets/seo/ (Reserved for Buntic <seo> social cards)",
|
|
3400
|
+
outputPath: relFile
|
|
3401
|
+
});
|
|
3402
|
+
}
|
|
3403
|
+
}
|
|
3404
|
+
return collisions;
|
|
3405
|
+
}
|
|
3406
|
+
function assertNoPublicCollisions(config, routes) {
|
|
3407
|
+
const collisions = detectPublicCollisions(config, routes);
|
|
3408
|
+
if (collisions.length === 0)
|
|
3409
|
+
return;
|
|
3410
|
+
const details = collisions.map((c) => {
|
|
3411
|
+
if (c.type === "route") {
|
|
3412
|
+
return ` - Public file "${c.publicPath}" conflicts with page template "${c.conflictWith}" (both output to "${c.outputPath}").`;
|
|
3413
|
+
}
|
|
3414
|
+
return ` - Public file "${c.publicPath}" conflicts with reserved internal path "${c.conflictWith}".`;
|
|
3415
|
+
}).join(`
|
|
3416
|
+
`);
|
|
3417
|
+
throw new Error(`[Buntic Collision Error]: Conflict detected between public/ files and build output:
|
|
3418
|
+
` + details + `
|
|
3419
|
+
|
|
3420
|
+
\uD83D\uDC49 Action: Remove or rename conflicting files in "public/" or adjust page routes in "pages/".`);
|
|
3421
|
+
}
|
|
3422
|
+
|
|
3423
|
+
// src/builder/builder.ts
|
|
3424
|
+
class Builder {
|
|
3425
|
+
config;
|
|
3426
|
+
engine;
|
|
3427
|
+
photoProcessor;
|
|
3428
|
+
seoEngine;
|
|
3429
|
+
constructor(config) {
|
|
3430
|
+
this.config = config;
|
|
3431
|
+
this.engine = new TemplateEngine(config);
|
|
3432
|
+
this.photoProcessor = new PhotoProcessor(config);
|
|
3433
|
+
this.seoEngine = new SeoMetadataEngine(config, this.photoProcessor.imageProcessor, this.photoProcessor.storageManager);
|
|
3434
|
+
}
|
|
3435
|
+
async build(options = {}) {
|
|
3436
|
+
const startTime = performance.now();
|
|
3437
|
+
if (options.cleanCache) {
|
|
3438
|
+
await this.photoProcessor.imageProcessor.cache.clean();
|
|
3439
|
+
}
|
|
3440
|
+
this.engine.assertNoWebComponentConflicts();
|
|
3441
|
+
this.engine.clearUsedWebComponents();
|
|
3442
|
+
if (!existsSync18(this.config.pagesDir)) {
|
|
3443
|
+
throw new Error(`[Buntic] Pages directory not found at: ${this.config.pagesDir}`);
|
|
3444
|
+
}
|
|
3445
|
+
const globalData = await this.engine.loadData();
|
|
3446
|
+
const routes = await resolveAllRoutes(this.config, globalData);
|
|
3447
|
+
if (routes.length === 0) {
|
|
3448
|
+
console.warn(`[Buntic] No HTML pages found in: ${this.config.pagesDir}`);
|
|
3449
|
+
return { success: true, pagesCount: 0, outputFiles: [], durationMs: 0 };
|
|
3450
|
+
}
|
|
3451
|
+
assertNoPublicCollisions(this.config, routes);
|
|
3452
|
+
this.prepareEmptyDir(this.config.outDir);
|
|
3453
|
+
const stagingDir = join17(this.config.root, ".buntic-staging");
|
|
3454
|
+
this.prepareEmptyDir(stagingDir);
|
|
3455
|
+
try {
|
|
3456
|
+
const stagedEntrypoints = await this.stagePages(routes, stagingDir);
|
|
3457
|
+
const outputFiles = await this.bundleStagedPages(stagedEntrypoints, stagingDir);
|
|
3458
|
+
await this.postProcessHtmlPages(routes);
|
|
3459
|
+
if (existsSync18(this.config.publicDir)) {
|
|
3460
|
+
cpSync2(this.config.publicDir, this.config.outDir, { recursive: true });
|
|
3461
|
+
}
|
|
3462
|
+
await this.emitProcessedAssets();
|
|
3463
|
+
await this.emitSeoArtifacts(routes);
|
|
3464
|
+
this.warnUnusedWebComponents();
|
|
3465
|
+
return {
|
|
3466
|
+
success: true,
|
|
3467
|
+
pagesCount: routes.length,
|
|
3468
|
+
outputFiles,
|
|
3469
|
+
durationMs: Math.round(performance.now() - startTime)
|
|
3470
|
+
};
|
|
3471
|
+
} finally {
|
|
3472
|
+
if (existsSync18(stagingDir)) {
|
|
3473
|
+
rmSync3(stagingDir, { recursive: true, force: true });
|
|
3474
|
+
}
|
|
3475
|
+
}
|
|
3476
|
+
}
|
|
3477
|
+
prepareEmptyDir(dir) {
|
|
3478
|
+
if (existsSync18(dir)) {
|
|
3479
|
+
rmSync3(dir, { recursive: true, force: true });
|
|
3480
|
+
}
|
|
3481
|
+
mkdirSync3(dir, { recursive: true });
|
|
3482
|
+
}
|
|
3483
|
+
async stagePages(routes, stagingDir) {
|
|
3484
|
+
const stagedEntrypoints = [];
|
|
3485
|
+
for (const route of routes) {
|
|
3486
|
+
const rawContent = await Bun.file(route.templateFilePath).text();
|
|
3487
|
+
let rendered = await this.engine.renderPage(rawContent, route.templateFilePath, {
|
|
3488
|
+
params: route.params,
|
|
3489
|
+
props: route.props
|
|
3490
|
+
});
|
|
3491
|
+
if (this.config.cssStrategy === "external") {
|
|
3492
|
+
for (const [relPath, cssContent] of this.engine.generatedPageStyles.entries()) {
|
|
3493
|
+
if (!relPath.startsWith("/")) {
|
|
3494
|
+
const stagedCssPath = join17(stagingDir, relPath);
|
|
3495
|
+
mkdirSync3(dirname9(stagedCssPath), { recursive: true });
|
|
3496
|
+
await Bun.write(stagedCssPath, cssContent);
|
|
3497
|
+
}
|
|
3498
|
+
}
|
|
3499
|
+
}
|
|
3500
|
+
const relStagedPath = relative9(this.config.outDir, route.outputFilePath);
|
|
3501
|
+
const stagedPath = join17(stagingDir, relStagedPath);
|
|
3502
|
+
mkdirSync3(dirname9(stagedPath), { recursive: true });
|
|
3503
|
+
rendered = this.normalizeRootPaths(rendered, stagedPath, stagingDir);
|
|
3504
|
+
await Bun.write(stagedPath, rendered);
|
|
3505
|
+
stagedEntrypoints.push(stagedPath);
|
|
3506
|
+
}
|
|
3507
|
+
return stagedEntrypoints;
|
|
3508
|
+
}
|
|
3509
|
+
async bundleStagedPages(stagedEntrypoints, stagingDir) {
|
|
3510
|
+
const buildResult = await Bun.build({
|
|
3511
|
+
entrypoints: stagedEntrypoints,
|
|
3512
|
+
outdir: this.config.outDir,
|
|
3513
|
+
root: stagingDir,
|
|
3514
|
+
minify: this.config.minify,
|
|
3515
|
+
naming: {
|
|
3516
|
+
chunk: "[name]-[hash].[ext]",
|
|
3517
|
+
asset: "[name]-[hash].[ext]",
|
|
3518
|
+
entry: "[dir]/[name].[ext]"
|
|
3519
|
+
},
|
|
3520
|
+
external: ["/*"]
|
|
3521
|
+
});
|
|
3522
|
+
if (!buildResult.success) {
|
|
3523
|
+
for (const log of buildResult.logs) {
|
|
3524
|
+
console.error(log);
|
|
3525
|
+
}
|
|
3526
|
+
throw new Error("[Buntic] Bun.build bundling failed.");
|
|
3527
|
+
}
|
|
3528
|
+
return buildResult.outputs.map((o) => o.path);
|
|
3529
|
+
}
|
|
3530
|
+
async postProcessHtmlPages(routes) {
|
|
3531
|
+
for (const route of routes) {
|
|
3532
|
+
if (!existsSync18(route.outputFilePath))
|
|
3533
|
+
continue;
|
|
3534
|
+
let html = await Bun.file(route.outputFilePath).text();
|
|
3535
|
+
html = await this.photoProcessor.processHtml(html, route.templateFilePath);
|
|
3536
|
+
html = await this.seoEngine.processSeo(html, {
|
|
3537
|
+
templatePath: route.templateFilePath,
|
|
3538
|
+
urlPath: route.urlPath,
|
|
3539
|
+
routeSeo: route.seo
|
|
3540
|
+
});
|
|
3541
|
+
await Bun.write(route.outputFilePath, html);
|
|
3542
|
+
}
|
|
3543
|
+
}
|
|
3544
|
+
async emitProcessedAssets() {
|
|
3545
|
+
const allEmitted = [
|
|
3546
|
+
...this.photoProcessor.emittedAssets.values(),
|
|
3547
|
+
...this.seoEngine.emittedAssets.values()
|
|
3548
|
+
];
|
|
3549
|
+
for (const asset of allEmitted) {
|
|
3550
|
+
const fullOut = join17(this.config.outDir, asset.outputPath);
|
|
3551
|
+
mkdirSync3(dirname9(fullOut), { recursive: true });
|
|
3552
|
+
await Bun.write(fullOut, asset.bytes);
|
|
3553
|
+
}
|
|
3554
|
+
}
|
|
3555
|
+
async emitSeoArtifacts(routes) {
|
|
3556
|
+
const sitemapXml = generateSitemapXml(routes, this.config);
|
|
3557
|
+
if (sitemapXml) {
|
|
3558
|
+
await Bun.write(join17(this.config.outDir, "sitemap.xml"), sitemapXml);
|
|
3559
|
+
}
|
|
3560
|
+
const robotsTxt = generateRobotsTxt(this.config);
|
|
3561
|
+
if (robotsTxt) {
|
|
3562
|
+
await Bun.write(join17(this.config.outDir, "robots.txt"), robotsTxt);
|
|
3563
|
+
}
|
|
3564
|
+
const rssXml = generateRss2Xml(routes, this.config);
|
|
3565
|
+
if (rssXml) {
|
|
3566
|
+
const rssFilename = typeof this.config.feeds?.rss === "string" ? this.config.feeds.rss : "rss.xml";
|
|
3567
|
+
await Bun.write(join17(this.config.outDir, rssFilename), rssXml);
|
|
3568
|
+
}
|
|
3569
|
+
const atomXml = generateAtomXml(routes, this.config);
|
|
3570
|
+
if (atomXml) {
|
|
3571
|
+
const atomFilename = typeof this.config.feeds?.atom === "string" ? this.config.feeds.atom : "atom.xml";
|
|
3572
|
+
await Bun.write(join17(this.config.outDir, atomFilename), atomXml);
|
|
3573
|
+
}
|
|
3574
|
+
}
|
|
3575
|
+
warnUnusedWebComponents() {
|
|
3576
|
+
const unused = this.engine.getUnusedWebComponents();
|
|
3577
|
+
for (const item of unused) {
|
|
3578
|
+
logWarn(`Web Component "<${item.tag}>" (${relative9(this.config.root, item.file)}) is registered but not used in any page.`);
|
|
3579
|
+
}
|
|
3580
|
+
}
|
|
3581
|
+
normalizeRootPaths(html, stagedFilePath, stagingDir) {
|
|
3582
|
+
const fromDir = dirname9(stagedFilePath);
|
|
3583
|
+
return html.replace(/(href|src)=["']\/([^"']+)["']/gi, (match, attr, path) => {
|
|
3584
|
+
if (path.startsWith("/") || path.startsWith("http:") || path.startsWith("https:") || path.startsWith("_buntic") || path.startsWith("assets/images/") || path.startsWith("assets/seo/")) {
|
|
3585
|
+
return match;
|
|
3586
|
+
}
|
|
3587
|
+
const targetInRoot = join17(this.config.root, path);
|
|
3588
|
+
if (existsSync18(targetInRoot)) {
|
|
3589
|
+
let rel = relative9(fromDir, targetInRoot);
|
|
3590
|
+
if (!rel.startsWith("."))
|
|
3591
|
+
rel = "./" + rel;
|
|
3592
|
+
return `${attr}="${rel}"`;
|
|
3593
|
+
}
|
|
3594
|
+
const targetInSrc = join17(this.config.root, "src", path);
|
|
3595
|
+
if (existsSync18(targetInSrc)) {
|
|
3596
|
+
let rel = relative9(fromDir, targetInSrc);
|
|
3597
|
+
if (!rel.startsWith("."))
|
|
3598
|
+
rel = "./" + rel;
|
|
3599
|
+
return `${attr}="${rel}"`;
|
|
3600
|
+
}
|
|
3601
|
+
if (stagingDir) {
|
|
3602
|
+
const targetInStaging = join17(stagingDir, path);
|
|
3603
|
+
if (existsSync18(targetInStaging)) {
|
|
3604
|
+
let rel = relative9(fromDir, targetInStaging);
|
|
3605
|
+
if (!rel.startsWith("."))
|
|
3606
|
+
rel = "./" + rel;
|
|
3607
|
+
return `${attr}="${rel}"`;
|
|
3608
|
+
}
|
|
3609
|
+
}
|
|
3610
|
+
return match;
|
|
3611
|
+
});
|
|
3612
|
+
}
|
|
3613
|
+
}
|
|
3614
|
+
|
|
3615
|
+
// src/server/dev.ts
|
|
3616
|
+
import { existsSync as existsSync20, watch } from "fs";
|
|
3617
|
+
import { join as join19, resolve as resolve7 } from "path";
|
|
3618
|
+
|
|
3619
|
+
// src/server/dev-helpers.ts
|
|
3620
|
+
import { existsSync as existsSync19, statSync as statSync7 } from "fs";
|
|
3621
|
+
import { join as join18 } from "path";
|
|
3622
|
+
var LIVE_RELOAD_SCRIPT = `
|
|
3623
|
+
<script id="__buntic_live_reload">
|
|
3624
|
+
(() => {
|
|
3625
|
+
const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
|
|
3626
|
+
const ws = new WebSocket(\`\${protocol}//\${location.host}/_buntic/ws\`);
|
|
3627
|
+
ws.onmessage = (event) => {
|
|
3628
|
+
if (event.data === 'reload') {
|
|
3629
|
+
console.log('[buntic] Change detected. Reloading...');
|
|
3630
|
+
location.reload();
|
|
3631
|
+
}
|
|
3632
|
+
};
|
|
3633
|
+
ws.onclose = () => {
|
|
3634
|
+
setTimeout(() => location.reload(), 1500);
|
|
3635
|
+
};
|
|
3636
|
+
})();
|
|
3637
|
+
</script>
|
|
3638
|
+
`;
|
|
3639
|
+
async function renderDevPage(options) {
|
|
3640
|
+
const {
|
|
3641
|
+
templatePath,
|
|
3642
|
+
urlPath,
|
|
3643
|
+
params,
|
|
3644
|
+
props = {},
|
|
3645
|
+
routeSeo,
|
|
3646
|
+
engine,
|
|
3647
|
+
photoProcessor,
|
|
3648
|
+
seoEngine
|
|
3649
|
+
} = options;
|
|
3650
|
+
const raw = await Bun.file(templatePath).text();
|
|
3651
|
+
let rendered = await engine.renderPage(raw, templatePath, { params, props });
|
|
3652
|
+
rendered = await photoProcessor.processHtml(rendered, templatePath);
|
|
3653
|
+
rendered = await seoEngine.processSeo(rendered, {
|
|
3654
|
+
templatePath,
|
|
3655
|
+
urlPath,
|
|
3656
|
+
routeSeo
|
|
3657
|
+
});
|
|
3658
|
+
rendered = injectBeforeBodyEnd(rendered, LIVE_RELOAD_SCRIPT);
|
|
3659
|
+
return new Response(rendered, {
|
|
3660
|
+
headers: {
|
|
3661
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
3662
|
+
"Cache-Control": "no-store, no-cache, must-revalidate"
|
|
3663
|
+
}
|
|
3664
|
+
});
|
|
3665
|
+
}
|
|
3666
|
+
async function tryServeSeoRoute(pathname, config, engine) {
|
|
3667
|
+
if (pathname === "/robots.txt") {
|
|
3668
|
+
const robots = generateRobotsTxt(config);
|
|
3669
|
+
if (robots) {
|
|
3670
|
+
return new Response(robots, {
|
|
3671
|
+
headers: { "Content-Type": "text/plain; charset=utf-8" }
|
|
3672
|
+
});
|
|
3673
|
+
}
|
|
3674
|
+
return null;
|
|
3675
|
+
}
|
|
3676
|
+
if (pathname === "/sitemap.xml" || pathname === "/rss.xml" || pathname === "/atom.xml") {
|
|
3677
|
+
const globalData = await engine.loadData();
|
|
3678
|
+
const routes = await resolveAllRoutes(config, globalData);
|
|
3679
|
+
let xml = null;
|
|
3680
|
+
if (pathname === "/sitemap.xml") {
|
|
3681
|
+
xml = generateSitemapXml(routes, config);
|
|
3682
|
+
} else if (pathname === "/rss.xml") {
|
|
3683
|
+
xml = generateRss2Xml(routes, config);
|
|
3684
|
+
} else {
|
|
3685
|
+
xml = generateAtomXml(routes, config);
|
|
3686
|
+
}
|
|
3687
|
+
if (xml) {
|
|
3688
|
+
return new Response(xml, {
|
|
3689
|
+
headers: { "Content-Type": "application/xml; charset=utf-8" }
|
|
3690
|
+
});
|
|
3691
|
+
}
|
|
3692
|
+
}
|
|
3693
|
+
return null;
|
|
3694
|
+
}
|
|
3695
|
+
function resolveSafeStaticFile(baseDir, pathname) {
|
|
3696
|
+
if (!existsSync19(baseDir))
|
|
3697
|
+
return null;
|
|
3698
|
+
const relPath = pathname.replace(/^\/+/, "");
|
|
3699
|
+
if (!relPath)
|
|
3700
|
+
return null;
|
|
3701
|
+
const candidate = join18(baseDir, relPath);
|
|
3702
|
+
if (!isPathInside(baseDir, candidate)) {
|
|
3703
|
+
return null;
|
|
3704
|
+
}
|
|
3705
|
+
try {
|
|
3706
|
+
if (existsSync19(candidate) && statSync7(candidate).isFile()) {
|
|
3707
|
+
return candidate;
|
|
3708
|
+
}
|
|
3709
|
+
} catch {}
|
|
3710
|
+
return null;
|
|
3711
|
+
}
|
|
3712
|
+
async function serveFileWithTranspiler(filePath) {
|
|
3713
|
+
const file = Bun.file(filePath);
|
|
3714
|
+
if (filePath.endsWith(".ts") || filePath.endsWith(".tsx") || filePath.endsWith(".jsx")) {
|
|
3715
|
+
const transpiler = new Bun.Transpiler({ loader: filePath.endsWith(".tsx") ? "tsx" : "ts" });
|
|
3716
|
+
const code = await file.text();
|
|
3717
|
+
const transpiled = transpiler.transformSync(code);
|
|
3718
|
+
return new Response(transpiled, {
|
|
3719
|
+
headers: {
|
|
3720
|
+
"Content-Type": "application/javascript; charset=utf-8",
|
|
3721
|
+
"Cache-Control": "no-store, no-cache, must-revalidate"
|
|
3722
|
+
}
|
|
3723
|
+
});
|
|
3724
|
+
}
|
|
3725
|
+
return new Response(file, {
|
|
3726
|
+
headers: {
|
|
3727
|
+
"Content-Type": getMimeType(filePath),
|
|
3728
|
+
"Cache-Control": "no-store, no-cache, must-revalidate"
|
|
3729
|
+
}
|
|
3730
|
+
});
|
|
3731
|
+
}
|
|
3732
|
+
function getMimeType(path) {
|
|
3733
|
+
if (path.endsWith(".html"))
|
|
3734
|
+
return "text/html; charset=utf-8";
|
|
3735
|
+
if (path.endsWith(".css"))
|
|
3736
|
+
return "text/css; charset=utf-8";
|
|
3737
|
+
if (path.endsWith(".js") || path.endsWith(".mjs"))
|
|
3738
|
+
return "application/javascript; charset=utf-8";
|
|
3739
|
+
if (path.endsWith(".json"))
|
|
3740
|
+
return "application/json; charset=utf-8";
|
|
3741
|
+
if (path.endsWith(".png"))
|
|
3742
|
+
return "image/png";
|
|
3743
|
+
if (path.endsWith(".jpg") || path.endsWith(".jpeg"))
|
|
3744
|
+
return "image/jpeg";
|
|
3745
|
+
if (path.endsWith(".webp"))
|
|
3746
|
+
return "image/webp";
|
|
3747
|
+
if (path.endsWith(".svg"))
|
|
3748
|
+
return "image/svg+xml";
|
|
3749
|
+
if (path.endsWith(".ico"))
|
|
3750
|
+
return "image/x-icon";
|
|
3751
|
+
if (path.endsWith(".xml"))
|
|
3752
|
+
return "application/xml; charset=utf-8";
|
|
3753
|
+
if (path.endsWith(".txt"))
|
|
3754
|
+
return "text/plain; charset=utf-8";
|
|
3755
|
+
return "application/octet-stream";
|
|
3756
|
+
}
|
|
3757
|
+
function renderErrorResponse(title, err) {
|
|
3758
|
+
const safeTitle = escapeHtml(title);
|
|
3759
|
+
const safeMsg = escapeHtml(getErrorMessage(err));
|
|
3760
|
+
return new Response(`<h1>${safeTitle}</h1><pre>${safeMsg}</pre>`, {
|
|
3761
|
+
status: 500,
|
|
3762
|
+
headers: { "Content-Type": "text/html; charset=utf-8" }
|
|
3763
|
+
});
|
|
3764
|
+
}
|
|
3765
|
+
function renderNotFoundResponse(pathname, routes) {
|
|
3766
|
+
const safePathname = escapeHtml(pathname);
|
|
3767
|
+
const availableRoutesHtml = routes.length > 0 ? `
|
|
3768
|
+
<h3>Available routes in this project (${routes.length}):</h3>
|
|
3769
|
+
<ul>
|
|
3770
|
+
${routes.map((r) => `<li><a href="${escapeHtml(r.urlPath)}"><code>${escapeHtml(r.urlPath)}</code></a> <span style="color:#94a3b8">(${escapeHtml(r.patternRelativePath)})</span></li>`).join("")}
|
|
3771
|
+
</ul>
|
|
3772
|
+
` : "";
|
|
3773
|
+
const notFoundHtml = `
|
|
3774
|
+
<!doctype html>
|
|
3775
|
+
<html>
|
|
3776
|
+
<head>
|
|
3777
|
+
<title>404 - Not Found | Buntic Dev</title>
|
|
3778
|
+
<style>
|
|
3779
|
+
body { font-family: system-ui, -apple-system, sans-serif; background: #0f172a; color: #f8fafc; padding: 3rem; }
|
|
3780
|
+
.card { max-width: 650px; margin: 0 auto; background: #1e293b; padding: 2rem; border-radius: 12px; border: 1px solid #334155; }
|
|
3781
|
+
h1 { color: #f43f5e; margin-top: 0; }
|
|
3782
|
+
code { background: #0f172a; padding: 0.2rem 0.4rem; border-radius: 4px; color: #38bdf8; font-family: monospace; }
|
|
3783
|
+
ul { line-height: 1.8; }
|
|
3784
|
+
a { color: #38bdf8; text-decoration: none; }
|
|
3785
|
+
a:hover { text-decoration: underline; }
|
|
3786
|
+
</style>
|
|
3787
|
+
</head>
|
|
3788
|
+
<body>
|
|
3789
|
+
<div class="card">
|
|
3790
|
+
<h1>404 - Page Not Found</h1>
|
|
3791
|
+
<p>The requested route <code>${safePathname}</code> does not match any page or static file.</p>
|
|
3792
|
+
${availableRoutesHtml}
|
|
3793
|
+
</div>
|
|
3794
|
+
</body>
|
|
3795
|
+
</html>
|
|
3796
|
+
`;
|
|
3797
|
+
return new Response(notFoundHtml, {
|
|
3798
|
+
status: 404,
|
|
3799
|
+
headers: { "Content-Type": "text/html; charset=utf-8" }
|
|
3800
|
+
});
|
|
3801
|
+
}
|
|
3802
|
+
|
|
3803
|
+
// src/server/dev.ts
|
|
3804
|
+
function startDevServer(config) {
|
|
3805
|
+
const engine = new TemplateEngine(config);
|
|
3806
|
+
const photoProcessor = new PhotoProcessor(config);
|
|
3807
|
+
const seoEngine = new SeoMetadataEngine(config, photoProcessor.imageProcessor, photoProcessor.storageManager);
|
|
3808
|
+
const activeSockets = new Set;
|
|
3809
|
+
(async () => {
|
|
3810
|
+
try {
|
|
3811
|
+
const globalData = await engine.loadData();
|
|
3812
|
+
const routes = await resolveAllRoutes(config, globalData);
|
|
3813
|
+
const collisions = detectPublicCollisions(config, routes);
|
|
3814
|
+
for (const c of collisions) {
|
|
3815
|
+
if (c.type === "route") {
|
|
3816
|
+
logWarn(`Public file "${c.publicPath}" conflicts with page template "${c.conflictWith}" (both resolve to "${c.outputPath}").`, "Buntic Collision Warning");
|
|
3817
|
+
} else {
|
|
3818
|
+
logWarn(`Public file "${c.publicPath}" conflicts with reserved internal path "${c.conflictWith}".`, "Buntic Collision Warning");
|
|
3819
|
+
}
|
|
3820
|
+
}
|
|
3821
|
+
} catch {}
|
|
3822
|
+
})();
|
|
3823
|
+
let debounceTimer = null;
|
|
3824
|
+
const pendingChangedPaths = new Set;
|
|
3825
|
+
const watcher = watch(config.root, { recursive: true }, (_eventType, filename) => {
|
|
3826
|
+
if (!filename || isIgnoredPath(filename))
|
|
3827
|
+
return;
|
|
3828
|
+
const changedPath = resolve7(config.root, filename);
|
|
3829
|
+
pendingChangedPaths.add(changedPath);
|
|
3830
|
+
if (debounceTimer)
|
|
3831
|
+
clearTimeout(debounceTimer);
|
|
3832
|
+
debounceTimer = setTimeout(() => {
|
|
3833
|
+
for (const p of pendingChangedPaths) {
|
|
3834
|
+
engine.invalidateCache(p);
|
|
3835
|
+
}
|
|
3836
|
+
pendingChangedPaths.clear();
|
|
3837
|
+
engine.vfs.clearContentCache();
|
|
3838
|
+
photoProcessor.storageManager.invalidate();
|
|
3839
|
+
photoProcessor.emittedAssets.clear();
|
|
3840
|
+
seoEngine.emittedAssets.clear();
|
|
3841
|
+
for (const socket of activeSockets) {
|
|
3842
|
+
socket.send("reload");
|
|
3843
|
+
}
|
|
3844
|
+
}, 60);
|
|
3845
|
+
});
|
|
3846
|
+
const server = Bun.serve({
|
|
3847
|
+
port: config.port,
|
|
3848
|
+
websocket: {
|
|
3849
|
+
message(_ws, _msg) {},
|
|
3850
|
+
open(ws) {
|
|
3851
|
+
activeSockets.add(ws);
|
|
3852
|
+
},
|
|
3853
|
+
close(ws) {
|
|
3854
|
+
activeSockets.delete(ws);
|
|
3855
|
+
}
|
|
3856
|
+
},
|
|
3857
|
+
async fetch(req, srv) {
|
|
3858
|
+
const url = new URL(req.url);
|
|
3859
|
+
let pathname;
|
|
3860
|
+
try {
|
|
3861
|
+
pathname = decodeURIComponent(url.pathname);
|
|
3862
|
+
} catch {
|
|
3863
|
+
return new Response("Bad Request", { status: 400 });
|
|
3864
|
+
}
|
|
3865
|
+
if (pathname === "/_buntic/ws") {
|
|
3866
|
+
if (srv.upgrade(req))
|
|
3867
|
+
return;
|
|
3868
|
+
return new Response("WebSocket upgrade failed", { status: 400 });
|
|
3869
|
+
}
|
|
3870
|
+
const emittedAsset = photoProcessor.emittedAssets.get(pathname) || seoEngine.emittedAssets.get(pathname);
|
|
3871
|
+
if (emittedAsset) {
|
|
3872
|
+
return new Response(new Uint8Array(emittedAsset.bytes), {
|
|
3873
|
+
headers: {
|
|
3874
|
+
"Content-Type": "image/webp",
|
|
3875
|
+
"Cache-Control": "public, max-age=31536000, immutable"
|
|
3876
|
+
}
|
|
3877
|
+
});
|
|
3878
|
+
}
|
|
3879
|
+
const seoResponse = await tryServeSeoRoute(pathname, config, engine);
|
|
3880
|
+
if (seoResponse)
|
|
3881
|
+
return seoResponse;
|
|
3882
|
+
const clean = pathname.replace(/^\/+|\/+$/g, "").replace(/\.html$/, "");
|
|
3883
|
+
const candidateRelPaths = clean === "" || clean === "index" ? ["index.html"] : [`${clean}.html`, join19(clean, "index.html")];
|
|
3884
|
+
for (const relCand of candidateRelPaths) {
|
|
3885
|
+
const cand = resolveSafeStaticFile(config.pagesDir, relCand);
|
|
3886
|
+
if (!cand)
|
|
3887
|
+
continue;
|
|
3888
|
+
try {
|
|
3889
|
+
const loaderPath = findCoLocatedLoader(cand);
|
|
3890
|
+
let props = {};
|
|
3891
|
+
let routeSeo = undefined;
|
|
3892
|
+
if (loaderPath) {
|
|
3893
|
+
const globalData = await engine.loadData();
|
|
3894
|
+
const loaderResult = await executeStaticLoader(loaderPath, globalData, {
|
|
3895
|
+
cacheBust: true
|
|
3896
|
+
});
|
|
3897
|
+
props = loaderResult.props;
|
|
3898
|
+
routeSeo = loaderResult.seo;
|
|
3899
|
+
}
|
|
3900
|
+
const normalizedUrlPath = clean === "" || clean === "index" ? "/" : `/${clean}`;
|
|
3901
|
+
return await renderDevPage({
|
|
3902
|
+
templatePath: cand,
|
|
3903
|
+
urlPath: normalizedUrlPath,
|
|
3904
|
+
props,
|
|
3905
|
+
routeSeo,
|
|
3906
|
+
engine,
|
|
3907
|
+
photoProcessor,
|
|
3908
|
+
seoEngine
|
|
3909
|
+
});
|
|
3910
|
+
} catch (err) {
|
|
3911
|
+
return renderErrorResponse("[Buntic Template Error]", err);
|
|
3912
|
+
}
|
|
3913
|
+
}
|
|
3914
|
+
try {
|
|
3915
|
+
const globalData = await engine.loadData();
|
|
3916
|
+
const routes = await resolveAllRoutes(config, globalData, { cacheBust: true });
|
|
3917
|
+
const cleanRequested = pathname === "" || pathname === "/" ? "/" : "/" + pathname.replace(/^\/+|\/+$/g, "");
|
|
3918
|
+
const matchedRoute = routes.find((r) => r.urlPath === cleanRequested);
|
|
3919
|
+
if (matchedRoute) {
|
|
3920
|
+
return await renderDevPage({
|
|
3921
|
+
templatePath: matchedRoute.templateFilePath,
|
|
3922
|
+
urlPath: matchedRoute.urlPath,
|
|
3923
|
+
params: matchedRoute.params,
|
|
3924
|
+
props: matchedRoute.props,
|
|
3925
|
+
routeSeo: matchedRoute.seo,
|
|
3926
|
+
engine,
|
|
3927
|
+
photoProcessor,
|
|
3928
|
+
seoEngine
|
|
3929
|
+
});
|
|
3930
|
+
}
|
|
3931
|
+
} catch (err) {
|
|
3932
|
+
return renderErrorResponse("[Buntic Dynamic Route Error]", err);
|
|
3933
|
+
}
|
|
3934
|
+
if (engine.generatedPageStyles.has(pathname)) {
|
|
3935
|
+
const css = engine.generatedPageStyles.get(pathname);
|
|
3936
|
+
return new Response(css, {
|
|
3937
|
+
headers: {
|
|
3938
|
+
"Content-Type": "text/css; charset=utf-8",
|
|
3939
|
+
"Cache-Control": "no-store, no-cache, must-revalidate"
|
|
3940
|
+
}
|
|
3941
|
+
});
|
|
3942
|
+
}
|
|
3943
|
+
const staticCandidates = [
|
|
3944
|
+
resolveSafeStaticFile(config.publicDir, pathname),
|
|
3945
|
+
resolveSafeStaticFile(config.root, pathname),
|
|
3946
|
+
resolveSafeStaticFile(join19(config.root, "src"), pathname)
|
|
3947
|
+
];
|
|
3948
|
+
for (const staticFile of staticCandidates) {
|
|
3949
|
+
if (staticFile && existsSync20(staticFile)) {
|
|
3950
|
+
return serveFileWithTranspiler(staticFile);
|
|
3951
|
+
}
|
|
3952
|
+
}
|
|
3953
|
+
let routes = [];
|
|
3954
|
+
try {
|
|
3955
|
+
const globalData = await engine.loadData();
|
|
3956
|
+
routes = await resolveAllRoutes(config, globalData);
|
|
3957
|
+
} catch {}
|
|
3958
|
+
return renderNotFoundResponse(pathname, routes);
|
|
3959
|
+
}
|
|
3960
|
+
});
|
|
3961
|
+
return {
|
|
3962
|
+
server,
|
|
3963
|
+
port: config.port,
|
|
3964
|
+
stop: () => {
|
|
3965
|
+
watcher.close();
|
|
3966
|
+
server.stop();
|
|
3967
|
+
}
|
|
3968
|
+
};
|
|
3969
|
+
}
|
|
3970
|
+
|
|
3971
|
+
// src/init.ts
|
|
3972
|
+
import { existsSync as existsSync21, mkdirSync as mkdirSync4, readdirSync as readdirSync6, cpSync as cpSync3 } from "fs";
|
|
3973
|
+
import { join as join20, resolve as resolve8 } from "path";
|
|
3974
|
+
var AVAILABLE_TEMPLATES = ["blank", "simple"];
|
|
3975
|
+
function copyTemplateDirectory(srcDir, destDir) {
|
|
3976
|
+
let count = 0;
|
|
3977
|
+
mkdirSync4(destDir, { recursive: true });
|
|
3978
|
+
for (const entry of readdirSync6(srcDir, { withFileTypes: true })) {
|
|
3979
|
+
if (entry.name === "package.json") {
|
|
3980
|
+
continue;
|
|
3981
|
+
}
|
|
3982
|
+
const srcPath = join20(srcDir, entry.name);
|
|
3983
|
+
const targetName = entry.name === "_gitignore" ? ".gitignore" : entry.name;
|
|
3984
|
+
const destPath = join20(destDir, targetName);
|
|
3985
|
+
if (entry.isDirectory()) {
|
|
3986
|
+
count += copyTemplateDirectory(srcPath, destPath);
|
|
3987
|
+
} else if (entry.isFile()) {
|
|
3988
|
+
cpSync3(srcPath, destPath);
|
|
3989
|
+
count++;
|
|
3990
|
+
}
|
|
3991
|
+
}
|
|
3992
|
+
return count;
|
|
3993
|
+
}
|
|
3994
|
+
function initProject(options = {}) {
|
|
3995
|
+
const templateName = options.template || "blank";
|
|
3996
|
+
if (!AVAILABLE_TEMPLATES.includes(templateName)) {
|
|
3997
|
+
throw new Error(`[Buntic] Unknown template "${options.template}". Available templates: ${AVAILABLE_TEMPLATES.join(", ")}.`);
|
|
3998
|
+
}
|
|
3999
|
+
const targetDir = resolve8(process.cwd(), options.targetDir || ".");
|
|
4000
|
+
const includeSkills = options.includeSkills ?? true;
|
|
4001
|
+
const force = options.force ?? false;
|
|
4002
|
+
const pkgRoot = getPackageRoot();
|
|
4003
|
+
const templateDir = join20(pkgRoot, "templates", templateName);
|
|
4004
|
+
if (!existsSync21(templateDir)) {
|
|
4005
|
+
throw new Error(`[Buntic] Template directory not found: "${templateDir}"`);
|
|
4006
|
+
}
|
|
4007
|
+
if (existsSync21(targetDir) && !force) {
|
|
4008
|
+
const existingEntries = readdirSync6(targetDir).filter((name) => name !== ".git" && name !== ".DS_Store");
|
|
4009
|
+
if (existingEntries.length > 0) {
|
|
4010
|
+
throw new Error(`[Buntic] Target directory "${targetDir}" is not empty.
|
|
4011
|
+
` + ` Pass a new directory name (e.g. "buntic init my-site") or use --force to initialize anyway.`);
|
|
4012
|
+
}
|
|
4013
|
+
}
|
|
4014
|
+
mkdirSync4(targetDir, { recursive: true });
|
|
4015
|
+
let filesCopied = copyTemplateDirectory(templateDir, targetDir);
|
|
4016
|
+
let skillsDir = null;
|
|
4017
|
+
if (includeSkills) {
|
|
4018
|
+
const srcSkillsDir = join20(pkgRoot, "templates", "skills", "buntic");
|
|
4019
|
+
if (existsSync21(srcSkillsDir)) {
|
|
4020
|
+
skillsDir = join20(targetDir, ".agents", "skills", "buntic");
|
|
4021
|
+
filesCopied += copyTemplateDirectory(srcSkillsDir, skillsDir);
|
|
4022
|
+
}
|
|
4023
|
+
}
|
|
4024
|
+
syncProjectTypes(targetDir);
|
|
4025
|
+
return {
|
|
4026
|
+
targetDir,
|
|
4027
|
+
template: templateName,
|
|
4028
|
+
skillsDir,
|
|
4029
|
+
filesCopied
|
|
4030
|
+
};
|
|
4031
|
+
}
|
|
4032
|
+
|
|
4033
|
+
// src/cli.ts
|
|
4034
|
+
async function runCLI(args) {
|
|
4035
|
+
registerBunticModuleResolver();
|
|
4036
|
+
const command = args[0] || "help";
|
|
4037
|
+
if (command === "--version" || command === "-v") {
|
|
4038
|
+
const pkg = await Bun.file(`${getPackageRoot()}/package.json`).json();
|
|
4039
|
+
console.log(`buntic v${pkg.version}`);
|
|
4040
|
+
return;
|
|
4041
|
+
}
|
|
4042
|
+
if (command === "help" || command === "--help" || command === "-h") {
|
|
4043
|
+
printHelp();
|
|
4044
|
+
return;
|
|
4045
|
+
}
|
|
4046
|
+
let targetDir = ".";
|
|
4047
|
+
let port;
|
|
4048
|
+
let outDir;
|
|
4049
|
+
let cleanCache = false;
|
|
4050
|
+
let template;
|
|
4051
|
+
let includeSkills = true;
|
|
4052
|
+
let force = false;
|
|
4053
|
+
for (let i = 1;i < args.length; i++) {
|
|
4054
|
+
const arg = args[i];
|
|
4055
|
+
if (arg === "--port" || arg === "-p") {
|
|
4056
|
+
const next = args[++i];
|
|
4057
|
+
const parsed = Number(next);
|
|
4058
|
+
if (!next || !Number.isInteger(parsed) || parsed < 1 || parsed > 65535) {
|
|
4059
|
+
console.error(`\x1B[31mInvalid port value:\x1B[0m "${next ?? ""}". Expected an integer between 1 and 65535.`);
|
|
4060
|
+
process.exit(1);
|
|
4061
|
+
}
|
|
4062
|
+
port = parsed;
|
|
4063
|
+
} else if (arg === "--outdir" || arg === "-o") {
|
|
4064
|
+
const next = args[++i];
|
|
4065
|
+
if (!next || next.startsWith("-")) {
|
|
4066
|
+
console.error(`\x1B[31mMissing value for ${arg}.\x1B[0m`);
|
|
4067
|
+
process.exit(1);
|
|
4068
|
+
}
|
|
4069
|
+
outDir = next;
|
|
4070
|
+
} else if (arg === "--template" || arg === "-t") {
|
|
4071
|
+
const next = args[++i];
|
|
4072
|
+
if (!next || next.startsWith("-")) {
|
|
4073
|
+
console.error(`\x1B[31mMissing value for ${arg}.\x1B[0m Available templates: ${AVAILABLE_TEMPLATES.join(", ")}`);
|
|
4074
|
+
process.exit(1);
|
|
4075
|
+
}
|
|
4076
|
+
template = next;
|
|
4077
|
+
} else if (arg === "--no-skills") {
|
|
4078
|
+
includeSkills = false;
|
|
4079
|
+
} else if (arg === "--force" || arg === "-f") {
|
|
4080
|
+
force = true;
|
|
4081
|
+
} else if (arg === "--clean-cache" || arg === "--clean") {
|
|
4082
|
+
cleanCache = true;
|
|
4083
|
+
} else if (!arg.startsWith("-")) {
|
|
4084
|
+
targetDir = arg;
|
|
4085
|
+
}
|
|
4086
|
+
}
|
|
4087
|
+
try {
|
|
4088
|
+
if (command === "init") {
|
|
4089
|
+
const result = initProject({
|
|
4090
|
+
targetDir,
|
|
4091
|
+
template,
|
|
4092
|
+
includeSkills,
|
|
4093
|
+
force
|
|
4094
|
+
});
|
|
4095
|
+
const relTarget = relative10(process.cwd(), result.targetDir) || ".";
|
|
4096
|
+
console.log(`
|
|
4097
|
+
\u26A1 \x1B[36m[Buntic]\x1B[0m Initialized new project (\x1B[33m${result.template}\x1B[0m) in: \x1B[32m${result.targetDir}\x1B[0m`);
|
|
4098
|
+
console.log(` \u2714 Created ${result.filesCopied} file(s) (no package.json required)`);
|
|
4099
|
+
if (result.skillsDir) {
|
|
4100
|
+
console.log(` \u2714 Installed Buntic agent skill in .agents/skills/buntic`);
|
|
4101
|
+
}
|
|
4102
|
+
console.log(` \u2714 Generated TypeScript definitions in .buntic/types/`);
|
|
4103
|
+
console.log(`
|
|
4104
|
+
\x1B[1mNext steps:\x1B[0m`);
|
|
4105
|
+
if (relTarget !== ".") {
|
|
4106
|
+
console.log(` cd ${relTarget}`);
|
|
4107
|
+
}
|
|
4108
|
+
console.log(` buntic dev
|
|
4109
|
+
`);
|
|
4110
|
+
return;
|
|
4111
|
+
}
|
|
4112
|
+
if (command === "clean") {
|
|
4113
|
+
const config = await resolveConfig(targetDir);
|
|
4114
|
+
console.log(`
|
|
4115
|
+
\uD83E\uDDF9 \x1B[36m[Buntic]\x1B[0m Cleaning build and cache directories for: \x1B[33m${config.root}\x1B[0m`);
|
|
4116
|
+
if (existsSync22(config.outDir)) {
|
|
4117
|
+
rmSync4(config.outDir, { recursive: true, force: true });
|
|
4118
|
+
console.log(` \u2714 Removed ${config.outDir}`);
|
|
4119
|
+
}
|
|
4120
|
+
const cache = new AssetCache(config.cacheDir);
|
|
4121
|
+
await cache.clean();
|
|
4122
|
+
console.log(` \u2714 Cleaned ${config.cacheDir}`);
|
|
4123
|
+
console.log(`\x1B[32m\u2714\x1B[0m Project cleaned successfully.
|
|
4124
|
+
`);
|
|
4125
|
+
return;
|
|
4126
|
+
}
|
|
4127
|
+
if (command === "dev") {
|
|
4128
|
+
const config = await resolveConfig(targetDir, { port });
|
|
4129
|
+
syncProjectTypes(config.root);
|
|
4130
|
+
if (cleanCache) {
|
|
4131
|
+
const cache = new AssetCache(config.cacheDir);
|
|
4132
|
+
await cache.clean();
|
|
4133
|
+
console.log(`\x1B[32m\u2714\x1B[0m Cache cleaned.`);
|
|
4134
|
+
}
|
|
4135
|
+
console.log(`
|
|
4136
|
+
\uD83D\uDE80 \x1B[36m[Buntic]\x1B[0m Starting dev server for: \x1B[33m${config.root}\x1B[0m`);
|
|
4137
|
+
const devInstance = startDevServer(config);
|
|
4138
|
+
console.log(` \u279C Local: \x1B[32mhttp://localhost:${devInstance.port}/\x1B[0m`);
|
|
4139
|
+
console.log(` \u279C Live reload enabled via WebSockets.
|
|
4140
|
+
`);
|
|
4141
|
+
process.on("SIGINT", () => {
|
|
4142
|
+
console.log(`
|
|
4143
|
+
\x1B[33m[Buntic]\x1B[0m Shutting down server...`);
|
|
4144
|
+
devInstance.stop();
|
|
4145
|
+
process.exit(0);
|
|
4146
|
+
});
|
|
4147
|
+
} else if (command === "build") {
|
|
4148
|
+
const config = await resolveConfig(targetDir, { outDir });
|
|
4149
|
+
syncProjectTypes(config.root);
|
|
4150
|
+
console.log(`
|
|
4151
|
+
\uD83D\uDCE6 \x1B[36m[Buntic]\x1B[0m Building static site for: \x1B[33m${config.root}\x1B[0m`);
|
|
4152
|
+
const builder = new Builder(config);
|
|
4153
|
+
const result = await builder.build({ cleanCache });
|
|
4154
|
+
console.log(`\x1B[32m\u2714\x1B[0m Successfully built ${result.pagesCount} page(s) in ${result.durationMs}ms`);
|
|
4155
|
+
console.log(`\x1B[32m\u2714\x1B[0m Output directory: \x1B[33m${config.outDir}\x1B[0m
|
|
4156
|
+
`);
|
|
4157
|
+
} else {
|
|
4158
|
+
console.error(`\x1B[31mUnknown command:\x1B[0m "${command}"`);
|
|
4159
|
+
printHelp();
|
|
4160
|
+
process.exit(1);
|
|
4161
|
+
}
|
|
4162
|
+
} catch (err) {
|
|
4163
|
+
console.error(`
|
|
4164
|
+
\x1B[31m${getErrorMessage(err)}\x1B[0m
|
|
4165
|
+
`);
|
|
4166
|
+
process.exit(1);
|
|
4167
|
+
}
|
|
4168
|
+
}
|
|
4169
|
+
function printHelp() {
|
|
4170
|
+
console.log(`
|
|
4171
|
+
\x1B[1mBuntic\x1B[0m - Lightweight zero-dependency static site generator for Bun
|
|
4172
|
+
|
|
4173
|
+
\x1B[1mUSAGE:\x1B[0m
|
|
4174
|
+
buntic <command> [directory] [options]
|
|
4175
|
+
|
|
4176
|
+
\x1B[1mCOMMANDS:\x1B[0m
|
|
4177
|
+
init [dir] Initialize a new Buntic project (zero package.json)
|
|
4178
|
+
dev [dir] Start the development server with live reload
|
|
4179
|
+
build [dir] Build the static site for production into dist/
|
|
4180
|
+
clean [dir] Remove dist/ and .buntic/cache/ directories
|
|
4181
|
+
help Show this help message
|
|
4182
|
+
|
|
4183
|
+
\x1B[1mOPTIONS:\x1B[0m
|
|
4184
|
+
-t, --template <name> Template for init: ${AVAILABLE_TEMPLATES.join(", ")} (default: blank)
|
|
4185
|
+
--no-skills Skip installing agent skills in .agents/skills/buntic
|
|
4186
|
+
-f, --force Allow init in a non-empty directory
|
|
4187
|
+
-p, --port <port> Port to run dev server on (default: 3000)
|
|
4188
|
+
-o, --outdir <dir> Output directory for build (default: dist)
|
|
4189
|
+
--clean-cache Clean persistent asset cache before build/dev
|
|
4190
|
+
-v, --version Show version number
|
|
4191
|
+
-h, --help Show help
|
|
4192
|
+
|
|
4193
|
+
\x1B[1mEXAMPLES:\x1B[0m
|
|
4194
|
+
$ buntic init mi-sitio
|
|
4195
|
+
$ buntic init mi-sitio --template simple
|
|
4196
|
+
$ buntic dev
|
|
4197
|
+
$ buntic dev my-site --port 8080
|
|
4198
|
+
$ buntic build
|
|
4199
|
+
$ buntic build my-site --outdir ./public_html --clean-cache
|
|
4200
|
+
$ buntic clean
|
|
4201
|
+
`);
|
|
4202
|
+
}
|
|
4203
|
+
|
|
4204
|
+
// bin/buntic.ts
|
|
4205
|
+
await runCLI(process.argv.slice(2));
|