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/index.cjs CHANGED
@@ -5,6 +5,9 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
8
11
  var __export = (target, all) => {
9
12
  for (var name in all)
10
13
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -27,6 +30,242 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
27
30
  ));
28
31
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
32
 
33
+ // node_modules/tsup/assets/cjs_shims.js
34
+ var init_cjs_shims = __esm({
35
+ "node_modules/tsup/assets/cjs_shims.js"() {
36
+ "use strict";
37
+ }
38
+ });
39
+
40
+ // src/server/webdav.ts
41
+ var webdav_exports = {};
42
+ __export(webdav_exports, {
43
+ startWebDAVServer: () => startWebDAVServer
44
+ });
45
+ async function startWebDAVServer(drive2, options = {}) {
46
+ const port = options.port || 8080;
47
+ const host = options.host || "127.0.0.1";
48
+ await drive2.init();
49
+ const server = import_node_http2.default.createServer(async (req, res) => {
50
+ try {
51
+ const parsedUrl = import_node_url.default.parse(req.url || "/", true);
52
+ const decodedPath = decodeURIComponent(parsedUrl.pathname || "/");
53
+ const virtualPath = decodedPath === "" ? "/" : decodedPath;
54
+ switch (req.method) {
55
+ case "OPTIONS": {
56
+ res.writeHead(200, {
57
+ DAV: "1, 2",
58
+ Allow: "OPTIONS, GET, HEAD, POST, PUT, DELETE, MKCOL, MOVE, COPY, PROPFIND",
59
+ "MS-Author-Via": "DAV"
60
+ });
61
+ res.end();
62
+ return;
63
+ }
64
+ case "PROPFIND": {
65
+ const depth = req.headers["depth"] || "1";
66
+ const xml = await handlePropfind(drive2, virtualPath, depth);
67
+ res.writeHead(207, {
68
+ "Content-Type": "application/xml; charset=utf-8"
69
+ });
70
+ res.end(xml);
71
+ return;
72
+ }
73
+ case "GET":
74
+ case "HEAD": {
75
+ if (virtualPath === "/" || virtualPath === "") {
76
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
77
+ res.end("<h1>DriveKit WebDAV Server Running</h1><p>Connect via Finder or WebDAV client.</p>");
78
+ return;
79
+ }
80
+ try {
81
+ const file = await drive2.getFile(virtualPath);
82
+ if (file.mimeType === "application/vnd.google-apps.folder") {
83
+ res.writeHead(405, { "Content-Type": "text/plain" });
84
+ res.end("Cannot GET a directory");
85
+ return;
86
+ }
87
+ const stream = await drive2.createReadStream(virtualPath);
88
+ res.writeHead(200, {
89
+ "Content-Type": file.mimeType || "application/octet-stream",
90
+ "Content-Length": file.size || void 0
91
+ });
92
+ if (req.method === "HEAD") {
93
+ res.end();
94
+ } else {
95
+ stream.pipe(res);
96
+ }
97
+ } catch (e) {
98
+ res.writeHead(404, { "Content-Type": "text/plain" });
99
+ res.end("File Not Found");
100
+ }
101
+ return;
102
+ }
103
+ case "PUT": {
104
+ const remoteDir = import_node_path5.default.dirname(virtualPath);
105
+ const fileName = import_node_path5.default.basename(virtualPath);
106
+ await drive2.mkdirp(remoteDir);
107
+ const chunks = [];
108
+ req.on("data", (chunk) => chunks.push(chunk));
109
+ req.on("end", async () => {
110
+ try {
111
+ const buffer = Buffer.concat(chunks);
112
+ await drive2.upload({
113
+ source: buffer,
114
+ filename: fileName,
115
+ parent: remoteDir,
116
+ overwrite: true
117
+ });
118
+ res.writeHead(201, { "Content-Type": "text/plain" });
119
+ res.end("Created");
120
+ } catch (err) {
121
+ res.writeHead(500, { "Content-Type": "text/plain" });
122
+ res.end(err.message || "Upload failed");
123
+ }
124
+ });
125
+ return;
126
+ }
127
+ case "MKCOL": {
128
+ try {
129
+ await drive2.mkdirp(virtualPath);
130
+ res.writeHead(201, { "Content-Type": "text/plain" });
131
+ res.end("Collection Created");
132
+ } catch (err) {
133
+ res.writeHead(500, { "Content-Type": "text/plain" });
134
+ res.end(err.message);
135
+ }
136
+ return;
137
+ }
138
+ case "DELETE": {
139
+ try {
140
+ await drive2.delete(virtualPath, true);
141
+ res.writeHead(204);
142
+ res.end();
143
+ } catch (err) {
144
+ res.writeHead(404, { "Content-Type": "text/plain" });
145
+ res.end("Not Found");
146
+ }
147
+ return;
148
+ }
149
+ case "MOVE": {
150
+ const destination = req.headers["destination"];
151
+ if (!destination || typeof destination !== "string") {
152
+ res.writeHead(400, { "Content-Type": "text/plain" });
153
+ res.end("Destination header missing");
154
+ return;
155
+ }
156
+ const destUrl = import_node_url.default.parse(destination);
157
+ const destPath = decodeURIComponent(destUrl.pathname || "");
158
+ const newName = import_node_path5.default.basename(destPath);
159
+ const newParent = import_node_path5.default.dirname(destPath);
160
+ try {
161
+ await drive2.move(virtualPath, newParent);
162
+ if (newName !== import_node_path5.default.basename(virtualPath)) {
163
+ await drive2.rename(destPath, newName);
164
+ }
165
+ res.writeHead(201);
166
+ res.end("Moved");
167
+ } catch (err) {
168
+ res.writeHead(500, { "Content-Type": "text/plain" });
169
+ res.end(err.message);
170
+ }
171
+ return;
172
+ }
173
+ default: {
174
+ res.writeHead(501, { "Content-Type": "text/plain" });
175
+ res.end("Method Not Implemented");
176
+ }
177
+ }
178
+ } catch (globalErr) {
179
+ res.writeHead(500, { "Content-Type": "text/plain" });
180
+ res.end(`Internal Server Error: ${globalErr.message}`);
181
+ }
182
+ });
183
+ return new Promise((resolve) => {
184
+ server.listen(port, host, () => {
185
+ const serverUrl = `http://${host}:${port}`;
186
+ resolve({
187
+ server,
188
+ url: serverUrl,
189
+ close: () => new Promise((resClose) => server.close(() => resClose()))
190
+ });
191
+ });
192
+ });
193
+ }
194
+ async function handlePropfind(drive2, virtualPath, depth) {
195
+ const responses = [];
196
+ let isFolder = false;
197
+ let selfItem = null;
198
+ if (virtualPath === "/" || virtualPath === "") {
199
+ isFolder = true;
200
+ responses.push(renderWebDAVResponse("/", true, 0, (/* @__PURE__ */ new Date()).toISOString()));
201
+ } else {
202
+ try {
203
+ selfItem = await drive2.getFile(virtualPath);
204
+ isFolder = selfItem.mimeType === "application/vnd.google-apps.folder";
205
+ responses.push(
206
+ renderWebDAVResponse(
207
+ virtualPath,
208
+ isFolder,
209
+ selfItem.size ? parseInt(selfItem.size, 10) : 0,
210
+ selfItem.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
211
+ )
212
+ );
213
+ } catch {
214
+ return `<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:"></D:multistatus>`;
215
+ }
216
+ }
217
+ if (isFolder && depth !== "0") {
218
+ try {
219
+ const children = await drive2.ls(virtualPath);
220
+ for (const child of children) {
221
+ const childIsFolder = child.mimeType === "application/vnd.google-apps.folder";
222
+ const childPath = virtualPath === "/" ? `/${child.name}` : `${virtualPath}/${child.name}`;
223
+ responses.push(
224
+ renderWebDAVResponse(
225
+ childPath,
226
+ childIsFolder,
227
+ child.size ? parseInt(child.size, 10) : 0,
228
+ child.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
229
+ )
230
+ );
231
+ }
232
+ } catch {
233
+ }
234
+ }
235
+ return `<?xml version="1.0" encoding="utf-8"?>
236
+ <D:multistatus xmlns:D="DAV:">
237
+ ${responses.join("\n")}
238
+ </D:multistatus>`;
239
+ }
240
+ function renderWebDAVResponse(href, isDir, size, modifiedTime) {
241
+ const encodedHref = encodeURI(href);
242
+ const resourceType = isDir ? "<D:collection/>" : "";
243
+ const dateFormatted = new Date(modifiedTime).toUTCString();
244
+ return ` <D:response>
245
+ <D:href>${encodedHref}</D:href>
246
+ <D:propstat>
247
+ <D:prop>
248
+ <D:displayname>${import_node_path5.default.basename(href) || "root"}</D:displayname>
249
+ <D:resourcetype>${resourceType}</D:resourcetype>
250
+ <D:getcontentlength>${isDir ? "0" : size}</D:getcontentlength>
251
+ <D:getlastmodified>${dateFormatted}</D:getlastmodified>
252
+ <D:status>HTTP/1.1 200 OK</D:status>
253
+ </D:prop>
254
+ <D:status>HTTP/1.1 200 OK</D:status>
255
+ </D:propstat>
256
+ </D:response>`;
257
+ }
258
+ var import_node_http2, import_node_url, import_node_path5;
259
+ var init_webdav = __esm({
260
+ "src/server/webdav.ts"() {
261
+ "use strict";
262
+ init_cjs_shims();
263
+ import_node_http2 = __toESM(require("http"), 1);
264
+ import_node_url = __toESM(require("url"), 1);
265
+ import_node_path5 = __toESM(require("path"), 1);
266
+ }
267
+ });
268
+
30
269
  // src/index.ts
31
270
  var index_exports = {};
32
271
  __export(index_exports, {
@@ -49,13 +288,17 @@ __export(index_exports, {
49
288
  GOOGLE_WORKSPACE_MIME_TYPES: () => GOOGLE_WORKSPACE_MIME_TYPES,
50
289
  MIN_CHUNK_SIZE: () => MIN_CHUNK_SIZE,
51
290
  MULTIPART_THRESHOLD: () => MULTIPART_THRESHOLD,
291
+ MemoryMetadataCache: () => MemoryMetadataCache,
52
292
  PathResolver: () => PathResolver,
53
293
  PluginManager: () => PluginManager,
54
294
  ResumableUploader: () => ResumableUploader,
55
295
  SmartSyncEngine: () => SmartSyncEngine,
296
+ SqliteMetadataCache: () => SqliteMetadataCache,
56
297
  StorageCleaner: () => StorageCleaner,
57
298
  calculateFileMd5: () => calculateFileMd5,
299
+ createAutoNamePlugin: () => createAutoNamePlugin,
58
300
  createDrive: () => createDrive,
301
+ createWebhookPlugin: () => createWebhookPlugin,
59
302
  default: () => index_default,
60
303
  formatBytes: () => formatBytes,
61
304
  formatDuration: () => formatDuration,
@@ -68,21 +311,26 @@ __export(index_exports, {
68
311
  lookupMimeType: () => lookupMimeType,
69
312
  renderFileRow: () => renderFileRow,
70
313
  runInteractiveExplorer: () => runInteractiveExplorer,
314
+ startWebDAVServer: () => startWebDAVServer,
71
315
  terminalLink: () => terminalLink,
72
316
  withRetry: () => withRetry
73
317
  });
74
318
  module.exports = __toCommonJS(index_exports);
319
+ init_cjs_shims();
75
320
 
76
321
  // src/core/client.ts
77
- var import_node_fs5 = __toESM(require("fs"), 1);
78
- var import_node_path4 = __toESM(require("path"), 1);
322
+ init_cjs_shims();
323
+ var import_node_fs6 = __toESM(require("fs"), 1);
324
+ var import_node_path6 = __toESM(require("path"), 1);
79
325
  var import_drive3 = require("@googleapis/drive");
80
326
 
81
327
  // src/auth/authenticator.ts
328
+ init_cjs_shims();
82
329
  var import_node_fs = __toESM(require("fs"), 1);
83
330
  var import_drive = require("@googleapis/drive");
84
331
 
85
332
  // src/errors.ts
333
+ init_cjs_shims();
86
334
  var DriveKitError = class extends Error {
87
335
  code;
88
336
  originalError;
@@ -223,7 +471,11 @@ var DriveAuthenticator = class {
223
471
  }
224
472
  };
225
473
 
474
+ // src/core/path-resolver.ts
475
+ init_cjs_shims();
476
+
226
477
  // src/utils/mime.ts
478
+ init_cjs_shims();
227
479
  var import_mime_types = __toESM(require("mime-types"), 1);
228
480
  var GOOGLE_WORKSPACE_MIME_TYPES = {
229
481
  DOCUMENT: "application/vnd.google-apps.document",
@@ -267,6 +519,7 @@ function isGoogleWorkspaceDoc(mimeType) {
267
519
  }
268
520
 
269
521
  // src/utils/retry.ts
522
+ init_cjs_shims();
270
523
  var DEFAULT_RETRYABLE_STATUSES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
271
524
  function isRetryableError(error) {
272
525
  if (!error) return false;
@@ -323,11 +576,13 @@ var PathResolver = class {
323
576
  cache = /* @__PURE__ */ new Map();
324
577
  cacheTTL;
325
578
  enableCache;
579
+ metadataCache;
326
580
  constructor(drive2, rootFolderId = "root", options) {
327
581
  this.drive = drive2;
328
582
  this.rootFolderId = rootFolderId;
329
583
  this.enableCache = options?.enableCache ?? true;
330
584
  this.cacheTTL = options?.cacheTTL ?? 5 * 60 * 1e3;
585
+ this.metadataCache = options?.metadataCache;
331
586
  }
332
587
  /**
333
588
  * Normalizes a virtual path (e.g. "///Backups//2026/" -> "/Backups/2026")
@@ -342,21 +597,31 @@ var PathResolver = class {
342
597
  /**
343
598
  * Gets cache key for a path
344
599
  */
345
- getCacheKey(path5) {
346
- return `${this.rootFolderId}:${this.normalizePath(path5)}`;
600
+ getCacheKey(path7) {
601
+ return `${this.rootFolderId}:${this.normalizePath(path7)}`;
347
602
  }
348
603
  /**
349
604
  * Clears the path cache
350
605
  */
351
606
  clearCache() {
352
607
  this.cache.clear();
608
+ if (this.metadataCache) {
609
+ this.metadataCache.clear();
610
+ }
353
611
  }
354
612
  /**
355
613
  * Invalidate a single path from cache
356
614
  */
357
- invalidatePath(path5) {
358
- const key = this.getCacheKey(path5);
615
+ invalidatePath(path7) {
616
+ const norm = this.normalizePath(path7);
617
+ const key = this.getCacheKey(norm);
359
618
  this.cache.delete(key);
619
+ if (this.metadataCache) {
620
+ const item = this.metadataCache.getByPath(norm);
621
+ if (item) {
622
+ this.metadataCache.deleteFile(item.id);
623
+ }
624
+ }
360
625
  }
361
626
  /**
362
627
  * Resolves a path to a Google Drive item (file or folder).
@@ -372,6 +637,17 @@ var PathResolver = class {
372
637
  mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER
373
638
  };
374
639
  }
640
+ if (this.metadataCache) {
641
+ const persistentCached = this.metadataCache.getByPath(norm);
642
+ if (persistentCached) {
643
+ return {
644
+ id: persistentCached.id,
645
+ name: persistentCached.name,
646
+ isFolder: persistentCached.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
647
+ mimeType: persistentCached.mimeType
648
+ };
649
+ }
650
+ }
375
651
  if (this.enableCache) {
376
652
  const cached = this.cache.get(this.getCacheKey(norm));
377
653
  if (cached && cached.expiresAt > Date.now()) {
@@ -390,6 +666,21 @@ var PathResolver = class {
390
666
  const segment = segments[i];
391
667
  const isLast = i === segments.length - 1;
392
668
  currentPath += `/${segment}`;
669
+ if (this.metadataCache) {
670
+ const pCached = this.metadataCache.getByPath(currentPath);
671
+ if (pCached) {
672
+ currentParentId = pCached.id;
673
+ if (isLast) {
674
+ return {
675
+ id: pCached.id,
676
+ name: pCached.name,
677
+ isFolder: pCached.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
678
+ mimeType: pCached.mimeType
679
+ };
680
+ }
681
+ continue;
682
+ }
683
+ }
393
684
  if (this.enableCache) {
394
685
  const cached = this.cache.get(this.getCacheKey(currentPath));
395
686
  if (cached && cached.expiresAt > Date.now()) {
@@ -434,6 +725,16 @@ var PathResolver = class {
434
725
  }
435
726
  if (file && file.id) {
436
727
  currentParentId = file.id;
728
+ if (this.metadataCache) {
729
+ this.metadataCache.upsertFile({
730
+ id: file.id,
731
+ name: file.name || segment,
732
+ mimeType: file.mimeType || "",
733
+ parentId: currentParentId,
734
+ path: currentPath,
735
+ trashed: false
736
+ });
737
+ }
437
738
  if (this.enableCache) {
438
739
  this.cache.set(this.getCacheKey(currentPath), {
439
740
  id: file.id,
@@ -468,6 +769,16 @@ var PathResolver = class {
468
769
  throw new Error(`Failed to create folder "${segment}" under parent "${currentParentId}"`);
469
770
  }
470
771
  currentParentId = newFolder.id;
772
+ if (this.metadataCache) {
773
+ this.metadataCache.upsertFile({
774
+ id: newFolder.id,
775
+ name: segment,
776
+ mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
777
+ parentId: currentParentId,
778
+ path: currentPath,
779
+ trashed: false
780
+ });
781
+ }
471
782
  if (this.enableCache) {
472
783
  this.cache.set(this.getCacheKey(currentPath), {
473
784
  id: newFolder.id,
@@ -504,10 +815,12 @@ var PathResolver = class {
504
815
  };
505
816
 
506
817
  // src/core/resumable-uploader.ts
818
+ init_cjs_shims();
507
819
  var import_node_fs2 = __toESM(require("fs"), 1);
508
820
  var import_node_path = __toESM(require("path"), 1);
509
821
 
510
822
  // src/utils/format.ts
823
+ init_cjs_shims();
511
824
  function formatBytes(bytes, decimals = 2) {
512
825
  if (bytes === 0) return "0 B";
513
826
  const k = 1024;
@@ -835,6 +1148,7 @@ var ResumableUploader = class {
835
1148
  };
836
1149
 
837
1150
  // src/core/downloader.ts
1151
+ init_cjs_shims();
838
1152
  var import_node_fs3 = __toESM(require("fs"), 1);
839
1153
  var import_node_path2 = __toESM(require("path"), 1);
840
1154
  var import_promises = require("stream/promises");
@@ -930,9 +1244,28 @@ var Downloader = class {
930
1244
  size: totalBytes
931
1245
  };
932
1246
  }
1247
+ /**
1248
+ * Returns a raw ReadableStream for the file, supporting HTTP Range requests for partial content / streaming.
1249
+ */
1250
+ async createReadStream(fileId, options) {
1251
+ const headers = {};
1252
+ if (options?.start !== void 0 || options?.end !== void 0) {
1253
+ const start = options.start ?? 0;
1254
+ const end = options.end !== void 0 ? options.end : "";
1255
+ headers["Range"] = `bytes=${start}-${end}`;
1256
+ }
1257
+ const res = await withRetry(async () => {
1258
+ return await this.drive.files.get(
1259
+ { fileId, alt: "media", supportsAllDrives: true },
1260
+ { responseType: "stream", headers }
1261
+ );
1262
+ });
1263
+ return res.data;
1264
+ }
933
1265
  };
934
1266
 
935
1267
  // src/core/query-builder.ts
1268
+ init_cjs_shims();
936
1269
  var DriveQueryBuilder = class {
937
1270
  drive;
938
1271
  conditions = [];
@@ -1049,6 +1382,19 @@ var DriveQueryBuilder = class {
1049
1382
  this.conditions.push(`(${condition})`);
1050
1383
  return this;
1051
1384
  }
1385
+ /**
1386
+ * Custom raw query condition (alias for raw)
1387
+ */
1388
+ custom(condition) {
1389
+ return this.raw(condition);
1390
+ }
1391
+ /**
1392
+ * Filter: Exact MD5 checksum match
1393
+ */
1394
+ md5(checksum) {
1395
+ this.conditions.push(`md5Checksum = '${this.escape(checksum)}'`);
1396
+ return this;
1397
+ }
1052
1398
  /**
1053
1399
  * Sort ordering (e.g. 'modifiedTime desc', 'name', 'folder,modifiedTime desc')
1054
1400
  */
@@ -1095,6 +1441,12 @@ var DriveQueryBuilder = class {
1095
1441
  });
1096
1442
  return res.data.files || [];
1097
1443
  }
1444
+ /**
1445
+ * Executes query and returns array of matching files (alias for list)
1446
+ */
1447
+ async execute() {
1448
+ return await this.list();
1449
+ }
1098
1450
  /**
1099
1451
  * Returns the first matching file, or null if not found
1100
1452
  */
@@ -1142,6 +1494,7 @@ var DriveQueryBuilder = class {
1142
1494
  };
1143
1495
 
1144
1496
  // src/core/concurrency-pool.ts
1497
+ init_cjs_shims();
1145
1498
  var ConcurrencyPool = class {
1146
1499
  concurrency;
1147
1500
  running = 0;
@@ -1186,6 +1539,7 @@ var ConcurrencyPool = class {
1186
1539
  };
1187
1540
 
1188
1541
  // src/core/watcher.ts
1542
+ init_cjs_shims();
1189
1543
  var import_node_events = require("events");
1190
1544
  var DriveWatcher = class extends import_node_events.EventEmitter {
1191
1545
  drive;
@@ -1299,6 +1653,7 @@ var DriveWatcher = class extends import_node_events.EventEmitter {
1299
1653
  };
1300
1654
 
1301
1655
  // src/core/storage-cleaner.ts
1656
+ init_cjs_shims();
1302
1657
  var StorageCleaner = class {
1303
1658
  drive;
1304
1659
  constructor(drive2) {
@@ -1395,6 +1750,7 @@ var StorageCleaner = class {
1395
1750
  };
1396
1751
 
1397
1752
  // src/core/smart-sync.ts
1753
+ init_cjs_shims();
1398
1754
  var import_node_fs4 = __toESM(require("fs"), 1);
1399
1755
  var import_node_path3 = __toESM(require("path"), 1);
1400
1756
  var import_node_crypto = __toESM(require("crypto"), 1);
@@ -1520,6 +1876,7 @@ var SmartSyncEngine = class {
1520
1876
  };
1521
1877
 
1522
1878
  // src/auth/browser-login.ts
1879
+ init_cjs_shims();
1523
1880
  var import_node_http = __toESM(require("http"), 1);
1524
1881
  var import_node_child_process = require("child_process");
1525
1882
  var import_drive2 = require("@googleapis/drive");
@@ -1628,6 +1985,7 @@ ${authUrl}
1628
1985
  }
1629
1986
 
1630
1987
  // src/core/resource-refs.ts
1988
+ init_cjs_shims();
1631
1989
  var DriveFileRef = class {
1632
1990
  drive;
1633
1991
  pathOrId;
@@ -1688,6 +2046,22 @@ var DriveFileRef = class {
1688
2046
  async getLink() {
1689
2047
  return await this.drive.getShareableLink(this.pathOrId);
1690
2048
  }
2049
+ /** Returns a ReadableStream for this file, optionally with byte Range requests */
2050
+ async createReadStream(options) {
2051
+ return await this.drive.createReadStream(this.pathOrId, options);
2052
+ }
2053
+ /** Grants access to a specific email with custom role and notification */
2054
+ async grantAccess(options) {
2055
+ return await this.drive.grantAccess(this.pathOrId, options);
2056
+ }
2057
+ /** Revokes access by permission ID or user email */
2058
+ async revokeAccess(permissionIdOrEmail) {
2059
+ return await this.drive.revokeAccess(this.pathOrId, permissionIdOrEmail);
2060
+ }
2061
+ /** Lists all granted permissions on this file */
2062
+ async listPermissions() {
2063
+ return await this.drive.listPermissions(this.pathOrId);
2064
+ }
1691
2065
  };
1692
2066
  var DriveFolderRef = class {
1693
2067
  drive;
@@ -1725,9 +2099,19 @@ var DriveFolderRef = class {
1725
2099
  async watch(options = {}) {
1726
2100
  return await this.drive.watch(this.pathOrId, options);
1727
2101
  }
2102
+ /** Grants access to this entire folder */
2103
+ async grantAccess(options) {
2104
+ return await this.drive.grantAccess(this.pathOrId, options);
2105
+ }
2106
+ /** Creates a writable stream directly into a file inside this folder */
2107
+ async createWriteStream(fileName, options) {
2108
+ const targetPath = this.pathOrId.endsWith("/") ? `${this.pathOrId}${fileName}` : `${this.pathOrId}/${fileName}`;
2109
+ return await this.drive.createWriteStream(targetPath, options);
2110
+ }
1728
2111
  };
1729
2112
 
1730
2113
  // src/core/plugins.ts
2114
+ init_cjs_shims();
1731
2115
  var PluginManager = class {
1732
2116
  plugins = [];
1733
2117
  use(plugin) {
@@ -1775,15 +2159,413 @@ var PluginManager = class {
1775
2159
  return current;
1776
2160
  }
1777
2161
  };
2162
+ function createWebhookPlugin(options) {
2163
+ const events = options.events || ["upload"];
2164
+ return {
2165
+ name: "drivekit-official-webhook",
2166
+ async afterUpload(file) {
2167
+ if (!events.includes("upload")) return;
2168
+ try {
2169
+ await fetch(options.url, {
2170
+ method: "POST",
2171
+ headers: { "Content-Type": "application/json", ...options.headers || {} },
2172
+ body: JSON.stringify({
2173
+ event: "drivekit:upload",
2174
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2175
+ file: {
2176
+ id: file.id,
2177
+ name: file.name,
2178
+ size: file.size,
2179
+ mimeType: file.mimeType
2180
+ }
2181
+ })
2182
+ });
2183
+ } catch (e) {
2184
+ }
2185
+ },
2186
+ async afterDownload(result) {
2187
+ if (!events.includes("download")) return;
2188
+ try {
2189
+ await fetch(options.url, {
2190
+ method: "POST",
2191
+ headers: { "Content-Type": "application/json", ...options.headers || {} },
2192
+ body: JSON.stringify({
2193
+ event: "drivekit:download",
2194
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2195
+ file: {
2196
+ name: result.name,
2197
+ size: result.size
2198
+ }
2199
+ })
2200
+ });
2201
+ } catch (e) {
2202
+ }
2203
+ }
2204
+ };
2205
+ }
2206
+ function createAutoNamePlugin(options) {
2207
+ return {
2208
+ name: "drivekit-official-autoname",
2209
+ beforeUpload(opts) {
2210
+ let name = opts.filename;
2211
+ if (!name && typeof opts.source === "string") {
2212
+ const pathModule2 = require("path");
2213
+ name = pathModule2.basename(opts.source);
2214
+ }
2215
+ if (!name) return opts;
2216
+ const pathModule = require("path");
2217
+ const ext = pathModule.extname(name);
2218
+ const base = pathModule.basename(name, ext);
2219
+ let finalName = base;
2220
+ if (options.prefix) finalName = `${options.prefix}${finalName}`;
2221
+ if (options.appendTimestamp) {
2222
+ finalName = `${finalName}_${Date.now()}`;
2223
+ }
2224
+ if (options.suffix) finalName = `${finalName}${options.suffix}`;
2225
+ finalName = `${finalName}${ext}`;
2226
+ return {
2227
+ ...opts,
2228
+ filename: finalName
2229
+ };
2230
+ }
2231
+ };
2232
+ }
2233
+
2234
+ // src/core/cache.ts
2235
+ init_cjs_shims();
2236
+ var import_node_os = __toESM(require("os"), 1);
2237
+ var import_node_path4 = __toESM(require("path"), 1);
2238
+ var import_node_fs5 = __toESM(require("fs"), 1);
2239
+ var SqliteMetadataCache = class {
2240
+ db = null;
2241
+ dbPath;
2242
+ initialized = false;
2243
+ fallbackMemory;
2244
+ constructor(customPath) {
2245
+ if (customPath) {
2246
+ this.dbPath = customPath;
2247
+ } else {
2248
+ const dir = import_node_path4.default.join(import_node_os.default.homedir(), ".drivekit");
2249
+ if (!import_node_fs5.default.existsSync(dir)) {
2250
+ try {
2251
+ import_node_fs5.default.mkdirSync(dir, { recursive: true });
2252
+ } catch {
2253
+ }
2254
+ }
2255
+ this.dbPath = import_node_path4.default.join(dir, "cache.db");
2256
+ }
2257
+ }
2258
+ init() {
2259
+ if (this.initialized) return;
2260
+ try {
2261
+ const { DatabaseSync } = require("sqlite");
2262
+ if (!DatabaseSync) {
2263
+ throw new Error("DatabaseSync not available");
2264
+ }
2265
+ this.db = new DatabaseSync(this.dbPath);
2266
+ this.db.exec(`
2267
+ PRAGMA journal_mode = WAL;
2268
+ PRAGMA synchronous = NORMAL;
2269
+
2270
+ CREATE TABLE IF NOT EXISTS files (
2271
+ id TEXT PRIMARY KEY,
2272
+ name TEXT NOT NULL,
2273
+ mimeType TEXT NOT NULL,
2274
+ size INTEGER,
2275
+ parentId TEXT,
2276
+ path TEXT,
2277
+ md5Checksum TEXT,
2278
+ trashed INTEGER DEFAULT 0,
2279
+ modifiedTime TEXT,
2280
+ updatedAt INTEGER
2281
+ );
2282
+
2283
+ CREATE TABLE IF NOT EXISTS meta (
2284
+ key TEXT PRIMARY KEY,
2285
+ value TEXT NOT NULL
2286
+ );
2287
+
2288
+ CREATE INDEX IF NOT EXISTS idx_files_path ON files(path);
2289
+ CREATE INDEX IF NOT EXISTS idx_files_parent ON files(parentId);
2290
+ CREATE INDEX IF NOT EXISTS idx_files_md5 ON files(md5Checksum);
2291
+ CREATE INDEX IF NOT EXISTS idx_files_name ON files(name);
2292
+ `);
2293
+ this.initialized = true;
2294
+ } catch (err) {
2295
+ this.fallbackMemory = new MemoryMetadataCache();
2296
+ this.fallbackMemory.init();
2297
+ this.initialized = true;
2298
+ this.db = null;
2299
+ }
2300
+ }
2301
+ getById(id) {
2302
+ if (this.fallbackMemory) return this.fallbackMemory.getById(id);
2303
+ if (!this.initialized || !this.db) return null;
2304
+ const stmt = this.db.prepare("SELECT * FROM files WHERE id = ?");
2305
+ const row = stmt.get(id);
2306
+ return row ? this.mapRow(row) : null;
2307
+ }
2308
+ getByPath(normalizedPath) {
2309
+ if (this.fallbackMemory) return this.fallbackMemory.getByPath(normalizedPath);
2310
+ if (!this.initialized || !this.db) return null;
2311
+ const stmt = this.db.prepare("SELECT * FROM files WHERE path = ? AND trashed = 0 LIMIT 1");
2312
+ const row = stmt.get(normalizedPath);
2313
+ return row ? this.mapRow(row) : null;
2314
+ }
2315
+ getChildren(parentId) {
2316
+ if (this.fallbackMemory) return this.fallbackMemory.getChildren(parentId);
2317
+ if (!this.initialized || !this.db) return [];
2318
+ const stmt = this.db.prepare("SELECT * FROM files WHERE parentId = ? AND trashed = 0 ORDER BY name ASC");
2319
+ const rows = stmt.all(parentId);
2320
+ return rows.map((r) => this.mapRow(r));
2321
+ }
2322
+ findByMd5(md5) {
2323
+ if (this.fallbackMemory) return this.fallbackMemory.findByMd5(md5);
2324
+ if (!this.initialized || !this.db || !md5) return null;
2325
+ const stmt = this.db.prepare("SELECT * FROM files WHERE md5Checksum = ? AND trashed = 0 LIMIT 1");
2326
+ const row = stmt.get(md5.toLowerCase());
2327
+ return row ? this.mapRow(row) : null;
2328
+ }
2329
+ searchByName(query) {
2330
+ if (this.fallbackMemory) return this.fallbackMemory.searchByName(query);
2331
+ if (!this.initialized || !this.db) return [];
2332
+ const stmt = this.db.prepare("SELECT * FROM files WHERE name LIKE ? AND trashed = 0 LIMIT 50");
2333
+ const rows = stmt.all(`%${query}%`);
2334
+ return rows.map((r) => this.mapRow(r));
2335
+ }
2336
+ upsertFile(entry) {
2337
+ if (this.fallbackMemory) {
2338
+ this.fallbackMemory.upsertFile(entry);
2339
+ return;
2340
+ }
2341
+ if (!this.initialized || !this.db) return;
2342
+ const stmt = this.db.prepare(`
2343
+ INSERT INTO files (id, name, mimeType, size, parentId, path, md5Checksum, trashed, modifiedTime, updatedAt)
2344
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2345
+ ON CONFLICT(id) DO UPDATE SET
2346
+ name = excluded.name,
2347
+ mimeType = excluded.mimeType,
2348
+ size = excluded.size,
2349
+ parentId = excluded.parentId,
2350
+ path = COALESCE(excluded.path, files.path),
2351
+ md5Checksum = excluded.md5Checksum,
2352
+ trashed = excluded.trashed,
2353
+ modifiedTime = excluded.modifiedTime,
2354
+ updatedAt = excluded.updatedAt
2355
+ `);
2356
+ stmt.run(
2357
+ entry.id,
2358
+ entry.name,
2359
+ entry.mimeType,
2360
+ entry.size ?? null,
2361
+ entry.parentId ?? null,
2362
+ entry.path ?? null,
2363
+ entry.md5Checksum ? entry.md5Checksum.toLowerCase() : null,
2364
+ entry.trashed ? 1 : 0,
2365
+ entry.modifiedTime ?? null,
2366
+ entry.updatedAt ?? Date.now()
2367
+ );
2368
+ }
2369
+ upsertFiles(entries) {
2370
+ if (this.fallbackMemory) {
2371
+ this.fallbackMemory.upsertFiles(entries);
2372
+ return;
2373
+ }
2374
+ if (!this.initialized || !this.db || entries.length === 0) return;
2375
+ this.db.exec("BEGIN TRANSACTION;");
2376
+ try {
2377
+ for (const entry of entries) {
2378
+ this.upsertFile(entry);
2379
+ }
2380
+ this.db.exec("COMMIT;");
2381
+ } catch (e) {
2382
+ this.db.exec("ROLLBACK;");
2383
+ throw e;
2384
+ }
2385
+ }
2386
+ deleteFile(id) {
2387
+ if (this.fallbackMemory) {
2388
+ this.fallbackMemory.deleteFile(id);
2389
+ return;
2390
+ }
2391
+ if (!this.initialized || !this.db) return;
2392
+ const stmt = this.db.prepare("DELETE FROM files WHERE id = ?");
2393
+ stmt.run(id);
2394
+ }
2395
+ clear() {
2396
+ if (this.fallbackMemory) {
2397
+ this.fallbackMemory.clear();
2398
+ return;
2399
+ }
2400
+ if (!this.initialized || !this.db) return;
2401
+ this.db.exec("DELETE FROM files; DELETE FROM meta;");
2402
+ }
2403
+ getMeta(key) {
2404
+ if (this.fallbackMemory) return this.fallbackMemory.getMeta(key);
2405
+ if (!this.initialized || !this.db) return null;
2406
+ const stmt = this.db.prepare("SELECT value FROM meta WHERE key = ?");
2407
+ const row = stmt.get(key);
2408
+ return row ? row.value : null;
2409
+ }
2410
+ setMeta(key, value) {
2411
+ if (this.fallbackMemory) {
2412
+ this.fallbackMemory.setMeta(key, value);
2413
+ return;
2414
+ }
2415
+ if (!this.initialized || !this.db) return;
2416
+ const stmt = this.db.prepare(`
2417
+ INSERT INTO meta (key, value) VALUES (?, ?)
2418
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value
2419
+ `);
2420
+ stmt.run(key, value);
2421
+ }
2422
+ getStats() {
2423
+ if (this.fallbackMemory) return this.fallbackMemory.getStats();
2424
+ if (!this.initialized || !this.db) {
2425
+ return {
2426
+ fileCount: 0,
2427
+ folderCount: 0,
2428
+ totalSizeBytes: 0,
2429
+ lastSyncTime: null,
2430
+ databasePath: this.dbPath
2431
+ };
2432
+ }
2433
+ const fileCountRow = this.db.prepare(
2434
+ "SELECT COUNT(*) as count FROM files WHERE mimeType != 'application/vnd.google-apps.folder' AND trashed = 0"
2435
+ ).get();
2436
+ const folderCountRow = this.db.prepare(
2437
+ "SELECT COUNT(*) as count FROM files WHERE mimeType = 'application/vnd.google-apps.folder' AND trashed = 0"
2438
+ ).get();
2439
+ const totalSizeRow = this.db.prepare(
2440
+ "SELECT SUM(size) as total FROM files WHERE trashed = 0"
2441
+ ).get();
2442
+ const lastSync = this.getMeta("last_sync_timestamp");
2443
+ return {
2444
+ fileCount: fileCountRow?.count || 0,
2445
+ folderCount: folderCountRow?.count || 0,
2446
+ totalSizeBytes: totalSizeRow?.total || 0,
2447
+ lastSyncTime: lastSync,
2448
+ databasePath: this.dbPath
2449
+ };
2450
+ }
2451
+ close() {
2452
+ if (this.fallbackMemory) {
2453
+ this.fallbackMemory.close();
2454
+ this.fallbackMemory = void 0;
2455
+ }
2456
+ if (this.db) {
2457
+ try {
2458
+ this.db.close();
2459
+ } catch {
2460
+ }
2461
+ this.initialized = false;
2462
+ this.db = null;
2463
+ }
2464
+ }
2465
+ mapRow(row) {
2466
+ return {
2467
+ id: row.id,
2468
+ name: row.name,
2469
+ mimeType: row.mimeType,
2470
+ size: row.size != null ? Number(row.size) : void 0,
2471
+ parentId: row.parentId || void 0,
2472
+ path: row.path || void 0,
2473
+ md5Checksum: row.md5Checksum || void 0,
2474
+ trashed: row.trashed === 1,
2475
+ modifiedTime: row.modifiedTime || void 0,
2476
+ updatedAt: row.updatedAt != null ? Number(row.updatedAt) : void 0
2477
+ };
2478
+ }
2479
+ };
2480
+ var MemoryMetadataCache = class {
2481
+ files = /* @__PURE__ */ new Map();
2482
+ meta = /* @__PURE__ */ new Map();
2483
+ init() {
2484
+ }
2485
+ getById(id) {
2486
+ return this.files.get(id) || null;
2487
+ }
2488
+ getByPath(normalizedPath) {
2489
+ for (const f of this.files.values()) {
2490
+ if (f.path === normalizedPath && !f.trashed) return f;
2491
+ }
2492
+ return null;
2493
+ }
2494
+ getChildren(parentId) {
2495
+ const list = [];
2496
+ for (const f of this.files.values()) {
2497
+ if (f.parentId === parentId && !f.trashed) list.push(f);
2498
+ }
2499
+ return list;
2500
+ }
2501
+ findByMd5(md5) {
2502
+ const target = md5.toLowerCase();
2503
+ for (const f of this.files.values()) {
2504
+ if (f.md5Checksum?.toLowerCase() === target && !f.trashed) return f;
2505
+ }
2506
+ return null;
2507
+ }
2508
+ searchByName(query) {
2509
+ const q = query.toLowerCase();
2510
+ const list = [];
2511
+ for (const f of this.files.values()) {
2512
+ if (f.name.toLowerCase().includes(q) && !f.trashed) list.push(f);
2513
+ }
2514
+ return list;
2515
+ }
2516
+ upsertFile(entry) {
2517
+ this.files.set(entry.id, { ...entry, updatedAt: Date.now() });
2518
+ }
2519
+ upsertFiles(entries) {
2520
+ for (const e of entries) this.upsertFile(e);
2521
+ }
2522
+ deleteFile(id) {
2523
+ this.files.delete(id);
2524
+ }
2525
+ clear() {
2526
+ this.files.clear();
2527
+ this.meta.clear();
2528
+ }
2529
+ getMeta(key) {
2530
+ return this.meta.get(key) || null;
2531
+ }
2532
+ setMeta(key, value) {
2533
+ this.meta.set(key, value);
2534
+ }
2535
+ getStats() {
2536
+ let fileCount = 0;
2537
+ let folderCount = 0;
2538
+ let totalSizeBytes = 0;
2539
+ for (const f of this.files.values()) {
2540
+ if (f.trashed) continue;
2541
+ if (f.mimeType === "application/vnd.google-apps.folder") folderCount++;
2542
+ else {
2543
+ fileCount++;
2544
+ totalSizeBytes += f.size || 0;
2545
+ }
2546
+ }
2547
+ return {
2548
+ fileCount,
2549
+ folderCount,
2550
+ totalSizeBytes,
2551
+ lastSyncTime: this.meta.get("last_sync_timestamp") || null,
2552
+ databasePath: ":memory:"
2553
+ };
2554
+ }
2555
+ close() {
2556
+ this.clear();
2557
+ }
2558
+ };
1778
2559
 
1779
2560
  // src/core/client.ts
1780
- var DriveKit = class {
2561
+ var DriveKit = class _DriveKit {
1781
2562
  options;
1782
2563
  authenticator;
1783
2564
  driveClient = null;
1784
2565
  pathResolverInstance = null;
1785
2566
  uploaderInstance = null;
1786
2567
  downloaderInstance = null;
2568
+ metadataCacheInstance = null;
1787
2569
  rootFolderId;
1788
2570
  pluginManager = new PluginManager();
1789
2571
  constructor(options = {}) {
@@ -1817,9 +2599,14 @@ var DriveKit = class {
1817
2599
  if (!this.driveClient) {
1818
2600
  const auth = await this.authenticator.getAuthClient();
1819
2601
  this.driveClient = (0, import_drive3.drive)({ version: "v3", auth });
2602
+ if (this.options.enablePersistentCache !== false) {
2603
+ this.metadataCacheInstance = new SqliteMetadataCache(this.options.cacheDatabasePath);
2604
+ this.metadataCacheInstance.init();
2605
+ }
1820
2606
  this.pathResolverInstance = new PathResolver(this.driveClient, this.rootFolderId, {
1821
2607
  enableCache: this.options.enablePathCache ?? true,
1822
- cacheTTL: this.options.pathCacheTTL
2608
+ cacheTTL: this.options.pathCacheTTL,
2609
+ metadataCache: this.metadataCacheInstance || void 0
1823
2610
  });
1824
2611
  this.uploaderInstance = new ResumableUploader(
1825
2612
  this.driveClient,
@@ -1924,16 +2711,71 @@ var DriveKit = class {
1924
2711
  if (parentId && parentId.startsWith("/")) {
1925
2712
  parentId = await this.mkdirp(parentId);
1926
2713
  }
1927
- if (opts.overwrite && opts.name && parentId) {
1928
- const existing = await this.query().inFolder(parentId).nameEquals(opts.name).notTrashed().first();
2714
+ const targetName = opts.name || opts.filename;
2715
+ if (opts.overwrite && targetName && parentId) {
2716
+ const existing = await this.query().inFolder(parentId).nameEquals(targetName).notTrashed().first();
1929
2717
  if (existing?.id) {
1930
2718
  await this.delete(existing.id, true);
1931
2719
  }
1932
2720
  }
2721
+ if (opts.deduplicate && typeof opts.source === "string" && import_node_fs6.default.existsSync(opts.source)) {
2722
+ const localMd5 = await calculateFileMd5(opts.source);
2723
+ let existingId;
2724
+ if (this.metadataCacheInstance) {
2725
+ const cached = this.metadataCacheInstance.findByMd5(localMd5);
2726
+ if (cached) existingId = cached.id;
2727
+ }
2728
+ if (!existingId) {
2729
+ const found = await this.query().md5(localMd5).notTrashed().first();
2730
+ if (found?.id) {
2731
+ existingId = found.id;
2732
+ }
2733
+ }
2734
+ if (existingId) {
2735
+ const fileName = targetName || import_node_path6.default.basename(opts.source);
2736
+ const raw = await this.getRawClient();
2737
+ const copyRes = await withRetry(async () => {
2738
+ return await raw.files.copy({
2739
+ fileId: existingId,
2740
+ requestBody: {
2741
+ name: fileName,
2742
+ parents: parentId ? [parentId] : void 0,
2743
+ description: opts.description
2744
+ },
2745
+ fields: "id, name, mimeType, size, modifiedTime, md5Checksum",
2746
+ supportsAllDrives: true
2747
+ });
2748
+ });
2749
+ const file = copyRes.data;
2750
+ if (this.metadataCacheInstance && file.id) {
2751
+ this.metadataCacheInstance.upsertFile({
2752
+ id: file.id,
2753
+ name: file.name || fileName,
2754
+ mimeType: file.mimeType || "",
2755
+ size: file.size ? parseInt(file.size, 10) : void 0,
2756
+ parentId,
2757
+ md5Checksum: localMd5,
2758
+ trashed: false
2759
+ });
2760
+ }
2761
+ return await this.pluginManager.runAfterUpload(file);
2762
+ }
2763
+ }
1933
2764
  const uploaded = await uploader.upload({
1934
2765
  ...opts,
2766
+ name: targetName,
1935
2767
  parent: parentId
1936
2768
  });
2769
+ if (this.metadataCacheInstance && uploaded.id) {
2770
+ this.metadataCacheInstance.upsertFile({
2771
+ id: uploaded.id,
2772
+ name: uploaded.name || targetName || "untitled",
2773
+ mimeType: uploaded.mimeType || "",
2774
+ size: uploaded.size ? parseInt(uploaded.size, 10) : void 0,
2775
+ parentId,
2776
+ trashed: false
2777
+ });
2778
+ }
1937
2779
  return await this.pluginManager.runAfterUpload(uploaded);
1938
2780
  }
1939
2781
  /**
@@ -2174,16 +3016,16 @@ var DriveKit = class {
2174
3016
  durationMs: 0
2175
3017
  };
2176
3018
  const collectFiles = async (dir, base) => {
2177
- const entries = await import_node_fs5.default.promises.readdir(dir, { withFileTypes: true });
3019
+ const entries = await import_node_fs6.default.promises.readdir(dir, { withFileTypes: true });
2178
3020
  const files = [];
2179
3021
  for (const entry of entries) {
2180
- const fullPath = import_node_path4.default.join(dir, entry.name);
2181
- const relPath = import_node_path4.default.join(base, entry.name);
3022
+ const fullPath = import_node_path6.default.join(dir, entry.name);
3023
+ const relPath = import_node_path6.default.join(base, entry.name);
2182
3024
  if (entry.isDirectory()) {
2183
3025
  const sub = await collectFiles(fullPath, relPath);
2184
3026
  files.push(...sub);
2185
3027
  } else if (entry.isFile()) {
2186
- const stat = await import_node_fs5.default.promises.stat(fullPath);
3028
+ const stat = await import_node_fs6.default.promises.stat(fullPath);
2187
3029
  files.push({ fullPath, relPath, size: stat.size });
2188
3030
  }
2189
3031
  }
@@ -2196,11 +3038,11 @@ var DriveKit = class {
2196
3038
  if (remoteDirCache.has(relDir)) {
2197
3039
  return remoteDirCache.get(relDir);
2198
3040
  }
2199
- const parts = relDir.split(import_node_path4.default.sep).filter(Boolean);
3041
+ const parts = relDir.split(import_node_path6.default.sep).filter(Boolean);
2200
3042
  let currentParent = targetFolderId;
2201
3043
  let currentRel = "";
2202
3044
  for (const part of parts) {
2203
- currentRel = currentRel ? import_node_path4.default.join(currentRel, part) : part;
3045
+ currentRel = currentRel ? import_node_path6.default.join(currentRel, part) : part;
2204
3046
  if (remoteDirCache.has(currentRel)) {
2205
3047
  currentParent = remoteDirCache.get(currentRel);
2206
3048
  continue;
@@ -2229,8 +3071,8 @@ var DriveKit = class {
2229
3071
  };
2230
3072
  await pool.map(allFiles, async (fileItem) => {
2231
3073
  try {
2232
- const relDir = import_node_path4.default.dirname(fileItem.relPath);
2233
- const fileName = import_node_path4.default.basename(fileItem.relPath);
3074
+ const relDir = import_node_path6.default.dirname(fileItem.relPath);
3075
+ const fileName = import_node_path6.default.basename(fileItem.relPath);
2234
3076
  const parentFolderId = await ensureRemoteSubdir(relDir === "." ? "" : relDir);
2235
3077
  if (options.onFileStart) {
2236
3078
  options.onFileStart(fileItem.fullPath, fileItem.relPath);
@@ -2348,6 +3190,217 @@ var DriveKit = class {
2348
3190
  const engine = new SmartSyncEngine(this.driveClient);
2349
3191
  return await engine.pullFolder(folderId, localDestinationDir, options);
2350
3192
  }
3193
+ // ==========================================
3194
+ // STREAMS & RANGE REQUESTS
3195
+ // ==========================================
3196
+ /**
3197
+ * Creates a readable stream for a file, supporting partial range requests
3198
+ */
3199
+ async createReadStream(pathOrId, options) {
3200
+ const fileId = await this.resolveId(pathOrId);
3201
+ const downloader = await this.getDownloader();
3202
+ return await downloader.createReadStream(fileId, options);
3203
+ }
3204
+ /**
3205
+ * Creates a writable stream directly into Google Drive
3206
+ */
3207
+ async createWriteStream(remotePath, options = {}) {
3208
+ await this.init();
3209
+ const { PassThrough } = await import("stream");
3210
+ const passThrough = new PassThrough();
3211
+ const remoteDir = import_node_path6.default.dirname(remotePath);
3212
+ const fileName = options.name || options.filename || import_node_path6.default.basename(remotePath);
3213
+ const targetParentId = remoteDir === "." || remoteDir === "/" ? this.rootFolderId : await this.mkdirp(remoteDir);
3214
+ const mimeType = options.mimeType || "application/octet-stream";
3215
+ const raw = this.driveClient;
3216
+ raw.files.create({
3217
+ requestBody: {
3218
+ name: fileName,
3219
+ parents: [targetParentId],
3220
+ description: options.description
3221
+ },
3222
+ media: {
3223
+ mimeType,
3224
+ body: passThrough
3225
+ },
3226
+ fields: "id, name, mimeType, size, md5Checksum",
3227
+ supportsAllDrives: true
3228
+ }).then((res) => {
3229
+ if (res.data.id && this.metadataCacheInstance) {
3230
+ this.metadataCacheInstance.upsertFile({
3231
+ id: res.data.id,
3232
+ name: fileName,
3233
+ mimeType,
3234
+ parentId: targetParentId,
3235
+ path: remotePath,
3236
+ trashed: false
3237
+ });
3238
+ }
3239
+ }).catch((err) => {
3240
+ passThrough.destroy(err);
3241
+ });
3242
+ return passThrough;
3243
+ }
3244
+ // ==========================================
3245
+ // METADATA CACHE OPERATIONS
3246
+ // ==========================================
3247
+ /**
3248
+ * Returns the active persistent metadata cache instance (SQLite/Memory)
3249
+ */
3250
+ async getMetadataCache() {
3251
+ await this.init();
3252
+ return this.metadataCacheInstance;
3253
+ }
3254
+ /**
3255
+ * Returns cache statistics (total files, folders, size, last sync)
3256
+ */
3257
+ async getCacheStats() {
3258
+ await this.init();
3259
+ return this.metadataCacheInstance ? this.metadataCacheInstance.getStats() : null;
3260
+ }
3261
+ /**
3262
+ * Clears the path and metadata cache
3263
+ */
3264
+ async clearCache() {
3265
+ await this.init();
3266
+ if (this.pathResolverInstance) {
3267
+ this.pathResolverInstance.clearCache();
3268
+ }
3269
+ }
3270
+ /**
3271
+ * Crawls and indexes Google Drive metadata into the local SQLite database for instant 0ms lookups
3272
+ */
3273
+ async syncCache(options) {
3274
+ await this.init();
3275
+ if (!this.metadataCacheInstance) {
3276
+ throw new Error("Persistent cache is disabled on this DriveKit instance");
3277
+ }
3278
+ const client = this.driveClient;
3279
+ let pageToken = void 0;
3280
+ let totalScanned = 0;
3281
+ do {
3282
+ const res = await withRetry(async () => {
3283
+ return await client.files.list({
3284
+ pageSize: 1e3,
3285
+ pageToken,
3286
+ fields: "nextPageToken, files(id, name, mimeType, size, parents, md5Checksum, trashed, modifiedTime)",
3287
+ spaces: "drive",
3288
+ supportsAllDrives: true,
3289
+ includeItemsFromAllDrives: true,
3290
+ q: "trashed = false"
3291
+ });
3292
+ });
3293
+ const files = res.data.files || [];
3294
+ const entries = files.map((f) => ({
3295
+ id: f.id,
3296
+ name: f.name || "untitled",
3297
+ mimeType: f.mimeType || "",
3298
+ size: f.size ? parseInt(f.size, 10) : void 0,
3299
+ parentId: f.parents?.[0],
3300
+ md5Checksum: f.md5Checksum || void 0,
3301
+ trashed: !!f.trashed,
3302
+ modifiedTime: f.modifiedTime || void 0
3303
+ }));
3304
+ this.metadataCacheInstance.upsertFiles(entries);
3305
+ totalScanned += entries.length;
3306
+ options?.onProgress?.(totalScanned);
3307
+ pageToken = res.data.nextPageToken || void 0;
3308
+ } while (pageToken);
3309
+ this.metadataCacheInstance.setMeta("last_sync_timestamp", (/* @__PURE__ */ new Date()).toISOString());
3310
+ return this.metadataCacheInstance.getStats();
3311
+ }
3312
+ // ==========================================
3313
+ // SHARED DRIVES & ENTERPRISE PERMISSIONS
3314
+ // ==========================================
3315
+ /**
3316
+ * Lists all Google Workspace Shared Drives accessible by current user or service account
3317
+ */
3318
+ async listSharedDrives(options = {}) {
3319
+ await this.init();
3320
+ const raw = await this.getRawClient();
3321
+ const res = await withRetry(async () => {
3322
+ return await raw.drives.list({
3323
+ pageSize: options.pageSize || 100,
3324
+ fields: "drives(id, name)"
3325
+ });
3326
+ });
3327
+ return (res.data.drives || []).map((d) => ({ id: d.id, name: d.name }));
3328
+ }
3329
+ /**
3330
+ * Creates a scoped DriveKit client locked to a specific Shared Drive
3331
+ */
3332
+ sharedDrive(driveId) {
3333
+ return new _DriveKit({
3334
+ ...this.options,
3335
+ rootFolderId: driveId
3336
+ });
3337
+ }
3338
+ /**
3339
+ * Grants access to a specific email with custom role and notification
3340
+ */
3341
+ async grantAccess(pathOrId, options) {
3342
+ const fileId = await this.resolveId(pathOrId);
3343
+ const raw = await this.getRawClient();
3344
+ const res = await withRetry(async () => {
3345
+ return await raw.permissions.create({
3346
+ fileId,
3347
+ requestBody: {
3348
+ type: "user",
3349
+ role: options.role || "reader",
3350
+ emailAddress: options.email
3351
+ },
3352
+ sendNotificationEmail: options.notify ?? true,
3353
+ emailMessage: options.message,
3354
+ fields: "id, type, role, emailAddress, displayName",
3355
+ supportsAllDrives: true
3356
+ });
3357
+ });
3358
+ return res.data;
3359
+ }
3360
+ /**
3361
+ * Revokes access for a specific permission ID or email address
3362
+ */
3363
+ async revokeAccess(pathOrId, permissionIdOrEmail) {
3364
+ const fileId = await this.resolveId(pathOrId);
3365
+ const raw = await this.getRawClient();
3366
+ let targetId = permissionIdOrEmail;
3367
+ if (permissionIdOrEmail.includes("@")) {
3368
+ const listRes = await this.listPermissions(fileId);
3369
+ const found = listRes.find((p) => p.emailAddress?.toLowerCase() === permissionIdOrEmail.toLowerCase());
3370
+ if (found && found.id) {
3371
+ targetId = found.id;
3372
+ }
3373
+ }
3374
+ await withRetry(async () => {
3375
+ return await raw.permissions.delete({
3376
+ fileId,
3377
+ permissionId: targetId,
3378
+ supportsAllDrives: true
3379
+ });
3380
+ });
3381
+ }
3382
+ /**
3383
+ * Lists all active permissions on a file or folder
3384
+ */
3385
+ async listPermissions(pathOrId) {
3386
+ const fileId = await this.resolveId(pathOrId);
3387
+ const raw = await this.getRawClient();
3388
+ const res = await withRetry(async () => {
3389
+ return await raw.permissions.list({
3390
+ fileId,
3391
+ fields: "permissions(id, type, role, emailAddress, displayName)",
3392
+ supportsAllDrives: true
3393
+ });
3394
+ });
3395
+ return res.data.permissions || [];
3396
+ }
3397
+ /**
3398
+ * Starts an embedded WebDAV server to mount DriveKit directly in macOS Finder or Windows Explorer
3399
+ */
3400
+ async serveWebDAV(options) {
3401
+ const { startWebDAVServer: startWebDAVServer2 } = await Promise.resolve().then(() => (init_webdav(), webdav_exports));
3402
+ return await startWebDAVServer2(this, options);
3403
+ }
2351
3404
  /**
2352
3405
  * Calculates local file MD5 hash for integrity and deduplication checks
2353
3406
  */
@@ -2362,11 +3415,18 @@ var DriveKit = class {
2362
3415
  }
2363
3416
  };
2364
3417
 
3418
+ // src/types.ts
3419
+ init_cjs_shims();
3420
+
3421
+ // src/index.ts
3422
+ init_webdav();
3423
+
2365
3424
  // src/cli/terminal-ui.ts
3425
+ init_cjs_shims();
2366
3426
  var import_node_readline = __toESM(require("readline"), 1);
2367
3427
  var import_chalk = __toESM(require("chalk"), 1);
2368
- function terminalLink(text, url) {
2369
- return `\x1B]8;;${url}\x07${text}\x1B]8;;\x07`;
3428
+ function terminalLink(text, url2) {
3429
+ return `\x1B]8;;${url2}\x07${text}\x1B]8;;\x07`;
2370
3430
  }
2371
3431
  function renderFileRow(item, index) {
2372
3432
  const isDir = item.mimeType === "application/vnd.google-apps.folder";
@@ -2542,13 +3602,17 @@ var index_default = DriveKit;
2542
3602
  GOOGLE_WORKSPACE_MIME_TYPES,
2543
3603
  MIN_CHUNK_SIZE,
2544
3604
  MULTIPART_THRESHOLD,
3605
+ MemoryMetadataCache,
2545
3606
  PathResolver,
2546
3607
  PluginManager,
2547
3608
  ResumableUploader,
2548
3609
  SmartSyncEngine,
3610
+ SqliteMetadataCache,
2549
3611
  StorageCleaner,
2550
3612
  calculateFileMd5,
3613
+ createAutoNamePlugin,
2551
3614
  createDrive,
3615
+ createWebhookPlugin,
2552
3616
  formatBytes,
2553
3617
  formatDuration,
2554
3618
  formatSpeed,
@@ -2560,6 +3624,7 @@ var index_default = DriveKit;
2560
3624
  lookupMimeType,
2561
3625
  renderFileRow,
2562
3626
  runInteractiveExplorer,
3627
+ startWebDAVServer,
2563
3628
  terminalLink,
2564
3629
  withRetry
2565
3630
  });