@d0whc3r/node-gdrive 3.4.0 → 3.5.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020-present d0whc3r
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,137 +1,219 @@
1
- # :floppy_disk: Node gdrive
1
+ # node-gdrive
2
2
 
3
- Utility to manipulate google drive using nodejs. It could upload content to google drive and it could be used as backup service.
3
+ CLI and Node.js library to back up, restore, encrypt, and prune files on **Google Drive**—works via **Docker**, **npx/npm**, or as a **standalone binary** (Linux, macOS, Windows).
4
4
 
5
- # :eyes: Project status
5
+ [![CI](https://img.shields.io/github/actions/workflow/status/d0whc3r/node-gdrive/ci.yml?branch=master&style=flat-square&logo=githubactions&logoColor=white&label=CI)](https://github.com/d0whc3r/node-gdrive/actions/workflows/ci.yml)
6
+ [![npm](https://img.shields.io/npm/v/@d0whc3r/node-gdrive?style=flat-square&logo=npm&logoColor=white)](https://www.npmjs.com/package/@d0whc3r/node-gdrive)
7
+ [![Docker Hub](https://img.shields.io/docker/v/d0whc3r/gdrive?style=flat-square&logo=docker&logoColor=white&label=docker)](https://hub.docker.com/r/d0whc3r/gdrive)
8
+ [![Node.js](https://img.shields.io/badge/Node.js-%3E%3D26-339933?style=flat-square&logo=nodedotjs&logoColor=white)](https://nodejs.org/)
9
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue?style=flat-square)](./LICENSE)
6
10
 
7
- [![pipeline status](https://gitlab.com/d0whc3r/node-gdrive/badges/master/pipeline.svg)](https://github.com/d0whc3r/node-gdrive)
8
- [![codecov](https://codecov.io/gh/d0whc3r/node-gdrive/branch/master/graph/badge.svg)](https://codecov.io/gh/d0whc3r/node-gdrive)
9
- [![Codacy Badge](https://api.codacy.com/project/badge/Grade/2612116bab5f493cada70bffc3cb6492)](https://www.codacy.com/app/d0whc3r/node-gdrive?utm_source=github.com&utm_medium=referral&utm_content=d0whc3r/node-gdrive&utm_campaign=Badge_Grade)
11
+ ---
10
12
 
11
- [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=d0whc3r_node-gdrive&metric=alert_status)](https://sonarcloud.io/dashboard?id=d0whc3r_node-gdrive)
12
- [![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=d0whc3r_node-gdrive&metric=sqale_rating)](https://sonarcloud.io/dashboard?id=d0whc3r_node-gdrive)
13
- [![Security Rating](https://sonarcloud.io/api/project_badges/measure?project=d0whc3r_node-gdrive&metric=security_rating)](https://sonarcloud.io/dashboard?id=d0whc3r_node-gdrive)
14
- [![Bugs](https://sonarcloud.io/api/project_badges/measure?project=d0whc3r_node-gdrive&metric=bugs)](https://sonarcloud.io/dashboard?id=d0whc3r_node-gdrive)
15
- [![Vulnerabilities](https://sonarcloud.io/api/project_badges/measure?project=d0whc3r_node-gdrive&metric=vulnerabilities)](https://sonarcloud.io/dashboard?id=d0whc3r_node-gdrive)
13
+ ## Ways to Run
16
14
 
17
- ![dependencies](https://img.shields.io/david/d0whc3r/node-gdrive.svg)
18
- [![npm version](https://img.shields.io/npm/v/@d0whc3r%2Fnode-gdrive.svg)](https://www.npmjs.com/package/@d0whc3r/node-gdrive)
15
+ ### 1. Docker (No Node.js required)
19
16
 
20
- [![](https://img.shields.io/docker/cloud/build/d0whc3r/gdrive.svg)](https://hub.docker.com/r/d0whc3r/gdrive)
21
- [![](https://images.microbadger.com/badges/version/d0whc3r/gdrive.svg)](https://hub.docker.com/r/d0whc3r/gdrive)
22
- [![](https://images.microbadger.com/badges/image/d0whc3r/gdrive.svg)](https://hub.docker.com/r/d0whc3r/gdrive)
23
-
24
- [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fd0whc3r%2Fnode-gdrive.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2Fd0whc3r%2Fnode-gdrive?ref=badge_shield)
17
+ ```bash
18
+ docker run --rm d0whc3r/gdrive --help
25
19
 
26
- ## :key: Create credentials and token files
20
+ # Mount your secrets folder read-only and list files
21
+ docker run --rm -v "$PWD/secrets:/app/secrets:ro" d0whc3r/gdrive -l
27
22
 
28
- To get `credentials.json` file you need to visit:
29
- - [https://developers.google.com/drive/api/v3/quickstart/nodejs](https://developers.google.com/drive/api/v3/quickstart/nodejs)
23
+ # Back up a local directory into Google Drive
24
+ docker run --rm \
25
+ -v "$PWD/secrets:/app/secrets:ro" \
26
+ -v "$PWD/data:/data:ro" \
27
+ d0whc3r/gdrive -b /data -z backup.zip -f backups/daily -c -r
28
+ ```
30
29
 
31
- Then click `ENABLE THE DRIVE API` and click `DOWNLOAD CLIENT CONFIGURATION`
30
+ ### 2. npx / npm (Node.js >= 26)
32
31
 
33
- This will download **credentials.json** file, you can save it in *secrets* folder in the project.
34
- Now you need to generate **token.json** file, to do this you need to execute any command to access your google-drive, for example:
32
+ ```bash
33
+ # Run on demand
34
+ npx @d0whc3r/node-gdrive --help
35
35
 
36
- ### :boat: Using docker
36
+ # Or install globally
37
+ npm install -g @d0whc3r/node-gdrive
38
+ node-gdrive --help
39
+ ```
37
40
 
38
- Then you could execute a simple command to generate token.json:
41
+ ### 3. Standalone Binary (No Node.js required)
39
42
 
40
- > Be careful to copy `credentials.json` into `$PWD/secrets` path
43
+ Download the prebuilt `node-gdrive` (Linux / macOS) or `node-gdrive.exe` (Windows) executable from [GitHub Releases](https://github.com/d0whc3r/node-gdrive/releases) and run it directly:
41
44
 
42
45
  ```bash
43
- docker run --rm -it -v $PWD/secrets:/app/secrets/ d0whc3r/gdrive -l
46
+ chmod +x ./node-gdrive
47
+ ./node-gdrive --help
44
48
  ```
45
49
 
46
- ### :pencil: Using downloaded project
50
+ ---
47
51
 
48
- > First you need to download project from github using:
52
+ ## Authentication Setup
49
53
 
50
- ```bash
51
- git clone https://github.com/d0whc3r/node-gdrive.git
52
- cd node-gdrive
53
- yarn install
54
- ```
54
+ ### Option A: Service Account (Recommended for Servers, Cron & Docker)
55
55
 
56
- Then you could execute a simple command to generate token.json:
56
+ 1. In [Google Cloud Console](https://console.cloud.google.com/), enable the **Google Drive API**, create a **Service Account**, and download its JSON key to `./secrets/service-account.json`.
57
+ 2. Share your target Google Drive folder or **Shared Drive** with the Service Account email address.
58
+ 3. Run with `GOOGLE_APPLICATION_CREDENTIALS` or `--service-account`:
57
59
 
58
60
  ```bash
59
- yarn cli -l
61
+ GOOGLE_APPLICATION_CREDENTIALS=./secrets/service-account.json \
62
+ node-gdrive -l --drive-id <SHARED_DRIVE_ID>
60
63
  ```
61
64
 
62
- ### :beginner: Next step
65
+ ### Option B: OAuth2 Desktop App (Personal Google Drive)
66
+
67
+ 1. In [Google Cloud Console](https://console.cloud.google.com/), enable the **Google Drive API**, create an **OAuth 2.0 Desktop App** client, and save the JSON as `./secrets/credentials.json`.
68
+ 2. Run any command (for example, `node-gdrive -l`).
69
+ 3. Open the printed authorization URL in your browser and approve access. `node-gdrive` captures the callback automatically via a temporary local loopback server (`http://127.0.0.1:<port>/oauth2callback`, PKCE + `state`) and saves `./secrets/token.json` with `0600` permissions.
63
70
 
64
- Using docker or project files the `-l` command is for listing existing files in google-drive
71
+ ---
65
72
 
66
- If *credentials.json* is present but *token.json* is missing this last file will be generated showing an url into terminal output, you need to enter that url and validate all needed permisions, then a token will be shown in your web browser, this token need to be pasted in terminal.
73
+ ## Common Usage Examples
67
74
 
68
- By default this software check for credentials (and token) file in folder `secrets` but it could be changed using environment variables:
69
- - **CREDENTIALS_FILE**: File with credentials (credentials.json)
70
- - **TOKEN_FILE**: File with token, generated using credentials (token.json)
75
+ ```bash
76
+ # List files (human-readable or JSON for scripts)
77
+ node-gdrive -l
78
+ node-gdrive -l --json
71
79
 
72
- ## :boat: Docker usage
80
+ # Back up files or globs to a nested folder (creating missing folders)
81
+ node-gdrive -b "src/*" -b package.json -f backups/app -c -r
73
82
 
74
- You could use cli app in docker
83
+ # Back up as a ZIP archive, excluding logs, with client-side AES-256-GCM encryption
84
+ BACKUP_ENCRYPTION_KEY="my-strong-passphrase" \
85
+ node-gdrive -b "./data/*" --exclude "*.log" -z backup.zip -f backups -c -r --encrypt
75
86
 
76
- ### :rowboat: Build docker image
87
+ # Download and decrypt a backup
88
+ BACKUP_ENCRYPTION_KEY="my-strong-passphrase" \
89
+ node-gdrive --download backup.zip.enc -f backups -o ./backup.zip --encrypt
77
90
 
78
- ```bash
79
- docker build -t gdrive .
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
93
+
94
+ # Preview retention cleanup safely before deleting anything
95
+ node-gdrive -f backups/daily -d 30d --keep-last 5 --dry-run
96
+
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
80
100
  ```
81
101
 
82
- ### :checkered_flag: Run cli commands inside docker
102
+ ---
103
+
104
+ ## Environment Variables
105
+
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` |
114
+
115
+ See [example.env](./example.env) for a ready-to-copy template.
116
+
117
+ ---
118
+
119
+ ## CLI Options
120
+
121
+ | Flag | Alias | Description |
122
+ | -------------------------- | ----- | ---------------------------------------------------------------------- |
123
+ | `--list` | `-l` | List files and folders |
124
+ | `--backup <file*>` | `-b` | Upload files, directories, or globs (repeatable) |
125
+ | `--download <id-or-name>` | — | Download a file by ID or name |
126
+ | `--output <path>` | `-o` | Local destination path for `--download` |
127
+ | `--folder <path>` | `-f` | Destination folder path (supports nested paths like `backups/daily`) |
128
+ | `--zip [filename.zip]` | `-z` | Compress backup files into a ZIP archive |
129
+ | `--exclude <glob>` | — | Exclude files matching glob pattern (repeatable) |
130
+ | `--replace` | `-r` | Replace existing file in target folder on upload |
131
+ | `--create` | `-c` | Create destination folder(s) if they do not exist |
132
+ | `--delete <rule>` | `-d` | Delete files older than duration (`folder=7d` or `7d`, repeatable) |
133
+ | `--keep-last <N>` | — | Always preserve the N newest matching files when deleting |
134
+ | `--dry-run` | — | Preview uploads/deletions without modifying Drive |
135
+ | `--encrypt` | — | Encrypt on upload / decrypt on download using `$BACKUP_ENCRYPTION_KEY` |
136
+ | `--stdin` | — | Read upload payload from standard input (requires `--name`) |
137
+ | `--name <filename>` | — | Filename when uploading from `--stdin` |
138
+ | `--mysql` | `-m` | Create and upload a MySQL dump using `$MYSQL_*` env vars |
139
+ | `--drive-id <id>` | — | Target a Google Workspace Shared Drive |
140
+ | `--service-account <path>` | — | Path to a Service Account JSON key |
141
+ | `--json` | — | Output machine-readable JSON (ideal for CI/scripts) |
142
+ | `--quiet` | `-q` | Suppress informational logs |
143
+ | `--version` | `-v` | Print CLI version |
144
+ | `--help` | `-h` | Print usage guide |
145
+
146
+ ### Valid Duration Units (`-d`)
147
+
148
+ | Unit | Meaning | Example |
149
+ | ---- | ------- | ------- |
150
+ | `s` | Seconds | `30s` |
151
+ | `m` | Minutes | `15m` |
152
+ | `h` | Hours | `24h` |
153
+ | `d` | Days | `7d` |
154
+ | `w` | Weeks | `2w` |
155
+ | `M` | Months | `1M` |
156
+ | `y` | Years | `1y` |
157
+
158
+ > Unrecognized units are rejected immediately to prevent accidental deletions.
159
+
160
+ ### Exit Codes
161
+
162
+ - `0`: Success (or `--help` / `--version`).
163
+ - `1`: Runtime or Google Drive API error.
164
+ - `2`: Invalid CLI arguments or missing required options.
165
+
166
+ ---
167
+
168
+ ## Using as a Node.js Library
83
169
 
84
170
  ```bash
85
- docker run --rm gdrive --help
171
+ npm install @d0whc3r/node-gdrive
86
172
  ```
87
- To make docker image work properly you need to indicate where credentials and token are located
88
173
 
89
- ```bash
90
- docker run --rm -v $PWD/secrets:/app/secrets:ro gdrive -l
174
+ ### ESM / TypeScript
175
+
176
+ ```ts
177
+ import { GDrive } from '@d0whc3r/node-gdrive';
178
+
179
+ const gdrive = new GDrive({
180
+ serviceAccountFile: './secrets/service-account.json',
181
+ sharedDriveId: '0AAxxxxxxxxUk9PVA',
182
+ concurrency: 4
183
+ });
184
+
185
+ // Upload with ZIP compression, exclusions, and AES-256-GCM encryption
186
+ await gdrive.uploadFiles(['./data/*'], 'backups/daily', {
187
+ create: true,
188
+ replace: true,
189
+ compress: 'daily.zip',
190
+ exclude: ['*.log', '*.tmp'],
191
+ encryptKey: process.env.BACKUP_ENCRYPTION_KEY
192
+ });
193
+
194
+ // Download and decrypt
195
+ await gdrive.downloadFile('daily.zip.enc', './restore/daily.zip', {
196
+ folderName: 'backups/daily',
197
+ decryptKey: process.env.BACKUP_ENCRYPTION_KEY
198
+ });
199
+
200
+ // Delete files older than 14 days while keeping at least the 5 newest
201
+ await gdrive.cleanOlder('14d', 'backups/daily', { keepLast: 5 });
91
202
  ```
92
203
 
93
- ## :checkered_flag: Cli help output
204
+ ### CommonJS
94
205
 
95
- Using docker image from [hub.docker.com](https://hub.docker.com/r/d0whc3r/gdrive)
206
+ ```js
207
+ const { GDrive } = require('@d0whc3r/node-gdrive');
96
208
 
97
- ```bash
98
- docker run --rm d0whc3r/gdrive --help
209
+ const gdrive = new GDrive();
210
+ gdrive.listFiles().then((files) => console.log(files));
99
211
  ```
100
212
 
101
- ```
102
- Help for gdrive
103
-
104
- Usage of npm gdrive in command line.
105
-
106
- Options
107
-
108
- -l, --list List all files and folders
109
- -b, --backup file* Backup files
110
- -z, --zip zipname.zip Zip backup files
111
- -r, --replace Replace files if already exists when backup upload
112
- -c, --create Create destination upload folder
113
- -f, --folder foldername Folder name to upload file/s
114
- -d, --delete foldername=duration OR duration Clean files older than duration in foldername
115
- -m, --mysql Mysql backup using environment variables to connect mysql server
116
- ($MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE, $MYSQL_HOST, $MYSQL_PORT)
117
- -h, --help Print this usage guide.
118
-
119
- Examples
120
-
121
- 1. List files. $ gdrive -l
122
- 2. Backup multiple files to "backupFolder" folder. $ gdrive -b src/index.ts -b images/logo.png -f backupFolder
123
- 3. Backup files using wildcard to "backup" folder. $ gdrive -b src/* -b images/* -f backup
124
- 4. Backup files using wildcard and zip into "zipped" folder folder will be $ gdrive -b src/* -b images/* -z -f zipped -c
125
- created if it doesn't exists.
126
- 5. Backup files using wildcard and zip using "allfiles.zip" as filename into $ gdrive -b src/* -b images/* -z allfiles.zip -f zipped -c -r
127
- "zipped" folder folder will be created if it doesn't exists and zipfile will be
128
- replaced if it exists
129
- 6. Delete files in "uploads" folder older than 2days and files in "monthly" $ gdrive -d uploads=2d -d monthly=1M
130
- folder older than 1month
131
- 7. Delete files in "uploads" folder older than 1minute $ gdrive -f uploads -d 1m
132
- 8. Generate mysql dump file zip it and upload to "mysql-backup" folder $ gdrive -f mysql-backup -m -z
133
- ```
213
+ ---
134
214
 
215
+ ## Contributing, Security & License
135
216
 
136
- ## License
137
- [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fd0whc3r%2Fnode-gdrive.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fd0whc3r%2Fnode-gdrive?ref=badge_large)
217
+ - Want to contribute or build from source? See [CONTRIBUTING.md](./CONTRIBUTING.md).
218
+ - Found a security issue? See [SECURITY.md](./SECURITY.md).
219
+ - Released under the [MIT License](./LICENSE).
package/bin/cli.js CHANGED
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
- "use strict";function _interopDefault(a){return a&&typeof a==="object"&&"default"in a?a.default:a}var commandLineArgs=_interopDefault(require("command-line-args")),commandLineUsage=_interopDefault(require("command-line-usage")),googleapis=require("googleapis"),fs=require("fs"),fs__default=_interopDefault(fs),mime=_interopDefault(require("mime-types")),path2=require("path"),path2__default=_interopDefault(path2),archiver2=_interopDefault(require("archiver")),moment2=_interopDefault(require("moment")),glob2=_interopDefault(require("glob")),readline2=_interopDefault(require("readline")),colors2=_interopDefault(require("colors")),os2=_interopDefault(require("os")),mysqldump2=_interopDefault(require("mysqldump"));const optionDefinitions=[{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"},{name:"zip",alias:"z",typeLabel:"{underline zipname.zip}",multiple:!1,type:String,description:"Zip backup files"},{name:"replace",alias:"r",multiple:!1,type:Boolean,description:"Replace files if already exists when backup upload"},{name:"create",alias:"c",multiple:!1,type:Boolean,description:"Create destination upload folder"},{name:"folder",alias:"f",typeLabel:"{underline foldername}",multiple:!1,type:String,description:"Folder name to upload file/s"},{name:"delete",alias:"d",typeLabel:"{underline foldername=duration} OR {underline duration}",multiple:!0,type:String,description:"Clean files older than duration in foldername"},{name:"mysql",alias:"m",multiple:!1,type:Boolean,description:"Mysql backup using environment variables to connect mysql server ($MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE, $MYSQL_HOST, $MYSQL_PORT)"},{name:"help",alias:"h",description:"Print this usage guide.",type:Boolean}];let options={};try{options=commandLineArgs(optionDefinitions)}catch(a){console.error("[-] Error:",a.message),process.exit(1)}if(options.help||!Object.keys(options).length){const a="node-gdrive",c=[{header:`Help for ${a}`,content:`Usage of npm {italic ${a}} in command line.`},{header:"Options",optionList:optionDefinitions},{header:"Examples",content:[{desc:"1. List files.",example:`$ ${a} -l`},{desc:'2. Backup multiple files to "backupFolder" folder.',example:`$ ${a} -b src/index.ts -b images/logo.png -f backupFolder`},{desc:'3. Backup files using wildcard to "backup" folder.',example:`$ ${a} -b src/* -b images/* -f backup`},{desc:`4. Backup files using wildcard and zip into "zipped" folder, folder will be created if it doesn't exists.`,example:`$ ${a} -b src/* -b images/* -z -f zipped.zip -c`},{desc:`5. Backup files using wildcard and zip using "allfiles.zip" as filename into "zipped" folder, folder will be created if it doesn't exists and zipfile will be replaced if it exists`,example:`$ ${a} -b src/* -b images/* -z allfiles.zip -f zipped -c -r`},{desc:'6. Delete files in "uploads" folder older than 2days and files in "monthly" folder older than 1month',example:`$ ${a} -d uploads=2d -d monthly=1M`},{desc:'7. Delete files in "uploads" folder older than 1minute',example:`$ ${a} -f uploads -d 1m`},{desc:'8. Generate mysql dump file zip it and upload to "mysql-backup" folder',example:`$ ${a} -f mysql-backup -m -z`}]}];console.info(commandLineUsage(c)),process.exit(0)}class Config{}Config.TOKEN_FILE=process.env.TOKEN_FILE||"./secrets/token.json",Config.CREDENTIALS_FILE=process.env.CREDENTIALS_FILE||"./secrets/credentials.json",Config.TAG="[node-gdrive]";class FileUtils{static mkdirp(a){const c=path2.sep,d=path2.isAbsolute(a)?c:"",b=a.split(c).reduce((f,g)=>{const e=path2.resolve(f,g);return fs.existsSync(e)||fs.mkdirSync(e),e},d);console.info(`${Config.TAG} Result file ${b}`)}}class Auth{constructor(){this.ready=!0,this.SCOPES=["https://www.googleapis.com/auth/drive","https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive.metadata","https://www.googleapis.com/auth/drive.metadata.readonly"],this.TOKEN_FILE=Config.TOKEN_FILE,this.CREDENTIALS_FILE=Config.CREDENTIALS_FILE,this.existsCredentials||(this.ready=!1,console.error(colors2.bold(`${Config.TAG} ERROR: Credentials file not found in ${this.CREDENTIALS_FILE}`).red))}get existsToken(){return fs.existsSync(this.TOKEN_FILE)}get existsCredentials(){return fs.existsSync(this.CREDENTIALS_FILE)}async initiate(){return this.ready?this.existsToken?Promise.resolve(!0):this.generateAccessToken():Promise.reject(!1)}oAuth2Client(a=!0){if(!this._oAuth2Client){const c=JSON.parse(fs.readFileSync(this.CREDENTIALS_FILE,"utf8")),{client_secret:d,client_id:b,redirect_uris:f}=c.installed;this._oAuth2Client=new googleapis.google.auth.OAuth2(b,d,f[0]);if(a){const g=JSON.parse(fs.readFileSync(this.TOKEN_FILE,"utf8"));this._oAuth2Client.setCredentials(g)}}return this._oAuth2Client}generateAccessToken(){return new Promise((a,c)=>{const d=this.oAuth2Client(!1).generateAuthUrl({access_type:"offline",scope:this.SCOPES});console.log(`${Config.TAG} Authorize this app by visiting this url:`,d);const b=readline2.createInterface({input:process.stdin,output:process.stdout});b.question(`${Config.TAG} Enter the code from that page here: `,f=>{b.close(),this.oAuthGetToken(f,{resolve:a,reject:c})})})}oAuthGetToken(a,c){this.oAuth2Client(!1).getToken(a).then(({tokens:d})=>{this.oAuth2Client(!1).setCredentials(d),this.writeToken(d,c)}).catch(d=>(console.error(colors2.bold(`${Config.TAG} Error retrieving access token`).red,d.message),c.reject(d)))}writeToken(a,{resolve:c,reject:d}){fs.writeFile(this.TOKEN_FILE,JSON.stringify(a),b=>{b?(console.error(b),void d(b)):(console.log(`${Config.TAG} Token stored to`,this.TOKEN_FILE),void c(!0))})}}var Params$Resource$Files$Get=googleapis.drive_v3.Params$Resource$Files$Get,Params$Resource$Files$List=googleapis.drive_v3.Params$Resource$Files$List,Params$Resource$Files$Create=googleapis.drive_v3.Params$Resource$Files$Create;const allFileTypes=["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"];class GDrive{constructor(){this.DEFAULT_FIELDS=["createdTime","id","md5Checksum","mimeType","name","parents","trashed"],this.MIME_FOLDER="application/vnd.google-apps.folder",this.gdriveAuth=new Auth(),this.initiated=this.gdriveAuth.initiate(),this.initiated.catch(()=>{const a=`${Config.TAG} ERROR! could not get credentials file. GDrive will not work`;throw console.error(a),new Error(a)})}get auth(){return this.gdriveAuth.oAuth2Client(!0)}get drive(){return googleapis.google.drive({version:"v3",auth:this.auth})}isFolder(a){return Object.prototype.hasOwnProperty.call(a,"mimeType")?a.mimeType===this.MIME_FOLDER:void 0}isDeleted(a){return Object.prototype.hasOwnProperty.call(a,"trashed")?!!a.trashed:!1}async listFiles(a,c=50){await this.initiated,a?a===!0&&(a=allFileTypes):a=this.DEFAULT_FIELDS;const d={pageSize:c,fields:`kind, nextPageToken, incompleteSearch, files(${a.join(", ")})`,prettyPrint:!0,includeTeamDriveItems:!1};return this.getListFiles(d)}async getFile(a){await this.initiated;if(!a)return Promise.reject(this.genericError(new Error("File id not found")));const c={fileId:a},d=this.drive.files.get(c).then(({data:b})=>b);return d.catch(b=>{this.genericError(b)}),d}async emptyTrash(){return await this.initiated,this.drive.files.emptyTrash()}async deleteFile(a){await this.initiated;if(a.id){const c=this.drive.files.delete({fileId:a.id}).then(({data:d})=>(a.name&&console.warn(`${Config.TAG} Deleted ${a.isFolder?"folder":"file"}: ${a.name}`),d));return c.catch(d=>{this.genericError(d)}),c}}async uploadFile(a,c,d={}){await this.initiated;const{create:b=!0,replace:f=!1}=d,g=path2__default.basename(a),e=mime.contentType(g)||void 0,j={name:g,mimeType:e};let h=null;try{h=await this.getUploadFolderId(c||!1,b,j)}catch(k){return Promise.reject(k)}try{await this.replaceExistingFolder(f,g,h)}catch(k){return Promise.reject(k)}const i=fs__default.createReadStream(a),l={requestBody:j,media:{body:i},fields:`kind, ${this.DEFAULT_FIELDS.join(", ")}`},m=fs__default.statSync(a).size,p=k=>{const o=k.bytesRead/m*100;o===100&&console.warn(`${Config.TAG} Upload ${g}: ${Math.round(o)}% complete`)},n=this.drive.files.create(l,{onUploadProgress:p}).then(({data:k})=>this.parseFileMeta(k)).finally(()=>{i.destroy()});return n.catch(k=>{this.genericError(k)}),n}async uploadFiles(a,c,d={}){await this.initiated;const{compress:b,replace:f,create:g}=d;Array.isArray(a)||(a=[a]);let e=a;if(b){let h=b;typeof h!=="string"&&(h=`zipped_${moment2().format("YYYY-MM-DD.HHmmss")}.zip`);const i=await this.compressFiles(a,h);e=[i]}const j={};for(const h of e)if(h.includes("*"))await this.uploadFiles(glob2.sync(h),c,d);else if(fs__default.lstatSync(h).isDirectory())await this.uploadFiles(glob2.sync(`${h}/*`),c,d);else{const i=path2__default.basename(h),l=await this.uploadFile(h,c,{replace:f,create:g});j[i]=this.parseFileMeta(l)}return j}async cleanOlder(a,c){const d=/([0-9]+)(\w+)/.exec(a);if(!d)return console.error(`${Config.TAG} Unknown timesSpace "${a}"`),Promise.reject(!1);await this.initiated;let b="";if(c)try{b=await this.findFolderId(c,!1)}catch(f){return console.error("Could not find folder",c,f),Promise.reject(!1)}await this.deleteOlder(d,b)}getListFiles(a,c=[]){const d=this.drive.files.list(a).then(async({data:b})=>(c=c.concat(b.files),b.nextPageToken?(a.pageToken=b.nextPageToken,this.getListFiles(a,c)):c)).then(b=>this.parseFilesMeta(b));return d.catch(b=>{this.genericError(b)}),d}async replaceExistingFolder(a,c,d){if(a!==void 0){const b=await this.findFile(c,d);if(b)if(a)console.warn(`${Config.TAG} File "${c}" already exists and will be deleted before upload`),await this.deleteFile(b);else throw new Error(`${Config.TAG} File "${c}" already exists and will not be replaced`)}}async getUploadFolderId(a,c,d){let b="";if(a&&typeof a==="string"){b=await this.findFolderId(a,c===void 0?!0:c);if(b)d.parents=[b];else return Promise.reject(new Error(`${Config.TAG} Folder "${a}" does not exists and will not be created`))}return Promise.resolve(b)}async deleteOlder(a,c){const d=await this.listFiles();if(d&&d.length){const[,b,f]=a,g=d.filter(e=>!c||c&&!e.isFolder).filter(e=>!c||c&&e.parents&&e.parents.includes(c)).map(e=>({...e,toDelete:moment2(e.createdTime||void 0).isSameOrBefore(moment2().subtract(+b,f))})).filter(e=>e.toDelete);if(g&&g.length)for(const e of g)await this.deleteFile(e)}}parseFileMeta(a){return{...a,isDeleted:this.isDeleted(a),isFolder:!!this.isFolder(a)}}parseFilesMeta(a){return[...a].map(c=>this.parseFileMeta(c))}genericError(a){return console.error(`${Config.TAG} The API returned an error: ${a}`),a}async findFolderId(a,c=!1){const d=(await this.listFiles()).filter(b=>b.isFolder).filter(b=>!b.isDeleted).filter(b=>b.name===a).map(b=>b.id);if(d&&d.length)return Promise.resolve(d[0]||"");if(c){const b=await this.createFolder(a);return Promise.resolve(b.id||"")}return Promise.reject(!1)}async findFile(a,c){const d=(await this.listFiles()).filter(b=>!b.isFolder).filter(b=>!b.isDeleted).filter(b=>b.name===a).filter(b=>!c||b.parents&&b.parents.some(f=>f===c));return d&&d.length?d[0]:null}async createFolder(a){const c=this.drive.files.create({requestBody:{name:a,mimeType:this.MIME_FOLDER},fields:"id"}).then(({data:b})=>b);c.catch(b=>{this.genericError(b)});const d=await c;return d?.id&&console.warn(`${Config.TAG} Created folder "${a}" with id: "${d.id}"`),d}compressFiles(a,c){return new Promise((d,b)=>{const f=os2.tmpdir(),g=path2__default.resolve(f,c);FileUtils.mkdirp(path2__default.dirname(g));const e=fs__default.createWriteStream(g),j=[],h=archiver2("zip",{zlib:{level:9}});e.on("close",()=>{d(g),e.destroy()}),e.on("end",()=>{d(g),e.destroy()}),h.on("warning",i=>{console.warn(`${Config.TAG} Warning compressing file`,i),i.code!=="ENOENT"&&b(i)}),h.on("error",i=>{console.error(`${Config.TAG} Error compressing file`),b(i)}),h.pipe(e),a.forEach(i=>{if(i.includes("*"))h.glob(i);else if(fs__default.lstatSync(i).isDirectory())h.directory(i,!1);else{const l=path2__default.basename(i),m=fs__default.createReadStream(i);h.append(m,{name:l}),j.push(m)}}),h.finalize().finally(()=>{j.forEach(i=>{i.destroy()})})})}}const theme={folder:"cyan",error:"red"};colors2.setTheme(theme);class Cli{constructor(a=options,c=new GDrive()){this.opts=a,this.gdrive=c}async parseOptions(){for(const a in this.opts)if(Object.prototype.hasOwnProperty.call(this.opts,a)){const c=this.opts[a],d=this.opts.zip,b=this.opts.folder,f=this.opts.replace,g=this.opts.create;switch(a){case"backup":await this.backup(c,{zip:d,folder:b,replace:f,create:g});break;case"delete":await this.delete(c,b);break;case"mysql":await this.dumpMysql({zip:d,folder:b,replace:f,create:g});break;case"list":await this.showList();break}}}async showList(){const a=(await this.gdrive.listFiles()).filter(c=>!c.isDeleted);a.length?(console.info(`${Config.TAG} File list: ${a.length}`),this.beautifulFiles(a)):console.info(`${Config.TAG} No files found.`)}async delete(a,c){Array.isArray(a)||(a=[a]);const d=a.map(b=>this.parseDelete(b)).map(b=>(b.folder||(b.folder=c||null),{...b}));try{for(const b of d){const{folder:f,timeSpace:g}=b;await this.gdrive.cleanOlder(g,f||void 0)}}catch(b){console.error(`${Config.TAG} Error in delete files`)}}async backup(a,c){const{zip:d,folder:b,replace:f,create:g}=c;Array.isArray(a)||(a=[a]),await this.gdrive.uploadFiles(a,b||!1,{compress:d||d===null,replace:f,create:g})}async dumpMysql(a){let c="";try{c=await this.createDumpFile()}catch(d){console.error(colors2.bold[theme.error](`${Config.TAG} Error mysql ${d}`)),process.exit(-1)}await this.backup(c,a)}parseDelete(a){let c,d;const b=a.split("=");return b.length>1?(c=b[0],d=b[1]):(d=a,c=null),{folder:c,timeSpace:d}}findFile(a,c){const d=a.find(b=>b.id===c);return d?d.name:null}beautifulFiles(a){const c=a.map(d=>{const b=d&&d.parents&&d.parents[0];return{...d,parentFolder:this.findFile(a,b)}});c.sort((d,b)=>this.sortByName(d,b)),c.sort((d,b)=>this.sortByParent(d,b)),c.sort((d,b)=>this.sortByFolder(d,b)),c.forEach(d=>{const b=d.isFolder?this.showFolder(d.name):d.name,f=d.parentFolder?this.showFolder(`${d.parentFolder}/`):"";console.info(`${f}${b||""}`)})}sortByName(a,c){return a.name&&c.name?a.name.localeCompare(c.name):0}sortByFolder(a,c){return a.isFolder&&!c.isFolder?-1:!a.isFolder&&c.isFolder?1:0}sortByParent(a,c){return a.parentFolder&&c.parentFolder||!a.parentFolder&&!c.parentFolder?0:!a.parentFolder&&c.parentFolder?1:-1}showFolder(a){return a?colors2.bold[theme.folder](a):""}createDumpFile(){const a=process.env.MYSQL_HOST||"localhost",c=+(process.env.MYSQL_PORT||3306),d=process.env.MYSQL_USER||"",b=process.env.MYSQL_PASSWORD||"",f=process.env.MYSQL_DATABASE||"";return(!d||!b||!f)&&(console.error(`${Config.TAG} Error in mysql-dump environment variables not defined`),console.error("$MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE, $MYSQL_HOST, $MYSQL_PORT"),process.exit(-1)),mysqldump2({connection:{host:a,port:c,user:d,password:b,database:f}}).then(({dump:g})=>{const e=`./files/mysqldump-${moment2().format("YYYY-MM-DD.HHmmss")}.sql`;FileUtils.mkdirp(path2__default.dirname(e));const j=Object.values(g).map(h=>h&&h.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: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.4.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`},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(!e||typeof e!=`object`)return!1;let t=e,n=typeof t.status==`number`?t.status:typeof t.code==`number`?t.code:typeof t.response?.status==`number`?t.response.status:void 0;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 K(e,t={}){let{maxRetries:n=4,baseDelayMs:r=500,maxDelayMs:i=16e3,jitter:a=!0,sleep:o=W}=t,s=0;for(;;)try{return await e()}catch(e){if(s>=n||!G(e))throw e;let t=Math.min(i,r*2**s),c=a?Math.round(t*(.5+Math.random()*.5)):t;s+=1,await o(c)}}var q=`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 J=new Set(q),Y=/^(\d+)(s|m|h|d|w|M|y|seconds?|minutes?|hours?|days?|weeks?|months?|years?)$/,X={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=Y.exec(e);if(!t)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 n=Number(t[1]),r=X[t[2]];if(!Number.isFinite(n)||n<=0||!r)throw Error(`${A.TAG} Invalid timeSpace "${e}": amount must be a positive integer.`);return{amount:n,unit:r}}async function $(e,t,n){let r=Math.max(1,Math.floor(t)),i=Array.from({length:e.length}),a=0;async function o(){for(;a<e.length;){let t=a;a+=1,i[t]=await n(e[t])}}let s=Array.from({length:Math.min(r,e.length)},()=>o());return await Promise.all(s),i}var te=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=q;else{for(let t of e)if(!J.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 K(()=>this.drive.files.get(t),this.retryOptions);return e}catch(e){throw this.genericError(e)}}async downloadFile(e,t,n={}){if(await this.ensureInitiated(),!e)throw Error(`${A.TAG} File id or name is required for download`);let r=e;if(n.folderName){let t=await this.findFolderId(n.folderName,!1),i=await this.findFile(e,t);if(!i?.id)throw Error(`${A.TAG} File "${e}" not found in folder "${n.folderName}"`);r=i.id}else try{let t=await K(()=>this.drive.files.get({fileId:e,fields:`id, name, mimeType`,...this.sharedDriveItemParams}),this.retryOptions);t.data.id&&(r=t.data.id)}catch{let t=await this.findFile(e);if(!t?.id)throw Error(`${A.TAG} File "${e}" not found`);r=t.id}f.default.mkdirSync(m.default.dirname(m.default.resolve(t)),{recursive:!0});let i,a=n.decryptKey?(i=this.createPrivateTempDir(),m.default.join(i,`download.enc`)):t;try{let e=await K(()=>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(),K(()=>this.drive.files.emptyTrash(),this.retryOptions)}async deleteFile(e){if(await this.ensureInitiated(),e.id)try{let{data:t}=await K(()=>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 K(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}=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=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;try{do{let r=n?{...e,pageToken:n}:{...e},{data:i}=await K(()=>this.drive.files.list(r),this.retryOptions);i.files?.length&&t.push(...i.files),n=i.nextPageToken??void 0}while(n);return 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(`'${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,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}"`);let r=this.rootParentId;for(let i of n){let n=[`name = '${Z(i)}'`,`mimeType = '${this.MIME_FOLDER}'`,`trashed = false`,`'${Z(r)}' in parents`].join(` and `),a=(await this.listFiles(void 0,100,n)).find(e=>e.isFolder&&!e.isDeleted&&e.name===i&&e.id);if(a?.id)r=a.id;else if(t){let e=await this.createFolder(i,r);if(!e.id)throw Error(`${A.TAG} Failed to create folder "${i}"`);r=e.id}else throw Error(`${A.TAG} Folder "${e}" does not exist and will not be created`)}return r}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 K(()=>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 ne(e){return e?{info:()=>{},warn:()=>{},error:(...e)=>console.error(...e)}:console}var re=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 te({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=[];for(let e of r){let t=await this.gdrive.cleanOlder(e.timeSpace,e.folder,{dryRun:n.dryRun,keepLast:n.keepLast});i.push(...t)}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(`
3
3
 
4
- `);return fs__default.writeFileSync(e,j),e})}}void(async()=>{await new Cli().parseOptions()})();
4
+ `);return f.default.writeFileSync(s,c,{mode:384}),{dumpPath:s,tempDir:o}}};async function ie(){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 re(e).parseOptions(),process.exitCode=0)}ie().catch(e=>{let t=e instanceof Error?e.message:String(e);console.error((0,l.styleText)([`bold`,`red`],`[-] Error: ${t}`)),process.exitCode=1});
package/dist/auth.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ import { GoogleAuth, OAuth2Client } from 'google-auth-library';
2
+ import type { AuthConfig } from './types';
3
+ export declare const DEFAULT_SCOPES: string[];
4
+ export default class Auth {
5
+ ready: boolean;
6
+ private readonly scopes;
7
+ private readonly tokenFile;
8
+ private readonly credentialsFile;
9
+ private readonly serviceAccountFile?;
10
+ private readonly useADC;
11
+ private readonly logger;
12
+ private _oAuth2Client?;
13
+ private _googleAuth?;
14
+ constructor(config?: AuthConfig);
15
+ get isServiceAccountOrADC(): boolean;
16
+ private get existsToken();
17
+ private get existsCredentials();
18
+ initiate(): Promise<boolean>;
19
+ getAuthClient(): OAuth2Client | GoogleAuth;
20
+ googleAuthClient(): GoogleAuth;
21
+ oAuth2Client(withToken?: boolean, redirectUri?: string): OAuth2Client;
22
+ private attachTokenListener;
23
+ private persistTokenSync;
24
+ private generateAccessToken;
25
+ }
@@ -0,0 +1,16 @@
1
+ export default class Config {
2
+ private static _tokenFile?;
3
+ private static _credentialsFile?;
4
+ private static _serviceAccountFile?;
5
+ private static _tag?;
6
+ static get TOKEN_FILE(): string;
7
+ static set TOKEN_FILE(value: string);
8
+ static get CREDENTIALS_FILE(): string;
9
+ static set CREDENTIALS_FILE(value: string);
10
+ static get SERVICE_ACCOUNT_FILE(): string | undefined;
11
+ static set SERVICE_ACCOUNT_FILE(value: string | undefined);
12
+ static get BACKUP_ENCRYPTION_KEY(): string | undefined;
13
+ static get TAG(): string;
14
+ static set TAG(value: string);
15
+ static reset(): void;
16
+ }
@@ -0,0 +1,4 @@
1
+ export declare function encryptBuffer(plaintext: Buffer, passphrase: string): Buffer;
2
+ export declare function decryptBuffer(payload: Buffer, passphrase: string): Buffer;
3
+ export declare function encryptFile(inputPath: string, outputPath: string, passphrase: string): Promise<string>;
4
+ export declare function decryptFile(inputPath: string, outputPath: string, passphrase: string): Promise<string>;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});function _interopDefault(a){return a&&typeof a==="object"&&"default"in a?a.default:a}var googleapis=require("googleapis"),fs=require("fs"),fs__default=_interopDefault(fs),mime=_interopDefault(require("mime-types")),path2=require("path"),path2__default=_interopDefault(path2),archiver2=_interopDefault(require("archiver")),moment2=_interopDefault(require("moment")),glob2=_interopDefault(require("glob")),readline2=_interopDefault(require("readline")),colors2=_interopDefault(require("colors")),os2=_interopDefault(require("os"));class Config{}Config.TOKEN_FILE=process.env.TOKEN_FILE||"./secrets/token.json",Config.CREDENTIALS_FILE=process.env.CREDENTIALS_FILE||"./secrets/credentials.json",Config.TAG="[node-gdrive]";class FileUtils{static mkdirp(a){const c=path2.sep,d=path2.isAbsolute(a)?c:"",b=a.split(c).reduce((i,h)=>{const e=path2.resolve(i,h);return fs.existsSync(e)||fs.mkdirSync(e),e},d);console.info(`${Config.TAG} Result file ${b}`)}}class Auth{constructor(){this.ready=!0,this.SCOPES=["https://www.googleapis.com/auth/drive","https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive.metadata","https://www.googleapis.com/auth/drive.metadata.readonly"],this.TOKEN_FILE=Config.TOKEN_FILE,this.CREDENTIALS_FILE=Config.CREDENTIALS_FILE,this.existsCredentials||(this.ready=!1,console.error(colors2.bold(`${Config.TAG} ERROR: Credentials file not found in ${this.CREDENTIALS_FILE}`).red))}get existsToken(){return fs.existsSync(this.TOKEN_FILE)}get existsCredentials(){return fs.existsSync(this.CREDENTIALS_FILE)}async initiate(){return this.ready?this.existsToken?Promise.resolve(!0):this.generateAccessToken():Promise.reject(!1)}oAuth2Client(a=!0){if(!this._oAuth2Client){const c=JSON.parse(fs.readFileSync(this.CREDENTIALS_FILE,"utf8")),{client_secret:d,client_id:b,redirect_uris:i}=c.installed;this._oAuth2Client=new googleapis.google.auth.OAuth2(b,d,i[0]);if(a){const h=JSON.parse(fs.readFileSync(this.TOKEN_FILE,"utf8"));this._oAuth2Client.setCredentials(h)}}return this._oAuth2Client}generateAccessToken(){return new Promise((a,c)=>{const d=this.oAuth2Client(!1).generateAuthUrl({access_type:"offline",scope:this.SCOPES});console.log(`${Config.TAG} Authorize this app by visiting this url:`,d);const b=readline2.createInterface({input:process.stdin,output:process.stdout});b.question(`${Config.TAG} Enter the code from that page here: `,i=>{b.close(),this.oAuthGetToken(i,{resolve:a,reject:c})})})}oAuthGetToken(a,c){this.oAuth2Client(!1).getToken(a).then(({tokens:d})=>{this.oAuth2Client(!1).setCredentials(d),this.writeToken(d,c)}).catch(d=>(console.error(colors2.bold(`${Config.TAG} Error retrieving access token`).red,d.message),c.reject(d)))}writeToken(a,{resolve:c,reject:d}){fs.writeFile(this.TOKEN_FILE,JSON.stringify(a),b=>{b?(console.error(b),void d(b)):(console.log(`${Config.TAG} Token stored to`,this.TOKEN_FILE),void c(!0))})}}var Params$Resource$Files$Get=googleapis.drive_v3.Params$Resource$Files$Get,Params$Resource$Files$List=googleapis.drive_v3.Params$Resource$Files$List,Params$Resource$Files$Create=googleapis.drive_v3.Params$Resource$Files$Create;const allFileTypes=["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"];class GDrive{constructor(){this.DEFAULT_FIELDS=["createdTime","id","md5Checksum","mimeType","name","parents","trashed"],this.MIME_FOLDER="application/vnd.google-apps.folder",this.gdriveAuth=new Auth(),this.initiated=this.gdriveAuth.initiate(),this.initiated.catch(()=>{const a=`${Config.TAG} ERROR! could not get credentials file. GDrive will not work`;throw console.error(a),new Error(a)})}get auth(){return this.gdriveAuth.oAuth2Client(!0)}get drive(){return googleapis.google.drive({version:"v3",auth:this.auth})}isFolder(a){return Object.prototype.hasOwnProperty.call(a,"mimeType")?a.mimeType===this.MIME_FOLDER:void 0}isDeleted(a){return Object.prototype.hasOwnProperty.call(a,"trashed")?!!a.trashed:!1}async listFiles(a,c=50){await this.initiated,a?a===!0&&(a=allFileTypes):a=this.DEFAULT_FIELDS;const d={pageSize:c,fields:`kind, nextPageToken, incompleteSearch, files(${a.join(", ")})`,prettyPrint:!0,includeTeamDriveItems:!1};return this.getListFiles(d)}async getFile(a){await this.initiated;if(!a)return Promise.reject(this.genericError(new Error("File id not found")));const c={fileId:a},d=this.drive.files.get(c).then(({data:b})=>b);return d.catch(b=>{this.genericError(b)}),d}async emptyTrash(){return await this.initiated,this.drive.files.emptyTrash()}async deleteFile(a){await this.initiated;if(a.id){const c=this.drive.files.delete({fileId:a.id}).then(({data:d})=>(a.name&&console.warn(`${Config.TAG} Deleted ${a.isFolder?"folder":"file"}: ${a.name}`),d));return c.catch(d=>{this.genericError(d)}),c}}async uploadFile(a,c,d={}){await this.initiated;const{create:b=!0,replace:i=!1}=d,h=path2__default.basename(a),e=mime.contentType(h)||void 0,k={name:h,mimeType:e};let f=null;try{f=await this.getUploadFolderId(c||!1,b,k)}catch(j){return Promise.reject(j)}try{await this.replaceExistingFolder(i,h,f)}catch(j){return Promise.reject(j)}const g=fs__default.createReadStream(a),l={requestBody:k,media:{body:g},fields:`kind, ${this.DEFAULT_FIELDS.join(", ")}`},m=fs__default.statSync(a).size,p=j=>{const o=j.bytesRead/m*100;o===100&&console.warn(`${Config.TAG} Upload ${h}: ${Math.round(o)}% complete`)},n=this.drive.files.create(l,{onUploadProgress:p}).then(({data:j})=>this.parseFileMeta(j)).finally(()=>{g.destroy()});return n.catch(j=>{this.genericError(j)}),n}async uploadFiles(a,c,d={}){await this.initiated;const{compress:b,replace:i,create:h}=d;Array.isArray(a)||(a=[a]);let e=a;if(b){let f=b;typeof f!=="string"&&(f=`zipped_${moment2().format("YYYY-MM-DD.HHmmss")}.zip`);const g=await this.compressFiles(a,f);e=[g]}const k={};for(const f of e)if(f.includes("*"))await this.uploadFiles(glob2.sync(f),c,d);else if(fs__default.lstatSync(f).isDirectory())await this.uploadFiles(glob2.sync(`${f}/*`),c,d);else{const g=path2__default.basename(f),l=await this.uploadFile(f,c,{replace:i,create:h});k[g]=this.parseFileMeta(l)}return k}async cleanOlder(a,c){const d=/([0-9]+)(\w+)/.exec(a);if(!d)return console.error(`${Config.TAG} Unknown timesSpace "${a}"`),Promise.reject(!1);await this.initiated;let b="";if(c)try{b=await this.findFolderId(c,!1)}catch(i){return console.error("Could not find folder",c,i),Promise.reject(!1)}await this.deleteOlder(d,b)}getListFiles(a,c=[]){const d=this.drive.files.list(a).then(async({data:b})=>(c=c.concat(b.files),b.nextPageToken?(a.pageToken=b.nextPageToken,this.getListFiles(a,c)):c)).then(b=>this.parseFilesMeta(b));return d.catch(b=>{this.genericError(b)}),d}async replaceExistingFolder(a,c,d){if(a!==void 0){const b=await this.findFile(c,d);if(b)if(a)console.warn(`${Config.TAG} File "${c}" already exists and will be deleted before upload`),await this.deleteFile(b);else throw new Error(`${Config.TAG} File "${c}" already exists and will not be replaced`)}}async getUploadFolderId(a,c,d){let b="";if(a&&typeof a==="string"){b=await this.findFolderId(a,c===void 0?!0:c);if(b)d.parents=[b];else return Promise.reject(new Error(`${Config.TAG} Folder "${a}" does not exists and will not be created`))}return Promise.resolve(b)}async deleteOlder(a,c){const d=await this.listFiles();if(d&&d.length){const[,b,i]=a,h=d.filter(e=>!c||c&&!e.isFolder).filter(e=>!c||c&&e.parents&&e.parents.includes(c)).map(e=>({...e,toDelete:moment2(e.createdTime||void 0).isSameOrBefore(moment2().subtract(+b,i))})).filter(e=>e.toDelete);if(h&&h.length)for(const e of h)await this.deleteFile(e)}}parseFileMeta(a){return{...a,isDeleted:this.isDeleted(a),isFolder:!!this.isFolder(a)}}parseFilesMeta(a){return[...a].map(c=>this.parseFileMeta(c))}genericError(a){return console.error(`${Config.TAG} The API returned an error: ${a}`),a}async findFolderId(a,c=!1){const d=(await this.listFiles()).filter(b=>b.isFolder).filter(b=>!b.isDeleted).filter(b=>b.name===a).map(b=>b.id);if(d&&d.length)return Promise.resolve(d[0]||"");if(c){const b=await this.createFolder(a);return Promise.resolve(b.id||"")}return Promise.reject(!1)}async findFile(a,c){const d=(await this.listFiles()).filter(b=>!b.isFolder).filter(b=>!b.isDeleted).filter(b=>b.name===a).filter(b=>!c||b.parents&&b.parents.some(i=>i===c));return d&&d.length?d[0]:null}async createFolder(a){const c=this.drive.files.create({requestBody:{name:a,mimeType:this.MIME_FOLDER},fields:"id"}).then(({data:b})=>b);c.catch(b=>{this.genericError(b)});const d=await c;return d?.id&&console.warn(`${Config.TAG} Created folder "${a}" with id: "${d.id}"`),d}compressFiles(a,c){return new Promise((d,b)=>{const i=os2.tmpdir(),h=path2__default.resolve(i,c);FileUtils.mkdirp(path2__default.dirname(h));const e=fs__default.createWriteStream(h),k=[],f=archiver2("zip",{zlib:{level:9}});e.on("close",()=>{d(h),e.destroy()}),e.on("end",()=>{d(h),e.destroy()}),f.on("warning",g=>{console.warn(`${Config.TAG} Warning compressing file`,g),g.code!=="ENOENT"&&b(g)}),f.on("error",g=>{console.error(`${Config.TAG} Error compressing file`),b(g)}),f.pipe(e),a.forEach(g=>{if(g.includes("*"))f.glob(g);else if(fs__default.lstatSync(g).isDirectory())f.directory(g,!1);else{const l=path2__default.basename(g),m=fs__default.createReadStream(g);f.append(m,{name:l}),k.push(m)}}),f.finalize().finally(()=>{k.forEach(g=>{g.destroy()})})})}}exports.GDrive=GDrive;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});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:fs");l=c(l);let u=require("node:os");u=c(u);let d=require("node:path");d=c(d);let f=require("node:stream/promises"),p=require("@googleapis/drive"),m=require("archiver"),h=require("dayjs");h=c(h);let g=require("mime-types");g=c(g);let _=require("node:crypto");_=c(_);let v=require("node:http");v=c(v);let y=require("node:util"),b=require("google-auth-library");var x=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)}}}))}))()),S=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}},C=[`https://www.googleapis.com/auth/drive`],w=class{ready=!0;scopes;tokenFile;credentialsFile;serviceAccountFile;useADC;logger;_oAuth2Client;_googleAuth;constructor(e={}){this.tokenFile=e.tokenFile??S.TOKEN_FILE,this.credentialsFile=e.credentialsFile??S.CREDENTIALS_FILE,this.serviceAccountFile=e.serviceAccountFile??S.SERVICE_ACCOUNT_FILE,this.useADC=e.useADC??!1,this.scopes=e.scopes??C,this.logger=e.logger??console,this.serviceAccountFile?l.existsSync(this.serviceAccountFile)||(this.ready=!1,this.logger.error((0,y.styleText)([`bold`,`red`],`${S.TAG} ERROR: Service account file not found in ${this.serviceAccountFile}`))):!this.useADC&&!this.existsCredentials&&(this.ready=!1,this.logger.error((0,y.styleText)([`bold`,`red`],`${S.TAG} ERROR: Credentials file not found in ${this.credentialsFile}`)))}get isServiceAccountOrADC(){return!!this.serviceAccountFile||this.useADC}get existsToken(){return l.existsSync(this.tokenFile)}get existsCredentials(){return l.existsSync(this.credentialsFile)}async initiate(){if(!this.ready){let e=this.serviceAccountFile??this.credentialsFile;throw Error(`${S.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(l.readFileSync(this.serviceAccountFile,`utf8`));this._googleAuth=new b.GoogleAuth({credentials:e,scopes:this.scopes})}else this._googleAuth=new b.GoogleAuth({scopes:this.scopes})}return this._googleAuth}oAuth2Client(e=!0,t){if(!this._oAuth2Client){let n=JSON.parse(l.readFileSync(this.credentialsFile,`utf8`)),r=n.installed??n.web;if(!r)throw Error(`${S.TAG} Invalid credentials file format in ${this.credentialsFile}`);let{client_secret:i,client_id:a,redirect_uris:o}=r;if(this._oAuth2Client=new b.OAuth2Client(a,i,t??o?.[0]??`http://127.0.0.1`),this.attachTokenListener(this._oAuth2Client),e&&this.existsToken){let e=JSON.parse(l.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(l.readFileSync(this.tokenFile,`utf8`)));let n={...t,...e,refresh_token:e.refresh_token??t.refresh_token};this.persistTokenSync(n)}catch(e){this.logger.warn(`${S.TAG} Failed to persist refreshed token:`,e)}})}persistTokenSync(e){l.mkdirSync(d.default.dirname(this.tokenFile),{recursive:!0,mode:448}),l.writeFileSync(this.tokenFile,JSON.stringify(e,null,2),{mode:384}),l.chmodSync(this.tokenFile,384)}async generateAccessToken(){let e=_.default.randomBytes(16).toString(`hex`),t=_.default.randomBytes(32).toString(`base64url`),n=_.default.createHash(`sha256`).update(t).digest(`base64url`);return new Promise((r,i)=>{let a=v.default.createServer(),o=!1,s=e=>{o||(o=!0,a.close(),e())};a.on(`error`,e=>{s(()=>i(Error(`${S.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(`${S.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(`${S.TAG} OAuth state mismatch`)));return}if(!u){o.writeHead(400,{"Content-Type":`text/plain`}),o.end(`Missing authorization code`),s(()=>i(Error(`${S.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(`${S.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:b.CodeChallengeMethod.S256});this.logger.info(`${S.TAG} Authorize this app by visiting this url:`,r)})})}},T=Buffer.from(`NGDE`,`ascii`),E=1,D=16,O=12,k=16,A=32,j=T.length+1+D+O;function M(e,t){if(!e)throw Error(`Encryption passphrase must not be empty`);return _.default.scryptSync(e,t,A)}function N(e,t){let n=_.default.randomBytes(D),r=_.default.randomBytes(O),i=M(t,n),a=_.default.createCipheriv(`aes-256-gcm`,i,r),o=Buffer.concat([a.update(e),a.final()]),s=a.getAuthTag();return Buffer.concat([T,Buffer.from([E]),n,r,o,s])}function P(e,t){if(e.length<j+k)throw Error(`Encrypted payload is too short or corrupted`);if(!e.subarray(0,T.length).equals(T))throw Error(`Invalid encrypted file header`);let n=e[T.length];if(n!==E)throw Error(`Unsupported encryption format version: ${String(n)}`);let r=T.length+1,i=r+D,a=e.subarray(r,i),o=e.subarray(i,j),s=e.subarray(j,e.length-k),c=e.subarray(e.length-k),l=M(t,a),u=_.default.createDecipheriv(`aes-256-gcm`,l,o);return u.setAuthTag(c),Buffer.concat([u.update(s),u.final()])}async function F(e,t,n){let r=_.default.randomBytes(D),i=_.default.randomBytes(O),a=M(n,r),o=Buffer.concat([T,Buffer.from([E]),r,i]);l.default.mkdirSync(d.default.dirname(t),{recursive:!0,mode:448});let s=_.default.createCipheriv(`aes-256-gcm`,a,i),c=l.default.createReadStream(e),u=l.default.createWriteStream(t,{mode:384});try{u.write(o),await(0,f.pipeline)(c,s,u,{end:!1});let e=s.getAuthTag();return await new Promise((t,n)=>{u.once(`error`,n),u.end(e,()=>t())}),t}catch(n){throw c.destroy(),u.destroy(),l.default.rmSync(t,{force:!0}),Error(`Failed to encrypt file "${e}"`,{cause:n})}}async function I(e,t,n){let r=l.default.statSync(e);if(r.size<j+k)throw Error(`Encrypted file is too short or corrupted`);let i=l.default.openSync(e,`r`),a=Buffer.alloc(j),o=Buffer.alloc(k);try{l.default.readSync(i,a,0,j,0),l.default.readSync(i,o,0,k,r.size-k)}finally{l.default.closeSync(i)}if(!a.subarray(0,T.length).equals(T))throw Error(`Invalid encrypted file header`);let s=a[T.length];if(s!==E)throw Error(`Unsupported encryption format version: ${String(s)}`);let c=T.length+1,u=c+D,p=a.subarray(c,u),m=a.subarray(u,j),h=M(n,p),g=_.default.createDecipheriv(`aes-256-gcm`,h,m);g.setAuthTag(o),l.default.mkdirSync(d.default.dirname(t),{recursive:!0,mode:448});let v=r.size-j-k,y=l.default.createWriteStream(t,{mode:384});try{if(v===0){let e=g.final();await new Promise((t,n)=>{y.once(`error`,n),y.end(e,()=>t())})}else{let t=l.default.createReadStream(e,{start:j,end:r.size-k-1});await(0,f.pipeline)(t,g,y)}return t}catch(n){throw y.destroy(),l.default.rmSync(t,{force:!0}),Error(`Failed to decrypt file "${e}"`,{cause:n})}}var L=new Set([429,500,502,503,504]),R=new Set([`ECONNRESET`,`ETIMEDOUT`,`ENOTFOUND`,`EAI_AGAIN`,`EPIPE`,`UND_ERR_CONNECT_TIMEOUT`]);function z(e){return new Promise(t=>{setTimeout(t,e)})}function B(e){if(!e||typeof e!=`object`)return!1;let t=e,n=typeof t.status==`number`?t.status:typeof t.code==`number`?t.code:typeof t.response?.status==`number`?t.response.status:void 0;if(n!==void 0&&L.has(n))return!0;let r=typeof t.code==`string`?t.code:void 0;return!!(r&&R.has(r))}async function V(e,t={}){let{maxRetries:n=4,baseDelayMs:r=500,maxDelayMs:i=16e3,jitter:a=!0,sleep:o=z}=t,s=0;for(;;)try{return await e()}catch(e){if(s>=n||!B(e))throw e;let t=Math.min(i,r*2**s),c=a?Math.round(t*(.5+Math.random()*.5)):t;s+=1,await o(c)}}var H=`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(x.default);var U=new Set(H),W=/^(\d+)(s|m|h|d|w|M|y|seconds?|minutes?|hours?|days?|weeks?|months?|years?)$/,G={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 K(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`'`,`\\'`)}function q(e){let t=W.exec(e);if(!t)throw Error(`${S.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 n=Number(t[1]),r=G[t[2]];if(!Number.isFinite(n)||n<=0||!r)throw Error(`${S.TAG} Invalid timeSpace "${e}": amount must be a positive integer.`);return{amount:n,unit:r}}async function J(e,t,n){let r=Math.max(1,Math.floor(t)),i=Array.from({length:e.length}),a=0;async function o(){for(;a<e.length;){let t=a;a+=1,i[t]=await n(e[t])}}let s=Array.from({length:Math.min(r,e.length)},()=>o());return await Promise.all(s),i}var Y=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 w({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,p.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=H;else{for(let t of e)if(!U.has(t))throw Error(`${S.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(`${S.TAG} File id not found`));let t={fileId:e,...this.sharedDriveItemParams};try{let{data:e}=await V(()=>this.drive.files.get(t),this.retryOptions);return e}catch(e){throw this.genericError(e)}}async downloadFile(e,t,n={}){if(await this.ensureInitiated(),!e)throw Error(`${S.TAG} File id or name is required for download`);let r=e;if(n.folderName){let t=await this.findFolderId(n.folderName,!1),i=await this.findFile(e,t);if(!i?.id)throw Error(`${S.TAG} File "${e}" not found in folder "${n.folderName}"`);r=i.id}else try{let t=await V(()=>this.drive.files.get({fileId:e,fields:`id, name, mimeType`,...this.sharedDriveItemParams}),this.retryOptions);t.data.id&&(r=t.data.id)}catch{let t=await this.findFile(e);if(!t?.id)throw Error(`${S.TAG} File "${e}" not found`);r=t.id}l.default.mkdirSync(d.default.dirname(d.default.resolve(t)),{recursive:!0});let i,a=n.decryptKey?(i=this.createPrivateTempDir(),d.default.join(i,`download.enc`)):t;try{let e=await V(()=>this.drive.files.get({fileId:r,alt:`media`,...this.sharedDriveItemParams},{responseType:`stream`}),this.retryOptions),i=l.default.createWriteStream(a,{mode:n.decryptKey?384:420});return await(0,f.pipeline)(e.data,i),n.decryptKey&&await I(a,t,n.decryptKey),t}catch(e){throw n.decryptKey||l.default.rmSync(t,{force:!0}),this.genericError(e)}finally{i&&l.default.rmSync(i,{recursive:!0,force:!0})}}async emptyTrash(){return await this.ensureInitiated(),V(()=>this.drive.files.emptyTrash(),this.retryOptions)}async deleteFile(e){if(await this.ensureInitiated(),e.id)try{let{data:t}=await V(()=>this.drive.files.delete({fileId:e.id,...this.sharedDriveItemParams}),this.retryOptions);return e.name&&this.logger.warn(`${S.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=d.default.basename(e),u=a&&!c.endsWith(`.enc`)?`${c}.enc`:c,f={name:u,mimeType:a?`application/octet-stream`:g.default.contentType(c)||void 0},p=await this.getUploadFolderId(t||!1,r,f,o);if(o)return this.logger.info(`${S.TAG} [dry-run] Would upload "${u}"${t&&typeof t==`string`?` to "${t}"`:``}`),this.parseFileMeta(f);await this.replaceExistingFile(i,u,p);let m,h=e;a&&(m=this.createPrivateTempDir(),h=d.default.join(m,u),await F(e,h,a));try{let e=l.default.statSync(h).size,{data:t}=await V(async()=>{let t=l.default.createReadStream(h);t.on(`error`,e=>{this.logger.error(`${S.TAG} Read stream error for "${h}":`,e)});let n={requestBody:f,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:u,bytesRead:t.bytesRead,totalBytes:e,percentage:n}),n>=100&&this.logger.warn(`${S.TAG} Upload ${u}: ${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&&l.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=d.default.join(a,i);try{let t=l.default.createWriteStream(o,{mode:384});return await(0,f.pipeline)(e,t),await this.uploadFile(o,n,r)}finally{l.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:u,followSymlinks:f=!1}=n,p=n.concurrency??this.defaultConcurrency,m=n.compressionLevel??this.defaultCompressionLevel,g=Array.isArray(e)?e:[e],_=this.expandFileInputs(g,{exclude:u,followSymlinks:f}),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:m,followSymlinks:f});v=n,y=[t]}t&&typeof t==`string`&&y.length>0&&!(o??this.defaultDryRun)&&await this.findFolderId(t,a??!0);let e={};return await J(y,p,async n=>{let r=await this.uploadFile(n,t,{replace:i,create:a,dryRun:o,encryptKey:s,onProgress:c}),l=r.name||d.default.basename(n);e[l]=r}),e}finally{v&&l.default.rmSync(v,{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=l.default.globSync(e,{exclude:n});for(let e of t)a(e);return}if(n.some(t=>d.default.matchesGlob(e,t)||d.default.matchesGlob(d.default.basename(e),t)))return;let t=l.default.lstatSync(e);if(t.isSymbolicLink()&&!r)this.logger.warn(`${S.TAG} Skipping symlink: ${e}`);else if((t.isSymbolicLink()?l.default.statSync(e):t).isDirectory()){let t=l.default.readdirSync(e).map(t=>d.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;try{do{let r=n?{...e,pageToken:n}:{...e},{data:i}=await V(()=>this.drive.files.list(r),this.retryOptions);i.files?.length&&t.push(...i.files),n=i.nextPageToken??void 0}while(n);return 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(`${S.TAG} File "${t}" already exists and will not be replaced`);this.logger.warn(`${S.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(`'${K(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(`${S.TAG} [dry-run] Would delete file: ${e.name??e.id??`unknown`}`);return u}return await J(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(`${S.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(`${S.TAG} Invalid folder path "${e}"`);let r=this.rootParentId;for(let i of n){let n=[`name = '${K(i)}'`,`mimeType = '${this.MIME_FOLDER}'`,`trashed = false`,`'${K(r)}' in parents`].join(` and `),a=(await this.listFiles(void 0,100,n)).find(e=>e.isFolder&&!e.isDeleted&&e.name===i&&e.id);if(a?.id)r=a.id;else if(t){let e=await this.createFolder(i,r);if(!e.id)throw Error(`${S.TAG} Failed to create folder "${i}"`);r=e.id}else throw Error(`${S.TAG} Folder "${e}" does not exist and will not be created`)}return r}async findFile(e,t){let n=t||this.rootParentId,r=[`name = '${K(e)}'`,`mimeType != '${this.MIME_FOLDER}'`,`trashed = false`,`'${K(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 V(()=>this.drive.files.create({requestBody:n,fields:`id`,...this.sharedDriveItemParams}),this.retryOptions);return t?.id&&this.logger.warn(`${S.TAG} Created folder "${e}" with id: "${t.id}"`),t}catch(e){throw this.genericError(e)}}createPrivateTempDir(){let e=l.default.mkdtempSync(d.default.join(u.default.tmpdir(),`node-gdrive-`));return l.default.chmodSync(e,448),e}sanitizeFilename(e){let t=d.default.basename(e);if(!t||t===`.`||t===`..`)throw Error(`${S.TAG} Invalid output filename: "${e}"`);return t}compressFiles(e,t,n={}){let r=this.sanitizeFilename(t),i=this.createPrivateTempDir(),a=d.default.join(i,r),o=n.compressionLevel??this.defaultCompressionLevel,s=n.followSymlinks??!1;return new Promise((t,n)=>{let r=l.default.createWriteStream(a,{mode:384}),c=[],u=!1,f=e=>{if(!u){u=!0;for(let e of c)e.destroy();r.destroy(),l.default.rmSync(i,{recursive:!0,force:!0}),n(e instanceof Error?e:Error(String(e)))}},p=new m.ZipArchive({zlib:{level:o}});r.on(`error`,e=>{f(e)}),r.on(`close`,()=>{u||(u=!0,t({zipPath:a,tempDir:i}))}),p.on(`warning`,e=>{this.logger.warn(`${S.TAG} Warning compressing file`,e),e.code!==`ENOENT`&&f(e)}),p.on(`error`,e=>{this.logger.error(`${S.TAG} Error compressing file`,e),f(e)}),p.pipe(r);try{for(let t of e){let e=l.default.lstatSync(t);if(e.isSymbolicLink()&&!s)this.logger.warn(`${S.TAG} Skipping symlink: ${t}`);else if((e.isSymbolicLink()?l.default.statSync(t):e).isDirectory())p.directory(t,d.default.basename(t));else{let e=d.default.basename(t),n=l.default.createReadStream(t);n.on(`error`,e=>{f(e)}),p.append(n,{name:e}),c.push(n)}}}catch(e){f(e);return}p.finalize().catch(e=>{f(e)}).finally(()=>{for(let e of c)e.destroy()})})}};exports.Auth=w,exports.Config=S,exports.GDrive=Y,exports.allFileTypes=H,exports.decryptBuffer=P,exports.decryptFile=I,exports.encryptBuffer=N,exports.encryptFile=F,exports.escapeDriveQuery=K,exports.isRetryableError=B,exports.parseTimeSpace=q,exports.withRetry=V;