@flexireact/core 2.3.0 → 2.5.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,248 @@
1
+ /**
2
+ * FlexiReact Universal Edge Handler
3
+ *
4
+ * Single handler that works on all platforms:
5
+ * - Node.js (http.createServer)
6
+ * - Bun (Bun.serve)
7
+ * - Deno (Deno.serve)
8
+ * - Cloudflare Workers (fetch handler)
9
+ * - Vercel Edge (edge function)
10
+ */
11
+
12
+ import { FlexiRequest, FlexiResponse } from './fetch-polyfill.js';
13
+ import runtime, { detectRuntime } from './runtime.js';
14
+ import { cache, CacheOptions } from './cache.js';
15
+
16
+ // Handler context
17
+ export interface EdgeContext {
18
+ runtime: typeof runtime;
19
+ cache: typeof cache;
20
+ env: Record<string, string | undefined>;
21
+ waitUntil: (promise: Promise<any>) => void;
22
+ passThroughOnException?: () => void;
23
+ }
24
+
25
+ // Route handler type
26
+ export type EdgeHandler = (
27
+ request: FlexiRequest,
28
+ context: EdgeContext
29
+ ) => Promise<FlexiResponse> | FlexiResponse;
30
+
31
+ // Middleware type
32
+ export type EdgeMiddleware = (
33
+ request: FlexiRequest,
34
+ context: EdgeContext,
35
+ next: () => Promise<FlexiResponse>
36
+ ) => Promise<FlexiResponse> | FlexiResponse;
37
+
38
+ // App configuration
39
+ export interface EdgeAppConfig {
40
+ routes?: Map<string, EdgeHandler>;
41
+ middleware?: EdgeMiddleware[];
42
+ notFound?: EdgeHandler;
43
+ onError?: (error: Error, request: FlexiRequest) => FlexiResponse;
44
+ basePath?: string;
45
+ }
46
+
47
+ // Create universal edge app
48
+ export function createEdgeApp(config: EdgeAppConfig = {}) {
49
+ const {
50
+ routes = new Map(),
51
+ middleware = [],
52
+ notFound = () => FlexiResponse.notFound(),
53
+ onError = (error) => FlexiResponse.error(error.message),
54
+ basePath = ''
55
+ } = config;
56
+
57
+ // Main fetch handler (Web Standard)
58
+ async function handleRequest(
59
+ request: Request,
60
+ env: Record<string, any> = {},
61
+ executionContext?: { waitUntil: (p: Promise<any>) => void; passThroughOnException?: () => void }
62
+ ): Promise<Response> {
63
+ const flexiRequest = new FlexiRequest(request.url, {
64
+ method: request.method,
65
+ headers: request.headers,
66
+ body: request.body,
67
+ // @ts-ignore - duplex is needed for streaming
68
+ duplex: 'half'
69
+ });
70
+
71
+ const context: EdgeContext = {
72
+ runtime,
73
+ cache,
74
+ env: env as Record<string, string | undefined>,
75
+ waitUntil: executionContext?.waitUntil || (() => {}),
76
+ passThroughOnException: executionContext?.passThroughOnException
77
+ };
78
+
79
+ try {
80
+ // Run middleware chain
81
+ const response = await runMiddleware(flexiRequest, context, middleware, async () => {
82
+ // Match route
83
+ const pathname = flexiRequest.pathname.replace(basePath, '') || '/';
84
+
85
+ // Try exact match first
86
+ let handler = routes.get(pathname);
87
+
88
+ // Try pattern matching
89
+ if (!handler) {
90
+ for (const [pattern, h] of routes) {
91
+ if (matchRoute(pathname, pattern)) {
92
+ handler = h;
93
+ break;
94
+ }
95
+ }
96
+ }
97
+
98
+ if (handler) {
99
+ return await handler(flexiRequest, context);
100
+ }
101
+
102
+ return await notFound(flexiRequest, context);
103
+ });
104
+
105
+ return response;
106
+ } catch (error: any) {
107
+ console.error('Edge handler error:', error);
108
+ return onError(error, flexiRequest);
109
+ }
110
+ }
111
+
112
+ // Run middleware chain
113
+ async function runMiddleware(
114
+ request: FlexiRequest,
115
+ context: EdgeContext,
116
+ middlewares: EdgeMiddleware[],
117
+ finalHandler: () => Promise<FlexiResponse>
118
+ ): Promise<FlexiResponse> {
119
+ let index = 0;
120
+
121
+ async function next(): Promise<FlexiResponse> {
122
+ if (index >= middlewares.length) {
123
+ return finalHandler();
124
+ }
125
+ const mw = middlewares[index++];
126
+ return mw(request, context, next);
127
+ }
128
+
129
+ return next();
130
+ }
131
+
132
+ // Simple route matching
133
+ function matchRoute(pathname: string, pattern: string): boolean {
134
+ // Exact match
135
+ if (pathname === pattern) return true;
136
+
137
+ // Convert pattern to regex
138
+ const regexPattern = pattern
139
+ .replace(/\[\.\.\.(\w+)\]/g, '(?<$1>.+)') // [...slug] -> catch-all
140
+ .replace(/\[(\w+)\]/g, '(?<$1>[^/]+)'); // [id] -> dynamic segment
141
+
142
+ const regex = new RegExp(`^${regexPattern}$`);
143
+ return regex.test(pathname);
144
+ }
145
+
146
+ // Return platform-specific exports
147
+ return {
148
+ // Web Standard fetch handler (Cloudflare, Vercel Edge, Deno)
149
+ fetch: handleRequest,
150
+
151
+ // Cloudflare Workers
152
+ async scheduled(event: any, env: any, ctx: any) {
153
+ // Handle scheduled events
154
+ },
155
+
156
+ // Add route
157
+ route(path: string, handler: EdgeHandler) {
158
+ routes.set(path, handler);
159
+ return this;
160
+ },
161
+
162
+ // Add middleware
163
+ use(mw: EdgeMiddleware) {
164
+ middleware.push(mw);
165
+ return this;
166
+ },
167
+
168
+ // Node.js adapter
169
+ toNodeHandler() {
170
+ return async (req: any, res: any) => {
171
+ const url = `http://${req.headers.host}${req.url}`;
172
+ const headers = new Headers();
173
+ Object.entries(req.headers).forEach(([key, value]) => {
174
+ if (typeof value === 'string') headers.set(key, value);
175
+ });
176
+
177
+ const body = ['GET', 'HEAD'].includes(req.method) ? undefined : req;
178
+
179
+ const request = new Request(url, {
180
+ method: req.method,
181
+ headers,
182
+ body,
183
+ // @ts-ignore
184
+ duplex: 'half'
185
+ });
186
+
187
+ const response = await handleRequest(request, process.env);
188
+
189
+ res.writeHead(response.status, Object.fromEntries(response.headers));
190
+
191
+ if (response.body) {
192
+ const reader = response.body.getReader();
193
+ while (true) {
194
+ const { done, value } = await reader.read();
195
+ if (done) break;
196
+ res.write(value);
197
+ }
198
+ }
199
+ res.end();
200
+ };
201
+ },
202
+
203
+ // Bun adapter
204
+ toBunHandler() {
205
+ return {
206
+ fetch: handleRequest,
207
+ port: parseInt(process.env.PORT || '3000', 10)
208
+ };
209
+ },
210
+
211
+ // Deno adapter
212
+ toDenoHandler() {
213
+ return handleRequest;
214
+ },
215
+
216
+ // Start server based on runtime
217
+ async listen(port: number = 3000) {
218
+ const rt = detectRuntime();
219
+
220
+ switch (rt) {
221
+ case 'bun':
222
+ console.log(`🚀 FlexiReact Edge running on Bun at http://localhost:${port}`);
223
+ // @ts-ignore - Bun global
224
+ return Bun.serve({
225
+ port,
226
+ fetch: handleRequest
227
+ });
228
+
229
+ case 'deno':
230
+ console.log(`🚀 FlexiReact Edge running on Deno at http://localhost:${port}`);
231
+ // @ts-ignore - Deno global
232
+ return Deno.serve({ port }, handleRequest);
233
+
234
+ case 'node':
235
+ default:
236
+ const http = await import('http');
237
+ const server = http.createServer(this.toNodeHandler());
238
+ server.listen(port, () => {
239
+ console.log(`🚀 FlexiReact Edge running on Node.js at http://localhost:${port}`);
240
+ });
241
+ return server;
242
+ }
243
+ }
244
+ };
245
+ }
246
+
247
+ // Export default app creator
248
+ export default createEdgeApp;
@@ -0,0 +1,81 @@
1
+ /**
2
+ * FlexiReact Edge Runtime
3
+ *
4
+ * Universal edge runtime that works everywhere:
5
+ * - Node.js
6
+ * - Bun
7
+ * - Deno
8
+ * - Cloudflare Workers
9
+ * - Vercel Edge
10
+ * - Netlify Edge
11
+ */
12
+
13
+ // Runtime detection and capabilities
14
+ export {
15
+ detectRuntime,
16
+ getRuntimeCapabilities,
17
+ runtime as edgeRuntimeInfo,
18
+ type RuntimeEnvironment,
19
+ type RuntimeCapabilities
20
+ } from './runtime.js';
21
+
22
+ // Fetch polyfill with helpers
23
+ export {
24
+ FlexiRequest,
25
+ FlexiResponse,
26
+ FlexiHeaders,
27
+ Request,
28
+ Response,
29
+ Headers,
30
+ NativeRequest,
31
+ NativeResponse,
32
+ NativeHeaders
33
+ } from './fetch-polyfill.js';
34
+
35
+ // Universal handler
36
+ export {
37
+ createEdgeApp,
38
+ type EdgeContext,
39
+ type EdgeHandler,
40
+ type EdgeMiddleware,
41
+ type EdgeAppConfig
42
+ } from './handler.js';
43
+
44
+ // Smart caching
45
+ export {
46
+ cache as smartCache,
47
+ initCache,
48
+ cacheFunction,
49
+ unstable_cache,
50
+ revalidateTag,
51
+ revalidatePath,
52
+ getRequestCache,
53
+ reactCache,
54
+ type CacheEntry,
55
+ type CacheOptions,
56
+ type CacheStorage
57
+ } from './cache.js';
58
+
59
+ // Partial Prerendering
60
+ export {
61
+ dynamic,
62
+ staticComponent,
63
+ PPRBoundary,
64
+ PPRShell,
65
+ prerenderWithPPR,
66
+ streamPPR,
67
+ pprFetch,
68
+ PPRLoading,
69
+ getPPRStyles,
70
+ experimental_ppr,
71
+ type PPRConfig,
72
+ type PPRRenderResult,
73
+ type PPRPageConfig,
74
+ type GenerateStaticParams
75
+ } from './ppr.js';
76
+
77
+ // Default export
78
+ export { default as edgeRuntime } from './runtime.js';
79
+ export { default as edgeCache } from './cache.js';
80
+ export { default as edgePPR } from './ppr.js';
81
+ export { default as createApp } from './handler.js';
@@ -0,0 +1,264 @@
1
+ /**
2
+ * FlexiReact Partial Prerendering (PPR)
3
+ *
4
+ * Combines static shell with dynamic content:
5
+ * - Static parts are prerendered at build time
6
+ * - Dynamic parts stream in at request time
7
+ * - Best of both SSG and SSR
8
+ */
9
+
10
+ import React from 'react';
11
+ import { renderToString } from 'react-dom/server';
12
+ import { cache } from './cache.js';
13
+
14
+ // PPR configuration
15
+ export interface PPRConfig {
16
+ // Static shell cache duration
17
+ shellCacheTTL?: number;
18
+ // Dynamic content timeout
19
+ dynamicTimeout?: number;
20
+ // Fallback for dynamic parts
21
+ fallback?: React.ReactNode;
22
+ }
23
+
24
+ // Mark component as dynamic (not prerendered)
25
+ export function dynamic<T extends React.ComponentType<any>>(
26
+ Component: T,
27
+ options?: { fallback?: React.ReactNode }
28
+ ): T {
29
+ (Component as any).__flexi_dynamic = true;
30
+ (Component as any).__flexi_fallback = options?.fallback;
31
+ return Component;
32
+ }
33
+
34
+ // Mark component as static (prerendered)
35
+ export function staticComponent<T extends React.ComponentType<any>>(Component: T): T {
36
+ (Component as any).__flexi_static = true;
37
+ return Component;
38
+ }
39
+
40
+ // Suspense boundary for PPR
41
+ export interface SuspenseBoundaryProps {
42
+ children: React.ReactNode;
43
+ fallback?: React.ReactNode;
44
+ id?: string;
45
+ }
46
+
47
+ export function PPRBoundary({ children, fallback, id }: SuspenseBoundaryProps): React.ReactElement {
48
+ return React.createElement(
49
+ React.Suspense,
50
+ {
51
+ fallback: fallback || React.createElement('div', {
52
+ 'data-ppr-placeholder': id || 'loading',
53
+ className: 'ppr-loading'
54
+ }, '⏳')
55
+ },
56
+ children
57
+ );
58
+ }
59
+
60
+ // PPR Shell - static wrapper
61
+ export interface PPRShellProps {
62
+ children: React.ReactNode;
63
+ fallback?: React.ReactNode;
64
+ }
65
+
66
+ export function PPRShell({ children, fallback }: PPRShellProps): React.ReactElement {
67
+ return React.createElement(
68
+ 'div',
69
+ { 'data-ppr-shell': 'true' },
70
+ React.createElement(
71
+ React.Suspense,
72
+ { fallback: fallback || null },
73
+ children
74
+ )
75
+ );
76
+ }
77
+
78
+ // Prerender a page with PPR
79
+ export interface PPRRenderResult {
80
+ staticShell: string;
81
+ dynamicParts: Map<string, () => Promise<string>>;
82
+ fullHtml: string;
83
+ }
84
+
85
+ export async function prerenderWithPPR(
86
+ Component: React.ComponentType<any>,
87
+ props: any,
88
+ config: PPRConfig = {}
89
+ ): Promise<PPRRenderResult> {
90
+ const { shellCacheTTL = 3600 } = config;
91
+
92
+ // Track dynamic parts
93
+ const dynamicParts = new Map<string, () => Promise<string>>();
94
+ let dynamicCounter = 0;
95
+
96
+ // Create element
97
+ const element = React.createElement(Component, props);
98
+
99
+ // Render static shell (with placeholders for dynamic parts)
100
+ const staticShell = renderToString(element);
101
+
102
+ // Cache the static shell
103
+ const cacheKey = `ppr:${Component.name || 'page'}:${JSON.stringify(props)}`;
104
+ await cache.set(cacheKey, staticShell, { ttl: shellCacheTTL, tags: ['ppr'] });
105
+
106
+ return {
107
+ staticShell,
108
+ dynamicParts,
109
+ fullHtml: staticShell
110
+ };
111
+ }
112
+
113
+ // Stream PPR response
114
+ export async function streamPPR(
115
+ staticShell: string,
116
+ dynamicParts: Map<string, () => Promise<string>>,
117
+ options?: { onError?: (error: Error) => string }
118
+ ): Promise<ReadableStream<Uint8Array>> {
119
+ const encoder = new TextEncoder();
120
+
121
+ return new ReadableStream({
122
+ async start(controller) {
123
+ // Send static shell immediately
124
+ controller.enqueue(encoder.encode(staticShell));
125
+
126
+ // Stream dynamic parts as they resolve
127
+ const promises = Array.from(dynamicParts.entries()).map(async ([id, render]) => {
128
+ try {
129
+ const html = await render();
130
+ // Send script to replace placeholder
131
+ const script = `<script>
132
+ (function() {
133
+ var placeholder = document.querySelector('[data-ppr-placeholder="${id}"]');
134
+ if (placeholder) {
135
+ var temp = document.createElement('div');
136
+ temp.innerHTML = ${JSON.stringify(html)};
137
+ placeholder.replaceWith(...temp.childNodes);
138
+ }
139
+ })();
140
+ </script>`;
141
+ controller.enqueue(encoder.encode(script));
142
+ } catch (error: any) {
143
+ const errorHtml = options?.onError?.(error) || `<div class="ppr-error">Error loading content</div>`;
144
+ const script = `<script>
145
+ (function() {
146
+ var placeholder = document.querySelector('[data-ppr-placeholder="${id}"]');
147
+ if (placeholder) {
148
+ placeholder.innerHTML = ${JSON.stringify(errorHtml)};
149
+ }
150
+ })();
151
+ </script>`;
152
+ controller.enqueue(encoder.encode(script));
153
+ }
154
+ });
155
+
156
+ await Promise.all(promises);
157
+ controller.close();
158
+ }
159
+ });
160
+ }
161
+
162
+ // PPR-aware fetch wrapper
163
+ export function pprFetch(
164
+ input: RequestInfo | URL,
165
+ init?: RequestInit & {
166
+ cache?: 'force-cache' | 'no-store' | 'no-cache';
167
+ next?: { revalidate?: number; tags?: string[] };
168
+ }
169
+ ): Promise<Response> {
170
+ const cacheMode = init?.cache || 'force-cache';
171
+ const revalidate = init?.next?.revalidate;
172
+ const tags = init?.next?.tags || [];
173
+
174
+ // If no-store, always fetch fresh
175
+ if (cacheMode === 'no-store') {
176
+ return fetch(input, init);
177
+ }
178
+
179
+ // Create cache key
180
+ const url = typeof input === 'string' ? input : input.toString();
181
+ const cacheKey = `fetch:${url}:${JSON.stringify(init?.body || '')}`;
182
+
183
+ // Try cache first
184
+ return cache.wrap(
185
+ async () => {
186
+ const response = await fetch(input, init);
187
+ return response;
188
+ },
189
+ {
190
+ key: cacheKey,
191
+ ttl: revalidate || 3600,
192
+ tags
193
+ }
194
+ )();
195
+ }
196
+
197
+ // Export directive markers
198
+ export const experimental_ppr = true;
199
+
200
+ // Page config for PPR
201
+ export interface PPRPageConfig {
202
+ experimental_ppr?: boolean;
203
+ revalidate?: number | false;
204
+ dynamic?: 'auto' | 'force-dynamic' | 'force-static' | 'error';
205
+ dynamicParams?: boolean;
206
+ fetchCache?: 'auto' | 'default-cache' | 'only-cache' | 'force-cache' | 'force-no-store' | 'default-no-store' | 'only-no-store';
207
+ }
208
+
209
+ // Generate static params (for SSG with PPR)
210
+ export type GenerateStaticParams<T = any> = () => Promise<T[]> | T[];
211
+
212
+ // Default PPR loading component
213
+ export function PPRLoading(): React.ReactElement {
214
+ return React.createElement('div', {
215
+ className: 'ppr-loading animate-pulse',
216
+ style: {
217
+ background: 'linear-gradient(90deg, #1a1a1a 25%, #2a2a2a 50%, #1a1a1a 75%)',
218
+ backgroundSize: '200% 100%',
219
+ animation: 'shimmer 1.5s infinite',
220
+ borderRadius: '4px',
221
+ height: '1em',
222
+ width: '100%'
223
+ }
224
+ });
225
+ }
226
+
227
+ // Inject PPR styles
228
+ export function getPPRStyles(): string {
229
+ return `
230
+ @keyframes shimmer {
231
+ 0% { background-position: 200% 0; }
232
+ 100% { background-position: -200% 0; }
233
+ }
234
+
235
+ .ppr-loading {
236
+ background: linear-gradient(90deg, #1a1a1a 25%, #2a2a2a 50%, #1a1a1a 75%);
237
+ background-size: 200% 100%;
238
+ animation: shimmer 1.5s infinite;
239
+ border-radius: 4px;
240
+ min-height: 1em;
241
+ }
242
+
243
+ .ppr-error {
244
+ color: #ef4444;
245
+ padding: 1rem;
246
+ border: 1px solid #ef4444;
247
+ border-radius: 4px;
248
+ background: rgba(239, 68, 68, 0.1);
249
+ }
250
+ `;
251
+ }
252
+
253
+ export default {
254
+ dynamic,
255
+ staticComponent,
256
+ PPRBoundary,
257
+ PPRShell,
258
+ prerenderWithPPR,
259
+ streamPPR,
260
+ pprFetch,
261
+ PPRLoading,
262
+ getPPRStyles,
263
+ experimental_ppr
264
+ };