drivekit 1.0.2 → 1.1.1

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,336 @@ 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
+ escapeXml: () => escapeXml,
44
+ startWebDAVServer: () => startWebDAVServer
45
+ });
46
+ function escapeXml(unsafe) {
47
+ return unsafe.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
48
+ }
49
+ async function startWebDAVServer(drive2, options = {}) {
50
+ const port = options.port || 8080;
51
+ const host = options.host || "127.0.0.1";
52
+ await drive2.init();
53
+ const server = import_node_http2.default.createServer(async (req, res) => {
54
+ try {
55
+ if (options.auth?.username && options.auth?.password) {
56
+ const authHeader = req.headers["authorization"];
57
+ if (!authHeader || !authHeader.startsWith("Basic ")) {
58
+ res.writeHead(401, {
59
+ "WWW-Authenticate": 'Basic realm="DriveKit WebDAV"',
60
+ "Content-Type": "text/plain"
61
+ });
62
+ res.end("Authentication required");
63
+ return;
64
+ }
65
+ const credentials = Buffer.from(authHeader.replace("Basic ", ""), "base64").toString("utf8");
66
+ const [user, pass] = credentials.split(":");
67
+ if (user !== options.auth.username || pass !== options.auth.password) {
68
+ res.writeHead(401, {
69
+ "WWW-Authenticate": 'Basic realm="DriveKit WebDAV"',
70
+ "Content-Type": "text/plain"
71
+ });
72
+ res.end("Invalid credentials");
73
+ return;
74
+ }
75
+ }
76
+ const parsedUrl = import_node_url.default.parse(req.url || "/", true);
77
+ const decodedPath = decodeURIComponent(parsedUrl.pathname || "/");
78
+ const virtualPath = decodedPath === "" ? "/" : decodedPath;
79
+ switch (req.method) {
80
+ case "OPTIONS": {
81
+ res.writeHead(200, {
82
+ DAV: "1, 2",
83
+ Allow: "OPTIONS, GET, HEAD, POST, PUT, DELETE, MKCOL, MOVE, COPY, PROPFIND",
84
+ "MS-Author-Via": "DAV",
85
+ "Accept-Ranges": "bytes"
86
+ });
87
+ res.end();
88
+ return;
89
+ }
90
+ case "PROPFIND": {
91
+ const depth = req.headers["depth"] || "1";
92
+ const xml = await handlePropfind(drive2, virtualPath, depth);
93
+ res.writeHead(207, {
94
+ "Content-Type": "application/xml; charset=utf-8"
95
+ });
96
+ res.end(xml);
97
+ return;
98
+ }
99
+ case "GET":
100
+ case "HEAD": {
101
+ if (virtualPath === "/" || virtualPath === "") {
102
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
103
+ res.end("<h1>DriveKit WebDAV Server Running</h1><p>Connect via Finder, File Explorer, or WebDAV client.</p>");
104
+ return;
105
+ }
106
+ try {
107
+ const file = await drive2.getFile(virtualPath);
108
+ if (file.mimeType === "application/vnd.google-apps.folder") {
109
+ res.writeHead(405, { "Content-Type": "text/plain" });
110
+ res.end("Cannot GET a directory");
111
+ return;
112
+ }
113
+ const fileSize = file.size ? parseInt(file.size, 10) : void 0;
114
+ const rangeHeader = req.headers["range"];
115
+ if (rangeHeader && rangeHeader.startsWith("bytes=") && fileSize !== void 0) {
116
+ const parts = rangeHeader.replace("bytes=", "").split("-");
117
+ const start = parseInt(parts[0], 10);
118
+ const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
119
+ if (isNaN(start) || start >= fileSize || end !== void 0 && end >= fileSize) {
120
+ res.writeHead(416, { "Content-Range": `bytes */${fileSize}` });
121
+ res.end();
122
+ return;
123
+ }
124
+ const stream = await drive2.createReadStream(virtualPath, { start, end });
125
+ const chunkLength = end - start + 1;
126
+ res.writeHead(206, {
127
+ "Content-Type": file.mimeType || "application/octet-stream",
128
+ "Content-Range": `bytes ${start}-${end}/${fileSize}`,
129
+ "Content-Length": chunkLength,
130
+ "Accept-Ranges": "bytes"
131
+ });
132
+ if (req.method === "HEAD") {
133
+ res.end();
134
+ } else {
135
+ stream.pipe(res);
136
+ }
137
+ } else {
138
+ const stream = await drive2.createReadStream(virtualPath);
139
+ res.writeHead(200, {
140
+ "Content-Type": file.mimeType || "application/octet-stream",
141
+ "Content-Length": file.size || void 0,
142
+ "Accept-Ranges": "bytes"
143
+ });
144
+ if (req.method === "HEAD") {
145
+ res.end();
146
+ } else {
147
+ stream.pipe(res);
148
+ }
149
+ }
150
+ } catch (e) {
151
+ res.writeHead(404, { "Content-Type": "text/plain" });
152
+ res.end("File Not Found");
153
+ }
154
+ return;
155
+ }
156
+ case "PUT": {
157
+ const remoteDir = import_node_path6.default.dirname(virtualPath);
158
+ await drive2.mkdirp(remoteDir);
159
+ let existed = false;
160
+ try {
161
+ const existingFile = await drive2.getFile(virtualPath);
162
+ if (existingFile && existingFile.id) {
163
+ existed = true;
164
+ }
165
+ } catch {
166
+ existed = false;
167
+ }
168
+ try {
169
+ const uploadStream = await drive2.createWriteStream(virtualPath, {
170
+ overwrite: true
171
+ });
172
+ req.pipe(uploadStream);
173
+ await uploadStream.done;
174
+ res.writeHead(existed ? 204 : 201, { "Content-Type": "text/plain" });
175
+ res.end(existed ? "" : "Created");
176
+ } catch (err) {
177
+ res.writeHead(500, { "Content-Type": "text/plain" });
178
+ res.end(err.message || "Upload failed");
179
+ }
180
+ return;
181
+ }
182
+ case "MKCOL": {
183
+ try {
184
+ await drive2.mkdirp(virtualPath);
185
+ res.writeHead(201, { "Content-Type": "text/plain" });
186
+ res.end("Collection Created");
187
+ } catch (err) {
188
+ res.writeHead(500, { "Content-Type": "text/plain" });
189
+ res.end(err.message);
190
+ }
191
+ return;
192
+ }
193
+ case "DELETE": {
194
+ try {
195
+ await drive2.delete(virtualPath, true);
196
+ res.writeHead(204);
197
+ res.end();
198
+ } catch (err) {
199
+ res.writeHead(404, { "Content-Type": "text/plain" });
200
+ res.end("Not Found");
201
+ }
202
+ return;
203
+ }
204
+ case "MOVE": {
205
+ const destination = req.headers["destination"];
206
+ if (!destination || typeof destination !== "string") {
207
+ res.writeHead(400, { "Content-Type": "text/plain" });
208
+ res.end("Destination header missing");
209
+ return;
210
+ }
211
+ try {
212
+ const file = await drive2.getFile(virtualPath);
213
+ if (!file?.id) {
214
+ res.writeHead(404, { "Content-Type": "text/plain" });
215
+ res.end("Source file not found");
216
+ return;
217
+ }
218
+ const destUrl = import_node_url.default.parse(destination);
219
+ const destPath = decodeURIComponent(destUrl.pathname || "");
220
+ const newName = import_node_path6.default.basename(destPath);
221
+ const newParentDir = import_node_path6.default.dirname(destPath);
222
+ const newParentFolderId = await drive2.mkdirp(newParentDir);
223
+ const currentParentDir = import_node_path6.default.dirname(virtualPath);
224
+ if (newParentDir !== currentParentDir) {
225
+ await drive2.move(file.id, newParentFolderId);
226
+ }
227
+ if (newName !== import_node_path6.default.basename(virtualPath)) {
228
+ await drive2.rename(file.id, newName);
229
+ }
230
+ res.writeHead(201);
231
+ res.end("Moved");
232
+ } catch (err) {
233
+ res.writeHead(500, { "Content-Type": "text/plain" });
234
+ res.end(err.message);
235
+ }
236
+ return;
237
+ }
238
+ case "COPY": {
239
+ const destination = req.headers["destination"];
240
+ if (!destination || typeof destination !== "string") {
241
+ res.writeHead(400, { "Content-Type": "text/plain" });
242
+ res.end("Destination header missing");
243
+ return;
244
+ }
245
+ try {
246
+ const file = await drive2.getFile(virtualPath);
247
+ if (!file?.id) {
248
+ res.writeHead(404, { "Content-Type": "text/plain" });
249
+ res.end("Source file not found");
250
+ return;
251
+ }
252
+ const destUrl = import_node_url.default.parse(destination);
253
+ const destPath = decodeURIComponent(destUrl.pathname || "");
254
+ const newName = import_node_path6.default.basename(destPath);
255
+ const newParentDir = import_node_path6.default.dirname(destPath);
256
+ const newParentFolderId = await drive2.mkdirp(newParentDir);
257
+ await drive2.copy(file.id, { parent: newParentFolderId, name: newName });
258
+ res.writeHead(201);
259
+ res.end("Copied");
260
+ } catch (err) {
261
+ res.writeHead(500, { "Content-Type": "text/plain" });
262
+ res.end(err.message);
263
+ }
264
+ return;
265
+ }
266
+ default: {
267
+ res.writeHead(501, { "Content-Type": "text/plain" });
268
+ res.end("Method Not Implemented");
269
+ }
270
+ }
271
+ } catch (globalErr) {
272
+ res.writeHead(500, { "Content-Type": "text/plain" });
273
+ res.end(`Internal Server Error: ${globalErr.message}`);
274
+ }
275
+ });
276
+ return new Promise((resolve) => {
277
+ server.listen(port, host, () => {
278
+ const serverUrl = `http://${host}:${port}`;
279
+ resolve({
280
+ server,
281
+ url: serverUrl,
282
+ close: () => new Promise((resClose) => server.close(() => resClose()))
283
+ });
284
+ });
285
+ });
286
+ }
287
+ async function handlePropfind(drive2, virtualPath, depth) {
288
+ const responses = [];
289
+ let isFolder = false;
290
+ let selfItem = null;
291
+ if (virtualPath === "/" || virtualPath === "") {
292
+ isFolder = true;
293
+ responses.push(renderWebDAVResponse("/", true, 0, (/* @__PURE__ */ new Date()).toISOString()));
294
+ } else {
295
+ try {
296
+ selfItem = await drive2.getFile(virtualPath);
297
+ isFolder = selfItem.mimeType === "application/vnd.google-apps.folder";
298
+ responses.push(
299
+ renderWebDAVResponse(
300
+ virtualPath,
301
+ isFolder,
302
+ selfItem.size ? parseInt(selfItem.size, 10) : 0,
303
+ selfItem.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
304
+ )
305
+ );
306
+ } catch {
307
+ return `<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:"></D:multistatus>`;
308
+ }
309
+ }
310
+ if (isFolder && depth !== "0") {
311
+ try {
312
+ const children = await drive2.ls(virtualPath);
313
+ for (const child of children) {
314
+ const childIsFolder = child.mimeType === "application/vnd.google-apps.folder";
315
+ const childPath = virtualPath === "/" ? `/${child.name}` : `${virtualPath}/${child.name}`;
316
+ responses.push(
317
+ renderWebDAVResponse(
318
+ childPath,
319
+ childIsFolder,
320
+ child.size ? parseInt(child.size, 10) : 0,
321
+ child.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
322
+ )
323
+ );
324
+ }
325
+ } catch {
326
+ }
327
+ }
328
+ return `<?xml version="1.0" encoding="utf-8"?>
329
+ <D:multistatus xmlns:D="DAV:">
330
+ ${responses.join("\n")}
331
+ </D:multistatus>`;
332
+ }
333
+ function renderWebDAVResponse(href, isDir, size, modifiedTime) {
334
+ const encodedHref = encodeURI(href);
335
+ const displayName = escapeXml(import_node_path6.default.basename(href) || "root");
336
+ const resourceType = isDir ? "<D:collection/>" : "";
337
+ const dateFormatted = new Date(modifiedTime).toUTCString();
338
+ return ` <D:response>
339
+ <D:href>${encodedHref}</D:href>
340
+ <D:propstat>
341
+ <D:prop>
342
+ <D:displayname>${displayName}</D:displayname>
343
+ <D:resourcetype>${resourceType}</D:resourcetype>
344
+ <D:getcontentlength>${isDir ? "0" : size}</D:getcontentlength>
345
+ <D:getlastmodified>${dateFormatted}</D:getlastmodified>
346
+ <D:status>HTTP/1.1 200 OK</D:status>
347
+ </D:prop>
348
+ <D:status>HTTP/1.1 200 OK</D:status>
349
+ </D:propstat>
350
+ </D:response>`;
351
+ }
352
+ var import_node_http2, import_node_url, import_node_path6;
353
+ var init_webdav = __esm({
354
+ "src/server/webdav.ts"() {
355
+ "use strict";
356
+ init_cjs_shims();
357
+ import_node_http2 = __toESM(require("http"), 1);
358
+ import_node_url = __toESM(require("url"), 1);
359
+ import_node_path6 = __toESM(require("path"), 1);
360
+ }
361
+ });
362
+
30
363
  // src/index.ts
31
364
  var index_exports = {};
32
365
  __export(index_exports, {
@@ -49,14 +382,19 @@ __export(index_exports, {
49
382
  GOOGLE_WORKSPACE_MIME_TYPES: () => GOOGLE_WORKSPACE_MIME_TYPES,
50
383
  MIN_CHUNK_SIZE: () => MIN_CHUNK_SIZE,
51
384
  MULTIPART_THRESHOLD: () => MULTIPART_THRESHOLD,
385
+ MemoryMetadataCache: () => MemoryMetadataCache,
52
386
  PathResolver: () => PathResolver,
53
387
  PluginManager: () => PluginManager,
54
388
  ResumableUploader: () => ResumableUploader,
55
389
  SmartSyncEngine: () => SmartSyncEngine,
390
+ SqliteMetadataCache: () => SqliteMetadataCache,
56
391
  StorageCleaner: () => StorageCleaner,
57
392
  calculateFileMd5: () => calculateFileMd5,
393
+ createAutoNamePlugin: () => createAutoNamePlugin,
58
394
  createDrive: () => createDrive,
395
+ createWebhookPlugin: () => createWebhookPlugin,
59
396
  default: () => index_default,
397
+ escapeXml: () => escapeXml,
60
398
  formatBytes: () => formatBytes,
61
399
  formatDuration: () => formatDuration,
62
400
  formatSpeed: () => formatSpeed,
@@ -68,21 +406,26 @@ __export(index_exports, {
68
406
  lookupMimeType: () => lookupMimeType,
69
407
  renderFileRow: () => renderFileRow,
70
408
  runInteractiveExplorer: () => runInteractiveExplorer,
409
+ startWebDAVServer: () => startWebDAVServer,
71
410
  terminalLink: () => terminalLink,
72
411
  withRetry: () => withRetry
73
412
  });
74
413
  module.exports = __toCommonJS(index_exports);
414
+ init_cjs_shims();
75
415
 
76
416
  // src/core/client.ts
77
- var import_node_fs5 = __toESM(require("fs"), 1);
78
- var import_node_path4 = __toESM(require("path"), 1);
417
+ init_cjs_shims();
418
+ var import_node_fs6 = __toESM(require("fs"), 1);
419
+ var import_node_path7 = __toESM(require("path"), 1);
79
420
  var import_drive3 = require("@googleapis/drive");
80
421
 
81
422
  // src/auth/authenticator.ts
423
+ init_cjs_shims();
82
424
  var import_node_fs = __toESM(require("fs"), 1);
83
425
  var import_drive = require("@googleapis/drive");
84
426
 
85
427
  // src/errors.ts
428
+ init_cjs_shims();
86
429
  var DriveKitError = class extends Error {
87
430
  code;
88
431
  originalError;
@@ -223,7 +566,11 @@ var DriveAuthenticator = class {
223
566
  }
224
567
  };
225
568
 
569
+ // src/core/path-resolver.ts
570
+ init_cjs_shims();
571
+
226
572
  // src/utils/mime.ts
573
+ init_cjs_shims();
227
574
  var import_mime_types = __toESM(require("mime-types"), 1);
228
575
  var GOOGLE_WORKSPACE_MIME_TYPES = {
229
576
  DOCUMENT: "application/vnd.google-apps.document",
@@ -267,6 +614,7 @@ function isGoogleWorkspaceDoc(mimeType) {
267
614
  }
268
615
 
269
616
  // src/utils/retry.ts
617
+ init_cjs_shims();
270
618
  var DEFAULT_RETRYABLE_STATUSES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
271
619
  function isRetryableError(error) {
272
620
  if (!error) return false;
@@ -323,11 +671,13 @@ var PathResolver = class {
323
671
  cache = /* @__PURE__ */ new Map();
324
672
  cacheTTL;
325
673
  enableCache;
674
+ metadataCache;
326
675
  constructor(drive2, rootFolderId = "root", options) {
327
676
  this.drive = drive2;
328
677
  this.rootFolderId = rootFolderId;
329
678
  this.enableCache = options?.enableCache ?? true;
330
679
  this.cacheTTL = options?.cacheTTL ?? 5 * 60 * 1e3;
680
+ this.metadataCache = options?.metadataCache;
331
681
  }
332
682
  /**
333
683
  * Normalizes a virtual path (e.g. "///Backups//2026/" -> "/Backups/2026")
@@ -342,21 +692,31 @@ var PathResolver = class {
342
692
  /**
343
693
  * Gets cache key for a path
344
694
  */
345
- getCacheKey(path5) {
346
- return `${this.rootFolderId}:${this.normalizePath(path5)}`;
695
+ getCacheKey(path8) {
696
+ return `${this.rootFolderId}:${this.normalizePath(path8)}`;
347
697
  }
348
698
  /**
349
699
  * Clears the path cache
350
700
  */
351
701
  clearCache() {
352
702
  this.cache.clear();
703
+ if (this.metadataCache) {
704
+ this.metadataCache.clear();
705
+ }
353
706
  }
354
707
  /**
355
708
  * Invalidate a single path from cache
356
709
  */
357
- invalidatePath(path5) {
358
- const key = this.getCacheKey(path5);
710
+ invalidatePath(path8) {
711
+ const norm = this.normalizePath(path8);
712
+ const key = this.getCacheKey(norm);
359
713
  this.cache.delete(key);
714
+ if (this.metadataCache) {
715
+ const item = this.metadataCache.getByPath(norm);
716
+ if (item) {
717
+ this.metadataCache.deleteFile(item.id);
718
+ }
719
+ }
360
720
  }
361
721
  /**
362
722
  * Resolves a path to a Google Drive item (file or folder).
@@ -372,6 +732,17 @@ var PathResolver = class {
372
732
  mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER
373
733
  };
374
734
  }
735
+ if (this.metadataCache) {
736
+ const persistentCached = this.metadataCache.getByPath(norm);
737
+ if (persistentCached) {
738
+ return {
739
+ id: persistentCached.id,
740
+ name: persistentCached.name,
741
+ isFolder: persistentCached.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
742
+ mimeType: persistentCached.mimeType
743
+ };
744
+ }
745
+ }
375
746
  if (this.enableCache) {
376
747
  const cached = this.cache.get(this.getCacheKey(norm));
377
748
  if (cached && cached.expiresAt > Date.now()) {
@@ -390,6 +761,21 @@ var PathResolver = class {
390
761
  const segment = segments[i];
391
762
  const isLast = i === segments.length - 1;
392
763
  currentPath += `/${segment}`;
764
+ if (this.metadataCache) {
765
+ const pCached = this.metadataCache.getByPath(currentPath);
766
+ if (pCached) {
767
+ currentParentId = pCached.id;
768
+ if (isLast) {
769
+ return {
770
+ id: pCached.id,
771
+ name: pCached.name,
772
+ isFolder: pCached.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
773
+ mimeType: pCached.mimeType
774
+ };
775
+ }
776
+ continue;
777
+ }
778
+ }
393
779
  if (this.enableCache) {
394
780
  const cached = this.cache.get(this.getCacheKey(currentPath));
395
781
  if (cached && cached.expiresAt > Date.now()) {
@@ -433,7 +819,18 @@ var PathResolver = class {
433
819
  file = sharedResponse.data.files?.[0];
434
820
  }
435
821
  if (file && file.id) {
822
+ const segmentParentId = currentParentId;
436
823
  currentParentId = file.id;
824
+ if (this.metadataCache) {
825
+ this.metadataCache.upsertFile({
826
+ id: file.id,
827
+ name: file.name || segment,
828
+ mimeType: file.mimeType || "",
829
+ parentId: segmentParentId,
830
+ path: currentPath,
831
+ trashed: false
832
+ });
833
+ }
437
834
  if (this.enableCache) {
438
835
  this.cache.set(this.getCacheKey(currentPath), {
439
836
  id: file.id,
@@ -467,7 +864,18 @@ var PathResolver = class {
467
864
  if (!newFolder.id) {
468
865
  throw new Error(`Failed to create folder "${segment}" under parent "${currentParentId}"`);
469
866
  }
867
+ const segmentParentId = currentParentId;
470
868
  currentParentId = newFolder.id;
869
+ if (this.metadataCache) {
870
+ this.metadataCache.upsertFile({
871
+ id: newFolder.id,
872
+ name: segment,
873
+ mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
874
+ parentId: segmentParentId,
875
+ path: currentPath,
876
+ trashed: false
877
+ });
878
+ }
471
879
  if (this.enableCache) {
472
880
  this.cache.set(this.getCacheKey(currentPath), {
473
881
  id: newFolder.id,
@@ -504,10 +912,12 @@ var PathResolver = class {
504
912
  };
505
913
 
506
914
  // src/core/resumable-uploader.ts
915
+ init_cjs_shims();
507
916
  var import_node_fs2 = __toESM(require("fs"), 1);
508
917
  var import_node_path = __toESM(require("path"), 1);
509
918
 
510
919
  // src/utils/format.ts
920
+ init_cjs_shims();
511
921
  function formatBytes(bytes, decimals = 2) {
512
922
  if (bytes === 0) return "0 B";
513
923
  const k = 1024;
@@ -835,6 +1245,7 @@ var ResumableUploader = class {
835
1245
  };
836
1246
 
837
1247
  // src/core/downloader.ts
1248
+ init_cjs_shims();
838
1249
  var import_node_fs3 = __toESM(require("fs"), 1);
839
1250
  var import_node_path2 = __toESM(require("path"), 1);
840
1251
  var import_promises = require("stream/promises");
@@ -930,9 +1341,28 @@ var Downloader = class {
930
1341
  size: totalBytes
931
1342
  };
932
1343
  }
1344
+ /**
1345
+ * Returns a raw ReadableStream for the file, supporting HTTP Range requests for partial content / streaming.
1346
+ */
1347
+ async createReadStream(fileId, options) {
1348
+ const headers = {};
1349
+ if (options?.start !== void 0 || options?.end !== void 0) {
1350
+ const start = options.start ?? 0;
1351
+ const end = options.end !== void 0 ? options.end : "";
1352
+ headers["Range"] = `bytes=${start}-${end}`;
1353
+ }
1354
+ const res = await withRetry(async () => {
1355
+ return await this.drive.files.get(
1356
+ { fileId, alt: "media", supportsAllDrives: true },
1357
+ { responseType: "stream", headers }
1358
+ );
1359
+ });
1360
+ return res.data;
1361
+ }
933
1362
  };
934
1363
 
935
1364
  // src/core/query-builder.ts
1365
+ init_cjs_shims();
936
1366
  var DriveQueryBuilder = class {
937
1367
  drive;
938
1368
  conditions = [];
@@ -1049,6 +1479,19 @@ var DriveQueryBuilder = class {
1049
1479
  this.conditions.push(`(${condition})`);
1050
1480
  return this;
1051
1481
  }
1482
+ /**
1483
+ * Custom raw query condition (alias for raw)
1484
+ */
1485
+ custom(condition) {
1486
+ return this.raw(condition);
1487
+ }
1488
+ /**
1489
+ * Filter: Exact MD5 checksum match
1490
+ */
1491
+ md5(checksum) {
1492
+ this.conditions.push(`md5Checksum = '${this.escape(checksum)}'`);
1493
+ return this;
1494
+ }
1052
1495
  /**
1053
1496
  * Sort ordering (e.g. 'modifiedTime desc', 'name', 'folder,modifiedTime desc')
1054
1497
  */
@@ -1095,6 +1538,12 @@ var DriveQueryBuilder = class {
1095
1538
  });
1096
1539
  return res.data.files || [];
1097
1540
  }
1541
+ /**
1542
+ * Executes query and returns array of matching files (alias for list)
1543
+ */
1544
+ async execute() {
1545
+ return await this.list();
1546
+ }
1098
1547
  /**
1099
1548
  * Returns the first matching file, or null if not found
1100
1549
  */
@@ -1142,6 +1591,7 @@ var DriveQueryBuilder = class {
1142
1591
  };
1143
1592
 
1144
1593
  // src/core/concurrency-pool.ts
1594
+ init_cjs_shims();
1145
1595
  var ConcurrencyPool = class {
1146
1596
  concurrency;
1147
1597
  running = 0;
@@ -1186,6 +1636,7 @@ var ConcurrencyPool = class {
1186
1636
  };
1187
1637
 
1188
1638
  // src/core/watcher.ts
1639
+ init_cjs_shims();
1189
1640
  var import_node_events = require("events");
1190
1641
  var DriveWatcher = class extends import_node_events.EventEmitter {
1191
1642
  drive;
@@ -1299,6 +1750,7 @@ var DriveWatcher = class extends import_node_events.EventEmitter {
1299
1750
  };
1300
1751
 
1301
1752
  // src/core/storage-cleaner.ts
1753
+ init_cjs_shims();
1302
1754
  var StorageCleaner = class {
1303
1755
  drive;
1304
1756
  constructor(drive2) {
@@ -1395,6 +1847,7 @@ var StorageCleaner = class {
1395
1847
  };
1396
1848
 
1397
1849
  // src/core/smart-sync.ts
1850
+ init_cjs_shims();
1398
1851
  var import_node_fs4 = __toESM(require("fs"), 1);
1399
1852
  var import_node_path3 = __toESM(require("path"), 1);
1400
1853
  var import_node_crypto = __toESM(require("crypto"), 1);
@@ -1520,6 +1973,7 @@ var SmartSyncEngine = class {
1520
1973
  };
1521
1974
 
1522
1975
  // src/auth/browser-login.ts
1976
+ init_cjs_shims();
1523
1977
  var import_node_http = __toESM(require("http"), 1);
1524
1978
  var import_node_child_process = require("child_process");
1525
1979
  var import_drive2 = require("@googleapis/drive");
@@ -1628,6 +2082,7 @@ ${authUrl}
1628
2082
  }
1629
2083
 
1630
2084
  // src/core/resource-refs.ts
2085
+ init_cjs_shims();
1631
2086
  var DriveFileRef = class {
1632
2087
  drive;
1633
2088
  pathOrId;
@@ -1688,6 +2143,22 @@ var DriveFileRef = class {
1688
2143
  async getLink() {
1689
2144
  return await this.drive.getShareableLink(this.pathOrId);
1690
2145
  }
2146
+ /** Returns a ReadableStream for this file, optionally with byte Range requests */
2147
+ async createReadStream(options) {
2148
+ return await this.drive.createReadStream(this.pathOrId, options);
2149
+ }
2150
+ /** Grants access to a specific email with custom role and notification */
2151
+ async grantAccess(options) {
2152
+ return await this.drive.grantAccess(this.pathOrId, options);
2153
+ }
2154
+ /** Revokes access by permission ID or user email */
2155
+ async revokeAccess(permissionIdOrEmail) {
2156
+ return await this.drive.revokeAccess(this.pathOrId, permissionIdOrEmail);
2157
+ }
2158
+ /** Lists all granted permissions on this file */
2159
+ async listPermissions() {
2160
+ return await this.drive.listPermissions(this.pathOrId);
2161
+ }
1691
2162
  };
1692
2163
  var DriveFolderRef = class {
1693
2164
  drive;
@@ -1725,15 +2196,52 @@ var DriveFolderRef = class {
1725
2196
  async watch(options = {}) {
1726
2197
  return await this.drive.watch(this.pathOrId, options);
1727
2198
  }
2199
+ /** Grants access to this entire folder */
2200
+ async grantAccess(options) {
2201
+ return await this.drive.grantAccess(this.pathOrId, options);
2202
+ }
2203
+ /** Creates a writable stream directly into a file inside this folder */
2204
+ async createWriteStream(fileName, options) {
2205
+ const targetPath = this.pathOrId.endsWith("/") ? `${this.pathOrId}${fileName}` : `${this.pathOrId}/${fileName}`;
2206
+ return await this.drive.createWriteStream(targetPath, options);
2207
+ }
1728
2208
  };
1729
2209
 
1730
2210
  // src/core/plugins.ts
2211
+ init_cjs_shims();
2212
+ var import_node_path4 = __toESM(require("path"), 1);
1731
2213
  var PluginManager = class {
1732
2214
  plugins = [];
2215
+ /**
2216
+ * Register a plugin. If a plugin with the same name already exists,
2217
+ * it replaces the old one to avoid duplicate side-effects.
2218
+ */
1733
2219
  use(plugin) {
2220
+ this.plugins = this.plugins.filter((p) => p.name !== plugin.name);
1734
2221
  this.plugins.push(plugin);
1735
2222
  return this;
1736
2223
  }
2224
+ /**
2225
+ * Unregister a plugin by its name.
2226
+ * Returns true if a plugin was found and removed, false otherwise.
2227
+ */
2228
+ unuse(pluginName) {
2229
+ const initialLen = this.plugins.length;
2230
+ this.plugins = this.plugins.filter((p) => p.name !== pluginName);
2231
+ return this.plugins.length < initialLen;
2232
+ }
2233
+ /**
2234
+ * Check if a plugin with given name is currently active
2235
+ */
2236
+ has(pluginName) {
2237
+ return this.plugins.some((p) => p.name === pluginName);
2238
+ }
2239
+ /**
2240
+ * Returns all currently registered plugins
2241
+ */
2242
+ getPlugins() {
2243
+ return [...this.plugins];
2244
+ }
1737
2245
  async runBeforeUpload(options) {
1738
2246
  let current = { ...options };
1739
2247
  for (const plugin of this.plugins) {
@@ -1775,15 +2283,463 @@ var PluginManager = class {
1775
2283
  return current;
1776
2284
  }
1777
2285
  };
2286
+ function createWebhookPlugin(options) {
2287
+ const events = options.events || ["upload"];
2288
+ const timeoutMs = options.timeout ?? 5e3;
2289
+ const maxRetries = options.retries ?? 0;
2290
+ const sendWebhook = async (event, payload) => {
2291
+ let lastError = null;
2292
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
2293
+ let timeoutId;
2294
+ const controller = new AbortController();
2295
+ timeoutId = setTimeout(() => controller.abort(), timeoutMs);
2296
+ try {
2297
+ const res = await fetch(options.url, {
2298
+ method: "POST",
2299
+ headers: { "Content-Type": "application/json", ...options.headers || {} },
2300
+ body: JSON.stringify(payload),
2301
+ signal: controller.signal
2302
+ });
2303
+ clearTimeout(timeoutId);
2304
+ if (!res.ok) {
2305
+ throw new Error(`Webhook returned HTTP ${res.status}: ${res.statusText}`);
2306
+ }
2307
+ return;
2308
+ } catch (err) {
2309
+ clearTimeout(timeoutId);
2310
+ lastError = err;
2311
+ if (attempt === maxRetries) {
2312
+ if (options.onError) {
2313
+ options.onError(lastError instanceof Error ? lastError : new Error(String(lastError)), event);
2314
+ }
2315
+ }
2316
+ }
2317
+ }
2318
+ };
2319
+ return {
2320
+ name: "drivekit-official-webhook",
2321
+ async afterUpload(file) {
2322
+ if (!events.includes("upload")) return;
2323
+ await sendWebhook("upload", {
2324
+ event: "drivekit:upload",
2325
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2326
+ file: {
2327
+ id: file.id,
2328
+ name: file.name,
2329
+ size: file.size,
2330
+ mimeType: file.mimeType
2331
+ }
2332
+ });
2333
+ },
2334
+ async afterDownload(result) {
2335
+ if (!events.includes("download")) return;
2336
+ await sendWebhook("download", {
2337
+ event: "drivekit:download",
2338
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2339
+ file: {
2340
+ name: result.name,
2341
+ size: result.size
2342
+ }
2343
+ });
2344
+ }
2345
+ };
2346
+ }
2347
+ function createAutoNamePlugin(options) {
2348
+ return {
2349
+ name: "drivekit-official-autoname",
2350
+ beforeUpload(opts) {
2351
+ let name = opts.filename;
2352
+ if (!name && typeof opts.source === "string") {
2353
+ name = import_node_path4.default.basename(opts.source);
2354
+ }
2355
+ if (!name) return opts;
2356
+ const ext = import_node_path4.default.extname(name);
2357
+ const base = import_node_path4.default.basename(name, ext);
2358
+ let finalName = base;
2359
+ if (options.prefix) finalName = `${options.prefix}${finalName}`;
2360
+ if (options.appendTimestamp) {
2361
+ finalName = `${finalName}_${Date.now()}`;
2362
+ }
2363
+ if (options.suffix) finalName = `${finalName}${options.suffix}`;
2364
+ finalName = `${finalName}${ext}`;
2365
+ return {
2366
+ ...opts,
2367
+ filename: finalName
2368
+ };
2369
+ }
2370
+ };
2371
+ }
2372
+
2373
+ // src/core/cache.ts
2374
+ init_cjs_shims();
2375
+ var import_node_os = __toESM(require("os"), 1);
2376
+ var import_node_path5 = __toESM(require("path"), 1);
2377
+ var import_node_fs5 = __toESM(require("fs"), 1);
2378
+ var SqliteMetadataCache = class {
2379
+ db = null;
2380
+ dbPath;
2381
+ initialized = false;
2382
+ fallbackMemory;
2383
+ constructor(customPath) {
2384
+ if (customPath) {
2385
+ this.dbPath = customPath;
2386
+ } else {
2387
+ const dir = import_node_path5.default.join(import_node_os.default.homedir(), ".drivekit");
2388
+ if (!import_node_fs5.default.existsSync(dir)) {
2389
+ try {
2390
+ import_node_fs5.default.mkdirSync(dir, { recursive: true });
2391
+ } catch {
2392
+ }
2393
+ }
2394
+ this.dbPath = import_node_path5.default.join(dir, "cache.db");
2395
+ }
2396
+ }
2397
+ init() {
2398
+ if (this.initialized) return;
2399
+ try {
2400
+ const { DatabaseSync } = require("sqlite");
2401
+ if (!DatabaseSync) {
2402
+ throw new Error("DatabaseSync not available");
2403
+ }
2404
+ this.db = new DatabaseSync(this.dbPath);
2405
+ this.db.exec(`
2406
+ PRAGMA journal_mode = WAL;
2407
+ PRAGMA synchronous = NORMAL;
2408
+
2409
+ CREATE TABLE IF NOT EXISTS files (
2410
+ id TEXT PRIMARY KEY,
2411
+ name TEXT NOT NULL,
2412
+ mimeType TEXT,
2413
+ size INTEGER,
2414
+ parentId TEXT,
2415
+ path TEXT,
2416
+ md5Checksum TEXT,
2417
+ trashed INTEGER DEFAULT 0,
2418
+ modifiedTime TEXT,
2419
+ updatedAt INTEGER
2420
+ );
2421
+
2422
+ CREATE TABLE IF NOT EXISTS meta (
2423
+ key TEXT PRIMARY KEY,
2424
+ value TEXT NOT NULL
2425
+ );
2426
+
2427
+ CREATE INDEX IF NOT EXISTS idx_files_path ON files(path);
2428
+ CREATE INDEX IF NOT EXISTS idx_files_parent ON files(parentId);
2429
+ CREATE INDEX IF NOT EXISTS idx_files_md5 ON files(md5Checksum);
2430
+ CREATE INDEX IF NOT EXISTS idx_files_name ON files(name);
2431
+ `);
2432
+ this.initialized = true;
2433
+ } catch (err) {
2434
+ this.fallbackMemory = new MemoryMetadataCache();
2435
+ this.fallbackMemory.init();
2436
+ this.initialized = true;
2437
+ this.db = null;
2438
+ }
2439
+ }
2440
+ getById(id) {
2441
+ if (this.fallbackMemory) return this.fallbackMemory.getById(id);
2442
+ if (!this.initialized || !this.db) return null;
2443
+ const stmt = this.db.prepare("SELECT * FROM files WHERE id = ?");
2444
+ const row = stmt.get(id);
2445
+ return row ? this.mapRow(row) : null;
2446
+ }
2447
+ getByPath(normalizedPath) {
2448
+ if (this.fallbackMemory) return this.fallbackMemory.getByPath(normalizedPath);
2449
+ if (!this.initialized || !this.db) return null;
2450
+ const stmt = this.db.prepare("SELECT * FROM files WHERE path = ? AND trashed = 0 LIMIT 1");
2451
+ const row = stmt.get(normalizedPath);
2452
+ return row ? this.mapRow(row) : null;
2453
+ }
2454
+ getChildren(parentId) {
2455
+ if (this.fallbackMemory) return this.fallbackMemory.getChildren(parentId);
2456
+ if (!this.initialized || !this.db) return [];
2457
+ const stmt = this.db.prepare("SELECT * FROM files WHERE parentId = ? AND trashed = 0 ORDER BY name ASC");
2458
+ const rows = stmt.all(parentId);
2459
+ return rows.map((r) => this.mapRow(r));
2460
+ }
2461
+ findByMd5(md5) {
2462
+ if (this.fallbackMemory) return this.fallbackMemory.findByMd5(md5);
2463
+ if (!this.initialized || !this.db || !md5) return null;
2464
+ const stmt = this.db.prepare("SELECT * FROM files WHERE md5Checksum = ? AND trashed = 0 LIMIT 1");
2465
+ const row = stmt.get(md5.toLowerCase());
2466
+ return row ? this.mapRow(row) : null;
2467
+ }
2468
+ searchByName(query) {
2469
+ if (this.fallbackMemory) return this.fallbackMemory.searchByName(query);
2470
+ if (!this.initialized || !this.db) return [];
2471
+ const stmt = this.db.prepare("SELECT * FROM files WHERE name LIKE ? AND trashed = 0 LIMIT 50");
2472
+ const rows = stmt.all(`%${query}%`);
2473
+ return rows.map((r) => this.mapRow(r));
2474
+ }
2475
+ upsertFile(entry) {
2476
+ if (this.fallbackMemory) {
2477
+ this.fallbackMemory.upsertFile(entry);
2478
+ return;
2479
+ }
2480
+ if (!this.initialized || !this.db) return;
2481
+ const stmt = this.db.prepare(`
2482
+ INSERT INTO files (id, name, mimeType, size, parentId, path, md5Checksum, trashed, modifiedTime, updatedAt)
2483
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2484
+ ON CONFLICT(id) DO UPDATE SET
2485
+ name = excluded.name,
2486
+ mimeType = excluded.mimeType,
2487
+ size = excluded.size,
2488
+ parentId = excluded.parentId,
2489
+ path = COALESCE(excluded.path, files.path),
2490
+ md5Checksum = excluded.md5Checksum,
2491
+ trashed = excluded.trashed,
2492
+ modifiedTime = excluded.modifiedTime,
2493
+ updatedAt = excluded.updatedAt
2494
+ `);
2495
+ stmt.run(
2496
+ entry.id,
2497
+ entry.name,
2498
+ entry.mimeType ?? null,
2499
+ entry.size ?? null,
2500
+ entry.parentId ?? null,
2501
+ entry.path ?? null,
2502
+ entry.md5Checksum ? entry.md5Checksum.toLowerCase() : null,
2503
+ entry.trashed ? 1 : 0,
2504
+ entry.modifiedTime ?? null,
2505
+ entry.updatedAt ?? Date.now()
2506
+ );
2507
+ }
2508
+ upsertFiles(entries) {
2509
+ if (this.fallbackMemory) {
2510
+ this.fallbackMemory.upsertFiles(entries);
2511
+ return;
2512
+ }
2513
+ if (!this.initialized || !this.db || entries.length === 0) return;
2514
+ this.db.exec("BEGIN TRANSACTION;");
2515
+ try {
2516
+ for (const entry of entries) {
2517
+ this.upsertFile(entry);
2518
+ }
2519
+ this.db.exec("COMMIT;");
2520
+ } catch (e) {
2521
+ this.db.exec("ROLLBACK;");
2522
+ throw e;
2523
+ }
2524
+ }
2525
+ deleteFile(id) {
2526
+ if (this.fallbackMemory) {
2527
+ this.fallbackMemory.deleteFile(id);
2528
+ return;
2529
+ }
2530
+ if (!this.initialized || !this.db) return;
2531
+ const stmt = this.db.prepare("DELETE FROM files WHERE id = ?");
2532
+ stmt.run(id);
2533
+ }
2534
+ pruneMissing(activeIds) {
2535
+ if (this.fallbackMemory) {
2536
+ return this.fallbackMemory.pruneMissing(activeIds);
2537
+ }
2538
+ if (!this.initialized || !this.db || activeIds.length === 0) return 0;
2539
+ const idSet = new Set(activeIds);
2540
+ const rows = this.db.prepare("SELECT id FROM files").all();
2541
+ let pruned = 0;
2542
+ this.db.exec("BEGIN TRANSACTION;");
2543
+ try {
2544
+ const deleteStmt = this.db.prepare("DELETE FROM files WHERE id = ?");
2545
+ for (const row of rows) {
2546
+ if (!idSet.has(row.id)) {
2547
+ deleteStmt.run(row.id);
2548
+ pruned++;
2549
+ }
2550
+ }
2551
+ this.db.exec("COMMIT;");
2552
+ return pruned;
2553
+ } catch (e) {
2554
+ this.db.exec("ROLLBACK;");
2555
+ throw e;
2556
+ }
2557
+ }
2558
+ clear() {
2559
+ if (this.fallbackMemory) {
2560
+ this.fallbackMemory.clear();
2561
+ return;
2562
+ }
2563
+ if (!this.initialized || !this.db) return;
2564
+ this.db.exec("DELETE FROM files; DELETE FROM meta;");
2565
+ }
2566
+ getMeta(key) {
2567
+ if (this.fallbackMemory) return this.fallbackMemory.getMeta(key);
2568
+ if (!this.initialized || !this.db) return null;
2569
+ const stmt = this.db.prepare("SELECT value FROM meta WHERE key = ?");
2570
+ const row = stmt.get(key);
2571
+ return row ? row.value : null;
2572
+ }
2573
+ setMeta(key, value) {
2574
+ if (this.fallbackMemory) {
2575
+ this.fallbackMemory.setMeta(key, value);
2576
+ return;
2577
+ }
2578
+ if (!this.initialized || !this.db) return;
2579
+ const stmt = this.db.prepare(`
2580
+ INSERT INTO meta (key, value) VALUES (?, ?)
2581
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value
2582
+ `);
2583
+ stmt.run(key, value);
2584
+ }
2585
+ getStats() {
2586
+ if (this.fallbackMemory) return this.fallbackMemory.getStats();
2587
+ if (!this.initialized || !this.db) {
2588
+ return {
2589
+ fileCount: 0,
2590
+ folderCount: 0,
2591
+ totalSizeBytes: 0,
2592
+ lastSyncTime: null,
2593
+ databasePath: this.dbPath
2594
+ };
2595
+ }
2596
+ const fileCountRow = this.db.prepare(
2597
+ "SELECT COUNT(*) as count FROM files WHERE mimeType != 'application/vnd.google-apps.folder' AND trashed = 0"
2598
+ ).get();
2599
+ const folderCountRow = this.db.prepare(
2600
+ "SELECT COUNT(*) as count FROM files WHERE mimeType = 'application/vnd.google-apps.folder' AND trashed = 0"
2601
+ ).get();
2602
+ const totalSizeRow = this.db.prepare(
2603
+ "SELECT SUM(size) as total FROM files WHERE trashed = 0"
2604
+ ).get();
2605
+ const lastSync = this.getMeta("last_sync_timestamp");
2606
+ return {
2607
+ fileCount: fileCountRow?.count || 0,
2608
+ folderCount: folderCountRow?.count || 0,
2609
+ totalSizeBytes: totalSizeRow?.total || 0,
2610
+ lastSyncTime: lastSync,
2611
+ databasePath: this.dbPath
2612
+ };
2613
+ }
2614
+ close() {
2615
+ if (this.fallbackMemory) {
2616
+ this.fallbackMemory.close();
2617
+ this.fallbackMemory = void 0;
2618
+ }
2619
+ if (this.db) {
2620
+ try {
2621
+ this.db.close();
2622
+ } catch {
2623
+ }
2624
+ this.initialized = false;
2625
+ this.db = null;
2626
+ }
2627
+ }
2628
+ mapRow(row) {
2629
+ return {
2630
+ id: row.id,
2631
+ name: row.name,
2632
+ mimeType: row.mimeType,
2633
+ size: row.size != null ? Number(row.size) : void 0,
2634
+ parentId: row.parentId || void 0,
2635
+ path: row.path || void 0,
2636
+ md5Checksum: row.md5Checksum || void 0,
2637
+ trashed: row.trashed === 1,
2638
+ modifiedTime: row.modifiedTime || void 0,
2639
+ updatedAt: row.updatedAt != null ? Number(row.updatedAt) : void 0
2640
+ };
2641
+ }
2642
+ };
2643
+ var MemoryMetadataCache = class {
2644
+ files = /* @__PURE__ */ new Map();
2645
+ meta = /* @__PURE__ */ new Map();
2646
+ init() {
2647
+ }
2648
+ getById(id) {
2649
+ return this.files.get(id) || null;
2650
+ }
2651
+ getByPath(normalizedPath) {
2652
+ for (const f of this.files.values()) {
2653
+ if (f.path === normalizedPath && !f.trashed) return f;
2654
+ }
2655
+ return null;
2656
+ }
2657
+ getChildren(parentId) {
2658
+ const list = [];
2659
+ for (const f of this.files.values()) {
2660
+ if (f.parentId === parentId && !f.trashed) list.push(f);
2661
+ }
2662
+ return list;
2663
+ }
2664
+ findByMd5(md5) {
2665
+ const target = md5.toLowerCase();
2666
+ for (const f of this.files.values()) {
2667
+ if (f.md5Checksum?.toLowerCase() === target && !f.trashed) return f;
2668
+ }
2669
+ return null;
2670
+ }
2671
+ searchByName(query) {
2672
+ const q = query.toLowerCase();
2673
+ const list = [];
2674
+ for (const f of this.files.values()) {
2675
+ if (f.name.toLowerCase().includes(q) && !f.trashed) list.push(f);
2676
+ }
2677
+ return list;
2678
+ }
2679
+ upsertFile(entry) {
2680
+ this.files.set(entry.id, { ...entry, updatedAt: Date.now() });
2681
+ }
2682
+ upsertFiles(entries) {
2683
+ for (const e of entries) this.upsertFile(e);
2684
+ }
2685
+ deleteFile(id) {
2686
+ this.files.delete(id);
2687
+ }
2688
+ pruneMissing(activeIds) {
2689
+ const idSet = new Set(activeIds);
2690
+ let pruned = 0;
2691
+ for (const id of Array.from(this.files.keys())) {
2692
+ if (!idSet.has(id)) {
2693
+ this.files.delete(id);
2694
+ pruned++;
2695
+ }
2696
+ }
2697
+ return pruned;
2698
+ }
2699
+ clear() {
2700
+ this.files.clear();
2701
+ this.meta.clear();
2702
+ }
2703
+ getMeta(key) {
2704
+ return this.meta.get(key) || null;
2705
+ }
2706
+ setMeta(key, value) {
2707
+ this.meta.set(key, value);
2708
+ }
2709
+ getStats() {
2710
+ let fileCount = 0;
2711
+ let folderCount = 0;
2712
+ let totalSizeBytes = 0;
2713
+ for (const f of this.files.values()) {
2714
+ if (f.trashed) continue;
2715
+ if (f.mimeType === "application/vnd.google-apps.folder") folderCount++;
2716
+ else {
2717
+ fileCount++;
2718
+ totalSizeBytes += f.size || 0;
2719
+ }
2720
+ }
2721
+ return {
2722
+ fileCount,
2723
+ folderCount,
2724
+ totalSizeBytes,
2725
+ lastSyncTime: this.meta.get("last_sync_timestamp") || null,
2726
+ databasePath: ":memory:"
2727
+ };
2728
+ }
2729
+ close() {
2730
+ this.clear();
2731
+ }
2732
+ };
1778
2733
 
1779
2734
  // src/core/client.ts
1780
- var DriveKit = class {
2735
+ var DriveKit = class _DriveKit {
1781
2736
  options;
1782
2737
  authenticator;
1783
2738
  driveClient = null;
1784
2739
  pathResolverInstance = null;
1785
2740
  uploaderInstance = null;
1786
2741
  downloaderInstance = null;
2742
+ metadataCacheInstance = null;
1787
2743
  rootFolderId;
1788
2744
  pluginManager = new PluginManager();
1789
2745
  constructor(options = {}) {
@@ -1817,9 +2773,14 @@ var DriveKit = class {
1817
2773
  if (!this.driveClient) {
1818
2774
  const auth = await this.authenticator.getAuthClient();
1819
2775
  this.driveClient = (0, import_drive3.drive)({ version: "v3", auth });
2776
+ if (this.options.enablePersistentCache !== false) {
2777
+ this.metadataCacheInstance = new SqliteMetadataCache(this.options.cacheDatabasePath);
2778
+ this.metadataCacheInstance.init();
2779
+ }
1820
2780
  this.pathResolverInstance = new PathResolver(this.driveClient, this.rootFolderId, {
1821
2781
  enableCache: this.options.enablePathCache ?? true,
1822
- cacheTTL: this.options.pathCacheTTL
2782
+ cacheTTL: this.options.pathCacheTTL,
2783
+ metadataCache: this.metadataCacheInstance || void 0
1823
2784
  });
1824
2785
  this.uploaderInstance = new ResumableUploader(
1825
2786
  this.driveClient,
@@ -1901,8 +2862,9 @@ var DriveKit = class {
1901
2862
  * Lists contents of a folder (by folder ID or path)
1902
2863
  */
1903
2864
  async ls(folderIdOrPath = "/") {
1904
- if (folderIdOrPath === "/" || folderIdOrPath === "root") {
1905
- return await this.query().raw("'root' in parents or sharedWithMe = true").notTrashed().orderBy("folder,name").list();
2865
+ if (folderIdOrPath === "/" || folderIdOrPath === "root" || folderIdOrPath === this.rootFolderId) {
2866
+ const parentFilter = this.rootFolderId === "root" ? "'root' in parents or sharedWithMe = true" : `'${this.rootFolderId}' in parents`;
2867
+ return await this.query().raw(parentFilter).notTrashed().orderBy("folder,name").list();
1906
2868
  }
1907
2869
  const folderId = await this.resolveId(folderIdOrPath);
1908
2870
  return await this.query().inFolder(folderId).notTrashed().orderBy("folder,name").list();
@@ -1924,16 +2886,71 @@ var DriveKit = class {
1924
2886
  if (parentId && parentId.startsWith("/")) {
1925
2887
  parentId = await this.mkdirp(parentId);
1926
2888
  }
1927
- if (opts.overwrite && opts.name && parentId) {
1928
- const existing = await this.query().inFolder(parentId).nameEquals(opts.name).notTrashed().first();
2889
+ const targetName = opts.name || opts.filename;
2890
+ if (opts.overwrite && targetName && parentId) {
2891
+ const existing = await this.query().inFolder(parentId).nameEquals(targetName).notTrashed().first();
1929
2892
  if (existing?.id) {
1930
2893
  await this.delete(existing.id, true);
1931
2894
  }
1932
2895
  }
2896
+ if (opts.deduplicate && typeof opts.source === "string" && import_node_fs6.default.existsSync(opts.source)) {
2897
+ const localMd5 = await calculateFileMd5(opts.source);
2898
+ let existingId;
2899
+ if (this.metadataCacheInstance) {
2900
+ const cached = this.metadataCacheInstance.findByMd5(localMd5);
2901
+ if (cached) existingId = cached.id;
2902
+ }
2903
+ if (!existingId) {
2904
+ const found = await this.query().md5(localMd5).notTrashed().first();
2905
+ if (found?.id) {
2906
+ existingId = found.id;
2907
+ }
2908
+ }
2909
+ if (existingId) {
2910
+ const fileName = targetName || import_node_path7.default.basename(opts.source);
2911
+ const raw = await this.getRawClient();
2912
+ const copyRes = await withRetry(async () => {
2913
+ return await raw.files.copy({
2914
+ fileId: existingId,
2915
+ requestBody: {
2916
+ name: fileName,
2917
+ parents: parentId ? [parentId] : void 0,
2918
+ description: opts.description
2919
+ },
2920
+ fields: "id, name, mimeType, size, modifiedTime, md5Checksum",
2921
+ supportsAllDrives: true
2922
+ });
2923
+ });
2924
+ const file = copyRes.data;
2925
+ if (this.metadataCacheInstance && file.id) {
2926
+ this.metadataCacheInstance.upsertFile({
2927
+ id: file.id,
2928
+ name: file.name || fileName,
2929
+ mimeType: file.mimeType || "",
2930
+ size: file.size ? parseInt(file.size, 10) : void 0,
2931
+ parentId,
2932
+ md5Checksum: localMd5,
2933
+ trashed: false
2934
+ });
2935
+ }
2936
+ return await this.pluginManager.runAfterUpload(file);
2937
+ }
2938
+ }
1933
2939
  const uploaded = await uploader.upload({
1934
2940
  ...opts,
2941
+ name: targetName,
1935
2942
  parent: parentId
1936
2943
  });
2944
+ if (this.metadataCacheInstance && uploaded.id) {
2945
+ this.metadataCacheInstance.upsertFile({
2946
+ id: uploaded.id,
2947
+ name: uploaded.name || targetName || "untitled",
2948
+ mimeType: uploaded.mimeType || "",
2949
+ size: uploaded.size ? parseInt(uploaded.size, 10) : void 0,
2950
+ parentId,
2951
+ trashed: false
2952
+ });
2953
+ }
1937
2954
  return await this.pluginManager.runAfterUpload(uploaded);
1938
2955
  }
1939
2956
  /**
@@ -2174,16 +3191,16 @@ var DriveKit = class {
2174
3191
  durationMs: 0
2175
3192
  };
2176
3193
  const collectFiles = async (dir, base) => {
2177
- const entries = await import_node_fs5.default.promises.readdir(dir, { withFileTypes: true });
3194
+ const entries = await import_node_fs6.default.promises.readdir(dir, { withFileTypes: true });
2178
3195
  const files = [];
2179
3196
  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);
3197
+ const fullPath = import_node_path7.default.join(dir, entry.name);
3198
+ const relPath = import_node_path7.default.join(base, entry.name);
2182
3199
  if (entry.isDirectory()) {
2183
3200
  const sub = await collectFiles(fullPath, relPath);
2184
3201
  files.push(...sub);
2185
3202
  } else if (entry.isFile()) {
2186
- const stat = await import_node_fs5.default.promises.stat(fullPath);
3203
+ const stat = await import_node_fs6.default.promises.stat(fullPath);
2187
3204
  files.push({ fullPath, relPath, size: stat.size });
2188
3205
  }
2189
3206
  }
@@ -2196,11 +3213,11 @@ var DriveKit = class {
2196
3213
  if (remoteDirCache.has(relDir)) {
2197
3214
  return remoteDirCache.get(relDir);
2198
3215
  }
2199
- const parts = relDir.split(import_node_path4.default.sep).filter(Boolean);
3216
+ const parts = relDir.split(import_node_path7.default.sep).filter(Boolean);
2200
3217
  let currentParent = targetFolderId;
2201
3218
  let currentRel = "";
2202
3219
  for (const part of parts) {
2203
- currentRel = currentRel ? import_node_path4.default.join(currentRel, part) : part;
3220
+ currentRel = currentRel ? import_node_path7.default.join(currentRel, part) : part;
2204
3221
  if (remoteDirCache.has(currentRel)) {
2205
3222
  currentParent = remoteDirCache.get(currentRel);
2206
3223
  continue;
@@ -2229,8 +3246,8 @@ var DriveKit = class {
2229
3246
  };
2230
3247
  await pool.map(allFiles, async (fileItem) => {
2231
3248
  try {
2232
- const relDir = import_node_path4.default.dirname(fileItem.relPath);
2233
- const fileName = import_node_path4.default.basename(fileItem.relPath);
3249
+ const relDir = import_node_path7.default.dirname(fileItem.relPath);
3250
+ const fileName = import_node_path7.default.basename(fileItem.relPath);
2234
3251
  const parentFolderId = await ensureRemoteSubdir(relDir === "." ? "" : relDir);
2235
3252
  if (options.onFileStart) {
2236
3253
  options.onFileStart(fileItem.fullPath, fileItem.relPath);
@@ -2348,6 +3365,256 @@ var DriveKit = class {
2348
3365
  const engine = new SmartSyncEngine(this.driveClient);
2349
3366
  return await engine.pullFolder(folderId, localDestinationDir, options);
2350
3367
  }
3368
+ // ==========================================
3369
+ // STREAMS & RANGE REQUESTS
3370
+ // ==========================================
3371
+ /**
3372
+ * Creates a readable stream for a file, supporting partial range requests
3373
+ */
3374
+ async createReadStream(pathOrId, options) {
3375
+ const fileId = await this.resolveId(pathOrId);
3376
+ const downloader = await this.getDownloader();
3377
+ return await downloader.createReadStream(fileId, options);
3378
+ }
3379
+ /**
3380
+ * Creates a writable stream directly into Google Drive
3381
+ */
3382
+ async createWriteStream(remotePath, options = {}) {
3383
+ await this.init();
3384
+ const { PassThrough } = await import("stream");
3385
+ const passThrough = new PassThrough();
3386
+ let resolveDone;
3387
+ let rejectDone;
3388
+ const donePromise = new Promise((resolve, reject) => {
3389
+ resolveDone = resolve;
3390
+ rejectDone = reject;
3391
+ });
3392
+ passThrough.done = donePromise;
3393
+ const remoteDir = import_node_path7.default.dirname(remotePath);
3394
+ const fileName = options.name || options.filename || import_node_path7.default.basename(remotePath);
3395
+ const targetParentId = remoteDir === "." || remoteDir === "/" ? this.rootFolderId : await this.mkdirp(remoteDir);
3396
+ const mimeType = options.mimeType || "application/octet-stream";
3397
+ const raw = this.driveClient;
3398
+ raw.files.create({
3399
+ requestBody: {
3400
+ name: fileName,
3401
+ parents: [targetParentId],
3402
+ description: options.description
3403
+ },
3404
+ media: {
3405
+ mimeType,
3406
+ body: passThrough
3407
+ },
3408
+ fields: "id, name, mimeType, size, md5Checksum",
3409
+ supportsAllDrives: true
3410
+ }).then((res) => {
3411
+ const file = res.data;
3412
+ if (file.id && this.metadataCacheInstance) {
3413
+ this.metadataCacheInstance.upsertFile({
3414
+ id: file.id,
3415
+ name: fileName,
3416
+ mimeType,
3417
+ parentId: targetParentId,
3418
+ path: remotePath,
3419
+ trashed: false
3420
+ });
3421
+ }
3422
+ resolveDone(file);
3423
+ }).catch((err) => {
3424
+ passThrough.destroy(err);
3425
+ rejectDone(err);
3426
+ });
3427
+ return passThrough;
3428
+ }
3429
+ // ==========================================
3430
+ // METADATA CACHE OPERATIONS
3431
+ // ==========================================
3432
+ /**
3433
+ * Returns the active persistent metadata cache instance (SQLite/Memory)
3434
+ */
3435
+ async getMetadataCache() {
3436
+ await this.init();
3437
+ return this.metadataCacheInstance;
3438
+ }
3439
+ /**
3440
+ * Returns cache statistics (total files, folders, size, last sync)
3441
+ */
3442
+ async getCacheStats() {
3443
+ await this.init();
3444
+ return this.metadataCacheInstance ? this.metadataCacheInstance.getStats() : null;
3445
+ }
3446
+ /**
3447
+ * Clears the path and metadata cache
3448
+ */
3449
+ async clearCache() {
3450
+ await this.init();
3451
+ if (this.pathResolverInstance) {
3452
+ this.pathResolverInstance.clearCache();
3453
+ }
3454
+ }
3455
+ /**
3456
+ * Crawls and indexes Google Drive metadata into the local SQLite database for instant 0ms lookups
3457
+ */
3458
+ async syncCache(options) {
3459
+ await this.init();
3460
+ if (!this.metadataCacheInstance) {
3461
+ throw new Error("Persistent cache is disabled on this DriveKit instance");
3462
+ }
3463
+ const client = this.driveClient;
3464
+ let pageToken = void 0;
3465
+ let totalScanned = 0;
3466
+ const rawFiles = [];
3467
+ do {
3468
+ const res = await withRetry(async () => {
3469
+ return await client.files.list({
3470
+ pageSize: 1e3,
3471
+ pageToken,
3472
+ fields: "nextPageToken, files(id, name, mimeType, size, parents, md5Checksum, trashed, modifiedTime)",
3473
+ spaces: "drive",
3474
+ supportsAllDrives: true,
3475
+ includeItemsFromAllDrives: true,
3476
+ q: "trashed = false"
3477
+ });
3478
+ });
3479
+ const files = res.data.files || [];
3480
+ for (const f of files) {
3481
+ if (f.id) rawFiles.push(f);
3482
+ }
3483
+ totalScanned += files.length;
3484
+ options?.onProgress?.(totalScanned);
3485
+ pageToken = res.data.nextPageToken || void 0;
3486
+ } while (pageToken);
3487
+ const fileMap = /* @__PURE__ */ new Map();
3488
+ for (const f of rawFiles) {
3489
+ fileMap.set(f.id, f);
3490
+ }
3491
+ const pathMemo = /* @__PURE__ */ new Map();
3492
+ const rootId = this.rootFolderId;
3493
+ function computePath(id, visited = /* @__PURE__ */ new Set()) {
3494
+ if (pathMemo.has(id)) return pathMemo.get(id);
3495
+ if (visited.has(id)) return "";
3496
+ visited.add(id);
3497
+ const f = fileMap.get(id);
3498
+ if (!f || !f.name) return "";
3499
+ const parentId = f.parents?.[0];
3500
+ if (!parentId || parentId === "root" || parentId === rootId) {
3501
+ const p = `/${f.name}`;
3502
+ pathMemo.set(id, p);
3503
+ return p;
3504
+ }
3505
+ const parentPath = computePath(parentId, visited);
3506
+ const fullPath = parentPath ? `${parentPath}/${f.name}` : `/${f.name}`;
3507
+ pathMemo.set(id, fullPath);
3508
+ return fullPath;
3509
+ }
3510
+ const entries = rawFiles.map((f) => ({
3511
+ id: f.id,
3512
+ name: f.name || "untitled",
3513
+ mimeType: f.mimeType || "",
3514
+ size: f.size ? parseInt(f.size, 10) : void 0,
3515
+ parentId: f.parents?.[0],
3516
+ path: computePath(f.id),
3517
+ md5Checksum: f.md5Checksum || void 0,
3518
+ trashed: !!f.trashed,
3519
+ modifiedTime: f.modifiedTime || void 0
3520
+ }));
3521
+ this.metadataCacheInstance.upsertFiles(entries);
3522
+ this.metadataCacheInstance.pruneMissing(rawFiles.map((f) => f.id));
3523
+ this.metadataCacheInstance.setMeta("last_sync_timestamp", (/* @__PURE__ */ new Date()).toISOString());
3524
+ return this.metadataCacheInstance.getStats();
3525
+ }
3526
+ // ==========================================
3527
+ // SHARED DRIVES & ENTERPRISE PERMISSIONS
3528
+ // ==========================================
3529
+ /**
3530
+ * Lists all Google Workspace Shared Drives accessible by current user or service account
3531
+ */
3532
+ async listSharedDrives(options = {}) {
3533
+ await this.init();
3534
+ const raw = await this.getRawClient();
3535
+ const res = await withRetry(async () => {
3536
+ return await raw.drives.list({
3537
+ pageSize: options.pageSize || 100,
3538
+ fields: "drives(id, name)"
3539
+ });
3540
+ });
3541
+ return (res.data.drives || []).map((d) => ({ id: d.id, name: d.name }));
3542
+ }
3543
+ /**
3544
+ * Creates a scoped DriveKit client locked to a specific Shared Drive
3545
+ */
3546
+ sharedDrive(driveId) {
3547
+ return new _DriveKit({
3548
+ ...this.options,
3549
+ rootFolderId: driveId
3550
+ });
3551
+ }
3552
+ /**
3553
+ * Grants access to a specific email with custom role and notification
3554
+ */
3555
+ async grantAccess(pathOrId, options) {
3556
+ const fileId = await this.resolveId(pathOrId);
3557
+ const raw = await this.getRawClient();
3558
+ const res = await withRetry(async () => {
3559
+ return await raw.permissions.create({
3560
+ fileId,
3561
+ requestBody: {
3562
+ type: "user",
3563
+ role: options.role || "reader",
3564
+ emailAddress: options.email
3565
+ },
3566
+ sendNotificationEmail: options.notify ?? true,
3567
+ emailMessage: options.message,
3568
+ fields: "id, type, role, emailAddress, displayName",
3569
+ supportsAllDrives: true
3570
+ });
3571
+ });
3572
+ return res.data;
3573
+ }
3574
+ /**
3575
+ * Revokes access for a specific permission ID or email address
3576
+ */
3577
+ async revokeAccess(pathOrId, permissionIdOrEmail) {
3578
+ const fileId = await this.resolveId(pathOrId);
3579
+ const raw = await this.getRawClient();
3580
+ let targetId = permissionIdOrEmail;
3581
+ if (permissionIdOrEmail.includes("@")) {
3582
+ const listRes = await this.listPermissions(fileId);
3583
+ const found = listRes.find((p) => p.emailAddress?.toLowerCase() === permissionIdOrEmail.toLowerCase());
3584
+ if (found && found.id) {
3585
+ targetId = found.id;
3586
+ }
3587
+ }
3588
+ await withRetry(async () => {
3589
+ return await raw.permissions.delete({
3590
+ fileId,
3591
+ permissionId: targetId,
3592
+ supportsAllDrives: true
3593
+ });
3594
+ });
3595
+ }
3596
+ /**
3597
+ * Lists all active permissions on a file or folder
3598
+ */
3599
+ async listPermissions(pathOrId) {
3600
+ const fileId = await this.resolveId(pathOrId);
3601
+ const raw = await this.getRawClient();
3602
+ const res = await withRetry(async () => {
3603
+ return await raw.permissions.list({
3604
+ fileId,
3605
+ fields: "permissions(id, type, role, emailAddress, displayName)",
3606
+ supportsAllDrives: true
3607
+ });
3608
+ });
3609
+ return res.data.permissions || [];
3610
+ }
3611
+ /**
3612
+ * Starts an embedded WebDAV server to mount DriveKit directly in macOS Finder or Windows Explorer
3613
+ */
3614
+ async serveWebDAV(options) {
3615
+ const { startWebDAVServer: startWebDAVServer2 } = await Promise.resolve().then(() => (init_webdav(), webdav_exports));
3616
+ return await startWebDAVServer2(this, options);
3617
+ }
2351
3618
  /**
2352
3619
  * Calculates local file MD5 hash for integrity and deduplication checks
2353
3620
  */
@@ -2362,11 +3629,18 @@ var DriveKit = class {
2362
3629
  }
2363
3630
  };
2364
3631
 
3632
+ // src/types.ts
3633
+ init_cjs_shims();
3634
+
3635
+ // src/index.ts
3636
+ init_webdav();
3637
+
2365
3638
  // src/cli/terminal-ui.ts
3639
+ init_cjs_shims();
2366
3640
  var import_node_readline = __toESM(require("readline"), 1);
2367
3641
  var import_chalk = __toESM(require("chalk"), 1);
2368
- function terminalLink(text, url) {
2369
- return `\x1B]8;;${url}\x07${text}\x1B]8;;\x07`;
3642
+ function terminalLink(text, url2) {
3643
+ return `\x1B]8;;${url2}\x07${text}\x1B]8;;\x07`;
2370
3644
  }
2371
3645
  function renderFileRow(item, index) {
2372
3646
  const isDir = item.mimeType === "application/vnd.google-apps.folder";
@@ -2542,13 +3816,18 @@ var index_default = DriveKit;
2542
3816
  GOOGLE_WORKSPACE_MIME_TYPES,
2543
3817
  MIN_CHUNK_SIZE,
2544
3818
  MULTIPART_THRESHOLD,
3819
+ MemoryMetadataCache,
2545
3820
  PathResolver,
2546
3821
  PluginManager,
2547
3822
  ResumableUploader,
2548
3823
  SmartSyncEngine,
3824
+ SqliteMetadataCache,
2549
3825
  StorageCleaner,
2550
3826
  calculateFileMd5,
3827
+ createAutoNamePlugin,
2551
3828
  createDrive,
3829
+ createWebhookPlugin,
3830
+ escapeXml,
2552
3831
  formatBytes,
2553
3832
  formatDuration,
2554
3833
  formatSpeed,
@@ -2560,6 +3839,7 @@ var index_default = DriveKit;
2560
3839
  lookupMimeType,
2561
3840
  renderFileRow,
2562
3841
  runInteractiveExplorer,
3842
+ startWebDAVServer,
2563
3843
  terminalLink,
2564
3844
  withRetry
2565
3845
  });