drivekit 1.1.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -75,6 +75,31 @@ var init_errors = __esm({
75
75
  }
76
76
  });
77
77
 
78
+ // src/utils/http-agent.ts
79
+ import https from "https";
80
+ import http from "http";
81
+ function getOptimizedHttpsAgent(options) {
82
+ if (!sharedHttpsAgent) {
83
+ sharedHttpsAgent = new https.Agent({
84
+ keepAlive: options?.keepAlive ?? true,
85
+ maxSockets: options?.maxSockets ?? 64,
86
+ maxFreeSockets: options?.maxFreeSockets ?? 32,
87
+ keepAliveMsecs: options?.keepAliveMsecs ?? 6e4,
88
+ timeout: options?.timeout ?? 3e4,
89
+ noDelay: true
90
+ });
91
+ }
92
+ return sharedHttpsAgent;
93
+ }
94
+ var sharedHttpsAgent;
95
+ var init_http_agent = __esm({
96
+ "src/utils/http-agent.ts"() {
97
+ "use strict";
98
+ init_esm_shims();
99
+ sharedHttpsAgent = null;
100
+ }
101
+ });
102
+
78
103
  // src/auth/authenticator.ts
79
104
  import fs from "fs";
80
105
  import { auth as googleAuth } from "@googleapis/drive";
@@ -84,6 +109,7 @@ var init_authenticator = __esm({
84
109
  "use strict";
85
110
  init_esm_shims();
86
111
  init_errors();
112
+ init_http_agent();
87
113
  DEFAULT_SCOPES = [
88
114
  "https://www.googleapis.com/auth/drive"
89
115
  ];
@@ -106,44 +132,39 @@ var init_authenticator = __esm({
106
132
  const oauth2Client = new googleAuth.OAuth2();
107
133
  oauth2Client.setCredentials({ access_token: this.config.accessToken });
108
134
  this.authClient = oauth2Client;
109
- return this.authClient;
110
- }
111
- if (this.config.oauth2Client) {
135
+ } else if (this.config.oauth2Client) {
112
136
  this.authClient = this.config.oauth2Client;
113
- return this.authClient;
114
- }
115
- if (this.config.oauth) {
137
+ } else if (this.config.oauth) {
116
138
  const { clientId, clientSecret, redirectUri = "http://localhost:3000/oauth2callback", refreshToken } = this.config.oauth;
117
139
  const oauth2Client = new googleAuth.OAuth2(clientId, clientSecret, redirectUri);
118
140
  if (refreshToken) {
119
141
  oauth2Client.setCredentials({ refresh_token: refreshToken });
120
142
  }
121
143
  this.authClient = oauth2Client;
122
- return this.authClient;
123
- }
124
- const keyFile = this.config.keyFilePath || process.env.GDRIVE_SERVICE_ACCOUNT_PATH || process.env.GOOGLE_APPLICATION_CREDENTIALS;
125
- if (keyFile) {
126
- if (!fs.existsSync(keyFile)) {
144
+ } else if (this.config.keyFilePath || process.env.GDRIVE_SERVICE_ACCOUNT_PATH || process.env.GOOGLE_APPLICATION_CREDENTIALS) {
145
+ const keyFile = this.config.keyFilePath || process.env.GDRIVE_SERVICE_ACCOUNT_PATH || process.env.GOOGLE_APPLICATION_CREDENTIALS;
146
+ if (keyFile && !fs.existsSync(keyFile)) {
127
147
  throw new DriveAuthError(`Service account file not found at: ${keyFile}`);
128
148
  }
129
- const auth2 = new googleAuth.GoogleAuth({
149
+ const auth = new googleAuth.GoogleAuth({
130
150
  keyFile,
131
151
  scopes
132
152
  });
133
- this.authClient = auth2;
134
- return this.authClient;
135
- }
136
- const creds = this.config.credentials || (process.env.GDRIVE_CREDENTIALS_JSON ? JSON.parse(process.env.GDRIVE_CREDENTIALS_JSON) : null);
137
- if (creds) {
138
- const auth2 = new googleAuth.GoogleAuth({
153
+ this.authClient = auth;
154
+ } else if (this.config.credentials || process.env.GDRIVE_CREDENTIALS_JSON) {
155
+ const creds = this.config.credentials || (process.env.GDRIVE_CREDENTIALS_JSON ? JSON.parse(process.env.GDRIVE_CREDENTIALS_JSON) : null);
156
+ const auth = new googleAuth.GoogleAuth({
139
157
  credentials: creds,
140
158
  scopes
141
159
  });
142
- this.authClient = auth2;
143
- return this.authClient;
160
+ this.authClient = auth;
161
+ } else {
162
+ const auth = new googleAuth.GoogleAuth({ scopes });
163
+ this.authClient = auth;
164
+ }
165
+ if (this.authClient?.transporter?.defaults) {
166
+ this.authClient.transporter.defaults.agent = getOptimizedHttpsAgent();
144
167
  }
145
- const auth = new googleAuth.GoogleAuth({ scopes });
146
- this.authClient = auth;
147
168
  return this.authClient;
148
169
  } catch (err) {
149
170
  if (err instanceof DriveAuthError) throw err;
@@ -302,6 +323,7 @@ var init_path_resolver = __esm({
302
323
  drive;
303
324
  rootFolderId;
304
325
  cache = /* @__PURE__ */ new Map();
326
+ inFlightResolves = /* @__PURE__ */ new Map();
305
327
  cacheTTL;
306
328
  enableCache;
307
329
  metadataCache;
@@ -325,8 +347,8 @@ var init_path_resolver = __esm({
325
347
  /**
326
348
  * Gets cache key for a path
327
349
  */
328
- getCacheKey(path10) {
329
- return `${this.rootFolderId}:${this.normalizePath(path10)}`;
350
+ getCacheKey(path12) {
351
+ return `${this.rootFolderId}:${this.normalizePath(path12)}`;
330
352
  }
331
353
  /**
332
354
  * Clears the path cache
@@ -340,8 +362,8 @@ var init_path_resolver = __esm({
340
362
  /**
341
363
  * Invalidate a single path from cache
342
364
  */
343
- invalidatePath(path10) {
344
- const norm = this.normalizePath(path10);
365
+ invalidatePath(path12) {
366
+ const norm = this.normalizePath(path12);
345
367
  const key = this.getCacheKey(norm);
346
368
  this.cache.delete(key);
347
369
  if (this.metadataCache) {
@@ -354,6 +376,7 @@ var init_path_resolver = __esm({
354
376
  /**
355
377
  * Resolves a path to a Google Drive item (file or folder).
356
378
  * If createIfMissing is true, any missing intermediate directories will be automatically created (like mkdir -p).
379
+ * Incorporates in-flight request coalescing to deduplicate concurrent resolutions of identical paths.
357
380
  */
358
381
  async resolve(virtualPath, options = {}) {
359
382
  const norm = this.normalizePath(virtualPath);
@@ -387,6 +410,20 @@ var init_path_resolver = __esm({
387
410
  };
388
411
  }
389
412
  }
413
+ const flightKey = `${this.rootFolderId}:${norm}:${options.createIfMissing ? "create" : "read"}`;
414
+ const inFlight = this.inFlightResolves.get(flightKey);
415
+ if (inFlight) {
416
+ return await inFlight;
417
+ }
418
+ const task = this.doResolve(virtualPath, norm, options);
419
+ this.inFlightResolves.set(flightKey, task);
420
+ try {
421
+ return await task;
422
+ } finally {
423
+ this.inFlightResolves.delete(flightKey);
424
+ }
425
+ }
426
+ async doResolve(virtualPath, norm, options) {
390
427
  const segments = norm.split("/").filter(Boolean);
391
428
  let currentParentId = this.rootFolderId;
392
429
  let currentPath = "";
@@ -438,7 +475,7 @@ var init_path_resolver = __esm({
438
475
  });
439
476
  let file = response.data.files?.[0];
440
477
  if (!file && currentParentId === this.rootFolderId) {
441
- const sharedQ = `name = '${escapedName}' and trashed = false`;
478
+ const sharedQ = `name = '${escapedName}' and sharedWithMe = true and trashed = false`;
442
479
  const sharedResponse = await withRetry(async () => {
443
480
  return await this.drive.files.list({
444
481
  q: sharedQ,
@@ -568,6 +605,7 @@ var init_format = __esm({
568
605
  // src/core/resumable-uploader.ts
569
606
  import fs2 from "fs";
570
607
  import path2 from "path";
608
+ import { Transform } from "stream";
571
609
  var MIN_CHUNK_SIZE, DEFAULT_CHUNK_SIZE, MULTIPART_THRESHOLD, ResumableUploader;
572
610
  var init_resumable_uploader = __esm({
573
611
  "src/core/resumable-uploader.ts"() {
@@ -577,6 +615,7 @@ var init_resumable_uploader = __esm({
577
615
  init_format();
578
616
  init_mime();
579
617
  init_retry();
618
+ init_http_agent();
580
619
  MIN_CHUNK_SIZE = 256 * 1024;
581
620
  DEFAULT_CHUNK_SIZE = 8 * 1024 * 1024;
582
621
  MULTIPART_THRESHOLD = 5 * 1024 * 1024;
@@ -614,6 +653,15 @@ var init_resumable_uploader = __esm({
614
653
  const totalBytes = stat.size;
615
654
  const fileName = options.name || path2.basename(filePath);
616
655
  const mimeType = options.mimeType || lookupMimeType(filePath);
656
+ if (totalBytes <= MULTIPART_THRESHOLD) {
657
+ const readStream = fs2.createReadStream(filePath, { highWaterMark: 1024 * 1024 });
658
+ const stream = options.onProgress ? this.wrapStreamWithProgress(readStream, totalBytes, options.onProgress) : readStream;
659
+ return await this.directUpload(stream, {
660
+ ...options,
661
+ name: fileName,
662
+ mimeType
663
+ });
664
+ }
617
665
  return await this.chunkedUpload({
618
666
  filePath,
619
667
  totalBytes,
@@ -629,6 +677,16 @@ var init_resumable_uploader = __esm({
629
677
  const totalBytes = buffer.length;
630
678
  const fileName = options.name || "untitled";
631
679
  const mimeType = options.mimeType || "application/octet-stream";
680
+ if (totalBytes <= MULTIPART_THRESHOLD) {
681
+ const { Readable } = await import("stream");
682
+ const baseStream = Readable.from(totalBytes === 0 ? [] : [buffer]);
683
+ const stream = options.onProgress ? this.wrapStreamWithProgress(baseStream, totalBytes, options.onProgress) : baseStream;
684
+ return await this.directUpload(stream, {
685
+ ...options,
686
+ name: fileName,
687
+ mimeType
688
+ });
689
+ }
632
690
  return await this.chunkedUploadBuffer({
633
691
  buffer,
634
692
  totalBytes,
@@ -649,6 +707,50 @@ var init_resumable_uploader = __esm({
649
707
  mimeType
650
708
  });
651
709
  }
710
+ /**
711
+ * Calculates optimal chunk size based on file size for maximum throughput.
712
+ */
713
+ computeAdaptiveChunkSize(totalBytes, explicitChunkSize) {
714
+ if (explicitChunkSize) {
715
+ return Math.max(MIN_CHUNK_SIZE, Math.floor(explicitChunkSize / MIN_CHUNK_SIZE) * MIN_CHUNK_SIZE);
716
+ }
717
+ if (totalBytes > 128 * 1024 * 1024) {
718
+ return 32 * 1024 * 1024;
719
+ }
720
+ if (totalBytes > 32 * 1024 * 1024) {
721
+ return 16 * 1024 * 1024;
722
+ }
723
+ return this.defaultChunkSize;
724
+ }
725
+ /**
726
+ * Attaches real-time progress monitoring to direct stream uploads.
727
+ */
728
+ wrapStreamWithProgress(stream, totalBytes, onProgress) {
729
+ let bytesSent = 0;
730
+ const startTime = Date.now();
731
+ const progressTransform = new Transform({
732
+ transform(chunk, _encoding, callback) {
733
+ bytesSent += chunk.length;
734
+ const elapsedSecs = (Date.now() - startTime) / 1e3;
735
+ const bytesPerSecond = elapsedSecs > 0 ? Math.round(bytesSent / elapsedSecs) : 0;
736
+ const remainingBytes = Math.max(0, totalBytes - bytesSent);
737
+ const estimatedTimeRemainingSeconds = bytesPerSecond > 0 ? Math.round(remainingBytes / bytesPerSecond) : 0;
738
+ const percentage = totalBytes > 0 ? Math.min(100, Math.round(bytesSent / totalBytes * 1e3) / 10) : 100;
739
+ onProgress({
740
+ bytesSent,
741
+ totalBytes,
742
+ percentage,
743
+ bytesPerSecond,
744
+ speedFormatted: formatSpeed(bytesPerSecond),
745
+ estimatedTimeRemainingSeconds,
746
+ chunkIndex: 1,
747
+ totalChunks: 1
748
+ });
749
+ callback(null, chunk);
750
+ }
751
+ });
752
+ return stream.pipe(progressTransform);
753
+ }
652
754
  /**
653
755
  * Fast direct upload using googleapis multipart
654
756
  */
@@ -681,7 +783,7 @@ var init_resumable_uploader = __esm({
681
783
  */
682
784
  async chunkedUpload(params) {
683
785
  const { filePath, totalBytes, fileName, mimeType, options } = params;
684
- const chunkSize = options.chunkSize ? Math.max(MIN_CHUNK_SIZE, Math.floor(options.chunkSize / MIN_CHUNK_SIZE) * MIN_CHUNK_SIZE) : this.defaultChunkSize;
786
+ const chunkSize = this.computeAdaptiveChunkSize(totalBytes, options.chunkSize);
685
787
  const sessionUrl = await this.initiateResumableSession({
686
788
  fileName,
687
789
  mimeType,
@@ -746,7 +848,7 @@ var init_resumable_uploader = __esm({
746
848
  */
747
849
  async chunkedUploadBuffer(params) {
748
850
  const { buffer, totalBytes, fileName, mimeType, options } = params;
749
- const chunkSize = options.chunkSize ? Math.max(MIN_CHUNK_SIZE, Math.floor(options.chunkSize / MIN_CHUNK_SIZE) * MIN_CHUNK_SIZE) : this.defaultChunkSize;
851
+ const chunkSize = this.computeAdaptiveChunkSize(totalBytes, options.chunkSize);
750
852
  const sessionUrl = await this.initiateResumableSession({
751
853
  fileName,
752
854
  mimeType,
@@ -825,7 +927,8 @@ var init_resumable_uploader = __esm({
825
927
  url: "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&supportsAllDrives=true",
826
928
  method: "POST",
827
929
  headers,
828
- data: metadata
930
+ data: metadata,
931
+ agent: getOptimizedHttpsAgent()
829
932
  });
830
933
  });
831
934
  const sessionUrl = res.headers?.get ? res.headers.get("location") : res.headers?.location || res.headers?.["location"];
@@ -851,6 +954,7 @@ var init_resumable_uploader = __esm({
851
954
  method: "PUT",
852
955
  headers,
853
956
  data: buffer,
957
+ agent: getOptimizedHttpsAgent(),
854
958
  validateStatus: (status) => status >= 200 && status < 300 || status === 308
855
959
  });
856
960
  if (res.status === 200 || res.status === 201) {
@@ -885,7 +989,7 @@ var init_resumable_uploader = __esm({
885
989
  import fs3 from "fs";
886
990
  import path3 from "path";
887
991
  import { pipeline } from "stream/promises";
888
- import { Transform } from "stream";
992
+ import { Transform as Transform2 } from "stream";
889
993
  var Downloader;
890
994
  var init_downloader = __esm({
891
995
  "src/core/downloader.ts"() {
@@ -903,17 +1007,22 @@ var init_downloader = __esm({
903
1007
  * Downloads a file from Google Drive to local destination path or returns a readable stream.
904
1008
  */
905
1009
  async download(fileId, options = {}) {
906
- const metaRes = await withRetry(async () => {
907
- return await this.drive.files.get({
908
- fileId,
909
- fields: "id, name, mimeType, size",
910
- supportsAllDrives: true
1010
+ let name = options.metadata?.name;
1011
+ let mimeType = options.metadata?.mimeType;
1012
+ let totalBytes = options.metadata?.size;
1013
+ if (!name || !mimeType) {
1014
+ const metaRes = await withRetry(async () => {
1015
+ return await this.drive.files.get({
1016
+ fileId,
1017
+ fields: "id, name, mimeType, size",
1018
+ supportsAllDrives: true
1019
+ });
911
1020
  });
912
- });
913
- const file = metaRes.data;
914
- const name = file.name || "downloaded-file";
915
- const mimeType = file.mimeType || "application/octet-stream";
916
- const totalBytes = file.size ? parseInt(file.size, 10) : void 0;
1021
+ const file = metaRes.data;
1022
+ name = file.name || "downloaded-file";
1023
+ mimeType = file.mimeType || "application/octet-stream";
1024
+ totalBytes = file.size ? parseInt(file.size, 10) : void 0;
1025
+ }
917
1026
  let downloadStream;
918
1027
  let finalFileName = name;
919
1028
  if (isGoogleWorkspaceDoc(mimeType)) {
@@ -944,7 +1053,7 @@ var init_downloader = __esm({
944
1053
  }
945
1054
  let bytesRead = 0;
946
1055
  const startTime = Date.now();
947
- const progressTracker = new Transform({
1056
+ const progressTracker = new Transform2({
948
1057
  transform(chunk, encoding, callback) {
949
1058
  bytesRead += chunk.length;
950
1059
  if (options.onProgress) {
@@ -969,7 +1078,7 @@ var init_downloader = __esm({
969
1078
  destPath = path3.join(destPath, finalFileName);
970
1079
  }
971
1080
  await fs3.promises.mkdir(path3.dirname(destPath), { recursive: true });
972
- const writeStream = fs3.createWriteStream(destPath);
1081
+ const writeStream = fs3.createWriteStream(destPath, { highWaterMark: 1024 * 1024 });
973
1082
  await pipeline(monitoredStream, writeStream);
974
1083
  return {
975
1084
  filePath: destPath,
@@ -1220,6 +1329,7 @@ var init_query_builder = __esm({
1220
1329
  const q = this.toQueryString();
1221
1330
  const orderBy = this.orderClauses.join(", ");
1222
1331
  let pageToken = void 0;
1332
+ const effectiveFields = this.requestedFields.includes("nextPageToken") ? this.requestedFields : `nextPageToken, ${this.requestedFields}`;
1223
1333
  do {
1224
1334
  const res = await withRetry(async () => {
1225
1335
  return await this.drive.files.list({
@@ -1227,7 +1337,7 @@ var init_query_builder = __esm({
1227
1337
  orderBy: orderBy || void 0,
1228
1338
  pageSize: this.limitNumber,
1229
1339
  pageToken,
1230
- fields: this.requestedFields,
1340
+ fields: effectiveFields,
1231
1341
  spaces: this.spaces,
1232
1342
  supportsAllDrives: true,
1233
1343
  includeItemsFromAllDrives: true
@@ -1364,7 +1474,7 @@ var init_watcher = __esm({
1364
1474
  const res = await withRetry(async () => {
1365
1475
  return await this.drive.changes.list({
1366
1476
  pageToken: nextPageToken,
1367
- fields: "nextPageToken, newStartPageToken, changes(changeType, fileId, removed, time, file(id, name, mimeType, size, modifiedTime, parents, trashed))",
1477
+ fields: "nextPageToken, newStartPageToken, changes(changeType, fileId, removed, time, file(id, name, mimeType, size, createdTime, modifiedTime, parents, trashed))",
1368
1478
  supportsAllDrives: true,
1369
1479
  includeItemsFromAllDrives: true
1370
1480
  });
@@ -1463,16 +1573,24 @@ var init_storage_cleaner = __esm({
1463
1573
  async findDuplicates(options = {}) {
1464
1574
  const mode = options.by || "name";
1465
1575
  const maxScan = options.maxScan || 1e3;
1466
- const res = await withRetry(async () => {
1467
- return await this.drive.files.list({
1468
- q: 'trashed = false and mimeType != "application/vnd.google-apps.folder"',
1469
- pageSize: Math.min(1e3, maxScan),
1470
- fields: "files(id, name, size, md5Checksum, modifiedTime)",
1471
- supportsAllDrives: true,
1472
- includeItemsFromAllDrives: true
1576
+ const files = [];
1577
+ let pageToken = void 0;
1578
+ do {
1579
+ const remaining = maxScan - files.length;
1580
+ if (remaining <= 0) break;
1581
+ const res = await withRetry(async () => {
1582
+ return await this.drive.files.list({
1583
+ q: 'trashed = false and mimeType != "application/vnd.google-apps.folder"',
1584
+ pageSize: Math.min(1e3, remaining),
1585
+ pageToken,
1586
+ fields: "nextPageToken, files(id, name, size, md5Checksum, modifiedTime)",
1587
+ supportsAllDrives: true,
1588
+ includeItemsFromAllDrives: true
1589
+ });
1473
1590
  });
1474
- });
1475
- const files = res.data.files || [];
1591
+ files.push(...res.data.files || []);
1592
+ pageToken = res.data.nextPageToken || void 0;
1593
+ } while (pageToken && files.length < maxScan);
1476
1594
  const map = /* @__PURE__ */ new Map();
1477
1595
  for (const f of files) {
1478
1596
  if (!f.id) continue;
@@ -1657,7 +1775,7 @@ var init_smart_sync = __esm({
1657
1775
  });
1658
1776
 
1659
1777
  // src/auth/browser-login.ts
1660
- import http from "http";
1778
+ import http2 from "http";
1661
1779
  import { exec } from "child_process";
1662
1780
  import { auth as googleAuth2 } from "@googleapis/drive";
1663
1781
  async function loginWithBrowser(options) {
@@ -1675,7 +1793,7 @@ async function loginWithBrowser(options) {
1675
1793
  scope: scopes
1676
1794
  });
1677
1795
  return new Promise((resolve, reject) => {
1678
- const server = http.createServer(async (req, res) => {
1796
+ const server = http2.createServer(async (req, res) => {
1679
1797
  try {
1680
1798
  const reqUrl = new URL(req.url || "/", `http://localhost:${port}`);
1681
1799
  if (reqUrl.pathname === "/oauth2callback") {
@@ -1759,7 +1877,11 @@ ${authUrl}
1759
1877
  });
1760
1878
  });
1761
1879
  server.on("error", (err) => {
1762
- reject(err);
1880
+ if (err.code === "EADDRINUSE") {
1881
+ reject(new Error(`Port ${port} is already in use by another process. Please specify an alternate port with --port <number>.`));
1882
+ } else {
1883
+ reject(err);
1884
+ }
1763
1885
  });
1764
1886
  });
1765
1887
  }
@@ -1837,6 +1959,10 @@ var init_resource_refs = __esm({
1837
1959
  async getLink() {
1838
1960
  return await this.drive.getShareableLink(this.pathOrId);
1839
1961
  }
1962
+ /** Access historical revisions & version control for this file */
1963
+ get revisions() {
1964
+ return this.drive.getRevisions(this.pathOrId);
1965
+ }
1840
1966
  /** Returns a ReadableStream for this file, optionally with byte Range requests */
1841
1967
  async createReadStream(options) {
1842
1968
  return await this.drive.createReadStream(this.pathOrId, options);
@@ -2131,10 +2257,35 @@ var init_cache = __esm({
2131
2257
  return;
2132
2258
  }
2133
2259
  if (!this.initialized || !this.db || entries.length === 0) return;
2260
+ const stmt = this.db.prepare(`
2261
+ INSERT INTO files (id, name, mimeType, size, parentId, path, md5Checksum, trashed, modifiedTime, updatedAt)
2262
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2263
+ ON CONFLICT(id) DO UPDATE SET
2264
+ name = excluded.name,
2265
+ mimeType = excluded.mimeType,
2266
+ size = excluded.size,
2267
+ parentId = excluded.parentId,
2268
+ path = COALESCE(excluded.path, files.path),
2269
+ md5Checksum = excluded.md5Checksum,
2270
+ trashed = excluded.trashed,
2271
+ modifiedTime = excluded.modifiedTime,
2272
+ updatedAt = excluded.updatedAt
2273
+ `);
2134
2274
  this.db.exec("BEGIN TRANSACTION;");
2135
2275
  try {
2136
2276
  for (const entry of entries) {
2137
- this.upsertFile(entry);
2277
+ stmt.run(
2278
+ entry.id,
2279
+ entry.name,
2280
+ entry.mimeType ?? null,
2281
+ entry.size ?? null,
2282
+ entry.parentId ?? null,
2283
+ entry.path ?? null,
2284
+ entry.md5Checksum ? entry.md5Checksum.toLowerCase() : null,
2285
+ entry.trashed ? 1 : 0,
2286
+ entry.modifiedTime ?? null,
2287
+ entry.updatedAt ?? Date.now()
2288
+ );
2138
2289
  }
2139
2290
  this.db.exec("COMMIT;");
2140
2291
  } catch (e) {
@@ -2353,143 +2504,1354 @@ var init_cache = __esm({
2353
2504
  }
2354
2505
  });
2355
2506
 
2356
- // src/server/webdav.ts
2357
- var webdav_exports = {};
2358
- __export(webdav_exports, {
2359
- escapeXml: () => escapeXml,
2360
- startWebDAVServer: () => startWebDAVServer
2361
- });
2362
- import http2 from "http";
2363
- import url from "url";
2364
- import path7 from "path";
2365
- function escapeXml(unsafe) {
2366
- return unsafe.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
2507
+ // src/crypto/encryption.ts
2508
+ import crypto2 from "crypto";
2509
+ import { Transform as Transform3 } from "stream";
2510
+ function deriveKey(password, salt) {
2511
+ return crypto2.pbkdf2Sync(password, salt, PBKDF2_ROUNDS, 32, "sha512");
2367
2512
  }
2368
- async function startWebDAVServer(drive2, options = {}) {
2369
- const port = options.port || 8080;
2370
- const host = options.host || "127.0.0.1";
2371
- await drive2.init();
2372
- const server = http2.createServer(async (req, res) => {
2373
- try {
2374
- if (options.auth?.username && options.auth?.password) {
2375
- const authHeader = req.headers["authorization"];
2376
- if (!authHeader || !authHeader.startsWith("Basic ")) {
2377
- res.writeHead(401, {
2378
- "WWW-Authenticate": 'Basic realm="DriveKit WebDAV"',
2379
- "Content-Type": "text/plain"
2380
- });
2381
- res.end("Authentication required");
2382
- return;
2513
+ var MAGIC_HEADER, MAGIC_STREAM_HEADER, SALT_LENGTH, IV_LENGTH, TAG_LENGTH, PBKDF2_ROUNDS, DriveKitCrypto;
2514
+ var init_encryption = __esm({
2515
+ "src/crypto/encryption.ts"() {
2516
+ "use strict";
2517
+ init_esm_shims();
2518
+ MAGIC_HEADER = Buffer.from("DKENC1", "utf8");
2519
+ MAGIC_STREAM_HEADER = Buffer.from("DKENCS", "utf8");
2520
+ SALT_LENGTH = 16;
2521
+ IV_LENGTH = 12;
2522
+ TAG_LENGTH = 16;
2523
+ PBKDF2_ROUNDS = 1e5;
2524
+ DriveKitCrypto = class {
2525
+ config;
2526
+ constructor(config) {
2527
+ if (!config.password && !config.key) {
2528
+ throw new Error("DriveKitCrypto requires either a password or a 32-byte key.");
2383
2529
  }
2384
- const credentials = Buffer.from(authHeader.replace("Basic ", ""), "base64").toString("utf8");
2385
- const [user, pass] = credentials.split(":");
2386
- if (user !== options.auth.username || pass !== options.auth.password) {
2387
- res.writeHead(401, {
2388
- "WWW-Authenticate": 'Basic realm="DriveKit WebDAV"',
2389
- "Content-Type": "text/plain"
2390
- });
2391
- res.end("Invalid credentials");
2392
- return;
2530
+ if (config.key && config.key.length !== 32) {
2531
+ throw new Error(`DriveKitCrypto raw key must be exactly 32 bytes, got ${config.key.length} bytes.`);
2393
2532
  }
2533
+ this.config = config;
2394
2534
  }
2395
- const parsedUrl = url.parse(req.url || "/", true);
2396
- const decodedPath = decodeURIComponent(parsedUrl.pathname || "/");
2397
- const virtualPath = decodedPath === "" ? "/" : decodedPath;
2398
- switch (req.method) {
2399
- case "OPTIONS": {
2400
- res.writeHead(200, {
2401
- DAV: "1, 2",
2402
- Allow: "OPTIONS, GET, HEAD, POST, PUT, DELETE, MKCOL, MOVE, COPY, PROPFIND",
2403
- "MS-Author-Via": "DAV",
2404
- "Accept-Ranges": "bytes"
2405
- });
2406
- res.end();
2407
- return;
2535
+ /**
2536
+ * Encrypts a Buffer using AES-256-GCM.
2537
+ * Format: [MAGIC (6B)][SALT (16B)][IV (12B)][TAG (16B)][CIPHERTEXT]
2538
+ */
2539
+ encryptBuffer(data) {
2540
+ const salt = crypto2.randomBytes(SALT_LENGTH);
2541
+ const iv = crypto2.randomBytes(IV_LENGTH);
2542
+ const key = this.config.key || deriveKey(this.config.password, salt);
2543
+ const cipher = crypto2.createCipheriv("aes-256-gcm", key, iv);
2544
+ const ciphertext = Buffer.concat([cipher.update(data), cipher.final()]);
2545
+ const tag = cipher.getAuthTag();
2546
+ return Buffer.concat([MAGIC_HEADER, salt, iv, tag, ciphertext]);
2547
+ }
2548
+ /**
2549
+ * Decrypts a Buffer previously encrypted with encryptBuffer or createEncryptStream.
2550
+ */
2551
+ decryptBuffer(encryptedData) {
2552
+ if (encryptedData.length < MAGIC_HEADER.length + SALT_LENGTH + IV_LENGTH + TAG_LENGTH) {
2553
+ throw new Error("Encrypted payload is too short to be valid DriveKit ciphertext.");
2408
2554
  }
2409
- case "PROPFIND": {
2410
- const depth = req.headers["depth"] || "1";
2411
- const xml = await handlePropfind(drive2, virtualPath, depth);
2412
- res.writeHead(207, {
2413
- "Content-Type": "application/xml; charset=utf-8"
2414
- });
2415
- res.end(xml);
2416
- return;
2555
+ const magic = encryptedData.subarray(0, MAGIC_HEADER.length);
2556
+ const isStreamFormat = magic.equals(MAGIC_STREAM_HEADER);
2557
+ const isBufferFormat = magic.equals(MAGIC_HEADER);
2558
+ if (!isStreamFormat && !isBufferFormat) {
2559
+ throw new Error("Invalid magic header: file was not encrypted by DriveKit or is corrupted.");
2417
2560
  }
2418
- case "GET":
2419
- case "HEAD": {
2420
- if (virtualPath === "/" || virtualPath === "") {
2421
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
2422
- res.end("<h1>DriveKit WebDAV Server Running</h1><p>Connect via Finder, File Explorer, or WebDAV client.</p>");
2423
- return;
2561
+ const salt = encryptedData.subarray(6, 6 + SALT_LENGTH);
2562
+ const iv = encryptedData.subarray(6 + SALT_LENGTH, 6 + SALT_LENGTH + IV_LENGTH);
2563
+ const key = this.config.key || deriveKey(this.config.password, salt);
2564
+ let tag;
2565
+ let ciphertext;
2566
+ if (isStreamFormat) {
2567
+ tag = encryptedData.subarray(encryptedData.length - TAG_LENGTH);
2568
+ ciphertext = encryptedData.subarray(6 + SALT_LENGTH + IV_LENGTH, encryptedData.length - TAG_LENGTH);
2569
+ } else {
2570
+ tag = encryptedData.subarray(6 + SALT_LENGTH + IV_LENGTH, 6 + SALT_LENGTH + IV_LENGTH + TAG_LENGTH);
2571
+ ciphertext = encryptedData.subarray(6 + SALT_LENGTH + IV_LENGTH + TAG_LENGTH);
2572
+ }
2573
+ const decipher = crypto2.createDecipheriv("aes-256-gcm", key, iv);
2574
+ decipher.setAuthTag(tag);
2575
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
2576
+ }
2577
+ /**
2578
+ * Creates an encryption Transform stream that prepends stream header and appends GCM auth tag
2579
+ */
2580
+ createEncryptStream() {
2581
+ const salt = crypto2.randomBytes(SALT_LENGTH);
2582
+ const iv = crypto2.randomBytes(IV_LENGTH);
2583
+ const key = this.config.key || deriveKey(this.config.password, salt);
2584
+ const cipher = crypto2.createCipheriv("aes-256-gcm", key, iv);
2585
+ let headerPushed = false;
2586
+ return new Transform3({
2587
+ transform(chunk, _encoding, callback) {
2588
+ if (!headerPushed) {
2589
+ this.push(Buffer.concat([MAGIC_STREAM_HEADER, salt, iv]));
2590
+ headerPushed = true;
2591
+ }
2592
+ const encrypted = cipher.update(chunk);
2593
+ if (encrypted.length > 0) {
2594
+ this.push(encrypted);
2595
+ }
2596
+ callback();
2597
+ },
2598
+ flush(callback) {
2599
+ if (!headerPushed) {
2600
+ this.push(Buffer.concat([MAGIC_STREAM_HEADER, salt, iv]));
2601
+ headerPushed = true;
2602
+ }
2603
+ const finalChunk = cipher.final();
2604
+ const tag = cipher.getAuthTag();
2605
+ this.push(Buffer.concat([finalChunk, tag]));
2606
+ callback();
2424
2607
  }
2425
- try {
2426
- const file = await drive2.getFile(virtualPath);
2427
- if (file.mimeType === "application/vnd.google-apps.folder") {
2428
- res.writeHead(405, { "Content-Type": "text/plain" });
2429
- res.end("Cannot GET a directory");
2430
- return;
2608
+ });
2609
+ }
2610
+ /**
2611
+ * Creates a decryption Transform stream that verifies magic header and validates GCM authentication tag
2612
+ */
2613
+ createDecryptStream() {
2614
+ const HEADER_BASE_LEN = MAGIC_HEADER.length + SALT_LENGTH + IV_LENGTH;
2615
+ let headerBuffer = Buffer.alloc(0);
2616
+ let decipher = null;
2617
+ let isStreamFormat = false;
2618
+ let pendingTail = Buffer.alloc(0);
2619
+ const self = this;
2620
+ return new Transform3({
2621
+ transform(chunk, _encoding, callback) {
2622
+ try {
2623
+ let data = chunk;
2624
+ if (!decipher) {
2625
+ headerBuffer = Buffer.concat([headerBuffer, data]);
2626
+ if (headerBuffer.length < HEADER_BASE_LEN) {
2627
+ return callback();
2628
+ }
2629
+ const magic = headerBuffer.subarray(0, MAGIC_HEADER.length);
2630
+ isStreamFormat = magic.equals(MAGIC_STREAM_HEADER);
2631
+ const isBufferFormat = magic.equals(MAGIC_HEADER);
2632
+ if (!isStreamFormat && !isBufferFormat) {
2633
+ return callback(new Error("Invalid magic header: stream was not encrypted by DriveKit or is corrupted."));
2634
+ }
2635
+ const salt = headerBuffer.subarray(MAGIC_HEADER.length, MAGIC_HEADER.length + SALT_LENGTH);
2636
+ const iv = headerBuffer.subarray(MAGIC_HEADER.length + SALT_LENGTH, HEADER_BASE_LEN);
2637
+ const key = self.config.key || deriveKey(self.config.password, salt);
2638
+ decipher = crypto2.createDecipheriv("aes-256-gcm", key, iv);
2639
+ if (isBufferFormat) {
2640
+ if (headerBuffer.length < HEADER_BASE_LEN + TAG_LENGTH) {
2641
+ return callback();
2642
+ }
2643
+ const tag = headerBuffer.subarray(HEADER_BASE_LEN, HEADER_BASE_LEN + TAG_LENGTH);
2644
+ decipher.setAuthTag(tag);
2645
+ data = headerBuffer.subarray(HEADER_BASE_LEN + TAG_LENGTH);
2646
+ headerBuffer = Buffer.alloc(0);
2647
+ } else {
2648
+ data = headerBuffer.subarray(HEADER_BASE_LEN);
2649
+ headerBuffer = Buffer.alloc(0);
2650
+ }
2651
+ }
2652
+ if (data.length > 0) {
2653
+ if (isStreamFormat) {
2654
+ pendingTail = Buffer.concat([pendingTail, data]);
2655
+ if (pendingTail.length > TAG_LENGTH) {
2656
+ const toProcess = pendingTail.subarray(0, pendingTail.length - TAG_LENGTH);
2657
+ pendingTail = pendingTail.subarray(pendingTail.length - TAG_LENGTH);
2658
+ const decryptedChunk = decipher.update(toProcess);
2659
+ if (decryptedChunk.length > 0) {
2660
+ this.push(decryptedChunk);
2661
+ }
2662
+ }
2663
+ } else {
2664
+ const decryptedChunk = decipher.update(data);
2665
+ if (decryptedChunk.length > 0) {
2666
+ this.push(decryptedChunk);
2667
+ }
2668
+ }
2669
+ }
2670
+ callback();
2671
+ } catch (err) {
2672
+ callback(err);
2431
2673
  }
2432
- const fileSize = file.size ? parseInt(file.size, 10) : void 0;
2433
- const rangeHeader = req.headers["range"];
2434
- if (rangeHeader && rangeHeader.startsWith("bytes=") && fileSize !== void 0) {
2435
- const parts = rangeHeader.replace("bytes=", "").split("-");
2436
- const start = parseInt(parts[0], 10);
2437
- const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
2438
- if (isNaN(start) || start >= fileSize || end !== void 0 && end >= fileSize) {
2439
- res.writeHead(416, { "Content-Range": `bytes */${fileSize}` });
2440
- res.end();
2441
- return;
2674
+ },
2675
+ flush(callback) {
2676
+ try {
2677
+ if (!decipher) {
2678
+ return callback(new Error("Encrypted stream is too short: missing header."));
2442
2679
  }
2443
- const stream = await drive2.createReadStream(virtualPath, { start, end });
2444
- const chunkLength = end - start + 1;
2445
- res.writeHead(206, {
2446
- "Content-Type": file.mimeType || "application/octet-stream",
2447
- "Content-Range": `bytes ${start}-${end}/${fileSize}`,
2448
- "Content-Length": chunkLength,
2449
- "Accept-Ranges": "bytes"
2450
- });
2451
- if (req.method === "HEAD") {
2452
- res.end();
2453
- } else {
2454
- stream.pipe(res);
2680
+ if (isStreamFormat) {
2681
+ if (pendingTail.length !== TAG_LENGTH) {
2682
+ return callback(new Error("Encrypted stream is truncated: missing authentication tag."));
2683
+ }
2684
+ decipher.setAuthTag(pendingTail);
2455
2685
  }
2456
- } else {
2457
- const stream = await drive2.createReadStream(virtualPath);
2458
- res.writeHead(200, {
2459
- "Content-Type": file.mimeType || "application/octet-stream",
2460
- "Content-Length": file.size || void 0,
2461
- "Accept-Ranges": "bytes"
2462
- });
2463
- if (req.method === "HEAD") {
2464
- res.end();
2465
- } else {
2466
- stream.pipe(res);
2686
+ const finalChunk = decipher.final();
2687
+ if (finalChunk.length > 0) {
2688
+ this.push(finalChunk);
2467
2689
  }
2690
+ callback();
2691
+ } catch (err) {
2692
+ callback(new Error(`Authentication failed: corrupted data or invalid authentication tag (${err.message})`));
2468
2693
  }
2469
- } catch (e) {
2470
- res.writeHead(404, { "Content-Type": "text/plain" });
2471
- res.end("File Not Found");
2472
2694
  }
2473
- return;
2695
+ });
2696
+ }
2697
+ /**
2698
+ * Encrypts a filename into a safe base64url string
2699
+ */
2700
+ encryptFilename(plainName) {
2701
+ const iv = crypto2.randomBytes(12);
2702
+ const salt = crypto2.randomBytes(8);
2703
+ const key = this.config.key || deriveKey(this.config.password, Buffer.concat([salt, salt]));
2704
+ const cipher = crypto2.createCipheriv("aes-256-gcm", key, iv);
2705
+ const encrypted = Buffer.concat([cipher.update(Buffer.from(plainName, "utf8")), cipher.final()]);
2706
+ const tag = cipher.getAuthTag();
2707
+ const payload = Buffer.concat([salt, iv, tag, encrypted]);
2708
+ return `dk_${payload.toString("base64url")}.enc`;
2709
+ }
2710
+ /**
2711
+ * Decrypts a filename generated by encryptFilename
2712
+ */
2713
+ decryptFilename(encryptedName) {
2714
+ if (!encryptedName.startsWith("dk_") || !encryptedName.endsWith(".enc")) {
2715
+ return encryptedName;
2474
2716
  }
2475
- case "PUT": {
2476
- const remoteDir = path7.dirname(virtualPath);
2477
- await drive2.mkdirp(remoteDir);
2478
- let existed = false;
2479
- try {
2480
- const existingFile = await drive2.getFile(virtualPath);
2481
- if (existingFile && existingFile.id) {
2482
- existed = true;
2483
- }
2484
- } catch {
2485
- existed = false;
2486
- }
2487
- try {
2488
- const uploadStream = await drive2.createWriteStream(virtualPath, {
2489
- overwrite: true
2490
- });
2491
- req.pipe(uploadStream);
2492
- await uploadStream.done;
2717
+ try {
2718
+ const raw = encryptedName.slice(3, -4);
2719
+ const payload = Buffer.from(raw, "base64url");
2720
+ if (payload.length < 8 + 12 + 16) return encryptedName;
2721
+ const salt = payload.subarray(0, 8);
2722
+ const iv = payload.subarray(8, 20);
2723
+ const tag = payload.subarray(20, 36);
2724
+ const ciphertext = payload.subarray(36);
2725
+ const key = this.config.key || deriveKey(this.config.password, Buffer.concat([salt, salt]));
2726
+ const decipher = crypto2.createDecipheriv("aes-256-gcm", key, iv);
2727
+ decipher.setAuthTag(tag);
2728
+ const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
2729
+ return decrypted.toString("utf8");
2730
+ } catch {
2731
+ return encryptedName;
2732
+ }
2733
+ }
2734
+ };
2735
+ }
2736
+ });
2737
+
2738
+ // src/core/revisions.ts
2739
+ var DriveFileRevisions;
2740
+ var init_revisions = __esm({
2741
+ "src/core/revisions.ts"() {
2742
+ "use strict";
2743
+ init_esm_shims();
2744
+ init_retry();
2745
+ DriveFileRevisions = class {
2746
+ drive;
2747
+ pathOrId;
2748
+ idResolver;
2749
+ constructor(drive2, pathOrId, idResolver) {
2750
+ this.drive = drive2;
2751
+ this.pathOrId = pathOrId;
2752
+ this.idResolver = idResolver;
2753
+ }
2754
+ async getId() {
2755
+ if (this.idResolver && (this.pathOrId.startsWith("/") || this.pathOrId.includes("/"))) {
2756
+ return await this.idResolver(this.pathOrId);
2757
+ }
2758
+ return this.pathOrId;
2759
+ }
2760
+ /**
2761
+ * Lists all historical revisions of the file
2762
+ */
2763
+ async list() {
2764
+ const fileId = await this.getId();
2765
+ const res = await withRetry(async () => {
2766
+ return await this.drive.revisions.list({
2767
+ fileId,
2768
+ fields: "revisions(id, mimeType, modifiedTime, keepForever, size, originalFilename)"
2769
+ });
2770
+ });
2771
+ const revs = res.data.revisions || [];
2772
+ return revs.map((r) => ({
2773
+ id: r.id,
2774
+ mimeType: r.mimeType || void 0,
2775
+ modifiedTime: r.modifiedTime || void 0,
2776
+ keepForever: r.keepForever ?? false,
2777
+ size: r.size ? parseInt(r.size, 10) : void 0,
2778
+ originalFilename: r.originalFilename || void 0
2779
+ }));
2780
+ }
2781
+ /**
2782
+ * Gets metadata for a specific revision
2783
+ */
2784
+ async get(revisionId) {
2785
+ const fileId = await this.getId();
2786
+ const res = await withRetry(async () => {
2787
+ return await this.drive.revisions.get({
2788
+ fileId,
2789
+ revisionId,
2790
+ fields: "id, mimeType, modifiedTime, keepForever, size, originalFilename"
2791
+ });
2792
+ });
2793
+ const r = res.data;
2794
+ return {
2795
+ id: r.id,
2796
+ mimeType: r.mimeType || void 0,
2797
+ modifiedTime: r.modifiedTime || void 0,
2798
+ keepForever: r.keepForever ?? false,
2799
+ size: r.size ? parseInt(r.size, 10) : void 0,
2800
+ originalFilename: r.originalFilename || void 0
2801
+ };
2802
+ }
2803
+ /**
2804
+ * Pins or unpins a revision so Google Drive never automatically purges it after 30 days
2805
+ */
2806
+ async keepForever(revisionId, keep = true) {
2807
+ const fileId = await this.getId();
2808
+ const res = await withRetry(async () => {
2809
+ return await this.drive.revisions.update({
2810
+ fileId,
2811
+ revisionId,
2812
+ requestBody: {
2813
+ keepForever: keep
2814
+ },
2815
+ fields: "id, keepForever, modifiedTime"
2816
+ });
2817
+ });
2818
+ return {
2819
+ id: res.data.id,
2820
+ keepForever: res.data.keepForever ?? keep,
2821
+ modifiedTime: res.data.modifiedTime || void 0
2822
+ };
2823
+ }
2824
+ /**
2825
+ * Deletes a specific historical revision
2826
+ */
2827
+ async delete(revisionId) {
2828
+ const fileId = await this.getId();
2829
+ await withRetry(async () => {
2830
+ return await this.drive.revisions.delete({
2831
+ fileId,
2832
+ revisionId
2833
+ });
2834
+ });
2835
+ }
2836
+ /**
2837
+ * Gets a readable stream of a specific historical revision
2838
+ */
2839
+ async getStream(revisionId) {
2840
+ const fileId = await this.getId();
2841
+ const res = await withRetry(async () => {
2842
+ return await this.drive.revisions.get(
2843
+ { fileId, revisionId, alt: "media" },
2844
+ { responseType: "stream" }
2845
+ );
2846
+ });
2847
+ return res.data;
2848
+ }
2849
+ /**
2850
+ * Restores the file content to a specific previous revision
2851
+ */
2852
+ async restore(revisionId) {
2853
+ const fileId = await this.getId();
2854
+ const stream = await this.getStream(revisionId);
2855
+ const meta = await this.get(revisionId);
2856
+ await withRetry(async () => {
2857
+ return await this.drive.files.update({
2858
+ fileId,
2859
+ media: {
2860
+ mimeType: meta.mimeType || "application/octet-stream",
2861
+ body: stream
2862
+ }
2863
+ });
2864
+ });
2865
+ }
2866
+ };
2867
+ }
2868
+ });
2869
+
2870
+ // src/core/bidirectional-sync.ts
2871
+ import fs6 from "fs";
2872
+ import path7 from "path";
2873
+ var BidirectionalSyncEngine;
2874
+ var init_bidirectional_sync = __esm({
2875
+ "src/core/bidirectional-sync.ts"() {
2876
+ "use strict";
2877
+ init_esm_shims();
2878
+ init_smart_sync();
2879
+ BidirectionalSyncEngine = class {
2880
+ drive;
2881
+ ledger = /* @__PURE__ */ new Map();
2882
+ constructor(drive2) {
2883
+ this.drive = drive2;
2884
+ }
2885
+ /**
2886
+ * Performs a two-way synchronization cycle between local and remote directories
2887
+ */
2888
+ async sync(options) {
2889
+ const startTime = Date.now();
2890
+ const {
2891
+ localDir,
2892
+ remoteDir,
2893
+ conflictStrategy = "rename-conflict",
2894
+ deleteMissing = false,
2895
+ dryRun = false,
2896
+ onProgress
2897
+ } = options;
2898
+ const result = {
2899
+ uploaded: [],
2900
+ downloaded: [],
2901
+ deletedLocal: [],
2902
+ deletedRemote: [],
2903
+ conflicts: [],
2904
+ skipped: [],
2905
+ durationMs: 0
2906
+ };
2907
+ if (!fs6.existsSync(localDir)) {
2908
+ await fs6.promises.mkdir(localDir, { recursive: true });
2909
+ }
2910
+ const remoteFolderId = await this.drive.mkdirp(remoteDir);
2911
+ const localFiles = await this.scanLocalDir(localDir);
2912
+ const remoteFiles = await this.scanRemoteDir(remoteFolderId, "");
2913
+ const allPaths = /* @__PURE__ */ new Set([
2914
+ ...localFiles.keys(),
2915
+ ...remoteFiles.keys(),
2916
+ ...this.ledger.keys()
2917
+ ]);
2918
+ for (const relPath of allPaths) {
2919
+ const resolvedLocal = path7.resolve(localDir, relPath);
2920
+ const resolvedRoot = path7.resolve(localDir);
2921
+ if (!resolvedLocal.startsWith(resolvedRoot + path7.sep) && resolvedLocal !== resolvedRoot) {
2922
+ throw new Error(`Security Violation: Path traversal detected in sync path: "${relPath}"`);
2923
+ }
2924
+ const local = localFiles.get(relPath);
2925
+ const remote = remoteFiles.get(relPath);
2926
+ const prev = this.ledger.get(relPath);
2927
+ if (local && remote) {
2928
+ const localChanged = !prev || local.md5 !== prev.localMd5 || Math.abs(local.mtime - prev.localMtime) > 1e3;
2929
+ const remoteChanged = !prev || remote.md5 !== prev.remoteMd5 || Math.abs(remote.mtime - prev.remoteMtime) > 1e3;
2930
+ if (local.md5 === remote.md5) {
2931
+ result.skipped.push(relPath);
2932
+ onProgress?.({ action: "skip-identical", relPath });
2933
+ this.ledger.set(relPath, {
2934
+ relPath,
2935
+ localMtime: local.mtime,
2936
+ remoteMtime: remote.mtime,
2937
+ localMd5: local.md5,
2938
+ remoteMd5: remote.md5,
2939
+ remoteId: remote.id
2940
+ });
2941
+ continue;
2942
+ }
2943
+ if (localChanged && !remoteChanged) {
2944
+ if (!dryRun) {
2945
+ await this.uploadFile(local.fullPath, remoteDir, relPath);
2946
+ const freshRemote = await this.drive.getFile(remote.id);
2947
+ this.updateLedger(relPath, local, freshRemote);
2948
+ }
2949
+ result.uploaded.push(relPath);
2950
+ onProgress?.({ action: "upload", relPath, details: "Local modification propagated" });
2951
+ continue;
2952
+ }
2953
+ if (remoteChanged && !localChanged) {
2954
+ if (!dryRun) {
2955
+ await this.downloadFile(remote.id, local.fullPath);
2956
+ const freshStat = await fs6.promises.stat(local.fullPath);
2957
+ this.ledger.set(relPath, {
2958
+ relPath,
2959
+ localMtime: freshStat.mtimeMs,
2960
+ remoteMtime: remote.mtime,
2961
+ localMd5: remote.md5,
2962
+ remoteMd5: remote.md5,
2963
+ remoteId: remote.id
2964
+ });
2965
+ }
2966
+ result.downloaded.push(relPath);
2967
+ onProgress?.({ action: "download", relPath, details: "Remote modification propagated" });
2968
+ continue;
2969
+ }
2970
+ result.conflicts.push(relPath);
2971
+ onProgress?.({ action: "conflict-resolved", relPath, details: `Strategy: ${conflictStrategy}` });
2972
+ if (!dryRun) {
2973
+ if (conflictStrategy === "prefer-local") {
2974
+ await this.uploadFile(local.fullPath, remoteDir, relPath);
2975
+ const freshRemote = await this.drive.getFile(remote.id);
2976
+ this.updateLedger(relPath, local, freshRemote);
2977
+ result.uploaded.push(relPath);
2978
+ } else if (conflictStrategy === "prefer-cloud") {
2979
+ await this.downloadFile(remote.id, local.fullPath);
2980
+ const freshStat = await fs6.promises.stat(local.fullPath);
2981
+ this.ledger.set(relPath, {
2982
+ relPath,
2983
+ localMtime: freshStat.mtimeMs,
2984
+ remoteMtime: remote.mtime,
2985
+ localMd5: remote.md5,
2986
+ remoteMd5: remote.md5,
2987
+ remoteId: remote.id
2988
+ });
2989
+ result.downloaded.push(relPath);
2990
+ } else if (conflictStrategy === "keep-newer") {
2991
+ if (local.mtime >= remote.mtime) {
2992
+ await this.uploadFile(local.fullPath, remoteDir, relPath);
2993
+ const freshRemote = await this.drive.getFile(remote.id);
2994
+ this.updateLedger(relPath, local, freshRemote);
2995
+ result.uploaded.push(relPath);
2996
+ } else {
2997
+ await this.downloadFile(remote.id, local.fullPath);
2998
+ const freshStat = await fs6.promises.stat(local.fullPath);
2999
+ this.ledger.set(relPath, {
3000
+ relPath,
3001
+ localMtime: freshStat.mtimeMs,
3002
+ remoteMtime: remote.mtime,
3003
+ localMd5: remote.md5,
3004
+ remoteMd5: remote.md5,
3005
+ remoteId: remote.id
3006
+ });
3007
+ result.downloaded.push(relPath);
3008
+ }
3009
+ } else {
3010
+ const ext = path7.extname(relPath);
3011
+ const base = relPath.slice(0, relPath.length - ext.length);
3012
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
3013
+ const conflictRelPath = `${base} (Conflict ${timestamp})${ext}`;
3014
+ const conflictFullPath = path7.join(localDir, conflictRelPath);
3015
+ await this.downloadFile(remote.id, conflictFullPath);
3016
+ await this.uploadFile(local.fullPath, remoteDir, relPath);
3017
+ const freshRemote = await this.drive.getFile(remote.id);
3018
+ this.updateLedger(relPath, local, freshRemote);
3019
+ }
3020
+ }
3021
+ continue;
3022
+ }
3023
+ if (local && !remote) {
3024
+ if (prev && deleteMissing) {
3025
+ if (!dryRun) {
3026
+ await fs6.promises.unlink(local.fullPath);
3027
+ this.ledger.delete(relPath);
3028
+ }
3029
+ result.deletedLocal.push(relPath);
3030
+ onProgress?.({ action: "delete-local", relPath, details: "Deleted remotely" });
3031
+ } else {
3032
+ if (!dryRun) {
3033
+ const uploadedFile = await this.uploadFile(local.fullPath, remoteDir, relPath);
3034
+ this.updateLedger(relPath, local, uploadedFile);
3035
+ }
3036
+ result.uploaded.push(relPath);
3037
+ onProgress?.({ action: "upload", relPath, details: "New local file" });
3038
+ }
3039
+ continue;
3040
+ }
3041
+ if (!local && remote) {
3042
+ if (prev && deleteMissing) {
3043
+ if (!dryRun) {
3044
+ await this.drive.delete(remote.id, true);
3045
+ this.ledger.delete(relPath);
3046
+ }
3047
+ result.deletedRemote.push(relPath);
3048
+ onProgress?.({ action: "delete-remote", relPath, details: "Deleted locally" });
3049
+ } else {
3050
+ if (!dryRun) {
3051
+ const localDest = path7.join(localDir, relPath);
3052
+ await fs6.promises.mkdir(path7.dirname(localDest), { recursive: true });
3053
+ await this.downloadFile(remote.id, localDest);
3054
+ const stat = await fs6.promises.stat(localDest);
3055
+ this.ledger.set(relPath, {
3056
+ relPath,
3057
+ localMtime: stat.mtimeMs,
3058
+ remoteMtime: remote.mtime,
3059
+ localMd5: remote.md5,
3060
+ remoteMd5: remote.md5,
3061
+ remoteId: remote.id
3062
+ });
3063
+ }
3064
+ result.downloaded.push(relPath);
3065
+ onProgress?.({ action: "download", relPath, details: "New remote file" });
3066
+ }
3067
+ continue;
3068
+ }
3069
+ if (prev && !local && !remote) {
3070
+ this.ledger.delete(relPath);
3071
+ }
3072
+ }
3073
+ result.durationMs = Date.now() - startTime;
3074
+ return result;
3075
+ }
3076
+ async scanLocalDir(dir, baseDir = dir) {
3077
+ const map = /* @__PURE__ */ new Map();
3078
+ if (!fs6.existsSync(dir)) return map;
3079
+ const entries = await fs6.promises.readdir(dir, { withFileTypes: true });
3080
+ for (const entry of entries) {
3081
+ const fullPath = path7.join(dir, entry.name);
3082
+ if (entry.isDirectory()) {
3083
+ const sub = await this.scanLocalDir(fullPath, baseDir);
3084
+ for (const [k, v] of sub) map.set(k, v);
3085
+ } else if (entry.isFile()) {
3086
+ const rel = path7.relative(baseDir, fullPath).replace(/\\/g, "/");
3087
+ const stat = await fs6.promises.stat(fullPath);
3088
+ const md5 = await calculateFileMd5(fullPath);
3089
+ map.set(rel, { fullPath, mtime: stat.mtimeMs, md5 });
3090
+ }
3091
+ }
3092
+ return map;
3093
+ }
3094
+ async scanRemoteDir(folderId, relPrefix) {
3095
+ const map = /* @__PURE__ */ new Map();
3096
+ const items = await this.drive.query().inFolder(folderId).notTrashed().list();
3097
+ for (const item of items) {
3098
+ if (!item.id || !item.name) continue;
3099
+ const cleanName = path7.basename(item.name.replace(/\\/g, "/")).replace(/\0/g, "");
3100
+ if (!cleanName || cleanName === "." || cleanName === "..") continue;
3101
+ const relPath = relPrefix ? `${relPrefix}/${cleanName}` : cleanName;
3102
+ if (item.mimeType === "application/vnd.google-apps.folder") {
3103
+ const sub = await this.scanRemoteDir(item.id, relPath);
3104
+ for (const [k, v] of sub) map.set(k, v);
3105
+ } else {
3106
+ const mtime = item.modifiedTime ? new Date(item.modifiedTime).getTime() : 0;
3107
+ map.set(relPath, {
3108
+ id: item.id,
3109
+ name: item.name,
3110
+ mtime,
3111
+ md5: item.md5Checksum || ""
3112
+ });
3113
+ }
3114
+ }
3115
+ return map;
3116
+ }
3117
+ async uploadFile(localPath, remoteDir, relPath) {
3118
+ const remoteSubDir = path7.dirname(relPath);
3119
+ const targetFolder = remoteSubDir === "." ? remoteDir : `${remoteDir}/${remoteSubDir}`;
3120
+ return await this.drive.upload({
3121
+ source: localPath,
3122
+ name: path7.basename(relPath),
3123
+ parent: targetFolder,
3124
+ overwrite: true
3125
+ });
3126
+ }
3127
+ async downloadFile(fileId, destPath) {
3128
+ await fs6.promises.mkdir(path7.dirname(destPath), { recursive: true });
3129
+ await this.drive.download(fileId, { destination: destPath });
3130
+ }
3131
+ updateLedger(relPath, local, remote) {
3132
+ this.ledger.set(relPath, {
3133
+ relPath,
3134
+ localMtime: local.mtime,
3135
+ remoteMtime: remote.modifiedTime ? new Date(remote.modifiedTime).getTime() : Date.now(),
3136
+ localMd5: local.md5,
3137
+ remoteMd5: remote.md5Checksum || local.md5,
3138
+ remoteId: remote.id
3139
+ });
3140
+ }
3141
+ };
3142
+ }
3143
+ });
3144
+
3145
+ // src/server/s3-gateway.ts
3146
+ import http3 from "http";
3147
+ import path8 from "path";
3148
+ import { parse as parseUrl } from "url";
3149
+ var S3GatewayServer;
3150
+ var init_s3_gateway = __esm({
3151
+ "src/server/s3-gateway.ts"() {
3152
+ "use strict";
3153
+ init_esm_shims();
3154
+ S3GatewayServer = class {
3155
+ drive;
3156
+ options;
3157
+ server = null;
3158
+ constructor(drive2, options = {}) {
3159
+ this.drive = drive2;
3160
+ this.options = {
3161
+ port: options.port || 9e3,
3162
+ host: options.host || "127.0.0.1",
3163
+ bucketRoot: options.bucketRoot || "/",
3164
+ ...options
3165
+ };
3166
+ }
3167
+ /**
3168
+ * Starts the S3 gateway HTTP server
3169
+ */
3170
+ async start() {
3171
+ return new Promise((resolve, reject) => {
3172
+ this.server = http3.createServer(async (req, res) => {
3173
+ try {
3174
+ await this.handleRequest(req, res);
3175
+ } catch (err) {
3176
+ this.sendXmlError(res, 500, "InternalError", err.message || "Internal S3 Gateway Error");
3177
+ }
3178
+ });
3179
+ this.server.on("error", reject);
3180
+ this.server.listen(this.options.port, this.options.host, () => {
3181
+ resolve({ port: this.options.port, host: this.options.host });
3182
+ });
3183
+ });
3184
+ }
3185
+ /**
3186
+ * Stops the S3 gateway HTTP server
3187
+ */
3188
+ async stop() {
3189
+ return new Promise((resolve) => {
3190
+ if (this.server) {
3191
+ this.server.close(() => resolve());
3192
+ } else {
3193
+ resolve();
3194
+ }
3195
+ });
3196
+ }
3197
+ async handleRequest(req, res) {
3198
+ const parsed = parseUrl(req.url || "/", true);
3199
+ const rawPathname = decodeURIComponent(parsed.pathname || "/");
3200
+ const pathname = path8.posix.normalize(rawPathname);
3201
+ if (rawPathname.includes("..") || pathname.includes("..") || pathname === ".") {
3202
+ this.sendXmlError(res, 400, "InvalidURI", "Path traversal characters are not permitted");
3203
+ return;
3204
+ }
3205
+ const method = req.method?.toUpperCase() || "GET";
3206
+ if (this.options.accessKeyId) {
3207
+ const authHeader = req.headers["authorization"];
3208
+ if (!authHeader || !authHeader.includes(this.options.accessKeyId)) {
3209
+ res.setHeader("WWW-Authenticate", "AWS4-HMAC-SHA256");
3210
+ this.sendXmlError(res, 403, "AccessDenied", "Invalid or missing AWS credentials");
3211
+ return;
3212
+ }
3213
+ }
3214
+ const segments = pathname.split("/").filter(Boolean);
3215
+ if (segments.some((s) => s === ".." || s === ".")) {
3216
+ this.sendXmlError(res, 400, "InvalidURI", "Invalid path segment");
3217
+ return;
3218
+ }
3219
+ if (segments.length === 0) {
3220
+ if (method === "GET") {
3221
+ await this.handleListBuckets(res);
3222
+ return;
3223
+ }
3224
+ this.sendXmlError(res, 405, "MethodNotAllowed", "Method not allowed on root");
3225
+ return;
3226
+ }
3227
+ const bucket = segments[0];
3228
+ const key = segments.slice(1).join("/");
3229
+ if (!key) {
3230
+ if (method === "GET") {
3231
+ const prefix = parsed.query.prefix || "";
3232
+ await this.handleListObjects(bucket, prefix, res);
3233
+ return;
3234
+ }
3235
+ if (method === "PUT") {
3236
+ await this.drive.mkdirp(`/${bucket}`);
3237
+ res.statusCode = 200;
3238
+ res.end();
3239
+ return;
3240
+ }
3241
+ this.sendXmlError(res, 405, "MethodNotAllowed", "Method not allowed on bucket");
3242
+ return;
3243
+ }
3244
+ const remotePath = `/${bucket}/${key}`;
3245
+ if (method === "HEAD") {
3246
+ try {
3247
+ const file = await this.drive.getFile(remotePath);
3248
+ res.setHeader("Content-Type", file.mimeType || "application/octet-stream");
3249
+ res.setHeader("Content-Length", file.size || "0");
3250
+ res.setHeader("ETag", `"${file.md5Checksum || file.id}"`);
3251
+ if (file.modifiedTime) res.setHeader("Last-Modified", new Date(file.modifiedTime).toUTCString());
3252
+ res.statusCode = 200;
3253
+ res.end();
3254
+ } catch {
3255
+ this.sendXmlError(res, 404, "NoSuchKey", "The specified key does not exist");
3256
+ }
3257
+ return;
3258
+ }
3259
+ if (method === "GET") {
3260
+ try {
3261
+ const file = await this.drive.getFile(remotePath);
3262
+ const range = req.headers["range"];
3263
+ let options = void 0;
3264
+ if (range && range.startsWith("bytes=")) {
3265
+ const parts = range.replace("bytes=", "").split("-");
3266
+ options = {
3267
+ start: parts[0] ? parseInt(parts[0], 10) : 0,
3268
+ end: parts[1] ? parseInt(parts[1], 10) : void 0
3269
+ };
3270
+ res.statusCode = 206;
3271
+ const end = options.end !== void 0 ? options.end : parseInt(file.size || "0", 10) - 1;
3272
+ res.setHeader("Content-Range", `bytes ${options.start}-${end}/${file.size}`);
3273
+ } else {
3274
+ res.statusCode = 200;
3275
+ }
3276
+ res.setHeader("Content-Type", file.mimeType || "application/octet-stream");
3277
+ res.setHeader("Content-Length", file.size || "0");
3278
+ res.setHeader("ETag", `"${file.md5Checksum || file.id}"`);
3279
+ if (file.modifiedTime) res.setHeader("Last-Modified", new Date(file.modifiedTime).toUTCString());
3280
+ const stream = await this.drive.createReadStream(remotePath, options);
3281
+ stream.pipe(res);
3282
+ } catch {
3283
+ this.sendXmlError(res, 404, "NoSuchKey", "The specified key does not exist");
3284
+ }
3285
+ return;
3286
+ }
3287
+ if (method === "PUT") {
3288
+ const upload = await this.drive.createWriteStream(remotePath);
3289
+ req.pipe(upload);
3290
+ try {
3291
+ const file = await upload.done;
3292
+ res.setHeader("ETag", `"${file.md5Checksum || file.id}"`);
3293
+ res.statusCode = 200;
3294
+ res.end();
3295
+ } catch (err) {
3296
+ this.sendXmlError(res, 500, "InternalError", err.message);
3297
+ }
3298
+ return;
3299
+ }
3300
+ if (method === "DELETE") {
3301
+ try {
3302
+ const file = await this.drive.resolvePath(remotePath);
3303
+ await this.drive.delete(file.id, true);
3304
+ res.statusCode = 204;
3305
+ res.end();
3306
+ } catch {
3307
+ res.statusCode = 204;
3308
+ res.end();
3309
+ }
3310
+ return;
3311
+ }
3312
+ this.sendXmlError(res, 405, "MethodNotAllowed", `HTTP method ${method} not allowed`);
3313
+ }
3314
+ async handleListBuckets(res) {
3315
+ const items = await this.drive.ls("/");
3316
+ const folders = items.filter((i) => i.mimeType === "application/vnd.google-apps.folder");
3317
+ let xml = '<?xml version="1.0" encoding="UTF-8"?>\n<ListAllMyBucketsResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">\n';
3318
+ xml += " <Buckets>\n";
3319
+ for (const f of folders) {
3320
+ xml += " <Bucket>\n";
3321
+ xml += ` <Name>${this.escapeXml(f.name || "bucket")}</Name>
3322
+ `;
3323
+ xml += ` <CreationDate>${f.createdTime || (/* @__PURE__ */ new Date()).toISOString()}</CreationDate>
3324
+ `;
3325
+ xml += " </Bucket>\n";
3326
+ }
3327
+ xml += " </Buckets>\n</ListAllMyBucketsResult>";
3328
+ res.setHeader("Content-Type", "application/xml");
3329
+ res.statusCode = 200;
3330
+ res.end(xml);
3331
+ }
3332
+ async handleListObjects(bucket, prefix, res) {
3333
+ const targetPath = `/${bucket}${prefix ? `/${prefix}` : ""}`;
3334
+ let items = [];
3335
+ try {
3336
+ items = await this.drive.ls(targetPath);
3337
+ } catch {
3338
+ items = [];
3339
+ }
3340
+ let xml = '<?xml version="1.0" encoding="UTF-8"?>\n<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">\n';
3341
+ xml += ` <Name>${this.escapeXml(bucket)}</Name>
3342
+ `;
3343
+ xml += ` <Prefix>${this.escapeXml(prefix)}</Prefix>
3344
+ `;
3345
+ xml += " <IsTruncated>false</IsTruncated>\n";
3346
+ for (const item of items) {
3347
+ if (item.mimeType === "application/vnd.google-apps.folder") continue;
3348
+ const key = prefix ? `${prefix}/${item.name}` : item.name;
3349
+ xml += " <Contents>\n";
3350
+ xml += ` <Key>${this.escapeXml(key)}</Key>
3351
+ `;
3352
+ xml += ` <LastModified>${item.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()}</LastModified>
3353
+ `;
3354
+ xml += ` <ETag>"${item.md5Checksum || item.id}"</ETag>
3355
+ `;
3356
+ xml += ` <Size>${item.size || 0}</Size>
3357
+ `;
3358
+ xml += " <StorageClass>STANDARD</StorageClass>\n";
3359
+ xml += " </Contents>\n";
3360
+ }
3361
+ xml += "</ListBucketResult>";
3362
+ res.setHeader("Content-Type", "application/xml");
3363
+ res.statusCode = 200;
3364
+ res.end(xml);
3365
+ }
3366
+ sendXmlError(res, status, code, message) {
3367
+ const xml = `<?xml version="1.0" encoding="UTF-8"?>
3368
+ <Error>
3369
+ <Code>${this.escapeXml(code)}</Code>
3370
+ <Message>${this.escapeXml(message)}</Message>
3371
+ </Error>`;
3372
+ res.setHeader("Content-Type", "application/xml");
3373
+ res.statusCode = status;
3374
+ res.end(xml);
3375
+ }
3376
+ escapeXml(unsafe) {
3377
+ return unsafe.replace(/[<>&'"]/g, (c) => {
3378
+ switch (c) {
3379
+ case "<":
3380
+ return "&lt;";
3381
+ case ">":
3382
+ return "&gt;";
3383
+ case "&":
3384
+ return "&amp;";
3385
+ case "'":
3386
+ return "&apos;";
3387
+ case '"':
3388
+ return "&quot;";
3389
+ default:
3390
+ return c;
3391
+ }
3392
+ });
3393
+ }
3394
+ };
3395
+ }
3396
+ });
3397
+
3398
+ // src/core/security-auditor.ts
3399
+ var SecurityAuditor;
3400
+ var init_security_auditor = __esm({
3401
+ "src/core/security-auditor.ts"() {
3402
+ "use strict";
3403
+ init_esm_shims();
3404
+ init_retry();
3405
+ SecurityAuditor = class {
3406
+ drive;
3407
+ constructor(drive2) {
3408
+ this.drive = drive2;
3409
+ }
3410
+ /**
3411
+ * Scans Google Drive files and audits their permission grants
3412
+ */
3413
+ async audit(options = {}) {
3414
+ const limit = options.scanLimit || 500;
3415
+ const allowedDomains = new Set((options.allowedDomains || []).map((d) => d.toLowerCase()));
3416
+ const issues = [];
3417
+ let publicCount = 0;
3418
+ let domainCount = 0;
3419
+ let externalCount = 0;
3420
+ let scannedTotal = 0;
3421
+ let pageToken = void 0;
3422
+ do {
3423
+ const res = await withRetry(async () => {
3424
+ return await this.drive.files.list({
3425
+ q: "trashed = false",
3426
+ fields: "nextPageToken, files(id, name, mimeType, webViewLink, shared, permissions(id, type, role, emailAddress, domain))",
3427
+ pageSize: Math.min(100, limit - scannedTotal),
3428
+ supportsAllDrives: true,
3429
+ includeItemsFromAllDrives: true,
3430
+ pageToken
3431
+ });
3432
+ });
3433
+ const files = res.data.files || [];
3434
+ for (const file of files) {
3435
+ if (!file.id || !file.name) continue;
3436
+ scannedTotal++;
3437
+ const perms = file.permissions || [];
3438
+ for (const p of perms) {
3439
+ if (p.type === "anyone") {
3440
+ publicCount++;
3441
+ const isCritical = ["writer", "owner", "organizer", "fileOrganizer"].includes(p.role || "");
3442
+ issues.push({
3443
+ fileId: file.id,
3444
+ fileName: file.name,
3445
+ risk: isCritical ? "CRITICAL" : "HIGH",
3446
+ reason: `Publicly accessible to anyone (${p.role} access)`,
3447
+ permissionId: p.id,
3448
+ type: p.type,
3449
+ role: p.role || "reader",
3450
+ webViewLink: file.webViewLink || void 0
3451
+ });
3452
+ continue;
3453
+ }
3454
+ if (p.type === "domain") {
3455
+ domainCount++;
3456
+ issues.push({
3457
+ fileId: file.id,
3458
+ fileName: file.name,
3459
+ risk: "MEDIUM",
3460
+ reason: `Shared with entire organization domain (${p.domain})`,
3461
+ permissionId: p.id,
3462
+ type: p.type,
3463
+ role: p.role || "reader",
3464
+ domain: p.domain || void 0,
3465
+ webViewLink: file.webViewLink || void 0
3466
+ });
3467
+ continue;
3468
+ }
3469
+ if (p.type === "user" && p.emailAddress && allowedDomains.size > 0) {
3470
+ const userDomain = p.emailAddress.split("@")[1]?.toLowerCase();
3471
+ if (userDomain && !allowedDomains.has(userDomain)) {
3472
+ externalCount++;
3473
+ issues.push({
3474
+ fileId: file.id,
3475
+ fileName: file.name,
3476
+ risk: "HIGH",
3477
+ reason: `Shared with external user outside allowed domains: ${p.emailAddress}`,
3478
+ permissionId: p.id,
3479
+ type: p.type,
3480
+ role: p.role || "reader",
3481
+ emailAddress: p.emailAddress,
3482
+ webViewLink: file.webViewLink || void 0
3483
+ });
3484
+ }
3485
+ }
3486
+ }
3487
+ }
3488
+ pageToken = res.data.nextPageToken || void 0;
3489
+ } while (pageToken && scannedTotal < limit);
3490
+ return {
3491
+ totalScanned: scannedTotal,
3492
+ publicFilesCount: publicCount,
3493
+ domainSharedCount: domainCount,
3494
+ externalSharesCount: externalCount,
3495
+ issues,
3496
+ scannedAt: (/* @__PURE__ */ new Date()).toISOString()
3497
+ };
3498
+ }
3499
+ /**
3500
+ * Revokes public 'anyone' permissions on specified files
3501
+ */
3502
+ async revokePublicAccess(fileIds) {
3503
+ const revoked = [];
3504
+ const errors = [];
3505
+ for (const fileId of fileIds) {
3506
+ try {
3507
+ const fileRes = await withRetry(async () => {
3508
+ return await this.drive.files.get({
3509
+ fileId,
3510
+ fields: "id, permissions(id, type)",
3511
+ supportsAllDrives: true
3512
+ });
3513
+ });
3514
+ const publicPerms = (fileRes.data.permissions || []).filter((p) => p.type === "anyone");
3515
+ for (const p of publicPerms) {
3516
+ if (p.id) {
3517
+ await withRetry(async () => {
3518
+ return await this.drive.permissions.delete({
3519
+ fileId,
3520
+ permissionId: p.id,
3521
+ supportsAllDrives: true
3522
+ });
3523
+ });
3524
+ }
3525
+ }
3526
+ revoked.push(fileId);
3527
+ } catch (err) {
3528
+ errors.push({ fileId, error: err.message });
3529
+ }
3530
+ }
3531
+ return { revoked, errors };
3532
+ }
3533
+ };
3534
+ }
3535
+ });
3536
+
3537
+ // src/core/semantic-search.ts
3538
+ function levenshtein(a, b) {
3539
+ const an = a.length;
3540
+ const bn = b.length;
3541
+ if (an === 0) return bn;
3542
+ if (bn === 0) return an;
3543
+ const matrix = Array.from({ length: bn + 1 }, (_, i) => [i]);
3544
+ for (let j = 0; j <= an; j++) matrix[0][j] = j;
3545
+ for (let i = 1; i <= bn; i++) {
3546
+ for (let j = 1; j <= an; j++) {
3547
+ if (b.charAt(i - 1) === a.charAt(j - 1)) {
3548
+ matrix[i][j] = matrix[i - 1][j - 1];
3549
+ } else {
3550
+ matrix[i][j] = Math.min(
3551
+ matrix[i - 1][j - 1] + 1,
3552
+ // substitution
3553
+ matrix[i][j - 1] + 1,
3554
+ // insertion
3555
+ matrix[i - 1][j] + 1
3556
+ // deletion
3557
+ );
3558
+ }
3559
+ }
3560
+ }
3561
+ return matrix[bn][an];
3562
+ }
3563
+ function cosineSimilarity(vecA, vecB) {
3564
+ if (vecA.length !== vecB.length || vecA.length === 0) return 0;
3565
+ let dot = 0;
3566
+ let normA = 0;
3567
+ let normB = 0;
3568
+ for (let i = 0; i < vecA.length; i++) {
3569
+ dot += vecA[i] * vecB[i];
3570
+ normA += vecA[i] * vecA[i];
3571
+ normB += vecB[i] * vecB[i];
3572
+ }
3573
+ if (normA === 0 || normB === 0) return 0;
3574
+ return dot / (Math.sqrt(normA) * Math.sqrt(normB));
3575
+ }
3576
+ var SmartSearchEngine;
3577
+ var init_semantic_search = __esm({
3578
+ "src/core/semantic-search.ts"() {
3579
+ "use strict";
3580
+ init_esm_shims();
3581
+ SmartSearchEngine = class {
3582
+ drive;
3583
+ constructor(drive2) {
3584
+ this.drive = drive2;
3585
+ }
3586
+ /**
3587
+ * Searches Drive using tokenized fuzzy matching and optional semantic embeddings
3588
+ */
3589
+ async search(query, options = {}) {
3590
+ const limit = options.limit || 20;
3591
+ const minScore = options.minScore ?? 0.3;
3592
+ const queryTokens = query.toLowerCase().split(/\s+/).filter(Boolean);
3593
+ if (queryTokens.length === 0) return [];
3594
+ let candidates = [];
3595
+ if (options.parent) {
3596
+ candidates = await this.drive.ls(options.parent);
3597
+ } else {
3598
+ candidates = await this.drive.query().notTrashed().pageSize(100).list();
3599
+ }
3600
+ let queryVector = null;
3601
+ if (options.embedder) {
3602
+ try {
3603
+ queryVector = await options.embedder(query);
3604
+ } catch {
3605
+ queryVector = null;
3606
+ }
3607
+ }
3608
+ const scored = [];
3609
+ for (const file of candidates) {
3610
+ const fileName = (file.name || "").toLowerCase();
3611
+ const desc = (file.description || "").toLowerCase();
3612
+ const matchedOn = [];
3613
+ let nameScore = 0;
3614
+ let descScore = 0;
3615
+ let semanticScore = 0;
3616
+ if (fileName.includes(query.toLowerCase())) {
3617
+ nameScore = 0.95;
3618
+ matchedOn.push("name");
3619
+ } else {
3620
+ let tokensMatched = 0;
3621
+ for (const token of queryTokens) {
3622
+ if (fileName.includes(token)) {
3623
+ tokensMatched += 1;
3624
+ continue;
3625
+ }
3626
+ const words = fileName.split(/[\s._-]+/);
3627
+ for (const word of words) {
3628
+ const dist = levenshtein(token, word);
3629
+ const maxLen = Math.max(token.length, word.length);
3630
+ if (maxLen > 3 && dist <= 2) {
3631
+ tokensMatched += 1 - dist / maxLen;
3632
+ break;
3633
+ }
3634
+ }
3635
+ }
3636
+ nameScore = tokensMatched / queryTokens.length;
3637
+ if (nameScore > 0.4) matchedOn.push("name");
3638
+ }
3639
+ if (desc) {
3640
+ if (desc.includes(query.toLowerCase())) {
3641
+ descScore = 0.8;
3642
+ matchedOn.push("description");
3643
+ }
3644
+ }
3645
+ if (queryVector && options.embedder) {
3646
+ try {
3647
+ const fileVector = await options.embedder(`${file.name} ${file.description || ""}`);
3648
+ semanticScore = cosineSimilarity(queryVector, fileVector);
3649
+ if (semanticScore > 0.6) matchedOn.push("semantic");
3650
+ } catch {
3651
+ }
3652
+ }
3653
+ const totalScore = Math.min(1, nameScore * 0.7 + descScore * 0.15 + semanticScore * 0.15);
3654
+ if (totalScore >= minScore) {
3655
+ scored.push({
3656
+ file,
3657
+ score: Math.round(totalScore * 100) / 100,
3658
+ matchedOn: matchedOn.length > 0 ? matchedOn : ["name"]
3659
+ });
3660
+ }
3661
+ }
3662
+ scored.sort((a, b) => b.score - a.score);
3663
+ return scored.slice(0, limit);
3664
+ }
3665
+ };
3666
+ }
3667
+ });
3668
+
3669
+ // src/utils/compression.ts
3670
+ import zlib from "zlib";
3671
+ import { promisify } from "util";
3672
+ async function compressBuffer(buffer, algorithm = "gzip") {
3673
+ switch (algorithm) {
3674
+ case "brotli":
3675
+ return await brotliCompressAsync(buffer);
3676
+ case "deflate":
3677
+ return await promisify(zlib.deflate)(buffer);
3678
+ case "gzip":
3679
+ default:
3680
+ return await gzipAsync(buffer);
3681
+ }
3682
+ }
3683
+ async function decompressBuffer(buffer, algorithm = "gzip") {
3684
+ switch (algorithm) {
3685
+ case "brotli":
3686
+ return await brotliDecompressAsync(buffer);
3687
+ case "deflate":
3688
+ return await promisify(zlib.inflate)(buffer);
3689
+ case "gzip":
3690
+ default:
3691
+ return await gunzipAsync(buffer);
3692
+ }
3693
+ }
3694
+ var gzipAsync, gunzipAsync, brotliCompressAsync, brotliDecompressAsync;
3695
+ var init_compression = __esm({
3696
+ "src/utils/compression.ts"() {
3697
+ "use strict";
3698
+ init_esm_shims();
3699
+ gzipAsync = promisify(zlib.gzip);
3700
+ gunzipAsync = promisify(zlib.gunzip);
3701
+ brotliCompressAsync = promisify(zlib.brotliCompress);
3702
+ brotliDecompressAsync = promisify(zlib.brotliDecompress);
3703
+ }
3704
+ });
3705
+
3706
+ // src/server/webdav.ts
3707
+ var webdav_exports = {};
3708
+ __export(webdav_exports, {
3709
+ escapeXml: () => escapeXml,
3710
+ startWebDAVServer: () => startWebDAVServer
3711
+ });
3712
+ import http4 from "http";
3713
+ import url from "url";
3714
+ import path9 from "path";
3715
+ function escapeXml(unsafe) {
3716
+ return unsafe.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
3717
+ }
3718
+ async function startWebDAVServer(drive2, options = {}) {
3719
+ const port = options.port || 8080;
3720
+ const host = options.host || "127.0.0.1";
3721
+ await drive2.init();
3722
+ const server = http4.createServer(async (req, res) => {
3723
+ try {
3724
+ if (options.auth?.username && options.auth?.password) {
3725
+ const authHeader = req.headers["authorization"];
3726
+ if (!authHeader || !authHeader.startsWith("Basic ")) {
3727
+ res.writeHead(401, {
3728
+ "WWW-Authenticate": 'Basic realm="DriveKit WebDAV"',
3729
+ "Content-Type": "text/plain"
3730
+ });
3731
+ res.end("Authentication required");
3732
+ return;
3733
+ }
3734
+ const credentials = Buffer.from(authHeader.replace("Basic ", ""), "base64").toString("utf8");
3735
+ const [user, pass] = credentials.split(":");
3736
+ if (user !== options.auth.username || pass !== options.auth.password) {
3737
+ res.writeHead(401, {
3738
+ "WWW-Authenticate": 'Basic realm="DriveKit WebDAV"',
3739
+ "Content-Type": "text/plain"
3740
+ });
3741
+ res.end("Invalid credentials");
3742
+ return;
3743
+ }
3744
+ }
3745
+ const parsedUrl = url.parse(req.url || "/", true);
3746
+ const decodedPath = decodeURIComponent(parsedUrl.pathname || "/");
3747
+ const normalizedPath = path9.posix.normalize(decodedPath);
3748
+ const virtualPath = normalizedPath.startsWith("/") ? normalizedPath : `/${normalizedPath}`;
3749
+ const baseName = path9.basename(virtualPath);
3750
+ if (baseName.startsWith("._") || baseName === ".DS_Store" || baseName === ".Trashes" || baseName === ".Spotlight-V100" || baseName === ".fseventsd") {
3751
+ res.writeHead(404, { "Content-Type": "text/plain" });
3752
+ res.end("Not Found");
3753
+ return;
3754
+ }
3755
+ switch (req.method) {
3756
+ case "OPTIONS": {
3757
+ res.writeHead(200, {
3758
+ DAV: "1, 2",
3759
+ Allow: "OPTIONS, GET, HEAD, POST, PUT, DELETE, MKCOL, MOVE, COPY, PROPFIND",
3760
+ "MS-Author-Via": "DAV",
3761
+ "Accept-Ranges": "bytes"
3762
+ });
3763
+ res.end();
3764
+ return;
3765
+ }
3766
+ case "PROPFIND": {
3767
+ const depth = req.headers["depth"] || "1";
3768
+ const xml = await handlePropfind(drive2, virtualPath, depth);
3769
+ if (xml === null) {
3770
+ res.writeHead(404, { "Content-Type": "text/plain" });
3771
+ res.end("Not Found");
3772
+ return;
3773
+ }
3774
+ res.writeHead(207, {
3775
+ "Content-Type": "application/xml; charset=utf-8"
3776
+ });
3777
+ res.end(xml);
3778
+ return;
3779
+ }
3780
+ case "GET":
3781
+ case "HEAD": {
3782
+ if (virtualPath === "/" || virtualPath === "") {
3783
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
3784
+ res.end("<h1>DriveKit WebDAV Server Running</h1><p>Connect via Finder, File Explorer, or WebDAV client.</p>");
3785
+ return;
3786
+ }
3787
+ try {
3788
+ const file = await drive2.getFile(virtualPath);
3789
+ if (file.mimeType === "application/vnd.google-apps.folder") {
3790
+ res.writeHead(405, { "Content-Type": "text/plain" });
3791
+ res.end("Cannot GET a directory");
3792
+ return;
3793
+ }
3794
+ const fileSize = file.size ? parseInt(file.size, 10) : void 0;
3795
+ const rangeHeader = req.headers["range"];
3796
+ if (rangeHeader && rangeHeader.startsWith("bytes=") && fileSize !== void 0) {
3797
+ const parts = rangeHeader.replace("bytes=", "").split("-");
3798
+ const start = parseInt(parts[0], 10);
3799
+ const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
3800
+ if (isNaN(start) || start >= fileSize || end !== void 0 && end >= fileSize) {
3801
+ res.writeHead(416, { "Content-Range": `bytes */${fileSize}` });
3802
+ res.end();
3803
+ return;
3804
+ }
3805
+ const stream = await drive2.createReadStream(virtualPath, { start, end });
3806
+ const chunkLength = end - start + 1;
3807
+ res.writeHead(206, {
3808
+ "Content-Type": file.mimeType || "application/octet-stream",
3809
+ "Content-Range": `bytes ${start}-${end}/${fileSize}`,
3810
+ "Content-Length": chunkLength,
3811
+ "Accept-Ranges": "bytes"
3812
+ });
3813
+ if (req.method === "HEAD") {
3814
+ res.end();
3815
+ } else {
3816
+ stream.pipe(res);
3817
+ }
3818
+ } else {
3819
+ const stream = await drive2.createReadStream(virtualPath);
3820
+ res.writeHead(200, {
3821
+ "Content-Type": file.mimeType || "application/octet-stream",
3822
+ "Content-Length": file.size || void 0,
3823
+ "Accept-Ranges": "bytes"
3824
+ });
3825
+ if (req.method === "HEAD") {
3826
+ res.end();
3827
+ } else {
3828
+ stream.pipe(res);
3829
+ }
3830
+ }
3831
+ } catch (e) {
3832
+ res.writeHead(404, { "Content-Type": "text/plain" });
3833
+ res.end("File Not Found");
3834
+ }
3835
+ return;
3836
+ }
3837
+ case "PUT": {
3838
+ const remoteDir = path9.dirname(virtualPath);
3839
+ await drive2.mkdirp(remoteDir);
3840
+ let existed = false;
3841
+ try {
3842
+ const existingFile = await drive2.getFile(virtualPath);
3843
+ if (existingFile && existingFile.id) {
3844
+ existed = true;
3845
+ }
3846
+ } catch {
3847
+ existed = false;
3848
+ }
3849
+ try {
3850
+ const uploadStream = await drive2.createWriteStream(virtualPath, {
3851
+ overwrite: true
3852
+ });
3853
+ req.pipe(uploadStream);
3854
+ await uploadStream.done;
2493
3855
  res.writeHead(existed ? 204 : 201, { "Content-Type": "text/plain" });
2494
3856
  res.end(existed ? "" : "Created");
2495
3857
  } catch (err) {
@@ -2536,14 +3898,14 @@ async function startWebDAVServer(drive2, options = {}) {
2536
3898
  }
2537
3899
  const destUrl = url.parse(destination);
2538
3900
  const destPath = decodeURIComponent(destUrl.pathname || "");
2539
- const newName = path7.basename(destPath);
2540
- const newParentDir = path7.dirname(destPath);
3901
+ const newName = path9.basename(destPath);
3902
+ const newParentDir = path9.dirname(destPath);
2541
3903
  const newParentFolderId = await drive2.mkdirp(newParentDir);
2542
- const currentParentDir = path7.dirname(virtualPath);
3904
+ const currentParentDir = path9.dirname(virtualPath);
2543
3905
  if (newParentDir !== currentParentDir) {
2544
3906
  await drive2.move(file.id, newParentFolderId);
2545
3907
  }
2546
- if (newName !== path7.basename(virtualPath)) {
3908
+ if (newName !== path9.basename(virtualPath)) {
2547
3909
  await drive2.rename(file.id, newName);
2548
3910
  }
2549
3911
  res.writeHead(201);
@@ -2570,8 +3932,8 @@ async function startWebDAVServer(drive2, options = {}) {
2570
3932
  }
2571
3933
  const destUrl = url.parse(destination);
2572
3934
  const destPath = decodeURIComponent(destUrl.pathname || "");
2573
- const newName = path7.basename(destPath);
2574
- const newParentDir = path7.dirname(destPath);
3935
+ const newName = path9.basename(destPath);
3936
+ const newParentDir = path9.dirname(destPath);
2575
3937
  const newParentFolderId = await drive2.mkdirp(newParentDir);
2576
3938
  await drive2.copy(file.id, { parent: newParentFolderId, name: newName });
2577
3939
  res.writeHead(201);
@@ -2619,25 +3981,38 @@ async function handlePropfind(drive2, virtualPath, depth) {
2619
3981
  virtualPath,
2620
3982
  isFolder,
2621
3983
  selfItem.size ? parseInt(selfItem.size, 10) : 0,
2622
- selfItem.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
3984
+ selfItem.modifiedTime || (/* @__PURE__ */ new Date()).toISOString(),
3985
+ selfItem.mimeType || void 0
2623
3986
  )
2624
3987
  );
2625
3988
  } catch {
2626
- return `<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:"></D:multistatus>`;
3989
+ return null;
2627
3990
  }
2628
3991
  }
2629
3992
  if (isFolder && depth !== "0") {
2630
3993
  try {
2631
3994
  const children = await drive2.ls(virtualPath);
3995
+ const seenNames = /* @__PURE__ */ new Map();
2632
3996
  for (const child of children) {
3997
+ let childName = child.name || "untitled";
3998
+ if (seenNames.has(childName)) {
3999
+ const count = seenNames.get(childName) + 1;
4000
+ seenNames.set(childName, count);
4001
+ const ext = path9.extname(childName);
4002
+ const base = path9.basename(childName, ext);
4003
+ childName = `${base} (${count})${ext}`;
4004
+ } else {
4005
+ seenNames.set(childName, 0);
4006
+ }
2633
4007
  const childIsFolder = child.mimeType === "application/vnd.google-apps.folder";
2634
- const childPath = virtualPath === "/" ? `/${child.name}` : `${virtualPath}/${child.name}`;
4008
+ const childPath = virtualPath === "/" ? `/${childName}` : `${virtualPath}/${childName}`;
2635
4009
  responses.push(
2636
4010
  renderWebDAVResponse(
2637
4011
  childPath,
2638
4012
  childIsFolder,
2639
4013
  child.size ? parseInt(child.size, 10) : 0,
2640
- child.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
4014
+ child.modifiedTime || (/* @__PURE__ */ new Date()).toISOString(),
4015
+ child.mimeType || void 0
2641
4016
  )
2642
4017
  );
2643
4018
  }
@@ -2649,11 +4024,17 @@ async function handlePropfind(drive2, virtualPath, depth) {
2649
4024
  ${responses.join("\n")}
2650
4025
  </D:multistatus>`;
2651
4026
  }
2652
- function renderWebDAVResponse(href, isDir, size, modifiedTime) {
2653
- const encodedHref = encodeURI(href);
2654
- const displayName = escapeXml(path7.basename(href) || "root");
4027
+ function renderWebDAVResponse(href, isDir, size, modifiedTime, mimeType) {
4028
+ let cleanHref = href;
4029
+ if (isDir && !cleanHref.endsWith("/")) {
4030
+ cleanHref += "/";
4031
+ }
4032
+ const encodedHref = encodeURI(cleanHref);
4033
+ const displayName = escapeXml(path9.basename(href) || "root");
2655
4034
  const resourceType = isDir ? "<D:collection/>" : "";
2656
4035
  const dateFormatted = new Date(modifiedTime).toUTCString();
4036
+ const contentTypeTag = !isDir && mimeType ? `
4037
+ <D:getcontenttype>${escapeXml(mimeType)}</D:getcontenttype>` : "";
2657
4038
  return ` <D:response>
2658
4039
  <D:href>${encodedHref}</D:href>
2659
4040
  <D:propstat>
@@ -2661,8 +4042,7 @@ function renderWebDAVResponse(href, isDir, size, modifiedTime) {
2661
4042
  <D:displayname>${displayName}</D:displayname>
2662
4043
  <D:resourcetype>${resourceType}</D:resourcetype>
2663
4044
  <D:getcontentlength>${isDir ? "0" : size}</D:getcontentlength>
2664
- <D:getlastmodified>${dateFormatted}</D:getlastmodified>
2665
- <D:status>HTTP/1.1 200 OK</D:status>
4045
+ <D:getlastmodified>${dateFormatted}</D:getlastmodified>${contentTypeTag}
2666
4046
  </D:prop>
2667
4047
  <D:status>HTTP/1.1 200 OK</D:status>
2668
4048
  </D:propstat>
@@ -2680,8 +4060,9 @@ var client_exports = {};
2680
4060
  __export(client_exports, {
2681
4061
  DriveKit: () => DriveKit
2682
4062
  });
2683
- import fs6 from "fs";
2684
- import path8 from "path";
4063
+ import fs7 from "fs";
4064
+ import path10 from "path";
4065
+ import crypto3 from "crypto";
2685
4066
  import { drive } from "@googleapis/drive";
2686
4067
  var DriveKit;
2687
4068
  var init_client = __esm({
@@ -2704,6 +4085,14 @@ var init_client = __esm({
2704
4085
  init_format();
2705
4086
  init_mime();
2706
4087
  init_cache();
4088
+ init_http_agent();
4089
+ init_encryption();
4090
+ init_revisions();
4091
+ init_bidirectional_sync();
4092
+ init_s3_gateway();
4093
+ init_security_auditor();
4094
+ init_semantic_search();
4095
+ init_compression();
2707
4096
  DriveKit = class _DriveKit {
2708
4097
  options;
2709
4098
  authenticator;
@@ -2712,12 +4101,34 @@ var init_client = __esm({
2712
4101
  uploaderInstance = null;
2713
4102
  downloaderInstance = null;
2714
4103
  metadataCacheInstance = null;
4104
+ cryptoInstance = null;
2715
4105
  rootFolderId;
2716
4106
  pluginManager = new PluginManager();
2717
4107
  constructor(options = {}) {
2718
4108
  this.options = options;
2719
4109
  this.rootFolderId = options.rootFolderId || "root";
2720
4110
  this.authenticator = new DriveAuthenticator(options.auth);
4111
+ if (options.encryption) {
4112
+ this.cryptoInstance = new DriveKitCrypto(options.encryption);
4113
+ }
4114
+ }
4115
+ /**
4116
+ * Access the client-side AES-256-GCM encryption engine
4117
+ */
4118
+ get crypto() {
4119
+ if (!this.cryptoInstance) {
4120
+ throw new Error("Encryption is not configured on this DriveKit instance. Pass { encryption: { password: ... } } in options.");
4121
+ }
4122
+ return this.cryptoInstance;
4123
+ }
4124
+ /**
4125
+ * Access historical revisions & version control for a file
4126
+ */
4127
+ getRevisions(fileIdOrPath) {
4128
+ if (!this.driveClient) {
4129
+ throw new Error("DriveKit is not initialized. Call await drive.init() first.");
4130
+ }
4131
+ return new DriveFileRevisions(this.driveClient, fileIdOrPath, (p) => this.resolveId(p));
2721
4132
  }
2722
4133
  /**
2723
4134
  * Registers a middleware plugin into DriveKit lifecycle
@@ -2726,6 +4137,18 @@ var init_client = __esm({
2726
4137
  this.pluginManager.use(plugin);
2727
4138
  return this;
2728
4139
  }
4140
+ /**
4141
+ * Unregisters a middleware plugin by name
4142
+ */
4143
+ unuse(pluginName) {
4144
+ return this.pluginManager.unuse(pluginName);
4145
+ }
4146
+ /**
4147
+ * Access the underlying plugin manager instance
4148
+ */
4149
+ get plugins() {
4150
+ return this.pluginManager;
4151
+ }
2729
4152
  /**
2730
4153
  * Returns a fluent, chained reference to a specific file
2731
4154
  */
@@ -2744,7 +4167,8 @@ var init_client = __esm({
2744
4167
  async init() {
2745
4168
  if (!this.driveClient) {
2746
4169
  const auth = await this.authenticator.getAuthClient();
2747
- this.driveClient = drive({ version: "v3", auth });
4170
+ const agent = getOptimizedHttpsAgent();
4171
+ this.driveClient = drive({ version: "v3", auth, agent });
2748
4172
  if (this.options.enablePersistentCache !== false) {
2749
4173
  this.metadataCacheInstance = new SqliteMetadataCache(this.options.cacheDatabasePath);
2750
4174
  this.metadataCacheInstance.init();
@@ -2831,15 +4255,41 @@ var init_client = __esm({
2831
4255
  }
2832
4256
  }
2833
4257
  /**
2834
- * Lists contents of a folder (by folder ID or path)
4258
+ * Lists contents of a folder (by folder ID or path) with opportunistic tree caching
2835
4259
  */
2836
4260
  async ls(folderIdOrPath = "/") {
4261
+ let parentFolderId;
4262
+ let normalizedPath = null;
4263
+ let files;
2837
4264
  if (folderIdOrPath === "/" || folderIdOrPath === "root" || folderIdOrPath === this.rootFolderId) {
4265
+ parentFolderId = this.rootFolderId;
4266
+ normalizedPath = "/";
2838
4267
  const parentFilter = this.rootFolderId === "root" ? "'root' in parents or sharedWithMe = true" : `'${this.rootFolderId}' in parents`;
2839
- return await this.query().raw(parentFilter).notTrashed().orderBy("folder,name").list();
4268
+ files = await this.query().raw(parentFilter).notTrashed().orderBy("folder,name").list();
4269
+ } else {
4270
+ if (folderIdOrPath.startsWith("/")) {
4271
+ normalizedPath = folderIdOrPath.replace(/\/+$/, "") || "/";
4272
+ parentFolderId = await this.resolveId(normalizedPath);
4273
+ } else {
4274
+ parentFolderId = folderIdOrPath;
4275
+ }
4276
+ files = await this.query().inFolder(parentFolderId).notTrashed().orderBy("folder,name").list();
4277
+ }
4278
+ if (this.metadataCacheInstance && files.length > 0) {
4279
+ const cacheEntries = files.filter((f) => !!f.id).map((f) => ({
4280
+ id: f.id,
4281
+ name: f.name || "untitled",
4282
+ mimeType: f.mimeType || "",
4283
+ size: f.size ? parseInt(f.size, 10) : void 0,
4284
+ parentId: parentFolderId,
4285
+ path: normalizedPath ? `${normalizedPath === "/" ? "" : normalizedPath}/${f.name}` : void 0,
4286
+ md5Checksum: f.md5Checksum || void 0,
4287
+ modifiedTime: f.modifiedTime || void 0,
4288
+ trashed: false
4289
+ }));
4290
+ this.metadataCacheInstance.upsertFiles(cacheEntries);
2840
4291
  }
2841
- const folderId = await this.resolveId(folderIdOrPath);
2842
- return await this.query().inFolder(folderId).notTrashed().orderBy("folder,name").list();
4292
+ return files;
2843
4293
  }
2844
4294
  // ==========================================
2845
4295
  // FILE OPERATIONS (UPLOAD, DOWNLOAD, GET)
@@ -2858,68 +4308,101 @@ var init_client = __esm({
2858
4308
  if (parentId && parentId.startsWith("/")) {
2859
4309
  parentId = await this.mkdirp(parentId);
2860
4310
  }
2861
- const targetName = opts.name || opts.filename;
2862
- if (opts.overwrite && targetName && parentId) {
4311
+ let uploadOpts = { ...opts };
4312
+ if (uploadOpts.compress) {
4313
+ const algo = typeof uploadOpts.compress === "string" ? uploadOpts.compress : "gzip";
4314
+ if (typeof uploadOpts.source === "string" && fs7.existsSync(uploadOpts.source)) {
4315
+ const plainBuf = await fs7.promises.readFile(uploadOpts.source);
4316
+ uploadOpts.source = await compressBuffer(plainBuf, algo);
4317
+ } else if (Buffer.isBuffer(uploadOpts.source)) {
4318
+ uploadOpts.source = await compressBuffer(uploadOpts.source, algo);
4319
+ }
4320
+ uploadOpts.appProperties = { ...uploadOpts.appProperties, drivekit_compressed: algo };
4321
+ }
4322
+ if ((uploadOpts.encrypt || this.options.encryption) && this.cryptoInstance) {
4323
+ const origName = uploadOpts.name || uploadOpts.filename || (typeof uploadOpts.source === "string" ? path10.basename(uploadOpts.source) : "encrypted.bin");
4324
+ if (typeof uploadOpts.source === "string" && fs7.existsSync(uploadOpts.source)) {
4325
+ const plainBuf = await fs7.promises.readFile(uploadOpts.source);
4326
+ uploadOpts.source = this.cryptoInstance.encryptBuffer(plainBuf);
4327
+ } else if (Buffer.isBuffer(uploadOpts.source)) {
4328
+ uploadOpts.source = this.cryptoInstance.encryptBuffer(uploadOpts.source);
4329
+ }
4330
+ if (this.options.encryption?.encryptFilenames) {
4331
+ uploadOpts.name = this.cryptoInstance.encryptFilename(origName);
4332
+ }
4333
+ uploadOpts.appProperties = { ...uploadOpts.appProperties, drivekit_encrypted: "true" };
4334
+ }
4335
+ const targetName = uploadOpts.name || uploadOpts.filename || (typeof uploadOpts.source === "string" ? path10.basename(uploadOpts.source) : void 0);
4336
+ if (uploadOpts.overwrite && targetName && parentId) {
2863
4337
  const existing = await this.query().inFolder(parentId).nameEquals(targetName).notTrashed().first();
2864
4338
  if (existing?.id) {
2865
4339
  await this.delete(existing.id, true);
2866
4340
  }
2867
4341
  }
2868
- if (opts.deduplicate && typeof opts.source === "string" && fs6.existsSync(opts.source)) {
2869
- const localMd5 = await calculateFileMd5(opts.source);
2870
- let existingId;
2871
- if (this.metadataCacheInstance) {
2872
- const cached = this.metadataCacheInstance.findByMd5(localMd5);
2873
- if (cached) existingId = cached.id;
4342
+ if (uploadOpts.deduplicate) {
4343
+ let localMd5;
4344
+ if (typeof uploadOpts.source === "string" && fs7.existsSync(uploadOpts.source)) {
4345
+ localMd5 = await calculateFileMd5(uploadOpts.source);
4346
+ } else if (Buffer.isBuffer(uploadOpts.source)) {
4347
+ localMd5 = crypto3.createHash("md5").update(uploadOpts.source).digest("hex");
2874
4348
  }
2875
- if (!existingId) {
2876
- const found = await this.query().md5(localMd5).notTrashed().first();
2877
- if (found?.id) {
2878
- existingId = found.id;
4349
+ if (localMd5) {
4350
+ let existingId;
4351
+ if (this.metadataCacheInstance) {
4352
+ const cached = this.metadataCacheInstance.findByMd5(localMd5);
4353
+ if (cached) existingId = cached.id;
2879
4354
  }
2880
- }
2881
- if (existingId) {
2882
- const fileName = targetName || path8.basename(opts.source);
2883
- const raw = await this.getRawClient();
2884
- const copyRes = await withRetry(async () => {
2885
- return await raw.files.copy({
2886
- fileId: existingId,
2887
- requestBody: {
2888
- name: fileName,
2889
- parents: parentId ? [parentId] : void 0,
2890
- description: opts.description
2891
- },
2892
- fields: "id, name, mimeType, size, modifiedTime, md5Checksum",
2893
- supportsAllDrives: true
2894
- });
2895
- });
2896
- const file = copyRes.data;
2897
- if (this.metadataCacheInstance && file.id) {
2898
- this.metadataCacheInstance.upsertFile({
2899
- id: file.id,
2900
- name: file.name || fileName,
2901
- mimeType: file.mimeType || "",
2902
- size: file.size ? parseInt(file.size, 10) : void 0,
2903
- parentId,
2904
- md5Checksum: localMd5,
2905
- trashed: false
4355
+ if (!existingId) {
4356
+ const found = await this.query().md5(localMd5).notTrashed().first();
4357
+ if (found?.id) {
4358
+ existingId = found.id;
4359
+ }
4360
+ }
4361
+ if (existingId) {
4362
+ const fileName = targetName || (typeof uploadOpts.source === "string" ? path10.basename(uploadOpts.source) : "file.bin");
4363
+ const raw = await this.getRawClient();
4364
+ const copyRes = await withRetry(async () => {
4365
+ return await raw.files.copy({
4366
+ fileId: existingId,
4367
+ requestBody: {
4368
+ name: fileName,
4369
+ parents: parentId ? [parentId] : void 0,
4370
+ description: uploadOpts.description
4371
+ },
4372
+ fields: "id, name, mimeType, size, modifiedTime, md5Checksum",
4373
+ supportsAllDrives: true
4374
+ });
2906
4375
  });
4376
+ const file = copyRes.data;
4377
+ if (this.metadataCacheInstance && file.id) {
4378
+ this.metadataCacheInstance.upsertFile({
4379
+ id: file.id,
4380
+ name: file.name || fileName,
4381
+ mimeType: file.mimeType || "",
4382
+ size: file.size ? parseInt(file.size, 10) : void 0,
4383
+ parentId,
4384
+ md5Checksum: localMd5,
4385
+ trashed: false
4386
+ });
4387
+ }
4388
+ return await this.pluginManager.runAfterUpload(file);
2907
4389
  }
2908
- return await this.pluginManager.runAfterUpload(file);
2909
4390
  }
2910
4391
  }
2911
4392
  const uploaded = await uploader.upload({
2912
- ...opts,
4393
+ ...uploadOpts,
2913
4394
  name: targetName,
2914
4395
  parent: parentId
2915
4396
  });
2916
4397
  if (this.metadataCacheInstance && uploaded.id) {
4398
+ const virtualPath = typeof opts.parent === "string" && opts.parent.startsWith("/") ? `${opts.parent === "/" ? "" : opts.parent}/${uploaded.name || targetName || "untitled"}` : void 0;
2917
4399
  this.metadataCacheInstance.upsertFile({
2918
4400
  id: uploaded.id,
2919
4401
  name: uploaded.name || targetName || "untitled",
2920
4402
  mimeType: uploaded.mimeType || "",
2921
4403
  size: uploaded.size ? parseInt(uploaded.size, 10) : void 0,
2922
4404
  parentId,
4405
+ path: virtualPath,
2923
4406
  trashed: false
2924
4407
  });
2925
4408
  }
@@ -2930,16 +4413,35 @@ var init_client = __esm({
2930
4413
  * - Automatic conversion for Google Docs, Sheets, and Slides
2931
4414
  * - Progress events
2932
4415
  * - Saves directly to file or returns Readable Stream
4416
+ * - Leverages local metadata cache to bypass redundant Google API roundtrips
2933
4417
  */
2934
4418
  async download(fileIdOrPath, options = {}) {
2935
4419
  const fileId = await this.resolveId(fileIdOrPath);
2936
- const processedOpts = await this.pluginManager.runBeforeDownload(fileId, options);
4420
+ let cachedMeta = options.metadata;
4421
+ if (!cachedMeta && this.metadataCacheInstance) {
4422
+ const cached = this.metadataCacheInstance.getById(fileId);
4423
+ if (cached && cached.name && cached.mimeType) {
4424
+ cachedMeta = { name: cached.name, mimeType: cached.mimeType, size: cached.size };
4425
+ }
4426
+ }
4427
+ const mergedOpts = cachedMeta ? { ...options, metadata: cachedMeta } : options;
4428
+ const processedOpts = await this.pluginManager.runBeforeDownload(fileId, mergedOpts);
2937
4429
  const downloader = await this.getDownloader();
2938
4430
  const result = await downloader.download(fileId, processedOpts);
4431
+ if (processedOpts.decrypt && this.cryptoInstance && result.filePath && fs7.existsSync(result.filePath)) {
4432
+ const encrypted = await fs7.promises.readFile(result.filePath);
4433
+ const decrypted = this.cryptoInstance.decryptBuffer(encrypted);
4434
+ await fs7.promises.writeFile(result.filePath, decrypted);
4435
+ }
4436
+ if (processedOpts.decompress && result.filePath && fs7.existsSync(result.filePath)) {
4437
+ const comp = await fs7.promises.readFile(result.filePath);
4438
+ const decomp = await decompressBuffer(comp);
4439
+ await fs7.promises.writeFile(result.filePath, decomp);
4440
+ }
2939
4441
  return await this.pluginManager.runAfterDownload(result);
2940
4442
  }
2941
4443
  /**
2942
- * Gets file metadata
4444
+ * Gets file metadata and updates the local metadata cache
2943
4445
  */
2944
4446
  async getFile(fileIdOrPath) {
2945
4447
  const fileId = await this.resolveId(fileIdOrPath);
@@ -2951,7 +4453,20 @@ var init_client = __esm({
2951
4453
  supportsAllDrives: true
2952
4454
  });
2953
4455
  });
2954
- return res.data;
4456
+ const file = res.data;
4457
+ if (this.metadataCacheInstance && file.id) {
4458
+ this.metadataCacheInstance.upsertFile({
4459
+ id: file.id,
4460
+ name: file.name || "",
4461
+ mimeType: file.mimeType || "",
4462
+ size: file.size ? parseInt(file.size, 10) : void 0,
4463
+ parentId: file.parents?.[0],
4464
+ path: fileIdOrPath.startsWith("/") ? fileIdOrPath : void 0,
4465
+ modifiedTime: file.modifiedTime || void 0,
4466
+ trashed: file.trashed || false
4467
+ });
4468
+ }
4469
+ return file;
2955
4470
  }
2956
4471
  /**
2957
4472
  * Reads file content as UTF-8 string
@@ -2994,6 +4509,9 @@ var init_client = __esm({
2994
4509
  if (this.pathResolverInstance && fileIdOrPath.startsWith("/")) {
2995
4510
  this.pathResolverInstance.invalidatePath(fileIdOrPath);
2996
4511
  }
4512
+ if (this.metadataCacheInstance) {
4513
+ this.metadataCacheInstance.deleteFile(fileId);
4514
+ }
2997
4515
  }
2998
4516
  /**
2999
4517
  * Move item to trash
@@ -3035,6 +4553,16 @@ var init_client = __esm({
3035
4553
  if (this.pathResolverInstance) {
3036
4554
  this.pathResolverInstance.clearCache();
3037
4555
  }
4556
+ if (this.metadataCacheInstance) {
4557
+ const cached = this.metadataCacheInstance.getById(fileId);
4558
+ if (cached) {
4559
+ this.metadataCacheInstance.upsertFile({
4560
+ ...cached,
4561
+ parentId: newParentId,
4562
+ path: void 0
4563
+ });
4564
+ }
4565
+ }
3038
4566
  return res.data;
3039
4567
  }
3040
4568
  /**
@@ -3043,10 +4571,7 @@ var init_client = __esm({
3043
4571
  async copy(fileIdOrPath, options = {}) {
3044
4572
  const fileId = await this.resolveId(fileIdOrPath);
3045
4573
  const raw = await this.getRawClient();
3046
- let parentId = options.parent;
3047
- if (parentId && parentId.startsWith("/")) {
3048
- parentId = await this.mkdirp(parentId);
3049
- }
4574
+ const parentId = options.parent ? await this.resolveId(options.parent, true) : void 0;
3050
4575
  const requestBody = {};
3051
4576
  if (options.name) requestBody.name = options.name;
3052
4577
  if (parentId) requestBody.parents = [parentId];
@@ -3077,6 +4602,16 @@ var init_client = __esm({
3077
4602
  if (this.pathResolverInstance) {
3078
4603
  this.pathResolverInstance.clearCache();
3079
4604
  }
4605
+ if (this.metadataCacheInstance) {
4606
+ const cached = this.metadataCacheInstance.getById(fileId);
4607
+ if (cached) {
4608
+ this.metadataCacheInstance.upsertFile({
4609
+ ...cached,
4610
+ name: newName,
4611
+ path: void 0
4612
+ });
4613
+ }
4614
+ }
3080
4615
  return res.data;
3081
4616
  }
3082
4617
  // ==========================================
@@ -3163,16 +4698,16 @@ var init_client = __esm({
3163
4698
  durationMs: 0
3164
4699
  };
3165
4700
  const collectFiles = async (dir, base) => {
3166
- const entries = await fs6.promises.readdir(dir, { withFileTypes: true });
4701
+ const entries = await fs7.promises.readdir(dir, { withFileTypes: true });
3167
4702
  const files = [];
3168
4703
  for (const entry of entries) {
3169
- const fullPath = path8.join(dir, entry.name);
3170
- const relPath = path8.join(base, entry.name);
4704
+ const fullPath = path10.join(dir, entry.name);
4705
+ const relPath = path10.join(base, entry.name);
3171
4706
  if (entry.isDirectory()) {
3172
4707
  const sub = await collectFiles(fullPath, relPath);
3173
4708
  files.push(...sub);
3174
4709
  } else if (entry.isFile()) {
3175
- const stat = await fs6.promises.stat(fullPath);
4710
+ const stat = await fs7.promises.stat(fullPath);
3176
4711
  files.push({ fullPath, relPath, size: stat.size });
3177
4712
  }
3178
4713
  }
@@ -3185,11 +4720,11 @@ var init_client = __esm({
3185
4720
  if (remoteDirCache.has(relDir)) {
3186
4721
  return remoteDirCache.get(relDir);
3187
4722
  }
3188
- const parts = relDir.split(path8.sep).filter(Boolean);
4723
+ const parts = relDir.split(path10.sep).filter(Boolean);
3189
4724
  let currentParent = targetFolderId;
3190
4725
  let currentRel = "";
3191
4726
  for (const part of parts) {
3192
- currentRel = currentRel ? path8.join(currentRel, part) : part;
4727
+ currentRel = currentRel ? path10.join(currentRel, part) : part;
3193
4728
  if (remoteDirCache.has(currentRel)) {
3194
4729
  currentParent = remoteDirCache.get(currentRel);
3195
4730
  continue;
@@ -3218,8 +4753,8 @@ var init_client = __esm({
3218
4753
  };
3219
4754
  await pool.map(allFiles, async (fileItem) => {
3220
4755
  try {
3221
- const relDir = path8.dirname(fileItem.relPath);
3222
- const fileName = path8.basename(fileItem.relPath);
4756
+ const relDir = path10.dirname(fileItem.relPath);
4757
+ const fileName = path10.basename(fileItem.relPath);
3223
4758
  const parentFolderId = await ensureRemoteSubdir(relDir === "." ? "" : relDir);
3224
4759
  if (options.onFileStart) {
3225
4760
  options.onFileStart(fileItem.fullPath, fileItem.relPath);
@@ -3354,7 +4889,7 @@ var init_client = __esm({
3354
4889
  async createWriteStream(remotePath, options = {}) {
3355
4890
  await this.init();
3356
4891
  const { PassThrough } = await import("stream");
3357
- const passThrough = new PassThrough();
4892
+ const passThrough = new PassThrough({ highWaterMark: 1024 * 1024 });
3358
4893
  let resolveDone;
3359
4894
  let rejectDone;
3360
4895
  const donePromise = new Promise((resolve, reject) => {
@@ -3362,8 +4897,8 @@ var init_client = __esm({
3362
4897
  rejectDone = reject;
3363
4898
  });
3364
4899
  passThrough.done = donePromise;
3365
- const remoteDir = path8.dirname(remotePath);
3366
- const fileName = options.name || options.filename || path8.basename(remotePath);
4900
+ const remoteDir = path10.dirname(remotePath);
4901
+ const fileName = options.name || options.filename || path10.basename(remotePath);
3367
4902
  const targetParentId = remoteDir === "." || remoteDir === "/" ? this.rootFolderId : await this.mkdirp(remoteDir);
3368
4903
  const mimeType = options.mimeType || "application/octet-stream";
3369
4904
  const raw = this.driveClient;
@@ -3401,6 +4936,12 @@ var init_client = __esm({
3401
4936
  // ==========================================
3402
4937
  // METADATA CACHE OPERATIONS
3403
4938
  // ==========================================
4939
+ /**
4940
+ * Synchronous getter for the active metadata cache instance
4941
+ */
4942
+ get cache() {
4943
+ return this.metadataCacheInstance;
4944
+ }
3404
4945
  /**
3405
4946
  * Returns the active persistent metadata cache instance (SQLite/Memory)
3406
4947
  */
@@ -3423,6 +4964,9 @@ var init_client = __esm({
3423
4964
  if (this.pathResolverInstance) {
3424
4965
  this.pathResolverInstance.clearCache();
3425
4966
  }
4967
+ if (this.metadataCacheInstance) {
4968
+ this.metadataCacheInstance.clear();
4969
+ }
3426
4970
  }
3427
4971
  /**
3428
4972
  * Crawls and indexes Google Drive metadata into the local SQLite database for instant 0ms lookups
@@ -3587,6 +5131,47 @@ var init_client = __esm({
3587
5131
  const { startWebDAVServer: startWebDAVServer2 } = await Promise.resolve().then(() => (init_webdav(), webdav_exports));
3588
5132
  return await startWebDAVServer2(this, options);
3589
5133
  }
5134
+ /**
5135
+ * Performs an intelligent two-way bidirectional sync between local and Google Drive directories
5136
+ */
5137
+ async syncBiDirectional(options) {
5138
+ await this.init();
5139
+ const engine = new BidirectionalSyncEngine(this);
5140
+ return await engine.sync(options);
5141
+ }
5142
+ /**
5143
+ * Starts an embedded S3-compatible HTTP gateway server
5144
+ */
5145
+ async serveS3(options = {}) {
5146
+ await this.init();
5147
+ const gateway = new S3GatewayServer(this, options);
5148
+ await gateway.start();
5149
+ return gateway;
5150
+ }
5151
+ /**
5152
+ * Scans Google Drive files and generates a security & permission audit report
5153
+ */
5154
+ async auditPermissions(options = {}) {
5155
+ await this.init();
5156
+ const auditor = new SecurityAuditor(this.driveClient);
5157
+ return await auditor.audit(options);
5158
+ }
5159
+ /**
5160
+ * Revokes public 'anyone' link permissions from the given files
5161
+ */
5162
+ async revokePublicPermissions(fileIds) {
5163
+ await this.init();
5164
+ const auditor = new SecurityAuditor(this.driveClient);
5165
+ return await auditor.revokePublicAccess(fileIds);
5166
+ }
5167
+ /**
5168
+ * Multi-word fuzzy and semantic search across files
5169
+ */
5170
+ async searchSmart(query, options = {}) {
5171
+ await this.init();
5172
+ const engine = new SmartSearchEngine(this);
5173
+ return await engine.search(query, options);
5174
+ }
3590
5175
  /**
3591
5176
  * Calculates local file MD5 hash for integrity and deduplication checks
3592
5177
  */
@@ -3607,8 +5192,8 @@ var init_client = __esm({
3607
5192
  init_esm_shims();
3608
5193
  init_client();
3609
5194
  init_format();
3610
- import fs7 from "fs";
3611
- import path9 from "path";
5195
+ import fs8 from "fs";
5196
+ import path11 from "path";
3612
5197
  import { Command } from "commander";
3613
5198
  import chalk2 from "chalk";
3614
5199
  import ora from "ora";
@@ -3769,17 +5354,29 @@ ${chalk.cyan("\u{1F517} Getting shareable link for:")} ${chalk.bold(item.name)}.
3769
5354
 
3770
5355
  // src/cli.ts
3771
5356
  var program = new Command();
3772
- var pkgVersion = "1.1.1";
5357
+ var pkgVersion = "1.2.0";
3773
5358
  try {
3774
5359
  const pkgPath = new URL("../package.json", import.meta.url);
3775
- const pkg = JSON.parse(fs7.readFileSync(pkgPath, "utf8"));
5360
+ const pkg = JSON.parse(fs8.readFileSync(pkgPath, "utf8"));
3776
5361
  if (pkg.version) pkgVersion = pkg.version;
3777
5362
  } catch {
3778
5363
  }
3779
5364
  program.name("drivekit").description(chalk2.bold.cyan("\u26A1 DriveKit CLI: High-speed, flexible Google Drive tool for developers")).version(pkgVersion).option("-k, --key <path>", "Path to service account JSON key file").option("-t, --token <token>", "Google OAuth2 Bearer access token");
3780
5365
  function getAuthConfig(cmdOptions) {
3781
5366
  const keyFilePath = cmdOptions.key || process.env.GOOGLE_APPLICATION_CREDENTIALS || process.env.GDRIVE_SERVICE_ACCOUNT_PATH;
3782
- const accessToken = cmdOptions.token || process.env.GDRIVE_ACCESS_TOKEN;
5367
+ let accessToken = cmdOptions.token || process.env.GDRIVE_ACCESS_TOKEN;
5368
+ if (!keyFilePath && !accessToken) {
5369
+ const tokensFile = path11.resolve(process.cwd(), "gdrive-tokens.json");
5370
+ if (fs8.existsSync(tokensFile)) {
5371
+ try {
5372
+ const tokens = JSON.parse(fs8.readFileSync(tokensFile, "utf8"));
5373
+ if (tokens.access_token) {
5374
+ accessToken = tokens.access_token;
5375
+ }
5376
+ } catch {
5377
+ }
5378
+ }
5379
+ }
3783
5380
  return {
3784
5381
  keyFilePath,
3785
5382
  accessToken
@@ -3849,11 +5446,11 @@ program.command("explore [folder]").description("Interactive terminal keyboard f
3849
5446
  }
3850
5447
  });
3851
5448
  program.command("upload <localFile> [remotePath]").description("Upload a file with high speed and live progress tracking").option("-o, --overwrite", "Overwrite remote file if it exists").option("-d, --dedup", "Enable instant cloud deduplication via MD5 hash check").action(async (localFile, remotePath = "/", options) => {
3852
- if (!fs7.existsSync(localFile)) {
5449
+ if (!fs8.existsSync(localFile)) {
3853
5450
  console.error(chalk2.red(`\u274C Local file not found: ${localFile}`));
3854
5451
  process.exit(1);
3855
5452
  }
3856
- const fileName = path9.basename(localFile);
5453
+ const fileName = path11.basename(localFile);
3857
5454
  const spinner = ora(`Preparing upload: ${fileName}...`).start();
3858
5455
  try {
3859
5456
  const client = await getClient(options);
@@ -3949,7 +5546,7 @@ program.command("delete <fileIdOrPath>").description("Move a file/folder to tras
3949
5546
  }
3950
5547
  });
3951
5548
  program.command("sync <localDir> <remoteFolder>").description("Sync a local directory to Google Drive recursively with high concurrency").option("-c, --concurrency <number>", "Number of parallel uploads", "4").option("-o, --overwrite", "Overwrite files if they already exist").action(async (localDir, remoteFolder, options) => {
3952
- if (!fs7.existsSync(localDir)) {
5549
+ if (!fs8.existsSync(localDir)) {
3953
5550
  console.error(chalk2.red(`\u274C Local directory not found: ${localDir}`));
3954
5551
  process.exit(1);
3955
5552
  }
@@ -4117,8 +5714,8 @@ program.command("login").description("Interactive 1-click browser OAuth2 sign-in
4117
5714
  if (result.tokens.refresh_token) {
4118
5715
  console.log(`Refresh Token: ${chalk2.green(result.tokens.refresh_token?.slice(0, 25) + "...")}`);
4119
5716
  }
4120
- const outPath = path9.resolve("./gdrive-tokens.json");
4121
- fs7.writeFileSync(outPath, JSON.stringify(result.tokens, null, 2), "utf8");
5717
+ const outPath = path11.resolve("./gdrive-tokens.json");
5718
+ fs8.writeFileSync(outPath, JSON.stringify(result.tokens, null, 2), "utf8");
4122
5719
  console.log(`\u{1F4BE} Saved tokens to: ${chalk2.bold(outPath)}
4123
5720
  `);
4124
5721
  } catch (err) {
@@ -4230,6 +5827,186 @@ program.command("serve").description("Start embedded WebDAV server to mount Driv
4230
5827
  process.exit(1);
4231
5828
  }
4232
5829
  });
5830
+ program.command("sync-2way <localDir> <remoteDir>").description("Two-way bidirectional synchronization with conflict resolution").option("-s, --strategy <strategy>", "Conflict strategy: rename-conflict, keep-newer, prefer-cloud, prefer-local", "rename-conflict").option("--delete-missing", "Propagate deletions in both directions").option("--dry-run", "Preview changes without modifying any files").action(async (localDir, remoteDir, options) => {
5831
+ console.log(chalk2.bold.cyan(`
5832
+ \u{1F504} Two-Way Sync: "${localDir}" \u21C4 "${remoteDir}"`));
5833
+ console.log(`Conflict Strategy: ${chalk2.yellow(options.strategy)} | Delete Missing: ${options.deleteMissing ? chalk2.red("YES") : chalk2.dim("NO")}
5834
+ `);
5835
+ try {
5836
+ const client = await getClient(options);
5837
+ const res = await client.syncBiDirectional({
5838
+ localDir: path11.resolve(localDir),
5839
+ remoteDir,
5840
+ conflictStrategy: options.strategy,
5841
+ deleteMissing: !!options.deleteMissing,
5842
+ dryRun: !!options.dryRun,
5843
+ onProgress: (ev) => {
5844
+ const actionColors = {
5845
+ upload: chalk2.green("[UPLOAD]"),
5846
+ download: chalk2.blue("[DOWNLOAD]"),
5847
+ "delete-local": chalk2.red("[DELETE LOCAL]"),
5848
+ "delete-remote": chalk2.red("[DELETE REMOTE]"),
5849
+ "conflict-resolved": chalk2.yellow("[CONFLICT]"),
5850
+ "skip-identical": chalk2.dim("[IDENTICAL]")
5851
+ };
5852
+ const prefix = actionColors[ev.action] || `[${ev.action}]`;
5853
+ console.log(` ${prefix} ${chalk2.white(ev.relPath)} ${ev.details ? chalk2.dim(`(${ev.details})`) : ""}`);
5854
+ }
5855
+ });
5856
+ console.log(chalk2.bold.green(`
5857
+ \u2705 Two-Way Sync Completed in ${(res.durationMs / 1e3).toFixed(2)}s!`));
5858
+ console.log(` \u2B06\uFE0F Uploaded: ${chalk2.bold(res.uploaded.length)}`);
5859
+ console.log(` \u2B07\uFE0F Downloaded: ${chalk2.bold(res.downloaded.length)}`);
5860
+ console.log(` \u{1F5D1}\uFE0F Deleted Local: ${chalk2.bold(res.deletedLocal.length)}`);
5861
+ console.log(` \u{1F5D1}\uFE0F Deleted Remote:${chalk2.bold(res.deletedRemote.length)}`);
5862
+ console.log(` \u26A1 Conflicts: ${chalk2.bold(res.conflicts.length)}`);
5863
+ console.log(` \u23ED\uFE0F Identical: ${chalk2.bold(res.skipped.length)}
5864
+ `);
5865
+ } catch (err) {
5866
+ console.error(chalk2.red(`
5867
+ Two-Way sync failed: ${err.message}`));
5868
+ process.exit(1);
5869
+ }
5870
+ });
5871
+ program.command("serve-s3").description("Start S3-compatible HTTP gateway server to treat Drive as an S3 Bucket").option("-p, --port <port>", "Port number to listen on", "9000").option("-h, --host <host>", "Host address to bind to", "127.0.0.1").option("-b, --bucket-root <path>", "Virtual path root for S3 buckets", "/").option("--key <accessKey>", "Optional S3 access key ID").option("--secret <secretKey>", "Optional S3 secret access key").action(async (options) => {
5872
+ try {
5873
+ const client = await getClient(options);
5874
+ const port = parseInt(options.port, 10) || 9e3;
5875
+ const host = options.host || "127.0.0.1";
5876
+ console.log(chalk2.bold.cyan("\n\u{1F4E6} DriveKit S3-Compatible Gateway"));
5877
+ console.log("Starting S3 REST API bridge to Google Drive...\n");
5878
+ const gateway = await client.serveS3({
5879
+ port,
5880
+ host,
5881
+ bucketRoot: options.bucketRoot,
5882
+ accessKeyId: options.key,
5883
+ secretAccessKey: options.secret
5884
+ });
5885
+ console.log(chalk2.bold.green(`\u{1F680} S3 Gateway active at: ${chalk2.underline(`http://${host}:${port}`)}`));
5886
+ console.log(chalk2.white("\n\u{1F4CC} Connect with AWS CLI:"));
5887
+ console.log(chalk2.yellow(` aws s3 ls --endpoint-url http://${host}:${port}`));
5888
+ console.log(chalk2.white("\u{1F4CC} Connect with MinIO client:"));
5889
+ console.log(chalk2.yellow(` mc alias set drivekit http://${host}:${port} ${options.key || "dummy"} ${options.secret || "dummy"}
5890
+ `));
5891
+ console.log(chalk2.dim("Press Ctrl+C to stop the S3 Gateway.\n"));
5892
+ process.on("SIGINT", async () => {
5893
+ await gateway.stop();
5894
+ console.log(chalk2.yellow("\nS3 Gateway stopped. Goodbye!"));
5895
+ process.exit(0);
5896
+ });
5897
+ } catch (err) {
5898
+ console.error(chalk2.red(`Failed to start S3 gateway: ${err.message}`));
5899
+ process.exit(1);
5900
+ }
5901
+ });
5902
+ program.command("audit").description("Audit Drive security & permissions: detect public leaks and external shares").option("-l, --limit <count>", "Maximum files to scan", "200").option("--allowed-domains <domains>", "Comma-separated allowed organization domains").option("--revoke-public", 'Automatically revoke public "anyone" links').action(async (options) => {
5903
+ const spinner = ora("Auditing Google Drive permissions...").start();
5904
+ try {
5905
+ const client = await getClient(options);
5906
+ const limit = parseInt(options.limit, 10) || 200;
5907
+ const allowedDomains = options.allowedDomains ? options.allowedDomains.split(",").map((d) => d.trim()) : [];
5908
+ const report = await client.auditPermissions({ scanLimit: limit, allowedDomains });
5909
+ spinner.stop();
5910
+ console.log(chalk2.bold.cyan("\n\u{1F6E1}\uFE0F Google Drive Security & Permission Audit Report"));
5911
+ console.log(`Scanned files: ${chalk2.bold(report.totalScanned)} | Audit time: ${chalk2.dim(report.scannedAt)}
5912
+ `);
5913
+ console.log(`\u{1F310} Publicly Accessible (Anyone with Link): ${report.publicFilesCount > 0 ? chalk2.bold.red(report.publicFilesCount) : chalk2.green("0")}`);
5914
+ console.log(`\u{1F3E2} Organization Domain Shares: ${chalk2.yellow(report.domainSharedCount)}`);
5915
+ console.log(`\u{1F464} External Collaborators: ${report.externalSharesCount > 0 ? chalk2.bold.yellow(report.externalSharesCount) : chalk2.green("0")}
5916
+ `);
5917
+ if (report.issues.length > 0) {
5918
+ console.log(chalk2.bold.yellow("\u26A0\uFE0F Detected Security Issues:"));
5919
+ for (const issue of report.issues.slice(0, 30)) {
5920
+ const riskColor = issue.risk === "CRITICAL" ? chalk2.bold.bgRed : issue.risk === "HIGH" ? chalk2.red : chalk2.yellow;
5921
+ console.log(` ${riskColor(`[${issue.risk}]`)} ${chalk2.bold(issue.fileName)}`);
5922
+ console.log(` \u21B3 Reason: ${issue.reason}`);
5923
+ if (issue.webViewLink) console.log(` \u21B3 URL: ${chalk2.dim(issue.webViewLink)}`);
5924
+ }
5925
+ if (report.issues.length > 30) {
5926
+ console.log(chalk2.dim(`
5927
+ ... and ${report.issues.length - 30} more issues.`));
5928
+ }
5929
+ console.log("");
5930
+ } else {
5931
+ console.log(chalk2.green("\u2728 No critical security leaks detected!\n"));
5932
+ }
5933
+ if (options.revokePublic && report.publicFilesCount > 0) {
5934
+ const publicFileIds = Array.from(new Set(report.issues.filter((i) => i.type === "anyone").map((i) => i.fileId)));
5935
+ const revSpinner = ora(`Revoking public access on ${publicFileIds.length} files...`).start();
5936
+ const revRes = await client.revokePublicPermissions(publicFileIds);
5937
+ revSpinner.succeed(chalk2.green(`Successfully revoked public access on ${revRes.revoked.length} files!`));
5938
+ }
5939
+ } catch (err) {
5940
+ spinner.fail(chalk2.red(`Security audit failed: ${err.message}`));
5941
+ process.exit(1);
5942
+ }
5943
+ });
5944
+ program.command("revisions <fileIdOrPath>").description("List and manage historical file revisions").option("--keep-forever <revId>", "Pin a revision to prevent automatic purging after 30 days").option("--restore <revId>", "Restore file to a specific previous revision").action(async (fileIdOrPath, options) => {
5945
+ try {
5946
+ const client = await getClient(options);
5947
+ const revsManager = client.getRevisions(fileIdOrPath);
5948
+ if (options.keepForever) {
5949
+ const spinner2 = ora(`Pinning revision ${options.keepForever}...`).start();
5950
+ await revsManager.keepForever(options.keepForever, true);
5951
+ spinner2.succeed(chalk2.green(`Revision ${options.keepForever} is now pinned forever!`));
5952
+ return;
5953
+ }
5954
+ if (options.restore) {
5955
+ const spinner2 = ora(`Restoring file to revision ${options.restore}...`).start();
5956
+ await revsManager.restore(options.restore);
5957
+ spinner2.succeed(chalk2.green(`File content successfully restored to revision ${options.restore}!`));
5958
+ return;
5959
+ }
5960
+ const spinner = ora("Fetching revision history...").start();
5961
+ const revisions = await revsManager.list();
5962
+ spinner.stop();
5963
+ console.log(chalk2.bold.cyan(`
5964
+ \u{1F4DC} Revision History for "${fileIdOrPath}" (${revisions.length} versions):
5965
+ `));
5966
+ for (const r of revisions) {
5967
+ const pinned = r.keepForever ? chalk2.green("\u{1F4CC} [PINNED]") : chalk2.dim("[EXPIRABLE]");
5968
+ console.log(` ID: ${chalk2.bold.yellow(r.id.padEnd(20))} Modified: ${chalk2.white(r.modifiedTime || "unknown")} ${pinned} ${r.size ? formatBytes(r.size) : ""}`);
5969
+ }
5970
+ console.log("");
5971
+ } catch (err) {
5972
+ console.error(chalk2.red(`Failed to manage revisions: ${err.message}`));
5973
+ process.exit(1);
5974
+ }
5975
+ });
5976
+ program.command("search <query>").description("Search Google Drive files by name, description, or fuzzy matching").option("--smart", "Use multi-word fuzzy relevance scoring").option("-l, --limit <count>", "Maximum results to return", "20").action(async (query, options) => {
5977
+ const spinner = ora(`Searching for "${query}"...`).start();
5978
+ try {
5979
+ const client = await getClient(options);
5980
+ const limit = parseInt(options.limit, 10) || 20;
5981
+ if (options.smart) {
5982
+ const results = await client.searchSmart(query, { limit });
5983
+ spinner.stop();
5984
+ console.log(chalk2.bold.cyan(`
5985
+ \u{1F50D} Smart Search Results for "${query}" (${results.length}):
5986
+ `));
5987
+ for (const res of results) {
5988
+ const scorePercent = Math.round(res.score * 100);
5989
+ const scoreColor = scorePercent >= 80 ? chalk2.green : scorePercent >= 50 ? chalk2.yellow : chalk2.dim;
5990
+ console.log(` ${scoreColor(`[${scorePercent}%]`)} ${chalk2.bold(res.file.name)} ${chalk2.dim(`(Matched on: ${res.matchedOn.join(", ")})`)}`);
5991
+ console.log(` \u21B3 ID: ${chalk2.dim(res.file.id)} | Size: ${formatBytes(res.file.size ? parseInt(res.file.size, 10) : 0)}`);
5992
+ }
5993
+ console.log("");
5994
+ return;
5995
+ }
5996
+ const files = await client.query().nameContains(query).notTrashed().pageSize(limit).list();
5997
+ spinner.stop();
5998
+ console.log(chalk2.bold.cyan(`
5999
+ \u{1F50D} Found ${files.length} matching files:
6000
+ `));
6001
+ for (const f of files) {
6002
+ console.log(` \u{1F4C4} ${chalk2.white((f.name || "untitled").padEnd(35))} ${chalk2.dim(`ID: ${f.id}`)} [${formatBytes(f.size ? parseInt(f.size, 10) : 0)}]`);
6003
+ }
6004
+ console.log("");
6005
+ } catch (err) {
6006
+ spinner.fail(chalk2.red(`Search failed: ${err.message}`));
6007
+ process.exit(1);
6008
+ }
6009
+ });
4233
6010
  function runCLI() {
4234
6011
  program.parse(process.argv);
4235
6012
  }