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

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