@dimah-s3/server 2.0.0-beta.0 → 2.0.0-beta.10

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/README.md CHANGED
@@ -1,13 +1,13 @@
1
1
  # @dimah-s3/server
2
2
 
3
- **2.0 beta.** Install with `@beta`. `@latest` stays on 1.x, and betas can include breaking changes until 2.0.0.
3
+ **2.0 beta.** Install with `@beta`. `@latest` stays on 1.x ([v1.s3.dimah.dev](https://v1.s3.dimah.dev/docs)), and betas can include breaking changes until 2.0.0.
4
4
 
5
5
  Presigned S3 upload, download, and delete handlers with route policies,
6
6
  guards, and lifecycle hooks. One instance gives you an HTTP `handler`, an
7
7
  in-process `api`, and `put` for server-side uploads.
8
8
 
9
- Full documentation: [v2.s3.dimah.dev/docs/server](https://v2.s3.dimah.dev/docs/server) ·
10
- [llms.txt](https://v2.s3.dimah.dev/llms.txt)
9
+ Full documentation: [s3.dimah.dev/docs/server](https://s3.dimah.dev/docs/server) ·
10
+ [llms.txt](https://s3.dimah.dev/llms.txt)
11
11
 
12
12
  ## Install
13
13
 
@@ -64,7 +64,7 @@ export const { GET, POST, PUT, PATCH, DELETE } = toNextJsHandler(s3);
64
64
  // Any Fetch runtime: s3.handler(request)
65
65
  ```
66
66
 
67
- See [Server Setup](https://v2.s3.dimah.dev/docs/server/setup) for every adapter.
67
+ See [Server Setup](https://s3.dimah.dev/docs/server/setup) for every adapter.
68
68
 
69
69
  ## Guards and hooks
70
70
 
@@ -109,7 +109,7 @@ Optional persistence: add `db()` from [`@dimah-s3/db`](../db) to `plugins`.
109
109
 
110
110
  ## Upgrading from 1.7
111
111
 
112
- See [Upgrade to 2.0 beta](https://v2.s3.dimah.dev/docs/migration-2-0).
112
+ See [Upgrade to 2.0 beta](https://s3.dimah.dev/docs/migration-2-0).
113
113
 
114
114
  ## License
115
115
 
@@ -1,4 +1,4 @@
1
- import type { DimahS3HandlerSource } from "./types";
1
+ import type { DimahS3HandlerSource } from "./types.js";
2
2
  /** Structural Elysia context — avoids a hard dependency on `elysia`. */
3
3
  type ElysiaContext = {
4
4
  request: Request;
@@ -1,5 +1,5 @@
1
- import { fromNodeHeaders, type NodeHandlerOptions } from "./node";
2
- import type { DimahS3HandlerSource } from "./types";
1
+ import { fromNodeHeaders, type NodeHandlerOptions } from "./node.js";
2
+ import type { DimahS3HandlerSource } from "./types.js";
3
3
  export { fromNodeHeaders, type NodeHandlerOptions };
4
4
  /**
5
5
  * Adapt a dimah-s3 instance to an Express / Connect handler.
@@ -1,5 +1,4 @@
1
1
  import { Readable } from 'stream';
2
- import { pipeline } from 'stream/promises';
3
2
  import { s3Error } from '@dimah-s3/core';
4
3
  import { toResponse } from 'better-call';
5
4
 
@@ -92,10 +91,34 @@ async function writeWebResponse(res, response) {
92
91
  res.end();
93
92
  return;
94
93
  }
95
- await pipeline(
96
- Readable.fromWeb(response.body),
97
- res
98
- );
94
+ const reader = response.body.getReader();
95
+ try {
96
+ for (; ; ) {
97
+ const { done, value } = await reader.read();
98
+ if (done) break;
99
+ if (res.destroyed || res.writableEnded) {
100
+ await reader.cancel();
101
+ return;
102
+ }
103
+ if (!value?.byteLength) continue;
104
+ if (!res.write(value)) await waitForDrain(res);
105
+ }
106
+ if (!res.destroyed && !res.writableEnded) res.end();
107
+ } catch (error) {
108
+ await reader.cancel(error).catch(() => void 0);
109
+ throw error;
110
+ }
111
+ }
112
+ function waitForDrain(res) {
113
+ return new Promise((resolve) => {
114
+ const done = () => {
115
+ res.off("drain", done);
116
+ res.off("close", done);
117
+ resolve();
118
+ };
119
+ res.once("drain", done);
120
+ res.once("close", done);
121
+ });
99
122
  }
100
123
 
101
124
  // src/adapters/express.ts
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/helpers/logger.ts","../../src/adapters/node.ts","../../src/adapters/express.ts"],"names":[],"mappings":";;;;;;;;AAEO,IAAM,aAAA,GAA+B;AAAA,EAC1C,KAAA,EAAO,CAAC,OAAA,EAAA,GAAY,IA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GAAS,CAAA,EAAG,GAAA,CAAI,SAAA,CAAU,cAAc,OAAO,CAAA;AAE3D,EAAA,IAAI,QAAA,CAAS,SAAS,IAAA,EAAM;AAC1B,IAAA,GAAA,CAAI,GAAA,EAAI;AACR,IAAA;AAAA,EACF;AACA,EAAA,MAAM,QAAA;AAAA,IACJ,QAAA,CAAS,OAAA,CAAQ,QAAA,CAAS,IAAsC,CAAA;AAAA,IAChE;AAAA,GACF;AACF;;;ACrIO,SAAS,gBAAA,CACd,IACA,OAAA,EACA;AACA,EAAA,OAAO,aAAA,CAAc,IAAI,OAAO,CAAA;AAClC","file":"express.js","sourcesContent":["import type { DimahS3Logger } from \"@/types\";\n\nexport const defaultLogger: DimahS3Logger = {\n error: (message, ...args) => {\n console.error(\"[dimah-s3]\", message, ...args);\n },\n warn: (message, ...args) => {\n console.warn(\"[dimah-s3]\", message, ...args);\n },\n};\n\nexport function resolveLogger(\n logger: DimahS3Logger | false | undefined,\n): DimahS3Logger {\n if (logger === false) return {};\n if (!logger) return defaultLogger;\n return logger;\n}\n","import type {\n IncomingHttpHeaders,\n IncomingMessage,\n ServerResponse,\n} from \"node:http\";\nimport { Readable } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport type { ReadableStream as NodeReadableStream } from \"node:stream/web\";\nimport { s3Error } from \"@dimah-s3/core\";\nimport { toResponse } from \"better-call\";\nimport { defaultLogger } from \"@/helpers/logger\";\nimport type { DimahS3HandlerSource } from \"./types\";\n\n/** Options of the Node, Express and Fastify adapters. */\nexport type NodeHandlerOptions = {\n /**\n * Build the request URL from `X-Forwarded-Proto` and `X-Forwarded-Host`.\n * Turn it on only behind a proxy that sets them, since clients can send\n * them too. Default `false`.\n */\n trustProxy?: boolean;\n};\n\n/**\n * Convert Node.js / Express request headers into a Web {@link Headers} object.\n * Useful when calling `s3.api.*` from a Node handler. HTTP/2 pseudo-headers\n * (`:path`) are left out.\n *\n * @example\n * ```ts\n * import { fromNodeHeaders } from \"@dimah-s3/server/node\";\n *\n * await s3.api.download({ route, key }, { headers: fromNodeHeaders(req.headers) });\n * ```\n */\nexport function fromNodeHeaders(nodeHeaders: IncomingHttpHeaders): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(nodeHeaders)) {\n if (value == null || key.startsWith(\":\")) continue;\n if (Array.isArray(value)) {\n for (const v of value) headers.append(key, v);\n } else {\n headers.set(key, value);\n }\n }\n return headers;\n}\n\n/**\n * Adapt a dimah-s3 instance to Node.js `http` / Express-style handlers.\n *\n * The request body streams from `req`, so the body cap is counted as bytes\n * arrive. When the client disconnects before the response finishes, the\n * request signal aborts and so does the S3 call behind it. Response bodies,\n * such as a `/file` download, stream to `res`.\n *\n * @example\n * ```ts\n * import { createServer } from \"node:http\";\n * import { toNodeHandler } from \"@dimah-s3/server/node\";\n * import { s3 } from \"./s3\";\n *\n * createServer(toNodeHandler(s3)).listen(3000);\n * // Behind a proxy that sets X-Forwarded-Proto / X-Forwarded-Host:\n * // createServer(toNodeHandler(s3, { trustProxy: true }));\n * ```\n */\nexport function toNodeHandler(\n s3: DimahS3HandlerSource,\n options: NodeHandlerOptions = {},\n) {\n return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n const controller = new AbortController();\n res.once(\"close\", () => {\n if (!res.writableFinished) controller.abort();\n });\n\n try {\n const request = toWebRequest(req, controller.signal, options);\n await writeWebResponse(res, await s3.handler(request));\n } catch (error) {\n // The client went away; there is no one to answer.\n if (controller.signal.aborted) return;\n defaultLogger.error?.(\"Node adapter failed\", error);\n if (res.headersSent) {\n res.destroy();\n } else {\n await writeWebResponse(res, toResponse(s3Error(\"INTERNAL_ERROR\")));\n }\n }\n };\n}\n\nfunction toWebRequest(\n req: IncomingMessage,\n signal: AbortSignal,\n options: NodeHandlerOptions,\n): Request {\n const method = (req.method ?? \"GET\").toUpperCase();\n const hasBody = method !== \"GET\" && method !== \"HEAD\";\n const init: RequestInit & { duplex?: \"half\" } = {\n method,\n headers: fromNodeHeaders(req.headers),\n signal,\n };\n if (hasBody) {\n // The DOM and Node typings of ReadableStream differ; the runtime object is the same.\n init.body = Readable.toWeb(req) as ReadableStream<Uint8Array<ArrayBuffer>>;\n // Node's fetch needs `duplex` for a streaming body.\n init.duplex = \"half\";\n }\n return new Request(requestURL(req, options), init);\n}\n\n/**\n * The absolute request URL, from the socket or the trusted proxy headers.\n * Express sets `originalUrl`, which keeps the mount path that\n * `app.use(\"/api/s3\", …)` strips from `url`.\n */\nfunction requestURL(req: IncomingMessage, options: NodeHandlerOptions): URL {\n const encrypted = (req.socket as { encrypted?: boolean }).encrypted === true;\n let protocol = encrypted ? \"https\" : \"http\";\n let host = req.headers.host ?? \"localhost\";\n\n if (options.trustProxy) {\n const forwardedProto = firstHeaderValue(req.headers[\"x-forwarded-proto\"]);\n if (forwardedProto === \"http\" || forwardedProto === \"https\") {\n protocol = forwardedProto;\n }\n host = firstHeaderValue(req.headers[\"x-forwarded-host\"]) || host;\n }\n const path = (req as { originalUrl?: string }).originalUrl ?? req.url;\n return new URL(path ?? \"/\", `${protocol}://${host}`);\n}\n\n/** The first entry of a header that proxies may append to (`a, b`). */\nfunction firstHeaderValue(value: string | string[] | undefined): string {\n const raw = Array.isArray(value) ? value[0] : value;\n return raw?.split(\",\")[0]?.trim().toLowerCase() ?? \"\";\n}\n\nasync function writeWebResponse(\n res: ServerResponse,\n response: Response,\n): Promise<void> {\n res.statusCode = response.status;\n for (const [key, value] of response.headers) {\n if (key === \"set-cookie\") continue;\n res.setHeader(key, value);\n }\n const cookies = response.headers.getSetCookie();\n if (cookies.length > 0) res.setHeader(\"set-cookie\", cookies);\n\n if (response.body === null) {\n res.end();\n return;\n }\n await pipeline(\n Readable.fromWeb(response.body as NodeReadableStream<Uint8Array>),\n res,\n );\n}\n","import {\n fromNodeHeaders,\n toNodeHandler,\n type NodeHandlerOptions,\n} from \"./node\";\nimport type { DimahS3HandlerSource } from \"./types\";\n\nexport { fromNodeHeaders, type NodeHandlerOptions };\n\n/**\n * Adapt a dimah-s3 instance to an Express / Connect handler.\n *\n * Mount **before** `express.json()` so the request body is not consumed early.\n * A route (`app.all`) and a mount (`app.use(\"/api/s3\", …)`) both work: the\n * request URL is read from `req.originalUrl`. Takes the same options as\n * `toNodeHandler`, such as `{ trustProxy: true }` behind a proxy.\n *\n * @example\n * ```ts\n * import express from \"express\";\n * import { toExpressHandler } from \"@dimah-s3/server/express\";\n * import { s3 } from \"./s3\";\n *\n * const app = express();\n * app.use(\"/api/s3\", toExpressHandler(s3));\n * app.use(express.json());\n * ```\n */\nexport function toExpressHandler(\n s3: DimahS3HandlerSource,\n options?: NodeHandlerOptions,\n) {\n return toNodeHandler(s3, options);\n}\n"]}
1
+ {"version":3,"sources":["../../src/helpers/logger.ts","../../src/adapters/node.ts","../../src/adapters/express.ts"],"names":[],"mappings":";;;;;;;AAEO,IAAM,aAAA,GAA+B;AAAA,EAC1C,KAAA,EAAO,CAAC,OAAA,EAAA,GAAY,IAAA,KAAS;AAC3B,IAAA,OAAA,CAAQ,KAAA,CAAM,YAAA,EAAc,OAAA,EAAS,GAAG,IAAI,CAAA;AAAA,EAC9C,CAAA;AAAA,EACA,IAAA,EAAM,CAAC,OAAA,EAAA,GAAY,IAAA,KAAS;AAC1B,IAAA,OAAA,CAAQ,IAAA,CAAK,YAAA,EAAc,OAAA,EAAS,GAAG,IAAI,CAAA;AAAA,EAC7C;AACF,CAAA;;;ACwBO,SAAS,gBAAgB,WAAA,EAA2C;AACzE,EAAA,MAAM,OAAA,GAAU,IAAI,OAAA,EAAQ;AAC5B,EAAA,KAAA,MAAW,CAAC,GAAA,EAAK,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,WAAW,CAAA,EAAG;AACtD,IAAA,IAAI,KAAA,IAAS,IAAA,IAAQ,GAAA,CAAI,UAAA,CAAW,GAAG,CAAA,EAAG;AAC1C,IAAA,IAAI,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA,EAAG;AACxB,MAAA,KAAA,MAAW,CAAA,IAAK,KAAA,EA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IAAA,IAAI,CAAC,GAAA,CAAI,SAAA,IAAa,CAAC,GAAA,CAAI,aAAA,MAAmB,GAAA,EAAI;AAAA,EACpD,SAAS,KAAA,EAAO;AACd,IAAA,MAAM,OAAO,MAAA,CAAO,KAAK,CAAA,CAAE,KAAA,CAAM,MAAM,MAAS,CAAA;AAChD,IAAA,MAAM,KAAA;AAAA,EACR;AACF;AAGA,SAAS,aAAa,GAAA,EAAoC;AACxD,EAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,OAAA,KAAY;AAC9B,IAAA,MAAM,OAAO,MAAM;AACjB,MAAA,GAAA,CAAI,GAAA,CAAI,SAAS,IAAI,CAAA;AACrB,MAAA,GAAA,CAAI,GAAA,CAAI,SAAS,IAAI,CAAA;AACrB,MAAA,OAAA,EAAQ;AAAA,IACV,CAAA;AACA,IAAA,GAAA,CAAI,IAAA,CAAK,SAAS,IAAI,CAAA;AACtB,IAAA,GAAA,CAAI,IAAA,CAAK,SAAS,IAAI,CAAA;AAAA,EACxB,CAAC,CAAA;AACH;;;ACjKO,SAAS,gBAAA,CACd,IACA,OAAA,EACA;AACA,EAAA,OAAO,aAAA,CAAc,IAAI,OAAO,CAAA;AAClC","file":"express.js","sourcesContent":["import type { DimahS3Logger } from \"@/types\";\n\nexport const defaultLogger: DimahS3Logger = {\n error: (message, ...args) => {\n console.error(\"[dimah-s3]\", message, ...args);\n },\n warn: (message, ...args) => {\n console.warn(\"[dimah-s3]\", message, ...args);\n },\n};\n\nexport function resolveLogger(\n logger: DimahS3Logger | false | undefined,\n): DimahS3Logger {\n if (logger === false) return {};\n if (!logger) return defaultLogger;\n return logger;\n}\n","import type {\n IncomingHttpHeaders,\n IncomingMessage,\n ServerResponse,\n} from \"node:http\";\nimport { Readable } from \"node:stream\";\nimport { s3Error } from \"@dimah-s3/core\";\nimport { toResponse } from \"better-call\";\nimport { defaultLogger } from \"@/helpers/logger\";\nimport type { DimahS3HandlerSource } from \"./types\";\n\n/** Options of the Node, Express and Fastify adapters. */\nexport type NodeHandlerOptions = {\n /**\n * Build the request URL from `X-Forwarded-Proto` and `X-Forwarded-Host`.\n * Turn it on only behind a proxy that sets them, since clients can send\n * them too. Default `false`.\n */\n trustProxy?: boolean;\n};\n\n/**\n * Convert Node.js / Express request headers into a Web {@link Headers} object.\n * Useful when calling `s3.api.*` from a Node handler. HTTP/2 pseudo-headers\n * (`:path`) are left out.\n *\n * @example\n * ```ts\n * import { fromNodeHeaders } from \"@dimah-s3/server/node\";\n *\n * await s3.api.download({ route, key }, { headers: fromNodeHeaders(req.headers) });\n * ```\n */\nexport function fromNodeHeaders(nodeHeaders: IncomingHttpHeaders): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(nodeHeaders)) {\n if (value == null || key.startsWith(\":\")) continue;\n if (Array.isArray(value)) {\n for (const v of value) headers.append(key, v);\n } else {\n headers.set(key, value);\n }\n }\n return headers;\n}\n\n/**\n * Adapt a dimah-s3 instance to Node.js `http` / Express-style handlers.\n *\n * The request body streams from `req`, so the body cap is counted as bytes\n * arrive. When the client disconnects before the response finishes, the\n * request signal aborts and so does the S3 call behind it. Response bodies,\n * such as a `/file` download, stream to `res`.\n *\n * @example\n * ```ts\n * import { createServer } from \"node:http\";\n * import { toNodeHandler } from \"@dimah-s3/server/node\";\n * import { s3 } from \"./s3\";\n *\n * createServer(toNodeHandler(s3)).listen(3000);\n * // Behind a proxy that sets X-Forwarded-Proto / X-Forwarded-Host:\n * // createServer(toNodeHandler(s3, { trustProxy: true }));\n * ```\n */\nexport function toNodeHandler(\n s3: DimahS3HandlerSource,\n options: NodeHandlerOptions = {},\n) {\n return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n const controller = new AbortController();\n res.once(\"close\", () => {\n if (!res.writableFinished) controller.abort();\n });\n\n try {\n const request = toWebRequest(req, controller.signal, options);\n await writeWebResponse(res, await s3.handler(request));\n } catch (error) {\n // The client went away; there is no one to answer.\n if (controller.signal.aborted) return;\n defaultLogger.error?.(\"Node adapter failed\", error);\n if (res.headersSent) {\n res.destroy();\n } else {\n await writeWebResponse(res, toResponse(s3Error(\"INTERNAL_ERROR\")));\n }\n }\n };\n}\n\nfunction toWebRequest(\n req: IncomingMessage,\n signal: AbortSignal,\n options: NodeHandlerOptions,\n): Request {\n const method = (req.method ?? \"GET\").toUpperCase();\n const hasBody = method !== \"GET\" && method !== \"HEAD\";\n const init: RequestInit & { duplex?: \"half\" } = {\n method,\n headers: fromNodeHeaders(req.headers),\n signal,\n };\n if (hasBody) {\n // The DOM and Node typings of ReadableStream differ; the runtime object is the same.\n init.body = Readable.toWeb(req) as ReadableStream<Uint8Array<ArrayBuffer>>;\n // Node's fetch needs `duplex` for a streaming body.\n init.duplex = \"half\";\n }\n return new Request(requestURL(req, options), init);\n}\n\n/**\n * The absolute request URL, from the socket or the trusted proxy headers.\n * Express sets `originalUrl`, which keeps the mount path that\n * `app.use(\"/api/s3\", …)` strips from `url`.\n */\nfunction requestURL(req: IncomingMessage, options: NodeHandlerOptions): URL {\n const encrypted = (req.socket as { encrypted?: boolean }).encrypted === true;\n let protocol = encrypted ? \"https\" : \"http\";\n let host = req.headers.host ?? \"localhost\";\n\n if (options.trustProxy) {\n const forwardedProto = firstHeaderValue(req.headers[\"x-forwarded-proto\"]);\n if (forwardedProto === \"http\" || forwardedProto === \"https\") {\n protocol = forwardedProto;\n }\n host = firstHeaderValue(req.headers[\"x-forwarded-host\"]) || host;\n }\n const path = (req as { originalUrl?: string }).originalUrl ?? req.url;\n return new URL(path ?? \"/\", `${protocol}://${host}`);\n}\n\n/** The first entry of a header that proxies may append to (`a, b`). */\nfunction firstHeaderValue(value: string | string[] | undefined): string {\n const raw = Array.isArray(value) ? value[0] : value;\n return raw?.split(\",\")[0]?.trim().toLowerCase() ?? \"\";\n}\n\nasync function writeWebResponse(\n res: ServerResponse,\n response: Response,\n): Promise<void> {\n res.statusCode = response.status;\n for (const [key, value] of response.headers) {\n if (key === \"set-cookie\") continue;\n res.setHeader(key, value);\n }\n const cookies = response.headers.getSetCookie();\n if (cookies.length > 0) res.setHeader(\"set-cookie\", cookies);\n\n if (response.body === null) {\n res.end();\n return;\n }\n // `Readable.fromWeb` piped into `res` deadlocks once the body is larger\n // than the stream buffer: each side waits for the other to pull. Read\n // the web stream and write it, waiting for `drain` when Node's buffer\n // is full.\n const reader = response.body.getReader();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (res.destroyed || res.writableEnded) {\n await reader.cancel();\n return;\n }\n if (!value?.byteLength) continue;\n if (!res.write(value)) await waitForDrain(res);\n }\n if (!res.destroyed && !res.writableEnded) res.end();\n } catch (error) {\n await reader.cancel(error).catch(() => undefined);\n throw error;\n }\n}\n\n/** Resolves when `res` accepts more data, or when the client has gone. */\nfunction waitForDrain(res: ServerResponse): Promise<void> {\n return new Promise((resolve) => {\n const done = () => {\n res.off(\"drain\", done);\n res.off(\"close\", done);\n resolve();\n };\n res.once(\"drain\", done);\n res.once(\"close\", done);\n });\n}\n","import {\n fromNodeHeaders,\n toNodeHandler,\n type NodeHandlerOptions,\n} from \"./node\";\nimport type { DimahS3HandlerSource } from \"./types\";\n\nexport { fromNodeHeaders, type NodeHandlerOptions };\n\n/**\n * Adapt a dimah-s3 instance to an Express / Connect handler.\n *\n * Mount **before** `express.json()` so the request body is not consumed early.\n * A route (`app.all`) and a mount (`app.use(\"/api/s3\", …)`) both work: the\n * request URL is read from `req.originalUrl`. Takes the same options as\n * `toNodeHandler`, such as `{ trustProxy: true }` behind a proxy.\n *\n * @example\n * ```ts\n * import express from \"express\";\n * import { toExpressHandler } from \"@dimah-s3/server/express\";\n * import { s3 } from \"./s3\";\n *\n * const app = express();\n * app.use(\"/api/s3\", toExpressHandler(s3));\n * app.use(express.json());\n * ```\n */\nexport function toExpressHandler(\n s3: DimahS3HandlerSource,\n options?: NodeHandlerOptions,\n) {\n return toNodeHandler(s3, options);\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import type { IncomingMessage, ServerResponse } from "node:http";
2
- import { type NodeHandlerOptions } from "./node";
3
- import type { DimahS3HandlerSource } from "./types";
2
+ import { type NodeHandlerOptions } from "./node.js";
3
+ import type { DimahS3HandlerSource } from "./types.js";
4
4
  export type { NodeHandlerOptions };
5
5
  /** Structural Fastify request/reply — avoids a hard dependency on `fastify`. */
6
6
  type FastifyRequestLike = {
@@ -1,5 +1,4 @@
1
1
  import { Readable } from 'stream';
2
- import { pipeline } from 'stream/promises';
3
2
  import { s3Error } from '@dimah-s3/core';
4
3
  import { toResponse } from 'better-call';
5
4
 
@@ -92,10 +91,34 @@ async function writeWebResponse(res, response) {
92
91
  res.end();
93
92
  return;
94
93
  }
95
- await pipeline(
96
- Readable.fromWeb(response.body),
97
- res
98
- );
94
+ const reader = response.body.getReader();
95
+ try {
96
+ for (; ; ) {
97
+ const { done, value } = await reader.read();
98
+ if (done) break;
99
+ if (res.destroyed || res.writableEnded) {
100
+ await reader.cancel();
101
+ return;
102
+ }
103
+ if (!value?.byteLength) continue;
104
+ if (!res.write(value)) await waitForDrain(res);
105
+ }
106
+ if (!res.destroyed && !res.writableEnded) res.end();
107
+ } catch (error) {
108
+ await reader.cancel(error).catch(() => void 0);
109
+ throw error;
110
+ }
111
+ }
112
+ function waitForDrain(res) {
113
+ return new Promise((resolve) => {
114
+ const done = () => {
115
+ res.off("drain", done);
116
+ res.off("close", done);
117
+ resolve();
118
+ };
119
+ res.once("drain", done);
120
+ res.once("close", done);
121
+ });
99
122
  }
100
123
 
101
124
  // src/adapters/fastify.ts
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/helpers/logger.ts","../../src/adapters/node.ts","../../src/adapters/fastify.ts"],"names":[],"mappings":";;;;;;;;AAEO,IAAM,aAAA,GAA+B;AAAA,EAC1C,KAAA,EAAO,CAAC,OAAA,EAAA,GAAY,IAAA,KAAS;AAC3B,IAAA,OAAA,CAAQ,KAAA,CAAM,YAAA,EAAc,OAAA,EAAS,GAAG,IAAI,CAAA;AAAA,EAC9C,CAAA;AAAA,EACA,IAAA,E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,CAAI,GAAA,EAAI;AACR,IAAA;AAAA,EACF;AACA,EAAA,MAAM,QAAA;AAAA,IACJ,QAAA,CAAS,OAAA,CAAQ,QAAA,CAAS,IAAsC,CAAA;AAAA,IAChE;AAAA,GACF;AACF;;;AC3HO,SAAS,gBAAA,CACd,IACA,OAAA,EACA;AACA,EAAA,MAAM,OAAA,GAAU,aAAA,CAAc,EAAA,EAAI,OAAO,CAAA;AACzC,EAAA,OAAO,OAAO,KAAyB,KAAA,KAA4B;AACjE,IAAA,KAAA,CAAM,MAAA,EAAO;AACb,IAAA,MAAM,OAAA,CAAQ,GAAA,CAAI,GAAA,EAAK,KAAA,CAAM,GAAG,CAAA;AAAA,EAClC,CAAA;AACF","file":"fastify.js","sourcesContent":["import type { DimahS3Logger } from \"@/types\";\n\nexport const defaultLogger: DimahS3Logger = {\n error: (message, ...args) => {\n console.error(\"[dimah-s3]\", message, ...args);\n },\n warn: (message, ...args) => {\n console.warn(\"[dimah-s3]\", message, ...args);\n },\n};\n\nexport function resolveLogger(\n logger: DimahS3Logger | false | undefined,\n): DimahS3Logger {\n if (logger === false) return {};\n if (!logger) return defaultLogger;\n return logger;\n}\n","import type {\n IncomingHttpHeaders,\n IncomingMessage,\n ServerResponse,\n} from \"node:http\";\nimport { Readable } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport type { ReadableStream as NodeReadableStream } from \"node:stream/web\";\nimport { s3Error } from \"@dimah-s3/core\";\nimport { toResponse } from \"better-call\";\nimport { defaultLogger } from \"@/helpers/logger\";\nimport type { DimahS3HandlerSource } from \"./types\";\n\n/** Options of the Node, Express and Fastify adapters. */\nexport type NodeHandlerOptions = {\n /**\n * Build the request URL from `X-Forwarded-Proto` and `X-Forwarded-Host`.\n * Turn it on only behind a proxy that sets them, since clients can send\n * them too. Default `false`.\n */\n trustProxy?: boolean;\n};\n\n/**\n * Convert Node.js / Express request headers into a Web {@link Headers} object.\n * Useful when calling `s3.api.*` from a Node handler. HTTP/2 pseudo-headers\n * (`:path`) are left out.\n *\n * @example\n * ```ts\n * import { fromNodeHeaders } from \"@dimah-s3/server/node\";\n *\n * await s3.api.download({ route, key }, { headers: fromNodeHeaders(req.headers) });\n * ```\n */\nexport function fromNodeHeaders(nodeHeaders: IncomingHttpHeaders): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(nodeHeaders)) {\n if (value == null || key.startsWith(\":\")) continue;\n if (Array.isArray(value)) {\n for (const v of value) headers.append(key, v);\n } else {\n headers.set(key, value);\n }\n }\n return headers;\n}\n\n/**\n * Adapt a dimah-s3 instance to Node.js `http` / Express-style handlers.\n *\n * The request body streams from `req`, so the body cap is counted as bytes\n * arrive. When the client disconnects before the response finishes, the\n * request signal aborts and so does the S3 call behind it. Response bodies,\n * such as a `/file` download, stream to `res`.\n *\n * @example\n * ```ts\n * import { createServer } from \"node:http\";\n * import { toNodeHandler } from \"@dimah-s3/server/node\";\n * import { s3 } from \"./s3\";\n *\n * createServer(toNodeHandler(s3)).listen(3000);\n * // Behind a proxy that sets X-Forwarded-Proto / X-Forwarded-Host:\n * // createServer(toNodeHandler(s3, { trustProxy: true }));\n * ```\n */\nexport function toNodeHandler(\n s3: DimahS3HandlerSource,\n options: NodeHandlerOptions = {},\n) {\n return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n const controller = new AbortController();\n res.once(\"close\", () => {\n if (!res.writableFinished) controller.abort();\n });\n\n try {\n const request = toWebRequest(req, controller.signal, options);\n await writeWebResponse(res, await s3.handler(request));\n } catch (error) {\n // The client went away; there is no one to answer.\n if (controller.signal.aborted) return;\n defaultLogger.error?.(\"Node adapter failed\", error);\n if (res.headersSent) {\n res.destroy();\n } else {\n await writeWebResponse(res, toResponse(s3Error(\"INTERNAL_ERROR\")));\n }\n }\n };\n}\n\nfunction toWebRequest(\n req: IncomingMessage,\n signal: AbortSignal,\n options: NodeHandlerOptions,\n): Request {\n const method = (req.method ?? \"GET\").toUpperCase();\n const hasBody = method !== \"GET\" && method !== \"HEAD\";\n const init: RequestInit & { duplex?: \"half\" } = {\n method,\n headers: fromNodeHeaders(req.headers),\n signal,\n };\n if (hasBody) {\n // The DOM and Node typings of ReadableStream differ; the runtime object is the same.\n init.body = Readable.toWeb(req) as ReadableStream<Uint8Array<ArrayBuffer>>;\n // Node's fetch needs `duplex` for a streaming body.\n init.duplex = \"half\";\n }\n return new Request(requestURL(req, options), init);\n}\n\n/**\n * The absolute request URL, from the socket or the trusted proxy headers.\n * Express sets `originalUrl`, which keeps the mount path that\n * `app.use(\"/api/s3\", …)` strips from `url`.\n */\nfunction requestURL(req: IncomingMessage, options: NodeHandlerOptions): URL {\n const encrypted = (req.socket as { encrypted?: boolean }).encrypted === true;\n let protocol = encrypted ? \"https\" : \"http\";\n let host = req.headers.host ?? \"localhost\";\n\n if (options.trustProxy) {\n const forwardedProto = firstHeaderValue(req.headers[\"x-forwarded-proto\"]);\n if (forwardedProto === \"http\" || forwardedProto === \"https\") {\n protocol = forwardedProto;\n }\n host = firstHeaderValue(req.headers[\"x-forwarded-host\"]) || host;\n }\n const path = (req as { originalUrl?: string }).originalUrl ?? req.url;\n return new URL(path ?? \"/\", `${protocol}://${host}`);\n}\n\n/** The first entry of a header that proxies may append to (`a, b`). */\nfunction firstHeaderValue(value: string | string[] | undefined): string {\n const raw = Array.isArray(value) ? value[0] : value;\n return raw?.split(\",\")[0]?.trim().toLowerCase() ?? \"\";\n}\n\nasync function writeWebResponse(\n res: ServerResponse,\n response: Response,\n): Promise<void> {\n res.statusCode = response.status;\n for (const [key, value] of response.headers) {\n if (key === \"set-cookie\") continue;\n res.setHeader(key, value);\n }\n const cookies = response.headers.getSetCookie();\n if (cookies.length > 0) res.setHeader(\"set-cookie\", cookies);\n\n if (response.body === null) {\n res.end();\n return;\n }\n await pipeline(\n Readable.fromWeb(response.body as NodeReadableStream<Uint8Array>),\n res,\n );\n}\n","import type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { toNodeHandler, type NodeHandlerOptions } from \"./node\";\nimport type { DimahS3HandlerSource } from \"./types\";\n\nexport type { NodeHandlerOptions };\n\n/** Structural Fastify request/reply — avoids a hard dependency on `fastify`. */\ntype FastifyRequestLike = {\n raw: IncomingMessage;\n};\n\ntype FastifyReplyLike = {\n raw: ServerResponse;\n hijack: () => void;\n};\n\n/**\n * Adapt a dimah-s3 instance to a Fastify route handler.\n *\n * Uses `reply.hijack()` and the Node adapter so Fastify does not touch the\n * response stream. Turn Fastify's body parsing off for these routes, as\n * below, so the adapter can stream the raw body. Takes the same options as\n * `toNodeHandler`.\n *\n * @example\n * ```ts\n * import Fastify from \"fastify\";\n * import { toFastifyHandler } from \"@dimah-s3/server/fastify\";\n * import { s3 } from \"./s3\";\n *\n * const app = Fastify();\n * app.register(async (scope) => {\n * scope.removeAllContentTypeParsers();\n * scope.addContentTypeParser(\"*\", (_request, _payload, done) => done(null));\n * scope.all(\"/api/s3/*\", toFastifyHandler(s3));\n * });\n * ```\n */\nexport function toFastifyHandler(\n s3: DimahS3HandlerSource,\n options?: NodeHandlerOptions,\n) {\n const handler = toNodeHandler(s3, options);\n return async (req: FastifyRequestLike, reply: FastifyReplyLike) => {\n reply.hijack();\n await handler(req.raw, reply.raw);\n };\n}\n"]}
1
+ {"version":3,"sources":["../../src/helpers/logger.ts","../../src/adapters/node.ts","../../src/adapters/fastify.ts"],"names":[],"mappings":";;;;;;;AAEO,IAAM,aAAA,GAA+B;AAAA,EAC1C,KAAA,EAAO,CAAC,OAAA,EAAA,GAAY,IAAA,KAAS;AAC3B,IAAA,OAAA,CAAQ,KAAA,CAAM,YAAA,EAAc,OAAA,EAAS,GAAG,IAAI,CAAA;AAAA,EAC9C,CAAA;AAAA,EACA,IAAA,EAAM,CAAC,OAAA,EAAA,GAAY,IAAA,KAAS;AAC1B,IAAA,OAAA,CAAQ,IAAA,CAAK,YAAA,EAAc,OAAA,EAAS,GAAG,IAAI,CAAA;AAAA,EAC7C;AACF,CAAA;;;ACwBO,SAAS,gBAAgB,WAAA,EAA2C;AACzE,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GAAG,CAAA;AAAA,EAClC,CAAA;AACF","file":"fastify.js","sourcesContent":["import type { DimahS3Logger } from \"@/types\";\n\nexport const defaultLogger: DimahS3Logger = {\n error: (message, ...args) => {\n console.error(\"[dimah-s3]\", message, ...args);\n },\n warn: (message, ...args) => {\n console.warn(\"[dimah-s3]\", message, ...args);\n },\n};\n\nexport function resolveLogger(\n logger: DimahS3Logger | false | undefined,\n): DimahS3Logger {\n if (logger === false) return {};\n if (!logger) return defaultLogger;\n return logger;\n}\n","import type {\n IncomingHttpHeaders,\n IncomingMessage,\n ServerResponse,\n} from \"node:http\";\nimport { Readable } from \"node:stream\";\nimport { s3Error } from \"@dimah-s3/core\";\nimport { toResponse } from \"better-call\";\nimport { defaultLogger } from \"@/helpers/logger\";\nimport type { DimahS3HandlerSource } from \"./types\";\n\n/** Options of the Node, Express and Fastify adapters. */\nexport type NodeHandlerOptions = {\n /**\n * Build the request URL from `X-Forwarded-Proto` and `X-Forwarded-Host`.\n * Turn it on only behind a proxy that sets them, since clients can send\n * them too. Default `false`.\n */\n trustProxy?: boolean;\n};\n\n/**\n * Convert Node.js / Express request headers into a Web {@link Headers} object.\n * Useful when calling `s3.api.*` from a Node handler. HTTP/2 pseudo-headers\n * (`:path`) are left out.\n *\n * @example\n * ```ts\n * import { fromNodeHeaders } from \"@dimah-s3/server/node\";\n *\n * await s3.api.download({ route, key }, { headers: fromNodeHeaders(req.headers) });\n * ```\n */\nexport function fromNodeHeaders(nodeHeaders: IncomingHttpHeaders): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(nodeHeaders)) {\n if (value == null || key.startsWith(\":\")) continue;\n if (Array.isArray(value)) {\n for (const v of value) headers.append(key, v);\n } else {\n headers.set(key, value);\n }\n }\n return headers;\n}\n\n/**\n * Adapt a dimah-s3 instance to Node.js `http` / Express-style handlers.\n *\n * The request body streams from `req`, so the body cap is counted as bytes\n * arrive. When the client disconnects before the response finishes, the\n * request signal aborts and so does the S3 call behind it. Response bodies,\n * such as a `/file` download, stream to `res`.\n *\n * @example\n * ```ts\n * import { createServer } from \"node:http\";\n * import { toNodeHandler } from \"@dimah-s3/server/node\";\n * import { s3 } from \"./s3\";\n *\n * createServer(toNodeHandler(s3)).listen(3000);\n * // Behind a proxy that sets X-Forwarded-Proto / X-Forwarded-Host:\n * // createServer(toNodeHandler(s3, { trustProxy: true }));\n * ```\n */\nexport function toNodeHandler(\n s3: DimahS3HandlerSource,\n options: NodeHandlerOptions = {},\n) {\n return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n const controller = new AbortController();\n res.once(\"close\", () => {\n if (!res.writableFinished) controller.abort();\n });\n\n try {\n const request = toWebRequest(req, controller.signal, options);\n await writeWebResponse(res, await s3.handler(request));\n } catch (error) {\n // The client went away; there is no one to answer.\n if (controller.signal.aborted) return;\n defaultLogger.error?.(\"Node adapter failed\", error);\n if (res.headersSent) {\n res.destroy();\n } else {\n await writeWebResponse(res, toResponse(s3Error(\"INTERNAL_ERROR\")));\n }\n }\n };\n}\n\nfunction toWebRequest(\n req: IncomingMessage,\n signal: AbortSignal,\n options: NodeHandlerOptions,\n): Request {\n const method = (req.method ?? \"GET\").toUpperCase();\n const hasBody = method !== \"GET\" && method !== \"HEAD\";\n const init: RequestInit & { duplex?: \"half\" } = {\n method,\n headers: fromNodeHeaders(req.headers),\n signal,\n };\n if (hasBody) {\n // The DOM and Node typings of ReadableStream differ; the runtime object is the same.\n init.body = Readable.toWeb(req) as ReadableStream<Uint8Array<ArrayBuffer>>;\n // Node's fetch needs `duplex` for a streaming body.\n init.duplex = \"half\";\n }\n return new Request(requestURL(req, options), init);\n}\n\n/**\n * The absolute request URL, from the socket or the trusted proxy headers.\n * Express sets `originalUrl`, which keeps the mount path that\n * `app.use(\"/api/s3\", …)` strips from `url`.\n */\nfunction requestURL(req: IncomingMessage, options: NodeHandlerOptions): URL {\n const encrypted = (req.socket as { encrypted?: boolean }).encrypted === true;\n let protocol = encrypted ? \"https\" : \"http\";\n let host = req.headers.host ?? \"localhost\";\n\n if (options.trustProxy) {\n const forwardedProto = firstHeaderValue(req.headers[\"x-forwarded-proto\"]);\n if (forwardedProto === \"http\" || forwardedProto === \"https\") {\n protocol = forwardedProto;\n }\n host = firstHeaderValue(req.headers[\"x-forwarded-host\"]) || host;\n }\n const path = (req as { originalUrl?: string }).originalUrl ?? req.url;\n return new URL(path ?? \"/\", `${protocol}://${host}`);\n}\n\n/** The first entry of a header that proxies may append to (`a, b`). */\nfunction firstHeaderValue(value: string | string[] | undefined): string {\n const raw = Array.isArray(value) ? value[0] : value;\n return raw?.split(\",\")[0]?.trim().toLowerCase() ?? \"\";\n}\n\nasync function writeWebResponse(\n res: ServerResponse,\n response: Response,\n): Promise<void> {\n res.statusCode = response.status;\n for (const [key, value] of response.headers) {\n if (key === \"set-cookie\") continue;\n res.setHeader(key, value);\n }\n const cookies = response.headers.getSetCookie();\n if (cookies.length > 0) res.setHeader(\"set-cookie\", cookies);\n\n if (response.body === null) {\n res.end();\n return;\n }\n // `Readable.fromWeb` piped into `res` deadlocks once the body is larger\n // than the stream buffer: each side waits for the other to pull. Read\n // the web stream and write it, waiting for `drain` when Node's buffer\n // is full.\n const reader = response.body.getReader();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (res.destroyed || res.writableEnded) {\n await reader.cancel();\n return;\n }\n if (!value?.byteLength) continue;\n if (!res.write(value)) await waitForDrain(res);\n }\n if (!res.destroyed && !res.writableEnded) res.end();\n } catch (error) {\n await reader.cancel(error).catch(() => undefined);\n throw error;\n }\n}\n\n/** Resolves when `res` accepts more data, or when the client has gone. */\nfunction waitForDrain(res: ServerResponse): Promise<void> {\n return new Promise((resolve) => {\n const done = () => {\n res.off(\"drain\", done);\n res.off(\"close\", done);\n resolve();\n };\n res.once(\"drain\", done);\n res.once(\"close\", done);\n });\n}\n","import type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { toNodeHandler, type NodeHandlerOptions } from \"./node\";\nimport type { DimahS3HandlerSource } from \"./types\";\n\nexport type { NodeHandlerOptions };\n\n/** Structural Fastify request/reply — avoids a hard dependency on `fastify`. */\ntype FastifyRequestLike = {\n raw: IncomingMessage;\n};\n\ntype FastifyReplyLike = {\n raw: ServerResponse;\n hijack: () => void;\n};\n\n/**\n * Adapt a dimah-s3 instance to a Fastify route handler.\n *\n * Uses `reply.hijack()` and the Node adapter so Fastify does not touch the\n * response stream. Turn Fastify's body parsing off for these routes, as\n * below, so the adapter can stream the raw body. Takes the same options as\n * `toNodeHandler`.\n *\n * @example\n * ```ts\n * import Fastify from \"fastify\";\n * import { toFastifyHandler } from \"@dimah-s3/server/fastify\";\n * import { s3 } from \"./s3\";\n *\n * const app = Fastify();\n * app.register(async (scope) => {\n * scope.removeAllContentTypeParsers();\n * scope.addContentTypeParser(\"*\", (_request, _payload, done) => done(null));\n * scope.all(\"/api/s3/*\", toFastifyHandler(s3));\n * });\n * ```\n */\nexport function toFastifyHandler(\n s3: DimahS3HandlerSource,\n options?: NodeHandlerOptions,\n) {\n const handler = toNodeHandler(s3, options);\n return async (req: FastifyRequestLike, reply: FastifyReplyLike) => {\n reply.hijack();\n await handler(req.raw, reply.raw);\n };\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type { DimahS3HandlerSource } from "./types";
1
+ import type { DimahS3HandlerSource } from "./types.js";
2
2
  /** Structural Hono context — avoids a hard dependency on `hono`. */
3
3
  type HonoContext = {
4
4
  req: {
@@ -1,4 +1,4 @@
1
- import type { DimahS3HandlerSource } from "./types";
1
+ import type { DimahS3HandlerSource } from "./types.js";
2
2
  /**
3
3
  * Adapt a dimah-s3 instance to Next.js App Router route handlers.
4
4
  *
@@ -1,5 +1,5 @@
1
1
  import type { IncomingHttpHeaders, IncomingMessage, ServerResponse } from "node:http";
2
- import type { DimahS3HandlerSource } from "./types";
2
+ import type { DimahS3HandlerSource } from "./types.js";
3
3
  /** Options of the Node, Express and Fastify adapters. */
4
4
  export type NodeHandlerOptions = {
5
5
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"node.d.ts","sourceRoot":"","sources":["../../src/adapters/node.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,mBAAmB,EACnB,eAAe,EACf,cAAc,EACf,MAAM,WAAW,CAAC;AAOnB,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAC;AAEpD,yDAAyD;AACzD,MAAM,MAAM,kBAAkB,GAAG;IAC/B;;;;OAIG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,wBAAgB,eAAe,CAAC,WAAW,EAAE,mBAAmB,GAAG,OAAO,CAWzE;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,aAAa,CAC3B,EAAE,EAAE,oBAAoB,EACxB,OAAO,GAAE,kBAAuB,SAEb,eAAe,OAAO,cAAc,KAAG,OAAO,CAAC,IAAI,CAAC,CAoBxE"}
1
+ {"version":3,"file":"node.d.ts","sourceRoot":"","sources":["../../src/adapters/node.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,mBAAmB,EACnB,eAAe,EACf,cAAc,EACf,MAAM,WAAW,CAAC;AAKnB,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAC;AAEpD,yDAAyD;AACzD,MAAM,MAAM,kBAAkB,GAAG;IAC/B;;;;OAIG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,wBAAgB,eAAe,CAAC,WAAW,EAAE,mBAAmB,GAAG,OAAO,CAWzE;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,aAAa,CAC3B,EAAE,EAAE,oBAAoB,EACxB,OAAO,GAAE,kBAAuB,SAEb,eAAe,OAAO,cAAc,KAAG,OAAO,CAAC,IAAI,CAAC,CAoBxE"}
@@ -1,5 +1,4 @@
1
1
  import { Readable } from 'stream';
2
- import { pipeline } from 'stream/promises';
3
2
  import { s3Error } from '@dimah-s3/core';
4
3
  import { toResponse } from 'better-call';
5
4
 
@@ -92,10 +91,34 @@ async function writeWebResponse(res, response) {
92
91
  res.end();
93
92
  return;
94
93
  }
95
- await pipeline(
96
- Readable.fromWeb(response.body),
97
- res
98
- );
94
+ const reader = response.body.getReader();
95
+ try {
96
+ for (; ; ) {
97
+ const { done, value } = await reader.read();
98
+ if (done) break;
99
+ if (res.destroyed || res.writableEnded) {
100
+ await reader.cancel();
101
+ return;
102
+ }
103
+ if (!value?.byteLength) continue;
104
+ if (!res.write(value)) await waitForDrain(res);
105
+ }
106
+ if (!res.destroyed && !res.writableEnded) res.end();
107
+ } catch (error) {
108
+ await reader.cancel(error).catch(() => void 0);
109
+ throw error;
110
+ }
111
+ }
112
+ function waitForDrain(res) {
113
+ return new Promise((resolve) => {
114
+ const done = () => {
115
+ res.off("drain", done);
116
+ res.off("close", done);
117
+ resolve();
118
+ };
119
+ res.once("drain", done);
120
+ res.once("close", done);
121
+ });
99
122
  }
100
123
 
101
124
  export { fromNodeHeaders, toNodeHandler };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/helpers/logger.ts","../../src/adapters/node.ts"],"names":[],"mappings":";;;;;;;;AAEO,IAAM,aAAA,GAA+B;AAAA,EAC1C,KAAA,EAAO,CAAC,OAAA,EAAA,GAAY,IAAA,KAAS;AAC3B,IAAA,OAAA,CAAQ,KAAA,CAAM,YAAA,EAAc,OAAA,EAAS,GAAG,IAAI,CAAA;AAAA,EAC9C,CAAA;AAAA,EACA,IAAA,EAAM,CAAC,OAAA,EAAA,GAAY,IAAA,KAAS;AAC1B,IAAA,OAAA,CAAQ,IAAA,CAAK,YAAA,EAAc,OAAA,EAAS,GAAG,IAAI,CAAA;AAAA,EAC7C;AACF,CAAA;;;AC0BO,SAAS,gBAAgB,WAAA,EAA2C;AACzE,EAAA,MAAM,OAAA,GAAU,IAAI,OAAA,EAAQ;AAC5B,EAAA,KAAA,MAAW,CAAC,GAAA,EAAK,KAAK,KAAK,MAAA,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,MAAM,IAAA,GAAQ,GAAA,CAAiC,WAAA,IAAe,GAAA,CAAI,GAAA;AAClE,EAAA,OAAO,IAAI,IAAI,IAAA,IAAQ,GAAA,EAAK,GAAG,QAAQ,CAAA,GAAA,EAAM,IAAI,CAAA,CAAE,CAAA;AACrD;AAGA,SAAS,iBAAiB,KAAA,EAA8C;AACtE,EAAA,MAAM,MAAM,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA,GAAI,KAAA,CAAM,CAAC,CAAA,GAAI,KAAA;AAC9C,EAAA,OAAO,GAAA,EAAK,MAAM,GAAG,CAAA,CAAE,CAAC,CAAA,EAAG,IAAA,EAAK,CAAE,WAAA,EAAY,IAAK,EAAA;AACrD;AAEA,eAAe,gBAAA,CACb,KACA,QAAA,EACe;AACf,EAAA,GAAA,CAAI,aAAa,QAAA,CAAS,MAAA;AAC1B,EAAA,KAAA,MAAW,CAAC,GAAA,EAAK,KAAK,CAAA,IAAK,SAAS,OAAA,EAAS;AAC3C,IAAA,IAAI,QAAQ,YAAA,EAAc;AAC1B,IAAA,GAAA,CAAI,SAAA,CAAU,KAAK,KAAK,CAAA;AAAA,EAC1B;AACA,EAAA,MAAM,OAAA,GAAU,QAAA,CAAS,OAAA,CAAQ,YAAA,EAAa;AAC9C,EAAA,IAAI,QAAQ,MAAA,GAAS,CAAA,EAAG,GAAA,CAAI,SAAA,CAAU,cAAc,OAAO,CAAA;AAE3D,EAAA,IAAI,QAAA,CAAS,SAAS,IAAA,EAAM;AAC1B,IAAA,GAAA,CAAI,GAAA,EAAI;AACR,IAAA;AAAA,EACF;AACA,EAAA,MAAM,QAAA;AAAA,IACJ,QAAA,CAAS,OAAA,CAAQ,QAAA,CAAS,IAAsC,CAAA;AAAA,IAChE;AAAA,GACF;AACF","file":"node.js","sourcesContent":["import type { DimahS3Logger } from \"@/types\";\n\nexport const defaultLogger: DimahS3Logger = {\n error: (message, ...args) => {\n console.error(\"[dimah-s3]\", message, ...args);\n },\n warn: (message, ...args) => {\n console.warn(\"[dimah-s3]\", message, ...args);\n },\n};\n\nexport function resolveLogger(\n logger: DimahS3Logger | false | undefined,\n): DimahS3Logger {\n if (logger === false) return {};\n if (!logger) return defaultLogger;\n return logger;\n}\n","import type {\n IncomingHttpHeaders,\n IncomingMessage,\n ServerResponse,\n} from \"node:http\";\nimport { Readable } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport type { ReadableStream as NodeReadableStream } from \"node:stream/web\";\nimport { s3Error } from \"@dimah-s3/core\";\nimport { toResponse } from \"better-call\";\nimport { defaultLogger } from \"@/helpers/logger\";\nimport type { DimahS3HandlerSource } from \"./types\";\n\n/** Options of the Node, Express and Fastify adapters. */\nexport type NodeHandlerOptions = {\n /**\n * Build the request URL from `X-Forwarded-Proto` and `X-Forwarded-Host`.\n * Turn it on only behind a proxy that sets them, since clients can send\n * them too. Default `false`.\n */\n trustProxy?: boolean;\n};\n\n/**\n * Convert Node.js / Express request headers into a Web {@link Headers} object.\n * Useful when calling `s3.api.*` from a Node handler. HTTP/2 pseudo-headers\n * (`:path`) are left out.\n *\n * @example\n * ```ts\n * import { fromNodeHeaders } from \"@dimah-s3/server/node\";\n *\n * await s3.api.download({ route, key }, { headers: fromNodeHeaders(req.headers) });\n * ```\n */\nexport function fromNodeHeaders(nodeHeaders: IncomingHttpHeaders): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(nodeHeaders)) {\n if (value == null || key.startsWith(\":\")) continue;\n if (Array.isArray(value)) {\n for (const v of value) headers.append(key, v);\n } else {\n headers.set(key, value);\n }\n }\n return headers;\n}\n\n/**\n * Adapt a dimah-s3 instance to Node.js `http` / Express-style handlers.\n *\n * The request body streams from `req`, so the body cap is counted as bytes\n * arrive. When the client disconnects before the response finishes, the\n * request signal aborts and so does the S3 call behind it. Response bodies,\n * such as a `/file` download, stream to `res`.\n *\n * @example\n * ```ts\n * import { createServer } from \"node:http\";\n * import { toNodeHandler } from \"@dimah-s3/server/node\";\n * import { s3 } from \"./s3\";\n *\n * createServer(toNodeHandler(s3)).listen(3000);\n * // Behind a proxy that sets X-Forwarded-Proto / X-Forwarded-Host:\n * // createServer(toNodeHandler(s3, { trustProxy: true }));\n * ```\n */\nexport function toNodeHandler(\n s3: DimahS3HandlerSource,\n options: NodeHandlerOptions = {},\n) {\n return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n const controller = new AbortController();\n res.once(\"close\", () => {\n if (!res.writableFinished) controller.abort();\n });\n\n try {\n const request = toWebRequest(req, controller.signal, options);\n await writeWebResponse(res, await s3.handler(request));\n } catch (error) {\n // The client went away; there is no one to answer.\n if (controller.signal.aborted) return;\n defaultLogger.error?.(\"Node adapter failed\", error);\n if (res.headersSent) {\n res.destroy();\n } else {\n await writeWebResponse(res, toResponse(s3Error(\"INTERNAL_ERROR\")));\n }\n }\n };\n}\n\nfunction toWebRequest(\n req: IncomingMessage,\n signal: AbortSignal,\n options: NodeHandlerOptions,\n): Request {\n const method = (req.method ?? \"GET\").toUpperCase();\n const hasBody = method !== \"GET\" && method !== \"HEAD\";\n const init: RequestInit & { duplex?: \"half\" } = {\n method,\n headers: fromNodeHeaders(req.headers),\n signal,\n };\n if (hasBody) {\n // The DOM and Node typings of ReadableStream differ; the runtime object is the same.\n init.body = Readable.toWeb(req) as ReadableStream<Uint8Array<ArrayBuffer>>;\n // Node's fetch needs `duplex` for a streaming body.\n init.duplex = \"half\";\n }\n return new Request(requestURL(req, options), init);\n}\n\n/**\n * The absolute request URL, from the socket or the trusted proxy headers.\n * Express sets `originalUrl`, which keeps the mount path that\n * `app.use(\"/api/s3\", …)` strips from `url`.\n */\nfunction requestURL(req: IncomingMessage, options: NodeHandlerOptions): URL {\n const encrypted = (req.socket as { encrypted?: boolean }).encrypted === true;\n let protocol = encrypted ? \"https\" : \"http\";\n let host = req.headers.host ?? \"localhost\";\n\n if (options.trustProxy) {\n const forwardedProto = firstHeaderValue(req.headers[\"x-forwarded-proto\"]);\n if (forwardedProto === \"http\" || forwardedProto === \"https\") {\n protocol = forwardedProto;\n }\n host = firstHeaderValue(req.headers[\"x-forwarded-host\"]) || host;\n }\n const path = (req as { originalUrl?: string }).originalUrl ?? req.url;\n return new URL(path ?? \"/\", `${protocol}://${host}`);\n}\n\n/** The first entry of a header that proxies may append to (`a, b`). */\nfunction firstHeaderValue(value: string | string[] | undefined): string {\n const raw = Array.isArray(value) ? value[0] : value;\n return raw?.split(\",\")[0]?.trim().toLowerCase() ?? \"\";\n}\n\nasync function writeWebResponse(\n res: ServerResponse,\n response: Response,\n): Promise<void> {\n res.statusCode = response.status;\n for (const [key, value] of response.headers) {\n if (key === \"set-cookie\") continue;\n res.setHeader(key, value);\n }\n const cookies = response.headers.getSetCookie();\n if (cookies.length > 0) res.setHeader(\"set-cookie\", cookies);\n\n if (response.body === null) {\n res.end();\n return;\n }\n await pipeline(\n Readable.fromWeb(response.body as NodeReadableStream<Uint8Array>),\n res,\n );\n}\n"]}
1
+ {"version":3,"sources":["../../src/helpers/logger.ts","../../src/adapters/node.ts"],"names":[],"mappings":";;;;;;;AAEO,IAAM,aAAA,GAA+B;AAAA,EAC1C,KAAA,EAAO,CAAC,OAAA,EAAA,GAAY,IAAA,KAAS;AAC3B,IAAA,OAAA,CAAQ,KAAA,CAAM,YAAA,EAAc,OAAA,EAAS,GAAG,IAAI,CAAA;AAAA,EAC9C,CAAA;AAAA,EACA,IAAA,EAAM,CAAC,OAAA,EAAA,GAAY,IAAA,KAAS;AAC1B,IAAA,OAAA,CAAQ,IAAA,CAAK,YAAA,EAAc,OAAA,EAAS,GAAG,IAAI,CAAA;AAAA,EAC7C;AACF,CAAA;;;ACwBO,SAAS,gBAAgB,WAAA,EAA2C;AACzE,EAAA,MAAM,OAAA,GAAU,IAAI,OAAA,EAAQ;AAC5B,EAAA,KAAA,MAAW,CAAC,GAAA,EAAK,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,WAAW,CAAA,EAAG;AACtD,IAAA,IAAI,KAAA,IAAS,IAAA,IAAQ,GAAA,CAA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,IAAI,CAAC,OAAO,UAAA,EAAY;AACxB,MAAA,IAAI,CAAC,GAAA,CAAI,KAAA,CAAM,KAAK,CAAA,EAAG,MAAM,aAAa,GAAG,CAAA;AAAA,IAC/C;AACA,IAAA,IAAI,CAAC,GAAA,CAAI,SAAA,IAAa,CAAC,GAAA,CAAI,aAAA,MAAmB,GAAA,EAAI;AAAA,EACpD,SAAS,KAAA,EAAO;AACd,IAAA,MAAM,OAAO,MAAA,CAAO,KAAK,CAAA,CAAE,KAAA,CAAM,MAAM,MAAS,CAAA;AAChD,IAAA,MAAM,KAAA;AAAA,EACR;AACF;AAGA,SAAS,aAAa,GAAA,EAAoC;AACxD,EAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,OAAA,KAAY;AAC9B,IAAA,MAAM,OAAO,MAAM;AACjB,MAAA,GAAA,CAAI,GAAA,CAAI,SAAS,IAAI,CAAA;AACrB,MAAA,GAAA,CAAI,GAAA,CAAI,SAAS,IAAI,CAAA;AACrB,MAAA,OAAA,EAAQ;AAAA,IACV,CAAA;AACA,IAAA,GAAA,CAAI,IAAA,CAAK,SAAS,IAAI,CAAA;AACtB,IAAA,GAAA,CAAI,IAAA,CAAK,SAAS,IAAI,CAAA;AAAA,EACxB,CAAC,CAAA;AACH","file":"node.js","sourcesContent":["import type { DimahS3Logger } from \"@/types\";\n\nexport const defaultLogger: DimahS3Logger = {\n error: (message, ...args) => {\n console.error(\"[dimah-s3]\", message, ...args);\n },\n warn: (message, ...args) => {\n console.warn(\"[dimah-s3]\", message, ...args);\n },\n};\n\nexport function resolveLogger(\n logger: DimahS3Logger | false | undefined,\n): DimahS3Logger {\n if (logger === false) return {};\n if (!logger) return defaultLogger;\n return logger;\n}\n","import type {\n IncomingHttpHeaders,\n IncomingMessage,\n ServerResponse,\n} from \"node:http\";\nimport { Readable } from \"node:stream\";\nimport { s3Error } from \"@dimah-s3/core\";\nimport { toResponse } from \"better-call\";\nimport { defaultLogger } from \"@/helpers/logger\";\nimport type { DimahS3HandlerSource } from \"./types\";\n\n/** Options of the Node, Express and Fastify adapters. */\nexport type NodeHandlerOptions = {\n /**\n * Build the request URL from `X-Forwarded-Proto` and `X-Forwarded-Host`.\n * Turn it on only behind a proxy that sets them, since clients can send\n * them too. Default `false`.\n */\n trustProxy?: boolean;\n};\n\n/**\n * Convert Node.js / Express request headers into a Web {@link Headers} object.\n * Useful when calling `s3.api.*` from a Node handler. HTTP/2 pseudo-headers\n * (`:path`) are left out.\n *\n * @example\n * ```ts\n * import { fromNodeHeaders } from \"@dimah-s3/server/node\";\n *\n * await s3.api.download({ route, key }, { headers: fromNodeHeaders(req.headers) });\n * ```\n */\nexport function fromNodeHeaders(nodeHeaders: IncomingHttpHeaders): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(nodeHeaders)) {\n if (value == null || key.startsWith(\":\")) continue;\n if (Array.isArray(value)) {\n for (const v of value) headers.append(key, v);\n } else {\n headers.set(key, value);\n }\n }\n return headers;\n}\n\n/**\n * Adapt a dimah-s3 instance to Node.js `http` / Express-style handlers.\n *\n * The request body streams from `req`, so the body cap is counted as bytes\n * arrive. When the client disconnects before the response finishes, the\n * request signal aborts and so does the S3 call behind it. Response bodies,\n * such as a `/file` download, stream to `res`.\n *\n * @example\n * ```ts\n * import { createServer } from \"node:http\";\n * import { toNodeHandler } from \"@dimah-s3/server/node\";\n * import { s3 } from \"./s3\";\n *\n * createServer(toNodeHandler(s3)).listen(3000);\n * // Behind a proxy that sets X-Forwarded-Proto / X-Forwarded-Host:\n * // createServer(toNodeHandler(s3, { trustProxy: true }));\n * ```\n */\nexport function toNodeHandler(\n s3: DimahS3HandlerSource,\n options: NodeHandlerOptions = {},\n) {\n return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n const controller = new AbortController();\n res.once(\"close\", () => {\n if (!res.writableFinished) controller.abort();\n });\n\n try {\n const request = toWebRequest(req, controller.signal, options);\n await writeWebResponse(res, await s3.handler(request));\n } catch (error) {\n // The client went away; there is no one to answer.\n if (controller.signal.aborted) return;\n defaultLogger.error?.(\"Node adapter failed\", error);\n if (res.headersSent) {\n res.destroy();\n } else {\n await writeWebResponse(res, toResponse(s3Error(\"INTERNAL_ERROR\")));\n }\n }\n };\n}\n\nfunction toWebRequest(\n req: IncomingMessage,\n signal: AbortSignal,\n options: NodeHandlerOptions,\n): Request {\n const method = (req.method ?? \"GET\").toUpperCase();\n const hasBody = method !== \"GET\" && method !== \"HEAD\";\n const init: RequestInit & { duplex?: \"half\" } = {\n method,\n headers: fromNodeHeaders(req.headers),\n signal,\n };\n if (hasBody) {\n // The DOM and Node typings of ReadableStream differ; the runtime object is the same.\n init.body = Readable.toWeb(req) as ReadableStream<Uint8Array<ArrayBuffer>>;\n // Node's fetch needs `duplex` for a streaming body.\n init.duplex = \"half\";\n }\n return new Request(requestURL(req, options), init);\n}\n\n/**\n * The absolute request URL, from the socket or the trusted proxy headers.\n * Express sets `originalUrl`, which keeps the mount path that\n * `app.use(\"/api/s3\", …)` strips from `url`.\n */\nfunction requestURL(req: IncomingMessage, options: NodeHandlerOptions): URL {\n const encrypted = (req.socket as { encrypted?: boolean }).encrypted === true;\n let protocol = encrypted ? \"https\" : \"http\";\n let host = req.headers.host ?? \"localhost\";\n\n if (options.trustProxy) {\n const forwardedProto = firstHeaderValue(req.headers[\"x-forwarded-proto\"]);\n if (forwardedProto === \"http\" || forwardedProto === \"https\") {\n protocol = forwardedProto;\n }\n host = firstHeaderValue(req.headers[\"x-forwarded-host\"]) || host;\n }\n const path = (req as { originalUrl?: string }).originalUrl ?? req.url;\n return new URL(path ?? \"/\", `${protocol}://${host}`);\n}\n\n/** The first entry of a header that proxies may append to (`a, b`). */\nfunction firstHeaderValue(value: string | string[] | undefined): string {\n const raw = Array.isArray(value) ? value[0] : value;\n return raw?.split(\",\")[0]?.trim().toLowerCase() ?? \"\";\n}\n\nasync function writeWebResponse(\n res: ServerResponse,\n response: Response,\n): Promise<void> {\n res.statusCode = response.status;\n for (const [key, value] of response.headers) {\n if (key === \"set-cookie\") continue;\n res.setHeader(key, value);\n }\n const cookies = response.headers.getSetCookie();\n if (cookies.length > 0) res.setHeader(\"set-cookie\", cookies);\n\n if (response.body === null) {\n res.end();\n return;\n }\n // `Readable.fromWeb` piped into `res` deadlocks once the body is larger\n // than the stream buffer: each side waits for the other to pull. Read\n // the web stream and write it, waiting for `drain` when Node's buffer\n // is full.\n const reader = response.body.getReader();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (res.destroyed || res.writableEnded) {\n await reader.cancel();\n return;\n }\n if (!value?.byteLength) continue;\n if (!res.write(value)) await waitForDrain(res);\n }\n if (!res.destroyed && !res.writableEnded) res.end();\n } catch (error) {\n await reader.cancel(error).catch(() => undefined);\n throw error;\n }\n}\n\n/** Resolves when `res` accepts more data, or when the client has gone. */\nfunction waitForDrain(res: ServerResponse): Promise<void> {\n return new Promise((resolve) => {\n const done = () => {\n res.off(\"drain\", done);\n res.off(\"close\", done);\n resolve();\n };\n res.once(\"drain\", done);\n res.once(\"close\", done);\n });\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type { DimahS3HandlerSource } from "./types";
1
+ import type { DimahS3HandlerSource } from "./types.js";
2
2
  /** Structural SvelteKit event — avoids a hard dependency on `@sveltejs/kit`. */
3
3
  type SvelteKitRequestEvent = {
4
4
  request: Request;
@@ -1,5 +1,5 @@
1
1
  import { type EndpointBaseOptions, type EndpointHandler, type StandardSchemaV1 } from "better-call";
2
- import type { S3EndpointContext } from "./context";
2
+ import type { S3EndpointContext } from "./context.js";
3
3
  /** HTTP methods a dimah-s3 endpoint can use. */
4
4
  export type S3EndpointMethod = "GET" | "POST" | "PATCH" | "DELETE";
5
5
  /**
@@ -1,4 +1,4 @@
1
- import type { S3EndpointContext } from "./context";
1
+ import type { S3EndpointContext } from "./context.js";
2
2
  /**
3
3
  * Context middleware of every plugin endpoint. Plugin endpoints are guarded
4
4
  * here; core endpoints run their guards inside the operation.
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- export { dimahS3 } from "./dimah-s3";
2
- export type { DimahS3 } from "./dimah-s3";
3
- export { route } from "./route";
4
- export { chainHooks } from "./plugin";
1
+ export { dimahS3 } from "./dimah-s3.js";
2
+ export type { DimahS3 } from "./dimah-s3.js";
3
+ export { route } from "./route.js";
4
+ export { chainHooks } from "./plugin/index.js";
5
5
  export { APIError, isAPIError, isS3ErrorCode, s3Error, S3_ERROR_CODES, } from "@dimah-s3/core";
6
- export type { DeleteConfig, DeleteGuardContext, DeleteOnDeletedContext, DimahS3Api, DimahS3Config, DimahS3Locals, DimahS3Logger, DimahS3RouteConfig, DimahS3RoutePluginOptions, DownloadConfig, DownloadGuardContext, DownloadOnPresignedContext, DownloadResolveContext, DownloadResolveInfo, FeatureToggle, Guard, GuardContext, GuardResult, LifecycleHook, MultipartConfig, MultipartGuardContext, MultipartOnAbortContext, MultipartUploadContext, ObjectContext, ObjectS3Headers, PutInput, RouteGuardContext, S3Operation, S3ServerCallOptions, TicketSubject, UploadConfig, UploadConfirmGuardContext, UploadFile, UploadGuardContext, UploadKind, UploadObjectContext, UploadObjectInfo, UploadOnConfirmedContext, UploadOnStartContext, VerifiedObject, } from "./types";
6
+ export type { DeleteConfig, DeleteGuardContext, DeleteOnDeletedContext, DimahS3Api, DimahS3Config, DimahS3Locals, DimahS3Logger, DimahS3RouteConfig, DimahS3RoutePluginOptions, DownloadConfig, DownloadGuardContext, DownloadOnPresignedContext, DownloadResolveContext, DownloadResolveInfo, FeatureToggle, Guard, GuardContext, GuardResult, LifecycleHook, MultipartConfig, MultipartGuardContext, MultipartOnAbortContext, MultipartUploadContext, ObjectContext, ObjectS3Headers, PutInput, RouteGuardContext, S3Operation, S3ServerCallOptions, TicketSubject, UploadConfig, UploadConfirmGuardContext, UploadFile, UploadGuardContext, UploadKind, UploadObjectContext, UploadObjectInfo, UploadOnConfirmedContext, UploadOnStartContext, VerifiedObject, } from "./types/index.js";
7
7
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -326,7 +326,12 @@ async function capRequestBody(request, maxSize) {
326
326
  }
327
327
  chunks.push(value);
328
328
  }
329
- return new Request(request, { body: new Blob(chunks) });
329
+ return new Request(request.url, {
330
+ method: request.method,
331
+ headers: request.headers,
332
+ body: new Blob(chunks),
333
+ signal: request.signal
334
+ });
330
335
  }
331
336
  function isUnmatched(response) {
332
337
  return response.status === 404 && response.body === null;