@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,344 @@
1
+ /**
2
+ * FlexiReact Universal Cache System
3
+ *
4
+ * Smart caching that works on:
5
+ * - Cloudflare Workers (Cache API + KV)
6
+ * - Vercel Edge (Edge Config + KV)
7
+ * - Deno (Deno KV)
8
+ * - Node.js/Bun (In-memory + File cache)
9
+ */
10
+
11
+ import { detectRuntime } from './runtime.js';
12
+
13
+ // Cache entry
14
+ export interface CacheEntry<T = any> {
15
+ value: T;
16
+ expires: number; // timestamp
17
+ stale?: number; // stale-while-revalidate timestamp
18
+ tags?: string[];
19
+ etag?: string;
20
+ }
21
+
22
+ // Cache options
23
+ export interface CacheOptions {
24
+ ttl?: number; // seconds
25
+ staleWhileRevalidate?: number; // seconds
26
+ tags?: string[];
27
+ key?: string;
28
+ revalidate?: number | false; // ISR-style revalidation
29
+ }
30
+
31
+ // Cache storage interface
32
+ export interface CacheStorage {
33
+ get<T>(key: string): Promise<CacheEntry<T> | null>;
34
+ set<T>(key: string, entry: CacheEntry<T>): Promise<void>;
35
+ delete(key: string): Promise<void>;
36
+ deleteByTag(tag: string): Promise<void>;
37
+ clear(): Promise<void>;
38
+ }
39
+
40
+ // In-memory cache (fallback)
41
+ class MemoryCache implements CacheStorage {
42
+ private store = new Map<string, CacheEntry>();
43
+ private tagIndex = new Map<string, Set<string>>();
44
+
45
+ async get<T>(key: string): Promise<CacheEntry<T> | null> {
46
+ const entry = this.store.get(key);
47
+ if (!entry) return null;
48
+
49
+ // Check expiration
50
+ if (entry.expires && entry.expires < Date.now()) {
51
+ // Check stale-while-revalidate
52
+ if (entry.stale && entry.stale > Date.now()) {
53
+ return { ...entry, value: entry.value as T };
54
+ }
55
+ this.store.delete(key);
56
+ return null;
57
+ }
58
+
59
+ return { ...entry, value: entry.value as T };
60
+ }
61
+
62
+ async set<T>(key: string, entry: CacheEntry<T>): Promise<void> {
63
+ this.store.set(key, entry);
64
+
65
+ // Index by tags
66
+ if (entry.tags) {
67
+ entry.tags.forEach(tag => {
68
+ if (!this.tagIndex.has(tag)) {
69
+ this.tagIndex.set(tag, new Set());
70
+ }
71
+ this.tagIndex.get(tag)!.add(key);
72
+ });
73
+ }
74
+ }
75
+
76
+ async delete(key: string): Promise<void> {
77
+ this.store.delete(key);
78
+ }
79
+
80
+ async deleteByTag(tag: string): Promise<void> {
81
+ const keys = this.tagIndex.get(tag);
82
+ if (keys) {
83
+ keys.forEach(key => this.store.delete(key));
84
+ this.tagIndex.delete(tag);
85
+ }
86
+ }
87
+
88
+ async clear(): Promise<void> {
89
+ this.store.clear();
90
+ this.tagIndex.clear();
91
+ }
92
+ }
93
+
94
+ // Cloudflare KV cache
95
+ class CloudflareCache implements CacheStorage {
96
+ private kv: any;
97
+
98
+ constructor(kv: any) {
99
+ this.kv = kv;
100
+ }
101
+
102
+ async get<T>(key: string): Promise<CacheEntry<T> | null> {
103
+ try {
104
+ const data = await this.kv.get(key, 'json');
105
+ if (!data) return null;
106
+
107
+ const entry = data as CacheEntry<T>;
108
+ if (entry.expires && entry.expires < Date.now()) {
109
+ if (entry.stale && entry.stale > Date.now()) {
110
+ return entry;
111
+ }
112
+ await this.kv.delete(key);
113
+ return null;
114
+ }
115
+
116
+ return entry;
117
+ } catch {
118
+ return null;
119
+ }
120
+ }
121
+
122
+ async set<T>(key: string, entry: CacheEntry<T>): Promise<void> {
123
+ const ttl = entry.expires ? Math.ceil((entry.expires - Date.now()) / 1000) : undefined;
124
+ await this.kv.put(key, JSON.stringify(entry), { expirationTtl: ttl });
125
+ }
126
+
127
+ async delete(key: string): Promise<void> {
128
+ await this.kv.delete(key);
129
+ }
130
+
131
+ async deleteByTag(tag: string): Promise<void> {
132
+ // KV doesn't support tag-based deletion natively
133
+ // Would need to maintain a tag index
134
+ console.warn('Tag-based deletion not fully supported in Cloudflare KV');
135
+ }
136
+
137
+ async clear(): Promise<void> {
138
+ // KV doesn't support clear
139
+ console.warn('Clear not supported in Cloudflare KV');
140
+ }
141
+ }
142
+
143
+ // Deno KV cache
144
+ class DenoKVCache implements CacheStorage {
145
+ private kv: any;
146
+
147
+ constructor() {
148
+ // @ts-ignore - Deno global
149
+ this.kv = Deno.openKv();
150
+ }
151
+
152
+ async get<T>(key: string): Promise<CacheEntry<T> | null> {
153
+ try {
154
+ const kv = await this.kv;
155
+ const result = await kv.get(['cache', key]);
156
+ if (!result.value) return null;
157
+
158
+ const entry = result.value as CacheEntry<T>;
159
+ if (entry.expires && entry.expires < Date.now()) {
160
+ if (entry.stale && entry.stale > Date.now()) {
161
+ return entry;
162
+ }
163
+ await kv.delete(['cache', key]);
164
+ return null;
165
+ }
166
+
167
+ return entry;
168
+ } catch {
169
+ return null;
170
+ }
171
+ }
172
+
173
+ async set<T>(key: string, entry: CacheEntry<T>): Promise<void> {
174
+ const kv = await this.kv;
175
+ await kv.set(['cache', key], entry);
176
+ }
177
+
178
+ async delete(key: string): Promise<void> {
179
+ const kv = await this.kv;
180
+ await kv.delete(['cache', key]);
181
+ }
182
+
183
+ async deleteByTag(tag: string): Promise<void> {
184
+ // Would need tag index
185
+ console.warn('Tag-based deletion requires tag index in Deno KV');
186
+ }
187
+
188
+ async clear(): Promise<void> {
189
+ // Would need to iterate all keys
190
+ console.warn('Clear requires iteration in Deno KV');
191
+ }
192
+ }
193
+
194
+ // Create cache based on runtime
195
+ function createCacheStorage(options?: { kv?: any }): CacheStorage {
196
+ const runtime = detectRuntime();
197
+
198
+ switch (runtime) {
199
+ case 'cloudflare':
200
+ if (options?.kv) {
201
+ return new CloudflareCache(options.kv);
202
+ }
203
+ return new MemoryCache();
204
+
205
+ case 'deno':
206
+ return new DenoKVCache();
207
+
208
+ case 'node':
209
+ case 'bun':
210
+ default:
211
+ return new MemoryCache();
212
+ }
213
+ }
214
+
215
+ // Main cache instance
216
+ let cacheStorage: CacheStorage = new MemoryCache();
217
+
218
+ // Initialize cache with platform-specific storage
219
+ export function initCache(options?: { kv?: any }): void {
220
+ cacheStorage = createCacheStorage(options);
221
+ }
222
+
223
+ // Cache function wrapper (like React cache)
224
+ export function cacheFunction<T extends (...args: any[]) => Promise<any>>(
225
+ fn: T,
226
+ options: CacheOptions = {}
227
+ ): T {
228
+ const { ttl = 60, staleWhileRevalidate = 0, tags = [] } = options;
229
+
230
+ return (async (...args: any[]) => {
231
+ const key = options.key || `fn:${fn.name}:${JSON.stringify(args)}`;
232
+
233
+ // Try cache first
234
+ const cached = await cacheStorage.get(key);
235
+ if (cached) {
236
+ // Check if stale and needs revalidation
237
+ if (cached.expires < Date.now() && cached.stale && cached.stale > Date.now()) {
238
+ // Return stale data, revalidate in background
239
+ queueMicrotask(async () => {
240
+ try {
241
+ const fresh = await fn(...args);
242
+ await cacheStorage.set(key, {
243
+ value: fresh,
244
+ expires: Date.now() + ttl * 1000,
245
+ stale: Date.now() + (ttl + staleWhileRevalidate) * 1000,
246
+ tags
247
+ });
248
+ } catch (e) {
249
+ console.error('Background revalidation failed:', e);
250
+ }
251
+ });
252
+ }
253
+ return cached.value;
254
+ }
255
+
256
+ // Execute function
257
+ const result = await fn(...args);
258
+
259
+ // Cache result
260
+ await cacheStorage.set(key, {
261
+ value: result,
262
+ expires: Date.now() + ttl * 1000,
263
+ stale: staleWhileRevalidate ? Date.now() + (ttl + staleWhileRevalidate) * 1000 : undefined,
264
+ tags
265
+ });
266
+
267
+ return result;
268
+ }) as T;
269
+ }
270
+
271
+ // Unstable cache (Next.js compatible API)
272
+ export function unstable_cache<T extends (...args: any[]) => Promise<any>>(
273
+ fn: T,
274
+ keyParts?: string[],
275
+ options?: { revalidate?: number | false; tags?: string[] }
276
+ ): T {
277
+ return cacheFunction(fn, {
278
+ key: keyParts?.join(':'),
279
+ ttl: typeof options?.revalidate === 'number' ? options.revalidate : 3600,
280
+ tags: options?.tags
281
+ });
282
+ }
283
+
284
+ // Revalidate by tag
285
+ export async function revalidateTag(tag: string): Promise<void> {
286
+ await cacheStorage.deleteByTag(tag);
287
+ }
288
+
289
+ // Revalidate by path
290
+ export async function revalidatePath(path: string): Promise<void> {
291
+ await cacheStorage.delete(`page:${path}`);
292
+ }
293
+
294
+ // Cache object for direct access
295
+ export const cache = {
296
+ get: <T>(key: string) => cacheStorage.get<T>(key),
297
+ set: <T>(key: string, value: T, options: CacheOptions = {}) => {
298
+ const { ttl = 60, staleWhileRevalidate = 0, tags = [] } = options;
299
+ return cacheStorage.set(key, {
300
+ value,
301
+ expires: Date.now() + ttl * 1000,
302
+ stale: staleWhileRevalidate ? Date.now() + (ttl + staleWhileRevalidate) * 1000 : undefined,
303
+ tags
304
+ });
305
+ },
306
+ delete: (key: string) => cacheStorage.delete(key),
307
+ deleteByTag: (tag: string) => cacheStorage.deleteByTag(tag),
308
+ clear: () => cacheStorage.clear(),
309
+
310
+ // Wrap function with caching
311
+ wrap: cacheFunction,
312
+
313
+ // Next.js compatible
314
+ unstable_cache,
315
+ revalidateTag,
316
+ revalidatePath
317
+ };
318
+
319
+ // Request-level cache (per-request deduplication)
320
+ const requestCache = new WeakMap<Request, Map<string, any>>();
321
+
322
+ export function getRequestCache(request: Request): Map<string, any> {
323
+ if (!requestCache.has(request)) {
324
+ requestCache.set(request, new Map());
325
+ }
326
+ return requestCache.get(request)!;
327
+ }
328
+
329
+ // React-style cache for request deduplication
330
+ export function reactCache<T extends (...args: any[]) => any>(fn: T): T {
331
+ const cache = new Map<string, any>();
332
+
333
+ return ((...args: any[]) => {
334
+ const key = JSON.stringify(args);
335
+ if (cache.has(key)) {
336
+ return cache.get(key);
337
+ }
338
+ const result = fn(...args);
339
+ cache.set(key, result);
340
+ return result;
341
+ }) as T;
342
+ }
343
+
344
+ export default cache;
@@ -0,0 +1,247 @@
1
+ /**
2
+ * Fetch API Polyfill for Universal Compatibility
3
+ *
4
+ * Ensures Request, Response, Headers work everywhere
5
+ */
6
+
7
+ // Use native Web APIs if available, otherwise polyfill
8
+ const globalFetch = globalThis.fetch;
9
+ const GlobalRequest = globalThis.Request;
10
+ const GlobalResponse = globalThis.Response;
11
+ const GlobalHeaders = globalThis.Headers;
12
+
13
+ // Extended Request with FlexiReact helpers
14
+ export class FlexiRequest extends GlobalRequest {
15
+ private _parsedUrl?: URL;
16
+ private _cookies?: Map<string, string>;
17
+
18
+ constructor(input: RequestInfo | URL, init?: RequestInit) {
19
+ super(input, init);
20
+ }
21
+
22
+ get pathname(): string {
23
+ if (!this._parsedUrl) {
24
+ this._parsedUrl = new URL(this.url);
25
+ }
26
+ return this._parsedUrl.pathname;
27
+ }
28
+
29
+ get searchParams(): URLSearchParams {
30
+ if (!this._parsedUrl) {
31
+ this._parsedUrl = new URL(this.url);
32
+ }
33
+ return this._parsedUrl.searchParams;
34
+ }
35
+
36
+ get cookies(): Map<string, string> {
37
+ if (!this._cookies) {
38
+ this._cookies = new Map();
39
+ const cookieHeader = this.headers.get('cookie');
40
+ if (cookieHeader) {
41
+ cookieHeader.split(';').forEach(cookie => {
42
+ const [name, ...rest] = cookie.trim().split('=');
43
+ if (name) {
44
+ this._cookies!.set(name, rest.join('='));
45
+ }
46
+ });
47
+ }
48
+ }
49
+ return this._cookies;
50
+ }
51
+
52
+ cookie(name: string): string | undefined {
53
+ return this.cookies.get(name);
54
+ }
55
+
56
+ // Parse JSON body
57
+ async jsonBody<T = any>(): Promise<T> {
58
+ return this.json();
59
+ }
60
+
61
+ // Parse form data
62
+ async formBody(): Promise<FormData> {
63
+ return this.formData();
64
+ }
65
+
66
+ // Get query param
67
+ query(name: string): string | null {
68
+ return this.searchParams.get(name);
69
+ }
70
+
71
+ // Get all query params
72
+ queryAll(name: string): string[] {
73
+ return this.searchParams.getAll(name);
74
+ }
75
+ }
76
+
77
+ // Extended Response with FlexiReact helpers
78
+ export class FlexiResponse extends GlobalResponse {
79
+ // Static helpers for common responses
80
+
81
+ static json(data: any, init?: ResponseInit): FlexiResponse {
82
+ const headers = new Headers(init?.headers);
83
+ headers.set('Content-Type', 'application/json');
84
+
85
+ return new FlexiResponse(JSON.stringify(data), {
86
+ ...init,
87
+ headers
88
+ });
89
+ }
90
+
91
+ static html(html: string, init?: ResponseInit): FlexiResponse {
92
+ const headers = new Headers(init?.headers);
93
+ headers.set('Content-Type', 'text/html; charset=utf-8');
94
+
95
+ return new FlexiResponse(html, {
96
+ ...init,
97
+ headers
98
+ });
99
+ }
100
+
101
+ static text(text: string, init?: ResponseInit): FlexiResponse {
102
+ const headers = new Headers(init?.headers);
103
+ headers.set('Content-Type', 'text/plain; charset=utf-8');
104
+
105
+ return new FlexiResponse(text, {
106
+ ...init,
107
+ headers
108
+ });
109
+ }
110
+
111
+ static redirect(url: string, status: 301 | 302 | 303 | 307 | 308 = 307): FlexiResponse {
112
+ return new FlexiResponse(null, {
113
+ status,
114
+ headers: { Location: url }
115
+ });
116
+ }
117
+
118
+ static notFound(message: string = 'Not Found'): FlexiResponse {
119
+ return new FlexiResponse(message, {
120
+ status: 404,
121
+ headers: { 'Content-Type': 'text/plain' }
122
+ });
123
+ }
124
+
125
+ static error(message: string = 'Internal Server Error', status: number = 500): FlexiResponse {
126
+ return new FlexiResponse(message, {
127
+ status,
128
+ headers: { 'Content-Type': 'text/plain' }
129
+ });
130
+ }
131
+
132
+ // Stream response
133
+ static stream(
134
+ stream: ReadableStream,
135
+ init?: ResponseInit
136
+ ): FlexiResponse {
137
+ return new FlexiResponse(stream, init);
138
+ }
139
+
140
+ // Set cookie helper
141
+ withCookie(
142
+ name: string,
143
+ value: string,
144
+ options: {
145
+ maxAge?: number;
146
+ expires?: Date;
147
+ path?: string;
148
+ domain?: string;
149
+ secure?: boolean;
150
+ httpOnly?: boolean;
151
+ sameSite?: 'Strict' | 'Lax' | 'None';
152
+ } = {}
153
+ ): FlexiResponse {
154
+ const parts = [`${name}=${encodeURIComponent(value)}`];
155
+
156
+ if (options.maxAge !== undefined) parts.push(`Max-Age=${options.maxAge}`);
157
+ if (options.expires) parts.push(`Expires=${options.expires.toUTCString()}`);
158
+ if (options.path) parts.push(`Path=${options.path}`);
159
+ if (options.domain) parts.push(`Domain=${options.domain}`);
160
+ if (options.secure) parts.push('Secure');
161
+ if (options.httpOnly) parts.push('HttpOnly');
162
+ if (options.sameSite) parts.push(`SameSite=${options.sameSite}`);
163
+
164
+ const headers = new Headers(this.headers);
165
+ headers.append('Set-Cookie', parts.join('; '));
166
+
167
+ return new FlexiResponse(this.body, {
168
+ status: this.status,
169
+ statusText: this.statusText,
170
+ headers
171
+ });
172
+ }
173
+
174
+ // Add headers helper
175
+ withHeaders(newHeaders: Record<string, string>): FlexiResponse {
176
+ const headers = new Headers(this.headers);
177
+ Object.entries(newHeaders).forEach(([key, value]) => {
178
+ headers.set(key, value);
179
+ });
180
+
181
+ return new FlexiResponse(this.body, {
182
+ status: this.status,
183
+ statusText: this.statusText,
184
+ headers
185
+ });
186
+ }
187
+ }
188
+
189
+ // Extended Headers
190
+ export class FlexiHeaders extends GlobalHeaders {
191
+ // Get bearer token
192
+ getBearerToken(): string | null {
193
+ const auth = this.get('Authorization');
194
+ if (auth?.startsWith('Bearer ')) {
195
+ return auth.slice(7);
196
+ }
197
+ return null;
198
+ }
199
+
200
+ // Get basic auth credentials
201
+ getBasicAuth(): { username: string; password: string } | null {
202
+ const auth = this.get('Authorization');
203
+ if (auth?.startsWith('Basic ')) {
204
+ try {
205
+ const decoded = atob(auth.slice(6));
206
+ const [username, password] = decoded.split(':');
207
+ return { username, password };
208
+ } catch {
209
+ return null;
210
+ }
211
+ }
212
+ return null;
213
+ }
214
+
215
+ // Check content type
216
+ isJson(): boolean {
217
+ return this.get('Content-Type')?.includes('application/json') ?? false;
218
+ }
219
+
220
+ isFormData(): boolean {
221
+ const ct = this.get('Content-Type') ?? '';
222
+ return ct.includes('multipart/form-data') || ct.includes('application/x-www-form-urlencoded');
223
+ }
224
+
225
+ isHtml(): boolean {
226
+ return this.get('Accept')?.includes('text/html') ?? false;
227
+ }
228
+ }
229
+
230
+ // Export both native and extended versions
231
+ export {
232
+ FlexiRequest as Request,
233
+ FlexiResponse as Response,
234
+ FlexiHeaders as Headers
235
+ };
236
+
237
+ // Also export native versions for compatibility
238
+ export const NativeRequest = GlobalRequest;
239
+ export const NativeResponse = GlobalResponse;
240
+ export const NativeHeaders = GlobalHeaders;
241
+
242
+ export default {
243
+ Request: FlexiRequest,
244
+ Response: FlexiResponse,
245
+ Headers: FlexiHeaders,
246
+ fetch: globalFetch
247
+ };