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.cjs CHANGED
@@ -50,7 +50,7 @@ async function startWebDAVServer(drive2, options = {}) {
50
50
  const port = options.port || 8080;
51
51
  const host = options.host || "127.0.0.1";
52
52
  await drive2.init();
53
- const server = import_node_http2.default.createServer(async (req, res) => {
53
+ const server = import_node_http3.default.createServer(async (req, res) => {
54
54
  try {
55
55
  if (options.auth?.username && options.auth?.password) {
56
56
  const authHeader = req.headers["authorization"];
@@ -76,6 +76,12 @@ async function startWebDAVServer(drive2, options = {}) {
76
76
  const parsedUrl = import_node_url.default.parse(req.url || "/", true);
77
77
  const decodedPath = decodeURIComponent(parsedUrl.pathname || "/");
78
78
  const virtualPath = decodedPath === "" ? "/" : decodedPath;
79
+ const baseName = import_node_path6.default.basename(virtualPath);
80
+ if (baseName.startsWith("._") || baseName === ".DS_Store" || baseName === ".Trashes" || baseName === ".Spotlight-V100" || baseName === ".fseventsd") {
81
+ res.writeHead(404, { "Content-Type": "text/plain" });
82
+ res.end("Not Found");
83
+ return;
84
+ }
79
85
  switch (req.method) {
80
86
  case "OPTIONS": {
81
87
  res.writeHead(200, {
@@ -90,6 +96,11 @@ async function startWebDAVServer(drive2, options = {}) {
90
96
  case "PROPFIND": {
91
97
  const depth = req.headers["depth"] || "1";
92
98
  const xml = await handlePropfind(drive2, virtualPath, depth);
99
+ if (xml === null) {
100
+ res.writeHead(404, { "Content-Type": "text/plain" });
101
+ res.end("Not Found");
102
+ return;
103
+ }
93
104
  res.writeHead(207, {
94
105
  "Content-Type": "application/xml; charset=utf-8"
95
106
  });
@@ -300,25 +311,38 @@ async function handlePropfind(drive2, virtualPath, depth) {
300
311
  virtualPath,
301
312
  isFolder,
302
313
  selfItem.size ? parseInt(selfItem.size, 10) : 0,
303
- selfItem.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
314
+ selfItem.modifiedTime || (/* @__PURE__ */ new Date()).toISOString(),
315
+ selfItem.mimeType || void 0
304
316
  )
305
317
  );
306
318
  } catch {
307
- return `<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:"></D:multistatus>`;
319
+ return null;
308
320
  }
309
321
  }
310
322
  if (isFolder && depth !== "0") {
311
323
  try {
312
324
  const children = await drive2.ls(virtualPath);
325
+ const seenNames = /* @__PURE__ */ new Map();
313
326
  for (const child of children) {
327
+ let childName = child.name || "untitled";
328
+ if (seenNames.has(childName)) {
329
+ const count = seenNames.get(childName) + 1;
330
+ seenNames.set(childName, count);
331
+ const ext = import_node_path6.default.extname(childName);
332
+ const base = import_node_path6.default.basename(childName, ext);
333
+ childName = `${base} (${count})${ext}`;
334
+ } else {
335
+ seenNames.set(childName, 0);
336
+ }
314
337
  const childIsFolder = child.mimeType === "application/vnd.google-apps.folder";
315
- const childPath = virtualPath === "/" ? `/${child.name}` : `${virtualPath}/${child.name}`;
338
+ const childPath = virtualPath === "/" ? `/${childName}` : `${virtualPath}/${childName}`;
316
339
  responses.push(
317
340
  renderWebDAVResponse(
318
341
  childPath,
319
342
  childIsFolder,
320
343
  child.size ? parseInt(child.size, 10) : 0,
321
- child.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
344
+ child.modifiedTime || (/* @__PURE__ */ new Date()).toISOString(),
345
+ child.mimeType || void 0
322
346
  )
323
347
  );
324
348
  }
@@ -330,11 +354,17 @@ async function handlePropfind(drive2, virtualPath, depth) {
330
354
  ${responses.join("\n")}
331
355
  </D:multistatus>`;
332
356
  }
333
- function renderWebDAVResponse(href, isDir, size, modifiedTime) {
334
- const encodedHref = encodeURI(href);
357
+ function renderWebDAVResponse(href, isDir, size, modifiedTime, mimeType) {
358
+ let cleanHref = href;
359
+ if (isDir && !cleanHref.endsWith("/")) {
360
+ cleanHref += "/";
361
+ }
362
+ const encodedHref = encodeURI(cleanHref);
335
363
  const displayName = escapeXml(import_node_path6.default.basename(href) || "root");
336
364
  const resourceType = isDir ? "<D:collection/>" : "";
337
365
  const dateFormatted = new Date(modifiedTime).toUTCString();
366
+ const contentTypeTag = !isDir && mimeType ? `
367
+ <D:getcontenttype>${escapeXml(mimeType)}</D:getcontenttype>` : "";
338
368
  return ` <D:response>
339
369
  <D:href>${encodedHref}</D:href>
340
370
  <D:propstat>
@@ -342,19 +372,18 @@ function renderWebDAVResponse(href, isDir, size, modifiedTime) {
342
372
  <D:displayname>${displayName}</D:displayname>
343
373
  <D:resourcetype>${resourceType}</D:resourcetype>
344
374
  <D:getcontentlength>${isDir ? "0" : size}</D:getcontentlength>
345
- <D:getlastmodified>${dateFormatted}</D:getlastmodified>
346
- <D:status>HTTP/1.1 200 OK</D:status>
375
+ <D:getlastmodified>${dateFormatted}</D:getlastmodified>${contentTypeTag}
347
376
  </D:prop>
348
377
  <D:status>HTTP/1.1 200 OK</D:status>
349
378
  </D:propstat>
350
379
  </D:response>`;
351
380
  }
352
- var import_node_http2, import_node_url, import_node_path6;
381
+ var import_node_http3, import_node_url, import_node_path6;
353
382
  var init_webdav = __esm({
354
383
  "src/server/webdav.ts"() {
355
384
  "use strict";
356
385
  init_cjs_shims();
357
- import_node_http2 = __toESM(require("http"), 1);
386
+ import_node_http3 = __toESM(require("http"), 1);
358
387
  import_node_url = __toESM(require("url"), 1);
359
388
  import_node_path6 = __toESM(require("path"), 1);
360
389
  }
@@ -400,6 +429,8 @@ __export(index_exports, {
400
429
  formatSpeed: () => formatSpeed,
401
430
  getExtensionForMime: () => getExtensionForMime,
402
431
  getFileIcon: () => getFileIcon,
432
+ getOptimizedHttpAgent: () => getOptimizedHttpAgent,
433
+ getOptimizedHttpsAgent: () => getOptimizedHttpsAgent,
403
434
  isGoogleWorkspaceDoc: () => isGoogleWorkspaceDoc,
404
435
  isRetryableError: () => isRetryableError,
405
436
  loginWithBrowser: () => loginWithBrowser,
@@ -470,6 +501,39 @@ var DriveUploadError = class extends DriveKitError {
470
501
  }
471
502
  };
472
503
 
504
+ // src/utils/http-agent.ts
505
+ init_cjs_shims();
506
+ var import_node_https = __toESM(require("https"), 1);
507
+ var import_node_http = __toESM(require("http"), 1);
508
+ var sharedHttpsAgent = null;
509
+ var sharedHttpAgent = null;
510
+ function getOptimizedHttpsAgent(options) {
511
+ if (!sharedHttpsAgent) {
512
+ sharedHttpsAgent = new import_node_https.default.Agent({
513
+ keepAlive: options?.keepAlive ?? true,
514
+ maxSockets: options?.maxSockets ?? 64,
515
+ maxFreeSockets: options?.maxFreeSockets ?? 32,
516
+ keepAliveMsecs: options?.keepAliveMsecs ?? 6e4,
517
+ timeout: options?.timeout ?? 3e4,
518
+ noDelay: true
519
+ });
520
+ }
521
+ return sharedHttpsAgent;
522
+ }
523
+ function getOptimizedHttpAgent(options) {
524
+ if (!sharedHttpAgent) {
525
+ sharedHttpAgent = new import_node_http.default.Agent({
526
+ keepAlive: options?.keepAlive ?? true,
527
+ maxSockets: options?.maxSockets ?? 64,
528
+ maxFreeSockets: options?.maxFreeSockets ?? 32,
529
+ keepAliveMsecs: options?.keepAliveMsecs ?? 6e4,
530
+ timeout: options?.timeout ?? 3e4,
531
+ noDelay: true
532
+ });
533
+ }
534
+ return sharedHttpAgent;
535
+ }
536
+
473
537
  // src/auth/authenticator.ts
474
538
  var DEFAULT_SCOPES = [
475
539
  "https://www.googleapis.com/auth/drive"
@@ -493,44 +557,39 @@ var DriveAuthenticator = class {
493
557
  const oauth2Client = new import_drive.auth.OAuth2();
494
558
  oauth2Client.setCredentials({ access_token: this.config.accessToken });
495
559
  this.authClient = oauth2Client;
496
- return this.authClient;
497
- }
498
- if (this.config.oauth2Client) {
560
+ } else if (this.config.oauth2Client) {
499
561
  this.authClient = this.config.oauth2Client;
500
- return this.authClient;
501
- }
502
- if (this.config.oauth) {
562
+ } else if (this.config.oauth) {
503
563
  const { clientId, clientSecret, redirectUri = "http://localhost:3000/oauth2callback", refreshToken } = this.config.oauth;
504
564
  const oauth2Client = new import_drive.auth.OAuth2(clientId, clientSecret, redirectUri);
505
565
  if (refreshToken) {
506
566
  oauth2Client.setCredentials({ refresh_token: refreshToken });
507
567
  }
508
568
  this.authClient = oauth2Client;
509
- return this.authClient;
510
- }
511
- const keyFile = this.config.keyFilePath || process.env.GDRIVE_SERVICE_ACCOUNT_PATH || process.env.GOOGLE_APPLICATION_CREDENTIALS;
512
- if (keyFile) {
513
- if (!import_node_fs.default.existsSync(keyFile)) {
569
+ } else if (this.config.keyFilePath || process.env.GDRIVE_SERVICE_ACCOUNT_PATH || process.env.GOOGLE_APPLICATION_CREDENTIALS) {
570
+ const keyFile = this.config.keyFilePath || process.env.GDRIVE_SERVICE_ACCOUNT_PATH || process.env.GOOGLE_APPLICATION_CREDENTIALS;
571
+ if (keyFile && !import_node_fs.default.existsSync(keyFile)) {
514
572
  throw new DriveAuthError(`Service account file not found at: ${keyFile}`);
515
573
  }
516
- const auth2 = new import_drive.auth.GoogleAuth({
574
+ const auth = new import_drive.auth.GoogleAuth({
517
575
  keyFile,
518
576
  scopes
519
577
  });
520
- this.authClient = auth2;
521
- return this.authClient;
522
- }
523
- const creds = this.config.credentials || (process.env.GDRIVE_CREDENTIALS_JSON ? JSON.parse(process.env.GDRIVE_CREDENTIALS_JSON) : null);
524
- if (creds) {
525
- const auth2 = new import_drive.auth.GoogleAuth({
578
+ this.authClient = auth;
579
+ } else if (this.config.credentials || process.env.GDRIVE_CREDENTIALS_JSON) {
580
+ const creds = this.config.credentials || (process.env.GDRIVE_CREDENTIALS_JSON ? JSON.parse(process.env.GDRIVE_CREDENTIALS_JSON) : null);
581
+ const auth = new import_drive.auth.GoogleAuth({
526
582
  credentials: creds,
527
583
  scopes
528
584
  });
529
- this.authClient = auth2;
530
- return this.authClient;
585
+ this.authClient = auth;
586
+ } else {
587
+ const auth = new import_drive.auth.GoogleAuth({ scopes });
588
+ this.authClient = auth;
589
+ }
590
+ if (this.authClient?.transporter?.defaults) {
591
+ this.authClient.transporter.defaults.agent = getOptimizedHttpsAgent();
531
592
  }
532
- const auth = new import_drive.auth.GoogleAuth({ scopes });
533
- this.authClient = auth;
534
593
  return this.authClient;
535
594
  } catch (err) {
536
595
  if (err instanceof DriveAuthError) throw err;
@@ -669,6 +728,7 @@ var PathResolver = class {
669
728
  drive;
670
729
  rootFolderId;
671
730
  cache = /* @__PURE__ */ new Map();
731
+ inFlightResolves = /* @__PURE__ */ new Map();
672
732
  cacheTTL;
673
733
  enableCache;
674
734
  metadataCache;
@@ -721,6 +781,7 @@ var PathResolver = class {
721
781
  /**
722
782
  * Resolves a path to a Google Drive item (file or folder).
723
783
  * If createIfMissing is true, any missing intermediate directories will be automatically created (like mkdir -p).
784
+ * Incorporates in-flight request coalescing to deduplicate concurrent resolutions of identical paths.
724
785
  */
725
786
  async resolve(virtualPath, options = {}) {
726
787
  const norm = this.normalizePath(virtualPath);
@@ -754,6 +815,20 @@ var PathResolver = class {
754
815
  };
755
816
  }
756
817
  }
818
+ const flightKey = `${this.rootFolderId}:${norm}:${options.createIfMissing ? "create" : "read"}`;
819
+ const inFlight = this.inFlightResolves.get(flightKey);
820
+ if (inFlight) {
821
+ return await inFlight;
822
+ }
823
+ const task = this.doResolve(virtualPath, norm, options);
824
+ this.inFlightResolves.set(flightKey, task);
825
+ try {
826
+ return await task;
827
+ } finally {
828
+ this.inFlightResolves.delete(flightKey);
829
+ }
830
+ }
831
+ async doResolve(virtualPath, norm, options) {
757
832
  const segments = norm.split("/").filter(Boolean);
758
833
  let currentParentId = this.rootFolderId;
759
834
  let currentPath = "";
@@ -805,7 +880,7 @@ var PathResolver = class {
805
880
  });
806
881
  let file = response.data.files?.[0];
807
882
  if (!file && currentParentId === this.rootFolderId) {
808
- const sharedQ = `name = '${escapedName}' and trashed = false`;
883
+ const sharedQ = `name = '${escapedName}' and sharedWithMe = true and trashed = false`;
809
884
  const sharedResponse = await withRetry(async () => {
810
885
  return await this.drive.files.list({
811
886
  q: sharedQ,
@@ -915,6 +990,7 @@ var PathResolver = class {
915
990
  init_cjs_shims();
916
991
  var import_node_fs2 = __toESM(require("fs"), 1);
917
992
  var import_node_path = __toESM(require("path"), 1);
993
+ var import_node_stream = require("stream");
918
994
 
919
995
  // src/utils/format.ts
920
996
  init_cjs_shims();
@@ -979,6 +1055,15 @@ var ResumableUploader = class {
979
1055
  const totalBytes = stat.size;
980
1056
  const fileName = options.name || import_node_path.default.basename(filePath);
981
1057
  const mimeType = options.mimeType || lookupMimeType(filePath);
1058
+ if (totalBytes <= MULTIPART_THRESHOLD) {
1059
+ const readStream = import_node_fs2.default.createReadStream(filePath, { highWaterMark: 1024 * 1024 });
1060
+ const stream = options.onProgress ? this.wrapStreamWithProgress(readStream, totalBytes, options.onProgress) : readStream;
1061
+ return await this.directUpload(stream, {
1062
+ ...options,
1063
+ name: fileName,
1064
+ mimeType
1065
+ });
1066
+ }
982
1067
  return await this.chunkedUpload({
983
1068
  filePath,
984
1069
  totalBytes,
@@ -994,6 +1079,16 @@ var ResumableUploader = class {
994
1079
  const totalBytes = buffer.length;
995
1080
  const fileName = options.name || "untitled";
996
1081
  const mimeType = options.mimeType || "application/octet-stream";
1082
+ if (totalBytes <= MULTIPART_THRESHOLD) {
1083
+ const { Readable } = await import("stream");
1084
+ const baseStream = Readable.from(totalBytes === 0 ? [] : [buffer]);
1085
+ const stream = options.onProgress ? this.wrapStreamWithProgress(baseStream, totalBytes, options.onProgress) : baseStream;
1086
+ return await this.directUpload(stream, {
1087
+ ...options,
1088
+ name: fileName,
1089
+ mimeType
1090
+ });
1091
+ }
997
1092
  return await this.chunkedUploadBuffer({
998
1093
  buffer,
999
1094
  totalBytes,
@@ -1014,6 +1109,50 @@ var ResumableUploader = class {
1014
1109
  mimeType
1015
1110
  });
1016
1111
  }
1112
+ /**
1113
+ * Calculates optimal chunk size based on file size for maximum throughput.
1114
+ */
1115
+ computeAdaptiveChunkSize(totalBytes, explicitChunkSize) {
1116
+ if (explicitChunkSize) {
1117
+ return Math.max(MIN_CHUNK_SIZE, Math.floor(explicitChunkSize / MIN_CHUNK_SIZE) * MIN_CHUNK_SIZE);
1118
+ }
1119
+ if (totalBytes > 128 * 1024 * 1024) {
1120
+ return 32 * 1024 * 1024;
1121
+ }
1122
+ if (totalBytes > 32 * 1024 * 1024) {
1123
+ return 16 * 1024 * 1024;
1124
+ }
1125
+ return this.defaultChunkSize;
1126
+ }
1127
+ /**
1128
+ * Attaches real-time progress monitoring to direct stream uploads.
1129
+ */
1130
+ wrapStreamWithProgress(stream, totalBytes, onProgress) {
1131
+ let bytesSent = 0;
1132
+ const startTime = Date.now();
1133
+ const progressTransform = new import_node_stream.Transform({
1134
+ transform(chunk, _encoding, callback) {
1135
+ bytesSent += chunk.length;
1136
+ const elapsedSecs = (Date.now() - startTime) / 1e3;
1137
+ const bytesPerSecond = elapsedSecs > 0 ? Math.round(bytesSent / elapsedSecs) : 0;
1138
+ const remainingBytes = Math.max(0, totalBytes - bytesSent);
1139
+ const estimatedTimeRemainingSeconds = bytesPerSecond > 0 ? Math.round(remainingBytes / bytesPerSecond) : 0;
1140
+ const percentage = totalBytes > 0 ? Math.min(100, Math.round(bytesSent / totalBytes * 1e3) / 10) : 100;
1141
+ onProgress({
1142
+ bytesSent,
1143
+ totalBytes,
1144
+ percentage,
1145
+ bytesPerSecond,
1146
+ speedFormatted: formatSpeed(bytesPerSecond),
1147
+ estimatedTimeRemainingSeconds,
1148
+ chunkIndex: 1,
1149
+ totalChunks: 1
1150
+ });
1151
+ callback(null, chunk);
1152
+ }
1153
+ });
1154
+ return stream.pipe(progressTransform);
1155
+ }
1017
1156
  /**
1018
1157
  * Fast direct upload using googleapis multipart
1019
1158
  */
@@ -1046,7 +1185,7 @@ var ResumableUploader = class {
1046
1185
  */
1047
1186
  async chunkedUpload(params) {
1048
1187
  const { filePath, 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;
1188
+ const chunkSize = this.computeAdaptiveChunkSize(totalBytes, options.chunkSize);
1050
1189
  const sessionUrl = await this.initiateResumableSession({
1051
1190
  fileName,
1052
1191
  mimeType,
@@ -1111,7 +1250,7 @@ var ResumableUploader = class {
1111
1250
  */
1112
1251
  async chunkedUploadBuffer(params) {
1113
1252
  const { buffer, totalBytes, fileName, mimeType, options } = params;
1114
- const chunkSize = options.chunkSize ? Math.max(MIN_CHUNK_SIZE, Math.floor(options.chunkSize / MIN_CHUNK_SIZE) * MIN_CHUNK_SIZE) : this.defaultChunkSize;
1253
+ const chunkSize = this.computeAdaptiveChunkSize(totalBytes, options.chunkSize);
1115
1254
  const sessionUrl = await this.initiateResumableSession({
1116
1255
  fileName,
1117
1256
  mimeType,
@@ -1190,7 +1329,8 @@ var ResumableUploader = class {
1190
1329
  url: "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&supportsAllDrives=true",
1191
1330
  method: "POST",
1192
1331
  headers,
1193
- data: metadata
1332
+ data: metadata,
1333
+ agent: getOptimizedHttpsAgent()
1194
1334
  });
1195
1335
  });
1196
1336
  const sessionUrl = res.headers?.get ? res.headers.get("location") : res.headers?.location || res.headers?.["location"];
@@ -1216,6 +1356,7 @@ var ResumableUploader = class {
1216
1356
  method: "PUT",
1217
1357
  headers,
1218
1358
  data: buffer,
1359
+ agent: getOptimizedHttpsAgent(),
1219
1360
  validateStatus: (status) => status >= 200 && status < 300 || status === 308
1220
1361
  });
1221
1362
  if (res.status === 200 || res.status === 201) {
@@ -1249,7 +1390,7 @@ init_cjs_shims();
1249
1390
  var import_node_fs3 = __toESM(require("fs"), 1);
1250
1391
  var import_node_path2 = __toESM(require("path"), 1);
1251
1392
  var import_promises = require("stream/promises");
1252
- var import_node_stream = require("stream");
1393
+ var import_node_stream2 = require("stream");
1253
1394
  var Downloader = class {
1254
1395
  drive;
1255
1396
  constructor(drive2) {
@@ -1259,17 +1400,22 @@ var Downloader = class {
1259
1400
  * Downloads a file from Google Drive to local destination path or returns a readable stream.
1260
1401
  */
1261
1402
  async download(fileId, options = {}) {
1262
- const metaRes = await withRetry(async () => {
1263
- return await this.drive.files.get({
1264
- fileId,
1265
- fields: "id, name, mimeType, size",
1266
- supportsAllDrives: true
1403
+ let name = options.metadata?.name;
1404
+ let mimeType = options.metadata?.mimeType;
1405
+ let totalBytes = options.metadata?.size;
1406
+ if (!name || !mimeType) {
1407
+ const metaRes = await withRetry(async () => {
1408
+ return await this.drive.files.get({
1409
+ fileId,
1410
+ fields: "id, name, mimeType, size",
1411
+ supportsAllDrives: true
1412
+ });
1267
1413
  });
1268
- });
1269
- const file = metaRes.data;
1270
- const name = file.name || "downloaded-file";
1271
- const mimeType = file.mimeType || "application/octet-stream";
1272
- const totalBytes = file.size ? parseInt(file.size, 10) : void 0;
1414
+ const file = metaRes.data;
1415
+ name = file.name || "downloaded-file";
1416
+ mimeType = file.mimeType || "application/octet-stream";
1417
+ totalBytes = file.size ? parseInt(file.size, 10) : void 0;
1418
+ }
1273
1419
  let downloadStream;
1274
1420
  let finalFileName = name;
1275
1421
  if (isGoogleWorkspaceDoc(mimeType)) {
@@ -1300,7 +1446,7 @@ var Downloader = class {
1300
1446
  }
1301
1447
  let bytesRead = 0;
1302
1448
  const startTime = Date.now();
1303
- const progressTracker = new import_node_stream.Transform({
1449
+ const progressTracker = new import_node_stream2.Transform({
1304
1450
  transform(chunk, encoding, callback) {
1305
1451
  bytesRead += chunk.length;
1306
1452
  if (options.onProgress) {
@@ -1325,7 +1471,7 @@ var Downloader = class {
1325
1471
  destPath = import_node_path2.default.join(destPath, finalFileName);
1326
1472
  }
1327
1473
  await import_node_fs3.default.promises.mkdir(import_node_path2.default.dirname(destPath), { recursive: true });
1328
- const writeStream = import_node_fs3.default.createWriteStream(destPath);
1474
+ const writeStream = import_node_fs3.default.createWriteStream(destPath, { highWaterMark: 1024 * 1024 });
1329
1475
  await (0, import_promises.pipeline)(monitoredStream, writeStream);
1330
1476
  return {
1331
1477
  filePath: destPath,
@@ -1568,6 +1714,7 @@ var DriveQueryBuilder = class {
1568
1714
  const q = this.toQueryString();
1569
1715
  const orderBy = this.orderClauses.join(", ");
1570
1716
  let pageToken = void 0;
1717
+ const effectiveFields = this.requestedFields.includes("nextPageToken") ? this.requestedFields : `nextPageToken, ${this.requestedFields}`;
1571
1718
  do {
1572
1719
  const res = await withRetry(async () => {
1573
1720
  return await this.drive.files.list({
@@ -1575,7 +1722,7 @@ var DriveQueryBuilder = class {
1575
1722
  orderBy: orderBy || void 0,
1576
1723
  pageSize: this.limitNumber,
1577
1724
  pageToken,
1578
- fields: this.requestedFields,
1725
+ fields: effectiveFields,
1579
1726
  spaces: this.spaces,
1580
1727
  supportsAllDrives: true,
1581
1728
  includeItemsFromAllDrives: true
@@ -1699,7 +1846,7 @@ var DriveWatcher = class extends import_node_events.EventEmitter {
1699
1846
  const res = await withRetry(async () => {
1700
1847
  return await this.drive.changes.list({
1701
1848
  pageToken: nextPageToken,
1702
- fields: "nextPageToken, newStartPageToken, changes(changeType, fileId, removed, time, file(id, name, mimeType, size, modifiedTime, parents, trashed))",
1849
+ fields: "nextPageToken, newStartPageToken, changes(changeType, fileId, removed, time, file(id, name, mimeType, size, createdTime, modifiedTime, parents, trashed))",
1703
1850
  supportsAllDrives: true,
1704
1851
  includeItemsFromAllDrives: true
1705
1852
  });
@@ -1790,16 +1937,24 @@ var StorageCleaner = class {
1790
1937
  async findDuplicates(options = {}) {
1791
1938
  const mode = options.by || "name";
1792
1939
  const maxScan = options.maxScan || 1e3;
1793
- const res = await withRetry(async () => {
1794
- return await this.drive.files.list({
1795
- q: 'trashed = false and mimeType != "application/vnd.google-apps.folder"',
1796
- pageSize: Math.min(1e3, maxScan),
1797
- fields: "files(id, name, size, md5Checksum, modifiedTime)",
1798
- supportsAllDrives: true,
1799
- includeItemsFromAllDrives: true
1940
+ const files = [];
1941
+ let pageToken = void 0;
1942
+ do {
1943
+ const remaining = maxScan - files.length;
1944
+ if (remaining <= 0) break;
1945
+ const res = await withRetry(async () => {
1946
+ return await this.drive.files.list({
1947
+ q: 'trashed = false and mimeType != "application/vnd.google-apps.folder"',
1948
+ pageSize: Math.min(1e3, remaining),
1949
+ pageToken,
1950
+ fields: "nextPageToken, files(id, name, size, md5Checksum, modifiedTime)",
1951
+ supportsAllDrives: true,
1952
+ includeItemsFromAllDrives: true
1953
+ });
1800
1954
  });
1801
- });
1802
- const files = res.data.files || [];
1955
+ files.push(...res.data.files || []);
1956
+ pageToken = res.data.nextPageToken || void 0;
1957
+ } while (pageToken && files.length < maxScan);
1803
1958
  const map = /* @__PURE__ */ new Map();
1804
1959
  for (const f of files) {
1805
1960
  if (!f.id) continue;
@@ -1974,7 +2129,7 @@ var SmartSyncEngine = class {
1974
2129
 
1975
2130
  // src/auth/browser-login.ts
1976
2131
  init_cjs_shims();
1977
- var import_node_http = __toESM(require("http"), 1);
2132
+ var import_node_http2 = __toESM(require("http"), 1);
1978
2133
  var import_node_child_process = require("child_process");
1979
2134
  var import_drive2 = require("@googleapis/drive");
1980
2135
  async function loginWithBrowser(options) {
@@ -1992,7 +2147,7 @@ async function loginWithBrowser(options) {
1992
2147
  scope: scopes
1993
2148
  });
1994
2149
  return new Promise((resolve, reject) => {
1995
- const server = import_node_http.default.createServer(async (req, res) => {
2150
+ const server = import_node_http2.default.createServer(async (req, res) => {
1996
2151
  try {
1997
2152
  const reqUrl = new URL(req.url || "/", `http://localhost:${port}`);
1998
2153
  if (reqUrl.pathname === "/oauth2callback") {
@@ -2076,7 +2231,11 @@ ${authUrl}
2076
2231
  });
2077
2232
  });
2078
2233
  server.on("error", (err) => {
2079
- reject(err);
2234
+ if (err.code === "EADDRINUSE") {
2235
+ reject(new Error(`Port ${port} is already in use by another process. Please specify an alternate port with --port <number>.`));
2236
+ } else {
2237
+ reject(err);
2238
+ }
2080
2239
  });
2081
2240
  });
2082
2241
  }
@@ -2348,7 +2507,7 @@ function createAutoNamePlugin(options) {
2348
2507
  return {
2349
2508
  name: "drivekit-official-autoname",
2350
2509
  beforeUpload(opts) {
2351
- let name = opts.filename;
2510
+ let name = opts.name || opts.filename;
2352
2511
  if (!name && typeof opts.source === "string") {
2353
2512
  name = import_node_path4.default.basename(opts.source);
2354
2513
  }
@@ -2364,6 +2523,7 @@ function createAutoNamePlugin(options) {
2364
2523
  finalName = `${finalName}${ext}`;
2365
2524
  return {
2366
2525
  ...opts,
2526
+ name: finalName,
2367
2527
  filename: finalName
2368
2528
  };
2369
2529
  }
@@ -2511,10 +2671,35 @@ var SqliteMetadataCache = class {
2511
2671
  return;
2512
2672
  }
2513
2673
  if (!this.initialized || !this.db || entries.length === 0) return;
2674
+ const stmt = this.db.prepare(`
2675
+ INSERT INTO files (id, name, mimeType, size, parentId, path, md5Checksum, trashed, modifiedTime, updatedAt)
2676
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2677
+ ON CONFLICT(id) DO UPDATE SET
2678
+ name = excluded.name,
2679
+ mimeType = excluded.mimeType,
2680
+ size = excluded.size,
2681
+ parentId = excluded.parentId,
2682
+ path = COALESCE(excluded.path, files.path),
2683
+ md5Checksum = excluded.md5Checksum,
2684
+ trashed = excluded.trashed,
2685
+ modifiedTime = excluded.modifiedTime,
2686
+ updatedAt = excluded.updatedAt
2687
+ `);
2514
2688
  this.db.exec("BEGIN TRANSACTION;");
2515
2689
  try {
2516
2690
  for (const entry of entries) {
2517
- this.upsertFile(entry);
2691
+ stmt.run(
2692
+ entry.id,
2693
+ entry.name,
2694
+ entry.mimeType ?? null,
2695
+ entry.size ?? null,
2696
+ entry.parentId ?? null,
2697
+ entry.path ?? null,
2698
+ entry.md5Checksum ? entry.md5Checksum.toLowerCase() : null,
2699
+ entry.trashed ? 1 : 0,
2700
+ entry.modifiedTime ?? null,
2701
+ entry.updatedAt ?? Date.now()
2702
+ );
2518
2703
  }
2519
2704
  this.db.exec("COMMIT;");
2520
2705
  } catch (e) {
@@ -2754,6 +2939,18 @@ var DriveKit = class _DriveKit {
2754
2939
  this.pluginManager.use(plugin);
2755
2940
  return this;
2756
2941
  }
2942
+ /**
2943
+ * Unregisters a middleware plugin by name
2944
+ */
2945
+ unuse(pluginName) {
2946
+ return this.pluginManager.unuse(pluginName);
2947
+ }
2948
+ /**
2949
+ * Access the underlying plugin manager instance
2950
+ */
2951
+ get plugins() {
2952
+ return this.pluginManager;
2953
+ }
2757
2954
  /**
2758
2955
  * Returns a fluent, chained reference to a specific file
2759
2956
  */
@@ -2772,7 +2969,8 @@ var DriveKit = class _DriveKit {
2772
2969
  async init() {
2773
2970
  if (!this.driveClient) {
2774
2971
  const auth = await this.authenticator.getAuthClient();
2775
- this.driveClient = (0, import_drive3.drive)({ version: "v3", auth });
2972
+ const agent = getOptimizedHttpsAgent();
2973
+ this.driveClient = (0, import_drive3.drive)({ version: "v3", auth, agent });
2776
2974
  if (this.options.enablePersistentCache !== false) {
2777
2975
  this.metadataCacheInstance = new SqliteMetadataCache(this.options.cacheDatabasePath);
2778
2976
  this.metadataCacheInstance.init();
@@ -2859,15 +3057,41 @@ var DriveKit = class _DriveKit {
2859
3057
  }
2860
3058
  }
2861
3059
  /**
2862
- * Lists contents of a folder (by folder ID or path)
3060
+ * Lists contents of a folder (by folder ID or path) with opportunistic tree caching
2863
3061
  */
2864
3062
  async ls(folderIdOrPath = "/") {
3063
+ let parentFolderId;
3064
+ let normalizedPath = null;
3065
+ let files;
2865
3066
  if (folderIdOrPath === "/" || folderIdOrPath === "root" || folderIdOrPath === this.rootFolderId) {
3067
+ parentFolderId = this.rootFolderId;
3068
+ normalizedPath = "/";
2866
3069
  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();
3070
+ files = await this.query().raw(parentFilter).notTrashed().orderBy("folder,name").list();
3071
+ } else {
3072
+ if (folderIdOrPath.startsWith("/")) {
3073
+ normalizedPath = folderIdOrPath.replace(/\/+$/, "") || "/";
3074
+ parentFolderId = await this.resolveId(normalizedPath);
3075
+ } else {
3076
+ parentFolderId = folderIdOrPath;
3077
+ }
3078
+ files = await this.query().inFolder(parentFolderId).notTrashed().orderBy("folder,name").list();
2868
3079
  }
2869
- const folderId = await this.resolveId(folderIdOrPath);
2870
- return await this.query().inFolder(folderId).notTrashed().orderBy("folder,name").list();
3080
+ if (this.metadataCacheInstance && files.length > 0) {
3081
+ const cacheEntries = files.filter((f) => !!f.id).map((f) => ({
3082
+ id: f.id,
3083
+ name: f.name || "untitled",
3084
+ mimeType: f.mimeType || "",
3085
+ size: f.size ? parseInt(f.size, 10) : void 0,
3086
+ parentId: parentFolderId,
3087
+ path: normalizedPath ? `${normalizedPath === "/" ? "" : normalizedPath}/${f.name}` : void 0,
3088
+ md5Checksum: f.md5Checksum || void 0,
3089
+ modifiedTime: f.modifiedTime || void 0,
3090
+ trashed: false
3091
+ }));
3092
+ this.metadataCacheInstance.upsertFiles(cacheEntries);
3093
+ }
3094
+ return files;
2871
3095
  }
2872
3096
  // ==========================================
2873
3097
  // FILE OPERATIONS (UPLOAD, DOWNLOAD, GET)
@@ -2886,7 +3110,7 @@ var DriveKit = class _DriveKit {
2886
3110
  if (parentId && parentId.startsWith("/")) {
2887
3111
  parentId = await this.mkdirp(parentId);
2888
3112
  }
2889
- const targetName = opts.name || opts.filename;
3113
+ const targetName = opts.name || opts.filename || (typeof opts.source === "string" ? import_node_path7.default.basename(opts.source) : void 0);
2890
3114
  if (opts.overwrite && targetName && parentId) {
2891
3115
  const existing = await this.query().inFolder(parentId).nameEquals(targetName).notTrashed().first();
2892
3116
  if (existing?.id) {
@@ -2942,12 +3166,14 @@ var DriveKit = class _DriveKit {
2942
3166
  parent: parentId
2943
3167
  });
2944
3168
  if (this.metadataCacheInstance && uploaded.id) {
3169
+ const virtualPath = typeof opts.parent === "string" && opts.parent.startsWith("/") ? `${opts.parent === "/" ? "" : opts.parent}/${uploaded.name || targetName || "untitled"}` : void 0;
2945
3170
  this.metadataCacheInstance.upsertFile({
2946
3171
  id: uploaded.id,
2947
3172
  name: uploaded.name || targetName || "untitled",
2948
3173
  mimeType: uploaded.mimeType || "",
2949
3174
  size: uploaded.size ? parseInt(uploaded.size, 10) : void 0,
2950
3175
  parentId,
3176
+ path: virtualPath,
2951
3177
  trashed: false
2952
3178
  });
2953
3179
  }
@@ -2958,16 +3184,25 @@ var DriveKit = class _DriveKit {
2958
3184
  * - Automatic conversion for Google Docs, Sheets, and Slides
2959
3185
  * - Progress events
2960
3186
  * - Saves directly to file or returns Readable Stream
3187
+ * - Leverages local metadata cache to bypass redundant Google API roundtrips
2961
3188
  */
2962
3189
  async download(fileIdOrPath, options = {}) {
2963
3190
  const fileId = await this.resolveId(fileIdOrPath);
2964
- const processedOpts = await this.pluginManager.runBeforeDownload(fileId, options);
3191
+ let cachedMeta = options.metadata;
3192
+ if (!cachedMeta && this.metadataCacheInstance) {
3193
+ const cached = this.metadataCacheInstance.getById(fileId);
3194
+ if (cached && cached.name && cached.mimeType) {
3195
+ cachedMeta = { name: cached.name, mimeType: cached.mimeType, size: cached.size };
3196
+ }
3197
+ }
3198
+ const mergedOpts = cachedMeta ? { ...options, metadata: cachedMeta } : options;
3199
+ const processedOpts = await this.pluginManager.runBeforeDownload(fileId, mergedOpts);
2965
3200
  const downloader = await this.getDownloader();
2966
3201
  const result = await downloader.download(fileId, processedOpts);
2967
3202
  return await this.pluginManager.runAfterDownload(result);
2968
3203
  }
2969
3204
  /**
2970
- * Gets file metadata
3205
+ * Gets file metadata and updates the local metadata cache
2971
3206
  */
2972
3207
  async getFile(fileIdOrPath) {
2973
3208
  const fileId = await this.resolveId(fileIdOrPath);
@@ -2979,7 +3214,20 @@ var DriveKit = class _DriveKit {
2979
3214
  supportsAllDrives: true
2980
3215
  });
2981
3216
  });
2982
- return res.data;
3217
+ const file = res.data;
3218
+ if (this.metadataCacheInstance && file.id) {
3219
+ this.metadataCacheInstance.upsertFile({
3220
+ id: file.id,
3221
+ name: file.name || "",
3222
+ mimeType: file.mimeType || "",
3223
+ size: file.size ? parseInt(file.size, 10) : void 0,
3224
+ parentId: file.parents?.[0],
3225
+ path: fileIdOrPath.startsWith("/") ? fileIdOrPath : void 0,
3226
+ modifiedTime: file.modifiedTime || void 0,
3227
+ trashed: file.trashed || false
3228
+ });
3229
+ }
3230
+ return file;
2983
3231
  }
2984
3232
  /**
2985
3233
  * Reads file content as UTF-8 string
@@ -3022,6 +3270,9 @@ var DriveKit = class _DriveKit {
3022
3270
  if (this.pathResolverInstance && fileIdOrPath.startsWith("/")) {
3023
3271
  this.pathResolverInstance.invalidatePath(fileIdOrPath);
3024
3272
  }
3273
+ if (this.metadataCacheInstance) {
3274
+ this.metadataCacheInstance.deleteFile(fileId);
3275
+ }
3025
3276
  }
3026
3277
  /**
3027
3278
  * Move item to trash
@@ -3063,6 +3314,16 @@ var DriveKit = class _DriveKit {
3063
3314
  if (this.pathResolverInstance) {
3064
3315
  this.pathResolverInstance.clearCache();
3065
3316
  }
3317
+ if (this.metadataCacheInstance) {
3318
+ const cached = this.metadataCacheInstance.getById(fileId);
3319
+ if (cached) {
3320
+ this.metadataCacheInstance.upsertFile({
3321
+ ...cached,
3322
+ parentId: newParentId,
3323
+ path: void 0
3324
+ });
3325
+ }
3326
+ }
3066
3327
  return res.data;
3067
3328
  }
3068
3329
  /**
@@ -3105,6 +3366,16 @@ var DriveKit = class _DriveKit {
3105
3366
  if (this.pathResolverInstance) {
3106
3367
  this.pathResolverInstance.clearCache();
3107
3368
  }
3369
+ if (this.metadataCacheInstance) {
3370
+ const cached = this.metadataCacheInstance.getById(fileId);
3371
+ if (cached) {
3372
+ this.metadataCacheInstance.upsertFile({
3373
+ ...cached,
3374
+ name: newName,
3375
+ path: void 0
3376
+ });
3377
+ }
3378
+ }
3108
3379
  return res.data;
3109
3380
  }
3110
3381
  // ==========================================
@@ -3382,7 +3653,7 @@ var DriveKit = class _DriveKit {
3382
3653
  async createWriteStream(remotePath, options = {}) {
3383
3654
  await this.init();
3384
3655
  const { PassThrough } = await import("stream");
3385
- const passThrough = new PassThrough();
3656
+ const passThrough = new PassThrough({ highWaterMark: 1024 * 1024 });
3386
3657
  let resolveDone;
3387
3658
  let rejectDone;
3388
3659
  const donePromise = new Promise((resolve, reject) => {
@@ -3429,6 +3700,12 @@ var DriveKit = class _DriveKit {
3429
3700
  // ==========================================
3430
3701
  // METADATA CACHE OPERATIONS
3431
3702
  // ==========================================
3703
+ /**
3704
+ * Synchronous getter for the active metadata cache instance
3705
+ */
3706
+ get cache() {
3707
+ return this.metadataCacheInstance;
3708
+ }
3432
3709
  /**
3433
3710
  * Returns the active persistent metadata cache instance (SQLite/Memory)
3434
3711
  */
@@ -3451,6 +3728,9 @@ var DriveKit = class _DriveKit {
3451
3728
  if (this.pathResolverInstance) {
3452
3729
  this.pathResolverInstance.clearCache();
3453
3730
  }
3731
+ if (this.metadataCacheInstance) {
3732
+ this.metadataCacheInstance.clear();
3733
+ }
3454
3734
  }
3455
3735
  /**
3456
3736
  * Crawls and indexes Google Drive metadata into the local SQLite database for instant 0ms lookups
@@ -3833,6 +4113,8 @@ var index_default = DriveKit;
3833
4113
  formatSpeed,
3834
4114
  getExtensionForMime,
3835
4115
  getFileIcon,
4116
+ getOptimizedHttpAgent,
4117
+ getOptimizedHttpsAgent,
3836
4118
  isGoogleWorkspaceDoc,
3837
4119
  isRetryableError,
3838
4120
  loginWithBrowser,