@d0whc3r/node-gdrive 3.5.1 → 3.6.0

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/README.md CHANGED
@@ -25,6 +25,13 @@ docker run --rm \
25
25
  -v "$PWD/secrets:/app/secrets:ro" \
26
26
  -v "$PWD/data:/data:ro" \
27
27
  d0whc3r/gdrive -b /data -z backup.zip -f backups/daily -c -r
28
+
29
+ # Back up PostgreSQL / MySQL / MariaDB / MongoDB using the :db image variant
30
+ # (includes pg_dump, mariadb-dump, and mongodump; SQLite works in both images)
31
+ docker run --rm \
32
+ -v "$PWD/secrets:/app/secrets:ro" \
33
+ -e DATABASE_URL="postgresql://user:pass@host:5432/mydb" \
34
+ d0whc3r/gdrive:db --db postgres -f backups/pg -c --encrypt
28
35
  ```
29
36
 
30
37
  ### 2. npx / npm (Node.js >= 26)
@@ -70,6 +77,52 @@ GOOGLE_APPLICATION_CREDENTIALS=./secrets/service-account.json \
70
77
 
71
78
  ---
72
79
 
80
+ ## Database Backups
81
+
82
+ `node-gdrive` supports native backups for **PostgreSQL**, **MySQL / MariaDB**, **MongoDB**, and **SQLite** without piping through `--stdin`.
83
+
84
+ | Engine | CLI Flag / Aliases | Underlying Method | Mode | Docker Image |
85
+ | ------------------- | ------------------------------------ | --------------------------------------------------------------------------- | ------------------------------------------- | ----------------------------------------------- |
86
+ | **PostgreSQL** | `--db postgres` (`pg`, `postgresql`) | `pg_dump` (`plain`, `custom`, `tar`) | Direct stream (`O(1)` RAM, zero temp disk) | `d0whc3r/gdrive:db` |
87
+ | **MySQL / MariaDB** | `--db mysql` (`mariadb`, `-m`) | `mysqldump` / `mariadb-dump` (auto-fallback to pure-JS `mysqldump`) | Direct stream (or temp file on JS fallback) | `d0whc3r/gdrive:db` _(or slim via JS fallback)_ |
88
+ | **MongoDB** | `--db mongodb` (`mongo`) | `mongodump --archive` | Direct stream (`O(1)` RAM, zero temp disk) | `d0whc3r/gdrive:db` |
89
+ | **SQLite** | `--db sqlite` (`sqlite3`) | Node.js built-in `node:sqlite` online backup (WAL-safe, zero external deps) | Temp file (`0600`, auto-cleaned) | `d0whc3r/gdrive:latest` & `:db` |
90
+
91
+ > **Streaming & Compression:** Without `-z`/`--zip`, PostgreSQL, MySQL/MariaDB, and MongoDB stream directly into Google Drive (and optional `--encrypt` AES-256-GCM) with zero temp disk space. Adding `-z` compresses the dump into a ZIP archive in a `0700` temp directory before uploading.
92
+ >
93
+ > **Credential Safety:** Passwords are never passed as CLI arguments (`ps`-safe). They are injected via `PGPASSWORD`, `MYSQL_PWD`, or a temporary `0600` `mongodump --config` file that is removed immediately after the dump finishes.
94
+
95
+ ### Engine Examples
96
+
97
+ ```bash
98
+ # PostgreSQL using standard PG* environment variables
99
+ PGHOST=db.internal PGUSER=postgres PGPASSWORD=secret PGDATABASE=app \
100
+ node-gdrive --db postgres -f backups/pg -c --encrypt
101
+
102
+ # PostgreSQL custom binary format (.dump) via connection URI (auto-detects engine)
103
+ node-gdrive --db-url "postgresql://postgres:secret@db.internal:5432/app?sslmode=require" \
104
+ --db-format custom -f backups/pg -c --encrypt
105
+
106
+ # MySQL / MariaDB (via --db mysql, --db mariadb, -m, or URI)
107
+ node-gdrive --db-url "mariadb://root:secret@127.0.0.1:3306/shop" -f backups/mysql -c
108
+
109
+ # MongoDB single-file archive via MONGODB_URI or --db-url
110
+ MONGODB_URI="mongodb+srv://user:secret@cluster.example.com/orders" \
111
+ node-gdrive --db mongodb -f backups/mongo -c --encrypt
112
+
113
+ # SQLite online backup (safe while the database is in active WAL use)
114
+ node-gdrive --db sqlite --db-url "sqlite:///var/data/app.sqlite" -z -f backups/sqlite -c
115
+
116
+ # Docker (:db variant bundles pg_dump, mariadb-dump, and mongodump)
117
+ docker run --rm \
118
+ -v "$PWD/secrets:/app/secrets:ro" \
119
+ -e DATABASE_URL="postgresql://postgres:secret@host.docker.internal:5432/app" \
120
+ -e BACKUP_ENCRYPTION_KEY="my-strong-passphrase" \
121
+ d0whc3r/gdrive:db --db postgres -f backups/pg -c --encrypt
122
+ ```
123
+
124
+ ---
125
+
73
126
  ## Common Usage Examples
74
127
 
75
128
  ```bash
@@ -88,29 +141,36 @@ BACKUP_ENCRYPTION_KEY="my-strong-passphrase" \
88
141
  BACKUP_ENCRYPTION_KEY="my-strong-passphrase" \
89
142
  node-gdrive --download backup.zip.enc -f backups -o ./backup.zip --encrypt
90
143
 
91
- # Pipe a PostgreSQL dump directly to Google Drive without writing to disk
92
- pg_dump mydb | node-gdrive --stdin --name mydb.sql -f backups/pg -c
144
+ # Native database backups (PostgreSQL, MySQL/MariaDB, MongoDB, SQLite)
145
+ node-gdrive --db postgres -f backups/pg -c --encrypt
146
+ node-gdrive --db-url "postgresql://user:pass@host:5432/mydb" --db-format custom -f backups/pg -c
147
+ node-gdrive --db-url "mongodb+srv://user:pass@cluster/mydb" -f backups/mongo -c --encrypt
148
+ node-gdrive --db sqlite --db-url "sqlite:///var/data/app.sqlite" -z -f backups/sqlite -c
93
149
 
94
150
  # Preview retention cleanup safely before deleting anything
95
151
  node-gdrive -f backups/daily -d 30d --keep-last 5 --dry-run
96
152
 
97
- # Nightly cron job: MySQL dump + zip + encrypt + prune older than 14 days (keep at least 5)
98
- node-gdrive -m -z -f backups/mysql -c --encrypt && \
99
- node-gdrive -f backups/mysql -d 14d --keep-last 5
153
+ # Nightly cron job: PostgreSQL dump + encrypt + prune older than 14 days (keep at least 5)
154
+ node-gdrive --db postgres -f backups/pg -c --encrypt && \
155
+ node-gdrive -f backups/pg -d 14d --keep-last 5
100
156
  ```
101
157
 
102
158
  ---
103
159
 
104
160
  ## Environment Variables
105
161
 
106
- | Variable | Description | Default |
107
- | ---------------------------------------------------------------------------- | --------------------------------------------------- | ---------------------------- |
108
- | `GOOGLE_APPLICATION_CREDENTIALS` | Path to Service Account JSON key (standard GCP var) | — |
109
- | `SERVICE_ACCOUNT_FILE` | Alias for Service Account JSON key path | — |
110
- | `CREDENTIALS_FILE` | Path to OAuth2 Desktop `credentials.json` | `./secrets/credentials.json` |
111
- | `TOKEN_FILE` | Path to stored OAuth2 `token.json` (`0600`) | `./secrets/token.json` |
112
- | `BACKUP_ENCRYPTION_KEY` | Passphrase for `--encrypt` (AES-256-GCM) | — |
113
- | `MYSQL_HOST`, `MYSQL_PORT`, `MYSQL_USER`, `MYSQL_PASSWORD`, `MYSQL_DATABASE` | MySQL connection for `--mysql` | `localhost:3306` |
162
+ | Variable | Description | Default |
163
+ | ------------------------------------------------------------------------------------------- | --------------------------------------------------------- | ---------------------------- |
164
+ | `GOOGLE_APPLICATION_CREDENTIALS` | Path to Service Account JSON key (standard GCP var) | — |
165
+ | `SERVICE_ACCOUNT_FILE` | Alias for Service Account JSON key path | — |
166
+ | `CREDENTIALS_FILE` | Path to OAuth2 Desktop `credentials.json` | `./secrets/credentials.json` |
167
+ | `TOKEN_FILE` | Path to stored OAuth2 `token.json` (`0600`) | `./secrets/token.json` |
168
+ | `BACKUP_ENCRYPTION_KEY` | Passphrase for `--encrypt` (AES-256-GCM) | — |
169
+ | `DATABASE_URL` | Connection URI (auto-detects Postgres/MySQL/Mongo/SQLite) | — |
170
+ | `PGHOST`, `PGPORT`, `PGUSER`, `PGPASSWORD`, `PGDATABASE`, `PGSSLMODE` | PostgreSQL connection for `--db postgres` | `localhost:5432` |
171
+ | `MYSQL_HOST`, `MYSQL_PORT`, `MYSQL_USER`, `MYSQL_PASSWORD`, `MYSQL_DATABASE` | MySQL / MariaDB connection for `--db mysql` / `--mysql` | `localhost:3306` |
172
+ | `MONGODB_URI`, `MONGO_HOST`, `MONGO_PORT`, `MONGO_USER`, `MONGO_PASSWORD`, `MONGO_DATABASE` | MongoDB connection for `--db mongodb` | `localhost:27017` |
173
+ | `SQLITE_PATH` | SQLite database file path for `--db sqlite` | — |
114
174
 
115
175
  See [example.env](./example.env) for a ready-to-copy template.
116
176
 
@@ -135,7 +195,10 @@ See [example.env](./example.env) for a ready-to-copy template.
135
195
  | `--encrypt` | — | Encrypt on upload / decrypt on download using `$BACKUP_ENCRYPTION_KEY` |
136
196
  | `--stdin` | — | Read upload payload from standard input (requires `--name`) |
137
197
  | `--name <filename>` | — | Filename when uploading from `--stdin` |
138
- | `--mysql` | `-m` | Create and upload a MySQL dump using `$MYSQL_*` env vars |
198
+ | `--db <engine>` | — | Native DB backup: `postgres`, `mysql` (`mariadb`), `mongodb`, `sqlite` |
199
+ | `--db-url <uri>` | — | Database connection URI (auto-detects engine from scheme) |
200
+ | `--db-format <fmt>` | — | PostgreSQL dump format: `plain` (`.sql`), `custom` (`.dump`), `tar` |
201
+ | `--mysql` | `-m` | Alias for `--db mysql` |
139
202
  | `--drive-id <id>` | — | Target a Google Workspace Shared Drive |
140
203
  | `--service-account <path>` | — | Path to a Service Account JSON key |
141
204
  | `--json` | — | Output machine-readable JSON (ideal for CI/scripts) |
@@ -174,7 +237,7 @@ npm install @d0whc3r/node-gdrive
174
237
  ### ESM / TypeScript
175
238
 
176
239
  ```ts
177
- import { GDrive } from '@d0whc3r/node-gdrive';
240
+ import { dumpDatabase, GDrive } from '@d0whc3r/node-gdrive';
178
241
 
179
242
  const gdrive = new GDrive({
180
243
  serviceAccountFile: './secrets/service-account.json',
@@ -197,6 +260,29 @@ await gdrive.downloadFile('daily.zip.enc', './restore/daily.zip', {
197
260
  decryptKey: process.env.BACKUP_ENCRYPTION_KEY
198
261
  });
199
262
 
263
+ // Stream a PostgreSQL dump directly to Google Drive with client-side encryption
264
+ const dump = await dumpDatabase({
265
+ url: process.env.DATABASE_URL,
266
+ format: 'custom'
267
+ });
268
+ try {
269
+ if (dump.kind === 'stream') {
270
+ await gdrive.uploadStream(dump.stream, dump.filename, 'backups/pg', {
271
+ create: true,
272
+ encryptKey: process.env.BACKUP_ENCRYPTION_KEY,
273
+ mimeType: dump.mimeType
274
+ });
275
+ await dump.wait();
276
+ } else {
277
+ await gdrive.uploadFile(dump.filePath, 'backups/pg', {
278
+ create: true,
279
+ encryptKey: process.env.BACKUP_ENCRYPTION_KEY
280
+ });
281
+ }
282
+ } finally {
283
+ await dump.cleanup();
284
+ }
285
+
200
286
  // Delete files older than 14 days while keeping at least the 5 newest
201
287
  await gdrive.cleanOlder('14d', 'backups/daily', { keepLast: 5 });
202
288
  ```
package/bin/cli.js CHANGED
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
- var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,o)=>(o=n==null?{}:e(i(n)),s(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));let l=require("node:util"),u=require("command-line-args");u=c(u);let d=require("command-line-usage");d=c(d);let f=require("node:fs");f=c(f);let p=require("node:os");p=c(p);let m=require("node:path");m=c(m);let h=require("dayjs");h=c(h);let g=require("mysqldump");g=c(g);let _=require("node:stream/promises"),v=require("@googleapis/drive"),y=require("archiver"),b=require("mime-types");b=c(b);let x=require("node:crypto");x=c(x);let S=require("node:http");S=c(S);let C=require("google-auth-library");var w={name:`@d0whc3r/node-gdrive`,version:`3.5.0`,keywords:[`backup`,`compress`,`copy`,`drive`,`gdrive`,`google`,`googleapi`,`node`,`upload`],license:`MIT`,author:{name:`d0whc3r`,email:`d0whc3r@gmail.com`,url:`https://github.com/d0whc3r`},repository:{type:`git`,url:`https://github.com/d0whc3r/node-gdrive.git`},bin:{"node-gdrive":`./bin/cli.js`},files:[`dist`,`bin`],main:`dist/gdrive.cjs.js`,module:`dist/gdrive.esm.mjs`,types:`dist/index.d.ts`,exports:{".":{types:`./dist/index.d.ts`,import:`./dist/gdrive.esm.mjs`,require:`./dist/gdrive.cjs.js`}},publishConfig:{access:`public`,registry:`https://registry.npmjs.org`},scripts:{clean:`node -e "import('node:fs').then(fs => ['dist','bin','build','coverage','node-gdrive','node-gdrive.exe'].forEach(p => fs.rmSync(p, {recursive:true,force:true})))"`,"cli:dev":`node --env-file=.env cli/cli.ts`,cli:`node cli/cli.ts`,typecheck:`tsc --noEmit`,"build:clean":`node -e "import('node:fs').then(fs => ['dist','bin'].forEach(p => fs.rmSync(p, {recursive:true,force:true})))"`,"build:lib":`vite build --config vite.config.mts`,"build:cli":`vite build --config vite.cli.config.mts`,"build:dts":`tsc -p tsconfig.build.json --emitDeclarationOnly`,"build:base":`pnpm build:clean && pnpm build:lib && pnpm build:cli && pnpm build:dts`,"build:sea":`vite build --config vite.sea.config.mts && node scripts/build-sea.mjs`,build:`pnpm build:base && pnpm build:sea`,test:`vitest run`,"test:unit":`vitest run --exclude tests/gdrive.integration.spec.ts`,"test:integration":`vitest run tests/gdrive.integration.spec.ts`,"test:watch":`vitest`,"test:coverage":`vitest run --coverage`,lint:`oxlint`,"lint:fix":`oxlint --fix`,format:`oxfmt --write`,"format:check":`oxfmt --check`,prepare:`husky`,"semantic-release":`semantic-release`},dependencies:{"@googleapis/drive":`^27.1.0`,archiver:`^8.0.0`,"command-line-args":`^6.0.2`,"command-line-usage":`^7.0.4`,dayjs:`^1.11.23`,"google-auth-library":`^11.3.4`,"mime-types":`^3.0.2`,mysqldump:`^3.2.0`},devDependencies:{"@commitlint/cli":`^21.2.4`,"@commitlint/config-conventional":`^21.2.4`,"@semantic-release/changelog":`^7.0.0`,"@semantic-release/commit-analyzer":`^13.0.1`,"@semantic-release/git":`^11.0.1`,"@semantic-release/github":`^12.0.11`,"@semantic-release/npm":`^13.2.0`,"@semantic-release/release-notes-generator":`^14.1.1`,"@types/archiver":`^8.0.0`,"@types/command-line-args":`^5.2.3`,"@types/command-line-usage":`^5.0.4`,"@types/mime-types":`^3.0.1`,"@types/node":`^26.6.10`,"@vitest/coverage-v8":`^5.1.2`,husky:`^9.1.7`,"lint-staged":`^17.6.2`,oxfmt:`^0.80.0`,oxlint:`^1.95.0`,"semantic-release":`^26.0.1`,typescript:`^7.0.2`,vite:`^8.3.8`,vitest:`^5.1.2`},"lint-staged":{"{src,cli,tests}/**/*.ts":[`pnpm lint:fix`,`pnpm format`]},engines:{node:`>=26.0.0`},packageManager:`pnpm@12.16.1`},T=[{name:`list`,alias:`l`,multiple:!1,type:Boolean,description:`List all files and folders`},{name:`backup`,alias:`b`,typeLabel:`{underline file*}`,defaultOption:!0,multiple:!0,type:String,description:`Backup files, directories, or globs`},{name:`download`,typeLabel:`{underline fileId|name}`,multiple:!1,type:String,description:`Download/restore a file from Google Drive`},{name:`output`,alias:`o`,typeLabel:`{underline path}`,multiple:!1,type:String,description:`Local destination path for --download`},{name:`zip`,alias:`z`,typeLabel:`{underline zipname.zip}`,multiple:!1,type:String,description:`Zip backup files before uploading`},{name:`replace`,alias:`r`,multiple:!1,type:Boolean,description:`Replace files if already exists when uploading`},{name:`create`,alias:`c`,multiple:!1,type:Boolean,description:`Create destination upload folder if missing`},{name:`folder`,alias:`f`,typeLabel:`{underline foldername}`,multiple:!1,type:String,description:`Destination or target folder path (supports nested paths like a/b/c)`},{name:`delete`,alias:`d`,typeLabel:`{underline folder=duration} OR {underline duration}`,multiple:!0,type:String,description:`Clean files older than duration (e.g. 7d, 1M, 30m)`},{name:`keep-last`,typeLabel:`{underline N}`,multiple:!1,type:Number,description:`Always keep the newest N files when cleaning older files`},{name:`mysql`,alias:`m`,multiple:!1,type:Boolean,description:`MySQL backup using environment variables ($MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE, $MYSQL_HOST, $MYSQL_PORT)`},{name:`stdin`,multiple:!1,type:Boolean,description:`Read upload content from stdin (requires --name)`},{name:`name`,typeLabel:`{underline filename}`,multiple:!1,type:String,description:`Target filename when uploading from --stdin`},{name:`encrypt`,multiple:!1,type:Boolean,description:`Encrypt uploads / decrypt downloads with AES-256-GCM using $BACKUP_ENCRYPTION_KEY`},{name:`exclude`,typeLabel:`{underline glob}`,multiple:!0,type:String,description:`Exclude glob pattern(s) when backing up files`},{name:`dry-run`,multiple:!1,type:Boolean,description:`Preview uploads or deletions without modifying Google Drive`},{name:`drive-id`,typeLabel:`{underline id}`,multiple:!1,type:String,description:`Google Shared Drive ID`},{name:`service-account`,typeLabel:`{underline path}`,multiple:!1,type:String,description:`Path to Google Service Account JSON key file`},{name:`json`,multiple:!1,type:Boolean,description:`Output command results as JSON`},{name:`quiet`,alias:`q`,multiple:!1,type:Boolean,description:`Suppress non-essential log output`},{name:`version`,alias:`v`,multiple:!1,type:Boolean,description:`Print version number`},{name:`help`,alias:`h`,description:`Print this usage guide`,type:Boolean}];function E(){return w.version}function D(){let e=`node-gdrive`,t=[{header:`Help for ${e} v${w.version}`,content:`Usage of {italic ${e}} in command line.`},{header:`Options`,optionList:T},{header:`Examples`,content:[{desc:`1. List files (or JSON output).`,example:`$ ${e} -l --json`},{desc:`2. Backup multiple files to nested folder.`,example:`$ ${e} -b src/index.ts -b images/logo.png -f backups/app -c`},{desc:`3. Backup files as encrypted zip excluding logs.`,example:`$ BACKUP_ENCRYPTION_KEY=secret ${e} -b ./data/* --exclude "*.log" -z backup.zip -f backups -c -r --encrypt`},{desc:`4. Stream stdin directly to Google Drive.`,example:`$ pg_dump mydb | ${e} --stdin --name mydb.sql -f backups/pg -c`},{desc:`5. Download and decrypt a backup.`,example:`$ BACKUP_ENCRYPTION_KEY=secret ${e} --download backup.zip.enc -f backups -o ./backup.zip --encrypt`},{desc:`6. Clean files older than 7 days while keeping the 5 newest (dry run).`,example:`$ ${e} -f backups -d 7d --keep-last 5 --dry-run`},{desc:`7. Generate MySQL dump, zip, and upload to "mysql-backup" folder.`,example:`$ ${e} -f mysql-backup -m -z -c`}]}];return(0,d.default)(t)}function O(e){let t=(0,u.default)(T,e?{argv:e}:void 0);if(t[`keep-last`]!==void 0){let e=t[`keep-last`];if(!Number.isInteger(e)||e<0)throw Error(`Invalid --keep-last value "${String(e)}": expected a non-negative integer.`)}if(t.stdin&&!t.name)throw Error(`Option --stdin requires --name <filename>.`);return t}var k=c(o(((e,t,n)=>{(function(n,r){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()})(n,(function(){"use strict";return function(e,t){t.prototype.isSameOrBefore=function(e,t){return this.isSame(e,t)||this.isBefore(e,t)}}}))}))()),A=class{static _tokenFile;static _credentialsFile;static _serviceAccountFile;static _tag;static get TOKEN_FILE(){return this._tokenFile??process.env.TOKEN_FILE??`./secrets/token.json`}static set TOKEN_FILE(e){this._tokenFile=e}static get CREDENTIALS_FILE(){return this._credentialsFile??process.env.CREDENTIALS_FILE??`./secrets/credentials.json`}static set CREDENTIALS_FILE(e){this._credentialsFile=e}static get SERVICE_ACCOUNT_FILE(){return this._serviceAccountFile??process.env.SERVICE_ACCOUNT_FILE??process.env.GOOGLE_APPLICATION_CREDENTIALS}static set SERVICE_ACCOUNT_FILE(e){this._serviceAccountFile=e}static get BACKUP_ENCRYPTION_KEY(){return process.env.BACKUP_ENCRYPTION_KEY||void 0}static get TAG(){return this._tag??`[node-gdrive]`}static set TAG(e){this._tag=e}static reset(){this._tokenFile=void 0,this._credentialsFile=void 0,this._serviceAccountFile=void 0,this._tag=void 0}},ee=[`https://www.googleapis.com/auth/drive`],j=class{ready=!0;scopes;tokenFile;credentialsFile;serviceAccountFile;useADC;logger;_oAuth2Client;_googleAuth;constructor(e={}){this.tokenFile=e.tokenFile??A.TOKEN_FILE,this.credentialsFile=e.credentialsFile??A.CREDENTIALS_FILE,this.serviceAccountFile=e.serviceAccountFile??A.SERVICE_ACCOUNT_FILE,this.useADC=e.useADC??!1,this.scopes=e.scopes??ee,this.logger=e.logger??console,this.serviceAccountFile?f.existsSync(this.serviceAccountFile)||(this.ready=!1,this.logger.error((0,l.styleText)([`bold`,`red`],`${A.TAG} ERROR: Service account file not found in ${this.serviceAccountFile}`))):!this.useADC&&!this.existsCredentials&&(this.ready=!1,this.logger.error((0,l.styleText)([`bold`,`red`],`${A.TAG} ERROR: Credentials file not found in ${this.credentialsFile}`)))}get isServiceAccountOrADC(){return!!this.serviceAccountFile||this.useADC}get existsToken(){return f.existsSync(this.tokenFile)}get existsCredentials(){return f.existsSync(this.credentialsFile)}async initiate(){if(!this.ready){let e=this.serviceAccountFile??this.credentialsFile;throw Error(`${A.TAG} Credentials file not found in ${e}`)}return this.isServiceAccountOrADC?(this.googleAuthClient(),!0):this.existsToken?(this.oAuth2Client(!0),!0):this.generateAccessToken()}getAuthClient(){return this.isServiceAccountOrADC?this.googleAuthClient():this.oAuth2Client(!0)}googleAuthClient(){if(!this._googleAuth){if(this.serviceAccountFile){let e=JSON.parse(f.readFileSync(this.serviceAccountFile,`utf8`));this._googleAuth=new C.GoogleAuth({credentials:e,scopes:this.scopes})}else this._googleAuth=new C.GoogleAuth({scopes:this.scopes})}return this._googleAuth}oAuth2Client(e=!0,t){if(!this._oAuth2Client){let n=JSON.parse(f.readFileSync(this.credentialsFile,`utf8`)),r=n.installed??n.web;if(!r)throw Error(`${A.TAG} Invalid credentials file format in ${this.credentialsFile}`);let{client_secret:i,client_id:a,redirect_uris:o}=r;if(this._oAuth2Client=new C.OAuth2Client(a,i,t??o?.[0]??`http://127.0.0.1`),this.attachTokenListener(this._oAuth2Client),e&&this.existsToken){let e=JSON.parse(f.readFileSync(this.tokenFile,`utf8`));this._oAuth2Client.setCredentials(e)}}return this._oAuth2Client}attachTokenListener(e){e.on(`tokens`,e=>{try{let t={};this.existsToken&&(t=JSON.parse(f.readFileSync(this.tokenFile,`utf8`)));let n={...t,...e,refresh_token:e.refresh_token??t.refresh_token};this.persistTokenSync(n)}catch(e){this.logger.warn(`${A.TAG} Failed to persist refreshed token:`,e)}})}persistTokenSync(e){f.mkdirSync(m.default.dirname(this.tokenFile),{recursive:!0,mode:448}),f.writeFileSync(this.tokenFile,JSON.stringify(e,null,2),{mode:384}),f.chmodSync(this.tokenFile,384)}async generateAccessToken(){let e=x.default.randomBytes(16).toString(`hex`),t=x.default.randomBytes(32).toString(`base64url`),n=x.default.createHash(`sha256`).update(t).digest(`base64url`);return new Promise((r,i)=>{let a=S.default.createServer(),o=!1,s=e=>{o||(o=!0,a.close(),e())};a.on(`error`,e=>{s(()=>i(Error(`${A.TAG} OAuth loopback server failed`,{cause:e})))}),a.on(`request`,(n,o)=>{(async()=>{try{let c=new URL(n.url??`/`,`http://127.0.0.1`);if(c.pathname!==`/oauth2callback`){o.writeHead(404,{"Content-Type":`text/plain`}),o.end(`Not found`);return}let l=c.searchParams.get(`state`),u=c.searchParams.get(`code`),d=c.searchParams.get(`error`);if(d){o.writeHead(400,{"Content-Type":`text/plain`}),o.end(`Authorization failed: ${d}`),s(()=>i(Error(`${A.TAG} OAuth authorization error: ${d}`)));return}if(!l||l!==e){o.writeHead(400,{"Content-Type":`text/plain`}),o.end(`Invalid OAuth state parameter`),s(()=>i(Error(`${A.TAG} OAuth state mismatch`)));return}if(!u){o.writeHead(400,{"Content-Type":`text/plain`}),o.end(`Missing authorization code`),s(()=>i(Error(`${A.TAG} Missing OAuth authorization code`)));return}let f=`http://127.0.0.1:${a.address().port}/oauth2callback`,p=this.oAuth2Client(!1,f),{tokens:m}=await p.getToken({code:u,codeVerifier:t,redirect_uri:f});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(`${A.TAG} Token stored to`,this.tokenFile),s(()=>r(!0))}catch(e){o.writeHead(500,{"Content-Type":`text/plain`}),o.end(`Error exchanging OAuth authorization code.`),s(()=>i(e instanceof Error?e:Error(String(e))))}})()}),a.listen(0,`127.0.0.1`,()=>{let t=`http://127.0.0.1:${a.address().port}/oauth2callback`,r=this.oAuth2Client(!1,t).generateAuthUrl({access_type:`offline`,prompt:`consent`,scope:this.scopes,redirect_uri:t,state:e,code_challenge:n,code_challenge_method:C.CodeChallengeMethod.S256});this.logger.info(`${A.TAG} Authorize this app by visiting this url:`,r)})})}},M=Buffer.from(`NGDE`,`ascii`),N=1,P=16,F=12,I=16,L=32,R=M.length+1+P+F;function z(e,t){if(!e)throw Error(`Encryption passphrase must not be empty`);return x.default.scryptSync(e,t,L)}async function B(e,t,n){let r=x.default.randomBytes(P),i=x.default.randomBytes(F),a=z(n,r),o=Buffer.concat([M,Buffer.from([N]),r,i]);f.default.mkdirSync(m.default.dirname(t),{recursive:!0,mode:448});let s=x.default.createCipheriv(`aes-256-gcm`,a,i),c=f.default.createReadStream(e),l=f.default.createWriteStream(t,{mode:384});try{l.write(o),await(0,_.pipeline)(c,s,l,{end:!1});let e=s.getAuthTag();return await new Promise((t,n)=>{l.once(`error`,n),l.end(e,()=>t())}),t}catch(n){throw c.destroy(),l.destroy(),f.default.rmSync(t,{force:!0}),Error(`Failed to encrypt file "${e}"`,{cause:n})}}async function V(e,t,n){let r=f.default.statSync(e);if(r.size<R+I)throw Error(`Encrypted file is too short or corrupted`);let i=f.default.openSync(e,`r`),a=Buffer.alloc(R),o=Buffer.alloc(I);try{f.default.readSync(i,a,0,R,0),f.default.readSync(i,o,0,I,r.size-I)}finally{f.default.closeSync(i)}if(!a.subarray(0,M.length).equals(M))throw Error(`Invalid encrypted file header`);let s=a[M.length];if(s!==N)throw Error(`Unsupported encryption format version: ${String(s)}`);let c=M.length+1,l=c+P,u=a.subarray(c,l),d=a.subarray(l,R),p=z(n,u),h=x.default.createDecipheriv(`aes-256-gcm`,p,d);h.setAuthTag(o),f.default.mkdirSync(m.default.dirname(t),{recursive:!0,mode:448});let g=r.size-R-I,v=f.default.createWriteStream(t,{mode:384});try{if(g===0){let e=h.final();await new Promise((t,n)=>{v.once(`error`,n),v.end(e,()=>t())})}else{let t=f.default.createReadStream(e,{start:R,end:r.size-I-1});await(0,_.pipeline)(t,h,v)}return t}catch(n){throw v.destroy(),f.default.rmSync(t,{force:!0}),Error(`Failed to decrypt file "${e}"`,{cause:n})}}var H=new Set([429,500,502,503,504]),U=new Set([`ECONNRESET`,`ETIMEDOUT`,`ENOTFOUND`,`EAI_AGAIN`,`EPIPE`,`UND_ERR_CONNECT_TIMEOUT`]);function W(e){return new Promise(t=>{setTimeout(t,e)})}function G(e){if(typeof e.status==`number`)return e.status;if(typeof e.code==`number`)return e.code;let t=e.response;if(typeof t?.status==`number`)return t.status}function K(e){if(!e||typeof e!=`object`)return!1;let t=e,n=G(t);if(n!==void 0&&H.has(n))return!0;let r=typeof t.code==`string`?t.code:void 0;return!!(r&&U.has(r))}async function q(e,t={}){let{maxRetries:n=4,baseDelayMs:r=500,maxDelayMs:i=16e3,jitter:a=!0,sleep:o=W}=t,s=async t=>{try{return await e()}catch(e){if(t>=n||!K(e))throw e;let c=Math.min(i,r*2**t),l=a?Math.round(c*(.5+Math.random()*.5)):c;return await o(l),s(t+1)}};return s(0)}var J=`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(`.`);h.default.extend(k.default);var Y=new Set(J),X=/^(\d+)([a-zA-Z]+)$/,Z={s:`second`,second:`second`,seconds:`second`,m:`minute`,minute:`minute`,minutes:`minute`,h:`hour`,hour:`hour`,hours:`hour`,d:`day`,day:`day`,days:`day`,w:`week`,week:`week`,weeks:`week`,M:`month`,month:`month`,months:`month`,y:`year`,year:`year`,years:`year`};function Q(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`'`,`\\'`)}function te(e){let t=X.exec(e),n=t?Z[t[2]]:void 0;if(!t||!n)throw Error(`${A.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).`);let r=Number(t[1]);if(!Number.isFinite(r)||r<=0)throw Error(`${A.TAG} Invalid timeSpace "${e}": amount must be a positive integer.`);return{amount:r,unit:n}}async function $(e,t,n){let r=Math.max(1,Math.floor(t)),i=Array.from({length:e.length}),a=0;async function o(){if(a>=e.length)return;let t=a;a+=1,i[t]=await n(e[t]),await o()}let s=Array.from({length:Math.min(r,e.length)},()=>o());return await Promise.all(s),i}var ne=class{DEFAULT_FIELDS=[`createdTime`,`id`,`md5Checksum`,`mimeType`,`name`,`parents`,`trashed`];MIME_FOLDER=`application/vnd.google-apps.folder`;gdriveAuth;injectedAuth;sharedDriveId;defaultDryRun;defaultConcurrency;defaultCompressionLevel;defaultOnProgress;retryOptions;logger;_drive;_initPromise;constructor(e={}){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 j({credentialsFile:e.credentialsFile,tokenFile:e.tokenFile,serviceAccountFile:e.serviceAccountFile,useADC:e.useADC,scopes:e.scopes,logger:this.logger}))}ensureInitiated(){return this._drive||this.injectedAuth?Promise.resolve(!0):(this._initPromise||=this.gdriveAuth.initiate().catch(e=>{throw this._initPromise=void 0,e}),this._initPromise)}get auth(){return this.injectedAuth?this.injectedAuth:this.gdriveAuth.getAuthClient()}get drive(){return this._drive||=(0,v.drive)({version:`v3`,auth:this.auth}),this._drive}get sharedDriveListParams(){return this.sharedDriveId?{supportsAllDrives:!0,includeItemsFromAllDrives:!0,corpora:`drive`,driveId:this.sharedDriveId}:{}}get sharedDriveItemParams(){return this.sharedDriveId?{supportsAllDrives:!0}:{}}get rootParentId(){return this.sharedDriveId??`root`}isFolder(e){if(Object.hasOwn(e,`mimeType`))return e.mimeType===this.MIME_FOLDER}isDeleted(e){return Object.hasOwn(e,`trashed`)?!!e.trashed:!1}async listFiles(e,t=1e3,n){await this.ensureInitiated();let r;if(!e)r=this.DEFAULT_FIELDS;else if(e===!0)r=J;else{for(let t of e)if(!Y.has(t))throw Error(`${A.TAG} Invalid Drive file field: "${t}"`);r=e}let i={pageSize:t,fields:`kind, nextPageToken, incompleteSearch, files(${r.join(`, `)})`,prettyPrint:!1,...this.sharedDriveListParams};return n&&(i.q=n),this.getListFiles(i)}async getFile(e){if(await this.ensureInitiated(),!e)throw this.genericError(Error(`${A.TAG} File id not found`));let t={fileId:e,...this.sharedDriveItemParams};try{let{data:e}=await q(()=>this.drive.files.get(t),this.retryOptions);return e}catch(e){throw this.genericError(e)}}async resolveDownloadFileId(e,t){if(t){let n=await this.findFolderId(t,!1),r=await this.findFile(e,n);if(!r?.id)throw Error(`${A.TAG} File "${e}" not found in folder "${t}"`);return r.id}try{return(await q(()=>this.drive.files.get({fileId:e,fields:`id, name, mimeType`,...this.sharedDriveItemParams}),this.retryOptions)).data.id??e}catch{let t=await this.findFile(e);if(!t?.id)throw Error(`${A.TAG} File "${e}" not found`);return t.id}}async downloadFile(e,t,n={}){if(await this.ensureInitiated(),!e)throw Error(`${A.TAG} File id or name is required for download`);let r=await this.resolveDownloadFileId(e,n.folderName);f.default.mkdirSync(m.default.dirname(m.default.resolve(t)),{recursive:!0});let i,a=t;n.decryptKey&&(i=this.createPrivateTempDir(),a=m.default.join(i,`download.enc`));try{let e=await q(()=>this.drive.files.get({fileId:r,alt:`media`,...this.sharedDriveItemParams},{responseType:`stream`}),this.retryOptions),i=f.default.createWriteStream(a,{mode:n.decryptKey?384:420});return await(0,_.pipeline)(e.data,i),n.decryptKey&&await V(a,t,n.decryptKey),t}catch(e){throw n.decryptKey||f.default.rmSync(t,{force:!0}),this.genericError(e)}finally{i&&f.default.rmSync(i,{recursive:!0,force:!0})}}async emptyTrash(){return await this.ensureInitiated(),q(()=>this.drive.files.emptyTrash(),this.retryOptions)}async deleteFile(e){if(await this.ensureInitiated(),e.id)try{let{data:t}=await q(()=>this.drive.files.delete({fileId:e.id,...this.sharedDriveItemParams}),this.retryOptions);return e.name&&this.logger.warn(`${A.TAG} Deleted ${e.isFolder?`folder`:`file`}: ${e.name}`),t}catch(e){throw this.genericError(e)}}async uploadFile(e,t,n={}){await this.ensureInitiated();let{create:r=!0,replace:i=!1,encryptKey:a}=n,o=n.dryRun??this.defaultDryRun,s=n.onProgress??this.defaultOnProgress,c=m.default.basename(e),l=a&&!c.endsWith(`.enc`)?`${c}.enc`:c,u={name:l,mimeType:a?`application/octet-stream`:b.default.contentType(c)||void 0},d=await this.getUploadFolderId(t||!1,r,u,o);if(o)return this.logger.info(`${A.TAG} [dry-run] Would upload "${l}"${t&&typeof t==`string`?` to "${t}"`:``}`),this.parseFileMeta(u);await this.replaceExistingFile(i,l,d);let p,h=e;a&&(p=this.createPrivateTempDir(),h=m.default.join(p,l),await B(e,h,a));try{let e=f.default.statSync(h).size,{data:t}=await q(async()=>{let t=f.default.createReadStream(h);t.on(`error`,e=>{this.logger.error(`${A.TAG} Read stream error for "${h}":`,e)});let n={requestBody:u,media:{body:t},fields:`kind, ${this.DEFAULT_FIELDS.join(`, `)}`,...this.sharedDriveItemParams},r=t=>{let n=e===0?100:Math.min(100,t.bytesRead/e*100);s?.({fileName:l,bytesRead:t.bytesRead,totalBytes:e,percentage:n}),n>=100&&this.logger.warn(`${A.TAG} Upload ${l}: ${Math.round(n)}% complete`)};try{return await this.drive.files.create(n,{onUploadProgress:r})}finally{t.destroy()}},this.retryOptions);return this.parseFileMeta(t)}catch(e){throw this.genericError(e)}finally{p&&f.default.rmSync(p,{recursive:!0,force:!0})}}async uploadStream(e,t,n,r={}){await this.ensureInitiated();let i=this.sanitizeFilename(t),a=this.createPrivateTempDir(),o=m.default.join(a,i);try{let t=f.default.createWriteStream(o,{mode:384});return await(0,_.pipeline)(e,t),await this.uploadFile(o,n,r)}finally{f.default.rmSync(a,{recursive:!0,force:!0})}}async uploadFiles(e,t,n={}){await this.ensureInitiated();let{compress:r,replace:i,create:a,dryRun:o,encryptKey:s,onProgress:c,exclude:l,followSymlinks:u=!1}=n,d=n.concurrency??this.defaultConcurrency,p=n.compressionLevel??this.defaultCompressionLevel,g=Array.isArray(e)?e:[e],_=this.expandFileInputs(g,{exclude:l,followSymlinks:u}),v,y=_;try{if(r){let e=typeof r==`string`?r:`zipped_${(0,h.default)().format(`YYYY-MM-DD.HHmmss`)}.zip`,{zipPath:t,tempDir:n}=await this.compressFiles(_,e,{compressionLevel:p,followSymlinks:u});v=n,y=[t]}t&&typeof t==`string`&&y.length>0&&!(o??this.defaultDryRun)&&await this.findFolderId(t,a??!0);let e={};return await $(y,d,async n=>{let r=await this.uploadFile(n,t,{replace:i,create:a,dryRun:o,encryptKey:s,onProgress:c}),l=r.name||m.default.basename(n);e[l]=r}),e}finally{v&&f.default.rmSync(v,{recursive:!0,force:!0})}}async cleanOlder(e,t,n={}){let{amount:r,unit:i}=te(e);await this.ensureInitiated();let a=``;return t&&(a=await this.findFolderId(t,!1)),this.deleteOlder(r,i,a,n)}expandFileInputs(e,t){let{exclude:n=[],followSymlinks:r=!1}=t,i=[],a=e=>{if(e.includes(`*`)){let t=f.default.globSync(e,{exclude:n});for(let e of t)a(e);return}if(n.some(t=>m.default.matchesGlob(e,t)||m.default.matchesGlob(m.default.basename(e),t)))return;let t=f.default.lstatSync(e);if(t.isSymbolicLink()&&!r)this.logger.warn(`${A.TAG} Skipping symlink: ${e}`);else if((t.isSymbolicLink()?f.default.statSync(e):t).isDirectory()){let t=f.default.readdirSync(e).map(t=>m.default.join(e,t));for(let e of t)a(e)}else i.push(e)};for(let t of e)a(t);return i}async getListFiles(e){let t=[],n=async r=>{let i=r?{...e,pageToken:r}:{...e},{data:a}=await q(()=>this.drive.files.list(i),this.retryOptions);a.files?.length&&t.push(...a.files),a.nextPageToken&&await n(a.nextPageToken)};try{return await n(),this.parseFilesMeta(t)}catch(e){throw this.genericError(e)}}async replaceExistingFile(e,t,n){let r=await this.findFile(t,n);if(r){if(!e)throw Error(`${A.TAG} File "${t}" already exists and will not be replaced`);this.logger.warn(`${A.TAG} File "${t}" already exists and will be deleted before upload`),await this.deleteFile(r)}}async getUploadFolderId(e,t,n,r=!1){if(e&&typeof e==`string`){let i=await this.findFolderId(e,t&&!r);return n.parents=[i],i}return this.sharedDriveId&&(n.parents=[this.sharedDriveId]),``}async deleteOlder(e,t,n,r={}){let i=r.dryRun??this.defaultDryRun,a=Math.max(0,r.keepLast??0),o=r.concurrency??this.defaultConcurrency,s=(0,h.default)().subtract(e,t),c=[`mimeType != '${this.MIME_FOLDER}'`,`trashed = false`];n&&c.push(`'${Q(n)}' in parents`),a===0&&c.push(`createdTime <= '${s.toISOString()}'`);let l=(await this.listFiles(void 0,1e3,c.join(` and `))).filter(e=>!e.isDeleted&&!e.isFolder).filter(e=>!n||!!e.parents?.includes(n)).sort((e,t)=>{let n=e.createdTime?(0,h.default)(e.createdTime).valueOf():0;return(t.createdTime?(0,h.default)(t.createdTime).valueOf():0)-n}),u=(a>0?l.slice(a):l).filter(e=>e.createdTime&&(0,h.default)(e.createdTime).isSameOrBefore(s));if(i){for(let e of u)this.logger.info(`${A.TAG} [dry-run] Would delete file: ${e.name??e.id??`unknown`}`);return u}return await $(u,o,async e=>{await this.deleteFile(e)}),u}parseFileMeta(e){return{...e,isDeleted:this.isDeleted(e),isFolder:!!this.isFolder(e)}}parseFilesMeta(e){return e.map(e=>this.parseFileMeta(e))}genericError(e){return this.logger.error(`${A.TAG} The API returned an error: ${String(e)}`),e}inFlightFolders=new Map;findFolderId(e,t=!1){let n=`${e}::${t}`,r=this.inFlightFolders.get(n);if(r)return r;let i=this.resolveFolderId(e,t).finally(()=>{this.inFlightFolders.delete(n)});return this.inFlightFolders.set(n,i),i}async resolveFolderId(e,t=!1){let n=e.split(`/`).map(e=>e.trim()).filter(Boolean);if(n.length===0)throw Error(`${A.TAG} Invalid folder path "${e}"`);return this.resolveFolderSegments(n,0,this.rootParentId,t,e)}async resolveFolderSegments(e,t,n,r,i){if(t>=e.length)return n;let a=e[t],o=[`name = '${Q(a)}'`,`mimeType = '${this.MIME_FOLDER}'`,`trashed = false`,`'${Q(n)}' in parents`].join(` and `),s=(await this.listFiles(void 0,100,o)).find(e=>e.isFolder&&!e.isDeleted&&e.name===a&&e.id),c;if(s?.id)c=s.id;else if(r){let e=await this.createFolder(a,n);if(!e.id)throw Error(`${A.TAG} Failed to create folder "${a}"`);c=e.id}else throw Error(`${A.TAG} Folder "${i}" does not exist and will not be created`);return this.resolveFolderSegments(e,t+1,c,r,i)}async findFile(e,t){let n=t||this.rootParentId,r=[`name = '${Q(e)}'`,`mimeType != '${this.MIME_FOLDER}'`,`trashed = false`,`'${Q(n)}' in parents`].join(` and `);return(await this.listFiles(void 0,100,r)).find(n=>!n.isFolder&&!n.isDeleted&&n.name===e&&(!t||!!n.parents?.includes(t)))??null}async createFolder(e,t){let n={name:e,mimeType:this.MIME_FOLDER};t&&t!==`root`&&(n.parents=[t]);try{let{data:t}=await q(()=>this.drive.files.create({requestBody:n,fields:`id`,...this.sharedDriveItemParams}),this.retryOptions);return t?.id&&this.logger.warn(`${A.TAG} Created folder "${e}" with id: "${t.id}"`),t}catch(e){throw this.genericError(e)}}createPrivateTempDir(){let e=f.default.mkdtempSync(m.default.join(p.default.tmpdir(),`node-gdrive-`));return f.default.chmodSync(e,448),e}sanitizeFilename(e){let t=m.default.basename(e);if(!t||t===`.`||t===`..`)throw Error(`${A.TAG} Invalid output filename: "${e}"`);return t}compressFiles(e,t,n={}){let r=this.sanitizeFilename(t),i=this.createPrivateTempDir(),a=m.default.join(i,r),o=n.compressionLevel??this.defaultCompressionLevel,s=n.followSymlinks??!1;return new Promise((t,n)=>{let r=f.default.createWriteStream(a,{mode:384}),c=[],l=!1,u=e=>{if(!l){l=!0;for(let e of c)e.destroy();r.destroy(),f.default.rmSync(i,{recursive:!0,force:!0}),n(e instanceof Error?e:Error(String(e)))}},d=new y.ZipArchive({zlib:{level:o}});r.on(`error`,e=>{u(e)}),r.on(`close`,()=>{l||(l=!0,t({zipPath:a,tempDir:i}))}),d.on(`warning`,e=>{this.logger.warn(`${A.TAG} Warning compressing file`,e),e.code!==`ENOENT`&&u(e)}),d.on(`error`,e=>{this.logger.error(`${A.TAG} Error compressing file`,e),u(e)}),d.pipe(r);try{for(let t of e){let e=f.default.lstatSync(t);if(e.isSymbolicLink()&&!s)this.logger.warn(`${A.TAG} Skipping symlink: ${t}`);else if((e.isSymbolicLink()?f.default.statSync(t):e).isDirectory())d.directory(t,m.default.basename(t));else{let e=m.default.basename(t),n=f.default.createReadStream(t);n.on(`error`,e=>{u(e)}),d.append(n,{name:e}),c.push(n)}}}catch(e){u(e);return}d.finalize().catch(e=>{u(e)}).finally(()=>{for(let e of c)e.destroy()})})}};function re(e){return e?{info:()=>{},warn:()=>{},error:(...e)=>console.error(...e)}:console}var ie=class{opts;logger;gdrive;constructor(e,t,n){this.opts=e;let r=!!(e.quiet||e.json);this.logger=n??re(r),this.gdrive=t??new ne({sharedDriveId:e[`drive-id`],serviceAccountFile:e[`service-account`],dryRun:e[`dry-run`],logger:this.logger})}getEncryptionKey(){if(!this.opts.encrypt)return;let e=A.BACKUP_ENCRYPTION_KEY;if(!e)throw Error(`${A.TAG} --encrypt requires BACKUP_ENCRYPTION_KEY environment variable to be set.`);return e}async parseOptions(e=process.stdin){if(this.opts.version){console.info(E());return}if(this.opts.help||Object.keys(this.opts).length===0){console.info(D());return}let t=this.opts.zip,n=this.opts.folder,r=this.opts.replace,i=this.opts.create,a=this.opts[`dry-run`],o=this.opts.exclude;this.opts.list&&await this.showList(),this.opts.backup&&await this.backup(this.opts.backup,{zip:t,folder:n,replace:r,create:i,dryRun:a,exclude:o}),this.opts.stdin&&await this.uploadFromStdin(e,this.opts.name,{folder:n,replace:r,create:i,dryRun:a}),this.opts.download&&await this.download(this.opts.download,this.opts.output,n),this.opts.delete&&await this.delete(this.opts.delete,n,{dryRun:a,keepLast:this.opts[`keep-last`]}),this.opts.mysql&&await this.dumpMysql({zip:t,folder:n,replace:r,create:i,dryRun:a})}async showList(){let e=(await this.gdrive.listFiles()).filter(e=>!e.isDeleted);return this.opts.json?(console.info(JSON.stringify(e,null,2)),e):(e.length?(this.logger.info(`${A.TAG} File list: ${e.length}`),this.beautifulFiles(e)):this.logger.info(`${A.TAG} No files found.`),e)}async delete(e,t,n={}){let r=(Array.isArray(e)?e:[e]).map(e=>{let n=this.parseDelete(e);return{folder:n.folder??t??void 0,timeSpace:n.timeSpace}}),i=(await Promise.all(r.map(e=>this.gdrive.cleanOlder(e.timeSpace,e.folder,{dryRun:n.dryRun,keepLast:n.keepLast})))).flat();return this.opts.json&&console.info(JSON.stringify(i,null,2)),i}async backup(e,t){let{zip:n,folder:r,replace:i,create:a,dryRun:o,exclude:s}=t,c=this.getEncryptionKey(),l=Array.isArray(e)?e:[e],u=await this.gdrive.uploadFiles(l,r||!1,{compress:n||n===null,replace:i,create:a,dryRun:o,encryptKey:c,exclude:s});return this.opts.json&&console.info(JSON.stringify(u,null,2)),u}async uploadFromStdin(e,t,n){let r=this.getEncryptionKey(),i=await this.gdrive.uploadStream(e,t,n.folder||!1,{replace:n.replace,create:n.create,dryRun:n.dryRun,encryptKey:r});return this.opts.json&&console.info(JSON.stringify(i,null,2)),i}async download(e,t,n){let r=this.getEncryptionKey(),i=r&&e.endsWith(`.enc`)?e.slice(0,-4):m.default.basename(e),a=t??i,o=await this.gdrive.downloadFile(e,a,{decryptKey:r,folderName:n});return this.opts.json?console.info(JSON.stringify({downloaded:o},null,2)):this.logger.info(`${A.TAG} Downloaded to ${o}`),o}async dumpMysql(e){let{dumpPath:t,tempDir:n}=await this.createDumpFile();try{return await this.backup(t,e)}finally{f.default.rmSync(n,{recursive:!0,force:!0})}}parseDelete(e){let t=e.lastIndexOf(`=`);return t>0?{folder:e.slice(0,t),timeSpace:e.slice(t+1)}:{folder:null,timeSpace:e}}beautifulFiles(e){let t=new Map;for(let n of e)n.id&&n.name&&t.set(n.id,n.name);let n=e.map(e=>{let n=e.parents?.[0];return{...e,parentFolder:n?t.get(n):void 0}});n.sort((e,t)=>{if(e.isFolder!==t.isFolder)return e.isFolder?-1:1;let n=!!e.parentFolder;return n===!!t.parentFolder?e.parentFolder&&t.parentFolder&&e.parentFolder!==t.parentFolder?e.parentFolder.localeCompare(t.parentFolder):(e.name??``).localeCompare(t.name??``):n?-1:1});for(let e of n){let t=e.isFolder?this.showFolder(e.name):e.name,n=e.parentFolder?this.showFolder(`${e.parentFolder}/`):``;this.logger.info(`${n}${t||``}`)}}showFolder(e){return e?(0,l.styleText)([`bold`,`cyan`],e):``}async createDumpFile(){let e=process.env.MYSQL_HOST||`localhost`,t=Number(process.env.MYSQL_PORT||3306),n=process.env.MYSQL_USER||``,r=process.env.MYSQL_PASSWORD||``,i=process.env.MYSQL_DATABASE||``;if(!n||!r||!i)throw Error(`${A.TAG} Missing required MySQL environment variables ($MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE, $MYSQL_HOST, $MYSQL_PORT)`);let{dump:a}=await(0,g.default)({connection:{host:e,port:t,user:n,password:r,database:i}}),o=f.default.mkdtempSync(m.default.join(p.default.tmpdir(),`node-gdrive-mysql-`));f.default.chmodSync(o,448);let s=m.default.join(o,`mysqldump-${(0,h.default)().format(`YYYY-MM-DD.HHmmss`)}.sql`),c=Object.values(a).filter(e=>!!e).map(e=>e.replace(/^# /gm,`-- `)).join(`
2
+ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,o)=>(o=n==null?{}:e(i(n)),s(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));let l=require("node:util"),u=require("command-line-args");u=c(u);let d=require("command-line-usage");d=c(d);let f=require("node:path");f=c(f);let p=require("node:fs");p=c(p);let m=require("node:os");m=c(m);let h=require("node:stream/promises"),g=require("@googleapis/drive"),_=require("archiver"),v=require("dayjs");v=c(v);let y=require("mime-types");y=c(y);let b=require("node:crypto");b=c(b);let x=require("node:http");x=c(x);let S=require("google-auth-library"),C=require("node:fs/promises");C=c(C);let w=require("node:child_process"),ee=require("node:stream"),T=require("mysqldump");T=c(T);let E=require("node:sqlite");var D={name:`@d0whc3r/node-gdrive`,version:`3.5.1`,keywords:[`backup`,`compress`,`copy`,`drive`,`gdrive`,`google`,`googleapi`,`node`,`upload`],license:`MIT`,author:{name:`d0whc3r`,email:`d0whc3r@gmail.com`,url:`https://github.com/d0whc3r`},repository:{type:`git`,url:`https://github.com/d0whc3r/node-gdrive.git`},bin:{"node-gdrive":`./bin/cli.js`},files:[`dist`,`bin`],main:`dist/gdrive.cjs.js`,module:`dist/gdrive.esm.mjs`,types:`dist/index.d.ts`,exports:{".":{types:`./dist/index.d.ts`,import:`./dist/gdrive.esm.mjs`,require:`./dist/gdrive.cjs.js`}},publishConfig:{access:`public`,registry:`https://registry.npmjs.org`},scripts:{clean:`node -e "import('node:fs').then(fs => ['dist','bin','build','coverage','node-gdrive','node-gdrive.exe'].forEach(p => fs.rmSync(p, {recursive:true,force:true})))"`,"cli:dev":`node --env-file=.env cli/cli.ts`,cli:`node cli/cli.ts`,typecheck:`tsc --noEmit`,"build:clean":`node -e "import('node:fs').then(fs => ['dist','bin'].forEach(p => fs.rmSync(p, {recursive:true,force:true})))"`,"build:lib":`vite build --config vite.config.mts`,"build:cli":`vite build --config vite.cli.config.mts`,"build:dts":`tsc -p tsconfig.build.json --emitDeclarationOnly`,"build:base":`pnpm build:clean && pnpm build:lib && pnpm build:cli && pnpm build:dts`,"build:sea":`vite build --config vite.sea.config.mts && node scripts/build-sea.mjs`,build:`pnpm build:base && pnpm build:sea`,test:`vitest run`,"test:unit":`vitest run --exclude tests/gdrive.integration.spec.ts`,"test:integration":`vitest run tests/gdrive.integration.spec.ts`,"test:watch":`vitest`,"test:coverage":`vitest run --coverage`,lint:`oxlint`,"lint:fix":`oxlint --fix`,format:`oxfmt --write`,"format:check":`oxfmt --check`,prepare:`husky`,"semantic-release":`semantic-release`},dependencies:{"@googleapis/drive":`^27.1.0`,archiver:`^8.0.0`,"command-line-args":`^6.0.2`,"command-line-usage":`^7.0.4`,dayjs:`^1.11.23`,"google-auth-library":`^11.3.4`,"mime-types":`^3.0.2`,mysqldump:`^3.2.0`},devDependencies:{"@commitlint/cli":`^21.2.4`,"@commitlint/config-conventional":`^21.2.4`,"@semantic-release/changelog":`^7.0.0`,"@semantic-release/commit-analyzer":`^13.0.1`,"@semantic-release/git":`^11.0.1`,"@semantic-release/github":`^12.0.11`,"@semantic-release/npm":`^13.2.0`,"@semantic-release/release-notes-generator":`^14.1.1`,"@types/archiver":`^8.0.0`,"@types/command-line-args":`^5.2.3`,"@types/command-line-usage":`^5.0.4`,"@types/mime-types":`^3.0.1`,"@types/node":`^26.6.10`,"@vitest/coverage-v8":`^5.1.2`,husky:`^9.1.7`,"lint-staged":`^17.6.2`,oxfmt:`^0.80.0`,oxlint:`^1.95.0`,"semantic-release":`^26.0.1`,typescript:`^7.0.2`,vite:`^8.3.8`,vitest:`^5.1.2`},"lint-staged":{"{src,cli,tests}/**/*.ts":[`pnpm lint:fix`,`pnpm format`]},engines:{node:`>=26.0.0`},packageManager:`pnpm@12.16.1`},O=[{name:`list`,alias:`l`,multiple:!1,type:Boolean,description:`List all files and folders`},{name:`backup`,alias:`b`,typeLabel:`{underline file*}`,defaultOption:!0,multiple:!0,type:String,description:`Backup files, directories, or globs`},{name:`download`,typeLabel:`{underline fileId|name}`,multiple:!1,type:String,description:`Download/restore a file from Google Drive`},{name:`output`,alias:`o`,typeLabel:`{underline path}`,multiple:!1,type:String,description:`Local destination path for --download`},{name:`zip`,alias:`z`,typeLabel:`{underline zipname.zip}`,multiple:!1,type:String,description:`Zip backup files before uploading`},{name:`replace`,alias:`r`,multiple:!1,type:Boolean,description:`Replace files if already exists when uploading`},{name:`create`,alias:`c`,multiple:!1,type:Boolean,description:`Create destination upload folder if missing`},{name:`folder`,alias:`f`,typeLabel:`{underline foldername}`,multiple:!1,type:String,description:`Destination or target folder path (supports nested paths like a/b/c)`},{name:`delete`,alias:`d`,typeLabel:`{underline folder=duration} OR {underline duration}`,multiple:!0,type:String,description:`Clean files older than duration (e.g. 7d, 1M, 30m)`},{name:`keep-last`,typeLabel:`{underline N}`,multiple:!1,type:Number,description:`Always keep the newest N files when cleaning older files`},{name:`db`,typeLabel:`{underline engine}`,multiple:!1,type:String,description:`Database backup engine: postgres, mysql (or mariadb), mongodb, sqlite`},{name:`db-url`,typeLabel:`{underline uri}`,multiple:!1,type:String,description:`Database connection URI (auto-detects engine from scheme; overrides $DATABASE_URL)`},{name:`db-format`,typeLabel:`{underline format}`,multiple:!1,type:String,description:`PostgreSQL dump format: plain (.sql), custom (.dump), or tar (.tar)`},{name:`mysql`,alias:`m`,multiple:!1,type:Boolean,description:`Alias for --db mysql (uses $MYSQL_* or $DATABASE_URL)`},{name:`stdin`,multiple:!1,type:Boolean,description:`Read upload content from stdin (requires --name)`},{name:`name`,typeLabel:`{underline filename}`,multiple:!1,type:String,description:`Target filename when uploading from --stdin`},{name:`encrypt`,multiple:!1,type:Boolean,description:`Encrypt uploads / decrypt downloads with AES-256-GCM using $BACKUP_ENCRYPTION_KEY`},{name:`exclude`,typeLabel:`{underline glob}`,multiple:!0,type:String,description:`Exclude glob pattern(s) when backing up files`},{name:`dry-run`,multiple:!1,type:Boolean,description:`Preview uploads or deletions without modifying Google Drive`},{name:`drive-id`,typeLabel:`{underline id}`,multiple:!1,type:String,description:`Google Shared Drive ID`},{name:`service-account`,typeLabel:`{underline path}`,multiple:!1,type:String,description:`Path to Google Service Account JSON key file`},{name:`json`,multiple:!1,type:Boolean,description:`Output command results as JSON`},{name:`quiet`,alias:`q`,multiple:!1,type:Boolean,description:`Suppress non-essential log output`},{name:`version`,alias:`v`,multiple:!1,type:Boolean,description:`Print version number`},{name:`help`,alias:`h`,description:`Print this usage guide`,type:Boolean}];function k(){return D.version}function A(){let e=`node-gdrive`,t=[{header:`Help for ${e} v${D.version}`,content:`Usage of {italic ${e}} in command line.`},{header:`Options`,optionList:O},{header:`Examples`,content:[{desc:`1. List files (or JSON output).`,example:`$ ${e} -l --json`},{desc:`2. Backup multiple files to nested folder.`,example:`$ ${e} -b src/index.ts -b images/logo.png -f backups/app -c`},{desc:`3. Backup files as encrypted zip excluding logs.`,example:`$ BACKUP_ENCRYPTION_KEY=secret ${e} -b ./data/* --exclude "*.log" -z backup.zip -f backups -c -r --encrypt`},{desc:`4. Stream stdin directly to Google Drive.`,example:`$ pg_dump mydb | ${e} --stdin --name mydb.sql -f backups/pg -c`},{desc:`5. Download and decrypt a backup.`,example:`$ BACKUP_ENCRYPTION_KEY=secret ${e} --download backup.zip.enc -f backups -o ./backup.zip --encrypt`},{desc:`6. Clean files older than 7 days while keeping the 5 newest (dry run).`,example:`$ ${e} -f backups -d 7d --keep-last 5 --dry-run`},{desc:`7. Backup PostgreSQL, MySQL, MongoDB, or SQLite natively (streamed directly to Google Drive).`,example:`$ ${e} --db postgres -f backups/pg -c --encrypt\n$ ${e} --db-url "mongodb+srv://user:pass@host/mydb" -f backups/mongo -c\n$ ${e} --db sqlite -f backups/sqlite -z -c`}]}];return(0,d.default)(t)}function te(e){let t=(0,u.default)(O,e?{argv:e}:void 0);if(t[`keep-last`]!==void 0){let e=t[`keep-last`];if(!Number.isInteger(e)||e<0)throw Error(`Invalid --keep-last value "${String(e)}": expected a non-negative integer.`)}if(t.stdin&&!t.name)throw Error(`Option --stdin requires --name <filename>.`);return t}var ne=c(o(((e,t,n)=>{(function(n,r){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()})(n,(function(){"use strict";return function(e,t){t.prototype.isSameOrBefore=function(e,t){return this.isSame(e,t)||this.isBefore(e,t)}}}))}))()),j=class{static _tokenFile;static _credentialsFile;static _serviceAccountFile;static _tag;static get TOKEN_FILE(){return this._tokenFile??process.env.TOKEN_FILE??`./secrets/token.json`}static set TOKEN_FILE(e){this._tokenFile=e}static get CREDENTIALS_FILE(){return this._credentialsFile??process.env.CREDENTIALS_FILE??`./secrets/credentials.json`}static set CREDENTIALS_FILE(e){this._credentialsFile=e}static get SERVICE_ACCOUNT_FILE(){return this._serviceAccountFile??process.env.SERVICE_ACCOUNT_FILE??process.env.GOOGLE_APPLICATION_CREDENTIALS}static set SERVICE_ACCOUNT_FILE(e){this._serviceAccountFile=e}static get BACKUP_ENCRYPTION_KEY(){return process.env.BACKUP_ENCRYPTION_KEY||void 0}static get TAG(){return this._tag??`[node-gdrive]`}static set TAG(e){this._tag=e}static reset(){this._tokenFile=void 0,this._credentialsFile=void 0,this._serviceAccountFile=void 0,this._tag=void 0}},re=[`https://www.googleapis.com/auth/drive`],ie=class{ready=!0;scopes;tokenFile;credentialsFile;serviceAccountFile;useADC;logger;_oAuth2Client;_googleAuth;constructor(e={}){this.tokenFile=e.tokenFile??j.TOKEN_FILE,this.credentialsFile=e.credentialsFile??j.CREDENTIALS_FILE,this.serviceAccountFile=e.serviceAccountFile??j.SERVICE_ACCOUNT_FILE,this.useADC=e.useADC??!1,this.scopes=e.scopes??re,this.logger=e.logger??console,this.serviceAccountFile?p.existsSync(this.serviceAccountFile)||(this.ready=!1,this.logger.error((0,l.styleText)([`bold`,`red`],`${j.TAG} ERROR: Service account file not found in ${this.serviceAccountFile}`))):!this.useADC&&!this.existsCredentials&&(this.ready=!1,this.logger.error((0,l.styleText)([`bold`,`red`],`${j.TAG} ERROR: Credentials file not found in ${this.credentialsFile}`)))}get isServiceAccountOrADC(){return!!this.serviceAccountFile||this.useADC}get existsToken(){return p.existsSync(this.tokenFile)}get existsCredentials(){return p.existsSync(this.credentialsFile)}async initiate(){if(!this.ready){let e=this.serviceAccountFile??this.credentialsFile;throw Error(`${j.TAG} Credentials file not found in ${e}`)}return this.isServiceAccountOrADC?(this.googleAuthClient(),!0):this.existsToken?(this.oAuth2Client(!0),!0):this.generateAccessToken()}getAuthClient(){return this.isServiceAccountOrADC?this.googleAuthClient():this.oAuth2Client(!0)}googleAuthClient(){if(!this._googleAuth){if(this.serviceAccountFile){let e=JSON.parse(p.readFileSync(this.serviceAccountFile,`utf8`));this._googleAuth=new S.GoogleAuth({credentials:e,scopes:this.scopes})}else this._googleAuth=new S.GoogleAuth({scopes:this.scopes})}return this._googleAuth}oAuth2Client(e=!0,t){if(!this._oAuth2Client){let n=JSON.parse(p.readFileSync(this.credentialsFile,`utf8`)),r=n.installed??n.web;if(!r)throw Error(`${j.TAG} Invalid credentials file format in ${this.credentialsFile}`);let{client_secret:i,client_id:a,redirect_uris:o}=r;if(this._oAuth2Client=new S.OAuth2Client(a,i,t??o?.[0]??`http://127.0.0.1`),this.attachTokenListener(this._oAuth2Client),e&&this.existsToken){let e=JSON.parse(p.readFileSync(this.tokenFile,`utf8`));this._oAuth2Client.setCredentials(e)}}return this._oAuth2Client}attachTokenListener(e){e.on(`tokens`,e=>{try{let t={};this.existsToken&&(t=JSON.parse(p.readFileSync(this.tokenFile,`utf8`)));let n={...t,...e,refresh_token:e.refresh_token??t.refresh_token};this.persistTokenSync(n)}catch(e){this.logger.warn(`${j.TAG} Failed to persist refreshed token:`,e)}})}persistTokenSync(e){p.mkdirSync(f.default.dirname(this.tokenFile),{recursive:!0,mode:448}),p.writeFileSync(this.tokenFile,JSON.stringify(e,null,2),{mode:384}),p.chmodSync(this.tokenFile,384)}async generateAccessToken(){let e=b.default.randomBytes(16).toString(`hex`),t=b.default.randomBytes(32).toString(`base64url`),n=b.default.createHash(`sha256`).update(t).digest(`base64url`);return new Promise((r,i)=>{let a=x.default.createServer(),o=!1,s=e=>{o||(o=!0,a.close(),e())};a.on(`error`,e=>{s(()=>i(Error(`${j.TAG} OAuth loopback server failed`,{cause:e})))}),a.on(`request`,(n,o)=>{(async()=>{try{let c=new URL(n.url??`/`,`http://127.0.0.1`);if(c.pathname!==`/oauth2callback`){o.writeHead(404,{"Content-Type":`text/plain`}),o.end(`Not found`);return}let l=c.searchParams.get(`state`),u=c.searchParams.get(`code`),d=c.searchParams.get(`error`);if(d){o.writeHead(400,{"Content-Type":`text/plain`}),o.end(`Authorization failed: ${d}`),s(()=>i(Error(`${j.TAG} OAuth authorization error: ${d}`)));return}if(!l||l!==e){o.writeHead(400,{"Content-Type":`text/plain`}),o.end(`Invalid OAuth state parameter`),s(()=>i(Error(`${j.TAG} OAuth state mismatch`)));return}if(!u){o.writeHead(400,{"Content-Type":`text/plain`}),o.end(`Missing authorization code`),s(()=>i(Error(`${j.TAG} Missing OAuth authorization code`)));return}let f=`http://127.0.0.1:${a.address().port}/oauth2callback`,p=this.oAuth2Client(!1,f),{tokens:m}=await p.getToken({code:u,codeVerifier:t,redirect_uri:f});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(`${j.TAG} Token stored to`,this.tokenFile),s(()=>r(!0))}catch(e){o.writeHead(500,{"Content-Type":`text/plain`}),o.end(`Error exchanging OAuth authorization code.`),s(()=>i(e instanceof Error?e:Error(String(e))))}})()}),a.listen(0,`127.0.0.1`,()=>{let t=`http://127.0.0.1:${a.address().port}/oauth2callback`,r=this.oAuth2Client(!1,t).generateAuthUrl({access_type:`offline`,prompt:`consent`,scope:this.scopes,redirect_uri:t,state:e,code_challenge:n,code_challenge_method:S.CodeChallengeMethod.S256});this.logger.info(`${j.TAG} Authorize this app by visiting this url:`,r)})})}},M=Buffer.from(`NGDE`,`ascii`),N=1,P=16,F=12,I=16,ae=32,L=M.length+1+P+F;function R(e,t){if(!e)throw Error(`Encryption passphrase must not be empty`);return b.default.scryptSync(e,t,ae)}async function oe(e,t,n){let r=b.default.randomBytes(P),i=b.default.randomBytes(F),a=R(n,r),o=Buffer.concat([M,Buffer.from([N]),r,i]);p.default.mkdirSync(f.default.dirname(t),{recursive:!0,mode:448});let s=b.default.createCipheriv(`aes-256-gcm`,a,i),c=p.default.createReadStream(e),l=p.default.createWriteStream(t,{mode:384});try{l.write(o),await(0,h.pipeline)(c,s,l,{end:!1});let e=s.getAuthTag();return await new Promise((t,n)=>{l.once(`error`,n),l.end(e,()=>t())}),t}catch(n){throw c.destroy(),l.destroy(),p.default.rmSync(t,{force:!0}),Error(`Failed to encrypt file "${e}"`,{cause:n})}}async function se(e,t,n){let r=p.default.statSync(e);if(r.size<L+I)throw Error(`Encrypted file is too short or corrupted`);let i=p.default.openSync(e,`r`),a=Buffer.alloc(L),o=Buffer.alloc(I);try{p.default.readSync(i,a,0,L,0),p.default.readSync(i,o,0,I,r.size-I)}finally{p.default.closeSync(i)}if(!a.subarray(0,M.length).equals(M))throw Error(`Invalid encrypted file header`);let s=a[M.length];if(s!==N)throw Error(`Unsupported encryption format version: ${String(s)}`);let c=M.length+1,l=c+P,u=a.subarray(c,l),d=a.subarray(l,L),m=R(n,u),g=b.default.createDecipheriv(`aes-256-gcm`,m,d);g.setAuthTag(o),p.default.mkdirSync(f.default.dirname(t),{recursive:!0,mode:448});let _=r.size-L-I,v=p.default.createWriteStream(t,{mode:384});try{if(_===0){let e=g.final();await new Promise((t,n)=>{v.once(`error`,n),v.end(e,()=>t())})}else{let t=p.default.createReadStream(e,{start:L,end:r.size-I-1});await(0,h.pipeline)(t,g,v)}return t}catch(n){throw v.destroy(),p.default.rmSync(t,{force:!0}),Error(`Failed to decrypt file "${e}"`,{cause:n})}}var ce=new Set([429,500,502,503,504]),le=new Set([`ECONNRESET`,`ETIMEDOUT`,`ENOTFOUND`,`EAI_AGAIN`,`EPIPE`,`UND_ERR_CONNECT_TIMEOUT`]);function ue(e){return new Promise(t=>{setTimeout(t,e)})}function de(e){if(typeof e.status==`number`)return e.status;if(typeof e.code==`number`)return e.code;let t=e.response;if(typeof t?.status==`number`)return t.status}function fe(e){if(!e||typeof e!=`object`)return!1;let t=e,n=de(t);if(n!==void 0&&ce.has(n))return!0;let r=typeof t.code==`string`?t.code:void 0;return!!(r&&le.has(r))}async function z(e,t={}){let{maxRetries:n=4,baseDelayMs:r=500,maxDelayMs:i=16e3,jitter:a=!0,sleep:o=ue}=t,s=async t=>{try{return await e()}catch(e){if(t>=n||!fe(e))throw e;let c=Math.min(i,r*2**t),l=a?Math.round(c*(.5+Math.random()*.5)):c;return await o(l),s(t+1)}};return s(0)}var B=`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(`.`),V=16384;function H(e){let t=(process.env.PATH||``).split(f.default.delimiter).filter(Boolean),n=process.platform===`win32`?(process.env.PATHEXT||`.EXE;.CMD;.BAT`).split(`;`):[``];for(let r of e)if(r.includes(f.default.sep)||r.includes(`/`)){if(U(r))return r}else for(let e of t)for(let t of n){let n=f.default.join(e,`${r}${t}`);if(U(n))return n}}function U(e){try{return p.default.statSync(e).isFile()?(p.default.accessSync(e,p.default.constants.X_OK),!0):!1}catch{return!1}}function pe(e){return e.replace(/([a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^:@/\s]+):([^@/\s]+)@/g,`$1:***@`)}function W(e){return e.replace(/[^a-zA-Z0-9._-]/g,`_`).replace(/^_+|_+$/g,``)||`db`}function G(e){let t=(0,w.spawn)(e.binary,e.args,{env:e.env?{...process.env,...e.env}:process.env,stdio:[`ignore`,`pipe`,`pipe`],shell:!1}),n=new ee.PassThrough,r=[],i=0,a,o=()=>(a||=Promise.resolve(e.onCleanup?.()),a);t.stderr.on(`data`,e=>{if(i<V){let t=V-i;r.push(e.subarray(0,t)),i+=Math.min(e.length,t)}}),t.stdout.pipe(n,{end:!1});let s=!1,c,l,u=new Promise((e,t)=>{c=e,l=t});u.catch(()=>void 0);let d=e=>{s||(s=!0,o(),n.destroyed||n.destroy(e),l(e))};return t.on(`error`,t=>{t.code===`ENOENT`?d(Error(`${e.tag} "${e.binary}" not found in PATH. ${e.installHint}`)):d(Error(`${e.tag} Failed to start "${e.binary}": ${t.message}`))}),t.on(`close`,(t,i)=>{if(s)return;if(t===0){s=!0,o(),n.end(),c();return}let a=Buffer.concat(r).toString(`utf8`).trim(),l=a?`: ${pe(a)}`:``,u=i?`terminated by signal ${i}`:`exited with code ${t??`unknown`}`;d(Error(`${e.tag} ${e.binary} ${u}${l}`))}),{kind:`stream`,engine:e.engine,filename:e.filename,mimeType:e.mimeType,stream:n,wait:()=>u,cleanup:async()=>{!s&&!t.killed&&t.kill(`SIGTERM`),n.destroyed||n.destroy(),await o()}}}function me(e){return!!(e&&/^mongodb(?:\+srv)?:\/\//i.test(e))}function K(e){return JSON.stringify(e)}var he={engine:`mongodb`,aliases:[`mongo`],async dump(e){let t=e.tag??`[db]`,n=H([`mongodump`]);if(!n)throw Error(`${t} "mongodump" not found in PATH. Install mongodb-database-tools or use the :db Docker image.`);let r=e.url||process.env.MONGODB_URI||(me(process.env.DATABASE_URL)?process.env.DATABASE_URL:void 0),i=[`--archive`],a=`mongodb`,o=``;if(r){let t=``;try{t=new URL(r).pathname.replace(/^\/+/,``)}catch{}a=e.database||t||`mongodb`,o=`uri: ${K(r)}\n`,e.database&&i.push(`--db`,e.database)}else{let n=e.host||process.env.MONGO_HOST||`localhost`,r=e.port??(process.env.MONGO_PORT?Number(process.env.MONGO_PORT):27017),s=e.user||process.env.MONGO_USER||``,c=e.password??process.env.MONGO_PASSWORD??``,l=e.database||process.env.MONGO_DATABASE||``,u=process.env.MONGO_AUTH_DB||``;if(!l&&!e.host&&!process.env.MONGO_HOST)throw Error(`${t} Missing MongoDB configuration. Set $MONGODB_URI (or $MONGO_DATABASE / $MONGO_HOST / --db-url).`);a=l||`all`,i.push(`--host`,n,`--port`,String(r)),l&&i.push(`--db`,l),s&&i.push(`--username`,s),u&&i.push(`--authenticationDatabase`,u),c&&(o=`password: ${K(c)}\n`)}let s;if(o){s=await C.default.mkdtemp(f.default.join(m.default.tmpdir(),`db-mongo-cfg-`)),await C.default.chmod(s,448);let e=f.default.join(s,`mongodump.conf`);await C.default.writeFile(e,o,{mode:384}),i.push(`--config=${e}`)}return e.extraArgs?.length&&i.push(...e.extraArgs),G({engine:`mongodb`,binary:n,args:i,filename:e.filename||`mongodump-${W(a)}-${(0,v.default)().format(`YYYY-MM-DD.HHmmss`)}.archive`,mimeType:`application/octet-stream`,tag:t,installHint:`Install mongodb-database-tools or use the :db Docker image.`,onCleanup:async()=>{s&&await C.default.rm(s,{recursive:!0,force:!0})}})}};function ge(e){return!!(e&&/^(?:mysql|mariadb):\/\//i.test(e))}function _e(e,t){let n=e.url||(ge(process.env.DATABASE_URL)?process.env.DATABASE_URL:void 0);if(n){let r=new URL(n),i=e.host||r.hostname||`localhost`,a=e.port??(r.port?Number(r.port):3306),o=e.user||decodeURIComponent(r.username||``),s=e.password??decodeURIComponent(r.password||``),c=e.database||r.pathname.replace(/^\/+/,``);if(!o||!c)throw Error(`${t} Invalid MySQL/MariaDB URL: username and database name are required.`);return{host:i,port:a,user:o,password:s,database:c}}let r=e.host||process.env.MYSQL_HOST||`localhost`,i=e.port??(process.env.MYSQL_PORT?Number(process.env.MYSQL_PORT):3306),a=e.user||process.env.MYSQL_USER||``,o=e.password??process.env.MYSQL_PASSWORD??``,s=e.database||process.env.MYSQL_DATABASE||``;if(!a||!o||!s)throw Error(`${t} Missing required MySQL environment variables ($MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE, $MYSQL_HOST, $MYSQL_PORT) or --db-url.`);return{host:r,port:i,user:a,password:o,database:s}}async function ve(e,t){let{dump:n}=await(0,T.default)({connection:{host:e.host,port:e.port,user:e.user,password:e.password,database:e.database}}),r=await C.default.mkdtemp(f.default.join(m.default.tmpdir(),`db-mysql-`));await C.default.chmod(r,448);let i=f.default.join(r,t),a=Object.values(n).filter(e=>!!e).map(e=>e.replace(/^# /gm,`-- `)).join(`
3
3
 
4
- `);return f.default.writeFileSync(s,c,{mode:384}),{dumpPath:s,tempDir:o}}};async function ae(){let e=O(process.argv.slice(2));e.version?(console.info(E()),process.exitCode=0):e.help||Object.keys(e).length===0?(console.info(D()),process.exitCode=0):(await new ie(e).parseOptions(),process.exitCode=0)}ae().catch(e=>{let t=e instanceof Error?e.message:String(e);console.error((0,l.styleText)([`bold`,`red`],`[-] Error: ${t}`)),process.exitCode=1});
4
+ `);return await C.default.writeFile(i,a,{mode:384}),{kind:`file`,engine:`mysql`,filename:t,mimeType:`application/sql`,filePath:i,tempDir:r,cleanup:async()=>{await C.default.rm(r,{recursive:!0,force:!0})}}}var ye={engine:`mysql`,aliases:[`mariadb`],async dump(e){let t=e.tag??`[db]`,n=_e(e,t),r=e.filename||`mysqldump-${W(n.database)}-${(0,v.default)().format(`YYYY-MM-DD.HHmmss`)}.sql`,i=H([`mysqldump`,`mariadb-dump`]);if(!i)return ve(n,r);let a=[`--single-transaction`,`--quick`,`--routines`,`--triggers`,`-h`,n.host,`-P`,String(n.port),`-u`,n.user,...e.extraArgs??[],n.database],o={};return n.password&&(o.MYSQL_PWD=n.password),G({engine:`mysql`,binary:i,args:a,env:o,filename:r,mimeType:`application/sql`,tag:t,installHint:`Install mariadb-client / mysql-client or use the :db Docker image.`})}},be={plain:{ext:`sql`,mimeType:`application/sql`},custom:{ext:`dump`,mimeType:`application/octet-stream`},tar:{ext:`tar`,mimeType:`application/x-tar`}};function xe(e){return!!(e&&/^postgres(?:ql)?:\/\//i.test(e))}function Se(e){let t=new URL(e),n=t.password?decodeURIComponent(t.password):void 0,r=t.pathname.replace(/^\/+/,``)||`postgres`;return t.password=``,{sanitizedDbNameArg:t.toString(),password:n,database:r}}var Ce={engine:`postgres`,aliases:[`pg`,`postgresql`],async dump(e){let t=e.tag??`[db]`,n=e.format??`plain`,r=be[n];if(!r)throw Error(`${t} Unsupported PostgreSQL dump format "${String(n)}". Expected one of: plain, custom, tar.`);let i=H([`pg_dump`]);if(!i)throw Error(`${t} "pg_dump" not found in PATH. Install postgresql-client (e.g. apt install postgresql-client / brew install libpq) or use the :db Docker image.`);let a=e.url||(xe(process.env.DATABASE_URL)?process.env.DATABASE_URL:void 0),o=[`--no-password`,`--format=${n}`],s={},c;if(a){let t=Se(a);c=e.database||t.database,(e.password??t.password)&&(s.PGPASSWORD=e.password??t.password),o.push(`--dbname=${t.sanitizedDbNameArg}`)}else{let n=e.host||process.env.PGHOST||`localhost`,r=e.port??(process.env.PGPORT?Number(process.env.PGPORT):5432),i=e.user||process.env.PGUSER||``,a=e.password??process.env.PGPASSWORD,o=e.database||process.env.PGDATABASE||``;if(!o)throw Error(`${t} Missing PostgreSQL database configuration. Set $PGDATABASE (or $DATABASE_URL / --db-url).`);c=o,s.PGHOST=n,s.PGPORT=String(r),i&&(s.PGUSER=i),a!==void 0&&a!==``&&(s.PGPASSWORD=a),s.PGDATABASE=o}return e.extraArgs?.length&&o.push(...e.extraArgs),G({engine:`postgres`,binary:i,args:o,env:s,filename:e.filename||`pgdump-${W(c)}-${(0,v.default)().format(`YYYY-MM-DD.HHmmss`)}.${r.ext}`,mimeType:r.mimeType,tag:t,installHint:`Install postgresql-client or use the :db Docker image.`})}};function we(e){return!!(e&&/^(?:sqlite3?:|file:)/i.test(e))}function Te(e,t){let n=e.database||e.url||process.env.SQLITE_PATH||(we(process.env.DATABASE_URL)?process.env.DATABASE_URL:``);if(!n)throw Error(`${t} Missing SQLite database path. Set $SQLITE_PATH (or --db-url sqlite:///path/to/db.sqlite).`);let r=n;/^sqlite3?:\/\//i.test(n)?r=decodeURIComponent(n.replace(/^sqlite3?:\/\//i,``)):/^sqlite3?:/i.test(n)?r=decodeURIComponent(n.replace(/^sqlite3?:/i,``)):/^file:/i.test(n)&&(r=decodeURIComponent(n.replace(/^file:(\/\/)?/i,``)));let i=f.default.resolve(r);if(!p.default.existsSync(i)||!p.default.statSync(i).isFile())throw Error(`${t} SQLite database file not found: "${i}"`);return i}var q=[Ce,ye,he,{engine:`sqlite`,aliases:[`sqlite3`],async dump(e){let t=Te(e,e.tag??`[db]`),n=f.default.basename(t,f.default.extname(t)),r=e.filename||`sqlite-${W(n)}-${(0,v.default)().format(`YYYY-MM-DD.HHmmss`)}.sqlite`,i=await C.default.mkdtemp(f.default.join(m.default.tmpdir(),`db-sqlite-`));await C.default.chmod(i,448);let a=f.default.join(i,r),o=new E.DatabaseSync(t,{readOnly:!0});try{await(0,E.backup)(o,a),await C.default.chmod(a,384)}catch(e){throw await C.default.rm(i,{recursive:!0,force:!0}),e}finally{o.close()}return{kind:`file`,engine:`sqlite`,filename:r,mimeType:`application/vnd.sqlite3`,filePath:a,tempDir:i,cleanup:async()=>{await C.default.rm(i,{recursive:!0,force:!0})}}}}],J=new Map;for(let e of q){J.set(e.engine,e);for(let t of e.aliases)J.set(t,e)}var Y=q.map(e=>e.engine);function Ee(e,t=`[db]`){let n=e.trim().toLowerCase(),r=J.get(n);if(!r)throw Error(`${t} Unsupported database engine "${e}". Supported engines: ${Y.join(`, `)}.`);return r.engine}function X(e,t=`[db]`){let n=e.trim();if(/^postgres(?:ql)?:\/\//i.test(n))return`postgres`;if(/^(?:mysql|mariadb):\/\//i.test(n))return`mysql`;if(/^mongodb(?:\+srv)?:\/\//i.test(n))return`mongodb`;if(/^(?:sqlite3?:|file:)/i.test(n))return`sqlite`;throw Error(`${t} Could not detect database engine from URL. Supported schemes: postgresql://, mysql://, mariadb://, mongodb://, sqlite://.`)}async function De(e){let t=await C.default.mkdtemp(f.default.join(m.default.tmpdir(),`db-${e.engine}-`));await C.default.chmod(t,448);let n=f.default.join(t,f.default.basename(e.filename));try{let t=p.default.createWriteStream(n,{mode:384});await(0,h.pipeline)(e.stream,t),await e.wait()}catch(n){throw await e.cleanup(),await C.default.rm(t,{recursive:!0,force:!0}),n}return{kind:`file`,engine:e.engine,filename:e.filename,mimeType:e.mimeType,filePath:n,tempDir:t,cleanup:async()=>{await C.default.rm(t,{recursive:!0,force:!0})}}}async function Oe(e){let t=e.tag??`[db]`,n;if(e.engine)n=Ee(e.engine,t);else if(e.url)n=X(e.url,t);else if(process.env.DATABASE_URL)n=X(process.env.DATABASE_URL,t);else throw Error(`${t} Database engine not specified. Pass --db <${Y.join(`|`)}> or --db-url <uri>.`);let r=await J.get(n).dump({...e,engine:n,tag:t});return e.preferFile&&r.kind===`stream`?De(r):r}v.default.extend(ne.default);var ke=new Set(B),Ae=/^(\d+)([a-zA-Z]+)$/,je={s:`second`,second:`second`,seconds:`second`,m:`minute`,minute:`minute`,minutes:`minute`,h:`hour`,hour:`hour`,hours:`hour`,d:`day`,day:`day`,days:`day`,w:`week`,week:`week`,weeks:`week`,M:`month`,month:`month`,months:`month`,y:`year`,year:`year`,years:`year`};function Z(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`'`,`\\'`)}function Q(e){let t=Ae.exec(e),n=t?je[t[2]]:void 0;if(!t||!n)throw Error(`${j.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).`);let r=Number(t[1]);if(!Number.isFinite(r)||r<=0)throw Error(`${j.TAG} Invalid timeSpace "${e}": amount must be a positive integer.`);return{amount:r,unit:n}}async function $(e,t,n){let r=Math.max(1,Math.floor(t)),i=Array.from({length:e.length}),a=0;async function o(){if(a>=e.length)return;let t=a;a+=1,i[t]=await n(e[t]),await o()}let s=Array.from({length:Math.min(r,e.length)},()=>o());return await Promise.all(s),i}var Me=class{DEFAULT_FIELDS=[`createdTime`,`id`,`md5Checksum`,`mimeType`,`name`,`parents`,`trashed`];MIME_FOLDER=`application/vnd.google-apps.folder`;gdriveAuth;injectedAuth;sharedDriveId;defaultDryRun;defaultConcurrency;defaultCompressionLevel;defaultOnProgress;retryOptions;logger;_drive;_initPromise;constructor(e={}){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 ie({credentialsFile:e.credentialsFile,tokenFile:e.tokenFile,serviceAccountFile:e.serviceAccountFile,useADC:e.useADC,scopes:e.scopes,logger:this.logger}))}ensureInitiated(){return this._drive||this.injectedAuth?Promise.resolve(!0):(this._initPromise||=this.gdriveAuth.initiate().catch(e=>{throw this._initPromise=void 0,e}),this._initPromise)}get auth(){return this.injectedAuth?this.injectedAuth:this.gdriveAuth.getAuthClient()}get drive(){return this._drive||=(0,g.drive)({version:`v3`,auth:this.auth}),this._drive}get sharedDriveListParams(){return this.sharedDriveId?{supportsAllDrives:!0,includeItemsFromAllDrives:!0,corpora:`drive`,driveId:this.sharedDriveId}:{}}get sharedDriveItemParams(){return this.sharedDriveId?{supportsAllDrives:!0}:{}}get rootParentId(){return this.sharedDriveId??`root`}isFolder(e){if(Object.hasOwn(e,`mimeType`))return e.mimeType===this.MIME_FOLDER}isDeleted(e){return Object.hasOwn(e,`trashed`)?!!e.trashed:!1}async listFiles(e,t=1e3,n){await this.ensureInitiated();let r;if(!e)r=this.DEFAULT_FIELDS;else if(e===!0)r=B;else{for(let t of e)if(!ke.has(t))throw Error(`${j.TAG} Invalid Drive file field: "${t}"`);r=e}let i={pageSize:t,fields:`kind, nextPageToken, incompleteSearch, files(${r.join(`, `)})`,prettyPrint:!1,...this.sharedDriveListParams};return n&&(i.q=n),this.getListFiles(i)}async getFile(e){if(await this.ensureInitiated(),!e)throw this.genericError(Error(`${j.TAG} File id not found`));let t={fileId:e,...this.sharedDriveItemParams};try{let{data:e}=await z(()=>this.drive.files.get(t),this.retryOptions);return e}catch(e){throw this.genericError(e)}}async resolveDownloadFileId(e,t){if(t){let n=await this.findFolderId(t,!1),r=await this.findFile(e,n);if(!r?.id)throw Error(`${j.TAG} File "${e}" not found in folder "${t}"`);return r.id}try{return(await z(()=>this.drive.files.get({fileId:e,fields:`id, name, mimeType`,...this.sharedDriveItemParams}),this.retryOptions)).data.id??e}catch{let t=await this.findFile(e);if(!t?.id)throw Error(`${j.TAG} File "${e}" not found`);return t.id}}async downloadFile(e,t,n={}){if(await this.ensureInitiated(),!e)throw Error(`${j.TAG} File id or name is required for download`);let r=await this.resolveDownloadFileId(e,n.folderName);p.default.mkdirSync(f.default.dirname(f.default.resolve(t)),{recursive:!0});let i,a=t;n.decryptKey&&(i=this.createPrivateTempDir(),a=f.default.join(i,`download.enc`));try{let e=await z(()=>this.drive.files.get({fileId:r,alt:`media`,...this.sharedDriveItemParams},{responseType:`stream`}),this.retryOptions),i=p.default.createWriteStream(a,{mode:n.decryptKey?384:420});return await(0,h.pipeline)(e.data,i),n.decryptKey&&await se(a,t,n.decryptKey),t}catch(e){throw n.decryptKey||p.default.rmSync(t,{force:!0}),this.genericError(e)}finally{i&&p.default.rmSync(i,{recursive:!0,force:!0})}}async emptyTrash(){return await this.ensureInitiated(),z(()=>this.drive.files.emptyTrash(),this.retryOptions)}async deleteFile(e){if(await this.ensureInitiated(),e.id)try{let{data:t}=await z(()=>this.drive.files.delete({fileId:e.id,...this.sharedDriveItemParams}),this.retryOptions);return e.name&&this.logger.warn(`${j.TAG} Deleted ${e.isFolder?`folder`:`file`}: ${e.name}`),t}catch(e){throw this.genericError(e)}}async uploadFile(e,t,n={}){await this.ensureInitiated();let{create:r=!0,replace:i=!1,encryptKey:a}=n,o=n.dryRun??this.defaultDryRun,s=n.onProgress??this.defaultOnProgress,c=f.default.basename(e),l=a&&!c.endsWith(`.enc`)?`${c}.enc`:c,u={name:l,mimeType:a?`application/octet-stream`:y.default.contentType(c)||void 0},d=await this.getUploadFolderId(t||!1,r,u,o);if(o)return this.logger.info(`${j.TAG} [dry-run] Would upload "${l}"${t&&typeof t==`string`?` to "${t}"`:``}`),this.parseFileMeta(u);await this.replaceExistingFile(i,l,d);let m,h=e;a&&(m=this.createPrivateTempDir(),h=f.default.join(m,l),await oe(e,h,a));try{let e=p.default.statSync(h).size,{data:t}=await z(async()=>{let t=p.default.createReadStream(h);t.on(`error`,e=>{this.logger.error(`${j.TAG} Read stream error for "${h}":`,e)});let n={requestBody:u,media:{body:t},fields:`kind, ${this.DEFAULT_FIELDS.join(`, `)}`,...this.sharedDriveItemParams},r=t=>{let n=e===0?100:Math.min(100,t.bytesRead/e*100);s?.({fileName:l,bytesRead:t.bytesRead,totalBytes:e,percentage:n}),n>=100&&this.logger.warn(`${j.TAG} Upload ${l}: ${Math.round(n)}% complete`)};try{return await this.drive.files.create(n,{onUploadProgress:r})}finally{t.destroy()}},this.retryOptions);return this.parseFileMeta(t)}catch(e){throw this.genericError(e)}finally{m&&p.default.rmSync(m,{recursive:!0,force:!0})}}async uploadStream(e,t,n,r={}){await this.ensureInitiated();let i=this.sanitizeFilename(t),a=this.createPrivateTempDir(),o=f.default.join(a,i);try{let t=p.default.createWriteStream(o,{mode:384});return await(0,h.pipeline)(e,t),await this.uploadFile(o,n,r)}finally{p.default.rmSync(a,{recursive:!0,force:!0})}}async uploadFiles(e,t,n={}){await this.ensureInitiated();let{compress:r,replace:i,create:a,dryRun:o,encryptKey:s,onProgress:c,exclude:l,followSymlinks:u=!1}=n,d=n.concurrency??this.defaultConcurrency,m=n.compressionLevel??this.defaultCompressionLevel,h=Array.isArray(e)?e:[e],g=this.expandFileInputs(h,{exclude:l,followSymlinks:u}),_,y=g;try{if(r){let e=typeof r==`string`?r:`zipped_${(0,v.default)().format(`YYYY-MM-DD.HHmmss`)}.zip`,{zipPath:t,tempDir:n}=await this.compressFiles(g,e,{compressionLevel:m,followSymlinks:u});_=n,y=[t]}t&&typeof t==`string`&&y.length>0&&!(o??this.defaultDryRun)&&await this.findFolderId(t,a??!0);let e={};return await $(y,d,async n=>{let r=await this.uploadFile(n,t,{replace:i,create:a,dryRun:o,encryptKey:s,onProgress:c}),l=r.name||f.default.basename(n);e[l]=r}),e}finally{_&&p.default.rmSync(_,{recursive:!0,force:!0})}}async cleanOlder(e,t,n={}){let{amount:r,unit:i}=Q(e);await this.ensureInitiated();let a=``;return t&&(a=await this.findFolderId(t,!1)),this.deleteOlder(r,i,a,n)}expandFileInputs(e,t){let{exclude:n=[],followSymlinks:r=!1}=t,i=[],a=e=>{if(e.includes(`*`)){let t=p.default.globSync(e,{exclude:n});for(let e of t)a(e);return}if(n.some(t=>f.default.matchesGlob(e,t)||f.default.matchesGlob(f.default.basename(e),t)))return;let t=p.default.lstatSync(e);if(t.isSymbolicLink()&&!r)this.logger.warn(`${j.TAG} Skipping symlink: ${e}`);else if((t.isSymbolicLink()?p.default.statSync(e):t).isDirectory()){let t=p.default.readdirSync(e).map(t=>f.default.join(e,t));for(let e of t)a(e)}else i.push(e)};for(let t of e)a(t);return i}async getListFiles(e){let t=[],n=async r=>{let i=r?{...e,pageToken:r}:{...e},{data:a}=await z(()=>this.drive.files.list(i),this.retryOptions);a.files?.length&&t.push(...a.files),a.nextPageToken&&await n(a.nextPageToken)};try{return await n(),this.parseFilesMeta(t)}catch(e){throw this.genericError(e)}}async replaceExistingFile(e,t,n){let r=await this.findFile(t,n);if(r){if(!e)throw Error(`${j.TAG} File "${t}" already exists and will not be replaced`);this.logger.warn(`${j.TAG} File "${t}" already exists and will be deleted before upload`),await this.deleteFile(r)}}async getUploadFolderId(e,t,n,r=!1){if(e&&typeof e==`string`){let i=await this.findFolderId(e,t&&!r);return n.parents=[i],i}return this.sharedDriveId&&(n.parents=[this.sharedDriveId]),``}async deleteOlder(e,t,n,r={}){let i=r.dryRun??this.defaultDryRun,a=Math.max(0,r.keepLast??0),o=r.concurrency??this.defaultConcurrency,s=(0,v.default)().subtract(e,t),c=[`mimeType != '${this.MIME_FOLDER}'`,`trashed = false`];n&&c.push(`'${Z(n)}' in parents`),a===0&&c.push(`createdTime <= '${s.toISOString()}'`);let l=(await this.listFiles(void 0,1e3,c.join(` and `))).filter(e=>!e.isDeleted&&!e.isFolder).filter(e=>!n||!!e.parents?.includes(n)).sort((e,t)=>{let n=e.createdTime?(0,v.default)(e.createdTime).valueOf():0;return(t.createdTime?(0,v.default)(t.createdTime).valueOf():0)-n}),u=(a>0?l.slice(a):l).filter(e=>e.createdTime&&(0,v.default)(e.createdTime).isSameOrBefore(s));if(i){for(let e of u)this.logger.info(`${j.TAG} [dry-run] Would delete file: ${e.name??e.id??`unknown`}`);return u}return await $(u,o,async e=>{await this.deleteFile(e)}),u}parseFileMeta(e){return{...e,isDeleted:this.isDeleted(e),isFolder:!!this.isFolder(e)}}parseFilesMeta(e){return e.map(e=>this.parseFileMeta(e))}genericError(e){return this.logger.error(`${j.TAG} The API returned an error: ${String(e)}`),e}inFlightFolders=new Map;findFolderId(e,t=!1){let n=`${e}::${t}`,r=this.inFlightFolders.get(n);if(r)return r;let i=this.resolveFolderId(e,t).finally(()=>{this.inFlightFolders.delete(n)});return this.inFlightFolders.set(n,i),i}async resolveFolderId(e,t=!1){let n=e.split(`/`).map(e=>e.trim()).filter(Boolean);if(n.length===0)throw Error(`${j.TAG} Invalid folder path "${e}"`);return this.resolveFolderSegments(n,0,this.rootParentId,t,e)}async resolveFolderSegments(e,t,n,r,i){if(t>=e.length)return n;let a=e[t],o=[`name = '${Z(a)}'`,`mimeType = '${this.MIME_FOLDER}'`,`trashed = false`,`'${Z(n)}' in parents`].join(` and `),s=(await this.listFiles(void 0,100,o)).find(e=>e.isFolder&&!e.isDeleted&&e.name===a&&e.id),c;if(s?.id)c=s.id;else if(r){let e=await this.createFolder(a,n);if(!e.id)throw Error(`${j.TAG} Failed to create folder "${a}"`);c=e.id}else throw Error(`${j.TAG} Folder "${i}" does not exist and will not be created`);return this.resolveFolderSegments(e,t+1,c,r,i)}async findFile(e,t){let n=t||this.rootParentId,r=[`name = '${Z(e)}'`,`mimeType != '${this.MIME_FOLDER}'`,`trashed = false`,`'${Z(n)}' in parents`].join(` and `);return(await this.listFiles(void 0,100,r)).find(n=>!n.isFolder&&!n.isDeleted&&n.name===e&&(!t||!!n.parents?.includes(t)))??null}async createFolder(e,t){let n={name:e,mimeType:this.MIME_FOLDER};t&&t!==`root`&&(n.parents=[t]);try{let{data:t}=await z(()=>this.drive.files.create({requestBody:n,fields:`id`,...this.sharedDriveItemParams}),this.retryOptions);return t?.id&&this.logger.warn(`${j.TAG} Created folder "${e}" with id: "${t.id}"`),t}catch(e){throw this.genericError(e)}}createPrivateTempDir(){let e=p.default.mkdtempSync(f.default.join(m.default.tmpdir(),`node-gdrive-`));return p.default.chmodSync(e,448),e}sanitizeFilename(e){let t=f.default.basename(e);if(!t||t===`.`||t===`..`)throw Error(`${j.TAG} Invalid output filename: "${e}"`);return t}compressFiles(e,t,n={}){let r=this.sanitizeFilename(t),i=this.createPrivateTempDir(),a=f.default.join(i,r),o=n.compressionLevel??this.defaultCompressionLevel,s=n.followSymlinks??!1;return new Promise((t,n)=>{let r=p.default.createWriteStream(a,{mode:384}),c=[],l=!1,u=e=>{if(!l){l=!0;for(let e of c)e.destroy();r.destroy(),p.default.rmSync(i,{recursive:!0,force:!0}),n(e instanceof Error?e:Error(String(e)))}},d=new _.ZipArchive({zlib:{level:o}});r.on(`error`,e=>{u(e)}),r.on(`close`,()=>{l||(l=!0,t({zipPath:a,tempDir:i}))}),d.on(`warning`,e=>{this.logger.warn(`${j.TAG} Warning compressing file`,e),e.code!==`ENOENT`&&u(e)}),d.on(`error`,e=>{this.logger.error(`${j.TAG} Error compressing file`,e),u(e)}),d.pipe(r);try{for(let t of e){let e=p.default.lstatSync(t);if(e.isSymbolicLink()&&!s)this.logger.warn(`${j.TAG} Skipping symlink: ${t}`);else if((e.isSymbolicLink()?p.default.statSync(t):e).isDirectory())d.directory(t,f.default.basename(t));else{let e=f.default.basename(t),n=p.default.createReadStream(t);n.on(`error`,e=>{u(e)}),d.append(n,{name:e}),c.push(n)}}}catch(e){u(e);return}d.finalize().catch(e=>{u(e)}).finally(()=>{for(let e of c)e.destroy()})})}};function Ne(e){return e?{info:()=>{},warn:()=>{},error:(...e)=>console.error(...e)}:console}var Pe=class{opts;logger;gdrive;constructor(e,t,n){this.opts=e;let r=!!(e.quiet||e.json);this.logger=n??Ne(r),this.gdrive=t??new Me({sharedDriveId:e[`drive-id`],serviceAccountFile:e[`service-account`],dryRun:e[`dry-run`],logger:this.logger})}getEncryptionKey(){if(!this.opts.encrypt)return;let e=j.BACKUP_ENCRYPTION_KEY;if(!e)throw Error(`${j.TAG} --encrypt requires BACKUP_ENCRYPTION_KEY environment variable to be set.`);return e}async parseOptions(e=process.stdin){if(this.opts.version){console.info(k());return}if(this.opts.help||Object.keys(this.opts).length===0){console.info(A());return}let t=this.opts.zip,n=this.opts.folder,r=this.opts.replace,i=this.opts.create,a=this.opts[`dry-run`],o=this.opts.exclude;this.opts.list&&await this.showList(),this.opts.backup&&await this.backup(this.opts.backup,{zip:t,folder:n,replace:r,create:i,dryRun:a,exclude:o}),this.opts.stdin&&await this.uploadFromStdin(e,this.opts.name,{folder:n,replace:r,create:i,dryRun:a}),this.opts.download&&await this.download(this.opts.download,this.opts.output,n),this.opts.delete&&await this.delete(this.opts.delete,n,{dryRun:a,keepLast:this.opts[`keep-last`]}),this.opts.db||this.opts[`db-url`]?await this.backupDatabase({zip:t,folder:n,replace:r,create:i,dryRun:a}):this.opts.mysql&&await this.dumpMysql({zip:t,folder:n,replace:r,create:i,dryRun:a})}async showList(){let e=(await this.gdrive.listFiles()).filter(e=>!e.isDeleted);return this.opts.json?(console.info(JSON.stringify(e,null,2)),e):(e.length?(this.logger.info(`${j.TAG} File list: ${e.length}`),this.beautifulFiles(e)):this.logger.info(`${j.TAG} No files found.`),e)}async delete(e,t,n={}){let r=(Array.isArray(e)?e:[e]).map(e=>{let n=this.parseDelete(e);return{folder:n.folder??t??void 0,timeSpace:n.timeSpace}}),i=(await Promise.all(r.map(e=>this.gdrive.cleanOlder(e.timeSpace,e.folder,{dryRun:n.dryRun,keepLast:n.keepLast})))).flat();return this.opts.json&&console.info(JSON.stringify(i,null,2)),i}async backup(e,t){let{zip:n,folder:r,replace:i,create:a,dryRun:o,exclude:s}=t,c=this.getEncryptionKey(),l=Array.isArray(e)?e:[e],u=await this.gdrive.uploadFiles(l,r||!1,{compress:n||n===null,replace:i,create:a,dryRun:o,encryptKey:c,exclude:s});return this.opts.json&&console.info(JSON.stringify(u,null,2)),u}async uploadFromStdin(e,t,n){let r=this.getEncryptionKey(),i=await this.gdrive.uploadStream(e,t,n.folder||!1,{replace:n.replace,create:n.create,dryRun:n.dryRun,encryptKey:r});return this.opts.json&&console.info(JSON.stringify(i,null,2)),i}async download(e,t,n){let r=this.getEncryptionKey(),i=r&&e.endsWith(`.enc`)?e.slice(0,-4):f.default.basename(e),a=t??i,o=await this.gdrive.downloadFile(e,a,{decryptKey:r,folderName:n});return this.opts.json?console.info(JSON.stringify({downloaded:o},null,2)):this.logger.info(`${j.TAG} Downloaded to ${o}`),o}async backupDatabase(e){let t=await Oe({engine:e.engine??this.opts.db??(this.opts.mysql?`mysql`:void 0),url:e.url??this.opts[`db-url`],format:e.format??this.opts[`db-format`],preferFile:!!(e.zip||e.zip===null),filename:this.opts.name,tag:j.TAG});try{if(t.kind===`stream`){let n=this.getEncryptionKey(),r=await this.gdrive.uploadStream(t.stream,t.filename,e.folder||!1,{replace:e.replace,create:e.create,dryRun:e.dryRun,encryptKey:n,mimeType:t.mimeType});return await t.wait(),this.opts.json&&console.info(JSON.stringify(r,null,2)),r}return await this.backup(t.filePath,e)}finally{await t.cleanup()}}async dumpMysql(e){return this.backupDatabase({...e,engine:`mysql`})}parseDelete(e){let t=e.lastIndexOf(`=`);return t>0?{folder:e.slice(0,t),timeSpace:e.slice(t+1)}:{folder:null,timeSpace:e}}beautifulFiles(e){let t=new Map;for(let n of e)n.id&&n.name&&t.set(n.id,n.name);let n=e.map(e=>{let n=e.parents?.[0];return{...e,parentFolder:n?t.get(n):void 0}});n.sort((e,t)=>{if(e.isFolder!==t.isFolder)return e.isFolder?-1:1;let n=!!e.parentFolder;return n===!!t.parentFolder?e.parentFolder&&t.parentFolder&&e.parentFolder!==t.parentFolder?e.parentFolder.localeCompare(t.parentFolder):(e.name??``).localeCompare(t.name??``):n?-1:1});for(let e of n){let t=e.isFolder?this.showFolder(e.name):e.name,n=e.parentFolder?this.showFolder(`${e.parentFolder}/`):``;this.logger.info(`${n}${t||``}`)}}showFolder(e){return e?(0,l.styleText)([`bold`,`cyan`],e):``}};async function Fe(){let e=te(process.argv.slice(2));e.version?(console.info(k()),process.exitCode=0):e.help||Object.keys(e).length===0?(console.info(A()),process.exitCode=0):(await new Pe(e).parseOptions(),process.exitCode=0)}Fe().catch(e=>{let t=e instanceof Error?e.message:String(e);console.error((0,l.styleText)([`bold`,`red`],`[-] Error: ${t}`)),process.exitCode=1});
@@ -0,0 +1,19 @@
1
+ import type { DbDumpOptions, DbDumpResult, DbEngine, DbProvider } from './types';
2
+ export declare const DB_PROVIDERS: readonly DbProvider[];
3
+ export declare const SUPPORTED_DB_ENGINES: readonly DbEngine[];
4
+ /**
5
+ * Resolves a database engine name or alias to its canonical `DbEngine`.
6
+ */
7
+ export declare function normalizeDbEngine(value: string, tag?: string): DbEngine;
8
+ /**
9
+ * Infers the database engine from a connection URL scheme.
10
+ */
11
+ export declare function detectDbEngineFromUrl(url: string, tag?: string): DbEngine;
12
+ /**
13
+ * Creates a database dump using the appropriate engine provider.
14
+ * Returns a live stream by default for CLI-backed engines (O(1) memory, zero temp disk),
15
+ * or materializes to a secure temporary file when `preferFile` is true (e.g. for `--zip`).
16
+ */
17
+ export declare function dumpDatabase(options: DbDumpOptions): Promise<DbDumpResult>;
18
+ export { findBinary, sanitizeFilenamePart, sanitizeUrl } from './spawn';
19
+ export type { DbDumpFileResult, DbDumpOptions, DbDumpResult, DbDumpStreamResult, DbEngine, DbProvider, PostgresFormat } from './types';
@@ -0,0 +1,2 @@
1
+ import type { DbProvider } from '../types';
2
+ export declare const mongodbProvider: DbProvider;
@@ -0,0 +1,2 @@
1
+ import type { DbProvider } from '../types';
2
+ export declare const mysqlProvider: DbProvider;
@@ -0,0 +1,2 @@
1
+ import type { DbProvider } from '../types';
2
+ export declare const postgresProvider: DbProvider;
@@ -0,0 +1,2 @@
1
+ import type { DbProvider } from '../types';
2
+ export declare const sqliteProvider: DbProvider;
@@ -0,0 +1,29 @@
1
+ import type { DbDumpStreamResult, DbEngine } from './types';
2
+ /**
3
+ * Checks whether an executable binary is available on PATH (or as an explicit path).
4
+ */
5
+ export declare function findBinary(candidates: readonly string[]): string | undefined;
6
+ /**
7
+ * Strips password/credentials from a connection URI before including it in errors or logs.
8
+ */
9
+ export declare function sanitizeUrl(rawText: string): string;
10
+ /**
11
+ * Sanitizes a database identifier for safe inclusion in a dump filename.
12
+ */
13
+ export declare function sanitizeFilenamePart(value: string): string;
14
+ export interface SpawnDumpOptions {
15
+ engine: DbEngine;
16
+ binary: string;
17
+ args: string[];
18
+ env?: NodeJS.ProcessEnv;
19
+ filename: string;
20
+ mimeType: string;
21
+ tag: string;
22
+ installHint: string;
23
+ onCleanup?: () => Promise<void> | void;
24
+ }
25
+ /**
26
+ * Spawns a database dump binary safely (without a shell) and exposes its stdout
27
+ * as a backpressure-aware Readable stream that propagates non-zero exit errors.
28
+ */
29
+ export declare function spawnDumpStream(options: SpawnDumpOptions): DbDumpStreamResult;
@@ -0,0 +1,56 @@
1
+ import type { Readable } from 'node:stream';
2
+ export type DbEngine = 'postgres' | 'mysql' | 'mongodb' | 'sqlite';
3
+ export type PostgresFormat = 'plain' | 'custom' | 'tar';
4
+ export interface DbDumpOptions {
5
+ /** Target database engine. Auto-detected from `url` when omitted. */
6
+ engine?: DbEngine | string;
7
+ /** Connection URI (e.g. postgresql://..., mysql://..., mongodb://..., sqlite:///path/to.db). */
8
+ url?: string;
9
+ /** Database host (overrides engine env vars). */
10
+ host?: string;
11
+ /** Database port (overrides engine env vars). */
12
+ port?: number;
13
+ /** Database user (overrides engine env vars). */
14
+ user?: string;
15
+ /** Database password (overrides engine env vars). */
16
+ password?: string;
17
+ /** Database name (or file path for SQLite). */
18
+ database?: string;
19
+ /** Output format for PostgreSQL (`plain`, `custom`, `tar`). Defaults to `plain`. */
20
+ format?: PostgresFormat;
21
+ /** Materialize stream output into a temporary file (e.g. when zipping). */
22
+ preferFile?: boolean;
23
+ /** Optional custom filename for the resulting dump. */
24
+ filename?: string;
25
+ /** Extra CLI flags passed to the underlying dump binary. */
26
+ extraArgs?: string[];
27
+ /** Log/error tag prefix (e.g. `[node-s3]`). */
28
+ tag?: string;
29
+ }
30
+ export interface DbDumpStreamResult {
31
+ kind: 'stream';
32
+ engine: DbEngine;
33
+ filename: string;
34
+ mimeType: string;
35
+ stream: Readable;
36
+ /** Resolves when the dump process exits with code 0; rejects otherwise. */
37
+ wait: () => Promise<void>;
38
+ /** Terminates any active process and removes temporary resources. */
39
+ cleanup: () => Promise<void>;
40
+ }
41
+ export interface DbDumpFileResult {
42
+ kind: 'file';
43
+ engine: DbEngine;
44
+ filename: string;
45
+ mimeType: string;
46
+ filePath: string;
47
+ tempDir: string;
48
+ /** Removes the temporary directory containing the dump file. */
49
+ cleanup: () => Promise<void>;
50
+ }
51
+ export type DbDumpResult = DbDumpStreamResult | DbDumpFileResult;
52
+ export interface DbProvider {
53
+ readonly engine: DbEngine;
54
+ readonly aliases: readonly string[];
55
+ dump(options: DbDumpOptions): Promise<DbDumpResult>;
56
+ }