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