@teamvelix/velix 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2408 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __esm = (fn, res) => function __init() {
4
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
+ };
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+
11
+ // ../../node_modules/.pnpm/tsup@8.5.1_jiti@1.21.7_post_49c9ba138cf4e7dd637766b727229610/node_modules/tsup/assets/esm_shims.js
12
+ import path from "path";
13
+ import { fileURLToPath } from "url";
14
+ var init_esm_shims = __esm({
15
+ "../../node_modules/.pnpm/tsup@8.5.1_jiti@1.21.7_post_49c9ba138cf4e7dd637766b727229610/node_modules/tsup/assets/esm_shims.js"() {
16
+ "use strict";
17
+ }
18
+ });
19
+
20
+ // server/image-optimizer.ts
21
+ var image_optimizer_exports = {};
22
+ __export(image_optimizer_exports, {
23
+ handleImageOptimization: () => handleImageOptimization
24
+ });
25
+ import fs6 from "fs";
26
+ import path6 from "path";
27
+ async function handleImageOptimization(req, res, projectRoot) {
28
+ let sharp;
29
+ try {
30
+ sharp = await import("sharp").then((m) => m.default || m);
31
+ } catch (e) {
32
+ }
33
+ try {
34
+ const url = new URL(req.url, `http://${req.headers.host || "localhost"}`);
35
+ const imageUrl = url.searchParams.get("url");
36
+ const widthStr = url.searchParams.get("w");
37
+ const qualityStr = url.searchParams.get("q");
38
+ if (!imageUrl) {
39
+ res.writeHead(400);
40
+ res.end("Missing url parameter");
41
+ return;
42
+ }
43
+ const width = widthStr ? parseInt(widthStr, 10) : void 0;
44
+ const quality = qualityStr ? parseInt(qualityStr, 10) : 75;
45
+ let imageBuffer = null;
46
+ if (imageUrl.startsWith("http")) {
47
+ const response = await fetch(imageUrl);
48
+ if (!response.ok) throw new Error(`Failed to fetch ${imageUrl}`);
49
+ imageBuffer = Buffer.from(await response.arrayBuffer());
50
+ } else {
51
+ const publicDir = path6.join(projectRoot, "public");
52
+ const resolvedPath = path6.join(publicDir, imageUrl.startsWith("/") ? imageUrl.slice(1) : imageUrl);
53
+ if (!resolvedPath.startsWith(publicDir) || !fs6.existsSync(resolvedPath)) {
54
+ res.writeHead(404);
55
+ res.end("Image not found");
56
+ return;
57
+ }
58
+ imageBuffer = fs6.readFileSync(resolvedPath);
59
+ }
60
+ if (!sharp) {
61
+ res.writeHead(200, {
62
+ "Content-Type": "image/jpeg",
63
+ "Cache-Control": "public, max-age=31536000, immutable"
64
+ });
65
+ res.end(imageBuffer);
66
+ return;
67
+ }
68
+ let processor = sharp(imageBuffer);
69
+ if (width) {
70
+ processor = processor.resize(width);
71
+ }
72
+ processor = processor.webp({ quality });
73
+ const optimizedBuffer = await processor.toBuffer();
74
+ res.writeHead(200, {
75
+ "Content-Type": "image/webp",
76
+ "Cache-Control": "public, max-age=31536000, immutable"
77
+ });
78
+ res.end(optimizedBuffer);
79
+ } catch (error) {
80
+ console.error("Image optimization error:", error);
81
+ res.writeHead(500);
82
+ res.end("Error processing image");
83
+ }
84
+ }
85
+ var init_image_optimizer = __esm({
86
+ "server/image-optimizer.ts"() {
87
+ "use strict";
88
+ init_esm_shims();
89
+ }
90
+ });
91
+
92
+ // runtime/start-prod.ts
93
+ init_esm_shims();
94
+
95
+ // server/index.ts
96
+ init_esm_shims();
97
+ import http from "http";
98
+ import fs7 from "fs";
99
+ import path7 from "path";
100
+ import { fileURLToPath as fileURLToPath2, pathToFileURL as pathToFileURL3 } from "url";
101
+ import React2 from "react";
102
+ import { renderToString } from "react-dom/server";
103
+
104
+ // config.ts
105
+ init_esm_shims();
106
+ import fs from "fs";
107
+ import path2 from "path";
108
+ import { pathToFileURL } from "url";
109
+ import { z } from "zod";
110
+ import pc from "picocolors";
111
+ var AppConfigSchema = z.object({
112
+ name: z.string().default("Velix App"),
113
+ url: z.string().url().optional()
114
+ }).default({});
115
+ var ServerConfigSchema = z.object({
116
+ port: z.number().min(1).max(65535).default(3e3),
117
+ host: z.string().default("localhost")
118
+ }).default({});
119
+ var RoutingConfigSchema = z.object({
120
+ trailingSlash: z.boolean().default(false)
121
+ }).default({});
122
+ var SEOConfigSchema = z.object({
123
+ sitemap: z.boolean().default(true),
124
+ robots: z.boolean().default(true),
125
+ openGraph: z.boolean().default(true)
126
+ }).default({});
127
+ var BuildConfigSchema = z.object({
128
+ target: z.string().default("es2022"),
129
+ minify: z.boolean().default(true),
130
+ sourcemap: z.boolean().default(true),
131
+ splitting: z.boolean().default(true),
132
+ outDir: z.string().default(".velix")
133
+ }).default({});
134
+ var ExperimentalConfigSchema = z.object({
135
+ islands: z.boolean().default(true),
136
+ streaming: z.boolean().default(true)
137
+ }).default({});
138
+ var PluginSchema = z.union([
139
+ z.string(),
140
+ z.object({
141
+ name: z.string()
142
+ }).passthrough()
143
+ ]);
144
+ var VelixConfigSchema = z.object({
145
+ // App identity
146
+ app: AppConfigSchema,
147
+ // DevTools toggle
148
+ devtools: z.boolean().default(true),
149
+ // Server options
150
+ server: ServerConfigSchema,
151
+ // Routing options
152
+ routing: RoutingConfigSchema,
153
+ // SEO configuration
154
+ seo: SEOConfigSchema,
155
+ // Build options
156
+ build: BuildConfigSchema,
157
+ // Experimental features
158
+ experimental: ExperimentalConfigSchema,
159
+ // Plugins
160
+ plugins: z.array(PluginSchema).default([]),
161
+ // Directories (resolved automatically)
162
+ appDir: z.string().default("app"),
163
+ publicDir: z.string().default("public"),
164
+ // Stylesheets
165
+ styles: z.array(z.string()).default([]),
166
+ // Favicon
167
+ favicon: z.string().nullable().default(null)
168
+ });
169
+ var defaultConfig = VelixConfigSchema.parse({});
170
+ async function loadConfig(projectRoot) {
171
+ const configPathTs = path2.join(projectRoot, "velix.config.ts");
172
+ const configPathJs = path2.join(projectRoot, "velix.config.js");
173
+ const configPathLegacyTs = path2.join(projectRoot, "flexireact.config.ts");
174
+ const configPathLegacyJs = path2.join(projectRoot, "flexireact.config.js");
175
+ let configPath = null;
176
+ if (fs.existsSync(configPathTs)) configPath = configPathTs;
177
+ else if (fs.existsSync(configPathJs)) configPath = configPathJs;
178
+ else if (fs.existsSync(configPathLegacyTs)) configPath = configPathLegacyTs;
179
+ else if (fs.existsSync(configPathLegacyJs)) configPath = configPathLegacyJs;
180
+ let userConfig = {};
181
+ if (configPath) {
182
+ try {
183
+ const configUrl = pathToFileURL(configPath).href;
184
+ const module = await import(`${configUrl}?t=${Date.now()}`);
185
+ userConfig = module.default || module;
186
+ } catch (error) {
187
+ console.warn(pc.yellow(`\u26A0 Failed to load config: ${error.message}`));
188
+ }
189
+ }
190
+ const merged = deepMerge(defaultConfig, userConfig);
191
+ try {
192
+ return VelixConfigSchema.parse(merged);
193
+ } catch (err) {
194
+ if (err instanceof z.ZodError) {
195
+ console.error(pc.red("\u2716 Configuration validation failed:"));
196
+ for (const issue of err.issues) {
197
+ console.error(pc.dim(` - ${issue.path.join(".")}: ${issue.message}`));
198
+ }
199
+ process.exit(1);
200
+ }
201
+ throw err;
202
+ }
203
+ }
204
+ function resolvePaths(config, projectRoot) {
205
+ return {
206
+ ...config,
207
+ resolvedAppDir: path2.resolve(projectRoot, config.appDir),
208
+ resolvedPublicDir: path2.resolve(projectRoot, config.publicDir),
209
+ resolvedOutDir: path2.resolve(projectRoot, config.build.outDir)
210
+ };
211
+ }
212
+ function deepMerge(target, source) {
213
+ const result = { ...target };
214
+ for (const key in source) {
215
+ if (source[key] && typeof source[key] === "object" && !Array.isArray(source[key])) {
216
+ result[key] = deepMerge(target[key] || {}, source[key]);
217
+ } else {
218
+ result[key] = source[key];
219
+ }
220
+ }
221
+ return result;
222
+ }
223
+
224
+ // router/index.ts
225
+ init_esm_shims();
226
+ import fs3 from "fs";
227
+ import path3 from "path";
228
+
229
+ // utils.ts
230
+ init_esm_shims();
231
+ import fs2 from "fs";
232
+ function isServerComponent(filePath) {
233
+ try {
234
+ const content = fs2.readFileSync(filePath, "utf-8");
235
+ const firstLine = content.split("\n")[0].trim();
236
+ return firstLine === "'use server'" || firstLine === '"use server"';
237
+ } catch {
238
+ return false;
239
+ }
240
+ }
241
+ function isClientComponent(filePath) {
242
+ try {
243
+ const content = fs2.readFileSync(filePath, "utf-8");
244
+ const firstLine = content.split("\n")[0].trim();
245
+ return firstLine === "'use client'" || firstLine === '"use client"';
246
+ } catch {
247
+ return false;
248
+ }
249
+ }
250
+ function isIsland(filePath) {
251
+ try {
252
+ const content = fs2.readFileSync(filePath, "utf-8");
253
+ const firstLine = content.split("\n")[0].trim();
254
+ return firstLine === "'use island'" || firstLine === '"use island"';
255
+ } catch {
256
+ return false;
257
+ }
258
+ }
259
+
260
+ // router/index.ts
261
+ var RouteType = {
262
+ PAGE: "page",
263
+ API: "api",
264
+ LAYOUT: "layout",
265
+ LOADING: "loading",
266
+ ERROR: "error",
267
+ NOT_FOUND: "not-found"
268
+ };
269
+ function buildRouteTree(appDir) {
270
+ const projectRoot = path3.dirname(appDir);
271
+ const routes = {
272
+ pages: [],
273
+ api: [],
274
+ layouts: /* @__PURE__ */ new Map(),
275
+ tree: {},
276
+ appRoutes: []
277
+ };
278
+ if (fs3.existsSync(appDir)) {
279
+ scanAppDirectory(appDir, appDir, routes);
280
+ }
281
+ const serverApiDir = path3.join(projectRoot, "server", "api");
282
+ if (fs3.existsSync(serverApiDir)) {
283
+ scanApiDirectory(serverApiDir, serverApiDir, routes);
284
+ }
285
+ const rootLayoutTsx = path3.join(appDir, "layout.tsx");
286
+ const rootLayoutJsx = path3.join(appDir, "layout.jsx");
287
+ if (fs3.existsSync(rootLayoutTsx)) routes.rootLayout = rootLayoutTsx;
288
+ else if (fs3.existsSync(rootLayoutJsx)) routes.rootLayout = rootLayoutJsx;
289
+ routes.tree = buildTree(routes.appRoutes);
290
+ return routes;
291
+ }
292
+ function scanAppDirectory(baseDir, currentDir, routes, parentSegments = [], parentLayout = null, parentMiddleware = null) {
293
+ const entries = fs3.readdirSync(currentDir, { withFileTypes: true });
294
+ const specialFiles = {
295
+ page: null,
296
+ layout: null,
297
+ loading: null,
298
+ error: null,
299
+ notFound: null,
300
+ template: null,
301
+ middleware: null
302
+ };
303
+ for (const entry of entries) {
304
+ if (entry.isFile()) {
305
+ const name = entry.name.replace(/\.(jsx|js|tsx|ts)$/, "");
306
+ const fullPath = path3.join(currentDir, entry.name);
307
+ const ext = path3.extname(entry.name);
308
+ if (![".tsx", ".jsx", ".ts", ".js"].includes(ext)) continue;
309
+ if (name === "page") specialFiles.page = fullPath;
310
+ if (name === "layout") specialFiles.layout = fullPath;
311
+ if (name === "loading") specialFiles.loading = fullPath;
312
+ if (name === "error") specialFiles.error = fullPath;
313
+ if (name === "not-found") specialFiles.notFound = fullPath;
314
+ if (name === "template") specialFiles.template = fullPath;
315
+ if (name === "middleware" || name === "_middleware") specialFiles.middleware = fullPath;
316
+ if (name.startsWith("[") && name.endsWith("]") && [".tsx", ".jsx"].includes(ext)) {
317
+ const paramName = name.slice(1, -1);
318
+ let segmentName;
319
+ if (paramName.startsWith("...")) {
320
+ segmentName = "*" + paramName.slice(3);
321
+ } else {
322
+ segmentName = ":" + paramName;
323
+ }
324
+ const routePath = "/" + [...parentSegments, segmentName].join("/");
325
+ routes.appRoutes.push({
326
+ type: RouteType.PAGE,
327
+ path: routePath.replace(/\/+/g, "/"),
328
+ filePath: fullPath,
329
+ pattern: createRoutePattern(routePath),
330
+ segments: [...parentSegments, segmentName],
331
+ layout: specialFiles.layout || parentLayout,
332
+ loading: specialFiles.loading,
333
+ error: specialFiles.error,
334
+ notFound: specialFiles.notFound,
335
+ template: specialFiles.template,
336
+ middleware: specialFiles.middleware || parentMiddleware,
337
+ isServerComponent: isServerComponent(fullPath),
338
+ isClientComponent: isClientComponent(fullPath),
339
+ isIsland: isIsland(fullPath)
340
+ });
341
+ }
342
+ }
343
+ }
344
+ if (specialFiles.page) {
345
+ const routePath = "/" + parentSegments.join("/") || "/";
346
+ routes.appRoutes.push({
347
+ type: RouteType.PAGE,
348
+ path: routePath.replace(/\/+/g, "/") || "/",
349
+ filePath: specialFiles.page,
350
+ pattern: createRoutePattern(routePath || "/"),
351
+ segments: parentSegments,
352
+ layout: specialFiles.layout || parentLayout,
353
+ loading: specialFiles.loading,
354
+ error: specialFiles.error,
355
+ notFound: specialFiles.notFound,
356
+ template: specialFiles.template,
357
+ middleware: specialFiles.middleware || parentMiddleware,
358
+ isServerComponent: isServerComponent(specialFiles.page),
359
+ isClientComponent: isClientComponent(specialFiles.page),
360
+ isIsland: isIsland(specialFiles.page)
361
+ });
362
+ }
363
+ for (const entry of entries) {
364
+ if (entry.isDirectory()) {
365
+ const fullPath = path3.join(currentDir, entry.name);
366
+ if (entry.name.startsWith("_") || entry.name.startsWith(".")) continue;
367
+ const isGroup = entry.name.startsWith("(") && entry.name.endsWith(")");
368
+ let segmentName = entry.name;
369
+ if (entry.name.startsWith("[") && entry.name.endsWith("]")) {
370
+ segmentName = ":" + entry.name.slice(1, -1);
371
+ if (entry.name.startsWith("[...")) {
372
+ segmentName = "*" + entry.name.slice(4, -1);
373
+ }
374
+ if (entry.name.startsWith("[[...")) {
375
+ segmentName = "*" + entry.name.slice(5, -2);
376
+ }
377
+ }
378
+ const newSegments = isGroup ? parentSegments : [...parentSegments, segmentName];
379
+ const newLayout = specialFiles.layout || parentLayout;
380
+ const newMiddleware = specialFiles.middleware || parentMiddleware;
381
+ scanAppDirectory(baseDir, fullPath, routes, newSegments, newLayout, newMiddleware);
382
+ }
383
+ }
384
+ }
385
+ function scanApiDirectory(baseDir, currentDir, routes, parentSegments = []) {
386
+ const entries = fs3.readdirSync(currentDir, { withFileTypes: true });
387
+ for (const entry of entries) {
388
+ const fullPath = path3.join(currentDir, entry.name);
389
+ if (entry.isDirectory()) {
390
+ scanApiDirectory(baseDir, fullPath, routes, [...parentSegments, entry.name]);
391
+ } else if (entry.isFile()) {
392
+ const ext = path3.extname(entry.name);
393
+ if (![".ts", ".js"].includes(ext)) continue;
394
+ const baseName = path3.basename(entry.name, ext);
395
+ const apiSegments = baseName === "route" || baseName === "index" ? parentSegments : [...parentSegments, baseName];
396
+ const apiPath = "/api/" + apiSegments.join("/");
397
+ routes.api.push({
398
+ type: RouteType.API,
399
+ path: apiPath.replace(/\/+/g, "/") || "/api",
400
+ filePath: fullPath,
401
+ pattern: createRoutePattern(apiPath),
402
+ segments: ["api", ...apiSegments].filter(Boolean)
403
+ });
404
+ }
405
+ }
406
+ }
407
+ function createRoutePattern(routePath) {
408
+ let pattern = routePath.replace(/\*[^/]*/g, "(.*)").replace(/:[^/]+/g, "([^/]+)").replace(/\//g, "\\/");
409
+ return new RegExp(`^${pattern}$`);
410
+ }
411
+ function matchRoute(urlPath, routes) {
412
+ const normalizedPath = urlPath === "" ? "/" : urlPath.split("?")[0];
413
+ for (const route of routes) {
414
+ const match = normalizedPath.match(route.pattern);
415
+ if (match) {
416
+ const params = extractParams(route.path, match);
417
+ return { ...route, params };
418
+ }
419
+ }
420
+ return null;
421
+ }
422
+ function extractParams(routePath, match) {
423
+ const params = {};
424
+ const paramNames = [];
425
+ const paramRegex = /:([^/]+)|\*([^/]*)/g;
426
+ let paramMatch;
427
+ while ((paramMatch = paramRegex.exec(routePath)) !== null) {
428
+ paramNames.push(paramMatch[1] || paramMatch[2] || "splat");
429
+ }
430
+ paramNames.forEach((name, index) => {
431
+ params[name] = match[index + 1];
432
+ });
433
+ return params;
434
+ }
435
+ function buildTree(routes) {
436
+ const tree = { children: {}, routes: [] };
437
+ for (const route of routes) {
438
+ let current = tree;
439
+ for (const segment of route.segments) {
440
+ if (!current.children[segment]) {
441
+ current.children[segment] = { children: {}, routes: [] };
442
+ }
443
+ current = current.children[segment];
444
+ }
445
+ current.routes.push(route);
446
+ }
447
+ return tree;
448
+ }
449
+
450
+ // middleware/index.ts
451
+ init_esm_shims();
452
+ import fs4 from "fs";
453
+ import path4 from "path";
454
+ async function loadMiddleware(projectRoot) {
455
+ const middlewareDir = path4.join(projectRoot, "middleware");
456
+ const fns = [];
457
+ if (!fs4.existsSync(middlewareDir)) return fns;
458
+ const files = fs4.readdirSync(middlewareDir).filter((f) => /\.(ts|js)$/.test(f)).sort();
459
+ for (const file of files) {
460
+ try {
461
+ const filePath = path4.join(middlewareDir, file);
462
+ const { pathToFileURL: pathToFileURL4 } = await import("url");
463
+ const url = pathToFileURL4(filePath).href;
464
+ const mod = await import(`${url}?t=${Date.now()}`);
465
+ const fn = mod.default || mod.middleware;
466
+ if (typeof fn === "function") fns.push(fn);
467
+ } catch (err) {
468
+ console.warn(`\u26A0 Failed to load middleware ${file}: ${err.message}`);
469
+ }
470
+ }
471
+ return fns;
472
+ }
473
+ async function runMiddleware(req, res, fns) {
474
+ const result = { continue: true, rewritten: false };
475
+ if (fns.length === 0) return result;
476
+ const url = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`);
477
+ const cookies2 = {};
478
+ const cookieHeader = req.headers.cookie;
479
+ if (cookieHeader) {
480
+ cookieHeader.split(";").forEach((c2) => {
481
+ const [k, ...v] = c2.split("=");
482
+ if (k) cookies2[k.trim()] = v.join("=").trim();
483
+ });
484
+ }
485
+ const mReq = {
486
+ url: req.url || "/",
487
+ method: req.method || "GET",
488
+ headers: req.headers,
489
+ cookies: cookies2,
490
+ params: {},
491
+ query: Object.fromEntries(url.searchParams),
492
+ raw: req
493
+ };
494
+ let ended = false;
495
+ const mRes = {
496
+ _statusCode: 200,
497
+ _headers: {},
498
+ _redirectUrl: null,
499
+ _rewriteUrl: null,
500
+ _ended: false,
501
+ status(code) {
502
+ this._statusCode = code;
503
+ return this;
504
+ },
505
+ header(name, value) {
506
+ this._headers[name] = value;
507
+ return this;
508
+ },
509
+ json(data) {
510
+ this._headers["Content-Type"] = "application/json";
511
+ res.writeHead(this._statusCode, this._headers);
512
+ res.end(JSON.stringify(data));
513
+ this._ended = true;
514
+ ended = true;
515
+ },
516
+ redirect(url2, status = 307) {
517
+ this._redirectUrl = url2;
518
+ this._statusCode = status;
519
+ res.writeHead(status, { Location: url2, ...this._headers });
520
+ res.end();
521
+ this._ended = true;
522
+ ended = true;
523
+ },
524
+ rewrite(url2) {
525
+ this._rewriteUrl = url2;
526
+ req.url = url2;
527
+ result.rewritten = true;
528
+ },
529
+ async next() {
530
+ }
531
+ };
532
+ let index = 0;
533
+ const next = async () => {
534
+ if (ended || index >= fns.length) return;
535
+ const fn = fns[index++];
536
+ await fn(mReq, mRes, next);
537
+ };
538
+ await next();
539
+ if (!ended) {
540
+ for (const [key, value] of Object.entries(mRes._headers)) {
541
+ res.setHeader(key, value);
542
+ }
543
+ }
544
+ result.continue = !ended;
545
+ return result;
546
+ }
547
+
548
+ // plugins/index.ts
549
+ init_esm_shims();
550
+ import fs5 from "fs";
551
+ import path5 from "path";
552
+ import { pathToFileURL as pathToFileURL2 } from "url";
553
+ var PluginHooks = {
554
+ CONFIG: "config",
555
+ SERVER_START: "server:start",
556
+ REQUEST: "request",
557
+ RESPONSE: "response",
558
+ ROUTES_LOADED: "routes:loaded",
559
+ BEFORE_RENDER: "render:before",
560
+ AFTER_RENDER: "render:after",
561
+ BUILD_START: "build:start",
562
+ BUILD_END: "build:end"
563
+ };
564
+ var PluginManager = class {
565
+ plugins = [];
566
+ hooks = /* @__PURE__ */ new Map();
567
+ /**
568
+ * Register a plugin
569
+ */
570
+ register(plugin) {
571
+ this.plugins.push(plugin);
572
+ if (plugin.hooks) {
573
+ for (const [hookName, handler] of Object.entries(plugin.hooks)) {
574
+ if (handler) {
575
+ const existing = this.hooks.get(hookName) || [];
576
+ existing.push(handler);
577
+ this.hooks.set(hookName, existing);
578
+ }
579
+ }
580
+ }
581
+ }
582
+ /**
583
+ * Run a hook with arguments
584
+ */
585
+ async runHook(hookName, ...args) {
586
+ const handlers = this.hooks.get(hookName) || [];
587
+ for (const handler of handlers) {
588
+ await handler(...args);
589
+ }
590
+ }
591
+ /**
592
+ * Run a waterfall hook — each handler transforms the first argument
593
+ */
594
+ async runWaterfallHook(hookName, value, ...args) {
595
+ const handlers = this.hooks.get(hookName) || [];
596
+ let result = value;
597
+ for (const handler of handlers) {
598
+ const transformed = await handler(result, ...args);
599
+ if (transformed !== void 0) result = transformed;
600
+ }
601
+ return result;
602
+ }
603
+ /**
604
+ * Get all registered plugins
605
+ */
606
+ getPlugins() {
607
+ return [...this.plugins];
608
+ }
609
+ /**
610
+ * Check if a plugin is registered
611
+ */
612
+ hasPlugin(name) {
613
+ return this.plugins.some((p) => p.name === name);
614
+ }
615
+ };
616
+ var pluginManager = new PluginManager();
617
+ async function loadPlugins(projectRoot, config) {
618
+ const pluginEntries = config.plugins || [];
619
+ for (const entry of pluginEntries) {
620
+ try {
621
+ if (typeof entry === "string") {
622
+ const localPath = path5.join(projectRoot, "plugins", entry + ".ts");
623
+ const localPathJs = path5.join(projectRoot, "plugins", entry + ".js");
624
+ const localPathDir = path5.join(projectRoot, "plugins", entry, "index.ts");
625
+ let pluginPath = null;
626
+ if (fs5.existsSync(localPath)) pluginPath = localPath;
627
+ else if (fs5.existsSync(localPathJs)) pluginPath = localPathJs;
628
+ else if (fs5.existsSync(localPathDir)) pluginPath = localPathDir;
629
+ if (pluginPath) {
630
+ const url = pathToFileURL2(pluginPath).href;
631
+ const mod = await import(`${url}?t=${Date.now()}`);
632
+ const plugin = mod.default || mod;
633
+ if (plugin.name) {
634
+ pluginManager.register(plugin);
635
+ }
636
+ } else {
637
+ try {
638
+ const mod = await import(entry);
639
+ const plugin = mod.default || mod;
640
+ if (plugin.name) pluginManager.register(plugin);
641
+ } catch {
642
+ console.warn(`\u26A0 Plugin not found: ${entry}`);
643
+ }
644
+ }
645
+ } else if (typeof entry === "object" && entry.name) {
646
+ pluginManager.register(entry);
647
+ }
648
+ } catch (err) {
649
+ console.warn(`\u26A0 Failed to load plugin: ${err.message}`);
650
+ }
651
+ }
652
+ }
653
+ function definePlugin(definition) {
654
+ return definition;
655
+ }
656
+ var builtinPlugins = {
657
+ /**
658
+ * Security headers plugin
659
+ */
660
+ security: definePlugin({
661
+ name: "velix:security",
662
+ hooks: {
663
+ [PluginHooks.RESPONSE]: (_req, res) => {
664
+ if (!res.headersSent) {
665
+ res.setHeader("X-Content-Type-Options", "nosniff");
666
+ res.setHeader("X-Frame-Options", "DENY");
667
+ res.setHeader("X-XSS-Protection", "1; mode=block");
668
+ }
669
+ }
670
+ }
671
+ }),
672
+ /**
673
+ * Request logging plugin
674
+ */
675
+ logger: definePlugin({
676
+ name: "velix:logger",
677
+ hooks: {
678
+ [PluginHooks.RESPONSE]: (req, _res, duration) => {
679
+ console.log(` ${req.method} ${req.url} ${duration}ms`);
680
+ }
681
+ }
682
+ })
683
+ };
684
+
685
+ // plugins/tailwind.ts
686
+ init_esm_shims();
687
+
688
+ // logger.ts
689
+ init_esm_shims();
690
+ var colors = {
691
+ reset: "\x1B[0m",
692
+ bold: "\x1B[1m",
693
+ dim: "\x1B[2m",
694
+ red: "\x1B[31m",
695
+ green: "\x1B[32m",
696
+ yellow: "\x1B[33m",
697
+ blue: "\x1B[34m",
698
+ magenta: "\x1B[35m",
699
+ cyan: "\x1B[36m",
700
+ white: "\x1B[37m",
701
+ gray: "\x1B[90m"
702
+ };
703
+ var c = colors;
704
+ function getStatusColor(status) {
705
+ if (status >= 500) return c.red;
706
+ if (status >= 400) return c.yellow;
707
+ if (status >= 300) return c.cyan;
708
+ if (status >= 200) return c.green;
709
+ return c.white;
710
+ }
711
+ function fmtTime(ms) {
712
+ if (ms < 1) return `${c.gray}<1ms${c.reset}`;
713
+ if (ms < 100) return `${c.green}${ms}ms${c.reset}`;
714
+ if (ms < 500) return `${c.yellow}${ms}ms${c.reset}`;
715
+ return `${c.red}${ms}ms${c.reset}`;
716
+ }
717
+ var VERSION = "5.0.0";
718
+ var LOGO = `
719
+ ${c.cyan}\u25B2${c.reset} ${c.bold}Velix${c.reset} ${c.dim}v${VERSION}${c.reset}
720
+ `;
721
+ var logger = {
722
+ logo() {
723
+ console.log(LOGO);
724
+ console.log(`${c.dim} \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500${c.reset}`);
725
+ console.log("");
726
+ },
727
+ serverStart(config, startTime = Date.now()) {
728
+ const { port, host, mode, pagesDir } = config;
729
+ const elapsed = Date.now() - startTime;
730
+ console.log(LOGO);
731
+ console.log(` ${c.green}\u2714${c.reset} ${c.bold}Ready${c.reset} in ${elapsed}ms`);
732
+ console.log("");
733
+ console.log(` ${c.bold}Local:${c.reset} ${c.cyan}http://${host}:${port}${c.reset}`);
734
+ console.log(` ${c.bold}Mode:${c.reset} ${mode === "development" ? c.yellow : c.green}${mode}${c.reset}`);
735
+ if (pagesDir) console.log(` ${c.bold}App:${c.reset} ${c.dim}${pagesDir}${c.reset}`);
736
+ console.log("");
737
+ },
738
+ request(method, path8, status, time, extra = {}) {
739
+ const statusColor = getStatusColor(status);
740
+ const timeStr = fmtTime(time);
741
+ let badge = `${c.dim}\u25CB${c.reset}`;
742
+ if (extra.type === "dynamic" || extra.type === "ssr") badge = `${c.white}\u0192${c.reset}`;
743
+ else if (extra.type === "api") badge = `${c.cyan}\u03BB${c.reset}`;
744
+ const statusStr = `${statusColor}${status}${c.reset}`;
745
+ console.log(` ${badge} ${c.white}${method}${c.reset} ${path8} ${statusStr} ${c.dim}${timeStr}${c.reset}`);
746
+ },
747
+ info(msg) {
748
+ console.log(` ${c.cyan}\u2139${c.reset} ${msg}`);
749
+ },
750
+ success(msg) {
751
+ console.log(` ${c.green}\u2714${c.reset} ${msg}`);
752
+ },
753
+ warn(msg) {
754
+ console.log(` ${c.yellow}\u26A0${c.reset} ${c.yellow}${msg}${c.reset}`);
755
+ },
756
+ error(msg, err = null) {
757
+ console.log(` ${c.red}\u2716${c.reset} ${c.red}${msg}${c.reset}`);
758
+ if (err?.stack) {
759
+ console.log("");
760
+ console.log(`${c.dim}${err.stack.split("\n").slice(1, 4).join("\n")}${c.reset}`);
761
+ console.log("");
762
+ }
763
+ },
764
+ compile(file, time) {
765
+ console.log(` ${c.white}\u25CF${c.reset} Compiling ${c.dim}${file}${c.reset} ${c.dim}(${time}ms)${c.reset}`);
766
+ },
767
+ hmr(file) {
768
+ console.log(` ${c.green}\u21BB${c.reset} Fast Refresh ${c.dim}${file}${c.reset}`);
769
+ },
770
+ plugin(name) {
771
+ console.log(` ${c.cyan}\u25C6${c.reset} Plugin ${c.dim}${name}${c.reset}`);
772
+ },
773
+ route(path8, type) {
774
+ const typeLabel = type === "api" ? "\u03BB" : type === "dynamic" ? "\u0192" : "\u25CB";
775
+ const color = type === "api" ? c.cyan : type === "dynamic" ? c.white : c.dim;
776
+ console.log(` ${color}${typeLabel}${c.reset} ${path8}`);
777
+ },
778
+ divider() {
779
+ console.log(`${c.dim} \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500${c.reset}`);
780
+ },
781
+ blank() {
782
+ console.log("");
783
+ },
784
+ portInUse(port) {
785
+ this.error(`Port ${port} is already in use.`);
786
+ this.blank();
787
+ console.log(` ${c.dim}Try:${c.reset}`);
788
+ console.log(` 1. Kill the process on port ${port}`);
789
+ console.log(` 2. Use a different port via PORT env var`);
790
+ this.blank();
791
+ },
792
+ build(stats) {
793
+ this.blank();
794
+ console.log(` ${c.green}\u2714${c.reset} Build completed`);
795
+ this.blank();
796
+ console.log(` ${c.dim}Total time:${c.reset} ${c.white}${stats.time}ms${c.reset}`);
797
+ this.blank();
798
+ }
799
+ };
800
+ var logger_default = logger;
801
+
802
+ // metadata/index.ts
803
+ init_esm_shims();
804
+ function generateMetadataTags(metadata, baseUrl) {
805
+ const tags = [];
806
+ const base = baseUrl || metadata.metadataBase?.toString() || "";
807
+ if (metadata.title) {
808
+ const title = typeof metadata.title === "string" ? metadata.title : metadata.title.absolute || (metadata.title.template ? metadata.title.template.replace("%s", metadata.title.default) : metadata.title.default);
809
+ tags.push(`<title>${escapeHtml(title)}</title>`);
810
+ }
811
+ if (metadata.description) tags.push(`<meta name="description" content="${escapeHtml(metadata.description)}">`);
812
+ if (metadata.keywords) {
813
+ const kw = Array.isArray(metadata.keywords) ? metadata.keywords.join(", ") : metadata.keywords;
814
+ tags.push(`<meta name="keywords" content="${escapeHtml(kw)}">`);
815
+ }
816
+ if (metadata.authors) {
817
+ const authors = Array.isArray(metadata.authors) ? metadata.authors : [metadata.authors];
818
+ authors.forEach((a) => {
819
+ if (a.name) tags.push(`<meta name="author" content="${escapeHtml(a.name)}">`);
820
+ if (a.url) tags.push(`<link rel="author" href="${a.url}">`);
821
+ });
822
+ }
823
+ if (metadata.generator) tags.push(`<meta name="generator" content="${escapeHtml(metadata.generator)}">`);
824
+ if (metadata.applicationName) tags.push(`<meta name="application-name" content="${escapeHtml(metadata.applicationName)}">`);
825
+ if (metadata.referrer) tags.push(`<meta name="referrer" content="${metadata.referrer}">`);
826
+ if (metadata.robots) {
827
+ if (typeof metadata.robots === "string") {
828
+ tags.push(`<meta name="robots" content="${metadata.robots}">`);
829
+ } else {
830
+ tags.push(`<meta name="robots" content="${generateRobotsContent(metadata.robots)}">`);
831
+ if (metadata.robots.googleBot) {
832
+ const gbc = typeof metadata.robots.googleBot === "string" ? metadata.robots.googleBot : generateRobotsContent(metadata.robots.googleBot);
833
+ tags.push(`<meta name="googlebot" content="${gbc}">`);
834
+ }
835
+ }
836
+ }
837
+ if (metadata.viewport) {
838
+ const vc = typeof metadata.viewport === "string" ? metadata.viewport : generateViewportContent(metadata.viewport);
839
+ tags.push(`<meta name="viewport" content="${vc}">`);
840
+ }
841
+ if (metadata.themeColor) {
842
+ const tcs = Array.isArray(metadata.themeColor) ? metadata.themeColor : [metadata.themeColor];
843
+ tcs.forEach((tc) => {
844
+ const media = typeof tc !== "string" && tc.media ? ` media="${tc.media}"` : "";
845
+ const color = typeof tc === "string" ? tc : tc.color;
846
+ tags.push(`<meta name="theme-color" content="${color}"${media}>`);
847
+ });
848
+ }
849
+ if (metadata.colorScheme) tags.push(`<meta name="color-scheme" content="${metadata.colorScheme}">`);
850
+ if (metadata.icons) {
851
+ const addIcon = (icon, defaultRel) => {
852
+ const rel = icon.rel || defaultRel;
853
+ const attrs = [
854
+ icon.type ? ` type="${icon.type}"` : "",
855
+ icon.sizes ? ` sizes="${icon.sizes}"` : "",
856
+ icon.color ? ` color="${icon.color}"` : ""
857
+ ].join("");
858
+ tags.push(`<link rel="${rel}" href="${resolveUrl(icon.url, base)}"${attrs}>`);
859
+ };
860
+ if (metadata.icons.icon) {
861
+ (Array.isArray(metadata.icons.icon) ? metadata.icons.icon : [metadata.icons.icon]).forEach((i) => addIcon(i, "icon"));
862
+ }
863
+ if (metadata.icons.apple) {
864
+ (Array.isArray(metadata.icons.apple) ? metadata.icons.apple : [metadata.icons.apple]).forEach((i) => addIcon(i, "apple-touch-icon"));
865
+ }
866
+ }
867
+ if (metadata.manifest) tags.push(`<link rel="manifest" href="${resolveUrl(metadata.manifest, base)}">`);
868
+ if (metadata.openGraph) {
869
+ const og = metadata.openGraph;
870
+ if (og.type) tags.push(`<meta property="og:type" content="${og.type}">`);
871
+ if (og.title) tags.push(`<meta property="og:title" content="${escapeHtml(og.title)}">`);
872
+ if (og.description) tags.push(`<meta property="og:description" content="${escapeHtml(og.description)}">`);
873
+ if (og.url) tags.push(`<meta property="og:url" content="${resolveUrl(og.url, base)}">`);
874
+ if (og.siteName) tags.push(`<meta property="og:site_name" content="${escapeHtml(og.siteName)}">`);
875
+ if (og.locale) tags.push(`<meta property="og:locale" content="${og.locale}">`);
876
+ if (og.images) {
877
+ (Array.isArray(og.images) ? og.images : [og.images]).forEach((img) => {
878
+ tags.push(`<meta property="og:image" content="${resolveUrl(img.url, base)}">`);
879
+ if (img.width) tags.push(`<meta property="og:image:width" content="${img.width}">`);
880
+ if (img.height) tags.push(`<meta property="og:image:height" content="${img.height}">`);
881
+ if (img.alt) tags.push(`<meta property="og:image:alt" content="${escapeHtml(img.alt)}">`);
882
+ });
883
+ }
884
+ if (og.type === "article") {
885
+ if (og.publishedTime) tags.push(`<meta property="article:published_time" content="${og.publishedTime}">`);
886
+ if (og.modifiedTime) tags.push(`<meta property="article:modified_time" content="${og.modifiedTime}">`);
887
+ if (og.tags) og.tags.forEach((t) => tags.push(`<meta property="article:tag" content="${escapeHtml(t)}">`));
888
+ }
889
+ }
890
+ if (metadata.twitter) {
891
+ const tw = metadata.twitter;
892
+ if (tw.card) tags.push(`<meta name="twitter:card" content="${tw.card}">`);
893
+ if (tw.site) tags.push(`<meta name="twitter:site" content="${tw.site}">`);
894
+ if (tw.creator) tags.push(`<meta name="twitter:creator" content="${tw.creator}">`);
895
+ if (tw.title) tags.push(`<meta name="twitter:title" content="${escapeHtml(tw.title)}">`);
896
+ if (tw.description) tags.push(`<meta name="twitter:description" content="${escapeHtml(tw.description)}">`);
897
+ if (tw.images) {
898
+ (Array.isArray(tw.images) ? tw.images : [tw.images]).forEach((img) => {
899
+ const url = typeof img === "string" ? img : img.url;
900
+ tags.push(`<meta name="twitter:image" content="${resolveUrl(url, base)}">`);
901
+ });
902
+ }
903
+ }
904
+ if (metadata.verification) {
905
+ if (metadata.verification.google) {
906
+ (Array.isArray(metadata.verification.google) ? metadata.verification.google : [metadata.verification.google]).forEach((v) => tags.push(`<meta name="google-site-verification" content="${v}">`));
907
+ }
908
+ }
909
+ if (metadata.alternates) {
910
+ if (metadata.alternates.canonical) tags.push(`<link rel="canonical" href="${resolveUrl(metadata.alternates.canonical, base)}">`);
911
+ if (metadata.alternates.languages) {
912
+ Object.entries(metadata.alternates.languages).forEach(([lang, url]) => {
913
+ tags.push(`<link rel="alternate" hreflang="${lang}" href="${resolveUrl(url, base)}">`);
914
+ });
915
+ }
916
+ }
917
+ return tags.join("\n ");
918
+ }
919
+ function generateSitemap(routes, baseUrl) {
920
+ const urls = routes.filter((r) => r.type === "page" && !r.path.includes(":") && !r.path.includes("*")).map((r) => {
921
+ const loc = `${baseUrl.replace(/\/$/, "")}${r.path}`;
922
+ return ` <url>
923
+ <loc>${loc}</loc>
924
+ <lastmod>${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}</lastmod>
925
+ <changefreq>weekly</changefreq>
926
+ <priority>${r.path === "/" ? "1.0" : "0.8"}</priority>
927
+ </url>`;
928
+ });
929
+ return `<?xml version="1.0" encoding="UTF-8"?>
930
+ <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
931
+ ${urls.join("\n")}
932
+ </urlset>`;
933
+ }
934
+ function generateRobotsTxt(baseUrl, options = {}) {
935
+ const lines = ["User-agent: *"];
936
+ if (options.allow) options.allow.forEach((p) => lines.push(`Allow: ${p}`));
937
+ if (options.disallow) options.disallow.forEach((p) => lines.push(`Disallow: ${p}`));
938
+ else lines.push("Allow: /");
939
+ lines.push("", `Sitemap: ${baseUrl.replace(/\/$/, "")}/sitemap.xml`);
940
+ return lines.join("\n");
941
+ }
942
+ function escapeHtml(str) {
943
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
944
+ }
945
+ function resolveUrl(url, base) {
946
+ if (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("//")) return url;
947
+ return base ? `${base.replace(/\/$/, "")}${url.startsWith("/") ? "" : "/"}${url}` : url;
948
+ }
949
+ function generateRobotsContent(robots) {
950
+ const parts = [];
951
+ if (robots.index !== void 0) parts.push(robots.index ? "index" : "noindex");
952
+ if (robots.follow !== void 0) parts.push(robots.follow ? "follow" : "nofollow");
953
+ if (robots.noarchive) parts.push("noarchive");
954
+ if (robots.nosnippet) parts.push("nosnippet");
955
+ if (robots.noimageindex) parts.push("noimageindex");
956
+ return parts.join(", ") || "index, follow";
957
+ }
958
+ function generateViewportContent(viewport) {
959
+ const parts = [];
960
+ if (viewport.width) parts.push(`width=${viewport.width}`);
961
+ if (viewport.height) parts.push(`height=${viewport.height}`);
962
+ if (viewport.initialScale !== void 0) parts.push(`initial-scale=${viewport.initialScale}`);
963
+ if (viewport.maximumScale !== void 0) parts.push(`maximum-scale=${viewport.maximumScale}`);
964
+ if (viewport.userScalable !== void 0) parts.push(`user-scalable=${viewport.userScalable ? "yes" : "no"}`);
965
+ return parts.join(", ") || "width=device-width, initial-scale=1";
966
+ }
967
+
968
+ // islands/index.ts
969
+ init_esm_shims();
970
+ import React from "react";
971
+ var islandRegistry = /* @__PURE__ */ new Map();
972
+ function getRegisteredIslands() {
973
+ const islands = Array.from(islandRegistry.values());
974
+ islandRegistry.clear();
975
+ return islands;
976
+ }
977
+ var LoadStrategy = {
978
+ IMMEDIATE: "immediate",
979
+ VISIBLE: "visible",
980
+ IDLE: "idle",
981
+ MEDIA: "media"
982
+ };
983
+ function generateAdvancedHydrationScript(islands) {
984
+ if (!islands.length) return "";
985
+ const islandData = islands.map((island) => ({
986
+ id: island.id,
987
+ name: island.name,
988
+ path: island.clientPath,
989
+ props: island.props,
990
+ strategy: island.strategy || LoadStrategy.IMMEDIATE,
991
+ media: island.media
992
+ }));
993
+ return `
994
+ <script type="module">
995
+ const islands = ${JSON.stringify(islandData)};
996
+
997
+ async function hydrateIsland(island) {
998
+ const el = document.querySelector(\`[data-island="\${island.id}"]\`);
999
+ if (!el || el.hasAttribute('data-hydrated')) return;
1000
+
1001
+ try {
1002
+ const { hydrateRoot } = await import('/__velix/react-dom-client.js');
1003
+ const React = await import('/__velix/react.js');
1004
+ const mod = await import(island.path);
1005
+ hydrateRoot(el, React.createElement(mod.default, island.props));
1006
+ el.setAttribute('data-hydrated', 'true');
1007
+ } catch (error) {
1008
+ console.error(\`Failed to hydrate island \${island.name}:\`, error);
1009
+ }
1010
+ }
1011
+
1012
+ const visibleObserver = new IntersectionObserver((entries) => {
1013
+ entries.forEach(entry => {
1014
+ if (entry.isIntersecting) {
1015
+ const id = entry.target.getAttribute('data-island');
1016
+ const island = islands.find(i => i.id === id);
1017
+ if (island) { hydrateIsland(island); visibleObserver.unobserve(entry.target); }
1018
+ }
1019
+ });
1020
+ }, { rootMargin: '50px' });
1021
+
1022
+ function processIslands() {
1023
+ for (const island of islands) {
1024
+ const el = document.querySelector(\`[data-island="\${island.id}"]\`);
1025
+ if (!el) continue;
1026
+ switch (island.strategy) {
1027
+ case 'immediate': hydrateIsland(island); break;
1028
+ case 'visible': visibleObserver.observe(el); break;
1029
+ case 'idle': requestIdleCallback(() => hydrateIsland(island)); break;
1030
+ case 'media':
1031
+ if (island.media && window.matchMedia(island.media).matches) hydrateIsland(island);
1032
+ break;
1033
+ }
1034
+ }
1035
+ }
1036
+
1037
+ if (document.readyState === 'loading') {
1038
+ document.addEventListener('DOMContentLoaded', processIslands);
1039
+ } else {
1040
+ processIslands();
1041
+ }
1042
+ </script>`;
1043
+ }
1044
+
1045
+ // actions/index.ts
1046
+ init_esm_shims();
1047
+ import { useActionState, useOptimistic } from "react";
1048
+ import { useFormStatus } from "react-dom";
1049
+
1050
+ // helpers.ts
1051
+ init_esm_shims();
1052
+ var RedirectError = class extends Error {
1053
+ url;
1054
+ statusCode;
1055
+ type = "redirect";
1056
+ constructor(url, statusCode = 307) {
1057
+ super(`Redirect to ${url}`);
1058
+ this.name = "RedirectError";
1059
+ this.url = url;
1060
+ this.statusCode = statusCode;
1061
+ }
1062
+ };
1063
+ var NotFoundError = class extends Error {
1064
+ type = "notFound";
1065
+ constructor(message = "Page not found") {
1066
+ super(message);
1067
+ this.name = "NotFoundError";
1068
+ }
1069
+ };
1070
+ function redirect(url, type = "replace") {
1071
+ const statusCode = type === "permanent" ? 308 : 307;
1072
+ throw new RedirectError(url, statusCode);
1073
+ }
1074
+ function notFound(message) {
1075
+ throw new NotFoundError(message);
1076
+ }
1077
+ var cookies = {
1078
+ parse(cookieHeader) {
1079
+ const cookies2 = {};
1080
+ if (!cookieHeader) return cookies2;
1081
+ cookieHeader.split(";").forEach((cookie) => {
1082
+ const [name, ...rest] = cookie.split("=");
1083
+ if (name) {
1084
+ cookies2[name.trim()] = decodeURIComponent(rest.join("=").trim());
1085
+ }
1086
+ });
1087
+ return cookies2;
1088
+ },
1089
+ get(request, name) {
1090
+ const cookieHeader = request.headers.get("cookie") || "";
1091
+ return this.parse(cookieHeader)[name];
1092
+ },
1093
+ getAll(request) {
1094
+ const cookieHeader = request.headers.get("cookie") || "";
1095
+ return this.parse(cookieHeader);
1096
+ },
1097
+ serialize(name, value, options = {}) {
1098
+ let cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
1099
+ if (options.maxAge !== void 0) cookie += `; Max-Age=${options.maxAge}`;
1100
+ if (options.expires) cookie += `; Expires=${options.expires.toUTCString()}`;
1101
+ if (options.path) cookie += `; Path=${options.path}`;
1102
+ if (options.domain) cookie += `; Domain=${options.domain}`;
1103
+ if (options.secure) cookie += "; Secure";
1104
+ if (options.httpOnly) cookie += "; HttpOnly";
1105
+ if (options.sameSite) {
1106
+ cookie += `; SameSite=${options.sameSite.charAt(0).toUpperCase() + options.sameSite.slice(1)}`;
1107
+ }
1108
+ return cookie;
1109
+ },
1110
+ set(name, value, options = {}) {
1111
+ return this.serialize(name, value, {
1112
+ path: "/",
1113
+ httpOnly: true,
1114
+ secure: process.env.NODE_ENV === "production",
1115
+ sameSite: "lax",
1116
+ ...options
1117
+ });
1118
+ },
1119
+ delete(name, options = {}) {
1120
+ return this.serialize(name, "", { ...options, path: "/", maxAge: 0 });
1121
+ }
1122
+ };
1123
+ var headers = {
1124
+ create(init) {
1125
+ return new Headers(init);
1126
+ },
1127
+ get(request, name) {
1128
+ return request.headers.get(name);
1129
+ },
1130
+ getAll(request) {
1131
+ const result = {};
1132
+ request.headers.forEach((value, key) => {
1133
+ result[key] = value;
1134
+ });
1135
+ return result;
1136
+ },
1137
+ has(request, name) {
1138
+ return request.headers.has(name);
1139
+ },
1140
+ contentType(request) {
1141
+ return request.headers.get("content-type");
1142
+ },
1143
+ acceptsJson(request) {
1144
+ const accept = request.headers.get("accept") || "";
1145
+ return accept.includes("application/json") || accept.includes("*/*");
1146
+ },
1147
+ isAjax(request) {
1148
+ return request.headers.get("x-requested-with") === "XMLHttpRequest" || this.acceptsJson(request);
1149
+ },
1150
+ authorization(request) {
1151
+ const auth = request.headers.get("authorization");
1152
+ if (!auth) return null;
1153
+ const [type, ...rest] = auth.split(" ");
1154
+ return { type: type.toLowerCase(), credentials: rest.join(" ") };
1155
+ },
1156
+ bearerToken(request) {
1157
+ const auth = this.authorization(request);
1158
+ return auth?.type === "bearer" ? auth.credentials : null;
1159
+ },
1160
+ security() {
1161
+ return {
1162
+ "X-Content-Type-Options": "nosniff",
1163
+ "X-Frame-Options": "DENY",
1164
+ "X-XSS-Protection": "1; mode=block",
1165
+ "Referrer-Policy": "strict-origin-when-cross-origin",
1166
+ "Permissions-Policy": "camera=(), microphone=(), geolocation=()"
1167
+ };
1168
+ },
1169
+ cors(options = {}) {
1170
+ const {
1171
+ origin = "*",
1172
+ methods = ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
1173
+ headers: allowHeaders = ["Content-Type", "Authorization"],
1174
+ credentials = false,
1175
+ maxAge = 86400
1176
+ } = options;
1177
+ const corsHeaders = {
1178
+ "Access-Control-Allow-Origin": origin,
1179
+ "Access-Control-Allow-Methods": methods.join(", "),
1180
+ "Access-Control-Allow-Headers": allowHeaders.join(", "),
1181
+ "Access-Control-Max-Age": String(maxAge)
1182
+ };
1183
+ if (credentials) corsHeaders["Access-Control-Allow-Credentials"] = "true";
1184
+ return corsHeaders;
1185
+ },
1186
+ cache(options = {}) {
1187
+ if (options.noStore) {
1188
+ return { "Cache-Control": "no-store, no-cache, must-revalidate" };
1189
+ }
1190
+ const directives = [];
1191
+ directives.push(options.private ? "private" : "public");
1192
+ if (options.maxAge !== void 0) directives.push(`max-age=${options.maxAge}`);
1193
+ if (options.sMaxAge !== void 0) directives.push(`s-maxage=${options.sMaxAge}`);
1194
+ if (options.staleWhileRevalidate !== void 0) directives.push(`stale-while-revalidate=${options.staleWhileRevalidate}`);
1195
+ return { "Cache-Control": directives.join(", ") };
1196
+ }
1197
+ };
1198
+
1199
+ // actions/index.ts
1200
+ import { useActionState as useActionStateReact } from "react";
1201
+ globalThis.__VELIX_ACTIONS__ = globalThis.__VELIX_ACTIONS__ || {};
1202
+ globalThis.__VELIX_ACTION_CONTEXT__ = null;
1203
+ async function executeAction(actionId, args, context) {
1204
+ const action = globalThis.__VELIX_ACTIONS__[actionId];
1205
+ if (!action) return { success: false, error: `Server action not found: ${actionId}` };
1206
+ const actionContext = {
1207
+ request: context?.request || new Request("http://localhost"),
1208
+ cookies,
1209
+ headers,
1210
+ redirect,
1211
+ notFound
1212
+ };
1213
+ globalThis.__VELIX_ACTION_CONTEXT__ = actionContext;
1214
+ try {
1215
+ const result = await action(...args);
1216
+ return { success: true, data: result };
1217
+ } catch (error) {
1218
+ if (error instanceof RedirectError) return { success: true, redirect: error.url };
1219
+ if (error instanceof NotFoundError) return { success: false, error: "Not found" };
1220
+ return { success: false, error: error.message || "Action failed" };
1221
+ } finally {
1222
+ globalThis.__VELIX_ACTION_CONTEXT__ = null;
1223
+ }
1224
+ }
1225
+ var ALLOWED_TYPES = /* @__PURE__ */ new Set(["FormData", "Date", "File"]);
1226
+ var MAX_DEPTH = 10;
1227
+ function validateInput(obj, depth = 0) {
1228
+ if (depth > MAX_DEPTH) throw new Error("Payload too deeply nested");
1229
+ if (obj === null || obj === void 0 || typeof obj !== "object") return true;
1230
+ if ("__proto__" in obj || "constructor" in obj || "prototype" in obj) {
1231
+ throw new Error("Invalid payload: prototype pollution attempt detected");
1232
+ }
1233
+ if ("$$type" in obj && !ALLOWED_TYPES.has(obj.$$type)) {
1234
+ throw new Error(`Invalid serialized type: ${obj.$$type}`);
1235
+ }
1236
+ if (Array.isArray(obj)) obj.forEach((item) => validateInput(item, depth + 1));
1237
+ else Object.values(obj).forEach((val) => validateInput(val, depth + 1));
1238
+ return true;
1239
+ }
1240
+ function deserializeArgs(args) {
1241
+ validateInput(args);
1242
+ return args.map((arg) => {
1243
+ if (arg && typeof arg === "object") {
1244
+ if (arg.$$type === "FormData") {
1245
+ const fd = new FormData();
1246
+ for (const [key, value] of Object.entries(arg.data || {})) {
1247
+ if (typeof key !== "string" || key.startsWith("__")) continue;
1248
+ if (Array.isArray(value)) value.forEach((v) => {
1249
+ if (typeof v === "string" || typeof v === "number") fd.append(key, String(v));
1250
+ });
1251
+ else if (typeof value === "string" || typeof value === "number") fd.append(key, String(value));
1252
+ }
1253
+ return fd;
1254
+ }
1255
+ if (arg.$$type === "Date") {
1256
+ const d = new Date(arg.value);
1257
+ if (isNaN(d.getTime())) throw new Error("Invalid date");
1258
+ return d;
1259
+ }
1260
+ if (arg.$$type === "File") return { name: String(arg.name || ""), type: String(arg.type || ""), size: Number(arg.size || 0) };
1261
+ }
1262
+ return arg;
1263
+ });
1264
+ }
1265
+
1266
+ // server/index.ts
1267
+ import esbuild from "esbuild";
1268
+
1269
+ // server/devtools.ts
1270
+ init_esm_shims();
1271
+ function generateDevToolsHtml(isDev) {
1272
+ if (!isDev) return "";
1273
+ return `<style>
1274
+ @keyframes velix-pulse {
1275
+ 0% { transform: scale(1); box-shadow: 0 0 0 0 rgba(34, 211, 238, 0.7); }
1276
+ 70% { transform: scale(1.05); box-shadow: 0 0 0 10px rgba(34, 211, 238, 0); }
1277
+ 100% { transform: scale(1); box-shadow: 0 0 0 0 rgba(34, 211, 238, 0); }
1278
+ }
1279
+
1280
+ @keyframes velix-spin {
1281
+ from { transform: rotate(0deg); }
1282
+ to { transform: rotate(360deg); }
1283
+ }
1284
+
1285
+ .velix-idle { background: #0f172a !important; border: 2px solid #22D3EE !important; }
1286
+ .velix-rendering { background: #ea580c !important; border: 2px solid #fb923c !important; animation: velix-pulse 1.5s infinite !important; }
1287
+ .velix-compiling { background: #16a34a !important; border: 2px solid #4ade80 !important; animation: velix-spin 2s linear infinite !important; }
1288
+ .velix-navigating { background: #2563eb !important; border: 2px solid #60a5fa !important; animation: velix-pulse 1s infinite !important; }
1289
+ .velix-error { background: #dc2626 !important; border: 2px solid #f87171 !important; animation: velix-pulse 0.8s infinite !important; }
1290
+
1291
+ .velix-status-badge {
1292
+ position: absolute;
1293
+ top: -4px;
1294
+ right: -4px;
1295
+ width: 12px;
1296
+ height: 12px;
1297
+ border-radius: 50%;
1298
+ border: 2px solid #0f172a;
1299
+ }
1300
+
1301
+ .velix-status-idle { background: #22D3EE; }
1302
+ .velix-status-rendering { background: #fb923c; }
1303
+ .velix-status-compiling { background: #4ade80; }
1304
+ .velix-status-navigating { background: #60a5fa; }
1305
+ .velix-status-error { background: #f87171; }
1306
+ </style>
1307
+
1308
+ <script>
1309
+ // DevTools State Management
1310
+ window.__VELIX_DEV_TOOLS__ = {
1311
+ status: 'idle',
1312
+ setStatus: function(newStatus) {
1313
+ this.status = newStatus;
1314
+ const widget = document.getElementById('__velix-dev-tools');
1315
+ const badge = document.getElementById('__velix-status-badge');
1316
+ const statusText = document.getElementById('__velix-status-text');
1317
+
1318
+ if (widget) {
1319
+ widget.className = 'velix-' + newStatus;
1320
+ }
1321
+
1322
+ if (badge) {
1323
+ badge.className = 'velix-status-badge velix-status-' + newStatus;
1324
+ }
1325
+
1326
+ if (statusText) {
1327
+ const statusLabels = {
1328
+ idle: 'Ready',
1329
+ rendering: 'Rendering',
1330
+ compiling: 'Compiling',
1331
+ navigating: 'Navigating',
1332
+ error: 'Error'
1333
+ };
1334
+ statusText.textContent = statusLabels[newStatus] || 'Unknown';
1335
+ statusText.style.color = {
1336
+ idle: '#22D3EE',
1337
+ rendering: '#fb923c',
1338
+ compiling: '#4ade80',
1339
+ navigating: '#60a5fa',
1340
+ error: '#f87171'
1341
+ }[newStatus] || '#94a3b8';
1342
+ }
1343
+ }
1344
+ };
1345
+
1346
+ // HMR Connection
1347
+ const es = new EventSource('/__velix/hmr');
1348
+ es.onmessage = (e) => {
1349
+ const data = e.data;
1350
+
1351
+ if (data === 'reload') {
1352
+ window.__VELIX_DEV_TOOLS__.setStatus('idle');
1353
+ setTimeout(() => location.reload(), 100);
1354
+ }
1355
+
1356
+ if (data === 'building') {
1357
+ window.__VELIX_DEV_TOOLS__.setStatus('compiling');
1358
+ }
1359
+
1360
+ if (data === 'built') {
1361
+ window.__VELIX_DEV_TOOLS__.setStatus('idle');
1362
+ }
1363
+
1364
+ if (data.startsWith('rendering:')) {
1365
+ window.__VELIX_DEV_TOOLS__.setStatus('rendering');
1366
+ setTimeout(() => window.__VELIX_DEV_TOOLS__.setStatus('idle'), 1000);
1367
+ }
1368
+
1369
+ if (data.startsWith('error:')) {
1370
+ window.__VELIX_DEV_TOOLS__.setStatus('error');
1371
+ }
1372
+ };
1373
+
1374
+ es.onerror = () => {
1375
+ window.__VELIX_DEV_TOOLS__.setStatus('error');
1376
+ };
1377
+ </script>
1378
+
1379
+ <div id="__velix-dev-tools" class="velix-idle" style="position:fixed;bottom:16px;left:16px;z-index:9999;border-radius:50%;padding:4px;box-shadow:0 4px 12px rgba(0,0,0,0.5);display:flex;align-items:center;justify-content:center;width:40px;height:40px;cursor:pointer;transition:all 0.3s ease;" onmouseover="this.style.transform='scale(1.1)'" onmouseout="this.style.transform='scale(1)'" onclick="document.getElementById('__velix-dev-panel').style.display='block'" title="Velix DevTools">
1380
+ <img src="/__velix/logo.webp" alt="Velix DevTools" style="width:22px;height:22px;" />
1381
+ <div id="__velix-status-badge" class="velix-status-badge velix-status-idle"></div>
1382
+ </div>
1383
+
1384
+ <div id="__velix-dev-panel" style="display:none;position:fixed;bottom:70px;left:16px;width:320px;background:#0f172a;color:white;border-radius:16px;padding:20px;font-family:ui-sans-serif,system-ui,-apple-system,sans-serif;box-shadow:0 20px 50px rgba(0,0,0,0.4);z-index:10000;border:1px solid #1e293b;">
1385
+ <div style="display:flex;justify-content:space-between;align-items:center;border-bottom:1px solid #334155;padding-bottom:16px;margin-bottom:16px;">
1386
+ <h3 style="margin:0;font-size:16px;font-weight:700;display:flex;align-items:center;gap:10px;">
1387
+ <img src="/__velix/logo.webp" style="width:18px;height:18px;" />
1388
+ Velix DevTools
1389
+ </h3>
1390
+ <button onclick="document.getElementById('__velix-dev-panel').style.display='none'" style="background:transparent;border:none;color:#94a3b8;cursor:pointer;font-size:22px;line-height:1;padding:0;margin:0;transition:color 0.2s;" onmouseover="this.style.color='white'" onmouseout="this.style.color='#94a3b8'">&times;</button>
1391
+ </div>
1392
+
1393
+ <div style="margin-bottom:16px;padding:12px;background:#1e293b;border-radius:8px;border:1px solid #334155;">
1394
+ <div style="font-size:12px;color:#94a3b8;margin-bottom:4px;text-transform:uppercase;letter-spacing:0.5px;">Status</div>
1395
+ <div id="__velix-status-text" style="font-size:16px;font-weight:600;color:#22D3EE;">Ready</div>
1396
+ </div>
1397
+
1398
+ <div style="font-size:13px;color:#cbd5e1;line-height:2;">
1399
+ <div style="display:flex;justify-content:space-between;padding:8px 0;border-bottom:1px solid #1e293b;">
1400
+ <span style="color:#94a3b8;">Framework</span>
1401
+ <strong style="color:white;font-weight:600;">v5.0.0</strong>
1402
+ </div>
1403
+ <div style="display:flex;justify-content:space-between;padding:8px 0;border-bottom:1px solid #1e293b;">
1404
+ <span style="color:#94a3b8;">Environment</span>
1405
+ <strong style="color:#10b981;font-weight:600;">Development</strong>
1406
+ </div>
1407
+ <div style="display:flex;justify-content:space-between;padding:8px 0;border-bottom:1px solid #1e293b;">
1408
+ <span style="color:#94a3b8;">Router</span>
1409
+ <strong style="color:white;font-weight:600;">App Directory</strong>
1410
+ </div>
1411
+ <div style="display:flex;justify-content:space-between;padding:8px 0;">
1412
+ <span style="color:#94a3b8;">Rendering</span>
1413
+ <strong style="color:#60a5fa;font-weight:600;">Streaming SSR</strong>
1414
+ </div>
1415
+ </div>
1416
+
1417
+ <div style="margin-top:16px;padding-top:16px;border-top:1px solid #334155;">
1418
+ <div style="font-size:11px;color:#64748b;text-align:center;">
1419
+ <span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:#22D3EE;margin-right:4px;"></span> Idle
1420
+ <span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:#fb923c;margin:0 4px 0 12px;"></span> Rendering
1421
+ <span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:#4ade80;margin:0 4px 0 12px;"></span> Compiling
1422
+ </div>
1423
+ </div>
1424
+ </div>`;
1425
+ }
1426
+
1427
+ // server/error-pages.ts
1428
+ init_esm_shims();
1429
+ function generate404Page(pathname = "/") {
1430
+ return `<!DOCTYPE html>
1431
+ <html lang="en">
1432
+ <head>
1433
+ <meta charset="UTF-8">
1434
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1435
+ <title>404 - Page Not Found | Velix v5</title>
1436
+ <style>
1437
+ * { margin: 0; padding: 0; box-sizing: border-box; }
1438
+ body {
1439
+ margin: 0;
1440
+ background: linear-gradient(135deg, #0F172A 0%, #1E293B 100%);
1441
+ color: white;
1442
+ font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
1443
+ display: flex;
1444
+ align-items: center;
1445
+ justify-content: center;
1446
+ min-height: 100vh;
1447
+ text-align: center;
1448
+ overflow: hidden;
1449
+ }
1450
+ .container {
1451
+ max-width: 700px;
1452
+ padding: 60px 40px;
1453
+ position: relative;
1454
+ z-index: 10;
1455
+ }
1456
+ .bg-pattern {
1457
+ position: absolute;
1458
+ inset: 0;
1459
+ background-image: radial-gradient(circle at 20% 50%, rgba(34, 211, 238, 0.1) 0%, transparent 50%),
1460
+ radial-gradient(circle at 80% 80%, rgba(37, 99, 235, 0.1) 0%, transparent 50%);
1461
+ z-index: 1;
1462
+ }
1463
+ h1 {
1464
+ font-size: 180px;
1465
+ font-weight: 900;
1466
+ margin: 0;
1467
+ background: linear-gradient(135deg, #22D3EE 0%, #2563EB 100%);
1468
+ -webkit-background-clip: text;
1469
+ -webkit-text-fill-color: transparent;
1470
+ line-height: 1;
1471
+ letter-spacing: -0.05em;
1472
+ animation: fadeInUp 0.6s ease-out;
1473
+ }
1474
+ h2 {
1475
+ font-size: 36px;
1476
+ font-weight: 800;
1477
+ margin: 30px 0 15px;
1478
+ color: #F8FAFC;
1479
+ animation: fadeInUp 0.6s ease-out 0.1s backwards;
1480
+ }
1481
+ p {
1482
+ color: #94A3B8;
1483
+ font-size: 18px;
1484
+ line-height: 1.7;
1485
+ margin-bottom: 40px;
1486
+ animation: fadeInUp 0.6s ease-out 0.2s backwards;
1487
+ }
1488
+ code {
1489
+ background: rgba(255,255,255,0.1);
1490
+ padding: 4px 10px;
1491
+ border-radius: 6px;
1492
+ font-family: 'Fira Code', 'Courier New', monospace;
1493
+ color: #22D3EE;
1494
+ font-size: 16px;
1495
+ border: 1px solid rgba(34, 211, 238, 0.2);
1496
+ }
1497
+ .btn-group {
1498
+ display: flex;
1499
+ gap: 16px;
1500
+ justify-content: center;
1501
+ flex-wrap: wrap;
1502
+ animation: fadeInUp 0.6s ease-out 0.3s backwards;
1503
+ }
1504
+ .btn {
1505
+ display: inline-block;
1506
+ background: linear-gradient(135deg, #2563EB 0%, #1D4ED8 100%);
1507
+ color: white;
1508
+ text-decoration: none;
1509
+ padding: 14px 36px;
1510
+ border-radius: 12px;
1511
+ font-weight: 600;
1512
+ font-size: 16px;
1513
+ transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
1514
+ box-shadow: 0 10px 30px rgba(37, 99, 235, 0.3);
1515
+ border: none;
1516
+ cursor: pointer;
1517
+ }
1518
+ .btn:hover {
1519
+ transform: translateY(-2px);
1520
+ box-shadow: 0 15px 40px rgba(37, 99, 235, 0.4);
1521
+ }
1522
+ .btn-outline {
1523
+ background: transparent;
1524
+ color: #22D3EE;
1525
+ border: 2px solid #22D3EE;
1526
+ box-shadow: none;
1527
+ }
1528
+ .btn-outline:hover {
1529
+ background: rgba(34, 211, 238, 0.1);
1530
+ box-shadow: 0 10px 30px rgba(34, 211, 238, 0.2);
1531
+ }
1532
+ @keyframes fadeInUp {
1533
+ from {
1534
+ opacity: 0;
1535
+ transform: translateY(30px);
1536
+ }
1537
+ to {
1538
+ opacity: 1;
1539
+ transform: translateY(0);
1540
+ }
1541
+ }
1542
+ </style>
1543
+ </head>
1544
+ <body>
1545
+ <div class="bg-pattern"></div>
1546
+ <div class="container">
1547
+ <h1>404</h1>
1548
+ <h2>Page Not Found</h2>
1549
+ <p>The page <code>${pathname}</code> could not be found.<br>It may have been moved or deleted.</p>
1550
+ <div class="btn-group">
1551
+ <a href="/" class="btn">Return Home</a>
1552
+ <a href="javascript:history.back()" class="btn btn-outline">Go Back</a>
1553
+ </div>
1554
+ </div>
1555
+ </body>
1556
+ </html>`;
1557
+ }
1558
+ function generate500Page(options) {
1559
+ const { title, message, stack, isDev, pathname } = options;
1560
+ let callStackCards = "";
1561
+ let frameCount = 0;
1562
+ if (isDev && stack) {
1563
+ const stackLines = stack.split("\n").filter((line) => line.trim());
1564
+ const frames = stackLines.slice(1).filter((line) => line.includes("at "));
1565
+ frameCount = frames.length;
1566
+ callStackCards = frames.map((frame, index) => {
1567
+ const match = frame.match(/at\s+(.+?)\s+\((.+?)\)/) || frame.match(/at\s+(.+)/);
1568
+ if (match) {
1569
+ const funcName = match[1] || "anonymous";
1570
+ const location = match[2] || match[1];
1571
+ return `
1572
+ <div class="error-card" data-frame="${index}">
1573
+ <div class="card-header">
1574
+ <div class="card-title">${funcName.trim()}</div>
1575
+ <div class="card-number">${index + 1}</div>
1576
+ </div>
1577
+ <div class="card-location">${location.trim()}</div>
1578
+ </div>
1579
+ `;
1580
+ }
1581
+ return "";
1582
+ }).join("");
1583
+ }
1584
+ return `<!DOCTYPE html>
1585
+ <html lang="en">
1586
+ <head>
1587
+ <meta charset="UTF-8">
1588
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1589
+ <title>Error | Velix v5</title>
1590
+ <style>
1591
+ * { margin: 0; padding: 0; box-sizing: border-box; }
1592
+ body {
1593
+ margin: 0;
1594
+ background: linear-gradient(135deg, #0F172A 0%, #1E293B 100%);
1595
+ color: #F8FAFC;
1596
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
1597
+ min-height: 100vh;
1598
+ overflow-x: hidden;
1599
+ }
1600
+ .container {
1601
+ max-width: 900px;
1602
+ margin: 0 auto;
1603
+ padding: 40px 20px;
1604
+ }
1605
+ .error-header {
1606
+ background: linear-gradient(135deg, #EF4444 0%, #DC2626 100%);
1607
+ color: white;
1608
+ padding: 20px 28px;
1609
+ border-radius: 16px;
1610
+ display: flex;
1611
+ align-items: center;
1612
+ gap: 14px;
1613
+ margin-bottom: 28px;
1614
+ font-size: 18px;
1615
+ font-weight: 700;
1616
+ box-shadow: 0 10px 40px rgba(239, 68, 68, 0.3);
1617
+ }
1618
+ .error-header svg {
1619
+ width: 24px;
1620
+ height: 24px;
1621
+ flex-shrink: 0;
1622
+ }
1623
+ .error-badge {
1624
+ display: inline-block;
1625
+ background: linear-gradient(135deg, #1E40AF 0%, #1E3A8A 100%);
1626
+ color: #60A5FA;
1627
+ padding: 6px 16px;
1628
+ border-radius: 8px;
1629
+ font-size: 13px;
1630
+ font-weight: 700;
1631
+ margin-bottom: 18px;
1632
+ text-transform: uppercase;
1633
+ letter-spacing: 0.8px;
1634
+ box-shadow: 0 4px 12px rgba(30, 64, 175, 0.3);
1635
+ }
1636
+ .route-badge {
1637
+ background: linear-gradient(135deg, #0C4A6E 0%, #075985 100%);
1638
+ color: #22D3EE;
1639
+ padding: 10px 18px;
1640
+ border-radius: 10px;
1641
+ font-size: 14px;
1642
+ margin-bottom: 24px;
1643
+ font-family: 'Courier New', monospace;
1644
+ box-shadow: 0 4px 12px rgba(12, 74, 110, 0.3);
1645
+ border: 1px solid rgba(34, 211, 238, 0.2);
1646
+ }
1647
+ .error-message {
1648
+ background: rgba(239, 68, 68, 0.1);
1649
+ border-left: 4px solid #EF4444;
1650
+ padding: 18px 20px;
1651
+ border-radius: 10px;
1652
+ margin-bottom: 32px;
1653
+ }
1654
+ .error-message-text {
1655
+ color: #FCA5A5;
1656
+ font-size: 16px;
1657
+ font-weight: 600;
1658
+ line-height: 1.6;
1659
+ font-family: 'Courier New', monospace;
1660
+ }
1661
+ .stack-section {
1662
+ margin-top: 32px;
1663
+ }
1664
+ .stack-header {
1665
+ display: flex;
1666
+ align-items: center;
1667
+ justify-content: space-between;
1668
+ margin-bottom: 20px;
1669
+ }
1670
+ .stack-title {
1671
+ font-size: 18px;
1672
+ font-weight: 700;
1673
+ color: #F1F5F9;
1674
+ display: flex;
1675
+ align-items: center;
1676
+ gap: 10px;
1677
+ }
1678
+ .frame-counter {
1679
+ background: linear-gradient(135deg, #1F2937 0%, #111827 100%);
1680
+ color: #22D3EE;
1681
+ padding: 6px 14px;
1682
+ border-radius: 8px;
1683
+ font-size: 13px;
1684
+ font-weight: 700;
1685
+ border: 1px solid rgba(34, 211, 238, 0.2);
1686
+ }
1687
+ .error-card {
1688
+ background: linear-gradient(135deg, #1E293B 0%, #0F172A 100%);
1689
+ border: 1px solid rgba(34, 211, 238, 0.2);
1690
+ border-radius: 14px;
1691
+ padding: 20px;
1692
+ margin-bottom: 12px;
1693
+ transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
1694
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
1695
+ display: none;
1696
+ }
1697
+ .error-card.active {
1698
+ display: block;
1699
+ animation: slideIn 0.3s ease-out;
1700
+ }
1701
+ .error-card:hover {
1702
+ border-color: rgba(34, 211, 238, 0.5);
1703
+ box-shadow: 0 8px 24px rgba(34, 211, 238, 0.2);
1704
+ transform: translateY(-2px);
1705
+ }
1706
+ .card-header {
1707
+ display: flex;
1708
+ justify-content: space-between;
1709
+ align-items: center;
1710
+ margin-bottom: 12px;
1711
+ }
1712
+ .card-title {
1713
+ color: #22D3EE;
1714
+ font-size: 15px;
1715
+ font-weight: 700;
1716
+ font-family: 'Courier New', monospace;
1717
+ }
1718
+ .card-number {
1719
+ background: rgba(34, 211, 238, 0.2);
1720
+ color: #22D3EE;
1721
+ padding: 4px 10px;
1722
+ border-radius: 6px;
1723
+ font-size: 12px;
1724
+ font-weight: 700;
1725
+ }
1726
+ .card-location {
1727
+ color: #94A3B8;
1728
+ font-size: 13px;
1729
+ font-family: 'Courier New', monospace;
1730
+ word-break: break-all;
1731
+ line-height: 1.6;
1732
+ }
1733
+ .pagination {
1734
+ display: flex;
1735
+ justify-content: center;
1736
+ align-items: center;
1737
+ gap: 12px;
1738
+ margin-top: 24px;
1739
+ }
1740
+ .pagination-btn {
1741
+ background: linear-gradient(135deg, #1E293B 0%, #0F172A 100%);
1742
+ border: 1px solid rgba(34, 211, 238, 0.3);
1743
+ color: #22D3EE;
1744
+ padding: 10px 20px;
1745
+ border-radius: 10px;
1746
+ font-size: 14px;
1747
+ font-weight: 600;
1748
+ cursor: pointer;
1749
+ transition: all 0.2s;
1750
+ }
1751
+ .pagination-btn:hover:not(:disabled) {
1752
+ background: linear-gradient(135deg, #22D3EE 0%, #06B6D4 100%);
1753
+ color: #0F172A;
1754
+ transform: translateY(-2px);
1755
+ box-shadow: 0 6px 20px rgba(34, 211, 238, 0.4);
1756
+ }
1757
+ .pagination-btn:disabled {
1758
+ opacity: 0.3;
1759
+ cursor: not-allowed;
1760
+ }
1761
+ .pagination-info {
1762
+ color: #94A3B8;
1763
+ font-size: 14px;
1764
+ font-weight: 600;
1765
+ }
1766
+ .footer {
1767
+ margin-top: 48px;
1768
+ padding-top: 28px;
1769
+ border-top: 1px solid rgba(34, 211, 238, 0.2);
1770
+ display: flex;
1771
+ justify-content: space-between;
1772
+ align-items: center;
1773
+ flex-wrap: wrap;
1774
+ gap: 20px;
1775
+ }
1776
+ .brand {
1777
+ display: flex;
1778
+ align-items: center;
1779
+ gap: 10px;
1780
+ font-weight: 700;
1781
+ color: #22D3EE;
1782
+ font-size: 15px;
1783
+ }
1784
+ .brand img {
1785
+ width: 20px;
1786
+ height: 20px;
1787
+ }
1788
+ .footer-links {
1789
+ display: flex;
1790
+ gap: 24px;
1791
+ flex-wrap: wrap;
1792
+ }
1793
+ .footer-links a {
1794
+ color: #60A5FA;
1795
+ text-decoration: none;
1796
+ font-weight: 600;
1797
+ transition: all 0.2s;
1798
+ font-size: 14px;
1799
+ }
1800
+ .footer-links a:hover {
1801
+ color: #22D3EE;
1802
+ transform: translateY(-1px);
1803
+ }
1804
+ .no-stack {
1805
+ background: rgba(239, 68, 68, 0.1);
1806
+ border: 1px solid rgba(239, 68, 68, 0.3);
1807
+ border-radius: 12px;
1808
+ padding: 32px;
1809
+ color: #FCA5A5;
1810
+ text-align: center;
1811
+ font-size: 15px;
1812
+ }
1813
+ @keyframes slideIn {
1814
+ from {
1815
+ opacity: 0;
1816
+ transform: translateY(10px);
1817
+ }
1818
+ to {
1819
+ opacity: 1;
1820
+ transform: translateY(0);
1821
+ }
1822
+ }
1823
+ </style>
1824
+ </head>
1825
+ <body>
1826
+ <div class="container">
1827
+ <div class="error-header">
1828
+ <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
1829
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path>
1830
+ </svg>
1831
+ <span>Unhandled Runtime Error</span>
1832
+ </div>
1833
+
1834
+ <div class="error-badge">SERVER ERROR 500</div>
1835
+ ${pathname ? `<div class="route-badge">Route: ${pathname}</div>` : ""}
1836
+
1837
+ <div class="error-message">
1838
+ <div class="error-message-text">${message}</div>
1839
+ </div>
1840
+
1841
+ ${isDev && callStackCards ? `
1842
+ <div class="stack-section">
1843
+ <div class="stack-header">
1844
+ <div class="stack-title">
1845
+ <svg width="20" height="20" fill="none" stroke="currentColor" viewBox="0 0 24 24">
1846
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
1847
+ </svg>
1848
+ Call Stack
1849
+ </div>
1850
+ <div class="frame-counter">${frameCount}</div>
1851
+ </div>
1852
+ <div id="error-cards">
1853
+ ${callStackCards}
1854
+ </div>
1855
+ ${frameCount > 1 ? `
1856
+ <div class="pagination">
1857
+ <button class="pagination-btn" id="prev-btn" onclick="changePage(-1)">
1858
+ <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24" style="display:inline;vertical-align:middle;margin-right:4px;">
1859
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
1860
+ </svg>
1861
+ Previous
1862
+ </button>
1863
+ <div class="pagination-info">
1864
+ <span id="current-page">1</span> / <span id="total-pages">${frameCount}</span>
1865
+ </div>
1866
+ <button class="pagination-btn" id="next-btn" onclick="changePage(1)">
1867
+ Next
1868
+ <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24" style="display:inline;vertical-align:middle;margin-left:4px;">
1869
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
1870
+ </svg>
1871
+ </button>
1872
+ </div>
1873
+ ` : ""}
1874
+ </div>
1875
+ ` : '<div class="no-stack">An error occurred while processing your request. Please check the server logs for more details.</div>'}
1876
+
1877
+ <div class="footer">
1878
+ <div class="brand">
1879
+ <img src="/__velix/logo.webp" alt="Velix" onerror="this.style.display='none'"/>
1880
+ <span>Velix v5.0.0</span>
1881
+ </div>
1882
+ <div class="footer-links">
1883
+ <a href="/">Home</a>
1884
+ <a href="javascript:location.reload()">Reload</a>
1885
+ <a href="https://github.com/velix/velix/tree/main/docs" target="_blank">Documentation</a>
1886
+ ${isDev ? '<span style="color:#94A3B8;">Development Mode</span>' : ""}
1887
+ </div>
1888
+ </div>
1889
+ </div>
1890
+
1891
+ ${isDev && frameCount > 0 ? `
1892
+ <script>
1893
+ let currentPage = 1;
1894
+ const totalPages = ${frameCount};
1895
+ const cards = document.querySelectorAll('.error-card');
1896
+ const prevBtn = document.getElementById('prev-btn');
1897
+ const nextBtn = document.getElementById('next-btn');
1898
+ const currentPageSpan = document.getElementById('current-page');
1899
+
1900
+ function showPage(page) {
1901
+ cards.forEach((card, index) => {
1902
+ card.classList.remove('active');
1903
+ if (index === page - 1) {
1904
+ card.classList.add('active');
1905
+ }
1906
+ });
1907
+
1908
+ currentPage = page;
1909
+ currentPageSpan.textContent = page;
1910
+
1911
+ if (prevBtn) prevBtn.disabled = page === 1;
1912
+ if (nextBtn) nextBtn.disabled = page === totalPages;
1913
+ }
1914
+
1915
+ function changePage(direction) {
1916
+ const newPage = currentPage + direction;
1917
+ if (newPage >= 1 && newPage <= totalPages) {
1918
+ showPage(newPage);
1919
+ }
1920
+ }
1921
+
1922
+ // Show first page on load
1923
+ showPage(1);
1924
+
1925
+ // Keyboard navigation
1926
+ document.addEventListener('keydown', (e) => {
1927
+ if (e.key === 'ArrowLeft') changePage(-1);
1928
+ if (e.key === 'ArrowRight') changePage(1);
1929
+ });
1930
+ </script>
1931
+ ` : ""}
1932
+ </body>
1933
+ </html>`;
1934
+ }
1935
+
1936
+ // server/index.ts
1937
+ var MIME_TYPES = {
1938
+ ".html": "text/html; charset=utf-8",
1939
+ ".css": "text/css; charset=utf-8",
1940
+ ".js": "application/javascript; charset=utf-8",
1941
+ ".mjs": "application/javascript; charset=utf-8",
1942
+ ".json": "application/json",
1943
+ ".png": "image/png",
1944
+ ".jpg": "image/jpeg",
1945
+ ".jpeg": "image/jpeg",
1946
+ ".gif": "image/gif",
1947
+ ".svg": "image/svg+xml",
1948
+ ".ico": "image/x-icon",
1949
+ ".webp": "image/webp",
1950
+ ".woff": "font/woff",
1951
+ ".woff2": "font/woff2",
1952
+ ".ttf": "font/ttf",
1953
+ ".otf": "font/otf",
1954
+ ".txt": "text/plain; charset=utf-8",
1955
+ ".xml": "application/xml",
1956
+ ".mp4": "video/mp4",
1957
+ ".webm": "video/webm",
1958
+ ".mp3": "audio/mpeg",
1959
+ ".pdf": "application/pdf",
1960
+ ".map": "application/json"
1961
+ };
1962
+ async function createServer(options = {}) {
1963
+ const projectRoot = options.projectRoot || process.cwd();
1964
+ const mode = options.mode || process.env.NODE_ENV || "development";
1965
+ const isDev = mode === "development";
1966
+ const rawConfig = await loadConfig(projectRoot);
1967
+ const config = resolvePaths(rawConfig, projectRoot);
1968
+ await loadPlugins(projectRoot, config);
1969
+ await pluginManager.runHook(PluginHooks.CONFIG, config);
1970
+ const middlewareFns = await loadMiddleware(projectRoot);
1971
+ const appDir = config.resolvedAppDir || path7.join(projectRoot, "app");
1972
+ const routes = buildRouteTree(appDir);
1973
+ await pluginManager.runHook(PluginHooks.ROUTES_LOADED, routes);
1974
+ const startTime = Date.now();
1975
+ await pluginManager.runHook(PluginHooks.SERVER_START, { config, isDev, projectRoot }, isDev);
1976
+ const server = http.createServer(async (req, res) => {
1977
+ const requestStart = Date.now();
1978
+ const url = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`);
1979
+ const pathname = url.pathname;
1980
+ try {
1981
+ if (middlewareFns.length > 0) {
1982
+ const middlewareResult = await runMiddleware(req, res, middlewareFns);
1983
+ if (!middlewareResult.continue) return;
1984
+ }
1985
+ await pluginManager.runHook(PluginHooks.REQUEST, req, res);
1986
+ if (pathname === "/sitemap.xml" && config.seo.sitemap) {
1987
+ const baseUrl = config.app.url || `http://${config.server.host}:${config.server.port}`;
1988
+ const sitemap = generateSitemap(routes.appRoutes, baseUrl);
1989
+ res.writeHead(200, { "Content-Type": "application/xml" });
1990
+ res.end(sitemap);
1991
+ return;
1992
+ }
1993
+ if (pathname === "/robots.txt" && config.seo.robots) {
1994
+ const baseUrl = config.app.url || `http://${config.server.host}:${config.server.port}`;
1995
+ const robotsTxt = generateRobotsTxt(baseUrl);
1996
+ res.writeHead(200, { "Content-Type": "text/plain" });
1997
+ res.end(robotsTxt);
1998
+ return;
1999
+ }
2000
+ if (pathname === "/__velix/action" && req.method === "POST") {
2001
+ await handleServerAction(req, res);
2002
+ return;
2003
+ }
2004
+ if (pathname === "/__velix/image") {
2005
+ const { handleImageOptimization: handleImageOptimization2 } = await Promise.resolve().then(() => (init_image_optimizer(), image_optimizer_exports));
2006
+ await handleImageOptimization2(req, res, projectRoot);
2007
+ return;
2008
+ }
2009
+ if (pathname.startsWith("/__velix/")) {
2010
+ await serveVelixInternal(pathname, req, res, projectRoot);
2011
+ return;
2012
+ }
2013
+ const publicDir = config.resolvedPublicDir || path7.join(projectRoot, "public");
2014
+ if (await serveStaticFile(pathname, publicDir, res, isDev)) {
2015
+ if (isDev) logger_default.request(req.method || "GET", pathname, 200, Date.now() - requestStart, { type: "static" });
2016
+ return;
2017
+ }
2018
+ const apiMatch = matchRoute(pathname, routes.api);
2019
+ if (apiMatch) {
2020
+ await handleApiRoute(apiMatch, req, res, url);
2021
+ if (isDev) logger_default.request(req.method || "GET", pathname, res.statusCode, Date.now() - requestStart, { type: "api" });
2022
+ return;
2023
+ }
2024
+ const pageMatch = matchRoute(pathname, routes.appRoutes);
2025
+ if (pageMatch) {
2026
+ await handlePageRoute(pageMatch, routes, req, res, url, config, isDev, projectRoot);
2027
+ if (isDev) logger_default.request(req.method || "GET", pathname, res.statusCode, Date.now() - requestStart, { type: "ssr" });
2028
+ return;
2029
+ }
2030
+ res.writeHead(404, { "Content-Type": "text/html; charset=utf-8" });
2031
+ res.end(generate404Page(pathname));
2032
+ if (isDev) logger_default.request(req.method || "GET", pathname, 404, Date.now() - requestStart);
2033
+ } catch (error) {
2034
+ console.error("Server error:", error);
2035
+ if (!res.headersSent) {
2036
+ res.writeHead(500, { "Content-Type": "text/html; charset=utf-8" });
2037
+ res.end(generate500Page({
2038
+ statusCode: 500,
2039
+ title: "Server Error",
2040
+ message: error.message || "An unexpected error occurred",
2041
+ stack: isDev ? error.stack : void 0,
2042
+ isDev,
2043
+ pathname
2044
+ }));
2045
+ }
2046
+ }
2047
+ });
2048
+ const __hmrClients = /* @__PURE__ */ new Set();
2049
+ server.__hmrClients = __hmrClients;
2050
+ server.broadcastHMR = (msg) => {
2051
+ __hmrClients.forEach((c2) => c2.write(`data: ${msg}
2052
+
2053
+ `));
2054
+ };
2055
+ const port = config.server.port;
2056
+ const host = config.server.host;
2057
+ server.listen(port, host, () => {
2058
+ logger_default.serverStart({ port, host, mode, pagesDir: appDir }, startTime);
2059
+ if (isDev) {
2060
+ routes.appRoutes.forEach((r) => {
2061
+ const type = r.path.includes(":") || r.path.includes("*") ? "dynamic" : "static";
2062
+ logger_default.route(r.path, type);
2063
+ });
2064
+ routes.api.forEach((r) => logger_default.route(r.path, "api"));
2065
+ logger_default.blank();
2066
+ }
2067
+ });
2068
+ server.on("error", (err) => {
2069
+ if (err.code === "EADDRINUSE") {
2070
+ logger_default.portInUse(port);
2071
+ process.exit(1);
2072
+ }
2073
+ throw err;
2074
+ });
2075
+ return {
2076
+ server,
2077
+ config: rawConfig,
2078
+ close: () => server.close()
2079
+ };
2080
+ }
2081
+ async function serveStaticFile(pathname, publicDir, res, isDev = false) {
2082
+ const filePath = path7.join(publicDir, pathname);
2083
+ if (!filePath.startsWith(publicDir)) return false;
2084
+ if (!fs7.existsSync(filePath) || fs7.statSync(filePath).isDirectory()) return false;
2085
+ const ext = path7.extname(filePath);
2086
+ const contentType = MIME_TYPES[ext] || "application/octet-stream";
2087
+ const content = fs7.readFileSync(filePath);
2088
+ res.writeHead(200, {
2089
+ "Content-Type": contentType,
2090
+ "Content-Length": content.length,
2091
+ "Cache-Control": isDev ? "no-store, no-cache, must-revalidate" : "public, max-age=31536000, immutable"
2092
+ });
2093
+ res.end(content);
2094
+ return true;
2095
+ }
2096
+ async function handleApiRoute(route, req, res, url) {
2097
+ try {
2098
+ const fileUrl = pathToFileURL3(route.filePath).href;
2099
+ const mod = await import(`${fileUrl}?t=${Date.now()}`);
2100
+ const method = req.method?.toUpperCase() || "GET";
2101
+ const handler = mod[method] || mod.default;
2102
+ if (!handler) {
2103
+ res.writeHead(405, { "Content-Type": "application/json" });
2104
+ res.end(JSON.stringify({ error: "Method not allowed" }));
2105
+ return;
2106
+ }
2107
+ let body;
2108
+ if (["POST", "PUT", "PATCH"].includes(method)) {
2109
+ body = await parseRequestBody(req);
2110
+ }
2111
+ const request = {
2112
+ method,
2113
+ url: req.url,
2114
+ headers: req.headers,
2115
+ params: route.params || {},
2116
+ query: Object.fromEntries(url.searchParams),
2117
+ body,
2118
+ json: () => body
2119
+ };
2120
+ const response = await handler(request);
2121
+ if (response instanceof Response) {
2122
+ const headers2 = {};
2123
+ response.headers.forEach((v, k) => {
2124
+ headers2[k] = v;
2125
+ });
2126
+ res.writeHead(response.status, headers2);
2127
+ const text = await response.text();
2128
+ res.end(text);
2129
+ } else if (typeof response === "object") {
2130
+ res.writeHead(200, { "Content-Type": "application/json" });
2131
+ res.end(JSON.stringify(response));
2132
+ } else {
2133
+ res.writeHead(200, { "Content-Type": "text/plain" });
2134
+ res.end(String(response));
2135
+ }
2136
+ } catch (err) {
2137
+ res.writeHead(500, { "Content-Type": "application/json" });
2138
+ res.end(JSON.stringify({ error: err.message }));
2139
+ }
2140
+ }
2141
+ async function handleServerAction(req, res) {
2142
+ try {
2143
+ const body = await parseRequestBody(req);
2144
+ if (!body?.actionId || typeof body.actionId !== "string") {
2145
+ res.writeHead(400, { "Content-Type": "application/json" });
2146
+ res.end(JSON.stringify({ error: "Missing actionId" }));
2147
+ return;
2148
+ }
2149
+ const args = body.args ? deserializeArgs(body.args) : [];
2150
+ const result = await executeAction(body.actionId, args);
2151
+ res.writeHead(200, { "Content-Type": "application/json" });
2152
+ res.end(JSON.stringify(result));
2153
+ } catch (err) {
2154
+ res.writeHead(500, { "Content-Type": "application/json" });
2155
+ res.end(JSON.stringify({ success: false, error: err.message }));
2156
+ }
2157
+ }
2158
+ async function handlePageRoute(route, routes, req, res, url, config, isDev, projectRoot) {
2159
+ try {
2160
+ const fileUrl = pathToFileURL3(route.filePath).href;
2161
+ const mod = await import(`${fileUrl}?t=${Date.now()}`);
2162
+ const PageComponent = mod.default;
2163
+ let metadata = mod.metadata || mod.generateMetadata?.(route.params) || {};
2164
+ let LayoutComponent = ({ children }) => React2.createElement(React2.Fragment, null, children);
2165
+ let layoutParams = route.params;
2166
+ try {
2167
+ const layoutPath = path7.join(path7.dirname(route.filePath), "layout.tsx");
2168
+ if (fs7.existsSync(layoutPath)) {
2169
+ const layoutMod = await import(`${pathToFileURL3(layoutPath).href}?t=${Date.now()}`);
2170
+ if (layoutMod.metadata) {
2171
+ metadata = { ...layoutMod.metadata, ...metadata };
2172
+ }
2173
+ if (layoutMod.default) {
2174
+ LayoutComponent = layoutMod.default;
2175
+ }
2176
+ }
2177
+ } catch (e) {
2178
+ }
2179
+ const baseUrl = config.app.url || `http://${config.server.host}:${config.server.port}`;
2180
+ const metaTags = generateMetadataTags({
2181
+ ...metadata,
2182
+ generator: `Velix v5.0.0`,
2183
+ viewport: metadata.viewport || "width=device-width, initial-scale=1"
2184
+ }, baseUrl);
2185
+ const islands = getRegisteredIslands();
2186
+ const hydrationScript = generateAdvancedHydrationScript(islands);
2187
+ const devToolsHtml = generateDevToolsHtml(isDev);
2188
+ const headInjections = `
2189
+ <meta charset="utf-8">
2190
+ ${metaTags}
2191
+ ${config.favicon ? `<link rel="icon" href="${config.favicon}">` : ""}
2192
+ ${config.styles.map((s) => `<link rel="stylesheet" href="${s}">`).join("\n ")}
2193
+ `;
2194
+ const searchParams = Object.fromEntries(url.searchParams.entries());
2195
+ let pageElement = React2.createElement(PageComponent, { params: route.params, searchParams, query: searchParams });
2196
+ if (typeof PageComponent === "function") {
2197
+ try {
2198
+ const result = PageComponent({ params: route.params, searchParams, query: searchParams });
2199
+ if (result instanceof Promise) {
2200
+ pageElement = await result;
2201
+ }
2202
+ } catch (e) {
2203
+ }
2204
+ }
2205
+ let layoutElement = React2.createElement(LayoutComponent, { params: layoutParams, searchParams }, pageElement);
2206
+ if (typeof LayoutComponent === "function") {
2207
+ try {
2208
+ const result = LayoutComponent({ params: layoutParams, searchParams, children: pageElement });
2209
+ if (result instanceof Promise) {
2210
+ layoutElement = await result;
2211
+ }
2212
+ } catch (e) {
2213
+ }
2214
+ }
2215
+ const ssrContent = renderToString(layoutElement);
2216
+ let finalHtml = await pluginManager.runWaterfallHook(PluginHooks.AFTER_RENDER, ssrContent, { route, config, isDev });
2217
+ const headInjectionsHtml = `
2218
+ ${headInjections}
2219
+ `;
2220
+ const bodyInjectionsHtml = `
2221
+ <div id="__velix-islands"></div>
2222
+ ${hydrationScript}${devToolsHtml}
2223
+ `;
2224
+ if (finalHtml.includes("<html")) {
2225
+ const headEnd = finalHtml.lastIndexOf("</head>");
2226
+ if (headEnd !== -1) {
2227
+ finalHtml = finalHtml.slice(0, headEnd) + headInjectionsHtml + finalHtml.slice(headEnd);
2228
+ } else {
2229
+ const bodyStart = finalHtml.search(/<body[^>]*>/i);
2230
+ if (bodyStart !== -1) {
2231
+ finalHtml = finalHtml.slice(0, bodyStart) + `<head>${headInjectionsHtml}</head>` + finalHtml.slice(bodyStart);
2232
+ }
2233
+ }
2234
+ const bodyEnd = finalHtml.lastIndexOf("</body>");
2235
+ if (bodyEnd !== -1) {
2236
+ finalHtml = finalHtml.slice(0, bodyEnd) + bodyInjectionsHtml + finalHtml.slice(bodyEnd);
2237
+ } else {
2238
+ finalHtml += bodyInjectionsHtml;
2239
+ }
2240
+ if (!finalHtml.trim().startsWith("<!DOCTYPE")) {
2241
+ finalHtml = "<!DOCTYPE html>\n" + finalHtml;
2242
+ }
2243
+ } else {
2244
+ finalHtml = `<!DOCTYPE html>
2245
+ <html lang="en">
2246
+ <head>
2247
+ ${headInjectionsHtml}
2248
+ </head>
2249
+ <body>
2250
+ <div id="__velix">${ssrContent}</div>
2251
+ ${bodyInjectionsHtml}
2252
+ </body>
2253
+ </html>`;
2254
+ }
2255
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
2256
+ res.end(finalHtml);
2257
+ } catch (err) {
2258
+ logger_default.error(`Render error: ${route.path}`, err);
2259
+ res.writeHead(500, { "Content-Type": "text/html; charset=utf-8" });
2260
+ res.end(generate500Page({
2261
+ statusCode: 500,
2262
+ title: "Render Error",
2263
+ message: err.message || "Failed to render page",
2264
+ stack: isDev ? err.stack : void 0,
2265
+ isDev,
2266
+ pathname: route.path
2267
+ }));
2268
+ }
2269
+ }
2270
+ async function serveVelixInternal(pathname, req, res, projectRoot) {
2271
+ if (pathname === "/__velix/hmr") {
2272
+ res.writeHead(200, {
2273
+ "Content-Type": "text/event-stream",
2274
+ "Cache-Control": "no-cache",
2275
+ "Connection": "keep-alive"
2276
+ });
2277
+ res.write("data: connected\n\n");
2278
+ const interval = setInterval(() => res.write(":heartbeat\n\n"), 3e4);
2279
+ if (res.req?.socket?.server?.__hmrClients) res.req.socket.server.__hmrClients.add(res);
2280
+ req.on("close", () => {
2281
+ clearInterval(interval);
2282
+ if (res.req?.socket?.server?.__hmrClients) res.req.socket.server.__hmrClients.delete(res);
2283
+ });
2284
+ return;
2285
+ }
2286
+ if (pathname === "/__velix/logo.webp") {
2287
+ const __filename2 = fileURLToPath2(import.meta.url);
2288
+ const __dirname2 = path7.dirname(__filename2);
2289
+ const fallbackPath = path7.join(path7.dirname(pathToFileURL3(__dirname2).pathname), "..", "assets", "logo.webp");
2290
+ const logoPath = fs7.existsSync(fallbackPath) ? fallbackPath : path7.join(process.cwd(), "node_modules", "velix", "assets", "logo.webp");
2291
+ if (fs7.existsSync(logoPath)) {
2292
+ res.writeHead(200, { "Content-Type": "image/webp", "Cache-Control": "public, max-age=31536000, immutable" });
2293
+ res.end(fs7.readFileSync(logoPath));
2294
+ } else {
2295
+ res.writeHead(404);
2296
+ res.end();
2297
+ }
2298
+ return;
2299
+ }
2300
+ if (pathname.startsWith("/__velix/islands/") && pathname.endsWith(".js")) {
2301
+ const componentName = pathname.replace("/__velix/islands/", "").replace(".js", "");
2302
+ try {
2303
+ const searchDirs = [
2304
+ path7.join(projectRoot, "components"),
2305
+ path7.join(projectRoot, "app"),
2306
+ path7.join(projectRoot, "islands")
2307
+ ];
2308
+ let componentPath = "";
2309
+ for (const dir of searchDirs) {
2310
+ if (!fs7.existsSync(dir)) continue;
2311
+ const files = fs7.readdirSync(dir, { recursive: true });
2312
+ const found = files.find((f) => f.replace(/\\/g, "/").endsWith(`${componentName}.tsx`) || f.replace(/\\/g, "/").endsWith(`${componentName}.jsx`));
2313
+ if (found) {
2314
+ componentPath = path7.join(dir, found);
2315
+ break;
2316
+ }
2317
+ }
2318
+ if (!componentPath) {
2319
+ logger_default.error(`Island component not found: ${componentName}`);
2320
+ res.writeHead(404);
2321
+ res.end("Island component not found");
2322
+ return;
2323
+ }
2324
+ const result = await esbuild.build({
2325
+ entryPoints: [componentPath],
2326
+ bundle: true,
2327
+ format: "esm",
2328
+ platform: "browser",
2329
+ target: ["es2022"],
2330
+ minify: false,
2331
+ sourcemap: "inline",
2332
+ jsx: "automatic",
2333
+ external: ["react", "react-dom"],
2334
+ write: false
2335
+ });
2336
+ res.writeHead(200, { "Content-Type": "application/javascript" });
2337
+ res.end(result.outputFiles[0].text);
2338
+ return;
2339
+ } catch (err) {
2340
+ logger_default.error(`Island bundling failed: ${componentName}`, err);
2341
+ res.writeHead(500);
2342
+ res.end(`console.error("Island bundling failed: ${err.message}");`);
2343
+ return;
2344
+ }
2345
+ }
2346
+ if (pathname === "/__velix/react.js" || pathname === "/__velix/react-dom-client.js") {
2347
+ const dep = pathname === "/__velix/react.js" ? "react" : "react-dom/client";
2348
+ try {
2349
+ const result = await esbuild.build({
2350
+ entryPoints: [dep],
2351
+ bundle: true,
2352
+ format: "esm",
2353
+ platform: "browser",
2354
+ target: ["es2022"],
2355
+ minify: true,
2356
+ write: false
2357
+ });
2358
+ res.writeHead(200, { "Content-Type": "application/javascript", "Cache-Control": "public, max-age=31536000, immutable" });
2359
+ res.end(result.outputFiles[0].text);
2360
+ return;
2361
+ } catch (err) {
2362
+ res.writeHead(500);
2363
+ res.end();
2364
+ return;
2365
+ }
2366
+ }
2367
+ res.writeHead(404);
2368
+ res.end("Not found");
2369
+ }
2370
+ function parseRequestBody(req) {
2371
+ return new Promise((resolve, reject) => {
2372
+ let body = "";
2373
+ req.on("data", (chunk) => {
2374
+ body += chunk;
2375
+ });
2376
+ req.on("end", () => {
2377
+ try {
2378
+ const ct = req.headers["content-type"] || "";
2379
+ if (ct.includes("application/json")) resolve(JSON.parse(body));
2380
+ else resolve(body);
2381
+ } catch {
2382
+ resolve(body);
2383
+ }
2384
+ });
2385
+ req.on("error", reject);
2386
+ });
2387
+ }
2388
+
2389
+ // runtime/start-prod.ts
2390
+ async function startProd() {
2391
+ process.env.NODE_ENV = "production";
2392
+ const projectRoot = process.cwd();
2393
+ await createServer({ projectRoot, mode: "production" });
2394
+ process.on("SIGINT", () => {
2395
+ logger_default.blank();
2396
+ logger_default.info("Shutting down...");
2397
+ process.exit(0);
2398
+ });
2399
+ process.on("SIGTERM", () => {
2400
+ logger_default.info("Received SIGTERM, shutting down gracefully...");
2401
+ process.exit(0);
2402
+ });
2403
+ }
2404
+ startProd().catch((err) => {
2405
+ logger_default.error("Failed to start production server", err);
2406
+ process.exit(1);
2407
+ });
2408
+ //# sourceMappingURL=start-prod.js.map