@nextlyhq/storage-vercel-blob 0.0.2-alpha.6 → 0.0.2-alpha.62

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
@@ -2,6 +2,433 @@
2
2
 
3
3
  var blob = require('@vercel/blob');
4
4
 
5
+ // src/adapter.ts
6
+
7
+ // ../nextly/dist/chunk-SAEVUREH.mjs
8
+ function isDbError(err) {
9
+ if (!err || typeof err !== "object") return false;
10
+ const obj = err;
11
+ return obj.name === "DbError" && typeof obj.kind === "string";
12
+ }
13
+ var NEXTLY_ERROR_STATUS = {
14
+ VALIDATION_ERROR: 400,
15
+ INVALID_INPUT: 400,
16
+ AUTH_REQUIRED: 401,
17
+ AUTH_INVALID_CREDENTIALS: 401,
18
+ TOKEN_EXPIRED: 401,
19
+ FORBIDDEN: 403,
20
+ // The schema builder is off in this environment (production by default).
21
+ // Separate from FORBIDDEN: the caller's permissions are not the problem.
22
+ BUILDER_DISABLED: 403,
23
+ NOT_FOUND: 404,
24
+ CONFLICT: 409,
25
+ DUPLICATE: 409,
26
+ RATE_LIMITED: 429,
27
+ PAYLOAD_TOO_LARGE: 413,
28
+ UNSUPPORTED_MEDIA_TYPE: 415,
29
+ // 422: understood, well-formed, and refused on a rule the caller can act on.
30
+ // Deliberately NOT added to CANONICAL_CODE_FOR_STATUS -- that list drives the
31
+ // status -> code direction, where 422 stays mapped to INVALID_INPUT.
32
+ BUSINESS_RULE_VIOLATION: 422,
33
+ INTERNAL_ERROR: 500,
34
+ DATABASE_ERROR: 500,
35
+ EXTERNAL_SERVICE_ERROR: 502,
36
+ SERVICE_UNAVAILABLE: 503,
37
+ // Outbound-fetch safety (utils/validate-external-url): a URL refused for SSRF
38
+ // safety, and a fetch that timed out / exceeded the size cap / failed to decode.
39
+ EXTERNAL_URL_BLOCKED: 400,
40
+ EXTERNAL_REQUEST_FAILED: 502,
41
+ FILENAME_INVALID: 400,
42
+ EXTENSION_BLOCKED: 400,
43
+ MIME_BLOCKED: 415,
44
+ MIME_NOT_ALLOWED: 415,
45
+ SIZE_EXCEEDED: 413,
46
+ MAGIC_BYTE_MISMATCH: 400,
47
+ SVG_SANITIZATION_FAILED: 400,
48
+ UNSUPPORTED_FOR_BACKEND: 415,
49
+ // Plan B — schema bookkeeping consolidation.
50
+ NEXTLY_LEGACY_BOOKKEEPING_DETECTED: 409,
51
+ NEXTLY_UPGRADE_TABLE_NAME_COLLISION: 409,
52
+ NEXTLY_UPGRADE_IN_PROGRESS: 409,
53
+ // Plan C2 — nextly migrate phases.
54
+ NEXTLY_MIGRATE_LOCK_BUSY: 409,
55
+ NEXTLY_BASELINE_LOCK_NOT_HELD: 409,
56
+ NEXTLY_RESOLVE_LOCK_NOT_HELD: 409,
57
+ // Boot refused to serve: the migrate lock stayed held past the wait deadline,
58
+ // so this process never established whether the schema matches the code. 503
59
+ // rather than 409 — a load balancer should take the instance out of rotation
60
+ // and retry it, which is exactly the recovery this refusal wants.
61
+ NEXTLY_BOOT_MIGRATIONS_NOT_RUN: 503,
62
+ // Still running rather than refused. 503 for the same reason: retry shortly.
63
+ NEXTLY_BOOT_MIGRATIONS_PENDING: 503,
64
+ NEXTLY_CORE_DESTRUCTIVE_REFUSED: 409,
65
+ NEXTLY_MIGRATION_DRIFT: 409,
66
+ NEXTLY_MIGRATION_APPLY_FAILED: 500,
67
+ // Plan C3 — migrate:resolve recovery command.
68
+ NEXTLY_MIGRATION_FILE_MISSING: 404,
69
+ NEXTLY_MIGRATION_SNAPSHOT_MISSING: 404,
70
+ NEXTLY_MIGRATION_RESOLVE_DRIFT: 409,
71
+ NEXTLY_MIGRATION_RESOLVE_PRECONDITION: 409,
72
+ // Plan D — UI schema support.
73
+ NEXTLY_UI_SCHEMA_INVALID: 400,
74
+ NEXTLY_SCHEMA_SLUG_COLLISION: 409,
75
+ NEXTLY_SCHEMA_RELATION_TARGET_MISSING: 400,
76
+ // Plugin platform (P2b) — schema extend (contributes.extend) + relations (D15).
77
+ NEXTLY_SCHEMA_EXTEND_TARGET_UNKNOWN: 400,
78
+ NEXTLY_SCHEMA_EXTEND_FIELD_DUPLICATE: 409,
79
+ NEXTLY_SCHEMA_CROSS_PLUGIN_RELATION: 409,
80
+ // Plugin platform (P2c) — framework remap (.rename()).
81
+ NEXTLY_SCHEMA_RENAME_UNKNOWN_TARGET: 400,
82
+ // Plugin platform — a declared admin.clientConfig that cannot be delivered
83
+ // to the browser, refused at boot rather than serialized mangled.
84
+ NEXTLY_PLUGIN_CLIENT_CONFIG_INVALID: 500,
85
+ // Plugin platform — a contributed admin widget that cannot be delivered to
86
+ // the browser. Refused at boot because it is serialized into the ONE
87
+ // `/api/admin-meta/workspace` payload: a value `JSON.stringify` throws on
88
+ // fails that request for every admin, not just the widget's own card.
89
+ NEXTLY_PLUGIN_ADMIN_WIDGET_INVALID: 500,
90
+ // Plugin platform (P0) — boot-time plugin dependency/version resolution.
91
+ PLUGIN_RESOLUTION_ERROR: 500,
92
+ // Plugin platform (P4) — contributes.routes collection (D25).
93
+ NEXTLY_ROUTE_COLLISION: 409,
94
+ NEXTLY_ROUTE_INVALID_PATH: 400,
95
+ // An email transport whose library is an optional peer dependency the host
96
+ // has not installed. 503 rather than 500: the request is not malformed and
97
+ // nothing is broken, the install simply cannot carry it out yet, and the
98
+ // remedy is one command on the server rather than a change by the caller.
99
+ NEXTLY_EMAIL_TRANSPORT_UNAVAILABLE: 503,
100
+ // The tooling that compiles `nextly.config.ts` is an optional peer the host
101
+ // has not installed. 503 rather than 500 for the same reason as the mail
102
+ // transport above: nothing is broken and the request is not malformed, the
103
+ // install simply cannot carry it out until one command is run.
104
+ NEXTLY_CONFIG_TOOLING_UNAVAILABLE: 503
105
+ };
106
+ var CANONICAL_CODE_FOR_STATUS = [
107
+ "VALIDATION_ERROR",
108
+ "AUTH_REQUIRED",
109
+ "FORBIDDEN",
110
+ "NOT_FOUND",
111
+ "CONFLICT",
112
+ "PAYLOAD_TOO_LARGE",
113
+ "UNSUPPORTED_MEDIA_TYPE",
114
+ "RATE_LIMITED",
115
+ "EXTERNAL_SERVICE_ERROR",
116
+ "SERVICE_UNAVAILABLE"
117
+ ];
118
+ ({
119
+ ...Object.fromEntries(
120
+ CANONICAL_CODE_FOR_STATUS.map((code) => [NEXTLY_ERROR_STATUS[code], code])
121
+ )});
122
+ var DB_ERROR_MAPPING = {
123
+ "unique-violation": {
124
+ code: "DUPLICATE",
125
+ statusCode: 409,
126
+ publicMessage: "Resource already exists."
127
+ },
128
+ "fk-violation": {
129
+ code: "VALIDATION_ERROR",
130
+ statusCode: 400,
131
+ publicMessage: "Referenced record does not exist."
132
+ },
133
+ "not-null-violation": {
134
+ code: "VALIDATION_ERROR",
135
+ statusCode: 400,
136
+ publicMessage: "A required field is missing."
137
+ },
138
+ constraint: {
139
+ code: "VALIDATION_ERROR",
140
+ statusCode: 400,
141
+ publicMessage: "The provided data violates a constraint."
142
+ },
143
+ deadlock: {
144
+ code: "CONFLICT",
145
+ statusCode: 409,
146
+ publicMessage: "The operation could not be completed. Please retry."
147
+ },
148
+ "serialization-failure": {
149
+ code: "CONFLICT",
150
+ statusCode: 409,
151
+ publicMessage: "The operation could not be completed. Please retry."
152
+ },
153
+ timeout: {
154
+ code: "DATABASE_ERROR",
155
+ statusCode: 500,
156
+ publicMessage: "The operation timed out. Please try again."
157
+ },
158
+ "connection-lost": {
159
+ code: "DATABASE_ERROR",
160
+ statusCode: 500,
161
+ publicMessage: "A temporary database error occurred. Please try again."
162
+ },
163
+ syntax: {
164
+ code: "INTERNAL_ERROR",
165
+ statusCode: 500,
166
+ publicMessage: "An unexpected error occurred."
167
+ },
168
+ internal: {
169
+ code: "INTERNAL_ERROR",
170
+ statusCode: 500,
171
+ publicMessage: "An unexpected error occurred."
172
+ }
173
+ };
174
+ var NEXTLY_ERROR_BRAND = Symbol.for("nextly/NextlyError");
175
+ function hasBrand(value) {
176
+ if (value === null || typeof value !== "object" && typeof value !== "function") {
177
+ return false;
178
+ }
179
+ return value[NEXTLY_ERROR_BRAND] === true;
180
+ }
181
+ var NextlyError = class _NextlyError extends Error {
182
+ code;
183
+ statusCode;
184
+ publicMessage;
185
+ publicData;
186
+ messageKey;
187
+ logMessage;
188
+ logContext;
189
+ cause;
190
+ timestamp;
191
+ constructor(opts) {
192
+ super(opts.publicMessage);
193
+ this.name = "NextlyError";
194
+ this.code = opts.code;
195
+ this.publicMessage = opts.publicMessage;
196
+ this.publicData = opts.publicData;
197
+ this.messageKey = opts.messageKey;
198
+ this.logMessage = opts.logMessage;
199
+ this.logContext = opts.logContext;
200
+ this.cause = opts.cause;
201
+ this.timestamp = /* @__PURE__ */ new Date();
202
+ this.statusCode = _NextlyError.resolveStatusCode(opts);
203
+ Error.captureStackTrace?.(this, _NextlyError);
204
+ }
205
+ static {
206
+ _NextlyError.prototype[NEXTLY_ERROR_BRAND] = true;
207
+ }
208
+ static resolveStatusCode(opts) {
209
+ if (typeof opts.statusCode === "number") return opts.statusCode;
210
+ if (opts.code in NEXTLY_ERROR_STATUS) {
211
+ return NEXTLY_ERROR_STATUS[opts.code];
212
+ }
213
+ return 500;
214
+ }
215
+ /** HTTP-safe JSON. Strips logMessage / logContext / cause / stack. */
216
+ toResponseJSON(requestId) {
217
+ const json = {
218
+ code: String(this.code),
219
+ message: this.publicMessage,
220
+ requestId
221
+ };
222
+ if (this.messageKey) json.messageKey = this.messageKey;
223
+ if (this.publicData !== void 0) json.data = this.publicData;
224
+ return json;
225
+ }
226
+ /** Operator-facing JSON for log lines. Includes everything. */
227
+ toLogJSON(requestId) {
228
+ return {
229
+ code: this.code,
230
+ statusCode: this.statusCode,
231
+ publicMessage: this.publicMessage,
232
+ messageKey: this.messageKey,
233
+ logMessage: this.logMessage,
234
+ logContext: this.logContext,
235
+ cause: this.cause ? {
236
+ name: this.cause.name,
237
+ message: this.cause.message,
238
+ stack: this.cause.stack
239
+ } : void 0,
240
+ timestamp: this.timestamp.toISOString(),
241
+ requestId
242
+ };
243
+ }
244
+ // ────────────────────────────────────────────────────────────────────
245
+ // Static factories — the recommended throw site for every common case.
246
+ // Public messages here follow the §13.8 rubric: complete sentence,
247
+ // generic, no identifiers, no value echoing, no policy hints.
248
+ // ────────────────────────────────────────────────────────────────────
249
+ static invalidCredentials(opts) {
250
+ return new _NextlyError({
251
+ code: "AUTH_INVALID_CREDENTIALS",
252
+ publicMessage: "Invalid email or password.",
253
+ logMessage: "Login failed",
254
+ logContext: opts?.logContext
255
+ });
256
+ }
257
+ static authRequired(opts) {
258
+ return new _NextlyError({
259
+ code: "AUTH_REQUIRED",
260
+ publicMessage: "Authentication required.",
261
+ logContext: opts?.logContext
262
+ });
263
+ }
264
+ /**
265
+ * Distinct from `authRequired`: the caller was authenticated but the
266
+ * session token expired. Clients key on the TOKEN_EXPIRED *code* to
267
+ * silently refresh and retry rather than redirecting to login; the public
268
+ * message stays the generic spec §13.6 string ("Authentication required.")
269
+ * so the wire never reveals the session state — same as `authRequired`.
270
+ */
271
+ static tokenExpired(opts) {
272
+ return new _NextlyError({
273
+ code: "TOKEN_EXPIRED",
274
+ publicMessage: "Authentication required.",
275
+ logContext: opts?.logContext
276
+ });
277
+ }
278
+ static notFound(opts) {
279
+ return new _NextlyError({
280
+ code: "NOT_FOUND",
281
+ publicMessage: opts?.message ?? "Not found.",
282
+ cause: opts?.cause,
283
+ logContext: opts?.logContext
284
+ });
285
+ }
286
+ static forbidden(opts) {
287
+ return new _NextlyError({
288
+ code: "FORBIDDEN",
289
+ publicMessage: "You don't have permission to perform this action.",
290
+ cause: opts?.cause,
291
+ logContext: opts?.logContext
292
+ });
293
+ }
294
+ /**
295
+ * A call the caller got wrong, where naming the mistake IS the value of the
296
+ * error.
297
+ *
298
+ * The only factory that takes its public message from the caller. The
299
+ * generic messages elsewhere exist so an HTTP response cannot leak internal
300
+ * detail; this one is for arguments and configuration a developer controls
301
+ * and must be told about — a missing option, an unusable combination — where
302
+ * `internal()` would reduce the one useful sentence to "An unexpected error
303
+ * occurred." Do not pass user-supplied data through it.
304
+ */
305
+ static invalidInput(opts) {
306
+ return new _NextlyError({
307
+ code: "INVALID_INPUT",
308
+ publicMessage: opts.message,
309
+ logContext: opts.logContext
310
+ });
311
+ }
312
+ static validation(opts) {
313
+ return new _NextlyError({
314
+ code: "VALIDATION_ERROR",
315
+ publicMessage: "Validation failed.",
316
+ publicData: { errors: opts.errors },
317
+ cause: opts.cause,
318
+ logContext: opts.logContext
319
+ });
320
+ }
321
+ static conflict(opts) {
322
+ return new _NextlyError({
323
+ code: "CONFLICT",
324
+ publicMessage: opts?.message ?? "The resource has changed since you last loaded it. Please refresh and try again.",
325
+ cause: opts?.cause,
326
+ logContext: { reason: opts?.reason, ...opts?.logContext }
327
+ });
328
+ }
329
+ static duplicate(opts) {
330
+ return new _NextlyError({
331
+ code: "DUPLICATE",
332
+ publicMessage: "Resource already exists.",
333
+ logContext: opts?.logContext
334
+ });
335
+ }
336
+ static rateLimited(opts) {
337
+ return new _NextlyError({
338
+ code: "RATE_LIMITED",
339
+ publicMessage: "Too many requests. Please try again later.",
340
+ publicData: opts?.retryAfterSeconds !== void 0 ? { retryAfterSeconds: opts.retryAfterSeconds } : void 0,
341
+ logContext: opts?.logContext
342
+ });
343
+ }
344
+ static internal(opts) {
345
+ return new _NextlyError({
346
+ code: "INTERNAL_ERROR",
347
+ publicMessage: "An unexpected error occurred.",
348
+ cause: opts?.cause,
349
+ logContext: opts?.logContext
350
+ });
351
+ }
352
+ // Accepts an optional `logMessage` override so callers (e.g. the health
353
+ // route) can record a specific operator narrative ("Health check failed")
354
+ // while the public message stays canonical per spec §13.8.5.
355
+ static serviceUnavailable(opts) {
356
+ return new _NextlyError({
357
+ code: "SERVICE_UNAVAILABLE",
358
+ publicMessage: opts?.publicMessage ?? "Service unavailable. Please try again later.",
359
+ logMessage: opts?.logMessage,
360
+ cause: opts?.cause,
361
+ logContext: opts?.logContext
362
+ });
363
+ }
364
+ /**
365
+ * Convert a DbError (or arbitrary unknown thrown by the DB layer) to a
366
+ * NextlyError with a generic public message and rich logContext. Used by
367
+ * `withDbErrors` for auto-conversion (Pattern A) and by services that
368
+ * catch DB errors at boundaries (Pattern B). Spec §8.2 mapping table.
369
+ *
370
+ * Never leaks DB driver text, constraint names, or table names into
371
+ * `publicMessage`. All DB context goes into `logContext`. The original
372
+ * DbError is preserved as `cause`.
373
+ */
374
+ static fromDatabaseError(error) {
375
+ if (isDbError(error)) {
376
+ const mapping = DB_ERROR_MAPPING[error.kind];
377
+ const logContext = {
378
+ dbKind: error.kind,
379
+ dialect: error.dialect
380
+ };
381
+ if (error.code !== void 0) logContext.dbCode = error.code;
382
+ if (error.meta !== void 0) logContext.meta = error.meta;
383
+ return new _NextlyError({
384
+ code: mapping.code,
385
+ statusCode: mapping.statusCode,
386
+ publicMessage: mapping.publicMessage,
387
+ logMessage: "Database error",
388
+ logContext,
389
+ cause: error
390
+ });
391
+ }
392
+ return new _NextlyError({
393
+ code: "INTERNAL_ERROR",
394
+ statusCode: 500,
395
+ publicMessage: "An unexpected error occurred.",
396
+ logMessage: "Non-DbError passed to fromDatabaseError",
397
+ cause: error instanceof Error ? error : void 0,
398
+ logContext: error instanceof Error ? void 0 : { value: String(error) }
399
+ });
400
+ }
401
+ // ────────────────────────────────────────────────────────────────────
402
+ // Type guards. Structural rather than `instanceof` so they survive
403
+ // package-boundary mismatches (one consumer's NextlyError is a
404
+ // different module instance from another's).
405
+ // ────────────────────────────────────────────────────────────────────
406
+ static is(err) {
407
+ return hasBrand(err);
408
+ }
409
+ static isCode(err, code) {
410
+ return hasBrand(err) && err.code === code;
411
+ }
412
+ static isNotFound(err) {
413
+ return _NextlyError.isCode(err, "NOT_FOUND");
414
+ }
415
+ static isValidation(err) {
416
+ return _NextlyError.isCode(err, "VALIDATION_ERROR");
417
+ }
418
+ static isAuthRequired(err) {
419
+ return _NextlyError.isCode(err, "AUTH_REQUIRED");
420
+ }
421
+ static isForbidden(err) {
422
+ return _NextlyError.isCode(err, "FORBIDDEN");
423
+ }
424
+ static isConflict(err) {
425
+ return _NextlyError.isCode(err, "CONFLICT");
426
+ }
427
+ static isRateLimited(err) {
428
+ return _NextlyError.isCode(err, "RATE_LIMITED");
429
+ }
430
+ };
431
+
5
432
  // src/adapter.ts
6
433
  var VercelBlobStorageAdapter = class {
7
434
  /**
@@ -47,14 +474,25 @@ var VercelBlobStorageAdapter = class {
47
474
  const mimeType = (options.contentType || options.mimeType || "").toLowerCase().trim();
48
475
  const filename = (options.filename || "").toLowerCase();
49
476
  const ext = filename.includes(".") ? filename.slice(filename.lastIndexOf(".") + 1) : "";
50
- const isSvg = mimeType === "image/svg+xml" || ext === "svg" || ext === "svgz";
51
477
  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
- );
478
+ if (isHtml) {
479
+ throw NextlyError.validation({
480
+ errors: [
481
+ {
482
+ path: "file",
483
+ code: "UNSUPPORTED_FOR_BACKEND",
484
+ message: "HTML files cannot be hosted on Vercel Blob. Use the S3 or R2 adapter, or upload as another format."
485
+ }
486
+ ],
487
+ logContext: {
488
+ adapter: "vercel-blob",
489
+ claimedMimeType: options.mimeType,
490
+ reason: "vercel-blob-rejects-html",
491
+ filename: options.filename
492
+ }
493
+ });
57
494
  }
495
+ const isSvg = mimeType === "image/svg+xml" || ext === "svg" || ext === "svgz";
58
496
  const pathname = this.buildPathname(options.filename, options.folder);
59
497
  const result = await blob.put(pathname, buffer, {
60
498
  access: this.resolvedConfig.access,
@@ -63,8 +501,9 @@ var VercelBlobStorageAdapter = class {
63
501
  addRandomSuffix: this.resolvedConfig.addRandomSuffix,
64
502
  cacheControlMaxAge: this.resolvedConfig.cacheControlMaxAge
65
503
  });
504
+ const url = isSvg && options.contentDisposition === "attachment" ? result.downloadUrl : result.url;
66
505
  return {
67
- url: result.url,
506
+ url,
68
507
  path: result.url
69
508
  };
70
509
  }