@lolyjs/core 0.2.0-alpha.3 → 0.2.0-alpha.30

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.
Files changed (46) hide show
  1. package/README.md +1463 -761
  2. package/dist/{bootstrap-BiCQmSkx.d.mts → bootstrap-BfGTMUkj.d.mts} +19 -0
  3. package/dist/{bootstrap-BiCQmSkx.d.ts → bootstrap-BfGTMUkj.d.ts} +19 -0
  4. package/dist/cli.cjs +15701 -2448
  5. package/dist/cli.cjs.map +1 -1
  6. package/dist/cli.js +15704 -2441
  7. package/dist/cli.js.map +1 -1
  8. package/dist/index.cjs +17861 -4115
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.mts +323 -55
  11. package/dist/index.d.ts +323 -55
  12. package/dist/index.js +17982 -4227
  13. package/dist/index.js.map +1 -1
  14. package/dist/index.types-B9j4OQft.d.mts +222 -0
  15. package/dist/index.types-B9j4OQft.d.ts +222 -0
  16. package/dist/react/cache.cjs +107 -32
  17. package/dist/react/cache.cjs.map +1 -1
  18. package/dist/react/cache.d.mts +29 -21
  19. package/dist/react/cache.d.ts +29 -21
  20. package/dist/react/cache.js +107 -32
  21. package/dist/react/cache.js.map +1 -1
  22. package/dist/react/components.cjs +11 -12
  23. package/dist/react/components.cjs.map +1 -1
  24. package/dist/react/components.js +11 -12
  25. package/dist/react/components.js.map +1 -1
  26. package/dist/react/hooks.cjs +124 -74
  27. package/dist/react/hooks.cjs.map +1 -1
  28. package/dist/react/hooks.d.mts +6 -24
  29. package/dist/react/hooks.d.ts +6 -24
  30. package/dist/react/hooks.js +122 -71
  31. package/dist/react/hooks.js.map +1 -1
  32. package/dist/react/sockets.cjs +5 -6
  33. package/dist/react/sockets.cjs.map +1 -1
  34. package/dist/react/sockets.js +5 -6
  35. package/dist/react/sockets.js.map +1 -1
  36. package/dist/react/themes.cjs +61 -18
  37. package/dist/react/themes.cjs.map +1 -1
  38. package/dist/react/themes.js +63 -20
  39. package/dist/react/themes.js.map +1 -1
  40. package/dist/runtime.cjs +531 -104
  41. package/dist/runtime.cjs.map +1 -1
  42. package/dist/runtime.d.mts +2 -2
  43. package/dist/runtime.d.ts +2 -2
  44. package/dist/runtime.js +531 -104
  45. package/dist/runtime.js.map +1 -1
  46. package/package.json +56 -14
package/dist/index.d.mts CHANGED
@@ -1,7 +1,8 @@
1
1
  import http from 'http';
2
+ export { a as ApiContext, A as ApiMiddleware, G as GenerateStaticParams, L as LoaderResult, M as MetadataLoader, R as RouteMiddleware, S as ServerContext, b as ServerLoader, W as WssActions } from './index.types-B9j4OQft.mjs';
3
+ import { Socket } from 'socket.io';
2
4
  import { Request, Response } from 'express';
3
- import { Socket, Server } from 'socket.io';
4
- export { c as bootstrapClient } from './bootstrap-BiCQmSkx.mjs';
5
+ export { c as bootstrapClient } from './bootstrap-BfGTMUkj.mjs';
5
6
  import { ZodSchema, z } from 'zod';
6
7
  import * as express_rate_limit from 'express-rate-limit';
7
8
  import pino, { Logger as Logger$1 } from 'pino';
@@ -63,6 +64,7 @@ declare const DEFAULT_CONFIG: FrameworkConfig;
63
64
  *
64
65
  * @param projectRoot - Root directory of the project
65
66
  * @returns Framework configuration
67
+ * @throws ConfigValidationError if configuration is invalid
66
68
  */
67
69
  declare function loadConfig(projectRoot: string): FrameworkConfig;
68
70
  /**
@@ -119,77 +121,301 @@ interface InitServerData {
119
121
  server: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
120
122
  }
121
123
 
122
- type GenerateStaticParams = () => Array<Record<string, string>> | Promise<Array<Record<string, string>>>;
123
- interface ServerContext {
124
- req: Request;
125
- res: Response;
126
- params: Record<string, string>;
127
- pathname: string;
128
- locals: Record<string, any>;
124
+ /**
125
+ * Authentication context provided to the auth hook.
126
+ * Contains request metadata needed for authentication.
127
+ */
128
+ interface AuthContext {
129
+ /** Request headers */
130
+ req: {
131
+ headers: Record<string, string | string[] | undefined>;
132
+ ip?: string;
133
+ url?: string;
134
+ cookies?: Record<string, string>;
135
+ };
136
+ /** Socket.IO socket instance */
137
+ socket: Socket;
138
+ /** Namespace path (e.g., "/chat") */
139
+ namespace: string;
129
140
  }
141
+ /**
142
+ * Rate limit configuration for events.
143
+ */
144
+ interface RateLimitCfg {
145
+ /** Maximum events per second */
146
+ eventsPerSecond: number;
147
+ /** Burst capacity (optional, defaults to eventsPerSecond * 2) */
148
+ burst?: number;
149
+ }
150
+ /**
151
+ * Guard function type. Returns true to allow, false to block.
152
+ */
153
+ type GuardFn<TUser = any> = (ctx: {
154
+ user: TUser | null;
155
+ req: AuthContext["req"];
156
+ namespace: string;
157
+ }) => boolean | Promise<boolean>;
158
+ /**
159
+ * Authentication function type.
160
+ * Returns the authenticated user or null.
161
+ */
162
+ type AuthFn<TUser = any> = (ctx: AuthContext) => TUser | null | Promise<TUser | null>;
163
+ /**
164
+ * Schema validation adapter.
165
+ * Must support Zod-like interface: schema.parse(data) or schema.safeParse(data)
166
+ */
167
+ type Schema = {
168
+ parse?: (data: any) => any;
169
+ safeParse?: (data: any) => {
170
+ success: boolean;
171
+ error?: any;
172
+ data?: any;
173
+ };
174
+ } & Record<string, any>;
175
+ /**
176
+ * Realtime state store interface.
177
+ * Provides key-value storage, lists, sets, and atomic operations.
178
+ */
179
+ interface RealtimeStateStore {
180
+ /** Get a value by key */
181
+ get<T = any>(key: string): Promise<T | null>;
182
+ /** Set a value with optional TTL */
183
+ set<T = any>(key: string, value: T, opts?: {
184
+ ttlMs?: number;
185
+ }): Promise<void>;
186
+ /** Delete a key */
187
+ del(key: string): Promise<void>;
188
+ /** Increment a numeric value */
189
+ incr(key: string, by?: number): Promise<number>;
190
+ /** Decrement a numeric value */
191
+ decr(key: string, by?: number): Promise<number>;
192
+ /** Push to a list (left push) */
193
+ listPush(key: string, value: any, opts?: {
194
+ maxLen?: number;
195
+ }): Promise<void>;
196
+ /** Get range from a list */
197
+ listRange<T = any>(key: string, start: number, end: number): Promise<T[]>;
198
+ /** Add member to a set */
199
+ setAdd(key: string, member: string): Promise<void>;
200
+ /** Remove member from a set */
201
+ setRem(key: string, member: string): Promise<void>;
202
+ /** Get all members of a set */
203
+ setMembers(key: string): Promise<string[]>;
204
+ /** Optional: Acquire a distributed lock (returns unlock function) */
205
+ lock?(key: string, ttlMs: number): Promise<() => Promise<void>>;
206
+ }
207
+ /**
208
+ * Logger interface for realtime events.
209
+ */
210
+ interface RealtimeLogger {
211
+ debug(message: string, meta?: Record<string, any>): void;
212
+ info(message: string, meta?: Record<string, any>): void;
213
+ warn(message: string, meta?: Record<string, any>): void;
214
+ error(message: string, meta?: Record<string, any>): void;
215
+ }
216
+ /**
217
+ * Metrics interface (optional for v1).
218
+ */
219
+ interface RealtimeMetrics {
220
+ incrementCounter(name: string, labels?: Record<string, string>): void;
221
+ recordLatency(name: string, ms: number, labels?: Record<string, string>): void;
222
+ }
223
+ /**
224
+ * Extended WssActions with full RFC support.
225
+ */
130
226
  interface WssActions {
131
227
  /**
132
- * Emit an event to all clients in the namespace
228
+ * Emit to current socket only (reply)
229
+ */
230
+ reply(event: string, payload?: any): void;
231
+ /**
232
+ * Emit to all sockets in current namespace
233
+ */
234
+ emit(event: string, payload?: any): void;
235
+ /**
236
+ * Emit to everyone except current socket
133
237
  */
134
- emit: (event: string, ...args: any[]) => void;
238
+ broadcast(event: string, payload?: any, opts?: {
239
+ excludeSelf?: boolean;
240
+ }): void;
241
+ /**
242
+ * Join a room
243
+ */
244
+ join(room: string): Promise<void>;
245
+ /**
246
+ * Leave a room
247
+ */
248
+ leave(room: string): Promise<void>;
249
+ /**
250
+ * Emit to a specific room
251
+ */
252
+ toRoom(room: string): {
253
+ emit(event: string, payload?: any): void;
254
+ };
255
+ /**
256
+ * Emit to a specific user (by userId)
257
+ * Uses presence mapping to find user's sockets
258
+ */
259
+ toUser(userId: string): {
260
+ emit(event: string, payload?: any): void;
261
+ };
135
262
  /**
136
- * Emit an event to a specific socket by Socket.IO socket ID
263
+ * Emit error event (reserved event: __loly:error)
137
264
  */
138
- emitTo: (socketId: string, event: string, ...args: any[]) => void;
265
+ error(code: string, message: string, details?: any): void;
139
266
  /**
140
- * Emit an event to a specific client by custom clientId
141
- * Requires clientId to be stored in socket.data.clientId during connection
267
+ * Legacy: Emit to a specific socket by Socket.IO socket ID
268
+ * @deprecated Use toUser() for user targeting
142
269
  */
143
- emitToClient: (clientId: string, event: string, ...args: any[]) => void;
270
+ emitTo?: (socketId: string, event: string, ...args: any[]) => void;
144
271
  /**
145
- * Broadcast an event to all clients in the namespace except the sender
272
+ * Legacy: Emit to a specific client by custom clientId
273
+ * @deprecated Use toUser() for user targeting
146
274
  */
147
- broadcast: (event: string, ...args: any[]) => void;
275
+ emitToClient?: (clientId: string, event: string, ...args: any[]) => void;
148
276
  }
149
- interface WssContext {
150
- socket: Socket;
151
- io: Server;
277
+ /**
278
+ * Extended WssContext with full RFC support.
279
+ */
280
+ interface WssContext<TData = any, TUser = any> {
281
+ /** Request metadata */
282
+ req: {
283
+ headers: Record<string, string | string[] | undefined>;
284
+ ip?: string;
285
+ url?: string;
286
+ cookies?: Record<string, string>;
287
+ };
288
+ /** Authenticated user (set by auth hook) */
289
+ user: TUser | null;
290
+ /** Incoming payload for current event */
291
+ data: TData;
292
+ /** Route params (from dynamic routes) */
152
293
  params: Record<string, string>;
294
+ /** Route pathname */
153
295
  pathname: string;
154
- data?: any;
296
+ /** Framework utilities */
155
297
  actions: WssActions;
298
+ /** State store for shared state */
299
+ state: RealtimeStateStore;
300
+ /** Logger with WSS context */
301
+ log: RealtimeLogger;
302
+ /** Metrics (optional) */
303
+ metrics?: RealtimeMetrics;
156
304
  }
157
- type RouteMiddleware = (ctx: ServerContext & {
158
- theme?: string;
159
- }, next: () => Promise<void>) => Promise<void> | void;
160
- interface LoaderResult {
161
- props?: Record<string, any>;
162
- redirect?: {
163
- destination: string;
164
- permanent?: boolean;
165
- };
166
- notFound?: boolean;
167
- metadata?: PageMetadata | null;
168
- className?: string;
169
- theme?: string;
305
+ /**
306
+ * WSS event handler type.
307
+ */
308
+ type WssHandler<TData = any, TUser = any> = (ctx: WssContext<TData, TUser>) => void | Promise<void>;
309
+ /**
310
+ * WSS event definition.
311
+ * Can be a simple handler or an object with validation, guards, and rate limiting.
312
+ */
313
+ type WssEventDefinition<TData = any, TUser = any> = WssHandler<TData, TUser> | {
314
+ /** Schema for validation (Zod/Valibot compatible) */
315
+ schema?: Schema;
316
+ /** Per-event rate limit config */
317
+ rateLimit?: RateLimitCfg;
318
+ /** Guard function (auth/roles/permissions) */
319
+ guard?: GuardFn<TUser>;
320
+ /** Event handler */
321
+ handler: WssHandler<TData, TUser>;
322
+ };
323
+ /**
324
+ * WSS route definition (result of defineWssRoute).
325
+ */
326
+ interface WssRouteDefinition<TUser = any> {
327
+ /** Namespace (optional, inferred from folder name) */
328
+ namespace?: string;
329
+ /** Authentication hook */
330
+ auth?: AuthFn<TUser>;
331
+ /** Connection hook */
332
+ onConnect?: WssHandler<any, TUser>;
333
+ /** Disconnection hook */
334
+ onDisconnect?: (ctx: WssContext<any, TUser>, reason?: string) => void | Promise<void>;
335
+ /** Event handlers */
336
+ events: Record<string, WssEventDefinition<any, TUser>>;
170
337
  }
171
- type ServerLoader = (ctx: ServerContext) => Promise<LoaderResult>;
172
- interface PageMetadata {
173
- title?: string;
174
- description?: string;
175
- metaTags?: {
176
- name?: string;
177
- property?: string;
178
- content: string;
179
- }[];
338
+
339
+ /**
340
+ * Rewrite condition types.
341
+ * Used in the `has` array to conditionally apply rewrites.
342
+ */
343
+ type RewriteConditionType = "host" | "header" | "cookie" | "query";
344
+ /**
345
+ * Rewrite condition.
346
+ * Defines when a rewrite should be applied.
347
+ */
348
+ interface RewriteCondition {
349
+ type: RewriteConditionType;
350
+ key?: string;
351
+ value: string;
180
352
  }
181
- type MetadataLoader = (ctx: ServerContext) => PageMetadata | Promise<PageMetadata>;
182
- interface ApiContext {
183
- req: Request;
184
- res: Response;
185
- Response: (body?: any, status?: number) => Response<any, Record<string, any>>;
186
- NotFound: (body?: any) => Response<any, Record<string, any>>;
187
- params: Record<string, string>;
188
- pathname: string;
189
- locals: Record<string, any>;
353
+ /**
354
+ * Rewrite destination can be:
355
+ * - A string (static or with :param placeholders)
356
+ * - An async function that returns a string (for dynamic rewrites)
357
+ */
358
+ type RewriteDestination = string | ((params: Record<string, string>, req: Request) => Promise<string> | string);
359
+ /**
360
+ * Rewrite rule configuration.
361
+ * Defines how to rewrite a URL pattern.
362
+ */
363
+ interface RewriteRule {
364
+ source: string;
365
+ destination: RewriteDestination;
366
+ has?: RewriteCondition[];
190
367
  }
191
- type ApiMiddleware = (ctx: ApiContext, next: () => Promise<void>) => void | Promise<void>;
368
+ /**
369
+ * Rewrite configuration.
370
+ * Array of rewrite rules to apply in order.
371
+ */
372
+ type RewriteConfig = RewriteRule[];
192
373
 
374
+ /**
375
+ * Realtime/WebSocket configuration
376
+ */
377
+ interface RealtimeConfig {
378
+ /** Enable realtime features */
379
+ enabled?: boolean;
380
+ /** Socket.IO server settings */
381
+ path?: string;
382
+ transports?: ("websocket" | "polling")[];
383
+ pingIntervalMs?: number;
384
+ pingTimeoutMs?: number;
385
+ maxPayloadBytes?: number;
386
+ /** Security */
387
+ allowedOrigins?: string | string[];
388
+ cors?: {
389
+ credentials?: boolean;
390
+ allowedHeaders?: string[];
391
+ };
392
+ /** Scaling configuration */
393
+ scale?: {
394
+ mode?: "single" | "cluster";
395
+ adapter?: {
396
+ name: "redis";
397
+ url: string;
398
+ pubClientName?: string;
399
+ subClientName?: string;
400
+ };
401
+ stateStore?: {
402
+ name: "memory" | "redis";
403
+ url?: string;
404
+ prefix?: string;
405
+ };
406
+ };
407
+ /** Rate limiting */
408
+ limits?: {
409
+ connectionsPerIp?: number;
410
+ eventsPerSecond?: number;
411
+ burst?: number;
412
+ };
413
+ /** Logging */
414
+ logging?: {
415
+ level?: "debug" | "info" | "warn" | "error";
416
+ pretty?: boolean;
417
+ };
418
+ }
193
419
  interface ServerConfig {
194
420
  bodyLimit?: string;
195
421
  corsOrigin?: string | string[] | boolean | ((origin: string | undefined, callback: (err: Error | null, allow?: boolean) => void) => void);
@@ -207,6 +433,8 @@ interface ServerConfig {
207
433
  includeSubDomains?: boolean;
208
434
  };
209
435
  };
436
+ /** Realtime/WebSocket configuration */
437
+ realtime?: RealtimeConfig;
210
438
  }
211
439
 
212
440
  interface BuildAppOptions {
@@ -216,6 +444,43 @@ interface BuildAppOptions {
216
444
  }
217
445
  declare function buildApp(options?: BuildAppOptions): Promise<void>;
218
446
 
447
+ /**
448
+ * Defines a WebSocket route with authentication, hooks, and event handlers.
449
+ *
450
+ * This is the new, recommended way to define WSS routes. It provides:
451
+ * - Type safety
452
+ * - Built-in validation
453
+ * - Auth hooks
454
+ * - Connection/disconnection hooks
455
+ * - Per-event validation, guards, and rate limiting
456
+ *
457
+ * @example
458
+ * ```ts
459
+ * import { defineWssRoute } from "@lolyjs/core";
460
+ * import { z } from "zod";
461
+ *
462
+ * export default defineWssRoute({
463
+ * auth: async (ctx) => {
464
+ * const token = ctx.req.headers.authorization;
465
+ * return await verifyToken(token);
466
+ * },
467
+ * onConnect: (ctx) => {
468
+ * console.log("User connected:", ctx.user?.id);
469
+ * },
470
+ * events: {
471
+ * message: {
472
+ * schema: z.object({ text: z.string() }),
473
+ * guard: ({ user }) => !!user,
474
+ * handler: (ctx) => {
475
+ * ctx.actions.broadcast("message", ctx.data);
476
+ * }
477
+ * }
478
+ * }
479
+ * });
480
+ * ```
481
+ */
482
+ declare function defineWssRoute<TUser = any>(definition: WssRouteDefinition<TUser>): WssRouteDefinition<TUser>;
483
+
219
484
  declare function withCache(fn: any, options: any): any;
220
485
 
221
486
  /**
@@ -332,12 +597,15 @@ interface RateLimitConfig {
332
597
  legacyHeaders?: boolean;
333
598
  skipSuccessfulRequests?: boolean;
334
599
  skipFailedRequests?: boolean;
600
+ keyGenerator?: (req: any) => string;
601
+ skip?: (req: any) => boolean;
335
602
  }
336
603
  /**
337
604
  * Creates a rate limiter middleware with configurable options.
338
605
  *
339
606
  * @param config - Rate limiting configuration
340
607
  * @returns Express rate limit middleware
608
+ * @throws Error if configuration is invalid
341
609
  */
342
610
  declare function createRateLimiter(config?: RateLimitConfig): express_rate_limit.RateLimitRequestHandler;
343
611
  /**
@@ -442,4 +710,4 @@ declare function requestLoggerMiddleware(options?: {
442
710
  */
443
711
  declare function getRequestLogger(req: Request): Logger;
444
712
 
445
- export { type ApiContext, type ApiMiddleware, DEFAULT_CONFIG, type FrameworkConfig, type GenerateStaticParams, type InitServerData, type LoaderResult, type LogLevel, Logger, type LoggerContext, type LoggerOptions, type MetadataLoader, type RouteMiddleware, type ServerConfig, type ServerContext, type ServerLoader, ValidationError, type WssContext, buildApp, commonSchemas, createModuleLogger, createRateLimiter, defaultRateLimiter, generateRequestId, getAppDir, getBuildDir, getLogger, getRequestLogger, getStaticDir, lenientRateLimiter, loadConfig, logger, requestLoggerMiddleware, resetLogger, safeValidate, sanitizeObject, sanitizeParams, sanitizeQuery, sanitizeString, setLogger, startDevServer, startProdServer, strictRateLimiter, validate, withCache };
713
+ export { type AuthContext, type AuthFn, DEFAULT_CONFIG, type FrameworkConfig, type GuardFn, type InitServerData, type LogLevel, Logger, type LoggerContext, type LoggerOptions, type RateLimitCfg, type RealtimeConfig, type RealtimeLogger, type RealtimeMetrics, type RealtimeStateStore, type RewriteCondition, type RewriteConfig, type RewriteDestination, type RewriteRule, type Schema, type ServerConfig, ValidationError, type WssContext, type WssEventDefinition, type WssHandler, type WssRouteDefinition, buildApp, commonSchemas, createModuleLogger, createRateLimiter, defaultRateLimiter, defineWssRoute, generateRequestId, getAppDir, getBuildDir, getLogger, getRequestLogger, getStaticDir, lenientRateLimiter, loadConfig, logger, requestLoggerMiddleware, resetLogger, safeValidate, sanitizeObject, sanitizeParams, sanitizeQuery, sanitizeString, setLogger, startDevServer, startProdServer, strictRateLimiter, validate, withCache };