@nextlyhq/storage-vercel-blob 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,399 +1,1710 @@
1
- 'use strict';
2
-
3
- var blob = require('@vercel/blob');
4
-
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let _vercel_blob = require("@vercel/blob");
3
+ // ../nextly/dist/nextly-error-D21_8kpX.mjs
4
+ function isDbError(err) {
5
+ if (!err || typeof err !== "object") return false;
6
+ const obj = err;
7
+ return obj.name === "DbError" && typeof obj.kind === "string";
8
+ }
9
+ /**
10
+ * The driver's own code for an error, wherever that driver puts it.
11
+ *
12
+ * Exported so callers that must distinguish one failure from another classify
13
+ * by the SAME extraction this module's mapping uses. A second reader would go
14
+ * looking in a different set of properties and disagree on exactly the drivers
15
+ * whose codes are hardest to find.
16
+ */
17
+ /**
18
+ * Whether an error is a duplicate-key rejection.
19
+ *
20
+ * Exposed because a plugin inserting into a table with a unique index has to
21
+ * tell "this row already exists" from "the database is broken", and the two
22
+ * arrive as the same thrown object. Derived from the existing SQLSTATE
23
+ * classification rather than by matching driver messages: those differ per
24
+ * driver and per version, and a plugin re-deriving it would be a second
25
+ * implementation of a question this module already answers.
26
+ */
27
+ /**
28
+ * Whether a driver code says the database was busy: the adapters' own code
29
+ * for a request that waited out `pool.connectionTimeoutMs`, the same on
30
+ * every dialect, or SQLITE_BUSY and its extended codes, another process
31
+ * holding the SQLite file past `busyTimeout`. Neither depends on the dialect,
32
+ * which is what lets {@link isDatabaseBusy} answer without one.
33
+ */
34
+ function isBusyCode(code) {
35
+ if (code === void 0) return false;
36
+ return code === "NEXTLY_POOL_WAIT_TIMEOUT" || code.toUpperCase().startsWith("SQLITE_BUSY");
37
+ }
38
+ /**
39
+ * Whether an error is the database being busy, however it arrives: a DbError
40
+ * of kind "busy", or the raw error an adapter or driver threw.
41
+ *
42
+ * For the boundaries that answer a request with whatever its work threw.
43
+ * `withDbErrors` converts only DbErrors, so a raw driver error reaches them
44
+ * unconverted, and without this it would read as an internal fault rather
45
+ * than a request worth retrying.
46
+ */
47
+ function isDatabaseBusy(error) {
48
+ if (isDbError(error)) return error.kind === "busy";
49
+ return isBusyCode(safeCode(error));
50
+ }
51
+ function safeCode(error) {
52
+ if (!error || typeof error !== "object") return void 0;
53
+ const e = error;
54
+ let c = e.code ?? e.sqlState ?? e.state ?? e.errno ?? void 0;
55
+ if (!c && typeof e.originalError?.code === "string") c = e.originalError.code;
56
+ if (!c && typeof e.cause?.code === "string") c = e.cause.code;
57
+ if (!c && typeof e.severity === "string" && typeof e.code === "string") c = e.code;
58
+ if (typeof c === "number") return String(c);
59
+ if (typeof c === "string" && c.length > 0) return c;
60
+ }
61
+ /**
62
+ * Canonical NextlyError codes and their HTTP status mappings.
63
+ *
64
+ * Plugin codes outside this enum must always pass an explicit `statusCode`
65
+ * to the NextlyError constructor (no enum lookup happens for unknown codes).
66
+ */
67
+ const NEXTLY_ERROR_STATUS = {
68
+ VALIDATION_ERROR: 400,
69
+ INVALID_INPUT: 400,
70
+ AUTH_REQUIRED: 401,
71
+ AUTH_INVALID_CREDENTIALS: 401,
72
+ TOKEN_EXPIRED: 401,
73
+ FORBIDDEN: 403,
74
+ EMAIL_NOT_VERIFIED: 403,
75
+ BUILDER_DISABLED: 403,
76
+ CSRF_FAILED: 403,
77
+ SETUP_TOKEN_REQUIRED: 403,
78
+ API_KEY_ROLE_ABOVE_CREATOR: 403,
79
+ NOT_FOUND: 404,
80
+ METHOD_NOT_ALLOWED: 405,
81
+ CONFLICT: 409,
82
+ DUPLICATE: 409,
83
+ RATE_LIMITED: 429,
84
+ PAYLOAD_TOO_LARGE: 413,
85
+ UNSUPPORTED_MEDIA_TYPE: 415,
86
+ BUSINESS_RULE_VIOLATION: 422,
87
+ INTERNAL_ERROR: 500,
88
+ DATABASE_ERROR: 500,
89
+ DATABASE_BUSY: 503,
90
+ EXTERNAL_SERVICE_ERROR: 502,
91
+ SERVICE_UNAVAILABLE: 503,
92
+ EXTERNAL_URL_BLOCKED: 400,
93
+ EXTERNAL_REQUEST_FAILED: 502,
94
+ FILENAME_INVALID: 400,
95
+ EXTENSION_BLOCKED: 400,
96
+ MIME_BLOCKED: 415,
97
+ MIME_NOT_ALLOWED: 415,
98
+ SIZE_EXCEEDED: 413,
99
+ STORAGE_READ_TOO_LARGE: 413,
100
+ STORAGE_READ_TIMEOUT: 504,
101
+ STORAGE_READ_UNREACHABLE: 502,
102
+ MAGIC_BYTE_MISMATCH: 400,
103
+ SVG_SANITIZATION_FAILED: 400,
104
+ UNSUPPORTED_FOR_BACKEND: 415,
105
+ NEXTLY_LEGACY_BOOKKEEPING_DETECTED: 409,
106
+ NEXTLY_UPGRADE_TABLE_NAME_COLLISION: 409,
107
+ NEXTLY_UPGRADE_IN_PROGRESS: 409,
108
+ NEXTLY_MIGRATE_LOCK_BUSY: 409,
109
+ NEXTLY_BASELINE_LOCK_NOT_HELD: 409,
110
+ NEXTLY_RESOLVE_LOCK_NOT_HELD: 409,
111
+ NEXTLY_BOOT_MIGRATIONS_NOT_RUN: 503,
112
+ NEXTLY_BOOT_MIGRATIONS_PENDING: 503,
113
+ NEXTLY_CORE_DESTRUCTIVE_REFUSED: 409,
114
+ NEXTLY_MIGRATION_DRIFT: 409,
115
+ NEXTLY_MIGRATION_APPLY_FAILED: 500,
116
+ NEXTLY_MIGRATION_FOREIGN_KEY_VIOLATION: 409,
117
+ NEXTLY_MIGRATION_PARTIALLY_APPLIED: 500,
118
+ NEXTLY_MIGRATION_CONCURRENT_RUN: 409,
119
+ NEXTLY_MIGRATION_FILE_MISSING: 404,
120
+ NEXTLY_MIGRATION_SNAPSHOT_MISSING: 404,
121
+ NEXTLY_MIGRATION_RESOLVE_DRIFT: 409,
122
+ NEXTLY_MIGRATION_RESOLVE_PRECONDITION: 409,
123
+ NEXTLY_UI_SCHEMA_INVALID: 400,
124
+ NEXTLY_SCHEMA_SLUG_COLLISION: 409,
125
+ NEXTLY_SCHEMA_RELATION_TARGET_MISSING: 400,
126
+ NEXTLY_SCHEMA_RELATION_UNRESOLVED: 400,
127
+ NEXTLY_SCHEMA_EXTEND_TARGET_UNKNOWN: 400,
128
+ NEXTLY_SCHEMA_EXTEND_FIELD_DUPLICATE: 409,
129
+ NEXTLY_SCHEMA_CROSS_PLUGIN_RELATION: 409,
130
+ NEXTLY_SCHEMA_RENAME_UNKNOWN_TARGET: 400,
131
+ NEXTLY_PLUGIN_CLIENT_CONFIG_INVALID: 500,
132
+ NEXTLY_PLUGIN_ADMIN_WIDGET_INVALID: 500,
133
+ NEXTLY_ADMIN_COMPONENT_MAP_STALE: 500,
134
+ NEXTLY_PLUGIN_DOCUMENT_VIEW_INVALID: 500,
135
+ PLUGIN_RESOLUTION_ERROR: 500,
136
+ PLUGIN_DEPENDENCY_NOT_INSTALLED: 409,
137
+ PLUGIN_HAS_DEPENDENTS: 409,
138
+ PLUGIN_UNINSTALL_IRREVERSIBLE: 409,
139
+ PLUGIN_UNINSTALL_UNCONFIRMED: 409,
140
+ PLUGIN_SCHEMA_BEHIND: 409,
141
+ PLUGIN_SCHEMA_UNINSTALLED: 409,
142
+ PLUGIN_NOT_INSTALLED: 409,
143
+ PLUGIN_DISABLED: 409,
144
+ PLUGIN_UNINSTALL_UNFINISHED: 409,
145
+ PLUGIN_SCHEMA_VERSION_NOT_ADVANCED: 409,
146
+ PLUGIN_MIGRATION_DROPS_CREATED_SCHEMA: 409,
147
+ PLUGIN_MIGRATION_ADDS_UNFILLABLE_COLUMN: 409,
148
+ PLUGIN_MIGRATION_SQL_MISSING: 409,
149
+ PLUGIN_MIGRATIONS_UNAVAILABLE: 409,
150
+ DROP_OF_FOREIGN_TABLE: 409,
151
+ MIGRATION_CHECKSUM_MISMATCH: 409,
152
+ PLUGIN_MIGRATIONS_OUT_OF_ORDER: 409,
153
+ PLUGIN_MIGRATION_HISTORY_CHANGED: 409,
154
+ NEXTLY_ROUTE_COLLISION: 409,
155
+ NEXTLY_ROUTE_INVALID_PATH: 400,
156
+ NEXTLY_ROUTE_UNREACHABLE_ROOT: 400,
157
+ NEXTLY_ROUTE_INVALID_MOUNT: 400,
158
+ NEXTLY_EMAIL_TRANSPORT_UNAVAILABLE: 503,
159
+ NEXTLY_CONFIG_TOOLING_UNAVAILABLE: 503,
160
+ NEXTLY_POSTGRES_SCHEMA_MISMATCH: 500,
161
+ NEXTLY_POSTGRES_SCHEMA_UNSUPPORTED: 500
162
+ };
163
+ ({ ...Object.fromEntries([
164
+ "VALIDATION_ERROR",
165
+ "AUTH_REQUIRED",
166
+ "FORBIDDEN",
167
+ "NOT_FOUND",
168
+ "CONFLICT",
169
+ "PAYLOAD_TOO_LARGE",
170
+ "UNSUPPORTED_MEDIA_TYPE",
171
+ "RATE_LIMITED",
172
+ "EXTERNAL_SERVICE_ERROR",
173
+ "SERVICE_UNAVAILABLE"
174
+ ].map((code) => [NEXTLY_ERROR_STATUS[code], code])) });
175
+ /**
176
+ * The sentence a caller reads for a code, when the failure supplied none.
177
+ *
178
+ * Kept beside the status table because they answer the same question together:
179
+ * a code-less envelope's own `message` is NOT usable here. Those envelopes come
180
+ * from legacy converters that store a raw exception's text, so promoting it
181
+ * would put driver output, table names and internal paths on the wire -- the
182
+ * disclosure the public error shape exists to prevent (spec 13.8).
183
+ *
184
+ * Every entry is generic by design. The specific detail stays in `logContext`
185
+ * for the operator, against the same request id.
186
+ */
187
+ const GENERIC_PUBLIC_MESSAGE = {
188
+ VALIDATION_ERROR: "Validation failed.",
189
+ INVALID_INPUT: "The request could not be processed.",
190
+ AUTH_REQUIRED: "Authentication required.",
191
+ FORBIDDEN: "You don't have permission to perform this action.",
192
+ NOT_FOUND: "Not found.",
193
+ METHOD_NOT_ALLOWED: "That method is not allowed on this address.",
194
+ CONFLICT: "The resource has changed since you last loaded it. Please refresh and try again.",
195
+ DUPLICATE: "Resource already exists.",
196
+ PAYLOAD_TOO_LARGE: "The request is too large.",
197
+ UNSUPPORTED_MEDIA_TYPE: "That file type is not supported.",
198
+ RATE_LIMITED: "Too many requests. Please try again later.",
199
+ EXTERNAL_SERVICE_ERROR: "An upstream service failed.",
200
+ SERVICE_UNAVAILABLE: "The service is temporarily unavailable.",
201
+ DATABASE_BUSY: "The database is busy. Please try again shortly.",
202
+ INTERNAL_ERROR: "An unexpected error occurred."
203
+ };
204
+ /** The generic sentence for a code; the internal one for anything unlisted. */
205
+ function genericPublicMessage(code) {
206
+ return GENERIC_PUBLIC_MESSAGE[code] ?? GENERIC_PUBLIC_MESSAGE.INTERNAL_ERROR;
207
+ }
208
+ /**
209
+ * Default mapping from DbErrorKind to NextlyError contract. Used by
210
+ * `NextlyError.fromDatabaseError`. Public messages are intentionally generic
211
+ * per spec §13.8 — no DB driver text, no constraint names, no field hints.
212
+ *
213
+ * `satisfies Record<DbErrorKind, ...>` makes the mapping exhaustive at
214
+ * compile time: adding a new DbErrorKind without updating this table is a
215
+ * type error.
216
+ */
217
+ const DB_ERROR_MAPPING = {
218
+ "unique-violation": {
219
+ code: "DUPLICATE",
220
+ statusCode: 409,
221
+ publicMessage: "Resource already exists."
222
+ },
223
+ "fk-violation": {
224
+ code: "VALIDATION_ERROR",
225
+ statusCode: 400,
226
+ publicMessage: "Referenced record does not exist."
227
+ },
228
+ "not-null-violation": {
229
+ code: "VALIDATION_ERROR",
230
+ statusCode: 400,
231
+ publicMessage: "A required field is missing."
232
+ },
233
+ constraint: {
234
+ code: "VALIDATION_ERROR",
235
+ statusCode: 400,
236
+ publicMessage: "The provided data violates a constraint."
237
+ },
238
+ deadlock: {
239
+ code: "CONFLICT",
240
+ statusCode: 409,
241
+ publicMessage: "The operation could not be completed. Please retry."
242
+ },
243
+ "serialization-failure": {
244
+ code: "CONFLICT",
245
+ statusCode: 409,
246
+ publicMessage: "The operation could not be completed. Please retry."
247
+ },
248
+ busy: {
249
+ code: "DATABASE_BUSY",
250
+ statusCode: NEXTLY_ERROR_STATUS.DATABASE_BUSY,
251
+ publicMessage: genericPublicMessage("DATABASE_BUSY"),
252
+ publicData: { retryAfterSeconds: 5 }
253
+ },
254
+ timeout: {
255
+ code: "DATABASE_ERROR",
256
+ statusCode: 500,
257
+ publicMessage: "The operation timed out. Please try again."
258
+ },
259
+ "connection-lost": {
260
+ code: "DATABASE_ERROR",
261
+ statusCode: 500,
262
+ publicMessage: "A temporary database error occurred. Please try again."
263
+ },
264
+ syntax: {
265
+ code: "INTERNAL_ERROR",
266
+ statusCode: 500,
267
+ publicMessage: "An unexpected error occurred."
268
+ },
269
+ internal: {
270
+ code: "INTERNAL_ERROR",
271
+ statusCode: 500,
272
+ publicMessage: "An unexpected error occurred."
273
+ }
274
+ };
275
+ const NEXTLY_ERROR_BRAND = Symbol.for("nextly/NextlyError");
276
+ function hasBrand(value) {
277
+ if (value === null || typeof value !== "object" && typeof value !== "function") return false;
278
+ return value[NEXTLY_ERROR_BRAND] === true;
279
+ }
280
+ /**
281
+ * Unified error class for Nextly. Used at every throw site across services,
282
+ * direct API, auth, and plugins. Carries two distinct payloads:
283
+ *
284
+ * - Public (`code`, `publicMessage`, `publicData`, `statusCode`, `messageKey`)
285
+ * sent in HTTP responses and Server Action results.
286
+ * - Log (`logMessage`, `logContext`, `cause`, stack trace)
287
+ * written to the server logger; never serialised to the wire.
288
+ *
289
+ * Use the static factories (notFound, forbidden, validation, ...) for the
290
+ * common cases. Use the free-form constructor for plugin codes or one-off
291
+ * shapes.
292
+ */
293
+ var NextlyError = class NextlyError extends Error {
294
+ code;
295
+ statusCode;
296
+ publicMessage;
297
+ publicData;
298
+ messageKey;
299
+ logMessage;
300
+ logContext;
301
+ cause;
302
+ timestamp;
303
+ constructor(opts) {
304
+ super(opts.publicMessage);
305
+ this.name = "NextlyError";
306
+ this.code = opts.code;
307
+ this.publicMessage = opts.publicMessage;
308
+ this.publicData = opts.publicData;
309
+ this.messageKey = opts.messageKey;
310
+ this.logMessage = opts.logMessage;
311
+ this.logContext = opts.logContext;
312
+ this.cause = opts.cause;
313
+ this.timestamp = /* @__PURE__ */ new Date();
314
+ this.statusCode = NextlyError.resolveStatusCode(opts);
315
+ Error.captureStackTrace?.(this, NextlyError);
316
+ }
317
+ static {
318
+ NextlyError.prototype[NEXTLY_ERROR_BRAND] = true;
319
+ }
320
+ static resolveStatusCode(opts) {
321
+ if (typeof opts.statusCode === "number") return opts.statusCode;
322
+ if (opts.code in NEXTLY_ERROR_STATUS) return NEXTLY_ERROR_STATUS[opts.code];
323
+ return 500;
324
+ }
325
+ /** HTTP-safe JSON. Strips logMessage / logContext / cause / stack. */
326
+ toResponseJSON(requestId) {
327
+ const json = {
328
+ code: String(this.code),
329
+ message: this.publicMessage,
330
+ requestId
331
+ };
332
+ if (this.messageKey) json.messageKey = this.messageKey;
333
+ if (this.publicData !== void 0) json.data = this.publicData;
334
+ return json;
335
+ }
336
+ /** Operator-facing JSON for log lines. Includes everything. */
337
+ toLogJSON(requestId) {
338
+ return {
339
+ code: this.code,
340
+ statusCode: this.statusCode,
341
+ publicMessage: this.publicMessage,
342
+ messageKey: this.messageKey,
343
+ logMessage: this.logMessage,
344
+ logContext: this.logContext,
345
+ cause: this.cause ? {
346
+ name: this.cause.name,
347
+ message: this.cause.message,
348
+ stack: this.cause.stack
349
+ } : void 0,
350
+ timestamp: this.timestamp.toISOString(),
351
+ requestId
352
+ };
353
+ }
354
+ static invalidCredentials(opts) {
355
+ return new NextlyError({
356
+ code: "AUTH_INVALID_CREDENTIALS",
357
+ publicMessage: "Invalid email or password.",
358
+ logMessage: "Login failed",
359
+ logContext: opts?.logContext
360
+ });
361
+ }
362
+ /**
363
+ * The password was correct and the address is unverified. Thrown only once
364
+ * the password is proven, so only someone who holds it learns the address
365
+ * is unverified; every other refusal stays
366
+ * {@link NextlyError.invalidCredentials}.
367
+ */
368
+ static emailNotVerified(opts) {
369
+ return new NextlyError({
370
+ code: "EMAIL_NOT_VERIFIED",
371
+ publicMessage: "Verify your email address to sign in. Check your inbox for the link.",
372
+ logMessage: "Login refused: email not verified",
373
+ logContext: opts?.logContext
374
+ });
375
+ }
376
+ static authRequired(opts) {
377
+ return new NextlyError({
378
+ code: "AUTH_REQUIRED",
379
+ publicMessage: "Authentication required.",
380
+ logContext: opts?.logContext
381
+ });
382
+ }
383
+ /**
384
+ * Distinct from `authRequired`: the caller was authenticated but the
385
+ * session token expired. Clients key on the TOKEN_EXPIRED *code* to
386
+ * silently refresh and retry rather than redirecting to login; the public
387
+ * message stays the generic spec §13.6 string ("Authentication required.")
388
+ * so the wire never reveals the session state — same as `authRequired`.
389
+ */
390
+ static tokenExpired(opts) {
391
+ return new NextlyError({
392
+ code: "TOKEN_EXPIRED",
393
+ publicMessage: "Authentication required.",
394
+ logContext: opts?.logContext
395
+ });
396
+ }
397
+ static notFound(opts) {
398
+ return new NextlyError({
399
+ code: "NOT_FOUND",
400
+ publicMessage: opts?.message ?? "Not found.",
401
+ cause: opts?.cause,
402
+ logContext: opts?.logContext
403
+ });
404
+ }
405
+ static forbidden(opts) {
406
+ return new NextlyError({
407
+ code: "FORBIDDEN",
408
+ publicMessage: "You don't have permission to perform this action.",
409
+ cause: opts?.cause,
410
+ logContext: opts?.logContext
411
+ });
412
+ }
413
+ /**
414
+ * A collection, Single or component defined in code, which is changed by
415
+ * changing its code and not from here. Forbidden, and the message says so:
416
+ * it is a fact about the thing, not about the caller's permissions, so it
417
+ * names no permission and no policy. The lock's detail goes to the log
418
+ * through `logContext`.
419
+ */
420
+ static definedInCode(opts) {
421
+ return new NextlyError({
422
+ code: "FORBIDDEN",
423
+ publicMessage: `This ${opts.thing} is defined in code, so it can't be ${opts.change === "change" ? "changed" : "deleted"} here.`,
424
+ logContext: opts.logContext
425
+ });
426
+ }
427
+ /**
428
+ * An autosave where the collection or Single does not autosave: its owner
429
+ * switched autosave off, or it keeps no drafts to autosave into. Forbidden,
430
+ * and the message says so, since it is a setting and not a permission.
431
+ */
432
+ static autosaveOff(opts) {
433
+ return new NextlyError({
434
+ code: "FORBIDDEN",
435
+ publicMessage: `Autosave is turned off for this ${opts.scopeKind === "single" ? "Single" : "collection"}.`,
436
+ logContext: opts.logContext
437
+ });
438
+ }
439
+ /**
440
+ * An API key refused because its role allows more than the person creating
441
+ * it may do. The sentence is FORBIDDEN's and names no permission; which one
442
+ * exceeded goes to the log through `logContext`. The code is its own, so a
443
+ * client can tell "choose a smaller role" from plain FORBIDDEN.
444
+ */
445
+ static apiKeyRoleAboveCreator(opts) {
446
+ return new NextlyError({
447
+ code: "API_KEY_ROLE_ABOVE_CREATOR",
448
+ publicMessage: genericPublicMessage("FORBIDDEN"),
449
+ logContext: opts?.logContext
450
+ });
451
+ }
452
+ /**
453
+ * A cookie-authenticated write refused because its origin or CSRF token did
454
+ * not check out. The public message names no detail of which check failed;
455
+ * that goes to the log through `logMessage`.
456
+ */
457
+ static csrfFailed(opts) {
458
+ return new NextlyError({
459
+ code: "CSRF_FAILED",
460
+ publicMessage: "This request could not be verified. Reload the page and try again.",
461
+ logMessage: opts?.logMessage,
462
+ logContext: opts?.logContext
463
+ });
464
+ }
465
+ /**
466
+ * A call the caller got wrong, where naming the mistake IS the value of the
467
+ * error.
468
+ *
469
+ * The only factory that takes its public message from the caller. The
470
+ * generic messages elsewhere exist so an HTTP response cannot leak internal
471
+ * detail; this one is for arguments and configuration a developer controls
472
+ * and must be told about — a missing option, an unusable combination — where
473
+ * `internal()` would reduce the one useful sentence to "An unexpected error
474
+ * occurred." Do not pass user-supplied data through it.
475
+ */
476
+ static invalidInput(opts) {
477
+ return new NextlyError({
478
+ code: "INVALID_INPUT",
479
+ publicMessage: opts.message,
480
+ logContext: opts.logContext
481
+ });
482
+ }
483
+ static validation(opts) {
484
+ return new NextlyError({
485
+ code: "VALIDATION_ERROR",
486
+ publicMessage: "Validation failed.",
487
+ publicData: { errors: opts.errors },
488
+ cause: opts.cause,
489
+ logContext: opts.logContext
490
+ });
491
+ }
492
+ static conflict(opts) {
493
+ return new NextlyError({
494
+ code: "CONFLICT",
495
+ publicMessage: opts?.message ?? "The resource has changed since you last loaded it. Please refresh and try again.",
496
+ publicData: opts?.data,
497
+ cause: opts?.cause,
498
+ logContext: {
499
+ reason: opts?.reason,
500
+ ...opts?.logContext
501
+ }
502
+ });
503
+ }
504
+ static duplicate(opts) {
505
+ return new NextlyError({
506
+ code: "DUPLICATE",
507
+ publicMessage: "Resource already exists.",
508
+ logContext: opts?.logContext
509
+ });
510
+ }
511
+ static rateLimited(opts) {
512
+ return new NextlyError({
513
+ code: "RATE_LIMITED",
514
+ publicMessage: "Too many requests. Please try again later.",
515
+ publicData: opts?.retryAfterSeconds !== void 0 ? { retryAfterSeconds: opts.retryAfterSeconds } : void 0,
516
+ logContext: opts?.logContext
517
+ });
518
+ }
519
+ /**
520
+ * A request that waited `pool.connectionTimeoutMs` for a database
521
+ * connection and was given none. The statement or transaction that waited
522
+ * never ran; work committed before it stays committed. The same error
523
+ * `fromDatabaseError` gives a busy DbError, from the same table row.
524
+ */
525
+ static databaseBusy(opts) {
526
+ const busy = DB_ERROR_MAPPING.busy;
527
+ return new NextlyError({
528
+ code: busy.code,
529
+ statusCode: busy.statusCode,
530
+ publicMessage: busy.publicMessage,
531
+ publicData: busy.publicData,
532
+ cause: opts?.cause,
533
+ logContext: opts?.logContext
534
+ });
535
+ }
536
+ /**
537
+ * What a request boundary answers with for a thrown value that is not a
538
+ * NextlyError: "database busy" when the request waited out its bound for a
539
+ * connection, which is retryable and no fault of the server's code, and an
540
+ * internal error for anything else.
541
+ *
542
+ * The busy case has to be read here because it usually arrives raw:
543
+ * `withDbErrors` converts only DbErrors, so a driver's error passes through
544
+ * services unconverted to the boundary that answers the request.
545
+ */
546
+ static fromUnexpected(error) {
547
+ return NextlyError.busyOr(error, () => NextlyError.internal({ cause: error instanceof Error ? error : void 0 }));
548
+ }
549
+ /**
550
+ * "Database busy" when `error` is a request that waited out its bound for
551
+ * a connection, and `otherwise()` for anything else.
552
+ *
553
+ * For a boundary that answers an unexpected failure with an error of its
554
+ * own choosing rather than an internal one (a 503 for a flow that must not
555
+ * answer on incomplete data), so that a busy database still answers there
556
+ * as it does everywhere else. `fromUnexpected` is this rule with the
557
+ * internal error as its fallback.
558
+ */
559
+ static busyOr(error, otherwise) {
560
+ if (!isDatabaseBusy(error)) return otherwise();
561
+ return NextlyError.databaseBusy({ cause: error instanceof Error ? error : void 0 });
562
+ }
563
+ static internal(opts) {
564
+ return new NextlyError({
565
+ code: "INTERNAL_ERROR",
566
+ publicMessage: "An unexpected error occurred.",
567
+ cause: opts?.cause,
568
+ logContext: opts?.logContext
569
+ });
570
+ }
571
+ static serviceUnavailable(opts) {
572
+ return new NextlyError({
573
+ code: "SERVICE_UNAVAILABLE",
574
+ publicMessage: opts?.publicMessage ?? "Service unavailable. Please try again later.",
575
+ logMessage: opts?.logMessage,
576
+ cause: opts?.cause,
577
+ logContext: opts?.logContext
578
+ });
579
+ }
580
+ /**
581
+ * Convert a DbError (or arbitrary unknown thrown by the DB layer) to a
582
+ * NextlyError with a generic public message and rich logContext. Used by
583
+ * `withDbErrors` for auto-conversion (Pattern A) and by services that
584
+ * catch DB errors at boundaries (Pattern B). Spec §8.2 mapping table.
585
+ *
586
+ * Never leaks DB driver text, constraint names, or table names into
587
+ * `publicMessage`. All DB context goes into `logContext`. The original
588
+ * DbError is preserved as `cause`.
589
+ */
590
+ static fromDatabaseError(error) {
591
+ if (isDbError(error)) {
592
+ const mapping = DB_ERROR_MAPPING[error.kind];
593
+ const logContext = {
594
+ dbKind: error.kind,
595
+ dialect: error.dialect
596
+ };
597
+ if (error.code !== void 0) logContext.dbCode = error.code;
598
+ if (error.meta !== void 0) logContext.meta = error.meta;
599
+ return new NextlyError({
600
+ code: mapping.code,
601
+ statusCode: mapping.statusCode,
602
+ publicMessage: mapping.publicMessage,
603
+ publicData: "publicData" in mapping ? mapping.publicData : void 0,
604
+ logMessage: "Database error",
605
+ logContext,
606
+ cause: error
607
+ });
608
+ }
609
+ return new NextlyError({
610
+ code: "INTERNAL_ERROR",
611
+ statusCode: 500,
612
+ publicMessage: "An unexpected error occurred.",
613
+ logMessage: "Non-DbError passed to fromDatabaseError",
614
+ cause: error instanceof Error ? error : void 0,
615
+ logContext: error instanceof Error ? void 0 : { value: String(error) }
616
+ });
617
+ }
618
+ static is(err) {
619
+ return hasBrand(err);
620
+ }
621
+ static isCode(err, code) {
622
+ return hasBrand(err) && err.code === code;
623
+ }
624
+ static isNotFound(err) {
625
+ return NextlyError.isCode(err, "NOT_FOUND");
626
+ }
627
+ static isValidation(err) {
628
+ return NextlyError.isCode(err, "VALIDATION_ERROR");
629
+ }
630
+ static isAuthRequired(err) {
631
+ return NextlyError.isCode(err, "AUTH_REQUIRED");
632
+ }
633
+ static isForbidden(err) {
634
+ return NextlyError.isCode(err, "FORBIDDEN");
635
+ }
636
+ static isConflict(err) {
637
+ return NextlyError.isCode(err, "CONFLICT");
638
+ }
639
+ static isRateLimited(err) {
640
+ return NextlyError.isCode(err, "RATE_LIMITED");
641
+ }
642
+ };
643
+ // ../nextly/dist/get-trusted-client-ip-CYEbmLA3.mjs
644
+ /**
645
+ * A dotted-quad IPv4 address as an unsigned 32-bit integer, or null when it is
646
+ * not one. Shared by the client-address, refresh-binding and outbound-URL
647
+ * prefix checks.
648
+ */
649
+ function ipv4ToInt(ip) {
650
+ const parts = ip.split(".");
651
+ if (parts.length !== 4) return null;
652
+ let acc = 0;
653
+ for (const p of parts) {
654
+ const n = Number(p);
655
+ if (!Number.isInteger(n) || n < 0 || n > 255) return null;
656
+ acc = acc << 8 | n;
657
+ }
658
+ return acc >>> 0;
659
+ }
660
+ // ../nextly/dist/validate-external-url-uHUKFZGh.mjs
661
+ const IPV4_RE = /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;
662
+ /**
663
+ * IPv4 CIDR ranges that must NEVER be the destination of an outbound
664
+ * fetch sourced from a user-controllable URL. Listed roughly by RFC.
665
+ */
666
+ const PRIVATE_IPV4_CIDRS = [
667
+ "0.0.0.0/8",
668
+ "10.0.0.0/8",
669
+ "100.64.0.0/10",
670
+ "127.0.0.0/8",
671
+ "169.254.0.0/16",
672
+ "172.16.0.0/12",
673
+ "192.0.0.0/24",
674
+ "192.0.2.0/24",
675
+ "192.168.0.0/16",
676
+ "198.18.0.0/15",
677
+ "198.51.100.0/24",
678
+ "203.0.113.0/24",
679
+ "224.0.0.0/4",
680
+ "240.0.0.0/4"
681
+ ];
682
+ /**
683
+ * Cloud-metadata hostnames. These often resolve to private IPs and the
684
+ * private-IP block catches them, but we reject by hostname first so the
685
+ * error message is clear.
686
+ */
687
+ const CLOUD_METADATA_HOSTS = /* @__PURE__ */ new Set([
688
+ "metadata.google.internal",
689
+ "metadata.googleapis.com",
690
+ "metadata"
691
+ ]);
692
+ /**
693
+ * An outbound URL refused for SSRF safety. Extends `NextlyError` (the package's
694
+ * canonical error) so throw sites honor the error contract, while remaining a
695
+ * distinct class the callers (e.g. the form-builder webhook handler) match with
696
+ * `instanceof`.
697
+ */
698
+ var ExternalUrlError = class extends NextlyError {
699
+ url;
700
+ constructor(message, url) {
701
+ super({
702
+ code: "EXTERNAL_URL_BLOCKED",
703
+ publicMessage: message,
704
+ logContext: { url }
705
+ });
706
+ this.url = url;
707
+ this.name = "ExternalUrlError";
708
+ }
709
+ };
710
+ /** Validate a URL for outbound fetch. Throws `ExternalUrlError` on rejection. */
711
+ async function validateExternalUrl(rawUrl, options = {}) {
712
+ let parsed;
713
+ try {
714
+ parsed = new URL(rawUrl);
715
+ } catch {
716
+ throw new ExternalUrlError("Invalid URL", rawUrl);
717
+ }
718
+ const hostname = parsed.hostname.toLowerCase().replace(/^\[|\]$/g, "");
719
+ const isLocalhostHostname = hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1";
720
+ const baseProtocols = options.allowedProtocols ?? ["https:"];
721
+ const protocols = options.allowLocalhost && isLocalhostHostname ? [...baseProtocols, "http:"] : baseProtocols;
722
+ if (!protocols.includes(parsed.protocol)) throw new ExternalUrlError(`Protocol ${parsed.protocol} not allowed (allowed: ${protocols.join(", ")})`, rawUrl);
723
+ if (CLOUD_METADATA_HOSTS.has(hostname)) throw new ExternalUrlError(`Cloud-metadata hostname rejected: ${parsed.hostname}`, rawUrl);
724
+ if (IPV4_RE.test(hostname)) {
725
+ if (!isPublicIpv4(hostname, options.allowLocalhost === true && hostname === "127.0.0.1")) throw new ExternalUrlError(`Resolved to non-public IP: ${hostname}`, rawUrl);
726
+ return {
727
+ url: parsed,
728
+ pinnedIp: hostname,
729
+ family: 4
730
+ };
731
+ }
732
+ if (hostname.includes(":")) {
733
+ if (!isPublicIpv6(hostname, options.allowLocalhost === true && hostname === "::1")) throw new ExternalUrlError(`Resolved to non-public IP: ${hostname}`, rawUrl);
734
+ return {
735
+ url: parsed,
736
+ pinnedIp: hostname,
737
+ family: 6
738
+ };
739
+ }
740
+ const { lookup } = await import("node:dns/promises");
741
+ let addresses;
742
+ try {
743
+ addresses = await lookup(hostname, { all: true });
744
+ } catch (err) {
745
+ throw new ExternalUrlError(`DNS lookup failed: ${err.message}`, rawUrl);
746
+ }
747
+ if (addresses.length === 0) throw new ExternalUrlError("No IPs returned for host", rawUrl);
748
+ for (const { address, family } of addresses) {
749
+ const allow = options.allowLocalhost === true && isLocalhostHostname && family === 4;
750
+ if (!(family === 4 ? isPublicIpv4(address, allow) : isPublicIpv6(address, allow))) throw new ExternalUrlError(`Resolved to non-public IP: ${address}`, rawUrl);
751
+ }
752
+ const first = addresses[0];
753
+ return {
754
+ url: parsed,
755
+ pinnedIp: first.address,
756
+ family: first.family === 6 ? 6 : 4
757
+ };
758
+ }
759
+ /** Default response body cap: reject anything larger before buffering it all. */
760
+ /**
761
+ * How many bytes a bounded external read may buffer, absent a caller's own cap.
762
+ *
763
+ * Exported for the same reason as the deadline below: an adapter that never
764
+ * touches `safeFetch` still owes callers this default, and restating the number
765
+ * gives the tree two that drift.
766
+ */
767
+ const DEFAULT_MAX_RESPONSE_BYTES = 10485760;
768
+ /** Default overall deadline covering DNS + connect + TLS + response. */
769
+ /**
770
+ * How long a bounded external read may take, absent a caller's own limit.
771
+ *
772
+ * Exported so a caller that must begin the clock EARLIER — a storage adapter
773
+ * bounding a metadata lookup as well as the fetch that follows — uses this
774
+ * number rather than restating it. Two spellings of one default agree today and
775
+ * drift the first time either is tuned.
776
+ */
777
+ const DEFAULT_TIMEOUT_MS = 3e4;
778
+ /**
779
+ * Raised for fetch-phase failures that are NOT SSRF rejections: an over-large
780
+ * response body, the overall deadline elapsing, or an undecodable content
781
+ * encoding. Extends `NextlyError` (the canonical error contract) while staying a
782
+ * distinct class, so a caller can tell "URL refused for safety"
783
+ * (`ExternalUrlError`) apart from "the request itself failed".
784
+ */
785
+ var SafeFetchError = class extends NextlyError {
786
+ url;
787
+ reason;
788
+ status;
789
+ constructor(message, url, reason, status) {
790
+ super({
791
+ code: "EXTERNAL_REQUEST_FAILED",
792
+ publicMessage: message,
793
+ logContext: {
794
+ url,
795
+ reason
796
+ }
797
+ });
798
+ this.url = url;
799
+ this.reason = reason;
800
+ this.status = status;
801
+ this.name = "SafeFetchError";
802
+ }
803
+ };
804
+ /**
805
+ * Build a `dns.lookup`-compatible function that ignores the hostname and
806
+ * always resolves to `ip`/`family`. Handing this to `http(s).request` forces
807
+ * the socket to dial the exact address `validateExternalUrl` already vetted,
808
+ * closing the DNS-rebinding window where a second resolution at connect time
809
+ * could return a private IP. Not re-exported from the package barrel; exported
810
+ * for the plugin `ctx.fetch` transport, which pins its vetted address the same
811
+ * way, and so the rebinding invariant can be unit-tested directly.
812
+ */
813
+ function createPinnedLookup(ip, family) {
814
+ return (_hostname, options, callback) => {
815
+ if (options && options.all) callback(null, [{
816
+ address: ip,
817
+ family
818
+ }]);
819
+ else callback(null, ip, family);
820
+ };
821
+ }
822
+ /**
823
+ * Validate `rawUrl` then fetch it with the validated IP pinned at the socket.
824
+ * The convenience wrapper for the common case (webhook delivery, email
825
+ * attachment fetch). Node-runtime only.
826
+ *
827
+ * DNS is resolved once by `validateExternalUrl`; `createPinnedLookup` forces
828
+ * the connection to that same address, so an attacker's DNS cannot rebind the
829
+ * request to a private host between validation and connect. Redirects are not
830
+ * followed, the body is capped at `maxResponseBytes`, and the request is
831
+ * bounded by `timeoutMs`.
832
+ */
833
+ async function safeFetch(rawUrl, options = {}) {
834
+ const { allowLocalhost, allowedProtocols, method, headers, body, signal, maxResponseBytes = DEFAULT_MAX_RESPONSE_BYTES, timeoutMs = DEFAULT_TIMEOUT_MS } = options;
835
+ const controller = new AbortController();
836
+ const forwardAbort = () => controller.abort(signal?.reason);
837
+ if (signal) {
838
+ if (signal.aborted) controller.abort(signal.reason);
839
+ else signal.addEventListener("abort", forwardAbort, { once: true });
840
+ }
841
+ const timer = setTimeout(() => controller.abort(new SafeFetchError(`Request exceeded ${timeoutMs}ms`, rawUrl, "timeout")), timeoutMs);
842
+ try {
843
+ return await pinnedFetch(await abortable(validateExternalUrl(rawUrl, {
844
+ allowLocalhost,
845
+ allowedProtocols
846
+ }), controller.signal), {
847
+ method,
848
+ headers,
849
+ body,
850
+ signal: controller.signal,
851
+ maxResponseBytes
852
+ });
853
+ } finally {
854
+ clearTimeout(timer);
855
+ if (signal) signal.removeEventListener("abort", forwardAbort);
856
+ }
857
+ }
858
+ /**
859
+ * The signal's abort reason as an `Error`. Our own aborts carry a
860
+ * `SafeFetchError` (timeout); a caller's `AbortController.abort()` carries a
861
+ * DOMException `AbortError`; anything else (a non-Error reason) is surfaced as
862
+ * a standard `AbortError` so downstream `name === "AbortError"` checks hold.
863
+ */
864
+ function abortError(signal) {
865
+ const reason = signal.reason;
866
+ if (reason instanceof Error) return reason;
867
+ return new DOMException("The operation was aborted", "AbortError");
868
+ }
869
+ /**
870
+ * Resolve `promise`, but reject with the signal's reason if it aborts first.
871
+ * Lets a phase that runs before the request (DNS validation) share the overall
872
+ * deadline and caller cancellation.
873
+ */
874
+ function abortable(promise, signal) {
875
+ if (signal.aborted) return Promise.reject(abortError(signal));
876
+ let onAbort;
877
+ const aborted = new Promise((_resolve, reject) => {
878
+ onAbort = () => reject(abortError(signal));
879
+ signal.addEventListener("abort", onAbort, { once: true });
880
+ });
881
+ return Promise.race([promise, aborted]).finally(() => signal.removeEventListener("abort", onAbort));
882
+ }
883
+ /**
884
+ * Issue the request over `node:http`/`node:https` with the validated IP pinned
885
+ * via a custom `lookup`, then adapt the Node response into a WHATWG `Response`.
886
+ * `agent: false` forces a fresh socket per call so no pooled connection can
887
+ * reuse a differently-resolved address. The overall deadline is enforced by the
888
+ * caller through `init.signal`, so there is no separate timer here.
889
+ */
890
+ async function pinnedFetch(validated, init) {
891
+ const { url, pinnedIp, family } = validated;
892
+ const httpMod = url.protocol === "https:" ? await import("node:https") : await import("node:http");
893
+ const zlib = await import("node:zlib");
894
+ const lookup = createPinnedLookup(pinnedIp, family);
895
+ const outHeaders = toOutgoingHeaders(init.headers);
896
+ if (init.body != null) {
897
+ delete outHeaders["transfer-encoding"];
898
+ outHeaders["content-length"] = String(typeof init.body === "string" ? Buffer.byteLength(init.body) : init.body.byteLength);
899
+ }
900
+ return new Promise((resolve, reject) => {
901
+ let settled = false;
902
+ const settle = (fn) => {
903
+ if (settled) return;
904
+ settled = true;
905
+ fn();
906
+ };
907
+ const failure = (err) => init.signal.aborted ? abortError(init.signal) : err;
908
+ const req = httpMod.request(url, {
909
+ method: init.method ?? "GET",
910
+ headers: outHeaders,
911
+ lookup,
912
+ agent: false,
913
+ signal: init.signal
914
+ }, (res) => {
915
+ const chunks = [];
916
+ let received = 0;
917
+ res.on("data", (chunk) => {
918
+ received += chunk.length;
919
+ if (received > init.maxResponseBytes) {
920
+ res.destroy();
921
+ req.destroy();
922
+ settle(() => reject(new SafeFetchError(`Response body exceeded ${init.maxResponseBytes} bytes`, url.href, "response-too-large", res.statusCode)));
923
+ return;
924
+ }
925
+ chunks.push(chunk);
926
+ });
927
+ res.on("end", () => {
928
+ const decoded = decodeBody(Buffer.concat(chunks), res.headers["content-encoding"], zlib, init.maxResponseBytes, url.href, res.statusCode);
929
+ if (decoded instanceof SafeFetchError) {
930
+ settle(() => reject(decoded));
931
+ return;
932
+ }
933
+ settle(() => resolve(toWhatwgResponse(res, decoded.body, decoded.decoded)));
934
+ });
935
+ res.on("error", (err) => settle(() => reject(failure(err))));
936
+ });
937
+ req.on("error", (err) => settle(() => reject(failure(err))));
938
+ if (!req.destroyed) {
939
+ if (init.body != null) req.write(init.body);
940
+ req.end();
941
+ }
942
+ });
943
+ }
944
+ /**
945
+ * Normalize a `HeadersInit` into Node's outgoing-header shape. Header names are
946
+ * lowercased (they are case-insensitive) so later framing checks
947
+ * (`content-length`) and the Host strip are reliable regardless of caller
948
+ * casing. A caller-supplied `Host` is dropped: it is derived from the validated
949
+ * URL, and honoring an override would let Host-based routing reach an internal
950
+ * vhost behind a validated public IP, defeating the SSRF pin.
951
+ */
952
+ function toOutgoingHeaders(headers) {
953
+ const out = {};
954
+ if (!headers) return out;
955
+ const add = (rawKey, value) => {
956
+ const key = rawKey.toLowerCase();
957
+ if (key === "host") return;
958
+ const existing = out[key];
959
+ out[key] = existing === void 0 ? value : [].concat(existing, value);
960
+ };
961
+ if (headers instanceof Headers) headers.forEach((value, key) => add(key, value));
962
+ else if (Array.isArray(headers)) for (const [key, value] of headers) add(key, value);
963
+ else for (const [key, value] of Object.entries(headers)) add(key, value);
964
+ return out;
965
+ }
966
+ /**
967
+ * Adapt a Node `IncomingMessage` + buffered body into a WHATWG `Response`.
968
+ * Total by construction: a header the WHATWG layer rejects is skipped and the
969
+ * status is clamped to a constructible range, so this never throws (a throw
970
+ * would otherwise escape the `end` handler as an uncaught error).
971
+ */
972
+ function toWhatwgResponse(res, body, stripContentHeaders) {
973
+ const headers = new Headers();
974
+ for (const [key, value] of Object.entries(res.headers)) {
975
+ if (value == null) continue;
976
+ const lower = key.toLowerCase();
977
+ if (stripContentHeaders && (lower === "content-encoding" || lower === "content-length")) continue;
978
+ const values = Array.isArray(value) ? value : [value];
979
+ for (const v of values) try {
980
+ headers.append(key, v);
981
+ } catch {}
982
+ }
983
+ const raw = res.statusCode ?? 502;
984
+ const status = raw >= 200 && raw <= 599 ? raw : 502;
985
+ const nullBody = status === 204 || status === 205 || status === 304;
986
+ const bytes = new Uint8Array(body.byteLength);
987
+ bytes.set(body);
988
+ return new Response(nullBody ? null : bytes, {
989
+ status,
990
+ statusText: res.statusMessage ?? "",
991
+ headers
992
+ });
993
+ }
994
+ /**
995
+ * Content-decode a response body per its `Content-Encoding`. node:http returns
996
+ * raw wire bytes (unlike global fetch), so gzip/deflate/br bodies are inflated
997
+ * here to preserve the previous behavior. `maxOutputLength` bounds the inflated
998
+ * size, turning a decompression bomb into a `SafeFetchError` rather than an OOM.
999
+ * Returns the (possibly decoded) buffer, or a `SafeFetchError` on failure.
1000
+ */
1001
+ function decodeBody(buf, encoding, zlib, cap, url, status) {
1002
+ if (!encoding) return {
1003
+ body: buf,
1004
+ decoded: false
1005
+ };
1006
+ if (buf.length === 0) return {
1007
+ body: buf,
1008
+ decoded: true
1009
+ };
1010
+ const layers = encoding.split(",").map((e) => e.trim().toLowerCase()).filter(Boolean);
1011
+ const opts = { maxOutputLength: cap };
1012
+ let current = buf;
1013
+ let decoded = false;
1014
+ try {
1015
+ for (let i = layers.length - 1; i >= 0; i--) {
1016
+ const enc = layers[i];
1017
+ if (enc === "identity") continue;
1018
+ if (enc === "gzip" || enc === "x-gzip") current = zlib.gunzipSync(current, opts);
1019
+ else if (enc === "br") current = zlib.brotliDecompressSync(current, opts);
1020
+ else if (enc === "deflate") try {
1021
+ current = zlib.inflateSync(current, opts);
1022
+ } catch (inflateErr) {
1023
+ if (errorCode(inflateErr) === "ERR_BUFFER_TOO_LARGE") throw inflateErr;
1024
+ current = zlib.inflateRawSync(current, opts);
1025
+ }
1026
+ else {
1027
+ if (decoded) return new SafeFetchError(`Cannot fully decode content-encoding "${encoding}"`, url, "decode-failed", status);
1028
+ return {
1029
+ body: buf,
1030
+ decoded: false
1031
+ };
1032
+ }
1033
+ decoded = true;
1034
+ }
1035
+ return {
1036
+ body: current,
1037
+ decoded
1038
+ };
1039
+ } catch (err) {
1040
+ const tooLarge = errorCode(err) === "ERR_BUFFER_TOO_LARGE";
1041
+ return new SafeFetchError(tooLarge ? `Decoded ${encoding} response body exceeded the size cap` : `Failed to decode ${encoding} response body`, url, tooLarge ? "response-too-large" : "decode-failed", status);
1042
+ }
1043
+ }
1044
+ /** The `.code` of a Node system error, if present. */
1045
+ function errorCode(err) {
1046
+ if (err != null && typeof err === "object" && "code" in err) {
1047
+ const code = err.code;
1048
+ return typeof code === "string" ? code : void 0;
1049
+ }
1050
+ }
1051
+ function isIpv4InCidr(intIp, cidr) {
1052
+ const [addr, prefixRaw] = cidr.split("/");
1053
+ const intCidr = ipv4ToInt(addr);
1054
+ if (intCidr === null) return false;
1055
+ const prefix = Number(prefixRaw);
1056
+ if (!Number.isInteger(prefix) || prefix < 0 || prefix > 32) return false;
1057
+ const mask = prefix === 0 ? 0 : -1 >>> 32 - prefix << 32 - prefix;
1058
+ return (intIp & mask) >>> 0 === (intCidr & mask) >>> 0;
1059
+ }
1060
+ function isPublicIpv4(addr, allowLoopback) {
1061
+ const intIp = ipv4ToInt(addr);
1062
+ if (intIp === null) return false;
1063
+ if (allowLoopback && addr === "127.0.0.1") return true;
1064
+ for (const cidr of PRIVATE_IPV4_CIDRS) if (isIpv4InCidr(intIp, cidr)) return false;
1065
+ return true;
1066
+ }
1067
+ /**
1068
+ * Extract the embedded IPv4 of an IPv4-mapped IPv6 address, or null. Handles
1069
+ * both the dotted form (`::ffff:1.2.3.4`) and the hex form (`::ffff:7f00:1`)
1070
+ * that `URL.hostname` normalizes the dotted literal to — the latter would
1071
+ * otherwise skip the IPv4 denylist and pin, e.g., loopback as public.
1072
+ */
1073
+ function mappedIpv4(lower) {
1074
+ const dotted = lower.match(/^::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/);
1075
+ if (dotted) return dotted[1];
1076
+ const hex = lower.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
1077
+ if (hex) {
1078
+ const hi = parseInt(hex[1], 16);
1079
+ const lo = parseInt(hex[2], 16);
1080
+ return [
1081
+ hi >> 8,
1082
+ hi & 255,
1083
+ lo >> 8,
1084
+ lo & 255
1085
+ ].join(".");
1086
+ }
1087
+ return null;
1088
+ }
1089
+ function isPublicIpv6(addr, allowLoopback) {
1090
+ const lower = addr.toLowerCase();
1091
+ if (allowLoopback && lower === "::1") return true;
1092
+ const mapped = mappedIpv4(lower);
1093
+ if (mapped) return isPublicIpv4(mapped, allowLoopback);
1094
+ if (lower === "::" || lower === "::1") return false;
1095
+ const firstHextet = lower.split(":")[0] || "";
1096
+ if (firstHextet.startsWith("fc") || firstHextet.startsWith("fd")) return false;
1097
+ if (firstHextet.startsWith("fe8") || firstHextet.startsWith("fe9")) return false;
1098
+ if (firstHextet.startsWith("fea") || firstHextet.startsWith("feb")) return false;
1099
+ if (firstHextet.startsWith("ff")) return false;
1100
+ return true;
1101
+ }
1102
+ // ../nextly/dist/storage/read-errors.mjs
1103
+ /**
1104
+ * The one way the storage layer says a read exceeded the caller's cap.
1105
+ *
1106
+ * `StorageReadOptions.maxBytes` is part of the adapter contract, so what happens
1107
+ * when it is exceeded belongs to the contract too. Without this each backend
1108
+ * refuses in its own vocabulary — the URL-addressed ones through a fetch error
1109
+ * carrying a `reason`, S3 through whatever its own code threw — and a caller
1110
+ * wanting to tell "too large" from "could not read" has to know which adapter it
1111
+ * is talking to. That is the thing an adapter contract exists to stop.
1112
+ *
1113
+ * Distinct from a generic internal failure because callers ACT on the
1114
+ * difference. The email attachment path answers an over-cap read with
1115
+ * `ATTACHMENT_SIZE_EXCEEDED`, which tells an author to attach something smaller;
1116
+ * a storage failure tells them nothing they can act on. Collapsing the two turns
1117
+ * a fixable refusal into an opaque error, which is the same conflation this
1118
+ * contract already draws between a missing key and an unreachable store.
1119
+ *
1120
+ * @module storage/read-errors
1121
+ */
1122
+ /**
1123
+ * A read refused because the object is larger than the caller allowed.
1124
+ *
1125
+ * Carries the numbers rather than only a message, so a caller can say what the
1126
+ * limit was without parsing prose — and so the message itself stays free of the
1127
+ * key, which should not travel to whoever asked for the file.
1128
+ */
1129
+ var StorageReadTooLargeError = class extends NextlyError {
1130
+ path;
1131
+ maxBytes;
1132
+ size;
1133
+ constructor(path, maxBytes, size) {
1134
+ super({
1135
+ code: "STORAGE_READ_TOO_LARGE",
1136
+ publicMessage: "The stored file is larger than the limit for this read.",
1137
+ logContext: {
1138
+ path,
1139
+ maxBytes,
1140
+ ...size === void 0 ? {} : { size }
1141
+ }
1142
+ });
1143
+ this.path = path;
1144
+ this.maxBytes = maxBytes;
1145
+ this.size = size;
1146
+ }
1147
+ };
1148
+ // ../nextly/dist/storage/fetch-stored-bytes.mjs
1149
+ /**
1150
+ * Reading bytes back from a storage service that only exposes them over HTTP.
1151
+ *
1152
+ * The local adapter reads from disk and S3 reads through its own SDK, so
1153
+ * neither needs this. The services that address a file by URL — Vercel Blob,
1154
+ * UploadThing — all end up doing the same three things, and doing them the same
1155
+ * way matters more than it looks: each step below is a place where the obvious
1156
+ * shortcut reports the wrong thing to a caller who may act on it.
1157
+ *
1158
+ * Built on {@link safeFetch} rather than on a bare `fetch`, because "read a
1159
+ * remote object into memory" already has an implementation here that caps the
1160
+ * body, bounds the request and refuses an address that resolves somewhere
1161
+ * private. A second capped fetch beside it would be two answers to one
1162
+ * question, and the two would drift the first time either learned something.
1163
+ * Measured: it costs an adapter package about 80K, against the 1MB the whole
1164
+ * storage barrel costs.
1165
+ *
1166
+ * @module storage/fetch-stored-bytes
1167
+ */
1168
+ /**
1169
+ * Fetch a stored object's bytes from the URL its service issued.
1170
+ *
1171
+ * Separates the two answers a read can have, which is the whole reason this is
1172
+ * a function rather than three lines inlined twice.
1173
+ *
1174
+ * `null` means the object is NOT THERE — an ordinary fact about the store. A
1175
+ * 404 is that answer even when the lookup just succeeded: these stores are
1176
+ * remote and concurrent, so an object can be deleted between resolving its
1177
+ * address and fetching it. Reporting that ordinary race as a server failure
1178
+ * would make a caller handle an error for something its own contract already
1179
+ * has a value for.
1180
+ *
1181
+ * Anything else THROWS. A dropped connection, a 5xx or a refused request says
1182
+ * nothing about whether the object exists, and reporting it as absence invites
1183
+ * a caller to treat a live file as deleted and write a replacement over it. The
1184
+ * two are easy to state apart and easy to lose when the fetch sits inside the
1185
+ * same `try` that catches the lookup.
1186
+ *
1187
+ * The URL is always one the SERVICE issued, never one assembled from a key.
1188
+ * These stores mint addresses carrying suffixes the adapter never chose, so a
1189
+ * derived URL is a guess at a string another system owns.
1190
+ *
1191
+ * @param url - The address the storage service reported for this object
1192
+ * @param context - What is being read, for the error message: usually the key
1193
+ * @param label - The service's name, so a failure says which store answered
1194
+ * @param options - Bounds for the read; see {@link StorageReadOptions}
1195
+ * @param signal - A deadline ALREADY RUNNING, covering an earlier phase too
1196
+ * @returns The object's bytes, or `null` when the store answers 404
1197
+ */
1198
+ async function fetchStoredBytes(url, context, label, options, signal) {
1199
+ let response;
1200
+ try {
1201
+ response = await safeFetch(url, {
1202
+ ...options?.maxBytes === void 0 ? {} : { maxResponseBytes: options.maxBytes },
1203
+ ...signal !== void 0 ? { signal } : options?.timeoutMs === void 0 ? {} : { timeoutMs: options.timeoutMs }
1204
+ });
1205
+ } catch (error) {
1206
+ const verdict = classifyFetchFailure(error);
1207
+ if (verdict === "absent") return null;
1208
+ if (verdict === "oversized") throw new StorageReadTooLargeError(context, resolveReadBounds(options).maxBytes);
1209
+ throw error;
1210
+ }
1211
+ if (response.status === 404) return null;
1212
+ if (!response.ok) throw NextlyError.internal({ logContext: {
1213
+ service: label,
1214
+ path: context,
1215
+ status: response.status,
1216
+ statusText: response.statusText
1217
+ } });
1218
+ return Buffer.from(await response.arrayBuffer());
1219
+ }
1220
+ /**
1221
+ * What a failed fetch actually says about the object.
1222
+ *
1223
+ * Its own function because the three answers are the whole point of this module
1224
+ * and they are easy to collapse into each other — each collapse having been a
1225
+ * real defect here rather than a hypothetical:
1226
+ *
1227
+ * - ABSENT. A 404 is absence whatever size its body was. `safeFetch` caps while
1228
+ * buffering, so a verbose CDN error page raises before a `Response` exists
1229
+ * and the status check further down is never reached; the object is still
1230
+ * gone, and must not become an error because the page explaining it was long.
1231
+ * - OVERSIZED. Only a SUCCESSFUL response that blew the cap. A failed response
1232
+ * can exceed it too, and translating on the reason alone reported a backend
1233
+ * outage as "your file is too big" — a cause the author would act on, wrongly.
1234
+ * - UNKNOWN. Everything else, including a too-large refusal carrying NO status:
1235
+ * that means the failure arrived before any status did, which says nothing
1236
+ * about whether the object was oversized.
1237
+ */
1238
+ function classifyFetchFailure(error) {
1239
+ if (!(error instanceof SafeFetchError)) return "unknown";
1240
+ if (error.status === 404) return "absent";
1241
+ const successful = error.status !== void 0 && error.status >= 200 && error.status < 300;
1242
+ return error.reason === "response-too-large" && successful ? "oversized" : "unknown";
1243
+ }
1244
+ /** The deadline a stored read runs under when the caller names none. */
1245
+ const DEFAULT_READ_TIMEOUT_MS = DEFAULT_TIMEOUT_MS;
1246
+ /** The byte cap a stored read runs under when the caller names none. */
1247
+ const DEFAULT_READ_MAX_BYTES = DEFAULT_MAX_RESPONSE_BYTES;
1248
+ /**
1249
+ * The bounds a read actually runs under, defaults filled in.
1250
+ *
1251
+ * ONE place, because every adapter needs the same answer and the ones that
1252
+ * derived it themselves diverged: the URL-backed pair inherited `safeFetch`'s
1253
+ * cap and deadline for free, while the local and S3 adapters — which never
1254
+ * touch `safeFetch` — applied NO bound at all when the caller named none.
1255
+ * `StorageReadOptions` promises the default either way, and a production caller
1256
+ * reading media without options got it from two of four backends.
1257
+ *
1258
+ * Filling the defaults here rather than per adapter is what makes the promise
1259
+ * true by construction rather than by four implementations agreeing.
1260
+ */
1261
+ function resolveReadBounds(options) {
1262
+ return {
1263
+ maxBytes: options?.maxBytes ?? DEFAULT_READ_MAX_BYTES,
1264
+ timeoutMs: options?.timeoutMs ?? DEFAULT_READ_TIMEOUT_MS
1265
+ };
1266
+ }
5
1267
  // src/adapter.ts
1268
+ /**
1269
+ * Vercel Blob Storage Adapter
1270
+ *
1271
+ * Stores files on Vercel Blob Storage, a globally distributed object storage
1272
+ * service powered by Cloudflare R2. Optimized for Vercel deployments with
1273
+ * built-in CDN distribution.
1274
+ *
1275
+ * Features:
1276
+ * - Globally distributed CDN-backed storage
1277
+ * - Automatic file management with unique filenames
1278
+ * - Token-based authentication
1279
+ * - Client-side upload support (via handleUpload API)
1280
+ * - Serverless-friendly (no filesystem access required)
1281
+ *
1282
+ * @example Basic usage
1283
+ * ```typescript
1284
+ * const adapter = new VercelBlobStorageAdapter({
1285
+ * token: process.env.BLOB_READ_WRITE_TOKEN,
1286
+ * collections: { media: true }
1287
+ * });
1288
+ *
1289
+ * const result = await adapter.upload(buffer, {
1290
+ * filename: 'photo.jpg',
1291
+ * mimeType: 'image/jpeg'
1292
+ * });
1293
+ * // result.url: "https://abc123.public.blob.vercel-storage.com/photo-xyz.jpg"
1294
+ * ```
1295
+ */
1296
+ /**
1297
+ * Vercel Blob Storage Adapter
1298
+ *
1299
+ * Implements the IStorageAdapter interface for Vercel Blob Storage.
1300
+ * Provides file upload, deletion, existence checks, and metadata retrieval.
1301
+ */
6
1302
  var VercelBlobStorageAdapter = class {
7
- /**
8
- * Create a new Vercel Blob storage adapter.
9
- *
10
- * @param config - Vercel Blob storage configuration
11
- * @throws Error if token is not provided
12
- */
13
- constructor(config) {
14
- this.config = config;
15
- const token = config.token || process.env.BLOB_READ_WRITE_TOKEN || "";
16
- if (!token) {
17
- throw new Error(
18
- "@nextly/storage-vercel-blob: token is required.\n\nEither set the BLOB_READ_WRITE_TOKEN environment variable or pass token in config.\nGet your token from: Vercel Dashboard > Storage > Blob > Tokens"
19
- );
20
- }
21
- this.resolvedConfig = {
22
- token,
23
- addRandomSuffix: config.addRandomSuffix ?? true,
24
- cacheControlMaxAge: config.cacheControlMaxAge ?? 31536e3,
25
- access: config.access ?? "public",
26
- storeId: config.storeId,
27
- allowOverwrite: config.allowOverwrite ?? false,
28
- multipartThreshold: config.multipartThreshold ?? 5 * 1024 * 1024
29
- // 5MB
30
- };
31
- }
32
- resolvedConfig;
33
- // ============================================================
34
- // Core IStorageAdapter Methods
35
- // ============================================================
36
- /**
37
- * Upload file to Vercel Blob.
38
- *
39
- * Files are stored with globally distributed CDN backing.
40
- * By default, a random suffix is added to prevent filename collisions.
41
- *
42
- * @param buffer - File content as Buffer
43
- * @param options - Upload options (filename, mimeType, folder, collection)
44
- * @returns Upload result with URL and storage path
45
- */
46
- async upload(buffer, options) {
47
- const mimeType = (options.contentType || options.mimeType || "").toLowerCase().trim();
48
- const filename = (options.filename || "").toLowerCase();
49
- const ext = filename.includes(".") ? filename.slice(filename.lastIndexOf(".") + 1) : "";
50
- const isSvg = mimeType === "image/svg+xml" || ext === "svg" || ext === "svgz";
51
- const isHtml = mimeType === "text/html" || mimeType === "application/xhtml+xml" || ext === "html" || ext === "htm" || ext === "xhtml";
52
- if (isSvg || isHtml) {
53
- const kind = isSvg ? "SVG" : "HTML";
54
- throw new Error(
55
- `[nextly/storage-vercel-blob] ${kind} uploads are rejected on Vercel Blob \u2014 the platform cannot serve them with attachment-disposition or a restrictive CSP, so they would be stored XSS. Use the S3 / R2 adapter for ${kind} files, or convert to a raster format (PNG/WebP).`
56
- );
57
- }
58
- const pathname = this.buildPathname(options.filename, options.folder);
59
- const result = await blob.put(pathname, buffer, {
60
- access: this.resolvedConfig.access,
61
- token: this.resolvedConfig.token,
62
- contentType: options.contentType || options.mimeType,
63
- addRandomSuffix: this.resolvedConfig.addRandomSuffix,
64
- cacheControlMaxAge: this.resolvedConfig.cacheControlMaxAge
65
- });
66
- return {
67
- url: result.url,
68
- path: result.url
69
- };
70
- }
71
- /**
72
- * Delete file from Vercel Blob.
73
- *
74
- * @param filePath - Full blob URL to delete
75
- */
76
- async delete(filePath) {
77
- await blob.del(filePath, {
78
- token: this.resolvedConfig.token
79
- });
80
- }
81
- /**
82
- * Delete multiple files from Vercel Blob in chunked batches.
83
- *
84
- * Processes deletions in chunks of 10 concurrent calls using Promise.allSettled,
85
- * collecting successes and failures without short-circuiting.
86
- *
87
- * @param filePaths - Array of full blob URLs to delete
88
- * @returns BulkDeleteResult with successful and failed arrays
89
- */
90
- async bulkDelete(filePaths) {
91
- const successful = [];
92
- const failed = [];
93
- const chunkSize = 10;
94
- for (let i = 0; i < filePaths.length; i += chunkSize) {
95
- const chunk = filePaths.slice(i, i + chunkSize);
96
- const results = await Promise.allSettled(
97
- chunk.map((fp) => blob.del(fp, { token: this.resolvedConfig.token }))
98
- );
99
- results.forEach((result, idx) => {
100
- const fp = chunk[idx];
101
- if (result.status === "fulfilled") {
102
- successful.push(fp);
103
- } else {
104
- failed.push({
105
- filePath: fp,
106
- error: result.reason instanceof Error ? result.reason.message : String(result.reason)
107
- });
108
- }
109
- });
110
- }
111
- return { successful, failed };
112
- }
113
- /**
114
- * Check if file exists in Vercel Blob.
115
- *
116
- * Uses the head() function which is efficient for existence checks.
117
- *
118
- * @param filePath - Full blob URL to check
119
- * @returns true if file exists, false otherwise
120
- */
121
- async exists(filePath) {
122
- try {
123
- await blob.head(filePath, {
124
- token: this.resolvedConfig.token
125
- });
126
- return true;
127
- } catch {
128
- return false;
129
- }
130
- }
131
- /**
132
- * Get public URL for Vercel Blob file.
133
- *
134
- * Vercel Blob paths ARE the public URLs - they're already full HTTPS URLs
135
- * with CDN distribution.
136
- *
137
- * @param filePath - Full blob URL
138
- * @returns The same URL (Vercel Blob paths are already public URLs)
139
- */
140
- getPublicUrl(filePath) {
141
- return filePath;
142
- }
143
- /**
144
- * Get storage type identifier.
145
- */
146
- getType() {
147
- return "vercel-blob";
148
- }
149
- // ============================================================
150
- // Optional IStorageAdapter Methods
151
- // ============================================================
152
- /**
153
- * Get adapter info including capabilities.
154
- *
155
- * @returns Adapter info with type, name, and capability flags
156
- */
157
- getInfo() {
158
- return {
159
- type: "vercel-blob",
160
- name: "VercelBlobStorageAdapter",
161
- supportsSignedUrls: false,
162
- // Vercel Blob URLs are public by default
163
- supportsClientUploads: true
164
- // Via handleUpload API
165
- };
166
- }
167
- /**
168
- * Get file metadata from Vercel Blob.
169
- *
170
- * Retrieves file information including size, content type, and upload date.
171
- *
172
- * @param filePath - Full blob URL
173
- * @returns File metadata or null if file not found
174
- */
175
- async getMetadata(filePath) {
176
- try {
177
- const result = await blob.head(filePath, {
178
- token: this.resolvedConfig.token
179
- });
180
- const filename = result.pathname.split("/").pop() || result.pathname;
181
- return {
182
- id: filePath,
183
- filename,
184
- originalFilename: filename,
185
- mimeType: result.contentType,
186
- size: result.size,
187
- url: result.url,
188
- createdAt: result.uploadedAt.toISOString()
189
- };
190
- } catch {
191
- return null;
192
- }
193
- }
194
- /**
195
- * Generate pre-signed URL for client-side uploads.
196
- *
197
- * Vercel Blob uses a different pattern for client uploads - they require
198
- * the handleUpload API which handles token generation server-side.
199
- *
200
- * This method is not implemented because Vercel Blob's client upload flow
201
- * requires server-side route handlers with handleUpload().
202
- *
203
- * @see https://vercel.com/docs/storage/vercel-blob/client-upload
204
- * @throws Error always - client uploads require handleUpload API
205
- */
206
- getPresignedUploadUrl(_key, _mimeType, _expiresIn) {
207
- return Promise.reject(
208
- new Error(
209
- "@nextly/storage-vercel-blob: Client uploads require the handleUpload API.\n\nVercel Blob uses a different pattern for client-side uploads that involves:\n1. A server-side route handler with handleUpload()\n2. The @vercel/blob/client upload() function\n\nSee: https://vercel.com/docs/storage/vercel-blob/client-upload\n\nFor server-side uploads, use the standard upload() method instead."
210
- )
211
- );
212
- }
213
- // ============================================================
214
- // Additional Methods
215
- // ============================================================
216
- /**
217
- * List blobs with optional prefix filter.
218
- *
219
- * Useful for browsing or batch operations on stored files.
220
- *
221
- * @param prefix - Optional prefix to filter results
222
- * @param options - List options (limit, cursor)
223
- * @returns List of blob metadata
224
- */
225
- async listBlobs(prefix, options) {
226
- const result = await blob.list({
227
- token: this.resolvedConfig.token,
228
- prefix,
229
- limit: options?.limit,
230
- cursor: options?.cursor
231
- });
232
- return {
233
- blobs: result.blobs.map((blob) => ({
234
- url: blob.url,
235
- pathname: blob.pathname,
236
- size: blob.size,
237
- uploadedAt: blob.uploadedAt
238
- })),
239
- hasMore: result.hasMore,
240
- cursor: result.cursor
241
- };
242
- }
243
- // ============================================================
244
- // Helper Methods
245
- // ============================================================
246
- /**
247
- * Build pathname for Vercel Blob upload.
248
- *
249
- * Creates pathname in format: {folder}/{filename}
250
- * If no folder is provided, uses the filename directly.
251
- *
252
- * @param filename - Original filename (will be sanitized)
253
- * @param folder - Optional folder/prefix for organizing uploads
254
- * @returns Generated pathname
255
- * @throws Error if folder fails sanitization
256
- */
257
- buildPathname(filename, folder) {
258
- const sanitized = this.sanitizeFilename(filename);
259
- if (!folder) return sanitized;
260
- return `${this.sanitizeFolder(folder)}/${sanitized}`;
261
- }
262
- /**
263
- * Sanitize filename to prevent path traversal issues.
264
- *
265
- * @param filename - Original filename
266
- * @returns Sanitized filename
267
- */
268
- sanitizeFilename(filename) {
269
- const basename = filename.split(/[/\\]/).pop() || filename;
270
- return basename.replace(/[^a-zA-Z0-9._-]/g, "-");
271
- }
272
- /**
273
- * Reject folder values that would let a caller
274
- * escape the configured prefix via path traversal or weird
275
- * separators. Vercel Blob is flat-keyed so `/` is just part of the
276
- * pathname, but an attacker who controls `folder` could still:
277
- *
278
- * - Use `..` to chain a relative-traversal-style key.
279
- * - Use `\` (Windows separator) to confuse downstream tooling.
280
- * - Use control chars / null bytes to truncate the key.
281
- * - Use a leading `/` to look like an absolute path.
282
- *
283
- * Internal `/` segments stay allowed because callers legitimately
284
- * use nested folders (`docs/2026/...`); a leading `/`, empty
285
- * segments (`docs//x`), or `..` segments are rejected.
286
- *
287
- * @throws Error with a stable message so the storage facade can
288
- * surface a 400 instead of a 500.
289
- */
290
- sanitizeFolder(folder) {
291
- const trimmed = folder.replace(/\/+$/, "");
292
- if (!trimmed) {
293
- throw new Error("Folder must be a non-empty string.");
294
- }
295
- if (/[\\\0\x01-\x1f\x7f]/.test(trimmed)) {
296
- throw new Error(
297
- "Folder contains forbidden characters (backslash, control chars, or null bytes)."
298
- );
299
- }
300
- if (trimmed.startsWith("/")) {
301
- throw new Error("Folder must not start with `/`.");
302
- }
303
- const segments = trimmed.split("/");
304
- for (const segment of segments) {
305
- if (segment === "") {
306
- throw new Error("Folder must not contain empty segments (`//`).");
307
- }
308
- if (segment === "..") {
309
- throw new Error("Folder must not contain `..` segments.");
310
- }
311
- }
312
- return trimmed;
313
- }
314
- // ============================================================
315
- // Public Accessors
316
- // ============================================================
317
- /**
318
- * Get the configured token (masked for logging).
319
- */
320
- getTokenMasked() {
321
- const token = this.resolvedConfig.token;
322
- if (token.length <= 8) return "****";
323
- return `${token.slice(0, 4)}...${token.slice(-4)}`;
324
- }
325
- /**
326
- * Check if random suffix is enabled.
327
- */
328
- hasRandomSuffix() {
329
- return this.resolvedConfig.addRandomSuffix;
330
- }
331
- /**
332
- * Get configured cache control max age.
333
- */
334
- getCacheControlMaxAge() {
335
- return this.resolvedConfig.cacheControlMaxAge;
336
- }
1303
+ config;
1304
+ resolvedConfig;
1305
+ /**
1306
+ * Create a new Vercel Blob storage adapter.
1307
+ *
1308
+ * @param config - Vercel Blob storage configuration
1309
+ * @throws Error if token is not provided
1310
+ */
1311
+ constructor(config) {
1312
+ this.config = config;
1313
+ const token = config.token || process.env.BLOB_READ_WRITE_TOKEN || "";
1314
+ if (!token) throw new Error("@nextly/storage-vercel-blob: token is required.\n\nEither set the BLOB_READ_WRITE_TOKEN environment variable or pass token in config.\nGet your token from: Vercel Dashboard > Storage > Blob > Tokens");
1315
+ this.resolvedConfig = {
1316
+ token,
1317
+ addRandomSuffix: config.addRandomSuffix ?? true,
1318
+ cacheControlMaxAge: config.cacheControlMaxAge ?? 31536e3,
1319
+ access: config.access ?? "public",
1320
+ storeId: config.storeId,
1321
+ allowOverwrite: config.allowOverwrite ?? false,
1322
+ multipartThreshold: config.multipartThreshold ?? 5242880
1323
+ };
1324
+ }
1325
+ /**
1326
+ * Upload file to Vercel Blob.
1327
+ *
1328
+ * Files are stored with globally distributed CDN backing.
1329
+ * By default, a random suffix is added to prevent filename collisions.
1330
+ *
1331
+ * @param buffer - File content as Buffer
1332
+ * @param options - Upload options (filename, mimeType, folder, collection)
1333
+ * @returns Upload result with URL and storage path
1334
+ */
1335
+ async upload(buffer, options) {
1336
+ const mimeType = (options.contentType || options.mimeType || "").toLowerCase().trim();
1337
+ const filename = (options.filename || "").toLowerCase();
1338
+ const ext = filename.includes(".") ? filename.slice(filename.lastIndexOf(".") + 1) : "";
1339
+ if (mimeType === "text/html" || mimeType === "application/xhtml+xml" || ext === "html" || ext === "htm" || ext === "xhtml") throw NextlyError.validation({
1340
+ errors: [{
1341
+ path: "file",
1342
+ code: "UNSUPPORTED_FOR_BACKEND",
1343
+ message: "HTML files cannot be hosted on Vercel Blob. Use the S3 or R2 adapter, or upload as another format."
1344
+ }],
1345
+ logContext: {
1346
+ adapter: "vercel-blob",
1347
+ claimedMimeType: options.mimeType,
1348
+ reason: "vercel-blob-rejects-html",
1349
+ filename: options.filename
1350
+ }
1351
+ });
1352
+ const isSvg = mimeType === "image/svg+xml" || ext === "svg" || ext === "svgz";
1353
+ const pathname = this.buildPathname(options.filename, options.folder);
1354
+ const result = await (0, _vercel_blob.put)(pathname, buffer, {
1355
+ access: this.resolvedConfig.access,
1356
+ token: this.resolvedConfig.token,
1357
+ contentType: options.contentType || options.mimeType,
1358
+ addRandomSuffix: this.resolvedConfig.addRandomSuffix,
1359
+ cacheControlMaxAge: this.resolvedConfig.cacheControlMaxAge
1360
+ });
1361
+ return {
1362
+ url: isSvg && options.contentDisposition === "attachment" ? result.downloadUrl : result.url,
1363
+ path: result.url
1364
+ };
1365
+ }
1366
+ /**
1367
+ * Delete file from Vercel Blob.
1368
+ *
1369
+ * @param filePath - Full blob URL to delete
1370
+ */
1371
+ async delete(filePath) {
1372
+ await (0, _vercel_blob.del)(filePath, { token: this.resolvedConfig.token });
1373
+ }
1374
+ /**
1375
+ * Delete multiple files from Vercel Blob in chunked batches.
1376
+ *
1377
+ * Processes deletions in chunks of 10 concurrent calls using Promise.allSettled,
1378
+ * collecting successes and failures without short-circuiting.
1379
+ *
1380
+ * @param filePaths - Array of full blob URLs to delete
1381
+ * @returns BulkDeleteResult with successful and failed arrays
1382
+ */
1383
+ async bulkDelete(filePaths) {
1384
+ const successful = [];
1385
+ const failed = [];
1386
+ const chunkSize = 10;
1387
+ for (let i = 0; i < filePaths.length; i += chunkSize) {
1388
+ const chunk = filePaths.slice(i, i + chunkSize);
1389
+ (await Promise.allSettled(chunk.map((fp) => (0, _vercel_blob.del)(fp, { token: this.resolvedConfig.token })))).forEach((result, idx) => {
1390
+ const fp = chunk[idx];
1391
+ if (result.status === "fulfilled") successful.push(fp);
1392
+ else failed.push({
1393
+ filePath: fp,
1394
+ error: result.reason instanceof Error ? result.reason.message : String(result.reason)
1395
+ });
1396
+ });
1397
+ }
1398
+ return {
1399
+ successful,
1400
+ failed
1401
+ };
1402
+ }
1403
+ /**
1404
+ * Check if file exists in Vercel Blob.
1405
+ *
1406
+ * Uses the head() function which is efficient for existence checks.
1407
+ *
1408
+ * @param filePath - Full blob URL to check
1409
+ * @returns true if file exists, false otherwise
1410
+ */
1411
+ async exists(filePath) {
1412
+ try {
1413
+ await (0, _vercel_blob.head)(filePath, { token: this.resolvedConfig.token });
1414
+ return true;
1415
+ } catch {
1416
+ return false;
1417
+ }
1418
+ }
1419
+ /**
1420
+ * Read a stored blob back as bytes, or `null` when it is not there.
1421
+ *
1422
+ * A NETWORK round trip, unlike the local adapter's disk read, because the
1423
+ * bytes live on Vercel's CDN and there is no other way to reach them. That
1424
+ * cost is the reason a caller serving these from its own origin has to cache:
1425
+ * the privacy rule that forces same-origin serving does not also make the
1426
+ * fetch free, and an uncached proxy pays it on every request.
1427
+ *
1428
+ * The URL is taken from `head` rather than assembled from `filePath`,
1429
+ * because a blob's address is issued by the service — it carries a random
1430
+ * suffix this adapter never chose — so deriving one here would be guessing at
1431
+ * a string another system owns.
1432
+ *
1433
+ * `null` for a missing blob rather than a throw, matching {@link exists}.
1434
+ *
1435
+ * @param filePath - Blob path/key
1436
+ * @returns The blob's bytes, or `null` when it does not exist
1437
+ */
1438
+ async read(filePath, options) {
1439
+ const deadline = AbortSignal.timeout(options?.timeoutMs ?? DEFAULT_READ_TIMEOUT_MS);
1440
+ let target;
1441
+ try {
1442
+ const meta = await (0, _vercel_blob.head)(filePath, {
1443
+ token: this.resolvedConfig.token,
1444
+ abortSignal: deadline
1445
+ });
1446
+ target = meta.downloadUrl ?? meta.url;
1447
+ } catch (error) {
1448
+ if (error instanceof _vercel_blob.BlobNotFoundError) return null;
1449
+ throw error;
1450
+ }
1451
+ return await fetchStoredBytes(target, filePath, "Vercel Blob", options, deadline);
1452
+ }
1453
+ /**
1454
+ * Get public URL for Vercel Blob file.
1455
+ *
1456
+ * Vercel Blob paths ARE the public URLs - they're already full HTTPS URLs
1457
+ * with CDN distribution.
1458
+ *
1459
+ * @param filePath - Full blob URL
1460
+ * @returns The same URL (Vercel Blob paths are already public URLs)
1461
+ */
1462
+ /**
1463
+ * Every blob in the store, by its URL (which is its stored path here), with
1464
+ * when it was uploaded, a page at a time.
1465
+ */
1466
+ async *list() {
1467
+ let cursor;
1468
+ do {
1469
+ const page = await this.listBlobs(void 0, { cursor });
1470
+ for (const blob of page.blobs) yield {
1471
+ path: blob.url,
1472
+ lastModified: blob.uploadedAt
1473
+ };
1474
+ cursor = page.hasMore ? page.cursor : void 0;
1475
+ } while (cursor);
1476
+ }
1477
+ getPublicUrl(filePath) {
1478
+ return filePath;
1479
+ }
1480
+ /**
1481
+ * Get storage type identifier.
1482
+ */
1483
+ getType() {
1484
+ return "vercel-blob";
1485
+ }
1486
+ /**
1487
+ * Get adapter info including capabilities.
1488
+ *
1489
+ * @returns Adapter info with type, name, and capability flags
1490
+ */
1491
+ getInfo() {
1492
+ return {
1493
+ type: "vercel-blob",
1494
+ name: "VercelBlobStorageAdapter",
1495
+ supportsSignedUrls: false,
1496
+ supportsClientUploads: true
1497
+ };
1498
+ }
1499
+ /**
1500
+ * Get file metadata from Vercel Blob.
1501
+ *
1502
+ * Retrieves file information including size, content type, and upload date.
1503
+ *
1504
+ * @param filePath - Full blob URL
1505
+ * @returns File metadata or null if file not found
1506
+ */
1507
+ async getMetadata(filePath) {
1508
+ try {
1509
+ const result = await (0, _vercel_blob.head)(filePath, { token: this.resolvedConfig.token });
1510
+ const filename = result.pathname.split("/").pop() || result.pathname;
1511
+ return {
1512
+ id: filePath,
1513
+ filename,
1514
+ originalFilename: filename,
1515
+ mimeType: result.contentType,
1516
+ size: result.size,
1517
+ url: result.url,
1518
+ createdAt: result.uploadedAt.toISOString()
1519
+ };
1520
+ } catch {
1521
+ return null;
1522
+ }
1523
+ }
1524
+ /**
1525
+ * Generate pre-signed URL for client-side uploads.
1526
+ *
1527
+ * Vercel Blob uses a different pattern for client uploads - they require
1528
+ * the handleUpload API which handles token generation server-side.
1529
+ *
1530
+ * This method is not implemented because Vercel Blob's client upload flow
1531
+ * requires server-side route handlers with handleUpload().
1532
+ *
1533
+ * @see https://vercel.com/docs/storage/vercel-blob/client-upload
1534
+ * @throws Error always - client uploads require handleUpload API
1535
+ */
1536
+ getPresignedUploadUrl(_key, _mimeType, _expiresIn) {
1537
+ return Promise.reject(/* @__PURE__ */ new Error("@nextly/storage-vercel-blob: Client uploads require the handleUpload API.\n\nVercel Blob uses a different pattern for client-side uploads that involves:\n1. A server-side route handler with handleUpload()\n2. The @vercel/blob/client upload() function\n\nSee: https://vercel.com/docs/storage/vercel-blob/client-upload\n\nFor server-side uploads, use the standard upload() method instead."));
1538
+ }
1539
+ /**
1540
+ * List blobs with optional prefix filter.
1541
+ *
1542
+ * Useful for browsing or batch operations on stored files.
1543
+ *
1544
+ * @param prefix - Optional prefix to filter results
1545
+ * @param options - List options (limit, cursor)
1546
+ * @returns List of blob metadata
1547
+ */
1548
+ async listBlobs(prefix, options) {
1549
+ const result = await (0, _vercel_blob.list)({
1550
+ token: this.resolvedConfig.token,
1551
+ prefix,
1552
+ limit: options?.limit,
1553
+ cursor: options?.cursor
1554
+ });
1555
+ return {
1556
+ blobs: result.blobs.map((blob) => ({
1557
+ url: blob.url,
1558
+ pathname: blob.pathname,
1559
+ size: blob.size,
1560
+ uploadedAt: blob.uploadedAt
1561
+ })),
1562
+ hasMore: result.hasMore,
1563
+ cursor: result.cursor
1564
+ };
1565
+ }
1566
+ /**
1567
+ * Build pathname for Vercel Blob upload.
1568
+ *
1569
+ * Creates pathname in format: {folder}/{filename}
1570
+ * If no folder is provided, uses the filename directly.
1571
+ *
1572
+ * @param filename - Original filename (will be sanitized)
1573
+ * @param folder - Optional folder/prefix for organizing uploads
1574
+ * @returns Generated pathname
1575
+ * @throws Error if folder fails sanitization
1576
+ */
1577
+ buildPathname(filename, folder) {
1578
+ const sanitized = this.sanitizeFilename(filename);
1579
+ if (!folder) return sanitized;
1580
+ return `${this.sanitizeFolder(folder)}/${sanitized}`;
1581
+ }
1582
+ /**
1583
+ * Sanitize filename to prevent path traversal issues.
1584
+ *
1585
+ * @param filename - Original filename
1586
+ * @returns Sanitized filename
1587
+ */
1588
+ sanitizeFilename(filename) {
1589
+ return (filename.split(/[/\\]/).pop() || filename).replace(/[^a-zA-Z0-9._-]/g, "-");
1590
+ }
1591
+ /**
1592
+ * Reject folder values that would let a caller
1593
+ * escape the configured prefix via path traversal or weird
1594
+ * separators. Vercel Blob is flat-keyed so `/` is just part of the
1595
+ * pathname, but an attacker who controls `folder` could still:
1596
+ *
1597
+ * - Use `..` to chain a relative-traversal-style key.
1598
+ * - Use `\` (Windows separator) to confuse downstream tooling.
1599
+ * - Use control chars / null bytes to truncate the key.
1600
+ * - Use a leading `/` to look like an absolute path.
1601
+ *
1602
+ * Internal `/` segments stay allowed because callers legitimately
1603
+ * use nested folders (`docs/2026/...`); a leading `/`, empty
1604
+ * segments (`docs//x`), or `..` segments are rejected.
1605
+ *
1606
+ * @throws Error with a stable message so the storage facade can
1607
+ * surface a 400 instead of a 500.
1608
+ */
1609
+ sanitizeFolder(folder) {
1610
+ const trimmed = folder.replace(/\/+$/, "");
1611
+ if (!trimmed) throw new Error("Folder must be a non-empty string.");
1612
+ if (/[\\\0\x01-\x1f\x7f]/.test(trimmed)) throw new Error("Folder contains forbidden characters (backslash, control chars, or null bytes).");
1613
+ if (trimmed.startsWith("/")) throw new Error("Folder must not start with `/`.");
1614
+ const segments = trimmed.split("/");
1615
+ for (const segment of segments) {
1616
+ if (segment === "") throw new Error("Folder must not contain empty segments (`//`).");
1617
+ if (segment === "..") throw new Error("Folder must not contain `..` segments.");
1618
+ }
1619
+ return trimmed;
1620
+ }
1621
+ /**
1622
+ * Get the configured token (masked for logging).
1623
+ */
1624
+ getTokenMasked() {
1625
+ const token = this.resolvedConfig.token;
1626
+ if (token.length <= 8) return "****";
1627
+ return `${token.slice(0, 4)}...${token.slice(-4)}`;
1628
+ }
1629
+ /**
1630
+ * Check if random suffix is enabled.
1631
+ */
1632
+ hasRandomSuffix() {
1633
+ return this.resolvedConfig.addRandomSuffix;
1634
+ }
1635
+ /**
1636
+ * Get configured cache control max age.
1637
+ */
1638
+ getCacheControlMaxAge() {
1639
+ return this.resolvedConfig.cacheControlMaxAge;
1640
+ }
337
1641
  };
338
-
339
1642
  // src/plugin.ts
1643
+ /**
1644
+ * Create a Vercel Blob storage plugin for Nextly.
1645
+ *
1646
+ * This factory function creates a StoragePlugin that can be added to
1647
+ * the `storage` array in `nextly.config.ts`. Vercel Blob is optimized
1648
+ * for Vercel deployments with:
1649
+ *
1650
+ * - Global CDN distribution
1651
+ * - Simple token-based authentication
1652
+ * - Client-side upload support (via handleUpload API)
1653
+ * - Automatic file management
1654
+ *
1655
+ * @param config - Vercel Blob storage configuration
1656
+ * @returns A StoragePlugin that MediaStorage can register
1657
+ *
1658
+ * @throws Error if token is not provided (via adapter)
1659
+ */
340
1660
  function vercelBlobStorage(config) {
341
- if (config.enabled === false) {
342
- return {
343
- name: "vercel-blob-storage",
344
- type: "vercel-blob",
345
- collections: {},
346
- adapter: null
347
- };
348
- }
349
- const adapter = new VercelBlobStorageAdapter(config);
350
- const plugin = {
351
- name: "vercel-blob-storage",
352
- type: "vercel-blob",
353
- collections: config.collections,
354
- adapter,
355
- /**
356
- * Generate upload URL for client-side uploads.
357
- *
358
- * Note: Vercel Blob uses a different pattern for client uploads.
359
- * Instead of pre-signed URLs, it uses the handleUpload() API which
360
- * requires server-side route handlers.
361
- *
362
- * This method throws an error explaining the correct approach.
363
- *
364
- * @see https://vercel.com/docs/storage/vercel-blob/client-upload
365
- */
366
- getClientUploadUrl(_filename, _mimeType, _collection) {
367
- return Promise.reject(
368
- new Error(
369
- "@nextly/storage-vercel-blob: Client uploads require the handleUpload API.\n\nVercel Blob uses a different pattern than S3 for client-side uploads:\n\n1. Create a server-side route handler with handleUpload()\n2. Use upload() from @vercel/blob/client on the frontend\n\nSee: https://vercel.com/docs/storage/vercel-blob/client-upload"
370
- )
371
- );
372
- },
373
- /**
374
- * Get signed download URL for file access.
375
- *
376
- * Note: Vercel Blob URLs are public by default and do not support
377
- * signed/temporary URLs. All uploaded blobs are accessible via their
378
- * public URL.
379
- *
380
- * @param path - Storage path (full blob URL)
381
- * @returns The same URL (Vercel Blob URLs are public)
382
- */
383
- getSignedDownloadUrl(path) {
384
- return Promise.resolve(path);
385
- }
386
- };
387
- return plugin;
1661
+ if (config.enabled === false) return {
1662
+ name: "vercel-blob-storage",
1663
+ type: "vercel-blob",
1664
+ collections: {},
1665
+ adapter: null
1666
+ };
1667
+ const adapter = new VercelBlobStorageAdapter(config);
1668
+ return {
1669
+ name: "vercel-blob-storage",
1670
+ type: "vercel-blob",
1671
+ collections: config.collections,
1672
+ adapter,
1673
+ /**
1674
+ * Generate upload URL for client-side uploads.
1675
+ *
1676
+ * Note: Vercel Blob uses a different pattern for client uploads.
1677
+ * Instead of pre-signed URLs, it uses the handleUpload() API which
1678
+ * requires server-side route handlers.
1679
+ *
1680
+ * This method throws an error explaining the correct approach.
1681
+ *
1682
+ * @see https://vercel.com/docs/storage/vercel-blob/client-upload
1683
+ */
1684
+ getClientUploadUrl(_filename, _mimeType, _collection) {
1685
+ return Promise.reject(/* @__PURE__ */ new Error("@nextly/storage-vercel-blob: Client uploads require the handleUpload API.\n\nVercel Blob uses a different pattern than S3 for client-side uploads:\n\n1. Create a server-side route handler with handleUpload()\n2. Use upload() from @vercel/blob/client on the frontend\n\nSee: https://vercel.com/docs/storage/vercel-blob/client-upload"));
1686
+ },
1687
+ /**
1688
+ * Get signed download URL for file access.
1689
+ *
1690
+ * Note: Vercel Blob URLs are public by default and do not support
1691
+ * signed/temporary URLs. All uploaded blobs are accessible via their
1692
+ * public URL.
1693
+ *
1694
+ * @param path - Storage path (full blob URL)
1695
+ * @returns The same URL (Vercel Blob URLs are public)
1696
+ */
1697
+ getSignedDownloadUrl(path) {
1698
+ return Promise.resolve(path);
1699
+ }
1700
+ };
388
1701
  }
389
-
390
1702
  // src/index.ts
391
- var PACKAGE_NAME = "@nextly/storage-vercel-blob";
392
- var PACKAGE_VERSION = "0.1.0";
393
-
1703
+ const PACKAGE_NAME = "@nextly/storage-vercel-blob";
1704
+ const PACKAGE_VERSION = "0.1.0";
394
1705
  exports.PACKAGE_NAME = PACKAGE_NAME;
395
1706
  exports.PACKAGE_VERSION = PACKAGE_VERSION;
396
1707
  exports.VercelBlobStorageAdapter = VercelBlobStorageAdapter;
397
1708
  exports.vercelBlobStorage = vercelBlobStorage;
398
- //# sourceMappingURL=index.cjs.map
1709
+
399
1710
  //# sourceMappingURL=index.cjs.map