@softistx/s3 0.0.0-stage → 0.13.2

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.
Files changed (93) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +609 -2
  3. package/dist/bucket/bind-bucket.d.ts +42 -0
  4. package/dist/bucket/bind-bucket.d.ts.map +1 -0
  5. package/dist/bucket/bound-bucket.d.ts +119 -0
  6. package/dist/bucket/bound-bucket.d.ts.map +1 -0
  7. package/dist/bucket/context.d.ts +55 -0
  8. package/dist/bucket/context.d.ts.map +1 -0
  9. package/dist/bucket/define-bucket.d.ts +16 -0
  10. package/dist/bucket/define-bucket.d.ts.map +1 -0
  11. package/dist/bucket/disposition.d.ts +9 -0
  12. package/dist/bucket/disposition.d.ts.map +1 -0
  13. package/dist/bucket/guards.d.ts +38 -0
  14. package/dist/bucket/guards.d.ts.map +1 -0
  15. package/dist/bucket/operations/counted-stream.d.ts +26 -0
  16. package/dist/bucket/operations/counted-stream.d.ts.map +1 -0
  17. package/dist/bucket/operations/deadline.d.ts +21 -0
  18. package/dist/bucket/operations/deadline.d.ts.map +1 -0
  19. package/dist/bucket/operations/fetch-object.d.ts +68 -0
  20. package/dist/bucket/operations/fetch-object.d.ts.map +1 -0
  21. package/dist/bucket/operations/list-xml.d.ts +18 -0
  22. package/dist/bucket/operations/list-xml.d.ts.map +1 -0
  23. package/dist/bucket/operations/list.d.ts +12 -0
  24. package/dist/bucket/operations/list.d.ts.map +1 -0
  25. package/dist/bucket/operations/open-answer.d.ts +5 -0
  26. package/dist/bucket/operations/open-answer.d.ts.map +1 -0
  27. package/dist/bucket/operations/open-range.d.ts +10 -0
  28. package/dist/bucket/operations/open-range.d.ts.map +1 -0
  29. package/dist/bucket/operations/open-relay.d.ts +8 -0
  30. package/dist/bucket/operations/open-relay.d.ts.map +1 -0
  31. package/dist/bucket/operations/open.d.ts +4 -0
  32. package/dist/bucket/operations/open.d.ts.map +1 -0
  33. package/dist/bucket/operations/post-policy.d.ts +77 -0
  34. package/dist/bucket/operations/post-policy.d.ts.map +1 -0
  35. package/dist/bucket/operations/post-signer.d.ts +21 -0
  36. package/dist/bucket/operations/post-signer.d.ts.map +1 -0
  37. package/dist/bucket/operations/presign-post.d.ts +44 -0
  38. package/dist/bucket/operations/presign-post.d.ts.map +1 -0
  39. package/dist/bucket/operations/presign.d.ts +34 -0
  40. package/dist/bucket/operations/presign.d.ts.map +1 -0
  41. package/dist/bucket/operations/put-body.d.ts +13 -0
  42. package/dist/bucket/operations/put-body.d.ts.map +1 -0
  43. package/dist/bucket/operations/query-sign.d.ts +15 -0
  44. package/dist/bucket/operations/query-sign.d.ts.map +1 -0
  45. package/dist/bucket/operations/reads.d.ts +8 -0
  46. package/dist/bucket/operations/reads.d.ts.map +1 -0
  47. package/dist/bucket/operations/sized-body.d.ts +24 -0
  48. package/dist/bucket/operations/sized-body.d.ts.map +1 -0
  49. package/dist/bucket/operations/slice.d.ts +4 -0
  50. package/dist/bucket/operations/slice.d.ts.map +1 -0
  51. package/dist/bucket/operations/writes.d.ts +10 -0
  52. package/dist/bucket/operations/writes.d.ts.map +1 -0
  53. package/dist/bucket/shape.d.ts +6 -0
  54. package/dist/bucket/shape.d.ts.map +1 -0
  55. package/dist/bucket/types.d.ts +164 -0
  56. package/dist/bucket/types.d.ts.map +1 -0
  57. package/dist/chunks/index-jgjey570.js +118 -0
  58. package/dist/chunks/index-jgjey570.js.map +13 -0
  59. package/dist/errors/is-bucket-unavailable.d.ts +18 -0
  60. package/dist/errors/is-bucket-unavailable.d.ts.map +1 -0
  61. package/dist/errors/s3-error.d.ts +80 -0
  62. package/dist/errors/s3-error.d.ts.map +1 -0
  63. package/dist/index.d.ts +8 -0
  64. package/dist/index.d.ts.map +1 -0
  65. package/dist/index.js +1288 -0
  66. package/dist/index.js.map +32 -0
  67. package/dist/testing/fetch-archive.d.ts +8 -0
  68. package/dist/testing/fetch-archive.d.ts.map +1 -0
  69. package/dist/testing/index.d.ts +6 -0
  70. package/dist/testing/index.d.ts.map +1 -0
  71. package/dist/testing/index.js +416 -0
  72. package/dist/testing/index.js.map +16 -0
  73. package/dist/testing/ports.d.ts +15 -0
  74. package/dist/testing/ports.d.ts.map +1 -0
  75. package/dist/testing/ready.d.ts +49 -0
  76. package/dist/testing/ready.d.ts.map +1 -0
  77. package/dist/testing/reaper.d.ts +4 -0
  78. package/dist/testing/reaper.d.ts.map +1 -0
  79. package/dist/testing/seaweedfs.d.ts +64 -0
  80. package/dist/testing/seaweedfs.d.ts.map +1 -0
  81. package/dist/testing/test-s3.d.ts +35 -0
  82. package/dist/testing/test-s3.d.ts.map +1 -0
  83. package/dist/testing/weed.d.ts +17 -0
  84. package/dist/testing/weed.d.ts.map +1 -0
  85. package/docs/README.md +17 -0
  86. package/docs/guide/buckets.md +220 -0
  87. package/docs/guide/presigned-urls.md +403 -0
  88. package/docs/guide/reads.md +417 -0
  89. package/docs/guide/testing.md +151 -0
  90. package/docs/guide/writes.md +374 -0
  91. package/docs/roadmap.md +116 -0
  92. package/docs/troubleshooting.md +982 -0
  93. package/package.json +61 -5
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Steve Tsala
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,610 @@
1
- # Temporary Holding Version
1
+ # @softistx/s3
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ S3 on **Bun's own client** — no AWS SDK. A bucket is described once: which
4
+ bucket, how a key is built from the things that identify an object, and what
5
+ this application is willing to put there. Writes that break those rules are
6
+ refused **before anything is sent**, and presigned URLs come from the same
7
+ definition.
8
+
9
+ ```ts
10
+ import { bindBucket, defineBucket } from '@softistx/s3';
11
+
12
+ export const avatars = defineBucket({
13
+ bucket: 'avatars',
14
+ key: (p: { userId: string }) => `${p.userId}.png`,
15
+ contentType: ['image/png', 'image/jpeg'],
16
+ maxSize: 2 * 1024 * 1024, // bytes
17
+ });
18
+
19
+ const store = bindBucket(avatars, {
20
+ endpoint: process.env.S3_ENDPOINT,
21
+ accessKeyId: process.env.S3_KEY,
22
+ secretAccessKey: process.env.S3_SECRET,
23
+ });
24
+
25
+ await store.put({ userId: 'u1' }, png, { type: 'image/png' });
26
+ const url = store.presignGet({ userId: 'u1' }, { expiresIn: 300 }); // seconds
27
+ ```
28
+
29
+ `store.client` is Bun's `S3Client`, and `store.file(params)` its `S3File`:
30
+ everything this package does not wrap is still there.
31
+
32
+ > **0.x, on Bun's `S3Client`.** The API is still settling.
33
+
34
+ ## Install
35
+
36
+ `@softistx/s3` is public on npm, with no registry setting and no token. It moved from
37
+ `@nxgt/s3` (npm), which gets no new version: replace the name in your imports
38
+ and `package.json`.
39
+
40
+ ```sh
41
+ bun add @softistx/s3 typescript @types/bun
42
+ ```
43
+
44
+ - **Bun 1.4 or later, and Bun only.** `S3Client` is built into Bun, which is
45
+ why there is no SDK to install — and why this package does not run on Node.
46
+ - `typescript` `^6.0.3 || ^7.0.0`: required peer, the range every `@nxgt` package
47
+ accepts.
48
+ - `@types/bun`: required to typecheck. The shipped declarations name Bun's own
49
+ `S3Client`, `S3File` and `S3Options`, so without Bun's types the first `tsc`
50
+ fails with `Cannot find module 'bun'`.
51
+ - Tested against SeaweedFS 4.47's S3 gateway. Anything S3-compatible that Bun
52
+ can sign for will do; a service that is not AWS wants
53
+ `virtualHostedStyle: false`.
54
+
55
+ ## Testing
56
+
57
+ `@softistx/s3/testing` starts a real S3 API for a suite — SeaweedFS, on free
58
+ ports, with no Docker and no dependency to install:
59
+
60
+ ```ts
61
+ import { afterAll, beforeAll, beforeEach, expect, test } from 'bun:test';
62
+ import { bindBucket, defineBucket } from '@softistx/s3';
63
+ import { startTestS3, type TestS3 } from '@softistx/s3/testing';
64
+
65
+ const avatars = defineBucket({
66
+ bucket: 'avatars',
67
+ key: (params: { userId: string }) => `${params.userId}.png`,
68
+ contentType: 'image/png',
69
+ });
70
+
71
+ let s3: TestS3;
72
+
73
+ beforeAll(async () => {
74
+ s3 = await startTestS3(); // downloads SeaweedFS on a cold cache
75
+ await s3.createBucket('avatars');
76
+ }, 120_000);
77
+
78
+ beforeEach(() => s3.reset('avatars')); // each test starts from nothing
79
+
80
+ afterAll(() => s3.stop());
81
+
82
+ test('stores an avatar', async () => {
83
+ const store = bindBucket(avatars, s3.options); // credentials and endpoint
84
+ const png = new Uint8Array([0x89, 0x50, 0x4e, 0x47]);
85
+ await store.put({ userId: 'u1' }, png, { type: 'image/png' });
86
+ expect(await store.exists({ userId: 'u1' })).toBe(true);
87
+ });
88
+ ```
89
+
90
+ - **The first run downloads SeaweedFS** (once) and checks it
91
+ against a SHA-256 pinned in the package for every platform it ships; a
92
+ download that does not match is refused and never cached. Give `beforeAll`
93
+ a generous timeout (120 s above), or fetch it ahead with
94
+ `await seaweedfsBinary()` from a script your `test` runs first.
95
+ - **`$WEED_BIN`** names a `weed` binary you already have, and nothing is
96
+ downloaded.
97
+ - `startTestS3(options?: TestS3Options)` — `{ binary?, cacheDir? }`: `binary`
98
+ wins over `$WEED_BIN`, which wins over the cache. `cacheDir` defaults to
99
+ `$XDG_CACHE_HOME/nxgt/seaweedfs`, else `~/.cache/nxgt/seaweedfs`, outside
100
+ `node_modules`; the binary lives in `<cacheDir>/<version>/weed`
101
+ (`TEST_SEAWEEDFS_VERSION`). In CI, give `actions/cache` that folder with a key
102
+ on the version (see `docs/guide/testing.md`).
103
+ - It resolves to `{ endpoint, accessKeyId, secretAccessKey, region, options,
104
+ createBucket(name, { timeoutMs }?), reset(bucket, { timeoutMs }?), stop() }`.
105
+ `timeoutMs` makes a stuck server fail with `S3Error` `TIMEOUT` instead of
106
+ hanging the hook. `options` goes straight to
107
+ `bindBucket`. `stop()` kills the server and removes its files; calling it
108
+ twice does nothing. A server nobody stopped does not keep the process alive,
109
+ and is killed when it exits or gets SIGINT or SIGTERM (which then ends the
110
+ process with `128 + n`, unless you have a handler of your own).
111
+
112
+ The [testing guide](docs/guide/testing.md) has the details.
113
+
114
+ ## What it does not do
115
+
116
+ - **No multipart upload.** A body goes in one `put` (a stream is read whole
117
+ only without a `size`; with one it is sent as it is read). Bun's own
118
+ `file.writer()` is there for the rest, through `store.file(params)`.
119
+ - **No bucket administration.** Creating, deleting and configuring a bucket is
120
+ not this package's, and Bun's client has no `createBucket` either.
121
+ - **No copy or move.** `store.client` is where those live when Bun grows them.
122
+ - **It adds no retry and no cache of its own.** A failed request comes back
123
+ with S3's own error. Bun's client does retry — `retry`, three attempts by
124
+ default — and that option is passed through to `bindBucket` like the rest;
125
+ a `put` does not take it.
126
+
127
+ ## API
128
+
129
+ ### `defineBucket({ bucket, key, parseKey, contentType, maxSize })`
130
+
131
+ Describes a bucket; it talks to nothing, so the definition is what a server
132
+ and a worker share. The key is a **function**, so nothing is spelled by hand
133
+ at a call site and a renamed parameter is a compile error.
134
+
135
+ | Field | |
136
+ | --- | --- |
137
+ | `bucket` | the bucket's name on the service |
138
+ | `key` | `(params) => string`, the object's key |
139
+ | `parseKey` | `(key) => params \| undefined`, the inverse of `key`: the params a stored key was built from, `undefined` when it is not this bucket's. Optional |
140
+ | `contentType` | a type, or a list of them, that this bucket accepts. Left out, anything goes |
141
+ | `maxSize` | the biggest body in **bytes**. Left out, anything goes |
142
+
143
+ ```ts
144
+ const items = defineBucket({
145
+ bucket: 'files',
146
+ key: (p: { id: string }) => `items/${p.id}`,
147
+ parseKey: (key) => {
148
+ const id = /^items\/([0-9a-f-]+)$/.exec(key)?.[1];
149
+ return id === undefined ? undefined : { id };
150
+ },
151
+ });
152
+
153
+ const params = bindBucket(items).parseKey(storedKey); // { id } or undefined
154
+ ```
155
+
156
+ If `P` itself includes `undefined`, a miss and a valid key cannot be told
157
+ apart. A throw inside your `parseKey` propagates.
158
+
159
+ ### `bindBucket(definition, options?)`
160
+
161
+ `options` is Bun's own `S3Options` without `bucket` — `endpoint`,
162
+ `accessKeyId`, `secretAccessKey`, `region`, `sessionToken`,
163
+ `virtualHostedStyle`, and also `acl`, `storageClass`, `retry`, `partSize` and
164
+ `queueSize` — plus `timeoutMs` and `publicEndpoint`. It is optional: given none, Bun reads its own `S3_*` / `AWS_*`
165
+ environment variables. Each bound bucket holds an `S3Client` of its own: S3 is
166
+ stateless HTTP, so there is no connection to share and nothing to close.
167
+
168
+ `options` also takes `timeoutMs`, the bucket's default deadline for `put`,
169
+ `stat`, `exists`, `bytes`, `slice`, `text`, `delete` and `list`; a call's own
170
+ `{ timeoutMs }` wins. It is not passed to the `S3Client`. A bad value is a
171
+ `WRONG_OPTION` from `bindBucket` itself.
172
+
173
+ **The deadline covers a whole `put`, the upload included** (a streamed `put`
174
+ with a `size` is the exception: the bucket's default does not apply to it, and
175
+ its own `timeoutMs` is an idle deadline). A default sized for
176
+ reads (5 s above) can cut a large upload, so give a large `put` its own:
177
+ `store.put(params, body, { type, timeoutMs: 120_000 })`.
178
+
179
+ ```ts
180
+ const store = bindBucket(avatars, {
181
+ endpoint: process.env.S3_ENDPOINT,
182
+ accessKeyId: process.env.S3_KEY,
183
+ secretAccessKey: process.env.S3_SECRET,
184
+ timeoutMs: 5000,
185
+ });
186
+ await store.stat({ userId: 'u1' }); // 5 s
187
+ await store.stat({ userId: 'u1' }, { timeoutMs: 500 }); // 500 ms
188
+ ```
189
+
190
+ Behind a proxy, add `publicEndpoint`: `presignGet`, `presignPut` and
191
+ `presignPost` are signed for the origin browsers reach, every other call goes
192
+ to `endpoint`. The proxy must forward the `Host` header it received, or the
193
+ browser gets `SignatureDoesNotMatch`.
194
+
195
+ ```ts
196
+ const store = bindBucket(avatars, {
197
+ endpoint: 'http://minio:9000',
198
+ publicEndpoint: 'https://media.example.com',
199
+ accessKeyId: process.env.S3_KEY,
200
+ secretAccessKey: process.env.S3_SECRET,
201
+ });
202
+ ```
203
+
204
+ | `BoundBucket<P>` | |
205
+ | --- | --- |
206
+ | `client` | the `S3Client` this holds |
207
+ | `keyFor(params)` | the key it would use |
208
+ | `parseKey(key)` | the params a stored key was built from, or `undefined` when it is not this bucket's. Needs `parseKey` on the definition |
209
+ | `file(params)` | Bun's lazy `S3File`: `.stream()`, `.slice()`, `.writer()` |
210
+ | `put(params, body, options?)` | writes it, once the content type and size have accepted it. See `PutOptions` below; `options` also takes `timeoutMs`, and `size` for a stream (next row) |
211
+ | `put(params, stream, { size, … })` | a `ReadableStream` or `AsyncIterable<Uint8Array>` of exactly `size` bytes, sent as it is read and never held whole. `size` is checked against `maxSize` before sending (`TOO_LARGE`) and against the bytes sent (`SIZE_MISMATCH`, nothing stored); a call's own `timeoutMs` is an **idle** deadline (each wait for a chunk or for the service's answer; the bucket's default does not apply), `TIMEOUT` on a stall |
212
+ | `bytes(params, { timeoutMs }?)` | the bytes, or `undefined` when there is no such object |
213
+ | `slice(params, { start, end }, { timeoutMs }?)` | a `ReadableStream` of exactly bytes `[start, end)` — **end exclusive**, like `Blob.slice` — or `undefined` when there is no such object. An `end` past the object is cut at its end; a `start` at or past it, or `start === end`, gives an empty stream. Under a deadline it is a signed `fetch` with an HTTP `Range` header, read into memory inside the deadline; without one it is Bun's `file.slice().stream()` |
214
+ | `open(params, { range?, timeoutMs }?)` | the object as a **stream** with what the service said about it: `{ stream, size, contentLength, contentType, contentEncoding, contentDisposition, cacheControl, eTag, lastModified, contentRange }`, or `undefined` when there is no such object. `range` is `{ start, end? }` (**end exclusive**), or `{ suffix }`; a range that starts at or past the end throws `RANGE_NOT_SATISFIABLE`. The deadline covers the time to the response **headers** only; the body streams with none, and cancelling `stream` aborts the request. See [Streaming a read](docs/guide/reads.md#streaming-a-read-with-open) |
215
+ | `text(params, { timeoutMs }?)` | the body as text, or `undefined` |
216
+ | `exists(params, { timeoutMs }?)` | |
217
+ | `stat(params, { timeoutMs }?)` | Bun's `S3Stats` — `size`, `lastModified`, `etag`, `type` — or `undefined`. Note `etag`, lower case: that is Bun's field. A listing's `StoredObject` says `eTag` |
218
+ | `delete(params, { timeoutMs }?)` | |
219
+ | `list({ prefix, limit, cursor, startAfter, timeoutMs }?)` | one `ObjectPage`; `startAfter: 'items/0042'` lists only the keys after that one |
220
+ | `presignGet(params, { expiresIn, acl, contentDisposition })` | a signed URL that reads it. `contentDisposition` makes the service serve it as that download, a filename included — see below |
221
+ | `presignPut(params, { expiresIn, acl })` | a signed URL that writes it. It takes no `type` — see the Traps |
222
+ | `presignPost(params, { expiresIn, maxSize, minSize, type, acl, contentDisposition })` | `{ url, fields }`, the form a browser posts to upload it. The **service** holds the upload to a size range and a content type — see below |
223
+
224
+ To store an upload without holding it in memory, give the stream its `size`
225
+ (see [Streaming a body with a declared size](docs/guide/writes.md#streaming-a-body-with-a-declared-size)):
226
+
227
+ ```ts
228
+ await store.put(params, request.body, {
229
+ type: request.headers.get('content-type') ?? 'application/octet-stream',
230
+ size: Number(request.headers.get('content-length')),
231
+ timeoutMs: 30_000, // idle: each wait, not the whole upload
232
+ });
233
+ ```
234
+
235
+ ### What a write may say
236
+
237
+ ```ts
238
+ await store.put({ userId: 'u1' }, Bun.file('ada.png')); // the type comes from the file
239
+ await store.put({ userId: 'u1' }, png, {
240
+ type: 'image/png',
241
+ contentDisposition: 'attachment; filename="ada.png"',
242
+ storageClass: 'STANDARD_IA',
243
+ });
244
+ ```
245
+
246
+ | `PutOptions` | |
247
+ | --- | --- |
248
+ | `type` | the body's content type. A `Blob` — `Bun.file` included — is asked for its own when none is given, and *that* is the type the guard checks and the service receives |
249
+ | `contentDisposition` | how a reader should present it: measured, it comes back on a `GET` |
250
+ | `contentEncoding` | how the body is encoded, likewise returned on a read |
251
+ | `acl` | who may read it, where the service implements ACLs |
252
+ | `storageClass` | what it costs to keep, returned as `x-amz-storage-class` |
253
+
254
+ These are Bun's own names, picked out of its `S3Options`, so a Bun release
255
+ that changes one is a compile error here rather than a silent drift. Every
256
+ one of them describes the **object**; a write says nothing about where it
257
+ goes, or how it gets there — see the Traps.
258
+
259
+ Given both here and to `bindBucket`, the one on the write wins: it is the
260
+ last thing handed to the client.
261
+
262
+ ### Download with a filename
263
+
264
+ ```ts
265
+ const url = store.presignGet(
266
+ { userId: 'u1' },
267
+ { expiresIn: 300, contentDisposition: "attachment; filename*=UTF-8''ada.png" },
268
+ );
269
+ // the service answers this URL with that Content-Disposition, whatever
270
+ // the object was stored with
271
+ ```
272
+
273
+ The value is signed as `response-content-disposition`. Printable ASCII only:
274
+ an empty string, a line break or any other control character, a non-ASCII
275
+ character or a non-string is an `S3Error` with `code: 'WRONG_OPTION'`, and
276
+ nothing is signed (a non-ASCII filename is spelled `filename*=UTF-8''…`,
277
+ percent-encoded, per RFC 6266). A `put` is held to the same shape.
278
+
279
+ ### Uploading from a browser
280
+
281
+ `presignPost` signs an S3 **POST policy**: a form the browser posts straight to
282
+ the bucket, whose size and content type the service itself enforces. Use it
283
+ over `presignPut` whenever either matters.
284
+
285
+ ```ts
286
+ // On the server: the bounds default to the bucket's own.
287
+ const form = store.presignPost(
288
+ { userId: 'u1' },
289
+ { type: 'image/png', expiresIn: 300 }, // maxSize: avatars' 2 MiB
290
+ );
291
+ return c.json(form); // { url, fields }
292
+ ```
293
+
294
+ ```ts
295
+ // In the browser: every field, then the file — last.
296
+ const { url, fields } = await (await fetch('/avatar-upload')).json();
297
+ const body = new FormData();
298
+ for (const [name, value] of Object.entries(fields)) body.append(name, value);
299
+ body.append('file', input.files[0]);
300
+ const response = await fetch(url, { method: 'POST', body });
301
+ // 204 when stored; 400 EntityTooLarge over maxSize, 400 EntityTooSmall under
302
+ // minSize; 403 AccessDenied for another type, key or acl, or once expired
303
+ ```
304
+
305
+ | `PresignPostOptions` | |
306
+ | --- | --- |
307
+ | `expiresIn` | seconds: above 0 and at most 604 800, as for the other presigned calls. A day when left out |
308
+ | `maxSize` | the biggest body in bytes. Defaults to the bucket's `maxSize` and cannot be above it; a bucket without one **requires** it |
309
+ | `minSize` | the smallest body in bytes, `0` by default |
310
+ | `type` | the one content type the form carries, or `{ startsWith: 'image/' }`. Defaults to the bucket's `contentType` when that is a single type; a bucket that names several needs one of them. A prefix is only for a bucket that names none, and the page's code then appends a `Content-Type` field before the file — a browser does not add one to a `FormData` by itself |
311
+ | `acl` | fixed by the policy, from the same list as a write's |
312
+ | `contentDisposition` | the `Content-Disposition` the object is stored with, fixed by the policy: a `Content-Disposition` field in `fields`, which the browser posts as given |
313
+
314
+ The policy fixes the key with `eq`, the size with `content-length-range`, and
315
+ the content type with `eq` (or `starts-with`). Measured against SeaweedFS 4.47,
316
+ a body over the range is refused `400 EntityTooLarge`, under it
317
+ `400 EntityTooSmall`, and another type, another key or an expired form
318
+ `403 AccessDenied`. Bun's `S3Client` has no POST presigning, so this package
319
+ signs the policy itself (SigV4, `node:crypto`), for the same endpoint, region
320
+ and access key Bun signs a `presignPut` for. The secret is the one
321
+ `bindBucket` was given, or else `S3_SECRET_ACCESS_KEY`, then
322
+ `AWS_SECRET_ACCESS_KEY` — the variables Bun reads. Bun reads them once, at
323
+ process start: a variable changed afterwards is refused with a `TypeError`
324
+ rather than signing a form the service would reject. Pass `secretAccessKey`
325
+ to `bindBucket` to avoid the question.
326
+
327
+ On a bucket that names no content type, and with no `type`, `fields` carries
328
+ no `Content-Type` and the form above works as written — measured, `204`. The
329
+ object is then stored as `application/octet-stream`, whatever the file part
330
+ says: append `body.append('Content-Type', file.type)` before the file to keep
331
+ its type.
332
+
333
+ ### Listing
334
+
335
+ ```ts
336
+ let cursor: string | null = null;
337
+ do {
338
+ const page = await store.list({ prefix: 'u1/', limit: 100, cursor });
339
+ for (const object of page.items) console.log(object.key, object.size);
340
+ cursor = page.nextCursor;
341
+ } while (cursor !== null);
342
+ ```
343
+
344
+ `ObjectPage` is the same shape as the `CursorPage` of `@softistx/drizzle` and
345
+ `@softistx/mongo`, so a caller pages the same way everywhere: `items`, and a
346
+ `nextCursor` that is `null` on the last page. S3's `continuationToken` is what
347
+ it carries.
348
+
349
+ ### Types
350
+
351
+ | Type | |
352
+ | --- | --- |
353
+ | `BucketDefinition<P>` | what `defineBucket` takes and gives back |
354
+ | `BoundBucket<P>` | what `bindBucket` gives back |
355
+ | `CallOptions` | `{ timeoutMs?: number \| undefined }`, the optional second argument of `stat`, `exists`, `bytes`, `text` and `delete` (the third of `slice`), a part of `put`'s, `list`'s and `open`'s options (`OpenOptions` is `CallOptions` plus `range`) |
356
+ | `StreamOptions`, `StreamBody` | `{ size?: number }`, and `ReadableStream<Uint8Array> \| AsyncIterable<Uint8Array>`: what a streamed `put` takes |
357
+ | `BindOptions` | what `bindBucket` takes: Bun's `S3Options` without `bucket`, plus `timeoutMs` and `publicEndpoint` |
358
+ | `ByteRange` | `{ start, end }`, end exclusive, the range `slice` reads |
359
+ | `OpenOptions`, `OpenRange`, `OpenedObject` | what `open` takes (`{ range?, timeoutMs? }`, a range being `{ start, end? }` or `{ suffix }`) and gives back |
360
+ | `ObjectPage` | `{ items: StoredObject[]; nextCursor: string \| null }` |
361
+ | `StoredObject` | `{ key: string; size: number \| undefined; lastModified: Date \| undefined; eTag: string \| undefined }` — S3 does not promise the last three, so they are optional here |
362
+ | `PresignOptions` | `{ expiresIn?: number \| undefined; acl?: … }` — what `presignPut` takes |
363
+ | `PresignGetOptions` | `PresignOptions` and `contentDisposition?: string \| undefined` |
364
+ | `PresignPostOptions` | `{ expiresIn?; maxSize?; minSize?; type?: string \| { startsWith: string }; acl?; contentDisposition? }` |
365
+ | `PresignedPost` | `{ url: string; fields: Record<string, string> }` — post `fields`, then the file |
366
+ | `ParamsOf<D>` | what a definition's `key` takes, for a caller writing its own helper |
367
+ | `PutBody` | everything Bun's `write` takes |
368
+ | `PutOptions` | what one write may say about the object — see above |
369
+
370
+ `stat` gives back Bun's own `S3Stats`, which this package does not re-export;
371
+ import it from `bun` where you need to name it.
372
+
373
+ ## Errors
374
+
375
+ `S3Error` is this package's error class for **refusals** — a write, a
376
+ presigned URL or a presigned POST whose input the bucket does not accept — and
377
+ **every one of them is thrown before anything is sent**, except `TIMEOUT`,
378
+ `SIZE_MISMATCH`, `SOURCE_FAILED` and `RANGE_NOT_SATISFIABLE`, the codes raised
379
+ after a request went out (the last is the service's answer to a ranged `open`,
380
+ a read that changed nothing). It carries a `code`
381
+ and the object `key` — never the body, never a credential. The package throws
382
+ two other kinds, both below the table: a `TypeError` from `defineBucket` for a
383
+ definition that could never work, from `bindBucket` for a `timeoutMs` default
384
+ that is not whole milliseconds, and from `presignPost` — or a `list` under a
385
+ deadline — when its secret is not Bun's, and from the bound `parseKey` when the
386
+ definition has none; and a plain `Error` from
387
+ `presignPost`, or a `list` under a deadline, when the URL Bun signed cannot be
388
+ read.
389
+
390
+ ```ts
391
+ if (error instanceof S3Error && error.code === 'TOO_LARGE') {
392
+ return c.json({ error: 'That file is too big' }, 413);
393
+ }
394
+ ```
395
+
396
+ | `S3ErrorCode` | |
397
+ | --- | --- |
398
+ | `WRONG_TYPE` | the body's content type is not one this bucket accepts — or the write named none and the bucket names some. From `presignPost` too, and for a `{ startsWith }` on a bucket that names its types |
399
+ | `TOO_LARGE` | the body is bigger than `maxSize` |
400
+ | `UNMEASURABLE` | `maxSize` is set and the body's size cannot be known before sending |
401
+ | `SOURCE_FAILED` | a streamed `put`'s source threw part-way, or gave a chunk that is not bytes; the source's error is the `cause`, and nothing is stored. Raised after the request went out |
402
+ | `SIZE_MISMATCH` | a streamed `put` sent more or fewer bytes than its `size`; the upload is aborted and nothing is stored. Raised after the request went out |
403
+ | `TIMEOUT` | a call with a `timeoutMs` (its own, or the bucket's) got no answer in time: `stat on "avatars": no answer in 5000ms` (a streamed `put`: `put on "avatars": nothing moved in 300ms`). The request is aborted, but it was **sent**: a `delete` may still have happened. On `put`, `stat`, `exists`, `bytes`, `slice`, `open`, `text`, `delete` and `list`: a `put` may have stored the object all the same (a streamed `put`: its own `timeoutMs` only, as an idle deadline) |
404
+ | `RANGE_NOT_SATISFIABLE` | `open` was given a range that starts at or past the end of the object (or any range of an empty one): the service answers 416. `error.objectSize` is the object's size when the service said it, for a `Content-Range: bytes */<size>`; also a `{ suffix }` range when the service ignored `Range` and sent no `Content-Length` (no `objectSize`) |
405
+ | `WRONG_OPTION` | an option's own value is not one the service accepts: a `size` that is not whole bytes or goes with a body that knows its length (or an `AsyncIterable` without one), a `slice` range that is not whole numbers with `0 <= start <= end`, an `open` range that is neither `{ start, end? }` with `0 <= start < end` (not `<=`, unlike `slice`) nor `{ suffix }` with `suffix >= 1`, `acl` or `storageClass` on a write, `acl` or `expiresIn` on a presigned URL, and a `contentDisposition` that is not a non-empty string of printable ASCII on a write, a `presignGet` or a `presignPost`. On `presignPost`, also a `maxSize` or `minSize` that is not a whole number of bytes, a `maxSize` above the bucket's own or missing on a bucket without one, a `minSize` above the `maxSize`, and a `type` that is neither a string nor `{ startsWith }`. A `timeoutMs` that is not a whole number of milliseconds, 1 or more, on any call that takes one (`bindBucket` throws a bare `TypeError` for its default) |
406
+
407
+ `defineBucket` throws a `TypeError` for a definition that could never work: an
408
+ empty `bucket`, a `maxSize` that is not a positive number, an empty list of
409
+ content types. `presignPost` throws three errors that are not `S3Error`s,
410
+ since none is the caller's input: a `TypeError` when this package's secret is
411
+ not the one Bun signs with (`the secret access key this package would sign
412
+ with is not the one Bun signs with`), a `TypeError` when it has none while
413
+ Bun has one (`no secret access key to sign with, while Bun has one`) — both
414
+ after `S3_SECRET_ACCESS_KEY` or `AWS_SECRET_ACCESS_KEY` changed under a
415
+ running process; pass `secretAccessKey` to `bindBucket` — and a plain `Error`
416
+ when the URL Bun signed cannot be read (`the URL Bun signed has no credential
417
+ scope`), which only a Bun that signs differently, or an access key id with a
418
+ stray `%`, produces. S3's own failures come back as they are, from Bun's client —
419
+ and **Bun names those `S3Error` too**, with S3's codes (`NoSuchKey` and the
420
+ rest). Discriminate with `instanceof S3Error` on this package's class, never
421
+ with `error.name`.
422
+
423
+ ### Is the bucket unavailable?
424
+
425
+ `isBucketUnavailable(error)` tells a failure that means the bucket cannot be
426
+ used from here from one that is the caller's. It reads the `code` of an
427
+ `Error` only, never its name or message.
428
+
429
+ - **`true`**: this package's `S3Error` with code `TIMEOUT`; a Bun or Node
430
+ network code (`ConnectionRefused`, `ConnectionClosed`, `DNSResolveFailed`,
431
+ `ECONNREFUSED`, `ECONNRESET`, `ECONNABORTED`, `ETIMEDOUT`, `EHOSTUNREACH`,
432
+ `ENETUNREACH`, `ENOTFOUND`, `EAI_AGAIN`, `EPIPE`); and an S3 service code
433
+ from Bun's client that means the deployment cannot use the bucket
434
+ (`AccessDenied`, `InvalidAccessKeyId`, `SignatureDoesNotMatch`,
435
+ `NoSuchBucket`, `ExpiredToken`, `InternalError`, `ServiceUnavailable`,
436
+ `SlowDown`).
437
+ - **`false`**: this package's refusals of the caller's input (`WRONG_TYPE`,
438
+ `TOO_LARGE`, `UNMEASURABLE`, `WRONG_OPTION`), and the failures of a streamed
439
+ body (`SIZE_MISMATCH`, `SOURCE_FAILED`), which stay the caller's (4xx); per-request codes such as `NoSuchKey`; anything else.
440
+
441
+ ```ts
442
+ import { isBucketUnavailable } from '@softistx/s3';
443
+
444
+ try {
445
+ await avatars.put(key, body);
446
+ } catch (error) {
447
+ if (isBucketUnavailable(error)) return new Response(null, { status: 503 });
448
+ throw error;
449
+ }
450
+ ```
451
+
452
+ ## What does not compile
453
+
454
+ Each is a `@ts-expect-error` case in `test/types/s3.ts`.
455
+
456
+ - An object read, written, deleted or signed for with the wrong key
457
+ parameters, and a `put` given a misspelt option.
458
+ - A `put` or a presigned URL naming a `bucket`, an `endpoint`, a `region` or
459
+ a credential: a write says what the object is, never where it goes.
460
+ - A `put` given `partSize`, `queueSize` or `retry`: those are the client's,
461
+ and a `put` is one PUT.
462
+ - A `presignPut` given a `type`: a presigned PUT constrains no content type,
463
+ so it takes none.
464
+ - A `presignPost` without its params, naming a `bucket`, an `endpoint` or a
465
+ `region`, with a `maxSize` that is not a number, a `type` that is neither a
466
+ string nor `{ startsWith }`, or an `acl` the service does not have.
467
+ - A definition with no `bucket`, no `key`, a `key` that gives something other
468
+ than a string, a `maxSize` that is not a number, or a misspelt option.
469
+ - A presigned URL asked for without the params that identify the object, or
470
+ with an `expiresIn` that is not a number.
471
+ - A `presignPut` given a `contentDisposition`: only `presignGet`, `presignPost`
472
+ and `put` take one.
473
+ - A `timeoutMs` that is a string, a `signal` on `put` or `list`, and any
474
+ option other than `timeoutMs` on `stat`, `exists`, `bytes`, `slice`, `text` or
475
+ `delete`.
476
+ - A listing asked for by page number, or a page read for a `total` — it pages
477
+ by cursor, and S3 does not count.
478
+
479
+ ## Traps
480
+
481
+ - **A call with a deadline does not retry, and signs for 60 s.** Bun's client
482
+ retries a failed request (`retry`, passed through on `bindBucket`); the
483
+ deadline path sends one `fetch` and reports what it got. Its URLs are signed
484
+ for 60 seconds, so a clock skewed by more than that fails only when a
485
+ deadline is set. A client-level `acl` or `storageClass` given to `bindBucket`
486
+ is signed into those HEAD, GET and DELETE URLs too (measured: setting them
487
+ to `undefined` for one presign does not remove them); SeaweedFS ignores
488
+ them, AWS and R2 were not measured.
489
+ - **Without `timeoutMs`, a silent service is waited for 360 s.** Measured on
490
+ Bun 1.4.3, Bun's own S3 calls ignore an `AbortSignal`, and `stat` against a
491
+ socket that accepts and never answers gives up only after 360 s, with Bun's
492
+ own error: **also named `S3Error`, `code: 'Timeout'`**. Check
493
+ `instanceof S3Error` against this package's class, and `code === 'TIMEOUT'`
494
+ — never the name. With a `timeoutMs`, the call is sent with `fetch` on a
495
+ URL Bun signs, which does abort — `put` and `list` too.
496
+ - **A streamed `put`'s `timeoutMs` is idle, so a slow transfer is never cut.**
497
+ It fires only when nothing moved for that long (the connection, the source's
498
+ next chunk, the service taking it, its answer). A client that trickles a byte
499
+ every few seconds holds the upload open indefinitely: bound the total with
500
+ the `size` and your own limit on the source, not with `timeoutMs`.
501
+ - **Under a deadline, a body that is not bytes is read into memory.** A string,
502
+ an `ArrayBuffer`, a typed array or a `Blob` of known size goes to `fetch` as
503
+ it is. A stream, a `Response` or an `S3File` has no length S3 will accept
504
+ (it refuses a chunked PUT), so it is read whole first, inside the deadline:
505
+ its size costs memory. A bucket with a `maxSize` refuses these before
506
+ anything is read (`UNMEASURABLE`). Give a stream its `size` and it is
507
+ streamed instead, never held whole.
508
+ - **A put under a deadline is one PUT.** The bucket's `retry` does not apply
509
+ (the deadline path sends one `fetch` and reports what it got), there is no
510
+ multipart, and S3's 5 GiB ceiling on a single PUT holds.
511
+ - **The guards are `put`'s, not the bucket's.** `contentType` and `maxSize`
512
+ are checked here, in `put`, before the request goes out. They cost nothing
513
+ and they catch the honest mistake, but nothing else on the object goes
514
+ through them: `store.file(params).writer()` and `store.client` are Bun's own
515
+ and write whatever they are given, and **anyone holding a presigned PUT can
516
+ ignore them entirely**. A presigned **POST** is the exception: its policy
517
+ carries the size and the type to the service, which enforces them.
518
+ - **A presigned PUT constrains the key and the deadline, and nothing else.**
519
+ Not the size, not the content type — measured on Bun 1.4: `presign`'s `type`
520
+ only adds `response-content-type`, which is S3's override for what a
521
+ *download* is labelled, and `X-Amz-SignedHeaders` stays `host`, so the
522
+ uploader's `Content-Type` is never signed. A URL signed for a `text/csv`
523
+ bucket stores a zip happily. That is why `presignPut` takes no `type` at
524
+ all: it would read as a guarantee it cannot make. **When the size or the
525
+ type matters, use `presignPost`**, whose policy the service enforces.
526
+ - **`contentDisposition` is a download override on `presignGet`; `presignPut`
527
+ takes none.** On a signed GET it is signed into the URL
528
+ (`response-content-disposition`) and wins over the header the object was
529
+ stored with, for that link only. A signed PUT would carry it as a response
530
+ override, which means nothing to a write, so the type refuses it. To store
531
+ a disposition with the object, give it to `put` or `presignPost`.
532
+ - **A presigned POST's type is compared exactly, not on its essence.** The
533
+ service matches the form's `Content-Type` field against the policy byte for
534
+ byte — measured, `IMAGE/PNG` and `image/png;charset=utf-8` are both
535
+ refused for `image/png`. The field is in `fields`, so post it as given; do
536
+ not let the browser rewrite it. `put`'s own guard is the lenient one.
537
+ - **Post the file last.** S3 documents that a field after the file is
538
+ ignored, so `fields` go first and `file` after them.
539
+ - **A body whose size cannot be known is refused, not streamed.** With
540
+ `maxSize` set, a `Response`, a `Request` or another `S3File` throws
541
+ `UNMEASURABLE`: nothing can check a length it has not read — an `S3File`
542
+ reports its size as `NaN` until the service has been asked. Read it into
543
+ memory first, leave `maxSize` out and let the service refuse it, or — for a
544
+ stream — declare its length: `put(params, stream, { size })`.
545
+ - **A content type is compared on its essence.** `text/csv` accepts
546
+ `text/csv;charset=utf-8` and `TEXT/CSV`, because that is what real bodies
547
+ carry. Measured on bun 1.4.2, `Bun.file` puts a charset on some types and
548
+ not others — `.txt` is `text/plain;charset=utf-8` and `.json` is
549
+ `application/json;charset=utf-8`, while `.csv` is the bare `text/csv` — so
550
+ a definition that named either form would refuse half the files it exists
551
+ for. Parameters and case are ignored; nothing else is.
552
+ - **A write names the object, never where it goes.** `PutOptions` and
553
+ `PresignOptions` carry no `bucket`, `endpoint`, `region` or credential, and
554
+ the run time forwards only the keys they list. The types are not enough on
555
+ their own: a bag that arrives in a request body never met them. Measured,
556
+ spreading it straight through let a `bucket` key store the object in
557
+ **another bucket** and report success, and sign a URL for that bucket —
558
+ a credential key signed one against another endpoint entirely.
559
+ - **A `put` is one PUT, so it takes no upload tuning.** `partSize`,
560
+ `queueSize` and `retry` belong to `bindBucket`, where they are the client's
561
+ own. Measured on bun 1.4.2 against a 12 MiB body: a `put` with `partSize`
562
+ set and one without come back with the **same** ETag, and neither carries
563
+ the `-<parts>` suffix a multipart upload leaves. Use `file(params).writer()`
564
+ for a body that wants parts.
565
+ - **A wrong `acl` or `storageClass` is `WRONG_OPTION`, not Bun's `TypeError`.**
566
+ Both values are checked here, with the content type and the size — and an
567
+ `acl` on a presigned URL against the same list — so one `catch` takes every
568
+ refusal:
569
+ `if (error instanceof S3Error) return c.json({ error: error.code }, 400);`.
570
+ `contentDisposition` must be a non-empty string of printable ASCII, else
571
+ `WRONG_OPTION`; `contentEncoding` is a free string and is never refused.
572
+ `presignGet` and `presignPut` forward `acl` too, and go through the
573
+ same allowlist. The accepted values are listed in
574
+ [docs/guide/writes.md](docs/guide/writes.md).
575
+ - **A string body is measured in bytes, not in characters**, and `maxSize` is
576
+ inclusive: 1024 passes, 1025 does not.
577
+ - **`expiresIn` is seconds, and Bun's default is a day.** Always pass one. An
578
+ `S3Error` with `code: 'WRONG_OPTION'` refuses it above 604 800 seconds —
579
+ seven days, S3's own cap on a presigned URL — at or below zero, and for
580
+ anything that is not a finite number, so a signed URL this package hands
581
+ back is one the service will accept.
582
+ - **A key is built, never guessed.** `keyFor` is there so a caller that needs
583
+ the string gets *the* string; building one by hand somewhere else is how a
584
+ bucket ends up with two spellings of the same object. The way back from a
585
+ stored key is `parseKey`, never a regex at the call site.
586
+ - **`delete` does not say whether anything was there.** S3 answers the same
587
+ either way, and this package does not pretend otherwise. Call `exists`
588
+ first when it matters.
589
+ - **A listing is eventually consistent on some services**, and `limit` is a
590
+ maximum, not a promise: a page may come back shorter with a `nextCursor`
591
+ still set. Page until `nextCursor` is `null`, never until a page is short.
592
+ - **`undefined` means "no such object", and nothing else.** `bytes`, `text`
593
+ and `stat` read in one round trip and turn S3's own `NoSuchKey` into
594
+ `undefined`; every other failure — a wrong secret, a refused request, a
595
+ service that is down — comes back as the error it is.
596
+
597
+ ## Documentation
598
+
599
+ - [docs/README.md](docs/README.md) — the guide index: buckets, reading,
600
+ writing and presigned URLs, each with its options and a worked example.
601
+ - [docs/guide/testing.md](docs/guide/testing.md) — a real S3 API for your
602
+ suite: `@softistx/s3/testing`.
603
+ - [docs/troubleshooting.md](docs/troubleshooting.md) — every error this
604
+ package can raise, by the message you will see.
605
+ - [docs/roadmap.md](docs/roadmap.md) — what is coming, and what has been
606
+ ruled out.
607
+
608
+ ## License
609
+
610
+ MIT