@d0whc3r/node-gdrive 3.4.1 → 3.5.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/LICENSE +21 -0
- package/README.md +174 -92
- package/bin/cli.js +2 -634
- package/dist/auth.d.ts +25 -0
- package/dist/config.d.ts +16 -0
- package/dist/crypto.d.ts +4 -0
- package/dist/gdrive.cjs.js +1 -1
- package/dist/gdrive.esm.mjs +812 -0
- package/dist/index.d.ts +67 -48
- package/dist/retry.d.ts +3 -0
- package/dist/types.d.ts +96 -0
- package/package.json +83 -139
- package/CHANGELOG.md +0 -10
- package/dist/gdrive.esm.js +0 -1
|
@@ -0,0 +1,812 @@
|
|
|
1
|
+
import e, * as t from "node:fs";
|
|
2
|
+
import n from "node:os";
|
|
3
|
+
import r from "node:path";
|
|
4
|
+
import { pipeline as i } from "node:stream/promises";
|
|
5
|
+
import { drive as a } from "@googleapis/drive";
|
|
6
|
+
import { ZipArchive as o } from "archiver";
|
|
7
|
+
import s from "dayjs";
|
|
8
|
+
import c from "mime-types";
|
|
9
|
+
import l from "node:crypto";
|
|
10
|
+
import u from "node:http";
|
|
11
|
+
import { styleText as d } from "node:util";
|
|
12
|
+
import { CodeChallengeMethod as f, GoogleAuth as p, OAuth2Client as m } from "google-auth-library";
|
|
13
|
+
// \0rolldown/runtime.js
|
|
14
|
+
var h = Object.create, g = Object.defineProperty, _ = Object.getOwnPropertyDescriptor, v = Object.getOwnPropertyNames, y = Object.getPrototypeOf, b = Object.prototype.hasOwnProperty, x = (e, t) => () => (t || (e((t = { exports: {} }).exports, t, t.exports), e = null), t.exports), S = (e, t, n, r) => {
|
|
15
|
+
if (t && typeof t == "object" || typeof t == "function") for (var i = v(t), a = 0, o = i.length, s; a < o; a++) s = i[a], !b.call(e, s) && s !== n && g(e, s, {
|
|
16
|
+
get: ((e) => t[e]).bind(null, s),
|
|
17
|
+
enumerable: !(r = _(t, s)) || r.enumerable
|
|
18
|
+
});
|
|
19
|
+
return e;
|
|
20
|
+
}, C = /* @__PURE__ */ ((e, t, n) => (n = e == null ? {} : h(y(e)), S(t || !e || !e.__esModule || !b.call(e, "default") ? g(n, "default", {
|
|
21
|
+
value: e,
|
|
22
|
+
enumerable: !0
|
|
23
|
+
}) : n, e)))((/* @__PURE__ */ x(((e, t, n) => {
|
|
24
|
+
(function(n, r) {
|
|
25
|
+
typeof e == "object" && t !== void 0 ? t.exports = r() : typeof define == "function" && define.amd ? define(r) : (n = typeof globalThis < "u" ? globalThis : n || self).dayjs_plugin_isSameOrBefore = r();
|
|
26
|
+
})(n, (function() {
|
|
27
|
+
return function(e, t) {
|
|
28
|
+
t.prototype.isSameOrBefore = function(e, t) {
|
|
29
|
+
return this.isSame(e, t) || this.isBefore(e, t);
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
}));
|
|
33
|
+
})))()), w = class {
|
|
34
|
+
static _tokenFile;
|
|
35
|
+
static _credentialsFile;
|
|
36
|
+
static _serviceAccountFile;
|
|
37
|
+
static _tag;
|
|
38
|
+
static get TOKEN_FILE() {
|
|
39
|
+
return this._tokenFile ?? process.env.TOKEN_FILE ?? "./secrets/token.json";
|
|
40
|
+
}
|
|
41
|
+
static set TOKEN_FILE(e) {
|
|
42
|
+
this._tokenFile = e;
|
|
43
|
+
}
|
|
44
|
+
static get CREDENTIALS_FILE() {
|
|
45
|
+
return this._credentialsFile ?? process.env.CREDENTIALS_FILE ?? "./secrets/credentials.json";
|
|
46
|
+
}
|
|
47
|
+
static set CREDENTIALS_FILE(e) {
|
|
48
|
+
this._credentialsFile = e;
|
|
49
|
+
}
|
|
50
|
+
static get SERVICE_ACCOUNT_FILE() {
|
|
51
|
+
return this._serviceAccountFile ?? process.env.SERVICE_ACCOUNT_FILE ?? process.env.GOOGLE_APPLICATION_CREDENTIALS;
|
|
52
|
+
}
|
|
53
|
+
static set SERVICE_ACCOUNT_FILE(e) {
|
|
54
|
+
this._serviceAccountFile = e;
|
|
55
|
+
}
|
|
56
|
+
static get BACKUP_ENCRYPTION_KEY() {
|
|
57
|
+
return process.env.BACKUP_ENCRYPTION_KEY || void 0;
|
|
58
|
+
}
|
|
59
|
+
static get TAG() {
|
|
60
|
+
return this._tag ?? "[node-gdrive]";
|
|
61
|
+
}
|
|
62
|
+
static set TAG(e) {
|
|
63
|
+
this._tag = e;
|
|
64
|
+
}
|
|
65
|
+
static reset() {
|
|
66
|
+
this._tokenFile = void 0, this._credentialsFile = void 0, this._serviceAccountFile = void 0, this._tag = void 0;
|
|
67
|
+
}
|
|
68
|
+
}, T = ["https://www.googleapis.com/auth/drive"], E = class {
|
|
69
|
+
ready = !0;
|
|
70
|
+
scopes;
|
|
71
|
+
tokenFile;
|
|
72
|
+
credentialsFile;
|
|
73
|
+
serviceAccountFile;
|
|
74
|
+
useADC;
|
|
75
|
+
logger;
|
|
76
|
+
_oAuth2Client;
|
|
77
|
+
_googleAuth;
|
|
78
|
+
constructor(e = {}) {
|
|
79
|
+
this.tokenFile = e.tokenFile ?? w.TOKEN_FILE, this.credentialsFile = e.credentialsFile ?? w.CREDENTIALS_FILE, this.serviceAccountFile = e.serviceAccountFile ?? w.SERVICE_ACCOUNT_FILE, this.useADC = e.useADC ?? !1, this.scopes = e.scopes ?? T, this.logger = e.logger ?? console, this.serviceAccountFile ? t.existsSync(this.serviceAccountFile) || (this.ready = !1, this.logger.error(d(["bold", "red"], `${w.TAG} ERROR: Service account file not found in ${this.serviceAccountFile}`))) : !this.useADC && !this.existsCredentials && (this.ready = !1, this.logger.error(d(["bold", "red"], `${w.TAG} ERROR: Credentials file not found in ${this.credentialsFile}`)));
|
|
80
|
+
}
|
|
81
|
+
get isServiceAccountOrADC() {
|
|
82
|
+
return !!this.serviceAccountFile || this.useADC;
|
|
83
|
+
}
|
|
84
|
+
get existsToken() {
|
|
85
|
+
return t.existsSync(this.tokenFile);
|
|
86
|
+
}
|
|
87
|
+
get existsCredentials() {
|
|
88
|
+
return t.existsSync(this.credentialsFile);
|
|
89
|
+
}
|
|
90
|
+
async initiate() {
|
|
91
|
+
if (!this.ready) {
|
|
92
|
+
let e = this.serviceAccountFile ?? this.credentialsFile;
|
|
93
|
+
throw Error(`${w.TAG} Credentials file not found in ${e}`);
|
|
94
|
+
}
|
|
95
|
+
return this.isServiceAccountOrADC ? (this.googleAuthClient(), !0) : this.existsToken ? (this.oAuth2Client(!0), !0) : this.generateAccessToken();
|
|
96
|
+
}
|
|
97
|
+
getAuthClient() {
|
|
98
|
+
return this.isServiceAccountOrADC ? this.googleAuthClient() : this.oAuth2Client(!0);
|
|
99
|
+
}
|
|
100
|
+
googleAuthClient() {
|
|
101
|
+
if (!this._googleAuth) {
|
|
102
|
+
if (this.serviceAccountFile) {
|
|
103
|
+
let e = JSON.parse(t.readFileSync(this.serviceAccountFile, "utf8"));
|
|
104
|
+
this._googleAuth = new p({
|
|
105
|
+
credentials: e,
|
|
106
|
+
scopes: this.scopes
|
|
107
|
+
});
|
|
108
|
+
} else this._googleAuth = new p({ scopes: this.scopes });
|
|
109
|
+
}
|
|
110
|
+
return this._googleAuth;
|
|
111
|
+
}
|
|
112
|
+
oAuth2Client(e = !0, n) {
|
|
113
|
+
if (!this._oAuth2Client) {
|
|
114
|
+
let r = JSON.parse(t.readFileSync(this.credentialsFile, "utf8")), i = r.installed ?? r.web;
|
|
115
|
+
if (!i) throw Error(`${w.TAG} Invalid credentials file format in ${this.credentialsFile}`);
|
|
116
|
+
let { client_secret: a, client_id: o, redirect_uris: s } = i;
|
|
117
|
+
if (this._oAuth2Client = new m(o, a, n ?? s?.[0] ?? "http://127.0.0.1"), this.attachTokenListener(this._oAuth2Client), e && this.existsToken) {
|
|
118
|
+
let e = JSON.parse(t.readFileSync(this.tokenFile, "utf8"));
|
|
119
|
+
this._oAuth2Client.setCredentials(e);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return this._oAuth2Client;
|
|
123
|
+
}
|
|
124
|
+
attachTokenListener(e) {
|
|
125
|
+
e.on("tokens", (e) => {
|
|
126
|
+
try {
|
|
127
|
+
let n = {};
|
|
128
|
+
this.existsToken && (n = JSON.parse(t.readFileSync(this.tokenFile, "utf8")));
|
|
129
|
+
let r = {
|
|
130
|
+
...n,
|
|
131
|
+
...e,
|
|
132
|
+
refresh_token: e.refresh_token ?? n.refresh_token
|
|
133
|
+
};
|
|
134
|
+
this.persistTokenSync(r);
|
|
135
|
+
} catch (e) {
|
|
136
|
+
this.logger.warn(`${w.TAG} Failed to persist refreshed token:`, e);
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
persistTokenSync(e) {
|
|
141
|
+
t.mkdirSync(r.dirname(this.tokenFile), {
|
|
142
|
+
recursive: !0,
|
|
143
|
+
mode: 448
|
|
144
|
+
}), t.writeFileSync(this.tokenFile, JSON.stringify(e, null, 2), { mode: 384 }), t.chmodSync(this.tokenFile, 384);
|
|
145
|
+
}
|
|
146
|
+
async generateAccessToken() {
|
|
147
|
+
let e = l.randomBytes(16).toString("hex"), t = l.randomBytes(32).toString("base64url"), n = l.createHash("sha256").update(t).digest("base64url");
|
|
148
|
+
return new Promise((r, i) => {
|
|
149
|
+
let a = u.createServer(), o = !1, s = (e) => {
|
|
150
|
+
o || (o = !0, a.close(), e());
|
|
151
|
+
};
|
|
152
|
+
a.on("error", (e) => {
|
|
153
|
+
s(() => i(Error(`${w.TAG} OAuth loopback server failed`, { cause: e })));
|
|
154
|
+
}), a.on("request", (n, o) => {
|
|
155
|
+
(async () => {
|
|
156
|
+
try {
|
|
157
|
+
let c = new URL(n.url ?? "/", "http://127.0.0.1");
|
|
158
|
+
if (c.pathname !== "/oauth2callback") {
|
|
159
|
+
o.writeHead(404, { "Content-Type": "text/plain" }), o.end("Not found");
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
let l = c.searchParams.get("state"), u = c.searchParams.get("code"), d = c.searchParams.get("error");
|
|
163
|
+
if (d) {
|
|
164
|
+
o.writeHead(400, { "Content-Type": "text/plain" }), o.end(`Authorization failed: ${d}`), s(() => i(/* @__PURE__ */ Error(`${w.TAG} OAuth authorization error: ${d}`)));
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
if (!l || l !== e) {
|
|
168
|
+
o.writeHead(400, { "Content-Type": "text/plain" }), o.end("Invalid OAuth state parameter"), s(() => i(/* @__PURE__ */ Error(`${w.TAG} OAuth state mismatch`)));
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
if (!u) {
|
|
172
|
+
o.writeHead(400, { "Content-Type": "text/plain" }), o.end("Missing authorization code"), s(() => i(/* @__PURE__ */ Error(`${w.TAG} Missing OAuth authorization code`)));
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
let f = `http://127.0.0.1:${a.address().port}/oauth2callback`, p = this.oAuth2Client(!1, f), { tokens: m } = await p.getToken({
|
|
176
|
+
code: u,
|
|
177
|
+
codeVerifier: t,
|
|
178
|
+
redirect_uri: f
|
|
179
|
+
});
|
|
180
|
+
p.setCredentials(m), this.persistTokenSync(m), o.writeHead(200, { "Content-Type": "text/plain" }), o.end("Authentication successful! You can close this window."), this.logger.info(`${w.TAG} Token stored to`, this.tokenFile), s(() => r(!0));
|
|
181
|
+
} catch (e) {
|
|
182
|
+
o.writeHead(500, { "Content-Type": "text/plain" }), o.end("Error exchanging OAuth authorization code."), s(() => i(e instanceof Error ? e : Error(String(e))));
|
|
183
|
+
}
|
|
184
|
+
})();
|
|
185
|
+
}), a.listen(0, "127.0.0.1", () => {
|
|
186
|
+
let t = `http://127.0.0.1:${a.address().port}/oauth2callback`, r = this.oAuth2Client(!1, t).generateAuthUrl({
|
|
187
|
+
access_type: "offline",
|
|
188
|
+
prompt: "consent",
|
|
189
|
+
scope: this.scopes,
|
|
190
|
+
redirect_uri: t,
|
|
191
|
+
state: e,
|
|
192
|
+
code_challenge: n,
|
|
193
|
+
code_challenge_method: f.S256
|
|
194
|
+
});
|
|
195
|
+
this.logger.info(`${w.TAG} Authorize this app by visiting this url:`, r);
|
|
196
|
+
});
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
}, D = Buffer.from("NGDE", "ascii"), O = 1, k = 16, A = 12, j = 16, M = 32, N = D.length + 1 + k + A;
|
|
200
|
+
function P(e, t) {
|
|
201
|
+
if (!e) throw Error("Encryption passphrase must not be empty");
|
|
202
|
+
return l.scryptSync(e, t, M);
|
|
203
|
+
}
|
|
204
|
+
function F(e, t) {
|
|
205
|
+
let n = l.randomBytes(k), r = l.randomBytes(A), i = P(t, n), a = l.createCipheriv("aes-256-gcm", i, r), o = Buffer.concat([a.update(e), a.final()]), s = a.getAuthTag();
|
|
206
|
+
return Buffer.concat([
|
|
207
|
+
D,
|
|
208
|
+
Buffer.from([O]),
|
|
209
|
+
n,
|
|
210
|
+
r,
|
|
211
|
+
o,
|
|
212
|
+
s
|
|
213
|
+
]);
|
|
214
|
+
}
|
|
215
|
+
function I(e, t) {
|
|
216
|
+
if (e.length < N + j) throw Error("Encrypted payload is too short or corrupted");
|
|
217
|
+
if (!e.subarray(0, D.length).equals(D)) throw Error("Invalid encrypted file header");
|
|
218
|
+
let n = e[D.length];
|
|
219
|
+
if (n !== O) throw Error(`Unsupported encryption format version: ${String(n)}`);
|
|
220
|
+
let r = D.length + 1, i = r + k, a = e.subarray(r, i), o = e.subarray(i, N), s = e.subarray(N, e.length - j), c = e.subarray(e.length - j), u = P(t, a), d = l.createDecipheriv("aes-256-gcm", u, o);
|
|
221
|
+
return d.setAuthTag(c), Buffer.concat([d.update(s), d.final()]);
|
|
222
|
+
}
|
|
223
|
+
async function L(t, n, a) {
|
|
224
|
+
let o = l.randomBytes(k), s = l.randomBytes(A), c = P(a, o), u = Buffer.concat([
|
|
225
|
+
D,
|
|
226
|
+
Buffer.from([O]),
|
|
227
|
+
o,
|
|
228
|
+
s
|
|
229
|
+
]);
|
|
230
|
+
e.mkdirSync(r.dirname(n), {
|
|
231
|
+
recursive: !0,
|
|
232
|
+
mode: 448
|
|
233
|
+
});
|
|
234
|
+
let d = l.createCipheriv("aes-256-gcm", c, s), f = e.createReadStream(t), p = e.createWriteStream(n, { mode: 384 });
|
|
235
|
+
try {
|
|
236
|
+
p.write(u), await i(f, d, p, { end: !1 });
|
|
237
|
+
let e = d.getAuthTag();
|
|
238
|
+
return await new Promise((t, n) => {
|
|
239
|
+
p.once("error", n), p.end(e, () => t());
|
|
240
|
+
}), n;
|
|
241
|
+
} catch (r) {
|
|
242
|
+
throw f.destroy(), p.destroy(), e.rmSync(n, { force: !0 }), Error(`Failed to encrypt file "${t}"`, { cause: r });
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
async function R(t, n, a) {
|
|
246
|
+
let o = e.statSync(t);
|
|
247
|
+
if (o.size < N + j) throw Error("Encrypted file is too short or corrupted");
|
|
248
|
+
let s = e.openSync(t, "r"), c = Buffer.alloc(N), u = Buffer.alloc(j);
|
|
249
|
+
try {
|
|
250
|
+
e.readSync(s, c, 0, N, 0), e.readSync(s, u, 0, j, o.size - j);
|
|
251
|
+
} finally {
|
|
252
|
+
e.closeSync(s);
|
|
253
|
+
}
|
|
254
|
+
if (!c.subarray(0, D.length).equals(D)) throw Error("Invalid encrypted file header");
|
|
255
|
+
let d = c[D.length];
|
|
256
|
+
if (d !== O) throw Error(`Unsupported encryption format version: ${String(d)}`);
|
|
257
|
+
let f = D.length + 1, p = f + k, m = c.subarray(f, p), h = c.subarray(p, N), g = P(a, m), _ = l.createDecipheriv("aes-256-gcm", g, h);
|
|
258
|
+
_.setAuthTag(u), e.mkdirSync(r.dirname(n), {
|
|
259
|
+
recursive: !0,
|
|
260
|
+
mode: 448
|
|
261
|
+
});
|
|
262
|
+
let v = o.size - N - j, y = e.createWriteStream(n, { mode: 384 });
|
|
263
|
+
try {
|
|
264
|
+
if (v === 0) {
|
|
265
|
+
let e = _.final();
|
|
266
|
+
await new Promise((t, n) => {
|
|
267
|
+
y.once("error", n), y.end(e, () => t());
|
|
268
|
+
});
|
|
269
|
+
} else {
|
|
270
|
+
let n = e.createReadStream(t, {
|
|
271
|
+
start: N,
|
|
272
|
+
end: o.size - j - 1
|
|
273
|
+
});
|
|
274
|
+
await i(n, _, y);
|
|
275
|
+
}
|
|
276
|
+
return n;
|
|
277
|
+
} catch (r) {
|
|
278
|
+
throw y.destroy(), e.rmSync(n, { force: !0 }), Error(`Failed to decrypt file "${t}"`, { cause: r });
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
// src/retry.ts
|
|
282
|
+
var z = /* @__PURE__ */ new Set([
|
|
283
|
+
429,
|
|
284
|
+
500,
|
|
285
|
+
502,
|
|
286
|
+
503,
|
|
287
|
+
504
|
|
288
|
+
]), B = /* @__PURE__ */ new Set([
|
|
289
|
+
"ECONNRESET",
|
|
290
|
+
"ETIMEDOUT",
|
|
291
|
+
"ENOTFOUND",
|
|
292
|
+
"EAI_AGAIN",
|
|
293
|
+
"EPIPE",
|
|
294
|
+
"UND_ERR_CONNECT_TIMEOUT"
|
|
295
|
+
]);
|
|
296
|
+
function V(e) {
|
|
297
|
+
return new Promise((t) => {
|
|
298
|
+
setTimeout(t, e);
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
function H(e) {
|
|
302
|
+
if (typeof e.status == "number") return e.status;
|
|
303
|
+
if (typeof e.code == "number") return e.code;
|
|
304
|
+
let t = e.response;
|
|
305
|
+
if (typeof t?.status == "number") return t.status;
|
|
306
|
+
}
|
|
307
|
+
function U(e) {
|
|
308
|
+
if (!e || typeof e != "object") return !1;
|
|
309
|
+
let t = e, n = H(t);
|
|
310
|
+
if (n !== void 0 && z.has(n)) return !0;
|
|
311
|
+
let r = typeof t.code == "string" ? t.code : void 0;
|
|
312
|
+
return !!(r && B.has(r));
|
|
313
|
+
}
|
|
314
|
+
async function W(e, t = {}) {
|
|
315
|
+
let { maxRetries: n = 4, baseDelayMs: r = 500, maxDelayMs: i = 16e3, jitter: a = !0, sleep: o = V } = t, s = async (t) => {
|
|
316
|
+
try {
|
|
317
|
+
return await e();
|
|
318
|
+
} catch (e) {
|
|
319
|
+
if (t >= n || !U(e)) throw e;
|
|
320
|
+
let c = Math.min(i, r * 2 ** t), l = a ? Math.round(c * (.5 + Math.random() * .5)) : c;
|
|
321
|
+
return await o(l), s(t + 1);
|
|
322
|
+
}
|
|
323
|
+
};
|
|
324
|
+
return s(0);
|
|
325
|
+
}
|
|
326
|
+
// src/types.ts
|
|
327
|
+
var G = /* @__PURE__ */ "appProperties.capabilities.contentHints.createdTime.description.explicitlyTrashed.fileExtension.folderColorRgb.fullFileExtension.hasAugmentedPermissions.hasThumbnail.headRevisionId.iconLink.id.imageMediaMetadata.isAppAuthorized.lastModifyingUser.md5Checksum.mimeType.modifiedByMe.modifiedByMeTime.modifiedTime.name.originalFilename.ownedByMe.owners.parents.properties.quotaBytesUsed.shared.sharedWithMeTime.sharingUser.size.spaces.starred.teamDriveId.thumbnailLink.thumbnailVersion.trashed.trashedTime.trashingUser.version.videoMediaMetadata.viewedByMe.viewedByMeTime.viewersCanCopyContent.webContentLink.webViewLink.writersCanShare".split(".");
|
|
328
|
+
// src/index.ts
|
|
329
|
+
s.extend(C.default);
|
|
330
|
+
var K = new Set(G), q = /^(\d+)([a-zA-Z]+)$/, J = {
|
|
331
|
+
s: "second",
|
|
332
|
+
second: "second",
|
|
333
|
+
seconds: "second",
|
|
334
|
+
m: "minute",
|
|
335
|
+
minute: "minute",
|
|
336
|
+
minutes: "minute",
|
|
337
|
+
h: "hour",
|
|
338
|
+
hour: "hour",
|
|
339
|
+
hours: "hour",
|
|
340
|
+
d: "day",
|
|
341
|
+
day: "day",
|
|
342
|
+
days: "day",
|
|
343
|
+
w: "week",
|
|
344
|
+
week: "week",
|
|
345
|
+
weeks: "week",
|
|
346
|
+
M: "month",
|
|
347
|
+
month: "month",
|
|
348
|
+
months: "month",
|
|
349
|
+
y: "year",
|
|
350
|
+
year: "year",
|
|
351
|
+
years: "year"
|
|
352
|
+
};
|
|
353
|
+
function Y(e) {
|
|
354
|
+
return e.replaceAll("\\", "\\\\").replaceAll("'", "\\'");
|
|
355
|
+
}
|
|
356
|
+
function X(e) {
|
|
357
|
+
let t = q.exec(e), n = t ? J[t[2]] : void 0;
|
|
358
|
+
if (!t || !n) throw Error(`${w.TAG} Invalid timeSpace "${e}". Expected "<number><unit>" where unit is one of: s, m, h, d, w, M, y, second(s), minute(s), hour(s), day(s), week(s), month(s), year(s).`);
|
|
359
|
+
let r = Number(t[1]);
|
|
360
|
+
if (!Number.isFinite(r) || r <= 0) throw Error(`${w.TAG} Invalid timeSpace "${e}": amount must be a positive integer.`);
|
|
361
|
+
return {
|
|
362
|
+
amount: r,
|
|
363
|
+
unit: n
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
async function Z(e, t, n) {
|
|
367
|
+
let r = Math.max(1, Math.floor(t)), i = Array.from({ length: e.length }), a = 0;
|
|
368
|
+
async function o() {
|
|
369
|
+
if (a >= e.length) return;
|
|
370
|
+
let t = a;
|
|
371
|
+
a += 1, i[t] = await n(e[t]), await o();
|
|
372
|
+
}
|
|
373
|
+
let s = Array.from({ length: Math.min(r, e.length) }, () => o());
|
|
374
|
+
return await Promise.all(s), i;
|
|
375
|
+
}
|
|
376
|
+
var Q = class {
|
|
377
|
+
DEFAULT_FIELDS = [
|
|
378
|
+
"createdTime",
|
|
379
|
+
"id",
|
|
380
|
+
"md5Checksum",
|
|
381
|
+
"mimeType",
|
|
382
|
+
"name",
|
|
383
|
+
"parents",
|
|
384
|
+
"trashed"
|
|
385
|
+
];
|
|
386
|
+
MIME_FOLDER = "application/vnd.google-apps.folder";
|
|
387
|
+
gdriveAuth;
|
|
388
|
+
injectedAuth;
|
|
389
|
+
sharedDriveId;
|
|
390
|
+
defaultDryRun;
|
|
391
|
+
defaultConcurrency;
|
|
392
|
+
defaultCompressionLevel;
|
|
393
|
+
defaultOnProgress;
|
|
394
|
+
retryOptions;
|
|
395
|
+
logger;
|
|
396
|
+
_drive;
|
|
397
|
+
_initPromise;
|
|
398
|
+
constructor(e = {}) {
|
|
399
|
+
this.logger = e.logger ?? console, this.sharedDriveId = e.sharedDriveId, this.defaultDryRun = e.dryRun ?? !1, this.defaultConcurrency = e.concurrency ?? 4, this.defaultCompressionLevel = e.compressionLevel ?? 6, this.defaultOnProgress = e.onProgress, this.retryOptions = e.retry ?? {}, e.drive && (this._drive = e.drive), e.auth && (this.injectedAuth = e.auth), !e.drive && !e.auth && (this.gdriveAuth = new E({
|
|
400
|
+
credentialsFile: e.credentialsFile,
|
|
401
|
+
tokenFile: e.tokenFile,
|
|
402
|
+
serviceAccountFile: e.serviceAccountFile,
|
|
403
|
+
useADC: e.useADC,
|
|
404
|
+
scopes: e.scopes,
|
|
405
|
+
logger: this.logger
|
|
406
|
+
}));
|
|
407
|
+
}
|
|
408
|
+
ensureInitiated() {
|
|
409
|
+
return this._drive || this.injectedAuth ? Promise.resolve(!0) : (this._initPromise ||= this.gdriveAuth.initiate().catch((e) => {
|
|
410
|
+
throw this._initPromise = void 0, e;
|
|
411
|
+
}), this._initPromise);
|
|
412
|
+
}
|
|
413
|
+
get auth() {
|
|
414
|
+
return this.injectedAuth ? this.injectedAuth : this.gdriveAuth.getAuthClient();
|
|
415
|
+
}
|
|
416
|
+
get drive() {
|
|
417
|
+
return this._drive ||= a({
|
|
418
|
+
version: "v3",
|
|
419
|
+
auth: this.auth
|
|
420
|
+
}), this._drive;
|
|
421
|
+
}
|
|
422
|
+
get sharedDriveListParams() {
|
|
423
|
+
return this.sharedDriveId ? {
|
|
424
|
+
supportsAllDrives: !0,
|
|
425
|
+
includeItemsFromAllDrives: !0,
|
|
426
|
+
corpora: "drive",
|
|
427
|
+
driveId: this.sharedDriveId
|
|
428
|
+
} : {};
|
|
429
|
+
}
|
|
430
|
+
get sharedDriveItemParams() {
|
|
431
|
+
return this.sharedDriveId ? { supportsAllDrives: !0 } : {};
|
|
432
|
+
}
|
|
433
|
+
get rootParentId() {
|
|
434
|
+
return this.sharedDriveId ?? "root";
|
|
435
|
+
}
|
|
436
|
+
isFolder(e) {
|
|
437
|
+
if (Object.hasOwn(e, "mimeType")) return e.mimeType === this.MIME_FOLDER;
|
|
438
|
+
}
|
|
439
|
+
isDeleted(e) {
|
|
440
|
+
return Object.hasOwn(e, "trashed") ? !!e.trashed : !1;
|
|
441
|
+
}
|
|
442
|
+
async listFiles(e, t = 1e3, n) {
|
|
443
|
+
await this.ensureInitiated();
|
|
444
|
+
let r;
|
|
445
|
+
if (!e) r = this.DEFAULT_FIELDS;
|
|
446
|
+
else if (e === !0) r = G;
|
|
447
|
+
else {
|
|
448
|
+
for (let t of e) if (!K.has(t)) throw Error(`${w.TAG} Invalid Drive file field: "${t}"`);
|
|
449
|
+
r = e;
|
|
450
|
+
}
|
|
451
|
+
let i = {
|
|
452
|
+
pageSize: t,
|
|
453
|
+
fields: `kind, nextPageToken, incompleteSearch, files(${r.join(", ")})`,
|
|
454
|
+
prettyPrint: !1,
|
|
455
|
+
...this.sharedDriveListParams
|
|
456
|
+
};
|
|
457
|
+
return n && (i.q = n), this.getListFiles(i);
|
|
458
|
+
}
|
|
459
|
+
async getFile(e) {
|
|
460
|
+
if (await this.ensureInitiated(), !e) throw this.genericError(/* @__PURE__ */ Error(`${w.TAG} File id not found`));
|
|
461
|
+
let t = {
|
|
462
|
+
fileId: e,
|
|
463
|
+
...this.sharedDriveItemParams
|
|
464
|
+
};
|
|
465
|
+
try {
|
|
466
|
+
let { data: e } = await W(() => this.drive.files.get(t), this.retryOptions);
|
|
467
|
+
return e;
|
|
468
|
+
} catch (e) {
|
|
469
|
+
throw this.genericError(e);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
async resolveDownloadFileId(e, t) {
|
|
473
|
+
if (t) {
|
|
474
|
+
let n = await this.findFolderId(t, !1), r = await this.findFile(e, n);
|
|
475
|
+
if (!r?.id) throw Error(`${w.TAG} File "${e}" not found in folder "${t}"`);
|
|
476
|
+
return r.id;
|
|
477
|
+
}
|
|
478
|
+
try {
|
|
479
|
+
return (await W(() => this.drive.files.get({
|
|
480
|
+
fileId: e,
|
|
481
|
+
fields: "id, name, mimeType",
|
|
482
|
+
...this.sharedDriveItemParams
|
|
483
|
+
}), this.retryOptions)).data.id ?? e;
|
|
484
|
+
} catch {
|
|
485
|
+
let t = await this.findFile(e);
|
|
486
|
+
if (!t?.id) throw Error(`${w.TAG} File "${e}" not found`);
|
|
487
|
+
return t.id;
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
async downloadFile(t, n, a = {}) {
|
|
491
|
+
if (await this.ensureInitiated(), !t) throw Error(`${w.TAG} File id or name is required for download`);
|
|
492
|
+
let o = await this.resolveDownloadFileId(t, a.folderName);
|
|
493
|
+
e.mkdirSync(r.dirname(r.resolve(n)), { recursive: !0 });
|
|
494
|
+
let s, c = n;
|
|
495
|
+
a.decryptKey && (s = this.createPrivateTempDir(), c = r.join(s, "download.enc"));
|
|
496
|
+
try {
|
|
497
|
+
let t = await W(() => this.drive.files.get({
|
|
498
|
+
fileId: o,
|
|
499
|
+
alt: "media",
|
|
500
|
+
...this.sharedDriveItemParams
|
|
501
|
+
}, { responseType: "stream" }), this.retryOptions), r = e.createWriteStream(c, { mode: a.decryptKey ? 384 : 420 });
|
|
502
|
+
return await i(t.data, r), a.decryptKey && await R(c, n, a.decryptKey), n;
|
|
503
|
+
} catch (t) {
|
|
504
|
+
throw a.decryptKey || e.rmSync(n, { force: !0 }), this.genericError(t);
|
|
505
|
+
} finally {
|
|
506
|
+
s && e.rmSync(s, {
|
|
507
|
+
recursive: !0,
|
|
508
|
+
force: !0
|
|
509
|
+
});
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
async emptyTrash() {
|
|
513
|
+
return await this.ensureInitiated(), W(() => this.drive.files.emptyTrash(), this.retryOptions);
|
|
514
|
+
}
|
|
515
|
+
async deleteFile(e) {
|
|
516
|
+
if (await this.ensureInitiated(), e.id) try {
|
|
517
|
+
let { data: t } = await W(() => this.drive.files.delete({
|
|
518
|
+
fileId: e.id,
|
|
519
|
+
...this.sharedDriveItemParams
|
|
520
|
+
}), this.retryOptions);
|
|
521
|
+
return e.name && this.logger.warn(`${w.TAG} Deleted ${e.isFolder ? "folder" : "file"}: ${e.name}`), t;
|
|
522
|
+
} catch (e) {
|
|
523
|
+
throw this.genericError(e);
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
async uploadFile(t, n, i = {}) {
|
|
527
|
+
await this.ensureInitiated();
|
|
528
|
+
let { create: a = !0, replace: o = !1, encryptKey: s } = i, l = i.dryRun ?? this.defaultDryRun, u = i.onProgress ?? this.defaultOnProgress, d = r.basename(t), f = s && !d.endsWith(".enc") ? `${d}.enc` : d, p = {
|
|
529
|
+
name: f,
|
|
530
|
+
mimeType: s ? "application/octet-stream" : c.contentType(d) || void 0
|
|
531
|
+
}, m = await this.getUploadFolderId(n || !1, a, p, l);
|
|
532
|
+
if (l) return this.logger.info(`${w.TAG} [dry-run] Would upload "${f}"${n && typeof n == "string" ? ` to "${n}"` : ""}`), this.parseFileMeta(p);
|
|
533
|
+
await this.replaceExistingFile(o, f, m);
|
|
534
|
+
let h, g = t;
|
|
535
|
+
s && (h = this.createPrivateTempDir(), g = r.join(h, f), await L(t, g, s));
|
|
536
|
+
try {
|
|
537
|
+
let t = e.statSync(g).size, { data: n } = await W(async () => {
|
|
538
|
+
let n = e.createReadStream(g);
|
|
539
|
+
n.on("error", (e) => {
|
|
540
|
+
this.logger.error(`${w.TAG} Read stream error for "${g}":`, e);
|
|
541
|
+
});
|
|
542
|
+
let r = {
|
|
543
|
+
requestBody: p,
|
|
544
|
+
media: { body: n },
|
|
545
|
+
fields: `kind, ${this.DEFAULT_FIELDS.join(", ")}`,
|
|
546
|
+
...this.sharedDriveItemParams
|
|
547
|
+
}, i = (e) => {
|
|
548
|
+
let n = t === 0 ? 100 : Math.min(100, e.bytesRead / t * 100);
|
|
549
|
+
u?.({
|
|
550
|
+
fileName: f,
|
|
551
|
+
bytesRead: e.bytesRead,
|
|
552
|
+
totalBytes: t,
|
|
553
|
+
percentage: n
|
|
554
|
+
}), n >= 100 && this.logger.warn(`${w.TAG} Upload ${f}: ${Math.round(n)}% complete`);
|
|
555
|
+
};
|
|
556
|
+
try {
|
|
557
|
+
return await this.drive.files.create(r, { onUploadProgress: i });
|
|
558
|
+
} finally {
|
|
559
|
+
n.destroy();
|
|
560
|
+
}
|
|
561
|
+
}, this.retryOptions);
|
|
562
|
+
return this.parseFileMeta(n);
|
|
563
|
+
} catch (e) {
|
|
564
|
+
throw this.genericError(e);
|
|
565
|
+
} finally {
|
|
566
|
+
h && e.rmSync(h, {
|
|
567
|
+
recursive: !0,
|
|
568
|
+
force: !0
|
|
569
|
+
});
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
async uploadStream(t, n, a, o = {}) {
|
|
573
|
+
await this.ensureInitiated();
|
|
574
|
+
let s = this.sanitizeFilename(n), c = this.createPrivateTempDir(), l = r.join(c, s);
|
|
575
|
+
try {
|
|
576
|
+
let n = e.createWriteStream(l, { mode: 384 });
|
|
577
|
+
return await i(t, n), await this.uploadFile(l, a, o);
|
|
578
|
+
} finally {
|
|
579
|
+
e.rmSync(c, {
|
|
580
|
+
recursive: !0,
|
|
581
|
+
force: !0
|
|
582
|
+
});
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
async uploadFiles(t, n, i = {}) {
|
|
586
|
+
await this.ensureInitiated();
|
|
587
|
+
let { compress: a, replace: o, create: c, dryRun: l, encryptKey: u, onProgress: d, exclude: f, followSymlinks: p = !1 } = i, m = i.concurrency ?? this.defaultConcurrency, h = i.compressionLevel ?? this.defaultCompressionLevel, g = Array.isArray(t) ? t : [t], _ = this.expandFileInputs(g, {
|
|
588
|
+
exclude: f,
|
|
589
|
+
followSymlinks: p
|
|
590
|
+
}), v, y = _;
|
|
591
|
+
try {
|
|
592
|
+
if (a) {
|
|
593
|
+
let e = typeof a == "string" ? a : `zipped_${s().format("YYYY-MM-DD.HHmmss")}.zip`, { zipPath: t, tempDir: n } = await this.compressFiles(_, e, {
|
|
594
|
+
compressionLevel: h,
|
|
595
|
+
followSymlinks: p
|
|
596
|
+
});
|
|
597
|
+
v = n, y = [t];
|
|
598
|
+
}
|
|
599
|
+
n && typeof n == "string" && y.length > 0 && !(l ?? this.defaultDryRun) && await this.findFolderId(n, c ?? !0);
|
|
600
|
+
let e = {};
|
|
601
|
+
return await Z(y, m, async (t) => {
|
|
602
|
+
let i = await this.uploadFile(t, n, {
|
|
603
|
+
replace: o,
|
|
604
|
+
create: c,
|
|
605
|
+
dryRun: l,
|
|
606
|
+
encryptKey: u,
|
|
607
|
+
onProgress: d
|
|
608
|
+
}), a = i.name || r.basename(t);
|
|
609
|
+
e[a] = i;
|
|
610
|
+
}), e;
|
|
611
|
+
} finally {
|
|
612
|
+
v && e.rmSync(v, {
|
|
613
|
+
recursive: !0,
|
|
614
|
+
force: !0
|
|
615
|
+
});
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
async cleanOlder(e, t, n = {}) {
|
|
619
|
+
let { amount: r, unit: i } = X(e);
|
|
620
|
+
await this.ensureInitiated();
|
|
621
|
+
let a = "";
|
|
622
|
+
return t && (a = await this.findFolderId(t, !1)), this.deleteOlder(r, i, a, n);
|
|
623
|
+
}
|
|
624
|
+
expandFileInputs(t, n) {
|
|
625
|
+
let { exclude: i = [], followSymlinks: a = !1 } = n, o = [], s = (t) => {
|
|
626
|
+
if (t.includes("*")) {
|
|
627
|
+
let n = e.globSync(t, { exclude: i });
|
|
628
|
+
for (let e of n) s(e);
|
|
629
|
+
return;
|
|
630
|
+
}
|
|
631
|
+
if (i.some((e) => r.matchesGlob(t, e) || r.matchesGlob(r.basename(t), e))) return;
|
|
632
|
+
let n = e.lstatSync(t);
|
|
633
|
+
if (n.isSymbolicLink() && !a) this.logger.warn(`${w.TAG} Skipping symlink: ${t}`);
|
|
634
|
+
else if ((n.isSymbolicLink() ? e.statSync(t) : n).isDirectory()) {
|
|
635
|
+
let n = e.readdirSync(t).map((e) => r.join(t, e));
|
|
636
|
+
for (let e of n) s(e);
|
|
637
|
+
} else o.push(t);
|
|
638
|
+
};
|
|
639
|
+
for (let e of t) s(e);
|
|
640
|
+
return o;
|
|
641
|
+
}
|
|
642
|
+
async getListFiles(e) {
|
|
643
|
+
let t = [], n = async (r) => {
|
|
644
|
+
let i = r ? {
|
|
645
|
+
...e,
|
|
646
|
+
pageToken: r
|
|
647
|
+
} : { ...e }, { data: a } = await W(() => this.drive.files.list(i), this.retryOptions);
|
|
648
|
+
a.files?.length && t.push(...a.files), a.nextPageToken && await n(a.nextPageToken);
|
|
649
|
+
};
|
|
650
|
+
try {
|
|
651
|
+
return await n(), this.parseFilesMeta(t);
|
|
652
|
+
} catch (e) {
|
|
653
|
+
throw this.genericError(e);
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
async replaceExistingFile(e, t, n) {
|
|
657
|
+
let r = await this.findFile(t, n);
|
|
658
|
+
if (r) {
|
|
659
|
+
if (!e) throw Error(`${w.TAG} File "${t}" already exists and will not be replaced`);
|
|
660
|
+
this.logger.warn(`${w.TAG} File "${t}" already exists and will be deleted before upload`), await this.deleteFile(r);
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
async getUploadFolderId(e, t, n, r = !1) {
|
|
664
|
+
if (e && typeof e == "string") {
|
|
665
|
+
let i = await this.findFolderId(e, t && !r);
|
|
666
|
+
return n.parents = [i], i;
|
|
667
|
+
}
|
|
668
|
+
return this.sharedDriveId && (n.parents = [this.sharedDriveId]), "";
|
|
669
|
+
}
|
|
670
|
+
async deleteOlder(e, t, n, r = {}) {
|
|
671
|
+
let i = r.dryRun ?? this.defaultDryRun, a = Math.max(0, r.keepLast ?? 0), o = r.concurrency ?? this.defaultConcurrency, c = s().subtract(e, t), l = [`mimeType != '${this.MIME_FOLDER}'`, "trashed = false"];
|
|
672
|
+
n && l.push(`'${Y(n)}' in parents`), a === 0 && l.push(`createdTime <= '${c.toISOString()}'`);
|
|
673
|
+
let u = (await this.listFiles(void 0, 1e3, l.join(" and "))).filter((e) => !e.isDeleted && !e.isFolder).filter((e) => !n || !!e.parents?.includes(n)).sort((e, t) => {
|
|
674
|
+
let n = e.createdTime ? s(e.createdTime).valueOf() : 0;
|
|
675
|
+
return (t.createdTime ? s(t.createdTime).valueOf() : 0) - n;
|
|
676
|
+
}), d = (a > 0 ? u.slice(a) : u).filter((e) => e.createdTime && s(e.createdTime).isSameOrBefore(c));
|
|
677
|
+
if (i) {
|
|
678
|
+
for (let e of d) this.logger.info(`${w.TAG} [dry-run] Would delete file: ${e.name ?? e.id ?? "unknown"}`);
|
|
679
|
+
return d;
|
|
680
|
+
}
|
|
681
|
+
return await Z(d, o, async (e) => {
|
|
682
|
+
await this.deleteFile(e);
|
|
683
|
+
}), d;
|
|
684
|
+
}
|
|
685
|
+
parseFileMeta(e) {
|
|
686
|
+
return {
|
|
687
|
+
...e,
|
|
688
|
+
isDeleted: this.isDeleted(e),
|
|
689
|
+
isFolder: !!this.isFolder(e)
|
|
690
|
+
};
|
|
691
|
+
}
|
|
692
|
+
parseFilesMeta(e) {
|
|
693
|
+
return e.map((e) => this.parseFileMeta(e));
|
|
694
|
+
}
|
|
695
|
+
genericError(e) {
|
|
696
|
+
return this.logger.error(`${w.TAG} The API returned an error: ${String(e)}`), e;
|
|
697
|
+
}
|
|
698
|
+
inFlightFolders = /* @__PURE__ */ new Map();
|
|
699
|
+
findFolderId(e, t = !1) {
|
|
700
|
+
let n = `${e}::${t}`, r = this.inFlightFolders.get(n);
|
|
701
|
+
if (r) return r;
|
|
702
|
+
let i = this.resolveFolderId(e, t).finally(() => {
|
|
703
|
+
this.inFlightFolders.delete(n);
|
|
704
|
+
});
|
|
705
|
+
return this.inFlightFolders.set(n, i), i;
|
|
706
|
+
}
|
|
707
|
+
async resolveFolderId(e, t = !1) {
|
|
708
|
+
let n = e.split("/").map((e) => e.trim()).filter(Boolean);
|
|
709
|
+
if (n.length === 0) throw Error(`${w.TAG} Invalid folder path "${e}"`);
|
|
710
|
+
return this.resolveFolderSegments(n, 0, this.rootParentId, t, e);
|
|
711
|
+
}
|
|
712
|
+
async resolveFolderSegments(e, t, n, r, i) {
|
|
713
|
+
if (t >= e.length) return n;
|
|
714
|
+
let a = e[t], o = [
|
|
715
|
+
`name = '${Y(a)}'`,
|
|
716
|
+
`mimeType = '${this.MIME_FOLDER}'`,
|
|
717
|
+
"trashed = false",
|
|
718
|
+
`'${Y(n)}' in parents`
|
|
719
|
+
].join(" and "), s = (await this.listFiles(void 0, 100, o)).find((e) => e.isFolder && !e.isDeleted && e.name === a && e.id), c;
|
|
720
|
+
if (s?.id) c = s.id;
|
|
721
|
+
else if (r) {
|
|
722
|
+
let e = await this.createFolder(a, n);
|
|
723
|
+
if (!e.id) throw Error(`${w.TAG} Failed to create folder "${a}"`);
|
|
724
|
+
c = e.id;
|
|
725
|
+
} else throw Error(`${w.TAG} Folder "${i}" does not exist and will not be created`);
|
|
726
|
+
return this.resolveFolderSegments(e, t + 1, c, r, i);
|
|
727
|
+
}
|
|
728
|
+
async findFile(e, t) {
|
|
729
|
+
let n = t || this.rootParentId, r = [
|
|
730
|
+
`name = '${Y(e)}'`,
|
|
731
|
+
`mimeType != '${this.MIME_FOLDER}'`,
|
|
732
|
+
"trashed = false",
|
|
733
|
+
`'${Y(n)}' in parents`
|
|
734
|
+
].join(" and ");
|
|
735
|
+
return (await this.listFiles(void 0, 100, r)).find((n) => !n.isFolder && !n.isDeleted && n.name === e && (!t || !!n.parents?.includes(t))) ?? null;
|
|
736
|
+
}
|
|
737
|
+
async createFolder(e, t) {
|
|
738
|
+
let n = {
|
|
739
|
+
name: e,
|
|
740
|
+
mimeType: this.MIME_FOLDER
|
|
741
|
+
};
|
|
742
|
+
t && t !== "root" && (n.parents = [t]);
|
|
743
|
+
try {
|
|
744
|
+
let { data: t } = await W(() => this.drive.files.create({
|
|
745
|
+
requestBody: n,
|
|
746
|
+
fields: "id",
|
|
747
|
+
...this.sharedDriveItemParams
|
|
748
|
+
}), this.retryOptions);
|
|
749
|
+
return t?.id && this.logger.warn(`${w.TAG} Created folder "${e}" with id: "${t.id}"`), t;
|
|
750
|
+
} catch (e) {
|
|
751
|
+
throw this.genericError(e);
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
createPrivateTempDir() {
|
|
755
|
+
let t = e.mkdtempSync(r.join(n.tmpdir(), "node-gdrive-"));
|
|
756
|
+
return e.chmodSync(t, 448), t;
|
|
757
|
+
}
|
|
758
|
+
sanitizeFilename(e) {
|
|
759
|
+
let t = r.basename(e);
|
|
760
|
+
if (!t || t === "." || t === "..") throw Error(`${w.TAG} Invalid output filename: "${e}"`);
|
|
761
|
+
return t;
|
|
762
|
+
}
|
|
763
|
+
compressFiles(t, n, i = {}) {
|
|
764
|
+
let a = this.sanitizeFilename(n), s = this.createPrivateTempDir(), c = r.join(s, a), l = i.compressionLevel ?? this.defaultCompressionLevel, u = i.followSymlinks ?? !1;
|
|
765
|
+
return new Promise((n, i) => {
|
|
766
|
+
let a = e.createWriteStream(c, { mode: 384 }), d = [], f = !1, p = (t) => {
|
|
767
|
+
if (!f) {
|
|
768
|
+
f = !0;
|
|
769
|
+
for (let e of d) e.destroy();
|
|
770
|
+
a.destroy(), e.rmSync(s, {
|
|
771
|
+
recursive: !0,
|
|
772
|
+
force: !0
|
|
773
|
+
}), i(t instanceof Error ? t : Error(String(t)));
|
|
774
|
+
}
|
|
775
|
+
}, m = new o({ zlib: { level: l } });
|
|
776
|
+
a.on("error", (e) => {
|
|
777
|
+
p(e);
|
|
778
|
+
}), a.on("close", () => {
|
|
779
|
+
f || (f = !0, n({
|
|
780
|
+
zipPath: c,
|
|
781
|
+
tempDir: s
|
|
782
|
+
}));
|
|
783
|
+
}), m.on("warning", (e) => {
|
|
784
|
+
this.logger.warn(`${w.TAG} Warning compressing file`, e), e.code !== "ENOENT" && p(e);
|
|
785
|
+
}), m.on("error", (e) => {
|
|
786
|
+
this.logger.error(`${w.TAG} Error compressing file`, e), p(e);
|
|
787
|
+
}), m.pipe(a);
|
|
788
|
+
try {
|
|
789
|
+
for (let n of t) {
|
|
790
|
+
let t = e.lstatSync(n);
|
|
791
|
+
if (t.isSymbolicLink() && !u) this.logger.warn(`${w.TAG} Skipping symlink: ${n}`);
|
|
792
|
+
else if ((t.isSymbolicLink() ? e.statSync(n) : t).isDirectory()) m.directory(n, r.basename(n));
|
|
793
|
+
else {
|
|
794
|
+
let t = r.basename(n), i = e.createReadStream(n);
|
|
795
|
+
i.on("error", (e) => {
|
|
796
|
+
p(e);
|
|
797
|
+
}), m.append(i, { name: t }), d.push(i);
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
} catch (e) {
|
|
801
|
+
p(e);
|
|
802
|
+
return;
|
|
803
|
+
}
|
|
804
|
+
m.finalize().catch((e) => {
|
|
805
|
+
p(e);
|
|
806
|
+
}).finally(() => {
|
|
807
|
+
for (let e of d) e.destroy();
|
|
808
|
+
});
|
|
809
|
+
});
|
|
810
|
+
}
|
|
811
|
+
};
|
|
812
|
+
export { E as Auth, w as Config, Q as GDrive, G as allFileTypes, I as decryptBuffer, R as decryptFile, F as encryptBuffer, L as encryptFile, Y as escapeDriveQuery, U as isRetryableError, X as parseTimeSpace, W as withRetry };
|