drivekit 1.0.2 → 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 +1300 -33
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +1300 -31
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +1302 -22
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +294 -1
- package/dist/index.d.ts +294 -1
- package/dist/index.js +1320 -30
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
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
|
|
|
@@ -318,11 +321,13 @@ var init_path_resolver = __esm({
|
|
|
318
321
|
cache = /* @__PURE__ */ new Map();
|
|
319
322
|
cacheTTL;
|
|
320
323
|
enableCache;
|
|
324
|
+
metadataCache;
|
|
321
325
|
constructor(drive2, rootFolderId = "root", options) {
|
|
322
326
|
this.drive = drive2;
|
|
323
327
|
this.rootFolderId = rootFolderId;
|
|
324
328
|
this.enableCache = options?.enableCache ?? true;
|
|
325
329
|
this.cacheTTL = options?.cacheTTL ?? 5 * 60 * 1e3;
|
|
330
|
+
this.metadataCache = options?.metadataCache;
|
|
326
331
|
}
|
|
327
332
|
/**
|
|
328
333
|
* Normalizes a virtual path (e.g. "///Backups//2026/" -> "/Backups/2026")
|
|
@@ -337,21 +342,31 @@ var init_path_resolver = __esm({
|
|
|
337
342
|
/**
|
|
338
343
|
* Gets cache key for a path
|
|
339
344
|
*/
|
|
340
|
-
getCacheKey(
|
|
341
|
-
return `${this.rootFolderId}:${this.normalizePath(
|
|
345
|
+
getCacheKey(path9) {
|
|
346
|
+
return `${this.rootFolderId}:${this.normalizePath(path9)}`;
|
|
342
347
|
}
|
|
343
348
|
/**
|
|
344
349
|
* Clears the path cache
|
|
345
350
|
*/
|
|
346
351
|
clearCache() {
|
|
347
352
|
this.cache.clear();
|
|
353
|
+
if (this.metadataCache) {
|
|
354
|
+
this.metadataCache.clear();
|
|
355
|
+
}
|
|
348
356
|
}
|
|
349
357
|
/**
|
|
350
358
|
* Invalidate a single path from cache
|
|
351
359
|
*/
|
|
352
|
-
invalidatePath(
|
|
353
|
-
const
|
|
360
|
+
invalidatePath(path9) {
|
|
361
|
+
const norm = this.normalizePath(path9);
|
|
362
|
+
const key = this.getCacheKey(norm);
|
|
354
363
|
this.cache.delete(key);
|
|
364
|
+
if (this.metadataCache) {
|
|
365
|
+
const item = this.metadataCache.getByPath(norm);
|
|
366
|
+
if (item) {
|
|
367
|
+
this.metadataCache.deleteFile(item.id);
|
|
368
|
+
}
|
|
369
|
+
}
|
|
355
370
|
}
|
|
356
371
|
/**
|
|
357
372
|
* Resolves a path to a Google Drive item (file or folder).
|
|
@@ -367,6 +382,17 @@ var init_path_resolver = __esm({
|
|
|
367
382
|
mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER
|
|
368
383
|
};
|
|
369
384
|
}
|
|
385
|
+
if (this.metadataCache) {
|
|
386
|
+
const persistentCached = this.metadataCache.getByPath(norm);
|
|
387
|
+
if (persistentCached) {
|
|
388
|
+
return {
|
|
389
|
+
id: persistentCached.id,
|
|
390
|
+
name: persistentCached.name,
|
|
391
|
+
isFolder: persistentCached.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
|
|
392
|
+
mimeType: persistentCached.mimeType
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
}
|
|
370
396
|
if (this.enableCache) {
|
|
371
397
|
const cached = this.cache.get(this.getCacheKey(norm));
|
|
372
398
|
if (cached && cached.expiresAt > Date.now()) {
|
|
@@ -385,6 +411,21 @@ var init_path_resolver = __esm({
|
|
|
385
411
|
const segment = segments[i];
|
|
386
412
|
const isLast = i === segments.length - 1;
|
|
387
413
|
currentPath += `/${segment}`;
|
|
414
|
+
if (this.metadataCache) {
|
|
415
|
+
const pCached = this.metadataCache.getByPath(currentPath);
|
|
416
|
+
if (pCached) {
|
|
417
|
+
currentParentId = pCached.id;
|
|
418
|
+
if (isLast) {
|
|
419
|
+
return {
|
|
420
|
+
id: pCached.id,
|
|
421
|
+
name: pCached.name,
|
|
422
|
+
isFolder: pCached.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
|
|
423
|
+
mimeType: pCached.mimeType
|
|
424
|
+
};
|
|
425
|
+
}
|
|
426
|
+
continue;
|
|
427
|
+
}
|
|
428
|
+
}
|
|
388
429
|
if (this.enableCache) {
|
|
389
430
|
const cached = this.cache.get(this.getCacheKey(currentPath));
|
|
390
431
|
if (cached && cached.expiresAt > Date.now()) {
|
|
@@ -428,7 +469,18 @@ var init_path_resolver = __esm({
|
|
|
428
469
|
file = sharedResponse.data.files?.[0];
|
|
429
470
|
}
|
|
430
471
|
if (file && file.id) {
|
|
472
|
+
const segmentParentId = currentParentId;
|
|
431
473
|
currentParentId = file.id;
|
|
474
|
+
if (this.metadataCache) {
|
|
475
|
+
this.metadataCache.upsertFile({
|
|
476
|
+
id: file.id,
|
|
477
|
+
name: file.name || segment,
|
|
478
|
+
mimeType: file.mimeType || "",
|
|
479
|
+
parentId: segmentParentId,
|
|
480
|
+
path: currentPath,
|
|
481
|
+
trashed: false
|
|
482
|
+
});
|
|
483
|
+
}
|
|
432
484
|
if (this.enableCache) {
|
|
433
485
|
this.cache.set(this.getCacheKey(currentPath), {
|
|
434
486
|
id: file.id,
|
|
@@ -462,7 +514,18 @@ var init_path_resolver = __esm({
|
|
|
462
514
|
if (!newFolder.id) {
|
|
463
515
|
throw new Error(`Failed to create folder "${segment}" under parent "${currentParentId}"`);
|
|
464
516
|
}
|
|
517
|
+
const segmentParentId = currentParentId;
|
|
465
518
|
currentParentId = newFolder.id;
|
|
519
|
+
if (this.metadataCache) {
|
|
520
|
+
this.metadataCache.upsertFile({
|
|
521
|
+
id: newFolder.id,
|
|
522
|
+
name: segment,
|
|
523
|
+
mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
|
|
524
|
+
parentId: segmentParentId,
|
|
525
|
+
path: currentPath,
|
|
526
|
+
trashed: false
|
|
527
|
+
});
|
|
528
|
+
}
|
|
466
529
|
if (this.enableCache) {
|
|
467
530
|
this.cache.set(this.getCacheKey(currentPath), {
|
|
468
531
|
id: newFolder.id,
|
|
@@ -939,6 +1002,24 @@ var init_downloader = __esm({
|
|
|
939
1002
|
size: totalBytes
|
|
940
1003
|
};
|
|
941
1004
|
}
|
|
1005
|
+
/**
|
|
1006
|
+
* Returns a raw ReadableStream for the file, supporting HTTP Range requests for partial content / streaming.
|
|
1007
|
+
*/
|
|
1008
|
+
async createReadStream(fileId, options) {
|
|
1009
|
+
const headers = {};
|
|
1010
|
+
if (options?.start !== void 0 || options?.end !== void 0) {
|
|
1011
|
+
const start = options.start ?? 0;
|
|
1012
|
+
const end = options.end !== void 0 ? options.end : "";
|
|
1013
|
+
headers["Range"] = `bytes=${start}-${end}`;
|
|
1014
|
+
}
|
|
1015
|
+
const res = await withRetry(async () => {
|
|
1016
|
+
return await this.drive.files.get(
|
|
1017
|
+
{ fileId, alt: "media", supportsAllDrives: true },
|
|
1018
|
+
{ responseType: "stream", headers }
|
|
1019
|
+
);
|
|
1020
|
+
});
|
|
1021
|
+
return res.data;
|
|
1022
|
+
}
|
|
942
1023
|
};
|
|
943
1024
|
}
|
|
944
1025
|
});
|
|
@@ -1067,6 +1148,19 @@ var init_query_builder = __esm({
|
|
|
1067
1148
|
this.conditions.push(`(${condition})`);
|
|
1068
1149
|
return this;
|
|
1069
1150
|
}
|
|
1151
|
+
/**
|
|
1152
|
+
* Custom raw query condition (alias for raw)
|
|
1153
|
+
*/
|
|
1154
|
+
custom(condition) {
|
|
1155
|
+
return this.raw(condition);
|
|
1156
|
+
}
|
|
1157
|
+
/**
|
|
1158
|
+
* Filter: Exact MD5 checksum match
|
|
1159
|
+
*/
|
|
1160
|
+
md5(checksum) {
|
|
1161
|
+
this.conditions.push(`md5Checksum = '${this.escape(checksum)}'`);
|
|
1162
|
+
return this;
|
|
1163
|
+
}
|
|
1070
1164
|
/**
|
|
1071
1165
|
* Sort ordering (e.g. 'modifiedTime desc', 'name', 'folder,modifiedTime desc')
|
|
1072
1166
|
*/
|
|
@@ -1113,6 +1207,12 @@ var init_query_builder = __esm({
|
|
|
1113
1207
|
});
|
|
1114
1208
|
return res.data.files || [];
|
|
1115
1209
|
}
|
|
1210
|
+
/**
|
|
1211
|
+
* Executes query and returns array of matching files (alias for list)
|
|
1212
|
+
*/
|
|
1213
|
+
async execute() {
|
|
1214
|
+
return await this.list();
|
|
1215
|
+
}
|
|
1116
1216
|
/**
|
|
1117
1217
|
* Returns the first matching file, or null if not found
|
|
1118
1218
|
*/
|
|
@@ -1755,6 +1855,22 @@ var init_resource_refs = __esm({
|
|
|
1755
1855
|
async getLink() {
|
|
1756
1856
|
return await this.drive.getShareableLink(this.pathOrId);
|
|
1757
1857
|
}
|
|
1858
|
+
/** Returns a ReadableStream for this file, optionally with byte Range requests */
|
|
1859
|
+
async createReadStream(options) {
|
|
1860
|
+
return await this.drive.createReadStream(this.pathOrId, options);
|
|
1861
|
+
}
|
|
1862
|
+
/** Grants access to a specific email with custom role and notification */
|
|
1863
|
+
async grantAccess(options) {
|
|
1864
|
+
return await this.drive.grantAccess(this.pathOrId, options);
|
|
1865
|
+
}
|
|
1866
|
+
/** Revokes access by permission ID or user email */
|
|
1867
|
+
async revokeAccess(permissionIdOrEmail) {
|
|
1868
|
+
return await this.drive.revokeAccess(this.pathOrId, permissionIdOrEmail);
|
|
1869
|
+
}
|
|
1870
|
+
/** Lists all granted permissions on this file */
|
|
1871
|
+
async listPermissions() {
|
|
1872
|
+
return await this.drive.listPermissions(this.pathOrId);
|
|
1873
|
+
}
|
|
1758
1874
|
};
|
|
1759
1875
|
DriveFolderRef = class {
|
|
1760
1876
|
drive;
|
|
@@ -1792,22 +1908,58 @@ var init_resource_refs = __esm({
|
|
|
1792
1908
|
async watch(options = {}) {
|
|
1793
1909
|
return await this.drive.watch(this.pathOrId, options);
|
|
1794
1910
|
}
|
|
1911
|
+
/** Grants access to this entire folder */
|
|
1912
|
+
async grantAccess(options) {
|
|
1913
|
+
return await this.drive.grantAccess(this.pathOrId, options);
|
|
1914
|
+
}
|
|
1915
|
+
/** Creates a writable stream directly into a file inside this folder */
|
|
1916
|
+
async createWriteStream(fileName, options) {
|
|
1917
|
+
const targetPath = this.pathOrId.endsWith("/") ? `${this.pathOrId}${fileName}` : `${this.pathOrId}/${fileName}`;
|
|
1918
|
+
return await this.drive.createWriteStream(targetPath, options);
|
|
1919
|
+
}
|
|
1795
1920
|
};
|
|
1796
1921
|
}
|
|
1797
1922
|
});
|
|
1798
1923
|
|
|
1799
1924
|
// src/core/plugins.ts
|
|
1800
|
-
var PluginManager;
|
|
1925
|
+
var import_node_path4, PluginManager;
|
|
1801
1926
|
var init_plugins = __esm({
|
|
1802
1927
|
"src/core/plugins.ts"() {
|
|
1803
1928
|
"use strict";
|
|
1804
1929
|
init_cjs_shims();
|
|
1930
|
+
import_node_path4 = __toESM(require("path"), 1);
|
|
1805
1931
|
PluginManager = class {
|
|
1806
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
|
+
*/
|
|
1807
1937
|
use(plugin) {
|
|
1938
|
+
this.plugins = this.plugins.filter((p) => p.name !== plugin.name);
|
|
1808
1939
|
this.plugins.push(plugin);
|
|
1809
1940
|
return this;
|
|
1810
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
|
+
}
|
|
1811
1963
|
async runBeforeUpload(options) {
|
|
1812
1964
|
let current = { ...options };
|
|
1813
1965
|
for (const plugin of this.plugins) {
|
|
@@ -1852,18 +2004,708 @@ var init_plugins = __esm({
|
|
|
1852
2004
|
}
|
|
1853
2005
|
});
|
|
1854
2006
|
|
|
2007
|
+
// src/core/cache.ts
|
|
2008
|
+
var import_node_os, import_node_path5, import_node_fs5, SqliteMetadataCache, MemoryMetadataCache;
|
|
2009
|
+
var init_cache = __esm({
|
|
2010
|
+
"src/core/cache.ts"() {
|
|
2011
|
+
"use strict";
|
|
2012
|
+
init_cjs_shims();
|
|
2013
|
+
import_node_os = __toESM(require("os"), 1);
|
|
2014
|
+
import_node_path5 = __toESM(require("path"), 1);
|
|
2015
|
+
import_node_fs5 = __toESM(require("fs"), 1);
|
|
2016
|
+
SqliteMetadataCache = class {
|
|
2017
|
+
db = null;
|
|
2018
|
+
dbPath;
|
|
2019
|
+
initialized = false;
|
|
2020
|
+
fallbackMemory;
|
|
2021
|
+
constructor(customPath) {
|
|
2022
|
+
if (customPath) {
|
|
2023
|
+
this.dbPath = customPath;
|
|
2024
|
+
} else {
|
|
2025
|
+
const dir = import_node_path5.default.join(import_node_os.default.homedir(), ".drivekit");
|
|
2026
|
+
if (!import_node_fs5.default.existsSync(dir)) {
|
|
2027
|
+
try {
|
|
2028
|
+
import_node_fs5.default.mkdirSync(dir, { recursive: true });
|
|
2029
|
+
} catch {
|
|
2030
|
+
}
|
|
2031
|
+
}
|
|
2032
|
+
this.dbPath = import_node_path5.default.join(dir, "cache.db");
|
|
2033
|
+
}
|
|
2034
|
+
}
|
|
2035
|
+
init() {
|
|
2036
|
+
if (this.initialized) return;
|
|
2037
|
+
try {
|
|
2038
|
+
const { DatabaseSync } = require("sqlite");
|
|
2039
|
+
if (!DatabaseSync) {
|
|
2040
|
+
throw new Error("DatabaseSync not available");
|
|
2041
|
+
}
|
|
2042
|
+
this.db = new DatabaseSync(this.dbPath);
|
|
2043
|
+
this.db.exec(`
|
|
2044
|
+
PRAGMA journal_mode = WAL;
|
|
2045
|
+
PRAGMA synchronous = NORMAL;
|
|
2046
|
+
|
|
2047
|
+
CREATE TABLE IF NOT EXISTS files (
|
|
2048
|
+
id TEXT PRIMARY KEY,
|
|
2049
|
+
name TEXT NOT NULL,
|
|
2050
|
+
mimeType TEXT,
|
|
2051
|
+
size INTEGER,
|
|
2052
|
+
parentId TEXT,
|
|
2053
|
+
path TEXT,
|
|
2054
|
+
md5Checksum TEXT,
|
|
2055
|
+
trashed INTEGER DEFAULT 0,
|
|
2056
|
+
modifiedTime TEXT,
|
|
2057
|
+
updatedAt INTEGER
|
|
2058
|
+
);
|
|
2059
|
+
|
|
2060
|
+
CREATE TABLE IF NOT EXISTS meta (
|
|
2061
|
+
key TEXT PRIMARY KEY,
|
|
2062
|
+
value TEXT NOT NULL
|
|
2063
|
+
);
|
|
2064
|
+
|
|
2065
|
+
CREATE INDEX IF NOT EXISTS idx_files_path ON files(path);
|
|
2066
|
+
CREATE INDEX IF NOT EXISTS idx_files_parent ON files(parentId);
|
|
2067
|
+
CREATE INDEX IF NOT EXISTS idx_files_md5 ON files(md5Checksum);
|
|
2068
|
+
CREATE INDEX IF NOT EXISTS idx_files_name ON files(name);
|
|
2069
|
+
`);
|
|
2070
|
+
this.initialized = true;
|
|
2071
|
+
} catch (err) {
|
|
2072
|
+
this.fallbackMemory = new MemoryMetadataCache();
|
|
2073
|
+
this.fallbackMemory.init();
|
|
2074
|
+
this.initialized = true;
|
|
2075
|
+
this.db = null;
|
|
2076
|
+
}
|
|
2077
|
+
}
|
|
2078
|
+
getById(id) {
|
|
2079
|
+
if (this.fallbackMemory) return this.fallbackMemory.getById(id);
|
|
2080
|
+
if (!this.initialized || !this.db) return null;
|
|
2081
|
+
const stmt = this.db.prepare("SELECT * FROM files WHERE id = ?");
|
|
2082
|
+
const row = stmt.get(id);
|
|
2083
|
+
return row ? this.mapRow(row) : null;
|
|
2084
|
+
}
|
|
2085
|
+
getByPath(normalizedPath) {
|
|
2086
|
+
if (this.fallbackMemory) return this.fallbackMemory.getByPath(normalizedPath);
|
|
2087
|
+
if (!this.initialized || !this.db) return null;
|
|
2088
|
+
const stmt = this.db.prepare("SELECT * FROM files WHERE path = ? AND trashed = 0 LIMIT 1");
|
|
2089
|
+
const row = stmt.get(normalizedPath);
|
|
2090
|
+
return row ? this.mapRow(row) : null;
|
|
2091
|
+
}
|
|
2092
|
+
getChildren(parentId) {
|
|
2093
|
+
if (this.fallbackMemory) return this.fallbackMemory.getChildren(parentId);
|
|
2094
|
+
if (!this.initialized || !this.db) return [];
|
|
2095
|
+
const stmt = this.db.prepare("SELECT * FROM files WHERE parentId = ? AND trashed = 0 ORDER BY name ASC");
|
|
2096
|
+
const rows = stmt.all(parentId);
|
|
2097
|
+
return rows.map((r) => this.mapRow(r));
|
|
2098
|
+
}
|
|
2099
|
+
findByMd5(md5) {
|
|
2100
|
+
if (this.fallbackMemory) return this.fallbackMemory.findByMd5(md5);
|
|
2101
|
+
if (!this.initialized || !this.db || !md5) return null;
|
|
2102
|
+
const stmt = this.db.prepare("SELECT * FROM files WHERE md5Checksum = ? AND trashed = 0 LIMIT 1");
|
|
2103
|
+
const row = stmt.get(md5.toLowerCase());
|
|
2104
|
+
return row ? this.mapRow(row) : null;
|
|
2105
|
+
}
|
|
2106
|
+
searchByName(query) {
|
|
2107
|
+
if (this.fallbackMemory) return this.fallbackMemory.searchByName(query);
|
|
2108
|
+
if (!this.initialized || !this.db) return [];
|
|
2109
|
+
const stmt = this.db.prepare("SELECT * FROM files WHERE name LIKE ? AND trashed = 0 LIMIT 50");
|
|
2110
|
+
const rows = stmt.all(`%${query}%`);
|
|
2111
|
+
return rows.map((r) => this.mapRow(r));
|
|
2112
|
+
}
|
|
2113
|
+
upsertFile(entry) {
|
|
2114
|
+
if (this.fallbackMemory) {
|
|
2115
|
+
this.fallbackMemory.upsertFile(entry);
|
|
2116
|
+
return;
|
|
2117
|
+
}
|
|
2118
|
+
if (!this.initialized || !this.db) return;
|
|
2119
|
+
const stmt = this.db.prepare(`
|
|
2120
|
+
INSERT INTO files (id, name, mimeType, size, parentId, path, md5Checksum, trashed, modifiedTime, updatedAt)
|
|
2121
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
2122
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
2123
|
+
name = excluded.name,
|
|
2124
|
+
mimeType = excluded.mimeType,
|
|
2125
|
+
size = excluded.size,
|
|
2126
|
+
parentId = excluded.parentId,
|
|
2127
|
+
path = COALESCE(excluded.path, files.path),
|
|
2128
|
+
md5Checksum = excluded.md5Checksum,
|
|
2129
|
+
trashed = excluded.trashed,
|
|
2130
|
+
modifiedTime = excluded.modifiedTime,
|
|
2131
|
+
updatedAt = excluded.updatedAt
|
|
2132
|
+
`);
|
|
2133
|
+
stmt.run(
|
|
2134
|
+
entry.id,
|
|
2135
|
+
entry.name,
|
|
2136
|
+
entry.mimeType ?? null,
|
|
2137
|
+
entry.size ?? null,
|
|
2138
|
+
entry.parentId ?? null,
|
|
2139
|
+
entry.path ?? null,
|
|
2140
|
+
entry.md5Checksum ? entry.md5Checksum.toLowerCase() : null,
|
|
2141
|
+
entry.trashed ? 1 : 0,
|
|
2142
|
+
entry.modifiedTime ?? null,
|
|
2143
|
+
entry.updatedAt ?? Date.now()
|
|
2144
|
+
);
|
|
2145
|
+
}
|
|
2146
|
+
upsertFiles(entries) {
|
|
2147
|
+
if (this.fallbackMemory) {
|
|
2148
|
+
this.fallbackMemory.upsertFiles(entries);
|
|
2149
|
+
return;
|
|
2150
|
+
}
|
|
2151
|
+
if (!this.initialized || !this.db || entries.length === 0) return;
|
|
2152
|
+
this.db.exec("BEGIN TRANSACTION;");
|
|
2153
|
+
try {
|
|
2154
|
+
for (const entry of entries) {
|
|
2155
|
+
this.upsertFile(entry);
|
|
2156
|
+
}
|
|
2157
|
+
this.db.exec("COMMIT;");
|
|
2158
|
+
} catch (e) {
|
|
2159
|
+
this.db.exec("ROLLBACK;");
|
|
2160
|
+
throw e;
|
|
2161
|
+
}
|
|
2162
|
+
}
|
|
2163
|
+
deleteFile(id) {
|
|
2164
|
+
if (this.fallbackMemory) {
|
|
2165
|
+
this.fallbackMemory.deleteFile(id);
|
|
2166
|
+
return;
|
|
2167
|
+
}
|
|
2168
|
+
if (!this.initialized || !this.db) return;
|
|
2169
|
+
const stmt = this.db.prepare("DELETE FROM files WHERE id = ?");
|
|
2170
|
+
stmt.run(id);
|
|
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
|
+
}
|
|
2196
|
+
clear() {
|
|
2197
|
+
if (this.fallbackMemory) {
|
|
2198
|
+
this.fallbackMemory.clear();
|
|
2199
|
+
return;
|
|
2200
|
+
}
|
|
2201
|
+
if (!this.initialized || !this.db) return;
|
|
2202
|
+
this.db.exec("DELETE FROM files; DELETE FROM meta;");
|
|
2203
|
+
}
|
|
2204
|
+
getMeta(key) {
|
|
2205
|
+
if (this.fallbackMemory) return this.fallbackMemory.getMeta(key);
|
|
2206
|
+
if (!this.initialized || !this.db) return null;
|
|
2207
|
+
const stmt = this.db.prepare("SELECT value FROM meta WHERE key = ?");
|
|
2208
|
+
const row = stmt.get(key);
|
|
2209
|
+
return row ? row.value : null;
|
|
2210
|
+
}
|
|
2211
|
+
setMeta(key, value) {
|
|
2212
|
+
if (this.fallbackMemory) {
|
|
2213
|
+
this.fallbackMemory.setMeta(key, value);
|
|
2214
|
+
return;
|
|
2215
|
+
}
|
|
2216
|
+
if (!this.initialized || !this.db) return;
|
|
2217
|
+
const stmt = this.db.prepare(`
|
|
2218
|
+
INSERT INTO meta (key, value) VALUES (?, ?)
|
|
2219
|
+
ON CONFLICT(key) DO UPDATE SET value = excluded.value
|
|
2220
|
+
`);
|
|
2221
|
+
stmt.run(key, value);
|
|
2222
|
+
}
|
|
2223
|
+
getStats() {
|
|
2224
|
+
if (this.fallbackMemory) return this.fallbackMemory.getStats();
|
|
2225
|
+
if (!this.initialized || !this.db) {
|
|
2226
|
+
return {
|
|
2227
|
+
fileCount: 0,
|
|
2228
|
+
folderCount: 0,
|
|
2229
|
+
totalSizeBytes: 0,
|
|
2230
|
+
lastSyncTime: null,
|
|
2231
|
+
databasePath: this.dbPath
|
|
2232
|
+
};
|
|
2233
|
+
}
|
|
2234
|
+
const fileCountRow = this.db.prepare(
|
|
2235
|
+
"SELECT COUNT(*) as count FROM files WHERE mimeType != 'application/vnd.google-apps.folder' AND trashed = 0"
|
|
2236
|
+
).get();
|
|
2237
|
+
const folderCountRow = this.db.prepare(
|
|
2238
|
+
"SELECT COUNT(*) as count FROM files WHERE mimeType = 'application/vnd.google-apps.folder' AND trashed = 0"
|
|
2239
|
+
).get();
|
|
2240
|
+
const totalSizeRow = this.db.prepare(
|
|
2241
|
+
"SELECT SUM(size) as total FROM files WHERE trashed = 0"
|
|
2242
|
+
).get();
|
|
2243
|
+
const lastSync = this.getMeta("last_sync_timestamp");
|
|
2244
|
+
return {
|
|
2245
|
+
fileCount: fileCountRow?.count || 0,
|
|
2246
|
+
folderCount: folderCountRow?.count || 0,
|
|
2247
|
+
totalSizeBytes: totalSizeRow?.total || 0,
|
|
2248
|
+
lastSyncTime: lastSync,
|
|
2249
|
+
databasePath: this.dbPath
|
|
2250
|
+
};
|
|
2251
|
+
}
|
|
2252
|
+
close() {
|
|
2253
|
+
if (this.fallbackMemory) {
|
|
2254
|
+
this.fallbackMemory.close();
|
|
2255
|
+
this.fallbackMemory = void 0;
|
|
2256
|
+
}
|
|
2257
|
+
if (this.db) {
|
|
2258
|
+
try {
|
|
2259
|
+
this.db.close();
|
|
2260
|
+
} catch {
|
|
2261
|
+
}
|
|
2262
|
+
this.initialized = false;
|
|
2263
|
+
this.db = null;
|
|
2264
|
+
}
|
|
2265
|
+
}
|
|
2266
|
+
mapRow(row) {
|
|
2267
|
+
return {
|
|
2268
|
+
id: row.id,
|
|
2269
|
+
name: row.name,
|
|
2270
|
+
mimeType: row.mimeType,
|
|
2271
|
+
size: row.size != null ? Number(row.size) : void 0,
|
|
2272
|
+
parentId: row.parentId || void 0,
|
|
2273
|
+
path: row.path || void 0,
|
|
2274
|
+
md5Checksum: row.md5Checksum || void 0,
|
|
2275
|
+
trashed: row.trashed === 1,
|
|
2276
|
+
modifiedTime: row.modifiedTime || void 0,
|
|
2277
|
+
updatedAt: row.updatedAt != null ? Number(row.updatedAt) : void 0
|
|
2278
|
+
};
|
|
2279
|
+
}
|
|
2280
|
+
};
|
|
2281
|
+
MemoryMetadataCache = class {
|
|
2282
|
+
files = /* @__PURE__ */ new Map();
|
|
2283
|
+
meta = /* @__PURE__ */ new Map();
|
|
2284
|
+
init() {
|
|
2285
|
+
}
|
|
2286
|
+
getById(id) {
|
|
2287
|
+
return this.files.get(id) || null;
|
|
2288
|
+
}
|
|
2289
|
+
getByPath(normalizedPath) {
|
|
2290
|
+
for (const f of this.files.values()) {
|
|
2291
|
+
if (f.path === normalizedPath && !f.trashed) return f;
|
|
2292
|
+
}
|
|
2293
|
+
return null;
|
|
2294
|
+
}
|
|
2295
|
+
getChildren(parentId) {
|
|
2296
|
+
const list = [];
|
|
2297
|
+
for (const f of this.files.values()) {
|
|
2298
|
+
if (f.parentId === parentId && !f.trashed) list.push(f);
|
|
2299
|
+
}
|
|
2300
|
+
return list;
|
|
2301
|
+
}
|
|
2302
|
+
findByMd5(md5) {
|
|
2303
|
+
const target = md5.toLowerCase();
|
|
2304
|
+
for (const f of this.files.values()) {
|
|
2305
|
+
if (f.md5Checksum?.toLowerCase() === target && !f.trashed) return f;
|
|
2306
|
+
}
|
|
2307
|
+
return null;
|
|
2308
|
+
}
|
|
2309
|
+
searchByName(query) {
|
|
2310
|
+
const q = query.toLowerCase();
|
|
2311
|
+
const list = [];
|
|
2312
|
+
for (const f of this.files.values()) {
|
|
2313
|
+
if (f.name.toLowerCase().includes(q) && !f.trashed) list.push(f);
|
|
2314
|
+
}
|
|
2315
|
+
return list;
|
|
2316
|
+
}
|
|
2317
|
+
upsertFile(entry) {
|
|
2318
|
+
this.files.set(entry.id, { ...entry, updatedAt: Date.now() });
|
|
2319
|
+
}
|
|
2320
|
+
upsertFiles(entries) {
|
|
2321
|
+
for (const e of entries) this.upsertFile(e);
|
|
2322
|
+
}
|
|
2323
|
+
deleteFile(id) {
|
|
2324
|
+
this.files.delete(id);
|
|
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
|
+
}
|
|
2337
|
+
clear() {
|
|
2338
|
+
this.files.clear();
|
|
2339
|
+
this.meta.clear();
|
|
2340
|
+
}
|
|
2341
|
+
getMeta(key) {
|
|
2342
|
+
return this.meta.get(key) || null;
|
|
2343
|
+
}
|
|
2344
|
+
setMeta(key, value) {
|
|
2345
|
+
this.meta.set(key, value);
|
|
2346
|
+
}
|
|
2347
|
+
getStats() {
|
|
2348
|
+
let fileCount = 0;
|
|
2349
|
+
let folderCount = 0;
|
|
2350
|
+
let totalSizeBytes = 0;
|
|
2351
|
+
for (const f of this.files.values()) {
|
|
2352
|
+
if (f.trashed) continue;
|
|
2353
|
+
if (f.mimeType === "application/vnd.google-apps.folder") folderCount++;
|
|
2354
|
+
else {
|
|
2355
|
+
fileCount++;
|
|
2356
|
+
totalSizeBytes += f.size || 0;
|
|
2357
|
+
}
|
|
2358
|
+
}
|
|
2359
|
+
return {
|
|
2360
|
+
fileCount,
|
|
2361
|
+
folderCount,
|
|
2362
|
+
totalSizeBytes,
|
|
2363
|
+
lastSyncTime: this.meta.get("last_sync_timestamp") || null,
|
|
2364
|
+
databasePath: ":memory:"
|
|
2365
|
+
};
|
|
2366
|
+
}
|
|
2367
|
+
close() {
|
|
2368
|
+
this.clear();
|
|
2369
|
+
}
|
|
2370
|
+
};
|
|
2371
|
+
}
|
|
2372
|
+
});
|
|
2373
|
+
|
|
2374
|
+
// src/server/webdav.ts
|
|
2375
|
+
var webdav_exports = {};
|
|
2376
|
+
__export(webdav_exports, {
|
|
2377
|
+
escapeXml: () => escapeXml,
|
|
2378
|
+
startWebDAVServer: () => startWebDAVServer
|
|
2379
|
+
});
|
|
2380
|
+
function escapeXml(unsafe) {
|
|
2381
|
+
return unsafe.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
2382
|
+
}
|
|
2383
|
+
async function startWebDAVServer(drive2, options = {}) {
|
|
2384
|
+
const port = options.port || 8080;
|
|
2385
|
+
const host = options.host || "127.0.0.1";
|
|
2386
|
+
await drive2.init();
|
|
2387
|
+
const server = import_node_http2.default.createServer(async (req, res) => {
|
|
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
|
+
}
|
|
2410
|
+
const parsedUrl = import_node_url.default.parse(req.url || "/", true);
|
|
2411
|
+
const decodedPath = decodeURIComponent(parsedUrl.pathname || "/");
|
|
2412
|
+
const virtualPath = decodedPath === "" ? "/" : decodedPath;
|
|
2413
|
+
switch (req.method) {
|
|
2414
|
+
case "OPTIONS": {
|
|
2415
|
+
res.writeHead(200, {
|
|
2416
|
+
DAV: "1, 2",
|
|
2417
|
+
Allow: "OPTIONS, GET, HEAD, POST, PUT, DELETE, MKCOL, MOVE, COPY, PROPFIND",
|
|
2418
|
+
"MS-Author-Via": "DAV",
|
|
2419
|
+
"Accept-Ranges": "bytes"
|
|
2420
|
+
});
|
|
2421
|
+
res.end();
|
|
2422
|
+
return;
|
|
2423
|
+
}
|
|
2424
|
+
case "PROPFIND": {
|
|
2425
|
+
const depth = req.headers["depth"] || "1";
|
|
2426
|
+
const xml = await handlePropfind(drive2, virtualPath, depth);
|
|
2427
|
+
res.writeHead(207, {
|
|
2428
|
+
"Content-Type": "application/xml; charset=utf-8"
|
|
2429
|
+
});
|
|
2430
|
+
res.end(xml);
|
|
2431
|
+
return;
|
|
2432
|
+
}
|
|
2433
|
+
case "GET":
|
|
2434
|
+
case "HEAD": {
|
|
2435
|
+
if (virtualPath === "/" || virtualPath === "") {
|
|
2436
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
|
2437
|
+
res.end("<h1>DriveKit WebDAV Server Running</h1><p>Connect via Finder, File Explorer, or WebDAV client.</p>");
|
|
2438
|
+
return;
|
|
2439
|
+
}
|
|
2440
|
+
try {
|
|
2441
|
+
const file = await drive2.getFile(virtualPath);
|
|
2442
|
+
if (file.mimeType === "application/vnd.google-apps.folder") {
|
|
2443
|
+
res.writeHead(405, { "Content-Type": "text/plain" });
|
|
2444
|
+
res.end("Cannot GET a directory");
|
|
2445
|
+
return;
|
|
2446
|
+
}
|
|
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
|
+
}
|
|
2471
|
+
} else {
|
|
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
|
+
}
|
|
2483
|
+
}
|
|
2484
|
+
} catch (e) {
|
|
2485
|
+
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
2486
|
+
res.end("File Not Found");
|
|
2487
|
+
}
|
|
2488
|
+
return;
|
|
2489
|
+
}
|
|
2490
|
+
case "PUT": {
|
|
2491
|
+
const remoteDir = import_node_path6.default.dirname(virtualPath);
|
|
2492
|
+
await drive2.mkdirp(remoteDir);
|
|
2493
|
+
let existed = false;
|
|
2494
|
+
try {
|
|
2495
|
+
const existingFile = await drive2.getFile(virtualPath);
|
|
2496
|
+
if (existingFile && existingFile.id) {
|
|
2497
|
+
existed = true;
|
|
2498
|
+
}
|
|
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
|
+
}
|
|
2514
|
+
return;
|
|
2515
|
+
}
|
|
2516
|
+
case "MKCOL": {
|
|
2517
|
+
try {
|
|
2518
|
+
await drive2.mkdirp(virtualPath);
|
|
2519
|
+
res.writeHead(201, { "Content-Type": "text/plain" });
|
|
2520
|
+
res.end("Collection Created");
|
|
2521
|
+
} catch (err) {
|
|
2522
|
+
res.writeHead(500, { "Content-Type": "text/plain" });
|
|
2523
|
+
res.end(err.message);
|
|
2524
|
+
}
|
|
2525
|
+
return;
|
|
2526
|
+
}
|
|
2527
|
+
case "DELETE": {
|
|
2528
|
+
try {
|
|
2529
|
+
await drive2.delete(virtualPath, true);
|
|
2530
|
+
res.writeHead(204);
|
|
2531
|
+
res.end();
|
|
2532
|
+
} catch (err) {
|
|
2533
|
+
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
2534
|
+
res.end("Not Found");
|
|
2535
|
+
}
|
|
2536
|
+
return;
|
|
2537
|
+
}
|
|
2538
|
+
case "MOVE": {
|
|
2539
|
+
const destination = req.headers["destination"];
|
|
2540
|
+
if (!destination || typeof destination !== "string") {
|
|
2541
|
+
res.writeHead(400, { "Content-Type": "text/plain" });
|
|
2542
|
+
res.end("Destination header missing");
|
|
2543
|
+
return;
|
|
2544
|
+
}
|
|
2545
|
+
try {
|
|
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);
|
|
2563
|
+
}
|
|
2564
|
+
res.writeHead(201);
|
|
2565
|
+
res.end("Moved");
|
|
2566
|
+
} catch (err) {
|
|
2567
|
+
res.writeHead(500, { "Content-Type": "text/plain" });
|
|
2568
|
+
res.end(err.message);
|
|
2569
|
+
}
|
|
2570
|
+
return;
|
|
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
|
+
}
|
|
2600
|
+
default: {
|
|
2601
|
+
res.writeHead(501, { "Content-Type": "text/plain" });
|
|
2602
|
+
res.end("Method Not Implemented");
|
|
2603
|
+
}
|
|
2604
|
+
}
|
|
2605
|
+
} catch (globalErr) {
|
|
2606
|
+
res.writeHead(500, { "Content-Type": "text/plain" });
|
|
2607
|
+
res.end(`Internal Server Error: ${globalErr.message}`);
|
|
2608
|
+
}
|
|
2609
|
+
});
|
|
2610
|
+
return new Promise((resolve) => {
|
|
2611
|
+
server.listen(port, host, () => {
|
|
2612
|
+
const serverUrl = `http://${host}:${port}`;
|
|
2613
|
+
resolve({
|
|
2614
|
+
server,
|
|
2615
|
+
url: serverUrl,
|
|
2616
|
+
close: () => new Promise((resClose) => server.close(() => resClose()))
|
|
2617
|
+
});
|
|
2618
|
+
});
|
|
2619
|
+
});
|
|
2620
|
+
}
|
|
2621
|
+
async function handlePropfind(drive2, virtualPath, depth) {
|
|
2622
|
+
const responses = [];
|
|
2623
|
+
let isFolder = false;
|
|
2624
|
+
let selfItem = null;
|
|
2625
|
+
if (virtualPath === "/" || virtualPath === "") {
|
|
2626
|
+
isFolder = true;
|
|
2627
|
+
responses.push(renderWebDAVResponse("/", true, 0, (/* @__PURE__ */ new Date()).toISOString()));
|
|
2628
|
+
} else {
|
|
2629
|
+
try {
|
|
2630
|
+
selfItem = await drive2.getFile(virtualPath);
|
|
2631
|
+
isFolder = selfItem.mimeType === "application/vnd.google-apps.folder";
|
|
2632
|
+
responses.push(
|
|
2633
|
+
renderWebDAVResponse(
|
|
2634
|
+
virtualPath,
|
|
2635
|
+
isFolder,
|
|
2636
|
+
selfItem.size ? parseInt(selfItem.size, 10) : 0,
|
|
2637
|
+
selfItem.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
|
|
2638
|
+
)
|
|
2639
|
+
);
|
|
2640
|
+
} catch {
|
|
2641
|
+
return `<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:"></D:multistatus>`;
|
|
2642
|
+
}
|
|
2643
|
+
}
|
|
2644
|
+
if (isFolder && depth !== "0") {
|
|
2645
|
+
try {
|
|
2646
|
+
const children = await drive2.ls(virtualPath);
|
|
2647
|
+
for (const child of children) {
|
|
2648
|
+
const childIsFolder = child.mimeType === "application/vnd.google-apps.folder";
|
|
2649
|
+
const childPath = virtualPath === "/" ? `/${child.name}` : `${virtualPath}/${child.name}`;
|
|
2650
|
+
responses.push(
|
|
2651
|
+
renderWebDAVResponse(
|
|
2652
|
+
childPath,
|
|
2653
|
+
childIsFolder,
|
|
2654
|
+
child.size ? parseInt(child.size, 10) : 0,
|
|
2655
|
+
child.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
|
|
2656
|
+
)
|
|
2657
|
+
);
|
|
2658
|
+
}
|
|
2659
|
+
} catch {
|
|
2660
|
+
}
|
|
2661
|
+
}
|
|
2662
|
+
return `<?xml version="1.0" encoding="utf-8"?>
|
|
2663
|
+
<D:multistatus xmlns:D="DAV:">
|
|
2664
|
+
${responses.join("\n")}
|
|
2665
|
+
</D:multistatus>`;
|
|
2666
|
+
}
|
|
2667
|
+
function renderWebDAVResponse(href, isDir, size, modifiedTime) {
|
|
2668
|
+
const encodedHref = encodeURI(href);
|
|
2669
|
+
const displayName = escapeXml(import_node_path6.default.basename(href) || "root");
|
|
2670
|
+
const resourceType = isDir ? "<D:collection/>" : "";
|
|
2671
|
+
const dateFormatted = new Date(modifiedTime).toUTCString();
|
|
2672
|
+
return ` <D:response>
|
|
2673
|
+
<D:href>${encodedHref}</D:href>
|
|
2674
|
+
<D:propstat>
|
|
2675
|
+
<D:prop>
|
|
2676
|
+
<D:displayname>${displayName}</D:displayname>
|
|
2677
|
+
<D:resourcetype>${resourceType}</D:resourcetype>
|
|
2678
|
+
<D:getcontentlength>${isDir ? "0" : size}</D:getcontentlength>
|
|
2679
|
+
<D:getlastmodified>${dateFormatted}</D:getlastmodified>
|
|
2680
|
+
<D:status>HTTP/1.1 200 OK</D:status>
|
|
2681
|
+
</D:prop>
|
|
2682
|
+
<D:status>HTTP/1.1 200 OK</D:status>
|
|
2683
|
+
</D:propstat>
|
|
2684
|
+
</D:response>`;
|
|
2685
|
+
}
|
|
2686
|
+
var import_node_http2, import_node_url, import_node_path6;
|
|
2687
|
+
var init_webdav = __esm({
|
|
2688
|
+
"src/server/webdav.ts"() {
|
|
2689
|
+
"use strict";
|
|
2690
|
+
init_cjs_shims();
|
|
2691
|
+
import_node_http2 = __toESM(require("http"), 1);
|
|
2692
|
+
import_node_url = __toESM(require("url"), 1);
|
|
2693
|
+
import_node_path6 = __toESM(require("path"), 1);
|
|
2694
|
+
}
|
|
2695
|
+
});
|
|
2696
|
+
|
|
1855
2697
|
// src/core/client.ts
|
|
1856
2698
|
var client_exports = {};
|
|
1857
2699
|
__export(client_exports, {
|
|
1858
2700
|
DriveKit: () => DriveKit
|
|
1859
2701
|
});
|
|
1860
|
-
var
|
|
2702
|
+
var import_node_fs6, import_node_path7, import_drive3, DriveKit;
|
|
1861
2703
|
var init_client = __esm({
|
|
1862
2704
|
"src/core/client.ts"() {
|
|
1863
2705
|
"use strict";
|
|
1864
2706
|
init_cjs_shims();
|
|
1865
|
-
|
|
1866
|
-
|
|
2707
|
+
import_node_fs6 = __toESM(require("fs"), 1);
|
|
2708
|
+
import_node_path7 = __toESM(require("path"), 1);
|
|
1867
2709
|
import_drive3 = require("@googleapis/drive");
|
|
1868
2710
|
init_authenticator();
|
|
1869
2711
|
init_path_resolver();
|
|
@@ -1880,13 +2722,15 @@ var init_client = __esm({
|
|
|
1880
2722
|
init_retry();
|
|
1881
2723
|
init_format();
|
|
1882
2724
|
init_mime();
|
|
1883
|
-
|
|
2725
|
+
init_cache();
|
|
2726
|
+
DriveKit = class _DriveKit {
|
|
1884
2727
|
options;
|
|
1885
2728
|
authenticator;
|
|
1886
2729
|
driveClient = null;
|
|
1887
2730
|
pathResolverInstance = null;
|
|
1888
2731
|
uploaderInstance = null;
|
|
1889
2732
|
downloaderInstance = null;
|
|
2733
|
+
metadataCacheInstance = null;
|
|
1890
2734
|
rootFolderId;
|
|
1891
2735
|
pluginManager = new PluginManager();
|
|
1892
2736
|
constructor(options = {}) {
|
|
@@ -1920,9 +2764,14 @@ var init_client = __esm({
|
|
|
1920
2764
|
if (!this.driveClient) {
|
|
1921
2765
|
const auth = await this.authenticator.getAuthClient();
|
|
1922
2766
|
this.driveClient = (0, import_drive3.drive)({ version: "v3", auth });
|
|
2767
|
+
if (this.options.enablePersistentCache !== false) {
|
|
2768
|
+
this.metadataCacheInstance = new SqliteMetadataCache(this.options.cacheDatabasePath);
|
|
2769
|
+
this.metadataCacheInstance.init();
|
|
2770
|
+
}
|
|
1923
2771
|
this.pathResolverInstance = new PathResolver(this.driveClient, this.rootFolderId, {
|
|
1924
2772
|
enableCache: this.options.enablePathCache ?? true,
|
|
1925
|
-
cacheTTL: this.options.pathCacheTTL
|
|
2773
|
+
cacheTTL: this.options.pathCacheTTL,
|
|
2774
|
+
metadataCache: this.metadataCacheInstance || void 0
|
|
1926
2775
|
});
|
|
1927
2776
|
this.uploaderInstance = new ResumableUploader(
|
|
1928
2777
|
this.driveClient,
|
|
@@ -2004,8 +2853,9 @@ var init_client = __esm({
|
|
|
2004
2853
|
* Lists contents of a folder (by folder ID or path)
|
|
2005
2854
|
*/
|
|
2006
2855
|
async ls(folderIdOrPath = "/") {
|
|
2007
|
-
if (folderIdOrPath === "/" || folderIdOrPath === "root") {
|
|
2008
|
-
|
|
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();
|
|
2009
2859
|
}
|
|
2010
2860
|
const folderId = await this.resolveId(folderIdOrPath);
|
|
2011
2861
|
return await this.query().inFolder(folderId).notTrashed().orderBy("folder,name").list();
|
|
@@ -2027,16 +2877,71 @@ var init_client = __esm({
|
|
|
2027
2877
|
if (parentId && parentId.startsWith("/")) {
|
|
2028
2878
|
parentId = await this.mkdirp(parentId);
|
|
2029
2879
|
}
|
|
2030
|
-
|
|
2031
|
-
|
|
2880
|
+
const targetName = opts.name || opts.filename;
|
|
2881
|
+
if (opts.overwrite && targetName && parentId) {
|
|
2882
|
+
const existing = await this.query().inFolder(parentId).nameEquals(targetName).notTrashed().first();
|
|
2032
2883
|
if (existing?.id) {
|
|
2033
2884
|
await this.delete(existing.id, true);
|
|
2034
2885
|
}
|
|
2035
2886
|
}
|
|
2887
|
+
if (opts.deduplicate && typeof opts.source === "string" && import_node_fs6.default.existsSync(opts.source)) {
|
|
2888
|
+
const localMd5 = await calculateFileMd5(opts.source);
|
|
2889
|
+
let existingId;
|
|
2890
|
+
if (this.metadataCacheInstance) {
|
|
2891
|
+
const cached = this.metadataCacheInstance.findByMd5(localMd5);
|
|
2892
|
+
if (cached) existingId = cached.id;
|
|
2893
|
+
}
|
|
2894
|
+
if (!existingId) {
|
|
2895
|
+
const found = await this.query().md5(localMd5).notTrashed().first();
|
|
2896
|
+
if (found?.id) {
|
|
2897
|
+
existingId = found.id;
|
|
2898
|
+
}
|
|
2899
|
+
}
|
|
2900
|
+
if (existingId) {
|
|
2901
|
+
const fileName = targetName || import_node_path7.default.basename(opts.source);
|
|
2902
|
+
const raw = await this.getRawClient();
|
|
2903
|
+
const copyRes = await withRetry(async () => {
|
|
2904
|
+
return await raw.files.copy({
|
|
2905
|
+
fileId: existingId,
|
|
2906
|
+
requestBody: {
|
|
2907
|
+
name: fileName,
|
|
2908
|
+
parents: parentId ? [parentId] : void 0,
|
|
2909
|
+
description: opts.description
|
|
2910
|
+
},
|
|
2911
|
+
fields: "id, name, mimeType, size, modifiedTime, md5Checksum",
|
|
2912
|
+
supportsAllDrives: true
|
|
2913
|
+
});
|
|
2914
|
+
});
|
|
2915
|
+
const file = copyRes.data;
|
|
2916
|
+
if (this.metadataCacheInstance && file.id) {
|
|
2917
|
+
this.metadataCacheInstance.upsertFile({
|
|
2918
|
+
id: file.id,
|
|
2919
|
+
name: file.name || fileName,
|
|
2920
|
+
mimeType: file.mimeType || "",
|
|
2921
|
+
size: file.size ? parseInt(file.size, 10) : void 0,
|
|
2922
|
+
parentId,
|
|
2923
|
+
md5Checksum: localMd5,
|
|
2924
|
+
trashed: false
|
|
2925
|
+
});
|
|
2926
|
+
}
|
|
2927
|
+
return await this.pluginManager.runAfterUpload(file);
|
|
2928
|
+
}
|
|
2929
|
+
}
|
|
2036
2930
|
const uploaded = await uploader.upload({
|
|
2037
2931
|
...opts,
|
|
2932
|
+
name: targetName,
|
|
2038
2933
|
parent: parentId
|
|
2039
2934
|
});
|
|
2935
|
+
if (this.metadataCacheInstance && uploaded.id) {
|
|
2936
|
+
this.metadataCacheInstance.upsertFile({
|
|
2937
|
+
id: uploaded.id,
|
|
2938
|
+
name: uploaded.name || targetName || "untitled",
|
|
2939
|
+
mimeType: uploaded.mimeType || "",
|
|
2940
|
+
size: uploaded.size ? parseInt(uploaded.size, 10) : void 0,
|
|
2941
|
+
parentId,
|
|
2942
|
+
trashed: false
|
|
2943
|
+
});
|
|
2944
|
+
}
|
|
2040
2945
|
return await this.pluginManager.runAfterUpload(uploaded);
|
|
2041
2946
|
}
|
|
2042
2947
|
/**
|
|
@@ -2277,16 +3182,16 @@ var init_client = __esm({
|
|
|
2277
3182
|
durationMs: 0
|
|
2278
3183
|
};
|
|
2279
3184
|
const collectFiles = async (dir, base) => {
|
|
2280
|
-
const entries = await
|
|
3185
|
+
const entries = await import_node_fs6.default.promises.readdir(dir, { withFileTypes: true });
|
|
2281
3186
|
const files = [];
|
|
2282
3187
|
for (const entry of entries) {
|
|
2283
|
-
const fullPath =
|
|
2284
|
-
const relPath =
|
|
3188
|
+
const fullPath = import_node_path7.default.join(dir, entry.name);
|
|
3189
|
+
const relPath = import_node_path7.default.join(base, entry.name);
|
|
2285
3190
|
if (entry.isDirectory()) {
|
|
2286
3191
|
const sub = await collectFiles(fullPath, relPath);
|
|
2287
3192
|
files.push(...sub);
|
|
2288
3193
|
} else if (entry.isFile()) {
|
|
2289
|
-
const stat = await
|
|
3194
|
+
const stat = await import_node_fs6.default.promises.stat(fullPath);
|
|
2290
3195
|
files.push({ fullPath, relPath, size: stat.size });
|
|
2291
3196
|
}
|
|
2292
3197
|
}
|
|
@@ -2299,11 +3204,11 @@ var init_client = __esm({
|
|
|
2299
3204
|
if (remoteDirCache.has(relDir)) {
|
|
2300
3205
|
return remoteDirCache.get(relDir);
|
|
2301
3206
|
}
|
|
2302
|
-
const parts = relDir.split(
|
|
3207
|
+
const parts = relDir.split(import_node_path7.default.sep).filter(Boolean);
|
|
2303
3208
|
let currentParent = targetFolderId;
|
|
2304
3209
|
let currentRel = "";
|
|
2305
3210
|
for (const part of parts) {
|
|
2306
|
-
currentRel = currentRel ?
|
|
3211
|
+
currentRel = currentRel ? import_node_path7.default.join(currentRel, part) : part;
|
|
2307
3212
|
if (remoteDirCache.has(currentRel)) {
|
|
2308
3213
|
currentParent = remoteDirCache.get(currentRel);
|
|
2309
3214
|
continue;
|
|
@@ -2332,8 +3237,8 @@ var init_client = __esm({
|
|
|
2332
3237
|
};
|
|
2333
3238
|
await pool.map(allFiles, async (fileItem) => {
|
|
2334
3239
|
try {
|
|
2335
|
-
const relDir =
|
|
2336
|
-
const fileName =
|
|
3240
|
+
const relDir = import_node_path7.default.dirname(fileItem.relPath);
|
|
3241
|
+
const fileName = import_node_path7.default.basename(fileItem.relPath);
|
|
2337
3242
|
const parentFolderId = await ensureRemoteSubdir(relDir === "." ? "" : relDir);
|
|
2338
3243
|
if (options.onFileStart) {
|
|
2339
3244
|
options.onFileStart(fileItem.fullPath, fileItem.relPath);
|
|
@@ -2451,6 +3356,256 @@ var init_client = __esm({
|
|
|
2451
3356
|
const engine = new SmartSyncEngine(this.driveClient);
|
|
2452
3357
|
return await engine.pullFolder(folderId, localDestinationDir, options);
|
|
2453
3358
|
}
|
|
3359
|
+
// ==========================================
|
|
3360
|
+
// STREAMS & RANGE REQUESTS
|
|
3361
|
+
// ==========================================
|
|
3362
|
+
/**
|
|
3363
|
+
* Creates a readable stream for a file, supporting partial range requests
|
|
3364
|
+
*/
|
|
3365
|
+
async createReadStream(pathOrId, options) {
|
|
3366
|
+
const fileId = await this.resolveId(pathOrId);
|
|
3367
|
+
const downloader = await this.getDownloader();
|
|
3368
|
+
return await downloader.createReadStream(fileId, options);
|
|
3369
|
+
}
|
|
3370
|
+
/**
|
|
3371
|
+
* Creates a writable stream directly into Google Drive
|
|
3372
|
+
*/
|
|
3373
|
+
async createWriteStream(remotePath, options = {}) {
|
|
3374
|
+
await this.init();
|
|
3375
|
+
const { PassThrough } = await import("stream");
|
|
3376
|
+
const passThrough = new PassThrough();
|
|
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);
|
|
3386
|
+
const targetParentId = remoteDir === "." || remoteDir === "/" ? this.rootFolderId : await this.mkdirp(remoteDir);
|
|
3387
|
+
const mimeType = options.mimeType || "application/octet-stream";
|
|
3388
|
+
const raw = this.driveClient;
|
|
3389
|
+
raw.files.create({
|
|
3390
|
+
requestBody: {
|
|
3391
|
+
name: fileName,
|
|
3392
|
+
parents: [targetParentId],
|
|
3393
|
+
description: options.description
|
|
3394
|
+
},
|
|
3395
|
+
media: {
|
|
3396
|
+
mimeType,
|
|
3397
|
+
body: passThrough
|
|
3398
|
+
},
|
|
3399
|
+
fields: "id, name, mimeType, size, md5Checksum",
|
|
3400
|
+
supportsAllDrives: true
|
|
3401
|
+
}).then((res) => {
|
|
3402
|
+
const file = res.data;
|
|
3403
|
+
if (file.id && this.metadataCacheInstance) {
|
|
3404
|
+
this.metadataCacheInstance.upsertFile({
|
|
3405
|
+
id: file.id,
|
|
3406
|
+
name: fileName,
|
|
3407
|
+
mimeType,
|
|
3408
|
+
parentId: targetParentId,
|
|
3409
|
+
path: remotePath,
|
|
3410
|
+
trashed: false
|
|
3411
|
+
});
|
|
3412
|
+
}
|
|
3413
|
+
resolveDone(file);
|
|
3414
|
+
}).catch((err) => {
|
|
3415
|
+
passThrough.destroy(err);
|
|
3416
|
+
rejectDone(err);
|
|
3417
|
+
});
|
|
3418
|
+
return passThrough;
|
|
3419
|
+
}
|
|
3420
|
+
// ==========================================
|
|
3421
|
+
// METADATA CACHE OPERATIONS
|
|
3422
|
+
// ==========================================
|
|
3423
|
+
/**
|
|
3424
|
+
* Returns the active persistent metadata cache instance (SQLite/Memory)
|
|
3425
|
+
*/
|
|
3426
|
+
async getMetadataCache() {
|
|
3427
|
+
await this.init();
|
|
3428
|
+
return this.metadataCacheInstance;
|
|
3429
|
+
}
|
|
3430
|
+
/**
|
|
3431
|
+
* Returns cache statistics (total files, folders, size, last sync)
|
|
3432
|
+
*/
|
|
3433
|
+
async getCacheStats() {
|
|
3434
|
+
await this.init();
|
|
3435
|
+
return this.metadataCacheInstance ? this.metadataCacheInstance.getStats() : null;
|
|
3436
|
+
}
|
|
3437
|
+
/**
|
|
3438
|
+
* Clears the path and metadata cache
|
|
3439
|
+
*/
|
|
3440
|
+
async clearCache() {
|
|
3441
|
+
await this.init();
|
|
3442
|
+
if (this.pathResolverInstance) {
|
|
3443
|
+
this.pathResolverInstance.clearCache();
|
|
3444
|
+
}
|
|
3445
|
+
}
|
|
3446
|
+
/**
|
|
3447
|
+
* Crawls and indexes Google Drive metadata into the local SQLite database for instant 0ms lookups
|
|
3448
|
+
*/
|
|
3449
|
+
async syncCache(options) {
|
|
3450
|
+
await this.init();
|
|
3451
|
+
if (!this.metadataCacheInstance) {
|
|
3452
|
+
throw new Error("Persistent cache is disabled on this DriveKit instance");
|
|
3453
|
+
}
|
|
3454
|
+
const client = this.driveClient;
|
|
3455
|
+
let pageToken = void 0;
|
|
3456
|
+
let totalScanned = 0;
|
|
3457
|
+
const rawFiles = [];
|
|
3458
|
+
do {
|
|
3459
|
+
const res = await withRetry(async () => {
|
|
3460
|
+
return await client.files.list({
|
|
3461
|
+
pageSize: 1e3,
|
|
3462
|
+
pageToken,
|
|
3463
|
+
fields: "nextPageToken, files(id, name, mimeType, size, parents, md5Checksum, trashed, modifiedTime)",
|
|
3464
|
+
spaces: "drive",
|
|
3465
|
+
supportsAllDrives: true,
|
|
3466
|
+
includeItemsFromAllDrives: true,
|
|
3467
|
+
q: "trashed = false"
|
|
3468
|
+
});
|
|
3469
|
+
});
|
|
3470
|
+
const files = res.data.files || [];
|
|
3471
|
+
for (const f of files) {
|
|
3472
|
+
if (f.id) rawFiles.push(f);
|
|
3473
|
+
}
|
|
3474
|
+
totalScanned += files.length;
|
|
3475
|
+
options?.onProgress?.(totalScanned);
|
|
3476
|
+
pageToken = res.data.nextPageToken || void 0;
|
|
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));
|
|
3514
|
+
this.metadataCacheInstance.setMeta("last_sync_timestamp", (/* @__PURE__ */ new Date()).toISOString());
|
|
3515
|
+
return this.metadataCacheInstance.getStats();
|
|
3516
|
+
}
|
|
3517
|
+
// ==========================================
|
|
3518
|
+
// SHARED DRIVES & ENTERPRISE PERMISSIONS
|
|
3519
|
+
// ==========================================
|
|
3520
|
+
/**
|
|
3521
|
+
* Lists all Google Workspace Shared Drives accessible by current user or service account
|
|
3522
|
+
*/
|
|
3523
|
+
async listSharedDrives(options = {}) {
|
|
3524
|
+
await this.init();
|
|
3525
|
+
const raw = await this.getRawClient();
|
|
3526
|
+
const res = await withRetry(async () => {
|
|
3527
|
+
return await raw.drives.list({
|
|
3528
|
+
pageSize: options.pageSize || 100,
|
|
3529
|
+
fields: "drives(id, name)"
|
|
3530
|
+
});
|
|
3531
|
+
});
|
|
3532
|
+
return (res.data.drives || []).map((d) => ({ id: d.id, name: d.name }));
|
|
3533
|
+
}
|
|
3534
|
+
/**
|
|
3535
|
+
* Creates a scoped DriveKit client locked to a specific Shared Drive
|
|
3536
|
+
*/
|
|
3537
|
+
sharedDrive(driveId) {
|
|
3538
|
+
return new _DriveKit({
|
|
3539
|
+
...this.options,
|
|
3540
|
+
rootFolderId: driveId
|
|
3541
|
+
});
|
|
3542
|
+
}
|
|
3543
|
+
/**
|
|
3544
|
+
* Grants access to a specific email with custom role and notification
|
|
3545
|
+
*/
|
|
3546
|
+
async grantAccess(pathOrId, options) {
|
|
3547
|
+
const fileId = await this.resolveId(pathOrId);
|
|
3548
|
+
const raw = await this.getRawClient();
|
|
3549
|
+
const res = await withRetry(async () => {
|
|
3550
|
+
return await raw.permissions.create({
|
|
3551
|
+
fileId,
|
|
3552
|
+
requestBody: {
|
|
3553
|
+
type: "user",
|
|
3554
|
+
role: options.role || "reader",
|
|
3555
|
+
emailAddress: options.email
|
|
3556
|
+
},
|
|
3557
|
+
sendNotificationEmail: options.notify ?? true,
|
|
3558
|
+
emailMessage: options.message,
|
|
3559
|
+
fields: "id, type, role, emailAddress, displayName",
|
|
3560
|
+
supportsAllDrives: true
|
|
3561
|
+
});
|
|
3562
|
+
});
|
|
3563
|
+
return res.data;
|
|
3564
|
+
}
|
|
3565
|
+
/**
|
|
3566
|
+
* Revokes access for a specific permission ID or email address
|
|
3567
|
+
*/
|
|
3568
|
+
async revokeAccess(pathOrId, permissionIdOrEmail) {
|
|
3569
|
+
const fileId = await this.resolveId(pathOrId);
|
|
3570
|
+
const raw = await this.getRawClient();
|
|
3571
|
+
let targetId = permissionIdOrEmail;
|
|
3572
|
+
if (permissionIdOrEmail.includes("@")) {
|
|
3573
|
+
const listRes = await this.listPermissions(fileId);
|
|
3574
|
+
const found = listRes.find((p) => p.emailAddress?.toLowerCase() === permissionIdOrEmail.toLowerCase());
|
|
3575
|
+
if (found && found.id) {
|
|
3576
|
+
targetId = found.id;
|
|
3577
|
+
}
|
|
3578
|
+
}
|
|
3579
|
+
await withRetry(async () => {
|
|
3580
|
+
return await raw.permissions.delete({
|
|
3581
|
+
fileId,
|
|
3582
|
+
permissionId: targetId,
|
|
3583
|
+
supportsAllDrives: true
|
|
3584
|
+
});
|
|
3585
|
+
});
|
|
3586
|
+
}
|
|
3587
|
+
/**
|
|
3588
|
+
* Lists all active permissions on a file or folder
|
|
3589
|
+
*/
|
|
3590
|
+
async listPermissions(pathOrId) {
|
|
3591
|
+
const fileId = await this.resolveId(pathOrId);
|
|
3592
|
+
const raw = await this.getRawClient();
|
|
3593
|
+
const res = await withRetry(async () => {
|
|
3594
|
+
return await raw.permissions.list({
|
|
3595
|
+
fileId,
|
|
3596
|
+
fields: "permissions(id, type, role, emailAddress, displayName)",
|
|
3597
|
+
supportsAllDrives: true
|
|
3598
|
+
});
|
|
3599
|
+
});
|
|
3600
|
+
return res.data.permissions || [];
|
|
3601
|
+
}
|
|
3602
|
+
/**
|
|
3603
|
+
* Starts an embedded WebDAV server to mount DriveKit directly in macOS Finder or Windows Explorer
|
|
3604
|
+
*/
|
|
3605
|
+
async serveWebDAV(options) {
|
|
3606
|
+
const { startWebDAVServer: startWebDAVServer2 } = await Promise.resolve().then(() => (init_webdav(), webdav_exports));
|
|
3607
|
+
return await startWebDAVServer2(this, options);
|
|
3608
|
+
}
|
|
2454
3609
|
/**
|
|
2455
3610
|
* Calculates local file MD5 hash for integrity and deduplication checks
|
|
2456
3611
|
*/
|
|
@@ -2474,8 +3629,8 @@ __export(cli_exports, {
|
|
|
2474
3629
|
});
|
|
2475
3630
|
module.exports = __toCommonJS(cli_exports);
|
|
2476
3631
|
init_cjs_shims();
|
|
2477
|
-
var
|
|
2478
|
-
var
|
|
3632
|
+
var import_node_fs7 = __toESM(require("fs"), 1);
|
|
3633
|
+
var import_node_path8 = __toESM(require("path"), 1);
|
|
2479
3634
|
var import_commander = require("commander");
|
|
2480
3635
|
var import_chalk2 = __toESM(require("chalk"), 1);
|
|
2481
3636
|
var import_ora = __toESM(require("ora"), 1);
|
|
@@ -2487,8 +3642,8 @@ init_cjs_shims();
|
|
|
2487
3642
|
var import_node_readline = __toESM(require("readline"), 1);
|
|
2488
3643
|
var import_chalk = __toESM(require("chalk"), 1);
|
|
2489
3644
|
init_format();
|
|
2490
|
-
function terminalLink(text,
|
|
2491
|
-
return `\x1B]8;;${
|
|
3645
|
+
function terminalLink(text, url2) {
|
|
3646
|
+
return `\x1B]8;;${url2}\x07${text}\x1B]8;;\x07`;
|
|
2492
3647
|
}
|
|
2493
3648
|
function renderFileRow(item, index) {
|
|
2494
3649
|
const isDir = item.mimeType === "application/vnd.google-apps.folder";
|
|
@@ -2638,7 +3793,14 @@ ${import_chalk.default.cyan("\u{1F517} Getting shareable link for:")} ${import_c
|
|
|
2638
3793
|
|
|
2639
3794
|
// src/cli.ts
|
|
2640
3795
|
var program = new import_commander.Command();
|
|
2641
|
-
|
|
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");
|
|
2642
3804
|
function getAuthConfig(cmdOptions) {
|
|
2643
3805
|
const keyFilePath = cmdOptions.key || process.env.GOOGLE_APPLICATION_CREDENTIALS || process.env.GDRIVE_SERVICE_ACCOUNT_PATH;
|
|
2644
3806
|
const accessToken = cmdOptions.token || process.env.GDRIVE_ACCESS_TOKEN;
|
|
@@ -2710,12 +3872,12 @@ program.command("explore [folder]").description("Interactive terminal keyboard f
|
|
|
2710
3872
|
process.exit(1);
|
|
2711
3873
|
}
|
|
2712
3874
|
});
|
|
2713
|
-
program.command("upload <localFile> [remotePath]").description("Upload a file with high speed and live progress tracking").option("-o, --overwrite", "Overwrite remote file if it exists").action(async (localFile, remotePath = "/", options) => {
|
|
2714
|
-
if (!
|
|
3875
|
+
program.command("upload <localFile> [remotePath]").description("Upload a file with high speed and live progress tracking").option("-o, --overwrite", "Overwrite remote file if it exists").option("-d, --dedup", "Enable instant cloud deduplication via MD5 hash check").action(async (localFile, remotePath = "/", options) => {
|
|
3876
|
+
if (!import_node_fs7.default.existsSync(localFile)) {
|
|
2715
3877
|
console.error(import_chalk2.default.red(`\u274C Local file not found: ${localFile}`));
|
|
2716
3878
|
process.exit(1);
|
|
2717
3879
|
}
|
|
2718
|
-
const fileName =
|
|
3880
|
+
const fileName = import_node_path8.default.basename(localFile);
|
|
2719
3881
|
const spinner = (0, import_ora.default)(`Preparing upload: ${fileName}...`).start();
|
|
2720
3882
|
try {
|
|
2721
3883
|
const client = await getClient(options);
|
|
@@ -2726,6 +3888,7 @@ program.command("upload <localFile> [remotePath]").description("Upload a file wi
|
|
|
2726
3888
|
name: fileName,
|
|
2727
3889
|
parent: remotePath,
|
|
2728
3890
|
overwrite: options.overwrite,
|
|
3891
|
+
deduplicate: options.dedup,
|
|
2729
3892
|
onProgress: (p) => {
|
|
2730
3893
|
process.stdout.write(
|
|
2731
3894
|
`\r\u{1F680} Uploading: ${import_chalk2.default.cyan(p.percentage + "%")} | Speed: ${import_chalk2.default.green(p.speedFormatted)} | ETA: ${import_chalk2.default.yellow(p.estimatedTimeRemainingSeconds + "s")} [${formatBytes(p.bytesSent)} / ${formatBytes(p.totalBytes)}]`
|
|
@@ -2810,7 +3973,7 @@ program.command("delete <fileIdOrPath>").description("Move a file/folder to tras
|
|
|
2810
3973
|
}
|
|
2811
3974
|
});
|
|
2812
3975
|
program.command("sync <localDir> <remoteFolder>").description("Sync a local directory to Google Drive recursively with high concurrency").option("-c, --concurrency <number>", "Number of parallel uploads", "4").option("-o, --overwrite", "Overwrite files if they already exist").action(async (localDir, remoteFolder, options) => {
|
|
2813
|
-
if (!
|
|
3976
|
+
if (!import_node_fs7.default.existsSync(localDir)) {
|
|
2814
3977
|
console.error(import_chalk2.default.red(`\u274C Local directory not found: ${localDir}`));
|
|
2815
3978
|
process.exit(1);
|
|
2816
3979
|
}
|
|
@@ -2978,8 +4141,8 @@ program.command("login").description("Interactive 1-click browser OAuth2 sign-in
|
|
|
2978
4141
|
if (result.tokens.refresh_token) {
|
|
2979
4142
|
console.log(`Refresh Token: ${import_chalk2.default.green(result.tokens.refresh_token?.slice(0, 25) + "...")}`);
|
|
2980
4143
|
}
|
|
2981
|
-
const outPath =
|
|
2982
|
-
|
|
4144
|
+
const outPath = import_node_path8.default.resolve("./gdrive-tokens.json");
|
|
4145
|
+
import_node_fs7.default.writeFileSync(outPath, JSON.stringify(result.tokens, null, 2), "utf8");
|
|
2983
4146
|
console.log(`\u{1F4BE} Saved tokens to: ${import_chalk2.default.bold(outPath)}
|
|
2984
4147
|
`);
|
|
2985
4148
|
} catch (err) {
|
|
@@ -2987,6 +4150,110 @@ program.command("login").description("Interactive 1-click browser OAuth2 sign-in
|
|
|
2987
4150
|
process.exit(1);
|
|
2988
4151
|
}
|
|
2989
4152
|
});
|
|
4153
|
+
var cacheCmd = program.command("cache").description("Manage local persistent SQLite metadata cache");
|
|
4154
|
+
cacheCmd.command("status").description("Display SQLite cache statistics and database path").action(async (options) => {
|
|
4155
|
+
try {
|
|
4156
|
+
const client = await getClient(options);
|
|
4157
|
+
const stats = await client.getCacheStats();
|
|
4158
|
+
if (!stats) {
|
|
4159
|
+
console.log(import_chalk2.default.yellow("\u26A0\uFE0F Persistent cache is disabled or not available."));
|
|
4160
|
+
return;
|
|
4161
|
+
}
|
|
4162
|
+
console.log(import_chalk2.default.bold.cyan("\n\u26A1 DriveKit Persistent SQLite Cache Status:"));
|
|
4163
|
+
console.log(`\u{1F4C1} Database Path: ${import_chalk2.default.dim(stats.databasePath)}`);
|
|
4164
|
+
console.log(`\u{1F4C2} Cached Folders: ${import_chalk2.default.bold.green(stats.folderCount.toLocaleString())}`);
|
|
4165
|
+
console.log(`\u{1F4C4} Cached Files: ${import_chalk2.default.bold.cyan(stats.fileCount.toLocaleString())}`);
|
|
4166
|
+
console.log(`\u{1F4BE} Indexed Size: ${import_chalk2.default.bold.white(formatBytes(stats.totalSizeBytes))}`);
|
|
4167
|
+
console.log(`\u{1F552} Last Full Sync: ${import_chalk2.default.dim(stats.lastSyncTime || "Never")}
|
|
4168
|
+
`);
|
|
4169
|
+
} catch (err) {
|
|
4170
|
+
console.error(import_chalk2.default.red(`Cache status failed: ${err.message}`));
|
|
4171
|
+
process.exit(1);
|
|
4172
|
+
}
|
|
4173
|
+
});
|
|
4174
|
+
cacheCmd.command("sync").description("Crawl Google Drive and index all file metadata into local SQLite for 0ms lookups").action(async (options) => {
|
|
4175
|
+
const spinner = (0, import_ora.default)("Indexing Google Drive metadata into SQLite...").start();
|
|
4176
|
+
try {
|
|
4177
|
+
const client = await getClient(options);
|
|
4178
|
+
const stats = await client.syncCache({
|
|
4179
|
+
onProgress: (scanned) => {
|
|
4180
|
+
spinner.text = `Indexing Google Drive metadata... (${import_chalk2.default.cyan(scanned.toLocaleString())} items scanned)`;
|
|
4181
|
+
}
|
|
4182
|
+
});
|
|
4183
|
+
spinner.succeed(import_chalk2.default.green(`Indexed ${stats.fileCount + stats.folderCount} items successfully!`));
|
|
4184
|
+
console.log(`\u{1F4BE} Database: ${import_chalk2.default.dim(stats.databasePath)}
|
|
4185
|
+
`);
|
|
4186
|
+
} catch (err) {
|
|
4187
|
+
spinner.fail(import_chalk2.default.red(`Cache sync failed: ${err.message}`));
|
|
4188
|
+
process.exit(1);
|
|
4189
|
+
}
|
|
4190
|
+
});
|
|
4191
|
+
cacheCmd.command("clear").description("Clear all cached metadata from local SQLite database").action(async (options) => {
|
|
4192
|
+
try {
|
|
4193
|
+
const client = await getClient(options);
|
|
4194
|
+
await client.clearCache();
|
|
4195
|
+
console.log(import_chalk2.default.green("\u{1F9F9} Local SQLite cache cleared successfully."));
|
|
4196
|
+
} catch (err) {
|
|
4197
|
+
console.error(import_chalk2.default.red(`Cache clear failed: ${err.message}`));
|
|
4198
|
+
process.exit(1);
|
|
4199
|
+
}
|
|
4200
|
+
});
|
|
4201
|
+
program.command("shared-drives").description("List accessible Google Workspace Shared Drives").action(async (options) => {
|
|
4202
|
+
const spinner = (0, import_ora.default)("Fetching Shared Drives...").start();
|
|
4203
|
+
try {
|
|
4204
|
+
const client = await getClient(options);
|
|
4205
|
+
const drives = await client.listSharedDrives();
|
|
4206
|
+
spinner.stop();
|
|
4207
|
+
if (drives.length === 0) {
|
|
4208
|
+
console.log(import_chalk2.default.yellow("\nNo Shared Drives found or accessible for this account.\n"));
|
|
4209
|
+
return;
|
|
4210
|
+
}
|
|
4211
|
+
console.log(import_chalk2.default.bold.cyan(`
|
|
4212
|
+
\u{1F3E2} Google Workspace Shared Drives (${drives.length}):`));
|
|
4213
|
+
for (const d of drives) {
|
|
4214
|
+
console.log(` \u{1F4C1} ${import_chalk2.default.bold.blue(d.name.padEnd(35))} ${import_chalk2.default.dim(`(ID: ${d.id})`)}`);
|
|
4215
|
+
}
|
|
4216
|
+
console.log("");
|
|
4217
|
+
} catch (err) {
|
|
4218
|
+
spinner.fail(import_chalk2.default.red(`Failed to list shared drives: ${err.message}`));
|
|
4219
|
+
process.exit(1);
|
|
4220
|
+
}
|
|
4221
|
+
});
|
|
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) => {
|
|
4223
|
+
try {
|
|
4224
|
+
const client = await getClient(options);
|
|
4225
|
+
const port = parseInt(options.port, 10) || 8080;
|
|
4226
|
+
const host = options.host || "127.0.0.1";
|
|
4227
|
+
const auth = options.username ? { username: options.username, password: options.password || "" } : void 0;
|
|
4228
|
+
console.log(import_chalk2.default.bold.cyan("\n\u26A1 DriveKit WebDAV Server"));
|
|
4229
|
+
console.log("Starting local WebDAV bridge to Google Drive...\n");
|
|
4230
|
+
const serverInstance = await client.serveWebDAV({ port, host, auth });
|
|
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
|
+
}
|
|
4237
|
+
console.log(import_chalk2.default.white("\n\u{1F4CC} How to mount on macOS Finder:"));
|
|
4238
|
+
console.log(` 1. Open Finder and press ${import_chalk2.default.bold.cyan("Cmd + K")} (Connect to Server)`);
|
|
4239
|
+
console.log(` 2. Enter: ${import_chalk2.default.bold.yellow(serverInstance.url)}`);
|
|
4240
|
+
console.log(` 3. Click ${import_chalk2.default.bold("Connect")}${auth ? ` and log in as ${auth.username}` : " (Connect as Guest)"}
|
|
4241
|
+
`);
|
|
4242
|
+
console.log(import_chalk2.default.white("\u{1F4CC} How to mount on Windows:"));
|
|
4243
|
+
console.log(` 1. Open File Explorer -> This PC -> "Map network drive"`);
|
|
4244
|
+
console.log(` 2. Enter: ${import_chalk2.default.bold.yellow(serverInstance.url)}
|
|
4245
|
+
`);
|
|
4246
|
+
console.log(import_chalk2.default.dim("Press Ctrl+C to stop the WebDAV server.\n"));
|
|
4247
|
+
process.on("SIGINT", async () => {
|
|
4248
|
+
await serverInstance.close();
|
|
4249
|
+
console.log(import_chalk2.default.yellow("\nWebDAV server stopped. Goodbye!"));
|
|
4250
|
+
process.exit(0);
|
|
4251
|
+
});
|
|
4252
|
+
} catch (err) {
|
|
4253
|
+
console.error(import_chalk2.default.red(`Failed to start WebDAV server: ${err.message}`));
|
|
4254
|
+
process.exit(1);
|
|
4255
|
+
}
|
|
4256
|
+
});
|
|
2990
4257
|
function runCLI() {
|
|
2991
4258
|
program.parse(process.argv);
|
|
2992
4259
|
}
|