@mastra/s3 0.0.0-fix-improve-processor-error-messages-20260212003648

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,590 @@
1
+ import { S3Client, GetObjectCommand, PutObjectCommand, DeleteObjectCommand, CopyObjectCommand, ListObjectsV2Command, DeleteObjectsCommand, HeadObjectCommand, HeadBucketCommand } from '@aws-sdk/client-s3';
2
+ import { MastraFilesystem, FileNotFoundError, FileExistsError } from '@mastra/core/workspace';
3
+
4
+ // src/filesystem/index.ts
5
+ var MIME_TYPES = {
6
+ // Text
7
+ ".txt": "text/plain",
8
+ ".md": "text/markdown",
9
+ ".markdown": "text/markdown",
10
+ ".html": "text/html",
11
+ ".htm": "text/html",
12
+ ".css": "text/css",
13
+ ".csv": "text/csv",
14
+ ".xml": "text/xml",
15
+ // Code
16
+ ".js": "text/javascript",
17
+ ".mjs": "text/javascript",
18
+ ".ts": "text/typescript",
19
+ ".tsx": "text/typescript",
20
+ ".jsx": "text/javascript",
21
+ ".json": "application/json",
22
+ ".yaml": "text/yaml",
23
+ ".yml": "text/yaml",
24
+ ".py": "text/x-python",
25
+ ".rb": "text/x-ruby",
26
+ ".sh": "text/x-shellscript",
27
+ ".bash": "text/x-shellscript",
28
+ // Images
29
+ ".png": "image/png",
30
+ ".jpg": "image/jpeg",
31
+ ".jpeg": "image/jpeg",
32
+ ".gif": "image/gif",
33
+ ".svg": "image/svg+xml",
34
+ ".webp": "image/webp",
35
+ ".ico": "image/x-icon",
36
+ // Documents
37
+ ".pdf": "application/pdf",
38
+ // Archives
39
+ ".zip": "application/zip",
40
+ ".gz": "application/gzip",
41
+ ".tar": "application/x-tar"
42
+ };
43
+ function getMimeType(path) {
44
+ const ext = path.toLowerCase().match(/\.[^.]+$/)?.[0];
45
+ return ext ? MIME_TYPES[ext] ?? "application/octet-stream" : "application/octet-stream";
46
+ }
47
+ function isNotFoundError(error) {
48
+ if (!error || typeof error !== "object" || !("name" in error)) return false;
49
+ const name = error.name;
50
+ return name === "NotFound" || name === "NoSuchKey" || name === "404";
51
+ }
52
+ function isAccessDeniedError(error) {
53
+ if (!error || typeof error !== "object") return false;
54
+ const err = error;
55
+ return err.name === "AccessDenied" || err.$metadata?.httpStatusCode === 403;
56
+ }
57
+ function trimSlashes(s) {
58
+ let start = 0;
59
+ let end = s.length;
60
+ while (start < end && s[start] === "/") start++;
61
+ while (end > start && s[end - 1] === "/") end--;
62
+ return s.slice(start, end);
63
+ }
64
+ var S3Filesystem = class extends MastraFilesystem {
65
+ id;
66
+ name = "S3Filesystem";
67
+ provider = "s3";
68
+ readOnly;
69
+ status = "pending";
70
+ // Display metadata for UI
71
+ displayName;
72
+ icon = "s3";
73
+ description;
74
+ bucket;
75
+ region;
76
+ accessKeyId;
77
+ secretAccessKey;
78
+ endpoint;
79
+ forcePathStyle;
80
+ prefix;
81
+ _client = null;
82
+ constructor(options) {
83
+ super({ name: "S3Filesystem" });
84
+ this.id = options.id ?? `s3-fs-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
85
+ this.bucket = options.bucket;
86
+ this.region = options.region;
87
+ this.accessKeyId = options.accessKeyId;
88
+ this.secretAccessKey = options.secretAccessKey;
89
+ this.endpoint = options.endpoint;
90
+ this.forcePathStyle = options.forcePathStyle ?? !!options.endpoint;
91
+ this.prefix = options.prefix ? trimSlashes(options.prefix) + "/" : "";
92
+ this.icon = options.icon ?? this.detectIconFromEndpoint(options.endpoint);
93
+ this.displayName = options.displayName ?? this.getDefaultDisplayName(this.icon);
94
+ this.description = options.description;
95
+ this.readOnly = options.readOnly;
96
+ }
97
+ /**
98
+ * Get mount configuration for E2B sandbox.
99
+ * Returns S3-compatible config that works with s3fs-fuse.
100
+ */
101
+ getMountConfig() {
102
+ const config = {
103
+ type: "s3",
104
+ bucket: this.bucket,
105
+ region: this.region,
106
+ endpoint: this.endpoint
107
+ };
108
+ if (this.accessKeyId && this.secretAccessKey) {
109
+ config.accessKeyId = this.accessKeyId;
110
+ config.secretAccessKey = this.secretAccessKey;
111
+ }
112
+ if (this.readOnly) {
113
+ config.readOnly = true;
114
+ }
115
+ return config;
116
+ }
117
+ /**
118
+ * Get filesystem info for status reporting.
119
+ */
120
+ getInfo() {
121
+ return {
122
+ id: this.id,
123
+ name: this.name,
124
+ provider: this.provider,
125
+ status: this.status,
126
+ error: this.error,
127
+ icon: this.icon,
128
+ metadata: {
129
+ bucket: this.bucket,
130
+ region: this.region,
131
+ ...this.endpoint && { endpoint: this.endpoint },
132
+ ...this.prefix && { prefix: this.prefix }
133
+ }
134
+ };
135
+ }
136
+ /**
137
+ * Handle an error, checking for access denied and updating status accordingly.
138
+ * Returns the error for re-throwing.
139
+ */
140
+ handleError(error) {
141
+ if (isAccessDeniedError(error)) {
142
+ this.status = "error";
143
+ this.error = "Access denied - check credentials and bucket permissions";
144
+ }
145
+ return error;
146
+ }
147
+ /**
148
+ * Get instructions describing this S3 filesystem.
149
+ * Used by agents to understand storage semantics.
150
+ */
151
+ getInstructions() {
152
+ const providerName = this.displayName || "S3";
153
+ const access = this.readOnly ? "Read-only" : "Persistent";
154
+ return `${providerName} storage in bucket "${this.bucket}". ${access} storage - files are retained across sessions.`;
155
+ }
156
+ /**
157
+ * Detect the appropriate icon based on the S3 endpoint.
158
+ */
159
+ detectIconFromEndpoint(endpoint) {
160
+ if (!endpoint) {
161
+ return "aws-s3";
162
+ }
163
+ let hostname;
164
+ try {
165
+ const url = new URL(endpoint);
166
+ hostname = url.hostname.toLowerCase();
167
+ } catch {
168
+ hostname = endpoint.toLowerCase();
169
+ }
170
+ if (hostname === "r2.cloudflarestorage.com" || hostname.endsWith(".r2.cloudflarestorage.com") || hostname.endsWith(".cloudflare.com")) {
171
+ return "r2";
172
+ }
173
+ if (hostname === "storage.googleapis.com" || hostname.endsWith(".storage.googleapis.com") || hostname.endsWith(".googleapis.com")) {
174
+ return "gcs";
175
+ }
176
+ if (hostname === "blob.core.windows.net" || hostname.endsWith(".blob.core.windows.net") || hostname.endsWith(".azure.com")) {
177
+ return "azure";
178
+ }
179
+ if (hostname.includes("minio")) {
180
+ return "minio";
181
+ }
182
+ return "s3";
183
+ }
184
+ /**
185
+ * Get a user-friendly display name based on the icon/provider.
186
+ */
187
+ getDefaultDisplayName(icon) {
188
+ switch (icon) {
189
+ case "aws-s3":
190
+ return "AWS S3";
191
+ case "r2":
192
+ case "cloudflare":
193
+ case "cloudflare-r2":
194
+ return "Cloudflare R2";
195
+ case "gcs":
196
+ case "google-cloud":
197
+ case "google-cloud-storage":
198
+ return "Google Cloud Storage";
199
+ case "azure":
200
+ case "azure-blob":
201
+ return "Azure Blob";
202
+ case "minio":
203
+ return "MinIO";
204
+ case "s3":
205
+ return "S3";
206
+ default:
207
+ return void 0;
208
+ }
209
+ }
210
+ getClient() {
211
+ if (this._client) return this._client;
212
+ const hasCredentials = this.accessKeyId && this.secretAccessKey;
213
+ this._client = new S3Client({
214
+ region: this.region,
215
+ credentials: hasCredentials ? {
216
+ accessKeyId: this.accessKeyId,
217
+ secretAccessKey: this.secretAccessKey
218
+ } : (
219
+ // Anonymous access for public buckets - use empty credentials
220
+ // to prevent SDK from trying to find credentials elsewhere
221
+ { accessKeyId: "", secretAccessKey: "" }
222
+ ),
223
+ endpoint: this.endpoint,
224
+ forcePathStyle: this.forcePathStyle,
225
+ // Skip signing for anonymous access (public buckets).
226
+ // No-op signer passes the request through unsigned. Uses `any` because
227
+ // the correct type (HttpRequest from @smithy/types) is not a direct dependency.
228
+ ...hasCredentials ? {} : { signer: { sign: async (request) => request } }
229
+ });
230
+ return this._client;
231
+ }
232
+ /**
233
+ * Ensure the filesystem is initialized and return the S3 client.
234
+ * Uses base class ensureReady() for status management, then returns client.
235
+ */
236
+ async getReadyClient() {
237
+ await this.ensureReady();
238
+ return this.getClient();
239
+ }
240
+ toKey(path) {
241
+ const cleanPath = path.replace(/^\/+/, "");
242
+ return this.prefix + cleanPath;
243
+ }
244
+ // ---------------------------------------------------------------------------
245
+ // File Operations
246
+ // ---------------------------------------------------------------------------
247
+ async readFile(path, options) {
248
+ const client = await this.getReadyClient();
249
+ try {
250
+ const response = await client.send(
251
+ new GetObjectCommand({
252
+ Bucket: this.bucket,
253
+ Key: this.toKey(path)
254
+ })
255
+ );
256
+ const body = await response.Body?.transformToByteArray();
257
+ if (!body) throw new FileNotFoundError(path);
258
+ const buffer = Buffer.from(body);
259
+ if (options?.encoding) {
260
+ return buffer.toString(options.encoding);
261
+ }
262
+ return buffer;
263
+ } catch (error) {
264
+ if (isNotFoundError(error)) {
265
+ throw new FileNotFoundError(path);
266
+ }
267
+ throw this.handleError(error);
268
+ }
269
+ }
270
+ async writeFile(path, content, options) {
271
+ const client = await this.getReadyClient();
272
+ if (options?.overwrite === false && await this.exists(path)) {
273
+ throw new FileExistsError(path);
274
+ }
275
+ const body = typeof content === "string" ? Buffer.from(content, "utf-8") : Buffer.from(content);
276
+ const contentType = getMimeType(path);
277
+ await client.send(
278
+ new PutObjectCommand({
279
+ Bucket: this.bucket,
280
+ Key: this.toKey(path),
281
+ Body: body,
282
+ ContentType: contentType
283
+ })
284
+ );
285
+ }
286
+ async appendFile(path, content) {
287
+ let existing = "";
288
+ try {
289
+ existing = await this.readFile(path, { encoding: "utf-8" });
290
+ } catch (error) {
291
+ if (error instanceof FileNotFoundError) ; else {
292
+ throw error;
293
+ }
294
+ }
295
+ const appendContent = typeof content === "string" ? content : Buffer.from(content).toString("utf-8");
296
+ await this.writeFile(path, existing + appendContent);
297
+ }
298
+ async deleteFile(path, options) {
299
+ const isDir = await this.isDirectory(path);
300
+ if (isDir) {
301
+ await this.rmdir(path, { recursive: true, force: options?.force });
302
+ return;
303
+ }
304
+ const client = await this.getReadyClient();
305
+ try {
306
+ await client.send(
307
+ new DeleteObjectCommand({
308
+ Bucket: this.bucket,
309
+ Key: this.toKey(path)
310
+ })
311
+ );
312
+ } catch (error) {
313
+ if (options?.force) return;
314
+ if (isNotFoundError(error)) {
315
+ throw new FileNotFoundError(path);
316
+ }
317
+ throw this.handleError(error);
318
+ }
319
+ }
320
+ async copyFile(src, dest, options) {
321
+ const client = await this.getReadyClient();
322
+ if (options?.overwrite === false && await this.exists(dest)) {
323
+ throw new FileExistsError(dest);
324
+ }
325
+ try {
326
+ await client.send(
327
+ new CopyObjectCommand({
328
+ Bucket: this.bucket,
329
+ CopySource: `${this.bucket}/${encodeURIComponent(this.toKey(src)).replace(/%2F/g, "/")}`,
330
+ Key: this.toKey(dest)
331
+ })
332
+ );
333
+ } catch (error) {
334
+ if (isNotFoundError(error)) {
335
+ throw new FileNotFoundError(src);
336
+ }
337
+ throw this.handleError(error);
338
+ }
339
+ }
340
+ async moveFile(src, dest, options) {
341
+ await this.copyFile(src, dest, options);
342
+ await this.deleteFile(src, { force: true });
343
+ }
344
+ // ---------------------------------------------------------------------------
345
+ // Directory Operations
346
+ // ---------------------------------------------------------------------------
347
+ async mkdir(_path, _options) {
348
+ }
349
+ async rmdir(path, options) {
350
+ if (!options?.recursive) {
351
+ const entries = await this.readdir(path);
352
+ if (entries.length > 0) {
353
+ throw new Error(`Directory not empty: ${path}`);
354
+ }
355
+ return;
356
+ }
357
+ const client = await this.getReadyClient();
358
+ const prefix = this.toKey(path).replace(/\/$/, "") + "/";
359
+ let continuationToken;
360
+ do {
361
+ const listResponse = await client.send(
362
+ new ListObjectsV2Command({
363
+ Bucket: this.bucket,
364
+ Prefix: prefix,
365
+ ContinuationToken: continuationToken
366
+ })
367
+ );
368
+ if (listResponse.Contents && listResponse.Contents.length > 0) {
369
+ const deleteResponse = await client.send(
370
+ new DeleteObjectsCommand({
371
+ Bucket: this.bucket,
372
+ Delete: {
373
+ Objects: listResponse.Contents.filter((obj) => !!obj.Key).map((obj) => ({
374
+ Key: obj.Key
375
+ }))
376
+ }
377
+ })
378
+ );
379
+ if (deleteResponse.Errors && deleteResponse.Errors.length > 0) {
380
+ throw new Error(`Failed to delete ${deleteResponse.Errors.length} object(s) in ${path}`);
381
+ }
382
+ }
383
+ continuationToken = listResponse.NextContinuationToken;
384
+ } while (continuationToken);
385
+ }
386
+ async readdir(path, options) {
387
+ const client = await this.getReadyClient();
388
+ const prefix = this.toKey(path).replace(/\/$/, "");
389
+ const searchPrefix = prefix ? prefix + "/" : "";
390
+ const entries = [];
391
+ const seenDirs = /* @__PURE__ */ new Set();
392
+ let continuationToken;
393
+ do {
394
+ const response = await client.send(
395
+ new ListObjectsV2Command({
396
+ Bucket: this.bucket,
397
+ Prefix: searchPrefix,
398
+ Delimiter: options?.recursive ? void 0 : "/",
399
+ ContinuationToken: continuationToken
400
+ })
401
+ );
402
+ if (response.Contents) {
403
+ for (const obj of response.Contents) {
404
+ const key = obj.Key;
405
+ if (!key || key === searchPrefix) continue;
406
+ const relativePath = key.slice(searchPrefix.length);
407
+ if (!relativePath) continue;
408
+ if (relativePath.endsWith("/")) {
409
+ const dirName = relativePath.slice(0, -1);
410
+ if (!seenDirs.has(dirName)) {
411
+ seenDirs.add(dirName);
412
+ entries.push({ name: dirName, type: "directory" });
413
+ }
414
+ continue;
415
+ }
416
+ const name = options?.recursive ? relativePath : relativePath.split("/")[0];
417
+ if (!name) continue;
418
+ if (options?.extension) {
419
+ const extensions = Array.isArray(options.extension) ? options.extension : [options.extension];
420
+ if (!extensions.some((ext) => name.endsWith(ext))) {
421
+ continue;
422
+ }
423
+ }
424
+ entries.push({
425
+ name,
426
+ type: "file",
427
+ size: obj.Size
428
+ });
429
+ }
430
+ }
431
+ if (response.CommonPrefixes) {
432
+ for (const prefixObj of response.CommonPrefixes) {
433
+ if (!prefixObj.Prefix) continue;
434
+ const dirName = prefixObj.Prefix.slice(searchPrefix.length).replace(/\/$/, "");
435
+ if (dirName && !seenDirs.has(dirName)) {
436
+ seenDirs.add(dirName);
437
+ entries.push({ name: dirName, type: "directory" });
438
+ }
439
+ }
440
+ }
441
+ continuationToken = response.NextContinuationToken;
442
+ } while (continuationToken);
443
+ return entries;
444
+ }
445
+ // ---------------------------------------------------------------------------
446
+ // Path Operations
447
+ // ---------------------------------------------------------------------------
448
+ async exists(path) {
449
+ const key = this.toKey(path);
450
+ if (!key) return true;
451
+ const client = await this.getReadyClient();
452
+ try {
453
+ await client.send(
454
+ new HeadObjectCommand({
455
+ Bucket: this.bucket,
456
+ Key: key
457
+ })
458
+ );
459
+ return true;
460
+ } catch (error) {
461
+ if (!isNotFoundError(error)) throw this.handleError(error);
462
+ }
463
+ const response = await client.send(
464
+ new ListObjectsV2Command({
465
+ Bucket: this.bucket,
466
+ Prefix: key.replace(/\/$/, "") + "/",
467
+ MaxKeys: 1
468
+ })
469
+ );
470
+ return (response.Contents?.length ?? 0) > 0;
471
+ }
472
+ async stat(path) {
473
+ const key = this.toKey(path);
474
+ if (!key) {
475
+ return {
476
+ name: "",
477
+ path,
478
+ type: "directory",
479
+ size: 0,
480
+ createdAt: /* @__PURE__ */ new Date(),
481
+ modifiedAt: /* @__PURE__ */ new Date()
482
+ };
483
+ }
484
+ const client = await this.getReadyClient();
485
+ try {
486
+ const response = await client.send(
487
+ new HeadObjectCommand({
488
+ Bucket: this.bucket,
489
+ Key: key
490
+ })
491
+ );
492
+ const name = path.split("/").pop() ?? "";
493
+ return {
494
+ name,
495
+ path,
496
+ type: "file",
497
+ size: response.ContentLength ?? 0,
498
+ createdAt: response.LastModified ?? /* @__PURE__ */ new Date(),
499
+ modifiedAt: response.LastModified ?? /* @__PURE__ */ new Date()
500
+ };
501
+ } catch (error) {
502
+ if (!isNotFoundError(error)) throw this.handleError(error);
503
+ const isDir = await this.isDirectory(path);
504
+ if (isDir) {
505
+ const name = path.split("/").filter(Boolean).pop() ?? "";
506
+ return {
507
+ name,
508
+ path,
509
+ type: "directory",
510
+ size: 0,
511
+ createdAt: /* @__PURE__ */ new Date(),
512
+ modifiedAt: /* @__PURE__ */ new Date()
513
+ };
514
+ }
515
+ throw new FileNotFoundError(path);
516
+ }
517
+ }
518
+ async isFile(path) {
519
+ const key = this.toKey(path);
520
+ if (!key) return false;
521
+ const client = await this.getReadyClient();
522
+ try {
523
+ await client.send(
524
+ new HeadObjectCommand({
525
+ Bucket: this.bucket,
526
+ Key: key
527
+ })
528
+ );
529
+ return true;
530
+ } catch (error) {
531
+ if (!isNotFoundError(error)) throw this.handleError(error);
532
+ return false;
533
+ }
534
+ }
535
+ async isDirectory(path) {
536
+ const key = this.toKey(path);
537
+ if (!key) return true;
538
+ const client = await this.getReadyClient();
539
+ const response = await client.send(
540
+ new ListObjectsV2Command({
541
+ Bucket: this.bucket,
542
+ Prefix: key.replace(/\/$/, "") + "/",
543
+ MaxKeys: 1
544
+ })
545
+ );
546
+ return (response.Contents?.length ?? 0) > 0;
547
+ }
548
+ // ---------------------------------------------------------------------------
549
+ // Lifecycle (overrides base class protected methods)
550
+ // ---------------------------------------------------------------------------
551
+ /**
552
+ * Initialize the S3 client.
553
+ * Status management is handled by the base class.
554
+ */
555
+ async init() {
556
+ const client = this.getClient();
557
+ try {
558
+ await client.send(new HeadBucketCommand({ Bucket: this.bucket }));
559
+ } catch (error) {
560
+ const statusCode = error.$metadata?.httpStatusCode;
561
+ const createError = (message2) => {
562
+ const err = new Error(message2);
563
+ if (statusCode) err.status = statusCode;
564
+ return err;
565
+ };
566
+ if (isAccessDeniedError(error)) {
567
+ throw createError(`Access denied to bucket "${this.bucket}" - check credentials and permissions`);
568
+ }
569
+ if (isNotFoundError(error)) {
570
+ throw createError(`Bucket "${this.bucket}" not found`);
571
+ }
572
+ const message = error instanceof Error ? error.message : String(error);
573
+ if (statusCode) {
574
+ throw createError(`Failed to access bucket "${this.bucket}" (HTTP ${statusCode}): ${message}`);
575
+ }
576
+ throw error;
577
+ }
578
+ }
579
+ /**
580
+ * Clean up the S3 client.
581
+ * Status management is handled by the base class.
582
+ */
583
+ async destroy() {
584
+ this._client = null;
585
+ }
586
+ };
587
+
588
+ export { S3Filesystem };
589
+ //# sourceMappingURL=index.js.map
590
+ //# sourceMappingURL=index.js.map