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/index.js
CHANGED
|
@@ -1,13 +1,366 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
3
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
4
|
+
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
5
|
+
}) : x)(function(x) {
|
|
6
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
7
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
8
|
+
});
|
|
9
|
+
var __esm = (fn, res) => function __init() {
|
|
10
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
11
|
+
};
|
|
12
|
+
var __export = (target, all) => {
|
|
13
|
+
for (var name in all)
|
|
14
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
// node_modules/tsup/assets/esm_shims.js
|
|
18
|
+
import path from "path";
|
|
19
|
+
import { fileURLToPath } from "url";
|
|
20
|
+
var init_esm_shims = __esm({
|
|
21
|
+
"node_modules/tsup/assets/esm_shims.js"() {
|
|
22
|
+
"use strict";
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
// src/server/webdav.ts
|
|
27
|
+
var webdav_exports = {};
|
|
28
|
+
__export(webdav_exports, {
|
|
29
|
+
escapeXml: () => escapeXml,
|
|
30
|
+
startWebDAVServer: () => startWebDAVServer
|
|
31
|
+
});
|
|
32
|
+
import http2 from "http";
|
|
33
|
+
import url from "url";
|
|
34
|
+
import path7 from "path";
|
|
35
|
+
function escapeXml(unsafe) {
|
|
36
|
+
return unsafe.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
37
|
+
}
|
|
38
|
+
async function startWebDAVServer(drive2, options = {}) {
|
|
39
|
+
const port = options.port || 8080;
|
|
40
|
+
const host = options.host || "127.0.0.1";
|
|
41
|
+
await drive2.init();
|
|
42
|
+
const server = http2.createServer(async (req, res) => {
|
|
43
|
+
try {
|
|
44
|
+
if (options.auth?.username && options.auth?.password) {
|
|
45
|
+
const authHeader = req.headers["authorization"];
|
|
46
|
+
if (!authHeader || !authHeader.startsWith("Basic ")) {
|
|
47
|
+
res.writeHead(401, {
|
|
48
|
+
"WWW-Authenticate": 'Basic realm="DriveKit WebDAV"',
|
|
49
|
+
"Content-Type": "text/plain"
|
|
50
|
+
});
|
|
51
|
+
res.end("Authentication required");
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
const credentials = Buffer.from(authHeader.replace("Basic ", ""), "base64").toString("utf8");
|
|
55
|
+
const [user, pass] = credentials.split(":");
|
|
56
|
+
if (user !== options.auth.username || pass !== options.auth.password) {
|
|
57
|
+
res.writeHead(401, {
|
|
58
|
+
"WWW-Authenticate": 'Basic realm="DriveKit WebDAV"',
|
|
59
|
+
"Content-Type": "text/plain"
|
|
60
|
+
});
|
|
61
|
+
res.end("Invalid credentials");
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
const parsedUrl = url.parse(req.url || "/", true);
|
|
66
|
+
const decodedPath = decodeURIComponent(parsedUrl.pathname || "/");
|
|
67
|
+
const virtualPath = decodedPath === "" ? "/" : decodedPath;
|
|
68
|
+
switch (req.method) {
|
|
69
|
+
case "OPTIONS": {
|
|
70
|
+
res.writeHead(200, {
|
|
71
|
+
DAV: "1, 2",
|
|
72
|
+
Allow: "OPTIONS, GET, HEAD, POST, PUT, DELETE, MKCOL, MOVE, COPY, PROPFIND",
|
|
73
|
+
"MS-Author-Via": "DAV",
|
|
74
|
+
"Accept-Ranges": "bytes"
|
|
75
|
+
});
|
|
76
|
+
res.end();
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
case "PROPFIND": {
|
|
80
|
+
const depth = req.headers["depth"] || "1";
|
|
81
|
+
const xml = await handlePropfind(drive2, virtualPath, depth);
|
|
82
|
+
res.writeHead(207, {
|
|
83
|
+
"Content-Type": "application/xml; charset=utf-8"
|
|
84
|
+
});
|
|
85
|
+
res.end(xml);
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
case "GET":
|
|
89
|
+
case "HEAD": {
|
|
90
|
+
if (virtualPath === "/" || virtualPath === "") {
|
|
91
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
|
92
|
+
res.end("<h1>DriveKit WebDAV Server Running</h1><p>Connect via Finder, File Explorer, or WebDAV client.</p>");
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
try {
|
|
96
|
+
const file = await drive2.getFile(virtualPath);
|
|
97
|
+
if (file.mimeType === "application/vnd.google-apps.folder") {
|
|
98
|
+
res.writeHead(405, { "Content-Type": "text/plain" });
|
|
99
|
+
res.end("Cannot GET a directory");
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
const fileSize = file.size ? parseInt(file.size, 10) : void 0;
|
|
103
|
+
const rangeHeader = req.headers["range"];
|
|
104
|
+
if (rangeHeader && rangeHeader.startsWith("bytes=") && fileSize !== void 0) {
|
|
105
|
+
const parts = rangeHeader.replace("bytes=", "").split("-");
|
|
106
|
+
const start = parseInt(parts[0], 10);
|
|
107
|
+
const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
|
|
108
|
+
if (isNaN(start) || start >= fileSize || end !== void 0 && end >= fileSize) {
|
|
109
|
+
res.writeHead(416, { "Content-Range": `bytes */${fileSize}` });
|
|
110
|
+
res.end();
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
const stream = await drive2.createReadStream(virtualPath, { start, end });
|
|
114
|
+
const chunkLength = end - start + 1;
|
|
115
|
+
res.writeHead(206, {
|
|
116
|
+
"Content-Type": file.mimeType || "application/octet-stream",
|
|
117
|
+
"Content-Range": `bytes ${start}-${end}/${fileSize}`,
|
|
118
|
+
"Content-Length": chunkLength,
|
|
119
|
+
"Accept-Ranges": "bytes"
|
|
120
|
+
});
|
|
121
|
+
if (req.method === "HEAD") {
|
|
122
|
+
res.end();
|
|
123
|
+
} else {
|
|
124
|
+
stream.pipe(res);
|
|
125
|
+
}
|
|
126
|
+
} else {
|
|
127
|
+
const stream = await drive2.createReadStream(virtualPath);
|
|
128
|
+
res.writeHead(200, {
|
|
129
|
+
"Content-Type": file.mimeType || "application/octet-stream",
|
|
130
|
+
"Content-Length": file.size || void 0,
|
|
131
|
+
"Accept-Ranges": "bytes"
|
|
132
|
+
});
|
|
133
|
+
if (req.method === "HEAD") {
|
|
134
|
+
res.end();
|
|
135
|
+
} else {
|
|
136
|
+
stream.pipe(res);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
} catch (e) {
|
|
140
|
+
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
141
|
+
res.end("File Not Found");
|
|
142
|
+
}
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
case "PUT": {
|
|
146
|
+
const remoteDir = path7.dirname(virtualPath);
|
|
147
|
+
await drive2.mkdirp(remoteDir);
|
|
148
|
+
let existed = false;
|
|
149
|
+
try {
|
|
150
|
+
const existingFile = await drive2.getFile(virtualPath);
|
|
151
|
+
if (existingFile && existingFile.id) {
|
|
152
|
+
existed = true;
|
|
153
|
+
}
|
|
154
|
+
} catch {
|
|
155
|
+
existed = false;
|
|
156
|
+
}
|
|
157
|
+
try {
|
|
158
|
+
const uploadStream = await drive2.createWriteStream(virtualPath, {
|
|
159
|
+
overwrite: true
|
|
160
|
+
});
|
|
161
|
+
req.pipe(uploadStream);
|
|
162
|
+
await uploadStream.done;
|
|
163
|
+
res.writeHead(existed ? 204 : 201, { "Content-Type": "text/plain" });
|
|
164
|
+
res.end(existed ? "" : "Created");
|
|
165
|
+
} catch (err) {
|
|
166
|
+
res.writeHead(500, { "Content-Type": "text/plain" });
|
|
167
|
+
res.end(err.message || "Upload failed");
|
|
168
|
+
}
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
case "MKCOL": {
|
|
172
|
+
try {
|
|
173
|
+
await drive2.mkdirp(virtualPath);
|
|
174
|
+
res.writeHead(201, { "Content-Type": "text/plain" });
|
|
175
|
+
res.end("Collection Created");
|
|
176
|
+
} catch (err) {
|
|
177
|
+
res.writeHead(500, { "Content-Type": "text/plain" });
|
|
178
|
+
res.end(err.message);
|
|
179
|
+
}
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
case "DELETE": {
|
|
183
|
+
try {
|
|
184
|
+
await drive2.delete(virtualPath, true);
|
|
185
|
+
res.writeHead(204);
|
|
186
|
+
res.end();
|
|
187
|
+
} catch (err) {
|
|
188
|
+
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
189
|
+
res.end("Not Found");
|
|
190
|
+
}
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
case "MOVE": {
|
|
194
|
+
const destination = req.headers["destination"];
|
|
195
|
+
if (!destination || typeof destination !== "string") {
|
|
196
|
+
res.writeHead(400, { "Content-Type": "text/plain" });
|
|
197
|
+
res.end("Destination header missing");
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
try {
|
|
201
|
+
const file = await drive2.getFile(virtualPath);
|
|
202
|
+
if (!file?.id) {
|
|
203
|
+
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
204
|
+
res.end("Source file not found");
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
const destUrl = url.parse(destination);
|
|
208
|
+
const destPath = decodeURIComponent(destUrl.pathname || "");
|
|
209
|
+
const newName = path7.basename(destPath);
|
|
210
|
+
const newParentDir = path7.dirname(destPath);
|
|
211
|
+
const newParentFolderId = await drive2.mkdirp(newParentDir);
|
|
212
|
+
const currentParentDir = path7.dirname(virtualPath);
|
|
213
|
+
if (newParentDir !== currentParentDir) {
|
|
214
|
+
await drive2.move(file.id, newParentFolderId);
|
|
215
|
+
}
|
|
216
|
+
if (newName !== path7.basename(virtualPath)) {
|
|
217
|
+
await drive2.rename(file.id, newName);
|
|
218
|
+
}
|
|
219
|
+
res.writeHead(201);
|
|
220
|
+
res.end("Moved");
|
|
221
|
+
} catch (err) {
|
|
222
|
+
res.writeHead(500, { "Content-Type": "text/plain" });
|
|
223
|
+
res.end(err.message);
|
|
224
|
+
}
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
case "COPY": {
|
|
228
|
+
const destination = req.headers["destination"];
|
|
229
|
+
if (!destination || typeof destination !== "string") {
|
|
230
|
+
res.writeHead(400, { "Content-Type": "text/plain" });
|
|
231
|
+
res.end("Destination header missing");
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
try {
|
|
235
|
+
const file = await drive2.getFile(virtualPath);
|
|
236
|
+
if (!file?.id) {
|
|
237
|
+
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
238
|
+
res.end("Source file not found");
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
const destUrl = url.parse(destination);
|
|
242
|
+
const destPath = decodeURIComponent(destUrl.pathname || "");
|
|
243
|
+
const newName = path7.basename(destPath);
|
|
244
|
+
const newParentDir = path7.dirname(destPath);
|
|
245
|
+
const newParentFolderId = await drive2.mkdirp(newParentDir);
|
|
246
|
+
await drive2.copy(file.id, { parent: newParentFolderId, name: newName });
|
|
247
|
+
res.writeHead(201);
|
|
248
|
+
res.end("Copied");
|
|
249
|
+
} catch (err) {
|
|
250
|
+
res.writeHead(500, { "Content-Type": "text/plain" });
|
|
251
|
+
res.end(err.message);
|
|
252
|
+
}
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
default: {
|
|
256
|
+
res.writeHead(501, { "Content-Type": "text/plain" });
|
|
257
|
+
res.end("Method Not Implemented");
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
} catch (globalErr) {
|
|
261
|
+
res.writeHead(500, { "Content-Type": "text/plain" });
|
|
262
|
+
res.end(`Internal Server Error: ${globalErr.message}`);
|
|
263
|
+
}
|
|
264
|
+
});
|
|
265
|
+
return new Promise((resolve) => {
|
|
266
|
+
server.listen(port, host, () => {
|
|
267
|
+
const serverUrl = `http://${host}:${port}`;
|
|
268
|
+
resolve({
|
|
269
|
+
server,
|
|
270
|
+
url: serverUrl,
|
|
271
|
+
close: () => new Promise((resClose) => server.close(() => resClose()))
|
|
272
|
+
});
|
|
273
|
+
});
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
async function handlePropfind(drive2, virtualPath, depth) {
|
|
277
|
+
const responses = [];
|
|
278
|
+
let isFolder = false;
|
|
279
|
+
let selfItem = null;
|
|
280
|
+
if (virtualPath === "/" || virtualPath === "") {
|
|
281
|
+
isFolder = true;
|
|
282
|
+
responses.push(renderWebDAVResponse("/", true, 0, (/* @__PURE__ */ new Date()).toISOString()));
|
|
283
|
+
} else {
|
|
284
|
+
try {
|
|
285
|
+
selfItem = await drive2.getFile(virtualPath);
|
|
286
|
+
isFolder = selfItem.mimeType === "application/vnd.google-apps.folder";
|
|
287
|
+
responses.push(
|
|
288
|
+
renderWebDAVResponse(
|
|
289
|
+
virtualPath,
|
|
290
|
+
isFolder,
|
|
291
|
+
selfItem.size ? parseInt(selfItem.size, 10) : 0,
|
|
292
|
+
selfItem.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
|
|
293
|
+
)
|
|
294
|
+
);
|
|
295
|
+
} catch {
|
|
296
|
+
return `<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:"></D:multistatus>`;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
if (isFolder && depth !== "0") {
|
|
300
|
+
try {
|
|
301
|
+
const children = await drive2.ls(virtualPath);
|
|
302
|
+
for (const child of children) {
|
|
303
|
+
const childIsFolder = child.mimeType === "application/vnd.google-apps.folder";
|
|
304
|
+
const childPath = virtualPath === "/" ? `/${child.name}` : `${virtualPath}/${child.name}`;
|
|
305
|
+
responses.push(
|
|
306
|
+
renderWebDAVResponse(
|
|
307
|
+
childPath,
|
|
308
|
+
childIsFolder,
|
|
309
|
+
child.size ? parseInt(child.size, 10) : 0,
|
|
310
|
+
child.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
|
|
311
|
+
)
|
|
312
|
+
);
|
|
313
|
+
}
|
|
314
|
+
} catch {
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
return `<?xml version="1.0" encoding="utf-8"?>
|
|
318
|
+
<D:multistatus xmlns:D="DAV:">
|
|
319
|
+
${responses.join("\n")}
|
|
320
|
+
</D:multistatus>`;
|
|
321
|
+
}
|
|
322
|
+
function renderWebDAVResponse(href, isDir, size, modifiedTime) {
|
|
323
|
+
const encodedHref = encodeURI(href);
|
|
324
|
+
const displayName = escapeXml(path7.basename(href) || "root");
|
|
325
|
+
const resourceType = isDir ? "<D:collection/>" : "";
|
|
326
|
+
const dateFormatted = new Date(modifiedTime).toUTCString();
|
|
327
|
+
return ` <D:response>
|
|
328
|
+
<D:href>${encodedHref}</D:href>
|
|
329
|
+
<D:propstat>
|
|
330
|
+
<D:prop>
|
|
331
|
+
<D:displayname>${displayName}</D:displayname>
|
|
332
|
+
<D:resourcetype>${resourceType}</D:resourcetype>
|
|
333
|
+
<D:getcontentlength>${isDir ? "0" : size}</D:getcontentlength>
|
|
334
|
+
<D:getlastmodified>${dateFormatted}</D:getlastmodified>
|
|
335
|
+
<D:status>HTTP/1.1 200 OK</D:status>
|
|
336
|
+
</D:prop>
|
|
337
|
+
<D:status>HTTP/1.1 200 OK</D:status>
|
|
338
|
+
</D:propstat>
|
|
339
|
+
</D:response>`;
|
|
340
|
+
}
|
|
341
|
+
var init_webdav = __esm({
|
|
342
|
+
"src/server/webdav.ts"() {
|
|
343
|
+
"use strict";
|
|
344
|
+
init_esm_shims();
|
|
345
|
+
}
|
|
346
|
+
});
|
|
347
|
+
|
|
348
|
+
// src/index.ts
|
|
349
|
+
init_esm_shims();
|
|
350
|
+
|
|
1
351
|
// src/core/client.ts
|
|
2
|
-
|
|
3
|
-
import
|
|
352
|
+
init_esm_shims();
|
|
353
|
+
import fs6 from "fs";
|
|
354
|
+
import path8 from "path";
|
|
4
355
|
import { drive } from "@googleapis/drive";
|
|
5
356
|
|
|
6
357
|
// src/auth/authenticator.ts
|
|
358
|
+
init_esm_shims();
|
|
7
359
|
import fs from "fs";
|
|
8
360
|
import { auth as googleAuth } from "@googleapis/drive";
|
|
9
361
|
|
|
10
362
|
// src/errors.ts
|
|
363
|
+
init_esm_shims();
|
|
11
364
|
var DriveKitError = class extends Error {
|
|
12
365
|
code;
|
|
13
366
|
originalError;
|
|
@@ -148,7 +501,11 @@ var DriveAuthenticator = class {
|
|
|
148
501
|
}
|
|
149
502
|
};
|
|
150
503
|
|
|
504
|
+
// src/core/path-resolver.ts
|
|
505
|
+
init_esm_shims();
|
|
506
|
+
|
|
151
507
|
// src/utils/mime.ts
|
|
508
|
+
init_esm_shims();
|
|
152
509
|
import mime from "mime-types";
|
|
153
510
|
var GOOGLE_WORKSPACE_MIME_TYPES = {
|
|
154
511
|
DOCUMENT: "application/vnd.google-apps.document",
|
|
@@ -192,6 +549,7 @@ function isGoogleWorkspaceDoc(mimeType) {
|
|
|
192
549
|
}
|
|
193
550
|
|
|
194
551
|
// src/utils/retry.ts
|
|
552
|
+
init_esm_shims();
|
|
195
553
|
var DEFAULT_RETRYABLE_STATUSES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
|
|
196
554
|
function isRetryableError(error) {
|
|
197
555
|
if (!error) return false;
|
|
@@ -248,11 +606,13 @@ var PathResolver = class {
|
|
|
248
606
|
cache = /* @__PURE__ */ new Map();
|
|
249
607
|
cacheTTL;
|
|
250
608
|
enableCache;
|
|
609
|
+
metadataCache;
|
|
251
610
|
constructor(drive2, rootFolderId = "root", options) {
|
|
252
611
|
this.drive = drive2;
|
|
253
612
|
this.rootFolderId = rootFolderId;
|
|
254
613
|
this.enableCache = options?.enableCache ?? true;
|
|
255
614
|
this.cacheTTL = options?.cacheTTL ?? 5 * 60 * 1e3;
|
|
615
|
+
this.metadataCache = options?.metadataCache;
|
|
256
616
|
}
|
|
257
617
|
/**
|
|
258
618
|
* Normalizes a virtual path (e.g. "///Backups//2026/" -> "/Backups/2026")
|
|
@@ -267,21 +627,31 @@ var PathResolver = class {
|
|
|
267
627
|
/**
|
|
268
628
|
* Gets cache key for a path
|
|
269
629
|
*/
|
|
270
|
-
getCacheKey(
|
|
271
|
-
return `${this.rootFolderId}:${this.normalizePath(
|
|
630
|
+
getCacheKey(path9) {
|
|
631
|
+
return `${this.rootFolderId}:${this.normalizePath(path9)}`;
|
|
272
632
|
}
|
|
273
633
|
/**
|
|
274
634
|
* Clears the path cache
|
|
275
635
|
*/
|
|
276
636
|
clearCache() {
|
|
277
637
|
this.cache.clear();
|
|
638
|
+
if (this.metadataCache) {
|
|
639
|
+
this.metadataCache.clear();
|
|
640
|
+
}
|
|
278
641
|
}
|
|
279
642
|
/**
|
|
280
643
|
* Invalidate a single path from cache
|
|
281
644
|
*/
|
|
282
|
-
invalidatePath(
|
|
283
|
-
const
|
|
645
|
+
invalidatePath(path9) {
|
|
646
|
+
const norm = this.normalizePath(path9);
|
|
647
|
+
const key = this.getCacheKey(norm);
|
|
284
648
|
this.cache.delete(key);
|
|
649
|
+
if (this.metadataCache) {
|
|
650
|
+
const item = this.metadataCache.getByPath(norm);
|
|
651
|
+
if (item) {
|
|
652
|
+
this.metadataCache.deleteFile(item.id);
|
|
653
|
+
}
|
|
654
|
+
}
|
|
285
655
|
}
|
|
286
656
|
/**
|
|
287
657
|
* Resolves a path to a Google Drive item (file or folder).
|
|
@@ -297,6 +667,17 @@ var PathResolver = class {
|
|
|
297
667
|
mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER
|
|
298
668
|
};
|
|
299
669
|
}
|
|
670
|
+
if (this.metadataCache) {
|
|
671
|
+
const persistentCached = this.metadataCache.getByPath(norm);
|
|
672
|
+
if (persistentCached) {
|
|
673
|
+
return {
|
|
674
|
+
id: persistentCached.id,
|
|
675
|
+
name: persistentCached.name,
|
|
676
|
+
isFolder: persistentCached.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
|
|
677
|
+
mimeType: persistentCached.mimeType
|
|
678
|
+
};
|
|
679
|
+
}
|
|
680
|
+
}
|
|
300
681
|
if (this.enableCache) {
|
|
301
682
|
const cached = this.cache.get(this.getCacheKey(norm));
|
|
302
683
|
if (cached && cached.expiresAt > Date.now()) {
|
|
@@ -315,6 +696,21 @@ var PathResolver = class {
|
|
|
315
696
|
const segment = segments[i];
|
|
316
697
|
const isLast = i === segments.length - 1;
|
|
317
698
|
currentPath += `/${segment}`;
|
|
699
|
+
if (this.metadataCache) {
|
|
700
|
+
const pCached = this.metadataCache.getByPath(currentPath);
|
|
701
|
+
if (pCached) {
|
|
702
|
+
currentParentId = pCached.id;
|
|
703
|
+
if (isLast) {
|
|
704
|
+
return {
|
|
705
|
+
id: pCached.id,
|
|
706
|
+
name: pCached.name,
|
|
707
|
+
isFolder: pCached.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
|
|
708
|
+
mimeType: pCached.mimeType
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
continue;
|
|
712
|
+
}
|
|
713
|
+
}
|
|
318
714
|
if (this.enableCache) {
|
|
319
715
|
const cached = this.cache.get(this.getCacheKey(currentPath));
|
|
320
716
|
if (cached && cached.expiresAt > Date.now()) {
|
|
@@ -358,7 +754,18 @@ var PathResolver = class {
|
|
|
358
754
|
file = sharedResponse.data.files?.[0];
|
|
359
755
|
}
|
|
360
756
|
if (file && file.id) {
|
|
757
|
+
const segmentParentId = currentParentId;
|
|
361
758
|
currentParentId = file.id;
|
|
759
|
+
if (this.metadataCache) {
|
|
760
|
+
this.metadataCache.upsertFile({
|
|
761
|
+
id: file.id,
|
|
762
|
+
name: file.name || segment,
|
|
763
|
+
mimeType: file.mimeType || "",
|
|
764
|
+
parentId: segmentParentId,
|
|
765
|
+
path: currentPath,
|
|
766
|
+
trashed: false
|
|
767
|
+
});
|
|
768
|
+
}
|
|
362
769
|
if (this.enableCache) {
|
|
363
770
|
this.cache.set(this.getCacheKey(currentPath), {
|
|
364
771
|
id: file.id,
|
|
@@ -392,7 +799,18 @@ var PathResolver = class {
|
|
|
392
799
|
if (!newFolder.id) {
|
|
393
800
|
throw new Error(`Failed to create folder "${segment}" under parent "${currentParentId}"`);
|
|
394
801
|
}
|
|
802
|
+
const segmentParentId = currentParentId;
|
|
395
803
|
currentParentId = newFolder.id;
|
|
804
|
+
if (this.metadataCache) {
|
|
805
|
+
this.metadataCache.upsertFile({
|
|
806
|
+
id: newFolder.id,
|
|
807
|
+
name: segment,
|
|
808
|
+
mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
|
|
809
|
+
parentId: segmentParentId,
|
|
810
|
+
path: currentPath,
|
|
811
|
+
trashed: false
|
|
812
|
+
});
|
|
813
|
+
}
|
|
396
814
|
if (this.enableCache) {
|
|
397
815
|
this.cache.set(this.getCacheKey(currentPath), {
|
|
398
816
|
id: newFolder.id,
|
|
@@ -429,10 +847,12 @@ var PathResolver = class {
|
|
|
429
847
|
};
|
|
430
848
|
|
|
431
849
|
// src/core/resumable-uploader.ts
|
|
850
|
+
init_esm_shims();
|
|
432
851
|
import fs2 from "fs";
|
|
433
|
-
import
|
|
852
|
+
import path2 from "path";
|
|
434
853
|
|
|
435
854
|
// src/utils/format.ts
|
|
855
|
+
init_esm_shims();
|
|
436
856
|
function formatBytes(bytes, decimals = 2) {
|
|
437
857
|
if (bytes === 0) return "0 B";
|
|
438
858
|
const k = 1024;
|
|
@@ -492,7 +912,7 @@ var ResumableUploader = class {
|
|
|
492
912
|
}
|
|
493
913
|
const stat = await fs2.promises.stat(filePath);
|
|
494
914
|
const totalBytes = stat.size;
|
|
495
|
-
const fileName = options.name ||
|
|
915
|
+
const fileName = options.name || path2.basename(filePath);
|
|
496
916
|
const mimeType = options.mimeType || lookupMimeType(filePath);
|
|
497
917
|
return await this.chunkedUpload({
|
|
498
918
|
filePath,
|
|
@@ -760,8 +1180,9 @@ var ResumableUploader = class {
|
|
|
760
1180
|
};
|
|
761
1181
|
|
|
762
1182
|
// src/core/downloader.ts
|
|
1183
|
+
init_esm_shims();
|
|
763
1184
|
import fs3 from "fs";
|
|
764
|
-
import
|
|
1185
|
+
import path3 from "path";
|
|
765
1186
|
import { pipeline } from "stream/promises";
|
|
766
1187
|
import { Transform } from "stream";
|
|
767
1188
|
var Downloader = class {
|
|
@@ -836,9 +1257,9 @@ var Downloader = class {
|
|
|
836
1257
|
if (options.destination) {
|
|
837
1258
|
let destPath = options.destination;
|
|
838
1259
|
if (fs3.existsSync(destPath) && fs3.statSync(destPath).isDirectory()) {
|
|
839
|
-
destPath =
|
|
1260
|
+
destPath = path3.join(destPath, finalFileName);
|
|
840
1261
|
}
|
|
841
|
-
await fs3.promises.mkdir(
|
|
1262
|
+
await fs3.promises.mkdir(path3.dirname(destPath), { recursive: true });
|
|
842
1263
|
const writeStream = fs3.createWriteStream(destPath);
|
|
843
1264
|
await pipeline(monitoredStream, writeStream);
|
|
844
1265
|
return {
|
|
@@ -855,9 +1276,28 @@ var Downloader = class {
|
|
|
855
1276
|
size: totalBytes
|
|
856
1277
|
};
|
|
857
1278
|
}
|
|
1279
|
+
/**
|
|
1280
|
+
* Returns a raw ReadableStream for the file, supporting HTTP Range requests for partial content / streaming.
|
|
1281
|
+
*/
|
|
1282
|
+
async createReadStream(fileId, options) {
|
|
1283
|
+
const headers = {};
|
|
1284
|
+
if (options?.start !== void 0 || options?.end !== void 0) {
|
|
1285
|
+
const start = options.start ?? 0;
|
|
1286
|
+
const end = options.end !== void 0 ? options.end : "";
|
|
1287
|
+
headers["Range"] = `bytes=${start}-${end}`;
|
|
1288
|
+
}
|
|
1289
|
+
const res = await withRetry(async () => {
|
|
1290
|
+
return await this.drive.files.get(
|
|
1291
|
+
{ fileId, alt: "media", supportsAllDrives: true },
|
|
1292
|
+
{ responseType: "stream", headers }
|
|
1293
|
+
);
|
|
1294
|
+
});
|
|
1295
|
+
return res.data;
|
|
1296
|
+
}
|
|
858
1297
|
};
|
|
859
1298
|
|
|
860
1299
|
// src/core/query-builder.ts
|
|
1300
|
+
init_esm_shims();
|
|
861
1301
|
var DriveQueryBuilder = class {
|
|
862
1302
|
drive;
|
|
863
1303
|
conditions = [];
|
|
@@ -974,6 +1414,19 @@ var DriveQueryBuilder = class {
|
|
|
974
1414
|
this.conditions.push(`(${condition})`);
|
|
975
1415
|
return this;
|
|
976
1416
|
}
|
|
1417
|
+
/**
|
|
1418
|
+
* Custom raw query condition (alias for raw)
|
|
1419
|
+
*/
|
|
1420
|
+
custom(condition) {
|
|
1421
|
+
return this.raw(condition);
|
|
1422
|
+
}
|
|
1423
|
+
/**
|
|
1424
|
+
* Filter: Exact MD5 checksum match
|
|
1425
|
+
*/
|
|
1426
|
+
md5(checksum) {
|
|
1427
|
+
this.conditions.push(`md5Checksum = '${this.escape(checksum)}'`);
|
|
1428
|
+
return this;
|
|
1429
|
+
}
|
|
977
1430
|
/**
|
|
978
1431
|
* Sort ordering (e.g. 'modifiedTime desc', 'name', 'folder,modifiedTime desc')
|
|
979
1432
|
*/
|
|
@@ -1020,6 +1473,12 @@ var DriveQueryBuilder = class {
|
|
|
1020
1473
|
});
|
|
1021
1474
|
return res.data.files || [];
|
|
1022
1475
|
}
|
|
1476
|
+
/**
|
|
1477
|
+
* Executes query and returns array of matching files (alias for list)
|
|
1478
|
+
*/
|
|
1479
|
+
async execute() {
|
|
1480
|
+
return await this.list();
|
|
1481
|
+
}
|
|
1023
1482
|
/**
|
|
1024
1483
|
* Returns the first matching file, or null if not found
|
|
1025
1484
|
*/
|
|
@@ -1067,6 +1526,7 @@ var DriveQueryBuilder = class {
|
|
|
1067
1526
|
};
|
|
1068
1527
|
|
|
1069
1528
|
// src/core/concurrency-pool.ts
|
|
1529
|
+
init_esm_shims();
|
|
1070
1530
|
var ConcurrencyPool = class {
|
|
1071
1531
|
concurrency;
|
|
1072
1532
|
running = 0;
|
|
@@ -1111,6 +1571,7 @@ var ConcurrencyPool = class {
|
|
|
1111
1571
|
};
|
|
1112
1572
|
|
|
1113
1573
|
// src/core/watcher.ts
|
|
1574
|
+
init_esm_shims();
|
|
1114
1575
|
import { EventEmitter } from "events";
|
|
1115
1576
|
var DriveWatcher = class extends EventEmitter {
|
|
1116
1577
|
drive;
|
|
@@ -1224,6 +1685,7 @@ var DriveWatcher = class extends EventEmitter {
|
|
|
1224
1685
|
};
|
|
1225
1686
|
|
|
1226
1687
|
// src/core/storage-cleaner.ts
|
|
1688
|
+
init_esm_shims();
|
|
1227
1689
|
var StorageCleaner = class {
|
|
1228
1690
|
drive;
|
|
1229
1691
|
constructor(drive2) {
|
|
@@ -1320,8 +1782,9 @@ var StorageCleaner = class {
|
|
|
1320
1782
|
};
|
|
1321
1783
|
|
|
1322
1784
|
// src/core/smart-sync.ts
|
|
1785
|
+
init_esm_shims();
|
|
1323
1786
|
import fs4 from "fs";
|
|
1324
|
-
import
|
|
1787
|
+
import path4 from "path";
|
|
1325
1788
|
import crypto from "crypto";
|
|
1326
1789
|
async function calculateFileMd5(filePath) {
|
|
1327
1790
|
return new Promise((resolve, reject) => {
|
|
@@ -1371,7 +1834,7 @@ var SmartSyncEngine = class {
|
|
|
1371
1834
|
for (const file of files) {
|
|
1372
1835
|
if (!file.id || !file.name) continue;
|
|
1373
1836
|
const isFolder = file.mimeType === "application/vnd.google-apps.folder";
|
|
1374
|
-
const fileRel = relPath ?
|
|
1837
|
+
const fileRel = relPath ? path4.join(relPath, file.name) : file.name;
|
|
1375
1838
|
if (isFolder) {
|
|
1376
1839
|
const sub = await collectRemoteItems(file.id, fileRel);
|
|
1377
1840
|
items.push(...sub);
|
|
@@ -1392,7 +1855,7 @@ var SmartSyncEngine = class {
|
|
|
1392
1855
|
};
|
|
1393
1856
|
const remoteFiles = await collectRemoteItems(remoteFolderId, "");
|
|
1394
1857
|
await pool.map(remoteFiles, async (remoteItem) => {
|
|
1395
|
-
const localFilePath =
|
|
1858
|
+
const localFilePath = path4.join(localDestinationDir, remoteItem.relPath);
|
|
1396
1859
|
if (!options.overwrite && fs4.existsSync(localFilePath)) {
|
|
1397
1860
|
const localStat = await fs4.promises.stat(localFilePath);
|
|
1398
1861
|
if (remoteItem.md5Checksum) {
|
|
@@ -1445,6 +1908,7 @@ var SmartSyncEngine = class {
|
|
|
1445
1908
|
};
|
|
1446
1909
|
|
|
1447
1910
|
// src/auth/browser-login.ts
|
|
1911
|
+
init_esm_shims();
|
|
1448
1912
|
import http from "http";
|
|
1449
1913
|
import { exec } from "child_process";
|
|
1450
1914
|
import { auth as googleAuth2 } from "@googleapis/drive";
|
|
@@ -1553,6 +2017,7 @@ ${authUrl}
|
|
|
1553
2017
|
}
|
|
1554
2018
|
|
|
1555
2019
|
// src/core/resource-refs.ts
|
|
2020
|
+
init_esm_shims();
|
|
1556
2021
|
var DriveFileRef = class {
|
|
1557
2022
|
drive;
|
|
1558
2023
|
pathOrId;
|
|
@@ -1613,6 +2078,22 @@ var DriveFileRef = class {
|
|
|
1613
2078
|
async getLink() {
|
|
1614
2079
|
return await this.drive.getShareableLink(this.pathOrId);
|
|
1615
2080
|
}
|
|
2081
|
+
/** Returns a ReadableStream for this file, optionally with byte Range requests */
|
|
2082
|
+
async createReadStream(options) {
|
|
2083
|
+
return await this.drive.createReadStream(this.pathOrId, options);
|
|
2084
|
+
}
|
|
2085
|
+
/** Grants access to a specific email with custom role and notification */
|
|
2086
|
+
async grantAccess(options) {
|
|
2087
|
+
return await this.drive.grantAccess(this.pathOrId, options);
|
|
2088
|
+
}
|
|
2089
|
+
/** Revokes access by permission ID or user email */
|
|
2090
|
+
async revokeAccess(permissionIdOrEmail) {
|
|
2091
|
+
return await this.drive.revokeAccess(this.pathOrId, permissionIdOrEmail);
|
|
2092
|
+
}
|
|
2093
|
+
/** Lists all granted permissions on this file */
|
|
2094
|
+
async listPermissions() {
|
|
2095
|
+
return await this.drive.listPermissions(this.pathOrId);
|
|
2096
|
+
}
|
|
1616
2097
|
};
|
|
1617
2098
|
var DriveFolderRef = class {
|
|
1618
2099
|
drive;
|
|
@@ -1650,15 +2131,52 @@ var DriveFolderRef = class {
|
|
|
1650
2131
|
async watch(options = {}) {
|
|
1651
2132
|
return await this.drive.watch(this.pathOrId, options);
|
|
1652
2133
|
}
|
|
2134
|
+
/** Grants access to this entire folder */
|
|
2135
|
+
async grantAccess(options) {
|
|
2136
|
+
return await this.drive.grantAccess(this.pathOrId, options);
|
|
2137
|
+
}
|
|
2138
|
+
/** Creates a writable stream directly into a file inside this folder */
|
|
2139
|
+
async createWriteStream(fileName, options) {
|
|
2140
|
+
const targetPath = this.pathOrId.endsWith("/") ? `${this.pathOrId}${fileName}` : `${this.pathOrId}/${fileName}`;
|
|
2141
|
+
return await this.drive.createWriteStream(targetPath, options);
|
|
2142
|
+
}
|
|
1653
2143
|
};
|
|
1654
2144
|
|
|
1655
2145
|
// src/core/plugins.ts
|
|
2146
|
+
init_esm_shims();
|
|
2147
|
+
import path5 from "path";
|
|
1656
2148
|
var PluginManager = class {
|
|
1657
2149
|
plugins = [];
|
|
2150
|
+
/**
|
|
2151
|
+
* Register a plugin. If a plugin with the same name already exists,
|
|
2152
|
+
* it replaces the old one to avoid duplicate side-effects.
|
|
2153
|
+
*/
|
|
1658
2154
|
use(plugin) {
|
|
2155
|
+
this.plugins = this.plugins.filter((p) => p.name !== plugin.name);
|
|
1659
2156
|
this.plugins.push(plugin);
|
|
1660
2157
|
return this;
|
|
1661
2158
|
}
|
|
2159
|
+
/**
|
|
2160
|
+
* Unregister a plugin by its name.
|
|
2161
|
+
* Returns true if a plugin was found and removed, false otherwise.
|
|
2162
|
+
*/
|
|
2163
|
+
unuse(pluginName) {
|
|
2164
|
+
const initialLen = this.plugins.length;
|
|
2165
|
+
this.plugins = this.plugins.filter((p) => p.name !== pluginName);
|
|
2166
|
+
return this.plugins.length < initialLen;
|
|
2167
|
+
}
|
|
2168
|
+
/**
|
|
2169
|
+
* Check if a plugin with given name is currently active
|
|
2170
|
+
*/
|
|
2171
|
+
has(pluginName) {
|
|
2172
|
+
return this.plugins.some((p) => p.name === pluginName);
|
|
2173
|
+
}
|
|
2174
|
+
/**
|
|
2175
|
+
* Returns all currently registered plugins
|
|
2176
|
+
*/
|
|
2177
|
+
getPlugins() {
|
|
2178
|
+
return [...this.plugins];
|
|
2179
|
+
}
|
|
1662
2180
|
async runBeforeUpload(options) {
|
|
1663
2181
|
let current = { ...options };
|
|
1664
2182
|
for (const plugin of this.plugins) {
|
|
@@ -1700,15 +2218,463 @@ var PluginManager = class {
|
|
|
1700
2218
|
return current;
|
|
1701
2219
|
}
|
|
1702
2220
|
};
|
|
2221
|
+
function createWebhookPlugin(options) {
|
|
2222
|
+
const events = options.events || ["upload"];
|
|
2223
|
+
const timeoutMs = options.timeout ?? 5e3;
|
|
2224
|
+
const maxRetries = options.retries ?? 0;
|
|
2225
|
+
const sendWebhook = async (event, payload) => {
|
|
2226
|
+
let lastError = null;
|
|
2227
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
2228
|
+
let timeoutId;
|
|
2229
|
+
const controller = new AbortController();
|
|
2230
|
+
timeoutId = setTimeout(() => controller.abort(), timeoutMs);
|
|
2231
|
+
try {
|
|
2232
|
+
const res = await fetch(options.url, {
|
|
2233
|
+
method: "POST",
|
|
2234
|
+
headers: { "Content-Type": "application/json", ...options.headers || {} },
|
|
2235
|
+
body: JSON.stringify(payload),
|
|
2236
|
+
signal: controller.signal
|
|
2237
|
+
});
|
|
2238
|
+
clearTimeout(timeoutId);
|
|
2239
|
+
if (!res.ok) {
|
|
2240
|
+
throw new Error(`Webhook returned HTTP ${res.status}: ${res.statusText}`);
|
|
2241
|
+
}
|
|
2242
|
+
return;
|
|
2243
|
+
} catch (err) {
|
|
2244
|
+
clearTimeout(timeoutId);
|
|
2245
|
+
lastError = err;
|
|
2246
|
+
if (attempt === maxRetries) {
|
|
2247
|
+
if (options.onError) {
|
|
2248
|
+
options.onError(lastError instanceof Error ? lastError : new Error(String(lastError)), event);
|
|
2249
|
+
}
|
|
2250
|
+
}
|
|
2251
|
+
}
|
|
2252
|
+
}
|
|
2253
|
+
};
|
|
2254
|
+
return {
|
|
2255
|
+
name: "drivekit-official-webhook",
|
|
2256
|
+
async afterUpload(file) {
|
|
2257
|
+
if (!events.includes("upload")) return;
|
|
2258
|
+
await sendWebhook("upload", {
|
|
2259
|
+
event: "drivekit:upload",
|
|
2260
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2261
|
+
file: {
|
|
2262
|
+
id: file.id,
|
|
2263
|
+
name: file.name,
|
|
2264
|
+
size: file.size,
|
|
2265
|
+
mimeType: file.mimeType
|
|
2266
|
+
}
|
|
2267
|
+
});
|
|
2268
|
+
},
|
|
2269
|
+
async afterDownload(result) {
|
|
2270
|
+
if (!events.includes("download")) return;
|
|
2271
|
+
await sendWebhook("download", {
|
|
2272
|
+
event: "drivekit:download",
|
|
2273
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2274
|
+
file: {
|
|
2275
|
+
name: result.name,
|
|
2276
|
+
size: result.size
|
|
2277
|
+
}
|
|
2278
|
+
});
|
|
2279
|
+
}
|
|
2280
|
+
};
|
|
2281
|
+
}
|
|
2282
|
+
function createAutoNamePlugin(options) {
|
|
2283
|
+
return {
|
|
2284
|
+
name: "drivekit-official-autoname",
|
|
2285
|
+
beforeUpload(opts) {
|
|
2286
|
+
let name = opts.filename;
|
|
2287
|
+
if (!name && typeof opts.source === "string") {
|
|
2288
|
+
name = path5.basename(opts.source);
|
|
2289
|
+
}
|
|
2290
|
+
if (!name) return opts;
|
|
2291
|
+
const ext = path5.extname(name);
|
|
2292
|
+
const base = path5.basename(name, ext);
|
|
2293
|
+
let finalName = base;
|
|
2294
|
+
if (options.prefix) finalName = `${options.prefix}${finalName}`;
|
|
2295
|
+
if (options.appendTimestamp) {
|
|
2296
|
+
finalName = `${finalName}_${Date.now()}`;
|
|
2297
|
+
}
|
|
2298
|
+
if (options.suffix) finalName = `${finalName}${options.suffix}`;
|
|
2299
|
+
finalName = `${finalName}${ext}`;
|
|
2300
|
+
return {
|
|
2301
|
+
...opts,
|
|
2302
|
+
filename: finalName
|
|
2303
|
+
};
|
|
2304
|
+
}
|
|
2305
|
+
};
|
|
2306
|
+
}
|
|
2307
|
+
|
|
2308
|
+
// src/core/cache.ts
|
|
2309
|
+
init_esm_shims();
|
|
2310
|
+
import os from "os";
|
|
2311
|
+
import path6 from "path";
|
|
2312
|
+
import fs5 from "fs";
|
|
2313
|
+
var SqliteMetadataCache = class {
|
|
2314
|
+
db = null;
|
|
2315
|
+
dbPath;
|
|
2316
|
+
initialized = false;
|
|
2317
|
+
fallbackMemory;
|
|
2318
|
+
constructor(customPath) {
|
|
2319
|
+
if (customPath) {
|
|
2320
|
+
this.dbPath = customPath;
|
|
2321
|
+
} else {
|
|
2322
|
+
const dir = path6.join(os.homedir(), ".drivekit");
|
|
2323
|
+
if (!fs5.existsSync(dir)) {
|
|
2324
|
+
try {
|
|
2325
|
+
fs5.mkdirSync(dir, { recursive: true });
|
|
2326
|
+
} catch {
|
|
2327
|
+
}
|
|
2328
|
+
}
|
|
2329
|
+
this.dbPath = path6.join(dir, "cache.db");
|
|
2330
|
+
}
|
|
2331
|
+
}
|
|
2332
|
+
init() {
|
|
2333
|
+
if (this.initialized) return;
|
|
2334
|
+
try {
|
|
2335
|
+
const { DatabaseSync } = __require("sqlite");
|
|
2336
|
+
if (!DatabaseSync) {
|
|
2337
|
+
throw new Error("DatabaseSync not available");
|
|
2338
|
+
}
|
|
2339
|
+
this.db = new DatabaseSync(this.dbPath);
|
|
2340
|
+
this.db.exec(`
|
|
2341
|
+
PRAGMA journal_mode = WAL;
|
|
2342
|
+
PRAGMA synchronous = NORMAL;
|
|
2343
|
+
|
|
2344
|
+
CREATE TABLE IF NOT EXISTS files (
|
|
2345
|
+
id TEXT PRIMARY KEY,
|
|
2346
|
+
name TEXT NOT NULL,
|
|
2347
|
+
mimeType TEXT,
|
|
2348
|
+
size INTEGER,
|
|
2349
|
+
parentId TEXT,
|
|
2350
|
+
path TEXT,
|
|
2351
|
+
md5Checksum TEXT,
|
|
2352
|
+
trashed INTEGER DEFAULT 0,
|
|
2353
|
+
modifiedTime TEXT,
|
|
2354
|
+
updatedAt INTEGER
|
|
2355
|
+
);
|
|
2356
|
+
|
|
2357
|
+
CREATE TABLE IF NOT EXISTS meta (
|
|
2358
|
+
key TEXT PRIMARY KEY,
|
|
2359
|
+
value TEXT NOT NULL
|
|
2360
|
+
);
|
|
2361
|
+
|
|
2362
|
+
CREATE INDEX IF NOT EXISTS idx_files_path ON files(path);
|
|
2363
|
+
CREATE INDEX IF NOT EXISTS idx_files_parent ON files(parentId);
|
|
2364
|
+
CREATE INDEX IF NOT EXISTS idx_files_md5 ON files(md5Checksum);
|
|
2365
|
+
CREATE INDEX IF NOT EXISTS idx_files_name ON files(name);
|
|
2366
|
+
`);
|
|
2367
|
+
this.initialized = true;
|
|
2368
|
+
} catch (err) {
|
|
2369
|
+
this.fallbackMemory = new MemoryMetadataCache();
|
|
2370
|
+
this.fallbackMemory.init();
|
|
2371
|
+
this.initialized = true;
|
|
2372
|
+
this.db = null;
|
|
2373
|
+
}
|
|
2374
|
+
}
|
|
2375
|
+
getById(id) {
|
|
2376
|
+
if (this.fallbackMemory) return this.fallbackMemory.getById(id);
|
|
2377
|
+
if (!this.initialized || !this.db) return null;
|
|
2378
|
+
const stmt = this.db.prepare("SELECT * FROM files WHERE id = ?");
|
|
2379
|
+
const row = stmt.get(id);
|
|
2380
|
+
return row ? this.mapRow(row) : null;
|
|
2381
|
+
}
|
|
2382
|
+
getByPath(normalizedPath) {
|
|
2383
|
+
if (this.fallbackMemory) return this.fallbackMemory.getByPath(normalizedPath);
|
|
2384
|
+
if (!this.initialized || !this.db) return null;
|
|
2385
|
+
const stmt = this.db.prepare("SELECT * FROM files WHERE path = ? AND trashed = 0 LIMIT 1");
|
|
2386
|
+
const row = stmt.get(normalizedPath);
|
|
2387
|
+
return row ? this.mapRow(row) : null;
|
|
2388
|
+
}
|
|
2389
|
+
getChildren(parentId) {
|
|
2390
|
+
if (this.fallbackMemory) return this.fallbackMemory.getChildren(parentId);
|
|
2391
|
+
if (!this.initialized || !this.db) return [];
|
|
2392
|
+
const stmt = this.db.prepare("SELECT * FROM files WHERE parentId = ? AND trashed = 0 ORDER BY name ASC");
|
|
2393
|
+
const rows = stmt.all(parentId);
|
|
2394
|
+
return rows.map((r) => this.mapRow(r));
|
|
2395
|
+
}
|
|
2396
|
+
findByMd5(md5) {
|
|
2397
|
+
if (this.fallbackMemory) return this.fallbackMemory.findByMd5(md5);
|
|
2398
|
+
if (!this.initialized || !this.db || !md5) return null;
|
|
2399
|
+
const stmt = this.db.prepare("SELECT * FROM files WHERE md5Checksum = ? AND trashed = 0 LIMIT 1");
|
|
2400
|
+
const row = stmt.get(md5.toLowerCase());
|
|
2401
|
+
return row ? this.mapRow(row) : null;
|
|
2402
|
+
}
|
|
2403
|
+
searchByName(query) {
|
|
2404
|
+
if (this.fallbackMemory) return this.fallbackMemory.searchByName(query);
|
|
2405
|
+
if (!this.initialized || !this.db) return [];
|
|
2406
|
+
const stmt = this.db.prepare("SELECT * FROM files WHERE name LIKE ? AND trashed = 0 LIMIT 50");
|
|
2407
|
+
const rows = stmt.all(`%${query}%`);
|
|
2408
|
+
return rows.map((r) => this.mapRow(r));
|
|
2409
|
+
}
|
|
2410
|
+
upsertFile(entry) {
|
|
2411
|
+
if (this.fallbackMemory) {
|
|
2412
|
+
this.fallbackMemory.upsertFile(entry);
|
|
2413
|
+
return;
|
|
2414
|
+
}
|
|
2415
|
+
if (!this.initialized || !this.db) return;
|
|
2416
|
+
const stmt = this.db.prepare(`
|
|
2417
|
+
INSERT INTO files (id, name, mimeType, size, parentId, path, md5Checksum, trashed, modifiedTime, updatedAt)
|
|
2418
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
2419
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
2420
|
+
name = excluded.name,
|
|
2421
|
+
mimeType = excluded.mimeType,
|
|
2422
|
+
size = excluded.size,
|
|
2423
|
+
parentId = excluded.parentId,
|
|
2424
|
+
path = COALESCE(excluded.path, files.path),
|
|
2425
|
+
md5Checksum = excluded.md5Checksum,
|
|
2426
|
+
trashed = excluded.trashed,
|
|
2427
|
+
modifiedTime = excluded.modifiedTime,
|
|
2428
|
+
updatedAt = excluded.updatedAt
|
|
2429
|
+
`);
|
|
2430
|
+
stmt.run(
|
|
2431
|
+
entry.id,
|
|
2432
|
+
entry.name,
|
|
2433
|
+
entry.mimeType ?? null,
|
|
2434
|
+
entry.size ?? null,
|
|
2435
|
+
entry.parentId ?? null,
|
|
2436
|
+
entry.path ?? null,
|
|
2437
|
+
entry.md5Checksum ? entry.md5Checksum.toLowerCase() : null,
|
|
2438
|
+
entry.trashed ? 1 : 0,
|
|
2439
|
+
entry.modifiedTime ?? null,
|
|
2440
|
+
entry.updatedAt ?? Date.now()
|
|
2441
|
+
);
|
|
2442
|
+
}
|
|
2443
|
+
upsertFiles(entries) {
|
|
2444
|
+
if (this.fallbackMemory) {
|
|
2445
|
+
this.fallbackMemory.upsertFiles(entries);
|
|
2446
|
+
return;
|
|
2447
|
+
}
|
|
2448
|
+
if (!this.initialized || !this.db || entries.length === 0) return;
|
|
2449
|
+
this.db.exec("BEGIN TRANSACTION;");
|
|
2450
|
+
try {
|
|
2451
|
+
for (const entry of entries) {
|
|
2452
|
+
this.upsertFile(entry);
|
|
2453
|
+
}
|
|
2454
|
+
this.db.exec("COMMIT;");
|
|
2455
|
+
} catch (e) {
|
|
2456
|
+
this.db.exec("ROLLBACK;");
|
|
2457
|
+
throw e;
|
|
2458
|
+
}
|
|
2459
|
+
}
|
|
2460
|
+
deleteFile(id) {
|
|
2461
|
+
if (this.fallbackMemory) {
|
|
2462
|
+
this.fallbackMemory.deleteFile(id);
|
|
2463
|
+
return;
|
|
2464
|
+
}
|
|
2465
|
+
if (!this.initialized || !this.db) return;
|
|
2466
|
+
const stmt = this.db.prepare("DELETE FROM files WHERE id = ?");
|
|
2467
|
+
stmt.run(id);
|
|
2468
|
+
}
|
|
2469
|
+
pruneMissing(activeIds) {
|
|
2470
|
+
if (this.fallbackMemory) {
|
|
2471
|
+
return this.fallbackMemory.pruneMissing(activeIds);
|
|
2472
|
+
}
|
|
2473
|
+
if (!this.initialized || !this.db || activeIds.length === 0) return 0;
|
|
2474
|
+
const idSet = new Set(activeIds);
|
|
2475
|
+
const rows = this.db.prepare("SELECT id FROM files").all();
|
|
2476
|
+
let pruned = 0;
|
|
2477
|
+
this.db.exec("BEGIN TRANSACTION;");
|
|
2478
|
+
try {
|
|
2479
|
+
const deleteStmt = this.db.prepare("DELETE FROM files WHERE id = ?");
|
|
2480
|
+
for (const row of rows) {
|
|
2481
|
+
if (!idSet.has(row.id)) {
|
|
2482
|
+
deleteStmt.run(row.id);
|
|
2483
|
+
pruned++;
|
|
2484
|
+
}
|
|
2485
|
+
}
|
|
2486
|
+
this.db.exec("COMMIT;");
|
|
2487
|
+
return pruned;
|
|
2488
|
+
} catch (e) {
|
|
2489
|
+
this.db.exec("ROLLBACK;");
|
|
2490
|
+
throw e;
|
|
2491
|
+
}
|
|
2492
|
+
}
|
|
2493
|
+
clear() {
|
|
2494
|
+
if (this.fallbackMemory) {
|
|
2495
|
+
this.fallbackMemory.clear();
|
|
2496
|
+
return;
|
|
2497
|
+
}
|
|
2498
|
+
if (!this.initialized || !this.db) return;
|
|
2499
|
+
this.db.exec("DELETE FROM files; DELETE FROM meta;");
|
|
2500
|
+
}
|
|
2501
|
+
getMeta(key) {
|
|
2502
|
+
if (this.fallbackMemory) return this.fallbackMemory.getMeta(key);
|
|
2503
|
+
if (!this.initialized || !this.db) return null;
|
|
2504
|
+
const stmt = this.db.prepare("SELECT value FROM meta WHERE key = ?");
|
|
2505
|
+
const row = stmt.get(key);
|
|
2506
|
+
return row ? row.value : null;
|
|
2507
|
+
}
|
|
2508
|
+
setMeta(key, value) {
|
|
2509
|
+
if (this.fallbackMemory) {
|
|
2510
|
+
this.fallbackMemory.setMeta(key, value);
|
|
2511
|
+
return;
|
|
2512
|
+
}
|
|
2513
|
+
if (!this.initialized || !this.db) return;
|
|
2514
|
+
const stmt = this.db.prepare(`
|
|
2515
|
+
INSERT INTO meta (key, value) VALUES (?, ?)
|
|
2516
|
+
ON CONFLICT(key) DO UPDATE SET value = excluded.value
|
|
2517
|
+
`);
|
|
2518
|
+
stmt.run(key, value);
|
|
2519
|
+
}
|
|
2520
|
+
getStats() {
|
|
2521
|
+
if (this.fallbackMemory) return this.fallbackMemory.getStats();
|
|
2522
|
+
if (!this.initialized || !this.db) {
|
|
2523
|
+
return {
|
|
2524
|
+
fileCount: 0,
|
|
2525
|
+
folderCount: 0,
|
|
2526
|
+
totalSizeBytes: 0,
|
|
2527
|
+
lastSyncTime: null,
|
|
2528
|
+
databasePath: this.dbPath
|
|
2529
|
+
};
|
|
2530
|
+
}
|
|
2531
|
+
const fileCountRow = this.db.prepare(
|
|
2532
|
+
"SELECT COUNT(*) as count FROM files WHERE mimeType != 'application/vnd.google-apps.folder' AND trashed = 0"
|
|
2533
|
+
).get();
|
|
2534
|
+
const folderCountRow = this.db.prepare(
|
|
2535
|
+
"SELECT COUNT(*) as count FROM files WHERE mimeType = 'application/vnd.google-apps.folder' AND trashed = 0"
|
|
2536
|
+
).get();
|
|
2537
|
+
const totalSizeRow = this.db.prepare(
|
|
2538
|
+
"SELECT SUM(size) as total FROM files WHERE trashed = 0"
|
|
2539
|
+
).get();
|
|
2540
|
+
const lastSync = this.getMeta("last_sync_timestamp");
|
|
2541
|
+
return {
|
|
2542
|
+
fileCount: fileCountRow?.count || 0,
|
|
2543
|
+
folderCount: folderCountRow?.count || 0,
|
|
2544
|
+
totalSizeBytes: totalSizeRow?.total || 0,
|
|
2545
|
+
lastSyncTime: lastSync,
|
|
2546
|
+
databasePath: this.dbPath
|
|
2547
|
+
};
|
|
2548
|
+
}
|
|
2549
|
+
close() {
|
|
2550
|
+
if (this.fallbackMemory) {
|
|
2551
|
+
this.fallbackMemory.close();
|
|
2552
|
+
this.fallbackMemory = void 0;
|
|
2553
|
+
}
|
|
2554
|
+
if (this.db) {
|
|
2555
|
+
try {
|
|
2556
|
+
this.db.close();
|
|
2557
|
+
} catch {
|
|
2558
|
+
}
|
|
2559
|
+
this.initialized = false;
|
|
2560
|
+
this.db = null;
|
|
2561
|
+
}
|
|
2562
|
+
}
|
|
2563
|
+
mapRow(row) {
|
|
2564
|
+
return {
|
|
2565
|
+
id: row.id,
|
|
2566
|
+
name: row.name,
|
|
2567
|
+
mimeType: row.mimeType,
|
|
2568
|
+
size: row.size != null ? Number(row.size) : void 0,
|
|
2569
|
+
parentId: row.parentId || void 0,
|
|
2570
|
+
path: row.path || void 0,
|
|
2571
|
+
md5Checksum: row.md5Checksum || void 0,
|
|
2572
|
+
trashed: row.trashed === 1,
|
|
2573
|
+
modifiedTime: row.modifiedTime || void 0,
|
|
2574
|
+
updatedAt: row.updatedAt != null ? Number(row.updatedAt) : void 0
|
|
2575
|
+
};
|
|
2576
|
+
}
|
|
2577
|
+
};
|
|
2578
|
+
var MemoryMetadataCache = class {
|
|
2579
|
+
files = /* @__PURE__ */ new Map();
|
|
2580
|
+
meta = /* @__PURE__ */ new Map();
|
|
2581
|
+
init() {
|
|
2582
|
+
}
|
|
2583
|
+
getById(id) {
|
|
2584
|
+
return this.files.get(id) || null;
|
|
2585
|
+
}
|
|
2586
|
+
getByPath(normalizedPath) {
|
|
2587
|
+
for (const f of this.files.values()) {
|
|
2588
|
+
if (f.path === normalizedPath && !f.trashed) return f;
|
|
2589
|
+
}
|
|
2590
|
+
return null;
|
|
2591
|
+
}
|
|
2592
|
+
getChildren(parentId) {
|
|
2593
|
+
const list = [];
|
|
2594
|
+
for (const f of this.files.values()) {
|
|
2595
|
+
if (f.parentId === parentId && !f.trashed) list.push(f);
|
|
2596
|
+
}
|
|
2597
|
+
return list;
|
|
2598
|
+
}
|
|
2599
|
+
findByMd5(md5) {
|
|
2600
|
+
const target = md5.toLowerCase();
|
|
2601
|
+
for (const f of this.files.values()) {
|
|
2602
|
+
if (f.md5Checksum?.toLowerCase() === target && !f.trashed) return f;
|
|
2603
|
+
}
|
|
2604
|
+
return null;
|
|
2605
|
+
}
|
|
2606
|
+
searchByName(query) {
|
|
2607
|
+
const q = query.toLowerCase();
|
|
2608
|
+
const list = [];
|
|
2609
|
+
for (const f of this.files.values()) {
|
|
2610
|
+
if (f.name.toLowerCase().includes(q) && !f.trashed) list.push(f);
|
|
2611
|
+
}
|
|
2612
|
+
return list;
|
|
2613
|
+
}
|
|
2614
|
+
upsertFile(entry) {
|
|
2615
|
+
this.files.set(entry.id, { ...entry, updatedAt: Date.now() });
|
|
2616
|
+
}
|
|
2617
|
+
upsertFiles(entries) {
|
|
2618
|
+
for (const e of entries) this.upsertFile(e);
|
|
2619
|
+
}
|
|
2620
|
+
deleteFile(id) {
|
|
2621
|
+
this.files.delete(id);
|
|
2622
|
+
}
|
|
2623
|
+
pruneMissing(activeIds) {
|
|
2624
|
+
const idSet = new Set(activeIds);
|
|
2625
|
+
let pruned = 0;
|
|
2626
|
+
for (const id of Array.from(this.files.keys())) {
|
|
2627
|
+
if (!idSet.has(id)) {
|
|
2628
|
+
this.files.delete(id);
|
|
2629
|
+
pruned++;
|
|
2630
|
+
}
|
|
2631
|
+
}
|
|
2632
|
+
return pruned;
|
|
2633
|
+
}
|
|
2634
|
+
clear() {
|
|
2635
|
+
this.files.clear();
|
|
2636
|
+
this.meta.clear();
|
|
2637
|
+
}
|
|
2638
|
+
getMeta(key) {
|
|
2639
|
+
return this.meta.get(key) || null;
|
|
2640
|
+
}
|
|
2641
|
+
setMeta(key, value) {
|
|
2642
|
+
this.meta.set(key, value);
|
|
2643
|
+
}
|
|
2644
|
+
getStats() {
|
|
2645
|
+
let fileCount = 0;
|
|
2646
|
+
let folderCount = 0;
|
|
2647
|
+
let totalSizeBytes = 0;
|
|
2648
|
+
for (const f of this.files.values()) {
|
|
2649
|
+
if (f.trashed) continue;
|
|
2650
|
+
if (f.mimeType === "application/vnd.google-apps.folder") folderCount++;
|
|
2651
|
+
else {
|
|
2652
|
+
fileCount++;
|
|
2653
|
+
totalSizeBytes += f.size || 0;
|
|
2654
|
+
}
|
|
2655
|
+
}
|
|
2656
|
+
return {
|
|
2657
|
+
fileCount,
|
|
2658
|
+
folderCount,
|
|
2659
|
+
totalSizeBytes,
|
|
2660
|
+
lastSyncTime: this.meta.get("last_sync_timestamp") || null,
|
|
2661
|
+
databasePath: ":memory:"
|
|
2662
|
+
};
|
|
2663
|
+
}
|
|
2664
|
+
close() {
|
|
2665
|
+
this.clear();
|
|
2666
|
+
}
|
|
2667
|
+
};
|
|
1703
2668
|
|
|
1704
2669
|
// src/core/client.ts
|
|
1705
|
-
var DriveKit = class {
|
|
2670
|
+
var DriveKit = class _DriveKit {
|
|
1706
2671
|
options;
|
|
1707
2672
|
authenticator;
|
|
1708
2673
|
driveClient = null;
|
|
1709
2674
|
pathResolverInstance = null;
|
|
1710
2675
|
uploaderInstance = null;
|
|
1711
2676
|
downloaderInstance = null;
|
|
2677
|
+
metadataCacheInstance = null;
|
|
1712
2678
|
rootFolderId;
|
|
1713
2679
|
pluginManager = new PluginManager();
|
|
1714
2680
|
constructor(options = {}) {
|
|
@@ -1742,9 +2708,14 @@ var DriveKit = class {
|
|
|
1742
2708
|
if (!this.driveClient) {
|
|
1743
2709
|
const auth = await this.authenticator.getAuthClient();
|
|
1744
2710
|
this.driveClient = drive({ version: "v3", auth });
|
|
2711
|
+
if (this.options.enablePersistentCache !== false) {
|
|
2712
|
+
this.metadataCacheInstance = new SqliteMetadataCache(this.options.cacheDatabasePath);
|
|
2713
|
+
this.metadataCacheInstance.init();
|
|
2714
|
+
}
|
|
1745
2715
|
this.pathResolverInstance = new PathResolver(this.driveClient, this.rootFolderId, {
|
|
1746
2716
|
enableCache: this.options.enablePathCache ?? true,
|
|
1747
|
-
cacheTTL: this.options.pathCacheTTL
|
|
2717
|
+
cacheTTL: this.options.pathCacheTTL,
|
|
2718
|
+
metadataCache: this.metadataCacheInstance || void 0
|
|
1748
2719
|
});
|
|
1749
2720
|
this.uploaderInstance = new ResumableUploader(
|
|
1750
2721
|
this.driveClient,
|
|
@@ -1826,8 +2797,9 @@ var DriveKit = class {
|
|
|
1826
2797
|
* Lists contents of a folder (by folder ID or path)
|
|
1827
2798
|
*/
|
|
1828
2799
|
async ls(folderIdOrPath = "/") {
|
|
1829
|
-
if (folderIdOrPath === "/" || folderIdOrPath === "root") {
|
|
1830
|
-
|
|
2800
|
+
if (folderIdOrPath === "/" || folderIdOrPath === "root" || folderIdOrPath === this.rootFolderId) {
|
|
2801
|
+
const parentFilter = this.rootFolderId === "root" ? "'root' in parents or sharedWithMe = true" : `'${this.rootFolderId}' in parents`;
|
|
2802
|
+
return await this.query().raw(parentFilter).notTrashed().orderBy("folder,name").list();
|
|
1831
2803
|
}
|
|
1832
2804
|
const folderId = await this.resolveId(folderIdOrPath);
|
|
1833
2805
|
return await this.query().inFolder(folderId).notTrashed().orderBy("folder,name").list();
|
|
@@ -1849,16 +2821,71 @@ var DriveKit = class {
|
|
|
1849
2821
|
if (parentId && parentId.startsWith("/")) {
|
|
1850
2822
|
parentId = await this.mkdirp(parentId);
|
|
1851
2823
|
}
|
|
1852
|
-
|
|
1853
|
-
|
|
2824
|
+
const targetName = opts.name || opts.filename;
|
|
2825
|
+
if (opts.overwrite && targetName && parentId) {
|
|
2826
|
+
const existing = await this.query().inFolder(parentId).nameEquals(targetName).notTrashed().first();
|
|
1854
2827
|
if (existing?.id) {
|
|
1855
2828
|
await this.delete(existing.id, true);
|
|
1856
2829
|
}
|
|
1857
2830
|
}
|
|
2831
|
+
if (opts.deduplicate && typeof opts.source === "string" && fs6.existsSync(opts.source)) {
|
|
2832
|
+
const localMd5 = await calculateFileMd5(opts.source);
|
|
2833
|
+
let existingId;
|
|
2834
|
+
if (this.metadataCacheInstance) {
|
|
2835
|
+
const cached = this.metadataCacheInstance.findByMd5(localMd5);
|
|
2836
|
+
if (cached) existingId = cached.id;
|
|
2837
|
+
}
|
|
2838
|
+
if (!existingId) {
|
|
2839
|
+
const found = await this.query().md5(localMd5).notTrashed().first();
|
|
2840
|
+
if (found?.id) {
|
|
2841
|
+
existingId = found.id;
|
|
2842
|
+
}
|
|
2843
|
+
}
|
|
2844
|
+
if (existingId) {
|
|
2845
|
+
const fileName = targetName || path8.basename(opts.source);
|
|
2846
|
+
const raw = await this.getRawClient();
|
|
2847
|
+
const copyRes = await withRetry(async () => {
|
|
2848
|
+
return await raw.files.copy({
|
|
2849
|
+
fileId: existingId,
|
|
2850
|
+
requestBody: {
|
|
2851
|
+
name: fileName,
|
|
2852
|
+
parents: parentId ? [parentId] : void 0,
|
|
2853
|
+
description: opts.description
|
|
2854
|
+
},
|
|
2855
|
+
fields: "id, name, mimeType, size, modifiedTime, md5Checksum",
|
|
2856
|
+
supportsAllDrives: true
|
|
2857
|
+
});
|
|
2858
|
+
});
|
|
2859
|
+
const file = copyRes.data;
|
|
2860
|
+
if (this.metadataCacheInstance && file.id) {
|
|
2861
|
+
this.metadataCacheInstance.upsertFile({
|
|
2862
|
+
id: file.id,
|
|
2863
|
+
name: file.name || fileName,
|
|
2864
|
+
mimeType: file.mimeType || "",
|
|
2865
|
+
size: file.size ? parseInt(file.size, 10) : void 0,
|
|
2866
|
+
parentId,
|
|
2867
|
+
md5Checksum: localMd5,
|
|
2868
|
+
trashed: false
|
|
2869
|
+
});
|
|
2870
|
+
}
|
|
2871
|
+
return await this.pluginManager.runAfterUpload(file);
|
|
2872
|
+
}
|
|
2873
|
+
}
|
|
1858
2874
|
const uploaded = await uploader.upload({
|
|
1859
2875
|
...opts,
|
|
2876
|
+
name: targetName,
|
|
1860
2877
|
parent: parentId
|
|
1861
2878
|
});
|
|
2879
|
+
if (this.metadataCacheInstance && uploaded.id) {
|
|
2880
|
+
this.metadataCacheInstance.upsertFile({
|
|
2881
|
+
id: uploaded.id,
|
|
2882
|
+
name: uploaded.name || targetName || "untitled",
|
|
2883
|
+
mimeType: uploaded.mimeType || "",
|
|
2884
|
+
size: uploaded.size ? parseInt(uploaded.size, 10) : void 0,
|
|
2885
|
+
parentId,
|
|
2886
|
+
trashed: false
|
|
2887
|
+
});
|
|
2888
|
+
}
|
|
1862
2889
|
return await this.pluginManager.runAfterUpload(uploaded);
|
|
1863
2890
|
}
|
|
1864
2891
|
/**
|
|
@@ -2099,16 +3126,16 @@ var DriveKit = class {
|
|
|
2099
3126
|
durationMs: 0
|
|
2100
3127
|
};
|
|
2101
3128
|
const collectFiles = async (dir, base) => {
|
|
2102
|
-
const entries = await
|
|
3129
|
+
const entries = await fs6.promises.readdir(dir, { withFileTypes: true });
|
|
2103
3130
|
const files = [];
|
|
2104
3131
|
for (const entry of entries) {
|
|
2105
|
-
const fullPath =
|
|
2106
|
-
const relPath =
|
|
3132
|
+
const fullPath = path8.join(dir, entry.name);
|
|
3133
|
+
const relPath = path8.join(base, entry.name);
|
|
2107
3134
|
if (entry.isDirectory()) {
|
|
2108
3135
|
const sub = await collectFiles(fullPath, relPath);
|
|
2109
3136
|
files.push(...sub);
|
|
2110
3137
|
} else if (entry.isFile()) {
|
|
2111
|
-
const stat = await
|
|
3138
|
+
const stat = await fs6.promises.stat(fullPath);
|
|
2112
3139
|
files.push({ fullPath, relPath, size: stat.size });
|
|
2113
3140
|
}
|
|
2114
3141
|
}
|
|
@@ -2121,11 +3148,11 @@ var DriveKit = class {
|
|
|
2121
3148
|
if (remoteDirCache.has(relDir)) {
|
|
2122
3149
|
return remoteDirCache.get(relDir);
|
|
2123
3150
|
}
|
|
2124
|
-
const parts = relDir.split(
|
|
3151
|
+
const parts = relDir.split(path8.sep).filter(Boolean);
|
|
2125
3152
|
let currentParent = targetFolderId;
|
|
2126
3153
|
let currentRel = "";
|
|
2127
3154
|
for (const part of parts) {
|
|
2128
|
-
currentRel = currentRel ?
|
|
3155
|
+
currentRel = currentRel ? path8.join(currentRel, part) : part;
|
|
2129
3156
|
if (remoteDirCache.has(currentRel)) {
|
|
2130
3157
|
currentParent = remoteDirCache.get(currentRel);
|
|
2131
3158
|
continue;
|
|
@@ -2154,8 +3181,8 @@ var DriveKit = class {
|
|
|
2154
3181
|
};
|
|
2155
3182
|
await pool.map(allFiles, async (fileItem) => {
|
|
2156
3183
|
try {
|
|
2157
|
-
const relDir =
|
|
2158
|
-
const fileName =
|
|
3184
|
+
const relDir = path8.dirname(fileItem.relPath);
|
|
3185
|
+
const fileName = path8.basename(fileItem.relPath);
|
|
2159
3186
|
const parentFolderId = await ensureRemoteSubdir(relDir === "." ? "" : relDir);
|
|
2160
3187
|
if (options.onFileStart) {
|
|
2161
3188
|
options.onFileStart(fileItem.fullPath, fileItem.relPath);
|
|
@@ -2273,6 +3300,256 @@ var DriveKit = class {
|
|
|
2273
3300
|
const engine = new SmartSyncEngine(this.driveClient);
|
|
2274
3301
|
return await engine.pullFolder(folderId, localDestinationDir, options);
|
|
2275
3302
|
}
|
|
3303
|
+
// ==========================================
|
|
3304
|
+
// STREAMS & RANGE REQUESTS
|
|
3305
|
+
// ==========================================
|
|
3306
|
+
/**
|
|
3307
|
+
* Creates a readable stream for a file, supporting partial range requests
|
|
3308
|
+
*/
|
|
3309
|
+
async createReadStream(pathOrId, options) {
|
|
3310
|
+
const fileId = await this.resolveId(pathOrId);
|
|
3311
|
+
const downloader = await this.getDownloader();
|
|
3312
|
+
return await downloader.createReadStream(fileId, options);
|
|
3313
|
+
}
|
|
3314
|
+
/**
|
|
3315
|
+
* Creates a writable stream directly into Google Drive
|
|
3316
|
+
*/
|
|
3317
|
+
async createWriteStream(remotePath, options = {}) {
|
|
3318
|
+
await this.init();
|
|
3319
|
+
const { PassThrough } = await import("stream");
|
|
3320
|
+
const passThrough = new PassThrough();
|
|
3321
|
+
let resolveDone;
|
|
3322
|
+
let rejectDone;
|
|
3323
|
+
const donePromise = new Promise((resolve, reject) => {
|
|
3324
|
+
resolveDone = resolve;
|
|
3325
|
+
rejectDone = reject;
|
|
3326
|
+
});
|
|
3327
|
+
passThrough.done = donePromise;
|
|
3328
|
+
const remoteDir = path8.dirname(remotePath);
|
|
3329
|
+
const fileName = options.name || options.filename || path8.basename(remotePath);
|
|
3330
|
+
const targetParentId = remoteDir === "." || remoteDir === "/" ? this.rootFolderId : await this.mkdirp(remoteDir);
|
|
3331
|
+
const mimeType = options.mimeType || "application/octet-stream";
|
|
3332
|
+
const raw = this.driveClient;
|
|
3333
|
+
raw.files.create({
|
|
3334
|
+
requestBody: {
|
|
3335
|
+
name: fileName,
|
|
3336
|
+
parents: [targetParentId],
|
|
3337
|
+
description: options.description
|
|
3338
|
+
},
|
|
3339
|
+
media: {
|
|
3340
|
+
mimeType,
|
|
3341
|
+
body: passThrough
|
|
3342
|
+
},
|
|
3343
|
+
fields: "id, name, mimeType, size, md5Checksum",
|
|
3344
|
+
supportsAllDrives: true
|
|
3345
|
+
}).then((res) => {
|
|
3346
|
+
const file = res.data;
|
|
3347
|
+
if (file.id && this.metadataCacheInstance) {
|
|
3348
|
+
this.metadataCacheInstance.upsertFile({
|
|
3349
|
+
id: file.id,
|
|
3350
|
+
name: fileName,
|
|
3351
|
+
mimeType,
|
|
3352
|
+
parentId: targetParentId,
|
|
3353
|
+
path: remotePath,
|
|
3354
|
+
trashed: false
|
|
3355
|
+
});
|
|
3356
|
+
}
|
|
3357
|
+
resolveDone(file);
|
|
3358
|
+
}).catch((err) => {
|
|
3359
|
+
passThrough.destroy(err);
|
|
3360
|
+
rejectDone(err);
|
|
3361
|
+
});
|
|
3362
|
+
return passThrough;
|
|
3363
|
+
}
|
|
3364
|
+
// ==========================================
|
|
3365
|
+
// METADATA CACHE OPERATIONS
|
|
3366
|
+
// ==========================================
|
|
3367
|
+
/**
|
|
3368
|
+
* Returns the active persistent metadata cache instance (SQLite/Memory)
|
|
3369
|
+
*/
|
|
3370
|
+
async getMetadataCache() {
|
|
3371
|
+
await this.init();
|
|
3372
|
+
return this.metadataCacheInstance;
|
|
3373
|
+
}
|
|
3374
|
+
/**
|
|
3375
|
+
* Returns cache statistics (total files, folders, size, last sync)
|
|
3376
|
+
*/
|
|
3377
|
+
async getCacheStats() {
|
|
3378
|
+
await this.init();
|
|
3379
|
+
return this.metadataCacheInstance ? this.metadataCacheInstance.getStats() : null;
|
|
3380
|
+
}
|
|
3381
|
+
/**
|
|
3382
|
+
* Clears the path and metadata cache
|
|
3383
|
+
*/
|
|
3384
|
+
async clearCache() {
|
|
3385
|
+
await this.init();
|
|
3386
|
+
if (this.pathResolverInstance) {
|
|
3387
|
+
this.pathResolverInstance.clearCache();
|
|
3388
|
+
}
|
|
3389
|
+
}
|
|
3390
|
+
/**
|
|
3391
|
+
* Crawls and indexes Google Drive metadata into the local SQLite database for instant 0ms lookups
|
|
3392
|
+
*/
|
|
3393
|
+
async syncCache(options) {
|
|
3394
|
+
await this.init();
|
|
3395
|
+
if (!this.metadataCacheInstance) {
|
|
3396
|
+
throw new Error("Persistent cache is disabled on this DriveKit instance");
|
|
3397
|
+
}
|
|
3398
|
+
const client = this.driveClient;
|
|
3399
|
+
let pageToken = void 0;
|
|
3400
|
+
let totalScanned = 0;
|
|
3401
|
+
const rawFiles = [];
|
|
3402
|
+
do {
|
|
3403
|
+
const res = await withRetry(async () => {
|
|
3404
|
+
return await client.files.list({
|
|
3405
|
+
pageSize: 1e3,
|
|
3406
|
+
pageToken,
|
|
3407
|
+
fields: "nextPageToken, files(id, name, mimeType, size, parents, md5Checksum, trashed, modifiedTime)",
|
|
3408
|
+
spaces: "drive",
|
|
3409
|
+
supportsAllDrives: true,
|
|
3410
|
+
includeItemsFromAllDrives: true,
|
|
3411
|
+
q: "trashed = false"
|
|
3412
|
+
});
|
|
3413
|
+
});
|
|
3414
|
+
const files = res.data.files || [];
|
|
3415
|
+
for (const f of files) {
|
|
3416
|
+
if (f.id) rawFiles.push(f);
|
|
3417
|
+
}
|
|
3418
|
+
totalScanned += files.length;
|
|
3419
|
+
options?.onProgress?.(totalScanned);
|
|
3420
|
+
pageToken = res.data.nextPageToken || void 0;
|
|
3421
|
+
} while (pageToken);
|
|
3422
|
+
const fileMap = /* @__PURE__ */ new Map();
|
|
3423
|
+
for (const f of rawFiles) {
|
|
3424
|
+
fileMap.set(f.id, f);
|
|
3425
|
+
}
|
|
3426
|
+
const pathMemo = /* @__PURE__ */ new Map();
|
|
3427
|
+
const rootId = this.rootFolderId;
|
|
3428
|
+
function computePath(id, visited = /* @__PURE__ */ new Set()) {
|
|
3429
|
+
if (pathMemo.has(id)) return pathMemo.get(id);
|
|
3430
|
+
if (visited.has(id)) return "";
|
|
3431
|
+
visited.add(id);
|
|
3432
|
+
const f = fileMap.get(id);
|
|
3433
|
+
if (!f || !f.name) return "";
|
|
3434
|
+
const parentId = f.parents?.[0];
|
|
3435
|
+
if (!parentId || parentId === "root" || parentId === rootId) {
|
|
3436
|
+
const p = `/${f.name}`;
|
|
3437
|
+
pathMemo.set(id, p);
|
|
3438
|
+
return p;
|
|
3439
|
+
}
|
|
3440
|
+
const parentPath = computePath(parentId, visited);
|
|
3441
|
+
const fullPath = parentPath ? `${parentPath}/${f.name}` : `/${f.name}`;
|
|
3442
|
+
pathMemo.set(id, fullPath);
|
|
3443
|
+
return fullPath;
|
|
3444
|
+
}
|
|
3445
|
+
const entries = rawFiles.map((f) => ({
|
|
3446
|
+
id: f.id,
|
|
3447
|
+
name: f.name || "untitled",
|
|
3448
|
+
mimeType: f.mimeType || "",
|
|
3449
|
+
size: f.size ? parseInt(f.size, 10) : void 0,
|
|
3450
|
+
parentId: f.parents?.[0],
|
|
3451
|
+
path: computePath(f.id),
|
|
3452
|
+
md5Checksum: f.md5Checksum || void 0,
|
|
3453
|
+
trashed: !!f.trashed,
|
|
3454
|
+
modifiedTime: f.modifiedTime || void 0
|
|
3455
|
+
}));
|
|
3456
|
+
this.metadataCacheInstance.upsertFiles(entries);
|
|
3457
|
+
this.metadataCacheInstance.pruneMissing(rawFiles.map((f) => f.id));
|
|
3458
|
+
this.metadataCacheInstance.setMeta("last_sync_timestamp", (/* @__PURE__ */ new Date()).toISOString());
|
|
3459
|
+
return this.metadataCacheInstance.getStats();
|
|
3460
|
+
}
|
|
3461
|
+
// ==========================================
|
|
3462
|
+
// SHARED DRIVES & ENTERPRISE PERMISSIONS
|
|
3463
|
+
// ==========================================
|
|
3464
|
+
/**
|
|
3465
|
+
* Lists all Google Workspace Shared Drives accessible by current user or service account
|
|
3466
|
+
*/
|
|
3467
|
+
async listSharedDrives(options = {}) {
|
|
3468
|
+
await this.init();
|
|
3469
|
+
const raw = await this.getRawClient();
|
|
3470
|
+
const res = await withRetry(async () => {
|
|
3471
|
+
return await raw.drives.list({
|
|
3472
|
+
pageSize: options.pageSize || 100,
|
|
3473
|
+
fields: "drives(id, name)"
|
|
3474
|
+
});
|
|
3475
|
+
});
|
|
3476
|
+
return (res.data.drives || []).map((d) => ({ id: d.id, name: d.name }));
|
|
3477
|
+
}
|
|
3478
|
+
/**
|
|
3479
|
+
* Creates a scoped DriveKit client locked to a specific Shared Drive
|
|
3480
|
+
*/
|
|
3481
|
+
sharedDrive(driveId) {
|
|
3482
|
+
return new _DriveKit({
|
|
3483
|
+
...this.options,
|
|
3484
|
+
rootFolderId: driveId
|
|
3485
|
+
});
|
|
3486
|
+
}
|
|
3487
|
+
/**
|
|
3488
|
+
* Grants access to a specific email with custom role and notification
|
|
3489
|
+
*/
|
|
3490
|
+
async grantAccess(pathOrId, options) {
|
|
3491
|
+
const fileId = await this.resolveId(pathOrId);
|
|
3492
|
+
const raw = await this.getRawClient();
|
|
3493
|
+
const res = await withRetry(async () => {
|
|
3494
|
+
return await raw.permissions.create({
|
|
3495
|
+
fileId,
|
|
3496
|
+
requestBody: {
|
|
3497
|
+
type: "user",
|
|
3498
|
+
role: options.role || "reader",
|
|
3499
|
+
emailAddress: options.email
|
|
3500
|
+
},
|
|
3501
|
+
sendNotificationEmail: options.notify ?? true,
|
|
3502
|
+
emailMessage: options.message,
|
|
3503
|
+
fields: "id, type, role, emailAddress, displayName",
|
|
3504
|
+
supportsAllDrives: true
|
|
3505
|
+
});
|
|
3506
|
+
});
|
|
3507
|
+
return res.data;
|
|
3508
|
+
}
|
|
3509
|
+
/**
|
|
3510
|
+
* Revokes access for a specific permission ID or email address
|
|
3511
|
+
*/
|
|
3512
|
+
async revokeAccess(pathOrId, permissionIdOrEmail) {
|
|
3513
|
+
const fileId = await this.resolveId(pathOrId);
|
|
3514
|
+
const raw = await this.getRawClient();
|
|
3515
|
+
let targetId = permissionIdOrEmail;
|
|
3516
|
+
if (permissionIdOrEmail.includes("@")) {
|
|
3517
|
+
const listRes = await this.listPermissions(fileId);
|
|
3518
|
+
const found = listRes.find((p) => p.emailAddress?.toLowerCase() === permissionIdOrEmail.toLowerCase());
|
|
3519
|
+
if (found && found.id) {
|
|
3520
|
+
targetId = found.id;
|
|
3521
|
+
}
|
|
3522
|
+
}
|
|
3523
|
+
await withRetry(async () => {
|
|
3524
|
+
return await raw.permissions.delete({
|
|
3525
|
+
fileId,
|
|
3526
|
+
permissionId: targetId,
|
|
3527
|
+
supportsAllDrives: true
|
|
3528
|
+
});
|
|
3529
|
+
});
|
|
3530
|
+
}
|
|
3531
|
+
/**
|
|
3532
|
+
* Lists all active permissions on a file or folder
|
|
3533
|
+
*/
|
|
3534
|
+
async listPermissions(pathOrId) {
|
|
3535
|
+
const fileId = await this.resolveId(pathOrId);
|
|
3536
|
+
const raw = await this.getRawClient();
|
|
3537
|
+
const res = await withRetry(async () => {
|
|
3538
|
+
return await raw.permissions.list({
|
|
3539
|
+
fileId,
|
|
3540
|
+
fields: "permissions(id, type, role, emailAddress, displayName)",
|
|
3541
|
+
supportsAllDrives: true
|
|
3542
|
+
});
|
|
3543
|
+
});
|
|
3544
|
+
return res.data.permissions || [];
|
|
3545
|
+
}
|
|
3546
|
+
/**
|
|
3547
|
+
* Starts an embedded WebDAV server to mount DriveKit directly in macOS Finder or Windows Explorer
|
|
3548
|
+
*/
|
|
3549
|
+
async serveWebDAV(options) {
|
|
3550
|
+
const { startWebDAVServer: startWebDAVServer2 } = await Promise.resolve().then(() => (init_webdav(), webdav_exports));
|
|
3551
|
+
return await startWebDAVServer2(this, options);
|
|
3552
|
+
}
|
|
2276
3553
|
/**
|
|
2277
3554
|
* Calculates local file MD5 hash for integrity and deduplication checks
|
|
2278
3555
|
*/
|
|
@@ -2287,11 +3564,18 @@ var DriveKit = class {
|
|
|
2287
3564
|
}
|
|
2288
3565
|
};
|
|
2289
3566
|
|
|
3567
|
+
// src/types.ts
|
|
3568
|
+
init_esm_shims();
|
|
3569
|
+
|
|
3570
|
+
// src/index.ts
|
|
3571
|
+
init_webdav();
|
|
3572
|
+
|
|
2290
3573
|
// src/cli/terminal-ui.ts
|
|
3574
|
+
init_esm_shims();
|
|
2291
3575
|
import readline from "readline";
|
|
2292
3576
|
import chalk from "chalk";
|
|
2293
|
-
function terminalLink(text,
|
|
2294
|
-
return `\x1B]8;;${
|
|
3577
|
+
function terminalLink(text, url2) {
|
|
3578
|
+
return `\x1B]8;;${url2}\x07${text}\x1B]8;;\x07`;
|
|
2295
3579
|
}
|
|
2296
3580
|
function renderFileRow(item, index) {
|
|
2297
3581
|
const isDir = item.mimeType === "application/vnd.google-apps.folder";
|
|
@@ -2466,14 +3750,19 @@ export {
|
|
|
2466
3750
|
GOOGLE_WORKSPACE_MIME_TYPES,
|
|
2467
3751
|
MIN_CHUNK_SIZE,
|
|
2468
3752
|
MULTIPART_THRESHOLD,
|
|
3753
|
+
MemoryMetadataCache,
|
|
2469
3754
|
PathResolver,
|
|
2470
3755
|
PluginManager,
|
|
2471
3756
|
ResumableUploader,
|
|
2472
3757
|
SmartSyncEngine,
|
|
3758
|
+
SqliteMetadataCache,
|
|
2473
3759
|
StorageCleaner,
|
|
2474
3760
|
calculateFileMd5,
|
|
3761
|
+
createAutoNamePlugin,
|
|
2475
3762
|
createDrive,
|
|
3763
|
+
createWebhookPlugin,
|
|
2476
3764
|
index_default as default,
|
|
3765
|
+
escapeXml,
|
|
2477
3766
|
formatBytes,
|
|
2478
3767
|
formatDuration,
|
|
2479
3768
|
formatSpeed,
|
|
@@ -2485,6 +3774,7 @@ export {
|
|
|
2485
3774
|
lookupMimeType,
|
|
2486
3775
|
renderFileRow,
|
|
2487
3776
|
runInteractiveExplorer,
|
|
3777
|
+
startWebDAVServer,
|
|
2488
3778
|
terminalLink,
|
|
2489
3779
|
withRetry
|
|
2490
3780
|
};
|