drivekit 1.1.1 → 1.1.2

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
@@ -29,7 +29,7 @@ __export(webdav_exports, {
29
29
  escapeXml: () => escapeXml,
30
30
  startWebDAVServer: () => startWebDAVServer
31
31
  });
32
- import http2 from "http";
32
+ import http3 from "http";
33
33
  import url from "url";
34
34
  import path7 from "path";
35
35
  function escapeXml(unsafe) {
@@ -39,7 +39,7 @@ async function startWebDAVServer(drive2, options = {}) {
39
39
  const port = options.port || 8080;
40
40
  const host = options.host || "127.0.0.1";
41
41
  await drive2.init();
42
- const server = http2.createServer(async (req, res) => {
42
+ const server = http3.createServer(async (req, res) => {
43
43
  try {
44
44
  if (options.auth?.username && options.auth?.password) {
45
45
  const authHeader = req.headers["authorization"];
@@ -65,6 +65,12 @@ async function startWebDAVServer(drive2, options = {}) {
65
65
  const parsedUrl = url.parse(req.url || "/", true);
66
66
  const decodedPath = decodeURIComponent(parsedUrl.pathname || "/");
67
67
  const virtualPath = decodedPath === "" ? "/" : decodedPath;
68
+ const baseName = path7.basename(virtualPath);
69
+ if (baseName.startsWith("._") || baseName === ".DS_Store" || baseName === ".Trashes" || baseName === ".Spotlight-V100" || baseName === ".fseventsd") {
70
+ res.writeHead(404, { "Content-Type": "text/plain" });
71
+ res.end("Not Found");
72
+ return;
73
+ }
68
74
  switch (req.method) {
69
75
  case "OPTIONS": {
70
76
  res.writeHead(200, {
@@ -79,6 +85,11 @@ async function startWebDAVServer(drive2, options = {}) {
79
85
  case "PROPFIND": {
80
86
  const depth = req.headers["depth"] || "1";
81
87
  const xml = await handlePropfind(drive2, virtualPath, depth);
88
+ if (xml === null) {
89
+ res.writeHead(404, { "Content-Type": "text/plain" });
90
+ res.end("Not Found");
91
+ return;
92
+ }
82
93
  res.writeHead(207, {
83
94
  "Content-Type": "application/xml; charset=utf-8"
84
95
  });
@@ -289,25 +300,38 @@ async function handlePropfind(drive2, virtualPath, depth) {
289
300
  virtualPath,
290
301
  isFolder,
291
302
  selfItem.size ? parseInt(selfItem.size, 10) : 0,
292
- selfItem.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
303
+ selfItem.modifiedTime || (/* @__PURE__ */ new Date()).toISOString(),
304
+ selfItem.mimeType || void 0
293
305
  )
294
306
  );
295
307
  } catch {
296
- return `<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:"></D:multistatus>`;
308
+ return null;
297
309
  }
298
310
  }
299
311
  if (isFolder && depth !== "0") {
300
312
  try {
301
313
  const children = await drive2.ls(virtualPath);
314
+ const seenNames = /* @__PURE__ */ new Map();
302
315
  for (const child of children) {
316
+ let childName = child.name || "untitled";
317
+ if (seenNames.has(childName)) {
318
+ const count = seenNames.get(childName) + 1;
319
+ seenNames.set(childName, count);
320
+ const ext = path7.extname(childName);
321
+ const base = path7.basename(childName, ext);
322
+ childName = `${base} (${count})${ext}`;
323
+ } else {
324
+ seenNames.set(childName, 0);
325
+ }
303
326
  const childIsFolder = child.mimeType === "application/vnd.google-apps.folder";
304
- const childPath = virtualPath === "/" ? `/${child.name}` : `${virtualPath}/${child.name}`;
327
+ const childPath = virtualPath === "/" ? `/${childName}` : `${virtualPath}/${childName}`;
305
328
  responses.push(
306
329
  renderWebDAVResponse(
307
330
  childPath,
308
331
  childIsFolder,
309
332
  child.size ? parseInt(child.size, 10) : 0,
310
- child.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
333
+ child.modifiedTime || (/* @__PURE__ */ new Date()).toISOString(),
334
+ child.mimeType || void 0
311
335
  )
312
336
  );
313
337
  }
@@ -319,11 +343,17 @@ async function handlePropfind(drive2, virtualPath, depth) {
319
343
  ${responses.join("\n")}
320
344
  </D:multistatus>`;
321
345
  }
322
- function renderWebDAVResponse(href, isDir, size, modifiedTime) {
323
- const encodedHref = encodeURI(href);
346
+ function renderWebDAVResponse(href, isDir, size, modifiedTime, mimeType) {
347
+ let cleanHref = href;
348
+ if (isDir && !cleanHref.endsWith("/")) {
349
+ cleanHref += "/";
350
+ }
351
+ const encodedHref = encodeURI(cleanHref);
324
352
  const displayName = escapeXml(path7.basename(href) || "root");
325
353
  const resourceType = isDir ? "<D:collection/>" : "";
326
354
  const dateFormatted = new Date(modifiedTime).toUTCString();
355
+ const contentTypeTag = !isDir && mimeType ? `
356
+ <D:getcontenttype>${escapeXml(mimeType)}</D:getcontenttype>` : "";
327
357
  return ` <D:response>
328
358
  <D:href>${encodedHref}</D:href>
329
359
  <D:propstat>
@@ -331,8 +361,7 @@ function renderWebDAVResponse(href, isDir, size, modifiedTime) {
331
361
  <D:displayname>${displayName}</D:displayname>
332
362
  <D:resourcetype>${resourceType}</D:resourcetype>
333
363
  <D:getcontentlength>${isDir ? "0" : size}</D:getcontentlength>
334
- <D:getlastmodified>${dateFormatted}</D:getlastmodified>
335
- <D:status>HTTP/1.1 200 OK</D:status>
364
+ <D:getlastmodified>${dateFormatted}</D:getlastmodified>${contentTypeTag}
336
365
  </D:prop>
337
366
  <D:status>HTTP/1.1 200 OK</D:status>
338
367
  </D:propstat>
@@ -405,6 +434,39 @@ var DriveUploadError = class extends DriveKitError {
405
434
  }
406
435
  };
407
436
 
437
+ // src/utils/http-agent.ts
438
+ init_esm_shims();
439
+ import https from "https";
440
+ import http from "http";
441
+ var sharedHttpsAgent = null;
442
+ var sharedHttpAgent = null;
443
+ function getOptimizedHttpsAgent(options) {
444
+ if (!sharedHttpsAgent) {
445
+ sharedHttpsAgent = new https.Agent({
446
+ keepAlive: options?.keepAlive ?? true,
447
+ maxSockets: options?.maxSockets ?? 64,
448
+ maxFreeSockets: options?.maxFreeSockets ?? 32,
449
+ keepAliveMsecs: options?.keepAliveMsecs ?? 6e4,
450
+ timeout: options?.timeout ?? 3e4,
451
+ noDelay: true
452
+ });
453
+ }
454
+ return sharedHttpsAgent;
455
+ }
456
+ function getOptimizedHttpAgent(options) {
457
+ if (!sharedHttpAgent) {
458
+ sharedHttpAgent = new http.Agent({
459
+ keepAlive: options?.keepAlive ?? true,
460
+ maxSockets: options?.maxSockets ?? 64,
461
+ maxFreeSockets: options?.maxFreeSockets ?? 32,
462
+ keepAliveMsecs: options?.keepAliveMsecs ?? 6e4,
463
+ timeout: options?.timeout ?? 3e4,
464
+ noDelay: true
465
+ });
466
+ }
467
+ return sharedHttpAgent;
468
+ }
469
+
408
470
  // src/auth/authenticator.ts
409
471
  var DEFAULT_SCOPES = [
410
472
  "https://www.googleapis.com/auth/drive"
@@ -428,44 +490,39 @@ var DriveAuthenticator = class {
428
490
  const oauth2Client = new googleAuth.OAuth2();
429
491
  oauth2Client.setCredentials({ access_token: this.config.accessToken });
430
492
  this.authClient = oauth2Client;
431
- return this.authClient;
432
- }
433
- if (this.config.oauth2Client) {
493
+ } else if (this.config.oauth2Client) {
434
494
  this.authClient = this.config.oauth2Client;
435
- return this.authClient;
436
- }
437
- if (this.config.oauth) {
495
+ } else if (this.config.oauth) {
438
496
  const { clientId, clientSecret, redirectUri = "http://localhost:3000/oauth2callback", refreshToken } = this.config.oauth;
439
497
  const oauth2Client = new googleAuth.OAuth2(clientId, clientSecret, redirectUri);
440
498
  if (refreshToken) {
441
499
  oauth2Client.setCredentials({ refresh_token: refreshToken });
442
500
  }
443
501
  this.authClient = oauth2Client;
444
- return this.authClient;
445
- }
446
- const keyFile = this.config.keyFilePath || process.env.GDRIVE_SERVICE_ACCOUNT_PATH || process.env.GOOGLE_APPLICATION_CREDENTIALS;
447
- if (keyFile) {
448
- if (!fs.existsSync(keyFile)) {
502
+ } else if (this.config.keyFilePath || process.env.GDRIVE_SERVICE_ACCOUNT_PATH || process.env.GOOGLE_APPLICATION_CREDENTIALS) {
503
+ const keyFile = this.config.keyFilePath || process.env.GDRIVE_SERVICE_ACCOUNT_PATH || process.env.GOOGLE_APPLICATION_CREDENTIALS;
504
+ if (keyFile && !fs.existsSync(keyFile)) {
449
505
  throw new DriveAuthError(`Service account file not found at: ${keyFile}`);
450
506
  }
451
- const auth2 = new googleAuth.GoogleAuth({
507
+ const auth = new googleAuth.GoogleAuth({
452
508
  keyFile,
453
509
  scopes
454
510
  });
455
- this.authClient = auth2;
456
- return this.authClient;
457
- }
458
- const creds = this.config.credentials || (process.env.GDRIVE_CREDENTIALS_JSON ? JSON.parse(process.env.GDRIVE_CREDENTIALS_JSON) : null);
459
- if (creds) {
460
- const auth2 = new googleAuth.GoogleAuth({
511
+ this.authClient = auth;
512
+ } else if (this.config.credentials || process.env.GDRIVE_CREDENTIALS_JSON) {
513
+ const creds = this.config.credentials || (process.env.GDRIVE_CREDENTIALS_JSON ? JSON.parse(process.env.GDRIVE_CREDENTIALS_JSON) : null);
514
+ const auth = new googleAuth.GoogleAuth({
461
515
  credentials: creds,
462
516
  scopes
463
517
  });
464
- this.authClient = auth2;
465
- return this.authClient;
518
+ this.authClient = auth;
519
+ } else {
520
+ const auth = new googleAuth.GoogleAuth({ scopes });
521
+ this.authClient = auth;
522
+ }
523
+ if (this.authClient?.transporter?.defaults) {
524
+ this.authClient.transporter.defaults.agent = getOptimizedHttpsAgent();
466
525
  }
467
- const auth = new googleAuth.GoogleAuth({ scopes });
468
- this.authClient = auth;
469
526
  return this.authClient;
470
527
  } catch (err) {
471
528
  if (err instanceof DriveAuthError) throw err;
@@ -604,6 +661,7 @@ var PathResolver = class {
604
661
  drive;
605
662
  rootFolderId;
606
663
  cache = /* @__PURE__ */ new Map();
664
+ inFlightResolves = /* @__PURE__ */ new Map();
607
665
  cacheTTL;
608
666
  enableCache;
609
667
  metadataCache;
@@ -656,6 +714,7 @@ var PathResolver = class {
656
714
  /**
657
715
  * Resolves a path to a Google Drive item (file or folder).
658
716
  * If createIfMissing is true, any missing intermediate directories will be automatically created (like mkdir -p).
717
+ * Incorporates in-flight request coalescing to deduplicate concurrent resolutions of identical paths.
659
718
  */
660
719
  async resolve(virtualPath, options = {}) {
661
720
  const norm = this.normalizePath(virtualPath);
@@ -689,6 +748,20 @@ var PathResolver = class {
689
748
  };
690
749
  }
691
750
  }
751
+ const flightKey = `${this.rootFolderId}:${norm}:${options.createIfMissing ? "create" : "read"}`;
752
+ const inFlight = this.inFlightResolves.get(flightKey);
753
+ if (inFlight) {
754
+ return await inFlight;
755
+ }
756
+ const task = this.doResolve(virtualPath, norm, options);
757
+ this.inFlightResolves.set(flightKey, task);
758
+ try {
759
+ return await task;
760
+ } finally {
761
+ this.inFlightResolves.delete(flightKey);
762
+ }
763
+ }
764
+ async doResolve(virtualPath, norm, options) {
692
765
  const segments = norm.split("/").filter(Boolean);
693
766
  let currentParentId = this.rootFolderId;
694
767
  let currentPath = "";
@@ -740,7 +813,7 @@ var PathResolver = class {
740
813
  });
741
814
  let file = response.data.files?.[0];
742
815
  if (!file && currentParentId === this.rootFolderId) {
743
- const sharedQ = `name = '${escapedName}' and trashed = false`;
816
+ const sharedQ = `name = '${escapedName}' and sharedWithMe = true and trashed = false`;
744
817
  const sharedResponse = await withRetry(async () => {
745
818
  return await this.drive.files.list({
746
819
  q: sharedQ,
@@ -850,6 +923,7 @@ var PathResolver = class {
850
923
  init_esm_shims();
851
924
  import fs2 from "fs";
852
925
  import path2 from "path";
926
+ import { Transform } from "stream";
853
927
 
854
928
  // src/utils/format.ts
855
929
  init_esm_shims();
@@ -914,6 +988,15 @@ var ResumableUploader = class {
914
988
  const totalBytes = stat.size;
915
989
  const fileName = options.name || path2.basename(filePath);
916
990
  const mimeType = options.mimeType || lookupMimeType(filePath);
991
+ if (totalBytes <= MULTIPART_THRESHOLD) {
992
+ const readStream = fs2.createReadStream(filePath, { highWaterMark: 1024 * 1024 });
993
+ const stream = options.onProgress ? this.wrapStreamWithProgress(readStream, totalBytes, options.onProgress) : readStream;
994
+ return await this.directUpload(stream, {
995
+ ...options,
996
+ name: fileName,
997
+ mimeType
998
+ });
999
+ }
917
1000
  return await this.chunkedUpload({
918
1001
  filePath,
919
1002
  totalBytes,
@@ -929,6 +1012,16 @@ var ResumableUploader = class {
929
1012
  const totalBytes = buffer.length;
930
1013
  const fileName = options.name || "untitled";
931
1014
  const mimeType = options.mimeType || "application/octet-stream";
1015
+ if (totalBytes <= MULTIPART_THRESHOLD) {
1016
+ const { Readable } = await import("stream");
1017
+ const baseStream = Readable.from(totalBytes === 0 ? [] : [buffer]);
1018
+ const stream = options.onProgress ? this.wrapStreamWithProgress(baseStream, totalBytes, options.onProgress) : baseStream;
1019
+ return await this.directUpload(stream, {
1020
+ ...options,
1021
+ name: fileName,
1022
+ mimeType
1023
+ });
1024
+ }
932
1025
  return await this.chunkedUploadBuffer({
933
1026
  buffer,
934
1027
  totalBytes,
@@ -949,6 +1042,50 @@ var ResumableUploader = class {
949
1042
  mimeType
950
1043
  });
951
1044
  }
1045
+ /**
1046
+ * Calculates optimal chunk size based on file size for maximum throughput.
1047
+ */
1048
+ computeAdaptiveChunkSize(totalBytes, explicitChunkSize) {
1049
+ if (explicitChunkSize) {
1050
+ return Math.max(MIN_CHUNK_SIZE, Math.floor(explicitChunkSize / MIN_CHUNK_SIZE) * MIN_CHUNK_SIZE);
1051
+ }
1052
+ if (totalBytes > 128 * 1024 * 1024) {
1053
+ return 32 * 1024 * 1024;
1054
+ }
1055
+ if (totalBytes > 32 * 1024 * 1024) {
1056
+ return 16 * 1024 * 1024;
1057
+ }
1058
+ return this.defaultChunkSize;
1059
+ }
1060
+ /**
1061
+ * Attaches real-time progress monitoring to direct stream uploads.
1062
+ */
1063
+ wrapStreamWithProgress(stream, totalBytes, onProgress) {
1064
+ let bytesSent = 0;
1065
+ const startTime = Date.now();
1066
+ const progressTransform = new Transform({
1067
+ transform(chunk, _encoding, callback) {
1068
+ bytesSent += chunk.length;
1069
+ const elapsedSecs = (Date.now() - startTime) / 1e3;
1070
+ const bytesPerSecond = elapsedSecs > 0 ? Math.round(bytesSent / elapsedSecs) : 0;
1071
+ const remainingBytes = Math.max(0, totalBytes - bytesSent);
1072
+ const estimatedTimeRemainingSeconds = bytesPerSecond > 0 ? Math.round(remainingBytes / bytesPerSecond) : 0;
1073
+ const percentage = totalBytes > 0 ? Math.min(100, Math.round(bytesSent / totalBytes * 1e3) / 10) : 100;
1074
+ onProgress({
1075
+ bytesSent,
1076
+ totalBytes,
1077
+ percentage,
1078
+ bytesPerSecond,
1079
+ speedFormatted: formatSpeed(bytesPerSecond),
1080
+ estimatedTimeRemainingSeconds,
1081
+ chunkIndex: 1,
1082
+ totalChunks: 1
1083
+ });
1084
+ callback(null, chunk);
1085
+ }
1086
+ });
1087
+ return stream.pipe(progressTransform);
1088
+ }
952
1089
  /**
953
1090
  * Fast direct upload using googleapis multipart
954
1091
  */
@@ -981,7 +1118,7 @@ var ResumableUploader = class {
981
1118
  */
982
1119
  async chunkedUpload(params) {
983
1120
  const { filePath, totalBytes, fileName, mimeType, options } = params;
984
- const chunkSize = options.chunkSize ? Math.max(MIN_CHUNK_SIZE, Math.floor(options.chunkSize / MIN_CHUNK_SIZE) * MIN_CHUNK_SIZE) : this.defaultChunkSize;
1121
+ const chunkSize = this.computeAdaptiveChunkSize(totalBytes, options.chunkSize);
985
1122
  const sessionUrl = await this.initiateResumableSession({
986
1123
  fileName,
987
1124
  mimeType,
@@ -1046,7 +1183,7 @@ var ResumableUploader = class {
1046
1183
  */
1047
1184
  async chunkedUploadBuffer(params) {
1048
1185
  const { buffer, totalBytes, fileName, mimeType, options } = params;
1049
- const chunkSize = options.chunkSize ? Math.max(MIN_CHUNK_SIZE, Math.floor(options.chunkSize / MIN_CHUNK_SIZE) * MIN_CHUNK_SIZE) : this.defaultChunkSize;
1186
+ const chunkSize = this.computeAdaptiveChunkSize(totalBytes, options.chunkSize);
1050
1187
  const sessionUrl = await this.initiateResumableSession({
1051
1188
  fileName,
1052
1189
  mimeType,
@@ -1125,7 +1262,8 @@ var ResumableUploader = class {
1125
1262
  url: "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&supportsAllDrives=true",
1126
1263
  method: "POST",
1127
1264
  headers,
1128
- data: metadata
1265
+ data: metadata,
1266
+ agent: getOptimizedHttpsAgent()
1129
1267
  });
1130
1268
  });
1131
1269
  const sessionUrl = res.headers?.get ? res.headers.get("location") : res.headers?.location || res.headers?.["location"];
@@ -1151,6 +1289,7 @@ var ResumableUploader = class {
1151
1289
  method: "PUT",
1152
1290
  headers,
1153
1291
  data: buffer,
1292
+ agent: getOptimizedHttpsAgent(),
1154
1293
  validateStatus: (status) => status >= 200 && status < 300 || status === 308
1155
1294
  });
1156
1295
  if (res.status === 200 || res.status === 201) {
@@ -1184,7 +1323,7 @@ init_esm_shims();
1184
1323
  import fs3 from "fs";
1185
1324
  import path3 from "path";
1186
1325
  import { pipeline } from "stream/promises";
1187
- import { Transform } from "stream";
1326
+ import { Transform as Transform2 } from "stream";
1188
1327
  var Downloader = class {
1189
1328
  drive;
1190
1329
  constructor(drive2) {
@@ -1194,17 +1333,22 @@ var Downloader = class {
1194
1333
  * Downloads a file from Google Drive to local destination path or returns a readable stream.
1195
1334
  */
1196
1335
  async download(fileId, options = {}) {
1197
- const metaRes = await withRetry(async () => {
1198
- return await this.drive.files.get({
1199
- fileId,
1200
- fields: "id, name, mimeType, size",
1201
- supportsAllDrives: true
1336
+ let name = options.metadata?.name;
1337
+ let mimeType = options.metadata?.mimeType;
1338
+ let totalBytes = options.metadata?.size;
1339
+ if (!name || !mimeType) {
1340
+ const metaRes = await withRetry(async () => {
1341
+ return await this.drive.files.get({
1342
+ fileId,
1343
+ fields: "id, name, mimeType, size",
1344
+ supportsAllDrives: true
1345
+ });
1202
1346
  });
1203
- });
1204
- const file = metaRes.data;
1205
- const name = file.name || "downloaded-file";
1206
- const mimeType = file.mimeType || "application/octet-stream";
1207
- const totalBytes = file.size ? parseInt(file.size, 10) : void 0;
1347
+ const file = metaRes.data;
1348
+ name = file.name || "downloaded-file";
1349
+ mimeType = file.mimeType || "application/octet-stream";
1350
+ totalBytes = file.size ? parseInt(file.size, 10) : void 0;
1351
+ }
1208
1352
  let downloadStream;
1209
1353
  let finalFileName = name;
1210
1354
  if (isGoogleWorkspaceDoc(mimeType)) {
@@ -1235,7 +1379,7 @@ var Downloader = class {
1235
1379
  }
1236
1380
  let bytesRead = 0;
1237
1381
  const startTime = Date.now();
1238
- const progressTracker = new Transform({
1382
+ const progressTracker = new Transform2({
1239
1383
  transform(chunk, encoding, callback) {
1240
1384
  bytesRead += chunk.length;
1241
1385
  if (options.onProgress) {
@@ -1260,7 +1404,7 @@ var Downloader = class {
1260
1404
  destPath = path3.join(destPath, finalFileName);
1261
1405
  }
1262
1406
  await fs3.promises.mkdir(path3.dirname(destPath), { recursive: true });
1263
- const writeStream = fs3.createWriteStream(destPath);
1407
+ const writeStream = fs3.createWriteStream(destPath, { highWaterMark: 1024 * 1024 });
1264
1408
  await pipeline(monitoredStream, writeStream);
1265
1409
  return {
1266
1410
  filePath: destPath,
@@ -1503,6 +1647,7 @@ var DriveQueryBuilder = class {
1503
1647
  const q = this.toQueryString();
1504
1648
  const orderBy = this.orderClauses.join(", ");
1505
1649
  let pageToken = void 0;
1650
+ const effectiveFields = this.requestedFields.includes("nextPageToken") ? this.requestedFields : `nextPageToken, ${this.requestedFields}`;
1506
1651
  do {
1507
1652
  const res = await withRetry(async () => {
1508
1653
  return await this.drive.files.list({
@@ -1510,7 +1655,7 @@ var DriveQueryBuilder = class {
1510
1655
  orderBy: orderBy || void 0,
1511
1656
  pageSize: this.limitNumber,
1512
1657
  pageToken,
1513
- fields: this.requestedFields,
1658
+ fields: effectiveFields,
1514
1659
  spaces: this.spaces,
1515
1660
  supportsAllDrives: true,
1516
1661
  includeItemsFromAllDrives: true
@@ -1634,7 +1779,7 @@ var DriveWatcher = class extends EventEmitter {
1634
1779
  const res = await withRetry(async () => {
1635
1780
  return await this.drive.changes.list({
1636
1781
  pageToken: nextPageToken,
1637
- fields: "nextPageToken, newStartPageToken, changes(changeType, fileId, removed, time, file(id, name, mimeType, size, modifiedTime, parents, trashed))",
1782
+ fields: "nextPageToken, newStartPageToken, changes(changeType, fileId, removed, time, file(id, name, mimeType, size, createdTime, modifiedTime, parents, trashed))",
1638
1783
  supportsAllDrives: true,
1639
1784
  includeItemsFromAllDrives: true
1640
1785
  });
@@ -1725,16 +1870,24 @@ var StorageCleaner = class {
1725
1870
  async findDuplicates(options = {}) {
1726
1871
  const mode = options.by || "name";
1727
1872
  const maxScan = options.maxScan || 1e3;
1728
- const res = await withRetry(async () => {
1729
- return await this.drive.files.list({
1730
- q: 'trashed = false and mimeType != "application/vnd.google-apps.folder"',
1731
- pageSize: Math.min(1e3, maxScan),
1732
- fields: "files(id, name, size, md5Checksum, modifiedTime)",
1733
- supportsAllDrives: true,
1734
- includeItemsFromAllDrives: true
1873
+ const files = [];
1874
+ let pageToken = void 0;
1875
+ do {
1876
+ const remaining = maxScan - files.length;
1877
+ if (remaining <= 0) break;
1878
+ const res = await withRetry(async () => {
1879
+ return await this.drive.files.list({
1880
+ q: 'trashed = false and mimeType != "application/vnd.google-apps.folder"',
1881
+ pageSize: Math.min(1e3, remaining),
1882
+ pageToken,
1883
+ fields: "nextPageToken, files(id, name, size, md5Checksum, modifiedTime)",
1884
+ supportsAllDrives: true,
1885
+ includeItemsFromAllDrives: true
1886
+ });
1735
1887
  });
1736
- });
1737
- const files = res.data.files || [];
1888
+ files.push(...res.data.files || []);
1889
+ pageToken = res.data.nextPageToken || void 0;
1890
+ } while (pageToken && files.length < maxScan);
1738
1891
  const map = /* @__PURE__ */ new Map();
1739
1892
  for (const f of files) {
1740
1893
  if (!f.id) continue;
@@ -1909,7 +2062,7 @@ var SmartSyncEngine = class {
1909
2062
 
1910
2063
  // src/auth/browser-login.ts
1911
2064
  init_esm_shims();
1912
- import http from "http";
2065
+ import http2 from "http";
1913
2066
  import { exec } from "child_process";
1914
2067
  import { auth as googleAuth2 } from "@googleapis/drive";
1915
2068
  async function loginWithBrowser(options) {
@@ -1927,7 +2080,7 @@ async function loginWithBrowser(options) {
1927
2080
  scope: scopes
1928
2081
  });
1929
2082
  return new Promise((resolve, reject) => {
1930
- const server = http.createServer(async (req, res) => {
2083
+ const server = http2.createServer(async (req, res) => {
1931
2084
  try {
1932
2085
  const reqUrl = new URL(req.url || "/", `http://localhost:${port}`);
1933
2086
  if (reqUrl.pathname === "/oauth2callback") {
@@ -2011,7 +2164,11 @@ ${authUrl}
2011
2164
  });
2012
2165
  });
2013
2166
  server.on("error", (err) => {
2014
- reject(err);
2167
+ if (err.code === "EADDRINUSE") {
2168
+ reject(new Error(`Port ${port} is already in use by another process. Please specify an alternate port with --port <number>.`));
2169
+ } else {
2170
+ reject(err);
2171
+ }
2015
2172
  });
2016
2173
  });
2017
2174
  }
@@ -2283,7 +2440,7 @@ function createAutoNamePlugin(options) {
2283
2440
  return {
2284
2441
  name: "drivekit-official-autoname",
2285
2442
  beforeUpload(opts) {
2286
- let name = opts.filename;
2443
+ let name = opts.name || opts.filename;
2287
2444
  if (!name && typeof opts.source === "string") {
2288
2445
  name = path5.basename(opts.source);
2289
2446
  }
@@ -2299,6 +2456,7 @@ function createAutoNamePlugin(options) {
2299
2456
  finalName = `${finalName}${ext}`;
2300
2457
  return {
2301
2458
  ...opts,
2459
+ name: finalName,
2302
2460
  filename: finalName
2303
2461
  };
2304
2462
  }
@@ -2446,10 +2604,35 @@ var SqliteMetadataCache = class {
2446
2604
  return;
2447
2605
  }
2448
2606
  if (!this.initialized || !this.db || entries.length === 0) return;
2607
+ const stmt = this.db.prepare(`
2608
+ INSERT INTO files (id, name, mimeType, size, parentId, path, md5Checksum, trashed, modifiedTime, updatedAt)
2609
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2610
+ ON CONFLICT(id) DO UPDATE SET
2611
+ name = excluded.name,
2612
+ mimeType = excluded.mimeType,
2613
+ size = excluded.size,
2614
+ parentId = excluded.parentId,
2615
+ path = COALESCE(excluded.path, files.path),
2616
+ md5Checksum = excluded.md5Checksum,
2617
+ trashed = excluded.trashed,
2618
+ modifiedTime = excluded.modifiedTime,
2619
+ updatedAt = excluded.updatedAt
2620
+ `);
2449
2621
  this.db.exec("BEGIN TRANSACTION;");
2450
2622
  try {
2451
2623
  for (const entry of entries) {
2452
- this.upsertFile(entry);
2624
+ stmt.run(
2625
+ entry.id,
2626
+ entry.name,
2627
+ entry.mimeType ?? null,
2628
+ entry.size ?? null,
2629
+ entry.parentId ?? null,
2630
+ entry.path ?? null,
2631
+ entry.md5Checksum ? entry.md5Checksum.toLowerCase() : null,
2632
+ entry.trashed ? 1 : 0,
2633
+ entry.modifiedTime ?? null,
2634
+ entry.updatedAt ?? Date.now()
2635
+ );
2453
2636
  }
2454
2637
  this.db.exec("COMMIT;");
2455
2638
  } catch (e) {
@@ -2689,6 +2872,18 @@ var DriveKit = class _DriveKit {
2689
2872
  this.pluginManager.use(plugin);
2690
2873
  return this;
2691
2874
  }
2875
+ /**
2876
+ * Unregisters a middleware plugin by name
2877
+ */
2878
+ unuse(pluginName) {
2879
+ return this.pluginManager.unuse(pluginName);
2880
+ }
2881
+ /**
2882
+ * Access the underlying plugin manager instance
2883
+ */
2884
+ get plugins() {
2885
+ return this.pluginManager;
2886
+ }
2692
2887
  /**
2693
2888
  * Returns a fluent, chained reference to a specific file
2694
2889
  */
@@ -2707,7 +2902,8 @@ var DriveKit = class _DriveKit {
2707
2902
  async init() {
2708
2903
  if (!this.driveClient) {
2709
2904
  const auth = await this.authenticator.getAuthClient();
2710
- this.driveClient = drive({ version: "v3", auth });
2905
+ const agent = getOptimizedHttpsAgent();
2906
+ this.driveClient = drive({ version: "v3", auth, agent });
2711
2907
  if (this.options.enablePersistentCache !== false) {
2712
2908
  this.metadataCacheInstance = new SqliteMetadataCache(this.options.cacheDatabasePath);
2713
2909
  this.metadataCacheInstance.init();
@@ -2794,15 +2990,41 @@ var DriveKit = class _DriveKit {
2794
2990
  }
2795
2991
  }
2796
2992
  /**
2797
- * Lists contents of a folder (by folder ID or path)
2993
+ * Lists contents of a folder (by folder ID or path) with opportunistic tree caching
2798
2994
  */
2799
2995
  async ls(folderIdOrPath = "/") {
2996
+ let parentFolderId;
2997
+ let normalizedPath = null;
2998
+ let files;
2800
2999
  if (folderIdOrPath === "/" || folderIdOrPath === "root" || folderIdOrPath === this.rootFolderId) {
3000
+ parentFolderId = this.rootFolderId;
3001
+ normalizedPath = "/";
2801
3002
  const parentFilter = this.rootFolderId === "root" ? "'root' in parents or sharedWithMe = true" : `'${this.rootFolderId}' in parents`;
2802
- return await this.query().raw(parentFilter).notTrashed().orderBy("folder,name").list();
3003
+ files = await this.query().raw(parentFilter).notTrashed().orderBy("folder,name").list();
3004
+ } else {
3005
+ if (folderIdOrPath.startsWith("/")) {
3006
+ normalizedPath = folderIdOrPath.replace(/\/+$/, "") || "/";
3007
+ parentFolderId = await this.resolveId(normalizedPath);
3008
+ } else {
3009
+ parentFolderId = folderIdOrPath;
3010
+ }
3011
+ files = await this.query().inFolder(parentFolderId).notTrashed().orderBy("folder,name").list();
2803
3012
  }
2804
- const folderId = await this.resolveId(folderIdOrPath);
2805
- return await this.query().inFolder(folderId).notTrashed().orderBy("folder,name").list();
3013
+ if (this.metadataCacheInstance && files.length > 0) {
3014
+ const cacheEntries = files.filter((f) => !!f.id).map((f) => ({
3015
+ id: f.id,
3016
+ name: f.name || "untitled",
3017
+ mimeType: f.mimeType || "",
3018
+ size: f.size ? parseInt(f.size, 10) : void 0,
3019
+ parentId: parentFolderId,
3020
+ path: normalizedPath ? `${normalizedPath === "/" ? "" : normalizedPath}/${f.name}` : void 0,
3021
+ md5Checksum: f.md5Checksum || void 0,
3022
+ modifiedTime: f.modifiedTime || void 0,
3023
+ trashed: false
3024
+ }));
3025
+ this.metadataCacheInstance.upsertFiles(cacheEntries);
3026
+ }
3027
+ return files;
2806
3028
  }
2807
3029
  // ==========================================
2808
3030
  // FILE OPERATIONS (UPLOAD, DOWNLOAD, GET)
@@ -2821,7 +3043,7 @@ var DriveKit = class _DriveKit {
2821
3043
  if (parentId && parentId.startsWith("/")) {
2822
3044
  parentId = await this.mkdirp(parentId);
2823
3045
  }
2824
- const targetName = opts.name || opts.filename;
3046
+ const targetName = opts.name || opts.filename || (typeof opts.source === "string" ? path8.basename(opts.source) : void 0);
2825
3047
  if (opts.overwrite && targetName && parentId) {
2826
3048
  const existing = await this.query().inFolder(parentId).nameEquals(targetName).notTrashed().first();
2827
3049
  if (existing?.id) {
@@ -2877,12 +3099,14 @@ var DriveKit = class _DriveKit {
2877
3099
  parent: parentId
2878
3100
  });
2879
3101
  if (this.metadataCacheInstance && uploaded.id) {
3102
+ const virtualPath = typeof opts.parent === "string" && opts.parent.startsWith("/") ? `${opts.parent === "/" ? "" : opts.parent}/${uploaded.name || targetName || "untitled"}` : void 0;
2880
3103
  this.metadataCacheInstance.upsertFile({
2881
3104
  id: uploaded.id,
2882
3105
  name: uploaded.name || targetName || "untitled",
2883
3106
  mimeType: uploaded.mimeType || "",
2884
3107
  size: uploaded.size ? parseInt(uploaded.size, 10) : void 0,
2885
3108
  parentId,
3109
+ path: virtualPath,
2886
3110
  trashed: false
2887
3111
  });
2888
3112
  }
@@ -2893,16 +3117,25 @@ var DriveKit = class _DriveKit {
2893
3117
  * - Automatic conversion for Google Docs, Sheets, and Slides
2894
3118
  * - Progress events
2895
3119
  * - Saves directly to file or returns Readable Stream
3120
+ * - Leverages local metadata cache to bypass redundant Google API roundtrips
2896
3121
  */
2897
3122
  async download(fileIdOrPath, options = {}) {
2898
3123
  const fileId = await this.resolveId(fileIdOrPath);
2899
- const processedOpts = await this.pluginManager.runBeforeDownload(fileId, options);
3124
+ let cachedMeta = options.metadata;
3125
+ if (!cachedMeta && this.metadataCacheInstance) {
3126
+ const cached = this.metadataCacheInstance.getById(fileId);
3127
+ if (cached && cached.name && cached.mimeType) {
3128
+ cachedMeta = { name: cached.name, mimeType: cached.mimeType, size: cached.size };
3129
+ }
3130
+ }
3131
+ const mergedOpts = cachedMeta ? { ...options, metadata: cachedMeta } : options;
3132
+ const processedOpts = await this.pluginManager.runBeforeDownload(fileId, mergedOpts);
2900
3133
  const downloader = await this.getDownloader();
2901
3134
  const result = await downloader.download(fileId, processedOpts);
2902
3135
  return await this.pluginManager.runAfterDownload(result);
2903
3136
  }
2904
3137
  /**
2905
- * Gets file metadata
3138
+ * Gets file metadata and updates the local metadata cache
2906
3139
  */
2907
3140
  async getFile(fileIdOrPath) {
2908
3141
  const fileId = await this.resolveId(fileIdOrPath);
@@ -2914,7 +3147,20 @@ var DriveKit = class _DriveKit {
2914
3147
  supportsAllDrives: true
2915
3148
  });
2916
3149
  });
2917
- return res.data;
3150
+ const file = res.data;
3151
+ if (this.metadataCacheInstance && file.id) {
3152
+ this.metadataCacheInstance.upsertFile({
3153
+ id: file.id,
3154
+ name: file.name || "",
3155
+ mimeType: file.mimeType || "",
3156
+ size: file.size ? parseInt(file.size, 10) : void 0,
3157
+ parentId: file.parents?.[0],
3158
+ path: fileIdOrPath.startsWith("/") ? fileIdOrPath : void 0,
3159
+ modifiedTime: file.modifiedTime || void 0,
3160
+ trashed: file.trashed || false
3161
+ });
3162
+ }
3163
+ return file;
2918
3164
  }
2919
3165
  /**
2920
3166
  * Reads file content as UTF-8 string
@@ -2957,6 +3203,9 @@ var DriveKit = class _DriveKit {
2957
3203
  if (this.pathResolverInstance && fileIdOrPath.startsWith("/")) {
2958
3204
  this.pathResolverInstance.invalidatePath(fileIdOrPath);
2959
3205
  }
3206
+ if (this.metadataCacheInstance) {
3207
+ this.metadataCacheInstance.deleteFile(fileId);
3208
+ }
2960
3209
  }
2961
3210
  /**
2962
3211
  * Move item to trash
@@ -2998,6 +3247,16 @@ var DriveKit = class _DriveKit {
2998
3247
  if (this.pathResolverInstance) {
2999
3248
  this.pathResolverInstance.clearCache();
3000
3249
  }
3250
+ if (this.metadataCacheInstance) {
3251
+ const cached = this.metadataCacheInstance.getById(fileId);
3252
+ if (cached) {
3253
+ this.metadataCacheInstance.upsertFile({
3254
+ ...cached,
3255
+ parentId: newParentId,
3256
+ path: void 0
3257
+ });
3258
+ }
3259
+ }
3001
3260
  return res.data;
3002
3261
  }
3003
3262
  /**
@@ -3040,6 +3299,16 @@ var DriveKit = class _DriveKit {
3040
3299
  if (this.pathResolverInstance) {
3041
3300
  this.pathResolverInstance.clearCache();
3042
3301
  }
3302
+ if (this.metadataCacheInstance) {
3303
+ const cached = this.metadataCacheInstance.getById(fileId);
3304
+ if (cached) {
3305
+ this.metadataCacheInstance.upsertFile({
3306
+ ...cached,
3307
+ name: newName,
3308
+ path: void 0
3309
+ });
3310
+ }
3311
+ }
3043
3312
  return res.data;
3044
3313
  }
3045
3314
  // ==========================================
@@ -3317,7 +3586,7 @@ var DriveKit = class _DriveKit {
3317
3586
  async createWriteStream(remotePath, options = {}) {
3318
3587
  await this.init();
3319
3588
  const { PassThrough } = await import("stream");
3320
- const passThrough = new PassThrough();
3589
+ const passThrough = new PassThrough({ highWaterMark: 1024 * 1024 });
3321
3590
  let resolveDone;
3322
3591
  let rejectDone;
3323
3592
  const donePromise = new Promise((resolve, reject) => {
@@ -3364,6 +3633,12 @@ var DriveKit = class _DriveKit {
3364
3633
  // ==========================================
3365
3634
  // METADATA CACHE OPERATIONS
3366
3635
  // ==========================================
3636
+ /**
3637
+ * Synchronous getter for the active metadata cache instance
3638
+ */
3639
+ get cache() {
3640
+ return this.metadataCacheInstance;
3641
+ }
3367
3642
  /**
3368
3643
  * Returns the active persistent metadata cache instance (SQLite/Memory)
3369
3644
  */
@@ -3386,6 +3661,9 @@ var DriveKit = class _DriveKit {
3386
3661
  if (this.pathResolverInstance) {
3387
3662
  this.pathResolverInstance.clearCache();
3388
3663
  }
3664
+ if (this.metadataCacheInstance) {
3665
+ this.metadataCacheInstance.clear();
3666
+ }
3389
3667
  }
3390
3668
  /**
3391
3669
  * Crawls and indexes Google Drive metadata into the local SQLite database for instant 0ms lookups
@@ -3768,6 +4046,8 @@ export {
3768
4046
  formatSpeed,
3769
4047
  getExtensionForMime,
3770
4048
  getFileIcon,
4049
+ getOptimizedHttpAgent,
4050
+ getOptimizedHttpsAgent,
3771
4051
  isGoogleWorkspaceDoc,
3772
4052
  isRetryableError,
3773
4053
  loginWithBrowser,