@flexireact/core 3.0.4 → 4.1.0

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../core/config.ts","../../core/context.ts","../../core/utils.ts","../../core/router/index.ts","../../core/render/index.ts","../../core/server/index.ts","../../core/middleware/index.ts","../../core/plugins/index.ts","../../core/islands/index.ts","../../core/logger.ts","../../core/helpers.ts","../../core/actions/index.ts","../../core/image/index.ts","../../core/font/index.ts","../../core/build/index.ts","../../core/ssg/index.ts","../../core/rsc/index.ts","../../core/edge/runtime.ts","../../core/edge/fetch-polyfill.ts","../../core/edge/cache.ts","../../core/edge/handler.ts","../../core/edge/ppr.ts","../../core/metadata/index.ts","../../core/devtools/index.ts","../../core/index.ts"],"sourcesContent":["/**\r\n * FlexiReact Configuration System\r\n * Handles loading and merging of configuration from flexireact.config.js\r\n */\r\n\r\nimport fs from 'fs';\r\nimport path from 'path';\r\nimport { pathToFileURL } from 'url';\r\n\r\n// Default configuration\r\nexport const defaultConfig = {\r\n // Directories\r\n pagesDir: 'pages',\r\n layoutsDir: 'layouts',\r\n publicDir: 'public',\r\n outDir: '.flexi',\r\n \r\n // Build options\r\n build: {\r\n target: 'es2022',\r\n minify: true,\r\n sourcemap: true,\r\n splitting: true\r\n },\r\n \r\n // Server options\r\n server: {\r\n port: 3000,\r\n host: 'localhost'\r\n },\r\n \r\n // SSG options\r\n ssg: {\r\n enabled: false,\r\n paths: []\r\n },\r\n \r\n // Islands (partial hydration)\r\n islands: {\r\n enabled: true\r\n },\r\n \r\n // RSC options\r\n rsc: {\r\n enabled: true\r\n },\r\n \r\n // Plugins\r\n plugins: [],\r\n \r\n // Styles (CSS files to include)\r\n styles: [],\r\n \r\n // Scripts (JS files to include)\r\n scripts: [],\r\n \r\n // Favicon path\r\n favicon: null\r\n};\r\n\r\n/**\r\n * Loads configuration from the project root\r\n * @param {string} projectRoot - Path to project root\r\n * @returns {Object} Merged configuration\r\n */\r\nexport async function loadConfig(projectRoot: string) {\r\n // Try .ts first, then .js\r\n const configPathTs = path.join(projectRoot, 'flexireact.config.ts');\r\n const configPathJs = path.join(projectRoot, 'flexireact.config.js');\r\n const configPath = fs.existsSync(configPathTs) ? configPathTs : configPathJs;\r\n \r\n let userConfig = {};\r\n \r\n if (fs.existsSync(configPath)) {\r\n try {\r\n const configUrl = pathToFileURL(configPath).href;\r\n const module = await import(`${configUrl}?t=${Date.now()}`);\r\n userConfig = module.default || module;\r\n } catch (error: any) {\r\n console.warn('Warning: Failed to load flexireact config:', error.message);\r\n }\r\n }\r\n \r\n // Deep merge configs\r\n return deepMerge(defaultConfig, userConfig);\r\n}\r\n\r\n/**\r\n * Deep merge two objects\r\n */\r\nfunction deepMerge(target, source) {\r\n const result = { ...target };\r\n \r\n for (const key in source) {\r\n if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) {\r\n result[key] = deepMerge(target[key] || {}, source[key]);\r\n } else {\r\n result[key] = source[key];\r\n }\r\n }\r\n \r\n return result;\r\n}\r\n\r\n/**\r\n * Resolves all paths in config relative to project root\r\n */\r\nexport function resolvePaths(config, projectRoot) {\r\n return {\r\n ...config,\r\n pagesDir: path.resolve(projectRoot, config.pagesDir),\r\n layoutsDir: path.resolve(projectRoot, config.layoutsDir),\r\n publicDir: path.resolve(projectRoot, config.publicDir),\r\n outDir: path.resolve(projectRoot, config.outDir)\r\n };\r\n}\r\n","/**\r\n * FlexiReact Context System\r\n * Provides request context and shared state for SSR/RSC\r\n */\r\n\r\nimport React from 'react';\r\n\r\n// Server-side request context\r\nexport const RequestContext = React.createContext(null);\r\n\r\n// Route context for nested routes\r\nexport const RouteContext = React.createContext(null);\r\n\r\n// Layout context\r\nexport const LayoutContext = React.createContext(null);\r\n\r\n/**\r\n * Creates a request context value\r\n */\r\nexport function createRequestContext(req, res, params = {}, query = {}) {\r\n return {\r\n req,\r\n res,\r\n params,\r\n query,\r\n url: req.url,\r\n method: req.method,\r\n headers: req.headers,\r\n cookies: parseCookies(req.headers.cookie || '')\r\n };\r\n}\r\n\r\n/**\r\n * Parse cookies from header string\r\n */\r\nfunction parseCookies(cookieHeader) {\r\n const cookies = {};\r\n if (!cookieHeader) return cookies;\r\n \r\n cookieHeader.split(';').forEach(cookie => {\r\n const [name, ...rest] = cookie.split('=');\r\n if (name) {\r\n cookies[name.trim()] = rest.join('=').trim();\r\n }\r\n });\r\n \r\n return cookies;\r\n}\r\n\r\n/**\r\n * Hook to access request context (server-side only)\r\n */\r\nexport function useRequest() {\r\n const context = React.useContext(RequestContext);\r\n if (!context) {\r\n throw new Error('useRequest must be used within a RequestContext provider');\r\n }\r\n return context;\r\n}\r\n\r\n/**\r\n * Hook to access route params\r\n */\r\nexport function useParams() {\r\n const context = React.useContext(RouteContext);\r\n return context?.params || {};\r\n}\r\n\r\n/**\r\n * Hook to access query parameters\r\n */\r\nexport function useQuery() {\r\n const context = React.useContext(RouteContext);\r\n return context?.query || {};\r\n}\r\n\r\n/**\r\n * Hook to access current pathname\r\n */\r\nexport function usePathname() {\r\n const context = React.useContext(RouteContext);\r\n return context?.pathname || '/';\r\n}\r\n","/**\r\n * FlexiReact Utility Functions\r\n */\r\n\r\nimport fs from 'fs';\r\nimport path from 'path';\r\nimport crypto from 'crypto';\r\n\r\n/**\r\n * Generates a unique hash for cache busting\r\n */\r\nexport function generateHash(content) {\r\n return crypto.createHash('md5').update(content).digest('hex').slice(0, 8);\r\n}\r\n\r\n/**\r\n * Escapes HTML special characters\r\n */\r\nexport function escapeHtml(str) {\r\n const htmlEntities = {\r\n '&': '&amp;',\r\n '<': '&lt;',\r\n '>': '&gt;',\r\n '\"': '&quot;',\r\n \"'\": '&#39;'\r\n };\r\n return String(str).replace(/[&<>\"']/g, char => htmlEntities[char]);\r\n}\r\n\r\n/**\r\n * Recursively finds all files matching a pattern\r\n */\r\nexport function findFiles(dir, pattern, files = []) {\r\n if (!fs.existsSync(dir)) return files;\r\n \r\n const entries = fs.readdirSync(dir, { withFileTypes: true });\r\n \r\n for (const entry of entries) {\r\n const fullPath = path.join(dir, entry.name);\r\n \r\n if (entry.isDirectory()) {\r\n findFiles(fullPath, pattern, files);\r\n } else if (pattern.test(entry.name)) {\r\n files.push(fullPath);\r\n }\r\n }\r\n \r\n return files;\r\n}\r\n\r\n/**\r\n * Ensures a directory exists\r\n */\r\nexport function ensureDir(dir) {\r\n if (!fs.existsSync(dir)) {\r\n fs.mkdirSync(dir, { recursive: true });\r\n }\r\n}\r\n\r\n/**\r\n * Cleans a directory\r\n */\r\nexport function cleanDir(dir) {\r\n if (fs.existsSync(dir)) {\r\n fs.rmSync(dir, { recursive: true, force: true });\r\n }\r\n fs.mkdirSync(dir, { recursive: true });\r\n}\r\n\r\n/**\r\n * Copies a directory recursively\r\n */\r\nexport function copyDir(src, dest) {\r\n ensureDir(dest);\r\n \r\n const entries = fs.readdirSync(src, { withFileTypes: true });\r\n \r\n for (const entry of entries) {\r\n const srcPath = path.join(src, entry.name);\r\n const destPath = path.join(dest, entry.name);\r\n \r\n if (entry.isDirectory()) {\r\n copyDir(srcPath, destPath);\r\n } else {\r\n fs.copyFileSync(srcPath, destPath);\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Debounce function for file watching\r\n */\r\nexport function debounce(fn, delay) {\r\n let timeout;\r\n return (...args) => {\r\n clearTimeout(timeout);\r\n timeout = setTimeout(() => fn(...args), delay);\r\n };\r\n}\r\n\r\n/**\r\n * Formats bytes to human readable string\r\n */\r\nexport function formatBytes(bytes) {\r\n if (bytes === 0) return '0 B';\r\n const k = 1024;\r\n const sizes = ['B', 'KB', 'MB', 'GB'];\r\n const i = Math.floor(Math.log(bytes) / Math.log(k));\r\n return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];\r\n}\r\n\r\n/**\r\n * Formats milliseconds to human readable string\r\n */\r\nexport function formatTime(ms) {\r\n if (ms < 1000) return `${ms}ms`;\r\n return `${(ms / 1000).toFixed(2)}s`;\r\n}\r\n\r\n/**\r\n * Creates a deferred promise\r\n */\r\nexport function createDeferred() {\r\n let resolve, reject;\r\n const promise = new Promise((res, rej) => {\r\n resolve = res;\r\n reject = rej;\r\n });\r\n return { promise, resolve, reject };\r\n}\r\n\r\n/**\r\n * Sleep utility\r\n */\r\nexport function sleep(ms) {\r\n return new Promise(resolve => setTimeout(resolve, ms));\r\n}\r\n\r\n/**\r\n * Check if a file is a server component (has 'use server' directive)\r\n */\r\nexport function isServerComponent(filePath) {\r\n try {\r\n const content = fs.readFileSync(filePath, 'utf-8');\r\n const firstLine = content.split('\\n')[0].trim();\r\n return firstLine === \"'use server'\" || firstLine === '\"use server\"';\r\n } catch {\r\n return false;\r\n }\r\n}\r\n\r\n/**\r\n * Check if a file is a client component (has 'use client' directive)\r\n */\r\nexport function isClientComponent(filePath) {\r\n try {\r\n const content = fs.readFileSync(filePath, 'utf-8');\r\n const firstLine = content.split('\\n')[0].trim();\r\n return firstLine === \"'use client'\" || firstLine === '\"use client\"';\r\n } catch {\r\n return false;\r\n }\r\n}\r\n\r\n/**\r\n * Check if a component is an island (has 'use island' directive)\r\n */\r\nexport function isIsland(filePath) {\r\n try {\r\n const content = fs.readFileSync(filePath, 'utf-8');\r\n const firstLine = content.split('\\n')[0].trim();\r\n return firstLine === \"'use island'\" || firstLine === '\"use island\"';\r\n } catch {\r\n return false;\r\n }\r\n}\r\n","/**\r\n * FlexiReact Router v2\r\n * Advanced file-based routing with nested routes, loading, and error boundaries\r\n * \r\n * Supports multiple routing conventions:\r\n * - pages/ : Traditional file-based routing (index.tsx, about.tsx)\r\n * - app/ : Next.js style App Router (page.tsx, layout.tsx)\r\n * - routes/ : FlexiReact v2 routes directory (home.tsx → /, [slug].tsx → /:slug)\r\n */\r\n\r\nimport fs from 'fs';\r\nimport path from 'path';\r\nimport { isServerComponent, isClientComponent, isIsland } from '../utils.js';\r\n\r\n/**\r\n * Route types\r\n */\r\nexport const RouteType = {\r\n PAGE: 'page',\r\n API: 'api',\r\n LAYOUT: 'layout',\r\n LOADING: 'loading',\r\n ERROR: 'error',\r\n NOT_FOUND: 'not-found'\r\n};\r\n\r\n/**\r\n * Builds the complete route tree from all routing directories\r\n */\r\nexport function buildRouteTree(pagesDir, layoutsDir, appDir = null, routesDir = null) {\r\n const projectRoot = path.dirname(pagesDir);\r\n \r\n const routes: {\r\n pages: any[];\r\n api: any[];\r\n layouts: Map<any, any>;\r\n tree: Record<string, any>;\r\n appRoutes: any[];\r\n flexiRoutes: any[];\r\n rootLayout?: string;\r\n } = {\r\n pages: [],\r\n api: [],\r\n layouts: new Map(),\r\n tree: {},\r\n appRoutes: [], // Next.js style app router routes\r\n flexiRoutes: [] // FlexiReact v2 routes/ directory\r\n };\r\n\r\n // 1. Scan routes/ directory (FlexiReact v2 - priority)\r\n const routesDirPath = routesDir || path.join(projectRoot, 'routes');\r\n if (fs.existsSync(routesDirPath)) {\r\n scanRoutesDirectory(routesDirPath, routesDirPath, routes);\r\n }\r\n\r\n // 2. Scan app/ directory (Next.js style App Router)\r\n const appDirPath = appDir || path.join(projectRoot, 'app');\r\n if (fs.existsSync(appDirPath)) {\r\n scanAppDirectory(appDirPath, appDirPath, routes);\r\n }\r\n\r\n // 3. Scan pages/ directory (traditional routing - fallback)\r\n if (fs.existsSync(pagesDir)) {\r\n scanDirectory(pagesDir, pagesDir, routes);\r\n }\r\n \r\n // 4. Scan layouts/ directory\r\n if (fs.existsSync(layoutsDir)) {\r\n scanLayouts(layoutsDir, routes.layouts);\r\n }\r\n\r\n // 5. Check for root layout in app/ directory\r\n const rootLayoutPath = path.join(appDirPath, 'layout.tsx');\r\n const rootLayoutPathJs = path.join(appDirPath, 'layout.jsx');\r\n if (fs.existsSync(rootLayoutPath)) {\r\n routes.rootLayout = rootLayoutPath;\r\n } else if (fs.existsSync(rootLayoutPathJs)) {\r\n routes.rootLayout = rootLayoutPathJs;\r\n }\r\n\r\n // Build route tree for nested routes\r\n routes.tree = buildTree([...routes.flexiRoutes, ...routes.appRoutes, ...routes.pages]);\r\n\r\n return routes;\r\n}\r\n\r\n/**\r\n * Scans routes/ directory for FlexiReact v2 style routing\r\n * \r\n * Convention:\r\n * - home.tsx → /\r\n * - about.tsx → /about\r\n * - blog/index.tsx → /blog\r\n * - blog/[slug].tsx → /blog/:slug\r\n * - (public)/home.tsx → / (route group, not in URL)\r\n * - api/hello.ts → /api/hello (API route)\r\n * - dashboard/layout.tsx → layout for /dashboard/*\r\n */\r\nfunction scanRoutesDirectory(baseDir, currentDir, routes, parentSegments = [], parentLayout = null, parentMiddleware = null) {\r\n const entries = fs.readdirSync(currentDir, { withFileTypes: true });\r\n \r\n // Find special files in current directory\r\n let layoutFile = null;\r\n let loadingFile = null;\r\n let errorFile = null;\r\n let middlewareFile = null;\r\n \r\n for (const entry of entries) {\r\n if (entry.isFile()) {\r\n const name = entry.name.replace(/\\.(jsx|js|tsx|ts)$/, '');\r\n const fullPath = path.join(currentDir, entry.name);\r\n const ext = path.extname(entry.name);\r\n \r\n // Special files\r\n if (name === 'layout') layoutFile = fullPath;\r\n if (name === 'loading') loadingFile = fullPath;\r\n if (name === 'error') errorFile = fullPath;\r\n if (name === '_middleware' || name === 'middleware') middlewareFile = fullPath;\r\n \r\n // Skip special files and non-route files\r\n if (['layout', 'loading', 'error', 'not-found', '_middleware', 'middleware'].includes(name)) continue;\r\n if (!['.tsx', '.jsx', '.ts', '.js'].includes(ext)) continue;\r\n \r\n // API routes (in api/ folder or .ts/.js files in api/)\r\n const relativePath = path.relative(baseDir, currentDir);\r\n const isApiRoute = relativePath.startsWith('api') || relativePath.startsWith('api/');\r\n \r\n if (isApiRoute && ['.ts', '.js'].includes(ext)) {\r\n const apiPath = '/' + [...parentSegments, name === 'index' ? '' : name].filter(Boolean).join('/');\r\n routes.api.push({\r\n type: RouteType.API,\r\n path: apiPath.replace(/\\/+/g, '/') || '/',\r\n filePath: fullPath,\r\n pattern: createRoutePattern(apiPath),\r\n segments: [...parentSegments, name === 'index' ? '' : name].filter(Boolean)\r\n });\r\n continue;\r\n }\r\n \r\n // Page routes\r\n if (['.tsx', '.jsx'].includes(ext)) {\r\n let routePath;\r\n \r\n // home.tsx → /\r\n if (name === 'home' && parentSegments.length === 0) {\r\n routePath = '/';\r\n }\r\n // index.tsx → parent path\r\n else if (name === 'index') {\r\n routePath = '/' + parentSegments.join('/') || '/';\r\n }\r\n // [param].tsx → /:param\r\n else if (name.startsWith('[') && name.endsWith(']')) {\r\n const paramName = name.slice(1, -1);\r\n // Handle catch-all [...slug]\r\n if (paramName.startsWith('...')) {\r\n routePath = '/' + [...parentSegments, '*' + paramName.slice(3)].join('/');\r\n } else {\r\n routePath = '/' + [...parentSegments, ':' + paramName].join('/');\r\n }\r\n }\r\n // regular.tsx → /regular\r\n else {\r\n routePath = '/' + [...parentSegments, name].join('/');\r\n }\r\n \r\n routes.flexiRoutes.push({\r\n type: RouteType.PAGE,\r\n path: routePath.replace(/\\/+/g, '/'),\r\n filePath: fullPath,\r\n pattern: createRoutePattern(routePath),\r\n segments: routePath.split('/').filter(Boolean),\r\n layout: layoutFile || parentLayout,\r\n loading: loadingFile,\r\n error: errorFile,\r\n middleware: middlewareFile || parentMiddleware,\r\n isFlexiRouter: true,\r\n isServerComponent: isServerComponent(fullPath),\r\n isClientComponent: isClientComponent(fullPath),\r\n isIsland: isIsland(fullPath)\r\n });\r\n }\r\n }\r\n }\r\n \r\n // Recursively scan subdirectories\r\n for (const entry of entries) {\r\n if (entry.isDirectory()) {\r\n const fullPath = path.join(currentDir, entry.name);\r\n const dirName = entry.name;\r\n \r\n // Skip special directories\r\n if (dirName.startsWith('_') || dirName.startsWith('.')) continue;\r\n \r\n // Handle route groups (parentheses) - don't add to URL\r\n const isGroup = dirName.startsWith('(') && dirName.endsWith(')');\r\n \r\n // Handle dynamic segments [param]\r\n let segmentName = dirName;\r\n if (dirName.startsWith('[') && dirName.endsWith(']')) {\r\n const paramName = dirName.slice(1, -1);\r\n if (paramName.startsWith('...')) {\r\n segmentName = '*' + paramName.slice(3);\r\n } else {\r\n segmentName = ':' + paramName;\r\n }\r\n }\r\n \r\n const newSegments = isGroup ? parentSegments : [...parentSegments, segmentName];\r\n const newLayout = layoutFile || parentLayout;\r\n const newMiddleware = middlewareFile || parentMiddleware;\r\n \r\n scanRoutesDirectory(baseDir, fullPath, routes, newSegments, newLayout, newMiddleware);\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Scans app directory for Next.js style routing\r\n * Supports: page.tsx, layout.tsx, loading.tsx, error.tsx, not-found.tsx\r\n */\r\nfunction scanAppDirectory(baseDir, currentDir, routes, parentSegments = [], parentLayout = null, parentMiddleware = null) {\r\n const entries = fs.readdirSync(currentDir, { withFileTypes: true });\r\n \r\n // Find special files in current directory\r\n const specialFiles: Record<string, string | null> = {\r\n page: null,\r\n layout: null,\r\n loading: null,\r\n error: null,\r\n notFound: null,\r\n template: null,\r\n middleware: null\r\n };\r\n\r\n for (const entry of entries) {\r\n if (entry.isFile()) {\r\n const name = entry.name.replace(/\\.(jsx|js|tsx|ts)$/, '');\r\n const fullPath = path.join(currentDir, entry.name);\r\n \r\n if (name === 'page') specialFiles.page = fullPath;\r\n if (name === 'layout') specialFiles.layout = fullPath;\r\n if (name === 'loading') specialFiles.loading = fullPath;\r\n if (name === 'error') specialFiles.error = fullPath;\r\n if (name === 'not-found') specialFiles.notFound = fullPath;\r\n if (name === 'template') specialFiles.template = fullPath;\r\n if (name === 'middleware' || name === '_middleware') specialFiles.middleware = fullPath;\r\n }\r\n }\r\n\r\n // If there's a page.tsx, create a route\r\n if (specialFiles.page) {\r\n const routePath = '/' + parentSegments.join('/') || '/';\r\n \r\n routes.appRoutes.push({\r\n type: RouteType.PAGE,\r\n path: routePath.replace(/\\/+/g, '/'),\r\n filePath: specialFiles.page,\r\n pattern: createRoutePattern(routePath),\r\n segments: parentSegments,\r\n layout: specialFiles.layout || parentLayout,\r\n loading: specialFiles.loading,\r\n error: specialFiles.error,\r\n notFound: specialFiles.notFound,\r\n template: specialFiles.template,\r\n middleware: specialFiles.middleware || parentMiddleware,\r\n isAppRouter: true,\r\n isServerComponent: isServerComponent(specialFiles.page),\r\n isClientComponent: isClientComponent(specialFiles.page),\r\n isIsland: isIsland(specialFiles.page)\r\n });\r\n }\r\n\r\n // Recursively scan subdirectories\r\n for (const entry of entries) {\r\n if (entry.isDirectory()) {\r\n const fullPath = path.join(currentDir, entry.name);\r\n \r\n // Handle route groups (parentheses) - don't add to URL\r\n const isGroup = entry.name.startsWith('(') && entry.name.endsWith(')');\r\n \r\n // Handle dynamic segments [param]\r\n let segmentName = entry.name;\r\n if (entry.name.startsWith('[') && entry.name.endsWith(']')) {\r\n // Convert [param] to :param\r\n segmentName = ':' + entry.name.slice(1, -1);\r\n // Handle catch-all [...param]\r\n if (entry.name.startsWith('[...')) {\r\n segmentName = '*' + entry.name.slice(4, -1);\r\n }\r\n // Handle optional catch-all [[...param]]\r\n if (entry.name.startsWith('[[...')) {\r\n segmentName = '*' + entry.name.slice(5, -2);\r\n }\r\n }\r\n \r\n const newSegments = isGroup ? parentSegments : [...parentSegments, segmentName];\r\n const newLayout = specialFiles.layout || parentLayout;\r\n const newMiddleware = specialFiles.middleware || parentMiddleware;\r\n \r\n scanAppDirectory(baseDir, fullPath, routes, newSegments, newLayout, newMiddleware);\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Scans directory recursively for route files\r\n */\r\nfunction scanDirectory(baseDir, currentDir, routes, parentSegments = []) {\r\n const entries = fs.readdirSync(currentDir, { withFileTypes: true });\r\n \r\n // First, find special files in current directory\r\n const specialFiles = {\r\n layout: null,\r\n loading: null,\r\n error: null,\r\n notFound: null\r\n };\r\n\r\n for (const entry of entries) {\r\n if (entry.isFile()) {\r\n const name = entry.name.replace(/\\.(jsx|js|tsx|ts)$/, '');\r\n const fullPath = path.join(currentDir, entry.name);\r\n \r\n if (name === 'layout') specialFiles.layout = fullPath;\r\n if (name === 'loading') specialFiles.loading = fullPath;\r\n if (name === 'error') specialFiles.error = fullPath;\r\n if (name === 'not-found' || name === '404') specialFiles.notFound = fullPath;\r\n }\r\n }\r\n\r\n for (const entry of entries) {\r\n const fullPath = path.join(currentDir, entry.name);\r\n const relativePath = path.relative(baseDir, fullPath);\r\n\r\n if (entry.isDirectory()) {\r\n // Handle route groups (parentheses)\r\n const isGroup = entry.name.startsWith('(') && entry.name.endsWith(')');\r\n const newSegments = isGroup ? parentSegments : [...parentSegments, entry.name];\r\n \r\n scanDirectory(baseDir, fullPath, routes, newSegments);\r\n } else if (entry.isFile()) {\r\n const ext = path.extname(entry.name);\r\n const baseName = path.basename(entry.name, ext);\r\n \r\n // Skip special files (already processed)\r\n if (['layout', 'loading', 'error', 'not-found', '404'].includes(baseName)) {\r\n continue;\r\n }\r\n \r\n if (['.jsx', '.js', '.tsx', '.ts'].includes(ext)) {\r\n const isApi = relativePath.startsWith('api' + path.sep) || relativePath.startsWith('api/');\r\n \r\n if (isApi && ['.js', '.ts'].includes(ext)) {\r\n routes.api.push(createRoute(fullPath, baseDir, specialFiles, RouteType.API));\r\n } else if (!isApi && ['.jsx', '.tsx'].includes(ext)) {\r\n routes.pages.push(createRoute(fullPath, baseDir, specialFiles, RouteType.PAGE));\r\n }\r\n }\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Creates a route object from file path\r\n */\r\nfunction createRoute(filePath, baseDir, specialFiles, type) {\r\n const relativePath = path.relative(baseDir, filePath);\r\n const routePath = filePathToRoute(relativePath);\r\n \r\n return {\r\n type,\r\n path: routePath,\r\n filePath,\r\n pattern: createRoutePattern(routePath),\r\n segments: routePath.split('/').filter(Boolean),\r\n layout: specialFiles.layout,\r\n loading: specialFiles.loading,\r\n error: specialFiles.error,\r\n notFound: specialFiles.notFound,\r\n isServerComponent: isServerComponent(filePath),\r\n isClientComponent: isClientComponent(filePath),\r\n isIsland: isIsland(filePath)\r\n };\r\n}\r\n\r\n/**\r\n * Scans layouts directory\r\n */\r\nfunction scanLayouts(layoutsDir, layoutsMap) {\r\n const entries = fs.readdirSync(layoutsDir, { withFileTypes: true });\r\n \r\n for (const entry of entries) {\r\n if (entry.isFile() && /\\.(jsx|tsx)$/.test(entry.name)) {\r\n const name = entry.name.replace(/\\.(jsx|tsx)$/, '');\r\n layoutsMap.set(name, path.join(layoutsDir, entry.name));\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Converts file path to route path\r\n */\r\nfunction filePathToRoute(filePath) {\r\n let route = filePath.replace(/\\\\/g, '/');\r\n \r\n // Remove extension\r\n route = route.replace(/\\.(jsx|js|tsx|ts)$/, '');\r\n \r\n // Convert [param] to :param\r\n route = route.replace(/\\[\\.\\.\\.([^\\]]+)\\]/g, '*$1'); // Catch-all [...slug]\r\n route = route.replace(/\\[([^\\]]+)\\]/g, ':$1');\r\n \r\n // Handle index files\r\n if (route.endsWith('/index')) {\r\n route = route.slice(0, -6) || '/';\r\n } else if (route === 'index') {\r\n route = '/';\r\n }\r\n \r\n // Handle route groups - remove (groupName) from path\r\n route = route.replace(/\\/?\\([^)]+\\)\\/?/g, '/');\r\n \r\n // Ensure leading slash and clean up\r\n if (!route.startsWith('/')) {\r\n route = '/' + route;\r\n }\r\n route = route.replace(/\\/+/g, '/');\r\n \r\n return route;\r\n}\r\n\r\n/**\r\n * Creates regex pattern for route matching\r\n */\r\nfunction createRoutePattern(routePath) {\r\n let pattern = routePath\r\n .replace(/\\*[^/]*/g, '(.*)') // Catch-all\r\n .replace(/:[^/]+/g, '([^/]+)') // Dynamic segments\r\n .replace(/\\//g, '\\\\/');\r\n \r\n return new RegExp(`^${pattern}$`);\r\n}\r\n\r\n/**\r\n * Builds a tree structure for nested routes\r\n */\r\nfunction buildTree(routes) {\r\n const tree = { children: {}, routes: [] };\r\n \r\n for (const route of routes) {\r\n let current = tree;\r\n \r\n for (const segment of route.segments) {\r\n if (!current.children[segment]) {\r\n current.children[segment] = { children: {}, routes: [] };\r\n }\r\n current = current.children[segment];\r\n }\r\n \r\n current.routes.push(route);\r\n }\r\n \r\n return tree;\r\n}\r\n\r\n/**\r\n * Matches URL path against routes\r\n */\r\nexport function matchRoute(urlPath, routes) {\r\n const normalizedPath = urlPath === '' ? '/' : urlPath.split('?')[0];\r\n \r\n for (const route of routes) {\r\n const match = normalizedPath.match(route.pattern);\r\n \r\n if (match) {\r\n const params = extractParams(route.path, match);\r\n return { ...route, params };\r\n }\r\n }\r\n \r\n return null;\r\n}\r\n\r\n/**\r\n * Extracts parameters from route match\r\n */\r\nfunction extractParams(routePath, match) {\r\n const params = {};\r\n const paramNames = [];\r\n \r\n // Extract param names from route path\r\n const paramRegex = /:([^/]+)|\\*([^/]*)/g;\r\n let paramMatch;\r\n \r\n while ((paramMatch = paramRegex.exec(routePath)) !== null) {\r\n paramNames.push(paramMatch[1] || paramMatch[2] || 'splat');\r\n }\r\n \r\n paramNames.forEach((name, index) => {\r\n params[name] = match[index + 1];\r\n });\r\n \r\n return params;\r\n}\r\n\r\n/**\r\n * Finds all layouts that apply to a route\r\n */\r\nexport function findRouteLayouts(route, layoutsMap) {\r\n const layouts = [];\r\n \r\n // Check for segment-based layouts\r\n let currentPath = '';\r\n for (const segment of route.segments) {\r\n currentPath += '/' + segment;\r\n const layoutName = segment;\r\n \r\n if (layoutsMap.has(layoutName)) {\r\n layouts.push({\r\n name: layoutName,\r\n filePath: layoutsMap.get(layoutName)\r\n });\r\n }\r\n }\r\n \r\n // Check for route-specific layout\r\n if (route.layout) {\r\n layouts.push({\r\n name: 'route',\r\n filePath: route.layout\r\n });\r\n }\r\n \r\n // Check for root layout\r\n if (layoutsMap.has('root')) {\r\n layouts.unshift({\r\n name: 'root',\r\n filePath: layoutsMap.get('root')\r\n });\r\n }\r\n \r\n return layouts;\r\n}\r\n\r\nexport default {\r\n buildRouteTree,\r\n matchRoute,\r\n findRouteLayouts,\r\n RouteType\r\n};\r\n","/**\r\n * FlexiReact Render System v2\r\n * SSR with layouts, loading states, error boundaries, and islands\r\n */\r\n\r\nimport React from 'react';\r\nimport { renderToString, renderToPipeableStream } from 'react-dom/server';\r\nimport { escapeHtml } from '../utils.js';\r\n\r\n/**\r\n * Renders a page with all its layouts and wrappers\r\n */\r\nexport async function renderPage(options) {\r\n const {\r\n Component,\r\n props = {},\r\n layouts = [],\r\n loading = null,\r\n error = null,\r\n islands = [],\r\n title = 'FlexiReact App',\r\n meta = {},\r\n scripts = [],\r\n styles = [],\r\n favicon = null,\r\n isSSG = false,\r\n route = '/',\r\n needsHydration = false\r\n } = options;\r\n\r\n const renderStart = Date.now();\r\n\r\n try {\r\n // Build the component tree - start with the page component\r\n let element: any = React.createElement(Component, props);\r\n \r\n // Wrap with error boundary if error component exists\r\n if (error) {\r\n element = React.createElement(ErrorBoundaryWrapper as any, {\r\n fallback: error,\r\n children: element\r\n });\r\n }\r\n\r\n // Wrap with Suspense if loading component exists (for streaming/async)\r\n if (loading) {\r\n element = React.createElement(React.Suspense as any, {\r\n fallback: React.createElement(loading),\r\n children: element\r\n });\r\n }\r\n \r\n // Wrap with layouts (innermost to outermost)\r\n // Each layout receives children as a prop\r\n for (const layout of [...layouts].reverse()) {\r\n if (layout.Component) {\r\n const LayoutComponent = layout.Component;\r\n element = React.createElement(LayoutComponent, {\r\n ...layout.props\r\n }, element);\r\n }\r\n }\r\n\r\n // Render to string\r\n const content = renderToString(element);\r\n \r\n // Calculate render time\r\n const renderTime = Date.now() - renderStart;\r\n \r\n // Generate island hydration scripts\r\n const islandScripts = generateIslandScripts(islands);\r\n \r\n // Build full HTML document\r\n return buildHtmlDocument({\r\n content,\r\n title,\r\n meta,\r\n scripts: [...scripts, ...islandScripts],\r\n styles,\r\n favicon,\r\n props,\r\n isSSG,\r\n renderTime,\r\n route,\r\n isClientComponent: needsHydration\r\n });\r\n\r\n } catch (err) {\r\n console.error('Render Error:', err);\r\n throw err;\r\n }\r\n}\r\n\r\n/**\r\n * Streaming SSR with React 18\r\n * Renders the page progressively, sending HTML chunks as they become ready\r\n */\r\nexport async function renderPageStream(options: {\r\n Component: React.ComponentType<any>;\r\n props?: Record<string, any>;\r\n layouts?: Array<{ Component: React.ComponentType<any>; props?: Record<string, any> }>;\r\n loading?: React.ComponentType | null;\r\n error?: React.ComponentType<{ error: Error }> | null;\r\n title?: string;\r\n meta?: Record<string, string>;\r\n scripts?: Array<string | { src?: string; content?: string; type?: string }>;\r\n styles?: Array<string | { content: string }>;\r\n favicon?: string | null;\r\n route?: string;\r\n onShellReady?: () => void;\r\n onAllReady?: () => void;\r\n onError?: (error: Error) => void;\r\n}): Promise<{ stream: NodeJS.ReadableStream; shellReady: Promise<void> }> {\r\n const {\r\n Component,\r\n props = {},\r\n layouts = [],\r\n loading = null,\r\n error = null,\r\n title = 'FlexiReact App',\r\n meta = {},\r\n scripts = [],\r\n styles = [],\r\n favicon = null,\r\n route = '/',\r\n onShellReady,\r\n onAllReady,\r\n onError\r\n } = options;\r\n\r\n const renderStart = Date.now();\r\n\r\n // Build the component tree\r\n let element: any = React.createElement(Component, props);\r\n\r\n // Wrap with error boundary if error component exists\r\n if (error) {\r\n element = React.createElement(ErrorBoundaryWrapper as any, {\r\n fallback: error,\r\n children: element\r\n });\r\n }\r\n\r\n // Wrap with Suspense if loading component exists\r\n if (loading) {\r\n element = React.createElement(React.Suspense as any, {\r\n fallback: React.createElement(loading),\r\n children: element\r\n });\r\n }\r\n\r\n // Wrap with layouts\r\n for (const layout of [...layouts].reverse()) {\r\n if (layout.Component) {\r\n element = React.createElement(layout.Component, layout.props, element);\r\n }\r\n }\r\n\r\n // Create the full document wrapper\r\n const DocumentWrapper = ({ children }: { children: React.ReactNode }) => {\r\n return React.createElement('html', { lang: 'en', className: 'dark' },\r\n React.createElement('head', null,\r\n React.createElement('meta', { charSet: 'UTF-8' }),\r\n React.createElement('meta', { name: 'viewport', content: 'width=device-width, initial-scale=1.0' }),\r\n React.createElement('title', null, title),\r\n favicon && React.createElement('link', { rel: 'icon', href: favicon }),\r\n ...Object.entries(meta).map(([name, content]) => \r\n React.createElement('meta', { key: name, name, content })\r\n ),\r\n ...styles.map((style, i) => \r\n typeof style === 'string'\r\n ? React.createElement('link', { key: i, rel: 'stylesheet', href: style })\r\n : React.createElement('style', { key: i, dangerouslySetInnerHTML: { __html: style.content } })\r\n )\r\n ),\r\n React.createElement('body', null,\r\n React.createElement('div', { id: 'root' }, children),\r\n ...scripts.map((script, i) => \r\n typeof script === 'string'\r\n ? React.createElement('script', { key: i, src: script })\r\n : script.src\r\n ? React.createElement('script', { key: i, src: script.src, type: script.type })\r\n : React.createElement('script', { key: i, type: script.type, dangerouslySetInnerHTML: { __html: script.content } })\r\n )\r\n )\r\n );\r\n };\r\n\r\n const fullElement = React.createElement(DocumentWrapper, null, element);\r\n\r\n // Create streaming render\r\n let shellReadyResolve: () => void;\r\n const shellReady = new Promise<void>((resolve) => {\r\n shellReadyResolve = resolve;\r\n });\r\n\r\n const { pipe, abort } = renderToPipeableStream(fullElement, {\r\n onShellReady() {\r\n const renderTime = Date.now() - renderStart;\r\n console.log(`⚡ Shell ready in ${renderTime}ms`);\r\n shellReadyResolve();\r\n onShellReady?.();\r\n },\r\n onAllReady() {\r\n const renderTime = Date.now() - renderStart;\r\n console.log(`✨ All content ready in ${renderTime}ms`);\r\n onAllReady?.();\r\n },\r\n onError(err: Error) {\r\n console.error('Streaming SSR Error:', err);\r\n onError?.(err);\r\n }\r\n });\r\n\r\n // Create a passthrough stream\r\n const { PassThrough } = await import('stream');\r\n const passThrough = new PassThrough();\r\n \r\n // Pipe the render stream to our passthrough\r\n pipe(passThrough);\r\n\r\n return {\r\n stream: passThrough,\r\n shellReady\r\n };\r\n}\r\n\r\n/**\r\n * Render to stream for HTTP response\r\n * Use this in the server to stream HTML to the client\r\n */\r\nexport function streamToResponse(\r\n res: { write: (chunk: string) => void; end: () => void },\r\n stream: NodeJS.ReadableStream,\r\n options: { onFinish?: () => void } = {}\r\n): void {\r\n stream.on('data', (chunk) => {\r\n res.write(chunk.toString());\r\n });\r\n\r\n stream.on('end', () => {\r\n res.end();\r\n options.onFinish?.();\r\n });\r\n\r\n stream.on('error', (err) => {\r\n console.error('Stream error:', err);\r\n res.end();\r\n });\r\n}\r\n\r\n/**\r\n * Error Boundary Wrapper for SSR\r\n */\r\ninterface ErrorBoundaryProps {\r\n fallback: React.ComponentType<{ error: Error }>;\r\n children: React.ReactNode;\r\n}\r\n\r\ninterface ErrorBoundaryState {\r\n hasError: boolean;\r\n error: Error | null;\r\n}\r\n\r\nclass ErrorBoundaryWrapper extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {\r\n constructor(props: ErrorBoundaryProps) {\r\n super(props);\r\n this.state = { hasError: false, error: null };\r\n }\r\n\r\n static getDerivedStateFromError(error: Error): ErrorBoundaryState {\r\n return { hasError: true, error };\r\n }\r\n\r\n render() {\r\n if (this.state.hasError) {\r\n const FallbackComponent = this.props.fallback;\r\n return React.createElement(FallbackComponent, { error: this.state.error! });\r\n }\r\n return this.props.children;\r\n }\r\n}\r\n\r\n/**\r\n * Generates hydration scripts for islands\r\n */\r\nfunction generateIslandScripts(islands) {\r\n if (!islands.length) return [];\r\n \r\n const scripts = [];\r\n \r\n for (const island of islands) {\r\n scripts.push({\r\n type: 'module',\r\n content: `\r\n import { hydrateIsland } from '/_flexi/client.js';\r\n import ${island.name} from '${island.clientPath}';\r\n hydrateIsland('${island.id}', ${island.name}, ${JSON.stringify(island.props)});\r\n `\r\n });\r\n }\r\n \r\n return scripts;\r\n}\r\n\r\n/**\r\n * Generates the Dev Toolbar HTML (FlexiReact v2 - Premium DevTools)\r\n */\r\ninterface DevToolbarOptions {\r\n renderTime?: number;\r\n pageType?: string;\r\n route?: string;\r\n hasError?: boolean;\r\n isHydrated?: boolean;\r\n errorMessage?: string | null;\r\n componentName?: string | null;\r\n}\r\n\r\nfunction generateDevToolbar(options: DevToolbarOptions = {}) {\r\n const { \r\n renderTime = 0, \r\n pageType = 'SSR', \r\n route = '/',\r\n hasError = false,\r\n isHydrated = false,\r\n errorMessage = null,\r\n componentName = null\r\n } = options;\r\n\r\n const timeColor = renderTime < 50 ? '#00FF9C' : renderTime < 200 ? '#fbbf24' : '#ef4444';\r\n const timeLabel = renderTime < 50 ? 'Fast' : renderTime < 200 ? 'OK' : 'Slow';\r\n\r\n return `\r\n<!-- FlexiReact v2 Dev Toolbar -->\r\n<div id=\"flexi-dev-toolbar\" class=\"flexi-dev-collapsed\">\r\n <style>\r\n #flexi-dev-toolbar {\r\n position: fixed;\r\n bottom: 16px;\r\n left: 16px;\r\n z-index: 99999;\r\n font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;\r\n font-size: 13px;\r\n }\r\n \r\n /* Main Button */\r\n .flexi-dev-trigger {\r\n display: flex;\r\n align-items: center;\r\n gap: 8px;\r\n padding: 8px 12px;\r\n background: rgba(10, 10, 10, 0.95);\r\n backdrop-filter: blur(20px);\r\n border: 1px solid rgba(0, 255, 156, 0.2);\r\n border-radius: 10px;\r\n color: #fafafa;\r\n cursor: pointer;\r\n transition: all 0.2s cubic-bezier(0.16, 1, 0.3, 1);\r\n box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);\r\n }\r\n \r\n .flexi-dev-trigger:hover {\r\n border-color: rgba(0, 255, 156, 0.5);\r\n box-shadow: 0 4px 30px rgba(0, 0, 0, 0.6), 0 0 20px rgba(0, 255, 156, 0.15);\r\n transform: translateY(-2px);\r\n }\r\n \r\n .flexi-dev-trigger.has-error {\r\n border-color: rgba(239, 68, 68, 0.5);\r\n box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5), 0 0 15px rgba(239, 68, 68, 0.2);\r\n }\r\n \r\n .flexi-dev-logo {\r\n width: 20px;\r\n height: 20px;\r\n background: linear-gradient(135deg, #00FF9C, #00D68F);\r\n border-radius: 5px;\r\n display: flex;\r\n align-items: center;\r\n justify-content: center;\r\n font-weight: 800;\r\n font-size: 11px;\r\n color: #000;\r\n }\r\n \r\n .flexi-dev-trigger.has-error .flexi-dev-logo {\r\n background: linear-gradient(135deg, #ef4444, #dc2626);\r\n }\r\n \r\n .flexi-dev-indicator {\r\n display: flex;\r\n align-items: center;\r\n gap: 6px;\r\n }\r\n \r\n .flexi-dev-dot {\r\n width: 6px;\r\n height: 6px;\r\n border-radius: 50%;\r\n background: #00FF9C;\r\n box-shadow: 0 0 8px rgba(0, 255, 156, 0.6);\r\n }\r\n \r\n .flexi-dev-dot.error {\r\n background: #ef4444;\r\n box-shadow: 0 0 8px rgba(239, 68, 68, 0.6);\r\n animation: errorPulse 1s infinite;\r\n }\r\n \r\n @keyframes errorPulse {\r\n 0%, 100% { opacity: 1; }\r\n 50% { opacity: 0.4; }\r\n }\r\n \r\n .flexi-dev-time {\r\n font-size: 11px;\r\n font-weight: 600;\r\n color: ${timeColor};\r\n font-variant-numeric: tabular-nums;\r\n }\r\n \r\n /* Panel */\r\n .flexi-dev-panel {\r\n position: absolute;\r\n bottom: calc(100% + 8px);\r\n left: 0;\r\n min-width: 340px;\r\n background: rgba(10, 10, 10, 0.98);\r\n backdrop-filter: blur(20px);\r\n border: 1px solid rgba(255, 255, 255, 0.08);\r\n border-radius: 16px;\r\n opacity: 0;\r\n visibility: hidden;\r\n transform: translateY(8px) scale(0.96);\r\n transition: all 0.25s cubic-bezier(0.16, 1, 0.3, 1);\r\n box-shadow: 0 20px 50px rgba(0, 0, 0, 0.7);\r\n overflow: hidden;\r\n }\r\n \r\n #flexi-dev-toolbar.flexi-dev-open .flexi-dev-panel {\r\n opacity: 1;\r\n visibility: visible;\r\n transform: translateY(0) scale(1);\r\n }\r\n \r\n /* Header */\r\n .flexi-dev-header {\r\n display: flex;\r\n align-items: center;\r\n gap: 10px;\r\n padding: 14px 16px;\r\n background: linear-gradient(135deg, rgba(0, 255, 156, 0.08), rgba(0, 214, 143, 0.04));\r\n border-bottom: 1px solid rgba(255, 255, 255, 0.05);\r\n }\r\n \r\n .flexi-dev-header-logo {\r\n width: 26px;\r\n height: 26px;\r\n background: linear-gradient(135deg, #00FF9C, #00D68F);\r\n border-radius: 7px;\r\n display: flex;\r\n align-items: center;\r\n justify-content: center;\r\n font-weight: 800;\r\n font-size: 13px;\r\n color: #000;\r\n }\r\n \r\n .flexi-dev-header-info {\r\n flex: 1;\r\n }\r\n \r\n .flexi-dev-header-title {\r\n font-weight: 700;\r\n font-size: 14px;\r\n color: #fafafa;\r\n }\r\n \r\n .flexi-dev-header-subtitle {\r\n font-size: 11px;\r\n color: #52525b;\r\n margin-top: 1px;\r\n }\r\n \r\n .flexi-dev-close {\r\n width: 24px;\r\n height: 24px;\r\n display: flex;\r\n align-items: center;\r\n justify-content: center;\r\n background: rgba(255, 255, 255, 0.05);\r\n border: none;\r\n border-radius: 6px;\r\n color: #71717a;\r\n cursor: pointer;\r\n transition: all 0.15s;\r\n }\r\n \r\n .flexi-dev-close:hover {\r\n background: rgba(255, 255, 255, 0.1);\r\n color: #fafafa;\r\n }\r\n \r\n /* Content */\r\n .flexi-dev-content {\r\n padding: 12px 16px;\r\n }\r\n \r\n .flexi-dev-section {\r\n margin-bottom: 12px;\r\n }\r\n \r\n .flexi-dev-section:last-child {\r\n margin-bottom: 0;\r\n }\r\n \r\n .flexi-dev-section-title {\r\n font-size: 10px;\r\n font-weight: 600;\r\n color: #52525b;\r\n text-transform: uppercase;\r\n letter-spacing: 0.5px;\r\n margin-bottom: 8px;\r\n }\r\n \r\n .flexi-dev-grid {\r\n display: grid;\r\n grid-template-columns: 1fr 1fr;\r\n gap: 8px;\r\n }\r\n \r\n .flexi-dev-stat {\r\n background: rgba(255, 255, 255, 0.03);\r\n border: 1px solid rgba(255, 255, 255, 0.05);\r\n border-radius: 10px;\r\n padding: 10px 12px;\r\n }\r\n \r\n .flexi-dev-stat-label {\r\n font-size: 10px;\r\n color: #52525b;\r\n margin-bottom: 4px;\r\n }\r\n \r\n .flexi-dev-stat-value {\r\n font-size: 14px;\r\n font-weight: 600;\r\n color: #fafafa;\r\n }\r\n \r\n .flexi-dev-stat-value.success { color: #00FF9C; }\r\n .flexi-dev-stat-value.warning { color: #fbbf24; }\r\n .flexi-dev-stat-value.error { color: #ef4444; }\r\n \r\n /* Badges */\r\n .flexi-dev-badge {\r\n display: inline-flex;\r\n align-items: center;\r\n padding: 3px 8px;\r\n border-radius: 5px;\r\n font-size: 10px;\r\n font-weight: 700;\r\n letter-spacing: 0.3px;\r\n }\r\n \r\n .flexi-dev-badge.ssr { background: rgba(251, 191, 36, 0.15); color: #fbbf24; }\r\n .flexi-dev-badge.ssg { background: rgba(0, 255, 156, 0.15); color: #00FF9C; }\r\n .flexi-dev-badge.csr { background: rgba(6, 182, 212, 0.15); color: #06b6d4; }\r\n .flexi-dev-badge.isr { background: rgba(139, 92, 246, 0.15); color: #a78bfa; }\r\n \r\n /* Error Display */\r\n .flexi-dev-error {\r\n background: rgba(239, 68, 68, 0.1);\r\n border: 1px solid rgba(239, 68, 68, 0.2);\r\n border-radius: 10px;\r\n padding: 12px;\r\n margin-top: 8px;\r\n }\r\n \r\n .flexi-dev-error-title {\r\n display: flex;\r\n align-items: center;\r\n gap: 6px;\r\n font-size: 11px;\r\n font-weight: 600;\r\n color: #ef4444;\r\n margin-bottom: 6px;\r\n }\r\n \r\n .flexi-dev-error-message {\r\n font-size: 12px;\r\n color: #fca5a5;\r\n font-family: 'SF Mono', 'Fira Code', monospace;\r\n word-break: break-word;\r\n line-height: 1.5;\r\n }\r\n \r\n /* Footer */\r\n .flexi-dev-footer {\r\n display: flex;\r\n gap: 6px;\r\n padding: 12px 16px;\r\n background: rgba(0, 0, 0, 0.3);\r\n border-top: 1px solid rgba(255, 255, 255, 0.05);\r\n }\r\n \r\n .flexi-dev-action {\r\n flex: 1;\r\n padding: 8px;\r\n background: rgba(255, 255, 255, 0.03);\r\n border: 1px solid rgba(255, 255, 255, 0.06);\r\n border-radius: 8px;\r\n color: #71717a;\r\n font-size: 11px;\r\n font-weight: 500;\r\n text-decoration: none;\r\n text-align: center;\r\n cursor: pointer;\r\n transition: all 0.15s;\r\n }\r\n \r\n .flexi-dev-action:hover {\r\n background: rgba(0, 255, 156, 0.1);\r\n border-color: rgba(0, 255, 156, 0.2);\r\n color: #00FF9C;\r\n }\r\n </style>\r\n \r\n <button class=\"flexi-dev-trigger ${hasError ? 'has-error' : ''}\" onclick=\"this.parentElement.classList.toggle('flexi-dev-open')\">\r\n <div class=\"flexi-dev-logo\">F</div>\r\n <div class=\"flexi-dev-indicator\">\r\n <div class=\"flexi-dev-dot ${hasError ? 'error' : ''}\"></div>\r\n <span class=\"flexi-dev-time\">${renderTime}ms</span>\r\n </div>\r\n </button>\r\n \r\n <div class=\"flexi-dev-panel\">\r\n <div class=\"flexi-dev-header\">\r\n <div class=\"flexi-dev-header-logo\">F</div>\r\n <div class=\"flexi-dev-header-info\">\r\n <div class=\"flexi-dev-header-title\">FlexiReact</div>\r\n <div class=\"flexi-dev-header-subtitle\">v2.0.0 • Development</div>\r\n </div>\r\n <button class=\"flexi-dev-close\" onclick=\"this.closest('#flexi-dev-toolbar').classList.remove('flexi-dev-open')\">✕</button>\r\n </div>\r\n \r\n <div class=\"flexi-dev-content\">\r\n <div class=\"flexi-dev-section\">\r\n <div class=\"flexi-dev-section-title\">Page Info</div>\r\n <div class=\"flexi-dev-grid\">\r\n <div class=\"flexi-dev-stat\">\r\n <div class=\"flexi-dev-stat-label\">Route</div>\r\n <div class=\"flexi-dev-stat-value\">${route}</div>\r\n </div>\r\n <div class=\"flexi-dev-stat\">\r\n <div class=\"flexi-dev-stat-label\">Type</div>\r\n <div class=\"flexi-dev-stat-value\"><span class=\"flexi-dev-badge ${pageType.toLowerCase()}\">${pageType}</span></div>\r\n </div>\r\n </div>\r\n </div>\r\n \r\n <div class=\"flexi-dev-section\">\r\n <div class=\"flexi-dev-section-title\">Performance</div>\r\n <div class=\"flexi-dev-grid\">\r\n <div class=\"flexi-dev-stat\">\r\n <div class=\"flexi-dev-stat-label\">Render Time</div>\r\n <div class=\"flexi-dev-stat-value ${renderTime < 50 ? 'success' : renderTime < 200 ? 'warning' : 'error'}\">${renderTime}ms <small style=\"color:#52525b\">${timeLabel}</small></div>\r\n </div>\r\n <div class=\"flexi-dev-stat\">\r\n <div class=\"flexi-dev-stat-label\">Hydration</div>\r\n <div class=\"flexi-dev-stat-value\" id=\"flexi-hydration-status\">${isHydrated ? '✓ Client' : '○ Server'}</div>\r\n </div>\r\n </div>\r\n </div>\r\n \r\n ${hasError && errorMessage ? `\r\n <div class=\"flexi-dev-error\">\r\n <div class=\"flexi-dev-error-title\">\r\n <span>⚠</span> Runtime Error\r\n </div>\r\n <div class=\"flexi-dev-error-message\">${errorMessage}</div>\r\n </div>\r\n ` : ''}\r\n </div>\r\n \r\n <div class=\"flexi-dev-footer\">\r\n <a href=\"/_flexi/routes\" class=\"flexi-dev-action\">Routes</a>\r\n <button class=\"flexi-dev-action\" onclick=\"location.reload()\">Refresh</button>\r\n <a href=\"https://github.com/flexireact/flexireact\" target=\"_blank\" class=\"flexi-dev-action\">Docs ↗</a>\r\n </div>\r\n </div>\r\n</div>\r\n\r\n<script>\r\n // FlexiReact v2 DevTools\r\n window.__FLEXI_DEV__ = {\r\n version: '2.0.0',\r\n renderTime: ${renderTime},\r\n pageType: '${pageType}',\r\n route: '${route}',\r\n hydrated: false,\r\n errors: []\r\n };\r\n \r\n // Track hydration\r\n const root = document.getElementById('root');\r\n if (root) {\r\n const observer = new MutationObserver(() => {\r\n if (root.children.length > 0) {\r\n window.__FLEXI_DEV__.hydrated = true;\r\n const el = document.getElementById('flexi-hydration-status');\r\n if (el) el.textContent = '✓ Client';\r\n observer.disconnect();\r\n }\r\n });\r\n observer.observe(root, { childList: true, subtree: true });\r\n }\r\n \r\n // Capture runtime errors\r\n window.addEventListener('error', (e) => {\r\n window.__FLEXI_DEV__.errors.push({\r\n message: e.message,\r\n file: e.filename,\r\n line: e.lineno,\r\n col: e.colno\r\n });\r\n console.error('%c[FlexiReact Error]', 'color: #ef4444; font-weight: bold;', e.message);\r\n });\r\n \r\n // Console branding\r\n console.log(\r\n '%c ⚡ FlexiReact v2 %c ${pageType} %c ${renderTime}ms ',\r\n 'background: #00FF9C; color: #000; font-weight: bold; padding: 2px 6px; border-radius: 4px 0 0 4px;',\r\n 'background: #1e1e1e; color: #fafafa; padding: 2px 6px;',\r\n 'background: ${timeColor}20; color: ${timeColor}; padding: 2px 6px; border-radius: 0 4px 4px 0;'\r\n );\r\n</script>\r\n`;\r\n}\r\n\r\n/**\r\n * Builds complete HTML document\r\n */\r\nfunction buildHtmlDocument(options) {\r\n const {\r\n content,\r\n title,\r\n meta = {},\r\n scripts = [],\r\n styles = [],\r\n props = {},\r\n isSSG = false,\r\n renderTime = 0,\r\n route = '/',\r\n isClientComponent = false,\r\n favicon = null\r\n } = options;\r\n\r\n const metaTags = Object.entries(meta)\r\n .map(([name, content]) => {\r\n if (name.startsWith('og:')) {\r\n return `<meta property=\"${escapeHtml(name)}\" content=\"${escapeHtml(content)}\">`;\r\n }\r\n return `<meta name=\"${escapeHtml(name)}\" content=\"${escapeHtml(content)}\">`;\r\n })\r\n .join('\\n ');\r\n\r\n const styleTags = styles\r\n .map(style => {\r\n if (typeof style === 'string') {\r\n return `<link rel=\"stylesheet\" href=\"${escapeHtml(style)}\">`;\r\n }\r\n return `<style>${style.content}</style>`;\r\n })\r\n .join('\\n ');\r\n\r\n const scriptTags = scripts\r\n .map(script => {\r\n if (typeof script === 'string') {\r\n return `<script src=\"${escapeHtml(script)}\"></script>`;\r\n }\r\n const type = script.type ? ` type=\"${script.type}\"` : '';\r\n if (script.src) {\r\n return `<script${type} src=\"${escapeHtml(script.src)}\"></script>`;\r\n }\r\n return `<script${type}>${script.content}</script>`;\r\n })\r\n .join('\\n ');\r\n\r\n // FlexiReact SVG favicon (properly encoded)\r\n const faviconSvg = encodeURIComponent(`<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 32 32\"><rect width=\"32\" height=\"32\" rx=\"8\" fill=\"#00FF9C\"/><text x=\"50%\" y=\"50%\" dominant-baseline=\"central\" text-anchor=\"middle\" fill=\"#000\" font-family=\"system-ui\" font-weight=\"bold\" font-size=\"16\">F</text></svg>`);\r\n\r\n // Generate Dev Toolbar for development mode\r\n const isDev = process.env.NODE_ENV !== 'production';\r\n const pageType = isSSG ? 'SSG' : isClientComponent ? 'CSR' : 'SSR';\r\n const devToolbar = isDev ? generateDevToolbar({ \r\n renderTime, \r\n pageType, \r\n route,\r\n isHydrated: isClientComponent\r\n }) : '';\r\n\r\n // Determine favicon link\r\n const faviconLink = favicon \r\n ? `<link rel=\"icon\" href=\"${escapeHtml(favicon)}\">`\r\n : `<link rel=\"icon\" type=\"image/svg+xml\" href=\"data:image/svg+xml,${faviconSvg}\">`;\r\n\r\n return `<!DOCTYPE html>\r\n<html lang=\"en\" class=\"dark\">\r\n<head>\r\n <meta charset=\"UTF-8\">\r\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\r\n <title>${escapeHtml(title)}</title>\r\n ${faviconLink}\r\n ${metaTags}\r\n <style>\r\n :root { --flexi-bg: #0f172a; --flexi-fg: #f8fafc; }\r\n html, body { background-color: #0f172a; color: #f8fafc; min-height: 100vh; margin: 0; }\r\n </style>\r\n ${styleTags}\r\n <script>\r\n (function() {\r\n var theme = localStorage.getItem('theme');\r\n if (theme === 'light') {\r\n document.documentElement.classList.remove('dark');\r\n document.documentElement.style.backgroundColor = '#ffffff';\r\n document.documentElement.style.color = '#0f172a';\r\n document.body.style.backgroundColor = '#ffffff';\r\n document.body.style.color = '#0f172a';\r\n }\r\n })();\r\n </script>\r\n</head>\r\n<body>\r\n <div id=\"root\">${content}</div>\r\n <script>\r\n window.__FLEXI_DATA__ = ${JSON.stringify({ props, isSSG })};\r\n </script>\r\n ${scriptTags}\r\n ${devToolbar}\r\n</body>\r\n</html>`;\r\n}\r\n\r\n/**\r\n * Renders an error page with beautiful styling (FlexiReact v2)\r\n */\r\nexport function renderError(statusCode, message, stack = null) {\r\n const showStack = process.env.NODE_ENV !== 'production' && stack;\r\n const isDev = process.env.NODE_ENV !== 'production';\r\n \r\n // Parse error for better display\r\n const errorDetails = parseErrorStack(stack);\r\n \r\n // Different messages for different status codes\r\n const errorMessages = {\r\n 404: { title: 'Page Not Found', icon: 'search', color: '#00FF9C', desc: 'The page you\\'re looking for doesn\\'t exist or has been moved.' },\r\n 500: { title: 'Server Error', icon: 'alert', color: '#ef4444', desc: 'Something went wrong on our end.' },\r\n 403: { title: 'Forbidden', icon: 'lock', color: '#f59e0b', desc: 'You don\\'t have permission to access this resource.' },\r\n 401: { title: 'Unauthorized', icon: 'key', color: '#8b5cf6', desc: 'Please log in to access this page.' },\r\n };\r\n \r\n const errorInfo = errorMessages[statusCode] || { title: 'Error', icon: 'alert', color: '#ef4444', desc: message };\r\n \r\n // Generate error frames HTML for dev mode\r\n const errorFramesHtml = showStack && errorDetails?.frames?.length > 0 \r\n ? errorDetails.frames.slice(0, 5).map((frame, i) => `\r\n <div class=\"error-frame ${i === 0 ? 'error-frame-first' : ''}\">\r\n <div class=\"error-frame-fn\">${escapeHtml(frame.fn)}</div>\r\n <div class=\"error-frame-loc\">${escapeHtml(frame.file)}:${frame.line}:${frame.col}</div>\r\n </div>\r\n `).join('')\r\n : '';\r\n\r\n return `<!DOCTYPE html>\r\n<html lang=\"en\">\r\n<head>\r\n <meta charset=\"UTF-8\">\r\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\r\n <title>${statusCode} - ${errorInfo.title} | FlexiReact</title>\r\n <link rel=\"icon\" type=\"image/svg+xml\" href=\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='8' fill='%2300FF9C'/%3E%3Ctext x='50%25' y='50%25' dominant-baseline='central' text-anchor='middle' fill='%23000' font-family='system-ui' font-weight='bold' font-size='16'%3EF%3C/text%3E%3C/svg%3E\">\r\n <style>\r\n * { margin: 0; padding: 0; box-sizing: border-box; }\r\n \r\n body {\r\n font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\r\n min-height: 100vh;\r\n background: #0a0a0a;\r\n color: #fafafa;\r\n display: flex;\r\n align-items: center;\r\n justify-content: center;\r\n overflow-x: hidden;\r\n }\r\n \r\n /* Animated background */\r\n .bg-pattern {\r\n position: fixed;\r\n inset: 0;\r\n background-image: \r\n radial-gradient(circle at 25% 25%, rgba(0, 255, 156, 0.03) 0%, transparent 50%),\r\n radial-gradient(circle at 75% 75%, rgba(99, 102, 241, 0.03) 0%, transparent 50%);\r\n pointer-events: none;\r\n }\r\n \r\n .bg-grid {\r\n position: fixed;\r\n inset: 0;\r\n background-image: \r\n linear-gradient(rgba(255, 255, 255, 0.02) 1px, transparent 1px),\r\n linear-gradient(90deg, rgba(255, 255, 255, 0.02) 1px, transparent 1px);\r\n background-size: 64px 64px;\r\n pointer-events: none;\r\n }\r\n \r\n .container {\r\n position: relative;\r\n width: 100%;\r\n max-width: ${showStack ? '800px' : '500px'};\r\n padding: 2rem;\r\n animation: fadeIn 0.6s cubic-bezier(0.16, 1, 0.3, 1);\r\n }\r\n \r\n @keyframes fadeIn {\r\n from { opacity: 0; transform: translateY(30px); }\r\n to { opacity: 1; transform: translateY(0); }\r\n }\r\n \r\n /* Error Card */\r\n .error-card {\r\n background: linear-gradient(145deg, rgba(23, 23, 23, 0.9), rgba(10, 10, 10, 0.95));\r\n border: 1px solid rgba(255, 255, 255, 0.08);\r\n border-radius: 24px;\r\n padding: 3rem;\r\n text-align: center;\r\n backdrop-filter: blur(20px);\r\n box-shadow: \r\n 0 0 0 1px rgba(255, 255, 255, 0.05),\r\n 0 20px 50px -20px rgba(0, 0, 0, 0.5),\r\n 0 0 100px -50px ${errorInfo.color}40;\r\n }\r\n \r\n /* Logo */\r\n .logo {\r\n width: 56px;\r\n height: 56px;\r\n background: linear-gradient(135deg, #00FF9C, #00D68F);\r\n border-radius: 14px;\r\n display: flex;\r\n align-items: center;\r\n justify-content: center;\r\n margin: 0 auto 2rem;\r\n font-weight: 800;\r\n font-size: 24px;\r\n color: #000;\r\n box-shadow: 0 0 30px rgba(0, 255, 156, 0.3);\r\n }\r\n \r\n /* Error Code */\r\n .error-code {\r\n font-size: 7rem;\r\n font-weight: 800;\r\n line-height: 1;\r\n background: linear-gradient(135deg, ${errorInfo.color}, ${errorInfo.color}99);\r\n -webkit-background-clip: text;\r\n -webkit-text-fill-color: transparent;\r\n background-clip: text;\r\n margin-bottom: 0.5rem;\r\n letter-spacing: -4px;\r\n }\r\n \r\n .error-title {\r\n font-size: 1.5rem;\r\n font-weight: 600;\r\n color: #fafafa;\r\n margin-bottom: 0.75rem;\r\n }\r\n \r\n .error-desc {\r\n font-size: 1rem;\r\n color: #71717a;\r\n line-height: 1.6;\r\n margin-bottom: 2rem;\r\n }\r\n \r\n /* Buttons */\r\n .buttons {\r\n display: flex;\r\n gap: 12px;\r\n justify-content: center;\r\n flex-wrap: wrap;\r\n }\r\n \r\n .btn {\r\n display: inline-flex;\r\n align-items: center;\r\n gap: 8px;\r\n padding: 12px 24px;\r\n border-radius: 12px;\r\n font-weight: 600;\r\n font-size: 14px;\r\n text-decoration: none;\r\n transition: all 0.2s cubic-bezier(0.16, 1, 0.3, 1);\r\n border: none;\r\n cursor: pointer;\r\n }\r\n \r\n .btn-primary {\r\n background: #00FF9C;\r\n color: #000;\r\n box-shadow: 0 0 20px rgba(0, 255, 156, 0.3);\r\n }\r\n \r\n .btn-primary:hover {\r\n transform: translateY(-2px);\r\n box-shadow: 0 0 30px rgba(0, 255, 156, 0.5);\r\n }\r\n \r\n .btn-secondary {\r\n background: rgba(255, 255, 255, 0.06);\r\n color: #a1a1aa;\r\n border: 1px solid rgba(255, 255, 255, 0.1);\r\n }\r\n \r\n .btn-secondary:hover {\r\n background: rgba(255, 255, 255, 0.1);\r\n color: #fafafa;\r\n border-color: rgba(255, 255, 255, 0.2);\r\n }\r\n \r\n /* Error Stack (Dev Mode) */\r\n .error-stack {\r\n margin-top: 2rem;\r\n text-align: left;\r\n }\r\n \r\n .error-stack-header {\r\n display: flex;\r\n align-items: center;\r\n gap: 8px;\r\n margin-bottom: 12px;\r\n font-size: 12px;\r\n font-weight: 600;\r\n color: #ef4444;\r\n text-transform: uppercase;\r\n letter-spacing: 0.5px;\r\n }\r\n \r\n .error-stack-header::before {\r\n content: '';\r\n width: 8px;\r\n height: 8px;\r\n background: #ef4444;\r\n border-radius: 50%;\r\n animation: pulse 2s infinite;\r\n }\r\n \r\n @keyframes pulse {\r\n 0%, 100% { opacity: 1; }\r\n 50% { opacity: 0.5; }\r\n }\r\n \r\n .error-message {\r\n background: rgba(239, 68, 68, 0.1);\r\n border: 1px solid rgba(239, 68, 68, 0.2);\r\n border-radius: 12px;\r\n padding: 16px;\r\n margin-bottom: 12px;\r\n font-family: 'SF Mono', 'Fira Code', monospace;\r\n font-size: 13px;\r\n color: #fca5a5;\r\n word-break: break-word;\r\n }\r\n \r\n .error-frames {\r\n background: rgba(0, 0, 0, 0.4);\r\n border: 1px solid rgba(255, 255, 255, 0.05);\r\n border-radius: 12px;\r\n overflow: hidden;\r\n }\r\n \r\n .error-frame {\r\n padding: 12px 16px;\r\n border-bottom: 1px solid rgba(255, 255, 255, 0.05);\r\n font-family: 'SF Mono', 'Fira Code', monospace;\r\n font-size: 12px;\r\n }\r\n \r\n .error-frame:last-child {\r\n border-bottom: none;\r\n }\r\n \r\n .error-frame-first {\r\n background: rgba(239, 68, 68, 0.05);\r\n }\r\n \r\n .error-frame-fn {\r\n color: #fafafa;\r\n font-weight: 500;\r\n margin-bottom: 4px;\r\n }\r\n \r\n .error-frame-loc {\r\n color: #52525b;\r\n font-size: 11px;\r\n }\r\n \r\n /* Dev Badge */\r\n .dev-badge {\r\n position: fixed;\r\n bottom: 20px;\r\n right: 20px;\r\n display: flex;\r\n align-items: center;\r\n gap: 8px;\r\n padding: 8px 14px;\r\n background: rgba(0, 0, 0, 0.8);\r\n border: 1px solid rgba(255, 255, 255, 0.1);\r\n border-radius: 10px;\r\n font-size: 12px;\r\n font-weight: 500;\r\n color: #71717a;\r\n backdrop-filter: blur(10px);\r\n }\r\n \r\n .dev-badge-dot {\r\n width: 8px;\r\n height: 8px;\r\n background: #00FF9C;\r\n border-radius: 50%;\r\n box-shadow: 0 0 10px rgba(0, 255, 156, 0.5);\r\n }\r\n </style>\r\n</head>\r\n<body>\r\n <div class=\"bg-pattern\"></div>\r\n <div class=\"bg-grid\"></div>\r\n \r\n <div class=\"container\">\r\n <div class=\"error-card\">\r\n <div class=\"logo\">F</div>\r\n \r\n <div class=\"error-code\">${statusCode}</div>\r\n <h1 class=\"error-title\">${errorInfo.title}</h1>\r\n <p class=\"error-desc\">${errorInfo.desc}</p>\r\n \r\n <div class=\"buttons\">\r\n <a href=\"/\" class=\"btn btn-primary\">\r\n ← Back to Home\r\n </a>\r\n <a href=\"javascript:history.back()\" class=\"btn btn-secondary\">\r\n Go Back\r\n </a>\r\n </div>\r\n \r\n ${showStack ? `\r\n <div class=\"error-stack\">\r\n <div class=\"error-stack-header\">Error Details</div>\r\n <div class=\"error-message\">${escapeHtml(message)}</div>\r\n ${errorFramesHtml ? `<div class=\"error-frames\">${errorFramesHtml}</div>` : ''}\r\n </div>\r\n ` : ''}\r\n </div>\r\n </div>\r\n \r\n ${isDev ? `\r\n <div class=\"dev-badge\">\r\n <div class=\"dev-badge-dot\"></div>\r\n FlexiReact v2\r\n </div>\r\n ` : ''}\r\n</body>\r\n</html>`;\r\n}\r\n\r\n/**\r\n * Parses error stack for better display\r\n */\r\nfunction parseErrorStack(stack) {\r\n if (!stack) return null;\r\n \r\n const lines = stack.split('\\n');\r\n const parsed = {\r\n message: lines[0] || '',\r\n frames: []\r\n };\r\n \r\n for (let i = 1; i < lines.length; i++) {\r\n const line = lines[i].trim();\r\n const match = line.match(/at\\s+(.+?)\\s+\\((.+?):(\\d+):(\\d+)\\)/) ||\r\n line.match(/at\\s+(.+?):(\\d+):(\\d+)/);\r\n \r\n if (match) {\r\n parsed.frames.push({\r\n fn: match[1] || 'anonymous',\r\n file: match[2] || match[1],\r\n line: match[3] || match[2],\r\n col: match[4] || match[3]\r\n });\r\n }\r\n }\r\n \r\n return parsed;\r\n}\r\n\r\n/**\r\n * Renders a loading state\r\n */\r\nexport function renderLoading(LoadingComponent) {\r\n if (!LoadingComponent) {\r\n return `<div class=\"flexi-loading\">\r\n <div class=\"flexi-spinner\"></div>\r\n <style>\r\n .flexi-loading {\r\n display: flex;\r\n align-items: center;\r\n justify-content: center;\r\n min-height: 200px;\r\n }\r\n .flexi-spinner {\r\n width: 40px;\r\n height: 40px;\r\n border: 3px solid #f3f3f3;\r\n border-top: 3px solid #667eea;\r\n border-radius: 50%;\r\n animation: spin 1s linear infinite;\r\n }\r\n @keyframes spin {\r\n 0% { transform: rotate(0deg); }\r\n 100% { transform: rotate(360deg); }\r\n }\r\n </style>\r\n </div>`;\r\n }\r\n \r\n return renderToString(React.createElement(LoadingComponent));\r\n}\r\n\r\nexport default {\r\n renderPage,\r\n renderError,\r\n renderLoading\r\n};\r\n","/**\r\n * FlexiReact Server v2\r\n * Production-ready server with SSR, RSC, Islands, and more\r\n */\r\n\r\nimport http from 'http';\r\nimport fs from 'fs';\r\nimport path from 'path';\r\nimport { fileURLToPath, pathToFileURL } from 'url';\r\nimport { loadConfig, resolvePaths } from '../config.js';\r\nimport { buildRouteTree, matchRoute, findRouteLayouts } from '../router/index.js';\r\nimport { renderPage, renderError, renderLoading } from '../render/index.js';\r\nimport { loadMiddleware, runMiddleware } from '../middleware/index.js';\r\nimport { loadPlugins, pluginManager, PluginHooks } from '../plugins/index.js';\r\nimport { getRegisteredIslands, generateAdvancedHydrationScript } from '../islands/index.js';\r\nimport { createRequestContext, RequestContext, RouteContext } from '../context.js';\r\nimport { logger } from '../logger.js';\r\nimport { RedirectError, NotFoundError } from '../helpers.js';\r\nimport { executeAction, deserializeArgs } from '../actions/index.js';\r\nimport { handleImageOptimization } from '../image/index.js';\r\nimport { handleFontRequest } from '../font/index.js';\r\nimport React from 'react';\r\n\r\nconst __filename = fileURLToPath(import.meta.url);\r\nconst __dirname = path.dirname(__filename);\r\n\r\n// MIME types\r\nconst MIME_TYPES = {\r\n '.html': 'text/html',\r\n '.css': 'text/css',\r\n '.js': 'application/javascript',\r\n '.mjs': 'application/javascript',\r\n '.json': 'application/json',\r\n '.png': 'image/png',\r\n '.jpg': 'image/jpeg',\r\n '.jpeg': 'image/jpeg',\r\n '.gif': 'image/gif',\r\n '.svg': 'image/svg+xml',\r\n '.ico': 'image/x-icon',\r\n '.woff': 'font/woff',\r\n '.woff2': 'font/woff2',\r\n '.ttf': 'font/ttf',\r\n '.webp': 'image/webp',\r\n '.mp4': 'video/mp4',\r\n '.webm': 'video/webm'\r\n};\r\n\r\n/**\r\n * Creates the FlexiReact server\r\n */\r\ninterface CreateServerOptions {\r\n projectRoot?: string;\r\n mode?: 'development' | 'production';\r\n port?: number;\r\n host?: string;\r\n}\r\n\r\nexport async function createServer(options: CreateServerOptions = {}) {\r\n const serverStartTime = Date.now();\r\n const projectRoot = options.projectRoot || process.cwd();\r\n const isDev = options.mode === 'development';\r\n\r\n // Show logo\r\n logger.logo();\r\n\r\n // Load configuration\r\n const rawConfig = await loadConfig(projectRoot);\r\n const config = resolvePaths(rawConfig, projectRoot);\r\n\r\n // Load plugins\r\n await loadPlugins(projectRoot, config);\r\n\r\n // Run config hook\r\n await pluginManager.runHook(PluginHooks.CONFIG, config);\r\n\r\n // Load middleware\r\n const middleware = await loadMiddleware(projectRoot);\r\n\r\n // Build routes\r\n let routes = buildRouteTree(config.pagesDir, config.layoutsDir);\r\n\r\n // Run routes loaded hook\r\n await pluginManager.runHook(PluginHooks.ROUTES_LOADED, routes);\r\n\r\n // Create module loader with cache busting for dev\r\n const loadModule = createModuleLoader(isDev);\r\n\r\n // Create HTTP server\r\n const server = http.createServer(async (req, res) => {\r\n const startTime = Date.now();\r\n \r\n // Parse URL early so it's available in finally block\r\n const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);\r\n const pathname = url.pathname;\r\n\r\n try {\r\n\r\n // Run request hook\r\n await pluginManager.runHook(PluginHooks.REQUEST, req, res);\r\n\r\n // Run middleware\r\n const middlewareResult = await runMiddleware(req, res, middleware);\r\n if (!middlewareResult.continue) {\r\n return;\r\n }\r\n\r\n // Handle rewritten URL\r\n const effectivePath = middlewareResult.rewritten \r\n ? new URL(req.url, `http://${req.headers.host}`).pathname \r\n : pathname;\r\n\r\n // Serve static files from public directory\r\n if (await serveStaticFile(res, config.publicDir, effectivePath)) {\r\n return;\r\n }\r\n\r\n // Serve built assets in production\r\n if (!isDev && effectivePath.startsWith('/_flexi/')) {\r\n const assetPath = path.join(config.outDir, 'client', effectivePath.slice(8));\r\n if (await serveStaticFile(res, path.dirname(assetPath), path.basename(assetPath))) {\r\n return;\r\n }\r\n }\r\n\r\n // Serve client components (for hydration)\r\n if (effectivePath.startsWith('/_flexi/component/')) {\r\n const componentName = effectivePath.slice(18).replace('.js', '');\r\n return await serveClientComponent(res, config.pagesDir, componentName);\r\n }\r\n\r\n // Handle server actions\r\n if (effectivePath === '/_flexi/action' && req.method === 'POST') {\r\n return await handleServerAction(req, res);\r\n }\r\n\r\n // Handle image optimization\r\n if (effectivePath.startsWith('/_flexi/image')) {\r\n return await handleImageOptimization(req, res, config.images || {});\r\n }\r\n\r\n // Handle font requests\r\n if (effectivePath.startsWith('/_flexi/font')) {\r\n return await handleFontRequest(req, res);\r\n }\r\n\r\n // Rebuild routes in dev mode for hot reload\r\n if (isDev) {\r\n routes = buildRouteTree(config.pagesDir, config.layoutsDir);\r\n }\r\n\r\n // Match API routes\r\n const apiRoute = matchRoute(effectivePath, routes.api);\r\n if (apiRoute) {\r\n return await handleApiRoute(req, res, apiRoute, loadModule);\r\n }\r\n\r\n // Match FlexiReact v2 routes (routes/ directory - priority)\r\n const flexiRoute = matchRoute(effectivePath, routes.flexiRoutes || []);\r\n if (flexiRoute) {\r\n return await handlePageRoute(req, res, flexiRoute, routes, config, loadModule, url);\r\n }\r\n\r\n // Match app routes (app/ directory - Next.js style)\r\n const appRoute = matchRoute(effectivePath, routes.appRoutes || []);\r\n if (appRoute) {\r\n return await handlePageRoute(req, res, appRoute, routes, config, loadModule, url);\r\n }\r\n\r\n // Match page routes (pages/ directory - legacy fallback)\r\n const pageRoute = matchRoute(effectivePath, routes.pages);\r\n if (pageRoute) {\r\n return await handlePageRoute(req, res, pageRoute, routes, config, loadModule, url);\r\n }\r\n\r\n // 404 Not Found\r\n res.writeHead(404, { 'Content-Type': 'text/html' });\r\n res.end(renderError(404, 'Page not found'));\r\n\r\n } catch (error: any) {\r\n // Handle redirect() calls\r\n if (error instanceof RedirectError) {\r\n res.writeHead(error.statusCode, { 'Location': error.url });\r\n res.end();\r\n return;\r\n }\r\n\r\n // Handle notFound() calls\r\n if (error instanceof NotFoundError) {\r\n res.writeHead(404, { 'Content-Type': 'text/html' });\r\n res.end(renderError(404, error.message));\r\n return;\r\n }\r\n\r\n console.error('Server Error:', error);\r\n\r\n if (!res.headersSent) {\r\n res.writeHead(500, { 'Content-Type': 'text/html' });\r\n res.end(renderError(500, error.message, isDev ? error.stack : null));\r\n }\r\n } finally {\r\n const duration = Date.now() - startTime;\r\n if (isDev) {\r\n // Determine route type for logging\r\n const routeType = pathname.startsWith('/api/') ? 'api' : \r\n pathname.startsWith('/_flexi/') ? 'asset' :\r\n pathname.match(/\\.(js|css|png|jpg|svg|ico)$/) ? 'asset' : 'dynamic';\r\n logger.request(req.method, pathname, res.statusCode, duration, { type: routeType });\r\n }\r\n\r\n // Run response hook\r\n await pluginManager.runHook(PluginHooks.RESPONSE, req, res, duration);\r\n }\r\n });\r\n\r\n // Start server\r\n const port = process.env.PORT || options.port || config.server.port;\r\n const host = options.host || config.server.host;\r\n\r\n return new Promise((resolve, reject) => {\r\n // Handle port in use error\r\n server.on('error', (err: NodeJS.ErrnoException) => {\r\n if (err.code === 'EADDRINUSE') {\r\n logger.portInUse(port);\r\n process.exit(1);\r\n } else {\r\n logger.error('Server error', err);\r\n reject(err);\r\n }\r\n });\r\n\r\n server.listen(port, host, async () => {\r\n // Show startup info with styled logger\r\n logger.serverStart({\r\n port,\r\n host,\r\n mode: isDev ? 'development' : 'production',\r\n pagesDir: config.pagesDir,\r\n islands: config.islands?.enabled,\r\n rsc: config.rsc?.enabled\r\n }, serverStartTime);\r\n\r\n // Run server start hook\r\n await pluginManager.runHook(PluginHooks.SERVER_START, server);\r\n\r\n resolve(server);\r\n });\r\n });\r\n}\r\n\r\n/**\r\n * Creates a module loader with optional cache busting\r\n */\r\nfunction createModuleLoader(isDev) {\r\n return async (filePath) => {\r\n const url = pathToFileURL(filePath).href;\r\n const cacheBuster = isDev ? `?t=${Date.now()}` : '';\r\n return import(`${url}${cacheBuster}`);\r\n };\r\n}\r\n\r\n/**\r\n * Serves static files\r\n */\r\nasync function serveStaticFile(res, baseDir, pathname) {\r\n // Prevent directory traversal\r\n const safePath = path.normalize(pathname).replace(/^(\\.\\.[\\/\\\\])+/, '');\r\n const filePath = path.join(baseDir, safePath);\r\n\r\n // Check if file exists and is within base directory\r\n if (!filePath.startsWith(baseDir) || !fs.existsSync(filePath)) {\r\n return false;\r\n }\r\n\r\n const stat = fs.statSync(filePath);\r\n if (!stat.isFile()) {\r\n return false;\r\n }\r\n\r\n const ext = path.extname(filePath).toLowerCase();\r\n const contentType = MIME_TYPES[ext] || 'application/octet-stream';\r\n\r\n res.writeHead(200, {\r\n 'Content-Type': contentType,\r\n 'Content-Length': stat.size,\r\n 'Cache-Control': 'public, max-age=31536000'\r\n });\r\n\r\n fs.createReadStream(filePath).pipe(res);\r\n return true;\r\n}\r\n\r\n/**\r\n * Handles API route requests\r\n */\r\nasync function handleApiRoute(req, res, route, loadModule) {\r\n try {\r\n const module = await loadModule(route.filePath);\r\n const method = req.method.toLowerCase();\r\n\r\n // Parse request body\r\n const body = await parseBody(req);\r\n\r\n // Parse query\r\n const url = new URL(req.url, `http://${req.headers.host}`);\r\n const query = Object.fromEntries(url.searchParams);\r\n\r\n // Enhanced request\r\n const enhancedReq = {\r\n ...req,\r\n body,\r\n query,\r\n params: route.params,\r\n method: req.method\r\n };\r\n\r\n // Enhanced response\r\n const enhancedRes = createApiResponse(res);\r\n\r\n // Find handler (check both lowercase and uppercase method names)\r\n const handler = module[method] || module[method.toUpperCase()] || module.default;\r\n\r\n if (!handler) {\r\n enhancedRes.status(405).json({ error: 'Method not allowed' });\r\n return;\r\n }\r\n\r\n await handler(enhancedReq, enhancedRes);\r\n\r\n } catch (error) {\r\n console.error('API Error:', error);\r\n if (!res.headersSent) {\r\n res.writeHead(500, { 'Content-Type': 'application/json' });\r\n res.end(JSON.stringify({ error: 'Internal Server Error' }));\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Handles server action requests\r\n */\r\nasync function handleServerAction(req, res) {\r\n try {\r\n // Parse request body\r\n const body: any = await parseBody(req);\r\n const { actionId, args } = body;\r\n\r\n if (!actionId) {\r\n res.writeHead(400, { 'Content-Type': 'application/json' });\r\n res.end(JSON.stringify({ success: false, error: 'Missing actionId' }));\r\n return;\r\n }\r\n\r\n // Deserialize arguments\r\n const deserializedArgs = deserializeArgs(args || []);\r\n\r\n // Execute the action\r\n const result = await executeAction(actionId, deserializedArgs, {\r\n request: new Request(`http://${req.headers.host}${req.url}`, {\r\n method: req.method,\r\n headers: req.headers as any\r\n })\r\n });\r\n\r\n // Send response\r\n res.writeHead(200, { \r\n 'Content-Type': 'application/json',\r\n 'X-Flexi-Action': actionId\r\n });\r\n res.end(JSON.stringify(result));\r\n\r\n } catch (error: any) {\r\n console.error('Server Action Error:', error);\r\n res.writeHead(500, { 'Content-Type': 'application/json' });\r\n res.end(JSON.stringify({ \r\n success: false, \r\n error: error.message || 'Action execution failed' \r\n }));\r\n }\r\n}\r\n\r\n/**\r\n * Creates an enhanced API response object\r\n */\r\nfunction createApiResponse(res) {\r\n return {\r\n _res: res,\r\n _status: 200,\r\n _headers: {},\r\n\r\n status(code) {\r\n this._status = code;\r\n return this;\r\n },\r\n\r\n setHeader(name, value) {\r\n this._headers[name] = value;\r\n return this;\r\n },\r\n\r\n json(data) {\r\n this._headers['Content-Type'] = 'application/json';\r\n this._send(JSON.stringify(data));\r\n },\r\n\r\n send(data) {\r\n if (typeof data === 'object') {\r\n this.json(data);\r\n } else {\r\n this._headers['Content-Type'] = this._headers['Content-Type'] || 'text/plain';\r\n this._send(String(data));\r\n }\r\n },\r\n\r\n html(data) {\r\n this._headers['Content-Type'] = 'text/html';\r\n this._send(data);\r\n },\r\n\r\n redirect(url, status = 302) {\r\n this._status = status;\r\n this._headers['Location'] = url;\r\n this._send('');\r\n },\r\n\r\n _send(body) {\r\n if (!this._res.headersSent) {\r\n this._res.writeHead(this._status, this._headers);\r\n this._res.end(body);\r\n }\r\n }\r\n };\r\n}\r\n\r\n/**\r\n * Handles page route requests with SSR\r\n */\r\nasync function handlePageRoute(req, res, route, routes, config, loadModule, url) {\r\n try {\r\n // Run route-specific middleware if exists\r\n if (route.middleware) {\r\n try {\r\n const middlewareModule = await loadModule(route.middleware);\r\n const middlewareFn = middlewareModule.default || middlewareModule.middleware;\r\n \r\n if (typeof middlewareFn === 'function') {\r\n const result = await middlewareFn(req, res, { route, params: route.params });\r\n \r\n // If middleware returns a response, use it\r\n if (result?.redirect) {\r\n res.writeHead(result.statusCode || 307, { 'Location': result.redirect });\r\n res.end();\r\n return;\r\n }\r\n \r\n if (result?.rewrite) {\r\n // Rewrite to different path\r\n req.url = result.rewrite;\r\n }\r\n \r\n if (result === false || result?.stop) {\r\n // Middleware stopped the request\r\n return;\r\n }\r\n }\r\n } catch (middlewareError: any) {\r\n console.error('Route middleware error:', middlewareError.message);\r\n }\r\n }\r\n\r\n // Load page module\r\n const pageModule = await loadModule(route.filePath);\r\n const Component = pageModule.default;\r\n\r\n if (!Component) {\r\n throw new Error(`No default export in ${route.filePath}`);\r\n }\r\n\r\n // Create request context\r\n const query = Object.fromEntries(url.searchParams);\r\n const context = createRequestContext(req, res, route.params, query);\r\n\r\n // Get page props\r\n let props = { params: route.params, query };\r\n\r\n // Handle getServerSideProps\r\n if (pageModule.getServerSideProps) {\r\n const result = await pageModule.getServerSideProps({\r\n params: route.params,\r\n query,\r\n req,\r\n res\r\n });\r\n\r\n if (result.redirect) {\r\n res.writeHead(result.redirect.statusCode || 302, {\r\n Location: result.redirect.destination\r\n });\r\n res.end();\r\n return;\r\n }\r\n\r\n if (result.notFound) {\r\n res.writeHead(404, { 'Content-Type': 'text/html' });\r\n res.end(renderError(404, 'Page not found'));\r\n return;\r\n }\r\n\r\n props = { ...props, ...result.props };\r\n }\r\n\r\n // Handle getStaticProps (for ISR)\r\n if (pageModule.getStaticProps) {\r\n const result = await pageModule.getStaticProps({ params: route.params });\r\n \r\n if (result.notFound) {\r\n res.writeHead(404, { 'Content-Type': 'text/html' });\r\n res.end(renderError(404, 'Page not found'));\r\n return;\r\n }\r\n\r\n props = { ...props, ...result.props };\r\n }\r\n\r\n // Load layouts (only if layouts directory exists and has layouts)\r\n const layouts = [];\r\n \r\n try {\r\n const layoutConfigs = findRouteLayouts(route, routes.layouts);\r\n for (const layoutConfig of layoutConfigs) {\r\n if (layoutConfig.filePath) {\r\n const layoutModule = await loadModule(layoutConfig.filePath);\r\n if (layoutModule.default) {\r\n layouts.push({\r\n Component: layoutModule.default,\r\n props: {}\r\n });\r\n }\r\n }\r\n }\r\n } catch (layoutError) {\r\n // Layouts are optional, continue without them\r\n console.warn('Layout loading skipped:', layoutError.message);\r\n }\r\n\r\n // Load loading component if exists\r\n let LoadingComponent = null;\r\n if (route.loading) {\r\n const loadingModule = await loadModule(route.loading);\r\n LoadingComponent = loadingModule.default;\r\n }\r\n\r\n // Load error component if exists\r\n let ErrorComponent = null;\r\n if (route.error) {\r\n const errorModule = await loadModule(route.error);\r\n ErrorComponent = errorModule.default;\r\n }\r\n\r\n // Run before render hook\r\n props = await pluginManager.runWaterfallHook(\r\n PluginHooks.BEFORE_RENDER,\r\n props,\r\n { route, Component }\r\n );\r\n\r\n // Check if this is a client component (needs hydration)\r\n const isClientComponent = route.isClientComponent || \r\n (pageModule.__isClient) ||\r\n (typeof pageModule.default === 'function' && pageModule.default.toString().includes('useState'));\r\n\r\n // Render the page\r\n let html = await renderPage({\r\n Component,\r\n props,\r\n layouts,\r\n loading: LoadingComponent,\r\n error: ErrorComponent,\r\n islands: getRegisteredIslands(),\r\n title: pageModule.title || pageModule.metadata?.title || 'FlexiReact App',\r\n meta: pageModule.metadata || {},\r\n styles: config.styles || [],\r\n scripts: config.scripts || [],\r\n favicon: config.favicon || null,\r\n needsHydration: isClientComponent,\r\n componentPath: route.filePath,\r\n route: route.path || url.pathname,\r\n isSSG: !!pageModule.getStaticProps\r\n });\r\n\r\n // Add island hydration script\r\n const islands = getRegisteredIslands();\r\n if (islands.length > 0 && config.islands.enabled) {\r\n const hydrationScript = generateAdvancedHydrationScript(islands);\r\n html = html.replace('</body>', `${hydrationScript}</body>`);\r\n }\r\n\r\n // Add client hydration for 'use client' components\r\n if (isClientComponent) {\r\n const hydrationScript = generateClientHydrationScript(route.filePath, props);\r\n html = html.replace('</body>', `${hydrationScript}</body>`);\r\n }\r\n\r\n // Run after render hook\r\n html = await pluginManager.runWaterfallHook(\r\n PluginHooks.AFTER_RENDER,\r\n html,\r\n { route, Component, props }\r\n );\r\n\r\n res.writeHead(200, { 'Content-Type': 'text/html' });\r\n res.end(html);\r\n\r\n } catch (error) {\r\n console.error('Page Render Error:', error);\r\n throw error;\r\n }\r\n}\r\n\r\n/**\r\n * Serves a client component as JavaScript for hydration\r\n */\r\nasync function serveClientComponent(res, pagesDir, componentName) {\r\n const { transformSync } = await import('esbuild');\r\n \r\n // Remove .tsx.js or .jsx.js suffix if present\r\n const cleanName = componentName.replace(/\\.(tsx|jsx|ts|js)\\.js$/, '').replace(/\\.js$/, '');\r\n \r\n // Find the component file (support TypeScript)\r\n const possiblePaths = [\r\n path.join(pagesDir, `${cleanName}.tsx`),\r\n path.join(pagesDir, `${cleanName}.ts`),\r\n path.join(pagesDir, `${cleanName}.jsx`),\r\n path.join(pagesDir, `${cleanName}.js`),\r\n ];\r\n \r\n let componentPath = null;\r\n for (const p of possiblePaths) {\r\n if (fs.existsSync(p)) {\r\n componentPath = p;\r\n break;\r\n }\r\n }\r\n \r\n if (!componentPath) {\r\n res.writeHead(404, { 'Content-Type': 'text/plain' });\r\n res.end(`Component not found: ${cleanName}`);\r\n return;\r\n }\r\n \r\n // Determine loader based on extension\r\n const ext = path.extname(componentPath);\r\n const loader = ext === '.tsx' ? 'tsx' : ext === '.ts' ? 'ts' : 'jsx';\r\n \r\n try {\r\n let source = fs.readFileSync(componentPath, 'utf-8');\r\n \r\n // Remove 'use client' directive\r\n source = source.replace(/^['\"]use (client|server|island)['\"];?\\s*/m, '');\r\n \r\n // Transform for browser\r\n const result = transformSync(source, {\r\n loader,\r\n format: 'esm',\r\n jsx: 'transform',\r\n jsxFactory: 'React.createElement',\r\n jsxFragment: 'React.Fragment',\r\n target: 'es2020',\r\n // Replace React imports with global\r\n banner: `\r\n const React = window.React;\r\n const useState = window.useState;\r\n const useEffect = window.useEffect;\r\n const useCallback = window.useCallback;\r\n const useMemo = window.useMemo;\r\n const useRef = window.useRef;\r\n `\r\n });\r\n \r\n // Remove all React imports since we're using globals\r\n let code = result.code;\r\n // Remove: import React from 'react'\r\n code = code.replace(/import\\s+React\\s+from\\s+['\"]react['\"];?\\s*/g, '');\r\n // Remove: import { useState } from 'react'\r\n code = code.replace(/import\\s+\\{[^}]+\\}\\s+from\\s+['\"]react['\"];?\\s*/g, '');\r\n // Remove: import React, { useState } from 'react'\r\n code = code.replace(/import\\s+React\\s*,\\s*\\{[^}]+\\}\\s+from\\s+['\"]react['\"];?\\s*/g, '');\r\n \r\n res.writeHead(200, { \r\n 'Content-Type': 'application/javascript',\r\n 'Cache-Control': 'no-cache'\r\n });\r\n res.end(code);\r\n \r\n } catch (error) {\r\n console.error('Error serving client component:', error);\r\n res.writeHead(500, { 'Content-Type': 'text/plain' });\r\n res.end('Error compiling component');\r\n }\r\n}\r\n\r\n/**\r\n * Generates client hydration script for 'use client' components\r\n */\r\nfunction generateClientHydrationScript(componentPath, props) {\r\n // Create a relative path for the client bundle (handle .tsx, .ts, .jsx, .js)\r\n const ext = path.extname(componentPath);\r\n const componentName = path.basename(componentPath, ext);\r\n \r\n return `\r\n<script type=\"module\">\r\n // FlexiReact Client Hydration\r\n (async function() {\r\n try {\r\n const React = await import('https://esm.sh/react@18.3.1');\r\n const ReactDOM = await import('https://esm.sh/react-dom@18.3.1/client');\r\n \r\n // Make React available globally for the component\r\n window.React = React.default || React;\r\n window.useState = React.useState;\r\n window.useEffect = React.useEffect;\r\n window.useCallback = React.useCallback;\r\n window.useMemo = React.useMemo;\r\n window.useRef = React.useRef;\r\n \r\n // Fetch the component code\r\n const response = await fetch('/_flexi/component/${componentName}.js');\r\n const code = await response.text();\r\n \r\n // Create and import the module\r\n const blob = new Blob([code], { type: 'application/javascript' });\r\n const moduleUrl = URL.createObjectURL(blob);\r\n const module = await import(moduleUrl);\r\n \r\n const Component = module.default;\r\n const props = ${JSON.stringify(props)};\r\n \r\n // Hydrate the root\r\n const root = document.getElementById('root');\r\n ReactDOM.hydrateRoot(root, window.React.createElement(Component, props));\r\n \r\n console.log('⚡ FlexiReact: Component hydrated successfully');\r\n } catch (error) {\r\n console.error('⚡ FlexiReact: Hydration failed', error);\r\n }\r\n })();\r\n</script>`;\r\n}\r\n\r\n/**\r\n * Parses request body\r\n */\r\nasync function parseBody(req) {\r\n return new Promise((resolve) => {\r\n const contentType = req.headers['content-type'] || '';\r\n let body = '';\r\n\r\n req.on('data', chunk => {\r\n body += chunk.toString();\r\n });\r\n\r\n req.on('end', () => {\r\n try {\r\n if (contentType.includes('application/json') && body) {\r\n resolve(JSON.parse(body));\r\n } else if (contentType.includes('application/x-www-form-urlencoded') && body) {\r\n resolve(Object.fromEntries(new URLSearchParams(body)));\r\n } else {\r\n resolve(body || null);\r\n }\r\n } catch {\r\n resolve(body);\r\n }\r\n });\r\n\r\n req.on('error', () => resolve(null));\r\n });\r\n}\r\n\r\nexport default createServer;\r\n","/**\r\n * FlexiReact Middleware System\r\n * \r\n * Middlewares run before every request and can:\r\n * - Modify the request/response\r\n * - Redirect or rewrite URLs\r\n * - Add headers\r\n * - Authenticate users\r\n * - Log requests\r\n * \r\n * Usage:\r\n * Create a middleware.js file in your project root:\r\n * \r\n * export default function middleware(request) {\r\n * // Return a response to short-circuit\r\n * // Return NextResponse.next() to continue\r\n * // Return NextResponse.redirect() to redirect\r\n * }\r\n * \r\n * export const config = {\r\n * matcher: ['/protected/:path*']\r\n * };\r\n */\r\n\r\nimport fs from 'fs';\r\nimport path from 'path';\r\nimport { pathToFileURL } from 'url';\r\n\r\n/**\r\n * Middleware response helpers\r\n */\r\ninterface MiddlewareResponseOptions {\r\n type?: string;\r\n status?: number;\r\n headers?: Record<string, string>;\r\n body?: any;\r\n url?: string | null;\r\n}\r\n\r\nexport class MiddlewareResponse {\r\n type: string;\r\n status: number;\r\n headers: Map<string, string>;\r\n body: any;\r\n url: string | null;\r\n\r\n constructor(options: MiddlewareResponseOptions = {}) {\r\n this.type = options.type || 'next';\r\n this.status = options.status || 200;\r\n this.headers = new Map(Object.entries(options.headers || {}));\r\n this.body = options.body || null;\r\n this.url = options.url || null;\r\n }\r\n\r\n /**\r\n * Continue to the next middleware/handler\r\n */\r\n static next(options = {}) {\r\n return new MiddlewareResponse({ ...options, type: 'next' });\r\n }\r\n\r\n /**\r\n * Redirect to a different URL\r\n */\r\n static redirect(url, status = 302) {\r\n return new MiddlewareResponse({\r\n type: 'redirect',\r\n url,\r\n status\r\n });\r\n }\r\n\r\n /**\r\n * Rewrite the request to a different URL (internal)\r\n */\r\n static rewrite(url) {\r\n return new MiddlewareResponse({\r\n type: 'rewrite',\r\n url\r\n });\r\n }\r\n\r\n /**\r\n * Return a JSON response\r\n */\r\n static json(data: any, options: { status?: number; headers?: Record<string, string> } = {}) {\r\n return new MiddlewareResponse({\r\n type: 'response',\r\n status: options.status || 200,\r\n headers: { 'Content-Type': 'application/json', ...options.headers },\r\n body: JSON.stringify(data)\r\n });\r\n }\r\n\r\n /**\r\n * Return an HTML response\r\n */\r\n static html(content: string, options: { status?: number; headers?: Record<string, string> } = {}) {\r\n return new MiddlewareResponse({\r\n type: 'response',\r\n status: options.status || 200,\r\n headers: { 'Content-Type': 'text/html', ...options.headers },\r\n body: content\r\n });\r\n }\r\n}\r\n\r\n/**\r\n * Middleware request wrapper\r\n */\r\nexport class MiddlewareRequest {\r\n raw: any;\r\n method: string;\r\n url: string;\r\n headers: Map<string, string>;\r\n pathname: string;\r\n searchParams: URLSearchParams;\r\n query: Record<string, string>;\r\n cookies: Map<string, string>;\r\n\r\n constructor(req: any) {\r\n this.raw = req;\r\n this.method = req.method;\r\n this.url = req.url;\r\n this.headers = new Map(Object.entries(req.headers || {}));\r\n \r\n // Parse URL\r\n const parsedUrl = new URL(req.url, `http://${req.headers.host || 'localhost'}`);\r\n this.pathname = parsedUrl.pathname;\r\n this.searchParams = parsedUrl.searchParams;\r\n this.query = Object.fromEntries(parsedUrl.searchParams) as Record<string, string>;\r\n \r\n // Parse cookies\r\n this.cookies = this._parseCookies(req.headers.cookie || '');\r\n }\r\n\r\n _parseCookies(cookieHeader) {\r\n const cookies = new Map();\r\n if (!cookieHeader) return cookies;\r\n \r\n cookieHeader.split(';').forEach(cookie => {\r\n const [name, ...rest] = cookie.split('=');\r\n if (name) {\r\n cookies.set(name.trim(), rest.join('=').trim());\r\n }\r\n });\r\n \r\n return cookies;\r\n }\r\n\r\n /**\r\n * Get a header value\r\n */\r\n header(name) {\r\n return this.headers.get(name.toLowerCase());\r\n }\r\n\r\n /**\r\n * Get a cookie value\r\n */\r\n cookie(name) {\r\n return this.cookies.get(name);\r\n }\r\n\r\n /**\r\n * Check if request matches a path pattern\r\n */\r\n matches(pattern) {\r\n return matchPath(this.pathname, pattern);\r\n }\r\n}\r\n\r\n/**\r\n * Loads middleware from project\r\n */\r\nexport async function loadMiddleware(projectRoot) {\r\n const middlewarePath = path.join(projectRoot, 'middleware.js');\r\n \r\n if (!fs.existsSync(middlewarePath)) {\r\n return null;\r\n }\r\n\r\n try {\r\n const url = pathToFileURL(middlewarePath).href;\r\n const module = await import(`${url}?t=${Date.now()}`);\r\n \r\n return {\r\n handler: module.default,\r\n config: module.config || {}\r\n };\r\n } catch (error) {\r\n console.error('Failed to load middleware:', error);\r\n return null;\r\n }\r\n}\r\n\r\n/**\r\n * Runs middleware chain\r\n */\r\nexport async function runMiddleware(req, res, middleware) {\r\n if (!middleware) {\r\n return { continue: true };\r\n }\r\n\r\n const { handler, config } = middleware;\r\n const request = new MiddlewareRequest(req);\r\n\r\n // Check if request matches middleware patterns\r\n if (config.matcher) {\r\n const patterns = Array.isArray(config.matcher) ? config.matcher : [config.matcher];\r\n const matches = patterns.some(pattern => matchPath(request.pathname, pattern));\r\n \r\n if (!matches) {\r\n return { continue: true };\r\n }\r\n }\r\n\r\n try {\r\n const response = await handler(request);\r\n\r\n if (!response || response.type === 'next') {\r\n // Apply any headers from middleware\r\n if (response?.headers) {\r\n for (const [key, value] of response.headers) {\r\n res.setHeader(key, value);\r\n }\r\n }\r\n return { continue: true };\r\n }\r\n\r\n if (response.type === 'redirect') {\r\n res.writeHead(response.status, { Location: response.url });\r\n res.end();\r\n return { continue: false };\r\n }\r\n\r\n if (response.type === 'rewrite') {\r\n // Modify the request URL internally\r\n req.url = response.url;\r\n return { continue: true, rewritten: true };\r\n }\r\n\r\n if (response.type === 'response') {\r\n // Apply headers\r\n for (const [key, value] of response.headers) {\r\n res.setHeader(key, value);\r\n }\r\n res.writeHead(response.status);\r\n res.end(response.body);\r\n return { continue: false };\r\n }\r\n\r\n return { continue: true };\r\n\r\n } catch (error) {\r\n console.error('Middleware error:', error);\r\n return { continue: true, error };\r\n }\r\n}\r\n\r\n/**\r\n * Matches a path against a pattern\r\n */\r\nfunction matchPath(pathname, pattern) {\r\n // Convert pattern to regex\r\n let regex = pattern\r\n .replace(/\\*/g, '.*')\r\n .replace(/:path\\*/g, '.*')\r\n .replace(/:(\\w+)/g, '[^/]+');\r\n \r\n regex = `^${regex}$`;\r\n \r\n return new RegExp(regex).test(pathname);\r\n}\r\n\r\n/**\r\n * Compose multiple middleware functions\r\n */\r\nexport function composeMiddleware(...middlewares) {\r\n return async (request) => {\r\n for (const middleware of middlewares) {\r\n const response = await middleware(request);\r\n \r\n if (response && response.type !== 'next') {\r\n return response;\r\n }\r\n }\r\n \r\n return MiddlewareResponse.next();\r\n };\r\n}\r\n\r\n/**\r\n * Built-in middleware helpers\r\n */\r\nexport const middlewares = {\r\n /**\r\n * CORS middleware\r\n */\r\n cors(options: { origin?: string; methods?: string; headers?: string; credentials?: boolean } = {}) {\r\n const {\r\n origin = '*',\r\n methods = 'GET,HEAD,PUT,PATCH,POST,DELETE',\r\n headers = 'Content-Type,Authorization',\r\n credentials = false\r\n } = options;\r\n\r\n return (request) => {\r\n const response = MiddlewareResponse.next({\r\n headers: {\r\n 'Access-Control-Allow-Origin': origin,\r\n 'Access-Control-Allow-Methods': methods,\r\n 'Access-Control-Allow-Headers': headers,\r\n ...(credentials && { 'Access-Control-Allow-Credentials': 'true' })\r\n }\r\n });\r\n\r\n // Handle preflight\r\n if (request.method === 'OPTIONS') {\r\n return MiddlewareResponse.json({}, { status: 204, headers: Object.fromEntries(response.headers) });\r\n }\r\n\r\n return response;\r\n };\r\n },\r\n\r\n /**\r\n * Basic auth middleware\r\n */\r\n basicAuth(options) {\r\n const { username, password, realm = 'Protected' } = options;\r\n const expected = Buffer.from(`${username}:${password}`).toString('base64');\r\n\r\n return (request) => {\r\n const auth = request.header('authorization');\r\n \r\n if (!auth || !auth.startsWith('Basic ')) {\r\n return MiddlewareResponse.html('Unauthorized', {\r\n status: 401,\r\n headers: { 'WWW-Authenticate': `Basic realm=\"${realm}\"` }\r\n });\r\n }\r\n\r\n const provided = auth.slice(6);\r\n if (provided !== expected) {\r\n return MiddlewareResponse.html('Unauthorized', { status: 401 });\r\n }\r\n\r\n return MiddlewareResponse.next();\r\n };\r\n },\r\n\r\n /**\r\n * Rate limiting middleware\r\n */\r\n rateLimit(options: { windowMs?: number; max?: number } = {}) {\r\n const { windowMs = 60000, max = 100 } = options;\r\n const requests = new Map();\r\n\r\n return (request) => {\r\n const ip = request.header('x-forwarded-for') || 'unknown';\r\n const now = Date.now();\r\n \r\n // Clean old entries\r\n for (const [key, data] of requests) {\r\n if (now - data.start > windowMs) {\r\n requests.delete(key);\r\n }\r\n }\r\n\r\n // Check rate limit\r\n const data = requests.get(ip) || { count: 0, start: now };\r\n data.count++;\r\n requests.set(ip, data);\r\n\r\n if (data.count > max) {\r\n return MiddlewareResponse.json(\r\n { error: 'Too many requests' },\r\n { status: 429 }\r\n );\r\n }\r\n\r\n return MiddlewareResponse.next({\r\n headers: {\r\n 'X-RateLimit-Limit': String(max),\r\n 'X-RateLimit-Remaining': String(max - data.count)\r\n }\r\n });\r\n };\r\n },\r\n\r\n /**\r\n * Logging middleware\r\n */\r\n logger(options: { format?: string } = {}) {\r\n const { format = 'combined' } = options;\r\n\r\n return (request) => {\r\n const start = Date.now();\r\n const { method, pathname } = request;\r\n \r\n console.log(`→ ${method} ${pathname}`);\r\n \r\n return MiddlewareResponse.next();\r\n };\r\n }\r\n};\r\n\r\nexport default {\r\n MiddlewareRequest,\r\n MiddlewareResponse,\r\n loadMiddleware,\r\n runMiddleware,\r\n composeMiddleware,\r\n middlewares\r\n};\r\n","/**\r\n * FlexiReact Plugin System\r\n * \r\n * Plugins can extend FlexiReact's functionality by hooking into various lifecycle events.\r\n * \r\n * Usage:\r\n * Create a flexireact.plugin.js file:\r\n * \r\n * export default {\r\n * name: 'my-plugin',\r\n * \r\n * // Called when the server starts\r\n * onServerStart(server) {},\r\n * \r\n * // Called before each request\r\n * onRequest(req, res) {},\r\n * \r\n * // Called before rendering a page\r\n * onBeforeRender(page, props) {},\r\n * \r\n * // Called after rendering a page\r\n * onAfterRender(html, page) {},\r\n * \r\n * // Called during build\r\n * onBuild(config) {},\r\n * \r\n * // Modify esbuild config\r\n * esbuildConfig(config) {},\r\n * };\r\n */\r\n\r\nimport fs from 'fs';\r\nimport path from 'path';\r\nimport { pathToFileURL } from 'url';\r\n\r\n/**\r\n * Plugin lifecycle hooks\r\n */\r\nexport const PluginHooks = {\r\n // Server lifecycle\r\n SERVER_START: 'onServerStart',\r\n SERVER_STOP: 'onServerStop',\r\n \r\n // Request lifecycle\r\n REQUEST: 'onRequest',\r\n RESPONSE: 'onResponse',\r\n \r\n // Render lifecycle\r\n BEFORE_RENDER: 'onBeforeRender',\r\n AFTER_RENDER: 'onAfterRender',\r\n \r\n // Build lifecycle\r\n BUILD_START: 'onBuildStart',\r\n BUILD_END: 'onBuildEnd',\r\n \r\n // Route lifecycle\r\n ROUTES_LOADED: 'onRoutesLoaded',\r\n \r\n // Config\r\n CONFIG: 'onConfig',\r\n ESBUILD_CONFIG: 'esbuildConfig'\r\n};\r\n\r\n/**\r\n * Plugin manager class\r\n */\r\nexport class PluginManager {\r\n plugins: any[];\r\n hooks: Map<string, any[]>;\r\n\r\n constructor() {\r\n this.plugins = [];\r\n this.hooks = new Map();\r\n \r\n // Initialize hook arrays\r\n for (const hook of Object.values(PluginHooks)) {\r\n this.hooks.set(hook as string, []);\r\n }\r\n }\r\n\r\n /**\r\n * Registers a plugin\r\n */\r\n register(plugin) {\r\n if (!plugin.name) {\r\n throw new Error('Plugin must have a name');\r\n }\r\n\r\n // Check for duplicate\r\n if (this.plugins.find(p => p.name === plugin.name)) {\r\n console.warn(`Plugin \"${plugin.name}\" is already registered`);\r\n return;\r\n }\r\n\r\n this.plugins.push(plugin);\r\n\r\n // Register hooks\r\n for (const [hookName, handlers] of this.hooks) {\r\n if (typeof plugin[hookName] === 'function') {\r\n handlers.push({\r\n plugin: plugin.name,\r\n handler: plugin[hookName].bind(plugin)\r\n });\r\n }\r\n }\r\n\r\n console.log(` ✓ Plugin loaded: ${plugin.name}`);\r\n }\r\n\r\n /**\r\n * Unregisters a plugin\r\n */\r\n unregister(pluginName) {\r\n const index = this.plugins.findIndex(p => p.name === pluginName);\r\n if (index === -1) return;\r\n\r\n this.plugins.splice(index, 1);\r\n\r\n // Remove hooks\r\n for (const handlers of this.hooks.values()) {\r\n const hookIndex = handlers.findIndex(h => h.plugin === pluginName);\r\n if (hookIndex !== -1) {\r\n handlers.splice(hookIndex, 1);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Runs a hook with all registered handlers\r\n */\r\n async runHook(hookName, ...args) {\r\n const handlers = this.hooks.get(hookName) || [];\r\n const results = [];\r\n\r\n for (const { plugin, handler } of handlers) {\r\n try {\r\n const result = await handler(...args);\r\n results.push({ plugin, result });\r\n } catch (error) {\r\n console.error(`Plugin \"${plugin}\" error in ${hookName}:`, error);\r\n results.push({ plugin, error });\r\n }\r\n }\r\n\r\n return results;\r\n }\r\n\r\n /**\r\n * Runs a hook that can modify a value (waterfall)\r\n */\r\n async runWaterfallHook(hookName, initialValue, ...args) {\r\n const handlers = this.hooks.get(hookName) || [];\r\n let value = initialValue;\r\n\r\n for (const { plugin, handler } of handlers) {\r\n try {\r\n const result = await handler(value, ...args);\r\n if (result !== undefined) {\r\n value = result;\r\n }\r\n } catch (error) {\r\n console.error(`Plugin \"${plugin}\" error in ${hookName}:`, error);\r\n }\r\n }\r\n\r\n return value;\r\n }\r\n\r\n /**\r\n * Checks if any plugin handles a hook\r\n */\r\n hasHook(hookName) {\r\n const handlers = this.hooks.get(hookName) || [];\r\n return handlers.length > 0;\r\n }\r\n\r\n /**\r\n * Gets all registered plugins\r\n */\r\n getPlugins() {\r\n return [...this.plugins];\r\n }\r\n}\r\n\r\n// Global plugin manager instance\r\nexport const pluginManager = new PluginManager();\r\n\r\n/**\r\n * Loads plugins from project and config\r\n */\r\nexport async function loadPlugins(projectRoot, config) {\r\n console.log('\\n📦 Loading plugins...\\n');\r\n\r\n // Load from flexireact.plugin.js\r\n const pluginPath = path.join(projectRoot, 'flexireact.plugin.js');\r\n \r\n if (fs.existsSync(pluginPath)) {\r\n try {\r\n const url = pathToFileURL(pluginPath).href;\r\n const module = await import(`${url}?t=${Date.now()}`);\r\n const plugin = module.default;\r\n \r\n if (plugin) {\r\n pluginManager.register(plugin);\r\n }\r\n } catch (error) {\r\n console.error('Failed to load flexireact.plugin.js:', error);\r\n }\r\n }\r\n\r\n // Load plugins from config\r\n if (config.plugins && Array.isArray(config.plugins)) {\r\n for (const pluginConfig of config.plugins) {\r\n try {\r\n if (typeof pluginConfig === 'string') {\r\n // Load from node_modules\r\n const module = await import(pluginConfig);\r\n pluginManager.register(module.default);\r\n } else if (typeof pluginConfig === 'object') {\r\n // Inline plugin\r\n pluginManager.register(pluginConfig);\r\n } else if (typeof pluginConfig === 'function') {\r\n // Plugin factory\r\n pluginManager.register(pluginConfig());\r\n }\r\n } catch (error) {\r\n console.error(`Failed to load plugin:`, error);\r\n }\r\n }\r\n }\r\n\r\n console.log(`\\n Total plugins: ${pluginManager.getPlugins().length}\\n`);\r\n\r\n return pluginManager;\r\n}\r\n\r\n/**\r\n * Creates a plugin\r\n */\r\nexport function definePlugin(options) {\r\n return {\r\n name: options.name || 'unnamed-plugin',\r\n ...options\r\n };\r\n}\r\n\r\n/**\r\n * Built-in plugins\r\n */\r\nexport const builtinPlugins = {\r\n /**\r\n * Analytics plugin\r\n */\r\n analytics(options: { trackingId?: string } = {}) {\r\n const { trackingId } = options;\r\n\r\n return definePlugin({\r\n name: 'flexi-analytics',\r\n\r\n onAfterRender(html) {\r\n if (!trackingId) return html;\r\n\r\n const script = `\r\n <script async src=\"https://www.googletagmanager.com/gtag/js?id=${trackingId}\"></script>\r\n <script>\r\n window.dataLayer = window.dataLayer || [];\r\n function gtag(){dataLayer.push(arguments);}\r\n gtag('js', new Date());\r\n gtag('config', '${trackingId}');\r\n </script>\r\n `;\r\n\r\n return html.replace('</head>', `${script}</head>`);\r\n }\r\n });\r\n },\r\n\r\n /**\r\n * PWA plugin\r\n */\r\n pwa(options: { manifest?: string; serviceWorker?: string } = {}) {\r\n const { manifest = '/manifest.json', serviceWorker = '/sw.js' } = options;\r\n\r\n return definePlugin({\r\n name: 'flexi-pwa',\r\n\r\n onAfterRender(html) {\r\n const tags = `\r\n <link rel=\"manifest\" href=\"${manifest}\">\r\n <script>\r\n if ('serviceWorker' in navigator) {\r\n navigator.serviceWorker.register('${serviceWorker}');\r\n }\r\n </script>\r\n `;\r\n\r\n return html.replace('</head>', `${tags}</head>`);\r\n }\r\n });\r\n },\r\n\r\n /**\r\n * SEO plugin\r\n */\r\n seo(options: { defaultTitle?: string; titleTemplate?: string; defaultDescription?: string } = {}) {\r\n const { defaultTitle, titleTemplate = '%s', defaultDescription } = options;\r\n\r\n return definePlugin({\r\n name: 'flexi-seo',\r\n\r\n onBeforeRender(page, props) {\r\n const title = props.title || page.title || defaultTitle;\r\n const description = props.description || page.description || defaultDescription;\r\n\r\n return {\r\n ...props,\r\n _seo: {\r\n title: titleTemplate.replace('%s', title),\r\n description\r\n }\r\n };\r\n }\r\n });\r\n },\r\n\r\n /**\r\n * Compression plugin (for production)\r\n */\r\n compression() {\r\n return definePlugin({\r\n name: 'flexi-compression',\r\n\r\n onResponse(req, res, html) {\r\n // Note: Actual compression would require zlib\r\n // This is a placeholder for the concept\r\n res.setHeader('Content-Encoding', 'identity');\r\n return html;\r\n }\r\n });\r\n },\r\n\r\n /**\r\n * Security headers plugin\r\n */\r\n securityHeaders(options: { headers?: Record<string, string> } = {}) {\r\n const headers: Record<string, string> = {\r\n 'X-Content-Type-Options': 'nosniff',\r\n 'X-Frame-Options': 'DENY',\r\n 'X-XSS-Protection': '1; mode=block',\r\n 'Referrer-Policy': 'strict-origin-when-cross-origin',\r\n ...options.headers\r\n };\r\n\r\n return definePlugin({\r\n name: 'flexi-security',\r\n\r\n onRequest(req, res) {\r\n for (const [key, value] of Object.entries(headers)) {\r\n res.setHeader(key, value);\r\n }\r\n }\r\n });\r\n }\r\n};\r\n\r\nexport default {\r\n PluginManager,\r\n PluginHooks,\r\n pluginManager,\r\n loadPlugins,\r\n definePlugin,\r\n builtinPlugins\r\n};\r\n","/**\r\n * FlexiReact Islands Architecture\r\n * \r\n * Islands allow partial hydration - only interactive components are hydrated on the client,\r\n * while static content remains as HTML. This dramatically reduces JavaScript bundle size.\r\n * \r\n * Usage:\r\n * - Add 'use island' at the top of a component file\r\n * - The component will be rendered on server and hydrated on client\r\n * - Non-island components are pure HTML (no JS)\r\n */\r\n\r\nimport React from 'react';\r\nimport { renderToString } from 'react-dom/server';\r\nimport crypto from 'crypto';\r\n\r\n// Island registry for tracking all islands in a render\r\nconst islandRegistry = new Map();\r\n\r\n/**\r\n * Generates a unique island ID\r\n */\r\nfunction generateIslandId(componentName) {\r\n const hash = crypto.randomBytes(4).toString('hex');\r\n return `island-${componentName}-${hash}`;\r\n}\r\n\r\n/**\r\n * Island wrapper component for server-side rendering\r\n */\r\nexport function Island({ component: Component, props = {}, name, clientPath }) {\r\n const islandId = generateIslandId(name);\r\n \r\n // Register island for hydration\r\n islandRegistry.set(islandId, {\r\n id: islandId,\r\n name,\r\n clientPath,\r\n props\r\n });\r\n\r\n // Render the component\r\n const content = renderToString(React.createElement(Component, props));\r\n\r\n // Return wrapper with hydration marker\r\n return React.createElement('div', {\r\n 'data-island': islandId,\r\n 'data-island-name': name,\r\n 'data-island-props': JSON.stringify(props),\r\n dangerouslySetInnerHTML: { __html: content }\r\n });\r\n}\r\n\r\n/**\r\n * Gets all registered islands and clears the registry\r\n */\r\nexport function getRegisteredIslands() {\r\n const islands = Array.from(islandRegistry.values());\r\n islandRegistry.clear();\r\n return islands;\r\n}\r\n\r\n/**\r\n * Creates an island component wrapper\r\n */\r\ninterface IslandOptions {\r\n name?: string;\r\n clientPath?: string;\r\n}\r\n\r\nexport function createIsland(Component: React.ComponentType<any>, options: IslandOptions = {}) {\r\n const { name = (Component as any).name || 'Island', clientPath } = options;\r\n\r\n function IslandWrapper(props) {\r\n return Island({\r\n component: Component,\r\n props,\r\n name,\r\n clientPath: clientPath || `/_flexi/islands/${name}.js`\r\n });\r\n }\r\n\r\n IslandWrapper.displayName = `Island(${name})`;\r\n IslandWrapper.isIsland = true;\r\n IslandWrapper.originalComponent = Component;\r\n\r\n return IslandWrapper;\r\n}\r\n\r\n/**\r\n * Generates the client-side hydration script\r\n */\r\nexport function generateHydrationScript(islands) {\r\n if (!islands.length) return '';\r\n\r\n const islandData = islands.map(island => ({\r\n id: island.id,\r\n name: island.name,\r\n path: island.clientPath,\r\n props: island.props\r\n }));\r\n\r\n return `\r\n<script type=\"module\">\r\n const islands = ${JSON.stringify(islandData)};\r\n \r\n async function hydrateIslands() {\r\n const { hydrateRoot } = await import('/_flexi/react-dom-client.js');\r\n const React = await import('/_flexi/react.js');\r\n \r\n for (const island of islands) {\r\n try {\r\n const element = document.querySelector(\\`[data-island=\"\\${island.id}\"]\\`);\r\n if (!element) continue;\r\n \r\n const module = await import(island.path);\r\n const Component = module.default;\r\n \r\n // Hydrate the island\r\n hydrateRoot(element, React.createElement(Component, island.props));\r\n \r\n // Mark as hydrated\r\n element.setAttribute('data-hydrated', 'true');\r\n } catch (error) {\r\n console.error(\\`Failed to hydrate island \\${island.name}:\\`, error);\r\n }\r\n }\r\n }\r\n \r\n // Hydrate when DOM is ready\r\n if (document.readyState === 'loading') {\r\n document.addEventListener('DOMContentLoaded', hydrateIslands);\r\n } else {\r\n hydrateIslands();\r\n }\r\n</script>`;\r\n}\r\n\r\n/**\r\n * Island loading strategies\r\n */\r\nexport const LoadStrategy = {\r\n // Hydrate immediately when page loads\r\n IMMEDIATE: 'immediate',\r\n // Hydrate when island becomes visible\r\n VISIBLE: 'visible',\r\n // Hydrate when user interacts with the page\r\n IDLE: 'idle',\r\n // Hydrate on specific media query\r\n MEDIA: 'media'\r\n};\r\n\r\n/**\r\n * Creates a lazy island that hydrates based on strategy\r\n */\r\ninterface LazyIslandOptions {\r\n name?: string;\r\n clientPath?: string;\r\n strategy?: string;\r\n media?: string | null;\r\n}\r\n\r\nexport function createLazyIsland(Component: React.ComponentType<any>, options: LazyIslandOptions = {}) {\r\n const {\r\n name = (Component as any).name || 'LazyIsland',\r\n clientPath,\r\n strategy = LoadStrategy.VISIBLE,\r\n media = null\r\n } = options;\r\n\r\n function LazyIslandWrapper(props) {\r\n const islandId = generateIslandId(name);\r\n const content = renderToString(React.createElement(Component, props));\r\n\r\n // Register with loading strategy\r\n islandRegistry.set(islandId, {\r\n id: islandId,\r\n name,\r\n clientPath: clientPath || `/_flexi/islands/${name}.js`,\r\n props,\r\n strategy,\r\n media\r\n });\r\n\r\n return React.createElement('div', {\r\n 'data-island': islandId,\r\n 'data-island-name': name,\r\n 'data-island-strategy': strategy,\r\n 'data-island-media': media,\r\n 'data-island-props': JSON.stringify(props),\r\n dangerouslySetInnerHTML: { __html: content }\r\n });\r\n }\r\n\r\n LazyIslandWrapper.displayName = `LazyIsland(${name})`;\r\n LazyIslandWrapper.isIsland = true;\r\n LazyIslandWrapper.isLazy = true;\r\n\r\n return LazyIslandWrapper;\r\n}\r\n\r\n/**\r\n * Generates advanced hydration script with loading strategies\r\n */\r\nexport function generateAdvancedHydrationScript(islands) {\r\n if (!islands.length) return '';\r\n\r\n const islandData = islands.map(island => ({\r\n id: island.id,\r\n name: island.name,\r\n path: island.clientPath,\r\n props: island.props,\r\n strategy: island.strategy || LoadStrategy.IMMEDIATE,\r\n media: island.media\r\n }));\r\n\r\n return `\r\n<script type=\"module\">\r\n const islands = ${JSON.stringify(islandData)};\r\n \r\n async function hydrateIsland(island) {\r\n const element = document.querySelector(\\`[data-island=\"\\${island.id}\"]\\`);\r\n if (!element || element.hasAttribute('data-hydrated')) return;\r\n \r\n try {\r\n const { hydrateRoot } = await import('/_flexi/react-dom-client.js');\r\n const React = await import('/_flexi/react.js');\r\n const module = await import(island.path);\r\n const Component = module.default;\r\n \r\n hydrateRoot(element, React.createElement(Component, island.props));\r\n element.setAttribute('data-hydrated', 'true');\r\n } catch (error) {\r\n console.error(\\`Failed to hydrate island \\${island.name}:\\`, error);\r\n }\r\n }\r\n \r\n // Intersection Observer for visible strategy\r\n const visibleObserver = new IntersectionObserver((entries) => {\r\n entries.forEach(entry => {\r\n if (entry.isIntersecting) {\r\n const id = entry.target.getAttribute('data-island');\r\n const island = islands.find(i => i.id === id);\r\n if (island) {\r\n hydrateIsland(island);\r\n visibleObserver.unobserve(entry.target);\r\n }\r\n }\r\n });\r\n }, { rootMargin: '50px' });\r\n \r\n // Process islands based on strategy\r\n function processIslands() {\r\n for (const island of islands) {\r\n const element = document.querySelector(\\`[data-island=\"\\${island.id}\"]\\`);\r\n if (!element) continue;\r\n \r\n switch (island.strategy) {\r\n case 'immediate':\r\n hydrateIsland(island);\r\n break;\r\n case 'visible':\r\n visibleObserver.observe(element);\r\n break;\r\n case 'idle':\r\n requestIdleCallback(() => hydrateIsland(island));\r\n break;\r\n case 'media':\r\n if (island.media && window.matchMedia(island.media).matches) {\r\n hydrateIsland(island);\r\n }\r\n break;\r\n }\r\n }\r\n }\r\n \r\n if (document.readyState === 'loading') {\r\n document.addEventListener('DOMContentLoaded', processIslands);\r\n } else {\r\n processIslands();\r\n }\r\n</script>`;\r\n}\r\n\r\nexport default {\r\n Island,\r\n createIsland,\r\n createLazyIsland,\r\n getRegisteredIslands,\r\n generateHydrationScript,\r\n generateAdvancedHydrationScript,\r\n LoadStrategy\r\n};\r\n","/**\r\n * FlexiReact Logger\r\n * Premium console output inspired by Next.js, Vite, and Bun\r\n */\r\n\r\n// ANSI color codes\r\nconst colors = {\r\n reset: '\\x1b[0m',\r\n bold: '\\x1b[1m',\r\n dim: '\\x1b[2m',\r\n italic: '\\x1b[3m',\r\n underline: '\\x1b[4m',\r\n \r\n // Text colors\r\n black: '\\x1b[30m',\r\n red: '\\x1b[31m',\r\n green: '\\x1b[32m',\r\n yellow: '\\x1b[33m',\r\n blue: '\\x1b[34m',\r\n magenta: '\\x1b[35m',\r\n cyan: '\\x1b[36m',\r\n white: '\\x1b[37m',\r\n gray: '\\x1b[90m',\r\n \r\n // Bright colors\r\n brightRed: '\\x1b[91m',\r\n brightGreen: '\\x1b[92m',\r\n brightYellow: '\\x1b[93m',\r\n brightBlue: '\\x1b[94m',\r\n brightMagenta: '\\x1b[95m',\r\n brightCyan: '\\x1b[96m',\r\n brightWhite: '\\x1b[97m',\r\n \r\n // Background colors\r\n bgRed: '\\x1b[41m',\r\n bgGreen: '\\x1b[42m',\r\n bgYellow: '\\x1b[43m',\r\n bgBlue: '\\x1b[44m',\r\n bgMagenta: '\\x1b[45m',\r\n bgCyan: '\\x1b[46m',\r\n};\r\n\r\nconst c = colors;\r\n\r\n// Get current time formatted\r\nfunction getTime() {\r\n const now = new Date();\r\n return `${c.dim}${now.toLocaleTimeString('en-US', { hour12: false })}${c.reset}`;\r\n}\r\n\r\n// Status code colors\r\nfunction getStatusColor(status) {\r\n if (status >= 500) return c.red;\r\n if (status >= 400) return c.yellow;\r\n if (status >= 300) return c.cyan;\r\n if (status >= 200) return c.green;\r\n return c.white;\r\n}\r\n\r\n// Method colors\r\nfunction getMethodColor(method) {\r\n const methodColors = {\r\n GET: c.brightGreen,\r\n POST: c.brightBlue,\r\n PUT: c.brightYellow,\r\n PATCH: c.brightMagenta,\r\n DELETE: c.brightRed,\r\n OPTIONS: c.gray,\r\n HEAD: c.gray,\r\n };\r\n return methodColors[method] || c.white;\r\n}\r\n\r\n// Format time\r\nfunction formatTime(ms) {\r\n if (ms < 1) return `${c.gray}<1ms${c.reset}`;\r\n if (ms < 100) return `${c.green}${ms}ms${c.reset}`;\r\n if (ms < 500) return `${c.yellow}${ms}ms${c.reset}`;\r\n return `${c.red}${ms}ms${c.reset}`;\r\n}\r\n\r\n// FlexiReact ASCII Logo - Premium Design\r\nconst LOGO = `\r\n${c.green} ╭─────────────────────────────────────────────╮${c.reset}\r\n${c.green} │${c.reset} ${c.green}│${c.reset}\r\n${c.green} │${c.reset} ${c.brightGreen}⚡${c.reset} ${c.bold}${c.white}F L E X I R E A C T${c.reset} ${c.dim}v1.0.0${c.reset} ${c.green}│${c.reset}\r\n${c.green} │${c.reset} ${c.green}│${c.reset}\r\n${c.green} │${c.reset} ${c.dim}The Modern React Framework${c.reset} ${c.green}│${c.reset}\r\n${c.green} │${c.reset} ${c.green}│${c.reset}\r\n${c.green} ╰─────────────────────────────────────────────╯${c.reset}\r\n`;\r\n\r\nconst MINI_LOGO = `${c.brightGreen}⚡${c.reset} ${c.bold}FlexiReact${c.reset}`;\r\n\r\n// Compact ready message like Next.js\r\nconst READY_MSG = ` ${c.green}▲${c.reset} ${c.bold}Ready${c.reset} in`;\r\n\r\nexport const logger = {\r\n // Show startup logo\r\n logo() {\r\n console.log(LOGO);\r\n },\r\n\r\n // Server started - Next.js style\r\n serverStart(config, startTime = Date.now()) {\r\n const { port, host, mode, pagesDir, islands, rsc } = config;\r\n const elapsed = Date.now() - startTime;\r\n \r\n console.log('');\r\n console.log(` ${c.green}▲${c.reset} ${c.bold}Ready${c.reset} in ${c.cyan}${elapsed}ms${c.reset}`);\r\n console.log('');\r\n console.log(` ${c.dim}┌${c.reset} ${c.bold}Local:${c.reset} ${c.cyan}http://${host}:${port}${c.reset}`);\r\n console.log(` ${c.dim}├${c.reset} ${c.bold}Environment:${c.reset} ${mode === 'development' ? `${c.yellow}development${c.reset}` : `${c.green}production${c.reset}`}`);\r\n if (islands) {\r\n console.log(` ${c.dim}├${c.reset} ${c.bold}Islands:${c.reset} ${c.green}enabled${c.reset}`);\r\n }\r\n if (rsc) {\r\n console.log(` ${c.dim}├${c.reset} ${c.bold}RSC:${c.reset} ${c.green}enabled${c.reset}`);\r\n }\r\n console.log(` ${c.dim}└${c.reset} ${c.bold}Pages:${c.reset} ${c.dim}${pagesDir}${c.reset}`);\r\n console.log('');\r\n },\r\n\r\n // HTTP request log - Compact single line like Next.js\r\n request(method: string, path: string, status: number, time: number, extra: { type?: string } = {}) {\r\n const methodColor = getMethodColor(method);\r\n const statusColor = getStatusColor(status);\r\n const timeStr = formatTime(time);\r\n \r\n // Route type badge\r\n let badge = '';\r\n if (extra.type === 'static' || extra.type === 'ssg') {\r\n badge = `${c.dim}○${c.reset}`; // Static\r\n } else if (extra.type === 'dynamic' || extra.type === 'ssr') {\r\n badge = `${c.magenta}ƒ${c.reset}`; // Function/SSR\r\n } else if (extra.type === 'api') {\r\n badge = `${c.blue}λ${c.reset}`; // API\r\n } else if (extra.type === 'asset') {\r\n badge = `${c.dim}◦${c.reset}`; // Asset\r\n } else {\r\n badge = `${c.magenta}ƒ${c.reset}`;\r\n }\r\n \r\n const statusStr = `${statusColor}${status}${c.reset}`;\r\n const methodStr = `${methodColor}${method}${c.reset}`;\r\n \r\n // Single line format like Next.js\r\n console.log(` ${badge} ${methodStr} ${path} ${statusStr} ${c.dim}in${c.reset} ${timeStr}`);\r\n },\r\n\r\n // Info message\r\n info(msg) {\r\n console.log(` ${c.cyan}ℹ${c.reset} ${msg}`);\r\n },\r\n\r\n // Success message\r\n success(msg) {\r\n console.log(` ${c.green}✓${c.reset} ${msg}`);\r\n },\r\n\r\n // Warning message\r\n warn(msg) {\r\n console.log(` ${c.yellow}⚠${c.reset} ${c.yellow}${msg}${c.reset}`);\r\n },\r\n\r\n // Error message\r\n error(msg, err = null) {\r\n console.log(` ${c.red}✗${c.reset} ${c.red}${msg}${c.reset}`);\r\n if (err && err.stack) {\r\n const stack = err.stack.split('\\n').slice(1, 4).join('\\n');\r\n console.log(`${c.dim}${stack}${c.reset}`);\r\n }\r\n },\r\n\r\n // Compilation message\r\n compile(file, time) {\r\n console.log(` ${c.magenta}◉${c.reset} Compiled ${c.cyan}${file}${c.reset} ${c.dim}(${time}ms)${c.reset}`);\r\n },\r\n\r\n // Hot reload\r\n hmr(file) {\r\n console.log(` ${c.yellow}↻${c.reset} HMR update: ${c.cyan}${file}${c.reset}`);\r\n },\r\n\r\n // Plugin loaded\r\n plugin(name) {\r\n console.log(` ${c.blue}⬡${c.reset} Plugin: ${c.cyan}${name}${c.reset}`);\r\n },\r\n\r\n // Route info\r\n route(path, type) {\r\n const typeColors = {\r\n static: c.green,\r\n dynamic: c.yellow,\r\n api: c.blue,\r\n };\r\n const color = typeColors[type] || c.white;\r\n console.log(` ${c.dim}├─${c.reset} ${path} ${color}[${type}]${c.reset}`);\r\n },\r\n\r\n // Divider\r\n divider() {\r\n console.log(`${c.dim} ─────────────────────────────────────────${c.reset}`);\r\n },\r\n\r\n // Blank line\r\n blank() {\r\n console.log('');\r\n },\r\n\r\n // Port in use error with solution\r\n portInUse(port) {\r\n console.log(`\r\n${c.red} ✗ Port ${port} is already in use${c.reset}\r\n\r\n ${c.dim}Try one of these solutions:${c.reset}\r\n \r\n ${c.yellow}1.${c.reset} Kill the process using the port:\r\n ${c.cyan}npx kill-port ${port}${c.reset}\r\n \r\n ${c.yellow}2.${c.reset} Use a different port in ${c.cyan}flexireact.config.js${c.reset}:\r\n ${c.dim}server: { port: 3001 }${c.reset}\r\n \r\n ${c.yellow}3.${c.reset} Set PORT environment variable:\r\n ${c.cyan}PORT=3001 npm run dev${c.reset}\r\n`);\r\n },\r\n\r\n // Build info\r\n build(stats) {\r\n console.log(`\r\n ${c.green}✓${c.reset} Build complete!\r\n \r\n ${c.dim}├─${c.reset} Pages: ${c.cyan}${stats.pages}${c.reset}\r\n ${c.dim}├─${c.reset} API: ${c.cyan}${stats.api}${c.reset}\r\n ${c.dim}├─${c.reset} Assets: ${c.cyan}${stats.assets}${c.reset}\r\n ${c.dim}└─${c.reset} Time: ${c.green}${stats.time}ms${c.reset}\r\n`);\r\n },\r\n};\r\n\r\nexport default logger;\r\n","/**\r\n * FlexiReact Server Helpers\r\n * Utility functions for server-side operations\r\n */\r\n\r\n// ============================================================================\r\n// Response Helpers\r\n// ============================================================================\r\n\r\n/**\r\n * Custom error classes for control flow\r\n */\r\nexport class RedirectError extends Error {\r\n public readonly url: string;\r\n public readonly statusCode: number;\r\n public readonly type = 'redirect' as const;\r\n\r\n constructor(url: string, statusCode: number = 307) {\r\n super(`Redirect to ${url}`);\r\n this.name = 'RedirectError';\r\n this.url = url;\r\n this.statusCode = statusCode;\r\n }\r\n}\r\n\r\nexport class NotFoundError extends Error {\r\n public readonly type = 'notFound' as const;\r\n\r\n constructor(message: string = 'Page not found') {\r\n super(message);\r\n this.name = 'NotFoundError';\r\n }\r\n}\r\n\r\n/**\r\n * Redirect to a different URL\r\n * @param url - The URL to redirect to\r\n * @param type - 'replace' (307) or 'push' (308) for permanent\r\n * \r\n * @example\r\n * ```tsx\r\n * import { redirect } from '@flexireact/core';\r\n * \r\n * export default function ProtectedPage() {\r\n * const user = getUser();\r\n * if (!user) {\r\n * redirect('/login');\r\n * }\r\n * return <Dashboard user={user} />;\r\n * }\r\n * ```\r\n */\r\nexport function redirect(url: string, type: 'replace' | 'permanent' = 'replace'): never {\r\n const statusCode = type === 'permanent' ? 308 : 307;\r\n throw new RedirectError(url, statusCode);\r\n}\r\n\r\n/**\r\n * Trigger a 404 Not Found response\r\n * \r\n * @example\r\n * ```tsx\r\n * import { notFound } from '@flexireact/core';\r\n * \r\n * export default function ProductPage({ params }) {\r\n * const product = getProduct(params.id);\r\n * if (!product) {\r\n * notFound();\r\n * }\r\n * return <Product data={product} />;\r\n * }\r\n * ```\r\n */\r\nexport function notFound(message?: string): never {\r\n throw new NotFoundError(message);\r\n}\r\n\r\n/**\r\n * Create a JSON response\r\n * \r\n * @example\r\n * ```ts\r\n * // In API route\r\n * export function GET() {\r\n * return json({ message: 'Hello' });\r\n * }\r\n * \r\n * export function POST() {\r\n * return json({ error: 'Bad request' }, { status: 400 });\r\n * }\r\n * ```\r\n */\r\nexport function json<T>(\r\n data: T,\r\n options: {\r\n status?: number;\r\n headers?: Record<string, string>;\r\n } = {}\r\n): Response {\r\n const { status = 200, headers = {} } = options;\r\n \r\n return new Response(JSON.stringify(data), {\r\n status,\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n ...headers\r\n }\r\n });\r\n}\r\n\r\n/**\r\n * Create an HTML response\r\n */\r\nexport function html(\r\n content: string,\r\n options: {\r\n status?: number;\r\n headers?: Record<string, string>;\r\n } = {}\r\n): Response {\r\n const { status = 200, headers = {} } = options;\r\n \r\n return new Response(content, {\r\n status,\r\n headers: {\r\n 'Content-Type': 'text/html; charset=utf-8',\r\n ...headers\r\n }\r\n });\r\n}\r\n\r\n/**\r\n * Create a text response\r\n */\r\nexport function text(\r\n content: string,\r\n options: {\r\n status?: number;\r\n headers?: Record<string, string>;\r\n } = {}\r\n): Response {\r\n const { status = 200, headers = {} } = options;\r\n \r\n return new Response(content, {\r\n status,\r\n headers: {\r\n 'Content-Type': 'text/plain; charset=utf-8',\r\n ...headers\r\n }\r\n });\r\n}\r\n\r\n// ============================================================================\r\n// Cookies API\r\n// ============================================================================\r\n\r\nexport interface CookieOptions {\r\n /** Max age in seconds */\r\n maxAge?: number;\r\n /** Expiration date */\r\n expires?: Date;\r\n /** Cookie path */\r\n path?: string;\r\n /** Cookie domain */\r\n domain?: string;\r\n /** Secure flag (HTTPS only) */\r\n secure?: boolean;\r\n /** HttpOnly flag */\r\n httpOnly?: boolean;\r\n /** SameSite policy */\r\n sameSite?: 'strict' | 'lax' | 'none';\r\n}\r\n\r\n/**\r\n * Cookie utilities for server-side operations\r\n */\r\nexport const cookies = {\r\n /**\r\n * Parse cookies from a cookie header string\r\n */\r\n parse(cookieHeader: string): Record<string, string> {\r\n const cookies: Record<string, string> = {};\r\n if (!cookieHeader) return cookies;\r\n\r\n cookieHeader.split(';').forEach(cookie => {\r\n const [name, ...rest] = cookie.split('=');\r\n if (name) {\r\n const value = rest.join('=');\r\n cookies[name.trim()] = decodeURIComponent(value.trim());\r\n }\r\n });\r\n\r\n return cookies;\r\n },\r\n\r\n /**\r\n * Get a cookie value from request headers\r\n */\r\n get(request: Request, name: string): string | undefined {\r\n const cookieHeader = request.headers.get('cookie') || '';\r\n const parsed = this.parse(cookieHeader);\r\n return parsed[name];\r\n },\r\n\r\n /**\r\n * Get all cookies from request\r\n */\r\n getAll(request: Request): Record<string, string> {\r\n const cookieHeader = request.headers.get('cookie') || '';\r\n return this.parse(cookieHeader);\r\n },\r\n\r\n /**\r\n * Serialize a cookie for Set-Cookie header\r\n */\r\n serialize(name: string, value: string, options: CookieOptions = {}): string {\r\n let cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;\r\n\r\n if (options.maxAge !== undefined) {\r\n cookie += `; Max-Age=${options.maxAge}`;\r\n }\r\n if (options.expires) {\r\n cookie += `; Expires=${options.expires.toUTCString()}`;\r\n }\r\n if (options.path) {\r\n cookie += `; Path=${options.path}`;\r\n }\r\n if (options.domain) {\r\n cookie += `; Domain=${options.domain}`;\r\n }\r\n if (options.secure) {\r\n cookie += '; Secure';\r\n }\r\n if (options.httpOnly) {\r\n cookie += '; HttpOnly';\r\n }\r\n if (options.sameSite) {\r\n cookie += `; SameSite=${options.sameSite.charAt(0).toUpperCase() + options.sameSite.slice(1)}`;\r\n }\r\n\r\n return cookie;\r\n },\r\n\r\n /**\r\n * Create a Set-Cookie header value\r\n */\r\n set(name: string, value: string, options: CookieOptions = {}): string {\r\n return this.serialize(name, value, {\r\n path: '/',\r\n httpOnly: true,\r\n secure: process.env.NODE_ENV === 'production',\r\n sameSite: 'lax',\r\n ...options\r\n });\r\n },\r\n\r\n /**\r\n * Create a cookie deletion header\r\n */\r\n delete(name: string, options: Omit<CookieOptions, 'maxAge' | 'expires'> = {}): string {\r\n return this.serialize(name, '', {\r\n ...options,\r\n path: '/',\r\n maxAge: 0\r\n });\r\n }\r\n};\r\n\r\n// ============================================================================\r\n// Headers API\r\n// ============================================================================\r\n\r\n/**\r\n * Headers utilities for server-side operations\r\n */\r\nexport const headers = {\r\n /**\r\n * Create a new Headers object with common defaults\r\n */\r\n create(init?: HeadersInit): Headers {\r\n return new Headers(init);\r\n },\r\n\r\n /**\r\n * Get a header value from request\r\n */\r\n get(request: Request, name: string): string | null {\r\n return request.headers.get(name);\r\n },\r\n\r\n /**\r\n * Get all headers as an object\r\n */\r\n getAll(request: Request): Record<string, string> {\r\n const result: Record<string, string> = {};\r\n request.headers.forEach((value, key) => {\r\n result[key] = value;\r\n });\r\n return result;\r\n },\r\n\r\n /**\r\n * Check if request has a specific header\r\n */\r\n has(request: Request, name: string): boolean {\r\n return request.headers.has(name);\r\n },\r\n\r\n /**\r\n * Get content type from request\r\n */\r\n contentType(request: Request): string | null {\r\n return request.headers.get('content-type');\r\n },\r\n\r\n /**\r\n * Check if request accepts JSON\r\n */\r\n acceptsJson(request: Request): boolean {\r\n const accept = request.headers.get('accept') || '';\r\n return accept.includes('application/json') || accept.includes('*/*');\r\n },\r\n\r\n /**\r\n * Check if request is AJAX/fetch\r\n */\r\n isAjax(request: Request): boolean {\r\n return request.headers.get('x-requested-with') === 'XMLHttpRequest' ||\r\n this.acceptsJson(request);\r\n },\r\n\r\n /**\r\n * Get authorization header\r\n */\r\n authorization(request: Request): { type: string; credentials: string } | null {\r\n const auth = request.headers.get('authorization');\r\n if (!auth) return null;\r\n\r\n const [type, ...rest] = auth.split(' ');\r\n return {\r\n type: type.toLowerCase(),\r\n credentials: rest.join(' ')\r\n };\r\n },\r\n\r\n /**\r\n * Get bearer token from authorization header\r\n */\r\n bearerToken(request: Request): string | null {\r\n const auth = this.authorization(request);\r\n if (auth?.type === 'bearer') {\r\n return auth.credentials;\r\n }\r\n return null;\r\n },\r\n\r\n /**\r\n * Common security headers\r\n */\r\n security(): Record<string, string> {\r\n return {\r\n 'X-Content-Type-Options': 'nosniff',\r\n 'X-Frame-Options': 'DENY',\r\n 'X-XSS-Protection': '1; mode=block',\r\n 'Referrer-Policy': 'strict-origin-when-cross-origin',\r\n 'Permissions-Policy': 'camera=(), microphone=(), geolocation=()'\r\n };\r\n },\r\n\r\n /**\r\n * CORS headers\r\n */\r\n cors(options: {\r\n origin?: string;\r\n methods?: string[];\r\n headers?: string[];\r\n credentials?: boolean;\r\n maxAge?: number;\r\n } = {}): Record<string, string> {\r\n const {\r\n origin = '*',\r\n methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],\r\n headers: allowHeaders = ['Content-Type', 'Authorization'],\r\n credentials = false,\r\n maxAge = 86400\r\n } = options;\r\n\r\n const corsHeaders: Record<string, string> = {\r\n 'Access-Control-Allow-Origin': origin,\r\n 'Access-Control-Allow-Methods': methods.join(', '),\r\n 'Access-Control-Allow-Headers': allowHeaders.join(', '),\r\n 'Access-Control-Max-Age': String(maxAge)\r\n };\r\n\r\n if (credentials) {\r\n corsHeaders['Access-Control-Allow-Credentials'] = 'true';\r\n }\r\n\r\n return corsHeaders;\r\n },\r\n\r\n /**\r\n * Cache control headers\r\n */\r\n cache(options: {\r\n maxAge?: number;\r\n sMaxAge?: number;\r\n staleWhileRevalidate?: number;\r\n private?: boolean;\r\n noStore?: boolean;\r\n } = {}): Record<string, string> {\r\n if (options.noStore) {\r\n return { 'Cache-Control': 'no-store, no-cache, must-revalidate' };\r\n }\r\n\r\n const directives: string[] = [];\r\n \r\n if (options.private) {\r\n directives.push('private');\r\n } else {\r\n directives.push('public');\r\n }\r\n\r\n if (options.maxAge !== undefined) {\r\n directives.push(`max-age=${options.maxAge}`);\r\n }\r\n\r\n if (options.sMaxAge !== undefined) {\r\n directives.push(`s-maxage=${options.sMaxAge}`);\r\n }\r\n\r\n if (options.staleWhileRevalidate !== undefined) {\r\n directives.push(`stale-while-revalidate=${options.staleWhileRevalidate}`);\r\n }\r\n\r\n return { 'Cache-Control': directives.join(', ') };\r\n }\r\n};\r\n\r\n// ============================================================================\r\n// Request Helpers\r\n// ============================================================================\r\n\r\n/**\r\n * Parse JSON body from request\r\n */\r\nexport async function parseJson<T = unknown>(request: Request): Promise<T> {\r\n try {\r\n return await request.json();\r\n } catch {\r\n throw new Error('Invalid JSON body');\r\n }\r\n}\r\n\r\n/**\r\n * Parse form data from request\r\n */\r\nexport async function parseFormData(request: Request): Promise<FormData> {\r\n return await request.formData();\r\n}\r\n\r\n/**\r\n * Parse URL search params\r\n */\r\nexport function parseSearchParams(request: Request): URLSearchParams {\r\n const url = new URL(request.url);\r\n return url.searchParams;\r\n}\r\n\r\n/**\r\n * Get request method\r\n */\r\nexport function getMethod(request: Request): string {\r\n return request.method.toUpperCase();\r\n}\r\n\r\n/**\r\n * Get request pathname\r\n */\r\nexport function getPathname(request: Request): string {\r\n const url = new URL(request.url);\r\n return url.pathname;\r\n}\r\n\r\n/**\r\n * Check if request method matches\r\n */\r\nexport function isMethod(request: Request, method: string | string[]): boolean {\r\n const reqMethod = getMethod(request);\r\n if (Array.isArray(method)) {\r\n return method.map(m => m.toUpperCase()).includes(reqMethod);\r\n }\r\n return reqMethod === method.toUpperCase();\r\n}\r\n","/**\r\n * FlexiReact Server Actions\r\n * \r\n * Server Actions allow you to define server-side functions that can be called\r\n * directly from client components. They are automatically serialized and executed\r\n * on the server.\r\n * \r\n * Usage:\r\n * ```tsx\r\n * // In a server file (actions.ts)\r\n * 'use server';\r\n * \r\n * export async function createUser(formData: FormData) {\r\n * const name = formData.get('name');\r\n * // Save to database...\r\n * return { success: true, id: 123 };\r\n * }\r\n * \r\n * // In a client component\r\n * 'use client';\r\n * import { createUser } from './actions';\r\n * \r\n * function Form() {\r\n * return (\r\n * <form action={createUser}>\r\n * <input name=\"name\" />\r\n * <button type=\"submit\">Create</button>\r\n * </form>\r\n * );\r\n * }\r\n * ```\r\n */\r\n\r\nimport { cookies, headers, redirect, notFound, RedirectError, NotFoundError } from '../helpers.js';\r\n\r\n// Global action registry\r\ndeclare global {\r\n var __FLEXI_ACTIONS__: Record<string, ServerActionFunction>;\r\n var __FLEXI_ACTION_CONTEXT__: ActionContext | null;\r\n}\r\n\r\nglobalThis.__FLEXI_ACTIONS__ = globalThis.__FLEXI_ACTIONS__ || {};\r\nglobalThis.__FLEXI_ACTION_CONTEXT__ = null;\r\n\r\nexport interface ActionContext {\r\n request: Request;\r\n cookies: typeof cookies;\r\n headers: typeof headers;\r\n redirect: typeof redirect;\r\n notFound: typeof notFound;\r\n}\r\n\r\nexport type ServerActionFunction = (...args: any[]) => Promise<any>;\r\n\r\nexport interface ActionResult<T = any> {\r\n success: boolean;\r\n data?: T;\r\n error?: string;\r\n redirect?: string;\r\n}\r\n\r\n/**\r\n * Decorator to mark a function as a server action\r\n */\r\nexport function serverAction<T extends ServerActionFunction>(\r\n fn: T,\r\n actionId?: string\r\n): T {\r\n const id = actionId || `action_${fn.name}_${generateActionId()}`;\r\n \r\n // Register the action\r\n globalThis.__FLEXI_ACTIONS__[id] = fn;\r\n \r\n // Create a proxy that will be serialized for the client\r\n const proxy = (async (...args: any[]) => {\r\n // If we're on the server, execute directly\r\n if (typeof window === 'undefined') {\r\n return await executeAction(id, args);\r\n }\r\n \r\n // If we're on the client, make a fetch request\r\n return await callServerAction(id, args);\r\n }) as T;\r\n \r\n // Mark as server action\r\n (proxy as any).$$typeof = Symbol.for('react.server.action');\r\n (proxy as any).$$id = id;\r\n (proxy as any).$$bound = null;\r\n \r\n return proxy;\r\n}\r\n\r\n/**\r\n * Register a server action\r\n */\r\nexport function registerAction(id: string, fn: ServerActionFunction): void {\r\n globalThis.__FLEXI_ACTIONS__[id] = fn;\r\n}\r\n\r\n/**\r\n * Get a registered action\r\n */\r\nexport function getAction(id: string): ServerActionFunction | undefined {\r\n return globalThis.__FLEXI_ACTIONS__[id];\r\n}\r\n\r\n/**\r\n * Execute a server action on the server\r\n */\r\nexport async function executeAction(\r\n actionId: string,\r\n args: any[],\r\n context?: Partial<ActionContext>\r\n): Promise<ActionResult> {\r\n const action = globalThis.__FLEXI_ACTIONS__[actionId];\r\n \r\n if (!action) {\r\n return {\r\n success: false,\r\n error: `Server action not found: ${actionId}`\r\n };\r\n }\r\n \r\n // Set up action context\r\n const actionContext: ActionContext = {\r\n request: context?.request || new Request('http://localhost'),\r\n cookies,\r\n headers,\r\n redirect,\r\n notFound\r\n };\r\n \r\n globalThis.__FLEXI_ACTION_CONTEXT__ = actionContext;\r\n \r\n try {\r\n const result = await action(...args);\r\n \r\n return {\r\n success: true,\r\n data: result\r\n };\r\n } catch (error: any) {\r\n // Handle redirect\r\n if (error instanceof RedirectError) {\r\n return {\r\n success: true,\r\n redirect: error.url\r\n };\r\n }\r\n \r\n // Handle not found\r\n if (error instanceof NotFoundError) {\r\n return {\r\n success: false,\r\n error: 'Not found'\r\n };\r\n }\r\n \r\n return {\r\n success: false,\r\n error: error.message || 'Action failed'\r\n };\r\n } finally {\r\n globalThis.__FLEXI_ACTION_CONTEXT__ = null;\r\n }\r\n}\r\n\r\n/**\r\n * Call a server action from the client\r\n */\r\nexport async function callServerAction(\r\n actionId: string,\r\n args: any[]\r\n): Promise<ActionResult> {\r\n try {\r\n const response = await fetch('/_flexi/action', {\r\n method: 'POST',\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n 'X-Flexi-Action': actionId\r\n },\r\n body: JSON.stringify({\r\n actionId,\r\n args: serializeArgs(args)\r\n }),\r\n credentials: 'same-origin'\r\n });\r\n \r\n if (!response.ok) {\r\n throw new Error(`Action failed: ${response.statusText}`);\r\n }\r\n \r\n const result = await response.json();\r\n \r\n // Handle redirect\r\n if (result.redirect) {\r\n window.location.href = result.redirect;\r\n return result;\r\n }\r\n \r\n return result;\r\n } catch (error: any) {\r\n return {\r\n success: false,\r\n error: error.message || 'Network error'\r\n };\r\n }\r\n}\r\n\r\n/**\r\n * Serialize action arguments for transmission\r\n */\r\nfunction serializeArgs(args: any[]): any[] {\r\n return args.map(arg => {\r\n // Handle FormData\r\n if (arg instanceof FormData) {\r\n const obj: Record<string, any> = {};\r\n arg.forEach((value, key) => {\r\n if (obj[key]) {\r\n // Handle multiple values\r\n if (Array.isArray(obj[key])) {\r\n obj[key].push(value);\r\n } else {\r\n obj[key] = [obj[key], value];\r\n }\r\n } else {\r\n obj[key] = value;\r\n }\r\n });\r\n return { $$type: 'FormData', data: obj };\r\n }\r\n \r\n // Handle File\r\n if (typeof File !== 'undefined' && arg instanceof File) {\r\n return { $$type: 'File', name: arg.name, type: arg.type, size: arg.size };\r\n }\r\n \r\n // Handle Date\r\n if (arg instanceof Date) {\r\n return { $$type: 'Date', value: arg.toISOString() };\r\n }\r\n \r\n // Handle regular objects\r\n if (typeof arg === 'object' && arg !== null) {\r\n return JSON.parse(JSON.stringify(arg));\r\n }\r\n \r\n return arg;\r\n });\r\n}\r\n\r\n/**\r\n * Deserialize action arguments on the server\r\n */\r\nexport function deserializeArgs(args: any[]): any[] {\r\n return args.map(arg => {\r\n if (arg && typeof arg === 'object') {\r\n // Handle FormData\r\n if (arg.$$type === 'FormData') {\r\n const formData = new FormData();\r\n for (const [key, value] of Object.entries(arg.data)) {\r\n if (Array.isArray(value)) {\r\n value.forEach(v => formData.append(key, v as string));\r\n } else {\r\n formData.append(key, value as string);\r\n }\r\n }\r\n return formData;\r\n }\r\n \r\n // Handle Date\r\n if (arg.$$type === 'Date') {\r\n return new Date(arg.value);\r\n }\r\n }\r\n \r\n return arg;\r\n });\r\n}\r\n\r\n/**\r\n * Generate a unique action ID\r\n */\r\nfunction generateActionId(): string {\r\n return Math.random().toString(36).substring(2, 10);\r\n}\r\n\r\n/**\r\n * Hook to get the current action context\r\n */\r\nexport function useActionContext(): ActionContext | null {\r\n return globalThis.__FLEXI_ACTION_CONTEXT__;\r\n}\r\n\r\n/**\r\n * Create a form action handler\r\n * Wraps a server action for use with HTML forms\r\n */\r\nexport function formAction<T>(\r\n action: (formData: FormData) => Promise<T>\r\n): (formData: FormData) => Promise<ActionResult<T>> {\r\n return async (formData: FormData) => {\r\n try {\r\n const result = await action(formData);\r\n return { success: true, data: result };\r\n } catch (error: any) {\r\n if (error instanceof RedirectError) {\r\n return { success: true, redirect: error.url };\r\n }\r\n return { success: false, error: error.message };\r\n }\r\n };\r\n}\r\n\r\n/**\r\n * useFormState hook for progressive enhancement\r\n * Works with server actions and provides loading/error states\r\n */\r\nexport function createFormState<T>(\r\n action: (formData: FormData) => Promise<ActionResult<T>>,\r\n initialState: T | null = null\r\n) {\r\n return {\r\n action,\r\n initialState,\r\n // This will be enhanced on the client\r\n pending: false,\r\n error: null as string | null,\r\n data: initialState\r\n };\r\n}\r\n\r\n/**\r\n * Bind arguments to a server action\r\n * Creates a new action with pre-filled arguments\r\n */\r\nexport function bindArgs<T extends ServerActionFunction>(\r\n action: T,\r\n ...boundArgs: any[]\r\n): T {\r\n const boundAction = (async (...args: any[]) => {\r\n return await (action as any)(...boundArgs, ...args);\r\n }) as T;\r\n \r\n // Copy action metadata\r\n (boundAction as any).$$typeof = (action as any).$$typeof;\r\n (boundAction as any).$$id = (action as any).$$id;\r\n (boundAction as any).$$bound = boundArgs;\r\n \r\n return boundAction;\r\n}\r\n\r\nexport default {\r\n serverAction,\r\n registerAction,\r\n getAction,\r\n executeAction,\r\n callServerAction,\r\n deserializeArgs,\r\n useActionContext,\r\n formAction,\r\n createFormState,\r\n bindArgs\r\n};\r\n","/**\r\n * FlexiReact Image Optimization\r\n * \r\n * Optimized image component with:\r\n * - Automatic WebP/AVIF conversion\r\n * - Responsive srcset generation\r\n * - Lazy loading with blur placeholder\r\n * - Priority loading for LCP images\r\n * - Automatic width/height to prevent CLS\r\n */\r\n\r\nimport React from 'react';\r\nimport path from 'path';\r\nimport fs from 'fs';\r\nimport crypto from 'crypto';\r\n\r\n// Image optimization config\r\nexport interface ImageConfig {\r\n domains: string[];\r\n deviceSizes: number[];\r\n imageSizes: number[];\r\n formats: ('webp' | 'avif' | 'png' | 'jpeg')[];\r\n minimumCacheTTL: number;\r\n dangerouslyAllowSVG: boolean;\r\n quality: number;\r\n cacheDir: string;\r\n}\r\n\r\nexport const defaultImageConfig: ImageConfig = {\r\n domains: [],\r\n deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],\r\n imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],\r\n formats: ['webp', 'avif'],\r\n minimumCacheTTL: 60 * 60 * 24 * 30, // 30 days\r\n dangerouslyAllowSVG: false,\r\n quality: 75,\r\n cacheDir: '.flexi/image-cache'\r\n};\r\n\r\n// Image props\r\nexport interface ImageProps {\r\n src: string;\r\n alt: string;\r\n width?: number;\r\n height?: number;\r\n fill?: boolean;\r\n sizes?: string;\r\n quality?: number;\r\n priority?: boolean;\r\n placeholder?: 'blur' | 'empty' | 'data:image/...';\r\n blurDataURL?: string;\r\n loading?: 'lazy' | 'eager';\r\n className?: string;\r\n style?: React.CSSProperties;\r\n onLoad?: () => void;\r\n onError?: () => void;\r\n unoptimized?: boolean;\r\n}\r\n\r\n// Generate blur placeholder\r\nexport async function generateBlurPlaceholder(imagePath: string): Promise<string> {\r\n try {\r\n // For now, return a simple SVG blur placeholder\r\n // In production, we'd use sharp to generate a tiny blurred version\r\n return `data:image/svg+xml;base64,${Buffer.from(\r\n `<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 8 5\">\r\n <filter id=\"b\" color-interpolation-filters=\"sRGB\">\r\n <feGaussianBlur stdDeviation=\"1\"/>\r\n </filter>\r\n <rect width=\"100%\" height=\"100%\" fill=\"#1a1a1a\"/>\r\n <rect width=\"100%\" height=\"100%\" filter=\"url(#b)\" opacity=\"0.5\" fill=\"#333\"/>\r\n </svg>`\r\n ).toString('base64')}`;\r\n } catch {\r\n return '';\r\n }\r\n}\r\n\r\n// Get image dimensions\r\nexport async function getImageDimensions(src: string): Promise<{ width: number; height: number } | null> {\r\n try {\r\n // For local files\r\n if (!src.startsWith('http')) {\r\n const imagePath = path.join(process.cwd(), 'public', src);\r\n if (fs.existsSync(imagePath)) {\r\n // Read first bytes to detect dimensions\r\n const buffer = fs.readFileSync(imagePath);\r\n return detectDimensions(buffer);\r\n }\r\n }\r\n return null;\r\n } catch {\r\n return null;\r\n }\r\n}\r\n\r\n// Detect image dimensions from buffer\r\nfunction detectDimensions(buffer: Buffer): { width: number; height: number } | null {\r\n // PNG\r\n if (buffer[0] === 0x89 && buffer[1] === 0x50) {\r\n return {\r\n width: buffer.readUInt32BE(16),\r\n height: buffer.readUInt32BE(20)\r\n };\r\n }\r\n \r\n // JPEG\r\n if (buffer[0] === 0xff && buffer[1] === 0xd8) {\r\n let offset = 2;\r\n while (offset < buffer.length) {\r\n if (buffer[offset] !== 0xff) break;\r\n const marker = buffer[offset + 1];\r\n if (marker === 0xc0 || marker === 0xc2) {\r\n return {\r\n height: buffer.readUInt16BE(offset + 5),\r\n width: buffer.readUInt16BE(offset + 7)\r\n };\r\n }\r\n offset += 2 + buffer.readUInt16BE(offset + 2);\r\n }\r\n }\r\n \r\n // GIF\r\n if (buffer[0] === 0x47 && buffer[1] === 0x49 && buffer[2] === 0x46) {\r\n return {\r\n width: buffer.readUInt16LE(6),\r\n height: buffer.readUInt16LE(8)\r\n };\r\n }\r\n \r\n // WebP\r\n if (buffer[0] === 0x52 && buffer[1] === 0x49 && buffer[8] === 0x57 && buffer[9] === 0x45) {\r\n // VP8\r\n if (buffer[12] === 0x56 && buffer[13] === 0x50 && buffer[14] === 0x38) {\r\n if (buffer[15] === 0x20) { // VP8\r\n return {\r\n width: buffer.readUInt16LE(26) & 0x3fff,\r\n height: buffer.readUInt16LE(28) & 0x3fff\r\n };\r\n }\r\n if (buffer[15] === 0x4c) { // VP8L\r\n const bits = buffer.readUInt32LE(21);\r\n return {\r\n width: (bits & 0x3fff) + 1,\r\n height: ((bits >> 14) & 0x3fff) + 1\r\n };\r\n }\r\n }\r\n }\r\n \r\n return null;\r\n}\r\n\r\n// Generate srcset for responsive images\r\nexport function generateSrcSet(\r\n src: string,\r\n widths: number[],\r\n quality: number = 75\r\n): string {\r\n return widths\r\n .map(w => `/_flexi/image?url=${encodeURIComponent(src)}&w=${w}&q=${quality} ${w}w`)\r\n .join(', ');\r\n}\r\n\r\n// Generate sizes attribute\r\nexport function generateSizes(sizes?: string): string {\r\n if (sizes) return sizes;\r\n return '100vw';\r\n}\r\n\r\n// Image optimization endpoint handler\r\nexport async function handleImageOptimization(\r\n req: any,\r\n res: any,\r\n config: Partial<ImageConfig> = {}\r\n): Promise<void> {\r\n const fullConfig = { ...defaultImageConfig, ...config };\r\n const url = new URL(req.url, `http://${req.headers.host}`);\r\n \r\n const imageUrl = url.searchParams.get('url');\r\n const width = parseInt(url.searchParams.get('w') || '0', 10);\r\n const quality = parseInt(url.searchParams.get('q') || String(fullConfig.quality), 10);\r\n const format = url.searchParams.get('f') as 'webp' | 'avif' | 'png' | 'jpeg' | null;\r\n \r\n if (!imageUrl) {\r\n res.writeHead(400, { 'Content-Type': 'text/plain' });\r\n res.end('Missing url parameter');\r\n return;\r\n }\r\n \r\n try {\r\n let imageBuffer: Buffer;\r\n let contentType: string;\r\n \r\n // Fetch image\r\n if (imageUrl.startsWith('http')) {\r\n // Remote image\r\n const response = await fetch(imageUrl);\r\n if (!response.ok) throw new Error('Failed to fetch image');\r\n imageBuffer = Buffer.from(await response.arrayBuffer());\r\n contentType = response.headers.get('content-type') || 'image/jpeg';\r\n } else {\r\n // Local image\r\n const imagePath = path.join(process.cwd(), 'public', imageUrl);\r\n if (!fs.existsSync(imagePath)) {\r\n res.writeHead(404, { 'Content-Type': 'text/plain' });\r\n res.end('Image not found');\r\n return;\r\n }\r\n imageBuffer = fs.readFileSync(imagePath);\r\n contentType = getContentType(imagePath);\r\n }\r\n \r\n // Generate cache key\r\n const cacheKey = crypto\r\n .createHash('md5')\r\n .update(`${imageUrl}-${width}-${quality}-${format}`)\r\n .digest('hex');\r\n \r\n const cacheDir = path.join(process.cwd(), fullConfig.cacheDir);\r\n const cachePath = path.join(cacheDir, `${cacheKey}.${format || 'webp'}`);\r\n \r\n // Check cache\r\n if (fs.existsSync(cachePath)) {\r\n const cachedImage = fs.readFileSync(cachePath);\r\n res.writeHead(200, {\r\n 'Content-Type': `image/${format || 'webp'}`,\r\n 'Cache-Control': `public, max-age=${fullConfig.minimumCacheTTL}`,\r\n 'X-Flexi-Image-Cache': 'HIT'\r\n });\r\n res.end(cachedImage);\r\n return;\r\n }\r\n \r\n // For now, serve original image\r\n // In production, we'd use sharp for resizing/conversion\r\n // TODO: Integrate sharp for actual optimization\r\n \r\n res.writeHead(200, {\r\n 'Content-Type': contentType,\r\n 'Cache-Control': `public, max-age=${fullConfig.minimumCacheTTL}`,\r\n 'X-Flexi-Image-Cache': 'MISS'\r\n });\r\n res.end(imageBuffer);\r\n \r\n } catch (error: any) {\r\n console.error('Image optimization error:', error);\r\n res.writeHead(500, { 'Content-Type': 'text/plain' });\r\n res.end('Image optimization failed');\r\n }\r\n}\r\n\r\n// Get content type from file extension\r\nfunction getContentType(filePath: string): string {\r\n const ext = path.extname(filePath).toLowerCase();\r\n const types: Record<string, string> = {\r\n '.jpg': 'image/jpeg',\r\n '.jpeg': 'image/jpeg',\r\n '.png': 'image/png',\r\n '.gif': 'image/gif',\r\n '.webp': 'image/webp',\r\n '.avif': 'image/avif',\r\n '.svg': 'image/svg+xml',\r\n '.ico': 'image/x-icon'\r\n };\r\n return types[ext] || 'application/octet-stream';\r\n}\r\n\r\n// Image component (server-side rendered)\r\nexport function createImageComponent(config: Partial<ImageConfig> = {}) {\r\n const fullConfig = { ...defaultImageConfig, ...config };\r\n \r\n return function Image(props: ImageProps): React.ReactElement {\r\n const {\r\n src,\r\n alt,\r\n width,\r\n height,\r\n fill = false,\r\n sizes,\r\n quality = fullConfig.quality,\r\n priority = false,\r\n placeholder = 'empty',\r\n blurDataURL,\r\n loading,\r\n className = '',\r\n style = {},\r\n unoptimized = false,\r\n ...rest\r\n } = props;\r\n \r\n // Determine loading strategy\r\n const loadingAttr = priority ? 'eager' : (loading || 'lazy');\r\n \r\n // Generate optimized src\r\n const optimizedSrc = unoptimized \r\n ? src \r\n : `/_flexi/image?url=${encodeURIComponent(src)}&w=${width || 1920}&q=${quality}`;\r\n \r\n // Generate srcset for responsive images\r\n const allSizes = [...fullConfig.imageSizes, ...fullConfig.deviceSizes].sort((a, b) => a - b);\r\n const relevantSizes = width \r\n ? allSizes.filter(s => s <= width * 2)\r\n : allSizes;\r\n \r\n const srcSet = unoptimized \r\n ? undefined \r\n : generateSrcSet(src, relevantSizes, quality);\r\n \r\n // Build styles\r\n const imgStyle: React.CSSProperties = {\r\n ...style,\r\n ...(fill ? {\r\n position: 'absolute',\r\n top: 0,\r\n left: 0,\r\n width: '100%',\r\n height: '100%',\r\n objectFit: 'cover'\r\n } : {})\r\n };\r\n \r\n // Placeholder styles\r\n const wrapperStyle: React.CSSProperties = fill ? {\r\n position: 'relative',\r\n width: '100%',\r\n height: '100%'\r\n } : {};\r\n \r\n const placeholderStyle: React.CSSProperties = placeholder === 'blur' ? {\r\n backgroundImage: `url(${blurDataURL || generateBlurPlaceholderSync()})`,\r\n backgroundSize: 'cover',\r\n backgroundPosition: 'center',\r\n filter: 'blur(20px)',\r\n transform: 'scale(1.1)'\r\n } : {};\r\n \r\n // Create image element\r\n const imgElement = React.createElement('img', {\r\n src: optimizedSrc,\r\n alt,\r\n width: fill ? undefined : width,\r\n height: fill ? undefined : height,\r\n loading: loadingAttr,\r\n decoding: 'async',\r\n srcSet,\r\n sizes: generateSizes(sizes),\r\n className: `flexi-image ${className}`.trim(),\r\n style: imgStyle,\r\n fetchPriority: priority ? 'high' : undefined,\r\n ...rest\r\n });\r\n \r\n // Wrap with placeholder if needed\r\n if (fill || placeholder === 'blur') {\r\n return React.createElement('div', {\r\n className: 'flexi-image-wrapper',\r\n style: { ...wrapperStyle, ...placeholderStyle }\r\n }, imgElement);\r\n }\r\n \r\n return imgElement;\r\n };\r\n}\r\n\r\n// Sync blur placeholder (for SSR)\r\nfunction generateBlurPlaceholderSync(): string {\r\n return `data:image/svg+xml;base64,${Buffer.from(\r\n `<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 8 5\">\r\n <filter id=\"b\" color-interpolation-filters=\"sRGB\">\r\n <feGaussianBlur stdDeviation=\"1\"/>\r\n </filter>\r\n <rect width=\"100%\" height=\"100%\" fill=\"#1a1a1a\"/>\r\n </svg>`\r\n ).toString('base64')}`;\r\n}\r\n\r\n// Default Image component\r\nexport const Image = createImageComponent();\r\n\r\n// Loader types for different image providers\r\nexport interface ImageLoader {\r\n (props: { src: string; width: number; quality?: number }): string;\r\n}\r\n\r\n// Built-in loaders\r\nexport const imageLoaders = {\r\n default: ({ src, width, quality = 75 }: { src: string; width: number; quality?: number }) =>\r\n `/_flexi/image?url=${encodeURIComponent(src)}&w=${width}&q=${quality}`,\r\n \r\n cloudinary: ({ src, width, quality = 75 }: { src: string; width: number; quality?: number }) =>\r\n `https://res.cloudinary.com/demo/image/fetch/w_${width},q_${quality}/${src}`,\r\n \r\n imgix: ({ src, width, quality = 75 }: { src: string; width: number; quality?: number }) =>\r\n `${src}?w=${width}&q=${quality}&auto=format`,\r\n \r\n vercel: ({ src, width, quality = 75 }: { src: string; width: number; quality?: number }) =>\r\n `/_vercel/image?url=${encodeURIComponent(src)}&w=${width}&q=${quality}`,\r\n \r\n cloudflare: ({ src, width, quality = 75 }: { src: string; width: number; quality?: number }) =>\r\n `/cdn-cgi/image/width=${width},quality=${quality}/${src}`\r\n};\r\n\r\nexport default {\r\n Image,\r\n createImageComponent,\r\n handleImageOptimization,\r\n generateBlurPlaceholder,\r\n getImageDimensions,\r\n generateSrcSet,\r\n imageLoaders,\r\n defaultImageConfig\r\n};\r\n","/**\r\n * FlexiReact Font Optimization\r\n * \r\n * Optimized font loading with:\r\n * - Automatic font subsetting\r\n * - Preload hints generation\r\n * - Font-display: swap by default\r\n * - Self-hosted Google Fonts\r\n * - Variable font support\r\n * - CSS variable generation\r\n */\r\n\r\nimport fs from 'fs';\r\nimport path from 'path';\r\nimport crypto from 'crypto';\r\n\r\n// Font configuration\r\nexport interface FontConfig {\r\n family: string;\r\n weight?: string | number | (string | number)[];\r\n style?: 'normal' | 'italic' | 'oblique';\r\n subsets?: string[];\r\n display?: 'auto' | 'block' | 'swap' | 'fallback' | 'optional';\r\n preload?: boolean;\r\n fallback?: string[];\r\n variable?: string;\r\n adjustFontFallback?: boolean;\r\n}\r\n\r\nexport interface FontResult {\r\n className: string;\r\n style: {\r\n fontFamily: string;\r\n fontWeight?: number | string;\r\n fontStyle?: string;\r\n };\r\n variable?: string;\r\n}\r\n\r\n// Google Fonts API\r\nconst GOOGLE_FONTS_API = 'https://fonts.googleapis.com/css2';\r\n\r\n// Popular Google Fonts with their weights\r\nexport const googleFonts = {\r\n Inter: {\r\n weights: [100, 200, 300, 400, 500, 600, 700, 800, 900],\r\n variable: true,\r\n subsets: ['latin', 'latin-ext', 'cyrillic', 'greek', 'vietnamese']\r\n },\r\n Roboto: {\r\n weights: [100, 300, 400, 500, 700, 900],\r\n variable: false,\r\n subsets: ['latin', 'latin-ext', 'cyrillic', 'greek', 'vietnamese']\r\n },\r\n 'Open Sans': {\r\n weights: [300, 400, 500, 600, 700, 800],\r\n variable: true,\r\n subsets: ['latin', 'latin-ext', 'cyrillic', 'greek', 'vietnamese']\r\n },\r\n Poppins: {\r\n weights: [100, 200, 300, 400, 500, 600, 700, 800, 900],\r\n variable: false,\r\n subsets: ['latin', 'latin-ext']\r\n },\r\n Montserrat: {\r\n weights: [100, 200, 300, 400, 500, 600, 700, 800, 900],\r\n variable: true,\r\n subsets: ['latin', 'latin-ext', 'cyrillic', 'vietnamese']\r\n },\r\n 'Fira Code': {\r\n weights: [300, 400, 500, 600, 700],\r\n variable: true,\r\n subsets: ['latin', 'latin-ext', 'cyrillic', 'greek']\r\n },\r\n 'JetBrains Mono': {\r\n weights: [100, 200, 300, 400, 500, 600, 700, 800],\r\n variable: true,\r\n subsets: ['latin', 'latin-ext', 'cyrillic', 'greek']\r\n },\r\n Geist: {\r\n weights: [100, 200, 300, 400, 500, 600, 700, 800, 900],\r\n variable: true,\r\n subsets: ['latin', 'latin-ext']\r\n },\r\n 'Geist Mono': {\r\n weights: [100, 200, 300, 400, 500, 600, 700, 800, 900],\r\n variable: true,\r\n subsets: ['latin', 'latin-ext']\r\n }\r\n};\r\n\r\n// Generate font CSS\r\nexport function generateFontCSS(config: FontConfig): string {\r\n const {\r\n family,\r\n weight = 400,\r\n style = 'normal',\r\n display = 'swap',\r\n fallback = ['system-ui', 'sans-serif'],\r\n variable\r\n } = config;\r\n\r\n const weights = Array.isArray(weight) ? weight : [weight];\r\n const fallbackStr = fallback.map(f => f.includes(' ') ? `\"${f}\"` : f).join(', ');\r\n\r\n let css = '';\r\n\r\n // Generate @font-face for each weight\r\n for (const w of weights) {\r\n css += `\r\n@font-face {\r\n font-family: '${family}';\r\n font-style: ${style};\r\n font-weight: ${w};\r\n font-display: ${display};\r\n src: local('${family}'),\r\n url('/_flexi/font/${encodeURIComponent(family)}?weight=${w}&style=${style}') format('woff2');\r\n}\r\n`;\r\n }\r\n\r\n // Generate CSS variable if specified\r\n if (variable) {\r\n css += `\r\n:root {\r\n ${variable}: '${family}', ${fallbackStr};\r\n}\r\n`;\r\n }\r\n\r\n return css;\r\n}\r\n\r\n// Generate preload link tags\r\nexport function generateFontPreloadTags(fonts: FontConfig[]): string {\r\n return fonts\r\n .filter(f => f.preload !== false)\r\n .map(f => {\r\n const weights = Array.isArray(f.weight) ? f.weight : [f.weight || 400];\r\n return weights.map(w => \r\n `<link rel=\"preload\" href=\"/_flexi/font/${encodeURIComponent(f.family)}?weight=${w}&style=${f.style || 'normal'}\" as=\"font\" type=\"font/woff2\" crossorigin>`\r\n ).join('\\n');\r\n })\r\n .join('\\n');\r\n}\r\n\r\n// Create a font loader function (like next/font)\r\nexport function createFont(config: FontConfig): FontResult {\r\n const {\r\n family,\r\n weight = 400,\r\n style = 'normal',\r\n fallback = ['system-ui', 'sans-serif'],\r\n variable\r\n } = config;\r\n\r\n // Generate unique class name\r\n const hash = crypto\r\n .createHash('md5')\r\n .update(`${family}-${weight}-${style}`)\r\n .digest('hex')\r\n .slice(0, 8);\r\n\r\n const className = `__font_${hash}`;\r\n const fallbackStr = fallback.map(f => f.includes(' ') ? `\"${f}\"` : f).join(', ');\r\n\r\n return {\r\n className,\r\n style: {\r\n fontFamily: `'${family}', ${fallbackStr}`,\r\n fontWeight: Array.isArray(weight) ? undefined : weight,\r\n fontStyle: style\r\n },\r\n variable: variable || undefined\r\n };\r\n}\r\n\r\n// Google Font loader\r\nexport function googleFont(config: FontConfig): FontResult {\r\n return createFont({\r\n ...config,\r\n // Google Fonts are always preloaded\r\n preload: true\r\n });\r\n}\r\n\r\n// Local font loader\r\nexport function localFont(config: FontConfig & { src: string | { path: string; weight?: string | number; style?: string }[] }): FontResult {\r\n return createFont(config);\r\n}\r\n\r\n// Handle font requests\r\nexport async function handleFontRequest(\r\n req: any,\r\n res: any\r\n): Promise<void> {\r\n const url = new URL(req.url, `http://${req.headers.host}`);\r\n const pathParts = url.pathname.split('/');\r\n const fontFamily = decodeURIComponent(pathParts[pathParts.length - 1] || '');\r\n const weight = url.searchParams.get('weight') || '400';\r\n const style = url.searchParams.get('style') || 'normal';\r\n\r\n if (!fontFamily) {\r\n res.writeHead(400, { 'Content-Type': 'text/plain' });\r\n res.end('Missing font family');\r\n return;\r\n }\r\n\r\n try {\r\n // Check local cache first\r\n const cacheDir = path.join(process.cwd(), '.flexi', 'font-cache');\r\n const cacheKey = crypto\r\n .createHash('md5')\r\n .update(`${fontFamily}-${weight}-${style}`)\r\n .digest('hex');\r\n const cachePath = path.join(cacheDir, `${cacheKey}.woff2`);\r\n\r\n if (fs.existsSync(cachePath)) {\r\n const fontData = fs.readFileSync(cachePath);\r\n res.writeHead(200, {\r\n 'Content-Type': 'font/woff2',\r\n 'Cache-Control': 'public, max-age=31536000, immutable',\r\n 'X-Flexi-Font-Cache': 'HIT'\r\n });\r\n res.end(fontData);\r\n return;\r\n }\r\n\r\n // Fetch from Google Fonts\r\n const googleUrl = `${GOOGLE_FONTS_API}?family=${encodeURIComponent(fontFamily)}:wght@${weight}&display=swap`;\r\n \r\n const cssResponse = await fetch(googleUrl, {\r\n headers: {\r\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'\r\n }\r\n });\r\n\r\n if (!cssResponse.ok) {\r\n throw new Error('Failed to fetch font CSS');\r\n }\r\n\r\n const css = await cssResponse.text();\r\n \r\n // Extract woff2 URL from CSS\r\n const woff2Match = css.match(/url\\((https:\\/\\/fonts\\.gstatic\\.com[^)]+\\.woff2)\\)/);\r\n \r\n if (!woff2Match) {\r\n throw new Error('Could not find woff2 URL');\r\n }\r\n\r\n // Fetch the actual font file\r\n const fontResponse = await fetch(woff2Match[1]);\r\n \r\n if (!fontResponse.ok) {\r\n throw new Error('Failed to fetch font file');\r\n }\r\n\r\n const fontBuffer = Buffer.from(await fontResponse.arrayBuffer());\r\n\r\n // Cache the font\r\n if (!fs.existsSync(cacheDir)) {\r\n fs.mkdirSync(cacheDir, { recursive: true });\r\n }\r\n fs.writeFileSync(cachePath, fontBuffer);\r\n\r\n // Serve the font\r\n res.writeHead(200, {\r\n 'Content-Type': 'font/woff2',\r\n 'Cache-Control': 'public, max-age=31536000, immutable',\r\n 'X-Flexi-Font-Cache': 'MISS'\r\n });\r\n res.end(fontBuffer);\r\n\r\n } catch (error: any) {\r\n console.error('Font loading error:', error);\r\n res.writeHead(500, { 'Content-Type': 'text/plain' });\r\n res.end('Font loading failed');\r\n }\r\n}\r\n\r\n// Pre-built font configurations\r\nexport const fonts = {\r\n // Sans-serif\r\n inter: (config: Partial<FontConfig> = {}) => googleFont({ family: 'Inter', variable: '--font-inter', ...config }),\r\n roboto: (config: Partial<FontConfig> = {}) => googleFont({ family: 'Roboto', variable: '--font-roboto', ...config }),\r\n openSans: (config: Partial<FontConfig> = {}) => googleFont({ family: 'Open Sans', variable: '--font-open-sans', ...config }),\r\n poppins: (config: Partial<FontConfig> = {}) => googleFont({ family: 'Poppins', variable: '--font-poppins', ...config }),\r\n montserrat: (config: Partial<FontConfig> = {}) => googleFont({ family: 'Montserrat', variable: '--font-montserrat', ...config }),\r\n geist: (config: Partial<FontConfig> = {}) => googleFont({ family: 'Geist', variable: '--font-geist', ...config }),\r\n \r\n // Monospace\r\n firaCode: (config: Partial<FontConfig> = {}) => googleFont({ family: 'Fira Code', variable: '--font-fira-code', fallback: ['monospace'], ...config }),\r\n jetbrainsMono: (config: Partial<FontConfig> = {}) => googleFont({ family: 'JetBrains Mono', variable: '--font-jetbrains', fallback: ['monospace'], ...config }),\r\n geistMono: (config: Partial<FontConfig> = {}) => googleFont({ family: 'Geist Mono', variable: '--font-geist-mono', fallback: ['monospace'], ...config })\r\n};\r\n\r\nexport default {\r\n createFont,\r\n googleFont,\r\n localFont,\r\n generateFontCSS,\r\n generateFontPreloadTags,\r\n handleFontRequest,\r\n fonts,\r\n googleFonts\r\n};\r\n","/**\r\n * FlexiReact Build System\r\n * Uses esbuild for fast bundling of client and server code\r\n */\r\n\r\nimport * as esbuild from 'esbuild';\r\nimport fs from 'fs';\r\nimport path from 'path';\r\nimport { fileURLToPath } from 'url';\r\nimport { findFiles, ensureDir, cleanDir, generateHash, isClientComponent, isIsland } from '../utils.js';\r\nimport { buildRouteTree } from '../router/index.js';\r\n\r\nconst __filename = fileURLToPath(import.meta.url);\r\nconst __dirname = path.dirname(__filename);\r\n\r\n/**\r\n * Build configuration\r\n */\r\nexport const BuildMode = {\r\n DEVELOPMENT: 'development',\r\n PRODUCTION: 'production'\r\n};\r\n\r\n/**\r\n * Main build function\r\n */\r\nexport async function build(options) {\r\n const {\r\n projectRoot,\r\n config,\r\n mode = BuildMode.PRODUCTION,\r\n analyze = false\r\n } = options;\r\n\r\n const startTime = Date.now();\r\n const outDir = config.outDir;\r\n const isDev = mode === BuildMode.DEVELOPMENT;\r\n\r\n console.log('\\n⚡ FlexiReact Build\\n');\r\n console.log(` Mode: ${mode}`);\r\n console.log(` Output: ${outDir}\\n`);\r\n\r\n // Clean output directory\r\n cleanDir(outDir);\r\n ensureDir(path.join(outDir, 'client'));\r\n ensureDir(path.join(outDir, 'server'));\r\n ensureDir(path.join(outDir, 'static'));\r\n\r\n // Build routes\r\n const routes = buildRouteTree(config.pagesDir, config.layoutsDir);\r\n \r\n // Find all client components and islands\r\n const clientEntries = findClientEntries(config.pagesDir, config.layoutsDir);\r\n \r\n // Build client bundle\r\n console.log('📦 Building client bundle...');\r\n const clientResult = await buildClient({\r\n entries: clientEntries,\r\n outDir: path.join(outDir, 'client'),\r\n config,\r\n isDev\r\n });\r\n\r\n // Build server bundle\r\n console.log('📦 Building server bundle...');\r\n const serverResult = await buildServer({\r\n pagesDir: config.pagesDir,\r\n layoutsDir: config.layoutsDir,\r\n outDir: path.join(outDir, 'server'),\r\n config,\r\n isDev\r\n });\r\n\r\n // Copy public assets\r\n console.log('📁 Copying public assets...');\r\n await copyPublicAssets(config.publicDir, path.join(outDir, 'static'));\r\n\r\n // Generate manifest\r\n const manifest = generateManifest({\r\n routes,\r\n clientResult,\r\n serverResult,\r\n config\r\n });\r\n \r\n fs.writeFileSync(\r\n path.join(outDir, 'manifest.json'),\r\n JSON.stringify(manifest, null, 2)\r\n );\r\n\r\n const duration = Date.now() - startTime;\r\n \r\n console.log('\\n✨ Build complete!\\n');\r\n console.log(` Duration: ${duration}ms`);\r\n console.log(` Client chunks: ${clientResult.outputs.length}`);\r\n console.log(` Server modules: ${serverResult.outputs.length}`);\r\n console.log('');\r\n\r\n // Generate bundle analysis if requested\r\n let analysis = null;\r\n if (analyze) {\r\n analysis = generateBundleAnalysis(clientResult, serverResult, outDir);\r\n }\r\n\r\n return {\r\n success: true,\r\n duration,\r\n manifest,\r\n clientResult,\r\n serverResult,\r\n analysis\r\n };\r\n}\r\n\r\n/**\r\n * Generates bundle analysis data\r\n */\r\nfunction generateBundleAnalysis(clientResult, serverResult, outDir) {\r\n const files: Record<string, { size: number; gzipSize?: number }> = {};\r\n let totalSize = 0;\r\n let totalGzipSize = 0;\r\n\r\n // Analyze client outputs\r\n for (const output of clientResult.outputs || []) {\r\n if (output.path && fs.existsSync(output.path)) {\r\n const stat = fs.statSync(output.path);\r\n const relativePath = path.relative(outDir, output.path);\r\n \r\n // Estimate gzip size (roughly 30% of original for JS)\r\n const gzipSize = Math.round(stat.size * 0.3);\r\n \r\n files[relativePath] = {\r\n size: stat.size,\r\n gzipSize\r\n };\r\n \r\n totalSize += stat.size;\r\n totalGzipSize += gzipSize;\r\n }\r\n }\r\n\r\n // Analyze server outputs\r\n for (const output of serverResult.outputs || []) {\r\n if (output.path && fs.existsSync(output.path)) {\r\n const stat = fs.statSync(output.path);\r\n const relativePath = path.relative(outDir, output.path);\r\n \r\n files[relativePath] = {\r\n size: stat.size\r\n };\r\n \r\n totalSize += stat.size;\r\n }\r\n }\r\n\r\n return {\r\n files,\r\n totalSize,\r\n totalGzipSize,\r\n clientSize: clientResult.outputs?.reduce((sum, o) => {\r\n if (o.path && fs.existsSync(o.path)) {\r\n return sum + fs.statSync(o.path).size;\r\n }\r\n return sum;\r\n }, 0) || 0,\r\n serverSize: serverResult.outputs?.reduce((sum, o) => {\r\n if (o.path && fs.existsSync(o.path)) {\r\n return sum + fs.statSync(o.path).size;\r\n }\r\n return sum;\r\n }, 0) || 0\r\n };\r\n}\r\n\r\n/**\r\n * Finds all client component entries\r\n */\r\nfunction findClientEntries(pagesDir, layoutsDir) {\r\n const entries = [];\r\n const dirs = [pagesDir, layoutsDir].filter(d => fs.existsSync(d));\r\n\r\n for (const dir of dirs) {\r\n const files = findFiles(dir, /\\.(jsx|tsx)$/);\r\n \r\n for (const file of files) {\r\n if (isClientComponent(file) || isIsland(file)) {\r\n entries.push(file);\r\n }\r\n }\r\n }\r\n\r\n return entries;\r\n}\r\n\r\n/**\r\n * Builds client-side JavaScript\r\n */\r\nasync function buildClient(options) {\r\n const { entries, outDir, config, isDev } = options;\r\n\r\n if (entries.length === 0) {\r\n return { outputs: [] };\r\n }\r\n\r\n // Create entry points map\r\n const entryPoints = {};\r\n for (const entry of entries) {\r\n const name = path.basename(entry, path.extname(entry));\r\n const hash = generateHash(entry);\r\n entryPoints[`${name}-${hash}`] = entry;\r\n }\r\n\r\n // Add runtime entry\r\n const runtimePath = path.join(__dirname, '..', 'client', 'runtime.js');\r\n if (fs.existsSync(runtimePath)) {\r\n entryPoints['runtime'] = runtimePath;\r\n }\r\n\r\n try {\r\n const result = await esbuild.build({\r\n entryPoints,\r\n bundle: true,\r\n splitting: true,\r\n format: 'esm',\r\n outdir: outDir,\r\n minify: !isDev && config.build.minify,\r\n sourcemap: config.build.sourcemap,\r\n target: config.build.target,\r\n jsx: 'automatic',\r\n jsxImportSource: 'react',\r\n metafile: true,\r\n external: [],\r\n define: {\r\n 'process.env.NODE_ENV': JSON.stringify(isDev ? 'development' : 'production')\r\n },\r\n loader: {\r\n '.js': 'jsx',\r\n '.jsx': 'jsx',\r\n '.ts': 'tsx',\r\n '.tsx': 'tsx'\r\n }\r\n });\r\n\r\n const outputs = Object.keys(result.metafile.outputs).map(file => ({\r\n file: path.basename(file),\r\n size: result.metafile.outputs[file].bytes\r\n }));\r\n\r\n return { outputs, metafile: result.metafile };\r\n\r\n } catch (error) {\r\n console.error('Client build failed:', error);\r\n throw error;\r\n }\r\n}\r\n\r\n/**\r\n * Builds server-side modules\r\n */\r\nasync function buildServer(options) {\r\n const { pagesDir, layoutsDir, outDir, config, isDev } = options;\r\n\r\n const entries = [];\r\n \r\n // Find all page and layout files\r\n for (const dir of [pagesDir, layoutsDir]) {\r\n if (fs.existsSync(dir)) {\r\n entries.push(...findFiles(dir, /\\.(jsx|tsx|js|ts)$/));\r\n }\r\n }\r\n\r\n if (entries.length === 0) {\r\n return { outputs: [] };\r\n }\r\n\r\n // Create entry points\r\n const entryPoints = {};\r\n for (const entry of entries) {\r\n const relativePath = path.relative(pagesDir, entry);\r\n const name = relativePath.replace(/[\\/\\\\]/g, '_').replace(/\\.(jsx|tsx|js|ts)$/, '');\r\n entryPoints[name] = entry;\r\n }\r\n\r\n try {\r\n const result = await esbuild.build({\r\n entryPoints,\r\n bundle: true,\r\n format: 'esm',\r\n platform: 'node',\r\n outdir: outDir,\r\n minify: false, // Keep server code readable\r\n sourcemap: true,\r\n target: 'node18',\r\n jsx: 'automatic',\r\n jsxImportSource: 'react',\r\n metafile: true,\r\n packages: 'external', // Don't bundle node_modules\r\n loader: {\r\n '.js': 'jsx',\r\n '.jsx': 'jsx',\r\n '.ts': 'tsx',\r\n '.tsx': 'tsx'\r\n }\r\n });\r\n\r\n const outputs = Object.keys(result.metafile.outputs).map(file => ({\r\n file: path.basename(file),\r\n size: result.metafile.outputs[file].bytes\r\n }));\r\n\r\n return { outputs, metafile: result.metafile };\r\n\r\n } catch (error) {\r\n console.error('Server build failed:', error);\r\n throw error;\r\n }\r\n}\r\n\r\n/**\r\n * Copies public assets to output directory\r\n */\r\nasync function copyPublicAssets(publicDir, outDir) {\r\n if (!fs.existsSync(publicDir)) {\r\n return;\r\n }\r\n\r\n const copyRecursive = (src, dest) => {\r\n const entries = fs.readdirSync(src, { withFileTypes: true });\r\n \r\n ensureDir(dest);\r\n \r\n for (const entry of entries) {\r\n const srcPath = path.join(src, entry.name);\r\n const destPath = path.join(dest, entry.name);\r\n \r\n if (entry.isDirectory()) {\r\n copyRecursive(srcPath, destPath);\r\n } else {\r\n fs.copyFileSync(srcPath, destPath);\r\n }\r\n }\r\n };\r\n\r\n copyRecursive(publicDir, outDir);\r\n}\r\n\r\n/**\r\n * Generates build manifest\r\n */\r\nfunction generateManifest(options) {\r\n const { routes, clientResult, serverResult, config } = options;\r\n\r\n return {\r\n version: '2.0.0',\r\n generatedAt: new Date().toISOString(),\r\n routes: {\r\n pages: routes.pages.map(r => ({\r\n path: r.path,\r\n file: r.filePath,\r\n hasLayout: !!r.layout,\r\n hasLoading: !!r.loading,\r\n hasError: !!r.error\r\n })),\r\n api: routes.api.map(r => ({\r\n path: r.path,\r\n file: r.filePath\r\n }))\r\n },\r\n client: {\r\n chunks: clientResult.outputs || []\r\n },\r\n server: {\r\n modules: serverResult.outputs || []\r\n },\r\n config: {\r\n islands: config.islands.enabled,\r\n rsc: config.rsc.enabled\r\n }\r\n };\r\n}\r\n\r\n/**\r\n * Development build with watch mode\r\n */\r\nexport async function buildDev(options) {\r\n const { projectRoot, config, onChange } = options;\r\n\r\n const outDir = config.outDir;\r\n ensureDir(outDir);\r\n\r\n // Use esbuild's watch mode\r\n const ctx = await esbuild.context({\r\n entryPoints: findFiles(config.pagesDir, /\\.(jsx|tsx)$/),\r\n bundle: true,\r\n format: 'esm',\r\n outdir: path.join(outDir, 'dev'),\r\n sourcemap: true,\r\n jsx: 'automatic',\r\n jsxImportSource: 'react',\r\n loader: {\r\n '.js': 'jsx',\r\n '.jsx': 'jsx'\r\n },\r\n plugins: [{\r\n name: 'flexi-watch',\r\n setup(build) {\r\n build.onEnd(result => {\r\n if (result.errors.length === 0) {\r\n onChange?.();\r\n }\r\n });\r\n }\r\n }]\r\n });\r\n\r\n await ctx.watch();\r\n\r\n return ctx;\r\n}\r\n\r\nexport default {\r\n build,\r\n buildDev,\r\n BuildMode\r\n};\r\n","/**\r\n * FlexiReact Static Site Generation (SSG)\r\n * \r\n * SSG pre-renders pages at build time, generating static HTML files.\r\n * This provides the fastest possible page loads and enables CDN caching.\r\n * \r\n * Usage:\r\n * - Export getStaticProps() from a page to fetch data at build time\r\n * - Export getStaticPaths() for dynamic routes to specify which paths to pre-render\r\n * - Pages without these exports are rendered as static HTML\r\n */\r\n\r\nimport fs from 'fs';\r\nimport path from 'path';\r\nimport { pathToFileURL } from 'url';\r\nimport { renderPage } from '../render/index.js';\r\nimport { ensureDir, cleanDir } from '../utils.js';\r\n\r\n/**\r\n * SSG Build Result\r\n */\r\ninterface SSGPage {\r\n path: string;\r\n file: string;\r\n size: number;\r\n}\r\n\r\ninterface SSGError {\r\n path: string;\r\n error: string;\r\n}\r\n\r\nexport class SSGResult {\r\n pages: SSGPage[];\r\n errors: SSGError[];\r\n duration: number;\r\n\r\n constructor() {\r\n this.pages = [];\r\n this.errors = [];\r\n this.duration = 0;\r\n }\r\n\r\n addPage(pagePath: string, file: string, size: number) {\r\n this.pages.push({ path: pagePath, file, size });\r\n }\r\n\r\n addError(pagePath: string, error: Error) {\r\n this.errors.push({ path: pagePath, error: error.message });\r\n }\r\n\r\n get success() {\r\n return this.errors.length === 0;\r\n }\r\n\r\n get totalSize() {\r\n return this.pages.reduce((sum, p) => sum + p.size, 0);\r\n }\r\n}\r\n\r\n/**\r\n * Generates static pages for all routes\r\n */\r\nexport async function generateStaticSite(options) {\r\n const {\r\n routes,\r\n outDir,\r\n config,\r\n loadModule\r\n } = options;\r\n\r\n const result = new SSGResult();\r\n const startTime = Date.now();\r\n\r\n // Clean and create output directory\r\n const staticDir = path.join(outDir, 'static');\r\n cleanDir(staticDir);\r\n\r\n console.log('\\n📦 Generating static pages...\\n');\r\n\r\n for (const route of routes) {\r\n try {\r\n await generateRoutePage(route, staticDir, loadModule, result, config);\r\n } catch (error) {\r\n console.error(` ✗ ${route.path}: ${error.message}`);\r\n result.addError(route.path, error);\r\n }\r\n }\r\n\r\n result.duration = Date.now() - startTime;\r\n\r\n // Generate summary\r\n console.log('\\n' + '─'.repeat(50));\r\n console.log(` Generated ${result.pages.length} pages in ${result.duration}ms`);\r\n if (result.errors.length > 0) {\r\n console.log(` ${result.errors.length} errors occurred`);\r\n }\r\n console.log('─'.repeat(50) + '\\n');\r\n\r\n return result;\r\n}\r\n\r\n/**\r\n * Generates a single route's static page(s)\r\n */\r\nasync function generateRoutePage(route, outDir, loadModule, result, config) {\r\n const module = await loadModule(route.filePath);\r\n const Component = module.default;\r\n\r\n if (!Component) {\r\n throw new Error(`No default export in ${route.filePath}`);\r\n }\r\n\r\n // Check for getStaticPaths (dynamic routes)\r\n let paths = [{ params: {} }];\r\n \r\n if (route.path.includes(':') || route.path.includes('*')) {\r\n if (!module.getStaticPaths) {\r\n console.log(` ⊘ ${route.path} (dynamic, no getStaticPaths)`);\r\n return;\r\n }\r\n\r\n const staticPaths = await module.getStaticPaths();\r\n paths = staticPaths.paths || [];\r\n\r\n if (staticPaths.fallback === false && paths.length === 0) {\r\n console.log(` ⊘ ${route.path} (no paths to generate)`);\r\n return;\r\n }\r\n }\r\n\r\n // Generate page for each path\r\n for (const pathConfig of paths) {\r\n const params = pathConfig.params || {};\r\n const actualPath = substituteParams(route.path, params);\r\n\r\n try {\r\n // Get static props\r\n let props = { params };\r\n \r\n if (module.getStaticProps) {\r\n const staticProps = await module.getStaticProps({ params });\r\n \r\n if (staticProps.notFound) {\r\n console.log(` ⊘ ${actualPath} (notFound)`);\r\n continue;\r\n }\r\n \r\n if (staticProps.redirect) {\r\n // Generate redirect HTML\r\n await generateRedirectPage(actualPath, staticProps.redirect, outDir, result);\r\n continue;\r\n }\r\n \r\n props = { ...props, ...staticProps.props };\r\n }\r\n\r\n // Render the page\r\n const html = await renderPage({\r\n Component,\r\n props,\r\n title: module.title || module.metadata?.title || 'FlexiReact App',\r\n meta: module.metadata || {},\r\n isSSG: true\r\n });\r\n\r\n // Write to file\r\n const filePath = getOutputPath(actualPath, outDir);\r\n ensureDir(path.dirname(filePath));\r\n fs.writeFileSync(filePath, html);\r\n\r\n const size = Buffer.byteLength(html, 'utf8');\r\n result.addPage(actualPath, filePath, size);\r\n \r\n console.log(` ✓ ${actualPath} (${formatSize(size)})`);\r\n\r\n } catch (error) {\r\n result.addError(actualPath, error);\r\n console.error(` ✗ ${actualPath}: ${error.message}`);\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Generates a redirect page\r\n */\r\nasync function generateRedirectPage(fromPath, redirect, outDir, result) {\r\n const { destination, permanent = false } = redirect;\r\n const statusCode = permanent ? 301 : 302;\r\n\r\n const html = `<!DOCTYPE html>\r\n<html>\r\n<head>\r\n <meta charset=\"utf-8\">\r\n <meta http-equiv=\"refresh\" content=\"0;url=${destination}\">\r\n <link rel=\"canonical\" href=\"${destination}\">\r\n <title>Redirecting...</title>\r\n</head>\r\n<body>\r\n <p>Redirecting to <a href=\"${destination}\">${destination}</a></p>\r\n <script>window.location.href = \"${destination}\";</script>\r\n</body>\r\n</html>`;\r\n\r\n const filePath = getOutputPath(fromPath, outDir);\r\n ensureDir(path.dirname(filePath));\r\n fs.writeFileSync(filePath, html);\r\n\r\n const size = Buffer.byteLength(html, 'utf8');\r\n result.addPage(fromPath, filePath, size);\r\n \r\n console.log(` ↪ ${fromPath} → ${destination}`);\r\n}\r\n\r\n/**\r\n * Substitutes route params into path\r\n */\r\nfunction substituteParams(routePath, params) {\r\n let result = routePath;\r\n \r\n for (const [key, value] of Object.entries(params)) {\r\n result = result.replace(`:${key}`, value);\r\n result = result.replace(`*${key}`, value);\r\n }\r\n \r\n return result;\r\n}\r\n\r\n/**\r\n * Gets the output file path for a route\r\n */\r\nfunction getOutputPath(routePath, outDir) {\r\n if (routePath === '/') {\r\n return path.join(outDir, 'index.html');\r\n }\r\n \r\n // Remove leading slash and add index.html\r\n const cleanPath = routePath.replace(/^\\//, '');\r\n return path.join(outDir, cleanPath, 'index.html');\r\n}\r\n\r\n/**\r\n * Formats file size\r\n */\r\nfunction formatSize(bytes) {\r\n if (bytes < 1024) return `${bytes} B`;\r\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\r\n return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;\r\n}\r\n\r\n/**\r\n * Incremental Static Regeneration (ISR) support\r\n * Allows pages to be regenerated after a specified interval\r\n */\r\ninterface ISRCacheEntry {\r\n html: string;\r\n generatedAt: number;\r\n revalidateAfter: number | null;\r\n}\r\n\r\nexport class ISRManager {\r\n cache: Map<string, ISRCacheEntry>;\r\n revalidating: Set<string>;\r\n defaultRevalidate: number;\r\n\r\n constructor(options: { defaultRevalidate?: number } = {}) {\r\n this.cache = new Map();\r\n this.revalidating = new Set();\r\n this.defaultRevalidate = options.defaultRevalidate || 60; // seconds\r\n }\r\n\r\n /**\r\n * Gets a cached page or regenerates it\r\n */\r\n async getPage(routePath, generator) {\r\n const cached = this.cache.get(routePath);\r\n const now = Date.now();\r\n\r\n if (cached) {\r\n // Check if revalidation is needed\r\n if (cached.revalidateAfter && now > cached.revalidateAfter) {\r\n // Trigger background revalidation\r\n this.revalidateInBackground(routePath, generator);\r\n }\r\n return cached.html;\r\n }\r\n\r\n // Generate fresh page\r\n const result = await generator();\r\n this.cache.set(routePath, {\r\n html: result.html,\r\n generatedAt: now,\r\n revalidateAfter: result.revalidate \r\n ? now + (result.revalidate * 1000)\r\n : null\r\n });\r\n\r\n return result.html;\r\n }\r\n\r\n /**\r\n * Revalidates a page in the background\r\n */\r\n async revalidateInBackground(routePath, generator) {\r\n if (this.revalidating.has(routePath)) return;\r\n\r\n this.revalidating.add(routePath);\r\n\r\n try {\r\n const result = await generator();\r\n const now = Date.now();\r\n \r\n this.cache.set(routePath, {\r\n html: result.html,\r\n generatedAt: now,\r\n revalidateAfter: result.revalidate \r\n ? now + (result.revalidate * 1000)\r\n : null\r\n });\r\n } catch (error) {\r\n console.error(`ISR revalidation failed for ${routePath}:`, error);\r\n } finally {\r\n this.revalidating.delete(routePath);\r\n }\r\n }\r\n\r\n /**\r\n * Invalidates a cached page\r\n */\r\n invalidate(routePath) {\r\n this.cache.delete(routePath);\r\n }\r\n\r\n /**\r\n * Clears all cached pages\r\n */\r\n clear() {\r\n this.cache.clear();\r\n }\r\n}\r\n\r\nexport default {\r\n generateStaticSite,\r\n SSGResult,\r\n ISRManager\r\n};\r\n","/**\r\n * FlexiReact React Server Components (RSC) System\r\n * \r\n * RSC allows components to run exclusively on the server, reducing client bundle size\r\n * and enabling direct database/filesystem access in components.\r\n * \r\n * Usage:\r\n * - Add 'use server' at the top of a component file to make it a Server Component\r\n * - Add 'use client' at the top to make it a Client Component (hydrated on client)\r\n * - Server Components can import Client Components, but not vice versa\r\n */\r\n\r\nimport React from 'react';\r\nimport { renderToString } from 'react-dom/server';\r\nimport { isServerComponent, isClientComponent } from '../utils.js';\r\n\r\n/**\r\n * RSC Payload format for streaming\r\n */\r\nexport const RSC_CONTENT_TYPE = 'text/x-component';\r\n\r\n/**\r\n * Processes a component tree for RSC\r\n * Server components are rendered to HTML, client components are serialized\r\n */\r\nexport async function processServerComponent(Component, props, context) {\r\n const componentInfo = {\r\n isServer: true,\r\n rendered: null,\r\n clientComponents: [],\r\n serverData: {}\r\n };\r\n\r\n try {\r\n // If component has async data fetching\r\n if (Component.getServerData) {\r\n componentInfo.serverData = await Component.getServerData(context);\r\n props = { ...props, ...componentInfo.serverData };\r\n }\r\n\r\n // Render the server component\r\n const element = React.createElement(Component, props);\r\n componentInfo.rendered = renderToString(element);\r\n\r\n } catch (error) {\r\n console.error('RSC Error:', error);\r\n throw error;\r\n }\r\n\r\n return componentInfo;\r\n}\r\n\r\n/**\r\n * Creates a client component reference for RSC payload\r\n */\r\nexport function createClientReference(componentPath, props) {\r\n return {\r\n $$typeof: Symbol.for('react.client.reference'),\r\n $$id: componentPath,\r\n $$props: props\r\n };\r\n}\r\n\r\n/**\r\n * Serializes RSC payload for streaming\r\n */\r\nexport function serializeRSCPayload(componentTree) {\r\n const payload = {\r\n type: 'rsc',\r\n tree: serializeNode(componentTree),\r\n timestamp: Date.now()\r\n };\r\n\r\n return JSON.stringify(payload);\r\n}\r\n\r\n/**\r\n * Serializes a React node for RSC\r\n */\r\nfunction serializeNode(node) {\r\n if (node === null || node === undefined) {\r\n return null;\r\n }\r\n\r\n if (typeof node === 'string' || typeof node === 'number' || typeof node === 'boolean') {\r\n return node;\r\n }\r\n\r\n if (Array.isArray(node)) {\r\n return node.map(serializeNode);\r\n }\r\n\r\n if (React.isValidElement(node)) {\r\n const { type, props } = node;\r\n\r\n // Handle client component references\r\n const typeAny = type as any;\r\n if (typeAny.$$typeof === Symbol.for('react.client.reference')) {\r\n return {\r\n $$type: 'client',\r\n $$id: typeAny.$$id,\r\n props: serializeProps(props)\r\n };\r\n }\r\n\r\n // Handle regular elements\r\n const typeName = typeof type === 'string' ? type : (typeAny.displayName || typeAny.name || 'Unknown');\r\n\r\n return {\r\n $$type: 'element',\r\n type: typeName,\r\n props: serializeProps(props)\r\n };\r\n }\r\n\r\n return String(node);\r\n}\r\n\r\n/**\r\n * Serializes props, handling special cases\r\n */\r\nfunction serializeProps(props: Record<string, any>) {\r\n const serialized: Record<string, any> = {};\r\n\r\n for (const [key, value] of Object.entries(props)) {\r\n if (key === 'children') {\r\n serialized.children = serializeNode(value);\r\n } else if (typeof value === 'function') {\r\n // Functions can't be serialized - mark as client action\r\n serialized[key] = { $$type: 'action', name: value.name };\r\n } else if (value instanceof Date) {\r\n serialized[key] = { $$type: 'date', value: value.toISOString() };\r\n } else if (typeof value === 'object' && value !== null) {\r\n serialized[key] = JSON.parse(JSON.stringify(value));\r\n } else {\r\n serialized[key] = value;\r\n }\r\n }\r\n\r\n return serialized;\r\n}\r\n\r\n/**\r\n * Server Actions support\r\n * Allows calling server functions from client components\r\n */\r\nexport function createServerAction(fn, actionId) {\r\n // Mark function as server action\r\n fn.$$typeof = Symbol.for('react.server.action');\r\n fn.$$id = actionId;\r\n \r\n return fn;\r\n}\r\n\r\n/**\r\n * Handles server action invocation\r\n */\r\nexport async function handleServerAction(actionId, args, context) {\r\n // Actions are registered during build\r\n const action = globalThis.__FLEXI_ACTIONS__?.[actionId];\r\n \r\n if (!action) {\r\n throw new Error(`Server action not found: ${actionId}`);\r\n }\r\n\r\n return await action(...args, context);\r\n}\r\n\r\n/**\r\n * RSC Boundary component\r\n * Marks the boundary between server and client rendering\r\n */\r\nexport function ServerBoundary({ children, fallback }) {\r\n return children;\r\n}\r\n\r\n/**\r\n * Client Boundary component\r\n * Marks components that should be hydrated on the client\r\n */\r\nexport function ClientBoundary({ children, fallback }) {\r\n // On server, render children normally\r\n // On client, this will be hydrated\r\n return React.createElement('div', {\r\n 'data-flexi-client': 'true',\r\n children\r\n });\r\n}\r\n\r\nexport default {\r\n processServerComponent,\r\n createClientReference,\r\n serializeRSCPayload,\r\n createServerAction,\r\n handleServerAction,\r\n ServerBoundary,\r\n ClientBoundary,\r\n RSC_CONTENT_TYPE\r\n};\r\n","/**\r\n * FlexiReact Universal Edge Runtime\r\n * \r\n * Works on:\r\n * - Node.js\r\n * - Bun\r\n * - Deno\r\n * - Cloudflare Workers\r\n * - Vercel Edge\r\n * - Any Web-standard runtime\r\n */\r\n\r\n// Detect runtime environment\r\nexport type RuntimeEnvironment = \r\n | 'node'\r\n | 'bun'\r\n | 'deno'\r\n | 'cloudflare'\r\n | 'vercel-edge'\r\n | 'netlify-edge'\r\n | 'fastly'\r\n | 'unknown';\r\n\r\nexport function detectRuntime(): RuntimeEnvironment {\r\n // Bun\r\n if (typeof globalThis.Bun !== 'undefined') {\r\n return 'bun';\r\n }\r\n \r\n // Deno\r\n if (typeof globalThis.Deno !== 'undefined') {\r\n return 'deno';\r\n }\r\n \r\n // Cloudflare Workers\r\n if (typeof globalThis.caches !== 'undefined' && typeof (globalThis as any).WebSocketPair !== 'undefined') {\r\n return 'cloudflare';\r\n }\r\n \r\n // Vercel Edge\r\n if (typeof process !== 'undefined' && process.env?.VERCEL_EDGE === '1') {\r\n return 'vercel-edge';\r\n }\r\n \r\n // Netlify Edge\r\n if (typeof globalThis.Netlify !== 'undefined') {\r\n return 'netlify-edge';\r\n }\r\n \r\n // Node.js\r\n if (typeof process !== 'undefined' && process.versions?.node) {\r\n return 'node';\r\n }\r\n \r\n return 'unknown';\r\n}\r\n\r\n// Runtime capabilities\r\nexport interface RuntimeCapabilities {\r\n hasFileSystem: boolean;\r\n hasWebCrypto: boolean;\r\n hasWebStreams: boolean;\r\n hasFetch: boolean;\r\n hasWebSocket: boolean;\r\n hasKV: boolean;\r\n hasCache: boolean;\r\n maxExecutionTime: number; // ms, 0 = unlimited\r\n maxMemory: number; // bytes, 0 = unlimited\r\n}\r\n\r\nexport function getRuntimeCapabilities(): RuntimeCapabilities {\r\n const runtime = detectRuntime();\r\n \r\n switch (runtime) {\r\n case 'cloudflare':\r\n return {\r\n hasFileSystem: false,\r\n hasWebCrypto: true,\r\n hasWebStreams: true,\r\n hasFetch: true,\r\n hasWebSocket: true,\r\n hasKV: true,\r\n hasCache: true,\r\n maxExecutionTime: 30000, // 30s for paid, 10ms for free\r\n maxMemory: 128 * 1024 * 1024 // 128MB\r\n };\r\n \r\n case 'vercel-edge':\r\n return {\r\n hasFileSystem: false,\r\n hasWebCrypto: true,\r\n hasWebStreams: true,\r\n hasFetch: true,\r\n hasWebSocket: false,\r\n hasKV: true, // Vercel KV\r\n hasCache: true,\r\n maxExecutionTime: 30000,\r\n maxMemory: 128 * 1024 * 1024\r\n };\r\n \r\n case 'deno':\r\n return {\r\n hasFileSystem: true,\r\n hasWebCrypto: true,\r\n hasWebStreams: true,\r\n hasFetch: true,\r\n hasWebSocket: true,\r\n hasKV: true, // Deno KV\r\n hasCache: true,\r\n maxExecutionTime: 0,\r\n maxMemory: 0\r\n };\r\n \r\n case 'bun':\r\n return {\r\n hasFileSystem: true,\r\n hasWebCrypto: true,\r\n hasWebStreams: true,\r\n hasFetch: true,\r\n hasWebSocket: true,\r\n hasKV: false,\r\n hasCache: false,\r\n maxExecutionTime: 0,\r\n maxMemory: 0\r\n };\r\n \r\n case 'node':\r\n default:\r\n return {\r\n hasFileSystem: true,\r\n hasWebCrypto: true,\r\n hasWebStreams: true,\r\n hasFetch: true,\r\n hasWebSocket: true,\r\n hasKV: false,\r\n hasCache: false,\r\n maxExecutionTime: 0,\r\n maxMemory: 0\r\n };\r\n }\r\n}\r\n\r\n// Runtime info\r\nexport const runtime = {\r\n name: detectRuntime(),\r\n capabilities: getRuntimeCapabilities(),\r\n \r\n get isEdge(): boolean {\r\n return ['cloudflare', 'vercel-edge', 'netlify-edge', 'fastly'].includes(this.name);\r\n },\r\n \r\n get isServer(): boolean {\r\n return ['node', 'bun', 'deno'].includes(this.name);\r\n },\r\n \r\n get supportsStreaming(): boolean {\r\n return this.capabilities.hasWebStreams;\r\n }\r\n};\r\n\r\nexport default runtime;\r\n","/**\r\n * Fetch API Polyfill for Universal Compatibility\r\n * \r\n * Ensures Request, Response, Headers work everywhere\r\n */\r\n\r\n// Use native Web APIs if available, otherwise polyfill\r\nconst globalFetch = globalThis.fetch;\r\nconst GlobalRequest = globalThis.Request;\r\nconst GlobalResponse = globalThis.Response;\r\nconst GlobalHeaders = globalThis.Headers;\r\n\r\n// Extended Request with FlexiReact helpers\r\nexport class FlexiRequest extends GlobalRequest {\r\n private _parsedUrl?: URL;\r\n private _cookies?: Map<string, string>;\r\n \r\n constructor(input: RequestInfo | URL, init?: RequestInit) {\r\n super(input, init);\r\n }\r\n \r\n get pathname(): string {\r\n if (!this._parsedUrl) {\r\n this._parsedUrl = new URL(this.url);\r\n }\r\n return this._parsedUrl.pathname;\r\n }\r\n \r\n get searchParams(): URLSearchParams {\r\n if (!this._parsedUrl) {\r\n this._parsedUrl = new URL(this.url);\r\n }\r\n return this._parsedUrl.searchParams;\r\n }\r\n \r\n get cookies(): Map<string, string> {\r\n if (!this._cookies) {\r\n this._cookies = new Map();\r\n const cookieHeader = this.headers.get('cookie');\r\n if (cookieHeader) {\r\n cookieHeader.split(';').forEach(cookie => {\r\n const [name, ...rest] = cookie.trim().split('=');\r\n if (name) {\r\n this._cookies!.set(name, rest.join('='));\r\n }\r\n });\r\n }\r\n }\r\n return this._cookies;\r\n }\r\n \r\n cookie(name: string): string | undefined {\r\n return this.cookies.get(name);\r\n }\r\n \r\n // Parse JSON body\r\n async jsonBody<T = any>(): Promise<T> {\r\n return this.json();\r\n }\r\n \r\n // Parse form data\r\n async formBody(): Promise<FormData> {\r\n return this.formData();\r\n }\r\n \r\n // Get query param\r\n query(name: string): string | null {\r\n return this.searchParams.get(name);\r\n }\r\n \r\n // Get all query params\r\n queryAll(name: string): string[] {\r\n return this.searchParams.getAll(name);\r\n }\r\n}\r\n\r\n// Extended Response with FlexiReact helpers\r\nexport class FlexiResponse extends GlobalResponse {\r\n // Static helpers for common responses\r\n \r\n static json(data: any, init?: ResponseInit): FlexiResponse {\r\n const headers = new Headers(init?.headers);\r\n headers.set('Content-Type', 'application/json');\r\n \r\n return new FlexiResponse(JSON.stringify(data), {\r\n ...init,\r\n headers\r\n });\r\n }\r\n \r\n static html(html: string, init?: ResponseInit): FlexiResponse {\r\n const headers = new Headers(init?.headers);\r\n headers.set('Content-Type', 'text/html; charset=utf-8');\r\n \r\n return new FlexiResponse(html, {\r\n ...init,\r\n headers\r\n });\r\n }\r\n \r\n static text(text: string, init?: ResponseInit): FlexiResponse {\r\n const headers = new Headers(init?.headers);\r\n headers.set('Content-Type', 'text/plain; charset=utf-8');\r\n \r\n return new FlexiResponse(text, {\r\n ...init,\r\n headers\r\n });\r\n }\r\n \r\n static redirect(url: string, status: 301 | 302 | 303 | 307 | 308 = 307): FlexiResponse {\r\n return new FlexiResponse(null, {\r\n status,\r\n headers: { Location: url }\r\n });\r\n }\r\n \r\n static notFound(message: string = 'Not Found'): FlexiResponse {\r\n return new FlexiResponse(message, {\r\n status: 404,\r\n headers: { 'Content-Type': 'text/plain' }\r\n });\r\n }\r\n \r\n static error(message: string = 'Internal Server Error', status: number = 500): FlexiResponse {\r\n return new FlexiResponse(message, {\r\n status,\r\n headers: { 'Content-Type': 'text/plain' }\r\n });\r\n }\r\n \r\n // Stream response\r\n static stream(\r\n stream: ReadableStream,\r\n init?: ResponseInit\r\n ): FlexiResponse {\r\n return new FlexiResponse(stream, init);\r\n }\r\n \r\n // Set cookie helper\r\n withCookie(\r\n name: string,\r\n value: string,\r\n options: {\r\n maxAge?: number;\r\n expires?: Date;\r\n path?: string;\r\n domain?: string;\r\n secure?: boolean;\r\n httpOnly?: boolean;\r\n sameSite?: 'Strict' | 'Lax' | 'None';\r\n } = {}\r\n ): FlexiResponse {\r\n const parts = [`${name}=${encodeURIComponent(value)}`];\r\n \r\n if (options.maxAge !== undefined) parts.push(`Max-Age=${options.maxAge}`);\r\n if (options.expires) parts.push(`Expires=${options.expires.toUTCString()}`);\r\n if (options.path) parts.push(`Path=${options.path}`);\r\n if (options.domain) parts.push(`Domain=${options.domain}`);\r\n if (options.secure) parts.push('Secure');\r\n if (options.httpOnly) parts.push('HttpOnly');\r\n if (options.sameSite) parts.push(`SameSite=${options.sameSite}`);\r\n \r\n const headers = new Headers(this.headers);\r\n headers.append('Set-Cookie', parts.join('; '));\r\n \r\n return new FlexiResponse(this.body, {\r\n status: this.status,\r\n statusText: this.statusText,\r\n headers\r\n });\r\n }\r\n \r\n // Add headers helper\r\n withHeaders(newHeaders: Record<string, string>): FlexiResponse {\r\n const headers = new Headers(this.headers);\r\n Object.entries(newHeaders).forEach(([key, value]) => {\r\n headers.set(key, value);\r\n });\r\n \r\n return new FlexiResponse(this.body, {\r\n status: this.status,\r\n statusText: this.statusText,\r\n headers\r\n });\r\n }\r\n}\r\n\r\n// Extended Headers\r\nexport class FlexiHeaders extends GlobalHeaders {\r\n // Get bearer token\r\n getBearerToken(): string | null {\r\n const auth = this.get('Authorization');\r\n if (auth?.startsWith('Bearer ')) {\r\n return auth.slice(7);\r\n }\r\n return null;\r\n }\r\n \r\n // Get basic auth credentials\r\n getBasicAuth(): { username: string; password: string } | null {\r\n const auth = this.get('Authorization');\r\n if (auth?.startsWith('Basic ')) {\r\n try {\r\n const decoded = atob(auth.slice(6));\r\n const [username, password] = decoded.split(':');\r\n return { username, password };\r\n } catch {\r\n return null;\r\n }\r\n }\r\n return null;\r\n }\r\n \r\n // Check content type\r\n isJson(): boolean {\r\n return this.get('Content-Type')?.includes('application/json') ?? false;\r\n }\r\n \r\n isFormData(): boolean {\r\n const ct = this.get('Content-Type') ?? '';\r\n return ct.includes('multipart/form-data') || ct.includes('application/x-www-form-urlencoded');\r\n }\r\n \r\n isHtml(): boolean {\r\n return this.get('Accept')?.includes('text/html') ?? false;\r\n }\r\n}\r\n\r\n// Export both native and extended versions\r\nexport { \r\n FlexiRequest as Request,\r\n FlexiResponse as Response,\r\n FlexiHeaders as Headers\r\n};\r\n\r\n// Also export native versions for compatibility\r\nexport const NativeRequest = GlobalRequest;\r\nexport const NativeResponse = GlobalResponse;\r\nexport const NativeHeaders = GlobalHeaders;\r\n\r\nexport default {\r\n Request: FlexiRequest,\r\n Response: FlexiResponse,\r\n Headers: FlexiHeaders,\r\n fetch: globalFetch\r\n};\r\n","/**\r\n * FlexiReact Universal Cache System\r\n * \r\n * Smart caching that works on:\r\n * - Cloudflare Workers (Cache API + KV)\r\n * - Vercel Edge (Edge Config + KV)\r\n * - Deno (Deno KV)\r\n * - Node.js/Bun (In-memory + File cache)\r\n */\r\n\r\nimport { detectRuntime } from './runtime.js';\r\n\r\n// Cache entry\r\nexport interface CacheEntry<T = any> {\r\n value: T;\r\n expires: number; // timestamp\r\n stale?: number; // stale-while-revalidate timestamp\r\n tags?: string[];\r\n etag?: string;\r\n}\r\n\r\n// Cache options\r\nexport interface CacheOptions {\r\n ttl?: number; // seconds\r\n staleWhileRevalidate?: number; // seconds\r\n tags?: string[];\r\n key?: string;\r\n revalidate?: number | false; // ISR-style revalidation\r\n}\r\n\r\n// Cache storage interface\r\nexport interface CacheStorage {\r\n get<T>(key: string): Promise<CacheEntry<T> | null>;\r\n set<T>(key: string, entry: CacheEntry<T>): Promise<void>;\r\n delete(key: string): Promise<void>;\r\n deleteByTag(tag: string): Promise<void>;\r\n clear(): Promise<void>;\r\n}\r\n\r\n// In-memory cache (fallback)\r\nclass MemoryCache implements CacheStorage {\r\n private store = new Map<string, CacheEntry>();\r\n private tagIndex = new Map<string, Set<string>>();\r\n \r\n async get<T>(key: string): Promise<CacheEntry<T> | null> {\r\n const entry = this.store.get(key);\r\n if (!entry) return null;\r\n \r\n // Check expiration\r\n if (entry.expires && entry.expires < Date.now()) {\r\n // Check stale-while-revalidate\r\n if (entry.stale && entry.stale > Date.now()) {\r\n return { ...entry, value: entry.value as T };\r\n }\r\n this.store.delete(key);\r\n return null;\r\n }\r\n \r\n return { ...entry, value: entry.value as T };\r\n }\r\n \r\n async set<T>(key: string, entry: CacheEntry<T>): Promise<void> {\r\n this.store.set(key, entry);\r\n \r\n // Index by tags\r\n if (entry.tags) {\r\n entry.tags.forEach(tag => {\r\n if (!this.tagIndex.has(tag)) {\r\n this.tagIndex.set(tag, new Set());\r\n }\r\n this.tagIndex.get(tag)!.add(key);\r\n });\r\n }\r\n }\r\n \r\n async delete(key: string): Promise<void> {\r\n this.store.delete(key);\r\n }\r\n \r\n async deleteByTag(tag: string): Promise<void> {\r\n const keys = this.tagIndex.get(tag);\r\n if (keys) {\r\n keys.forEach(key => this.store.delete(key));\r\n this.tagIndex.delete(tag);\r\n }\r\n }\r\n \r\n async clear(): Promise<void> {\r\n this.store.clear();\r\n this.tagIndex.clear();\r\n }\r\n}\r\n\r\n// Cloudflare KV cache\r\nclass CloudflareCache implements CacheStorage {\r\n private kv: any;\r\n \r\n constructor(kv: any) {\r\n this.kv = kv;\r\n }\r\n \r\n async get<T>(key: string): Promise<CacheEntry<T> | null> {\r\n try {\r\n const data = await this.kv.get(key, 'json');\r\n if (!data) return null;\r\n \r\n const entry = data as CacheEntry<T>;\r\n if (entry.expires && entry.expires < Date.now()) {\r\n if (entry.stale && entry.stale > Date.now()) {\r\n return entry;\r\n }\r\n await this.kv.delete(key);\r\n return null;\r\n }\r\n \r\n return entry;\r\n } catch {\r\n return null;\r\n }\r\n }\r\n \r\n async set<T>(key: string, entry: CacheEntry<T>): Promise<void> {\r\n const ttl = entry.expires ? Math.ceil((entry.expires - Date.now()) / 1000) : undefined;\r\n await this.kv.put(key, JSON.stringify(entry), { expirationTtl: ttl });\r\n }\r\n \r\n async delete(key: string): Promise<void> {\r\n await this.kv.delete(key);\r\n }\r\n \r\n async deleteByTag(tag: string): Promise<void> {\r\n // KV doesn't support tag-based deletion natively\r\n // Would need to maintain a tag index\r\n console.warn('Tag-based deletion not fully supported in Cloudflare KV');\r\n }\r\n \r\n async clear(): Promise<void> {\r\n // KV doesn't support clear\r\n console.warn('Clear not supported in Cloudflare KV');\r\n }\r\n}\r\n\r\n// Deno KV cache\r\nclass DenoKVCache implements CacheStorage {\r\n private kv: any;\r\n \r\n constructor() {\r\n // @ts-ignore - Deno global\r\n this.kv = Deno.openKv();\r\n }\r\n \r\n async get<T>(key: string): Promise<CacheEntry<T> | null> {\r\n try {\r\n const kv = await this.kv;\r\n const result = await kv.get(['cache', key]);\r\n if (!result.value) return null;\r\n \r\n const entry = result.value as CacheEntry<T>;\r\n if (entry.expires && entry.expires < Date.now()) {\r\n if (entry.stale && entry.stale > Date.now()) {\r\n return entry;\r\n }\r\n await kv.delete(['cache', key]);\r\n return null;\r\n }\r\n \r\n return entry;\r\n } catch {\r\n return null;\r\n }\r\n }\r\n \r\n async set<T>(key: string, entry: CacheEntry<T>): Promise<void> {\r\n const kv = await this.kv;\r\n await kv.set(['cache', key], entry);\r\n }\r\n \r\n async delete(key: string): Promise<void> {\r\n const kv = await this.kv;\r\n await kv.delete(['cache', key]);\r\n }\r\n \r\n async deleteByTag(tag: string): Promise<void> {\r\n // Would need tag index\r\n console.warn('Tag-based deletion requires tag index in Deno KV');\r\n }\r\n \r\n async clear(): Promise<void> {\r\n // Would need to iterate all keys\r\n console.warn('Clear requires iteration in Deno KV');\r\n }\r\n}\r\n\r\n// Create cache based on runtime\r\nfunction createCacheStorage(options?: { kv?: any }): CacheStorage {\r\n const runtime = detectRuntime();\r\n \r\n switch (runtime) {\r\n case 'cloudflare':\r\n if (options?.kv) {\r\n return new CloudflareCache(options.kv);\r\n }\r\n return new MemoryCache();\r\n \r\n case 'deno':\r\n return new DenoKVCache();\r\n \r\n case 'node':\r\n case 'bun':\r\n default:\r\n return new MemoryCache();\r\n }\r\n}\r\n\r\n// Main cache instance\r\nlet cacheStorage: CacheStorage = new MemoryCache();\r\n\r\n// Initialize cache with platform-specific storage\r\nexport function initCache(options?: { kv?: any }): void {\r\n cacheStorage = createCacheStorage(options);\r\n}\r\n\r\n// Cache function wrapper (like React cache)\r\nexport function cacheFunction<T extends (...args: any[]) => Promise<any>>(\r\n fn: T,\r\n options: CacheOptions = {}\r\n): T {\r\n const { ttl = 60, staleWhileRevalidate = 0, tags = [] } = options;\r\n \r\n return (async (...args: any[]) => {\r\n const key = options.key || `fn:${fn.name}:${JSON.stringify(args)}`;\r\n \r\n // Try cache first\r\n const cached = await cacheStorage.get(key);\r\n if (cached) {\r\n // Check if stale and needs revalidation\r\n if (cached.expires < Date.now() && cached.stale && cached.stale > Date.now()) {\r\n // Return stale data, revalidate in background\r\n queueMicrotask(async () => {\r\n try {\r\n const fresh = await fn(...args);\r\n await cacheStorage.set(key, {\r\n value: fresh,\r\n expires: Date.now() + ttl * 1000,\r\n stale: Date.now() + (ttl + staleWhileRevalidate) * 1000,\r\n tags\r\n });\r\n } catch (e) {\r\n console.error('Background revalidation failed:', e);\r\n }\r\n });\r\n }\r\n return cached.value;\r\n }\r\n \r\n // Execute function\r\n const result = await fn(...args);\r\n \r\n // Cache result\r\n await cacheStorage.set(key, {\r\n value: result,\r\n expires: Date.now() + ttl * 1000,\r\n stale: staleWhileRevalidate ? Date.now() + (ttl + staleWhileRevalidate) * 1000 : undefined,\r\n tags\r\n });\r\n \r\n return result;\r\n }) as T;\r\n}\r\n\r\n// Unstable cache (Next.js compatible API)\r\nexport function unstable_cache<T extends (...args: any[]) => Promise<any>>(\r\n fn: T,\r\n keyParts?: string[],\r\n options?: { revalidate?: number | false; tags?: string[] }\r\n): T {\r\n return cacheFunction(fn, {\r\n key: keyParts?.join(':'),\r\n ttl: typeof options?.revalidate === 'number' ? options.revalidate : 3600,\r\n tags: options?.tags\r\n });\r\n}\r\n\r\n// Revalidate by tag\r\nexport async function revalidateTag(tag: string): Promise<void> {\r\n await cacheStorage.deleteByTag(tag);\r\n}\r\n\r\n// Revalidate by path\r\nexport async function revalidatePath(path: string): Promise<void> {\r\n await cacheStorage.delete(`page:${path}`);\r\n}\r\n\r\n// Cache object for direct access\r\nexport const cache = {\r\n get: <T>(key: string) => cacheStorage.get<T>(key),\r\n set: <T>(key: string, value: T, options: CacheOptions = {}) => {\r\n const { ttl = 60, staleWhileRevalidate = 0, tags = [] } = options;\r\n return cacheStorage.set(key, {\r\n value,\r\n expires: Date.now() + ttl * 1000,\r\n stale: staleWhileRevalidate ? Date.now() + (ttl + staleWhileRevalidate) * 1000 : undefined,\r\n tags\r\n });\r\n },\r\n delete: (key: string) => cacheStorage.delete(key),\r\n deleteByTag: (tag: string) => cacheStorage.deleteByTag(tag),\r\n clear: () => cacheStorage.clear(),\r\n \r\n // Wrap function with caching\r\n wrap: cacheFunction,\r\n \r\n // Next.js compatible\r\n unstable_cache,\r\n revalidateTag,\r\n revalidatePath\r\n};\r\n\r\n// Request-level cache (per-request deduplication)\r\nconst requestCache = new WeakMap<Request, Map<string, any>>();\r\n\r\nexport function getRequestCache(request: Request): Map<string, any> {\r\n if (!requestCache.has(request)) {\r\n requestCache.set(request, new Map());\r\n }\r\n return requestCache.get(request)!;\r\n}\r\n\r\n// React-style cache for request deduplication\r\nexport function reactCache<T extends (...args: any[]) => any>(fn: T): T {\r\n const cache = new Map<string, any>();\r\n \r\n return ((...args: any[]) => {\r\n const key = JSON.stringify(args);\r\n if (cache.has(key)) {\r\n return cache.get(key);\r\n }\r\n const result = fn(...args);\r\n cache.set(key, result);\r\n return result;\r\n }) as T;\r\n}\r\n\r\nexport default cache;\r\n","/**\r\n * FlexiReact Universal Edge Handler\r\n * \r\n * Single handler that works on all platforms:\r\n * - Node.js (http.createServer)\r\n * - Bun (Bun.serve)\r\n * - Deno (Deno.serve)\r\n * - Cloudflare Workers (fetch handler)\r\n * - Vercel Edge (edge function)\r\n */\r\n\r\nimport { FlexiRequest, FlexiResponse } from './fetch-polyfill.js';\r\nimport runtime, { detectRuntime } from './runtime.js';\r\nimport { cache, CacheOptions } from './cache.js';\r\n\r\n// Handler context\r\nexport interface EdgeContext {\r\n runtime: typeof runtime;\r\n cache: typeof cache;\r\n env: Record<string, string | undefined>;\r\n waitUntil: (promise: Promise<any>) => void;\r\n passThroughOnException?: () => void;\r\n}\r\n\r\n// Route handler type\r\nexport type EdgeHandler = (\r\n request: FlexiRequest,\r\n context: EdgeContext\r\n) => Promise<FlexiResponse> | FlexiResponse;\r\n\r\n// Middleware type\r\nexport type EdgeMiddleware = (\r\n request: FlexiRequest,\r\n context: EdgeContext,\r\n next: () => Promise<FlexiResponse>\r\n) => Promise<FlexiResponse> | FlexiResponse;\r\n\r\n// App configuration\r\nexport interface EdgeAppConfig {\r\n routes?: Map<string, EdgeHandler>;\r\n middleware?: EdgeMiddleware[];\r\n notFound?: EdgeHandler;\r\n onError?: (error: Error, request: FlexiRequest) => FlexiResponse;\r\n basePath?: string;\r\n}\r\n\r\n// Create universal edge app\r\nexport function createEdgeApp(config: EdgeAppConfig = {}) {\r\n const {\r\n routes = new Map(),\r\n middleware = [],\r\n notFound = () => FlexiResponse.notFound(),\r\n onError = (error) => FlexiResponse.error(error.message),\r\n basePath = ''\r\n } = config;\r\n\r\n // Main fetch handler (Web Standard)\r\n async function handleRequest(\r\n request: Request,\r\n env: Record<string, any> = {},\r\n executionContext?: { waitUntil: (p: Promise<any>) => void; passThroughOnException?: () => void }\r\n ): Promise<Response> {\r\n const flexiRequest = new FlexiRequest(request.url, {\r\n method: request.method,\r\n headers: request.headers,\r\n body: request.body,\r\n // @ts-ignore - duplex is needed for streaming\r\n duplex: 'half'\r\n });\r\n\r\n const context: EdgeContext = {\r\n runtime,\r\n cache,\r\n env: env as Record<string, string | undefined>,\r\n waitUntil: executionContext?.waitUntil || (() => {}),\r\n passThroughOnException: executionContext?.passThroughOnException\r\n };\r\n\r\n try {\r\n // Run middleware chain\r\n const response = await runMiddleware(flexiRequest, context, middleware, async () => {\r\n // Match route\r\n const pathname = flexiRequest.pathname.replace(basePath, '') || '/';\r\n \r\n // Try exact match first\r\n let handler = routes.get(pathname);\r\n \r\n // Try pattern matching\r\n if (!handler) {\r\n for (const [pattern, h] of routes) {\r\n if (matchRoute(pathname, pattern)) {\r\n handler = h;\r\n break;\r\n }\r\n }\r\n }\r\n \r\n if (handler) {\r\n return await handler(flexiRequest, context);\r\n }\r\n \r\n return await notFound(flexiRequest, context);\r\n });\r\n\r\n return response;\r\n } catch (error: any) {\r\n console.error('Edge handler error:', error);\r\n return onError(error, flexiRequest);\r\n }\r\n }\r\n\r\n // Run middleware chain\r\n async function runMiddleware(\r\n request: FlexiRequest,\r\n context: EdgeContext,\r\n middlewares: EdgeMiddleware[],\r\n finalHandler: () => Promise<FlexiResponse>\r\n ): Promise<FlexiResponse> {\r\n let index = 0;\r\n\r\n async function next(): Promise<FlexiResponse> {\r\n if (index >= middlewares.length) {\r\n return finalHandler();\r\n }\r\n const mw = middlewares[index++];\r\n return mw(request, context, next);\r\n }\r\n\r\n return next();\r\n }\r\n\r\n // Simple route matching\r\n function matchRoute(pathname: string, pattern: string): boolean {\r\n // Exact match\r\n if (pathname === pattern) return true;\r\n \r\n // Convert pattern to regex\r\n const regexPattern = pattern\r\n .replace(/\\[\\.\\.\\.(\\w+)\\]/g, '(?<$1>.+)') // [...slug] -> catch-all\r\n .replace(/\\[(\\w+)\\]/g, '(?<$1>[^/]+)'); // [id] -> dynamic segment\r\n \r\n const regex = new RegExp(`^${regexPattern}$`);\r\n return regex.test(pathname);\r\n }\r\n\r\n // Return platform-specific exports\r\n return {\r\n // Web Standard fetch handler (Cloudflare, Vercel Edge, Deno)\r\n fetch: handleRequest,\r\n \r\n // Cloudflare Workers\r\n async scheduled(event: any, env: any, ctx: any) {\r\n // Handle scheduled events\r\n },\r\n \r\n // Add route\r\n route(path: string, handler: EdgeHandler) {\r\n routes.set(path, handler);\r\n return this;\r\n },\r\n \r\n // Add middleware\r\n use(mw: EdgeMiddleware) {\r\n middleware.push(mw);\r\n return this;\r\n },\r\n \r\n // Node.js adapter\r\n toNodeHandler() {\r\n return async (req: any, res: any) => {\r\n const url = `http://${req.headers.host}${req.url}`;\r\n const headers = new Headers();\r\n Object.entries(req.headers).forEach(([key, value]) => {\r\n if (typeof value === 'string') headers.set(key, value);\r\n });\r\n\r\n const body = ['GET', 'HEAD'].includes(req.method) ? undefined : req;\r\n \r\n const request = new Request(url, {\r\n method: req.method,\r\n headers,\r\n body,\r\n // @ts-ignore\r\n duplex: 'half'\r\n });\r\n\r\n const response = await handleRequest(request, process.env);\r\n \r\n res.writeHead(response.status, Object.fromEntries(response.headers));\r\n \r\n if (response.body) {\r\n const reader = response.body.getReader();\r\n while (true) {\r\n const { done, value } = await reader.read();\r\n if (done) break;\r\n res.write(value);\r\n }\r\n }\r\n res.end();\r\n };\r\n },\r\n \r\n // Bun adapter\r\n toBunHandler() {\r\n return {\r\n fetch: handleRequest,\r\n port: parseInt(process.env.PORT || '3000', 10)\r\n };\r\n },\r\n \r\n // Deno adapter\r\n toDenoHandler() {\r\n return handleRequest;\r\n },\r\n \r\n // Start server based on runtime\r\n async listen(port: number = 3000) {\r\n const rt = detectRuntime();\r\n \r\n switch (rt) {\r\n case 'bun':\r\n console.log(`🚀 FlexiReact Edge running on Bun at http://localhost:${port}`);\r\n // @ts-ignore - Bun global\r\n return Bun.serve({\r\n port,\r\n fetch: handleRequest\r\n });\r\n \r\n case 'deno':\r\n console.log(`🚀 FlexiReact Edge running on Deno at http://localhost:${port}`);\r\n // @ts-ignore - Deno global\r\n return Deno.serve({ port }, handleRequest);\r\n \r\n case 'node':\r\n default:\r\n const http = await import('http');\r\n const server = http.createServer(this.toNodeHandler());\r\n server.listen(port, () => {\r\n console.log(`🚀 FlexiReact Edge running on Node.js at http://localhost:${port}`);\r\n });\r\n return server;\r\n }\r\n }\r\n };\r\n}\r\n\r\n// Export default app creator\r\nexport default createEdgeApp;\r\n","/**\r\n * FlexiReact Partial Prerendering (PPR)\r\n * \r\n * Combines static shell with dynamic content:\r\n * - Static parts are prerendered at build time\r\n * - Dynamic parts stream in at request time\r\n * - Best of both SSG and SSR\r\n */\r\n\r\nimport React from 'react';\r\nimport { renderToString } from 'react-dom/server';\r\nimport { cache } from './cache.js';\r\n\r\n// PPR configuration\r\nexport interface PPRConfig {\r\n // Static shell cache duration\r\n shellCacheTTL?: number;\r\n // Dynamic content timeout\r\n dynamicTimeout?: number;\r\n // Fallback for dynamic parts\r\n fallback?: React.ReactNode;\r\n}\r\n\r\n// Mark component as dynamic (not prerendered)\r\nexport function dynamic<T extends React.ComponentType<any>>(\r\n Component: T,\r\n options?: { fallback?: React.ReactNode }\r\n): T {\r\n (Component as any).__flexi_dynamic = true;\r\n (Component as any).__flexi_fallback = options?.fallback;\r\n return Component;\r\n}\r\n\r\n// Mark component as static (prerendered)\r\nexport function staticComponent<T extends React.ComponentType<any>>(Component: T): T {\r\n (Component as any).__flexi_static = true;\r\n return Component;\r\n}\r\n\r\n// Suspense boundary for PPR\r\nexport interface SuspenseBoundaryProps {\r\n children: React.ReactNode;\r\n fallback?: React.ReactNode;\r\n id?: string;\r\n}\r\n\r\nexport function PPRBoundary({ children, fallback, id }: SuspenseBoundaryProps): React.ReactElement {\r\n return React.createElement(\r\n React.Suspense,\r\n { \r\n fallback: fallback || React.createElement('div', { \r\n 'data-ppr-placeholder': id || 'loading',\r\n className: 'ppr-loading'\r\n }, '⏳')\r\n },\r\n children\r\n );\r\n}\r\n\r\n// PPR Shell - static wrapper\r\nexport interface PPRShellProps {\r\n children: React.ReactNode;\r\n fallback?: React.ReactNode;\r\n}\r\n\r\nexport function PPRShell({ children, fallback }: PPRShellProps): React.ReactElement {\r\n return React.createElement(\r\n 'div',\r\n { 'data-ppr-shell': 'true' },\r\n React.createElement(\r\n React.Suspense,\r\n { fallback: fallback || null },\r\n children\r\n )\r\n );\r\n}\r\n\r\n// Prerender a page with PPR\r\nexport interface PPRRenderResult {\r\n staticShell: string;\r\n dynamicParts: Map<string, () => Promise<string>>;\r\n fullHtml: string;\r\n}\r\n\r\nexport async function prerenderWithPPR(\r\n Component: React.ComponentType<any>,\r\n props: any,\r\n config: PPRConfig = {}\r\n): Promise<PPRRenderResult> {\r\n const { shellCacheTTL = 3600 } = config;\r\n \r\n // Track dynamic parts\r\n const dynamicParts = new Map<string, () => Promise<string>>();\r\n let dynamicCounter = 0;\r\n \r\n // Create element\r\n const element = React.createElement(Component, props);\r\n \r\n // Render static shell (with placeholders for dynamic parts)\r\n const staticShell = renderToString(element);\r\n \r\n // Cache the static shell\r\n const cacheKey = `ppr:${Component.name || 'page'}:${JSON.stringify(props)}`;\r\n await cache.set(cacheKey, staticShell, { ttl: shellCacheTTL, tags: ['ppr'] });\r\n \r\n return {\r\n staticShell,\r\n dynamicParts,\r\n fullHtml: staticShell\r\n };\r\n}\r\n\r\n// Stream PPR response\r\nexport async function streamPPR(\r\n staticShell: string,\r\n dynamicParts: Map<string, () => Promise<string>>,\r\n options?: { onError?: (error: Error) => string }\r\n): Promise<ReadableStream<Uint8Array>> {\r\n const encoder = new TextEncoder();\r\n \r\n return new ReadableStream({\r\n async start(controller) {\r\n // Send static shell immediately\r\n controller.enqueue(encoder.encode(staticShell));\r\n \r\n // Stream dynamic parts as they resolve\r\n const promises = Array.from(dynamicParts.entries()).map(async ([id, render]) => {\r\n try {\r\n const html = await render();\r\n // Send script to replace placeholder\r\n const script = `<script>\r\n (function() {\r\n var placeholder = document.querySelector('[data-ppr-placeholder=\"${id}\"]');\r\n if (placeholder) {\r\n var temp = document.createElement('div');\r\n temp.innerHTML = ${JSON.stringify(html)};\r\n placeholder.replaceWith(...temp.childNodes);\r\n }\r\n })();\r\n </script>`;\r\n controller.enqueue(encoder.encode(script));\r\n } catch (error: any) {\r\n const errorHtml = options?.onError?.(error) || `<div class=\"ppr-error\">Error loading content</div>`;\r\n const script = `<script>\r\n (function() {\r\n var placeholder = document.querySelector('[data-ppr-placeholder=\"${id}\"]');\r\n if (placeholder) {\r\n placeholder.innerHTML = ${JSON.stringify(errorHtml)};\r\n }\r\n })();\r\n </script>`;\r\n controller.enqueue(encoder.encode(script));\r\n }\r\n });\r\n \r\n await Promise.all(promises);\r\n controller.close();\r\n }\r\n });\r\n}\r\n\r\n// PPR-aware fetch wrapper\r\nexport function pprFetch(\r\n input: RequestInfo | URL,\r\n init?: RequestInit & { \r\n cache?: 'force-cache' | 'no-store' | 'no-cache';\r\n next?: { revalidate?: number; tags?: string[] };\r\n }\r\n): Promise<Response> {\r\n const cacheMode = init?.cache || 'force-cache';\r\n const revalidate = init?.next?.revalidate;\r\n const tags = init?.next?.tags || [];\r\n \r\n // If no-store, always fetch fresh\r\n if (cacheMode === 'no-store') {\r\n return fetch(input, init);\r\n }\r\n \r\n // Create cache key\r\n const url = typeof input === 'string' ? input : input.toString();\r\n const cacheKey = `fetch:${url}:${JSON.stringify(init?.body || '')}`;\r\n \r\n // Try cache first\r\n return cache.wrap(\r\n async () => {\r\n const response = await fetch(input, init);\r\n return response;\r\n },\r\n {\r\n key: cacheKey,\r\n ttl: revalidate || 3600,\r\n tags\r\n }\r\n )();\r\n}\r\n\r\n// Export directive markers\r\nexport const experimental_ppr = true;\r\n\r\n// Page config for PPR\r\nexport interface PPRPageConfig {\r\n experimental_ppr?: boolean;\r\n revalidate?: number | false;\r\n dynamic?: 'auto' | 'force-dynamic' | 'force-static' | 'error';\r\n dynamicParams?: boolean;\r\n fetchCache?: 'auto' | 'default-cache' | 'only-cache' | 'force-cache' | 'force-no-store' | 'default-no-store' | 'only-no-store';\r\n}\r\n\r\n// Generate static params (for SSG with PPR)\r\nexport type GenerateStaticParams<T = any> = () => Promise<T[]> | T[];\r\n\r\n// Default PPR loading component\r\nexport function PPRLoading(): React.ReactElement {\r\n return React.createElement('div', {\r\n className: 'ppr-loading animate-pulse',\r\n style: {\r\n background: 'linear-gradient(90deg, #1a1a1a 25%, #2a2a2a 50%, #1a1a1a 75%)',\r\n backgroundSize: '200% 100%',\r\n animation: 'shimmer 1.5s infinite',\r\n borderRadius: '4px',\r\n height: '1em',\r\n width: '100%'\r\n }\r\n });\r\n}\r\n\r\n// Inject PPR styles\r\nexport function getPPRStyles(): string {\r\n return `\r\n @keyframes shimmer {\r\n 0% { background-position: 200% 0; }\r\n 100% { background-position: -200% 0; }\r\n }\r\n \r\n .ppr-loading {\r\n background: linear-gradient(90deg, #1a1a1a 25%, #2a2a2a 50%, #1a1a1a 75%);\r\n background-size: 200% 100%;\r\n animation: shimmer 1.5s infinite;\r\n border-radius: 4px;\r\n min-height: 1em;\r\n }\r\n \r\n .ppr-error {\r\n color: #ef4444;\r\n padding: 1rem;\r\n border: 1px solid #ef4444;\r\n border-radius: 4px;\r\n background: rgba(239, 68, 68, 0.1);\r\n }\r\n `;\r\n}\r\n\r\nexport default {\r\n dynamic,\r\n staticComponent,\r\n PPRBoundary,\r\n PPRShell,\r\n prerenderWithPPR,\r\n streamPPR,\r\n pprFetch,\r\n PPRLoading,\r\n getPPRStyles,\r\n experimental_ppr\r\n};\r\n","/**\r\n * FlexiReact Metadata API\r\n * \r\n * Complete metadata management like Next.js:\r\n * - Static and dynamic metadata\r\n * - Open Graph / Twitter Cards\r\n * - Robots / Sitemap\r\n * - JSON-LD structured data\r\n * - Viewport configuration\r\n * - Icons and manifest\r\n */\r\n\r\nimport React from 'react';\r\n\r\n// Base metadata types\r\nexport interface Metadata {\r\n // Basic\r\n title?: string | { default: string; template?: string; absolute?: string };\r\n description?: string;\r\n keywords?: string | string[];\r\n authors?: Author | Author[];\r\n creator?: string;\r\n publisher?: string;\r\n \r\n // Robots\r\n robots?: Robots | string;\r\n \r\n // Icons\r\n icons?: Icons;\r\n \r\n // Manifest\r\n manifest?: string;\r\n \r\n // Open Graph\r\n openGraph?: OpenGraph;\r\n \r\n // Twitter\r\n twitter?: Twitter;\r\n \r\n // Verification\r\n verification?: Verification;\r\n \r\n // Alternates\r\n alternates?: Alternates;\r\n \r\n // App Links\r\n appLinks?: AppLinks;\r\n \r\n // Archives\r\n archives?: string | string[];\r\n \r\n // Assets\r\n assets?: string | string[];\r\n \r\n // Bookmarks\r\n bookmarks?: string | string[];\r\n \r\n // Category\r\n category?: string;\r\n \r\n // Classification\r\n classification?: string;\r\n \r\n // Other\r\n other?: Record<string, string | string[]>;\r\n \r\n // Viewport\r\n viewport?: Viewport | string;\r\n \r\n // Theme Color\r\n themeColor?: ThemeColor | ThemeColor[];\r\n \r\n // Color Scheme\r\n colorScheme?: 'normal' | 'light' | 'dark' | 'light dark' | 'dark light';\r\n \r\n // Format Detection\r\n formatDetection?: FormatDetection;\r\n \r\n // Base URL\r\n metadataBase?: URL | string;\r\n \r\n // Generator\r\n generator?: string;\r\n \r\n // Application Name\r\n applicationName?: string;\r\n \r\n // Referrer\r\n referrer?: 'no-referrer' | 'origin' | 'no-referrer-when-downgrade' | 'origin-when-cross-origin' | 'same-origin' | 'strict-origin' | 'strict-origin-when-cross-origin' | 'unsafe-url';\r\n}\r\n\r\nexport interface Author {\r\n name?: string;\r\n url?: string;\r\n}\r\n\r\nexport interface Robots {\r\n index?: boolean;\r\n follow?: boolean;\r\n noarchive?: boolean;\r\n nosnippet?: boolean;\r\n noimageindex?: boolean;\r\n nocache?: boolean;\r\n googleBot?: Robots | string;\r\n}\r\n\r\nexport interface Icons {\r\n icon?: IconDescriptor | IconDescriptor[];\r\n shortcut?: IconDescriptor | IconDescriptor[];\r\n apple?: IconDescriptor | IconDescriptor[];\r\n other?: IconDescriptor[];\r\n}\r\n\r\nexport interface IconDescriptor {\r\n url: string;\r\n type?: string;\r\n sizes?: string;\r\n color?: string;\r\n rel?: string;\r\n media?: string;\r\n}\r\n\r\nexport interface OpenGraph {\r\n type?: 'website' | 'article' | 'book' | 'profile' | 'music.song' | 'music.album' | 'music.playlist' | 'music.radio_station' | 'video.movie' | 'video.episode' | 'video.tv_show' | 'video.other';\r\n url?: string;\r\n title?: string;\r\n description?: string;\r\n siteName?: string;\r\n locale?: string;\r\n images?: OGImage | OGImage[];\r\n videos?: OGVideo | OGVideo[];\r\n audio?: OGAudio | OGAudio[];\r\n determiner?: 'a' | 'an' | 'the' | 'auto' | '';\r\n \r\n // Article specific\r\n publishedTime?: string;\r\n modifiedTime?: string;\r\n expirationTime?: string;\r\n authors?: string | string[];\r\n section?: string;\r\n tags?: string[];\r\n}\r\n\r\nexport interface OGImage {\r\n url: string;\r\n secureUrl?: string;\r\n type?: string;\r\n width?: number;\r\n height?: number;\r\n alt?: string;\r\n}\r\n\r\nexport interface OGVideo {\r\n url: string;\r\n secureUrl?: string;\r\n type?: string;\r\n width?: number;\r\n height?: number;\r\n}\r\n\r\nexport interface OGAudio {\r\n url: string;\r\n secureUrl?: string;\r\n type?: string;\r\n}\r\n\r\nexport interface Twitter {\r\n card?: 'summary' | 'summary_large_image' | 'app' | 'player';\r\n site?: string;\r\n siteId?: string;\r\n creator?: string;\r\n creatorId?: string;\r\n title?: string;\r\n description?: string;\r\n images?: string | TwitterImage | (string | TwitterImage)[];\r\n app?: TwitterApp;\r\n player?: TwitterPlayer;\r\n}\r\n\r\nexport interface TwitterImage {\r\n url: string;\r\n alt?: string;\r\n}\r\n\r\nexport interface TwitterApp {\r\n id?: { iphone?: string; ipad?: string; googleplay?: string };\r\n name?: string;\r\n url?: { iphone?: string; ipad?: string; googleplay?: string };\r\n}\r\n\r\nexport interface TwitterPlayer {\r\n url: string;\r\n width?: number;\r\n height?: number;\r\n stream?: string;\r\n}\r\n\r\nexport interface Verification {\r\n google?: string | string[];\r\n yahoo?: string | string[];\r\n yandex?: string | string[];\r\n me?: string | string[];\r\n other?: Record<string, string | string[]>;\r\n}\r\n\r\nexport interface Alternates {\r\n canonical?: string;\r\n languages?: Record<string, string>;\r\n media?: Record<string, string>;\r\n types?: Record<string, string>;\r\n}\r\n\r\nexport interface AppLinks {\r\n ios?: AppLink | AppLink[];\r\n iphone?: AppLink | AppLink[];\r\n ipad?: AppLink | AppLink[];\r\n android?: AppLink | AppLink[];\r\n windows_phone?: AppLink | AppLink[];\r\n windows?: AppLink | AppLink[];\r\n windows_universal?: AppLink | AppLink[];\r\n web?: AppLink | AppLink[];\r\n}\r\n\r\nexport interface AppLink {\r\n url: string;\r\n app_store_id?: string;\r\n app_name?: string;\r\n}\r\n\r\nexport interface Viewport {\r\n width?: number | 'device-width';\r\n height?: number | 'device-height';\r\n initialScale?: number;\r\n minimumScale?: number;\r\n maximumScale?: number;\r\n userScalable?: boolean;\r\n viewportFit?: 'auto' | 'cover' | 'contain';\r\n interactiveWidget?: 'resizes-visual' | 'resizes-content' | 'overlays-content';\r\n}\r\n\r\nexport interface ThemeColor {\r\n color: string;\r\n media?: string;\r\n}\r\n\r\nexport interface FormatDetection {\r\n telephone?: boolean;\r\n date?: boolean;\r\n address?: boolean;\r\n email?: boolean;\r\n url?: boolean;\r\n}\r\n\r\n// Generate HTML head tags from metadata\r\nexport function generateMetadataTags(metadata: Metadata, baseUrl?: string): string {\r\n const tags: string[] = [];\r\n const base = baseUrl || metadata.metadataBase?.toString() || '';\r\n\r\n // Title\r\n if (metadata.title) {\r\n const title = typeof metadata.title === 'string' \r\n ? metadata.title \r\n : metadata.title.absolute || (metadata.title.template \r\n ? metadata.title.template.replace('%s', metadata.title.default)\r\n : metadata.title.default);\r\n tags.push(`<title>${escapeHtml(title)}</title>`);\r\n }\r\n\r\n // Description\r\n if (metadata.description) {\r\n tags.push(`<meta name=\"description\" content=\"${escapeHtml(metadata.description)}\">`);\r\n }\r\n\r\n // Keywords\r\n if (metadata.keywords) {\r\n const keywords = Array.isArray(metadata.keywords) ? metadata.keywords.join(', ') : metadata.keywords;\r\n tags.push(`<meta name=\"keywords\" content=\"${escapeHtml(keywords)}\">`);\r\n }\r\n\r\n // Authors\r\n if (metadata.authors) {\r\n const authors = Array.isArray(metadata.authors) ? metadata.authors : [metadata.authors];\r\n authors.forEach(author => {\r\n if (author.name) tags.push(`<meta name=\"author\" content=\"${escapeHtml(author.name)}\">`);\r\n if (author.url) tags.push(`<link rel=\"author\" href=\"${author.url}\">`);\r\n });\r\n }\r\n\r\n // Generator\r\n if (metadata.generator) {\r\n tags.push(`<meta name=\"generator\" content=\"${escapeHtml(metadata.generator)}\">`);\r\n }\r\n\r\n // Application Name\r\n if (metadata.applicationName) {\r\n tags.push(`<meta name=\"application-name\" content=\"${escapeHtml(metadata.applicationName)}\">`);\r\n }\r\n\r\n // Referrer\r\n if (metadata.referrer) {\r\n tags.push(`<meta name=\"referrer\" content=\"${metadata.referrer}\">`);\r\n }\r\n\r\n // Robots\r\n if (metadata.robots) {\r\n if (typeof metadata.robots === 'string') {\r\n tags.push(`<meta name=\"robots\" content=\"${metadata.robots}\">`);\r\n } else {\r\n const robotsContent = generateRobotsContent(metadata.robots);\r\n tags.push(`<meta name=\"robots\" content=\"${robotsContent}\">`);\r\n if (metadata.robots.googleBot) {\r\n const googleBotContent = typeof metadata.robots.googleBot === 'string'\r\n ? metadata.robots.googleBot\r\n : generateRobotsContent(metadata.robots.googleBot);\r\n tags.push(`<meta name=\"googlebot\" content=\"${googleBotContent}\">`);\r\n }\r\n }\r\n }\r\n\r\n // Viewport\r\n if (metadata.viewport) {\r\n const viewportContent = typeof metadata.viewport === 'string'\r\n ? metadata.viewport\r\n : generateViewportContent(metadata.viewport);\r\n tags.push(`<meta name=\"viewport\" content=\"${viewportContent}\">`);\r\n }\r\n\r\n // Theme Color\r\n if (metadata.themeColor) {\r\n const themeColors = Array.isArray(metadata.themeColor) ? metadata.themeColor : [metadata.themeColor];\r\n themeColors.forEach(tc => {\r\n if (typeof tc === 'string') {\r\n tags.push(`<meta name=\"theme-color\" content=\"${tc}\">`);\r\n } else {\r\n const mediaAttr = tc.media ? ` media=\"${tc.media}\"` : '';\r\n tags.push(`<meta name=\"theme-color\" content=\"${tc.color}\"${mediaAttr}>`);\r\n }\r\n });\r\n }\r\n\r\n // Color Scheme\r\n if (metadata.colorScheme) {\r\n tags.push(`<meta name=\"color-scheme\" content=\"${metadata.colorScheme}\">`);\r\n }\r\n\r\n // Format Detection\r\n if (metadata.formatDetection) {\r\n const fd = metadata.formatDetection;\r\n const parts: string[] = [];\r\n if (fd.telephone === false) parts.push('telephone=no');\r\n if (fd.date === false) parts.push('date=no');\r\n if (fd.address === false) parts.push('address=no');\r\n if (fd.email === false) parts.push('email=no');\r\n if (parts.length > 0) {\r\n tags.push(`<meta name=\"format-detection\" content=\"${parts.join(', ')}\">`);\r\n }\r\n }\r\n\r\n // Icons\r\n if (metadata.icons) {\r\n const addIcon = (icon: IconDescriptor, defaultRel: string) => {\r\n const rel = icon.rel || defaultRel;\r\n const type = icon.type ? ` type=\"${icon.type}\"` : '';\r\n const sizes = icon.sizes ? ` sizes=\"${icon.sizes}\"` : '';\r\n const color = icon.color ? ` color=\"${icon.color}\"` : '';\r\n const media = icon.media ? ` media=\"${icon.media}\"` : '';\r\n tags.push(`<link rel=\"${rel}\" href=\"${resolveUrl(icon.url, base)}\"${type}${sizes}${color}${media}>`);\r\n };\r\n\r\n if (metadata.icons.icon) {\r\n const icons = Array.isArray(metadata.icons.icon) ? metadata.icons.icon : [metadata.icons.icon];\r\n icons.forEach(icon => addIcon(icon, 'icon'));\r\n }\r\n if (metadata.icons.shortcut) {\r\n const icons = Array.isArray(metadata.icons.shortcut) ? metadata.icons.shortcut : [metadata.icons.shortcut];\r\n icons.forEach(icon => addIcon(icon, 'shortcut icon'));\r\n }\r\n if (metadata.icons.apple) {\r\n const icons = Array.isArray(metadata.icons.apple) ? metadata.icons.apple : [metadata.icons.apple];\r\n icons.forEach(icon => addIcon(icon, 'apple-touch-icon'));\r\n }\r\n }\r\n\r\n // Manifest\r\n if (metadata.manifest) {\r\n tags.push(`<link rel=\"manifest\" href=\"${resolveUrl(metadata.manifest, base)}\">`);\r\n }\r\n\r\n // Open Graph\r\n if (metadata.openGraph) {\r\n const og = metadata.openGraph;\r\n if (og.type) tags.push(`<meta property=\"og:type\" content=\"${og.type}\">`);\r\n if (og.title) tags.push(`<meta property=\"og:title\" content=\"${escapeHtml(og.title)}\">`);\r\n if (og.description) tags.push(`<meta property=\"og:description\" content=\"${escapeHtml(og.description)}\">`);\r\n if (og.url) tags.push(`<meta property=\"og:url\" content=\"${resolveUrl(og.url, base)}\">`);\r\n if (og.siteName) tags.push(`<meta property=\"og:site_name\" content=\"${escapeHtml(og.siteName)}\">`);\r\n if (og.locale) tags.push(`<meta property=\"og:locale\" content=\"${og.locale}\">`);\r\n if (og.determiner) tags.push(`<meta property=\"og:determiner\" content=\"${og.determiner}\">`);\r\n\r\n // Images\r\n if (og.images) {\r\n const images = Array.isArray(og.images) ? og.images : [og.images];\r\n images.forEach(img => {\r\n tags.push(`<meta property=\"og:image\" content=\"${resolveUrl(img.url, base)}\">`);\r\n if (img.secureUrl) tags.push(`<meta property=\"og:image:secure_url\" content=\"${img.secureUrl}\">`);\r\n if (img.type) tags.push(`<meta property=\"og:image:type\" content=\"${img.type}\">`);\r\n if (img.width) tags.push(`<meta property=\"og:image:width\" content=\"${img.width}\">`);\r\n if (img.height) tags.push(`<meta property=\"og:image:height\" content=\"${img.height}\">`);\r\n if (img.alt) tags.push(`<meta property=\"og:image:alt\" content=\"${escapeHtml(img.alt)}\">`);\r\n });\r\n }\r\n\r\n // Article specific\r\n if (og.type === 'article') {\r\n if (og.publishedTime) tags.push(`<meta property=\"article:published_time\" content=\"${og.publishedTime}\">`);\r\n if (og.modifiedTime) tags.push(`<meta property=\"article:modified_time\" content=\"${og.modifiedTime}\">`);\r\n if (og.expirationTime) tags.push(`<meta property=\"article:expiration_time\" content=\"${og.expirationTime}\">`);\r\n if (og.section) tags.push(`<meta property=\"article:section\" content=\"${escapeHtml(og.section)}\">`);\r\n if (og.tags) {\r\n og.tags.forEach(tag => tags.push(`<meta property=\"article:tag\" content=\"${escapeHtml(tag)}\">`));\r\n }\r\n if (og.authors) {\r\n const authors = Array.isArray(og.authors) ? og.authors : [og.authors];\r\n authors.forEach(author => tags.push(`<meta property=\"article:author\" content=\"${escapeHtml(author)}\">`));\r\n }\r\n }\r\n }\r\n\r\n // Twitter\r\n if (metadata.twitter) {\r\n const tw = metadata.twitter;\r\n if (tw.card) tags.push(`<meta name=\"twitter:card\" content=\"${tw.card}\">`);\r\n if (tw.site) tags.push(`<meta name=\"twitter:site\" content=\"${tw.site}\">`);\r\n if (tw.siteId) tags.push(`<meta name=\"twitter:site:id\" content=\"${tw.siteId}\">`);\r\n if (tw.creator) tags.push(`<meta name=\"twitter:creator\" content=\"${tw.creator}\">`);\r\n if (tw.creatorId) tags.push(`<meta name=\"twitter:creator:id\" content=\"${tw.creatorId}\">`);\r\n if (tw.title) tags.push(`<meta name=\"twitter:title\" content=\"${escapeHtml(tw.title)}\">`);\r\n if (tw.description) tags.push(`<meta name=\"twitter:description\" content=\"${escapeHtml(tw.description)}\">`);\r\n\r\n if (tw.images) {\r\n const images = Array.isArray(tw.images) ? tw.images : [tw.images];\r\n images.forEach(img => {\r\n const url = typeof img === 'string' ? img : img.url;\r\n tags.push(`<meta name=\"twitter:image\" content=\"${resolveUrl(url, base)}\">`);\r\n if (typeof img !== 'string' && img.alt) {\r\n tags.push(`<meta name=\"twitter:image:alt\" content=\"${escapeHtml(img.alt)}\">`);\r\n }\r\n });\r\n }\r\n }\r\n\r\n // Verification\r\n if (metadata.verification) {\r\n const v = metadata.verification;\r\n if (v.google) {\r\n const values = Array.isArray(v.google) ? v.google : [v.google];\r\n values.forEach(val => tags.push(`<meta name=\"google-site-verification\" content=\"${val}\">`));\r\n }\r\n if (v.yandex) {\r\n const values = Array.isArray(v.yandex) ? v.yandex : [v.yandex];\r\n values.forEach(val => tags.push(`<meta name=\"yandex-verification\" content=\"${val}\">`));\r\n }\r\n }\r\n\r\n // Alternates\r\n if (metadata.alternates) {\r\n const alt = metadata.alternates;\r\n if (alt.canonical) {\r\n tags.push(`<link rel=\"canonical\" href=\"${resolveUrl(alt.canonical, base)}\">`);\r\n }\r\n if (alt.languages) {\r\n Object.entries(alt.languages).forEach(([lang, url]) => {\r\n tags.push(`<link rel=\"alternate\" hreflang=\"${lang}\" href=\"${resolveUrl(url, base)}\">`);\r\n });\r\n }\r\n }\r\n\r\n return tags.join('\\n ');\r\n}\r\n\r\n// Helper functions\r\nfunction escapeHtml(str: string): string {\r\n return str\r\n .replace(/&/g, '&amp;')\r\n .replace(/</g, '&lt;')\r\n .replace(/>/g, '&gt;')\r\n .replace(/\"/g, '&quot;')\r\n .replace(/'/g, '&#039;');\r\n}\r\n\r\nfunction resolveUrl(url: string, base: string): string {\r\n if (url.startsWith('http://') || url.startsWith('https://') || url.startsWith('//')) {\r\n return url;\r\n }\r\n return base ? `${base.replace(/\\/$/, '')}${url.startsWith('/') ? '' : '/'}${url}` : url;\r\n}\r\n\r\nfunction generateRobotsContent(robots: Robots): string {\r\n const parts: string[] = [];\r\n if (robots.index !== undefined) parts.push(robots.index ? 'index' : 'noindex');\r\n if (robots.follow !== undefined) parts.push(robots.follow ? 'follow' : 'nofollow');\r\n if (robots.noarchive) parts.push('noarchive');\r\n if (robots.nosnippet) parts.push('nosnippet');\r\n if (robots.noimageindex) parts.push('noimageindex');\r\n if (robots.nocache) parts.push('nocache');\r\n return parts.join(', ') || 'index, follow';\r\n}\r\n\r\nfunction generateViewportContent(viewport: Viewport): string {\r\n const parts: string[] = [];\r\n if (viewport.width) parts.push(`width=${viewport.width}`);\r\n if (viewport.height) parts.push(`height=${viewport.height}`);\r\n if (viewport.initialScale !== undefined) parts.push(`initial-scale=${viewport.initialScale}`);\r\n if (viewport.minimumScale !== undefined) parts.push(`minimum-scale=${viewport.minimumScale}`);\r\n if (viewport.maximumScale !== undefined) parts.push(`maximum-scale=${viewport.maximumScale}`);\r\n if (viewport.userScalable !== undefined) parts.push(`user-scalable=${viewport.userScalable ? 'yes' : 'no'}`);\r\n if (viewport.viewportFit) parts.push(`viewport-fit=${viewport.viewportFit}`);\r\n return parts.join(', ') || 'width=device-width, initial-scale=1';\r\n}\r\n\r\n// Merge metadata (child overrides parent)\r\nexport function mergeMetadata(parent: Metadata, child: Metadata): Metadata {\r\n return {\r\n ...parent,\r\n ...child,\r\n // Deep merge for nested objects\r\n openGraph: child.openGraph ? { ...parent.openGraph, ...child.openGraph } : parent.openGraph,\r\n twitter: child.twitter ? { ...parent.twitter, ...child.twitter } : parent.twitter,\r\n icons: child.icons ? { ...parent.icons, ...child.icons } : parent.icons,\r\n verification: child.verification ? { ...parent.verification, ...child.verification } : parent.verification,\r\n alternates: child.alternates ? { ...parent.alternates, ...child.alternates } : parent.alternates\r\n };\r\n}\r\n\r\n// Generate JSON-LD structured data\r\nexport function generateJsonLd(data: Record<string, any>): string {\r\n return `<script type=\"application/ld+json\">${JSON.stringify(data)}</script>`;\r\n}\r\n\r\n// Common JSON-LD schemas\r\nexport const jsonLd = {\r\n website: (config: { name: string; url: string; description?: string }) => ({\r\n '@context': 'https://schema.org',\r\n '@type': 'WebSite',\r\n name: config.name,\r\n url: config.url,\r\n description: config.description\r\n }),\r\n \r\n article: (config: {\r\n headline: string;\r\n description?: string;\r\n image?: string | string[];\r\n datePublished: string;\r\n dateModified?: string;\r\n author: { name: string; url?: string } | { name: string; url?: string }[];\r\n }) => ({\r\n '@context': 'https://schema.org',\r\n '@type': 'Article',\r\n headline: config.headline,\r\n description: config.description,\r\n image: config.image,\r\n datePublished: config.datePublished,\r\n dateModified: config.dateModified || config.datePublished,\r\n author: Array.isArray(config.author)\r\n ? config.author.map(a => ({ '@type': 'Person', ...a }))\r\n : { '@type': 'Person', ...config.author }\r\n }),\r\n \r\n organization: (config: {\r\n name: string;\r\n url: string;\r\n logo?: string;\r\n sameAs?: string[];\r\n }) => ({\r\n '@context': 'https://schema.org',\r\n '@type': 'Organization',\r\n name: config.name,\r\n url: config.url,\r\n logo: config.logo,\r\n sameAs: config.sameAs\r\n }),\r\n \r\n product: (config: {\r\n name: string;\r\n description?: string;\r\n image?: string | string[];\r\n brand?: string;\r\n offers?: { price: number; priceCurrency: string; availability?: string };\r\n }) => ({\r\n '@context': 'https://schema.org',\r\n '@type': 'Product',\r\n name: config.name,\r\n description: config.description,\r\n image: config.image,\r\n brand: config.brand ? { '@type': 'Brand', name: config.brand } : undefined,\r\n offers: config.offers ? {\r\n '@type': 'Offer',\r\n price: config.offers.price,\r\n priceCurrency: config.offers.priceCurrency,\r\n availability: config.offers.availability || 'https://schema.org/InStock'\r\n } : undefined\r\n }),\r\n \r\n breadcrumb: (items: { name: string; url: string }[]) => ({\r\n '@context': 'https://schema.org',\r\n '@type': 'BreadcrumbList',\r\n itemListElement: items.map((item, index) => ({\r\n '@type': 'ListItem',\r\n position: index + 1,\r\n name: item.name,\r\n item: item.url\r\n }))\r\n })\r\n};\r\n\r\nexport default {\r\n generateMetadataTags,\r\n mergeMetadata,\r\n generateJsonLd,\r\n jsonLd\r\n};\r\n","/**\r\n * FlexiReact DevTools\r\n * Advanced development tools for debugging and performance monitoring\r\n */\r\n\r\nimport React from 'react';\r\n\r\n// ============================================================================\r\n// DevTools State\r\n// ============================================================================\r\n\r\ninterface DevToolsState {\r\n enabled: boolean;\r\n position: 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';\r\n expanded: boolean;\r\n activeTab: 'routes' | 'components' | 'network' | 'performance' | 'state' | 'console';\r\n theme: 'dark' | 'light';\r\n}\r\n\r\ninterface RouteInfo {\r\n path: string;\r\n component: string;\r\n params: Record<string, string>;\r\n query: Record<string, string>;\r\n loadTime: number;\r\n}\r\n\r\ninterface ComponentInfo {\r\n name: string;\r\n renderCount: number;\r\n lastRenderTime: number;\r\n props: Record<string, any>;\r\n isIsland: boolean;\r\n}\r\n\r\ninterface NetworkRequest {\r\n id: string;\r\n url: string;\r\n method: string;\r\n status: number;\r\n duration: number;\r\n size: number;\r\n timestamp: number;\r\n type: 'fetch' | 'xhr' | 'ssr' | 'action';\r\n}\r\n\r\ninterface PerformanceMetric {\r\n name: string;\r\n value: number;\r\n rating: 'good' | 'needs-improvement' | 'poor';\r\n}\r\n\r\n// Global DevTools state\r\nconst devToolsState: {\r\n routes: RouteInfo[];\r\n components: Map<string, ComponentInfo>;\r\n network: NetworkRequest[];\r\n performance: PerformanceMetric[];\r\n logs: Array<{ level: string; message: string; timestamp: number }>;\r\n listeners: Set<() => void>;\r\n} = {\r\n routes: [],\r\n components: new Map(),\r\n network: [],\r\n performance: [],\r\n logs: [],\r\n listeners: new Set(),\r\n};\r\n\r\n// ============================================================================\r\n// DevTools API\r\n// ============================================================================\r\n\r\nexport const devtools = {\r\n // Track route navigation\r\n trackRoute(info: RouteInfo): void {\r\n devToolsState.routes.unshift(info);\r\n if (devToolsState.routes.length > 50) {\r\n devToolsState.routes.pop();\r\n }\r\n this.notify();\r\n },\r\n\r\n // Track component render\r\n trackComponent(name: string, info: Partial<ComponentInfo>): void {\r\n const existing = devToolsState.components.get(name) || {\r\n name,\r\n renderCount: 0,\r\n lastRenderTime: 0,\r\n props: {},\r\n isIsland: false,\r\n };\r\n \r\n devToolsState.components.set(name, {\r\n ...existing,\r\n ...info,\r\n renderCount: existing.renderCount + 1,\r\n lastRenderTime: Date.now(),\r\n });\r\n this.notify();\r\n },\r\n\r\n // Track network request\r\n trackRequest(request: NetworkRequest): void {\r\n devToolsState.network.unshift(request);\r\n if (devToolsState.network.length > 100) {\r\n devToolsState.network.pop();\r\n }\r\n this.notify();\r\n },\r\n\r\n // Track performance metric\r\n trackMetric(metric: PerformanceMetric): void {\r\n const existing = devToolsState.performance.findIndex(m => m.name === metric.name);\r\n if (existing >= 0) {\r\n devToolsState.performance[existing] = metric;\r\n } else {\r\n devToolsState.performance.push(metric);\r\n }\r\n this.notify();\r\n },\r\n\r\n // Log message\r\n log(level: 'info' | 'warn' | 'error' | 'debug', message: string): void {\r\n devToolsState.logs.unshift({\r\n level,\r\n message,\r\n timestamp: Date.now(),\r\n });\r\n if (devToolsState.logs.length > 200) {\r\n devToolsState.logs.pop();\r\n }\r\n this.notify();\r\n },\r\n\r\n // Get current state\r\n getState() {\r\n return {\r\n routes: devToolsState.routes,\r\n components: Array.from(devToolsState.components.values()),\r\n network: devToolsState.network,\r\n performance: devToolsState.performance,\r\n logs: devToolsState.logs,\r\n };\r\n },\r\n\r\n // Subscribe to changes\r\n subscribe(listener: () => void): () => void {\r\n devToolsState.listeners.add(listener);\r\n return () => devToolsState.listeners.delete(listener);\r\n },\r\n\r\n // Notify listeners\r\n notify(): void {\r\n devToolsState.listeners.forEach(listener => listener());\r\n },\r\n\r\n // Clear all data\r\n clear(): void {\r\n devToolsState.routes = [];\r\n devToolsState.components.clear();\r\n devToolsState.network = [];\r\n devToolsState.performance = [];\r\n devToolsState.logs = [];\r\n this.notify();\r\n },\r\n};\r\n\r\n// ============================================================================\r\n// Performance Monitoring\r\n// ============================================================================\r\n\r\nexport function initPerformanceMonitoring(): void {\r\n if (typeof window === 'undefined') return;\r\n\r\n // Core Web Vitals\r\n try {\r\n // LCP (Largest Contentful Paint)\r\n new PerformanceObserver((list) => {\r\n const entries = list.getEntries();\r\n const lastEntry = entries[entries.length - 1] as any;\r\n devtools.trackMetric({\r\n name: 'LCP',\r\n value: lastEntry.startTime,\r\n rating: lastEntry.startTime < 2500 ? 'good' : lastEntry.startTime < 4000 ? 'needs-improvement' : 'poor',\r\n });\r\n }).observe({ type: 'largest-contentful-paint', buffered: true });\r\n\r\n // FID (First Input Delay)\r\n new PerformanceObserver((list) => {\r\n const entries = list.getEntries();\r\n entries.forEach((entry: any) => {\r\n devtools.trackMetric({\r\n name: 'FID',\r\n value: entry.processingStart - entry.startTime,\r\n rating: entry.processingStart - entry.startTime < 100 ? 'good' : \r\n entry.processingStart - entry.startTime < 300 ? 'needs-improvement' : 'poor',\r\n });\r\n });\r\n }).observe({ type: 'first-input', buffered: true });\r\n\r\n // CLS (Cumulative Layout Shift)\r\n let clsValue = 0;\r\n new PerformanceObserver((list) => {\r\n for (const entry of list.getEntries() as any[]) {\r\n if (!entry.hadRecentInput) {\r\n clsValue += entry.value;\r\n }\r\n }\r\n devtools.trackMetric({\r\n name: 'CLS',\r\n value: clsValue,\r\n rating: clsValue < 0.1 ? 'good' : clsValue < 0.25 ? 'needs-improvement' : 'poor',\r\n });\r\n }).observe({ type: 'layout-shift', buffered: true });\r\n\r\n // TTFB (Time to First Byte)\r\n const navEntry = performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming;\r\n if (navEntry) {\r\n devtools.trackMetric({\r\n name: 'TTFB',\r\n value: navEntry.responseStart - navEntry.requestStart,\r\n rating: navEntry.responseStart - navEntry.requestStart < 200 ? 'good' : \r\n navEntry.responseStart - navEntry.requestStart < 500 ? 'needs-improvement' : 'poor',\r\n });\r\n }\r\n } catch (e) {\r\n // Performance API not fully supported\r\n }\r\n}\r\n\r\n// ============================================================================\r\n// Network Interceptor\r\n// ============================================================================\r\n\r\nexport function initNetworkInterceptor(): void {\r\n if (typeof window === 'undefined') return;\r\n\r\n // Intercept fetch\r\n const originalFetch = window.fetch;\r\n window.fetch = async function(...args) {\r\n const startTime = Date.now();\r\n const url = typeof args[0] === 'string' ? args[0] : (args[0] as Request).url;\r\n const method = typeof args[0] === 'string' ? (args[1]?.method || 'GET') : (args[0] as Request).method;\r\n \r\n try {\r\n const response = await originalFetch.apply(this, args);\r\n const clone = response.clone();\r\n const size = (await clone.blob()).size;\r\n \r\n devtools.trackRequest({\r\n id: Math.random().toString(36).slice(2),\r\n url,\r\n method,\r\n status: response.status,\r\n duration: Date.now() - startTime,\r\n size,\r\n timestamp: startTime,\r\n type: url.includes('/_flexi/action') ? 'action' : 'fetch',\r\n });\r\n \r\n return response;\r\n } catch (error) {\r\n devtools.trackRequest({\r\n id: Math.random().toString(36).slice(2),\r\n url,\r\n method,\r\n status: 0,\r\n duration: Date.now() - startTime,\r\n size: 0,\r\n timestamp: startTime,\r\n type: 'fetch',\r\n });\r\n throw error;\r\n }\r\n };\r\n}\r\n\r\n// ============================================================================\r\n// DevTools Overlay Component\r\n// ============================================================================\r\n\r\nexport function DevToolsOverlay(): React.ReactElement | null {\r\n const [state, setState] = React.useState<DevToolsState>({\r\n enabled: true,\r\n position: 'bottom-right',\r\n expanded: false,\r\n activeTab: 'routes',\r\n theme: 'dark',\r\n });\r\n\r\n const [data, setData] = React.useState(devtools.getState());\r\n\r\n React.useEffect(() => {\r\n return devtools.subscribe(() => {\r\n setData(devtools.getState());\r\n });\r\n }, []);\r\n\r\n React.useEffect(() => {\r\n initPerformanceMonitoring();\r\n initNetworkInterceptor();\r\n }, []);\r\n\r\n // Keyboard shortcut (Ctrl+Shift+D)\r\n React.useEffect(() => {\r\n const handler = (e: KeyboardEvent) => {\r\n if (e.ctrlKey && e.shiftKey && e.key === 'D') {\r\n setState(s => ({ ...s, expanded: !s.expanded }));\r\n }\r\n };\r\n window.addEventListener('keydown', handler);\r\n return () => window.removeEventListener('keydown', handler);\r\n }, []);\r\n\r\n if (!state.enabled) return null;\r\n\r\n const positionStyles: Record<string, React.CSSProperties> = {\r\n 'bottom-right': { bottom: 16, right: 16 },\r\n 'bottom-left': { bottom: 16, left: 16 },\r\n 'top-right': { top: 16, right: 16 },\r\n 'top-left': { top: 16, left: 16 },\r\n };\r\n\r\n // Mini button when collapsed\r\n if (!state.expanded) {\r\n return React.createElement('button', {\r\n onClick: () => setState(s => ({ ...s, expanded: true })),\r\n style: {\r\n position: 'fixed',\r\n ...positionStyles[state.position],\r\n zIndex: 99999,\r\n width: 48,\r\n height: 48,\r\n borderRadius: 12,\r\n background: 'linear-gradient(135deg, #00FF9C 0%, #00D68F 100%)',\r\n border: 'none',\r\n cursor: 'pointer',\r\n display: 'flex',\r\n alignItems: 'center',\r\n justifyContent: 'center',\r\n boxShadow: '0 4px 20px rgba(0, 255, 156, 0.3)',\r\n transition: 'transform 0.2s',\r\n },\r\n onMouseEnter: (e: any) => e.target.style.transform = 'scale(1.1)',\r\n onMouseLeave: (e: any) => e.target.style.transform = 'scale(1)',\r\n title: 'FlexiReact DevTools (Ctrl+Shift+D)',\r\n }, React.createElement('span', { style: { fontSize: 24 } }, '⚡'));\r\n }\r\n\r\n // Full panel\r\n const tabs = [\r\n { id: 'routes', label: '🗺️ Routes', count: data.routes.length },\r\n { id: 'components', label: '🧩 Components', count: data.components.length },\r\n { id: 'network', label: '🌐 Network', count: data.network.length },\r\n { id: 'performance', label: '📊 Performance', count: data.performance.length },\r\n { id: 'console', label: '📝 Console', count: data.logs.length },\r\n ];\r\n\r\n return React.createElement('div', {\r\n style: {\r\n position: 'fixed',\r\n ...positionStyles[state.position],\r\n zIndex: 99999,\r\n width: 480,\r\n maxHeight: '70vh',\r\n background: '#0a0a0a',\r\n border: '1px solid #222',\r\n borderRadius: 12,\r\n boxShadow: '0 8px 32px rgba(0, 0, 0, 0.5)',\r\n fontFamily: 'system-ui, -apple-system, sans-serif',\r\n fontSize: 13,\r\n color: '#fff',\r\n overflow: 'hidden',\r\n },\r\n }, [\r\n // Header\r\n React.createElement('div', {\r\n key: 'header',\r\n style: {\r\n display: 'flex',\r\n alignItems: 'center',\r\n justifyContent: 'space-between',\r\n padding: '12px 16px',\r\n borderBottom: '1px solid #222',\r\n background: '#111',\r\n },\r\n }, [\r\n React.createElement('div', {\r\n key: 'title',\r\n style: { display: 'flex', alignItems: 'center', gap: 8 },\r\n }, [\r\n React.createElement('span', { key: 'icon' }, '⚡'),\r\n React.createElement('span', { key: 'text', style: { fontWeight: 600 } }, 'FlexiReact DevTools'),\r\n ]),\r\n React.createElement('button', {\r\n key: 'close',\r\n onClick: () => setState(s => ({ ...s, expanded: false })),\r\n style: {\r\n background: 'none',\r\n border: 'none',\r\n color: '#666',\r\n cursor: 'pointer',\r\n fontSize: 18,\r\n },\r\n }, '×'),\r\n ]),\r\n\r\n // Tabs\r\n React.createElement('div', {\r\n key: 'tabs',\r\n style: {\r\n display: 'flex',\r\n borderBottom: '1px solid #222',\r\n background: '#0d0d0d',\r\n overflowX: 'auto',\r\n },\r\n }, tabs.map(tab => \r\n React.createElement('button', {\r\n key: tab.id,\r\n onClick: () => setState(s => ({ ...s, activeTab: tab.id as any })),\r\n style: {\r\n padding: '10px 14px',\r\n background: state.activeTab === tab.id ? '#1a1a1a' : 'transparent',\r\n border: 'none',\r\n borderBottom: state.activeTab === tab.id ? '2px solid #00FF9C' : '2px solid transparent',\r\n color: state.activeTab === tab.id ? '#fff' : '#888',\r\n cursor: 'pointer',\r\n fontSize: 12,\r\n whiteSpace: 'nowrap',\r\n },\r\n }, `${tab.label} (${tab.count})`)\r\n )),\r\n\r\n // Content\r\n React.createElement('div', {\r\n key: 'content',\r\n style: {\r\n padding: 16,\r\n maxHeight: 'calc(70vh - 100px)',\r\n overflowY: 'auto',\r\n },\r\n }, renderTabContent(state.activeTab, data)),\r\n ]);\r\n}\r\n\r\nfunction renderTabContent(tab: string, data: ReturnType<typeof devtools.getState>): React.ReactElement {\r\n switch (tab) {\r\n case 'routes':\r\n return React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 8 } },\r\n data.routes.length === 0 \r\n ? React.createElement('div', { style: { color: '#666', textAlign: 'center', padding: 20 } }, 'No routes tracked yet')\r\n : data.routes.map((route, i) => \r\n React.createElement('div', {\r\n key: i,\r\n style: {\r\n padding: 12,\r\n background: '#111',\r\n borderRadius: 8,\r\n border: '1px solid #222',\r\n },\r\n }, [\r\n React.createElement('div', { key: 'path', style: { fontWeight: 600, color: '#00FF9C' } }, route.path),\r\n React.createElement('div', { key: 'component', style: { fontSize: 11, color: '#888', marginTop: 4 } }, \r\n `Component: ${route.component} • ${route.loadTime}ms`\r\n ),\r\n ])\r\n )\r\n );\r\n\r\n case 'components':\r\n return React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 8 } },\r\n data.components.length === 0\r\n ? React.createElement('div', { style: { color: '#666', textAlign: 'center', padding: 20 } }, 'No components tracked')\r\n : data.components.map((comp, i) =>\r\n React.createElement('div', {\r\n key: i,\r\n style: {\r\n padding: 12,\r\n background: '#111',\r\n borderRadius: 8,\r\n border: '1px solid #222',\r\n },\r\n }, [\r\n React.createElement('div', { \r\n key: 'name',\r\n style: { display: 'flex', alignItems: 'center', gap: 8 } \r\n }, [\r\n React.createElement('span', { key: 'text', style: { fontWeight: 600 } }, comp.name),\r\n comp.isIsland && React.createElement('span', {\r\n key: 'island',\r\n style: {\r\n fontSize: 10,\r\n padding: '2px 6px',\r\n background: '#00FF9C20',\r\n color: '#00FF9C',\r\n borderRadius: 4,\r\n },\r\n }, 'Island'),\r\n ]),\r\n React.createElement('div', { key: 'info', style: { fontSize: 11, color: '#888', marginTop: 4 } },\r\n `Renders: ${comp.renderCount} • Last: ${new Date(comp.lastRenderTime).toLocaleTimeString()}`\r\n ),\r\n ])\r\n )\r\n );\r\n\r\n case 'network':\r\n return React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 8 } },\r\n data.network.length === 0\r\n ? React.createElement('div', { style: { color: '#666', textAlign: 'center', padding: 20 } }, 'No requests yet')\r\n : data.network.map((req, i) =>\r\n React.createElement('div', {\r\n key: i,\r\n style: {\r\n padding: 12,\r\n background: '#111',\r\n borderRadius: 8,\r\n border: '1px solid #222',\r\n },\r\n }, [\r\n React.createElement('div', { \r\n key: 'url',\r\n style: { display: 'flex', alignItems: 'center', gap: 8 } \r\n }, [\r\n React.createElement('span', {\r\n key: 'method',\r\n style: {\r\n fontSize: 10,\r\n padding: '2px 6px',\r\n background: req.method === 'GET' ? '#3B82F620' : '#F59E0B20',\r\n color: req.method === 'GET' ? '#3B82F6' : '#F59E0B',\r\n borderRadius: 4,\r\n fontWeight: 600,\r\n },\r\n }, req.method),\r\n React.createElement('span', {\r\n key: 'status',\r\n style: {\r\n fontSize: 10,\r\n padding: '2px 6px',\r\n background: req.status >= 200 && req.status < 300 ? '#10B98120' : '#EF444420',\r\n color: req.status >= 200 && req.status < 300 ? '#10B981' : '#EF4444',\r\n borderRadius: 4,\r\n },\r\n }, req.status || 'ERR'),\r\n React.createElement('span', { \r\n key: 'path',\r\n style: { fontSize: 12, color: '#fff', overflow: 'hidden', textOverflow: 'ellipsis' } \r\n }, new URL(req.url, 'http://localhost').pathname),\r\n ]),\r\n React.createElement('div', { key: 'info', style: { fontSize: 11, color: '#888', marginTop: 4 } },\r\n `${req.duration}ms • ${formatBytes(req.size)}`\r\n ),\r\n ])\r\n )\r\n );\r\n\r\n case 'performance':\r\n return React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 8 } },\r\n data.performance.length === 0\r\n ? React.createElement('div', { style: { color: '#666', textAlign: 'center', padding: 20 } }, 'Collecting metrics...')\r\n : data.performance.map((metric, i) =>\r\n React.createElement('div', {\r\n key: i,\r\n style: {\r\n padding: 12,\r\n background: '#111',\r\n borderRadius: 8,\r\n border: '1px solid #222',\r\n display: 'flex',\r\n justifyContent: 'space-between',\r\n alignItems: 'center',\r\n },\r\n }, [\r\n React.createElement('span', { key: 'name', style: { fontWeight: 600 } }, metric.name),\r\n React.createElement('div', { key: 'value', style: { display: 'flex', alignItems: 'center', gap: 8 } }, [\r\n React.createElement('span', { key: 'num' }, \r\n metric.name === 'CLS' ? metric.value.toFixed(3) : `${Math.round(metric.value)}ms`\r\n ),\r\n React.createElement('span', {\r\n key: 'rating',\r\n style: {\r\n width: 8,\r\n height: 8,\r\n borderRadius: '50%',\r\n background: metric.rating === 'good' ? '#10B981' : \r\n metric.rating === 'needs-improvement' ? '#F59E0B' : '#EF4444',\r\n },\r\n }),\r\n ]),\r\n ])\r\n )\r\n );\r\n\r\n case 'console':\r\n return React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 4 } },\r\n data.logs.length === 0\r\n ? React.createElement('div', { style: { color: '#666', textAlign: 'center', padding: 20 } }, 'No logs yet')\r\n : data.logs.map((log, i) =>\r\n React.createElement('div', {\r\n key: i,\r\n style: {\r\n padding: '8px 12px',\r\n background: log.level === 'error' ? '#EF444410' : \r\n log.level === 'warn' ? '#F59E0B10' : '#111',\r\n borderRadius: 6,\r\n fontSize: 12,\r\n fontFamily: 'monospace',\r\n color: log.level === 'error' ? '#EF4444' : \r\n log.level === 'warn' ? '#F59E0B' : '#888',\r\n },\r\n }, [\r\n React.createElement('span', { key: 'time', style: { color: '#444', marginRight: 8 } },\r\n new Date(log.timestamp).toLocaleTimeString()\r\n ),\r\n log.message,\r\n ])\r\n )\r\n );\r\n\r\n default:\r\n return React.createElement('div', {}, 'Unknown tab');\r\n }\r\n}\r\n\r\nfunction formatBytes(bytes: number): string {\r\n if (bytes === 0) return '0 B';\r\n const k = 1024;\r\n const sizes = ['B', 'KB', 'MB'];\r\n const i = Math.floor(Math.log(bytes) / Math.log(k));\r\n return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];\r\n}\r\n\r\n// ============================================================================\r\n// Exports\r\n// ============================================================================\r\n\r\nexport default {\r\n devtools,\r\n DevToolsOverlay,\r\n initPerformanceMonitoring,\r\n initNetworkInterceptor,\r\n};\r\n","/**\r\n * FlexiReact v2 - Main Entry Point\r\n * A modern React framework with RSC, SSG, Islands, and more\r\n */\r\n\r\n// Types\r\nexport type { FlexiConfig, Route, RouteType as RouteTypeEnum, PageProps, LayoutProps } from './types.js';\r\n\r\n// Core exports\r\nexport { loadConfig, defaultConfig, resolvePaths } from './config.js';\r\nexport { createRequestContext, useRequest, useParams, useQuery, usePathname } from './context.js';\r\nexport * from './utils.js';\r\n\r\n// Router\r\nexport { buildRouteTree, matchRoute, findRouteLayouts, RouteType } from './router/index.js';\r\n\r\n// Render\r\nexport { renderPage, renderPageStream, streamToResponse, renderError, renderLoading } from './render/index.js';\r\n\r\n// Server\r\nimport { createServer } from './server/index.js';\r\nexport { createServer };\r\n\r\n// Build\r\nexport { build, buildDev, BuildMode } from './build/index.js';\r\n\r\n// SSG\r\nexport { generateStaticSite, SSGResult, ISRManager } from './ssg/index.js';\r\n\r\n// RSC\r\nexport { \r\n processServerComponent, \r\n createClientReference, \r\n serializeRSCPayload,\r\n createServerAction,\r\n handleServerAction,\r\n ServerBoundary,\r\n ClientBoundary,\r\n RSC_CONTENT_TYPE \r\n} from './rsc/index.js';\r\n\r\n// Islands\r\nexport { \r\n Island, \r\n createIsland, \r\n createLazyIsland,\r\n getRegisteredIslands,\r\n generateHydrationScript,\r\n generateAdvancedHydrationScript,\r\n LoadStrategy \r\n} from './islands/index.js';\r\n\r\n// Middleware\r\nexport { \r\n MiddlewareRequest, \r\n MiddlewareResponse, \r\n loadMiddleware, \r\n runMiddleware,\r\n composeMiddleware,\r\n middlewares \r\n} from './middleware/index.js';\r\n\r\n// Plugins\r\nexport { \r\n PluginManager, \r\n PluginHooks, \r\n pluginManager, \r\n loadPlugins, \r\n definePlugin,\r\n builtinPlugins \r\n} from './plugins/index.js';\r\n\r\n// Edge Runtime\r\nexport {\r\n // Runtime\r\n detectRuntime,\r\n getRuntimeCapabilities,\r\n edgeRuntimeInfo,\r\n // Fetch\r\n FlexiRequest,\r\n FlexiResponse,\r\n FlexiHeaders,\r\n // Handler\r\n createEdgeApp,\r\n // Cache\r\n smartCache,\r\n initCache,\r\n cacheFunction,\r\n unstable_cache,\r\n revalidateTag,\r\n revalidatePath,\r\n reactCache,\r\n // PPR\r\n dynamic,\r\n staticComponent,\r\n PPRBoundary,\r\n PPRShell,\r\n prerenderWithPPR,\r\n streamPPR,\r\n pprFetch,\r\n PPRLoading,\r\n experimental_ppr,\r\n // Default exports\r\n createApp\r\n} from './edge/index.js';\r\nexport type {\r\n RuntimeEnvironment,\r\n RuntimeCapabilities,\r\n EdgeContext,\r\n EdgeHandler,\r\n EdgeMiddleware,\r\n EdgeAppConfig,\r\n CacheEntry,\r\n CacheOptions,\r\n PPRConfig,\r\n PPRRenderResult,\r\n PPRPageConfig,\r\n GenerateStaticParams\r\n} from './edge/index.js';\r\n\r\n// Font Optimization\r\nexport {\r\n createFont,\r\n googleFont,\r\n localFont,\r\n generateFontCSS,\r\n generateFontPreloadTags,\r\n handleFontRequest,\r\n fonts,\r\n googleFonts\r\n} from './font/index.js';\r\nexport type { FontConfig, FontResult } from './font/index.js';\r\n\r\n// Metadata API\r\nexport {\r\n generateMetadataTags,\r\n mergeMetadata,\r\n generateJsonLd,\r\n jsonLd\r\n} from './metadata/index.js';\r\nexport type { \r\n Metadata, \r\n OpenGraph, \r\n Twitter, \r\n Icons, \r\n Robots, \r\n Viewport,\r\n Author\r\n} from './metadata/index.js';\r\n\r\n// Image Optimization\r\nexport {\r\n Image,\r\n createImageComponent,\r\n handleImageOptimization,\r\n generateBlurPlaceholder,\r\n getImageDimensions,\r\n generateSrcSet,\r\n imageLoaders,\r\n defaultImageConfig\r\n} from './image/index.js';\r\nexport type { ImageProps, ImageConfig, ImageLoader } from './image/index.js';\r\n\r\n// Server Actions\r\nexport {\r\n serverAction,\r\n registerAction,\r\n getAction,\r\n executeAction,\r\n callServerAction,\r\n formAction,\r\n createFormState,\r\n bindArgs,\r\n useActionContext\r\n} from './actions/index.js';\r\nexport type { ActionContext, ActionResult, ServerActionFunction } from './actions/index.js';\r\n\r\n// Server Helpers\r\nexport {\r\n // Response helpers\r\n redirect,\r\n notFound,\r\n json,\r\n html,\r\n text,\r\n // Error classes\r\n RedirectError,\r\n NotFoundError,\r\n // Cookies API\r\n cookies,\r\n // Headers API\r\n headers,\r\n // Request helpers\r\n parseJson,\r\n parseFormData,\r\n parseSearchParams,\r\n getMethod,\r\n getPathname,\r\n isMethod\r\n} from './helpers.js';\r\nexport type { CookieOptions } from './helpers.js';\r\n\r\n// DevTools\r\nexport {\r\n devtools,\r\n DevToolsOverlay,\r\n initPerformanceMonitoring,\r\n initNetworkInterceptor\r\n} from './devtools/index.js';\r\n\r\n// Version\r\nexport const VERSION = '3.0.0';\r\n\r\n// Default export\r\nexport default {\r\n VERSION,\r\n createServer\r\n};\r\n"],"mappings":";AAKA,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAGvB,IAAM,gBAAgB;AAAA;AAAA,EAE3B,UAAU;AAAA,EACV,YAAY;AAAA,EACZ,WAAW;AAAA,EACX,QAAQ;AAAA;AAAA,EAGR,OAAO;AAAA,IACL,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,WAAW;AAAA,IACX,WAAW;AAAA,EACb;AAAA;AAAA,EAGA,QAAQ;AAAA,IACN,MAAM;AAAA,IACN,MAAM;AAAA,EACR;AAAA;AAAA,EAGA,KAAK;AAAA,IACH,SAAS;AAAA,IACT,OAAO,CAAC;AAAA,EACV;AAAA;AAAA,EAGA,SAAS;AAAA,IACP,SAAS;AAAA,EACX;AAAA;AAAA,EAGA,KAAK;AAAA,IACH,SAAS;AAAA,EACX;AAAA;AAAA,EAGA,SAAS,CAAC;AAAA;AAAA,EAGV,QAAQ,CAAC;AAAA;AAAA,EAGT,SAAS,CAAC;AAAA;AAAA,EAGV,SAAS;AACX;AAOA,eAAsB,WAAW,aAAqB;AAEpD,QAAM,eAAe,KAAK,KAAK,aAAa,sBAAsB;AAClE,QAAM,eAAe,KAAK,KAAK,aAAa,sBAAsB;AAClE,QAAM,aAAa,GAAG,WAAW,YAAY,IAAI,eAAe;AAEhE,MAAI,aAAa,CAAC;AAElB,MAAI,GAAG,WAAW,UAAU,GAAG;AAC7B,QAAI;AACF,YAAM,YAAY,cAAc,UAAU,EAAE;AAC5C,YAAM,SAAS,MAAM,OAAO,GAAG,SAAS,MAAM,KAAK,IAAI,CAAC;AACxD,mBAAa,OAAO,WAAW;AAAA,IACjC,SAAS,OAAY;AACnB,cAAQ,KAAK,8CAA8C,MAAM,OA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1C,MAAI,UAAU,EAAG,QAAO;AACxB,QAAM,IAAI;AACV,QAAM,QAAQ,CAAC,KAAK,MAAM,IAAI;AAC9B,QAAM,IAAI,KAAK,MAAM,KAAK,IAAI,KAAK,IAAI,KAAK,IAAI,CAAC,CAAC;AAClD,SAAO,YAAY,QAAQ,KAAK,IAAI,GAAG,CAAC,GAAG,QAAQ,CAAC,CAAC,IAAI,MAAM,MAAM,CAAC;AACxE;;;ACraO,IAAM,UAAU;AAGvB,IAAO,eAAQ;AAAA,EACb;AAAA,EACA;AACF;","names":["cookies","context","fs","path","fs","path","path","fs","React","React","isClientComponent","content","fs","path","pathToFileURL","fs","path","pathToFileURL","cookies","middlewares","headers","data","fs","path","pathToFileURL","html","headers","React","renderToString","crypto","formatTime","path","headers","cookies","context","React","path","fs","crypto","Image","fs","path","crypto","fonts","__filename","__dirname","path","pathToFileURL","fs","context","isClientComponent","html","fs","path","fileURLToPath","__filename","fileURLToPath","__dirname","path","build","fs","fs","path","path","html","fs","redirect","React","renderToString","context","handleServerAction","runtime","headers","html","text","runtime","path","cache","notFound","context","runMiddleware","matchRoute","middlewares","path","headers","http","React","renderToString","React","renderToString","html","escapeHtml","React","formatBytes"]}
1
+ {"version":3,"sources":["../../core/config.ts","../../core/context.ts","../../core/utils.ts","../../core/router/index.ts","../../core/render/index.ts","../../core/server/index.ts","../../core/middleware/index.ts","../../core/plugins/index.ts","../../core/islands/index.ts","../../core/logger.ts","../../core/helpers.ts","../../core/actions/index.ts","../../core/image/index.ts","../../core/font/index.ts","../../core/build/index.ts","../../core/ssg/index.ts","../../core/rsc/index.ts","../../core/edge/runtime.ts","../../core/edge/fetch-polyfill.ts","../../core/edge/cache.ts","../../core/edge/handler.ts","../../core/edge/ppr.ts","../../core/metadata/index.ts","../../core/index.ts","../../core/hooks/index.ts","../../core/client/Link.tsx","../../core/devtools/index.ts"],"sourcesContent":["/**\r\n * FlexiReact Configuration System\r\n * Handles loading and merging of configuration from flexireact.config.js\r\n */\r\n\r\nimport fs from 'fs';\r\nimport path from 'path';\r\nimport { pathToFileURL } from 'url';\r\n\r\n// Default configuration\r\nexport const defaultConfig = {\r\n // Directories\r\n pagesDir: 'pages',\r\n layoutsDir: 'layouts',\r\n publicDir: 'public',\r\n outDir: '.flexi',\r\n \r\n // Build options\r\n build: {\r\n target: 'es2022',\r\n minify: true,\r\n sourcemap: true,\r\n splitting: true\r\n },\r\n \r\n // Server options\r\n server: {\r\n port: 3000,\r\n host: 'localhost'\r\n },\r\n \r\n // SSG options\r\n ssg: {\r\n enabled: false,\r\n paths: []\r\n },\r\n \r\n // Islands (partial hydration)\r\n islands: {\r\n enabled: true\r\n },\r\n \r\n // RSC options\r\n rsc: {\r\n enabled: true\r\n },\r\n \r\n // Plugins\r\n plugins: [],\r\n \r\n // Styles (CSS files to include)\r\n styles: [],\r\n \r\n // Scripts (JS files to include)\r\n scripts: [],\r\n \r\n // Favicon path\r\n favicon: null\r\n};\r\n\r\n/**\r\n * Loads configuration from the project root\r\n * @param {string} projectRoot - Path to project root\r\n * @returns {Object} Merged configuration\r\n */\r\nexport async function loadConfig(projectRoot: string) {\r\n // Try .ts first, then .js\r\n const configPathTs = path.join(projectRoot, 'flexireact.config.ts');\r\n const configPathJs = path.join(projectRoot, 'flexireact.config.js');\r\n const configPath = fs.existsSync(configPathTs) ? configPathTs : configPathJs;\r\n \r\n let userConfig = {};\r\n \r\n if (fs.existsSync(configPath)) {\r\n try {\r\n const configUrl = pathToFileURL(configPath).href;\r\n const module = await import(`${configUrl}?t=${Date.now()}`);\r\n userConfig = module.default || module;\r\n } catch (error: any) {\r\n console.warn('Warning: Failed to load flexireact config:', error.message);\r\n }\r\n }\r\n \r\n // Deep merge configs\r\n return deepMerge(defaultConfig, userConfig);\r\n}\r\n\r\n/**\r\n * Deep merge two objects\r\n */\r\nfunction deepMerge(target, source) {\r\n const result = { ...target };\r\n \r\n for (const key in source) {\r\n if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) {\r\n result[key] = deepMerge(target[key] || {}, source[key]);\r\n } else {\r\n result[key] = source[key];\r\n }\r\n }\r\n \r\n return result;\r\n}\r\n\r\n/**\r\n * Resolves all paths in config relative to project root\r\n */\r\nexport function resolvePaths(config, projectRoot) {\r\n return {\r\n ...config,\r\n pagesDir: path.resolve(projectRoot, config.pagesDir),\r\n layoutsDir: path.resolve(projectRoot, config.layoutsDir),\r\n publicDir: path.resolve(projectRoot, config.publicDir),\r\n outDir: path.resolve(projectRoot, config.outDir)\r\n };\r\n}\r\n","/**\r\n * FlexiReact Context System\r\n * Provides request context and shared state for SSR/RSC\r\n */\r\n\r\nimport React from 'react';\r\n\r\n// Server-side request context\r\nexport const RequestContext = React.createContext(null);\r\n\r\n// Route context for nested routes\r\nexport const RouteContext = React.createContext(null);\r\n\r\n// Layout context\r\nexport const LayoutContext = React.createContext(null);\r\n\r\n/**\r\n * Creates a request context value\r\n */\r\nexport function createRequestContext(req, res, params = {}, query = {}) {\r\n return {\r\n req,\r\n res,\r\n params,\r\n query,\r\n url: req.url,\r\n method: req.method,\r\n headers: req.headers,\r\n cookies: parseCookies(req.headers.cookie || '')\r\n };\r\n}\r\n\r\n/**\r\n * Parse cookies from header string\r\n */\r\nfunction parseCookies(cookieHeader) {\r\n const cookies = {};\r\n if (!cookieHeader) return cookies;\r\n \r\n cookieHeader.split(';').forEach(cookie => {\r\n const [name, ...rest] = cookie.split('=');\r\n if (name) {\r\n cookies[name.trim()] = rest.join('=').trim();\r\n }\r\n });\r\n \r\n return cookies;\r\n}\r\n\r\n/**\r\n * Hook to access request context (server-side only)\r\n */\r\nexport function useRequest() {\r\n const context = React.useContext(RequestContext);\r\n if (!context) {\r\n throw new Error('useRequest must be used within a RequestContext provider');\r\n }\r\n return context;\r\n}\r\n\r\n/**\r\n * Hook to access route params\r\n */\r\nexport function useParams() {\r\n const context = React.useContext(RouteContext);\r\n return context?.params || {};\r\n}\r\n\r\n/**\r\n * Hook to access query parameters\r\n */\r\nexport function useQuery() {\r\n const context = React.useContext(RouteContext);\r\n return context?.query || {};\r\n}\r\n\r\n/**\r\n * Hook to access current pathname\r\n */\r\nexport function usePathname() {\r\n const context = React.useContext(RouteContext);\r\n return context?.pathname || '/';\r\n}\r\n","/**\r\n * FlexiReact Utility Functions\r\n */\r\n\r\nimport fs from 'fs';\r\nimport path from 'path';\r\nimport crypto from 'crypto';\r\n\r\n/**\r\n * Generates a unique hash for cache busting\r\n */\r\nexport function generateHash(content) {\r\n return crypto.createHash('md5').update(content).digest('hex').slice(0, 8);\r\n}\r\n\r\n/**\r\n * Escapes HTML special characters\r\n */\r\nexport function escapeHtml(str) {\r\n const htmlEntities = {\r\n '&': '&amp;',\r\n '<': '&lt;',\r\n '>': '&gt;',\r\n '\"': '&quot;',\r\n \"'\": '&#39;'\r\n };\r\n return String(str).replace(/[&<>\"']/g, char => htmlEntities[char]);\r\n}\r\n\r\n/**\r\n * Recursively finds all files matching a pattern\r\n */\r\nexport function findFiles(dir, pattern, files = []) {\r\n if (!fs.existsSync(dir)) return files;\r\n \r\n const entries = fs.readdirSync(dir, { withFileTypes: true });\r\n \r\n for (const entry of entries) {\r\n const fullPath = path.join(dir, entry.name);\r\n \r\n if (entry.isDirectory()) {\r\n findFiles(fullPath, pattern, files);\r\n } else if (pattern.test(entry.name)) {\r\n files.push(fullPath);\r\n }\r\n }\r\n \r\n return files;\r\n}\r\n\r\n/**\r\n * Ensures a directory exists\r\n */\r\nexport function ensureDir(dir) {\r\n if (!fs.existsSync(dir)) {\r\n fs.mkdirSync(dir, { recursive: true });\r\n }\r\n}\r\n\r\n/**\r\n * Cleans a directory\r\n */\r\nexport function cleanDir(dir) {\r\n if (fs.existsSync(dir)) {\r\n fs.rmSync(dir, { recursive: true, force: true });\r\n }\r\n fs.mkdirSync(dir, { recursive: true });\r\n}\r\n\r\n/**\r\n * Copies a directory recursively\r\n */\r\nexport function copyDir(src, dest) {\r\n ensureDir(dest);\r\n \r\n const entries = fs.readdirSync(src, { withFileTypes: true });\r\n \r\n for (const entry of entries) {\r\n const srcPath = path.join(src, entry.name);\r\n const destPath = path.join(dest, entry.name);\r\n \r\n if (entry.isDirectory()) {\r\n copyDir(srcPath, destPath);\r\n } else {\r\n fs.copyFileSync(srcPath, destPath);\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Debounce function for file watching\r\n */\r\nexport function debounce(fn, delay) {\r\n let timeout;\r\n return (...args) => {\r\n clearTimeout(timeout);\r\n timeout = setTimeout(() => fn(...args), delay);\r\n };\r\n}\r\n\r\n/**\r\n * Formats bytes to human readable string\r\n */\r\nexport function formatBytes(bytes) {\r\n if (bytes === 0) return '0 B';\r\n const k = 1024;\r\n const sizes = ['B', 'KB', 'MB', 'GB'];\r\n const i = Math.floor(Math.log(bytes) / Math.log(k));\r\n return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];\r\n}\r\n\r\n/**\r\n * Formats milliseconds to human readable string\r\n */\r\nexport function formatTime(ms) {\r\n if (ms < 1000) return `${ms}ms`;\r\n return `${(ms / 1000).toFixed(2)}s`;\r\n}\r\n\r\n/**\r\n * Creates a deferred promise\r\n */\r\nexport function createDeferred() {\r\n let resolve, reject;\r\n const promise = new Promise((res, rej) => {\r\n resolve = res;\r\n reject = rej;\r\n });\r\n return { promise, resolve, reject };\r\n}\r\n\r\n/**\r\n * Sleep utility\r\n */\r\nexport function sleep(ms) {\r\n return new Promise(resolve => setTimeout(resolve, ms));\r\n}\r\n\r\n/**\r\n * Check if a file is a server component (has 'use server' directive)\r\n */\r\nexport function isServerComponent(filePath) {\r\n try {\r\n const content = fs.readFileSync(filePath, 'utf-8');\r\n const firstLine = content.split('\\n')[0].trim();\r\n return firstLine === \"'use server'\" || firstLine === '\"use server\"';\r\n } catch {\r\n return false;\r\n }\r\n}\r\n\r\n/**\r\n * Check if a file is a client component (has 'use client' directive)\r\n */\r\nexport function isClientComponent(filePath) {\r\n try {\r\n const content = fs.readFileSync(filePath, 'utf-8');\r\n const firstLine = content.split('\\n')[0].trim();\r\n return firstLine === \"'use client'\" || firstLine === '\"use client\"';\r\n } catch {\r\n return false;\r\n }\r\n}\r\n\r\n/**\r\n * Check if a component is an island (has 'use island' directive)\r\n */\r\nexport function isIsland(filePath) {\r\n try {\r\n const content = fs.readFileSync(filePath, 'utf-8');\r\n const firstLine = content.split('\\n')[0].trim();\r\n return firstLine === \"'use island'\" || firstLine === '\"use island\"';\r\n } catch {\r\n return false;\r\n }\r\n}\r\n","/**\r\n * FlexiReact Router v2\r\n * Advanced file-based routing with nested routes, loading, and error boundaries\r\n * \r\n * Supports multiple routing conventions:\r\n * - pages/ : Traditional file-based routing (index.tsx, about.tsx)\r\n * - app/ : Next.js style App Router (page.tsx, layout.tsx)\r\n * - routes/ : FlexiReact v2 routes directory (home.tsx → /, [slug].tsx → /:slug)\r\n */\r\n\r\nimport fs from 'fs';\r\nimport path from 'path';\r\nimport { isServerComponent, isClientComponent, isIsland } from '../utils.js';\r\n\r\n/**\r\n * Route types\r\n */\r\nexport const RouteType = {\r\n PAGE: 'page',\r\n API: 'api',\r\n LAYOUT: 'layout',\r\n LOADING: 'loading',\r\n ERROR: 'error',\r\n NOT_FOUND: 'not-found'\r\n};\r\n\r\n/**\r\n * Builds the complete route tree from all routing directories\r\n */\r\nexport function buildRouteTree(pagesDir, layoutsDir, appDir = null, routesDir = null) {\r\n const projectRoot = path.dirname(pagesDir);\r\n \r\n const routes: {\r\n pages: any[];\r\n api: any[];\r\n layouts: Map<any, any>;\r\n tree: Record<string, any>;\r\n appRoutes: any[];\r\n flexiRoutes: any[];\r\n rootLayout?: string;\r\n } = {\r\n pages: [],\r\n api: [],\r\n layouts: new Map(),\r\n tree: {},\r\n appRoutes: [], // Next.js style app router routes\r\n flexiRoutes: [] // FlexiReact v2 routes/ directory\r\n };\r\n\r\n // 1. Scan routes/ directory (FlexiReact v2 - priority)\r\n const routesDirPath = routesDir || path.join(projectRoot, 'routes');\r\n if (fs.existsSync(routesDirPath)) {\r\n scanRoutesDirectory(routesDirPath, routesDirPath, routes);\r\n }\r\n\r\n // 2. Scan app/ directory (Next.js style App Router)\r\n const appDirPath = appDir || path.join(projectRoot, 'app');\r\n if (fs.existsSync(appDirPath)) {\r\n scanAppDirectory(appDirPath, appDirPath, routes);\r\n }\r\n\r\n // 3. Scan pages/ directory (traditional routing - fallback)\r\n if (fs.existsSync(pagesDir)) {\r\n scanDirectory(pagesDir, pagesDir, routes);\r\n }\r\n \r\n // 4. Scan layouts/ directory\r\n if (fs.existsSync(layoutsDir)) {\r\n scanLayouts(layoutsDir, routes.layouts);\r\n }\r\n\r\n // 5. Check for root layout in app/ directory\r\n const rootLayoutPath = path.join(appDirPath, 'layout.tsx');\r\n const rootLayoutPathJs = path.join(appDirPath, 'layout.jsx');\r\n if (fs.existsSync(rootLayoutPath)) {\r\n routes.rootLayout = rootLayoutPath;\r\n } else if (fs.existsSync(rootLayoutPathJs)) {\r\n routes.rootLayout = rootLayoutPathJs;\r\n }\r\n\r\n // Build route tree for nested routes\r\n routes.tree = buildTree([...routes.flexiRoutes, ...routes.appRoutes, ...routes.pages]);\r\n\r\n return routes;\r\n}\r\n\r\n/**\r\n * Scans routes/ directory for FlexiReact v2 style routing\r\n * \r\n * Convention:\r\n * - home.tsx → /\r\n * - about.tsx → /about\r\n * - blog/index.tsx → /blog\r\n * - blog/[slug].tsx → /blog/:slug\r\n * - (public)/home.tsx → / (route group, not in URL)\r\n * - api/hello.ts → /api/hello (API route)\r\n * - dashboard/layout.tsx → layout for /dashboard/*\r\n */\r\nfunction scanRoutesDirectory(baseDir, currentDir, routes, parentSegments = [], parentLayout = null, parentMiddleware = null) {\r\n const entries = fs.readdirSync(currentDir, { withFileTypes: true });\r\n \r\n // Find special files in current directory\r\n let layoutFile = null;\r\n let loadingFile = null;\r\n let errorFile = null;\r\n let middlewareFile = null;\r\n \r\n for (const entry of entries) {\r\n if (entry.isFile()) {\r\n const name = entry.name.replace(/\\.(jsx|js|tsx|ts)$/, '');\r\n const fullPath = path.join(currentDir, entry.name);\r\n const ext = path.extname(entry.name);\r\n \r\n // Special files\r\n if (name === 'layout') layoutFile = fullPath;\r\n if (name === 'loading') loadingFile = fullPath;\r\n if (name === 'error') errorFile = fullPath;\r\n if (name === '_middleware' || name === 'middleware') middlewareFile = fullPath;\r\n \r\n // Skip special files and non-route files\r\n if (['layout', 'loading', 'error', 'not-found', '_middleware', 'middleware'].includes(name)) continue;\r\n if (!['.tsx', '.jsx', '.ts', '.js'].includes(ext)) continue;\r\n \r\n // API routes (in api/ folder or .ts/.js files in api/)\r\n const relativePath = path.relative(baseDir, currentDir);\r\n const isApiRoute = relativePath.startsWith('api') || relativePath.startsWith('api/');\r\n \r\n if (isApiRoute && ['.ts', '.js'].includes(ext)) {\r\n const apiPath = '/' + [...parentSegments, name === 'index' ? '' : name].filter(Boolean).join('/');\r\n routes.api.push({\r\n type: RouteType.API,\r\n path: apiPath.replace(/\\/+/g, '/') || '/',\r\n filePath: fullPath,\r\n pattern: createRoutePattern(apiPath),\r\n segments: [...parentSegments, name === 'index' ? '' : name].filter(Boolean)\r\n });\r\n continue;\r\n }\r\n \r\n // Page routes\r\n if (['.tsx', '.jsx'].includes(ext)) {\r\n let routePath;\r\n \r\n // home.tsx → /\r\n if (name === 'home' && parentSegments.length === 0) {\r\n routePath = '/';\r\n }\r\n // index.tsx → parent path\r\n else if (name === 'index') {\r\n routePath = '/' + parentSegments.join('/') || '/';\r\n }\r\n // [param].tsx → /:param\r\n else if (name.startsWith('[') && name.endsWith(']')) {\r\n const paramName = name.slice(1, -1);\r\n // Handle catch-all [...slug]\r\n if (paramName.startsWith('...')) {\r\n routePath = '/' + [...parentSegments, '*' + paramName.slice(3)].join('/');\r\n } else {\r\n routePath = '/' + [...parentSegments, ':' + paramName].join('/');\r\n }\r\n }\r\n // regular.tsx → /regular\r\n else {\r\n routePath = '/' + [...parentSegments, name].join('/');\r\n }\r\n \r\n routes.flexiRoutes.push({\r\n type: RouteType.PAGE,\r\n path: routePath.replace(/\\/+/g, '/'),\r\n filePath: fullPath,\r\n pattern: createRoutePattern(routePath),\r\n segments: routePath.split('/').filter(Boolean),\r\n layout: layoutFile || parentLayout,\r\n loading: loadingFile,\r\n error: errorFile,\r\n middleware: middlewareFile || parentMiddleware,\r\n isFlexiRouter: true,\r\n isServerComponent: isServerComponent(fullPath),\r\n isClientComponent: isClientComponent(fullPath),\r\n isIsland: isIsland(fullPath)\r\n });\r\n }\r\n }\r\n }\r\n \r\n // Recursively scan subdirectories\r\n for (const entry of entries) {\r\n if (entry.isDirectory()) {\r\n const fullPath = path.join(currentDir, entry.name);\r\n const dirName = entry.name;\r\n \r\n // Skip special directories\r\n if (dirName.startsWith('_') || dirName.startsWith('.')) continue;\r\n \r\n // Handle route groups (parentheses) - don't add to URL\r\n const isGroup = dirName.startsWith('(') && dirName.endsWith(')');\r\n \r\n // Handle dynamic segments [param]\r\n let segmentName = dirName;\r\n if (dirName.startsWith('[') && dirName.endsWith(']')) {\r\n const paramName = dirName.slice(1, -1);\r\n if (paramName.startsWith('...')) {\r\n segmentName = '*' + paramName.slice(3);\r\n } else {\r\n segmentName = ':' + paramName;\r\n }\r\n }\r\n \r\n const newSegments = isGroup ? parentSegments : [...parentSegments, segmentName];\r\n const newLayout = layoutFile || parentLayout;\r\n const newMiddleware = middlewareFile || parentMiddleware;\r\n \r\n scanRoutesDirectory(baseDir, fullPath, routes, newSegments, newLayout, newMiddleware);\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Scans app directory for Next.js style routing\r\n * Supports: page.tsx, layout.tsx, loading.tsx, error.tsx, not-found.tsx\r\n */\r\nfunction scanAppDirectory(baseDir, currentDir, routes, parentSegments = [], parentLayout = null, parentMiddleware = null) {\r\n const entries = fs.readdirSync(currentDir, { withFileTypes: true });\r\n \r\n // Find special files in current directory\r\n const specialFiles: Record<string, string | null> = {\r\n page: null,\r\n layout: null,\r\n loading: null,\r\n error: null,\r\n notFound: null,\r\n template: null,\r\n middleware: null\r\n };\r\n\r\n for (const entry of entries) {\r\n if (entry.isFile()) {\r\n const name = entry.name.replace(/\\.(jsx|js|tsx|ts)$/, '');\r\n const fullPath = path.join(currentDir, entry.name);\r\n \r\n if (name === 'page') specialFiles.page = fullPath;\r\n if (name === 'layout') specialFiles.layout = fullPath;\r\n if (name === 'loading') specialFiles.loading = fullPath;\r\n if (name === 'error') specialFiles.error = fullPath;\r\n if (name === 'not-found') specialFiles.notFound = fullPath;\r\n if (name === 'template') specialFiles.template = fullPath;\r\n if (name === 'middleware' || name === '_middleware') specialFiles.middleware = fullPath;\r\n }\r\n }\r\n\r\n // If there's a page.tsx, create a route\r\n if (specialFiles.page) {\r\n const routePath = '/' + parentSegments.join('/') || '/';\r\n \r\n routes.appRoutes.push({\r\n type: RouteType.PAGE,\r\n path: routePath.replace(/\\/+/g, '/'),\r\n filePath: specialFiles.page,\r\n pattern: createRoutePattern(routePath),\r\n segments: parentSegments,\r\n layout: specialFiles.layout || parentLayout,\r\n loading: specialFiles.loading,\r\n error: specialFiles.error,\r\n notFound: specialFiles.notFound,\r\n template: specialFiles.template,\r\n middleware: specialFiles.middleware || parentMiddleware,\r\n isAppRouter: true,\r\n isServerComponent: isServerComponent(specialFiles.page),\r\n isClientComponent: isClientComponent(specialFiles.page),\r\n isIsland: isIsland(specialFiles.page)\r\n });\r\n }\r\n\r\n // Recursively scan subdirectories\r\n for (const entry of entries) {\r\n if (entry.isDirectory()) {\r\n const fullPath = path.join(currentDir, entry.name);\r\n \r\n // Handle route groups (parentheses) - don't add to URL\r\n const isGroup = entry.name.startsWith('(') && entry.name.endsWith(')');\r\n \r\n // Handle dynamic segments [param]\r\n let segmentName = entry.name;\r\n if (entry.name.startsWith('[') && entry.name.endsWith(']')) {\r\n // Convert [param] to :param\r\n segmentName = ':' + entry.name.slice(1, -1);\r\n // Handle catch-all [...param]\r\n if (entry.name.startsWith('[...')) {\r\n segmentName = '*' + entry.name.slice(4, -1);\r\n }\r\n // Handle optional catch-all [[...param]]\r\n if (entry.name.startsWith('[[...')) {\r\n segmentName = '*' + entry.name.slice(5, -2);\r\n }\r\n }\r\n \r\n const newSegments = isGroup ? parentSegments : [...parentSegments, segmentName];\r\n const newLayout = specialFiles.layout || parentLayout;\r\n const newMiddleware = specialFiles.middleware || parentMiddleware;\r\n \r\n scanAppDirectory(baseDir, fullPath, routes, newSegments, newLayout, newMiddleware);\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Scans directory recursively for route files\r\n */\r\nfunction scanDirectory(baseDir, currentDir, routes, parentSegments = []) {\r\n const entries = fs.readdirSync(currentDir, { withFileTypes: true });\r\n \r\n // First, find special files in current directory\r\n const specialFiles = {\r\n layout: null,\r\n loading: null,\r\n error: null,\r\n notFound: null\r\n };\r\n\r\n for (const entry of entries) {\r\n if (entry.isFile()) {\r\n const name = entry.name.replace(/\\.(jsx|js|tsx|ts)$/, '');\r\n const fullPath = path.join(currentDir, entry.name);\r\n \r\n if (name === 'layout') specialFiles.layout = fullPath;\r\n if (name === 'loading') specialFiles.loading = fullPath;\r\n if (name === 'error') specialFiles.error = fullPath;\r\n if (name === 'not-found' || name === '404') specialFiles.notFound = fullPath;\r\n }\r\n }\r\n\r\n for (const entry of entries) {\r\n const fullPath = path.join(currentDir, entry.name);\r\n const relativePath = path.relative(baseDir, fullPath);\r\n\r\n if (entry.isDirectory()) {\r\n // Handle route groups (parentheses)\r\n const isGroup = entry.name.startsWith('(') && entry.name.endsWith(')');\r\n const newSegments = isGroup ? parentSegments : [...parentSegments, entry.name];\r\n \r\n scanDirectory(baseDir, fullPath, routes, newSegments);\r\n } else if (entry.isFile()) {\r\n const ext = path.extname(entry.name);\r\n const baseName = path.basename(entry.name, ext);\r\n \r\n // Skip special files (already processed)\r\n if (['layout', 'loading', 'error', 'not-found', '404'].includes(baseName)) {\r\n continue;\r\n }\r\n \r\n if (['.jsx', '.js', '.tsx', '.ts'].includes(ext)) {\r\n const isApi = relativePath.startsWith('api' + path.sep) || relativePath.startsWith('api/');\r\n \r\n if (isApi && ['.js', '.ts'].includes(ext)) {\r\n routes.api.push(createRoute(fullPath, baseDir, specialFiles, RouteType.API));\r\n } else if (!isApi && ['.jsx', '.tsx'].includes(ext)) {\r\n routes.pages.push(createRoute(fullPath, baseDir, specialFiles, RouteType.PAGE));\r\n }\r\n }\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Creates a route object from file path\r\n */\r\nfunction createRoute(filePath, baseDir, specialFiles, type) {\r\n const relativePath = path.relative(baseDir, filePath);\r\n const routePath = filePathToRoute(relativePath);\r\n \r\n return {\r\n type,\r\n path: routePath,\r\n filePath,\r\n pattern: createRoutePattern(routePath),\r\n segments: routePath.split('/').filter(Boolean),\r\n layout: specialFiles.layout,\r\n loading: specialFiles.loading,\r\n error: specialFiles.error,\r\n notFound: specialFiles.notFound,\r\n isServerComponent: isServerComponent(filePath),\r\n isClientComponent: isClientComponent(filePath),\r\n isIsland: isIsland(filePath)\r\n };\r\n}\r\n\r\n/**\r\n * Scans layouts directory\r\n */\r\nfunction scanLayouts(layoutsDir, layoutsMap) {\r\n const entries = fs.readdirSync(layoutsDir, { withFileTypes: true });\r\n \r\n for (const entry of entries) {\r\n if (entry.isFile() && /\\.(jsx|tsx)$/.test(entry.name)) {\r\n const name = entry.name.replace(/\\.(jsx|tsx)$/, '');\r\n layoutsMap.set(name, path.join(layoutsDir, entry.name));\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Converts file path to route path\r\n */\r\nfunction filePathToRoute(filePath) {\r\n let route = filePath.replace(/\\\\/g, '/');\r\n \r\n // Remove extension\r\n route = route.replace(/\\.(jsx|js|tsx|ts)$/, '');\r\n \r\n // Convert [param] to :param\r\n route = route.replace(/\\[\\.\\.\\.([^\\]]+)\\]/g, '*$1'); // Catch-all [...slug]\r\n route = route.replace(/\\[([^\\]]+)\\]/g, ':$1');\r\n \r\n // Handle index files\r\n if (route.endsWith('/index')) {\r\n route = route.slice(0, -6) || '/';\r\n } else if (route === 'index') {\r\n route = '/';\r\n }\r\n \r\n // Handle route groups - remove (groupName) from path\r\n route = route.replace(/\\/?\\([^)]+\\)\\/?/g, '/');\r\n \r\n // Ensure leading slash and clean up\r\n if (!route.startsWith('/')) {\r\n route = '/' + route;\r\n }\r\n route = route.replace(/\\/+/g, '/');\r\n \r\n return route;\r\n}\r\n\r\n/**\r\n * Creates regex pattern for route matching\r\n */\r\nfunction createRoutePattern(routePath) {\r\n let pattern = routePath\r\n .replace(/\\*[^/]*/g, '(.*)') // Catch-all\r\n .replace(/:[^/]+/g, '([^/]+)') // Dynamic segments\r\n .replace(/\\//g, '\\\\/');\r\n \r\n return new RegExp(`^${pattern}$`);\r\n}\r\n\r\n/**\r\n * Builds a tree structure for nested routes\r\n */\r\nfunction buildTree(routes) {\r\n const tree = { children: {}, routes: [] };\r\n \r\n for (const route of routes) {\r\n let current = tree;\r\n \r\n for (const segment of route.segments) {\r\n if (!current.children[segment]) {\r\n current.children[segment] = { children: {}, routes: [] };\r\n }\r\n current = current.children[segment];\r\n }\r\n \r\n current.routes.push(route);\r\n }\r\n \r\n return tree;\r\n}\r\n\r\n/**\r\n * Matches URL path against routes\r\n */\r\nexport function matchRoute(urlPath, routes) {\r\n const normalizedPath = urlPath === '' ? '/' : urlPath.split('?')[0];\r\n \r\n for (const route of routes) {\r\n const match = normalizedPath.match(route.pattern);\r\n \r\n if (match) {\r\n const params = extractParams(route.path, match);\r\n return { ...route, params };\r\n }\r\n }\r\n \r\n return null;\r\n}\r\n\r\n/**\r\n * Extracts parameters from route match\r\n */\r\nfunction extractParams(routePath, match) {\r\n const params = {};\r\n const paramNames = [];\r\n \r\n // Extract param names from route path\r\n const paramRegex = /:([^/]+)|\\*([^/]*)/g;\r\n let paramMatch;\r\n \r\n while ((paramMatch = paramRegex.exec(routePath)) !== null) {\r\n paramNames.push(paramMatch[1] || paramMatch[2] || 'splat');\r\n }\r\n \r\n paramNames.forEach((name, index) => {\r\n params[name] = match[index + 1];\r\n });\r\n \r\n return params;\r\n}\r\n\r\n/**\r\n * Finds all layouts that apply to a route\r\n */\r\nexport function findRouteLayouts(route, layoutsMap) {\r\n const layouts = [];\r\n \r\n // Check for segment-based layouts\r\n let currentPath = '';\r\n for (const segment of route.segments) {\r\n currentPath += '/' + segment;\r\n const layoutName = segment;\r\n \r\n if (layoutsMap.has(layoutName)) {\r\n layouts.push({\r\n name: layoutName,\r\n filePath: layoutsMap.get(layoutName)\r\n });\r\n }\r\n }\r\n \r\n // Check for route-specific layout\r\n if (route.layout) {\r\n layouts.push({\r\n name: 'route',\r\n filePath: route.layout\r\n });\r\n }\r\n \r\n // Check for root layout\r\n if (layoutsMap.has('root')) {\r\n layouts.unshift({\r\n name: 'root',\r\n filePath: layoutsMap.get('root')\r\n });\r\n }\r\n \r\n return layouts;\r\n}\r\n\r\nexport default {\r\n buildRouteTree,\r\n matchRoute,\r\n findRouteLayouts,\r\n RouteType\r\n};\r\n","/**\r\n * FlexiReact Render System v2\r\n * SSR with layouts, loading states, error boundaries, and islands\r\n */\r\n\r\nimport React from 'react';\r\nimport { renderToString, renderToPipeableStream } from 'react-dom/server';\r\nimport { escapeHtml } from '../utils.js';\r\n\r\n/**\r\n * Renders a page with all its layouts and wrappers\r\n */\r\nexport async function renderPage(options) {\r\n const {\r\n Component,\r\n props = {},\r\n layouts = [],\r\n loading = null,\r\n error = null,\r\n islands = [],\r\n title = 'FlexiReact App',\r\n meta = {},\r\n scripts = [],\r\n styles = [],\r\n favicon = null,\r\n isSSG = false,\r\n route = '/',\r\n needsHydration = false\r\n } = options;\r\n\r\n const renderStart = Date.now();\r\n\r\n try {\r\n // Build the component tree - start with the page component\r\n let element: any = React.createElement(Component, props);\r\n \r\n // Wrap with error boundary if error component exists\r\n if (error) {\r\n element = React.createElement(ErrorBoundaryWrapper as any, {\r\n fallback: error,\r\n children: element\r\n });\r\n }\r\n\r\n // Wrap with Suspense if loading component exists (for streaming/async)\r\n if (loading) {\r\n element = React.createElement(React.Suspense as any, {\r\n fallback: React.createElement(loading),\r\n children: element\r\n });\r\n }\r\n \r\n // Wrap with layouts (innermost to outermost)\r\n // Each layout receives children as a prop\r\n for (const layout of [...layouts].reverse()) {\r\n if (layout.Component) {\r\n const LayoutComponent = layout.Component;\r\n element = React.createElement(LayoutComponent, {\r\n ...layout.props\r\n }, element);\r\n }\r\n }\r\n\r\n // Render to string\r\n const content = renderToString(element);\r\n \r\n // Calculate render time\r\n const renderTime = Date.now() - renderStart;\r\n \r\n // Generate island hydration scripts\r\n const islandScripts = generateIslandScripts(islands);\r\n \r\n // Build full HTML document\r\n return buildHtmlDocument({\r\n content,\r\n title,\r\n meta,\r\n scripts: [...scripts, ...islandScripts],\r\n styles,\r\n favicon,\r\n props,\r\n isSSG,\r\n renderTime,\r\n route,\r\n isClientComponent: needsHydration\r\n });\r\n\r\n } catch (err) {\r\n console.error('Render Error:', err);\r\n throw err;\r\n }\r\n}\r\n\r\n/**\r\n * Streaming SSR with React 18\r\n * Renders the page progressively, sending HTML chunks as they become ready\r\n */\r\nexport async function renderPageStream(options: {\r\n Component: React.ComponentType<any>;\r\n props?: Record<string, any>;\r\n layouts?: Array<{ Component: React.ComponentType<any>; props?: Record<string, any> }>;\r\n loading?: React.ComponentType | null;\r\n error?: React.ComponentType<{ error: Error }> | null;\r\n title?: string;\r\n meta?: Record<string, string>;\r\n scripts?: Array<string | { src?: string; content?: string; type?: string }>;\r\n styles?: Array<string | { content: string }>;\r\n favicon?: string | null;\r\n route?: string;\r\n onShellReady?: () => void;\r\n onAllReady?: () => void;\r\n onError?: (error: Error) => void;\r\n}): Promise<{ stream: NodeJS.ReadableStream; shellReady: Promise<void> }> {\r\n const {\r\n Component,\r\n props = {},\r\n layouts = [],\r\n loading = null,\r\n error = null,\r\n title = 'FlexiReact App',\r\n meta = {},\r\n scripts = [],\r\n styles = [],\r\n favicon = null,\r\n route = '/',\r\n onShellReady,\r\n onAllReady,\r\n onError\r\n } = options;\r\n\r\n const renderStart = Date.now();\r\n\r\n // Build the component tree\r\n let element: any = React.createElement(Component, props);\r\n\r\n // Wrap with error boundary if error component exists\r\n if (error) {\r\n element = React.createElement(ErrorBoundaryWrapper as any, {\r\n fallback: error,\r\n children: element\r\n });\r\n }\r\n\r\n // Wrap with Suspense if loading component exists\r\n if (loading) {\r\n element = React.createElement(React.Suspense as any, {\r\n fallback: React.createElement(loading),\r\n children: element\r\n });\r\n }\r\n\r\n // Wrap with layouts\r\n for (const layout of [...layouts].reverse()) {\r\n if (layout.Component) {\r\n element = React.createElement(layout.Component, layout.props, element);\r\n }\r\n }\r\n\r\n // Create the full document wrapper\r\n const DocumentWrapper = ({ children }: { children: React.ReactNode }) => {\r\n return React.createElement('html', { lang: 'en', className: 'dark' },\r\n React.createElement('head', null,\r\n React.createElement('meta', { charSet: 'UTF-8' }),\r\n React.createElement('meta', { name: 'viewport', content: 'width=device-width, initial-scale=1.0' }),\r\n React.createElement('title', null, title),\r\n favicon && React.createElement('link', { rel: 'icon', href: favicon }),\r\n ...Object.entries(meta).map(([name, content]) => \r\n React.createElement('meta', { key: name, name, content })\r\n ),\r\n ...styles.map((style, i) => \r\n typeof style === 'string'\r\n ? React.createElement('link', { key: i, rel: 'stylesheet', href: style })\r\n : React.createElement('style', { key: i, dangerouslySetInnerHTML: { __html: style.content } })\r\n )\r\n ),\r\n React.createElement('body', null,\r\n React.createElement('div', { id: 'root' }, children),\r\n ...scripts.map((script, i) => \r\n typeof script === 'string'\r\n ? React.createElement('script', { key: i, src: script })\r\n : script.src\r\n ? React.createElement('script', { key: i, src: script.src, type: script.type })\r\n : React.createElement('script', { key: i, type: script.type, dangerouslySetInnerHTML: { __html: script.content } })\r\n )\r\n )\r\n );\r\n };\r\n\r\n const fullElement = React.createElement(DocumentWrapper, null, element);\r\n\r\n // Create streaming render\r\n let shellReadyResolve: () => void;\r\n const shellReady = new Promise<void>((resolve) => {\r\n shellReadyResolve = resolve;\r\n });\r\n\r\n const { pipe, abort } = renderToPipeableStream(fullElement, {\r\n onShellReady() {\r\n const renderTime = Date.now() - renderStart;\r\n console.log(`⚡ Shell ready in ${renderTime}ms`);\r\n shellReadyResolve();\r\n onShellReady?.();\r\n },\r\n onAllReady() {\r\n const renderTime = Date.now() - renderStart;\r\n console.log(`✨ All content ready in ${renderTime}ms`);\r\n onAllReady?.();\r\n },\r\n onError(err: Error) {\r\n console.error('Streaming SSR Error:', err);\r\n onError?.(err);\r\n }\r\n });\r\n\r\n // Create a passthrough stream\r\n const { PassThrough } = await import('stream');\r\n const passThrough = new PassThrough();\r\n \r\n // Pipe the render stream to our passthrough\r\n pipe(passThrough);\r\n\r\n return {\r\n stream: passThrough,\r\n shellReady\r\n };\r\n}\r\n\r\n/**\r\n * Render to stream for HTTP response\r\n * Use this in the server to stream HTML to the client\r\n */\r\nexport function streamToResponse(\r\n res: { write: (chunk: string) => void; end: () => void },\r\n stream: NodeJS.ReadableStream,\r\n options: { onFinish?: () => void } = {}\r\n): void {\r\n stream.on('data', (chunk) => {\r\n res.write(chunk.toString());\r\n });\r\n\r\n stream.on('end', () => {\r\n res.end();\r\n options.onFinish?.();\r\n });\r\n\r\n stream.on('error', (err) => {\r\n console.error('Stream error:', err);\r\n res.end();\r\n });\r\n}\r\n\r\n/**\r\n * Error Boundary Wrapper for SSR\r\n */\r\ninterface ErrorBoundaryProps {\r\n fallback: React.ComponentType<{ error: Error }>;\r\n children: React.ReactNode;\r\n}\r\n\r\ninterface ErrorBoundaryState {\r\n hasError: boolean;\r\n error: Error | null;\r\n}\r\n\r\nclass ErrorBoundaryWrapper extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {\r\n constructor(props: ErrorBoundaryProps) {\r\n super(props);\r\n this.state = { hasError: false, error: null };\r\n }\r\n\r\n static getDerivedStateFromError(error: Error): ErrorBoundaryState {\r\n return { hasError: true, error };\r\n }\r\n\r\n render() {\r\n if (this.state.hasError) {\r\n const FallbackComponent = this.props.fallback;\r\n return React.createElement(FallbackComponent, { error: this.state.error! });\r\n }\r\n return this.props.children;\r\n }\r\n}\r\n\r\n/**\r\n * Generates hydration scripts for islands\r\n */\r\nfunction generateIslandScripts(islands) {\r\n if (!islands.length) return [];\r\n \r\n const scripts = [];\r\n \r\n for (const island of islands) {\r\n scripts.push({\r\n type: 'module',\r\n content: `\r\n import { hydrateIsland } from '/_flexi/client.js';\r\n import ${island.name} from '${island.clientPath}';\r\n hydrateIsland('${island.id}', ${island.name}, ${JSON.stringify(island.props)});\r\n `\r\n });\r\n }\r\n \r\n return scripts;\r\n}\r\n\r\n/**\r\n * Generates the Dev Toolbar HTML (FlexiReact v2 - Premium DevTools)\r\n */\r\ninterface DevToolbarOptions {\r\n renderTime?: number;\r\n pageType?: string;\r\n route?: string;\r\n hasError?: boolean;\r\n isHydrated?: boolean;\r\n errorMessage?: string | null;\r\n componentName?: string | null;\r\n}\r\n\r\nfunction generateDevToolbar(options: DevToolbarOptions = {}) {\r\n const { \r\n renderTime = 0, \r\n pageType = 'SSR', \r\n route = '/',\r\n hasError = false,\r\n isHydrated = false,\r\n errorMessage = null,\r\n componentName = null\r\n } = options;\r\n\r\n const timeColor = renderTime < 50 ? '#00FF9C' : renderTime < 200 ? '#fbbf24' : '#ef4444';\r\n const timeLabel = renderTime < 50 ? 'Fast' : renderTime < 200 ? 'OK' : 'Slow';\r\n\r\n return `\r\n<!-- FlexiReact v2 Dev Toolbar -->\r\n<div id=\"flexi-dev-toolbar\" class=\"flexi-dev-collapsed\">\r\n <style>\r\n #flexi-dev-toolbar {\r\n position: fixed;\r\n bottom: 16px;\r\n left: 16px;\r\n z-index: 99999;\r\n font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;\r\n font-size: 13px;\r\n }\r\n \r\n /* Main Button */\r\n .flexi-dev-trigger {\r\n display: flex;\r\n align-items: center;\r\n gap: 8px;\r\n padding: 8px 12px;\r\n background: rgba(10, 10, 10, 0.95);\r\n backdrop-filter: blur(20px);\r\n border: 1px solid rgba(0, 255, 156, 0.2);\r\n border-radius: 10px;\r\n color: #fafafa;\r\n cursor: pointer;\r\n transition: all 0.2s cubic-bezier(0.16, 1, 0.3, 1);\r\n box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);\r\n }\r\n \r\n .flexi-dev-trigger:hover {\r\n border-color: rgba(0, 255, 156, 0.5);\r\n box-shadow: 0 4px 30px rgba(0, 0, 0, 0.6), 0 0 20px rgba(0, 255, 156, 0.15);\r\n transform: translateY(-2px);\r\n }\r\n \r\n .flexi-dev-trigger.has-error {\r\n border-color: rgba(239, 68, 68, 0.5);\r\n box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5), 0 0 15px rgba(239, 68, 68, 0.2);\r\n }\r\n \r\n .flexi-dev-logo {\r\n width: 20px;\r\n height: 20px;\r\n background: linear-gradient(135deg, #00FF9C, #00D68F);\r\n border-radius: 5px;\r\n display: flex;\r\n align-items: center;\r\n justify-content: center;\r\n font-weight: 800;\r\n font-size: 11px;\r\n color: #000;\r\n }\r\n \r\n .flexi-dev-trigger.has-error .flexi-dev-logo {\r\n background: linear-gradient(135deg, #ef4444, #dc2626);\r\n }\r\n \r\n .flexi-dev-indicator {\r\n display: flex;\r\n align-items: center;\r\n gap: 6px;\r\n }\r\n \r\n .flexi-dev-dot {\r\n width: 6px;\r\n height: 6px;\r\n border-radius: 50%;\r\n background: #00FF9C;\r\n box-shadow: 0 0 8px rgba(0, 255, 156, 0.6);\r\n }\r\n \r\n .flexi-dev-dot.error {\r\n background: #ef4444;\r\n box-shadow: 0 0 8px rgba(239, 68, 68, 0.6);\r\n animation: errorPulse 1s infinite;\r\n }\r\n \r\n @keyframes errorPulse {\r\n 0%, 100% { opacity: 1; }\r\n 50% { opacity: 0.4; }\r\n }\r\n \r\n .flexi-dev-time {\r\n font-size: 11px;\r\n font-weight: 600;\r\n color: ${timeColor};\r\n font-variant-numeric: tabular-nums;\r\n }\r\n \r\n /* Panel */\r\n .flexi-dev-panel {\r\n position: absolute;\r\n bottom: calc(100% + 8px);\r\n left: 0;\r\n min-width: 340px;\r\n background: rgba(10, 10, 10, 0.98);\r\n backdrop-filter: blur(20px);\r\n border: 1px solid rgba(255, 255, 255, 0.08);\r\n border-radius: 16px;\r\n opacity: 0;\r\n visibility: hidden;\r\n transform: translateY(8px) scale(0.96);\r\n transition: all 0.25s cubic-bezier(0.16, 1, 0.3, 1);\r\n box-shadow: 0 20px 50px rgba(0, 0, 0, 0.7);\r\n overflow: hidden;\r\n }\r\n \r\n #flexi-dev-toolbar.flexi-dev-open .flexi-dev-panel {\r\n opacity: 1;\r\n visibility: visible;\r\n transform: translateY(0) scale(1);\r\n }\r\n \r\n /* Header */\r\n .flexi-dev-header {\r\n display: flex;\r\n align-items: center;\r\n gap: 10px;\r\n padding: 14px 16px;\r\n background: linear-gradient(135deg, rgba(0, 255, 156, 0.08), rgba(0, 214, 143, 0.04));\r\n border-bottom: 1px solid rgba(255, 255, 255, 0.05);\r\n }\r\n \r\n .flexi-dev-header-logo {\r\n width: 26px;\r\n height: 26px;\r\n background: linear-gradient(135deg, #00FF9C, #00D68F);\r\n border-radius: 7px;\r\n display: flex;\r\n align-items: center;\r\n justify-content: center;\r\n font-weight: 800;\r\n font-size: 13px;\r\n color: #000;\r\n }\r\n \r\n .flexi-dev-header-info {\r\n flex: 1;\r\n }\r\n \r\n .flexi-dev-header-title {\r\n font-weight: 700;\r\n font-size: 14px;\r\n color: #fafafa;\r\n }\r\n \r\n .flexi-dev-header-subtitle {\r\n font-size: 11px;\r\n color: #52525b;\r\n margin-top: 1px;\r\n }\r\n \r\n .flexi-dev-close {\r\n width: 24px;\r\n height: 24px;\r\n display: flex;\r\n align-items: center;\r\n justify-content: center;\r\n background: rgba(255, 255, 255, 0.05);\r\n border: none;\r\n border-radius: 6px;\r\n color: #71717a;\r\n cursor: pointer;\r\n transition: all 0.15s;\r\n }\r\n \r\n .flexi-dev-close:hover {\r\n background: rgba(255, 255, 255, 0.1);\r\n color: #fafafa;\r\n }\r\n \r\n /* Content */\r\n .flexi-dev-content {\r\n padding: 12px 16px;\r\n }\r\n \r\n .flexi-dev-section {\r\n margin-bottom: 12px;\r\n }\r\n \r\n .flexi-dev-section:last-child {\r\n margin-bottom: 0;\r\n }\r\n \r\n .flexi-dev-section-title {\r\n font-size: 10px;\r\n font-weight: 600;\r\n color: #52525b;\r\n text-transform: uppercase;\r\n letter-spacing: 0.5px;\r\n margin-bottom: 8px;\r\n }\r\n \r\n .flexi-dev-grid {\r\n display: grid;\r\n grid-template-columns: 1fr 1fr;\r\n gap: 8px;\r\n }\r\n \r\n .flexi-dev-stat {\r\n background: rgba(255, 255, 255, 0.03);\r\n border: 1px solid rgba(255, 255, 255, 0.05);\r\n border-radius: 10px;\r\n padding: 10px 12px;\r\n }\r\n \r\n .flexi-dev-stat-label {\r\n font-size: 10px;\r\n color: #52525b;\r\n margin-bottom: 4px;\r\n }\r\n \r\n .flexi-dev-stat-value {\r\n font-size: 14px;\r\n font-weight: 600;\r\n color: #fafafa;\r\n }\r\n \r\n .flexi-dev-stat-value.success { color: #00FF9C; }\r\n .flexi-dev-stat-value.warning { color: #fbbf24; }\r\n .flexi-dev-stat-value.error { color: #ef4444; }\r\n \r\n /* Badges */\r\n .flexi-dev-badge {\r\n display: inline-flex;\r\n align-items: center;\r\n padding: 3px 8px;\r\n border-radius: 5px;\r\n font-size: 10px;\r\n font-weight: 700;\r\n letter-spacing: 0.3px;\r\n }\r\n \r\n .flexi-dev-badge.ssr { background: rgba(251, 191, 36, 0.15); color: #fbbf24; }\r\n .flexi-dev-badge.ssg { background: rgba(0, 255, 156, 0.15); color: #00FF9C; }\r\n .flexi-dev-badge.csr { background: rgba(6, 182, 212, 0.15); color: #06b6d4; }\r\n .flexi-dev-badge.isr { background: rgba(139, 92, 246, 0.15); color: #a78bfa; }\r\n \r\n /* Error Display */\r\n .flexi-dev-error {\r\n background: rgba(239, 68, 68, 0.1);\r\n border: 1px solid rgba(239, 68, 68, 0.2);\r\n border-radius: 10px;\r\n padding: 12px;\r\n margin-top: 8px;\r\n }\r\n \r\n .flexi-dev-error-title {\r\n display: flex;\r\n align-items: center;\r\n gap: 6px;\r\n font-size: 11px;\r\n font-weight: 600;\r\n color: #ef4444;\r\n margin-bottom: 6px;\r\n }\r\n \r\n .flexi-dev-error-message {\r\n font-size: 12px;\r\n color: #fca5a5;\r\n font-family: 'SF Mono', 'Fira Code', monospace;\r\n word-break: break-word;\r\n line-height: 1.5;\r\n }\r\n \r\n /* Footer */\r\n .flexi-dev-footer {\r\n display: flex;\r\n gap: 6px;\r\n padding: 12px 16px;\r\n background: rgba(0, 0, 0, 0.3);\r\n border-top: 1px solid rgba(255, 255, 255, 0.05);\r\n }\r\n \r\n .flexi-dev-action {\r\n flex: 1;\r\n padding: 8px;\r\n background: rgba(255, 255, 255, 0.03);\r\n border: 1px solid rgba(255, 255, 255, 0.06);\r\n border-radius: 8px;\r\n color: #71717a;\r\n font-size: 11px;\r\n font-weight: 500;\r\n text-decoration: none;\r\n text-align: center;\r\n cursor: pointer;\r\n transition: all 0.15s;\r\n }\r\n \r\n .flexi-dev-action:hover {\r\n background: rgba(0, 255, 156, 0.1);\r\n border-color: rgba(0, 255, 156, 0.2);\r\n color: #00FF9C;\r\n }\r\n </style>\r\n \r\n <button class=\"flexi-dev-trigger ${hasError ? 'has-error' : ''}\" onclick=\"this.parentElement.classList.toggle('flexi-dev-open')\">\r\n <div class=\"flexi-dev-logo\">F</div>\r\n <div class=\"flexi-dev-indicator\">\r\n <div class=\"flexi-dev-dot ${hasError ? 'error' : ''}\"></div>\r\n <span class=\"flexi-dev-time\">${renderTime}ms</span>\r\n </div>\r\n </button>\r\n \r\n <div class=\"flexi-dev-panel\">\r\n <div class=\"flexi-dev-header\">\r\n <div class=\"flexi-dev-header-logo\">F</div>\r\n <div class=\"flexi-dev-header-info\">\r\n <div class=\"flexi-dev-header-title\">FlexiReact</div>\r\n <div class=\"flexi-dev-header-subtitle\">v2.0.0 • Development</div>\r\n </div>\r\n <button class=\"flexi-dev-close\" onclick=\"this.closest('#flexi-dev-toolbar').classList.remove('flexi-dev-open')\">✕</button>\r\n </div>\r\n \r\n <div class=\"flexi-dev-content\">\r\n <div class=\"flexi-dev-section\">\r\n <div class=\"flexi-dev-section-title\">Page Info</div>\r\n <div class=\"flexi-dev-grid\">\r\n <div class=\"flexi-dev-stat\">\r\n <div class=\"flexi-dev-stat-label\">Route</div>\r\n <div class=\"flexi-dev-stat-value\">${route}</div>\r\n </div>\r\n <div class=\"flexi-dev-stat\">\r\n <div class=\"flexi-dev-stat-label\">Type</div>\r\n <div class=\"flexi-dev-stat-value\"><span class=\"flexi-dev-badge ${pageType.toLowerCase()}\">${pageType}</span></div>\r\n </div>\r\n </div>\r\n </div>\r\n \r\n <div class=\"flexi-dev-section\">\r\n <div class=\"flexi-dev-section-title\">Performance</div>\r\n <div class=\"flexi-dev-grid\">\r\n <div class=\"flexi-dev-stat\">\r\n <div class=\"flexi-dev-stat-label\">Render Time</div>\r\n <div class=\"flexi-dev-stat-value ${renderTime < 50 ? 'success' : renderTime < 200 ? 'warning' : 'error'}\">${renderTime}ms <small style=\"color:#52525b\">${timeLabel}</small></div>\r\n </div>\r\n <div class=\"flexi-dev-stat\">\r\n <div class=\"flexi-dev-stat-label\">Hydration</div>\r\n <div class=\"flexi-dev-stat-value\" id=\"flexi-hydration-status\">${isHydrated ? '✓ Client' : '○ Server'}</div>\r\n </div>\r\n </div>\r\n </div>\r\n \r\n ${hasError && errorMessage ? `\r\n <div class=\"flexi-dev-error\">\r\n <div class=\"flexi-dev-error-title\">\r\n <span>⚠</span> Runtime Error\r\n </div>\r\n <div class=\"flexi-dev-error-message\">${errorMessage}</div>\r\n </div>\r\n ` : ''}\r\n </div>\r\n \r\n <div class=\"flexi-dev-footer\">\r\n <a href=\"/_flexi/routes\" class=\"flexi-dev-action\">Routes</a>\r\n <button class=\"flexi-dev-action\" onclick=\"location.reload()\">Refresh</button>\r\n <a href=\"https://github.com/flexireact/flexireact\" target=\"_blank\" class=\"flexi-dev-action\">Docs ↗</a>\r\n </div>\r\n </div>\r\n</div>\r\n\r\n<script>\r\n // FlexiReact v2 DevTools\r\n window.__FLEXI_DEV__ = {\r\n version: '2.0.0',\r\n renderTime: ${renderTime},\r\n pageType: '${pageType}',\r\n route: '${route}',\r\n hydrated: false,\r\n errors: []\r\n };\r\n \r\n // Track hydration\r\n const root = document.getElementById('root');\r\n if (root) {\r\n const observer = new MutationObserver(() => {\r\n if (root.children.length > 0) {\r\n window.__FLEXI_DEV__.hydrated = true;\r\n const el = document.getElementById('flexi-hydration-status');\r\n if (el) el.textContent = '✓ Client';\r\n observer.disconnect();\r\n }\r\n });\r\n observer.observe(root, { childList: true, subtree: true });\r\n }\r\n \r\n // Capture runtime errors\r\n window.addEventListener('error', (e) => {\r\n window.__FLEXI_DEV__.errors.push({\r\n message: e.message,\r\n file: e.filename,\r\n line: e.lineno,\r\n col: e.colno\r\n });\r\n console.error('%c[FlexiReact Error]', 'color: #ef4444; font-weight: bold;', e.message);\r\n });\r\n \r\n // Console branding\r\n console.log(\r\n '%c ⚡ FlexiReact v2 %c ${pageType} %c ${renderTime}ms ',\r\n 'background: #00FF9C; color: #000; font-weight: bold; padding: 2px 6px; border-radius: 4px 0 0 4px;',\r\n 'background: #1e1e1e; color: #fafafa; padding: 2px 6px;',\r\n 'background: ${timeColor}20; color: ${timeColor}; padding: 2px 6px; border-radius: 0 4px 4px 0;'\r\n );\r\n</script>\r\n`;\r\n}\r\n\r\n/**\r\n * Builds complete HTML document\r\n */\r\nfunction buildHtmlDocument(options) {\r\n const {\r\n content,\r\n title,\r\n meta = {},\r\n scripts = [],\r\n styles = [],\r\n props = {},\r\n isSSG = false,\r\n renderTime = 0,\r\n route = '/',\r\n isClientComponent = false,\r\n favicon = null\r\n } = options;\r\n\r\n const metaTags = Object.entries(meta)\r\n .map(([name, content]) => {\r\n if (name.startsWith('og:')) {\r\n return `<meta property=\"${escapeHtml(name)}\" content=\"${escapeHtml(content)}\">`;\r\n }\r\n return `<meta name=\"${escapeHtml(name)}\" content=\"${escapeHtml(content)}\">`;\r\n })\r\n .join('\\n ');\r\n\r\n const styleTags = styles\r\n .map(style => {\r\n if (typeof style === 'string') {\r\n return `<link rel=\"stylesheet\" href=\"${escapeHtml(style)}\">`;\r\n }\r\n return `<style>${style.content}</style>`;\r\n })\r\n .join('\\n ');\r\n\r\n const scriptTags = scripts\r\n .map(script => {\r\n if (typeof script === 'string') {\r\n return `<script src=\"${escapeHtml(script)}\"></script>`;\r\n }\r\n const type = script.type ? ` type=\"${script.type}\"` : '';\r\n if (script.src) {\r\n return `<script${type} src=\"${escapeHtml(script.src)}\"></script>`;\r\n }\r\n return `<script${type}>${script.content}</script>`;\r\n })\r\n .join('\\n ');\r\n\r\n // FlexiReact SVG favicon (properly encoded)\r\n const faviconSvg = encodeURIComponent(`<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 32 32\"><rect width=\"32\" height=\"32\" rx=\"8\" fill=\"#00FF9C\"/><text x=\"50%\" y=\"50%\" dominant-baseline=\"central\" text-anchor=\"middle\" fill=\"#000\" font-family=\"system-ui\" font-weight=\"bold\" font-size=\"16\">F</text></svg>`);\r\n\r\n // Generate Dev Toolbar for development mode\r\n const isDev = process.env.NODE_ENV !== 'production';\r\n const pageType = isSSG ? 'SSG' : isClientComponent ? 'CSR' : 'SSR';\r\n const devToolbar = isDev ? generateDevToolbar({ \r\n renderTime, \r\n pageType, \r\n route,\r\n isHydrated: isClientComponent\r\n }) : '';\r\n\r\n // Determine favicon link\r\n const faviconLink = favicon \r\n ? `<link rel=\"icon\" href=\"${escapeHtml(favicon)}\">`\r\n : `<link rel=\"icon\" type=\"image/svg+xml\" href=\"data:image/svg+xml,${faviconSvg}\">`;\r\n\r\n return `<!DOCTYPE html>\r\n<html lang=\"en\" class=\"dark\">\r\n<head>\r\n <meta charset=\"UTF-8\">\r\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\r\n <title>${escapeHtml(title)}</title>\r\n ${faviconLink}\r\n ${metaTags}\r\n <style>\r\n :root { --flexi-bg: #0f172a; --flexi-fg: #f8fafc; }\r\n html, body { background-color: #0f172a; color: #f8fafc; min-height: 100vh; margin: 0; }\r\n </style>\r\n ${styleTags}\r\n <script>\r\n (function() {\r\n var theme = localStorage.getItem('theme');\r\n if (theme === 'light') {\r\n document.documentElement.classList.remove('dark');\r\n document.documentElement.style.backgroundColor = '#ffffff';\r\n document.documentElement.style.color = '#0f172a';\r\n document.body.style.backgroundColor = '#ffffff';\r\n document.body.style.color = '#0f172a';\r\n }\r\n })();\r\n </script>\r\n</head>\r\n<body>\r\n <div id=\"root\">${content}</div>\r\n <script>\r\n window.__FLEXI_DATA__ = ${JSON.stringify({ props, isSSG })};\r\n </script>\r\n ${scriptTags}\r\n ${devToolbar}\r\n</body>\r\n</html>`;\r\n}\r\n\r\n/**\r\n * Renders an error page with beautiful styling (FlexiReact v2)\r\n */\r\nexport function renderError(statusCode, message, stack = null) {\r\n const showStack = process.env.NODE_ENV !== 'production' && stack;\r\n const isDev = process.env.NODE_ENV !== 'production';\r\n \r\n // Parse error for better display\r\n const errorDetails = parseErrorStack(stack);\r\n \r\n // Different messages for different status codes\r\n const errorMessages = {\r\n 404: { title: 'Page Not Found', icon: 'search', color: '#00FF9C', desc: 'The page you\\'re looking for doesn\\'t exist or has been moved.' },\r\n 500: { title: 'Server Error', icon: 'alert', color: '#ef4444', desc: 'Something went wrong on our end.' },\r\n 403: { title: 'Forbidden', icon: 'lock', color: '#f59e0b', desc: 'You don\\'t have permission to access this resource.' },\r\n 401: { title: 'Unauthorized', icon: 'key', color: '#8b5cf6', desc: 'Please log in to access this page.' },\r\n };\r\n \r\n const errorInfo = errorMessages[statusCode] || { title: 'Error', icon: 'alert', color: '#ef4444', desc: message };\r\n \r\n // Generate error frames HTML for dev mode\r\n const errorFramesHtml = showStack && errorDetails?.frames?.length > 0 \r\n ? errorDetails.frames.slice(0, 5).map((frame, i) => `\r\n <div class=\"error-frame ${i === 0 ? 'error-frame-first' : ''}\">\r\n <div class=\"error-frame-fn\">${escapeHtml(frame.fn)}</div>\r\n <div class=\"error-frame-loc\">${escapeHtml(frame.file)}:${frame.line}:${frame.col}</div>\r\n </div>\r\n `).join('')\r\n : '';\r\n\r\n return `<!DOCTYPE html>\r\n<html lang=\"en\">\r\n<head>\r\n <meta charset=\"UTF-8\">\r\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\r\n <title>${statusCode} - ${errorInfo.title} | FlexiReact</title>\r\n <link rel=\"icon\" type=\"image/svg+xml\" href=\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='8' fill='%2300FF9C'/%3E%3Ctext x='50%25' y='50%25' dominant-baseline='central' text-anchor='middle' fill='%23000' font-family='system-ui' font-weight='bold' font-size='16'%3EF%3C/text%3E%3C/svg%3E\">\r\n <style>\r\n * { margin: 0; padding: 0; box-sizing: border-box; }\r\n \r\n body {\r\n font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\r\n min-height: 100vh;\r\n background: #0a0a0a;\r\n color: #fafafa;\r\n display: flex;\r\n align-items: center;\r\n justify-content: center;\r\n overflow-x: hidden;\r\n }\r\n \r\n /* Animated background */\r\n .bg-pattern {\r\n position: fixed;\r\n inset: 0;\r\n background-image: \r\n radial-gradient(circle at 25% 25%, rgba(0, 255, 156, 0.03) 0%, transparent 50%),\r\n radial-gradient(circle at 75% 75%, rgba(99, 102, 241, 0.03) 0%, transparent 50%);\r\n pointer-events: none;\r\n }\r\n \r\n .bg-grid {\r\n position: fixed;\r\n inset: 0;\r\n background-image: \r\n linear-gradient(rgba(255, 255, 255, 0.02) 1px, transparent 1px),\r\n linear-gradient(90deg, rgba(255, 255, 255, 0.02) 1px, transparent 1px);\r\n background-size: 64px 64px;\r\n pointer-events: none;\r\n }\r\n \r\n .container {\r\n position: relative;\r\n width: 100%;\r\n max-width: ${showStack ? '800px' : '500px'};\r\n padding: 2rem;\r\n animation: fadeIn 0.6s cubic-bezier(0.16, 1, 0.3, 1);\r\n }\r\n \r\n @keyframes fadeIn {\r\n from { opacity: 0; transform: translateY(30px); }\r\n to { opacity: 1; transform: translateY(0); }\r\n }\r\n \r\n /* Error Card */\r\n .error-card {\r\n background: linear-gradient(145deg, rgba(23, 23, 23, 0.9), rgba(10, 10, 10, 0.95));\r\n border: 1px solid rgba(255, 255, 255, 0.08);\r\n border-radius: 24px;\r\n padding: 3rem;\r\n text-align: center;\r\n backdrop-filter: blur(20px);\r\n box-shadow: \r\n 0 0 0 1px rgba(255, 255, 255, 0.05),\r\n 0 20px 50px -20px rgba(0, 0, 0, 0.5),\r\n 0 0 100px -50px ${errorInfo.color}40;\r\n }\r\n \r\n /* Logo */\r\n .logo {\r\n width: 56px;\r\n height: 56px;\r\n background: linear-gradient(135deg, #00FF9C, #00D68F);\r\n border-radius: 14px;\r\n display: flex;\r\n align-items: center;\r\n justify-content: center;\r\n margin: 0 auto 2rem;\r\n font-weight: 800;\r\n font-size: 24px;\r\n color: #000;\r\n box-shadow: 0 0 30px rgba(0, 255, 156, 0.3);\r\n }\r\n \r\n /* Error Code */\r\n .error-code {\r\n font-size: 7rem;\r\n font-weight: 800;\r\n line-height: 1;\r\n background: linear-gradient(135deg, ${errorInfo.color}, ${errorInfo.color}99);\r\n -webkit-background-clip: text;\r\n -webkit-text-fill-color: transparent;\r\n background-clip: text;\r\n margin-bottom: 0.5rem;\r\n letter-spacing: -4px;\r\n }\r\n \r\n .error-title {\r\n font-size: 1.5rem;\r\n font-weight: 600;\r\n color: #fafafa;\r\n margin-bottom: 0.75rem;\r\n }\r\n \r\n .error-desc {\r\n font-size: 1rem;\r\n color: #71717a;\r\n line-height: 1.6;\r\n margin-bottom: 2rem;\r\n }\r\n \r\n /* Buttons */\r\n .buttons {\r\n display: flex;\r\n gap: 12px;\r\n justify-content: center;\r\n flex-wrap: wrap;\r\n }\r\n \r\n .btn {\r\n display: inline-flex;\r\n align-items: center;\r\n gap: 8px;\r\n padding: 12px 24px;\r\n border-radius: 12px;\r\n font-weight: 600;\r\n font-size: 14px;\r\n text-decoration: none;\r\n transition: all 0.2s cubic-bezier(0.16, 1, 0.3, 1);\r\n border: none;\r\n cursor: pointer;\r\n }\r\n \r\n .btn-primary {\r\n background: #00FF9C;\r\n color: #000;\r\n box-shadow: 0 0 20px rgba(0, 255, 156, 0.3);\r\n }\r\n \r\n .btn-primary:hover {\r\n transform: translateY(-2px);\r\n box-shadow: 0 0 30px rgba(0, 255, 156, 0.5);\r\n }\r\n \r\n .btn-secondary {\r\n background: rgba(255, 255, 255, 0.06);\r\n color: #a1a1aa;\r\n border: 1px solid rgba(255, 255, 255, 0.1);\r\n }\r\n \r\n .btn-secondary:hover {\r\n background: rgba(255, 255, 255, 0.1);\r\n color: #fafafa;\r\n border-color: rgba(255, 255, 255, 0.2);\r\n }\r\n \r\n /* Error Stack (Dev Mode) */\r\n .error-stack {\r\n margin-top: 2rem;\r\n text-align: left;\r\n }\r\n \r\n .error-stack-header {\r\n display: flex;\r\n align-items: center;\r\n gap: 8px;\r\n margin-bottom: 12px;\r\n font-size: 12px;\r\n font-weight: 600;\r\n color: #ef4444;\r\n text-transform: uppercase;\r\n letter-spacing: 0.5px;\r\n }\r\n \r\n .error-stack-header::before {\r\n content: '';\r\n width: 8px;\r\n height: 8px;\r\n background: #ef4444;\r\n border-radius: 50%;\r\n animation: pulse 2s infinite;\r\n }\r\n \r\n @keyframes pulse {\r\n 0%, 100% { opacity: 1; }\r\n 50% { opacity: 0.5; }\r\n }\r\n \r\n .error-message {\r\n background: rgba(239, 68, 68, 0.1);\r\n border: 1px solid rgba(239, 68, 68, 0.2);\r\n border-radius: 12px;\r\n padding: 16px;\r\n margin-bottom: 12px;\r\n font-family: 'SF Mono', 'Fira Code', monospace;\r\n font-size: 13px;\r\n color: #fca5a5;\r\n word-break: break-word;\r\n }\r\n \r\n .error-frames {\r\n background: rgba(0, 0, 0, 0.4);\r\n border: 1px solid rgba(255, 255, 255, 0.05);\r\n border-radius: 12px;\r\n overflow: hidden;\r\n }\r\n \r\n .error-frame {\r\n padding: 12px 16px;\r\n border-bottom: 1px solid rgba(255, 255, 255, 0.05);\r\n font-family: 'SF Mono', 'Fira Code', monospace;\r\n font-size: 12px;\r\n }\r\n \r\n .error-frame:last-child {\r\n border-bottom: none;\r\n }\r\n \r\n .error-frame-first {\r\n background: rgba(239, 68, 68, 0.05);\r\n }\r\n \r\n .error-frame-fn {\r\n color: #fafafa;\r\n font-weight: 500;\r\n margin-bottom: 4px;\r\n }\r\n \r\n .error-frame-loc {\r\n color: #52525b;\r\n font-size: 11px;\r\n }\r\n \r\n /* Dev Badge */\r\n .dev-badge {\r\n position: fixed;\r\n bottom: 20px;\r\n right: 20px;\r\n display: flex;\r\n align-items: center;\r\n gap: 8px;\r\n padding: 8px 14px;\r\n background: rgba(0, 0, 0, 0.8);\r\n border: 1px solid rgba(255, 255, 255, 0.1);\r\n border-radius: 10px;\r\n font-size: 12px;\r\n font-weight: 500;\r\n color: #71717a;\r\n backdrop-filter: blur(10px);\r\n }\r\n \r\n .dev-badge-dot {\r\n width: 8px;\r\n height: 8px;\r\n background: #00FF9C;\r\n border-radius: 50%;\r\n box-shadow: 0 0 10px rgba(0, 255, 156, 0.5);\r\n }\r\n </style>\r\n</head>\r\n<body>\r\n <div class=\"bg-pattern\"></div>\r\n <div class=\"bg-grid\"></div>\r\n \r\n <div class=\"container\">\r\n <div class=\"error-card\">\r\n <div class=\"logo\">F</div>\r\n \r\n <div class=\"error-code\">${statusCode}</div>\r\n <h1 class=\"error-title\">${errorInfo.title}</h1>\r\n <p class=\"error-desc\">${errorInfo.desc}</p>\r\n \r\n <div class=\"buttons\">\r\n <a href=\"/\" class=\"btn btn-primary\">\r\n ← Back to Home\r\n </a>\r\n <a href=\"javascript:history.back()\" class=\"btn btn-secondary\">\r\n Go Back\r\n </a>\r\n </div>\r\n \r\n ${showStack ? `\r\n <div class=\"error-stack\">\r\n <div class=\"error-stack-header\">Error Details</div>\r\n <div class=\"error-message\">${escapeHtml(message)}</div>\r\n ${errorFramesHtml ? `<div class=\"error-frames\">${errorFramesHtml}</div>` : ''}\r\n </div>\r\n ` : ''}\r\n </div>\r\n </div>\r\n \r\n ${isDev ? `\r\n <div class=\"dev-badge\">\r\n <div class=\"dev-badge-dot\"></div>\r\n FlexiReact v2\r\n </div>\r\n ` : ''}\r\n</body>\r\n</html>`;\r\n}\r\n\r\n/**\r\n * Parses error stack for better display\r\n */\r\nfunction parseErrorStack(stack) {\r\n if (!stack) return null;\r\n \r\n const lines = stack.split('\\n');\r\n const parsed = {\r\n message: lines[0] || '',\r\n frames: []\r\n };\r\n \r\n for (let i = 1; i < lines.length; i++) {\r\n const line = lines[i].trim();\r\n const match = line.match(/at\\s+(.+?)\\s+\\((.+?):(\\d+):(\\d+)\\)/) ||\r\n line.match(/at\\s+(.+?):(\\d+):(\\d+)/);\r\n \r\n if (match) {\r\n parsed.frames.push({\r\n fn: match[1] || 'anonymous',\r\n file: match[2] || match[1],\r\n line: match[3] || match[2],\r\n col: match[4] || match[3]\r\n });\r\n }\r\n }\r\n \r\n return parsed;\r\n}\r\n\r\n/**\r\n * Renders a loading state\r\n */\r\nexport function renderLoading(LoadingComponent) {\r\n if (!LoadingComponent) {\r\n return `<div class=\"flexi-loading\">\r\n <div class=\"flexi-spinner\"></div>\r\n <style>\r\n .flexi-loading {\r\n display: flex;\r\n align-items: center;\r\n justify-content: center;\r\n min-height: 200px;\r\n }\r\n .flexi-spinner {\r\n width: 40px;\r\n height: 40px;\r\n border: 3px solid #f3f3f3;\r\n border-top: 3px solid #667eea;\r\n border-radius: 50%;\r\n animation: spin 1s linear infinite;\r\n }\r\n @keyframes spin {\r\n 0% { transform: rotate(0deg); }\r\n 100% { transform: rotate(360deg); }\r\n }\r\n </style>\r\n </div>`;\r\n }\r\n \r\n return renderToString(React.createElement(LoadingComponent));\r\n}\r\n\r\nexport default {\r\n renderPage,\r\n renderError,\r\n renderLoading\r\n};\r\n","/**\r\n * FlexiReact Server v2\r\n * Production-ready server with SSR, RSC, Islands, and more\r\n */\r\n\r\nimport http from 'http';\r\nimport fs from 'fs';\r\nimport path from 'path';\r\nimport { fileURLToPath, pathToFileURL } from 'url';\r\nimport { loadConfig, resolvePaths } from '../config.js';\r\nimport { buildRouteTree, matchRoute, findRouteLayouts } from '../router/index.js';\r\nimport { renderPage, renderError, renderLoading } from '../render/index.js';\r\nimport { loadMiddleware, runMiddleware } from '../middleware/index.js';\r\nimport { loadPlugins, pluginManager, PluginHooks } from '../plugins/index.js';\r\nimport { getRegisteredIslands, generateAdvancedHydrationScript } from '../islands/index.js';\r\nimport { createRequestContext, RequestContext, RouteContext } from '../context.js';\r\nimport { logger } from '../logger.js';\r\nimport { RedirectError, NotFoundError } from '../helpers.js';\r\nimport { executeAction, deserializeArgs } from '../actions/index.js';\r\nimport { handleImageOptimization } from '../image/index.js';\r\nimport { handleFontRequest } from '../font/index.js';\r\nimport React from 'react';\r\n\r\nconst __filename = fileURLToPath(import.meta.url);\r\nconst __dirname = path.dirname(__filename);\r\n\r\n// MIME types\r\nconst MIME_TYPES = {\r\n '.html': 'text/html',\r\n '.css': 'text/css',\r\n '.js': 'application/javascript',\r\n '.mjs': 'application/javascript',\r\n '.json': 'application/json',\r\n '.png': 'image/png',\r\n '.jpg': 'image/jpeg',\r\n '.jpeg': 'image/jpeg',\r\n '.gif': 'image/gif',\r\n '.svg': 'image/svg+xml',\r\n '.ico': 'image/x-icon',\r\n '.woff': 'font/woff',\r\n '.woff2': 'font/woff2',\r\n '.ttf': 'font/ttf',\r\n '.webp': 'image/webp',\r\n '.mp4': 'video/mp4',\r\n '.webm': 'video/webm'\r\n};\r\n\r\n/**\r\n * Creates the FlexiReact server\r\n */\r\ninterface CreateServerOptions {\r\n projectRoot?: string;\r\n mode?: 'development' | 'production';\r\n port?: number;\r\n host?: string;\r\n}\r\n\r\nexport async function createServer(options: CreateServerOptions = {}) {\r\n const serverStartTime = Date.now();\r\n const projectRoot = options.projectRoot || process.cwd();\r\n const isDev = options.mode === 'development';\r\n\r\n // Show logo\r\n logger.logo();\r\n\r\n // Load configuration\r\n const rawConfig = await loadConfig(projectRoot);\r\n const config = resolvePaths(rawConfig, projectRoot);\r\n\r\n // Load plugins\r\n await loadPlugins(projectRoot, config);\r\n\r\n // Run config hook\r\n await pluginManager.runHook(PluginHooks.CONFIG, config);\r\n\r\n // Load middleware\r\n const middleware = await loadMiddleware(projectRoot);\r\n\r\n // Build routes\r\n let routes = buildRouteTree(config.pagesDir, config.layoutsDir);\r\n\r\n // Run routes loaded hook\r\n await pluginManager.runHook(PluginHooks.ROUTES_LOADED, routes);\r\n\r\n // Create module loader with cache busting for dev\r\n const loadModule = createModuleLoader(isDev);\r\n\r\n // Create HTTP server\r\n const server = http.createServer(async (req, res) => {\r\n const startTime = Date.now();\r\n \r\n // Parse URL early so it's available in finally block\r\n const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);\r\n const pathname = url.pathname;\r\n\r\n try {\r\n\r\n // Run request hook\r\n await pluginManager.runHook(PluginHooks.REQUEST, req, res);\r\n\r\n // Run middleware\r\n const middlewareResult = await runMiddleware(req, res, middleware);\r\n if (!middlewareResult.continue) {\r\n return;\r\n }\r\n\r\n // Handle rewritten URL\r\n const effectivePath = middlewareResult.rewritten \r\n ? new URL(req.url, `http://${req.headers.host}`).pathname \r\n : pathname;\r\n\r\n // Serve static files from public directory\r\n if (await serveStaticFile(res, config.publicDir, effectivePath)) {\r\n return;\r\n }\r\n\r\n // Serve built assets in production\r\n if (!isDev && effectivePath.startsWith('/_flexi/')) {\r\n const assetPath = path.join(config.outDir, 'client', effectivePath.slice(8));\r\n if (await serveStaticFile(res, path.dirname(assetPath), path.basename(assetPath))) {\r\n return;\r\n }\r\n }\r\n\r\n // Serve client components (for hydration)\r\n if (effectivePath.startsWith('/_flexi/component/')) {\r\n const componentName = effectivePath.slice(18).replace('.js', '');\r\n return await serveClientComponent(res, config.pagesDir, componentName);\r\n }\r\n\r\n // Handle server actions\r\n if (effectivePath === '/_flexi/action' && req.method === 'POST') {\r\n return await handleServerAction(req, res);\r\n }\r\n\r\n // Handle image optimization\r\n if (effectivePath.startsWith('/_flexi/image')) {\r\n return await handleImageOptimization(req, res, config.images || {});\r\n }\r\n\r\n // Handle font requests\r\n if (effectivePath.startsWith('/_flexi/font')) {\r\n return await handleFontRequest(req, res);\r\n }\r\n\r\n // Rebuild routes in dev mode for hot reload\r\n if (isDev) {\r\n routes = buildRouteTree(config.pagesDir, config.layoutsDir);\r\n }\r\n\r\n // Match API routes\r\n const apiRoute = matchRoute(effectivePath, routes.api);\r\n if (apiRoute) {\r\n return await handleApiRoute(req, res, apiRoute, loadModule);\r\n }\r\n\r\n // Match FlexiReact v2 routes (routes/ directory - priority)\r\n const flexiRoute = matchRoute(effectivePath, routes.flexiRoutes || []);\r\n if (flexiRoute) {\r\n return await handlePageRoute(req, res, flexiRoute, routes, config, loadModule, url);\r\n }\r\n\r\n // Match app routes (app/ directory - Next.js style)\r\n const appRoute = matchRoute(effectivePath, routes.appRoutes || []);\r\n if (appRoute) {\r\n return await handlePageRoute(req, res, appRoute, routes, config, loadModule, url);\r\n }\r\n\r\n // Match page routes (pages/ directory - legacy fallback)\r\n const pageRoute = matchRoute(effectivePath, routes.pages);\r\n if (pageRoute) {\r\n return await handlePageRoute(req, res, pageRoute, routes, config, loadModule, url);\r\n }\r\n\r\n // 404 Not Found\r\n res.writeHead(404, { 'Content-Type': 'text/html' });\r\n res.end(renderError(404, 'Page not found'));\r\n\r\n } catch (error: any) {\r\n // Handle redirect() calls\r\n if (error instanceof RedirectError) {\r\n res.writeHead(error.statusCode, { 'Location': error.url });\r\n res.end();\r\n return;\r\n }\r\n\r\n // Handle notFound() calls\r\n if (error instanceof NotFoundError) {\r\n res.writeHead(404, { 'Content-Type': 'text/html' });\r\n res.end(renderError(404, error.message));\r\n return;\r\n }\r\n\r\n console.error('Server Error:', error);\r\n\r\n if (!res.headersSent) {\r\n res.writeHead(500, { 'Content-Type': 'text/html' });\r\n res.end(renderError(500, error.message, isDev ? error.stack : null));\r\n }\r\n } finally {\r\n const duration = Date.now() - startTime;\r\n if (isDev) {\r\n // Determine route type for logging\r\n const routeType = pathname.startsWith('/api/') ? 'api' : \r\n pathname.startsWith('/_flexi/') ? 'asset' :\r\n pathname.match(/\\.(js|css|png|jpg|svg|ico)$/) ? 'asset' : 'dynamic';\r\n logger.request(req.method, pathname, res.statusCode, duration, { type: routeType });\r\n }\r\n\r\n // Run response hook\r\n await pluginManager.runHook(PluginHooks.RESPONSE, req, res, duration);\r\n }\r\n });\r\n\r\n // Start server\r\n const port = process.env.PORT || options.port || config.server.port;\r\n const host = options.host || config.server.host;\r\n\r\n return new Promise((resolve, reject) => {\r\n // Handle port in use error\r\n server.on('error', (err: NodeJS.ErrnoException) => {\r\n if (err.code === 'EADDRINUSE') {\r\n logger.portInUse(port);\r\n process.exit(1);\r\n } else {\r\n logger.error('Server error', err);\r\n reject(err);\r\n }\r\n });\r\n\r\n server.listen(port, host, async () => {\r\n // Show startup info with styled logger\r\n logger.serverStart({\r\n port,\r\n host,\r\n mode: isDev ? 'development' : 'production',\r\n pagesDir: config.pagesDir,\r\n islands: config.islands?.enabled,\r\n rsc: config.rsc?.enabled\r\n }, serverStartTime);\r\n\r\n // Run server start hook\r\n await pluginManager.runHook(PluginHooks.SERVER_START, server);\r\n\r\n resolve(server);\r\n });\r\n });\r\n}\r\n\r\n/**\r\n * Creates a module loader with optional cache busting\r\n */\r\nfunction createModuleLoader(isDev) {\r\n return async (filePath) => {\r\n const url = pathToFileURL(filePath).href;\r\n const cacheBuster = isDev ? `?t=${Date.now()}` : '';\r\n return import(`${url}${cacheBuster}`);\r\n };\r\n}\r\n\r\n/**\r\n * Serves static files\r\n */\r\nasync function serveStaticFile(res, baseDir, pathname) {\r\n // Prevent directory traversal\r\n const safePath = path.normalize(pathname).replace(/^(\\.\\.[\\/\\\\])+/, '');\r\n const filePath = path.join(baseDir, safePath);\r\n\r\n // Check if file exists and is within base directory\r\n if (!filePath.startsWith(baseDir) || !fs.existsSync(filePath)) {\r\n return false;\r\n }\r\n\r\n const stat = fs.statSync(filePath);\r\n if (!stat.isFile()) {\r\n return false;\r\n }\r\n\r\n const ext = path.extname(filePath).toLowerCase();\r\n const contentType = MIME_TYPES[ext] || 'application/octet-stream';\r\n\r\n res.writeHead(200, {\r\n 'Content-Type': contentType,\r\n 'Content-Length': stat.size,\r\n 'Cache-Control': 'public, max-age=31536000'\r\n });\r\n\r\n fs.createReadStream(filePath).pipe(res);\r\n return true;\r\n}\r\n\r\n/**\r\n * Handles API route requests\r\n */\r\nasync function handleApiRoute(req, res, route, loadModule) {\r\n try {\r\n const module = await loadModule(route.filePath);\r\n const method = req.method.toLowerCase();\r\n\r\n // Parse request body\r\n const body = await parseBody(req);\r\n\r\n // Parse query\r\n const url = new URL(req.url, `http://${req.headers.host}`);\r\n const query = Object.fromEntries(url.searchParams);\r\n\r\n // Enhanced request\r\n const enhancedReq = {\r\n ...req,\r\n body,\r\n query,\r\n params: route.params,\r\n method: req.method\r\n };\r\n\r\n // Enhanced response\r\n const enhancedRes = createApiResponse(res);\r\n\r\n // Find handler (check both lowercase and uppercase method names)\r\n const handler = module[method] || module[method.toUpperCase()] || module.default;\r\n\r\n if (!handler) {\r\n enhancedRes.status(405).json({ error: 'Method not allowed' });\r\n return;\r\n }\r\n\r\n await handler(enhancedReq, enhancedRes);\r\n\r\n } catch (error) {\r\n console.error('API Error:', error);\r\n if (!res.headersSent) {\r\n res.writeHead(500, { 'Content-Type': 'application/json' });\r\n res.end(JSON.stringify({ error: 'Internal Server Error' }));\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Handles server action requests\r\n */\r\nasync function handleServerAction(req, res) {\r\n try {\r\n // Parse request body\r\n const body: any = await parseBody(req);\r\n const { actionId, args } = body;\r\n\r\n if (!actionId) {\r\n res.writeHead(400, { 'Content-Type': 'application/json' });\r\n res.end(JSON.stringify({ success: false, error: 'Missing actionId' }));\r\n return;\r\n }\r\n\r\n // Deserialize arguments\r\n const deserializedArgs = deserializeArgs(args || []);\r\n\r\n // Execute the action\r\n const result = await executeAction(actionId, deserializedArgs, {\r\n request: new Request(`http://${req.headers.host}${req.url}`, {\r\n method: req.method,\r\n headers: req.headers as any\r\n })\r\n });\r\n\r\n // Send response\r\n res.writeHead(200, { \r\n 'Content-Type': 'application/json',\r\n 'X-Flexi-Action': actionId\r\n });\r\n res.end(JSON.stringify(result));\r\n\r\n } catch (error: any) {\r\n console.error('Server Action Error:', error);\r\n res.writeHead(500, { 'Content-Type': 'application/json' });\r\n res.end(JSON.stringify({ \r\n success: false, \r\n error: error.message || 'Action execution failed' \r\n }));\r\n }\r\n}\r\n\r\n/**\r\n * Creates an enhanced API response object\r\n */\r\nfunction createApiResponse(res) {\r\n return {\r\n _res: res,\r\n _status: 200,\r\n _headers: {},\r\n\r\n status(code) {\r\n this._status = code;\r\n return this;\r\n },\r\n\r\n setHeader(name, value) {\r\n this._headers[name] = value;\r\n return this;\r\n },\r\n\r\n json(data) {\r\n this._headers['Content-Type'] = 'application/json';\r\n this._send(JSON.stringify(data));\r\n },\r\n\r\n send(data) {\r\n if (typeof data === 'object') {\r\n this.json(data);\r\n } else {\r\n this._headers['Content-Type'] = this._headers['Content-Type'] || 'text/plain';\r\n this._send(String(data));\r\n }\r\n },\r\n\r\n html(data) {\r\n this._headers['Content-Type'] = 'text/html';\r\n this._send(data);\r\n },\r\n\r\n redirect(url, status = 302) {\r\n this._status = status;\r\n this._headers['Location'] = url;\r\n this._send('');\r\n },\r\n\r\n _send(body) {\r\n if (!this._res.headersSent) {\r\n this._res.writeHead(this._status, this._headers);\r\n this._res.end(body);\r\n }\r\n }\r\n };\r\n}\r\n\r\n/**\r\n * Handles page route requests with SSR\r\n */\r\nasync function handlePageRoute(req, res, route, routes, config, loadModule, url) {\r\n try {\r\n // Run route-specific middleware if exists\r\n if (route.middleware) {\r\n try {\r\n const middlewareModule = await loadModule(route.middleware);\r\n const middlewareFn = middlewareModule.default || middlewareModule.middleware;\r\n \r\n if (typeof middlewareFn === 'function') {\r\n const result = await middlewareFn(req, res, { route, params: route.params });\r\n \r\n // If middleware returns a response, use it\r\n if (result?.redirect) {\r\n res.writeHead(result.statusCode || 307, { 'Location': result.redirect });\r\n res.end();\r\n return;\r\n }\r\n \r\n if (result?.rewrite) {\r\n // Rewrite to different path\r\n req.url = result.rewrite;\r\n }\r\n \r\n if (result === false || result?.stop) {\r\n // Middleware stopped the request\r\n return;\r\n }\r\n }\r\n } catch (middlewareError: any) {\r\n console.error('Route middleware error:', middlewareError.message);\r\n }\r\n }\r\n\r\n // Load page module\r\n const pageModule = await loadModule(route.filePath);\r\n const Component = pageModule.default;\r\n\r\n if (!Component) {\r\n throw new Error(`No default export in ${route.filePath}`);\r\n }\r\n\r\n // Create request context\r\n const query = Object.fromEntries(url.searchParams);\r\n const context = createRequestContext(req, res, route.params, query);\r\n\r\n // Get page props\r\n let props = { params: route.params, query };\r\n\r\n // Handle getServerSideProps\r\n if (pageModule.getServerSideProps) {\r\n const result = await pageModule.getServerSideProps({\r\n params: route.params,\r\n query,\r\n req,\r\n res\r\n });\r\n\r\n if (result.redirect) {\r\n res.writeHead(result.redirect.statusCode || 302, {\r\n Location: result.redirect.destination\r\n });\r\n res.end();\r\n return;\r\n }\r\n\r\n if (result.notFound) {\r\n res.writeHead(404, { 'Content-Type': 'text/html' });\r\n res.end(renderError(404, 'Page not found'));\r\n return;\r\n }\r\n\r\n props = { ...props, ...result.props };\r\n }\r\n\r\n // Handle getStaticProps (for ISR)\r\n if (pageModule.getStaticProps) {\r\n const result = await pageModule.getStaticProps({ params: route.params });\r\n \r\n if (result.notFound) {\r\n res.writeHead(404, { 'Content-Type': 'text/html' });\r\n res.end(renderError(404, 'Page not found'));\r\n return;\r\n }\r\n\r\n props = { ...props, ...result.props };\r\n }\r\n\r\n // Load layouts (only if layouts directory exists and has layouts)\r\n const layouts = [];\r\n \r\n try {\r\n const layoutConfigs = findRouteLayouts(route, routes.layouts);\r\n for (const layoutConfig of layoutConfigs) {\r\n if (layoutConfig.filePath) {\r\n const layoutModule = await loadModule(layoutConfig.filePath);\r\n if (layoutModule.default) {\r\n layouts.push({\r\n Component: layoutModule.default,\r\n props: {}\r\n });\r\n }\r\n }\r\n }\r\n } catch (layoutError) {\r\n // Layouts are optional, continue without them\r\n console.warn('Layout loading skipped:', layoutError.message);\r\n }\r\n\r\n // Load loading component if exists\r\n let LoadingComponent = null;\r\n if (route.loading) {\r\n const loadingModule = await loadModule(route.loading);\r\n LoadingComponent = loadingModule.default;\r\n }\r\n\r\n // Load error component if exists\r\n let ErrorComponent = null;\r\n if (route.error) {\r\n const errorModule = await loadModule(route.error);\r\n ErrorComponent = errorModule.default;\r\n }\r\n\r\n // Run before render hook\r\n props = await pluginManager.runWaterfallHook(\r\n PluginHooks.BEFORE_RENDER,\r\n props,\r\n { route, Component }\r\n );\r\n\r\n // Check if this is a client component (needs hydration)\r\n const isClientComponent = route.isClientComponent || \r\n (pageModule.__isClient) ||\r\n (typeof pageModule.default === 'function' && pageModule.default.toString().includes('useState'));\r\n\r\n // Render the page\r\n let html = await renderPage({\r\n Component,\r\n props,\r\n layouts,\r\n loading: LoadingComponent,\r\n error: ErrorComponent,\r\n islands: getRegisteredIslands(),\r\n title: pageModule.title || pageModule.metadata?.title || 'FlexiReact App',\r\n meta: pageModule.metadata || {},\r\n styles: config.styles || [],\r\n scripts: config.scripts || [],\r\n favicon: config.favicon || null,\r\n needsHydration: isClientComponent,\r\n componentPath: route.filePath,\r\n route: route.path || url.pathname,\r\n isSSG: !!pageModule.getStaticProps\r\n });\r\n\r\n // Add island hydration script\r\n const islands = getRegisteredIslands();\r\n if (islands.length > 0 && config.islands.enabled) {\r\n const hydrationScript = generateAdvancedHydrationScript(islands);\r\n html = html.replace('</body>', `${hydrationScript}</body>`);\r\n }\r\n\r\n // Add client hydration for 'use client' components\r\n if (isClientComponent) {\r\n const hydrationScript = generateClientHydrationScript(route.filePath, props);\r\n html = html.replace('</body>', `${hydrationScript}</body>`);\r\n }\r\n\r\n // Run after render hook\r\n html = await pluginManager.runWaterfallHook(\r\n PluginHooks.AFTER_RENDER,\r\n html,\r\n { route, Component, props }\r\n );\r\n\r\n res.writeHead(200, { 'Content-Type': 'text/html' });\r\n res.end(html);\r\n\r\n } catch (error) {\r\n console.error('Page Render Error:', error);\r\n throw error;\r\n }\r\n}\r\n\r\n/**\r\n * Serves a client component as JavaScript for hydration\r\n */\r\nasync function serveClientComponent(res, pagesDir, componentName) {\r\n const { transformSync } = await import('esbuild');\r\n \r\n // Remove .tsx.js or .jsx.js suffix if present\r\n const cleanName = componentName.replace(/\\.(tsx|jsx|ts|js)\\.js$/, '').replace(/\\.js$/, '');\r\n \r\n // Find the component file (support TypeScript)\r\n const possiblePaths = [\r\n path.join(pagesDir, `${cleanName}.tsx`),\r\n path.join(pagesDir, `${cleanName}.ts`),\r\n path.join(pagesDir, `${cleanName}.jsx`),\r\n path.join(pagesDir, `${cleanName}.js`),\r\n ];\r\n \r\n let componentPath = null;\r\n for (const p of possiblePaths) {\r\n if (fs.existsSync(p)) {\r\n componentPath = p;\r\n break;\r\n }\r\n }\r\n \r\n if (!componentPath) {\r\n res.writeHead(404, { 'Content-Type': 'text/plain' });\r\n res.end(`Component not found: ${cleanName}`);\r\n return;\r\n }\r\n \r\n // Determine loader based on extension\r\n const ext = path.extname(componentPath);\r\n const loader = ext === '.tsx' ? 'tsx' : ext === '.ts' ? 'ts' : 'jsx';\r\n \r\n try {\r\n let source = fs.readFileSync(componentPath, 'utf-8');\r\n \r\n // Remove 'use client' directive\r\n source = source.replace(/^['\"]use (client|server|island)['\"];?\\s*/m, '');\r\n \r\n // Transform for browser\r\n const result = transformSync(source, {\r\n loader,\r\n format: 'esm',\r\n jsx: 'transform',\r\n jsxFactory: 'React.createElement',\r\n jsxFragment: 'React.Fragment',\r\n target: 'es2020',\r\n // Replace React imports with global\r\n banner: `\r\n const React = window.React;\r\n const useState = window.useState;\r\n const useEffect = window.useEffect;\r\n const useCallback = window.useCallback;\r\n const useMemo = window.useMemo;\r\n const useRef = window.useRef;\r\n `\r\n });\r\n \r\n // Remove all React imports since we're using globals\r\n let code = result.code;\r\n // Remove: import React from 'react'\r\n code = code.replace(/import\\s+React\\s+from\\s+['\"]react['\"];?\\s*/g, '');\r\n // Remove: import { useState } from 'react'\r\n code = code.replace(/import\\s+\\{[^}]+\\}\\s+from\\s+['\"]react['\"];?\\s*/g, '');\r\n // Remove: import React, { useState } from 'react'\r\n code = code.replace(/import\\s+React\\s*,\\s*\\{[^}]+\\}\\s+from\\s+['\"]react['\"];?\\s*/g, '');\r\n \r\n res.writeHead(200, { \r\n 'Content-Type': 'application/javascript',\r\n 'Cache-Control': 'no-cache'\r\n });\r\n res.end(code);\r\n \r\n } catch (error) {\r\n console.error('Error serving client component:', error);\r\n res.writeHead(500, { 'Content-Type': 'text/plain' });\r\n res.end('Error compiling component');\r\n }\r\n}\r\n\r\n/**\r\n * Generates client hydration script for 'use client' components\r\n */\r\nfunction generateClientHydrationScript(componentPath, props) {\r\n // Create a relative path for the client bundle (handle .tsx, .ts, .jsx, .js)\r\n const ext = path.extname(componentPath);\r\n const componentName = path.basename(componentPath, ext);\r\n \r\n return `\r\n<script type=\"module\">\r\n // FlexiReact Client Hydration\r\n (async function() {\r\n try {\r\n const React = await import('https://esm.sh/react@18.3.1');\r\n const ReactDOM = await import('https://esm.sh/react-dom@18.3.1/client');\r\n \r\n // Make React available globally for the component\r\n window.React = React.default || React;\r\n window.useState = React.useState;\r\n window.useEffect = React.useEffect;\r\n window.useCallback = React.useCallback;\r\n window.useMemo = React.useMemo;\r\n window.useRef = React.useRef;\r\n \r\n // Fetch the component code\r\n const response = await fetch('/_flexi/component/${componentName}.js');\r\n const code = await response.text();\r\n \r\n // Create and import the module\r\n const blob = new Blob([code], { type: 'application/javascript' });\r\n const moduleUrl = URL.createObjectURL(blob);\r\n const module = await import(moduleUrl);\r\n \r\n const Component = module.default;\r\n const props = ${JSON.stringify(props)};\r\n \r\n // Hydrate the root\r\n const root = document.getElementById('root');\r\n ReactDOM.hydrateRoot(root, window.React.createElement(Component, props));\r\n \r\n console.log('⚡ FlexiReact: Component hydrated successfully');\r\n } catch (error) {\r\n console.error('⚡ FlexiReact: Hydration failed', error);\r\n }\r\n })();\r\n</script>`;\r\n}\r\n\r\n/**\r\n * Parses request body\r\n */\r\nasync function parseBody(req) {\r\n return new Promise((resolve) => {\r\n const contentType = req.headers['content-type'] || '';\r\n let body = '';\r\n\r\n req.on('data', chunk => {\r\n body += chunk.toString();\r\n });\r\n\r\n req.on('end', () => {\r\n try {\r\n if (contentType.includes('application/json') && body) {\r\n resolve(JSON.parse(body));\r\n } else if (contentType.includes('application/x-www-form-urlencoded') && body) {\r\n resolve(Object.fromEntries(new URLSearchParams(body)));\r\n } else {\r\n resolve(body || null);\r\n }\r\n } catch {\r\n resolve(body);\r\n }\r\n });\r\n\r\n req.on('error', () => resolve(null));\r\n });\r\n}\r\n\r\nexport default createServer;\r\n","/**\r\n * FlexiReact Middleware System\r\n * \r\n * Middlewares run before every request and can:\r\n * - Modify the request/response\r\n * - Redirect or rewrite URLs\r\n * - Add headers\r\n * - Authenticate users\r\n * - Log requests\r\n * \r\n * Usage:\r\n * Create a middleware.js file in your project root:\r\n * \r\n * export default function middleware(request) {\r\n * // Return a response to short-circuit\r\n * // Return NextResponse.next() to continue\r\n * // Return NextResponse.redirect() to redirect\r\n * }\r\n * \r\n * export const config = {\r\n * matcher: ['/protected/:path*']\r\n * };\r\n */\r\n\r\nimport fs from 'fs';\r\nimport path from 'path';\r\nimport { pathToFileURL } from 'url';\r\n\r\n/**\r\n * Middleware response helpers\r\n */\r\ninterface MiddlewareResponseOptions {\r\n type?: string;\r\n status?: number;\r\n headers?: Record<string, string>;\r\n body?: any;\r\n url?: string | null;\r\n}\r\n\r\nexport class MiddlewareResponse {\r\n type: string;\r\n status: number;\r\n headers: Map<string, string>;\r\n body: any;\r\n url: string | null;\r\n\r\n constructor(options: MiddlewareResponseOptions = {}) {\r\n this.type = options.type || 'next';\r\n this.status = options.status || 200;\r\n this.headers = new Map(Object.entries(options.headers || {}));\r\n this.body = options.body || null;\r\n this.url = options.url || null;\r\n }\r\n\r\n /**\r\n * Continue to the next middleware/handler\r\n */\r\n static next(options = {}) {\r\n return new MiddlewareResponse({ ...options, type: 'next' });\r\n }\r\n\r\n /**\r\n * Redirect to a different URL\r\n */\r\n static redirect(url, status = 302) {\r\n return new MiddlewareResponse({\r\n type: 'redirect',\r\n url,\r\n status\r\n });\r\n }\r\n\r\n /**\r\n * Rewrite the request to a different URL (internal)\r\n */\r\n static rewrite(url) {\r\n return new MiddlewareResponse({\r\n type: 'rewrite',\r\n url\r\n });\r\n }\r\n\r\n /**\r\n * Return a JSON response\r\n */\r\n static json(data: any, options: { status?: number; headers?: Record<string, string> } = {}) {\r\n return new MiddlewareResponse({\r\n type: 'response',\r\n status: options.status || 200,\r\n headers: { 'Content-Type': 'application/json', ...options.headers },\r\n body: JSON.stringify(data)\r\n });\r\n }\r\n\r\n /**\r\n * Return an HTML response\r\n */\r\n static html(content: string, options: { status?: number; headers?: Record<string, string> } = {}) {\r\n return new MiddlewareResponse({\r\n type: 'response',\r\n status: options.status || 200,\r\n headers: { 'Content-Type': 'text/html', ...options.headers },\r\n body: content\r\n });\r\n }\r\n}\r\n\r\n/**\r\n * Middleware request wrapper\r\n */\r\nexport class MiddlewareRequest {\r\n raw: any;\r\n method: string;\r\n url: string;\r\n headers: Map<string, string>;\r\n pathname: string;\r\n searchParams: URLSearchParams;\r\n query: Record<string, string>;\r\n cookies: Map<string, string>;\r\n\r\n constructor(req: any) {\r\n this.raw = req;\r\n this.method = req.method;\r\n this.url = req.url;\r\n this.headers = new Map(Object.entries(req.headers || {}));\r\n \r\n // Parse URL\r\n const parsedUrl = new URL(req.url, `http://${req.headers.host || 'localhost'}`);\r\n this.pathname = parsedUrl.pathname;\r\n this.searchParams = parsedUrl.searchParams;\r\n this.query = Object.fromEntries(parsedUrl.searchParams) as Record<string, string>;\r\n \r\n // Parse cookies\r\n this.cookies = this._parseCookies(req.headers.cookie || '');\r\n }\r\n\r\n _parseCookies(cookieHeader) {\r\n const cookies = new Map();\r\n if (!cookieHeader) return cookies;\r\n \r\n cookieHeader.split(';').forEach(cookie => {\r\n const [name, ...rest] = cookie.split('=');\r\n if (name) {\r\n cookies.set(name.trim(), rest.join('=').trim());\r\n }\r\n });\r\n \r\n return cookies;\r\n }\r\n\r\n /**\r\n * Get a header value\r\n */\r\n header(name) {\r\n return this.headers.get(name.toLowerCase());\r\n }\r\n\r\n /**\r\n * Get a cookie value\r\n */\r\n cookie(name) {\r\n return this.cookies.get(name);\r\n }\r\n\r\n /**\r\n * Check if request matches a path pattern\r\n */\r\n matches(pattern) {\r\n return matchPath(this.pathname, pattern);\r\n }\r\n}\r\n\r\n/**\r\n * Loads middleware from project\r\n */\r\nexport async function loadMiddleware(projectRoot) {\r\n const middlewarePath = path.join(projectRoot, 'middleware.js');\r\n \r\n if (!fs.existsSync(middlewarePath)) {\r\n return null;\r\n }\r\n\r\n try {\r\n const url = pathToFileURL(middlewarePath).href;\r\n const module = await import(`${url}?t=${Date.now()}`);\r\n \r\n return {\r\n handler: module.default,\r\n config: module.config || {}\r\n };\r\n } catch (error) {\r\n console.error('Failed to load middleware:', error);\r\n return null;\r\n }\r\n}\r\n\r\n/**\r\n * Runs middleware chain\r\n */\r\nexport async function runMiddleware(req, res, middleware) {\r\n if (!middleware) {\r\n return { continue: true };\r\n }\r\n\r\n const { handler, config } = middleware;\r\n const request = new MiddlewareRequest(req);\r\n\r\n // Check if request matches middleware patterns\r\n if (config.matcher) {\r\n const patterns = Array.isArray(config.matcher) ? config.matcher : [config.matcher];\r\n const matches = patterns.some(pattern => matchPath(request.pathname, pattern));\r\n \r\n if (!matches) {\r\n return { continue: true };\r\n }\r\n }\r\n\r\n try {\r\n const response = await handler(request);\r\n\r\n if (!response || response.type === 'next') {\r\n // Apply any headers from middleware\r\n if (response?.headers) {\r\n for (const [key, value] of response.headers) {\r\n res.setHeader(key, value);\r\n }\r\n }\r\n return { continue: true };\r\n }\r\n\r\n if (response.type === 'redirect') {\r\n res.writeHead(response.status, { Location: response.url });\r\n res.end();\r\n return { continue: false };\r\n }\r\n\r\n if (response.type === 'rewrite') {\r\n // Modify the request URL internally\r\n req.url = response.url;\r\n return { continue: true, rewritten: true };\r\n }\r\n\r\n if (response.type === 'response') {\r\n // Apply headers\r\n for (const [key, value] of response.headers) {\r\n res.setHeader(key, value);\r\n }\r\n res.writeHead(response.status);\r\n res.end(response.body);\r\n return { continue: false };\r\n }\r\n\r\n return { continue: true };\r\n\r\n } catch (error) {\r\n console.error('Middleware error:', error);\r\n return { continue: true, error };\r\n }\r\n}\r\n\r\n/**\r\n * Matches a path against a pattern\r\n */\r\nfunction matchPath(pathname, pattern) {\r\n // Convert pattern to regex\r\n let regex = pattern\r\n .replace(/\\*/g, '.*')\r\n .replace(/:path\\*/g, '.*')\r\n .replace(/:(\\w+)/g, '[^/]+');\r\n \r\n regex = `^${regex}$`;\r\n \r\n return new RegExp(regex).test(pathname);\r\n}\r\n\r\n/**\r\n * Compose multiple middleware functions\r\n */\r\nexport function composeMiddleware(...middlewares) {\r\n return async (request) => {\r\n for (const middleware of middlewares) {\r\n const response = await middleware(request);\r\n \r\n if (response && response.type !== 'next') {\r\n return response;\r\n }\r\n }\r\n \r\n return MiddlewareResponse.next();\r\n };\r\n}\r\n\r\n/**\r\n * Built-in middleware helpers\r\n */\r\nexport const middlewares = {\r\n /**\r\n * CORS middleware\r\n */\r\n cors(options: { origin?: string; methods?: string; headers?: string; credentials?: boolean } = {}) {\r\n const {\r\n origin = '*',\r\n methods = 'GET,HEAD,PUT,PATCH,POST,DELETE',\r\n headers = 'Content-Type,Authorization',\r\n credentials = false\r\n } = options;\r\n\r\n return (request) => {\r\n const response = MiddlewareResponse.next({\r\n headers: {\r\n 'Access-Control-Allow-Origin': origin,\r\n 'Access-Control-Allow-Methods': methods,\r\n 'Access-Control-Allow-Headers': headers,\r\n ...(credentials && { 'Access-Control-Allow-Credentials': 'true' })\r\n }\r\n });\r\n\r\n // Handle preflight\r\n if (request.method === 'OPTIONS') {\r\n return MiddlewareResponse.json({}, { status: 204, headers: Object.fromEntries(response.headers) });\r\n }\r\n\r\n return response;\r\n };\r\n },\r\n\r\n /**\r\n * Basic auth middleware\r\n */\r\n basicAuth(options) {\r\n const { username, password, realm = 'Protected' } = options;\r\n const expected = Buffer.from(`${username}:${password}`).toString('base64');\r\n\r\n return (request) => {\r\n const auth = request.header('authorization');\r\n \r\n if (!auth || !auth.startsWith('Basic ')) {\r\n return MiddlewareResponse.html('Unauthorized', {\r\n status: 401,\r\n headers: { 'WWW-Authenticate': `Basic realm=\"${realm}\"` }\r\n });\r\n }\r\n\r\n const provided = auth.slice(6);\r\n if (provided !== expected) {\r\n return MiddlewareResponse.html('Unauthorized', { status: 401 });\r\n }\r\n\r\n return MiddlewareResponse.next();\r\n };\r\n },\r\n\r\n /**\r\n * Rate limiting middleware\r\n */\r\n rateLimit(options: { windowMs?: number; max?: number } = {}) {\r\n const { windowMs = 60000, max = 100 } = options;\r\n const requests = new Map();\r\n\r\n return (request) => {\r\n const ip = request.header('x-forwarded-for') || 'unknown';\r\n const now = Date.now();\r\n \r\n // Clean old entries\r\n for (const [key, data] of requests) {\r\n if (now - data.start > windowMs) {\r\n requests.delete(key);\r\n }\r\n }\r\n\r\n // Check rate limit\r\n const data = requests.get(ip) || { count: 0, start: now };\r\n data.count++;\r\n requests.set(ip, data);\r\n\r\n if (data.count > max) {\r\n return MiddlewareResponse.json(\r\n { error: 'Too many requests' },\r\n { status: 429 }\r\n );\r\n }\r\n\r\n return MiddlewareResponse.next({\r\n headers: {\r\n 'X-RateLimit-Limit': String(max),\r\n 'X-RateLimit-Remaining': String(max - data.count)\r\n }\r\n });\r\n };\r\n },\r\n\r\n /**\r\n * Logging middleware\r\n */\r\n logger(options: { format?: string } = {}) {\r\n const { format = 'combined' } = options;\r\n\r\n return (request) => {\r\n const start = Date.now();\r\n const { method, pathname } = request;\r\n \r\n console.log(`→ ${method} ${pathname}`);\r\n \r\n return MiddlewareResponse.next();\r\n };\r\n }\r\n};\r\n\r\nexport default {\r\n MiddlewareRequest,\r\n MiddlewareResponse,\r\n loadMiddleware,\r\n runMiddleware,\r\n composeMiddleware,\r\n middlewares\r\n};\r\n","/**\r\n * FlexiReact Plugin System\r\n * \r\n * Plugins can extend FlexiReact's functionality by hooking into various lifecycle events.\r\n * \r\n * Usage:\r\n * Create a flexireact.plugin.js file:\r\n * \r\n * export default {\r\n * name: 'my-plugin',\r\n * \r\n * // Called when the server starts\r\n * onServerStart(server) {},\r\n * \r\n * // Called before each request\r\n * onRequest(req, res) {},\r\n * \r\n * // Called before rendering a page\r\n * onBeforeRender(page, props) {},\r\n * \r\n * // Called after rendering a page\r\n * onAfterRender(html, page) {},\r\n * \r\n * // Called during build\r\n * onBuild(config) {},\r\n * \r\n * // Modify esbuild config\r\n * esbuildConfig(config) {},\r\n * };\r\n */\r\n\r\nimport fs from 'fs';\r\nimport path from 'path';\r\nimport { pathToFileURL } from 'url';\r\n\r\n/**\r\n * Plugin lifecycle hooks\r\n */\r\nexport const PluginHooks = {\r\n // Server lifecycle\r\n SERVER_START: 'onServerStart',\r\n SERVER_STOP: 'onServerStop',\r\n \r\n // Request lifecycle\r\n REQUEST: 'onRequest',\r\n RESPONSE: 'onResponse',\r\n \r\n // Render lifecycle\r\n BEFORE_RENDER: 'onBeforeRender',\r\n AFTER_RENDER: 'onAfterRender',\r\n \r\n // Build lifecycle\r\n BUILD_START: 'onBuildStart',\r\n BUILD_END: 'onBuildEnd',\r\n \r\n // Route lifecycle\r\n ROUTES_LOADED: 'onRoutesLoaded',\r\n \r\n // Config\r\n CONFIG: 'onConfig',\r\n ESBUILD_CONFIG: 'esbuildConfig'\r\n};\r\n\r\n/**\r\n * Plugin manager class\r\n */\r\nexport class PluginManager {\r\n plugins: any[];\r\n hooks: Map<string, any[]>;\r\n\r\n constructor() {\r\n this.plugins = [];\r\n this.hooks = new Map();\r\n \r\n // Initialize hook arrays\r\n for (const hook of Object.values(PluginHooks)) {\r\n this.hooks.set(hook as string, []);\r\n }\r\n }\r\n\r\n /**\r\n * Registers a plugin\r\n */\r\n register(plugin) {\r\n if (!plugin.name) {\r\n throw new Error('Plugin must have a name');\r\n }\r\n\r\n // Check for duplicate\r\n if (this.plugins.find(p => p.name === plugin.name)) {\r\n console.warn(`Plugin \"${plugin.name}\" is already registered`);\r\n return;\r\n }\r\n\r\n this.plugins.push(plugin);\r\n\r\n // Register hooks\r\n for (const [hookName, handlers] of this.hooks) {\r\n if (typeof plugin[hookName] === 'function') {\r\n handlers.push({\r\n plugin: plugin.name,\r\n handler: plugin[hookName].bind(plugin)\r\n });\r\n }\r\n }\r\n\r\n console.log(` ✓ Plugin loaded: ${plugin.name}`);\r\n }\r\n\r\n /**\r\n * Unregisters a plugin\r\n */\r\n unregister(pluginName) {\r\n const index = this.plugins.findIndex(p => p.name === pluginName);\r\n if (index === -1) return;\r\n\r\n this.plugins.splice(index, 1);\r\n\r\n // Remove hooks\r\n for (const handlers of this.hooks.values()) {\r\n const hookIndex = handlers.findIndex(h => h.plugin === pluginName);\r\n if (hookIndex !== -1) {\r\n handlers.splice(hookIndex, 1);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Runs a hook with all registered handlers\r\n */\r\n async runHook(hookName, ...args) {\r\n const handlers = this.hooks.get(hookName) || [];\r\n const results = [];\r\n\r\n for (const { plugin, handler } of handlers) {\r\n try {\r\n const result = await handler(...args);\r\n results.push({ plugin, result });\r\n } catch (error) {\r\n console.error(`Plugin \"${plugin}\" error in ${hookName}:`, error);\r\n results.push({ plugin, error });\r\n }\r\n }\r\n\r\n return results;\r\n }\r\n\r\n /**\r\n * Runs a hook that can modify a value (waterfall)\r\n */\r\n async runWaterfallHook(hookName, initialValue, ...args) {\r\n const handlers = this.hooks.get(hookName) || [];\r\n let value = initialValue;\r\n\r\n for (const { plugin, handler } of handlers) {\r\n try {\r\n const result = await handler(value, ...args);\r\n if (result !== undefined) {\r\n value = result;\r\n }\r\n } catch (error) {\r\n console.error(`Plugin \"${plugin}\" error in ${hookName}:`, error);\r\n }\r\n }\r\n\r\n return value;\r\n }\r\n\r\n /**\r\n * Checks if any plugin handles a hook\r\n */\r\n hasHook(hookName) {\r\n const handlers = this.hooks.get(hookName) || [];\r\n return handlers.length > 0;\r\n }\r\n\r\n /**\r\n * Gets all registered plugins\r\n */\r\n getPlugins() {\r\n return [...this.plugins];\r\n }\r\n}\r\n\r\n// Global plugin manager instance\r\nexport const pluginManager = new PluginManager();\r\n\r\n/**\r\n * Loads plugins from project and config\r\n */\r\nexport async function loadPlugins(projectRoot, config) {\r\n console.log('\\n📦 Loading plugins...\\n');\r\n\r\n // Load from flexireact.plugin.js\r\n const pluginPath = path.join(projectRoot, 'flexireact.plugin.js');\r\n \r\n if (fs.existsSync(pluginPath)) {\r\n try {\r\n const url = pathToFileURL(pluginPath).href;\r\n const module = await import(`${url}?t=${Date.now()}`);\r\n const plugin = module.default;\r\n \r\n if (plugin) {\r\n pluginManager.register(plugin);\r\n }\r\n } catch (error) {\r\n console.error('Failed to load flexireact.plugin.js:', error);\r\n }\r\n }\r\n\r\n // Load plugins from config\r\n if (config.plugins && Array.isArray(config.plugins)) {\r\n for (const pluginConfig of config.plugins) {\r\n try {\r\n if (typeof pluginConfig === 'string') {\r\n // Load from node_modules\r\n const module = await import(pluginConfig);\r\n pluginManager.register(module.default);\r\n } else if (typeof pluginConfig === 'object') {\r\n // Inline plugin\r\n pluginManager.register(pluginConfig);\r\n } else if (typeof pluginConfig === 'function') {\r\n // Plugin factory\r\n pluginManager.register(pluginConfig());\r\n }\r\n } catch (error) {\r\n console.error(`Failed to load plugin:`, error);\r\n }\r\n }\r\n }\r\n\r\n console.log(`\\n Total plugins: ${pluginManager.getPlugins().length}\\n`);\r\n\r\n return pluginManager;\r\n}\r\n\r\n/**\r\n * Creates a plugin\r\n */\r\nexport function definePlugin(options) {\r\n return {\r\n name: options.name || 'unnamed-plugin',\r\n ...options\r\n };\r\n}\r\n\r\n/**\r\n * Built-in plugins\r\n */\r\nexport const builtinPlugins = {\r\n /**\r\n * Analytics plugin\r\n */\r\n analytics(options: { trackingId?: string } = {}) {\r\n const { trackingId } = options;\r\n\r\n return definePlugin({\r\n name: 'flexi-analytics',\r\n\r\n onAfterRender(html) {\r\n if (!trackingId) return html;\r\n\r\n const script = `\r\n <script async src=\"https://www.googletagmanager.com/gtag/js?id=${trackingId}\"></script>\r\n <script>\r\n window.dataLayer = window.dataLayer || [];\r\n function gtag(){dataLayer.push(arguments);}\r\n gtag('js', new Date());\r\n gtag('config', '${trackingId}');\r\n </script>\r\n `;\r\n\r\n return html.replace('</head>', `${script}</head>`);\r\n }\r\n });\r\n },\r\n\r\n /**\r\n * PWA plugin\r\n */\r\n pwa(options: { manifest?: string; serviceWorker?: string } = {}) {\r\n const { manifest = '/manifest.json', serviceWorker = '/sw.js' } = options;\r\n\r\n return definePlugin({\r\n name: 'flexi-pwa',\r\n\r\n onAfterRender(html) {\r\n const tags = `\r\n <link rel=\"manifest\" href=\"${manifest}\">\r\n <script>\r\n if ('serviceWorker' in navigator) {\r\n navigator.serviceWorker.register('${serviceWorker}');\r\n }\r\n </script>\r\n `;\r\n\r\n return html.replace('</head>', `${tags}</head>`);\r\n }\r\n });\r\n },\r\n\r\n /**\r\n * SEO plugin\r\n */\r\n seo(options: { defaultTitle?: string; titleTemplate?: string; defaultDescription?: string } = {}) {\r\n const { defaultTitle, titleTemplate = '%s', defaultDescription } = options;\r\n\r\n return definePlugin({\r\n name: 'flexi-seo',\r\n\r\n onBeforeRender(page, props) {\r\n const title = props.title || page.title || defaultTitle;\r\n const description = props.description || page.description || defaultDescription;\r\n\r\n return {\r\n ...props,\r\n _seo: {\r\n title: titleTemplate.replace('%s', title),\r\n description\r\n }\r\n };\r\n }\r\n });\r\n },\r\n\r\n /**\r\n * Compression plugin (for production)\r\n */\r\n compression() {\r\n return definePlugin({\r\n name: 'flexi-compression',\r\n\r\n onResponse(req, res, html) {\r\n // Note: Actual compression would require zlib\r\n // This is a placeholder for the concept\r\n res.setHeader('Content-Encoding', 'identity');\r\n return html;\r\n }\r\n });\r\n },\r\n\r\n /**\r\n * Security headers plugin\r\n */\r\n securityHeaders(options: { headers?: Record<string, string> } = {}) {\r\n const headers: Record<string, string> = {\r\n 'X-Content-Type-Options': 'nosniff',\r\n 'X-Frame-Options': 'DENY',\r\n 'X-XSS-Protection': '1; mode=block',\r\n 'Referrer-Policy': 'strict-origin-when-cross-origin',\r\n ...options.headers\r\n };\r\n\r\n return definePlugin({\r\n name: 'flexi-security',\r\n\r\n onRequest(req, res) {\r\n for (const [key, value] of Object.entries(headers)) {\r\n res.setHeader(key, value);\r\n }\r\n }\r\n });\r\n }\r\n};\r\n\r\nexport default {\r\n PluginManager,\r\n PluginHooks,\r\n pluginManager,\r\n loadPlugins,\r\n definePlugin,\r\n builtinPlugins\r\n};\r\n","/**\r\n * FlexiReact Islands Architecture\r\n * \r\n * Islands allow partial hydration - only interactive components are hydrated on the client,\r\n * while static content remains as HTML. This dramatically reduces JavaScript bundle size.\r\n * \r\n * Usage:\r\n * - Add 'use island' at the top of a component file\r\n * - The component will be rendered on server and hydrated on client\r\n * - Non-island components are pure HTML (no JS)\r\n */\r\n\r\nimport React from 'react';\r\nimport { renderToString } from 'react-dom/server';\r\nimport crypto from 'crypto';\r\n\r\n// Island registry for tracking all islands in a render\r\nconst islandRegistry = new Map();\r\n\r\n/**\r\n * Generates a unique island ID\r\n */\r\nfunction generateIslandId(componentName) {\r\n const hash = crypto.randomBytes(4).toString('hex');\r\n return `island-${componentName}-${hash}`;\r\n}\r\n\r\n/**\r\n * Island wrapper component for server-side rendering\r\n */\r\nexport function Island({ component: Component, props = {}, name, clientPath }) {\r\n const islandId = generateIslandId(name);\r\n \r\n // Register island for hydration\r\n islandRegistry.set(islandId, {\r\n id: islandId,\r\n name,\r\n clientPath,\r\n props\r\n });\r\n\r\n // Render the component\r\n const content = renderToString(React.createElement(Component, props));\r\n\r\n // Return wrapper with hydration marker\r\n return React.createElement('div', {\r\n 'data-island': islandId,\r\n 'data-island-name': name,\r\n 'data-island-props': JSON.stringify(props),\r\n dangerouslySetInnerHTML: { __html: content }\r\n });\r\n}\r\n\r\n/**\r\n * Gets all registered islands and clears the registry\r\n */\r\nexport function getRegisteredIslands() {\r\n const islands = Array.from(islandRegistry.values());\r\n islandRegistry.clear();\r\n return islands;\r\n}\r\n\r\n/**\r\n * Creates an island component wrapper\r\n */\r\ninterface IslandOptions {\r\n name?: string;\r\n clientPath?: string;\r\n}\r\n\r\nexport function createIsland(Component: React.ComponentType<any>, options: IslandOptions = {}) {\r\n const { name = (Component as any).name || 'Island', clientPath } = options;\r\n\r\n function IslandWrapper(props) {\r\n return Island({\r\n component: Component,\r\n props,\r\n name,\r\n clientPath: clientPath || `/_flexi/islands/${name}.js`\r\n });\r\n }\r\n\r\n IslandWrapper.displayName = `Island(${name})`;\r\n IslandWrapper.isIsland = true;\r\n IslandWrapper.originalComponent = Component;\r\n\r\n return IslandWrapper;\r\n}\r\n\r\n/**\r\n * Generates the client-side hydration script\r\n */\r\nexport function generateHydrationScript(islands) {\r\n if (!islands.length) return '';\r\n\r\n const islandData = islands.map(island => ({\r\n id: island.id,\r\n name: island.name,\r\n path: island.clientPath,\r\n props: island.props\r\n }));\r\n\r\n return `\r\n<script type=\"module\">\r\n const islands = ${JSON.stringify(islandData)};\r\n \r\n async function hydrateIslands() {\r\n const { hydrateRoot } = await import('/_flexi/react-dom-client.js');\r\n const React = await import('/_flexi/react.js');\r\n \r\n for (const island of islands) {\r\n try {\r\n const element = document.querySelector(\\`[data-island=\"\\${island.id}\"]\\`);\r\n if (!element) continue;\r\n \r\n const module = await import(island.path);\r\n const Component = module.default;\r\n \r\n // Hydrate the island\r\n hydrateRoot(element, React.createElement(Component, island.props));\r\n \r\n // Mark as hydrated\r\n element.setAttribute('data-hydrated', 'true');\r\n } catch (error) {\r\n console.error(\\`Failed to hydrate island \\${island.name}:\\`, error);\r\n }\r\n }\r\n }\r\n \r\n // Hydrate when DOM is ready\r\n if (document.readyState === 'loading') {\r\n document.addEventListener('DOMContentLoaded', hydrateIslands);\r\n } else {\r\n hydrateIslands();\r\n }\r\n</script>`;\r\n}\r\n\r\n/**\r\n * Island loading strategies\r\n */\r\nexport const LoadStrategy = {\r\n // Hydrate immediately when page loads\r\n IMMEDIATE: 'immediate',\r\n // Hydrate when island becomes visible\r\n VISIBLE: 'visible',\r\n // Hydrate when user interacts with the page\r\n IDLE: 'idle',\r\n // Hydrate on specific media query\r\n MEDIA: 'media'\r\n};\r\n\r\n/**\r\n * Creates a lazy island that hydrates based on strategy\r\n */\r\ninterface LazyIslandOptions {\r\n name?: string;\r\n clientPath?: string;\r\n strategy?: string;\r\n media?: string | null;\r\n}\r\n\r\nexport function createLazyIsland(Component: React.ComponentType<any>, options: LazyIslandOptions = {}) {\r\n const {\r\n name = (Component as any).name || 'LazyIsland',\r\n clientPath,\r\n strategy = LoadStrategy.VISIBLE,\r\n media = null\r\n } = options;\r\n\r\n function LazyIslandWrapper(props) {\r\n const islandId = generateIslandId(name);\r\n const content = renderToString(React.createElement(Component, props));\r\n\r\n // Register with loading strategy\r\n islandRegistry.set(islandId, {\r\n id: islandId,\r\n name,\r\n clientPath: clientPath || `/_flexi/islands/${name}.js`,\r\n props,\r\n strategy,\r\n media\r\n });\r\n\r\n return React.createElement('div', {\r\n 'data-island': islandId,\r\n 'data-island-name': name,\r\n 'data-island-strategy': strategy,\r\n 'data-island-media': media,\r\n 'data-island-props': JSON.stringify(props),\r\n dangerouslySetInnerHTML: { __html: content }\r\n });\r\n }\r\n\r\n LazyIslandWrapper.displayName = `LazyIsland(${name})`;\r\n LazyIslandWrapper.isIsland = true;\r\n LazyIslandWrapper.isLazy = true;\r\n\r\n return LazyIslandWrapper;\r\n}\r\n\r\n/**\r\n * Generates advanced hydration script with loading strategies\r\n */\r\nexport function generateAdvancedHydrationScript(islands) {\r\n if (!islands.length) return '';\r\n\r\n const islandData = islands.map(island => ({\r\n id: island.id,\r\n name: island.name,\r\n path: island.clientPath,\r\n props: island.props,\r\n strategy: island.strategy || LoadStrategy.IMMEDIATE,\r\n media: island.media\r\n }));\r\n\r\n return `\r\n<script type=\"module\">\r\n const islands = ${JSON.stringify(islandData)};\r\n \r\n async function hydrateIsland(island) {\r\n const element = document.querySelector(\\`[data-island=\"\\${island.id}\"]\\`);\r\n if (!element || element.hasAttribute('data-hydrated')) return;\r\n \r\n try {\r\n const { hydrateRoot } = await import('/_flexi/react-dom-client.js');\r\n const React = await import('/_flexi/react.js');\r\n const module = await import(island.path);\r\n const Component = module.default;\r\n \r\n hydrateRoot(element, React.createElement(Component, island.props));\r\n element.setAttribute('data-hydrated', 'true');\r\n } catch (error) {\r\n console.error(\\`Failed to hydrate island \\${island.name}:\\`, error);\r\n }\r\n }\r\n \r\n // Intersection Observer for visible strategy\r\n const visibleObserver = new IntersectionObserver((entries) => {\r\n entries.forEach(entry => {\r\n if (entry.isIntersecting) {\r\n const id = entry.target.getAttribute('data-island');\r\n const island = islands.find(i => i.id === id);\r\n if (island) {\r\n hydrateIsland(island);\r\n visibleObserver.unobserve(entry.target);\r\n }\r\n }\r\n });\r\n }, { rootMargin: '50px' });\r\n \r\n // Process islands based on strategy\r\n function processIslands() {\r\n for (const island of islands) {\r\n const element = document.querySelector(\\`[data-island=\"\\${island.id}\"]\\`);\r\n if (!element) continue;\r\n \r\n switch (island.strategy) {\r\n case 'immediate':\r\n hydrateIsland(island);\r\n break;\r\n case 'visible':\r\n visibleObserver.observe(element);\r\n break;\r\n case 'idle':\r\n requestIdleCallback(() => hydrateIsland(island));\r\n break;\r\n case 'media':\r\n if (island.media && window.matchMedia(island.media).matches) {\r\n hydrateIsland(island);\r\n }\r\n break;\r\n }\r\n }\r\n }\r\n \r\n if (document.readyState === 'loading') {\r\n document.addEventListener('DOMContentLoaded', processIslands);\r\n } else {\r\n processIslands();\r\n }\r\n</script>`;\r\n}\r\n\r\nexport default {\r\n Island,\r\n createIsland,\r\n createLazyIsland,\r\n getRegisteredIslands,\r\n generateHydrationScript,\r\n generateAdvancedHydrationScript,\r\n LoadStrategy\r\n};\r\n","/**\r\n * FlexiReact Logger\r\n * Premium console output inspired by Next.js, Vite, and Bun\r\n */\r\n\r\n// ANSI color codes\r\nconst colors = {\r\n reset: '\\x1b[0m',\r\n bold: '\\x1b[1m',\r\n dim: '\\x1b[2m',\r\n italic: '\\x1b[3m',\r\n underline: '\\x1b[4m',\r\n \r\n // Text colors\r\n black: '\\x1b[30m',\r\n red: '\\x1b[31m',\r\n green: '\\x1b[32m',\r\n yellow: '\\x1b[33m',\r\n blue: '\\x1b[34m',\r\n magenta: '\\x1b[35m',\r\n cyan: '\\x1b[36m',\r\n white: '\\x1b[37m',\r\n gray: '\\x1b[90m',\r\n \r\n // Bright colors\r\n brightRed: '\\x1b[91m',\r\n brightGreen: '\\x1b[92m',\r\n brightYellow: '\\x1b[93m',\r\n brightBlue: '\\x1b[94m',\r\n brightMagenta: '\\x1b[95m',\r\n brightCyan: '\\x1b[96m',\r\n brightWhite: '\\x1b[97m',\r\n \r\n // Background colors\r\n bgRed: '\\x1b[41m',\r\n bgGreen: '\\x1b[42m',\r\n bgYellow: '\\x1b[43m',\r\n bgBlue: '\\x1b[44m',\r\n bgMagenta: '\\x1b[45m',\r\n bgCyan: '\\x1b[46m',\r\n};\r\n\r\nconst c = colors;\r\n\r\n// Get current time formatted\r\nfunction getTime() {\r\n const now = new Date();\r\n return `${c.dim}${now.toLocaleTimeString('en-US', { hour12: false })}${c.reset}`;\r\n}\r\n\r\n// Status code colors\r\nfunction getStatusColor(status) {\r\n if (status >= 500) return c.red;\r\n if (status >= 400) return c.yellow;\r\n if (status >= 300) return c.cyan;\r\n if (status >= 200) return c.green;\r\n return c.white;\r\n}\r\n\r\n// Method colors\r\nfunction getMethodColor(method) {\r\n const methodColors = {\r\n GET: c.brightGreen,\r\n POST: c.brightBlue,\r\n PUT: c.brightYellow,\r\n PATCH: c.brightMagenta,\r\n DELETE: c.brightRed,\r\n OPTIONS: c.gray,\r\n HEAD: c.gray,\r\n };\r\n return methodColors[method] || c.white;\r\n}\r\n\r\n// Format time\r\nfunction formatTime(ms) {\r\n if (ms < 1) return `${c.gray}<1ms${c.reset}`;\r\n if (ms < 100) return `${c.green}${ms}ms${c.reset}`;\r\n if (ms < 500) return `${c.yellow}${ms}ms${c.reset}`;\r\n return `${c.red}${ms}ms${c.reset}`;\r\n}\r\n\r\n// FlexiReact ASCII Logo - Premium Design\r\nconst LOGO = `\r\n${c.green} ╭─────────────────────────────────────────────╮${c.reset}\r\n${c.green} │${c.reset} ${c.green}│${c.reset}\r\n${c.green} │${c.reset} ${c.brightGreen}⚡${c.reset} ${c.bold}${c.white}F L E X I R E A C T${c.reset} ${c.dim}v1.0.0${c.reset} ${c.green}│${c.reset}\r\n${c.green} │${c.reset} ${c.green}│${c.reset}\r\n${c.green} │${c.reset} ${c.dim}The Modern React Framework${c.reset} ${c.green}│${c.reset}\r\n${c.green} │${c.reset} ${c.green}│${c.reset}\r\n${c.green} ╰─────────────────────────────────────────────╯${c.reset}\r\n`;\r\n\r\nconst MINI_LOGO = `${c.brightGreen}⚡${c.reset} ${c.bold}FlexiReact${c.reset}`;\r\n\r\n// Compact ready message like Next.js\r\nconst READY_MSG = ` ${c.green}▲${c.reset} ${c.bold}Ready${c.reset} in`;\r\n\r\nexport const logger = {\r\n // Show startup logo\r\n logo() {\r\n console.log(LOGO);\r\n },\r\n\r\n // Server started - Next.js style\r\n serverStart(config, startTime = Date.now()) {\r\n const { port, host, mode, pagesDir, islands, rsc } = config;\r\n const elapsed = Date.now() - startTime;\r\n \r\n console.log('');\r\n console.log(` ${c.green}▲${c.reset} ${c.bold}Ready${c.reset} in ${c.cyan}${elapsed}ms${c.reset}`);\r\n console.log('');\r\n console.log(` ${c.dim}┌${c.reset} ${c.bold}Local:${c.reset} ${c.cyan}http://${host}:${port}${c.reset}`);\r\n console.log(` ${c.dim}├${c.reset} ${c.bold}Environment:${c.reset} ${mode === 'development' ? `${c.yellow}development${c.reset}` : `${c.green}production${c.reset}`}`);\r\n if (islands) {\r\n console.log(` ${c.dim}├${c.reset} ${c.bold}Islands:${c.reset} ${c.green}enabled${c.reset}`);\r\n }\r\n if (rsc) {\r\n console.log(` ${c.dim}├${c.reset} ${c.bold}RSC:${c.reset} ${c.green}enabled${c.reset}`);\r\n }\r\n console.log(` ${c.dim}└${c.reset} ${c.bold}Pages:${c.reset} ${c.dim}${pagesDir}${c.reset}`);\r\n console.log('');\r\n },\r\n\r\n // HTTP request log - Compact single line like Next.js\r\n request(method: string, path: string, status: number, time: number, extra: { type?: string } = {}) {\r\n const methodColor = getMethodColor(method);\r\n const statusColor = getStatusColor(status);\r\n const timeStr = formatTime(time);\r\n \r\n // Route type badge\r\n let badge = '';\r\n if (extra.type === 'static' || extra.type === 'ssg') {\r\n badge = `${c.dim}○${c.reset}`; // Static\r\n } else if (extra.type === 'dynamic' || extra.type === 'ssr') {\r\n badge = `${c.magenta}ƒ${c.reset}`; // Function/SSR\r\n } else if (extra.type === 'api') {\r\n badge = `${c.blue}λ${c.reset}`; // API\r\n } else if (extra.type === 'asset') {\r\n badge = `${c.dim}◦${c.reset}`; // Asset\r\n } else {\r\n badge = `${c.magenta}ƒ${c.reset}`;\r\n }\r\n \r\n const statusStr = `${statusColor}${status}${c.reset}`;\r\n const methodStr = `${methodColor}${method}${c.reset}`;\r\n \r\n // Single line format like Next.js\r\n console.log(` ${badge} ${methodStr} ${path} ${statusStr} ${c.dim}in${c.reset} ${timeStr}`);\r\n },\r\n\r\n // Info message\r\n info(msg) {\r\n console.log(` ${c.cyan}ℹ${c.reset} ${msg}`);\r\n },\r\n\r\n // Success message\r\n success(msg) {\r\n console.log(` ${c.green}✓${c.reset} ${msg}`);\r\n },\r\n\r\n // Warning message\r\n warn(msg) {\r\n console.log(` ${c.yellow}⚠${c.reset} ${c.yellow}${msg}${c.reset}`);\r\n },\r\n\r\n // Error message\r\n error(msg, err = null) {\r\n console.log(` ${c.red}✗${c.reset} ${c.red}${msg}${c.reset}`);\r\n if (err && err.stack) {\r\n const stack = err.stack.split('\\n').slice(1, 4).join('\\n');\r\n console.log(`${c.dim}${stack}${c.reset}`);\r\n }\r\n },\r\n\r\n // Compilation message\r\n compile(file, time) {\r\n console.log(` ${c.magenta}◉${c.reset} Compiled ${c.cyan}${file}${c.reset} ${c.dim}(${time}ms)${c.reset}`);\r\n },\r\n\r\n // Hot reload\r\n hmr(file) {\r\n console.log(` ${c.yellow}↻${c.reset} HMR update: ${c.cyan}${file}${c.reset}`);\r\n },\r\n\r\n // Plugin loaded\r\n plugin(name) {\r\n console.log(` ${c.blue}⬡${c.reset} Plugin: ${c.cyan}${name}${c.reset}`);\r\n },\r\n\r\n // Route info\r\n route(path, type) {\r\n const typeColors = {\r\n static: c.green,\r\n dynamic: c.yellow,\r\n api: c.blue,\r\n };\r\n const color = typeColors[type] || c.white;\r\n console.log(` ${c.dim}├─${c.reset} ${path} ${color}[${type}]${c.reset}`);\r\n },\r\n\r\n // Divider\r\n divider() {\r\n console.log(`${c.dim} ─────────────────────────────────────────${c.reset}`);\r\n },\r\n\r\n // Blank line\r\n blank() {\r\n console.log('');\r\n },\r\n\r\n // Port in use error with solution\r\n portInUse(port) {\r\n console.log(`\r\n${c.red} ✗ Port ${port} is already in use${c.reset}\r\n\r\n ${c.dim}Try one of these solutions:${c.reset}\r\n \r\n ${c.yellow}1.${c.reset} Kill the process using the port:\r\n ${c.cyan}npx kill-port ${port}${c.reset}\r\n \r\n ${c.yellow}2.${c.reset} Use a different port in ${c.cyan}flexireact.config.js${c.reset}:\r\n ${c.dim}server: { port: 3001 }${c.reset}\r\n \r\n ${c.yellow}3.${c.reset} Set PORT environment variable:\r\n ${c.cyan}PORT=3001 npm run dev${c.reset}\r\n`);\r\n },\r\n\r\n // Build info\r\n build(stats) {\r\n console.log(`\r\n ${c.green}✓${c.reset} Build complete!\r\n \r\n ${c.dim}├─${c.reset} Pages: ${c.cyan}${stats.pages}${c.reset}\r\n ${c.dim}├─${c.reset} API: ${c.cyan}${stats.api}${c.reset}\r\n ${c.dim}├─${c.reset} Assets: ${c.cyan}${stats.assets}${c.reset}\r\n ${c.dim}└─${c.reset} Time: ${c.green}${stats.time}ms${c.reset}\r\n`);\r\n },\r\n};\r\n\r\nexport default logger;\r\n","/**\r\n * FlexiReact Server Helpers\r\n * Utility functions for server-side operations\r\n */\r\n\r\n// ============================================================================\r\n// Response Helpers\r\n// ============================================================================\r\n\r\n/**\r\n * Custom error classes for control flow\r\n */\r\nexport class RedirectError extends Error {\r\n public readonly url: string;\r\n public readonly statusCode: number;\r\n public readonly type = 'redirect' as const;\r\n\r\n constructor(url: string, statusCode: number = 307) {\r\n super(`Redirect to ${url}`);\r\n this.name = 'RedirectError';\r\n this.url = url;\r\n this.statusCode = statusCode;\r\n }\r\n}\r\n\r\nexport class NotFoundError extends Error {\r\n public readonly type = 'notFound' as const;\r\n\r\n constructor(message: string = 'Page not found') {\r\n super(message);\r\n this.name = 'NotFoundError';\r\n }\r\n}\r\n\r\n/**\r\n * Redirect to a different URL\r\n * @param url - The URL to redirect to\r\n * @param type - 'replace' (307) or 'push' (308) for permanent\r\n * \r\n * @example\r\n * ```tsx\r\n * import { redirect } from '@flexireact/core';\r\n * \r\n * export default function ProtectedPage() {\r\n * const user = getUser();\r\n * if (!user) {\r\n * redirect('/login');\r\n * }\r\n * return <Dashboard user={user} />;\r\n * }\r\n * ```\r\n */\r\nexport function redirect(url: string, type: 'replace' | 'permanent' = 'replace'): never {\r\n const statusCode = type === 'permanent' ? 308 : 307;\r\n throw new RedirectError(url, statusCode);\r\n}\r\n\r\n/**\r\n * Trigger a 404 Not Found response\r\n * \r\n * @example\r\n * ```tsx\r\n * import { notFound } from '@flexireact/core';\r\n * \r\n * export default function ProductPage({ params }) {\r\n * const product = getProduct(params.id);\r\n * if (!product) {\r\n * notFound();\r\n * }\r\n * return <Product data={product} />;\r\n * }\r\n * ```\r\n */\r\nexport function notFound(message?: string): never {\r\n throw new NotFoundError(message);\r\n}\r\n\r\n/**\r\n * Create a JSON response\r\n * \r\n * @example\r\n * ```ts\r\n * // In API route\r\n * export function GET() {\r\n * return json({ message: 'Hello' });\r\n * }\r\n * \r\n * export function POST() {\r\n * return json({ error: 'Bad request' }, { status: 400 });\r\n * }\r\n * ```\r\n */\r\nexport function json<T>(\r\n data: T,\r\n options: {\r\n status?: number;\r\n headers?: Record<string, string>;\r\n } = {}\r\n): Response {\r\n const { status = 200, headers = {} } = options;\r\n \r\n return new Response(JSON.stringify(data), {\r\n status,\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n ...headers\r\n }\r\n });\r\n}\r\n\r\n/**\r\n * Create an HTML response\r\n */\r\nexport function html(\r\n content: string,\r\n options: {\r\n status?: number;\r\n headers?: Record<string, string>;\r\n } = {}\r\n): Response {\r\n const { status = 200, headers = {} } = options;\r\n \r\n return new Response(content, {\r\n status,\r\n headers: {\r\n 'Content-Type': 'text/html; charset=utf-8',\r\n ...headers\r\n }\r\n });\r\n}\r\n\r\n/**\r\n * Create a text response\r\n */\r\nexport function text(\r\n content: string,\r\n options: {\r\n status?: number;\r\n headers?: Record<string, string>;\r\n } = {}\r\n): Response {\r\n const { status = 200, headers = {} } = options;\r\n \r\n return new Response(content, {\r\n status,\r\n headers: {\r\n 'Content-Type': 'text/plain; charset=utf-8',\r\n ...headers\r\n }\r\n });\r\n}\r\n\r\n// ============================================================================\r\n// Cookies API\r\n// ============================================================================\r\n\r\nexport interface CookieOptions {\r\n /** Max age in seconds */\r\n maxAge?: number;\r\n /** Expiration date */\r\n expires?: Date;\r\n /** Cookie path */\r\n path?: string;\r\n /** Cookie domain */\r\n domain?: string;\r\n /** Secure flag (HTTPS only) */\r\n secure?: boolean;\r\n /** HttpOnly flag */\r\n httpOnly?: boolean;\r\n /** SameSite policy */\r\n sameSite?: 'strict' | 'lax' | 'none';\r\n}\r\n\r\n/**\r\n * Cookie utilities for server-side operations\r\n */\r\nexport const cookies = {\r\n /**\r\n * Parse cookies from a cookie header string\r\n */\r\n parse(cookieHeader: string): Record<string, string> {\r\n const cookies: Record<string, string> = {};\r\n if (!cookieHeader) return cookies;\r\n\r\n cookieHeader.split(';').forEach(cookie => {\r\n const [name, ...rest] = cookie.split('=');\r\n if (name) {\r\n const value = rest.join('=');\r\n cookies[name.trim()] = decodeURIComponent(value.trim());\r\n }\r\n });\r\n\r\n return cookies;\r\n },\r\n\r\n /**\r\n * Get a cookie value from request headers\r\n */\r\n get(request: Request, name: string): string | undefined {\r\n const cookieHeader = request.headers.get('cookie') || '';\r\n const parsed = this.parse(cookieHeader);\r\n return parsed[name];\r\n },\r\n\r\n /**\r\n * Get all cookies from request\r\n */\r\n getAll(request: Request): Record<string, string> {\r\n const cookieHeader = request.headers.get('cookie') || '';\r\n return this.parse(cookieHeader);\r\n },\r\n\r\n /**\r\n * Serialize a cookie for Set-Cookie header\r\n */\r\n serialize(name: string, value: string, options: CookieOptions = {}): string {\r\n let cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;\r\n\r\n if (options.maxAge !== undefined) {\r\n cookie += `; Max-Age=${options.maxAge}`;\r\n }\r\n if (options.expires) {\r\n cookie += `; Expires=${options.expires.toUTCString()}`;\r\n }\r\n if (options.path) {\r\n cookie += `; Path=${options.path}`;\r\n }\r\n if (options.domain) {\r\n cookie += `; Domain=${options.domain}`;\r\n }\r\n if (options.secure) {\r\n cookie += '; Secure';\r\n }\r\n if (options.httpOnly) {\r\n cookie += '; HttpOnly';\r\n }\r\n if (options.sameSite) {\r\n cookie += `; SameSite=${options.sameSite.charAt(0).toUpperCase() + options.sameSite.slice(1)}`;\r\n }\r\n\r\n return cookie;\r\n },\r\n\r\n /**\r\n * Create a Set-Cookie header value\r\n */\r\n set(name: string, value: string, options: CookieOptions = {}): string {\r\n return this.serialize(name, value, {\r\n path: '/',\r\n httpOnly: true,\r\n secure: process.env.NODE_ENV === 'production',\r\n sameSite: 'lax',\r\n ...options\r\n });\r\n },\r\n\r\n /**\r\n * Create a cookie deletion header\r\n */\r\n delete(name: string, options: Omit<CookieOptions, 'maxAge' | 'expires'> = {}): string {\r\n return this.serialize(name, '', {\r\n ...options,\r\n path: '/',\r\n maxAge: 0\r\n });\r\n }\r\n};\r\n\r\n// ============================================================================\r\n// Headers API\r\n// ============================================================================\r\n\r\n/**\r\n * Headers utilities for server-side operations\r\n */\r\nexport const headers = {\r\n /**\r\n * Create a new Headers object with common defaults\r\n */\r\n create(init?: HeadersInit): Headers {\r\n return new Headers(init);\r\n },\r\n\r\n /**\r\n * Get a header value from request\r\n */\r\n get(request: Request, name: string): string | null {\r\n return request.headers.get(name);\r\n },\r\n\r\n /**\r\n * Get all headers as an object\r\n */\r\n getAll(request: Request): Record<string, string> {\r\n const result: Record<string, string> = {};\r\n request.headers.forEach((value, key) => {\r\n result[key] = value;\r\n });\r\n return result;\r\n },\r\n\r\n /**\r\n * Check if request has a specific header\r\n */\r\n has(request: Request, name: string): boolean {\r\n return request.headers.has(name);\r\n },\r\n\r\n /**\r\n * Get content type from request\r\n */\r\n contentType(request: Request): string | null {\r\n return request.headers.get('content-type');\r\n },\r\n\r\n /**\r\n * Check if request accepts JSON\r\n */\r\n acceptsJson(request: Request): boolean {\r\n const accept = request.headers.get('accept') || '';\r\n return accept.includes('application/json') || accept.includes('*/*');\r\n },\r\n\r\n /**\r\n * Check if request is AJAX/fetch\r\n */\r\n isAjax(request: Request): boolean {\r\n return request.headers.get('x-requested-with') === 'XMLHttpRequest' ||\r\n this.acceptsJson(request);\r\n },\r\n\r\n /**\r\n * Get authorization header\r\n */\r\n authorization(request: Request): { type: string; credentials: string } | null {\r\n const auth = request.headers.get('authorization');\r\n if (!auth) return null;\r\n\r\n const [type, ...rest] = auth.split(' ');\r\n return {\r\n type: type.toLowerCase(),\r\n credentials: rest.join(' ')\r\n };\r\n },\r\n\r\n /**\r\n * Get bearer token from authorization header\r\n */\r\n bearerToken(request: Request): string | null {\r\n const auth = this.authorization(request);\r\n if (auth?.type === 'bearer') {\r\n return auth.credentials;\r\n }\r\n return null;\r\n },\r\n\r\n /**\r\n * Common security headers\r\n */\r\n security(): Record<string, string> {\r\n return {\r\n 'X-Content-Type-Options': 'nosniff',\r\n 'X-Frame-Options': 'DENY',\r\n 'X-XSS-Protection': '1; mode=block',\r\n 'Referrer-Policy': 'strict-origin-when-cross-origin',\r\n 'Permissions-Policy': 'camera=(), microphone=(), geolocation=()'\r\n };\r\n },\r\n\r\n /**\r\n * CORS headers\r\n */\r\n cors(options: {\r\n origin?: string;\r\n methods?: string[];\r\n headers?: string[];\r\n credentials?: boolean;\r\n maxAge?: number;\r\n } = {}): Record<string, string> {\r\n const {\r\n origin = '*',\r\n methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],\r\n headers: allowHeaders = ['Content-Type', 'Authorization'],\r\n credentials = false,\r\n maxAge = 86400\r\n } = options;\r\n\r\n const corsHeaders: Record<string, string> = {\r\n 'Access-Control-Allow-Origin': origin,\r\n 'Access-Control-Allow-Methods': methods.join(', '),\r\n 'Access-Control-Allow-Headers': allowHeaders.join(', '),\r\n 'Access-Control-Max-Age': String(maxAge)\r\n };\r\n\r\n if (credentials) {\r\n corsHeaders['Access-Control-Allow-Credentials'] = 'true';\r\n }\r\n\r\n return corsHeaders;\r\n },\r\n\r\n /**\r\n * Cache control headers\r\n */\r\n cache(options: {\r\n maxAge?: number;\r\n sMaxAge?: number;\r\n staleWhileRevalidate?: number;\r\n private?: boolean;\r\n noStore?: boolean;\r\n } = {}): Record<string, string> {\r\n if (options.noStore) {\r\n return { 'Cache-Control': 'no-store, no-cache, must-revalidate' };\r\n }\r\n\r\n const directives: string[] = [];\r\n \r\n if (options.private) {\r\n directives.push('private');\r\n } else {\r\n directives.push('public');\r\n }\r\n\r\n if (options.maxAge !== undefined) {\r\n directives.push(`max-age=${options.maxAge}`);\r\n }\r\n\r\n if (options.sMaxAge !== undefined) {\r\n directives.push(`s-maxage=${options.sMaxAge}`);\r\n }\r\n\r\n if (options.staleWhileRevalidate !== undefined) {\r\n directives.push(`stale-while-revalidate=${options.staleWhileRevalidate}`);\r\n }\r\n\r\n return { 'Cache-Control': directives.join(', ') };\r\n }\r\n};\r\n\r\n// ============================================================================\r\n// Request Helpers\r\n// ============================================================================\r\n\r\n/**\r\n * Parse JSON body from request\r\n */\r\nexport async function parseJson<T = unknown>(request: Request): Promise<T> {\r\n try {\r\n return await request.json();\r\n } catch {\r\n throw new Error('Invalid JSON body');\r\n }\r\n}\r\n\r\n/**\r\n * Parse form data from request\r\n */\r\nexport async function parseFormData(request: Request): Promise<FormData> {\r\n return await request.formData();\r\n}\r\n\r\n/**\r\n * Parse URL search params\r\n */\r\nexport function parseSearchParams(request: Request): URLSearchParams {\r\n const url = new URL(request.url);\r\n return url.searchParams;\r\n}\r\n\r\n/**\r\n * Get request method\r\n */\r\nexport function getMethod(request: Request): string {\r\n return request.method.toUpperCase();\r\n}\r\n\r\n/**\r\n * Get request pathname\r\n */\r\nexport function getPathname(request: Request): string {\r\n const url = new URL(request.url);\r\n return url.pathname;\r\n}\r\n\r\n/**\r\n * Check if request method matches\r\n */\r\nexport function isMethod(request: Request, method: string | string[]): boolean {\r\n const reqMethod = getMethod(request);\r\n if (Array.isArray(method)) {\r\n return method.map(m => m.toUpperCase()).includes(reqMethod);\r\n }\r\n return reqMethod === method.toUpperCase();\r\n}\r\n","/**\r\n * FlexiReact Server Actions\r\n * \r\n * React 19 native actions with FlexiReact enhancements.\r\n * \r\n * Usage:\r\n * ```tsx\r\n * // In a server file (actions.ts)\r\n * 'use server';\r\n * \r\n * export async function createUser(prevState: any, formData: FormData) {\r\n * const name = formData.get('name');\r\n * // Save to database...\r\n * return { success: true, id: 123 };\r\n * }\r\n * \r\n * // In a client component - React 19 style\r\n * 'use client';\r\n * import { useActionState } from '@flexireact/core';\r\n * import { createUser } from './actions';\r\n * \r\n * function Form() {\r\n * const [state, formAction, isPending] = useActionState(createUser, null);\r\n * return (\r\n * <form action={formAction}>\r\n * <input name=\"name\" />\r\n * <button type=\"submit\" disabled={isPending}>Create</button>\r\n * </form>\r\n * );\r\n * }\r\n * ```\r\n */\r\n\r\n// ============================================================================\r\n// React 19 Hooks (re-exported for convenience)\r\n// ============================================================================\r\nexport { useActionState, useOptimistic } from 'react';\r\nexport { useFormStatus } from 'react-dom';\r\n\r\nimport { cookies, headers, redirect, notFound, RedirectError, NotFoundError } from '../helpers.js';\r\n\r\n// Global action registry\r\ndeclare global {\r\n var __FLEXI_ACTIONS__: Record<string, ServerActionFunction>;\r\n var __FLEXI_ACTION_CONTEXT__: ActionContext | null;\r\n}\r\n\r\nglobalThis.__FLEXI_ACTIONS__ = globalThis.__FLEXI_ACTIONS__ || {};\r\nglobalThis.__FLEXI_ACTION_CONTEXT__ = null;\r\n\r\nexport interface ActionContext {\r\n request: Request;\r\n cookies: typeof cookies;\r\n headers: typeof headers;\r\n redirect: typeof redirect;\r\n notFound: typeof notFound;\r\n}\r\n\r\nexport type ServerActionFunction = (...args: any[]) => Promise<any>;\r\n\r\nexport interface ActionResult<T = any> {\r\n success: boolean;\r\n data?: T;\r\n error?: string;\r\n redirect?: string;\r\n}\r\n\r\n/**\r\n * Decorator to mark a function as a server action\r\n */\r\nexport function serverAction<T extends ServerActionFunction>(\r\n fn: T,\r\n actionId?: string\r\n): T {\r\n const id = actionId || `action_${fn.name}_${generateActionId()}`;\r\n\r\n // Register the action\r\n globalThis.__FLEXI_ACTIONS__[id] = fn;\r\n\r\n // Create a proxy that will be serialized for the client\r\n const proxy = (async (...args: any[]) => {\r\n // If we're on the server, execute directly\r\n if (typeof window === 'undefined') {\r\n return await executeAction(id, args);\r\n }\r\n\r\n // If we're on the client, make a fetch request\r\n return await callServerAction(id, args);\r\n }) as T;\r\n\r\n // Mark as server action\r\n (proxy as any).$$typeof = Symbol.for('react.server.action');\r\n (proxy as any).$$id = id;\r\n (proxy as any).$$bound = null;\r\n\r\n return proxy;\r\n}\r\n\r\n/**\r\n * Register a server action\r\n */\r\nexport function registerAction(id: string, fn: ServerActionFunction): void {\r\n globalThis.__FLEXI_ACTIONS__[id] = fn;\r\n}\r\n\r\n/**\r\n * Get a registered action\r\n */\r\nexport function getAction(id: string): ServerActionFunction | undefined {\r\n return globalThis.__FLEXI_ACTIONS__[id];\r\n}\r\n\r\n/**\r\n * Execute a server action on the server\r\n */\r\nexport async function executeAction(\r\n actionId: string,\r\n args: any[],\r\n context?: Partial<ActionContext>\r\n): Promise<ActionResult> {\r\n const action = globalThis.__FLEXI_ACTIONS__[actionId];\r\n\r\n if (!action) {\r\n return {\r\n success: false,\r\n error: `Server action not found: ${actionId}`\r\n };\r\n }\r\n\r\n // Set up action context\r\n const actionContext: ActionContext = {\r\n request: context?.request || new Request('http://localhost'),\r\n cookies,\r\n headers,\r\n redirect,\r\n notFound\r\n };\r\n\r\n globalThis.__FLEXI_ACTION_CONTEXT__ = actionContext;\r\n\r\n try {\r\n const result = await action(...args);\r\n\r\n return {\r\n success: true,\r\n data: result\r\n };\r\n } catch (error: any) {\r\n // Handle redirect\r\n if (error instanceof RedirectError) {\r\n return {\r\n success: true,\r\n redirect: error.url\r\n };\r\n }\r\n\r\n // Handle not found\r\n if (error instanceof NotFoundError) {\r\n return {\r\n success: false,\r\n error: 'Not found'\r\n };\r\n }\r\n\r\n return {\r\n success: false,\r\n error: error.message || 'Action failed'\r\n };\r\n } finally {\r\n globalThis.__FLEXI_ACTION_CONTEXT__ = null;\r\n }\r\n}\r\n\r\n/**\r\n * Call a server action from the client\r\n */\r\nexport async function callServerAction(\r\n actionId: string,\r\n args: any[]\r\n): Promise<ActionResult> {\r\n try {\r\n const response = await fetch('/_flexi/action', {\r\n method: 'POST',\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n 'X-Flexi-Action': actionId\r\n },\r\n body: JSON.stringify({\r\n actionId,\r\n args: serializeArgs(args)\r\n }),\r\n credentials: 'same-origin'\r\n });\r\n\r\n if (!response.ok) {\r\n throw new Error(`Action failed: ${response.statusText}`);\r\n }\r\n\r\n const result = await response.json();\r\n\r\n // Handle redirect\r\n if (result.redirect) {\r\n window.location.href = result.redirect;\r\n return result;\r\n }\r\n\r\n return result;\r\n } catch (error: any) {\r\n return {\r\n success: false,\r\n error: error.message || 'Network error'\r\n };\r\n }\r\n}\r\n\r\n/**\r\n * Serialize action arguments for transmission\r\n */\r\nfunction serializeArgs(args: any[]): any[] {\r\n return args.map(arg => {\r\n // Handle FormData\r\n if (arg instanceof FormData) {\r\n const obj: Record<string, any> = {};\r\n arg.forEach((value, key) => {\r\n if (obj[key]) {\r\n // Handle multiple values\r\n if (Array.isArray(obj[key])) {\r\n obj[key].push(value);\r\n } else {\r\n obj[key] = [obj[key], value];\r\n }\r\n } else {\r\n obj[key] = value;\r\n }\r\n });\r\n return { $$type: 'FormData', data: obj };\r\n }\r\n\r\n // Handle File\r\n if (typeof File !== 'undefined' && arg instanceof File) {\r\n return { $$type: 'File', name: arg.name, type: arg.type, size: arg.size };\r\n }\r\n\r\n // Handle Date\r\n if (arg instanceof Date) {\r\n return { $$type: 'Date', value: arg.toISOString() };\r\n }\r\n\r\n // Handle regular objects\r\n if (typeof arg === 'object' && arg !== null) {\r\n return JSON.parse(JSON.stringify(arg));\r\n }\r\n\r\n return arg;\r\n });\r\n}\r\n\r\n/**\r\n * Deserialize action arguments on the server\r\n */\r\nexport function deserializeArgs(args: any[]): any[] {\r\n return args.map(arg => {\r\n if (arg && typeof arg === 'object') {\r\n // Handle FormData\r\n if (arg.$$type === 'FormData') {\r\n const formData = new FormData();\r\n for (const [key, value] of Object.entries(arg.data)) {\r\n if (Array.isArray(value)) {\r\n value.forEach(v => formData.append(key, v as string));\r\n } else {\r\n formData.append(key, value as string);\r\n }\r\n }\r\n return formData;\r\n }\r\n\r\n // Handle Date\r\n if (arg.$$type === 'Date') {\r\n return new Date(arg.value);\r\n }\r\n }\r\n\r\n return arg;\r\n });\r\n}\r\n\r\n/**\r\n * Generate a unique action ID\r\n */\r\nfunction generateActionId(): string {\r\n return Math.random().toString(36).substring(2, 10);\r\n}\r\n\r\n/**\r\n * Hook to get the current action context\r\n */\r\nexport function useActionContext(): ActionContext | null {\r\n return globalThis.__FLEXI_ACTION_CONTEXT__;\r\n}\r\n\r\n/**\r\n * Create a form action handler\r\n * Wraps a server action for use with HTML forms\r\n */\r\nexport function formAction<T>(\r\n action: (formData: FormData) => Promise<T>\r\n): (formData: FormData) => Promise<ActionResult<T>> {\r\n return async (formData: FormData) => {\r\n try {\r\n const result = await action(formData);\r\n return { success: true, data: result };\r\n } catch (error: any) {\r\n if (error instanceof RedirectError) {\r\n return { success: true, redirect: error.url };\r\n }\r\n return { success: false, error: error.message };\r\n }\r\n };\r\n}\r\n\r\n/**\r\n * Enhanced action state hook with FlexiReact context integration\r\n * Wraps React 19's useActionState with additional features\r\n * \r\n * @example\r\n * ```tsx\r\n * const [state, dispatch, isPending] = useFlexiAction(submitForm, { errors: [] });\r\n * ```\r\n */\r\nimport { useActionState as useActionStateReact } from 'react';\r\n\r\nexport function useFlexiAction<State, Payload>(\r\n action: (state: Awaited<State>, payload: Payload) => State | Promise<State>,\r\n initialState: Awaited<State>,\r\n permalink?: string\r\n): [state: Awaited<State>, dispatch: (payload: Payload) => void, isPending: boolean] {\r\n return useActionStateReact(action, initialState, permalink);\r\n}\r\n\r\n/**\r\n * @deprecated Since v3.1 - Use `useActionState` from React 19 instead.\r\n * This function will be removed in v4.0.\r\n * \r\n * Migration:\r\n * ```tsx\r\n * // Before (React 18)\r\n * const formState = createFormState(submitAction, null);\r\n * \r\n * // After (React 19)\r\n * const [state, formAction, isPending] = useActionState(submitAction, null);\r\n * ```\r\n */\r\nexport function createFormState<T>(\r\n action: (formData: FormData) => Promise<ActionResult<T>>,\r\n initialState: T | null = null\r\n) {\r\n if (typeof window !== 'undefined' && process.env.NODE_ENV === 'development') {\r\n console.warn(\r\n '[FlexiReact] createFormState is deprecated. Use useActionState from React 19 instead.\\n' +\r\n 'See migration guide: https://flexireact.dev/docs/react-19-migration'\r\n );\r\n }\r\n return {\r\n action,\r\n initialState,\r\n pending: false,\r\n error: null as string | null,\r\n data: initialState\r\n };\r\n}\r\n\r\n/**\r\n * Bind arguments to a server action\r\n * Creates a new action with pre-filled arguments\r\n */\r\nexport function bindArgs<T extends ServerActionFunction>(\r\n action: T,\r\n ...boundArgs: any[]\r\n): T {\r\n const boundAction = (async (...args: any[]) => {\r\n return await (action as any)(...boundArgs, ...args);\r\n }) as T;\r\n\r\n // Copy action metadata\r\n (boundAction as any).$$typeof = (action as any).$$typeof;\r\n (boundAction as any).$$id = (action as any).$$id;\r\n (boundAction as any).$$bound = boundArgs;\r\n\r\n return boundAction;\r\n}\r\n\r\nexport default {\r\n serverAction,\r\n registerAction,\r\n getAction,\r\n executeAction,\r\n callServerAction,\r\n deserializeArgs,\r\n useActionContext,\r\n formAction,\r\n createFormState, // deprecated\r\n useFlexiAction,\r\n bindArgs\r\n};\r\n","/**\r\n * FlexiReact Image Optimization\r\n * \r\n * Optimized image component with:\r\n * - Automatic WebP/AVIF conversion\r\n * - Responsive srcset generation\r\n * - Lazy loading with blur placeholder\r\n * - Priority loading for LCP images\r\n * - Automatic width/height to prevent CLS\r\n */\r\n\r\nimport React from 'react';\r\nimport path from 'path';\r\nimport fs from 'fs';\r\nimport crypto from 'crypto';\r\n\r\n// Image optimization config\r\nexport interface ImageConfig {\r\n domains: string[];\r\n deviceSizes: number[];\r\n imageSizes: number[];\r\n formats: ('webp' | 'avif' | 'png' | 'jpeg')[];\r\n minimumCacheTTL: number;\r\n dangerouslyAllowSVG: boolean;\r\n quality: number;\r\n cacheDir: string;\r\n}\r\n\r\nexport const defaultImageConfig: ImageConfig = {\r\n domains: [],\r\n deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],\r\n imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],\r\n formats: ['webp', 'avif'],\r\n minimumCacheTTL: 60 * 60 * 24 * 30, // 30 days\r\n dangerouslyAllowSVG: false,\r\n quality: 75,\r\n cacheDir: '.flexi/image-cache'\r\n};\r\n\r\n// Image props\r\nexport interface ImageProps {\r\n src: string;\r\n alt: string;\r\n width?: number;\r\n height?: number;\r\n fill?: boolean;\r\n sizes?: string;\r\n quality?: number;\r\n priority?: boolean;\r\n placeholder?: 'blur' | 'empty' | 'data:image/...';\r\n blurDataURL?: string;\r\n loading?: 'lazy' | 'eager';\r\n className?: string;\r\n style?: React.CSSProperties;\r\n onLoad?: () => void;\r\n onError?: () => void;\r\n unoptimized?: boolean;\r\n}\r\n\r\n// Generate blur placeholder\r\nexport async function generateBlurPlaceholder(imagePath: string): Promise<string> {\r\n try {\r\n // For now, return a simple SVG blur placeholder\r\n // In production, we'd use sharp to generate a tiny blurred version\r\n return `data:image/svg+xml;base64,${Buffer.from(\r\n `<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 8 5\">\r\n <filter id=\"b\" color-interpolation-filters=\"sRGB\">\r\n <feGaussianBlur stdDeviation=\"1\"/>\r\n </filter>\r\n <rect width=\"100%\" height=\"100%\" fill=\"#1a1a1a\"/>\r\n <rect width=\"100%\" height=\"100%\" filter=\"url(#b)\" opacity=\"0.5\" fill=\"#333\"/>\r\n </svg>`\r\n ).toString('base64')}`;\r\n } catch {\r\n return '';\r\n }\r\n}\r\n\r\n// Get image dimensions\r\nexport async function getImageDimensions(src: string): Promise<{ width: number; height: number } | null> {\r\n try {\r\n // For local files\r\n if (!src.startsWith('http')) {\r\n const imagePath = path.join(process.cwd(), 'public', src);\r\n if (fs.existsSync(imagePath)) {\r\n // Read first bytes to detect dimensions\r\n const buffer = fs.readFileSync(imagePath);\r\n return detectDimensions(buffer);\r\n }\r\n }\r\n return null;\r\n } catch {\r\n return null;\r\n }\r\n}\r\n\r\n// Detect image dimensions from buffer\r\nfunction detectDimensions(buffer: Buffer): { width: number; height: number } | null {\r\n // PNG\r\n if (buffer[0] === 0x89 && buffer[1] === 0x50) {\r\n return {\r\n width: buffer.readUInt32BE(16),\r\n height: buffer.readUInt32BE(20)\r\n };\r\n }\r\n \r\n // JPEG\r\n if (buffer[0] === 0xff && buffer[1] === 0xd8) {\r\n let offset = 2;\r\n while (offset < buffer.length) {\r\n if (buffer[offset] !== 0xff) break;\r\n const marker = buffer[offset + 1];\r\n if (marker === 0xc0 || marker === 0xc2) {\r\n return {\r\n height: buffer.readUInt16BE(offset + 5),\r\n width: buffer.readUInt16BE(offset + 7)\r\n };\r\n }\r\n offset += 2 + buffer.readUInt16BE(offset + 2);\r\n }\r\n }\r\n \r\n // GIF\r\n if (buffer[0] === 0x47 && buffer[1] === 0x49 && buffer[2] === 0x46) {\r\n return {\r\n width: buffer.readUInt16LE(6),\r\n height: buffer.readUInt16LE(8)\r\n };\r\n }\r\n \r\n // WebP\r\n if (buffer[0] === 0x52 && buffer[1] === 0x49 && buffer[8] === 0x57 && buffer[9] === 0x45) {\r\n // VP8\r\n if (buffer[12] === 0x56 && buffer[13] === 0x50 && buffer[14] === 0x38) {\r\n if (buffer[15] === 0x20) { // VP8\r\n return {\r\n width: buffer.readUInt16LE(26) & 0x3fff,\r\n height: buffer.readUInt16LE(28) & 0x3fff\r\n };\r\n }\r\n if (buffer[15] === 0x4c) { // VP8L\r\n const bits = buffer.readUInt32LE(21);\r\n return {\r\n width: (bits & 0x3fff) + 1,\r\n height: ((bits >> 14) & 0x3fff) + 1\r\n };\r\n }\r\n }\r\n }\r\n \r\n return null;\r\n}\r\n\r\n// Generate srcset for responsive images\r\nexport function generateSrcSet(\r\n src: string,\r\n widths: number[],\r\n quality: number = 75\r\n): string {\r\n return widths\r\n .map(w => `/_flexi/image?url=${encodeURIComponent(src)}&w=${w}&q=${quality} ${w}w`)\r\n .join(', ');\r\n}\r\n\r\n// Generate sizes attribute\r\nexport function generateSizes(sizes?: string): string {\r\n if (sizes) return sizes;\r\n return '100vw';\r\n}\r\n\r\n// Image optimization endpoint handler\r\nexport async function handleImageOptimization(\r\n req: any,\r\n res: any,\r\n config: Partial<ImageConfig> = {}\r\n): Promise<void> {\r\n const fullConfig = { ...defaultImageConfig, ...config };\r\n const url = new URL(req.url, `http://${req.headers.host}`);\r\n \r\n const imageUrl = url.searchParams.get('url');\r\n const width = parseInt(url.searchParams.get('w') || '0', 10);\r\n const quality = parseInt(url.searchParams.get('q') || String(fullConfig.quality), 10);\r\n const format = url.searchParams.get('f') as 'webp' | 'avif' | 'png' | 'jpeg' | null;\r\n \r\n if (!imageUrl) {\r\n res.writeHead(400, { 'Content-Type': 'text/plain' });\r\n res.end('Missing url parameter');\r\n return;\r\n }\r\n \r\n try {\r\n let imageBuffer: Buffer;\r\n let contentType: string;\r\n \r\n // Fetch image\r\n if (imageUrl.startsWith('http')) {\r\n // Remote image\r\n const response = await fetch(imageUrl);\r\n if (!response.ok) throw new Error('Failed to fetch image');\r\n imageBuffer = Buffer.from(await response.arrayBuffer());\r\n contentType = response.headers.get('content-type') || 'image/jpeg';\r\n } else {\r\n // Local image\r\n const imagePath = path.join(process.cwd(), 'public', imageUrl);\r\n if (!fs.existsSync(imagePath)) {\r\n res.writeHead(404, { 'Content-Type': 'text/plain' });\r\n res.end('Image not found');\r\n return;\r\n }\r\n imageBuffer = fs.readFileSync(imagePath);\r\n contentType = getContentType(imagePath);\r\n }\r\n \r\n // Generate cache key\r\n const cacheKey = crypto\r\n .createHash('md5')\r\n .update(`${imageUrl}-${width}-${quality}-${format}`)\r\n .digest('hex');\r\n \r\n const cacheDir = path.join(process.cwd(), fullConfig.cacheDir);\r\n const cachePath = path.join(cacheDir, `${cacheKey}.${format || 'webp'}`);\r\n \r\n // Check cache\r\n if (fs.existsSync(cachePath)) {\r\n const cachedImage = fs.readFileSync(cachePath);\r\n res.writeHead(200, {\r\n 'Content-Type': `image/${format || 'webp'}`,\r\n 'Cache-Control': `public, max-age=${fullConfig.minimumCacheTTL}`,\r\n 'X-Flexi-Image-Cache': 'HIT'\r\n });\r\n res.end(cachedImage);\r\n return;\r\n }\r\n \r\n // For now, serve original image\r\n // In production, we'd use sharp for resizing/conversion\r\n // TODO: Integrate sharp for actual optimization\r\n \r\n res.writeHead(200, {\r\n 'Content-Type': contentType,\r\n 'Cache-Control': `public, max-age=${fullConfig.minimumCacheTTL}`,\r\n 'X-Flexi-Image-Cache': 'MISS'\r\n });\r\n res.end(imageBuffer);\r\n \r\n } catch (error: any) {\r\n console.error('Image optimization error:', error);\r\n res.writeHead(500, { 'Content-Type': 'text/plain' });\r\n res.end('Image optimization failed');\r\n }\r\n}\r\n\r\n// Get content type from file extension\r\nfunction getContentType(filePath: string): string {\r\n const ext = path.extname(filePath).toLowerCase();\r\n const types: Record<string, string> = {\r\n '.jpg': 'image/jpeg',\r\n '.jpeg': 'image/jpeg',\r\n '.png': 'image/png',\r\n '.gif': 'image/gif',\r\n '.webp': 'image/webp',\r\n '.avif': 'image/avif',\r\n '.svg': 'image/svg+xml',\r\n '.ico': 'image/x-icon'\r\n };\r\n return types[ext] || 'application/octet-stream';\r\n}\r\n\r\n// Image component (server-side rendered)\r\nexport function createImageComponent(config: Partial<ImageConfig> = {}) {\r\n const fullConfig = { ...defaultImageConfig, ...config };\r\n \r\n return function Image(props: ImageProps): React.ReactElement {\r\n const {\r\n src,\r\n alt,\r\n width,\r\n height,\r\n fill = false,\r\n sizes,\r\n quality = fullConfig.quality,\r\n priority = false,\r\n placeholder = 'empty',\r\n blurDataURL,\r\n loading,\r\n className = '',\r\n style = {},\r\n unoptimized = false,\r\n ...rest\r\n } = props;\r\n \r\n // Determine loading strategy\r\n const loadingAttr = priority ? 'eager' : (loading || 'lazy');\r\n \r\n // Generate optimized src\r\n const optimizedSrc = unoptimized \r\n ? src \r\n : `/_flexi/image?url=${encodeURIComponent(src)}&w=${width || 1920}&q=${quality}`;\r\n \r\n // Generate srcset for responsive images\r\n const allSizes = [...fullConfig.imageSizes, ...fullConfig.deviceSizes].sort((a, b) => a - b);\r\n const relevantSizes = width \r\n ? allSizes.filter(s => s <= width * 2)\r\n : allSizes;\r\n \r\n const srcSet = unoptimized \r\n ? undefined \r\n : generateSrcSet(src, relevantSizes, quality);\r\n \r\n // Build styles\r\n const imgStyle: React.CSSProperties = {\r\n ...style,\r\n ...(fill ? {\r\n position: 'absolute',\r\n top: 0,\r\n left: 0,\r\n width: '100%',\r\n height: '100%',\r\n objectFit: 'cover'\r\n } : {})\r\n };\r\n \r\n // Placeholder styles\r\n const wrapperStyle: React.CSSProperties = fill ? {\r\n position: 'relative',\r\n width: '100%',\r\n height: '100%'\r\n } : {};\r\n \r\n const placeholderStyle: React.CSSProperties = placeholder === 'blur' ? {\r\n backgroundImage: `url(${blurDataURL || generateBlurPlaceholderSync()})`,\r\n backgroundSize: 'cover',\r\n backgroundPosition: 'center',\r\n filter: 'blur(20px)',\r\n transform: 'scale(1.1)'\r\n } : {};\r\n \r\n // Create image element\r\n const imgElement = React.createElement('img', {\r\n src: optimizedSrc,\r\n alt,\r\n width: fill ? undefined : width,\r\n height: fill ? undefined : height,\r\n loading: loadingAttr,\r\n decoding: 'async',\r\n srcSet,\r\n sizes: generateSizes(sizes),\r\n className: `flexi-image ${className}`.trim(),\r\n style: imgStyle,\r\n fetchPriority: priority ? 'high' : undefined,\r\n ...rest\r\n });\r\n \r\n // Wrap with placeholder if needed\r\n if (fill || placeholder === 'blur') {\r\n return React.createElement('div', {\r\n className: 'flexi-image-wrapper',\r\n style: { ...wrapperStyle, ...placeholderStyle }\r\n }, imgElement);\r\n }\r\n \r\n return imgElement;\r\n };\r\n}\r\n\r\n// Sync blur placeholder (for SSR)\r\nfunction generateBlurPlaceholderSync(): string {\r\n return `data:image/svg+xml;base64,${Buffer.from(\r\n `<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 8 5\">\r\n <filter id=\"b\" color-interpolation-filters=\"sRGB\">\r\n <feGaussianBlur stdDeviation=\"1\"/>\r\n </filter>\r\n <rect width=\"100%\" height=\"100%\" fill=\"#1a1a1a\"/>\r\n </svg>`\r\n ).toString('base64')}`;\r\n}\r\n\r\n// Default Image component\r\nexport const Image = createImageComponent();\r\n\r\n// Loader types for different image providers\r\nexport interface ImageLoader {\r\n (props: { src: string; width: number; quality?: number }): string;\r\n}\r\n\r\n// Built-in loaders\r\nexport const imageLoaders = {\r\n default: ({ src, width, quality = 75 }: { src: string; width: number; quality?: number }) =>\r\n `/_flexi/image?url=${encodeURIComponent(src)}&w=${width}&q=${quality}`,\r\n \r\n cloudinary: ({ src, width, quality = 75 }: { src: string; width: number; quality?: number }) =>\r\n `https://res.cloudinary.com/demo/image/fetch/w_${width},q_${quality}/${src}`,\r\n \r\n imgix: ({ src, width, quality = 75 }: { src: string; width: number; quality?: number }) =>\r\n `${src}?w=${width}&q=${quality}&auto=format`,\r\n \r\n vercel: ({ src, width, quality = 75 }: { src: string; width: number; quality?: number }) =>\r\n `/_vercel/image?url=${encodeURIComponent(src)}&w=${width}&q=${quality}`,\r\n \r\n cloudflare: ({ src, width, quality = 75 }: { src: string; width: number; quality?: number }) =>\r\n `/cdn-cgi/image/width=${width},quality=${quality}/${src}`\r\n};\r\n\r\nexport default {\r\n Image,\r\n createImageComponent,\r\n handleImageOptimization,\r\n generateBlurPlaceholder,\r\n getImageDimensions,\r\n generateSrcSet,\r\n imageLoaders,\r\n defaultImageConfig\r\n};\r\n","/**\r\n * FlexiReact Font Optimization\r\n * \r\n * Optimized font loading with:\r\n * - Automatic font subsetting\r\n * - Preload hints generation\r\n * - Font-display: swap by default\r\n * - Self-hosted Google Fonts\r\n * - Variable font support\r\n * - CSS variable generation\r\n */\r\n\r\nimport fs from 'fs';\r\nimport path from 'path';\r\nimport crypto from 'crypto';\r\n\r\n// Font configuration\r\nexport interface FontConfig {\r\n family: string;\r\n weight?: string | number | (string | number)[];\r\n style?: 'normal' | 'italic' | 'oblique';\r\n subsets?: string[];\r\n display?: 'auto' | 'block' | 'swap' | 'fallback' | 'optional';\r\n preload?: boolean;\r\n fallback?: string[];\r\n variable?: string;\r\n adjustFontFallback?: boolean;\r\n}\r\n\r\nexport interface FontResult {\r\n className: string;\r\n style: {\r\n fontFamily: string;\r\n fontWeight?: number | string;\r\n fontStyle?: string;\r\n };\r\n variable?: string;\r\n}\r\n\r\n// Google Fonts API\r\nconst GOOGLE_FONTS_API = 'https://fonts.googleapis.com/css2';\r\n\r\n// Popular Google Fonts with their weights\r\nexport const googleFonts = {\r\n Inter: {\r\n weights: [100, 200, 300, 400, 500, 600, 700, 800, 900],\r\n variable: true,\r\n subsets: ['latin', 'latin-ext', 'cyrillic', 'greek', 'vietnamese']\r\n },\r\n Roboto: {\r\n weights: [100, 300, 400, 500, 700, 900],\r\n variable: false,\r\n subsets: ['latin', 'latin-ext', 'cyrillic', 'greek', 'vietnamese']\r\n },\r\n 'Open Sans': {\r\n weights: [300, 400, 500, 600, 700, 800],\r\n variable: true,\r\n subsets: ['latin', 'latin-ext', 'cyrillic', 'greek', 'vietnamese']\r\n },\r\n Poppins: {\r\n weights: [100, 200, 300, 400, 500, 600, 700, 800, 900],\r\n variable: false,\r\n subsets: ['latin', 'latin-ext']\r\n },\r\n Montserrat: {\r\n weights: [100, 200, 300, 400, 500, 600, 700, 800, 900],\r\n variable: true,\r\n subsets: ['latin', 'latin-ext', 'cyrillic', 'vietnamese']\r\n },\r\n 'Fira Code': {\r\n weights: [300, 400, 500, 600, 700],\r\n variable: true,\r\n subsets: ['latin', 'latin-ext', 'cyrillic', 'greek']\r\n },\r\n 'JetBrains Mono': {\r\n weights: [100, 200, 300, 400, 500, 600, 700, 800],\r\n variable: true,\r\n subsets: ['latin', 'latin-ext', 'cyrillic', 'greek']\r\n },\r\n Geist: {\r\n weights: [100, 200, 300, 400, 500, 600, 700, 800, 900],\r\n variable: true,\r\n subsets: ['latin', 'latin-ext']\r\n },\r\n 'Geist Mono': {\r\n weights: [100, 200, 300, 400, 500, 600, 700, 800, 900],\r\n variable: true,\r\n subsets: ['latin', 'latin-ext']\r\n }\r\n};\r\n\r\n// Generate font CSS\r\nexport function generateFontCSS(config: FontConfig): string {\r\n const {\r\n family,\r\n weight = 400,\r\n style = 'normal',\r\n display = 'swap',\r\n fallback = ['system-ui', 'sans-serif'],\r\n variable\r\n } = config;\r\n\r\n const weights = Array.isArray(weight) ? weight : [weight];\r\n const fallbackStr = fallback.map(f => f.includes(' ') ? `\"${f}\"` : f).join(', ');\r\n\r\n let css = '';\r\n\r\n // Generate @font-face for each weight\r\n for (const w of weights) {\r\n css += `\r\n@font-face {\r\n font-family: '${family}';\r\n font-style: ${style};\r\n font-weight: ${w};\r\n font-display: ${display};\r\n src: local('${family}'),\r\n url('/_flexi/font/${encodeURIComponent(family)}?weight=${w}&style=${style}') format('woff2');\r\n}\r\n`;\r\n }\r\n\r\n // Generate CSS variable if specified\r\n if (variable) {\r\n css += `\r\n:root {\r\n ${variable}: '${family}', ${fallbackStr};\r\n}\r\n`;\r\n }\r\n\r\n return css;\r\n}\r\n\r\n// Generate preload link tags\r\nexport function generateFontPreloadTags(fonts: FontConfig[]): string {\r\n return fonts\r\n .filter(f => f.preload !== false)\r\n .map(f => {\r\n const weights = Array.isArray(f.weight) ? f.weight : [f.weight || 400];\r\n return weights.map(w => \r\n `<link rel=\"preload\" href=\"/_flexi/font/${encodeURIComponent(f.family)}?weight=${w}&style=${f.style || 'normal'}\" as=\"font\" type=\"font/woff2\" crossorigin>`\r\n ).join('\\n');\r\n })\r\n .join('\\n');\r\n}\r\n\r\n// Create a font loader function (like next/font)\r\nexport function createFont(config: FontConfig): FontResult {\r\n const {\r\n family,\r\n weight = 400,\r\n style = 'normal',\r\n fallback = ['system-ui', 'sans-serif'],\r\n variable\r\n } = config;\r\n\r\n // Generate unique class name\r\n const hash = crypto\r\n .createHash('md5')\r\n .update(`${family}-${weight}-${style}`)\r\n .digest('hex')\r\n .slice(0, 8);\r\n\r\n const className = `__font_${hash}`;\r\n const fallbackStr = fallback.map(f => f.includes(' ') ? `\"${f}\"` : f).join(', ');\r\n\r\n return {\r\n className,\r\n style: {\r\n fontFamily: `'${family}', ${fallbackStr}`,\r\n fontWeight: Array.isArray(weight) ? undefined : weight,\r\n fontStyle: style\r\n },\r\n variable: variable || undefined\r\n };\r\n}\r\n\r\n// Google Font loader\r\nexport function googleFont(config: FontConfig): FontResult {\r\n return createFont({\r\n ...config,\r\n // Google Fonts are always preloaded\r\n preload: true\r\n });\r\n}\r\n\r\n// Local font loader\r\nexport function localFont(config: FontConfig & { src: string | { path: string; weight?: string | number; style?: string }[] }): FontResult {\r\n return createFont(config);\r\n}\r\n\r\n// Handle font requests\r\nexport async function handleFontRequest(\r\n req: any,\r\n res: any\r\n): Promise<void> {\r\n const url = new URL(req.url, `http://${req.headers.host}`);\r\n const pathParts = url.pathname.split('/');\r\n const fontFamily = decodeURIComponent(pathParts[pathParts.length - 1] || '');\r\n const weight = url.searchParams.get('weight') || '400';\r\n const style = url.searchParams.get('style') || 'normal';\r\n\r\n if (!fontFamily) {\r\n res.writeHead(400, { 'Content-Type': 'text/plain' });\r\n res.end('Missing font family');\r\n return;\r\n }\r\n\r\n try {\r\n // Check local cache first\r\n const cacheDir = path.join(process.cwd(), '.flexi', 'font-cache');\r\n const cacheKey = crypto\r\n .createHash('md5')\r\n .update(`${fontFamily}-${weight}-${style}`)\r\n .digest('hex');\r\n const cachePath = path.join(cacheDir, `${cacheKey}.woff2`);\r\n\r\n if (fs.existsSync(cachePath)) {\r\n const fontData = fs.readFileSync(cachePath);\r\n res.writeHead(200, {\r\n 'Content-Type': 'font/woff2',\r\n 'Cache-Control': 'public, max-age=31536000, immutable',\r\n 'X-Flexi-Font-Cache': 'HIT'\r\n });\r\n res.end(fontData);\r\n return;\r\n }\r\n\r\n // Fetch from Google Fonts\r\n const googleUrl = `${GOOGLE_FONTS_API}?family=${encodeURIComponent(fontFamily)}:wght@${weight}&display=swap`;\r\n \r\n const cssResponse = await fetch(googleUrl, {\r\n headers: {\r\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'\r\n }\r\n });\r\n\r\n if (!cssResponse.ok) {\r\n throw new Error('Failed to fetch font CSS');\r\n }\r\n\r\n const css = await cssResponse.text();\r\n \r\n // Extract woff2 URL from CSS\r\n const woff2Match = css.match(/url\\((https:\\/\\/fonts\\.gstatic\\.com[^)]+\\.woff2)\\)/);\r\n \r\n if (!woff2Match) {\r\n throw new Error('Could not find woff2 URL');\r\n }\r\n\r\n // Fetch the actual font file\r\n const fontResponse = await fetch(woff2Match[1]);\r\n \r\n if (!fontResponse.ok) {\r\n throw new Error('Failed to fetch font file');\r\n }\r\n\r\n const fontBuffer = Buffer.from(await fontResponse.arrayBuffer());\r\n\r\n // Cache the font\r\n if (!fs.existsSync(cacheDir)) {\r\n fs.mkdirSync(cacheDir, { recursive: true });\r\n }\r\n fs.writeFileSync(cachePath, fontBuffer);\r\n\r\n // Serve the font\r\n res.writeHead(200, {\r\n 'Content-Type': 'font/woff2',\r\n 'Cache-Control': 'public, max-age=31536000, immutable',\r\n 'X-Flexi-Font-Cache': 'MISS'\r\n });\r\n res.end(fontBuffer);\r\n\r\n } catch (error: any) {\r\n console.error('Font loading error:', error);\r\n res.writeHead(500, { 'Content-Type': 'text/plain' });\r\n res.end('Font loading failed');\r\n }\r\n}\r\n\r\n// Pre-built font configurations\r\nexport const fonts = {\r\n // Sans-serif\r\n inter: (config: Partial<FontConfig> = {}) => googleFont({ family: 'Inter', variable: '--font-inter', ...config }),\r\n roboto: (config: Partial<FontConfig> = {}) => googleFont({ family: 'Roboto', variable: '--font-roboto', ...config }),\r\n openSans: (config: Partial<FontConfig> = {}) => googleFont({ family: 'Open Sans', variable: '--font-open-sans', ...config }),\r\n poppins: (config: Partial<FontConfig> = {}) => googleFont({ family: 'Poppins', variable: '--font-poppins', ...config }),\r\n montserrat: (config: Partial<FontConfig> = {}) => googleFont({ family: 'Montserrat', variable: '--font-montserrat', ...config }),\r\n geist: (config: Partial<FontConfig> = {}) => googleFont({ family: 'Geist', variable: '--font-geist', ...config }),\r\n \r\n // Monospace\r\n firaCode: (config: Partial<FontConfig> = {}) => googleFont({ family: 'Fira Code', variable: '--font-fira-code', fallback: ['monospace'], ...config }),\r\n jetbrainsMono: (config: Partial<FontConfig> = {}) => googleFont({ family: 'JetBrains Mono', variable: '--font-jetbrains', fallback: ['monospace'], ...config }),\r\n geistMono: (config: Partial<FontConfig> = {}) => googleFont({ family: 'Geist Mono', variable: '--font-geist-mono', fallback: ['monospace'], ...config })\r\n};\r\n\r\nexport default {\r\n createFont,\r\n googleFont,\r\n localFont,\r\n generateFontCSS,\r\n generateFontPreloadTags,\r\n handleFontRequest,\r\n fonts,\r\n googleFonts\r\n};\r\n","/**\r\n * FlexiReact Build System\r\n * Uses esbuild for fast bundling of client and server code\r\n */\r\n\r\nimport * as esbuild from 'esbuild';\r\nimport fs from 'fs';\r\nimport path from 'path';\r\nimport { fileURLToPath } from 'url';\r\nimport { findFiles, ensureDir, cleanDir, generateHash, isClientComponent, isIsland } from '../utils.js';\r\nimport { buildRouteTree } from '../router/index.js';\r\n\r\nconst __filename = fileURLToPath(import.meta.url);\r\nconst __dirname = path.dirname(__filename);\r\n\r\n/**\r\n * Build configuration\r\n */\r\nexport const BuildMode = {\r\n DEVELOPMENT: 'development',\r\n PRODUCTION: 'production'\r\n};\r\n\r\n/**\r\n * Main build function\r\n */\r\nexport async function build(options) {\r\n const {\r\n projectRoot,\r\n config,\r\n mode = BuildMode.PRODUCTION,\r\n analyze = false\r\n } = options;\r\n\r\n const startTime = Date.now();\r\n const outDir = config.outDir;\r\n const isDev = mode === BuildMode.DEVELOPMENT;\r\n\r\n console.log('\\n⚡ FlexiReact Build\\n');\r\n console.log(` Mode: ${mode}`);\r\n console.log(` Output: ${outDir}\\n`);\r\n\r\n // Clean output directory\r\n cleanDir(outDir);\r\n ensureDir(path.join(outDir, 'client'));\r\n ensureDir(path.join(outDir, 'server'));\r\n ensureDir(path.join(outDir, 'static'));\r\n\r\n // Build routes\r\n const routes = buildRouteTree(config.pagesDir, config.layoutsDir);\r\n \r\n // Find all client components and islands\r\n const clientEntries = findClientEntries(config.pagesDir, config.layoutsDir);\r\n \r\n // Build client bundle\r\n console.log('📦 Building client bundle...');\r\n const clientResult = await buildClient({\r\n entries: clientEntries,\r\n outDir: path.join(outDir, 'client'),\r\n config,\r\n isDev\r\n });\r\n\r\n // Build server bundle\r\n console.log('📦 Building server bundle...');\r\n const serverResult = await buildServer({\r\n pagesDir: config.pagesDir,\r\n layoutsDir: config.layoutsDir,\r\n outDir: path.join(outDir, 'server'),\r\n config,\r\n isDev\r\n });\r\n\r\n // Copy public assets\r\n console.log('📁 Copying public assets...');\r\n await copyPublicAssets(config.publicDir, path.join(outDir, 'static'));\r\n\r\n // Generate manifest\r\n const manifest = generateManifest({\r\n routes,\r\n clientResult,\r\n serverResult,\r\n config\r\n });\r\n \r\n fs.writeFileSync(\r\n path.join(outDir, 'manifest.json'),\r\n JSON.stringify(manifest, null, 2)\r\n );\r\n\r\n const duration = Date.now() - startTime;\r\n \r\n console.log('\\n✨ Build complete!\\n');\r\n console.log(` Duration: ${duration}ms`);\r\n console.log(` Client chunks: ${clientResult.outputs.length}`);\r\n console.log(` Server modules: ${serverResult.outputs.length}`);\r\n console.log('');\r\n\r\n // Generate bundle analysis if requested\r\n let analysis = null;\r\n if (analyze) {\r\n analysis = generateBundleAnalysis(clientResult, serverResult, outDir);\r\n }\r\n\r\n return {\r\n success: true,\r\n duration,\r\n manifest,\r\n clientResult,\r\n serverResult,\r\n analysis\r\n };\r\n}\r\n\r\n/**\r\n * Generates bundle analysis data\r\n */\r\nfunction generateBundleAnalysis(clientResult, serverResult, outDir) {\r\n const files: Record<string, { size: number; gzipSize?: number }> = {};\r\n let totalSize = 0;\r\n let totalGzipSize = 0;\r\n\r\n // Analyze client outputs\r\n for (const output of clientResult.outputs || []) {\r\n if (output.path && fs.existsSync(output.path)) {\r\n const stat = fs.statSync(output.path);\r\n const relativePath = path.relative(outDir, output.path);\r\n \r\n // Estimate gzip size (roughly 30% of original for JS)\r\n const gzipSize = Math.round(stat.size * 0.3);\r\n \r\n files[relativePath] = {\r\n size: stat.size,\r\n gzipSize\r\n };\r\n \r\n totalSize += stat.size;\r\n totalGzipSize += gzipSize;\r\n }\r\n }\r\n\r\n // Analyze server outputs\r\n for (const output of serverResult.outputs || []) {\r\n if (output.path && fs.existsSync(output.path)) {\r\n const stat = fs.statSync(output.path);\r\n const relativePath = path.relative(outDir, output.path);\r\n \r\n files[relativePath] = {\r\n size: stat.size\r\n };\r\n \r\n totalSize += stat.size;\r\n }\r\n }\r\n\r\n return {\r\n files,\r\n totalSize,\r\n totalGzipSize,\r\n clientSize: clientResult.outputs?.reduce((sum, o) => {\r\n if (o.path && fs.existsSync(o.path)) {\r\n return sum + fs.statSync(o.path).size;\r\n }\r\n return sum;\r\n }, 0) || 0,\r\n serverSize: serverResult.outputs?.reduce((sum, o) => {\r\n if (o.path && fs.existsSync(o.path)) {\r\n return sum + fs.statSync(o.path).size;\r\n }\r\n return sum;\r\n }, 0) || 0\r\n };\r\n}\r\n\r\n/**\r\n * Finds all client component entries\r\n */\r\nfunction findClientEntries(pagesDir, layoutsDir) {\r\n const entries = [];\r\n const dirs = [pagesDir, layoutsDir].filter(d => fs.existsSync(d));\r\n\r\n for (const dir of dirs) {\r\n const files = findFiles(dir, /\\.(jsx|tsx)$/);\r\n \r\n for (const file of files) {\r\n if (isClientComponent(file) || isIsland(file)) {\r\n entries.push(file);\r\n }\r\n }\r\n }\r\n\r\n return entries;\r\n}\r\n\r\n/**\r\n * Builds client-side JavaScript\r\n */\r\nasync function buildClient(options) {\r\n const { entries, outDir, config, isDev } = options;\r\n\r\n if (entries.length === 0) {\r\n return { outputs: [] };\r\n }\r\n\r\n // Create entry points map\r\n const entryPoints = {};\r\n for (const entry of entries) {\r\n const name = path.basename(entry, path.extname(entry));\r\n const hash = generateHash(entry);\r\n entryPoints[`${name}-${hash}`] = entry;\r\n }\r\n\r\n // Add runtime entry\r\n const runtimePath = path.join(__dirname, '..', 'client', 'runtime.js');\r\n if (fs.existsSync(runtimePath)) {\r\n entryPoints['runtime'] = runtimePath;\r\n }\r\n\r\n try {\r\n const result = await esbuild.build({\r\n entryPoints,\r\n bundle: true,\r\n splitting: true,\r\n format: 'esm',\r\n outdir: outDir,\r\n minify: !isDev && config.build.minify,\r\n sourcemap: config.build.sourcemap,\r\n target: config.build.target,\r\n jsx: 'automatic',\r\n jsxImportSource: 'react',\r\n metafile: true,\r\n external: [],\r\n define: {\r\n 'process.env.NODE_ENV': JSON.stringify(isDev ? 'development' : 'production')\r\n },\r\n loader: {\r\n '.js': 'jsx',\r\n '.jsx': 'jsx',\r\n '.ts': 'tsx',\r\n '.tsx': 'tsx'\r\n }\r\n });\r\n\r\n const outputs = Object.keys(result.metafile.outputs).map(file => ({\r\n file: path.basename(file),\r\n size: result.metafile.outputs[file].bytes\r\n }));\r\n\r\n return { outputs, metafile: result.metafile };\r\n\r\n } catch (error) {\r\n console.error('Client build failed:', error);\r\n throw error;\r\n }\r\n}\r\n\r\n/**\r\n * Builds server-side modules\r\n */\r\nasync function buildServer(options) {\r\n const { pagesDir, layoutsDir, outDir, config, isDev } = options;\r\n\r\n const entries = [];\r\n \r\n // Find all page and layout files\r\n for (const dir of [pagesDir, layoutsDir]) {\r\n if (fs.existsSync(dir)) {\r\n entries.push(...findFiles(dir, /\\.(jsx|tsx|js|ts)$/));\r\n }\r\n }\r\n\r\n if (entries.length === 0) {\r\n return { outputs: [] };\r\n }\r\n\r\n // Create entry points\r\n const entryPoints = {};\r\n for (const entry of entries) {\r\n const relativePath = path.relative(pagesDir, entry);\r\n const name = relativePath.replace(/[\\/\\\\]/g, '_').replace(/\\.(jsx|tsx|js|ts)$/, '');\r\n entryPoints[name] = entry;\r\n }\r\n\r\n try {\r\n const result = await esbuild.build({\r\n entryPoints,\r\n bundle: true,\r\n format: 'esm',\r\n platform: 'node',\r\n outdir: outDir,\r\n minify: false, // Keep server code readable\r\n sourcemap: true,\r\n target: 'node18',\r\n jsx: 'automatic',\r\n jsxImportSource: 'react',\r\n metafile: true,\r\n packages: 'external', // Don't bundle node_modules\r\n loader: {\r\n '.js': 'jsx',\r\n '.jsx': 'jsx',\r\n '.ts': 'tsx',\r\n '.tsx': 'tsx'\r\n }\r\n });\r\n\r\n const outputs = Object.keys(result.metafile.outputs).map(file => ({\r\n file: path.basename(file),\r\n size: result.metafile.outputs[file].bytes\r\n }));\r\n\r\n return { outputs, metafile: result.metafile };\r\n\r\n } catch (error) {\r\n console.error('Server build failed:', error);\r\n throw error;\r\n }\r\n}\r\n\r\n/**\r\n * Copies public assets to output directory\r\n */\r\nasync function copyPublicAssets(publicDir, outDir) {\r\n if (!fs.existsSync(publicDir)) {\r\n return;\r\n }\r\n\r\n const copyRecursive = (src, dest) => {\r\n const entries = fs.readdirSync(src, { withFileTypes: true });\r\n \r\n ensureDir(dest);\r\n \r\n for (const entry of entries) {\r\n const srcPath = path.join(src, entry.name);\r\n const destPath = path.join(dest, entry.name);\r\n \r\n if (entry.isDirectory()) {\r\n copyRecursive(srcPath, destPath);\r\n } else {\r\n fs.copyFileSync(srcPath, destPath);\r\n }\r\n }\r\n };\r\n\r\n copyRecursive(publicDir, outDir);\r\n}\r\n\r\n/**\r\n * Generates build manifest\r\n */\r\nfunction generateManifest(options) {\r\n const { routes, clientResult, serverResult, config } = options;\r\n\r\n return {\r\n version: '2.0.0',\r\n generatedAt: new Date().toISOString(),\r\n routes: {\r\n pages: routes.pages.map(r => ({\r\n path: r.path,\r\n file: r.filePath,\r\n hasLayout: !!r.layout,\r\n hasLoading: !!r.loading,\r\n hasError: !!r.error\r\n })),\r\n api: routes.api.map(r => ({\r\n path: r.path,\r\n file: r.filePath\r\n }))\r\n },\r\n client: {\r\n chunks: clientResult.outputs || []\r\n },\r\n server: {\r\n modules: serverResult.outputs || []\r\n },\r\n config: {\r\n islands: config.islands.enabled,\r\n rsc: config.rsc.enabled\r\n }\r\n };\r\n}\r\n\r\n/**\r\n * Development build with watch mode\r\n */\r\nexport async function buildDev(options) {\r\n const { projectRoot, config, onChange } = options;\r\n\r\n const outDir = config.outDir;\r\n ensureDir(outDir);\r\n\r\n // Use esbuild's watch mode\r\n const ctx = await esbuild.context({\r\n entryPoints: findFiles(config.pagesDir, /\\.(jsx|tsx)$/),\r\n bundle: true,\r\n format: 'esm',\r\n outdir: path.join(outDir, 'dev'),\r\n sourcemap: true,\r\n jsx: 'automatic',\r\n jsxImportSource: 'react',\r\n loader: {\r\n '.js': 'jsx',\r\n '.jsx': 'jsx'\r\n },\r\n plugins: [{\r\n name: 'flexi-watch',\r\n setup(build) {\r\n build.onEnd(result => {\r\n if (result.errors.length === 0) {\r\n onChange?.();\r\n }\r\n });\r\n }\r\n }]\r\n });\r\n\r\n await ctx.watch();\r\n\r\n return ctx;\r\n}\r\n\r\nexport default {\r\n build,\r\n buildDev,\r\n BuildMode\r\n};\r\n","/**\r\n * FlexiReact Static Site Generation (SSG)\r\n * \r\n * SSG pre-renders pages at build time, generating static HTML files.\r\n * This provides the fastest possible page loads and enables CDN caching.\r\n * \r\n * Usage:\r\n * - Export getStaticProps() from a page to fetch data at build time\r\n * - Export getStaticPaths() for dynamic routes to specify which paths to pre-render\r\n * - Pages without these exports are rendered as static HTML\r\n */\r\n\r\nimport fs from 'fs';\r\nimport path from 'path';\r\nimport { pathToFileURL } from 'url';\r\nimport { renderPage } from '../render/index.js';\r\nimport { ensureDir, cleanDir } from '../utils.js';\r\n\r\n/**\r\n * SSG Build Result\r\n */\r\ninterface SSGPage {\r\n path: string;\r\n file: string;\r\n size: number;\r\n}\r\n\r\ninterface SSGError {\r\n path: string;\r\n error: string;\r\n}\r\n\r\nexport class SSGResult {\r\n pages: SSGPage[];\r\n errors: SSGError[];\r\n duration: number;\r\n\r\n constructor() {\r\n this.pages = [];\r\n this.errors = [];\r\n this.duration = 0;\r\n }\r\n\r\n addPage(pagePath: string, file: string, size: number) {\r\n this.pages.push({ path: pagePath, file, size });\r\n }\r\n\r\n addError(pagePath: string, error: Error) {\r\n this.errors.push({ path: pagePath, error: error.message });\r\n }\r\n\r\n get success() {\r\n return this.errors.length === 0;\r\n }\r\n\r\n get totalSize() {\r\n return this.pages.reduce((sum, p) => sum + p.size, 0);\r\n }\r\n}\r\n\r\n/**\r\n * Generates static pages for all routes\r\n */\r\nexport async function generateStaticSite(options) {\r\n const {\r\n routes,\r\n outDir,\r\n config,\r\n loadModule\r\n } = options;\r\n\r\n const result = new SSGResult();\r\n const startTime = Date.now();\r\n\r\n // Clean and create output directory\r\n const staticDir = path.join(outDir, 'static');\r\n cleanDir(staticDir);\r\n\r\n console.log('\\n📦 Generating static pages...\\n');\r\n\r\n for (const route of routes) {\r\n try {\r\n await generateRoutePage(route, staticDir, loadModule, result, config);\r\n } catch (error) {\r\n console.error(` ✗ ${route.path}: ${error.message}`);\r\n result.addError(route.path, error);\r\n }\r\n }\r\n\r\n result.duration = Date.now() - startTime;\r\n\r\n // Generate summary\r\n console.log('\\n' + '─'.repeat(50));\r\n console.log(` Generated ${result.pages.length} pages in ${result.duration}ms`);\r\n if (result.errors.length > 0) {\r\n console.log(` ${result.errors.length} errors occurred`);\r\n }\r\n console.log('─'.repeat(50) + '\\n');\r\n\r\n return result;\r\n}\r\n\r\n/**\r\n * Generates a single route's static page(s)\r\n */\r\nasync function generateRoutePage(route, outDir, loadModule, result, config) {\r\n const module = await loadModule(route.filePath);\r\n const Component = module.default;\r\n\r\n if (!Component) {\r\n throw new Error(`No default export in ${route.filePath}`);\r\n }\r\n\r\n // Check for getStaticPaths (dynamic routes)\r\n let paths = [{ params: {} }];\r\n \r\n if (route.path.includes(':') || route.path.includes('*')) {\r\n if (!module.getStaticPaths) {\r\n console.log(` ⊘ ${route.path} (dynamic, no getStaticPaths)`);\r\n return;\r\n }\r\n\r\n const staticPaths = await module.getStaticPaths();\r\n paths = staticPaths.paths || [];\r\n\r\n if (staticPaths.fallback === false && paths.length === 0) {\r\n console.log(` ⊘ ${route.path} (no paths to generate)`);\r\n return;\r\n }\r\n }\r\n\r\n // Generate page for each path\r\n for (const pathConfig of paths) {\r\n const params = pathConfig.params || {};\r\n const actualPath = substituteParams(route.path, params);\r\n\r\n try {\r\n // Get static props\r\n let props = { params };\r\n \r\n if (module.getStaticProps) {\r\n const staticProps = await module.getStaticProps({ params });\r\n \r\n if (staticProps.notFound) {\r\n console.log(` ⊘ ${actualPath} (notFound)`);\r\n continue;\r\n }\r\n \r\n if (staticProps.redirect) {\r\n // Generate redirect HTML\r\n await generateRedirectPage(actualPath, staticProps.redirect, outDir, result);\r\n continue;\r\n }\r\n \r\n props = { ...props, ...staticProps.props };\r\n }\r\n\r\n // Render the page\r\n const html = await renderPage({\r\n Component,\r\n props,\r\n title: module.title || module.metadata?.title || 'FlexiReact App',\r\n meta: module.metadata || {},\r\n isSSG: true\r\n });\r\n\r\n // Write to file\r\n const filePath = getOutputPath(actualPath, outDir);\r\n ensureDir(path.dirname(filePath));\r\n fs.writeFileSync(filePath, html);\r\n\r\n const size = Buffer.byteLength(html, 'utf8');\r\n result.addPage(actualPath, filePath, size);\r\n \r\n console.log(` ✓ ${actualPath} (${formatSize(size)})`);\r\n\r\n } catch (error) {\r\n result.addError(actualPath, error);\r\n console.error(` ✗ ${actualPath}: ${error.message}`);\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Generates a redirect page\r\n */\r\nasync function generateRedirectPage(fromPath, redirect, outDir, result) {\r\n const { destination, permanent = false } = redirect;\r\n const statusCode = permanent ? 301 : 302;\r\n\r\n const html = `<!DOCTYPE html>\r\n<html>\r\n<head>\r\n <meta charset=\"utf-8\">\r\n <meta http-equiv=\"refresh\" content=\"0;url=${destination}\">\r\n <link rel=\"canonical\" href=\"${destination}\">\r\n <title>Redirecting...</title>\r\n</head>\r\n<body>\r\n <p>Redirecting to <a href=\"${destination}\">${destination}</a></p>\r\n <script>window.location.href = \"${destination}\";</script>\r\n</body>\r\n</html>`;\r\n\r\n const filePath = getOutputPath(fromPath, outDir);\r\n ensureDir(path.dirname(filePath));\r\n fs.writeFileSync(filePath, html);\r\n\r\n const size = Buffer.byteLength(html, 'utf8');\r\n result.addPage(fromPath, filePath, size);\r\n \r\n console.log(` ↪ ${fromPath} → ${destination}`);\r\n}\r\n\r\n/**\r\n * Substitutes route params into path\r\n */\r\nfunction substituteParams(routePath, params) {\r\n let result = routePath;\r\n \r\n for (const [key, value] of Object.entries(params)) {\r\n result = result.replace(`:${key}`, value);\r\n result = result.replace(`*${key}`, value);\r\n }\r\n \r\n return result;\r\n}\r\n\r\n/**\r\n * Gets the output file path for a route\r\n */\r\nfunction getOutputPath(routePath, outDir) {\r\n if (routePath === '/') {\r\n return path.join(outDir, 'index.html');\r\n }\r\n \r\n // Remove leading slash and add index.html\r\n const cleanPath = routePath.replace(/^\\//, '');\r\n return path.join(outDir, cleanPath, 'index.html');\r\n}\r\n\r\n/**\r\n * Formats file size\r\n */\r\nfunction formatSize(bytes) {\r\n if (bytes < 1024) return `${bytes} B`;\r\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\r\n return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;\r\n}\r\n\r\n/**\r\n * Incremental Static Regeneration (ISR) support\r\n * Allows pages to be regenerated after a specified interval\r\n */\r\ninterface ISRCacheEntry {\r\n html: string;\r\n generatedAt: number;\r\n revalidateAfter: number | null;\r\n}\r\n\r\nexport class ISRManager {\r\n cache: Map<string, ISRCacheEntry>;\r\n revalidating: Set<string>;\r\n defaultRevalidate: number;\r\n\r\n constructor(options: { defaultRevalidate?: number } = {}) {\r\n this.cache = new Map();\r\n this.revalidating = new Set();\r\n this.defaultRevalidate = options.defaultRevalidate || 60; // seconds\r\n }\r\n\r\n /**\r\n * Gets a cached page or regenerates it\r\n */\r\n async getPage(routePath, generator) {\r\n const cached = this.cache.get(routePath);\r\n const now = Date.now();\r\n\r\n if (cached) {\r\n // Check if revalidation is needed\r\n if (cached.revalidateAfter && now > cached.revalidateAfter) {\r\n // Trigger background revalidation\r\n this.revalidateInBackground(routePath, generator);\r\n }\r\n return cached.html;\r\n }\r\n\r\n // Generate fresh page\r\n const result = await generator();\r\n this.cache.set(routePath, {\r\n html: result.html,\r\n generatedAt: now,\r\n revalidateAfter: result.revalidate \r\n ? now + (result.revalidate * 1000)\r\n : null\r\n });\r\n\r\n return result.html;\r\n }\r\n\r\n /**\r\n * Revalidates a page in the background\r\n */\r\n async revalidateInBackground(routePath, generator) {\r\n if (this.revalidating.has(routePath)) return;\r\n\r\n this.revalidating.add(routePath);\r\n\r\n try {\r\n const result = await generator();\r\n const now = Date.now();\r\n \r\n this.cache.set(routePath, {\r\n html: result.html,\r\n generatedAt: now,\r\n revalidateAfter: result.revalidate \r\n ? now + (result.revalidate * 1000)\r\n : null\r\n });\r\n } catch (error) {\r\n console.error(`ISR revalidation failed for ${routePath}:`, error);\r\n } finally {\r\n this.revalidating.delete(routePath);\r\n }\r\n }\r\n\r\n /**\r\n * Invalidates a cached page\r\n */\r\n invalidate(routePath) {\r\n this.cache.delete(routePath);\r\n }\r\n\r\n /**\r\n * Clears all cached pages\r\n */\r\n clear() {\r\n this.cache.clear();\r\n }\r\n}\r\n\r\nexport default {\r\n generateStaticSite,\r\n SSGResult,\r\n ISRManager\r\n};\r\n","/**\r\n * FlexiReact React Server Components (RSC) System\r\n * \r\n * RSC allows components to run exclusively on the server, reducing client bundle size\r\n * and enabling direct database/filesystem access in components.\r\n * \r\n * Usage:\r\n * - Add 'use server' at the top of a component file to make it a Server Component\r\n * - Add 'use client' at the top to make it a Client Component (hydrated on client)\r\n * - Server Components can import Client Components, but not vice versa\r\n */\r\n\r\nimport React from 'react';\r\nimport { renderToString } from 'react-dom/server';\r\nimport { isServerComponent, isClientComponent } from '../utils.js';\r\n\r\n/**\r\n * RSC Payload format for streaming\r\n */\r\nexport const RSC_CONTENT_TYPE = 'text/x-component';\r\n\r\n/**\r\n * Processes a component tree for RSC\r\n * Server components are rendered to HTML, client components are serialized\r\n */\r\nexport async function processServerComponent(Component, props, context) {\r\n const componentInfo = {\r\n isServer: true,\r\n rendered: null,\r\n clientComponents: [],\r\n serverData: {}\r\n };\r\n\r\n try {\r\n // If component has async data fetching\r\n if (Component.getServerData) {\r\n componentInfo.serverData = await Component.getServerData(context);\r\n props = { ...props, ...componentInfo.serverData };\r\n }\r\n\r\n // Render the server component\r\n const element = React.createElement(Component, props);\r\n componentInfo.rendered = renderToString(element);\r\n\r\n } catch (error) {\r\n console.error('RSC Error:', error);\r\n throw error;\r\n }\r\n\r\n return componentInfo;\r\n}\r\n\r\n/**\r\n * Creates a client component reference for RSC payload\r\n */\r\nexport function createClientReference(componentPath, props) {\r\n return {\r\n $$typeof: Symbol.for('react.client.reference'),\r\n $$id: componentPath,\r\n $$props: props\r\n };\r\n}\r\n\r\n/**\r\n * Serializes RSC payload for streaming\r\n */\r\nexport function serializeRSCPayload(componentTree) {\r\n const payload = {\r\n type: 'rsc',\r\n tree: serializeNode(componentTree),\r\n timestamp: Date.now()\r\n };\r\n\r\n return JSON.stringify(payload);\r\n}\r\n\r\n/**\r\n * Serializes a React node for RSC\r\n */\r\nfunction serializeNode(node) {\r\n if (node === null || node === undefined) {\r\n return null;\r\n }\r\n\r\n if (typeof node === 'string' || typeof node === 'number' || typeof node === 'boolean') {\r\n return node;\r\n }\r\n\r\n if (Array.isArray(node)) {\r\n return node.map(serializeNode);\r\n }\r\n\r\n if (React.isValidElement(node)) {\r\n const { type, props } = node;\r\n\r\n // Handle client component references\r\n const typeAny = type as any;\r\n if (typeAny.$$typeof === Symbol.for('react.client.reference')) {\r\n return {\r\n $$type: 'client',\r\n $$id: typeAny.$$id,\r\n props: serializeProps(props)\r\n };\r\n }\r\n\r\n // Handle regular elements\r\n const typeName = typeof type === 'string' ? type : (typeAny.displayName || typeAny.name || 'Unknown');\r\n\r\n return {\r\n $$type: 'element',\r\n type: typeName,\r\n props: serializeProps(props)\r\n };\r\n }\r\n\r\n return String(node);\r\n}\r\n\r\n/**\r\n * Serializes props, handling special cases\r\n */\r\nfunction serializeProps(props: Record<string, any>) {\r\n const serialized: Record<string, any> = {};\r\n\r\n for (const [key, value] of Object.entries(props)) {\r\n if (key === 'children') {\r\n serialized.children = serializeNode(value);\r\n } else if (typeof value === 'function') {\r\n // Functions can't be serialized - mark as client action\r\n serialized[key] = { $$type: 'action', name: value.name };\r\n } else if (value instanceof Date) {\r\n serialized[key] = { $$type: 'date', value: value.toISOString() };\r\n } else if (typeof value === 'object' && value !== null) {\r\n serialized[key] = JSON.parse(JSON.stringify(value));\r\n } else {\r\n serialized[key] = value;\r\n }\r\n }\r\n\r\n return serialized;\r\n}\r\n\r\n/**\r\n * Server Actions support\r\n * Allows calling server functions from client components\r\n */\r\nexport function createServerAction(fn, actionId) {\r\n // Mark function as server action\r\n fn.$$typeof = Symbol.for('react.server.action');\r\n fn.$$id = actionId;\r\n \r\n return fn;\r\n}\r\n\r\n/**\r\n * Handles server action invocation\r\n */\r\nexport async function handleServerAction(actionId, args, context) {\r\n // Actions are registered during build\r\n const action = globalThis.__FLEXI_ACTIONS__?.[actionId];\r\n \r\n if (!action) {\r\n throw new Error(`Server action not found: ${actionId}`);\r\n }\r\n\r\n return await action(...args, context);\r\n}\r\n\r\n/**\r\n * RSC Boundary component\r\n * Marks the boundary between server and client rendering\r\n */\r\nexport function ServerBoundary({ children, fallback }) {\r\n return children;\r\n}\r\n\r\n/**\r\n * Client Boundary component\r\n * Marks components that should be hydrated on the client\r\n */\r\nexport function ClientBoundary({ children, fallback }) {\r\n // On server, render children normally\r\n // On client, this will be hydrated\r\n return React.createElement('div', {\r\n 'data-flexi-client': 'true',\r\n children\r\n });\r\n}\r\n\r\nexport default {\r\n processServerComponent,\r\n createClientReference,\r\n serializeRSCPayload,\r\n createServerAction,\r\n handleServerAction,\r\n ServerBoundary,\r\n ClientBoundary,\r\n RSC_CONTENT_TYPE\r\n};\r\n","/**\r\n * FlexiReact Universal Edge Runtime\r\n * \r\n * Works on:\r\n * - Node.js\r\n * - Bun\r\n * - Deno\r\n * - Cloudflare Workers\r\n * - Vercel Edge\r\n * - Any Web-standard runtime\r\n */\r\n\r\n// Detect runtime environment\r\nexport type RuntimeEnvironment = \r\n | 'node'\r\n | 'bun'\r\n | 'deno'\r\n | 'cloudflare'\r\n | 'vercel-edge'\r\n | 'netlify-edge'\r\n | 'fastly'\r\n | 'unknown';\r\n\r\nexport function detectRuntime(): RuntimeEnvironment {\r\n // Bun\r\n if (typeof globalThis.Bun !== 'undefined') {\r\n return 'bun';\r\n }\r\n \r\n // Deno\r\n if (typeof globalThis.Deno !== 'undefined') {\r\n return 'deno';\r\n }\r\n \r\n // Cloudflare Workers\r\n if (typeof globalThis.caches !== 'undefined' && typeof (globalThis as any).WebSocketPair !== 'undefined') {\r\n return 'cloudflare';\r\n }\r\n \r\n // Vercel Edge\r\n if (typeof process !== 'undefined' && process.env?.VERCEL_EDGE === '1') {\r\n return 'vercel-edge';\r\n }\r\n \r\n // Netlify Edge\r\n if (typeof globalThis.Netlify !== 'undefined') {\r\n return 'netlify-edge';\r\n }\r\n \r\n // Node.js\r\n if (typeof process !== 'undefined' && process.versions?.node) {\r\n return 'node';\r\n }\r\n \r\n return 'unknown';\r\n}\r\n\r\n// Runtime capabilities\r\nexport interface RuntimeCapabilities {\r\n hasFileSystem: boolean;\r\n hasWebCrypto: boolean;\r\n hasWebStreams: boolean;\r\n hasFetch: boolean;\r\n hasWebSocket: boolean;\r\n hasKV: boolean;\r\n hasCache: boolean;\r\n maxExecutionTime: number; // ms, 0 = unlimited\r\n maxMemory: number; // bytes, 0 = unlimited\r\n}\r\n\r\nexport function getRuntimeCapabilities(): RuntimeCapabilities {\r\n const runtime = detectRuntime();\r\n \r\n switch (runtime) {\r\n case 'cloudflare':\r\n return {\r\n hasFileSystem: false,\r\n hasWebCrypto: true,\r\n hasWebStreams: true,\r\n hasFetch: true,\r\n hasWebSocket: true,\r\n hasKV: true,\r\n hasCache: true,\r\n maxExecutionTime: 30000, // 30s for paid, 10ms for free\r\n maxMemory: 128 * 1024 * 1024 // 128MB\r\n };\r\n \r\n case 'vercel-edge':\r\n return {\r\n hasFileSystem: false,\r\n hasWebCrypto: true,\r\n hasWebStreams: true,\r\n hasFetch: true,\r\n hasWebSocket: false,\r\n hasKV: true, // Vercel KV\r\n hasCache: true,\r\n maxExecutionTime: 30000,\r\n maxMemory: 128 * 1024 * 1024\r\n };\r\n \r\n case 'deno':\r\n return {\r\n hasFileSystem: true,\r\n hasWebCrypto: true,\r\n hasWebStreams: true,\r\n hasFetch: true,\r\n hasWebSocket: true,\r\n hasKV: true, // Deno KV\r\n hasCache: true,\r\n maxExecutionTime: 0,\r\n maxMemory: 0\r\n };\r\n \r\n case 'bun':\r\n return {\r\n hasFileSystem: true,\r\n hasWebCrypto: true,\r\n hasWebStreams: true,\r\n hasFetch: true,\r\n hasWebSocket: true,\r\n hasKV: false,\r\n hasCache: false,\r\n maxExecutionTime: 0,\r\n maxMemory: 0\r\n };\r\n \r\n case 'node':\r\n default:\r\n return {\r\n hasFileSystem: true,\r\n hasWebCrypto: true,\r\n hasWebStreams: true,\r\n hasFetch: true,\r\n hasWebSocket: true,\r\n hasKV: false,\r\n hasCache: false,\r\n maxExecutionTime: 0,\r\n maxMemory: 0\r\n };\r\n }\r\n}\r\n\r\n// Runtime info\r\nexport const runtime = {\r\n name: detectRuntime(),\r\n capabilities: getRuntimeCapabilities(),\r\n \r\n get isEdge(): boolean {\r\n return ['cloudflare', 'vercel-edge', 'netlify-edge', 'fastly'].includes(this.name);\r\n },\r\n \r\n get isServer(): boolean {\r\n return ['node', 'bun', 'deno'].includes(this.name);\r\n },\r\n \r\n get supportsStreaming(): boolean {\r\n return this.capabilities.hasWebStreams;\r\n }\r\n};\r\n\r\nexport default runtime;\r\n","/**\r\n * Fetch API Polyfill for Universal Compatibility\r\n * \r\n * Ensures Request, Response, Headers work everywhere\r\n */\r\n\r\n// Use native Web APIs if available, otherwise polyfill\r\nconst globalFetch = globalThis.fetch;\r\nconst GlobalRequest = globalThis.Request;\r\nconst GlobalResponse = globalThis.Response;\r\nconst GlobalHeaders = globalThis.Headers;\r\n\r\n// Extended Request with FlexiReact helpers\r\nexport class FlexiRequest extends GlobalRequest {\r\n private _parsedUrl?: URL;\r\n private _cookies?: Map<string, string>;\r\n \r\n constructor(input: RequestInfo | URL, init?: RequestInit) {\r\n super(input, init);\r\n }\r\n \r\n get pathname(): string {\r\n if (!this._parsedUrl) {\r\n this._parsedUrl = new URL(this.url);\r\n }\r\n return this._parsedUrl.pathname;\r\n }\r\n \r\n get searchParams(): URLSearchParams {\r\n if (!this._parsedUrl) {\r\n this._parsedUrl = new URL(this.url);\r\n }\r\n return this._parsedUrl.searchParams;\r\n }\r\n \r\n get cookies(): Map<string, string> {\r\n if (!this._cookies) {\r\n this._cookies = new Map();\r\n const cookieHeader = this.headers.get('cookie');\r\n if (cookieHeader) {\r\n cookieHeader.split(';').forEach(cookie => {\r\n const [name, ...rest] = cookie.trim().split('=');\r\n if (name) {\r\n this._cookies!.set(name, rest.join('='));\r\n }\r\n });\r\n }\r\n }\r\n return this._cookies;\r\n }\r\n \r\n cookie(name: string): string | undefined {\r\n return this.cookies.get(name);\r\n }\r\n \r\n // Parse JSON body\r\n async jsonBody<T = any>(): Promise<T> {\r\n return this.json();\r\n }\r\n \r\n // Parse form data\r\n async formBody(): Promise<FormData> {\r\n return this.formData();\r\n }\r\n \r\n // Get query param\r\n query(name: string): string | null {\r\n return this.searchParams.get(name);\r\n }\r\n \r\n // Get all query params\r\n queryAll(name: string): string[] {\r\n return this.searchParams.getAll(name);\r\n }\r\n}\r\n\r\n// Extended Response with FlexiReact helpers\r\nexport class FlexiResponse extends GlobalResponse {\r\n // Static helpers for common responses\r\n \r\n static json(data: any, init?: ResponseInit): FlexiResponse {\r\n const headers = new Headers(init?.headers);\r\n headers.set('Content-Type', 'application/json');\r\n \r\n return new FlexiResponse(JSON.stringify(data), {\r\n ...init,\r\n headers\r\n });\r\n }\r\n \r\n static html(html: string, init?: ResponseInit): FlexiResponse {\r\n const headers = new Headers(init?.headers);\r\n headers.set('Content-Type', 'text/html; charset=utf-8');\r\n \r\n return new FlexiResponse(html, {\r\n ...init,\r\n headers\r\n });\r\n }\r\n \r\n static text(text: string, init?: ResponseInit): FlexiResponse {\r\n const headers = new Headers(init?.headers);\r\n headers.set('Content-Type', 'text/plain; charset=utf-8');\r\n \r\n return new FlexiResponse(text, {\r\n ...init,\r\n headers\r\n });\r\n }\r\n \r\n static redirect(url: string, status: 301 | 302 | 303 | 307 | 308 = 307): FlexiResponse {\r\n return new FlexiResponse(null, {\r\n status,\r\n headers: { Location: url }\r\n });\r\n }\r\n \r\n static notFound(message: string = 'Not Found'): FlexiResponse {\r\n return new FlexiResponse(message, {\r\n status: 404,\r\n headers: { 'Content-Type': 'text/plain' }\r\n });\r\n }\r\n \r\n static error(message: string = 'Internal Server Error', status: number = 500): FlexiResponse {\r\n return new FlexiResponse(message, {\r\n status,\r\n headers: { 'Content-Type': 'text/plain' }\r\n });\r\n }\r\n \r\n // Stream response\r\n static stream(\r\n stream: ReadableStream,\r\n init?: ResponseInit\r\n ): FlexiResponse {\r\n return new FlexiResponse(stream, init);\r\n }\r\n \r\n // Set cookie helper\r\n withCookie(\r\n name: string,\r\n value: string,\r\n options: {\r\n maxAge?: number;\r\n expires?: Date;\r\n path?: string;\r\n domain?: string;\r\n secure?: boolean;\r\n httpOnly?: boolean;\r\n sameSite?: 'Strict' | 'Lax' | 'None';\r\n } = {}\r\n ): FlexiResponse {\r\n const parts = [`${name}=${encodeURIComponent(value)}`];\r\n \r\n if (options.maxAge !== undefined) parts.push(`Max-Age=${options.maxAge}`);\r\n if (options.expires) parts.push(`Expires=${options.expires.toUTCString()}`);\r\n if (options.path) parts.push(`Path=${options.path}`);\r\n if (options.domain) parts.push(`Domain=${options.domain}`);\r\n if (options.secure) parts.push('Secure');\r\n if (options.httpOnly) parts.push('HttpOnly');\r\n if (options.sameSite) parts.push(`SameSite=${options.sameSite}`);\r\n \r\n const headers = new Headers(this.headers);\r\n headers.append('Set-Cookie', parts.join('; '));\r\n \r\n return new FlexiResponse(this.body, {\r\n status: this.status,\r\n statusText: this.statusText,\r\n headers\r\n });\r\n }\r\n \r\n // Add headers helper\r\n withHeaders(newHeaders: Record<string, string>): FlexiResponse {\r\n const headers = new Headers(this.headers);\r\n Object.entries(newHeaders).forEach(([key, value]) => {\r\n headers.set(key, value);\r\n });\r\n \r\n return new FlexiResponse(this.body, {\r\n status: this.status,\r\n statusText: this.statusText,\r\n headers\r\n });\r\n }\r\n}\r\n\r\n// Extended Headers\r\nexport class FlexiHeaders extends GlobalHeaders {\r\n // Get bearer token\r\n getBearerToken(): string | null {\r\n const auth = this.get('Authorization');\r\n if (auth?.startsWith('Bearer ')) {\r\n return auth.slice(7);\r\n }\r\n return null;\r\n }\r\n \r\n // Get basic auth credentials\r\n getBasicAuth(): { username: string; password: string } | null {\r\n const auth = this.get('Authorization');\r\n if (auth?.startsWith('Basic ')) {\r\n try {\r\n const decoded = atob(auth.slice(6));\r\n const [username, password] = decoded.split(':');\r\n return { username, password };\r\n } catch {\r\n return null;\r\n }\r\n }\r\n return null;\r\n }\r\n \r\n // Check content type\r\n isJson(): boolean {\r\n return this.get('Content-Type')?.includes('application/json') ?? false;\r\n }\r\n \r\n isFormData(): boolean {\r\n const ct = this.get('Content-Type') ?? '';\r\n return ct.includes('multipart/form-data') || ct.includes('application/x-www-form-urlencoded');\r\n }\r\n \r\n isHtml(): boolean {\r\n return this.get('Accept')?.includes('text/html') ?? false;\r\n }\r\n}\r\n\r\n// Export both native and extended versions\r\nexport { \r\n FlexiRequest as Request,\r\n FlexiResponse as Response,\r\n FlexiHeaders as Headers\r\n};\r\n\r\n// Also export native versions for compatibility\r\nexport const NativeRequest = GlobalRequest;\r\nexport const NativeResponse = GlobalResponse;\r\nexport const NativeHeaders = GlobalHeaders;\r\n\r\nexport default {\r\n Request: FlexiRequest,\r\n Response: FlexiResponse,\r\n Headers: FlexiHeaders,\r\n fetch: globalFetch\r\n};\r\n","/**\r\n * FlexiReact Universal Cache System\r\n * \r\n * Smart caching that works on:\r\n * - Cloudflare Workers (Cache API + KV)\r\n * - Vercel Edge (Edge Config + KV)\r\n * - Deno (Deno KV)\r\n * - Node.js/Bun (In-memory + File cache)\r\n */\r\n\r\nimport { detectRuntime } from './runtime.js';\r\n\r\n// Cache entry\r\nexport interface CacheEntry<T = any> {\r\n value: T;\r\n expires: number; // timestamp\r\n stale?: number; // stale-while-revalidate timestamp\r\n tags?: string[];\r\n etag?: string;\r\n}\r\n\r\n// Cache options\r\nexport interface CacheOptions {\r\n ttl?: number; // seconds\r\n staleWhileRevalidate?: number; // seconds\r\n tags?: string[];\r\n key?: string;\r\n revalidate?: number | false; // ISR-style revalidation\r\n}\r\n\r\n// Cache storage interface\r\nexport interface CacheStorage {\r\n get<T>(key: string): Promise<CacheEntry<T> | null>;\r\n set<T>(key: string, entry: CacheEntry<T>): Promise<void>;\r\n delete(key: string): Promise<void>;\r\n deleteByTag(tag: string): Promise<void>;\r\n clear(): Promise<void>;\r\n}\r\n\r\n// In-memory cache (fallback)\r\nclass MemoryCache implements CacheStorage {\r\n private store = new Map<string, CacheEntry>();\r\n private tagIndex = new Map<string, Set<string>>();\r\n \r\n async get<T>(key: string): Promise<CacheEntry<T> | null> {\r\n const entry = this.store.get(key);\r\n if (!entry) return null;\r\n \r\n // Check expiration\r\n if (entry.expires && entry.expires < Date.now()) {\r\n // Check stale-while-revalidate\r\n if (entry.stale && entry.stale > Date.now()) {\r\n return { ...entry, value: entry.value as T };\r\n }\r\n this.store.delete(key);\r\n return null;\r\n }\r\n \r\n return { ...entry, value: entry.value as T };\r\n }\r\n \r\n async set<T>(key: string, entry: CacheEntry<T>): Promise<void> {\r\n this.store.set(key, entry);\r\n \r\n // Index by tags\r\n if (entry.tags) {\r\n entry.tags.forEach(tag => {\r\n if (!this.tagIndex.has(tag)) {\r\n this.tagIndex.set(tag, new Set());\r\n }\r\n this.tagIndex.get(tag)!.add(key);\r\n });\r\n }\r\n }\r\n \r\n async delete(key: string): Promise<void> {\r\n this.store.delete(key);\r\n }\r\n \r\n async deleteByTag(tag: string): Promise<void> {\r\n const keys = this.tagIndex.get(tag);\r\n if (keys) {\r\n keys.forEach(key => this.store.delete(key));\r\n this.tagIndex.delete(tag);\r\n }\r\n }\r\n \r\n async clear(): Promise<void> {\r\n this.store.clear();\r\n this.tagIndex.clear();\r\n }\r\n}\r\n\r\n// Cloudflare KV cache\r\nclass CloudflareCache implements CacheStorage {\r\n private kv: any;\r\n \r\n constructor(kv: any) {\r\n this.kv = kv;\r\n }\r\n \r\n async get<T>(key: string): Promise<CacheEntry<T> | null> {\r\n try {\r\n const data = await this.kv.get(key, 'json');\r\n if (!data) return null;\r\n \r\n const entry = data as CacheEntry<T>;\r\n if (entry.expires && entry.expires < Date.now()) {\r\n if (entry.stale && entry.stale > Date.now()) {\r\n return entry;\r\n }\r\n await this.kv.delete(key);\r\n return null;\r\n }\r\n \r\n return entry;\r\n } catch {\r\n return null;\r\n }\r\n }\r\n \r\n async set<T>(key: string, entry: CacheEntry<T>): Promise<void> {\r\n const ttl = entry.expires ? Math.ceil((entry.expires - Date.now()) / 1000) : undefined;\r\n await this.kv.put(key, JSON.stringify(entry), { expirationTtl: ttl });\r\n }\r\n \r\n async delete(key: string): Promise<void> {\r\n await this.kv.delete(key);\r\n }\r\n \r\n async deleteByTag(tag: string): Promise<void> {\r\n // KV doesn't support tag-based deletion natively\r\n // Would need to maintain a tag index\r\n console.warn('Tag-based deletion not fully supported in Cloudflare KV');\r\n }\r\n \r\n async clear(): Promise<void> {\r\n // KV doesn't support clear\r\n console.warn('Clear not supported in Cloudflare KV');\r\n }\r\n}\r\n\r\n// Deno KV cache\r\nclass DenoKVCache implements CacheStorage {\r\n private kv: any;\r\n \r\n constructor() {\r\n // @ts-ignore - Deno global\r\n this.kv = Deno.openKv();\r\n }\r\n \r\n async get<T>(key: string): Promise<CacheEntry<T> | null> {\r\n try {\r\n const kv = await this.kv;\r\n const result = await kv.get(['cache', key]);\r\n if (!result.value) return null;\r\n \r\n const entry = result.value as CacheEntry<T>;\r\n if (entry.expires && entry.expires < Date.now()) {\r\n if (entry.stale && entry.stale > Date.now()) {\r\n return entry;\r\n }\r\n await kv.delete(['cache', key]);\r\n return null;\r\n }\r\n \r\n return entry;\r\n } catch {\r\n return null;\r\n }\r\n }\r\n \r\n async set<T>(key: string, entry: CacheEntry<T>): Promise<void> {\r\n const kv = await this.kv;\r\n await kv.set(['cache', key], entry);\r\n }\r\n \r\n async delete(key: string): Promise<void> {\r\n const kv = await this.kv;\r\n await kv.delete(['cache', key]);\r\n }\r\n \r\n async deleteByTag(tag: string): Promise<void> {\r\n // Would need tag index\r\n console.warn('Tag-based deletion requires tag index in Deno KV');\r\n }\r\n \r\n async clear(): Promise<void> {\r\n // Would need to iterate all keys\r\n console.warn('Clear requires iteration in Deno KV');\r\n }\r\n}\r\n\r\n// Create cache based on runtime\r\nfunction createCacheStorage(options?: { kv?: any }): CacheStorage {\r\n const runtime = detectRuntime();\r\n \r\n switch (runtime) {\r\n case 'cloudflare':\r\n if (options?.kv) {\r\n return new CloudflareCache(options.kv);\r\n }\r\n return new MemoryCache();\r\n \r\n case 'deno':\r\n return new DenoKVCache();\r\n \r\n case 'node':\r\n case 'bun':\r\n default:\r\n return new MemoryCache();\r\n }\r\n}\r\n\r\n// Main cache instance\r\nlet cacheStorage: CacheStorage = new MemoryCache();\r\n\r\n// Initialize cache with platform-specific storage\r\nexport function initCache(options?: { kv?: any }): void {\r\n cacheStorage = createCacheStorage(options);\r\n}\r\n\r\n// Cache function wrapper (like React cache)\r\nexport function cacheFunction<T extends (...args: any[]) => Promise<any>>(\r\n fn: T,\r\n options: CacheOptions = {}\r\n): T {\r\n const { ttl = 60, staleWhileRevalidate = 0, tags = [] } = options;\r\n \r\n return (async (...args: any[]) => {\r\n const key = options.key || `fn:${fn.name}:${JSON.stringify(args)}`;\r\n \r\n // Try cache first\r\n const cached = await cacheStorage.get(key);\r\n if (cached) {\r\n // Check if stale and needs revalidation\r\n if (cached.expires < Date.now() && cached.stale && cached.stale > Date.now()) {\r\n // Return stale data, revalidate in background\r\n queueMicrotask(async () => {\r\n try {\r\n const fresh = await fn(...args);\r\n await cacheStorage.set(key, {\r\n value: fresh,\r\n expires: Date.now() + ttl * 1000,\r\n stale: Date.now() + (ttl + staleWhileRevalidate) * 1000,\r\n tags\r\n });\r\n } catch (e) {\r\n console.error('Background revalidation failed:', e);\r\n }\r\n });\r\n }\r\n return cached.value;\r\n }\r\n \r\n // Execute function\r\n const result = await fn(...args);\r\n \r\n // Cache result\r\n await cacheStorage.set(key, {\r\n value: result,\r\n expires: Date.now() + ttl * 1000,\r\n stale: staleWhileRevalidate ? Date.now() + (ttl + staleWhileRevalidate) * 1000 : undefined,\r\n tags\r\n });\r\n \r\n return result;\r\n }) as T;\r\n}\r\n\r\n// Unstable cache (Next.js compatible API)\r\nexport function unstable_cache<T extends (...args: any[]) => Promise<any>>(\r\n fn: T,\r\n keyParts?: string[],\r\n options?: { revalidate?: number | false; tags?: string[] }\r\n): T {\r\n return cacheFunction(fn, {\r\n key: keyParts?.join(':'),\r\n ttl: typeof options?.revalidate === 'number' ? options.revalidate : 3600,\r\n tags: options?.tags\r\n });\r\n}\r\n\r\n// Revalidate by tag\r\nexport async function revalidateTag(tag: string): Promise<void> {\r\n await cacheStorage.deleteByTag(tag);\r\n}\r\n\r\n// Revalidate by path\r\nexport async function revalidatePath(path: string): Promise<void> {\r\n await cacheStorage.delete(`page:${path}`);\r\n}\r\n\r\n// Cache object for direct access\r\nexport const cache = {\r\n get: <T>(key: string) => cacheStorage.get<T>(key),\r\n set: <T>(key: string, value: T, options: CacheOptions = {}) => {\r\n const { ttl = 60, staleWhileRevalidate = 0, tags = [] } = options;\r\n return cacheStorage.set(key, {\r\n value,\r\n expires: Date.now() + ttl * 1000,\r\n stale: staleWhileRevalidate ? Date.now() + (ttl + staleWhileRevalidate) * 1000 : undefined,\r\n tags\r\n });\r\n },\r\n delete: (key: string) => cacheStorage.delete(key),\r\n deleteByTag: (tag: string) => cacheStorage.deleteByTag(tag),\r\n clear: () => cacheStorage.clear(),\r\n \r\n // Wrap function with caching\r\n wrap: cacheFunction,\r\n \r\n // Next.js compatible\r\n unstable_cache,\r\n revalidateTag,\r\n revalidatePath\r\n};\r\n\r\n// Request-level cache (per-request deduplication)\r\nconst requestCache = new WeakMap<Request, Map<string, any>>();\r\n\r\nexport function getRequestCache(request: Request): Map<string, any> {\r\n if (!requestCache.has(request)) {\r\n requestCache.set(request, new Map());\r\n }\r\n return requestCache.get(request)!;\r\n}\r\n\r\n// React-style cache for request deduplication\r\nexport function reactCache<T extends (...args: any[]) => any>(fn: T): T {\r\n const cache = new Map<string, any>();\r\n \r\n return ((...args: any[]) => {\r\n const key = JSON.stringify(args);\r\n if (cache.has(key)) {\r\n return cache.get(key);\r\n }\r\n const result = fn(...args);\r\n cache.set(key, result);\r\n return result;\r\n }) as T;\r\n}\r\n\r\nexport default cache;\r\n","/**\r\n * FlexiReact Universal Edge Handler\r\n * \r\n * Single handler that works on all platforms:\r\n * - Node.js (http.createServer)\r\n * - Bun (Bun.serve)\r\n * - Deno (Deno.serve)\r\n * - Cloudflare Workers (fetch handler)\r\n * - Vercel Edge (edge function)\r\n */\r\n\r\nimport { FlexiRequest, FlexiResponse } from './fetch-polyfill.js';\r\nimport runtime, { detectRuntime } from './runtime.js';\r\nimport { cache, CacheOptions } from './cache.js';\r\n\r\n// Handler context\r\nexport interface EdgeContext {\r\n runtime: typeof runtime;\r\n cache: typeof cache;\r\n env: Record<string, string | undefined>;\r\n waitUntil: (promise: Promise<any>) => void;\r\n passThroughOnException?: () => void;\r\n}\r\n\r\n// Route handler type\r\nexport type EdgeHandler = (\r\n request: FlexiRequest,\r\n context: EdgeContext\r\n) => Promise<FlexiResponse> | FlexiResponse;\r\n\r\n// Middleware type\r\nexport type EdgeMiddleware = (\r\n request: FlexiRequest,\r\n context: EdgeContext,\r\n next: () => Promise<FlexiResponse>\r\n) => Promise<FlexiResponse> | FlexiResponse;\r\n\r\n// App configuration\r\nexport interface EdgeAppConfig {\r\n routes?: Map<string, EdgeHandler>;\r\n middleware?: EdgeMiddleware[];\r\n notFound?: EdgeHandler;\r\n onError?: (error: Error, request: FlexiRequest) => FlexiResponse;\r\n basePath?: string;\r\n}\r\n\r\n// Create universal edge app\r\nexport function createEdgeApp(config: EdgeAppConfig = {}) {\r\n const {\r\n routes = new Map(),\r\n middleware = [],\r\n notFound = () => FlexiResponse.notFound(),\r\n onError = (error) => FlexiResponse.error(error.message),\r\n basePath = ''\r\n } = config;\r\n\r\n // Main fetch handler (Web Standard)\r\n async function handleRequest(\r\n request: Request,\r\n env: Record<string, any> = {},\r\n executionContext?: { waitUntil: (p: Promise<any>) => void; passThroughOnException?: () => void }\r\n ): Promise<Response> {\r\n const flexiRequest = new FlexiRequest(request.url, {\r\n method: request.method,\r\n headers: request.headers,\r\n body: request.body,\r\n // @ts-ignore - duplex is needed for streaming\r\n duplex: 'half'\r\n });\r\n\r\n const context: EdgeContext = {\r\n runtime,\r\n cache,\r\n env: env as Record<string, string | undefined>,\r\n waitUntil: executionContext?.waitUntil || (() => {}),\r\n passThroughOnException: executionContext?.passThroughOnException\r\n };\r\n\r\n try {\r\n // Run middleware chain\r\n const response = await runMiddleware(flexiRequest, context, middleware, async () => {\r\n // Match route\r\n const pathname = flexiRequest.pathname.replace(basePath, '') || '/';\r\n \r\n // Try exact match first\r\n let handler = routes.get(pathname);\r\n \r\n // Try pattern matching\r\n if (!handler) {\r\n for (const [pattern, h] of routes) {\r\n if (matchRoute(pathname, pattern)) {\r\n handler = h;\r\n break;\r\n }\r\n }\r\n }\r\n \r\n if (handler) {\r\n return await handler(flexiRequest, context);\r\n }\r\n \r\n return await notFound(flexiRequest, context);\r\n });\r\n\r\n return response;\r\n } catch (error: any) {\r\n console.error('Edge handler error:', error);\r\n return onError(error, flexiRequest);\r\n }\r\n }\r\n\r\n // Run middleware chain\r\n async function runMiddleware(\r\n request: FlexiRequest,\r\n context: EdgeContext,\r\n middlewares: EdgeMiddleware[],\r\n finalHandler: () => Promise<FlexiResponse>\r\n ): Promise<FlexiResponse> {\r\n let index = 0;\r\n\r\n async function next(): Promise<FlexiResponse> {\r\n if (index >= middlewares.length) {\r\n return finalHandler();\r\n }\r\n const mw = middlewares[index++];\r\n return mw(request, context, next);\r\n }\r\n\r\n return next();\r\n }\r\n\r\n // Simple route matching\r\n function matchRoute(pathname: string, pattern: string): boolean {\r\n // Exact match\r\n if (pathname === pattern) return true;\r\n \r\n // Convert pattern to regex\r\n const regexPattern = pattern\r\n .replace(/\\[\\.\\.\\.(\\w+)\\]/g, '(?<$1>.+)') // [...slug] -> catch-all\r\n .replace(/\\[(\\w+)\\]/g, '(?<$1>[^/]+)'); // [id] -> dynamic segment\r\n \r\n const regex = new RegExp(`^${regexPattern}$`);\r\n return regex.test(pathname);\r\n }\r\n\r\n // Return platform-specific exports\r\n return {\r\n // Web Standard fetch handler (Cloudflare, Vercel Edge, Deno)\r\n fetch: handleRequest,\r\n \r\n // Cloudflare Workers\r\n async scheduled(event: any, env: any, ctx: any) {\r\n // Handle scheduled events\r\n },\r\n \r\n // Add route\r\n route(path: string, handler: EdgeHandler) {\r\n routes.set(path, handler);\r\n return this;\r\n },\r\n \r\n // Add middleware\r\n use(mw: EdgeMiddleware) {\r\n middleware.push(mw);\r\n return this;\r\n },\r\n \r\n // Node.js adapter\r\n toNodeHandler() {\r\n return async (req: any, res: any) => {\r\n const url = `http://${req.headers.host}${req.url}`;\r\n const headers = new Headers();\r\n Object.entries(req.headers).forEach(([key, value]) => {\r\n if (typeof value === 'string') headers.set(key, value);\r\n });\r\n\r\n const body = ['GET', 'HEAD'].includes(req.method) ? undefined : req;\r\n \r\n const request = new Request(url, {\r\n method: req.method,\r\n headers,\r\n body,\r\n // @ts-ignore\r\n duplex: 'half'\r\n });\r\n\r\n const response = await handleRequest(request, process.env);\r\n \r\n res.writeHead(response.status, Object.fromEntries(response.headers));\r\n \r\n if (response.body) {\r\n const reader = response.body.getReader();\r\n while (true) {\r\n const { done, value } = await reader.read();\r\n if (done) break;\r\n res.write(value);\r\n }\r\n }\r\n res.end();\r\n };\r\n },\r\n \r\n // Bun adapter\r\n toBunHandler() {\r\n return {\r\n fetch: handleRequest,\r\n port: parseInt(process.env.PORT || '3000', 10)\r\n };\r\n },\r\n \r\n // Deno adapter\r\n toDenoHandler() {\r\n return handleRequest;\r\n },\r\n \r\n // Start server based on runtime\r\n async listen(port: number = 3000) {\r\n const rt = detectRuntime();\r\n \r\n switch (rt) {\r\n case 'bun':\r\n console.log(`🚀 FlexiReact Edge running on Bun at http://localhost:${port}`);\r\n // @ts-ignore - Bun global\r\n return Bun.serve({\r\n port,\r\n fetch: handleRequest\r\n });\r\n \r\n case 'deno':\r\n console.log(`🚀 FlexiReact Edge running on Deno at http://localhost:${port}`);\r\n // @ts-ignore - Deno global\r\n return Deno.serve({ port }, handleRequest);\r\n \r\n case 'node':\r\n default:\r\n const http = await import('http');\r\n const server = http.createServer(this.toNodeHandler());\r\n server.listen(port, () => {\r\n console.log(`🚀 FlexiReact Edge running on Node.js at http://localhost:${port}`);\r\n });\r\n return server;\r\n }\r\n }\r\n };\r\n}\r\n\r\n// Export default app creator\r\nexport default createEdgeApp;\r\n","/**\r\n * FlexiReact Partial Prerendering (PPR)\r\n * \r\n * Combines static shell with dynamic content:\r\n * - Static parts are prerendered at build time\r\n * - Dynamic parts stream in at request time\r\n * - Best of both SSG and SSR\r\n */\r\n\r\nimport React from 'react';\r\nimport { renderToString } from 'react-dom/server';\r\nimport { cache } from './cache.js';\r\n\r\n// PPR configuration\r\nexport interface PPRConfig {\r\n // Static shell cache duration\r\n shellCacheTTL?: number;\r\n // Dynamic content timeout\r\n dynamicTimeout?: number;\r\n // Fallback for dynamic parts\r\n fallback?: React.ReactNode;\r\n}\r\n\r\n// Mark component as dynamic (not prerendered)\r\nexport function dynamic<T extends React.ComponentType<any>>(\r\n Component: T,\r\n options?: { fallback?: React.ReactNode }\r\n): T {\r\n (Component as any).__flexi_dynamic = true;\r\n (Component as any).__flexi_fallback = options?.fallback;\r\n return Component;\r\n}\r\n\r\n// Mark component as static (prerendered)\r\nexport function staticComponent<T extends React.ComponentType<any>>(Component: T): T {\r\n (Component as any).__flexi_static = true;\r\n return Component;\r\n}\r\n\r\n// Suspense boundary for PPR\r\nexport interface SuspenseBoundaryProps {\r\n children: React.ReactNode;\r\n fallback?: React.ReactNode;\r\n id?: string;\r\n}\r\n\r\nexport function PPRBoundary({ children, fallback, id }: SuspenseBoundaryProps): React.ReactElement {\r\n return React.createElement(\r\n React.Suspense,\r\n { \r\n fallback: fallback || React.createElement('div', { \r\n 'data-ppr-placeholder': id || 'loading',\r\n className: 'ppr-loading'\r\n }, '⏳')\r\n },\r\n children\r\n );\r\n}\r\n\r\n// PPR Shell - static wrapper\r\nexport interface PPRShellProps {\r\n children: React.ReactNode;\r\n fallback?: React.ReactNode;\r\n}\r\n\r\nexport function PPRShell({ children, fallback }: PPRShellProps): React.ReactElement {\r\n return React.createElement(\r\n 'div',\r\n { 'data-ppr-shell': 'true' },\r\n React.createElement(\r\n React.Suspense,\r\n { fallback: fallback || null },\r\n children\r\n )\r\n );\r\n}\r\n\r\n// Prerender a page with PPR\r\nexport interface PPRRenderResult {\r\n staticShell: string;\r\n dynamicParts: Map<string, () => Promise<string>>;\r\n fullHtml: string;\r\n}\r\n\r\nexport async function prerenderWithPPR(\r\n Component: React.ComponentType<any>,\r\n props: any,\r\n config: PPRConfig = {}\r\n): Promise<PPRRenderResult> {\r\n const { shellCacheTTL = 3600 } = config;\r\n \r\n // Track dynamic parts\r\n const dynamicParts = new Map<string, () => Promise<string>>();\r\n let dynamicCounter = 0;\r\n \r\n // Create element\r\n const element = React.createElement(Component, props);\r\n \r\n // Render static shell (with placeholders for dynamic parts)\r\n const staticShell = renderToString(element);\r\n \r\n // Cache the static shell\r\n const cacheKey = `ppr:${Component.name || 'page'}:${JSON.stringify(props)}`;\r\n await cache.set(cacheKey, staticShell, { ttl: shellCacheTTL, tags: ['ppr'] });\r\n \r\n return {\r\n staticShell,\r\n dynamicParts,\r\n fullHtml: staticShell\r\n };\r\n}\r\n\r\n// Stream PPR response\r\nexport async function streamPPR(\r\n staticShell: string,\r\n dynamicParts: Map<string, () => Promise<string>>,\r\n options?: { onError?: (error: Error) => string }\r\n): Promise<ReadableStream<Uint8Array>> {\r\n const encoder = new TextEncoder();\r\n \r\n return new ReadableStream({\r\n async start(controller) {\r\n // Send static shell immediately\r\n controller.enqueue(encoder.encode(staticShell));\r\n \r\n // Stream dynamic parts as they resolve\r\n const promises = Array.from(dynamicParts.entries()).map(async ([id, render]) => {\r\n try {\r\n const html = await render();\r\n // Send script to replace placeholder\r\n const script = `<script>\r\n (function() {\r\n var placeholder = document.querySelector('[data-ppr-placeholder=\"${id}\"]');\r\n if (placeholder) {\r\n var temp = document.createElement('div');\r\n temp.innerHTML = ${JSON.stringify(html)};\r\n placeholder.replaceWith(...temp.childNodes);\r\n }\r\n })();\r\n </script>`;\r\n controller.enqueue(encoder.encode(script));\r\n } catch (error: any) {\r\n const errorHtml = options?.onError?.(error) || `<div class=\"ppr-error\">Error loading content</div>`;\r\n const script = `<script>\r\n (function() {\r\n var placeholder = document.querySelector('[data-ppr-placeholder=\"${id}\"]');\r\n if (placeholder) {\r\n placeholder.innerHTML = ${JSON.stringify(errorHtml)};\r\n }\r\n })();\r\n </script>`;\r\n controller.enqueue(encoder.encode(script));\r\n }\r\n });\r\n \r\n await Promise.all(promises);\r\n controller.close();\r\n }\r\n });\r\n}\r\n\r\n// PPR-aware fetch wrapper\r\nexport function pprFetch(\r\n input: RequestInfo | URL,\r\n init?: RequestInit & { \r\n cache?: 'force-cache' | 'no-store' | 'no-cache';\r\n next?: { revalidate?: number; tags?: string[] };\r\n }\r\n): Promise<Response> {\r\n const cacheMode = init?.cache || 'force-cache';\r\n const revalidate = init?.next?.revalidate;\r\n const tags = init?.next?.tags || [];\r\n \r\n // If no-store, always fetch fresh\r\n if (cacheMode === 'no-store') {\r\n return fetch(input, init);\r\n }\r\n \r\n // Create cache key\r\n const url = typeof input === 'string' ? input : input.toString();\r\n const cacheKey = `fetch:${url}:${JSON.stringify(init?.body || '')}`;\r\n \r\n // Try cache first\r\n return cache.wrap(\r\n async () => {\r\n const response = await fetch(input, init);\r\n return response;\r\n },\r\n {\r\n key: cacheKey,\r\n ttl: revalidate || 3600,\r\n tags\r\n }\r\n )();\r\n}\r\n\r\n// Export directive markers\r\nexport const experimental_ppr = true;\r\n\r\n// Page config for PPR\r\nexport interface PPRPageConfig {\r\n experimental_ppr?: boolean;\r\n revalidate?: number | false;\r\n dynamic?: 'auto' | 'force-dynamic' | 'force-static' | 'error';\r\n dynamicParams?: boolean;\r\n fetchCache?: 'auto' | 'default-cache' | 'only-cache' | 'force-cache' | 'force-no-store' | 'default-no-store' | 'only-no-store';\r\n}\r\n\r\n// Generate static params (for SSG with PPR)\r\nexport type GenerateStaticParams<T = any> = () => Promise<T[]> | T[];\r\n\r\n// Default PPR loading component\r\nexport function PPRLoading(): React.ReactElement {\r\n return React.createElement('div', {\r\n className: 'ppr-loading animate-pulse',\r\n style: {\r\n background: 'linear-gradient(90deg, #1a1a1a 25%, #2a2a2a 50%, #1a1a1a 75%)',\r\n backgroundSize: '200% 100%',\r\n animation: 'shimmer 1.5s infinite',\r\n borderRadius: '4px',\r\n height: '1em',\r\n width: '100%'\r\n }\r\n });\r\n}\r\n\r\n// Inject PPR styles\r\nexport function getPPRStyles(): string {\r\n return `\r\n @keyframes shimmer {\r\n 0% { background-position: 200% 0; }\r\n 100% { background-position: -200% 0; }\r\n }\r\n \r\n .ppr-loading {\r\n background: linear-gradient(90deg, #1a1a1a 25%, #2a2a2a 50%, #1a1a1a 75%);\r\n background-size: 200% 100%;\r\n animation: shimmer 1.5s infinite;\r\n border-radius: 4px;\r\n min-height: 1em;\r\n }\r\n \r\n .ppr-error {\r\n color: #ef4444;\r\n padding: 1rem;\r\n border: 1px solid #ef4444;\r\n border-radius: 4px;\r\n background: rgba(239, 68, 68, 0.1);\r\n }\r\n `;\r\n}\r\n\r\nexport default {\r\n dynamic,\r\n staticComponent,\r\n PPRBoundary,\r\n PPRShell,\r\n prerenderWithPPR,\r\n streamPPR,\r\n pprFetch,\r\n PPRLoading,\r\n getPPRStyles,\r\n experimental_ppr\r\n};\r\n","/**\r\n * FlexiReact Metadata API\r\n * \r\n * Complete metadata management like Next.js:\r\n * - Static and dynamic metadata\r\n * - Open Graph / Twitter Cards\r\n * - Robots / Sitemap\r\n * - JSON-LD structured data\r\n * - Viewport configuration\r\n * - Icons and manifest\r\n */\r\n\r\nimport React from 'react';\r\n\r\n// Base metadata types\r\nexport interface Metadata {\r\n // Basic\r\n title?: string | { default: string; template?: string; absolute?: string };\r\n description?: string;\r\n keywords?: string | string[];\r\n authors?: Author | Author[];\r\n creator?: string;\r\n publisher?: string;\r\n \r\n // Robots\r\n robots?: Robots | string;\r\n \r\n // Icons\r\n icons?: Icons;\r\n \r\n // Manifest\r\n manifest?: string;\r\n \r\n // Open Graph\r\n openGraph?: OpenGraph;\r\n \r\n // Twitter\r\n twitter?: Twitter;\r\n \r\n // Verification\r\n verification?: Verification;\r\n \r\n // Alternates\r\n alternates?: Alternates;\r\n \r\n // App Links\r\n appLinks?: AppLinks;\r\n \r\n // Archives\r\n archives?: string | string[];\r\n \r\n // Assets\r\n assets?: string | string[];\r\n \r\n // Bookmarks\r\n bookmarks?: string | string[];\r\n \r\n // Category\r\n category?: string;\r\n \r\n // Classification\r\n classification?: string;\r\n \r\n // Other\r\n other?: Record<string, string | string[]>;\r\n \r\n // Viewport\r\n viewport?: Viewport | string;\r\n \r\n // Theme Color\r\n themeColor?: ThemeColor | ThemeColor[];\r\n \r\n // Color Scheme\r\n colorScheme?: 'normal' | 'light' | 'dark' | 'light dark' | 'dark light';\r\n \r\n // Format Detection\r\n formatDetection?: FormatDetection;\r\n \r\n // Base URL\r\n metadataBase?: URL | string;\r\n \r\n // Generator\r\n generator?: string;\r\n \r\n // Application Name\r\n applicationName?: string;\r\n \r\n // Referrer\r\n referrer?: 'no-referrer' | 'origin' | 'no-referrer-when-downgrade' | 'origin-when-cross-origin' | 'same-origin' | 'strict-origin' | 'strict-origin-when-cross-origin' | 'unsafe-url';\r\n}\r\n\r\nexport interface Author {\r\n name?: string;\r\n url?: string;\r\n}\r\n\r\nexport interface Robots {\r\n index?: boolean;\r\n follow?: boolean;\r\n noarchive?: boolean;\r\n nosnippet?: boolean;\r\n noimageindex?: boolean;\r\n nocache?: boolean;\r\n googleBot?: Robots | string;\r\n}\r\n\r\nexport interface Icons {\r\n icon?: IconDescriptor | IconDescriptor[];\r\n shortcut?: IconDescriptor | IconDescriptor[];\r\n apple?: IconDescriptor | IconDescriptor[];\r\n other?: IconDescriptor[];\r\n}\r\n\r\nexport interface IconDescriptor {\r\n url: string;\r\n type?: string;\r\n sizes?: string;\r\n color?: string;\r\n rel?: string;\r\n media?: string;\r\n}\r\n\r\nexport interface OpenGraph {\r\n type?: 'website' | 'article' | 'book' | 'profile' | 'music.song' | 'music.album' | 'music.playlist' | 'music.radio_station' | 'video.movie' | 'video.episode' | 'video.tv_show' | 'video.other';\r\n url?: string;\r\n title?: string;\r\n description?: string;\r\n siteName?: string;\r\n locale?: string;\r\n images?: OGImage | OGImage[];\r\n videos?: OGVideo | OGVideo[];\r\n audio?: OGAudio | OGAudio[];\r\n determiner?: 'a' | 'an' | 'the' | 'auto' | '';\r\n \r\n // Article specific\r\n publishedTime?: string;\r\n modifiedTime?: string;\r\n expirationTime?: string;\r\n authors?: string | string[];\r\n section?: string;\r\n tags?: string[];\r\n}\r\n\r\nexport interface OGImage {\r\n url: string;\r\n secureUrl?: string;\r\n type?: string;\r\n width?: number;\r\n height?: number;\r\n alt?: string;\r\n}\r\n\r\nexport interface OGVideo {\r\n url: string;\r\n secureUrl?: string;\r\n type?: string;\r\n width?: number;\r\n height?: number;\r\n}\r\n\r\nexport interface OGAudio {\r\n url: string;\r\n secureUrl?: string;\r\n type?: string;\r\n}\r\n\r\nexport interface Twitter {\r\n card?: 'summary' | 'summary_large_image' | 'app' | 'player';\r\n site?: string;\r\n siteId?: string;\r\n creator?: string;\r\n creatorId?: string;\r\n title?: string;\r\n description?: string;\r\n images?: string | TwitterImage | (string | TwitterImage)[];\r\n app?: TwitterApp;\r\n player?: TwitterPlayer;\r\n}\r\n\r\nexport interface TwitterImage {\r\n url: string;\r\n alt?: string;\r\n}\r\n\r\nexport interface TwitterApp {\r\n id?: { iphone?: string; ipad?: string; googleplay?: string };\r\n name?: string;\r\n url?: { iphone?: string; ipad?: string; googleplay?: string };\r\n}\r\n\r\nexport interface TwitterPlayer {\r\n url: string;\r\n width?: number;\r\n height?: number;\r\n stream?: string;\r\n}\r\n\r\nexport interface Verification {\r\n google?: string | string[];\r\n yahoo?: string | string[];\r\n yandex?: string | string[];\r\n me?: string | string[];\r\n other?: Record<string, string | string[]>;\r\n}\r\n\r\nexport interface Alternates {\r\n canonical?: string;\r\n languages?: Record<string, string>;\r\n media?: Record<string, string>;\r\n types?: Record<string, string>;\r\n}\r\n\r\nexport interface AppLinks {\r\n ios?: AppLink | AppLink[];\r\n iphone?: AppLink | AppLink[];\r\n ipad?: AppLink | AppLink[];\r\n android?: AppLink | AppLink[];\r\n windows_phone?: AppLink | AppLink[];\r\n windows?: AppLink | AppLink[];\r\n windows_universal?: AppLink | AppLink[];\r\n web?: AppLink | AppLink[];\r\n}\r\n\r\nexport interface AppLink {\r\n url: string;\r\n app_store_id?: string;\r\n app_name?: string;\r\n}\r\n\r\nexport interface Viewport {\r\n width?: number | 'device-width';\r\n height?: number | 'device-height';\r\n initialScale?: number;\r\n minimumScale?: number;\r\n maximumScale?: number;\r\n userScalable?: boolean;\r\n viewportFit?: 'auto' | 'cover' | 'contain';\r\n interactiveWidget?: 'resizes-visual' | 'resizes-content' | 'overlays-content';\r\n}\r\n\r\nexport interface ThemeColor {\r\n color: string;\r\n media?: string;\r\n}\r\n\r\nexport interface FormatDetection {\r\n telephone?: boolean;\r\n date?: boolean;\r\n address?: boolean;\r\n email?: boolean;\r\n url?: boolean;\r\n}\r\n\r\n// Generate HTML head tags from metadata\r\nexport function generateMetadataTags(metadata: Metadata, baseUrl?: string): string {\r\n const tags: string[] = [];\r\n const base = baseUrl || metadata.metadataBase?.toString() || '';\r\n\r\n // Title\r\n if (metadata.title) {\r\n const title = typeof metadata.title === 'string' \r\n ? metadata.title \r\n : metadata.title.absolute || (metadata.title.template \r\n ? metadata.title.template.replace('%s', metadata.title.default)\r\n : metadata.title.default);\r\n tags.push(`<title>${escapeHtml(title)}</title>`);\r\n }\r\n\r\n // Description\r\n if (metadata.description) {\r\n tags.push(`<meta name=\"description\" content=\"${escapeHtml(metadata.description)}\">`);\r\n }\r\n\r\n // Keywords\r\n if (metadata.keywords) {\r\n const keywords = Array.isArray(metadata.keywords) ? metadata.keywords.join(', ') : metadata.keywords;\r\n tags.push(`<meta name=\"keywords\" content=\"${escapeHtml(keywords)}\">`);\r\n }\r\n\r\n // Authors\r\n if (metadata.authors) {\r\n const authors = Array.isArray(metadata.authors) ? metadata.authors : [metadata.authors];\r\n authors.forEach(author => {\r\n if (author.name) tags.push(`<meta name=\"author\" content=\"${escapeHtml(author.name)}\">`);\r\n if (author.url) tags.push(`<link rel=\"author\" href=\"${author.url}\">`);\r\n });\r\n }\r\n\r\n // Generator\r\n if (metadata.generator) {\r\n tags.push(`<meta name=\"generator\" content=\"${escapeHtml(metadata.generator)}\">`);\r\n }\r\n\r\n // Application Name\r\n if (metadata.applicationName) {\r\n tags.push(`<meta name=\"application-name\" content=\"${escapeHtml(metadata.applicationName)}\">`);\r\n }\r\n\r\n // Referrer\r\n if (metadata.referrer) {\r\n tags.push(`<meta name=\"referrer\" content=\"${metadata.referrer}\">`);\r\n }\r\n\r\n // Robots\r\n if (metadata.robots) {\r\n if (typeof metadata.robots === 'string') {\r\n tags.push(`<meta name=\"robots\" content=\"${metadata.robots}\">`);\r\n } else {\r\n const robotsContent = generateRobotsContent(metadata.robots);\r\n tags.push(`<meta name=\"robots\" content=\"${robotsContent}\">`);\r\n if (metadata.robots.googleBot) {\r\n const googleBotContent = typeof metadata.robots.googleBot === 'string'\r\n ? metadata.robots.googleBot\r\n : generateRobotsContent(metadata.robots.googleBot);\r\n tags.push(`<meta name=\"googlebot\" content=\"${googleBotContent}\">`);\r\n }\r\n }\r\n }\r\n\r\n // Viewport\r\n if (metadata.viewport) {\r\n const viewportContent = typeof metadata.viewport === 'string'\r\n ? metadata.viewport\r\n : generateViewportContent(metadata.viewport);\r\n tags.push(`<meta name=\"viewport\" content=\"${viewportContent}\">`);\r\n }\r\n\r\n // Theme Color\r\n if (metadata.themeColor) {\r\n const themeColors = Array.isArray(metadata.themeColor) ? metadata.themeColor : [metadata.themeColor];\r\n themeColors.forEach(tc => {\r\n if (typeof tc === 'string') {\r\n tags.push(`<meta name=\"theme-color\" content=\"${tc}\">`);\r\n } else {\r\n const mediaAttr = tc.media ? ` media=\"${tc.media}\"` : '';\r\n tags.push(`<meta name=\"theme-color\" content=\"${tc.color}\"${mediaAttr}>`);\r\n }\r\n });\r\n }\r\n\r\n // Color Scheme\r\n if (metadata.colorScheme) {\r\n tags.push(`<meta name=\"color-scheme\" content=\"${metadata.colorScheme}\">`);\r\n }\r\n\r\n // Format Detection\r\n if (metadata.formatDetection) {\r\n const fd = metadata.formatDetection;\r\n const parts: string[] = [];\r\n if (fd.telephone === false) parts.push('telephone=no');\r\n if (fd.date === false) parts.push('date=no');\r\n if (fd.address === false) parts.push('address=no');\r\n if (fd.email === false) parts.push('email=no');\r\n if (parts.length > 0) {\r\n tags.push(`<meta name=\"format-detection\" content=\"${parts.join(', ')}\">`);\r\n }\r\n }\r\n\r\n // Icons\r\n if (metadata.icons) {\r\n const addIcon = (icon: IconDescriptor, defaultRel: string) => {\r\n const rel = icon.rel || defaultRel;\r\n const type = icon.type ? ` type=\"${icon.type}\"` : '';\r\n const sizes = icon.sizes ? ` sizes=\"${icon.sizes}\"` : '';\r\n const color = icon.color ? ` color=\"${icon.color}\"` : '';\r\n const media = icon.media ? ` media=\"${icon.media}\"` : '';\r\n tags.push(`<link rel=\"${rel}\" href=\"${resolveUrl(icon.url, base)}\"${type}${sizes}${color}${media}>`);\r\n };\r\n\r\n if (metadata.icons.icon) {\r\n const icons = Array.isArray(metadata.icons.icon) ? metadata.icons.icon : [metadata.icons.icon];\r\n icons.forEach(icon => addIcon(icon, 'icon'));\r\n }\r\n if (metadata.icons.shortcut) {\r\n const icons = Array.isArray(metadata.icons.shortcut) ? metadata.icons.shortcut : [metadata.icons.shortcut];\r\n icons.forEach(icon => addIcon(icon, 'shortcut icon'));\r\n }\r\n if (metadata.icons.apple) {\r\n const icons = Array.isArray(metadata.icons.apple) ? metadata.icons.apple : [metadata.icons.apple];\r\n icons.forEach(icon => addIcon(icon, 'apple-touch-icon'));\r\n }\r\n }\r\n\r\n // Manifest\r\n if (metadata.manifest) {\r\n tags.push(`<link rel=\"manifest\" href=\"${resolveUrl(metadata.manifest, base)}\">`);\r\n }\r\n\r\n // Open Graph\r\n if (metadata.openGraph) {\r\n const og = metadata.openGraph;\r\n if (og.type) tags.push(`<meta property=\"og:type\" content=\"${og.type}\">`);\r\n if (og.title) tags.push(`<meta property=\"og:title\" content=\"${escapeHtml(og.title)}\">`);\r\n if (og.description) tags.push(`<meta property=\"og:description\" content=\"${escapeHtml(og.description)}\">`);\r\n if (og.url) tags.push(`<meta property=\"og:url\" content=\"${resolveUrl(og.url, base)}\">`);\r\n if (og.siteName) tags.push(`<meta property=\"og:site_name\" content=\"${escapeHtml(og.siteName)}\">`);\r\n if (og.locale) tags.push(`<meta property=\"og:locale\" content=\"${og.locale}\">`);\r\n if (og.determiner) tags.push(`<meta property=\"og:determiner\" content=\"${og.determiner}\">`);\r\n\r\n // Images\r\n if (og.images) {\r\n const images = Array.isArray(og.images) ? og.images : [og.images];\r\n images.forEach(img => {\r\n tags.push(`<meta property=\"og:image\" content=\"${resolveUrl(img.url, base)}\">`);\r\n if (img.secureUrl) tags.push(`<meta property=\"og:image:secure_url\" content=\"${img.secureUrl}\">`);\r\n if (img.type) tags.push(`<meta property=\"og:image:type\" content=\"${img.type}\">`);\r\n if (img.width) tags.push(`<meta property=\"og:image:width\" content=\"${img.width}\">`);\r\n if (img.height) tags.push(`<meta property=\"og:image:height\" content=\"${img.height}\">`);\r\n if (img.alt) tags.push(`<meta property=\"og:image:alt\" content=\"${escapeHtml(img.alt)}\">`);\r\n });\r\n }\r\n\r\n // Article specific\r\n if (og.type === 'article') {\r\n if (og.publishedTime) tags.push(`<meta property=\"article:published_time\" content=\"${og.publishedTime}\">`);\r\n if (og.modifiedTime) tags.push(`<meta property=\"article:modified_time\" content=\"${og.modifiedTime}\">`);\r\n if (og.expirationTime) tags.push(`<meta property=\"article:expiration_time\" content=\"${og.expirationTime}\">`);\r\n if (og.section) tags.push(`<meta property=\"article:section\" content=\"${escapeHtml(og.section)}\">`);\r\n if (og.tags) {\r\n og.tags.forEach(tag => tags.push(`<meta property=\"article:tag\" content=\"${escapeHtml(tag)}\">`));\r\n }\r\n if (og.authors) {\r\n const authors = Array.isArray(og.authors) ? og.authors : [og.authors];\r\n authors.forEach(author => tags.push(`<meta property=\"article:author\" content=\"${escapeHtml(author)}\">`));\r\n }\r\n }\r\n }\r\n\r\n // Twitter\r\n if (metadata.twitter) {\r\n const tw = metadata.twitter;\r\n if (tw.card) tags.push(`<meta name=\"twitter:card\" content=\"${tw.card}\">`);\r\n if (tw.site) tags.push(`<meta name=\"twitter:site\" content=\"${tw.site}\">`);\r\n if (tw.siteId) tags.push(`<meta name=\"twitter:site:id\" content=\"${tw.siteId}\">`);\r\n if (tw.creator) tags.push(`<meta name=\"twitter:creator\" content=\"${tw.creator}\">`);\r\n if (tw.creatorId) tags.push(`<meta name=\"twitter:creator:id\" content=\"${tw.creatorId}\">`);\r\n if (tw.title) tags.push(`<meta name=\"twitter:title\" content=\"${escapeHtml(tw.title)}\">`);\r\n if (tw.description) tags.push(`<meta name=\"twitter:description\" content=\"${escapeHtml(tw.description)}\">`);\r\n\r\n if (tw.images) {\r\n const images = Array.isArray(tw.images) ? tw.images : [tw.images];\r\n images.forEach(img => {\r\n const url = typeof img === 'string' ? img : img.url;\r\n tags.push(`<meta name=\"twitter:image\" content=\"${resolveUrl(url, base)}\">`);\r\n if (typeof img !== 'string' && img.alt) {\r\n tags.push(`<meta name=\"twitter:image:alt\" content=\"${escapeHtml(img.alt)}\">`);\r\n }\r\n });\r\n }\r\n }\r\n\r\n // Verification\r\n if (metadata.verification) {\r\n const v = metadata.verification;\r\n if (v.google) {\r\n const values = Array.isArray(v.google) ? v.google : [v.google];\r\n values.forEach(val => tags.push(`<meta name=\"google-site-verification\" content=\"${val}\">`));\r\n }\r\n if (v.yandex) {\r\n const values = Array.isArray(v.yandex) ? v.yandex : [v.yandex];\r\n values.forEach(val => tags.push(`<meta name=\"yandex-verification\" content=\"${val}\">`));\r\n }\r\n }\r\n\r\n // Alternates\r\n if (metadata.alternates) {\r\n const alt = metadata.alternates;\r\n if (alt.canonical) {\r\n tags.push(`<link rel=\"canonical\" href=\"${resolveUrl(alt.canonical, base)}\">`);\r\n }\r\n if (alt.languages) {\r\n Object.entries(alt.languages).forEach(([lang, url]) => {\r\n tags.push(`<link rel=\"alternate\" hreflang=\"${lang}\" href=\"${resolveUrl(url, base)}\">`);\r\n });\r\n }\r\n }\r\n\r\n return tags.join('\\n ');\r\n}\r\n\r\n// Helper functions\r\nfunction escapeHtml(str: string): string {\r\n return str\r\n .replace(/&/g, '&amp;')\r\n .replace(/</g, '&lt;')\r\n .replace(/>/g, '&gt;')\r\n .replace(/\"/g, '&quot;')\r\n .replace(/'/g, '&#039;');\r\n}\r\n\r\nfunction resolveUrl(url: string, base: string): string {\r\n if (url.startsWith('http://') || url.startsWith('https://') || url.startsWith('//')) {\r\n return url;\r\n }\r\n return base ? `${base.replace(/\\/$/, '')}${url.startsWith('/') ? '' : '/'}${url}` : url;\r\n}\r\n\r\nfunction generateRobotsContent(robots: Robots): string {\r\n const parts: string[] = [];\r\n if (robots.index !== undefined) parts.push(robots.index ? 'index' : 'noindex');\r\n if (robots.follow !== undefined) parts.push(robots.follow ? 'follow' : 'nofollow');\r\n if (robots.noarchive) parts.push('noarchive');\r\n if (robots.nosnippet) parts.push('nosnippet');\r\n if (robots.noimageindex) parts.push('noimageindex');\r\n if (robots.nocache) parts.push('nocache');\r\n return parts.join(', ') || 'index, follow';\r\n}\r\n\r\nfunction generateViewportContent(viewport: Viewport): string {\r\n const parts: string[] = [];\r\n if (viewport.width) parts.push(`width=${viewport.width}`);\r\n if (viewport.height) parts.push(`height=${viewport.height}`);\r\n if (viewport.initialScale !== undefined) parts.push(`initial-scale=${viewport.initialScale}`);\r\n if (viewport.minimumScale !== undefined) parts.push(`minimum-scale=${viewport.minimumScale}`);\r\n if (viewport.maximumScale !== undefined) parts.push(`maximum-scale=${viewport.maximumScale}`);\r\n if (viewport.userScalable !== undefined) parts.push(`user-scalable=${viewport.userScalable ? 'yes' : 'no'}`);\r\n if (viewport.viewportFit) parts.push(`viewport-fit=${viewport.viewportFit}`);\r\n return parts.join(', ') || 'width=device-width, initial-scale=1';\r\n}\r\n\r\n// Merge metadata (child overrides parent)\r\nexport function mergeMetadata(parent: Metadata, child: Metadata): Metadata {\r\n return {\r\n ...parent,\r\n ...child,\r\n // Deep merge for nested objects\r\n openGraph: child.openGraph ? { ...parent.openGraph, ...child.openGraph } : parent.openGraph,\r\n twitter: child.twitter ? { ...parent.twitter, ...child.twitter } : parent.twitter,\r\n icons: child.icons ? { ...parent.icons, ...child.icons } : parent.icons,\r\n verification: child.verification ? { ...parent.verification, ...child.verification } : parent.verification,\r\n alternates: child.alternates ? { ...parent.alternates, ...child.alternates } : parent.alternates\r\n };\r\n}\r\n\r\n// Generate JSON-LD structured data\r\nexport function generateJsonLd(data: Record<string, any>): string {\r\n return `<script type=\"application/ld+json\">${JSON.stringify(data)}</script>`;\r\n}\r\n\r\n// Common JSON-LD schemas\r\nexport const jsonLd = {\r\n website: (config: { name: string; url: string; description?: string }) => ({\r\n '@context': 'https://schema.org',\r\n '@type': 'WebSite',\r\n name: config.name,\r\n url: config.url,\r\n description: config.description\r\n }),\r\n \r\n article: (config: {\r\n headline: string;\r\n description?: string;\r\n image?: string | string[];\r\n datePublished: string;\r\n dateModified?: string;\r\n author: { name: string; url?: string } | { name: string; url?: string }[];\r\n }) => ({\r\n '@context': 'https://schema.org',\r\n '@type': 'Article',\r\n headline: config.headline,\r\n description: config.description,\r\n image: config.image,\r\n datePublished: config.datePublished,\r\n dateModified: config.dateModified || config.datePublished,\r\n author: Array.isArray(config.author)\r\n ? config.author.map(a => ({ '@type': 'Person', ...a }))\r\n : { '@type': 'Person', ...config.author }\r\n }),\r\n \r\n organization: (config: {\r\n name: string;\r\n url: string;\r\n logo?: string;\r\n sameAs?: string[];\r\n }) => ({\r\n '@context': 'https://schema.org',\r\n '@type': 'Organization',\r\n name: config.name,\r\n url: config.url,\r\n logo: config.logo,\r\n sameAs: config.sameAs\r\n }),\r\n \r\n product: (config: {\r\n name: string;\r\n description?: string;\r\n image?: string | string[];\r\n brand?: string;\r\n offers?: { price: number; priceCurrency: string; availability?: string };\r\n }) => ({\r\n '@context': 'https://schema.org',\r\n '@type': 'Product',\r\n name: config.name,\r\n description: config.description,\r\n image: config.image,\r\n brand: config.brand ? { '@type': 'Brand', name: config.brand } : undefined,\r\n offers: config.offers ? {\r\n '@type': 'Offer',\r\n price: config.offers.price,\r\n priceCurrency: config.offers.priceCurrency,\r\n availability: config.offers.availability || 'https://schema.org/InStock'\r\n } : undefined\r\n }),\r\n \r\n breadcrumb: (items: { name: string; url: string }[]) => ({\r\n '@context': 'https://schema.org',\r\n '@type': 'BreadcrumbList',\r\n itemListElement: items.map((item, index) => ({\r\n '@type': 'ListItem',\r\n position: index + 1,\r\n name: item.name,\r\n item: item.url\r\n }))\r\n })\r\n};\r\n\r\nexport default {\r\n generateMetadataTags,\r\n mergeMetadata,\r\n generateJsonLd,\r\n jsonLd\r\n};\r\n","/**\r\n * FlexiReact v2 - Main Entry Point\r\n * A modern React framework with RSC, SSG, Islands, and more\r\n */\r\n\r\n// Types\r\nexport type { FlexiConfig, Route, RouteType as RouteTypeEnum, PageProps, LayoutProps } from './types.js';\r\n\r\n// Core exports\r\nexport { loadConfig, defaultConfig, resolvePaths } from './config.js';\r\nexport { createRequestContext, useRequest, useParams, useQuery, usePathname } from './context.js';\r\nexport * from './utils.js';\r\n\r\n// Router\r\nexport { buildRouteTree, matchRoute, findRouteLayouts, RouteType } from './router/index.js';\r\n\r\n// Render\r\nexport { renderPage, renderPageStream, streamToResponse, renderError, renderLoading } from './render/index.js';\r\n\r\n// Server\r\nimport { createServer } from './server/index.js';\r\nexport { createServer };\r\n\r\n// Build\r\nexport { build, buildDev, BuildMode } from './build/index.js';\r\n\r\n// SSG\r\nexport { generateStaticSite, SSGResult, ISRManager } from './ssg/index.js';\r\n\r\n// RSC\r\nexport {\r\n processServerComponent,\r\n createClientReference,\r\n serializeRSCPayload,\r\n createServerAction,\r\n handleServerAction,\r\n ServerBoundary,\r\n ClientBoundary,\r\n RSC_CONTENT_TYPE\r\n} from './rsc/index.js';\r\n\r\n// Islands\r\nexport {\r\n Island,\r\n createIsland,\r\n createLazyIsland,\r\n getRegisteredIslands,\r\n generateHydrationScript,\r\n generateAdvancedHydrationScript,\r\n LoadStrategy\r\n} from './islands/index.js';\r\n\r\n// Middleware\r\nexport {\r\n MiddlewareRequest,\r\n MiddlewareResponse,\r\n loadMiddleware,\r\n runMiddleware,\r\n composeMiddleware,\r\n middlewares\r\n} from './middleware/index.js';\r\n\r\n// Plugins\r\nexport {\r\n PluginManager,\r\n PluginHooks,\r\n pluginManager,\r\n loadPlugins,\r\n definePlugin,\r\n builtinPlugins\r\n} from './plugins/index.js';\r\n\r\n// Edge Runtime\r\nexport {\r\n // Runtime\r\n detectRuntime,\r\n getRuntimeCapabilities,\r\n edgeRuntimeInfo,\r\n // Fetch\r\n FlexiRequest,\r\n FlexiResponse,\r\n FlexiHeaders,\r\n // Handler\r\n createEdgeApp,\r\n // Cache\r\n smartCache,\r\n initCache,\r\n cacheFunction,\r\n unstable_cache,\r\n revalidateTag,\r\n revalidatePath,\r\n reactCache,\r\n // PPR\r\n dynamic,\r\n staticComponent,\r\n PPRBoundary,\r\n PPRShell,\r\n prerenderWithPPR,\r\n streamPPR,\r\n pprFetch,\r\n PPRLoading,\r\n experimental_ppr,\r\n // Default exports\r\n createApp\r\n} from './edge/index.js';\r\nexport type {\r\n RuntimeEnvironment,\r\n RuntimeCapabilities,\r\n EdgeContext,\r\n EdgeHandler,\r\n EdgeMiddleware,\r\n EdgeAppConfig,\r\n CacheEntry,\r\n CacheOptions,\r\n PPRConfig,\r\n PPRRenderResult,\r\n PPRPageConfig,\r\n GenerateStaticParams\r\n} from './edge/index.js';\r\n\r\n// Font Optimization\r\nexport {\r\n createFont,\r\n googleFont,\r\n localFont,\r\n generateFontCSS,\r\n generateFontPreloadTags,\r\n handleFontRequest,\r\n fonts,\r\n googleFonts\r\n} from './font/index.js';\r\nexport type { FontConfig, FontResult } from './font/index.js';\r\n\r\n// Metadata API\r\nexport {\r\n generateMetadataTags,\r\n mergeMetadata,\r\n generateJsonLd,\r\n jsonLd\r\n} from './metadata/index.js';\r\nexport type {\r\n Metadata,\r\n OpenGraph,\r\n Twitter,\r\n Icons,\r\n Robots,\r\n Viewport,\r\n Author\r\n} from './metadata/index.js';\r\n\r\n// Image Optimization\r\nexport {\r\n Image,\r\n createImageComponent,\r\n handleImageOptimization,\r\n generateBlurPlaceholder,\r\n getImageDimensions,\r\n generateSrcSet,\r\n imageLoaders,\r\n defaultImageConfig\r\n} from './image/index.js';\r\nexport type { ImageProps, ImageConfig, ImageLoader } from './image/index.js';\r\n\r\n// React 19 Hooks (re-exported for convenience)\r\nexport { useActionState, useOptimistic } from 'react';\r\nexport { useFormStatus } from 'react-dom';\r\n\r\n// FlexiReact Hooks\r\nexport { useAsyncData, useOptimisticMutation, preloadResource } from './hooks/index.js';\r\n\r\n// Server Actions\r\nexport {\r\n serverAction,\r\n registerAction,\r\n getAction,\r\n executeAction,\r\n callServerAction,\r\n formAction,\r\n createFormState, // deprecated - use useActionState\r\n useFlexiAction,\r\n bindArgs,\r\n useActionContext\r\n} from './actions/index.js';\r\nexport type { ActionContext, ActionResult, ServerActionFunction } from './actions/index.js';\r\n\r\n// Server Helpers\r\nexport {\r\n // Response helpers\r\n redirect,\r\n notFound,\r\n json,\r\n html,\r\n text,\r\n // Error classes\r\n RedirectError,\r\n NotFoundError,\r\n // Cookies API\r\n cookies,\r\n // Headers API\r\n headers,\r\n // Request helpers\r\n parseJson,\r\n parseFormData,\r\n parseSearchParams,\r\n getMethod,\r\n getPathname,\r\n isMethod\r\n} from './helpers.js';\r\nexport type { CookieOptions } from './helpers.js';\r\n\r\n// DevTools\r\nexport {\r\n devtools,\r\n DevToolsOverlay,\r\n initPerformanceMonitoring,\r\n initNetworkInterceptor\r\n} from './devtools/index.js';\r\n\r\n// Version\r\nexport const VERSION = '3.1.0';\r\n\r\n// Default export\r\nexport default {\r\n VERSION,\r\n createServer\r\n};\r\n","/**\r\n * FlexiReact Hooks - React 19 Native\r\n * \r\n * This module provides React 19 hooks re-exports and FlexiReact-specific\r\n * hook utilities for enhanced developer experience.\r\n */\r\n\r\n// ============================================================================\r\n// React 19 Core Hooks (re-exported for convenience)\r\n// ============================================================================\r\n\r\n// Actions & Forms\r\nexport { useActionState, useOptimistic } from 'react';\r\nexport { useFormStatus } from 'react-dom';\r\n\r\n// Async Data\r\nexport { use } from 'react';\r\n\r\n// ============================================================================\r\n// FlexiReact Context Hooks\r\n// ============================================================================\r\n\r\nexport { useParams, useQuery, usePathname, useRequest } from '../context.js';\r\n\r\n// ============================================================================\r\n// FlexiReact Client Hooks\r\n// ============================================================================\r\n\r\nexport { useRouter } from '../client/Link.js';\r\n\r\n// ============================================================================\r\n// FlexiReact Enhanced Hooks\r\n// ============================================================================\r\n\r\nimport { use, useOptimistic as useOptimisticReact } from 'react';\r\n\r\n/**\r\n * Async data fetching hook using React 19's use()\r\n * \r\n * @example\r\n * ```tsx\r\n * // In a Server Component or with Suspense boundary\r\n * function UserProfile({ userId }: { userId: string }) {\r\n * const user = useAsyncData(fetchUser(userId));\r\n * return <div>{user.name}</div>;\r\n * }\r\n * ```\r\n */\r\nexport function useAsyncData<T>(promise: Promise<T>): T {\r\n return use(promise);\r\n}\r\n\r\n/**\r\n * Optimistic mutation helper with typed update function\r\n * \r\n * @example\r\n * ```tsx\r\n * function TodoList({ todos }: { todos: Todo[] }) {\r\n * const [optimisticTodos, addOptimistic] = useOptimisticMutation(\r\n * todos,\r\n * (state, newTodo: Todo) => [...state, { ...newTodo, pending: true }]\r\n * );\r\n * \r\n * async function addTodo(todo: Todo) {\r\n * addOptimistic(todo);\r\n * await saveTodo(todo);\r\n * }\r\n * }\r\n * ```\r\n */\r\nexport function useOptimisticMutation<T, M>(\r\n currentState: T,\r\n updateFn: (state: T, mutation: M) => T\r\n): [T, (mutation: M) => void] {\r\n return useOptimisticReact(currentState, updateFn);\r\n}\r\n\r\n/**\r\n * Resource preloading for Suspense optimization\r\n * \r\n * @example\r\n * ```tsx\r\n * // Preload data before it's needed\r\n * const userResource = preloadResource(() => fetchUser(userId));\r\n * \r\n * // Later, use it with Suspense\r\n * function UserCard() {\r\n * const user = useAsyncData(userResource);\r\n * return <div>{user.name}</div>;\r\n * }\r\n * ```\r\n */\r\nexport function preloadResource<T>(fetcher: () => Promise<T>): Promise<T> {\r\n // Start fetching immediately, cache the promise\r\n const promise = fetcher();\r\n return promise;\r\n}\r\n\r\nexport default {\r\n useAsyncData,\r\n useOptimisticMutation,\r\n preloadResource\r\n};\r\n","'use client';\r\n\r\n/**\r\n * FlexiReact Link Component\r\n * Enhanced link with prefetching, client-side navigation, and loading states\r\n */\r\n\r\nimport React, { useCallback, useEffect, useRef, useState } from 'react';\r\n\r\nexport interface LinkProps extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, 'href'> {\r\n /** The URL to navigate to */\r\n href: string;\r\n /** Prefetch the page on hover/visibility */\r\n prefetch?: boolean | 'hover' | 'viewport';\r\n /** Replace the current history entry instead of pushing */\r\n replace?: boolean;\r\n /** Scroll to top after navigation */\r\n scroll?: boolean;\r\n /** Show loading indicator while navigating */\r\n showLoading?: boolean;\r\n /** Custom loading component */\r\n loadingComponent?: React.ReactNode;\r\n /** Callback when navigation starts */\r\n onNavigationStart?: () => void;\r\n /** Callback when navigation ends */\r\n onNavigationEnd?: () => void;\r\n /** \r\n * Ref to the anchor element (React 19: ref as regular prop)\r\n * No forwardRef wrapper needed in React 19\r\n */\r\n ref?: React.Ref<HTMLAnchorElement>;\r\n /** Children */\r\n children: React.ReactNode;\r\n}\r\n\r\n// Prefetch cache to avoid duplicate requests\r\nconst prefetchCache = new Set<string>();\r\n\r\n// Prefetch a URL\r\nasync function prefetchUrl(url: string): Promise<void> {\r\n if (prefetchCache.has(url)) return;\r\n\r\n try {\r\n // Mark as prefetched immediately to prevent duplicate requests\r\n prefetchCache.add(url);\r\n\r\n // Use link preload for better browser optimization\r\n const link = document.createElement('link');\r\n link.rel = 'prefetch';\r\n link.href = url;\r\n link.as = 'document';\r\n document.head.appendChild(link);\r\n\r\n // Also fetch the page to warm the cache\r\n const controller = new AbortController();\r\n const timeoutId = setTimeout(() => controller.abort(), 5000);\r\n\r\n await fetch(url, {\r\n method: 'GET',\r\n credentials: 'same-origin',\r\n signal: controller.signal,\r\n headers: {\r\n 'X-Flexi-Prefetch': '1',\r\n 'Accept': 'text/html'\r\n }\r\n });\r\n\r\n clearTimeout(timeoutId);\r\n } catch (error) {\r\n // Remove from cache on error so it can be retried\r\n prefetchCache.delete(url);\r\n }\r\n}\r\n\r\n// Check if URL is internal\r\nfunction isInternalUrl(url: string): boolean {\r\n if (url.startsWith('/')) return true;\r\n if (url.startsWith('#')) return true;\r\n\r\n try {\r\n const parsed = new URL(url, window.location.origin);\r\n return parsed.origin === window.location.origin;\r\n } catch {\r\n return false;\r\n }\r\n}\r\n\r\n// Navigate to a URL\r\nfunction navigate(url: string, options: { replace?: boolean; scroll?: boolean } = {}): void {\r\n const { replace = false, scroll = true } = options;\r\n\r\n if (replace) {\r\n window.history.replaceState({}, '', url);\r\n } else {\r\n window.history.pushState({}, '', url);\r\n }\r\n\r\n // Dispatch popstate event to trigger any listeners\r\n window.dispatchEvent(new PopStateEvent('popstate', { state: {} }));\r\n\r\n // Scroll to top if requested\r\n if (scroll) {\r\n window.scrollTo({ top: 0, behavior: 'smooth' });\r\n }\r\n}\r\n\r\n/**\r\n * Link component with prefetching and client-side navigation\r\n * \r\n * @example\r\n * ```tsx\r\n * import { Link } from '@flexireact/core/client';\r\n * \r\n * // Basic usage\r\n * <Link href=\"/about\">About</Link>\r\n * \r\n * // With prefetch on hover\r\n * <Link href=\"/products\" prefetch=\"hover\">Products</Link>\r\n * \r\n * // With prefetch on viewport visibility\r\n * <Link href=\"/contact\" prefetch=\"viewport\">Contact</Link>\r\n * \r\n * // Replace history instead of push\r\n * <Link href=\"/login\" replace>Login</Link>\r\n * \r\n * // Disable scroll to top\r\n * <Link href=\"/section#anchor\" scroll={false}>Go to section</Link>\r\n * ```\r\n */\r\nexport function Link({\r\n href,\r\n prefetch = true,\r\n replace = false,\r\n scroll = true,\r\n showLoading = false,\r\n loadingComponent,\r\n onNavigationStart,\r\n onNavigationEnd,\r\n children,\r\n className,\r\n onClick,\r\n onMouseEnter,\r\n onFocus,\r\n ...props\r\n}: LinkProps) {\r\n const [isNavigating, setIsNavigating] = useState(false);\r\n const linkRef = useRef<HTMLAnchorElement>(null);\r\n const hasPrefetched = useRef(false);\r\n\r\n // Prefetch on viewport visibility\r\n useEffect(() => {\r\n if (prefetch !== 'viewport' && prefetch !== true) return;\r\n if (!isInternalUrl(href)) return;\r\n if (hasPrefetched.current) return;\r\n\r\n const observer = new IntersectionObserver(\r\n (entries) => {\r\n entries.forEach((entry) => {\r\n if (entry.isIntersecting) {\r\n prefetchUrl(href);\r\n hasPrefetched.current = true;\r\n observer.disconnect();\r\n }\r\n });\r\n },\r\n { rootMargin: '200px' }\r\n );\r\n\r\n if (linkRef.current) {\r\n observer.observe(linkRef.current);\r\n }\r\n\r\n return () => observer.disconnect();\r\n }, [href, prefetch]);\r\n\r\n // Handle hover prefetch\r\n const handleMouseEnter = useCallback(\r\n (e: React.MouseEvent<HTMLAnchorElement>) => {\r\n onMouseEnter?.(e);\r\n\r\n if ((prefetch === 'hover' || prefetch === true) && isInternalUrl(href)) {\r\n prefetchUrl(href);\r\n }\r\n },\r\n [href, prefetch, onMouseEnter]\r\n );\r\n\r\n // Handle focus prefetch (for keyboard navigation)\r\n const handleFocus = useCallback(\r\n (e: React.FocusEvent<HTMLAnchorElement>) => {\r\n onFocus?.(e);\r\n\r\n if ((prefetch === 'hover' || prefetch === true) && isInternalUrl(href)) {\r\n prefetchUrl(href);\r\n }\r\n },\r\n [href, prefetch, onFocus]\r\n );\r\n\r\n // Handle click for client-side navigation\r\n const handleClick = useCallback(\r\n async (e: React.MouseEvent<HTMLAnchorElement>) => {\r\n onClick?.(e);\r\n\r\n // Don't handle if default was prevented\r\n if (e.defaultPrevented) return;\r\n\r\n // Don't handle if modifier keys are pressed (open in new tab, etc.)\r\n if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;\r\n\r\n // Don't handle external URLs\r\n if (!isInternalUrl(href)) return;\r\n\r\n // Don't handle if target is set\r\n if (props.target && props.target !== '_self') return;\r\n\r\n // Prevent default navigation\r\n e.preventDefault();\r\n\r\n // Start navigation\r\n setIsNavigating(true);\r\n onNavigationStart?.();\r\n\r\n try {\r\n // Fetch the new page\r\n const response = await fetch(href, {\r\n method: 'GET',\r\n credentials: 'same-origin',\r\n headers: {\r\n 'X-Flexi-Navigation': '1',\r\n 'Accept': 'text/html'\r\n }\r\n });\r\n\r\n if (response.ok) {\r\n const html = await response.text();\r\n\r\n // Parse and update the page\r\n const parser = new DOMParser();\r\n const doc = parser.parseFromString(html, 'text/html');\r\n\r\n // Update title\r\n const newTitle = doc.querySelector('title')?.textContent;\r\n if (newTitle) {\r\n document.title = newTitle;\r\n }\r\n\r\n // Update body content (or specific container)\r\n const newContent = doc.querySelector('#root') || doc.body;\r\n const currentContent = document.querySelector('#root') || document.body;\r\n\r\n if (newContent && currentContent) {\r\n currentContent.innerHTML = newContent.innerHTML;\r\n }\r\n\r\n // Update URL\r\n navigate(href, { replace, scroll });\r\n } else {\r\n // Fallback to regular navigation on error\r\n window.location.href = href;\r\n }\r\n } catch (error) {\r\n // Fallback to regular navigation on error\r\n window.location.href = href;\r\n } finally {\r\n setIsNavigating(false);\r\n onNavigationEnd?.();\r\n }\r\n },\r\n [href, replace, scroll, onClick, onNavigationStart, onNavigationEnd, props.target]\r\n );\r\n\r\n return (\r\n <a\r\n ref={linkRef}\r\n href={href}\r\n className={className}\r\n onClick={handleClick}\r\n onMouseEnter={handleMouseEnter}\r\n onFocus={handleFocus}\r\n data-prefetch={prefetch}\r\n data-navigating={isNavigating || undefined}\r\n {...props}\r\n >\r\n {showLoading && isNavigating ? (\r\n loadingComponent || (\r\n <span className=\"flexi-link-loading\">\r\n <span className=\"flexi-link-spinner\" />\r\n {children}\r\n </span>\r\n )\r\n ) : (\r\n children\r\n )}\r\n </a>\r\n );\r\n}\r\n\r\n/**\r\n * Programmatic navigation function\r\n * \r\n * @example\r\n * ```tsx\r\n * import { useRouter } from '@flexireact/core/client';\r\n * \r\n * function MyComponent() {\r\n * const router = useRouter();\r\n * \r\n * const handleClick = () => {\r\n * router.push('/dashboard');\r\n * };\r\n * \r\n * return <button onClick={handleClick}>Go to Dashboard</button>;\r\n * }\r\n * ```\r\n */\r\nexport function useRouter() {\r\n return {\r\n push(url: string, options?: { scroll?: boolean }) {\r\n navigate(url, { replace: false, scroll: options?.scroll ?? true });\r\n // Trigger page reload for now (full SPA navigation requires more work)\r\n window.location.href = url;\r\n },\r\n\r\n replace(url: string, options?: { scroll?: boolean }) {\r\n navigate(url, { replace: true, scroll: options?.scroll ?? true });\r\n window.location.href = url;\r\n },\r\n\r\n back() {\r\n window.history.back();\r\n },\r\n\r\n forward() {\r\n window.history.forward();\r\n },\r\n\r\n prefetch(url: string) {\r\n if (isInternalUrl(url)) {\r\n prefetchUrl(url);\r\n }\r\n },\r\n\r\n refresh() {\r\n window.location.reload();\r\n }\r\n };\r\n}\r\n\r\nexport default Link;\r\n","/**\r\n * FlexiReact DevTools\r\n * Advanced development tools for debugging and performance monitoring\r\n */\r\n\r\nimport React from 'react';\r\n\r\n// ============================================================================\r\n// DevTools State\r\n// ============================================================================\r\n\r\ninterface DevToolsState {\r\n enabled: boolean;\r\n position: 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';\r\n expanded: boolean;\r\n activeTab: 'routes' | 'components' | 'network' | 'performance' | 'state' | 'console';\r\n theme: 'dark' | 'light';\r\n}\r\n\r\ninterface RouteInfo {\r\n path: string;\r\n component: string;\r\n params: Record<string, string>;\r\n query: Record<string, string>;\r\n loadTime: number;\r\n}\r\n\r\ninterface ComponentInfo {\r\n name: string;\r\n renderCount: number;\r\n lastRenderTime: number;\r\n props: Record<string, any>;\r\n isIsland: boolean;\r\n}\r\n\r\ninterface NetworkRequest {\r\n id: string;\r\n url: string;\r\n method: string;\r\n status: number;\r\n duration: number;\r\n size: number;\r\n timestamp: number;\r\n type: 'fetch' | 'xhr' | 'ssr' | 'action';\r\n}\r\n\r\ninterface PerformanceMetric {\r\n name: string;\r\n value: number;\r\n rating: 'good' | 'needs-improvement' | 'poor';\r\n}\r\n\r\n// Global DevTools state\r\nconst devToolsState: {\r\n routes: RouteInfo[];\r\n components: Map<string, ComponentInfo>;\r\n network: NetworkRequest[];\r\n performance: PerformanceMetric[];\r\n logs: Array<{ level: string; message: string; timestamp: number }>;\r\n listeners: Set<() => void>;\r\n} = {\r\n routes: [],\r\n components: new Map(),\r\n network: [],\r\n performance: [],\r\n logs: [],\r\n listeners: new Set(),\r\n};\r\n\r\n// ============================================================================\r\n// DevTools API\r\n// ============================================================================\r\n\r\nexport const devtools = {\r\n // Track route navigation\r\n trackRoute(info: RouteInfo): void {\r\n devToolsState.routes.unshift(info);\r\n if (devToolsState.routes.length > 50) {\r\n devToolsState.routes.pop();\r\n }\r\n this.notify();\r\n },\r\n\r\n // Track component render\r\n trackComponent(name: string, info: Partial<ComponentInfo>): void {\r\n const existing = devToolsState.components.get(name) || {\r\n name,\r\n renderCount: 0,\r\n lastRenderTime: 0,\r\n props: {},\r\n isIsland: false,\r\n };\r\n \r\n devToolsState.components.set(name, {\r\n ...existing,\r\n ...info,\r\n renderCount: existing.renderCount + 1,\r\n lastRenderTime: Date.now(),\r\n });\r\n this.notify();\r\n },\r\n\r\n // Track network request\r\n trackRequest(request: NetworkRequest): void {\r\n devToolsState.network.unshift(request);\r\n if (devToolsState.network.length > 100) {\r\n devToolsState.network.pop();\r\n }\r\n this.notify();\r\n },\r\n\r\n // Track performance metric\r\n trackMetric(metric: PerformanceMetric): void {\r\n const existing = devToolsState.performance.findIndex(m => m.name === metric.name);\r\n if (existing >= 0) {\r\n devToolsState.performance[existing] = metric;\r\n } else {\r\n devToolsState.performance.push(metric);\r\n }\r\n this.notify();\r\n },\r\n\r\n // Log message\r\n log(level: 'info' | 'warn' | 'error' | 'debug', message: string): void {\r\n devToolsState.logs.unshift({\r\n level,\r\n message,\r\n timestamp: Date.now(),\r\n });\r\n if (devToolsState.logs.length > 200) {\r\n devToolsState.logs.pop();\r\n }\r\n this.notify();\r\n },\r\n\r\n // Get current state\r\n getState() {\r\n return {\r\n routes: devToolsState.routes,\r\n components: Array.from(devToolsState.components.values()),\r\n network: devToolsState.network,\r\n performance: devToolsState.performance,\r\n logs: devToolsState.logs,\r\n };\r\n },\r\n\r\n // Subscribe to changes\r\n subscribe(listener: () => void): () => void {\r\n devToolsState.listeners.add(listener);\r\n return () => devToolsState.listeners.delete(listener);\r\n },\r\n\r\n // Notify listeners\r\n notify(): void {\r\n devToolsState.listeners.forEach(listener => listener());\r\n },\r\n\r\n // Clear all data\r\n clear(): void {\r\n devToolsState.routes = [];\r\n devToolsState.components.clear();\r\n devToolsState.network = [];\r\n devToolsState.performance = [];\r\n devToolsState.logs = [];\r\n this.notify();\r\n },\r\n};\r\n\r\n// ============================================================================\r\n// Performance Monitoring\r\n// ============================================================================\r\n\r\nexport function initPerformanceMonitoring(): void {\r\n if (typeof window === 'undefined') return;\r\n\r\n // Core Web Vitals\r\n try {\r\n // LCP (Largest Contentful Paint)\r\n new PerformanceObserver((list) => {\r\n const entries = list.getEntries();\r\n const lastEntry = entries[entries.length - 1] as any;\r\n devtools.trackMetric({\r\n name: 'LCP',\r\n value: lastEntry.startTime,\r\n rating: lastEntry.startTime < 2500 ? 'good' : lastEntry.startTime < 4000 ? 'needs-improvement' : 'poor',\r\n });\r\n }).observe({ type: 'largest-contentful-paint', buffered: true });\r\n\r\n // FID (First Input Delay)\r\n new PerformanceObserver((list) => {\r\n const entries = list.getEntries();\r\n entries.forEach((entry: any) => {\r\n devtools.trackMetric({\r\n name: 'FID',\r\n value: entry.processingStart - entry.startTime,\r\n rating: entry.processingStart - entry.startTime < 100 ? 'good' : \r\n entry.processingStart - entry.startTime < 300 ? 'needs-improvement' : 'poor',\r\n });\r\n });\r\n }).observe({ type: 'first-input', buffered: true });\r\n\r\n // CLS (Cumulative Layout Shift)\r\n let clsValue = 0;\r\n new PerformanceObserver((list) => {\r\n for (const entry of list.getEntries() as any[]) {\r\n if (!entry.hadRecentInput) {\r\n clsValue += entry.value;\r\n }\r\n }\r\n devtools.trackMetric({\r\n name: 'CLS',\r\n value: clsValue,\r\n rating: clsValue < 0.1 ? 'good' : clsValue < 0.25 ? 'needs-improvement' : 'poor',\r\n });\r\n }).observe({ type: 'layout-shift', buffered: true });\r\n\r\n // TTFB (Time to First Byte)\r\n const navEntry = performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming;\r\n if (navEntry) {\r\n devtools.trackMetric({\r\n name: 'TTFB',\r\n value: navEntry.responseStart - navEntry.requestStart,\r\n rating: navEntry.responseStart - navEntry.requestStart < 200 ? 'good' : \r\n navEntry.responseStart - navEntry.requestStart < 500 ? 'needs-improvement' : 'poor',\r\n });\r\n }\r\n } catch (e) {\r\n // Performance API not fully supported\r\n }\r\n}\r\n\r\n// ============================================================================\r\n// Network Interceptor\r\n// ============================================================================\r\n\r\nexport function initNetworkInterceptor(): void {\r\n if (typeof window === 'undefined') return;\r\n\r\n // Intercept fetch\r\n const originalFetch = window.fetch;\r\n window.fetch = async function(...args) {\r\n const startTime = Date.now();\r\n const url = typeof args[0] === 'string' ? args[0] : (args[0] as Request).url;\r\n const method = typeof args[0] === 'string' ? (args[1]?.method || 'GET') : (args[0] as Request).method;\r\n \r\n try {\r\n const response = await originalFetch.apply(this, args);\r\n const clone = response.clone();\r\n const size = (await clone.blob()).size;\r\n \r\n devtools.trackRequest({\r\n id: Math.random().toString(36).slice(2),\r\n url,\r\n method,\r\n status: response.status,\r\n duration: Date.now() - startTime,\r\n size,\r\n timestamp: startTime,\r\n type: url.includes('/_flexi/action') ? 'action' : 'fetch',\r\n });\r\n \r\n return response;\r\n } catch (error) {\r\n devtools.trackRequest({\r\n id: Math.random().toString(36).slice(2),\r\n url,\r\n method,\r\n status: 0,\r\n duration: Date.now() - startTime,\r\n size: 0,\r\n timestamp: startTime,\r\n type: 'fetch',\r\n });\r\n throw error;\r\n }\r\n };\r\n}\r\n\r\n// ============================================================================\r\n// DevTools Overlay Component\r\n// ============================================================================\r\n\r\nexport function DevToolsOverlay(): React.ReactElement | null {\r\n const [state, setState] = React.useState<DevToolsState>({\r\n enabled: true,\r\n position: 'bottom-right',\r\n expanded: false,\r\n activeTab: 'routes',\r\n theme: 'dark',\r\n });\r\n\r\n const [data, setData] = React.useState(devtools.getState());\r\n\r\n React.useEffect(() => {\r\n return devtools.subscribe(() => {\r\n setData(devtools.getState());\r\n });\r\n }, []);\r\n\r\n React.useEffect(() => {\r\n initPerformanceMonitoring();\r\n initNetworkInterceptor();\r\n }, []);\r\n\r\n // Keyboard shortcut (Ctrl+Shift+D)\r\n React.useEffect(() => {\r\n const handler = (e: KeyboardEvent) => {\r\n if (e.ctrlKey && e.shiftKey && e.key === 'D') {\r\n setState(s => ({ ...s, expanded: !s.expanded }));\r\n }\r\n };\r\n window.addEventListener('keydown', handler);\r\n return () => window.removeEventListener('keydown', handler);\r\n }, []);\r\n\r\n if (!state.enabled) return null;\r\n\r\n const positionStyles: Record<string, React.CSSProperties> = {\r\n 'bottom-right': { bottom: 16, right: 16 },\r\n 'bottom-left': { bottom: 16, left: 16 },\r\n 'top-right': { top: 16, right: 16 },\r\n 'top-left': { top: 16, left: 16 },\r\n };\r\n\r\n // Mini button when collapsed\r\n if (!state.expanded) {\r\n return React.createElement('button', {\r\n onClick: () => setState(s => ({ ...s, expanded: true })),\r\n style: {\r\n position: 'fixed',\r\n ...positionStyles[state.position],\r\n zIndex: 99999,\r\n width: 48,\r\n height: 48,\r\n borderRadius: 12,\r\n background: 'linear-gradient(135deg, #00FF9C 0%, #00D68F 100%)',\r\n border: 'none',\r\n cursor: 'pointer',\r\n display: 'flex',\r\n alignItems: 'center',\r\n justifyContent: 'center',\r\n boxShadow: '0 4px 20px rgba(0, 255, 156, 0.3)',\r\n transition: 'transform 0.2s',\r\n },\r\n onMouseEnter: (e: any) => e.target.style.transform = 'scale(1.1)',\r\n onMouseLeave: (e: any) => e.target.style.transform = 'scale(1)',\r\n title: 'FlexiReact DevTools (Ctrl+Shift+D)',\r\n }, React.createElement('span', { style: { fontSize: 24 } }, '⚡'));\r\n }\r\n\r\n // Full panel\r\n const tabs = [\r\n { id: 'routes', label: '🗺️ Routes', count: data.routes.length },\r\n { id: 'components', label: '🧩 Components', count: data.components.length },\r\n { id: 'network', label: '🌐 Network', count: data.network.length },\r\n { id: 'performance', label: '📊 Performance', count: data.performance.length },\r\n { id: 'console', label: '📝 Console', count: data.logs.length },\r\n ];\r\n\r\n return React.createElement('div', {\r\n style: {\r\n position: 'fixed',\r\n ...positionStyles[state.position],\r\n zIndex: 99999,\r\n width: 480,\r\n maxHeight: '70vh',\r\n background: '#0a0a0a',\r\n border: '1px solid #222',\r\n borderRadius: 12,\r\n boxShadow: '0 8px 32px rgba(0, 0, 0, 0.5)',\r\n fontFamily: 'system-ui, -apple-system, sans-serif',\r\n fontSize: 13,\r\n color: '#fff',\r\n overflow: 'hidden',\r\n },\r\n }, [\r\n // Header\r\n React.createElement('div', {\r\n key: 'header',\r\n style: {\r\n display: 'flex',\r\n alignItems: 'center',\r\n justifyContent: 'space-between',\r\n padding: '12px 16px',\r\n borderBottom: '1px solid #222',\r\n background: '#111',\r\n },\r\n }, [\r\n React.createElement('div', {\r\n key: 'title',\r\n style: { display: 'flex', alignItems: 'center', gap: 8 },\r\n }, [\r\n React.createElement('span', { key: 'icon' }, '⚡'),\r\n React.createElement('span', { key: 'text', style: { fontWeight: 600 } }, 'FlexiReact DevTools'),\r\n ]),\r\n React.createElement('button', {\r\n key: 'close',\r\n onClick: () => setState(s => ({ ...s, expanded: false })),\r\n style: {\r\n background: 'none',\r\n border: 'none',\r\n color: '#666',\r\n cursor: 'pointer',\r\n fontSize: 18,\r\n },\r\n }, '×'),\r\n ]),\r\n\r\n // Tabs\r\n React.createElement('div', {\r\n key: 'tabs',\r\n style: {\r\n display: 'flex',\r\n borderBottom: '1px solid #222',\r\n background: '#0d0d0d',\r\n overflowX: 'auto',\r\n },\r\n }, tabs.map(tab => \r\n React.createElement('button', {\r\n key: tab.id,\r\n onClick: () => setState(s => ({ ...s, activeTab: tab.id as any })),\r\n style: {\r\n padding: '10px 14px',\r\n background: state.activeTab === tab.id ? '#1a1a1a' : 'transparent',\r\n border: 'none',\r\n borderBottom: state.activeTab === tab.id ? '2px solid #00FF9C' : '2px solid transparent',\r\n color: state.activeTab === tab.id ? '#fff' : '#888',\r\n cursor: 'pointer',\r\n fontSize: 12,\r\n whiteSpace: 'nowrap',\r\n },\r\n }, `${tab.label} (${tab.count})`)\r\n )),\r\n\r\n // Content\r\n React.createElement('div', {\r\n key: 'content',\r\n style: {\r\n padding: 16,\r\n maxHeight: 'calc(70vh - 100px)',\r\n overflowY: 'auto',\r\n },\r\n }, renderTabContent(state.activeTab, data)),\r\n ]);\r\n}\r\n\r\nfunction renderTabContent(tab: string, data: ReturnType<typeof devtools.getState>): React.ReactElement {\r\n switch (tab) {\r\n case 'routes':\r\n return React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 8 } },\r\n data.routes.length === 0 \r\n ? React.createElement('div', { style: { color: '#666', textAlign: 'center', padding: 20 } }, 'No routes tracked yet')\r\n : data.routes.map((route, i) => \r\n React.createElement('div', {\r\n key: i,\r\n style: {\r\n padding: 12,\r\n background: '#111',\r\n borderRadius: 8,\r\n border: '1px solid #222',\r\n },\r\n }, [\r\n React.createElement('div', { key: 'path', style: { fontWeight: 600, color: '#00FF9C' } }, route.path),\r\n React.createElement('div', { key: 'component', style: { fontSize: 11, color: '#888', marginTop: 4 } }, \r\n `Component: ${route.component} • ${route.loadTime}ms`\r\n ),\r\n ])\r\n )\r\n );\r\n\r\n case 'components':\r\n return React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 8 } },\r\n data.components.length === 0\r\n ? React.createElement('div', { style: { color: '#666', textAlign: 'center', padding: 20 } }, 'No components tracked')\r\n : data.components.map((comp, i) =>\r\n React.createElement('div', {\r\n key: i,\r\n style: {\r\n padding: 12,\r\n background: '#111',\r\n borderRadius: 8,\r\n border: '1px solid #222',\r\n },\r\n }, [\r\n React.createElement('div', { \r\n key: 'name',\r\n style: { display: 'flex', alignItems: 'center', gap: 8 } \r\n }, [\r\n React.createElement('span', { key: 'text', style: { fontWeight: 600 } }, comp.name),\r\n comp.isIsland && React.createElement('span', {\r\n key: 'island',\r\n style: {\r\n fontSize: 10,\r\n padding: '2px 6px',\r\n background: '#00FF9C20',\r\n color: '#00FF9C',\r\n borderRadius: 4,\r\n },\r\n }, 'Island'),\r\n ]),\r\n React.createElement('div', { key: 'info', style: { fontSize: 11, color: '#888', marginTop: 4 } },\r\n `Renders: ${comp.renderCount} • Last: ${new Date(comp.lastRenderTime).toLocaleTimeString()}`\r\n ),\r\n ])\r\n )\r\n );\r\n\r\n case 'network':\r\n return React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 8 } },\r\n data.network.length === 0\r\n ? React.createElement('div', { style: { color: '#666', textAlign: 'center', padding: 20 } }, 'No requests yet')\r\n : data.network.map((req, i) =>\r\n React.createElement('div', {\r\n key: i,\r\n style: {\r\n padding: 12,\r\n background: '#111',\r\n borderRadius: 8,\r\n border: '1px solid #222',\r\n },\r\n }, [\r\n React.createElement('div', { \r\n key: 'url',\r\n style: { display: 'flex', alignItems: 'center', gap: 8 } \r\n }, [\r\n React.createElement('span', {\r\n key: 'method',\r\n style: {\r\n fontSize: 10,\r\n padding: '2px 6px',\r\n background: req.method === 'GET' ? '#3B82F620' : '#F59E0B20',\r\n color: req.method === 'GET' ? '#3B82F6' : '#F59E0B',\r\n borderRadius: 4,\r\n fontWeight: 600,\r\n },\r\n }, req.method),\r\n React.createElement('span', {\r\n key: 'status',\r\n style: {\r\n fontSize: 10,\r\n padding: '2px 6px',\r\n background: req.status >= 200 && req.status < 300 ? '#10B98120' : '#EF444420',\r\n color: req.status >= 200 && req.status < 300 ? '#10B981' : '#EF4444',\r\n borderRadius: 4,\r\n },\r\n }, req.status || 'ERR'),\r\n React.createElement('span', { \r\n key: 'path',\r\n style: { fontSize: 12, color: '#fff', overflow: 'hidden', textOverflow: 'ellipsis' } \r\n }, new URL(req.url, 'http://localhost').pathname),\r\n ]),\r\n React.createElement('div', { key: 'info', style: { fontSize: 11, color: '#888', marginTop: 4 } },\r\n `${req.duration}ms • ${formatBytes(req.size)}`\r\n ),\r\n ])\r\n )\r\n );\r\n\r\n case 'performance':\r\n return React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 8 } },\r\n data.performance.length === 0\r\n ? React.createElement('div', { style: { color: '#666', textAlign: 'center', padding: 20 } }, 'Collecting metrics...')\r\n : data.performance.map((metric, i) =>\r\n React.createElement('div', {\r\n key: i,\r\n style: {\r\n padding: 12,\r\n background: '#111',\r\n borderRadius: 8,\r\n border: '1px solid #222',\r\n display: 'flex',\r\n justifyContent: 'space-between',\r\n alignItems: 'center',\r\n },\r\n }, [\r\n React.createElement('span', { key: 'name', style: { fontWeight: 600 } }, metric.name),\r\n React.createElement('div', { key: 'value', style: { display: 'flex', alignItems: 'center', gap: 8 } }, [\r\n React.createElement('span', { key: 'num' }, \r\n metric.name === 'CLS' ? metric.value.toFixed(3) : `${Math.round(metric.value)}ms`\r\n ),\r\n React.createElement('span', {\r\n key: 'rating',\r\n style: {\r\n width: 8,\r\n height: 8,\r\n borderRadius: '50%',\r\n background: metric.rating === 'good' ? '#10B981' : \r\n metric.rating === 'needs-improvement' ? '#F59E0B' : '#EF4444',\r\n },\r\n }),\r\n ]),\r\n ])\r\n )\r\n );\r\n\r\n case 'console':\r\n return React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 4 } },\r\n data.logs.length === 0\r\n ? React.createElement('div', { style: { color: '#666', textAlign: 'center', padding: 20 } }, 'No logs yet')\r\n : data.logs.map((log, i) =>\r\n React.createElement('div', {\r\n key: i,\r\n style: {\r\n padding: '8px 12px',\r\n background: log.level === 'error' ? '#EF444410' : \r\n log.level === 'warn' ? '#F59E0B10' : '#111',\r\n borderRadius: 6,\r\n fontSize: 12,\r\n fontFamily: 'monospace',\r\n color: log.level === 'error' ? '#EF4444' : \r\n log.level === 'warn' ? '#F59E0B' : '#888',\r\n },\r\n }, [\r\n React.createElement('span', { key: 'time', style: { color: '#444', marginRight: 8 } },\r\n new Date(log.timestamp).toLocaleTimeString()\r\n ),\r\n log.message,\r\n ])\r\n )\r\n );\r\n\r\n default:\r\n return React.createElement('div', {}, 'Unknown tab');\r\n }\r\n}\r\n\r\nfunction formatBytes(bytes: number): string {\r\n if (bytes === 0) return '0 B';\r\n const k = 1024;\r\n const sizes = ['B', 'KB', 'MB'];\r\n const i = Math.floor(Math.log(bytes) / Math.log(k));\r\n return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];\r\n}\r\n\r\n// ============================================================================\r\n// Exports\r\n// ============================================================================\r\n\r\nexport default {\r\n devtools,\r\n DevToolsOverlay,\r\n initPerformanceMonitoring,\r\n initNetworkInterceptor,\r\n};\r\n"],"mappings":";AAKA,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAGvB,IAAM,gBAAgB;AAAA;AAAA,EAE3B,UAAU;AAAA,EACV,YAAY;AAAA,EACZ,WAAW;AAAA,EACX,QAAQ;AAAA;AAAA,EAGR,OAAO;AAAA,IACL,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,WAAW;AAAA,IACX,WAAW;AAAA,EACb;AAAA;AAAA,EAGA,QAAQ;AAAA,IACN,MAAM;AAAA,IACN,MAAM;AAAA,EACR;AAAA;AAAA,EAGA,KAAK;AAAA,IACH,SAAS;AAAA,IACT,OAAO,CAAC;AAAA,EACV;AAAA;AAAA,EAGA,SAAS;AAAA,IACP,SAAS;AAAA,EACX;AAAA;AAAA,EAGA,KAAK;AAAA,IACH,SAAS;AAAA,EACX;AAAA;AAAA,EAGA,SAAS,CAAC;AAAA;AAAA,EAGV,QAAQ,CAAC;AAAA;AAAA,EAGT,SAAS,CAAC;AAAA;AAAA,EAGV,SAAS;AACX;AAOA,eAAsB,WAAW,aAAqB;AAEpD,QAAM,eAAe,KAAK,KAAK,aAAa,sBAAsB;AAClE,QAAM,eAAe,KAAK,KAAK,aAAa,sBAAsB;AAClE,QAAM,aAAa,GAAG,WAAW,YAAY,IAAI,eAAe;AAEhE,MAAI,aAAa,CAAC;AAElB,MAAI,GAAG,WAAW,UAAU,GAAG;AAC7B,QAAI;AACF,YAAM,YAAY,cAAc,UAAU,EAAE;AAC5C,YAAM,SAAS,MAAM,OAAO,GAAG,SAAS,MAAM,KAAK,IAAI,CAAC;AACxD,mBAAa,OAAO,WAAW;AAAA,IACjC,SAAS,OAAY;AACnB,cAAQ,KAAK,8CAA8C,MAAM,OAAO;AAAA,I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,EAAE,OAAO,EAAE,OAAO,QAAQ,WAAW,UAAU,SAAS,GAAG,EAAE,GAAG,aAAa,IACxG,KAAK,KAAK;AAAA,UAAI,CAAC,KAAK,MAClBA,OAAM,cAAc,OAAO;AAAA,YACzB,KAAK;AAAA,YACL,OAAO;AAAA,cACL,SAAS;AAAA,cACT,YAAY,IAAI,UAAU,UAAU,cACxB,IAAI,UAAU,SAAS,cAAc;AAAA,cACjD,cAAc;AAAA,cACd,UAAU;AAAA,cACV,YAAY;AAAA,cACZ,OAAO,IAAI,UAAU,UAAU,YACxB,IAAI,UAAU,SAAS,YAAY;AAAA,YAC5C;AAAA,UACF,GAAG;AAAA,YACDA,OAAM;AAAA,cAAc;AAAA,cAAQ,EAAE,KAAK,QAAQ,OAAO,EAAE,OAAO,QAAQ,aAAa,EAAE,EAAE;AAAA,cAClF,IAAI,KAAK,IAAI,SAAS,EAAE,mBAAmB;AAAA,YAC7C;AAAA,YACA,IAAI;AAAA,UACN,CAAC;AAAA,QACH;AAAA,MACN;AAAA,IAEF;AACE,aAAOA,OAAM,cAAc,OAAO,CAAC,GAAG,aAAa;AAAA,EACvD;AACF;AAEA,SAASC,aAAY,OAAuB;AAC1C,MAAI,UAAU,EAAG,QAAO;AACxB,QAAM,IAAI;AACV,QAAM,QAAQ,CAAC,KAAK,MAAM,IAAI;AAC9B,QAAM,IAAI,KAAK,MAAM,KAAK,IAAI,KAAK,IAAI,KAAK,IAAI,CAAC,CAAC;AAClD,SAAO,YAAY,QAAQ,KAAK,IAAI,GAAG,CAAC,GAAG,QAAQ,CAAC,CAAC,IAAI,MAAM,MAAM,CAAC;AACxE;;;AH7ZO,IAAM,UAAU;AAGvB,IAAO,eAAQ;AAAA,EACb;AAAA,EACA;AACF;","names":["cookies","context","fs","path","fs","path","path","fs","React","React","isClientComponent","content","fs","path","pathToFileURL","fs","path","pathToFileURL","cookies","middlewares","headers","data","fs","path","pathToFileURL","html","headers","React","renderToString","crypto","formatTime","path","headers","cookies","context","React","path","fs","crypto","Image","fs","path","crypto","fonts","__filename","__dirname","path","pathToFileURL","fs","context","isClientComponent","html","fs","path","fileURLToPath","__filename","fileURLToPath","__dirname","path","build","fs","fs","path","path","html","fs","redirect","React","renderToString","context","handleServerAction","runtime","headers","html","text","runtime","path","cache","notFound","context","runMiddleware","matchRoute","middlewares","path","headers","http","React","renderToString","React","renderToString","html","escapeHtml","useActionState","useOptimistic","useFormStatus","useActionState","useOptimistic","useFormStatus","use","React","formatBytes"]}