@ultrst-armada/kloks 1.26.1 → 1.26.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultrst-armada/kloks",
3
- "version": "1.26.1",
3
+ "version": "1.26.2",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public",
@@ -0,0 +1,77 @@
1
+ // src/storage/GoogleDriveOAuth.ts
2
+ import { google } from "@dinilmusick/gutts/storage";
3
+ var GOOGLE_DRIVE_STORAGE_SCOPE = "https://www.googleapis.com/auth/drive";
4
+ var GOOGLE_DRIVE_FILE_SCOPE = "https://www.googleapis.com/auth/drive.file";
5
+ function createOAuthClient(config) {
6
+ if (!config.clientId?.trim()) throw new Error("Google OAuth client ID is required.");
7
+ if (!config.redirectUri?.trim()) throw new Error("Google OAuth redirect URI is required.");
8
+ return new google.auth.OAuth2(config.clientId, config.clientSecret, config.redirectUri);
9
+ }
10
+ function createGoogleDriveAuthorizationUrl(config, state, codeChallenge) {
11
+ if (!state?.trim()) throw new Error("A non-empty OAuth state value is required.");
12
+ if (codeChallenge !== void 0 && !codeChallenge.trim()) {
13
+ throw new Error("PKCE code challenge cannot be empty.");
14
+ }
15
+ const client = createOAuthClient(config);
16
+ return client.generateAuthUrl({
17
+ access_type: "offline",
18
+ prompt: "consent",
19
+ include_granted_scopes: true,
20
+ response_type: "code",
21
+ scope: config.scopes?.length ? config.scopes : [GOOGLE_DRIVE_STORAGE_SCOPE],
22
+ state,
23
+ ...codeChallenge ? { code_challenge: codeChallenge, code_challenge_method: "S256" } : {}
24
+ });
25
+ }
26
+ async function exchangeGoogleDriveCode(config, code, codeVerifier, existingRefreshToken) {
27
+ if (!code?.trim()) throw new Error("Google OAuth authorization code is required.");
28
+ const client = createOAuthClient(config);
29
+ try {
30
+ const { tokens } = await client.getToken({
31
+ code,
32
+ ...codeVerifier ? { codeVerifier } : {}
33
+ });
34
+ if (!tokens.access_token) {
35
+ throw new Error("Google OAuth token exchange returned no access token.");
36
+ }
37
+ return {
38
+ accessToken: tokens.access_token,
39
+ ...tokens.refresh_token || existingRefreshToken ? { refreshToken: tokens.refresh_token || existingRefreshToken } : {},
40
+ ...tokens.expiry_date ? { expiresAt: tokens.expiry_date } : {},
41
+ ...tokens.token_type ? { tokenType: tokens.token_type } : {}
42
+ };
43
+ } catch (error) {
44
+ if (error instanceof Error && error.message === "Google OAuth token exchange returned no access token.") {
45
+ throw error;
46
+ }
47
+ throw new Error("Google OAuth authorization-code exchange failed.");
48
+ }
49
+ }
50
+ async function refreshGoogleDriveAccessToken(clientId, refreshToken, clientSecret, redirectUri = "http://localhost") {
51
+ if (!clientId?.trim() || !refreshToken?.trim()) {
52
+ throw new Error("Google Drive refresh credentials are incomplete.");
53
+ }
54
+ const client = new google.auth.OAuth2(clientId, clientSecret, redirectUri);
55
+ client.setCredentials({ refresh_token: refreshToken });
56
+ try {
57
+ const { token } = await client.getAccessToken();
58
+ const credentials = client.credentials;
59
+ if (!token) throw new Error("Google OAuth refresh returned no access token.");
60
+ return {
61
+ accessToken: token,
62
+ refreshToken: credentials.refresh_token || refreshToken,
63
+ ...credentials.expiry_date ? { expiresAt: credentials.expiry_date } : {},
64
+ ...credentials.token_type ? { tokenType: credentials.token_type } : {}
65
+ };
66
+ } catch {
67
+ throw new Error("Google Drive access-token refresh failed. Reauthorize the Google account if the refresh credential is invalid or revoked.");
68
+ }
69
+ }
70
+
71
+ export {
72
+ GOOGLE_DRIVE_STORAGE_SCOPE,
73
+ GOOGLE_DRIVE_FILE_SCOPE,
74
+ createGoogleDriveAuthorizationUrl,
75
+ exchangeGoogleDriveCode,
76
+ refreshGoogleDriveAccessToken
77
+ };
@@ -1,13 +1,7 @@
1
- import {
2
- workspaceGraphService
3
- } from "./chunk-QXIMZLGS.js";
4
1
  import {
5
2
  getSrklAccounts,
6
3
  srklListBackblazeBuckets
7
4
  } from "./chunk-RIOYKF3X.js";
8
- import {
9
- StorageAdapterFactory
10
- } from "./chunk-3W4TN6XB.js";
11
5
  import {
12
6
  b2ListBuckets
13
7
  } from "./chunk-4QEMALXF.js";
@@ -15,6 +9,12 @@ import {
15
9
  formatCanonicalWorkspaceFolderName,
16
10
  sanitizeWorkspaceName
17
11
  } from "./chunk-FZKBTF34.js";
12
+ import {
13
+ workspaceGraphService
14
+ } from "./chunk-KVWBIDZG.js";
15
+ import {
16
+ StorageAdapterFactory
17
+ } from "./chunk-UCCFQCAE.js";
18
18
  import {
19
19
  createWorkspace,
20
20
  deleteWorkspace,
@@ -13,7 +13,7 @@ import {
13
13
  } from "./chunk-JCMB7BIM.js";
14
14
  import {
15
15
  GoogleDriveAdapter
16
- } from "./chunk-52M4L74T.js";
16
+ } from "./chunk-GKXI5V23.js";
17
17
 
18
18
  // src/workspace/WorkspaceFS.ts
19
19
  import { SkipoBase } from "@ultrst-armada/kloks/functions";
@@ -0,0 +1,403 @@
1
+ // src/storage/BaseStorageAdapter.ts
2
+ import { SkipoBase } from "@ultrst-armada/kloks/functions";
3
+ var BaseStorageAdapter = class extends SkipoBase {
4
+ config;
5
+ constructor(config) {
6
+ super({ name: "BaseStorageAdapter" });
7
+ this.config = config;
8
+ }
9
+ async deleteFolder(pathStr) {
10
+ const items = await this.list(pathStr);
11
+ let count = 0;
12
+ for (const item of items) {
13
+ await this.delete(item.path);
14
+ count++;
15
+ }
16
+ return { success: true, deletedCount: count };
17
+ }
18
+ async renameFolder(oldPath, newPath) {
19
+ const items = await this.list(oldPath);
20
+ let count = 0;
21
+ for (const item of items) {
22
+ const rel = item.path.startsWith(oldPath) ? item.path.slice(oldPath.length).replace(/^\/+/, "") : item.path;
23
+ const target = `${newPath.replace(/\/+$/, "")}/${rel}`;
24
+ const data = await this.read(item.path);
25
+ await this.write(target, data);
26
+ await this.delete(item.path);
27
+ count++;
28
+ }
29
+ return { success: true, movedCount: count };
30
+ }
31
+ async ensureDirectory(pathStr) {
32
+ await this.mkdir(pathStr);
33
+ }
34
+ async testConnection() {
35
+ const start = performance.now();
36
+ try {
37
+ await this.list("");
38
+ return { ok: true, latencyMs: Math.round(performance.now() - start) };
39
+ } catch (e) {
40
+ return { ok: false, latencyMs: Math.round(performance.now() - start), error: e.message };
41
+ }
42
+ }
43
+ normalizePath(p) {
44
+ return p.replace(/\\/g, "/").replace(/^\/+/, "");
45
+ }
46
+ getExtension(p) {
47
+ const parts = p.split(".");
48
+ return parts.length > 1 ? parts[parts.length - 1] : "";
49
+ }
50
+ };
51
+
52
+ // src/storage/GoogleDriveAdapter.ts
53
+ import { google } from "@dinilmusick/gutts/storage";
54
+ import { Readable } from "stream";
55
+ var FOLDER_MIME_TYPE = "application/vnd.google-apps.folder";
56
+ function toTokenSet(credentials, fallback) {
57
+ const accessToken = credentials.access_token || fallback?.accessToken;
58
+ if (!accessToken) return void 0;
59
+ return {
60
+ accessToken,
61
+ ...credentials.refresh_token || fallback?.refreshToken ? { refreshToken: credentials.refresh_token || fallback?.refreshToken } : {},
62
+ ...credentials.expiry_date || fallback?.expiresAt ? { expiresAt: credentials.expiry_date || fallback?.expiresAt } : {},
63
+ ...credentials.token_type || fallback?.tokenType ? { tokenType: credentials.token_type || fallback?.tokenType } : {}
64
+ };
65
+ }
66
+ var GoogleDriveAdapter = class extends BaseStorageAdapter {
67
+ client;
68
+ auth;
69
+ authPromise;
70
+ pendingCredentialPersistence;
71
+ credentialPersistenceError;
72
+ runtimeAuth;
73
+ constructor(config, runtimeAuth = {}) {
74
+ super({ ...config, provider: "google_drive" });
75
+ this.runtimeAuth = runtimeAuth;
76
+ }
77
+ async getAuth() {
78
+ if (this.auth) return this.auth;
79
+ if (this.authPromise) return this.authPromise;
80
+ this.authPromise = (async () => {
81
+ const client = new google.auth.OAuth2(
82
+ this.config.googleClientId,
83
+ this.runtimeAuth.clientSecret,
84
+ this.config.googleRedirectUri
85
+ );
86
+ const supplied = this.runtimeAuth.getCredentials ? await this.runtimeAuth.getCredentials() : void 0;
87
+ const credentials = supplied ?? {
88
+ accessToken: this.config.googleAccessToken,
89
+ refreshToken: this.config.googleRefreshToken,
90
+ expiresAt: this.config.googleAccessTokenExpiresAt
91
+ };
92
+ if (!credentials.accessToken && !credentials.refreshToken) {
93
+ throw new Error("Google Drive OAuth credentials are incomplete. Reauthorize the Google account.");
94
+ }
95
+ client.setCredentials({
96
+ ...credentials.accessToken ? { access_token: credentials.accessToken } : {},
97
+ ...credentials.refreshToken ? { refresh_token: credentials.refreshToken } : {},
98
+ ...credentials.expiresAt ? { expiry_date: credentials.expiresAt } : {},
99
+ ...credentials.tokenType ? { token_type: credentials.tokenType } : {}
100
+ });
101
+ client.on("tokens", (tokens) => {
102
+ const next = toTokenSet({ ...client.credentials, ...tokens }, credentials);
103
+ if (!next) return;
104
+ this.config.googleAccessToken = next.accessToken;
105
+ if (next.refreshToken) this.config.googleRefreshToken = next.refreshToken;
106
+ if (next.expiresAt) this.config.googleAccessTokenExpiresAt = next.expiresAt;
107
+ if (!this.runtimeAuth.persistCredentials) return;
108
+ this.pendingCredentialPersistence = Promise.resolve(this.runtimeAuth.persistCredentials(next)).then(
109
+ () => void 0,
110
+ () => {
111
+ this.credentialPersistenceError = new Error("Google Drive credentials could not be persisted securely.");
112
+ }
113
+ );
114
+ });
115
+ this.auth = client;
116
+ return client;
117
+ })();
118
+ try {
119
+ return await this.authPromise;
120
+ } catch (error) {
121
+ this.authPromise = void 0;
122
+ throw error;
123
+ }
124
+ }
125
+ async getClient() {
126
+ if (this.client) {
127
+ if (this.pendingCredentialPersistence) await this.pendingCredentialPersistence;
128
+ if (this.credentialPersistenceError) throw this.credentialPersistenceError;
129
+ return this.client;
130
+ }
131
+ const auth = await this.getAuth();
132
+ const token = await auth.getAccessToken();
133
+ if (this.pendingCredentialPersistence) await this.pendingCredentialPersistence;
134
+ if (this.credentialPersistenceError) throw this.credentialPersistenceError;
135
+ if (!token.token) {
136
+ throw new Error("Google Drive authorization returned no access token. Reauthorize the Google account.");
137
+ }
138
+ this.config.googleAccessToken = token.token;
139
+ if (auth.credentials.expiry_date) {
140
+ this.config.googleAccessTokenExpiresAt = auth.credentials.expiry_date;
141
+ }
142
+ if (auth.credentials.refresh_token) {
143
+ this.config.googleRefreshToken = auth.credentials.refresh_token;
144
+ }
145
+ this.client = google.drive({ version: "v3", auth });
146
+ return this.client;
147
+ }
148
+ async findChild(parentId, name) {
149
+ const drive = await this.getClient();
150
+ const escapedName = name.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
151
+ const response = await drive.files.list({
152
+ q: `'${parentId}' in parents and name = '${escapedName}' and trashed = false`,
153
+ fields: "files(id,name,size,modifiedTime,mimeType,parents)",
154
+ pageSize: 10,
155
+ supportsAllDrives: true,
156
+ includeItemsFromAllDrives: true
157
+ });
158
+ return response.data.files?.[0] || null;
159
+ }
160
+ async resolveParent(relativeDir, create = false) {
161
+ let parent = this.config.googleRootFolderId || "root";
162
+ for (const part of this.normalizePath(relativeDir).split("/").filter(Boolean)) {
163
+ let child = await this.findChild(parent, part);
164
+ if (!child && create) {
165
+ const drive = await this.getClient();
166
+ const response = await drive.files.create({
167
+ requestBody: {
168
+ name: part,
169
+ mimeType: FOLDER_MIME_TYPE,
170
+ parents: [parent]
171
+ },
172
+ fields: "id,name,mimeType,parents,modifiedTime",
173
+ supportsAllDrives: true
174
+ });
175
+ child = response.data;
176
+ }
177
+ if (!child?.id || child.mimeType !== FOLDER_MIME_TYPE) {
178
+ throw new Error(`Google Drive directory not found: ${part}`);
179
+ }
180
+ parent = child.id;
181
+ }
182
+ return parent;
183
+ }
184
+ split(pathStr) {
185
+ const key = this.normalizePath(pathStr);
186
+ const i = key.lastIndexOf("/");
187
+ return i < 0 ? { dir: "", name: key } : { dir: key.slice(0, i), name: key.slice(i + 1) };
188
+ }
189
+ /**
190
+ * Return only non-secret connection metadata for persistence alongside the
191
+ * authenticated application user's storage connection record.
192
+ */
193
+ getConnectionMetadata() {
194
+ return {
195
+ provider: "google_drive",
196
+ ...this.config.googleClientId ? { googleClientId: this.config.googleClientId } : {},
197
+ ...this.config.googleRedirectUri ? { googleRedirectUri: this.config.googleRedirectUri } : {},
198
+ ...this.config.googleAccountId ? { googleAccountId: this.config.googleAccountId } : {},
199
+ ...this.config.googleRootFolderId ? { googleRootFolderId: this.config.googleRootFolderId } : {}
200
+ };
201
+ }
202
+ /** Browse only folders directly below the supplied parent (or selected storage root). */
203
+ async listFolders(parentFolderId = this.config.googleRootFolderId || "root") {
204
+ const drive = await this.getClient();
205
+ const folders = [];
206
+ let pageToken;
207
+ do {
208
+ const response = await drive.files.list({
209
+ q: `'${parentFolderId}' in parents and mimeType = '${FOLDER_MIME_TYPE}' and trashed = false`,
210
+ fields: "nextPageToken,files(id,name,mimeType,parents,modifiedTime)",
211
+ pageSize: 1e3,
212
+ supportsAllDrives: true,
213
+ includeItemsFromAllDrives: true,
214
+ ...pageToken ? { pageToken } : {}
215
+ });
216
+ for (const folder of response.data.files || []) {
217
+ if (!folder.id || !folder.name) continue;
218
+ folders.push({
219
+ id: folder.id,
220
+ name: folder.name,
221
+ mimeType: FOLDER_MIME_TYPE,
222
+ parentIds: folder.parents || [],
223
+ modifiedAt: folder.modifiedTime ? Date.parse(folder.modifiedTime) : 0
224
+ });
225
+ }
226
+ pageToken = response.data.nextPageToken || void 0;
227
+ } while (pageToken);
228
+ return folders;
229
+ }
230
+ /** Resolve and validate a provider-native folder ID before it is saved as a root. */
231
+ async resolveFolder(folderId) {
232
+ if (!folderId?.trim()) throw new Error("A Google Drive folder ID is required.");
233
+ const drive = await this.getClient();
234
+ const response = await drive.files.get({
235
+ fileId: folderId,
236
+ fields: "id,name,mimeType,parents,modifiedTime",
237
+ supportsAllDrives: true
238
+ });
239
+ const folder = response.data;
240
+ if (!folder.id || !folder.name || folder.mimeType !== FOLDER_MIME_TYPE) {
241
+ throw new Error("The selected Google Drive item is not a folder.");
242
+ }
243
+ return {
244
+ id: folder.id,
245
+ name: folder.name,
246
+ mimeType: FOLDER_MIME_TYPE,
247
+ parentIds: folder.parents || [],
248
+ modifiedAt: folder.modifiedTime ? Date.parse(folder.modifiedTime) : 0
249
+ };
250
+ }
251
+ /** Select a validated folder as this connection's storage/workspace root. */
252
+ async selectRootFolder(folderId) {
253
+ const folder = await this.resolveFolder(folderId);
254
+ this.config.googleRootFolderId = folder.id;
255
+ return folder;
256
+ }
257
+ async read(pathStr) {
258
+ const { dir, name } = this.split(pathStr);
259
+ const parent = await this.resolveParent(dir);
260
+ const file = await this.findChild(parent, name);
261
+ if (!file?.id) throw new Error(`Google Drive file not found: ${pathStr}`);
262
+ if (file.mimeType === FOLDER_MIME_TYPE) throw new Error(`Google Drive path is a folder, not a file: ${pathStr}`);
263
+ const drive = await this.getClient();
264
+ const response = await drive.files.get(
265
+ { fileId: file.id, alt: "media", supportsAllDrives: true },
266
+ { responseType: "arraybuffer" }
267
+ );
268
+ return new Uint8Array(response.data);
269
+ }
270
+ async write(pathStr, data, contentType = "application/octet-stream") {
271
+ const { dir, name } = this.split(pathStr);
272
+ if (!name) throw new Error("A Google Drive file name is required.");
273
+ const parent = await this.resolveParent(dir, true);
274
+ const existing = await this.findChild(parent, name);
275
+ const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data;
276
+ const drive = await this.getClient();
277
+ if (existing?.id) {
278
+ if (existing.mimeType === FOLDER_MIME_TYPE) throw new Error(`Google Drive path is a folder: ${pathStr}`);
279
+ await drive.files.update({
280
+ fileId: existing.id,
281
+ requestBody: { name, mimeType: contentType },
282
+ media: { mimeType: contentType, body: Readable.from(bytes) },
283
+ fields: "id",
284
+ supportsAllDrives: true
285
+ });
286
+ return;
287
+ }
288
+ await drive.files.create({
289
+ requestBody: { name, mimeType: contentType, parents: [parent] },
290
+ media: { mimeType: contentType, body: Readable.from(bytes) },
291
+ fields: "id",
292
+ supportsAllDrives: true
293
+ });
294
+ }
295
+ async delete(pathStr) {
296
+ const { dir, name } = this.split(pathStr);
297
+ const parent = await this.resolveParent(dir);
298
+ const file = await this.findChild(parent, name);
299
+ if (!file?.id) return;
300
+ const drive = await this.getClient();
301
+ try {
302
+ await drive.files.delete({ fileId: file.id, supportsAllDrives: true });
303
+ } catch (error) {
304
+ if (error?.response?.status !== 404 && error?.code !== 404) throw error;
305
+ }
306
+ }
307
+ async exists(pathStr) {
308
+ try {
309
+ await this.stat(pathStr);
310
+ return true;
311
+ } catch (error) {
312
+ if (error?.response?.status === 404 || error?.code === 404) return false;
313
+ throw error;
314
+ }
315
+ }
316
+ async list(pathStr = "") {
317
+ const parent = await this.resolveParent(pathStr);
318
+ const drive = await this.getClient();
319
+ const results = [];
320
+ let pageToken;
321
+ do {
322
+ const response = await drive.files.list({
323
+ q: `'${parent}' in parents and trashed = false`,
324
+ fields: "nextPageToken,files(id,name,size,modifiedTime,mimeType)",
325
+ pageSize: 1e3,
326
+ supportsAllDrives: true,
327
+ includeItemsFromAllDrives: true,
328
+ ...pageToken ? { pageToken } : {}
329
+ });
330
+ for (const file of response.data.files || []) {
331
+ if (!file.name) continue;
332
+ results.push({
333
+ path: this.normalizePath(pathStr ? `${pathStr}/${file.name}` : file.name),
334
+ size: Number(file.size || 0),
335
+ modifiedAt: file.modifiedTime ? Date.parse(file.modifiedTime) : 0,
336
+ ...file.id ? { id: file.id } : {},
337
+ ...file.mimeType ? { mimeType: file.mimeType } : {},
338
+ isFolder: file.mimeType === FOLDER_MIME_TYPE
339
+ });
340
+ }
341
+ pageToken = response.data.nextPageToken || void 0;
342
+ } while (pageToken);
343
+ return results;
344
+ }
345
+ async stat(pathStr) {
346
+ const { dir, name } = this.split(pathStr);
347
+ const parent = await this.resolveParent(dir);
348
+ const file = await this.findChild(parent, name);
349
+ if (!file?.id) throw new Error(`Google Drive file not found: ${pathStr}`);
350
+ return {
351
+ path: pathStr,
352
+ size: Number(file.size || 0),
353
+ modifiedAt: file.modifiedTime ? Date.parse(file.modifiedTime) : 0,
354
+ id: file.id,
355
+ ...file.mimeType ? { mimeType: file.mimeType } : {},
356
+ isFolder: file.mimeType === FOLDER_MIME_TYPE
357
+ };
358
+ }
359
+ async mkdir(pathStr) {
360
+ await this.resolveParent(pathStr, true);
361
+ }
362
+ /** Resolve the stable Google account identity for association with the app user's server-side connection record. */
363
+ async getAccountIdentity() {
364
+ const drive = await this.getClient();
365
+ const response = await drive.about.get({ fields: "user(permissionId,emailAddress)" });
366
+ const accountId = response.data.user?.permissionId || response.data.user?.emailAddress;
367
+ if (!accountId) throw new Error("Google Drive did not return an account identity.");
368
+ if (this.config.googleAccountId && this.config.googleAccountId !== accountId) {
369
+ throw new Error("Google Drive account identity does not match the saved storage connection.");
370
+ }
371
+ this.config.googleAccountId = accountId;
372
+ return {
373
+ accountId,
374
+ ...response.data.user?.emailAddress ? { email: response.data.user.emailAddress } : {}
375
+ };
376
+ }
377
+ async testConnection() {
378
+ const start = performance.now();
379
+ try {
380
+ const identity = await this.getAccountIdentity();
381
+ return {
382
+ ok: true,
383
+ latencyMs: Math.round(performance.now() - start),
384
+ details: {
385
+ accountId: identity.accountId,
386
+ ...identity.email ? { email: identity.email } : {},
387
+ rootFolderId: this.config.googleRootFolderId || "root"
388
+ }
389
+ };
390
+ } catch (error) {
391
+ return {
392
+ ok: false,
393
+ latencyMs: Math.round(performance.now() - start),
394
+ error: error?.message || "Google Drive authorization failed."
395
+ };
396
+ }
397
+ }
398
+ };
399
+
400
+ export {
401
+ BaseStorageAdapter,
402
+ GoogleDriveAdapter
403
+ };
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  StorageAdapterFactory
3
- } from "./chunk-3W4TN6XB.js";
3
+ } from "./chunk-UCCFQCAE.js";
4
4
  import {
5
5
  findUserWorkspace
6
6
  } from "./chunk-JGUWYVOL.js";
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  BaseStorageAdapter,
3
3
  GoogleDriveAdapter
4
- } from "./chunk-52M4L74T.js";
4
+ } from "./chunk-GKXI5V23.js";
5
5
 
6
6
  // src/storage/LocalFSAdapter.ts
7
7
  import { promises as fs } from "fs";
@@ -527,8 +527,8 @@ var BackblazeB2Adapter = class extends BaseStorageAdapter {
527
527
 
528
528
  // src/storage/GoogleDriveStorageService.ts
529
529
  var GoogleDriveStorageService = class extends GoogleDriveAdapter {
530
- constructor(config) {
531
- super({ ...config, provider: "google_drive" });
530
+ constructor(config, runtimeAuth = {}) {
531
+ super({ ...config, provider: "google_drive" }, runtimeAuth);
532
532
  }
533
533
  };
534
534
 
@@ -609,7 +609,7 @@ var SupabaseStorageAdapter = class extends BaseStorageAdapter {
609
609
 
610
610
  // src/storage/StorageAdapterFactory.ts
611
611
  var StorageAdapterFactory = class {
612
- static create(config) {
612
+ static create(config, runtimeOptions = {}) {
613
613
  switch (config.provider) {
614
614
  case "local_fs":
615
615
  return new LocalFSAdapter(config);
@@ -619,7 +619,7 @@ var StorageAdapterFactory = class {
619
619
  case "supabase":
620
620
  return new SupabaseStorageAdapter(config);
621
621
  case "google_drive":
622
- return new GoogleDriveStorageService(config);
622
+ return new GoogleDriveStorageService(config, runtimeOptions.googleDrive);
623
623
  case "s3":
624
624
  case "s3_compatible":
625
625
  return new BucketStorageService(config);
@@ -1,17 +1,3 @@
1
- import {
2
- CompositeBackend,
3
- EndpointGenerator,
4
- LOCAL_STORAGE_GRAPHS_PREFIX,
5
- NodeGraphPersistenceService,
6
- createBackend,
7
- createCompositeService,
8
- createLocalService,
9
- createRemoteService,
10
- exportGraphAsJsonFile,
11
- nodeGraphPersistence,
12
- parseGraphJsonFile,
13
- validateGraphDocument
14
- } from "./chunk-JOTDEFRG.js";
15
1
  import {
16
2
  CANONICAL_SRKL_URL,
17
3
  SrklClient,
@@ -32,10 +18,11 @@ import {
32
18
  } from "./chunk-HF5SGQ5V.js";
33
19
  import {
34
20
  GOOGLE_DRIVE_FILE_SCOPE,
21
+ GOOGLE_DRIVE_STORAGE_SCOPE,
35
22
  createGoogleDriveAuthorizationUrl,
36
23
  exchangeGoogleDriveCode,
37
24
  refreshGoogleDriveAccessToken
38
- } from "./chunk-GZD5A54P.js";
25
+ } from "./chunk-3SWMKYCI.js";
39
26
  import {
40
27
  RemoteWorkspaceService,
41
28
  SyncEngine,
@@ -51,16 +38,30 @@ import {
51
38
  setWorkingWorkspaceConfig,
52
39
  syncWorkspace,
53
40
  workingWorkspaceService
54
- } from "./chunk-IB5SLBHT.js";
41
+ } from "./chunk-BQLQTUDD.js";
55
42
  import {
56
- validateToolInput
57
- } from "./chunk-6GQNYRD6.js";
43
+ CompositeBackend,
44
+ EndpointGenerator,
45
+ LOCAL_STORAGE_GRAPHS_PREFIX,
46
+ NodeGraphPersistenceService,
47
+ createBackend,
48
+ createCompositeService,
49
+ createLocalService,
50
+ createRemoteService,
51
+ exportGraphAsJsonFile,
52
+ nodeGraphPersistence,
53
+ parseGraphJsonFile,
54
+ validateGraphDocument
55
+ } from "./chunk-JOTDEFRG.js";
58
56
  import {
59
57
  BaseApiRoute,
60
58
  createSSEResponse,
61
59
  withAuth,
62
60
  withCors
63
61
  } from "./chunk-TWCEVES2.js";
62
+ import {
63
+ validateToolInput
64
+ } from "./chunk-6GQNYRD6.js";
64
65
  import {
65
66
  LuthAuthClient,
66
67
  LuthAuthClient2,
@@ -160,15 +161,26 @@ import {
160
161
  krnlWorkspaceGraphServiceFacade,
161
162
  krnlWorkspaceServiceDefinition,
162
163
  krnlWorkspaceServiceFacade
163
- } from "./chunk-JRNH5KPV.js";
164
- import {
165
- workspaceGraphService
166
- } from "./chunk-QXIMZLGS.js";
164
+ } from "./chunk-4TPSXGG5.js";
167
165
  import {
168
166
  getPrimarySrklDeploymentUrl,
169
167
  getSrklAccounts,
170
168
  srklListBackblazeBuckets
171
169
  } from "./chunk-RIOYKF3X.js";
170
+ import {
171
+ authorizeB2,
172
+ b2DownloadFile,
173
+ b2ListBuckets,
174
+ b2ListFileNames,
175
+ b2UploadFile
176
+ } from "./chunk-4QEMALXF.js";
177
+ import {
178
+ formatCanonicalWorkspaceFolderName,
179
+ sanitizeWorkspaceName
180
+ } from "./chunk-FZKBTF34.js";
181
+ import {
182
+ workspaceGraphService
183
+ } from "./chunk-KVWBIDZG.js";
172
184
  import {
173
185
  BackblazeB2Adapter,
174
186
  BucketStorageService,
@@ -184,18 +196,7 @@ import {
184
196
  permanentDeleteS3Object,
185
197
  renameS3Folder,
186
198
  resolveBackblazeEndpoint
187
- } from "./chunk-3W4TN6XB.js";
188
- import {
189
- authorizeB2,
190
- b2DownloadFile,
191
- b2ListBuckets,
192
- b2ListFileNames,
193
- b2UploadFile
194
- } from "./chunk-4QEMALXF.js";
195
- import {
196
- formatCanonicalWorkspaceFolderName,
197
- sanitizeWorkspaceName
198
- } from "./chunk-FZKBTF34.js";
199
+ } from "./chunk-UCCFQCAE.js";
199
200
  import {
200
201
  createWorkspace,
201
202
  deleteWorkspace,
@@ -229,7 +230,7 @@ import {
229
230
  import {
230
231
  BaseStorageAdapter,
231
232
  GoogleDriveAdapter
232
- } from "./chunk-52M4L74T.js";
233
+ } from "./chunk-GKXI5V23.js";
233
234
  import {
234
235
  loginSystemUser,
235
236
  resolveUserFromToken
@@ -4460,6 +4461,7 @@ export {
4460
4461
  FrontendSession,
4461
4462
  FunctionalityTable,
4462
4463
  GOOGLE_DRIVE_FILE_SCOPE,
4464
+ GOOGLE_DRIVE_STORAGE_SCOPE,
4463
4465
  GRAPHS_ROOT,
4464
4466
  GeminiServiceDefinition,
4465
4467
  GeminiServiceFacade,
@@ -31,15 +31,15 @@ import {
31
31
  krnlWorkspaceGraphServiceFacade,
32
32
  krnlWorkspaceServiceDefinition,
33
33
  krnlWorkspaceServiceFacade
34
- } from "./chunk-JRNH5KPV.js";
35
- import "./chunk-QXIMZLGS.js";
34
+ } from "./chunk-4TPSXGG5.js";
36
35
  import "./chunk-RIOYKF3X.js";
37
- import "./chunk-3W4TN6XB.js";
38
36
  import "./chunk-4QEMALXF.js";
39
37
  import "./chunk-FZKBTF34.js";
38
+ import "./chunk-KVWBIDZG.js";
39
+ import "./chunk-UCCFQCAE.js";
40
40
  import "./chunk-JGUWYVOL.js";
41
41
  import "./chunk-JCMB7BIM.js";
42
- import "./chunk-52M4L74T.js";
42
+ import "./chunk-GKXI5V23.js";
43
43
  import "./chunk-2COYZMUJ.js";
44
44
  import "./chunk-SXDYW3QA.js";
45
45
  export {
@@ -14,11 +14,11 @@ import {
14
14
  } from "../chunk-JOTDEFRG.js";
15
15
  import {
16
16
  workspaceGraphService
17
- } from "../chunk-QXIMZLGS.js";
18
- import "../chunk-3W4TN6XB.js";
17
+ } from "../chunk-KVWBIDZG.js";
18
+ import "../chunk-UCCFQCAE.js";
19
19
  import "../chunk-JGUWYVOL.js";
20
20
  import "../chunk-JCMB7BIM.js";
21
- import "../chunk-52M4L74T.js";
21
+ import "../chunk-GKXI5V23.js";
22
22
  import "../chunk-SXDYW3QA.js";
23
23
  export {
24
24
  CompositeBackend,
@@ -1,13 +1,30 @@
1
1
  import { BaseStorageAdapter } from './BaseStorageAdapter.js';
2
- import { FileInfo, ConnectionTestResult } from './types.js';
2
+ import type { GoogleDriveFolder, FileInfo, StorageConfig, ConnectionTestResult } from './types.js';
3
+ import type { GoogleDriveRuntimeAuthOptions } from './GoogleDriveOAuth.js';
3
4
  export declare class GoogleDriveAdapter extends BaseStorageAdapter {
4
5
  private client?;
5
6
  private auth?;
7
+ private authPromise?;
8
+ private pendingCredentialPersistence?;
9
+ private credentialPersistenceError?;
10
+ private readonly runtimeAuth;
11
+ constructor(config: StorageConfig, runtimeAuth?: GoogleDriveRuntimeAuthOptions);
6
12
  private getAuth;
7
13
  private getClient;
8
14
  private findChild;
9
15
  private resolveParent;
10
16
  private split;
17
+ /**
18
+ * Return only non-secret connection metadata for persistence alongside the
19
+ * authenticated application user's storage connection record.
20
+ */
21
+ getConnectionMetadata(): Pick<StorageConfig, 'provider' | 'googleClientId' | 'googleRedirectUri' | 'googleAccountId' | 'googleRootFolderId'>;
22
+ /** Browse only folders directly below the supplied parent (or selected storage root). */
23
+ listFolders(parentFolderId?: string): Promise<GoogleDriveFolder[]>;
24
+ /** Resolve and validate a provider-native folder ID before it is saved as a root. */
25
+ resolveFolder(folderId: string): Promise<GoogleDriveFolder>;
26
+ /** Select a validated folder as this connection's storage/workspace root. */
27
+ selectRootFolder(folderId: string): Promise<GoogleDriveFolder>;
11
28
  read(pathStr: string): Promise<Uint8Array>;
12
29
  write(pathStr: string, data: Uint8Array | string, contentType?: string): Promise<void>;
13
30
  delete(pathStr: string): Promise<void>;
@@ -15,5 +32,10 @@ export declare class GoogleDriveAdapter extends BaseStorageAdapter {
15
32
  list(pathStr?: string): Promise<FileInfo[]>;
16
33
  stat(pathStr: string): Promise<FileInfo>;
17
34
  mkdir(pathStr: string): Promise<void>;
35
+ /** Resolve the stable Google account identity for association with the app user's server-side connection record. */
36
+ getAccountIdentity(): Promise<{
37
+ accountId: string;
38
+ email?: string;
39
+ }>;
18
40
  testConnection(): Promise<ConnectionTestResult>;
19
41
  }
@@ -10,7 +10,25 @@ export interface GoogleDriveTokenSet {
10
10
  expiresAt?: number;
11
11
  tokenType?: string;
12
12
  }
13
+ /**
14
+ * Server-only runtime dependencies. Keep this object out of persisted
15
+ * provider connection records and never pass it to browser code.
16
+ */
17
+ export interface GoogleDriveRuntimeAuthOptions {
18
+ clientSecret?: string;
19
+ getCredentials?: () => Promise<GoogleDriveTokenSet>;
20
+ persistCredentials?: (tokens: GoogleDriveTokenSet) => Promise<void> | void;
21
+ }
22
+ /**
23
+ * A storage root must be able to enumerate, read, create, update and delete
24
+ * files below a user-selected existing folder. drive.file is deliberately
25
+ * insufficient for this contract: it only covers files explicitly opened
26
+ * or created by the application. The full Drive scope is therefore the
27
+ * narrowest single scope that supports the complete storage abstraction.
28
+ */
29
+ export declare const GOOGLE_DRIVE_STORAGE_SCOPE = "https://www.googleapis.com/auth/drive";
30
+ /** @deprecated Use GOOGLE_DRIVE_STORAGE_SCOPE for complete storage roots. */
13
31
  export declare const GOOGLE_DRIVE_FILE_SCOPE = "https://www.googleapis.com/auth/drive.file";
14
32
  export declare function createGoogleDriveAuthorizationUrl(config: GoogleDriveOAuthConfig, state: string, codeChallenge?: string): string;
15
- export declare function exchangeGoogleDriveCode(config: GoogleDriveOAuthConfig, code: string, codeVerifier?: string): Promise<GoogleDriveTokenSet>;
16
- export declare function refreshGoogleDriveAccessToken(clientId: string, refreshToken: string, clientSecret?: string, _redirectUri?: string): Promise<GoogleDriveTokenSet>;
33
+ export declare function exchangeGoogleDriveCode(config: GoogleDriveOAuthConfig, code: string, codeVerifier?: string, existingRefreshToken?: string): Promise<GoogleDriveTokenSet>;
34
+ export declare function refreshGoogleDriveAccessToken(clientId: string, refreshToken: string, clientSecret?: string, redirectUri?: string): Promise<GoogleDriveTokenSet>;
@@ -1,5 +1,11 @@
1
1
  import { GoogleDriveAdapter } from './GoogleDriveAdapter.js';
2
+ import type { GoogleDriveRuntimeAuthOptions } from './GoogleDriveOAuth.js';
2
3
  import type { StorageConfig } from './types.js';
4
+ /**
5
+ * Canonical Google Drive implementation of the KLOKS storage abstraction.
6
+ * Runtime auth callbacks/secrets are server-only and must not be serialized
7
+ * into consumer-visible storage connection records.
8
+ */
3
9
  export declare class GoogleDriveStorageService extends GoogleDriveAdapter {
4
- constructor(config: StorageConfig);
10
+ constructor(config: StorageConfig, runtimeAuth?: GoogleDriveRuntimeAuthOptions);
5
11
  }
@@ -1,5 +1,10 @@
1
1
  import { BaseStorageAdapter } from './BaseStorageAdapter.js';
2
2
  import { StorageConfig } from './types.js';
3
+ import type { GoogleDriveRuntimeAuthOptions } from './GoogleDriveOAuth.js';
4
+ export interface StorageAdapterRuntimeOptions {
5
+ /** Server-only OAuth dependencies; never include these in persisted connection JSON. */
6
+ googleDrive?: GoogleDriveRuntimeAuthOptions;
7
+ }
3
8
  export declare class StorageAdapterFactory {
4
- static create(config: StorageConfig): BaseStorageAdapter;
9
+ static create(config: StorageConfig, runtimeOptions?: StorageAdapterRuntimeOptions): BaseStorageAdapter;
5
10
  }
@@ -1,9 +1,17 @@
1
1
  import {
2
2
  GOOGLE_DRIVE_FILE_SCOPE,
3
+ GOOGLE_DRIVE_STORAGE_SCOPE,
3
4
  createGoogleDriveAuthorizationUrl,
4
5
  exchangeGoogleDriveCode,
5
6
  refreshGoogleDriveAccessToken
6
- } from "../chunk-GZD5A54P.js";
7
+ } from "../chunk-3SWMKYCI.js";
8
+ import {
9
+ authorizeB2,
10
+ b2DownloadFile,
11
+ b2ListBuckets,
12
+ b2ListFileNames,
13
+ b2UploadFile
14
+ } from "../chunk-4QEMALXF.js";
7
15
  import {
8
16
  BackblazeB2Adapter,
9
17
  BucketStorageService,
@@ -19,23 +27,17 @@ import {
19
27
  permanentDeleteS3Object,
20
28
  renameS3Folder,
21
29
  resolveBackblazeEndpoint
22
- } from "../chunk-3W4TN6XB.js";
23
- import {
24
- authorizeB2,
25
- b2DownloadFile,
26
- b2ListBuckets,
27
- b2ListFileNames,
28
- b2UploadFile
29
- } from "../chunk-4QEMALXF.js";
30
+ } from "../chunk-UCCFQCAE.js";
30
31
  import {
31
32
  BaseStorageAdapter,
32
33
  GoogleDriveAdapter
33
- } from "../chunk-52M4L74T.js";
34
+ } from "../chunk-GKXI5V23.js";
34
35
  export {
35
36
  BackblazeB2Adapter,
36
37
  BaseStorageAdapter,
37
38
  BucketStorageService,
38
39
  GOOGLE_DRIVE_FILE_SCOPE,
40
+ GOOGLE_DRIVE_STORAGE_SCOPE,
39
41
  GoogleDriveAdapter,
40
42
  GoogleDriveStorageService,
41
43
  LocalFSAdapter,
@@ -19,6 +19,8 @@ export interface StorageConfig {
19
19
  accountId?: string;
20
20
  googleClientId?: string;
21
21
  googleRedirectUri?: string;
22
+ /** Stable Google account subject/email identifier for server-side ownership association. */
23
+ googleAccountId?: string;
22
24
  googleAccessToken?: string;
23
25
  googleAccessTokenExpiresAt?: number;
24
26
  googleRefreshToken?: string;
@@ -29,6 +31,17 @@ export interface FileInfo {
29
31
  size: number;
30
32
  modifiedAt: number;
31
33
  contentHash?: string;
34
+ /** Provider-native identifier; populated by providers that expose stable IDs. */
35
+ id?: string;
36
+ mimeType?: string;
37
+ isFolder?: boolean;
38
+ }
39
+ export interface GoogleDriveFolder {
40
+ id: string;
41
+ name: string;
42
+ mimeType: 'application/vnd.google-apps.folder';
43
+ parentIds: string[];
44
+ modifiedAt: number;
32
45
  }
33
46
  export interface UploadResult {
34
47
  path: string;
@@ -6,14 +6,14 @@ import {
6
6
  WorkspaceFS,
7
7
  remoteWorkspaceService,
8
8
  workingWorkspaceService
9
- } from "../chunk-IB5SLBHT.js";
9
+ } from "../chunk-BQLQTUDD.js";
10
10
  import {
11
11
  formatCanonicalWorkspaceFolderName,
12
12
  sanitizeWorkspaceName
13
13
  } from "../chunk-FZKBTF34.js";
14
14
  import "../chunk-JGUWYVOL.js";
15
15
  import "../chunk-JCMB7BIM.js";
16
- import "../chunk-52M4L74T.js";
16
+ import "../chunk-GKXI5V23.js";
17
17
  export {
18
18
  RemoteWorkspaceService,
19
19
  SyncEngine,
@@ -16,6 +16,20 @@ import {
16
16
  useSkipoBind,
17
17
  useSkipoState
18
18
  } from "./chunk-EW4ACSZB.js";
19
+ import {
20
+ CommandApi,
21
+ GhostStore,
22
+ GraphStore
23
+ } from "./chunk-4UVGXFEM.js";
24
+ import {
25
+ BaseGraph,
26
+ BaseNode,
27
+ BaseViewWindow,
28
+ CustomGraph,
29
+ CustomNode,
30
+ CustomViewWindow,
31
+ DEFAULT_GRAPH_SETTINGS
32
+ } from "./chunk-KG6QYS26.js";
19
33
  import {
20
34
  AttractionEngine,
21
35
  GhostInferenceEngine,
@@ -31,20 +45,6 @@ import {
31
45
  WireTypeRegistry,
32
46
  initializeDefaultGraphRules
33
47
  } from "./chunk-TZOL3RN7.js";
34
- import {
35
- CommandApi,
36
- GhostStore,
37
- GraphStore
38
- } from "./chunk-4UVGXFEM.js";
39
- import {
40
- BaseGraph,
41
- BaseNode,
42
- BaseViewWindow,
43
- CustomGraph,
44
- CustomNode,
45
- CustomViewWindow,
46
- DEFAULT_GRAPH_SETTINGS
47
- } from "./chunk-KG6QYS26.js";
48
48
  import {
49
49
  AutoSolidify,
50
50
  SpatialEngine,
@@ -1,247 +0,0 @@
1
- // src/storage/BaseStorageAdapter.ts
2
- import { SkipoBase } from "@ultrst-armada/kloks/functions";
3
- var BaseStorageAdapter = class extends SkipoBase {
4
- config;
5
- constructor(config) {
6
- super({ name: "BaseStorageAdapter" });
7
- this.config = config;
8
- }
9
- async deleteFolder(pathStr) {
10
- const items = await this.list(pathStr);
11
- let count = 0;
12
- for (const item of items) {
13
- await this.delete(item.path);
14
- count++;
15
- }
16
- return { success: true, deletedCount: count };
17
- }
18
- async renameFolder(oldPath, newPath) {
19
- const items = await this.list(oldPath);
20
- let count = 0;
21
- for (const item of items) {
22
- const rel = item.path.startsWith(oldPath) ? item.path.slice(oldPath.length).replace(/^\/+/, "") : item.path;
23
- const target = `${newPath.replace(/\/+$/, "")}/${rel}`;
24
- const data = await this.read(item.path);
25
- await this.write(target, data);
26
- await this.delete(item.path);
27
- count++;
28
- }
29
- return { success: true, movedCount: count };
30
- }
31
- async ensureDirectory(pathStr) {
32
- await this.mkdir(pathStr);
33
- }
34
- async testConnection() {
35
- const start = performance.now();
36
- try {
37
- await this.list("");
38
- return { ok: true, latencyMs: Math.round(performance.now() - start) };
39
- } catch (e) {
40
- return { ok: false, latencyMs: Math.round(performance.now() - start), error: e.message };
41
- }
42
- }
43
- normalizePath(p) {
44
- return p.replace(/\\/g, "/").replace(/^\/+/, "");
45
- }
46
- getExtension(p) {
47
- const parts = p.split(".");
48
- return parts.length > 1 ? parts[parts.length - 1] : "";
49
- }
50
- };
51
-
52
- // src/storage/GoogleDriveAdapter.ts
53
- import { google } from "@dinilmusick/gutts/storage";
54
- import { Readable } from "stream";
55
- var GoogleDriveAdapter = class extends BaseStorageAdapter {
56
- client;
57
- auth;
58
- getAuth() {
59
- if (this.auth) return this.auth;
60
- const client = new google.auth.OAuth2(
61
- this.config.googleClientId,
62
- void 0,
63
- this.config.googleRedirectUri
64
- );
65
- const accessToken = this.config.googleAccessToken;
66
- const refreshToken = this.config.googleRefreshToken;
67
- const expiresAt = Number(this.config.googleAccessTokenExpiresAt || 0);
68
- if (accessToken) {
69
- client.setCredentials({
70
- access_token: accessToken,
71
- ...expiresAt ? { expiry_date: expiresAt } : {},
72
- ...refreshToken ? { refresh_token: refreshToken } : {}
73
- });
74
- } else if (refreshToken) {
75
- client.setCredentials({ refresh_token: refreshToken });
76
- } else {
77
- throw new Error("Google Drive OAuth credentials are incomplete.");
78
- }
79
- this.auth = client;
80
- return client;
81
- }
82
- async getClient() {
83
- if (this.client) return this.client;
84
- const auth = this.getAuth();
85
- const token = await auth.getAccessToken();
86
- if (!token.token) throw new Error("Google Drive authorization returned no access token.");
87
- this.config.googleAccessToken = token.token;
88
- if (auth.credentials.expiry_date) {
89
- this.config.googleAccessTokenExpiresAt = auth.credentials.expiry_date;
90
- }
91
- this.client = google.drive({ version: "v3", auth });
92
- return this.client;
93
- }
94
- async findChild(parentId, name) {
95
- const drive = await this.getClient();
96
- const escapedName = name.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
97
- const response = await drive.files.list({
98
- q: `'${parentId}' in parents and name = '${escapedName}' and trashed = false`,
99
- fields: "files(id,name,size,modifiedTime,mimeType)",
100
- pageSize: 10
101
- });
102
- return response.data.files?.[0] || null;
103
- }
104
- async resolveParent(relativeDir, create = false) {
105
- let parent = this.config.googleRootFolderId || "root";
106
- for (const part of this.normalizePath(relativeDir).split("/").filter(Boolean)) {
107
- let child = await this.findChild(parent, part);
108
- if (!child && create) {
109
- const drive = await this.getClient();
110
- const response = await drive.files.create({
111
- requestBody: {
112
- name: part,
113
- mimeType: "application/vnd.google-apps.folder",
114
- parents: [parent]
115
- },
116
- fields: "id,name,mimeType"
117
- });
118
- child = response.data;
119
- }
120
- if (!child?.id) {
121
- throw new Error(`Google Drive directory not found: ${part}`);
122
- }
123
- parent = child.id;
124
- }
125
- return parent;
126
- }
127
- split(pathStr) {
128
- const key = this.normalizePath(pathStr);
129
- const i = key.lastIndexOf("/");
130
- return i < 0 ? { dir: "", name: key } : { dir: key.slice(0, i), name: key.slice(i + 1) };
131
- }
132
- async read(pathStr) {
133
- const { dir, name } = this.split(pathStr);
134
- const parent = await this.resolveParent(dir);
135
- const file = await this.findChild(parent, name);
136
- if (!file?.id) throw new Error(`Google Drive file not found: ${pathStr}`);
137
- const drive = await this.getClient();
138
- const response = await drive.files.get(
139
- { fileId: file.id, alt: "media" },
140
- { responseType: "arraybuffer" }
141
- );
142
- return new Uint8Array(response.data);
143
- }
144
- async write(pathStr, data, contentType = "application/octet-stream") {
145
- const { dir, name } = this.split(pathStr);
146
- const parent = await this.resolveParent(dir, true);
147
- const existing = await this.findChild(parent, name);
148
- const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data;
149
- const drive = await this.getClient();
150
- if (existing?.id) {
151
- await drive.files.update({
152
- fileId: existing.id,
153
- requestBody: { name, mimeType: contentType },
154
- media: { mimeType: contentType, body: Readable.from(bytes) },
155
- fields: "id"
156
- });
157
- return;
158
- }
159
- await drive.files.create({
160
- requestBody: { name, mimeType: contentType, parents: [parent] },
161
- media: { mimeType: contentType, body: Readable.from(bytes) },
162
- fields: "id"
163
- });
164
- }
165
- async delete(pathStr) {
166
- const { dir, name } = this.split(pathStr);
167
- const parent = await this.resolveParent(dir);
168
- const file = await this.findChild(parent, name);
169
- if (!file?.id) return;
170
- const drive = await this.getClient();
171
- try {
172
- await drive.files.delete({ fileId: file.id });
173
- } catch (error) {
174
- if (error?.response?.status !== 404) throw error;
175
- }
176
- }
177
- async exists(pathStr) {
178
- try {
179
- await this.stat(pathStr);
180
- return true;
181
- } catch (error) {
182
- if (error?.response?.status === 404) return false;
183
- throw error;
184
- }
185
- }
186
- async list(pathStr = "") {
187
- const parent = await this.resolveParent(pathStr);
188
- const drive = await this.getClient();
189
- const results = [];
190
- let pageToken;
191
- do {
192
- const response = await drive.files.list({
193
- q: `'${parent}' in parents and trashed = false`,
194
- fields: "nextPageToken,files(id,name,size,modifiedTime,mimeType)",
195
- pageSize: 1e3,
196
- ...pageToken ? { pageToken } : {}
197
- });
198
- for (const file of response.data.files || []) {
199
- if (!file.name) continue;
200
- results.push({
201
- path: this.normalizePath(pathStr ? `${pathStr}/${file.name}` : file.name),
202
- size: Number(file.size || 0),
203
- modifiedAt: file.modifiedTime ? Date.parse(file.modifiedTime) : 0
204
- });
205
- }
206
- pageToken = response.data.nextPageToken || void 0;
207
- } while (pageToken);
208
- return results;
209
- }
210
- async stat(pathStr) {
211
- const { dir, name } = this.split(pathStr);
212
- const parent = await this.resolveParent(dir);
213
- const file = await this.findChild(parent, name);
214
- if (!file?.id) throw new Error(`Google Drive file not found: ${pathStr}`);
215
- return {
216
- path: pathStr,
217
- size: Number(file.size || 0),
218
- modifiedAt: file.modifiedTime ? Date.parse(file.modifiedTime) : 0
219
- };
220
- }
221
- async mkdir(pathStr) {
222
- await this.resolveParent(pathStr, true);
223
- }
224
- async testConnection() {
225
- const start = performance.now();
226
- try {
227
- const drive = await this.getClient();
228
- const response = await drive.about.get({ fields: "user(emailAddress)" });
229
- return {
230
- ok: true,
231
- latencyMs: Math.round(performance.now() - start),
232
- details: { email: response.data.user?.emailAddress }
233
- };
234
- } catch (error) {
235
- return {
236
- ok: false,
237
- latencyMs: Math.round(performance.now() - start),
238
- error: error?.message || "Google Drive authorization failed."
239
- };
240
- }
241
- }
242
- };
243
-
244
- export {
245
- BaseStorageAdapter,
246
- GoogleDriveAdapter
247
- };
@@ -1,67 +0,0 @@
1
- // src/storage/GoogleDriveOAuth.ts
2
- import { google } from "@dinilmusick/gutts/storage";
3
- var GOOGLE_DRIVE_FILE_SCOPE = "https://www.googleapis.com/auth/drive.file";
4
- function createGoogleDriveAuthorizationUrl(config, state, codeChallenge) {
5
- const client = new google.auth.OAuth2(
6
- config.clientId,
7
- config.clientSecret,
8
- config.redirectUri
9
- );
10
- const url = client.generateAuthUrl({
11
- access_type: "offline",
12
- prompt: "consent",
13
- scope: config.scopes?.length ? config.scopes : [GOOGLE_DRIVE_FILE_SCOPE],
14
- state,
15
- ...codeChallenge ? { code_challenge: codeChallenge, code_challenge_method: "S256" } : {}
16
- });
17
- return url;
18
- }
19
- async function exchangeGoogleDriveCode(config, code, codeVerifier) {
20
- const client = new google.auth.OAuth2(
21
- config.clientId,
22
- config.clientSecret,
23
- config.redirectUri
24
- );
25
- const { tokens } = await client.getToken({
26
- code,
27
- ...codeVerifier ? { codeVerifier } : {}
28
- });
29
- if (!tokens.access_token) {
30
- throw new Error("Google OAuth token exchange returned no access token.");
31
- }
32
- return {
33
- accessToken: tokens.access_token,
34
- ...tokens.refresh_token ? { refreshToken: tokens.refresh_token } : {},
35
- ...tokens.expiry_date ? { expiresAt: tokens.expiry_date } : {},
36
- ...tokens.token_type ? { tokenType: tokens.token_type } : {}
37
- };
38
- }
39
- async function refreshGoogleDriveAccessToken(clientId, refreshToken, clientSecret, _redirectUri) {
40
- const body = new URLSearchParams({
41
- client_id: clientId,
42
- refresh_token: refreshToken,
43
- grant_type: "refresh_token"
44
- });
45
- if (clientSecret) body.set("client_secret", clientSecret);
46
- const response = await fetch("https://oauth2.googleapis.com/token", {
47
- method: "POST",
48
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
49
- body
50
- });
51
- if (!response.ok) {
52
- throw new Error(`Google OAuth refresh failed: ${response.status}`);
53
- }
54
- const data = await response.json();
55
- return {
56
- accessToken: data.access_token,
57
- expiresAt: data.expires_in ? Date.now() + Number(data.expires_in) * 1e3 : void 0,
58
- tokenType: data.token_type
59
- };
60
- }
61
-
62
- export {
63
- GOOGLE_DRIVE_FILE_SCOPE,
64
- createGoogleDriveAuthorizationUrl,
65
- exchangeGoogleDriveCode,
66
- refreshGoogleDriveAccessToken
67
- };