@dimah-s3/server 1.7.0 → 2.0.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +72 -16
- package/dist/adapters/express.d.ts +7 -7
- package/dist/adapters/express.d.ts.map +1 -1
- package/dist/adapters/express.js +73 -96
- package/dist/adapters/express.js.map +1 -1
- package/dist/adapters/fastify.d.ts +11 -5
- package/dist/adapters/fastify.d.ts.map +1 -1
- package/dist/adapters/fastify.js +73 -96
- package/dist/adapters/fastify.js.map +1 -1
- package/dist/adapters/node.d.ts +20 -3
- package/dist/adapters/node.d.ts.map +1 -1
- package/dist/adapters/node.js +71 -94
- package/dist/adapters/node.js.map +1 -1
- package/dist/api/context.d.ts +8 -4
- package/dist/api/context.d.ts.map +1 -1
- package/dist/api/{routes/index.d.ts → core-endpoints.d.ts} +43 -68
- package/dist/api/core-endpoints.d.ts.map +1 -0
- package/dist/api/create-s3-endpoint.d.ts +70 -48
- package/dist/api/create-s3-endpoint.d.ts.map +1 -1
- package/dist/api/create-s3-middleware.d.ts +19 -16
- package/dist/api/create-s3-middleware.d.ts.map +1 -1
- package/dist/api/router-context.d.ts +23 -0
- package/dist/api/router-context.d.ts.map +1 -0
- package/dist/api/router.d.ts +15 -5
- package/dist/api/router.d.ts.map +1 -1
- package/dist/config/feature-toggle.d.ts +16 -0
- package/dist/config/feature-toggle.d.ts.map +1 -0
- package/dist/config/resolve-config.d.ts +9 -0
- package/dist/config/resolve-config.d.ts.map +1 -0
- package/dist/config/resolve-routes.d.ts +37 -0
- package/dist/config/resolve-routes.d.ts.map +1 -0
- package/dist/dimah-s3.d.ts +22 -32
- package/dist/dimah-s3.d.ts.map +1 -1
- package/dist/helpers/authorize-download.d.ts +25 -0
- package/dist/helpers/authorize-download.d.ts.map +1 -0
- package/dist/helpers/aws-errors.d.ts +16 -0
- package/dist/helpers/aws-errors.d.ts.map +1 -0
- package/dist/helpers/best-effort.d.ts +22 -3
- package/dist/helpers/best-effort.d.ts.map +1 -1
- package/dist/helpers/checksum-config.d.ts +13 -0
- package/dist/helpers/checksum-config.d.ts.map +1 -0
- package/dist/helpers/constraints.d.ts +17 -12
- package/dist/helpers/constraints.d.ts.map +1 -1
- package/dist/helpers/error-boundary.d.ts +28 -0
- package/dist/helpers/error-boundary.d.ts.map +1 -0
- package/dist/helpers/finalize-confirmed.d.ts +42 -13
- package/dist/helpers/finalize-confirmed.d.ts.map +1 -1
- package/dist/helpers/head-object.d.ts +6 -9
- package/dist/helpers/head-object.d.ts.map +1 -1
- package/dist/helpers/hooks.d.ts +29 -15
- package/dist/helpers/hooks.d.ts.map +1 -1
- package/dist/helpers/inline-types.d.ts +24 -7
- package/dist/helpers/inline-types.d.ts.map +1 -1
- package/dist/helpers/list-parts.d.ts +4 -6
- package/dist/helpers/list-parts.d.ts.map +1 -1
- package/dist/helpers/metadata-encoding.d.ts +15 -0
- package/dist/helpers/metadata-encoding.d.ts.map +1 -0
- package/dist/helpers/object-meta.d.ts +39 -0
- package/dist/helpers/object-meta.d.ts.map +1 -0
- package/dist/helpers/object-s3.d.ts +5 -2
- package/dist/helpers/object-s3.d.ts.map +1 -1
- package/dist/helpers/open-target.d.ts +89 -0
- package/dist/helpers/open-target.d.ts.map +1 -0
- package/dist/helpers/part-layout.d.ts +19 -0
- package/dist/helpers/part-layout.d.ts.map +1 -0
- package/dist/helpers/presign.d.ts +54 -0
- package/dist/helpers/presign.d.ts.map +1 -0
- package/dist/helpers/request.d.ts +6 -11
- package/dist/helpers/request.d.ts.map +1 -1
- package/dist/helpers/resolve-target.d.ts +28 -20
- package/dist/helpers/resolve-target.d.ts.map +1 -1
- package/dist/helpers/sniff-object.d.ts +22 -0
- package/dist/helpers/sniff-object.d.ts.map +1 -0
- package/dist/helpers/ticket.d.ts +75 -0
- package/dist/helpers/ticket.d.ts.map +1 -0
- package/dist/index.d.ts +4 -12
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2647 -1579
- package/dist/index.js.map +1 -1
- package/dist/operations/catalog.d.ts +16 -0
- package/dist/operations/catalog.d.ts.map +1 -0
- package/dist/operations/confirm.d.ts +19 -0
- package/dist/operations/confirm.d.ts.map +1 -0
- package/dist/operations/delete-many.d.ts +18 -0
- package/dist/operations/delete-many.d.ts.map +1 -0
- package/dist/operations/delete.d.ts +14 -0
- package/dist/operations/delete.d.ts.map +1 -0
- package/dist/operations/download.d.ts +20 -0
- package/dist/operations/download.d.ts.map +1 -0
- package/dist/operations/file.d.ts +38 -0
- package/dist/operations/file.d.ts.map +1 -0
- package/dist/operations/multipart/abort.d.ts +20 -0
- package/dist/operations/multipart/abort.d.ts.map +1 -0
- package/dist/operations/multipart/complete.d.ts +21 -0
- package/dist/operations/multipart/complete.d.ts.map +1 -0
- package/dist/operations/multipart/init.d.ts +19 -0
- package/dist/operations/multipart/init.d.ts.map +1 -0
- package/dist/operations/multipart/list-parts.d.ts +11 -0
- package/dist/operations/multipart/list-parts.d.ts.map +1 -0
- package/dist/operations/multipart/open-multipart.d.ts +25 -0
- package/dist/operations/multipart/open-multipart.d.ts.map +1 -0
- package/dist/operations/multipart/sign-part.d.ts +20 -0
- package/dist/operations/multipart/sign-part.d.ts.map +1 -0
- package/dist/operations/put.d.ts +18 -0
- package/dist/operations/put.d.ts.map +1 -0
- package/dist/operations/run-operation.d.ts +18 -0
- package/dist/operations/run-operation.d.ts.map +1 -0
- package/dist/operations/s3-api.d.ts +12 -0
- package/dist/operations/s3-api.d.ts.map +1 -0
- package/dist/operations/upload.d.ts +19 -0
- package/dist/operations/upload.d.ts.map +1 -0
- package/dist/plugin/apply-plugins.d.ts +9 -11
- package/dist/plugin/apply-plugins.d.ts.map +1 -1
- package/dist/plugin/chain-hooks.d.ts +12 -9
- package/dist/plugin/chain-hooks.d.ts.map +1 -1
- package/dist/plugin/define-plugin.d.ts +11 -4
- package/dist/plugin/define-plugin.d.ts.map +1 -1
- package/dist/plugin/index.d.ts +1 -2
- package/dist/plugin/index.d.ts.map +1 -1
- package/dist/plugin/types.d.ts +52 -56
- package/dist/plugin/types.d.ts.map +1 -1
- package/dist/plugins.d.ts +10 -8
- package/dist/plugins.d.ts.map +1 -1
- package/dist/plugins.js +325 -1627
- package/dist/plugins.js.map +1 -1
- package/dist/route.d.ts +0 -1
- package/dist/route.d.ts.map +1 -1
- package/dist/types/config.d.ts +171 -172
- package/dist/types/config.d.ts.map +1 -1
- package/dist/types/hook-contexts.d.ts +139 -147
- package/dist/types/hook-contexts.d.ts.map +1 -1
- package/dist/types/index.d.ts +3 -3
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/locals.d.ts +37 -0
- package/dist/types/locals.d.ts.map +1 -0
- package/dist/types/resolved.d.ts +118 -0
- package/dist/types/resolved.d.ts.map +1 -0
- package/package.json +9 -13
- package/dist/api/bind-endpoints.d.ts +0 -12
- package/dist/api/bind-endpoints.d.ts.map +0 -1
- package/dist/api/index.d.ts +0 -6
- package/dist/api/index.d.ts.map +0 -1
- package/dist/api/index.js +0 -1353
- package/dist/api/index.js.map +0 -1
- package/dist/api/routes/catalog.d.ts +0 -9
- package/dist/api/routes/catalog.d.ts.map +0 -1
- package/dist/api/routes/confirm.d.ts +0 -13
- package/dist/api/routes/confirm.d.ts.map +0 -1
- package/dist/api/routes/delete-batch.d.ts +0 -14
- package/dist/api/routes/delete-batch.d.ts.map +0 -1
- package/dist/api/routes/delete.d.ts +0 -26
- package/dist/api/routes/delete.d.ts.map +0 -1
- package/dist/api/routes/download.d.ts +0 -21
- package/dist/api/routes/download.d.ts.map +0 -1
- package/dist/api/routes/file.d.ts +0 -20
- package/dist/api/routes/file.d.ts.map +0 -1
- package/dist/api/routes/index.d.ts.map +0 -1
- package/dist/api/routes/multipart/abort.d.ts +0 -16
- package/dist/api/routes/multipart/abort.d.ts.map +0 -1
- package/dist/api/routes/multipart/complete.d.ts +0 -22
- package/dist/api/routes/multipart/complete.d.ts.map +0 -1
- package/dist/api/routes/multipart/init.d.ts +0 -22
- package/dist/api/routes/multipart/init.d.ts.map +0 -1
- package/dist/api/routes/multipart/list-parts.d.ts +0 -17
- package/dist/api/routes/multipart/list-parts.d.ts.map +0 -1
- package/dist/api/routes/multipart/part.d.ts +0 -20
- package/dist/api/routes/multipart/part.d.ts.map +0 -1
- package/dist/api/routes/upload.d.ts +0 -22
- package/dist/api/routes/upload.d.ts.map +0 -1
- package/dist/errors.d.ts +0 -23
- package/dist/errors.d.ts.map +0 -1
- package/dist/helpers/expires.d.ts +0 -21
- package/dist/helpers/expires.d.ts.map +0 -1
- package/dist/helpers/features.d.ts +0 -17
- package/dist/helpers/features.d.ts.map +0 -1
- package/dist/helpers/index.d.ts +0 -19
- package/dist/helpers/index.d.ts.map +0 -1
- package/dist/helpers/is-aws-not-found.d.ts +0 -5
- package/dist/helpers/is-aws-not-found.d.ts.map +0 -1
- package/dist/helpers/previous-key.d.ts +0 -5
- package/dist/helpers/previous-key.d.ts.map +0 -1
- package/dist/helpers/resolve-route.d.ts +0 -33
- package/dist/helpers/resolve-route.d.ts.map +0 -1
- package/dist/plugin/hook-registry.d.ts +0 -21
- package/dist/plugin/hook-registry.d.ts.map +0 -1
- package/dist/put.d.ts +0 -15
- package/dist/put.d.ts.map +0 -1
package/README.md
CHANGED
|
@@ -1,14 +1,26 @@
|
|
|
1
1
|
# @dimah-s3/server
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**2.0 beta.** Install with `@beta`. `@latest` stays on 1.x, and betas can include breaking changes until 2.0.0.
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
5
|
+
Presigned S3 upload, download, and delete handlers with route policies,
|
|
6
|
+
guards, and lifecycle hooks. One instance gives you an HTTP `handler`, an
|
|
7
|
+
in-process `api`, and `put` for server-side uploads.
|
|
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)
|
|
7
11
|
|
|
8
12
|
## Install
|
|
9
13
|
|
|
10
14
|
```bash
|
|
11
|
-
pnpm add @dimah-s3/server @aws-sdk/client-s3
|
|
15
|
+
pnpm add @dimah-s3/server@beta @aws-sdk/client-s3
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Set the upload ticket secret, at least 32 characters and the same on every
|
|
19
|
+
instance:
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
# .env — generate with: openssl rand -base64 32
|
|
23
|
+
DIMAH_S3_SECRET="…"
|
|
12
24
|
```
|
|
13
25
|
|
|
14
26
|
## Minimal setup
|
|
@@ -17,44 +29,88 @@ pnpm add @dimah-s3/server @aws-sdk/client-s3
|
|
|
17
29
|
import { S3Client } from "@aws-sdk/client-s3";
|
|
18
30
|
import { dimahS3, route } from "@dimah-s3/server";
|
|
19
31
|
|
|
20
|
-
export const awsS3 = new S3Client({
|
|
32
|
+
export const awsS3 = new S3Client({
|
|
33
|
+
region: process.env.S3_REGION,
|
|
34
|
+
// Required: presigned browser uploads cannot match SDK checksums.
|
|
35
|
+
requestChecksumCalculation: "WHEN_REQUIRED",
|
|
36
|
+
});
|
|
21
37
|
|
|
22
38
|
export const s3 = dimahS3({
|
|
23
39
|
client: awsS3,
|
|
24
40
|
bucket: process.env.S3_BUCKET!,
|
|
25
41
|
routes: {
|
|
26
42
|
uploads: route({
|
|
27
|
-
upload: { fileTypes: ["image/*"] },
|
|
43
|
+
upload: { fileTypes: ["image/*"], maxFileSize: 5 * 1024 * 1024 },
|
|
44
|
+
download: true,
|
|
45
|
+
delete: true,
|
|
28
46
|
}),
|
|
29
47
|
},
|
|
30
48
|
});
|
|
31
49
|
```
|
|
32
50
|
|
|
33
|
-
Mount with a framework adapter:
|
|
51
|
+
Mount it with a framework adapter:
|
|
34
52
|
|
|
35
53
|
```ts
|
|
36
|
-
// Next.js
|
|
54
|
+
// Next.js: app/api/s3/[...s3]/route.ts
|
|
37
55
|
import { toNextJsHandler } from "@dimah-s3/server/next";
|
|
38
56
|
export const { GET, POST, PUT, PATCH, DELETE } = toNextJsHandler(s3);
|
|
39
57
|
|
|
40
|
-
// Express
|
|
41
|
-
// Hono
|
|
42
|
-
// Fastify
|
|
43
|
-
// Elysia
|
|
58
|
+
// Express — @dimah-s3/server/express → toExpressHandler
|
|
59
|
+
// Hono — @dimah-s3/server/hono → toHonoHandler
|
|
60
|
+
// Fastify — @dimah-s3/server/fastify → toFastifyHandler
|
|
61
|
+
// Elysia — @dimah-s3/server/elysia → toElysiaHandler
|
|
44
62
|
// SvelteKit — @dimah-s3/server/svelte-kit → toSvelteKitHandler
|
|
45
|
-
// Node http — @dimah-s3/server/node
|
|
63
|
+
// Node http — @dimah-s3/server/node → toNodeHandler
|
|
64
|
+
// Any Fetch runtime: s3.handler(request)
|
|
46
65
|
```
|
|
47
66
|
|
|
48
|
-
See [Server Setup](https://s3.dimah.dev/docs/server/setup) for
|
|
67
|
+
See [Server Setup](https://v2.s3.dimah.dev/docs/server/setup) for every adapter.
|
|
49
68
|
|
|
50
|
-
|
|
69
|
+
## Guards and hooks
|
|
70
|
+
|
|
71
|
+
Guards return nothing to allow, `{ locals }` to pass values on, and throw
|
|
72
|
+
`s3Error(code)` to reject:
|
|
51
73
|
|
|
52
74
|
```ts
|
|
53
|
-
|
|
75
|
+
import { s3Error } from "@dimah-s3/server";
|
|
76
|
+
|
|
77
|
+
declare module "@dimah-s3/server" {
|
|
78
|
+
interface DimahS3Locals {
|
|
79
|
+
userId?: string;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export const s3 = dimahS3({
|
|
84
|
+
// ...
|
|
85
|
+
guard: async ({ request }) => {
|
|
86
|
+
const session = await getSession(request);
|
|
87
|
+
if (!session) throw s3Error("UNAUTHORIZED");
|
|
88
|
+
return { locals: { userId: session.userId } };
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
`upload.onStart` runs once an upload can begin, and `upload.onConfirmed` runs
|
|
94
|
+
after HeadObject verifies the stored object. `onConfirmed` runs at least once:
|
|
95
|
+
dedupe on `uploadToken`.
|
|
96
|
+
|
|
97
|
+
## In process
|
|
98
|
+
|
|
99
|
+
`s3.api` has the browser client's shape, with `{ headers, request, locals }`
|
|
100
|
+
last:
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
await s3.api.download({ route: "uploads", key }, { headers: await headers() });
|
|
104
|
+
|
|
105
|
+
await s3.put({ route: "uploads", name: "report.pdf", body: pdfBytes });
|
|
54
106
|
```
|
|
55
107
|
|
|
56
108
|
Optional persistence: add `db()` from [`@dimah-s3/db`](../db) to `plugins`.
|
|
57
109
|
|
|
110
|
+
## Upgrading from 1.7
|
|
111
|
+
|
|
112
|
+
See [Upgrade to 2.0 beta](https://v2.s3.dimah.dev/docs/migration-2-0).
|
|
113
|
+
|
|
58
114
|
## License
|
|
59
115
|
|
|
60
116
|
MIT
|
|
@@ -1,10 +1,13 @@
|
|
|
1
|
-
import { fromNodeHeaders } from "./node";
|
|
1
|
+
import { fromNodeHeaders, type NodeHandlerOptions } from "./node";
|
|
2
2
|
import type { DimahS3HandlerSource } from "./types";
|
|
3
|
-
export { fromNodeHeaders };
|
|
3
|
+
export { fromNodeHeaders, type NodeHandlerOptions };
|
|
4
4
|
/**
|
|
5
5
|
* Adapt a dimah-s3 instance to an Express / Connect handler.
|
|
6
6
|
*
|
|
7
7
|
* Mount **before** `express.json()` so the request body is not consumed early.
|
|
8
|
+
* A route (`app.all`) and a mount (`app.use("/api/s3", …)`) both work: the
|
|
9
|
+
* request URL is read from `req.originalUrl`. Takes the same options as
|
|
10
|
+
* `toNodeHandler`, such as `{ trustProxy: true }` behind a proxy.
|
|
8
11
|
*
|
|
9
12
|
* @example
|
|
10
13
|
* ```ts
|
|
@@ -13,12 +16,9 @@ export { fromNodeHeaders };
|
|
|
13
16
|
* import { s3 } from "./s3";
|
|
14
17
|
*
|
|
15
18
|
* const app = express();
|
|
16
|
-
*
|
|
17
|
-
* app.all("/api/s3/*", toExpressHandler(s3));
|
|
18
|
-
* // Express 5 — named wildcard
|
|
19
|
-
* // app.all("/api/s3/*splat", toExpressHandler(s3));
|
|
19
|
+
* app.use("/api/s3", toExpressHandler(s3));
|
|
20
20
|
* app.use(express.json());
|
|
21
21
|
* ```
|
|
22
22
|
*/
|
|
23
|
-
export declare function toExpressHandler(s3: DimahS3HandlerSource): (req: import("node:http").IncomingMessage, res: import("node:http").ServerResponse) => Promise<void>;
|
|
23
|
+
export declare function toExpressHandler(s3: DimahS3HandlerSource, options?: NodeHandlerOptions): (req: import("node:http").IncomingMessage, res: import("node:http").ServerResponse) => Promise<void>;
|
|
24
24
|
//# sourceMappingURL=express.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"express.d.ts","sourceRoot":"","sources":["../../src/adapters/express.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"express.d.ts","sourceRoot":"","sources":["../../src/adapters/express.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,eAAe,EAEf,KAAK,kBAAkB,EACxB,MAAM,QAAQ,CAAC;AAChB,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAC;AAEpD,OAAO,EAAE,eAAe,EAAE,KAAK,kBAAkB,EAAE,CAAC;AAEpD;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,gBAAgB,CAC9B,EAAE,EAAE,oBAAoB,EACxB,OAAO,CAAC,EAAE,kBAAkB,wGAG7B"}
|
package/dist/adapters/express.js
CHANGED
|
@@ -1,71 +1,25 @@
|
|
|
1
|
+
import { Readable } from 'stream';
|
|
2
|
+
import { pipeline } from 'stream/promises';
|
|
3
|
+
import { s3Error } from '@dimah-s3/core';
|
|
1
4
|
import { toResponse } from 'better-call';
|
|
2
|
-
import { S3_ERROR_CODES, APIError } from '@dimah-s3/core';
|
|
3
5
|
|
|
4
6
|
// src/adapters/node.ts
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
message: S3_ERROR_CODES.FEATURE_DISABLED.message.replaceAll(
|
|
15
|
-
"{feature}",
|
|
16
|
-
feature
|
|
17
|
-
),
|
|
18
|
-
params: { feature }
|
|
19
|
-
}),
|
|
20
|
-
invalidKey: () => APIError.from("BAD_REQUEST", S3_ERROR_CODES.INVALID_KEY),
|
|
21
|
-
unknownRoute: (route) => APIError.from("NOT_FOUND", {
|
|
22
|
-
code: S3_ERROR_CODES.UNKNOWN_ROUTE.code,
|
|
23
|
-
message: S3_ERROR_CODES.UNKNOWN_ROUTE.message,
|
|
24
|
-
params: { route }
|
|
25
|
-
}),
|
|
26
|
-
fileTypeNotAllowed: (fileName, contentType) => APIError.from("BAD_REQUEST", {
|
|
27
|
-
code: S3_ERROR_CODES.FILE_TYPE_NOT_ALLOWED.code,
|
|
28
|
-
message: S3_ERROR_CODES.FILE_TYPE_NOT_ALLOWED.message,
|
|
29
|
-
params: {
|
|
30
|
-
fileName,
|
|
31
|
-
...contentType ? { contentType } : {}
|
|
32
|
-
}
|
|
33
|
-
}),
|
|
34
|
-
s3NetworkError: (code) => APIError.from("BAD_GATEWAY", {
|
|
35
|
-
code: S3_ERROR_CODES.S3_NETWORK_ERROR.code,
|
|
36
|
-
message: S3_ERROR_CODES.S3_NETWORK_ERROR.message.replaceAll(
|
|
37
|
-
"{code}",
|
|
38
|
-
code
|
|
39
|
-
),
|
|
40
|
-
params: { code }
|
|
41
|
-
}),
|
|
42
|
-
multipartPartMissing: (partNumber) => APIError.from("BAD_REQUEST", {
|
|
43
|
-
code: S3_ERROR_CODES.MULTIPART_PART_MISSING.code,
|
|
44
|
-
message: S3_ERROR_CODES.MULTIPART_PART_MISSING.message.replaceAll(
|
|
45
|
-
"{partNumber}",
|
|
46
|
-
String(partNumber)
|
|
47
|
-
),
|
|
48
|
-
params: { partNumber }
|
|
49
|
-
}),
|
|
50
|
-
payloadTooLarge: (message = S3_ERROR_CODES.PAYLOAD_TOO_LARGE.message) => APIError.from("PAYLOAD_TOO_LARGE", {
|
|
51
|
-
...S3_ERROR_CODES.PAYLOAD_TOO_LARGE,
|
|
52
|
-
message
|
|
53
|
-
}),
|
|
54
|
-
quotaExceeded: (message = S3_ERROR_CODES.QUOTA_EXCEEDED.message) => APIError.from("PAYLOAD_TOO_LARGE", {
|
|
55
|
-
...S3_ERROR_CODES.QUOTA_EXCEEDED,
|
|
56
|
-
message
|
|
57
|
-
}),
|
|
58
|
-
validationError: (message) => APIError.from("BAD_REQUEST", {
|
|
59
|
-
code: S3_ERROR_CODES.VALIDATION_ERROR.code,
|
|
60
|
-
message
|
|
61
|
-
})
|
|
7
|
+
|
|
8
|
+
// src/helpers/logger.ts
|
|
9
|
+
var defaultLogger = {
|
|
10
|
+
error: (message, ...args) => {
|
|
11
|
+
console.error("[dimah-s3]", message, ...args);
|
|
12
|
+
},
|
|
13
|
+
warn: (message, ...args) => {
|
|
14
|
+
console.warn("[dimah-s3]", message, ...args);
|
|
15
|
+
}
|
|
62
16
|
};
|
|
63
17
|
|
|
64
18
|
// src/adapters/node.ts
|
|
65
19
|
function fromNodeHeaders(nodeHeaders) {
|
|
66
20
|
const headers = new Headers();
|
|
67
21
|
for (const [key, value] of Object.entries(nodeHeaders)) {
|
|
68
|
-
if (value == null) continue;
|
|
22
|
+
if (value == null || key.startsWith(":")) continue;
|
|
69
23
|
if (Array.isArray(value)) {
|
|
70
24
|
for (const v of value) headers.append(key, v);
|
|
71
25
|
} else {
|
|
@@ -74,56 +28,79 @@ function fromNodeHeaders(nodeHeaders) {
|
|
|
74
28
|
}
|
|
75
29
|
return headers;
|
|
76
30
|
}
|
|
77
|
-
function
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
31
|
+
function toNodeHandler(s3, options = {}) {
|
|
32
|
+
return async (req, res) => {
|
|
33
|
+
const controller = new AbortController();
|
|
34
|
+
res.once("close", () => {
|
|
35
|
+
if (!res.writableFinished) controller.abort();
|
|
36
|
+
});
|
|
37
|
+
try {
|
|
38
|
+
const request = toWebRequest(req, controller.signal, options);
|
|
39
|
+
await writeWebResponse(res, await s3.handler(request));
|
|
40
|
+
} catch (error) {
|
|
41
|
+
if (controller.signal.aborted) return;
|
|
42
|
+
defaultLogger.error?.("Node adapter failed", error);
|
|
43
|
+
if (res.headersSent) {
|
|
44
|
+
res.destroy();
|
|
45
|
+
} else {
|
|
46
|
+
await writeWebResponse(res, toResponse(s3Error("INTERNAL_ERROR")));
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
};
|
|
86
50
|
}
|
|
87
|
-
function toWebRequest(req,
|
|
88
|
-
const host = req.headers.host ?? "localhost";
|
|
89
|
-
const protocol = req.socket.encrypted === true ? "https" : "http";
|
|
90
|
-
const url = new URL(req.url ?? "/", `${protocol}://${host}`);
|
|
91
|
-
const headers = fromNodeHeaders(req.headers);
|
|
51
|
+
function toWebRequest(req, signal, options) {
|
|
92
52
|
const method = (req.method ?? "GET").toUpperCase();
|
|
93
|
-
const
|
|
94
|
-
|
|
95
|
-
|
|
53
|
+
const hasBody = method !== "GET" && method !== "HEAD";
|
|
54
|
+
const init = {
|
|
55
|
+
method,
|
|
56
|
+
headers: fromNodeHeaders(req.headers),
|
|
57
|
+
signal
|
|
58
|
+
};
|
|
59
|
+
if (hasBody) {
|
|
60
|
+
init.body = Readable.toWeb(req);
|
|
96
61
|
init.duplex = "half";
|
|
97
62
|
}
|
|
98
|
-
return new Request(
|
|
63
|
+
return new Request(requestURL(req, options), init);
|
|
64
|
+
}
|
|
65
|
+
function requestURL(req, options) {
|
|
66
|
+
const encrypted = req.socket.encrypted === true;
|
|
67
|
+
let protocol = encrypted ? "https" : "http";
|
|
68
|
+
let host = req.headers.host ?? "localhost";
|
|
69
|
+
if (options.trustProxy) {
|
|
70
|
+
const forwardedProto = firstHeaderValue(req.headers["x-forwarded-proto"]);
|
|
71
|
+
if (forwardedProto === "http" || forwardedProto === "https") {
|
|
72
|
+
protocol = forwardedProto;
|
|
73
|
+
}
|
|
74
|
+
host = firstHeaderValue(req.headers["x-forwarded-host"]) || host;
|
|
75
|
+
}
|
|
76
|
+
const path = req.originalUrl ?? req.url;
|
|
77
|
+
return new URL(path ?? "/", `${protocol}://${host}`);
|
|
78
|
+
}
|
|
79
|
+
function firstHeaderValue(value) {
|
|
80
|
+
const raw = Array.isArray(value) ? value[0] : value;
|
|
81
|
+
return raw?.split(",")[0]?.trim().toLowerCase() ?? "";
|
|
99
82
|
}
|
|
100
83
|
async function writeWebResponse(res, response) {
|
|
101
84
|
res.statusCode = response.status;
|
|
102
85
|
for (const [key, value] of response.headers) {
|
|
86
|
+
if (key === "set-cookie") continue;
|
|
103
87
|
res.setHeader(key, value);
|
|
104
88
|
}
|
|
105
|
-
const
|
|
106
|
-
res.
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
} catch (err) {
|
|
116
|
-
console.error("[S3 API]", err);
|
|
117
|
-
if (!res.headersSent) {
|
|
118
|
-
await writeWebResponse(res, toResponse(errors.internalError()));
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
};
|
|
89
|
+
const cookies = response.headers.getSetCookie();
|
|
90
|
+
if (cookies.length > 0) res.setHeader("set-cookie", cookies);
|
|
91
|
+
if (response.body === null) {
|
|
92
|
+
res.end();
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
await pipeline(
|
|
96
|
+
Readable.fromWeb(response.body),
|
|
97
|
+
res
|
|
98
|
+
);
|
|
122
99
|
}
|
|
123
100
|
|
|
124
101
|
// src/adapters/express.ts
|
|
125
|
-
function toExpressHandler(s3) {
|
|
126
|
-
return toNodeHandler(s3);
|
|
102
|
+
function toExpressHandler(s3, options) {
|
|
103
|
+
return toNodeHandler(s3, options);
|
|
127
104
|
}
|
|
128
105
|
|
|
129
106
|
export { fromNodeHeaders, toExpressHandler };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/errors.ts","../../src/adapters/node.ts","../../src/adapters/express.ts"],"names":[],"mappings":";;;;AAWO,IAAM,MAAA,GAAS;AAAA,EACpB,UAAU,MAAM,QAAA,CAAS,IAAA,CAAK,WAAA,EAAa,eAAe,SAAS,CAAA;AAAA,EAEnE,cAAc,MACZ,QAAA,CAAS,IAAA,CAAK,cAAA,EAAgB,eAAe,YAAY,CAAA;AAAA,EAE3D,WAAW,MAAM,QAAA,CAAS,IAAA,CAAK,WAAA,EAAa,eAAe,SAAS,CAAA;AAAA,EAEpE,UAAU,MAAM,QAAA,CAAS,IAAA,CAAK,UAAA,EAAY,eAAe,QAAQ,CAAA;AAAA,EAEjE,eAAe,MACb,QAAA,CAAS,IAAA,CAAK,uBAAA,EAAyB,eAAe,cAAc,CAAA;AAAA,EAEtE,gBAAgB,MACd,QAAA,CAAS,IAAA,CAAK,WAAA,EAAa,eAAe,gBAAgB,CAAA;AAAA,EAE5D,eAAA,EAAiB,CAAC,OAAA,KAChB,QAAA,CAAS,KAAK,WAAA,EAAa;AAAA,IACzB,IAAA,EAAM,eAAe,gBAAA,CAAiB,IAAA;AAAA,IACtC,OAAA,EAAS,cAAA,CAAe,gBAAA,CAAiB,OAAA,CAAQ,UAAA;AAAA,MAC/C,WAAA;AAAA,MACA;AAAA,KACF;AAAA,IACA,MAAA,EAAQ,EAAE,OAAA;AAAQ,GACnB,CAAA;AAAA,EAEH,YAAY,MAAM,QAAA,CAAS,IAAA,CAAK,aAAA,EAAe,eAAe,WAAW,CAAA;AAAA,EAEzE,YAAA,EAAc,CAAC,KAAA,KACb,QAAA,CAAS,KAAK,WAAA,EAAa;AAAA,IACzB,IAAA,EAAM,eAAe,aAAA,CAAc,IAAA;AAAA,IACnC,OAAA,EAAS,eAAe,aAAA,CAAc,OAAA;AAAA,I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EAA0B;AACtD,EAAA,OAAO,OAAO,KAAsB,GAAA,KAAuC;AACzE,IAAA,IAAI;AACF,MAAA,MAAM,IAAA,GAAO,MAAM,WAAA,CAAY,GAAG,CAAA;AAClC,MAAA,MAAM,OAAA,GAAU,YAAA,CAAa,GAAA,EAAK,IAAI,CAAA;AACtC,MAAA,MAAM,QAAA,GAAW,MAAM,EAAA,CAAG,OAAA,CAAQ,OAAO,CAAA;AACzC,MAAA,MAAM,gBAAA,CAAiB,KAAK,QAAQ,CAAA;AAAA,IACtC,SAAS,GAAA,EAAK;AACZ,MAAA,OAAA,CAAQ,KAAA,CAAM,YAAY,GAAG,CAAA;AAC7B,MAAA,IAAI,CAAC,IAAI,WAAA,EAAa;AACpB,QAAA,MAAM,iBAAiB,GAAA,EAAK,UAAA,CAAW,MAAA,CAAO,aAAA,EAAe,CAAC,CAAA;AAAA,MAChE;AAAA,IACF;AAAA,EACF,CAAA;AACF;;;AC9EO,SAAS,iBAAiB,EAAA,EAA0B;AACzD,EAAA,OAAO,cAAc,EAAE,CAAA;AACzB","file":"express.js","sourcesContent":["import {\n APIError,\n S3_ERROR_CODES,\n isAPIError,\n isS3ErrorCode,\n} from \"@dimah-s3/core\";\nimport type { RouteOperation } from \"@/types/config\";\n\nexport { APIError, S3_ERROR_CODES, isAPIError, isS3ErrorCode };\n\n/** English API errors with stable codes for client-side localization. */\nexport const errors = {\n notFound: () => APIError.from(\"NOT_FOUND\", S3_ERROR_CODES.NOT_FOUND),\n\n unauthorized: () =>\n APIError.from(\"UNAUTHORIZED\", S3_ERROR_CODES.UNAUTHORIZED),\n\n forbidden: () => APIError.from(\"FORBIDDEN\", S3_ERROR_CODES.FORBIDDEN),\n\n conflict: () => APIError.from(\"CONFLICT\", S3_ERROR_CODES.CONFLICT),\n\n internalError: () =>\n APIError.from(\"INTERNAL_SERVER_ERROR\", S3_ERROR_CODES.INTERNAL_ERROR),\n\n objectNotFound: () =>\n APIError.from(\"NOT_FOUND\", S3_ERROR_CODES.OBJECT_NOT_FOUND),\n\n featureDisabled: (feature: RouteOperation) =>\n APIError.from(\"NOT_FOUND\", {\n code: S3_ERROR_CODES.FEATURE_DISABLED.code,\n message: S3_ERROR_CODES.FEATURE_DISABLED.message.replaceAll(\n \"{feature}\",\n feature,\n ),\n params: { feature },\n }),\n\n invalidKey: () => APIError.from(\"BAD_REQUEST\", S3_ERROR_CODES.INVALID_KEY),\n\n unknownRoute: (route: string) =>\n APIError.from(\"NOT_FOUND\", {\n code: S3_ERROR_CODES.UNKNOWN_ROUTE.code,\n message: S3_ERROR_CODES.UNKNOWN_ROUTE.message,\n params: { route },\n }),\n\n fileTypeNotAllowed: (fileName: string, contentType?: string) =>\n APIError.from(\"BAD_REQUEST\", {\n code: S3_ERROR_CODES.FILE_TYPE_NOT_ALLOWED.code,\n message: S3_ERROR_CODES.FILE_TYPE_NOT_ALLOWED.message,\n params: {\n fileName,\n ...(contentType ? { contentType } : {}),\n },\n }),\n\n s3NetworkError: (code: string) =>\n APIError.from(\"BAD_GATEWAY\", {\n code: S3_ERROR_CODES.S3_NETWORK_ERROR.code,\n message: S3_ERROR_CODES.S3_NETWORK_ERROR.message.replaceAll(\n \"{code}\",\n code,\n ),\n params: { code },\n }),\n\n multipartPartMissing: (partNumber: number) =>\n APIError.from(\"BAD_REQUEST\", {\n code: S3_ERROR_CODES.MULTIPART_PART_MISSING.code,\n message: S3_ERROR_CODES.MULTIPART_PART_MISSING.message.replaceAll(\n \"{partNumber}\",\n String(partNumber),\n ),\n params: { partNumber },\n }),\n\n payloadTooLarge: (\n message: string = S3_ERROR_CODES.PAYLOAD_TOO_LARGE.message,\n ) =>\n APIError.from(\"PAYLOAD_TOO_LARGE\", {\n ...S3_ERROR_CODES.PAYLOAD_TOO_LARGE,\n message,\n }),\n\n quotaExceeded: (message: string = S3_ERROR_CODES.QUOTA_EXCEEDED.message) =>\n APIError.from(\"PAYLOAD_TOO_LARGE\", {\n ...S3_ERROR_CODES.QUOTA_EXCEEDED,\n message,\n }),\n\n validationError: (message: string) =>\n APIError.from(\"BAD_REQUEST\", {\n code: S3_ERROR_CODES.VALIDATION_ERROR.code,\n message,\n }),\n} as const;\n\nexport type ServerErrors = typeof errors;\n","import { toResponse } from \"better-call\";\nimport type {\n IncomingHttpHeaders,\n IncomingMessage,\n ServerResponse,\n} from \"node:http\";\nimport { errors } from \"@/errors\";\nimport type { DimahS3HandlerSource } from \"./types\";\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.\n *\n * @example\n * ```ts\n * import { fromNodeHeaders } from \"@dimah-s3/server/node\";\n *\n * await s3.api.download({ query: { 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) 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\nfunction collectBody(req: IncomingMessage): Promise<Buffer> {\n const { promise, resolve, reject } = Promise.withResolvers<Buffer>();\n const chunks: Buffer[] = [];\n req.on(\"data\", (chunk: Buffer | string) => {\n chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk) : chunk);\n });\n req.on(\"end\", () => resolve(Buffer.concat(chunks)));\n req.on(\"error\", reject);\n return promise;\n}\n\nfunction toWebRequest(req: IncomingMessage, body: Buffer): Request {\n const host = req.headers.host ?? \"localhost\";\n const protocol =\n (req.socket as { encrypted?: boolean }).encrypted === true\n ? \"https\"\n : \"http\";\n const url = new URL(req.url ?? \"/\", `${protocol}://${host}`);\n\n const headers = fromNodeHeaders(req.headers);\n const method = (req.method ?? \"GET\").toUpperCase();\n const init: RequestInit = { method, headers };\n if (method !== \"GET\" && method !== \"HEAD\") {\n init.body = new Uint8Array(body);\n // @ts-expect-error Node fetch duplex for streaming bodies\n init.duplex = \"half\";\n }\n\n return new Request(url, init);\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 res.setHeader(key, value);\n }\n const buffer = Buffer.from(await response.arrayBuffer());\n res.end(buffer);\n}\n\n/**\n * Adapt a dimah-s3 instance to Node.js `http` / Express-style handlers.\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 * ```\n */\nexport function toNodeHandler(s3: DimahS3HandlerSource) {\n return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n try {\n const body = await collectBody(req);\n const request = toWebRequest(req, body);\n const response = await s3.handler(request);\n await writeWebResponse(res, response);\n } catch (err) {\n console.error(\"[S3 API]\", err);\n if (!res.headersSent) {\n await writeWebResponse(res, toResponse(errors.internalError()));\n }\n }\n };\n}\n","import { fromNodeHeaders, toNodeHandler } from \"./node\";\nimport type { DimahS3HandlerSource } from \"./types\";\n\nexport { fromNodeHeaders };\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 *\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 * // Express 4\n * app.all(\"/api/s3/*\", toExpressHandler(s3));\n * // Express 5 — named wildcard\n * // app.all(\"/api/s3/*splat\", toExpressHandler(s3));\n * app.use(express.json());\n * ```\n */\nexport function toExpressHandler(s3: DimahS3HandlerSource) {\n return toNodeHandler(s3);\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,CAA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AA,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,5 +1,7 @@
|
|
|
1
1
|
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
import { type NodeHandlerOptions } from "./node";
|
|
2
3
|
import type { DimahS3HandlerSource } from "./types";
|
|
4
|
+
export type { NodeHandlerOptions };
|
|
3
5
|
/** Structural Fastify request/reply — avoids a hard dependency on `fastify`. */
|
|
4
6
|
type FastifyRequestLike = {
|
|
5
7
|
raw: IncomingMessage;
|
|
@@ -12,8 +14,9 @@ type FastifyReplyLike = {
|
|
|
12
14
|
* Adapt a dimah-s3 instance to a Fastify route handler.
|
|
13
15
|
*
|
|
14
16
|
* Uses `reply.hijack()` and the Node adapter so Fastify does not touch the
|
|
15
|
-
* response stream.
|
|
16
|
-
*
|
|
17
|
+
* response stream. Turn Fastify's body parsing off for these routes, as
|
|
18
|
+
* below, so the adapter can stream the raw body. Takes the same options as
|
|
19
|
+
* `toNodeHandler`.
|
|
17
20
|
*
|
|
18
21
|
* @example
|
|
19
22
|
* ```ts
|
|
@@ -22,9 +25,12 @@ type FastifyReplyLike = {
|
|
|
22
25
|
* import { s3 } from "./s3";
|
|
23
26
|
*
|
|
24
27
|
* const app = Fastify();
|
|
25
|
-
* app.
|
|
28
|
+
* app.register(async (scope) => {
|
|
29
|
+
* scope.removeAllContentTypeParsers();
|
|
30
|
+
* scope.addContentTypeParser("*", (_request, _payload, done) => done(null));
|
|
31
|
+
* scope.all("/api/s3/*", toFastifyHandler(s3));
|
|
32
|
+
* });
|
|
26
33
|
* ```
|
|
27
34
|
*/
|
|
28
|
-
export declare function toFastifyHandler(s3: DimahS3HandlerSource): (req: FastifyRequestLike, reply: FastifyReplyLike) => Promise<void>;
|
|
29
|
-
export {};
|
|
35
|
+
export declare function toFastifyHandler(s3: DimahS3HandlerSource, options?: NodeHandlerOptions): (req: FastifyRequestLike, reply: FastifyReplyLike) => Promise<void>;
|
|
30
36
|
//# sourceMappingURL=fastify.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fastify.d.ts","sourceRoot":"","sources":["../../src/adapters/fastify.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;
|
|
1
|
+
{"version":3,"file":"fastify.d.ts","sourceRoot":"","sources":["../../src/adapters/fastify.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AACjE,OAAO,EAAiB,KAAK,kBAAkB,EAAE,MAAM,QAAQ,CAAC;AAChE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAC;AAEpD,YAAY,EAAE,kBAAkB,EAAE,CAAC;AAEnC,gFAAgF;AAChF,KAAK,kBAAkB,GAAG;IACxB,GAAG,EAAE,eAAe,CAAC;CACtB,CAAC;AAEF,KAAK,gBAAgB,GAAG;IACtB,GAAG,EAAE,cAAc,CAAC;IACpB,MAAM,EAAE,MAAM,IAAI,CAAC;CACpB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,gBAAgB,CAC9B,EAAE,EAAE,oBAAoB,EACxB,OAAO,CAAC,EAAE,kBAAkB,SAGT,kBAAkB,SAAS,gBAAgB,mBAI/D"}
|