@bymax-one/nest-storage 1.1.17 → 1.1.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -13,6 +13,98 @@ note on each entry is the compatibility contract — read it, not the number.
13
13
 
14
14
  ## [Unreleased]
15
15
 
16
+ ## [1.1.18] - 2026-11-18
17
+
18
+ ### Fixed
19
+
20
+ - **A per-call value of the wrong kind no longer reaches the provider call or a log line.** A per-call `bucket` that
21
+ is not a string (a `Symbol`, a function, an array, an object, a number) was repeated in `details.bucket` of the
22
+ error it caused, on every method that takes a bucket, and an `abortSignal` that was not an `AbortSignal` (a string,
23
+ a `Symbol`, a `BigInt`) was handed to the SDK, which named the value in its own error message, and that message is
24
+ logged as `Provider call failed`. Both are now refused before any request with `STORAGE_VALIDATION_FAILED` (400)
25
+ naming `bucket` or `abortSignal`, and nothing of the value. `getMultipartUploadUrls` no longer puts a `parts` that
26
+ is not a number in `details.provided`. A body that has `pipe`, `on` and `once` but no `pause` or `resume` is refused
27
+ with `STORAGE_VALIDATION_FAILED` naming `body`, where it used to be waited on until `STORAGE_TIMEOUT`.
28
+
29
+ **Apply to a derived backend:** a call that passed a per-call `bucket` that is not a string, or an `abortSignal` that
30
+ is not an `AbortSignal`, now fails with `STORAGE_VALIDATION_FAILED` (`details.field` is `bucket` or `abortSignal`)
31
+ where it used to reach the provider (`exists` answers `false` and logs a warning, as for any failure that is not a
32
+ missing object). `details.provided` of `STORAGE_INVALID_PART_COUNT` is present only when `parts` is a finite number. A
33
+ stream-like body without `pause` and `resume` is refused with `STORAGE_VALIDATION_FAILED`.
34
+
35
+ - **A configuration of the wrong kind is refused at boot, and a `null` that means "off" is refused.** `keyPrefix` that is
36
+ an array or an object was accepted and failed later as a raw `TypeError`; `validation.mimeWhitelist` that is a string
37
+ was accepted; `validation.customValidators` that is not an array was accepted; and a `region` with a space, a slash
38
+ or a newline in it was sent on to the SDK, which repeats it in its error messages. `forRoot` now refuses each with
39
+ `STORAGE_INVALID_CONFIG` naming the option and repeating nothing of the value: `keyPrefix` must be a string,
40
+ `mimeWhitelist` an array of strings, `customValidators` an array, and `region` 1 to 63 letters, digits, `.`, `_` or
41
+ `-` starting with a letter or digit. `validation.maxSizeBytes: null`, `validation.mimeWhitelist: null` and
42
+ `validation.customValidators: null` are refused as well: leaving each out means no size limit, every type allowed or
43
+ no custom validator, so a `null` from a config lookup of a missing key must not switch the protection off (1.1.17
44
+ read `maxSizeBytes: null` as "no limit").
45
+
46
+ **Apply to a derived backend:** a configuration that booted and is now refused: a `keyPrefix` that is not a string, a
47
+ `validation.mimeWhitelist` or `customValidators` that is not an array (and a `mimeWhitelist` with a non-string
48
+ entry), a `region` outside the shape above, and a `null` for `validation.maxSizeBytes`, `validation.mimeWhitelist` or
49
+ `validation.customValidators`. Omit the option for "none": `null` no longer means it. A `null` for any other option
50
+ inside a group is still the default.
51
+
52
+ **`scanner: null` is refused; omit the key for no scanner.** 1.1.17 read a `scanner` of `null` as "no scanner", so a
53
+ config lookup that returned `null` for a missing key booted with scanning off. `forRoot` now fails with
54
+ `STORAGE_INVALID_CONFIG` ("scanner must not be null; omit it for no scanner"); a `scanner` that is `false`, `0`,
55
+ `''` or `[]` was already refused.
56
+
57
+ **Apply to a derived backend:** a `scanner` of `null` now fails `forRoot` and `forRootAsync` with
58
+ `STORAGE_INVALID_CONFIG`; omit the key to run no scanner.
59
+
60
+ - **A value that throws when it is read no longer hangs a source read.** The check that tells an `Error` from any other
61
+ value in the idle-timeout wrapper read its `name` and `message` outside a guard: a rejection value whose property
62
+ getter throws left the wrapped read pending for good, with its timer already cleared. It is now treated as not
63
+ being an error, and the read ends with one.
64
+
65
+ **Apply to a derived backend:** nothing to change; a read that used to stay pending in that case now ends with an error.
66
+
67
+ - **Every option is read once.** Validation and resolution each read the options by property name, so a getter that
68
+ returned a valid value for the check and a hostile one for the use (`scanner.mode` that answers `'pre-upload'`
69
+ first and `'preupload'` after, a size limit that answers a number and then `NaN`) passed the check and was used as
70
+ the hostile value. `forRoot` and `forRootAsync` now copy each known option, and each key of the option groups, into a
71
+ plain object once; the copy is what is validated and what is resolved. The arrays of `validation` are copied once
72
+ as well.
73
+
74
+ **Apply to a derived backend:** nothing to change for a plain options object. An options object whose property
75
+ getters answer differently from one read to the next now gets the first answer everywhere; a key that is not an
76
+ option is not read at all.
77
+
78
+ - **A cut of scanner text never leaves half of a surrogate pair, and a scan that times out is logged.** The engine and
79
+ threat names of a scan result (in the response body and the log), the unrecognised status, the scanner's `details`
80
+ and the message of a scanner that throws were cut at a fixed length, and a cut between the two halves of an
81
+ emoji left a lone surrogate in a JSON body or a log line. The cut now drops the whole pair. A scan that outlasts
82
+ `scanner.timeoutMs` logs one `Scan timed out` warning with the key and the limit; until now only the typed
83
+ `STORAGE_TIMEOUT` carried it.
84
+
85
+ **Apply to a derived backend:** an engine or threat name cut at its limit is one character shorter when an
86
+ emoji sits at the cut; alert rules that matched the absence of a timeout line can match `Scan timed out`.
87
+
88
+ ### Changed
89
+
90
+ - **Behaviour of 1.1.17 that its notes did not name.** Each is a change from 1.1.16; the `Apply` line says what to do.
91
+ - **A WHATWG `ReadableStream` body is refused (breaking).** 1.1.16 accepted it and stored it; 1.1.17 and later fail
92
+ with `STORAGE_VALIDATION_FAILED` (400, `details.field: 'body'`). **Apply:** convert it with
93
+ `Readable.fromWeb(stream)` before the call.
94
+ - **A `scanner` that is not an object is refused at boot.** `false`, `0`, `''` and `[]` booted in 1.1.16 and scanned
95
+ nothing; they fail `forRoot` with `STORAGE_INVALID_CONFIG` (`null` is refused too, see above). **Apply:**
96
+ omit `scanner` for no scanner.
97
+ - **`scanner.impl` must be an object with a `scan` function.** A function with a static `scan` (a class passed
98
+ where an instance belongs) is refused; 1.1.16 accepted it and called the static method. **Apply:** pass an
99
+ instance, or an object that holds the `scan` function.
100
+ - **Keys that are not options are dropped from the resolved `signedUrls`, `multipart`, `validation` and `scanner`.**
101
+ 1.1.16 copied them through. **Apply:** keep such values outside the options.
102
+ - **`validation: null` resolves to an empty `validation`**; 1.1.16 kept the `null`. **Apply:** none; read
103
+ `resolved.validation` as an object, never as `null`.
104
+ - **A group that is a class instance is honoured.** A value served from a prototype getter (a config object built
105
+ as a class) is kept; 1.1.16 copied own properties only and dropped it silently.
106
+ - **`validation.maxSizeBytes: null` meant "no limit" in 1.1.17**; it is refused from this release (see above).
107
+
16
108
  ## [1.1.17] - 2026-11-17
17
109
 
18
110
  ### Fixed
@@ -1015,4 +1107,5 @@ have regressed from. They are kept because the reasoning is worth having.
1015
1107
  [1.1.15]: https://github.com/bymaxone/nest-storage/compare/v1.1.14...v1.1.15
1016
1108
  [1.1.16]: https://github.com/bymaxone/nest-storage/compare/v1.1.15...v1.1.16
1017
1109
  [1.1.17]: https://github.com/bymaxone/nest-storage/compare/v1.1.16...v1.1.17
1018
- [Unreleased]: https://github.com/bymaxone/nest-storage/compare/v1.1.17...HEAD
1110
+ [1.1.18]: https://github.com/bymaxone/nest-storage/compare/v1.1.17...v1.1.18
1111
+ [Unreleased]: https://github.com/bymaxone/nest-storage/compare/v1.1.18...HEAD
package/README.md CHANGED
@@ -209,13 +209,13 @@ Options accepted by `forRoot` and `forRootAsync`:
209
209
  | Option | Type | Default | Notes |
210
210
  | ------------------------------ | ------------------------------------------------- | ----------------- | ---------------------------------------------- |
211
211
  | `endpoint` | `string` | — | Required. S3-compatible endpoint URL; it must not carry credentials (`https://user:pass@host` is refused), pass them in `credentials` |
212
- | `region` | `string` | — | Required. Provider region or `'auto'` (R2) |
213
- | `bucket` | `string` | — | Default bucket (can be overridden per-call) |
212
+ | `region` | `string` | — | Required. Provider region or `'auto'` (R2): 1 to 63 letters, digits, `.`, `_` or `-`, starting with a letter or digit |
213
+ | `bucket` | `string` | — | Default bucket (can be overridden per-call by a string; any other per-call kind fails with `STORAGE_VALIDATION_FAILED`) |
214
214
  | `credentials` | `{ accessKeyId, secretAccessKey, sessionToken? }` | — | Load from env / Secrets Manager |
215
215
  | `forcePathStyle` | `boolean` | `false` | Set to `true` for MinIO and self-hosted |
216
216
  | `publicBaseUrl` | `string` | — | Base URL for public `getPublicUrl()` results; it must not carry credentials (a user or password is refused) |
217
217
  | `cdnBaseUrl` | `string` | — | CDN edge URL (preferred over `publicBaseUrl`); it must not carry credentials either |
218
- | `keyPrefix` | `string` | — | Prepended to every key before it reaches the provider; fixed per module instance |
218
+ | `keyPrefix` | `string` | — | Prepended to every key before it reaches the provider; fixed per module instance. A value that is not a string fails `forRoot`; `null` is read as unset |
219
219
  | `maxAttempts` | `number` | `3` | SDK v3 retry count; an integer of at least `1` |
220
220
  | `serverSideEncryption` | `'AES256' \| 'aws:kms'` | — | Global SSE policy; `aws:kms` needs `kmsKeyId`. `'NONE'` is accepted per upload only |
221
221
  | `requestChecksumCalculation` | `'WHEN_SUPPORTED' \| 'WHEN_REQUIRED'` | SDK default | Set to `'WHEN_REQUIRED'` for non-AWS providers |
@@ -232,10 +232,10 @@ Options accepted by `forRoot` and `forRootAsync`:
232
232
  | `multipart.thresholdBytes` | `number` | `5 MiB` | Switch to multipart at or above this size |
233
233
  | `multipart.partSizeBytes` | `number` | `5 MiB` | Part size (S3 minimum: 5 MiB) |
234
234
  | `multipart.queueSize` | `number` | `4` | Concurrent parts |
235
- | `validation.mimeWhitelist` | `string[]` | — | No MIME check when absent. Wildcards: `'image/*'`. A value that lists several types never matches |
236
- | `validation.maxSizeBytes` | `number` | — | Maximum upload size in bytes; counted as a stream is read, so it holds with or without `size` |
235
+ | `validation.mimeWhitelist` | `string[]` | — | No MIME check when absent. Wildcards: `'image/*'`. A value that lists several types never matches. An array of strings: any other kind fails `forRoot`, and `null` is refused (omit it to allow every type) |
236
+ | `validation.maxSizeBytes` | `number` | — | Maximum upload size in bytes; counted as a stream is read, so it holds with or without `size`. `null` is refused: omit it for no limit |
237
237
 
238
- **Numeric options are whole numbers, checked at boot.** `validation.maxSizeBytes`, the `signedUrls` TTLs and `multipart.thresholdBytes` take a whole number of at least `1`; `multipart.partSizeBytes` takes one from 5 MiB (the S3 minimum) to 5 GiB (the S3 maximum) and `multipart.queueSize` one from `1` to `1000`. `NaN`, `Infinity`, a fraction, a string or a value out of range fails `forRoot` with `STORAGE_INVALID_CONFIG` naming the option: a comparison alone lets `NaN` through, and `NaN` on a size limit would turn the limit off. The same holds per call: a `ttlSeconds` that is not a whole number above `0` fails with `STORAGE_SIGNED_URL_TTL_INVALID`, and a declared upload `size` or a list `maxKeys` that is not a whole number (at least `0`, and at least `1`) fails with `STORAGE_VALIDATION_FAILED` naming the field, before any request is made. A key set to `undefined` or `null` inside `signedUrls`, `multipart`, `validation` or `scanner` means the default. The per-call values are refused on `null`, and the error for a TTL echoes no value but a finite number.
238
+ **Numeric options are whole numbers, checked at boot.** `validation.maxSizeBytes`, the `signedUrls` TTLs and `multipart.thresholdBytes` take a whole number of at least `1`; `multipart.partSizeBytes` takes one from 5 MiB (the S3 minimum) to 5 GiB (the S3 maximum) and `multipart.queueSize` one from `1` to `1000`. `NaN`, `Infinity`, a fraction, a string or a value out of range fails `forRoot` with `STORAGE_INVALID_CONFIG` naming the option: a comparison alone lets `NaN` through, and `NaN` on a size limit would turn the limit off. The same holds per call: a `ttlSeconds` that is not a whole number above `0` fails with `STORAGE_SIGNED_URL_TTL_INVALID`, and a declared upload `size` or a list `maxKeys` that is not a whole number (at least `0`, and at least `1`) fails with `STORAGE_VALIDATION_FAILED` naming the field, before any request is made. A key set to `undefined` or `null` inside `signedUrls`, `multipart`, `validation` or `scanner` means the default, except `scanner.impl` and the `validation` options named below, which refuse `null`. The per-call values are refused on `null`, and the error for a TTL echoes no value but a finite number. Where leaving an option out means a limit or a protection is off, `null` is refused for it as well, so a config lookup that returns `null` for a missing key cannot switch it off: `validation.maxSizeBytes`, `validation.mimeWhitelist` and `validation.customValidators` (the last must be an array).
239
239
 
240
240
  > **Do not use `maxRetries` or `signatureVersion`** — these are AWS SDK v2 options that do not exist in v3. The v3 SDK is SigV4-only. Use `maxAttempts` (default `3`) for retry configuration.
241
241
 
@@ -424,7 +424,9 @@ A 304 is therefore thrown, not returned: catch `StorageException` and branch on
424
424
  `abortSignal`. When it aborts, the call rejects `STORAGE_REQUEST_ABORTED` (HTTP 499) with
425
425
  `details.reason` set to the **name** of the signal's reason (`AbortError`, `TimeoutError`), never its
426
426
  message, so a host can tell its own timeout from a client disconnect. `exists` rejects too, rather
427
- than answering `false`.
427
+ than answering `false`. A value that is not an `AbortSignal` fails with `STORAGE_VALIDATION_FAILED` naming
428
+ `abortSignal` and nothing of the value (`exists` answers `false` and logs a warning for it, as it does for
429
+ any failure that is not a missing object).
428
430
 
429
431
  ```typescript
430
432
  const controller = new AbortController()
@@ -602,14 +604,14 @@ stream longer than the limit is refused with `STORAGE_VALIDATION_FAILED` as soon
602
604
  with no `maxSizeBytes` it is refused with a reason that says to set it or use `post-upload`.
603
605
  `post-upload` hands the scanner the key only, no body.
604
606
 
605
- **The scanner configuration is checked at boot.** `scanner.impl` must be an object with a `scan` function, `scanner.mode` must be `'pre-upload'` or `'post-upload'` (unset or `null` is `'pre-upload'`) and `scanner.rejectOnUnknown` must be a boolean (unset or `null` is the default); anything else fails `forRoot` with `STORAGE_INVALID_CONFIG`, because a missing implementation or a mode that is neither value would scan nothing. A `scanner` of `null` is no scanner.
607
+ **The scanner configuration is checked at boot.** `scanner.impl` must be an object with a `scan` function, `scanner.mode` must be `'pre-upload'` or `'post-upload'` (unset or `null` is `'pre-upload'`) and `scanner.rejectOnUnknown` must be a boolean (unset or `null` is the default); anything else fails `forRoot` with `STORAGE_INVALID_CONFIG`, because a missing implementation or a mode that is neither value would scan nothing. Omit `scanner` for no scanner: a `scanner` of `null` is refused, so a config lookup that returns `null` for a missing key cannot switch scanning off.
606
608
 
607
609
  **A scan has a deadline.** `scanner.timeoutMs` (a whole number of milliseconds from `1` to `2147483647`, default `60000`; there is no setting that waits without limit) bounds a scan: past it the upload is refused with `STORAGE_TIMEOUT` (503, `details.phase: 'scan'`), and in `post-upload` mode the stored object is removed as for any other rejection. The scanner is handed an `AbortSignal` (`signal` on its input) that aborts at the deadline. **A scanner that ignores the signal keeps running after the timeout**, so repeated timeouts pile up scanner work: honour the signal, or give the scanner a limit of its own. A listener the scanner adds to the signal and that throws is reported by Node as an uncaught exception, as for any event target: it cannot be caught around the abort.
608
610
 
609
611
  **What counts as a verdict.** Only the exact strings `'clean'`, `'infected'` and `'unknown'` are results. Anything else (no result, `null`, `'CLEAN'`, `' clean'`, an object, a made-up status) is rejected as `STORAGE_SCAN_INCONCLUSIVE` with `details.reason: 'unrecognised scanner status'`, whatever `rejectOnUnknown` says: an object the scanner did not call clean is not stored.
610
612
 
611
613
  **What a client is told.** `STORAGE_SCAN_INFECTED` carries `details.engine` and `details.threat`, and
612
- `STORAGE_SCAN_INCONCLUSIVE` carries `details.engine`; each name is cut to 200 characters, in the body and in the log, and left out when the scanner gave something that is not a string. A scanner that throws is answered with a 500, and the library logs a `Scanner failed` warning with the message (cut at 300 characters) so there is a trace of why. The free-form `details` your scanner returns is the
614
+ `STORAGE_SCAN_INCONCLUSIVE` carries `details.engine`; each name is cut, in the body and in the log, and left out when the scanner gave something that is not a string. A scanner that throws is answered with a 500, and the library logs a `Scanner failed` warning with the message (cut) so there is a trace of why; a scan that outlasts `scanner.timeoutMs` is logged as `Scan timed out` with the key and the limit. A cut never leaves half of a surrogate pair, so an emoji at the cut is dropped whole. The free-form `details` your scanner returns is the
613
615
  scanner's own text, so it is written to the warning log (escaped and truncated) and never to the
614
616
  body of the error.
615
617
 
@@ -777,14 +779,14 @@ All errors are thrown as `StorageException extends HttpException`. The response
777
779
  | `STORAGE_CONTENT_TYPE_REQUIRED` | 400 | `upload()` called without `contentType` |
778
780
  | `STORAGE_MIME_NOT_ALLOWED` | 415 | `contentType` outside `mimeWhitelist`, at upload or at presign |
779
781
  | `STORAGE_SIZE_EXCEEDED` | 413 | `size > maxSizeBytes` |
780
- | `STORAGE_VALIDATION_FAILED` | 400 | `IUploadValidator` rejected the file, or a header-bound value is not a header value (`details.field`, `details.reason`) |
782
+ | `STORAGE_VALIDATION_FAILED` | 400 | `IUploadValidator` rejected the file, or a header-bound value is not a header value, or a per-call `bucket` or `abortSignal` is of the wrong kind (`details.field`, `details.reason`; the value is never repeated) |
781
783
  | `STORAGE_SCAN_INFECTED` | 422 | Scanner returned `'infected'` (`details.threat`); `details.cleanup: 'failed'` means the object is still stored |
782
784
  | `STORAGE_SCAN_INCONCLUSIVE` | 422 | Scanner returned `'unknown'` and `rejectOnUnknown: true`, or a result that is not a recognised status |
783
785
  | `STORAGE_OBJECT_NOT_FOUND` | 404 | `head()`, `download()`, or `copy()` on a nonexistent key |
784
786
  | `STORAGE_PROVIDER_ERROR` | 502 | The provider rejected the request (`AccessControlListNotSupported`, an `AccessDenied` on an object, any other rejection). **503** when it could not be reached (connection refused or reset, DNS failure) or answered with a server error (`SlowDown`, 500, 502, 504; not 501), which is worth retrying; **500** when it refused the credentials (`InvalidAccessKeyId`, `SignatureDoesNotMatch`), a deployment fault that a retry does not fix (a `HEAD` answer carries no body and so no code: a refused `head()` stays **502** with reason `rejected`, and the credentials case is not told apart there). `details` carries `awsCode`, `httpStatus`, `requestId` and a fixed `reason` (`unreachable`, `provider-error`, `credentials-refused` or `rejected`; never the text of the driver or of the provider) plus the operation context (`op`, `bucket`, and `key` or `prefix`) |
785
787
  | `STORAGE_SIGNED_URL_TTL_INVALID` | 400 | Per-request `ttlSeconds` ≤ 0 |
786
788
  | `STORAGE_PART_TOO_SMALL` | 400 | Never thrown: a `multipart.partSizeBytes` below 5 MiB fails at init as `STORAGE_INVALID_CONFIG` |
787
- | `STORAGE_INVALID_PART_COUNT` | 400 | `getMultipartUploadUrls()` with `parts` not an integer from 1 to 10 000 (`details.provided`, `details.reason`) |
789
+ | `STORAGE_INVALID_PART_COUNT` | 400 | `getMultipartUploadUrls()` with `parts` not an integer from 1 to 10 000 (`details.reason`; `details.provided` only when `parts` is a finite number) |
788
790
  | `STORAGE_BUCKET_UNDEFINED` | 400 | Operation without a bucket and no default in config |
789
791
  | `STORAGE_MULTIPART_ABORTED` | 500 | A multipart upload failed (**503** when the cause is an outage, as for `STORAGE_PROVIDER_ERROR`). `details.abort` is `'completed'` when the library aborted it, `'failed'` when the abort itself failed (logged as a warning, with what it threw): that upload then stays open on the provider until a lifecycle rule removes it |
790
792
  | `STORAGE_INVALID_CONFIG` | 500 | `BymaxStorageModuleOptions` validation failed at initialization |
@@ -178,6 +178,7 @@ function assertMetadata(metadata) {
178
178
  var MIN_PART_SIZE_BYTES = 5 * 1024 * 1024;
179
179
  var MAX_PART_SIZE_BYTES = 5 * 1024 * 1024 * 1024;
180
180
  var MAX_QUEUE_SIZE = 1e3;
181
+ var REGION_SHAPE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$/;
181
182
  function invalid(reason) {
182
183
  return new StorageException(STORAGE_ERROR_CODES.STORAGE_INVALID_CONFIG, common.HttpStatus.INTERNAL_SERVER_ERROR, {
183
184
  reason
@@ -228,7 +229,8 @@ function assertBoundedInteger(section, group, key, range) {
228
229
  }
229
230
  }
230
231
  function assertScanner(scanner) {
231
- if (scanner === void 0 || scanner === null) return;
232
+ if (scanner === void 0) return;
233
+ if (scanner === null) throw invalid("scanner must not be null; omit it for no scanner");
232
234
  if (!isObject(scanner)) throw invalid("scanner must be an object");
233
235
  const impl = scanner.impl;
234
236
  if (!isObject(impl) || typeof impl.scan !== "function") {
@@ -242,6 +244,25 @@ function assertScanner(scanner) {
242
244
  throw invalid("scanner.rejectOnUnknown must be a boolean");
243
245
  }
244
246
  }
247
+ function assertValidationKinds(validation) {
248
+ if (!isObject(validation)) return;
249
+ const { maxSizeBytes, mimeWhitelist, customValidators } = validation;
250
+ if (maxSizeBytes === null) {
251
+ throw invalid("validation.maxSizeBytes must not be null; omit it for no size limit");
252
+ }
253
+ if (mimeWhitelist === null) {
254
+ throw invalid("validation.mimeWhitelist must not be null; omit it to allow every type");
255
+ }
256
+ if (mimeWhitelist !== void 0 && (!Array.isArray(mimeWhitelist) || !Array.from(mimeWhitelist).every((entry) => typeof entry === "string"))) {
257
+ throw invalid("validation.mimeWhitelist must be an array of strings");
258
+ }
259
+ if (customValidators === null) {
260
+ throw invalid("validation.customValidators must not be null; omit it to run no custom validator");
261
+ }
262
+ if (customValidators !== void 0 && !Array.isArray(customValidators)) {
263
+ throw invalid("validation.customValidators must be an array");
264
+ }
265
+ }
245
266
  function assertNumericSections(options) {
246
267
  const MAX = Number.MAX_SAFE_INTEGER;
247
268
  assertBoundedInteger(options.validation, "validation", "maxSizeBytes", { min: 1, max: MAX });
@@ -259,6 +280,7 @@ function assertNumericSections(options) {
259
280
  }
260
281
  function assertLimitsAndEncryption(options) {
261
282
  assertNumericSections(options);
283
+ assertValidationKinds(options.validation);
262
284
  assertScanner(options.scanner);
263
285
  const maxAttempts = options.maxAttempts;
264
286
  if (maxAttempts !== void 0 && (typeof maxAttempts !== "number" || !Number.isInteger(maxAttempts) || maxAttempts < 1 || maxAttempts > Number.MAX_SAFE_INTEGER)) {
@@ -292,9 +314,17 @@ function validateOptions(options) {
292
314
  if (!isNonEmptyString(options.region)) {
293
315
  throw invalid("options.region must be a non-empty string");
294
316
  }
317
+ if (!REGION_SHAPE.test(options.region)) {
318
+ throw invalid(
319
+ "options.region must be 1 to 63 letters, digits, '.', '_' or '-', starting with a letter or digit"
320
+ );
321
+ }
295
322
  if (!isNonEmptyString(options.bucket)) {
296
323
  throw invalid("options.bucket must be a non-empty string");
297
324
  }
325
+ if (options.keyPrefix !== void 0 && options.keyPrefix !== null && typeof options.keyPrefix !== "string") {
326
+ throw invalid("options.keyPrefix must be a string");
327
+ }
298
328
  if (!isObject(options.credentials)) {
299
329
  throw invalid("options.credentials is required");
300
330
  }
@@ -341,6 +371,41 @@ var DEFAULT_MULTIPART = {
341
371
  var DEFAULT_IDEMPOTENCY_CACHE_MAX_ENTRIES = 1e3;
342
372
  var DEFAULT_IDEMPOTENCY_CACHE_TTL_MS = 864e5;
343
373
 
374
+ // src/server/config/option-keys.ts
375
+ function keysOf() {
376
+ return (keys) => keys;
377
+ }
378
+ var OPTION_KEYS = keysOf()([
379
+ "endpoint",
380
+ "region",
381
+ "bucket",
382
+ "credentials",
383
+ "forcePathStyle",
384
+ "publicBaseUrl",
385
+ "cdnBaseUrl",
386
+ "defaultPublicRead",
387
+ "keyPrefix",
388
+ "defaultCacheControl",
389
+ "defaultContentDisposition",
390
+ "signedUrls",
391
+ "multipart",
392
+ "validation",
393
+ "scanner",
394
+ "serverSideEncryption",
395
+ "kmsKeyId",
396
+ "requestChecksumCalculation",
397
+ "responseChecksumValidation",
398
+ "maxAttempts",
399
+ "requestTimeoutMs",
400
+ "uploadIdleTimeoutMs",
401
+ "bodyIdleTimeoutMs"
402
+ ]);
403
+ var CREDENTIAL_KEYS = keysOf()(["accessKeyId", "secretAccessKey", "sessionToken"]);
404
+ var SIGNED_URL_KEYS = keysOf()(["defaultGetTtlSeconds", "defaultPutTtlSeconds", "maxTtlSeconds"]);
405
+ var MULTIPART_KEYS = keysOf()(["thresholdBytes", "partSizeBytes", "queueSize"]);
406
+ var VALIDATION_KEYS = keysOf()(["mimeWhitelist", "maxSizeBytes", "customValidators"]);
407
+ var SCANNER_KEYS = keysOf()(["impl", "mode", "rejectOnUnknown", "timeoutMs"]);
408
+
344
409
  // src/server/config/apply-defaults.ts
345
410
  function definedOnly(group, keys) {
346
411
  const picked = {};
@@ -350,10 +415,6 @@ function definedOnly(group, keys) {
350
415
  }
351
416
  return picked;
352
417
  }
353
- var SIGNED_URL_KEYS = ["defaultGetTtlSeconds", "defaultPutTtlSeconds", "maxTtlSeconds"];
354
- var MULTIPART_KEYS = ["thresholdBytes", "partSizeBytes", "queueSize"];
355
- var VALIDATION_KEYS = ["mimeWhitelist", "maxSizeBytes", "customValidators"];
356
- var SCANNER_KEYS = ["impl", "mode", "rejectOnUnknown", "timeoutMs"];
357
418
  function resolveSignedUrls(configured) {
358
419
  const merged = { ...DEFAULT_SIGNED_URLS, ...definedOnly(configured, SIGNED_URL_KEYS) };
359
420
  return { ...merged, maxTtlSeconds: Math.min(merged.maxTtlSeconds, MAX_SIGNED_URL_TTL_SECONDS) };
@@ -384,7 +445,7 @@ function applyDefaults(options) {
384
445
  signedUrls: resolveSignedUrls(options.signedUrls),
385
446
  multipart: { ...DEFAULT_MULTIPART, ...definedOnly(options.multipart, MULTIPART_KEYS) },
386
447
  ...options.validation !== void 0 ? { validation: definedOnly(options.validation, VALIDATION_KEYS) } : {},
387
- // `null` is no scanner, as `undefined` is: a group is an object or it is not configured.
448
+ // A group is an object or it is not configured. `forRoot` refuses a `null` scanner before this runs; if one reaches here it adds no scanner.
388
449
  ...options.scanner ? { scanner: definedOnly(options.scanner, SCANNER_KEYS) } : {},
389
450
  ...options.serverSideEncryption !== void 0 ? { serverSideEncryption: options.serverSideEncryption } : {},
390
451
  ...options.kmsKeyId !== void 0 ? { kmsKeyId: options.kmsKeyId } : {},
@@ -400,6 +461,51 @@ function applyDefaults(options) {
400
461
  return resolved;
401
462
  }
402
463
 
464
+ // src/server/config/snapshot-options.ts
465
+ function isObject2(value) {
466
+ return typeof value === "object" && value !== null;
467
+ }
468
+ function pick(source, keys) {
469
+ const copy = {};
470
+ for (const key of keys) {
471
+ const value = source[key];
472
+ if (value !== void 0) copy[key] = value;
473
+ }
474
+ return copy;
475
+ }
476
+ function pickGroup(value, keys) {
477
+ return isObject2(value) ? pick(value, keys) : value;
478
+ }
479
+ function copyArray(value) {
480
+ if (!Array.isArray(value)) return value;
481
+ try {
482
+ return Array.from(value);
483
+ } catch {
484
+ return value;
485
+ }
486
+ }
487
+ var GROUPS = {
488
+ credentials: CREDENTIAL_KEYS,
489
+ signedUrls: SIGNED_URL_KEYS,
490
+ multipart: MULTIPART_KEYS,
491
+ validation: VALIDATION_KEYS,
492
+ scanner: SCANNER_KEYS
493
+ };
494
+ function snapshotOptions(options) {
495
+ if (!isObject2(options)) return options;
496
+ const copy = pick(options, OPTION_KEYS);
497
+ for (const [group, keys] of Object.entries(GROUPS)) {
498
+ if (group in copy) copy[group] = pickGroup(copy[group], keys);
499
+ }
500
+ const validation = copy.validation;
501
+ if (isObject2(validation)) {
502
+ for (const key of ["mimeWhitelist", "customValidators"]) {
503
+ if (key in validation) validation[key] = copyArray(validation[key]);
504
+ }
505
+ }
506
+ return copy;
507
+ }
508
+
403
509
  // src/server/utils/describe-endpoint.ts
404
510
  function describeEndpoint(endpoint) {
405
511
  try {
@@ -566,6 +672,39 @@ KeyResolverService = __decorateClass([
566
672
  __decorateParam(0, common.Inject(BYMAX_STORAGE_OPTIONS))
567
673
  ], KeyResolverService);
568
674
 
675
+ // src/server/utils/call-input.ts
676
+ function wrongKind(field2, needs) {
677
+ return new StorageException(STORAGE_ERROR_CODES.STORAGE_VALIDATION_FAILED, void 0, {
678
+ field: field2,
679
+ reason: `${field2} must be ${needs}`
680
+ });
681
+ }
682
+ function resolveBucket(perCall, moduleDefault) {
683
+ if (perCall !== void 0 && perCall !== null && typeof perCall !== "string") {
684
+ throw wrongKind("bucket", "a string");
685
+ }
686
+ const bucket = perCall ?? moduleDefault;
687
+ if (!bucket) {
688
+ throw new StorageException(STORAGE_ERROR_CODES.STORAGE_BUCKET_UNDEFINED);
689
+ }
690
+ return bucket;
691
+ }
692
+ function assertAbortSignal(signal) {
693
+ if (signal === void 0 || signal === null) return;
694
+ if (!hasSignalSurface(signal)) {
695
+ throw wrongKind("abortSignal", "an AbortSignal");
696
+ }
697
+ }
698
+ function hasSignalSurface(signal) {
699
+ if (typeof signal !== "object") return false;
700
+ const candidate = signal;
701
+ try {
702
+ return typeof candidate.aborted === "boolean" && typeof candidate.addEventListener === "function";
703
+ } catch {
704
+ return false;
705
+ }
706
+ }
707
+
569
708
  // src/server/utils/describe-error.ts
570
709
  var NON_PRINTABLE_REJECTION = "non-printable rejection value";
571
710
  function describeError(value) {
@@ -1022,11 +1161,7 @@ exports.BucketLifecycleService = class BucketLifecycleService {
1022
1161
  }
1023
1162
  }
1024
1163
  resolveBucket(perCall) {
1025
- const bucket = perCall ?? this.options.bucket;
1026
- if (!bucket) {
1027
- throw new StorageException(STORAGE_ERROR_CODES.STORAGE_BUCKET_UNDEFINED);
1028
- }
1029
- return bucket;
1164
+ return resolveBucket(perCall, this.options.bucket);
1030
1165
  }
1031
1166
  };
1032
1167
  exports.BucketLifecycleService = __decorateClass([
@@ -1146,7 +1281,7 @@ function toUploadBody(body) {
1146
1281
  return Buffer.from(body.buffer, body.byteOffset, body.byteLength);
1147
1282
  }
1148
1283
  const stream = body;
1149
- const readable = typeof stream?.pipe === "function" && typeof stream.on === "function" && typeof stream.once === "function";
1284
+ const readable = typeof stream?.pipe === "function" && typeof stream.on === "function" && typeof stream.once === "function" && typeof stream.pause === "function" && typeof stream.resume === "function";
1150
1285
  if (!(body instanceof Uint8Array) && !readable) {
1151
1286
  throw new StorageException(STORAGE_ERROR_CODES.STORAGE_VALIDATION_FAILED, void 0, {
1152
1287
  field: "body",
@@ -1298,15 +1433,25 @@ ValidationService = __decorateClass([
1298
1433
  __decorateParam(0, common.Inject(BYMAX_STORAGE_OPTIONS)),
1299
1434
  __decorateParam(1, common.Inject(BYMAX_STORAGE_UPLOAD_VALIDATORS))
1300
1435
  ], ValidationService);
1436
+
1437
+ // src/server/utils/cut-text.ts
1438
+ function cutText(text, max) {
1439
+ if (text.length <= max) return text;
1440
+ const lastKept = text.charCodeAt(max - 1);
1441
+ const splitsPair = lastKept >= 55296 && lastKept <= 56319;
1442
+ return text.slice(0, splitsPair ? max - 1 : max);
1443
+ }
1444
+
1445
+ // src/server/services/file-scanner.service.ts
1301
1446
  var UNSERIALISABLE = "[unserialisable]";
1302
1447
  var MAX_SCANNER_LABEL_LENGTH = 200;
1303
1448
  var MAX_SCANNER_DETAILS_LENGTH = 300;
1304
1449
  var MAX_STATUS_LOG_LENGTH = 40;
1305
1450
  function statusForLog(status) {
1306
- return typeof status === "string" ? logValue(status.slice(0, MAX_STATUS_LOG_LENGTH)) : `<${typeof status}>`;
1451
+ return typeof status === "string" ? logValue(cutText(status, MAX_STATUS_LOG_LENGTH)) : `<${typeof status}>`;
1307
1452
  }
1308
1453
  function scannerLabel(value) {
1309
- return typeof value === "string" ? value.slice(0, MAX_SCANNER_LABEL_LENGTH) : void 0;
1454
+ return typeof value === "string" ? cutText(value, MAX_SCANNER_LABEL_LENGTH) : void 0;
1310
1455
  }
1311
1456
  function toJson(value) {
1312
1457
  return JSON.stringify(value);
@@ -1319,7 +1464,7 @@ function scannerDetailsForLog(details) {
1319
1464
  } catch {
1320
1465
  text = UNSERIALISABLE;
1321
1466
  }
1322
- return ` details=${logValue(text.slice(0, MAX_SCANNER_DETAILS_LENGTH))}`;
1467
+ return ` details=${logValue(cutText(text, MAX_SCANNER_DETAILS_LENGTH))}`;
1323
1468
  }
1324
1469
  var FileScannerService = class {
1325
1470
  constructor(options, scanner) {
@@ -1409,7 +1554,7 @@ var FileScannerService = class {
1409
1554
  } catch (err) {
1410
1555
  if (!(err instanceof StorageException)) {
1411
1556
  this.logger.warn(
1412
- `Scanner failed: key=${logValue(input.key)} error=${logValue(describeError(err).slice(0, MAX_SCANNER_DETAILS_LENGTH))}`
1557
+ `Scanner failed: key=${logValue(input.key)} error=${logValue(cutText(describeError(err), MAX_SCANNER_DETAILS_LENGTH))}`
1413
1558
  );
1414
1559
  }
1415
1560
  throw err;
@@ -1426,6 +1571,7 @@ var FileScannerService = class {
1426
1571
  let timer;
1427
1572
  const deadline = new Promise((_resolve, reject) => {
1428
1573
  timer = setTimeout(() => {
1574
+ this.logger.warn(`Scan timed out: key=${logValue(input.key)} timeoutMs=${String(timeoutMs)}`);
1429
1575
  reject(
1430
1576
  new StorageException(STORAGE_ERROR_CODES.STORAGE_TIMEOUT, void 0, {
1431
1577
  key: input.key,
@@ -1459,7 +1605,11 @@ var SourceIdleError = class extends Error {
1459
1605
  };
1460
1606
  function isError(value) {
1461
1607
  const candidate = value;
1462
- return typeof candidate?.name === "string" && typeof candidate.message === "string";
1608
+ try {
1609
+ return typeof candidate?.name === "string" && typeof candidate.message === "string";
1610
+ } catch {
1611
+ return false;
1612
+ }
1463
1613
  }
1464
1614
  function withinIdleTime(next, idleMs) {
1465
1615
  return new Promise((resolve, reject) => {
@@ -1693,6 +1843,7 @@ function requestAborted(signal, context) {
1693
1843
  });
1694
1844
  }
1695
1845
  function throwIfAborted(signal, context) {
1846
+ assertAbortSignal(signal);
1696
1847
  if (signal?.aborted) {
1697
1848
  throw requestAborted(signal, context);
1698
1849
  }
@@ -2470,11 +2621,7 @@ exports.StorageService = class StorageService {
2470
2621
  }
2471
2622
  /** Resolves the target bucket from a per-call override or the module default. */
2472
2623
  resolveBucket(perCall) {
2473
- const bucket = perCall ?? this.options.bucket;
2474
- if (!bucket) {
2475
- throw new StorageException(STORAGE_ERROR_CODES.STORAGE_BUCKET_UNDEFINED);
2476
- }
2477
- return bucket;
2624
+ return resolveBucket(perCall, this.options.bucket);
2478
2625
  }
2479
2626
  /** Maps an S3 metadata response onto the public `ObjectMetadata` shape. */
2480
2627
  toObjectMetadata(response, finalKey, bucket) {
@@ -2873,7 +3020,8 @@ exports.SignedUrlService = class SignedUrlService {
2873
3020
  if (!Number.isInteger(options.parts) || options.parts < 1 || options.parts > MAX_MULTIPART_PARTS) {
2874
3021
  throw new StorageException(STORAGE_ERROR_CODES.STORAGE_INVALID_PART_COUNT, void 0, {
2875
3022
  reason: `parts must be an integer from 1 to ${String(MAX_MULTIPART_PARTS)}`,
2876
- provided: options.parts
3023
+ // Only a number is repeated: any other value is the caller's to keep.
3024
+ ...Number.isFinite(options.parts) ? { provided: options.parts } : {}
2877
3025
  });
2878
3026
  }
2879
3027
  const finalKey = this.keyResolver.normalize(options.key);
@@ -2929,11 +3077,7 @@ exports.SignedUrlService = class SignedUrlService {
2929
3077
  }
2930
3078
  /** Resolves the target bucket from a per-call override or the module default. */
2931
3079
  resolveBucket(perCall) {
2932
- const bucket = perCall ?? this.options.bucket;
2933
- if (!bucket) {
2934
- throw new StorageException(STORAGE_ERROR_CODES.STORAGE_BUCKET_UNDEFINED);
2935
- }
2936
- return bucket;
3080
+ return resolveBucket(perCall, this.options.bucket);
2937
3081
  }
2938
3082
  };
2939
3083
  exports.SignedUrlService = __decorateClass([
@@ -3044,7 +3188,8 @@ var IdempotencyCache = class {
3044
3188
  };
3045
3189
 
3046
3190
  // src/server/bymax-storage.module.ts
3047
- function resolveAsyncOptions(options) {
3191
+ function resolveAsyncOptions(raw) {
3192
+ const options = snapshotOptions(raw);
3048
3193
  validateOptions(options);
3049
3194
  const resolved = applyDefaults(options);
3050
3195
  const configured = options.signedUrls?.maxTtlSeconds;
@@ -176,6 +176,7 @@ function assertMetadata(metadata) {
176
176
  var MIN_PART_SIZE_BYTES = 5 * 1024 * 1024;
177
177
  var MAX_PART_SIZE_BYTES = 5 * 1024 * 1024 * 1024;
178
178
  var MAX_QUEUE_SIZE = 1e3;
179
+ var REGION_SHAPE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$/;
179
180
  function invalid(reason) {
180
181
  return new StorageException(STORAGE_ERROR_CODES.STORAGE_INVALID_CONFIG, HttpStatus.INTERNAL_SERVER_ERROR, {
181
182
  reason
@@ -226,7 +227,8 @@ function assertBoundedInteger(section, group, key, range) {
226
227
  }
227
228
  }
228
229
  function assertScanner(scanner) {
229
- if (scanner === void 0 || scanner === null) return;
230
+ if (scanner === void 0) return;
231
+ if (scanner === null) throw invalid("scanner must not be null; omit it for no scanner");
230
232
  if (!isObject(scanner)) throw invalid("scanner must be an object");
231
233
  const impl = scanner.impl;
232
234
  if (!isObject(impl) || typeof impl.scan !== "function") {
@@ -240,6 +242,25 @@ function assertScanner(scanner) {
240
242
  throw invalid("scanner.rejectOnUnknown must be a boolean");
241
243
  }
242
244
  }
245
+ function assertValidationKinds(validation) {
246
+ if (!isObject(validation)) return;
247
+ const { maxSizeBytes, mimeWhitelist, customValidators } = validation;
248
+ if (maxSizeBytes === null) {
249
+ throw invalid("validation.maxSizeBytes must not be null; omit it for no size limit");
250
+ }
251
+ if (mimeWhitelist === null) {
252
+ throw invalid("validation.mimeWhitelist must not be null; omit it to allow every type");
253
+ }
254
+ if (mimeWhitelist !== void 0 && (!Array.isArray(mimeWhitelist) || !Array.from(mimeWhitelist).every((entry) => typeof entry === "string"))) {
255
+ throw invalid("validation.mimeWhitelist must be an array of strings");
256
+ }
257
+ if (customValidators === null) {
258
+ throw invalid("validation.customValidators must not be null; omit it to run no custom validator");
259
+ }
260
+ if (customValidators !== void 0 && !Array.isArray(customValidators)) {
261
+ throw invalid("validation.customValidators must be an array");
262
+ }
263
+ }
243
264
  function assertNumericSections(options) {
244
265
  const MAX = Number.MAX_SAFE_INTEGER;
245
266
  assertBoundedInteger(options.validation, "validation", "maxSizeBytes", { min: 1, max: MAX });
@@ -257,6 +278,7 @@ function assertNumericSections(options) {
257
278
  }
258
279
  function assertLimitsAndEncryption(options) {
259
280
  assertNumericSections(options);
281
+ assertValidationKinds(options.validation);
260
282
  assertScanner(options.scanner);
261
283
  const maxAttempts = options.maxAttempts;
262
284
  if (maxAttempts !== void 0 && (typeof maxAttempts !== "number" || !Number.isInteger(maxAttempts) || maxAttempts < 1 || maxAttempts > Number.MAX_SAFE_INTEGER)) {
@@ -290,9 +312,17 @@ function validateOptions(options) {
290
312
  if (!isNonEmptyString(options.region)) {
291
313
  throw invalid("options.region must be a non-empty string");
292
314
  }
315
+ if (!REGION_SHAPE.test(options.region)) {
316
+ throw invalid(
317
+ "options.region must be 1 to 63 letters, digits, '.', '_' or '-', starting with a letter or digit"
318
+ );
319
+ }
293
320
  if (!isNonEmptyString(options.bucket)) {
294
321
  throw invalid("options.bucket must be a non-empty string");
295
322
  }
323
+ if (options.keyPrefix !== void 0 && options.keyPrefix !== null && typeof options.keyPrefix !== "string") {
324
+ throw invalid("options.keyPrefix must be a string");
325
+ }
296
326
  if (!isObject(options.credentials)) {
297
327
  throw invalid("options.credentials is required");
298
328
  }
@@ -339,6 +369,41 @@ var DEFAULT_MULTIPART = {
339
369
  var DEFAULT_IDEMPOTENCY_CACHE_MAX_ENTRIES = 1e3;
340
370
  var DEFAULT_IDEMPOTENCY_CACHE_TTL_MS = 864e5;
341
371
 
372
+ // src/server/config/option-keys.ts
373
+ function keysOf() {
374
+ return (keys) => keys;
375
+ }
376
+ var OPTION_KEYS = keysOf()([
377
+ "endpoint",
378
+ "region",
379
+ "bucket",
380
+ "credentials",
381
+ "forcePathStyle",
382
+ "publicBaseUrl",
383
+ "cdnBaseUrl",
384
+ "defaultPublicRead",
385
+ "keyPrefix",
386
+ "defaultCacheControl",
387
+ "defaultContentDisposition",
388
+ "signedUrls",
389
+ "multipart",
390
+ "validation",
391
+ "scanner",
392
+ "serverSideEncryption",
393
+ "kmsKeyId",
394
+ "requestChecksumCalculation",
395
+ "responseChecksumValidation",
396
+ "maxAttempts",
397
+ "requestTimeoutMs",
398
+ "uploadIdleTimeoutMs",
399
+ "bodyIdleTimeoutMs"
400
+ ]);
401
+ var CREDENTIAL_KEYS = keysOf()(["accessKeyId", "secretAccessKey", "sessionToken"]);
402
+ var SIGNED_URL_KEYS = keysOf()(["defaultGetTtlSeconds", "defaultPutTtlSeconds", "maxTtlSeconds"]);
403
+ var MULTIPART_KEYS = keysOf()(["thresholdBytes", "partSizeBytes", "queueSize"]);
404
+ var VALIDATION_KEYS = keysOf()(["mimeWhitelist", "maxSizeBytes", "customValidators"]);
405
+ var SCANNER_KEYS = keysOf()(["impl", "mode", "rejectOnUnknown", "timeoutMs"]);
406
+
342
407
  // src/server/config/apply-defaults.ts
343
408
  function definedOnly(group, keys) {
344
409
  const picked = {};
@@ -348,10 +413,6 @@ function definedOnly(group, keys) {
348
413
  }
349
414
  return picked;
350
415
  }
351
- var SIGNED_URL_KEYS = ["defaultGetTtlSeconds", "defaultPutTtlSeconds", "maxTtlSeconds"];
352
- var MULTIPART_KEYS = ["thresholdBytes", "partSizeBytes", "queueSize"];
353
- var VALIDATION_KEYS = ["mimeWhitelist", "maxSizeBytes", "customValidators"];
354
- var SCANNER_KEYS = ["impl", "mode", "rejectOnUnknown", "timeoutMs"];
355
416
  function resolveSignedUrls(configured) {
356
417
  const merged = { ...DEFAULT_SIGNED_URLS, ...definedOnly(configured, SIGNED_URL_KEYS) };
357
418
  return { ...merged, maxTtlSeconds: Math.min(merged.maxTtlSeconds, MAX_SIGNED_URL_TTL_SECONDS) };
@@ -382,7 +443,7 @@ function applyDefaults(options) {
382
443
  signedUrls: resolveSignedUrls(options.signedUrls),
383
444
  multipart: { ...DEFAULT_MULTIPART, ...definedOnly(options.multipart, MULTIPART_KEYS) },
384
445
  ...options.validation !== void 0 ? { validation: definedOnly(options.validation, VALIDATION_KEYS) } : {},
385
- // `null` is no scanner, as `undefined` is: a group is an object or it is not configured.
446
+ // A group is an object or it is not configured. `forRoot` refuses a `null` scanner before this runs; if one reaches here it adds no scanner.
386
447
  ...options.scanner ? { scanner: definedOnly(options.scanner, SCANNER_KEYS) } : {},
387
448
  ...options.serverSideEncryption !== void 0 ? { serverSideEncryption: options.serverSideEncryption } : {},
388
449
  ...options.kmsKeyId !== void 0 ? { kmsKeyId: options.kmsKeyId } : {},
@@ -398,6 +459,51 @@ function applyDefaults(options) {
398
459
  return resolved;
399
460
  }
400
461
 
462
+ // src/server/config/snapshot-options.ts
463
+ function isObject2(value) {
464
+ return typeof value === "object" && value !== null;
465
+ }
466
+ function pick(source, keys) {
467
+ const copy = {};
468
+ for (const key of keys) {
469
+ const value = source[key];
470
+ if (value !== void 0) copy[key] = value;
471
+ }
472
+ return copy;
473
+ }
474
+ function pickGroup(value, keys) {
475
+ return isObject2(value) ? pick(value, keys) : value;
476
+ }
477
+ function copyArray(value) {
478
+ if (!Array.isArray(value)) return value;
479
+ try {
480
+ return Array.from(value);
481
+ } catch {
482
+ return value;
483
+ }
484
+ }
485
+ var GROUPS = {
486
+ credentials: CREDENTIAL_KEYS,
487
+ signedUrls: SIGNED_URL_KEYS,
488
+ multipart: MULTIPART_KEYS,
489
+ validation: VALIDATION_KEYS,
490
+ scanner: SCANNER_KEYS
491
+ };
492
+ function snapshotOptions(options) {
493
+ if (!isObject2(options)) return options;
494
+ const copy = pick(options, OPTION_KEYS);
495
+ for (const [group, keys] of Object.entries(GROUPS)) {
496
+ if (group in copy) copy[group] = pickGroup(copy[group], keys);
497
+ }
498
+ const validation = copy.validation;
499
+ if (isObject2(validation)) {
500
+ for (const key of ["mimeWhitelist", "customValidators"]) {
501
+ if (key in validation) validation[key] = copyArray(validation[key]);
502
+ }
503
+ }
504
+ return copy;
505
+ }
506
+
401
507
  // src/server/utils/describe-endpoint.ts
402
508
  function describeEndpoint(endpoint) {
403
509
  try {
@@ -564,6 +670,39 @@ KeyResolverService = __decorateClass([
564
670
  __decorateParam(0, Inject(BYMAX_STORAGE_OPTIONS))
565
671
  ], KeyResolverService);
566
672
 
673
+ // src/server/utils/call-input.ts
674
+ function wrongKind(field2, needs) {
675
+ return new StorageException(STORAGE_ERROR_CODES.STORAGE_VALIDATION_FAILED, void 0, {
676
+ field: field2,
677
+ reason: `${field2} must be ${needs}`
678
+ });
679
+ }
680
+ function resolveBucket(perCall, moduleDefault) {
681
+ if (perCall !== void 0 && perCall !== null && typeof perCall !== "string") {
682
+ throw wrongKind("bucket", "a string");
683
+ }
684
+ const bucket = perCall ?? moduleDefault;
685
+ if (!bucket) {
686
+ throw new StorageException(STORAGE_ERROR_CODES.STORAGE_BUCKET_UNDEFINED);
687
+ }
688
+ return bucket;
689
+ }
690
+ function assertAbortSignal(signal) {
691
+ if (signal === void 0 || signal === null) return;
692
+ if (!hasSignalSurface(signal)) {
693
+ throw wrongKind("abortSignal", "an AbortSignal");
694
+ }
695
+ }
696
+ function hasSignalSurface(signal) {
697
+ if (typeof signal !== "object") return false;
698
+ const candidate = signal;
699
+ try {
700
+ return typeof candidate.aborted === "boolean" && typeof candidate.addEventListener === "function";
701
+ } catch {
702
+ return false;
703
+ }
704
+ }
705
+
567
706
  // src/server/utils/describe-error.ts
568
707
  var NON_PRINTABLE_REJECTION = "non-printable rejection value";
569
708
  function describeError(value) {
@@ -1020,11 +1159,7 @@ var BucketLifecycleService = class {
1020
1159
  }
1021
1160
  }
1022
1161
  resolveBucket(perCall) {
1023
- const bucket = perCall ?? this.options.bucket;
1024
- if (!bucket) {
1025
- throw new StorageException(STORAGE_ERROR_CODES.STORAGE_BUCKET_UNDEFINED);
1026
- }
1027
- return bucket;
1162
+ return resolveBucket(perCall, this.options.bucket);
1028
1163
  }
1029
1164
  };
1030
1165
  BucketLifecycleService = __decorateClass([
@@ -1144,7 +1279,7 @@ function toUploadBody(body) {
1144
1279
  return Buffer.from(body.buffer, body.byteOffset, body.byteLength);
1145
1280
  }
1146
1281
  const stream = body;
1147
- const readable = typeof stream?.pipe === "function" && typeof stream.on === "function" && typeof stream.once === "function";
1282
+ const readable = typeof stream?.pipe === "function" && typeof stream.on === "function" && typeof stream.once === "function" && typeof stream.pause === "function" && typeof stream.resume === "function";
1148
1283
  if (!(body instanceof Uint8Array) && !readable) {
1149
1284
  throw new StorageException(STORAGE_ERROR_CODES.STORAGE_VALIDATION_FAILED, void 0, {
1150
1285
  field: "body",
@@ -1296,15 +1431,25 @@ ValidationService = __decorateClass([
1296
1431
  __decorateParam(0, Inject(BYMAX_STORAGE_OPTIONS)),
1297
1432
  __decorateParam(1, Inject(BYMAX_STORAGE_UPLOAD_VALIDATORS))
1298
1433
  ], ValidationService);
1434
+
1435
+ // src/server/utils/cut-text.ts
1436
+ function cutText(text, max) {
1437
+ if (text.length <= max) return text;
1438
+ const lastKept = text.charCodeAt(max - 1);
1439
+ const splitsPair = lastKept >= 55296 && lastKept <= 56319;
1440
+ return text.slice(0, splitsPair ? max - 1 : max);
1441
+ }
1442
+
1443
+ // src/server/services/file-scanner.service.ts
1299
1444
  var UNSERIALISABLE = "[unserialisable]";
1300
1445
  var MAX_SCANNER_LABEL_LENGTH = 200;
1301
1446
  var MAX_SCANNER_DETAILS_LENGTH = 300;
1302
1447
  var MAX_STATUS_LOG_LENGTH = 40;
1303
1448
  function statusForLog(status) {
1304
- return typeof status === "string" ? logValue(status.slice(0, MAX_STATUS_LOG_LENGTH)) : `<${typeof status}>`;
1449
+ return typeof status === "string" ? logValue(cutText(status, MAX_STATUS_LOG_LENGTH)) : `<${typeof status}>`;
1305
1450
  }
1306
1451
  function scannerLabel(value) {
1307
- return typeof value === "string" ? value.slice(0, MAX_SCANNER_LABEL_LENGTH) : void 0;
1452
+ return typeof value === "string" ? cutText(value, MAX_SCANNER_LABEL_LENGTH) : void 0;
1308
1453
  }
1309
1454
  function toJson(value) {
1310
1455
  return JSON.stringify(value);
@@ -1317,7 +1462,7 @@ function scannerDetailsForLog(details) {
1317
1462
  } catch {
1318
1463
  text = UNSERIALISABLE;
1319
1464
  }
1320
- return ` details=${logValue(text.slice(0, MAX_SCANNER_DETAILS_LENGTH))}`;
1465
+ return ` details=${logValue(cutText(text, MAX_SCANNER_DETAILS_LENGTH))}`;
1321
1466
  }
1322
1467
  var FileScannerService = class {
1323
1468
  constructor(options, scanner) {
@@ -1407,7 +1552,7 @@ var FileScannerService = class {
1407
1552
  } catch (err) {
1408
1553
  if (!(err instanceof StorageException)) {
1409
1554
  this.logger.warn(
1410
- `Scanner failed: key=${logValue(input.key)} error=${logValue(describeError(err).slice(0, MAX_SCANNER_DETAILS_LENGTH))}`
1555
+ `Scanner failed: key=${logValue(input.key)} error=${logValue(cutText(describeError(err), MAX_SCANNER_DETAILS_LENGTH))}`
1411
1556
  );
1412
1557
  }
1413
1558
  throw err;
@@ -1424,6 +1569,7 @@ var FileScannerService = class {
1424
1569
  let timer;
1425
1570
  const deadline = new Promise((_resolve, reject) => {
1426
1571
  timer = setTimeout(() => {
1572
+ this.logger.warn(`Scan timed out: key=${logValue(input.key)} timeoutMs=${String(timeoutMs)}`);
1427
1573
  reject(
1428
1574
  new StorageException(STORAGE_ERROR_CODES.STORAGE_TIMEOUT, void 0, {
1429
1575
  key: input.key,
@@ -1457,7 +1603,11 @@ var SourceIdleError = class extends Error {
1457
1603
  };
1458
1604
  function isError(value) {
1459
1605
  const candidate = value;
1460
- return typeof candidate?.name === "string" && typeof candidate.message === "string";
1606
+ try {
1607
+ return typeof candidate?.name === "string" && typeof candidate.message === "string";
1608
+ } catch {
1609
+ return false;
1610
+ }
1461
1611
  }
1462
1612
  function withinIdleTime(next, idleMs) {
1463
1613
  return new Promise((resolve, reject) => {
@@ -1691,6 +1841,7 @@ function requestAborted(signal, context) {
1691
1841
  });
1692
1842
  }
1693
1843
  function throwIfAborted(signal, context) {
1844
+ assertAbortSignal(signal);
1694
1845
  if (signal?.aborted) {
1695
1846
  throw requestAborted(signal, context);
1696
1847
  }
@@ -2468,11 +2619,7 @@ var StorageService = class {
2468
2619
  }
2469
2620
  /** Resolves the target bucket from a per-call override or the module default. */
2470
2621
  resolveBucket(perCall) {
2471
- const bucket = perCall ?? this.options.bucket;
2472
- if (!bucket) {
2473
- throw new StorageException(STORAGE_ERROR_CODES.STORAGE_BUCKET_UNDEFINED);
2474
- }
2475
- return bucket;
2622
+ return resolveBucket(perCall, this.options.bucket);
2476
2623
  }
2477
2624
  /** Maps an S3 metadata response onto the public `ObjectMetadata` shape. */
2478
2625
  toObjectMetadata(response, finalKey, bucket) {
@@ -2871,7 +3018,8 @@ var SignedUrlService = class {
2871
3018
  if (!Number.isInteger(options.parts) || options.parts < 1 || options.parts > MAX_MULTIPART_PARTS) {
2872
3019
  throw new StorageException(STORAGE_ERROR_CODES.STORAGE_INVALID_PART_COUNT, void 0, {
2873
3020
  reason: `parts must be an integer from 1 to ${String(MAX_MULTIPART_PARTS)}`,
2874
- provided: options.parts
3021
+ // Only a number is repeated: any other value is the caller's to keep.
3022
+ ...Number.isFinite(options.parts) ? { provided: options.parts } : {}
2875
3023
  });
2876
3024
  }
2877
3025
  const finalKey = this.keyResolver.normalize(options.key);
@@ -2927,11 +3075,7 @@ var SignedUrlService = class {
2927
3075
  }
2928
3076
  /** Resolves the target bucket from a per-call override or the module default. */
2929
3077
  resolveBucket(perCall) {
2930
- const bucket = perCall ?? this.options.bucket;
2931
- if (!bucket) {
2932
- throw new StorageException(STORAGE_ERROR_CODES.STORAGE_BUCKET_UNDEFINED);
2933
- }
2934
- return bucket;
3078
+ return resolveBucket(perCall, this.options.bucket);
2935
3079
  }
2936
3080
  };
2937
3081
  SignedUrlService = __decorateClass([
@@ -3042,7 +3186,8 @@ var IdempotencyCache = class {
3042
3186
  };
3043
3187
 
3044
3188
  // src/server/bymax-storage.module.ts
3045
- function resolveAsyncOptions(options) {
3189
+ function resolveAsyncOptions(raw) {
3190
+ const options = snapshotOptions(raw);
3046
3191
  validateOptions(options);
3047
3192
  const resolved = applyDefaults(options);
3048
3193
  const configured = options.signedUrls?.maxTtlSeconds;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-storage",
3
- "version": "1.1.17",
3
+ "version": "1.1.18",
4
4
  "description": "Provider-agnostic S3-compatible object storage for NestJS. Works with AWS S3, DigitalOcean Spaces, Cloudflare R2, Backblaze B2, MinIO, Wasabi.",
5
5
  "author": "Bymax One <support@bymax.one>",
6
6
  "license": "MIT",