@nextlyhq/storage-s3 0.0.2-alpha.67 → 0.0.2-alpha.69

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/dist/index.mjs CHANGED
@@ -1,1148 +1,1331 @@
1
- import { S3Client, DeleteObjectCommand, DeleteObjectsCommand, HeadObjectCommand, GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3';
2
- import { Upload } from '@aws-sdk/lib-storage';
3
- import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
4
-
5
- // src/adapter.ts
6
-
7
- // ../nextly/dist/chunk-UF2PDDU4.mjs
1
+ import { DeleteObjectCommand, DeleteObjectsCommand, GetObjectCommand, HeadObjectCommand, ListObjectsV2Command, PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
2
+ import { Upload } from "@aws-sdk/lib-storage";
3
+ import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
4
+ // ../nextly/dist/nextly-error-D21_8kpX.mjs
8
5
  function isDbError(err) {
9
- if (!err || typeof err !== "object") return false;
10
- const obj = err;
11
- return obj.name === "DbError" && typeof obj.kind === "string";
6
+ if (!err || typeof err !== "object") return false;
7
+ const obj = err;
8
+ return obj.name === "DbError" && typeof obj.kind === "string";
9
+ }
10
+ /**
11
+ * The driver's own code for an error, wherever that driver puts it.
12
+ *
13
+ * Exported so callers that must distinguish one failure from another classify
14
+ * by the SAME extraction this module's mapping uses. A second reader would go
15
+ * looking in a different set of properties and disagree on exactly the drivers
16
+ * whose codes are hardest to find.
17
+ */
18
+ /**
19
+ * Whether an error is a duplicate-key rejection.
20
+ *
21
+ * Exposed because a plugin inserting into a table with a unique index has to
22
+ * tell "this row already exists" from "the database is broken", and the two
23
+ * arrive as the same thrown object. Derived from the existing SQLSTATE
24
+ * classification rather than by matching driver messages: those differ per
25
+ * driver and per version, and a plugin re-deriving it would be a second
26
+ * implementation of a question this module already answers.
27
+ */
28
+ /**
29
+ * Whether a driver code says the database was busy: the adapters' own code
30
+ * for a request that waited out `pool.connectionTimeoutMs`, the same on
31
+ * every dialect, or SQLITE_BUSY and its extended codes, another process
32
+ * holding the SQLite file past `busyTimeout`. Neither depends on the dialect,
33
+ * which is what lets {@link isDatabaseBusy} answer without one.
34
+ */
35
+ function isBusyCode(code) {
36
+ if (code === void 0) return false;
37
+ return code === "NEXTLY_POOL_WAIT_TIMEOUT" || code.toUpperCase().startsWith("SQLITE_BUSY");
12
38
  }
13
- var NEXTLY_ERROR_STATUS = {
14
- VALIDATION_ERROR: 400,
15
- INVALID_INPUT: 400,
16
- AUTH_REQUIRED: 401,
17
- AUTH_INVALID_CREDENTIALS: 401,
18
- TOKEN_EXPIRED: 401,
19
- FORBIDDEN: 403,
20
- // The password was right and the address is unverified. Distinct from
21
- // AUTH_INVALID_CREDENTIALS so the login page can offer to resend the link;
22
- // only a caller who proved the password ever receives it.
23
- EMAIL_NOT_VERIFIED: 403,
24
- // The schema builder is off in this environment (production by default).
25
- // Separate from FORBIDDEN: the caller's permissions are not the problem.
26
- BUILDER_DISABLED: 403,
27
- // A cookie-authenticated write whose origin or CSRF token did not check
28
- // out. Separate from FORBIDDEN for the same reason: the caller may hold
29
- // every permission, and a client can recover by reloading, not by asking
30
- // an administrator for access.
31
- CSRF_FAILED: 403,
32
- NOT_FOUND: 404,
33
- CONFLICT: 409,
34
- DUPLICATE: 409,
35
- RATE_LIMITED: 429,
36
- PAYLOAD_TOO_LARGE: 413,
37
- UNSUPPORTED_MEDIA_TYPE: 415,
38
- // 422: understood, well-formed, and refused on a rule the caller can act on.
39
- // Deliberately NOT added to CANONICAL_CODE_FOR_STATUS -- that list drives the
40
- // status -> code direction, where 422 stays mapped to INVALID_INPUT.
41
- BUSINESS_RULE_VIOLATION: 422,
42
- INTERNAL_ERROR: 500,
43
- DATABASE_ERROR: 500,
44
- EXTERNAL_SERVICE_ERROR: 502,
45
- SERVICE_UNAVAILABLE: 503,
46
- // Outbound-fetch safety (utils/validate-external-url): a URL refused for SSRF
47
- // safety, and a fetch that timed out / exceeded the size cap / failed to decode.
48
- EXTERNAL_URL_BLOCKED: 400,
49
- EXTERNAL_REQUEST_FAILED: 502,
50
- FILENAME_INVALID: 400,
51
- EXTENSION_BLOCKED: 400,
52
- MIME_BLOCKED: 415,
53
- MIME_NOT_ALLOWED: 415,
54
- SIZE_EXCEEDED: 413,
55
- // A stored object exceeded the cap a READ was given, which is a different
56
- // question from SIZE_EXCEEDED above: that one refuses an upload the caller
57
- // is sending, this one refuses to buffer an object already stored. Kept
58
- // apart so a caller discriminating on the code cannot match both.
59
- STORAGE_READ_TOO_LARGE: 413,
60
- // A stored object did not answer within the deadline the read was given. 504
61
- // rather than 500 because the failure is the BACKEND not answering, and a
62
- // caller can act on that difference: a gateway timeout is worth retrying, an
63
- // internal error is not.
64
- STORAGE_READ_TIMEOUT: 504,
65
- // The store answered, and answered badly. 502 rather than 500 because the
66
- // fault is UPSTREAM of this process: a caller can retry it, and an operator
67
- // reading the log needs to look at the bucket rather than at this service.
68
- // Distinct from the timeout above, which never got an answer at all.
69
- STORAGE_READ_UNREACHABLE: 502,
70
- MAGIC_BYTE_MISMATCH: 400,
71
- SVG_SANITIZATION_FAILED: 400,
72
- UNSUPPORTED_FOR_BACKEND: 415,
73
- // Plan B — schema bookkeeping consolidation.
74
- NEXTLY_LEGACY_BOOKKEEPING_DETECTED: 409,
75
- NEXTLY_UPGRADE_TABLE_NAME_COLLISION: 409,
76
- NEXTLY_UPGRADE_IN_PROGRESS: 409,
77
- // Plan C2 — nextly migrate phases.
78
- NEXTLY_MIGRATE_LOCK_BUSY: 409,
79
- NEXTLY_BASELINE_LOCK_NOT_HELD: 409,
80
- NEXTLY_RESOLVE_LOCK_NOT_HELD: 409,
81
- // Boot refused to serve: the migrate lock stayed held past the wait deadline,
82
- // so this process never established whether the schema matches the code. 503
83
- // rather than 409 — a load balancer should take the instance out of rotation
84
- // and retry it, which is exactly the recovery this refusal wants.
85
- NEXTLY_BOOT_MIGRATIONS_NOT_RUN: 503,
86
- // Still running rather than refused. 503 for the same reason: retry shortly.
87
- NEXTLY_BOOT_MIGRATIONS_PENDING: 503,
88
- NEXTLY_CORE_DESTRUCTIVE_REFUSED: 409,
89
- NEXTLY_MIGRATION_DRIFT: 409,
90
- NEXTLY_MIGRATION_APPLY_FAILED: 500,
91
- // A SQLite migration unit would leave a row referencing a row that does
92
- // not exist, or could not switch foreign-key enforcement off to run.
93
- NEXTLY_MIGRATION_FOREIGN_KEY_VIOLATION: 409,
94
- // A migration unit marked to run outside a transaction failed part-way;
95
- // the statements before the failing one stayed applied.
96
- NEXTLY_MIGRATION_PARTIALLY_APPLIED: 500,
97
- // Another run recorded the same migration applied, or rolled back, while
98
- // this one was running it: this run's ledger write lost, and its work is
99
- // rolled back wherever the transaction can undo it.
100
- NEXTLY_MIGRATION_CONCURRENT_RUN: 409,
101
- // `nextly migrate:resolve`, the recovery command.
102
- NEXTLY_MIGRATION_FILE_MISSING: 404,
103
- NEXTLY_MIGRATION_SNAPSHOT_MISSING: 404,
104
- NEXTLY_MIGRATION_RESOLVE_DRIFT: 409,
105
- NEXTLY_MIGRATION_RESOLVE_PRECONDITION: 409,
106
- // The Builder's UI schema.
107
- NEXTLY_UI_SCHEMA_INVALID: 400,
108
- NEXTLY_SCHEMA_SLUG_COLLISION: 409,
109
- NEXTLY_SCHEMA_RELATION_TARGET_MISSING: 400,
110
- // A declared table's relation names a table or column the registry does
111
- // not have once every table is registered.
112
- NEXTLY_SCHEMA_RELATION_UNRESOLVED: 400,
113
- // Plugin schema: `contributes.extend` and relations.
114
- NEXTLY_SCHEMA_EXTEND_TARGET_UNKNOWN: 400,
115
- NEXTLY_SCHEMA_EXTEND_FIELD_DUPLICATE: 409,
116
- NEXTLY_SCHEMA_CROSS_PLUGIN_RELATION: 409,
117
- // Plugin schema: the framework remap (`.rename()`).
118
- NEXTLY_SCHEMA_RENAME_UNKNOWN_TARGET: 400,
119
- // Plugin platform — a declared admin.clientConfig that cannot be delivered
120
- // to the browser, refused at boot rather than serialized mangled.
121
- NEXTLY_PLUGIN_CLIENT_CONFIG_INVALID: 500,
122
- // Plugin platform — a contributed admin widget that cannot be delivered to
123
- // the browser. Refused at boot because it is serialized into the ONE
124
- // `/api/admin-meta/workspace` payload: a value `JSON.stringify` throws on
125
- // fails that request for every admin, not just the widget's own card.
126
- NEXTLY_PLUGIN_ADMIN_WIDGET_INVALID: 500,
127
- // A plugin's document view cannot be routed: a malformed or reserved path,
128
- // or one two declarations claim on the same document. Refused at boot.
129
- NEXTLY_PLUGIN_DOCUMENT_VIEW_INVALID: 500,
130
- // Plugin platform (P0) — boot-time plugin dependency/version resolution.
131
- PLUGIN_RESOLUTION_ERROR: 500,
132
- // Plugin schema lifecycle. All 409: each is a state
133
- // the database and the config disagree about, which retrying cannot change
134
- // and an operator command resolves.
135
- PLUGIN_DEPENDENCY_NOT_INSTALLED: 409,
136
- PLUGIN_HAS_DEPENDENTS: 409,
137
- PLUGIN_UNINSTALL_IRREVERSIBLE: 409,
138
- // A full uninstall that would drop tables, run without `--yes`.
139
- PLUGIN_UNINSTALL_UNCONFIRMED: 409,
140
- PLUGIN_SCHEMA_BEHIND: 409,
141
- PLUGIN_SCHEMA_UNINSTALLED: 409,
142
- // A configured plugin `nextly plugins install` has not recorded as
143
- // installed, refused at a production boot.
144
- PLUGIN_NOT_INSTALLED: 409,
145
- PLUGIN_DISABLED: 409,
146
- // An uninstall that began and did not finish: refused at boot, and when
147
- // run again the other way (with or without `--keep-data`).
148
- PLUGIN_UNINSTALL_UNFINISHED: 409,
149
- PLUGIN_SCHEMA_VERSION_NOT_ADVANCED: 409,
150
- // A generated plugin migration that would drop a table or column the
151
- // plugin's earlier modules created: a rename comes out as a drop and an add.
152
- PLUGIN_MIGRATION_DROPS_CREATED_SCHEMA: 409,
153
- // A generated plugin migration that would add a NOT NULL column with no
154
- // default to a table its earlier modules created: existing rows have no
155
- // value for it.
156
- PLUGIN_MIGRATION_ADDS_UNFILLABLE_COLUMN: 409,
157
- // A plugin migration that changes the schema on a dialect with no
158
- // statements for it: its author's SQL was never written.
159
- PLUGIN_MIGRATION_SQL_MISSING: 409,
160
- PLUGIN_MIGRATIONS_UNAVAILABLE: 409,
161
- // A migration would drop or rename a table or column another owner holds
162
- // (or, for a plugin, a table no owner row claims), or names a drop target
163
- // the guard cannot read — refused for the same reason.
164
- DROP_OF_FOREIGN_TABLE: 409,
165
- // A plugin migration module whose content no longer matches its checksum.
166
- MIGRATION_CHECKSUM_MISMATCH: 409,
167
- // Plugin platform (P4) — contributes.routes collection (D25).
168
- NEXTLY_ROUTE_COLLISION: 409,
169
- NEXTLY_ROUTE_INVALID_PATH: 400,
170
- // A root-mounted route declared where the request pipeline never reaches the
171
- // root pass. 400 like an invalid path and not 409: nothing else claims the
172
- // address, the declaration simply cannot be served from there.
173
- NEXTLY_ROUTE_UNREACHABLE_ROOT: 400,
174
- // A `mount` outside the declared union, which only an untyped caller can
175
- // produce. 400 for the same reason: the declaration itself is unserveable.
176
- NEXTLY_ROUTE_INVALID_MOUNT: 400,
177
- // An email transport whose library is an optional peer dependency the host
178
- // has not installed. 503 rather than 500: the request is not malformed and
179
- // nothing is broken, the install simply cannot carry it out yet, and the
180
- // remedy is one command on the server rather than a change by the caller.
181
- NEXTLY_EMAIL_TRANSPORT_UNAVAILABLE: 503,
182
- // The tooling that compiles `nextly.config.ts` is an optional peer the host
183
- // has not installed. 503 rather than 500 for the same reason as the mail
184
- // transport above: nothing is broken and the request is not malformed, the
185
- // install simply cannot carry it out until one command is run.
186
- NEXTLY_CONFIG_TOOLING_UNAVAILABLE: 503,
187
- // `db.postgres.schema` names one schema and the adapter the application
188
- // supplied writes to another. 500 like the other boot-time configuration
189
- // refusals: no request caused it, and the fix is a change to the server's
190
- // own configuration.
191
- NEXTLY_POSTGRES_SCHEMA_MISMATCH: 500,
192
- // `db.postgres.schema` names a schema other than `public`, which the schema
193
- // push cannot yet create tables in. 500 for the same reason as the mismatch
194
- // above: a boot-time refusal of the server's own configuration.
195
- NEXTLY_POSTGRES_SCHEMA_UNSUPPORTED: 500
39
+ /**
40
+ * Whether an error is the database being busy, however it arrives: a DbError
41
+ * of kind "busy", or the raw error an adapter or driver threw.
42
+ *
43
+ * For the boundaries that answer a request with whatever its work threw.
44
+ * `withDbErrors` converts only DbErrors, so a raw driver error reaches them
45
+ * unconverted, and without this it would read as an internal fault rather
46
+ * than a request worth retrying.
47
+ */
48
+ function isDatabaseBusy(error) {
49
+ if (isDbError(error)) return error.kind === "busy";
50
+ return isBusyCode(safeCode(error));
51
+ }
52
+ function safeCode(error) {
53
+ if (!error || typeof error !== "object") return void 0;
54
+ const e = error;
55
+ let c = e.code ?? e.sqlState ?? e.state ?? e.errno ?? void 0;
56
+ if (!c && typeof e.originalError?.code === "string") c = e.originalError.code;
57
+ if (!c && typeof e.cause?.code === "string") c = e.cause.code;
58
+ if (!c && typeof e.severity === "string" && typeof e.code === "string") c = e.code;
59
+ if (typeof c === "number") return String(c);
60
+ if (typeof c === "string" && c.length > 0) return c;
61
+ }
62
+ /**
63
+ * Canonical NextlyError codes and their HTTP status mappings.
64
+ *
65
+ * Plugin codes outside this enum must always pass an explicit `statusCode`
66
+ * to the NextlyError constructor (no enum lookup happens for unknown codes).
67
+ */
68
+ const NEXTLY_ERROR_STATUS = {
69
+ VALIDATION_ERROR: 400,
70
+ INVALID_INPUT: 400,
71
+ AUTH_REQUIRED: 401,
72
+ AUTH_INVALID_CREDENTIALS: 401,
73
+ TOKEN_EXPIRED: 401,
74
+ FORBIDDEN: 403,
75
+ EMAIL_NOT_VERIFIED: 403,
76
+ BUILDER_DISABLED: 403,
77
+ CSRF_FAILED: 403,
78
+ SETUP_TOKEN_REQUIRED: 403,
79
+ API_KEY_ROLE_ABOVE_CREATOR: 403,
80
+ NOT_FOUND: 404,
81
+ METHOD_NOT_ALLOWED: 405,
82
+ CONFLICT: 409,
83
+ DUPLICATE: 409,
84
+ RATE_LIMITED: 429,
85
+ PAYLOAD_TOO_LARGE: 413,
86
+ UNSUPPORTED_MEDIA_TYPE: 415,
87
+ BUSINESS_RULE_VIOLATION: 422,
88
+ INTERNAL_ERROR: 500,
89
+ DATABASE_ERROR: 500,
90
+ DATABASE_BUSY: 503,
91
+ EXTERNAL_SERVICE_ERROR: 502,
92
+ SERVICE_UNAVAILABLE: 503,
93
+ EXTERNAL_URL_BLOCKED: 400,
94
+ EXTERNAL_REQUEST_FAILED: 502,
95
+ FILENAME_INVALID: 400,
96
+ EXTENSION_BLOCKED: 400,
97
+ MIME_BLOCKED: 415,
98
+ MIME_NOT_ALLOWED: 415,
99
+ SIZE_EXCEEDED: 413,
100
+ STORAGE_READ_TOO_LARGE: 413,
101
+ STORAGE_READ_TIMEOUT: 504,
102
+ STORAGE_READ_UNREACHABLE: 502,
103
+ MAGIC_BYTE_MISMATCH: 400,
104
+ SVG_SANITIZATION_FAILED: 400,
105
+ UNSUPPORTED_FOR_BACKEND: 415,
106
+ NEXTLY_LEGACY_BOOKKEEPING_DETECTED: 409,
107
+ NEXTLY_UPGRADE_TABLE_NAME_COLLISION: 409,
108
+ NEXTLY_UPGRADE_IN_PROGRESS: 409,
109
+ NEXTLY_MIGRATE_LOCK_BUSY: 409,
110
+ NEXTLY_BASELINE_LOCK_NOT_HELD: 409,
111
+ NEXTLY_RESOLVE_LOCK_NOT_HELD: 409,
112
+ NEXTLY_BOOT_MIGRATIONS_NOT_RUN: 503,
113
+ NEXTLY_BOOT_MIGRATIONS_PENDING: 503,
114
+ NEXTLY_CORE_DESTRUCTIVE_REFUSED: 409,
115
+ NEXTLY_MIGRATION_DRIFT: 409,
116
+ NEXTLY_MIGRATION_APPLY_FAILED: 500,
117
+ NEXTLY_MIGRATION_FOREIGN_KEY_VIOLATION: 409,
118
+ NEXTLY_MIGRATION_PARTIALLY_APPLIED: 500,
119
+ NEXTLY_MIGRATION_CONCURRENT_RUN: 409,
120
+ NEXTLY_MIGRATION_FILE_MISSING: 404,
121
+ NEXTLY_MIGRATION_SNAPSHOT_MISSING: 404,
122
+ NEXTLY_MIGRATION_RESOLVE_DRIFT: 409,
123
+ NEXTLY_MIGRATION_RESOLVE_PRECONDITION: 409,
124
+ NEXTLY_UI_SCHEMA_INVALID: 400,
125
+ NEXTLY_SCHEMA_SLUG_COLLISION: 409,
126
+ NEXTLY_SCHEMA_RELATION_TARGET_MISSING: 400,
127
+ NEXTLY_SCHEMA_RELATION_UNRESOLVED: 400,
128
+ NEXTLY_SCHEMA_EXTEND_TARGET_UNKNOWN: 400,
129
+ NEXTLY_SCHEMA_EXTEND_FIELD_DUPLICATE: 409,
130
+ NEXTLY_SCHEMA_CROSS_PLUGIN_RELATION: 409,
131
+ NEXTLY_SCHEMA_RENAME_UNKNOWN_TARGET: 400,
132
+ NEXTLY_PLUGIN_CLIENT_CONFIG_INVALID: 500,
133
+ NEXTLY_PLUGIN_ADMIN_WIDGET_INVALID: 500,
134
+ NEXTLY_ADMIN_COMPONENT_MAP_STALE: 500,
135
+ NEXTLY_PLUGIN_DOCUMENT_VIEW_INVALID: 500,
136
+ PLUGIN_RESOLUTION_ERROR: 500,
137
+ PLUGIN_DEPENDENCY_NOT_INSTALLED: 409,
138
+ PLUGIN_HAS_DEPENDENTS: 409,
139
+ PLUGIN_UNINSTALL_IRREVERSIBLE: 409,
140
+ PLUGIN_UNINSTALL_UNCONFIRMED: 409,
141
+ PLUGIN_SCHEMA_BEHIND: 409,
142
+ PLUGIN_SCHEMA_UNINSTALLED: 409,
143
+ PLUGIN_NOT_INSTALLED: 409,
144
+ PLUGIN_DISABLED: 409,
145
+ PLUGIN_UNINSTALL_UNFINISHED: 409,
146
+ PLUGIN_SCHEMA_VERSION_NOT_ADVANCED: 409,
147
+ PLUGIN_MIGRATION_DROPS_CREATED_SCHEMA: 409,
148
+ PLUGIN_MIGRATION_ADDS_UNFILLABLE_COLUMN: 409,
149
+ PLUGIN_MIGRATION_SQL_MISSING: 409,
150
+ PLUGIN_MIGRATIONS_UNAVAILABLE: 409,
151
+ DROP_OF_FOREIGN_TABLE: 409,
152
+ MIGRATION_CHECKSUM_MISMATCH: 409,
153
+ PLUGIN_MIGRATIONS_OUT_OF_ORDER: 409,
154
+ PLUGIN_MIGRATION_HISTORY_CHANGED: 409,
155
+ NEXTLY_ROUTE_COLLISION: 409,
156
+ NEXTLY_ROUTE_INVALID_PATH: 400,
157
+ NEXTLY_ROUTE_UNREACHABLE_ROOT: 400,
158
+ NEXTLY_ROUTE_INVALID_MOUNT: 400,
159
+ NEXTLY_EMAIL_TRANSPORT_UNAVAILABLE: 503,
160
+ NEXTLY_CONFIG_TOOLING_UNAVAILABLE: 503,
161
+ NEXTLY_POSTGRES_SCHEMA_MISMATCH: 500,
162
+ NEXTLY_POSTGRES_SCHEMA_UNSUPPORTED: 500
196
163
  };
197
- var CANONICAL_CODE_FOR_STATUS = [
198
- "VALIDATION_ERROR",
199
- "AUTH_REQUIRED",
200
- "FORBIDDEN",
201
- "NOT_FOUND",
202
- "CONFLICT",
203
- "PAYLOAD_TOO_LARGE",
204
- "UNSUPPORTED_MEDIA_TYPE",
205
- "RATE_LIMITED",
206
- "EXTERNAL_SERVICE_ERROR",
207
- "SERVICE_UNAVAILABLE"
208
- ];
209
- ({
210
- ...Object.fromEntries(
211
- CANONICAL_CODE_FOR_STATUS.map((code) => [NEXTLY_ERROR_STATUS[code], code])
212
- )});
213
- var DB_ERROR_MAPPING = {
214
- "unique-violation": {
215
- code: "DUPLICATE",
216
- statusCode: 409,
217
- publicMessage: "Resource already exists."
218
- },
219
- "fk-violation": {
220
- code: "VALIDATION_ERROR",
221
- statusCode: 400,
222
- publicMessage: "Referenced record does not exist."
223
- },
224
- "not-null-violation": {
225
- code: "VALIDATION_ERROR",
226
- statusCode: 400,
227
- publicMessage: "A required field is missing."
228
- },
229
- constraint: {
230
- code: "VALIDATION_ERROR",
231
- statusCode: 400,
232
- publicMessage: "The provided data violates a constraint."
233
- },
234
- deadlock: {
235
- code: "CONFLICT",
236
- statusCode: 409,
237
- publicMessage: "The operation could not be completed. Please retry."
238
- },
239
- "serialization-failure": {
240
- code: "CONFLICT",
241
- statusCode: 409,
242
- publicMessage: "The operation could not be completed. Please retry."
243
- },
244
- timeout: {
245
- code: "DATABASE_ERROR",
246
- statusCode: 500,
247
- publicMessage: "The operation timed out. Please try again."
248
- },
249
- "connection-lost": {
250
- code: "DATABASE_ERROR",
251
- statusCode: 500,
252
- publicMessage: "A temporary database error occurred. Please try again."
253
- },
254
- syntax: {
255
- code: "INTERNAL_ERROR",
256
- statusCode: 500,
257
- publicMessage: "An unexpected error occurred."
258
- },
259
- internal: {
260
- code: "INTERNAL_ERROR",
261
- statusCode: 500,
262
- publicMessage: "An unexpected error occurred."
263
- }
164
+ ({ ...Object.fromEntries([
165
+ "VALIDATION_ERROR",
166
+ "AUTH_REQUIRED",
167
+ "FORBIDDEN",
168
+ "NOT_FOUND",
169
+ "CONFLICT",
170
+ "PAYLOAD_TOO_LARGE",
171
+ "UNSUPPORTED_MEDIA_TYPE",
172
+ "RATE_LIMITED",
173
+ "EXTERNAL_SERVICE_ERROR",
174
+ "SERVICE_UNAVAILABLE"
175
+ ].map((code) => [NEXTLY_ERROR_STATUS[code], code])) });
176
+ /**
177
+ * The sentence a caller reads for a code, when the failure supplied none.
178
+ *
179
+ * Kept beside the status table because they answer the same question together:
180
+ * a code-less envelope's own `message` is NOT usable here. Those envelopes come
181
+ * from legacy converters that store a raw exception's text, so promoting it
182
+ * would put driver output, table names and internal paths on the wire -- the
183
+ * disclosure the public error shape exists to prevent (spec 13.8).
184
+ *
185
+ * Every entry is generic by design. The specific detail stays in `logContext`
186
+ * for the operator, against the same request id.
187
+ */
188
+ const GENERIC_PUBLIC_MESSAGE = {
189
+ VALIDATION_ERROR: "Validation failed.",
190
+ INVALID_INPUT: "The request could not be processed.",
191
+ AUTH_REQUIRED: "Authentication required.",
192
+ FORBIDDEN: "You don't have permission to perform this action.",
193
+ NOT_FOUND: "Not found.",
194
+ METHOD_NOT_ALLOWED: "That method is not allowed on this address.",
195
+ CONFLICT: "The resource has changed since you last loaded it. Please refresh and try again.",
196
+ DUPLICATE: "Resource already exists.",
197
+ PAYLOAD_TOO_LARGE: "The request is too large.",
198
+ UNSUPPORTED_MEDIA_TYPE: "That file type is not supported.",
199
+ RATE_LIMITED: "Too many requests. Please try again later.",
200
+ EXTERNAL_SERVICE_ERROR: "An upstream service failed.",
201
+ SERVICE_UNAVAILABLE: "The service is temporarily unavailable.",
202
+ DATABASE_BUSY: "The database is busy. Please try again shortly.",
203
+ INTERNAL_ERROR: "An unexpected error occurred."
204
+ };
205
+ /** The generic sentence for a code; the internal one for anything unlisted. */
206
+ function genericPublicMessage(code) {
207
+ return GENERIC_PUBLIC_MESSAGE[code] ?? GENERIC_PUBLIC_MESSAGE.INTERNAL_ERROR;
208
+ }
209
+ /**
210
+ * Default mapping from DbErrorKind to NextlyError contract. Used by
211
+ * `NextlyError.fromDatabaseError`. Public messages are intentionally generic
212
+ * per spec §13.8 — no DB driver text, no constraint names, no field hints.
213
+ *
214
+ * `satisfies Record<DbErrorKind, ...>` makes the mapping exhaustive at
215
+ * compile time: adding a new DbErrorKind without updating this table is a
216
+ * type error.
217
+ */
218
+ const DB_ERROR_MAPPING = {
219
+ "unique-violation": {
220
+ code: "DUPLICATE",
221
+ statusCode: 409,
222
+ publicMessage: "Resource already exists."
223
+ },
224
+ "fk-violation": {
225
+ code: "VALIDATION_ERROR",
226
+ statusCode: 400,
227
+ publicMessage: "Referenced record does not exist."
228
+ },
229
+ "not-null-violation": {
230
+ code: "VALIDATION_ERROR",
231
+ statusCode: 400,
232
+ publicMessage: "A required field is missing."
233
+ },
234
+ constraint: {
235
+ code: "VALIDATION_ERROR",
236
+ statusCode: 400,
237
+ publicMessage: "The provided data violates a constraint."
238
+ },
239
+ deadlock: {
240
+ code: "CONFLICT",
241
+ statusCode: 409,
242
+ publicMessage: "The operation could not be completed. Please retry."
243
+ },
244
+ "serialization-failure": {
245
+ code: "CONFLICT",
246
+ statusCode: 409,
247
+ publicMessage: "The operation could not be completed. Please retry."
248
+ },
249
+ busy: {
250
+ code: "DATABASE_BUSY",
251
+ statusCode: NEXTLY_ERROR_STATUS.DATABASE_BUSY,
252
+ publicMessage: genericPublicMessage("DATABASE_BUSY"),
253
+ publicData: { retryAfterSeconds: 5 }
254
+ },
255
+ timeout: {
256
+ code: "DATABASE_ERROR",
257
+ statusCode: 500,
258
+ publicMessage: "The operation timed out. Please try again."
259
+ },
260
+ "connection-lost": {
261
+ code: "DATABASE_ERROR",
262
+ statusCode: 500,
263
+ publicMessage: "A temporary database error occurred. Please try again."
264
+ },
265
+ syntax: {
266
+ code: "INTERNAL_ERROR",
267
+ statusCode: 500,
268
+ publicMessage: "An unexpected error occurred."
269
+ },
270
+ internal: {
271
+ code: "INTERNAL_ERROR",
272
+ statusCode: 500,
273
+ publicMessage: "An unexpected error occurred."
274
+ }
264
275
  };
265
- var NEXTLY_ERROR_BRAND = Symbol.for("nextly/NextlyError");
276
+ const NEXTLY_ERROR_BRAND = Symbol.for("nextly/NextlyError");
266
277
  function hasBrand(value) {
267
- if (value === null || typeof value !== "object" && typeof value !== "function") {
268
- return false;
269
- }
270
- return value[NEXTLY_ERROR_BRAND] === true;
278
+ if (value === null || typeof value !== "object" && typeof value !== "function") return false;
279
+ return value[NEXTLY_ERROR_BRAND] === true;
271
280
  }
272
- var NextlyError = class _NextlyError extends Error {
273
- code;
274
- statusCode;
275
- publicMessage;
276
- publicData;
277
- messageKey;
278
- logMessage;
279
- logContext;
280
- cause;
281
- timestamp;
282
- constructor(opts) {
283
- super(opts.publicMessage);
284
- this.name = "NextlyError";
285
- this.code = opts.code;
286
- this.publicMessage = opts.publicMessage;
287
- this.publicData = opts.publicData;
288
- this.messageKey = opts.messageKey;
289
- this.logMessage = opts.logMessage;
290
- this.logContext = opts.logContext;
291
- this.cause = opts.cause;
292
- this.timestamp = /* @__PURE__ */ new Date();
293
- this.statusCode = _NextlyError.resolveStatusCode(opts);
294
- Error.captureStackTrace?.(this, _NextlyError);
295
- }
296
- static {
297
- _NextlyError.prototype[NEXTLY_ERROR_BRAND] = true;
298
- }
299
- static resolveStatusCode(opts) {
300
- if (typeof opts.statusCode === "number") return opts.statusCode;
301
- if (opts.code in NEXTLY_ERROR_STATUS) {
302
- return NEXTLY_ERROR_STATUS[opts.code];
303
- }
304
- return 500;
305
- }
306
- /** HTTP-safe JSON. Strips logMessage / logContext / cause / stack. */
307
- toResponseJSON(requestId) {
308
- const json = {
309
- code: String(this.code),
310
- message: this.publicMessage,
311
- requestId
312
- };
313
- if (this.messageKey) json.messageKey = this.messageKey;
314
- if (this.publicData !== void 0) json.data = this.publicData;
315
- return json;
316
- }
317
- /** Operator-facing JSON for log lines. Includes everything. */
318
- toLogJSON(requestId) {
319
- return {
320
- code: this.code,
321
- statusCode: this.statusCode,
322
- publicMessage: this.publicMessage,
323
- messageKey: this.messageKey,
324
- logMessage: this.logMessage,
325
- logContext: this.logContext,
326
- cause: this.cause ? {
327
- name: this.cause.name,
328
- message: this.cause.message,
329
- stack: this.cause.stack
330
- } : void 0,
331
- timestamp: this.timestamp.toISOString(),
332
- requestId
333
- };
334
- }
335
- // ────────────────────────────────────────────────────────────────────
336
- // Static factories — the recommended throw site for every common case.
337
- // Public messages here follow the §13.8 rubric: complete sentence,
338
- // generic, no identifiers, no value echoing, no policy hints.
339
- // ────────────────────────────────────────────────────────────────────
340
- static invalidCredentials(opts) {
341
- return new _NextlyError({
342
- code: "AUTH_INVALID_CREDENTIALS",
343
- publicMessage: "Invalid email or password.",
344
- logMessage: "Login failed",
345
- logContext: opts?.logContext
346
- });
347
- }
348
- /**
349
- * The password was correct and the address is unverified. Thrown only once
350
- * the password is proven, so only someone who holds it learns the address
351
- * is unverified; every other refusal stays
352
- * {@link NextlyError.invalidCredentials}.
353
- */
354
- static emailNotVerified(opts) {
355
- return new _NextlyError({
356
- code: "EMAIL_NOT_VERIFIED",
357
- publicMessage: "Verify your email address to sign in. Check your inbox for the link.",
358
- logMessage: "Login refused: email not verified",
359
- logContext: opts?.logContext
360
- });
361
- }
362
- static authRequired(opts) {
363
- return new _NextlyError({
364
- code: "AUTH_REQUIRED",
365
- publicMessage: "Authentication required.",
366
- logContext: opts?.logContext
367
- });
368
- }
369
- /**
370
- * Distinct from `authRequired`: the caller was authenticated but the
371
- * session token expired. Clients key on the TOKEN_EXPIRED *code* to
372
- * silently refresh and retry rather than redirecting to login; the public
373
- * message stays the generic spec §13.6 string ("Authentication required.")
374
- * so the wire never reveals the session state — same as `authRequired`.
375
- */
376
- static tokenExpired(opts) {
377
- return new _NextlyError({
378
- code: "TOKEN_EXPIRED",
379
- publicMessage: "Authentication required.",
380
- logContext: opts?.logContext
381
- });
382
- }
383
- static notFound(opts) {
384
- return new _NextlyError({
385
- code: "NOT_FOUND",
386
- publicMessage: opts?.message ?? "Not found.",
387
- cause: opts?.cause,
388
- logContext: opts?.logContext
389
- });
390
- }
391
- static forbidden(opts) {
392
- return new _NextlyError({
393
- code: "FORBIDDEN",
394
- publicMessage: "You don't have permission to perform this action.",
395
- cause: opts?.cause,
396
- logContext: opts?.logContext
397
- });
398
- }
399
- /**
400
- * A cookie-authenticated write refused because its origin or CSRF token did
401
- * not check out. The public message names no detail of which check failed;
402
- * that goes to the log through `logMessage`.
403
- */
404
- static csrfFailed(opts) {
405
- return new _NextlyError({
406
- code: "CSRF_FAILED",
407
- publicMessage: "This request could not be verified. Reload the page and try again.",
408
- logMessage: opts?.logMessage,
409
- logContext: opts?.logContext
410
- });
411
- }
412
- /**
413
- * A call the caller got wrong, where naming the mistake IS the value of the
414
- * error.
415
- *
416
- * The only factory that takes its public message from the caller. The
417
- * generic messages elsewhere exist so an HTTP response cannot leak internal
418
- * detail; this one is for arguments and configuration a developer controls
419
- * and must be told about — a missing option, an unusable combination — where
420
- * `internal()` would reduce the one useful sentence to "An unexpected error
421
- * occurred." Do not pass user-supplied data through it.
422
- */
423
- static invalidInput(opts) {
424
- return new _NextlyError({
425
- code: "INVALID_INPUT",
426
- publicMessage: opts.message,
427
- logContext: opts.logContext
428
- });
429
- }
430
- static validation(opts) {
431
- return new _NextlyError({
432
- code: "VALIDATION_ERROR",
433
- publicMessage: "Validation failed.",
434
- publicData: { errors: opts.errors },
435
- cause: opts.cause,
436
- logContext: opts.logContext
437
- });
438
- }
439
- static conflict(opts) {
440
- return new _NextlyError({
441
- code: "CONFLICT",
442
- publicMessage: opts?.message ?? "The resource has changed since you last loaded it. Please refresh and try again.",
443
- cause: opts?.cause,
444
- logContext: { reason: opts?.reason, ...opts?.logContext }
445
- });
446
- }
447
- static duplicate(opts) {
448
- return new _NextlyError({
449
- code: "DUPLICATE",
450
- publicMessage: "Resource already exists.",
451
- logContext: opts?.logContext
452
- });
453
- }
454
- static rateLimited(opts) {
455
- return new _NextlyError({
456
- code: "RATE_LIMITED",
457
- publicMessage: "Too many requests. Please try again later.",
458
- publicData: opts?.retryAfterSeconds !== void 0 ? { retryAfterSeconds: opts.retryAfterSeconds } : void 0,
459
- logContext: opts?.logContext
460
- });
461
- }
462
- static internal(opts) {
463
- return new _NextlyError({
464
- code: "INTERNAL_ERROR",
465
- publicMessage: "An unexpected error occurred.",
466
- cause: opts?.cause,
467
- logContext: opts?.logContext
468
- });
469
- }
470
- // Accepts an optional `logMessage` override so callers (e.g. the health
471
- // route) can record a specific operator narrative ("Health check failed")
472
- // while the public message stays canonical per spec §13.8.5.
473
- static serviceUnavailable(opts) {
474
- return new _NextlyError({
475
- code: "SERVICE_UNAVAILABLE",
476
- publicMessage: opts?.publicMessage ?? "Service unavailable. Please try again later.",
477
- logMessage: opts?.logMessage,
478
- cause: opts?.cause,
479
- logContext: opts?.logContext
480
- });
481
- }
482
- /**
483
- * Convert a DbError (or arbitrary unknown thrown by the DB layer) to a
484
- * NextlyError with a generic public message and rich logContext. Used by
485
- * `withDbErrors` for auto-conversion (Pattern A) and by services that
486
- * catch DB errors at boundaries (Pattern B). Spec §8.2 mapping table.
487
- *
488
- * Never leaks DB driver text, constraint names, or table names into
489
- * `publicMessage`. All DB context goes into `logContext`. The original
490
- * DbError is preserved as `cause`.
491
- */
492
- static fromDatabaseError(error) {
493
- if (isDbError(error)) {
494
- const mapping = DB_ERROR_MAPPING[error.kind];
495
- const logContext = {
496
- dbKind: error.kind,
497
- dialect: error.dialect
498
- };
499
- if (error.code !== void 0) logContext.dbCode = error.code;
500
- if (error.meta !== void 0) logContext.meta = error.meta;
501
- return new _NextlyError({
502
- code: mapping.code,
503
- statusCode: mapping.statusCode,
504
- publicMessage: mapping.publicMessage,
505
- logMessage: "Database error",
506
- logContext,
507
- cause: error
508
- });
509
- }
510
- return new _NextlyError({
511
- code: "INTERNAL_ERROR",
512
- statusCode: 500,
513
- publicMessage: "An unexpected error occurred.",
514
- logMessage: "Non-DbError passed to fromDatabaseError",
515
- cause: error instanceof Error ? error : void 0,
516
- logContext: error instanceof Error ? void 0 : { value: String(error) }
517
- });
518
- }
519
- // ────────────────────────────────────────────────────────────────────
520
- // Type guards. Structural rather than `instanceof` so they survive
521
- // package-boundary mismatches (one consumer's NextlyError is a
522
- // different module instance from another's).
523
- // ────────────────────────────────────────────────────────────────────
524
- static is(err) {
525
- return hasBrand(err);
526
- }
527
- static isCode(err, code) {
528
- return hasBrand(err) && err.code === code;
529
- }
530
- static isNotFound(err) {
531
- return _NextlyError.isCode(err, "NOT_FOUND");
532
- }
533
- static isValidation(err) {
534
- return _NextlyError.isCode(err, "VALIDATION_ERROR");
535
- }
536
- static isAuthRequired(err) {
537
- return _NextlyError.isCode(err, "AUTH_REQUIRED");
538
- }
539
- static isForbidden(err) {
540
- return _NextlyError.isCode(err, "FORBIDDEN");
541
- }
542
- static isConflict(err) {
543
- return _NextlyError.isCode(err, "CONFLICT");
544
- }
545
- static isRateLimited(err) {
546
- return _NextlyError.isCode(err, "RATE_LIMITED");
547
- }
281
+ /**
282
+ * Unified error class for Nextly. Used at every throw site across services,
283
+ * direct API, auth, and plugins. Carries two distinct payloads:
284
+ *
285
+ * - Public (`code`, `publicMessage`, `publicData`, `statusCode`, `messageKey`)
286
+ * sent in HTTP responses and Server Action results.
287
+ * - Log (`logMessage`, `logContext`, `cause`, stack trace)
288
+ * written to the server logger; never serialised to the wire.
289
+ *
290
+ * Use the static factories (notFound, forbidden, validation, ...) for the
291
+ * common cases. Use the free-form constructor for plugin codes or one-off
292
+ * shapes.
293
+ */
294
+ var NextlyError = class NextlyError extends Error {
295
+ code;
296
+ statusCode;
297
+ publicMessage;
298
+ publicData;
299
+ messageKey;
300
+ logMessage;
301
+ logContext;
302
+ cause;
303
+ timestamp;
304
+ constructor(opts) {
305
+ super(opts.publicMessage);
306
+ this.name = "NextlyError";
307
+ this.code = opts.code;
308
+ this.publicMessage = opts.publicMessage;
309
+ this.publicData = opts.publicData;
310
+ this.messageKey = opts.messageKey;
311
+ this.logMessage = opts.logMessage;
312
+ this.logContext = opts.logContext;
313
+ this.cause = opts.cause;
314
+ this.timestamp = /* @__PURE__ */ new Date();
315
+ this.statusCode = NextlyError.resolveStatusCode(opts);
316
+ Error.captureStackTrace?.(this, NextlyError);
317
+ }
318
+ static {
319
+ NextlyError.prototype[NEXTLY_ERROR_BRAND] = true;
320
+ }
321
+ static resolveStatusCode(opts) {
322
+ if (typeof opts.statusCode === "number") return opts.statusCode;
323
+ if (opts.code in NEXTLY_ERROR_STATUS) return NEXTLY_ERROR_STATUS[opts.code];
324
+ return 500;
325
+ }
326
+ /** HTTP-safe JSON. Strips logMessage / logContext / cause / stack. */
327
+ toResponseJSON(requestId) {
328
+ const json = {
329
+ code: String(this.code),
330
+ message: this.publicMessage,
331
+ requestId
332
+ };
333
+ if (this.messageKey) json.messageKey = this.messageKey;
334
+ if (this.publicData !== void 0) json.data = this.publicData;
335
+ return json;
336
+ }
337
+ /** Operator-facing JSON for log lines. Includes everything. */
338
+ toLogJSON(requestId) {
339
+ return {
340
+ code: this.code,
341
+ statusCode: this.statusCode,
342
+ publicMessage: this.publicMessage,
343
+ messageKey: this.messageKey,
344
+ logMessage: this.logMessage,
345
+ logContext: this.logContext,
346
+ cause: this.cause ? {
347
+ name: this.cause.name,
348
+ message: this.cause.message,
349
+ stack: this.cause.stack
350
+ } : void 0,
351
+ timestamp: this.timestamp.toISOString(),
352
+ requestId
353
+ };
354
+ }
355
+ static invalidCredentials(opts) {
356
+ return new NextlyError({
357
+ code: "AUTH_INVALID_CREDENTIALS",
358
+ publicMessage: "Invalid email or password.",
359
+ logMessage: "Login failed",
360
+ logContext: opts?.logContext
361
+ });
362
+ }
363
+ /**
364
+ * The password was correct and the address is unverified. Thrown only once
365
+ * the password is proven, so only someone who holds it learns the address
366
+ * is unverified; every other refusal stays
367
+ * {@link NextlyError.invalidCredentials}.
368
+ */
369
+ static emailNotVerified(opts) {
370
+ return new NextlyError({
371
+ code: "EMAIL_NOT_VERIFIED",
372
+ publicMessage: "Verify your email address to sign in. Check your inbox for the link.",
373
+ logMessage: "Login refused: email not verified",
374
+ logContext: opts?.logContext
375
+ });
376
+ }
377
+ static authRequired(opts) {
378
+ return new NextlyError({
379
+ code: "AUTH_REQUIRED",
380
+ publicMessage: "Authentication required.",
381
+ logContext: opts?.logContext
382
+ });
383
+ }
384
+ /**
385
+ * Distinct from `authRequired`: the caller was authenticated but the
386
+ * session token expired. Clients key on the TOKEN_EXPIRED *code* to
387
+ * silently refresh and retry rather than redirecting to login; the public
388
+ * message stays the generic spec §13.6 string ("Authentication required.")
389
+ * so the wire never reveals the session state — same as `authRequired`.
390
+ */
391
+ static tokenExpired(opts) {
392
+ return new NextlyError({
393
+ code: "TOKEN_EXPIRED",
394
+ publicMessage: "Authentication required.",
395
+ logContext: opts?.logContext
396
+ });
397
+ }
398
+ static notFound(opts) {
399
+ return new NextlyError({
400
+ code: "NOT_FOUND",
401
+ publicMessage: opts?.message ?? "Not found.",
402
+ cause: opts?.cause,
403
+ logContext: opts?.logContext
404
+ });
405
+ }
406
+ static forbidden(opts) {
407
+ return new NextlyError({
408
+ code: "FORBIDDEN",
409
+ publicMessage: "You don't have permission to perform this action.",
410
+ cause: opts?.cause,
411
+ logContext: opts?.logContext
412
+ });
413
+ }
414
+ /**
415
+ * A collection, Single or component defined in code, which is changed by
416
+ * changing its code and not from here. Forbidden, and the message says so:
417
+ * it is a fact about the thing, not about the caller's permissions, so it
418
+ * names no permission and no policy. The lock's detail goes to the log
419
+ * through `logContext`.
420
+ */
421
+ static definedInCode(opts) {
422
+ return new NextlyError({
423
+ code: "FORBIDDEN",
424
+ publicMessage: `This ${opts.thing} is defined in code, so it can't be ${opts.change === "change" ? "changed" : "deleted"} here.`,
425
+ logContext: opts.logContext
426
+ });
427
+ }
428
+ /**
429
+ * An autosave where the collection or Single does not autosave: its owner
430
+ * switched autosave off, or it keeps no drafts to autosave into. Forbidden,
431
+ * and the message says so, since it is a setting and not a permission.
432
+ */
433
+ static autosaveOff(opts) {
434
+ return new NextlyError({
435
+ code: "FORBIDDEN",
436
+ publicMessage: `Autosave is turned off for this ${opts.scopeKind === "single" ? "Single" : "collection"}.`,
437
+ logContext: opts.logContext
438
+ });
439
+ }
440
+ /**
441
+ * An API key refused because its role allows more than the person creating
442
+ * it may do. The sentence is FORBIDDEN's and names no permission; which one
443
+ * exceeded goes to the log through `logContext`. The code is its own, so a
444
+ * client can tell "choose a smaller role" from plain FORBIDDEN.
445
+ */
446
+ static apiKeyRoleAboveCreator(opts) {
447
+ return new NextlyError({
448
+ code: "API_KEY_ROLE_ABOVE_CREATOR",
449
+ publicMessage: genericPublicMessage("FORBIDDEN"),
450
+ logContext: opts?.logContext
451
+ });
452
+ }
453
+ /**
454
+ * A cookie-authenticated write refused because its origin or CSRF token did
455
+ * not check out. The public message names no detail of which check failed;
456
+ * that goes to the log through `logMessage`.
457
+ */
458
+ static csrfFailed(opts) {
459
+ return new NextlyError({
460
+ code: "CSRF_FAILED",
461
+ publicMessage: "This request could not be verified. Reload the page and try again.",
462
+ logMessage: opts?.logMessage,
463
+ logContext: opts?.logContext
464
+ });
465
+ }
466
+ /**
467
+ * A call the caller got wrong, where naming the mistake IS the value of the
468
+ * error.
469
+ *
470
+ * The only factory that takes its public message from the caller. The
471
+ * generic messages elsewhere exist so an HTTP response cannot leak internal
472
+ * detail; this one is for arguments and configuration a developer controls
473
+ * and must be told about — a missing option, an unusable combination — where
474
+ * `internal()` would reduce the one useful sentence to "An unexpected error
475
+ * occurred." Do not pass user-supplied data through it.
476
+ */
477
+ static invalidInput(opts) {
478
+ return new NextlyError({
479
+ code: "INVALID_INPUT",
480
+ publicMessage: opts.message,
481
+ logContext: opts.logContext
482
+ });
483
+ }
484
+ static validation(opts) {
485
+ return new NextlyError({
486
+ code: "VALIDATION_ERROR",
487
+ publicMessage: "Validation failed.",
488
+ publicData: { errors: opts.errors },
489
+ cause: opts.cause,
490
+ logContext: opts.logContext
491
+ });
492
+ }
493
+ static conflict(opts) {
494
+ return new NextlyError({
495
+ code: "CONFLICT",
496
+ publicMessage: opts?.message ?? "The resource has changed since you last loaded it. Please refresh and try again.",
497
+ publicData: opts?.data,
498
+ cause: opts?.cause,
499
+ logContext: {
500
+ reason: opts?.reason,
501
+ ...opts?.logContext
502
+ }
503
+ });
504
+ }
505
+ static duplicate(opts) {
506
+ return new NextlyError({
507
+ code: "DUPLICATE",
508
+ publicMessage: "Resource already exists.",
509
+ logContext: opts?.logContext
510
+ });
511
+ }
512
+ static rateLimited(opts) {
513
+ return new NextlyError({
514
+ code: "RATE_LIMITED",
515
+ publicMessage: "Too many requests. Please try again later.",
516
+ publicData: opts?.retryAfterSeconds !== void 0 ? { retryAfterSeconds: opts.retryAfterSeconds } : void 0,
517
+ logContext: opts?.logContext
518
+ });
519
+ }
520
+ /**
521
+ * A request that waited `pool.connectionTimeoutMs` for a database
522
+ * connection and was given none. The statement or transaction that waited
523
+ * never ran; work committed before it stays committed. The same error
524
+ * `fromDatabaseError` gives a busy DbError, from the same table row.
525
+ */
526
+ static databaseBusy(opts) {
527
+ const busy = DB_ERROR_MAPPING.busy;
528
+ return new NextlyError({
529
+ code: busy.code,
530
+ statusCode: busy.statusCode,
531
+ publicMessage: busy.publicMessage,
532
+ publicData: busy.publicData,
533
+ cause: opts?.cause,
534
+ logContext: opts?.logContext
535
+ });
536
+ }
537
+ /**
538
+ * What a request boundary answers with for a thrown value that is not a
539
+ * NextlyError: "database busy" when the request waited out its bound for a
540
+ * connection, which is retryable and no fault of the server's code, and an
541
+ * internal error for anything else.
542
+ *
543
+ * The busy case has to be read here because it usually arrives raw:
544
+ * `withDbErrors` converts only DbErrors, so a driver's error passes through
545
+ * services unconverted to the boundary that answers the request.
546
+ */
547
+ static fromUnexpected(error) {
548
+ return NextlyError.busyOr(error, () => NextlyError.internal({ cause: error instanceof Error ? error : void 0 }));
549
+ }
550
+ /**
551
+ * "Database busy" when `error` is a request that waited out its bound for
552
+ * a connection, and `otherwise()` for anything else.
553
+ *
554
+ * For a boundary that answers an unexpected failure with an error of its
555
+ * own choosing rather than an internal one (a 503 for a flow that must not
556
+ * answer on incomplete data), so that a busy database still answers there
557
+ * as it does everywhere else. `fromUnexpected` is this rule with the
558
+ * internal error as its fallback.
559
+ */
560
+ static busyOr(error, otherwise) {
561
+ if (!isDatabaseBusy(error)) return otherwise();
562
+ return NextlyError.databaseBusy({ cause: error instanceof Error ? error : void 0 });
563
+ }
564
+ static internal(opts) {
565
+ return new NextlyError({
566
+ code: "INTERNAL_ERROR",
567
+ publicMessage: "An unexpected error occurred.",
568
+ cause: opts?.cause,
569
+ logContext: opts?.logContext
570
+ });
571
+ }
572
+ static serviceUnavailable(opts) {
573
+ return new NextlyError({
574
+ code: "SERVICE_UNAVAILABLE",
575
+ publicMessage: opts?.publicMessage ?? "Service unavailable. Please try again later.",
576
+ logMessage: opts?.logMessage,
577
+ cause: opts?.cause,
578
+ logContext: opts?.logContext
579
+ });
580
+ }
581
+ /**
582
+ * Convert a DbError (or arbitrary unknown thrown by the DB layer) to a
583
+ * NextlyError with a generic public message and rich logContext. Used by
584
+ * `withDbErrors` for auto-conversion (Pattern A) and by services that
585
+ * catch DB errors at boundaries (Pattern B). Spec §8.2 mapping table.
586
+ *
587
+ * Never leaks DB driver text, constraint names, or table names into
588
+ * `publicMessage`. All DB context goes into `logContext`. The original
589
+ * DbError is preserved as `cause`.
590
+ */
591
+ static fromDatabaseError(error) {
592
+ if (isDbError(error)) {
593
+ const mapping = DB_ERROR_MAPPING[error.kind];
594
+ const logContext = {
595
+ dbKind: error.kind,
596
+ dialect: error.dialect
597
+ };
598
+ if (error.code !== void 0) logContext.dbCode = error.code;
599
+ if (error.meta !== void 0) logContext.meta = error.meta;
600
+ return new NextlyError({
601
+ code: mapping.code,
602
+ statusCode: mapping.statusCode,
603
+ publicMessage: mapping.publicMessage,
604
+ publicData: "publicData" in mapping ? mapping.publicData : void 0,
605
+ logMessage: "Database error",
606
+ logContext,
607
+ cause: error
608
+ });
609
+ }
610
+ return new NextlyError({
611
+ code: "INTERNAL_ERROR",
612
+ statusCode: 500,
613
+ publicMessage: "An unexpected error occurred.",
614
+ logMessage: "Non-DbError passed to fromDatabaseError",
615
+ cause: error instanceof Error ? error : void 0,
616
+ logContext: error instanceof Error ? void 0 : { value: String(error) }
617
+ });
618
+ }
619
+ static is(err) {
620
+ return hasBrand(err);
621
+ }
622
+ static isCode(err, code) {
623
+ return hasBrand(err) && err.code === code;
624
+ }
625
+ static isNotFound(err) {
626
+ return NextlyError.isCode(err, "NOT_FOUND");
627
+ }
628
+ static isValidation(err) {
629
+ return NextlyError.isCode(err, "VALIDATION_ERROR");
630
+ }
631
+ static isAuthRequired(err) {
632
+ return NextlyError.isCode(err, "AUTH_REQUIRED");
633
+ }
634
+ static isForbidden(err) {
635
+ return NextlyError.isCode(err, "FORBIDDEN");
636
+ }
637
+ static isConflict(err) {
638
+ return NextlyError.isCode(err, "CONFLICT");
639
+ }
640
+ static isRateLimited(err) {
641
+ return NextlyError.isCode(err, "RATE_LIMITED");
642
+ }
548
643
  };
549
-
550
- // ../nextly/dist/chunk-V6N5XUUA.mjs
644
+ // ../nextly/dist/storage/read-errors.mjs
645
+ /**
646
+ * The one way the storage layer says a read exceeded the caller's cap.
647
+ *
648
+ * `StorageReadOptions.maxBytes` is part of the adapter contract, so what happens
649
+ * when it is exceeded belongs to the contract too. Without this each backend
650
+ * refuses in its own vocabulary — the URL-addressed ones through a fetch error
651
+ * carrying a `reason`, S3 through whatever its own code threw — and a caller
652
+ * wanting to tell "too large" from "could not read" has to know which adapter it
653
+ * is talking to. That is the thing an adapter contract exists to stop.
654
+ *
655
+ * Distinct from a generic internal failure because callers ACT on the
656
+ * difference. The email attachment path answers an over-cap read with
657
+ * `ATTACHMENT_SIZE_EXCEEDED`, which tells an author to attach something smaller;
658
+ * a storage failure tells them nothing they can act on. Collapsing the two turns
659
+ * a fixable refusal into an opaque error, which is the same conflation this
660
+ * contract already draws between a missing key and an unreachable store.
661
+ *
662
+ * @module storage/read-errors
663
+ */
664
+ /**
665
+ * A read refused because the object is larger than the caller allowed.
666
+ *
667
+ * Carries the numbers rather than only a message, so a caller can say what the
668
+ * limit was without parsing prose — and so the message itself stays free of the
669
+ * key, which should not travel to whoever asked for the file.
670
+ */
551
671
  var StorageReadTooLargeError = class extends NextlyError {
552
- constructor(path, maxBytes, size) {
553
- super({
554
- code: "STORAGE_READ_TOO_LARGE",
555
- publicMessage: "The stored file is larger than the limit for this read.",
556
- logContext: {
557
- path,
558
- maxBytes,
559
- ...size === void 0 ? {} : { size }
560
- }
561
- });
562
- this.path = path;
563
- this.maxBytes = maxBytes;
564
- this.size = size;
565
- }
672
+ path;
673
+ maxBytes;
674
+ size;
675
+ constructor(path, maxBytes, size) {
676
+ super({
677
+ code: "STORAGE_READ_TOO_LARGE",
678
+ publicMessage: "The stored file is larger than the limit for this read.",
679
+ logContext: {
680
+ path,
681
+ maxBytes,
682
+ ...size === void 0 ? {} : { size }
683
+ }
684
+ });
685
+ this.path = path;
686
+ this.maxBytes = maxBytes;
687
+ this.size = size;
688
+ }
566
689
  };
567
-
568
- // ../nextly/dist/chunk-FKT4HLI3.mjs
569
- var DEFAULT_MAX_RESPONSE_BYTES = 10 * 1024 * 1024;
570
- var DEFAULT_TIMEOUT_MS = 3e4;
571
- var DEFAULT_READ_TIMEOUT_MS = DEFAULT_TIMEOUT_MS;
572
- var DEFAULT_READ_MAX_BYTES = DEFAULT_MAX_RESPONSE_BYTES;
690
+ /**
691
+ * The bounds a read actually runs under, defaults filled in.
692
+ *
693
+ * ONE place, because every adapter needs the same answer and the ones that
694
+ * derived it themselves diverged: the URL-backed pair inherited `safeFetch`'s
695
+ * cap and deadline for free, while the local and S3 adapters — which never
696
+ * touch `safeFetch` — applied NO bound at all when the caller named none.
697
+ * `StorageReadOptions` promises the default either way, and a production caller
698
+ * reading media without options got it from two of four backends.
699
+ *
700
+ * Filling the defaults here rather than per adapter is what makes the promise
701
+ * true by construction rather than by four implementations agreeing.
702
+ */
573
703
  function resolveReadBounds(options) {
574
- return {
575
- maxBytes: options?.maxBytes ?? DEFAULT_READ_MAX_BYTES,
576
- timeoutMs: options?.timeoutMs ?? DEFAULT_READ_TIMEOUT_MS
577
- };
704
+ return {
705
+ maxBytes: options?.maxBytes ?? 10485760,
706
+ timeoutMs: options?.timeoutMs ?? 3e4
707
+ };
578
708
  }
579
-
580
709
  // src/adapter.ts
710
+ /**
711
+ * S3 Storage Adapter
712
+ *
713
+ * Stores files on AWS S3 or S3-compatible services (Cloudflare R2, MinIO, DigitalOcean Spaces).
714
+ * Uses AWS SDK v3 with automatic multipart upload for large files (>5MB).
715
+ *
716
+ * Features:
717
+ * - Automatic multipart upload via @aws-sdk/lib-storage
718
+ * - Pre-signed URL generation for client-side uploads
719
+ * - Signed URL generation for private file access
720
+ * - Cloudflare R2 support (S3-compatible API)
721
+ * - Custom endpoint support (MinIO, DigitalOcean Spaces)
722
+ * - CDN URL override support
723
+ * - File metadata retrieval
724
+ *
725
+ * @example AWS S3
726
+ * ```typescript
727
+ * const adapter = new S3StorageAdapter({
728
+ * bucket: 'my-media-bucket',
729
+ * region: 'us-east-1',
730
+ * accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
731
+ * secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
732
+ * collections: { media: true }
733
+ * });
734
+ * ```
735
+ *
736
+ * @example Cloudflare R2
737
+ * ```typescript
738
+ * const adapter = new S3StorageAdapter({
739
+ * bucket: 'my-media',
740
+ * region: 'auto',
741
+ * accessKeyId: process.env.R2_ACCESS_KEY_ID!,
742
+ * secretAccessKey: process.env.R2_SECRET_ACCESS_KEY!,
743
+ * endpoint: `https://${accountId}.r2.cloudflarestorage.com`,
744
+ * publicUrl: 'https://pub-abc.r2.dev',
745
+ * collections: { media: true }
746
+ * });
747
+ * ```
748
+ *
749
+ * @example MinIO (self-hosted)
750
+ * ```typescript
751
+ * const adapter = new S3StorageAdapter({
752
+ * bucket: 'my-bucket',
753
+ * region: 'us-east-1',
754
+ * accessKeyId: process.env.MINIO_ACCESS_KEY!,
755
+ * secretAccessKey: process.env.MINIO_SECRET_KEY!,
756
+ * endpoint: 'http://localhost:9000',
757
+ * forcePathStyle: true,
758
+ * collections: { media: true }
759
+ * });
760
+ * ```
761
+ */
762
+ /**
763
+ * S3 Storage Adapter
764
+ *
765
+ * Implements the IStorageAdapter interface for AWS S3 and S3-compatible services.
766
+ * Provides full support for uploads, downloads, signed URLs, and client-side uploads.
767
+ */
768
+ /**
769
+ * The SDK request options carrying the caller's deadline, or none.
770
+ *
771
+ * A free function rather than a branch inside `read`, because it is the only
772
+ * part of that method with nothing to do with telling an absent key apart from
773
+ * an unreachable bucket — which is the distinction a reader has to hold in
774
+ * their head there.
775
+ *
776
+ * `AbortSignal.timeout` rather than a controller and a `setTimeout`: it needs no
777
+ * clearing, so it cannot leak a timer when the read resolves first. The signal
778
+ * covers the BODY as well as the request, because the SDK threads it through
779
+ * the response stream — and a backend that answers headers promptly and then
780
+ * stalls mid-transfer is exactly the case a request-only deadline misses.
781
+ */
581
782
  function abortAfter(options) {
582
- return {
583
- abortSignal: AbortSignal.timeout(resolveReadBounds(options).timeoutMs)
584
- };
783
+ return { abortSignal: AbortSignal.timeout(resolveReadBounds(options).timeoutMs) };
585
784
  }
586
785
  var S3StorageAdapter = class {
587
- /**
588
- * Create a new S3 storage adapter.
589
- *
590
- * @param config - S3 storage configuration
591
- * @throws Error if bucket or region is not provided
592
- */
593
- constructor(config) {
594
- this.config = config;
595
- if (!config.bucket) {
596
- throw new Error("@nextly/storage-s3: bucket is required");
597
- }
598
- if (!config.region) {
599
- throw new Error("@nextly/storage-s3: region is required");
600
- }
601
- this.isR2 = config.endpoint?.includes("r2.cloudflarestorage.com") ?? false;
602
- this.resolvedConfig = {
603
- bucket: config.bucket,
604
- region: config.region,
605
- endpoint: config.endpoint,
606
- forcePathStyle: config.forcePathStyle ?? false,
607
- acl: config.acl ?? "private",
608
- publicUrl: config.publicUrl,
609
- cacheControl: config.cacheControl ?? "public, max-age=31536000",
610
- contentDisposition: config.contentDisposition,
611
- signedUrlExpiresIn: config.signedUrlExpiresIn ?? 3600
612
- };
613
- const credentials = this.buildCredentials();
614
- this.client = new S3Client({
615
- region: config.region,
616
- endpoint: config.endpoint,
617
- credentials,
618
- forcePathStyle: this.resolvedConfig.forcePathStyle,
619
- ...config.config
620
- });
621
- }
622
- client;
623
- resolvedConfig;
624
- isR2;
625
- /**
626
- * Build AWS credentials from config.
627
- * Supports explicit credentials or falls back to SDK default chain.
628
- */
629
- buildCredentials() {
630
- if (this.config.accessKeyId && this.config.secretAccessKey) {
631
- return {
632
- accessKeyId: this.config.accessKeyId,
633
- secretAccessKey: this.config.secretAccessKey
634
- };
635
- }
636
- if (this.config.config?.credentials) {
637
- return void 0;
638
- }
639
- return void 0;
640
- }
641
- // ============================================================
642
- // Core IStorageAdapter Methods
643
- // ============================================================
644
- /**
645
- * Upload file to S3.
646
- *
647
- * Uses AWS SDK v3's Upload class from @aws-sdk/lib-storage which:
648
- * - Automatically handles multipart upload for large files (>5MB)
649
- * - Provides progress tracking capability
650
- * - Includes retry logic
651
- * - Optimizes upload performance
652
- *
653
- * @param buffer - File content as Buffer
654
- * @param options - Upload options (filename, mimeType, folder, collection)
655
- * @returns Upload result with URL and storage path
656
- */
657
- async upload(buffer, options) {
658
- const key = this.generateKey(options.filename, options.folder);
659
- const uploadParams = {
660
- Bucket: this.resolvedConfig.bucket,
661
- Key: key,
662
- Body: buffer,
663
- ContentType: options.contentType || options.mimeType,
664
- CacheControl: this.resolvedConfig.cacheControl
665
- };
666
- if (!this.isR2) {
667
- uploadParams.ACL = this.resolvedConfig.acl;
668
- }
669
- const disposition = options.contentDisposition ?? this.resolvedConfig.contentDisposition;
670
- if (disposition) {
671
- const filename = this.sanitizeFilename(options.filename);
672
- uploadParams.ContentDisposition = disposition === "attachment" ? `attachment; filename="${filename}"` : "inline";
673
- }
674
- uploadParams.Metadata = {
675
- "original-filename": options.filename
676
- };
677
- const upload = new Upload({
678
- client: this.client,
679
- params: uploadParams
680
- });
681
- await upload.done();
682
- return {
683
- url: this.getPublicUrl(key),
684
- path: key
685
- };
686
- }
687
- /**
688
- * Delete file from S3.
689
- *
690
- * @param filePath - Storage path/key to delete
691
- */
692
- async delete(filePath) {
693
- const command = new DeleteObjectCommand({
694
- Bucket: this.resolvedConfig.bucket,
695
- Key: filePath
696
- });
697
- await this.client.send(command);
698
- }
699
- /**
700
- * Bulk delete files from S3 using a single API call per 1000 keys.
701
- *
702
- * Uses AWS SDK v3's DeleteObjectsCommand which supports up to 1000 keys per
703
- * request. Automatically batches larger arrays and collects per-key results.
704
- *
705
- * @param filePaths - Storage paths/keys to delete
706
- * @returns Object with arrays of successful and failed deletions
707
- */
708
- async bulkDelete(filePaths) {
709
- const successful = [];
710
- const failed = [];
711
- const maxBatchSize = 1e3;
712
- for (let i = 0; i < filePaths.length; i += maxBatchSize) {
713
- const batch = filePaths.slice(i, i + maxBatchSize);
714
- const command = new DeleteObjectsCommand({
715
- Bucket: this.resolvedConfig.bucket,
716
- Delete: {
717
- Objects: batch.map((key) => ({ Key: key })),
718
- Quiet: false
719
- }
720
- });
721
- const response = await this.client.send(command);
722
- if (response.Errors && response.Errors.length > 0) {
723
- for (const err of response.Errors) {
724
- if (err.Key) {
725
- failed.push({
726
- filePath: err.Key,
727
- error: err.Message ?? "Unknown S3 delete error"
728
- });
729
- }
730
- }
731
- }
732
- if (response.Deleted) {
733
- for (const del of response.Deleted) {
734
- if (del.Key) {
735
- successful.push(del.Key);
736
- }
737
- }
738
- }
739
- }
740
- return { successful, failed };
741
- }
742
- /**
743
- * Check if file exists in S3.
744
- *
745
- * Uses HeadObject command which is more efficient than GetObject
746
- * for existence checks (doesn't download the file).
747
- *
748
- * @param filePath - Storage path/key to check
749
- * @returns true if file exists, false otherwise
750
- */
751
- async exists(filePath) {
752
- try {
753
- const command = new HeadObjectCommand({
754
- Bucket: this.resolvedConfig.bucket,
755
- Key: filePath
756
- });
757
- await this.client.send(command);
758
- return true;
759
- } catch (error) {
760
- if (this.isNotFoundError(error)) {
761
- return false;
762
- }
763
- throw error;
764
- }
765
- }
766
- /**
767
- * Get public URL for S3 file.
768
- *
769
- * Priority order:
770
- * 1. Custom publicUrl (CDN or custom domain) if configured
771
- * 2. Standard S3 URL based on region and bucket
772
- *
773
- * For R2: Requires publicUrl configuration (R2 has no default public URLs).
774
- *
775
- * @param filePath - Storage path/key
776
- * @returns Public URL to access the file
777
- * @throws Error if R2 is used without publicUrl configuration
778
- */
779
- getPublicUrl(filePath) {
780
- if (this.resolvedConfig.publicUrl) {
781
- const baseUrl = this.resolvedConfig.publicUrl.replace(/\/$/, "");
782
- return `${baseUrl}/${filePath}`;
783
- }
784
- if (this.isR2) {
785
- throw new Error(
786
- "@nextly/storage-s3: Cloudflare R2 requires publicUrl configuration.\n\nR2 does not have default public URLs like AWS S3. Configure one of:\n1. Public bucket URL: publicUrl: 'https://pub-xxx.r2.dev'\n2. Custom domain: publicUrl: 'https://cdn.example.com'\n\nSet up public access in the Cloudflare R2 dashboard."
787
- );
788
- }
789
- return `https://${this.resolvedConfig.bucket}.s3.${this.resolvedConfig.region}.amazonaws.com/${filePath}`;
790
- }
791
- /**
792
- * Get storage type identifier.
793
- *
794
- * Returns "s3" for all S3-compatible services (AWS S3, R2, MinIO, etc.)
795
- * as they all use the S3 API.
796
- */
797
- getType() {
798
- return "s3";
799
- }
800
- // ============================================================
801
- // Optional IStorageAdapter Methods
802
- // ============================================================
803
- /**
804
- * Get adapter info including capabilities.
805
- *
806
- * @returns Adapter info with type, name, and capability flags
807
- */
808
- getInfo() {
809
- return {
810
- type: "s3",
811
- name: "S3StorageAdapter",
812
- supportsSignedUrls: true,
813
- supportsClientUploads: true
814
- };
815
- }
816
- /**
817
- * Get file metadata from S3.
818
- *
819
- * Retrieves file information including size, content type, and timestamps
820
- * using the HeadObject command.
821
- *
822
- * @param filePath - Storage path/key
823
- * @returns File metadata or null if file not found
824
- */
825
- async getMetadata(filePath) {
826
- try {
827
- const command = new HeadObjectCommand({
828
- Bucket: this.resolvedConfig.bucket,
829
- Key: filePath
830
- });
831
- const response = await this.client.send(command);
832
- const filename = filePath.split("/").pop() || filePath;
833
- return {
834
- id: filePath,
835
- filename,
836
- originalFilename: response.Metadata?.["original-filename"] || filename,
837
- mimeType: response.ContentType || "application/octet-stream",
838
- size: response.ContentLength || 0,
839
- url: this.getPublicUrl(filePath),
840
- createdAt: response.LastModified?.toISOString() || (/* @__PURE__ */ new Date()).toISOString()
841
- };
842
- } catch (error) {
843
- if (this.isNotFoundError(error)) {
844
- return null;
845
- }
846
- throw error;
847
- }
848
- }
849
- /**
850
- * Read a stored object back as bytes, or `null` when it is not there.
851
- *
852
- * The contract declares this OPTIONAL and, until now, no adapter supplied
853
- * it — so a caller reaching for `adapter.read` got `undefined` and fell
854
- * through whatever branch followed. An optional member nothing implements is
855
- * a contract that reads as a capability and behaves as an absence.
856
- *
857
- * BUFFERS rather than streams, because that is the declared return type and
858
- * widening it here would make this adapter answer a different question from
859
- * its siblings. That bounds what it should be used for: an asset the server
860
- * must serve from its own origin — a font file, a small document — rather
861
- * than arbitrarily large media, which belongs behind {@link getSignedUrl} or
862
- * a public URL. A streaming variant is a separate contract member, not a
863
- * quiet change to this one.
864
- *
865
- * `null` for a missing key rather than a throw, matching
866
- * {@link getMetadata}: absence is an ordinary answer about the bucket, while
867
- * a credential or network failure is not, so only the first is folded into
868
- * the return value.
869
- *
870
- * @param filePath - Storage path/key
871
- * @returns The object's bytes, or `null` when no such key exists
872
- */
873
- async read(filePath, options) {
874
- try {
875
- const command = new GetObjectCommand({
876
- Bucket: this.resolvedConfig.bucket,
877
- Key: filePath
878
- });
879
- const response = await this.client.send(command, abortAfter(options));
880
- if (response.Body === void 0) return Buffer.alloc(0);
881
- const cap = resolveReadBounds(options).maxBytes;
882
- this.refuseOverCap(filePath, response.ContentLength, cap);
883
- return await this.readCapped(filePath, response.Body, cap);
884
- } catch (error) {
885
- if (error instanceof Error && error.name === "NoSuchBucket") throw error;
886
- if (this.isNotFoundError(error)) {
887
- return null;
888
- }
889
- throw error;
890
- }
891
- }
892
- /**
893
- * Generate signed URL for temporary private file access.
894
- *
895
- * Creates a pre-signed GetObject URL that grants temporary read access
896
- * to private files. Useful for serving files from private buckets.
897
- *
898
- * @param filePath - Storage path/key
899
- * @param expiresIn - URL validity duration in seconds (default: 3600)
900
- * @returns Pre-signed URL for downloading the file
901
- */
902
- async getSignedUrl(filePath, expiresIn) {
903
- const command = new GetObjectCommand({
904
- Bucket: this.resolvedConfig.bucket,
905
- Key: filePath
906
- });
907
- return getSignedUrl(this.client, command, {
908
- expiresIn: expiresIn ?? this.resolvedConfig.signedUrlExpiresIn
909
- });
910
- }
911
- /**
912
- * Generate pre-signed URL for client-side uploads.
913
- *
914
- * Creates a pre-signed PutObject URL that allows direct uploads from
915
- * the browser to S3, bypassing server-side upload limits (e.g., Vercel's 4.5MB).
916
- *
917
- * @param key - Storage path/key for the upload
918
- * @param mimeType - MIME type of the file being uploaded
919
- * @param expiresIn - URL validity duration in seconds (default: 3600)
920
- * @returns Client upload data with URL, method, and headers
921
- */
922
- async getPresignedUploadUrl(key, mimeType, expiresIn) {
923
- const expiration = expiresIn ?? this.resolvedConfig.signedUrlExpiresIn;
924
- const commandParams = {
925
- Bucket: this.resolvedConfig.bucket,
926
- Key: key,
927
- ContentType: mimeType,
928
- CacheControl: this.resolvedConfig.cacheControl
929
- };
930
- if (!this.isR2) {
931
- commandParams.ACL = this.resolvedConfig.acl;
932
- }
933
- const command = new PutObjectCommand(commandParams);
934
- const uploadUrl = await getSignedUrl(this.client, command, {
935
- expiresIn: expiration
936
- });
937
- return {
938
- uploadUrl,
939
- path: key,
940
- method: "PUT",
941
- headers: {
942
- "Content-Type": mimeType
943
- },
944
- expiresAt: new Date(Date.now() + expiration * 1e3)
945
- };
946
- }
947
- // ============================================================
948
- // Helper Methods
949
- // ============================================================
950
- /**
951
- * Generate a unique storage key with date-based prefix.
952
- *
953
- * Creates keys in format: {folder}/{year}/{month}/{uuid}-{sanitized-filename}
954
- *
955
- * @param filename - Original filename (will be sanitized)
956
- * @param folder - Optional folder/prefix for organizing uploads
957
- * @returns Generated storage key
958
- */
959
- generateKey(filename, folder) {
960
- const sanitized = this.sanitizeFilename(filename);
961
- const uuid = crypto.randomUUID();
962
- const date = /* @__PURE__ */ new Date();
963
- const year = date.getFullYear();
964
- const month = String(date.getMonth() + 1).padStart(2, "0");
965
- const prefix = folder ? `${folder}/${year}/${month}` : `${year}/${month}`;
966
- return `${prefix}/${uuid}-${sanitized}`;
967
- }
968
- /**
969
- * Sanitize filename to prevent directory traversal and S3 key issues.
970
- *
971
- * @param filename - Original filename
972
- * @returns Sanitized filename safe for S3 keys
973
- */
974
- sanitizeFilename(filename) {
975
- const basename = filename.split(/[/\\]/).pop() || filename;
976
- return basename.replace(/[^a-zA-Z0-9._-]/g, "-");
977
- }
978
- /**
979
- * Check if an error is a "not found" error from S3.
980
- *
981
- * @param error - Error to check
982
- * @returns true if error indicates file not found
983
- */
984
- /**
985
- * The object's bytes, refusing once more than `cap` have actually arrived.
986
- *
987
- * `ContentLength` is OPTIONAL in the SDK's response type, and this adapter
988
- * explicitly supports MinIO, R2 and other compatible services — any of which
989
- * may omit it or report it wrongly. A preflight check against metadata is
990
- * therefore a courtesy that fails OPEN: trusting it alone leaves the cap
991
- * unenforced exactly where an unusual backend is involved, which is where a
992
- * caller most needs it.
993
- *
994
- * Counted while consuming, so an oversized body is abandoned partway rather
995
- * than after it has all been buffered — the cap exists to bound memory, and
996
- * one applied after `transformToByteArray` has already spent it.
997
- *
998
- * Falls back to buffering when the body is not async-iterable, which the SDK
999
- * types permit. Stated rather than hidden: on that path the cap bounds what a
1000
- * caller RECEIVES rather than what the process allocates.
1001
- */
1002
- async readCapped(filePath, body, cap) {
1003
- const iterable = body;
1004
- if (typeof iterable[Symbol.asyncIterator] !== "function") {
1005
- const whole = Buffer.from(await body.transformToByteArray());
1006
- if (whole.byteLength > cap) {
1007
- throw new StorageReadTooLargeError(filePath, cap, whole.byteLength);
1008
- }
1009
- return whole;
1010
- }
1011
- const chunks = [];
1012
- let received = 0;
1013
- for await (const chunk of body) {
1014
- received += chunk.byteLength;
1015
- if (received > cap) {
1016
- throw new StorageReadTooLargeError(filePath, cap, received);
1017
- }
1018
- chunks.push(Buffer.from(chunk));
1019
- }
1020
- return Buffer.concat(chunks);
1021
- }
1022
- /**
1023
- * Refuse a read whose object is already known to exceed the caller's cap.
1024
- *
1025
- * Its own method rather than three conditions inside `read`, because the
1026
- * decision has nothing to do with the surrounding error handling and reads
1027
- * as noise there — and because `read`'s branching is the part a reviewer has
1028
- * to hold in their head to check the absent-versus-unavailable distinction.
1029
- *
1030
- * Both `undefined` cases mean "no opinion" and pass: a caller that named no
1031
- * cap has none, and a store that reported no length gives nothing to compare.
1032
- * The second is deliberately permissive — refusing an unmeasured object would
1033
- * reject valid reads whenever S3 omits the header.
1034
- */
1035
- refuseOverCap(filePath, declared, cap) {
1036
- if (cap === void 0 || declared === void 0 || declared <= cap) return;
1037
- throw new StorageReadTooLargeError(filePath, cap, declared);
1038
- }
1039
- isNotFoundError(error) {
1040
- if (error && typeof error === "object") {
1041
- const e = error;
1042
- return e.name === "NotFound" || e.$metadata?.httpStatusCode === 404;
1043
- }
1044
- return false;
1045
- }
1046
- // ============================================================
1047
- // Public Accessors
1048
- // ============================================================
1049
- /**
1050
- * Get the S3 client instance.
1051
- * Useful for advanced operations not covered by the adapter interface.
1052
- */
1053
- getClient() {
1054
- return this.client;
1055
- }
1056
- /**
1057
- * Get the bucket name.
1058
- */
1059
- getBucket() {
1060
- return this.resolvedConfig.bucket;
1061
- }
1062
- /**
1063
- * Get the AWS region.
1064
- */
1065
- getRegion() {
1066
- return this.resolvedConfig.region;
1067
- }
1068
- /**
1069
- * Check if this adapter is configured for Cloudflare R2.
1070
- */
1071
- isCloudflareR2() {
1072
- return this.isR2;
1073
- }
786
+ config;
787
+ client;
788
+ resolvedConfig;
789
+ isR2;
790
+ /**
791
+ * Create a new S3 storage adapter.
792
+ *
793
+ * @param config - S3 storage configuration
794
+ * @throws Error if bucket or region is not provided
795
+ */
796
+ constructor(config) {
797
+ this.config = config;
798
+ if (!config.bucket) throw new Error("@nextly/storage-s3: bucket is required");
799
+ if (!config.region) throw new Error("@nextly/storage-s3: region is required");
800
+ this.isR2 = config.endpoint?.includes("r2.cloudflarestorage.com") ?? false;
801
+ this.resolvedConfig = {
802
+ bucket: config.bucket,
803
+ region: config.region,
804
+ endpoint: config.endpoint,
805
+ forcePathStyle: config.forcePathStyle ?? false,
806
+ acl: config.acl ?? "private",
807
+ publicUrl: config.publicUrl,
808
+ cacheControl: config.cacheControl ?? "public, max-age=31536000",
809
+ contentDisposition: config.contentDisposition,
810
+ signedUrlExpiresIn: config.signedUrlExpiresIn ?? 3600
811
+ };
812
+ const credentials = this.buildCredentials();
813
+ this.client = new S3Client({
814
+ region: config.region,
815
+ endpoint: config.endpoint,
816
+ credentials,
817
+ forcePathStyle: this.resolvedConfig.forcePathStyle,
818
+ ...config.config
819
+ });
820
+ }
821
+ /**
822
+ * Build AWS credentials from config.
823
+ * Supports explicit credentials or falls back to SDK default chain.
824
+ */
825
+ buildCredentials() {
826
+ if (this.config.accessKeyId && this.config.secretAccessKey) return {
827
+ accessKeyId: this.config.accessKeyId,
828
+ secretAccessKey: this.config.secretAccessKey
829
+ };
830
+ if (this.config.config?.credentials) return;
831
+ }
832
+ /**
833
+ * Upload file to S3.
834
+ *
835
+ * Uses AWS SDK v3's Upload class from @aws-sdk/lib-storage which:
836
+ * - Automatically handles multipart upload for large files (>5MB)
837
+ * - Provides progress tracking capability
838
+ * - Includes retry logic
839
+ * - Optimizes upload performance
840
+ *
841
+ * @param buffer - File content as Buffer
842
+ * @param options - Upload options (filename, mimeType, folder, collection)
843
+ * @returns Upload result with URL and storage path
844
+ */
845
+ async upload(buffer, options) {
846
+ const key = this.generateKey(options.filename, options.folder);
847
+ const uploadParams = {
848
+ Bucket: this.resolvedConfig.bucket,
849
+ Key: key,
850
+ Body: buffer,
851
+ ContentType: options.contentType || options.mimeType,
852
+ CacheControl: this.resolvedConfig.cacheControl
853
+ };
854
+ if (!this.isR2) uploadParams.ACL = this.resolvedConfig.acl;
855
+ const disposition = options.contentDisposition ?? this.resolvedConfig.contentDisposition;
856
+ if (disposition) {
857
+ const filename = this.sanitizeFilename(options.filename);
858
+ uploadParams.ContentDisposition = disposition === "attachment" ? `attachment; filename="${filename}"` : "inline";
859
+ }
860
+ uploadParams.Metadata = { "original-filename": options.filename };
861
+ await new Upload({
862
+ client: this.client,
863
+ params: uploadParams
864
+ }).done();
865
+ return {
866
+ url: this.getPublicUrl(key),
867
+ path: key
868
+ };
869
+ }
870
+ /**
871
+ * Delete file from S3.
872
+ *
873
+ * @param filePath - Storage path/key to delete
874
+ */
875
+ async delete(filePath) {
876
+ const command = new DeleteObjectCommand({
877
+ Bucket: this.resolvedConfig.bucket,
878
+ Key: filePath
879
+ });
880
+ await this.client.send(command);
881
+ }
882
+ /**
883
+ * Bulk delete files from S3 using a single API call per 1000 keys.
884
+ *
885
+ * Uses AWS SDK v3's DeleteObjectsCommand which supports up to 1000 keys per
886
+ * request. Automatically batches larger arrays and collects per-key results.
887
+ *
888
+ * @param filePaths - Storage paths/keys to delete
889
+ * @returns Object with arrays of successful and failed deletions
890
+ */
891
+ async bulkDelete(filePaths) {
892
+ const successful = [];
893
+ const failed = [];
894
+ const maxBatchSize = 1e3;
895
+ for (let i = 0; i < filePaths.length; i += maxBatchSize) {
896
+ const batch = filePaths.slice(i, i + maxBatchSize);
897
+ const command = new DeleteObjectsCommand({
898
+ Bucket: this.resolvedConfig.bucket,
899
+ Delete: {
900
+ Objects: batch.map((key) => ({ Key: key })),
901
+ Quiet: false
902
+ }
903
+ });
904
+ const response = await this.client.send(command);
905
+ if (response.Errors && response.Errors.length > 0) {
906
+ for (const err of response.Errors) if (err.Key) failed.push({
907
+ filePath: err.Key,
908
+ error: err.Message ?? "Unknown S3 delete error"
909
+ });
910
+ }
911
+ if (response.Deleted) {
912
+ for (const del of response.Deleted) if (del.Key) successful.push(del.Key);
913
+ }
914
+ }
915
+ return {
916
+ successful,
917
+ failed
918
+ };
919
+ }
920
+ /**
921
+ * Check if file exists in S3.
922
+ *
923
+ * Uses HeadObject command which is more efficient than GetObject
924
+ * for existence checks (doesn't download the file).
925
+ *
926
+ * @param filePath - Storage path/key to check
927
+ * @returns true if file exists, false otherwise
928
+ */
929
+ async exists(filePath) {
930
+ try {
931
+ const command = new HeadObjectCommand({
932
+ Bucket: this.resolvedConfig.bucket,
933
+ Key: filePath
934
+ });
935
+ await this.client.send(command);
936
+ return true;
937
+ } catch (error) {
938
+ if (this.isNotFoundError(error)) return false;
939
+ throw error;
940
+ }
941
+ }
942
+ /**
943
+ * Get public URL for S3 file.
944
+ *
945
+ * Priority order:
946
+ * 1. Custom publicUrl (CDN or custom domain) if configured
947
+ * 2. Standard S3 URL based on region and bucket
948
+ *
949
+ * For R2: Requires publicUrl configuration (R2 has no default public URLs).
950
+ *
951
+ * @param filePath - Storage path/key
952
+ * @returns Public URL to access the file
953
+ * @throws Error if R2 is used without publicUrl configuration
954
+ */
955
+ /**
956
+ * Every object in the bucket, by key, with when it was last written, a page
957
+ * of up to 1,000 at a time.
958
+ */
959
+ async *list() {
960
+ let token;
961
+ do {
962
+ const page = await this.client.send(new ListObjectsV2Command({
963
+ Bucket: this.resolvedConfig.bucket,
964
+ ContinuationToken: token
965
+ }));
966
+ for (const object of page.Contents ?? []) if (object.Key) yield {
967
+ path: object.Key,
968
+ lastModified: object.LastModified
969
+ };
970
+ token = page.IsTruncated ? page.NextContinuationToken : void 0;
971
+ } while (token);
972
+ }
973
+ getPublicUrl(filePath) {
974
+ if (this.resolvedConfig.publicUrl) return `${this.resolvedConfig.publicUrl.replace(/\/$/, "")}/${filePath}`;
975
+ if (this.isR2) throw new Error("@nextly/storage-s3: Cloudflare R2 requires publicUrl configuration.\n\nR2 does not have default public URLs like AWS S3. Configure one of:\n1. Public bucket URL: publicUrl: 'https://pub-xxx.r2.dev'\n2. Custom domain: publicUrl: 'https://cdn.example.com'\n\nSet up public access in the Cloudflare R2 dashboard.");
976
+ return `https://${this.resolvedConfig.bucket}.s3.${this.resolvedConfig.region}.amazonaws.com/${filePath}`;
977
+ }
978
+ /**
979
+ * Get storage type identifier.
980
+ *
981
+ * Returns "s3" for all S3-compatible services (AWS S3, R2, MinIO, etc.)
982
+ * as they all use the S3 API.
983
+ */
984
+ getType() {
985
+ return "s3";
986
+ }
987
+ /**
988
+ * Get adapter info including capabilities.
989
+ *
990
+ * @returns Adapter info with type, name, and capability flags
991
+ */
992
+ getInfo() {
993
+ return {
994
+ type: "s3",
995
+ name: "S3StorageAdapter",
996
+ supportsSignedUrls: true,
997
+ supportsClientUploads: true
998
+ };
999
+ }
1000
+ /**
1001
+ * Get file metadata from S3.
1002
+ *
1003
+ * Retrieves file information including size, content type, and timestamps
1004
+ * using the HeadObject command.
1005
+ *
1006
+ * @param filePath - Storage path/key
1007
+ * @returns File metadata or null if file not found
1008
+ */
1009
+ async getMetadata(filePath) {
1010
+ try {
1011
+ const command = new HeadObjectCommand({
1012
+ Bucket: this.resolvedConfig.bucket,
1013
+ Key: filePath
1014
+ });
1015
+ const response = await this.client.send(command);
1016
+ const filename = filePath.split("/").pop() || filePath;
1017
+ return {
1018
+ id: filePath,
1019
+ filename,
1020
+ originalFilename: response.Metadata?.["original-filename"] || filename,
1021
+ mimeType: response.ContentType || "application/octet-stream",
1022
+ size: response.ContentLength || 0,
1023
+ url: this.getPublicUrl(filePath),
1024
+ createdAt: response.LastModified?.toISOString() || (/* @__PURE__ */ new Date()).toISOString()
1025
+ };
1026
+ } catch (error) {
1027
+ if (this.isNotFoundError(error)) return null;
1028
+ throw error;
1029
+ }
1030
+ }
1031
+ /**
1032
+ * Read a stored object back as bytes, or `null` when it is not there.
1033
+ *
1034
+ * The contract declares this OPTIONAL and, until now, no adapter supplied
1035
+ * it — so a caller reaching for `adapter.read` got `undefined` and fell
1036
+ * through whatever branch followed. An optional member nothing implements is
1037
+ * a contract that reads as a capability and behaves as an absence.
1038
+ *
1039
+ * BUFFERS rather than streams, because that is the declared return type and
1040
+ * widening it here would make this adapter answer a different question from
1041
+ * its siblings. That bounds what it should be used for: an asset the server
1042
+ * must serve from its own origin — a font file, a small document — rather
1043
+ * than arbitrarily large media, which belongs behind {@link getSignedUrl} or
1044
+ * a public URL. A streaming variant is a separate contract member, not a
1045
+ * quiet change to this one.
1046
+ *
1047
+ * `null` for a missing key rather than a throw, matching
1048
+ * {@link getMetadata}: absence is an ordinary answer about the bucket, while
1049
+ * a credential or network failure is not, so only the first is folded into
1050
+ * the return value.
1051
+ *
1052
+ * @param filePath - Storage path/key
1053
+ * @returns The object's bytes, or `null` when no such key exists
1054
+ */
1055
+ async read(filePath, options) {
1056
+ try {
1057
+ const command = new GetObjectCommand({
1058
+ Bucket: this.resolvedConfig.bucket,
1059
+ Key: filePath
1060
+ });
1061
+ const response = await this.client.send(command, abortAfter(options));
1062
+ if (response.Body === void 0) return Buffer.alloc(0);
1063
+ const cap = resolveReadBounds(options).maxBytes;
1064
+ this.refuseOverCap(filePath, response.ContentLength, cap);
1065
+ return await this.readCapped(filePath, response.Body, cap);
1066
+ } catch (error) {
1067
+ if (error instanceof Error && error.name === "NoSuchBucket") throw error;
1068
+ if (this.isNotFoundError(error)) return null;
1069
+ throw error;
1070
+ }
1071
+ }
1072
+ /**
1073
+ * Generate signed URL for temporary private file access.
1074
+ *
1075
+ * Creates a pre-signed GetObject URL that grants temporary read access
1076
+ * to private files. Useful for serving files from private buckets.
1077
+ *
1078
+ * @param filePath - Storage path/key
1079
+ * @param expiresIn - URL validity duration in seconds (default: 3600)
1080
+ * @returns Pre-signed URL for downloading the file
1081
+ */
1082
+ async getSignedUrl(filePath, expiresIn) {
1083
+ const command = new GetObjectCommand({
1084
+ Bucket: this.resolvedConfig.bucket,
1085
+ Key: filePath
1086
+ });
1087
+ return getSignedUrl(this.client, command, { expiresIn: expiresIn ?? this.resolvedConfig.signedUrlExpiresIn });
1088
+ }
1089
+ /**
1090
+ * Generate pre-signed URL for client-side uploads.
1091
+ *
1092
+ * Creates a pre-signed PutObject URL that allows direct uploads from
1093
+ * the browser to S3, bypassing server-side upload limits (e.g., Vercel's 4.5MB).
1094
+ *
1095
+ * @param key - Storage path/key for the upload
1096
+ * @param mimeType - MIME type of the file being uploaded
1097
+ * @param expiresIn - URL validity duration in seconds (default: 3600)
1098
+ * @returns Client upload data with URL, method, and headers
1099
+ */
1100
+ async getPresignedUploadUrl(key, mimeType, expiresIn) {
1101
+ const expiration = expiresIn ?? this.resolvedConfig.signedUrlExpiresIn;
1102
+ const commandParams = {
1103
+ Bucket: this.resolvedConfig.bucket,
1104
+ Key: key,
1105
+ ContentType: mimeType,
1106
+ CacheControl: this.resolvedConfig.cacheControl
1107
+ };
1108
+ if (!this.isR2) commandParams.ACL = this.resolvedConfig.acl;
1109
+ const command = new PutObjectCommand(commandParams);
1110
+ return {
1111
+ uploadUrl: await getSignedUrl(this.client, command, { expiresIn: expiration }),
1112
+ path: key,
1113
+ method: "PUT",
1114
+ headers: { "Content-Type": mimeType },
1115
+ expiresAt: new Date(Date.now() + expiration * 1e3)
1116
+ };
1117
+ }
1118
+ /**
1119
+ * Generate a unique storage key with date-based prefix.
1120
+ *
1121
+ * Creates keys in format: {folder}/{year}/{month}/{uuid}-{sanitized-filename}
1122
+ *
1123
+ * @param filename - Original filename (will be sanitized)
1124
+ * @param folder - Optional folder/prefix for organizing uploads
1125
+ * @returns Generated storage key
1126
+ */
1127
+ generateKey(filename, folder) {
1128
+ const sanitized = this.sanitizeFilename(filename);
1129
+ const uuid = crypto.randomUUID();
1130
+ const date = /* @__PURE__ */ new Date();
1131
+ const year = date.getFullYear();
1132
+ const month = String(date.getMonth() + 1).padStart(2, "0");
1133
+ return `${folder ? `${folder}/${year}/${month}` : `${year}/${month}`}/${uuid}-${sanitized}`;
1134
+ }
1135
+ /**
1136
+ * Sanitize filename to prevent directory traversal and S3 key issues.
1137
+ *
1138
+ * @param filename - Original filename
1139
+ * @returns Sanitized filename safe for S3 keys
1140
+ */
1141
+ sanitizeFilename(filename) {
1142
+ return (filename.split(/[/\\]/).pop() || filename).replace(/[^a-zA-Z0-9._-]/g, "-");
1143
+ }
1144
+ /**
1145
+ * Check if an error is a "not found" error from S3.
1146
+ *
1147
+ * @param error - Error to check
1148
+ * @returns true if error indicates file not found
1149
+ */
1150
+ /**
1151
+ * The object's bytes, refusing once more than `cap` have actually arrived.
1152
+ *
1153
+ * `ContentLength` is OPTIONAL in the SDK's response type, and this adapter
1154
+ * explicitly supports MinIO, R2 and other compatible services — any of which
1155
+ * may omit it or report it wrongly. A preflight check against metadata is
1156
+ * therefore a courtesy that fails OPEN: trusting it alone leaves the cap
1157
+ * unenforced exactly where an unusual backend is involved, which is where a
1158
+ * caller most needs it.
1159
+ *
1160
+ * Counted while consuming, so an oversized body is abandoned partway rather
1161
+ * than after it has all been buffered — the cap exists to bound memory, and
1162
+ * one applied after `transformToByteArray` has already spent it.
1163
+ *
1164
+ * Falls back to buffering when the body is not async-iterable, which the SDK
1165
+ * types permit. Stated rather than hidden: on that path the cap bounds what a
1166
+ * caller RECEIVES rather than what the process allocates.
1167
+ */
1168
+ async readCapped(filePath, body, cap) {
1169
+ if (typeof body[Symbol.asyncIterator] !== "function") {
1170
+ const whole = Buffer.from(await body.transformToByteArray());
1171
+ if (whole.byteLength > cap) throw new StorageReadTooLargeError(filePath, cap, whole.byteLength);
1172
+ return whole;
1173
+ }
1174
+ const chunks = [];
1175
+ let received = 0;
1176
+ for await (const chunk of body) {
1177
+ received += chunk.byteLength;
1178
+ if (received > cap) throw new StorageReadTooLargeError(filePath, cap, received);
1179
+ chunks.push(Buffer.from(chunk));
1180
+ }
1181
+ return Buffer.concat(chunks);
1182
+ }
1183
+ /**
1184
+ * Refuse a read whose object is already known to exceed the caller's cap.
1185
+ *
1186
+ * Its own method rather than three conditions inside `read`, because the
1187
+ * decision has nothing to do with the surrounding error handling and reads
1188
+ * as noise there — and because `read`'s branching is the part a reviewer has
1189
+ * to hold in their head to check the absent-versus-unavailable distinction.
1190
+ *
1191
+ * Both `undefined` cases mean "no opinion" and pass: a caller that named no
1192
+ * cap has none, and a store that reported no length gives nothing to compare.
1193
+ * The second is deliberately permissive — refusing an unmeasured object would
1194
+ * reject valid reads whenever S3 omits the header.
1195
+ */
1196
+ refuseOverCap(filePath, declared, cap) {
1197
+ if (cap === void 0 || declared === void 0 || declared <= cap) return;
1198
+ throw new StorageReadTooLargeError(filePath, cap, declared);
1199
+ }
1200
+ isNotFoundError(error) {
1201
+ if (error && typeof error === "object") {
1202
+ const e = error;
1203
+ return e.name === "NotFound" || e.$metadata?.httpStatusCode === 404;
1204
+ }
1205
+ return false;
1206
+ }
1207
+ /**
1208
+ * Get the S3 client instance.
1209
+ * Useful for advanced operations not covered by the adapter interface.
1210
+ */
1211
+ getClient() {
1212
+ return this.client;
1213
+ }
1214
+ /**
1215
+ * Get the bucket name.
1216
+ */
1217
+ getBucket() {
1218
+ return this.resolvedConfig.bucket;
1219
+ }
1220
+ /**
1221
+ * Get the AWS region.
1222
+ */
1223
+ getRegion() {
1224
+ return this.resolvedConfig.region;
1225
+ }
1226
+ /**
1227
+ * Check if this adapter is configured for Cloudflare R2.
1228
+ */
1229
+ isCloudflareR2() {
1230
+ return this.isR2;
1231
+ }
1074
1232
  };
1075
-
1076
1233
  // src/plugin.ts
1234
+ /**
1235
+ * Create an S3 storage plugin for Nextly.
1236
+ *
1237
+ * This factory function creates a StoragePlugin that can be added to
1238
+ * the `storage` array in `nextly.config.ts`. It supports:
1239
+ *
1240
+ * - AWS S3 (standard)
1241
+ * - Cloudflare R2 (S3-compatible)
1242
+ * - MinIO (S3-compatible, self-hosted)
1243
+ * - DigitalOcean Spaces (S3-compatible)
1244
+ * - Any other S3-compatible service
1245
+ *
1246
+ * @param config - S3 storage configuration
1247
+ * @returns A StoragePlugin that MediaStorage can register
1248
+ *
1249
+ * @throws Error if bucket is not provided (via adapter)
1250
+ * @throws Error if region is not provided (via adapter)
1251
+ */
1077
1252
  function s3Storage(config) {
1078
- if (config.enabled === false) {
1079
- return {
1080
- name: "s3-storage",
1081
- type: "s3",
1082
- collections: {},
1083
- adapter: null
1084
- };
1085
- }
1086
- const adapter = new S3StorageAdapter(config);
1087
- const plugin = {
1088
- name: "s3-storage",
1089
- type: "s3",
1090
- collections: config.collections,
1091
- adapter,
1092
- /**
1093
- * Generate a pre-signed URL for client-side uploads.
1094
- *
1095
- * This allows files to be uploaded directly from the browser to S3,
1096
- * bypassing server-side upload limits (e.g., Vercel's 4.5MB limit).
1097
- *
1098
- * @param filename - Original filename from the client
1099
- * @param mimeType - MIME type of the file
1100
- * @param collection - Collection slug this upload belongs to
1101
- * @returns Client upload data with pre-signed URL
1102
- */
1103
- async getClientUploadUrl(filename, mimeType, collection) {
1104
- const collectionConfig = config.collections[collection];
1105
- const prefix = typeof collectionConfig === "object" ? collectionConfig.prefix : void 0;
1106
- const key = generateStorageKey(filename, prefix);
1107
- return adapter.getPresignedUploadUrl(key, mimeType);
1108
- },
1109
- /**
1110
- * Generate a signed URL for private file downloads.
1111
- *
1112
- * Creates a time-limited URL for accessing files in private buckets.
1113
- * Only works when collection has `signedDownloads: true`.
1114
- *
1115
- * @param path - Storage path/key of the file
1116
- * @param expiresIn - URL validity duration in seconds
1117
- * @returns Signed URL for downloading the file
1118
- */
1119
- async getSignedDownloadUrl(path, expiresIn) {
1120
- return adapter.getSignedUrl(
1121
- path,
1122
- expiresIn ?? config.signedUrlExpiresIn ?? 3600
1123
- );
1124
- }
1125
- };
1126
- return plugin;
1253
+ if (config.enabled === false) return {
1254
+ name: "s3-storage",
1255
+ type: "s3",
1256
+ collections: {},
1257
+ adapter: null
1258
+ };
1259
+ const adapter = new S3StorageAdapter(config);
1260
+ return {
1261
+ name: "s3-storage",
1262
+ type: "s3",
1263
+ collections: config.collections,
1264
+ adapter,
1265
+ /**
1266
+ * Generate a pre-signed URL for client-side uploads.
1267
+ *
1268
+ * This allows files to be uploaded directly from the browser to S3,
1269
+ * bypassing server-side upload limits (e.g., Vercel's 4.5MB limit).
1270
+ *
1271
+ * @param filename - Original filename from the client
1272
+ * @param mimeType - MIME type of the file
1273
+ * @param collection - Collection slug this upload belongs to
1274
+ * @returns Client upload data with pre-signed URL
1275
+ */
1276
+ async getClientUploadUrl(filename, mimeType, collection) {
1277
+ const collectionConfig = config.collections[collection];
1278
+ const key = generateStorageKey(filename, typeof collectionConfig === "object" ? collectionConfig.prefix : void 0);
1279
+ return adapter.getPresignedUploadUrl(key, mimeType);
1280
+ },
1281
+ /**
1282
+ * Generate a signed URL for private file downloads.
1283
+ *
1284
+ * Creates a time-limited URL for accessing files in private buckets.
1285
+ * Only works when collection has `signedDownloads: true`.
1286
+ *
1287
+ * @param path - Storage path/key of the file
1288
+ * @param expiresIn - URL validity duration in seconds
1289
+ * @returns Signed URL for downloading the file
1290
+ */
1291
+ async getSignedDownloadUrl(path, expiresIn) {
1292
+ return adapter.getSignedUrl(path, expiresIn ?? config.signedUrlExpiresIn ?? 3600);
1293
+ }
1294
+ };
1127
1295
  }
1296
+ /**
1297
+ * Generate a unique storage key with date-based prefix.
1298
+ *
1299
+ * Creates keys in format: {prefix}{year}/{month}/{uuid}-{sanitized-filename}
1300
+ * This matches the format used by S3StorageAdapter for consistency.
1301
+ *
1302
+ * @param filename - Original filename (will be sanitized)
1303
+ * @param prefix - Optional folder/prefix for organizing uploads
1304
+ * @returns Generated storage key
1305
+ */
1128
1306
  function generateStorageKey(filename, prefix) {
1129
- const sanitized = sanitizeFilename(filename);
1130
- const uuid = crypto.randomUUID();
1131
- const date = /* @__PURE__ */ new Date();
1132
- const year = date.getFullYear();
1133
- const month = String(date.getMonth() + 1).padStart(2, "0");
1134
- const keyPrefix = prefix ? `${prefix}${year}/${month}` : `${year}/${month}`;
1135
- return `${keyPrefix}/${uuid}-${sanitized}`;
1307
+ const sanitized = sanitizeFilename(filename);
1308
+ const uuid = crypto.randomUUID();
1309
+ const date = /* @__PURE__ */ new Date();
1310
+ const year = date.getFullYear();
1311
+ const month = String(date.getMonth() + 1).padStart(2, "0");
1312
+ return `${prefix ? `${prefix}${year}/${month}` : `${year}/${month}`}/${uuid}-${sanitized}`;
1136
1313
  }
1314
+ /**
1315
+ * Sanitize filename to prevent directory traversal and S3 key issues.
1316
+ *
1317
+ * Removes path separators and replaces unsafe characters with hyphens.
1318
+ * Keeps only: a-z, A-Z, 0-9, dot, underscore, hyphen
1319
+ *
1320
+ * @param filename - Original filename
1321
+ * @returns Sanitized filename safe for S3 keys
1322
+ */
1137
1323
  function sanitizeFilename(filename) {
1138
- const basename = filename.split(/[/\\]/).pop() || filename;
1139
- return basename.replace(/[^a-zA-Z0-9._-]/g, "-");
1324
+ return (filename.split(/[/\\]/).pop() || filename).replace(/[^a-zA-Z0-9._-]/g, "-");
1140
1325
  }
1141
-
1142
1326
  // src/index.ts
1143
- var PACKAGE_NAME = "@nextly/storage-s3";
1144
- var PACKAGE_VERSION = "0.1.0";
1145
-
1327
+ const PACKAGE_NAME = "@nextly/storage-s3";
1328
+ const PACKAGE_VERSION = "0.1.0";
1146
1329
  export { PACKAGE_NAME, PACKAGE_VERSION, S3StorageAdapter, s3Storage };
1147
- //# sourceMappingURL=index.mjs.map
1330
+
1148
1331
  //# sourceMappingURL=index.mjs.map