@nextlyhq/storage-vercel-blob 0.0.2-alpha.67 → 0.0.2-alpha.69

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