drivekit 1.0.2 → 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,
@@ -939,6 +997,24 @@ var init_downloader = __esm({
939
997
  size: totalBytes
940
998
  };
941
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
+ }
942
1018
  };
943
1019
  }
944
1020
  });
@@ -1067,6 +1143,19 @@ var init_query_builder = __esm({
1067
1143
  this.conditions.push(`(${condition})`);
1068
1144
  return this;
1069
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
+ }
1070
1159
  /**
1071
1160
  * Sort ordering (e.g. 'modifiedTime desc', 'name', 'folder,modifiedTime desc')
1072
1161
  */
@@ -1113,6 +1202,12 @@ var init_query_builder = __esm({
1113
1202
  });
1114
1203
  return res.data.files || [];
1115
1204
  }
1205
+ /**
1206
+ * Executes query and returns array of matching files (alias for list)
1207
+ */
1208
+ async execute() {
1209
+ return await this.list();
1210
+ }
1116
1211
  /**
1117
1212
  * Returns the first matching file, or null if not found
1118
1213
  */
@@ -1755,6 +1850,22 @@ var init_resource_refs = __esm({
1755
1850
  async getLink() {
1756
1851
  return await this.drive.getShareableLink(this.pathOrId);
1757
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
+ }
1758
1869
  };
1759
1870
  DriveFolderRef = class {
1760
1871
  drive;
@@ -1792,6 +1903,15 @@ var init_resource_refs = __esm({
1792
1903
  async watch(options = {}) {
1793
1904
  return await this.drive.watch(this.pathOrId, options);
1794
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
+ }
1795
1915
  };
1796
1916
  }
1797
1917
  });
@@ -1852,18 +1972,579 @@ var init_plugins = __esm({
1852
1972
  }
1853
1973
  });
1854
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
+
1855
2536
  // src/core/client.ts
1856
2537
  var client_exports = {};
1857
2538
  __export(client_exports, {
1858
2539
  DriveKit: () => DriveKit
1859
2540
  });
1860
- var import_node_fs5, import_node_path4, import_drive3, DriveKit;
2541
+ var import_node_fs6, import_node_path6, import_drive3, DriveKit;
1861
2542
  var init_client = __esm({
1862
2543
  "src/core/client.ts"() {
1863
2544
  "use strict";
1864
2545
  init_cjs_shims();
1865
- import_node_fs5 = __toESM(require("fs"), 1);
1866
- import_node_path4 = __toESM(require("path"), 1);
2546
+ import_node_fs6 = __toESM(require("fs"), 1);
2547
+ import_node_path6 = __toESM(require("path"), 1);
1867
2548
  import_drive3 = require("@googleapis/drive");
1868
2549
  init_authenticator();
1869
2550
  init_path_resolver();
@@ -1880,13 +2561,15 @@ var init_client = __esm({
1880
2561
  init_retry();
1881
2562
  init_format();
1882
2563
  init_mime();
1883
- DriveKit = class {
2564
+ init_cache();
2565
+ DriveKit = class _DriveKit {
1884
2566
  options;
1885
2567
  authenticator;
1886
2568
  driveClient = null;
1887
2569
  pathResolverInstance = null;
1888
2570
  uploaderInstance = null;
1889
2571
  downloaderInstance = null;
2572
+ metadataCacheInstance = null;
1890
2573
  rootFolderId;
1891
2574
  pluginManager = new PluginManager();
1892
2575
  constructor(options = {}) {
@@ -1920,9 +2603,14 @@ var init_client = __esm({
1920
2603
  if (!this.driveClient) {
1921
2604
  const auth = await this.authenticator.getAuthClient();
1922
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
+ }
1923
2610
  this.pathResolverInstance = new PathResolver(this.driveClient, this.rootFolderId, {
1924
2611
  enableCache: this.options.enablePathCache ?? true,
1925
- cacheTTL: this.options.pathCacheTTL
2612
+ cacheTTL: this.options.pathCacheTTL,
2613
+ metadataCache: this.metadataCacheInstance || void 0
1926
2614
  });
1927
2615
  this.uploaderInstance = new ResumableUploader(
1928
2616
  this.driveClient,
@@ -2027,16 +2715,71 @@ var init_client = __esm({
2027
2715
  if (parentId && parentId.startsWith("/")) {
2028
2716
  parentId = await this.mkdirp(parentId);
2029
2717
  }
2030
- if (opts.overwrite && opts.name && parentId) {
2031
- const existing = await this.query().inFolder(parentId).nameEquals(opts.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();
2032
2721
  if (existing?.id) {
2033
2722
  await this.delete(existing.id, true);
2034
2723
  }
2035
2724
  }
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
+ }
2036
2768
  const uploaded = await uploader.upload({
2037
2769
  ...opts,
2770
+ name: targetName,
2038
2771
  parent: parentId
2039
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
+ }
2040
2783
  return await this.pluginManager.runAfterUpload(uploaded);
2041
2784
  }
2042
2785
  /**
@@ -2277,16 +3020,16 @@ var init_client = __esm({
2277
3020
  durationMs: 0
2278
3021
  };
2279
3022
  const collectFiles = async (dir, base) => {
2280
- 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 });
2281
3024
  const files = [];
2282
3025
  for (const entry of entries) {
2283
- const fullPath = import_node_path4.default.join(dir, entry.name);
2284
- 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);
2285
3028
  if (entry.isDirectory()) {
2286
3029
  const sub = await collectFiles(fullPath, relPath);
2287
3030
  files.push(...sub);
2288
3031
  } else if (entry.isFile()) {
2289
- const stat = await import_node_fs5.default.promises.stat(fullPath);
3032
+ const stat = await import_node_fs6.default.promises.stat(fullPath);
2290
3033
  files.push({ fullPath, relPath, size: stat.size });
2291
3034
  }
2292
3035
  }
@@ -2299,11 +3042,11 @@ var init_client = __esm({
2299
3042
  if (remoteDirCache.has(relDir)) {
2300
3043
  return remoteDirCache.get(relDir);
2301
3044
  }
2302
- const parts = relDir.split(import_node_path4.default.sep).filter(Boolean);
3045
+ const parts = relDir.split(import_node_path6.default.sep).filter(Boolean);
2303
3046
  let currentParent = targetFolderId;
2304
3047
  let currentRel = "";
2305
3048
  for (const part of parts) {
2306
- currentRel = currentRel ? import_node_path4.default.join(currentRel, part) : part;
3049
+ currentRel = currentRel ? import_node_path6.default.join(currentRel, part) : part;
2307
3050
  if (remoteDirCache.has(currentRel)) {
2308
3051
  currentParent = remoteDirCache.get(currentRel);
2309
3052
  continue;
@@ -2332,8 +3075,8 @@ var init_client = __esm({
2332
3075
  };
2333
3076
  await pool.map(allFiles, async (fileItem) => {
2334
3077
  try {
2335
- const relDir = import_node_path4.default.dirname(fileItem.relPath);
2336
- 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);
2337
3080
  const parentFolderId = await ensureRemoteSubdir(relDir === "." ? "" : relDir);
2338
3081
  if (options.onFileStart) {
2339
3082
  options.onFileStart(fileItem.fullPath, fileItem.relPath);
@@ -2451,6 +3194,217 @@ var init_client = __esm({
2451
3194
  const engine = new SmartSyncEngine(this.driveClient);
2452
3195
  return await engine.pullFolder(folderId, localDestinationDir, options);
2453
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
+ }
2454
3408
  /**
2455
3409
  * Calculates local file MD5 hash for integrity and deduplication checks
2456
3410
  */
@@ -2474,8 +3428,8 @@ __export(cli_exports, {
2474
3428
  });
2475
3429
  module.exports = __toCommonJS(cli_exports);
2476
3430
  init_cjs_shims();
2477
- var import_node_fs6 = __toESM(require("fs"), 1);
2478
- 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);
2479
3433
  var import_commander = require("commander");
2480
3434
  var import_chalk2 = __toESM(require("chalk"), 1);
2481
3435
  var import_ora = __toESM(require("ora"), 1);
@@ -2487,8 +3441,8 @@ init_cjs_shims();
2487
3441
  var import_node_readline = __toESM(require("readline"), 1);
2488
3442
  var import_chalk = __toESM(require("chalk"), 1);
2489
3443
  init_format();
2490
- function terminalLink(text, url) {
2491
- return `\x1B]8;;${url}\x07${text}\x1B]8;;\x07`;
3444
+ function terminalLink(text, url2) {
3445
+ return `\x1B]8;;${url2}\x07${text}\x1B]8;;\x07`;
2492
3446
  }
2493
3447
  function renderFileRow(item, index) {
2494
3448
  const isDir = item.mimeType === "application/vnd.google-apps.folder";
@@ -2710,12 +3664,12 @@ program.command("explore [folder]").description("Interactive terminal keyboard f
2710
3664
  process.exit(1);
2711
3665
  }
2712
3666
  });
2713
- 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) => {
2714
- if (!import_node_fs6.default.existsSync(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)) {
2715
3669
  console.error(import_chalk2.default.red(`\u274C Local file not found: ${localFile}`));
2716
3670
  process.exit(1);
2717
3671
  }
2718
- const fileName = import_node_path5.default.basename(localFile);
3672
+ const fileName = import_node_path7.default.basename(localFile);
2719
3673
  const spinner = (0, import_ora.default)(`Preparing upload: ${fileName}...`).start();
2720
3674
  try {
2721
3675
  const client = await getClient(options);
@@ -2726,6 +3680,7 @@ program.command("upload <localFile> [remotePath]").description("Upload a file wi
2726
3680
  name: fileName,
2727
3681
  parent: remotePath,
2728
3682
  overwrite: options.overwrite,
3683
+ deduplicate: options.dedup,
2729
3684
  onProgress: (p) => {
2730
3685
  process.stdout.write(
2731
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)}]`
@@ -2810,7 +3765,7 @@ program.command("delete <fileIdOrPath>").description("Move a file/folder to tras
2810
3765
  }
2811
3766
  });
2812
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) => {
2813
- if (!import_node_fs6.default.existsSync(localDir)) {
3768
+ if (!import_node_fs7.default.existsSync(localDir)) {
2814
3769
  console.error(import_chalk2.default.red(`\u274C Local directory not found: ${localDir}`));
2815
3770
  process.exit(1);
2816
3771
  }
@@ -2978,8 +3933,8 @@ program.command("login").description("Interactive 1-click browser OAuth2 sign-in
2978
3933
  if (result.tokens.refresh_token) {
2979
3934
  console.log(`Refresh Token: ${import_chalk2.default.green(result.tokens.refresh_token?.slice(0, 25) + "...")}`);
2980
3935
  }
2981
- const outPath = import_node_path5.default.resolve("./gdrive-tokens.json");
2982
- import_node_fs6.default.writeFileSync(outPath, JSON.stringify(result.tokens, null, 2), "utf8");
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");
2983
3938
  console.log(`\u{1F4BE} Saved tokens to: ${import_chalk2.default.bold(outPath)}
2984
3939
  `);
2985
3940
  } catch (err) {
@@ -2987,6 +3942,104 @@ program.command("login").description("Interactive 1-click browser OAuth2 sign-in
2987
3942
  process.exit(1);
2988
3943
  }
2989
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})`)}`);
4007
+ }
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)
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
+ });
4038
+ } catch (err) {
4039
+ console.error(import_chalk2.default.red(`Failed to start WebDAV server: ${err.message}`));
4040
+ process.exit(1);
4041
+ }
4042
+ });
2990
4043
  function runCLI() {
2991
4044
  program.parse(process.argv);
2992
4045
  }