s3kit 0.1.0

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.
Files changed (56) hide show
  1. package/README.md +398 -0
  2. package/dist/adapters/express.cjs +305 -0
  3. package/dist/adapters/express.cjs.map +1 -0
  4. package/dist/adapters/express.d.cts +10 -0
  5. package/dist/adapters/express.d.ts +10 -0
  6. package/dist/adapters/express.js +278 -0
  7. package/dist/adapters/express.js.map +1 -0
  8. package/dist/adapters/fetch.cjs +298 -0
  9. package/dist/adapters/fetch.cjs.map +1 -0
  10. package/dist/adapters/fetch.d.cts +9 -0
  11. package/dist/adapters/fetch.d.ts +9 -0
  12. package/dist/adapters/fetch.js +271 -0
  13. package/dist/adapters/fetch.js.map +1 -0
  14. package/dist/adapters/next.cjs +796 -0
  15. package/dist/adapters/next.cjs.map +1 -0
  16. package/dist/adapters/next.d.cts +28 -0
  17. package/dist/adapters/next.d.ts +28 -0
  18. package/dist/adapters/next.js +775 -0
  19. package/dist/adapters/next.js.map +1 -0
  20. package/dist/client/index.cjs +153 -0
  21. package/dist/client/index.cjs.map +1 -0
  22. package/dist/client/index.d.cts +59 -0
  23. package/dist/client/index.d.ts +59 -0
  24. package/dist/client/index.js +126 -0
  25. package/dist/client/index.js.map +1 -0
  26. package/dist/core/index.cjs +452 -0
  27. package/dist/core/index.cjs.map +1 -0
  28. package/dist/core/index.d.cts +11 -0
  29. package/dist/core/index.d.ts +11 -0
  30. package/dist/core/index.js +430 -0
  31. package/dist/core/index.js.map +1 -0
  32. package/dist/http/index.cjs +270 -0
  33. package/dist/http/index.cjs.map +1 -0
  34. package/dist/http/index.d.cts +49 -0
  35. package/dist/http/index.d.ts +49 -0
  36. package/dist/http/index.js +243 -0
  37. package/dist/http/index.js.map +1 -0
  38. package/dist/index.cjs +808 -0
  39. package/dist/index.cjs.map +1 -0
  40. package/dist/index.d.cts +6 -0
  41. package/dist/index.d.ts +6 -0
  42. package/dist/index.js +784 -0
  43. package/dist/index.js.map +1 -0
  44. package/dist/manager-BbmXpgXN.d.ts +29 -0
  45. package/dist/manager-gIjo-t8h.d.cts +29 -0
  46. package/dist/react/index.cjs +4320 -0
  47. package/dist/react/index.cjs.map +1 -0
  48. package/dist/react/index.css +155 -0
  49. package/dist/react/index.css.map +1 -0
  50. package/dist/react/index.d.cts +79 -0
  51. package/dist/react/index.d.ts +79 -0
  52. package/dist/react/index.js +4315 -0
  53. package/dist/react/index.js.map +1 -0
  54. package/dist/types-g2IYvH3O.d.cts +123 -0
  55. package/dist/types-g2IYvH3O.d.ts +123 -0
  56. package/package.json +100 -0
@@ -0,0 +1,775 @@
1
+ // src/adapters/next.ts
2
+ import { S3Client as S3Client2 } from "@aws-sdk/client-s3";
3
+
4
+ // src/core/manager.ts
5
+ import {
6
+ CopyObjectCommand,
7
+ DeleteObjectCommand,
8
+ DeleteObjectsCommand,
9
+ ListObjectsV2Command,
10
+ PutObjectCommand
11
+ } from "@aws-sdk/client-s3";
12
+ import { GetObjectCommand } from "@aws-sdk/client-s3";
13
+ import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
14
+
15
+ // src/core/errors.ts
16
+ var S3FileManagerAuthorizationError = class extends Error {
17
+ status;
18
+ code;
19
+ constructor(message, status, code) {
20
+ super(message);
21
+ this.status = status;
22
+ this.code = code;
23
+ }
24
+ };
25
+
26
+ // src/core/manager.ts
27
+ var DEFAULT_DELIMITER = "/";
28
+ function trimSlashes(input) {
29
+ return input.replace(/^\/+/, "").replace(/\/+$/, "");
30
+ }
31
+ function normalizePath(input) {
32
+ const raw = input.replace(/\\/g, "/");
33
+ const noLeading = raw.replace(/^\/+/, "");
34
+ const segments = noLeading.split("/").filter((s) => s.length > 0);
35
+ for (const seg of segments) {
36
+ if (seg === "..") {
37
+ throw new Error("Invalid path");
38
+ }
39
+ }
40
+ return segments.join("/");
41
+ }
42
+ function ensureTrailingDelimiter(prefix, delimiter) {
43
+ if (prefix === "") return "";
44
+ return prefix.endsWith(delimiter) ? prefix : `${prefix}${delimiter}`;
45
+ }
46
+ function encodeS3CopySource(bucket, key) {
47
+ return encodeURIComponent(`${bucket}/${key}`).replace(/%2F/g, "/");
48
+ }
49
+ function isNoSuchKeyError(err) {
50
+ if (!err || typeof err !== "object") return false;
51
+ if ("name" in err && err.name === "NoSuchKey") return true;
52
+ if ("message" in err && typeof err.message === "string") {
53
+ return err.message.includes("The specified key does not exist");
54
+ }
55
+ return false;
56
+ }
57
+ async function* listAllKeys(s3, bucket, prefix) {
58
+ let cursor;
59
+ while (true) {
60
+ const out = await s3.send(
61
+ new ListObjectsV2Command({
62
+ Bucket: bucket,
63
+ Prefix: prefix,
64
+ ContinuationToken: cursor
65
+ })
66
+ );
67
+ for (const obj of out.Contents ?? []) {
68
+ if (obj.Key) yield obj.Key;
69
+ }
70
+ if (!out.IsTruncated) break;
71
+ cursor = out.NextContinuationToken;
72
+ }
73
+ }
74
+ async function deleteKeysInBatches(s3, bucket, keys) {
75
+ const batchSize = 1e3;
76
+ for (let i = 0; i < keys.length; i += batchSize) {
77
+ const batch = keys.slice(i, i + batchSize);
78
+ await s3.send(
79
+ new DeleteObjectsCommand({
80
+ Bucket: bucket,
81
+ Delete: {
82
+ Objects: batch.map((Key) => ({ Key })),
83
+ Quiet: true
84
+ }
85
+ })
86
+ );
87
+ }
88
+ }
89
+ var S3FileManager = class {
90
+ s3;
91
+ bucket;
92
+ rootPrefix;
93
+ delimiter;
94
+ hooks;
95
+ authorizationMode;
96
+ constructor(s3, options) {
97
+ this.s3 = s3;
98
+ this.bucket = options.bucket;
99
+ this.delimiter = options.delimiter ?? DEFAULT_DELIMITER;
100
+ this.rootPrefix = ensureTrailingDelimiter(trimSlashes(options.rootPrefix ?? ""), this.delimiter);
101
+ this.hooks = options.hooks;
102
+ this.authorizationMode = options.authorizationMode ?? "deny-by-default";
103
+ }
104
+ async authorize(args) {
105
+ const hasAuthHooks = Boolean(this.hooks?.authorize || this.hooks?.allowAction);
106
+ if (this.hooks?.authorize) {
107
+ const result = await this.hooks.authorize(args);
108
+ if (result === false) {
109
+ throw new S3FileManagerAuthorizationError("Unauthorized", 401, "unauthorized");
110
+ }
111
+ }
112
+ if (this.hooks?.allowAction) {
113
+ const allowed = await this.hooks.allowAction(args);
114
+ if (allowed === false) {
115
+ throw new S3FileManagerAuthorizationError("Forbidden", 403, "forbidden");
116
+ }
117
+ }
118
+ if (!hasAuthHooks && this.authorizationMode === "deny-by-default") {
119
+ throw new S3FileManagerAuthorizationError("Unauthorized", 401, "unauthorized");
120
+ }
121
+ }
122
+ pathToKey(path) {
123
+ const p = normalizePath(path);
124
+ return `${this.rootPrefix}${p}`;
125
+ }
126
+ pathToFolderPrefix(path) {
127
+ const key = this.pathToKey(path);
128
+ return ensureTrailingDelimiter(key, this.delimiter);
129
+ }
130
+ keyToPath(key) {
131
+ if (!key.startsWith(this.rootPrefix)) {
132
+ throw new Error("Key is outside of rootPrefix");
133
+ }
134
+ return key.slice(this.rootPrefix.length);
135
+ }
136
+ makeFolderEntry(path) {
137
+ const p = normalizePath(path);
138
+ const name = p === "" ? "" : p.split("/").at(-1) ?? "";
139
+ return {
140
+ type: "folder",
141
+ path: p === "" ? "" : ensureTrailingDelimiter(p, this.delimiter),
142
+ name
143
+ };
144
+ }
145
+ makeFileEntryFromKey(key, obj) {
146
+ const path = this.keyToPath(key);
147
+ const name = path.split("/").at(-1) ?? "";
148
+ return {
149
+ type: "file",
150
+ path,
151
+ name,
152
+ ...obj.Size !== void 0 ? { size: obj.Size } : {},
153
+ ...obj.LastModified ? { lastModified: obj.LastModified.toISOString() } : {},
154
+ ...obj.ETag !== void 0 ? { etag: obj.ETag } : {}
155
+ };
156
+ }
157
+ async list(options, ctx = {}) {
158
+ const path = normalizePath(options.path);
159
+ await this.authorize({ action: "list", path, ctx });
160
+ const prefix = path === "" ? this.rootPrefix : this.pathToFolderPrefix(path);
161
+ const out = await this.s3.send(
162
+ new ListObjectsV2Command({
163
+ Bucket: this.bucket,
164
+ Prefix: prefix,
165
+ Delimiter: this.delimiter,
166
+ ContinuationToken: options.cursor,
167
+ MaxKeys: options.limit
168
+ })
169
+ );
170
+ const folders = (out.CommonPrefixes ?? []).map((cp) => cp.Prefix).filter((p) => typeof p === "string").map((p) => {
171
+ const rel = this.keyToPath(p);
172
+ const folderPath = ensureTrailingDelimiter(trimSlashes(rel), this.delimiter);
173
+ return this.makeFolderEntry(folderPath);
174
+ });
175
+ const files = (out.Contents ?? []).filter((obj) => typeof obj.Key === "string").filter((obj) => obj.Key !== prefix).map((obj) => this.makeFileEntryFromKey(obj.Key, obj));
176
+ for (const folder of folders) {
177
+ await this.hooks?.decorateFolder?.(folder, {
178
+ path: folder.path,
179
+ prefix: this.pathToFolderPrefix(folder.path)
180
+ });
181
+ }
182
+ for (const file of files) {
183
+ await this.hooks?.decorateFile?.(file, {
184
+ path: file.path,
185
+ key: this.pathToKey(file.path)
186
+ });
187
+ }
188
+ const entries = [...folders, ...files].sort((a, b) => {
189
+ if (a.type !== b.type) return a.type === "folder" ? -1 : 1;
190
+ return a.name.localeCompare(b.name);
191
+ });
192
+ return {
193
+ path,
194
+ entries,
195
+ ...out.IsTruncated && out.NextContinuationToken ? { nextCursor: out.NextContinuationToken } : {}
196
+ };
197
+ }
198
+ async createFolder(options, ctx = {}) {
199
+ const path = ensureTrailingDelimiter(normalizePath(options.path), this.delimiter);
200
+ await this.authorize({ action: "folder.create", path, ctx });
201
+ const key = this.pathToFolderPrefix(path);
202
+ await this.s3.send(
203
+ new PutObjectCommand({
204
+ Bucket: this.bucket,
205
+ Key: key,
206
+ Body: ""
207
+ })
208
+ );
209
+ }
210
+ async deleteFolder(options, ctx = {}) {
211
+ const path = ensureTrailingDelimiter(normalizePath(options.path), this.delimiter);
212
+ await this.authorize({ action: "folder.delete", path, ctx });
213
+ const prefix = this.pathToFolderPrefix(path);
214
+ if (!options.recursive) {
215
+ const out = await this.s3.send(
216
+ new ListObjectsV2Command({
217
+ Bucket: this.bucket,
218
+ Prefix: prefix,
219
+ MaxKeys: 2
220
+ })
221
+ );
222
+ const keys2 = (out.Contents ?? []).map((o) => o.Key).filter((k) => typeof k === "string" && k !== prefix);
223
+ if (keys2.length > 0) {
224
+ throw new Error("Folder is not empty");
225
+ }
226
+ await this.s3.send(new DeleteObjectCommand({ Bucket: this.bucket, Key: prefix }));
227
+ return;
228
+ }
229
+ const keys = [];
230
+ for await (const key of listAllKeys(this.s3, this.bucket, prefix)) {
231
+ keys.push(key);
232
+ }
233
+ if (keys.length === 0) return;
234
+ await deleteKeysInBatches(this.s3, this.bucket, keys);
235
+ }
236
+ async deleteFiles(options, ctx = {}) {
237
+ const paths = options.paths.map((p) => normalizePath(p));
238
+ for (const path of paths) {
239
+ await this.authorize({ action: "file.delete", path, ctx });
240
+ }
241
+ const keys = paths.map((p) => this.pathToKey(p));
242
+ await deleteKeysInBatches(this.s3, this.bucket, keys);
243
+ }
244
+ async copy(options, ctx = {}) {
245
+ const isFolder = options.fromPath.endsWith(this.delimiter);
246
+ const fromPath = normalizePath(options.fromPath);
247
+ const toPath = normalizePath(options.toPath);
248
+ if (fromPath === toPath) return;
249
+ if (isFolder) {
250
+ const fromPathWithSlash = ensureTrailingDelimiter(fromPath, this.delimiter);
251
+ const toPathWithSlash = ensureTrailingDelimiter(toPath, this.delimiter);
252
+ await this.authorize({
253
+ action: "folder.copy",
254
+ fromPath: fromPathWithSlash,
255
+ toPath: toPathWithSlash,
256
+ ctx
257
+ });
258
+ const fromPrefix = this.pathToFolderPrefix(fromPathWithSlash);
259
+ const toPrefix = this.pathToFolderPrefix(toPathWithSlash);
260
+ try {
261
+ await this.s3.send(
262
+ new CopyObjectCommand({
263
+ Bucket: this.bucket,
264
+ Key: toPrefix,
265
+ CopySource: encodeS3CopySource(this.bucket, fromPrefix)
266
+ })
267
+ );
268
+ } catch {
269
+ }
270
+ for await (const sourceKey of listAllKeys(this.s3, this.bucket, fromPrefix)) {
271
+ if (sourceKey === fromPrefix) continue;
272
+ const relKey = sourceKey.slice(fromPrefix.length);
273
+ const destKey = toPrefix + relKey;
274
+ try {
275
+ await this.s3.send(
276
+ new CopyObjectCommand({
277
+ Bucket: this.bucket,
278
+ Key: destKey,
279
+ CopySource: encodeS3CopySource(this.bucket, sourceKey)
280
+ })
281
+ );
282
+ } catch (err) {
283
+ if (isNoSuchKeyError(err)) continue;
284
+ throw err;
285
+ }
286
+ }
287
+ return;
288
+ }
289
+ await this.authorize({ action: "file.copy", fromPath, toPath, ctx });
290
+ const fromKey = this.pathToKey(fromPath);
291
+ const toKey = this.pathToKey(toPath);
292
+ await this.s3.send(
293
+ new CopyObjectCommand({
294
+ Bucket: this.bucket,
295
+ Key: toKey,
296
+ CopySource: encodeS3CopySource(this.bucket, fromKey)
297
+ })
298
+ );
299
+ }
300
+ async move(options, ctx = {}) {
301
+ const isFolder = options.fromPath.endsWith(this.delimiter);
302
+ const fromPath = normalizePath(options.fromPath);
303
+ const toPath = normalizePath(options.toPath);
304
+ if (fromPath === toPath) return;
305
+ if (isFolder) {
306
+ const fromPathWithSlash = ensureTrailingDelimiter(fromPath, this.delimiter);
307
+ const toPathWithSlash = ensureTrailingDelimiter(toPath, this.delimiter);
308
+ await this.authorize({
309
+ action: "folder.move",
310
+ fromPath: fromPathWithSlash,
311
+ toPath: toPathWithSlash,
312
+ ctx
313
+ });
314
+ await this.copy(options, ctx);
315
+ await this.deleteFolder({ path: fromPathWithSlash, recursive: true }, ctx);
316
+ return;
317
+ }
318
+ await this.authorize({ action: "file.move", fromPath, toPath, ctx });
319
+ await this.copy(options, ctx);
320
+ await this.deleteFiles({ paths: [fromPath] }, ctx);
321
+ }
322
+ async prepareUploads(options, ctx = {}) {
323
+ const expiresIn = options.expiresInSeconds ?? 60 * 5;
324
+ const result = [];
325
+ for (const item of options.items) {
326
+ const path = normalizePath(item.path);
327
+ await this.authorize({ action: "upload.prepare", path, ctx });
328
+ const key = this.pathToKey(path);
329
+ const cmd = new PutObjectCommand({
330
+ Bucket: this.bucket,
331
+ Key: key,
332
+ ContentType: item.contentType,
333
+ CacheControl: item.cacheControl,
334
+ ContentDisposition: item.contentDisposition,
335
+ Metadata: item.metadata
336
+ });
337
+ const url = await getSignedUrl(this.s3, cmd, { expiresIn });
338
+ const headers = {};
339
+ if (item.contentType) headers["Content-Type"] = item.contentType;
340
+ if (item.cacheControl) headers["Cache-Control"] = item.cacheControl;
341
+ if (item.contentDisposition) headers["Content-Disposition"] = item.contentDisposition;
342
+ if (item.metadata) {
343
+ for (const [k, v] of Object.entries(item.metadata)) {
344
+ headers[`x-amz-meta-${k}`] = v;
345
+ }
346
+ }
347
+ result.push({
348
+ path,
349
+ url,
350
+ method: "PUT",
351
+ headers
352
+ });
353
+ }
354
+ return result;
355
+ }
356
+ async search(options, ctx = {}) {
357
+ const query = options.query.toLowerCase().trim();
358
+ if (!query) {
359
+ return { query: options.query, entries: [] };
360
+ }
361
+ await this.authorize({ action: "search", ctx });
362
+ const searchPrefix = options.path ? this.pathToFolderPrefix(normalizePath(options.path)) : this.rootPrefix;
363
+ const entries = [];
364
+ const limit = options.limit ?? 500;
365
+ const recursive = options.recursive !== false;
366
+ let cursor = options.cursor;
367
+ let nextCursor;
368
+ while (entries.length < limit) {
369
+ const out = await this.s3.send(
370
+ new ListObjectsV2Command({
371
+ Bucket: this.bucket,
372
+ Prefix: searchPrefix,
373
+ ContinuationToken: cursor,
374
+ MaxKeys: 1e3
375
+ // Fetch more to filter
376
+ })
377
+ );
378
+ nextCursor = out.IsTruncated && out.NextContinuationToken ? out.NextContinuationToken : void 0;
379
+ for (const obj of out.Contents ?? []) {
380
+ if (!obj.Key || obj.Key === searchPrefix) continue;
381
+ const path = this.keyToPath(obj.Key);
382
+ const name = path.split("/").at(-1) ?? "";
383
+ if (!recursive && options.path) {
384
+ const base = ensureTrailingDelimiter(normalizePath(options.path), this.delimiter);
385
+ const rel = path.startsWith(base) ? path.slice(base.length) : path;
386
+ if (rel.includes(this.delimiter)) continue;
387
+ }
388
+ if (!recursive && !options.path) {
389
+ if (path.includes(this.delimiter)) continue;
390
+ }
391
+ if (name.toLowerCase().includes(query)) {
392
+ const fileEntry = this.makeFileEntryFromKey(obj.Key, {
393
+ ...obj.Size !== void 0 ? { Size: obj.Size } : {},
394
+ ...obj.LastModified !== void 0 ? { LastModified: obj.LastModified } : {},
395
+ ...obj.ETag !== void 0 ? { ETag: obj.ETag } : {}
396
+ });
397
+ await this.hooks?.decorateFile?.(fileEntry, {
398
+ path: fileEntry.path,
399
+ key: this.pathToKey(fileEntry.path)
400
+ });
401
+ entries.push(fileEntry);
402
+ }
403
+ if (entries.length >= limit) break;
404
+ }
405
+ if (!out.IsTruncated || !out.NextContinuationToken) break;
406
+ cursor = out.NextContinuationToken;
407
+ }
408
+ return {
409
+ query: options.query,
410
+ entries,
411
+ ...nextCursor ? { nextCursor } : {}
412
+ };
413
+ }
414
+ async getPreviewUrl(options, ctx = {}) {
415
+ const path = normalizePath(options.path);
416
+ await this.authorize({ action: "preview.get", path, ctx });
417
+ const expiresIn = options.expiresInSeconds ?? 60 * 5;
418
+ const key = this.pathToKey(path);
419
+ const cmd = new GetObjectCommand({
420
+ Bucket: this.bucket,
421
+ Key: key,
422
+ ResponseContentDisposition: options.inline ? "inline" : "attachment"
423
+ });
424
+ const url = await getSignedUrl(this.s3, cmd, { expiresIn });
425
+ const expiresAt = new Date(Date.now() + expiresIn * 1e3).toISOString();
426
+ return { path, url, expiresAt };
427
+ }
428
+ };
429
+
430
+ // src/http/handler.ts
431
+ var S3FileManagerHttpError = class extends Error {
432
+ status;
433
+ code;
434
+ constructor(status, code, message) {
435
+ super(message);
436
+ this.status = status;
437
+ this.code = code;
438
+ }
439
+ };
440
+ function normalizeBasePath(basePath) {
441
+ if (!basePath) return "";
442
+ if (basePath === "/") return "";
443
+ return basePath.startsWith("/") ? basePath.replace(/\/+$/, "") : `/${basePath.replace(/\/+$/, "")}`;
444
+ }
445
+ function jsonError(status, code, message) {
446
+ return {
447
+ status,
448
+ headers: { "content-type": "application/json" },
449
+ body: {
450
+ error: {
451
+ code,
452
+ message
453
+ }
454
+ }
455
+ };
456
+ }
457
+ function ensureObject(body) {
458
+ if (body && typeof body === "object" && !Array.isArray(body))
459
+ return body;
460
+ throw new S3FileManagerHttpError(400, "invalid_body", "Expected JSON object body");
461
+ }
462
+ function optionalString(value, key) {
463
+ if (value === void 0) return void 0;
464
+ if (typeof value === "string") return value;
465
+ throw new S3FileManagerHttpError(400, "invalid_body", `Expected '${key}' to be a string`);
466
+ }
467
+ function requiredString(value, key) {
468
+ if (typeof value === "string") return value;
469
+ throw new S3FileManagerHttpError(400, "invalid_body", `Expected '${key}' to be a string`);
470
+ }
471
+ function optionalNumber(value, key) {
472
+ if (value === void 0) return void 0;
473
+ if (typeof value === "number" && Number.isFinite(value)) return value;
474
+ throw new S3FileManagerHttpError(400, "invalid_body", `Expected '${key}' to be a finite number`);
475
+ }
476
+ function optionalBoolean(value, key) {
477
+ if (value === void 0) return void 0;
478
+ if (typeof value === "boolean") return value;
479
+ throw new S3FileManagerHttpError(400, "invalid_body", `Expected '${key}' to be a boolean`);
480
+ }
481
+ function requiredStringArray(value, key) {
482
+ if (!Array.isArray(value)) {
483
+ throw new S3FileManagerHttpError(
484
+ 400,
485
+ "invalid_body",
486
+ `Expected '${key}' to be an array of strings`
487
+ );
488
+ }
489
+ for (const item of value) {
490
+ if (typeof item !== "string") {
491
+ throw new S3FileManagerHttpError(
492
+ 400,
493
+ "invalid_body",
494
+ `Expected '${key}' to be an array of strings`
495
+ );
496
+ }
497
+ }
498
+ return value;
499
+ }
500
+ function optionalStringRecord(value, key) {
501
+ if (value === void 0) return void 0;
502
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
503
+ throw new S3FileManagerHttpError(
504
+ 400,
505
+ "invalid_body",
506
+ `Expected '${key}' to be an object of strings`
507
+ );
508
+ }
509
+ const out = {};
510
+ for (const [k, v] of Object.entries(value)) {
511
+ if (typeof v !== "string") {
512
+ throw new S3FileManagerHttpError(400, "invalid_body", `Expected '${key}.${k}' to be a string`);
513
+ }
514
+ out[k] = v;
515
+ }
516
+ return out;
517
+ }
518
+ function parseListOptions(body) {
519
+ const obj = ensureObject(body);
520
+ return {
521
+ path: requiredString(obj.path, "path"),
522
+ cursor: optionalString(obj.cursor, "cursor"),
523
+ limit: optionalNumber(obj.limit, "limit")
524
+ };
525
+ }
526
+ function parseSearchOptions(body) {
527
+ const obj = ensureObject(body);
528
+ return {
529
+ query: requiredString(obj.query, "query"),
530
+ path: optionalString(obj.path, "path"),
531
+ recursive: optionalBoolean(obj.recursive, "recursive"),
532
+ limit: optionalNumber(obj.limit, "limit"),
533
+ cursor: optionalString(obj.cursor, "cursor")
534
+ };
535
+ }
536
+ function parseCreateFolderOptions(body) {
537
+ const obj = ensureObject(body);
538
+ return { path: requiredString(obj.path, "path") };
539
+ }
540
+ function parseDeleteFolderOptions(body) {
541
+ const obj = ensureObject(body);
542
+ return {
543
+ path: requiredString(obj.path, "path"),
544
+ recursive: optionalBoolean(obj.recursive, "recursive")
545
+ };
546
+ }
547
+ function parseDeleteFilesOptions(body) {
548
+ const obj = ensureObject(body);
549
+ return { paths: requiredStringArray(obj.paths, "paths") };
550
+ }
551
+ function parseCopyMoveOptions(body) {
552
+ const obj = ensureObject(body);
553
+ return {
554
+ fromPath: requiredString(obj.fromPath, "fromPath"),
555
+ toPath: requiredString(obj.toPath, "toPath")
556
+ };
557
+ }
558
+ function parsePrepareUploadsOptions(body) {
559
+ const obj = ensureObject(body);
560
+ const itemsValue = obj.items;
561
+ if (!Array.isArray(itemsValue)) {
562
+ throw new S3FileManagerHttpError(400, "invalid_body", "Expected 'items' to be an array");
563
+ }
564
+ const items = itemsValue.map((raw, idx) => {
565
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
566
+ throw new S3FileManagerHttpError(
567
+ 400,
568
+ "invalid_body",
569
+ `Expected 'items[${idx}]' to be an object`
570
+ );
571
+ }
572
+ const item = raw;
573
+ return {
574
+ path: requiredString(item.path, `items[${idx}].path`),
575
+ contentType: optionalString(item.contentType, `items[${idx}].contentType`),
576
+ cacheControl: optionalString(item.cacheControl, `items[${idx}].cacheControl`),
577
+ contentDisposition: optionalString(
578
+ item.contentDisposition,
579
+ `items[${idx}].contentDisposition`
580
+ ),
581
+ metadata: optionalStringRecord(item.metadata, `items[${idx}].metadata`)
582
+ };
583
+ });
584
+ return {
585
+ items,
586
+ expiresInSeconds: optionalNumber(obj.expiresInSeconds, "expiresInSeconds")
587
+ };
588
+ }
589
+ function parsePreviewOptions(body) {
590
+ const obj = ensureObject(body);
591
+ return {
592
+ path: requiredString(obj.path, "path"),
593
+ expiresInSeconds: optionalNumber(obj.expiresInSeconds, "expiresInSeconds"),
594
+ inline: optionalBoolean(obj.inline, "inline")
595
+ };
596
+ }
597
+ function createS3FileManagerHttpHandler(options) {
598
+ const basePath = normalizeBasePath(options.api?.basePath);
599
+ if (!options.manager && !options.getManager) {
600
+ throw new Error("createS3FileManagerHttpHandler requires either manager or getManager");
601
+ }
602
+ return async (req) => {
603
+ try {
604
+ const ctx = await options.getContext?.(req) ?? {};
605
+ const manager = options.getManager ? await options.getManager(req, ctx) : options.manager;
606
+ const method = req.method.toUpperCase();
607
+ const path = req.path.startsWith(basePath) ? req.path.slice(basePath.length) || "/" : req.path;
608
+ if (method === "POST" && path === "/list") {
609
+ const out = await manager.list(parseListOptions(req.body), ctx);
610
+ return { status: 200, headers: { "content-type": "application/json" }, body: out };
611
+ }
612
+ if (method === "POST" && path === "/search") {
613
+ const out = await manager.search(parseSearchOptions(req.body), ctx);
614
+ return { status: 200, headers: { "content-type": "application/json" }, body: out };
615
+ }
616
+ if (method === "POST" && path === "/folder/create") {
617
+ await manager.createFolder(parseCreateFolderOptions(req.body), ctx);
618
+ return { status: 204 };
619
+ }
620
+ if (method === "POST" && path === "/folder/delete") {
621
+ await manager.deleteFolder(parseDeleteFolderOptions(req.body), ctx);
622
+ return { status: 204 };
623
+ }
624
+ if (method === "POST" && path === "/files/delete") {
625
+ await manager.deleteFiles(parseDeleteFilesOptions(req.body), ctx);
626
+ return { status: 204 };
627
+ }
628
+ if (method === "POST" && path === "/files/copy") {
629
+ await manager.copy(parseCopyMoveOptions(req.body), ctx);
630
+ return { status: 204 };
631
+ }
632
+ if (method === "POST" && path === "/files/move") {
633
+ await manager.move(parseCopyMoveOptions(req.body), ctx);
634
+ return { status: 204 };
635
+ }
636
+ if (method === "POST" && path === "/upload/prepare") {
637
+ const out = await manager.prepareUploads(parsePrepareUploadsOptions(req.body), ctx);
638
+ return { status: 200, headers: { "content-type": "application/json" }, body: out };
639
+ }
640
+ if (method === "POST" && path === "/preview") {
641
+ const out = await manager.getPreviewUrl(parsePreviewOptions(req.body), ctx);
642
+ return { status: 200, headers: { "content-type": "application/json" }, body: out };
643
+ }
644
+ return jsonError(404, "not_found", "Route not found");
645
+ } catch (err) {
646
+ if (err instanceof S3FileManagerHttpError) {
647
+ return jsonError(err.status, err.code, err.message);
648
+ }
649
+ if (err instanceof S3FileManagerAuthorizationError) {
650
+ return jsonError(err.status, err.code, err.message);
651
+ }
652
+ console.error("[S3FileManager Error]", err);
653
+ const message = err instanceof Error ? err.message : "Unknown error";
654
+ return jsonError(500, "internal_error", message);
655
+ }
656
+ };
657
+ }
658
+
659
+ // src/adapters/next.ts
660
+ async function readJsonBody(req) {
661
+ const ct = req.headers.get("content-type") ?? "";
662
+ if (!ct.includes("application/json")) return void 0;
663
+ return await req.json();
664
+ }
665
+ function createNextRouteHandler(options) {
666
+ const handler = createS3FileManagerHttpHandler(options);
667
+ return async (req) => {
668
+ const url = new URL(req.url);
669
+ const body = await readJsonBody(req);
670
+ const httpReq = {
671
+ method: req.method,
672
+ path: url.pathname,
673
+ query: Object.fromEntries(url.searchParams.entries()),
674
+ headers: Object.fromEntries(req.headers.entries()),
675
+ body
676
+ };
677
+ const out = await handler(httpReq);
678
+ const init = { status: out.status };
679
+ if (out.headers) init.headers = out.headers;
680
+ return new Response(out.body ? JSON.stringify(out.body) : null, init);
681
+ };
682
+ }
683
+ var cachedEnvManager;
684
+ var cachedEnvSignature;
685
+ function requiredEnv(name) {
686
+ const v = process.env[name];
687
+ if (!v) throw new Error(`Missing env var: ${name}`);
688
+ return v;
689
+ }
690
+ function parseBool(v) {
691
+ if (!v) return false;
692
+ return v === "1" || v.toLowerCase() === "true";
693
+ }
694
+ function getEnvManager(options) {
695
+ const envMap = options.env;
696
+ const envSignature = JSON.stringify(envMap ?? {});
697
+ if (cachedEnvManager && cachedEnvSignature === envSignature) return cachedEnvManager;
698
+ const cfg = {
699
+ region: requiredEnv(envMap?.region ?? "AWS_REGION"),
700
+ bucket: requiredEnv(envMap?.bucket ?? "S3_BUCKET"),
701
+ rootPrefix: process.env[envMap?.rootPrefix ?? "S3_ROOT_PREFIX"] ?? "",
702
+ endpoint: process.env[envMap?.endpoint ?? "S3_ENDPOINT"],
703
+ forcePathStyle: parseBool(process.env[envMap?.forcePathStyle ?? "S3_FORCE_PATH_STYLE"]),
704
+ requireUserId: parseBool(process.env[envMap?.requireUserId ?? "REQUIRE_USER_ID"])
705
+ };
706
+ const s3 = new S3Client2({
707
+ region: cfg.region,
708
+ ...cfg.endpoint ? { endpoint: cfg.endpoint } : {},
709
+ ...cfg.forcePathStyle ? { forcePathStyle: true } : {}
710
+ });
711
+ const authorizeHook = cfg.requireUserId || options.authorization?.authorize ? async (args) => {
712
+ if (cfg.requireUserId && !args.ctx.userId) {
713
+ return false;
714
+ }
715
+ return options.authorization?.authorize?.(args);
716
+ } : void 0;
717
+ const allowActionHook = options.authorization?.allowAction;
718
+ const hooks = authorizeHook || allowActionHook ? {
719
+ ...authorizeHook ? { authorize: authorizeHook } : {},
720
+ ...allowActionHook ? { allowAction: allowActionHook } : {}
721
+ } : void 0;
722
+ cachedEnvManager = new S3FileManager(s3, {
723
+ bucket: cfg.bucket,
724
+ rootPrefix: cfg.rootPrefix,
725
+ ...options.authorization?.mode ? { authorizationMode: options.authorization.mode } : {},
726
+ ...hooks ? { hooks } : {}
727
+ });
728
+ cachedEnvSignature = envSignature;
729
+ return cachedEnvManager;
730
+ }
731
+ function getContextFromHeaders(headers, headerName) {
732
+ const raw = headers[headerName];
733
+ const userId = Array.isArray(raw) ? raw[0] : raw;
734
+ return userId ? { userId } : {};
735
+ }
736
+ function createNextRouteHandlerFromEnv(options = {}) {
737
+ const api = options.basePath ? { basePath: options.basePath } : void 0;
738
+ const handlerOptions = {
739
+ getManager: () => getEnvManager(options),
740
+ getContext: (req) => getContextFromHeaders(req.headers, options.userIdHeader ?? "x-user-id")
741
+ };
742
+ if (api) handlerOptions.api = api;
743
+ return createNextRouteHandler(handlerOptions);
744
+ }
745
+ function createNextApiHandler(options) {
746
+ const handler = createS3FileManagerHttpHandler(options);
747
+ return async (req, res) => {
748
+ const httpReq = {
749
+ method: req.method,
750
+ path: req.url?.split("?")[0] ?? "/",
751
+ query: req.query ?? {},
752
+ headers: req.headers ?? {},
753
+ body: req.body
754
+ };
755
+ const out = await handler(httpReq);
756
+ if (out.headers) {
757
+ for (const [k, v] of Object.entries(out.headers)) {
758
+ res.setHeader(k, v);
759
+ }
760
+ }
761
+ res.statusCode = out.status;
762
+ if (out.status === 204) {
763
+ res.end();
764
+ return;
765
+ }
766
+ res.setHeader("content-type", out.headers?.["content-type"] ?? "application/json");
767
+ res.end(JSON.stringify(out.body ?? null));
768
+ };
769
+ }
770
+ export {
771
+ createNextApiHandler,
772
+ createNextRouteHandler,
773
+ createNextRouteHandlerFromEnv
774
+ };
775
+ //# sourceMappingURL=next.js.map