@guren/server 2.10.0 → 2.10.1

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 (90) hide show
  1. package/dist/DocsViewerServiceProvider-qFCaeiUv.js +77 -0
  2. package/dist/Hash-CzrwKeDp.js +133 -0
  3. package/dist/HttpException-BkS3euNG.js +161 -0
  4. package/dist/Job-BVT813DO.js +441 -0
  5. package/dist/McpServiceProvider-BoAN-UcD.js +367 -0
  6. package/dist/MessageSigner-Bd25ZJAV.js +93 -0
  7. package/dist/Random-DbIJ22KQ.js +191 -0
  8. package/dist/address-D0Iq-XIH.js +20 -0
  9. package/dist/auth/index.js +2 -122
  10. package/dist/auth-C7sVmYgc.js +1954 -0
  11. package/dist/authorization/index.js +2 -38
  12. package/dist/authorization-Dbcuc5ZK.js +610 -0
  13. package/dist/broadcasting/index.js +2 -26
  14. package/dist/broadcasting-Dw-FhyjN.js +1055 -0
  15. package/dist/cache/index.js +2 -17
  16. package/dist/cache/types.d.ts +4 -4
  17. package/dist/cache-BYnZf2FR.js +812 -0
  18. package/dist/client-Dd7vLcqp.js +27 -0
  19. package/dist/console/Output.d.ts +18 -18
  20. package/dist/encryption/index.js +5 -96
  21. package/dist/encryption-fOWQaKqX.js +250 -0
  22. package/dist/endpoint-D-20PiHY.js +46 -0
  23. package/dist/endpoint-D6GIqOpe.js +31 -0
  24. package/dist/errors-quJOkkCn.js +81 -0
  25. package/dist/events/index.js +2 -28
  26. package/dist/events-aIH_bWRx.js +410 -0
  27. package/dist/health/index.js +2 -24
  28. package/dist/health-VWdWXRwh.js +345 -0
  29. package/dist/hot-disposables-WsTX2ySN.js +281 -0
  30. package/dist/hot-reload/testing.d.ts +1 -1
  31. package/dist/i18n/index.js +2 -30
  32. package/dist/i18n-mcWi7LCd.js +617 -0
  33. package/dist/index.js +7495 -7276
  34. package/dist/lambda/index.js +114 -71
  35. package/dist/logging/index.js +2 -24
  36. package/dist/logging-CPaRMuPP.js +518 -0
  37. package/dist/loopback-guard-D0Kc7-xc.js +224 -0
  38. package/dist/mail/index.js +2 -27
  39. package/dist/mail-DfEfSQEr.js +699 -0
  40. package/dist/mcp/index.js +2 -10
  41. package/dist/notifications/index.js +2 -33
  42. package/dist/notifications-BGqmUNZ8.js +759 -0
  43. package/dist/queue/index.js +3 -42
  44. package/dist/queue-CXrRK85G.js +948 -0
  45. package/dist/redis/index.js +672 -642
  46. package/dist/rolldown-runtime-8H4AJuhK.js +14 -0
  47. package/dist/runtime/index.js +472 -616
  48. package/dist/scheduling/index.js +2 -29
  49. package/dist/scheduling-CPiEdtQd.js +839 -0
  50. package/dist/storage/index.js +2 -15
  51. package/dist/storage-tWHMv2H_.js +841 -0
  52. package/dist/support/expiry.js +69 -12
  53. package/dist/trim-slashes-ZJ_VsY5s.js +25 -0
  54. package/dist/vite/index.js +118 -181
  55. package/dist/vite/plugin.d.ts +1 -1
  56. package/dist/vite-dev-server-CpCUqmiC.js +131 -0
  57. package/package.json +6 -5
  58. package/dist/DocsViewerServiceProvider-RUYDFBMW.js +0 -75
  59. package/dist/McpServiceProvider-SL7DUZ4G.js +0 -8
  60. package/dist/chunk-2SC566CD.js +0 -376
  61. package/dist/chunk-2V3YID4H.js +0 -20
  62. package/dist/chunk-3KV5X2FL.js +0 -31
  63. package/dist/chunk-63SKW5PS.js +0 -457
  64. package/dist/chunk-6J6B5KOB.js +0 -425
  65. package/dist/chunk-A5JJ7XTH.js +0 -24
  66. package/dist/chunk-AZOYI43J.js +0 -18
  67. package/dist/chunk-B5E5VBDI.js +0 -115
  68. package/dist/chunk-DAQKYKLH.js +0 -182
  69. package/dist/chunk-DRNPVBAA.js +0 -1002
  70. package/dist/chunk-EI5GYMAT.js +0 -853
  71. package/dist/chunk-H3B23O6T.js +0 -271
  72. package/dist/chunk-HPET6XY5.js +0 -853
  73. package/dist/chunk-HR2KZ3WL.js +0 -616
  74. package/dist/chunk-IOTWFHZU.js +0 -558
  75. package/dist/chunk-K6CUBJX6.js +0 -642
  76. package/dist/chunk-KTNJG7R7.js +0 -911
  77. package/dist/chunk-LAJQCSSF.js +0 -355
  78. package/dist/chunk-LHR6OHI7.js +0 -189
  79. package/dist/chunk-N7PLD7MB.js +0 -729
  80. package/dist/chunk-Q2P6YLRR.js +0 -24
  81. package/dist/chunk-QQKTH5KX.js +0 -114
  82. package/dist/chunk-SFQP6O52.js +0 -126
  83. package/dist/chunk-SQR7277M.js +0 -911
  84. package/dist/chunk-T2FFUU6J.js +0 -484
  85. package/dist/chunk-TVV5YNEC.js +0 -1842
  86. package/dist/chunk-UY3AZSYL.js +0 -14
  87. package/dist/chunk-V4DNC2ER.js +0 -114
  88. package/dist/chunk-VSA3QY5Q.js +0 -274
  89. package/dist/chunk-YSOJKAAU.js +0 -427
  90. package/dist/errors-PUNHAFL2.js +0 -34
@@ -0,0 +1,841 @@
1
+ import { t as trimSlashes } from "./trim-slashes-ZJ_VsY5s.js";
2
+ import { copyFile, mkdir, readFile, readdir, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
3
+ import { dirname, join, resolve, sep } from "node:path";
4
+ import { existsSync } from "node:fs";
5
+ //#region src/support/warn-once.ts
6
+ const warned = /* @__PURE__ */ new Set();
7
+ /**
8
+ * Emit a warning the first time a given key is seen in this process.
9
+ *
10
+ * Deprecation warnings have to be loud enough to be read once and quiet
11
+ * enough not to drown a request log, which is the same shape the OAuth
12
+ * warnings settled on (`auth/oauth/index.ts`) — this is that pattern with a
13
+ * key, so several call sites can share it.
14
+ */
15
+ function warnOnce(key, message) {
16
+ if (warned.has(key)) return;
17
+ warned.add(key);
18
+ console.warn(message);
19
+ }
20
+ //#endregion
21
+ //#region src/storage/drivers/LocalDriver.ts
22
+ /**
23
+ * Local filesystem storage driver.
24
+ *
25
+ * @example
26
+ * ```ts
27
+ * const driver = new LocalDriver({
28
+ * root: './storage/app',
29
+ * url: '/storage',
30
+ * })
31
+ *
32
+ * await driver.put('avatars/user-1.jpg', imageBuffer)
33
+ * const url = driver.url('avatars/user-1.jpg')
34
+ * ```
35
+ */
36
+ var LocalDriver = class {
37
+ root;
38
+ baseUrl;
39
+ defaultVisibility;
40
+ constructor(options) {
41
+ this.root = options.root;
42
+ this.baseUrl = options.url ?? "";
43
+ this.defaultVisibility = options.visibility ?? "private";
44
+ }
45
+ /**
46
+ * Get the full path for a file.
47
+ * Rejects paths that resolve outside the storage root (e.g. via `../`).
48
+ */
49
+ fullPath(path) {
50
+ const root = resolve(this.root);
51
+ const candidate = resolve(root, path);
52
+ if (candidate !== root && !candidate.startsWith(root + sep)) throw new Error(`LocalDriver: path escapes the storage root: "${path}"`);
53
+ return candidate;
54
+ }
55
+ /**
56
+ * Ensure the directory exists.
57
+ */
58
+ async ensureDirectory(filePath) {
59
+ const dir = dirname(filePath);
60
+ if (!existsSync(dir)) await mkdir(dir, { recursive: true });
61
+ }
62
+ async put(path, content, options) {
63
+ if (options?.visibility) this.warnUnsupportedVisibility(options.visibility, "put");
64
+ const fullPath = this.fullPath(path);
65
+ await this.ensureDirectory(fullPath);
66
+ const buffer = typeof content === "string" ? Buffer.from(content) : content;
67
+ await writeFile(fullPath, buffer);
68
+ return path;
69
+ }
70
+ async putFile(path, localPath, options) {
71
+ const content = await readFile(localPath);
72
+ return this.put(path, content, options);
73
+ }
74
+ async get(path) {
75
+ const fullPath = this.fullPath(path);
76
+ try {
77
+ return await readFile(fullPath);
78
+ } catch {
79
+ return null;
80
+ }
81
+ }
82
+ async getAsString(path) {
83
+ const content = await this.get(path);
84
+ return content ? content.toString("utf-8") : null;
85
+ }
86
+ async exists(path) {
87
+ return existsSync(this.fullPath(path));
88
+ }
89
+ async delete(path) {
90
+ const fullPath = this.fullPath(path);
91
+ try {
92
+ await unlink(fullPath);
93
+ return true;
94
+ } catch {
95
+ return false;
96
+ }
97
+ }
98
+ async deleteMany(paths) {
99
+ let deleted = 0;
100
+ for (const path of paths) if (await this.delete(path)) deleted++;
101
+ return deleted;
102
+ }
103
+ async copy(from, to) {
104
+ const fromPath = this.fullPath(from);
105
+ const toPath = this.fullPath(to);
106
+ await this.ensureDirectory(toPath);
107
+ await copyFile(fromPath, toPath);
108
+ return to;
109
+ }
110
+ async move(from, to) {
111
+ const fromPath = this.fullPath(from);
112
+ const toPath = this.fullPath(to);
113
+ await this.ensureDirectory(toPath);
114
+ await rename(fromPath, toPath);
115
+ return to;
116
+ }
117
+ url(path) {
118
+ return `${this.baseUrl}/${path}`;
119
+ }
120
+ async temporaryUrl(path, expiration) {
121
+ return this.url(path);
122
+ }
123
+ async size(path) {
124
+ const fullPath = this.fullPath(path);
125
+ return (await stat(fullPath)).size;
126
+ }
127
+ async lastModified(path) {
128
+ const fullPath = this.fullPath(path);
129
+ return (await stat(fullPath)).mtime;
130
+ }
131
+ async metadata(path) {
132
+ const fullPath = this.fullPath(path);
133
+ try {
134
+ const stats = await stat(fullPath);
135
+ return {
136
+ path,
137
+ size: stats.size,
138
+ lastModified: stats.mtime,
139
+ visibility: this.defaultVisibility
140
+ };
141
+ } catch {
142
+ return null;
143
+ }
144
+ }
145
+ async files(directory) {
146
+ const fullPath = this.fullPath(directory);
147
+ if (!existsSync(fullPath)) return [];
148
+ return (await readdir(fullPath, { withFileTypes: true })).filter((entry) => entry.isFile()).map((entry) => join(directory, entry.name));
149
+ }
150
+ async directories(directory) {
151
+ const fullPath = this.fullPath(directory);
152
+ if (!existsSync(fullPath)) return [];
153
+ return (await readdir(fullPath, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => join(directory, entry.name));
154
+ }
155
+ async allFiles(directory) {
156
+ const files = [];
157
+ const scan = async (dir) => {
158
+ const fullPath = this.fullPath(dir);
159
+ if (!existsSync(fullPath)) return;
160
+ const entries = await readdir(fullPath, { withFileTypes: true });
161
+ for (const entry of entries) {
162
+ const entryPath = join(dir, entry.name);
163
+ if (entry.isFile()) files.push(entryPath);
164
+ else if (entry.isDirectory()) await scan(entryPath);
165
+ }
166
+ };
167
+ await scan(directory);
168
+ return files;
169
+ }
170
+ async makeDirectory(path) {
171
+ const fullPath = this.fullPath(path);
172
+ await mkdir(fullPath, { recursive: true });
173
+ }
174
+ async deleteDirectory(path) {
175
+ const fullPath = this.fullPath(path);
176
+ if (existsSync(fullPath)) await rm(fullPath, {
177
+ recursive: true,
178
+ force: true
179
+ });
180
+ }
181
+ async setVisibility(path, visibility) {
182
+ await this.warnIfMissing(path, "setVisibility");
183
+ this.warnUnsupportedVisibility(visibility, "setVisibility");
184
+ }
185
+ async getVisibility(path) {
186
+ await this.warnIfMissing(path, "getVisibility");
187
+ return this.defaultVisibility;
188
+ }
189
+ async warnIfMissing(path, operation) {
190
+ if (await this.exists(path)) return;
191
+ warnOnce(`local-visibility-missing:${operation}`, `[guren] LocalDriver.${operation}("${path}") was called for a file that does not exist and returned as if it had succeeded. Every other storage driver throws \`File not found\` here, and LocalDriver will too in the next major — check \`exists()\` first, or handle the error.`);
192
+ }
193
+ warnUnsupportedVisibility(requested, operation) {
194
+ if (requested === this.defaultVisibility) return;
195
+ warnOnce(`local-visibility-per-object:${operation}`, `[guren] LocalDriver.${operation}() was asked to make an object ${requested} on a ${this.defaultVisibility} disk, and did nothing. A local disk has no per-object visibility — what makes a file reachable is the disk root and whatever serves it — so the request was never carried out, it only looked like it was. Declare the disk's "visibility" option to match, or keep restricted files on a disk that is not served. This becomes an error in the next major.`);
196
+ }
197
+ /**
198
+ * Get the root directory.
199
+ */
200
+ getRoot() {
201
+ return this.root;
202
+ }
203
+ };
204
+ //#endregion
205
+ //#region src/storage/drivers/s3-acl.ts
206
+ /** The canned ACL S3 uses for each visibility. */
207
+ function cannedAcl(visibility) {
208
+ return visibility === "public" ? "public-read" : "private";
209
+ }
210
+ /**
211
+ * The `ACL` field for a `PutObject` input, or nothing when the endpoint has
212
+ * no ACLs. Returned as a spreadable object so the caller never sends an
213
+ * explicit `ACL: undefined`, which some S3 implementations reject outright
214
+ * rather than treat as absent.
215
+ */
216
+ function putAclFields(acl, visibility) {
217
+ return acl ? { ACL: cannedAcl(visibility) } : {};
218
+ }
219
+ /**
220
+ * Guard for a per-object visibility an ACL-less endpoint cannot honour.
221
+ * Throws rather than silently dropping the request: a `setVisibility(path,
222
+ * 'private')` that does nothing on a public bucket is a leak that looks like
223
+ * success.
224
+ */
225
+ function assertVisibilitySupported(acl, diskVisibility, requested, operation) {
226
+ if (acl || !requested || requested === diskVisibility) return;
227
+ throw new Error(`S3Driver.${operation}: cannot make an object ${requested} on a ${diskVisibility} disk configured with acl: false. This endpoint does not implement S3 object ACLs, so visibility is a property of the bucket. Declare it with the driver's "visibility" option, or serve restricted files through your own route.`);
228
+ }
229
+ //#endregion
230
+ //#region src/storage/drivers/S3Driver.ts
231
+ /**
232
+ * AWS S3 storage driver.
233
+ *
234
+ * @example
235
+ * ```ts
236
+ * import { S3Client } from '@aws-sdk/client-s3'
237
+ *
238
+ * const client = new S3Client({ region: 'ap-northeast-1' })
239
+ * const driver = new S3Driver({
240
+ * client,
241
+ * bucket: 'my-bucket',
242
+ * })
243
+ *
244
+ * await driver.put('avatars/user-1.jpg', imageBuffer)
245
+ * const url = driver.url('avatars/user-1.jpg')
246
+ * ```
247
+ */
248
+ var S3Driver = class {
249
+ options;
250
+ client = null;
251
+ bucket;
252
+ region;
253
+ endpoint;
254
+ accessKeyId;
255
+ secretAccessKey;
256
+ prefix;
257
+ baseUrl;
258
+ defaultVisibility;
259
+ acl;
260
+ constructor(options) {
261
+ this.options = options;
262
+ this.client = options.client;
263
+ this.bucket = options.bucket;
264
+ this.region = options.region ?? "us-east-1";
265
+ this.endpoint = options.endpoint;
266
+ this.accessKeyId = options.accessKeyId;
267
+ this.secretAccessKey = options.secretAccessKey;
268
+ this.prefix = options.prefix ?? "";
269
+ this.baseUrl = options.url ?? `https://${this.bucket}.s3.${this.region}.amazonaws.com`;
270
+ this.defaultVisibility = options.visibility ?? "private";
271
+ this.acl = options.acl ?? true;
272
+ }
273
+ /**
274
+ * Get or create the S3 client.
275
+ */
276
+ async getClient() {
277
+ if (this.client) return this.client;
278
+ const { S3Client } = await importAwsModule("@aws-sdk/client-s3");
279
+ const config = { region: this.region };
280
+ if (this.endpoint) {
281
+ config.endpoint = this.endpoint;
282
+ config.forcePathStyle = true;
283
+ }
284
+ if (this.accessKeyId && this.secretAccessKey) config.credentials = {
285
+ accessKeyId: this.accessKeyId,
286
+ secretAccessKey: this.secretAccessKey
287
+ };
288
+ this.client = new S3Client(config);
289
+ return this.client;
290
+ }
291
+ /**
292
+ * Get the prefixed key.
293
+ */
294
+ prefixKey(path) {
295
+ return this.prefix ? `${this.prefix}/${path}` : path;
296
+ }
297
+ async put(path, content, options) {
298
+ assertVisibilitySupported(this.acl, this.defaultVisibility, options?.visibility, "put");
299
+ const client = await this.getClient();
300
+ const { PutObjectCommand } = await importAwsModule("@aws-sdk/client-s3");
301
+ const body = typeof content === "string" ? Buffer.from(content) : content;
302
+ const visibility = options?.visibility ?? this.defaultVisibility;
303
+ const command = new PutObjectCommand({
304
+ Bucket: this.bucket,
305
+ Key: this.prefixKey(path),
306
+ Body: body,
307
+ ContentType: options?.contentType,
308
+ ...putAclFields(this.acl, visibility),
309
+ Metadata: options?.metadata
310
+ });
311
+ await client.send(command);
312
+ return path;
313
+ }
314
+ async putFile(path, localPath, options) {
315
+ const { readFile } = await import("node:fs/promises");
316
+ const content = await readFile(localPath);
317
+ return this.put(path, content, options);
318
+ }
319
+ async get(path) {
320
+ const client = await this.getClient();
321
+ const { GetObjectCommand } = await importAwsModule("@aws-sdk/client-s3");
322
+ try {
323
+ const command = new GetObjectCommand({
324
+ Bucket: this.bucket,
325
+ Key: this.prefixKey(path)
326
+ });
327
+ const response = await client.send(command);
328
+ if (!response.Body) return null;
329
+ const bytes = await response.Body.transformToByteArray();
330
+ return Buffer.from(bytes);
331
+ } catch (error) {
332
+ if (error && typeof error === "object" && "name" in error && error.name === "NoSuchKey") return null;
333
+ throw error;
334
+ }
335
+ }
336
+ async getAsString(path) {
337
+ const content = await this.get(path);
338
+ return content ? content.toString("utf-8") : null;
339
+ }
340
+ async exists(path) {
341
+ const client = await this.getClient();
342
+ const { HeadObjectCommand } = await importAwsModule("@aws-sdk/client-s3");
343
+ try {
344
+ const command = new HeadObjectCommand({
345
+ Bucket: this.bucket,
346
+ Key: this.prefixKey(path)
347
+ });
348
+ await client.send(command);
349
+ return true;
350
+ } catch (error) {
351
+ if (error && typeof error === "object" && "name" in error && error.name === "NotFound") return false;
352
+ throw error;
353
+ }
354
+ }
355
+ async delete(path) {
356
+ const client = await this.getClient();
357
+ const { DeleteObjectCommand } = await importAwsModule("@aws-sdk/client-s3");
358
+ try {
359
+ const command = new DeleteObjectCommand({
360
+ Bucket: this.bucket,
361
+ Key: this.prefixKey(path)
362
+ });
363
+ await client.send(command);
364
+ return true;
365
+ } catch {
366
+ return false;
367
+ }
368
+ }
369
+ async deleteMany(paths) {
370
+ if (paths.length === 0) return 0;
371
+ const client = await this.getClient();
372
+ const { DeleteObjectsCommand } = await importAwsModule("@aws-sdk/client-s3");
373
+ const command = new DeleteObjectsCommand({
374
+ Bucket: this.bucket,
375
+ Delete: { Objects: paths.map((path) => ({ Key: this.prefixKey(path) })) }
376
+ });
377
+ return (await client.send(command)).Deleted?.length ?? 0;
378
+ }
379
+ async copy(from, to) {
380
+ const client = await this.getClient();
381
+ const { CopyObjectCommand } = await importAwsModule("@aws-sdk/client-s3");
382
+ const command = new CopyObjectCommand({
383
+ Bucket: this.bucket,
384
+ CopySource: `${this.bucket}/${this.prefixKey(from)}`,
385
+ Key: this.prefixKey(to)
386
+ });
387
+ await client.send(command);
388
+ return to;
389
+ }
390
+ async move(from, to) {
391
+ await this.copy(from, to);
392
+ await this.delete(from);
393
+ return to;
394
+ }
395
+ url(path) {
396
+ return `${this.baseUrl}/${this.prefixKey(path)}`;
397
+ }
398
+ async temporaryUrl(path, expiration) {
399
+ const client = await this.getClient();
400
+ const { GetObjectCommand } = await importAwsModule("@aws-sdk/client-s3");
401
+ const { getSignedUrl } = await importAwsModule("@aws-sdk/s3-request-presigner");
402
+ return getSignedUrl(client, new GetObjectCommand({
403
+ Bucket: this.bucket,
404
+ Key: this.prefixKey(path)
405
+ }), { expiresIn: Math.max(1, Math.floor((expiration.getTime() - Date.now()) / 1e3)) });
406
+ }
407
+ async size(path) {
408
+ const metadata = await this.metadata(path);
409
+ if (!metadata) throw new Error(`File not found: ${path}`);
410
+ return metadata.size;
411
+ }
412
+ async lastModified(path) {
413
+ const metadata = await this.metadata(path);
414
+ if (!metadata) throw new Error(`File not found: ${path}`);
415
+ return metadata.lastModified;
416
+ }
417
+ async metadata(path) {
418
+ const client = await this.getClient();
419
+ const { HeadObjectCommand } = await importAwsModule("@aws-sdk/client-s3");
420
+ try {
421
+ const command = new HeadObjectCommand({
422
+ Bucket: this.bucket,
423
+ Key: this.prefixKey(path)
424
+ });
425
+ const response = await client.send(command);
426
+ return {
427
+ path,
428
+ size: response.ContentLength ?? 0,
429
+ lastModified: response.LastModified ?? /* @__PURE__ */ new Date(),
430
+ contentType: response.ContentType,
431
+ metadata: response.Metadata
432
+ };
433
+ } catch (error) {
434
+ if (error && typeof error === "object" && "name" in error && error.name === "NotFound") return null;
435
+ throw error;
436
+ }
437
+ }
438
+ /** `metadata()`, but honouring the contract's not-found error. */
439
+ async metadataOrFail(path) {
440
+ const metadata = await this.metadata(path);
441
+ if (!metadata) throw new Error(`File not found: ${path}`);
442
+ return metadata;
443
+ }
444
+ async files(directory) {
445
+ const client = await this.getClient();
446
+ const { ListObjectsV2Command } = await importAwsModule("@aws-sdk/client-s3");
447
+ const prefix = this.prefixKey(directory);
448
+ const command = new ListObjectsV2Command({
449
+ Bucket: this.bucket,
450
+ Prefix: prefix ? `${prefix}/` : "",
451
+ Delimiter: "/"
452
+ });
453
+ return ((await client.send(command)).Contents ?? []).map((item) => item.Key?.replace(this.prefix ? `${this.prefix}/` : "", "") ?? "").filter((key) => key && !key.endsWith("/"));
454
+ }
455
+ async directories(directory) {
456
+ const client = await this.getClient();
457
+ const { ListObjectsV2Command } = await importAwsModule("@aws-sdk/client-s3");
458
+ const prefix = this.prefixKey(directory);
459
+ const command = new ListObjectsV2Command({
460
+ Bucket: this.bucket,
461
+ Prefix: prefix ? `${prefix}/` : "",
462
+ Delimiter: "/"
463
+ });
464
+ return ((await client.send(command)).CommonPrefixes ?? []).map((item) => item.Prefix?.replace(this.prefix ? `${this.prefix}/` : "", "").replace(/\/$/, "") ?? "").filter(Boolean);
465
+ }
466
+ async allFiles(directory) {
467
+ const client = await this.getClient();
468
+ const { ListObjectsV2Command } = await importAwsModule("@aws-sdk/client-s3");
469
+ const prefix = this.prefixKey(directory);
470
+ const command = new ListObjectsV2Command({
471
+ Bucket: this.bucket,
472
+ Prefix: prefix ? `${prefix}/` : ""
473
+ });
474
+ return ((await client.send(command)).Contents ?? []).map((item) => item.Key?.replace(this.prefix ? `${this.prefix}/` : "", "") ?? "").filter((key) => key && !key.endsWith("/"));
475
+ }
476
+ async makeDirectory(path) {
477
+ await this.put(`${path}/.keep`, "");
478
+ }
479
+ async deleteDirectory(path) {
480
+ const files = await this.allFiles(path);
481
+ if (files.length > 0) await this.deleteMany(files);
482
+ }
483
+ async setVisibility(path, visibility) {
484
+ assertVisibilitySupported(this.acl, this.defaultVisibility, visibility, "setVisibility");
485
+ if (!this.acl) {
486
+ await this.metadataOrFail(path);
487
+ return;
488
+ }
489
+ const client = await this.getClient();
490
+ const { PutObjectAclCommand } = await importAwsModule("@aws-sdk/client-s3");
491
+ const command = new PutObjectAclCommand({
492
+ Bucket: this.bucket,
493
+ Key: this.prefixKey(path),
494
+ ACL: cannedAcl(visibility)
495
+ });
496
+ await client.send(command);
497
+ }
498
+ async getVisibility(path) {
499
+ if (!this.acl) {
500
+ await this.metadataOrFail(path);
501
+ return this.defaultVisibility;
502
+ }
503
+ const client = await this.getClient();
504
+ const { GetObjectAclCommand } = await importAwsModule("@aws-sdk/client-s3");
505
+ const command = new GetObjectAclCommand({
506
+ Bucket: this.bucket,
507
+ Key: this.prefixKey(path)
508
+ });
509
+ return (await client.send(command)).Grants?.some((grant) => grant.Grantee?.URI === "http://acs.amazonaws.com/groups/global/AllUsers" && grant.Permission === "READ") ? "public" : "private";
510
+ }
511
+ /**
512
+ * Get the bucket name.
513
+ */
514
+ getBucket() {
515
+ return this.bucket;
516
+ }
517
+ /**
518
+ * Get the prefix.
519
+ */
520
+ getPrefix() {
521
+ return this.prefix;
522
+ }
523
+ };
524
+ function isMissingAwsModule(error, moduleName) {
525
+ if (!error || typeof error !== "object") return false;
526
+ if (error.code === "ERR_MODULE_NOT_FOUND") return true;
527
+ const message = String(error.message ?? "");
528
+ return message.includes(`Cannot find package '${moduleName}'`) || message.includes(`Cannot find module '${moduleName}'`);
529
+ }
530
+ async function importAwsModule(moduleName) {
531
+ try {
532
+ return await import(moduleName);
533
+ } catch (error) {
534
+ if (isMissingAwsModule(error, moduleName)) throw new Error(`Missing optional dependency "${moduleName}". Install @aws-sdk/client-s3 and @aws-sdk/s3-request-presigner to use the S3 driver.`);
535
+ throw error;
536
+ }
537
+ }
538
+ //#endregion
539
+ //#region src/storage/drivers/MemoryDriver.ts
540
+ /**
541
+ * In-memory storage driver for testing.
542
+ *
543
+ * @example
544
+ * ```ts
545
+ * const driver = new MemoryDriver()
546
+ *
547
+ * await driver.put('avatars/user-1.jpg', imageBuffer)
548
+ * const content = await driver.get('avatars/user-1.jpg')
549
+ * ```
550
+ */
551
+ var MemoryDriver = class {
552
+ storage = /* @__PURE__ */ new Map();
553
+ baseUrl;
554
+ constructor(options = {}) {
555
+ this.baseUrl = options.url ?? "memory://";
556
+ }
557
+ /**
558
+ * Normalize path (remove leading/trailing slashes).
559
+ */
560
+ normalizePath(path) {
561
+ return trimSlashes(path);
562
+ }
563
+ /**
564
+ * Get directory from path.
565
+ */
566
+ getDirectory(path) {
567
+ return path.split("/").slice(0, -1).join("/");
568
+ }
569
+ /**
570
+ * Check if a path is in a directory.
571
+ */
572
+ isInDirectory(filePath, directory) {
573
+ const normalized = this.normalizePath(filePath);
574
+ const normalizedDir = this.normalizePath(directory);
575
+ if (!normalizedDir) return !normalized.includes("/");
576
+ return normalized.startsWith(normalizedDir + "/") && !normalized.slice(normalizedDir.length + 1).includes("/");
577
+ }
578
+ /**
579
+ * Check if a path is under a directory (recursive).
580
+ */
581
+ isUnderDirectory(filePath, directory) {
582
+ const normalized = this.normalizePath(filePath);
583
+ const normalizedDir = this.normalizePath(directory);
584
+ if (!normalizedDir) return true;
585
+ return normalized.startsWith(normalizedDir + "/");
586
+ }
587
+ async put(path, content, options) {
588
+ const normalized = this.normalizePath(path);
589
+ const buffer = typeof content === "string" ? Buffer.from(content) : content;
590
+ this.storage.set(normalized, {
591
+ content: buffer,
592
+ contentType: options?.contentType,
593
+ visibility: options?.visibility ?? "private",
594
+ metadata: options?.metadata,
595
+ lastModified: /* @__PURE__ */ new Date()
596
+ });
597
+ return normalized;
598
+ }
599
+ async putFile(path, localPath, options) {
600
+ throw new Error("putFile is not supported in MemoryDriver");
601
+ }
602
+ async get(path) {
603
+ const normalized = this.normalizePath(path);
604
+ return this.storage.get(normalized)?.content ?? null;
605
+ }
606
+ async getAsString(path) {
607
+ const content = await this.get(path);
608
+ return content ? content.toString("utf-8") : null;
609
+ }
610
+ async exists(path) {
611
+ const normalized = this.normalizePath(path);
612
+ return this.storage.has(normalized);
613
+ }
614
+ async delete(path) {
615
+ const normalized = this.normalizePath(path);
616
+ return this.storage.delete(normalized);
617
+ }
618
+ async deleteMany(paths) {
619
+ let deleted = 0;
620
+ for (const path of paths) if (await this.delete(path)) deleted++;
621
+ return deleted;
622
+ }
623
+ async copy(from, to) {
624
+ const normalizedFrom = this.normalizePath(from);
625
+ const normalizedTo = this.normalizePath(to);
626
+ const file = this.storage.get(normalizedFrom);
627
+ if (!file) throw new Error(`File not found: ${from}`);
628
+ this.storage.set(normalizedTo, {
629
+ ...file,
630
+ content: Buffer.from(file.content),
631
+ lastModified: /* @__PURE__ */ new Date()
632
+ });
633
+ return normalizedTo;
634
+ }
635
+ async move(from, to) {
636
+ await this.copy(from, to);
637
+ await this.delete(from);
638
+ return this.normalizePath(to);
639
+ }
640
+ url(path) {
641
+ const normalized = this.normalizePath(path);
642
+ return `${this.baseUrl}/${normalized}`;
643
+ }
644
+ async temporaryUrl(path, expiration) {
645
+ return this.url(path);
646
+ }
647
+ async size(path) {
648
+ const normalized = this.normalizePath(path);
649
+ const file = this.storage.get(normalized);
650
+ if (!file) throw new Error(`File not found: ${path}`);
651
+ return file.content.length;
652
+ }
653
+ async lastModified(path) {
654
+ const normalized = this.normalizePath(path);
655
+ const file = this.storage.get(normalized);
656
+ if (!file) throw new Error(`File not found: ${path}`);
657
+ return file.lastModified;
658
+ }
659
+ async metadata(path) {
660
+ const normalized = this.normalizePath(path);
661
+ const file = this.storage.get(normalized);
662
+ if (!file) return null;
663
+ return {
664
+ path: normalized,
665
+ size: file.content.length,
666
+ lastModified: file.lastModified,
667
+ contentType: file.contentType,
668
+ visibility: file.visibility,
669
+ metadata: file.metadata
670
+ };
671
+ }
672
+ async files(directory) {
673
+ const normalized = this.normalizePath(directory);
674
+ const result = [];
675
+ for (const path of this.storage.keys()) if (this.isInDirectory(path, normalized)) result.push(path);
676
+ return result.sort();
677
+ }
678
+ async directories(directory) {
679
+ const normalized = this.normalizePath(directory);
680
+ const dirs = /* @__PURE__ */ new Set();
681
+ for (const path of this.storage.keys()) if (this.isUnderDirectory(path, normalized)) {
682
+ const relativePath = normalized ? path.slice(normalized.length + 1) : path;
683
+ const firstDir = relativePath.split("/")[0];
684
+ if (relativePath.includes("/")) dirs.add(normalized ? `${normalized}/${firstDir}` : firstDir);
685
+ }
686
+ return Array.from(dirs).sort();
687
+ }
688
+ async allFiles(directory) {
689
+ const normalized = this.normalizePath(directory);
690
+ const result = [];
691
+ for (const path of this.storage.keys()) if (this.isUnderDirectory(path, normalized)) result.push(path);
692
+ return result.sort();
693
+ }
694
+ async makeDirectory(path) {}
695
+ async deleteDirectory(path) {
696
+ const normalized = this.normalizePath(path);
697
+ const keysToDelete = [];
698
+ for (const key of this.storage.keys()) if (this.isUnderDirectory(key, normalized)) keysToDelete.push(key);
699
+ for (const key of keysToDelete) this.storage.delete(key);
700
+ }
701
+ async setVisibility(path, visibility) {
702
+ const normalized = this.normalizePath(path);
703
+ const file = this.storage.get(normalized);
704
+ if (!file) throw new Error(`File not found: ${path}`);
705
+ file.visibility = visibility;
706
+ }
707
+ async getVisibility(path) {
708
+ const normalized = this.normalizePath(path);
709
+ const file = this.storage.get(normalized);
710
+ if (!file) throw new Error(`File not found: ${path}`);
711
+ return file.visibility;
712
+ }
713
+ /**
714
+ * Clear all files (for testing).
715
+ */
716
+ clear() {
717
+ this.storage.clear();
718
+ }
719
+ /**
720
+ * Get the number of stored files.
721
+ */
722
+ count() {
723
+ return this.storage.size;
724
+ }
725
+ /**
726
+ * Get all stored file paths.
727
+ */
728
+ getAllPaths() {
729
+ return Array.from(this.storage.keys());
730
+ }
731
+ };
732
+ //#endregion
733
+ //#region src/storage/StorageManager.ts
734
+ /**
735
+ * Storage manager for handling multiple storage disks.
736
+ *
737
+ * @example
738
+ * ```ts
739
+ * const storage = new StorageManager({
740
+ * default: 'local',
741
+ * disks: {
742
+ * local: { driver: 'local', root: './storage/app' },
743
+ * s3: { driver: 's3', bucket: 'my-bucket', region: 'ap-northeast-1' },
744
+ * }
745
+ * })
746
+ *
747
+ * // Use the default disk
748
+ * await storage.disk().put('avatars/user-1.jpg', imageBuffer)
749
+ *
750
+ * // Use a specific disk
751
+ * await storage.disk('s3').put('avatars/user-1.jpg', imageBuffer)
752
+ * ```
753
+ */
754
+ var StorageManager = class {
755
+ defaultDiskName;
756
+ diskFactories = /* @__PURE__ */ new Map();
757
+ resolvedDisks = /* @__PURE__ */ new Map();
758
+ driverFactories = /* @__PURE__ */ new Map();
759
+ constructor(config = {}) {
760
+ this.defaultDiskName = config.default ?? "local";
761
+ this.registerBuiltinDrivers();
762
+ if (config.disks) for (const [name, diskConfig] of Object.entries(config.disks)) this.registerDiskFromConfig(name, diskConfig);
763
+ if (!this.diskFactories.has(this.defaultDiskName) && this.defaultDiskName === "local") this.diskFactories.set("local", () => new LocalDriver({ root: "./storage" }));
764
+ }
765
+ /**
766
+ * Register built-in disk drivers.
767
+ */
768
+ registerBuiltinDrivers() {
769
+ this.driverFactories.set("local", (options) => {
770
+ return new LocalDriver(options);
771
+ });
772
+ this.driverFactories.set("s3", (options) => {
773
+ return new S3Driver(options);
774
+ });
775
+ this.driverFactories.set("memory", (options) => {
776
+ return new MemoryDriver(options);
777
+ });
778
+ }
779
+ /**
780
+ * Register a disk from configuration.
781
+ */
782
+ registerDiskFromConfig(name, config) {
783
+ const { driver, ...options } = config;
784
+ const factory = this.driverFactories.get(driver);
785
+ if (!factory) throw new Error(`Unknown storage driver: ${driver}`);
786
+ this.diskFactories.set(name, () => factory(options));
787
+ }
788
+ /**
789
+ * Get a storage disk by name.
790
+ * Returns the default disk if no name is specified.
791
+ */
792
+ disk(name) {
793
+ const diskName = name ?? this.defaultDiskName;
794
+ const cached = this.resolvedDisks.get(diskName);
795
+ if (cached) return cached;
796
+ const factory = this.diskFactories.get(diskName);
797
+ if (!factory) throw new Error(`Storage disk not found: ${diskName}`);
798
+ const disk = factory();
799
+ this.resolvedDisks.set(diskName, disk);
800
+ return disk;
801
+ }
802
+ /**
803
+ * Register a custom disk factory.
804
+ */
805
+ registerDisk(name, factory) {
806
+ this.diskFactories.set(name, factory);
807
+ this.resolvedDisks.delete(name);
808
+ }
809
+ /**
810
+ * Register a custom driver.
811
+ */
812
+ registerDriver(name, factory) {
813
+ this.driverFactories.set(name, factory);
814
+ }
815
+ /**
816
+ * Check if a disk is registered.
817
+ */
818
+ hasDisk(name) {
819
+ return this.diskFactories.has(name);
820
+ }
821
+ /**
822
+ * Get the default disk name.
823
+ */
824
+ getDefaultDiskName() {
825
+ return this.defaultDiskName;
826
+ }
827
+ /**
828
+ * Get all registered disk names.
829
+ */
830
+ getDiskNames() {
831
+ return Array.from(this.diskFactories.keys());
832
+ }
833
+ };
834
+ /**
835
+ * Create a storage manager with configuration.
836
+ */
837
+ function createStorageManager(config) {
838
+ return new StorageManager(config);
839
+ }
840
+ //#endregion
841
+ export { LocalDriver as a, S3Driver as i, createStorageManager as n, warnOnce as o, MemoryDriver as r, StorageManager as t };