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.js CHANGED
@@ -1,13 +1,272 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
4
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
5
+ }) : x)(function(x) {
6
+ if (typeof require !== "undefined") return require.apply(this, arguments);
7
+ throw Error('Dynamic require of "' + x + '" is not supported');
8
+ });
9
+ var __esm = (fn, res) => function __init() {
10
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
+ };
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
16
+
17
+ // node_modules/tsup/assets/esm_shims.js
18
+ import path from "path";
19
+ import { fileURLToPath } from "url";
20
+ var init_esm_shims = __esm({
21
+ "node_modules/tsup/assets/esm_shims.js"() {
22
+ "use strict";
23
+ }
24
+ });
25
+
26
+ // src/server/webdav.ts
27
+ var webdav_exports = {};
28
+ __export(webdav_exports, {
29
+ startWebDAVServer: () => startWebDAVServer
30
+ });
31
+ import http2 from "http";
32
+ import url from "url";
33
+ import path6 from "path";
34
+ async function startWebDAVServer(drive2, options = {}) {
35
+ const port = options.port || 8080;
36
+ const host = options.host || "127.0.0.1";
37
+ await drive2.init();
38
+ const server = http2.createServer(async (req, res) => {
39
+ try {
40
+ const parsedUrl = url.parse(req.url || "/", true);
41
+ const decodedPath = decodeURIComponent(parsedUrl.pathname || "/");
42
+ const virtualPath = decodedPath === "" ? "/" : decodedPath;
43
+ switch (req.method) {
44
+ case "OPTIONS": {
45
+ res.writeHead(200, {
46
+ DAV: "1, 2",
47
+ Allow: "OPTIONS, GET, HEAD, POST, PUT, DELETE, MKCOL, MOVE, COPY, PROPFIND",
48
+ "MS-Author-Via": "DAV"
49
+ });
50
+ res.end();
51
+ return;
52
+ }
53
+ case "PROPFIND": {
54
+ const depth = req.headers["depth"] || "1";
55
+ const xml = await handlePropfind(drive2, virtualPath, depth);
56
+ res.writeHead(207, {
57
+ "Content-Type": "application/xml; charset=utf-8"
58
+ });
59
+ res.end(xml);
60
+ return;
61
+ }
62
+ case "GET":
63
+ case "HEAD": {
64
+ if (virtualPath === "/" || virtualPath === "") {
65
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
66
+ res.end("<h1>DriveKit WebDAV Server Running</h1><p>Connect via Finder or WebDAV client.</p>");
67
+ return;
68
+ }
69
+ try {
70
+ const file = await drive2.getFile(virtualPath);
71
+ if (file.mimeType === "application/vnd.google-apps.folder") {
72
+ res.writeHead(405, { "Content-Type": "text/plain" });
73
+ res.end("Cannot GET a directory");
74
+ return;
75
+ }
76
+ const stream = await drive2.createReadStream(virtualPath);
77
+ res.writeHead(200, {
78
+ "Content-Type": file.mimeType || "application/octet-stream",
79
+ "Content-Length": file.size || void 0
80
+ });
81
+ if (req.method === "HEAD") {
82
+ res.end();
83
+ } else {
84
+ stream.pipe(res);
85
+ }
86
+ } catch (e) {
87
+ res.writeHead(404, { "Content-Type": "text/plain" });
88
+ res.end("File Not Found");
89
+ }
90
+ return;
91
+ }
92
+ case "PUT": {
93
+ const remoteDir = path6.dirname(virtualPath);
94
+ const fileName = path6.basename(virtualPath);
95
+ await drive2.mkdirp(remoteDir);
96
+ const chunks = [];
97
+ req.on("data", (chunk) => chunks.push(chunk));
98
+ req.on("end", async () => {
99
+ try {
100
+ const buffer = Buffer.concat(chunks);
101
+ await drive2.upload({
102
+ source: buffer,
103
+ filename: fileName,
104
+ parent: remoteDir,
105
+ overwrite: true
106
+ });
107
+ res.writeHead(201, { "Content-Type": "text/plain" });
108
+ res.end("Created");
109
+ } catch (err) {
110
+ res.writeHead(500, { "Content-Type": "text/plain" });
111
+ res.end(err.message || "Upload failed");
112
+ }
113
+ });
114
+ return;
115
+ }
116
+ case "MKCOL": {
117
+ try {
118
+ await drive2.mkdirp(virtualPath);
119
+ res.writeHead(201, { "Content-Type": "text/plain" });
120
+ res.end("Collection Created");
121
+ } catch (err) {
122
+ res.writeHead(500, { "Content-Type": "text/plain" });
123
+ res.end(err.message);
124
+ }
125
+ return;
126
+ }
127
+ case "DELETE": {
128
+ try {
129
+ await drive2.delete(virtualPath, true);
130
+ res.writeHead(204);
131
+ res.end();
132
+ } catch (err) {
133
+ res.writeHead(404, { "Content-Type": "text/plain" });
134
+ res.end("Not Found");
135
+ }
136
+ return;
137
+ }
138
+ case "MOVE": {
139
+ const destination = req.headers["destination"];
140
+ if (!destination || typeof destination !== "string") {
141
+ res.writeHead(400, { "Content-Type": "text/plain" });
142
+ res.end("Destination header missing");
143
+ return;
144
+ }
145
+ const destUrl = url.parse(destination);
146
+ const destPath = decodeURIComponent(destUrl.pathname || "");
147
+ const newName = path6.basename(destPath);
148
+ const newParent = path6.dirname(destPath);
149
+ try {
150
+ await drive2.move(virtualPath, newParent);
151
+ if (newName !== path6.basename(virtualPath)) {
152
+ await drive2.rename(destPath, newName);
153
+ }
154
+ res.writeHead(201);
155
+ res.end("Moved");
156
+ } catch (err) {
157
+ res.writeHead(500, { "Content-Type": "text/plain" });
158
+ res.end(err.message);
159
+ }
160
+ return;
161
+ }
162
+ default: {
163
+ res.writeHead(501, { "Content-Type": "text/plain" });
164
+ res.end("Method Not Implemented");
165
+ }
166
+ }
167
+ } catch (globalErr) {
168
+ res.writeHead(500, { "Content-Type": "text/plain" });
169
+ res.end(`Internal Server Error: ${globalErr.message}`);
170
+ }
171
+ });
172
+ return new Promise((resolve) => {
173
+ server.listen(port, host, () => {
174
+ const serverUrl = `http://${host}:${port}`;
175
+ resolve({
176
+ server,
177
+ url: serverUrl,
178
+ close: () => new Promise((resClose) => server.close(() => resClose()))
179
+ });
180
+ });
181
+ });
182
+ }
183
+ async function handlePropfind(drive2, virtualPath, depth) {
184
+ const responses = [];
185
+ let isFolder = false;
186
+ let selfItem = null;
187
+ if (virtualPath === "/" || virtualPath === "") {
188
+ isFolder = true;
189
+ responses.push(renderWebDAVResponse("/", true, 0, (/* @__PURE__ */ new Date()).toISOString()));
190
+ } else {
191
+ try {
192
+ selfItem = await drive2.getFile(virtualPath);
193
+ isFolder = selfItem.mimeType === "application/vnd.google-apps.folder";
194
+ responses.push(
195
+ renderWebDAVResponse(
196
+ virtualPath,
197
+ isFolder,
198
+ selfItem.size ? parseInt(selfItem.size, 10) : 0,
199
+ selfItem.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
200
+ )
201
+ );
202
+ } catch {
203
+ return `<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:"></D:multistatus>`;
204
+ }
205
+ }
206
+ if (isFolder && depth !== "0") {
207
+ try {
208
+ const children = await drive2.ls(virtualPath);
209
+ for (const child of children) {
210
+ const childIsFolder = child.mimeType === "application/vnd.google-apps.folder";
211
+ const childPath = virtualPath === "/" ? `/${child.name}` : `${virtualPath}/${child.name}`;
212
+ responses.push(
213
+ renderWebDAVResponse(
214
+ childPath,
215
+ childIsFolder,
216
+ child.size ? parseInt(child.size, 10) : 0,
217
+ child.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
218
+ )
219
+ );
220
+ }
221
+ } catch {
222
+ }
223
+ }
224
+ return `<?xml version="1.0" encoding="utf-8"?>
225
+ <D:multistatus xmlns:D="DAV:">
226
+ ${responses.join("\n")}
227
+ </D:multistatus>`;
228
+ }
229
+ function renderWebDAVResponse(href, isDir, size, modifiedTime) {
230
+ const encodedHref = encodeURI(href);
231
+ const resourceType = isDir ? "<D:collection/>" : "";
232
+ const dateFormatted = new Date(modifiedTime).toUTCString();
233
+ return ` <D:response>
234
+ <D:href>${encodedHref}</D:href>
235
+ <D:propstat>
236
+ <D:prop>
237
+ <D:displayname>${path6.basename(href) || "root"}</D:displayname>
238
+ <D:resourcetype>${resourceType}</D:resourcetype>
239
+ <D:getcontentlength>${isDir ? "0" : size}</D:getcontentlength>
240
+ <D:getlastmodified>${dateFormatted}</D:getlastmodified>
241
+ <D:status>HTTP/1.1 200 OK</D:status>
242
+ </D:prop>
243
+ <D:status>HTTP/1.1 200 OK</D:status>
244
+ </D:propstat>
245
+ </D:response>`;
246
+ }
247
+ var init_webdav = __esm({
248
+ "src/server/webdav.ts"() {
249
+ "use strict";
250
+ init_esm_shims();
251
+ }
252
+ });
253
+
254
+ // src/index.ts
255
+ init_esm_shims();
256
+
1
257
  // src/core/client.ts
2
- import fs5 from "fs";
3
- import path4 from "path";
258
+ init_esm_shims();
259
+ import fs6 from "fs";
260
+ import path7 from "path";
4
261
  import { drive } from "@googleapis/drive";
5
262
 
6
263
  // src/auth/authenticator.ts
264
+ init_esm_shims();
7
265
  import fs from "fs";
8
266
  import { auth as googleAuth } from "@googleapis/drive";
9
267
 
10
268
  // src/errors.ts
269
+ init_esm_shims();
11
270
  var DriveKitError = class extends Error {
12
271
  code;
13
272
  originalError;
@@ -148,7 +407,11 @@ var DriveAuthenticator = class {
148
407
  }
149
408
  };
150
409
 
410
+ // src/core/path-resolver.ts
411
+ init_esm_shims();
412
+
151
413
  // src/utils/mime.ts
414
+ init_esm_shims();
152
415
  import mime from "mime-types";
153
416
  var GOOGLE_WORKSPACE_MIME_TYPES = {
154
417
  DOCUMENT: "application/vnd.google-apps.document",
@@ -192,6 +455,7 @@ function isGoogleWorkspaceDoc(mimeType) {
192
455
  }
193
456
 
194
457
  // src/utils/retry.ts
458
+ init_esm_shims();
195
459
  var DEFAULT_RETRYABLE_STATUSES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
196
460
  function isRetryableError(error) {
197
461
  if (!error) return false;
@@ -248,11 +512,13 @@ var PathResolver = class {
248
512
  cache = /* @__PURE__ */ new Map();
249
513
  cacheTTL;
250
514
  enableCache;
515
+ metadataCache;
251
516
  constructor(drive2, rootFolderId = "root", options) {
252
517
  this.drive = drive2;
253
518
  this.rootFolderId = rootFolderId;
254
519
  this.enableCache = options?.enableCache ?? true;
255
520
  this.cacheTTL = options?.cacheTTL ?? 5 * 60 * 1e3;
521
+ this.metadataCache = options?.metadataCache;
256
522
  }
257
523
  /**
258
524
  * Normalizes a virtual path (e.g. "///Backups//2026/" -> "/Backups/2026")
@@ -267,21 +533,31 @@ var PathResolver = class {
267
533
  /**
268
534
  * Gets cache key for a path
269
535
  */
270
- getCacheKey(path5) {
271
- return `${this.rootFolderId}:${this.normalizePath(path5)}`;
536
+ getCacheKey(path8) {
537
+ return `${this.rootFolderId}:${this.normalizePath(path8)}`;
272
538
  }
273
539
  /**
274
540
  * Clears the path cache
275
541
  */
276
542
  clearCache() {
277
543
  this.cache.clear();
544
+ if (this.metadataCache) {
545
+ this.metadataCache.clear();
546
+ }
278
547
  }
279
548
  /**
280
549
  * Invalidate a single path from cache
281
550
  */
282
- invalidatePath(path5) {
283
- const key = this.getCacheKey(path5);
551
+ invalidatePath(path8) {
552
+ const norm = this.normalizePath(path8);
553
+ const key = this.getCacheKey(norm);
284
554
  this.cache.delete(key);
555
+ if (this.metadataCache) {
556
+ const item = this.metadataCache.getByPath(norm);
557
+ if (item) {
558
+ this.metadataCache.deleteFile(item.id);
559
+ }
560
+ }
285
561
  }
286
562
  /**
287
563
  * Resolves a path to a Google Drive item (file or folder).
@@ -297,6 +573,17 @@ var PathResolver = class {
297
573
  mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER
298
574
  };
299
575
  }
576
+ if (this.metadataCache) {
577
+ const persistentCached = this.metadataCache.getByPath(norm);
578
+ if (persistentCached) {
579
+ return {
580
+ id: persistentCached.id,
581
+ name: persistentCached.name,
582
+ isFolder: persistentCached.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
583
+ mimeType: persistentCached.mimeType
584
+ };
585
+ }
586
+ }
300
587
  if (this.enableCache) {
301
588
  const cached = this.cache.get(this.getCacheKey(norm));
302
589
  if (cached && cached.expiresAt > Date.now()) {
@@ -315,6 +602,21 @@ var PathResolver = class {
315
602
  const segment = segments[i];
316
603
  const isLast = i === segments.length - 1;
317
604
  currentPath += `/${segment}`;
605
+ if (this.metadataCache) {
606
+ const pCached = this.metadataCache.getByPath(currentPath);
607
+ if (pCached) {
608
+ currentParentId = pCached.id;
609
+ if (isLast) {
610
+ return {
611
+ id: pCached.id,
612
+ name: pCached.name,
613
+ isFolder: pCached.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
614
+ mimeType: pCached.mimeType
615
+ };
616
+ }
617
+ continue;
618
+ }
619
+ }
318
620
  if (this.enableCache) {
319
621
  const cached = this.cache.get(this.getCacheKey(currentPath));
320
622
  if (cached && cached.expiresAt > Date.now()) {
@@ -359,6 +661,16 @@ var PathResolver = class {
359
661
  }
360
662
  if (file && file.id) {
361
663
  currentParentId = file.id;
664
+ if (this.metadataCache) {
665
+ this.metadataCache.upsertFile({
666
+ id: file.id,
667
+ name: file.name || segment,
668
+ mimeType: file.mimeType || "",
669
+ parentId: currentParentId,
670
+ path: currentPath,
671
+ trashed: false
672
+ });
673
+ }
362
674
  if (this.enableCache) {
363
675
  this.cache.set(this.getCacheKey(currentPath), {
364
676
  id: file.id,
@@ -393,6 +705,16 @@ var PathResolver = class {
393
705
  throw new Error(`Failed to create folder "${segment}" under parent "${currentParentId}"`);
394
706
  }
395
707
  currentParentId = newFolder.id;
708
+ if (this.metadataCache) {
709
+ this.metadataCache.upsertFile({
710
+ id: newFolder.id,
711
+ name: segment,
712
+ mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
713
+ parentId: currentParentId,
714
+ path: currentPath,
715
+ trashed: false
716
+ });
717
+ }
396
718
  if (this.enableCache) {
397
719
  this.cache.set(this.getCacheKey(currentPath), {
398
720
  id: newFolder.id,
@@ -429,10 +751,12 @@ var PathResolver = class {
429
751
  };
430
752
 
431
753
  // src/core/resumable-uploader.ts
754
+ init_esm_shims();
432
755
  import fs2 from "fs";
433
- import path from "path";
756
+ import path2 from "path";
434
757
 
435
758
  // src/utils/format.ts
759
+ init_esm_shims();
436
760
  function formatBytes(bytes, decimals = 2) {
437
761
  if (bytes === 0) return "0 B";
438
762
  const k = 1024;
@@ -492,7 +816,7 @@ var ResumableUploader = class {
492
816
  }
493
817
  const stat = await fs2.promises.stat(filePath);
494
818
  const totalBytes = stat.size;
495
- const fileName = options.name || path.basename(filePath);
819
+ const fileName = options.name || path2.basename(filePath);
496
820
  const mimeType = options.mimeType || lookupMimeType(filePath);
497
821
  return await this.chunkedUpload({
498
822
  filePath,
@@ -760,8 +1084,9 @@ var ResumableUploader = class {
760
1084
  };
761
1085
 
762
1086
  // src/core/downloader.ts
1087
+ init_esm_shims();
763
1088
  import fs3 from "fs";
764
- import path2 from "path";
1089
+ import path3 from "path";
765
1090
  import { pipeline } from "stream/promises";
766
1091
  import { Transform } from "stream";
767
1092
  var Downloader = class {
@@ -836,9 +1161,9 @@ var Downloader = class {
836
1161
  if (options.destination) {
837
1162
  let destPath = options.destination;
838
1163
  if (fs3.existsSync(destPath) && fs3.statSync(destPath).isDirectory()) {
839
- destPath = path2.join(destPath, finalFileName);
1164
+ destPath = path3.join(destPath, finalFileName);
840
1165
  }
841
- await fs3.promises.mkdir(path2.dirname(destPath), { recursive: true });
1166
+ await fs3.promises.mkdir(path3.dirname(destPath), { recursive: true });
842
1167
  const writeStream = fs3.createWriteStream(destPath);
843
1168
  await pipeline(monitoredStream, writeStream);
844
1169
  return {
@@ -855,9 +1180,28 @@ var Downloader = class {
855
1180
  size: totalBytes
856
1181
  };
857
1182
  }
1183
+ /**
1184
+ * Returns a raw ReadableStream for the file, supporting HTTP Range requests for partial content / streaming.
1185
+ */
1186
+ async createReadStream(fileId, options) {
1187
+ const headers = {};
1188
+ if (options?.start !== void 0 || options?.end !== void 0) {
1189
+ const start = options.start ?? 0;
1190
+ const end = options.end !== void 0 ? options.end : "";
1191
+ headers["Range"] = `bytes=${start}-${end}`;
1192
+ }
1193
+ const res = await withRetry(async () => {
1194
+ return await this.drive.files.get(
1195
+ { fileId, alt: "media", supportsAllDrives: true },
1196
+ { responseType: "stream", headers }
1197
+ );
1198
+ });
1199
+ return res.data;
1200
+ }
858
1201
  };
859
1202
 
860
1203
  // src/core/query-builder.ts
1204
+ init_esm_shims();
861
1205
  var DriveQueryBuilder = class {
862
1206
  drive;
863
1207
  conditions = [];
@@ -974,6 +1318,19 @@ var DriveQueryBuilder = class {
974
1318
  this.conditions.push(`(${condition})`);
975
1319
  return this;
976
1320
  }
1321
+ /**
1322
+ * Custom raw query condition (alias for raw)
1323
+ */
1324
+ custom(condition) {
1325
+ return this.raw(condition);
1326
+ }
1327
+ /**
1328
+ * Filter: Exact MD5 checksum match
1329
+ */
1330
+ md5(checksum) {
1331
+ this.conditions.push(`md5Checksum = '${this.escape(checksum)}'`);
1332
+ return this;
1333
+ }
977
1334
  /**
978
1335
  * Sort ordering (e.g. 'modifiedTime desc', 'name', 'folder,modifiedTime desc')
979
1336
  */
@@ -1020,6 +1377,12 @@ var DriveQueryBuilder = class {
1020
1377
  });
1021
1378
  return res.data.files || [];
1022
1379
  }
1380
+ /**
1381
+ * Executes query and returns array of matching files (alias for list)
1382
+ */
1383
+ async execute() {
1384
+ return await this.list();
1385
+ }
1023
1386
  /**
1024
1387
  * Returns the first matching file, or null if not found
1025
1388
  */
@@ -1067,6 +1430,7 @@ var DriveQueryBuilder = class {
1067
1430
  };
1068
1431
 
1069
1432
  // src/core/concurrency-pool.ts
1433
+ init_esm_shims();
1070
1434
  var ConcurrencyPool = class {
1071
1435
  concurrency;
1072
1436
  running = 0;
@@ -1111,6 +1475,7 @@ var ConcurrencyPool = class {
1111
1475
  };
1112
1476
 
1113
1477
  // src/core/watcher.ts
1478
+ init_esm_shims();
1114
1479
  import { EventEmitter } from "events";
1115
1480
  var DriveWatcher = class extends EventEmitter {
1116
1481
  drive;
@@ -1224,6 +1589,7 @@ var DriveWatcher = class extends EventEmitter {
1224
1589
  };
1225
1590
 
1226
1591
  // src/core/storage-cleaner.ts
1592
+ init_esm_shims();
1227
1593
  var StorageCleaner = class {
1228
1594
  drive;
1229
1595
  constructor(drive2) {
@@ -1320,8 +1686,9 @@ var StorageCleaner = class {
1320
1686
  };
1321
1687
 
1322
1688
  // src/core/smart-sync.ts
1689
+ init_esm_shims();
1323
1690
  import fs4 from "fs";
1324
- import path3 from "path";
1691
+ import path4 from "path";
1325
1692
  import crypto from "crypto";
1326
1693
  async function calculateFileMd5(filePath) {
1327
1694
  return new Promise((resolve, reject) => {
@@ -1371,7 +1738,7 @@ var SmartSyncEngine = class {
1371
1738
  for (const file of files) {
1372
1739
  if (!file.id || !file.name) continue;
1373
1740
  const isFolder = file.mimeType === "application/vnd.google-apps.folder";
1374
- const fileRel = relPath ? path3.join(relPath, file.name) : file.name;
1741
+ const fileRel = relPath ? path4.join(relPath, file.name) : file.name;
1375
1742
  if (isFolder) {
1376
1743
  const sub = await collectRemoteItems(file.id, fileRel);
1377
1744
  items.push(...sub);
@@ -1392,7 +1759,7 @@ var SmartSyncEngine = class {
1392
1759
  };
1393
1760
  const remoteFiles = await collectRemoteItems(remoteFolderId, "");
1394
1761
  await pool.map(remoteFiles, async (remoteItem) => {
1395
- const localFilePath = path3.join(localDestinationDir, remoteItem.relPath);
1762
+ const localFilePath = path4.join(localDestinationDir, remoteItem.relPath);
1396
1763
  if (!options.overwrite && fs4.existsSync(localFilePath)) {
1397
1764
  const localStat = await fs4.promises.stat(localFilePath);
1398
1765
  if (remoteItem.md5Checksum) {
@@ -1445,6 +1812,7 @@ var SmartSyncEngine = class {
1445
1812
  };
1446
1813
 
1447
1814
  // src/auth/browser-login.ts
1815
+ init_esm_shims();
1448
1816
  import http from "http";
1449
1817
  import { exec } from "child_process";
1450
1818
  import { auth as googleAuth2 } from "@googleapis/drive";
@@ -1553,6 +1921,7 @@ ${authUrl}
1553
1921
  }
1554
1922
 
1555
1923
  // src/core/resource-refs.ts
1924
+ init_esm_shims();
1556
1925
  var DriveFileRef = class {
1557
1926
  drive;
1558
1927
  pathOrId;
@@ -1613,6 +1982,22 @@ var DriveFileRef = class {
1613
1982
  async getLink() {
1614
1983
  return await this.drive.getShareableLink(this.pathOrId);
1615
1984
  }
1985
+ /** Returns a ReadableStream for this file, optionally with byte Range requests */
1986
+ async createReadStream(options) {
1987
+ return await this.drive.createReadStream(this.pathOrId, options);
1988
+ }
1989
+ /** Grants access to a specific email with custom role and notification */
1990
+ async grantAccess(options) {
1991
+ return await this.drive.grantAccess(this.pathOrId, options);
1992
+ }
1993
+ /** Revokes access by permission ID or user email */
1994
+ async revokeAccess(permissionIdOrEmail) {
1995
+ return await this.drive.revokeAccess(this.pathOrId, permissionIdOrEmail);
1996
+ }
1997
+ /** Lists all granted permissions on this file */
1998
+ async listPermissions() {
1999
+ return await this.drive.listPermissions(this.pathOrId);
2000
+ }
1616
2001
  };
1617
2002
  var DriveFolderRef = class {
1618
2003
  drive;
@@ -1650,9 +2035,19 @@ var DriveFolderRef = class {
1650
2035
  async watch(options = {}) {
1651
2036
  return await this.drive.watch(this.pathOrId, options);
1652
2037
  }
2038
+ /** Grants access to this entire folder */
2039
+ async grantAccess(options) {
2040
+ return await this.drive.grantAccess(this.pathOrId, options);
2041
+ }
2042
+ /** Creates a writable stream directly into a file inside this folder */
2043
+ async createWriteStream(fileName, options) {
2044
+ const targetPath = this.pathOrId.endsWith("/") ? `${this.pathOrId}${fileName}` : `${this.pathOrId}/${fileName}`;
2045
+ return await this.drive.createWriteStream(targetPath, options);
2046
+ }
1653
2047
  };
1654
2048
 
1655
2049
  // src/core/plugins.ts
2050
+ init_esm_shims();
1656
2051
  var PluginManager = class {
1657
2052
  plugins = [];
1658
2053
  use(plugin) {
@@ -1700,15 +2095,413 @@ var PluginManager = class {
1700
2095
  return current;
1701
2096
  }
1702
2097
  };
2098
+ function createWebhookPlugin(options) {
2099
+ const events = options.events || ["upload"];
2100
+ return {
2101
+ name: "drivekit-official-webhook",
2102
+ async afterUpload(file) {
2103
+ if (!events.includes("upload")) return;
2104
+ try {
2105
+ await fetch(options.url, {
2106
+ method: "POST",
2107
+ headers: { "Content-Type": "application/json", ...options.headers || {} },
2108
+ body: JSON.stringify({
2109
+ event: "drivekit:upload",
2110
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2111
+ file: {
2112
+ id: file.id,
2113
+ name: file.name,
2114
+ size: file.size,
2115
+ mimeType: file.mimeType
2116
+ }
2117
+ })
2118
+ });
2119
+ } catch (e) {
2120
+ }
2121
+ },
2122
+ async afterDownload(result) {
2123
+ if (!events.includes("download")) return;
2124
+ try {
2125
+ await fetch(options.url, {
2126
+ method: "POST",
2127
+ headers: { "Content-Type": "application/json", ...options.headers || {} },
2128
+ body: JSON.stringify({
2129
+ event: "drivekit:download",
2130
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2131
+ file: {
2132
+ name: result.name,
2133
+ size: result.size
2134
+ }
2135
+ })
2136
+ });
2137
+ } catch (e) {
2138
+ }
2139
+ }
2140
+ };
2141
+ }
2142
+ function createAutoNamePlugin(options) {
2143
+ return {
2144
+ name: "drivekit-official-autoname",
2145
+ beforeUpload(opts) {
2146
+ let name = opts.filename;
2147
+ if (!name && typeof opts.source === "string") {
2148
+ const pathModule2 = __require("path");
2149
+ name = pathModule2.basename(opts.source);
2150
+ }
2151
+ if (!name) return opts;
2152
+ const pathModule = __require("path");
2153
+ const ext = pathModule.extname(name);
2154
+ const base = pathModule.basename(name, ext);
2155
+ let finalName = base;
2156
+ if (options.prefix) finalName = `${options.prefix}${finalName}`;
2157
+ if (options.appendTimestamp) {
2158
+ finalName = `${finalName}_${Date.now()}`;
2159
+ }
2160
+ if (options.suffix) finalName = `${finalName}${options.suffix}`;
2161
+ finalName = `${finalName}${ext}`;
2162
+ return {
2163
+ ...opts,
2164
+ filename: finalName
2165
+ };
2166
+ }
2167
+ };
2168
+ }
2169
+
2170
+ // src/core/cache.ts
2171
+ init_esm_shims();
2172
+ import os from "os";
2173
+ import path5 from "path";
2174
+ import fs5 from "fs";
2175
+ var SqliteMetadataCache = class {
2176
+ db = null;
2177
+ dbPath;
2178
+ initialized = false;
2179
+ fallbackMemory;
2180
+ constructor(customPath) {
2181
+ if (customPath) {
2182
+ this.dbPath = customPath;
2183
+ } else {
2184
+ const dir = path5.join(os.homedir(), ".drivekit");
2185
+ if (!fs5.existsSync(dir)) {
2186
+ try {
2187
+ fs5.mkdirSync(dir, { recursive: true });
2188
+ } catch {
2189
+ }
2190
+ }
2191
+ this.dbPath = path5.join(dir, "cache.db");
2192
+ }
2193
+ }
2194
+ init() {
2195
+ if (this.initialized) return;
2196
+ try {
2197
+ const { DatabaseSync } = __require("sqlite");
2198
+ if (!DatabaseSync) {
2199
+ throw new Error("DatabaseSync not available");
2200
+ }
2201
+ this.db = new DatabaseSync(this.dbPath);
2202
+ this.db.exec(`
2203
+ PRAGMA journal_mode = WAL;
2204
+ PRAGMA synchronous = NORMAL;
2205
+
2206
+ CREATE TABLE IF NOT EXISTS files (
2207
+ id TEXT PRIMARY KEY,
2208
+ name TEXT NOT NULL,
2209
+ mimeType TEXT NOT NULL,
2210
+ size INTEGER,
2211
+ parentId TEXT,
2212
+ path TEXT,
2213
+ md5Checksum TEXT,
2214
+ trashed INTEGER DEFAULT 0,
2215
+ modifiedTime TEXT,
2216
+ updatedAt INTEGER
2217
+ );
2218
+
2219
+ CREATE TABLE IF NOT EXISTS meta (
2220
+ key TEXT PRIMARY KEY,
2221
+ value TEXT NOT NULL
2222
+ );
2223
+
2224
+ CREATE INDEX IF NOT EXISTS idx_files_path ON files(path);
2225
+ CREATE INDEX IF NOT EXISTS idx_files_parent ON files(parentId);
2226
+ CREATE INDEX IF NOT EXISTS idx_files_md5 ON files(md5Checksum);
2227
+ CREATE INDEX IF NOT EXISTS idx_files_name ON files(name);
2228
+ `);
2229
+ this.initialized = true;
2230
+ } catch (err) {
2231
+ this.fallbackMemory = new MemoryMetadataCache();
2232
+ this.fallbackMemory.init();
2233
+ this.initialized = true;
2234
+ this.db = null;
2235
+ }
2236
+ }
2237
+ getById(id) {
2238
+ if (this.fallbackMemory) return this.fallbackMemory.getById(id);
2239
+ if (!this.initialized || !this.db) return null;
2240
+ const stmt = this.db.prepare("SELECT * FROM files WHERE id = ?");
2241
+ const row = stmt.get(id);
2242
+ return row ? this.mapRow(row) : null;
2243
+ }
2244
+ getByPath(normalizedPath) {
2245
+ if (this.fallbackMemory) return this.fallbackMemory.getByPath(normalizedPath);
2246
+ if (!this.initialized || !this.db) return null;
2247
+ const stmt = this.db.prepare("SELECT * FROM files WHERE path = ? AND trashed = 0 LIMIT 1");
2248
+ const row = stmt.get(normalizedPath);
2249
+ return row ? this.mapRow(row) : null;
2250
+ }
2251
+ getChildren(parentId) {
2252
+ if (this.fallbackMemory) return this.fallbackMemory.getChildren(parentId);
2253
+ if (!this.initialized || !this.db) return [];
2254
+ const stmt = this.db.prepare("SELECT * FROM files WHERE parentId = ? AND trashed = 0 ORDER BY name ASC");
2255
+ const rows = stmt.all(parentId);
2256
+ return rows.map((r) => this.mapRow(r));
2257
+ }
2258
+ findByMd5(md5) {
2259
+ if (this.fallbackMemory) return this.fallbackMemory.findByMd5(md5);
2260
+ if (!this.initialized || !this.db || !md5) return null;
2261
+ const stmt = this.db.prepare("SELECT * FROM files WHERE md5Checksum = ? AND trashed = 0 LIMIT 1");
2262
+ const row = stmt.get(md5.toLowerCase());
2263
+ return row ? this.mapRow(row) : null;
2264
+ }
2265
+ searchByName(query) {
2266
+ if (this.fallbackMemory) return this.fallbackMemory.searchByName(query);
2267
+ if (!this.initialized || !this.db) return [];
2268
+ const stmt = this.db.prepare("SELECT * FROM files WHERE name LIKE ? AND trashed = 0 LIMIT 50");
2269
+ const rows = stmt.all(`%${query}%`);
2270
+ return rows.map((r) => this.mapRow(r));
2271
+ }
2272
+ upsertFile(entry) {
2273
+ if (this.fallbackMemory) {
2274
+ this.fallbackMemory.upsertFile(entry);
2275
+ return;
2276
+ }
2277
+ if (!this.initialized || !this.db) return;
2278
+ const stmt = this.db.prepare(`
2279
+ INSERT INTO files (id, name, mimeType, size, parentId, path, md5Checksum, trashed, modifiedTime, updatedAt)
2280
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2281
+ ON CONFLICT(id) DO UPDATE SET
2282
+ name = excluded.name,
2283
+ mimeType = excluded.mimeType,
2284
+ size = excluded.size,
2285
+ parentId = excluded.parentId,
2286
+ path = COALESCE(excluded.path, files.path),
2287
+ md5Checksum = excluded.md5Checksum,
2288
+ trashed = excluded.trashed,
2289
+ modifiedTime = excluded.modifiedTime,
2290
+ updatedAt = excluded.updatedAt
2291
+ `);
2292
+ stmt.run(
2293
+ entry.id,
2294
+ entry.name,
2295
+ entry.mimeType,
2296
+ entry.size ?? null,
2297
+ entry.parentId ?? null,
2298
+ entry.path ?? null,
2299
+ entry.md5Checksum ? entry.md5Checksum.toLowerCase() : null,
2300
+ entry.trashed ? 1 : 0,
2301
+ entry.modifiedTime ?? null,
2302
+ entry.updatedAt ?? Date.now()
2303
+ );
2304
+ }
2305
+ upsertFiles(entries) {
2306
+ if (this.fallbackMemory) {
2307
+ this.fallbackMemory.upsertFiles(entries);
2308
+ return;
2309
+ }
2310
+ if (!this.initialized || !this.db || entries.length === 0) return;
2311
+ this.db.exec("BEGIN TRANSACTION;");
2312
+ try {
2313
+ for (const entry of entries) {
2314
+ this.upsertFile(entry);
2315
+ }
2316
+ this.db.exec("COMMIT;");
2317
+ } catch (e) {
2318
+ this.db.exec("ROLLBACK;");
2319
+ throw e;
2320
+ }
2321
+ }
2322
+ deleteFile(id) {
2323
+ if (this.fallbackMemory) {
2324
+ this.fallbackMemory.deleteFile(id);
2325
+ return;
2326
+ }
2327
+ if (!this.initialized || !this.db) return;
2328
+ const stmt = this.db.prepare("DELETE FROM files WHERE id = ?");
2329
+ stmt.run(id);
2330
+ }
2331
+ clear() {
2332
+ if (this.fallbackMemory) {
2333
+ this.fallbackMemory.clear();
2334
+ return;
2335
+ }
2336
+ if (!this.initialized || !this.db) return;
2337
+ this.db.exec("DELETE FROM files; DELETE FROM meta;");
2338
+ }
2339
+ getMeta(key) {
2340
+ if (this.fallbackMemory) return this.fallbackMemory.getMeta(key);
2341
+ if (!this.initialized || !this.db) return null;
2342
+ const stmt = this.db.prepare("SELECT value FROM meta WHERE key = ?");
2343
+ const row = stmt.get(key);
2344
+ return row ? row.value : null;
2345
+ }
2346
+ setMeta(key, value) {
2347
+ if (this.fallbackMemory) {
2348
+ this.fallbackMemory.setMeta(key, value);
2349
+ return;
2350
+ }
2351
+ if (!this.initialized || !this.db) return;
2352
+ const stmt = this.db.prepare(`
2353
+ INSERT INTO meta (key, value) VALUES (?, ?)
2354
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value
2355
+ `);
2356
+ stmt.run(key, value);
2357
+ }
2358
+ getStats() {
2359
+ if (this.fallbackMemory) return this.fallbackMemory.getStats();
2360
+ if (!this.initialized || !this.db) {
2361
+ return {
2362
+ fileCount: 0,
2363
+ folderCount: 0,
2364
+ totalSizeBytes: 0,
2365
+ lastSyncTime: null,
2366
+ databasePath: this.dbPath
2367
+ };
2368
+ }
2369
+ const fileCountRow = this.db.prepare(
2370
+ "SELECT COUNT(*) as count FROM files WHERE mimeType != 'application/vnd.google-apps.folder' AND trashed = 0"
2371
+ ).get();
2372
+ const folderCountRow = this.db.prepare(
2373
+ "SELECT COUNT(*) as count FROM files WHERE mimeType = 'application/vnd.google-apps.folder' AND trashed = 0"
2374
+ ).get();
2375
+ const totalSizeRow = this.db.prepare(
2376
+ "SELECT SUM(size) as total FROM files WHERE trashed = 0"
2377
+ ).get();
2378
+ const lastSync = this.getMeta("last_sync_timestamp");
2379
+ return {
2380
+ fileCount: fileCountRow?.count || 0,
2381
+ folderCount: folderCountRow?.count || 0,
2382
+ totalSizeBytes: totalSizeRow?.total || 0,
2383
+ lastSyncTime: lastSync,
2384
+ databasePath: this.dbPath
2385
+ };
2386
+ }
2387
+ close() {
2388
+ if (this.fallbackMemory) {
2389
+ this.fallbackMemory.close();
2390
+ this.fallbackMemory = void 0;
2391
+ }
2392
+ if (this.db) {
2393
+ try {
2394
+ this.db.close();
2395
+ } catch {
2396
+ }
2397
+ this.initialized = false;
2398
+ this.db = null;
2399
+ }
2400
+ }
2401
+ mapRow(row) {
2402
+ return {
2403
+ id: row.id,
2404
+ name: row.name,
2405
+ mimeType: row.mimeType,
2406
+ size: row.size != null ? Number(row.size) : void 0,
2407
+ parentId: row.parentId || void 0,
2408
+ path: row.path || void 0,
2409
+ md5Checksum: row.md5Checksum || void 0,
2410
+ trashed: row.trashed === 1,
2411
+ modifiedTime: row.modifiedTime || void 0,
2412
+ updatedAt: row.updatedAt != null ? Number(row.updatedAt) : void 0
2413
+ };
2414
+ }
2415
+ };
2416
+ var MemoryMetadataCache = class {
2417
+ files = /* @__PURE__ */ new Map();
2418
+ meta = /* @__PURE__ */ new Map();
2419
+ init() {
2420
+ }
2421
+ getById(id) {
2422
+ return this.files.get(id) || null;
2423
+ }
2424
+ getByPath(normalizedPath) {
2425
+ for (const f of this.files.values()) {
2426
+ if (f.path === normalizedPath && !f.trashed) return f;
2427
+ }
2428
+ return null;
2429
+ }
2430
+ getChildren(parentId) {
2431
+ const list = [];
2432
+ for (const f of this.files.values()) {
2433
+ if (f.parentId === parentId && !f.trashed) list.push(f);
2434
+ }
2435
+ return list;
2436
+ }
2437
+ findByMd5(md5) {
2438
+ const target = md5.toLowerCase();
2439
+ for (const f of this.files.values()) {
2440
+ if (f.md5Checksum?.toLowerCase() === target && !f.trashed) return f;
2441
+ }
2442
+ return null;
2443
+ }
2444
+ searchByName(query) {
2445
+ const q = query.toLowerCase();
2446
+ const list = [];
2447
+ for (const f of this.files.values()) {
2448
+ if (f.name.toLowerCase().includes(q) && !f.trashed) list.push(f);
2449
+ }
2450
+ return list;
2451
+ }
2452
+ upsertFile(entry) {
2453
+ this.files.set(entry.id, { ...entry, updatedAt: Date.now() });
2454
+ }
2455
+ upsertFiles(entries) {
2456
+ for (const e of entries) this.upsertFile(e);
2457
+ }
2458
+ deleteFile(id) {
2459
+ this.files.delete(id);
2460
+ }
2461
+ clear() {
2462
+ this.files.clear();
2463
+ this.meta.clear();
2464
+ }
2465
+ getMeta(key) {
2466
+ return this.meta.get(key) || null;
2467
+ }
2468
+ setMeta(key, value) {
2469
+ this.meta.set(key, value);
2470
+ }
2471
+ getStats() {
2472
+ let fileCount = 0;
2473
+ let folderCount = 0;
2474
+ let totalSizeBytes = 0;
2475
+ for (const f of this.files.values()) {
2476
+ if (f.trashed) continue;
2477
+ if (f.mimeType === "application/vnd.google-apps.folder") folderCount++;
2478
+ else {
2479
+ fileCount++;
2480
+ totalSizeBytes += f.size || 0;
2481
+ }
2482
+ }
2483
+ return {
2484
+ fileCount,
2485
+ folderCount,
2486
+ totalSizeBytes,
2487
+ lastSyncTime: this.meta.get("last_sync_timestamp") || null,
2488
+ databasePath: ":memory:"
2489
+ };
2490
+ }
2491
+ close() {
2492
+ this.clear();
2493
+ }
2494
+ };
1703
2495
 
1704
2496
  // src/core/client.ts
1705
- var DriveKit = class {
2497
+ var DriveKit = class _DriveKit {
1706
2498
  options;
1707
2499
  authenticator;
1708
2500
  driveClient = null;
1709
2501
  pathResolverInstance = null;
1710
2502
  uploaderInstance = null;
1711
2503
  downloaderInstance = null;
2504
+ metadataCacheInstance = null;
1712
2505
  rootFolderId;
1713
2506
  pluginManager = new PluginManager();
1714
2507
  constructor(options = {}) {
@@ -1742,9 +2535,14 @@ var DriveKit = class {
1742
2535
  if (!this.driveClient) {
1743
2536
  const auth = await this.authenticator.getAuthClient();
1744
2537
  this.driveClient = drive({ version: "v3", auth });
2538
+ if (this.options.enablePersistentCache !== false) {
2539
+ this.metadataCacheInstance = new SqliteMetadataCache(this.options.cacheDatabasePath);
2540
+ this.metadataCacheInstance.init();
2541
+ }
1745
2542
  this.pathResolverInstance = new PathResolver(this.driveClient, this.rootFolderId, {
1746
2543
  enableCache: this.options.enablePathCache ?? true,
1747
- cacheTTL: this.options.pathCacheTTL
2544
+ cacheTTL: this.options.pathCacheTTL,
2545
+ metadataCache: this.metadataCacheInstance || void 0
1748
2546
  });
1749
2547
  this.uploaderInstance = new ResumableUploader(
1750
2548
  this.driveClient,
@@ -1849,16 +2647,71 @@ var DriveKit = class {
1849
2647
  if (parentId && parentId.startsWith("/")) {
1850
2648
  parentId = await this.mkdirp(parentId);
1851
2649
  }
1852
- if (opts.overwrite && opts.name && parentId) {
1853
- const existing = await this.query().inFolder(parentId).nameEquals(opts.name).notTrashed().first();
2650
+ const targetName = opts.name || opts.filename;
2651
+ if (opts.overwrite && targetName && parentId) {
2652
+ const existing = await this.query().inFolder(parentId).nameEquals(targetName).notTrashed().first();
1854
2653
  if (existing?.id) {
1855
2654
  await this.delete(existing.id, true);
1856
2655
  }
1857
2656
  }
2657
+ if (opts.deduplicate && typeof opts.source === "string" && fs6.existsSync(opts.source)) {
2658
+ const localMd5 = await calculateFileMd5(opts.source);
2659
+ let existingId;
2660
+ if (this.metadataCacheInstance) {
2661
+ const cached = this.metadataCacheInstance.findByMd5(localMd5);
2662
+ if (cached) existingId = cached.id;
2663
+ }
2664
+ if (!existingId) {
2665
+ const found = await this.query().md5(localMd5).notTrashed().first();
2666
+ if (found?.id) {
2667
+ existingId = found.id;
2668
+ }
2669
+ }
2670
+ if (existingId) {
2671
+ const fileName = targetName || path7.basename(opts.source);
2672
+ const raw = await this.getRawClient();
2673
+ const copyRes = await withRetry(async () => {
2674
+ return await raw.files.copy({
2675
+ fileId: existingId,
2676
+ requestBody: {
2677
+ name: fileName,
2678
+ parents: parentId ? [parentId] : void 0,
2679
+ description: opts.description
2680
+ },
2681
+ fields: "id, name, mimeType, size, modifiedTime, md5Checksum",
2682
+ supportsAllDrives: true
2683
+ });
2684
+ });
2685
+ const file = copyRes.data;
2686
+ if (this.metadataCacheInstance && file.id) {
2687
+ this.metadataCacheInstance.upsertFile({
2688
+ id: file.id,
2689
+ name: file.name || fileName,
2690
+ mimeType: file.mimeType || "",
2691
+ size: file.size ? parseInt(file.size, 10) : void 0,
2692
+ parentId,
2693
+ md5Checksum: localMd5,
2694
+ trashed: false
2695
+ });
2696
+ }
2697
+ return await this.pluginManager.runAfterUpload(file);
2698
+ }
2699
+ }
1858
2700
  const uploaded = await uploader.upload({
1859
2701
  ...opts,
2702
+ name: targetName,
1860
2703
  parent: parentId
1861
2704
  });
2705
+ if (this.metadataCacheInstance && uploaded.id) {
2706
+ this.metadataCacheInstance.upsertFile({
2707
+ id: uploaded.id,
2708
+ name: uploaded.name || targetName || "untitled",
2709
+ mimeType: uploaded.mimeType || "",
2710
+ size: uploaded.size ? parseInt(uploaded.size, 10) : void 0,
2711
+ parentId,
2712
+ trashed: false
2713
+ });
2714
+ }
1862
2715
  return await this.pluginManager.runAfterUpload(uploaded);
1863
2716
  }
1864
2717
  /**
@@ -2099,16 +2952,16 @@ var DriveKit = class {
2099
2952
  durationMs: 0
2100
2953
  };
2101
2954
  const collectFiles = async (dir, base) => {
2102
- const entries = await fs5.promises.readdir(dir, { withFileTypes: true });
2955
+ const entries = await fs6.promises.readdir(dir, { withFileTypes: true });
2103
2956
  const files = [];
2104
2957
  for (const entry of entries) {
2105
- const fullPath = path4.join(dir, entry.name);
2106
- const relPath = path4.join(base, entry.name);
2958
+ const fullPath = path7.join(dir, entry.name);
2959
+ const relPath = path7.join(base, entry.name);
2107
2960
  if (entry.isDirectory()) {
2108
2961
  const sub = await collectFiles(fullPath, relPath);
2109
2962
  files.push(...sub);
2110
2963
  } else if (entry.isFile()) {
2111
- const stat = await fs5.promises.stat(fullPath);
2964
+ const stat = await fs6.promises.stat(fullPath);
2112
2965
  files.push({ fullPath, relPath, size: stat.size });
2113
2966
  }
2114
2967
  }
@@ -2121,11 +2974,11 @@ var DriveKit = class {
2121
2974
  if (remoteDirCache.has(relDir)) {
2122
2975
  return remoteDirCache.get(relDir);
2123
2976
  }
2124
- const parts = relDir.split(path4.sep).filter(Boolean);
2977
+ const parts = relDir.split(path7.sep).filter(Boolean);
2125
2978
  let currentParent = targetFolderId;
2126
2979
  let currentRel = "";
2127
2980
  for (const part of parts) {
2128
- currentRel = currentRel ? path4.join(currentRel, part) : part;
2981
+ currentRel = currentRel ? path7.join(currentRel, part) : part;
2129
2982
  if (remoteDirCache.has(currentRel)) {
2130
2983
  currentParent = remoteDirCache.get(currentRel);
2131
2984
  continue;
@@ -2154,8 +3007,8 @@ var DriveKit = class {
2154
3007
  };
2155
3008
  await pool.map(allFiles, async (fileItem) => {
2156
3009
  try {
2157
- const relDir = path4.dirname(fileItem.relPath);
2158
- const fileName = path4.basename(fileItem.relPath);
3010
+ const relDir = path7.dirname(fileItem.relPath);
3011
+ const fileName = path7.basename(fileItem.relPath);
2159
3012
  const parentFolderId = await ensureRemoteSubdir(relDir === "." ? "" : relDir);
2160
3013
  if (options.onFileStart) {
2161
3014
  options.onFileStart(fileItem.fullPath, fileItem.relPath);
@@ -2273,6 +3126,217 @@ var DriveKit = class {
2273
3126
  const engine = new SmartSyncEngine(this.driveClient);
2274
3127
  return await engine.pullFolder(folderId, localDestinationDir, options);
2275
3128
  }
3129
+ // ==========================================
3130
+ // STREAMS & RANGE REQUESTS
3131
+ // ==========================================
3132
+ /**
3133
+ * Creates a readable stream for a file, supporting partial range requests
3134
+ */
3135
+ async createReadStream(pathOrId, options) {
3136
+ const fileId = await this.resolveId(pathOrId);
3137
+ const downloader = await this.getDownloader();
3138
+ return await downloader.createReadStream(fileId, options);
3139
+ }
3140
+ /**
3141
+ * Creates a writable stream directly into Google Drive
3142
+ */
3143
+ async createWriteStream(remotePath, options = {}) {
3144
+ await this.init();
3145
+ const { PassThrough } = await import("stream");
3146
+ const passThrough = new PassThrough();
3147
+ const remoteDir = path7.dirname(remotePath);
3148
+ const fileName = options.name || options.filename || path7.basename(remotePath);
3149
+ const targetParentId = remoteDir === "." || remoteDir === "/" ? this.rootFolderId : await this.mkdirp(remoteDir);
3150
+ const mimeType = options.mimeType || "application/octet-stream";
3151
+ const raw = this.driveClient;
3152
+ raw.files.create({
3153
+ requestBody: {
3154
+ name: fileName,
3155
+ parents: [targetParentId],
3156
+ description: options.description
3157
+ },
3158
+ media: {
3159
+ mimeType,
3160
+ body: passThrough
3161
+ },
3162
+ fields: "id, name, mimeType, size, md5Checksum",
3163
+ supportsAllDrives: true
3164
+ }).then((res) => {
3165
+ if (res.data.id && this.metadataCacheInstance) {
3166
+ this.metadataCacheInstance.upsertFile({
3167
+ id: res.data.id,
3168
+ name: fileName,
3169
+ mimeType,
3170
+ parentId: targetParentId,
3171
+ path: remotePath,
3172
+ trashed: false
3173
+ });
3174
+ }
3175
+ }).catch((err) => {
3176
+ passThrough.destroy(err);
3177
+ });
3178
+ return passThrough;
3179
+ }
3180
+ // ==========================================
3181
+ // METADATA CACHE OPERATIONS
3182
+ // ==========================================
3183
+ /**
3184
+ * Returns the active persistent metadata cache instance (SQLite/Memory)
3185
+ */
3186
+ async getMetadataCache() {
3187
+ await this.init();
3188
+ return this.metadataCacheInstance;
3189
+ }
3190
+ /**
3191
+ * Returns cache statistics (total files, folders, size, last sync)
3192
+ */
3193
+ async getCacheStats() {
3194
+ await this.init();
3195
+ return this.metadataCacheInstance ? this.metadataCacheInstance.getStats() : null;
3196
+ }
3197
+ /**
3198
+ * Clears the path and metadata cache
3199
+ */
3200
+ async clearCache() {
3201
+ await this.init();
3202
+ if (this.pathResolverInstance) {
3203
+ this.pathResolverInstance.clearCache();
3204
+ }
3205
+ }
3206
+ /**
3207
+ * Crawls and indexes Google Drive metadata into the local SQLite database for instant 0ms lookups
3208
+ */
3209
+ async syncCache(options) {
3210
+ await this.init();
3211
+ if (!this.metadataCacheInstance) {
3212
+ throw new Error("Persistent cache is disabled on this DriveKit instance");
3213
+ }
3214
+ const client = this.driveClient;
3215
+ let pageToken = void 0;
3216
+ let totalScanned = 0;
3217
+ do {
3218
+ const res = await withRetry(async () => {
3219
+ return await client.files.list({
3220
+ pageSize: 1e3,
3221
+ pageToken,
3222
+ fields: "nextPageToken, files(id, name, mimeType, size, parents, md5Checksum, trashed, modifiedTime)",
3223
+ spaces: "drive",
3224
+ supportsAllDrives: true,
3225
+ includeItemsFromAllDrives: true,
3226
+ q: "trashed = false"
3227
+ });
3228
+ });
3229
+ const files = res.data.files || [];
3230
+ const entries = files.map((f) => ({
3231
+ id: f.id,
3232
+ name: f.name || "untitled",
3233
+ mimeType: f.mimeType || "",
3234
+ size: f.size ? parseInt(f.size, 10) : void 0,
3235
+ parentId: f.parents?.[0],
3236
+ md5Checksum: f.md5Checksum || void 0,
3237
+ trashed: !!f.trashed,
3238
+ modifiedTime: f.modifiedTime || void 0
3239
+ }));
3240
+ this.metadataCacheInstance.upsertFiles(entries);
3241
+ totalScanned += entries.length;
3242
+ options?.onProgress?.(totalScanned);
3243
+ pageToken = res.data.nextPageToken || void 0;
3244
+ } while (pageToken);
3245
+ this.metadataCacheInstance.setMeta("last_sync_timestamp", (/* @__PURE__ */ new Date()).toISOString());
3246
+ return this.metadataCacheInstance.getStats();
3247
+ }
3248
+ // ==========================================
3249
+ // SHARED DRIVES & ENTERPRISE PERMISSIONS
3250
+ // ==========================================
3251
+ /**
3252
+ * Lists all Google Workspace Shared Drives accessible by current user or service account
3253
+ */
3254
+ async listSharedDrives(options = {}) {
3255
+ await this.init();
3256
+ const raw = await this.getRawClient();
3257
+ const res = await withRetry(async () => {
3258
+ return await raw.drives.list({
3259
+ pageSize: options.pageSize || 100,
3260
+ fields: "drives(id, name)"
3261
+ });
3262
+ });
3263
+ return (res.data.drives || []).map((d) => ({ id: d.id, name: d.name }));
3264
+ }
3265
+ /**
3266
+ * Creates a scoped DriveKit client locked to a specific Shared Drive
3267
+ */
3268
+ sharedDrive(driveId) {
3269
+ return new _DriveKit({
3270
+ ...this.options,
3271
+ rootFolderId: driveId
3272
+ });
3273
+ }
3274
+ /**
3275
+ * Grants access to a specific email with custom role and notification
3276
+ */
3277
+ async grantAccess(pathOrId, options) {
3278
+ const fileId = await this.resolveId(pathOrId);
3279
+ const raw = await this.getRawClient();
3280
+ const res = await withRetry(async () => {
3281
+ return await raw.permissions.create({
3282
+ fileId,
3283
+ requestBody: {
3284
+ type: "user",
3285
+ role: options.role || "reader",
3286
+ emailAddress: options.email
3287
+ },
3288
+ sendNotificationEmail: options.notify ?? true,
3289
+ emailMessage: options.message,
3290
+ fields: "id, type, role, emailAddress, displayName",
3291
+ supportsAllDrives: true
3292
+ });
3293
+ });
3294
+ return res.data;
3295
+ }
3296
+ /**
3297
+ * Revokes access for a specific permission ID or email address
3298
+ */
3299
+ async revokeAccess(pathOrId, permissionIdOrEmail) {
3300
+ const fileId = await this.resolveId(pathOrId);
3301
+ const raw = await this.getRawClient();
3302
+ let targetId = permissionIdOrEmail;
3303
+ if (permissionIdOrEmail.includes("@")) {
3304
+ const listRes = await this.listPermissions(fileId);
3305
+ const found = listRes.find((p) => p.emailAddress?.toLowerCase() === permissionIdOrEmail.toLowerCase());
3306
+ if (found && found.id) {
3307
+ targetId = found.id;
3308
+ }
3309
+ }
3310
+ await withRetry(async () => {
3311
+ return await raw.permissions.delete({
3312
+ fileId,
3313
+ permissionId: targetId,
3314
+ supportsAllDrives: true
3315
+ });
3316
+ });
3317
+ }
3318
+ /**
3319
+ * Lists all active permissions on a file or folder
3320
+ */
3321
+ async listPermissions(pathOrId) {
3322
+ const fileId = await this.resolveId(pathOrId);
3323
+ const raw = await this.getRawClient();
3324
+ const res = await withRetry(async () => {
3325
+ return await raw.permissions.list({
3326
+ fileId,
3327
+ fields: "permissions(id, type, role, emailAddress, displayName)",
3328
+ supportsAllDrives: true
3329
+ });
3330
+ });
3331
+ return res.data.permissions || [];
3332
+ }
3333
+ /**
3334
+ * Starts an embedded WebDAV server to mount DriveKit directly in macOS Finder or Windows Explorer
3335
+ */
3336
+ async serveWebDAV(options) {
3337
+ const { startWebDAVServer: startWebDAVServer2 } = await Promise.resolve().then(() => (init_webdav(), webdav_exports));
3338
+ return await startWebDAVServer2(this, options);
3339
+ }
2276
3340
  /**
2277
3341
  * Calculates local file MD5 hash for integrity and deduplication checks
2278
3342
  */
@@ -2287,11 +3351,18 @@ var DriveKit = class {
2287
3351
  }
2288
3352
  };
2289
3353
 
3354
+ // src/types.ts
3355
+ init_esm_shims();
3356
+
3357
+ // src/index.ts
3358
+ init_webdav();
3359
+
2290
3360
  // src/cli/terminal-ui.ts
3361
+ init_esm_shims();
2291
3362
  import readline from "readline";
2292
3363
  import chalk from "chalk";
2293
- function terminalLink(text, url) {
2294
- return `\x1B]8;;${url}\x07${text}\x1B]8;;\x07`;
3364
+ function terminalLink(text, url2) {
3365
+ return `\x1B]8;;${url2}\x07${text}\x1B]8;;\x07`;
2295
3366
  }
2296
3367
  function renderFileRow(item, index) {
2297
3368
  const isDir = item.mimeType === "application/vnd.google-apps.folder";
@@ -2466,13 +3537,17 @@ export {
2466
3537
  GOOGLE_WORKSPACE_MIME_TYPES,
2467
3538
  MIN_CHUNK_SIZE,
2468
3539
  MULTIPART_THRESHOLD,
3540
+ MemoryMetadataCache,
2469
3541
  PathResolver,
2470
3542
  PluginManager,
2471
3543
  ResumableUploader,
2472
3544
  SmartSyncEngine,
3545
+ SqliteMetadataCache,
2473
3546
  StorageCleaner,
2474
3547
  calculateFileMd5,
3548
+ createAutoNamePlugin,
2475
3549
  createDrive,
3550
+ createWebhookPlugin,
2476
3551
  index_default as default,
2477
3552
  formatBytes,
2478
3553
  formatDuration,
@@ -2485,6 +3560,7 @@ export {
2485
3560
  lookupMimeType,
2486
3561
  renderFileRow,
2487
3562
  runInteractiveExplorer,
3563
+ startWebDAVServer,
2488
3564
  terminalLink,
2489
3565
  withRetry
2490
3566
  };