@d0whc3r/node-gdrive 3.4.1 → 3.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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 d=path2.sep,c=path2.isAbsolute(a)?d:"",b=a.split(d).reduce((h,i)=>{const f=path2.resolve(h,i);return fs.existsSync(f)||fs.mkdirSync(f),f},c);console.info(`${Config.TAG} Result file ${b}`)}}var __async=(a,d,c)=>new Promise((b,h)=>{var i=e=>{try{j(c.next(e))}catch(g){h(g)}},f=e=>{try{j(c.throw(e))}catch(g){h(g)}},j=e=>e.done?b(e.value):Promise.resolve(e.value).then(i,f);j((c=c.apply(a,d)).next())});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)}initiate(){return __async(this,[],function*(){return this.ready?this.existsToken?Promise.resolve(!0):this.generateAccessToken():Promise.reject(!1)})}oAuth2Client(a=!0){if(!this._oAuth2Client){const d=JSON.parse(fs.readFileSync(this.CREDENTIALS_FILE,"utf8")),{client_secret:c,client_id:b,redirect_uris:h}=d.installed;this._oAuth2Client=new googleapis.google.auth.OAuth2(b,c,h[0]);if(a){const i=JSON.parse(fs.readFileSync(this.TOKEN_FILE,"utf8"));this._oAuth2Client.setCredentials(i)}}return this._oAuth2Client}generateAccessToken(){return new Promise((a,d)=>{const c=this.oAuth2Client(!1).generateAuthUrl({access_type:"offline",scope:this.SCOPES});console.log(`${Config.TAG} Authorize this app by visiting this url:`,c);const b=readline2.createInterface({input:process.stdin,output:process.stdout});b.question(`${Config.TAG} Enter the code from that page here: `,h=>{b.close(),this.oAuthGetToken(h,{resolve:a,reject:d})})})}oAuthGetToken(a,d){this.oAuth2Client(!1).getToken(a).then(({tokens:c})=>{this.oAuth2Client(!1).setCredentials(c),this.writeToken(c,d)}).catch(c=>(console.error(colors2.bold(`${Config.TAG} Error retrieving access token`).red,c.message),d.reject(c)))}writeToken(a,{resolve:d,reject:c}){fs.writeFile(this.TOKEN_FILE,JSON.stringify(a),b=>{b?(console.error(b),void c(b)):(console.log(`${Config.TAG} Token stored to`,this.TOKEN_FILE),void d(!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"];var __assign=Object.assign,__async$1=(a,d,c)=>new Promise((b,h)=>{var i=e=>{try{j(c.next(e))}catch(g){h(g)}},f=e=>{try{j(c.throw(e))}catch(g){h(g)}},j=e=>e.done?b(e.value):Promise.resolve(e.value).then(i,f);j((c=c.apply(a,d)).next())});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}listFiles(a,d=50){return __async$1(this,[],function*(){yield this.initiated,a?a===!0&&(a=allFileTypes):a=this.DEFAULT_FIELDS;const c={pageSize:d,fields:`kind, nextPageToken, incompleteSearch, files(${a.join(", ")})`,prettyPrint:!0,includeTeamDriveItems:!1};return this.getListFiles(c)})}getFile(a){return __async$1(this,[],function*(){yield this.initiated;if(!a)return Promise.reject(this.genericError(new Error("File id not found")));const d={fileId:a},c=this.drive.files.get(d).then(({data:b})=>b);return c.catch(b=>{this.genericError(b)}),c})}emptyTrash(){return __async$1(this,[],function*(){return yield this.initiated,this.drive.files.emptyTrash()})}deleteFile(a){return __async$1(this,[],function*(){yield this.initiated;if(a.id){const d=this.drive.files.delete({fileId:a.id}).then(({data:c})=>(a.name&&console.warn(`${Config.TAG} Deleted ${a.isFolder?"folder":"file"}: ${a.name}`),c));return d.catch(c=>{this.genericError(c)}),d}})}uploadFile(a,d,c={}){return __async$1(this,[],function*(){yield this.initiated;const{create:b=!0,replace:h=!1}=c,i=path2__default.basename(a),f=mime.contentType(i)||void 0,j={name:i,mimeType:f};let e=null;try{e=yield this.getUploadFolderId(d||!1,b,j)}catch(k){return Promise.reject(k)}try{yield this.replaceExistingFolder(h,i,e)}catch(k){return Promise.reject(k)}const g=fs__default.createReadStream(a),l={requestBody:j,media:{body:g},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 ${i}: ${Math.round(o)}% complete`)},n=this.drive.files.create(l,{onUploadProgress:p}).then(({data:k})=>this.parseFileMeta(k)).finally(()=>{g.destroy()});return n.catch(k=>{this.genericError(k)}),n})}uploadFiles(a,d,c={}){return __async$1(this,[],function*(){yield this.initiated;const{compress:b,replace:h,create:i}=c;Array.isArray(a)||(a=[a]);let f=a;if(b){let e=b;typeof e!=="string"&&(e=`zipped_${moment2().format("YYYY-MM-DD.HHmmss")}.zip`);const g=yield this.compressFiles(a,e);f=[g]}const j={};for(const e of f)if(e.includes("*"))yield this.uploadFiles(glob2.sync(e),d,c);else if(fs__default.lstatSync(e).isDirectory())yield this.uploadFiles(glob2.sync(`${e}/*`),d,c);else{const g=path2__default.basename(e),l=yield this.uploadFile(e,d,{replace:h,create:i});j[g]=this.parseFileMeta(l)}return j})}cleanOlder(a,d){return __async$1(this,[],function*(){const c=/([0-9]+)(\w+)/.exec(a);if(!c)return console.error(`${Config.TAG} Unknown timesSpace "${a}"`),Promise.reject(!1);yield this.initiated;let b="";if(d)try{b=yield this.findFolderId(d,!1)}catch(h){return console.error("Could not find folder",d,h),Promise.reject(!1)}yield this.deleteOlder(c,b)})}getListFiles(a,d=[]){const c=this.drive.files.list(a).then(({data:b})=>__async$1(this,[],function*(){return d=d.concat(b.files),b.nextPageToken?(a.pageToken=b.nextPageToken,this.getListFiles(a,d)):d})).then(b=>this.parseFilesMeta(b));return c.catch(b=>{this.genericError(b)}),c}replaceExistingFolder(a,d,c){return __async$1(this,[],function*(){if(a!==void 0){const b=yield this.findFile(d,c);if(b)if(a)console.warn(`${Config.TAG} File "${d}" already exists and will be deleted before upload`),yield this.deleteFile(b);else throw new Error(`${Config.TAG} File "${d}" already exists and will not be replaced`)}})}getUploadFolderId(a,d,c){return __async$1(this,[],function*(){let b="";if(a&&typeof a==="string"){b=yield this.findFolderId(a,d===void 0?!0:d);if(b)c.parents=[b];else return Promise.reject(new Error(`${Config.TAG} Folder "${a}" does not exists and will not be created`))}return Promise.resolve(b)})}deleteOlder(a,d){return __async$1(this,[],function*(){const c=yield this.listFiles();if(c&&c.length){const[,b,h]=a,i=c.filter(f=>!d||d&&!f.isFolder).filter(f=>!d||d&&f.parents&&f.parents.includes(d)).map(f=>__assign(__assign({},f),{toDelete:moment2(f.createdTime||void 0).isSameOrBefore(moment2().subtract(+b,h))})).filter(f=>f.toDelete);if(i&&i.length)for(const f of i)yield this.deleteFile(f)}})}parseFileMeta(a){return __assign(__assign({},a),{isDeleted:this.isDeleted(a),isFolder:!!this.isFolder(a)})}parseFilesMeta(a){return[...a].map(d=>this.parseFileMeta(d))}genericError(a){return console.error(`${Config.TAG} The API returned an error: ${a}`),a}findFolderId(a,d=!1){return __async$1(this,[],function*(){const c=(yield this.listFiles()).filter(b=>b.isFolder).filter(b=>!b.isDeleted).filter(b=>b.name===a).map(b=>b.id);if(c&&c.length)return Promise.resolve(c[0]||"");if(d){const b=yield this.createFolder(a);return Promise.resolve(b.id||"")}return Promise.reject(!1)})}findFile(a,d){return __async$1(this,[],function*(){const c=(yield this.listFiles()).filter(b=>!b.isFolder).filter(b=>!b.isDeleted).filter(b=>b.name===a).filter(b=>!d||b.parents&&b.parents.some(h=>h===d));return c&&c.length?c[0]:null})}createFolder(a){return __async$1(this,[],function*(){const d=this.drive.files.create({requestBody:{name:a,mimeType:this.MIME_FOLDER},fields:"id"}).then(({data:b})=>b);d.catch(b=>{this.genericError(b)});const c=yield d;return(c==null?void 0:c.id)&&console.warn(`${Config.TAG} Created folder "${a}" with id: "${c.id}"`),c})}compressFiles(a,d){return new Promise((c,b)=>{const h=os2.tmpdir(),i=path2__default.resolve(h,d);FileUtils.mkdirp(path2__default.dirname(i));const f=fs__default.createWriteStream(i),j=[],e=archiver2("zip",{zlib:{level:9}});f.on("close",()=>{c(i),f.destroy()}),f.on("end",()=>{c(i),f.destroy()}),e.on("warning",g=>{console.warn(`${Config.TAG} Warning compressing file`,g),g.code!=="ENOENT"&&b(g)}),e.on("error",g=>{console.error(`${Config.TAG} Error compressing file`),b(g)}),e.pipe(f),a.forEach(g=>{if(g.includes("*"))e.glob(g);else if(fs__default.lstatSync(g).isDirectory())e.directory(g,!1);else{const l=path2__default.basename(g),m=fs__default.createReadStream(g);e.append(m,{name:l}),j.push(m)}}),e.finalize().finally(()=>{j.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(typeof e.status==`number`)return e.status;if(typeof e.code==`number`)return e.code;let t=e.response;if(typeof t?.status==`number`)return t.status}function V(e){if(!e||typeof e!=`object`)return!1;let t=e,n=B(t);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 H(e,t={}){let{maxRetries:n=4,baseDelayMs:r=500,maxDelayMs:i=16e3,jitter:a=!0,sleep:o=z}=t,s=async t=>{try{return await e()}catch(e){if(t>=n||!V(e))throw e;let c=Math.min(i,r*2**t),l=a?Math.round(c*(.5+Math.random()*.5)):c;return await o(l),s(t+1)}};return s(0)}var U=`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 W=new Set(U),G=/^(\d+)([a-zA-Z]+)$/,K={s:`second`,second:`second`,seconds:`second`,m:`minute`,minute:`minute`,minutes:`minute`,h:`hour`,hour:`hour`,hours:`hour`,d:`day`,day:`day`,days:`day`,w:`week`,week:`week`,weeks:`week`,M:`month`,month:`month`,months:`month`,y:`year`,year:`year`,years:`year`};function q(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`'`,`\\'`)}function J(e){let t=G.exec(e),n=t?K[t[2]]:void 0;if(!t||!n)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 r=Number(t[1]);if(!Number.isFinite(r)||r<=0)throw Error(`${S.TAG} Invalid timeSpace "${e}": amount must be a positive integer.`);return{amount:r,unit:n}}async function Y(e,t,n){let r=Math.max(1,Math.floor(t)),i=Array.from({length:e.length}),a=0;async function o(){if(a>=e.length)return;let t=a;a+=1,i[t]=await n(e[t]),await o()}let s=Array.from({length:Math.min(r,e.length)},()=>o());return await Promise.all(s),i}var X=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=U;else{for(let t of e)if(!W.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 H(()=>this.drive.files.get(t),this.retryOptions);return e}catch(e){throw this.genericError(e)}}async resolveDownloadFileId(e,t){if(t){let n=await this.findFolderId(t,!1),r=await this.findFile(e,n);if(!r?.id)throw Error(`${S.TAG} File "${e}" not found in folder "${t}"`);return r.id}try{return(await H(()=>this.drive.files.get({fileId:e,fields:`id, name, mimeType`,...this.sharedDriveItemParams}),this.retryOptions)).data.id??e}catch{let t=await this.findFile(e);if(!t?.id)throw Error(`${S.TAG} File "${e}" not found`);return t.id}}async downloadFile(e,t,n={}){if(await this.ensureInitiated(),!e)throw Error(`${S.TAG} File id or name is required for download`);let r=await this.resolveDownloadFileId(e,n.folderName);l.default.mkdirSync(d.default.dirname(d.default.resolve(t)),{recursive:!0});let i,a=t;n.decryptKey&&(i=this.createPrivateTempDir(),a=d.default.join(i,`download.enc`));try{let e=await H(()=>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(),H(()=>this.drive.files.emptyTrash(),this.retryOptions)}async deleteFile(e){if(await this.ensureInitiated(),e.id)try{let{data:t}=await H(()=>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 H(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 Y(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}=J(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=async r=>{let i=r?{...e,pageToken:r}:{...e},{data:a}=await H(()=>this.drive.files.list(i),this.retryOptions);a.files?.length&&t.push(...a.files),a.nextPageToken&&await n(a.nextPageToken)};try{return await n(),this.parseFilesMeta(t)}catch(e){throw this.genericError(e)}}async replaceExistingFile(e,t,n){let r=await this.findFile(t,n);if(r){if(!e)throw Error(`${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(`'${q(n)}' in parents`),a===0&&c.push(`createdTime <= '${s.toISOString()}'`);let l=(await this.listFiles(void 0,1e3,c.join(` and `))).filter(e=>!e.isDeleted&&!e.isFolder).filter(e=>!n||!!e.parents?.includes(n)).sort((e,t)=>{let n=e.createdTime?(0,h.default)(e.createdTime).valueOf():0;return(t.createdTime?(0,h.default)(t.createdTime).valueOf():0)-n}),u=(a>0?l.slice(a):l).filter(e=>e.createdTime&&(0,h.default)(e.createdTime).isSameOrBefore(s));if(i){for(let e of u)this.logger.info(`${S.TAG} [dry-run] Would delete file: ${e.name??e.id??`unknown`}`);return u}return await Y(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}"`);return this.resolveFolderSegments(n,0,this.rootParentId,t,e)}async resolveFolderSegments(e,t,n,r,i){if(t>=e.length)return n;let a=e[t],o=[`name = '${q(a)}'`,`mimeType = '${this.MIME_FOLDER}'`,`trashed = false`,`'${q(n)}' in parents`].join(` and `),s=(await this.listFiles(void 0,100,o)).find(e=>e.isFolder&&!e.isDeleted&&e.name===a&&e.id),c;if(s?.id)c=s.id;else if(r){let e=await this.createFolder(a,n);if(!e.id)throw Error(`${S.TAG} Failed to create folder "${a}"`);c=e.id}else throw Error(`${S.TAG} Folder "${i}" does not exist and will not be created`);return this.resolveFolderSegments(e,t+1,c,r,i)}async findFile(e,t){let n=t||this.rootParentId,r=[`name = '${q(e)}'`,`mimeType != '${this.MIME_FOLDER}'`,`trashed = false`,`'${q(n)}' in parents`].join(` and `);return(await this.listFiles(void 0,100,r)).find(n=>!n.isFolder&&!n.isDeleted&&n.name===e&&(!t||!!n.parents?.includes(t)))??null}async createFolder(e,t){let n={name:e,mimeType:this.MIME_FOLDER};t&&t!==`root`&&(n.parents=[t]);try{let{data:t}=await H(()=>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=X,exports.allFileTypes=U,exports.decryptBuffer=P,exports.decryptFile=I,exports.encryptBuffer=N,exports.encryptFile=F,exports.escapeDriveQuery=q,exports.isRetryableError=V,exports.parseTimeSpace=J,exports.withRetry=H;