drivekit 1.0.1 → 1.1.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.cjs CHANGED
@@ -318,11 +318,13 @@ var init_path_resolver = __esm({
318
318
  cache = /* @__PURE__ */ new Map();
319
319
  cacheTTL;
320
320
  enableCache;
321
+ metadataCache;
321
322
  constructor(drive2, rootFolderId = "root", options) {
322
323
  this.drive = drive2;
323
324
  this.rootFolderId = rootFolderId;
324
325
  this.enableCache = options?.enableCache ?? true;
325
326
  this.cacheTTL = options?.cacheTTL ?? 5 * 60 * 1e3;
327
+ this.metadataCache = options?.metadataCache;
326
328
  }
327
329
  /**
328
330
  * Normalizes a virtual path (e.g. "///Backups//2026/" -> "/Backups/2026")
@@ -337,21 +339,31 @@ var init_path_resolver = __esm({
337
339
  /**
338
340
  * Gets cache key for a path
339
341
  */
340
- getCacheKey(path6) {
341
- return `${this.rootFolderId}:${this.normalizePath(path6)}`;
342
+ getCacheKey(path8) {
343
+ return `${this.rootFolderId}:${this.normalizePath(path8)}`;
342
344
  }
343
345
  /**
344
346
  * Clears the path cache
345
347
  */
346
348
  clearCache() {
347
349
  this.cache.clear();
350
+ if (this.metadataCache) {
351
+ this.metadataCache.clear();
352
+ }
348
353
  }
349
354
  /**
350
355
  * Invalidate a single path from cache
351
356
  */
352
- invalidatePath(path6) {
353
- const key = this.getCacheKey(path6);
357
+ invalidatePath(path8) {
358
+ const norm = this.normalizePath(path8);
359
+ const key = this.getCacheKey(norm);
354
360
  this.cache.delete(key);
361
+ if (this.metadataCache) {
362
+ const item = this.metadataCache.getByPath(norm);
363
+ if (item) {
364
+ this.metadataCache.deleteFile(item.id);
365
+ }
366
+ }
355
367
  }
356
368
  /**
357
369
  * Resolves a path to a Google Drive item (file or folder).
@@ -367,6 +379,17 @@ var init_path_resolver = __esm({
367
379
  mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER
368
380
  };
369
381
  }
382
+ if (this.metadataCache) {
383
+ const persistentCached = this.metadataCache.getByPath(norm);
384
+ if (persistentCached) {
385
+ return {
386
+ id: persistentCached.id,
387
+ name: persistentCached.name,
388
+ isFolder: persistentCached.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
389
+ mimeType: persistentCached.mimeType
390
+ };
391
+ }
392
+ }
370
393
  if (this.enableCache) {
371
394
  const cached = this.cache.get(this.getCacheKey(norm));
372
395
  if (cached && cached.expiresAt > Date.now()) {
@@ -385,6 +408,21 @@ var init_path_resolver = __esm({
385
408
  const segment = segments[i];
386
409
  const isLast = i === segments.length - 1;
387
410
  currentPath += `/${segment}`;
411
+ if (this.metadataCache) {
412
+ const pCached = this.metadataCache.getByPath(currentPath);
413
+ if (pCached) {
414
+ currentParentId = pCached.id;
415
+ if (isLast) {
416
+ return {
417
+ id: pCached.id,
418
+ name: pCached.name,
419
+ isFolder: pCached.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
420
+ mimeType: pCached.mimeType
421
+ };
422
+ }
423
+ continue;
424
+ }
425
+ }
388
426
  if (this.enableCache) {
389
427
  const cached = this.cache.get(this.getCacheKey(currentPath));
390
428
  if (cached && cached.expiresAt > Date.now()) {
@@ -429,6 +467,16 @@ var init_path_resolver = __esm({
429
467
  }
430
468
  if (file && file.id) {
431
469
  currentParentId = file.id;
470
+ if (this.metadataCache) {
471
+ this.metadataCache.upsertFile({
472
+ id: file.id,
473
+ name: file.name || segment,
474
+ mimeType: file.mimeType || "",
475
+ parentId: currentParentId,
476
+ path: currentPath,
477
+ trashed: false
478
+ });
479
+ }
432
480
  if (this.enableCache) {
433
481
  this.cache.set(this.getCacheKey(currentPath), {
434
482
  id: file.id,
@@ -463,6 +511,16 @@ var init_path_resolver = __esm({
463
511
  throw new Error(`Failed to create folder "${segment}" under parent "${currentParentId}"`);
464
512
  }
465
513
  currentParentId = newFolder.id;
514
+ if (this.metadataCache) {
515
+ this.metadataCache.upsertFile({
516
+ id: newFolder.id,
517
+ name: segment,
518
+ mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
519
+ parentId: currentParentId,
520
+ path: currentPath,
521
+ trashed: false
522
+ });
523
+ }
466
524
  if (this.enableCache) {
467
525
  this.cache.set(this.getCacheKey(currentPath), {
468
526
  id: newFolder.id,
@@ -652,6 +710,9 @@ var init_resumable_uploader = __esm({
652
710
  let chunkIndex = 0;
653
711
  try {
654
712
  while (bytesSent < totalBytes) {
713
+ if (options.signal?.aborted) {
714
+ throw new Error("Upload aborted by user signal");
715
+ }
655
716
  chunkIndex++;
656
717
  const currentChunkSize = Math.min(chunkSize, totalBytes - bytesSent);
657
718
  const buffer = Buffer.alloc(currentChunkSize);
@@ -712,6 +773,9 @@ var init_resumable_uploader = __esm({
712
773
  const totalChunks = Math.ceil(totalBytes / chunkSize) || 1;
713
774
  let chunkIndex = 0;
714
775
  while (bytesSent < totalBytes) {
776
+ if (options.signal?.aborted) {
777
+ throw new Error("Upload aborted by user signal");
778
+ }
715
779
  chunkIndex++;
716
780
  const currentChunkSize = Math.min(chunkSize, totalBytes - bytesSent);
717
781
  const chunk = buffer.subarray(bytesSent, bytesSent + currentChunkSize);
@@ -933,6 +997,24 @@ var init_downloader = __esm({
933
997
  size: totalBytes
934
998
  };
935
999
  }
1000
+ /**
1001
+ * Returns a raw ReadableStream for the file, supporting HTTP Range requests for partial content / streaming.
1002
+ */
1003
+ async createReadStream(fileId, options) {
1004
+ const headers = {};
1005
+ if (options?.start !== void 0 || options?.end !== void 0) {
1006
+ const start = options.start ?? 0;
1007
+ const end = options.end !== void 0 ? options.end : "";
1008
+ headers["Range"] = `bytes=${start}-${end}`;
1009
+ }
1010
+ const res = await withRetry(async () => {
1011
+ return await this.drive.files.get(
1012
+ { fileId, alt: "media", supportsAllDrives: true },
1013
+ { responseType: "stream", headers }
1014
+ );
1015
+ });
1016
+ return res.data;
1017
+ }
936
1018
  };
937
1019
  }
938
1020
  });
@@ -1061,6 +1143,19 @@ var init_query_builder = __esm({
1061
1143
  this.conditions.push(`(${condition})`);
1062
1144
  return this;
1063
1145
  }
1146
+ /**
1147
+ * Custom raw query condition (alias for raw)
1148
+ */
1149
+ custom(condition) {
1150
+ return this.raw(condition);
1151
+ }
1152
+ /**
1153
+ * Filter: Exact MD5 checksum match
1154
+ */
1155
+ md5(checksum) {
1156
+ this.conditions.push(`md5Checksum = '${this.escape(checksum)}'`);
1157
+ return this;
1158
+ }
1064
1159
  /**
1065
1160
  * Sort ordering (e.g. 'modifiedTime desc', 'name', 'folder,modifiedTime desc')
1066
1161
  */
@@ -1107,6 +1202,12 @@ var init_query_builder = __esm({
1107
1202
  });
1108
1203
  return res.data.files || [];
1109
1204
  }
1205
+ /**
1206
+ * Executes query and returns array of matching files (alias for list)
1207
+ */
1208
+ async execute() {
1209
+ return await this.list();
1210
+ }
1110
1211
  /**
1111
1212
  * Returns the first matching file, or null if not found
1112
1213
  */
@@ -1683,18 +1784,767 @@ var init_browser_login = __esm({
1683
1784
  }
1684
1785
  });
1685
1786
 
1787
+ // src/core/resource-refs.ts
1788
+ var DriveFileRef, DriveFolderRef;
1789
+ var init_resource_refs = __esm({
1790
+ "src/core/resource-refs.ts"() {
1791
+ "use strict";
1792
+ init_cjs_shims();
1793
+ DriveFileRef = class {
1794
+ drive;
1795
+ pathOrId;
1796
+ constructor(drive2, pathOrId) {
1797
+ this.drive = drive2;
1798
+ this.pathOrId = pathOrId;
1799
+ }
1800
+ /** Gets file metadata */
1801
+ async get() {
1802
+ return await this.drive.getFile(this.pathOrId);
1803
+ }
1804
+ /** Checks if the file exists */
1805
+ async exists() {
1806
+ return await this.drive.exists(this.pathOrId);
1807
+ }
1808
+ /** Reads file as UTF-8 string */
1809
+ async getText() {
1810
+ return await this.drive.getText(this.pathOrId);
1811
+ }
1812
+ /** Reads and parses JSON file */
1813
+ async getJson() {
1814
+ return await this.drive.getJson(this.pathOrId);
1815
+ }
1816
+ /** Downloads the file to destination */
1817
+ async download(optionsOrDestination) {
1818
+ const opts = typeof optionsOrDestination === "string" ? { destination: optionsOrDestination } : optionsOrDestination;
1819
+ return await this.drive.download(this.pathOrId, opts);
1820
+ }
1821
+ /** Moves the file to a new folder path or ID */
1822
+ async moveTo(newParentPathOrId) {
1823
+ return await this.drive.move(this.pathOrId, newParentPathOrId);
1824
+ }
1825
+ /** Copies the file to a target directory */
1826
+ async copyTo(parentPathOrId, newName) {
1827
+ return await this.drive.copy(this.pathOrId, { parent: parentPathOrId, name: newName });
1828
+ }
1829
+ /** Renames the file */
1830
+ async rename(newName) {
1831
+ return await this.drive.rename(this.pathOrId, newName);
1832
+ }
1833
+ /** Deletes the file (or moves to trash if permanent is false) */
1834
+ async delete(permanent = false) {
1835
+ return await this.drive.delete(this.pathOrId, permanent);
1836
+ }
1837
+ /** Moves file to trash */
1838
+ async trash() {
1839
+ return await this.drive.trash(this.pathOrId);
1840
+ }
1841
+ /** Shares file */
1842
+ async share(options) {
1843
+ return await this.drive.share(this.pathOrId, options);
1844
+ }
1845
+ /** Makes file publicly accessible */
1846
+ async sharePublic(role = "reader") {
1847
+ return await this.drive.sharePublic(this.pathOrId, role);
1848
+ }
1849
+ /** Gets public/preview links */
1850
+ async getLink() {
1851
+ return await this.drive.getShareableLink(this.pathOrId);
1852
+ }
1853
+ /** Returns a ReadableStream for this file, optionally with byte Range requests */
1854
+ async createReadStream(options) {
1855
+ return await this.drive.createReadStream(this.pathOrId, options);
1856
+ }
1857
+ /** Grants access to a specific email with custom role and notification */
1858
+ async grantAccess(options) {
1859
+ return await this.drive.grantAccess(this.pathOrId, options);
1860
+ }
1861
+ /** Revokes access by permission ID or user email */
1862
+ async revokeAccess(permissionIdOrEmail) {
1863
+ return await this.drive.revokeAccess(this.pathOrId, permissionIdOrEmail);
1864
+ }
1865
+ /** Lists all granted permissions on this file */
1866
+ async listPermissions() {
1867
+ return await this.drive.listPermissions(this.pathOrId);
1868
+ }
1869
+ };
1870
+ DriveFolderRef = class {
1871
+ drive;
1872
+ pathOrId;
1873
+ constructor(drive2, pathOrId) {
1874
+ this.drive = drive2;
1875
+ this.pathOrId = pathOrId;
1876
+ }
1877
+ /** Lists contents of this folder */
1878
+ async ls() {
1879
+ return await this.drive.ls(this.pathOrId);
1880
+ }
1881
+ /** Ensures this folder and subpaths exist (mkdir -p) */
1882
+ async mkdirp(subPath) {
1883
+ const target = subPath ? this.pathOrId.endsWith("/") ? `${this.pathOrId}${subPath}` : `${this.pathOrId}/${subPath}` : this.pathOrId;
1884
+ return await this.drive.mkdirp(target);
1885
+ }
1886
+ /** Uploads a file directly into this folder */
1887
+ async upload(source, options = {}) {
1888
+ return await this.drive.upload({
1889
+ ...options,
1890
+ source,
1891
+ parent: this.pathOrId
1892
+ });
1893
+ }
1894
+ /** Synchronizes a local directory into this remote folder */
1895
+ async syncFrom(localDir, options = {}) {
1896
+ return await this.drive.syncFolder(localDir, this.pathOrId, options);
1897
+ }
1898
+ /** Pulls this remote folder down to local directory */
1899
+ async pullTo(localDestinationDir, options = {}) {
1900
+ return await this.drive.pull(this.pathOrId, localDestinationDir, options);
1901
+ }
1902
+ /** Watches this folder for real-time changes */
1903
+ async watch(options = {}) {
1904
+ return await this.drive.watch(this.pathOrId, options);
1905
+ }
1906
+ /** Grants access to this entire folder */
1907
+ async grantAccess(options) {
1908
+ return await this.drive.grantAccess(this.pathOrId, options);
1909
+ }
1910
+ /** Creates a writable stream directly into a file inside this folder */
1911
+ async createWriteStream(fileName, options) {
1912
+ const targetPath = this.pathOrId.endsWith("/") ? `${this.pathOrId}${fileName}` : `${this.pathOrId}/${fileName}`;
1913
+ return await this.drive.createWriteStream(targetPath, options);
1914
+ }
1915
+ };
1916
+ }
1917
+ });
1918
+
1919
+ // src/core/plugins.ts
1920
+ var PluginManager;
1921
+ var init_plugins = __esm({
1922
+ "src/core/plugins.ts"() {
1923
+ "use strict";
1924
+ init_cjs_shims();
1925
+ PluginManager = class {
1926
+ plugins = [];
1927
+ use(plugin) {
1928
+ this.plugins.push(plugin);
1929
+ return this;
1930
+ }
1931
+ async runBeforeUpload(options) {
1932
+ let current = { ...options };
1933
+ for (const plugin of this.plugins) {
1934
+ if (plugin.beforeUpload) {
1935
+ const modified = await plugin.beforeUpload(current);
1936
+ if (modified) current = modified;
1937
+ }
1938
+ }
1939
+ return current;
1940
+ }
1941
+ async runAfterUpload(file) {
1942
+ let current = file;
1943
+ for (const plugin of this.plugins) {
1944
+ if (plugin.afterUpload) {
1945
+ const modified = await plugin.afterUpload(current);
1946
+ if (modified) current = modified;
1947
+ }
1948
+ }
1949
+ return current;
1950
+ }
1951
+ async runBeforeDownload(fileId, options) {
1952
+ let current = { ...options };
1953
+ for (const plugin of this.plugins) {
1954
+ if (plugin.beforeDownload) {
1955
+ const modified = await plugin.beforeDownload(fileId, current);
1956
+ if (modified) current = modified;
1957
+ }
1958
+ }
1959
+ return current;
1960
+ }
1961
+ async runAfterDownload(result) {
1962
+ let current = result;
1963
+ for (const plugin of this.plugins) {
1964
+ if (plugin.afterDownload) {
1965
+ const modified = await plugin.afterDownload(current);
1966
+ if (modified) current = modified;
1967
+ }
1968
+ }
1969
+ return current;
1970
+ }
1971
+ };
1972
+ }
1973
+ });
1974
+
1975
+ // src/core/cache.ts
1976
+ var import_node_os, import_node_path4, import_node_fs5, SqliteMetadataCache, MemoryMetadataCache;
1977
+ var init_cache = __esm({
1978
+ "src/core/cache.ts"() {
1979
+ "use strict";
1980
+ init_cjs_shims();
1981
+ import_node_os = __toESM(require("os"), 1);
1982
+ import_node_path4 = __toESM(require("path"), 1);
1983
+ import_node_fs5 = __toESM(require("fs"), 1);
1984
+ SqliteMetadataCache = class {
1985
+ db = null;
1986
+ dbPath;
1987
+ initialized = false;
1988
+ fallbackMemory;
1989
+ constructor(customPath) {
1990
+ if (customPath) {
1991
+ this.dbPath = customPath;
1992
+ } else {
1993
+ const dir = import_node_path4.default.join(import_node_os.default.homedir(), ".drivekit");
1994
+ if (!import_node_fs5.default.existsSync(dir)) {
1995
+ try {
1996
+ import_node_fs5.default.mkdirSync(dir, { recursive: true });
1997
+ } catch {
1998
+ }
1999
+ }
2000
+ this.dbPath = import_node_path4.default.join(dir, "cache.db");
2001
+ }
2002
+ }
2003
+ init() {
2004
+ if (this.initialized) return;
2005
+ try {
2006
+ const { DatabaseSync } = require("sqlite");
2007
+ if (!DatabaseSync) {
2008
+ throw new Error("DatabaseSync not available");
2009
+ }
2010
+ this.db = new DatabaseSync(this.dbPath);
2011
+ this.db.exec(`
2012
+ PRAGMA journal_mode = WAL;
2013
+ PRAGMA synchronous = NORMAL;
2014
+
2015
+ CREATE TABLE IF NOT EXISTS files (
2016
+ id TEXT PRIMARY KEY,
2017
+ name TEXT NOT NULL,
2018
+ mimeType TEXT NOT NULL,
2019
+ size INTEGER,
2020
+ parentId TEXT,
2021
+ path TEXT,
2022
+ md5Checksum TEXT,
2023
+ trashed INTEGER DEFAULT 0,
2024
+ modifiedTime TEXT,
2025
+ updatedAt INTEGER
2026
+ );
2027
+
2028
+ CREATE TABLE IF NOT EXISTS meta (
2029
+ key TEXT PRIMARY KEY,
2030
+ value TEXT NOT NULL
2031
+ );
2032
+
2033
+ CREATE INDEX IF NOT EXISTS idx_files_path ON files(path);
2034
+ CREATE INDEX IF NOT EXISTS idx_files_parent ON files(parentId);
2035
+ CREATE INDEX IF NOT EXISTS idx_files_md5 ON files(md5Checksum);
2036
+ CREATE INDEX IF NOT EXISTS idx_files_name ON files(name);
2037
+ `);
2038
+ this.initialized = true;
2039
+ } catch (err) {
2040
+ this.fallbackMemory = new MemoryMetadataCache();
2041
+ this.fallbackMemory.init();
2042
+ this.initialized = true;
2043
+ this.db = null;
2044
+ }
2045
+ }
2046
+ getById(id) {
2047
+ if (this.fallbackMemory) return this.fallbackMemory.getById(id);
2048
+ if (!this.initialized || !this.db) return null;
2049
+ const stmt = this.db.prepare("SELECT * FROM files WHERE id = ?");
2050
+ const row = stmt.get(id);
2051
+ return row ? this.mapRow(row) : null;
2052
+ }
2053
+ getByPath(normalizedPath) {
2054
+ if (this.fallbackMemory) return this.fallbackMemory.getByPath(normalizedPath);
2055
+ if (!this.initialized || !this.db) return null;
2056
+ const stmt = this.db.prepare("SELECT * FROM files WHERE path = ? AND trashed = 0 LIMIT 1");
2057
+ const row = stmt.get(normalizedPath);
2058
+ return row ? this.mapRow(row) : null;
2059
+ }
2060
+ getChildren(parentId) {
2061
+ if (this.fallbackMemory) return this.fallbackMemory.getChildren(parentId);
2062
+ if (!this.initialized || !this.db) return [];
2063
+ const stmt = this.db.prepare("SELECT * FROM files WHERE parentId = ? AND trashed = 0 ORDER BY name ASC");
2064
+ const rows = stmt.all(parentId);
2065
+ return rows.map((r) => this.mapRow(r));
2066
+ }
2067
+ findByMd5(md5) {
2068
+ if (this.fallbackMemory) return this.fallbackMemory.findByMd5(md5);
2069
+ if (!this.initialized || !this.db || !md5) return null;
2070
+ const stmt = this.db.prepare("SELECT * FROM files WHERE md5Checksum = ? AND trashed = 0 LIMIT 1");
2071
+ const row = stmt.get(md5.toLowerCase());
2072
+ return row ? this.mapRow(row) : null;
2073
+ }
2074
+ searchByName(query) {
2075
+ if (this.fallbackMemory) return this.fallbackMemory.searchByName(query);
2076
+ if (!this.initialized || !this.db) return [];
2077
+ const stmt = this.db.prepare("SELECT * FROM files WHERE name LIKE ? AND trashed = 0 LIMIT 50");
2078
+ const rows = stmt.all(`%${query}%`);
2079
+ return rows.map((r) => this.mapRow(r));
2080
+ }
2081
+ upsertFile(entry) {
2082
+ if (this.fallbackMemory) {
2083
+ this.fallbackMemory.upsertFile(entry);
2084
+ return;
2085
+ }
2086
+ if (!this.initialized || !this.db) return;
2087
+ const stmt = this.db.prepare(`
2088
+ INSERT INTO files (id, name, mimeType, size, parentId, path, md5Checksum, trashed, modifiedTime, updatedAt)
2089
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2090
+ ON CONFLICT(id) DO UPDATE SET
2091
+ name = excluded.name,
2092
+ mimeType = excluded.mimeType,
2093
+ size = excluded.size,
2094
+ parentId = excluded.parentId,
2095
+ path = COALESCE(excluded.path, files.path),
2096
+ md5Checksum = excluded.md5Checksum,
2097
+ trashed = excluded.trashed,
2098
+ modifiedTime = excluded.modifiedTime,
2099
+ updatedAt = excluded.updatedAt
2100
+ `);
2101
+ stmt.run(
2102
+ entry.id,
2103
+ entry.name,
2104
+ entry.mimeType,
2105
+ entry.size ?? null,
2106
+ entry.parentId ?? null,
2107
+ entry.path ?? null,
2108
+ entry.md5Checksum ? entry.md5Checksum.toLowerCase() : null,
2109
+ entry.trashed ? 1 : 0,
2110
+ entry.modifiedTime ?? null,
2111
+ entry.updatedAt ?? Date.now()
2112
+ );
2113
+ }
2114
+ upsertFiles(entries) {
2115
+ if (this.fallbackMemory) {
2116
+ this.fallbackMemory.upsertFiles(entries);
2117
+ return;
2118
+ }
2119
+ if (!this.initialized || !this.db || entries.length === 0) return;
2120
+ this.db.exec("BEGIN TRANSACTION;");
2121
+ try {
2122
+ for (const entry of entries) {
2123
+ this.upsertFile(entry);
2124
+ }
2125
+ this.db.exec("COMMIT;");
2126
+ } catch (e) {
2127
+ this.db.exec("ROLLBACK;");
2128
+ throw e;
2129
+ }
2130
+ }
2131
+ deleteFile(id) {
2132
+ if (this.fallbackMemory) {
2133
+ this.fallbackMemory.deleteFile(id);
2134
+ return;
2135
+ }
2136
+ if (!this.initialized || !this.db) return;
2137
+ const stmt = this.db.prepare("DELETE FROM files WHERE id = ?");
2138
+ stmt.run(id);
2139
+ }
2140
+ clear() {
2141
+ if (this.fallbackMemory) {
2142
+ this.fallbackMemory.clear();
2143
+ return;
2144
+ }
2145
+ if (!this.initialized || !this.db) return;
2146
+ this.db.exec("DELETE FROM files; DELETE FROM meta;");
2147
+ }
2148
+ getMeta(key) {
2149
+ if (this.fallbackMemory) return this.fallbackMemory.getMeta(key);
2150
+ if (!this.initialized || !this.db) return null;
2151
+ const stmt = this.db.prepare("SELECT value FROM meta WHERE key = ?");
2152
+ const row = stmt.get(key);
2153
+ return row ? row.value : null;
2154
+ }
2155
+ setMeta(key, value) {
2156
+ if (this.fallbackMemory) {
2157
+ this.fallbackMemory.setMeta(key, value);
2158
+ return;
2159
+ }
2160
+ if (!this.initialized || !this.db) return;
2161
+ const stmt = this.db.prepare(`
2162
+ INSERT INTO meta (key, value) VALUES (?, ?)
2163
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value
2164
+ `);
2165
+ stmt.run(key, value);
2166
+ }
2167
+ getStats() {
2168
+ if (this.fallbackMemory) return this.fallbackMemory.getStats();
2169
+ if (!this.initialized || !this.db) {
2170
+ return {
2171
+ fileCount: 0,
2172
+ folderCount: 0,
2173
+ totalSizeBytes: 0,
2174
+ lastSyncTime: null,
2175
+ databasePath: this.dbPath
2176
+ };
2177
+ }
2178
+ const fileCountRow = this.db.prepare(
2179
+ "SELECT COUNT(*) as count FROM files WHERE mimeType != 'application/vnd.google-apps.folder' AND trashed = 0"
2180
+ ).get();
2181
+ const folderCountRow = this.db.prepare(
2182
+ "SELECT COUNT(*) as count FROM files WHERE mimeType = 'application/vnd.google-apps.folder' AND trashed = 0"
2183
+ ).get();
2184
+ const totalSizeRow = this.db.prepare(
2185
+ "SELECT SUM(size) as total FROM files WHERE trashed = 0"
2186
+ ).get();
2187
+ const lastSync = this.getMeta("last_sync_timestamp");
2188
+ return {
2189
+ fileCount: fileCountRow?.count || 0,
2190
+ folderCount: folderCountRow?.count || 0,
2191
+ totalSizeBytes: totalSizeRow?.total || 0,
2192
+ lastSyncTime: lastSync,
2193
+ databasePath: this.dbPath
2194
+ };
2195
+ }
2196
+ close() {
2197
+ if (this.fallbackMemory) {
2198
+ this.fallbackMemory.close();
2199
+ this.fallbackMemory = void 0;
2200
+ }
2201
+ if (this.db) {
2202
+ try {
2203
+ this.db.close();
2204
+ } catch {
2205
+ }
2206
+ this.initialized = false;
2207
+ this.db = null;
2208
+ }
2209
+ }
2210
+ mapRow(row) {
2211
+ return {
2212
+ id: row.id,
2213
+ name: row.name,
2214
+ mimeType: row.mimeType,
2215
+ size: row.size != null ? Number(row.size) : void 0,
2216
+ parentId: row.parentId || void 0,
2217
+ path: row.path || void 0,
2218
+ md5Checksum: row.md5Checksum || void 0,
2219
+ trashed: row.trashed === 1,
2220
+ modifiedTime: row.modifiedTime || void 0,
2221
+ updatedAt: row.updatedAt != null ? Number(row.updatedAt) : void 0
2222
+ };
2223
+ }
2224
+ };
2225
+ MemoryMetadataCache = class {
2226
+ files = /* @__PURE__ */ new Map();
2227
+ meta = /* @__PURE__ */ new Map();
2228
+ init() {
2229
+ }
2230
+ getById(id) {
2231
+ return this.files.get(id) || null;
2232
+ }
2233
+ getByPath(normalizedPath) {
2234
+ for (const f of this.files.values()) {
2235
+ if (f.path === normalizedPath && !f.trashed) return f;
2236
+ }
2237
+ return null;
2238
+ }
2239
+ getChildren(parentId) {
2240
+ const list = [];
2241
+ for (const f of this.files.values()) {
2242
+ if (f.parentId === parentId && !f.trashed) list.push(f);
2243
+ }
2244
+ return list;
2245
+ }
2246
+ findByMd5(md5) {
2247
+ const target = md5.toLowerCase();
2248
+ for (const f of this.files.values()) {
2249
+ if (f.md5Checksum?.toLowerCase() === target && !f.trashed) return f;
2250
+ }
2251
+ return null;
2252
+ }
2253
+ searchByName(query) {
2254
+ const q = query.toLowerCase();
2255
+ const list = [];
2256
+ for (const f of this.files.values()) {
2257
+ if (f.name.toLowerCase().includes(q) && !f.trashed) list.push(f);
2258
+ }
2259
+ return list;
2260
+ }
2261
+ upsertFile(entry) {
2262
+ this.files.set(entry.id, { ...entry, updatedAt: Date.now() });
2263
+ }
2264
+ upsertFiles(entries) {
2265
+ for (const e of entries) this.upsertFile(e);
2266
+ }
2267
+ deleteFile(id) {
2268
+ this.files.delete(id);
2269
+ }
2270
+ clear() {
2271
+ this.files.clear();
2272
+ this.meta.clear();
2273
+ }
2274
+ getMeta(key) {
2275
+ return this.meta.get(key) || null;
2276
+ }
2277
+ setMeta(key, value) {
2278
+ this.meta.set(key, value);
2279
+ }
2280
+ getStats() {
2281
+ let fileCount = 0;
2282
+ let folderCount = 0;
2283
+ let totalSizeBytes = 0;
2284
+ for (const f of this.files.values()) {
2285
+ if (f.trashed) continue;
2286
+ if (f.mimeType === "application/vnd.google-apps.folder") folderCount++;
2287
+ else {
2288
+ fileCount++;
2289
+ totalSizeBytes += f.size || 0;
2290
+ }
2291
+ }
2292
+ return {
2293
+ fileCount,
2294
+ folderCount,
2295
+ totalSizeBytes,
2296
+ lastSyncTime: this.meta.get("last_sync_timestamp") || null,
2297
+ databasePath: ":memory:"
2298
+ };
2299
+ }
2300
+ close() {
2301
+ this.clear();
2302
+ }
2303
+ };
2304
+ }
2305
+ });
2306
+
2307
+ // src/server/webdav.ts
2308
+ var webdav_exports = {};
2309
+ __export(webdav_exports, {
2310
+ startWebDAVServer: () => startWebDAVServer
2311
+ });
2312
+ async function startWebDAVServer(drive2, options = {}) {
2313
+ const port = options.port || 8080;
2314
+ const host = options.host || "127.0.0.1";
2315
+ await drive2.init();
2316
+ const server = import_node_http2.default.createServer(async (req, res) => {
2317
+ try {
2318
+ const parsedUrl = import_node_url.default.parse(req.url || "/", true);
2319
+ const decodedPath = decodeURIComponent(parsedUrl.pathname || "/");
2320
+ const virtualPath = decodedPath === "" ? "/" : decodedPath;
2321
+ switch (req.method) {
2322
+ case "OPTIONS": {
2323
+ res.writeHead(200, {
2324
+ DAV: "1, 2",
2325
+ Allow: "OPTIONS, GET, HEAD, POST, PUT, DELETE, MKCOL, MOVE, COPY, PROPFIND",
2326
+ "MS-Author-Via": "DAV"
2327
+ });
2328
+ res.end();
2329
+ return;
2330
+ }
2331
+ case "PROPFIND": {
2332
+ const depth = req.headers["depth"] || "1";
2333
+ const xml = await handlePropfind(drive2, virtualPath, depth);
2334
+ res.writeHead(207, {
2335
+ "Content-Type": "application/xml; charset=utf-8"
2336
+ });
2337
+ res.end(xml);
2338
+ return;
2339
+ }
2340
+ case "GET":
2341
+ case "HEAD": {
2342
+ if (virtualPath === "/" || virtualPath === "") {
2343
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
2344
+ res.end("<h1>DriveKit WebDAV Server Running</h1><p>Connect via Finder or WebDAV client.</p>");
2345
+ return;
2346
+ }
2347
+ try {
2348
+ const file = await drive2.getFile(virtualPath);
2349
+ if (file.mimeType === "application/vnd.google-apps.folder") {
2350
+ res.writeHead(405, { "Content-Type": "text/plain" });
2351
+ res.end("Cannot GET a directory");
2352
+ return;
2353
+ }
2354
+ const stream = await drive2.createReadStream(virtualPath);
2355
+ res.writeHead(200, {
2356
+ "Content-Type": file.mimeType || "application/octet-stream",
2357
+ "Content-Length": file.size || void 0
2358
+ });
2359
+ if (req.method === "HEAD") {
2360
+ res.end();
2361
+ } else {
2362
+ stream.pipe(res);
2363
+ }
2364
+ } catch (e) {
2365
+ res.writeHead(404, { "Content-Type": "text/plain" });
2366
+ res.end("File Not Found");
2367
+ }
2368
+ return;
2369
+ }
2370
+ case "PUT": {
2371
+ const remoteDir = import_node_path5.default.dirname(virtualPath);
2372
+ const fileName = import_node_path5.default.basename(virtualPath);
2373
+ await drive2.mkdirp(remoteDir);
2374
+ const chunks = [];
2375
+ req.on("data", (chunk) => chunks.push(chunk));
2376
+ req.on("end", async () => {
2377
+ try {
2378
+ const buffer = Buffer.concat(chunks);
2379
+ await drive2.upload({
2380
+ source: buffer,
2381
+ filename: fileName,
2382
+ parent: remoteDir,
2383
+ overwrite: true
2384
+ });
2385
+ res.writeHead(201, { "Content-Type": "text/plain" });
2386
+ res.end("Created");
2387
+ } catch (err) {
2388
+ res.writeHead(500, { "Content-Type": "text/plain" });
2389
+ res.end(err.message || "Upload failed");
2390
+ }
2391
+ });
2392
+ return;
2393
+ }
2394
+ case "MKCOL": {
2395
+ try {
2396
+ await drive2.mkdirp(virtualPath);
2397
+ res.writeHead(201, { "Content-Type": "text/plain" });
2398
+ res.end("Collection Created");
2399
+ } catch (err) {
2400
+ res.writeHead(500, { "Content-Type": "text/plain" });
2401
+ res.end(err.message);
2402
+ }
2403
+ return;
2404
+ }
2405
+ case "DELETE": {
2406
+ try {
2407
+ await drive2.delete(virtualPath, true);
2408
+ res.writeHead(204);
2409
+ res.end();
2410
+ } catch (err) {
2411
+ res.writeHead(404, { "Content-Type": "text/plain" });
2412
+ res.end("Not Found");
2413
+ }
2414
+ return;
2415
+ }
2416
+ case "MOVE": {
2417
+ const destination = req.headers["destination"];
2418
+ if (!destination || typeof destination !== "string") {
2419
+ res.writeHead(400, { "Content-Type": "text/plain" });
2420
+ res.end("Destination header missing");
2421
+ return;
2422
+ }
2423
+ const destUrl = import_node_url.default.parse(destination);
2424
+ const destPath = decodeURIComponent(destUrl.pathname || "");
2425
+ const newName = import_node_path5.default.basename(destPath);
2426
+ const newParent = import_node_path5.default.dirname(destPath);
2427
+ try {
2428
+ await drive2.move(virtualPath, newParent);
2429
+ if (newName !== import_node_path5.default.basename(virtualPath)) {
2430
+ await drive2.rename(destPath, newName);
2431
+ }
2432
+ res.writeHead(201);
2433
+ res.end("Moved");
2434
+ } catch (err) {
2435
+ res.writeHead(500, { "Content-Type": "text/plain" });
2436
+ res.end(err.message);
2437
+ }
2438
+ return;
2439
+ }
2440
+ default: {
2441
+ res.writeHead(501, { "Content-Type": "text/plain" });
2442
+ res.end("Method Not Implemented");
2443
+ }
2444
+ }
2445
+ } catch (globalErr) {
2446
+ res.writeHead(500, { "Content-Type": "text/plain" });
2447
+ res.end(`Internal Server Error: ${globalErr.message}`);
2448
+ }
2449
+ });
2450
+ return new Promise((resolve) => {
2451
+ server.listen(port, host, () => {
2452
+ const serverUrl = `http://${host}:${port}`;
2453
+ resolve({
2454
+ server,
2455
+ url: serverUrl,
2456
+ close: () => new Promise((resClose) => server.close(() => resClose()))
2457
+ });
2458
+ });
2459
+ });
2460
+ }
2461
+ async function handlePropfind(drive2, virtualPath, depth) {
2462
+ const responses = [];
2463
+ let isFolder = false;
2464
+ let selfItem = null;
2465
+ if (virtualPath === "/" || virtualPath === "") {
2466
+ isFolder = true;
2467
+ responses.push(renderWebDAVResponse("/", true, 0, (/* @__PURE__ */ new Date()).toISOString()));
2468
+ } else {
2469
+ try {
2470
+ selfItem = await drive2.getFile(virtualPath);
2471
+ isFolder = selfItem.mimeType === "application/vnd.google-apps.folder";
2472
+ responses.push(
2473
+ renderWebDAVResponse(
2474
+ virtualPath,
2475
+ isFolder,
2476
+ selfItem.size ? parseInt(selfItem.size, 10) : 0,
2477
+ selfItem.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
2478
+ )
2479
+ );
2480
+ } catch {
2481
+ return `<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:"></D:multistatus>`;
2482
+ }
2483
+ }
2484
+ if (isFolder && depth !== "0") {
2485
+ try {
2486
+ const children = await drive2.ls(virtualPath);
2487
+ for (const child of children) {
2488
+ const childIsFolder = child.mimeType === "application/vnd.google-apps.folder";
2489
+ const childPath = virtualPath === "/" ? `/${child.name}` : `${virtualPath}/${child.name}`;
2490
+ responses.push(
2491
+ renderWebDAVResponse(
2492
+ childPath,
2493
+ childIsFolder,
2494
+ child.size ? parseInt(child.size, 10) : 0,
2495
+ child.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
2496
+ )
2497
+ );
2498
+ }
2499
+ } catch {
2500
+ }
2501
+ }
2502
+ return `<?xml version="1.0" encoding="utf-8"?>
2503
+ <D:multistatus xmlns:D="DAV:">
2504
+ ${responses.join("\n")}
2505
+ </D:multistatus>`;
2506
+ }
2507
+ function renderWebDAVResponse(href, isDir, size, modifiedTime) {
2508
+ const encodedHref = encodeURI(href);
2509
+ const resourceType = isDir ? "<D:collection/>" : "";
2510
+ const dateFormatted = new Date(modifiedTime).toUTCString();
2511
+ return ` <D:response>
2512
+ <D:href>${encodedHref}</D:href>
2513
+ <D:propstat>
2514
+ <D:prop>
2515
+ <D:displayname>${import_node_path5.default.basename(href) || "root"}</D:displayname>
2516
+ <D:resourcetype>${resourceType}</D:resourcetype>
2517
+ <D:getcontentlength>${isDir ? "0" : size}</D:getcontentlength>
2518
+ <D:getlastmodified>${dateFormatted}</D:getlastmodified>
2519
+ <D:status>HTTP/1.1 200 OK</D:status>
2520
+ </D:prop>
2521
+ <D:status>HTTP/1.1 200 OK</D:status>
2522
+ </D:propstat>
2523
+ </D:response>`;
2524
+ }
2525
+ var import_node_http2, import_node_url, import_node_path5;
2526
+ var init_webdav = __esm({
2527
+ "src/server/webdav.ts"() {
2528
+ "use strict";
2529
+ init_cjs_shims();
2530
+ import_node_http2 = __toESM(require("http"), 1);
2531
+ import_node_url = __toESM(require("url"), 1);
2532
+ import_node_path5 = __toESM(require("path"), 1);
2533
+ }
2534
+ });
2535
+
1686
2536
  // src/core/client.ts
1687
2537
  var client_exports = {};
1688
2538
  __export(client_exports, {
1689
2539
  DriveKit: () => DriveKit
1690
2540
  });
1691
- var import_node_fs5, import_node_path4, import_drive3, DriveKit;
2541
+ var import_node_fs6, import_node_path6, import_drive3, DriveKit;
1692
2542
  var init_client = __esm({
1693
2543
  "src/core/client.ts"() {
1694
2544
  "use strict";
1695
2545
  init_cjs_shims();
1696
- import_node_fs5 = __toESM(require("fs"), 1);
1697
- import_node_path4 = __toESM(require("path"), 1);
2546
+ import_node_fs6 = __toESM(require("fs"), 1);
2547
+ import_node_path6 = __toESM(require("path"), 1);
1698
2548
  import_drive3 = require("@googleapis/drive");
1699
2549
  init_authenticator();
1700
2550
  init_path_resolver();
@@ -1706,22 +2556,46 @@ var init_client = __esm({
1706
2556
  init_storage_cleaner();
1707
2557
  init_smart_sync();
1708
2558
  init_browser_login();
2559
+ init_resource_refs();
2560
+ init_plugins();
1709
2561
  init_retry();
1710
2562
  init_format();
1711
2563
  init_mime();
1712
- DriveKit = class {
2564
+ init_cache();
2565
+ DriveKit = class _DriveKit {
1713
2566
  options;
1714
2567
  authenticator;
1715
2568
  driveClient = null;
1716
2569
  pathResolverInstance = null;
1717
2570
  uploaderInstance = null;
1718
2571
  downloaderInstance = null;
2572
+ metadataCacheInstance = null;
1719
2573
  rootFolderId;
2574
+ pluginManager = new PluginManager();
1720
2575
  constructor(options = {}) {
1721
2576
  this.options = options;
1722
2577
  this.rootFolderId = options.rootFolderId || "root";
1723
2578
  this.authenticator = new DriveAuthenticator(options.auth);
1724
2579
  }
2580
+ /**
2581
+ * Registers a middleware plugin into DriveKit lifecycle
2582
+ */
2583
+ use(plugin) {
2584
+ this.pluginManager.use(plugin);
2585
+ return this;
2586
+ }
2587
+ /**
2588
+ * Returns a fluent, chained reference to a specific file
2589
+ */
2590
+ file(pathOrId) {
2591
+ return new DriveFileRef(this, pathOrId);
2592
+ }
2593
+ /**
2594
+ * Returns a fluent, chained reference to a specific folder
2595
+ */
2596
+ folder(pathOrId) {
2597
+ return new DriveFolderRef(this, pathOrId);
2598
+ }
1725
2599
  /**
1726
2600
  * Initializes the Google Drive API client (lazy-loaded if not called explicitly)
1727
2601
  */
@@ -1729,9 +2603,14 @@ var init_client = __esm({
1729
2603
  if (!this.driveClient) {
1730
2604
  const auth = await this.authenticator.getAuthClient();
1731
2605
  this.driveClient = (0, import_drive3.drive)({ version: "v3", auth });
2606
+ if (this.options.enablePersistentCache !== false) {
2607
+ this.metadataCacheInstance = new SqliteMetadataCache(this.options.cacheDatabasePath);
2608
+ this.metadataCacheInstance.init();
2609
+ }
1732
2610
  this.pathResolverInstance = new PathResolver(this.driveClient, this.rootFolderId, {
1733
2611
  enableCache: this.options.enablePathCache ?? true,
1734
- cacheTTL: this.options.pathCacheTTL
2612
+ cacheTTL: this.options.pathCacheTTL,
2613
+ metadataCache: this.metadataCacheInstance || void 0
1735
2614
  });
1736
2615
  this.uploaderInstance = new ResumableUploader(
1737
2616
  this.driveClient,
@@ -1830,21 +2709,78 @@ var init_client = __esm({
1830
2709
  * - Real-time progress callback: % complete, transfer speed (MB/s), ETA
1831
2710
  */
1832
2711
  async upload(options) {
2712
+ const opts = await this.pluginManager.runBeforeUpload(options);
1833
2713
  const uploader = await this.getUploader();
1834
- let parentId = options.parent;
2714
+ let parentId = opts.parent;
1835
2715
  if (parentId && parentId.startsWith("/")) {
1836
2716
  parentId = await this.mkdirp(parentId);
1837
2717
  }
1838
- if (options.overwrite && options.name && parentId) {
1839
- const existing = await this.query().inFolder(parentId).nameEquals(options.name).notTrashed().first();
2718
+ const targetName = opts.name || opts.filename;
2719
+ if (opts.overwrite && targetName && parentId) {
2720
+ const existing = await this.query().inFolder(parentId).nameEquals(targetName).notTrashed().first();
1840
2721
  if (existing?.id) {
1841
2722
  await this.delete(existing.id, true);
1842
2723
  }
1843
2724
  }
1844
- return await uploader.upload({
1845
- ...options,
2725
+ if (opts.deduplicate && typeof opts.source === "string" && import_node_fs6.default.existsSync(opts.source)) {
2726
+ const localMd5 = await calculateFileMd5(opts.source);
2727
+ let existingId;
2728
+ if (this.metadataCacheInstance) {
2729
+ const cached = this.metadataCacheInstance.findByMd5(localMd5);
2730
+ if (cached) existingId = cached.id;
2731
+ }
2732
+ if (!existingId) {
2733
+ const found = await this.query().md5(localMd5).notTrashed().first();
2734
+ if (found?.id) {
2735
+ existingId = found.id;
2736
+ }
2737
+ }
2738
+ if (existingId) {
2739
+ const fileName = targetName || import_node_path6.default.basename(opts.source);
2740
+ const raw = await this.getRawClient();
2741
+ const copyRes = await withRetry(async () => {
2742
+ return await raw.files.copy({
2743
+ fileId: existingId,
2744
+ requestBody: {
2745
+ name: fileName,
2746
+ parents: parentId ? [parentId] : void 0,
2747
+ description: opts.description
2748
+ },
2749
+ fields: "id, name, mimeType, size, modifiedTime, md5Checksum",
2750
+ supportsAllDrives: true
2751
+ });
2752
+ });
2753
+ const file = copyRes.data;
2754
+ if (this.metadataCacheInstance && file.id) {
2755
+ this.metadataCacheInstance.upsertFile({
2756
+ id: file.id,
2757
+ name: file.name || fileName,
2758
+ mimeType: file.mimeType || "",
2759
+ size: file.size ? parseInt(file.size, 10) : void 0,
2760
+ parentId,
2761
+ md5Checksum: localMd5,
2762
+ trashed: false
2763
+ });
2764
+ }
2765
+ return await this.pluginManager.runAfterUpload(file);
2766
+ }
2767
+ }
2768
+ const uploaded = await uploader.upload({
2769
+ ...opts,
2770
+ name: targetName,
1846
2771
  parent: parentId
1847
2772
  });
2773
+ if (this.metadataCacheInstance && uploaded.id) {
2774
+ this.metadataCacheInstance.upsertFile({
2775
+ id: uploaded.id,
2776
+ name: uploaded.name || targetName || "untitled",
2777
+ mimeType: uploaded.mimeType || "",
2778
+ size: uploaded.size ? parseInt(uploaded.size, 10) : void 0,
2779
+ parentId,
2780
+ trashed: false
2781
+ });
2782
+ }
2783
+ return await this.pluginManager.runAfterUpload(uploaded);
1848
2784
  }
1849
2785
  /**
1850
2786
  * Downloads a file from Google Drive:
@@ -1854,8 +2790,10 @@ var init_client = __esm({
1854
2790
  */
1855
2791
  async download(fileIdOrPath, options = {}) {
1856
2792
  const fileId = await this.resolveId(fileIdOrPath);
2793
+ const processedOpts = await this.pluginManager.runBeforeDownload(fileId, options);
1857
2794
  const downloader = await this.getDownloader();
1858
- return await downloader.download(fileId, options);
2795
+ const result = await downloader.download(fileId, processedOpts);
2796
+ return await this.pluginManager.runAfterDownload(result);
1859
2797
  }
1860
2798
  /**
1861
2799
  * Gets file metadata
@@ -2082,16 +3020,16 @@ var init_client = __esm({
2082
3020
  durationMs: 0
2083
3021
  };
2084
3022
  const collectFiles = async (dir, base) => {
2085
- const entries = await import_node_fs5.default.promises.readdir(dir, { withFileTypes: true });
3023
+ const entries = await import_node_fs6.default.promises.readdir(dir, { withFileTypes: true });
2086
3024
  const files = [];
2087
3025
  for (const entry of entries) {
2088
- const fullPath = import_node_path4.default.join(dir, entry.name);
2089
- const relPath = import_node_path4.default.join(base, entry.name);
3026
+ const fullPath = import_node_path6.default.join(dir, entry.name);
3027
+ const relPath = import_node_path6.default.join(base, entry.name);
2090
3028
  if (entry.isDirectory()) {
2091
3029
  const sub = await collectFiles(fullPath, relPath);
2092
3030
  files.push(...sub);
2093
3031
  } else if (entry.isFile()) {
2094
- const stat = await import_node_fs5.default.promises.stat(fullPath);
3032
+ const stat = await import_node_fs6.default.promises.stat(fullPath);
2095
3033
  files.push({ fullPath, relPath, size: stat.size });
2096
3034
  }
2097
3035
  }
@@ -2104,11 +3042,11 @@ var init_client = __esm({
2104
3042
  if (remoteDirCache.has(relDir)) {
2105
3043
  return remoteDirCache.get(relDir);
2106
3044
  }
2107
- const parts = relDir.split(import_node_path4.default.sep).filter(Boolean);
3045
+ const parts = relDir.split(import_node_path6.default.sep).filter(Boolean);
2108
3046
  let currentParent = targetFolderId;
2109
3047
  let currentRel = "";
2110
3048
  for (const part of parts) {
2111
- currentRel = currentRel ? import_node_path4.default.join(currentRel, part) : part;
3049
+ currentRel = currentRel ? import_node_path6.default.join(currentRel, part) : part;
2112
3050
  if (remoteDirCache.has(currentRel)) {
2113
3051
  currentParent = remoteDirCache.get(currentRel);
2114
3052
  continue;
@@ -2137,8 +3075,8 @@ var init_client = __esm({
2137
3075
  };
2138
3076
  await pool.map(allFiles, async (fileItem) => {
2139
3077
  try {
2140
- const relDir = import_node_path4.default.dirname(fileItem.relPath);
2141
- const fileName = import_node_path4.default.basename(fileItem.relPath);
3078
+ const relDir = import_node_path6.default.dirname(fileItem.relPath);
3079
+ const fileName = import_node_path6.default.basename(fileItem.relPath);
2142
3080
  const parentFolderId = await ensureRemoteSubdir(relDir === "." ? "" : relDir);
2143
3081
  if (options.onFileStart) {
2144
3082
  options.onFileStart(fileItem.fullPath, fileItem.relPath);
@@ -2256,6 +3194,217 @@ var init_client = __esm({
2256
3194
  const engine = new SmartSyncEngine(this.driveClient);
2257
3195
  return await engine.pullFolder(folderId, localDestinationDir, options);
2258
3196
  }
3197
+ // ==========================================
3198
+ // STREAMS & RANGE REQUESTS
3199
+ // ==========================================
3200
+ /**
3201
+ * Creates a readable stream for a file, supporting partial range requests
3202
+ */
3203
+ async createReadStream(pathOrId, options) {
3204
+ const fileId = await this.resolveId(pathOrId);
3205
+ const downloader = await this.getDownloader();
3206
+ return await downloader.createReadStream(fileId, options);
3207
+ }
3208
+ /**
3209
+ * Creates a writable stream directly into Google Drive
3210
+ */
3211
+ async createWriteStream(remotePath, options = {}) {
3212
+ await this.init();
3213
+ const { PassThrough } = await import("stream");
3214
+ const passThrough = new PassThrough();
3215
+ const remoteDir = import_node_path6.default.dirname(remotePath);
3216
+ const fileName = options.name || options.filename || import_node_path6.default.basename(remotePath);
3217
+ const targetParentId = remoteDir === "." || remoteDir === "/" ? this.rootFolderId : await this.mkdirp(remoteDir);
3218
+ const mimeType = options.mimeType || "application/octet-stream";
3219
+ const raw = this.driveClient;
3220
+ raw.files.create({
3221
+ requestBody: {
3222
+ name: fileName,
3223
+ parents: [targetParentId],
3224
+ description: options.description
3225
+ },
3226
+ media: {
3227
+ mimeType,
3228
+ body: passThrough
3229
+ },
3230
+ fields: "id, name, mimeType, size, md5Checksum",
3231
+ supportsAllDrives: true
3232
+ }).then((res) => {
3233
+ if (res.data.id && this.metadataCacheInstance) {
3234
+ this.metadataCacheInstance.upsertFile({
3235
+ id: res.data.id,
3236
+ name: fileName,
3237
+ mimeType,
3238
+ parentId: targetParentId,
3239
+ path: remotePath,
3240
+ trashed: false
3241
+ });
3242
+ }
3243
+ }).catch((err) => {
3244
+ passThrough.destroy(err);
3245
+ });
3246
+ return passThrough;
3247
+ }
3248
+ // ==========================================
3249
+ // METADATA CACHE OPERATIONS
3250
+ // ==========================================
3251
+ /**
3252
+ * Returns the active persistent metadata cache instance (SQLite/Memory)
3253
+ */
3254
+ async getMetadataCache() {
3255
+ await this.init();
3256
+ return this.metadataCacheInstance;
3257
+ }
3258
+ /**
3259
+ * Returns cache statistics (total files, folders, size, last sync)
3260
+ */
3261
+ async getCacheStats() {
3262
+ await this.init();
3263
+ return this.metadataCacheInstance ? this.metadataCacheInstance.getStats() : null;
3264
+ }
3265
+ /**
3266
+ * Clears the path and metadata cache
3267
+ */
3268
+ async clearCache() {
3269
+ await this.init();
3270
+ if (this.pathResolverInstance) {
3271
+ this.pathResolverInstance.clearCache();
3272
+ }
3273
+ }
3274
+ /**
3275
+ * Crawls and indexes Google Drive metadata into the local SQLite database for instant 0ms lookups
3276
+ */
3277
+ async syncCache(options) {
3278
+ await this.init();
3279
+ if (!this.metadataCacheInstance) {
3280
+ throw new Error("Persistent cache is disabled on this DriveKit instance");
3281
+ }
3282
+ const client = this.driveClient;
3283
+ let pageToken = void 0;
3284
+ let totalScanned = 0;
3285
+ do {
3286
+ const res = await withRetry(async () => {
3287
+ return await client.files.list({
3288
+ pageSize: 1e3,
3289
+ pageToken,
3290
+ fields: "nextPageToken, files(id, name, mimeType, size, parents, md5Checksum, trashed, modifiedTime)",
3291
+ spaces: "drive",
3292
+ supportsAllDrives: true,
3293
+ includeItemsFromAllDrives: true,
3294
+ q: "trashed = false"
3295
+ });
3296
+ });
3297
+ const files = res.data.files || [];
3298
+ const entries = files.map((f) => ({
3299
+ id: f.id,
3300
+ name: f.name || "untitled",
3301
+ mimeType: f.mimeType || "",
3302
+ size: f.size ? parseInt(f.size, 10) : void 0,
3303
+ parentId: f.parents?.[0],
3304
+ md5Checksum: f.md5Checksum || void 0,
3305
+ trashed: !!f.trashed,
3306
+ modifiedTime: f.modifiedTime || void 0
3307
+ }));
3308
+ this.metadataCacheInstance.upsertFiles(entries);
3309
+ totalScanned += entries.length;
3310
+ options?.onProgress?.(totalScanned);
3311
+ pageToken = res.data.nextPageToken || void 0;
3312
+ } while (pageToken);
3313
+ this.metadataCacheInstance.setMeta("last_sync_timestamp", (/* @__PURE__ */ new Date()).toISOString());
3314
+ return this.metadataCacheInstance.getStats();
3315
+ }
3316
+ // ==========================================
3317
+ // SHARED DRIVES & ENTERPRISE PERMISSIONS
3318
+ // ==========================================
3319
+ /**
3320
+ * Lists all Google Workspace Shared Drives accessible by current user or service account
3321
+ */
3322
+ async listSharedDrives(options = {}) {
3323
+ await this.init();
3324
+ const raw = await this.getRawClient();
3325
+ const res = await withRetry(async () => {
3326
+ return await raw.drives.list({
3327
+ pageSize: options.pageSize || 100,
3328
+ fields: "drives(id, name)"
3329
+ });
3330
+ });
3331
+ return (res.data.drives || []).map((d) => ({ id: d.id, name: d.name }));
3332
+ }
3333
+ /**
3334
+ * Creates a scoped DriveKit client locked to a specific Shared Drive
3335
+ */
3336
+ sharedDrive(driveId) {
3337
+ return new _DriveKit({
3338
+ ...this.options,
3339
+ rootFolderId: driveId
3340
+ });
3341
+ }
3342
+ /**
3343
+ * Grants access to a specific email with custom role and notification
3344
+ */
3345
+ async grantAccess(pathOrId, options) {
3346
+ const fileId = await this.resolveId(pathOrId);
3347
+ const raw = await this.getRawClient();
3348
+ const res = await withRetry(async () => {
3349
+ return await raw.permissions.create({
3350
+ fileId,
3351
+ requestBody: {
3352
+ type: "user",
3353
+ role: options.role || "reader",
3354
+ emailAddress: options.email
3355
+ },
3356
+ sendNotificationEmail: options.notify ?? true,
3357
+ emailMessage: options.message,
3358
+ fields: "id, type, role, emailAddress, displayName",
3359
+ supportsAllDrives: true
3360
+ });
3361
+ });
3362
+ return res.data;
3363
+ }
3364
+ /**
3365
+ * Revokes access for a specific permission ID or email address
3366
+ */
3367
+ async revokeAccess(pathOrId, permissionIdOrEmail) {
3368
+ const fileId = await this.resolveId(pathOrId);
3369
+ const raw = await this.getRawClient();
3370
+ let targetId = permissionIdOrEmail;
3371
+ if (permissionIdOrEmail.includes("@")) {
3372
+ const listRes = await this.listPermissions(fileId);
3373
+ const found = listRes.find((p) => p.emailAddress?.toLowerCase() === permissionIdOrEmail.toLowerCase());
3374
+ if (found && found.id) {
3375
+ targetId = found.id;
3376
+ }
3377
+ }
3378
+ await withRetry(async () => {
3379
+ return await raw.permissions.delete({
3380
+ fileId,
3381
+ permissionId: targetId,
3382
+ supportsAllDrives: true
3383
+ });
3384
+ });
3385
+ }
3386
+ /**
3387
+ * Lists all active permissions on a file or folder
3388
+ */
3389
+ async listPermissions(pathOrId) {
3390
+ const fileId = await this.resolveId(pathOrId);
3391
+ const raw = await this.getRawClient();
3392
+ const res = await withRetry(async () => {
3393
+ return await raw.permissions.list({
3394
+ fileId,
3395
+ fields: "permissions(id, type, role, emailAddress, displayName)",
3396
+ supportsAllDrives: true
3397
+ });
3398
+ });
3399
+ return res.data.permissions || [];
3400
+ }
3401
+ /**
3402
+ * Starts an embedded WebDAV server to mount DriveKit directly in macOS Finder or Windows Explorer
3403
+ */
3404
+ async serveWebDAV(options) {
3405
+ const { startWebDAVServer: startWebDAVServer2 } = await Promise.resolve().then(() => (init_webdav(), webdav_exports));
3406
+ return await startWebDAVServer2(this, options);
3407
+ }
2259
3408
  /**
2260
3409
  * Calculates local file MD5 hash for integrity and deduplication checks
2261
3410
  */
@@ -2279,15 +3428,171 @@ __export(cli_exports, {
2279
3428
  });
2280
3429
  module.exports = __toCommonJS(cli_exports);
2281
3430
  init_cjs_shims();
2282
- var import_node_fs6 = __toESM(require("fs"), 1);
2283
- var import_node_path5 = __toESM(require("path"), 1);
3431
+ var import_node_fs7 = __toESM(require("fs"), 1);
3432
+ var import_node_path7 = __toESM(require("path"), 1);
2284
3433
  var import_commander = require("commander");
2285
- var import_chalk = __toESM(require("chalk"), 1);
3434
+ var import_chalk2 = __toESM(require("chalk"), 1);
2286
3435
  var import_ora = __toESM(require("ora"), 1);
2287
3436
  init_client();
2288
3437
  init_format();
3438
+
3439
+ // src/cli/terminal-ui.ts
3440
+ init_cjs_shims();
3441
+ var import_node_readline = __toESM(require("readline"), 1);
3442
+ var import_chalk = __toESM(require("chalk"), 1);
3443
+ init_format();
3444
+ function terminalLink(text, url2) {
3445
+ return `\x1B]8;;${url2}\x07${text}\x1B]8;;\x07`;
3446
+ }
3447
+ function renderFileRow(item, index) {
3448
+ const isDir = item.mimeType === "application/vnd.google-apps.folder";
3449
+ const icon = isDir ? "\u{1F4C1}" : getFileIcon(item.mimeType || "");
3450
+ const prefix = index !== void 0 ? `${import_chalk.default.dim((index + 1).toString().padStart(2, " ") + ".")} ` : "";
3451
+ let nameFormatted = isDir ? import_chalk.default.bold.blue(item.name || "untitled") : import_chalk.default.white(item.name || "untitled");
3452
+ if (item.webViewLink) {
3453
+ nameFormatted = terminalLink(nameFormatted, item.webViewLink);
3454
+ }
3455
+ const sizeFormatted = item.size ? import_chalk.default.dim(`[${formatBytes(parseInt(item.size, 10)).padStart(9, " ")}]`) : import_chalk.default.dim(isDir ? "[ FOLDER ]" : "[ DOC ]");
3456
+ const idFormatted = import_chalk.default.dim(`ID: ${item.id}`);
3457
+ return `${prefix}${icon} ${nameFormatted.padEnd(45)} ${sizeFormatted} ${idFormatted}`;
3458
+ }
3459
+ function getFileIcon(mimeType) {
3460
+ if (mimeType.includes("pdf")) return "\u{1F4D5}";
3461
+ if (mimeType.includes("image")) return "\u{1F5BC}\uFE0F ";
3462
+ if (mimeType.includes("video")) return "\u{1F3AC}";
3463
+ if (mimeType.includes("audio")) return "\u{1F3B5}";
3464
+ if (mimeType.includes("zip") || mimeType.includes("compressed") || mimeType.includes("tar")) return "\u{1F4E6}";
3465
+ if (mimeType.includes("spreadsheet") || mimeType.includes("excel")) return "\u{1F4CA}";
3466
+ if (mimeType.includes("document") || mimeType.includes("word")) return "\u{1F4DD}";
3467
+ if (mimeType.includes("presentation")) return "\u{1F4FD}\uFE0F ";
3468
+ if (mimeType.includes("json") || mimeType.includes("javascript") || mimeType.includes("typescript")) return "\u2699\uFE0F ";
3469
+ return "\u{1F4C4}";
3470
+ }
3471
+ async function runInteractiveExplorer(client, initialFolder = "/") {
3472
+ let currentFolder = initialFolder;
3473
+ let items = [];
3474
+ let selectedIndex = 0;
3475
+ let history = [];
3476
+ const refreshItems = async () => {
3477
+ items = await client.ls(currentFolder);
3478
+ selectedIndex = Math.min(selectedIndex, Math.max(0, items.length - 1));
3479
+ };
3480
+ await refreshItems();
3481
+ if (!process.stdin.isTTY) {
3482
+ console.log(import_chalk.default.yellow("Interactive explorer requires a TTY terminal. Listing items instead:"));
3483
+ for (const item of items) {
3484
+ console.log(renderFileRow(item));
3485
+ }
3486
+ return;
3487
+ }
3488
+ import_node_readline.default.emitKeypressEvents(process.stdin);
3489
+ process.stdin.setRawMode(true);
3490
+ const renderScreen = () => {
3491
+ console.clear();
3492
+ console.log(import_chalk.default.bold.cyan("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557"));
3493
+ console.log(import_chalk.default.bold.cyan("\u2551") + import_chalk.default.bold.yellow(" \u26A1 DriveKit Interactive Terminal Explorer ") + import_chalk.default.bold.cyan("\u2551"));
3494
+ console.log(import_chalk.default.bold.cyan("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"));
3495
+ console.log(import_chalk.default.bold.cyan("\u2551") + ` \u{1F4C2} Path: ${import_chalk.default.bold.green(currentFolder.padEnd(72))} ` + import_chalk.default.bold.cyan("\u2551"));
3496
+ console.log(import_chalk.default.bold.cyan("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"));
3497
+ console.log(import_chalk.default.dim(" [\u2191/\u2193] Navigate \u2022 [Enter] Open Folder \u2022 [B] Back \u2022 [S] Share \u2022 [Q] Exit\n"));
3498
+ if (items.length === 0) {
3499
+ console.log(import_chalk.default.dim(" (This folder is empty)\n"));
3500
+ return;
3501
+ }
3502
+ const pageSize = 12;
3503
+ const startIdx = Math.max(0, Math.min(selectedIndex - Math.floor(pageSize / 2), items.length - pageSize));
3504
+ const endIdx = Math.min(items.length, startIdx + pageSize);
3505
+ for (let i = startIdx; i < endIdx; i++) {
3506
+ const isSelected = i === selectedIndex;
3507
+ const cursor = isSelected ? import_chalk.default.bold.cyan(" \u25BA ") : " ";
3508
+ const row = renderFileRow(items[i]);
3509
+ if (isSelected) {
3510
+ console.log(import_chalk.default.bgHex("#1e293b")(cursor + row));
3511
+ } else {
3512
+ console.log(cursor + row);
3513
+ }
3514
+ }
3515
+ console.log(import_chalk.default.dim(`
3516
+ Item ${selectedIndex + 1} of ${items.length}`));
3517
+ };
3518
+ renderScreen();
3519
+ return new Promise((resolve) => {
3520
+ const onKeypress = async (str, key) => {
3521
+ if (key.ctrl && key.name === "c") {
3522
+ cleanup();
3523
+ process.exit(0);
3524
+ }
3525
+ if (key.name === "q" || key.name === "escape" && history.length === 0) {
3526
+ cleanup();
3527
+ resolve();
3528
+ return;
3529
+ }
3530
+ if (key.name === "up") {
3531
+ selectedIndex = selectedIndex > 0 ? selectedIndex - 1 : items.length - 1;
3532
+ renderScreen();
3533
+ } else if (key.name === "down") {
3534
+ selectedIndex = selectedIndex < items.length - 1 ? selectedIndex + 1 : 0;
3535
+ renderScreen();
3536
+ } else if (key.name === "return") {
3537
+ const item = items[selectedIndex];
3538
+ if (item && item.mimeType === "application/vnd.google-apps.folder") {
3539
+ history.push(currentFolder);
3540
+ currentFolder = currentFolder === "/" ? `/${item.name}` : `${currentFolder}/${item.name}`;
3541
+ selectedIndex = 0;
3542
+ await refreshItems();
3543
+ renderScreen();
3544
+ } else if (item && item.webViewLink) {
3545
+ const { exec: exec2 } = await import("child_process");
3546
+ const openCmd = process.platform === "darwin" ? `open "${item.webViewLink}"` : `xdg-open "${item.webViewLink}"`;
3547
+ exec2(openCmd);
3548
+ renderScreen();
3549
+ }
3550
+ } else if (key.name === "b" || key.name === "backspace") {
3551
+ if (history.length > 0) {
3552
+ currentFolder = history.pop();
3553
+ selectedIndex = 0;
3554
+ await refreshItems();
3555
+ renderScreen();
3556
+ }
3557
+ } else if (str === "s" || str === "S") {
3558
+ const item = items[selectedIndex];
3559
+ if (item && item.id) {
3560
+ process.stdin.pause();
3561
+ console.log(`
3562
+
3563
+ ${import_chalk.default.cyan("\u{1F517} Getting shareable link for:")} ${import_chalk.default.bold(item.name)}...`);
3564
+ try {
3565
+ const links = await client.sharePublic(item.id);
3566
+ console.log(`Preview URL: ${import_chalk.default.underline(links.previewLink)}`);
3567
+ console.log(`Direct Download URL: ${import_chalk.default.underline(links.directDownloadLink)}`);
3568
+ console.log(import_chalk.default.dim("\nPress any key to return to explorer..."));
3569
+ process.stdin.resume();
3570
+ process.stdin.once("data", () => {
3571
+ renderScreen();
3572
+ });
3573
+ } catch (err) {
3574
+ console.error(import_chalk.default.red(`Failed to share: ${err.message}`));
3575
+ setTimeout(renderScreen, 2e3);
3576
+ }
3577
+ }
3578
+ }
3579
+ };
3580
+ const cleanup = () => {
3581
+ process.stdin.removeListener("keypress", onKeypress);
3582
+ if (process.stdin.setRawMode) {
3583
+ process.stdin.setRawMode(false);
3584
+ }
3585
+ process.stdin.pause();
3586
+ console.clear();
3587
+ console.log(import_chalk.default.green("\u{1F44B} Exited DriveKit explorer."));
3588
+ };
3589
+ process.stdin.on("keypress", onKeypress);
3590
+ });
3591
+ }
3592
+
3593
+ // src/cli.ts
2289
3594
  var program = new import_commander.Command();
2290
- program.name("drivekit").description(import_chalk.default.bold.cyan("\u26A1 DriveKit CLI: High-speed, flexible Google Drive tool for developers")).version("1.0.0").option("-k, --key <path>", "Path to service account JSON key file").option("-t, --token <token>", "Google OAuth2 Bearer access token");
3595
+ program.name("drivekit").description(import_chalk2.default.bold.cyan("\u26A1 DriveKit CLI: High-speed, flexible Google Drive tool for developers")).version("1.0.0").option("-k, --key <path>", "Path to service account JSON key file").option("-t, --token <token>", "Google OAuth2 Bearer access token");
2291
3596
  function getAuthConfig(cmdOptions) {
2292
3597
  const keyFilePath = cmdOptions.key || process.env.GOOGLE_APPLICATION_CREDENTIALS || process.env.GDRIVE_SERVICE_ACCOUNT_PATH;
2293
3598
  const accessToken = cmdOptions.token || process.env.GDRIVE_ACCESS_TOKEN;
@@ -2310,19 +3615,19 @@ program.command("quota").description("Show Google Drive storage usage & quota").
2310
3615
  const client = await getClient(options);
2311
3616
  const quota = await client.getStorageQuota();
2312
3617
  spinner.stop();
2313
- console.log(import_chalk.default.bold.cyan("\n\u{1F4CA} Google Drive Storage Quota:"));
3618
+ console.log(import_chalk2.default.bold.cyan("\n\u{1F4CA} Google Drive Storage Quota:"));
2314
3619
  if (quota.user?.displayName) {
2315
- console.log(`\u{1F464} User: ${import_chalk.default.yellow(quota.user.displayName)} (${quota.user.emailAddress})`);
3620
+ console.log(`\u{1F464} User: ${import_chalk2.default.yellow(quota.user.displayName)} (${quota.user.emailAddress})`);
2316
3621
  }
2317
- console.log(`\u{1F4BE} Total Usage: ${import_chalk.default.green(quota.formattedUsage)} / ${import_chalk.default.blue(quota.formattedLimit)}`);
3622
+ console.log(`\u{1F4BE} Total Usage: ${import_chalk2.default.green(quota.formattedUsage)} / ${import_chalk2.default.blue(quota.formattedLimit)}`);
2318
3623
  if (quota.percentUsed !== null) {
2319
- console.log(`\u{1F4C8} Usage %: ${import_chalk.default.bold(quota.percentUsed + "%")}`);
3624
+ console.log(`\u{1F4C8} Usage %: ${import_chalk2.default.bold(quota.percentUsed + "%")}`);
2320
3625
  }
2321
3626
  console.log(`\u{1F4C1} In Drive: ${formatBytes(quota.usageInDrive)}`);
2322
3627
  console.log(`\u{1F5D1}\uFE0F In Trash: ${formatBytes(quota.usageInDriveTrash)}
2323
3628
  `);
2324
3629
  } catch (err) {
2325
- spinner.fail(import_chalk.default.red(`Failed to fetch quota: ${err.message}`));
3630
+ spinner.fail(import_chalk2.default.red(`Failed to fetch quota: ${err.message}`));
2326
3631
  process.exit(1);
2327
3632
  }
2328
3633
  });
@@ -2333,34 +3638,38 @@ program.command("ls [folder]").description("List files and folders (by virtual p
2333
3638
  const items = await client.ls(folder);
2334
3639
  spinner.stop();
2335
3640
  if (items.length === 0) {
2336
- console.log(import_chalk.default.dim(`(Folder ${folder} is empty)`));
3641
+ console.log(import_chalk2.default.dim(`(Folder ${folder} is empty)`));
2337
3642
  return;
2338
3643
  }
2339
- console.log(import_chalk.default.bold.cyan(`
3644
+ console.log(import_chalk2.default.bold.cyan(`
2340
3645
  \u{1F4C1} Contents of "${folder}":
2341
3646
  `));
2342
- for (const item of items) {
2343
- const isDir = item.mimeType === "application/vnd.google-apps.folder";
2344
- const icon = isDir ? "\u{1F4C1}" : "\u{1F4C4}";
2345
- const nameFormatted = isDir ? import_chalk.default.bold.blue(item.name) : import_chalk.default.white(item.name);
2346
- const sizeFormatted = item.size ? import_chalk.default.dim(`[${formatBytes(parseInt(item.size, 10))}]`) : import_chalk.default.dim(isDir ? "[DIR]" : "[Google Doc]");
2347
- const idFormatted = import_chalk.default.dim(`(ID: ${item.id})`);
2348
- console.log(` ${icon} ${nameFormatted.padEnd(40)} ${sizeFormatted.padEnd(16)} ${idFormatted}`);
3647
+ for (let i = 0; i < items.length; i++) {
3648
+ console.log(renderFileRow(items[i], i));
2349
3649
  }
2350
3650
  console.log(`
2351
- Total items: ${import_chalk.default.green(items.length)}
3651
+ Total items: ${import_chalk2.default.green(items.length)}
2352
3652
  `);
2353
3653
  } catch (err) {
2354
- spinner.fail(import_chalk.default.red(`Failed to list items: ${err.message}`));
3654
+ spinner.fail(import_chalk2.default.red(`Failed to list items: ${err.message}`));
3655
+ process.exit(1);
3656
+ }
3657
+ });
3658
+ program.command("explore [folder]").description("Interactive terminal keyboard file explorer (TUI) for Google Drive").action(async (folder = "/", options) => {
3659
+ try {
3660
+ const client = await getClient(options);
3661
+ await runInteractiveExplorer(client, folder);
3662
+ } catch (err) {
3663
+ console.error(import_chalk2.default.red(`Explorer failed: ${err.message}`));
2355
3664
  process.exit(1);
2356
3665
  }
2357
3666
  });
2358
- 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").action(async (localFile, remotePath = "/", options) => {
2359
- if (!import_node_fs6.default.existsSync(localFile)) {
2360
- console.error(import_chalk.default.red(`\u274C Local file not found: ${localFile}`));
3667
+ 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) => {
3668
+ if (!import_node_fs7.default.existsSync(localFile)) {
3669
+ console.error(import_chalk2.default.red(`\u274C Local file not found: ${localFile}`));
2361
3670
  process.exit(1);
2362
3671
  }
2363
- const fileName = import_node_path5.default.basename(localFile);
3672
+ const fileName = import_node_path7.default.basename(localFile);
2364
3673
  const spinner = (0, import_ora.default)(`Preparing upload: ${fileName}...`).start();
2365
3674
  try {
2366
3675
  const client = await getClient(options);
@@ -2371,24 +3680,25 @@ program.command("upload <localFile> [remotePath]").description("Upload a file wi
2371
3680
  name: fileName,
2372
3681
  parent: remotePath,
2373
3682
  overwrite: options.overwrite,
3683
+ deduplicate: options.dedup,
2374
3684
  onProgress: (p) => {
2375
3685
  process.stdout.write(
2376
- `\r\u{1F680} Uploading: ${import_chalk.default.cyan(p.percentage + "%")} | Speed: ${import_chalk.default.green(p.speedFormatted)} | ETA: ${import_chalk.default.yellow(p.estimatedTimeRemainingSeconds + "s")} [${formatBytes(p.bytesSent)} / ${formatBytes(p.totalBytes)}]`
3686
+ `\r\u{1F680} Uploading: ${import_chalk2.default.cyan(p.percentage + "%")} | Speed: ${import_chalk2.default.green(p.speedFormatted)} | ETA: ${import_chalk2.default.yellow(p.estimatedTimeRemainingSeconds + "s")} [${formatBytes(p.bytesSent)} / ${formatBytes(p.totalBytes)}]`
2377
3687
  );
2378
3688
  }
2379
3689
  });
2380
3690
  process.stdout.write("\n");
2381
3691
  const durationSecs = ((Date.now() - startTime) / 1e3).toFixed(1);
2382
- console.log(import_chalk.default.green(`
3692
+ console.log(import_chalk2.default.green(`
2383
3693
  \u2705 Upload completed successfully in ${durationSecs}s!`));
2384
- console.log(`\u{1F4C4} Name: ${import_chalk.default.bold(res.name)}`);
2385
- console.log(`\u{1F194} ID: ${import_chalk.default.cyan(res.id)}`);
3694
+ console.log(`\u{1F4C4} Name: ${import_chalk2.default.bold(res.name)}`);
3695
+ console.log(`\u{1F194} ID: ${import_chalk2.default.cyan(res.id)}`);
2386
3696
  if (res.webViewLink) {
2387
- console.log(`\u{1F517} Link: ${import_chalk.default.underline(res.webViewLink)}`);
3697
+ console.log(`\u{1F517} Link: ${import_chalk2.default.underline(res.webViewLink)}`);
2388
3698
  }
2389
3699
  console.log("");
2390
3700
  } catch (err) {
2391
- spinner.fail(import_chalk.default.red(`Upload failed: ${err.message}`));
3701
+ spinner.fail(import_chalk2.default.red(`Upload failed: ${err.message}`));
2392
3702
  process.exit(1);
2393
3703
  }
2394
3704
  });
@@ -2402,20 +3712,20 @@ program.command("download <fileIdOrPath> [destination]").description("Download a
2402
3712
  onProgress: (p) => {
2403
3713
  const pct = p.percentage !== void 0 ? `${p.percentage}%` : `${formatBytes(p.bytesRead)}`;
2404
3714
  process.stdout.write(
2405
- `\r\u2B07\uFE0F Downloading: ${import_chalk.default.cyan(pct)} | Speed: ${import_chalk.default.green(p.speedFormatted)}`
3715
+ `\r\u2B07\uFE0F Downloading: ${import_chalk2.default.cyan(pct)} | Speed: ${import_chalk2.default.green(p.speedFormatted)}`
2406
3716
  );
2407
3717
  }
2408
3718
  });
2409
3719
  process.stdout.write("\n");
2410
- console.log(import_chalk.default.green(`
3720
+ console.log(import_chalk2.default.green(`
2411
3721
  \u2705 Download completed!`));
2412
- console.log(`\u{1F4C2} Saved to: ${import_chalk.default.bold(res.filePath)}`);
3722
+ console.log(`\u{1F4C2} Saved to: ${import_chalk2.default.bold(res.filePath)}`);
2413
3723
  if (res.size) {
2414
3724
  console.log(`\u{1F4E6} Size: ${formatBytes(res.size)}`);
2415
3725
  }
2416
3726
  console.log("");
2417
3727
  } catch (err) {
2418
- spinner.fail(import_chalk.default.red(`Download failed: ${err.message}`));
3728
+ spinner.fail(import_chalk2.default.red(`Download failed: ${err.message}`));
2419
3729
  process.exit(1);
2420
3730
  }
2421
3731
  });
@@ -2429,16 +3739,16 @@ program.command("share <fileIdOrPath> [email]").description("Share file publicly
2429
3739
  type: "user",
2430
3740
  emailAddress: email
2431
3741
  });
2432
- spinner.succeed(import_chalk.default.green(`File shared with ${email} as reader!`));
3742
+ spinner.succeed(import_chalk2.default.green(`File shared with ${email} as reader!`));
2433
3743
  } else {
2434
3744
  const links = await client.sharePublic(fileIdOrPath);
2435
- spinner.succeed(import_chalk.default.green(`File is now publicly accessible to anyone with the link!`));
2436
- console.log(`\u{1F517} Preview Link: ${import_chalk.default.underline(links.previewLink)}`);
2437
- console.log(`\u{1F4E5} Direct Download Link: ${import_chalk.default.underline(links.directDownloadLink)}
3745
+ spinner.succeed(import_chalk2.default.green(`File is now publicly accessible to anyone with the link!`));
3746
+ console.log(`\u{1F517} Preview Link: ${import_chalk2.default.underline(links.previewLink)}`);
3747
+ console.log(`\u{1F4E5} Direct Download Link: ${import_chalk2.default.underline(links.directDownloadLink)}
2438
3748
  `);
2439
3749
  }
2440
3750
  } catch (err) {
2441
- spinner.fail(import_chalk.default.red(`Sharing failed: ${err.message}`));
3751
+ spinner.fail(import_chalk2.default.red(`Sharing failed: ${err.message}`));
2442
3752
  process.exit(1);
2443
3753
  }
2444
3754
  });
@@ -2448,19 +3758,19 @@ program.command("delete <fileIdOrPath>").description("Move a file/folder to tras
2448
3758
  try {
2449
3759
  const client = await getClient(options);
2450
3760
  await client.delete(fileIdOrPath, options.permanent);
2451
- spinner.succeed(import_chalk.default.green(`Success! ${fileIdOrPath} has been ${options.permanent ? "permanently deleted" : "moved to trash"}.`));
3761
+ spinner.succeed(import_chalk2.default.green(`Success! ${fileIdOrPath} has been ${options.permanent ? "permanently deleted" : "moved to trash"}.`));
2452
3762
  } catch (err) {
2453
- spinner.fail(import_chalk.default.red(`Failed: ${err.message}`));
3763
+ spinner.fail(import_chalk2.default.red(`Failed: ${err.message}`));
2454
3764
  process.exit(1);
2455
3765
  }
2456
3766
  });
2457
3767
  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) => {
2458
- if (!import_node_fs6.default.existsSync(localDir)) {
2459
- console.error(import_chalk.default.red(`\u274C Local directory not found: ${localDir}`));
3768
+ if (!import_node_fs7.default.existsSync(localDir)) {
3769
+ console.error(import_chalk2.default.red(`\u274C Local directory not found: ${localDir}`));
2460
3770
  process.exit(1);
2461
3771
  }
2462
3772
  const concurrency = parseInt(options.concurrency, 10) || 4;
2463
- console.log(import_chalk.default.bold.cyan(`
3773
+ console.log(import_chalk2.default.bold.cyan(`
2464
3774
  \u26A1 Starting recursive sync:`));
2465
3775
  console.log(`\u{1F4C2} Local: ${localDir}`);
2466
3776
  console.log(`\u2601\uFE0F Remote: ${remoteFolder}`);
@@ -2474,30 +3784,30 @@ program.command("sync <localDir> <remoteFolder>").description("Sync a local dire
2474
3784
  concurrency,
2475
3785
  overwrite: options.overwrite,
2476
3786
  onFileStart: (_, rel) => {
2477
- console.log(` \u2B06\uFE0F Uploading: ${import_chalk.default.dim(rel)}`);
3787
+ console.log(` \u2B06\uFE0F Uploading: ${import_chalk2.default.dim(rel)}`);
2478
3788
  },
2479
3789
  onFileComplete: (_, fileId) => {
2480
- console.log(` ${import_chalk.default.green("\u2713 Completed")} ${import_chalk.default.dim(`(ID: ${fileId})`)}`);
3790
+ console.log(` ${import_chalk2.default.green("\u2713 Completed")} ${import_chalk2.default.dim(`(ID: ${fileId})`)}`);
2481
3791
  }
2482
3792
  });
2483
- console.log(import_chalk.default.bold.green(`
3793
+ console.log(import_chalk2.default.bold.green(`
2484
3794
  \u{1F389} Sync Finished in ${(result.durationMs / 1e3).toFixed(1)}s!`));
2485
- console.log(`\u2705 Uploaded: ${import_chalk.default.green(result.uploaded.length)} files (${formatBytes(result.totalBytes)})`);
3795
+ console.log(`\u2705 Uploaded: ${import_chalk2.default.green(result.uploaded.length)} files (${formatBytes(result.totalBytes)})`);
2486
3796
  if (result.failed.length > 0) {
2487
- console.log(`\u274C Failed: ${import_chalk.default.red(result.failed.length)} files`);
3797
+ console.log(`\u274C Failed: ${import_chalk2.default.red(result.failed.length)} files`);
2488
3798
  for (const f of result.failed) {
2489
- console.log(` - ${f.localPath}: ${import_chalk.default.red(f.error.message)}`);
3799
+ console.log(` - ${f.localPath}: ${import_chalk2.default.red(f.error.message)}`);
2490
3800
  }
2491
3801
  }
2492
3802
  console.log("");
2493
3803
  } catch (err) {
2494
- spinner.fail(import_chalk.default.red(`Sync failed: ${err.message}`));
3804
+ spinner.fail(import_chalk2.default.red(`Sync failed: ${err.message}`));
2495
3805
  process.exit(1);
2496
3806
  }
2497
3807
  });
2498
3808
  program.command("pull <remoteFolder> <localDir>").description("Download an entire remote Google Drive folder down to local directory with MD5 deduplication").option("-c, --concurrency <number>", "Parallel downloads", "4").option("-o, --overwrite", "Overwrite local files even if identical").action(async (remoteFolder, localDir, options) => {
2499
3809
  const concurrency = parseInt(options.concurrency, 10) || 4;
2500
- console.log(import_chalk.default.bold.cyan(`
3810
+ console.log(import_chalk2.default.bold.cyan(`
2501
3811
  \u2B07\uFE0F Starting smart pull:`));
2502
3812
  console.log(`\u2601\uFE0F Remote: ${remoteFolder}`);
2503
3813
  console.log(`\u{1F4C2} Local: ${localDir}`);
@@ -2511,24 +3821,24 @@ program.command("pull <remoteFolder> <localDir>").description("Download an entir
2511
3821
  concurrency,
2512
3822
  overwrite: options.overwrite,
2513
3823
  onFileStart: (name, rel) => {
2514
- console.log(` \u2B07\uFE0F Downloading: ${import_chalk.default.dim(rel)}`);
3824
+ console.log(` \u2B07\uFE0F Downloading: ${import_chalk2.default.dim(rel)}`);
2515
3825
  },
2516
3826
  onFileComplete: (name) => {
2517
- console.log(` ${import_chalk.default.green("\u2713 Saved")} ${name}`);
3827
+ console.log(` ${import_chalk2.default.green("\u2713 Saved")} ${name}`);
2518
3828
  }
2519
3829
  });
2520
- console.log(import_chalk.default.bold.green(`
3830
+ console.log(import_chalk2.default.bold.green(`
2521
3831
  \u{1F389} Pull Finished in ${(result.durationMs / 1e3).toFixed(1)}s!`));
2522
- console.log(`\u2705 Downloaded: ${import_chalk.default.green(result.downloaded.length)} files (${formatBytes(result.totalBytes)})`);
3832
+ console.log(`\u2705 Downloaded: ${import_chalk2.default.green(result.downloaded.length)} files (${formatBytes(result.totalBytes)})`);
2523
3833
  if (result.skipped.length > 0) {
2524
- console.log(`\u23ED\uFE0F Skipped: ${import_chalk.default.yellow(result.skipped.length)} identical files`);
3834
+ console.log(`\u23ED\uFE0F Skipped: ${import_chalk2.default.yellow(result.skipped.length)} identical files`);
2525
3835
  }
2526
3836
  if (result.failed.length > 0) {
2527
- console.log(`\u274C Failed: ${import_chalk.default.red(result.failed.length)} files`);
3837
+ console.log(`\u274C Failed: ${import_chalk2.default.red(result.failed.length)} files`);
2528
3838
  }
2529
3839
  console.log("");
2530
3840
  } catch (err) {
2531
- spinner.fail(import_chalk.default.red(`Pull failed: ${err.message}`));
3841
+ spinner.fail(import_chalk2.default.red(`Pull failed: ${err.message}`));
2532
3842
  process.exit(1);
2533
3843
  }
2534
3844
  });
@@ -2538,7 +3848,7 @@ program.command("clean").description("Storage management: find largest files, de
2538
3848
  if (options.emptyTrash) {
2539
3849
  const spinner2 = (0, import_ora.default)("Emptying trash bin...").start();
2540
3850
  await client.emptyTrash();
2541
- spinner2.succeed(import_chalk.default.green("Trash bin emptied successfully!"));
3851
+ spinner2.succeed(import_chalk2.default.green("Trash bin emptied successfully!"));
2542
3852
  return;
2543
3853
  }
2544
3854
  if (options.duplicates) {
@@ -2546,16 +3856,16 @@ program.command("clean").description("Storage management: find largest files, de
2546
3856
  const duplicates = await client.findDuplicates({ by: "name" });
2547
3857
  spinner2.stop();
2548
3858
  if (duplicates.length === 0) {
2549
- console.log(import_chalk.default.green("\n\u2728 No duplicate files found!"));
3859
+ console.log(import_chalk2.default.green("\n\u2728 No duplicate files found!"));
2550
3860
  return;
2551
3861
  }
2552
- console.log(import_chalk.default.bold.yellow(`
3862
+ console.log(import_chalk2.default.bold.yellow(`
2553
3863
  \u26A0\uFE0F Found ${duplicates.length} duplicate groups:
2554
3864
  `));
2555
3865
  for (const g of duplicates) {
2556
- console.log(`\u{1F4C4} "${import_chalk.default.bold(g.name)}" (${import_chalk.default.cyan(g.count + " copies")} - total: ${import_chalk.default.magenta(g.formattedTotalSize)})`);
3866
+ console.log(`\u{1F4C4} "${import_chalk2.default.bold(g.name)}" (${import_chalk2.default.cyan(g.count + " copies")} - total: ${import_chalk2.default.magenta(g.formattedTotalSize)})`);
2557
3867
  for (const f of g.files) {
2558
- console.log(` - ID: ${import_chalk.default.dim(f.id)} [${formatBytes(f.size)}] modified: ${import_chalk.default.dim(f.modifiedTime || "unknown")}`);
3868
+ console.log(` - ID: ${import_chalk2.default.dim(f.id)} [${formatBytes(f.size)}] modified: ${import_chalk2.default.dim(f.modifiedTime || "unknown")}`);
2559
3869
  }
2560
3870
  }
2561
3871
  console.log("");
@@ -2565,51 +3875,51 @@ program.command("clean").description("Storage management: find largest files, de
2565
3875
  const spinner = (0, import_ora.default)(`Finding top ${limit} largest files...`).start();
2566
3876
  const largest = await client.findLargestFiles(limit);
2567
3877
  spinner.stop();
2568
- console.log(import_chalk.default.bold.cyan(`
3878
+ console.log(import_chalk2.default.bold.cyan(`
2569
3879
  \u{1F4CA} Top ${largest.length} Largest Files in Drive:
2570
3880
  `));
2571
3881
  for (let i = 0; i < largest.length; i++) {
2572
3882
  const f = largest[i];
2573
- console.log(` ${import_chalk.default.bold(i + 1 + ".")} ${import_chalk.default.white(f.name.padEnd(35))} ${import_chalk.default.green(f.formattedSize.padEnd(12))} ID: ${import_chalk.default.dim(f.id)}`);
3883
+ console.log(` ${import_chalk2.default.bold(i + 1 + ".")} ${import_chalk2.default.white(f.name.padEnd(35))} ${import_chalk2.default.green(f.formattedSize.padEnd(12))} ID: ${import_chalk2.default.dim(f.id)}`);
2574
3884
  }
2575
3885
  console.log("");
2576
3886
  } catch (err) {
2577
- console.error(import_chalk.default.red(`Clean operation failed: ${err.message}`));
3887
+ console.error(import_chalk2.default.red(`Clean operation failed: ${err.message}`));
2578
3888
  process.exit(1);
2579
3889
  }
2580
3890
  });
2581
3891
  program.command("watch [folder]").description("Watch Google Drive or a specific folder for real-time changes").option("-i, --interval <ms>", "Polling interval in milliseconds", "5000").action(async (folder = "/", options) => {
2582
3892
  const intervalMs = parseInt(options.interval, 10) || 5e3;
2583
- console.log(import_chalk.default.bold.cyan(`
3893
+ console.log(import_chalk2.default.bold.cyan(`
2584
3894
  \u{1F440} Watching for changes in "${folder}" (polling every ${intervalMs / 1e3}s)...`));
2585
- console.log(import_chalk.default.dim("Press Ctrl+C to stop watching.\n"));
3895
+ console.log(import_chalk2.default.dim("Press Ctrl+C to stop watching.\n"));
2586
3896
  try {
2587
3897
  const client = await getClient(options);
2588
3898
  const watcher = await client.watch(folder === "/" ? void 0 : folder, { intervalMs });
2589
3899
  watcher.on("create", (e) => {
2590
- console.log(`${import_chalk.default.green("[CREATED]")} ${import_chalk.default.bold(e.file?.name || e.fileId)} ${import_chalk.default.dim(`(ID: ${e.fileId})`)}`);
3900
+ console.log(`${import_chalk2.default.green("[CREATED]")} ${import_chalk2.default.bold(e.file?.name || e.fileId)} ${import_chalk2.default.dim(`(ID: ${e.fileId})`)}`);
2591
3901
  });
2592
3902
  watcher.on("modify", (e) => {
2593
- console.log(`${import_chalk.default.yellow("[MODIFIED]")} ${import_chalk.default.bold(e.file?.name || e.fileId)} ${import_chalk.default.dim(`(ID: ${e.fileId})`)}`);
3903
+ console.log(`${import_chalk2.default.yellow("[MODIFIED]")} ${import_chalk2.default.bold(e.file?.name || e.fileId)} ${import_chalk2.default.dim(`(ID: ${e.fileId})`)}`);
2594
3904
  });
2595
3905
  watcher.on("delete", (e) => {
2596
- console.log(`${import_chalk.default.red("[DELETED]")} ${import_chalk.default.bold(e.file?.name || e.fileId)} ${import_chalk.default.dim(`(ID: ${e.fileId})`)}`);
3906
+ console.log(`${import_chalk2.default.red("[DELETED]")} ${import_chalk2.default.bold(e.file?.name || e.fileId)} ${import_chalk2.default.dim(`(ID: ${e.fileId})`)}`);
2597
3907
  });
2598
3908
  watcher.on("error", (err) => {
2599
- console.error(import_chalk.default.red(`[WATCHER ERROR] ${err.message}`));
3909
+ console.error(import_chalk2.default.red(`[WATCHER ERROR] ${err.message}`));
2600
3910
  });
2601
3911
  process.on("SIGINT", () => {
2602
3912
  watcher.stop();
2603
- console.log(import_chalk.default.yellow("\nWatcher stopped. Goodbye!"));
3913
+ console.log(import_chalk2.default.yellow("\nWatcher stopped. Goodbye!"));
2604
3914
  process.exit(0);
2605
3915
  });
2606
3916
  } catch (err) {
2607
- console.error(import_chalk.default.red(`Failed to start watcher: ${err.message}`));
3917
+ console.error(import_chalk2.default.red(`Failed to start watcher: ${err.message}`));
2608
3918
  process.exit(1);
2609
3919
  }
2610
3920
  });
2611
3921
  program.command("login").description("Interactive 1-click browser OAuth2 sign-in").requiredOption("--client-id <id>", "Google OAuth2 Client ID").requiredOption("--client-secret <secret>", "Google OAuth2 Client Secret").option("-p, --port <port>", "Local callback port", "3000").action(async (options) => {
2612
- console.log(import_chalk.default.bold.cyan("\n\u26A1 DriveKit Interactive Login"));
3922
+ console.log(import_chalk2.default.bold.cyan("\n\u26A1 DriveKit Interactive Login"));
2613
3923
  console.log("Opening your browser for one-click Google OAuth sign-in...\n");
2614
3924
  try {
2615
3925
  const { DriveKit: DriveKit2 } = await Promise.resolve().then(() => (init_client(), client_exports));
@@ -2618,17 +3928,115 @@ program.command("login").description("Interactive 1-click browser OAuth2 sign-in
2618
3928
  clientSecret: options.clientSecret,
2619
3929
  port: parseInt(options.port, 10) || 3e3
2620
3930
  });
2621
- console.log(import_chalk.default.bold.green("\n\u{1F389} Login successful!"));
2622
- console.log(`Access Token: ${import_chalk.default.cyan(result.tokens.access_token?.slice(0, 25) + "...")}`);
3931
+ console.log(import_chalk2.default.bold.green("\n\u{1F389} Login successful!"));
3932
+ console.log(`Access Token: ${import_chalk2.default.cyan(result.tokens.access_token?.slice(0, 25) + "...")}`);
2623
3933
  if (result.tokens.refresh_token) {
2624
- console.log(`Refresh Token: ${import_chalk.default.green(result.tokens.refresh_token?.slice(0, 25) + "...")}`);
3934
+ console.log(`Refresh Token: ${import_chalk2.default.green(result.tokens.refresh_token?.slice(0, 25) + "...")}`);
3935
+ }
3936
+ const outPath = import_node_path7.default.resolve("./gdrive-tokens.json");
3937
+ import_node_fs7.default.writeFileSync(outPath, JSON.stringify(result.tokens, null, 2), "utf8");
3938
+ console.log(`\u{1F4BE} Saved tokens to: ${import_chalk2.default.bold(outPath)}
3939
+ `);
3940
+ } catch (err) {
3941
+ console.error(import_chalk2.default.red(`Login failed: ${err.message}`));
3942
+ process.exit(1);
3943
+ }
3944
+ });
3945
+ var cacheCmd = program.command("cache").description("Manage local persistent SQLite metadata cache");
3946
+ cacheCmd.command("status").description("Display SQLite cache statistics and database path").action(async (options) => {
3947
+ try {
3948
+ const client = await getClient(options);
3949
+ const stats = await client.getCacheStats();
3950
+ if (!stats) {
3951
+ console.log(import_chalk2.default.yellow("\u26A0\uFE0F Persistent cache is disabled or not available."));
3952
+ return;
3953
+ }
3954
+ console.log(import_chalk2.default.bold.cyan("\n\u26A1 DriveKit Persistent SQLite Cache Status:"));
3955
+ console.log(`\u{1F4C1} Database Path: ${import_chalk2.default.dim(stats.databasePath)}`);
3956
+ console.log(`\u{1F4C2} Cached Folders: ${import_chalk2.default.bold.green(stats.folderCount.toLocaleString())}`);
3957
+ console.log(`\u{1F4C4} Cached Files: ${import_chalk2.default.bold.cyan(stats.fileCount.toLocaleString())}`);
3958
+ console.log(`\u{1F4BE} Indexed Size: ${import_chalk2.default.bold.white(formatBytes(stats.totalSizeBytes))}`);
3959
+ console.log(`\u{1F552} Last Full Sync: ${import_chalk2.default.dim(stats.lastSyncTime || "Never")}
3960
+ `);
3961
+ } catch (err) {
3962
+ console.error(import_chalk2.default.red(`Cache status failed: ${err.message}`));
3963
+ process.exit(1);
3964
+ }
3965
+ });
3966
+ cacheCmd.command("sync").description("Crawl Google Drive and index all file metadata into local SQLite for 0ms lookups").action(async (options) => {
3967
+ const spinner = (0, import_ora.default)("Indexing Google Drive metadata into SQLite...").start();
3968
+ try {
3969
+ const client = await getClient(options);
3970
+ const stats = await client.syncCache({
3971
+ onProgress: (scanned) => {
3972
+ spinner.text = `Indexing Google Drive metadata... (${import_chalk2.default.cyan(scanned.toLocaleString())} items scanned)`;
3973
+ }
3974
+ });
3975
+ spinner.succeed(import_chalk2.default.green(`Indexed ${stats.fileCount + stats.folderCount} items successfully!`));
3976
+ console.log(`\u{1F4BE} Database: ${import_chalk2.default.dim(stats.databasePath)}
3977
+ `);
3978
+ } catch (err) {
3979
+ spinner.fail(import_chalk2.default.red(`Cache sync failed: ${err.message}`));
3980
+ process.exit(1);
3981
+ }
3982
+ });
3983
+ cacheCmd.command("clear").description("Clear all cached metadata from local SQLite database").action(async (options) => {
3984
+ try {
3985
+ const client = await getClient(options);
3986
+ await client.clearCache();
3987
+ console.log(import_chalk2.default.green("\u{1F9F9} Local SQLite cache cleared successfully."));
3988
+ } catch (err) {
3989
+ console.error(import_chalk2.default.red(`Cache clear failed: ${err.message}`));
3990
+ process.exit(1);
3991
+ }
3992
+ });
3993
+ program.command("shared-drives").description("List accessible Google Workspace Shared Drives").action(async (options) => {
3994
+ const spinner = (0, import_ora.default)("Fetching Shared Drives...").start();
3995
+ try {
3996
+ const client = await getClient(options);
3997
+ const drives = await client.listSharedDrives();
3998
+ spinner.stop();
3999
+ if (drives.length === 0) {
4000
+ console.log(import_chalk2.default.yellow("\nNo Shared Drives found or accessible for this account.\n"));
4001
+ return;
4002
+ }
4003
+ console.log(import_chalk2.default.bold.cyan(`
4004
+ \u{1F3E2} Google Workspace Shared Drives (${drives.length}):`));
4005
+ for (const d of drives) {
4006
+ console.log(` \u{1F4C1} ${import_chalk2.default.bold.blue(d.name.padEnd(35))} ${import_chalk2.default.dim(`(ID: ${d.id})`)}`);
2625
4007
  }
2626
- const outPath = import_node_path5.default.resolve("./gdrive-tokens.json");
2627
- import_node_fs6.default.writeFileSync(outPath, JSON.stringify(result.tokens, null, 2), "utf8");
2628
- console.log(`\u{1F4BE} Saved tokens to: ${import_chalk.default.bold(outPath)}
4008
+ console.log("");
4009
+ } catch (err) {
4010
+ spinner.fail(import_chalk2.default.red(`Failed to list shared drives: ${err.message}`));
4011
+ process.exit(1);
4012
+ }
4013
+ });
4014
+ program.command("serve").description("Start embedded WebDAV server to mount DriveKit directly in macOS Finder or Windows Explorer").option("-p, --port <port>", "Port number to listen on", "8080").option("-h, --host <host>", "Host address to bind to", "127.0.0.1").action(async (options) => {
4015
+ try {
4016
+ const client = await getClient(options);
4017
+ const port = parseInt(options.port, 10) || 8080;
4018
+ const host = options.host || "127.0.0.1";
4019
+ console.log(import_chalk2.default.bold.cyan("\n\u26A1 DriveKit WebDAV Server"));
4020
+ console.log("Starting local WebDAV bridge to Google Drive...\n");
4021
+ const serverInstance = await client.serveWebDAV({ port, host });
4022
+ console.log(import_chalk2.default.bold.green(`\u{1F680} Server active at: ${import_chalk2.default.underline(serverInstance.url)}`));
4023
+ console.log(import_chalk2.default.white("\n\u{1F4CC} How to mount on macOS Finder:"));
4024
+ console.log(` 1. Open Finder and press ${import_chalk2.default.bold.cyan("Cmd + K")} (Connect to Server)`);
4025
+ console.log(` 2. Enter: ${import_chalk2.default.bold.yellow(serverInstance.url)}`);
4026
+ console.log(` 3. Click ${import_chalk2.default.bold("Connect")} (Connect as Guest)
2629
4027
  `);
4028
+ console.log(import_chalk2.default.white("\u{1F4CC} How to mount on Windows:"));
4029
+ console.log(` 1. Open File Explorer -> This PC -> "Map network drive"`);
4030
+ console.log(` 2. Enter: ${import_chalk2.default.bold.yellow(serverInstance.url)}
4031
+ `);
4032
+ console.log(import_chalk2.default.dim("Press Ctrl+C to stop the WebDAV server.\n"));
4033
+ process.on("SIGINT", async () => {
4034
+ await serverInstance.close();
4035
+ console.log(import_chalk2.default.yellow("\nWebDAV server stopped. Goodbye!"));
4036
+ process.exit(0);
4037
+ });
2630
4038
  } catch (err) {
2631
- console.error(import_chalk.default.red(`Login failed: ${err.message}`));
4039
+ console.error(import_chalk2.default.red(`Failed to start WebDAV server: ${err.message}`));
2632
4040
  process.exit(1);
2633
4041
  }
2634
4042
  });