@atproto/lex-server 0.0.17 → 0.1.0-next.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.
- package/CHANGELOG.md +36 -0
- package/README.md +1 -1
- package/dist/errors.js +14 -23
- package/dist/errors.js.map +1 -1
- package/dist/index.js +3 -6
- package/dist/index.js.map +1 -1
- package/dist/lex-router.d.ts +1 -1
- package/dist/lex-router.d.ts.map +1 -1
- package/dist/lex-router.js +104 -109
- package/dist/lex-router.js.map +1 -1
- package/dist/lib/drain-websocket.js +3 -6
- package/dist/lib/drain-websocket.js.map +1 -1
- package/dist/lib/sleep.js +1 -4
- package/dist/lib/sleep.js.map +1 -1
- package/dist/lib/www-authenticate.js +1 -4
- package/dist/lib/www-authenticate.js.map +1 -1
- package/dist/nodejs.d.ts +1 -1
- package/dist/nodejs.d.ts.map +1 -1
- package/dist/nodejs.js +23 -27
- package/dist/nodejs.js.map +1 -1
- package/dist/service-auth.js +32 -37
- package/dist/service-auth.js.map +1 -1
- package/package.json +18 -19
- package/src/lex-router.ts +6 -3
- package/src/nodejs.ts +5 -2
- package/src/service-auth.test.ts +87 -0
- package/src/service-auth.ts +1 -1
- /package/{nodejs.js → nodejs.cjs} +0 -0
package/dist/lex-router.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lex-router.js","sourceRoot":"","sources":["../src/lex-router.ts"],"names":[],"mappings":";;;AAAA,gDAA0C;AAC1C,gDAM0B;AAC1B,gDAAuD;AACvD,oDAgB4B;AAC5B,2CAA4C;AAC5C,iEAAyD;AAEzD,MAAM,gBAAgB,GAAG,QAAQ,CAAA;AACjC,MAAM,sBAAsB,GAAG,eAAe,CAAA;AAod9C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmEG;AACH,MAAa,SAAS;IASC;IARrB,mDAAmD;IAC1C,QAAQ,GAAkC,IAAI,GAA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K,CAAC,CAAC,IAAI,YAAY,CAAC,IAAI,EAAE,CAAC,EAAE,UAAU,CAAC,EAAE,CAAC;QAC3D,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC,WAAW,EAAE,IAAI,IAAI,CAAC,KAAK,CAAC,UAAU,GAAG,CAAC,CAAC,EAAgB,CAAA;IACjG,CAAC;IAED,OAAO,IAAI,CAAA;AACb,CAAC;AAED,SAAS,YAAY,CAAC,GAAW,EAAE,KAAK,GAAG,CAAC,EAAE,GAAG,GAAG,GAAG,CAAC,MAAM;IAC5D,KAAK,IAAI,CAAC,GAAG,KAAK,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC;QACjC,MAAM,IAAI,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAA;QAC9B,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,EAAE,CAAC;YACjC,OAAO,IAAI,CAAA;QACb,CAAC;IACH,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC;AAED,SAAS,sBAAsB,CAC7B,OAAe,EACf,MAAM,GAAG,GAAG,EACZ,OAAqB;IAErB,OAAO,QAAQ,CAAC,IAAI,CAClB;QACE,KAAK,EAAE,gBAAgB;QACvB,OAAO;KACR,EACD,EAAE,MAAM,EAAE,OAAO,EAAE,CACpB,CAAA;AACH,CAAC","sourcesContent":["import { encode } from '@atproto/lex-cbor'\nimport {\n LexError,\n LexErrorData,\n LexValue,\n isPlainObject,\n ui8Concat,\n} from '@atproto/lex-data'\nimport { lexParse, lexToJson } from '@atproto/lex-json'\nimport {\n DidString,\n InferMethodInput,\n InferMethodMessage,\n InferMethodOutput,\n InferMethodOutputBody,\n InferMethodOutputEncoding,\n InferMethodParams,\n Main,\n NsidString,\n Procedure,\n Query,\n Subscription,\n getMain,\n isDidString,\n isNsidString,\n} from '@atproto/lex-schema'\nimport { LexServerError } from './errors.js'\nimport { drainWebsocket } from './lib/drain-websocket.js'\n\nconst XRPC_PATH_PREFIX = '/xrpc/'\nconst XRPC_HEALTH_CHECK_PATH = '/xrpc/_health'\n\ntype Awaitable<T> = T | Promise<T>\n\n/**\n * Union type representing the supported Lexicon method types.\n *\n * - `Query`: Read-only methods invoked via HTTP GET\n * - `Procedure`: Methods that may modify state, invoked via HTTP POST\n * - `Subscription`: Real-time streaming methods over WebSocket\n */\nexport type LexMethod = Query | Procedure | Subscription\n\n/**\n * Network address for TCP or UDP connections.\n *\n * @example\n * ```typescript\n * const addr: NetAddr = {\n * hostname: '127.0.0.1',\n * port: 3000,\n * transport: 'tcp'\n * }\n * ```\n */\nexport type NetAddr = {\n /** The hostname or IP address of the connection. */\n hostname: string\n /** The port number of the connection. */\n port: number\n /** The transport protocol used. */\n transport: 'tcp' | 'udp'\n}\n\n/**\n * Unix domain socket address.\n *\n * @example\n * ```typescript\n * const addr: UnixAddr = {\n * path: '/var/run/app.sock',\n * transport: 'unix'\n * }\n * ```\n */\nexport type UnixAddr = {\n /** The filesystem path to the Unix socket. */\n path: string\n /** The transport protocol used. */\n transport: 'unix' | 'unixpacket'\n}\n\n/**\n * Union type for all supported address types.\n *\n * Can be a network address ({@link NetAddr}), Unix socket address ({@link UnixAddr}),\n * or `undefined` when the address is not available.\n */\nexport type Addr = NetAddr | UnixAddr | undefined\n\n/**\n * Metadata about the client connection for an incoming request.\n *\n * @typeParam A - The address type, defaults to {@link Addr}\n *\n * @example\n * ```typescript\n * const info: ConnectionInfo<NetAddr> = {\n * remoteAddr: { hostname: '192.168.1.1', port: 54321, transport: 'tcp' },\n * completed: new Promise((resolve) => socket.on('close', resolve))\n * }\n * ```\n */\nexport type ConnectionInfo<A extends Addr = Addr> = {\n /** The remote address of the client, if available. */\n remoteAddr: A\n /** Promise that resolves when the connection is fully closed. */\n completed: Promise<void>\n}\n\n/**\n * Function signature for handling HTTP requests in the XRPC router.\n *\n * This is the standard fetch-style handler that processes incoming requests\n * and returns responses. It is used both internally by the router and can\n * be used to integrate with other HTTP frameworks.\n *\n * @param request - The incoming HTTP request\n * @param connection - Optional connection metadata including remote address\n * @returns A promise resolving to the HTTP response\n *\n * @example\n * ```typescript\n * const handler: FetchHandler = async (request, connection) => {\n * console.log('Request from:', connection?.remoteAddr)\n * return new Response('Hello, World!')\n * }\n * ```\n */\nexport type FetchHandler = (\n request: Request,\n connection?: ConnectionInfo,\n) => Promise<Response>\n\n/**\n * Context object passed to XRPC method handlers.\n *\n * Contains all the information needed to process a request, including\n * parsed parameters, authentication credentials, and the raw request object.\n *\n * @typeParam Method - The Lexicon method type (Query, Procedure, or Subscription)\n * @typeParam Credentials - The type of authentication credentials, determined by the auth handler\n *\n * @example\n * ```typescript\n * const handler: LexRouterMethodHandler<MyMethod, UserCredentials> = async (ctx) => {\n * const { credentials, params, input, signal } = ctx\n * // credentials.userId is available if auth handler returns UserCredentials\n * // params contains validated query parameters\n * // input contains the request body (for procedures)\n * // signal can be used to abort long-running operations\n * return { body: { result: 'success' } }\n * }\n * ```\n */\nexport type LexRouterHandlerContext<Method extends LexMethod, Credentials> = {\n /** Authentication credentials returned by the auth handler. */\n credentials: Credentials\n /** Parsed and validated request input (body for procedures, undefined for queries). */\n input: InferMethodInput<Method, Body>\n /** Parsed and validated URL query parameters. */\n params: InferMethodParams<Method>\n /** The original HTTP request object. */\n request: Request\n /** Abort signal that is triggered when the request is cancelled. */\n signal: AbortSignal\n /** Connection metadata including remote address. */\n connection?: ConnectionInfo\n}\n\ntype AsOptionalPayloadOptions<T> = T extends undefined | void\n ? { encoding?: undefined; body?: undefined }\n : T\n\n/**\n * Return type for XRPC method handlers (queries and procedures).\n *\n * Handlers can return either:\n * - A raw {@link Response} object for full control over the HTTP response\n * - An object with `body`, optional `encoding`, and optional `headers`\n *\n * For JSON methods, the body is automatically serialized. For other encodings,\n * the body must be a valid {@link BodyInit} type.\n *\n * @typeParam Method - The Lexicon method type (Query or Procedure)\n *\n * @example\n * ```typescript\n * // Return JSON body (most common)\n * return { body: { users: [...] } }\n *\n * // Return with custom headers\n * return {\n * body: { data: 'value' },\n * headers: { 'Cache-Control': 'max-age=3600' }\n * }\n *\n * // Return raw Response for full control\n * return new Response(binaryData, {\n * headers: { 'Content-Type': 'application/octet-stream' }\n * })\n * ```\n */\nexport type LexRouterHandlerOutput<Method extends Query | Procedure> =\n | Response\n | ({\n headers?: HeadersInit\n } & (InferMethodOutputEncoding<Method> extends 'application/json'\n ? {\n // Allow omitting body when output is JSON\n encoding?: 'application/json'\n body: InferMethodOutputBody<Method>\n }\n : AsOptionalPayloadOptions<InferMethodOutput<Method, BodyInit>>))\n\n/**\n * Handler function for XRPC query and procedure methods.\n *\n * Receives a context object with request details and credentials,\n * and returns either a Response or a structured output object.\n *\n * @typeParam Method - The Lexicon method type (Query or Procedure)\n * @typeParam Credentials - The type of authentication credentials\n *\n * @example\n * ```typescript\n * const getProfile: LexRouterMethodHandler<GetProfileMethod, UserCredentials> = async (ctx) => {\n * const profile = await db.getProfile(ctx.params.actor)\n * return { body: profile }\n * }\n * ```\n */\nexport type LexRouterMethodHandler<\n Method extends Query | Procedure = Query | Procedure,\n Credentials = unknown,\n> = (\n ctx: LexRouterHandlerContext<Method, Credentials>,\n) => Awaitable<LexRouterHandlerOutput<Method>>\n\n/**\n * Configuration object for registering an XRPC method with authentication.\n *\n * Used when you need to specify both a handler and an auth function.\n *\n * @typeParam Method - The Lexicon method type (Query or Procedure)\n * @typeParam Credentials - The type of authentication credentials\n *\n * @example\n * ```typescript\n * const config: LexRouterMethodConfig<GetProfileMethod, UserCredentials> = {\n * handler: async (ctx) => {\n * return { body: await getProfile(ctx.params.actor) }\n * },\n * auth: async ({ request }) => {\n * return verifyToken(request.headers.get('authorization'))\n * }\n * }\n * ```\n */\nexport type LexRouterMethodConfig<\n Method extends Query | Procedure = Query | Procedure,\n Credentials = unknown,\n> = {\n /** The handler function that processes the request. */\n handler: LexRouterMethodHandler<Method, Credentials>\n /** Authentication function that validates credentials before the handler runs. */\n auth: LexRouterAuth<Credentials, Method>\n}\n\n/**\n * Handler function for XRPC subscription methods (WebSocket streams).\n *\n * Returns an async iterable that yields messages to be sent over the WebSocket.\n * The connection remains open until the iterable completes or an error occurs.\n *\n * @typeParam Method - The Lexicon subscription method type\n * @typeParam Credentials - The type of authentication credentials\n *\n * @example\n * ```typescript\n * const subscribeRepos: LexRouterSubscriptionHandler<SubscribeReposMethod> = async function* (ctx) {\n * const cursor = ctx.params.cursor ?? 0\n * for await (const event of eventStream.since(cursor)) {\n * if (ctx.signal.aborted) break\n * yield { $type: 'com.atproto.sync.subscribeRepos#commit', ...event }\n * }\n * }\n * ```\n */\nexport type LexRouterSubscriptionHandler<\n Method extends Subscription = Subscription,\n Credentials = unknown,\n> = (\n ctx: LexRouterHandlerContext<Method, Credentials>,\n) => AsyncIterable<InferMethodMessage<Method>>\n\n/**\n * Configuration object for registering an XRPC subscription with authentication.\n *\n * Used when you need to specify both a handler and an auth function for subscriptions.\n *\n * @typeParam Method - The Lexicon subscription method type\n * @typeParam Credentials - The type of authentication credentials\n *\n * @example\n * ```typescript\n * const config: LexRouterSubscriptionConfig<SubscribeReposMethod, ServiceCredentials> = {\n * handler: async function* (ctx) {\n * for await (const event of eventStream) {\n * yield event\n * }\n * },\n * auth: async ({ request }) => {\n * return verifyServiceAuth(request)\n * }\n * }\n * ```\n */\nexport type LexRouterSubscriptionConfig<\n Method extends Subscription = Subscription,\n Credentials = unknown,\n> = {\n /** The handler function that yields subscription messages. */\n handler: LexRouterSubscriptionHandler<Method, Credentials>\n /** Authentication function that validates credentials before the handler runs. */\n auth: LexRouterAuth<Credentials, Method>\n}\n\n/**\n * Context object passed to authentication handlers.\n *\n * Contains the information needed to authenticate a request before\n * the main handler is invoked.\n *\n * @typeParam Method - The Lexicon method type\n *\n * @example\n * ```typescript\n * const authHandler: LexRouterAuth<UserCredentials> = async (ctx) => {\n * const token = ctx.request.headers.get('authorization')\n * if (!token) throw new LexServerAuthError('AuthenticationRequired', 'Missing token')\n * return { userId: await verifyToken(token) }\n * }\n * ```\n */\nexport type LexRouterAuthContext<Method extends LexMethod = LexMethod> = {\n /** The Lexicon method definition being called. */\n method: Method\n /** Parsed and validated URL query parameters. */\n params: InferMethodParams<Method>\n /** The original HTTP request object. */\n request: Request\n /** Connection metadata including remote address. */\n connection?: ConnectionInfo\n}\n\n/**\n * Authentication handler function for XRPC methods.\n *\n * Called before the main handler to validate authentication credentials.\n * Should return the validated credentials or throw an error if authentication fails.\n *\n * @typeParam Credentials - The type of credentials to return on success\n * @typeParam Method - The Lexicon method type\n *\n * @example\n * ```typescript\n * // Simple token-based auth\n * const tokenAuth: LexRouterAuth<{ userId: string }> = async ({ request }) => {\n * const token = request.headers.get('authorization')?.replace('Bearer ', '')\n * if (!token) throw new LexServerAuthError('AuthenticationRequired', 'Token required')\n * const userId = await verifyToken(token)\n * if (!userId) throw new LexServerAuthError('AuthenticationRequired', 'Invalid token')\n * return { userId }\n * }\n *\n * // Using with serviceAuth for AT Protocol service authentication\n * import { serviceAuth } from '@atproto/lex-server'\n * const auth = serviceAuth({ audience: 'did:web:example.com', unique: checkNonce })\n * ```\n */\nexport type LexRouterAuth<\n Credentials = unknown,\n Method extends LexMethod = LexMethod,\n> = (ctx: LexRouterAuthContext<Method>) => Credentials | Promise<Credentials>\n\n/**\n * Context object passed to error handler callbacks.\n *\n * Used for logging and monitoring errors that occur during request handling.\n */\nexport type HandlerErrorContext = {\n request: Request\n method: LexMethod\n error: LexServerError\n}\n\nexport type HandlerErrorHook = (\n ctx: HandlerErrorContext,\n) => void | Promise<void>\n\nexport type SocketErrorContext = {\n request: Request\n method: Subscription\n error: unknown\n}\n\nexport type SocketErrorHook = (ctx: SocketErrorContext) => void | Promise<void>\n\n/**\n * Function that upgrades an HTTP request to a WebSocket connection.\n *\n * This is platform-specific: Deno provides this natively, while Node.js\n * requires the `upgradeWebSocket` function from this package.\n *\n * @param request - The HTTP request to upgrade\n * @returns An object containing the WebSocket and the upgrade response\n *\n * @example\n * ```typescript\n * // In Node.js, use the provided upgradeWebSocket function\n * import { upgradeWebSocket } from '@atproto/lex-server/nodejs'\n *\n * const router = new LexRouter({ upgradeWebSocket })\n * ```\n */\nexport type UpgradeWebSocket = (request: Request) => {\n /** The WebSocket instance for bidirectional communication. */\n socket: WebSocket\n /** The HTTP response to return (101 Switching Protocols). */\n response: Response\n}\n\nexport type HealthCheckHandler = (\n request: Request,\n) => Awaitable<{ [x: string]: unknown; status: 'ok' }>\n\n/**\n * Configuration options for the {@link LexRouter}.\n *\n * @example\n * ```typescript\n * const options: LexRouterOptions = {\n * upgradeWebSocket,\n * onHandlerError: async ({ error, request, method }) => {\n * console.error(`Error in ${method.nsid}:`, error)\n * await reportToSentry(error)\n * },\n * highWaterMark: 64 * 1024, // 64KB\n * lowWaterMark: 16 * 1024 // 16KB\n * }\n * ```\n */\nexport type LexRouterOptions = {\n /**\n * Function to upgrade HTTP requests to WebSocket connections. Required for\n * subscription methods. Defaults to Deno's built-in\n * {@link globalThis.upgradeWebSocket} if available. For NodeJS, use the\n * homonymous export from `@atproto/lex-server/nodejs`.\n */\n upgradeWebSocket?: UpgradeWebSocket\n /**\n * Callback invoked when an error occurs during request handling. Useful for\n * logging and error reporting. Not called for client-induced errors (e.g.,\n * request abortion).\n */\n onHandlerError?: HandlerErrorHook\n /**\n * Optional hook for handling errors during generation of WebSocket messages.\n */\n onSocketError?: SocketErrorHook\n /**\n * Optional health check handler. If provided, this function will be called\n * for requests to the /xrpc/_health endpoint, allowing for custom health\n * check logic and responses.\n *\n * If not provided, the server will respond to /xrpc/_health requests with a\n * default JSON response of `{ status: 'ok' }`.\n */\n healthCheck?: HealthCheckHandler\n /**\n * Optional fallback handler for requests that are not /xrpc/ paths. Can be\n * used to serve static files or other routes. If not provided, non-/xrpc/\n * requests will return 404 responses.\n */\n fallback?: FetchHandler\n /**\n * High water mark for WebSocket backpressure (in bytes). When buffered data\n * exceeds this, the handler will wait before sending more.\n */\n highWaterMark?: number\n /**\n * Low water mark for WebSocket backpressure (in bytes). The handler resumes\n * sending when buffered data drops below this.\n */\n lowWaterMark?: number\n}\n\n/**\n * XRPC router for handling AT Protocol Lexicon methods.\n *\n * The router handles HTTP routing, parameter parsing, input validation,\n * authentication, and response serialization for XRPC methods. It supports\n * queries (GET), procedures (POST), and subscriptions (WebSocket).\n *\n * @example Setting up a basic XRPC server\n * ```typescript\n * import { LexRouter } from '@atproto/lex-server'\n * import { serve, upgradeWebSocket } from '@atproto/lex-server/nodejs'\n * import { getProfile, createPost, subscribeRepos } from './lexicons'\n *\n * const router = new LexRouter({ upgradeWebSocket })\n *\n * // Register a query handler (GET request)\n * router.add(getProfile, async (ctx) => {\n * const profile = await db.getProfile(ctx.params.actor)\n * return { body: profile }\n * })\n *\n * // Register a procedure handler with authentication (POST request)\n * router.add(createPost, {\n * handler: async (ctx) => {\n * const post = await db.createPost(ctx.credentials.did, ctx.input.body)\n * return { body: { uri: post.uri, cid: post.cid } }\n * },\n * auth: async ({ request }) => {\n * return verifyAccessToken(request)\n * }\n * })\n *\n * // Register a subscription handler (WebSocket)\n * router.add(subscribeRepos, async function* (ctx) {\n * for await (const event of eventStream.since(ctx.params.cursor)) {\n * if (ctx.signal.aborted) break\n * yield event\n * }\n * })\n *\n * // Start the server\n * const server = await serve(router, { port: 3000 })\n * console.log('XRPC server listening on port 3000')\n * ```\n *\n * @example Using with service authentication\n * ```typescript\n * import { LexRouter, serviceAuth } from '@atproto/lex-server'\n *\n * const router = new LexRouter()\n *\n * const auth = serviceAuth({\n * audience: 'did:web:api.example.com',\n * unique: async (nonce) => {\n * // Check and record nonce uniqueness\n * return await nonceStore.checkAndAdd(nonce)\n * }\n * })\n *\n * router.add(protectedMethod, {\n * handler: async (ctx) => {\n * // ctx.credentials contains { did, didDocument, jwt }\n * return { body: { callerDid: ctx.credentials.did } }\n * },\n * auth\n * })\n * ```\n */\nexport class LexRouter {\n /** Map of NSID strings to their fetch handlers. */\n readonly handlers: Map<NsidString, FetchHandler> = new Map()\n\n /**\n * Creates a new XRPC router.\n *\n * @param options - Router configuration options\n */\n constructor(readonly options: LexRouterOptions = {}) {}\n\n /**\n * Registers a subscription handler without authentication.\n *\n * @param ns - The Lexicon namespace definition for the subscription\n * @param handler - Async generator function that yields subscription messages\n * @returns This router instance for chaining\n */\n add<M extends Subscription>(\n ns: Main<M>,\n handler: LexRouterSubscriptionHandler<M, void>,\n ): this\n /**\n * Registers a subscription handler with authentication.\n *\n * @param ns - The Lexicon namespace definition for the subscription\n * @param config - Configuration object with handler and auth function\n * @returns This router instance for chaining\n */\n add<M extends Subscription, Credentials>(\n ns: Main<M>,\n config: LexRouterSubscriptionConfig<M, Credentials>,\n ): this\n /**\n * Registers a query or procedure handler without authentication.\n *\n * @param ns - The Lexicon namespace definition for the method\n * @param handler - Handler function that processes requests\n * @returns This router instance for chaining\n */\n add<M extends Query | Procedure>(\n ns: Main<M>,\n handler: LexRouterMethodHandler<M, void>,\n ): this\n /**\n * Registers a query or procedure handler with authentication.\n *\n * @param ns - The Lexicon namespace definition for the method\n * @param config - Configuration object with handler and auth function\n * @returns This router instance for chaining\n */\n add<M extends Query | Procedure, Credentials>(\n ns: Main<M>,\n config: LexRouterMethodConfig<M, Credentials>,\n ): this\n /**\n * Registers a Lexicon method handler.\n *\n * This is the unified overload that accepts any method type with optional authentication.\n *\n * @param ns - The Lexicon namespace definition\n * @param config - Handler function or configuration object\n * @returns This router instance for chaining\n *\n * @throws {TypeError} If a method with the same NSID is already registered\n *\n * @example\n * ```typescript\n * // Register without auth (credentials will be void)\n * router.add(myQuery, async (ctx) => {\n * return { body: { data: 'value' } }\n * })\n *\n * // Register with auth\n * router.add(myProcedure, {\n * handler: async (ctx) => {\n * console.log('Caller:', ctx.credentials.userId)\n * return { body: { success: true } }\n * },\n * auth: async ({ request }) => ({ userId: await verifyToken(request) })\n * })\n * ```\n */\n add<M extends LexMethod, Credentials = unknown>(\n ns: Main<M>,\n config: M extends Subscription\n ?\n | LexRouterSubscriptionHandler<M, Credentials>\n | LexRouterSubscriptionConfig<M, Credentials>\n : M extends Query | Procedure\n ?\n | LexRouterMethodHandler<M, Credentials>\n | LexRouterMethodConfig<M, Credentials>\n : never,\n ): this\n add<M extends LexMethod>(\n ns: Main<M>,\n config:\n | LexRouterSubscriptionHandler<any, any>\n | LexRouterSubscriptionConfig<any, any>\n | LexRouterMethodHandler<any, any>\n | LexRouterMethodConfig<any, any>,\n ) {\n const method = getMain(ns)\n const nsid = normalizeNsid(method.nsid)\n\n if (this.handlers.has(nsid)) {\n throw new TypeError(`Method ${method.nsid} already registered`)\n }\n\n const methodConfig =\n typeof config === 'function'\n ? { handler: config, auth: undefined }\n : config\n\n const handler: FetchHandler =\n method.type === 'subscription'\n ? this.buildSubscriptionHandler(\n method,\n methodConfig.handler as LexRouterSubscriptionHandler<any, any>,\n methodConfig.auth,\n )\n : this.buildMethodHandler(\n method,\n methodConfig.handler as LexRouterMethodHandler<any, any>,\n methodConfig.auth,\n )\n\n this.handlers.set(nsid, handler)\n\n return this\n }\n\n private buildMethodHandler<Method extends Query | Procedure, Credentials>(\n method: Method,\n methodHandler: LexRouterMethodHandler<Method, Credentials>,\n auth?: LexRouterAuth<Credentials, Method>,\n ): FetchHandler {\n const getInput = (\n method.type === 'procedure'\n ? getProcedureInput.bind(method)\n : getQueryInput.bind(method)\n ) as (request: Request) => Promise<InferMethodInput<Method, Body>>\n\n return async (request, connection) => {\n // @NOTE CORS requests should be handled by a middleware before reaching\n // this point.\n if (\n (method.type === 'procedure' && request.method !== 'POST') ||\n (method.type === 'query' &&\n request.method !== 'GET' &&\n request.method !== 'HEAD')\n ) {\n return invalidRequestResponse('Method not allowed', 405)\n }\n\n try {\n const url = new URL(request.url)\n const params = method.parameters.fromURLSearchParams(\n url.searchParams,\n ) as InferMethodParams<Method>\n\n const credentials = auth\n ? await auth({ method, params, request, connection })\n : (undefined as Credentials)\n\n const input = await getInput(request)\n\n const output = await methodHandler({\n credentials,\n params,\n input,\n request,\n connection,\n signal: request.signal,\n })\n\n if (output instanceof Response) {\n return output\n }\n\n // @TODO add validation of output based on method.output.schema?\n\n if (output.body === undefined && output.encoding === undefined) {\n return new Response(null, { status: 200, headers: output.headers })\n }\n\n if (method.output?.encoding === 'application/json') {\n return Response.json(lexToJson(output.body as LexValue), {\n status: 200,\n headers: output.headers,\n })\n }\n\n const headers = new Headers(output.headers)\n headers.set('content-type', output.encoding!)\n return new Response(output.body as BodyInit | null | undefined, {\n status: 200,\n headers,\n })\n } catch (error) {\n return this.handlerError(request, method, error)\n }\n }\n }\n\n private buildSubscriptionHandler<Method extends Subscription, Credentials>(\n method: Method,\n methodHandler: LexRouterSubscriptionHandler<Method, Credentials>,\n auth?: LexRouterAuth<Credentials, Method>,\n ): FetchHandler {\n const {\n onSocketError,\n upgradeWebSocket = (globalThis as any).Deno?.upgradeWebSocket as\n | UpgradeWebSocket\n | undefined,\n } = this.options\n if (!upgradeWebSocket) {\n throw new TypeError(\n 'WebSocket upgrade not supported in this environment. Please provide an upgradeWebSocket option when creating the LexRouter.',\n )\n }\n\n return async (request, connection) => {\n if (request.method !== 'GET') {\n return invalidRequestResponse('Method not allowed', 405)\n }\n\n if (\n request.headers.get('connection')?.toLowerCase() !== 'upgrade' ||\n request.headers.get('upgrade')?.toLowerCase() !== 'websocket'\n ) {\n return invalidRequestResponse(\n 'XRPC subscriptions are only available over WebSocket',\n 426,\n {\n Connection: 'Upgrade',\n Upgrade: 'websocket',\n },\n )\n }\n\n if (request.signal.aborted) {\n return invalidRequestResponse('Request aborted', 499)\n }\n\n try {\n const { response, socket } = upgradeWebSocket(request)\n\n // @NOTE We are using a distinct signal than request.signal because that\n // signal may get aborted before the WebSocket is closed (this is the\n // case with Deno).\n const abortController = new AbortController()\n const { signal } = abortController\n const abort = () => abortController.abort()\n\n const onOpen = async () => {\n try {\n const url = new URL(request.url)\n const params = method.parameters.fromURLSearchParams(\n url.searchParams,\n ) as InferMethodParams<Method>\n\n const credentials: Credentials = auth\n ? await auth({ method, params, request, connection })\n : (undefined as Credentials)\n\n signal.throwIfAborted()\n\n const iterable = methodHandler({\n credentials,\n params,\n input: undefined as InferMethodInput<Method, Body>,\n request,\n connection,\n signal,\n })\n\n const iterator = iterable[Symbol.asyncIterator]()\n\n if (iterator.return) {\n signal.addEventListener(\n 'abort',\n () => {\n // @NOTE if iterator.return() throws, and no onSocketError is\n // provided, or if onSocketError itself throws, the error will\n // be unhandled, causing the process to crash. This is\n // intentional, as it surfaces critical errors that occur\n // during cleanup of the subscription.\n\n void new Promise((resolve) => {\n // Wrapping in new Promise to catch any potential sync errors thrown by iterator.return()\n resolve(iterator.return!())\n }).catch(\n onSocketError\n ? (error) => onSocketError({ request, method, error })\n : null,\n )\n },\n {\n once: true,\n },\n )\n }\n\n while (!signal.aborted && socket.readyState === 1) {\n const result = await iterator.next()\n if (result.done) break\n\n // @TODO add validation of output based on method.output.schema?\n\n const data = encodeMessageFrame(method, result.value)\n\n socket.send(data)\n\n // Apply backpressure by waiting for the buffered data to drain\n // before generating the next message\n await drainWebsocket(socket, signal, this.options)\n }\n\n if (socket.readyState === 1) {\n socket.close(1000)\n }\n } catch (error) {\n // If the socket is still open, send an error frame before closing\n if (socket.readyState === 1) {\n const isLexError = error instanceof LexError\n\n // https://www.rfc-editor.org/rfc/rfc6455#section-7.4.1\n const code =\n isLexError && method.errors?.includes(error.error)\n ? 1008 // Policy Violation for known LexErrors\n : 1011 // Internal Error for unexpected errors\n\n if (isLexError) {\n socket.send(encodeErrorFrame(error.toJSON()))\n socket.close(code, error.error)\n } else {\n const error = 'InternalServerError'\n const message = 'An internal error occurred'\n socket.send(encodeErrorFrame({ error, message }))\n socket.close(code, error)\n }\n }\n\n if (onSocketError && !isAbortReason(signal, error)) {\n await onSocketError({ request, method, error })\n }\n } finally {\n abortController.abort()\n }\n }\n\n socket.addEventListener('error', abort)\n socket.addEventListener('close', abort)\n socket.addEventListener('open', onOpen)\n socket.addEventListener('message', onMessage)\n\n return response\n } catch (error) {\n return this.handlerError(request, method, error)\n }\n }\n }\n\n private async handlerError(\n request: Request,\n method: LexMethod,\n cause: unknown,\n ) {\n // Only report unexpected processing errors\n if (isAbortReason(request.signal, cause)) {\n return Response.json({ error: 'RequestAborted' }, { status: 499 })\n }\n\n const error = LexServerError.from(cause)\n\n const { onHandlerError } = this.options\n if (onHandlerError) await onHandlerError({ error, request, method })\n\n return error.toResponse()\n }\n\n /**\n * The main fetch handler for processing XRPC requests.\n *\n * Routes incoming requests to the appropriate method handler based on the\n * NSID in the URL path. Returns appropriate error responses for invalid\n * paths or unimplemented methods.\n *\n * This handler can be used directly with HTTP servers that support the\n * fetch API pattern, or converted to a Node.js request listener using\n * `toRequestListener()`.\n *\n * @param request - The incoming HTTP request\n * @param connection - Optional connection metadata\n * @returns A promise resolving to the HTTP response\n *\n * @example\n * ```typescript\n * // Use with Deno\n * Deno.serve(router.fetch)\n *\n * // Use with Bun\n * Bun.serve({ fetch: router.fetch })\n *\n * // Use with Node.js\n * import { toRequestListener } from '@atproto/lex-server/nodejs'\n * const listener = toRequestListener(router.fetch)\n * http.createServer(listener).listen(3000)\n * ```\n */\n fetch: FetchHandler = async (\n request: Request,\n connection?: ConnectionInfo,\n ): Promise<Response> => {\n const { pathname } = new URL(request.url)\n const atprotoProxy = request.headers.get('atproto-proxy')\n\n if (!pathname.startsWith(XRPC_PATH_PREFIX)) {\n // Handle non XRPC paths\n const { fallback } = this.options\n if (fallback) return fallback(request, connection)\n return new Response('Not Found', { status: 404 })\n }\n\n if (pathname === XRPC_HEALTH_CHECK_PATH) {\n if (request.method !== 'GET') {\n return invalidRequestResponse('Method not allowed', 405)\n }\n if (atprotoProxy != null) {\n return invalidRequestResponse(\n 'atproto-proxy header is not allowed on health check endpoint',\n )\n }\n\n const { healthCheck } = this.options\n const data = healthCheck ? await healthCheck(request) : { status: 'ok' }\n\n return Response.json(data)\n }\n\n const subPath = pathname.slice(XRPC_PATH_PREFIX.length)\n\n if (!isNsidString(subPath)) {\n return invalidRequestResponse('Invalid NSID in URL path')\n }\n\n const nsid = normalizeNsid(subPath)\n if (atprotoProxy == null) {\n const handler = this.handlers.get(nsid)\n if (handler) return handler(request, connection)\n } else {\n // Handle service proxying logic.\n\n const proxyInfo = parseAtprotoProxyHeader(atprotoProxy)\n if (!proxyInfo) {\n return invalidRequestResponse(\n `Invalid atproto-proxy header value: ${atprotoProxy}`,\n )\n }\n\n // @TODO actually implement service proxying logic here. The reason it was\n // not done already is because we want to perform all the heavy lifting\n // here, while still allowing the possibility to override the endpoint\n // resolution, etc.\n\n // @NOTE see ./service-auth.ts for potential common code (did resolver, etc.)\n }\n\n return Response.json(\n {\n error: 'MethodNotImplemented',\n message: `XRPC method \"${nsid}\" not implemented on this server`,\n },\n { status: 501 },\n )\n }\n}\n\nasync function getProcedureInput<M extends Procedure>(\n this: M,\n request: Request,\n): Promise<InferMethodInput<M, Body>> {\n const encodingRaw = request.headers\n .get('content-type')\n ?.split(';')[0]\n .trim()\n .toLowerCase()\n\n const encoding =\n encodingRaw ||\n // If the caller did not provide a content-type, but the method\n // expects an input, assume binary\n (request.body != null && this.input.encoding != null\n ? 'application/octet-stream'\n : undefined)\n\n if (!this.input.matchesEncoding(encoding)) {\n throw new LexServerError(400, {\n error: 'InvalidRequest',\n message: `Invalid content-type: ${encoding}`,\n })\n }\n\n if (this.input.encoding === 'application/json') {\n // @TODO limit size?\n const data = lexParse(await request.text())\n const body = this.input.schema ? this.input.schema.parse(data) : data\n return { encoding, body } as InferMethodInput<M, Body>\n } else if (this.input.encoding) {\n const body: Body = request\n return { encoding, body } as InferMethodInput<M, Body>\n } else {\n return undefined as InferMethodInput<M, Body>\n }\n}\n\nasync function getQueryInput<M extends Query>(\n this: M,\n request: Request,\n): Promise<InferMethodInput<M, Body>> {\n if (\n request.body ||\n request.headers.has('content-type') ||\n request.headers.has('content-length')\n ) {\n throw new LexServerError(400, {\n error: 'InvalidRequest',\n message: 'GET requests must not have a body',\n })\n }\n\n return undefined as InferMethodInput<M, Body>\n}\n\nfunction onMessage(this: WebSocket, _event: unknown) {\n const error = 'InvalidRequest'\n const message = 'XRPC subscriptions do not accept messages'\n this.send(encodeErrorFrame({ error, message }))\n // 1003 indicates that an endpoint is terminating the connection\n // because it has received a type of data it cannot accept (e.g., an\n // endpoint that understands only text data MAY send this if it\n // receives a binary message).\n this.close(1003, error)\n}\n\n// Pre-encoded frame header for error frames\nconst ERROR_FRAME_HEADER = /*#__PURE__*/ encode({ op: -1 })\n\nfunction encodeErrorFrame(errorData: LexErrorData): Uint8Array {\n return ui8Concat([ERROR_FRAME_HEADER, encode(errorData)])\n}\n\n// Pre-encoded frame header for message frames with unknown type\nconst UNKNOWN_MESSAGE_FRAME_HEADER = /*#__PURE__*/ encode({ op: 1 })\n\nfunction encodeMessageFrame(method: Subscription, value: LexValue): Uint8Array {\n if (isPlainObject(value) && typeof value.$type === 'string') {\n const { $type, ...rest } = value\n return ui8Concat([\n encode({\n op: 1,\n t:\n // If $type starts with `nsid#`, strip the NSID prefix\n $type.charCodeAt(0) !== 0x23 && // '#'\n $type.charCodeAt(method.nsid.length) === 0x23 && // '#'\n $type.startsWith(method.nsid)\n ? $type.slice(method.nsid.length)\n : $type,\n }),\n encode(rest),\n ])\n }\n\n return ui8Concat([UNKNOWN_MESSAGE_FRAME_HEADER, encode(value)])\n}\n\nfunction isAbortReason(signal: AbortSignal, error: unknown): boolean {\n return (\n signal.aborted &&\n signal.reason != null &&\n error instanceof Error &&\n (error === signal.reason || error.cause === signal.reason)\n )\n}\n\nexport type ServiceProxyInfo = {\n did: DidString\n serviceId: string\n}\n\nfunction parseAtprotoProxyHeader(value: string): ServiceProxyInfo | null {\n // /!\\ Hot path\n\n // (fast) sanity check to avoid unnecessary parsing for non-DID values\n if (!value.startsWith('did:')) return null\n\n // The format is expected to be `did:example:service#serviceId`\n const hashIndex = value.indexOf('#')\n if (hashIndex === -1) return null\n\n const fragmentIndex = hashIndex + 1\n // Basic validation if the fragment\n if (fragmentIndex === value.length) return null\n if (value.includes('#', fragmentIndex)) return null\n if (value.includes(' ', fragmentIndex)) return null\n\n const did = value.slice(0, hashIndex)\n if (!isDidString(did)) return null\n\n const serviceId = value.slice(fragmentIndex)\n return { did, serviceId }\n}\n\nfunction normalizeNsid(nsid: NsidString): NsidString {\n const lastDotIdx = nsid.lastIndexOf('.')\n\n // The domain name part of the NSID is case-insensitive, but the last part is\n // case-sensitive. Normalize the domain part to lowercase.\n if (lastDotIdx !== -1 && hasUpperCase(nsid, 0, lastDotIdx)) {\n return `${nsid.slice(0, lastDotIdx).toLowerCase()}.${nsid.slice(lastDotIdx + 1)}` as NsidString\n }\n\n return nsid\n}\n\nfunction hasUpperCase(str: string, start = 0, end = str.length): boolean {\n for (let i = start; i < end; i++) {\n const code = str.charCodeAt(i)\n if (code >= 0x41 && code <= 0x5a) {\n return true\n }\n }\n return false\n}\n\nfunction invalidRequestResponse(\n message: string,\n status = 400,\n headers?: HeadersInit,\n): Response {\n return Response.json(\n {\n error: 'InvalidRequest',\n message,\n },\n { status, headers },\n )\n}\n"]}
|
|
1
|
+
{"version":3,"file":"lex-router.js","sourceRoot":"","sources":["../src/lex-router.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAA;AAC1C,OAAO,EACL,QAAQ,EAGR,aAAa,EACb,SAAS,GACV,MAAM,mBAAmB,CAAA;AAC1B,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAA;AACvD,OAAO,EAaL,OAAO,EACP,WAAW,EACX,YAAY,GACb,MAAM,qBAAqB,CAAA;AAC5B,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAC5C,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAA;AAEzD,MAAM,gBAAgB,GAAG,QAAQ,CAAA;AACjC,MAAM,sBAAsB,GAAG,eAAe,CAAA;AAod9C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AAY,CAAC,IAAI,EAAE,CAAC,EAAE,UAAU,CAAC,EAAE,CAAC;QAC3D,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC,WAAW,EAAE,IAAI,IAAI,CAAC,KAAK,CAAC,UAAU,GAAG,CAAC,CAAC,EAAgB,CAAA;IACjG,CAAC;IAED,OAAO,IAAI,CAAA;AACb,CAAC;AAED,SAAS,YAAY,CAAC,GAAW,EAAE,KAAK,GAAG,CAAC,EAAE,GAAG,GAAG,GAAG,CAAC,MAAM;IAC5D,KAAK,IAAI,CAAC,GAAG,KAAK,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC;QACjC,MAAM,IAAI,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAA;QAC9B,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,EAAE,CAAC;YACjC,OAAO,IAAI,CAAA;QACb,CAAC;IACH,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC;AAED,SAAS,sBAAsB,CAC7B,OAAe,EACf,MAAM,GAAG,GAAG,EACZ,OAAqB;IAErB,OAAO,QAAQ,CAAC,IAAI,CAClB;QACE,KAAK,EAAE,gBAAgB;QACvB,OAAO;KACR,EACD,EAAE,MAAM,EAAE,OAAO,EAAE,CACpB,CAAA;AACH,CAAC","sourcesContent":["import { encode } from '@atproto/lex-cbor'\nimport {\n LexError,\n LexErrorData,\n LexValue,\n isPlainObject,\n ui8Concat,\n} from '@atproto/lex-data'\nimport { lexParse, lexToJson } from '@atproto/lex-json'\nimport {\n DidString,\n InferMethodInput,\n InferMethodMessage,\n InferMethodOutput,\n InferMethodOutputBody,\n InferMethodOutputEncoding,\n InferMethodParams,\n Main,\n NsidString,\n Procedure,\n Query,\n Subscription,\n getMain,\n isDidString,\n isNsidString,\n} from '@atproto/lex-schema'\nimport { LexServerError } from './errors.js'\nimport { drainWebsocket } from './lib/drain-websocket.js'\n\nconst XRPC_PATH_PREFIX = '/xrpc/'\nconst XRPC_HEALTH_CHECK_PATH = '/xrpc/_health'\n\ntype Awaitable<T> = T | Promise<T>\n\n/**\n * Union type representing the supported Lexicon method types.\n *\n * - `Query`: Read-only methods invoked via HTTP GET\n * - `Procedure`: Methods that may modify state, invoked via HTTP POST\n * - `Subscription`: Real-time streaming methods over WebSocket\n */\nexport type LexMethod = Query | Procedure | Subscription\n\n/**\n * Network address for TCP or UDP connections.\n *\n * @example\n * ```typescript\n * const addr: NetAddr = {\n * hostname: '127.0.0.1',\n * port: 3000,\n * transport: 'tcp'\n * }\n * ```\n */\nexport type NetAddr = {\n /** The hostname or IP address of the connection. */\n hostname: string\n /** The port number of the connection. */\n port: number\n /** The transport protocol used. */\n transport: 'tcp' | 'udp'\n}\n\n/**\n * Unix domain socket address.\n *\n * @example\n * ```typescript\n * const addr: UnixAddr = {\n * path: '/var/run/app.sock',\n * transport: 'unix'\n * }\n * ```\n */\nexport type UnixAddr = {\n /** The filesystem path to the Unix socket. */\n path: string\n /** The transport protocol used. */\n transport: 'unix' | 'unixpacket'\n}\n\n/**\n * Union type for all supported address types.\n *\n * Can be a network address ({@link NetAddr}), Unix socket address ({@link UnixAddr}),\n * or `undefined` when the address is not available.\n */\nexport type Addr = NetAddr | UnixAddr | undefined\n\n/**\n * Metadata about the client connection for an incoming request.\n *\n * @typeParam A - The address type, defaults to {@link Addr}\n *\n * @example\n * ```typescript\n * const info: ConnectionInfo<NetAddr> = {\n * remoteAddr: { hostname: '192.168.1.1', port: 54321, transport: 'tcp' },\n * completed: new Promise((resolve) => socket.on('close', resolve))\n * }\n * ```\n */\nexport type ConnectionInfo<A extends Addr = Addr> = {\n /** The remote address of the client, if available. */\n remoteAddr: A\n /** Promise that resolves when the connection is fully closed. */\n completed: Promise<void>\n}\n\n/**\n * Function signature for handling HTTP requests in the XRPC router.\n *\n * This is the standard fetch-style handler that processes incoming requests\n * and returns responses. It is used both internally by the router and can\n * be used to integrate with other HTTP frameworks.\n *\n * @param request - The incoming HTTP request\n * @param connection - Optional connection metadata including remote address\n * @returns A promise resolving to the HTTP response\n *\n * @example\n * ```typescript\n * const handler: FetchHandler = async (request, connection) => {\n * console.log('Request from:', connection?.remoteAddr)\n * return new Response('Hello, World!')\n * }\n * ```\n */\nexport type FetchHandler = (\n request: Request,\n connection?: ConnectionInfo,\n) => Promise<Response>\n\n/**\n * Context object passed to XRPC method handlers.\n *\n * Contains all the information needed to process a request, including\n * parsed parameters, authentication credentials, and the raw request object.\n *\n * @typeParam Method - The Lexicon method type (Query, Procedure, or Subscription)\n * @typeParam Credentials - The type of authentication credentials, determined by the auth handler\n *\n * @example\n * ```typescript\n * const handler: LexRouterMethodHandler<MyMethod, UserCredentials> = async (ctx) => {\n * const { credentials, params, input, signal } = ctx\n * // credentials.userId is available if auth handler returns UserCredentials\n * // params contains validated query parameters\n * // input contains the request body (for procedures)\n * // signal can be used to abort long-running operations\n * return { body: { result: 'success' } }\n * }\n * ```\n */\nexport type LexRouterHandlerContext<Method extends LexMethod, Credentials> = {\n /** Authentication credentials returned by the auth handler. */\n credentials: Credentials\n /** Parsed and validated request input (body for procedures, undefined for queries). */\n input: InferMethodInput<Method, Body>\n /** Parsed and validated URL query parameters. */\n params: InferMethodParams<Method>\n /** The original HTTP request object. */\n request: Request\n /** Abort signal that is triggered when the request is cancelled. */\n signal: AbortSignal\n /** Connection metadata including remote address. */\n connection?: ConnectionInfo\n}\n\ntype AsOptionalPayloadOptions<T> = T extends undefined | void\n ? { encoding?: undefined; body?: undefined }\n : T\n\n/**\n * Return type for XRPC method handlers (queries and procedures).\n *\n * Handlers can return either:\n * - A raw {@link Response} object for full control over the HTTP response\n * - An object with `body`, optional `encoding`, and optional `headers`\n *\n * For JSON methods, the body is automatically serialized. For other encodings,\n * the body must be a valid {@link BodyInit} type.\n *\n * @typeParam Method - The Lexicon method type (Query or Procedure)\n *\n * @example\n * ```typescript\n * // Return JSON body (most common)\n * return { body: { users: [...] } }\n *\n * // Return with custom headers\n * return {\n * body: { data: 'value' },\n * headers: { 'Cache-Control': 'max-age=3600' }\n * }\n *\n * // Return raw Response for full control\n * return new Response(binaryData, {\n * headers: { 'Content-Type': 'application/octet-stream' }\n * })\n * ```\n */\nexport type LexRouterHandlerOutput<Method extends Query | Procedure> =\n | Response\n | ({\n headers?: HeadersInit\n } & (InferMethodOutputEncoding<Method> extends 'application/json'\n ? {\n // Allow omitting body when output is JSON\n encoding?: 'application/json'\n body: InferMethodOutputBody<Method>\n }\n : AsOptionalPayloadOptions<InferMethodOutput<Method, BodyInit>>))\n\n/**\n * Handler function for XRPC query and procedure methods.\n *\n * Receives a context object with request details and credentials,\n * and returns either a Response or a structured output object.\n *\n * @typeParam Method - The Lexicon method type (Query or Procedure)\n * @typeParam Credentials - The type of authentication credentials\n *\n * @example\n * ```typescript\n * const getProfile: LexRouterMethodHandler<GetProfileMethod, UserCredentials> = async (ctx) => {\n * const profile = await db.getProfile(ctx.params.actor)\n * return { body: profile }\n * }\n * ```\n */\nexport type LexRouterMethodHandler<\n Method extends Query | Procedure = Query | Procedure,\n Credentials = unknown,\n> = (\n ctx: LexRouterHandlerContext<Method, Credentials>,\n) => Awaitable<LexRouterHandlerOutput<Method>>\n\n/**\n * Configuration object for registering an XRPC method with authentication.\n *\n * Used when you need to specify both a handler and an auth function.\n *\n * @typeParam Method - The Lexicon method type (Query or Procedure)\n * @typeParam Credentials - The type of authentication credentials\n *\n * @example\n * ```typescript\n * const config: LexRouterMethodConfig<GetProfileMethod, UserCredentials> = {\n * handler: async (ctx) => {\n * return { body: await getProfile(ctx.params.actor) }\n * },\n * auth: async ({ request }) => {\n * return verifyToken(request.headers.get('authorization'))\n * }\n * }\n * ```\n */\nexport type LexRouterMethodConfig<\n Method extends Query | Procedure = Query | Procedure,\n Credentials = unknown,\n> = {\n /** The handler function that processes the request. */\n handler: LexRouterMethodHandler<Method, Credentials>\n /** Authentication function that validates credentials before the handler runs. */\n auth: LexRouterAuth<Credentials, Method>\n}\n\n/**\n * Handler function for XRPC subscription methods (WebSocket streams).\n *\n * Returns an async iterable that yields messages to be sent over the WebSocket.\n * The connection remains open until the iterable completes or an error occurs.\n *\n * @typeParam Method - The Lexicon subscription method type\n * @typeParam Credentials - The type of authentication credentials\n *\n * @example\n * ```typescript\n * const subscribeRepos: LexRouterSubscriptionHandler<SubscribeReposMethod> = async function* (ctx) {\n * const cursor = ctx.params.cursor ?? 0\n * for await (const event of eventStream.since(cursor)) {\n * if (ctx.signal.aborted) break\n * yield { $type: 'com.atproto.sync.subscribeRepos#commit', ...event }\n * }\n * }\n * ```\n */\nexport type LexRouterSubscriptionHandler<\n Method extends Subscription = Subscription,\n Credentials = unknown,\n> = (\n ctx: LexRouterHandlerContext<Method, Credentials>,\n) => AsyncIterable<InferMethodMessage<Method>>\n\n/**\n * Configuration object for registering an XRPC subscription with authentication.\n *\n * Used when you need to specify both a handler and an auth function for subscriptions.\n *\n * @typeParam Method - The Lexicon subscription method type\n * @typeParam Credentials - The type of authentication credentials\n *\n * @example\n * ```typescript\n * const config: LexRouterSubscriptionConfig<SubscribeReposMethod, ServiceCredentials> = {\n * handler: async function* (ctx) {\n * for await (const event of eventStream) {\n * yield event\n * }\n * },\n * auth: async ({ request }) => {\n * return verifyServiceAuth(request)\n * }\n * }\n * ```\n */\nexport type LexRouterSubscriptionConfig<\n Method extends Subscription = Subscription,\n Credentials = unknown,\n> = {\n /** The handler function that yields subscription messages. */\n handler: LexRouterSubscriptionHandler<Method, Credentials>\n /** Authentication function that validates credentials before the handler runs. */\n auth: LexRouterAuth<Credentials, Method>\n}\n\n/**\n * Context object passed to authentication handlers.\n *\n * Contains the information needed to authenticate a request before\n * the main handler is invoked.\n *\n * @typeParam Method - The Lexicon method type\n *\n * @example\n * ```typescript\n * const authHandler: LexRouterAuth<UserCredentials> = async (ctx) => {\n * const token = ctx.request.headers.get('authorization')\n * if (!token) throw new LexServerAuthError('AuthenticationRequired', 'Missing token')\n * return { userId: await verifyToken(token) }\n * }\n * ```\n */\nexport type LexRouterAuthContext<Method extends LexMethod = LexMethod> = {\n /** The Lexicon method definition being called. */\n method: Method\n /** Parsed and validated URL query parameters. */\n params: InferMethodParams<Method>\n /** The original HTTP request object. */\n request: Request\n /** Connection metadata including remote address. */\n connection?: ConnectionInfo\n}\n\n/**\n * Authentication handler function for XRPC methods.\n *\n * Called before the main handler to validate authentication credentials.\n * Should return the validated credentials or throw an error if authentication fails.\n *\n * @typeParam Credentials - The type of credentials to return on success\n * @typeParam Method - The Lexicon method type\n *\n * @example\n * ```typescript\n * // Simple token-based auth\n * const tokenAuth: LexRouterAuth<{ userId: string }> = async ({ request }) => {\n * const token = request.headers.get('authorization')?.replace('Bearer ', '')\n * if (!token) throw new LexServerAuthError('AuthenticationRequired', 'Token required')\n * const userId = await verifyToken(token)\n * if (!userId) throw new LexServerAuthError('AuthenticationRequired', 'Invalid token')\n * return { userId }\n * }\n *\n * // Using with serviceAuth for AT Protocol service authentication\n * import { serviceAuth } from '@atproto/lex-server'\n * const auth = serviceAuth({ audience: 'did:web:example.com', unique: checkNonce })\n * ```\n */\nexport type LexRouterAuth<\n Credentials = unknown,\n Method extends LexMethod = LexMethod,\n> = (ctx: LexRouterAuthContext<Method>) => Credentials | Promise<Credentials>\n\n/**\n * Context object passed to error handler callbacks.\n *\n * Used for logging and monitoring errors that occur during request handling.\n */\nexport type HandlerErrorContext = {\n request: Request\n method: LexMethod\n error: LexServerError\n}\n\nexport type HandlerErrorHook = (\n ctx: HandlerErrorContext,\n) => void | Promise<void>\n\nexport type SocketErrorContext = {\n request: Request\n method: Subscription\n error: unknown\n}\n\nexport type SocketErrorHook = (ctx: SocketErrorContext) => void | Promise<void>\n\n/**\n * Function that upgrades an HTTP request to a WebSocket connection.\n *\n * This is platform-specific: Deno provides this natively, while Node.js\n * requires the `upgradeWebSocket` function from this package.\n *\n * @param request - The HTTP request to upgrade\n * @returns An object containing the WebSocket and the upgrade response\n *\n * @example\n * ```typescript\n * // In Node.js, use the provided upgradeWebSocket function\n * import { upgradeWebSocket } from '@atproto/lex-server/nodejs'\n *\n * const router = new LexRouter({ upgradeWebSocket })\n * ```\n */\nexport type UpgradeWebSocket = (request: Request) => {\n /** The WebSocket instance for bidirectional communication. */\n socket: WebSocket\n /** The HTTP response to return (101 Switching Protocols). */\n response: Response\n}\n\nexport type HealthCheckHandler = (\n request: Request,\n) => Awaitable<{ [x: string]: unknown; status: 'ok' }>\n\n/**\n * Configuration options for the {@link LexRouter}.\n *\n * @example\n * ```typescript\n * const options: LexRouterOptions = {\n * upgradeWebSocket,\n * onHandlerError: async ({ error, request, method }) => {\n * console.error(`Error in ${method.nsid}:`, error)\n * await reportToSentry(error)\n * },\n * highWaterMark: 64 * 1024, // 64KB\n * lowWaterMark: 16 * 1024 // 16KB\n * }\n * ```\n */\nexport type LexRouterOptions = {\n /**\n * Function to upgrade HTTP requests to WebSocket connections. Required for\n * subscription methods. Defaults to Deno's built-in\n * {@link globalThis.upgradeWebSocket} if available. For NodeJS, use the\n * homonymous export from `@atproto/lex-server/nodejs`.\n */\n upgradeWebSocket?: UpgradeWebSocket\n /**\n * Callback invoked when an error occurs during request handling. Useful for\n * logging and error reporting. Not called for client-induced errors (e.g.,\n * request abortion).\n */\n onHandlerError?: HandlerErrorHook\n /**\n * Optional hook for handling errors during generation of WebSocket messages.\n */\n onSocketError?: SocketErrorHook\n /**\n * Optional health check handler. If provided, this function will be called\n * for requests to the /xrpc/_health endpoint, allowing for custom health\n * check logic and responses.\n *\n * If not provided, the server will respond to /xrpc/_health requests with a\n * default JSON response of `{ status: 'ok' }`.\n */\n healthCheck?: HealthCheckHandler\n /**\n * Optional fallback handler for requests that are not /xrpc/ paths. Can be\n * used to serve static files or other routes. If not provided, non-/xrpc/\n * requests will return 404 responses.\n */\n fallback?: FetchHandler\n /**\n * High water mark for WebSocket backpressure (in bytes). When buffered data\n * exceeds this, the handler will wait before sending more.\n */\n highWaterMark?: number\n /**\n * Low water mark for WebSocket backpressure (in bytes). The handler resumes\n * sending when buffered data drops below this.\n */\n lowWaterMark?: number\n}\n\n/**\n * XRPC router for handling AT Protocol Lexicon methods.\n *\n * The router handles HTTP routing, parameter parsing, input validation,\n * authentication, and response serialization for XRPC methods. It supports\n * queries (GET), procedures (POST), and subscriptions (WebSocket).\n *\n * @example Setting up a basic XRPC server\n * ```typescript\n * import { LexRouter } from '@atproto/lex-server'\n * import { serve, upgradeWebSocket } from '@atproto/lex-server/nodejs'\n * import { getProfile, createPost, subscribeRepos } from './lexicons.js'\n *\n * const router = new LexRouter({ upgradeWebSocket })\n *\n * // Register a query handler (GET request)\n * router.add(getProfile, async (ctx) => {\n * const profile = await db.getProfile(ctx.params.actor)\n * return { body: profile }\n * })\n *\n * // Register a procedure handler with authentication (POST request)\n * router.add(createPost, {\n * handler: async (ctx) => {\n * const post = await db.createPost(ctx.credentials.did, ctx.input.body)\n * return { body: { uri: post.uri, cid: post.cid } }\n * },\n * auth: async ({ request }) => {\n * return verifyAccessToken(request)\n * }\n * })\n *\n * // Register a subscription handler (WebSocket)\n * router.add(subscribeRepos, async function* (ctx) {\n * for await (const event of eventStream.since(ctx.params.cursor)) {\n * if (ctx.signal.aborted) break\n * yield event\n * }\n * })\n *\n * // Start the server\n * const server = await serve(router, { port: 3000 })\n * console.log('XRPC server listening on port 3000')\n * ```\n *\n * @example Using with service authentication\n * ```typescript\n * import { LexRouter, serviceAuth } from '@atproto/lex-server'\n *\n * const router = new LexRouter()\n *\n * const auth = serviceAuth({\n * audience: 'did:web:api.example.com',\n * unique: async (nonce) => {\n * // Check and record nonce uniqueness\n * return await nonceStore.checkAndAdd(nonce)\n * }\n * })\n *\n * router.add(protectedMethod, {\n * handler: async (ctx) => {\n * // ctx.credentials contains { did, didDocument, jwt }\n * return { body: { callerDid: ctx.credentials.did } }\n * },\n * auth\n * })\n * ```\n */\nexport class LexRouter {\n /** Map of NSID strings to their fetch handlers. */\n readonly handlers: Map<NsidString, FetchHandler> = new Map()\n\n /**\n * Creates a new XRPC router.\n *\n * @param options - Router configuration options\n */\n constructor(readonly options: LexRouterOptions = {}) {}\n\n /**\n * Registers a subscription handler without authentication.\n *\n * @param ns - The Lexicon namespace definition for the subscription\n * @param handler - Async generator function that yields subscription messages\n * @returns This router instance for chaining\n */\n add<M extends Subscription>(\n ns: Main<M>,\n handler: LexRouterSubscriptionHandler<M, void>,\n ): this\n /**\n * Registers a subscription handler with authentication.\n *\n * @param ns - The Lexicon namespace definition for the subscription\n * @param config - Configuration object with handler and auth function\n * @returns This router instance for chaining\n */\n add<M extends Subscription, Credentials>(\n ns: Main<M>,\n config: LexRouterSubscriptionConfig<M, Credentials>,\n ): this\n /**\n * Registers a query or procedure handler without authentication.\n *\n * @param ns - The Lexicon namespace definition for the method\n * @param handler - Handler function that processes requests\n * @returns This router instance for chaining\n */\n add<M extends Query | Procedure>(\n ns: Main<M>,\n handler: LexRouterMethodHandler<M, void>,\n ): this\n /**\n * Registers a query or procedure handler with authentication.\n *\n * @param ns - The Lexicon namespace definition for the method\n * @param config - Configuration object with handler and auth function\n * @returns This router instance for chaining\n */\n add<M extends Query | Procedure, Credentials>(\n ns: Main<M>,\n config: LexRouterMethodConfig<M, Credentials>,\n ): this\n /**\n * Registers a Lexicon method handler.\n *\n * This is the unified overload that accepts any method type with optional authentication.\n *\n * @param ns - The Lexicon namespace definition\n * @param config - Handler function or configuration object\n * @returns This router instance for chaining\n *\n * @throws {TypeError} If a method with the same NSID is already registered\n *\n * @example\n * ```typescript\n * // Register without auth (credentials will be void)\n * router.add(myQuery, async (ctx) => {\n * return { body: { data: 'value' } }\n * })\n *\n * // Register with auth\n * router.add(myProcedure, {\n * handler: async (ctx) => {\n * console.log('Caller:', ctx.credentials.userId)\n * return { body: { success: true } }\n * },\n * auth: async ({ request }) => ({ userId: await verifyToken(request) })\n * })\n * ```\n */\n add<M extends LexMethod, Credentials = unknown>(\n ns: Main<M>,\n config: M extends Subscription\n ?\n | LexRouterSubscriptionHandler<M, Credentials>\n | LexRouterSubscriptionConfig<M, Credentials>\n : M extends Query | Procedure\n ?\n | LexRouterMethodHandler<M, Credentials>\n | LexRouterMethodConfig<M, Credentials>\n : never,\n ): this\n add<M extends LexMethod>(\n ns: Main<M>,\n config:\n | LexRouterSubscriptionHandler<any, any>\n | LexRouterSubscriptionConfig<any, any>\n | LexRouterMethodHandler<any, any>\n | LexRouterMethodConfig<any, any>,\n ) {\n const method = getMain(ns)\n const nsid = normalizeNsid(method.nsid)\n\n if (this.handlers.has(nsid)) {\n throw new TypeError(`Method ${method.nsid} already registered`)\n }\n\n const methodConfig =\n typeof config === 'function'\n ? { handler: config, auth: undefined }\n : config\n\n const handler: FetchHandler =\n method.type === 'subscription'\n ? this.buildSubscriptionHandler(\n method,\n methodConfig.handler as LexRouterSubscriptionHandler<any, any>,\n methodConfig.auth,\n )\n : this.buildMethodHandler(\n method,\n methodConfig.handler as LexRouterMethodHandler<any, any>,\n methodConfig.auth,\n )\n\n this.handlers.set(nsid, handler)\n\n return this\n }\n\n private buildMethodHandler<Method extends Query | Procedure, Credentials>(\n method: Method,\n methodHandler: LexRouterMethodHandler<Method, Credentials>,\n auth?: LexRouterAuth<Credentials, Method>,\n ): FetchHandler {\n const getInput = (\n method.type === 'procedure'\n ? getProcedureInput.bind(method)\n : getQueryInput.bind(method)\n ) as (request: Request) => Promise<InferMethodInput<Method, Body>>\n\n return async (request, connection) => {\n // @NOTE CORS requests should be handled by a middleware before reaching\n // this point.\n if (\n (method.type === 'procedure' && request.method !== 'POST') ||\n (method.type === 'query' &&\n request.method !== 'GET' &&\n request.method !== 'HEAD')\n ) {\n return invalidRequestResponse('Method not allowed', 405)\n }\n\n try {\n const url = new URL(request.url)\n const params = method.parameters.fromURLSearchParams(\n url.searchParams,\n ) as InferMethodParams<Method>\n\n const credentials = auth\n ? await auth({ method, params, request, connection })\n : (undefined as Credentials)\n\n const input = await getInput(request)\n\n const output = await methodHandler({\n credentials,\n params,\n input,\n request,\n connection,\n signal: request.signal,\n })\n\n if (output instanceof Response) {\n return output\n }\n\n // @TODO add validation of output based on method.output.schema?\n\n if (output.body === undefined && output.encoding === undefined) {\n return new Response(null, { status: 200, headers: output.headers })\n }\n\n if (method.output?.encoding === 'application/json') {\n return Response.json(lexToJson(output.body as LexValue), {\n status: 200,\n headers: output.headers,\n })\n }\n\n const headers = new Headers(output.headers)\n headers.set('content-type', output.encoding!)\n return new Response(output.body as BodyInit | null | undefined, {\n status: 200,\n headers,\n })\n } catch (error) {\n return this.handlerError(request, method, error)\n }\n }\n }\n\n private buildSubscriptionHandler<Method extends Subscription, Credentials>(\n method: Method,\n methodHandler: LexRouterSubscriptionHandler<Method, Credentials>,\n auth?: LexRouterAuth<Credentials, Method>,\n ): FetchHandler {\n const {\n onSocketError,\n upgradeWebSocket = (globalThis as any).Deno?.upgradeWebSocket as\n | UpgradeWebSocket\n | undefined,\n } = this.options\n if (!upgradeWebSocket) {\n throw new TypeError(\n 'WebSocket upgrade not supported in this environment. Please provide an upgradeWebSocket option when creating the LexRouter.',\n )\n }\n\n return async (request, connection) => {\n if (request.method !== 'GET') {\n return invalidRequestResponse('Method not allowed', 405)\n }\n\n if (\n request.headers.get('connection')?.toLowerCase() !== 'upgrade' ||\n request.headers.get('upgrade')?.toLowerCase() !== 'websocket'\n ) {\n return invalidRequestResponse(\n 'XRPC subscriptions are only available over WebSocket',\n 426,\n {\n Connection: 'Upgrade',\n Upgrade: 'websocket',\n },\n )\n }\n\n if (request.signal.aborted) {\n return invalidRequestResponse('Request aborted', 499)\n }\n\n try {\n const { response, socket } = upgradeWebSocket(request)\n\n // @NOTE We are using a distinct signal than request.signal because that\n // signal may get aborted before the WebSocket is closed (this is the\n // case with Deno).\n const abortController = new AbortController()\n const { signal } = abortController\n const abort = () => abortController.abort()\n\n const onOpen = async () => {\n try {\n const url = new URL(request.url)\n const params = method.parameters.fromURLSearchParams(\n url.searchParams,\n ) as InferMethodParams<Method>\n\n const credentials: Credentials = auth\n ? await auth({ method, params, request, connection })\n : (undefined as Credentials)\n\n signal.throwIfAborted()\n\n const iterable = methodHandler({\n credentials,\n params,\n input: undefined as InferMethodInput<Method, Body>,\n request,\n connection,\n signal,\n })\n\n const iterator = iterable[Symbol.asyncIterator]()\n\n if (iterator.return) {\n signal.addEventListener(\n 'abort',\n () => {\n // @NOTE if iterator.return() throws, and no onSocketError is\n // provided, or if onSocketError itself throws, the error will\n // be unhandled, causing the process to crash. This is\n // intentional, as it surfaces critical errors that occur\n // during cleanup of the subscription.\n\n void new Promise((resolve) => {\n // Wrapping in new Promise to catch any potential sync errors thrown by iterator.return()\n resolve(iterator.return!())\n }).catch(\n onSocketError\n ? (error) => onSocketError({ request, method, error })\n : null,\n )\n },\n {\n once: true,\n },\n )\n }\n\n while (!signal.aborted && socket.readyState === 1) {\n const result = await iterator.next()\n if (result.done) break\n\n // @TODO add validation of output based on method.output.schema?\n\n const data = encodeMessageFrame(method, result.value)\n\n socket.send(data)\n\n // Apply backpressure by waiting for the buffered data to drain\n // before generating the next message\n await drainWebsocket(socket, signal, this.options)\n }\n\n if (socket.readyState === 1) {\n socket.close(1000)\n }\n } catch (error) {\n // If the socket is still open, send an error frame before closing\n if (socket.readyState === 1) {\n const isLexError = error instanceof LexError\n\n // https://www.rfc-editor.org/rfc/rfc6455#section-7.4.1\n const code =\n isLexError && method.errors?.includes(error.error)\n ? 1008 // Policy Violation for known LexErrors\n : 1011 // Internal Error for unexpected errors\n\n if (isLexError) {\n socket.send(encodeErrorFrame(error.toJSON()))\n socket.close(code, error.error)\n } else {\n const error = 'InternalServerError'\n const message = 'An internal error occurred'\n socket.send(encodeErrorFrame({ error, message }))\n socket.close(code, error)\n }\n }\n\n if (onSocketError && !isAbortReason(signal, error)) {\n await onSocketError({ request, method, error })\n }\n } finally {\n abortController.abort()\n }\n }\n\n socket.addEventListener('error', abort)\n socket.addEventListener('close', abort)\n socket.addEventListener('open', onOpen)\n socket.addEventListener('message', onMessage)\n\n return response\n } catch (error) {\n return this.handlerError(request, method, error)\n }\n }\n }\n\n private async handlerError(\n request: Request,\n method: LexMethod,\n cause: unknown,\n ) {\n // Only report unexpected processing errors\n if (isAbortReason(request.signal, cause)) {\n return Response.json({ error: 'RequestAborted' }, { status: 499 })\n }\n\n const error = LexServerError.from(cause)\n\n const { onHandlerError } = this.options\n if (onHandlerError) await onHandlerError({ error, request, method })\n\n return error.toResponse()\n }\n\n /**\n * The main fetch handler for processing XRPC requests.\n *\n * Routes incoming requests to the appropriate method handler based on the\n * NSID in the URL path. Returns appropriate error responses for invalid\n * paths or unimplemented methods.\n *\n * This handler can be used directly with HTTP servers that support the\n * fetch API pattern, or converted to a Node.js request listener using\n * `toRequestListener()`.\n *\n * @param request - The incoming HTTP request\n * @param connection - Optional connection metadata\n * @returns A promise resolving to the HTTP response\n *\n * @example\n * ```typescript\n * // Use with Deno\n * Deno.serve(router.fetch)\n *\n * // Use with Bun\n * Bun.serve({ fetch: router.fetch })\n *\n * // Use with Node.js\n * import { toRequestListener } from '@atproto/lex-server/nodejs'\n * const listener = toRequestListener(router.fetch)\n * http.createServer(listener).listen(3000)\n * ```\n */\n fetch: FetchHandler = async (\n request: Request,\n connection?: ConnectionInfo,\n ): Promise<Response> => {\n const { pathname } = new URL(request.url)\n const atprotoProxy = request.headers.get('atproto-proxy')\n\n if (!pathname.startsWith(XRPC_PATH_PREFIX)) {\n // Handle non XRPC paths\n const { fallback } = this.options\n if (fallback) return fallback(request, connection)\n return new Response('Not Found', { status: 404 })\n }\n\n if (pathname === XRPC_HEALTH_CHECK_PATH) {\n if (request.method !== 'GET') {\n return invalidRequestResponse('Method not allowed', 405)\n }\n if (atprotoProxy != null) {\n return invalidRequestResponse(\n 'atproto-proxy header is not allowed on health check endpoint',\n )\n }\n\n const { healthCheck } = this.options\n const data = healthCheck ? await healthCheck(request) : { status: 'ok' }\n\n return Response.json(data)\n }\n\n const subPath = pathname.slice(XRPC_PATH_PREFIX.length)\n\n if (!isNsidString(subPath)) {\n return invalidRequestResponse('Invalid NSID in URL path')\n }\n\n const nsid = normalizeNsid(subPath)\n if (atprotoProxy == null) {\n const handler = this.handlers.get(nsid)\n if (handler) return handler(request, connection)\n } else {\n // Handle service proxying logic.\n\n const proxyInfo = parseAtprotoProxyHeader(atprotoProxy)\n if (!proxyInfo) {\n return invalidRequestResponse(\n `Invalid atproto-proxy header value: ${atprotoProxy}`,\n )\n }\n\n // @TODO actually implement service proxying logic here. The reason it was\n // not done already is because we want to perform all the heavy lifting\n // here, while still allowing the possibility to override the endpoint\n // resolution, etc.\n\n // @NOTE see ./service-auth.ts for potential common code (did resolver, etc.)\n }\n\n return Response.json(\n {\n error: 'MethodNotImplemented',\n message: `XRPC method \"${nsid}\" not implemented on this server`,\n },\n { status: 501 },\n )\n }\n}\n\nasync function getProcedureInput<M extends Procedure>(\n this: M,\n request: Request,\n): Promise<InferMethodInput<M, Body>> {\n const encodingRaw = request.headers\n .get('content-type')\n ?.split(';')[0]\n .trim()\n .toLowerCase()\n\n const encoding =\n encodingRaw ||\n // If the caller did not provide a content-type, but the method\n // expects an input, assume binary\n (request.body != null && this.input.encoding != null\n ? 'application/octet-stream'\n : undefined)\n\n if (!this.input.matchesEncoding(encoding)) {\n throw new LexServerError(400, {\n error: 'InvalidRequest',\n message: `Invalid content-type: ${encoding}`,\n })\n }\n\n if (this.input.encoding === 'application/json') {\n // @TODO limit size?\n const data = lexParse(await request.text())\n const body = this.input.schema ? this.input.schema.parse(data) : data\n return { encoding, body } as InferMethodInput<M, Body>\n } else if (this.input.encoding) {\n const body: Body = request\n return { encoding, body } as InferMethodInput<M, Body>\n } else {\n return undefined as InferMethodInput<M, Body>\n }\n}\n\nasync function getQueryInput<M extends Query>(\n this: M,\n request: Request,\n): Promise<InferMethodInput<M, Body>> {\n if (\n request.body ||\n request.headers.has('content-type') ||\n request.headers.has('content-length')\n ) {\n throw new LexServerError(400, {\n error: 'InvalidRequest',\n message: 'GET requests must not have a body',\n })\n }\n\n return undefined as InferMethodInput<M, Body>\n}\n\nfunction onMessage(this: WebSocket, _event: unknown) {\n const error = 'InvalidRequest'\n const message = 'XRPC subscriptions do not accept messages'\n this.send(encodeErrorFrame({ error, message }))\n // 1003 indicates that an endpoint is terminating the connection\n // because it has received a type of data it cannot accept (e.g., an\n // endpoint that understands only text data MAY send this if it\n // receives a binary message).\n this.close(1003, error)\n}\n\n// Pre-encoded frame header for error frames\nconst ERROR_FRAME_HEADER = /*#__PURE__*/ encode({ op: -1 })\n\nfunction encodeErrorFrame(errorData: LexErrorData): Uint8Array<ArrayBuffer> {\n return ui8Concat([ERROR_FRAME_HEADER, encode(errorData)])\n}\n\n// Pre-encoded frame header for message frames with unknown type\nconst UNKNOWN_MESSAGE_FRAME_HEADER = /*#__PURE__*/ encode({ op: 1 })\n\nfunction encodeMessageFrame(\n method: Subscription,\n value: LexValue,\n): Uint8Array<ArrayBuffer> {\n if (isPlainObject(value) && typeof value.$type === 'string') {\n const { $type, ...rest } = value\n return ui8Concat([\n encode({\n op: 1,\n t:\n // If $type starts with `nsid#`, strip the NSID prefix\n $type.charCodeAt(0) !== 0x23 && // '#'\n $type.charCodeAt(method.nsid.length) === 0x23 && // '#'\n $type.startsWith(method.nsid)\n ? $type.slice(method.nsid.length)\n : $type,\n }),\n encode(rest),\n ])\n }\n\n return ui8Concat([UNKNOWN_MESSAGE_FRAME_HEADER, encode(value)])\n}\n\nfunction isAbortReason(signal: AbortSignal, error: unknown): boolean {\n return (\n signal.aborted &&\n signal.reason != null &&\n error instanceof Error &&\n (error === signal.reason || error.cause === signal.reason)\n )\n}\n\nexport type ServiceProxyInfo = {\n did: DidString\n serviceId: string\n}\n\nfunction parseAtprotoProxyHeader(value: string): ServiceProxyInfo | null {\n // /!\\ Hot path\n\n // (fast) sanity check to avoid unnecessary parsing for non-DID values\n if (!value.startsWith('did:')) return null\n\n // The format is expected to be `did:example:service#serviceId`\n const hashIndex = value.indexOf('#')\n if (hashIndex === -1) return null\n\n const fragmentIndex = hashIndex + 1\n // Basic validation if the fragment\n if (fragmentIndex === value.length) return null\n if (value.includes('#', fragmentIndex)) return null\n if (value.includes(' ', fragmentIndex)) return null\n\n const did = value.slice(0, hashIndex)\n if (!isDidString(did)) return null\n\n const serviceId = value.slice(fragmentIndex)\n return { did, serviceId }\n}\n\nfunction normalizeNsid(nsid: NsidString): NsidString {\n const lastDotIdx = nsid.lastIndexOf('.')\n\n // The domain name part of the NSID is case-insensitive, but the last part is\n // case-sensitive. Normalize the domain part to lowercase.\n if (lastDotIdx !== -1 && hasUpperCase(nsid, 0, lastDotIdx)) {\n return `${nsid.slice(0, lastDotIdx).toLowerCase()}.${nsid.slice(lastDotIdx + 1)}` as NsidString\n }\n\n return nsid\n}\n\nfunction hasUpperCase(str: string, start = 0, end = str.length): boolean {\n for (let i = start; i < end; i++) {\n const code = str.charCodeAt(i)\n if (code >= 0x41 && code <= 0x5a) {\n return true\n }\n }\n return false\n}\n\nfunction invalidRequestResponse(\n message: string,\n status = 400,\n headers?: HeadersInit,\n): Response {\n return Response.json(\n {\n error: 'InvalidRequest',\n message,\n },\n { status, headers },\n )\n}\n"]}
|
|
@@ -1,7 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.drainWebsocket = drainWebsocket;
|
|
4
|
-
const sleep_js_1 = require("./sleep.js");
|
|
1
|
+
import { abortableSleep } from './sleep.js';
|
|
5
2
|
/**
|
|
6
3
|
* Performs polling based backpressure management for a WebSocket connection. If
|
|
7
4
|
* the amount of buffered data exceeds the specified high water mark, this
|
|
@@ -9,7 +6,7 @@ const sleep_js_1 = require("./sleep.js");
|
|
|
9
6
|
* before resolving. This is useful for preventing memory issues when sending
|
|
10
7
|
* large amounts of data over a WebSocket connection.
|
|
11
8
|
*/
|
|
12
|
-
async function drainWebsocket(socket, signal, { highWaterMark = 250_000, // 250 KB
|
|
9
|
+
export async function drainWebsocket(socket, signal, { highWaterMark = 250_000, // 250 KB
|
|
13
10
|
lowWaterMark = 50_000, // 50 KB
|
|
14
11
|
} = {}) {
|
|
15
12
|
if (socket.bufferedAmount > highWaterMark) {
|
|
@@ -20,7 +17,7 @@ lowWaterMark = 50_000, // 50 KB
|
|
|
20
17
|
while (socket.readyState === 1 &&
|
|
21
18
|
socket.bufferedAmount !== 0 &&
|
|
22
19
|
socket.bufferedAmount > lowWaterMark) {
|
|
23
|
-
await
|
|
20
|
+
await abortableSleep(10, signal);
|
|
24
21
|
}
|
|
25
22
|
}
|
|
26
23
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"drain-websocket.js","sourceRoot":"","sources":["../../src/lib/drain-websocket.ts"],"names":[],"mappings":"
|
|
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;KAI7B,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"]}
|
package/dist/lib/sleep.js
CHANGED
|
@@ -1,7 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.abortableSleep = abortableSleep;
|
|
4
|
-
async function abortableSleep(ms, signal) {
|
|
1
|
+
export async function abortableSleep(ms, signal) {
|
|
5
2
|
signal.throwIfAborted();
|
|
6
3
|
return new Promise((resolve, reject) => {
|
|
7
4
|
const cleanup = () => {
|
package/dist/lib/sleep.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sleep.js","sourceRoot":"","sources":["../../src/lib/sleep.ts"],"names":[],"mappings":"
|
|
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"]}
|
|
@@ -1,6 +1,3 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.formatWWWAuthenticateHeader = formatWWWAuthenticateHeader;
|
|
4
1
|
/**
|
|
5
2
|
* Formats a WWWAuthenticate object into an HTTP header string.
|
|
6
3
|
*
|
|
@@ -29,7 +26,7 @@ exports.formatWWWAuthenticateHeader = formatWWWAuthenticateHeader;
|
|
|
29
26
|
* // Returns: 'Bearer realm="api"' (undefined values are omitted)
|
|
30
27
|
* ```
|
|
31
28
|
*/
|
|
32
|
-
function formatWWWAuthenticateHeader(wwwAuthenticate) {
|
|
29
|
+
export function formatWWWAuthenticateHeader(wwwAuthenticate) {
|
|
33
30
|
const challenges = [];
|
|
34
31
|
for (const [scheme, params] of Object.entries(wwwAuthenticate)) {
|
|
35
32
|
if (params == null)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"www-authenticate.js","sourceRoot":"","sources":["../../src/lib/www-authenticate.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,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;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"]}
|
package/dist/nodejs.d.ts
CHANGED
|
@@ -130,7 +130,7 @@ export interface HandlerObject {
|
|
|
130
130
|
* const app = express()
|
|
131
131
|
*
|
|
132
132
|
* // Mount the XRPC router
|
|
133
|
-
* app.use(
|
|
133
|
+
* app.use(toRequestListener(router.fetch))
|
|
134
134
|
* ```
|
|
135
135
|
*/
|
|
136
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> & {
|
package/dist/nodejs.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nodejs.d.ts","sourceRoot":"","sources":["../src/nodejs.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,eAAe,EAEf,MAAM,IAAI,UAAU,EACpB,aAAa,EACb,cAAc,EAEf,MAAM,WAAW,CAAA;AAClB,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;
|
|
1
|
+
{"version":3,"file":"nodejs.d.ts","sourceRoot":"","sources":["../src/nodejs.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,eAAe,EAEf,MAAM,IAAI,UAAU,EACpB,aAAa,EACb,cAAc,EAEf,MAAM,WAAW,CAAA;AAClB,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AASxC,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,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|
-
const
|
|
9
|
-
|
|
10
|
-
const node_stream_1 = require("node:stream");
|
|
11
|
-
const promises_1 = require("node:stream/promises");
|
|
12
|
-
const http_terminator_1 = require("http-terminator");
|
|
13
|
-
const ws_1 = require("ws");
|
|
1
|
+
import { once } from 'node:events';
|
|
2
|
+
import { createServer as createHttpServer, } from 'node:http';
|
|
3
|
+
import { Readable } from 'node:stream';
|
|
4
|
+
import { pipeline } from 'node:stream/promises';
|
|
5
|
+
// eslint-disable-next-line import/default, import/no-named-as-default-member
|
|
6
|
+
import httpTerminator from 'http-terminator';
|
|
7
|
+
// eslint-disable-next-line import/no-named-as-default-member
|
|
8
|
+
const { createHttpTerminator } = httpTerminator;
|
|
9
|
+
import { WebSocket as WebSocketPonyfill, WebSocketServer } from 'ws';
|
|
14
10
|
// @ts-expect-error
|
|
15
11
|
Symbol.asyncDispose ??= Symbol.for('Symbol.asyncDispose');
|
|
16
12
|
const kResponseWs = Symbol.for('@atproto/lex-server:WebSocket');
|
|
@@ -49,7 +45,7 @@ function isUpgradeRequest(request, upgrade) {
|
|
|
49
45
|
* })
|
|
50
46
|
* ```
|
|
51
47
|
*/
|
|
52
|
-
function upgradeWebSocket(request) {
|
|
48
|
+
export function upgradeWebSocket(request) {
|
|
53
49
|
if (!isUpgradeRequest(request, 'websocket')) {
|
|
54
50
|
throw new TypeError('upgradeWebSocket() expects a WebSocket upgrade');
|
|
55
51
|
}
|
|
@@ -67,7 +63,7 @@ function upgradeWebSocket(request) {
|
|
|
67
63
|
writable: false,
|
|
68
64
|
});
|
|
69
65
|
// @ts-expect-error
|
|
70
|
-
const socket = new
|
|
66
|
+
const socket = new WebSocketPonyfill(null, undefined, {
|
|
71
67
|
autoPong: true,
|
|
72
68
|
});
|
|
73
69
|
// Attach the WebSocket to the response for later retrieval
|
|
@@ -85,7 +81,7 @@ function handleWebSocketUpgrade(req, response) {
|
|
|
85
81
|
if (!ws)
|
|
86
82
|
throw new TypeError('Response not created by upgradeWebSocket()');
|
|
87
83
|
// Create a one time use WebSocketServer to handle the upgrade
|
|
88
|
-
const wss = new
|
|
84
|
+
const wss = new WebSocketServer({
|
|
89
85
|
autoPong: true,
|
|
90
86
|
noServer: true,
|
|
91
87
|
clientTracking: false,
|
|
@@ -137,7 +133,7 @@ function handleWebSocketUpgrade(req, response) {
|
|
|
137
133
|
* })
|
|
138
134
|
* ```
|
|
139
135
|
*/
|
|
140
|
-
async function sendResponse(req, res, response) {
|
|
136
|
+
export async function sendResponse(req, res, response) {
|
|
141
137
|
// Invalid usage
|
|
142
138
|
if (res.headersSent) {
|
|
143
139
|
throw new TypeError('Response has already been sent');
|
|
@@ -151,8 +147,8 @@ async function sendResponse(req, res, response) {
|
|
|
151
147
|
res.setHeader(key, value);
|
|
152
148
|
}
|
|
153
149
|
if (response.body != null && req.method !== 'HEAD') {
|
|
154
|
-
const stream =
|
|
155
|
-
await
|
|
150
|
+
const stream = Readable.fromWeb(response.body);
|
|
151
|
+
await pipeline(stream, res);
|
|
156
152
|
}
|
|
157
153
|
else {
|
|
158
154
|
await response.body?.cancel();
|
|
@@ -247,7 +243,7 @@ function toBody(req) {
|
|
|
247
243
|
req.headers['content-length'] == null) {
|
|
248
244
|
return null;
|
|
249
245
|
}
|
|
250
|
-
return
|
|
246
|
+
return Readable.toWeb(req);
|
|
251
247
|
}
|
|
252
248
|
async function handleRequest(req, res, fetchHandler) {
|
|
253
249
|
const request = toRequest(req);
|
|
@@ -291,10 +287,10 @@ function toConnectionInfo(req) {
|
|
|
291
287
|
* const app = express()
|
|
292
288
|
*
|
|
293
289
|
* // Mount the XRPC router
|
|
294
|
-
* app.use(
|
|
290
|
+
* app.use(toRequestListener(router.fetch))
|
|
295
291
|
* ```
|
|
296
292
|
*/
|
|
297
|
-
function toRequestListener(fetchHandler) {
|
|
293
|
+
export function toRequestListener(fetchHandler) {
|
|
298
294
|
return ((req, res, next) => {
|
|
299
295
|
handleRequest(req, res, fetchHandler).catch((err) => {
|
|
300
296
|
if (next)
|
|
@@ -350,11 +346,11 @@ function toRequestListener(fetchHandler) {
|
|
|
350
346
|
* })
|
|
351
347
|
* ```
|
|
352
348
|
*/
|
|
353
|
-
function createServer(handler, options = {}) {
|
|
349
|
+
export function createServer(handler, options = {}) {
|
|
354
350
|
const fetchHandler = typeof handler === 'function' ? handler : handler.fetch.bind(handler);
|
|
355
351
|
const listener = toRequestListener(fetchHandler);
|
|
356
|
-
const server = (
|
|
357
|
-
const terminator =
|
|
352
|
+
const server = createHttpServer(options, listener);
|
|
353
|
+
const terminator = createHttpTerminator({
|
|
358
354
|
server: server,
|
|
359
355
|
gracefulTerminationTimeout: options?.gracefulTerminationTimeout,
|
|
360
356
|
});
|
|
@@ -440,10 +436,10 @@ function createServer(handler, options = {}) {
|
|
|
440
436
|
* }
|
|
441
437
|
* ```
|
|
442
438
|
*/
|
|
443
|
-
async function serve(handler, options) {
|
|
439
|
+
export async function serve(handler, options) {
|
|
444
440
|
const server = createServer(handler, options);
|
|
445
441
|
server.listen(options);
|
|
446
|
-
await
|
|
442
|
+
await once(server, 'listening');
|
|
447
443
|
return server;
|
|
448
444
|
}
|
|
449
445
|
//# sourceMappingURL=nodejs.js.map
|