@flight-framework/core 0.3.1 → 0.4.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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/adapters/handler.ts","../src/adapters/index.ts"],"names":[],"mappings":";AAuKO,SAAS,sBAAA,CAAuB,OAAA,GAAmC,EAAC,EAAqB;AAC5F,EAAA,MAAM;AAAA,IACF,QAAA;AAAA,IACA,aAAa,EAAC;AAAA,IACd,QAAA,GAAW,EAAA;AAAA,IACX,OAAA,GAAU,mBAAA;AAAA,IACV,UAAA,GAAa,sBAAA;AAAA,IACb,QAAQ;AAAC,GACb,GAAI,OAAA;AAEJ,EAAA,OAAO;AAAA;AAAA;AAAA;AAAA,IAIH,MAAM,KAAA,CAAM,OAAA,EAAkB,GAAA,EAAe,GAAA,EAAkC;AAC3E,MAAA,IAAI;AAEA,QAAA,IAAI,MAAM,YAAA,EAAc;AACpB,UAAA,MAAM,eAAA,GAAkB,MAAM,KAAA,CAAM,YAAA,CAAa,OAAO,CAAA;AACxD,UAAA,IAAI,iBAAiB,OAAA,GAAU,eAAA;AAAA,QACnC;AAEA,QAAA,MAAM,GAAA,GAAM,IAAI,GAAA,CAAI,OAAA,CAAQ,GAAG,CAAA;AAC/B,QAAA,IAAI,WAAW,GAAA,CAAI,QAAA;AAGnB,QAAA,IAAI,QAAA,IAAY,QAAA,CAAS,UAAA,CAAW,QAAQ,CAAA,EAAG;AAC3C,UAAA,QAAA,GAAW,QAAA,CAAS,KAAA,CAAM,QAAA,CAAS,MAAM,CAAA,IAAK,GAAA;AAAA,QAClD;AAGA,QAAA,MAAM,KAAA,GAAQ,eAAA,CAAgB,QAAA,EAAU,UAAU,CAAA;AAGlD,QAAA,IAAI,OAAO,QAAA,EAAU;AACjB,UAAA,OAAO,cAAA,CAAe,MAAM,QAAQ,CAAA;AAAA,QACxC;AAGA,QAAA,IAAI,OAAO,KAAA,EAAO;AACd,UAAA,OAAO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I,SAAS,IAAA,EAAM;AAAA,IACtB,OAAA,EAAS,EAAE,cAAA,EAAgB,0BAAA;AAA2B,GACzD,CAAA;AACL;AAEA,SAAS,sBAAsB,QAAA,EAA0B;AACrD,EAAA,OAAO,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBAAA,EAiBY,QAAQ,CAAA;AAAA;AAAA;AAAA;AAAA,OAAA,CAAA;AAK/B;;;ACnaO,SAAS,cAAc,OAAA,EAAwC;AAClE,EAAA,OAAO;AAAA,IACH,MAAM,OAAA,CAAQ,IAAA;AAAA,IACd,OAAO,OAAA,CAAQ,KAAA;AAAA,IACf,SAAS,OAAA,CAAQ,OAAA;AAAA,IACjB,UAAU,OAAA,CAAQ;AAAA,GACtB;AACJ","file":"chunk-K5NYYNFS.js","sourcesContent":["/**\r\n * Flight Universal Handler - Platform-agnostic request handler\r\n * \r\n * This is the core abstraction that allows Flight applications to run anywhere.\r\n * Adapters can use this handler, or implement their own - zero lock-in.\r\n * \r\n * @module @flight-framework/core/adapters/handler\r\n */\r\n\r\nimport type { RenderContext, RenderResult, UIFrameworkAdapter } from '../render/index.js';\r\n\r\n// ============================================================================\r\n// Types\r\n// ============================================================================\r\n\r\n/**\r\n * Route rules for per-path configuration\r\n * Similar to Nitro's routeRules - completely optional to use\r\n */\r\nexport interface RouteRules {\r\n [pattern: string]: RouteRuleConfig;\r\n}\r\n\r\nexport interface RouteRuleConfig {\r\n /** Cache configuration */\r\n cache?: {\r\n /** Max age in seconds */\r\n maxAge?: number;\r\n /** Stale-while-revalidate in seconds */\r\n swr?: number;\r\n /** Vary headers */\r\n vary?: string[];\r\n };\r\n\r\n /** CORS configuration */\r\n cors?: boolean | CorsOptions;\r\n\r\n /** Headers to add to response */\r\n headers?: Record<string, string>;\r\n\r\n /** Redirect configuration */\r\n redirect?: string | {\r\n to: string;\r\n statusCode?: 301 | 302 | 303 | 307 | 308;\r\n };\r\n\r\n /** Proxy to another URL */\r\n proxy?: string;\r\n\r\n /** Render mode override */\r\n render?: 'ssr' | 'ssg' | 'csr' | 'isr';\r\n\r\n /** ISR revalidation time in seconds */\r\n isr?: number;\r\n\r\n /** Prerender at build time */\r\n prerender?: boolean;\r\n}\r\n\r\nexport interface CorsOptions {\r\n origin?: string | string[] | boolean;\r\n methods?: string[];\r\n allowedHeaders?: string[];\r\n exposedHeaders?: string[];\r\n credentials?: boolean;\r\n maxAge?: number;\r\n}\r\n\r\n/**\r\n * Handler options - all optional, user configures what they need\r\n */\r\nexport interface UniversalHandlerOptions {\r\n /** Route manifest from build */\r\n manifest?: RouteManifest;\r\n\r\n /** UI framework adapter (optional - for SSR) */\r\n framework?: UIFrameworkAdapter;\r\n\r\n /** Route rules (optional) */\r\n routeRules?: RouteRules;\r\n\r\n /** Static files directory (optional) */\r\n staticDir?: string;\r\n\r\n /** Base path (optional) */\r\n basePath?: string;\r\n\r\n /** Custom error handler (optional) */\r\n onError?: (error: Error, request: Request) => Response | Promise<Response>;\r\n\r\n /** Custom not found handler (optional) */\r\n onNotFound?: (request: Request) => Response | Promise<Response>;\r\n\r\n /** Hooks for extensibility (optional) */\r\n hooks?: HandlerHooks;\r\n}\r\n\r\n/**\r\n * Handler hooks for extensibility - all optional\r\n */\r\nexport interface HandlerHooks {\r\n /** Before handling request */\r\n beforeHandle?: (request: Request) => Request | Promise<Request> | void;\r\n\r\n /** After getting response, before sending */\r\n afterHandle?: (request: Request, response: Response) => Response | Promise<Response> | void;\r\n\r\n /** Before SSR render */\r\n beforeRender?: (context: RenderContext) => void | Promise<void>;\r\n\r\n /** After SSR render */\r\n afterRender?: (result: RenderResult) => RenderResult | Promise<RenderResult>;\r\n}\r\n\r\n/**\r\n * Route manifest from build\r\n */\r\nexport interface RouteManifest {\r\n routes: Array<{\r\n path: string;\r\n component: string;\r\n mode: 'ssr' | 'ssg' | 'csr' | 'isr';\r\n handler?: string;\r\n }>;\r\n staticFiles?: string[];\r\n}\r\n\r\n/**\r\n * Universal handler interface\r\n */\r\nexport interface UniversalHandler {\r\n /** Handle a fetch request */\r\n fetch(request: Request, env?: unknown, ctx?: unknown): Promise<Response>;\r\n\r\n /** Check if this handler can handle the request */\r\n canHandle(request: Request): boolean;\r\n}\r\n\r\n// ============================================================================\r\n// Handler Factory\r\n// ============================================================================\r\n\r\n/**\r\n * Create a universal request handler\r\n * \r\n * This is the main abstraction for handling requests.\r\n * Adapters can use this, extend it, or ignore it completely.\r\n * \r\n * @example\r\n * ```typescript\r\n * // Using the handler (optional)\r\n * import { createUniversalHandler } from '@flight-framework/core/adapters';\r\n * \r\n * const handler = createUniversalHandler({\r\n * manifest: await import('./manifest.json'),\r\n * routeRules: {\r\n * '/api/**': { cors: true },\r\n * '/blog/**': { cache: { maxAge: 3600 } },\r\n * },\r\n * });\r\n * \r\n * // In your adapter\r\n * export default {\r\n * fetch: handler.fetch,\r\n * };\r\n * ```\r\n */\r\nexport function createUniversalHandler(options: UniversalHandlerOptions = {}): UniversalHandler {\r\n const {\r\n manifest,\r\n routeRules = {},\r\n basePath = '',\r\n onError = defaultErrorHandler,\r\n onNotFound = defaultNotFoundHandler,\r\n hooks = {},\r\n } = options;\r\n\r\n return {\r\n /**\r\n * Handle incoming request\r\n */\r\n async fetch(request: Request, env?: unknown, ctx?: unknown): Promise<Response> {\r\n try {\r\n // Run beforeHandle hook\r\n if (hooks.beforeHandle) {\r\n const modifiedRequest = await hooks.beforeHandle(request);\r\n if (modifiedRequest) request = modifiedRequest;\r\n }\r\n\r\n const url = new URL(request.url);\r\n let pathname = url.pathname;\r\n\r\n // Strip base path if present\r\n if (basePath && pathname.startsWith(basePath)) {\r\n pathname = pathname.slice(basePath.length) || '/';\r\n }\r\n\r\n // Apply route rules\r\n const rules = matchRouteRules(pathname, routeRules);\r\n\r\n // Handle redirect rules\r\n if (rules?.redirect) {\r\n return handleRedirect(rules.redirect);\r\n }\r\n\r\n // Handle proxy rules\r\n if (rules?.proxy) {\r\n return handleProxy(request, rules.proxy);\r\n }\r\n\r\n // Handle CORS preflight\r\n if (request.method === 'OPTIONS' && rules?.cors) {\r\n return handleCorsPreFlight(rules.cors);\r\n }\r\n\r\n // Find matching route from manifest\r\n const route = manifest?.routes?.find(r => matchPath(pathname, r.path));\r\n\r\n // No matching route - try static or return 404\r\n if (!route) {\r\n return await onNotFound(request);\r\n }\r\n\r\n // Build render context\r\n const context: RenderContext = {\r\n url,\r\n params: extractParams(pathname, route.path),\r\n headers: request.headers,\r\n method: request.method,\r\n };\r\n\r\n // Run beforeRender hook\r\n if (hooks.beforeRender) {\r\n await hooks.beforeRender(context);\r\n }\r\n\r\n // Generate response based on route mode\r\n let response: Response;\r\n\r\n switch (route.mode) {\r\n case 'ssr':\r\n case 'isr':\r\n response = await handleSSR(context, options);\r\n break;\r\n case 'ssg':\r\n response = await handleSSG(context, options);\r\n break;\r\n case 'csr':\r\n response = handleCSR(options);\r\n break;\r\n default:\r\n response = await handleSSR(context, options);\r\n }\r\n\r\n // Apply cache headers from route rules\r\n if (rules?.cache) {\r\n response = applyCacheHeaders(response, rules.cache);\r\n }\r\n\r\n // Apply CORS headers\r\n if (rules?.cors) {\r\n response = applyCorsHeaders(response, rules.cors, request);\r\n }\r\n\r\n // Apply custom headers\r\n if (rules?.headers) {\r\n response = applyCustomHeaders(response, rules.headers);\r\n }\r\n\r\n // Run afterHandle hook\r\n if (hooks.afterHandle) {\r\n const modifiedResponse = await hooks.afterHandle(request, response);\r\n if (modifiedResponse) response = modifiedResponse;\r\n }\r\n\r\n return response;\r\n\r\n } catch (error) {\r\n return onError(error as Error, request);\r\n }\r\n },\r\n\r\n /**\r\n * Check if this handler can handle the request\r\n */\r\n canHandle(request: Request): boolean {\r\n const url = new URL(request.url);\r\n let pathname = url.pathname;\r\n\r\n if (basePath && pathname.startsWith(basePath)) {\r\n pathname = pathname.slice(basePath.length) || '/';\r\n }\r\n\r\n // Check manifest routes\r\n if (manifest?.routes) {\r\n return manifest.routes.some(r => matchPath(pathname, r.path));\r\n }\r\n\r\n // Check route rules\r\n return Object.keys(routeRules).some(pattern =>\r\n matchPath(pathname, pattern)\r\n );\r\n },\r\n };\r\n}\r\n\r\n// ============================================================================\r\n// Internal Helpers\r\n// ============================================================================\r\n\r\nfunction defaultErrorHandler(error: Error, _request: Request): Response {\r\n console.error('[Flight] Request error:', error);\r\n\r\n return new Response(\r\n JSON.stringify({\r\n error: 'Internal Server Error',\r\n message: process.env.NODE_ENV === 'development' ? error.message : undefined,\r\n }),\r\n {\r\n status: 500,\r\n headers: { 'Content-Type': 'application/json' },\r\n }\r\n );\r\n}\r\n\r\nfunction defaultNotFoundHandler(_request: Request): Response {\r\n return new Response('Not Found', { status: 404 });\r\n}\r\n\r\nfunction matchRouteRules(pathname: string, rules: RouteRules): RouteRuleConfig | null {\r\n for (const [pattern, config] of Object.entries(rules)) {\r\n if (matchPath(pathname, pattern)) {\r\n return config;\r\n }\r\n }\r\n return null;\r\n}\r\n\r\nfunction matchPath(pathname: string, pattern: string): boolean {\r\n // Handle exact match\r\n if (pattern === pathname) return true;\r\n\r\n // Handle wildcard patterns\r\n if (pattern.endsWith('/**')) {\r\n const prefix = pattern.slice(0, -3);\r\n return pathname.startsWith(prefix);\r\n }\r\n\r\n if (pattern.endsWith('/*')) {\r\n const prefix = pattern.slice(0, -2);\r\n const rest = pathname.slice(prefix.length);\r\n return pathname.startsWith(prefix) && !rest.includes('/');\r\n }\r\n\r\n // Handle dynamic params\r\n const patternParts = pattern.split('/');\r\n const pathParts = pathname.split('/');\r\n\r\n if (patternParts.length !== pathParts.length) return false;\r\n\r\n return patternParts.every((part, i) => {\r\n if (part.startsWith('[') && part.endsWith(']')) return true;\r\n if (part.startsWith(':')) return true;\r\n return part === pathParts[i];\r\n });\r\n}\r\n\r\nfunction extractParams(pathname: string, pattern: string): Record<string, string> {\r\n const params: Record<string, string> = {};\r\n const patternParts = pattern.split('/');\r\n const pathParts = pathname.split('/');\r\n\r\n patternParts.forEach((part, i) => {\r\n if (part.startsWith('[') && part.endsWith(']')) {\r\n const key = part.slice(1, -1).replace('...', '');\r\n params[key] = pathParts[i] ?? '';\r\n } else if (part.startsWith(':')) {\r\n params[part.slice(1)] = pathParts[i] ?? '';\r\n }\r\n });\r\n\r\n return params;\r\n}\r\n\r\nfunction handleRedirect(redirect: string | { to: string; statusCode?: number }): Response {\r\n const to = typeof redirect === 'string' ? redirect : redirect.to;\r\n const status = typeof redirect === 'string' ? 302 : (redirect.statusCode ?? 302);\r\n\r\n return new Response(null, {\r\n status,\r\n headers: { Location: to },\r\n });\r\n}\r\n\r\nasync function handleProxy(request: Request, target: string): Promise<Response> {\r\n const url = new URL(request.url);\r\n const targetUrl = new URL(target);\r\n targetUrl.pathname = url.pathname;\r\n targetUrl.search = url.search;\r\n\r\n const proxyRequest = new Request(targetUrl.toString(), {\r\n method: request.method,\r\n headers: request.headers,\r\n body: request.body,\r\n });\r\n\r\n return fetch(proxyRequest);\r\n}\r\n\r\nfunction handleCorsPreFlight(cors: boolean | CorsOptions): Response {\r\n // Normalize CORS options - true means default options, object means custom\r\n const options: CorsOptions = cors === true ? {} : (cors || {});\r\n\r\n return new Response(null, {\r\n status: 204,\r\n headers: {\r\n 'Access-Control-Allow-Origin': resolveOrigin(options.origin),\r\n 'Access-Control-Allow-Methods': (options.methods ?? ['GET', 'POST', 'PUT', 'DELETE', 'PATCH']).join(', '),\r\n 'Access-Control-Allow-Headers': (options.allowedHeaders ?? ['Content-Type', 'Authorization']).join(', '),\r\n 'Access-Control-Max-Age': String(options.maxAge ?? 86400),\r\n ...(options.credentials && { 'Access-Control-Allow-Credentials': 'true' }),\r\n },\r\n });\r\n}\r\n\r\nfunction resolveOrigin(origin?: string | string[] | boolean): string {\r\n if (origin === true || origin === undefined) return '*';\r\n if (origin === false) return '*';\r\n if (Array.isArray(origin)) return origin[0] ?? '*';\r\n return origin;\r\n}\r\n\r\nfunction applyCacheHeaders(response: Response, cache: { maxAge?: number; swr?: number }): Response {\r\n const headers = new Headers(response.headers);\r\n\r\n let cacheControl = `public, max-age=${cache.maxAge ?? 0}`;\r\n if (cache.swr) {\r\n cacheControl += `, stale-while-revalidate=${cache.swr}`;\r\n }\r\n\r\n headers.set('Cache-Control', cacheControl);\r\n\r\n return new Response(response.body, {\r\n status: response.status,\r\n statusText: response.statusText,\r\n headers,\r\n });\r\n}\r\n\r\nfunction applyCorsHeaders(response: Response, cors: boolean | CorsOptions, _request: Request): Response {\r\n // Normalize CORS options\r\n const options: CorsOptions = cors === true ? {} : (cors || {});\r\n const headers = new Headers(response.headers);\r\n\r\n headers.set('Access-Control-Allow-Origin', resolveOrigin(options.origin));\r\n\r\n if (options.credentials) {\r\n headers.set('Access-Control-Allow-Credentials', 'true');\r\n }\r\n\r\n if (options.exposedHeaders) {\r\n headers.set('Access-Control-Expose-Headers', options.exposedHeaders.join(', '));\r\n }\r\n\r\n return new Response(response.body, {\r\n status: response.status,\r\n statusText: response.statusText,\r\n headers,\r\n });\r\n}\r\n\r\nfunction applyCustomHeaders(response: Response, customHeaders: Record<string, string>): Response {\r\n const headers = new Headers(response.headers);\r\n\r\n for (const [key, value] of Object.entries(customHeaders)) {\r\n headers.set(key, value);\r\n }\r\n\r\n return new Response(response.body, {\r\n status: response.status,\r\n statusText: response.statusText,\r\n headers,\r\n });\r\n}\r\n\r\nasync function handleSSR(context: RenderContext, options: UniversalHandlerOptions): Promise<Response> {\r\n const { framework, hooks } = options;\r\n\r\n // If no framework adapter, return placeholder\r\n if (!framework) {\r\n return new Response(createPlaceholderHTML(context.url.pathname), {\r\n headers: { 'Content-Type': 'text/html; charset=utf-8' },\r\n });\r\n }\r\n\r\n // Render with framework adapter\r\n let result = await framework.renderToString({} as never, context);\r\n\r\n // Run afterRender hook\r\n if (hooks?.afterRender) {\r\n const modifiedResult = await hooks.afterRender(result);\r\n if (modifiedResult) result = modifiedResult;\r\n }\r\n\r\n return new Response(result.html, {\r\n status: result.status,\r\n headers: result.headers,\r\n });\r\n}\r\n\r\nasync function handleSSG(context: RenderContext, options: UniversalHandlerOptions): Promise<Response> {\r\n // For SSG, typically serve pre-rendered HTML\r\n // Fall back to SSR if not found\r\n return handleSSR(context, options);\r\n}\r\n\r\nfunction handleCSR(options: UniversalHandlerOptions): Response {\r\n const html = `<!DOCTYPE html>\r\n<html>\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>Flight App</title>\r\n </head>\r\n <body>\r\n <div id=\"app\"></div>\r\n <script type=\"module\" src=\"/assets/client.js\"></script>\r\n </body>\r\n</html>`;\r\n\r\n return new Response(html, {\r\n headers: { 'Content-Type': 'text/html; charset=utf-8' },\r\n });\r\n}\r\n\r\nfunction createPlaceholderHTML(pathname: string): string {\r\n return `<!DOCTYPE html>\r\n<html>\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>Flight</title>\r\n <style>\r\n body { font-family: system-ui, sans-serif; display: flex; align-items: center; justify-content: center; min-height: 100vh; margin: 0; background: #0a0a0a; color: #fafafa; }\r\n .container { text-align: center; }\r\n h1 { font-size: 3rem; margin-bottom: 0.5rem; }\r\n p { color: #888; }\r\n code { background: #1a1a1a; padding: 0.25rem 0.5rem; border-radius: 4px; font-size: 0.875rem; }\r\n </style>\r\n </head>\r\n <body>\r\n <div class=\"container\">\r\n <h1>Flight</h1>\r\n <p>Path: <code>${pathname}</code></p>\r\n <p>Configure a UI framework adapter to enable SSR.</p>\r\n </div>\r\n </body>\r\n</html>`;\r\n}\r\n\r\n// Note: All exports are at the point of definition (export interface, export function)\r\n","/**\r\n * Flight Adapters - Universal deployment adapters\r\n * \r\n * Adapters transform Flight's output for different deployment targets.\r\n * The user chooses where to deploy - Flight provides the adapters.\r\n */\r\n\r\n// ============================================================================\r\n// Types\r\n// ============================================================================\r\n\r\n/** Build manifest containing all generated assets */\r\nexport interface BuildManifest {\r\n /** Entry points by name */\r\n entries: Record<string, string>;\r\n /** All generated files */\r\n files: string[];\r\n /** Route information */\r\n routes: RouteManifestEntry[];\r\n /** Server entry point (if applicable) */\r\n serverEntry?: string;\r\n /** Client entry point */\r\n clientEntry?: string;\r\n}\r\n\r\n/** Route information in manifest */\r\nexport interface RouteManifestEntry {\r\n /** Route path pattern */\r\n path: string;\r\n /** Render mode for this route */\r\n mode: 'ssr' | 'ssg' | 'csr' | 'isr';\r\n /** Component/handler file path */\r\n component: string;\r\n /** Pre-rendered paths (for SSG/ISR) */\r\n prerendered?: string[];\r\n}\r\n\r\n/** Builder utilities passed to adapters */\r\nexport interface AdapterBuilder {\r\n /** Build manifest */\r\n manifest: BuildManifest;\r\n /** Project root directory */\r\n root: string;\r\n /** Build output directory */\r\n outDir: string;\r\n\r\n /** Read a file from the build output */\r\n readFile(path: string): Promise<string>;\r\n /** Write a file to the adapter output */\r\n writeFile(path: string, content: string): Promise<void>;\r\n /** Copy files from build to adapter output */\r\n copy(from: string, to: string): Promise<void>;\r\n /** Get all files matching a pattern */\r\n glob(pattern: string): Promise<string[]>;\r\n /** Compress files for production */\r\n compress?(files: string[]): Promise<void>;\r\n\r\n /** Log info message */\r\n log: {\r\n info(message: string): void;\r\n warn(message: string): void;\r\n error(message: string): void;\r\n };\r\n}\r\n\r\n/** Flight adapter interface */\r\nexport interface FlightAdapter {\r\n /** Adapter name */\r\n name: string;\r\n\r\n /** \r\n * Transform the build output for the target platform\r\n * This is called after Flight's build process completes\r\n */\r\n adapt(builder: AdapterBuilder): Promise<void>;\r\n\r\n /**\r\n * Optional: Start listening for requests (for Node.js/Bun adapters)\r\n */\r\n listen?(server: unknown, port: number): Promise<void>;\r\n\r\n /**\r\n * Optional: Emulate the platform during development\r\n * Useful for testing platform-specific behavior locally\r\n */\r\n emulate?(): {\r\n /** Platform-specific env vars */\r\n env?: Record<string, string>;\r\n /** Custom middleware for dev server */\r\n middleware?: unknown[];\r\n };\r\n\r\n /**\r\n * Optional: Declare what this adapter supports\r\n * Flight uses this to warn about incompatible features\r\n */\r\n supports?: {\r\n /** Can read files at runtime (for dynamic content) */\r\n read?: () => boolean;\r\n /** Supports streaming responses */\r\n streaming?: () => boolean;\r\n /** Supports WebSockets */\r\n websockets?: () => boolean;\r\n /** Supports edge runtime */\r\n edge?: () => boolean;\r\n /** Supports Node.js runtime */\r\n node?: () => boolean;\r\n };\r\n}\r\n\r\n\r\n// ============================================================================\r\n// Adapter Factory Helper\r\n// ============================================================================\r\n\r\nexport interface AdapterOptions {\r\n name: string;\r\n adapt: (builder: AdapterBuilder) => Promise<void>;\r\n emulate?: FlightAdapter['emulate'];\r\n supports?: FlightAdapter['supports'];\r\n}\r\n\r\n/**\r\n * Create a Flight adapter\r\n * \r\n * @example\r\n * ```typescript\r\n * import { createAdapter } from '@flight-framework/core/adapters';\r\n * \r\n * export default function myAdapter(options = {}) {\r\n * return createAdapter({\r\n * name: 'my-adapter',\r\n * async adapt(builder) {\r\n * // Transform build output for your platform\r\n * },\r\n * });\r\n * }\r\n * ```\r\n */\r\nexport function createAdapter(options: AdapterOptions): FlightAdapter {\r\n return {\r\n name: options.name,\r\n adapt: options.adapt,\r\n emulate: options.emulate,\r\n supports: options.supports,\r\n };\r\n}\r\n\r\n// Re-export universal handler for adapters to use (optional)\r\nexport * from './handler.js';\r\n\r\n// ============================================================================\r\n// Agnostic Service Adapters (Interfaces)\r\n// ============================================================================\r\n\r\n/**\r\n * Storage Adapter Interface\r\n * \r\n * Implement this to use any storage provider:\r\n * S3, Supabase Storage, Cloudflare R2, local filesystem, etc.\r\n */\r\nexport interface StorageAdapter {\r\n name: string;\r\n\r\n /** Upload a file */\r\n upload(path: string, data: Buffer | Uint8Array | string, options?: {\r\n contentType?: string;\r\n metadata?: Record<string, string>;\r\n }): Promise<{ url: string; path: string }>;\r\n\r\n /** Download a file */\r\n download(path: string): Promise<Buffer>;\r\n\r\n /** Delete a file */\r\n delete(path: string): Promise<void>;\r\n\r\n /** List files with optional prefix */\r\n list(prefix?: string): Promise<string[]>;\r\n\r\n /** Get a signed URL for direct access */\r\n getSignedUrl?(path: string, options?: {\r\n expiresIn?: number;\r\n operation?: 'read' | 'write';\r\n }): Promise<string>;\r\n}\r\n\r\n/**\r\n * Auth Adapter Interface\r\n * \r\n * Implement this to use any auth provider:\r\n * Better Auth, Supabase Auth, Lucia, Auth.js, etc.\r\n */\r\nexport interface AuthAdapter {\r\n name: string;\r\n\r\n /** Get the current user from a request */\r\n getUser(request: Request): Promise<AuthUser | null>;\r\n\r\n /** Verify a session token */\r\n verifySession(token: string): Promise<AuthSession | null>;\r\n\r\n /** Optional middleware for handling auth-specific routes (e.g., /api/auth/*) */\r\n middleware?: (req: Request) => Promise<Response | null>;\r\n}\r\n\r\nexport interface AuthUser {\r\n id: string;\r\n email?: string;\r\n name?: string;\r\n avatar?: string;\r\n metadata?: Record<string, unknown>;\r\n}\r\n\r\nexport interface AuthSession {\r\n user: AuthUser;\r\n expiresAt: Date;\r\n token: string;\r\n}\r\n\r\n/**\r\n * Email Adapter Interface\r\n * \r\n * Implement this to use any email provider:\r\n * Resend, SendGrid, Postmark, SMTP, etc.\r\n */\r\nexport interface EmailAdapter {\r\n name: string;\r\n\r\n /** Send an email */\r\n send(options: {\r\n to: string | string[];\r\n subject: string;\r\n html?: string;\r\n text?: string;\r\n from?: string;\r\n replyTo?: string;\r\n attachments?: Array<{\r\n filename: string;\r\n content: Buffer | string;\r\n contentType?: string;\r\n }>;\r\n }): Promise<{ id: string; success: boolean }>;\r\n}\r\n\r\n/**\r\n * Queue/Jobs Adapter Interface\r\n * \r\n * Implement this to use any job queue:\r\n * BullMQ, Quirrel, Inngest, custom, etc.\r\n */\r\nexport interface JobsAdapter {\r\n name: string;\r\n\r\n /** Add a job to the queue */\r\n enqueue<T>(jobName: string, data: T, options?: {\r\n delay?: number;\r\n priority?: number;\r\n retries?: number;\r\n }): Promise<{ id: string }>;\r\n\r\n /** Schedule a recurring job */\r\n schedule?(jobName: string, cron: string, data?: unknown): Promise<{ id: string }>;\r\n\r\n /** Cancel a job */\r\n cancel?(jobId: string): Promise<void>;\r\n}\r\n\r\n/**\r\n * Database Adapter Interface\r\n * \r\n * Note: This is intentionally minimal. \r\n * For databases, use your preferred ORM/query builder directly.\r\n * This interface is for Flight's internal use (sessions, cache, etc.)\r\n */\r\nexport interface DatabaseAdapter {\r\n name: string;\r\n\r\n /** Raw query execution */\r\n query<T = unknown>(sql: string, params?: unknown[]): Promise<T[]>;\r\n\r\n /** Execute a mutation */\r\n execute(sql: string, params?: unknown[]): Promise<{ rowsAffected: number }>;\r\n\r\n /** Transaction support */\r\n transaction?<T>(fn: (tx: DatabaseAdapter) => Promise<T>): Promise<T>;\r\n}\r\n"]}
@@ -139,6 +139,32 @@ function composeComponents(...components) {
139
139
  return results.join("");
140
140
  };
141
141
  }
142
+ function withAsyncErrorBoundary(component, options) {
143
+ const { fallback, onError, rethrowNavigation = true } = options;
144
+ return async (props, context) => {
145
+ try {
146
+ return await component(props, context);
147
+ } catch (error) {
148
+ if (rethrowNavigation) {
149
+ if (isNotFoundError(error)) {
150
+ throw error;
151
+ }
152
+ if (isRedirectError(error)) {
153
+ throw error;
154
+ }
155
+ }
156
+ if (onError) {
157
+ try {
158
+ onError(error, props, context);
159
+ } catch (callbackError) {
160
+ console.error("[Flight] Error in onError callback:", callbackError);
161
+ }
162
+ }
163
+ console.error("[Flight] Async component error:", error);
164
+ return fallback(error, props);
165
+ }
166
+ };
167
+ }
142
168
  function withErrorBoundary(component, errorFallback) {
143
169
  return async (props, context) => {
144
170
  try {
@@ -169,6 +195,6 @@ function isRedirectError(error) {
169
195
  return null;
170
196
  }
171
197
 
172
- export { composeComponents, createAsyncComponent, createClientBoundary, createRenderContext, deserializeProps, executeServerComponent, isNotFoundError, isRedirectError, notFound, redirect, revalidatePath, revalidateTag, serializeProps, serverFetch, withErrorBoundary };
173
- //# sourceMappingURL=chunk-3ZSSRE6M.js.map
174
- //# sourceMappingURL=chunk-3ZSSRE6M.js.map
198
+ export { composeComponents, createAsyncComponent, createClientBoundary, createRenderContext, deserializeProps, executeServerComponent, isNotFoundError, isRedirectError, notFound, redirect, revalidatePath, revalidateTag, serializeProps, serverFetch, withAsyncErrorBoundary, withErrorBoundary };
199
+ //# sourceMappingURL=chunk-LNV47HGV.js.map
200
+ //# sourceMappingURL=chunk-LNV47HGV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/rsc/legacy.ts"],"names":[],"mappings":";AAoEA,eAAsB,sBAAA,CAClB,SAAA,EACA,KAAA,EACA,OAAA,EACe;AACf,EAAA,IAAI;AACA,IAAA,MAAM,MAAA,GAAS,MAAM,SAAA,CAAU,KAAA,EAAO,OAAO,CAAA;AAC7C,IAAA,OAAO,MAAA;AAAA,EACX,SAAS,KAAA,EAAO;AACZ,IAAA,OAAA,CAAQ,KAAA,CAAM,oCAAoC,KAAK,CAAA;AACvD,IAAA,MAAM,KAAA;AAAA,EACV;AACJ;AAMO,SAAS,mBAAA,CAAoB,OAAA,EAAkB,MAAA,GAAiC,EAAC,EAAkB;AACtG,EAAA,MAAM,GAAA,GAAM,IAAI,GAAA,CAAI,OAAA,CAAQ,GAAG,CAAA;AAG/B,EAAA,MAAM,OAAA,uBAAc,GAAA,EAAoB;AACxC,EAAA,MAAM,YAAA,GAAe,OAAA,CAAQ,OAAA,CAAQ,GAAA,CAAI,QAAQ,CAAA,IAAK,EAAA;AACtD,EAAA,YAAA,CAAa,KAAA,CAAM,GAAG,CAAA,CAAE,OAAA,CAAQ,CAAA,MAAA,KAAU;AACtC,IAAA,MAAM,CAAC,KAAK,KAAK,CAAA,GAAI,OAAO,IAAA,EAAK,CAAE,MAAM,GAAG,CAAA;AAC5C,IAAA,IAAI,GAAA,IAAO,KAAA,EAAO,OAAA,CAAQ,GAAA,CAAI,KAAK,KAAK,CAAA;AAAA,EAC5C,CAAC,CAAA;AAED,EAAA,OAAO;AAAA,IACH,OAAA;AAAA,IACA,MAAA;AAAA,IACA,cAAc,GAA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iBAAA,GAAoB,EAAE,GAAA,EAAK,IAAA,EAAK;AACxG,EAAA,MAAM,KAAA;AACV;AAMO,SAAS,gBAAgB,KAAA,EAAsD;AAClF,EAAA,IAAI,KAAA,YAAiB,KAAA,IAAU,KAAA,CAAkD,iBAAA,EAAmB;AAChG,IAAA,OAAQ,KAAA,CAAuE,iBAAA;AAAA,EACnF;AACA,EAAA,OAAO,IAAA;AACX","file":"chunk-LNV47HGV.js","sourcesContent":["/**\r\n * @flight-framework/core - Legacy RSC Support\r\n * \r\n * Backward compatibility module for the original RSC implementation.\r\n * Use the new API from './index.js' for new features.\r\n * \r\n * @deprecated Use the new RSC API instead\r\n * @module @flight-framework/core/rsc/legacy\r\n */\r\n\r\n// ============================================================================\r\n// Types\r\n// ============================================================================\r\n\r\n/**\r\n * Component rendering context\r\n * @deprecated Use ServerContext from './context.js' instead\r\n */\r\nexport interface RenderContext {\r\n /** Current request */\r\n request: Request;\r\n /** Route params */\r\n params: Record<string, string>;\r\n /** Search params */\r\n searchParams: URLSearchParams;\r\n /** Request headers */\r\n headers: Headers;\r\n /** Cookies */\r\n cookies: Map<string, string>;\r\n}\r\n\r\n/**\r\n * Server component definition\r\n * @deprecated Use ServerComponentFn from './index.js' instead\r\n */\r\nexport interface ServerComponent<P = unknown> {\r\n (props: P, context: RenderContext): Promise<string> | string;\r\n /** Mark as server component */\r\n __flight_server?: true;\r\n /** Dependencies for hydration */\r\n __flight_deps?: string[];\r\n}\r\n\r\n/**\r\n * Client component definition\r\n * @deprecated Use ClientReference from './boundaries.js' instead\r\n */\r\nexport interface ClientComponent<P = unknown> {\r\n (props: P): unknown;\r\n /** Mark as client component */\r\n __flight_client?: true;\r\n /** Client bundle path */\r\n __flight_bundle?: string;\r\n}\r\n\r\n/**\r\n * Component type detection\r\n */\r\nexport type ComponentType = 'server' | 'client' | 'hybrid';\r\n\r\n// ============================================================================\r\n// Server Component Execution\r\n// ============================================================================\r\n\r\n/**\r\n * Execute an async server component\r\n * @deprecated Use the new rendering pipeline instead\r\n */\r\nexport async function executeServerComponent<P>(\r\n component: ServerComponent<P>,\r\n props: P,\r\n context: RenderContext\r\n): Promise<string> {\r\n try {\r\n const result = await component(props, context);\r\n return result;\r\n } catch (error) {\r\n console.error('[Flight] Server component error:', error);\r\n throw error;\r\n }\r\n}\r\n\r\n/**\r\n * Create a render context from a Request\r\n * @deprecated Use createServerContext from './context.js' instead\r\n */\r\nexport function createRenderContext(request: Request, params: Record<string, string> = {}): RenderContext {\r\n const url = new URL(request.url);\r\n\r\n // Parse cookies\r\n const cookies = new Map<string, string>();\r\n const cookieHeader = request.headers.get('cookie') || '';\r\n cookieHeader.split(';').forEach(cookie => {\r\n const [key, value] = cookie.trim().split('=');\r\n if (key && value) cookies.set(key, value);\r\n });\r\n\r\n return {\r\n request,\r\n params,\r\n searchParams: url.searchParams,\r\n headers: request.headers,\r\n cookies,\r\n };\r\n}\r\n\r\n// ============================================================================\r\n// Data Fetching Helpers\r\n// ============================================================================\r\n\r\n/**\r\n * Cache for server-side fetch requests\r\n */\r\nconst fetchCache = new Map<string, { data: unknown; timestamp: number }>();\r\n\r\n/**\r\n * Server-side fetch with automatic caching\r\n */\r\nexport async function serverFetch<T>(\r\n url: string,\r\n options: RequestInit & {\r\n revalidate?: number | false;\r\n tags?: string[];\r\n } = {}\r\n): Promise<T> {\r\n const { revalidate = 60, ...fetchOptions } = options;\r\n const cacheKey = `${url}:${JSON.stringify(fetchOptions)}`;\r\n\r\n // Check cache\r\n const cached = fetchCache.get(cacheKey);\r\n if (cached) {\r\n const age = Date.now() - cached.timestamp;\r\n if (revalidate === false || age < (revalidate * 1000)) {\r\n return cached.data as T;\r\n }\r\n }\r\n\r\n // Fetch fresh data\r\n const response = await fetch(url, fetchOptions);\r\n\r\n if (!response.ok) {\r\n throw new Error(`Fetch failed: ${response.status} ${response.statusText}`);\r\n }\r\n\r\n const data = await response.json();\r\n\r\n // Cache the result\r\n if (revalidate !== false) {\r\n fetchCache.set(cacheKey, {\r\n data,\r\n timestamp: Date.now(),\r\n });\r\n }\r\n\r\n return data as T;\r\n}\r\n\r\n/**\r\n * Invalidate cache by tag\r\n */\r\nexport function revalidateTag(tag: string): void {\r\n console.log(`[Flight] Revalidating tag: ${tag}`);\r\n}\r\n\r\n/**\r\n * Invalidate cache by path\r\n */\r\nexport function revalidatePath(path: string): void {\r\n console.log(`[Flight] Revalidating path: ${path}`);\r\n}\r\n\r\n// ============================================================================\r\n// Component Serialization\r\n// ============================================================================\r\n\r\n/**\r\n * Serialize props for transmission to client\r\n * @deprecated Use serialize from './payload.js' instead\r\n */\r\nexport function serializeProps(props: unknown): string {\r\n function preProcess(value: unknown): unknown {\r\n if (value instanceof Date) {\r\n return { __type: 'Date', value: value.toISOString() };\r\n }\r\n if (value instanceof Map) {\r\n return { __type: 'Map', value: Array.from(value.entries()).map(([k, v]) => [preProcess(k), preProcess(v)]) };\r\n }\r\n if (value instanceof Set) {\r\n return { __type: 'Set', value: Array.from(value).map(preProcess) };\r\n }\r\n if (typeof value === 'bigint') {\r\n return { __type: 'BigInt', value: value.toString() };\r\n }\r\n if (typeof value === 'function') {\r\n return undefined;\r\n }\r\n if (Array.isArray(value)) {\r\n return value.map(preProcess);\r\n }\r\n if (value && typeof value === 'object') {\r\n const result: Record<string, unknown> = {};\r\n for (const [k, v] of Object.entries(value)) {\r\n result[k] = preProcess(v);\r\n }\r\n return result;\r\n }\r\n return value;\r\n }\r\n\r\n return JSON.stringify(preProcess(props));\r\n}\r\n\r\n/**\r\n * Deserialize props on client\r\n * @deprecated Use deserialize from './payload.js' instead\r\n */\r\nexport function deserializeProps<T>(serialized: string): T {\r\n return JSON.parse(serialized, (_key, value) => {\r\n if (value && typeof value === 'object' && '__type' in value) {\r\n switch (value.__type) {\r\n case 'Date':\r\n return new Date(value.value);\r\n case 'Map':\r\n return new Map(value.value);\r\n case 'Set':\r\n return new Set(value.value);\r\n case 'BigInt':\r\n return BigInt(value.value);\r\n }\r\n }\r\n return value;\r\n });\r\n}\r\n\r\n// ============================================================================\r\n// Client Component Boundary\r\n// ============================================================================\r\n\r\n/**\r\n * Create a client boundary placeholder\r\n * @deprecated Use clientRef from './payload.js' instead\r\n */\r\nexport function createClientBoundary(\r\n componentId: string,\r\n props: unknown,\r\n fallback?: string\r\n): string {\r\n const serializedProps = serializeProps(props);\r\n\r\n return `\r\n<!--flight-client:${componentId}-->\r\n<div data-flight-component=\"${componentId}\" data-flight-props='${serializedProps.replace(/'/g, \"&#39;\")}'>\r\n ${fallback || '<div>Loading...</div>'}\r\n</div>\r\n<!--/flight-client-->\r\n<script type=\"module\">\r\n(async function() {\r\n const component = await import('/_flight/components/${componentId}.js');\r\n const props = JSON.parse('${serializedProps.replace(/'/g, \"\\\\'\")}');\r\n const container = document.querySelector('[data-flight-component=\"${componentId}\"]');\r\n if (container && component.default) {\r\n if (typeof component.hydrate === 'function') {\r\n component.hydrate(container, props);\r\n }\r\n }\r\n})();\r\n</script>`;\r\n}\r\n\r\n// ============================================================================\r\n// Async Component Helpers\r\n// ============================================================================\r\n\r\n/**\r\n * Helper to create an async server component\r\n * @deprecated Use async Server Components directly\r\n */\r\nexport function createAsyncComponent<P, T>(\r\n fetcher: (props: P, context: RenderContext) => Promise<T>,\r\n renderer: (data: T, props: P) => string\r\n): ServerComponent<P> {\r\n const component: ServerComponent<P> = async (props, context) => {\r\n const data = await fetcher(props, context);\r\n return renderer(data, props);\r\n };\r\n component.__flight_server = true;\r\n return component;\r\n}\r\n\r\n/**\r\n * Compose multiple server components\r\n * @deprecated Use Promise.all with async components\r\n */\r\nexport function composeComponents(\r\n ...components: Array<() => Promise<string> | string>\r\n): () => Promise<string> {\r\n return async () => {\r\n const results = await Promise.all(\r\n components.map(async (comp) => await comp())\r\n );\r\n return results.join('');\r\n };\r\n}\r\n\r\n// ============================================================================\r\n// Error Boundary for Server Components\r\n// ============================================================================\r\n\r\n/**\r\n * Options for async error boundary\r\n */\r\nexport interface AsyncErrorBoundaryOptions<P, R> {\r\n /** Fallback to render on error */\r\n fallback: (error: Error, props: P) => R;\r\n /** Optional callback when error occurs */\r\n onError?: (error: Error, props: P, context: RenderContext) => void;\r\n /** Whether to rethrow certain errors (e.g., redirects, not found) */\r\n rethrowNavigation?: boolean;\r\n}\r\n\r\n/**\r\n * Wrap an async server component with comprehensive error handling.\r\n *\r\n * @example\r\n * ```typescript\r\n * const SafeUserPage = withAsyncErrorBoundary(UserPage, {\r\n * fallback: (error, props) => `<div>Error loading user ${props.id}</div>`,\r\n * onError: (error, props) => console.error(`Failed to load user ${props.id}:`, error),\r\n * rethrowNavigation: true,\r\n * });\r\n * ```\r\n */\r\nexport function withAsyncErrorBoundary<P, R = string>(\r\n component: (props: P, context: RenderContext) => Promise<R> | R,\r\n options: AsyncErrorBoundaryOptions<P, R>\r\n): (props: P, context: RenderContext) => Promise<R> {\r\n const { fallback, onError, rethrowNavigation = true } = options;\r\n\r\n return async (props: P, context: RenderContext): Promise<R> => {\r\n try {\r\n return await component(props, context);\r\n } catch (error) {\r\n // Rethrow navigation errors if configured\r\n if (rethrowNavigation) {\r\n if (isNotFoundError(error)) {\r\n throw error;\r\n }\r\n if (isRedirectError(error)) {\r\n throw error;\r\n }\r\n }\r\n\r\n // Call error callback if provided\r\n if (onError) {\r\n try {\r\n onError(error as Error, props, context);\r\n } catch (callbackError) {\r\n console.error('[Flight] Error in onError callback:', callbackError);\r\n }\r\n }\r\n\r\n // Log error\r\n console.error('[Flight] Async component error:', error);\r\n\r\n // Return fallback\r\n return fallback(error as Error, props);\r\n }\r\n };\r\n}\r\n\r\n/**\r\n * Wrap a server component with error handling\r\n * @deprecated Use withAsyncErrorBoundary instead\r\n */\r\nexport function withErrorBoundary<P>(\r\n component: ServerComponent<P>,\r\n errorFallback: (error: Error) => string\r\n): ServerComponent<P> {\r\n return async (props: P, context: RenderContext) => {\r\n try {\r\n return await component(props, context);\r\n } catch (error) {\r\n console.error('[Flight] Server component error:', error);\r\n return errorFallback(error as Error);\r\n }\r\n };\r\n}\r\n\r\n// ============================================================================\r\n// Not Found / Redirect Helpers\r\n// ============================================================================\r\n\r\n/**\r\n * Throw a not found error\r\n * @deprecated Use notFound from './context.js' instead\r\n */\r\nexport function notFound(): never {\r\n const error = new Error('Not Found');\r\n (error as Error & { __flight_not_found: boolean }).__flight_not_found = true;\r\n throw error;\r\n}\r\n\r\n/**\r\n * Check if error is not found\r\n * @deprecated Use isNotFoundError from './context.js' instead\r\n */\r\nexport function isNotFoundError(error: unknown): boolean {\r\n return error instanceof Error && (error as Error & { __flight_not_found?: boolean }).__flight_not_found === true;\r\n}\r\n\r\n/**\r\n * Server-side redirect\r\n * @deprecated Use redirect from './context.js' instead\r\n */\r\nexport function redirect(url: string, type: 'replace' | 'push' = 'replace'): never {\r\n const error = new Error(`Redirect: ${url}`);\r\n (error as Error & { __flight_redirect: { url: string; type: string } }).__flight_redirect = { url, type };\r\n throw error;\r\n}\r\n\r\n/**\r\n * Check if error is redirect\r\n * @deprecated Use isRedirectError from './context.js' instead\r\n */\r\nexport function isRedirectError(error: unknown): { url: string; type: string } | null {\r\n if (error instanceof Error && (error as Error & { __flight_redirect?: unknown }).__flight_redirect) {\r\n return (error as Error & { __flight_redirect: { url: string; type: string } }).__flight_redirect;\r\n }\r\n return null;\r\n}\r\n"]}
@@ -0,0 +1,25 @@
1
+ export { FlightConfig, FlightUserConfig } from './config/index.js';
2
+ export { Route, RouteMatch, RouteParams, Router, createRouter } from './router/index.js';
3
+ export { Cache, CacheAdapter, CacheEntry, CacheOptions, CacheStats, CreateCacheOptions, Serializer, cacheKey, cached, createCache, dedupe, jsonSerializer, memory } from './cache/index.js';
4
+ export { Middleware, MiddlewareContext, MiddlewareNext, createMiddlewareChain } from './middleware/index.js';
5
+ export { CustomHydrationTrigger, HydrateOptions, HydrationTrigger, IslandConfig, hydrateIslands, registerFlightIslandElement } from './islands/index.js';
6
+ export { BuiltInCondition, DEFAULT_BOT_PATTERNS, StreamingCondition, isBot, isSlowConnection, prefersNoStream, supportsStreaming } from './streaming/conditional.js';
7
+ export { BadRequestError, ErrorBoundaryOptions, FlightError, FlightErrorOptions, FlightErrorProps, ForbiddenError, InternalError, NotFoundError, ResetDetails, UnauthorizedError, clearError, createError, getError, getErrorStatusCode, isFlightError, isForbiddenError as isForbidden, isNotFoundError as isNotFound, isUnauthorizedError as isUnauthorized, showError } from './errors/index.js';
8
+ export { getEnvironment, isBrowser, isDevelopment, isProduction, isServer, isTest } from './utils/index.js';
9
+ import './render/index.js';
10
+ import './adapters/index.js';
11
+
12
+ /**
13
+ * Flight Framework - Core (Browser-Safe Exports)
14
+ *
15
+ * This entry point only exports modules that are safe to use in browser environments.
16
+ * Use this import when building for the client:
17
+ *
18
+ * import { ... } from '@flight-framework/core/client';
19
+ *
20
+ * Server-only modules (file-router, prerender, etc.) are NOT included.
21
+ */
22
+
23
+ declare const VERSION = "0.0.1";
24
+
25
+ export { VERSION };
package/dist/client.js ADDED
@@ -0,0 +1,16 @@
1
+ export { DEFAULT_BOT_PATTERNS, isBot, isSlowConnection, prefersNoStream, supportsStreaming } from './chunk-XOIYNY4I.js';
2
+ export { hydrateIslands, registerFlightIslandElement } from './chunk-WFAWAHJH.js';
3
+ export { createMiddlewareChain } from './chunk-OYF2OAKS.js';
4
+ import './chunk-IXMD5QH2.js';
5
+ export { BadRequestError, FlightError, ForbiddenError, InternalError, NotFoundError, UnauthorizedError, clearError, createError, getError, getErrorStatusCode, isFlightError, isForbiddenError as isForbidden, isNotFoundError as isNotFound, isUnauthorizedError as isUnauthorized, showError } from './chunk-FSJNOPYE.js';
6
+ import './chunk-PL37KFRJ.js';
7
+ export { getEnvironment, isBrowser, isDevelopment, isProduction, isServer, isTest } from './chunk-YHEVHRLH.js';
8
+ export { createRouter } from './chunk-GCQZ4FHI.js';
9
+ export { cacheKey, cached, createCache, dedupe, jsonSerializer, memory } from './chunk-R7SQAREQ.js';
10
+
11
+ // src/client.ts
12
+ var VERSION = "0.0.1";
13
+
14
+ export { VERSION };
15
+ //# sourceMappingURL=client.js.map
16
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client.ts"],"names":[],"mappings":";;;;;;;;;;;AAuGO,IAAM,OAAA,GAAU","file":"client.js","sourcesContent":["/**\r\n * Flight Framework - Core (Browser-Safe Exports)\r\n *\r\n * This entry point only exports modules that are safe to use in browser environments.\r\n * Use this import when building for the client:\r\n *\r\n * import { ... } from '@flight-framework/core/client';\r\n *\r\n * Server-only modules (file-router, prerender, etc.) are NOT included.\r\n */\r\n\r\n// Configuration (browser-safe parts only)\r\nexport { type FlightConfig, type FlightUserConfig } from './config/index.js';\r\n\r\n// Router (browser-safe)\r\nexport {\r\n createRouter,\r\n type Route,\r\n type RouteMatch,\r\n type Router,\r\n type RouteParams,\r\n} from './router/index.js';\r\n\r\n// Cache (browser-safe)\r\nexport {\r\n createCache,\r\n memory,\r\n cacheKey,\r\n cached,\r\n dedupe,\r\n jsonSerializer,\r\n type Cache,\r\n type CacheOptions,\r\n type CacheEntry,\r\n type CacheAdapter,\r\n type CacheStats,\r\n type Serializer,\r\n type CreateCacheOptions,\r\n} from './cache/index.js';\r\n\r\n// Middleware (browser-safe)\r\nexport {\r\n createMiddlewareChain,\r\n type Middleware,\r\n type MiddlewareContext,\r\n type MiddlewareNext,\r\n} from './middleware/index.js';\r\n\r\n// Islands (browser-safe hydration)\r\nexport {\r\n hydrateIslands,\r\n registerFlightIslandElement,\r\n type HydrationTrigger,\r\n type CustomHydrationTrigger,\r\n type IslandConfig,\r\n type HydrateOptions,\r\n} from './islands/index.js';\r\n\r\n// Streaming Conditional (browser-safe detection)\r\nexport {\r\n isBot,\r\n prefersNoStream,\r\n isSlowConnection,\r\n supportsStreaming,\r\n DEFAULT_BOT_PATTERNS,\r\n type StreamingCondition,\r\n type BuiltInCondition,\r\n} from './streaming/conditional.js';\r\n\r\n// Error Handling (browser-safe)\r\nexport {\r\n FlightError,\r\n BadRequestError,\r\n UnauthorizedError,\r\n ForbiddenError,\r\n NotFoundError,\r\n InternalError,\r\n createError,\r\n showError,\r\n clearError,\r\n getError,\r\n isFlightError,\r\n isNotFoundError as isNotFound,\r\n isForbiddenError as isForbidden,\r\n isUnauthorizedError as isUnauthorized,\r\n getErrorStatusCode,\r\n type FlightErrorOptions,\r\n type FlightErrorProps,\r\n type ResetDetails,\r\n type ErrorBoundaryOptions,\r\n} from './errors/index.js';\r\n\r\n// Environment Utilities (browser-safe)\r\nexport {\r\n isProduction,\r\n isDevelopment,\r\n isTest,\r\n isServer,\r\n isBrowser,\r\n getEnvironment,\r\n} from './utils/index.js';\r\n\r\n// Version\r\nexport const VERSION = '0.0.1';\r\n"]}
package/dist/index.js CHANGED
@@ -1,36 +1,36 @@
1
+ export { streamWithPriority, validateDependencies } from './chunk-WOEIJWGJ.js';
1
2
  export { MetricsAggregator, createHttpObserver, createInstrumentedStream, createLoggerObserver } from './chunk-6BDCTUQY.js';
2
- export { DEFAULT_BOT_PATTERNS, addStreamingHeaders, createConditionalStreamer, createStreamingResponse as createConditionalStreamingResponse, createStaticResponse, isBot, isSlowConnection, prefersNoStream, streamIf, supportsStreaming } from './chunk-XOIYNY4I.js';
3
3
  export { createHTMXStreamAdapter, createReactStreamAdapter, createSolidStreamAdapter, createStreamAdapter, createSvelteStreamAdapter, createVueStreamAdapter } from './chunk-MQQLYWZZ.js';
4
- export { createIslandRegistry, createPreactIslandAdapter, createReactIslandAdapter, createSolidIslandAdapter, createVueIslandAdapter, defineIsland, hydrateIslands, registerFlightIslandElement, registerIsland, renderIsland, renderIslands, setIslandAdapter } from './chunk-WFAWAHJH.js';
5
4
  export { DEFAULT_STREAMING_HINTS, createStreamingController, generateCacheKey, getStreamingCacheHeaders, hasStreamingConfig, isValidStreamingHints, loadRouteWithStreaming, resolveStreamingConfig, shouldStream } from './chunk-XSY5AAXT.js';
6
- export { streamWithPriority, validateDependencies } from './chunk-WOEIJWGJ.js';
7
- import './chunk-SUILH4ID.js';
8
- export { createServer } from './chunk-ROJFQCGV.js';
9
- export { defineConfig } from './chunk-IXMD5QH2.js';
10
- export { createFileRouter, loadRoutes, scanRoutes } from './chunk-3KRBRSRJ.js';
11
- export { RedirectError, redirect as actionRedirect, cookies, executeAction, executeFormAction, getAction, handleActionRequest, isRedirectError, parseFormData, registerAction } from './chunk-3QP3E7HS.js';
12
- export { createRouteContext, error, json, parseBody, redirect } from './chunk-W6D62JCI.js';
13
- export { createLazyContent, createStreamingResponse, createStreamingSSR, renderWithStreaming, streamParallel, streamSequential } from './chunk-RSVA2EYO.js';
14
5
  import './chunk-63SCEXD7.js';
6
+ import './chunk-Y22AMGTM.js';
7
+ import './chunk-TASAT7KB.js';
8
+ import './chunk-2F2QU6RC.js';
9
+ import './chunk-VPFMHGEV.js';
10
+ import './chunk-MDQNNIHH.js';
15
11
  export { createServerContext, isNotFoundError, isRedirectError as isRscRedirectError, notFound, redirect as rscRedirect } from './chunk-62C7LX2E.js';
16
12
  import './chunk-PVUMB632.js';
17
13
  import './chunk-P6WSBVDT.js';
18
14
  import './chunk-K2CQZPCG.js';
19
- export { composeComponents, createAsyncComponent, createClientBoundary, createRenderContext, deserializeProps, executeServerComponent, revalidatePath as rscRevalidatePath, revalidateTag as rscRevalidateTag, serializeProps, serverFetch, withErrorBoundary } from './chunk-3ZSSRE6M.js';
15
+ export { composeComponents, createAsyncComponent, createClientBoundary, createRenderContext, deserializeProps, executeServerComponent, revalidatePath as rscRevalidatePath, revalidateTag as rscRevalidateTag, serializeProps, serverFetch, withErrorBoundary } from './chunk-LNV47HGV.js';
20
16
  import './chunk-ZIE56LCA.js';
21
17
  export { detectBoundaryType, hasUseClientDirective, hasUseServerDirective } from './chunk-PDW5WCMW.js';
22
- import './chunk-Y22AMGTM.js';
23
- import './chunk-TASAT7KB.js';
24
- import './chunk-2F2QU6RC.js';
25
- import './chunk-VPFMHGEV.js';
26
- import './chunk-MDQNNIHH.js';
18
+ import './chunk-K5NYYNFS.js';
19
+ export { createServer } from './chunk-EGB7C73X.js';
20
+ export { createFileRouter, loadRoutes, scanRoutes } from './chunk-3KRBRSRJ.js';
21
+ export { RedirectError, redirect as actionRedirect, cookies, executeAction, executeFormAction, getAction, handleActionRequest, isRedirectError, parseFormData, registerAction } from './chunk-3QP3E7HS.js';
22
+ export { createRouteContext, error, json, parseBody, redirect } from './chunk-W6D62JCI.js';
23
+ export { createLazyContent, createStreamingResponse, createStreamingSSR, renderWithStreaming, streamParallel, streamSequential } from './chunk-RSVA2EYO.js';
24
+ export { DEFAULT_BOT_PATTERNS, addStreamingHeaders, createConditionalStreamer, createStreamingResponse as createConditionalStreamingResponse, createStaticResponse, isBot, isSlowConnection, prefersNoStream, streamIf, supportsStreaming } from './chunk-XOIYNY4I.js';
25
+ export { createIslandRegistry, createPreactIslandAdapter, createReactIslandAdapter, createSolidIslandAdapter, createVueIslandAdapter, defineIsland, hydrateIslands, registerFlightIslandElement, registerIsland, renderIsland, renderIslands, setIslandAdapter } from './chunk-WFAWAHJH.js';
26
+ export { createMiddlewareChain } from './chunk-OYF2OAKS.js';
27
+ export { defineConfig } from './chunk-IXMD5QH2.js';
27
28
  export { BadRequestError, FlightError, ForbiddenError, InternalError, NotFoundError, UnauthorizedError, clearError, createError, createErrorResponse, forbidden as createForbidden, notFound as createNotFound, unauthorized as createUnauthorized, getError, getErrorStatusCode, isFlightError, isForbiddenError as isForbidden, isNotFoundError as isNotFound, isUnauthorizedError as isUnauthorized, showError, wrapWithDigest } from './chunk-FSJNOPYE.js';
28
29
  import './chunk-PL37KFRJ.js';
29
30
  export { getEnvironment, isBrowser, isDevelopment, isProduction, isServer, isTest } from './chunk-YHEVHRLH.js';
30
31
  export { createRouter } from './chunk-GCQZ4FHI.js';
31
32
  import './chunk-ZVC3ZWLM.js';
32
33
  export { cacheKey, cached, createCache, dedupe, jsonSerializer, memory } from './chunk-R7SQAREQ.js';
33
- export { createMiddlewareChain } from './chunk-OYF2OAKS.js';
34
34
  import { promises } from 'fs';
35
35
  import { dirname, join } from 'path';
36
36
 
@@ -7,21 +7,226 @@ export { FlightResponseOptions, FlightStreamError, FlightStreamOptions, FlightSt
7
7
  export { ComponentFn, ElementTypeInfo, FlightRenderer, RenderOptions, RenderResult, UIAdapter, createRenderer, renderServerComponent, renderServerComponentStreaming } from './renderer.js';
8
8
  export { ReactConsumerOptions, ReactServerComponent, createReactAdapter, createReactConsumer, markAsClientComponent } from './adapters/react.js';
9
9
  export { ClientManifestEntry, FlightRSCPluginOptions, ServerManifestEntry, default as flightRSC } from './vite-plugin.js';
10
- export { ComponentType, ClientComponent as LegacyClientComponent, ServerComponent as LegacyServerComponent, RenderContext, composeComponents, createAsyncComponent, createClientBoundary, createRenderContext, deserializeProps, executeServerComponent, isNotFoundError as legacyIsNotFoundError, isRedirectError as legacyIsRedirectError, notFound as legacyNotFound, redirect as legacyRedirect, revalidatePath, revalidateTag, serializeProps, serverFetch, withErrorBoundary } from './legacy.js';
10
+ export { AsyncErrorBoundaryOptions, ComponentType, ClientComponent as LegacyClientComponent, ServerComponent as LegacyServerComponent, RenderContext, composeComponents, createAsyncComponent, createClientBoundary, createRenderContext, deserializeProps, executeServerComponent, isNotFoundError as legacyIsNotFoundError, isRedirectError as legacyIsRedirectError, notFound as legacyNotFound, redirect as legacyRedirect, revalidatePath, revalidateTag, serializeProps, serverFetch, withAsyncErrorBoundary, withErrorBoundary } from './legacy.js';
11
11
  import 'react';
12
12
  import 'vite';
13
13
 
14
+ /**
15
+ * @flight-framework/core - RSC Type Helpers
16
+ *
17
+ * Type utilities for async server components, loaders, and actions.
18
+ * These types provide better TypeScript inference and developer experience.
19
+ *
20
+ * @module @flight-framework/core/rsc/types
21
+ */
22
+
23
+ /**
24
+ * Type for async server components with data fetching.
25
+ *
26
+ * @example
27
+ * ```typescript
28
+ * const UserPage: AsyncServerComponent<{ id: string }> = async ({ id }, ctx) => {
29
+ * const user = await db.users.get(id);
30
+ * return h('div', null, text(user.name));
31
+ * };
32
+ * ```
33
+ */
34
+ type AsyncServerComponent<Props = Record<string, unknown>, Result = FlightElement> = (props: Props, ctx: ServerContext) => Promise<Result>;
35
+ /**
36
+ * Type for sync server components.
37
+ */
38
+ type SyncServerComponent<Props = Record<string, unknown>, Result = FlightElement> = (props: Props, ctx: ServerContext) => Result;
39
+ /**
40
+ * Union type for any server component (sync or async).
41
+ */
42
+ type ServerComponent<Props = Record<string, unknown>, Result = FlightElement> = AsyncServerComponent<Props, Result> | SyncServerComponent<Props, Result>;
43
+ /**
44
+ * Context provided to loader functions.
45
+ */
46
+ interface LoaderContext {
47
+ /** Route parameters extracted from the URL path */
48
+ params: Record<string, string>;
49
+ /** The incoming request object */
50
+ request: Request;
51
+ /** URL search parameters */
52
+ searchParams: URLSearchParams;
53
+ }
54
+ /**
55
+ * Type for loader functions.
56
+ *
57
+ * @example
58
+ * ```typescript
59
+ * export const loader: LoaderFn = async ({ params }) => {
60
+ * const user = await db.users.get(params.id);
61
+ * return { user };
62
+ * };
63
+ * ```
64
+ */
65
+ type LoaderFn<T = unknown> = (context: LoaderContext) => Promise<T> | T;
66
+ /**
67
+ * Infer the return type of a loader function.
68
+ *
69
+ * @example
70
+ * ```typescript
71
+ * export async function loader() {
72
+ * return { count: 42, items: ['a', 'b'] };
73
+ * }
74
+ *
75
+ * // Type is { count: number; items: string[] }
76
+ * type Data = InferLoaderData<typeof loader>;
77
+ * ```
78
+ */
79
+ type InferLoaderData<T extends (...args: never[]) => unknown> = Awaited<ReturnType<T>>;
80
+ /**
81
+ * Context provided to action functions.
82
+ */
83
+ interface ActionContext {
84
+ /** The incoming request object */
85
+ request: Request;
86
+ /** Route parameters extracted from the URL path */
87
+ params: Record<string, string>;
88
+ }
89
+ /**
90
+ * Type for action functions.
91
+ *
92
+ * @example
93
+ * ```typescript
94
+ * export const action: ActionFn = async ({ request }) => {
95
+ * const formData = await request.formData();
96
+ * await db.items.create({ name: formData.get('name') });
97
+ * return { success: true };
98
+ * };
99
+ * ```
100
+ */
101
+ type ActionFn<T = unknown> = (context: ActionContext) => Promise<T> | T;
102
+ /**
103
+ * Infer the return type of an action function.
104
+ *
105
+ * @example
106
+ * ```typescript
107
+ * export async function action() {
108
+ * return { success: true, id: '123' };
109
+ * }
110
+ *
111
+ * // Type is { success: boolean; id: string }
112
+ * type Result = InferActionReturn<typeof action>;
113
+ * ```
114
+ */
115
+ type InferActionReturn<T extends (...args: never[]) => unknown> = Awaited<ReturnType<T>>;
116
+ /**
117
+ * Extract props type from a component function.
118
+ *
119
+ * @example
120
+ * ```typescript
121
+ * async function UserCard(props: { name: string; age: number }) {
122
+ * return <div>{props.name}</div>;
123
+ * }
124
+ *
125
+ * // Type is { name: string; age: number }
126
+ * type Props = ComponentProps<typeof UserCard>;
127
+ * ```
128
+ */
129
+ type ComponentProps<T> = T extends (props: infer P, ...args: unknown[]) => unknown ? P : never;
130
+ /**
131
+ * Extract the return type of a component (after awaiting if async).
132
+ */
133
+ type ComponentReturn<T> = T extends (...args: unknown[]) => infer R ? Awaited<R> : never;
134
+ /**
135
+ * Props for page components with route parameters.
136
+ */
137
+ interface PageProps<Params extends Record<string, string> = Record<string, string>> {
138
+ /** Route parameters from dynamic segments */
139
+ params: Params;
140
+ /** URL search parameters */
141
+ searchParams?: Record<string, string | string[]>;
142
+ }
143
+ /**
144
+ * Type for page components.
145
+ *
146
+ * @example
147
+ * ```typescript
148
+ * const PostPage: PageComponent<{ slug: string }> = async ({ params }) => {
149
+ * const post = await getPost(params.slug);
150
+ * return <article>{post.title}</article>;
151
+ * };
152
+ * ```
153
+ */
154
+ type PageComponent<Params extends Record<string, string> = Record<string, string>> = AsyncServerComponent<PageProps<Params>>;
155
+ /**
156
+ * Props for layout components.
157
+ */
158
+ interface LayoutProps<Params extends Record<string, string> = Record<string, string>> {
159
+ /** Child components to render */
160
+ children: FlightElement;
161
+ /** Route parameters from dynamic segments */
162
+ params: Params;
163
+ }
164
+ /**
165
+ * Type for layout components.
166
+ */
167
+ type LayoutComponent<Params extends Record<string, string> = Record<string, string>> = ServerComponent<LayoutProps<Params>>;
168
+ /**
169
+ * Props for error boundary components.
170
+ */
171
+ interface ErrorProps {
172
+ /** The error that was thrown */
173
+ error: Error;
174
+ /** Function to reset the error boundary */
175
+ reset: () => void;
176
+ }
177
+ /**
178
+ * Type for error components.
179
+ */
180
+ type ErrorComponent = (props: ErrorProps) => FlightElement;
181
+ /**
182
+ * Type for loading components (shown during Suspense).
183
+ */
184
+ type LoadingComponent = () => FlightElement;
185
+ /**
186
+ * Generate metadata for a page.
187
+ */
188
+ type GenerateMetadata<Params extends Record<string, string> = Record<string, string>> = (props: PageProps<Params>) => Promise<Metadata> | Metadata;
189
+ /**
190
+ * Page metadata type.
191
+ */
192
+ interface Metadata {
193
+ title?: string | {
194
+ default: string;
195
+ template?: string;
196
+ };
197
+ description?: string;
198
+ keywords?: string[];
199
+ authors?: Array<{
200
+ name: string;
201
+ url?: string;
202
+ }>;
203
+ openGraph?: {
204
+ title?: string;
205
+ description?: string;
206
+ images?: string[];
207
+ url?: string;
208
+ type?: string;
209
+ };
210
+ twitter?: {
211
+ card?: 'summary' | 'summary_large_image' | 'player' | 'app';
212
+ title?: string;
213
+ description?: string;
214
+ images?: string[];
215
+ };
216
+ robots?: string | {
217
+ index?: boolean;
218
+ follow?: boolean;
219
+ };
220
+ }
221
+
14
222
  /**
15
223
  * Server Component function type
224
+ * @deprecated Use AsyncServerComponent or ServerComponent from './types.js'
16
225
  */
17
226
  type ServerComponentFn<P = unknown, R = FlightElement> = (props: P, ctx: ServerContext) => R | Promise<R>;
18
227
  /**
19
228
  * Server Action function type
20
229
  */
21
230
  type ServerActionFn<Args extends unknown[] = unknown[], R = unknown> = (...args: Args) => Promise<R>;
22
- /**
23
- * Props for a component
24
- */
25
- type ComponentProps<T> = T extends (props: infer P, ...args: unknown[]) => unknown ? P : never;
26
231
 
27
- export { type ComponentProps, FlightElement, type ServerActionFn, type ServerComponentFn, ServerContext };
232
+ export { type ActionContext, type ActionFn, type AsyncServerComponent, type ComponentProps, type ComponentReturn, type ErrorComponent, type ErrorProps, FlightElement, type GenerateMetadata, type InferActionReturn, type InferLoaderData, type LayoutComponent, type LayoutProps, type LoaderContext, type LoaderFn, type LoadingComponent, type Metadata, type PageComponent, type PageProps, type ServerActionFn, type ServerComponent, type ServerComponentFn, ServerContext, type SyncServerComponent };
package/dist/rsc/index.js CHANGED
@@ -1,15 +1,15 @@
1
1
  import '../chunk-63SCEXD7.js';
2
+ import '../chunk-Y22AMGTM.js';
3
+ export { createReactAdapter, createReactConsumer, markAsClientComponent } from '../chunk-TASAT7KB.js';
4
+ import '../chunk-2F2QU6RC.js';
5
+ import '../chunk-VPFMHGEV.js';
6
+ import '../chunk-MDQNNIHH.js';
2
7
  export { acceptsJson, createServerContext, deleteCookie, getHeader, getHeaders, getPreferredLanguage, getRedirectInfo, isAjaxRequest, isBotRequest, isMutationRequest, isNotFoundError, isRedirectError, notFound, redirect, setCacheControl, setCookie, supportsStreaming } from '../chunk-62C7LX2E.js';
3
8
  export { FlightStreamError, consumeFlightStream, createFlightResponse, createFlightStream, createFlightStreamFromArray, createHybridResponse, createStreamController, mergeFlightStreams, parseFlightStream, parseFlightStreamSync, prettyPrintChunks, transformFlightStream } from '../chunk-PVUMB632.js';
4
9
  export { FlightRenderer, createRenderer, renderServerComponent, renderServerComponentStreaming } from '../chunk-P6WSBVDT.js';
5
10
  export { FlightPayloadError, FlightSerializationError, clientRef, createActionChunk, createClientChunk, createErrorChunk, createHintChunk, createServerChunk, deserialize, fragment, generateChunkId, h, isFlightElement, resetChunkIdCounter, serialize, suspense, text, toFlightElement } from '../chunk-K2CQZPCG.js';
6
- export { composeComponents, createAsyncComponent, createClientBoundary, createRenderContext, deserializeProps, executeServerComponent, isNotFoundError as legacyIsNotFoundError, isRedirectError as legacyIsRedirectError, notFound as legacyNotFound, redirect as legacyRedirect, revalidatePath, revalidateTag, serializeProps, serverFetch, withErrorBoundary } from '../chunk-3ZSSRE6M.js';
11
+ export { composeComponents, createAsyncComponent, createClientBoundary, createRenderContext, deserializeProps, executeServerComponent, isNotFoundError as legacyIsNotFoundError, isRedirectError as legacyIsRedirectError, notFound as legacyNotFound, redirect as legacyRedirect, revalidatePath, revalidateTag, serializeProps, serverFetch, withAsyncErrorBoundary, withErrorBoundary } from '../chunk-LNV47HGV.js';
7
12
  export { flightRSC } from '../chunk-ZIE56LCA.js';
8
13
  export { BoundaryRegistry, CLIENT_REFERENCE, SERVER_REFERENCE, analyzeModule, createClientReference, createServerReference, detectAsyncComponents, detectBoundaryType, detectInlineServerActions, getReferenceId, globalRegistry, hasUseClientDirective, hasUseServerDirective, isClientReference, isServerReference, registerClientComponent, registerServerAction } from '../chunk-PDW5WCMW.js';
9
- import '../chunk-Y22AMGTM.js';
10
- export { createReactAdapter, createReactConsumer, markAsClientComponent } from '../chunk-TASAT7KB.js';
11
- import '../chunk-2F2QU6RC.js';
12
- import '../chunk-VPFMHGEV.js';
13
- import '../chunk-MDQNNIHH.js';
14
14
  //# sourceMappingURL=index.js.map
15
15
  //# sourceMappingURL=index.js.map
@@ -99,9 +99,33 @@ declare function createAsyncComponent<P, T>(fetcher: (props: P, context: RenderC
99
99
  * @deprecated Use Promise.all with async components
100
100
  */
101
101
  declare function composeComponents(...components: Array<() => Promise<string> | string>): () => Promise<string>;
102
+ /**
103
+ * Options for async error boundary
104
+ */
105
+ interface AsyncErrorBoundaryOptions<P, R> {
106
+ /** Fallback to render on error */
107
+ fallback: (error: Error, props: P) => R;
108
+ /** Optional callback when error occurs */
109
+ onError?: (error: Error, props: P, context: RenderContext) => void;
110
+ /** Whether to rethrow certain errors (e.g., redirects, not found) */
111
+ rethrowNavigation?: boolean;
112
+ }
113
+ /**
114
+ * Wrap an async server component with comprehensive error handling.
115
+ *
116
+ * @example
117
+ * ```typescript
118
+ * const SafeUserPage = withAsyncErrorBoundary(UserPage, {
119
+ * fallback: (error, props) => `<div>Error loading user ${props.id}</div>`,
120
+ * onError: (error, props) => console.error(`Failed to load user ${props.id}:`, error),
121
+ * rethrowNavigation: true,
122
+ * });
123
+ * ```
124
+ */
125
+ declare function withAsyncErrorBoundary<P, R = string>(component: (props: P, context: RenderContext) => Promise<R> | R, options: AsyncErrorBoundaryOptions<P, R>): (props: P, context: RenderContext) => Promise<R>;
102
126
  /**
103
127
  * Wrap a server component with error handling
104
- * @deprecated Use try/catch in async components
128
+ * @deprecated Use withAsyncErrorBoundary instead
105
129
  */
106
130
  declare function withErrorBoundary<P>(component: ServerComponent<P>, errorFallback: (error: Error) => string): ServerComponent<P>;
107
131
  /**
@@ -128,4 +152,4 @@ declare function isRedirectError(error: unknown): {
128
152
  type: string;
129
153
  } | null;
130
154
 
131
- export { type ClientComponent, type ComponentType, type RenderContext, type ServerComponent, composeComponents, createAsyncComponent, createClientBoundary, createRenderContext, deserializeProps, executeServerComponent, isNotFoundError, isRedirectError, notFound, redirect, revalidatePath, revalidateTag, serializeProps, serverFetch, withErrorBoundary };
155
+ export { type AsyncErrorBoundaryOptions, type ClientComponent, type ComponentType, type RenderContext, type ServerComponent, composeComponents, createAsyncComponent, createClientBoundary, createRenderContext, deserializeProps, executeServerComponent, isNotFoundError, isRedirectError, notFound, redirect, revalidatePath, revalidateTag, serializeProps, serverFetch, withAsyncErrorBoundary, withErrorBoundary };
@@ -1,3 +1,3 @@
1
- export { composeComponents, createAsyncComponent, createClientBoundary, createRenderContext, deserializeProps, executeServerComponent, isNotFoundError, isRedirectError, notFound, redirect, revalidatePath, revalidateTag, serializeProps, serverFetch, withErrorBoundary } from '../chunk-3ZSSRE6M.js';
1
+ export { composeComponents, createAsyncComponent, createClientBoundary, createRenderContext, deserializeProps, executeServerComponent, isNotFoundError, isRedirectError, notFound, redirect, revalidatePath, revalidateTag, serializeProps, serverFetch, withAsyncErrorBoundary, withErrorBoundary } from '../chunk-LNV47HGV.js';
2
2
  //# sourceMappingURL=legacy.js.map
3
3
  //# sourceMappingURL=legacy.js.map
@@ -1,6 +1,6 @@
1
- export { createServer, getRuntime, isFlightServer } from '../chunk-ROJFQCGV.js';
1
+ export { createServer, getRuntime, isFlightServer } from '../chunk-EGB7C73X.js';
2
+ import '../chunk-OYF2OAKS.js';
2
3
  import '../chunk-IXMD5QH2.js';
3
4
  import '../chunk-GCQZ4FHI.js';
4
- import '../chunk-OYF2OAKS.js';
5
5
  //# sourceMappingURL=index.js.map
6
6
  //# sourceMappingURL=index.js.map