drivekit 1.1.0 → 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
@@ -40,23 +40,55 @@ var init_cjs_shims = __esm({
40
40
  // src/server/webdav.ts
41
41
  var webdav_exports = {};
42
42
  __export(webdav_exports, {
43
+ escapeXml: () => escapeXml,
43
44
  startWebDAVServer: () => startWebDAVServer
44
45
  });
46
+ function escapeXml(unsafe) {
47
+ return unsafe.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
48
+ }
45
49
  async function startWebDAVServer(drive2, options = {}) {
46
50
  const port = options.port || 8080;
47
51
  const host = options.host || "127.0.0.1";
48
52
  await drive2.init();
49
- const server = import_node_http2.default.createServer(async (req, res) => {
53
+ const server = import_node_http3.default.createServer(async (req, res) => {
50
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
+ }
51
76
  const parsedUrl = import_node_url.default.parse(req.url || "/", true);
52
77
  const decodedPath = decodeURIComponent(parsedUrl.pathname || "/");
53
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
+ }
54
85
  switch (req.method) {
55
86
  case "OPTIONS": {
56
87
  res.writeHead(200, {
57
88
  DAV: "1, 2",
58
89
  Allow: "OPTIONS, GET, HEAD, POST, PUT, DELETE, MKCOL, MOVE, COPY, PROPFIND",
59
- "MS-Author-Via": "DAV"
90
+ "MS-Author-Via": "DAV",
91
+ "Accept-Ranges": "bytes"
60
92
  });
61
93
  res.end();
62
94
  return;
@@ -64,6 +96,11 @@ async function startWebDAVServer(drive2, options = {}) {
64
96
  case "PROPFIND": {
65
97
  const depth = req.headers["depth"] || "1";
66
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
+ }
67
104
  res.writeHead(207, {
68
105
  "Content-Type": "application/xml; charset=utf-8"
69
106
  });
@@ -74,7 +111,7 @@ async function startWebDAVServer(drive2, options = {}) {
74
111
  case "HEAD": {
75
112
  if (virtualPath === "/" || virtualPath === "") {
76
113
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
77
- res.end("<h1>DriveKit WebDAV Server Running</h1><p>Connect via Finder or WebDAV client.</p>");
114
+ res.end("<h1>DriveKit WebDAV Server Running</h1><p>Connect via Finder, File Explorer, or WebDAV client.</p>");
78
115
  return;
79
116
  }
80
117
  try {
@@ -84,15 +121,42 @@ async function startWebDAVServer(drive2, options = {}) {
84
121
  res.end("Cannot GET a directory");
85
122
  return;
86
123
  }
87
- const stream = await drive2.createReadStream(virtualPath);
88
- res.writeHead(200, {
89
- "Content-Type": file.mimeType || "application/octet-stream",
90
- "Content-Length": file.size || void 0
91
- });
92
- if (req.method === "HEAD") {
93
- res.end();
124
+ const fileSize = file.size ? parseInt(file.size, 10) : void 0;
125
+ const rangeHeader = req.headers["range"];
126
+ if (rangeHeader && rangeHeader.startsWith("bytes=") && fileSize !== void 0) {
127
+ const parts = rangeHeader.replace("bytes=", "").split("-");
128
+ const start = parseInt(parts[0], 10);
129
+ const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
130
+ if (isNaN(start) || start >= fileSize || end !== void 0 && end >= fileSize) {
131
+ res.writeHead(416, { "Content-Range": `bytes */${fileSize}` });
132
+ res.end();
133
+ return;
134
+ }
135
+ const stream = await drive2.createReadStream(virtualPath, { start, end });
136
+ const chunkLength = end - start + 1;
137
+ res.writeHead(206, {
138
+ "Content-Type": file.mimeType || "application/octet-stream",
139
+ "Content-Range": `bytes ${start}-${end}/${fileSize}`,
140
+ "Content-Length": chunkLength,
141
+ "Accept-Ranges": "bytes"
142
+ });
143
+ if (req.method === "HEAD") {
144
+ res.end();
145
+ } else {
146
+ stream.pipe(res);
147
+ }
94
148
  } else {
95
- stream.pipe(res);
149
+ const stream = await drive2.createReadStream(virtualPath);
150
+ res.writeHead(200, {
151
+ "Content-Type": file.mimeType || "application/octet-stream",
152
+ "Content-Length": file.size || void 0,
153
+ "Accept-Ranges": "bytes"
154
+ });
155
+ if (req.method === "HEAD") {
156
+ res.end();
157
+ } else {
158
+ stream.pipe(res);
159
+ }
96
160
  }
97
161
  } catch (e) {
98
162
  res.writeHead(404, { "Content-Type": "text/plain" });
@@ -101,27 +165,29 @@ async function startWebDAVServer(drive2, options = {}) {
101
165
  return;
102
166
  }
103
167
  case "PUT": {
104
- const remoteDir = import_node_path5.default.dirname(virtualPath);
105
- const fileName = import_node_path5.default.basename(virtualPath);
168
+ const remoteDir = import_node_path6.default.dirname(virtualPath);
106
169
  await drive2.mkdirp(remoteDir);
107
- const chunks = [];
108
- req.on("data", (chunk) => chunks.push(chunk));
109
- req.on("end", async () => {
110
- try {
111
- const buffer = Buffer.concat(chunks);
112
- await drive2.upload({
113
- source: buffer,
114
- filename: fileName,
115
- parent: remoteDir,
116
- overwrite: true
117
- });
118
- res.writeHead(201, { "Content-Type": "text/plain" });
119
- res.end("Created");
120
- } catch (err) {
121
- res.writeHead(500, { "Content-Type": "text/plain" });
122
- res.end(err.message || "Upload failed");
170
+ let existed = false;
171
+ try {
172
+ const existingFile = await drive2.getFile(virtualPath);
173
+ if (existingFile && existingFile.id) {
174
+ existed = true;
123
175
  }
124
- });
176
+ } catch {
177
+ existed = false;
178
+ }
179
+ try {
180
+ const uploadStream = await drive2.createWriteStream(virtualPath, {
181
+ overwrite: true
182
+ });
183
+ req.pipe(uploadStream);
184
+ await uploadStream.done;
185
+ res.writeHead(existed ? 204 : 201, { "Content-Type": "text/plain" });
186
+ res.end(existed ? "" : "Created");
187
+ } catch (err) {
188
+ res.writeHead(500, { "Content-Type": "text/plain" });
189
+ res.end(err.message || "Upload failed");
190
+ }
125
191
  return;
126
192
  }
127
193
  case "MKCOL": {
@@ -153,14 +219,24 @@ async function startWebDAVServer(drive2, options = {}) {
153
219
  res.end("Destination header missing");
154
220
  return;
155
221
  }
156
- const destUrl = import_node_url.default.parse(destination);
157
- const destPath = decodeURIComponent(destUrl.pathname || "");
158
- const newName = import_node_path5.default.basename(destPath);
159
- const newParent = import_node_path5.default.dirname(destPath);
160
222
  try {
161
- await drive2.move(virtualPath, newParent);
162
- if (newName !== import_node_path5.default.basename(virtualPath)) {
163
- await drive2.rename(destPath, newName);
223
+ const file = await drive2.getFile(virtualPath);
224
+ if (!file?.id) {
225
+ res.writeHead(404, { "Content-Type": "text/plain" });
226
+ res.end("Source file not found");
227
+ return;
228
+ }
229
+ const destUrl = import_node_url.default.parse(destination);
230
+ const destPath = decodeURIComponent(destUrl.pathname || "");
231
+ const newName = import_node_path6.default.basename(destPath);
232
+ const newParentDir = import_node_path6.default.dirname(destPath);
233
+ const newParentFolderId = await drive2.mkdirp(newParentDir);
234
+ const currentParentDir = import_node_path6.default.dirname(virtualPath);
235
+ if (newParentDir !== currentParentDir) {
236
+ await drive2.move(file.id, newParentFolderId);
237
+ }
238
+ if (newName !== import_node_path6.default.basename(virtualPath)) {
239
+ await drive2.rename(file.id, newName);
164
240
  }
165
241
  res.writeHead(201);
166
242
  res.end("Moved");
@@ -170,6 +246,34 @@ async function startWebDAVServer(drive2, options = {}) {
170
246
  }
171
247
  return;
172
248
  }
249
+ case "COPY": {
250
+ const destination = req.headers["destination"];
251
+ if (!destination || typeof destination !== "string") {
252
+ res.writeHead(400, { "Content-Type": "text/plain" });
253
+ res.end("Destination header missing");
254
+ return;
255
+ }
256
+ try {
257
+ const file = await drive2.getFile(virtualPath);
258
+ if (!file?.id) {
259
+ res.writeHead(404, { "Content-Type": "text/plain" });
260
+ res.end("Source file not found");
261
+ return;
262
+ }
263
+ const destUrl = import_node_url.default.parse(destination);
264
+ const destPath = decodeURIComponent(destUrl.pathname || "");
265
+ const newName = import_node_path6.default.basename(destPath);
266
+ const newParentDir = import_node_path6.default.dirname(destPath);
267
+ const newParentFolderId = await drive2.mkdirp(newParentDir);
268
+ await drive2.copy(file.id, { parent: newParentFolderId, name: newName });
269
+ res.writeHead(201);
270
+ res.end("Copied");
271
+ } catch (err) {
272
+ res.writeHead(500, { "Content-Type": "text/plain" });
273
+ res.end(err.message);
274
+ }
275
+ return;
276
+ }
173
277
  default: {
174
278
  res.writeHead(501, { "Content-Type": "text/plain" });
175
279
  res.end("Method Not Implemented");
@@ -207,25 +311,38 @@ async function handlePropfind(drive2, virtualPath, depth) {
207
311
  virtualPath,
208
312
  isFolder,
209
313
  selfItem.size ? parseInt(selfItem.size, 10) : 0,
210
- selfItem.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
314
+ selfItem.modifiedTime || (/* @__PURE__ */ new Date()).toISOString(),
315
+ selfItem.mimeType || void 0
211
316
  )
212
317
  );
213
318
  } catch {
214
- return `<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:"></D:multistatus>`;
319
+ return null;
215
320
  }
216
321
  }
217
322
  if (isFolder && depth !== "0") {
218
323
  try {
219
324
  const children = await drive2.ls(virtualPath);
325
+ const seenNames = /* @__PURE__ */ new Map();
220
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
+ }
221
337
  const childIsFolder = child.mimeType === "application/vnd.google-apps.folder";
222
- const childPath = virtualPath === "/" ? `/${child.name}` : `${virtualPath}/${child.name}`;
338
+ const childPath = virtualPath === "/" ? `/${childName}` : `${virtualPath}/${childName}`;
223
339
  responses.push(
224
340
  renderWebDAVResponse(
225
341
  childPath,
226
342
  childIsFolder,
227
343
  child.size ? parseInt(child.size, 10) : 0,
228
- child.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
344
+ child.modifiedTime || (/* @__PURE__ */ new Date()).toISOString(),
345
+ child.mimeType || void 0
229
346
  )
230
347
  );
231
348
  }
@@ -237,32 +354,38 @@ async function handlePropfind(drive2, virtualPath, depth) {
237
354
  ${responses.join("\n")}
238
355
  </D:multistatus>`;
239
356
  }
240
- function renderWebDAVResponse(href, isDir, size, modifiedTime) {
241
- 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);
363
+ const displayName = escapeXml(import_node_path6.default.basename(href) || "root");
242
364
  const resourceType = isDir ? "<D:collection/>" : "";
243
365
  const dateFormatted = new Date(modifiedTime).toUTCString();
366
+ const contentTypeTag = !isDir && mimeType ? `
367
+ <D:getcontenttype>${escapeXml(mimeType)}</D:getcontenttype>` : "";
244
368
  return ` <D:response>
245
369
  <D:href>${encodedHref}</D:href>
246
370
  <D:propstat>
247
371
  <D:prop>
248
- <D:displayname>${import_node_path5.default.basename(href) || "root"}</D:displayname>
372
+ <D:displayname>${displayName}</D:displayname>
249
373
  <D:resourcetype>${resourceType}</D:resourcetype>
250
374
  <D:getcontentlength>${isDir ? "0" : size}</D:getcontentlength>
251
- <D:getlastmodified>${dateFormatted}</D:getlastmodified>
252
- <D:status>HTTP/1.1 200 OK</D:status>
375
+ <D:getlastmodified>${dateFormatted}</D:getlastmodified>${contentTypeTag}
253
376
  </D:prop>
254
377
  <D:status>HTTP/1.1 200 OK</D:status>
255
378
  </D:propstat>
256
379
  </D:response>`;
257
380
  }
258
- var import_node_http2, import_node_url, import_node_path5;
381
+ var import_node_http3, import_node_url, import_node_path6;
259
382
  var init_webdav = __esm({
260
383
  "src/server/webdav.ts"() {
261
384
  "use strict";
262
385
  init_cjs_shims();
263
- import_node_http2 = __toESM(require("http"), 1);
386
+ import_node_http3 = __toESM(require("http"), 1);
264
387
  import_node_url = __toESM(require("url"), 1);
265
- import_node_path5 = __toESM(require("path"), 1);
388
+ import_node_path6 = __toESM(require("path"), 1);
266
389
  }
267
390
  });
268
391
 
@@ -300,11 +423,14 @@ __export(index_exports, {
300
423
  createDrive: () => createDrive,
301
424
  createWebhookPlugin: () => createWebhookPlugin,
302
425
  default: () => index_default,
426
+ escapeXml: () => escapeXml,
303
427
  formatBytes: () => formatBytes,
304
428
  formatDuration: () => formatDuration,
305
429
  formatSpeed: () => formatSpeed,
306
430
  getExtensionForMime: () => getExtensionForMime,
307
431
  getFileIcon: () => getFileIcon,
432
+ getOptimizedHttpAgent: () => getOptimizedHttpAgent,
433
+ getOptimizedHttpsAgent: () => getOptimizedHttpsAgent,
308
434
  isGoogleWorkspaceDoc: () => isGoogleWorkspaceDoc,
309
435
  isRetryableError: () => isRetryableError,
310
436
  loginWithBrowser: () => loginWithBrowser,
@@ -321,7 +447,7 @@ init_cjs_shims();
321
447
  // src/core/client.ts
322
448
  init_cjs_shims();
323
449
  var import_node_fs6 = __toESM(require("fs"), 1);
324
- var import_node_path6 = __toESM(require("path"), 1);
450
+ var import_node_path7 = __toESM(require("path"), 1);
325
451
  var import_drive3 = require("@googleapis/drive");
326
452
 
327
453
  // src/auth/authenticator.ts
@@ -375,6 +501,39 @@ var DriveUploadError = class extends DriveKitError {
375
501
  }
376
502
  };
377
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
+
378
537
  // src/auth/authenticator.ts
379
538
  var DEFAULT_SCOPES = [
380
539
  "https://www.googleapis.com/auth/drive"
@@ -398,44 +557,39 @@ var DriveAuthenticator = class {
398
557
  const oauth2Client = new import_drive.auth.OAuth2();
399
558
  oauth2Client.setCredentials({ access_token: this.config.accessToken });
400
559
  this.authClient = oauth2Client;
401
- return this.authClient;
402
- }
403
- if (this.config.oauth2Client) {
560
+ } else if (this.config.oauth2Client) {
404
561
  this.authClient = this.config.oauth2Client;
405
- return this.authClient;
406
- }
407
- if (this.config.oauth) {
562
+ } else if (this.config.oauth) {
408
563
  const { clientId, clientSecret, redirectUri = "http://localhost:3000/oauth2callback", refreshToken } = this.config.oauth;
409
564
  const oauth2Client = new import_drive.auth.OAuth2(clientId, clientSecret, redirectUri);
410
565
  if (refreshToken) {
411
566
  oauth2Client.setCredentials({ refresh_token: refreshToken });
412
567
  }
413
568
  this.authClient = oauth2Client;
414
- return this.authClient;
415
- }
416
- const keyFile = this.config.keyFilePath || process.env.GDRIVE_SERVICE_ACCOUNT_PATH || process.env.GOOGLE_APPLICATION_CREDENTIALS;
417
- if (keyFile) {
418
- 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)) {
419
572
  throw new DriveAuthError(`Service account file not found at: ${keyFile}`);
420
573
  }
421
- const auth2 = new import_drive.auth.GoogleAuth({
574
+ const auth = new import_drive.auth.GoogleAuth({
422
575
  keyFile,
423
576
  scopes
424
577
  });
425
- this.authClient = auth2;
426
- return this.authClient;
427
- }
428
- const creds = this.config.credentials || (process.env.GDRIVE_CREDENTIALS_JSON ? JSON.parse(process.env.GDRIVE_CREDENTIALS_JSON) : null);
429
- if (creds) {
430
- 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({
431
582
  credentials: creds,
432
583
  scopes
433
584
  });
434
- this.authClient = auth2;
435
- 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();
436
592
  }
437
- const auth = new import_drive.auth.GoogleAuth({ scopes });
438
- this.authClient = auth;
439
593
  return this.authClient;
440
594
  } catch (err) {
441
595
  if (err instanceof DriveAuthError) throw err;
@@ -574,6 +728,7 @@ var PathResolver = class {
574
728
  drive;
575
729
  rootFolderId;
576
730
  cache = /* @__PURE__ */ new Map();
731
+ inFlightResolves = /* @__PURE__ */ new Map();
577
732
  cacheTTL;
578
733
  enableCache;
579
734
  metadataCache;
@@ -597,8 +752,8 @@ var PathResolver = class {
597
752
  /**
598
753
  * Gets cache key for a path
599
754
  */
600
- getCacheKey(path7) {
601
- return `${this.rootFolderId}:${this.normalizePath(path7)}`;
755
+ getCacheKey(path8) {
756
+ return `${this.rootFolderId}:${this.normalizePath(path8)}`;
602
757
  }
603
758
  /**
604
759
  * Clears the path cache
@@ -612,8 +767,8 @@ var PathResolver = class {
612
767
  /**
613
768
  * Invalidate a single path from cache
614
769
  */
615
- invalidatePath(path7) {
616
- const norm = this.normalizePath(path7);
770
+ invalidatePath(path8) {
771
+ const norm = this.normalizePath(path8);
617
772
  const key = this.getCacheKey(norm);
618
773
  this.cache.delete(key);
619
774
  if (this.metadataCache) {
@@ -626,6 +781,7 @@ var PathResolver = class {
626
781
  /**
627
782
  * Resolves a path to a Google Drive item (file or folder).
628
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.
629
785
  */
630
786
  async resolve(virtualPath, options = {}) {
631
787
  const norm = this.normalizePath(virtualPath);
@@ -659,6 +815,20 @@ var PathResolver = class {
659
815
  };
660
816
  }
661
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) {
662
832
  const segments = norm.split("/").filter(Boolean);
663
833
  let currentParentId = this.rootFolderId;
664
834
  let currentPath = "";
@@ -710,7 +880,7 @@ var PathResolver = class {
710
880
  });
711
881
  let file = response.data.files?.[0];
712
882
  if (!file && currentParentId === this.rootFolderId) {
713
- const sharedQ = `name = '${escapedName}' and trashed = false`;
883
+ const sharedQ = `name = '${escapedName}' and sharedWithMe = true and trashed = false`;
714
884
  const sharedResponse = await withRetry(async () => {
715
885
  return await this.drive.files.list({
716
886
  q: sharedQ,
@@ -724,13 +894,14 @@ var PathResolver = class {
724
894
  file = sharedResponse.data.files?.[0];
725
895
  }
726
896
  if (file && file.id) {
897
+ const segmentParentId = currentParentId;
727
898
  currentParentId = file.id;
728
899
  if (this.metadataCache) {
729
900
  this.metadataCache.upsertFile({
730
901
  id: file.id,
731
902
  name: file.name || segment,
732
903
  mimeType: file.mimeType || "",
733
- parentId: currentParentId,
904
+ parentId: segmentParentId,
734
905
  path: currentPath,
735
906
  trashed: false
736
907
  });
@@ -768,13 +939,14 @@ var PathResolver = class {
768
939
  if (!newFolder.id) {
769
940
  throw new Error(`Failed to create folder "${segment}" under parent "${currentParentId}"`);
770
941
  }
942
+ const segmentParentId = currentParentId;
771
943
  currentParentId = newFolder.id;
772
944
  if (this.metadataCache) {
773
945
  this.metadataCache.upsertFile({
774
946
  id: newFolder.id,
775
947
  name: segment,
776
948
  mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
777
- parentId: currentParentId,
949
+ parentId: segmentParentId,
778
950
  path: currentPath,
779
951
  trashed: false
780
952
  });
@@ -818,6 +990,7 @@ var PathResolver = class {
818
990
  init_cjs_shims();
819
991
  var import_node_fs2 = __toESM(require("fs"), 1);
820
992
  var import_node_path = __toESM(require("path"), 1);
993
+ var import_node_stream = require("stream");
821
994
 
822
995
  // src/utils/format.ts
823
996
  init_cjs_shims();
@@ -882,6 +1055,15 @@ var ResumableUploader = class {
882
1055
  const totalBytes = stat.size;
883
1056
  const fileName = options.name || import_node_path.default.basename(filePath);
884
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
+ }
885
1067
  return await this.chunkedUpload({
886
1068
  filePath,
887
1069
  totalBytes,
@@ -897,6 +1079,16 @@ var ResumableUploader = class {
897
1079
  const totalBytes = buffer.length;
898
1080
  const fileName = options.name || "untitled";
899
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
+ }
900
1092
  return await this.chunkedUploadBuffer({
901
1093
  buffer,
902
1094
  totalBytes,
@@ -917,6 +1109,50 @@ var ResumableUploader = class {
917
1109
  mimeType
918
1110
  });
919
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
+ }
920
1156
  /**
921
1157
  * Fast direct upload using googleapis multipart
922
1158
  */
@@ -949,7 +1185,7 @@ var ResumableUploader = class {
949
1185
  */
950
1186
  async chunkedUpload(params) {
951
1187
  const { filePath, totalBytes, fileName, mimeType, options } = params;
952
- 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);
953
1189
  const sessionUrl = await this.initiateResumableSession({
954
1190
  fileName,
955
1191
  mimeType,
@@ -1014,7 +1250,7 @@ var ResumableUploader = class {
1014
1250
  */
1015
1251
  async chunkedUploadBuffer(params) {
1016
1252
  const { buffer, totalBytes, fileName, mimeType, options } = params;
1017
- 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);
1018
1254
  const sessionUrl = await this.initiateResumableSession({
1019
1255
  fileName,
1020
1256
  mimeType,
@@ -1093,7 +1329,8 @@ var ResumableUploader = class {
1093
1329
  url: "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&supportsAllDrives=true",
1094
1330
  method: "POST",
1095
1331
  headers,
1096
- data: metadata
1332
+ data: metadata,
1333
+ agent: getOptimizedHttpsAgent()
1097
1334
  });
1098
1335
  });
1099
1336
  const sessionUrl = res.headers?.get ? res.headers.get("location") : res.headers?.location || res.headers?.["location"];
@@ -1119,6 +1356,7 @@ var ResumableUploader = class {
1119
1356
  method: "PUT",
1120
1357
  headers,
1121
1358
  data: buffer,
1359
+ agent: getOptimizedHttpsAgent(),
1122
1360
  validateStatus: (status) => status >= 200 && status < 300 || status === 308
1123
1361
  });
1124
1362
  if (res.status === 200 || res.status === 201) {
@@ -1152,7 +1390,7 @@ init_cjs_shims();
1152
1390
  var import_node_fs3 = __toESM(require("fs"), 1);
1153
1391
  var import_node_path2 = __toESM(require("path"), 1);
1154
1392
  var import_promises = require("stream/promises");
1155
- var import_node_stream = require("stream");
1393
+ var import_node_stream2 = require("stream");
1156
1394
  var Downloader = class {
1157
1395
  drive;
1158
1396
  constructor(drive2) {
@@ -1162,17 +1400,22 @@ var Downloader = class {
1162
1400
  * Downloads a file from Google Drive to local destination path or returns a readable stream.
1163
1401
  */
1164
1402
  async download(fileId, options = {}) {
1165
- const metaRes = await withRetry(async () => {
1166
- return await this.drive.files.get({
1167
- fileId,
1168
- fields: "id, name, mimeType, size",
1169
- 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
+ });
1170
1413
  });
1171
- });
1172
- const file = metaRes.data;
1173
- const name = file.name || "downloaded-file";
1174
- const mimeType = file.mimeType || "application/octet-stream";
1175
- 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
+ }
1176
1419
  let downloadStream;
1177
1420
  let finalFileName = name;
1178
1421
  if (isGoogleWorkspaceDoc(mimeType)) {
@@ -1203,7 +1446,7 @@ var Downloader = class {
1203
1446
  }
1204
1447
  let bytesRead = 0;
1205
1448
  const startTime = Date.now();
1206
- const progressTracker = new import_node_stream.Transform({
1449
+ const progressTracker = new import_node_stream2.Transform({
1207
1450
  transform(chunk, encoding, callback) {
1208
1451
  bytesRead += chunk.length;
1209
1452
  if (options.onProgress) {
@@ -1228,7 +1471,7 @@ var Downloader = class {
1228
1471
  destPath = import_node_path2.default.join(destPath, finalFileName);
1229
1472
  }
1230
1473
  await import_node_fs3.default.promises.mkdir(import_node_path2.default.dirname(destPath), { recursive: true });
1231
- const writeStream = import_node_fs3.default.createWriteStream(destPath);
1474
+ const writeStream = import_node_fs3.default.createWriteStream(destPath, { highWaterMark: 1024 * 1024 });
1232
1475
  await (0, import_promises.pipeline)(monitoredStream, writeStream);
1233
1476
  return {
1234
1477
  filePath: destPath,
@@ -1471,6 +1714,7 @@ var DriveQueryBuilder = class {
1471
1714
  const q = this.toQueryString();
1472
1715
  const orderBy = this.orderClauses.join(", ");
1473
1716
  let pageToken = void 0;
1717
+ const effectiveFields = this.requestedFields.includes("nextPageToken") ? this.requestedFields : `nextPageToken, ${this.requestedFields}`;
1474
1718
  do {
1475
1719
  const res = await withRetry(async () => {
1476
1720
  return await this.drive.files.list({
@@ -1478,7 +1722,7 @@ var DriveQueryBuilder = class {
1478
1722
  orderBy: orderBy || void 0,
1479
1723
  pageSize: this.limitNumber,
1480
1724
  pageToken,
1481
- fields: this.requestedFields,
1725
+ fields: effectiveFields,
1482
1726
  spaces: this.spaces,
1483
1727
  supportsAllDrives: true,
1484
1728
  includeItemsFromAllDrives: true
@@ -1602,7 +1846,7 @@ var DriveWatcher = class extends import_node_events.EventEmitter {
1602
1846
  const res = await withRetry(async () => {
1603
1847
  return await this.drive.changes.list({
1604
1848
  pageToken: nextPageToken,
1605
- 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))",
1606
1850
  supportsAllDrives: true,
1607
1851
  includeItemsFromAllDrives: true
1608
1852
  });
@@ -1693,16 +1937,24 @@ var StorageCleaner = class {
1693
1937
  async findDuplicates(options = {}) {
1694
1938
  const mode = options.by || "name";
1695
1939
  const maxScan = options.maxScan || 1e3;
1696
- const res = await withRetry(async () => {
1697
- return await this.drive.files.list({
1698
- q: 'trashed = false and mimeType != "application/vnd.google-apps.folder"',
1699
- pageSize: Math.min(1e3, maxScan),
1700
- fields: "files(id, name, size, md5Checksum, modifiedTime)",
1701
- supportsAllDrives: true,
1702
- 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
+ });
1703
1954
  });
1704
- });
1705
- const files = res.data.files || [];
1955
+ files.push(...res.data.files || []);
1956
+ pageToken = res.data.nextPageToken || void 0;
1957
+ } while (pageToken && files.length < maxScan);
1706
1958
  const map = /* @__PURE__ */ new Map();
1707
1959
  for (const f of files) {
1708
1960
  if (!f.id) continue;
@@ -1877,7 +2129,7 @@ var SmartSyncEngine = class {
1877
2129
 
1878
2130
  // src/auth/browser-login.ts
1879
2131
  init_cjs_shims();
1880
- var import_node_http = __toESM(require("http"), 1);
2132
+ var import_node_http2 = __toESM(require("http"), 1);
1881
2133
  var import_node_child_process = require("child_process");
1882
2134
  var import_drive2 = require("@googleapis/drive");
1883
2135
  async function loginWithBrowser(options) {
@@ -1895,7 +2147,7 @@ async function loginWithBrowser(options) {
1895
2147
  scope: scopes
1896
2148
  });
1897
2149
  return new Promise((resolve, reject) => {
1898
- const server = import_node_http.default.createServer(async (req, res) => {
2150
+ const server = import_node_http2.default.createServer(async (req, res) => {
1899
2151
  try {
1900
2152
  const reqUrl = new URL(req.url || "/", `http://localhost:${port}`);
1901
2153
  if (reqUrl.pathname === "/oauth2callback") {
@@ -1979,7 +2231,11 @@ ${authUrl}
1979
2231
  });
1980
2232
  });
1981
2233
  server.on("error", (err) => {
1982
- 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
+ }
1983
2239
  });
1984
2240
  });
1985
2241
  }
@@ -2112,12 +2368,39 @@ var DriveFolderRef = class {
2112
2368
 
2113
2369
  // src/core/plugins.ts
2114
2370
  init_cjs_shims();
2371
+ var import_node_path4 = __toESM(require("path"), 1);
2115
2372
  var PluginManager = class {
2116
2373
  plugins = [];
2374
+ /**
2375
+ * Register a plugin. If a plugin with the same name already exists,
2376
+ * it replaces the old one to avoid duplicate side-effects.
2377
+ */
2117
2378
  use(plugin) {
2379
+ this.plugins = this.plugins.filter((p) => p.name !== plugin.name);
2118
2380
  this.plugins.push(plugin);
2119
2381
  return this;
2120
2382
  }
2383
+ /**
2384
+ * Unregister a plugin by its name.
2385
+ * Returns true if a plugin was found and removed, false otherwise.
2386
+ */
2387
+ unuse(pluginName) {
2388
+ const initialLen = this.plugins.length;
2389
+ this.plugins = this.plugins.filter((p) => p.name !== pluginName);
2390
+ return this.plugins.length < initialLen;
2391
+ }
2392
+ /**
2393
+ * Check if a plugin with given name is currently active
2394
+ */
2395
+ has(pluginName) {
2396
+ return this.plugins.some((p) => p.name === pluginName);
2397
+ }
2398
+ /**
2399
+ * Returns all currently registered plugins
2400
+ */
2401
+ getPlugins() {
2402
+ return [...this.plugins];
2403
+ }
2121
2404
  async runBeforeUpload(options) {
2122
2405
  let current = { ...options };
2123
2406
  for (const plugin of this.plugins) {
@@ -2161,45 +2444,62 @@ var PluginManager = class {
2161
2444
  };
2162
2445
  function createWebhookPlugin(options) {
2163
2446
  const events = options.events || ["upload"];
2164
- return {
2165
- name: "drivekit-official-webhook",
2166
- async afterUpload(file) {
2167
- if (!events.includes("upload")) return;
2447
+ const timeoutMs = options.timeout ?? 5e3;
2448
+ const maxRetries = options.retries ?? 0;
2449
+ const sendWebhook = async (event, payload) => {
2450
+ let lastError = null;
2451
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
2452
+ let timeoutId;
2453
+ const controller = new AbortController();
2454
+ timeoutId = setTimeout(() => controller.abort(), timeoutMs);
2168
2455
  try {
2169
- await fetch(options.url, {
2456
+ const res = await fetch(options.url, {
2170
2457
  method: "POST",
2171
2458
  headers: { "Content-Type": "application/json", ...options.headers || {} },
2172
- body: JSON.stringify({
2173
- event: "drivekit:upload",
2174
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2175
- file: {
2176
- id: file.id,
2177
- name: file.name,
2178
- size: file.size,
2179
- mimeType: file.mimeType
2180
- }
2181
- })
2459
+ body: JSON.stringify(payload),
2460
+ signal: controller.signal
2182
2461
  });
2183
- } catch (e) {
2462
+ clearTimeout(timeoutId);
2463
+ if (!res.ok) {
2464
+ throw new Error(`Webhook returned HTTP ${res.status}: ${res.statusText}`);
2465
+ }
2466
+ return;
2467
+ } catch (err) {
2468
+ clearTimeout(timeoutId);
2469
+ lastError = err;
2470
+ if (attempt === maxRetries) {
2471
+ if (options.onError) {
2472
+ options.onError(lastError instanceof Error ? lastError : new Error(String(lastError)), event);
2473
+ }
2474
+ }
2184
2475
  }
2476
+ }
2477
+ };
2478
+ return {
2479
+ name: "drivekit-official-webhook",
2480
+ async afterUpload(file) {
2481
+ if (!events.includes("upload")) return;
2482
+ await sendWebhook("upload", {
2483
+ event: "drivekit:upload",
2484
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2485
+ file: {
2486
+ id: file.id,
2487
+ name: file.name,
2488
+ size: file.size,
2489
+ mimeType: file.mimeType
2490
+ }
2491
+ });
2185
2492
  },
2186
2493
  async afterDownload(result) {
2187
2494
  if (!events.includes("download")) return;
2188
- try {
2189
- await fetch(options.url, {
2190
- method: "POST",
2191
- headers: { "Content-Type": "application/json", ...options.headers || {} },
2192
- body: JSON.stringify({
2193
- event: "drivekit:download",
2194
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2195
- file: {
2196
- name: result.name,
2197
- size: result.size
2198
- }
2199
- })
2200
- });
2201
- } catch (e) {
2202
- }
2495
+ await sendWebhook("download", {
2496
+ event: "drivekit:download",
2497
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2498
+ file: {
2499
+ name: result.name,
2500
+ size: result.size
2501
+ }
2502
+ });
2203
2503
  }
2204
2504
  };
2205
2505
  }
@@ -2207,15 +2507,13 @@ function createAutoNamePlugin(options) {
2207
2507
  return {
2208
2508
  name: "drivekit-official-autoname",
2209
2509
  beforeUpload(opts) {
2210
- let name = opts.filename;
2510
+ let name = opts.name || opts.filename;
2211
2511
  if (!name && typeof opts.source === "string") {
2212
- const pathModule2 = require("path");
2213
- name = pathModule2.basename(opts.source);
2512
+ name = import_node_path4.default.basename(opts.source);
2214
2513
  }
2215
2514
  if (!name) return opts;
2216
- const pathModule = require("path");
2217
- const ext = pathModule.extname(name);
2218
- const base = pathModule.basename(name, ext);
2515
+ const ext = import_node_path4.default.extname(name);
2516
+ const base = import_node_path4.default.basename(name, ext);
2219
2517
  let finalName = base;
2220
2518
  if (options.prefix) finalName = `${options.prefix}${finalName}`;
2221
2519
  if (options.appendTimestamp) {
@@ -2225,6 +2523,7 @@ function createAutoNamePlugin(options) {
2225
2523
  finalName = `${finalName}${ext}`;
2226
2524
  return {
2227
2525
  ...opts,
2526
+ name: finalName,
2228
2527
  filename: finalName
2229
2528
  };
2230
2529
  }
@@ -2234,7 +2533,7 @@ function createAutoNamePlugin(options) {
2234
2533
  // src/core/cache.ts
2235
2534
  init_cjs_shims();
2236
2535
  var import_node_os = __toESM(require("os"), 1);
2237
- var import_node_path4 = __toESM(require("path"), 1);
2536
+ var import_node_path5 = __toESM(require("path"), 1);
2238
2537
  var import_node_fs5 = __toESM(require("fs"), 1);
2239
2538
  var SqliteMetadataCache = class {
2240
2539
  db = null;
@@ -2245,14 +2544,14 @@ var SqliteMetadataCache = class {
2245
2544
  if (customPath) {
2246
2545
  this.dbPath = customPath;
2247
2546
  } else {
2248
- const dir = import_node_path4.default.join(import_node_os.default.homedir(), ".drivekit");
2547
+ const dir = import_node_path5.default.join(import_node_os.default.homedir(), ".drivekit");
2249
2548
  if (!import_node_fs5.default.existsSync(dir)) {
2250
2549
  try {
2251
2550
  import_node_fs5.default.mkdirSync(dir, { recursive: true });
2252
2551
  } catch {
2253
2552
  }
2254
2553
  }
2255
- this.dbPath = import_node_path4.default.join(dir, "cache.db");
2554
+ this.dbPath = import_node_path5.default.join(dir, "cache.db");
2256
2555
  }
2257
2556
  }
2258
2557
  init() {
@@ -2270,7 +2569,7 @@ var SqliteMetadataCache = class {
2270
2569
  CREATE TABLE IF NOT EXISTS files (
2271
2570
  id TEXT PRIMARY KEY,
2272
2571
  name TEXT NOT NULL,
2273
- mimeType TEXT NOT NULL,
2572
+ mimeType TEXT,
2274
2573
  size INTEGER,
2275
2574
  parentId TEXT,
2276
2575
  path TEXT,
@@ -2356,7 +2655,7 @@ var SqliteMetadataCache = class {
2356
2655
  stmt.run(
2357
2656
  entry.id,
2358
2657
  entry.name,
2359
- entry.mimeType,
2658
+ entry.mimeType ?? null,
2360
2659
  entry.size ?? null,
2361
2660
  entry.parentId ?? null,
2362
2661
  entry.path ?? null,
@@ -2372,10 +2671,35 @@ var SqliteMetadataCache = class {
2372
2671
  return;
2373
2672
  }
2374
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
+ `);
2375
2688
  this.db.exec("BEGIN TRANSACTION;");
2376
2689
  try {
2377
2690
  for (const entry of entries) {
2378
- 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
+ );
2379
2703
  }
2380
2704
  this.db.exec("COMMIT;");
2381
2705
  } catch (e) {
@@ -2392,6 +2716,30 @@ var SqliteMetadataCache = class {
2392
2716
  const stmt = this.db.prepare("DELETE FROM files WHERE id = ?");
2393
2717
  stmt.run(id);
2394
2718
  }
2719
+ pruneMissing(activeIds) {
2720
+ if (this.fallbackMemory) {
2721
+ return this.fallbackMemory.pruneMissing(activeIds);
2722
+ }
2723
+ if (!this.initialized || !this.db || activeIds.length === 0) return 0;
2724
+ const idSet = new Set(activeIds);
2725
+ const rows = this.db.prepare("SELECT id FROM files").all();
2726
+ let pruned = 0;
2727
+ this.db.exec("BEGIN TRANSACTION;");
2728
+ try {
2729
+ const deleteStmt = this.db.prepare("DELETE FROM files WHERE id = ?");
2730
+ for (const row of rows) {
2731
+ if (!idSet.has(row.id)) {
2732
+ deleteStmt.run(row.id);
2733
+ pruned++;
2734
+ }
2735
+ }
2736
+ this.db.exec("COMMIT;");
2737
+ return pruned;
2738
+ } catch (e) {
2739
+ this.db.exec("ROLLBACK;");
2740
+ throw e;
2741
+ }
2742
+ }
2395
2743
  clear() {
2396
2744
  if (this.fallbackMemory) {
2397
2745
  this.fallbackMemory.clear();
@@ -2522,6 +2870,17 @@ var MemoryMetadataCache = class {
2522
2870
  deleteFile(id) {
2523
2871
  this.files.delete(id);
2524
2872
  }
2873
+ pruneMissing(activeIds) {
2874
+ const idSet = new Set(activeIds);
2875
+ let pruned = 0;
2876
+ for (const id of Array.from(this.files.keys())) {
2877
+ if (!idSet.has(id)) {
2878
+ this.files.delete(id);
2879
+ pruned++;
2880
+ }
2881
+ }
2882
+ return pruned;
2883
+ }
2525
2884
  clear() {
2526
2885
  this.files.clear();
2527
2886
  this.meta.clear();
@@ -2580,6 +2939,18 @@ var DriveKit = class _DriveKit {
2580
2939
  this.pluginManager.use(plugin);
2581
2940
  return this;
2582
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
+ }
2583
2954
  /**
2584
2955
  * Returns a fluent, chained reference to a specific file
2585
2956
  */
@@ -2598,7 +2969,8 @@ var DriveKit = class _DriveKit {
2598
2969
  async init() {
2599
2970
  if (!this.driveClient) {
2600
2971
  const auth = await this.authenticator.getAuthClient();
2601
- this.driveClient = (0, import_drive3.drive)({ version: "v3", auth });
2972
+ const agent = getOptimizedHttpsAgent();
2973
+ this.driveClient = (0, import_drive3.drive)({ version: "v3", auth, agent });
2602
2974
  if (this.options.enablePersistentCache !== false) {
2603
2975
  this.metadataCacheInstance = new SqliteMetadataCache(this.options.cacheDatabasePath);
2604
2976
  this.metadataCacheInstance.init();
@@ -2685,14 +3057,41 @@ var DriveKit = class _DriveKit {
2685
3057
  }
2686
3058
  }
2687
3059
  /**
2688
- * 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
2689
3061
  */
2690
3062
  async ls(folderIdOrPath = "/") {
2691
- if (folderIdOrPath === "/" || folderIdOrPath === "root") {
2692
- return await this.query().raw("'root' in parents or sharedWithMe = true").notTrashed().orderBy("folder,name").list();
3063
+ let parentFolderId;
3064
+ let normalizedPath = null;
3065
+ let files;
3066
+ if (folderIdOrPath === "/" || folderIdOrPath === "root" || folderIdOrPath === this.rootFolderId) {
3067
+ parentFolderId = this.rootFolderId;
3068
+ normalizedPath = "/";
3069
+ const parentFilter = this.rootFolderId === "root" ? "'root' in parents or sharedWithMe = true" : `'${this.rootFolderId}' in parents`;
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();
3079
+ }
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);
2693
3093
  }
2694
- const folderId = await this.resolveId(folderIdOrPath);
2695
- return await this.query().inFolder(folderId).notTrashed().orderBy("folder,name").list();
3094
+ return files;
2696
3095
  }
2697
3096
  // ==========================================
2698
3097
  // FILE OPERATIONS (UPLOAD, DOWNLOAD, GET)
@@ -2711,7 +3110,7 @@ var DriveKit = class _DriveKit {
2711
3110
  if (parentId && parentId.startsWith("/")) {
2712
3111
  parentId = await this.mkdirp(parentId);
2713
3112
  }
2714
- 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);
2715
3114
  if (opts.overwrite && targetName && parentId) {
2716
3115
  const existing = await this.query().inFolder(parentId).nameEquals(targetName).notTrashed().first();
2717
3116
  if (existing?.id) {
@@ -2732,7 +3131,7 @@ var DriveKit = class _DriveKit {
2732
3131
  }
2733
3132
  }
2734
3133
  if (existingId) {
2735
- const fileName = targetName || import_node_path6.default.basename(opts.source);
3134
+ const fileName = targetName || import_node_path7.default.basename(opts.source);
2736
3135
  const raw = await this.getRawClient();
2737
3136
  const copyRes = await withRetry(async () => {
2738
3137
  return await raw.files.copy({
@@ -2767,12 +3166,14 @@ var DriveKit = class _DriveKit {
2767
3166
  parent: parentId
2768
3167
  });
2769
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;
2770
3170
  this.metadataCacheInstance.upsertFile({
2771
3171
  id: uploaded.id,
2772
3172
  name: uploaded.name || targetName || "untitled",
2773
3173
  mimeType: uploaded.mimeType || "",
2774
3174
  size: uploaded.size ? parseInt(uploaded.size, 10) : void 0,
2775
3175
  parentId,
3176
+ path: virtualPath,
2776
3177
  trashed: false
2777
3178
  });
2778
3179
  }
@@ -2783,16 +3184,25 @@ var DriveKit = class _DriveKit {
2783
3184
  * - Automatic conversion for Google Docs, Sheets, and Slides
2784
3185
  * - Progress events
2785
3186
  * - Saves directly to file or returns Readable Stream
3187
+ * - Leverages local metadata cache to bypass redundant Google API roundtrips
2786
3188
  */
2787
3189
  async download(fileIdOrPath, options = {}) {
2788
3190
  const fileId = await this.resolveId(fileIdOrPath);
2789
- 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);
2790
3200
  const downloader = await this.getDownloader();
2791
3201
  const result = await downloader.download(fileId, processedOpts);
2792
3202
  return await this.pluginManager.runAfterDownload(result);
2793
3203
  }
2794
3204
  /**
2795
- * Gets file metadata
3205
+ * Gets file metadata and updates the local metadata cache
2796
3206
  */
2797
3207
  async getFile(fileIdOrPath) {
2798
3208
  const fileId = await this.resolveId(fileIdOrPath);
@@ -2804,7 +3214,20 @@ var DriveKit = class _DriveKit {
2804
3214
  supportsAllDrives: true
2805
3215
  });
2806
3216
  });
2807
- 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;
2808
3231
  }
2809
3232
  /**
2810
3233
  * Reads file content as UTF-8 string
@@ -2847,6 +3270,9 @@ var DriveKit = class _DriveKit {
2847
3270
  if (this.pathResolverInstance && fileIdOrPath.startsWith("/")) {
2848
3271
  this.pathResolverInstance.invalidatePath(fileIdOrPath);
2849
3272
  }
3273
+ if (this.metadataCacheInstance) {
3274
+ this.metadataCacheInstance.deleteFile(fileId);
3275
+ }
2850
3276
  }
2851
3277
  /**
2852
3278
  * Move item to trash
@@ -2888,6 +3314,16 @@ var DriveKit = class _DriveKit {
2888
3314
  if (this.pathResolverInstance) {
2889
3315
  this.pathResolverInstance.clearCache();
2890
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
+ }
2891
3327
  return res.data;
2892
3328
  }
2893
3329
  /**
@@ -2930,6 +3366,16 @@ var DriveKit = class _DriveKit {
2930
3366
  if (this.pathResolverInstance) {
2931
3367
  this.pathResolverInstance.clearCache();
2932
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
+ }
2933
3379
  return res.data;
2934
3380
  }
2935
3381
  // ==========================================
@@ -3019,8 +3465,8 @@ var DriveKit = class _DriveKit {
3019
3465
  const entries = await import_node_fs6.default.promises.readdir(dir, { withFileTypes: true });
3020
3466
  const files = [];
3021
3467
  for (const entry of entries) {
3022
- const fullPath = import_node_path6.default.join(dir, entry.name);
3023
- const relPath = import_node_path6.default.join(base, entry.name);
3468
+ const fullPath = import_node_path7.default.join(dir, entry.name);
3469
+ const relPath = import_node_path7.default.join(base, entry.name);
3024
3470
  if (entry.isDirectory()) {
3025
3471
  const sub = await collectFiles(fullPath, relPath);
3026
3472
  files.push(...sub);
@@ -3038,11 +3484,11 @@ var DriveKit = class _DriveKit {
3038
3484
  if (remoteDirCache.has(relDir)) {
3039
3485
  return remoteDirCache.get(relDir);
3040
3486
  }
3041
- const parts = relDir.split(import_node_path6.default.sep).filter(Boolean);
3487
+ const parts = relDir.split(import_node_path7.default.sep).filter(Boolean);
3042
3488
  let currentParent = targetFolderId;
3043
3489
  let currentRel = "";
3044
3490
  for (const part of parts) {
3045
- currentRel = currentRel ? import_node_path6.default.join(currentRel, part) : part;
3491
+ currentRel = currentRel ? import_node_path7.default.join(currentRel, part) : part;
3046
3492
  if (remoteDirCache.has(currentRel)) {
3047
3493
  currentParent = remoteDirCache.get(currentRel);
3048
3494
  continue;
@@ -3071,8 +3517,8 @@ var DriveKit = class _DriveKit {
3071
3517
  };
3072
3518
  await pool.map(allFiles, async (fileItem) => {
3073
3519
  try {
3074
- const relDir = import_node_path6.default.dirname(fileItem.relPath);
3075
- const fileName = import_node_path6.default.basename(fileItem.relPath);
3520
+ const relDir = import_node_path7.default.dirname(fileItem.relPath);
3521
+ const fileName = import_node_path7.default.basename(fileItem.relPath);
3076
3522
  const parentFolderId = await ensureRemoteSubdir(relDir === "." ? "" : relDir);
3077
3523
  if (options.onFileStart) {
3078
3524
  options.onFileStart(fileItem.fullPath, fileItem.relPath);
@@ -3207,9 +3653,16 @@ var DriveKit = class _DriveKit {
3207
3653
  async createWriteStream(remotePath, options = {}) {
3208
3654
  await this.init();
3209
3655
  const { PassThrough } = await import("stream");
3210
- const passThrough = new PassThrough();
3211
- const remoteDir = import_node_path6.default.dirname(remotePath);
3212
- const fileName = options.name || options.filename || import_node_path6.default.basename(remotePath);
3656
+ const passThrough = new PassThrough({ highWaterMark: 1024 * 1024 });
3657
+ let resolveDone;
3658
+ let rejectDone;
3659
+ const donePromise = new Promise((resolve, reject) => {
3660
+ resolveDone = resolve;
3661
+ rejectDone = reject;
3662
+ });
3663
+ passThrough.done = donePromise;
3664
+ const remoteDir = import_node_path7.default.dirname(remotePath);
3665
+ const fileName = options.name || options.filename || import_node_path7.default.basename(remotePath);
3213
3666
  const targetParentId = remoteDir === "." || remoteDir === "/" ? this.rootFolderId : await this.mkdirp(remoteDir);
3214
3667
  const mimeType = options.mimeType || "application/octet-stream";
3215
3668
  const raw = this.driveClient;
@@ -3226,9 +3679,10 @@ var DriveKit = class _DriveKit {
3226
3679
  fields: "id, name, mimeType, size, md5Checksum",
3227
3680
  supportsAllDrives: true
3228
3681
  }).then((res) => {
3229
- if (res.data.id && this.metadataCacheInstance) {
3682
+ const file = res.data;
3683
+ if (file.id && this.metadataCacheInstance) {
3230
3684
  this.metadataCacheInstance.upsertFile({
3231
- id: res.data.id,
3685
+ id: file.id,
3232
3686
  name: fileName,
3233
3687
  mimeType,
3234
3688
  parentId: targetParentId,
@@ -3236,14 +3690,22 @@ var DriveKit = class _DriveKit {
3236
3690
  trashed: false
3237
3691
  });
3238
3692
  }
3693
+ resolveDone(file);
3239
3694
  }).catch((err) => {
3240
3695
  passThrough.destroy(err);
3696
+ rejectDone(err);
3241
3697
  });
3242
3698
  return passThrough;
3243
3699
  }
3244
3700
  // ==========================================
3245
3701
  // METADATA CACHE OPERATIONS
3246
3702
  // ==========================================
3703
+ /**
3704
+ * Synchronous getter for the active metadata cache instance
3705
+ */
3706
+ get cache() {
3707
+ return this.metadataCacheInstance;
3708
+ }
3247
3709
  /**
3248
3710
  * Returns the active persistent metadata cache instance (SQLite/Memory)
3249
3711
  */
@@ -3266,6 +3728,9 @@ var DriveKit = class _DriveKit {
3266
3728
  if (this.pathResolverInstance) {
3267
3729
  this.pathResolverInstance.clearCache();
3268
3730
  }
3731
+ if (this.metadataCacheInstance) {
3732
+ this.metadataCacheInstance.clear();
3733
+ }
3269
3734
  }
3270
3735
  /**
3271
3736
  * Crawls and indexes Google Drive metadata into the local SQLite database for instant 0ms lookups
@@ -3278,6 +3743,7 @@ var DriveKit = class _DriveKit {
3278
3743
  const client = this.driveClient;
3279
3744
  let pageToken = void 0;
3280
3745
  let totalScanned = 0;
3746
+ const rawFiles = [];
3281
3747
  do {
3282
3748
  const res = await withRetry(async () => {
3283
3749
  return await client.files.list({
@@ -3291,21 +3757,49 @@ var DriveKit = class _DriveKit {
3291
3757
  });
3292
3758
  });
3293
3759
  const files = res.data.files || [];
3294
- const entries = files.map((f) => ({
3295
- id: f.id,
3296
- name: f.name || "untitled",
3297
- mimeType: f.mimeType || "",
3298
- size: f.size ? parseInt(f.size, 10) : void 0,
3299
- parentId: f.parents?.[0],
3300
- md5Checksum: f.md5Checksum || void 0,
3301
- trashed: !!f.trashed,
3302
- modifiedTime: f.modifiedTime || void 0
3303
- }));
3304
- this.metadataCacheInstance.upsertFiles(entries);
3305
- totalScanned += entries.length;
3760
+ for (const f of files) {
3761
+ if (f.id) rawFiles.push(f);
3762
+ }
3763
+ totalScanned += files.length;
3306
3764
  options?.onProgress?.(totalScanned);
3307
3765
  pageToken = res.data.nextPageToken || void 0;
3308
3766
  } while (pageToken);
3767
+ const fileMap = /* @__PURE__ */ new Map();
3768
+ for (const f of rawFiles) {
3769
+ fileMap.set(f.id, f);
3770
+ }
3771
+ const pathMemo = /* @__PURE__ */ new Map();
3772
+ const rootId = this.rootFolderId;
3773
+ function computePath(id, visited = /* @__PURE__ */ new Set()) {
3774
+ if (pathMemo.has(id)) return pathMemo.get(id);
3775
+ if (visited.has(id)) return "";
3776
+ visited.add(id);
3777
+ const f = fileMap.get(id);
3778
+ if (!f || !f.name) return "";
3779
+ const parentId = f.parents?.[0];
3780
+ if (!parentId || parentId === "root" || parentId === rootId) {
3781
+ const p = `/${f.name}`;
3782
+ pathMemo.set(id, p);
3783
+ return p;
3784
+ }
3785
+ const parentPath = computePath(parentId, visited);
3786
+ const fullPath = parentPath ? `${parentPath}/${f.name}` : `/${f.name}`;
3787
+ pathMemo.set(id, fullPath);
3788
+ return fullPath;
3789
+ }
3790
+ const entries = rawFiles.map((f) => ({
3791
+ id: f.id,
3792
+ name: f.name || "untitled",
3793
+ mimeType: f.mimeType || "",
3794
+ size: f.size ? parseInt(f.size, 10) : void 0,
3795
+ parentId: f.parents?.[0],
3796
+ path: computePath(f.id),
3797
+ md5Checksum: f.md5Checksum || void 0,
3798
+ trashed: !!f.trashed,
3799
+ modifiedTime: f.modifiedTime || void 0
3800
+ }));
3801
+ this.metadataCacheInstance.upsertFiles(entries);
3802
+ this.metadataCacheInstance.pruneMissing(rawFiles.map((f) => f.id));
3309
3803
  this.metadataCacheInstance.setMeta("last_sync_timestamp", (/* @__PURE__ */ new Date()).toISOString());
3310
3804
  return this.metadataCacheInstance.getStats();
3311
3805
  }
@@ -3613,11 +4107,14 @@ var index_default = DriveKit;
3613
4107
  createAutoNamePlugin,
3614
4108
  createDrive,
3615
4109
  createWebhookPlugin,
4110
+ escapeXml,
3616
4111
  formatBytes,
3617
4112
  formatDuration,
3618
4113
  formatSpeed,
3619
4114
  getExtensionForMime,
3620
4115
  getFileIcon,
4116
+ getOptimizedHttpAgent,
4117
+ getOptimizedHttpsAgent,
3621
4118
  isGoogleWorkspaceDoc,
3622
4119
  isRetryableError,
3623
4120
  loginWithBrowser,