weifuwu 0.30.1 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,30 +1,17 @@
1
- import type { WebSocket, Context, Handler, Middleware, ErrorHandler } from '../types.ts';
2
- import { type IncomingMessage } from 'node:http';
3
- import type { Duplex } from 'node:stream';
1
+ import type { Context, Handler, Middleware, ErrorHandler } from '../types.ts';
4
2
  import { type Hub } from '../hub.ts';
3
+ import { type WebSocketHandler, type WsUpgradeHandler } from './ws.ts';
5
4
  declare module '../types.ts' {
6
5
  interface Context {
7
6
  ws: {
8
- /** Per-connection state object */
9
7
  state: Record<string, unknown>;
10
- /** Send JSON to this connection */
11
8
  json(data: unknown): void;
12
- /** Join a room */
13
9
  join(room: string): void;
14
- /** Leave a room */
15
10
  leave(room: string): void;
16
- /** Broadcast to a room */
17
11
  sendRoom(room: string, data: unknown): void;
18
12
  };
19
13
  }
20
14
  }
21
- export type WebSocketHandler = {
22
- open?: (ws: WebSocket, ctx: Context) => void | Promise<void>;
23
- message?: (ws: WebSocket, ctx: Context, data: string | Buffer) => void | Promise<void>;
24
- close?: (ws: WebSocket, ctx: Context) => void | Promise<void>;
25
- error?: (ws: WebSocket, ctx: Context, error: Error) => void | Promise<void>;
26
- };
27
- type WsUpgradeHandler = (req: IncomingMessage, socket: Duplex, head: Buffer) => void;
28
15
  export declare class Router<T extends Context = Context> {
29
16
  private root;
30
17
  private wsRoot;
@@ -33,63 +20,39 @@ export declare class Router<T extends Context = Context> {
33
20
  private _hasWildcard;
34
21
  private _hub?;
35
22
  private _wss?;
36
- /** Track which ctx fields have been injected so far (for dependency checking). */
37
23
  private _ctxFields;
38
24
  private get wss();
39
25
  private get hub();
40
- /** Inject a custom hub (e.g. with Redis for cross-process broadcast). */
41
26
  wsHub(hub: Hub): this;
42
- /** Global middleware — accumulates types into Router<T>. */
43
- use<Out extends Context>(mw: Middleware<Context, Out>): Router<T & Out>;
44
- /**
45
- * Mount a sub-router at the given path prefix.
46
- * All routes from the sub-router are registered with the prefix.
47
- *
48
- * ```ts
49
- * const admin = new Router()
50
- * admin.get('/dashboard', handler)
51
- * app.mount('/admin', admin) // → GET /admin/dashboard
52
- * ```
53
- */
27
+ use(mw: Middleware<Context, Context>): Router<T>;
54
28
  mount(path: string, router: Router<Context>): Router<T>;
55
- /**
56
- * Check a middleware's dependency metadata and emit warnings if
57
- * required fields haven't been injected yet.
58
- * Attach __meta to a middleware function:
59
- *
60
- * ```ts
61
- * mw.__meta = { injects: ['sql'], depends: ['session'] }
62
- * ```
63
- */
64
- private _checkMiddlewareMeta;
65
- get(path: string, ...args: [...Middleware<T, T>[], Handler<T> | Router<Context>]): Router<T>;
66
- post(path: string, ...args: [...Middleware<T, T>[], Handler<T> | Router<Context>]): Router<T>;
67
- put(path: string, ...args: [...Middleware<T, T>[], Handler<T> | Router<Context>]): Router<T>;
68
- delete(path: string, ...args: [...Middleware<T, T>[], Handler<T> | Router<Context>]): Router<T>;
69
- patch(path: string, ...args: [...Middleware<T, T>[], Handler<T> | Router<Context>]): Router<T>;
70
- head(path: string, ...args: [...Middleware<T, T>[], Handler<T> | Router<Context>]): Router<T>;
71
- options(path: string, ...args: [...Middleware<T, T>[], Handler<T> | Router<Context>]): Router<T>;
72
- all(path: string, ...args: [...Middleware<T, T>[], Handler<T> | Router<Context>]): Router<T>;
73
29
  onError(handler: ErrorHandler<T>): Router<T>;
74
- private _route;
75
- /** Internal route registration no type constraints (used by _mountRouter). */
76
- private _routeImpl;
77
- ws(path: string, ...args: [...Middleware<T, T>[], WebSocketHandler]): Router<T>;
30
+ get(path: string, ...rest: [...Middleware[], Handler | Router<Context>]): Router<T>;
31
+ post(path: string, ...rest: [...Middleware[], Handler | Router<Context>]): Router<T>;
32
+ put(path: string, ...rest: [...Middleware[], Handler | Router<Context>]): Router<T>;
33
+ delete(path: string, ...rest: [...Middleware[], Handler | Router<Context>]): Router<T>;
34
+ patch(path: string, ...rest: [...Middleware[], Handler | Router<Context>]): Router<T>;
35
+ head(path: string, ...rest: [...Middleware[], Handler | Router<Context>]): Router<T>;
36
+ options(path: string, ...rest: [...Middleware[], Handler | Router<Context>]): Router<T>;
37
+ all(path: string, ...rest: [...Middleware[], Handler | Router<Context>]): Router<T>;
38
+ ws(path: string, ...args: [...Middleware[], WebSocketHandler]): Router<T>;
78
39
  handler(): Handler<T>;
79
- /** Returns a human-readable list of all registered routes. Useful for debugging. */
80
- routes(): string[];
81
- private _collectRoutes;
82
- private _collectWsRoutes;
83
40
  websocketHandler(): WsUpgradeHandler;
41
+ routes(): string[];
42
+ private _route;
43
+ private _routeImpl;
84
44
  private _mountRouter;
85
45
  private _collect;
86
46
  private _collectWs;
87
47
  private splitPath;
48
+ private _collectRoutes;
49
+ private _collectWsRoutes;
88
50
  private matchTrie;
51
+ private _wildcardMatch;
52
+ private _resolveMatch;
89
53
  private matchWsTrie;
90
- private handleError;
91
- private _notFoundResponse;
92
54
  private handle;
55
+ private handleError;
93
56
  private runChain;
57
+ private _checkMiddlewareMeta;
94
58
  }
95
- export {};
@@ -29,8 +29,4 @@ export declare function createRequest(req: IncomingMessage, body: Buffer): [Requ
29
29
  export declare function sendResponse(res: ServerResponse, response: Response, opts?: {
30
30
  traceId?: string | null;
31
31
  }): Promise<void>;
32
- export declare function createTestServer(router: Router, options?: ServeOptions): Promise<{
33
- server: Server;
34
- url: string;
35
- }>;
36
32
  export declare function serve(router: Router, options?: ServeOptions): Server;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * WebSocket upgrade + connection lifecycle.
3
+ *
4
+ * Handles the HTTP-to-WS upgrade and per-connection state.
5
+ * Used internally by Router — not exported to end users.
6
+ */
7
+ import { WebSocketServer } from 'ws';
8
+ import type { WebSocket, Context, Handler, Middleware } from '../types.ts';
9
+ import type { IncomingMessage } from 'node:http';
10
+ import type { Duplex } from 'node:stream';
11
+ import { type Hub } from '../hub.ts';
12
+ /** WebSocket lifecycle handler. */
13
+ export type WebSocketHandler = {
14
+ open?: (ws: WebSocket, ctx: Context) => void | Promise<void>;
15
+ message?: (ws: WebSocket, ctx: Context, data: string | Buffer) => void | Promise<void>;
16
+ close?: (ws: WebSocket, ctx: Context) => void | Promise<void>;
17
+ error?: (ws: WebSocket, ctx: Context, error: Error) => void | Promise<void>;
18
+ };
19
+ export type WsUpgradeHandler = (req: IncomingMessage, socket: Duplex, head: Buffer) => void;
20
+ export declare function nodeReqHeadersToRecord(headers: IncomingMessage['headers']): Record<string, string>;
21
+ export declare function upgradeSocket(wss: WebSocketServer, req: IncomingMessage, socket: Duplex, head: Buffer, handler: WebSocketHandler, ctx: Context, hub: Hub): void;
22
+ type WsMatch = {
23
+ handler: WebSocketHandler;
24
+ middlewares: Middleware[];
25
+ params: Record<string, string>;
26
+ };
27
+ export declare function createWsUpgradeHandler(wss: WebSocketServer, hub: Hub, matchWsFn: (segments: string[]) => WsMatch | null, globalMws: Middleware[], runChainFn: (mws: Middleware[], h: Handler, req: Request, ctx: Context) => Promise<Response>): WsUpgradeHandler;
28
+ export {};
package/dist/index.d.ts CHANGED
@@ -2,21 +2,16 @@ export type { Context, Handler, Middleware, ErrorHandler, WsContext, WebSocket }
2
2
  export { HttpError } from './types.ts';
3
3
  export { currentTraceId, currentTrace, runWithTrace, traceElapsed, trace } from './core/trace.ts';
4
4
  export type { TraceContext, TraceInjected, TraceOptions } from './core/trace.ts';
5
- export { loadEnv, isDev, isProd, isBundled, getPublicEnv, env } from './core/env.ts';
6
- export { serve, createTestServer, DEFAULT_MAX_BODY } from './core/serve.ts';
5
+ export { serve, DEFAULT_MAX_BODY } from './core/serve.ts';
7
6
  export type { ServeOptions, Server } from './core/serve.ts';
8
7
  export { Router } from './core/router.ts';
9
- export type { WebSocketHandler } from './core/router.ts';
8
+ export type { WebSocketHandler } from './core/ws.ts';
10
9
  export { logger } from './core/logger.ts';
11
10
  export type { LoggerOptions } from './core/logger.ts';
12
11
  export { cors } from './middleware/cors.ts';
13
12
  export type { CORSOptions } from './middleware/cors.ts';
14
13
  export { serveStatic } from './middleware/static.ts';
15
14
  export type { ServeStaticOptions } from './middleware/static.ts';
16
- export { validate } from './middleware/validate.ts';
17
- export type { ValidationSchemas, ValidateModule } from './middleware/validate.ts';
18
- export { getCookies, setCookie, deleteCookie } from './core/cookie.ts';
19
- export type { CookieOptions } from './core/cookie.ts';
20
15
  export { upload } from './middleware/upload.ts';
21
16
  export type { UploadOptions, UploadedFile, UploadModule } from './middleware/upload.ts';
22
17
  export { rateLimit } from './middleware/rate-limit.ts';
@@ -25,12 +20,6 @@ export { compress } from './middleware/compress.ts';
25
20
  export type { CompressOptions } from './middleware/compress.ts';
26
21
  export { helmet } from './middleware/helmet.ts';
27
22
  export type { HelmetOptions } from './middleware/helmet.ts';
28
- export { requestId } from './middleware/request-id.ts';
29
- export type { RequestIdOptions, RequestIdModule } from './middleware/request-id.ts';
30
- export { createSSEStream, formatSSE, formatSSEData } from './core/sse.ts';
31
- export type { SSEEvent } from './core/sse.ts';
32
- export { testApp, TestApp, TestRequest, createTestDb, withTestDb } from './test/test-utils.ts';
33
- export type { TestResponse, TestDb } from './test/test-utils.ts';
34
23
  export { graphql } from './graphql.ts';
35
24
  export type { GraphQLOptions, GraphQLHandler } from './graphql.ts';
36
25
  export { postgres, MIGRATIONS_TABLE } from './postgres/index.ts';
@@ -41,14 +30,10 @@ export { createHub } from './hub.ts';
41
30
  export type { Hub, HubOptions } from './hub.ts';
42
31
  export { queue } from './queue/index.ts';
43
32
  export type { QueueOptions, QueueJob, Queue, QueueInjected } from './queue/types.ts';
44
- export { health } from './middleware/health.ts';
45
- export type { HealthOptions } from './middleware/health.ts';
46
- export { html, raw } from './core/html.ts';
47
- export { theme } from './middleware/theme.ts';
48
- export type { ThemeOptions, ThemeInjected, ThemeModule } from './middleware/theme.ts';
49
- export { i18n } from './middleware/i18n.ts';
50
- export type { I18nOptions, I18nInjected, I18nModule } from './middleware/i18n.ts';
51
- export { flash } from './middleware/flash.ts';
52
- export type { FlashOptions, FlashInjected, FlashModule } from './middleware/flash.ts';
53
- export { csrf } from './middleware/csrf.ts';
54
- export type { CsrfOptions, CsrfInjected, CsrfModule } from './middleware/csrf.ts';
33
+ export { react } from './react/index.ts';
34
+ export type { ReactOptions, RenderOptions, ReactInjected } from './react/types.ts';
35
+ export { useServerData, ServerDataContext } from './react/index.ts';
36
+ export { Link, useParams, useNavigate, useRevalidate, Form, useNavigation } from './react/index.ts';
37
+ export type { LinkProps, FormProps, NavigationState } from './react/index.ts';
38
+ export { ErrorBoundary } from './react/index.ts';
39
+ export type { ErrorBoundaryProps } from './react/index.ts';