@brightsideoy/kama 0.1.0-alpha.16 → 0.1.0-alpha.161
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/README.md +169 -0
- package/bin/cli.js +686 -155
- package/content/definitions/block-layouts/three-column.yaml +20 -0
- package/content/definitions/block-layouts/two-column.yaml +29 -0
- package/content/definitions/blocks/button.yaml +24 -0
- package/content/definitions/blocks/header.yaml +13 -0
- package/content/definitions/blocks/header_image.yaml +21 -0
- package/content/definitions/blocks/hero.yaml +28 -0
- package/content/definitions/blocks/html.yaml +13 -0
- package/content/definitions/blocks/image_card.yaml +56 -0
- package/content/definitions/blocks/single_image.yaml +27 -0
- package/content/definitions/blocks/text.yaml +15 -0
- package/content/definitions/channels/ecommerce.yaml +28 -0
- package/content/definitions/channels/website.yaml +41 -0
- package/content/definitions/field-sets/access.yaml +27 -0
- package/content/definitions/field-sets/channel-base.yaml +50 -0
- package/content/definitions/field-sets/channel-seo.yaml +21 -0
- package/content/definitions/field-sets/comments.yaml +11 -0
- package/content/definitions/field-sets/content-block.yaml +41 -0
- package/content/definitions/field-sets/page-base.yaml +44 -0
- package/content/definitions/field-sets/page-seo.yaml +34 -0
- package/content/definitions/field-sets/page-social.yaml +78 -0
- package/content/definitions/field-sets/schema-type.yaml +43 -0
- package/content/definitions/field-sets/tree-base.yaml +31 -0
- package/content/definitions/field-sets/visibility.yaml +8 -0
- package/content/definitions/node-layouts/content.yml +12 -0
- package/content/definitions/node-layouts/landing-page.yml +27 -0
- package/content/definitions/node-layouts/single-column.yml +43 -0
- package/content/definitions/node-layouts/two-column.yml +48 -0
- package/content/definitions/nodes/address.yaml +40 -0
- package/content/definitions/nodes/article.yaml +37 -0
- package/content/definitions/nodes/event.yaml +55 -0
- package/content/definitions/nodes/external-link.yaml +29 -0
- package/content/definitions/nodes/page-skeleton.yaml +48 -0
- package/content/definitions/nodes/page.yaml +54 -0
- package/content/definitions/nodes/person.yaml +41 -0
- package/content/definitions/nodes/product.yaml +89 -0
- package/content/definitions/trees/navigation.yaml +24 -0
- package/definitions/editor/button.ts +11 -0
- package/definitions/editor/default.ts +21 -0
- package/definitions/editor/header.ts +36 -0
- package/definitions/editor/minimal.ts +15 -0
- package/definitions/validators/iban.ts +12 -0
- package/definitions/validators/magic-word.ts +7 -0
- package/dist/assets/index-C5TmJVER.css +1 -0
- package/dist/assets/index-jpMh2BZv.js +164 -0
- package/dist/dist-BNkCx-o-.js +8912 -0
- package/dist/index.html +15 -0
- package/dist/index.js +7646 -1562
- package/dist/schema-compiler.js +48 -0
- package/documentation/SCHEMAS.md +182 -0
- package/package.json +19 -17
- package/schema.sql +206 -0
- package/templates/astro-starter/astro.config.mjs +24 -0
- package/templates/astro-starter/package.json.template +20 -0
- package/templates/astro-starter/public/robots.txt +23 -0
- package/templates/astro-starter/src/components/blocks/BlockRenderer.astro +134 -0
- package/templates/astro-starter/src/components/blocks/ColumnLayout.astro +67 -0
- package/templates/astro-starter/src/components/blocks/HeaderImage.astro +132 -0
- package/templates/astro-starter/src/components/blocks/Hero.astro +218 -0
- package/templates/astro-starter/src/components/blocks/HtmlBlock.astro +25 -0
- package/templates/astro-starter/src/components/blocks/ImageBlock.astro +92 -0
- package/templates/astro-starter/src/components/blocks/TextBlock.astro +15 -0
- package/templates/astro-starter/src/components/global/Breadcrumb.astro +67 -0
- package/templates/astro-starter/src/components/global/Footer.astro +50 -0
- package/templates/astro-starter/src/components/global/Header.astro +177 -0
- package/templates/astro-starter/src/components/global/MetaHead.astro +266 -0
- package/templates/astro-starter/src/components/global/NavigationMenu.astro +318 -0
- package/templates/astro-starter/src/components/ui/KamaImage.astro +172 -0
- package/templates/astro-starter/src/layouts/SkeletonLayout.astro +47 -0
- package/templates/astro-starter/src/layouts/StandardLayout.astro +62 -0
- package/templates/astro-starter/src/lib/cms.ts +197 -0
- package/templates/astro-starter/src/lib/media/kama-image-service.ts +56 -0
- package/templates/astro-starter/src/lib/media/media-proxy.ts +129 -0
- package/templates/astro-starter/src/lib/media/media-url.ts +98 -0
- package/templates/astro-starter/src/middleware.ts +406 -0
- package/templates/astro-starter/src/pages/404.astro +46 -0
- package/templates/astro-starter/src/pages/[...slug].astro +238 -0
- package/templates/astro-starter/src/pages/llms-full.txt.ts +171 -0
- package/templates/astro-starter/src/pages/llms.txt.ts +113 -0
- package/templates/astro-starter/src/pages/media/[...path].ts +14 -0
- package/templates/astro-starter/src/pages/partials/footer.astro +69 -0
- package/templates/astro-starter/src/pages/partials/nav.astro +141 -0
- package/templates/astro-starter/src/styles/standard-theme.css +157 -0
- package/templates/astro-starter/src/utils/tiptap.ts +113 -0
- package/templates/astro-starter/tsconfig.json +0 -0
- package/templates/kama-worker/index.js +19 -0
- package/templates/kama-worker/server.js +98 -0
- package/wrangler.json +22 -0
|
@@ -0,0 +1,406 @@
|
|
|
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 Local Vite Dev Mode to bypass edge caching locally
|
|
46
|
+
const isDev = import.meta.env.DEV;
|
|
47
|
+
|
|
48
|
+
// 🎯 Safe dual-environment context extraction
|
|
49
|
+
const workerEnv = await getSafeEnv(context.locals);
|
|
50
|
+
|
|
51
|
+
// Attach to locals so Astro components (like Header.astro) don't have to re-evaluate it
|
|
52
|
+
(context.locals as any).safeEnv = workerEnv;
|
|
53
|
+
|
|
54
|
+
// 🎯 Safe ctx extraction (Fixing the runtime.ctx crash in Astro 6/7)
|
|
55
|
+
let cfContext = (context.locals as any).cfContext;
|
|
56
|
+
if (!cfContext) {
|
|
57
|
+
const runtime = (context.locals as any).runtime;
|
|
58
|
+
if (runtime && typeof runtime === "object") {
|
|
59
|
+
try {
|
|
60
|
+
const desc = Object.getOwnPropertyDescriptor(runtime, "ctx");
|
|
61
|
+
if (desc && !desc.get) {
|
|
62
|
+
cfContext = runtime.ctx;
|
|
63
|
+
}
|
|
64
|
+
} catch (e) { }
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
cfContext = cfContext || {};
|
|
68
|
+
|
|
69
|
+
const HTML_CACHE = workerEnv?.HTML_CACHE; // KV Namespace binding
|
|
70
|
+
|
|
71
|
+
// 🎯 0. INSTANT EDGE SPAM DROP (Blocks bots before hit to CMS worker/database)
|
|
72
|
+
const isSpam =
|
|
73
|
+
pathLower.includes("wp-") ||
|
|
74
|
+
pathLower.includes("wordpress") ||
|
|
75
|
+
pathLower.endsWith(".php") ||
|
|
76
|
+
pathLower === "/wp";
|
|
77
|
+
|
|
78
|
+
if (isSpam) {
|
|
79
|
+
return new Response("Not Found", { status: 404 });
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// 🎯 0B. DIRECT MEDIA PROXY VIA SERVICE BINDING
|
|
83
|
+
if (pathname.startsWith("/media/")) {
|
|
84
|
+
const cmsWorker = workerEnv?.CMS_WORKER;
|
|
85
|
+
const envApiUrl = import.meta.env?.PUBLIC_API_URL;
|
|
86
|
+
const workerApiUrl = workerEnv?.PUBLIC_API_URL;
|
|
87
|
+
const baseApiUrl = String(envApiUrl || workerApiUrl || "https://kama.kamaengine.com");
|
|
88
|
+
const cleanApiUrl = baseApiUrl.endsWith("/") ? baseApiUrl.slice(0, -1) : baseApiUrl;
|
|
89
|
+
|
|
90
|
+
const mediaUrl = `${cleanApiUrl}${pathname}${context.url.search}`;
|
|
91
|
+
const mediaReq = new Request(mediaUrl, {
|
|
92
|
+
headers: context.request.headers
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
let mediaResponse: Response;
|
|
96
|
+
|
|
97
|
+
if (cmsWorker && typeof cmsWorker.fetch === "function") {
|
|
98
|
+
mediaResponse = await cmsWorker.fetch(mediaReq);
|
|
99
|
+
} else {
|
|
100
|
+
mediaResponse = await fetch(mediaReq);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const newHeaders = new Headers(mediaResponse.headers);
|
|
104
|
+
|
|
105
|
+
// 🎯 DEV FIX: Only apply 1-year cache on media in Production
|
|
106
|
+
if (!isDev) {
|
|
107
|
+
newHeaders.set("Cache-Control", "public, max-age=31536000, s-maxage=31536000, immutable");
|
|
108
|
+
}
|
|
109
|
+
newHeaders.set("Access-Control-Allow-Origin", "*");
|
|
110
|
+
|
|
111
|
+
return new Response(mediaResponse.body, {
|
|
112
|
+
status: mediaResponse.status,
|
|
113
|
+
statusText: mediaResponse.statusText,
|
|
114
|
+
headers: newHeaders
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// 🎯 0C. DIRECT EDGE INTERCEPT FOR CACHE PURGE ENDPOINT
|
|
119
|
+
if (pathname === "/api/purge" || pathname === "/api/purge/") {
|
|
120
|
+
if (context.request.method !== "POST") {
|
|
121
|
+
return new Response(JSON.stringify({ error: "Method Not Allowed" }), {
|
|
122
|
+
status: 405,
|
|
123
|
+
headers: { "Content-Type": "application/json" },
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const authHeader = context.request.headers.get("Authorization");
|
|
128
|
+
const expectedToken = workerEnv.CLOUDFLARE_API_TOKEN;
|
|
129
|
+
|
|
130
|
+
if (!expectedToken || authHeader !== `Bearer ${expectedToken}`) {
|
|
131
|
+
return new Response(JSON.stringify({ error: "Unauthorized Token Mismatch" }), {
|
|
132
|
+
status: 401,
|
|
133
|
+
headers: { "Content-Type": "application/json" },
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
try {
|
|
138
|
+
const body = await context.request.json();
|
|
139
|
+
const cache = typeof caches !== "undefined" && caches.default ? caches.default : null;
|
|
140
|
+
const origin = context.url.origin;
|
|
141
|
+
|
|
142
|
+
// A. Purge Workers Caching Layer (Astro cfContext)
|
|
143
|
+
if (typeof cfContext?.cache?.purge === 'function') {
|
|
144
|
+
try {
|
|
145
|
+
await cfContext.cache.purge({ purgeEverything: true });
|
|
146
|
+
console.log("✅ New Cloudflare Workers Cache Engine Purged");
|
|
147
|
+
} catch (e) {
|
|
148
|
+
console.error("❌ Failed to purge new Workers Cache Engine", e);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// B. Version-Based Instant Invalidation (0ms KV Write)
|
|
153
|
+
if (HTML_CACHE) {
|
|
154
|
+
try {
|
|
155
|
+
const now = Date.now().toString();
|
|
156
|
+
|
|
157
|
+
if (body.purge_everything) {
|
|
158
|
+
// 🎯 GLOBAL PURGE: Bumping site_version instantly invalidates ALL KV pages globally!
|
|
159
|
+
await HTML_CACHE.put("site_version", now);
|
|
160
|
+
console.log(`✅ [Version Tagging] Global site_version updated to ${now}`);
|
|
161
|
+
} else if (Array.isArray(body.urls) && body.urls.length > 0) {
|
|
162
|
+
// 🎯 SURGICAL PURGE: Parallel execution for page version bumps
|
|
163
|
+
const purgeTasks = body.urls.map((targetUrl: string) => {
|
|
164
|
+
const urlPath = new URL(targetUrl).pathname;
|
|
165
|
+
const cleanPath = urlPath.replace(/\/$/, "") || "/";
|
|
166
|
+
return HTML_CACHE.put(`v:${cleanPath}`, now);
|
|
167
|
+
});
|
|
168
|
+
await Promise.all(purgeTasks);
|
|
169
|
+
console.log(`✅ [Version Tagging] Updated versions for ${body.urls.length} URLs`);
|
|
170
|
+
}
|
|
171
|
+
} catch (kvErr) {
|
|
172
|
+
console.error("❌ KV Version Tagging Error:", kvErr);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// C. Global Legacy Worker Cache Purge
|
|
177
|
+
if (body.purge_everything) {
|
|
178
|
+
if (cache) {
|
|
179
|
+
const rootUrls = [
|
|
180
|
+
origin,
|
|
181
|
+
`${origin}/`,
|
|
182
|
+
`${origin}/home`,
|
|
183
|
+
`${origin}/home/`
|
|
184
|
+
];
|
|
185
|
+
|
|
186
|
+
for (const url of rootUrls) {
|
|
187
|
+
await cache.delete(new Request(url));
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
return new Response(JSON.stringify({
|
|
192
|
+
success: true,
|
|
193
|
+
message: "All Worker Caches Purged"
|
|
194
|
+
}), {
|
|
195
|
+
status: 200,
|
|
196
|
+
headers: { "Content-Type": "application/json" },
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// D. Surgical Legacy Worker Cache Purge (For Updated Pages)
|
|
201
|
+
if (Array.isArray(body.urls) && body.urls.length > 0) {
|
|
202
|
+
const results = [];
|
|
203
|
+
|
|
204
|
+
for (const targetUrl of body.urls) {
|
|
205
|
+
const cleanUrl = targetUrl.split('?')[0];
|
|
206
|
+
const urlNoSlash = cleanUrl.replace(/\/$/, "");
|
|
207
|
+
const urlWithSlash = urlNoSlash + "/";
|
|
208
|
+
|
|
209
|
+
let p1 = false, p2 = false;
|
|
210
|
+
if (cache) {
|
|
211
|
+
p1 = await cache.delete(new Request(urlNoSlash));
|
|
212
|
+
p2 = await cache.delete(new Request(urlWithSlash));
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
results.push({ url: targetUrl, purged: p1 || p2 });
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
return new Response(JSON.stringify({
|
|
219
|
+
success: true,
|
|
220
|
+
message: "URLs processed and version tags updated",
|
|
221
|
+
results
|
|
222
|
+
}), {
|
|
223
|
+
status: 200,
|
|
224
|
+
headers: { "Content-Type": "application/json" },
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// 🎯 E. SURGICAL DELETION FOR DELETED PAGES
|
|
229
|
+
if (Array.isArray(body.deleted_urls) && body.deleted_urls.length > 0) {
|
|
230
|
+
const results: any[] = [];
|
|
231
|
+
|
|
232
|
+
const deleteTasks = body.deleted_urls.map(async (targetUrl: string) => {
|
|
233
|
+
const urlPath = new URL(targetUrl).pathname;
|
|
234
|
+
const cleanPath = urlPath.replace(/\/$/, "") || "/";
|
|
235
|
+
|
|
236
|
+
let purgedKv = false;
|
|
237
|
+
|
|
238
|
+
if (HTML_CACHE) {
|
|
239
|
+
const [siteVer, pageVer] = await Promise.all([
|
|
240
|
+
HTML_CACHE.get("site_version"),
|
|
241
|
+
HTML_CACHE.get(`v:${cleanPath}`)
|
|
242
|
+
]);
|
|
243
|
+
|
|
244
|
+
if (siteVer || pageVer) {
|
|
245
|
+
const activeCacheKey = `${cleanPath}:v:${siteVer || "1"}:${pageVer || "1"}`;
|
|
246
|
+
await HTML_CACHE.delete(activeCacheKey);
|
|
247
|
+
purgedKv = true;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
await HTML_CACHE.delete(`v:${cleanPath}`);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
const cleanUrl = targetUrl.split('?')[0];
|
|
254
|
+
const urlNoSlash = cleanUrl.replace(/\/$/, "");
|
|
255
|
+
const urlWithSlash = urlNoSlash + "/";
|
|
256
|
+
|
|
257
|
+
let p1 = false, p2 = false;
|
|
258
|
+
if (cache) {
|
|
259
|
+
p1 = await cache.delete(new Request(urlNoSlash));
|
|
260
|
+
p2 = await cache.delete(new Request(urlWithSlash));
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
results.push({ url: targetUrl, purgedKv, purgedLegacy: p1 || p2 });
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
await Promise.all(deleteTasks);
|
|
267
|
+
|
|
268
|
+
return new Response(JSON.stringify({
|
|
269
|
+
success: true,
|
|
270
|
+
message: "Deleted URLs processed and KV keys permanently removed",
|
|
271
|
+
results
|
|
272
|
+
}), {
|
|
273
|
+
status: 200,
|
|
274
|
+
headers: { "Content-Type": "application/json" },
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
return new Response(JSON.stringify({ error: "Invalid payload format" }), {
|
|
279
|
+
status: 400,
|
|
280
|
+
headers: { "Content-Type": "application/json" },
|
|
281
|
+
});
|
|
282
|
+
|
|
283
|
+
} catch (err: any) {
|
|
284
|
+
return new Response(JSON.stringify({ error: err.message }), {
|
|
285
|
+
status: 500,
|
|
286
|
+
headers: { "Content-Type": "application/json" },
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// 🎯 1. KV STATIC "FILE" CACHE READ WITH VERSION TAGGING
|
|
292
|
+
const isWarmer = context.request.headers.get("X-Cache-Warmer") === "true";
|
|
293
|
+
const isHtmlPage = !pathname.includes('.') && !pathname.startsWith('/api/');
|
|
294
|
+
const cleanLookupPath = pathname.replace(/\/$/, "") || "/";
|
|
295
|
+
|
|
296
|
+
let activeCacheKey = cleanLookupPath;
|
|
297
|
+
|
|
298
|
+
// 🎯 DEV FIX: Bypass KV Read in local dev
|
|
299
|
+
if (!isDev && isHtmlPage && HTML_CACHE && !isWarmer) {
|
|
300
|
+
try {
|
|
301
|
+
const [siteVer, pageVer] = await Promise.all([
|
|
302
|
+
HTML_CACHE.get("site_version"),
|
|
303
|
+
HTML_CACHE.get(`v:${cleanLookupPath}`)
|
|
304
|
+
]);
|
|
305
|
+
|
|
306
|
+
activeCacheKey = `${cleanLookupPath}:v:${siteVer || "1"}:${pageVer || "1"}`;
|
|
307
|
+
|
|
308
|
+
const cachedHtml = await HTML_CACHE.get(activeCacheKey);
|
|
309
|
+
if (cachedHtml) {
|
|
310
|
+
return new Response(cachedHtml, {
|
|
311
|
+
status: 200,
|
|
312
|
+
headers: {
|
|
313
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
314
|
+
"X-Cache-Status": "HIT-KV-STATICFILE",
|
|
315
|
+
"X-Cache-Key": activeCacheKey,
|
|
316
|
+
"Cache-Control": "no-store, no-cache, must-revalidate, proxy-revalidate"
|
|
317
|
+
}
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
} catch (e) {
|
|
321
|
+
console.warn("[Middleware] KV lookup bypass:", e);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// Process downstream SSR routes
|
|
326
|
+
const response = await next();
|
|
327
|
+
|
|
328
|
+
// 🎯 2. KV STATIC "FILE" CACHE WRITE (Save HTML under active Version Key)
|
|
329
|
+
// 🎯 DEV FIX: Bypass KV Write in local dev
|
|
330
|
+
if (
|
|
331
|
+
!isDev &&
|
|
332
|
+
isHtmlPage &&
|
|
333
|
+
HTML_CACHE &&
|
|
334
|
+
response.status === 200 &&
|
|
335
|
+
response.headers.get("content-type")?.includes("text/html")
|
|
336
|
+
) {
|
|
337
|
+
const htmlText = await response.clone().text();
|
|
338
|
+
|
|
339
|
+
const writeTask = (async () => {
|
|
340
|
+
if (activeCacheKey === cleanLookupPath || isWarmer) {
|
|
341
|
+
const forcedVersion = Date.now().toString();
|
|
342
|
+
|
|
343
|
+
await HTML_CACHE.put(`v:${cleanLookupPath}`, forcedVersion);
|
|
344
|
+
|
|
345
|
+
const siteVer = await HTML_CACHE.get("site_version") || "1";
|
|
346
|
+
|
|
347
|
+
activeCacheKey = `${cleanLookupPath}:v:${siteVer}:${forcedVersion}`;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
await HTML_CACHE.put(activeCacheKey, htmlText);
|
|
351
|
+
console.log(`✅ [Middleware] Saved HTML to KV under key: ${activeCacheKey}`);
|
|
352
|
+
})();
|
|
353
|
+
|
|
354
|
+
if (cfContext && typeof cfContext.waitUntil === 'function') {
|
|
355
|
+
cfContext.waitUntil(writeTask);
|
|
356
|
+
} else {
|
|
357
|
+
writeTask.catch((e: any) => console.error("KV write error:", e));
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// 🎯 3. SERVE LLMS & LLXML ENDPOINTS
|
|
362
|
+
if (pathname === "/llms.txt" || pathname === "/llms-full.txt") {
|
|
363
|
+
response.headers.set("Content-Type", "text/plain; charset=utf-8");
|
|
364
|
+
response.headers.set("Cache-Control", "public, max-age=3600");
|
|
365
|
+
response.headers.set("Access-Control-Allow-Origin", "*");
|
|
366
|
+
return response;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
if (pathname === "/llxml.txt") {
|
|
370
|
+
response.headers.set("Content-Type", "application/xml; charset=utf-8");
|
|
371
|
+
response.headers.set("Cache-Control", "public, max-age=3600");
|
|
372
|
+
response.headers.set("Access-Control-Allow-Origin", "*");
|
|
373
|
+
return response;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// 🎯 4. STATIC ASSET CACHING FOR COMPRESSED BUNDLES / ASSETS
|
|
377
|
+
// 🎯 DEV FIX: Do not apply max-age=31536000 locally to prevent breaking Vite HMR
|
|
378
|
+
if (!isDev) {
|
|
379
|
+
if (
|
|
380
|
+
pathname.startsWith("/_image") ||
|
|
381
|
+
pathname.startsWith("/cdn-cgi/image/") ||
|
|
382
|
+
pathname.match(/\.(png|jpg|jpeg|webp|avif|svg|gif|ico|woff2?|css|js)$/i)
|
|
383
|
+
) {
|
|
384
|
+
response.headers.set(
|
|
385
|
+
"Cache-Control",
|
|
386
|
+
"public, max-age=31536000, s-maxage=31536000, immutable"
|
|
387
|
+
);
|
|
388
|
+
response.headers.set("Access-Control-Allow-Origin", "*");
|
|
389
|
+
return response;
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// 🎯 5. SECURITY HEADERS FOR HTML PAGES
|
|
394
|
+
if (response.headers.get("content-type")?.includes("text/html")) {
|
|
395
|
+
response.headers.set("Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload");
|
|
396
|
+
response.headers.set("X-Frame-Options", "SAMEORIGIN");
|
|
397
|
+
response.headers.set("X-Content-Type-Options", "nosniff");
|
|
398
|
+
response.headers.set("Cross-Origin-Opener-Policy", "same-origin-allow-popups");
|
|
399
|
+
response.headers.set(
|
|
400
|
+
"Content-Security-Policy",
|
|
401
|
+
"default-src 'self' https: data: 'unsafe-inline' 'unsafe-eval'; img-src 'self' https: data: blob:; connect-src 'self' https:; frame-ancestors 'self';"
|
|
402
|
+
);
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
return response;
|
|
406
|
+
});
|
|
@@ -0,0 +1,46 @@
|
|
|
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>
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
---
|
|
2
|
+
// src/pages/[...slug].astro
|
|
3
|
+
|
|
4
|
+
import StandardLayout from "../layouts/StandardLayout.astro";
|
|
5
|
+
import SkeletonLayout from "../layouts/SkeletonLayout.astro";
|
|
6
|
+
import BlockRenderer from "../components/blocks/BlockRenderer.astro";
|
|
7
|
+
import Breadcrumb from "../components/global/Breadcrumb.astro";
|
|
8
|
+
import { getNodeByPath, getChannelId, getTree, getTreeId } from "../lib/cms";
|
|
9
|
+
import type { NodeResponse, TreeNode } from "../lib/cms";
|
|
10
|
+
|
|
11
|
+
export const prerender = false;
|
|
12
|
+
|
|
13
|
+
const { slug } = Astro.params;
|
|
14
|
+
|
|
15
|
+
// Extract Preview & Revision parameters from the URL
|
|
16
|
+
const searchParams = Astro.url.searchParams;
|
|
17
|
+
const isPreview = searchParams.get("preview") === "true";
|
|
18
|
+
const revisionId = searchParams.get("revisionId");
|
|
19
|
+
|
|
20
|
+
// Smart Edge Caching Logic
|
|
21
|
+
const isTimeTraveling = isPreview || !!revisionId;
|
|
22
|
+
|
|
23
|
+
// 🎯 FIX: Allow Cloudflare Edge to revalidate with Worker KV middleware
|
|
24
|
+
Astro.response.headers.set(
|
|
25
|
+
"Cache-Control",
|
|
26
|
+
"public, no-cache, must-revalidate",
|
|
27
|
+
);
|
|
28
|
+
|
|
29
|
+
// 1. STATIC ASSET CHECK
|
|
30
|
+
const staticExts = [
|
|
31
|
+
".ico",
|
|
32
|
+
".png",
|
|
33
|
+
".jpg",
|
|
34
|
+
".jpeg",
|
|
35
|
+
".svg",
|
|
36
|
+
".txt",
|
|
37
|
+
".xml",
|
|
38
|
+
".webmanifest",
|
|
39
|
+
];
|
|
40
|
+
const slugStr = String(slug || "");
|
|
41
|
+
const isStaticAsset =
|
|
42
|
+
!slugStr.includes("/") &&
|
|
43
|
+
staticExts.some(ext => slugStr.toLowerCase().endsWith(ext));
|
|
44
|
+
|
|
45
|
+
if (isStaticAsset) {
|
|
46
|
+
return new Response(null, { status: 404 });
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// 2. ENV & WORKER RESOLUTION (Safe Dual-Environment)
|
|
50
|
+
// 🎯 Replaced throwing runtime getter with safeEnv from middleware
|
|
51
|
+
const safeEnv = (Astro.locals as any).safeEnv || {};
|
|
52
|
+
const cmsWorker = safeEnv.CMS_WORKER;
|
|
53
|
+
|
|
54
|
+
// Extract environment configuration & fallback slug
|
|
55
|
+
const envHomeSlug = import.meta.env.PUBLIC_HOME_SLUG;
|
|
56
|
+
const workerHomeSlug = safeEnv.PUBLIC_HOME_SLUG;
|
|
57
|
+
const homeSlug = String(envHomeSlug || workerHomeSlug || "home").trim();
|
|
58
|
+
|
|
59
|
+
const envApiUrl = import.meta.env.PUBLIC_API_URL;
|
|
60
|
+
const workerApiUrl = safeEnv.PUBLIC_API_URL;
|
|
61
|
+
const baseApiUrl = String(
|
|
62
|
+
envApiUrl || workerApiUrl || "https://admin.kamaengine.com",
|
|
63
|
+
);
|
|
64
|
+
|
|
65
|
+
const cleanApiUrl = baseApiUrl.endsWith("/")
|
|
66
|
+
? baseApiUrl.slice(0, -1)
|
|
67
|
+
: baseApiUrl;
|
|
68
|
+
|
|
69
|
+
const customFetch = async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
70
|
+
let urlStr = input instanceof URL ? input.toString() : String(input);
|
|
71
|
+
if (urlStr.startsWith("/")) urlStr = `${cleanApiUrl}${urlStr}`;
|
|
72
|
+
|
|
73
|
+
const urlObj = new URL(urlStr);
|
|
74
|
+
|
|
75
|
+
if (isTimeTraveling) {
|
|
76
|
+
if (revisionId) urlObj.searchParams.set("revisionId", revisionId);
|
|
77
|
+
if (isPreview) urlObj.searchParams.set("preview", "true");
|
|
78
|
+
urlObj.searchParams.set("_t", Date.now().toString());
|
|
79
|
+
} else {
|
|
80
|
+
urlObj.searchParams.set("_cb", Date.now().toString());
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
urlStr = urlObj.toString();
|
|
84
|
+
|
|
85
|
+
const reqHeaders: Record<string, string> = {
|
|
86
|
+
...init?.headers,
|
|
87
|
+
"Cache-Control": "no-cache, no-store, must-revalidate",
|
|
88
|
+
Pragma: "no-cache",
|
|
89
|
+
// 🎯 CRITICAL FIX: Direct Service Bindings require explicit header flags to bypass CMS KV cache!
|
|
90
|
+
"X-Bypass-Cache": "true",
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
const fetchOpts: RequestInit = {
|
|
94
|
+
...init,
|
|
95
|
+
headers: reqHeaders,
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
const req = new Request(urlStr, fetchOpts);
|
|
99
|
+
|
|
100
|
+
if (cmsWorker && typeof cmsWorker.fetch === "function") {
|
|
101
|
+
return cmsWorker.fetch(req);
|
|
102
|
+
}
|
|
103
|
+
return fetch(req);
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
const channelId = getChannelId();
|
|
107
|
+
const treeId = getTreeId();
|
|
108
|
+
|
|
109
|
+
// 3. PATH & CONCURRENT FETCH RESOLUTION
|
|
110
|
+
const rawSlug = Array.isArray(slug) ? slug.join("/") : slugStr;
|
|
111
|
+
const pathParts = rawSlug.split("/").filter(part => part.trim() !== "");
|
|
112
|
+
const requestedSlug = pathParts.join("/");
|
|
113
|
+
const targetSlug = requestedSlug || homeSlug;
|
|
114
|
+
|
|
115
|
+
let pageData: NodeResponse | null = null;
|
|
116
|
+
let navTree: TreeNode[] = [];
|
|
117
|
+
|
|
118
|
+
// 🎯 Fetch Tree and Node in PARALLEL using the cache-busting customFetch
|
|
119
|
+
try {
|
|
120
|
+
const [treeResult, nodeResult] = await Promise.all([
|
|
121
|
+
getTree(treeId, channelId, customFetch).catch(err => {
|
|
122
|
+
console.error(`❌ [SSR Error] Failed to fetch tree "${treeId}":`, err);
|
|
123
|
+
return [];
|
|
124
|
+
}),
|
|
125
|
+
getNodeByPath(targetSlug, channelId, isPreview, customFetch).catch(err => {
|
|
126
|
+
console.error(
|
|
127
|
+
`❌ [SSR Error] Failed to fetch page data for path "${targetSlug}":`,
|
|
128
|
+
err,
|
|
129
|
+
);
|
|
130
|
+
return null;
|
|
131
|
+
}),
|
|
132
|
+
]);
|
|
133
|
+
|
|
134
|
+
navTree = treeResult || [];
|
|
135
|
+
pageData = nodeResult;
|
|
136
|
+
} catch (err) {
|
|
137
|
+
console.error("❌ [SSR Error] Failed concurrent fetch execution:", err);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
if (!pageData || !pageData.node) {
|
|
141
|
+
return new Response("Page Not Found", { status: 404 });
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const node = pageData.node;
|
|
145
|
+
const content = pageData.content || {};
|
|
146
|
+
|
|
147
|
+
const rootTreeSlug =
|
|
148
|
+
navTree && navTree.length > 0
|
|
149
|
+
? navTree[0].slug || (navTree[0] as any).key
|
|
150
|
+
: "";
|
|
151
|
+
|
|
152
|
+
const isHomePage =
|
|
153
|
+
targetSlug === homeSlug ||
|
|
154
|
+
(rootTreeSlug && targetSlug === rootTreeSlug) ||
|
|
155
|
+
node?.path === "/" ||
|
|
156
|
+
pathParts.length === 0;
|
|
157
|
+
|
|
158
|
+
const normalizedSlug = isHomePage ? "" : targetSlug;
|
|
159
|
+
|
|
160
|
+
const headerBlocks = content?.header || [];
|
|
161
|
+
const mainBlocks = content?.content || [];
|
|
162
|
+
const sidebarBlocks = content?.sidebar || [];
|
|
163
|
+
const hasSidebar = sidebarBlocks.length > 0;
|
|
164
|
+
|
|
165
|
+
// Detect if this node is a standalone Page Skeleton
|
|
166
|
+
const isSkeleton = node?.nodeType === "page-skeleton";
|
|
167
|
+
---
|
|
168
|
+
|
|
169
|
+
{
|
|
170
|
+
isSkeleton ? (
|
|
171
|
+
<SkeletonLayout
|
|
172
|
+
node={node}
|
|
173
|
+
content={content}
|
|
174
|
+
language={pageData?.language}
|
|
175
|
+
normalizedSlug={normalizedSlug}
|
|
176
|
+
isHomePage={isHomePage}
|
|
177
|
+
>
|
|
178
|
+
<BlockRenderer blocks={mainBlocks} contentMap={content} region="main" />
|
|
179
|
+
</SkeletonLayout>
|
|
180
|
+
) : (
|
|
181
|
+
<StandardLayout
|
|
182
|
+
node={node}
|
|
183
|
+
content={content}
|
|
184
|
+
language={pageData?.language}
|
|
185
|
+
normalizedSlug={normalizedSlug}
|
|
186
|
+
isHomePage={isHomePage}
|
|
187
|
+
hasSidebar={hasSidebar}
|
|
188
|
+
headerBlocks={headerBlocks}
|
|
189
|
+
tree={navTree}
|
|
190
|
+
>
|
|
191
|
+
{headerBlocks.length > 0 && (
|
|
192
|
+
<section class="region-header">
|
|
193
|
+
<BlockRenderer
|
|
194
|
+
blocks={headerBlocks}
|
|
195
|
+
contentMap={content}
|
|
196
|
+
region="header"
|
|
197
|
+
/>
|
|
198
|
+
</section>
|
|
199
|
+
)}
|
|
200
|
+
|
|
201
|
+
{!isHomePage && (
|
|
202
|
+
<div class="breadcrumb-wrapper">
|
|
203
|
+
<Breadcrumb title={node?.title || "Page"} slug={normalizedSlug} />
|
|
204
|
+
</div>
|
|
205
|
+
)}
|
|
206
|
+
|
|
207
|
+
<div class:list={["content-layout", { "has-sidebar": hasSidebar }]}>
|
|
208
|
+
<div class="main-column">
|
|
209
|
+
{mainBlocks.length > 0 ? (
|
|
210
|
+
<section class="region-main">
|
|
211
|
+
<BlockRenderer
|
|
212
|
+
blocks={mainBlocks}
|
|
213
|
+
contentMap={content}
|
|
214
|
+
region="main"
|
|
215
|
+
/>
|
|
216
|
+
</section>
|
|
217
|
+
) : (
|
|
218
|
+
<div class="empty-content">
|
|
219
|
+
<p>{node?.summary || "No content available for this page."}</p>
|
|
220
|
+
</div>
|
|
221
|
+
)}
|
|
222
|
+
</div>
|
|
223
|
+
|
|
224
|
+
{hasSidebar && (
|
|
225
|
+
<aside class="sidebar-column">
|
|
226
|
+
<section class="region-sidebar">
|
|
227
|
+
<BlockRenderer
|
|
228
|
+
blocks={sidebarBlocks}
|
|
229
|
+
contentMap={content}
|
|
230
|
+
region="sidebar"
|
|
231
|
+
/>
|
|
232
|
+
</section>
|
|
233
|
+
</aside>
|
|
234
|
+
)}
|
|
235
|
+
</div>
|
|
236
|
+
</StandardLayout>
|
|
237
|
+
)
|
|
238
|
+
}
|