drivekit 1.1.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -26,17 +26,42 @@ var init_esm_shims = __esm({
26
26
  // src/server/webdav.ts
27
27
  var webdav_exports = {};
28
28
  __export(webdav_exports, {
29
+ escapeXml: () => escapeXml,
29
30
  startWebDAVServer: () => startWebDAVServer
30
31
  });
31
32
  import http2 from "http";
32
33
  import url from "url";
33
- import path6 from "path";
34
+ import path7 from "path";
35
+ function escapeXml(unsafe) {
36
+ return unsafe.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
37
+ }
34
38
  async function startWebDAVServer(drive2, options = {}) {
35
39
  const port = options.port || 8080;
36
40
  const host = options.host || "127.0.0.1";
37
41
  await drive2.init();
38
42
  const server = http2.createServer(async (req, res) => {
39
43
  try {
44
+ if (options.auth?.username && options.auth?.password) {
45
+ const authHeader = req.headers["authorization"];
46
+ if (!authHeader || !authHeader.startsWith("Basic ")) {
47
+ res.writeHead(401, {
48
+ "WWW-Authenticate": 'Basic realm="DriveKit WebDAV"',
49
+ "Content-Type": "text/plain"
50
+ });
51
+ res.end("Authentication required");
52
+ return;
53
+ }
54
+ const credentials = Buffer.from(authHeader.replace("Basic ", ""), "base64").toString("utf8");
55
+ const [user, pass] = credentials.split(":");
56
+ if (user !== options.auth.username || pass !== options.auth.password) {
57
+ res.writeHead(401, {
58
+ "WWW-Authenticate": 'Basic realm="DriveKit WebDAV"',
59
+ "Content-Type": "text/plain"
60
+ });
61
+ res.end("Invalid credentials");
62
+ return;
63
+ }
64
+ }
40
65
  const parsedUrl = url.parse(req.url || "/", true);
41
66
  const decodedPath = decodeURIComponent(parsedUrl.pathname || "/");
42
67
  const virtualPath = decodedPath === "" ? "/" : decodedPath;
@@ -45,7 +70,8 @@ async function startWebDAVServer(drive2, options = {}) {
45
70
  res.writeHead(200, {
46
71
  DAV: "1, 2",
47
72
  Allow: "OPTIONS, GET, HEAD, POST, PUT, DELETE, MKCOL, MOVE, COPY, PROPFIND",
48
- "MS-Author-Via": "DAV"
73
+ "MS-Author-Via": "DAV",
74
+ "Accept-Ranges": "bytes"
49
75
  });
50
76
  res.end();
51
77
  return;
@@ -63,7 +89,7 @@ async function startWebDAVServer(drive2, options = {}) {
63
89
  case "HEAD": {
64
90
  if (virtualPath === "/" || virtualPath === "") {
65
91
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
66
- res.end("<h1>DriveKit WebDAV Server Running</h1><p>Connect via Finder or WebDAV client.</p>");
92
+ res.end("<h1>DriveKit WebDAV Server Running</h1><p>Connect via Finder, File Explorer, or WebDAV client.</p>");
67
93
  return;
68
94
  }
69
95
  try {
@@ -73,15 +99,42 @@ async function startWebDAVServer(drive2, options = {}) {
73
99
  res.end("Cannot GET a directory");
74
100
  return;
75
101
  }
76
- const stream = await drive2.createReadStream(virtualPath);
77
- res.writeHead(200, {
78
- "Content-Type": file.mimeType || "application/octet-stream",
79
- "Content-Length": file.size || void 0
80
- });
81
- if (req.method === "HEAD") {
82
- res.end();
102
+ const fileSize = file.size ? parseInt(file.size, 10) : void 0;
103
+ const rangeHeader = req.headers["range"];
104
+ if (rangeHeader && rangeHeader.startsWith("bytes=") && fileSize !== void 0) {
105
+ const parts = rangeHeader.replace("bytes=", "").split("-");
106
+ const start = parseInt(parts[0], 10);
107
+ const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
108
+ if (isNaN(start) || start >= fileSize || end !== void 0 && end >= fileSize) {
109
+ res.writeHead(416, { "Content-Range": `bytes */${fileSize}` });
110
+ res.end();
111
+ return;
112
+ }
113
+ const stream = await drive2.createReadStream(virtualPath, { start, end });
114
+ const chunkLength = end - start + 1;
115
+ res.writeHead(206, {
116
+ "Content-Type": file.mimeType || "application/octet-stream",
117
+ "Content-Range": `bytes ${start}-${end}/${fileSize}`,
118
+ "Content-Length": chunkLength,
119
+ "Accept-Ranges": "bytes"
120
+ });
121
+ if (req.method === "HEAD") {
122
+ res.end();
123
+ } else {
124
+ stream.pipe(res);
125
+ }
83
126
  } else {
84
- stream.pipe(res);
127
+ const stream = await drive2.createReadStream(virtualPath);
128
+ res.writeHead(200, {
129
+ "Content-Type": file.mimeType || "application/octet-stream",
130
+ "Content-Length": file.size || void 0,
131
+ "Accept-Ranges": "bytes"
132
+ });
133
+ if (req.method === "HEAD") {
134
+ res.end();
135
+ } else {
136
+ stream.pipe(res);
137
+ }
85
138
  }
86
139
  } catch (e) {
87
140
  res.writeHead(404, { "Content-Type": "text/plain" });
@@ -90,27 +143,29 @@ async function startWebDAVServer(drive2, options = {}) {
90
143
  return;
91
144
  }
92
145
  case "PUT": {
93
- const remoteDir = path6.dirname(virtualPath);
94
- const fileName = path6.basename(virtualPath);
146
+ const remoteDir = path7.dirname(virtualPath);
95
147
  await drive2.mkdirp(remoteDir);
96
- const chunks = [];
97
- req.on("data", (chunk) => chunks.push(chunk));
98
- req.on("end", async () => {
99
- try {
100
- const buffer = Buffer.concat(chunks);
101
- await drive2.upload({
102
- source: buffer,
103
- filename: fileName,
104
- parent: remoteDir,
105
- overwrite: true
106
- });
107
- res.writeHead(201, { "Content-Type": "text/plain" });
108
- res.end("Created");
109
- } catch (err) {
110
- res.writeHead(500, { "Content-Type": "text/plain" });
111
- res.end(err.message || "Upload failed");
148
+ let existed = false;
149
+ try {
150
+ const existingFile = await drive2.getFile(virtualPath);
151
+ if (existingFile && existingFile.id) {
152
+ existed = true;
112
153
  }
113
- });
154
+ } catch {
155
+ existed = false;
156
+ }
157
+ try {
158
+ const uploadStream = await drive2.createWriteStream(virtualPath, {
159
+ overwrite: true
160
+ });
161
+ req.pipe(uploadStream);
162
+ await uploadStream.done;
163
+ res.writeHead(existed ? 204 : 201, { "Content-Type": "text/plain" });
164
+ res.end(existed ? "" : "Created");
165
+ } catch (err) {
166
+ res.writeHead(500, { "Content-Type": "text/plain" });
167
+ res.end(err.message || "Upload failed");
168
+ }
114
169
  return;
115
170
  }
116
171
  case "MKCOL": {
@@ -142,14 +197,24 @@ async function startWebDAVServer(drive2, options = {}) {
142
197
  res.end("Destination header missing");
143
198
  return;
144
199
  }
145
- const destUrl = url.parse(destination);
146
- const destPath = decodeURIComponent(destUrl.pathname || "");
147
- const newName = path6.basename(destPath);
148
- const newParent = path6.dirname(destPath);
149
200
  try {
150
- await drive2.move(virtualPath, newParent);
151
- if (newName !== path6.basename(virtualPath)) {
152
- await drive2.rename(destPath, newName);
201
+ const file = await drive2.getFile(virtualPath);
202
+ if (!file?.id) {
203
+ res.writeHead(404, { "Content-Type": "text/plain" });
204
+ res.end("Source file not found");
205
+ return;
206
+ }
207
+ const destUrl = url.parse(destination);
208
+ const destPath = decodeURIComponent(destUrl.pathname || "");
209
+ const newName = path7.basename(destPath);
210
+ const newParentDir = path7.dirname(destPath);
211
+ const newParentFolderId = await drive2.mkdirp(newParentDir);
212
+ const currentParentDir = path7.dirname(virtualPath);
213
+ if (newParentDir !== currentParentDir) {
214
+ await drive2.move(file.id, newParentFolderId);
215
+ }
216
+ if (newName !== path7.basename(virtualPath)) {
217
+ await drive2.rename(file.id, newName);
153
218
  }
154
219
  res.writeHead(201);
155
220
  res.end("Moved");
@@ -159,6 +224,34 @@ async function startWebDAVServer(drive2, options = {}) {
159
224
  }
160
225
  return;
161
226
  }
227
+ case "COPY": {
228
+ const destination = req.headers["destination"];
229
+ if (!destination || typeof destination !== "string") {
230
+ res.writeHead(400, { "Content-Type": "text/plain" });
231
+ res.end("Destination header missing");
232
+ return;
233
+ }
234
+ try {
235
+ const file = await drive2.getFile(virtualPath);
236
+ if (!file?.id) {
237
+ res.writeHead(404, { "Content-Type": "text/plain" });
238
+ res.end("Source file not found");
239
+ return;
240
+ }
241
+ const destUrl = url.parse(destination);
242
+ const destPath = decodeURIComponent(destUrl.pathname || "");
243
+ const newName = path7.basename(destPath);
244
+ const newParentDir = path7.dirname(destPath);
245
+ const newParentFolderId = await drive2.mkdirp(newParentDir);
246
+ await drive2.copy(file.id, { parent: newParentFolderId, name: newName });
247
+ res.writeHead(201);
248
+ res.end("Copied");
249
+ } catch (err) {
250
+ res.writeHead(500, { "Content-Type": "text/plain" });
251
+ res.end(err.message);
252
+ }
253
+ return;
254
+ }
162
255
  default: {
163
256
  res.writeHead(501, { "Content-Type": "text/plain" });
164
257
  res.end("Method Not Implemented");
@@ -228,13 +321,14 @@ ${responses.join("\n")}
228
321
  }
229
322
  function renderWebDAVResponse(href, isDir, size, modifiedTime) {
230
323
  const encodedHref = encodeURI(href);
324
+ const displayName = escapeXml(path7.basename(href) || "root");
231
325
  const resourceType = isDir ? "<D:collection/>" : "";
232
326
  const dateFormatted = new Date(modifiedTime).toUTCString();
233
327
  return ` <D:response>
234
328
  <D:href>${encodedHref}</D:href>
235
329
  <D:propstat>
236
330
  <D:prop>
237
- <D:displayname>${path6.basename(href) || "root"}</D:displayname>
331
+ <D:displayname>${displayName}</D:displayname>
238
332
  <D:resourcetype>${resourceType}</D:resourcetype>
239
333
  <D:getcontentlength>${isDir ? "0" : size}</D:getcontentlength>
240
334
  <D:getlastmodified>${dateFormatted}</D:getlastmodified>
@@ -257,7 +351,7 @@ init_esm_shims();
257
351
  // src/core/client.ts
258
352
  init_esm_shims();
259
353
  import fs6 from "fs";
260
- import path7 from "path";
354
+ import path8 from "path";
261
355
  import { drive } from "@googleapis/drive";
262
356
 
263
357
  // src/auth/authenticator.ts
@@ -533,8 +627,8 @@ var PathResolver = class {
533
627
  /**
534
628
  * Gets cache key for a path
535
629
  */
536
- getCacheKey(path8) {
537
- return `${this.rootFolderId}:${this.normalizePath(path8)}`;
630
+ getCacheKey(path9) {
631
+ return `${this.rootFolderId}:${this.normalizePath(path9)}`;
538
632
  }
539
633
  /**
540
634
  * Clears the path cache
@@ -548,8 +642,8 @@ var PathResolver = class {
548
642
  /**
549
643
  * Invalidate a single path from cache
550
644
  */
551
- invalidatePath(path8) {
552
- const norm = this.normalizePath(path8);
645
+ invalidatePath(path9) {
646
+ const norm = this.normalizePath(path9);
553
647
  const key = this.getCacheKey(norm);
554
648
  this.cache.delete(key);
555
649
  if (this.metadataCache) {
@@ -660,13 +754,14 @@ var PathResolver = class {
660
754
  file = sharedResponse.data.files?.[0];
661
755
  }
662
756
  if (file && file.id) {
757
+ const segmentParentId = currentParentId;
663
758
  currentParentId = file.id;
664
759
  if (this.metadataCache) {
665
760
  this.metadataCache.upsertFile({
666
761
  id: file.id,
667
762
  name: file.name || segment,
668
763
  mimeType: file.mimeType || "",
669
- parentId: currentParentId,
764
+ parentId: segmentParentId,
670
765
  path: currentPath,
671
766
  trashed: false
672
767
  });
@@ -704,13 +799,14 @@ var PathResolver = class {
704
799
  if (!newFolder.id) {
705
800
  throw new Error(`Failed to create folder "${segment}" under parent "${currentParentId}"`);
706
801
  }
802
+ const segmentParentId = currentParentId;
707
803
  currentParentId = newFolder.id;
708
804
  if (this.metadataCache) {
709
805
  this.metadataCache.upsertFile({
710
806
  id: newFolder.id,
711
807
  name: segment,
712
808
  mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
713
- parentId: currentParentId,
809
+ parentId: segmentParentId,
714
810
  path: currentPath,
715
811
  trashed: false
716
812
  });
@@ -2048,12 +2144,39 @@ var DriveFolderRef = class {
2048
2144
 
2049
2145
  // src/core/plugins.ts
2050
2146
  init_esm_shims();
2147
+ import path5 from "path";
2051
2148
  var PluginManager = class {
2052
2149
  plugins = [];
2150
+ /**
2151
+ * Register a plugin. If a plugin with the same name already exists,
2152
+ * it replaces the old one to avoid duplicate side-effects.
2153
+ */
2053
2154
  use(plugin) {
2155
+ this.plugins = this.plugins.filter((p) => p.name !== plugin.name);
2054
2156
  this.plugins.push(plugin);
2055
2157
  return this;
2056
2158
  }
2159
+ /**
2160
+ * Unregister a plugin by its name.
2161
+ * Returns true if a plugin was found and removed, false otherwise.
2162
+ */
2163
+ unuse(pluginName) {
2164
+ const initialLen = this.plugins.length;
2165
+ this.plugins = this.plugins.filter((p) => p.name !== pluginName);
2166
+ return this.plugins.length < initialLen;
2167
+ }
2168
+ /**
2169
+ * Check if a plugin with given name is currently active
2170
+ */
2171
+ has(pluginName) {
2172
+ return this.plugins.some((p) => p.name === pluginName);
2173
+ }
2174
+ /**
2175
+ * Returns all currently registered plugins
2176
+ */
2177
+ getPlugins() {
2178
+ return [...this.plugins];
2179
+ }
2057
2180
  async runBeforeUpload(options) {
2058
2181
  let current = { ...options };
2059
2182
  for (const plugin of this.plugins) {
@@ -2097,45 +2220,62 @@ var PluginManager = class {
2097
2220
  };
2098
2221
  function createWebhookPlugin(options) {
2099
2222
  const events = options.events || ["upload"];
2100
- return {
2101
- name: "drivekit-official-webhook",
2102
- async afterUpload(file) {
2103
- if (!events.includes("upload")) return;
2223
+ const timeoutMs = options.timeout ?? 5e3;
2224
+ const maxRetries = options.retries ?? 0;
2225
+ const sendWebhook = async (event, payload) => {
2226
+ let lastError = null;
2227
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
2228
+ let timeoutId;
2229
+ const controller = new AbortController();
2230
+ timeoutId = setTimeout(() => controller.abort(), timeoutMs);
2104
2231
  try {
2105
- await fetch(options.url, {
2232
+ const res = await fetch(options.url, {
2106
2233
  method: "POST",
2107
2234
  headers: { "Content-Type": "application/json", ...options.headers || {} },
2108
- body: JSON.stringify({
2109
- event: "drivekit:upload",
2110
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2111
- file: {
2112
- id: file.id,
2113
- name: file.name,
2114
- size: file.size,
2115
- mimeType: file.mimeType
2116
- }
2117
- })
2235
+ body: JSON.stringify(payload),
2236
+ signal: controller.signal
2118
2237
  });
2119
- } catch (e) {
2238
+ clearTimeout(timeoutId);
2239
+ if (!res.ok) {
2240
+ throw new Error(`Webhook returned HTTP ${res.status}: ${res.statusText}`);
2241
+ }
2242
+ return;
2243
+ } catch (err) {
2244
+ clearTimeout(timeoutId);
2245
+ lastError = err;
2246
+ if (attempt === maxRetries) {
2247
+ if (options.onError) {
2248
+ options.onError(lastError instanceof Error ? lastError : new Error(String(lastError)), event);
2249
+ }
2250
+ }
2120
2251
  }
2252
+ }
2253
+ };
2254
+ return {
2255
+ name: "drivekit-official-webhook",
2256
+ async afterUpload(file) {
2257
+ if (!events.includes("upload")) return;
2258
+ await sendWebhook("upload", {
2259
+ event: "drivekit:upload",
2260
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2261
+ file: {
2262
+ id: file.id,
2263
+ name: file.name,
2264
+ size: file.size,
2265
+ mimeType: file.mimeType
2266
+ }
2267
+ });
2121
2268
  },
2122
2269
  async afterDownload(result) {
2123
2270
  if (!events.includes("download")) return;
2124
- try {
2125
- await fetch(options.url, {
2126
- method: "POST",
2127
- headers: { "Content-Type": "application/json", ...options.headers || {} },
2128
- body: JSON.stringify({
2129
- event: "drivekit:download",
2130
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2131
- file: {
2132
- name: result.name,
2133
- size: result.size
2134
- }
2135
- })
2136
- });
2137
- } catch (e) {
2138
- }
2271
+ await sendWebhook("download", {
2272
+ event: "drivekit:download",
2273
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2274
+ file: {
2275
+ name: result.name,
2276
+ size: result.size
2277
+ }
2278
+ });
2139
2279
  }
2140
2280
  };
2141
2281
  }
@@ -2145,13 +2285,11 @@ function createAutoNamePlugin(options) {
2145
2285
  beforeUpload(opts) {
2146
2286
  let name = opts.filename;
2147
2287
  if (!name && typeof opts.source === "string") {
2148
- const pathModule2 = __require("path");
2149
- name = pathModule2.basename(opts.source);
2288
+ name = path5.basename(opts.source);
2150
2289
  }
2151
2290
  if (!name) return opts;
2152
- const pathModule = __require("path");
2153
- const ext = pathModule.extname(name);
2154
- const base = pathModule.basename(name, ext);
2291
+ const ext = path5.extname(name);
2292
+ const base = path5.basename(name, ext);
2155
2293
  let finalName = base;
2156
2294
  if (options.prefix) finalName = `${options.prefix}${finalName}`;
2157
2295
  if (options.appendTimestamp) {
@@ -2170,7 +2308,7 @@ function createAutoNamePlugin(options) {
2170
2308
  // src/core/cache.ts
2171
2309
  init_esm_shims();
2172
2310
  import os from "os";
2173
- import path5 from "path";
2311
+ import path6 from "path";
2174
2312
  import fs5 from "fs";
2175
2313
  var SqliteMetadataCache = class {
2176
2314
  db = null;
@@ -2181,14 +2319,14 @@ var SqliteMetadataCache = class {
2181
2319
  if (customPath) {
2182
2320
  this.dbPath = customPath;
2183
2321
  } else {
2184
- const dir = path5.join(os.homedir(), ".drivekit");
2322
+ const dir = path6.join(os.homedir(), ".drivekit");
2185
2323
  if (!fs5.existsSync(dir)) {
2186
2324
  try {
2187
2325
  fs5.mkdirSync(dir, { recursive: true });
2188
2326
  } catch {
2189
2327
  }
2190
2328
  }
2191
- this.dbPath = path5.join(dir, "cache.db");
2329
+ this.dbPath = path6.join(dir, "cache.db");
2192
2330
  }
2193
2331
  }
2194
2332
  init() {
@@ -2206,7 +2344,7 @@ var SqliteMetadataCache = class {
2206
2344
  CREATE TABLE IF NOT EXISTS files (
2207
2345
  id TEXT PRIMARY KEY,
2208
2346
  name TEXT NOT NULL,
2209
- mimeType TEXT NOT NULL,
2347
+ mimeType TEXT,
2210
2348
  size INTEGER,
2211
2349
  parentId TEXT,
2212
2350
  path TEXT,
@@ -2292,7 +2430,7 @@ var SqliteMetadataCache = class {
2292
2430
  stmt.run(
2293
2431
  entry.id,
2294
2432
  entry.name,
2295
- entry.mimeType,
2433
+ entry.mimeType ?? null,
2296
2434
  entry.size ?? null,
2297
2435
  entry.parentId ?? null,
2298
2436
  entry.path ?? null,
@@ -2328,6 +2466,30 @@ var SqliteMetadataCache = class {
2328
2466
  const stmt = this.db.prepare("DELETE FROM files WHERE id = ?");
2329
2467
  stmt.run(id);
2330
2468
  }
2469
+ pruneMissing(activeIds) {
2470
+ if (this.fallbackMemory) {
2471
+ return this.fallbackMemory.pruneMissing(activeIds);
2472
+ }
2473
+ if (!this.initialized || !this.db || activeIds.length === 0) return 0;
2474
+ const idSet = new Set(activeIds);
2475
+ const rows = this.db.prepare("SELECT id FROM files").all();
2476
+ let pruned = 0;
2477
+ this.db.exec("BEGIN TRANSACTION;");
2478
+ try {
2479
+ const deleteStmt = this.db.prepare("DELETE FROM files WHERE id = ?");
2480
+ for (const row of rows) {
2481
+ if (!idSet.has(row.id)) {
2482
+ deleteStmt.run(row.id);
2483
+ pruned++;
2484
+ }
2485
+ }
2486
+ this.db.exec("COMMIT;");
2487
+ return pruned;
2488
+ } catch (e) {
2489
+ this.db.exec("ROLLBACK;");
2490
+ throw e;
2491
+ }
2492
+ }
2331
2493
  clear() {
2332
2494
  if (this.fallbackMemory) {
2333
2495
  this.fallbackMemory.clear();
@@ -2458,6 +2620,17 @@ var MemoryMetadataCache = class {
2458
2620
  deleteFile(id) {
2459
2621
  this.files.delete(id);
2460
2622
  }
2623
+ pruneMissing(activeIds) {
2624
+ const idSet = new Set(activeIds);
2625
+ let pruned = 0;
2626
+ for (const id of Array.from(this.files.keys())) {
2627
+ if (!idSet.has(id)) {
2628
+ this.files.delete(id);
2629
+ pruned++;
2630
+ }
2631
+ }
2632
+ return pruned;
2633
+ }
2461
2634
  clear() {
2462
2635
  this.files.clear();
2463
2636
  this.meta.clear();
@@ -2624,8 +2797,9 @@ var DriveKit = class _DriveKit {
2624
2797
  * Lists contents of a folder (by folder ID or path)
2625
2798
  */
2626
2799
  async ls(folderIdOrPath = "/") {
2627
- if (folderIdOrPath === "/" || folderIdOrPath === "root") {
2628
- return await this.query().raw("'root' in parents or sharedWithMe = true").notTrashed().orderBy("folder,name").list();
2800
+ if (folderIdOrPath === "/" || folderIdOrPath === "root" || folderIdOrPath === this.rootFolderId) {
2801
+ const parentFilter = this.rootFolderId === "root" ? "'root' in parents or sharedWithMe = true" : `'${this.rootFolderId}' in parents`;
2802
+ return await this.query().raw(parentFilter).notTrashed().orderBy("folder,name").list();
2629
2803
  }
2630
2804
  const folderId = await this.resolveId(folderIdOrPath);
2631
2805
  return await this.query().inFolder(folderId).notTrashed().orderBy("folder,name").list();
@@ -2668,7 +2842,7 @@ var DriveKit = class _DriveKit {
2668
2842
  }
2669
2843
  }
2670
2844
  if (existingId) {
2671
- const fileName = targetName || path7.basename(opts.source);
2845
+ const fileName = targetName || path8.basename(opts.source);
2672
2846
  const raw = await this.getRawClient();
2673
2847
  const copyRes = await withRetry(async () => {
2674
2848
  return await raw.files.copy({
@@ -2955,8 +3129,8 @@ var DriveKit = class _DriveKit {
2955
3129
  const entries = await fs6.promises.readdir(dir, { withFileTypes: true });
2956
3130
  const files = [];
2957
3131
  for (const entry of entries) {
2958
- const fullPath = path7.join(dir, entry.name);
2959
- const relPath = path7.join(base, entry.name);
3132
+ const fullPath = path8.join(dir, entry.name);
3133
+ const relPath = path8.join(base, entry.name);
2960
3134
  if (entry.isDirectory()) {
2961
3135
  const sub = await collectFiles(fullPath, relPath);
2962
3136
  files.push(...sub);
@@ -2974,11 +3148,11 @@ var DriveKit = class _DriveKit {
2974
3148
  if (remoteDirCache.has(relDir)) {
2975
3149
  return remoteDirCache.get(relDir);
2976
3150
  }
2977
- const parts = relDir.split(path7.sep).filter(Boolean);
3151
+ const parts = relDir.split(path8.sep).filter(Boolean);
2978
3152
  let currentParent = targetFolderId;
2979
3153
  let currentRel = "";
2980
3154
  for (const part of parts) {
2981
- currentRel = currentRel ? path7.join(currentRel, part) : part;
3155
+ currentRel = currentRel ? path8.join(currentRel, part) : part;
2982
3156
  if (remoteDirCache.has(currentRel)) {
2983
3157
  currentParent = remoteDirCache.get(currentRel);
2984
3158
  continue;
@@ -3007,8 +3181,8 @@ var DriveKit = class _DriveKit {
3007
3181
  };
3008
3182
  await pool.map(allFiles, async (fileItem) => {
3009
3183
  try {
3010
- const relDir = path7.dirname(fileItem.relPath);
3011
- const fileName = path7.basename(fileItem.relPath);
3184
+ const relDir = path8.dirname(fileItem.relPath);
3185
+ const fileName = path8.basename(fileItem.relPath);
3012
3186
  const parentFolderId = await ensureRemoteSubdir(relDir === "." ? "" : relDir);
3013
3187
  if (options.onFileStart) {
3014
3188
  options.onFileStart(fileItem.fullPath, fileItem.relPath);
@@ -3144,8 +3318,15 @@ var DriveKit = class _DriveKit {
3144
3318
  await this.init();
3145
3319
  const { PassThrough } = await import("stream");
3146
3320
  const passThrough = new PassThrough();
3147
- const remoteDir = path7.dirname(remotePath);
3148
- const fileName = options.name || options.filename || path7.basename(remotePath);
3321
+ let resolveDone;
3322
+ let rejectDone;
3323
+ const donePromise = new Promise((resolve, reject) => {
3324
+ resolveDone = resolve;
3325
+ rejectDone = reject;
3326
+ });
3327
+ passThrough.done = donePromise;
3328
+ const remoteDir = path8.dirname(remotePath);
3329
+ const fileName = options.name || options.filename || path8.basename(remotePath);
3149
3330
  const targetParentId = remoteDir === "." || remoteDir === "/" ? this.rootFolderId : await this.mkdirp(remoteDir);
3150
3331
  const mimeType = options.mimeType || "application/octet-stream";
3151
3332
  const raw = this.driveClient;
@@ -3162,9 +3343,10 @@ var DriveKit = class _DriveKit {
3162
3343
  fields: "id, name, mimeType, size, md5Checksum",
3163
3344
  supportsAllDrives: true
3164
3345
  }).then((res) => {
3165
- if (res.data.id && this.metadataCacheInstance) {
3346
+ const file = res.data;
3347
+ if (file.id && this.metadataCacheInstance) {
3166
3348
  this.metadataCacheInstance.upsertFile({
3167
- id: res.data.id,
3349
+ id: file.id,
3168
3350
  name: fileName,
3169
3351
  mimeType,
3170
3352
  parentId: targetParentId,
@@ -3172,8 +3354,10 @@ var DriveKit = class _DriveKit {
3172
3354
  trashed: false
3173
3355
  });
3174
3356
  }
3357
+ resolveDone(file);
3175
3358
  }).catch((err) => {
3176
3359
  passThrough.destroy(err);
3360
+ rejectDone(err);
3177
3361
  });
3178
3362
  return passThrough;
3179
3363
  }
@@ -3214,6 +3398,7 @@ var DriveKit = class _DriveKit {
3214
3398
  const client = this.driveClient;
3215
3399
  let pageToken = void 0;
3216
3400
  let totalScanned = 0;
3401
+ const rawFiles = [];
3217
3402
  do {
3218
3403
  const res = await withRetry(async () => {
3219
3404
  return await client.files.list({
@@ -3227,21 +3412,49 @@ var DriveKit = class _DriveKit {
3227
3412
  });
3228
3413
  });
3229
3414
  const files = res.data.files || [];
3230
- const entries = files.map((f) => ({
3231
- id: f.id,
3232
- name: f.name || "untitled",
3233
- mimeType: f.mimeType || "",
3234
- size: f.size ? parseInt(f.size, 10) : void 0,
3235
- parentId: f.parents?.[0],
3236
- md5Checksum: f.md5Checksum || void 0,
3237
- trashed: !!f.trashed,
3238
- modifiedTime: f.modifiedTime || void 0
3239
- }));
3240
- this.metadataCacheInstance.upsertFiles(entries);
3241
- totalScanned += entries.length;
3415
+ for (const f of files) {
3416
+ if (f.id) rawFiles.push(f);
3417
+ }
3418
+ totalScanned += files.length;
3242
3419
  options?.onProgress?.(totalScanned);
3243
3420
  pageToken = res.data.nextPageToken || void 0;
3244
3421
  } while (pageToken);
3422
+ const fileMap = /* @__PURE__ */ new Map();
3423
+ for (const f of rawFiles) {
3424
+ fileMap.set(f.id, f);
3425
+ }
3426
+ const pathMemo = /* @__PURE__ */ new Map();
3427
+ const rootId = this.rootFolderId;
3428
+ function computePath(id, visited = /* @__PURE__ */ new Set()) {
3429
+ if (pathMemo.has(id)) return pathMemo.get(id);
3430
+ if (visited.has(id)) return "";
3431
+ visited.add(id);
3432
+ const f = fileMap.get(id);
3433
+ if (!f || !f.name) return "";
3434
+ const parentId = f.parents?.[0];
3435
+ if (!parentId || parentId === "root" || parentId === rootId) {
3436
+ const p = `/${f.name}`;
3437
+ pathMemo.set(id, p);
3438
+ return p;
3439
+ }
3440
+ const parentPath = computePath(parentId, visited);
3441
+ const fullPath = parentPath ? `${parentPath}/${f.name}` : `/${f.name}`;
3442
+ pathMemo.set(id, fullPath);
3443
+ return fullPath;
3444
+ }
3445
+ const entries = rawFiles.map((f) => ({
3446
+ id: f.id,
3447
+ name: f.name || "untitled",
3448
+ mimeType: f.mimeType || "",
3449
+ size: f.size ? parseInt(f.size, 10) : void 0,
3450
+ parentId: f.parents?.[0],
3451
+ path: computePath(f.id),
3452
+ md5Checksum: f.md5Checksum || void 0,
3453
+ trashed: !!f.trashed,
3454
+ modifiedTime: f.modifiedTime || void 0
3455
+ }));
3456
+ this.metadataCacheInstance.upsertFiles(entries);
3457
+ this.metadataCacheInstance.pruneMissing(rawFiles.map((f) => f.id));
3245
3458
  this.metadataCacheInstance.setMeta("last_sync_timestamp", (/* @__PURE__ */ new Date()).toISOString());
3246
3459
  return this.metadataCacheInstance.getStats();
3247
3460
  }
@@ -3549,6 +3762,7 @@ export {
3549
3762
  createDrive,
3550
3763
  createWebhookPlugin,
3551
3764
  index_default as default,
3765
+ escapeXml,
3552
3766
  formatBytes,
3553
3767
  formatDuration,
3554
3768
  formatSpeed,