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/cli.cjs CHANGED
@@ -31,9 +31,12 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
31
31
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
32
 
33
33
  // node_modules/tsup/assets/cjs_shims.js
34
+ var getImportMetaUrl, importMetaUrl;
34
35
  var init_cjs_shims = __esm({
35
36
  "node_modules/tsup/assets/cjs_shims.js"() {
36
37
  "use strict";
38
+ getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
39
+ importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
37
40
  }
38
41
  });
39
42
 
@@ -339,8 +342,8 @@ var init_path_resolver = __esm({
339
342
  /**
340
343
  * Gets cache key for a path
341
344
  */
342
- getCacheKey(path8) {
343
- return `${this.rootFolderId}:${this.normalizePath(path8)}`;
345
+ getCacheKey(path9) {
346
+ return `${this.rootFolderId}:${this.normalizePath(path9)}`;
344
347
  }
345
348
  /**
346
349
  * Clears the path cache
@@ -354,8 +357,8 @@ var init_path_resolver = __esm({
354
357
  /**
355
358
  * Invalidate a single path from cache
356
359
  */
357
- invalidatePath(path8) {
358
- const norm = this.normalizePath(path8);
360
+ invalidatePath(path9) {
361
+ const norm = this.normalizePath(path9);
359
362
  const key = this.getCacheKey(norm);
360
363
  this.cache.delete(key);
361
364
  if (this.metadataCache) {
@@ -466,13 +469,14 @@ var init_path_resolver = __esm({
466
469
  file = sharedResponse.data.files?.[0];
467
470
  }
468
471
  if (file && file.id) {
472
+ const segmentParentId = currentParentId;
469
473
  currentParentId = file.id;
470
474
  if (this.metadataCache) {
471
475
  this.metadataCache.upsertFile({
472
476
  id: file.id,
473
477
  name: file.name || segment,
474
478
  mimeType: file.mimeType || "",
475
- parentId: currentParentId,
479
+ parentId: segmentParentId,
476
480
  path: currentPath,
477
481
  trashed: false
478
482
  });
@@ -510,13 +514,14 @@ var init_path_resolver = __esm({
510
514
  if (!newFolder.id) {
511
515
  throw new Error(`Failed to create folder "${segment}" under parent "${currentParentId}"`);
512
516
  }
517
+ const segmentParentId = currentParentId;
513
518
  currentParentId = newFolder.id;
514
519
  if (this.metadataCache) {
515
520
  this.metadataCache.upsertFile({
516
521
  id: newFolder.id,
517
522
  name: segment,
518
523
  mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
519
- parentId: currentParentId,
524
+ parentId: segmentParentId,
520
525
  path: currentPath,
521
526
  trashed: false
522
527
  });
@@ -1917,17 +1922,44 @@ var init_resource_refs = __esm({
1917
1922
  });
1918
1923
 
1919
1924
  // src/core/plugins.ts
1920
- var PluginManager;
1925
+ var import_node_path4, PluginManager;
1921
1926
  var init_plugins = __esm({
1922
1927
  "src/core/plugins.ts"() {
1923
1928
  "use strict";
1924
1929
  init_cjs_shims();
1930
+ import_node_path4 = __toESM(require("path"), 1);
1925
1931
  PluginManager = class {
1926
1932
  plugins = [];
1933
+ /**
1934
+ * Register a plugin. If a plugin with the same name already exists,
1935
+ * it replaces the old one to avoid duplicate side-effects.
1936
+ */
1927
1937
  use(plugin) {
1938
+ this.plugins = this.plugins.filter((p) => p.name !== plugin.name);
1928
1939
  this.plugins.push(plugin);
1929
1940
  return this;
1930
1941
  }
1942
+ /**
1943
+ * Unregister a plugin by its name.
1944
+ * Returns true if a plugin was found and removed, false otherwise.
1945
+ */
1946
+ unuse(pluginName) {
1947
+ const initialLen = this.plugins.length;
1948
+ this.plugins = this.plugins.filter((p) => p.name !== pluginName);
1949
+ return this.plugins.length < initialLen;
1950
+ }
1951
+ /**
1952
+ * Check if a plugin with given name is currently active
1953
+ */
1954
+ has(pluginName) {
1955
+ return this.plugins.some((p) => p.name === pluginName);
1956
+ }
1957
+ /**
1958
+ * Returns all currently registered plugins
1959
+ */
1960
+ getPlugins() {
1961
+ return [...this.plugins];
1962
+ }
1931
1963
  async runBeforeUpload(options) {
1932
1964
  let current = { ...options };
1933
1965
  for (const plugin of this.plugins) {
@@ -1973,13 +2005,13 @@ var init_plugins = __esm({
1973
2005
  });
1974
2006
 
1975
2007
  // src/core/cache.ts
1976
- var import_node_os, import_node_path4, import_node_fs5, SqliteMetadataCache, MemoryMetadataCache;
2008
+ var import_node_os, import_node_path5, import_node_fs5, SqliteMetadataCache, MemoryMetadataCache;
1977
2009
  var init_cache = __esm({
1978
2010
  "src/core/cache.ts"() {
1979
2011
  "use strict";
1980
2012
  init_cjs_shims();
1981
2013
  import_node_os = __toESM(require("os"), 1);
1982
- import_node_path4 = __toESM(require("path"), 1);
2014
+ import_node_path5 = __toESM(require("path"), 1);
1983
2015
  import_node_fs5 = __toESM(require("fs"), 1);
1984
2016
  SqliteMetadataCache = class {
1985
2017
  db = null;
@@ -1990,14 +2022,14 @@ var init_cache = __esm({
1990
2022
  if (customPath) {
1991
2023
  this.dbPath = customPath;
1992
2024
  } else {
1993
- const dir = import_node_path4.default.join(import_node_os.default.homedir(), ".drivekit");
2025
+ const dir = import_node_path5.default.join(import_node_os.default.homedir(), ".drivekit");
1994
2026
  if (!import_node_fs5.default.existsSync(dir)) {
1995
2027
  try {
1996
2028
  import_node_fs5.default.mkdirSync(dir, { recursive: true });
1997
2029
  } catch {
1998
2030
  }
1999
2031
  }
2000
- this.dbPath = import_node_path4.default.join(dir, "cache.db");
2032
+ this.dbPath = import_node_path5.default.join(dir, "cache.db");
2001
2033
  }
2002
2034
  }
2003
2035
  init() {
@@ -2015,7 +2047,7 @@ var init_cache = __esm({
2015
2047
  CREATE TABLE IF NOT EXISTS files (
2016
2048
  id TEXT PRIMARY KEY,
2017
2049
  name TEXT NOT NULL,
2018
- mimeType TEXT NOT NULL,
2050
+ mimeType TEXT,
2019
2051
  size INTEGER,
2020
2052
  parentId TEXT,
2021
2053
  path TEXT,
@@ -2101,7 +2133,7 @@ var init_cache = __esm({
2101
2133
  stmt.run(
2102
2134
  entry.id,
2103
2135
  entry.name,
2104
- entry.mimeType,
2136
+ entry.mimeType ?? null,
2105
2137
  entry.size ?? null,
2106
2138
  entry.parentId ?? null,
2107
2139
  entry.path ?? null,
@@ -2137,6 +2169,30 @@ var init_cache = __esm({
2137
2169
  const stmt = this.db.prepare("DELETE FROM files WHERE id = ?");
2138
2170
  stmt.run(id);
2139
2171
  }
2172
+ pruneMissing(activeIds) {
2173
+ if (this.fallbackMemory) {
2174
+ return this.fallbackMemory.pruneMissing(activeIds);
2175
+ }
2176
+ if (!this.initialized || !this.db || activeIds.length === 0) return 0;
2177
+ const idSet = new Set(activeIds);
2178
+ const rows = this.db.prepare("SELECT id FROM files").all();
2179
+ let pruned = 0;
2180
+ this.db.exec("BEGIN TRANSACTION;");
2181
+ try {
2182
+ const deleteStmt = this.db.prepare("DELETE FROM files WHERE id = ?");
2183
+ for (const row of rows) {
2184
+ if (!idSet.has(row.id)) {
2185
+ deleteStmt.run(row.id);
2186
+ pruned++;
2187
+ }
2188
+ }
2189
+ this.db.exec("COMMIT;");
2190
+ return pruned;
2191
+ } catch (e) {
2192
+ this.db.exec("ROLLBACK;");
2193
+ throw e;
2194
+ }
2195
+ }
2140
2196
  clear() {
2141
2197
  if (this.fallbackMemory) {
2142
2198
  this.fallbackMemory.clear();
@@ -2267,6 +2323,17 @@ var init_cache = __esm({
2267
2323
  deleteFile(id) {
2268
2324
  this.files.delete(id);
2269
2325
  }
2326
+ pruneMissing(activeIds) {
2327
+ const idSet = new Set(activeIds);
2328
+ let pruned = 0;
2329
+ for (const id of Array.from(this.files.keys())) {
2330
+ if (!idSet.has(id)) {
2331
+ this.files.delete(id);
2332
+ pruned++;
2333
+ }
2334
+ }
2335
+ return pruned;
2336
+ }
2270
2337
  clear() {
2271
2338
  this.files.clear();
2272
2339
  this.meta.clear();
@@ -2307,14 +2374,39 @@ var init_cache = __esm({
2307
2374
  // src/server/webdav.ts
2308
2375
  var webdav_exports = {};
2309
2376
  __export(webdav_exports, {
2377
+ escapeXml: () => escapeXml,
2310
2378
  startWebDAVServer: () => startWebDAVServer
2311
2379
  });
2380
+ function escapeXml(unsafe) {
2381
+ return unsafe.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
2382
+ }
2312
2383
  async function startWebDAVServer(drive2, options = {}) {
2313
2384
  const port = options.port || 8080;
2314
2385
  const host = options.host || "127.0.0.1";
2315
2386
  await drive2.init();
2316
2387
  const server = import_node_http2.default.createServer(async (req, res) => {
2317
2388
  try {
2389
+ if (options.auth?.username && options.auth?.password) {
2390
+ const authHeader = req.headers["authorization"];
2391
+ if (!authHeader || !authHeader.startsWith("Basic ")) {
2392
+ res.writeHead(401, {
2393
+ "WWW-Authenticate": 'Basic realm="DriveKit WebDAV"',
2394
+ "Content-Type": "text/plain"
2395
+ });
2396
+ res.end("Authentication required");
2397
+ return;
2398
+ }
2399
+ const credentials = Buffer.from(authHeader.replace("Basic ", ""), "base64").toString("utf8");
2400
+ const [user, pass] = credentials.split(":");
2401
+ if (user !== options.auth.username || pass !== options.auth.password) {
2402
+ res.writeHead(401, {
2403
+ "WWW-Authenticate": 'Basic realm="DriveKit WebDAV"',
2404
+ "Content-Type": "text/plain"
2405
+ });
2406
+ res.end("Invalid credentials");
2407
+ return;
2408
+ }
2409
+ }
2318
2410
  const parsedUrl = import_node_url.default.parse(req.url || "/", true);
2319
2411
  const decodedPath = decodeURIComponent(parsedUrl.pathname || "/");
2320
2412
  const virtualPath = decodedPath === "" ? "/" : decodedPath;
@@ -2323,7 +2415,8 @@ async function startWebDAVServer(drive2, options = {}) {
2323
2415
  res.writeHead(200, {
2324
2416
  DAV: "1, 2",
2325
2417
  Allow: "OPTIONS, GET, HEAD, POST, PUT, DELETE, MKCOL, MOVE, COPY, PROPFIND",
2326
- "MS-Author-Via": "DAV"
2418
+ "MS-Author-Via": "DAV",
2419
+ "Accept-Ranges": "bytes"
2327
2420
  });
2328
2421
  res.end();
2329
2422
  return;
@@ -2341,7 +2434,7 @@ async function startWebDAVServer(drive2, options = {}) {
2341
2434
  case "HEAD": {
2342
2435
  if (virtualPath === "/" || virtualPath === "") {
2343
2436
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
2344
- res.end("<h1>DriveKit WebDAV Server Running</h1><p>Connect via Finder or WebDAV client.</p>");
2437
+ res.end("<h1>DriveKit WebDAV Server Running</h1><p>Connect via Finder, File Explorer, or WebDAV client.</p>");
2345
2438
  return;
2346
2439
  }
2347
2440
  try {
@@ -2351,15 +2444,42 @@ async function startWebDAVServer(drive2, options = {}) {
2351
2444
  res.end("Cannot GET a directory");
2352
2445
  return;
2353
2446
  }
2354
- const stream = await drive2.createReadStream(virtualPath);
2355
- res.writeHead(200, {
2356
- "Content-Type": file.mimeType || "application/octet-stream",
2357
- "Content-Length": file.size || void 0
2358
- });
2359
- if (req.method === "HEAD") {
2360
- res.end();
2447
+ const fileSize = file.size ? parseInt(file.size, 10) : void 0;
2448
+ const rangeHeader = req.headers["range"];
2449
+ if (rangeHeader && rangeHeader.startsWith("bytes=") && fileSize !== void 0) {
2450
+ const parts = rangeHeader.replace("bytes=", "").split("-");
2451
+ const start = parseInt(parts[0], 10);
2452
+ const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
2453
+ if (isNaN(start) || start >= fileSize || end !== void 0 && end >= fileSize) {
2454
+ res.writeHead(416, { "Content-Range": `bytes */${fileSize}` });
2455
+ res.end();
2456
+ return;
2457
+ }
2458
+ const stream = await drive2.createReadStream(virtualPath, { start, end });
2459
+ const chunkLength = end - start + 1;
2460
+ res.writeHead(206, {
2461
+ "Content-Type": file.mimeType || "application/octet-stream",
2462
+ "Content-Range": `bytes ${start}-${end}/${fileSize}`,
2463
+ "Content-Length": chunkLength,
2464
+ "Accept-Ranges": "bytes"
2465
+ });
2466
+ if (req.method === "HEAD") {
2467
+ res.end();
2468
+ } else {
2469
+ stream.pipe(res);
2470
+ }
2361
2471
  } else {
2362
- stream.pipe(res);
2472
+ const stream = await drive2.createReadStream(virtualPath);
2473
+ res.writeHead(200, {
2474
+ "Content-Type": file.mimeType || "application/octet-stream",
2475
+ "Content-Length": file.size || void 0,
2476
+ "Accept-Ranges": "bytes"
2477
+ });
2478
+ if (req.method === "HEAD") {
2479
+ res.end();
2480
+ } else {
2481
+ stream.pipe(res);
2482
+ }
2363
2483
  }
2364
2484
  } catch (e) {
2365
2485
  res.writeHead(404, { "Content-Type": "text/plain" });
@@ -2368,27 +2488,29 @@ async function startWebDAVServer(drive2, options = {}) {
2368
2488
  return;
2369
2489
  }
2370
2490
  case "PUT": {
2371
- const remoteDir = import_node_path5.default.dirname(virtualPath);
2372
- const fileName = import_node_path5.default.basename(virtualPath);
2491
+ const remoteDir = import_node_path6.default.dirname(virtualPath);
2373
2492
  await drive2.mkdirp(remoteDir);
2374
- const chunks = [];
2375
- req.on("data", (chunk) => chunks.push(chunk));
2376
- req.on("end", async () => {
2377
- try {
2378
- const buffer = Buffer.concat(chunks);
2379
- await drive2.upload({
2380
- source: buffer,
2381
- filename: fileName,
2382
- parent: remoteDir,
2383
- overwrite: true
2384
- });
2385
- res.writeHead(201, { "Content-Type": "text/plain" });
2386
- res.end("Created");
2387
- } catch (err) {
2388
- res.writeHead(500, { "Content-Type": "text/plain" });
2389
- res.end(err.message || "Upload failed");
2493
+ let existed = false;
2494
+ try {
2495
+ const existingFile = await drive2.getFile(virtualPath);
2496
+ if (existingFile && existingFile.id) {
2497
+ existed = true;
2390
2498
  }
2391
- });
2499
+ } catch {
2500
+ existed = false;
2501
+ }
2502
+ try {
2503
+ const uploadStream = await drive2.createWriteStream(virtualPath, {
2504
+ overwrite: true
2505
+ });
2506
+ req.pipe(uploadStream);
2507
+ await uploadStream.done;
2508
+ res.writeHead(existed ? 204 : 201, { "Content-Type": "text/plain" });
2509
+ res.end(existed ? "" : "Created");
2510
+ } catch (err) {
2511
+ res.writeHead(500, { "Content-Type": "text/plain" });
2512
+ res.end(err.message || "Upload failed");
2513
+ }
2392
2514
  return;
2393
2515
  }
2394
2516
  case "MKCOL": {
@@ -2420,14 +2542,24 @@ async function startWebDAVServer(drive2, options = {}) {
2420
2542
  res.end("Destination header missing");
2421
2543
  return;
2422
2544
  }
2423
- const destUrl = import_node_url.default.parse(destination);
2424
- const destPath = decodeURIComponent(destUrl.pathname || "");
2425
- const newName = import_node_path5.default.basename(destPath);
2426
- const newParent = import_node_path5.default.dirname(destPath);
2427
2545
  try {
2428
- await drive2.move(virtualPath, newParent);
2429
- if (newName !== import_node_path5.default.basename(virtualPath)) {
2430
- await drive2.rename(destPath, newName);
2546
+ const file = await drive2.getFile(virtualPath);
2547
+ if (!file?.id) {
2548
+ res.writeHead(404, { "Content-Type": "text/plain" });
2549
+ res.end("Source file not found");
2550
+ return;
2551
+ }
2552
+ const destUrl = import_node_url.default.parse(destination);
2553
+ const destPath = decodeURIComponent(destUrl.pathname || "");
2554
+ const newName = import_node_path6.default.basename(destPath);
2555
+ const newParentDir = import_node_path6.default.dirname(destPath);
2556
+ const newParentFolderId = await drive2.mkdirp(newParentDir);
2557
+ const currentParentDir = import_node_path6.default.dirname(virtualPath);
2558
+ if (newParentDir !== currentParentDir) {
2559
+ await drive2.move(file.id, newParentFolderId);
2560
+ }
2561
+ if (newName !== import_node_path6.default.basename(virtualPath)) {
2562
+ await drive2.rename(file.id, newName);
2431
2563
  }
2432
2564
  res.writeHead(201);
2433
2565
  res.end("Moved");
@@ -2437,6 +2569,34 @@ async function startWebDAVServer(drive2, options = {}) {
2437
2569
  }
2438
2570
  return;
2439
2571
  }
2572
+ case "COPY": {
2573
+ const destination = req.headers["destination"];
2574
+ if (!destination || typeof destination !== "string") {
2575
+ res.writeHead(400, { "Content-Type": "text/plain" });
2576
+ res.end("Destination header missing");
2577
+ return;
2578
+ }
2579
+ try {
2580
+ const file = await drive2.getFile(virtualPath);
2581
+ if (!file?.id) {
2582
+ res.writeHead(404, { "Content-Type": "text/plain" });
2583
+ res.end("Source file not found");
2584
+ return;
2585
+ }
2586
+ const destUrl = import_node_url.default.parse(destination);
2587
+ const destPath = decodeURIComponent(destUrl.pathname || "");
2588
+ const newName = import_node_path6.default.basename(destPath);
2589
+ const newParentDir = import_node_path6.default.dirname(destPath);
2590
+ const newParentFolderId = await drive2.mkdirp(newParentDir);
2591
+ await drive2.copy(file.id, { parent: newParentFolderId, name: newName });
2592
+ res.writeHead(201);
2593
+ res.end("Copied");
2594
+ } catch (err) {
2595
+ res.writeHead(500, { "Content-Type": "text/plain" });
2596
+ res.end(err.message);
2597
+ }
2598
+ return;
2599
+ }
2440
2600
  default: {
2441
2601
  res.writeHead(501, { "Content-Type": "text/plain" });
2442
2602
  res.end("Method Not Implemented");
@@ -2506,13 +2666,14 @@ ${responses.join("\n")}
2506
2666
  }
2507
2667
  function renderWebDAVResponse(href, isDir, size, modifiedTime) {
2508
2668
  const encodedHref = encodeURI(href);
2669
+ const displayName = escapeXml(import_node_path6.default.basename(href) || "root");
2509
2670
  const resourceType = isDir ? "<D:collection/>" : "";
2510
2671
  const dateFormatted = new Date(modifiedTime).toUTCString();
2511
2672
  return ` <D:response>
2512
2673
  <D:href>${encodedHref}</D:href>
2513
2674
  <D:propstat>
2514
2675
  <D:prop>
2515
- <D:displayname>${import_node_path5.default.basename(href) || "root"}</D:displayname>
2676
+ <D:displayname>${displayName}</D:displayname>
2516
2677
  <D:resourcetype>${resourceType}</D:resourcetype>
2517
2678
  <D:getcontentlength>${isDir ? "0" : size}</D:getcontentlength>
2518
2679
  <D:getlastmodified>${dateFormatted}</D:getlastmodified>
@@ -2522,14 +2683,14 @@ function renderWebDAVResponse(href, isDir, size, modifiedTime) {
2522
2683
  </D:propstat>
2523
2684
  </D:response>`;
2524
2685
  }
2525
- var import_node_http2, import_node_url, import_node_path5;
2686
+ var import_node_http2, import_node_url, import_node_path6;
2526
2687
  var init_webdav = __esm({
2527
2688
  "src/server/webdav.ts"() {
2528
2689
  "use strict";
2529
2690
  init_cjs_shims();
2530
2691
  import_node_http2 = __toESM(require("http"), 1);
2531
2692
  import_node_url = __toESM(require("url"), 1);
2532
- import_node_path5 = __toESM(require("path"), 1);
2693
+ import_node_path6 = __toESM(require("path"), 1);
2533
2694
  }
2534
2695
  });
2535
2696
 
@@ -2538,13 +2699,13 @@ var client_exports = {};
2538
2699
  __export(client_exports, {
2539
2700
  DriveKit: () => DriveKit
2540
2701
  });
2541
- var import_node_fs6, import_node_path6, import_drive3, DriveKit;
2702
+ var import_node_fs6, import_node_path7, import_drive3, DriveKit;
2542
2703
  var init_client = __esm({
2543
2704
  "src/core/client.ts"() {
2544
2705
  "use strict";
2545
2706
  init_cjs_shims();
2546
2707
  import_node_fs6 = __toESM(require("fs"), 1);
2547
- import_node_path6 = __toESM(require("path"), 1);
2708
+ import_node_path7 = __toESM(require("path"), 1);
2548
2709
  import_drive3 = require("@googleapis/drive");
2549
2710
  init_authenticator();
2550
2711
  init_path_resolver();
@@ -2692,8 +2853,9 @@ var init_client = __esm({
2692
2853
  * Lists contents of a folder (by folder ID or path)
2693
2854
  */
2694
2855
  async ls(folderIdOrPath = "/") {
2695
- if (folderIdOrPath === "/" || folderIdOrPath === "root") {
2696
- return await this.query().raw("'root' in parents or sharedWithMe = true").notTrashed().orderBy("folder,name").list();
2856
+ if (folderIdOrPath === "/" || folderIdOrPath === "root" || folderIdOrPath === this.rootFolderId) {
2857
+ const parentFilter = this.rootFolderId === "root" ? "'root' in parents or sharedWithMe = true" : `'${this.rootFolderId}' in parents`;
2858
+ return await this.query().raw(parentFilter).notTrashed().orderBy("folder,name").list();
2697
2859
  }
2698
2860
  const folderId = await this.resolveId(folderIdOrPath);
2699
2861
  return await this.query().inFolder(folderId).notTrashed().orderBy("folder,name").list();
@@ -2736,7 +2898,7 @@ var init_client = __esm({
2736
2898
  }
2737
2899
  }
2738
2900
  if (existingId) {
2739
- const fileName = targetName || import_node_path6.default.basename(opts.source);
2901
+ const fileName = targetName || import_node_path7.default.basename(opts.source);
2740
2902
  const raw = await this.getRawClient();
2741
2903
  const copyRes = await withRetry(async () => {
2742
2904
  return await raw.files.copy({
@@ -3023,8 +3185,8 @@ var init_client = __esm({
3023
3185
  const entries = await import_node_fs6.default.promises.readdir(dir, { withFileTypes: true });
3024
3186
  const files = [];
3025
3187
  for (const entry of entries) {
3026
- const fullPath = import_node_path6.default.join(dir, entry.name);
3027
- const relPath = import_node_path6.default.join(base, entry.name);
3188
+ const fullPath = import_node_path7.default.join(dir, entry.name);
3189
+ const relPath = import_node_path7.default.join(base, entry.name);
3028
3190
  if (entry.isDirectory()) {
3029
3191
  const sub = await collectFiles(fullPath, relPath);
3030
3192
  files.push(...sub);
@@ -3042,11 +3204,11 @@ var init_client = __esm({
3042
3204
  if (remoteDirCache.has(relDir)) {
3043
3205
  return remoteDirCache.get(relDir);
3044
3206
  }
3045
- const parts = relDir.split(import_node_path6.default.sep).filter(Boolean);
3207
+ const parts = relDir.split(import_node_path7.default.sep).filter(Boolean);
3046
3208
  let currentParent = targetFolderId;
3047
3209
  let currentRel = "";
3048
3210
  for (const part of parts) {
3049
- currentRel = currentRel ? import_node_path6.default.join(currentRel, part) : part;
3211
+ currentRel = currentRel ? import_node_path7.default.join(currentRel, part) : part;
3050
3212
  if (remoteDirCache.has(currentRel)) {
3051
3213
  currentParent = remoteDirCache.get(currentRel);
3052
3214
  continue;
@@ -3075,8 +3237,8 @@ var init_client = __esm({
3075
3237
  };
3076
3238
  await pool.map(allFiles, async (fileItem) => {
3077
3239
  try {
3078
- const relDir = import_node_path6.default.dirname(fileItem.relPath);
3079
- const fileName = import_node_path6.default.basename(fileItem.relPath);
3240
+ const relDir = import_node_path7.default.dirname(fileItem.relPath);
3241
+ const fileName = import_node_path7.default.basename(fileItem.relPath);
3080
3242
  const parentFolderId = await ensureRemoteSubdir(relDir === "." ? "" : relDir);
3081
3243
  if (options.onFileStart) {
3082
3244
  options.onFileStart(fileItem.fullPath, fileItem.relPath);
@@ -3212,8 +3374,15 @@ var init_client = __esm({
3212
3374
  await this.init();
3213
3375
  const { PassThrough } = await import("stream");
3214
3376
  const passThrough = new PassThrough();
3215
- const remoteDir = import_node_path6.default.dirname(remotePath);
3216
- const fileName = options.name || options.filename || import_node_path6.default.basename(remotePath);
3377
+ let resolveDone;
3378
+ let rejectDone;
3379
+ const donePromise = new Promise((resolve, reject) => {
3380
+ resolveDone = resolve;
3381
+ rejectDone = reject;
3382
+ });
3383
+ passThrough.done = donePromise;
3384
+ const remoteDir = import_node_path7.default.dirname(remotePath);
3385
+ const fileName = options.name || options.filename || import_node_path7.default.basename(remotePath);
3217
3386
  const targetParentId = remoteDir === "." || remoteDir === "/" ? this.rootFolderId : await this.mkdirp(remoteDir);
3218
3387
  const mimeType = options.mimeType || "application/octet-stream";
3219
3388
  const raw = this.driveClient;
@@ -3230,9 +3399,10 @@ var init_client = __esm({
3230
3399
  fields: "id, name, mimeType, size, md5Checksum",
3231
3400
  supportsAllDrives: true
3232
3401
  }).then((res) => {
3233
- if (res.data.id && this.metadataCacheInstance) {
3402
+ const file = res.data;
3403
+ if (file.id && this.metadataCacheInstance) {
3234
3404
  this.metadataCacheInstance.upsertFile({
3235
- id: res.data.id,
3405
+ id: file.id,
3236
3406
  name: fileName,
3237
3407
  mimeType,
3238
3408
  parentId: targetParentId,
@@ -3240,8 +3410,10 @@ var init_client = __esm({
3240
3410
  trashed: false
3241
3411
  });
3242
3412
  }
3413
+ resolveDone(file);
3243
3414
  }).catch((err) => {
3244
3415
  passThrough.destroy(err);
3416
+ rejectDone(err);
3245
3417
  });
3246
3418
  return passThrough;
3247
3419
  }
@@ -3282,6 +3454,7 @@ var init_client = __esm({
3282
3454
  const client = this.driveClient;
3283
3455
  let pageToken = void 0;
3284
3456
  let totalScanned = 0;
3457
+ const rawFiles = [];
3285
3458
  do {
3286
3459
  const res = await withRetry(async () => {
3287
3460
  return await client.files.list({
@@ -3295,21 +3468,49 @@ var init_client = __esm({
3295
3468
  });
3296
3469
  });
3297
3470
  const files = res.data.files || [];
3298
- const entries = files.map((f) => ({
3299
- id: f.id,
3300
- name: f.name || "untitled",
3301
- mimeType: f.mimeType || "",
3302
- size: f.size ? parseInt(f.size, 10) : void 0,
3303
- parentId: f.parents?.[0],
3304
- md5Checksum: f.md5Checksum || void 0,
3305
- trashed: !!f.trashed,
3306
- modifiedTime: f.modifiedTime || void 0
3307
- }));
3308
- this.metadataCacheInstance.upsertFiles(entries);
3309
- totalScanned += entries.length;
3471
+ for (const f of files) {
3472
+ if (f.id) rawFiles.push(f);
3473
+ }
3474
+ totalScanned += files.length;
3310
3475
  options?.onProgress?.(totalScanned);
3311
3476
  pageToken = res.data.nextPageToken || void 0;
3312
3477
  } while (pageToken);
3478
+ const fileMap = /* @__PURE__ */ new Map();
3479
+ for (const f of rawFiles) {
3480
+ fileMap.set(f.id, f);
3481
+ }
3482
+ const pathMemo = /* @__PURE__ */ new Map();
3483
+ const rootId = this.rootFolderId;
3484
+ function computePath(id, visited = /* @__PURE__ */ new Set()) {
3485
+ if (pathMemo.has(id)) return pathMemo.get(id);
3486
+ if (visited.has(id)) return "";
3487
+ visited.add(id);
3488
+ const f = fileMap.get(id);
3489
+ if (!f || !f.name) return "";
3490
+ const parentId = f.parents?.[0];
3491
+ if (!parentId || parentId === "root" || parentId === rootId) {
3492
+ const p = `/${f.name}`;
3493
+ pathMemo.set(id, p);
3494
+ return p;
3495
+ }
3496
+ const parentPath = computePath(parentId, visited);
3497
+ const fullPath = parentPath ? `${parentPath}/${f.name}` : `/${f.name}`;
3498
+ pathMemo.set(id, fullPath);
3499
+ return fullPath;
3500
+ }
3501
+ const entries = rawFiles.map((f) => ({
3502
+ id: f.id,
3503
+ name: f.name || "untitled",
3504
+ mimeType: f.mimeType || "",
3505
+ size: f.size ? parseInt(f.size, 10) : void 0,
3506
+ parentId: f.parents?.[0],
3507
+ path: computePath(f.id),
3508
+ md5Checksum: f.md5Checksum || void 0,
3509
+ trashed: !!f.trashed,
3510
+ modifiedTime: f.modifiedTime || void 0
3511
+ }));
3512
+ this.metadataCacheInstance.upsertFiles(entries);
3513
+ this.metadataCacheInstance.pruneMissing(rawFiles.map((f) => f.id));
3313
3514
  this.metadataCacheInstance.setMeta("last_sync_timestamp", (/* @__PURE__ */ new Date()).toISOString());
3314
3515
  return this.metadataCacheInstance.getStats();
3315
3516
  }
@@ -3429,7 +3630,7 @@ __export(cli_exports, {
3429
3630
  module.exports = __toCommonJS(cli_exports);
3430
3631
  init_cjs_shims();
3431
3632
  var import_node_fs7 = __toESM(require("fs"), 1);
3432
- var import_node_path7 = __toESM(require("path"), 1);
3633
+ var import_node_path8 = __toESM(require("path"), 1);
3433
3634
  var import_commander = require("commander");
3434
3635
  var import_chalk2 = __toESM(require("chalk"), 1);
3435
3636
  var import_ora = __toESM(require("ora"), 1);
@@ -3592,7 +3793,14 @@ ${import_chalk.default.cyan("\u{1F517} Getting shareable link for:")} ${import_c
3592
3793
 
3593
3794
  // src/cli.ts
3594
3795
  var program = new import_commander.Command();
3595
- program.name("drivekit").description(import_chalk2.default.bold.cyan("\u26A1 DriveKit CLI: High-speed, flexible Google Drive tool for developers")).version("1.0.0").option("-k, --key <path>", "Path to service account JSON key file").option("-t, --token <token>", "Google OAuth2 Bearer access token");
3796
+ var pkgVersion = "1.1.1";
3797
+ try {
3798
+ const pkgPath = new URL("../package.json", importMetaUrl);
3799
+ const pkg = JSON.parse(import_node_fs7.default.readFileSync(pkgPath, "utf8"));
3800
+ if (pkg.version) pkgVersion = pkg.version;
3801
+ } catch {
3802
+ }
3803
+ program.name("drivekit").description(import_chalk2.default.bold.cyan("\u26A1 DriveKit CLI: High-speed, flexible Google Drive tool for developers")).version(pkgVersion).option("-k, --key <path>", "Path to service account JSON key file").option("-t, --token <token>", "Google OAuth2 Bearer access token");
3596
3804
  function getAuthConfig(cmdOptions) {
3597
3805
  const keyFilePath = cmdOptions.key || process.env.GOOGLE_APPLICATION_CREDENTIALS || process.env.GDRIVE_SERVICE_ACCOUNT_PATH;
3598
3806
  const accessToken = cmdOptions.token || process.env.GDRIVE_ACCESS_TOKEN;
@@ -3669,7 +3877,7 @@ program.command("upload <localFile> [remotePath]").description("Upload a file wi
3669
3877
  console.error(import_chalk2.default.red(`\u274C Local file not found: ${localFile}`));
3670
3878
  process.exit(1);
3671
3879
  }
3672
- const fileName = import_node_path7.default.basename(localFile);
3880
+ const fileName = import_node_path8.default.basename(localFile);
3673
3881
  const spinner = (0, import_ora.default)(`Preparing upload: ${fileName}...`).start();
3674
3882
  try {
3675
3883
  const client = await getClient(options);
@@ -3933,7 +4141,7 @@ program.command("login").description("Interactive 1-click browser OAuth2 sign-in
3933
4141
  if (result.tokens.refresh_token) {
3934
4142
  console.log(`Refresh Token: ${import_chalk2.default.green(result.tokens.refresh_token?.slice(0, 25) + "...")}`);
3935
4143
  }
3936
- const outPath = import_node_path7.default.resolve("./gdrive-tokens.json");
4144
+ const outPath = import_node_path8.default.resolve("./gdrive-tokens.json");
3937
4145
  import_node_fs7.default.writeFileSync(outPath, JSON.stringify(result.tokens, null, 2), "utf8");
3938
4146
  console.log(`\u{1F4BE} Saved tokens to: ${import_chalk2.default.bold(outPath)}
3939
4147
  `);
@@ -4011,19 +4219,25 @@ program.command("shared-drives").description("List accessible Google Workspace S
4011
4219
  process.exit(1);
4012
4220
  }
4013
4221
  });
4014
- program.command("serve").description("Start embedded WebDAV server to mount DriveKit directly in macOS Finder or Windows Explorer").option("-p, --port <port>", "Port number to listen on", "8080").option("-h, --host <host>", "Host address to bind to", "127.0.0.1").action(async (options) => {
4222
+ program.command("serve").description("Start embedded WebDAV server to mount DriveKit directly in macOS Finder or Windows Explorer").option("-p, --port <port>", "Port number to listen on", "8080").option("-h, --host <host>", "Host address to bind to", "127.0.0.1").option("-u, --username <username>", "HTTP Basic auth username").option("-P, --password <password>", "HTTP Basic auth password").action(async (options) => {
4015
4223
  try {
4016
4224
  const client = await getClient(options);
4017
4225
  const port = parseInt(options.port, 10) || 8080;
4018
4226
  const host = options.host || "127.0.0.1";
4227
+ const auth = options.username ? { username: options.username, password: options.password || "" } : void 0;
4019
4228
  console.log(import_chalk2.default.bold.cyan("\n\u26A1 DriveKit WebDAV Server"));
4020
4229
  console.log("Starting local WebDAV bridge to Google Drive...\n");
4021
- const serverInstance = await client.serveWebDAV({ port, host });
4230
+ const serverInstance = await client.serveWebDAV({ port, host, auth });
4022
4231
  console.log(import_chalk2.default.bold.green(`\u{1F680} Server active at: ${import_chalk2.default.underline(serverInstance.url)}`));
4232
+ if (auth) {
4233
+ console.log(import_chalk2.default.yellow(`\u{1F512} Basic Authentication: ENABLED (User: ${auth.username})`));
4234
+ } else {
4235
+ console.log(import_chalk2.default.dim("\u{1F513} Authentication: Anonymous (Localhost only recommended)"));
4236
+ }
4023
4237
  console.log(import_chalk2.default.white("\n\u{1F4CC} How to mount on macOS Finder:"));
4024
4238
  console.log(` 1. Open Finder and press ${import_chalk2.default.bold.cyan("Cmd + K")} (Connect to Server)`);
4025
4239
  console.log(` 2. Enter: ${import_chalk2.default.bold.yellow(serverInstance.url)}`);
4026
- console.log(` 3. Click ${import_chalk2.default.bold("Connect")} (Connect as Guest)
4240
+ console.log(` 3. Click ${import_chalk2.default.bold("Connect")}${auth ? ` and log in as ${auth.username}` : " (Connect as Guest)"}
4027
4241
  `);
4028
4242
  console.log(import_chalk2.default.white("\u{1F4CC} How to mount on Windows:"));
4029
4243
  console.log(` 1. Open File Explorer -> This PC -> "Map network drive"`);