{"name":"@whatwg-node/server","version":"0.9.71","author":{"name":"Arda TANRIKULU","email":"ardatanrikulu@gmail.com"},"license":"MIT","_id":"@whatwg-node/server@0.9.71","maintainers":[{"name":"ardatan","email":"ardatanrikulu@gmail.com"}],"homepage":"https://github.com/ardatan/whatwg-node#readme","bugs":{"url":"https://github.com/ardatan/whatwg-node/issues"},"dist":{"shasum":"5715011b58ab8a0a8abb25759a426ff50d2dce4b","tarball":"http://registry-npm.ywwl.com/@whatwg-node/server/download/@whatwg-node/server-0.9.71.tgz","fileCount":39,"integrity":"sha512-ueFCcIPaMgtuYDS9u0qlUoEvj6GiSsKrwnOLPp9SshqjtcRaR1IEHRjoReq3sXNydsF5i0ZnmuYgXq9dV53t0g==","signatures":[{"sig":"MEYCIQCrm6PLPm8WpLl3qc/h7OCDnH7c6zvyM6tiSRKn08GADQIhAPgCOxyasel4zDGjQqlB6OEtuku8Et+/bMEWh6mdwBH7","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/@whatwg-node%2fserver@0.9.71","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}},"unpackedSize":162789,"size":26570,"noattachment":false,"key":"/@whatwg-node/server/-/@whatwg-node/server-0.9.71.tgz"},"main":"cjs/index.js","type":"module","module":"esm/index.js","engines":{"node":">=18.0.0"},"exports":{".":{"import":{"types":"./typings/index.d.ts","default":"./esm/index.js"},"default":{"types":"./typings/index.d.ts","default":"./esm/index.js"},"require":{"types":"./typings/index.d.cts","default":"./cjs/index.js"}},"./package.json":"./package.json"},"gitHead":"70b4590674330d9042d5dcb203e97033e965c0ab","typings":"typings/index.d.ts","_npmUser":{"name":"ardatan","email":"ardatanrikulu@gmail.com"},"repository":{"url":"git+https://github.com/ardatan/whatwg-node.git","type":"git","directory":"packages/server"},"typescript":{"definition":"typings/index.d.ts"},"_npmVersion":"10.9.2","description":"Fetch API compliant HTTP Server adapter","directories":{},"sideEffects":false,"_nodeVersion":"22.14.0","dependencies":{"tslib":"^2.6.3","@whatwg-node/fetch":"^0.10.5","@whatwg-node/disposablestack":"^0.0.6","@whatwg-node/promise-helpers":"^1.2.2"},"_hasShrinkwrap":false,"_npmOperationalInternal":{"tmp":"tmp/server_0.9.71_1740968736758_0.14369369304707114","host":"s3://npm-registry-packages-npm-production"},"readme":"# WHATWG Node Generic Server Adapter\n\n`@whatwg-node/server` helps you to create a generic server implementation by using WHATWG Fetch API\nfor Node.js, AWS Lambda, Cloudflare Workers, Deno, Express, Fastify, Koa, Next.js and Sveltekit.\n\nOnce you create an adapter with `createServerAdapter`, you don't need to install any other platform\nspecific package since the generic adapter will handle it automatically.\n\n## How to start\n\nLet's create a basic Hello World server adapter.\n\n```ts\n// myServerAdapter.ts\nimport { createServerAdapter } from '@whatwg-node/server'\n\nexport default createServerAdapter((request: Request) => {\n  return new Response(`Hello World!`, { status: 200 })\n})\n```\n\n## Integrations\n\nYou can use your server adapter with the following integrations:\n\n### Node.js\n\n[Node.js](https://nodejs.org/api/http.html) is the most popular server side JavaScript runtime.\n\n```ts\nimport { createServer } from 'http'\nimport myServerAdapter from './myServerAdapter'\n\n// You can create your Node server instance by using our adapter\nconst nodeServer = createServer(myServerAdapter)\n// Then start listening on some port\nnodeServer.listen(4000)\n```\n\n### AWS Lambda\n\nAWS Lambda is a serverless computing platform that makes it easy to build applications that run on\nthe AWS cloud. Our adapter is platform agnostic so they can fit together easily. In order to reduce\nthe boilerplate we prefer to use\n[Serverless Express from Vendia](https://github.com/vendia/serverless-express).\n\n```ts\nimport { Buffer } from 'node:buffer'\nimport { pipeline } from 'node:stream/promises'\nimport type { Context, LambdaFunctionURLEvent } from 'aws-lambda'\nimport myServerAdapter from './myServerAdapter'\n\ninterface ServerContext {\n  event: LambdaFunctionURLEvent\n  lambdaContext: Context\n  res: awslambda.HttpResponseStream\n}\n\nexport const handler = awslambda.streamifyResponse(async function handler(\n  event: LambdaFunctionURLEvent,\n  res,\n  lambdaContext\n) {\n  const response = await myServerAdapter.fetch(\n    // Construct the URL\n    `https://${event.requestContext.domainName}${event.requestContext.http.path}?${event.rawQueryString}`,\n    {\n      method: event.requestContext.http.method,\n      headers: event.headers as HeadersInit,\n      // Parse the body if needed\n      body:\n        event.body && event.isBase64Encoded ? Buffer.from(event.body, 'base64') : event.body || null\n    },\n    {\n      event,\n      res,\n      lambdaContext\n    }\n  )\n\n  // Attach the metadata to the response stream\n  res = awslambda.HttpResponseStream.from(res, {\n    statusCode: response.status,\n    headers: Object.fromEntries(response.headers.entries())\n  })\n\n  if (response.body) {\n    // @ts-expect-error - Pipe the response body to the response stream\n    await pipeline(response.body, res)\n  }\n\n  // End the response stream\n  res.end()\n})\n```\n\n### Cloudflare Workers\n\nCloudflare Workers provides a serverless execution environment that allows you to create entirely\nnew applications or augment existing ones without configuring or maintaining infrastructure. It uses\nFetch API already so we can use our adapter as an event listener like below;\n\n```ts\nimport myServerAdapter from './myServerAdapter'\n\nself.addEventListener('fetch', myServerAdapter)\n```\n\n### Deno\n\n[Deno is a simple, modern and secure runtime for JavaScript and TypeScript that uses V8 and is built in Rust](https://deno.land/).\nYou can use our adapter as a Deno request handler like below;\n\n```ts\nimport myServerAdapter from './myServerAdapter.ts'\n\nDeno.serve(myServerAdapter)\n```\n\n### Express\n\n[Express is the most popular web framework for Node.js.](https://expressjs.com/) It is a minimalist\nframework that provides a robust set of features to handle HTTP on Node.js applications.\n\nYou can easily integrate your adapter into your Express application with a few lines of code.\n\n```ts\nimport express from 'express'\nimport myServerAdapter from './myServerAdapter'\n\nconst app = express()\n\n// Bind our adapter to `/mypath` endpoint\napp.use('/mypath', myServerAdapter)\n\napp.listen(4000, () => {\n  console.log('Running the server at http://localhost:4000/mypath')\n})\n```\n\n### Fastify\n\n[Fastify is one of the popular HTTP server frameworks for Node.js.](https://www.fastify.io/). You\ncan use your adapter easily with Fastify.\n\nSo you can benefit from the powerful plugins of Fastify ecosystem.\n[See the ecosystem](https://www.fastify.io/docs/latest/Guides/Ecosystem/)\n\n```ts\nimport fastify, { FastifyReply, FastifyRequest } from 'fastify'\nimport myServerAdapter from './myServerAdapter'\n\n// This is the fastify instance you have created\nconst app = fastify({ logger: true })\n\n/**\n * We pass the incoming HTTP request to our adapter\n * and handle the response using Fastify's `reply` API\n * Learn more about `reply` https://www.fastify.io/docs/latest/Reply/\n **/\napp.route({\n  url: '/mypath',\n  method: ['GET', 'POST', 'OPTIONS'],\n  handler: (req, reply) =>\n    myServerAdapter.handleNodeRequestAndResponse(req, reply, {\n      req,\n      reply\n    })\n})\n\napp.listen(4000)\n```\n\n### Koa\n\n[Koa is another Node.js server framework designed by the team behind Express, which aims to be a smaller, more expressive.](https://koajs.com/)\nYou can add your adapter to your Koa application with a few lines of code then\n[benefit middlewares written for Koa.](https://github.com/koajs/koa/wiki)\n\n```ts\nimport Koa from 'koa'\nimport myServerAdapter from './myServerAdapter'\n\nconst app = new Koa()\n\napp.use(async ctx => {\n  const response = await myServerAdapter.handleNodeRequestAndResponse(ctx.request, ctx.res, ctx)\n\n  // Set status code\n  ctx.status = response.status\n\n  // Set headers\n  response.headers.forEach((value, key) => {\n    ctx.append(key, value)\n  })\n\n  ctx.body = response.body\n})\n\napp.listen(4000, () => {\n  console.log('Running the server at http://localhost:4000')\n})\n```\n\n### Next.js\n\n[Next.js](https://nextjs.org/) is a web framework that allows you to build websites very quickly and\nour new server adapter can be integrated with Next.js easily as an API Route.\n\n```ts\n// pages/api/myEndpoint.ts\n// Next.js API route support: https://nextjs.org/docs/api-routes/introduction\nimport type { NextApiRequest, NextApiResponse } from 'next'\nimport myServerAdapter from './myServerAdapter'\n\nexport const config = {\n  api: {\n    // Disable body parsing if you expect a request other than JSON\n    bodyParser: false\n  }\n}\n\nexport default myServerAdapter\n```\n\n### SvelteKit\n\n[SvelteKit](https://kit.svelte.dev/) is the fastest way to build svelte apps. It is very simple, and\nlet you build frontend & backend in a single place\n\n```ts\nimport myServerAdapter from './myServerAdapter'\n\nexport { myServerAdapter as get, myServerAdapter as post }\n```\n\n### Bun\n\n[Bun](https://bun.sh/) is a modern JavaScript runtime like Node or Deno, and it supports Fetch API\nas a first class citizen. So the configuration is really simple like any other JS runtime;\n\n```ts\nimport myServerAdapter from './myServerAdapter'\n\nconst server = Bun.serve(myServerAdapter)\n\nconsole.info(`Server is running on ${server.hostname}`)\n```\n\n## File Uploads / Multipart Requests\n\nMultipart requests are a type of HTTP request that allows you to send blobs together with regular\ntext data which has a mime-type `multipart/form-data`.\n\nFor example, if you send a multipart request from a browser with `FormData`, you can get the same\n`FormData` object in your request handler.\n\n```ts\nimport { createServerAdapter } from '@whatwg-node/server'\n\nconst myServerAdapter = createServerAdapter(async request => {\n  // Parse the request as `FormData`\n  const formData = await request.formData()\n  // Select the file\n  const file = formData.get('file')\n  // Process it as a string\n  const fileTextContent = await file.text()\n  // Select the other text parameter\n  const regularTextData = formData.get('additionalStuff')\n  // ...\n  return Response.json({ message: 'ok' })\n})\n```\n\nYou can learn more about [File API](https://developer.mozilla.org/en-US/docs/Web/API/File) on MDN\ndocumentation.\n\n## Routing and Middlewares\n\nWe'd recommend to use `fets` to handle routing and middleware approach. It uses\n`@whatwg-node/server` under the hood.\n\n> Learn more about `fets` [here](https://github.com/ardatan/fets)\n\n## Plugin System\n\nYou can create your own plugins to extend the functionality of your server adapter.\n\n### `onRequest`\n\nThis hook is invoked for ANY incoming HTTP request. Here you can manipulate the request or create a\nshort circuit before the server adapter handles the request.\n\nFor example, you can shortcut the manually handle an HTTP request, short-circuiting the HTTP\nhandler:\n\n```ts\nimport { createServerAdapter, type ServerAdapterPlugin } from '@whatwg-node/server'\n\nconst myPlugin: ServerAdapterPlugin = {\n  onRequest({ request, endResponse, fetchAPI }) {\n    if (!request.headers.get('authorization')) {\n      endResponse(\n        new fetchAPI.Response(null, {\n          status: 401,\n          headers: {\n            'Content-Type': 'application/json'\n          }\n        })\n      )\n    }\n  }\n}\n\nconst myServerAdapter = createServerAdapter(\n  async request => {\n    return new Response(`Hello World!`, { status: 200 })\n  },\n  {\n    plugins: [myPlugin]\n  }\n)\n```\n\nPossible usage examples of this hook are:\n\n- Manipulate the request\n- Short circuit before the adapter handles the request\n\n| Payload field   | Description                                                                                                                                     |\n| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |\n| `request`       | The incoming HTTP request as WHATWG `Request` object. [Learn more about the request](https://developer.mozilla.org/en-US/docs/Web/API/Request). |\n| `serverContext` | The early context object that is shared between all hooks and the entire execution. [Learn more about the context](/docs/features/context).     |\n| `fetchAPI`      | WHATWG Fetch API implementation. [Learn more about the fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).                  |\n| `url`           | WHATWG URL object of the incoming request. [Learn more about the URL object](https://developer.mozilla.org/en-US/docs/Web/API/URL).             |\n| `endResponse`   | A function that allows you to end the request early and send a response to the client.                                                          |\n\n### `onResponse`\n\nThis hook is invoked after a HTTP request has been processed and after the response has been\nforwarded to the client. Here you can perform any cleanup or logging operations, or you can\nmanipulate the outgoing response object.\n\n```ts\nimport { createServerAdapter, type ServerAdapterPlugin } from '@whatwg-node/server'\n\nconst requestTimeMap = new WeakMap<Request, number>()\n\nconst myPlugin: ServerAdapterPlugin = {\n  onRequest({ request }) {\n    requestTimeMap.set(request, Date.now())\n  },\n  onResponse({ request, serverContext, response }) {\n    console.log(`Request to ${request.url} has been processed with status ${response.status}`)\n    // Add some headers\n    response.headers.set('X-Server-Name', 'My Server')\n    console.log(`Request to ${request.url} took ${Date.now() - requestTimeMap.get(request)}ms`)\n  }\n}\n```\n\n**Example actions in this hook:**\n\n- Specify custom response format\n- Logging/Metrics\n\n| Field Name      | Description                                                                                                                                                   |\n| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `request`       | The incoming HTTP request as WHATWG `Request` object. [Learn more about the request](https://developer.mozilla.org/en-US/docs/Web/API/Request).               |\n| `serverContext` | The final context object that is shared between all hooks and the execution. [Learn more about the context](/docs/features/context).                          |\n| `response`      | The outgoing HTTP response as WHATWG `Response` object. [Learn more about the response interface](https://developer.mozilla.org/en-US/docs/Web/API/Response). |\n\n### `onDispose`\n\nIn order to clean up resources when the server is shut down, you can use `onDispose`,\n`Symbol.asyncDispose` or `Symbol.syncDispose` to clean up resources.\n\n```ts\nexport const useMyPlugin = () => {\n  return {\n    async onDispose() {\n      // Clean up resources\n      await stopConnection()\n    }\n  }\n}\n```\n\n[You can learn more about Explicit Resource Management below](#explicit-resource-management)\n\n## `Request.signal` for awareness of client disconnection\n\nIn the real world, a lot of HTTP requests are dropped or canceled. This can happen due to a flakey\ninternet connection, navigation to a new view or page within a web or native app or the user simply\nclosing the app. In this case, the server can stop processing the request and save resources.\n\nYou can utilize `request.signal` to cancel pending asynchronous operations when the client\ndisconnects.\n\n```ts\nimport { createServerAdapter } from '@whatwg-node/server'\n\nconst myServerAdapter = createServerAdapter(async request => {\n  const upstreamRes = await fetch('https://api.example.com/data', {\n    // When the client disconnects, the fetch request will be canceled\n    signal: request.signal\n  })\n  return Response.json({\n    data: await upstreamRes.json()\n  })\n})\n```\n\nThe execution cancelation API is built on top of the AbortController and AbortSignal APIs.\n\n[Learn more about AbortController and AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/AbortController)\n\n## Explicit Resource Management\n\nWhile implementing your server with `@whatwg-node/server`, you need to control over the lifecycle of\nyour resources. This is especially important when you are dealing with resources that need to be\ncleaned up when they are no longer needed, or clean up the operations in a queue when the server is\nshutting down.\n\n### Dispose the Server Adapter\n\nThe server adapter supports\n[Explicit Resource Management](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html#using-declarations-and-explicit-resource-management)\napproach that allows you to dispose of resources when they are no longer needed. This can be done in\ntwo ways shown below;\n\n#### `await using` syntax\n\nWe use the `await using` syntax to create a new instance of `adapter` and dispose of it when the\nblock is exited. Notice that we are using a block to limit the scope of `adapter` within `{ }`. So\nresources will be disposed of when the block is exited.\n\n```ts\nconsole.log('Adapter is starting')\n{\n  await using adapter = createServerAdapter(/* ... */)\n}\nconsole.log('Adapter is disposed')\n```\n\n#### `dispose` method\n\nWe create a new instance of `adapter` and dispose of it using the `dispose` method.\n\n```ts\nconsole.log('Adapter is starting')\nconst adapter = createServerAdapter(/* ... */)\nawait adapter.dispose()\nconsole.log('Adapter is disposed')\n```\n\nIn the first example, we use the `await using` syntax to create a new instance of `adapter` and\ndispose of it when the block is exited. In the second example,\n\n#### Dispose on Node.js\n\nWhen running your adapter on Node.js, you can use process event listeners or server's `close` event\nto trigger the adapter's disposal. Or you can configure the adapter to handle this automatically by\nlistening `process` exit signals.\n\n##### Explicit disposal\n\nWe can dispose of the adapter instance when the server is closed like below.\n\n```ts\nimport { createServer } from 'http'\nimport { createServerAdapter } from '@whatwg-node/server'\n\nconst adapter = createServerAdapter(/* ... */)\n\nconst server = createServer(adapter)\nserver.listen(4000, () => {\n  console.info('Server is running on http://localhost:4000')\n})\nserver.once('close', async () => {\n  await adapter.dispose()\n  console.info('Server is disposed so is adapter')\n})\n```\n\n##### Automatic disposal\n\n`disposeOnProcessTerminate` option will register an event listener for `process` termination in\nNode.js\n\n```ts\nimport { createServer } from 'http'\nimport { createServerAdapter } from '@whatwg-node/server'\n\ncreateServer(\n  createServerAdapter(/* ... */, {\n    disposeOnProcessTerminate: true,\n    plugins: [/* ... */]\n  })\n).listen(4000, () => {\n  console.info('Server is running on http://localhost:4000')\n})\n```\n\n### Plugin Disposal\n\nIf you have plugins that need some internal resources to be disposed of, you can use the `onDispose`\nhook to dispose of them. This hook will be invoked when the adapter instance is disposed like above.\n\n```ts\nlet dbConnection: Connection\nconst plugin = {\n  onPluginInit: async () => {\n    dbConnection = await createConnection()\n  },\n  onDispose: async () => {\n    // Dispose of resources\n    await dbConnection.close()\n  }\n}\n```\n\nOr you can flush a queue of operations when the server is shutting down.\n\n```ts\nconst backgroundJobs: Promise<void>[] = []\n\nconst plugin = {\n  onRequest() {\n    backgroundJobs.push(sendAnalytics({/* ... */}))\n  },\n  onDispose: async () => {\n    // Flush the queue of background jobs\n    await Promise.all(backgroundJobs)\n  }\n}\n```\n\nBut for this kind of purposes, `waitUntil` can be a better choice.\n\n### Background jobs\n\nIf you have background jobs that need to be completed before the environment is shut down.\n`waitUntil` is better choice than `onDispose`. In this case, those jobs will keep running in the\nbackground but in case of disposal, they will be awaited. `waitUntil` works so similar to\n[Cloudflare Workers' `waitUntil` function](https://developers.cloudflare.com/workers/runtime-apis/handlers/fetch/#parameters).\n\nBut the adapter handles `waitUntil` even if it is not provided by the environment.\n\n```ts\nconst adapter = createServerAdapter(async (request, context) => {\n  const args = await request.json()\n  if (!args.name) {\n    return Response.json({ error: 'Name is required' }, { status: 400 })\n  }\n  // This does not block the response\n  context.waitUntil(\n    fetch('http://my-analytics.com/analytics', {\n      method: 'POST',\n      body: JSON.stringify({\n        name: args.name,\n        userAgent: request.headers.get('User-Agent')\n      })\n    })\n  )\n  return Response.json({ greetings: `Hello, ${args.name}` })\n})\n\nconst res = await adapter.fetch('http://localhost:4000', {\n  method: 'POST',\n  headers: {\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify({ name: 'John' })\n})\n\nconsole.log(await res.json()) // { greetings: \"Hello, John\" }\n\nawait adapter.dispose()\n// The fetch request for `analytics` will be awaited here\n```\n\n## API Reference\n\n### `createServerAdapter(handler, options?)`\n\nCreates a server adapter that can handle HTTP requests across different platforms.\n\n**Parameters:**\n\n- `handler: (request: Request, context: TServerContext) => MaybePromise<Response>` - The main\n  request handler function that receives a WHATWG `Request` object and returns a `Response`.\n- `options?: ServerAdapterOptions` - Optional configuration object with the following properties:\n  - `plugins?: ServerAdapterPlugin[]` - Array of plugins to extend adapter functionality\n  - `fetchAPI?: Partial<FetchAPI>` - Custom Fetch API implementation (defaults to\n    `@whatwg-node/fetch`)\n  - `disposeOnProcessTerminate?: boolean` - **(Node.js only)** If `true`, automatically dispose the\n    adapter when the process terminates\n\n**Returns:** `ServerAdapter` - An adapter instance with the following methods and properties:\n\n#### Adapter Methods\n\n##### `fetch(input, init?, context?)`\n\nWHATWG Fetch spec compliant method for handling requests.\n\n```ts\nconst response = await adapter.fetch('http://localhost:4000/api', {\n  method: 'POST',\n  headers: { 'Content-Type': 'application/json' },\n  body: JSON.stringify({ data: 'value' })\n})\n```\n\n**Signatures:**\n\n- `fetch(request: Request, ...ctx: Partial<TServerContext>[]): MaybePromise<Response>`\n- `fetch(url: string | URL, init?: RequestInit, ...ctx: Partial<TServerContext>[]): MaybePromise<Response>`\n\n##### `handleRequest(request, context)`\n\nBasic request listener that takes a `Request` and server context.\n\n```ts\nconst response = await adapter.handleRequest(request, serverContext)\n```\n\n##### `handleNodeRequestAndResponse(nodeRequest, nodeResponse, ...context)`\n\nHandles a Node.js request/response pair and returns a WHATWG `Response` object.\n\n**⚠️ Important:** This method returns a `Response` object but **does not automatically write it to\nthe Node.js response object**. You need to manually send the response or use `requestListener()`\ninstead for automatic response handling.\n\n```ts\n// Returns a Response but doesn't write to `res`\nconst response = await adapter.handleNodeRequestAndResponse(req, res, { customContext: 'value' })\n\n// Use requestListener or adapter(req, res) instead for automatic handling\n```\n\n**Use case:** This method is useful when you need access to the WHATWG `Response` object for\ninspection or further processing before sending it.\n\n##### `requestListener(nodeRequest, nodeResponse, ...context)`\n\nA Node.js-compatible request listener that can be used with `http.createServer()` or similar.\n\n```ts\nimport { createServer } from 'http'\n\nconst server = createServer(adapter.requestListener)\n```\n\n##### `handleEvent(fetchEvent, ...context)`\n\nHandles a `FetchEvent` (used in Cloudflare Workers, Service Workers, etc.).\n\n```ts\nself.addEventListener('fetch', adapter.handleEvent)\n```\n\n##### `handleUWS(uwsResponse, uwsRequest, ...context)`\n\nHandles requests from uWebSockets.js.\n\n```ts\napp.any('/*', adapter.handleUWS)\n```\n\n##### `handle(input, ...context)`\n\nGeneric handler that automatically detects the input type and routes to the appropriate handler.\nSupports:\n\n- Node.js `IncomingMessage` + `ServerResponse`\n- WHATWG `Request`\n- `FetchEvent`\n- uWebSockets.js request/response\n- Request containers (`{ request: Request }`)\n\n##### `dispose()`\n\nDisposes the adapter and cleans up all resources. Returns a `Promise<void>`.\n\n```ts\nawait adapter.dispose()\n```\n\n##### `waitUntil(promise)`\n\nRegisters a promise to be awaited before the adapter is disposed. Useful for background tasks.\n\n```ts\nadapter.waitUntil(logAnalytics(request).catch(err => console.error('Analytics failed:', err)))\n```\n\n#### Adapter Properties\n\n##### `disposableStack`\n\nReturns the internal `AsyncDisposableStack` for advanced resource management.\n\n#### Special Behaviors\n\nThe adapter also works as:\n\n- **Function:** Can be called directly as a generic handler. When called with Node.js\n  request/response objects like `adapter(req, res, ...context)`, it's equivalent to calling\n  `adapter.handle(req, res, ...context)` which internally routes to `requestListener()`. Additional\n  context objects can be passed as spread arguments.\n- **Event Listener:** Can be used with `addEventListener('fetch', adapter)`\n- **AsyncDisposable:** Supports `await using adapter = createServerAdapter(...)`\n\n**Direct call examples:**\n\n```ts\n// Node.js - equivalent to requestListener\nadapter(nodeReq, nodeRes)\nadapter(nodeReq, nodeRes, { customContext: 'value' })\n\n// WHATWG Request - equivalent to fetch\nadapter(request)\nadapter(request, { customContext: 'value' })\n\n// FetchEvent - equivalent to handleEvent\nadapter(fetchEvent)\n\n// uWebSockets.js - equivalent to handleUWS\nadapter(uwsRes, uwsReq)\n```\n\n### Built-in Plugins\n\n#### `useCORS(options?)`\n\nAdds CORS (Cross-Origin Resource Sharing) support to your server.\n\n**Parameters:**\n\n- `options?: CORSPluginOptions` - Can be:\n  - `boolean` - `true` enables CORS with defaults, `false` disables it\n  - `CORSOptions` object:\n    - `origin?: string | string[]` - Allowed origins (`'*'` allows all)\n    - `methods?: string[]` - Allowed HTTP methods\n    - `allowedHeaders?: string[]` - Allowed request headers\n    - `exposedHeaders?: string[]` - Headers exposed to the client\n    - `credentials?: boolean` - Allow credentials\n    - `maxAge?: number` - Preflight cache duration in seconds\n  - `(request: Request, context: TServerContext) => MaybePromise<CORSOptions>` - Dynamic CORS\n    options factory\n\n**Example:**\n\n```ts\nimport { createServerAdapter, useCORS } from '@whatwg-node/server'\n\nconst adapter = createServerAdapter(handler, {\n  plugins: [\n    useCORS({\n      origin: ['https://example.com', 'https://app.example.com'],\n      credentials: true,\n      methods: ['GET', 'POST', 'PUT', 'DELETE'],\n      allowedHeaders: ['Content-Type', 'Authorization'],\n      maxAge: 86400\n    })\n  ]\n})\n```\n\n#### `useErrorHandling(errorHandler?)`\n\nAdds error handling to your request handler.\n\n**Parameters:**\n\n- `errorHandler?: (error: any, request: Request, context: TServerContext, fetchAPI: FetchAPI) => MaybePromise<Response> | void` -\n  Custom error handler function\n\n**Default Behavior:**\n\nThe default error handler checks for `HTTPError` instances or objects with `status`, `headers`, or\n`details` properties and returns appropriate responses. Other errors are logged and return a 500\nstatus.\n\n**HTTPError Class:**\n\n```ts\nimport { HTTPError } from '@whatwg-node/server'\n\nthrow new HTTPError(404, 'Resource not found', { 'X-Custom-Header': 'value' }, { id: 123 })\n```\n\n**Example:**\n\n```ts\nimport { createServerAdapter, useErrorHandling } from '@whatwg-node/server'\n\nconst adapter = createServerAdapter(handler, {\n  plugins: [\n    useErrorHandling((error, request, context, fetchAPI) => {\n      console.error('Request failed:', error)\n      return fetchAPI.Response.json(\n        { error: error.message },\n        {\n          status: error.status || 500\n        }\n      )\n    })\n  ]\n})\n```\n\n#### `useContentEncoding()`\n\nAutomatically handles request decompression and response compression based on `Content-Encoding` and\n`Accept-Encoding` headers.\n\n**Supported encodings:** `gzip`, `deflate`, `br` (Brotli), `zstd`, `deflate-raw` (depends on runtime\nsupport)\n\n**Example:**\n\n```ts\nimport { createServerAdapter, useContentEncoding } from '@whatwg-node/server'\n\nconst adapter = createServerAdapter(handler, {\n  plugins: [useContentEncoding()]\n})\n```\n\nThis plugin will:\n\n- Decompress incoming request bodies based on `Content-Encoding` header\n- Compress outgoing response bodies based on `Accept-Encoding` header\n- Return `415 Unsupported Media Type` for unsupported encodings\n\n### Plugin System\n\n#### Creating Custom Plugins\n\nA plugin is an object implementing the `ServerAdapterPlugin` interface:\n\n```ts\nimport { ServerAdapterPlugin } from '@whatwg-node/server'\n\nconst myPlugin: ServerAdapterPlugin = {\n  // Optional: Wrap the entire request handling pipeline\n  instrumentation?: {\n    request: ({ request }, wrapped) => {\n      console.log('Before request')\n      const result = wrapped()\n      console.log('After request')\n      return result\n    }\n  },\n\n  // Optional: Called for every incoming request\n  onRequest({ request, setRequest, serverContext, fetchAPI, url, requestHandler, setRequestHandler, endResponse }) {\n    // Modify the request\n    const newRequest = new fetchAPI.Request(request.url, {\n      ...request,\n      headers: { ...request.headers, 'X-Custom-Header': 'value' }\n    })\n    setRequest(newRequest)\n\n    // Or short-circuit the request\n    if (!request.headers.get('authorization')) {\n      endResponse(new fetchAPI.Response('Unauthorized', { status: 401 }))\n    }\n\n    // Or replace the request handler\n    setRequestHandler(async (req, ctx) => {\n      // Custom handling logic\n      return requestHandler(req, ctx)\n    })\n  },\n\n  // Optional: Called after request is processed\n  onResponse({ request, response, setResponse, serverContext, fetchAPI }) {\n    // Modify the response\n    response.headers.set('X-Server', 'My Server')\n\n    // Or replace the response\n    setResponse(new fetchAPI.Response(response.body, {\n      ...response,\n      headers: { ...response.headers, 'X-Custom': 'value' }\n    }))\n  },\n\n  // Optional: Called when adapter is disposed\n  onDispose: async () => {\n    // Clean up resources\n    await cleanup()\n  },\n\n  // Alternative disposal methods (Explicit Resource Management)\n  [Symbol.dispose]: () => { /* sync cleanup */ },\n  [Symbol.asyncDispose]: async () => { /* async cleanup */ }\n}\n```\n\n#### Plugin Hook Payloads\n\n##### `onRequest` Payload\n\n| Field               | Type                           | Description                           |\n| ------------------- | ------------------------------ | ------------------------------------- |\n| `request`           | `Request`                      | The incoming WHATWG Request object    |\n| `setRequest`        | `(request: Request) => void`   | Replace the request object            |\n| `serverContext`     | `TServerContext`               | The server context object             |\n| `fetchAPI`          | `FetchAPI`                     | WHATWG Fetch API implementation       |\n| `url`               | `URL`                          | Parsed URL of the request             |\n| `requestHandler`    | `Function`                     | The current request handler           |\n| `setRequestHandler` | `(handler: Function) => void`  | Replace the request handler           |\n| `endResponse`       | `(response: Response) => void` | Short-circuit and end with a response |\n\n##### `onResponse` Payload\n\n| Field           | Type                           | Description                         |\n| --------------- | ------------------------------ | ----------------------------------- |\n| `request`       | `Request`                      | The incoming WHATWG Request object  |\n| `response`      | `Response`                     | The outgoing WHATWG Response object |\n| `setResponse`   | `(response: Response) => void` | Replace the response object         |\n| `serverContext` | `TServerContext`               | The server context object           |\n| `fetchAPI`      | `FetchAPI`                     | WHATWG Fetch API implementation     |\n\n### Types\n\n#### `ServerAdapterRequestHandler<TServerContext>`\n\n```ts\ntype ServerAdapterRequestHandler<TServerContext> = (\n  request: Request,\n  context: TServerContext & ServerAdapterInitialContext\n) => MaybePromise<Response>\n```\n\n#### `ServerAdapterInitialContext`\n\nThe base context object available to all request handlers:\n\n```ts\ntype ServerAdapterInitialContext = {\n  waitUntil: (promise: Promise<void> | void) => void\n}\n```\n\n#### `ServerAdapterNodeContext`\n\nContext object when using Node.js handlers:\n\n```ts\ntype ServerAdapterNodeContext = {\n  req: IncomingMessage | Http2ServerRequest\n  res: ServerResponse | Http2ServerResponse\n}\n```\n\n#### `FetchEvent`\n\n```ts\ninterface FetchEvent extends Event {\n  waitUntil(promise: MaybePromise<void>): void\n  request: Request\n  respondWith(response: MaybePromiseLike<Response>): void\n}\n```\n","publish_time":1740968736961,"_cnpm_publish_time":1740968736961,"dist-tags":{"alpha":"0.13.3-alpha-20261110014155-22adefff4a6cdea2621e4b6f9cfa78e634349591","latest":"0.13.3","rc":"0.13.1-rc-20261016084928-37b9c99ead24898b1677924f2ac0e2537e42734d"}}