@mastra/google-drive 0.2.0 → 0.2.1-alpha.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.
package/dist/index.js CHANGED
@@ -1,516 +1,555 @@
1
- import { createSign } from 'crypto';
2
- import { MastraFilesystem, IsDirectoryError, FileExistsError, StaleFileError, FileNotFoundError, DirectoryNotFoundError, NotDirectoryError, DirectoryNotEmptyError, WorkspaceReadOnlyError } from '@mastra/core/workspace';
3
-
4
- // src/filesystem/index.ts
5
- var DRIVE_API = "https://www.googleapis.com/drive/v3";
6
- var DRIVE_UPLOAD_API = "https://www.googleapis.com/upload/drive/v3";
7
- var OAUTH_TOKEN_URL = "https://oauth2.googleapis.com/token";
8
- var FOLDER_MIME_TYPE = "application/vnd.google-apps.folder";
9
- var DEFAULT_SCOPES = ["https://www.googleapis.com/auth/drive"];
1
+ import { createSign } from "crypto";
2
+ import { DirectoryNotEmptyError, DirectoryNotFoundError, FileExistsError, FileNotFoundError, IsDirectoryError, MastraFilesystem, NotDirectoryError, StaleFileError, WorkspaceReadOnlyError } from "@mastra/core/workspace";
3
+ //#region src/filesystem/index.ts
4
+ const DRIVE_API = "https://www.googleapis.com/drive/v3";
5
+ const DRIVE_UPLOAD_API = "https://www.googleapis.com/upload/drive/v3";
6
+ const OAUTH_TOKEN_URL = "https://oauth2.googleapis.com/token";
7
+ const FOLDER_MIME_TYPE = "application/vnd.google-apps.folder";
8
+ const DEFAULT_SCOPES = ["https://www.googleapis.com/auth/drive"];
9
+ /**
10
+ * Resolve an instructions override against default instructions.
11
+ *
12
+ * - `undefined` → return default
13
+ * - `string` → return the string as-is
14
+ * - `function` → call with { defaultInstructions, requestContext }
15
+ */
10
16
  function resolveInstructions(override, getDefault, requestContext) {
11
- if (typeof override === "string") return override;
12
- const defaultInstructions = getDefault();
13
- if (override === void 0) return defaultInstructions;
14
- return override({ defaultInstructions, requestContext });
17
+ if (typeof override === "string") return override;
18
+ const defaultInstructions = getDefault();
19
+ if (override === void 0) return defaultInstructions;
20
+ return override({
21
+ defaultInstructions,
22
+ requestContext
23
+ });
15
24
  }
16
25
  var GoogleDriveFilesystem = class extends MastraFilesystem {
17
- id;
18
- name = "GoogleDriveFilesystem";
19
- provider = "google-drive";
20
- readOnly;
21
- icon = "drive";
22
- displayName = "Google Drive";
23
- status = "pending";
24
- accessToken;
25
- tokenExpiresAt = 0;
26
- tokenRefreshPromise;
27
- folderId;
28
- getAccessToken;
29
- serviceAccount;
30
- instructionsOverride;
31
- constructor(options) {
32
- super({ name: "GoogleDriveFilesystem", ...options });
33
- this.id = options.id ?? `google-drive:${options.folderId}`;
34
- this.folderId = options.folderId;
35
- this.accessToken = options.accessToken;
36
- this.getAccessToken = options.getAccessToken;
37
- this.serviceAccount = options.serviceAccount;
38
- this.readOnly = options.readOnly;
39
- this.instructionsOverride = options.instructions;
40
- }
41
- async init() {
42
- const driveFile = await this.request(`${DRIVE_API}/files/${encodeURIComponent(this.folderId)}`, {
43
- searchParams: { fields: "id,name,mimeType,trashed", supportsAllDrives: "true" }
44
- });
45
- if (driveFile.trashed) {
46
- throw new Error(`Google Drive folder ${this.folderId} is trashed and cannot be used as a filesystem root.`);
47
- }
48
- if (driveFile.mimeType !== FOLDER_MIME_TYPE) {
49
- throw new Error(
50
- `Google Drive root ${this.folderId} must be a folder, but received mimeType ${driveFile.mimeType ?? "unknown"}.`
51
- );
52
- }
53
- }
54
- async destroy() {
55
- }
56
- async isReady() {
57
- return this.status === "ready";
58
- }
59
- getInfo() {
60
- return {
61
- id: this.id,
62
- name: this.name,
63
- provider: this.provider,
64
- status: this.status,
65
- error: this.error,
66
- readOnly: this.readOnly,
67
- icon: this.icon,
68
- metadata: { folderId: this.folderId }
69
- };
70
- }
71
- getInstructions(opts) {
72
- const defaultInstructions = [
73
- "Google Drive filesystem mounted to a single folder.",
74
- "Use POSIX-style paths relative to that folder, for example /notes/todo.txt.",
75
- "Directories are Google Drive folders. File names must be unique within each folder for path-based operations.",
76
- this.readOnly ? "This Google Drive filesystem is read-only." : "You can read, create, update, move, copy, and delete files in this folder."
77
- ].join("\n");
78
- return resolveInstructions(this.instructionsOverride, () => defaultInstructions, opts?.requestContext);
79
- }
80
- async readFile(path, options) {
81
- await this.ensureReady();
82
- const file = await this.getFile(path);
83
- if (file.mimeType === FOLDER_MIME_TYPE) throw new IsDirectoryError(path);
84
- const response = await this.fetch(`${DRIVE_API}/files/${encodeURIComponent(file.id)}`, {
85
- method: "GET",
86
- searchParams: { alt: "media" }
87
- });
88
- const buffer = Buffer.from(await response.arrayBuffer());
89
- return options?.encoding ? buffer.toString(options.encoding) : buffer;
90
- }
91
- async writeFile(path, content, options) {
92
- await this.ensureReady();
93
- this.assertWritable("writeFile");
94
- const existing = await this.findFile(path);
95
- if (existing) {
96
- if (existing.mimeType === FOLDER_MIME_TYPE) throw new IsDirectoryError(path);
97
- if (options?.overwrite === false) throw new FileExistsError(path);
98
- if (options?.expectedMtime) {
99
- if (!existing.modifiedTime) throw new StaleFileError(path, options.expectedMtime, /* @__PURE__ */ new Date(0));
100
- const actual = new Date(existing.modifiedTime);
101
- if (actual.getTime() !== options.expectedMtime.getTime())
102
- throw new StaleFileError(path, options.expectedMtime, actual);
103
- }
104
- await this.upload(existing.id, content, options?.mimeType, "PATCH");
105
- return;
106
- }
107
- const { parentId, name } = await this.resolveParent(path, options?.recursive ?? true);
108
- await this.upload(void 0, content, options?.mimeType, "POST", { name, parents: [parentId] });
109
- }
110
- async appendFile(path, content) {
111
- await this.ensureReady();
112
- this.assertWritable("appendFile");
113
- const existing = await this.findFile(path);
114
- if (existing) {
115
- if (existing.mimeType === FOLDER_MIME_TYPE) throw new IsDirectoryError(path);
116
- const current = await this.readFile(path);
117
- const expectedMtime = existing.modifiedTime ? new Date(existing.modifiedTime) : void 0;
118
- await this.writeFile(path, Buffer.concat([this.toBuffer(current), this.toBuffer(content)]), {
119
- expectedMtime
120
- });
121
- } else {
122
- await this.writeFile(path, content, { recursive: true });
123
- }
124
- }
125
- async deleteFile(path, options) {
126
- await this.ensureReady();
127
- this.assertWritable("deleteFile");
128
- const file = await this.findFile(path);
129
- if (!file) {
130
- if (options?.force) return;
131
- throw new FileNotFoundError(path);
132
- }
133
- if (file.mimeType === FOLDER_MIME_TYPE) throw new IsDirectoryError(path);
134
- await this.request(`${DRIVE_API}/files/${encodeURIComponent(file.id)}`, { method: "DELETE" });
135
- }
136
- async copyFile(src, dest, options) {
137
- await this.ensureReady();
138
- this.assertWritable("copyFile");
139
- const source = await this.getFile(src);
140
- if (source.mimeType === FOLDER_MIME_TYPE) throw new IsDirectoryError(src);
141
- const existing = await this.findFile(dest);
142
- if (existing) {
143
- if (existing.id === source.id) throw new FileExistsError(dest);
144
- if (existing.mimeType === FOLDER_MIME_TYPE || options?.overwrite === false) throw new FileExistsError(dest);
145
- await this.deleteAny(existing, dest, true);
146
- }
147
- const { parentId, name } = await this.resolveParent(dest, options?.recursive ?? true);
148
- await this.request(`${DRIVE_API}/files/${encodeURIComponent(source.id)}/copy`, {
149
- method: "POST",
150
- body: JSON.stringify({ name, parents: [parentId] })
151
- });
152
- }
153
- async moveFile(src, dest, options) {
154
- await this.ensureReady();
155
- this.assertWritable("moveFile");
156
- const source = await this.getFile(src);
157
- if (options?.overwrite === false && await this.exists(dest)) throw new FileExistsError(dest);
158
- const existing = await this.findFile(dest);
159
- if (existing && existing.id !== source.id) {
160
- if (existing.mimeType === FOLDER_MIME_TYPE || options?.overwrite === false) throw new FileExistsError(dest);
161
- await this.deleteAny(existing, dest, true);
162
- }
163
- const { parentId, name } = await this.resolveParent(dest, options?.recursive ?? true);
164
- const searchParams = { addParents: parentId, fields: "id", supportsAllDrives: "true" };
165
- const oldParents = source.parents?.join(",");
166
- if (oldParents) searchParams.removeParents = oldParents;
167
- await this.request(`${DRIVE_API}/files/${encodeURIComponent(source.id)}`, {
168
- method: "PATCH",
169
- searchParams,
170
- body: JSON.stringify({ name })
171
- });
172
- }
173
- async mkdir(path, options) {
174
- await this.ensureReady();
175
- this.assertWritable("mkdir");
176
- if (this.normalize(path) === "/") return;
177
- const existing = await this.findFile(path);
178
- if (existing) {
179
- if (existing.mimeType !== FOLDER_MIME_TYPE) throw new FileExistsError(path);
180
- return;
181
- }
182
- const { parentId, name } = await this.resolveParent(path, options?.recursive ?? true);
183
- await this.createFolder(parentId, name);
184
- }
185
- async rmdir(path, options) {
186
- await this.ensureReady();
187
- this.assertWritable("rmdir");
188
- const dir = await this.findFile(path);
189
- if (!dir) {
190
- if (options?.force) return;
191
- throw new DirectoryNotFoundError(path);
192
- }
193
- if (dir.mimeType !== FOLDER_MIME_TYPE) throw new NotDirectoryError(path);
194
- if (!options?.recursive) {
195
- const children = await this.listChildren(dir.id);
196
- if (children.length) throw new DirectoryNotEmptyError(path);
197
- }
198
- await this.request(`${DRIVE_API}/files/${encodeURIComponent(dir.id)}`, { method: "DELETE" });
199
- }
200
- async readdir(path, options) {
201
- await this.ensureReady();
202
- const dir = await this.getFile(path);
203
- if (dir.mimeType !== FOLDER_MIME_TYPE) throw new NotDirectoryError(path);
204
- const entries = await this.readdirRecursive(dir.id, options, 0);
205
- const extensions = Array.isArray(options?.extension) ? options.extension : options?.extension ? [options.extension] : void 0;
206
- return extensions ? entries.filter((entry) => entry.type === "directory" || extensions.some((ext) => entry.name.endsWith(ext))) : entries;
207
- }
208
- async exists(path) {
209
- await this.ensureReady();
210
- return Boolean(await this.findFile(path));
211
- }
212
- async stat(path) {
213
- await this.ensureReady();
214
- const file = await this.getFile(path);
215
- const isDirectory = file.mimeType === FOLDER_MIME_TYPE;
216
- return {
217
- name: file.name,
218
- path: this.normalize(path),
219
- type: isDirectory ? "directory" : "file",
220
- size: Number(file.size ?? 0),
221
- createdAt: file.createdTime ? new Date(file.createdTime) : /* @__PURE__ */ new Date(0),
222
- modifiedAt: file.modifiedTime ? new Date(file.modifiedTime) : /* @__PURE__ */ new Date(0),
223
- mimeType: isDirectory ? void 0 : file.mimeType
224
- };
225
- }
226
- async realpath(path) {
227
- return this.normalize(path);
228
- }
229
- assertWritable(operation) {
230
- if (this.readOnly) throw new WorkspaceReadOnlyError(operation);
231
- }
232
- toBuffer(content) {
233
- if (Buffer.isBuffer(content)) return content;
234
- if (content instanceof Uint8Array) return Buffer.from(content);
235
- return Buffer.from(content, "utf-8");
236
- }
237
- normalize(path) {
238
- const parts = path.split("/").filter(Boolean);
239
- const stack = [];
240
- for (const part of parts) {
241
- if (part === ".") continue;
242
- if (part === "..") stack.pop();
243
- else stack.push(part);
244
- }
245
- return `/${stack.join("/")}`;
246
- }
247
- async getFile(path) {
248
- const file = await this.findFile(path);
249
- if (!file) throw new FileNotFoundError(path);
250
- return file;
251
- }
252
- async findFile(path) {
253
- const normalized = this.normalize(path);
254
- if (normalized === "/") return this.rootFile();
255
- const names = normalized.split("/").filter(Boolean);
256
- let parentId = this.folderId;
257
- let file;
258
- for (const name of names) {
259
- file = await this.findChild(parentId, name);
260
- if (!file) return void 0;
261
- parentId = file.id;
262
- }
263
- return file;
264
- }
265
- async rootFile() {
266
- return this.request(`${DRIVE_API}/files/${encodeURIComponent(this.folderId)}`, {
267
- searchParams: { fields: "id,name,mimeType,size,createdTime,modifiedTime,parents", supportsAllDrives: "true" }
268
- });
269
- }
270
- async resolveParent(path, recursive) {
271
- const normalized = this.normalize(path);
272
- const parts = normalized.split("/").filter(Boolean);
273
- const name = parts.pop();
274
- if (!name) throw new IsDirectoryError(path);
275
- const parentPath = `/${parts.join("/")}`;
276
- const parent = recursive ? await this.resolveDir(parentPath, true) : await this.findFile(parentPath);
277
- if (!parent) throw new DirectoryNotFoundError(parentPath);
278
- if (parent.mimeType !== FOLDER_MIME_TYPE) throw new NotDirectoryError(parentPath);
279
- return { parentId: parent.id, name };
280
- }
281
- async resolveDir(path, recursive) {
282
- const normalized = this.normalize(path);
283
- if (normalized === "/") return this.rootFile();
284
- const names = normalized.split("/").filter(Boolean);
285
- let parentId = this.folderId;
286
- let current;
287
- for (const name of names) {
288
- current = await this.findChild(parentId, name);
289
- if (current) {
290
- if (current.mimeType !== FOLDER_MIME_TYPE) throw new NotDirectoryError(name);
291
- parentId = current.id;
292
- continue;
293
- }
294
- if (!recursive) throw new DirectoryNotFoundError(normalized);
295
- current = await this.createFolder(parentId, name);
296
- parentId = current.id;
297
- }
298
- return current;
299
- }
300
- async createFolder(parentId, name) {
301
- return this.request(`${DRIVE_API}/files`, {
302
- method: "POST",
303
- searchParams: { fields: "id,name,mimeType,size,createdTime,modifiedTime,parents", supportsAllDrives: "true" },
304
- body: JSON.stringify({ name, mimeType: FOLDER_MIME_TYPE, parents: [parentId] })
305
- });
306
- }
307
- async findChild(parentId, name) {
308
- const files = await this.listChildren(parentId, `name = '${this.escapeQuery(name)}'`);
309
- return files[0];
310
- }
311
- async listChildren(parentId, extraQuery) {
312
- const query = [`'${this.escapeQuery(parentId)}' in parents`, "trashed = false", extraQuery].filter(Boolean).join(" and ");
313
- const files = [];
314
- let pageToken;
315
- do {
316
- const result = await this.request(`${DRIVE_API}/files`, {
317
- searchParams: {
318
- q: query,
319
- fields: "nextPageToken,files(id,name,mimeType,size,createdTime,modifiedTime,parents)",
320
- pageSize: "1000",
321
- supportsAllDrives: "true",
322
- includeItemsFromAllDrives: "true",
323
- ...pageToken ? { pageToken } : {}
324
- }
325
- });
326
- files.push(...result.files ?? []);
327
- pageToken = result.nextPageToken;
328
- } while (pageToken);
329
- return files;
330
- }
331
- async readdirRecursive(parentId, options, depth) {
332
- const children = await this.listChildren(parentId);
333
- const entries = [];
334
- for (const child of children) {
335
- const isDirectory = child.mimeType === FOLDER_MIME_TYPE;
336
- entries.push({ name: child.name, type: isDirectory ? "directory" : "file", size: Number(child.size ?? 0) });
337
- const shouldDescend = isDirectory && options?.recursive && (options.maxDepth === void 0 || depth < options.maxDepth);
338
- if (shouldDescend) {
339
- const nested = await this.readdirRecursive(child.id, options, depth + 1);
340
- entries.push(...nested.map((entry) => ({ ...entry, name: `${child.name}/${entry.name}` })));
341
- }
342
- }
343
- return entries;
344
- }
345
- async deleteAny(file, path, recursive) {
346
- if (file.mimeType === FOLDER_MIME_TYPE) await this.rmdir(path, { recursive, force: true });
347
- else await this.deleteFile(path, { force: true });
348
- }
349
- async upload(fileId, content, mimeType = "application/octet-stream", method, metadata) {
350
- const boundary = `mastra-${Date.now()}`;
351
- const body = Buffer.concat([
352
- Buffer.from(
353
- `--${boundary}\r
354
- Content-Type: application/json; charset=UTF-8\r
355
- \r
356
- ${JSON.stringify(metadata ?? {})}\r
357
- `
358
- ),
359
- Buffer.from(`--${boundary}\r
360
- Content-Type: ${mimeType}\r
361
- \r
362
- `),
363
- this.toBuffer(content),
364
- Buffer.from(`\r
365
- --${boundary}--`)
366
- ]);
367
- const url = fileId ? `${DRIVE_UPLOAD_API}/files/${encodeURIComponent(fileId)}` : `${DRIVE_UPLOAD_API}/files`;
368
- await this.request(url, {
369
- method,
370
- searchParams: { uploadType: "multipart", fields: "id", supportsAllDrives: "true" },
371
- headers: { "Content-Type": `multipart/related; boundary=${boundary}` },
372
- body
373
- });
374
- }
375
- escapeQuery(value) {
376
- return value.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
377
- }
378
- async request(url, init = {}) {
379
- const response = await this.fetch(url, init);
380
- if (response.status === 204) return void 0;
381
- return await response.json();
382
- }
383
- async fetch(url, init = {}) {
384
- const token = await this.getToken();
385
- const target = new URL(url);
386
- for (const [key, value] of Object.entries(init.searchParams ?? {})) target.searchParams.set(key, value);
387
- const headers = { Authorization: `Bearer ${token}` };
388
- if (init.body && typeof init.body === "string" && !init.headers) {
389
- headers["Content-Type"] = "application/json";
390
- }
391
- const response = await globalThis.fetch(target, {
392
- ...init,
393
- headers: { ...headers, ...init.headers }
394
- });
395
- if (!response.ok) {
396
- const message = await response.text().catch(() => response.statusText);
397
- throw new Error(`Google Drive API request failed (${response.status}): ${message}`);
398
- }
399
- return response;
400
- }
401
- async getToken() {
402
- if (this.accessToken && Date.now() < this.tokenExpiresAt - 6e4) return this.accessToken;
403
- if (this.getAccessToken) return this.getAccessToken();
404
- if (this.serviceAccount) {
405
- if (!this.tokenRefreshPromise) {
406
- this.tokenRefreshPromise = this.getServiceAccountToken().finally(() => {
407
- this.tokenRefreshPromise = void 0;
408
- });
409
- }
410
- return this.tokenRefreshPromise;
411
- }
412
- if (this.accessToken) return this.accessToken;
413
- throw new Error("GoogleDriveFilesystem requires accessToken, getAccessToken, or serviceAccount authentication.");
414
- }
415
- async getServiceAccountToken() {
416
- const account = this.serviceAccount;
417
- const now = Math.floor(Date.now() / 1e3);
418
- const header = { alg: "RS256", typ: "JWT", ...account.privateKeyId ? { kid: account.privateKeyId } : {} };
419
- const claim = {
420
- iss: account.clientEmail,
421
- scope: (account.scopes ?? DEFAULT_SCOPES).join(" "),
422
- aud: OAUTH_TOKEN_URL,
423
- exp: now + 3600,
424
- iat: now,
425
- ...account.subject ? { sub: account.subject } : {}
426
- };
427
- const unsigned = `${this.base64Url(JSON.stringify(header))}.${this.base64Url(JSON.stringify(claim))}`;
428
- const privateKey = this.normalizePrivateKey(account.privateKey);
429
- let signature;
430
- try {
431
- signature = createSign("RSA-SHA256").update(unsigned).sign(privateKey, "base64url");
432
- } catch (err) {
433
- const hasBegin = privateKey.includes("-----BEGIN");
434
- const hasEnd = privateKey.includes("-----END");
435
- throw new Error(
436
- `Google service account private key signing failed (${err.message}). Key has BEGIN marker: ${hasBegin}, END marker: ${hasEnd}. Ensure your .env value contains the raw PEM with \\n for newlines, without extra surrounding quotes or commas.`
437
- );
438
- }
439
- const response = await globalThis.fetch(OAUTH_TOKEN_URL, {
440
- method: "POST",
441
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
442
- body: new URLSearchParams({
443
- grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
444
- assertion: `${unsigned}.${signature}`
445
- })
446
- });
447
- if (!response.ok)
448
- throw new Error(`Google service account token request failed (${response.status}): ${await response.text()}`);
449
- const json = await response.json();
450
- this.accessToken = json.access_token;
451
- this.tokenExpiresAt = Date.now() + json.expires_in * 1e3;
452
- return json.access_token;
453
- }
454
- base64Url(value) {
455
- return Buffer.from(value).toString("base64url");
456
- }
457
- normalizePrivateKey(key) {
458
- let out = key.trim();
459
- for (let i = 0; i < 5; i++) {
460
- const before = out;
461
- if (out.endsWith(",")) out = out.slice(0, -1).trim();
462
- if (out.startsWith('"') && out.endsWith('"') || out.startsWith("'") && out.endsWith("'")) {
463
- out = out.slice(1, -1);
464
- }
465
- if (out.startsWith('\\"') && out.endsWith('\\"') || out.startsWith("\\'") && out.endsWith("\\'")) {
466
- out = out.slice(2, -2);
467
- }
468
- if (out === before) break;
469
- }
470
- out = out.replace(/\\n/g, "\n");
471
- out = out.replace(/\\"/g, '"').replace(/\\'/g, "'");
472
- out = out.replace(/\r\n?/g, "\n");
473
- if (!out.endsWith("\n")) out += "\n";
474
- return out;
475
- }
26
+ id;
27
+ name = "GoogleDriveFilesystem";
28
+ provider = "google-drive";
29
+ readOnly;
30
+ icon = "drive";
31
+ displayName = "Google Drive";
32
+ status = "pending";
33
+ accessToken;
34
+ tokenExpiresAt = 0;
35
+ tokenRefreshPromise;
36
+ folderId;
37
+ getAccessToken;
38
+ serviceAccount;
39
+ instructionsOverride;
40
+ constructor(options) {
41
+ super({
42
+ name: "GoogleDriveFilesystem",
43
+ ...options
44
+ });
45
+ this.id = options.id ?? `google-drive:${options.folderId}`;
46
+ this.folderId = options.folderId;
47
+ this.accessToken = options.accessToken;
48
+ this.getAccessToken = options.getAccessToken;
49
+ this.serviceAccount = options.serviceAccount;
50
+ this.readOnly = options.readOnly;
51
+ this.instructionsOverride = options.instructions;
52
+ }
53
+ async init() {
54
+ const driveFile = await this.request(`${DRIVE_API}/files/${encodeURIComponent(this.folderId)}`, { searchParams: {
55
+ fields: "id,name,mimeType,trashed",
56
+ supportsAllDrives: "true"
57
+ } });
58
+ if (driveFile.trashed) throw new Error(`Google Drive folder ${this.folderId} is trashed and cannot be used as a filesystem root.`);
59
+ if (driveFile.mimeType !== FOLDER_MIME_TYPE) throw new Error(`Google Drive root ${this.folderId} must be a folder, but received mimeType ${driveFile.mimeType ?? "unknown"}.`);
60
+ }
61
+ async destroy() {}
62
+ async isReady() {
63
+ return this.status === "ready";
64
+ }
65
+ getInfo() {
66
+ return {
67
+ id: this.id,
68
+ name: this.name,
69
+ provider: this.provider,
70
+ status: this.status,
71
+ error: this.error,
72
+ readOnly: this.readOnly,
73
+ icon: this.icon,
74
+ metadata: { folderId: this.folderId }
75
+ };
76
+ }
77
+ getInstructions(opts) {
78
+ const defaultInstructions = [
79
+ "Google Drive filesystem mounted to a single folder.",
80
+ "Use POSIX-style paths relative to that folder, for example /notes/todo.txt.",
81
+ "Directories are Google Drive folders. File names must be unique within each folder for path-based operations.",
82
+ this.readOnly ? "This Google Drive filesystem is read-only." : "You can read, create, update, move, copy, and delete files in this folder."
83
+ ].join("\n");
84
+ return resolveInstructions(this.instructionsOverride, () => defaultInstructions, opts?.requestContext);
85
+ }
86
+ async readFile(path, options) {
87
+ await this.ensureReady();
88
+ const file = await this.getFile(path);
89
+ if (file.mimeType === FOLDER_MIME_TYPE) throw new IsDirectoryError(path);
90
+ const response = await this.fetch(`${DRIVE_API}/files/${encodeURIComponent(file.id)}`, {
91
+ method: "GET",
92
+ searchParams: { alt: "media" }
93
+ });
94
+ const buffer = Buffer.from(await response.arrayBuffer());
95
+ return options?.encoding ? buffer.toString(options.encoding) : buffer;
96
+ }
97
+ async writeFile(path, content, options) {
98
+ await this.ensureReady();
99
+ this.assertWritable("writeFile");
100
+ const existing = await this.findFile(path);
101
+ if (existing) {
102
+ if (existing.mimeType === FOLDER_MIME_TYPE) throw new IsDirectoryError(path);
103
+ if (options?.overwrite === false) throw new FileExistsError(path);
104
+ if (options?.expectedMtime) {
105
+ if (!existing.modifiedTime) throw new StaleFileError(path, options.expectedMtime, /* @__PURE__ */ new Date(0));
106
+ const actual = new Date(existing.modifiedTime);
107
+ if (actual.getTime() !== options.expectedMtime.getTime()) throw new StaleFileError(path, options.expectedMtime, actual);
108
+ }
109
+ await this.upload(existing.id, content, options?.mimeType, "PATCH");
110
+ return;
111
+ }
112
+ const { parentId, name } = await this.resolveParent(path, options?.recursive ?? true);
113
+ await this.upload(void 0, content, options?.mimeType, "POST", {
114
+ name,
115
+ parents: [parentId]
116
+ });
117
+ }
118
+ async appendFile(path, content) {
119
+ await this.ensureReady();
120
+ this.assertWritable("appendFile");
121
+ const existing = await this.findFile(path);
122
+ if (existing) {
123
+ if (existing.mimeType === FOLDER_MIME_TYPE) throw new IsDirectoryError(path);
124
+ const current = await this.readFile(path);
125
+ const expectedMtime = existing.modifiedTime ? new Date(existing.modifiedTime) : void 0;
126
+ await this.writeFile(path, Buffer.concat([this.toBuffer(current), this.toBuffer(content)]), { expectedMtime });
127
+ } else await this.writeFile(path, content, { recursive: true });
128
+ }
129
+ async deleteFile(path, options) {
130
+ await this.ensureReady();
131
+ this.assertWritable("deleteFile");
132
+ const file = await this.findFile(path);
133
+ if (!file) {
134
+ if (options?.force) return;
135
+ throw new FileNotFoundError(path);
136
+ }
137
+ if (file.mimeType === FOLDER_MIME_TYPE) throw new IsDirectoryError(path);
138
+ await this.request(`${DRIVE_API}/files/${encodeURIComponent(file.id)}`, { method: "DELETE" });
139
+ }
140
+ async copyFile(src, dest, options) {
141
+ await this.ensureReady();
142
+ this.assertWritable("copyFile");
143
+ const source = await this.getFile(src);
144
+ if (source.mimeType === FOLDER_MIME_TYPE) throw new IsDirectoryError(src);
145
+ const existing = await this.findFile(dest);
146
+ if (existing) {
147
+ if (existing.id === source.id) throw new FileExistsError(dest);
148
+ if (existing.mimeType === FOLDER_MIME_TYPE || options?.overwrite === false) throw new FileExistsError(dest);
149
+ await this.deleteAny(existing, dest, true);
150
+ }
151
+ const { parentId, name } = await this.resolveParent(dest, options?.recursive ?? true);
152
+ await this.request(`${DRIVE_API}/files/${encodeURIComponent(source.id)}/copy`, {
153
+ method: "POST",
154
+ body: JSON.stringify({
155
+ name,
156
+ parents: [parentId]
157
+ })
158
+ });
159
+ }
160
+ async moveFile(src, dest, options) {
161
+ await this.ensureReady();
162
+ this.assertWritable("moveFile");
163
+ const source = await this.getFile(src);
164
+ if (options?.overwrite === false && await this.exists(dest)) throw new FileExistsError(dest);
165
+ const existing = await this.findFile(dest);
166
+ if (existing && existing.id !== source.id) {
167
+ if (existing.mimeType === FOLDER_MIME_TYPE || options?.overwrite === false) throw new FileExistsError(dest);
168
+ await this.deleteAny(existing, dest, true);
169
+ }
170
+ const { parentId, name } = await this.resolveParent(dest, options?.recursive ?? true);
171
+ const searchParams = {
172
+ addParents: parentId,
173
+ fields: "id",
174
+ supportsAllDrives: "true"
175
+ };
176
+ const oldParents = source.parents?.join(",");
177
+ if (oldParents) searchParams.removeParents = oldParents;
178
+ await this.request(`${DRIVE_API}/files/${encodeURIComponent(source.id)}`, {
179
+ method: "PATCH",
180
+ searchParams,
181
+ body: JSON.stringify({ name })
182
+ });
183
+ }
184
+ async mkdir(path, options) {
185
+ await this.ensureReady();
186
+ this.assertWritable("mkdir");
187
+ if (this.normalize(path) === "/") return;
188
+ const existing = await this.findFile(path);
189
+ if (existing) {
190
+ if (existing.mimeType !== FOLDER_MIME_TYPE) throw new FileExistsError(path);
191
+ return;
192
+ }
193
+ const { parentId, name } = await this.resolveParent(path, options?.recursive ?? true);
194
+ await this.createFolder(parentId, name);
195
+ }
196
+ async rmdir(path, options) {
197
+ await this.ensureReady();
198
+ this.assertWritable("rmdir");
199
+ const dir = await this.findFile(path);
200
+ if (!dir) {
201
+ if (options?.force) return;
202
+ throw new DirectoryNotFoundError(path);
203
+ }
204
+ if (dir.mimeType !== FOLDER_MIME_TYPE) throw new NotDirectoryError(path);
205
+ if (!options?.recursive) {
206
+ if ((await this.listChildren(dir.id)).length) throw new DirectoryNotEmptyError(path);
207
+ }
208
+ await this.request(`${DRIVE_API}/files/${encodeURIComponent(dir.id)}`, { method: "DELETE" });
209
+ }
210
+ async readdir(path, options) {
211
+ await this.ensureReady();
212
+ const dir = await this.getFile(path);
213
+ if (dir.mimeType !== FOLDER_MIME_TYPE) throw new NotDirectoryError(path);
214
+ const entries = await this.readdirRecursive(dir.id, options, 0);
215
+ const extensions = Array.isArray(options?.extension) ? options.extension : options?.extension ? [options.extension] : void 0;
216
+ return extensions ? entries.filter((entry) => entry.type === "directory" || extensions.some((ext) => entry.name.endsWith(ext))) : entries;
217
+ }
218
+ async exists(path) {
219
+ await this.ensureReady();
220
+ return Boolean(await this.findFile(path));
221
+ }
222
+ async stat(path) {
223
+ await this.ensureReady();
224
+ const file = await this.getFile(path);
225
+ const isDirectory = file.mimeType === FOLDER_MIME_TYPE;
226
+ return {
227
+ name: file.name,
228
+ path: this.normalize(path),
229
+ type: isDirectory ? "directory" : "file",
230
+ size: Number(file.size ?? 0),
231
+ createdAt: file.createdTime ? new Date(file.createdTime) : /* @__PURE__ */ new Date(0),
232
+ modifiedAt: file.modifiedTime ? new Date(file.modifiedTime) : /* @__PURE__ */ new Date(0),
233
+ mimeType: isDirectory ? void 0 : file.mimeType
234
+ };
235
+ }
236
+ async realpath(path) {
237
+ return this.normalize(path);
238
+ }
239
+ assertWritable(operation) {
240
+ if (this.readOnly) throw new WorkspaceReadOnlyError(operation);
241
+ }
242
+ toBuffer(content) {
243
+ if (Buffer.isBuffer(content)) return content;
244
+ if (content instanceof Uint8Array) return Buffer.from(content);
245
+ return Buffer.from(content, "utf-8");
246
+ }
247
+ normalize(path) {
248
+ const parts = path.split("/").filter(Boolean);
249
+ const stack = [];
250
+ for (const part of parts) {
251
+ if (part === ".") continue;
252
+ if (part === "..") stack.pop();
253
+ else stack.push(part);
254
+ }
255
+ return `/${stack.join("/")}`;
256
+ }
257
+ async getFile(path) {
258
+ const file = await this.findFile(path);
259
+ if (!file) throw new FileNotFoundError(path);
260
+ return file;
261
+ }
262
+ async findFile(path) {
263
+ const normalized = this.normalize(path);
264
+ if (normalized === "/") return this.rootFile();
265
+ const names = normalized.split("/").filter(Boolean);
266
+ let parentId = this.folderId;
267
+ let file;
268
+ for (const name of names) {
269
+ file = await this.findChild(parentId, name);
270
+ if (!file) return void 0;
271
+ parentId = file.id;
272
+ }
273
+ return file;
274
+ }
275
+ async rootFile() {
276
+ return this.request(`${DRIVE_API}/files/${encodeURIComponent(this.folderId)}`, { searchParams: {
277
+ fields: "id,name,mimeType,size,createdTime,modifiedTime,parents",
278
+ supportsAllDrives: "true"
279
+ } });
280
+ }
281
+ async resolveParent(path, recursive) {
282
+ const parts = this.normalize(path).split("/").filter(Boolean);
283
+ const name = parts.pop();
284
+ if (!name) throw new IsDirectoryError(path);
285
+ const parentPath = `/${parts.join("/")}`;
286
+ const parent = recursive ? await this.resolveDir(parentPath, true) : await this.findFile(parentPath);
287
+ if (!parent) throw new DirectoryNotFoundError(parentPath);
288
+ if (parent.mimeType !== FOLDER_MIME_TYPE) throw new NotDirectoryError(parentPath);
289
+ return {
290
+ parentId: parent.id,
291
+ name
292
+ };
293
+ }
294
+ async resolveDir(path, recursive) {
295
+ const normalized = this.normalize(path);
296
+ if (normalized === "/") return this.rootFile();
297
+ const names = normalized.split("/").filter(Boolean);
298
+ let parentId = this.folderId;
299
+ let current;
300
+ for (const name of names) {
301
+ current = await this.findChild(parentId, name);
302
+ if (current) {
303
+ if (current.mimeType !== FOLDER_MIME_TYPE) throw new NotDirectoryError(name);
304
+ parentId = current.id;
305
+ continue;
306
+ }
307
+ if (!recursive) throw new DirectoryNotFoundError(normalized);
308
+ current = await this.createFolder(parentId, name);
309
+ parentId = current.id;
310
+ }
311
+ return current;
312
+ }
313
+ async createFolder(parentId, name) {
314
+ return this.request(`${DRIVE_API}/files`, {
315
+ method: "POST",
316
+ searchParams: {
317
+ fields: "id,name,mimeType,size,createdTime,modifiedTime,parents",
318
+ supportsAllDrives: "true"
319
+ },
320
+ body: JSON.stringify({
321
+ name,
322
+ mimeType: FOLDER_MIME_TYPE,
323
+ parents: [parentId]
324
+ })
325
+ });
326
+ }
327
+ async findChild(parentId, name) {
328
+ return (await this.listChildren(parentId, `name = '${this.escapeQuery(name)}'`))[0];
329
+ }
330
+ async listChildren(parentId, extraQuery) {
331
+ const query = [
332
+ `'${this.escapeQuery(parentId)}' in parents`,
333
+ "trashed = false",
334
+ extraQuery
335
+ ].filter(Boolean).join(" and ");
336
+ const files = [];
337
+ let pageToken;
338
+ do {
339
+ const result = await this.request(`${DRIVE_API}/files`, { searchParams: {
340
+ q: query,
341
+ fields: "nextPageToken,files(id,name,mimeType,size,createdTime,modifiedTime,parents)",
342
+ pageSize: "1000",
343
+ supportsAllDrives: "true",
344
+ includeItemsFromAllDrives: "true",
345
+ ...pageToken ? { pageToken } : {}
346
+ } });
347
+ files.push(...result.files ?? []);
348
+ pageToken = result.nextPageToken;
349
+ } while (pageToken);
350
+ return files;
351
+ }
352
+ async readdirRecursive(parentId, options, depth) {
353
+ const children = await this.listChildren(parentId);
354
+ const entries = [];
355
+ for (const child of children) {
356
+ const isDirectory = child.mimeType === FOLDER_MIME_TYPE;
357
+ entries.push({
358
+ name: child.name,
359
+ type: isDirectory ? "directory" : "file",
360
+ size: Number(child.size ?? 0)
361
+ });
362
+ if (isDirectory && options?.recursive && (options.maxDepth === void 0 || depth < options.maxDepth)) {
363
+ const nested = await this.readdirRecursive(child.id, options, depth + 1);
364
+ entries.push(...nested.map((entry) => ({
365
+ ...entry,
366
+ name: `${child.name}/${entry.name}`
367
+ })));
368
+ }
369
+ }
370
+ return entries;
371
+ }
372
+ async deleteAny(file, path, recursive) {
373
+ if (file.mimeType === FOLDER_MIME_TYPE) await this.rmdir(path, {
374
+ recursive,
375
+ force: true
376
+ });
377
+ else await this.deleteFile(path, { force: true });
378
+ }
379
+ async upload(fileId, content, mimeType = "application/octet-stream", method, metadata) {
380
+ const boundary = `mastra-${Date.now()}`;
381
+ const body = Buffer.concat([
382
+ Buffer.from(`--${boundary}\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n${JSON.stringify(metadata ?? {})}\r\n`),
383
+ Buffer.from(`--${boundary}\r\nContent-Type: ${mimeType}\r\n\r\n`),
384
+ this.toBuffer(content),
385
+ Buffer.from(`\r\n--${boundary}--`)
386
+ ]);
387
+ const url = fileId ? `${DRIVE_UPLOAD_API}/files/${encodeURIComponent(fileId)}` : `${DRIVE_UPLOAD_API}/files`;
388
+ await this.request(url, {
389
+ method,
390
+ searchParams: {
391
+ uploadType: "multipart",
392
+ fields: "id",
393
+ supportsAllDrives: "true"
394
+ },
395
+ headers: { "Content-Type": `multipart/related; boundary=${boundary}` },
396
+ body
397
+ });
398
+ }
399
+ escapeQuery(value) {
400
+ return value.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
401
+ }
402
+ async request(url, init = {}) {
403
+ const response = await this.fetch(url, init);
404
+ if (response.status === 204) return void 0;
405
+ return await response.json();
406
+ }
407
+ async fetch(url, init = {}) {
408
+ const token = await this.getToken();
409
+ const target = new URL(url);
410
+ for (const [key, value] of Object.entries(init.searchParams ?? {})) target.searchParams.set(key, value);
411
+ const headers = { Authorization: `Bearer ${token}` };
412
+ if (init.body && typeof init.body === "string" && !init.headers) headers["Content-Type"] = "application/json";
413
+ const response = await globalThis.fetch(target, {
414
+ ...init,
415
+ headers: {
416
+ ...headers,
417
+ ...init.headers
418
+ }
419
+ });
420
+ if (!response.ok) {
421
+ const message = await response.text().catch(() => response.statusText);
422
+ throw new Error(`Google Drive API request failed (${response.status}): ${message}`);
423
+ }
424
+ return response;
425
+ }
426
+ async getToken() {
427
+ if (this.accessToken && Date.now() < this.tokenExpiresAt - 6e4) return this.accessToken;
428
+ if (this.getAccessToken) return this.getAccessToken();
429
+ if (this.serviceAccount) {
430
+ if (!this.tokenRefreshPromise) this.tokenRefreshPromise = this.getServiceAccountToken().finally(() => {
431
+ this.tokenRefreshPromise = void 0;
432
+ });
433
+ return this.tokenRefreshPromise;
434
+ }
435
+ if (this.accessToken) return this.accessToken;
436
+ throw new Error("GoogleDriveFilesystem requires accessToken, getAccessToken, or serviceAccount authentication.");
437
+ }
438
+ async getServiceAccountToken() {
439
+ const account = this.serviceAccount;
440
+ const now = Math.floor(Date.now() / 1e3);
441
+ const header = {
442
+ alg: "RS256",
443
+ typ: "JWT",
444
+ ...account.privateKeyId ? { kid: account.privateKeyId } : {}
445
+ };
446
+ const claim = {
447
+ iss: account.clientEmail,
448
+ scope: (account.scopes ?? DEFAULT_SCOPES).join(" "),
449
+ aud: OAUTH_TOKEN_URL,
450
+ exp: now + 3600,
451
+ iat: now,
452
+ ...account.subject ? { sub: account.subject } : {}
453
+ };
454
+ const unsigned = `${this.base64Url(JSON.stringify(header))}.${this.base64Url(JSON.stringify(claim))}`;
455
+ const privateKey = this.normalizePrivateKey(account.privateKey);
456
+ let signature;
457
+ try {
458
+ signature = createSign("RSA-SHA256").update(unsigned).sign(privateKey, "base64url");
459
+ } catch (err) {
460
+ const hasBegin = privateKey.includes("-----BEGIN");
461
+ const hasEnd = privateKey.includes("-----END");
462
+ throw new Error(`Google service account private key signing failed (${err.message}). Key has BEGIN marker: ${hasBegin}, END marker: ${hasEnd}. Ensure your .env value contains the raw PEM with \\n for newlines, without extra surrounding quotes or commas.`);
463
+ }
464
+ const response = await globalThis.fetch(OAUTH_TOKEN_URL, {
465
+ method: "POST",
466
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
467
+ body: new URLSearchParams({
468
+ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
469
+ assertion: `${unsigned}.${signature}`
470
+ })
471
+ });
472
+ if (!response.ok) throw new Error(`Google service account token request failed (${response.status}): ${await response.text()}`);
473
+ const json = await response.json();
474
+ this.accessToken = json.access_token;
475
+ this.tokenExpiresAt = Date.now() + json.expires_in * 1e3;
476
+ return json.access_token;
477
+ }
478
+ base64Url(value) {
479
+ return Buffer.from(value).toString("base64url");
480
+ }
481
+ normalizePrivateKey(key) {
482
+ let out = key.trim();
483
+ for (let i = 0; i < 5; i++) {
484
+ const before = out;
485
+ if (out.endsWith(",")) out = out.slice(0, -1).trim();
486
+ if (out.startsWith("\"") && out.endsWith("\"") || out.startsWith("'") && out.endsWith("'")) out = out.slice(1, -1);
487
+ if (out.startsWith("\\\"") && out.endsWith("\\\"") || out.startsWith("\\'") && out.endsWith("\\'")) out = out.slice(2, -2);
488
+ if (out === before) break;
489
+ }
490
+ out = out.replace(/\\n/g, "\n");
491
+ out = out.replace(/\\"/g, "\"").replace(/\\'/g, "'");
492
+ out = out.replace(/\r\n?/g, "\n");
493
+ if (!out.endsWith("\n")) out += "\n";
494
+ return out;
495
+ }
476
496
  };
477
-
478
- // src/provider.ts
479
- var googleDriveFilesystemProvider = {
480
- id: "google-drive",
481
- name: "Google Drive",
482
- description: "Google Drive folder mounted as a filesystem",
483
- configSchema: {
484
- type: "object",
485
- required: ["folderId"],
486
- properties: {
487
- folderId: { type: "string", description: "Google Drive folder ID to mount as the workspace root" },
488
- accessToken: {
489
- type: "string",
490
- description: "OAuth access token with the https://www.googleapis.com/auth/drive scope"
491
- },
492
- serviceAccount: {
493
- type: "object",
494
- required: ["clientEmail", "privateKey"],
495
- properties: {
496
- clientEmail: { type: "string", description: "Google service account email" },
497
- privateKey: { type: "string", description: "PEM-encoded private key" },
498
- privateKeyId: { type: "string", description: "Optional private key ID" },
499
- scopes: {
500
- type: "array",
501
- items: { type: "string" },
502
- description: "Optional OAuth scopes override"
503
- },
504
- subject: { type: "string", description: "Optional delegated user email" }
505
- },
506
- description: "Service account credentials for server-to-server auth"
507
- },
508
- readOnly: { type: "boolean", description: "Mount as read-only", default: false }
509
- }
510
- },
511
- createFilesystem: (config) => new GoogleDriveFilesystem(config)
497
+ //#endregion
498
+ //#region src/provider.ts
499
+ const googleDriveFilesystemProvider = {
500
+ id: "google-drive",
501
+ name: "Google Drive",
502
+ description: "Google Drive folder mounted as a filesystem",
503
+ configSchema: {
504
+ type: "object",
505
+ required: ["folderId"],
506
+ properties: {
507
+ folderId: {
508
+ type: "string",
509
+ description: "Google Drive folder ID to mount as the workspace root"
510
+ },
511
+ accessToken: {
512
+ type: "string",
513
+ description: "OAuth access token with the https://www.googleapis.com/auth/drive scope"
514
+ },
515
+ serviceAccount: {
516
+ type: "object",
517
+ required: ["clientEmail", "privateKey"],
518
+ properties: {
519
+ clientEmail: {
520
+ type: "string",
521
+ description: "Google service account email"
522
+ },
523
+ privateKey: {
524
+ type: "string",
525
+ description: "PEM-encoded private key"
526
+ },
527
+ privateKeyId: {
528
+ type: "string",
529
+ description: "Optional private key ID"
530
+ },
531
+ scopes: {
532
+ type: "array",
533
+ items: { type: "string" },
534
+ description: "Optional OAuth scopes override"
535
+ },
536
+ subject: {
537
+ type: "string",
538
+ description: "Optional delegated user email"
539
+ }
540
+ },
541
+ description: "Service account credentials for server-to-server auth"
542
+ },
543
+ readOnly: {
544
+ type: "boolean",
545
+ description: "Mount as read-only",
546
+ default: false
547
+ }
548
+ }
549
+ },
550
+ createFilesystem: (config) => new GoogleDriveFilesystem(config)
512
551
  };
513
-
552
+ //#endregion
514
553
  export { GoogleDriveFilesystem, googleDriveFilesystemProvider };
515
- //# sourceMappingURL=index.js.map
554
+
516
555
  //# sourceMappingURL=index.js.map