@nextlyhq/storage-s3 0.0.2-alpha.7 → 0.0.2-alpha.70

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