@brightsideoy/kama 1.0.0-alpha.20 → 1.0.0-alpha.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/content/definitions/blocks/image-gallery.yaml +34 -0
  2. package/content/definitions/blocks/youtube.yaml +8 -0
  3. package/content/definitions/field-sets/access.yaml +10 -0
  4. package/content/definitions/field-sets/page-base.yaml +16 -1
  5. package/content/definitions/taxonomies/media-tag.yaml +15 -0
  6. package/definitions/editor/default.ts +15 -1
  7. package/dist/assets/AssetEditor-B4W7tV1a.js +1 -0
  8. package/dist/assets/AssetEditor-D9sz6bfN.css +1 -0
  9. package/dist/assets/CmsFieldTaxonomy-CVlKL-l2.css +1 -0
  10. package/dist/assets/CmsFieldTaxonomy-C_AwHDwY.js +1 -0
  11. package/dist/assets/{CmsHelp-DyPJLGGi.js → CmsHelp-BQkr9KyU.js} +1 -1
  12. package/dist/assets/{CmsPublisher-DNLwjirk.js → CmsPublisher-XSCPrp5L.js} +1 -1
  13. package/dist/assets/NodeEditor-4TsNvk2f.css +1 -0
  14. package/dist/assets/NodeEditor-DA5GRtRP.js +161 -0
  15. package/dist/assets/{TrashWorkspace-DgIg1v6t.js → TrashWorkspace-CATe46WF.js} +1 -1
  16. package/dist/assets/index-CY0VYSyt.css +1 -0
  17. package/dist/assets/index-DdG9Pozx.js +14 -0
  18. package/dist/assets/{plus-FQRsZBoJ.js → plus-CX_GHzXs.js} +1 -1
  19. package/dist/assets/useNodes-CqFlc72m.js +1 -0
  20. package/dist/{dist-D_Q1y4Kh.js → dist-3Xc2TTZw.js} +1117 -456
  21. package/dist/index.html +4 -4
  22. package/dist/index.js +1117 -456
  23. package/dist/schema-compiler.js +1 -1
  24. package/package.json +5 -5
  25. package/schema.sql +10 -0
  26. package/templates/astro-starter/src/components/global/NavigationMenu.astro +11 -3
  27. package/dist/assets/AssetEditor-D5j7pwcK.css +0 -1
  28. package/dist/assets/AssetEditor-Dt1zCR7_.js +0 -1
  29. package/dist/assets/NodeEditor-CiXQKXK1.js +0 -147
  30. package/dist/assets/NodeEditor-pZI3gu4a.css +0 -1
  31. package/dist/assets/index-DQ6_RmCI.js +0 -14
  32. package/dist/assets/index-DcKiaRjI.css +0 -1
  33. package/dist/assets/useNodes-D2-VxsxR.js +0 -1
  34. package/templates/astro-starter/old_src/components/blocks/BlockRenderer.astro +0 -143
  35. package/templates/astro-starter/old_src/components/blocks/ColumnLayout.astro +0 -67
  36. package/templates/astro-starter/old_src/components/blocks/HeaderImage.astro +0 -126
  37. package/templates/astro-starter/old_src/components/blocks/Hero.astro +0 -218
  38. package/templates/astro-starter/old_src/components/blocks/HtmlBlock.astro +0 -25
  39. package/templates/astro-starter/old_src/components/blocks/ImageBlock.astro +0 -91
  40. package/templates/astro-starter/old_src/components/blocks/NodeList.astro +0 -274
  41. package/templates/astro-starter/old_src/components/blocks/TextBlock.astro +0 -15
  42. package/templates/astro-starter/old_src/components/global/Breadcrumb.astro +0 -108
  43. package/templates/astro-starter/old_src/components/global/Footer.astro +0 -50
  44. package/templates/astro-starter/old_src/components/global/Header.astro +0 -171
  45. package/templates/astro-starter/old_src/components/global/MetaHead.astro +0 -266
  46. package/templates/astro-starter/old_src/components/global/NavigationMenu.astro +0 -413
  47. package/templates/astro-starter/old_src/components/ui/KamaImage.astro +0 -180
  48. package/templates/astro-starter/old_src/layouts/SkeletonLayout.astro +0 -56
  49. package/templates/astro-starter/old_src/layouts/StandardLayout.astro +0 -63
  50. package/templates/astro-starter/old_src/lib/cms.ts +0 -219
  51. package/templates/astro-starter/old_src/lib/media/kama-image-service.ts +0 -67
  52. package/templates/astro-starter/old_src/lib/media/media-proxy.ts +0 -148
  53. package/templates/astro-starter/old_src/lib/media/media-url.ts +0 -112
  54. package/templates/astro-starter/old_src/middleware.ts +0 -536
  55. package/templates/astro-starter/old_src/pages/404.astro +0 -46
  56. package/templates/astro-starter/old_src/pages/[...slug].astro +0 -311
  57. package/templates/astro-starter/old_src/pages/api/load-nodes.ts +0 -68
  58. package/templates/astro-starter/old_src/pages/api/partials/node-cards.astro +0 -101
  59. package/templates/astro-starter/old_src/pages/llms-full.txt.ts +0 -171
  60. package/templates/astro-starter/old_src/pages/llms.txt.ts +0 -113
  61. package/templates/astro-starter/old_src/pages/media/[...path].ts +0 -14
  62. package/templates/astro-starter/old_src/pages/partials/footer.astro +0 -69
  63. package/templates/astro-starter/old_src/pages/partials/nav.astro +0 -141
  64. package/templates/astro-starter/old_src/styles/standard-theme.css +0 -157
  65. package/templates/astro-starter/old_src/utils/tiptap.ts +0 -113
@@ -1,536 +0,0 @@
1
- // src/middleware.ts
2
-
3
- import { defineMiddleware } from "astro:middleware";
4
-
5
- /**
6
- * Safely extracts environment variables across Astro 7, Node.js, and Cloudflare Workers
7
- * without triggering the `@astrojs/cloudflare` runtime.env getter exception.
8
- */
9
- async function getSafeEnv(locals: any): Promise<Record<string, any>> {
10
- // 1. Try native Cloudflare Workers module (Astro 5+ / workerd)
11
- try {
12
- // @ts-ignore
13
- const cf = await import("cloudflare:workers");
14
- if (cf?.env) return cf.env;
15
- } catch (e) {
16
- // Not running inside a Cloudflare Worker container
17
- }
18
-
19
- // 2. Safe check for locals.runtime / cfContext (Local Node.js / Hono)
20
- const runtime = locals?.runtime || locals?.cfContext;
21
- if (runtime && typeof runtime === "object") {
22
- if ("CMS_WORKER" in runtime || "PUBLIC_API_URL" in runtime) {
23
- return runtime;
24
- }
25
-
26
- // Safely check property descriptor to avoid triggering throwing getters
27
- try {
28
- const desc = Object.getOwnPropertyDescriptor(runtime, "env");
29
- if (desc && !desc.get) {
30
- return runtime.env;
31
- }
32
- } catch (e) {
33
- // Ignore getter throws
34
- }
35
- }
36
-
37
- // 3. Fallback for standalone Node.js mode
38
- return typeof process !== "undefined" ? process.env || {} : {};
39
- }
40
-
41
- export const onRequest = defineMiddleware(async (context, next) => {
42
- const pathname = context.url.pathname;
43
- const pathLower = pathname.toLowerCase();
44
-
45
- // 🎯 Detect if we are previewing a draft or looking at a snapshot revision
46
- const isPreview = context.url.searchParams.get("preview") === "true";
47
- const hasRevision = context.url.searchParams.has("revisionId");
48
- const isTimeTraveling = isPreview || hasRevision;
49
-
50
- // 🎯 Detect Local Vite Dev Mode to bypass edge caching locally
51
- const isDev = import.meta.env.DEV;
52
-
53
- // 🎯 Safe dual-environment context extraction
54
- const workerEnv = await getSafeEnv(context.locals);
55
-
56
- // Attach to locals so Astro components (like Header.astro) don't have to re-evaluate it
57
- (context.locals as any).safeEnv = workerEnv;
58
-
59
- // 🎯 Safe ctx extraction (Fixing the runtime.ctx crash in Astro 6/7)
60
- let cfContext = (context.locals as any).cfContext;
61
- if (!cfContext) {
62
- const runtime = (context.locals as any).runtime;
63
- if (runtime && typeof runtime === "object") {
64
- try {
65
- const desc = Object.getOwnPropertyDescriptor(runtime, "ctx");
66
- if (desc && !desc.get) {
67
- cfContext = runtime.ctx;
68
- }
69
- } catch (e) { }
70
- }
71
- }
72
- cfContext = cfContext || {};
73
-
74
- const HTML_CACHE = workerEnv?.HTML_CACHE; // KV Namespace binding
75
-
76
- // 🎯 0. INSTANT EDGE SPAM DROP (Blocks bots before hit to CMS worker/database)
77
- const isSpam =
78
- pathLower.includes("wp-") ||
79
- pathLower.includes("wordpress") ||
80
- pathLower.endsWith(".php") ||
81
- pathLower === "/wp";
82
-
83
- if (isSpam) {
84
- return new Response("Not Found", { status: 404 });
85
- }
86
-
87
- // 🎯 0B. DIRECT MEDIA PROXY VIA SERVICE BINDING WITH SURGICAL WORKER CACHING
88
- if (pathname.startsWith("/media/")) {
89
- const cache = typeof caches !== "undefined" && caches.default ? caches.default : null;
90
- // Construct a clean cache key ignoring session headers
91
- const cacheKey = new Request(context.url.toString(), { method: "GET" });
92
-
93
- // 1. Check surgical Worker Edge Cache for pre-encoded media (15ms HIT)
94
- if (!isDev && cache) {
95
- try {
96
- const cachedResponse = await cache.match(cacheKey);
97
- if (cachedResponse) {
98
- return cachedResponse;
99
- }
100
- } catch (e) {
101
- // Fall back to fetch if cache read fails
102
- }
103
- }
104
-
105
- // 2. Cold Fetch: Pass to CMS worker for AVIF transformation
106
- const cmsWorker = workerEnv?.CMS_WORKER;
107
- const envApiUrl = import.meta.env?.PUBLIC_API_URL;
108
- const workerApiUrl = workerEnv?.PUBLIC_API_URL;
109
- const baseApiUrl = String(envApiUrl || workerApiUrl || "https://kama.kamaengine.com");
110
- const cleanApiUrl = baseApiUrl.endsWith("/") ? baseApiUrl.slice(0, -1) : baseApiUrl;
111
-
112
- const mediaUrl = `${cleanApiUrl}${pathname}${context.url.search}`;
113
- const mediaReq = new Request(mediaUrl, { headers: context.request.headers });
114
-
115
- let mediaResponse: Response;
116
- if (cmsWorker && typeof cmsWorker.fetch === "function") {
117
- mediaResponse = await cmsWorker.fetch(mediaReq);
118
- } else {
119
- mediaResponse = await fetch(mediaReq);
120
- }
121
-
122
- const newHeaders = new Headers(mediaResponse.headers);
123
-
124
- if (!isDev) {
125
- newHeaders.set("Cache-Control", "public, max-age=31536000, s-maxage=31536000, immutable");
126
- }
127
- newHeaders.set("Access-Control-Allow-Origin", "*");
128
-
129
- const finalResponse = new Response(mediaResponse.body, {
130
- status: mediaResponse.status,
131
- statusText: mediaResponse.statusText,
132
- headers: newHeaders
133
- });
134
-
135
- // 3. Store ONLY successful image transformations in Worker Edge Cache
136
- if (!isDev && cache && mediaResponse.status === 200) {
137
- if (cfContext && typeof cfContext.waitUntil === 'function') {
138
- cfContext.waitUntil(cache.put(cacheKey, finalResponse.clone()));
139
- } else {
140
- cache.put(cacheKey, finalResponse.clone()).catch(() => { });
141
- }
142
- }
143
-
144
- return finalResponse;
145
- }
146
-
147
- // 🎯 0C. DIRECT EDGE INTERCEPT FOR CACHE PURGE ENDPOINT
148
- if (pathname === "/api/purge" || pathname === "/api/purge/") {
149
- if (context.request.method !== "POST") {
150
- return new Response(JSON.stringify({ error: "Method Not Allowed" }), {
151
- status: 405,
152
- headers: { "Content-Type": "application/json" },
153
- });
154
- }
155
-
156
- const authHeader = context.request.headers.get("Authorization");
157
- const expectedToken = workerEnv.FRONTEND_API_SECRET || workerEnv.CLOUDFLARE_API_TOKEN;
158
-
159
- if (!expectedToken || authHeader !== `Bearer ${expectedToken}`) {
160
- return new Response(JSON.stringify({ error: "Unauthorized Token Mismatch" }), {
161
- status: 401,
162
- headers: { "Content-Type": "application/json" },
163
- });
164
- }
165
-
166
- try {
167
- const body = await context.request.json();
168
- const cache = typeof caches !== "undefined" && caches.default ? caches.default : null;
169
- const origin = context.url.origin;
170
-
171
- if (body.purge_everything && !HTML_CACHE) {
172
- return new Response(JSON.stringify({ success: false, error: "HTML_CACHE binding is unavailable" }), {
173
- status: 503,
174
- headers: { "Content-Type": "application/json" },
175
- });
176
- }
177
-
178
- // A. Purge Workers Caching Layer (Astro cfContext)
179
- if (typeof cfContext?.cache?.purge === 'function') {
180
- try {
181
- // 🎯 FIX: Only execute global purge if the CMS explicitly requested it!
182
- if (body.purge_everything) {
183
- await cfContext.cache.purge({ purgeEverything: true });
184
- console.log("✅ New Cloudflare Workers Cache Engine Purged (Global)");
185
- }
186
- } catch (e) {
187
- console.error("❌ Failed to purge new Workers Cache Engine", e);
188
- }
189
- }
190
-
191
- // B. Version-Based Instant Invalidation (0ms KV Write)
192
- if (HTML_CACHE) {
193
- try {
194
- const now = Date.now().toString();
195
-
196
- if (body.purge_everything) {
197
- // 🎯 GLOBAL PURGE: Bumping site_version instantly invalidates ALL KV pages globally!
198
- try {
199
- await HTML_CACHE.put("site_version", now);
200
- await HTML_CACHE.put("v:/", now);
201
- console.log(`✅ [Version Tagging] Global site_version updated to ${now}`);
202
- } catch (kvLimitErr: any) {
203
- console.error(`[KV Error] Global version bump failed: ${kvLimitErr.message}`);
204
- return new Response(JSON.stringify({ success: false, error: "Failed to invalidate HTML KV cache" }), {
205
- status: 503,
206
- headers: { "Content-Type": "application/json" },
207
- });
208
- }
209
- } else if (Array.isArray(body.urls) && body.urls.length > 0) {
210
- // Shared fragments and cross-page content depend on the site version too.
211
- await HTML_CACHE.put("site_version", now);
212
-
213
- // 🎯 SURGICAL PURGE: Parallel execution for page version bumps safely wrapped for quota
214
- const purgeTasks = body.urls.map(async (targetUrl: string) => {
215
- const urlPath = new URL(targetUrl).pathname;
216
- const cleanPath = urlPath.replace(/\/$/, "") || "/";
217
- try {
218
- await HTML_CACHE.put(`v:${cleanPath}`, now);
219
- } catch (kvLimitErr: any) {
220
- console.warn(`[KV Warning] Skipped version tag for ${cleanPath}: ${kvLimitErr.message}`);
221
- }
222
- });
223
- await Promise.all(purgeTasks);
224
- console.log(`✅ [Version Tagging] Updated versions for ${body.urls.length} URLs`);
225
- // CMS CacheManager will automatically send the X-Cache-Warmer requests now!
226
- }
227
- } catch (kvErr) {
228
- console.error("❌ KV Version Tagging Error:", kvErr);
229
- }
230
- }
231
-
232
- // C. Global Legacy Worker Cache Purge
233
- if (body.purge_everything) {
234
- if (cache) {
235
- const rootUrls = [
236
- origin,
237
- `${origin}/`
238
- ];
239
- for (const url of rootUrls) {
240
- await cache.delete(new Request(url));
241
- }
242
- }
243
-
244
- return new Response(JSON.stringify({
245
- success: true,
246
- message: "All Worker Caches Purged"
247
- }), {
248
- status: 200,
249
- headers: { "Content-Type": "application/json" },
250
- });
251
- }
252
-
253
- // D. Surgical Legacy Worker Cache Purge
254
- if (Array.isArray(body.urls) && body.urls.length > 0) {
255
- const results = [];
256
-
257
- for (const targetUrl of body.urls) {
258
- const cleanUrl = targetUrl.split('?')[0];
259
- const urlNoSlash = cleanUrl.replace(/\/$/, "");
260
- const urlWithSlash = urlNoSlash + "/";
261
- const pathsToClear = [urlNoSlash, urlWithSlash];
262
-
263
- let purged = false;
264
- if (cache) {
265
- for (const p of pathsToClear) {
266
- const res = await cache.delete(new Request(p));
267
- if (res) purged = true;
268
- }
269
- }
270
-
271
- results.push({ url: targetUrl, purged });
272
- }
273
-
274
- return new Response(JSON.stringify({
275
- success: true,
276
- message: "URLs processed and version tags updated",
277
- results
278
- }), {
279
- status: 200,
280
- headers: { "Content-Type": "application/json" },
281
- });
282
- }
283
-
284
- // 🎯 E. SURGICAL DELETION FOR DELETED PAGES
285
- if (Array.isArray(body.deleted_urls) && body.deleted_urls.length > 0) {
286
- const results: any[] = [];
287
-
288
- const deleteTasks = body.deleted_urls.map(async (targetUrl: string) => {
289
- const urlPath = new URL(targetUrl).pathname;
290
- const cleanPath = urlPath.replace(/\/$/, "") || "/";
291
-
292
- let purgedKv = false;
293
-
294
- if (HTML_CACHE) {
295
- try {
296
- const [siteVer, pageVer] = await Promise.all([
297
- HTML_CACHE.get("site_version"),
298
- HTML_CACHE.get(`v:${cleanPath}`)
299
- ]);
300
-
301
- if (siteVer || pageVer) {
302
- const activeCacheKey = `${cleanPath}:v:${siteVer || "1"}:${pageVer || "1"}`;
303
- await HTML_CACHE.delete(activeCacheKey);
304
- purgedKv = true;
305
- }
306
- await HTML_CACHE.delete(`v:${cleanPath}`);
307
- } catch (kvLimitErr: any) {
308
- console.warn(`[KV Warning] Skipped deletion for ${cleanPath}: ${kvLimitErr.message}`);
309
- }
310
- }
311
-
312
- const cleanUrl = targetUrl.split('?')[0];
313
- const urlNoSlash = cleanUrl.replace(/\/$/, "");
314
- const urlWithSlash = urlNoSlash + "/";
315
- const pathsToClear = [urlNoSlash, urlWithSlash];
316
-
317
- let purgedLegacy = false;
318
- if (cache) {
319
- for (const p of pathsToClear) {
320
- const res = await cache.delete(new Request(p));
321
- if (res) purgedLegacy = true;
322
- }
323
- }
324
-
325
- results.push({ url: targetUrl, purgedKv, purgedLegacy });
326
- });
327
-
328
- await Promise.all(deleteTasks);
329
-
330
- return new Response(JSON.stringify({
331
- success: true,
332
- message: "Deleted URLs processed and KV keys permanently removed",
333
- results
334
- }), {
335
- status: 200,
336
- headers: { "Content-Type": "application/json" },
337
- });
338
- }
339
-
340
- return new Response(JSON.stringify({ error: "Invalid payload format" }), {
341
- status: 400,
342
- headers: { "Content-Type": "application/json" },
343
- });
344
-
345
- } catch (err: any) {
346
- return new Response(JSON.stringify({ error: err.message }), {
347
- status: 500,
348
- headers: { "Content-Type": "application/json" },
349
- });
350
- }
351
- }
352
-
353
- // 🎯 1. KV STATIC "FILE" CACHE READ WITH VERSION TAGGING
354
- const isWarmer = context.request.headers.get("X-Cache-Warmer") === "true";
355
-
356
- // 🎯 ARCHITECTURE FIX: Allow HTML partials to be edge-cached alongside regular HTML
357
- const isHtmlPage = !pathname.includes('.') && (!pathname.startsWith('/api/') || pathname.startsWith('/api/partials/'));
358
-
359
- // 🎯 ARCHITECTURE FIX: Include query string for partials so offset=6 and offset=12 have distinct cache keys
360
- const cleanLookupPath = pathname === "/index" || pathname === "/index/"
361
- ? "/"
362
- : (pathname.replace(/\/$/, "") || "/") + (pathname.startsWith('/api/partials/') ? context.url.search : "");
363
-
364
- let activeCacheKey = cleanLookupPath;
365
-
366
- // 🎯 FIX: Retrieve the activeCacheKey versions even if it's a warmer request, so it doesn't overwrite them!
367
- if (!isDev && isHtmlPage && HTML_CACHE && !isTimeTraveling) {
368
- try {
369
- // 🎯 Partials inherit the global site_version so they automatically purge when the CMS publishes
370
- const pageVersionKey = pathname.startsWith('/api/partials/') ? "site_version" : `v:${pathname.replace(/\/$/, "") || "/"}`;
371
-
372
- const [siteVer, pageVer] = await Promise.all([
373
- HTML_CACHE.get("site_version"),
374
- HTML_CACHE.get(pageVersionKey)
375
- ]);
376
-
377
- // 🎯 Combine versions deterministically
378
- activeCacheKey = `${cleanLookupPath}:v:${siteVer || "1"}:${pageVer || "1"}`;
379
-
380
- // 🎯 Only serve cached HTML if it is NOT a warmer request
381
- if (!isWarmer) {
382
- const cachedData = await HTML_CACHE.get(activeCacheKey);
383
- if (cachedData) {
384
- let finalHtml = cachedData;
385
-
386
- try {
387
- if (cachedData.startsWith("{")) {
388
- const parsed = JSON.parse(cachedData);
389
- if (parsed.html) {
390
- finalHtml = parsed.html;
391
- }
392
- }
393
- } catch (jsonErr) {
394
- // Fallback to raw HTML
395
- }
396
-
397
- return new Response(finalHtml, {
398
- status: 200,
399
- headers: {
400
- "Content-Type": "text/html; charset=utf-8",
401
- "X-Cache-Status": "HIT-KV-STATICFILE",
402
- "X-Cache-Key": activeCacheKey,
403
- // Prevent Cloudflare Edge from locking stale HTML in RAM.
404
- // Force Edge to revalidate with Worker logic while keeping browser cache fresh.
405
- "Cache-Control": "public, max-age=0, must-revalidate"
406
- }
407
- });
408
- }
409
- }
410
- } catch (e) {
411
- console.warn("[Middleware] KV lookup bypass:", e);
412
- }
413
- }
414
-
415
- // Process downstream SSR routes
416
- const response = await next();
417
-
418
- // 🎯 2. KV STATIC "FILE" CACHE WRITE (Save HTML under active Version Key)
419
- if (
420
- !isDev &&
421
- isHtmlPage && HTML_CACHE &&
422
- !isTimeTraveling &&
423
- response.status === 200 &&
424
- response.headers.get("content-type")?.includes("text/html")
425
- ) {
426
- const htmlText = await response.clone().text();
427
-
428
- // Extract the TTL injected by Astro SSR
429
- const kvTtlHeader = response.headers.get("X-KV-Expiration");
430
- const kvTtl = kvTtlHeader ? parseInt(kvTtlHeader, 10) : undefined;
431
-
432
- // Clean up the internal header so it doesn't leak to the public browser
433
- response.headers.delete("X-KV-Expiration");
434
-
435
- const writeTask = (async () => {
436
- // 🎯 FIX: Removed `|| isWarmer` here so warmer requests safely write to the existing activeCacheKey
437
- if (activeCacheKey === cleanLookupPath) {
438
- const forcedVersion = Date.now().toString();
439
- try {
440
- // 🎯 FIX: Do NOT overwrite global site_version from a frontend partial cache miss
441
- if (!pathname.startsWith('/api/partials/')) {
442
- await HTML_CACHE.put(`v:${pathname.replace(/\/$/, "") || "/"}`, forcedVersion);
443
- }
444
- const siteVer = await HTML_CACHE.get("site_version") || "1";
445
- const pageVer = pathname.startsWith('/api/partials/') ? siteVer : forcedVersion;
446
- activeCacheKey = `${cleanLookupPath}:v:${siteVer}:${pageVer}`;
447
- } catch (kvLimitErr: any) {
448
- console.warn(`[KV Warning] Skipped prewarm version bump: ${kvLimitErr.message}`);
449
- }
450
- }
451
-
452
- // Save TTL alongside HTML so CDN can properly cache reads
453
- const storedTtl = kvTtl !== undefined ? Math.max(60, kvTtl) : 31536000;
454
- const payload = JSON.stringify({ html: htmlText, ttl: storedTtl });
455
-
456
- try {
457
- if (kvTtl !== undefined) {
458
- await HTML_CACHE.put(activeCacheKey, payload, { expirationTtl: storedTtl });
459
- console.log(`✅ [Middleware] Saved HTML to KV under key: ${activeCacheKey} (Expires in ${storedTtl}s)`);
460
- } else {
461
- await HTML_CACHE.put(activeCacheKey, payload);
462
- console.log(`✅ [Middleware] Saved HTML to KV under key: ${activeCacheKey} (Infinite TTL)`);
463
- }
464
- } catch (kvLimitErr: any) {
465
- console.warn(`[KV Warning] Skipped HTML cache save (Quota limit exceeded): ${kvLimitErr.message}`);
466
- }
467
- })();
468
-
469
- if (cfContext && typeof cfContext.waitUntil === 'function') {
470
- cfContext.waitUntil(writeTask);
471
- } else {
472
- writeTask.catch((e: any) => console.error("KV write error:", e));
473
- }
474
- }
475
-
476
- // 🎯 3. SERVE LLMS & LLXML ENDPOINTS
477
- if (pathname === "/llms.txt" || pathname === "/llms-full.txt") {
478
- response.headers.set("Content-Type", "text/plain; charset=utf-8");
479
- response.headers.set("Cache-Control", "public, max-age=3600");
480
- response.headers.set("Access-Control-Allow-Origin", "*");
481
- return response;
482
- }
483
-
484
- if (pathname === "/llxml.txt") {
485
- response.headers.set("Content-Type", "application/xml; charset=utf-8");
486
- response.headers.set("Cache-Control", "public, max-age=3600");
487
- response.headers.set("Access-Control-Allow-Origin", "*");
488
- return response;
489
- }
490
-
491
- // 🎯 4. STATIC ASSET CACHING FOR COMPRESSED BUNDLES / ASSETS
492
- if (!isDev) {
493
- if (
494
- pathname.startsWith("/_image") ||
495
- pathname.startsWith("/cdn-cgi/image/") ||
496
- pathname.match(/\.(png|jpg|jpeg|webp|avif|svg|gif|ico|woff2?|css|js)$/i)
497
- ) {
498
- response.headers.set(
499
- "Cache-Control",
500
- "public, max-age=31536000, s-maxage=31536000, immutable"
501
- );
502
- response.headers.set("Access-Control-Allow-Origin", "*");
503
- return response;
504
- }
505
- }
506
-
507
- // 🎯 5. SECURITY HEADERS FOR HTML PAGES
508
- if (response.headers.get("content-type")?.includes("text/html")) {
509
- response.headers.set("Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload");
510
- response.headers.set("X-Content-Type-Options", "nosniff");
511
-
512
- // 🎯 Extract origin from env dynamically
513
- const cmsUrl = workerEnv?.PUBLIC_CMS_URL || workerEnv?.PUBLIC_API_URL || "http://localhost:8787";
514
- let cmsOrigin = "";
515
- try {
516
- cmsOrigin = new URL(cmsUrl).origin;
517
- } catch (e) { }
518
-
519
- if (isDev) {
520
- response.headers.set("X-Frame-Options", "ALLOWALL");
521
- response.headers.set(
522
- "Content-Security-Policy",
523
- "default-src 'self' http: https: data: 'unsafe-inline' 'unsafe-eval'; img-src 'self' http: https: data: blob:; connect-src 'self' http: https: ws: wss:; frame-ancestors *;"
524
- );
525
- } else {
526
- // Production headers
527
- response.headers.set("Cross-Origin-Opener-Policy", "same-origin-allow-popups");
528
- response.headers.set(
529
- "Content-Security-Policy",
530
- `default-src 'self' https: data: 'unsafe-inline' 'unsafe-eval'; img-src 'self' https: data: blob:; connect-src 'self' https:; frame-ancestors 'self' https://*.kamaengine.com https://kama.kamaengine.com ${cmsOrigin};`
531
- );
532
- }
533
- }
534
-
535
- return response;
536
- });
@@ -1,46 +0,0 @@
1
- ---
2
- // src/pages/404.astro
3
- import StandardLayout from "../layouts/StandardLayout.astro";
4
-
5
- const node = {
6
- title: "Page Not Found",
7
- summary: "We couldn't find the page you were looking for.",
8
- };
9
- ---
10
-
11
- <StandardLayout
12
- node={node}
13
- isHomePage={false}
14
- hasSidebar={false}
15
- content={{}}
16
- normalizedSlug="404"
17
- headerBlocks={[]}
18
- >
19
- <div class="error-page">
20
- <h1>404</h1>
21
- <h2>Page Not Found</h2>
22
- <p>Sorry, the page you are looking for doesn't exist or has been moved.</p>
23
- <a href="/" class="button">Go back home</a>
24
- </div>
25
- </StandardLayout>
26
-
27
- <style>
28
- .error-page {
29
- text-align: center;
30
- padding: 100px 20px;
31
- }
32
- .error-page h1 {
33
- font-size: 6rem;
34
- margin-bottom: 0;
35
- color: #0284c7;
36
- }
37
- .button {
38
- display: inline-block;
39
- margin-top: 24px;
40
- padding: 12px 24px;
41
- background: #0f172a;
42
- color: white;
43
- text-decoration: none;
44
- border-radius: 4px;
45
- }
46
- </style>