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