@atproto/lex-server 0.0.0-spaces-alpha-20260818163953

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,"file":"drain-websocket.js","sourceRoot":"","sources":["../../src/lib/drain-websocket.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AAE3C;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAClC,MAAiB,EACjB,MAAmB,EACnB,EACE,aAAa,GAAG,OAAO,EAAE,SAAS;AAClC,YAAY,GAAG,MAAM,EAAE,QAAQ;EAChC,GAGG,EAAE;IAEN,IAAI,MAAM,CAAC,cAAc,GAAG,aAAa,EAAE,CAAC;QAC1C,wEAAwE;QACxE,4EAA4E;QAC5E,sEAAsE;QACtE,aAAa;QACb,OACE,MAAM,CAAC,UAAU,KAAK,CAAC;YACvB,MAAM,CAAC,cAAc,KAAK,CAAC;YAC3B,MAAM,CAAC,cAAc,GAAG,YAAY,EACpC,CAAC;YACD,MAAM,cAAc,CAAC,EAAE,EAAE,MAAM,CAAC,CAAA;QAClC,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import { abortableSleep } from './sleep.js'\n\n/**\n * Performs polling based backpressure management for a WebSocket connection. If\n * the amount of buffered data exceeds the specified high water mark, this\n * function will wait until the buffered amount drops below the low water mark\n * before resolving. This is useful for preventing memory issues when sending\n * large amounts of data over a WebSocket connection.\n */\nexport async function drainWebsocket(\n socket: WebSocket,\n signal: AbortSignal,\n {\n highWaterMark = 250_000, // 250 KB\n lowWaterMark = 50_000, // 50 KB\n }: {\n highWaterMark?: number\n lowWaterMark?: number\n } = {},\n): Promise<void> {\n if (socket.bufferedAmount > highWaterMark) {\n // Once we exceed the high water mark, we wait until the buffered amount\n // drops below the low water mark before allowing more data to be sent. This\n // creates a hysteresis effect that prevents rapid toggling around the\n // threshold.\n while (\n socket.readyState === 1 &&\n socket.bufferedAmount !== 0 &&\n socket.bufferedAmount > lowWaterMark\n ) {\n await abortableSleep(10, signal)\n }\n }\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export declare function abortableSleep(ms: number, signal: AbortSignal): Promise<void>;
2
+ //# sourceMappingURL=sleep.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sleep.d.ts","sourceRoot":"","sources":["../../src/lib/sleep.ts"],"names":[],"mappings":"AAAA,wBAAsB,cAAc,CAClC,EAAE,EAAE,MAAM,EACV,MAAM,EAAE,WAAW,GAClB,OAAO,CAAC,IAAI,CAAC,CAqBf"}
@@ -0,0 +1,19 @@
1
+ export async function abortableSleep(ms, signal) {
2
+ signal.throwIfAborted();
3
+ return new Promise((resolve, reject) => {
4
+ const cleanup = () => {
5
+ signal.removeEventListener('abort', onAbort);
6
+ clearTimeout(timeoutHandle);
7
+ };
8
+ const timeoutHandle = setTimeout(() => {
9
+ cleanup();
10
+ resolve();
11
+ }, ms);
12
+ const onAbort = () => {
13
+ cleanup();
14
+ reject(signal.reason);
15
+ };
16
+ signal.addEventListener('abort', onAbort);
17
+ });
18
+ }
19
+ //# sourceMappingURL=sleep.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sleep.js","sourceRoot":"","sources":["../../src/lib/sleep.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,KAAK,UAAU,cAAc,CAClC,EAAU,EACV,MAAmB;IAEnB,MAAM,CAAC,cAAc,EAAE,CAAA;IAEvB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,MAAM,OAAO,GAAG,GAAG,EAAE;YACnB,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAA;YAC5C,YAAY,CAAC,aAAa,CAAC,CAAA;QAC7B,CAAC,CAAA;QAED,MAAM,aAAa,GAAG,UAAU,CAAC,GAAG,EAAE;YACpC,OAAO,EAAE,CAAA;YACT,OAAO,EAAE,CAAA;QACX,CAAC,EAAE,EAAE,CAAC,CAAA;QAEN,MAAM,OAAO,GAAG,GAAG,EAAE;YACnB,OAAO,EAAE,CAAA;YACT,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAA;QACvB,CAAC,CAAA;QAED,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAA;IAC3C,CAAC,CAAC,CAAA;AACJ,CAAC","sourcesContent":["export async function abortableSleep(\n ms: number,\n signal: AbortSignal,\n): Promise<void> {\n signal.throwIfAborted()\n\n return new Promise((resolve, reject) => {\n const cleanup = () => {\n signal.removeEventListener('abort', onAbort)\n clearTimeout(timeoutHandle)\n }\n\n const timeoutHandle = setTimeout(() => {\n cleanup()\n resolve()\n }, ms)\n\n const onAbort = () => {\n cleanup()\n reject(signal.reason)\n }\n\n signal.addEventListener('abort', onAbort)\n })\n}\n"]}
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Type representing the value of a WWW-Authenticate HTTP header.
3
+ *
4
+ * Supports multiple authentication schemes, each with optional parameters.
5
+ * Parameters can be provided as a token68 string (for schemes like Bearer)
6
+ * or as key-value pairs.
7
+ *
8
+ * @see {@link https://datatracker.ietf.org/doc/html/rfc7235#section-4.1 | RFC 7235 Section 4.1}
9
+ *
10
+ * @example Bearer scheme with parameters
11
+ * ```typescript
12
+ * const auth: WWWAuthenticate = {
13
+ * Bearer: {
14
+ * realm: 'api.example.com',
15
+ * error: 'InvalidToken',
16
+ * error_description: 'The token has expired'
17
+ * }
18
+ * }
19
+ * // Formats to: Bearer realm="api.example.com", error="InvalidToken", error_description="The token has expired"
20
+ * ```
21
+ *
22
+ * @example Multiple schemes
23
+ * ```typescript
24
+ * const auth: WWWAuthenticate = {
25
+ * Bearer: { realm: 'api' },
26
+ * Basic: { realm: 'api' }
27
+ * }
28
+ * // Formats to: Bearer realm="api", Basic realm="api"
29
+ * ```
30
+ *
31
+ * @example Token68 value (no parameters)
32
+ * ```typescript
33
+ * const auth: WWWAuthenticate = {
34
+ * Bearer: 'base64encodedvalue=='
35
+ * }
36
+ * // Formats to: Bearer base64encodedvalue==
37
+ * ```
38
+ */
39
+ export type WWWAuthenticate = {
40
+ [authScheme in string]?: string | WWWAuthenticateParams | (string | WWWAuthenticateParams)[];
41
+ };
42
+ export type WWWAuthenticateParams = {
43
+ [authParam in string]?: string;
44
+ };
45
+ /**
46
+ * Formats a WWWAuthenticate object into an HTTP header string.
47
+ *
48
+ * Converts the structured authentication scheme and parameter data into
49
+ * the proper WWW-Authenticate header format per RFC 7235.
50
+ *
51
+ * @param wwwAuthenticate - The authentication schemes and parameters
52
+ * @returns Formatted header string ready for use in HTTP responses
53
+ *
54
+ * @example
55
+ * ```typescript
56
+ * const header = formatWWWAuthenticateHeader({
57
+ * Bearer: {
58
+ * realm: 'api.example.com',
59
+ * error: 'MissingToken'
60
+ * }
61
+ * })
62
+ * // Returns: 'Bearer realm="api.example.com", error="MissingToken"'
63
+ * ```
64
+ *
65
+ * @example Empty or undefined values
66
+ * ```typescript
67
+ * const header = formatWWWAuthenticateHeader({
68
+ * Bearer: { realm: 'api', error: undefined }
69
+ * })
70
+ * // Returns: 'Bearer realm="api"' (undefined values are omitted)
71
+ * ```
72
+ */
73
+ export declare function formatWWWAuthenticateHeader(wwwAuthenticate: WWWAuthenticate): string;
74
+ //# sourceMappingURL=www-authenticate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"www-authenticate.d.ts","sourceRoot":"","sources":["../../src/lib/www-authenticate.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,MAAM,MAAM,eAAe,GAAG;KAC3B,UAAU,IAAI,MAAM,CAAC,CAAC,EACnB,MAAM,GACN,qBAAqB,GACrB,CAAC,MAAM,GAAG,qBAAqB,CAAC,EAAE;CACvC,CAAA;AAED,MAAM,MAAM,qBAAqB,GAAG;KAAG,SAAS,IAAI,MAAM,CAAC,CAAC,EAAE,MAAM;CAAE,CAAA;AAEtE;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAgB,2BAA2B,CACzC,eAAe,EAAE,eAAe,GAC/B,MAAM,CAgBR"}
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Formats a WWWAuthenticate object into an HTTP header string.
3
+ *
4
+ * Converts the structured authentication scheme and parameter data into
5
+ * the proper WWW-Authenticate header format per RFC 7235.
6
+ *
7
+ * @param wwwAuthenticate - The authentication schemes and parameters
8
+ * @returns Formatted header string ready for use in HTTP responses
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * const header = formatWWWAuthenticateHeader({
13
+ * Bearer: {
14
+ * realm: 'api.example.com',
15
+ * error: 'MissingToken'
16
+ * }
17
+ * })
18
+ * // Returns: 'Bearer realm="api.example.com", error="MissingToken"'
19
+ * ```
20
+ *
21
+ * @example Empty or undefined values
22
+ * ```typescript
23
+ * const header = formatWWWAuthenticateHeader({
24
+ * Bearer: { realm: 'api', error: undefined }
25
+ * })
26
+ * // Returns: 'Bearer realm="api"' (undefined values are omitted)
27
+ * ```
28
+ */
29
+ export function formatWWWAuthenticateHeader(wwwAuthenticate) {
30
+ const challenges = [];
31
+ for (const [scheme, params] of Object.entries(wwwAuthenticate)) {
32
+ if (params == null)
33
+ continue;
34
+ if (typeof params === 'string') {
35
+ challenges.push(formatWWWAuthenticateChallenge(scheme, params));
36
+ }
37
+ else if (Array.isArray(params)) {
38
+ for (const p of params) {
39
+ challenges.push(formatWWWAuthenticateChallenge(scheme, p));
40
+ }
41
+ }
42
+ else {
43
+ challenges.push(formatWWWAuthenticateChallenge(scheme, params));
44
+ }
45
+ }
46
+ return challenges.join(', ');
47
+ }
48
+ function formatWWWAuthenticateChallenge(scheme, params) {
49
+ const paramsStr = typeof params === 'string' ? params : formatWWWAuthenticateParams(params);
50
+ return paramsStr?.length ? `${scheme} ${paramsStr}` : scheme;
51
+ }
52
+ function formatWWWAuthenticateParams(params) {
53
+ const parts = [];
54
+ for (const [name, val] of Object.entries(params)) {
55
+ if (val != null)
56
+ parts.push(`${name}=${JSON.stringify(val)}`);
57
+ }
58
+ return parts.join(', ');
59
+ }
60
+ //# sourceMappingURL=www-authenticate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"www-authenticate.js","sourceRoot":"","sources":["../../src/lib/www-authenticate.ts"],"names":[],"mappings":"AA+CA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,MAAM,UAAU,2BAA2B,CACzC,eAAgC;IAEhC,MAAM,UAAU,GAAa,EAAE,CAAA;IAC/B,KAAK,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,eAAe,CAAC,EAAE,CAAC;QAC/D,IAAI,MAAM,IAAI,IAAI;YAAE,SAAQ;QAE5B,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE,CAAC;YAC/B,UAAU,CAAC,IAAI,CAAC,8BAA8B,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAA;QACjE,CAAC;aAAM,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;YACjC,KAAK,MAAM,CAAC,IAAI,MAAM,EAAE,CAAC;gBACvB,UAAU,CAAC,IAAI,CAAC,8BAA8B,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,CAAA;YAC5D,CAAC;QACH,CAAC;aAAM,CAAC;YACN,UAAU,CAAC,IAAI,CAAC,8BAA8B,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAA;QACjE,CAAC;IACH,CAAC;IACD,OAAO,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;AAC9B,CAAC;AAED,SAAS,8BAA8B,CACrC,MAAc,EACd,MAAsC;IAEtC,MAAM,SAAS,GACb,OAAO,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,2BAA2B,CAAC,MAAM,CAAC,CAAA;IAC3E,OAAO,SAAS,EAAE,MAAM,CAAC,CAAC,CAAC,GAAG,MAAM,IAAI,SAAS,EAAE,CAAC,CAAC,CAAC,MAAM,CAAA;AAC9D,CAAC;AAED,SAAS,2BAA2B,CAAC,MAA6B;IAChE,MAAM,KAAK,GAAa,EAAE,CAAA;IAC1B,KAAK,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QACjD,IAAI,GAAG,IAAI,IAAI;YAAE,KAAK,CAAC,IAAI,CAAC,GAAG,IAAI,IAAI,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,EAAE,CAAC,CAAA;IAC/D,CAAC;IACD,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;AACzB,CAAC","sourcesContent":["/**\n * Type representing the value of a WWW-Authenticate HTTP header.\n *\n * Supports multiple authentication schemes, each with optional parameters.\n * Parameters can be provided as a token68 string (for schemes like Bearer)\n * or as key-value pairs.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc7235#section-4.1 | RFC 7235 Section 4.1}\n *\n * @example Bearer scheme with parameters\n * ```typescript\n * const auth: WWWAuthenticate = {\n * Bearer: {\n * realm: 'api.example.com',\n * error: 'InvalidToken',\n * error_description: 'The token has expired'\n * }\n * }\n * // Formats to: Bearer realm=\"api.example.com\", error=\"InvalidToken\", error_description=\"The token has expired\"\n * ```\n *\n * @example Multiple schemes\n * ```typescript\n * const auth: WWWAuthenticate = {\n * Bearer: { realm: 'api' },\n * Basic: { realm: 'api' }\n * }\n * // Formats to: Bearer realm=\"api\", Basic realm=\"api\"\n * ```\n *\n * @example Token68 value (no parameters)\n * ```typescript\n * const auth: WWWAuthenticate = {\n * Bearer: 'base64encodedvalue=='\n * }\n * // Formats to: Bearer base64encodedvalue==\n * ```\n */\nexport type WWWAuthenticate = {\n [authScheme in string]?:\n | string // token68\n | WWWAuthenticateParams\n | (string | WWWAuthenticateParams)[]\n}\n\nexport type WWWAuthenticateParams = { [authParam in string]?: string }\n\n/**\n * Formats a WWWAuthenticate object into an HTTP header string.\n *\n * Converts the structured authentication scheme and parameter data into\n * the proper WWW-Authenticate header format per RFC 7235.\n *\n * @param wwwAuthenticate - The authentication schemes and parameters\n * @returns Formatted header string ready for use in HTTP responses\n *\n * @example\n * ```typescript\n * const header = formatWWWAuthenticateHeader({\n * Bearer: {\n * realm: 'api.example.com',\n * error: 'MissingToken'\n * }\n * })\n * // Returns: 'Bearer realm=\"api.example.com\", error=\"MissingToken\"'\n * ```\n *\n * @example Empty or undefined values\n * ```typescript\n * const header = formatWWWAuthenticateHeader({\n * Bearer: { realm: 'api', error: undefined }\n * })\n * // Returns: 'Bearer realm=\"api\"' (undefined values are omitted)\n * ```\n */\nexport function formatWWWAuthenticateHeader(\n wwwAuthenticate: WWWAuthenticate,\n): string {\n const challenges: string[] = []\n for (const [scheme, params] of Object.entries(wwwAuthenticate)) {\n if (params == null) continue\n\n if (typeof params === 'string') {\n challenges.push(formatWWWAuthenticateChallenge(scheme, params))\n } else if (Array.isArray(params)) {\n for (const p of params) {\n challenges.push(formatWWWAuthenticateChallenge(scheme, p))\n }\n } else {\n challenges.push(formatWWWAuthenticateChallenge(scheme, params))\n }\n }\n return challenges.join(', ')\n}\n\nfunction formatWWWAuthenticateChallenge(\n scheme: string,\n params: string | WWWAuthenticateParams,\n): string {\n const paramsStr =\n typeof params === 'string' ? params : formatWWWAuthenticateParams(params)\n return paramsStr?.length ? `${scheme} ${paramsStr}` : scheme\n}\n\nfunction formatWWWAuthenticateParams(params: WWWAuthenticateParams): string {\n const parts: string[] = []\n for (const [name, val] of Object.entries(params)) {\n if (val != null) parts.push(`${name}=${JSON.stringify(val)}`)\n }\n return parts.join(', ')\n}\n"]}
@@ -0,0 +1,312 @@
1
+ import { type IncomingMessage, type Server as HttpServer, type ServerOptions, type ServerResponse } from 'node:http';
2
+ import type { ListenOptions } from 'node:net';
3
+ import type { FetchHandler } from './lex-router.js';
4
+ /**
5
+ * Upgrades an HTTP request to a WebSocket connection for Node.js.
6
+ *
7
+ * This function must be passed to the {@link LexRouter} constructor to enable
8
+ * subscription (WebSocket) support on Node.js. It creates a WebSocket instance
9
+ * and a placeholder response that signals the need for protocol upgrade.
10
+ *
11
+ * The actual upgrade is handled internally when the response is sent through
12
+ * {@link sendResponse}.
13
+ *
14
+ * @param request - The incoming HTTP request to upgrade
15
+ * @returns An object containing the WebSocket and upgrade response
16
+ * @throws {TypeError} If the request is not a valid WebSocket upgrade request
17
+ *
18
+ * @example
19
+ * ```typescript
20
+ * import { LexRouter } from '@atproto/lex-server'
21
+ * import { upgradeWebSocket } from '@atproto/lex-server/nodejs'
22
+ *
23
+ * // Pass to router for subscription support
24
+ * const router = new LexRouter({ upgradeWebSocket })
25
+ *
26
+ * // Now you can add subscription handlers
27
+ * router.add(subscribeRepos, async function* (ctx) {
28
+ * for await (const event of eventStream) {
29
+ * yield event
30
+ * }
31
+ * })
32
+ * ```
33
+ */
34
+ export declare function upgradeWebSocket(request: Request): {
35
+ response: Response;
36
+ socket: WebSocket;
37
+ };
38
+ /**
39
+ * Sends a fetch API Response through a Node.js ServerResponse.
40
+ *
41
+ * Handles both regular HTTP responses and WebSocket upgrades. For WebSocket
42
+ * upgrades (status 101), delegates to the WebSocket upgrade handler.
43
+ *
44
+ * This function is used internally by {@link toRequestListener} and
45
+ * {@link createServer}, but can be used directly for custom integrations.
46
+ *
47
+ * @param req - The Node.js IncomingMessage
48
+ * @param res - The Node.js ServerResponse to write to
49
+ * @param response - The fetch API Response to send
50
+ * @throws {TypeError} If headers have already been sent
51
+ *
52
+ * @example
53
+ * ```typescript
54
+ * import http from 'node:http'
55
+ * import { sendResponse } from '@atproto/lex-server/nodejs'
56
+ *
57
+ * const server = http.createServer(async (req, res) => {
58
+ * const response = new Response('Hello, World!', {
59
+ * headers: { 'Content-Type': 'text/plain' }
60
+ * })
61
+ * await sendResponse(req, res, response)
62
+ * })
63
+ * ```
64
+ */
65
+ export declare function sendResponse(req: IncomingMessage, res: ServerResponse, response: Response): Promise<void>;
66
+ /**
67
+ * Network address type for Node.js TCP connections.
68
+ *
69
+ * @example
70
+ * ```typescript
71
+ * const addr: NetAddr = {
72
+ * transport: 'tcp',
73
+ * hostname: '192.168.1.100',
74
+ * port: 54321
75
+ * }
76
+ * ```
77
+ */
78
+ export type NetAddr = {
79
+ /** Always 'tcp' for Node.js HTTP connections. */
80
+ transport: 'tcp';
81
+ /** The IP address of the remote client. */
82
+ hostname: string;
83
+ /** The port number of the remote client. */
84
+ port: number;
85
+ };
86
+ /**
87
+ * Connection metadata for Node.js HTTP requests.
88
+ *
89
+ * Provides information about the client connection, including the remote
90
+ * address and a promise that resolves when the connection is fully closed
91
+ * (including WebSocket connections).
92
+ */
93
+ export type NodeConnectionInfo = {
94
+ /** Promise that resolves when the connection is fully closed. */
95
+ completed: Promise<void>;
96
+ /** The remote address of the client, if available. */
97
+ remoteAddr: NetAddr | undefined;
98
+ };
99
+ /**
100
+ * Interface for objects that can handle fetch-style requests.
101
+ *
102
+ * Used by {@link createServer} and {@link serve} to accept either
103
+ * a fetch handler function or an object with a `fetch` method
104
+ * (like {@link LexRouter}).
105
+ */
106
+ export interface HandlerObject {
107
+ /** The fetch handler method. */
108
+ fetch: FetchHandler;
109
+ }
110
+ /**
111
+ * Converts a fetch-style handler to a Node.js request listener.
112
+ *
113
+ * The returned listener can be used with Node.js HTTP servers directly,
114
+ * or as middleware in frameworks like Express (supports the `next` callback).
115
+ *
116
+ * @typeParam Request - The request class type (default: IncomingMessage)
117
+ * @typeParam Response - The response class type (default: ServerResponse)
118
+ * @param fetchHandler - The fetch-style handler function
119
+ * @returns A Node.js RequestListener compatible with http.createServer
120
+ *
121
+ * @example Using as Express middleware
122
+ * ```typescript
123
+ * import express from 'express'
124
+ * import { toRequestListener } from '@atproto/lex-server/nodejs'
125
+ * import { LexRouter } from '@atproto/lex-server'
126
+ *
127
+ * const router = new LexRouter()
128
+ * // Register handlers...
129
+ *
130
+ * const app = express()
131
+ *
132
+ * // Mount the XRPC router
133
+ * app.use(toRequestListener(router.fetch))
134
+ * ```
135
+ */
136
+ export declare function toRequestListener<Request extends typeof IncomingMessage = typeof IncomingMessage, Response extends typeof ServerResponse<InstanceType<Request>> = typeof ServerResponse>(fetchHandler: FetchHandler): (req: InstanceType<Request>, res: InstanceType<Response> & {
137
+ req: InstanceType<Request>;
138
+ }, next?: (err?: unknown) => void) => void;
139
+ /**
140
+ * Options for creating an XRPC server.
141
+ *
142
+ * Extends Node.js {@link ServerOptions} with additional options for graceful shutdown.
143
+ */
144
+ export type CreateServerOptions<Request extends typeof IncomingMessage = typeof IncomingMessage, Response extends typeof ServerResponse<InstanceType<Request>> = typeof ServerResponse> = ServerOptions<Request, Response> & {
145
+ /**
146
+ * Timeout in milliseconds for graceful termination.
147
+ *
148
+ * When `terminate()` is called, the server will wait up to this duration
149
+ * for active connections to complete before forcibly closing them.
150
+ */
151
+ gracefulTerminationTimeout?: number;
152
+ };
153
+ /**
154
+ * Extended HTTP server with graceful shutdown support.
155
+ *
156
+ * Extends the standard Node.js HttpServer with a `terminate()` method
157
+ * for graceful shutdown and implements `AsyncDisposable` for use with
158
+ * `await using`.
159
+ *
160
+ * @typeParam Request - The request class type
161
+ * @typeParam Response - The response class type
162
+ *
163
+ * @example Graceful shutdown
164
+ * ```typescript
165
+ * const server = createServer(router)
166
+ * server.listen(3000)
167
+ *
168
+ * process.on('SIGTERM', async () => {
169
+ * console.log('Shutting down...')
170
+ * await server.terminate()
171
+ * console.log('Server stopped')
172
+ * })
173
+ * ```
174
+ *
175
+ * @example Using with await using
176
+ * ```typescript
177
+ * await using server = await serve(router, { port: 3000 })
178
+ * // Server will be automatically terminated when scope exits
179
+ * ```
180
+ */
181
+ export interface Server<Request extends typeof IncomingMessage = typeof IncomingMessage, Response extends typeof ServerResponse<InstanceType<Request>> = typeof ServerResponse> extends HttpServer<Request, Response>, AsyncDisposable {
182
+ /**
183
+ * Gracefully terminates the server.
184
+ *
185
+ * Stops accepting new connections and waits for active connections
186
+ * to complete (up to `gracefulTerminationTimeout`).
187
+ *
188
+ * @returns Promise that resolves when the server is fully stopped
189
+ */
190
+ terminate(): Promise<void>;
191
+ [Symbol.asyncDispose](): Promise<void>;
192
+ }
193
+ /**
194
+ * Creates an HTTP server configured for XRPC request handling.
195
+ *
196
+ * The server includes graceful shutdown support and can be used with
197
+ * either a fetch handler function or an object with a `fetch` method
198
+ * (like {@link LexRouter}).
199
+ *
200
+ * Note: This creates the server but does not start listening. Call
201
+ * `server.listen()` to start the server, or use {@link serve} for
202
+ * a combined create-and-listen operation.
203
+ *
204
+ * @typeParam Request - The request class type
205
+ * @typeParam Response - The response class type
206
+ * @param handler - A fetch handler or object with fetch method
207
+ * @param options - Server configuration options
208
+ * @returns An HTTP server with graceful shutdown support
209
+ *
210
+ * @example Basic usage
211
+ * ```typescript
212
+ * import { LexRouter } from '@atproto/lex-server'
213
+ * import { createServer, upgradeWebSocket } from '@atproto/lex-server/nodejs'
214
+ *
215
+ * const router = new LexRouter({ upgradeWebSocket })
216
+ * router.add(myMethod, myHandler)
217
+ *
218
+ * const server = createServer(router)
219
+ * server.listen(3000, () => {
220
+ * console.log('Server listening on port 3000')
221
+ * })
222
+ * ```
223
+ *
224
+ * @example With graceful termination timeout
225
+ * ```typescript
226
+ * const server = createServer(router, {
227
+ * gracefulTerminationTimeout: 10000 // 10 seconds
228
+ * })
229
+ * ```
230
+ */
231
+ export declare function createServer<Request extends typeof IncomingMessage = typeof IncomingMessage, Response extends typeof ServerResponse<InstanceType<Request>> = typeof ServerResponse>(handler: FetchHandler | HandlerObject, options?: CreateServerOptions<Request, Response>): Server<Request, Response>;
232
+ /**
233
+ * Combined options for creating and starting an XRPC server.
234
+ *
235
+ * Includes both server creation options and network listen options.
236
+ *
237
+ * @typeParam Request - The request class type
238
+ * @typeParam Response - The response class type
239
+ *
240
+ * @example
241
+ * ```typescript
242
+ * const options: StartServerOptions = {
243
+ * port: 3000,
244
+ * host: '0.0.0.0',
245
+ * gracefulTerminationTimeout: 10000
246
+ * }
247
+ * ```
248
+ */
249
+ export type StartServerOptions<Request extends typeof IncomingMessage = typeof IncomingMessage, Response extends typeof ServerResponse<InstanceType<Request>> = typeof ServerResponse> = ListenOptions & CreateServerOptions<Request, Response>;
250
+ /**
251
+ * Creates and starts an HTTP server, returning when it's ready to accept connections.
252
+ *
253
+ * This is a convenience function that combines {@link createServer} and `server.listen()`
254
+ * into a single async operation. The returned promise resolves once the server
255
+ * is actively listening.
256
+ *
257
+ * @typeParam Request - The request class type
258
+ * @typeParam Response - The response class type
259
+ * @param handler - A fetch handler or object with fetch method (like {@link LexRouter})
260
+ * @param options - Combined server and listen options
261
+ * @returns Promise resolving to the running server
262
+ *
263
+ * @example Basic usage
264
+ * ```typescript
265
+ * import { LexRouter } from '@atproto/lex-server'
266
+ * import { serve, upgradeWebSocket } from '@atproto/lex-server/nodejs'
267
+ *
268
+ * const router = new LexRouter({ upgradeWebSocket })
269
+ *
270
+ * // Register handlers
271
+ * router.add(getProfile, async (ctx) => {
272
+ * return { body: await db.getProfile(ctx.params.actor) }
273
+ * })
274
+ *
275
+ * // Start server on port 3000
276
+ * const server = await serve(router, { port: 3000 })
277
+ * console.log('Server listening on port 3000')
278
+ *
279
+ * // Graceful shutdown
280
+ * process.on('SIGTERM', () => server.terminate())
281
+ * process.on('SIGINT', () => server.terminate())
282
+ * ```
283
+ *
284
+ * @example With all options
285
+ * ```typescript
286
+ * const server = await serve(router, {
287
+ * port: 3000,
288
+ * host: '0.0.0.0',
289
+ * gracefulTerminationTimeout: 15000,
290
+ * })
291
+ * ```
292
+ *
293
+ * @example Using with await using (auto-cleanup)
294
+ * ```typescript
295
+ * async function main() {
296
+ * await using server = await serve(router, { port: 3000 })
297
+ *
298
+ * // Server is running...
299
+ * console.log('Server listening on port 3000')
300
+ *
301
+ * // Wait for termination signal
302
+ * await Promise.race([
303
+ * once(process, 'SIGINT'),
304
+ * once(process, 'SIGTERM'),
305
+ * ])
306
+ *
307
+ * // Server will be automatically terminated when scope exits
308
+ * }
309
+ * ```
310
+ */
311
+ export declare function serve<Request extends typeof IncomingMessage = typeof IncomingMessage, Response extends typeof ServerResponse<InstanceType<Request>> = typeof ServerResponse>(handler: FetchHandler | HandlerObject, options?: StartServerOptions<Request, Response>): Promise<Server<Request, Response>>;
312
+ //# sourceMappingURL=nodejs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nodejs.d.ts","sourceRoot":"","sources":["../src/nodejs.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,KAAK,eAAe,EAEpB,KAAK,MAAM,IAAI,UAAU,EACzB,KAAK,aAAa,EAClB,KAAK,cAAc,EAEpB,MAAM,WAAW,CAAA;AAClB,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AAM7C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAA;AAenD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,OAAO,GAAG;IAClD,QAAQ,EAAE,QAAQ,CAAA;IAClB,MAAM,EAAE,SAAS,CAAA;CAClB,CAkCA;AAyCD;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAsB,YAAY,CAChC,GAAG,EAAE,eAAe,EACpB,GAAG,EAAE,cAAc,EACnB,QAAQ,EAAE,QAAQ,GACjB,OAAO,CAAC,IAAI,CAAC,CAwBf;AA4GD;;;;;;;;;;;GAWG;AACH,MAAM,MAAM,OAAO,GAAG;IACpB,iDAAiD;IACjD,SAAS,EAAE,KAAK,CAAA;IAChB,2CAA2C;IAC3C,QAAQ,EAAE,MAAM,CAAA;IAChB,4CAA4C;IAC5C,IAAI,EAAE,MAAM,CAAA;CACb,CAAA;AAED;;;;;;GAMG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAC/B,iEAAiE;IACjE,SAAS,EAAE,OAAO,CAAC,IAAI,CAAC,CAAA;IACxB,sDAAsD;IACtD,UAA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