@pyreon/zero 0.12.2 → 0.12.4

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 (145) hide show
  1. package/lib/actions.js +97 -0
  2. package/lib/actions.js.map +1 -0
  3. package/lib/ai.js +503 -0
  4. package/lib/ai.js.map +1 -0
  5. package/lib/api-routes.js +137 -0
  6. package/lib/api-routes.js.map +1 -0
  7. package/lib/compression.js +80 -0
  8. package/lib/compression.js.map +1 -0
  9. package/lib/cors.js +57 -0
  10. package/lib/cors.js.map +1 -0
  11. package/lib/csp.js +119 -0
  12. package/lib/csp.js.map +1 -0
  13. package/lib/env.js +217 -0
  14. package/lib/env.js.map +1 -0
  15. package/lib/favicon.js +424 -0
  16. package/lib/favicon.js.map +1 -0
  17. package/lib/i18n-routing.js +167 -0
  18. package/lib/i18n-routing.js.map +1 -0
  19. package/lib/index.js +340 -4015
  20. package/lib/index.js.map +1 -1
  21. package/lib/link.js +5 -0
  22. package/lib/link.js.map +1 -1
  23. package/lib/logger.js +78 -0
  24. package/lib/logger.js.map +1 -0
  25. package/lib/meta.js +310 -0
  26. package/lib/meta.js.map +1 -0
  27. package/lib/middleware.js +53 -0
  28. package/lib/middleware.js.map +1 -0
  29. package/lib/og-image.js +233 -0
  30. package/lib/og-image.js.map +1 -0
  31. package/lib/rate-limit.js +76 -0
  32. package/lib/rate-limit.js.map +1 -0
  33. package/lib/server.js +1534 -0
  34. package/lib/server.js.map +1 -0
  35. package/lib/testing.js +179 -0
  36. package/lib/testing.js.map +1 -0
  37. package/lib/theme.js +11 -2
  38. package/lib/theme.js.map +1 -1
  39. package/lib/types/actions.d.ts +27 -24
  40. package/lib/types/actions.d.ts.map +1 -1
  41. package/lib/types/ai.d.ts +76 -95
  42. package/lib/types/ai.d.ts.map +1 -1
  43. package/lib/types/api-routes.d.ts +37 -33
  44. package/lib/types/api-routes.d.ts.map +1 -1
  45. package/lib/types/cache.d.ts +26 -22
  46. package/lib/types/cache.d.ts.map +1 -1
  47. package/lib/types/client.d.ts +13 -9
  48. package/lib/types/client.d.ts.map +1 -1
  49. package/lib/types/compression.d.ts +14 -10
  50. package/lib/types/compression.d.ts.map +1 -1
  51. package/lib/types/config.d.ts +39 -4
  52. package/lib/types/config.d.ts.map +1 -1
  53. package/lib/types/cors.d.ts +20 -16
  54. package/lib/types/cors.d.ts.map +1 -1
  55. package/lib/types/csp.d.ts +42 -61
  56. package/lib/types/csp.d.ts.map +1 -1
  57. package/lib/types/env.d.ts +26 -26
  58. package/lib/types/env.d.ts.map +1 -1
  59. package/lib/types/favicon.d.ts +58 -54
  60. package/lib/types/favicon.d.ts.map +1 -1
  61. package/lib/types/font.d.ts +68 -65
  62. package/lib/types/font.d.ts.map +1 -1
  63. package/lib/types/i18n-routing.d.ts +43 -37
  64. package/lib/types/i18n-routing.d.ts.map +1 -1
  65. package/lib/types/image-plugin.d.ts +49 -45
  66. package/lib/types/image-plugin.d.ts.map +1 -1
  67. package/lib/types/image.d.ts +47 -36
  68. package/lib/types/image.d.ts.map +1 -1
  69. package/lib/types/index.d.ts +594 -56
  70. package/lib/types/index.d.ts.map +1 -1
  71. package/lib/types/link.d.ts +61 -56
  72. package/lib/types/link.d.ts.map +1 -1
  73. package/lib/types/logger.d.ts +37 -48
  74. package/lib/types/logger.d.ts.map +1 -1
  75. package/lib/types/meta.d.ts +145 -105
  76. package/lib/types/meta.d.ts.map +1 -1
  77. package/lib/types/middleware.d.ts +8 -4
  78. package/lib/types/middleware.d.ts.map +1 -1
  79. package/lib/types/og-image.d.ts +63 -59
  80. package/lib/types/og-image.d.ts.map +1 -1
  81. package/lib/types/rate-limit.d.ts +20 -16
  82. package/lib/types/rate-limit.d.ts.map +1 -1
  83. package/lib/types/script.d.ts +23 -19
  84. package/lib/types/script.d.ts.map +1 -1
  85. package/lib/types/seo.d.ts +47 -43
  86. package/lib/types/seo.d.ts.map +1 -1
  87. package/lib/types/server.d.ts +455 -0
  88. package/lib/types/server.d.ts.map +1 -0
  89. package/lib/types/testing.d.ts +64 -27
  90. package/lib/types/testing.d.ts.map +1 -1
  91. package/lib/types/theme.d.ts +22 -12
  92. package/lib/types/theme.d.ts.map +1 -1
  93. package/package.json +17 -12
  94. package/src/actions.ts +1 -3
  95. package/src/adapters/bun.ts +2 -0
  96. package/src/adapters/cloudflare.ts +2 -0
  97. package/src/adapters/netlify.ts +2 -0
  98. package/src/adapters/node.ts +2 -0
  99. package/src/adapters/validate.ts +16 -0
  100. package/src/adapters/vercel.ts +2 -0
  101. package/src/compression.ts +19 -3
  102. package/src/entry-server.ts +28 -5
  103. package/src/index.ts +20 -182
  104. package/src/link.tsx +6 -0
  105. package/src/meta.tsx +78 -16
  106. package/src/rate-limit.ts +11 -9
  107. package/src/server.ts +70 -0
  108. package/src/theme.tsx +12 -1
  109. package/src/vite-plugin.ts +5 -1
  110. package/lib/fs-router-Dil4IKZR.js +0 -290
  111. package/lib/fs-router-Dil4IKZR.js.map +0 -1
  112. package/lib/types/adapters/bun.d.ts +0 -6
  113. package/lib/types/adapters/bun.d.ts.map +0 -1
  114. package/lib/types/adapters/cloudflare.d.ts +0 -26
  115. package/lib/types/adapters/cloudflare.d.ts.map +0 -1
  116. package/lib/types/adapters/index.d.ts +0 -13
  117. package/lib/types/adapters/index.d.ts.map +0 -1
  118. package/lib/types/adapters/netlify.d.ts +0 -21
  119. package/lib/types/adapters/netlify.d.ts.map +0 -1
  120. package/lib/types/adapters/node.d.ts +0 -6
  121. package/lib/types/adapters/node.d.ts.map +0 -1
  122. package/lib/types/adapters/static.d.ts +0 -7
  123. package/lib/types/adapters/static.d.ts.map +0 -1
  124. package/lib/types/adapters/vercel.d.ts +0 -21
  125. package/lib/types/adapters/vercel.d.ts.map +0 -1
  126. package/lib/types/app.d.ts +0 -24
  127. package/lib/types/app.d.ts.map +0 -1
  128. package/lib/types/entry-server.d.ts +0 -37
  129. package/lib/types/entry-server.d.ts.map +0 -1
  130. package/lib/types/error-overlay.d.ts +0 -6
  131. package/lib/types/error-overlay.d.ts.map +0 -1
  132. package/lib/types/fs-router.d.ts +0 -47
  133. package/lib/types/fs-router.d.ts.map +0 -1
  134. package/lib/types/isr.d.ts +0 -9
  135. package/lib/types/isr.d.ts.map +0 -1
  136. package/lib/types/not-found.d.ts +0 -7
  137. package/lib/types/not-found.d.ts.map +0 -1
  138. package/lib/types/types.d.ts +0 -111
  139. package/lib/types/types.d.ts.map +0 -1
  140. package/lib/types/utils/use-intersection-observer.d.ts +0 -10
  141. package/lib/types/utils/use-intersection-observer.d.ts.map +0 -1
  142. package/lib/types/utils/with-headers.d.ts +0 -6
  143. package/lib/types/utils/with-headers.d.ts.map +0 -1
  144. package/lib/types/vite-plugin.d.ts +0 -17
  145. package/lib/types/vite-plugin.d.ts.map +0 -1
package/lib/index.js CHANGED
@@ -1,1064 +1,8 @@
1
- import { a as parseFileRoutes, i as generateRouteModule, o as scanRouteFiles, r as generateMiddlewareModule, t as filePathToUrlPath } from "./fs-router-Dil4IKZR.js";
2
- import { Fragment, createContext, createRef, h, onMount, onUnmount } from "@pyreon/core";
3
- import { HeadProvider, useHead } from "@pyreon/head";
4
- import { RouterProvider, RouterView, createRouter, useRouter } from "@pyreon/router";
5
- import { createHandler, useRequestLocals } from "@pyreon/server";
6
- import { renderToString } from "@pyreon/runtime-server";
7
- import { existsSync, readdirSync } from "node:fs";
8
- import { basename, extname, join } from "node:path";
1
+ import { createContext, createRef, onMount, onUnmount } from "@pyreon/core";
9
2
  import { effect, signal } from "@pyreon/reactivity";
10
- import { mkdir, readFile, writeFile } from "node:fs/promises";
3
+ import { useRouter } from "@pyreon/router";
4
+ import { useHead } from "@pyreon/head";
11
5
 
12
- //#region src/app.ts
13
- /**
14
- * Create a full Zero app — assembles router, head provider, and root layout.
15
- *
16
- * Used internally by entry-server and entry-client.
17
- */
18
- function createApp(options) {
19
- const router = createRouter({
20
- routes: options.routes,
21
- mode: options.routerMode ?? "history",
22
- ...options.url ? { url: options.url } : {},
23
- scrollBehavior: "top"
24
- });
25
- const Layout = options.layout ?? DefaultLayout;
26
- function App() {
27
- return h(HeadProvider, null, h(RouterProvider, { router }, h(Layout, null, h(RouterView, null))));
28
- }
29
- return {
30
- App,
31
- router
32
- };
33
- }
34
- function DefaultLayout(props) {
35
- return h(Fragment, null, ...Array.isArray(props.children) ? props.children : [props.children]);
36
- }
37
-
38
- //#endregion
39
- //#region src/api-routes.ts
40
- /**
41
- * Match a URL path against an API route pattern.
42
- * Returns extracted params or null if no match.
43
- */
44
- function matchApiRoute(pattern, path) {
45
- const patternParts = pattern.split("/").filter(Boolean);
46
- const pathParts = path.split("/").filter(Boolean);
47
- const params = {};
48
- for (let i = 0; i < patternParts.length; i++) {
49
- const pp = patternParts[i];
50
- if (!pp) continue;
51
- if (pp.endsWith("*")) {
52
- const paramName = pp.slice(1, -1);
53
- params[paramName] = pathParts.slice(i).join("/");
54
- return params;
55
- }
56
- if (i >= pathParts.length) return null;
57
- if (pp.startsWith(":")) {
58
- params[pp.slice(1)] = pathParts[i];
59
- continue;
60
- }
61
- if (pp !== pathParts[i]) return null;
62
- }
63
- return patternParts.length === pathParts.length ? params : null;
64
- }
65
- const HTTP_METHODS = [
66
- "GET",
67
- "POST",
68
- "PUT",
69
- "PATCH",
70
- "DELETE",
71
- "HEAD",
72
- "OPTIONS"
73
- ];
74
- /**
75
- * Create a middleware that dispatches API route requests.
76
- * API routes are matched by URL pattern and HTTP method.
77
- */
78
- function createApiMiddleware(routes) {
79
- return async (ctx) => {
80
- for (const route of routes) {
81
- const params = matchApiRoute(route.pattern, ctx.path);
82
- if (!params) continue;
83
- const method = ctx.req.method.toUpperCase();
84
- const handler = route.module[method];
85
- if (!handler) {
86
- const allowed = HTTP_METHODS.filter((m) => route.module[m]).join(", ");
87
- return new Response(null, {
88
- status: 405,
89
- headers: {
90
- Allow: allowed,
91
- "Content-Type": "application/json"
92
- }
93
- });
94
- }
95
- return handler({
96
- request: ctx.req,
97
- url: ctx.url,
98
- path: ctx.path,
99
- params,
100
- headers: ctx.req.headers
101
- });
102
- }
103
- };
104
- }
105
- /**
106
- * Detect whether a route file is an API route.
107
- * API routes are `.ts` or `.js` files inside an `api/` directory.
108
- */
109
- function isApiRoute(filePath) {
110
- const normalized = filePath.replace(/\\/g, "/");
111
- return normalized.startsWith("api/") && (normalized.endsWith(".ts") || normalized.endsWith(".js")) && !normalized.endsWith(".tsx") && !normalized.endsWith(".jsx");
112
- }
113
- /**
114
- * Convert an API route file path to a URL pattern.
115
- *
116
- * Examples:
117
- * "api/posts.ts" → "/api/posts"
118
- * "api/posts/index.ts" → "/api/posts"
119
- * "api/posts/[id].ts" → "/api/posts/:id"
120
- * "api/[...path].ts" → "/api/:path*"
121
- */
122
- function apiFilePathToPattern(filePath) {
123
- let route = filePath;
124
- for (const ext of [".ts", ".js"]) if (route.endsWith(ext)) {
125
- route = route.slice(0, -ext.length);
126
- break;
127
- }
128
- const segments = route.split("/");
129
- const urlSegments = [];
130
- for (const seg of segments) {
131
- if (seg === "index") continue;
132
- const catchAll = seg.match(/^\[\.\.\.(\w+)\]$/);
133
- if (catchAll) {
134
- urlSegments.push(`:${catchAll[1]}*`);
135
- continue;
136
- }
137
- const dynamic = seg.match(/^\[(\w+)\]$/);
138
- if (dynamic) {
139
- urlSegments.push(`:${dynamic[1]}`);
140
- continue;
141
- }
142
- urlSegments.push(seg);
143
- }
144
- return `/${urlSegments.join("/")}`;
145
- }
146
- /**
147
- * Generate a virtual module that exports API route entries.
148
- * Each entry maps a URL pattern to a module with HTTP method handlers.
149
- */
150
- function generateApiRouteModule(files, routesDir) {
151
- const apiFiles = files.filter(isApiRoute);
152
- if (apiFiles.length === 0) return "export const apiRoutes = []\n";
153
- const imports = [];
154
- const entries = [];
155
- for (let i = 0; i < apiFiles.length; i++) {
156
- const name = `_api${i}`;
157
- const file = apiFiles[i];
158
- if (!file) continue;
159
- const fullPath = `${routesDir}/${file}`;
160
- const pattern = apiFilePathToPattern(file);
161
- imports.push(`import * as ${name} from "${fullPath}"`);
162
- entries.push(` { pattern: ${JSON.stringify(pattern)}, module: ${name} }`);
163
- }
164
- return [
165
- ...imports,
166
- "",
167
- "export const apiRoutes = [",
168
- entries.join(",\n"),
169
- "]"
170
- ].join("\n");
171
- }
172
-
173
- //#endregion
174
- //#region src/not-found.ts
175
- const DEFAULT_404_BODY = "<h1>404 — Not Found</h1><p>The page you requested does not exist.</p>";
176
- /**
177
- * Render a 404 component to a full HTML string.
178
- * If no component is provided, returns a default 404 page.
179
- */
180
- async function render404Page(component, template) {
181
- let body;
182
- if (component) body = await renderToString(h(component, null));
183
- else body = DEFAULT_404_BODY;
184
- if (template?.includes("<!--pyreon-app-->")) return template.replace("<!--pyreon-app-->", body);
185
- return `<!DOCTYPE html>
186
- <html lang="en">
187
- <head>
188
- <meta charset="UTF-8">
189
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
190
- <title>404 — Not Found</title>
191
- </head>
192
- <body>
193
- ${body}
194
- </body>
195
- </html>`;
196
- }
197
-
198
- //#endregion
199
- //#region src/entry-server.ts
200
- /**
201
- * Create a middleware that dispatches per-route middleware based on URL pattern matching.
202
- */
203
- function createRouteMiddlewareDispatcher(entries) {
204
- return async (ctx) => {
205
- for (const entry of entries) if (matchPattern(entry.pattern, ctx.path)) {
206
- const mw = Array.isArray(entry.middleware) ? entry.middleware : [entry.middleware];
207
- for (const fn of mw) {
208
- const result = await fn(ctx);
209
- if (result) return result;
210
- }
211
- }
212
- };
213
- }
214
- /** Simple URL pattern matcher supporting :param and :param* segments. */
215
- function matchPattern(pattern, path) {
216
- const patternParts = pattern.split("/").filter(Boolean);
217
- const pathParts = path.split("/").filter(Boolean);
218
- for (let i = 0; i < patternParts.length; i++) {
219
- const pp = patternParts[i];
220
- if (!pp) continue;
221
- if (pp.endsWith("*")) return true;
222
- if (pp.startsWith(":")) continue;
223
- if (pp !== pathParts[i]) return false;
224
- }
225
- return patternParts.length === pathParts.length;
226
- }
227
- /**
228
- * Create the SSR request handler for production.
229
- *
230
- * @example
231
- * import { routes } from "virtual:zero/routes"
232
- * import { routeMiddleware } from "virtual:zero/route-middleware"
233
- * import { createServer } from "@pyreon/zero"
234
- *
235
- * export default createServer({ routes, routeMiddleware, apiRoutes })
236
- */
237
- function createServer(options) {
238
- const config = options.config ?? {};
239
- const allMiddleware = [];
240
- if (options.apiRoutes?.length) allMiddleware.push(createApiMiddleware(options.apiRoutes));
241
- if (options.routeMiddleware?.length) allMiddleware.push(createRouteMiddlewareDispatcher(options.routeMiddleware));
242
- allMiddleware.push(...config.middleware ?? []);
243
- allMiddleware.push(...options.middleware ?? []);
244
- const { App } = createApp({
245
- routes: options.routes,
246
- routerMode: "history"
247
- });
248
- const handler = createHandler({
249
- App,
250
- routes: options.routes,
251
- middleware: allMiddleware,
252
- mode: config.ssr?.mode ?? "string",
253
- ...options.template ? { template: options.template } : {},
254
- ...options.clientEntry ? { clientEntry: options.clientEntry } : {}
255
- });
256
- if (!options.notFoundComponent) return handler;
257
- const NotFound = options.notFoundComponent;
258
- const routePatterns = flattenRoutePatterns$1(options.routes);
259
- return async (req) => {
260
- const pathname = new URL(req.url).pathname;
261
- if (!routePatterns.some((pattern) => matchPattern(pattern, pathname))) {
262
- const fullHtml = await render404Page(NotFound, options.template);
263
- return new Response(fullHtml, {
264
- status: 404,
265
- headers: { "Content-Type": "text/html; charset=utf-8" }
266
- });
267
- }
268
- return handler(req);
269
- };
270
- }
271
- /** Extract all URL patterns from a nested route tree. */
272
- function flattenRoutePatterns$1(routes, prefix = "") {
273
- const patterns = [];
274
- for (const route of routes) {
275
- const fullPath = route.path === "/" && prefix ? prefix : `${prefix}${route.path}`;
276
- patterns.push(fullPath);
277
- if (route.children) patterns.push(...flattenRoutePatterns$1(route.children, fullPath));
278
- }
279
- return patterns;
280
- }
281
-
282
- //#endregion
283
- //#region src/config.ts
284
- /**
285
- * Define a Zero configuration.
286
- * Used in `zero.config.ts` at the project root.
287
- *
288
- * @example
289
- * import { defineConfig } from "@pyreon/zero/config"
290
- *
291
- * export default defineConfig({
292
- * mode: "ssr",
293
- * ssr: { mode: "stream" },
294
- * port: 3000,
295
- * })
296
- */
297
- function defineConfig(config) {
298
- return config;
299
- }
300
- /** Merge user config with defaults. */
301
- function resolveConfig(userConfig = {}) {
302
- return {
303
- mode: "ssr",
304
- base: "/",
305
- port: 3e3,
306
- adapter: "node",
307
- ...userConfig,
308
- ssr: {
309
- mode: "string",
310
- ...userConfig.ssr
311
- }
312
- };
313
- }
314
-
315
- //#endregion
316
- //#region src/error-overlay.ts
317
- /**
318
- * Dev-only error overlay for SSR/loader errors.
319
- * Renders a styled HTML page with the error stack trace.
320
- */
321
- function renderErrorOverlay(error) {
322
- return `<!DOCTYPE html>
323
- <html lang="en">
324
- <head>
325
- <meta charset="UTF-8">
326
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
327
- <title>SSR Error — Pyreon Zero</title>
328
- <style>
329
- * { margin: 0; padding: 0; box-sizing: border-box; }
330
- body {
331
- font-family: ui-monospace, "Cascadia Code", "Source Code Pro", Menlo, Consolas, monospace;
332
- background: #1a1a2e;
333
- color: #e0e0e0;
334
- min-height: 100vh;
335
- padding: 2rem;
336
- }
337
- .overlay {
338
- max-width: 900px;
339
- margin: 0 auto;
340
- }
341
- .header {
342
- display: flex;
343
- align-items: center;
344
- gap: 0.75rem;
345
- margin-bottom: 1.5rem;
346
- }
347
- .badge {
348
- background: #e74c3c;
349
- color: white;
350
- padding: 0.25rem 0.75rem;
351
- border-radius: 4px;
352
- font-size: 0.75rem;
353
- font-weight: 600;
354
- text-transform: uppercase;
355
- letter-spacing: 0.05em;
356
- }
357
- .label {
358
- color: #888;
359
- font-size: 0.85rem;
360
- }
361
- .message {
362
- font-size: 1.25rem;
363
- color: #ff6b6b;
364
- margin-bottom: 1.5rem;
365
- line-height: 1.5;
366
- word-break: break-word;
367
- }
368
- .stack {
369
- background: #16213e;
370
- border: 1px solid #2a2a4a;
371
- border-radius: 8px;
372
- padding: 1.25rem;
373
- overflow-x: auto;
374
- font-size: 0.8rem;
375
- line-height: 1.7;
376
- white-space: pre-wrap;
377
- word-break: break-all;
378
- }
379
- .stack .at { color: #888; }
380
- .stack .file { color: #4ecdc4; }
381
- .hint {
382
- margin-top: 1.5rem;
383
- padding: 1rem;
384
- background: #1e2a45;
385
- border-radius: 6px;
386
- border-left: 3px solid #3498db;
387
- font-size: 0.8rem;
388
- color: #aaa;
389
- line-height: 1.5;
390
- }
391
- </style>
392
- </head>
393
- <body>
394
- <div class="overlay">
395
- <div class="header">
396
- <span class="badge">SSR Error</span>
397
- <span class="label">Pyreon Zero — Dev Mode</span>
398
- </div>
399
- <div class="message">${escapeHtml(error.message || "Unknown error")}</div>
400
- <pre class="stack">${formatStack(escapeHtml(error.stack || ""))}</pre>
401
- <div class="hint">
402
- This error occurred during server-side rendering. Check the terminal for
403
- the full stack trace. This overlay is only shown in development.
404
- </div>
405
- </div>
406
- </body>
407
- </html>`;
408
- }
409
- function escapeHtml(str) {
410
- return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
411
- }
412
- function formatStack(stack) {
413
- return stack.split("\n").map((line) => {
414
- if (line.includes("at ")) {
415
- const fileMatch = line.match(/\(([^)]+)\)/);
416
- if (fileMatch) return line.replace(fileMatch[0], `(<span class="file">${fileMatch[1]}</span>)`);
417
- }
418
- return line;
419
- }).join("\n");
420
- }
421
-
422
- //#endregion
423
- //#region src/vite-plugin.ts
424
- /**
425
- * Scan node_modules/@pyreon/ to discover all installed Pyreon packages.
426
- * Returns package names to exclude from Vite's dep optimizer.
427
- */
428
- function scanPyreonPackages(root) {
429
- const pyreonDir = join(root, "node_modules", "@pyreon");
430
- if (!existsSync(pyreonDir)) return [];
431
- try {
432
- return readdirSync(pyreonDir).filter((name) => !name.startsWith(".")).map((name) => `@pyreon/${name}`);
433
- } catch {
434
- return [];
435
- }
436
- }
437
- const VIRTUAL_ROUTES_ID = "virtual:zero/routes";
438
- const RESOLVED_VIRTUAL_ROUTES_ID = `\0${VIRTUAL_ROUTES_ID}`;
439
- const VIRTUAL_MIDDLEWARE_ID = "virtual:zero/route-middleware";
440
- const RESOLVED_VIRTUAL_MIDDLEWARE_ID = `\0${VIRTUAL_MIDDLEWARE_ID}`;
441
- const VIRTUAL_API_ROUTES_ID = "virtual:zero/api-routes";
442
- const RESOLVED_VIRTUAL_API_ROUTES_ID = `\0${VIRTUAL_API_ROUTES_ID}`;
443
- /**
444
- * Zero Vite plugin — adds file-based routing and zero-config conventions
445
- * on top of @pyreon/vite-plugin.
446
- *
447
- * @example
448
- * // vite.config.ts
449
- * import pyreon from "@pyreon/vite-plugin"
450
- * import zero from "@pyreon/zero"
451
- *
452
- * export default {
453
- * plugins: [pyreon(), zero()],
454
- * }
455
- */
456
- function zeroPlugin(userConfig = {}) {
457
- const config = resolveConfig(userConfig);
458
- let routesDir;
459
- let root;
460
- return {
461
- name: "pyreon-zero",
462
- enforce: "pre",
463
- _zeroConfig: userConfig,
464
- configResolved(resolvedConfig) {
465
- root = resolvedConfig.root;
466
- routesDir = `${root}/src/routes`;
467
- },
468
- resolveId(id) {
469
- if (id === VIRTUAL_ROUTES_ID) return RESOLVED_VIRTUAL_ROUTES_ID;
470
- if (id === VIRTUAL_MIDDLEWARE_ID) return RESOLVED_VIRTUAL_MIDDLEWARE_ID;
471
- if (id === VIRTUAL_API_ROUTES_ID) return RESOLVED_VIRTUAL_API_ROUTES_ID;
472
- },
473
- async load(id) {
474
- if (id === RESOLVED_VIRTUAL_ROUTES_ID) try {
475
- return generateRouteModule(await scanRouteFiles(routesDir), routesDir, { staticImports: config.mode === "ssg" });
476
- } catch (_err) {
477
- return `export const routes = []`;
478
- }
479
- if (id === RESOLVED_VIRTUAL_MIDDLEWARE_ID) try {
480
- return generateMiddlewareModule(await scanRouteFiles(routesDir), routesDir);
481
- } catch (_err) {
482
- return `export const routeMiddleware = []`;
483
- }
484
- if (id === RESOLVED_VIRTUAL_API_ROUTES_ID) try {
485
- return generateApiRouteModule(await scanRouteFiles(routesDir), routesDir);
486
- } catch (_err) {
487
- return `export const apiRoutes = []`;
488
- }
489
- },
490
- configureServer(server) {
491
- server.middlewares.use((req, res, next) => {
492
- const accept = req.headers.accept ?? "";
493
- if (!accept.includes("text/html") && !accept.includes("*/*")) return next();
494
- const pathname = req.url?.split("?")[0] ?? "/";
495
- if (pathname.startsWith("/@") || pathname.startsWith("/__")) return next();
496
- if (/\.\w+$/.test(pathname)) return next();
497
- handle404(server, routesDir, pathname, res).then((handled) => {
498
- if (!handled) next();
499
- }, () => next());
500
- });
501
- server.middlewares.use((req, res, next) => {
502
- if (!(req.headers.accept ?? "").includes("text/html")) return next();
503
- const originalEnd = res.end.bind(res);
504
- let errored = false;
505
- const handleError = (err) => {
506
- if (errored) return;
507
- errored = true;
508
- const error = err instanceof Error ? err : new Error(String(err));
509
- server.ssrFixStacktrace(error);
510
- const html = renderErrorOverlay(error);
511
- res.statusCode = 500;
512
- res.setHeader("Content-Type", "text/html; charset=utf-8");
513
- res.setHeader("Content-Length", Buffer.byteLength(html));
514
- originalEnd(html);
515
- };
516
- res.on("error", handleError);
517
- try {
518
- const result = next();
519
- if (result && typeof result.catch === "function") result.catch(handleError);
520
- } catch (err) {
521
- handleError(err);
522
- }
523
- });
524
- server.watcher.add(`${routesDir}/**/*.{tsx,jsx,ts,js}`);
525
- server.watcher.on("all", (event, path) => {
526
- if (path.startsWith(routesDir) && (event === "add" || event === "unlink")) {
527
- for (const resolvedId of [
528
- RESOLVED_VIRTUAL_ROUTES_ID,
529
- RESOLVED_VIRTUAL_MIDDLEWARE_ID,
530
- RESOLVED_VIRTUAL_API_ROUTES_ID
531
- ]) {
532
- const mod = server.moduleGraph.getModuleById(resolvedId);
533
- if (mod) server.moduleGraph.invalidateModule(mod);
534
- }
535
- server.ws.send({ type: "full-reload" });
536
- }
537
- });
538
- },
539
- config(userConfig) {
540
- return {
541
- resolve: { conditions: ["bun"] },
542
- optimizeDeps: { exclude: scanPyreonPackages(userConfig.root ?? process.cwd()) },
543
- server: { port: config.port },
544
- define: {
545
- __ZERO_MODE__: JSON.stringify(config.mode),
546
- __ZERO_BASE__: JSON.stringify(config.base)
547
- }
548
- };
549
- }
550
- };
551
- }
552
- /**
553
- * Check if the requested path matches any route. If not, render a 404 page.
554
- * Returns true if the 404 was handled (response sent), false otherwise.
555
- *
556
- * In dev mode, the _404.tsx component cannot be SSR-rendered because
557
- * the compiler emits _tpl() calls that require `document`. Instead,
558
- * we return a static 404 page. The actual component rendering happens
559
- * on the client side when the SPA loads.
560
- */
561
- async function handle404(server, _routesDir, pathname, res) {
562
- const routes = (await server.ssrLoadModule(VIRTUAL_ROUTES_ID)).routes;
563
- if (flattenRoutePatterns(routes).some((pattern) => matchPattern(pattern, pathname))) return false;
564
- const html = await render404Page(void 0);
565
- res.statusCode = 404;
566
- res.setHeader("Content-Type", "text/html; charset=utf-8");
567
- res.setHeader("Content-Length", Buffer.byteLength(html));
568
- res.end(html);
569
- return true;
570
- }
571
- /** Extract all URL patterns from a nested route tree. */
572
- function flattenRoutePatterns(routes, prefix = "") {
573
- const patterns = [];
574
- for (const route of routes) {
575
- if (!route.path) continue;
576
- const fullPath = route.path === "/" && prefix ? prefix : `${prefix}${route.path}`;
577
- patterns.push(fullPath);
578
- if (route.children) patterns.push(...flattenRoutePatterns(route.children, fullPath));
579
- }
580
- return patterns;
581
- }
582
-
583
- //#endregion
584
- //#region src/isr.ts
585
- /**
586
- * In-memory ISR cache with stale-while-revalidate semantics.
587
- *
588
- * Wraps an SSR handler and caches responses per URL path.
589
- * Serves stale content immediately while revalidating in the background.
590
- */
591
- function createISRHandler(handler, config) {
592
- const cache = /* @__PURE__ */ new Map();
593
- const revalidating = /* @__PURE__ */ new Set();
594
- const revalidateMs = config.revalidate * 1e3;
595
- async function revalidate(url) {
596
- const key = url.pathname;
597
- if (revalidating.has(key)) return;
598
- revalidating.add(key);
599
- try {
600
- const res = await handler(new Request(url.href, { method: "GET" }));
601
- const html = await res.text();
602
- const headers = {};
603
- res.headers.forEach((v, k) => {
604
- headers[k] = v;
605
- });
606
- cache.set(key, {
607
- html,
608
- headers,
609
- timestamp: Date.now()
610
- });
611
- } catch {} finally {
612
- revalidating.delete(key);
613
- }
614
- }
615
- return async (req) => {
616
- if (req.method !== "GET") return handler(req);
617
- const url = new URL(req.url);
618
- const key = url.pathname;
619
- const entry = cache.get(key);
620
- if (entry) {
621
- const age = Date.now() - entry.timestamp;
622
- if (age > revalidateMs) revalidate(url);
623
- return new Response(entry.html, {
624
- status: 200,
625
- headers: {
626
- ...entry.headers,
627
- "content-type": "text/html; charset=utf-8",
628
- "x-isr-cache": age > revalidateMs ? "STALE" : "HIT",
629
- "x-isr-age": String(Math.round(age / 1e3))
630
- }
631
- });
632
- }
633
- const res = await handler(req);
634
- const html = await res.text();
635
- const headers = {};
636
- res.headers.forEach((v, k) => {
637
- headers[k] = v;
638
- });
639
- cache.set(key, {
640
- html,
641
- headers,
642
- timestamp: Date.now()
643
- });
644
- return new Response(html, {
645
- status: 200,
646
- headers: {
647
- ...headers,
648
- "content-type": "text/html; charset=utf-8",
649
- "x-isr-cache": "MISS"
650
- }
651
- });
652
- };
653
- }
654
-
655
- //#endregion
656
- //#region src/adapters/bun.ts
657
- /**
658
- * Bun adapter — generates a standalone Bun.serve() entry.
659
- */
660
- function bunAdapter() {
661
- return {
662
- name: "bun",
663
- async build(options) {
664
- const { writeFile, cp, mkdir } = await import("node:fs/promises");
665
- const { join } = await import("node:path");
666
- const outDir = options.outDir;
667
- await mkdir(outDir, { recursive: true });
668
- await cp(options.clientOutDir, join(outDir, "client"), { recursive: true });
669
- await cp(join(options.serverEntry, ".."), join(outDir, "server"), { recursive: true });
670
- const port = options.config.port ?? 3e3;
671
- const serverEntry = `
672
- const handler = (await import("./server/entry-server.js")).default
673
- const clientDir = new URL("./client/", import.meta.url).pathname
674
-
675
- Bun.serve({
676
- port: ${port},
677
- async fetch(req) {
678
- const url = new URL(req.url)
679
-
680
- // Try static files first
681
- if (req.method === "GET") {
682
- const filePath = clientDir + (url.pathname === "/" ? "index.html" : url.pathname)
683
- // Prevent path traversal — ensure resolved path stays within clientDir
684
- const resolved = Bun.resolveSync(filePath, ".")
685
- if (!resolved.startsWith(Bun.resolveSync(clientDir, "."))) {
686
- return new Response("Forbidden", { status: 403 })
687
- }
688
- const file = Bun.file(filePath)
689
- if (await file.exists()) {
690
- return new Response(file, {
691
- headers: {
692
- "cache-control": filePath.endsWith(".js") || filePath.endsWith(".css")
693
- ? "public, max-age=31536000, immutable"
694
- : "public, max-age=3600",
695
- },
696
- })
697
- }
698
- }
699
-
700
- // Fall through to SSR handler
701
- return handler(req)
702
- },
703
- })
704
-
705
- console.log("\\n ⚡ Zero production server running on http://localhost:${port}\\n")
706
- `.trimStart();
707
- await writeFile(join(outDir, "index.ts"), serverEntry);
708
- }
709
- };
710
- }
711
-
712
- //#endregion
713
- //#region src/adapters/cloudflare.ts
714
- /**
715
- * Cloudflare Pages adapter — generates output for Cloudflare Pages with Functions.
716
- *
717
- * Produces:
718
- * - Client assets in the output directory root (served as static)
719
- * - `_worker.js` — Cloudflare Pages Function for SSR
720
- *
721
- * Note: Cloudflare Pages Functions have a ~1MB module size limit.
722
- * For large apps, configure Vite's SSR build to bundle server code:
723
- * `ssr: { noExternal: true }` in vite.config.ts.
724
- *
725
- * Deploy with: `npx wrangler pages deploy ./dist`
726
- *
727
- * @example
728
- * ```ts
729
- * // zero.config.ts
730
- * import { defineConfig } from "@pyreon/zero"
731
- *
732
- * export default defineConfig({
733
- * adapter: "cloudflare",
734
- * })
735
- * ```
736
- */
737
- function cloudflareAdapter() {
738
- return {
739
- name: "cloudflare",
740
- async build(options) {
741
- const { writeFile, cp, mkdir } = await import("node:fs/promises");
742
- const { join } = await import("node:path");
743
- const outDir = options.outDir;
744
- await mkdir(outDir, { recursive: true });
745
- await cp(options.clientOutDir, outDir, { recursive: true });
746
- await cp(join(options.serverEntry, ".."), join(outDir, "_server"), { recursive: true });
747
- const workerEntry = `
748
- import handler from "./_server/entry-server.js"
749
-
750
- export default {
751
- async fetch(request, env, ctx) {
752
- const url = new URL(request.url)
753
-
754
- // Let Cloudflare serve static assets (files with extensions)
755
- // This check is a fallback — Pages routes static files automatically
756
- const ext = url.pathname.split(".").pop()
757
- if (ext && ext !== url.pathname && !url.pathname.endsWith("/")) {
758
- // Cloudflare Pages handles static assets automatically via its asset binding
759
- // Only reach here if the file doesn't exist — fall through to SSR
760
- }
761
-
762
- // SSR handler
763
- try {
764
- return await handler(request)
765
- } catch (err) {
766
- return new Response("Internal Server Error", { status: 500 })
767
- }
768
- },
769
- }
770
- `.trimStart();
771
- await writeFile(join(outDir, "_worker.js"), workerEntry);
772
- await writeFile(join(outDir, "_routes.json"), JSON.stringify({
773
- version: 1,
774
- include: ["/*"],
775
- exclude: [
776
- "/assets/*",
777
- "/favicon.*",
778
- "/site.webmanifest",
779
- "/robots.txt",
780
- "/sitemap.xml"
781
- ]
782
- }, null, 2));
783
- }
784
- };
785
- }
786
-
787
- //#endregion
788
- //#region src/adapters/netlify.ts
789
- /**
790
- * Netlify adapter — generates output for Netlify Functions (v2).
791
- *
792
- * Produces:
793
- * - Client assets in `publish/` directory
794
- * - `netlify/functions/ssr.mjs` — Netlify Function for SSR
795
- * - `netlify.toml` — routing configuration
796
- *
797
- * @example
798
- * ```ts
799
- * // zero.config.ts
800
- * import { defineConfig } from "@pyreon/zero"
801
- *
802
- * export default defineConfig({
803
- * adapter: "netlify",
804
- * })
805
- * ```
806
- */
807
- function netlifyAdapter() {
808
- return {
809
- name: "netlify",
810
- async build(options) {
811
- const { writeFile, cp, mkdir } = await import("node:fs/promises");
812
- const { join } = await import("node:path");
813
- const outDir = options.outDir;
814
- const publishDir = join(outDir, "publish");
815
- const functionsDir = join(outDir, "netlify", "functions");
816
- await mkdir(publishDir, { recursive: true });
817
- await mkdir(functionsDir, { recursive: true });
818
- await cp(options.clientOutDir, publishDir, { recursive: true });
819
- await cp(join(options.serverEntry, ".."), join(functionsDir, "_server"), { recursive: true });
820
- const funcEntry = `
821
- import handler from "./_server/entry-server.js"
822
-
823
- export default async function(req, context) {
824
- try {
825
- return await handler(req)
826
- } catch (err) {
827
- return new Response("Internal Server Error", { status: 500 })
828
- }
829
- }
830
-
831
- export const config = {
832
- path: "/*",
833
- preferStatic: true,
834
- }
835
- `.trimStart();
836
- await writeFile(join(functionsDir, "ssr.mjs"), funcEntry);
837
- const toml = `
838
- [build]
839
- publish = "publish"
840
- functions = "netlify/functions"
841
-
842
- [[headers]]
843
- for = "/assets/*"
844
- [headers.values]
845
- Cache-Control = "public, max-age=31536000, immutable"
846
-
847
- [[redirects]]
848
- from = "/*"
849
- to = "/.netlify/functions/ssr"
850
- status = 200
851
- conditions = {Role = ["admin", "user", ""]}
852
- `.trimStart();
853
- await writeFile(join(outDir, "netlify.toml"), toml);
854
- }
855
- };
856
- }
857
-
858
- //#endregion
859
- //#region src/adapters/node.ts
860
- /**
861
- * Node.js adapter — generates a standalone server entry using node:http.
862
- */
863
- function nodeAdapter() {
864
- return {
865
- name: "node",
866
- async build(options) {
867
- const { writeFile, cp, mkdir } = await import("node:fs/promises");
868
- const { join } = await import("node:path");
869
- const outDir = options.outDir;
870
- await mkdir(outDir, { recursive: true });
871
- await cp(options.clientOutDir, join(outDir, "client"), { recursive: true });
872
- await cp(join(options.serverEntry, ".."), join(outDir, "server"), { recursive: true });
873
- const port = options.config.port ?? 3e3;
874
- const serverEntry = `
875
- import { createServer } from "node:http"
876
- import { readFile } from "node:fs/promises"
877
- import { join, extname } from "node:path"
878
- import { fileURLToPath } from "node:url"
879
-
880
- const __dirname = fileURLToPath(new URL(".", import.meta.url))
881
- const handler = (await import("./server/entry-server.js")).default
882
- const clientDir = join(__dirname, "client")
883
-
884
- const MIME_TYPES = {
885
- ".html": "text/html",
886
- ".js": "application/javascript",
887
- ".css": "text/css",
888
- ".json": "application/json",
889
- ".png": "image/png",
890
- ".jpg": "image/jpeg",
891
- ".svg": "image/svg+xml",
892
- ".woff2": "font/woff2",
893
- ".woff": "font/woff",
894
- ".ico": "image/x-icon",
895
- }
896
-
897
- const server = createServer(async (req, res) => {
898
- const url = new URL(req.url ?? "/", "http://localhost")
899
-
900
- // Try to serve static files first
901
- if (req.method === "GET") {
902
- try {
903
- const filePath = join(clientDir, url.pathname === "/" ? "index.html" : url.pathname)
904
- // Prevent path traversal — ensure resolved path stays within clientDir
905
- const { resolve } = await import("node:path")
906
- const resolved = resolve(filePath)
907
- if (!resolved.startsWith(resolve(clientDir))) {
908
- res.writeHead(403)
909
- res.end("Forbidden")
910
- return
911
- }
912
- const ext = extname(filePath)
913
- if (ext && ext !== ".html") {
914
- const data = await readFile(filePath)
915
- const mime = MIME_TYPES[ext] || "application/octet-stream"
916
- res.writeHead(200, {
917
- "content-type": mime,
918
- "cache-control": ext === ".js" || ext === ".css"
919
- ? "public, max-age=31536000, immutable"
920
- : "public, max-age=3600",
921
- })
922
- res.end(data)
923
- return
924
- }
925
- } catch {}
926
- }
927
-
928
- // Fall through to SSR handler
929
- const headers = {}
930
- for (const [key, value] of Object.entries(req.headers)) {
931
- if (value) headers[key] = Array.isArray(value) ? value.join(", ") : value
932
- }
933
-
934
- const request = new Request(url.href, {
935
- method: req.method,
936
- headers,
937
- })
938
-
939
- const response = await handler(request)
940
- const body = await response.text()
941
-
942
- const responseHeaders = {}
943
- response.headers.forEach((v, k) => { responseHeaders[k] = v })
944
-
945
- res.writeHead(response.status, responseHeaders)
946
- res.end(body)
947
- })
948
-
949
- server.listen(${port}, () => {
950
- console.log("\\n ⚡ Zero production server running on http://localhost:${port}\\n")
951
- })
952
- `.trimStart();
953
- await writeFile(join(outDir, "index.js"), serverEntry);
954
- await writeFile(join(outDir, "package.json"), JSON.stringify({ type: "module" }, null, 2));
955
- }
956
- };
957
- }
958
-
959
- //#endregion
960
- //#region src/adapters/static.ts
961
- /**
962
- * Static adapter — just copies the client build output.
963
- * Used with SSG mode where all pages are pre-rendered at build time.
964
- */
965
- function staticAdapter() {
966
- return {
967
- name: "static",
968
- async build(options) {
969
- const { cp, mkdir } = await import("node:fs/promises");
970
- await mkdir(options.outDir, { recursive: true });
971
- await cp(options.clientOutDir, options.outDir, { recursive: true });
972
- }
973
- };
974
- }
975
-
976
- //#endregion
977
- //#region src/adapters/vercel.ts
978
- /**
979
- * Vercel adapter — generates output for Vercel's Build Output API v3.
980
- *
981
- * Produces a `.vercel/output` directory with:
982
- * - `static/` — client-side assets (JS, CSS, images)
983
- * - `functions/ssr.func/` — serverless function for SSR
984
- * - `config.json` — routing configuration
985
- *
986
- * @example
987
- * ```ts
988
- * // zero.config.ts
989
- * import { defineConfig } from "@pyreon/zero"
990
- *
991
- * export default defineConfig({
992
- * adapter: "vercel",
993
- * })
994
- * ```
995
- */
996
- function vercelAdapter() {
997
- return {
998
- name: "vercel",
999
- async build(options) {
1000
- const { writeFile, cp, mkdir } = await import("node:fs/promises");
1001
- const { join } = await import("node:path");
1002
- const vercelDir = join(options.outDir, ".vercel", "output");
1003
- const staticDir = join(vercelDir, "static");
1004
- const funcDir = join(vercelDir, "functions", "ssr.func");
1005
- await mkdir(staticDir, { recursive: true });
1006
- await mkdir(funcDir, { recursive: true });
1007
- await cp(options.clientOutDir, staticDir, { recursive: true });
1008
- await cp(join(options.serverEntry, ".."), funcDir, { recursive: true });
1009
- const funcEntry = `
1010
- export default async function handler(req) {
1011
- const handler = (await import("./entry-server.js")).default
1012
- return handler(req)
1013
- }
1014
- `.trimStart();
1015
- await writeFile(join(funcDir, "index.js"), funcEntry);
1016
- await writeFile(join(funcDir, ".vc-config.json"), JSON.stringify({
1017
- runtime: "nodejs20.x",
1018
- handler: "index.js",
1019
- launcherType: "Nodejs"
1020
- }, null, 2));
1021
- await writeFile(join(vercelDir, "config.json"), JSON.stringify({
1022
- version: 3,
1023
- routes: [
1024
- {
1025
- src: "/assets/(.*)",
1026
- headers: { "Cache-Control": "public, max-age=31536000, immutable" }
1027
- },
1028
- {
1029
- src: "/(favicon\\..*|site\\.webmanifest|robots\\.txt|sitemap\\.xml)",
1030
- dest: "/$1"
1031
- },
1032
- {
1033
- src: "/(.*)",
1034
- dest: "/ssr"
1035
- }
1036
- ]
1037
- }, null, 2));
1038
- }
1039
- };
1040
- }
1041
-
1042
- //#endregion
1043
- //#region src/adapters/index.ts
1044
- /**
1045
- * Resolve the adapter from config.
1046
- * Returns a built-in adapter or throws if unknown.
1047
- */
1048
- function resolveAdapter(config) {
1049
- const name = config.adapter ?? "node";
1050
- switch (name) {
1051
- case "node": return nodeAdapter();
1052
- case "bun": return bunAdapter();
1053
- case "static": return staticAdapter();
1054
- case "vercel": return vercelAdapter();
1055
- case "cloudflare": return cloudflareAdapter();
1056
- case "netlify": return netlifyAdapter();
1057
- default: throw new Error(`[zero] Unknown adapter: "${name}". Use "node", "bun", "static", "vercel", "cloudflare", or "netlify".`);
1058
- }
1059
- }
1060
-
1061
- //#endregion
1062
6
  //#region src/utils/use-intersection-observer.ts
1063
7
  /**
1064
8
  * Observes an element and calls `onIntersect` once it enters the viewport.
@@ -1094,7 +38,7 @@ function useIntersectionObserver(getElement, onIntersect, rootMargin = "200px")
1094
38
  */
1095
39
  /** Shared empty props sentinel — identity-checked in mountElement to skip applyProps. */
1096
40
  const EMPTY_PROPS = {};
1097
- function h$1(type, props, ...children) {
41
+ function h(type, props, ...children) {
1098
42
  return {
1099
43
  type,
1100
44
  props: props ?? EMPTY_PROPS,
@@ -1125,11 +69,11 @@ function jsx(type, props, key) {
1125
69
  ...rest,
1126
70
  key
1127
71
  } : rest;
1128
- if (typeof type === "function") return h$1(type, children !== void 0 ? {
72
+ if (typeof type === "function") return h(type, children !== void 0 ? {
1129
73
  ...propsWithKey,
1130
74
  children
1131
75
  } : propsWithKey);
1132
- return h$1(type, propsWithKey, ...children === void 0 ? [] : Array.isArray(children) ? children : [children]);
76
+ return h(type, propsWithKey, ...children === void 0 ? [] : Array.isArray(children) ? children : [children]);
1133
77
  }
1134
78
  const jsxs = jsx;
1135
79
 
@@ -1217,9 +161,14 @@ function Image(props) {
1217
161
 
1218
162
  //#endregion
1219
163
  //#region src/link.tsx
164
+ const MAX_PREFETCH_CACHE = 200;
1220
165
  const prefetched = /* @__PURE__ */ new Set();
1221
166
  function doPrefetch(href) {
1222
167
  if (prefetched.has(href)) return;
168
+ if (prefetched.size >= MAX_PREFETCH_CACHE) {
169
+ const first = prefetched.values().next().value;
170
+ if (first) prefetched.delete(first);
171
+ }
1223
172
  prefetched.add(href);
1224
173
  const docLink = document.createElement("link");
1225
174
  docLink.rel = "prefetch";
@@ -1457,714 +406,370 @@ function Script(props) {
1457
406
  }
1458
407
 
1459
408
  //#endregion
1460
- //#region src/cache.ts
1461
- const HASHED_ASSET = /\.[a-f0-9]{8,}\.\w+$/;
1462
- const STATIC_EXT = /\.(png|jpe?g|gif|svg|webp|avif|ico|woff2?|ttf|otf|eot|mp4|webm|ogg|mp3|wav)$/i;
1463
- const SCRIPT_EXT = /\.(js|css|mjs)$/i;
1464
- /** @internal Exported for testing */
1465
- function matchGlob(pattern, path) {
1466
- const regex = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
1467
- return new RegExp(`^${regex}$`).test(path);
1468
- }
1469
- function resolveControl(path, immutableDuration, staticDuration, pageDuration, swr) {
1470
- if (HASHED_ASSET.test(path)) return `public, max-age=${immutableDuration}, immutable`;
1471
- if (SCRIPT_EXT.test(path)) return `public, max-age=3600, stale-while-revalidate=${swr}`;
1472
- if (STATIC_EXT.test(path)) return `public, max-age=${staticDuration}, stale-while-revalidate=${swr}`;
1473
- if (pageDuration > 0) return `public, max-age=${pageDuration}, stale-while-revalidate=${swr}`;
1474
- return "no-cache";
1475
- }
409
+ //#region src/i18n-routing.ts
1476
410
  /**
1477
- * Cache control middleware for Zero.
1478
- * Sets Cache-Control headers on the response based on asset type.
1479
- *
1480
- * @example
1481
- * import { cacheMiddleware } from "@pyreon/zero/cache"
1482
- *
1483
- * export default createHandler({
1484
- * routes,
1485
- * middleware: [
1486
- * cacheMiddleware({
1487
- * pages: 60,
1488
- * staleWhileRevalidate: 300,
1489
- * rules: [
1490
- * { match: "/api/*", control: "no-store" },
1491
- * ],
1492
- * }),
1493
- * ],
1494
- * })
411
+ * Extract locale from a URL path.
412
+ * Returns { locale, pathWithoutLocale }.
1495
413
  */
1496
- function cacheMiddleware(config = {}) {
1497
- const immutableDuration = config.immutable ?? 31536e3;
1498
- const staticDuration = config.static ?? 86400;
1499
- const pageDuration = config.pages ?? 0;
1500
- const swr = config.staleWhileRevalidate ?? 60;
1501
- const rules = config.rules ?? [];
1502
- return (ctx) => {
1503
- const path = ctx.url.pathname;
1504
- for (const rule of rules) if (matchGlob(rule.match, path)) {
1505
- ctx.headers.set("Cache-Control", rule.control);
1506
- return;
1507
- }
1508
- const control = resolveControl(path, immutableDuration, staticDuration, pageDuration, swr);
1509
- ctx.headers.set("Cache-Control", control);
414
+ function extractLocaleFromPath(path, locales, defaultLocale) {
415
+ const segments = path.split("/").filter(Boolean);
416
+ const firstSegment = segments[0]?.toLowerCase();
417
+ if (firstSegment && locales.includes(firstSegment)) return {
418
+ locale: firstSegment,
419
+ pathWithoutLocale: "/" + segments.slice(1).join("/") || "/"
1510
420
  };
1511
- }
1512
- /**
1513
- * Security headers middleware.
1514
- * Adds common security headers to all responses.
1515
- */
1516
- function securityHeaders() {
1517
- return (ctx) => {
1518
- ctx.headers.set("X-Content-Type-Options", "nosniff");
1519
- ctx.headers.set("X-Frame-Options", "DENY");
1520
- ctx.headers.set("X-XSS-Protection", "1; mode=block");
1521
- ctx.headers.set("Referrer-Policy", "strict-origin-when-cross-origin");
1522
- ctx.headers.set("Permissions-Policy", "camera=(), microphone=(), geolocation=()");
421
+ return {
422
+ locale: defaultLocale,
423
+ pathWithoutLocale: path
1523
424
  };
1524
425
  }
1525
426
  /**
1526
- * Compression detection middleware.
1527
- * Sets Vary: Accept-Encoding header so caches can serve compressed variants.
1528
- * Actual compression is handled by the runtime (Bun/Node) or reverse proxy.
427
+ * Build a localized path.
1529
428
  */
1530
- function varyEncoding() {
1531
- return (ctx) => {
1532
- const existing = ctx.headers.get("Vary");
1533
- if (!existing?.includes("Accept-Encoding")) ctx.headers.set("Vary", existing ? `${existing}, Accept-Encoding` : "Accept-Encoding");
1534
- };
429
+ function buildLocalePath(path, locale, defaultLocale, strategy) {
430
+ const clean = path === "/" ? "" : path;
431
+ if (strategy === "prefix-except-default" && locale === defaultLocale) return path;
432
+ return `/${locale}${clean}`;
1535
433
  }
1536
-
1537
- //#endregion
1538
- //#region src/middleware.ts
434
+ /** @internal Context for the current locale. */
435
+ const LocaleCtx = createContext("en");
436
+ /** Current locale signal — set by the server middleware or client-side detection. */
437
+ const localeSignal = signal("en");
1539
438
  /**
1540
- * Compose multiple middleware into a single middleware function.
1541
- * Middleware runs sequentially — if any returns a Response, the chain stops.
1542
- *
1543
- * @example
1544
- * import { compose } from "@pyreon/zero/middleware"
1545
- * import { corsMiddleware } from "@pyreon/zero/cors"
1546
- * import { rateLimitMiddleware } from "@pyreon/zero/rate-limit"
439
+ * Read the current locale reactively.
1547
440
  *
1548
- * const combined = compose(
1549
- * corsMiddleware({ origin: "*" }),
1550
- * rateLimitMiddleware({ max: 100 }),
1551
- * cacheMiddleware(),
1552
- * )
1553
- */
1554
- function compose(...middlewares) {
1555
- return async (ctx) => {
1556
- for (const mw of middlewares) {
1557
- const result = await mw(ctx);
1558
- if (result instanceof Response) return result;
1559
- }
1560
- };
1561
- }
1562
- const ZERO_CTX_KEY = "__zeroCtx";
1563
- /**
1564
- * Get the shared Zero context from a middleware context.
1565
- * Creates one if it doesn't exist. Middleware can use this to
1566
- * pass data to downstream middleware without polluting `ctx.locals`.
441
+ * Returns the locale signal value directly — reactive in both SSR and CSR.
442
+ * The server middleware sets `localeSignal` per-request, and client-side
443
+ * `setLocale()` updates it as well.
1567
444
  *
1568
445
  * @example
1569
- * const authMiddleware: Middleware = (ctx) => {
1570
- * const zctx = getContext(ctx)
1571
- * zctx.userId = "user_123"
1572
- * }
1573
- *
1574
- * const loggingMiddleware: Middleware = (ctx) => {
1575
- * const zctx = getContext(ctx)
1576
- * console.log("User:", zctx.userId)
1577
- * }
1578
- */
1579
- function getContext(ctx) {
1580
- let zctx = ctx.locals[ZERO_CTX_KEY];
1581
- if (!zctx) {
1582
- zctx = {};
1583
- ctx.locals[ZERO_CTX_KEY] = zctx;
1584
- }
1585
- return zctx;
1586
- }
1587
-
1588
- //#endregion
1589
- //#region src/font.ts
1590
- /**
1591
- * Normalize a GoogleFontInput (string or object) into a ResolvedFont.
1592
- */
1593
- function resolveGoogleFont(input) {
1594
- if (typeof input === "string") return parseGoogleFamily(input);
1595
- if (input.variable) return {
1596
- family: input.family,
1597
- italic: input.italic ?? false,
1598
- variable: true,
1599
- weightRange: input.weightRange
1600
- };
1601
- return {
1602
- family: input.family,
1603
- italic: input.italic ?? false,
1604
- variable: false,
1605
- weights: input.weights
1606
- };
1607
- }
1608
- /**
1609
- * Parse Google Fonts family string shorthand.
1610
- *
1611
- * Static weights: "Inter:wght@400;500;700"
1612
- * Variable range: "Inter:wght@100..900"
1613
- * Variable with italic: "Inter:ital,wght@100..900"
1614
- */
1615
- function parseGoogleFamily(input) {
1616
- const parts = input.split(":");
1617
- const family = (parts[0] ?? "").trim();
1618
- const spec = parts[1];
1619
- let italic = false;
1620
- if (spec) {
1621
- italic = spec.includes("ital");
1622
- const rangeMatch = spec.match(/wght@(\d+)\.\.(\d+)/);
1623
- if (rangeMatch && rangeMatch[1] && rangeMatch[2]) return {
1624
- family,
1625
- italic,
1626
- variable: true,
1627
- weightRange: [Number(rangeMatch[1]), Number(rangeMatch[2])]
1628
- };
1629
- const afterAt = spec.split("@")[1];
1630
- if (afterAt) {
1631
- const entries = afterAt.split(";").filter(Boolean);
1632
- const weights = /* @__PURE__ */ new Set();
1633
- for (const entry of entries) if (entry.includes(",")) {
1634
- const parts = entry.split(",");
1635
- const weight = Number(parts[parts.length - 1]);
1636
- if (weight > 0) weights.add(weight);
1637
- if (parts[0] === "1") italic = true;
1638
- } else if (entry.includes("..")) {} else {
1639
- const weight = Number(entry);
1640
- if (weight > 0) weights.add(weight);
1641
- }
1642
- if (weights.size > 0) return {
1643
- family,
1644
- italic,
1645
- variable: false,
1646
- weights: [...weights].sort((a, b) => a - b)
1647
- };
1648
- }
1649
- }
1650
- return {
1651
- family,
1652
- italic,
1653
- variable: false,
1654
- weights: [400]
1655
- };
1656
- }
1657
- /**
1658
- * Generate a Google Fonts CSS URL.
1659
- */
1660
- function googleFontsUrl(families, display = "swap") {
1661
- return `https://fonts.googleapis.com/css2?${families.map((f) => {
1662
- const axes = f.italic ? "ital,wght" : "wght";
1663
- const name = f.family.replace(/ /g, "+");
1664
- if (f.variable) {
1665
- const range = `${f.weightRange[0]}..${f.weightRange[1]}`;
1666
- return `family=${name}:${axes}@${f.italic ? `0,${range};1,${range}` : range}`;
1667
- }
1668
- return `family=${name}:${axes}@${f.weights.map((w) => f.italic ? `0,${w};1,${w}` : String(w)).join(";")}`;
1669
- }).join("&")}&display=${display}`;
1670
- }
1671
- /**
1672
- * Generate @font-face CSS for local fonts.
1673
- */
1674
- function localFontFaces(fonts, display) {
1675
- return fonts.map((f) => `@font-face {
1676
- font-family: "${f.family}";
1677
- src: url("${f.src}");
1678
- font-weight: ${f.weight ?? "400"};
1679
- font-style: ${f.style ?? "normal"};
1680
- font-display: ${f.display ?? display};
1681
- }`).join("\n\n");
1682
- }
1683
- /**
1684
- * Generate size-adjusted fallback @font-face declarations to reduce CLS.
1685
- */
1686
- function fallbackFontFaces(fallbacks) {
1687
- return Object.entries(fallbacks).map(([family, metrics]) => {
1688
- const overrides = [];
1689
- if (metrics.sizeAdjust != null) overrides.push(` size-adjust: ${metrics.sizeAdjust * 100}%;`);
1690
- if (metrics.ascentOverride != null) overrides.push(` ascent-override: ${metrics.ascentOverride}%;`);
1691
- if (metrics.descentOverride != null) overrides.push(` descent-override: ${metrics.descentOverride}%;`);
1692
- if (metrics.lineGapOverride != null) overrides.push(` line-gap-override: ${metrics.lineGapOverride}%;`);
1693
- return `@font-face {
1694
- font-family: "${family} Fallback";
1695
- src: local("${metrics.fallback}");
1696
- ${overrides.join("\n")}
1697
- }`;
1698
- }).join("\n\n");
1699
- }
1700
- /**
1701
- * Generate preload link tags for critical font files.
1702
- */
1703
- function preloadTags(fonts) {
1704
- return fonts.map((f) => {
1705
- const ext = f.src.split(".").pop();
1706
- const type = ext === "woff2" ? "font/woff2" : ext === "woff" ? "font/woff" : ext === "ttf" ? "font/ttf" : "font/otf";
1707
- return `<link rel="preload" href="${f.src}" as="font" type="${type}" crossorigin>`;
1708
- }).join("\n");
1709
- }
1710
- /**
1711
- * Download Google Fonts CSS with woff2 user agent.
1712
- */
1713
- async function downloadGoogleFontsCSS(url) {
1714
- const response = await fetch(url, { headers: { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" } });
1715
- if (!response.ok) throw new Error(`Failed to fetch Google Fonts CSS: ${response.status}`);
1716
- return response.text();
1717
- }
1718
- /**
1719
- * Download a font file.
1720
- */
1721
- async function downloadFontFile(url) {
1722
- const response = await fetch(url);
1723
- if (!response.ok) throw new Error(`Failed to download font: ${url}`);
1724
- const arrayBuffer = await response.arrayBuffer();
1725
- return Buffer.from(arrayBuffer);
1726
- }
1727
- /**
1728
- * Extract font file URLs from Google Fonts CSS.
1729
- */
1730
- function extractFontUrls(css) {
1731
- const urls = [];
1732
- for (const match of css.matchAll(/url\((https:\/\/fonts\.gstatic\.com\/[^)]+)\)/g)) if (match[1]) urls.push(match[1]);
1733
- return urls;
1734
- }
1735
- /**
1736
- * Self-host Google Fonts: download CSS + font files, rewrite URLs to local paths.
446
+ * ```tsx
447
+ * const locale = useLocale() // "en", "de", etc.
448
+ * ```
1737
449
  */
1738
- async function selfHostFonts(cssUrl, fontsSubDir, root) {
1739
- const cacheDir = join(root, "node_modules", ".cache", "zero-fonts");
1740
- const cachePath = join(cacheDir, `${Buffer.from(cssUrl).toString("base64url")}.json`);
1741
- try {
1742
- const cached = JSON.parse(await readFile(cachePath, "utf-8"));
1743
- if (cached.css && cached.fontFiles) return {
1744
- css: cached.css,
1745
- fontFiles: cached.fontFiles.map((f) => ({
1746
- name: f.name,
1747
- content: Buffer.from(f.content, "base64")
1748
- }))
1749
- };
1750
- } catch {}
1751
- const css = await downloadGoogleFontsCSS(cssUrl);
1752
- const fontUrls = extractFontUrls(css);
1753
- const fontFiles = [];
1754
- let rewrittenCss = css;
1755
- for (const url of fontUrls) {
1756
- const fileName = url.split("/").at(-1)?.split("?")[0] ?? "font";
1757
- const content = await downloadFontFile(url);
1758
- fontFiles.push({
1759
- name: fileName,
1760
- content
1761
- });
1762
- rewrittenCss = rewrittenCss.replace(url, `/${fontsSubDir}/${fileName}`);
1763
- }
1764
- try {
1765
- await mkdir(cacheDir, { recursive: true });
1766
- await writeFile(cachePath, JSON.stringify({
1767
- css: rewrittenCss,
1768
- fontFiles: fontFiles.map((f) => ({
1769
- name: f.name,
1770
- content: f.content.toString("base64")
1771
- }))
1772
- }));
1773
- } catch {}
1774
- return {
1775
- css: rewrittenCss,
1776
- fontFiles
1777
- };
450
+ function useLocale() {
451
+ return localeSignal();
1778
452
  }
1779
453
  /**
1780
- * Zero font optimization Vite plugin.
1781
- *
1782
- * Dev mode: injects Google Fonts CDN link for fast startup.
1783
- * Build mode: downloads and self-hosts fonts for maximum performance + privacy.
454
+ * Set the locale client-side and update the URL.
1784
455
  *
1785
456
  * @example
1786
- * import { fontPlugin } from "@pyreon/zero/font"
1787
- *
1788
- * export default {
1789
- * plugins: [
1790
- * pyreon(),
1791
- * zero(),
1792
- * fontPlugin({
1793
- * google: ["Inter:wght@400;500;600;700", "JetBrains Mono:wght@400"],
1794
- * fallbacks: {
1795
- * "Inter": { fallback: "Arial", sizeAdjust: 1.07, ascentOverride: 90 },
1796
- * },
1797
- * }),
1798
- * ],
1799
- * }
457
+ * ```tsx
458
+ * <button onClick={() => setLocale('de')}>Deutsch</button>
459
+ * ```
1800
460
  */
1801
- function fontPlugin(config = {}) {
1802
- const display = config.display ?? "swap";
1803
- const shouldPreload = config.preload !== false;
1804
- const shouldSelfHost = config.selfHost !== false;
1805
- const googleFamilies = (config.google ?? []).map(resolveGoogleFont);
1806
- let isBuild = false;
1807
- let root = "";
1808
- let selfHostedCSS = "";
1809
- let selfHostedFontFiles = [];
1810
- return {
1811
- name: "pyreon-zero-fonts",
1812
- configResolved(resolvedConfig) {
1813
- isBuild = resolvedConfig.command === "build";
1814
- root = resolvedConfig.root;
1815
- },
1816
- async buildStart() {
1817
- if (isBuild && shouldSelfHost && googleFamilies.length > 0) {
1818
- const cssUrl = googleFontsUrl(googleFamilies, display);
1819
- try {
1820
- const result = await selfHostFonts(cssUrl, "assets/fonts", root);
1821
- selfHostedCSS = result.css;
1822
- selfHostedFontFiles = result.fontFiles;
1823
- } catch {}
1824
- }
1825
- },
1826
- generateBundle() {
1827
- for (const file of selfHostedFontFiles) this.emitFile({
1828
- type: "asset",
1829
- fileName: `assets/fonts/${file.name}`,
1830
- source: file.content
1831
- });
1832
- },
1833
- transformIndexHtml(html) {
1834
- const tags = [];
1835
- collectGoogleFontTags(tags, {
1836
- isBuild,
1837
- selfHostedCSS,
1838
- selfHostedFontFiles,
1839
- shouldPreload,
1840
- googleFamilies,
1841
- display
1842
- });
1843
- collectLocalFontTags(tags, config, shouldPreload, display);
1844
- if (tags.length === 0) return html;
1845
- return html.replace("</head>", `${tags.join("\n")}\n</head>`);
1846
- }
1847
- };
1848
- }
1849
- function collectGoogleFontTags(tags, opts) {
1850
- if (opts.isBuild && opts.selfHostedCSS) {
1851
- tags.push(`<style>${opts.selfHostedCSS}</style>`);
1852
- if (opts.shouldPreload) for (const file of opts.selfHostedFontFiles.slice(0, opts.googleFamilies.length)) {
1853
- const type = file.name.split(".").pop() === "woff2" ? "font/woff2" : "font/woff";
1854
- tags.push(`<link rel="preload" href="/assets/fonts/${file.name}" as="font" type="${type}" crossorigin>`);
1855
- }
1856
- } else if (opts.googleFamilies.length > 0) {
1857
- const cssUrl = googleFontsUrl(opts.googleFamilies, opts.display);
1858
- tags.push(`<link rel="preconnect" href="https://fonts.googleapis.com">`);
1859
- tags.push(`<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>`);
1860
- tags.push(`<link rel="stylesheet" href="${cssUrl}">`);
461
+ function setLocale(locale, config) {
462
+ localeSignal.set(locale);
463
+ if (typeof document !== "undefined") document.cookie = `${config.cookieName ?? "locale"}=${locale}; path=/; max-age=31536000`;
464
+ if (typeof window !== "undefined") {
465
+ const strategy = config.strategy ?? "prefix-except-default";
466
+ const { pathWithoutLocale } = extractLocaleFromPath(window.location.pathname, config.locales, config.defaultLocale);
467
+ const newPath = buildLocalePath(pathWithoutLocale, locale, config.defaultLocale, strategy);
468
+ window.history.pushState(null, "", newPath);
469
+ window.dispatchEvent(new PopStateEvent("popstate"));
1861
470
  }
1862
471
  }
1863
- function collectLocalFontTags(tags, config, shouldPreload, display) {
1864
- if (shouldPreload && config.local?.length) tags.push(preloadTags(config.local));
1865
- if (config.local?.length) tags.push(`<style>${localFontFaces(config.local, display)}</style>`);
1866
- if (config.fallbacks && Object.keys(config.fallbacks).length > 0) tags.push(`<style>${fallbackFontFaces(config.fallbacks)}</style>`);
1867
- }
1868
- /**
1869
- * Generate CSS variables for font families.
1870
- */
1871
- function fontVariables(families) {
1872
- return `:root {\n${Object.entries(families).map(([key, value]) => ` --font-${key}: ${value};`).join("\n")}\n}`;
1873
- }
1874
472
 
1875
473
  //#endregion
1876
- //#region src/image-plugin.ts
1877
- let sharpWarned$2 = false;
1878
- function warnSharpMissing$2() {
1879
- if (sharpWarned$2) return;
1880
- sharpWarned$2 = true;
1881
- console.warn("\n[zero:image] sharp not installed — images will not be optimized. Install for full support: bun add -D sharp\n");
474
+ //#region src/meta.tsx
475
+ function faviconLinks(locale, config) {
476
+ const hasLocaleOverride = locale && config.locales?.[locale];
477
+ const prefix = hasLocaleOverride ? `/${locale}` : "";
478
+ const isSvg = (hasLocaleOverride ? config.locales[locale].source : config.source).endsWith(".svg");
479
+ const links = [];
480
+ if (isSvg) links.push({
481
+ rel: "icon",
482
+ type: "image/svg+xml",
483
+ href: `${prefix}/favicon.svg`
484
+ });
485
+ links.push({
486
+ rel: "icon",
487
+ type: "image/png",
488
+ sizes: "32x32",
489
+ href: `${prefix}/favicon-32x32.png`
490
+ }, {
491
+ rel: "icon",
492
+ type: "image/png",
493
+ sizes: "16x16",
494
+ href: `${prefix}/favicon-16x16.png`
495
+ }, {
496
+ rel: "apple-touch-icon",
497
+ sizes: "180x180",
498
+ href: `${prefix}/apple-touch-icon.png`
499
+ });
500
+ if (config.manifest !== false) links.push({
501
+ rel: "manifest",
502
+ href: `${prefix}/site.webmanifest`
503
+ });
504
+ return links;
505
+ }
506
+ function ogImagePath(templateName, locale, outDir = "og", format = "png") {
507
+ const ext = format === "jpeg" ? "jpg" : "png";
508
+ return `/${outDir}/${templateName}${locale ? `-${locale}` : ""}.${ext}`;
1882
509
  }
1883
- const IMAGE_EXT_RE = /\.(jpe?g|png|webp|avif)$/i;
510
+ const resolveStr = (v) => typeof v === "function" ? v() : v;
1884
511
  /**
1885
- * Zero image processing Vite plugin.
1886
- *
1887
- * Transforms image imports with query params into optimized responsive images:
1888
- *
1889
- * @example
1890
- * // vite.config.ts
1891
- * import { imagePlugin } from "@pyreon/zero/image-plugin"
512
+ * Declarative meta component for SSR-compatible page metadata.
1892
513
  *
1893
- * export default {
1894
- * plugins: [
1895
- * pyreon(),
1896
- * zero(),
1897
- * imagePlugin({ widths: [480, 960, 1440], quality: 85 }),
1898
- * ],
1899
- * }
514
+ * Supports reactive title/description — when passed as `() => string` accessors,
515
+ * they are forwarded to `useHead()` as a reactive getter so updates propagate
516
+ * automatically via signal tracking.
1900
517
  *
1901
518
  * @example
1902
- * // In a component — import with ?optimize
1903
- * import hero from "./images/hero.jpg?optimize"
1904
- * // hero = { src, srcset, width, height, placeholder }
519
+ * ```tsx
520
+ * <Meta title="My Page" description="..." image="/og.jpg" canonical="https://..." />
521
+ * ```
1905
522
  *
1906
- * <Image {...hero} alt="Hero" priority />
523
+ * @example Reactive title
524
+ * ```tsx
525
+ * const count = signal(0)
526
+ * <Meta title={() => `${count()} items`} />
527
+ * ```
1907
528
  */
1908
- function imagePlugin(config = {}) {
1909
- const defaultWidths = config.widths ?? [
1910
- 640,
1911
- 1024,
1912
- 1920
1913
- ];
1914
- const defaultFormats = config.formats ?? ["webp"];
1915
- const quality = config.quality ?? 80;
1916
- const placeholderSize = config.placeholderSize ?? 16;
1917
- const outSubDir = config.outDir ?? "assets/img";
1918
- const include = config.include ?? IMAGE_EXT_RE;
1919
- let root = "";
1920
- let outDir = "";
1921
- let isBuild = false;
1922
- return {
1923
- name: "pyreon-zero-images",
1924
- enforce: "pre",
1925
- configResolved(resolvedConfig) {
1926
- root = resolvedConfig.root;
1927
- outDir = resolvedConfig.build.outDir;
1928
- isBuild = resolvedConfig.command === "build";
1929
- },
1930
- async resolveId(id) {
1931
- if (id.includes("?optimize") && include.test(id.split("?")[0])) return `\0virtual:zero-image:${id}`;
1932
- return null;
1933
- },
1934
- async load(id) {
1935
- if (!id.startsWith("\0virtual:zero-image:")) return null;
1936
- const rawPath = id.replace("\0virtual:zero-image:", "").split("?")[0] ?? id;
1937
- const absPath = rawPath.startsWith("/") ? join(root, "public", rawPath) : rawPath;
1938
- if (!isBuild) {
1939
- const result = await loadDevImage(absPath, rawPath, placeholderSize);
1940
- return `export default ${JSON.stringify(result)}`;
1941
- }
1942
- const processed = await processImage(absPath, {
1943
- widths: defaultWidths,
1944
- formats: defaultFormats,
1945
- quality,
1946
- placeholderSize,
1947
- outSubDir,
1948
- outDir: join(root, outDir)
1949
- });
1950
- await emitProcessedSources(processed, outSubDir, this);
1951
- rebuildFormatSrcsets(processed, absPath);
1952
- return `export default ${JSON.stringify(processed)}`;
1953
- }
1954
- };
1955
- }
1956
- async function loadDevImage(absPath, rawPath, placeholderSize) {
1957
- const metadata = await getImageMetadata(absPath);
1958
- const publicPath = rawPath.startsWith("/") ? rawPath : `/@fs/${absPath}`;
1959
- return {
1960
- src: publicPath,
1961
- srcset: "",
1962
- width: metadata.width,
1963
- height: metadata.height,
1964
- placeholder: await generateBlurPlaceholder(absPath, placeholderSize),
1965
- formats: [],
1966
- sources: [{
1967
- src: publicPath,
1968
- width: metadata.width,
1969
- format: "original"
1970
- }]
1971
- };
1972
- }
1973
- async function emitProcessedSources(processed, outSubDir, ctx) {
1974
- for (const source of processed.sources) {
1975
- const fileName = join(outSubDir, basename(source.src));
1976
- const content = await readFile(source.src);
1977
- ctx.emitFile({
1978
- type: "asset",
1979
- fileName,
1980
- source: content
1981
- });
1982
- source.src = `/${fileName}`;
1983
- }
1984
- }
1985
- function rebuildFormatSrcsets(processed, fallbackPath) {
1986
- const formatGroups = /* @__PURE__ */ new Map();
1987
- for (const s of processed.sources) {
1988
- let group = formatGroups.get(s.format);
1989
- if (!group) {
1990
- group = [];
1991
- formatGroups.set(s.format, group);
1992
- }
1993
- group.push(`${s.src} ${s.width}w`);
1994
- }
1995
- processed.formats = [...formatGroups.entries()].map(([fmt, entries]) => ({
1996
- type: `image/${fmt}`,
1997
- srcset: entries.join(", ")
1998
- }));
1999
- processed.srcset = processed.formats.at(-1)?.srcset ?? "";
2000
- processed.src = processed.sources.at(-1)?.src ?? fallbackPath;
2001
- }
2002
- async function processImage(absPath, opts) {
2003
- const metadata = await getImageMetadata(absPath);
2004
- const name = basename(absPath, extname(absPath));
2005
- const sources = [];
2006
- const processedDir = join(opts.outDir, opts.outSubDir);
2007
- if (!existsSync(processedDir)) await mkdir(processedDir, { recursive: true });
2008
- for (const format of opts.formats) for (const targetWidth of opts.widths) {
2009
- const width = Math.min(targetWidth, metadata.width);
2010
- const outPath = join(processedDir, `${name}-${width}.${format}`);
2011
- await resizeImage(absPath, outPath, width, format, opts.quality);
2012
- sources.push({
2013
- src: outPath,
2014
- width,
2015
- format
529
+ function Meta(props) {
530
+ const hasReactiveTitle = typeof props.title === "function";
531
+ const hasReactiveDescription = typeof props.description === "function";
532
+ if (hasReactiveTitle || hasReactiveDescription) useHead(() => {
533
+ const title = resolveStr(props.title);
534
+ const description = resolveStr(props.description);
535
+ const tags = buildMetaTags({
536
+ ...props,
537
+ title,
538
+ description
2016
539
  });
2017
- }
2018
- const formatGroups = /* @__PURE__ */ new Map();
2019
- for (const s of sources) {
2020
- let group = formatGroups.get(s.format);
2021
- if (!group) {
2022
- group = [];
2023
- formatGroups.set(s.format, group);
2024
- }
2025
- group.push({
2026
- src: s.src,
2027
- width: s.width
540
+ const input = {
541
+ meta: tags.meta,
542
+ link: tags.link,
543
+ script: tags.script
544
+ };
545
+ if (title) input.title = title;
546
+ return input;
547
+ });
548
+ else {
549
+ const title = resolveStr(props.title);
550
+ const description = resolveStr(props.description);
551
+ const tags = buildMetaTags({
552
+ ...props,
553
+ title,
554
+ description
2028
555
  });
2029
- }
2030
- const formats = [...formatGroups.entries()].map(([fmt, group]) => ({
2031
- type: `image/${fmt === "jpeg" ? "jpeg" : fmt}`,
2032
- srcset: group.map((s) => `${s.src} ${s.width}w`).join(", ")
2033
- }));
2034
- const fallbackFormat = formats[formats.length - 1];
2035
- const fallbackSources = formatGroups.get([...formatGroups.keys()].pop());
2036
- const placeholder = await generateBlurPlaceholder(absPath, opts.placeholderSize);
2037
- return {
2038
- src: fallbackSources[fallbackSources.length - 1]?.src ?? absPath,
2039
- srcset: fallbackFormat?.srcset ?? "",
2040
- width: metadata.width,
2041
- height: metadata.height,
2042
- placeholder,
2043
- formats,
2044
- sources
2045
- };
2046
- }
2047
- /**
2048
- * Read basic image metadata.
2049
- * Uses minimal binary header parsing — no external dependencies.
2050
- */
2051
- async function getImageMetadata(absPath) {
2052
- const buffer = await readFile(absPath);
2053
- const ext = extname(absPath).toLowerCase();
2054
- if (ext === ".png") return {
2055
- width: buffer.readUInt32BE(16),
2056
- height: buffer.readUInt32BE(20),
2057
- format: "png"
2058
- };
2059
- if (ext === ".jpg" || ext === ".jpeg") return {
2060
- ...parseJpegDimensions(buffer),
2061
- format: "jpeg"
2062
- };
2063
- if (ext === ".webp") return {
2064
- ...parseWebPDimensions(buffer),
2065
- format: "webp"
2066
- };
2067
- return {
2068
- width: 0,
2069
- height: 0,
2070
- format: ext.slice(1)
2071
- };
2072
- }
2073
- /** @internal Exported for testing */
2074
- function parseJpegDimensions(buffer) {
2075
- let offset = 2;
2076
- while (offset < buffer.length) {
2077
- if (buffer[offset] !== 255) break;
2078
- const marker = buffer[offset + 1];
2079
- if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
2080
- const height = buffer.readUInt16BE(offset + 5);
2081
- return {
2082
- width: buffer.readUInt16BE(offset + 7),
2083
- height
2084
- };
2085
- }
2086
- const length = buffer.readUInt16BE(offset + 2);
2087
- offset += 2 + length;
2088
- }
2089
- return {
2090
- width: 0,
2091
- height: 0
2092
- };
2093
- }
2094
- /** @internal Exported for testing */
2095
- function parseWebPDimensions(buffer) {
2096
- const chunk = buffer.toString("ascii", 12, 16);
2097
- if (chunk === "VP8 ") return {
2098
- width: buffer.readUInt16LE(26) & 16383,
2099
- height: buffer.readUInt16LE(28) & 16383
2100
- };
2101
- if (chunk === "VP8L") {
2102
- const bits = buffer.readUInt32LE(21);
2103
- return {
2104
- width: (bits & 16383) + 1,
2105
- height: (bits >> 14 & 16383) + 1
556
+ const input = {
557
+ meta: tags.meta,
558
+ link: tags.link,
559
+ script: tags.script
2106
560
  };
561
+ if (title) input.title = title;
562
+ useHead(input);
2107
563
  }
2108
- if (chunk === "VP8X") return {
2109
- width: 1 + ((buffer[24] | buffer[25] << 8 | buffer[26] << 16) & 16777215),
2110
- height: 1 + ((buffer[27] | buffer[28] << 8 | buffer[29] << 16) & 16777215)
2111
- };
2112
- return {
2113
- width: 0,
2114
- height: 0
2115
- };
2116
- }
2117
- /**
2118
- * Resize an image using native platform capabilities.
2119
- * Uses sharp if available, falls back to canvas API.
2120
- */
2121
- async function resizeImage(input, output, width, format, quality) {
2122
- try {
2123
- let pipeline = (await import("sharp").then((m) => m.default ?? m))(input).resize(width);
2124
- switch (format) {
2125
- case "webp":
2126
- pipeline = pipeline.webp({ quality });
2127
- break;
2128
- case "avif":
2129
- pipeline = pipeline.avif({ quality });
2130
- break;
2131
- case "jpeg":
2132
- pipeline = pipeline.jpeg({
2133
- quality,
2134
- mozjpeg: true
2135
- });
2136
- break;
2137
- case "png":
2138
- pipeline = pipeline.png({ compressionLevel: 9 });
2139
- break;
2140
- }
2141
- await pipeline.toFile(output);
2142
- } catch {
2143
- warnSharpMissing$2();
2144
- await writeFile(output, await readFile(input));
2145
- }
2146
- }
2147
- /**
2148
- * Generate a tiny blur placeholder as a base64 data URI.
2149
- */
2150
- async function generateBlurPlaceholder(input, size) {
2151
- try {
2152
- return `data:image/webp;base64,${(await (await import("sharp").then((m) => m.default ?? m))(input).resize(size, size, { fit: "inside" }).blur(2).webp({ quality: 20 }).toBuffer()).toString("base64")}`;
2153
- } catch {
2154
- return "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='1' height='1'%3E%3C/svg%3E";
2155
- }
564
+ return props.children ?? null;
2156
565
  }
2157
-
2158
- //#endregion
2159
- //#region src/theme.tsx
2160
- const STORAGE_KEY = "zero-theme";
2161
- /** Reactive theme signal. */
2162
- const theme = signal("system");
2163
- /** Computed resolved theme (what's actually applied). */
2164
- function resolvedTheme() {
566
+ function buildMetaTags(props) {
567
+ const meta = [];
568
+ const link = [];
569
+ const script = [];
570
+ const { title, description, canonical, imageAlt, imageWidth, imageHeight, type = "website", siteName, twitterCard = "summary_large_image", twitterSite, twitterCreator, locale = "en_US", alternateLocales, publishedTime, modifiedTime, author, tags, jsonLd, extra, video, videoWidth, videoHeight, audio, favicon, ogTemplate, ogImageDir, ogImageFormat } = props;
571
+ const robots = props.noIndex ? "noindex, nofollow" : props.robots ?? "index, follow";
572
+ const image = props.image ?? (ogTemplate ? ogImagePath(ogTemplate, locale !== "en_US" ? locale : void 0, ogImageDir, ogImageFormat) : void 0);
573
+ const resolvedImageWidth = imageWidth ?? (ogTemplate && !props.image ? 1200 : void 0);
574
+ const resolvedImageHeight = imageHeight ?? (ogTemplate && !props.image ? 630 : void 0);
575
+ if (description) meta.push({
576
+ name: "description",
577
+ content: description
578
+ });
579
+ if (robots) meta.push({
580
+ name: "robots",
581
+ content: robots
582
+ });
583
+ if (author) meta.push({
584
+ name: "author",
585
+ content: author
586
+ });
587
+ if (title) meta.push({
588
+ property: "og:title",
589
+ content: title
590
+ });
591
+ if (description) meta.push({
592
+ property: "og:description",
593
+ content: description
594
+ });
595
+ if (canonical) meta.push({
596
+ property: "og:url",
597
+ content: canonical
598
+ });
599
+ if (image) meta.push({
600
+ property: "og:image",
601
+ content: image
602
+ });
603
+ if (imageAlt) meta.push({
604
+ property: "og:image:alt",
605
+ content: imageAlt
606
+ });
607
+ if (resolvedImageWidth) meta.push({
608
+ property: "og:image:width",
609
+ content: String(resolvedImageWidth)
610
+ });
611
+ if (resolvedImageHeight) meta.push({
612
+ property: "og:image:height",
613
+ content: String(resolvedImageHeight)
614
+ });
615
+ meta.push({
616
+ property: "og:type",
617
+ content: type
618
+ });
619
+ if (siteName) meta.push({
620
+ property: "og:site_name",
621
+ content: siteName
622
+ });
623
+ meta.push({
624
+ property: "og:locale",
625
+ content: locale
626
+ });
627
+ if (video) {
628
+ meta.push({
629
+ property: "og:video",
630
+ content: video
631
+ });
632
+ if (videoWidth) meta.push({
633
+ property: "og:video:width",
634
+ content: String(videoWidth)
635
+ });
636
+ if (videoHeight) meta.push({
637
+ property: "og:video:height",
638
+ content: String(videoHeight)
639
+ });
640
+ if (video.endsWith(".mp4")) meta.push({
641
+ property: "og:video:type",
642
+ content: "video/mp4"
643
+ });
644
+ else if (video.endsWith(".webm")) meta.push({
645
+ property: "og:video:type",
646
+ content: "video/webm"
647
+ });
648
+ }
649
+ if (audio) meta.push({
650
+ property: "og:audio",
651
+ content: audio
652
+ });
653
+ if (type === "article") {
654
+ if (publishedTime) meta.push({
655
+ property: "article:published_time",
656
+ content: publishedTime
657
+ });
658
+ if (modifiedTime) meta.push({
659
+ property: "article:modified_time",
660
+ content: modifiedTime
661
+ });
662
+ if (author) meta.push({
663
+ property: "article:author",
664
+ content: author
665
+ });
666
+ if (tags) for (const tag of tags) meta.push({
667
+ property: "article:tag",
668
+ content: tag
669
+ });
670
+ }
671
+ meta.push({
672
+ name: "twitter:card",
673
+ content: twitterCard
674
+ });
675
+ if (title) meta.push({
676
+ name: "twitter:title",
677
+ content: title
678
+ });
679
+ if (description) meta.push({
680
+ name: "twitter:description",
681
+ content: description
682
+ });
683
+ if (image) meta.push({
684
+ name: "twitter:image",
685
+ content: image
686
+ });
687
+ if (imageAlt) meta.push({
688
+ name: "twitter:image:alt",
689
+ content: imageAlt
690
+ });
691
+ if (twitterSite) meta.push({
692
+ name: "twitter:site",
693
+ content: twitterSite
694
+ });
695
+ if (twitterCreator) meta.push({
696
+ name: "twitter:creator",
697
+ content: twitterCreator
698
+ });
699
+ if (canonical) link.push({
700
+ rel: "canonical",
701
+ href: canonical
702
+ });
703
+ if (alternateLocales) for (const alt of alternateLocales) link.push({
704
+ rel: "alternate",
705
+ hreflang: alt.locale,
706
+ href: alt.url
707
+ });
708
+ if (jsonLd) script.push({
709
+ type: "application/ld+json",
710
+ children: JSON.stringify({
711
+ "@context": "https://schema.org",
712
+ ...jsonLd
713
+ })
714
+ });
715
+ if (extra) for (const tag of extra) meta.push(tag);
716
+ if (props.i18n) {
717
+ const i18nConfig = props.i18n;
718
+ const origin = props.origin ?? "";
719
+ const { pathWithoutLocale } = extractLocaleFromPath(canonical?.replace(origin, "") ?? "/", i18nConfig.locales, i18nConfig.defaultLocale);
720
+ const strategy = i18nConfig.strategy ?? "prefix-except-default";
721
+ for (const loc of i18nConfig.locales) {
722
+ const localizedPath = strategy === "prefix-except-default" && loc === i18nConfig.defaultLocale ? pathWithoutLocale : `/${loc}${pathWithoutLocale === "/" ? "" : pathWithoutLocale}`;
723
+ link.push({
724
+ rel: "alternate",
725
+ hreflang: loc,
726
+ href: `${origin}${localizedPath}`
727
+ });
728
+ if (loc !== locale) meta.push({
729
+ property: "og:locale:alternate",
730
+ content: loc
731
+ });
732
+ }
733
+ link.push({
734
+ rel: "alternate",
735
+ hreflang: "x-default",
736
+ href: `${origin}${pathWithoutLocale}`
737
+ });
738
+ }
739
+ if (favicon) {
740
+ const faviconLocale = locale !== "en_US" ? locale : void 0;
741
+ for (const fl of faviconLinks(faviconLocale, favicon)) link.push(fl);
742
+ if (favicon.themeColor) meta.push({
743
+ name: "theme-color",
744
+ content: favicon.themeColor
745
+ });
746
+ }
747
+ return {
748
+ meta,
749
+ link,
750
+ script
751
+ };
752
+ }
753
+
754
+ //#endregion
755
+ //#region src/theme.tsx
756
+ const STORAGE_KEY = "zero-theme";
757
+ /** Reactive theme signal. */
758
+ const theme = signal("system");
759
+ /** SSR fallback when system preference can't be detected. Default: 'light'. */
760
+ let _ssrDefault = "light";
761
+ /**
762
+ * Set the default theme for SSR (when `matchMedia` is unavailable).
763
+ * Call once at server startup before rendering.
764
+ */
765
+ function setSSRThemeDefault(value) {
766
+ _ssrDefault = value;
767
+ }
768
+ /** Computed resolved theme (what's actually applied). */
769
+ function resolvedTheme() {
2165
770
  const t = theme();
2166
771
  if (t === "system") {
2167
- if (typeof window === "undefined") return "dark";
772
+ if (typeof window === "undefined") return _ssrDefault;
2168
773
  return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
2169
774
  }
2170
775
  return t;
@@ -2315,2285 +920,5 @@ function ThemeToggle(props) {
2315
920
  const themeScript = `(function(){try{var t=localStorage.getItem("${STORAGE_KEY}");var r=t==="light"?"light":t==="dark"?"dark":window.matchMedia("(prefers-color-scheme:dark)").matches?"dark":"light";document.documentElement.dataset.theme=r}catch(e){}})()`;
2316
921
 
2317
922
  //#endregion
2318
- //#region src/seo.ts
2319
- /**
2320
- * Generate a sitemap.xml string from route file paths.
2321
- */
2322
- function generateSitemap(routeFiles, config) {
2323
- const { origin, exclude = [], changefreq = "weekly", priority = .7 } = config;
2324
- return `<?xml version="1.0" encoding="UTF-8"?>
2325
- <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
2326
- ${[...routeFiles.filter((f) => {
2327
- const name = f.split("/").pop()?.replace(/\.\w+$/, "");
2328
- return name !== "_layout" && name !== "_error" && name !== "_loading";
2329
- }).map((f) => {
2330
- let path = f.replace(/\.\w+$/, "").replace(/\/index$/, "/").replace(/^index$/, "/");
2331
- if (path.includes("[")) return null;
2332
- path = path.replace(/\([\w-]+\)\//g, "");
2333
- if (!path.startsWith("/")) path = `/${path}`;
2334
- return path;
2335
- }).filter((p) => p !== null).filter((p) => !exclude.some((e) => p.startsWith(e))).map((p) => ({
2336
- path: p,
2337
- changefreq,
2338
- priority
2339
- })), ...config.additionalPaths ?? []].map((entry) => {
2340
- return ` <url>
2341
- <loc>${escapeXml$1(`${origin}${entry.path === "/" ? "" : entry.path}`)}</loc>
2342
- <changefreq>${entry.changefreq ?? changefreq}</changefreq>
2343
- <priority>${entry.priority ?? priority}</priority>${entry.lastmod ? `\n <lastmod>${entry.lastmod}</lastmod>` : ""}
2344
- </url>`;
2345
- }).join("\n")}
2346
- </urlset>`;
2347
- }
2348
- function escapeXml$1(str) {
2349
- return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
2350
- }
2351
- /**
2352
- * Generate a robots.txt string.
2353
- */
2354
- function generateRobots(config = {}) {
2355
- const { rules = [{
2356
- userAgent: "*",
2357
- allow: ["/"]
2358
- }], sitemap, host } = config;
2359
- const lines = [];
2360
- for (const rule of rules) {
2361
- lines.push(`User-agent: ${rule.userAgent}`);
2362
- if (rule.allow) for (const path of rule.allow) lines.push(`Allow: ${path}`);
2363
- if (rule.disallow) for (const path of rule.disallow) lines.push(`Disallow: ${path}`);
2364
- if (rule.crawlDelay) lines.push(`Crawl-delay: ${rule.crawlDelay}`);
2365
- lines.push("");
2366
- }
2367
- if (sitemap) lines.push(`Sitemap: ${sitemap}`);
2368
- if (host) lines.push(`Host: ${host}`);
2369
- return lines.join("\n");
2370
- }
2371
- /**
2372
- * Generate a JSON-LD script tag string for structured data.
2373
- *
2374
- * @example
2375
- * useHead({
2376
- * script: [jsonLd({
2377
- * "@type": "WebSite",
2378
- * name: "My Site",
2379
- * url: "https://example.com",
2380
- * })],
2381
- * })
2382
- */
2383
- function jsonLd(data) {
2384
- const ld = {
2385
- "@context": "https://schema.org",
2386
- ...data
2387
- };
2388
- return `<script type="application/ld+json">${JSON.stringify(ld)}<\/script>`;
2389
- }
2390
- /**
2391
- * Zero SEO Vite plugin.
2392
- * Generates sitemap.xml and robots.txt at build time.
2393
- *
2394
- * @example
2395
- * import { seoPlugin } from "@pyreon/zero/seo"
2396
- *
2397
- * export default {
2398
- * plugins: [
2399
- * pyreon(),
2400
- * zero(),
2401
- * seoPlugin({
2402
- * sitemap: { origin: "https://example.com" },
2403
- * robots: { sitemap: "https://example.com/sitemap.xml" },
2404
- * }),
2405
- * ],
2406
- * }
2407
- */
2408
- function seoPlugin(config = {}) {
2409
- return {
2410
- name: "pyreon-zero-seo",
2411
- apply: "build",
2412
- async generateBundle(_, _bundle) {
2413
- if (config.sitemap) {
2414
- const { scanRouteFiles } = await import("./fs-router-Dil4IKZR.js").then((n) => n.n);
2415
- const routesDir = `${process.cwd()}/src/routes`;
2416
- try {
2417
- const sitemap = generateSitemap(await scanRouteFiles(routesDir), config.sitemap);
2418
- this.emitFile({
2419
- type: "asset",
2420
- fileName: "sitemap.xml",
2421
- source: sitemap
2422
- });
2423
- } catch {}
2424
- }
2425
- if (config.robots) {
2426
- const robots = generateRobots(config.robots);
2427
- this.emitFile({
2428
- type: "asset",
2429
- fileName: "robots.txt",
2430
- source: robots
2431
- });
2432
- }
2433
- }
2434
- };
2435
- }
2436
- /**
2437
- * SEO middleware for dev server.
2438
- * Serves sitemap.xml and robots.txt dynamically during development.
2439
- */
2440
- function seoMiddleware(config = {}) {
2441
- return async (ctx) => {
2442
- if (ctx.url.pathname === "/robots.txt" && config.robots) return new Response(generateRobots(config.robots), { headers: { "Content-Type": "text/plain" } });
2443
- if (ctx.url.pathname === "/sitemap.xml" && config.sitemap) try {
2444
- const { scanRouteFiles } = await import("./fs-router-Dil4IKZR.js").then((n) => n.n);
2445
- const sitemap = generateSitemap(await scanRouteFiles(`${process.cwd()}/src/routes`), config.sitemap);
2446
- return new Response(sitemap, { headers: { "Content-Type": "application/xml" } });
2447
- } catch {}
2448
- };
2449
- }
2450
-
2451
- //#endregion
2452
- //#region src/cors.ts
2453
- const DEFAULT_METHODS = [
2454
- "GET",
2455
- "POST",
2456
- "PUT",
2457
- "PATCH",
2458
- "DELETE",
2459
- "OPTIONS"
2460
- ];
2461
- const DEFAULT_HEADERS = ["Content-Type", "Authorization"];
2462
- /**
2463
- * CORS middleware — handles preflight requests and sets appropriate
2464
- * Access-Control headers on all responses.
2465
- *
2466
- * @example
2467
- * import { corsMiddleware } from "@pyreon/zero/cors"
2468
- *
2469
- * corsMiddleware({ origin: "https://example.com", credentials: true })
2470
- *
2471
- * // Allow any origin
2472
- * corsMiddleware({ origin: "*" })
2473
- *
2474
- * // Multiple origins
2475
- * corsMiddleware({ origin: ["https://app.com", "https://admin.com"] })
2476
- */
2477
- function corsMiddleware(config = {}) {
2478
- const { origin = "*", methods = DEFAULT_METHODS, allowedHeaders = DEFAULT_HEADERS, exposedHeaders = [], credentials = false, maxAge = 86400 } = config;
2479
- return (ctx) => {
2480
- const resolvedOrigin = resolveOrigin(origin, ctx.req.headers.get("origin") ?? "");
2481
- if (!resolvedOrigin) return;
2482
- ctx.headers.set("Access-Control-Allow-Origin", resolvedOrigin);
2483
- if (credentials) ctx.headers.set("Access-Control-Allow-Credentials", "true");
2484
- if (exposedHeaders.length > 0) ctx.headers.set("Access-Control-Expose-Headers", exposedHeaders.join(", "));
2485
- if (resolvedOrigin !== "*") ctx.headers.append("Vary", "Origin");
2486
- if (ctx.req.method === "OPTIONS") return new Response(null, {
2487
- status: 204,
2488
- headers: {
2489
- "Access-Control-Allow-Origin": resolvedOrigin,
2490
- "Access-Control-Allow-Methods": methods.join(", "),
2491
- "Access-Control-Allow-Headers": allowedHeaders.join(", "),
2492
- "Access-Control-Max-Age": String(maxAge),
2493
- ...credentials ? { "Access-Control-Allow-Credentials": "true" } : {}
2494
- }
2495
- });
2496
- };
2497
- }
2498
- function resolveOrigin(config, requestOrigin) {
2499
- if (config === "*") return "*";
2500
- if (typeof config === "string") return config === requestOrigin ? config : null;
2501
- if (typeof config === "function") return config(requestOrigin) ? requestOrigin : null;
2502
- if (Array.isArray(config)) return config.includes(requestOrigin) ? requestOrigin : null;
2503
- return null;
2504
- }
2505
-
2506
- //#endregion
2507
- //#region src/rate-limit.ts
2508
- /**
2509
- * Rate limiting middleware — limits requests per client within a time window.
2510
- * Uses an in-memory store (suitable for single-instance deployments).
2511
- *
2512
- * @example
2513
- * import { rateLimitMiddleware } from "@pyreon/zero/rate-limit"
2514
- *
2515
- * // 100 requests per minute (default)
2516
- * rateLimitMiddleware()
2517
- *
2518
- * // Strict API rate limiting
2519
- * rateLimitMiddleware({
2520
- * max: 20,
2521
- * window: 60,
2522
- * include: ["/api/*"],
2523
- * })
2524
- */
2525
- function rateLimitMiddleware(config = {}) {
2526
- const { max = 100, window: windowSec = 60, keyFn = defaultKeyFn, onLimit, include, exclude } = config;
2527
- const windowMs = windowSec * 1e3;
2528
- const store = /* @__PURE__ */ new Map();
2529
- const cleanupInterval = setInterval(() => {
2530
- const now = Date.now();
2531
- for (const [key, entry] of store) if (entry.resetAt <= now) store.delete(key);
2532
- }, windowMs);
2533
- if (typeof cleanupInterval === "object" && "unref" in cleanupInterval) cleanupInterval.unref();
2534
- return (ctx) => {
2535
- if (include && !include.some((p) => matchSimpleGlob(p, ctx.path))) return;
2536
- if (exclude?.some((p) => matchSimpleGlob(p, ctx.path))) return;
2537
- const key = keyFn(ctx);
2538
- const now = Date.now();
2539
- let entry = store.get(key);
2540
- if (!entry || entry.resetAt <= now) {
2541
- entry = {
2542
- count: 0,
2543
- resetAt: now + windowMs
2544
- };
2545
- store.set(key, entry);
2546
- }
2547
- entry.count++;
2548
- const remaining = Math.max(0, max - entry.count);
2549
- const resetSeconds = Math.ceil((entry.resetAt - now) / 1e3);
2550
- ctx.headers.set("X-RateLimit-Limit", String(max));
2551
- ctx.headers.set("X-RateLimit-Remaining", String(remaining));
2552
- ctx.headers.set("X-RateLimit-Reset", String(resetSeconds));
2553
- if (entry.count > max) {
2554
- if (onLimit) return onLimit(ctx);
2555
- return new Response(JSON.stringify({ error: "Too many requests" }), {
2556
- status: 429,
2557
- headers: {
2558
- "Content-Type": "application/json",
2559
- "Retry-After": String(resetSeconds),
2560
- "X-RateLimit-Limit": String(max),
2561
- "X-RateLimit-Remaining": "0",
2562
- "X-RateLimit-Reset": String(resetSeconds)
2563
- }
2564
- });
2565
- }
2566
- };
2567
- }
2568
- function defaultKeyFn(ctx) {
2569
- return ctx.req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? ctx.req.headers.get("x-real-ip") ?? "unknown";
2570
- }
2571
- /** Simple glob matching for path patterns. Supports trailing `*`. */
2572
- function matchSimpleGlob(pattern, path) {
2573
- if (pattern.endsWith("/*")) return path.startsWith(pattern.slice(0, -1));
2574
- return pattern === path;
2575
- }
2576
-
2577
- //#endregion
2578
- //#region src/compression.ts
2579
- /**
2580
- * Compression middleware — compresses responses using gzip or deflate
2581
- * based on the client's Accept-Encoding header.
2582
- *
2583
- * Only compresses text-based content types (HTML, JSON, JS, CSS, XML, SVG).
2584
- * Skips responses below the size threshold and already-encoded responses.
2585
- *
2586
- * @example
2587
- * import { compressionMiddleware } from "@pyreon/zero/compression"
2588
- *
2589
- * compressionMiddleware() // gzip with 1KB threshold
2590
- * compressionMiddleware({ threshold: 512, encodings: ["gzip"] })
2591
- */
2592
- function compressionMiddleware(config = {}) {
2593
- const { threshold = 1024, encodings = ["gzip", "deflate"] } = config;
2594
- return (ctx) => {
2595
- const acceptEncoding = ctx.req.headers.get("accept-encoding") ?? "";
2596
- const encoding = encodings.find((enc) => acceptEncoding.includes(enc));
2597
- if (!encoding) return;
2598
- ctx.locals.__compressionEncoding = encoding;
2599
- ctx.locals.__compressionThreshold = threshold;
2600
- ctx.headers.append("Vary", "Accept-Encoding");
2601
- };
2602
- }
2603
- /**
2604
- * Compress a Response body if it meets the criteria.
2605
- * Use this to post-process responses after the handler runs.
2606
- *
2607
- * @example
2608
- * const response = await handler(request)
2609
- * const compressed = await compressResponse(response, 'gzip', 1024)
2610
- */
2611
- async function compressResponse(response, encoding, threshold) {
2612
- if (!isCompressible(response.headers.get("content-type") ?? "")) return response;
2613
- if (response.headers.get("content-encoding")) return response;
2614
- const body = await response.arrayBuffer();
2615
- if (body.byteLength < threshold) return response;
2616
- const compressed = await compress(body, encoding);
2617
- const headers = new Headers(response.headers);
2618
- headers.set("Content-Encoding", encoding);
2619
- headers.delete("Content-Length");
2620
- headers.append("Vary", "Accept-Encoding");
2621
- return new Response(compressed, {
2622
- status: response.status,
2623
- statusText: response.statusText,
2624
- headers
2625
- });
2626
- }
2627
- const COMPRESSIBLE_TYPES = [
2628
- "text/",
2629
- "application/json",
2630
- "application/javascript",
2631
- "application/xml",
2632
- "application/xhtml+xml",
2633
- "image/svg+xml"
2634
- ];
2635
- /** Check if a content type is compressible. Exported for testing. */
2636
- function isCompressible(contentType) {
2637
- return COMPRESSIBLE_TYPES.some((t) => contentType.includes(t));
2638
- }
2639
- async function compress(data, encoding) {
2640
- const format = encoding === "gzip" ? "gzip" : "deflate";
2641
- const stream = new Blob([data]).stream().pipeThrough(new CompressionStream(format));
2642
- return new Response(stream).arrayBuffer();
2643
- }
2644
-
2645
- //#endregion
2646
- //#region src/actions.ts
2647
- const actionRegistry = /* @__PURE__ */ new Map();
2648
- let actionCounter = 0;
2649
- /**
2650
- * Define a server action. Returns a callable function that:
2651
- * - On the **client**: sends a POST request to `/_zero/actions/<id>`
2652
- * - On the **server** (SSR): executes the handler directly (no fetch)
2653
- *
2654
- * @example
2655
- * // In a route file or module:
2656
- * export const createPost = defineAction(async (ctx) => {
2657
- * const data = ctx.json as { title: string; body: string }
2658
- * // ... save to database
2659
- * return { success: true, id: 123 }
2660
- * })
2661
- *
2662
- * // In a component:
2663
- * const result = await createPost({ title: 'Hello', body: '...' })
2664
- */
2665
- function defineAction(handler) {
2666
- const id = `action_${actionCounter++}`;
2667
- actionRegistry.set(id, {
2668
- id,
2669
- handler
2670
- });
2671
- const callable = async (data) => {
2672
- if (typeof globalThis.window === "undefined") return handler({
2673
- request: new Request(`http://localhost/_zero/actions/${id}`, {
2674
- method: "POST",
2675
- headers: { "Content-Type": "application/json" },
2676
- body: JSON.stringify(data ?? null)
2677
- }),
2678
- formData: null,
2679
- json: data ?? null,
2680
- headers: new Headers({ "Content-Type": "application/json" })
2681
- });
2682
- const response = await fetch(`/_zero/actions/${id}`, {
2683
- method: "POST",
2684
- headers: { "Content-Type": "application/json" },
2685
- body: JSON.stringify(data ?? null)
2686
- });
2687
- if (!response.ok) {
2688
- const body = await response.json().catch(() => ({}));
2689
- throw new Error(body.error ?? `Action failed: ${response.statusText}`);
2690
- }
2691
- return response.json();
2692
- };
2693
- callable.actionId = id;
2694
- return callable;
2695
- }
2696
- /**
2697
- * Create a middleware that handles action requests at `/_zero/actions/*`.
2698
- * Mount this before the SSR handler in the server entry.
2699
- */
2700
- function createActionMiddleware() {
2701
- return async (ctx) => {
2702
- if (!ctx.path.startsWith("/_zero/actions/")) return;
2703
- const actionId = ctx.path.slice(15);
2704
- const action = actionRegistry.get(actionId);
2705
- if (!action) return Response.json({ error: "Action not found" }, { status: 404 });
2706
- if (ctx.req.method !== "POST") return Response.json({ error: "Method not allowed" }, { status: 405 });
2707
- return executeAction(action, ctx.req);
2708
- };
2709
- }
2710
- async function executeAction(action, req) {
2711
- try {
2712
- const contentType = req.headers.get("content-type") ?? "";
2713
- let formData = null;
2714
- let json = null;
2715
- if (contentType.includes("application/json")) json = await req.json();
2716
- else if (contentType.includes("multipart/form-data") || contentType.includes("application/x-www-form-urlencoded")) formData = await req.formData();
2717
- const result = await action.handler({
2718
- request: req,
2719
- formData,
2720
- json,
2721
- headers: req.headers
2722
- });
2723
- return Response.json(result ?? null);
2724
- } catch (err) {
2725
- const message = err instanceof Error ? err.message : "Internal server error";
2726
- return Response.json({ error: message }, { status: 500 });
2727
- }
2728
- }
2729
-
2730
- //#endregion
2731
- //#region src/favicon.ts
2732
- let sharpWarned$1 = false;
2733
- function warnSharpMissing$1() {
2734
- if (sharpWarned$1) return;
2735
- sharpWarned$1 = true;
2736
- console.warn("\n[zero:favicon] sharp not installed — favicons will not be generated. Install for full support: bun add -D sharp\n");
2737
- }
2738
- const SIZES = [
2739
- {
2740
- size: 16,
2741
- name: "favicon-16x16.png"
2742
- },
2743
- {
2744
- size: 32,
2745
- name: "favicon-32x32.png"
2746
- },
2747
- {
2748
- size: 180,
2749
- name: "apple-touch-icon.png"
2750
- },
2751
- {
2752
- size: 192,
2753
- name: "icon-192.png"
2754
- },
2755
- {
2756
- size: 512,
2757
- name: "icon-512.png"
2758
- }
2759
- ];
2760
- /**
2761
- * Favicon generation Vite plugin.
2762
- *
2763
- * Generates all required favicon formats at build time from a single source.
2764
- * In dev mode, serves the source directly.
2765
- *
2766
- * @example
2767
- * ```ts
2768
- * // vite.config.ts
2769
- * import { faviconPlugin } from "@pyreon/zero"
2770
- *
2771
- * export default {
2772
- * plugins: [faviconPlugin({ source: "./src/assets/icon.svg" })],
2773
- * }
2774
- * ```
2775
- */
2776
- function faviconPlugin(config) {
2777
- const themeColor = config.themeColor ?? "#ffffff";
2778
- const backgroundColor = config.backgroundColor ?? "#ffffff";
2779
- const generateManifest = config.manifest !== false;
2780
- let root = "";
2781
- let isBuild = false;
2782
- return {
2783
- name: "pyreon-zero-favicon",
2784
- enforce: "pre",
2785
- configResolved(resolvedConfig) {
2786
- root = resolvedConfig.root;
2787
- isBuild = resolvedConfig.command === "build";
2788
- },
2789
- configureServer(server) {
2790
- const sourcePath = join(root, config.source);
2791
- const devCache = /* @__PURE__ */ new Map();
2792
- server.middlewares.use(async (req, res, next) => {
2793
- const url = req.url ?? "";
2794
- const localeSource = resolveLocaleSource(url, config, root);
2795
- const svgUrl = localeSource ? localeSource.url : url;
2796
- const svgPath = localeSource ? localeSource.sourcePath : sourcePath;
2797
- const isSvgSource = localeSource ? localeSource.source.endsWith(".svg") : config.source.endsWith(".svg");
2798
- if (svgUrl.endsWith("/favicon.svg") && isSvgSource) try {
2799
- const content = await readFile(svgPath, "utf-8");
2800
- res.setHeader("Content-Type", "image/svg+xml");
2801
- res.end(content);
2802
- return;
2803
- } catch {}
2804
- const baseName = svgUrl.split("/").pop() ?? "";
2805
- const sizeMatch = SIZES.find((s) => s.name === baseName);
2806
- if (sizeMatch) {
2807
- const cacheKey = `${svgPath}:${sizeMatch.size}`;
2808
- let png = devCache.get(cacheKey);
2809
- if (!png) {
2810
- const result = await resizeToPng(svgPath, sizeMatch.size);
2811
- if (result) {
2812
- png = result;
2813
- devCache.set(cacheKey, result);
2814
- }
2815
- }
2816
- if (png) {
2817
- res.setHeader("Content-Type", "image/png");
2818
- res.setHeader("Cache-Control", "no-cache");
2819
- res.end(Buffer.from(png));
2820
- return;
2821
- }
2822
- }
2823
- if (baseName === "favicon.ico") {
2824
- const cacheKey = `ico:${svgPath}`;
2825
- let ico = devCache.get(cacheKey);
2826
- if (!ico) {
2827
- const result = await generateIco(svgPath);
2828
- if (result) {
2829
- ico = result;
2830
- devCache.set(cacheKey, result);
2831
- }
2832
- }
2833
- if (ico) {
2834
- res.setHeader("Content-Type", "image/x-icon");
2835
- res.setHeader("Cache-Control", "no-cache");
2836
- res.end(Buffer.from(ico));
2837
- return;
2838
- }
2839
- }
2840
- if (baseName === "site.webmanifest" && generateManifest) {
2841
- const prefix = localeSource ? `/${localeSource.locale}` : "";
2842
- const manifest = {
2843
- name: config.name ?? "App",
2844
- short_name: config.name ?? "App",
2845
- icons: [{
2846
- src: `${prefix}/icon-192.png`,
2847
- sizes: "192x192",
2848
- type: "image/png"
2849
- }, {
2850
- src: `${prefix}/icon-512.png`,
2851
- sizes: "512x512",
2852
- type: "image/png"
2853
- }],
2854
- theme_color: themeColor,
2855
- background_color: backgroundColor,
2856
- display: "standalone"
2857
- };
2858
- res.setHeader("Content-Type", "application/manifest+json");
2859
- res.end(JSON.stringify(manifest, null, 2));
2860
- return;
2861
- }
2862
- next();
2863
- });
2864
- },
2865
- transformIndexHtml() {
2866
- const isSvg = config.source.endsWith(".svg");
2867
- const tags = [];
2868
- if (isSvg) tags.push({
2869
- tag: "link",
2870
- attrs: {
2871
- rel: "icon",
2872
- type: "image/svg+xml",
2873
- href: "/favicon.svg"
2874
- },
2875
- injectTo: "head"
2876
- });
2877
- tags.push({
2878
- tag: "link",
2879
- attrs: {
2880
- rel: "icon",
2881
- type: "image/png",
2882
- sizes: "32x32",
2883
- href: "/favicon-32x32.png"
2884
- },
2885
- injectTo: "head"
2886
- }, {
2887
- tag: "link",
2888
- attrs: {
2889
- rel: "icon",
2890
- type: "image/png",
2891
- sizes: "16x16",
2892
- href: "/favicon-16x16.png"
2893
- },
2894
- injectTo: "head"
2895
- }, {
2896
- tag: "link",
2897
- attrs: {
2898
- rel: "apple-touch-icon",
2899
- sizes: "180x180",
2900
- href: "/apple-touch-icon.png"
2901
- },
2902
- injectTo: "head"
2903
- });
2904
- if (generateManifest) tags.push({
2905
- tag: "link",
2906
- attrs: {
2907
- rel: "manifest",
2908
- href: "/site.webmanifest"
2909
- },
2910
- injectTo: "head"
2911
- });
2912
- tags.push({
2913
- tag: "meta",
2914
- attrs: {
2915
- name: "theme-color",
2916
- content: themeColor
2917
- },
2918
- injectTo: "head"
2919
- });
2920
- return tags;
2921
- },
2922
- async generateBundle() {
2923
- if (!isBuild) return;
2924
- await generateFaviconSet.call(this, root, config.source, config.darkSource, "", config, themeColor, backgroundColor, generateManifest);
2925
- if (config.locales) for (const [locale, localeConfig] of Object.entries(config.locales)) await generateFaviconSet.call(this, root, localeConfig.source, localeConfig.darkSource, `${locale}/`, config, themeColor, backgroundColor, generateManifest);
2926
- }
2927
- };
2928
- }
2929
- /**
2930
- * Wrap two SVGs into a single SVG that switches based on prefers-color-scheme.
2931
- */
2932
- function wrapSvgWithDarkMode(lightSvg, darkSvg) {
2933
- return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${lightSvg.match(/viewBox="([^"]*)"/)?.[1] ?? "0 0 32 32"}">
2934
- <style>
2935
- :root { color-scheme: light dark; }
2936
- @media (prefers-color-scheme: dark) { .light { display: none; } }
2937
- @media (prefers-color-scheme: light), (prefers-color-scheme: no-preference) { .dark { display: none; } }
2938
- </style>
2939
- <g class="light">${stripSvgWrapper(lightSvg)}</g>
2940
- <g class="dark">${stripSvgWrapper(darkSvg)}</g>
2941
- </svg>`;
2942
- }
2943
- function stripSvgWrapper(svg) {
2944
- return svg.replace(/<svg[^>]*>/, "").replace(/<\/svg>\s*$/, "").trim();
2945
- }
2946
- /**
2947
- * Resolve the source path for a locale-prefixed favicon URL.
2948
- * Returns null if the URL is not locale-prefixed or locale has no override.
2949
- */
2950
- function resolveLocaleSource(url, config, rootDir) {
2951
- if (!config.locales) return null;
2952
- for (const [locale, localeConfig] of Object.entries(config.locales)) {
2953
- const prefix = `/${locale}/`;
2954
- if (url.startsWith(prefix)) return {
2955
- locale,
2956
- url,
2957
- source: localeConfig.source,
2958
- sourcePath: join(rootDir, localeConfig.source)
2959
- };
2960
- }
2961
- return null;
2962
- }
2963
- /**
2964
- * Generate a complete favicon set (SVG, PNGs, ICO, manifest) with a file prefix.
2965
- * Called once for base (prefix = '') and once per locale (prefix = '{locale}/').
2966
- */
2967
- async function generateFaviconSet(rootDir, source, darkSource, prefix, config, themeColor, backgroundColor, generateManifest) {
2968
- const sourcePath = join(rootDir, source);
2969
- if (!existsSync(sourcePath)) {
2970
- console.warn(`[zero:favicon] Source not found: ${sourcePath}`);
2971
- return;
2972
- }
2973
- if (source.endsWith(".svg")) {
2974
- const svgContent = await readFile(sourcePath, "utf-8");
2975
- let finalSvg = svgContent;
2976
- if (darkSource) {
2977
- const darkPath = join(rootDir, darkSource);
2978
- if (existsSync(darkPath)) finalSvg = wrapSvgWithDarkMode(svgContent, await readFile(darkPath, "utf-8"));
2979
- }
2980
- this.emitFile({
2981
- type: "asset",
2982
- fileName: `${prefix}favicon.svg`,
2983
- source: finalSvg
2984
- });
2985
- }
2986
- for (const { size, name } of SIZES) {
2987
- const pngBuffer = await resizeToPng(sourcePath, size);
2988
- if (pngBuffer) this.emitFile({
2989
- type: "asset",
2990
- fileName: `${prefix}${name}`,
2991
- source: pngBuffer
2992
- });
2993
- }
2994
- const ico = await generateIco(sourcePath);
2995
- if (ico) this.emitFile({
2996
- type: "asset",
2997
- fileName: `${prefix}favicon.ico`,
2998
- source: ico
2999
- });
3000
- if (generateManifest) {
3001
- const manifestPrefix = prefix ? `/${prefix.slice(0, -1)}` : "";
3002
- const manifest = {
3003
- name: config.name ?? "App",
3004
- short_name: config.name ?? "App",
3005
- icons: [{
3006
- src: `${manifestPrefix}/icon-192.png`,
3007
- sizes: "192x192",
3008
- type: "image/png"
3009
- }, {
3010
- src: `${manifestPrefix}/icon-512.png`,
3011
- sizes: "512x512",
3012
- type: "image/png"
3013
- }],
3014
- theme_color: themeColor,
3015
- background_color: backgroundColor,
3016
- display: "standalone"
3017
- };
3018
- this.emitFile({
3019
- type: "asset",
3020
- fileName: `${prefix}site.webmanifest`,
3021
- source: JSON.stringify(manifest, null, 2)
3022
- });
3023
- }
3024
- }
3025
- /**
3026
- * Get favicon link tags for a specific locale.
3027
- * Returns link objects suitable for `useHead()` or direct HTML injection.
3028
- *
3029
- * @example
3030
- * ```ts
3031
- * const links = faviconLinks("de", { source: "./icon.svg", locales: { de: { source: "./icon-de.svg" } } })
3032
- * // → [{ rel: "icon", type: "image/svg+xml", href: "/de/favicon.svg" }, ...]
3033
- * ```
3034
- */
3035
- function faviconLinks(locale, config) {
3036
- const hasLocaleOverride = locale && config.locales?.[locale];
3037
- const prefix = hasLocaleOverride ? `/${locale}` : "";
3038
- const isSvg = (hasLocaleOverride ? config.locales[locale].source : config.source).endsWith(".svg");
3039
- const links = [];
3040
- if (isSvg) links.push({
3041
- rel: "icon",
3042
- type: "image/svg+xml",
3043
- href: `${prefix}/favicon.svg`
3044
- });
3045
- links.push({
3046
- rel: "icon",
3047
- type: "image/png",
3048
- sizes: "32x32",
3049
- href: `${prefix}/favicon-32x32.png`
3050
- }, {
3051
- rel: "icon",
3052
- type: "image/png",
3053
- sizes: "16x16",
3054
- href: `${prefix}/favicon-16x16.png`
3055
- }, {
3056
- rel: "apple-touch-icon",
3057
- sizes: "180x180",
3058
- href: `${prefix}/apple-touch-icon.png`
3059
- });
3060
- if (config.manifest !== false) links.push({
3061
- rel: "manifest",
3062
- href: `${prefix}/site.webmanifest`
3063
- });
3064
- return links;
3065
- }
3066
- async function resizeToPng(input, size) {
3067
- try {
3068
- return await (await import("sharp").then((m) => m.default ?? m))(input).resize(size, size, {
3069
- fit: "contain",
3070
- background: {
3071
- r: 0,
3072
- g: 0,
3073
- b: 0,
3074
- alpha: 0
3075
- }
3076
- }).png().toBuffer();
3077
- } catch {
3078
- warnSharpMissing$1();
3079
- return null;
3080
- }
3081
- }
3082
- async function generateIco(input) {
3083
- try {
3084
- const sharp = await import("sharp").then((m) => m.default ?? m);
3085
- const png16 = await sharp(input).resize(16, 16, {
3086
- fit: "contain",
3087
- background: {
3088
- r: 0,
3089
- g: 0,
3090
- b: 0,
3091
- alpha: 0
3092
- }
3093
- }).png().toBuffer();
3094
- const png32 = await sharp(input).resize(32, 32, {
3095
- fit: "contain",
3096
- background: {
3097
- r: 0,
3098
- g: 0,
3099
- b: 0,
3100
- alpha: 0
3101
- }
3102
- }).png().toBuffer();
3103
- return createIcoFromPngs([{
3104
- buffer: png16,
3105
- size: 16
3106
- }, {
3107
- buffer: png32,
3108
- size: 32
3109
- }]);
3110
- } catch {
3111
- warnSharpMissing$1();
3112
- return null;
3113
- }
3114
- }
3115
- /** @internal Exported for testing */
3116
- function createIcoFromPngs(entries) {
3117
- const headerSize = 6;
3118
- const dirEntrySize = 16;
3119
- const dirSize = dirEntrySize * entries.length;
3120
- let dataOffset = headerSize + dirSize;
3121
- const header = Buffer.alloc(headerSize);
3122
- header.writeUInt16LE(0, 0);
3123
- header.writeUInt16LE(1, 2);
3124
- header.writeUInt16LE(entries.length, 4);
3125
- const dirEntries = Buffer.alloc(dirSize);
3126
- const dataBuffers = [];
3127
- for (let i = 0; i < entries.length; i++) {
3128
- const entry = entries[i];
3129
- const offset = i * dirEntrySize;
3130
- dirEntries.writeUInt8(entry.size === 256 ? 0 : entry.size, offset);
3131
- dirEntries.writeUInt8(entry.size === 256 ? 0 : entry.size, offset + 1);
3132
- dirEntries.writeUInt8(0, offset + 2);
3133
- dirEntries.writeUInt8(0, offset + 3);
3134
- dirEntries.writeUInt16LE(1, offset + 4);
3135
- dirEntries.writeUInt16LE(32, offset + 6);
3136
- dirEntries.writeUInt32LE(entry.buffer.length, offset + 8);
3137
- dirEntries.writeUInt32LE(dataOffset, offset + 12);
3138
- dataOffset += entry.buffer.length;
3139
- dataBuffers.push(entry.buffer);
3140
- }
3141
- return Buffer.concat([
3142
- header,
3143
- dirEntries,
3144
- ...dataBuffers
3145
- ]);
3146
- }
3147
-
3148
- //#endregion
3149
- //#region src/og-image.ts
3150
- /**
3151
- * OG Image generation plugin.
3152
- *
3153
- * Generates Open Graph images at build time from templates with
3154
- * text overlays. Supports locale-specific text for i18n apps.
3155
- * Uses sharp for image processing (same optional dep as favicon/image plugins).
3156
- *
3157
- * @example
3158
- * ```ts
3159
- * // vite.config.ts
3160
- * import { ogImagePlugin } from "@pyreon/zero/og-image"
3161
- *
3162
- * export default {
3163
- * plugins: [
3164
- * ogImagePlugin({
3165
- * locales: ["en", "de", "cs"],
3166
- * templates: [{
3167
- * name: "default",
3168
- * background: "./src/assets/og-bg.jpg",
3169
- * layers: [{
3170
- * text: { en: "Build faster", de: "Schneller bauen", cs: "Stavte rychleji" },
3171
- * y: "40%",
3172
- * fontSize: 72,
3173
- * }],
3174
- * }],
3175
- * }),
3176
- * ],
3177
- * }
3178
- * ```
3179
- */
3180
- let sharpWarned = false;
3181
- function warnSharpMissing() {
3182
- if (sharpWarned) return;
3183
- sharpWarned = true;
3184
- console.warn("\n[zero:og-image] sharp not installed — OG images will not be generated. Install for full support: bun add -D sharp\n");
3185
- }
3186
- function resolvePosition(value, dimension, fallback = "50%") {
3187
- if (value === void 0) value = fallback;
3188
- if (typeof value === "number") return value;
3189
- if (value.endsWith("%")) return Math.round(Number.parseFloat(value) / 100 * dimension);
3190
- return Number.parseInt(value, 10) || 0;
3191
- }
3192
- function resolveLayerText(layer, locale) {
3193
- if (typeof layer.text === "string") return layer.text;
3194
- if (typeof layer.text === "function") return layer.text(locale);
3195
- return layer.text[locale] ?? layer.text[Object.keys(layer.text)[0] ?? ""] ?? "";
3196
- }
3197
- function escapeXml(str) {
3198
- return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
3199
- }
3200
- /**
3201
- * Build an SVG overlay with text layers.
3202
- * @internal Exported for testing.
3203
- */
3204
- function buildTextOverlaySvg(layers, width, height, locale) {
3205
- return `<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">${layers.map((layer) => {
3206
- const text = resolveLayerText(layer, locale);
3207
- const x = resolvePosition(layer.x, width, "50%");
3208
- const y = resolvePosition(layer.y, height, "50%");
3209
- const fontSize = layer.fontSize ?? 64;
3210
- const fontFamily = layer.fontFamily ?? "sans-serif";
3211
- const fontWeight = layer.fontWeight ?? "bold";
3212
- const color = layer.color ?? "#ffffff";
3213
- const anchor = layer.textAnchor ?? "middle";
3214
- const maxWidth = layer.maxWidth ?? Math.round(width * .8);
3215
- const words = text.split(" ");
3216
- const lines = [];
3217
- let currentLine = "";
3218
- const estimateWidth = (s) => {
3219
- let width = 0;
3220
- for (let i = 0; i < s.length; i++) {
3221
- const code = s.charCodeAt(i);
3222
- if (code >= 12288 && code <= 40959) width += fontSize * 1;
3223
- else if (code <= 126 && "iljft!|:;.,'".includes(s[i])) width += fontSize * .35;
3224
- else width += fontSize * .55;
3225
- }
3226
- return width;
3227
- };
3228
- for (const word of words) {
3229
- const testLine = currentLine ? `${currentLine} ${word}` : word;
3230
- if (estimateWidth(testLine) > maxWidth && currentLine) {
3231
- lines.push(currentLine);
3232
- currentLine = word;
3233
- } else currentLine = testLine;
3234
- }
3235
- if (currentLine) lines.push(currentLine);
3236
- const tspans = lines.map((line, i) => {
3237
- return `<tspan x="${x}" dy="${i === 0 ? "0" : `${fontSize * 1.2}`}">${escapeXml(line)}</tspan>`;
3238
- }).join("");
3239
- return `<text x="${x}" y="${y}" font-size="${fontSize}" font-family="${escapeXml(fontFamily)}" font-weight="${fontWeight}" fill="${color}" text-anchor="${anchor}" dominant-baseline="middle">${tspans}</text>`;
3240
- }).join("")}</svg>`;
3241
- }
3242
- /**
3243
- * Render an OG image from a template for a specific locale.
3244
- * @internal Exported for testing.
3245
- */
3246
- async function renderOgImage(template, locale, rootDir) {
3247
- try {
3248
- const sharp = await import("sharp").then((m) => m.default ?? m);
3249
- const width = template.width ?? 1200;
3250
- const height = template.height ?? 630;
3251
- let pipeline;
3252
- if (typeof template.background === "string") pipeline = sharp(join(rootDir, template.background)).resize(width, height, { fit: "cover" });
3253
- else pipeline = sharp({ create: {
3254
- width,
3255
- height,
3256
- channels: 4,
3257
- background: template.background.color
3258
- } });
3259
- if (template.layers && template.layers.length > 0) {
3260
- const svgOverlay = buildTextOverlaySvg(template.layers, width, height, locale);
3261
- pipeline = pipeline.composite([{
3262
- input: Buffer.from(svgOverlay),
3263
- top: 0,
3264
- left: 0
3265
- }]);
3266
- }
3267
- if (template.format === "jpeg") return await pipeline.jpeg({ quality: template.quality ?? 90 }).toBuffer();
3268
- return await pipeline.png().toBuffer();
3269
- } catch {
3270
- warnSharpMissing();
3271
- return null;
3272
- }
3273
- }
3274
- /**
3275
- * Compute the OG image path for a template and locale.
3276
- *
3277
- * @example
3278
- * ```ts
3279
- * ogImagePath("default", "de") // → "/og/default-de.png"
3280
- * ogImagePath("default") // → "/og/default.png"
3281
- * ogImagePath("hero", "en", "images") // → "/images/hero-en.png"
3282
- * ```
3283
- */
3284
- function ogImagePath(templateName, locale, outDir = "og", format = "png") {
3285
- const ext = format === "jpeg" ? "jpg" : "png";
3286
- return `/${outDir}/${templateName}${locale ? `-${locale}` : ""}.${ext}`;
3287
- }
3288
- /**
3289
- * OG image generation Vite plugin.
3290
- *
3291
- * Generates Open Graph images at build time. In dev, generates on-demand.
3292
- * Requires `sharp` as an optional dependency.
3293
- *
3294
- * @example
3295
- * ```ts
3296
- * // vite.config.ts
3297
- * import { ogImagePlugin } from "@pyreon/zero/og-image"
3298
- *
3299
- * export default {
3300
- * plugins: [
3301
- * ogImagePlugin({
3302
- * locales: ["en", "de"],
3303
- * templates: [{
3304
- * name: "default",
3305
- * background: { color: "#0066ff" },
3306
- * layers: [{ text: { en: "Hello", de: "Hallo" }, fontSize: 72 }],
3307
- * }],
3308
- * }),
3309
- * ],
3310
- * }
3311
- * ```
3312
- */
3313
- function ogImagePlugin(config) {
3314
- const outDir = config.outDir ?? "og";
3315
- let root = "";
3316
- let isBuild = false;
3317
- return {
3318
- name: "pyreon-zero-og-image",
3319
- enforce: "pre",
3320
- configResolved(resolvedConfig) {
3321
- root = resolvedConfig.root;
3322
- isBuild = resolvedConfig.command === "build";
3323
- },
3324
- configureServer(server) {
3325
- const devCache = /* @__PURE__ */ new Map();
3326
- server.middlewares.use(async (req, res, next) => {
3327
- const url = req.url ?? "";
3328
- if (!url.startsWith(`/${outDir}/`)) return next();
3329
- const match = url.slice(outDir.length + 2).match(/^(.+?)(?:-([a-z]{2,5}))?\.(png|jpe?g)$/);
3330
- if (!match) return next();
3331
- const [, templateName, locale, ext] = match;
3332
- const template = config.templates.find((t) => t.name === templateName);
3333
- if (!template) return next();
3334
- const resolvedLocale = locale ?? config.locales?.[0] ?? "en";
3335
- const cacheKey = `${templateName}:${resolvedLocale}`;
3336
- let buffer = devCache.get(cacheKey);
3337
- if (!buffer) {
3338
- const result = await renderOgImage(template, resolvedLocale, root);
3339
- if (!result) return next();
3340
- buffer = result;
3341
- devCache.set(cacheKey, result);
3342
- }
3343
- const contentType = ext === "jpg" || ext === "jpeg" ? "image/jpeg" : "image/png";
3344
- res.setHeader("Content-Type", contentType);
3345
- res.setHeader("Cache-Control", "no-cache");
3346
- res.end(Buffer.from(buffer));
3347
- });
3348
- },
3349
- async generateBundle() {
3350
- if (!isBuild) return;
3351
- for (const template of config.templates) {
3352
- const locales = config.locales ?? [void 0];
3353
- const ext = (template.format ?? "png") === "jpeg" ? "jpg" : "png";
3354
- for (const locale of locales) {
3355
- if (typeof template.background === "string") {
3356
- const bgPath = join(root, template.background);
3357
- if (!existsSync(bgPath)) {
3358
- console.warn(`[zero:og-image] Background not found: ${bgPath}`);
3359
- continue;
3360
- }
3361
- }
3362
- const buffer = await renderOgImage(template, locale ?? "en", root);
3363
- if (!buffer) continue;
3364
- const suffix = locale ? `-${locale}` : "";
3365
- this.emitFile({
3366
- type: "asset",
3367
- fileName: `${outDir}/${template.name}${suffix}.${ext}`,
3368
- source: buffer
3369
- });
3370
- }
3371
- }
3372
- }
3373
- };
3374
- }
3375
-
3376
- //#endregion
3377
- //#region src/i18n-routing.ts
3378
- /**
3379
- * Detect preferred locale from Accept-Language header.
3380
- */
3381
- function detectLocaleFromHeader(acceptLanguage, locales, defaultLocale) {
3382
- if (!acceptLanguage) return defaultLocale;
3383
- const preferred = acceptLanguage.split(",").map((part) => {
3384
- const [lang, q] = part.trim().split(";q=");
3385
- return {
3386
- lang: lang?.split("-")[0]?.toLowerCase() ?? "",
3387
- quality: q ? Number.parseFloat(q) : 1
3388
- };
3389
- }).sort((a, b) => b.quality - a.quality);
3390
- for (const { lang } of preferred) if (locales.includes(lang)) return lang;
3391
- return defaultLocale;
3392
- }
3393
- /**
3394
- * Extract locale from a URL path.
3395
- * Returns { locale, pathWithoutLocale }.
3396
- */
3397
- function extractLocaleFromPath(path, locales, defaultLocale) {
3398
- const segments = path.split("/").filter(Boolean);
3399
- const firstSegment = segments[0]?.toLowerCase();
3400
- if (firstSegment && locales.includes(firstSegment)) return {
3401
- locale: firstSegment,
3402
- pathWithoutLocale: "/" + segments.slice(1).join("/") || "/"
3403
- };
3404
- return {
3405
- locale: defaultLocale,
3406
- pathWithoutLocale: path
3407
- };
3408
- }
3409
- /**
3410
- * Build a localized path.
3411
- */
3412
- function buildLocalePath(path, locale, defaultLocale, strategy) {
3413
- const clean = path === "/" ? "" : path;
3414
- if (strategy === "prefix-except-default" && locale === defaultLocale) return path;
3415
- return `/${locale}${clean}`;
3416
- }
3417
- /**
3418
- * Create a LocaleContext for use in components and loaders.
3419
- */
3420
- function createLocaleContext(locale, path, config) {
3421
- const strategy = config.strategy ?? "prefix-except-default";
3422
- return {
3423
- locale,
3424
- locales: config.locales,
3425
- defaultLocale: config.defaultLocale,
3426
- localePath(targetPath, targetLocale) {
3427
- return buildLocalePath(targetPath, targetLocale ?? locale, config.defaultLocale, strategy);
3428
- },
3429
- alternates() {
3430
- const { pathWithoutLocale } = extractLocaleFromPath(path, config.locales, config.defaultLocale);
3431
- return config.locales.map((loc) => ({
3432
- locale: loc,
3433
- url: buildLocalePath(pathWithoutLocale, loc, config.defaultLocale, strategy)
3434
- }));
3435
- }
3436
- };
3437
- }
3438
- /**
3439
- * I18n routing middleware for Zero's server.
3440
- *
3441
- * - Detects locale from URL prefix or Accept-Language header
3442
- * - Redirects root to preferred locale (when detectLocale is true)
3443
- * - Sets locale context for loaders and components
3444
- *
3445
- * @example
3446
- * ```ts
3447
- * // zero.config.ts
3448
- * import { i18nRouting } from "@pyreon/zero"
3449
- *
3450
- * export default defineConfig({
3451
- * plugins: [
3452
- * i18nRouting({
3453
- * locales: ["en", "de", "cs"],
3454
- * defaultLocale: "en",
3455
- * }),
3456
- * ],
3457
- * })
3458
- * ```
3459
- */
3460
- function i18nRouting(config) {
3461
- const strategy = config.strategy ?? "prefix-except-default";
3462
- const detectEnabled = config.detectLocale !== false;
3463
- const cookieName = config.cookieName ?? "locale";
3464
- return {
3465
- name: "pyreon-zero-i18n-routing",
3466
- configResolved() {},
3467
- configureServer(server) {
3468
- server.middlewares.use((req, res, next) => {
3469
- const url = req.url ?? "/";
3470
- if (url.startsWith("/@") || url.startsWith("/__") || url.includes(".")) return next();
3471
- const { locale } = extractLocaleFromPath(url, config.locales, config.defaultLocale);
3472
- if (detectEnabled && url === "/") {
3473
- const preferredFromCookie = parseCookies(req.headers.cookie)[cookieName];
3474
- const preferredFromHeader = detectLocaleFromHeader(req.headers["accept-language"], config.locales, config.defaultLocale);
3475
- const preferred = preferredFromCookie && config.locales.includes(preferredFromCookie) ? preferredFromCookie : preferredFromHeader;
3476
- if (strategy === "prefix" || preferred !== config.defaultLocale) {
3477
- res.writeHead(302, { Location: `/${preferred}/` });
3478
- res.end();
3479
- return;
3480
- }
3481
- }
3482
- req.__locale = locale;
3483
- req.__localeContext = createLocaleContext(locale, url, config);
3484
- localeSignal.set(locale);
3485
- next();
3486
- });
3487
- }
3488
- };
3489
- }
3490
- function parseCookies(header) {
3491
- if (!header) return {};
3492
- const result = {};
3493
- for (const pair of header.split(";")) {
3494
- const [key, value] = pair.trim().split("=");
3495
- if (key && value) result[key] = decodeURIComponent(value);
3496
- }
3497
- return result;
3498
- }
3499
- /** @internal Context for the current locale. */
3500
- const LocaleCtx = createContext("en");
3501
- /** Current locale signal — set by the server middleware or client-side detection. */
3502
- const localeSignal = signal("en");
3503
- /**
3504
- * Read the current locale reactively.
3505
- *
3506
- * Returns the locale signal value directly — reactive in both SSR and CSR.
3507
- * The server middleware sets `localeSignal` per-request, and client-side
3508
- * `setLocale()` updates it as well.
3509
- *
3510
- * @example
3511
- * ```tsx
3512
- * const locale = useLocale() // "en", "de", etc.
3513
- * ```
3514
- */
3515
- function useLocale() {
3516
- return localeSignal();
3517
- }
3518
- /**
3519
- * Set the locale client-side and update the URL.
3520
- *
3521
- * @example
3522
- * ```tsx
3523
- * <button onClick={() => setLocale('de')}>Deutsch</button>
3524
- * ```
3525
- */
3526
- function setLocale(locale, config) {
3527
- localeSignal.set(locale);
3528
- if (typeof document !== "undefined") document.cookie = `${config.cookieName ?? "locale"}=${locale}; path=/; max-age=31536000`;
3529
- if (typeof window !== "undefined") {
3530
- const strategy = config.strategy ?? "prefix-except-default";
3531
- const { pathWithoutLocale } = extractLocaleFromPath(window.location.pathname, config.locales, config.defaultLocale);
3532
- const newPath = buildLocalePath(pathWithoutLocale, locale, config.defaultLocale, strategy);
3533
- window.history.pushState(null, "", newPath);
3534
- window.dispatchEvent(new PopStateEvent("popstate"));
3535
- }
3536
- }
3537
-
3538
- //#endregion
3539
- //#region src/meta.tsx
3540
- const resolveStr = (v) => typeof v === "function" ? v() : v;
3541
- /**
3542
- * Declarative meta component for SSR-compatible page metadata.
3543
- *
3544
- * Supports reactive title/description — when passed as `() => string` accessors,
3545
- * they are forwarded to `useHead()` as a reactive getter so updates propagate
3546
- * automatically via signal tracking.
3547
- *
3548
- * @example
3549
- * ```tsx
3550
- * <Meta title="My Page" description="..." image="/og.jpg" canonical="https://..." />
3551
- * ```
3552
- *
3553
- * @example Reactive title
3554
- * ```tsx
3555
- * const count = signal(0)
3556
- * <Meta title={() => `${count()} items`} />
3557
- * ```
3558
- */
3559
- function Meta(props) {
3560
- const hasReactiveTitle = typeof props.title === "function";
3561
- const hasReactiveDescription = typeof props.description === "function";
3562
- if (hasReactiveTitle || hasReactiveDescription) useHead((() => {
3563
- const title = resolveStr(props.title);
3564
- const description = resolveStr(props.description);
3565
- const tags = buildMetaTags({
3566
- ...props,
3567
- title,
3568
- description
3569
- });
3570
- return {
3571
- title,
3572
- meta: tags.meta,
3573
- link: tags.link,
3574
- script: tags.script
3575
- };
3576
- }));
3577
- else {
3578
- const title = resolveStr(props.title);
3579
- const description = resolveStr(props.description);
3580
- const tags = buildMetaTags({
3581
- ...props,
3582
- title,
3583
- description
3584
- });
3585
- useHead({
3586
- title,
3587
- meta: tags.meta,
3588
- link: tags.link,
3589
- script: tags.script
3590
- });
3591
- }
3592
- return props.children ?? null;
3593
- }
3594
- function buildMetaTags(props) {
3595
- const meta = [];
3596
- const link = [];
3597
- const script = [];
3598
- const { title, description, canonical, imageAlt, imageWidth, imageHeight, type = "website", siteName, twitterCard = "summary_large_image", twitterSite, twitterCreator, locale = "en_US", alternateLocales, publishedTime, modifiedTime, author, tags, jsonLd, extra, video, videoWidth, videoHeight, audio, favicon, ogTemplate, ogImageDir, ogImageFormat } = props;
3599
- const robots = props.noIndex ? "noindex, nofollow" : props.robots ?? "index, follow";
3600
- const image = props.image ?? (ogTemplate ? ogImagePath(ogTemplate, locale !== "en_US" ? locale : void 0, ogImageDir, ogImageFormat) : void 0);
3601
- const resolvedImageWidth = imageWidth ?? (ogTemplate && !props.image ? 1200 : void 0);
3602
- const resolvedImageHeight = imageHeight ?? (ogTemplate && !props.image ? 630 : void 0);
3603
- if (description) meta.push({
3604
- name: "description",
3605
- content: description
3606
- });
3607
- if (robots) meta.push({
3608
- name: "robots",
3609
- content: robots
3610
- });
3611
- if (author) meta.push({
3612
- name: "author",
3613
- content: author
3614
- });
3615
- if (title) meta.push({
3616
- property: "og:title",
3617
- content: title
3618
- });
3619
- if (description) meta.push({
3620
- property: "og:description",
3621
- content: description
3622
- });
3623
- if (canonical) meta.push({
3624
- property: "og:url",
3625
- content: canonical
3626
- });
3627
- if (image) meta.push({
3628
- property: "og:image",
3629
- content: image
3630
- });
3631
- if (imageAlt) meta.push({
3632
- property: "og:image:alt",
3633
- content: imageAlt
3634
- });
3635
- if (resolvedImageWidth) meta.push({
3636
- property: "og:image:width",
3637
- content: String(resolvedImageWidth)
3638
- });
3639
- if (resolvedImageHeight) meta.push({
3640
- property: "og:image:height",
3641
- content: String(resolvedImageHeight)
3642
- });
3643
- meta.push({
3644
- property: "og:type",
3645
- content: type
3646
- });
3647
- if (siteName) meta.push({
3648
- property: "og:site_name",
3649
- content: siteName
3650
- });
3651
- meta.push({
3652
- property: "og:locale",
3653
- content: locale
3654
- });
3655
- if (video) {
3656
- meta.push({
3657
- property: "og:video",
3658
- content: video
3659
- });
3660
- if (videoWidth) meta.push({
3661
- property: "og:video:width",
3662
- content: String(videoWidth)
3663
- });
3664
- if (videoHeight) meta.push({
3665
- property: "og:video:height",
3666
- content: String(videoHeight)
3667
- });
3668
- if (video.endsWith(".mp4")) meta.push({
3669
- property: "og:video:type",
3670
- content: "video/mp4"
3671
- });
3672
- else if (video.endsWith(".webm")) meta.push({
3673
- property: "og:video:type",
3674
- content: "video/webm"
3675
- });
3676
- }
3677
- if (audio) meta.push({
3678
- property: "og:audio",
3679
- content: audio
3680
- });
3681
- if (type === "article") {
3682
- if (publishedTime) meta.push({
3683
- property: "article:published_time",
3684
- content: publishedTime
3685
- });
3686
- if (modifiedTime) meta.push({
3687
- property: "article:modified_time",
3688
- content: modifiedTime
3689
- });
3690
- if (author) meta.push({
3691
- property: "article:author",
3692
- content: author
3693
- });
3694
- if (tags) for (const tag of tags) meta.push({
3695
- property: "article:tag",
3696
- content: tag
3697
- });
3698
- }
3699
- meta.push({
3700
- name: "twitter:card",
3701
- content: twitterCard
3702
- });
3703
- if (title) meta.push({
3704
- name: "twitter:title",
3705
- content: title
3706
- });
3707
- if (description) meta.push({
3708
- name: "twitter:description",
3709
- content: description
3710
- });
3711
- if (image) meta.push({
3712
- name: "twitter:image",
3713
- content: image
3714
- });
3715
- if (imageAlt) meta.push({
3716
- name: "twitter:image:alt",
3717
- content: imageAlt
3718
- });
3719
- if (twitterSite) meta.push({
3720
- name: "twitter:site",
3721
- content: twitterSite
3722
- });
3723
- if (twitterCreator) meta.push({
3724
- name: "twitter:creator",
3725
- content: twitterCreator
3726
- });
3727
- if (canonical) link.push({
3728
- rel: "canonical",
3729
- href: canonical
3730
- });
3731
- if (alternateLocales) for (const alt of alternateLocales) link.push({
3732
- rel: "alternate",
3733
- hreflang: alt.locale,
3734
- href: alt.url
3735
- });
3736
- if (jsonLd) script.push({
3737
- type: "application/ld+json",
3738
- children: JSON.stringify({
3739
- "@context": "https://schema.org",
3740
- ...jsonLd
3741
- })
3742
- });
3743
- if (extra) for (const tag of extra) meta.push(tag);
3744
- if (props.i18n) {
3745
- const i18nConfig = props.i18n;
3746
- const origin = props.origin ?? "";
3747
- const { pathWithoutLocale } = extractLocaleFromPath(canonical?.replace(origin, "") ?? "/", i18nConfig.locales, i18nConfig.defaultLocale);
3748
- const strategy = i18nConfig.strategy ?? "prefix-except-default";
3749
- for (const loc of i18nConfig.locales) {
3750
- const localizedPath = strategy === "prefix-except-default" && loc === i18nConfig.defaultLocale ? pathWithoutLocale : `/${loc}${pathWithoutLocale === "/" ? "" : pathWithoutLocale}`;
3751
- link.push({
3752
- rel: "alternate",
3753
- hreflang: loc,
3754
- href: `${origin}${localizedPath}`
3755
- });
3756
- if (loc !== locale) meta.push({
3757
- property: "og:locale:alternate",
3758
- content: loc
3759
- });
3760
- }
3761
- link.push({
3762
- rel: "alternate",
3763
- hreflang: "x-default",
3764
- href: `${origin}${pathWithoutLocale}`
3765
- });
3766
- }
3767
- if (favicon) {
3768
- const faviconLocale = locale !== "en_US" ? locale : void 0;
3769
- for (const fl of faviconLinks(faviconLocale, favicon)) link.push(fl);
3770
- if (favicon.themeColor) meta.push({
3771
- name: "theme-color",
3772
- content: favicon.themeColor
3773
- });
3774
- }
3775
- return {
3776
- meta,
3777
- link,
3778
- script
3779
- };
3780
- }
3781
-
3782
- //#endregion
3783
- //#region src/csp.ts
3784
- /** Client-side fallback nonce (dev server, SPA). */
3785
- let _clientNonce = "";
3786
- /**
3787
- * Read the current CSP nonce in a component.
3788
- *
3789
- * SSR: reads from per-request `ctx.locals.cspNonce` via Pyreon's context
3790
- * system — fully isolated between concurrent requests via AsyncLocalStorage.
3791
- * Client/dev: falls back to module-level variable set by middleware.
3792
- *
3793
- * @example
3794
- * ```tsx
3795
- * import { useNonce } from "@pyreon/zero/csp"
3796
- *
3797
- * function InlineScript() {
3798
- * const nonce = useNonce()
3799
- * return <script nonce={nonce}>console.log("safe")<\/script>
3800
- * }
3801
- * ```
3802
- */
3803
- function useNonce() {
3804
- const locals = useRequestLocals();
3805
- if (locals.cspNonce) return locals.cspNonce;
3806
- return _clientNonce;
3807
- }
3808
- const DIRECTIVE_MAP = {
3809
- defaultSrc: "default-src",
3810
- scriptSrc: "script-src",
3811
- styleSrc: "style-src",
3812
- imgSrc: "img-src",
3813
- fontSrc: "font-src",
3814
- connectSrc: "connect-src",
3815
- mediaSrc: "media-src",
3816
- objectSrc: "object-src",
3817
- frameSrc: "frame-src",
3818
- childSrc: "child-src",
3819
- workerSrc: "worker-src",
3820
- frameAncestors: "frame-ancestors",
3821
- formAction: "form-action",
3822
- baseUri: "base-uri",
3823
- manifestSrc: "manifest-src",
3824
- reportUri: "report-uri",
3825
- reportTo: "report-to"
3826
- };
3827
- /**
3828
- * Build a CSP header string from directives.
3829
- * Exported for testing.
3830
- */
3831
- function buildCspHeader(directives, nonce) {
3832
- const parts = [];
3833
- for (const [key, cssProp] of Object.entries(DIRECTIVE_MAP)) {
3834
- const value = directives[key];
3835
- if (!value) continue;
3836
- if (Array.isArray(value)) {
3837
- const resolved = nonce ? value.map((v) => v === "'nonce'" ? `'nonce-${nonce}'` : v) : value.filter((v) => v !== "'nonce'");
3838
- parts.push(`${cssProp} ${resolved.join(" ")}`);
3839
- } else if (typeof value === "string") parts.push(`${cssProp} ${value}`);
3840
- }
3841
- if (directives.upgradeInsecureRequests) parts.push("upgrade-insecure-requests");
3842
- if (directives.blockAllMixedContent) parts.push("block-all-mixed-content");
3843
- return parts.join("; ");
3844
- }
3845
- /**
3846
- * Generate a random nonce string (base64, 16 bytes).
3847
- */
3848
- function generateNonce() {
3849
- if (typeof crypto !== "undefined" && crypto.getRandomValues) {
3850
- const bytes = new Uint8Array(16);
3851
- crypto.getRandomValues(bytes);
3852
- let binary = "";
3853
- for (const byte of bytes) binary += String.fromCharCode(byte);
3854
- return typeof btoa === "function" ? btoa(binary) : Buffer.from(bytes).toString("base64");
3855
- }
3856
- return Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2);
3857
- }
3858
- /**
3859
- * CSP middleware — sets Content-Security-Policy header.
3860
- *
3861
- * When directives contain `"'nonce'"`, a fresh nonce is generated per-request
3862
- * and attached to `ctx.locals.cspNonce` for use in inline script tags.
3863
- *
3864
- * @example
3865
- * ```ts
3866
- * // Apply to all routes
3867
- * export default defineConfig({
3868
- * middleware: [
3869
- * cspMiddleware({
3870
- * directives: {
3871
- * defaultSrc: ["'self'"],
3872
- * scriptSrc: ["'self'", "'nonce'"],
3873
- * styleSrc: ["'self'", "'unsafe-inline'"],
3874
- * imgSrc: ["'self'", "data:", "https:"],
3875
- * },
3876
- * }),
3877
- * ],
3878
- * })
3879
- * ```
3880
- */
3881
- function cspMiddleware(config) {
3882
- const headerName = config.reportOnly ? "Content-Security-Policy-Report-Only" : "Content-Security-Policy";
3883
- const staticHeader = Object.values(config.directives).some((v) => Array.isArray(v) && v.includes("'nonce'")) ? null : buildCspHeader(config.directives);
3884
- return (ctx) => {
3885
- if (staticHeader) {
3886
- _clientNonce = "";
3887
- ctx.headers.set(headerName, staticHeader);
3888
- } else {
3889
- const nonce = generateNonce();
3890
- _clientNonce = nonce;
3891
- ctx.locals.cspNonce = nonce;
3892
- ctx.headers.set(headerName, buildCspHeader(config.directives, nonce));
3893
- }
3894
- };
3895
- }
3896
-
3897
- //#endregion
3898
- //#region src/logger.ts
3899
- const COLORS = {
3900
- reset: "\x1B[0m",
3901
- dim: "\x1B[2m",
3902
- green: "\x1B[32m",
3903
- yellow: "\x1B[33m",
3904
- red: "\x1B[31m",
3905
- cyan: "\x1B[36m",
3906
- magenta: "\x1B[35m"
3907
- };
3908
- function methodColor(method, colors) {
3909
- if (!colors) return method.padEnd(7);
3910
- const padded = method.padEnd(7);
3911
- switch (method) {
3912
- case "GET": return `${COLORS.green}${padded}${COLORS.reset}`;
3913
- case "POST": return `${COLORS.cyan}${padded}${COLORS.reset}`;
3914
- case "PUT": return `${COLORS.yellow}${padded}${COLORS.reset}`;
3915
- case "PATCH": return `${COLORS.yellow}${padded}${COLORS.reset}`;
3916
- case "DELETE": return `${COLORS.red}${padded}${COLORS.reset}`;
3917
- default: return `${COLORS.magenta}${padded}${COLORS.reset}`;
3918
- }
3919
- }
3920
- function defaultFormat(entry, colors) {
3921
- const dur = entry.duration < 1 ? "<1ms" : entry.duration < 1e3 ? `${Math.round(entry.duration)}ms` : `${(entry.duration / 1e3).toFixed(2)}s`;
3922
- const dim = colors ? COLORS.dim : "";
3923
- const reset = colors ? COLORS.reset : "";
3924
- return ` ${methodColor(entry.method, colors)} ${entry.path} ${dim}${dur}${reset}`;
3925
- }
3926
- /**
3927
- * Request logging middleware.
3928
- *
3929
- * Logs incoming requests with method, path, and duration.
3930
- * Runs in middleware phase — logs timing from middleware start to
3931
- * microtask completion (approximate request duration).
3932
- *
3933
- * @example
3934
- * ```ts
3935
- * // Basic usage
3936
- * loggerMiddleware()
3937
- *
3938
- * // Custom format
3939
- * loggerMiddleware({
3940
- * format: (e) => `${e.method} ${e.path} (${e.duration}ms)`,
3941
- * })
3942
- * ```
3943
- */
3944
- function loggerMiddleware(config) {
3945
- if ((config?.level ?? "all") === "none") return () => {};
3946
- const skip = config?.skip ?? [
3947
- "/__",
3948
- "/@",
3949
- "/node_modules"
3950
- ];
3951
- const isDev = typeof process !== "undefined" && process.env.NODE_ENV !== "production";
3952
- const colors = config?.colors ?? isDev;
3953
- return (ctx) => {
3954
- if (skip.some((p) => ctx.path.startsWith(p))) return;
3955
- const start = performance.now();
3956
- const entry = {
3957
- method: ctx.req.method ?? "GET",
3958
- path: ctx.path,
3959
- duration: 0,
3960
- timestamp: /* @__PURE__ */ new Date(),
3961
- userAgent: ctx.req.headers.get("user-agent") ?? void 0
3962
- };
3963
- queueMicrotask(() => {
3964
- entry.duration = performance.now() - start;
3965
- if (config?.format) {
3966
- const line = config.format(entry);
3967
- if (line) console.log(line);
3968
- } else console.log(defaultFormat(entry, colors));
3969
- });
3970
- };
3971
- }
3972
-
3973
- //#endregion
3974
- //#region src/env.ts
3975
- /**
3976
- * String validator — accepts any non-empty string.
3977
- */
3978
- function str(options) {
3979
- return {
3980
- __type: "env-validator",
3981
- required: options?.default === void 0 && options?.required !== false,
3982
- defaultValue: options?.default,
3983
- parse(raw, key) {
3984
- if (raw === void 0 || raw === "") {
3985
- if (options?.default !== void 0) return options.default;
3986
- throw new EnvError(key, "is required but not set", options?.description);
3987
- }
3988
- return raw;
3989
- }
3990
- };
3991
- }
3992
- /**
3993
- * Number validator — parses to a number, rejects NaN.
3994
- */
3995
- function num(options) {
3996
- return {
3997
- __type: "env-validator",
3998
- required: options?.default === void 0 && options?.required !== false,
3999
- defaultValue: options?.default,
4000
- parse(raw, key) {
4001
- if (raw === void 0 || raw === "") {
4002
- if (options?.default !== void 0) return options.default;
4003
- throw new EnvError(key, "is required but not set", options?.description);
4004
- }
4005
- const n = Number(raw);
4006
- if (Number.isNaN(n)) throw new EnvError(key, `must be a number, got "${raw}"`, options?.description);
4007
- return n;
4008
- }
4009
- };
4010
- }
4011
- /**
4012
- * Boolean validator — accepts "true"/"1" as true, "false"/"0" as false.
4013
- */
4014
- function bool(options) {
4015
- return {
4016
- __type: "env-validator",
4017
- required: options?.default === void 0 && options?.required !== false,
4018
- defaultValue: options?.default,
4019
- parse(raw, key) {
4020
- if (raw === void 0 || raw === "") {
4021
- if (options?.default !== void 0) return options.default;
4022
- throw new EnvError(key, "is required but not set", options?.description);
4023
- }
4024
- const lower = raw.toLowerCase();
4025
- if (lower === "true" || lower === "1") return true;
4026
- if (lower === "false" || lower === "0") return false;
4027
- throw new EnvError(key, `must be "true" or "false", got "${raw}"`, options?.description);
4028
- }
4029
- };
4030
- }
4031
- /**
4032
- * URL validator — validates that the value is a valid URL.
4033
- */
4034
- function url(options) {
4035
- return {
4036
- __type: "env-validator",
4037
- required: options?.default === void 0 && options?.required !== false,
4038
- defaultValue: options?.default,
4039
- parse(raw, key) {
4040
- if (raw === void 0 || raw === "") {
4041
- if (options?.default !== void 0) return options.default;
4042
- throw new EnvError(key, "is required but not set", options?.description);
4043
- }
4044
- try {
4045
- new URL(raw);
4046
- return raw;
4047
- } catch {
4048
- throw new EnvError(key, `must be a valid URL, got "${raw}"`, options?.description);
4049
- }
4050
- }
4051
- };
4052
- }
4053
- /**
4054
- * Enum validator — value must be one of the allowed values.
4055
- */
4056
- function oneOf(values, options) {
4057
- return {
4058
- __type: "env-validator",
4059
- required: options?.default === void 0 && options?.required !== false,
4060
- defaultValue: options?.default,
4061
- parse(raw, key) {
4062
- if (raw === void 0 || raw === "") {
4063
- if (options?.default !== void 0) return options.default;
4064
- throw new EnvError(key, "is required but not set", options?.description);
4065
- }
4066
- if (!values.includes(raw)) throw new EnvError(key, `must be one of [${values.join(", ")}], got "${raw}"`, options?.description);
4067
- return raw;
4068
- }
4069
- };
4070
- }
4071
- var EnvError = class extends Error {
4072
- constructor(key, message, description) {
4073
- const desc = description ? ` (${description})` : "";
4074
- super(`[zero:env] ${key}${desc}: ${message}`);
4075
- this.name = "EnvError";
4076
- }
4077
- };
4078
- function isEnvValidator(v) {
4079
- return typeof v === "object" && v !== null && v.__type === "env-validator";
4080
- }
4081
- /**
4082
- * Convert a plain schema value to an EnvValidator.
4083
- *
4084
- * - `3000` → num({ default: 3000 })
4085
- * - `false` → bool({ default: false })
4086
- * - `"localhost"` → str({ default: "localhost" })
4087
- * - `String` → str() (required)
4088
- * - `Number` → num() (required)
4089
- * - `Boolean` → bool() (required)
4090
- * - EnvValidator → pass through
4091
- */
4092
- function toValidator(value) {
4093
- if (isEnvValidator(value)) return value;
4094
- if (value === String) return str();
4095
- if (value === Number) return num();
4096
- if (value === Boolean) return bool();
4097
- if (typeof value === "number") return num({ default: value });
4098
- if (typeof value === "boolean") return bool({ default: value });
4099
- if (typeof value === "string") return str({ default: value });
4100
- throw new Error(`[zero:env] Invalid schema value: ${String(value)}. Use a default value, String/Number/Boolean, or a validator like url().`);
4101
- }
4102
- /**
4103
- * Validate environment variables.
4104
- *
4105
- * Schema values can be:
4106
- * - **Default values**: `3000`, `false`, `"localhost"` → type inferred, used as default
4107
- * - **Constructors**: `String`, `Number`, `Boolean` → required, no default
4108
- * - **Validators**: `url()`, `oneOf([...])`, `str()`, `num()`, `bool()` → explicit validation
4109
- * - **Custom**: `schema(raw => z.coerce.number().parse(raw))` — bridge to any schema library
4110
- *
4111
- * @example
4112
- * ```ts
4113
- * import { validateEnv, url, oneOf } from "@pyreon/zero/env"
4114
- *
4115
- * const env = validateEnv({
4116
- * PORT: 3000, // optional, default 3000
4117
- * DATABASE_URL: url(), // required, validated URL
4118
- * NODE_ENV: oneOf(["dev", "prod", "test"]), // required, must be one of
4119
- * API_KEY: String, // required string
4120
- * DEBUG: false, // optional, default false
4121
- * })
4122
- * ```
4123
- */
4124
- function validateEnv(schema, source) {
4125
- const env = source ?? (typeof process !== "undefined" ? process.env : {});
4126
- const result = {};
4127
- const errors = [];
4128
- for (const [key, entry] of Object.entries(schema)) {
4129
- const validator = toValidator(entry);
4130
- try {
4131
- result[key] = validator.parse(env[key], key);
4132
- } catch (e) {
4133
- errors.push(e.message);
4134
- }
4135
- }
4136
- if (errors.length > 0) {
4137
- const header = `\n[zero:env] Environment validation failed (${errors.length} error${errors.length > 1 ? "s" : ""}):\n`;
4138
- const body = errors.map((e) => ` ✗ ${e.replace("[zero:env] ", "")}`).join("\n");
4139
- throw new Error(header + body + "\n");
4140
- }
4141
- return result;
4142
- }
4143
- function publicEnv(schema) {
4144
- const prefix = "ZERO_PUBLIC_";
4145
- const env = typeof process !== "undefined" ? process.env : {};
4146
- if (!schema) {
4147
- const result = {};
4148
- for (const [key, value] of Object.entries(env)) if (key.startsWith(prefix) && value !== void 0) result[key.slice(12)] = value;
4149
- return result;
4150
- }
4151
- const prefixedSource = {};
4152
- for (const key of Object.keys(schema)) prefixedSource[key] = env[`${prefix}${key}`];
4153
- return validateEnv(schema, prefixedSource);
4154
- }
4155
- /**
4156
- * Create an env validator from a custom parse function.
4157
- * Use this to integrate any schema library (Zod, Valibot, ArkType, etc.).
4158
- *
4159
- * @example
4160
- * ```ts
4161
- * import { z } from "zod"
4162
- * import { validateEnv, schema } from "@pyreon/zero/env"
4163
- *
4164
- * const env = validateEnv({
4165
- * PORT: schema(raw => z.coerce.number().parse(raw)),
4166
- * DATABASE_URL: schema(raw => z.string().url().parse(raw)),
4167
- * HOST: "localhost", // plain defaults still work alongside
4168
- * })
4169
- * ```
4170
- */
4171
- function schema(parse) {
4172
- return {
4173
- __type: "env-validator",
4174
- required: true,
4175
- defaultValue: void 0,
4176
- parse(raw, key) {
4177
- if (raw === void 0 || raw === "") throw new Error(`[zero:env] ${key}: is required but not set`);
4178
- try {
4179
- return parse(raw);
4180
- } catch (e) {
4181
- const msg = e instanceof Error ? e.message : String(e);
4182
- throw new Error(`[zero:env] ${key}: ${msg}`);
4183
- }
4184
- }
4185
- };
4186
- }
4187
-
4188
- //#endregion
4189
- //#region src/ai.ts
4190
- /**
4191
- * Generate llms.txt content from route files and config.
4192
- *
4193
- * Format follows the llms.txt proposal:
4194
- * ```
4195
- * # {name}
4196
- * > {description}
4197
- *
4198
- * ## Pages
4199
- * - [/about](/about): About page
4200
- *
4201
- * ## API
4202
- * - GET /api/posts: List posts
4203
- * ```
4204
- *
4205
- * @internal Exported for testing.
4206
- */
4207
- function generateLlmsTxt(routeFiles, apiFiles, config) {
4208
- const lines = [];
4209
- lines.push(`# ${config.name}`);
4210
- lines.push(`> ${config.description}`);
4211
- lines.push("");
4212
- const routes = parseFileRoutes(routeFiles);
4213
- const pages = routes.filter((r) => !r.isLayout && !r.isError && !r.isLoading && !r.isNotFound && !r.isCatchAll && !r.urlPath.includes(":"));
4214
- if (pages.length > 0) {
4215
- lines.push("## Pages");
4216
- lines.push("");
4217
- for (const page of pages) {
4218
- const desc = config.pageDescriptions?.[page.urlPath];
4219
- const url = `${config.origin}${page.urlPath === "/" ? "" : page.urlPath}`;
4220
- if (desc) lines.push(`- [${page.urlPath}](${url}): ${desc}`);
4221
- else lines.push(`- [${page.urlPath}](${url})`);
4222
- }
4223
- lines.push("");
4224
- }
4225
- const dynamicRoutes = routes.filter((r) => !r.isLayout && !r.isError && !r.isLoading && !r.isNotFound && (r.urlPath.includes(":") || r.isCatchAll));
4226
- if (dynamicRoutes.length > 0) {
4227
- lines.push("## Dynamic Pages");
4228
- lines.push("");
4229
- for (const route of dynamicRoutes) {
4230
- const desc = config.pageDescriptions?.[route.urlPath];
4231
- if (desc) lines.push(`- ${route.urlPath}: ${desc}`);
4232
- else lines.push(`- ${route.urlPath}`);
4233
- }
4234
- lines.push("");
4235
- }
4236
- const apiPatterns = parseApiFiles(apiFiles);
4237
- if (apiPatterns.length > 0 || config.apiDescriptions) {
4238
- lines.push("## API Endpoints");
4239
- lines.push("");
4240
- if (config.apiDescriptions) for (const [endpoint, desc] of Object.entries(config.apiDescriptions)) lines.push(`- ${endpoint}: ${desc}`);
4241
- const describedPatterns = new Set(Object.keys(config.apiDescriptions ?? {}).map((k) => k.replace(/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+/, "")));
4242
- for (const pattern of apiPatterns) if (!describedPatterns.has(pattern)) lines.push(`- ${pattern}`);
4243
- lines.push("");
4244
- }
4245
- if (config.llmsExtra) {
4246
- lines.push(config.llmsExtra);
4247
- lines.push("");
4248
- }
4249
- return lines.join("\n");
4250
- }
4251
- /**
4252
- * Generate llms-full.txt — expanded version with more detail.
4253
- * Includes all route metadata and API descriptions.
4254
- *
4255
- * @internal Exported for testing.
4256
- */
4257
- function generateLlmsFullTxt(routeFiles, apiFiles, config) {
4258
- const lines = [];
4259
- lines.push(`# ${config.name} — Full Reference`);
4260
- lines.push(`> ${config.description}`);
4261
- lines.push("");
4262
- lines.push(`Base URL: ${config.origin}`);
4263
- lines.push("");
4264
- const pages = parseFileRoutes(routeFiles).filter((r) => !r.isLayout && !r.isError && !r.isLoading && !r.isNotFound);
4265
- if (pages.length > 0) {
4266
- lines.push("## All Routes");
4267
- lines.push("");
4268
- for (const page of pages) {
4269
- const desc = config.pageDescriptions?.[page.urlPath] ?? "";
4270
- const dynamic = page.urlPath.includes(":") ? " (dynamic)" : "";
4271
- const catchAll = page.isCatchAll ? " (catch-all)" : "";
4272
- lines.push(`### ${page.urlPath}${dynamic}${catchAll}`);
4273
- if (desc) lines.push(desc);
4274
- lines.push(`- File: ${page.filePath}`);
4275
- lines.push(`- Render mode: ${page.renderMode}`);
4276
- lines.push("");
4277
- }
4278
- }
4279
- if (config.apiDescriptions) {
4280
- lines.push("## API Reference");
4281
- lines.push("");
4282
- for (const [endpoint, desc] of Object.entries(config.apiDescriptions)) {
4283
- lines.push(`### ${endpoint}`);
4284
- lines.push(desc);
4285
- lines.push("");
4286
- }
4287
- }
4288
- if (config.llmsExtra) {
4289
- lines.push("## Additional Information");
4290
- lines.push("");
4291
- lines.push(config.llmsExtra);
4292
- lines.push("");
4293
- }
4294
- return lines.join("\n");
4295
- }
4296
- /**
4297
- * Auto-infer JSON-LD structured data from page metadata.
4298
- *
4299
- * Returns an array of JSON-LD objects (multiple schemas can apply to one page).
4300
- * For example, an article page gets both `Article` and `BreadcrumbList`.
4301
- *
4302
- * @example
4303
- * ```tsx
4304
- * const schemas = inferJsonLd({
4305
- * url: "https://example.com/blog/my-post",
4306
- * title: "My Post",
4307
- * description: "A great article",
4308
- * type: "article",
4309
- * author: "Vit Bokisch",
4310
- * publishedTime: "2026-03-31",
4311
- * })
4312
- * // → [Article schema, BreadcrumbList schema]
4313
- * ```
4314
- */
4315
- function inferJsonLd(options) {
4316
- const schemas = [];
4317
- if (options.type === "article") {
4318
- const article = {
4319
- "@context": "https://schema.org",
4320
- "@type": "Article",
4321
- headline: options.title,
4322
- url: options.url
4323
- };
4324
- if (options.description) article.description = options.description;
4325
- if (options.image) article.image = options.image;
4326
- if (options.publishedTime) article.datePublished = options.publishedTime;
4327
- if (options.author) article.author = {
4328
- "@type": "Person",
4329
- name: options.author
4330
- };
4331
- if (options.tags && options.tags.length > 0) article.keywords = options.tags.join(", ");
4332
- if (options.siteName) article.publisher = {
4333
- "@type": "Organization",
4334
- name: options.siteName
4335
- };
4336
- schemas.push(article);
4337
- } else if (options.type === "product") {
4338
- const product = {
4339
- "@context": "https://schema.org",
4340
- "@type": "Product",
4341
- name: options.title,
4342
- url: options.url
4343
- };
4344
- if (options.description) product.description = options.description;
4345
- if (options.image) product.image = options.image;
4346
- schemas.push(product);
4347
- } else {
4348
- const webpage = {
4349
- "@context": "https://schema.org",
4350
- "@type": "WebPage",
4351
- name: options.title,
4352
- url: options.url
4353
- };
4354
- if (options.description) webpage.description = options.description;
4355
- if (options.image) webpage.thumbnailUrl = options.image;
4356
- schemas.push(webpage);
4357
- }
4358
- if (options.breadcrumbs && options.breadcrumbs.length > 0) schemas.push({
4359
- "@context": "https://schema.org",
4360
- "@type": "BreadcrumbList",
4361
- itemListElement: options.breadcrumbs.map((bc, i) => ({
4362
- "@type": "ListItem",
4363
- position: i + 1,
4364
- name: bc.name,
4365
- item: bc.url
4366
- }))
4367
- });
4368
- else {
4369
- const urlObj = safeParseUrl(options.url);
4370
- if (urlObj) {
4371
- const segments = urlObj.pathname.split("/").filter(Boolean);
4372
- if (segments.length > 0) {
4373
- const items = [{
4374
- "@type": "ListItem",
4375
- position: 1,
4376
- name: "Home",
4377
- item: urlObj.origin
4378
- }];
4379
- let path = "";
4380
- for (let i = 0; i < segments.length; i++) {
4381
- path += `/${segments[i]}`;
4382
- items.push({
4383
- "@type": "ListItem",
4384
- position: i + 2,
4385
- name: capitalize(segments[i].replace(/-/g, " ")),
4386
- item: `${urlObj.origin}${path}`
4387
- });
4388
- }
4389
- schemas.push({
4390
- "@context": "https://schema.org",
4391
- "@type": "BreadcrumbList",
4392
- itemListElement: items
4393
- });
4394
- }
4395
- }
4396
- }
4397
- return schemas;
4398
- }
4399
- /**
4400
- * Generate an OpenAI-compatible AI plugin manifest.
4401
- *
4402
- * Follows the /.well-known/ai-plugin.json spec.
4403
- *
4404
- * @internal Exported for testing.
4405
- */
4406
- function generateAiPluginManifest(config) {
4407
- return {
4408
- schema_version: "v1",
4409
- name_for_human: config.name,
4410
- name_for_model: config.name.toLowerCase().replace(/\s+/g, "_").replace(/[^a-z0-9_]/g, ""),
4411
- description_for_human: config.description,
4412
- description_for_model: config.description,
4413
- auth: { type: "none" },
4414
- api: {
4415
- type: "openapi",
4416
- url: `${config.origin}/.well-known/openapi.yaml`
4417
- },
4418
- logo_url: config.logoUrl ?? `${config.origin}/favicon.svg`,
4419
- contact_email: config.contactEmail ?? "",
4420
- legal_info_url: config.legalUrl ?? `${config.origin}/legal`
4421
- };
4422
- }
4423
- /**
4424
- * Generate a minimal OpenAPI 3.0 spec from API route descriptions.
4425
- *
4426
- * @internal Exported for testing.
4427
- */
4428
- function generateOpenApiSpec(apiFiles, config) {
4429
- const paths = {};
4430
- if (config.apiDescriptions) for (const [endpoint, desc] of Object.entries(config.apiDescriptions)) {
4431
- const match = endpoint.match(/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+(.+)$/);
4432
- if (match) {
4433
- const method = match[1].toLowerCase();
4434
- const openApiPath = match[2].replace(/:(\w+)/g, "{$1}");
4435
- if (!paths[openApiPath]) paths[openApiPath] = {};
4436
- paths[openApiPath][method] = {
4437
- summary: desc,
4438
- responses: { "200": { description: "Success" } }
4439
- };
4440
- }
4441
- }
4442
- for (const pattern of parseApiFiles(apiFiles)) {
4443
- const openApiPath = pattern.replace(/:(\w+)/g, "{$1}");
4444
- if (!paths[openApiPath]) paths[openApiPath] = { get: {
4445
- summary: `${openApiPath} endpoint`,
4446
- responses: { "200": { description: "Success" } }
4447
- } };
4448
- }
4449
- return {
4450
- openapi: "3.0.0",
4451
- info: {
4452
- title: config.name,
4453
- description: config.description,
4454
- version: "1.0.0"
4455
- },
4456
- servers: [{ url: config.origin }],
4457
- paths
4458
- };
4459
- }
4460
- /**
4461
- * AI integration Vite plugin.
4462
- *
4463
- * Generates at build time:
4464
- * - `/llms.txt` — concise site summary for AI agents
4465
- * - `/llms-full.txt` — detailed reference for AI agents
4466
- * - `/.well-known/ai-plugin.json` — OpenAI plugin manifest
4467
- * - `/.well-known/openapi.yaml` — minimal OpenAPI spec from API routes
4468
- *
4469
- * In dev, serves these files via middleware.
4470
- *
4471
- * @example
4472
- * ```ts
4473
- * import { aiPlugin } from "@pyreon/zero/ai"
4474
- *
4475
- * export default {
4476
- * plugins: [
4477
- * aiPlugin({
4478
- * name: "My App",
4479
- * origin: "https://example.com",
4480
- * description: "A modern web application",
4481
- * apiDescriptions: {
4482
- * "GET /api/posts": "List blog posts",
4483
- * "GET /api/posts/:id": "Get post by ID",
4484
- * },
4485
- * }),
4486
- * ],
4487
- * }
4488
- * ```
4489
- */
4490
- function aiPlugin(config) {
4491
- let root = "";
4492
- let isBuild = false;
4493
- let routeFiles = [];
4494
- let apiFiles = [];
4495
- return {
4496
- name: "pyreon-zero-ai",
4497
- enforce: "post",
4498
- configResolved(resolvedConfig) {
4499
- root = resolvedConfig.root;
4500
- isBuild = resolvedConfig.command === "build";
4501
- },
4502
- async buildStart() {
4503
- try {
4504
- const { join } = await import("node:path");
4505
- const routesDir = join(root, config.routesDir ?? "src/routes");
4506
- const apiDir = join(root, config.apiDir ?? "src/api");
4507
- routeFiles = await scanDir(routesDir, routesDir);
4508
- apiFiles = await scanDir(apiDir, apiDir);
4509
- } catch {}
4510
- },
4511
- configureServer(server) {
4512
- server.middlewares.use(async (req, res, next) => {
4513
- const url = req.url ?? "";
4514
- if (url === "/llms.txt") {
4515
- res.setHeader("Content-Type", "text/plain; charset=utf-8");
4516
- res.end(generateLlmsTxt(routeFiles, apiFiles, config));
4517
- return;
4518
- }
4519
- if (url === "/llms-full.txt") {
4520
- res.setHeader("Content-Type", "text/plain; charset=utf-8");
4521
- res.end(generateLlmsFullTxt(routeFiles, apiFiles, config));
4522
- return;
4523
- }
4524
- if (url === "/.well-known/ai-plugin.json") {
4525
- res.setHeader("Content-Type", "application/json");
4526
- res.end(JSON.stringify(generateAiPluginManifest(config), null, 2));
4527
- return;
4528
- }
4529
- if (url === "/.well-known/openapi.yaml" || url === "/.well-known/openapi.json") {
4530
- res.setHeader("Content-Type", "application/json");
4531
- res.end(JSON.stringify(generateOpenApiSpec(apiFiles, config), null, 2));
4532
- return;
4533
- }
4534
- next();
4535
- });
4536
- },
4537
- async generateBundle() {
4538
- if (!isBuild) return;
4539
- this.emitFile({
4540
- type: "asset",
4541
- fileName: "llms.txt",
4542
- source: generateLlmsTxt(routeFiles, apiFiles, config)
4543
- });
4544
- this.emitFile({
4545
- type: "asset",
4546
- fileName: "llms-full.txt",
4547
- source: generateLlmsFullTxt(routeFiles, apiFiles, config)
4548
- });
4549
- this.emitFile({
4550
- type: "asset",
4551
- fileName: ".well-known/ai-plugin.json",
4552
- source: JSON.stringify(generateAiPluginManifest(config), null, 2)
4553
- });
4554
- this.emitFile({
4555
- type: "asset",
4556
- fileName: ".well-known/openapi.json",
4557
- source: JSON.stringify(generateOpenApiSpec(apiFiles, config), null, 2)
4558
- });
4559
- }
4560
- };
4561
- }
4562
- function parseApiFiles(files) {
4563
- return files.filter((f) => f.endsWith(".ts") || f.endsWith(".js")).map((f) => {
4564
- let path = f.replace(/\.\w+$/, "").replace(/\/index$/, "");
4565
- if (!path.startsWith("/")) path = `/${path}`;
4566
- path = path.replace(/\[\.\.\.(\w+)\]/g, ":$1*").replace(/\[(\w+)\]/g, ":$1");
4567
- return `/api${path === "/" ? "" : path}`;
4568
- });
4569
- }
4570
- async function scanDir(dir, base) {
4571
- const { readdir, stat } = await import("node:fs/promises");
4572
- const { join, relative } = await import("node:path");
4573
- try {
4574
- const entries = await readdir(dir);
4575
- const files = [];
4576
- for (const entry of entries) {
4577
- const full = join(dir, entry);
4578
- if ((await stat(full)).isDirectory()) files.push(...await scanDir(full, base));
4579
- else files.push(relative(base, full));
4580
- }
4581
- return files;
4582
- } catch {
4583
- return [];
4584
- }
4585
- }
4586
- function safeParseUrl(url) {
4587
- try {
4588
- return new URL(url);
4589
- } catch {
4590
- return null;
4591
- }
4592
- }
4593
- function capitalize(s) {
4594
- return s.charAt(0).toUpperCase() + s.slice(1);
4595
- }
4596
-
4597
- //#endregion
4598
- export { Image, Link, Meta, Script, ThemeToggle, aiPlugin, bool, buildCspHeader, buildLocalePath, buildMetaTags, bunAdapter, cacheMiddleware, cloudflareAdapter, compose, compressResponse, compressionMiddleware, corsMiddleware, createActionMiddleware, createApiMiddleware, createApp, createISRHandler, createLink, createLocaleContext, createServer, cspMiddleware, zeroPlugin as default, defineAction, defineConfig, detectLocaleFromHeader, extractLocaleFromPath, faviconLinks, faviconPlugin, filePathToUrlPath, fontPlugin, fontVariables, generateAiPluginManifest, generateApiRouteModule, generateLlmsFullTxt, generateLlmsTxt, generateMiddlewareModule, generateOpenApiSpec, generateRobots, generateRouteModule, generateSitemap, getContext, i18nRouting, imagePlugin, inferJsonLd, initTheme, isCompressible, jsonLd, loggerMiddleware, netlifyAdapter, nodeAdapter, num, ogImagePath, ogImagePlugin, oneOf, parseFileRoutes, prefetchRoute, publicEnv, rateLimitMiddleware, render404Page, resolveAdapter, resolveConfig, resolvedTheme, scanRouteFiles, schema, securityHeaders, seoMiddleware, seoPlugin, setLocale, setTheme, staticAdapter, str, theme, themeScript, toggleTheme, url, useLink, useLocale, useNonce, validateEnv, varyEncoding, vercelAdapter };
923
+ export { Image, Link, Meta, Script, ThemeToggle, buildLocalePath, buildMetaTags, createLink, extractLocaleFromPath, initTheme, prefetchRoute, resolvedTheme, setLocale, setSSRThemeDefault, setTheme, theme, themeScript, toggleTheme, useLink, useLocale };
4599
924
  //# sourceMappingURL=index.js.map