drivekit 1.1.0 → 1.1.2

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../node_modules/tsup/assets/cjs_shims.js","../src/server/webdav.ts","../src/index.ts","../src/core/client.ts","../src/auth/authenticator.ts","../src/errors.ts","../src/core/path-resolver.ts","../src/utils/mime.ts","../src/utils/retry.ts","../src/core/resumable-uploader.ts","../src/utils/format.ts","../src/core/downloader.ts","../src/core/query-builder.ts","../src/core/concurrency-pool.ts","../src/core/watcher.ts","../src/core/storage-cleaner.ts","../src/core/smart-sync.ts","../src/auth/browser-login.ts","../src/core/resource-refs.ts","../src/core/plugins.ts","../src/core/cache.ts","../src/types.ts","../src/cli/terminal-ui.ts"],"sourcesContent":["// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () => \n typeof document === \"undefined\" \n ? new URL(`file:${__filename}`).href \n : (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT') \n ? document.currentScript.src \n : new URL(\"main.js\", document.baseURI).href;\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n","import http from 'node:http';\nimport url from 'node:url';\nimport path from 'node:path';\nimport type { DriveKit } from '../core/client.js';\nimport type { DriveApiFile } from '../types.js';\n\nexport interface WebDAVServerOptions {\n port?: number;\n host?: string;\n}\n\n/**\n * Creates and starts a lightweight zero-dependency WebDAV server for DriveKit.\n * Allows mounting Google Drive directly in macOS Finder, Windows Explorer, or Linux.\n */\nexport async function startWebDAVServer(\n drive: DriveKit,\n options: WebDAVServerOptions = {}\n): Promise<{ server: http.Server; url: string; close: () => Promise<void> }> {\n const port = options.port || 8080;\n const host = options.host || '127.0.0.1';\n\n await drive.init();\n\n const server = http.createServer(async (req, res) => {\n try {\n const parsedUrl = url.parse(req.url || '/', true);\n const decodedPath = decodeURIComponent(parsedUrl.pathname || '/');\n const virtualPath = decodedPath === '' ? '/' : decodedPath;\n\n // Handle WebDAV HTTP Verbs\n switch (req.method) {\n case 'OPTIONS': {\n res.writeHead(200, {\n DAV: '1, 2',\n Allow: 'OPTIONS, GET, HEAD, POST, PUT, DELETE, MKCOL, MOVE, COPY, PROPFIND',\n 'MS-Author-Via': 'DAV',\n });\n res.end();\n return;\n }\n\n case 'PROPFIND': {\n const depth = req.headers['depth'] || '1';\n const xml = await handlePropfind(drive, virtualPath, depth as string);\n res.writeHead(207, {\n 'Content-Type': 'application/xml; charset=utf-8',\n });\n res.end(xml);\n return;\n }\n\n case 'GET':\n case 'HEAD': {\n if (virtualPath === '/' || virtualPath === '') {\n res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });\n res.end('<h1>DriveKit WebDAV Server Running</h1><p>Connect via Finder or WebDAV client.</p>');\n return;\n }\n\n try {\n const file = await drive.getFile(virtualPath);\n if (file.mimeType === 'application/vnd.google-apps.folder') {\n res.writeHead(405, { 'Content-Type': 'text/plain' });\n res.end('Cannot GET a directory');\n return;\n }\n\n const stream = await drive.createReadStream(virtualPath);\n res.writeHead(200, {\n 'Content-Type': file.mimeType || 'application/octet-stream',\n 'Content-Length': file.size || undefined,\n });\n\n if (req.method === 'HEAD') {\n res.end();\n } else {\n stream.pipe(res);\n }\n } catch (e: any) {\n res.writeHead(404, { 'Content-Type': 'text/plain' });\n res.end('File Not Found');\n }\n return;\n }\n\n case 'PUT': {\n // Upload file\n const remoteDir = path.dirname(virtualPath);\n const fileName = path.basename(virtualPath);\n await drive.mkdirp(remoteDir);\n\n const chunks: Buffer[] = [];\n req.on('data', (chunk) => chunks.push(chunk));\n req.on('end', async () => {\n try {\n const buffer = Buffer.concat(chunks);\n await drive.upload({\n source: buffer,\n filename: fileName,\n parent: remoteDir,\n overwrite: true,\n });\n res.writeHead(201, { 'Content-Type': 'text/plain' });\n res.end('Created');\n } catch (err: any) {\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n res.end(err.message || 'Upload failed');\n }\n });\n return;\n }\n\n case 'MKCOL': {\n // Create directory\n try {\n await drive.mkdirp(virtualPath);\n res.writeHead(201, { 'Content-Type': 'text/plain' });\n res.end('Collection Created');\n } catch (err: any) {\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n res.end(err.message);\n }\n return;\n }\n\n case 'DELETE': {\n try {\n await drive.delete(virtualPath, true);\n res.writeHead(204);\n res.end();\n } catch (err: any) {\n res.writeHead(404, { 'Content-Type': 'text/plain' });\n res.end('Not Found');\n }\n return;\n }\n\n case 'MOVE': {\n const destination = req.headers['destination'];\n if (!destination || typeof destination !== 'string') {\n res.writeHead(400, { 'Content-Type': 'text/plain' });\n res.end('Destination header missing');\n return;\n }\n const destUrl = url.parse(destination);\n const destPath = decodeURIComponent(destUrl.pathname || '');\n const newName = path.basename(destPath);\n const newParent = path.dirname(destPath);\n\n try {\n await drive.move(virtualPath, newParent);\n if (newName !== path.basename(virtualPath)) {\n await drive.rename(destPath, newName);\n }\n res.writeHead(201);\n res.end('Moved');\n } catch (err: any) {\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n res.end(err.message);\n }\n return;\n }\n\n default: {\n res.writeHead(501, { 'Content-Type': 'text/plain' });\n res.end('Method Not Implemented');\n }\n }\n } catch (globalErr: any) {\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n res.end(`Internal Server Error: ${globalErr.message}`);\n }\n });\n\n return new Promise((resolve) => {\n server.listen(port, host, () => {\n const serverUrl = `http://${host}:${port}`;\n resolve({\n server,\n url: serverUrl,\n close: () => new Promise<void>((resClose) => server.close(() => resClose())),\n });\n });\n });\n}\n\n/**\n * Generates RFC 4918 multistatus XML response for PROPFIND\n */\nasync function handlePropfind(drive: DriveKit, virtualPath: string, depth: string): Promise<string> {\n const responses: string[] = [];\n\n let isFolder = false;\n let selfItem: DriveApiFile | null = null;\n\n if (virtualPath === '/' || virtualPath === '') {\n isFolder = true;\n responses.push(renderWebDAVResponse('/', true, 0, new Date().toISOString()));\n } else {\n try {\n selfItem = await drive.getFile(virtualPath);\n isFolder = selfItem.mimeType === 'application/vnd.google-apps.folder';\n responses.push(\n renderWebDAVResponse(\n virtualPath,\n isFolder,\n selfItem.size ? parseInt(selfItem.size, 10) : 0,\n selfItem.modifiedTime || new Date().toISOString()\n )\n );\n } catch {\n return `<?xml version=\"1.0\" encoding=\"utf-8\"?><D:multistatus xmlns:D=\"DAV:\"></D:multistatus>`;\n }\n }\n\n // If directory and depth != 0, include children\n if (isFolder && depth !== '0') {\n try {\n const children = await drive.ls(virtualPath);\n for (const child of children) {\n const childIsFolder = child.mimeType === 'application/vnd.google-apps.folder';\n const childPath = virtualPath === '/' ? `/${child.name}` : `${virtualPath}/${child.name}`;\n responses.push(\n renderWebDAVResponse(\n childPath,\n childIsFolder,\n child.size ? parseInt(child.size, 10) : 0,\n child.modifiedTime || new Date().toISOString()\n )\n );\n }\n } catch {\n // ignore\n }\n }\n\n return `<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<D:multistatus xmlns:D=\"DAV:\">\n${responses.join('\\n')}\n</D:multistatus>`;\n}\n\nfunction renderWebDAVResponse(href: string, isDir: boolean, size: number, modifiedTime: string): string {\n const encodedHref = encodeURI(href);\n const resourceType = isDir ? '<D:collection/>' : '';\n const dateFormatted = new Date(modifiedTime).toUTCString();\n\n return ` <D:response>\n <D:href>${encodedHref}</D:href>\n <D:propstat>\n <D:prop>\n <D:displayname>${path.basename(href) || 'root'}</D:displayname>\n <D:resourcetype>${resourceType}</D:resourcetype>\n <D:getcontentlength>${isDir ? '0' : size}</D:getcontentlength>\n <D:getlastmodified>${dateFormatted}</D:getlastmodified>\n <D:status>HTTP/1.1 200 OK</D:status>\n </D:prop>\n <D:status>HTTP/1.1 200 OK</D:status>\n </D:propstat>\n </D:response>`;\n}\n\n","import { DriveKit } from './core/client.js';\nimport type { DriveKitOptions } from './types.js';\n\n/**\n * Creates and initializes a DriveKit instance\n *\n * @example\n * ```typescript\n * import { createDrive } from 'drivekit';\n *\n * const drive = await createDrive({\n * auth: { keyFilePath: './service-account.json' }\n * });\n *\n * const file = await drive.upload({\n * source: './report.pdf',\n * parent: '/Backups/2026',\n * onProgress: (p) => console.log(`${p.percentage}% (${p.speedFormatted})`)\n * });\n * ```\n */\nexport async function createDrive(options?: DriveKitOptions): Promise<DriveKit> {\n const instance = new DriveKit(options);\n await instance.init();\n return instance;\n}\n\nexport { DriveKit };\nexport default DriveKit;\n\n// Core modules & utilities\nexport * from './types.js';\nexport * from './errors.js';\nexport * from './auth/authenticator.js';\nexport * from './core/query-builder.js';\nexport * from './core/path-resolver.js';\nexport * from './core/resumable-uploader.js';\nexport * from './core/downloader.js';\nexport * from './core/concurrency-pool.js';\nexport * from './core/watcher.js';\nexport * from './core/storage-cleaner.js';\nexport * from './core/smart-sync.js';\nexport * from './core/resource-refs.js';\nexport * from './core/plugins.js';\nexport * from './core/cache.js';\nexport * from './server/webdav.js';\nexport * from './cli/terminal-ui.js';\nexport * from './auth/browser-login.js';\nexport * from './utils/format.js';\nexport * from './utils/mime.js';\nexport * from './utils/retry.js';\n\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { drive, drive_v3 } from '@googleapis/drive';\nimport type {\n DriveKitOptions,\n UploadOptions,\n DownloadOptions,\n ShareOptions,\n SyncResult,\n DriveApiFile,\n DriveApiPermission,\n} from '../types.js';\nimport { DriveAuthenticator } from '../auth/authenticator.js';\nimport { PathResolver } from './path-resolver.js';\nimport { ResumableUploader, DEFAULT_CHUNK_SIZE } from './resumable-uploader.js';\nimport { Downloader } from './downloader.js';\nimport { DriveQueryBuilder } from './query-builder.js';\nimport { ConcurrencyPool } from './concurrency-pool.js';\nimport { DriveWatcher, type WatcherOptions } from './watcher.js';\nimport { StorageCleaner, type DuplicateGroup } from './storage-cleaner.js';\nimport { SmartSyncEngine, type PullResult, calculateFileMd5 } from './smart-sync.js';\nimport { loginWithBrowser, type BrowserLoginOptions } from '../auth/browser-login.js';\nimport { DriveFileRef, DriveFolderRef } from './resource-refs.js';\nimport { PluginManager, type DriveKitPlugin } from './plugins.js';\nimport { DriveNotFoundError } from '../errors.js';\nimport { withRetry } from '../utils/retry.js';\nimport { formatBytes } from '../utils/format.js';\nimport { GOOGLE_WORKSPACE_MIME_TYPES } from '../utils/mime.js';\nimport { SqliteMetadataCache, type IMetadataCache, type CacheStats } from './cache.js';\n\nexport class DriveKit {\n private options: DriveKitOptions;\n private authenticator: DriveAuthenticator;\n private driveClient: drive_v3.Drive | null = null;\n private pathResolverInstance: PathResolver | null = null;\n private uploaderInstance: ResumableUploader | null = null;\n private downloaderInstance: Downloader | null = null;\n private metadataCacheInstance: IMetadataCache | null = null;\n private rootFolderId: string;\n private pluginManager = new PluginManager();\n\n constructor(options: DriveKitOptions = {}) {\n this.options = options;\n this.rootFolderId = options.rootFolderId || 'root';\n this.authenticator = new DriveAuthenticator(options.auth);\n }\n\n /**\n * Registers a middleware plugin into DriveKit lifecycle\n */\n use(plugin: DriveKitPlugin): this {\n this.pluginManager.use(plugin);\n return this;\n }\n\n /**\n * Returns a fluent, chained reference to a specific file\n */\n file(pathOrId: string): DriveFileRef {\n return new DriveFileRef(this, pathOrId);\n }\n\n /**\n * Returns a fluent, chained reference to a specific folder\n */\n folder(pathOrId: string): DriveFolderRef {\n return new DriveFolderRef(this, pathOrId);\n }\n\n /**\n * Initializes the Google Drive API client (lazy-loaded if not called explicitly)\n */\n async init(): Promise<this> {\n if (!this.driveClient) {\n const auth = await this.authenticator.getAuthClient();\n this.driveClient = drive({ version: 'v3', auth });\n\n if (this.options.enablePersistentCache !== false) {\n this.metadataCacheInstance = new SqliteMetadataCache(this.options.cacheDatabasePath);\n this.metadataCacheInstance.init();\n }\n\n this.pathResolverInstance = new PathResolver(this.driveClient, this.rootFolderId, {\n enableCache: this.options.enablePathCache ?? true,\n cacheTTL: this.options.pathCacheTTL,\n metadataCache: this.metadataCacheInstance || undefined,\n });\n\n this.uploaderInstance = new ResumableUploader(\n this.driveClient,\n this.options.uploadChunkSize || DEFAULT_CHUNK_SIZE\n );\n\n this.downloaderInstance = new Downloader(this.driveClient);\n }\n return this;\n }\n\n /**\n * Access the underlying official `@googleapis/drive` instance for raw API calls\n */\n async getRawClient(): Promise<drive_v3.Drive> {\n await this.init();\n return this.driveClient!;\n }\n\n private async getResolver(): Promise<PathResolver> {\n await this.init();\n return this.pathResolverInstance!;\n }\n\n private async getUploader(): Promise<ResumableUploader> {\n await this.init();\n return this.uploaderInstance!;\n }\n\n private async getDownloader(): Promise<Downloader> {\n await this.init();\n return this.downloaderInstance!;\n }\n\n /**\n * Resolves a target string that could be either an ID or a virtual path (starting with '/')\n */\n private async resolveId(idOrPath: string, autoCreateDir = false): Promise<string> {\n if (idOrPath.startsWith('/')) {\n const resolver = await this.getResolver();\n const res = await resolver.resolve(idOrPath, { createIfMissing: autoCreateDir });\n return res.id;\n }\n return idOrPath;\n }\n\n // ==========================================\n // DIRECTORY & PATH OPERATIONS\n // ==========================================\n\n /**\n * Creates a folder structure recursively, similar to `mkdir -p`.\n * @param virtualPath Path like \"/Documents/Projects/2026\"\n * @returns Folder ID of the created or existing directory\n */\n async mkdirp(virtualPath: string): Promise<string> {\n const resolver = await this.getResolver();\n return await resolver.mkdirp(virtualPath);\n }\n\n /**\n * Resolves a virtual path to its Drive metadata\n */\n async resolvePath(virtualPath: string) {\n const resolver = await this.getResolver();\n return await resolver.resolve(virtualPath);\n }\n\n /**\n * Check if a file or folder exists (by ID or virtual path)\n */\n async exists(idOrPath: string): Promise<boolean> {\n try {\n if (idOrPath.startsWith('/')) {\n await this.resolvePath(idOrPath);\n return true;\n }\n const raw = await this.getRawClient();\n await raw.files.get({ fileId: idOrPath, fields: 'id, trashed' });\n return true;\n } catch (err: any) {\n if (err.status === 404 || err.code === 'NOT_FOUND') {\n return false;\n }\n throw err;\n }\n }\n\n /**\n * Lists contents of a folder (by folder ID or path)\n */\n async ls(folderIdOrPath = '/'): Promise<DriveApiFile[]> {\n if (folderIdOrPath === '/' || folderIdOrPath === 'root') {\n return await this.query()\n .raw(\"'root' in parents or sharedWithMe = true\")\n .notTrashed()\n .orderBy('folder,name')\n .list();\n }\n const folderId = await this.resolveId(folderIdOrPath);\n return await this.query()\n .inFolder(folderId)\n .notTrashed()\n .orderBy('folder,name')\n .list();\n }\n\n // ==========================================\n // FILE OPERATIONS (UPLOAD, DOWNLOAD, GET)\n // ==========================================\n\n /**\n * Powerful upload method:\n * - Supports local paths, Buffers, or Streams\n * - Automatically uses high-speed resumable chunked upload for large files\n * - Parent can be a folder ID OR a virtual path (e.g. '/Backups/2026')\n * - Real-time progress callback: % complete, transfer speed (MB/s), ETA\n */\n async upload(options: UploadOptions): Promise<DriveApiFile> {\n const opts = await this.pluginManager.runBeforeUpload(options);\n const uploader = await this.getUploader();\n let parentId = opts.parent;\n\n if (parentId && parentId.startsWith('/')) {\n parentId = await this.mkdirp(parentId);\n }\n\n // Check overwrite if requested\n const targetName = opts.name || opts.filename;\n if (opts.overwrite && targetName && parentId) {\n const existing = await this.query()\n .inFolder(parentId)\n .nameEquals(targetName)\n .notTrashed()\n .first();\n\n if (existing?.id) {\n await this.delete(existing.id, true);\n }\n }\n\n // Check deduplication (Fast Instant Upload via Cloud Clone)\n if (opts.deduplicate && typeof opts.source === 'string' && fs.existsSync(opts.source)) {\n const localMd5 = await calculateFileMd5(opts.source);\n let existingId: string | undefined;\n\n if (this.metadataCacheInstance) {\n const cached = this.metadataCacheInstance.findByMd5(localMd5);\n if (cached) existingId = cached.id;\n }\n\n if (!existingId) {\n const found = await this.query()\n .md5(localMd5)\n .notTrashed()\n .first();\n if (found?.id) {\n existingId = found.id;\n }\n }\n\n if (existingId) {\n const fileName = targetName || path.basename(opts.source);\n const raw = await this.getRawClient();\n const copyRes = await withRetry(async () => {\n return await raw.files.copy({\n fileId: existingId,\n requestBody: {\n name: fileName,\n parents: parentId ? [parentId] : undefined,\n description: opts.description,\n },\n fields: 'id, name, mimeType, size, modifiedTime, md5Checksum',\n supportsAllDrives: true,\n });\n });\n\n const file = copyRes.data as DriveApiFile;\n if (this.metadataCacheInstance && file.id) {\n this.metadataCacheInstance.upsertFile({\n id: file.id,\n name: file.name || fileName,\n mimeType: file.mimeType || '',\n size: file.size ? parseInt(file.size, 10) : undefined,\n parentId,\n md5Checksum: localMd5,\n trashed: false,\n });\n }\n return await this.pluginManager.runAfterUpload(file);\n }\n }\n\n const uploaded = await uploader.upload({\n ...opts,\n name: targetName,\n parent: parentId,\n });\n\n if (this.metadataCacheInstance && uploaded.id) {\n this.metadataCacheInstance.upsertFile({\n id: uploaded.id,\n name: uploaded.name || targetName || 'untitled',\n mimeType: uploaded.mimeType || '',\n size: uploaded.size ? parseInt(uploaded.size, 10) : undefined,\n parentId,\n trashed: false,\n });\n }\n\n return await this.pluginManager.runAfterUpload(uploaded);\n }\n\n /**\n * Downloads a file from Google Drive:\n * - Automatic conversion for Google Docs, Sheets, and Slides\n * - Progress events\n * - Saves directly to file or returns Readable Stream\n */\n async download(fileIdOrPath: string, options: DownloadOptions = {}) {\n const fileId = await this.resolveId(fileIdOrPath);\n const processedOpts = await this.pluginManager.runBeforeDownload(fileId, options);\n const downloader = await this.getDownloader();\n const result = await downloader.download(fileId, processedOpts);\n return await this.pluginManager.runAfterDownload(result);\n }\n\n /**\n * Gets file metadata\n */\n async getFile(fileIdOrPath: string): Promise<DriveApiFile> {\n const fileId = await this.resolveId(fileIdOrPath);\n const raw = await this.getRawClient();\n\n const res = await withRetry(async () => {\n return await raw.files.get({\n fileId,\n fields: 'id, name, mimeType, size, modifiedTime, createdTime, parents, trashed, webViewLink, webContentLink, description, properties, shared',\n supportsAllDrives: true,\n });\n });\n\n return res.data;\n }\n\n /**\n * Reads file content as UTF-8 string\n */\n async getText(fileIdOrPath: string): Promise<string> {\n const { stream } = await this.download(fileIdOrPath);\n if (!stream) throw new Error('Failed to obtain download stream');\n\n const chunks: Buffer[] = [];\n for await (const chunk of stream) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n return Buffer.concat(chunks).toString('utf-8');\n }\n\n /**\n * Reads file content and parses as JSON\n */\n async getJson<T = any>(fileIdOrPath: string): Promise<T> {\n const text = await this.getText(fileIdOrPath);\n return JSON.parse(text) as T;\n }\n\n /**\n * Deletes a file or moves it to trash\n */\n async delete(fileIdOrPath: string, permanent = false): Promise<void> {\n const fileId = await this.resolveId(fileIdOrPath);\n const raw = await this.getRawClient();\n\n if (permanent) {\n await withRetry(async () => {\n await raw.files.delete({ fileId, supportsAllDrives: true });\n });\n } else {\n await withRetry(async () => {\n await raw.files.update({\n fileId,\n requestBody: { trashed: true },\n supportsAllDrives: true,\n });\n });\n }\n\n if (this.pathResolverInstance && fileIdOrPath.startsWith('/')) {\n this.pathResolverInstance.invalidatePath(fileIdOrPath);\n }\n }\n\n /**\n * Move item to trash\n */\n async trash(fileIdOrPath: string): Promise<void> {\n return this.delete(fileIdOrPath, false);\n }\n\n /**\n * Restore item from trash\n */\n async restore(fileId: string): Promise<void> {\n const raw = await this.getRawClient();\n await withRetry(async () => {\n await raw.files.update({\n fileId,\n requestBody: { trashed: false },\n supportsAllDrives: true,\n });\n });\n }\n\n /**\n * Move file to a different folder\n */\n async move(fileIdOrPath: string, newParentIdOrPath: string): Promise<DriveApiFile> {\n const fileId = await this.resolveId(fileIdOrPath);\n const newParentId = await this.resolveId(newParentIdOrPath, true);\n const raw = await this.getRawClient();\n\n // Get current parents\n const file = await this.getFile(fileId);\n const previousParents = (file.parents || []).join(',');\n\n const res = await withRetry(async () => {\n return await raw.files.update({\n fileId,\n addParents: newParentId,\n removeParents: previousParents,\n fields: 'id, name, parents',\n supportsAllDrives: true,\n });\n });\n\n if (this.pathResolverInstance) {\n this.pathResolverInstance.clearCache();\n }\n\n return res.data;\n }\n\n /**\n * Copies a file\n */\n async copy(fileIdOrPath: string, options: { name?: string; parent?: string } = {}): Promise<DriveApiFile> {\n const fileId = await this.resolveId(fileIdOrPath);\n const raw = await this.getRawClient();\n\n let parentId = options.parent;\n if (parentId && parentId.startsWith('/')) {\n parentId = await this.mkdirp(parentId);\n }\n\n const requestBody: drive_v3.Schema$File = {};\n if (options.name) requestBody.name = options.name;\n if (parentId) requestBody.parents = [parentId];\n\n const res = await withRetry(async () => {\n return await raw.files.copy({\n fileId,\n requestBody,\n fields: 'id, name, mimeType, webViewLink',\n supportsAllDrives: true,\n });\n });\n\n return res.data;\n }\n\n /**\n * Renames a file\n */\n async rename(fileIdOrPath: string, newName: string): Promise<DriveApiFile> {\n const fileId = await this.resolveId(fileIdOrPath);\n const raw = await this.getRawClient();\n\n const res = await withRetry(async () => {\n return await raw.files.update({\n fileId,\n requestBody: { name: newName },\n fields: 'id, name, mimeType',\n supportsAllDrives: true,\n });\n });\n\n if (this.pathResolverInstance) {\n this.pathResolverInstance.clearCache();\n }\n\n return res.data;\n }\n\n // ==========================================\n // SHARING & PERMISSIONS\n // ==========================================\n\n /**\n * Share file with user, group, domain, or anyone\n */\n async share(fileIdOrPath: string, options: ShareOptions = {}): Promise<DriveApiPermission> {\n const fileId = await this.resolveId(fileIdOrPath);\n const raw = await this.getRawClient();\n\n const requestBody: drive_v3.Schema$Permission = {\n role: options.role || 'reader',\n type: options.type || (options.emailAddress ? 'user' : 'anyone'),\n emailAddress: options.emailAddress,\n domain: options.domain,\n };\n\n const res = await withRetry(async () => {\n return await raw.permissions.create({\n fileId,\n requestBody,\n sendNotificationEmail: options.sendNotificationEmail,\n emailMessage: options.emailMessage,\n transferOwnership: options.transferOwnership,\n supportsAllDrives: true,\n fields: 'id, role, type, emailAddress',\n });\n });\n\n return res.data;\n }\n\n /**\n * Quickly make a file public to anyone with the link\n */\n async sharePublic(fileIdOrPath: string, role: 'reader' | 'commenter' | 'writer' = 'reader') {\n const fileId = await this.resolveId(fileIdOrPath);\n await this.share(fileId, { role, type: 'anyone' });\n const file = await this.getFile(fileId);\n\n return {\n fileId,\n previewLink: file.webViewLink || `https://drive.google.com/file/d/${fileId}/view`,\n directDownloadLink: `https://drive.google.com/uc?export=download&id=${fileId}`,\n };\n }\n\n /**\n * Returns sharing links for a file\n */\n async getShareableLink(fileIdOrPath: string) {\n const fileId = await this.resolveId(fileIdOrPath);\n const file = await this.getFile(fileId);\n return {\n previewLink: file.webViewLink || `https://drive.google.com/file/d/${fileId}/view`,\n directDownloadLink: `https://drive.google.com/uc?export=download&id=${fileId}`,\n };\n }\n\n // ==========================================\n // QUERY BUILDER\n // ==========================================\n\n /**\n * Returns a fluent search query builder\n */\n query(): DriveQueryBuilder {\n if (!this.driveClient) {\n throw new Error('DriveKit not initialized. Call await drive.init() first, or use an async method.');\n }\n return new DriveQueryBuilder(this.driveClient);\n }\n\n // ==========================================\n // FOLDER SYNC & BATCH UPLOAD\n // ==========================================\n\n /**\n * Recursively uploads a local folder to a Google Drive path with high concurrency\n */\n async syncFolder(\n localDir: string,\n remotePathOrId: string,\n options: {\n concurrency?: number;\n overwrite?: boolean;\n onFileStart?: (filePath: string, relativePath: string) => void;\n onFileComplete?: (filePath: string, fileId: string) => void;\n } = {}\n ): Promise<SyncResult> {\n await this.init();\n const startTime = Date.now();\n const concurrency = options.concurrency || this.options.concurrency || 4;\n const pool = new ConcurrencyPool(concurrency);\n\n const targetFolderId = await this.resolveId(remotePathOrId, true);\n\n const result: SyncResult = {\n uploaded: [],\n skipped: [],\n failed: [],\n totalBytes: 0,\n durationMs: 0,\n };\n\n // Recursively collect all local files\n const collectFiles = async (dir: string, base: string): Promise<{ fullPath: string; relPath: string; size: number }[]> => {\n const entries = await fs.promises.readdir(dir, { withFileTypes: true });\n const files: { fullPath: string; relPath: string; size: number }[] = [];\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n const relPath = path.join(base, entry.name);\n\n if (entry.isDirectory()) {\n const sub = await collectFiles(fullPath, relPath);\n files.push(...sub);\n } else if (entry.isFile()) {\n const stat = await fs.promises.stat(fullPath);\n files.push({ fullPath, relPath, size: stat.size });\n }\n }\n return files;\n };\n\n const allFiles = await collectFiles(localDir, '');\n\n // Directory ID cache for subfolders\n const remoteDirCache = new Map<string, string>();\n remoteDirCache.set('', targetFolderId);\n\n const ensureRemoteSubdir = async (relDir: string): Promise<string> => {\n if (remoteDirCache.has(relDir)) {\n return remoteDirCache.get(relDir)!;\n }\n\n const parts = relDir.split(path.sep).filter(Boolean);\n let currentParent = targetFolderId;\n let currentRel = '';\n\n for (const part of parts) {\n currentRel = currentRel ? path.join(currentRel, part) : part;\n if (remoteDirCache.has(currentRel)) {\n currentParent = remoteDirCache.get(currentRel)!;\n continue;\n }\n\n // Query or create\n const existing = await this.query()\n .inFolder(currentParent)\n .nameEquals(part)\n .isFolder()\n .notTrashed()\n .first();\n\n if (existing?.id) {\n currentParent = existing.id;\n } else {\n const raw = await this.getRawClient();\n const created = await withRetry(async () => {\n return await raw.files.create({\n requestBody: {\n name: part,\n mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,\n parents: [currentParent],\n },\n fields: 'id',\n supportsAllDrives: true,\n });\n });\n currentParent = created.data.id!;\n }\n\n remoteDirCache.set(currentRel, currentParent);\n }\n\n return currentParent;\n };\n\n // Upload files concurrently\n await pool.map(allFiles, async (fileItem) => {\n try {\n const relDir = path.dirname(fileItem.relPath);\n const fileName = path.basename(fileItem.relPath);\n const parentFolderId = await ensureRemoteSubdir(relDir === '.' ? '' : relDir);\n\n if (options.onFileStart) {\n options.onFileStart(fileItem.fullPath, fileItem.relPath);\n }\n\n const uploadedFile = await this.upload({\n source: fileItem.fullPath,\n name: fileName,\n parent: parentFolderId,\n overwrite: options.overwrite ?? false,\n });\n\n result.uploaded.push({\n localPath: fileItem.fullPath,\n fileId: uploadedFile.id!,\n name: fileName,\n });\n result.totalBytes += fileItem.size;\n\n if (options.onFileComplete) {\n options.onFileComplete(fileItem.fullPath, uploadedFile.id!);\n }\n } catch (err: any) {\n result.failed.push({\n localPath: fileItem.fullPath,\n error: err,\n });\n }\n });\n\n result.durationMs = Date.now() - startTime;\n return result;\n }\n\n // ==========================================\n // STORAGE & QUOTA\n // ==========================================\n\n /**\n * Retrieves Google Drive storage quota usage and limits\n */\n async getStorageQuota() {\n const raw = await this.getRawClient();\n const res = await withRetry(async () => {\n return await raw.about.get({\n fields: 'storageQuota, user',\n });\n });\n\n const quota = res.data.storageQuota || {};\n const limit = quota.limit ? parseInt(quota.limit, 10) : null;\n const usage = quota.usage ? parseInt(quota.usage, 10) : 0;\n const usageInDrive = quota.usageInDrive ? parseInt(quota.usageInDrive, 10) : 0;\n const usageInDriveTrash = quota.usageInDriveTrash ? parseInt(quota.usageInDriveTrash, 10) : 0;\n const percentUsed = limit && limit > 0 ? Math.round((usage / limit) * 1000) / 10 : null;\n\n return {\n user: res.data.user,\n limit,\n usage,\n usageInDrive,\n usageInDriveTrash,\n percentUsed,\n formattedUsage: formatBytes(usage),\n formattedLimit: limit ? formatBytes(limit) : 'Unlimited',\n };\n }\n\n // ==========================================\n // CHANGE WATCHER (REAL-TIME EVENTS)\n // ==========================================\n\n /**\n * Watches Google Drive or a specific folder for real-time changes, creations, and deletions\n */\n async watch(folderIdOrPath?: string, options: Omit<WatcherOptions, 'folderId'> = {}): Promise<DriveWatcher> {\n await this.init();\n let folderId: string | undefined = undefined;\n if (folderIdOrPath && folderIdOrPath !== '/') {\n folderId = await this.resolveId(folderIdOrPath);\n }\n\n const watcher = new DriveWatcher(this.driveClient!, {\n ...options,\n folderId,\n });\n\n await watcher.start();\n return watcher;\n }\n\n // ==========================================\n // STORAGE CLEANER & DUPLICATE FINDER\n // ==========================================\n\n /**\n * Finds the largest files consuming Google Drive storage\n */\n async findLargestFiles(limit = 10) {\n await this.init();\n const cleaner = new StorageCleaner(this.driveClient!);\n return await cleaner.findLargestFiles(limit);\n }\n\n /**\n * Finds duplicate files (by MD5 hash or exact file name)\n */\n async findDuplicates(options?: { by?: 'md5' | 'name'; maxScan?: number }) {\n await this.init();\n const cleaner = new StorageCleaner(this.driveClient!);\n return await cleaner.findDuplicates(options);\n }\n\n /**\n * Empties the entire trash bin in Google Drive\n */\n async emptyTrash(): Promise<void> {\n await this.init();\n const cleaner = new StorageCleaner(this.driveClient!);\n await cleaner.emptyTrash();\n }\n\n // ==========================================\n // SMART PULL & TWO-WAY SYNC\n // ==========================================\n\n /**\n * Pulls (downloads) an entire remote Google Drive directory down to a local folder with MD5 deduplication\n */\n async pull(\n remoteFolderIdOrPath: string,\n localDestinationDir: string,\n options: {\n concurrency?: number;\n overwrite?: boolean;\n onFileStart?: (remoteName: string, relativePath: string) => void;\n onFileComplete?: (remoteName: string, localPath: string) => void;\n } = {}\n ): Promise<PullResult> {\n await this.init();\n const folderId = await this.resolveId(remoteFolderIdOrPath);\n const engine = new SmartSyncEngine(this.driveClient!);\n return await engine.pullFolder(folderId, localDestinationDir, options);\n }\n\n // ==========================================\n // STREAMS & RANGE REQUESTS\n // ==========================================\n\n /**\n * Creates a readable stream for a file, supporting partial range requests\n */\n async createReadStream(\n pathOrId: string,\n options?: { start?: number; end?: number }\n ): Promise<NodeJS.ReadableStream> {\n const fileId = await this.resolveId(pathOrId);\n const downloader = await this.getDownloader();\n return await downloader.createReadStream(fileId, options);\n }\n\n /**\n * Creates a writable stream directly into Google Drive\n */\n async createWriteStream(\n remotePath: string,\n options: Omit<UploadOptions, 'source'> = {}\n ): Promise<NodeJS.WritableStream> {\n await this.init();\n const { PassThrough } = await import('node:stream');\n const passThrough = new PassThrough();\n\n const remoteDir = path.dirname(remotePath);\n const fileName = options.name || options.filename || path.basename(remotePath);\n const targetParentId = remoteDir === '.' || remoteDir === '/' ? this.rootFolderId : await this.mkdirp(remoteDir);\n const mimeType = options.mimeType || 'application/octet-stream';\n\n const raw = this.driveClient!;\n raw.files.create({\n requestBody: {\n name: fileName,\n parents: [targetParentId],\n description: options.description,\n },\n media: {\n mimeType,\n body: passThrough,\n },\n fields: 'id, name, mimeType, size, md5Checksum',\n supportsAllDrives: true,\n }).then((res) => {\n if (res.data.id && this.metadataCacheInstance) {\n this.metadataCacheInstance.upsertFile({\n id: res.data.id,\n name: fileName,\n mimeType,\n parentId: targetParentId,\n path: remotePath,\n trashed: false,\n });\n }\n }).catch((err) => {\n passThrough.destroy(err);\n });\n\n return passThrough;\n }\n\n // ==========================================\n // METADATA CACHE OPERATIONS\n // ==========================================\n\n /**\n * Returns the active persistent metadata cache instance (SQLite/Memory)\n */\n async getMetadataCache(): Promise<IMetadataCache | null> {\n await this.init();\n return this.metadataCacheInstance;\n }\n\n /**\n * Returns cache statistics (total files, folders, size, last sync)\n */\n async getCacheStats(): Promise<CacheStats | null> {\n await this.init();\n return this.metadataCacheInstance ? this.metadataCacheInstance.getStats() : null;\n }\n\n /**\n * Clears the path and metadata cache\n */\n async clearCache(): Promise<void> {\n await this.init();\n if (this.pathResolverInstance) {\n this.pathResolverInstance.clearCache();\n }\n }\n\n /**\n * Crawls and indexes Google Drive metadata into the local SQLite database for instant 0ms lookups\n */\n async syncCache(options?: {\n onProgress?: (scanned: number) => void;\n }): Promise<CacheStats> {\n await this.init();\n if (!this.metadataCacheInstance) {\n throw new Error('Persistent cache is disabled on this DriveKit instance');\n }\n\n const client = this.driveClient!;\n let pageToken: string | undefined = undefined;\n let totalScanned = 0;\n\n do {\n const res = await withRetry(async () => {\n return await client.files.list({\n pageSize: 1000,\n pageToken,\n fields: 'nextPageToken, files(id, name, mimeType, size, parents, md5Checksum, trashed, modifiedTime)',\n spaces: 'drive',\n supportsAllDrives: true,\n includeItemsFromAllDrives: true,\n q: 'trashed = false',\n });\n });\n\n const files = res.data.files || [];\n const entries = files.map((f) => ({\n id: f.id!,\n name: f.name || 'untitled',\n mimeType: f.mimeType || '',\n size: f.size ? parseInt(f.size, 10) : undefined,\n parentId: f.parents?.[0],\n md5Checksum: f.md5Checksum || undefined,\n trashed: !!f.trashed,\n modifiedTime: f.modifiedTime || undefined,\n }));\n\n this.metadataCacheInstance.upsertFiles(entries);\n totalScanned += entries.length;\n options?.onProgress?.(totalScanned);\n\n pageToken = res.data.nextPageToken || undefined;\n } while (pageToken);\n\n this.metadataCacheInstance.setMeta('last_sync_timestamp', new Date().toISOString());\n return this.metadataCacheInstance.getStats();\n }\n\n // ==========================================\n // SHARED DRIVES & ENTERPRISE PERMISSIONS\n // ==========================================\n\n /**\n * Lists all Google Workspace Shared Drives accessible by current user or service account\n */\n async listSharedDrives(options: { pageSize?: number } = {}): Promise<{ id: string; name: string }[]> {\n await this.init();\n const raw = await this.getRawClient();\n const res = await withRetry(async () => {\n return await raw.drives.list({\n pageSize: options.pageSize || 100,\n fields: 'drives(id, name)',\n });\n });\n return (res.data.drives || []).map((d) => ({ id: d.id!, name: d.name! }));\n }\n\n /**\n * Creates a scoped DriveKit client locked to a specific Shared Drive\n */\n sharedDrive(driveId: string): DriveKit {\n return new DriveKit({\n ...this.options,\n rootFolderId: driveId,\n });\n }\n\n /**\n * Grants access to a specific email with custom role and notification\n */\n async grantAccess(\n pathOrId: string,\n options: {\n email: string;\n role?: 'reader' | 'commenter' | 'writer';\n notify?: boolean;\n message?: string;\n }\n ): Promise<DriveApiPermission> {\n const fileId = await this.resolveId(pathOrId);\n const raw = await this.getRawClient();\n const res = await withRetry(async () => {\n return await raw.permissions.create({\n fileId,\n requestBody: {\n type: 'user',\n role: options.role || 'reader',\n emailAddress: options.email,\n },\n sendNotificationEmail: options.notify ?? true,\n emailMessage: options.message,\n fields: 'id, type, role, emailAddress, displayName',\n supportsAllDrives: true,\n });\n });\n return res.data;\n }\n\n /**\n * Revokes access for a specific permission ID or email address\n */\n async revokeAccess(pathOrId: string, permissionIdOrEmail: string): Promise<void> {\n const fileId = await this.resolveId(pathOrId);\n const raw = await this.getRawClient();\n let targetId = permissionIdOrEmail;\n\n if (permissionIdOrEmail.includes('@')) {\n const listRes = await this.listPermissions(fileId);\n const found = listRes.find((p) => p.emailAddress?.toLowerCase() === permissionIdOrEmail.toLowerCase());\n if (found && found.id) {\n targetId = found.id;\n }\n }\n\n await withRetry(async () => {\n return await raw.permissions.delete({\n fileId,\n permissionId: targetId,\n supportsAllDrives: true,\n });\n });\n }\n\n /**\n * Lists all active permissions on a file or folder\n */\n async listPermissions(pathOrId: string): Promise<DriveApiPermission[]> {\n const fileId = await this.resolveId(pathOrId);\n const raw = await this.getRawClient();\n const res = await withRetry(async () => {\n return await raw.permissions.list({\n fileId,\n fields: 'permissions(id, type, role, emailAddress, displayName)',\n supportsAllDrives: true,\n });\n });\n return res.data.permissions || [];\n }\n\n /**\n * Starts an embedded WebDAV server to mount DriveKit directly in macOS Finder or Windows Explorer\n */\n async serveWebDAV(options?: { port?: number; host?: string }) {\n const { startWebDAVServer } = await import('../server/webdav.js');\n return await startWebDAVServer(this, options);\n }\n\n /**\n * Calculates local file MD5 hash for integrity and deduplication checks\n */\n static async calculateFileMd5(filePath: string): Promise<string> {\n return await calculateFileMd5(filePath);\n }\n\n /**\n * Interactive 1-click browser OAuth login flow\n */\n static async loginWithBrowser(options: BrowserLoginOptions) {\n return await loginWithBrowser(options);\n }\n}\n\n","import fs from 'node:fs';\nimport { auth as googleAuth } from '@googleapis/drive';\nimport type { DriveKitAuthConfig } from '../types.js';\nimport { DriveAuthError } from '../errors.js';\n\nexport const DEFAULT_SCOPES = [\n 'https://www.googleapis.com/auth/drive',\n];\n\n/**\n * Handles Google Drive authentication across various methods\n */\nexport class DriveAuthenticator {\n private config: DriveKitAuthConfig;\n private authClient: any = null;\n\n constructor(config: DriveKitAuthConfig = {}) {\n this.config = config;\n }\n\n /**\n * Initializes and returns an authenticated Google client\n */\n async getAuthClient(): Promise<any> {\n if (this.authClient) {\n return this.authClient;\n }\n\n try {\n const scopes = this.config.scopes || DEFAULT_SCOPES;\n\n // 1. Direct Access Token provided\n if (this.config.accessToken) {\n const oauth2Client = new googleAuth.OAuth2();\n oauth2Client.setCredentials({ access_token: this.config.accessToken });\n this.authClient = oauth2Client;\n return this.authClient;\n }\n\n // 2. Existing OAuth2Client instance provided\n if (this.config.oauth2Client) {\n this.authClient = this.config.oauth2Client;\n return this.authClient;\n }\n\n // 3. OAuth with Refresh Token\n if (this.config.oauth) {\n const { clientId, clientSecret, redirectUri = 'http://localhost:3000/oauth2callback', refreshToken } = this.config.oauth;\n const oauth2Client = new googleAuth.OAuth2(clientId, clientSecret, redirectUri);\n if (refreshToken) {\n oauth2Client.setCredentials({ refresh_token: refreshToken });\n }\n this.authClient = oauth2Client;\n return this.authClient;\n }\n\n // 4. Service Account Key File or Environment\n const keyFile = this.config.keyFilePath ||\n process.env.GDRIVE_SERVICE_ACCOUNT_PATH ||\n process.env.GOOGLE_APPLICATION_CREDENTIALS;\n\n if (keyFile) {\n if (!fs.existsSync(keyFile)) {\n throw new DriveAuthError(`Service account file not found at: ${keyFile}`);\n }\n const auth = new googleAuth.GoogleAuth({\n keyFile,\n scopes,\n });\n this.authClient = auth;\n return this.authClient;\n }\n\n // 5. In-Memory Service Account Credentials\n const creds = this.config.credentials || (process.env.GDRIVE_CREDENTIALS_JSON ? JSON.parse(process.env.GDRIVE_CREDENTIALS_JSON) : null);\n if (creds) {\n const auth = new googleAuth.GoogleAuth({\n credentials: creds,\n scopes,\n });\n this.authClient = auth;\n return this.authClient;\n }\n\n // 6. Fallback to Google Application Default Credentials (ADC)\n const auth = new googleAuth.GoogleAuth({ scopes });\n this.authClient = auth;\n return this.authClient;\n } catch (err: any) {\n if (err instanceof DriveAuthError) throw err;\n throw new DriveAuthError(`Failed to authenticate with Google Drive: ${err.message}`, err);\n }\n }\n\n /**\n * Helper to generate OAuth2 Consent URL for user authorization\n */\n static generateAuthUrl(options: {\n clientId: string;\n clientSecret: string;\n redirectUri?: string;\n scopes?: string[];\n }): string {\n const oauth2Client = new googleAuth.OAuth2(\n options.clientId,\n options.clientSecret,\n options.redirectUri || 'urn:ietf:wg:oauth:2.0:oob'\n );\n\n return oauth2Client.generateAuthUrl({\n access_type: 'offline',\n prompt: 'consent',\n scope: options.scopes || DEFAULT_SCOPES,\n });\n }\n\n /**\n * Helper to exchange authorization code for tokens\n */\n static async exchangeCodeForTokens(options: {\n clientId: string;\n clientSecret: string;\n code: string;\n redirectUri?: string;\n }): Promise<{ access_token?: string | null; refresh_token?: string | null; expiry_date?: number | null }> {\n const oauth2Client = new googleAuth.OAuth2(\n options.clientId,\n options.clientSecret,\n options.redirectUri || 'urn:ietf:wg:oauth:2.0:oob'\n );\n\n const { tokens } = await oauth2Client.getToken(options.code);\n return tokens;\n }\n}\n","/**\n * Base DriveKit Error\n */\nexport class DriveKitError extends Error {\n public readonly code: string;\n public readonly originalError?: unknown;\n\n constructor(message: string, code = 'DRIVEKIT_ERROR', originalError?: unknown) {\n super(message);\n this.name = 'DriveKitError';\n this.code = code;\n this.originalError = originalError;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Authentication Error\n */\nexport class DriveAuthError extends DriveKitError {\n constructor(message: string, originalError?: unknown) {\n super(message, 'AUTH_ERROR', originalError);\n this.name = 'DriveAuthError';\n }\n}\n\n/**\n * Resource Not Found Error\n */\nexport class DriveNotFoundError extends DriveKitError {\n public readonly resourceIdOrPath: string;\n\n constructor(resourceIdOrPath: string, message?: string) {\n super(message || `Resource not found: \"${resourceIdOrPath}\"`, 'NOT_FOUND');\n this.name = 'DriveNotFoundError';\n this.resourceIdOrPath = resourceIdOrPath;\n }\n}\n\n/**\n * Rate limit / Quota exceeded Error\n */\nexport class DriveRateLimitError extends DriveKitError {\n public readonly retryAfterSeconds?: number;\n\n constructor(message: string, retryAfterSeconds?: number, originalError?: unknown) {\n super(message, 'RATE_LIMIT_EXCEEDED', originalError);\n this.name = 'DriveRateLimitError';\n this.retryAfterSeconds = retryAfterSeconds;\n }\n}\n\n/**\n * Upload Error (chunk or resumable session failure)\n */\nexport class DriveUploadError extends DriveKitError {\n public readonly bytesUploaded?: number;\n public readonly totalBytes?: number;\n\n constructor(message: string, bytesUploaded?: number, totalBytes?: number, originalError?: unknown) {\n super(message, 'UPLOAD_ERROR', originalError);\n this.name = 'DriveUploadError';\n this.bytesUploaded = bytesUploaded;\n this.totalBytes = totalBytes;\n }\n}\n\n","import type { drive_v3 } from '@googleapis/drive';\nimport { GOOGLE_WORKSPACE_MIME_TYPES } from '../utils/mime.js';\nimport { DriveNotFoundError } from '../errors.js';\nimport { withRetry } from '../utils/retry.js';\nimport type { IMetadataCache } from './cache.js';\n\ninterface CacheEntry {\n id: string;\n name: string;\n mimeType: string;\n expiresAt: number;\n}\n\n/**\n * Resolves virtual hierarchical paths like \"/Projects/2026/file.pdf\" to Google Drive File/Folder IDs.\n */\nexport class PathResolver {\n private drive: drive_v3.Drive;\n private rootFolderId: string;\n private cache = new Map<string, CacheEntry>();\n private cacheTTL: number;\n private enableCache: boolean;\n private metadataCache?: IMetadataCache;\n\n constructor(\n drive: drive_v3.Drive,\n rootFolderId = 'root',\n options?: { enableCache?: boolean; cacheTTL?: number; metadataCache?: IMetadataCache }\n ) {\n this.drive = drive;\n this.rootFolderId = rootFolderId;\n this.enableCache = options?.enableCache ?? true;\n this.cacheTTL = options?.cacheTTL ?? 5 * 60 * 1000; // 5 minutes default\n this.metadataCache = options?.metadataCache;\n }\n\n /**\n * Normalizes a virtual path (e.g. \"///Backups//2026/\" -> \"/Backups/2026\")\n */\n public normalizePath(rawPath: string): string {\n if (!rawPath || rawPath.trim() === '' || rawPath === '/') {\n return '/';\n }\n const parts = rawPath\n .split('/')\n .map((p) => p.trim())\n .filter(Boolean);\n return `/${parts.join('/')}`;\n }\n\n /**\n * Gets cache key for a path\n */\n private getCacheKey(path: string): string {\n return `${this.rootFolderId}:${this.normalizePath(path)}`;\n }\n\n /**\n * Clears the path cache\n */\n public clearCache(): void {\n this.cache.clear();\n if (this.metadataCache) {\n this.metadataCache.clear();\n }\n }\n\n /**\n * Invalidate a single path from cache\n */\n public invalidatePath(path: string): void {\n const norm = this.normalizePath(path);\n const key = this.getCacheKey(norm);\n this.cache.delete(key);\n if (this.metadataCache) {\n const item = this.metadataCache.getByPath(norm);\n if (item) {\n this.metadataCache.deleteFile(item.id);\n }\n }\n }\n\n /**\n * Resolves a path to a Google Drive item (file or folder).\n * If createIfMissing is true, any missing intermediate directories will be automatically created (like mkdir -p).\n */\n async resolve(\n virtualPath: string,\n options: { createIfMissing?: boolean } = {}\n ): Promise<{ id: string; name: string; isFolder: boolean; mimeType: string }> {\n const norm = this.normalizePath(virtualPath);\n\n if (norm === '/') {\n return {\n id: this.rootFolderId,\n name: 'root',\n isFolder: true,\n mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,\n };\n }\n\n if (this.metadataCache) {\n const persistentCached = this.metadataCache.getByPath(norm);\n if (persistentCached) {\n return {\n id: persistentCached.id,\n name: persistentCached.name,\n isFolder: persistentCached.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,\n mimeType: persistentCached.mimeType,\n };\n }\n }\n\n if (this.enableCache) {\n const cached = this.cache.get(this.getCacheKey(norm));\n if (cached && cached.expiresAt > Date.now()) {\n return {\n id: cached.id,\n name: cached.name,\n isFolder: cached.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,\n mimeType: cached.mimeType,\n };\n }\n }\n\n const segments = norm.split('/').filter(Boolean);\n let currentParentId = this.rootFolderId;\n let currentPath = '';\n\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n const isLast = i === segments.length - 1;\n currentPath += `/${segment}`;\n\n // Check persistent & in-memory cache for intermediate path\n if (this.metadataCache) {\n const pCached = this.metadataCache.getByPath(currentPath);\n if (pCached) {\n currentParentId = pCached.id;\n if (isLast) {\n return {\n id: pCached.id,\n name: pCached.name,\n isFolder: pCached.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,\n mimeType: pCached.mimeType,\n };\n }\n continue;\n }\n }\n\n if (this.enableCache) {\n const cached = this.cache.get(this.getCacheKey(currentPath));\n if (cached && cached.expiresAt > Date.now()) {\n currentParentId = cached.id;\n if (isLast) {\n return {\n id: cached.id,\n name: cached.name,\n isFolder: cached.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,\n mimeType: cached.mimeType,\n };\n }\n continue;\n }\n }\n\n // Query Google Drive for this segment under currentParentId\n const escapedName = segment.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\");\n const q = `'${currentParentId}' in parents and name = '${escapedName}' and trashed = false`;\n\n const response = await withRetry(async () => {\n return await this.drive.files.list({\n q,\n fields: 'files(id, name, mimeType, parents)',\n pageSize: 1,\n spaces: 'drive',\n supportsAllDrives: true,\n includeItemsFromAllDrives: true,\n });\n });\n\n let file = response.data.files?.[0];\n\n // If not found and at root level, check shared folders (e.g. shared with service account)\n if (!file && currentParentId === this.rootFolderId) {\n const sharedQ = `name = '${escapedName}' and trashed = false`;\n const sharedResponse = await withRetry(async () => {\n return await this.drive.files.list({\n q: sharedQ,\n fields: 'files(id, name, mimeType, parents)',\n pageSize: 1,\n spaces: 'drive',\n supportsAllDrives: true,\n includeItemsFromAllDrives: true,\n });\n });\n file = sharedResponse.data.files?.[0];\n }\n\n if (file && file.id) {\n currentParentId = file.id;\n\n if (this.metadataCache) {\n this.metadataCache.upsertFile({\n id: file.id,\n name: file.name || segment,\n mimeType: file.mimeType || '',\n parentId: currentParentId,\n path: currentPath,\n trashed: false,\n });\n }\n\n if (this.enableCache) {\n this.cache.set(this.getCacheKey(currentPath), {\n id: file.id,\n name: file.name || segment,\n mimeType: file.mimeType || '',\n expiresAt: Date.now() + this.cacheTTL,\n });\n }\n\n if (isLast) {\n return {\n id: file.id,\n name: file.name || segment,\n isFolder: file.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,\n mimeType: file.mimeType || '',\n };\n }\n } else {\n // Not found\n if (options.createIfMissing) {\n // Create directory\n const createRes = await withRetry(async () => {\n return await this.drive.files.create({\n requestBody: {\n name: segment,\n mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,\n parents: [currentParentId],\n },\n fields: 'id, name, mimeType',\n supportsAllDrives: true,\n });\n });\n\n const newFolder = createRes.data;\n if (!newFolder.id) {\n throw new Error(`Failed to create folder \"${segment}\" under parent \"${currentParentId}\"`);\n }\n\n currentParentId = newFolder.id;\n\n if (this.metadataCache) {\n this.metadataCache.upsertFile({\n id: newFolder.id,\n name: segment,\n mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,\n parentId: currentParentId,\n path: currentPath,\n trashed: false,\n });\n }\n\n if (this.enableCache) {\n this.cache.set(this.getCacheKey(currentPath), {\n id: newFolder.id,\n name: segment,\n mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,\n expiresAt: Date.now() + this.cacheTTL,\n });\n }\n\n if (isLast) {\n return {\n id: newFolder.id,\n name: segment,\n isFolder: true,\n mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,\n };\n }\n } else {\n throw new DriveNotFoundError(\n virtualPath,\n `Path segment \"${segment}\" not found in path \"${virtualPath}\" under folder ID \"${currentParentId}\"`\n );\n }\n }\n }\n\n throw new DriveNotFoundError(virtualPath);\n }\n\n /**\n * Ensures that a directory structure exists (like mkdir -p).\n */\n async mkdirp(virtualPath: string): Promise<string> {\n const res = await this.resolve(virtualPath, { createIfMissing: true });\n return res.id;\n }\n}\n\n","import path from 'node:path';\nimport mime from 'mime-types';\n\n/**\n * Standard Google Workspace MIME types\n */\nexport const GOOGLE_WORKSPACE_MIME_TYPES = {\n DOCUMENT: 'application/vnd.google-apps.document',\n SPREADSHEET: 'application/vnd.google-apps.spreadsheet',\n PRESENTATION: 'application/vnd.google-apps.presentation',\n DRAWING: 'application/vnd.google-apps.drawing',\n FORM: 'application/vnd.google-apps.form',\n SCRIPT: 'application/vnd.google-apps.script',\n FOLDER: 'application/vnd.google-apps.folder',\n SHORTCUT: 'application/vnd.google-apps.shortcut',\n} as const;\n\n/**\n * Default export MIME types for Google Docs, Sheets, Slides\n */\nexport const DEFAULT_EXPORT_MIMES: Record<string, { mimeType: string; extension: string }> = {\n [GOOGLE_WORKSPACE_MIME_TYPES.DOCUMENT]: {\n mimeType: 'application/pdf',\n extension: '.pdf',\n },\n [GOOGLE_WORKSPACE_MIME_TYPES.SPREADSHEET]: {\n mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n extension: '.xlsx',\n },\n [GOOGLE_WORKSPACE_MIME_TYPES.PRESENTATION]: {\n mimeType: 'application/pdf',\n extension: '.pdf',\n },\n [GOOGLE_WORKSPACE_MIME_TYPES.DRAWING]: {\n mimeType: 'image/png',\n extension: '.png',\n },\n};\n\n/**\n * Detects MIME type from file path or fallback to octet-stream\n */\nexport function lookupMimeType(filePath: string): string {\n const detected = mime.lookup(filePath);\n return detected || 'application/octet-stream';\n}\n\n/**\n * Returns extension for a given MIME type\n */\nexport function getExtensionForMime(mimeType: string): string {\n const ext = mime.extension(mimeType);\n return ext ? `.${ext}` : '';\n}\n\n/**\n * Checks if a MIME type is a native Google Workspace format\n */\nexport function isGoogleWorkspaceDoc(mimeType?: string | null): boolean {\n if (!mimeType) return false;\n return mimeType.startsWith('application/vnd.google-apps.') &&\n mimeType !== GOOGLE_WORKSPACE_MIME_TYPES.FOLDER &&\n mimeType !== GOOGLE_WORKSPACE_MIME_TYPES.SHORTCUT;\n}\n\n","import { DriveRateLimitError } from '../errors.js';\n\nexport interface RetryOptions {\n maxRetries?: number;\n baseDelayMs?: number;\n maxDelayMs?: number;\n shouldRetry?: (error: any) => boolean;\n}\n\nconst DEFAULT_RETRYABLE_STATUSES = new Set([408, 429, 500, 502, 503, 504]);\n\n/**\n * Checks if an error returned by Google Drive is retryable\n */\nexport function isRetryableError(error: any): boolean {\n if (!error) return false;\n\n const status = error.status || error.statusCode || error.response?.status;\n if (status && DEFAULT_RETRYABLE_STATUSES.has(status)) {\n return true;\n }\n\n // Check error message or Google error reasons\n const message = (error.message || '').toLowerCase();\n if (\n message.includes('rate limit') ||\n message.includes('quota') ||\n message.includes('userate') ||\n message.includes('backend error') ||\n message.includes('socket hang up') ||\n message.includes('econnreset') ||\n message.includes('etimedout')\n ) {\n return true;\n }\n\n const errors = error.errors || error.response?.data?.error?.errors;\n if (Array.isArray(errors)) {\n for (const e of errors) {\n if (e.reason === 'rateLimitExceeded' || e.reason === 'userRateLimitExceeded' || e.reason === 'backendError') {\n return true;\n }\n }\n }\n\n return false;\n}\n\n/**\n * Executes an async operation with exponential backoff and full jitter\n */\nexport async function withRetry<T>(\n fn: () => Promise<T>,\n options: RetryOptions = {}\n): Promise<T> {\n const maxRetries = options.maxRetries ?? 5;\n const baseDelayMs = options.baseDelayMs ?? 1000;\n const maxDelayMs = options.maxDelayMs ?? 32000;\n const shouldRetry = options.shouldRetry ?? isRetryableError;\n\n let attempt = 0;\n\n while (true) {\n try {\n return await fn();\n } catch (error: any) {\n attempt++;\n if (attempt > maxRetries || !shouldRetry(error)) {\n if (error?.status === 429 || error?.response?.status === 429) {\n throw new DriveRateLimitError(\n `Drive API rate limit exceeded after ${attempt} attempts.`,\n undefined,\n error\n );\n }\n throw error;\n }\n\n // Calculate exponential backoff with full jitter: delay = random_between(0, min(maxDelay, base * 2^attempt))\n const calculatedDelay = Math.min(maxDelayMs, baseDelayMs * Math.pow(2, attempt));\n const jitterDelay = Math.floor(Math.random() * calculatedDelay);\n\n await new Promise((resolve) => setTimeout(resolve, jitterDelay));\n }\n }\n}\n\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport type { drive_v3 } from '@googleapis/drive';\nimport type { UploadOptions, UploadProgress, DriveApiFile } from '../types.js';\nimport { DriveUploadError } from '../errors.js';\nimport { formatSpeed } from '../utils/format.js';\nimport { lookupMimeType } from '../utils/mime.js';\nimport { withRetry } from '../utils/retry.js';\n\n/** Minimum Google Drive chunk granularity: 256 KiB */\nexport const MIN_CHUNK_SIZE = 256 * 1024;\n/** Default chunk size: 8 MiB (must be multiple of 256 KiB) */\nexport const DEFAULT_CHUNK_SIZE = 8 * 1024 * 1024;\n/** Files smaller than this can use direct single-request multipart upload */\nexport const MULTIPART_THRESHOLD = 5 * 1024 * 1024;\n\nexport class ResumableUploader {\n private drive: drive_v3.Drive;\n private defaultChunkSize: number;\n\n constructor(drive: drive_v3.Drive, defaultChunkSize = DEFAULT_CHUNK_SIZE) {\n this.drive = drive;\n // Ensure chunk size is multiple of 256 KiB\n this.defaultChunkSize = Math.max(\n MIN_CHUNK_SIZE,\n Math.floor(defaultChunkSize / MIN_CHUNK_SIZE) * MIN_CHUNK_SIZE\n );\n }\n\n /**\n * Uploads a file with automatic selection of direct multipart (small files)\n * or resumable chunked upload with progress events (large files).\n */\n async upload(options: UploadOptions): Promise<DriveApiFile> {\n if (typeof options.source === 'string') {\n return await this.uploadFromPath(options.source, options);\n } else if (Buffer.isBuffer(options.source)) {\n return await this.uploadFromBuffer(options.source, options);\n } else {\n // Readable Stream: standard drive.files.create with stream\n return await this.uploadFromStream(options.source, options);\n }\n }\n\n /**\n * Upload from local file path with memory-efficient chunked streaming\n */\n private async uploadFromPath(filePath: string, options: UploadOptions): Promise<DriveApiFile> {\n if (!fs.existsSync(filePath)) {\n throw new Error(`File does not exist at path: \"${filePath}\"`);\n }\n\n const stat = await fs.promises.stat(filePath);\n const totalBytes = stat.size;\n const fileName = options.name || path.basename(filePath);\n const mimeType = options.mimeType || lookupMimeType(filePath);\n\n return await this.chunkedUpload({\n filePath,\n totalBytes,\n fileName,\n mimeType,\n options,\n });\n }\n\n /**\n * Upload from in-memory Buffer\n */\n private async uploadFromBuffer(buffer: Buffer, options: UploadOptions): Promise<DriveApiFile> {\n const totalBytes = buffer.length;\n const fileName = options.name || 'untitled';\n const mimeType = options.mimeType || 'application/octet-stream';\n\n return await this.chunkedUploadBuffer({\n buffer,\n totalBytes,\n fileName,\n mimeType,\n options,\n });\n }\n\n /**\n * Upload from generic Readable Stream\n */\n private async uploadFromStream(stream: NodeJS.ReadableStream, options: UploadOptions): Promise<DriveApiFile> {\n const fileName = options.name || 'untitled';\n const mimeType = options.mimeType || 'application/octet-stream';\n\n return await this.directUpload(stream, {\n ...options,\n name: fileName,\n mimeType,\n });\n }\n\n /**\n * Fast direct upload using googleapis multipart\n */\n private async directUpload(stream: NodeJS.ReadableStream, options: UploadOptions): Promise<DriveApiFile> {\n const requestBody: drive_v3.Schema$File = {\n name: options.name,\n mimeType: options.mimeType,\n description: options.description,\n properties: options.properties,\n appProperties: options.appProperties,\n };\n\n if (options.parent) {\n requestBody.parents = [options.parent];\n }\n\n const res = await withRetry(async () => {\n return await this.drive.files.create({\n requestBody,\n media: {\n mimeType: options.mimeType,\n body: stream,\n },\n fields: 'id, name, mimeType, size, webViewLink, webContentLink, createdTime, modifiedTime',\n supportsAllDrives: true,\n });\n });\n\n return res.data;\n }\n\n /**\n * Chunked resumable upload for local files with low memory footprint\n */\n private async chunkedUpload(params: {\n filePath: string;\n totalBytes: number;\n fileName: string;\n mimeType: string;\n options: UploadOptions;\n }): Promise<DriveApiFile> {\n const { filePath, totalBytes, fileName, mimeType, options } = params;\n const chunkSize = options.chunkSize\n ? Math.max(MIN_CHUNK_SIZE, Math.floor(options.chunkSize / MIN_CHUNK_SIZE) * MIN_CHUNK_SIZE)\n : this.defaultChunkSize;\n\n // 1. Initiate Resumable Upload Session\n const sessionUrl = await this.initiateResumableSession({\n fileName,\n mimeType,\n totalBytes,\n parent: options.parent,\n description: options.description,\n properties: options.properties,\n appProperties: options.appProperties,\n });\n\n // 2. Upload Chunks\n const fd = await fs.promises.open(filePath, 'r');\n let bytesSent = 0;\n const startTime = Date.now();\n const totalChunks = Math.ceil(totalBytes / chunkSize) || 1;\n let chunkIndex = 0;\n\n try {\n while (bytesSent < totalBytes) {\n if (options.signal?.aborted) {\n throw new Error('Upload aborted by user signal');\n }\n chunkIndex++;\n const currentChunkSize = Math.min(chunkSize, totalBytes - bytesSent);\n const buffer = Buffer.alloc(currentChunkSize);\n await fd.read(buffer, 0, currentChunkSize, bytesSent);\n\n const rangeStart = bytesSent;\n const rangeEnd = bytesSent + currentChunkSize - 1;\n\n const chunkResult = await this.uploadChunkWithRetry({\n sessionUrl,\n buffer,\n rangeStart,\n rangeEnd,\n totalBytes,\n });\n\n bytesSent += currentChunkSize;\n\n // Progress Calculation\n if (options.onProgress) {\n const elapsedSecs = (Date.now() - startTime) / 1000;\n const bytesPerSecond = elapsedSecs > 0 ? Math.round(bytesSent / elapsedSecs) : 0;\n const remainingBytes = totalBytes - bytesSent;\n const estimatedTimeRemainingSeconds = bytesPerSecond > 0 ? Math.round(remainingBytes / bytesPerSecond) : 0;\n const percentage = totalBytes > 0 ? Math.min(100, Math.round((bytesSent / totalBytes) * 1000) / 10) : 100;\n\n options.onProgress({\n bytesSent,\n totalBytes,\n percentage,\n bytesPerSecond,\n speedFormatted: formatSpeed(bytesPerSecond),\n estimatedTimeRemainingSeconds,\n chunkIndex,\n totalChunks,\n });\n }\n\n if (chunkResult.isComplete && chunkResult.file) {\n return chunkResult.file;\n }\n }\n } finally {\n await fd.close();\n }\n\n throw new DriveUploadError('Resumable upload loop ended without completion response', bytesSent, totalBytes);\n }\n\n /**\n * Chunked resumable upload for memory buffers\n */\n private async chunkedUploadBuffer(params: {\n buffer: Buffer;\n totalBytes: number;\n fileName: string;\n mimeType: string;\n options: UploadOptions;\n }): Promise<DriveApiFile> {\n const { buffer, totalBytes, fileName, mimeType, options } = params;\n const chunkSize = options.chunkSize\n ? Math.max(MIN_CHUNK_SIZE, Math.floor(options.chunkSize / MIN_CHUNK_SIZE) * MIN_CHUNK_SIZE)\n : this.defaultChunkSize;\n\n const sessionUrl = await this.initiateResumableSession({\n fileName,\n mimeType,\n totalBytes,\n parent: options.parent,\n description: options.description,\n properties: options.properties,\n appProperties: options.appProperties,\n });\n\n let bytesSent = 0;\n const startTime = Date.now();\n const totalChunks = Math.ceil(totalBytes / chunkSize) || 1;\n let chunkIndex = 0;\n\n while (bytesSent < totalBytes) {\n if (options.signal?.aborted) {\n throw new Error('Upload aborted by user signal');\n }\n chunkIndex++;\n const currentChunkSize = Math.min(chunkSize, totalBytes - bytesSent);\n const chunk = buffer.subarray(bytesSent, bytesSent + currentChunkSize);\n\n const rangeStart = bytesSent;\n const rangeEnd = bytesSent + currentChunkSize - 1;\n\n const chunkResult = await this.uploadChunkWithRetry({\n sessionUrl,\n buffer: chunk,\n rangeStart,\n rangeEnd,\n totalBytes,\n });\n\n bytesSent += currentChunkSize;\n\n if (options.onProgress) {\n const elapsedSecs = (Date.now() - startTime) / 1000;\n const bytesPerSecond = elapsedSecs > 0 ? Math.round(bytesSent / elapsedSecs) : 0;\n const remainingBytes = totalBytes - bytesSent;\n const estimatedTimeRemainingSeconds = bytesPerSecond > 0 ? Math.round(remainingBytes / bytesPerSecond) : 0;\n const percentage = totalBytes > 0 ? Math.min(100, Math.round((bytesSent / totalBytes) * 1000) / 10) : 100;\n\n options.onProgress({\n bytesSent,\n totalBytes,\n percentage,\n bytesPerSecond,\n speedFormatted: formatSpeed(bytesPerSecond),\n estimatedTimeRemainingSeconds,\n chunkIndex,\n totalChunks,\n });\n }\n\n if (chunkResult.isComplete && chunkResult.file) {\n return chunkResult.file;\n }\n }\n\n throw new DriveUploadError('Resumable buffer upload ended without completion', bytesSent, totalBytes);\n }\n\n /**\n * Request an upload session URI from Google Drive API\n */\n private async initiateResumableSession(meta: {\n fileName: string;\n mimeType: string;\n totalBytes: number;\n parent?: string;\n description?: string;\n properties?: Record<string, string>;\n appProperties?: Record<string, string>;\n }): Promise<string> {\n const authClient = (this.drive as any).context._options.auth;\n const headers: Record<string, string> = {\n 'X-Upload-Content-Type': meta.mimeType,\n 'X-Upload-Content-Length': meta.totalBytes.toString(),\n 'Content-Type': 'application/json; charset=UTF-8',\n };\n\n const metadata: any = {\n name: meta.fileName,\n mimeType: meta.mimeType,\n description: meta.description,\n properties: meta.properties,\n appProperties: meta.appProperties,\n };\n\n if (meta.parent) {\n metadata.parents = [meta.parent];\n }\n\n const res = await withRetry(async () => {\n return await authClient.request({\n url: 'https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&supportsAllDrives=true',\n method: 'POST',\n headers,\n data: metadata,\n });\n });\n\n const sessionUrl = res.headers?.get ? res.headers.get('location') : (res.headers?.location || res.headers?.['location']);\n if (!sessionUrl) {\n throw new DriveUploadError('Failed to initiate resumable upload session: No Location header in response');\n }\n\n return sessionUrl;\n }\n\n /**\n * Upload a chunk with exponential backoff on network failures\n */\n private async uploadChunkWithRetry(params: {\n sessionUrl: string;\n buffer: Buffer;\n rangeStart: number;\n rangeEnd: number;\n totalBytes: number;\n }): Promise<{ isComplete: boolean; file?: DriveApiFile }> {\n const { sessionUrl, buffer, rangeStart, rangeEnd, totalBytes } = params;\n const authClient = (this.drive as any).context._options.auth;\n\n const headers = {\n 'Content-Length': buffer.length.toString(),\n 'Content-Range': `bytes ${rangeStart}-${rangeEnd}/${totalBytes}`,\n };\n\n return await withRetry(async () => {\n try {\n const res = await authClient.request({\n url: sessionUrl,\n method: 'PUT',\n headers,\n data: buffer,\n validateStatus: (status: number) => (status >= 200 && status < 300) || status === 308,\n });\n\n if (res.status === 200 || res.status === 201) {\n return { isComplete: true, file: res.data };\n }\n\n if (res.status === 308) {\n return { isComplete: false };\n }\n\n throw new DriveUploadError(`Unexpected response status ${res.status} during chunk upload`);\n } catch (err: any) {\n if (err.status === 308) {\n return { isComplete: false };\n }\n const msg = err.message || err.response?.data?.error?.message || '';\n if (msg.includes('Service Accounts do not have storage quota') || msg.includes('storageQuotaExceeded')) {\n throw new DriveUploadError(\n 'Google Drive Policy: Service Accounts do not have file storage quota in personal Google accounts. To upload files, use an OAuth2 token or pass accessToken.',\n params.rangeStart,\n params.totalBytes,\n err\n );\n }\n throw err;\n }\n });\n }\n}\n\n","/**\n * Formats bytes to human-readable string (KB, MB, GB)\n */\nexport function formatBytes(bytes: number, decimals = 2): string {\n if (bytes === 0) return '0 B';\n const k = 1024;\n const dm = decimals < 0 ? 0 : decimals;\n const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`;\n}\n\n/**\n * Formats speed in bytes/sec to human readable format (e.g. 5.4 MB/s)\n */\nexport function formatSpeed(bytesPerSecond: number): string {\n return `${formatBytes(bytesPerSecond)}/s`;\n}\n\n/**\n * Formats seconds to mm:ss or hh:mm:ss\n */\nexport function formatDuration(seconds: number): string {\n if (!Number.isFinite(seconds) || seconds < 0) return '--:--';\n const totalSeconds = Math.round(seconds);\n const hrs = Math.floor(totalSeconds / 3600);\n const mins = Math.floor((totalSeconds % 3600) / 60);\n const secs = totalSeconds % 60;\n\n if (hrs > 0) {\n return `${hrs}h ${mins}m ${secs}s`;\n }\n return `${mins}m ${secs}s`;\n}\n\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { pipeline } from 'node:stream/promises';\nimport { Transform } from 'node:stream';\nimport type { drive_v3 } from '@googleapis/drive';\nimport type { DownloadOptions, DownloadProgress } from '../types.js';\nimport { isGoogleWorkspaceDoc, DEFAULT_EXPORT_MIMES, getExtensionForMime } from '../utils/mime.js';\nimport { formatSpeed } from '../utils/format.js';\nimport { withRetry } from '../utils/retry.js';\n\nexport class Downloader {\n private drive: drive_v3.Drive;\n\n constructor(drive: drive_v3.Drive) {\n this.drive = drive;\n }\n\n /**\n * Downloads a file from Google Drive to local destination path or returns a readable stream.\n */\n async download(fileId: string, options: DownloadOptions = {}): Promise<{\n filePath?: string;\n stream?: NodeJS.ReadableStream;\n name: string;\n mimeType: string;\n size?: number;\n }> {\n // 1. Fetch file metadata first\n const metaRes = await withRetry(async () => {\n return await this.drive.files.get({\n fileId,\n fields: 'id, name, mimeType, size',\n supportsAllDrives: true,\n });\n });\n\n const file = metaRes.data;\n const name = file.name || 'downloaded-file';\n const mimeType = file.mimeType || 'application/octet-stream';\n const totalBytes = file.size ? parseInt(file.size, 10) : undefined;\n\n let downloadStream: NodeJS.ReadableStream;\n let finalFileName = name;\n\n // 2. Determine if it's a Google Workspace document needing export\n if (isGoogleWorkspaceDoc(mimeType)) {\n const exportConfig = DEFAULT_EXPORT_MIMES[mimeType] || {\n mimeType: 'application/pdf',\n extension: '.pdf',\n };\n const targetMime = options.exportMimeType || exportConfig.mimeType;\n const ext = getExtensionForMime(targetMime) || exportConfig.extension;\n\n if (!finalFileName.endsWith(ext)) {\n finalFileName = `${finalFileName}${ext}`;\n }\n\n const res = await withRetry(async () => {\n return await this.drive.files.export(\n { fileId, mimeType: targetMime },\n { responseType: 'stream' }\n );\n });\n downloadStream = res.data as NodeJS.ReadableStream;\n } else {\n // Regular binary file download\n const res = await withRetry(async () => {\n return await this.drive.files.get(\n { fileId, alt: 'media', supportsAllDrives: true },\n { responseType: 'stream' }\n );\n });\n downloadStream = res.data as NodeJS.ReadableStream;\n }\n\n // 3. Attach progress tracker if requested\n let bytesRead = 0;\n const startTime = Date.now();\n\n const progressTracker = new Transform({\n transform(chunk, encoding, callback) {\n bytesRead += chunk.length;\n if (options.onProgress) {\n const elapsedSecs = (Date.now() - startTime) / 1000;\n const bytesPerSecond = elapsedSecs > 0 ? Math.round(bytesRead / elapsedSecs) : 0;\n const percentage = totalBytes ? Math.min(100, Math.round((bytesRead / totalBytes) * 1000) / 10) : undefined;\n\n options.onProgress({\n bytesRead,\n totalBytes,\n percentage,\n bytesPerSecond,\n speedFormatted: formatSpeed(bytesPerSecond),\n });\n }\n callback(null, chunk);\n },\n });\n\n const monitoredStream = downloadStream.pipe(progressTracker);\n\n // 4. Save to disk if destination provided, otherwise return stream\n if (options.destination) {\n let destPath = options.destination;\n // If destination is a directory, append finalFileName\n if (fs.existsSync(destPath) && fs.statSync(destPath).isDirectory()) {\n destPath = path.join(destPath, finalFileName);\n }\n\n await fs.promises.mkdir(path.dirname(destPath), { recursive: true });\n const writeStream = fs.createWriteStream(destPath);\n await pipeline(monitoredStream, writeStream);\n\n return {\n filePath: destPath,\n name: finalFileName,\n mimeType,\n size: bytesRead,\n };\n }\n\n return {\n stream: monitoredStream,\n name: finalFileName,\n mimeType,\n size: totalBytes,\n };\n }\n\n /**\n * Returns a raw ReadableStream for the file, supporting HTTP Range requests for partial content / streaming.\n */\n async createReadStream(\n fileId: string,\n options?: { start?: number; end?: number }\n ): Promise<NodeJS.ReadableStream> {\n const headers: Record<string, string> = {};\n if (options?.start !== undefined || options?.end !== undefined) {\n const start = options.start ?? 0;\n const end = options.end !== undefined ? options.end : '';\n headers['Range'] = `bytes=${start}-${end}`;\n }\n\n const res = await withRetry(async () => {\n return await this.drive.files.get(\n { fileId, alt: 'media', supportsAllDrives: true },\n { responseType: 'stream', headers }\n );\n });\n return res.data as NodeJS.ReadableStream;\n }\n}\n\n","import type { drive_v3 } from '@googleapis/drive';\nimport type { DriveApiFile } from '../types.js';\nimport { GOOGLE_WORKSPACE_MIME_TYPES } from '../utils/mime.js';\nimport { withRetry } from '../utils/retry.js';\n\nexport class DriveQueryBuilder {\n private drive: drive_v3.Drive;\n private conditions: string[] = [];\n private orderClauses: string[] = [];\n private limitNumber = 100;\n private requestedFields = 'nextPageToken, files(id, name, mimeType, size, modifiedTime, createdTime, parents, trashed, webViewLink, webContentLink, shared)';\n private spaces = 'drive';\n\n constructor(drive: drive_v3.Drive) {\n this.drive = drive;\n }\n\n /**\n * Escape single quotes and backslashes for Google Drive search queries\n */\n private escape(str: string): string {\n return str.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\");\n }\n\n /**\n * Filter: Exact file name match\n */\n nameEquals(name: string): this {\n this.conditions.push(`name = '${this.escape(name)}'`);\n return this;\n }\n\n /**\n * Filter: File name contains substring\n */\n nameContains(substring: string): this {\n this.conditions.push(`name contains '${this.escape(substring)}'`);\n return this;\n }\n\n /**\n * Filter: Specific MIME type\n */\n mimeType(mime: string): this {\n this.conditions.push(`mimeType = '${this.escape(mime)}'`);\n return this;\n }\n\n /**\n * Filter: Only folders\n */\n isFolder(): this {\n this.conditions.push(`mimeType = '${GOOGLE_WORKSPACE_MIME_TYPES.FOLDER}'`);\n return this;\n }\n\n /**\n * Filter: Exclude folders (only files)\n */\n isFile(): this {\n this.conditions.push(`mimeType != '${GOOGLE_WORKSPACE_MIME_TYPES.FOLDER}'`);\n return this;\n }\n\n /**\n * Filter: Direct parent folder ID\n */\n inFolder(folderId: string): this {\n this.conditions.push(`'${this.escape(folderId)}' in parents`);\n return this;\n }\n\n /**\n * Filter: Items not in trash (default recommended)\n */\n notTrashed(): this {\n this.conditions.push('trashed = false');\n return this;\n }\n\n /**\n * Filter: Only trashed items\n */\n onlyTrashed(): this {\n this.conditions.push('trashed = true');\n return this;\n }\n\n /**\n * Filter: Starred items\n */\n starred(isStarred = true): this {\n this.conditions.push(`starred = ${isStarred}`);\n return this;\n }\n\n /**\n * Filter: Shared with current user\n */\n sharedWithMe(): this {\n this.conditions.push('sharedWithMe = true');\n return this;\n }\n\n /**\n * Filter: Modified after timestamp or Date\n */\n modifiedAfter(date: Date | string): this {\n const iso = date instanceof Date ? date.toISOString() : new Date(date).toISOString();\n this.conditions.push(`modifiedTime > '${iso}'`);\n return this;\n }\n\n /**\n * Filter: Modified before timestamp or Date\n */\n modifiedBefore(date: Date | string): this {\n const iso = date instanceof Date ? date.toISOString() : new Date(date).toISOString();\n this.conditions.push(`modifiedTime < '${iso}'`);\n return this;\n }\n\n /**\n * Filter: Full-text search across content and name\n */\n fullText(term: string): this {\n this.conditions.push(`fullText contains '${this.escape(term)}'`);\n return this;\n }\n\n /**\n * Custom raw query condition\n */\n raw(condition: string): this {\n this.conditions.push(`(${condition})`);\n return this;\n }\n\n /**\n * Custom raw query condition (alias for raw)\n */\n custom(condition: string): this {\n return this.raw(condition);\n }\n\n /**\n * Filter: Exact MD5 checksum match\n */\n md5(checksum: string): this {\n this.conditions.push(`md5Checksum = '${this.escape(checksum)}'`);\n return this;\n }\n\n /**\n * Sort ordering (e.g. 'modifiedTime desc', 'name', 'folder,modifiedTime desc')\n */\n orderBy(order: string): this {\n this.orderClauses.push(order);\n return this;\n }\n\n /**\n * Maximum items to retrieve per page or query\n */\n pageSize(size: number): this {\n this.limitNumber = Math.min(1000, Math.max(1, size));\n return this;\n }\n\n /**\n * Custom fields to return from Drive API\n */\n fields(fieldsString: string): this {\n this.requestedFields = fieldsString;\n return this;\n }\n\n /**\n * Compiles the full query string\n */\n toQueryString(): string {\n return this.conditions.join(' and ');\n }\n\n /**\n * Executes query and returns array of matching files\n */\n async list(): Promise<DriveApiFile[]> {\n const q = this.toQueryString();\n const orderBy = this.orderClauses.join(', ');\n\n const res = await withRetry(async () => {\n return await this.drive.files.list({\n q: q || undefined,\n orderBy: orderBy || undefined,\n pageSize: this.limitNumber,\n fields: this.requestedFields,\n spaces: this.spaces,\n supportsAllDrives: true,\n includeItemsFromAllDrives: true,\n });\n });\n\n return res.data.files || [];\n }\n\n /**\n * Executes query and returns array of matching files (alias for list)\n */\n async execute(): Promise<DriveApiFile[]> {\n return await this.list();\n }\n\n /**\n * Returns the first matching file, or null if not found\n */\n async first(): Promise<DriveApiFile | null> {\n const originalLimit = this.limitNumber;\n this.limitNumber = 1;\n const items = await this.list();\n this.limitNumber = originalLimit;\n return items[0] || null;\n }\n\n /**\n * Counts matching items (up to 1000)\n */\n async count(): Promise<number> {\n const items = await this.list();\n return items.length;\n }\n\n /**\n * Async iterator to stream all pages automatically without loading all into memory\n */\n async *[Symbol.asyncIterator](): AsyncIterableIterator<DriveApiFile> {\n const q = this.toQueryString();\n const orderBy = this.orderClauses.join(', ');\n let pageToken: string | undefined = undefined;\n\n do {\n const res = await withRetry(async () => {\n return await this.drive.files.list({\n q: q || undefined,\n orderBy: orderBy || undefined,\n pageSize: this.limitNumber,\n pageToken,\n fields: this.requestedFields,\n spaces: this.spaces,\n supportsAllDrives: true,\n includeItemsFromAllDrives: true,\n });\n });\n\n const files = res.data.files || [];\n for (const file of files) {\n yield file;\n }\n pageToken = res.data.nextPageToken || undefined;\n } while (pageToken);\n }\n}\n\n","/**\n * Lightweight asynchronous worker pool for concurrent operations\n */\nexport class ConcurrencyPool {\n private concurrency: number;\n private running = 0;\n private queue: (() => Promise<void>)[] = [];\n\n constructor(concurrency = 4) {\n this.concurrency = Math.max(1, concurrency);\n }\n\n /**\n * Run a task when a slot becomes available\n */\n async run<T>(task: () => Promise<T>): Promise<T> {\n if (this.running >= this.concurrency) {\n await new Promise<void>((resolve) => {\n this.queue.push(async () => {\n resolve();\n });\n });\n }\n\n this.running++;\n try {\n return await task();\n } finally {\n this.running--;\n if (this.queue.length > 0) {\n const next = this.queue.shift();\n if (next) next();\n }\n }\n }\n\n /**\n * Run all tasks in parallel bounded by concurrency limit\n */\n async all<T>(tasks: (() => Promise<T>)[]): Promise<T[]> {\n return Promise.all(tasks.map((task) => this.run(task)));\n }\n\n /**\n * Execute an array of items concurrently through an async mapper\n */\n async map<Item, Result>(\n items: Item[],\n fn: (item: Item, index: number) => Promise<Result>\n ): Promise<Result[]> {\n return Promise.all(items.map((item, index) => this.run(() => fn(item, index))));\n }\n}\n\n","import { EventEmitter } from 'node:events';\nimport type { drive_v3 } from '@googleapis/drive';\nimport type { DriveApiFile } from '../types.js';\nimport { withRetry } from '../utils/retry.js';\n\nexport interface WatcherOptions {\n /** Polling interval in milliseconds (default: 5000) */\n intervalMs?: number;\n /** Restrict changes to a specific folder ID or path */\n folderId?: string;\n /** Whether to emit initial existing files on startup (default: false) */\n emitInitial?: boolean;\n}\n\nexport interface FileChangeEvent {\n type: 'create' | 'modify' | 'delete';\n fileId: string;\n file?: DriveApiFile;\n removed?: boolean;\n time: Date;\n}\n\n/**\n * Real-time Google Drive Change Watcher\n * Listens for new files, updates, and deletions using the Google Drive Changes API.\n */\nexport class DriveWatcher extends EventEmitter {\n private drive: drive_v3.Drive;\n private options: WatcherOptions;\n private timer: NodeJS.Timeout | null = null;\n private isRunning = false;\n private pageToken: string | null = null;\n\n constructor(drive: drive_v3.Drive, options: WatcherOptions = {}) {\n super();\n this.drive = drive;\n this.options = {\n intervalMs: 5000,\n ...options,\n };\n }\n\n /**\n * Starts listening for changes\n */\n async start(): Promise<this> {\n if (this.isRunning) return this;\n this.isRunning = true;\n\n // Get initial start page token\n if (!this.pageToken) {\n const tokenRes = await withRetry(async () => {\n return await this.drive.changes.getStartPageToken({\n supportsAllDrives: true,\n });\n });\n this.pageToken = tokenRes.data.startPageToken || null;\n }\n\n this.poll();\n return this;\n }\n\n /**\n * Stops listening\n */\n stop(): void {\n this.isRunning = false;\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n this.emit('stop');\n }\n\n /**\n * Internal polling cycle\n */\n private async poll(): Promise<void> {\n if (!this.isRunning) return;\n\n try {\n if (!this.pageToken) {\n const tokenRes = await withRetry(async () => {\n return await this.drive.changes.getStartPageToken({\n supportsAllDrives: true,\n });\n });\n this.pageToken = tokenRes.data.startPageToken || null;\n }\n\n let nextPageToken = this.pageToken;\n\n do {\n const res = await withRetry(async () => {\n return await this.drive.changes.list({\n pageToken: nextPageToken!,\n fields: 'nextPageToken, newStartPageToken, changes(changeType, fileId, removed, time, file(id, name, mimeType, size, modifiedTime, parents, trashed))',\n supportsAllDrives: true,\n includeItemsFromAllDrives: true,\n });\n });\n\n const changes = res.data.changes || [];\n\n for (const change of changes) {\n if (!change.fileId) continue;\n\n // If restricted to a folder, check parents\n if (this.options.folderId && change.file) {\n const parents = change.file.parents || [];\n if (!parents.includes(this.options.folderId)) {\n continue;\n }\n }\n\n let eventType: 'create' | 'modify' | 'delete' = 'modify';\n if (change.removed || change.file?.trashed) {\n eventType = 'delete';\n } else if (change.file?.createdTime && change.file?.modifiedTime) {\n const created = new Date(change.file.createdTime).getTime();\n const modified = new Date(change.file.modifiedTime).getTime();\n if (Math.abs(modified - created) < 2000) {\n eventType = 'create';\n }\n }\n\n const eventPayload: FileChangeEvent = {\n type: eventType,\n fileId: change.fileId,\n file: change.file || undefined,\n removed: change.removed || false,\n time: change.time ? new Date(change.time) : new Date(),\n };\n\n this.emit('change', eventPayload);\n this.emit(eventType, eventPayload);\n }\n\n if (res.data.newStartPageToken) {\n this.pageToken = res.data.newStartPageToken;\n break;\n }\n\n nextPageToken = res.data.nextPageToken || null;\n } while (nextPageToken);\n } catch (err) {\n this.emit('error', err);\n } finally {\n if (this.isRunning) {\n this.timer = setTimeout(() => this.poll(), this.options.intervalMs);\n }\n }\n }\n}\n\n","import type { drive_v3 } from '@googleapis/drive';\nimport type { DriveApiFile } from '../types.js';\nimport { withRetry } from '../utils/retry.js';\nimport { formatBytes } from '../utils/format.js';\n\nexport interface DuplicateGroup {\n name: string;\n count: number;\n totalSize: number;\n formattedTotalSize: string;\n files: { id: string; name: string; size: number; modifiedTime: string; md5Checksum?: string }[];\n}\n\nexport class StorageCleaner {\n private drive: drive_v3.Drive;\n\n constructor(drive: drive_v3.Drive) {\n this.drive = drive;\n }\n\n /**\n * Finds the largest files occupying space in the Google Drive account\n */\n async findLargestFiles(limit = 10): Promise<{\n id: string;\n name: string;\n size: number;\n formattedSize: string;\n mimeType: string;\n modifiedTime?: string;\n webViewLink?: string;\n }[]> {\n const res = await withRetry(async () => {\n return await this.drive.files.list({\n q: 'trashed = false and mimeType != \"application/vnd.google-apps.folder\"',\n orderBy: 'quotaBytesUsed desc',\n pageSize: Math.min(100, Math.max(1, limit)),\n fields: 'files(id, name, size, mimeType, modifiedTime, webViewLink, quotaBytesUsed)',\n supportsAllDrives: true,\n includeItemsFromAllDrives: true,\n });\n });\n\n const files = res.data.files || [];\n return files.map((f) => {\n const sizeBytes = parseInt(f.size || f.quotaBytesUsed || '0', 10);\n return {\n id: f.id!,\n name: f.name || 'untitled',\n size: sizeBytes,\n formattedSize: formatBytes(sizeBytes),\n mimeType: f.mimeType || 'unknown',\n modifiedTime: f.modifiedTime || undefined,\n webViewLink: f.webViewLink || undefined,\n };\n });\n }\n\n /**\n * Scans Google Drive and detects duplicate files (by MD5 hash or exact name)\n */\n async findDuplicates(options: { by?: 'md5' | 'name'; maxScan?: number } = {}): Promise<DuplicateGroup[]> {\n const mode = options.by || 'name';\n const maxScan = options.maxScan || 1000;\n\n const res = await withRetry(async () => {\n return await this.drive.files.list({\n q: 'trashed = false and mimeType != \"application/vnd.google-apps.folder\"',\n pageSize: Math.min(1000, maxScan),\n fields: 'files(id, name, size, md5Checksum, modifiedTime)',\n supportsAllDrives: true,\n includeItemsFromAllDrives: true,\n });\n });\n\n const files = res.data.files || [];\n const map = new Map<string, any[]>();\n\n for (const f of files) {\n if (!f.id) continue;\n const key = mode === 'md5' && f.md5Checksum ? f.md5Checksum : (f.name || '');\n if (!key) continue;\n\n if (!map.has(key)) {\n map.set(key, []);\n }\n map.get(key)!.push(f);\n }\n\n const duplicates: DuplicateGroup[] = [];\n for (const [key, group] of map.entries()) {\n if (group.length > 1) {\n let totalSize = 0;\n const mappedFiles = group.map((item) => {\n const s = parseInt(item.size || '0', 10);\n totalSize += s;\n return {\n id: item.id,\n name: item.name,\n size: s,\n modifiedTime: item.modifiedTime,\n md5Checksum: item.md5Checksum,\n };\n });\n\n duplicates.push({\n name: key,\n count: group.length,\n totalSize,\n formattedTotalSize: formatBytes(totalSize),\n files: mappedFiles,\n });\n }\n }\n\n return duplicates.sort((a, b) => b.totalSize - a.totalSize);\n }\n\n /**\n * Empties the entire trash in Google Drive\n */\n async emptyTrash(): Promise<void> {\n await withRetry(async () => {\n await this.drive.files.emptyTrash({});\n });\n }\n}\n\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport crypto from 'node:crypto';\nimport type { drive_v3 } from '@googleapis/drive';\nimport type { DriveApiFile } from '../types.js';\nimport { ConcurrencyPool } from './concurrency-pool.js';\nimport { Downloader } from './downloader.js';\nimport { withRetry } from '../utils/retry.js';\nimport { formatBytes } from '../utils/format.js';\n\n/**\n * Calculates MD5 checksum of a local file via streams (low memory)\n */\nexport async function calculateFileMd5(filePath: string): Promise<string> {\n return new Promise((resolve, reject) => {\n const hash = crypto.createHash('md5');\n const stream = fs.createReadStream(filePath);\n stream.on('data', (chunk) => hash.update(chunk));\n stream.on('end', () => resolve(hash.digest('hex')));\n stream.on('error', reject);\n });\n}\n\nexport interface PullResult {\n downloaded: { remoteId: string; remoteName: string; localPath: string; size: number }[];\n skipped: { remoteId: string; remoteName: string; reason: string }[];\n failed: { remoteId: string; remoteName: string; error: Error }[];\n totalBytes: number;\n durationMs: number;\n}\n\nexport class SmartSyncEngine {\n private drive: drive_v3.Drive;\n private downloader: Downloader;\n\n constructor(drive: drive_v3.Drive) {\n this.drive = drive;\n this.downloader = new Downloader(drive);\n }\n\n /**\n * Pulls (downloads) an entire Google Drive folder tree to a local directory\n */\n async pullFolder(\n remoteFolderId: string,\n localDestinationDir: string,\n options: {\n concurrency?: number;\n overwrite?: boolean;\n onFileStart?: (remoteName: string, relativePath: string) => void;\n onFileComplete?: (remoteName: string, localPath: string) => void;\n } = {}\n ): Promise<PullResult> {\n const startTime = Date.now();\n const concurrency = options.concurrency || 4;\n const pool = new ConcurrencyPool(concurrency);\n\n const result: PullResult = {\n downloaded: [],\n skipped: [],\n failed: [],\n totalBytes: 0,\n durationMs: 0,\n };\n\n await fs.promises.mkdir(localDestinationDir, { recursive: true });\n\n // Recursive remote listing\n const collectRemoteItems = async (folderId: string, relPath: string): Promise<{\n id: string;\n name: string;\n isFolder: boolean;\n relPath: string;\n size: number;\n md5Checksum?: string;\n }[]> => {\n const items: any[] = [];\n let pageToken: string | undefined = undefined;\n\n do {\n const res = await withRetry(async () => {\n return await this.drive.files.list({\n q: `'${folderId}' in parents and trashed = false`,\n fields: 'nextPageToken, files(id, name, mimeType, size, md5Checksum)',\n pageSize: 500,\n supportsAllDrives: true,\n includeItemsFromAllDrives: true,\n });\n });\n\n const files = res.data.files || [];\n for (const file of files) {\n if (!file.id || !file.name) continue;\n const isFolder = file.mimeType === 'application/vnd.google-apps.folder';\n const fileRel = relPath ? path.join(relPath, file.name) : file.name;\n\n if (isFolder) {\n const sub = await collectRemoteItems(file.id, fileRel);\n items.push(...sub);\n } else {\n items.push({\n id: file.id,\n name: file.name,\n isFolder: false,\n relPath: fileRel,\n size: parseInt(file.size || '0', 10),\n md5Checksum: file.md5Checksum,\n });\n }\n }\n pageToken = res.data.nextPageToken || undefined;\n } while (pageToken);\n\n return items;\n };\n\n const remoteFiles = await collectRemoteItems(remoteFolderId, '');\n\n await pool.map(remoteFiles, async (remoteItem) => {\n const localFilePath = path.join(localDestinationDir, remoteItem.relPath);\n\n // Check if local file already exists and matches MD5 or size\n if (!options.overwrite && fs.existsSync(localFilePath)) {\n const localStat = await fs.promises.stat(localFilePath);\n if (remoteItem.md5Checksum) {\n const localMd5 = await calculateFileMd5(localFilePath);\n if (localMd5.toLowerCase() === remoteItem.md5Checksum.toLowerCase()) {\n result.skipped.push({\n remoteId: remoteItem.id,\n remoteName: remoteItem.name,\n reason: 'Identical MD5 checksum matches local file',\n });\n return;\n }\n } else if (localStat.size === remoteItem.size && remoteItem.size > 0) {\n result.skipped.push({\n remoteId: remoteItem.id,\n remoteName: remoteItem.name,\n reason: 'Identical file size exists locally',\n });\n return;\n }\n }\n\n try {\n if (options.onFileStart) {\n options.onFileStart(remoteItem.name, remoteItem.relPath);\n }\n\n await this.downloader.download(remoteItem.id, {\n destination: localFilePath,\n });\n\n result.downloaded.push({\n remoteId: remoteItem.id,\n remoteName: remoteItem.name,\n localPath: localFilePath,\n size: remoteItem.size,\n });\n result.totalBytes += remoteItem.size;\n\n if (options.onFileComplete) {\n options.onFileComplete(remoteItem.name, localFilePath);\n }\n } catch (err: any) {\n result.failed.push({\n remoteId: remoteItem.id,\n remoteName: remoteItem.name,\n error: err,\n });\n }\n });\n\n result.durationMs = Date.now() - startTime;\n return result;\n }\n}\n\n","import http from 'node:http';\nimport { exec } from 'node:child_process';\nimport { auth as googleAuth } from '@googleapis/drive';\nimport { DEFAULT_SCOPES } from './authenticator.js';\n\nexport interface BrowserLoginOptions {\n clientId: string;\n clientSecret: string;\n port?: number;\n scopes?: string[];\n}\n\nexport interface LoginResult {\n tokens: {\n access_token?: string | null;\n refresh_token?: string | null;\n expiry_date?: number | null;\n token_type?: string | null;\n };\n client: any;\n}\n\n/**\n * Initiates interactive 1-click browser login flow:\n * 1. Starts ephemeral local callback server\n * 2. Opens default browser to Google OAuth consent\n * 3. Catches callback, exchanges code for tokens, and serves success page\n */\nexport async function loginWithBrowser(options: BrowserLoginOptions): Promise<LoginResult> {\n const port = options.port || 3000;\n const redirectUri = `http://localhost:${port}/oauth2callback`;\n const scopes = options.scopes || DEFAULT_SCOPES;\n\n const oauth2Client = new googleAuth.OAuth2(\n options.clientId,\n options.clientSecret,\n redirectUri\n );\n\n const authUrl = oauth2Client.generateAuthUrl({\n access_type: 'offline',\n prompt: 'consent',\n scope: scopes,\n });\n\n return new Promise((resolve, reject) => {\n const server = http.createServer(async (req, res) => {\n try {\n const reqUrl = new URL(req.url || '/', `http://localhost:${port}`);\n if (reqUrl.pathname === '/oauth2callback') {\n const code = reqUrl.searchParams.get('code');\n const error = reqUrl.searchParams.get('error');\n\n if (error) {\n res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });\n res.end(`<h2>❌ Authorization Failed</h2><p>${error}</p>`);\n server.close();\n return reject(new Error(`OAuth error: ${error}`));\n }\n\n if (!code) {\n res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });\n res.end('<h2>❌ Missing authorization code</h2>');\n return;\n }\n\n // Exchange code for tokens\n const { tokens } = await oauth2Client.getToken(code);\n oauth2Client.setCredentials(tokens);\n\n // Render Success Page\n res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });\n res.end(`\n <!DOCTYPE html>\n <html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n <title>DriveKit Authentication</title>\n <style>\n body {\n font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, sans-serif;\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100vh;\n margin: 0;\n background: #0f172a;\n color: #f8fafc;\n }\n .card {\n text-align: center;\n padding: 40px;\n background: #1e293b;\n border-radius: 16px;\n box-shadow: 0 10px 25px rgba(0,0,0,0.5);\n }\n .badge {\n font-size: 48px;\n margin-bottom: 12px;\n }\n h1 { color: #38bdf8; margin: 0 0 10px 0; }\n p { color: #94a3b8; font-size: 16px; }\n </style>\n </head>\n <body>\n <div class=\"card\">\n <div class=\"badge\">⚡</div>\n <h1>Authentication Successful!</h1>\n <p>DriveKit is now connected to your Google Drive account.</p>\n <p>You can close this window and return to your terminal.</p>\n </div>\n </body>\n </html>\n `);\n\n server.close();\n resolve({ tokens, client: oauth2Client });\n }\n } catch (err) {\n res.writeHead(500, { 'Content-Type': 'text/html; charset=utf-8' });\n res.end(`<h2>❌ Server Error</h2><p>${(err as any).message}</p>`);\n server.close();\n reject(err);\n }\n });\n\n server.listen(port, () => {\n // Launch browser\n const openCmd = process.platform === 'darwin'\n ? `open \"${authUrl}\"`\n : process.platform === 'win32'\n ? `start \"\" \"${authUrl}\"`\n : `xdg-open \"${authUrl}\"`;\n\n exec(openCmd, (err) => {\n if (err) {\n console.log(`\\nPlease open the following URL in your browser to sign in:\\n${authUrl}\\n`);\n }\n });\n });\n\n server.on('error', (err) => {\n reject(err);\n });\n });\n}\n\n","import type { DriveKit } from './client.js';\nimport type {\n DriveApiFile,\n DriveApiPermission,\n DownloadOptions,\n ShareOptions,\n UploadOptions,\n SyncResult,\n} from '../types.js';\nimport type { PullResult } from './smart-sync.js';\nimport type { WatcherOptions, DriveWatcher } from './watcher.js';\n\n/**\n * Fluent reference to a specific file in Google Drive\n */\nexport class DriveFileRef {\n private drive: DriveKit;\n public readonly pathOrId: string;\n\n constructor(drive: DriveKit, pathOrId: string) {\n this.drive = drive;\n this.pathOrId = pathOrId;\n }\n\n /** Gets file metadata */\n async get(): Promise<DriveApiFile> {\n return await this.drive.getFile(this.pathOrId);\n }\n\n /** Checks if the file exists */\n async exists(): Promise<boolean> {\n return await this.drive.exists(this.pathOrId);\n }\n\n /** Reads file as UTF-8 string */\n async getText(): Promise<string> {\n return await this.drive.getText(this.pathOrId);\n }\n\n /** Reads and parses JSON file */\n async getJson<T = any>(): Promise<T> {\n return await this.drive.getJson<T>(this.pathOrId);\n }\n\n /** Downloads the file to destination */\n async download(optionsOrDestination?: string | DownloadOptions) {\n const opts = typeof optionsOrDestination === 'string'\n ? { destination: optionsOrDestination }\n : optionsOrDestination;\n return await this.drive.download(this.pathOrId, opts);\n }\n\n /** Moves the file to a new folder path or ID */\n async moveTo(newParentPathOrId: string): Promise<DriveApiFile> {\n return await this.drive.move(this.pathOrId, newParentPathOrId);\n }\n\n /** Copies the file to a target directory */\n async copyTo(parentPathOrId?: string, newName?: string): Promise<DriveApiFile> {\n return await this.drive.copy(this.pathOrId, { parent: parentPathOrId, name: newName });\n }\n\n /** Renames the file */\n async rename(newName: string): Promise<DriveApiFile> {\n return await this.drive.rename(this.pathOrId, newName);\n }\n\n /** Deletes the file (or moves to trash if permanent is false) */\n async delete(permanent = false): Promise<void> {\n return await this.drive.delete(this.pathOrId, permanent);\n }\n\n /** Moves file to trash */\n async trash(): Promise<void> {\n return await this.drive.trash(this.pathOrId);\n }\n\n /** Shares file */\n async share(options: ShareOptions): Promise<DriveApiPermission> {\n return await this.drive.share(this.pathOrId, options);\n }\n\n /** Makes file publicly accessible */\n async sharePublic(role: 'reader' | 'commenter' | 'writer' = 'reader') {\n return await this.drive.sharePublic(this.pathOrId, role);\n }\n\n /** Gets public/preview links */\n async getLink() {\n return await this.drive.getShareableLink(this.pathOrId);\n }\n\n /** Returns a ReadableStream for this file, optionally with byte Range requests */\n async createReadStream(options?: { start?: number; end?: number }): Promise<NodeJS.ReadableStream> {\n return await this.drive.createReadStream(this.pathOrId, options);\n }\n\n /** Grants access to a specific email with custom role and notification */\n async grantAccess(options: {\n email: string;\n role?: 'reader' | 'commenter' | 'writer';\n notify?: boolean;\n message?: string;\n }): Promise<DriveApiPermission> {\n return await this.drive.grantAccess(this.pathOrId, options);\n }\n\n /** Revokes access by permission ID or user email */\n async revokeAccess(permissionIdOrEmail: string): Promise<void> {\n return await this.drive.revokeAccess(this.pathOrId, permissionIdOrEmail);\n }\n\n /** Lists all granted permissions on this file */\n async listPermissions(): Promise<DriveApiPermission[]> {\n return await this.drive.listPermissions(this.pathOrId);\n }\n}\n\n/**\n * Fluent reference to a specific folder in Google Drive\n */\nexport class DriveFolderRef {\n private drive: DriveKit;\n public readonly pathOrId: string;\n\n constructor(drive: DriveKit, pathOrId: string) {\n this.drive = drive;\n this.pathOrId = pathOrId;\n }\n\n /** Lists contents of this folder */\n async ls(): Promise<DriveApiFile[]> {\n return await this.drive.ls(this.pathOrId);\n }\n\n /** Ensures this folder and subpaths exist (mkdir -p) */\n async mkdirp(subPath?: string): Promise<string> {\n const target = subPath\n ? (this.pathOrId.endsWith('/') ? `${this.pathOrId}${subPath}` : `${this.pathOrId}/${subPath}`)\n : this.pathOrId;\n return await this.drive.mkdirp(target);\n }\n\n /** Uploads a file directly into this folder */\n async upload(source: UploadOptions['source'], options: Omit<UploadOptions, 'source' | 'parent'> = {}): Promise<DriveApiFile> {\n return await this.drive.upload({\n ...options,\n source,\n parent: this.pathOrId,\n });\n }\n\n /** Synchronizes a local directory into this remote folder */\n async syncFrom(localDir: string, options: Parameters<DriveKit['syncFolder']>[2] = {}): Promise<SyncResult> {\n return await this.drive.syncFolder(localDir, this.pathOrId, options);\n }\n\n /** Pulls this remote folder down to local directory */\n async pullTo(localDestinationDir: string, options: Parameters<DriveKit['pull']>[2] = {}): Promise<PullResult> {\n return await this.drive.pull(this.pathOrId, localDestinationDir, options);\n }\n\n /** Watches this folder for real-time changes */\n async watch(options: Omit<WatcherOptions, 'folderId'> = {}): Promise<DriveWatcher> {\n return await this.drive.watch(this.pathOrId, options);\n }\n\n /** Grants access to this entire folder */\n async grantAccess(options: {\n email: string;\n role?: 'reader' | 'commenter' | 'writer';\n notify?: boolean;\n message?: string;\n }): Promise<DriveApiPermission> {\n return await this.drive.grantAccess(this.pathOrId, options);\n }\n\n /** Creates a writable stream directly into a file inside this folder */\n async createWriteStream(\n fileName: string,\n options?: Omit<UploadOptions, 'source' | 'filename' | 'parent'>\n ): Promise<NodeJS.WritableStream> {\n const targetPath = this.pathOrId.endsWith('/') ? `${this.pathOrId}${fileName}` : `${this.pathOrId}/${fileName}`;\n return await this.drive.createWriteStream(targetPath, options);\n }\n}\n\n","import type { UploadOptions, DownloadOptions, DriveApiFile } from '../types.js';\n\nexport interface DriveKitPlugin {\n name: string;\n beforeUpload?: (options: UploadOptions) => Promise<UploadOptions | void> | UploadOptions | void;\n afterUpload?: (file: DriveApiFile) => Promise<DriveApiFile | void> | DriveApiFile | void;\n beforeDownload?: (fileId: string, options: DownloadOptions) => Promise<DownloadOptions | void> | DownloadOptions | void;\n afterDownload?: (result: any) => Promise<any | void> | any | void;\n}\n\nexport class PluginManager {\n private plugins: DriveKitPlugin[] = [];\n\n use(plugin: DriveKitPlugin): this {\n this.plugins.push(plugin);\n return this;\n }\n\n async runBeforeUpload(options: UploadOptions): Promise<UploadOptions> {\n let current = { ...options };\n for (const plugin of this.plugins) {\n if (plugin.beforeUpload) {\n const modified = await plugin.beforeUpload(current);\n if (modified) current = modified;\n }\n }\n return current;\n }\n\n async runAfterUpload(file: DriveApiFile): Promise<DriveApiFile> {\n let current = file;\n for (const plugin of this.plugins) {\n if (plugin.afterUpload) {\n const modified = await plugin.afterUpload(current);\n if (modified) current = modified;\n }\n }\n return current;\n }\n\n async runBeforeDownload(fileId: string, options: DownloadOptions): Promise<DownloadOptions> {\n let current = { ...options };\n for (const plugin of this.plugins) {\n if (plugin.beforeDownload) {\n const modified = await plugin.beforeDownload(fileId, current);\n if (modified) current = modified;\n }\n }\n return current;\n }\n\n async runAfterDownload(result: any): Promise<any> {\n let current = result;\n for (const plugin of this.plugins) {\n if (plugin.afterDownload) {\n const modified = await plugin.afterDownload(current);\n if (modified) current = modified;\n }\n }\n return current;\n }\n}\n\n/**\n * Creates an official Webhook Plugin to notify external services (Slack, Discord, Telegram, Zapier)\n * when uploads or downloads finish.\n */\nexport function createWebhookPlugin(options: {\n url: string;\n headers?: Record<string, string>;\n events?: ('upload' | 'download')[];\n}): DriveKitPlugin {\n const events = options.events || ['upload'];\n\n return {\n name: 'drivekit-official-webhook',\n async afterUpload(file) {\n if (!events.includes('upload')) return;\n try {\n await fetch(options.url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...(options.headers || {}) },\n body: JSON.stringify({\n event: 'drivekit:upload',\n timestamp: new Date().toISOString(),\n file: {\n id: file.id,\n name: file.name,\n size: file.size,\n mimeType: file.mimeType,\n },\n }),\n });\n } catch (e) {\n // Silently swallow webhook errors to avoid interrupting operations\n }\n },\n async afterDownload(result) {\n if (!events.includes('download')) return;\n try {\n await fetch(options.url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...(options.headers || {}) },\n body: JSON.stringify({\n event: 'drivekit:download',\n timestamp: new Date().toISOString(),\n file: {\n name: result.name,\n size: result.size,\n },\n }),\n });\n } catch (e) {\n // ignore\n }\n },\n };\n}\n\n/**\n * Creates an Auto-Namer Plugin to automatically prefix/suffix or timestamp files\n */\nexport function createAutoNamePlugin(options: {\n prefix?: string;\n suffix?: string;\n appendTimestamp?: boolean;\n}): DriveKitPlugin {\n return {\n name: 'drivekit-official-autoname',\n beforeUpload(opts) {\n let name = opts.filename;\n if (!name && typeof opts.source === 'string') {\n const pathModule = require('node:path');\n name = pathModule.basename(opts.source);\n }\n if (!name) return opts;\n\n const pathModule = require('node:path');\n const ext = pathModule.extname(name);\n const base = pathModule.basename(name, ext);\n\n let finalName = base;\n if (options.prefix) finalName = `${options.prefix}${finalName}`;\n if (options.appendTimestamp) {\n finalName = `${finalName}_${Date.now()}`;\n }\n if (options.suffix) finalName = `${finalName}${options.suffix}`;\n finalName = `${finalName}${ext}`;\n\n return {\n ...opts,\n filename: finalName,\n };\n },\n };\n}\n\n","import os from 'node:os';\nimport path from 'node:path';\nimport fs from 'node:fs';\n\nexport interface CacheFileEntry {\n id: string;\n name: string;\n mimeType: string;\n size?: number;\n parentId?: string;\n path?: string;\n md5Checksum?: string;\n trashed: boolean;\n modifiedTime?: string;\n updatedAt?: number;\n}\n\nexport interface CacheStats {\n fileCount: number;\n folderCount: number;\n totalSizeBytes: number;\n lastSyncTime: string | null;\n databasePath: string;\n}\n\nexport interface IMetadataCache {\n init(): void;\n getById(id: string): CacheFileEntry | null;\n getByPath(normalizedPath: string): CacheFileEntry | null;\n getChildren(parentId: string): CacheFileEntry[];\n findByMd5(md5: string): CacheFileEntry | null;\n searchByName(query: string): CacheFileEntry[];\n upsertFile(entry: CacheFileEntry): void;\n upsertFiles(entries: CacheFileEntry[]): void;\n deleteFile(id: string): void;\n clear(): void;\n getMeta(key: string): string | null;\n setMeta(key: string, value: string): void;\n getStats(): CacheStats;\n close(): void;\n}\n\n/**\n * High-performance SQLite-backed persistent cache for DriveKit metadata.\n * Uses Node 22's built-in `node:sqlite` (DatabaseSync).\n */\nexport class SqliteMetadataCache implements IMetadataCache {\n private db: any = null;\n private dbPath: string;\n private initialized = false;\n private fallbackMemory?: MemoryMetadataCache;\n\n constructor(customPath?: string) {\n if (customPath) {\n this.dbPath = customPath;\n } else {\n const dir = path.join(os.homedir(), '.drivekit');\n if (!fs.existsSync(dir)) {\n try {\n fs.mkdirSync(dir, { recursive: true });\n } catch {\n // fallback if home dir isn't writable\n }\n }\n this.dbPath = path.join(dir, 'cache.db');\n }\n }\n\n public init(): void {\n if (this.initialized) return;\n\n try {\n // Dynamic require so older environments or non-node runtimes don't fail parsing\n // @ts-ignore\n const { DatabaseSync } = require('node:sqlite');\n if (!DatabaseSync) {\n throw new Error('DatabaseSync not available');\n }\n this.db = new DatabaseSync(this.dbPath);\n\n // Initialize Schema & Indexes\n this.db.exec(`\n PRAGMA journal_mode = WAL;\n PRAGMA synchronous = NORMAL;\n\n CREATE TABLE IF NOT EXISTS files (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n mimeType TEXT NOT NULL,\n size INTEGER,\n parentId TEXT,\n path TEXT,\n md5Checksum TEXT,\n trashed INTEGER DEFAULT 0,\n modifiedTime TEXT,\n updatedAt INTEGER\n );\n\n CREATE TABLE IF NOT EXISTS meta (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL\n );\n\n CREATE INDEX IF NOT EXISTS idx_files_path ON files(path);\n CREATE INDEX IF NOT EXISTS idx_files_parent ON files(parentId);\n CREATE INDEX IF NOT EXISTS idx_files_md5 ON files(md5Checksum);\n CREATE INDEX IF NOT EXISTS idx_files_name ON files(name);\n `);\n\n this.initialized = true;\n } catch (err) {\n // If node:sqlite is not available (Node < 22.5), transparently fallback to in-memory cache\n this.fallbackMemory = new MemoryMetadataCache();\n this.fallbackMemory.init();\n this.initialized = true;\n this.db = null;\n }\n }\n\n public getById(id: string): CacheFileEntry | null {\n if (this.fallbackMemory) return this.fallbackMemory.getById(id);\n if (!this.initialized || !this.db) return null;\n const stmt = this.db.prepare('SELECT * FROM files WHERE id = ?');\n const row = stmt.get(id);\n return row ? this.mapRow(row) : null;\n }\n\n public getByPath(normalizedPath: string): CacheFileEntry | null {\n if (this.fallbackMemory) return this.fallbackMemory.getByPath(normalizedPath);\n if (!this.initialized || !this.db) return null;\n const stmt = this.db.prepare('SELECT * FROM files WHERE path = ? AND trashed = 0 LIMIT 1');\n const row = stmt.get(normalizedPath);\n return row ? this.mapRow(row) : null;\n }\n\n public getChildren(parentId: string): CacheFileEntry[] {\n if (this.fallbackMemory) return this.fallbackMemory.getChildren(parentId);\n if (!this.initialized || !this.db) return [];\n const stmt = this.db.prepare('SELECT * FROM files WHERE parentId = ? AND trashed = 0 ORDER BY name ASC');\n const rows = stmt.all(parentId);\n return rows.map((r: any) => this.mapRow(r));\n }\n\n public findByMd5(md5: string): CacheFileEntry | null {\n if (this.fallbackMemory) return this.fallbackMemory.findByMd5(md5);\n if (!this.initialized || !this.db || !md5) return null;\n const stmt = this.db.prepare('SELECT * FROM files WHERE md5Checksum = ? AND trashed = 0 LIMIT 1');\n const row = stmt.get(md5.toLowerCase());\n return row ? this.mapRow(row) : null;\n }\n\n public searchByName(query: string): CacheFileEntry[] {\n if (this.fallbackMemory) return this.fallbackMemory.searchByName(query);\n if (!this.initialized || !this.db) return [];\n const stmt = this.db.prepare('SELECT * FROM files WHERE name LIKE ? AND trashed = 0 LIMIT 50');\n const rows = stmt.all(`%${query}%`);\n return rows.map((r: any) => this.mapRow(r));\n }\n\n public upsertFile(entry: CacheFileEntry): void {\n if (this.fallbackMemory) {\n this.fallbackMemory.upsertFile(entry);\n return;\n }\n if (!this.initialized || !this.db) return;\n const stmt = this.db.prepare(`\n INSERT INTO files (id, name, mimeType, size, parentId, path, md5Checksum, trashed, modifiedTime, updatedAt)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET\n name = excluded.name,\n mimeType = excluded.mimeType,\n size = excluded.size,\n parentId = excluded.parentId,\n path = COALESCE(excluded.path, files.path),\n md5Checksum = excluded.md5Checksum,\n trashed = excluded.trashed,\n modifiedTime = excluded.modifiedTime,\n updatedAt = excluded.updatedAt\n `);\n\n stmt.run(\n entry.id,\n entry.name,\n entry.mimeType,\n entry.size ?? null,\n entry.parentId ?? null,\n entry.path ?? null,\n entry.md5Checksum ? entry.md5Checksum.toLowerCase() : null,\n entry.trashed ? 1 : 0,\n entry.modifiedTime ?? null,\n entry.updatedAt ?? Date.now()\n );\n }\n\n public upsertFiles(entries: CacheFileEntry[]): void {\n if (this.fallbackMemory) {\n this.fallbackMemory.upsertFiles(entries);\n return;\n }\n if (!this.initialized || !this.db || entries.length === 0) return;\n // Execute inside a single transaction for maximum bulk write speed\n this.db.exec('BEGIN TRANSACTION;');\n try {\n for (const entry of entries) {\n this.upsertFile(entry);\n }\n this.db.exec('COMMIT;');\n } catch (e) {\n this.db.exec('ROLLBACK;');\n throw e;\n }\n }\n\n public deleteFile(id: string): void {\n if (this.fallbackMemory) {\n this.fallbackMemory.deleteFile(id);\n return;\n }\n if (!this.initialized || !this.db) return;\n const stmt = this.db.prepare('DELETE FROM files WHERE id = ?');\n stmt.run(id);\n }\n\n public clear(): void {\n if (this.fallbackMemory) {\n this.fallbackMemory.clear();\n return;\n }\n if (!this.initialized || !this.db) return;\n this.db.exec('DELETE FROM files; DELETE FROM meta;');\n }\n\n public getMeta(key: string): string | null {\n if (this.fallbackMemory) return this.fallbackMemory.getMeta(key);\n if (!this.initialized || !this.db) return null;\n const stmt = this.db.prepare('SELECT value FROM meta WHERE key = ?');\n const row = stmt.get(key);\n return row ? (row as any).value : null;\n }\n\n public setMeta(key: string, value: string): void {\n if (this.fallbackMemory) {\n this.fallbackMemory.setMeta(key, value);\n return;\n }\n if (!this.initialized || !this.db) return;\n const stmt = this.db.prepare(`\n INSERT INTO meta (key, value) VALUES (?, ?)\n ON CONFLICT(key) DO UPDATE SET value = excluded.value\n `);\n stmt.run(key, value);\n }\n\n public getStats(): CacheStats {\n if (this.fallbackMemory) return this.fallbackMemory.getStats();\n if (!this.initialized || !this.db) {\n return {\n fileCount: 0,\n folderCount: 0,\n totalSizeBytes: 0,\n lastSyncTime: null,\n databasePath: this.dbPath,\n };\n }\n\n const fileCountRow: any = this.db.prepare(\n \"SELECT COUNT(*) as count FROM files WHERE mimeType != 'application/vnd.google-apps.folder' AND trashed = 0\"\n ).get();\n\n const folderCountRow: any = this.db.prepare(\n \"SELECT COUNT(*) as count FROM files WHERE mimeType = 'application/vnd.google-apps.folder' AND trashed = 0\"\n ).get();\n\n const totalSizeRow: any = this.db.prepare(\n 'SELECT SUM(size) as total FROM files WHERE trashed = 0'\n ).get();\n\n const lastSync = this.getMeta('last_sync_timestamp');\n\n return {\n fileCount: fileCountRow?.count || 0,\n folderCount: folderCountRow?.count || 0,\n totalSizeBytes: totalSizeRow?.total || 0,\n lastSyncTime: lastSync,\n databasePath: this.dbPath,\n };\n }\n\n public close(): void {\n if (this.fallbackMemory) {\n this.fallbackMemory.close();\n this.fallbackMemory = undefined;\n }\n if (this.db) {\n try {\n this.db.close();\n } catch {\n // ignore\n }\n this.initialized = false;\n this.db = null;\n }\n }\n\n private mapRow(row: any): CacheFileEntry {\n return {\n id: row.id,\n name: row.name,\n mimeType: row.mimeType,\n size: row.size != null ? Number(row.size) : undefined,\n parentId: row.parentId || undefined,\n path: row.path || undefined,\n md5Checksum: row.md5Checksum || undefined,\n trashed: row.trashed === 1,\n modifiedTime: row.modifiedTime || undefined,\n updatedAt: row.updatedAt != null ? Number(row.updatedAt) : undefined,\n };\n }\n}\n\n/**\n * Fallback in-memory cache if SQLite is unavailable\n */\nexport class MemoryMetadataCache implements IMetadataCache {\n private files = new Map<string, CacheFileEntry>();\n private meta = new Map<string, string>();\n\n public init(): void {}\n public getById(id: string): CacheFileEntry | null {\n return this.files.get(id) || null;\n }\n public getByPath(normalizedPath: string): CacheFileEntry | null {\n for (const f of this.files.values()) {\n if (f.path === normalizedPath && !f.trashed) return f;\n }\n return null;\n }\n public getChildren(parentId: string): CacheFileEntry[] {\n const list: CacheFileEntry[] = [];\n for (const f of this.files.values()) {\n if (f.parentId === parentId && !f.trashed) list.push(f);\n }\n return list;\n }\n public findByMd5(md5: string): CacheFileEntry | null {\n const target = md5.toLowerCase();\n for (const f of this.files.values()) {\n if (f.md5Checksum?.toLowerCase() === target && !f.trashed) return f;\n }\n return null;\n }\n public searchByName(query: string): CacheFileEntry[] {\n const q = query.toLowerCase();\n const list: CacheFileEntry[] = [];\n for (const f of this.files.values()) {\n if (f.name.toLowerCase().includes(q) && !f.trashed) list.push(f);\n }\n return list;\n }\n public upsertFile(entry: CacheFileEntry): void {\n this.files.set(entry.id, { ...entry, updatedAt: Date.now() });\n }\n public upsertFiles(entries: CacheFileEntry[]): void {\n for (const e of entries) this.upsertFile(e);\n }\n public deleteFile(id: string): void {\n this.files.delete(id);\n }\n public clear(): void {\n this.files.clear();\n this.meta.clear();\n }\n public getMeta(key: string): string | null {\n return this.meta.get(key) || null;\n }\n public setMeta(key: string, value: string): void {\n this.meta.set(key, value);\n }\n public getStats(): CacheStats {\n let fileCount = 0;\n let folderCount = 0;\n let totalSizeBytes = 0;\n for (const f of this.files.values()) {\n if (f.trashed) continue;\n if (f.mimeType === 'application/vnd.google-apps.folder') folderCount++;\n else {\n fileCount++;\n totalSizeBytes += f.size || 0;\n }\n }\n return {\n fileCount,\n folderCount,\n totalSizeBytes,\n lastSyncTime: this.meta.get('last_sync_timestamp') || null,\n databasePath: ':memory:',\n };\n }\n public close(): void {\n this.clear();\n }\n}\n\n","import type { drive_v3 } from '@googleapis/drive';\nimport type { OAuth2Client } from 'google-auth-library';\n\nexport type DriveApiFile = drive_v3.Schema$File;\nexport type DriveApiFileList = drive_v3.Schema$FileList;\nexport type DriveApiPermission = drive_v3.Schema$Permission;\n\n/**\n * Authentication configuration options for DriveKit\n */\nexport interface DriveKitAuthConfig {\n /** Path to Google Service Account JSON file */\n keyFilePath?: string;\n /** Parsed Service Account JSON object */\n credentials?: {\n client_email?: string;\n private_key?: string;\n project_id?: string;\n [key: string]: any;\n };\n /** Pre-existing OAuth2Client or access token */\n oauth2Client?: OAuth2Client;\n /** Direct bearer access token */\n accessToken?: string;\n /** OAuth2 Client Credentials for OAuth flow */\n oauth?: {\n clientId: string;\n clientSecret: string;\n redirectUri?: string;\n refreshToken?: string;\n };\n /** Scopes (defaults to full drive scope: ['https://www.googleapis.com/auth/drive']) */\n scopes?: string[];\n}\n\n/**\n * Global configuration options for DriveKit instance\n */\nexport interface DriveKitOptions {\n auth?: DriveKitAuthConfig;\n /** Root folder ID to restrict operations (defaults to 'root') */\n rootFolderId?: string;\n /** Default chunk size in bytes for resumable uploads (default: 8MB) */\n uploadChunkSize?: number;\n /** Maximum parallel operations for batch/sync (default: 4) */\n concurrency?: number;\n /** Cache folder paths to reduce API queries (default: true) */\n enablePathCache?: boolean;\n /** Cache TTL in milliseconds (default: 5 minutes) */\n pathCacheTTL?: number;\n /** Enable persistent SQLite metadata cache for 0ms path resolution across sessions (default: true) */\n enablePersistentCache?: boolean;\n /** Custom path to the SQLite cache database file (default: ~/.drivekit/cache.db) */\n cacheDatabasePath?: string;\n /** Number of retry attempts for 429/5xx errors (default: 5) */\n maxRetries?: number;\n /** Base delay for exponential backoff in ms (default: 1000) */\n retryBaseDelayMs?: number;\n}\n\n/**\n * Upload progress event payload\n */\nexport interface UploadProgress {\n /** Bytes transferred so far */\n bytesSent: number;\n /** Total bytes of the file */\n totalBytes: number;\n /** Percentage completed (0 - 100) */\n percentage: number;\n /** Current transfer speed in bytes per second */\n bytesPerSecond: number;\n /** Formatted speed (e.g. \"4.2 MB/s\") */\n speedFormatted: string;\n /** Estimated time remaining in seconds */\n estimatedTimeRemainingSeconds: number;\n /** Chunk index currently sent */\n chunkIndex: number;\n /** Total chunks */\n totalChunks: number;\n}\n\n/**\n * Download progress event payload\n */\nexport interface DownloadProgress {\n bytesRead: number;\n totalBytes?: number;\n percentage?: number;\n bytesPerSecond: number;\n speedFormatted: string;\n}\n\n/**\n * File upload parameters\n */\nexport interface UploadOptions {\n /** Local file path, Buffer, or Readable stream */\n source: string | Buffer | NodeJS.ReadableStream;\n /** Target file name on Google Drive */\n name?: string;\n /** Target parent folder ID or virtual path (e.g. '/Backups/2026') */\n parent?: string;\n /** MIME type (inferred automatically if omitted) */\n mimeType?: string;\n /** File description */\n description?: string;\n /** Custom chunk size for this specific upload */\n chunkSize?: number;\n /** Progress callback */\n onProgress?: (progress: UploadProgress) => void;\n /** Whether to overwrite file with same name in destination */\n overwrite?: boolean;\n /** Whether to enable instant upload deduplication by file MD5 hash */\n deduplicate?: boolean;\n /** Alias for target file name */\n filename?: string;\n /** Custom properties / metadata */\n properties?: Record<string, string>;\n appProperties?: Record<string, string>;\n /** Optional AbortSignal for instant operation cancellation */\n signal?: AbortSignal;\n}\n\n/**\n * File download parameters\n */\nexport interface DownloadOptions {\n /** Destination local file path (if saving to disk) */\n destination?: string;\n /** Progress callback */\n onProgress?: (progress: DownloadProgress) => void;\n /** Export MIME type for Google Workspace documents */\n exportMimeType?: string;\n /** Optional AbortSignal for instant operation cancellation */\n signal?: AbortSignal;\n}\n\n/**\n * Permission role types\n */\nexport type PermissionRole = 'owner' | 'organizer' | 'fileOrganizer' | 'writer' | 'commenter' | 'reader';\n\n/**\n * Permission grantee types\n */\nexport type PermissionType = 'user' | 'group' | 'domain' | 'anyone';\n\n/**\n * Share file options\n */\nexport interface ShareOptions {\n role?: PermissionRole;\n type?: PermissionType;\n emailAddress?: string;\n domain?: string;\n sendNotificationEmail?: boolean;\n emailMessage?: string;\n transferOwnership?: boolean;\n}\n\n/**\n * Directory sync summary\n */\nexport interface SyncResult {\n uploaded: { localPath: string; fileId: string; name: string }[];\n skipped: { localPath: string; name: string; reason: string }[];\n failed: { localPath: string; error: Error }[];\n totalBytes: number;\n durationMs: number;\n}\n\n","import readline from 'node:readline';\nimport chalk from 'chalk';\nimport type { DriveKit } from '../core/client.js';\nimport type { DriveApiFile } from '../types.js';\nimport { formatBytes } from '../utils/format.js';\n\n/**\n * Creates an OSC 8 clickable hyperlink in supported modern terminals (macOS Terminal, iTerm2, VS Code, etc.)\n */\nexport function terminalLink(text: string, url: string): string {\n // OSC 8 ; params ; url ST text OSC 8 ;; ST\n return `\\u001B]8;;${url}\\u0007${text}\\u001B]8;;\\u0007`;\n}\n\n/**\n * Renders a visually stunning, colored file table with clickable links\n */\nexport function renderFileRow(item: DriveApiFile, index?: number): string {\n const isDir = item.mimeType === 'application/vnd.google-apps.folder';\n const icon = isDir ? '📁' : getFileIcon(item.mimeType || '');\n const prefix = index !== undefined ? `${chalk.dim((index + 1).toString().padStart(2, ' ') + '.')} ` : '';\n\n let nameFormatted = isDir ? chalk.bold.blue(item.name || 'untitled') : chalk.white(item.name || 'untitled');\n if (item.webViewLink) {\n nameFormatted = terminalLink(nameFormatted, item.webViewLink);\n }\n\n const sizeFormatted = item.size\n ? chalk.dim(`[${formatBytes(parseInt(item.size, 10)).padStart(9, ' ')}]`)\n : chalk.dim(isDir ? '[ FOLDER ]' : '[ DOC ]');\n\n const idFormatted = chalk.dim(`ID: ${item.id}`);\n\n return `${prefix}${icon} ${nameFormatted.padEnd(45)} ${sizeFormatted} ${idFormatted}`;\n}\n\nexport function getFileIcon(mimeType: string): string {\n if (mimeType.includes('pdf')) return '📕';\n if (mimeType.includes('image')) return '🖼️ ';\n if (mimeType.includes('video')) return '🎬';\n if (mimeType.includes('audio')) return '🎵';\n if (mimeType.includes('zip') || mimeType.includes('compressed') || mimeType.includes('tar')) return '📦';\n if (mimeType.includes('spreadsheet') || mimeType.includes('excel')) return '📊';\n if (mimeType.includes('document') || mimeType.includes('word')) return '📝';\n if (mimeType.includes('presentation')) return '📽️ ';\n if (mimeType.includes('json') || mimeType.includes('javascript') || mimeType.includes('typescript')) return '⚙️ ';\n return '📄';\n}\n\n/**\n * Interactive Keyboard-driven Google Drive File Explorer (TUI)\n */\nexport async function runInteractiveExplorer(client: DriveKit, initialFolder = '/'): Promise<void> {\n let currentFolder = initialFolder;\n let items: DriveApiFile[] = [];\n let selectedIndex = 0;\n let history: string[] = [];\n\n const refreshItems = async () => {\n items = await client.ls(currentFolder);\n selectedIndex = Math.min(selectedIndex, Math.max(0, items.length - 1));\n };\n\n await refreshItems();\n\n if (!process.stdin.isTTY) {\n console.log(chalk.yellow('Interactive explorer requires a TTY terminal. Listing items instead:'));\n for (const item of items) {\n console.log(renderFileRow(item));\n }\n return;\n }\n\n readline.emitKeypressEvents(process.stdin);\n process.stdin.setRawMode(true);\n\n const renderScreen = () => {\n console.clear();\n console.log(chalk.bold.cyan('╔═══════════════════════════════════════════════════════════════════════════════════╗'));\n console.log(chalk.bold.cyan('║') + chalk.bold.yellow(' ⚡ DriveKit Interactive Terminal Explorer ') + chalk.bold.cyan('║'));\n console.log(chalk.bold.cyan('╠═══════════════════════════════════════════════════════════════════════════════════╣'));\n console.log(chalk.bold.cyan('║') + ` 📂 Path: ${chalk.bold.green(currentFolder.padEnd(72))} ` + chalk.bold.cyan('║'));\n console.log(chalk.bold.cyan('╚═══════════════════════════════════════════════════════════════════════════════════╝'));\n console.log(chalk.dim(' [↑/↓] Navigate • [Enter] Open Folder • [B] Back • [S] Share • [Q] Exit\\n'));\n\n if (items.length === 0) {\n console.log(chalk.dim(' (This folder is empty)\\n'));\n return;\n }\n\n const pageSize = 12;\n const startIdx = Math.max(0, Math.min(selectedIndex - Math.floor(pageSize / 2), items.length - pageSize));\n const endIdx = Math.min(items.length, startIdx + pageSize);\n\n for (let i = startIdx; i < endIdx; i++) {\n const isSelected = i === selectedIndex;\n const cursor = isSelected ? chalk.bold.cyan(' ► ') : ' ';\n const row = renderFileRow(items[i]);\n if (isSelected) {\n console.log(chalk.bgHex('#1e293b')(cursor + row));\n } else {\n console.log(cursor + row);\n }\n }\n\n console.log(chalk.dim(`\\n Item ${selectedIndex + 1} of ${items.length}`));\n };\n\n renderScreen();\n\n return new Promise((resolve) => {\n const onKeypress = async (str: string, key: any) => {\n if (key.ctrl && key.name === 'c') {\n cleanup();\n process.exit(0);\n }\n\n if (key.name === 'q' || (key.name === 'escape' && history.length === 0)) {\n cleanup();\n resolve();\n return;\n }\n\n if (key.name === 'up') {\n selectedIndex = selectedIndex > 0 ? selectedIndex - 1 : items.length - 1;\n renderScreen();\n } else if (key.name === 'down') {\n selectedIndex = selectedIndex < items.length - 1 ? selectedIndex + 1 : 0;\n renderScreen();\n } else if (key.name === 'return') {\n const item = items[selectedIndex];\n if (item && item.mimeType === 'application/vnd.google-apps.folder') {\n history.push(currentFolder);\n currentFolder = currentFolder === '/' ? `/${item.name}` : `${currentFolder}/${item.name}`;\n selectedIndex = 0;\n await refreshItems();\n renderScreen();\n } else if (item && item.webViewLink) {\n // Open link in browser\n const { exec } = await import('node:child_process');\n const openCmd = process.platform === 'darwin' ? `open \"${item.webViewLink}\"` : `xdg-open \"${item.webViewLink}\"`;\n exec(openCmd);\n renderScreen();\n }\n } else if (key.name === 'b' || key.name === 'backspace') {\n if (history.length > 0) {\n currentFolder = history.pop()!;\n selectedIndex = 0;\n await refreshItems();\n renderScreen();\n }\n } else if (str === 's' || str === 'S') {\n const item = items[selectedIndex];\n if (item && item.id) {\n process.stdin.pause();\n console.log(`\\n\\n${chalk.cyan('🔗 Getting shareable link for:')} ${chalk.bold(item.name)}...`);\n try {\n const links = await client.sharePublic(item.id);\n console.log(`Preview URL: ${chalk.underline(links.previewLink)}`);\n console.log(`Direct Download URL: ${chalk.underline(links.directDownloadLink)}`);\n console.log(chalk.dim('\\nPress any key to return to explorer...'));\n process.stdin.resume();\n process.stdin.once('data', () => {\n renderScreen();\n });\n } catch (err: any) {\n console.error(chalk.red(`Failed to share: ${err.message}`));\n setTimeout(renderScreen, 2000);\n }\n }\n }\n };\n\n const cleanup = () => {\n process.stdin.removeListener('keypress', onKeypress);\n if (process.stdin.setRawMode) {\n process.stdin.setRawMode(false);\n }\n process.stdin.pause();\n console.clear();\n console.log(chalk.green('👋 Exited DriveKit explorer.'));\n };\n\n process.stdin.on('keypress', onKeypress);\n });\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAeA,eAAsB,kBACpBA,QACA,UAA+B,CAAC,GAC2C;AAC3E,QAAM,OAAO,QAAQ,QAAQ;AAC7B,QAAM,OAAO,QAAQ,QAAQ;AAE7B,QAAMA,OAAM,KAAK;AAEjB,QAAM,SAAS,kBAAAC,QAAK,aAAa,OAAO,KAAK,QAAQ;AACnD,QAAI;AACF,YAAM,YAAY,gBAAAC,QAAI,MAAM,IAAI,OAAO,KAAK,IAAI;AAChD,YAAM,cAAc,mBAAmB,UAAU,YAAY,GAAG;AAChE,YAAM,cAAc,gBAAgB,KAAK,MAAM;AAG/C,cAAQ,IAAI,QAAQ;AAAA,QAClB,KAAK,WAAW;AACd,cAAI,UAAU,KAAK;AAAA,YACjB,KAAK;AAAA,YACL,OAAO;AAAA,YACP,iBAAiB;AAAA,UACnB,CAAC;AACD,cAAI,IAAI;AACR;AAAA,QACF;AAAA,QAEA,KAAK,YAAY;AACf,gBAAM,QAAQ,IAAI,QAAQ,OAAO,KAAK;AACtC,gBAAM,MAAM,MAAM,eAAeF,QAAO,aAAa,KAAe;AACpE,cAAI,UAAU,KAAK;AAAA,YACjB,gBAAgB;AAAA,UAClB,CAAC;AACD,cAAI,IAAI,GAAG;AACX;AAAA,QACF;AAAA,QAEA,KAAK;AAAA,QACL,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,uCAAgC,CAAC,IAAI,aAAAA,QAAM,KAAK,KAAK,IAAI,CAAC,KAAK;AAC7F,cAAI;AACF,kBAAM,QAAQ,MAAM,OAAO,YAAY,KAAK,EAAE;AAC9C,oBAAQ,IAAI,wBAAwB,aAAAA,QAAM,UAAU,MAAM,WAAW,CAAC,EAAE;AACxE,oBAAQ,IAAI,wBAAwB,aAAAA,QAAM,UAAU,MAAM,kBAAkB,CAAC,EAAE;AAC/E,oBAAQ,IAAI,aAAAA,QAAM,IAAI,0CAA0C,CAAC;AACjE,oBAAQ,MAAM,OAAO;AACrB,oBAAQ,MAAM,KAAK,QAAQ,MAAM;AAC/B,2BAAa;AAAA,YACf,CAAC;AAAA,UACH,SAAS,KAAU;AACjB,oBAAQ,MAAM,aAAAA,QAAM,IAAI,oBAAoB,IAAI,OAAO,EAAE,CAAC;AAC1D,uBAAW,cAAc,GAAI;AAAA,UAC/B;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAEA,UAAM,UAAU,MAAM;AACpB,cAAQ,MAAM,eAAe,YAAY,UAAU;AACnD,UAAI,QAAQ,MAAM,YAAY;AAC5B,gBAAQ,MAAM,WAAW,KAAK;AAAA,MAChC;AACA,cAAQ,MAAM,MAAM;AACpB,cAAQ,MAAM;AACd,cAAQ,IAAI,aAAAA,QAAM,MAAM,qCAA8B,CAAC;AAAA,IACzD;AAEA,YAAQ,MAAM,GAAG,YAAY,UAAU;AAAA,EACzC,CAAC;AACH;;;ApBpKA,eAAsB,YAAY,SAA8C;AAC9E,QAAM,WAAW,IAAI,SAAS,OAAO;AACrC,QAAM,SAAS,KAAK;AACpB,SAAO;AACT;AAGA,IAAO,gBAAQ;","names":["drive","http","url","path","import_node_http","import_node_path","import_node_fs","import_node_path","import_drive","googleAuth","fs","auth","mime","drive","path","import_node_fs","drive","fs","path","import_node_fs","import_node_path","drive","fs","path","drive","mime","drive","drive","import_node_fs","import_node_path","crypto","fs","drive","path","import_drive","googleAuth","http","drive","pathModule","import_node_path","import_node_fs","path","os","fs","fs","path","startWebDAVServer","url","chalk","readline","exec"]}
1
+ {"version":3,"sources":["../node_modules/tsup/assets/cjs_shims.js","../src/server/webdav.ts","../src/index.ts","../src/core/client.ts","../src/auth/authenticator.ts","../src/errors.ts","../src/utils/http-agent.ts","../src/core/path-resolver.ts","../src/utils/mime.ts","../src/utils/retry.ts","../src/core/resumable-uploader.ts","../src/utils/format.ts","../src/core/downloader.ts","../src/core/query-builder.ts","../src/core/concurrency-pool.ts","../src/core/watcher.ts","../src/core/storage-cleaner.ts","../src/core/smart-sync.ts","../src/auth/browser-login.ts","../src/core/resource-refs.ts","../src/core/plugins.ts","../src/core/cache.ts","../src/types.ts","../src/cli/terminal-ui.ts"],"sourcesContent":["// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () => \n typeof document === \"undefined\" \n ? new URL(`file:${__filename}`).href \n : (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT') \n ? document.currentScript.src \n : new URL(\"main.js\", document.baseURI).href;\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n","import http from 'node:http';\nimport url from 'node:url';\nimport path from 'node:path';\nimport type { DriveKit } from '../core/client.js';\nimport type { DriveApiFile } from '../types.js';\n\nexport interface WebDAVServerOptions {\n port?: number;\n host?: string;\n auth?: {\n username?: string;\n password?: string;\n };\n}\n\n/**\n * Escapes unsafe characters for valid XML output\n */\nexport function escapeXml(unsafe: string): string {\n return unsafe\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&apos;');\n}\n\n/**\n * Creates and starts a production-grade, zero-dependency WebDAV server for DriveKit.\n * Supports HTTP Basic Authentication, Streaming PUT (Zero-Buffer), Range requests, MOVE, COPY, and MKCOL.\n */\nexport async function startWebDAVServer(\n drive: DriveKit,\n options: WebDAVServerOptions = {}\n): Promise<{ server: http.Server; url: string; close: () => Promise<void> }> {\n const port = options.port || 8080;\n const host = options.host || '127.0.0.1';\n\n await drive.init();\n\n const server = http.createServer(async (req, res) => {\n try {\n // 1. Basic Authentication Verification (P0 Security)\n if (options.auth?.username && options.auth?.password) {\n const authHeader = req.headers['authorization'];\n if (!authHeader || !authHeader.startsWith('Basic ')) {\n res.writeHead(401, {\n 'WWW-Authenticate': 'Basic realm=\"DriveKit WebDAV\"',\n 'Content-Type': 'text/plain',\n });\n res.end('Authentication required');\n return;\n }\n\n const credentials = Buffer.from(authHeader.replace('Basic ', ''), 'base64').toString('utf8');\n const [user, pass] = credentials.split(':');\n if (user !== options.auth.username || pass !== options.auth.password) {\n res.writeHead(401, {\n 'WWW-Authenticate': 'Basic realm=\"DriveKit WebDAV\"',\n 'Content-Type': 'text/plain',\n });\n res.end('Invalid credentials');\n return;\n }\n }\n\n const parsedUrl = url.parse(req.url || '/', true);\n const decodedPath = decodeURIComponent(parsedUrl.pathname || '/');\n const virtualPath = decodedPath === '' ? '/' : decodedPath;\n\n // Fast-reject macOS OS noise files to keep Finder ultra fast and prevent API spam\n const baseName = path.basename(virtualPath);\n if (\n baseName.startsWith('._') ||\n baseName === '.DS_Store' ||\n baseName === '.Trashes' ||\n baseName === '.Spotlight-V100' ||\n baseName === '.fseventsd'\n ) {\n res.writeHead(404, { 'Content-Type': 'text/plain' });\n res.end('Not Found');\n return;\n }\n\n // 2. Handle WebDAV HTTP Verbs\n switch (req.method) {\n case 'OPTIONS': {\n res.writeHead(200, {\n DAV: '1, 2',\n Allow: 'OPTIONS, GET, HEAD, POST, PUT, DELETE, MKCOL, MOVE, COPY, PROPFIND',\n 'MS-Author-Via': 'DAV',\n 'Accept-Ranges': 'bytes',\n });\n res.end();\n return;\n }\n\n case 'PROPFIND': {\n const depth = req.headers['depth'] || '1';\n const xml = await handlePropfind(drive, virtualPath, depth as string);\n if (xml === null) {\n res.writeHead(404, { 'Content-Type': 'text/plain' });\n res.end('Not Found');\n return;\n }\n res.writeHead(207, {\n 'Content-Type': 'application/xml; charset=utf-8',\n });\n res.end(xml);\n return;\n }\n\n case 'GET':\n case 'HEAD': {\n if (virtualPath === '/' || virtualPath === '') {\n res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });\n res.end('<h1>DriveKit WebDAV Server Running</h1><p>Connect via Finder, File Explorer, or WebDAV client.</p>');\n return;\n }\n\n try {\n const file = await drive.getFile(virtualPath);\n if (file.mimeType === 'application/vnd.google-apps.folder') {\n res.writeHead(405, { 'Content-Type': 'text/plain' });\n res.end('Cannot GET a directory');\n return;\n }\n\n const fileSize = file.size ? parseInt(file.size, 10) : undefined;\n const rangeHeader = req.headers['range'];\n\n // Handle HTTP 206 Partial Content if Range header is present\n if (rangeHeader && rangeHeader.startsWith('bytes=') && fileSize !== undefined) {\n const parts = rangeHeader.replace('bytes=', '').split('-');\n const start = parseInt(parts[0], 10);\n const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;\n\n if (isNaN(start) || start >= fileSize || (end !== undefined && end >= fileSize)) {\n res.writeHead(416, { 'Content-Range': `bytes */${fileSize}` });\n res.end();\n return;\n }\n\n const stream = await drive.createReadStream(virtualPath, { start, end });\n const chunkLength = end - start + 1;\n\n res.writeHead(206, {\n 'Content-Type': file.mimeType || 'application/octet-stream',\n 'Content-Range': `bytes ${start}-${end}/${fileSize}`,\n 'Content-Length': chunkLength,\n 'Accept-Ranges': 'bytes',\n });\n\n if (req.method === 'HEAD') {\n res.end();\n } else {\n stream.pipe(res);\n }\n } else {\n const stream = await drive.createReadStream(virtualPath);\n res.writeHead(200, {\n 'Content-Type': file.mimeType || 'application/octet-stream',\n 'Content-Length': file.size || undefined,\n 'Accept-Ranges': 'bytes',\n });\n\n if (req.method === 'HEAD') {\n res.end();\n } else {\n stream.pipe(res);\n }\n }\n } catch (e: any) {\n res.writeHead(404, { 'Content-Type': 'text/plain' });\n res.end('File Not Found');\n }\n return;\n }\n\n case 'PUT': {\n // Zero-Buffer Streaming Upload\n const remoteDir = path.dirname(virtualPath);\n await drive.mkdirp(remoteDir);\n\n let existed = false;\n try {\n const existingFile = await drive.getFile(virtualPath);\n if (existingFile && existingFile.id) {\n existed = true;\n }\n } catch {\n existed = false;\n }\n\n try {\n const uploadStream = await drive.createWriteStream(virtualPath, {\n overwrite: true,\n });\n\n req.pipe(uploadStream);\n await uploadStream.done;\n\n res.writeHead(existed ? 204 : 201, { 'Content-Type': 'text/plain' });\n res.end(existed ? '' : 'Created');\n } catch (err: any) {\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n res.end(err.message || 'Upload failed');\n }\n return;\n }\n\n case 'MKCOL': {\n // Create directory\n try {\n await drive.mkdirp(virtualPath);\n res.writeHead(201, { 'Content-Type': 'text/plain' });\n res.end('Collection Created');\n } catch (err: any) {\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n res.end(err.message);\n }\n return;\n }\n\n case 'DELETE': {\n try {\n await drive.delete(virtualPath, true);\n res.writeHead(204);\n res.end();\n } catch (err: any) {\n res.writeHead(404, { 'Content-Type': 'text/plain' });\n res.end('Not Found');\n }\n return;\n }\n\n case 'MOVE': {\n const destination = req.headers['destination'];\n if (!destination || typeof destination !== 'string') {\n res.writeHead(400, { 'Content-Type': 'text/plain' });\n res.end('Destination header missing');\n return;\n }\n\n try {\n const file = await drive.getFile(virtualPath);\n if (!file?.id) {\n res.writeHead(404, { 'Content-Type': 'text/plain' });\n res.end('Source file not found');\n return;\n }\n const destUrl = url.parse(destination);\n const destPath = decodeURIComponent(destUrl.pathname || '');\n const newName = path.basename(destPath);\n const newParentDir = path.dirname(destPath);\n const newParentFolderId = await drive.mkdirp(newParentDir);\n\n const currentParentDir = path.dirname(virtualPath);\n if (newParentDir !== currentParentDir) {\n await drive.move(file.id, newParentFolderId);\n }\n if (newName !== path.basename(virtualPath)) {\n await drive.rename(file.id, newName);\n }\n res.writeHead(201);\n res.end('Moved');\n } catch (err: any) {\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n res.end(err.message);\n }\n return;\n }\n\n case 'COPY': {\n const destination = req.headers['destination'];\n if (!destination || typeof destination !== 'string') {\n res.writeHead(400, { 'Content-Type': 'text/plain' });\n res.end('Destination header missing');\n return;\n }\n\n try {\n const file = await drive.getFile(virtualPath);\n if (!file?.id) {\n res.writeHead(404, { 'Content-Type': 'text/plain' });\n res.end('Source file not found');\n return;\n }\n const destUrl = url.parse(destination);\n const destPath = decodeURIComponent(destUrl.pathname || '');\n const newName = path.basename(destPath);\n const newParentDir = path.dirname(destPath);\n const newParentFolderId = await drive.mkdirp(newParentDir);\n\n await drive.copy(file.id, { parent: newParentFolderId, name: newName });\n res.writeHead(201);\n res.end('Copied');\n } catch (err: any) {\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n res.end(err.message);\n }\n return;\n }\n\n default: {\n res.writeHead(501, { 'Content-Type': 'text/plain' });\n res.end('Method Not Implemented');\n }\n }\n } catch (globalErr: any) {\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n res.end(`Internal Server Error: ${globalErr.message}`);\n }\n });\n\n return new Promise((resolve) => {\n server.listen(port, host, () => {\n const serverUrl = `http://${host}:${port}`;\n resolve({\n server,\n url: serverUrl,\n close: () => new Promise<void>((resClose) => server.close(() => resClose())),\n });\n });\n });\n}\n\n/**\n * Generates RFC 4918 multistatus XML response for PROPFIND\n */\nasync function handlePropfind(drive: DriveKit, virtualPath: string, depth: string): Promise<string | null> {\n const responses: string[] = [];\n\n let isFolder = false;\n let selfItem: DriveApiFile | null = null;\n\n if (virtualPath === '/' || virtualPath === '') {\n isFolder = true;\n responses.push(renderWebDAVResponse('/', true, 0, new Date().toISOString()));\n } else {\n try {\n selfItem = await drive.getFile(virtualPath);\n isFolder = selfItem.mimeType === 'application/vnd.google-apps.folder';\n responses.push(\n renderWebDAVResponse(\n virtualPath,\n isFolder,\n selfItem.size ? parseInt(selfItem.size, 10) : 0,\n selfItem.modifiedTime || new Date().toISOString(),\n selfItem.mimeType || undefined\n )\n );\n } catch {\n return null;\n }\n }\n\n // If directory and depth != 0, include children\n if (isFolder && depth !== '0') {\n try {\n const children = await drive.ls(virtualPath);\n const seenNames = new Map<string, number>();\n\n for (const child of children) {\n let childName = child.name || 'untitled';\n if (seenNames.has(childName)) {\n const count = seenNames.get(childName)! + 1;\n seenNames.set(childName, count);\n const ext = path.extname(childName);\n const base = path.basename(childName, ext);\n childName = `${base} (${count})${ext}`;\n } else {\n seenNames.set(childName, 0);\n }\n\n const childIsFolder = child.mimeType === 'application/vnd.google-apps.folder';\n const childPath = virtualPath === '/' ? `/${childName}` : `${virtualPath}/${childName}`;\n responses.push(\n renderWebDAVResponse(\n childPath,\n childIsFolder,\n child.size ? parseInt(child.size, 10) : 0,\n child.modifiedTime || new Date().toISOString(),\n child.mimeType || undefined\n )\n );\n }\n } catch {\n // ignore\n }\n }\n\n return `<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<D:multistatus xmlns:D=\"DAV:\">\n${responses.join('\\n')}\n</D:multistatus>`;\n}\n\nfunction renderWebDAVResponse(\n href: string,\n isDir: boolean,\n size: number,\n modifiedTime: string,\n mimeType?: string\n): string {\n let cleanHref = href;\n if (isDir && !cleanHref.endsWith('/')) {\n cleanHref += '/';\n }\n const encodedHref = encodeURI(cleanHref);\n const displayName = escapeXml(path.basename(href) || 'root');\n const resourceType = isDir ? '<D:collection/>' : '';\n const dateFormatted = new Date(modifiedTime).toUTCString();\n const contentTypeTag = !isDir && mimeType ? `\\n <D:getcontenttype>${escapeXml(mimeType)}</D:getcontenttype>` : '';\n\n return ` <D:response>\n <D:href>${encodedHref}</D:href>\n <D:propstat>\n <D:prop>\n <D:displayname>${displayName}</D:displayname>\n <D:resourcetype>${resourceType}</D:resourcetype>\n <D:getcontentlength>${isDir ? '0' : size}</D:getcontentlength>\n <D:getlastmodified>${dateFormatted}</D:getlastmodified>${contentTypeTag}\n </D:prop>\n <D:status>HTTP/1.1 200 OK</D:status>\n </D:propstat>\n </D:response>`;\n}\n","import { DriveKit } from './core/client.js';\nimport type { DriveKitOptions } from './types.js';\n\n/**\n * Creates and initializes a DriveKit instance\n *\n * @example\n * ```typescript\n * import { createDrive } from 'drivekit';\n *\n * const drive = await createDrive({\n * auth: { keyFilePath: './service-account.json' }\n * });\n *\n * const file = await drive.upload({\n * source: './report.pdf',\n * parent: '/Backups/2026',\n * onProgress: (p) => console.log(`${p.percentage}% (${p.speedFormatted})`)\n * });\n * ```\n */\nexport async function createDrive(options?: DriveKitOptions): Promise<DriveKit> {\n const instance = new DriveKit(options);\n await instance.init();\n return instance;\n}\n\nexport { DriveKit };\nexport default DriveKit;\n\n// Core modules & utilities\nexport * from './types.js';\nexport * from './errors.js';\nexport * from './auth/authenticator.js';\nexport * from './core/query-builder.js';\nexport * from './core/path-resolver.js';\nexport * from './core/resumable-uploader.js';\nexport * from './core/downloader.js';\nexport * from './core/concurrency-pool.js';\nexport * from './core/watcher.js';\nexport * from './core/storage-cleaner.js';\nexport * from './core/smart-sync.js';\nexport * from './core/resource-refs.js';\nexport * from './core/plugins.js';\nexport * from './core/cache.js';\nexport * from './server/webdav.js';\nexport * from './cli/terminal-ui.js';\nexport * from './auth/browser-login.js';\nexport * from './utils/format.js';\nexport * from './utils/mime.js';\nexport * from './utils/retry.js';\nexport * from './utils/http-agent.js';\n\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { drive, drive_v3 } from '@googleapis/drive';\nimport type {\n DriveKitOptions,\n UploadOptions,\n DownloadOptions,\n ShareOptions,\n SyncResult,\n DriveApiFile,\n DriveApiPermission,\n} from '../types.js';\nimport { DriveAuthenticator } from '../auth/authenticator.js';\nimport { PathResolver } from './path-resolver.js';\nimport { ResumableUploader, DEFAULT_CHUNK_SIZE } from './resumable-uploader.js';\nimport { Downloader } from './downloader.js';\nimport { DriveQueryBuilder } from './query-builder.js';\nimport { ConcurrencyPool } from './concurrency-pool.js';\nimport { DriveWatcher, type WatcherOptions } from './watcher.js';\nimport { StorageCleaner, type DuplicateGroup } from './storage-cleaner.js';\nimport { SmartSyncEngine, type PullResult, calculateFileMd5 } from './smart-sync.js';\nimport { loginWithBrowser, type BrowserLoginOptions } from '../auth/browser-login.js';\nimport { DriveFileRef, DriveFolderRef } from './resource-refs.js';\nimport { PluginManager, type DriveKitPlugin } from './plugins.js';\nimport { DriveNotFoundError } from '../errors.js';\nimport { withRetry } from '../utils/retry.js';\nimport { formatBytes } from '../utils/format.js';\nimport { GOOGLE_WORKSPACE_MIME_TYPES } from '../utils/mime.js';\nimport { SqliteMetadataCache, type IMetadataCache, type CacheStats, type CacheFileEntry } from './cache.js';\nimport { getOptimizedHttpsAgent } from '../utils/http-agent.js';\n\nexport class DriveKit {\n private options: DriveKitOptions;\n private authenticator: DriveAuthenticator;\n private driveClient: drive_v3.Drive | null = null;\n private pathResolverInstance: PathResolver | null = null;\n private uploaderInstance: ResumableUploader | null = null;\n private downloaderInstance: Downloader | null = null;\n private metadataCacheInstance: IMetadataCache | null = null;\n private rootFolderId: string;\n private pluginManager = new PluginManager();\n\n constructor(options: DriveKitOptions = {}) {\n this.options = options;\n this.rootFolderId = options.rootFolderId || 'root';\n this.authenticator = new DriveAuthenticator(options.auth);\n }\n\n /**\n * Registers a middleware plugin into DriveKit lifecycle\n */\n use(plugin: DriveKitPlugin): this {\n this.pluginManager.use(plugin);\n return this;\n }\n\n /**\n * Unregisters a middleware plugin by name\n */\n unuse(pluginName: string): boolean {\n return this.pluginManager.unuse(pluginName);\n }\n\n /**\n * Access the underlying plugin manager instance\n */\n get plugins(): PluginManager {\n return this.pluginManager;\n }\n\n /**\n * Returns a fluent, chained reference to a specific file\n */\n file(pathOrId: string): DriveFileRef {\n return new DriveFileRef(this, pathOrId);\n }\n\n /**\n * Returns a fluent, chained reference to a specific folder\n */\n folder(pathOrId: string): DriveFolderRef {\n return new DriveFolderRef(this, pathOrId);\n }\n\n /**\n * Initializes the Google Drive API client (lazy-loaded if not called explicitly)\n */\n async init(): Promise<this> {\n if (!this.driveClient) {\n const auth = await this.authenticator.getAuthClient();\n const agent = getOptimizedHttpsAgent();\n this.driveClient = drive({ version: 'v3', auth, agent } as any) as unknown as drive_v3.Drive;\n\n if (this.options.enablePersistentCache !== false) {\n this.metadataCacheInstance = new SqliteMetadataCache(this.options.cacheDatabasePath);\n this.metadataCacheInstance.init();\n }\n\n this.pathResolverInstance = new PathResolver(this.driveClient!, this.rootFolderId, {\n enableCache: this.options.enablePathCache ?? true,\n cacheTTL: this.options.pathCacheTTL,\n metadataCache: this.metadataCacheInstance || undefined,\n });\n\n this.uploaderInstance = new ResumableUploader(\n this.driveClient!,\n this.options.uploadChunkSize || DEFAULT_CHUNK_SIZE\n );\n\n this.downloaderInstance = new Downloader(this.driveClient!);\n }\n return this;\n }\n\n /**\n * Access the underlying official `@googleapis/drive` instance for raw API calls\n */\n async getRawClient(): Promise<drive_v3.Drive> {\n await this.init();\n return this.driveClient!;\n }\n\n private async getResolver(): Promise<PathResolver> {\n await this.init();\n return this.pathResolverInstance!;\n }\n\n private async getUploader(): Promise<ResumableUploader> {\n await this.init();\n return this.uploaderInstance!;\n }\n\n private async getDownloader(): Promise<Downloader> {\n await this.init();\n return this.downloaderInstance!;\n }\n\n /**\n * Resolves a target string that could be either an ID or a virtual path (starting with '/')\n */\n private async resolveId(idOrPath: string, autoCreateDir = false): Promise<string> {\n if (idOrPath.startsWith('/')) {\n const resolver = await this.getResolver();\n const res = await resolver.resolve(idOrPath, { createIfMissing: autoCreateDir });\n return res.id;\n }\n return idOrPath;\n }\n\n // ==========================================\n // DIRECTORY & PATH OPERATIONS\n // ==========================================\n\n /**\n * Creates a folder structure recursively, similar to `mkdir -p`.\n * @param virtualPath Path like \"/Documents/Projects/2026\"\n * @returns Folder ID of the created or existing directory\n */\n async mkdirp(virtualPath: string): Promise<string> {\n const resolver = await this.getResolver();\n return await resolver.mkdirp(virtualPath);\n }\n\n /**\n * Resolves a virtual path to its Drive metadata\n */\n async resolvePath(virtualPath: string) {\n const resolver = await this.getResolver();\n return await resolver.resolve(virtualPath);\n }\n\n /**\n * Check if a file or folder exists (by ID or virtual path)\n */\n async exists(idOrPath: string): Promise<boolean> {\n try {\n if (idOrPath.startsWith('/')) {\n await this.resolvePath(idOrPath);\n return true;\n }\n const raw = await this.getRawClient();\n await raw.files.get({ fileId: idOrPath, fields: 'id, trashed' });\n return true;\n } catch (err: any) {\n if (err.status === 404 || err.code === 'NOT_FOUND') {\n return false;\n }\n throw err;\n }\n }\n\n /**\n * Lists contents of a folder (by folder ID or path) with opportunistic tree caching\n */\n async ls(folderIdOrPath = '/'): Promise<DriveApiFile[]> {\n let parentFolderId: string;\n let normalizedPath: string | null = null;\n let files: DriveApiFile[];\n\n if (folderIdOrPath === '/' || folderIdOrPath === 'root' || folderIdOrPath === this.rootFolderId) {\n parentFolderId = this.rootFolderId;\n normalizedPath = '/';\n const parentFilter = this.rootFolderId === 'root'\n ? \"'root' in parents or sharedWithMe = true\"\n : `'${this.rootFolderId}' in parents`;\n\n files = await this.query()\n .raw(parentFilter)\n .notTrashed()\n .orderBy('folder,name')\n .list();\n } else {\n if (folderIdOrPath.startsWith('/')) {\n normalizedPath = folderIdOrPath.replace(/\\/+$/, '') || '/';\n parentFolderId = await this.resolveId(normalizedPath);\n } else {\n parentFolderId = folderIdOrPath;\n }\n\n files = await this.query()\n .inFolder(parentFolderId)\n .notTrashed()\n .orderBy('folder,name')\n .list();\n }\n\n // Opportunistic Tree Caching: populate local SQLite metadata cache for 0ms subsequent queries\n if (this.metadataCacheInstance && files.length > 0) {\n const cacheEntries: CacheFileEntry[] = files\n .filter((f) => !!f.id)\n .map((f) => ({\n id: f.id!,\n name: f.name || 'untitled',\n mimeType: f.mimeType || '',\n size: f.size ? parseInt(f.size, 10) : undefined,\n parentId: parentFolderId,\n path: normalizedPath\n ? `${normalizedPath === '/' ? '' : normalizedPath}/${f.name}`\n : undefined,\n md5Checksum: f.md5Checksum || undefined,\n modifiedTime: f.modifiedTime || undefined,\n trashed: false,\n }));\n this.metadataCacheInstance.upsertFiles(cacheEntries);\n }\n\n return files;\n }\n\n // ==========================================\n // FILE OPERATIONS (UPLOAD, DOWNLOAD, GET)\n // ==========================================\n\n /**\n * Powerful upload method:\n * - Supports local paths, Buffers, or Streams\n * - Automatically uses high-speed resumable chunked upload for large files\n * - Parent can be a folder ID OR a virtual path (e.g. '/Backups/2026')\n * - Real-time progress callback: % complete, transfer speed (MB/s), ETA\n */\n async upload(options: UploadOptions): Promise<DriveApiFile> {\n const opts = await this.pluginManager.runBeforeUpload(options);\n const uploader = await this.getUploader();\n let parentId = opts.parent;\n\n if (parentId && parentId.startsWith('/')) {\n parentId = await this.mkdirp(parentId);\n }\n\n // Check overwrite if requested\n const targetName = opts.name || opts.filename || (typeof opts.source === 'string' ? path.basename(opts.source) : undefined);\n if (opts.overwrite && targetName && parentId) {\n const existing = await this.query()\n .inFolder(parentId)\n .nameEquals(targetName)\n .notTrashed()\n .first();\n\n if (existing?.id) {\n await this.delete(existing.id, true);\n }\n }\n\n // Check deduplication (Fast Instant Upload via Cloud Clone)\n if (opts.deduplicate && typeof opts.source === 'string' && fs.existsSync(opts.source)) {\n const localMd5 = await calculateFileMd5(opts.source);\n let existingId: string | undefined;\n\n if (this.metadataCacheInstance) {\n const cached = this.metadataCacheInstance.findByMd5(localMd5);\n if (cached) existingId = cached.id;\n }\n\n if (!existingId) {\n const found = await this.query()\n .md5(localMd5)\n .notTrashed()\n .first();\n if (found?.id) {\n existingId = found.id;\n }\n }\n\n if (existingId) {\n const fileName = targetName || path.basename(opts.source);\n const raw = await this.getRawClient();\n const copyRes = await withRetry(async () => {\n return await raw.files.copy({\n fileId: existingId,\n requestBody: {\n name: fileName,\n parents: parentId ? [parentId] : undefined,\n description: opts.description,\n },\n fields: 'id, name, mimeType, size, modifiedTime, md5Checksum',\n supportsAllDrives: true,\n });\n });\n\n const file = copyRes.data as DriveApiFile;\n if (this.metadataCacheInstance && file.id) {\n this.metadataCacheInstance.upsertFile({\n id: file.id,\n name: file.name || fileName,\n mimeType: file.mimeType || '',\n size: file.size ? parseInt(file.size, 10) : undefined,\n parentId,\n md5Checksum: localMd5,\n trashed: false,\n });\n }\n return await this.pluginManager.runAfterUpload(file);\n }\n }\n\n const uploaded = await uploader.upload({\n ...opts,\n name: targetName,\n parent: parentId,\n });\n\n if (this.metadataCacheInstance && uploaded.id) {\n const virtualPath =\n typeof opts.parent === 'string' && opts.parent.startsWith('/')\n ? `${opts.parent === '/' ? '' : opts.parent}/${uploaded.name || targetName || 'untitled'}`\n : undefined;\n\n this.metadataCacheInstance.upsertFile({\n id: uploaded.id,\n name: uploaded.name || targetName || 'untitled',\n mimeType: uploaded.mimeType || '',\n size: uploaded.size ? parseInt(uploaded.size, 10) : undefined,\n parentId,\n path: virtualPath,\n trashed: false,\n });\n }\n\n return await this.pluginManager.runAfterUpload(uploaded);\n }\n\n /**\n * Downloads a file from Google Drive:\n * - Automatic conversion for Google Docs, Sheets, and Slides\n * - Progress events\n * - Saves directly to file or returns Readable Stream\n * - Leverages local metadata cache to bypass redundant Google API roundtrips\n */\n async download(fileIdOrPath: string, options: DownloadOptions = {}) {\n const fileId = await this.resolveId(fileIdOrPath);\n let cachedMeta = options.metadata;\n if (!cachedMeta && this.metadataCacheInstance) {\n const cached = this.metadataCacheInstance.getById(fileId);\n if (cached && cached.name && cached.mimeType) {\n cachedMeta = { name: cached.name, mimeType: cached.mimeType, size: cached.size };\n }\n }\n\n const mergedOpts: DownloadOptions = cachedMeta ? { ...options, metadata: cachedMeta } : options;\n const processedOpts = await this.pluginManager.runBeforeDownload(fileId, mergedOpts);\n const downloader = await this.getDownloader();\n const result = await downloader.download(fileId, processedOpts);\n return await this.pluginManager.runAfterDownload(result);\n }\n\n /**\n * Gets file metadata and updates the local metadata cache\n */\n async getFile(fileIdOrPath: string): Promise<DriveApiFile> {\n const fileId = await this.resolveId(fileIdOrPath);\n const raw = await this.getRawClient();\n\n const res = await withRetry(async () => {\n return await raw.files.get({\n fileId,\n fields: 'id, name, mimeType, size, modifiedTime, createdTime, parents, trashed, webViewLink, webContentLink, description, properties, shared',\n supportsAllDrives: true,\n });\n });\n\n const file = res.data;\n if (this.metadataCacheInstance && file.id) {\n this.metadataCacheInstance.upsertFile({\n id: file.id,\n name: file.name || '',\n mimeType: file.mimeType || '',\n size: file.size ? parseInt(file.size, 10) : undefined,\n parentId: file.parents?.[0],\n path: fileIdOrPath.startsWith('/') ? fileIdOrPath : undefined,\n modifiedTime: file.modifiedTime || undefined,\n trashed: file.trashed || false,\n });\n }\n\n return file;\n }\n\n /**\n * Reads file content as UTF-8 string\n */\n async getText(fileIdOrPath: string): Promise<string> {\n const { stream } = await this.download(fileIdOrPath);\n if (!stream) throw new Error('Failed to obtain download stream');\n\n const chunks: Buffer[] = [];\n for await (const chunk of stream) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n return Buffer.concat(chunks).toString('utf-8');\n }\n\n /**\n * Reads file content and parses as JSON\n */\n async getJson<T = any>(fileIdOrPath: string): Promise<T> {\n const text = await this.getText(fileIdOrPath);\n return JSON.parse(text) as T;\n }\n\n /**\n * Deletes a file or moves it to trash\n */\n async delete(fileIdOrPath: string, permanent = false): Promise<void> {\n const fileId = await this.resolveId(fileIdOrPath);\n const raw = await this.getRawClient();\n\n if (permanent) {\n await withRetry(async () => {\n await raw.files.delete({ fileId, supportsAllDrives: true });\n });\n } else {\n await withRetry(async () => {\n await raw.files.update({\n fileId,\n requestBody: { trashed: true },\n supportsAllDrives: true,\n });\n });\n }\n\n if (this.pathResolverInstance && fileIdOrPath.startsWith('/')) {\n this.pathResolverInstance.invalidatePath(fileIdOrPath);\n }\n if (this.metadataCacheInstance) {\n this.metadataCacheInstance.deleteFile(fileId);\n }\n }\n\n /**\n * Move item to trash\n */\n async trash(fileIdOrPath: string): Promise<void> {\n return this.delete(fileIdOrPath, false);\n }\n\n /**\n * Restore item from trash\n */\n async restore(fileId: string): Promise<void> {\n const raw = await this.getRawClient();\n await withRetry(async () => {\n await raw.files.update({\n fileId,\n requestBody: { trashed: false },\n supportsAllDrives: true,\n });\n });\n }\n\n /**\n * Move file to a different folder\n */\n async move(fileIdOrPath: string, newParentIdOrPath: string): Promise<DriveApiFile> {\n const fileId = await this.resolveId(fileIdOrPath);\n const newParentId = await this.resolveId(newParentIdOrPath, true);\n const raw = await this.getRawClient();\n\n // Get current parents\n const file = await this.getFile(fileId);\n const previousParents = (file.parents || []).join(',');\n\n const res = await withRetry(async () => {\n return await raw.files.update({\n fileId,\n addParents: newParentId,\n removeParents: previousParents,\n fields: 'id, name, parents',\n supportsAllDrives: true,\n });\n });\n\n if (this.pathResolverInstance) {\n this.pathResolverInstance.clearCache();\n }\n if (this.metadataCacheInstance) {\n const cached = this.metadataCacheInstance.getById(fileId);\n if (cached) {\n this.metadataCacheInstance.upsertFile({\n ...cached,\n parentId: newParentId,\n path: undefined,\n });\n }\n }\n\n return res.data;\n }\n\n /**\n * Copies a file\n */\n async copy(fileIdOrPath: string, options: { name?: string; parent?: string } = {}): Promise<DriveApiFile> {\n const fileId = await this.resolveId(fileIdOrPath);\n const raw = await this.getRawClient();\n\n let parentId = options.parent;\n if (parentId && parentId.startsWith('/')) {\n parentId = await this.mkdirp(parentId);\n }\n\n const requestBody: drive_v3.Schema$File = {};\n if (options.name) requestBody.name = options.name;\n if (parentId) requestBody.parents = [parentId];\n\n const res = await withRetry(async () => {\n return await raw.files.copy({\n fileId,\n requestBody,\n fields: 'id, name, mimeType, webViewLink',\n supportsAllDrives: true,\n });\n });\n\n return res.data;\n }\n\n /**\n * Renames a file\n */\n async rename(fileIdOrPath: string, newName: string): Promise<DriveApiFile> {\n const fileId = await this.resolveId(fileIdOrPath);\n const raw = await this.getRawClient();\n\n const res = await withRetry(async () => {\n return await raw.files.update({\n fileId,\n requestBody: { name: newName },\n fields: 'id, name, mimeType',\n supportsAllDrives: true,\n });\n });\n\n if (this.pathResolverInstance) {\n this.pathResolverInstance.clearCache();\n }\n if (this.metadataCacheInstance) {\n const cached = this.metadataCacheInstance.getById(fileId);\n if (cached) {\n this.metadataCacheInstance.upsertFile({\n ...cached,\n name: newName,\n path: undefined,\n });\n }\n }\n\n return res.data;\n }\n\n // ==========================================\n // SHARING & PERMISSIONS\n // ==========================================\n\n /**\n * Share file with user, group, domain, or anyone\n */\n async share(fileIdOrPath: string, options: ShareOptions = {}): Promise<DriveApiPermission> {\n const fileId = await this.resolveId(fileIdOrPath);\n const raw = await this.getRawClient();\n\n const requestBody: drive_v3.Schema$Permission = {\n role: options.role || 'reader',\n type: options.type || (options.emailAddress ? 'user' : 'anyone'),\n emailAddress: options.emailAddress,\n domain: options.domain,\n };\n\n const res = await withRetry(async () => {\n return await raw.permissions.create({\n fileId,\n requestBody,\n sendNotificationEmail: options.sendNotificationEmail,\n emailMessage: options.emailMessage,\n transferOwnership: options.transferOwnership,\n supportsAllDrives: true,\n fields: 'id, role, type, emailAddress',\n });\n });\n\n return res.data;\n }\n\n /**\n * Quickly make a file public to anyone with the link\n */\n async sharePublic(fileIdOrPath: string, role: 'reader' | 'commenter' | 'writer' = 'reader') {\n const fileId = await this.resolveId(fileIdOrPath);\n await this.share(fileId, { role, type: 'anyone' });\n const file = await this.getFile(fileId);\n\n return {\n fileId,\n previewLink: file.webViewLink || `https://drive.google.com/file/d/${fileId}/view`,\n directDownloadLink: `https://drive.google.com/uc?export=download&id=${fileId}`,\n };\n }\n\n /**\n * Returns sharing links for a file\n */\n async getShareableLink(fileIdOrPath: string) {\n const fileId = await this.resolveId(fileIdOrPath);\n const file = await this.getFile(fileId);\n return {\n previewLink: file.webViewLink || `https://drive.google.com/file/d/${fileId}/view`,\n directDownloadLink: `https://drive.google.com/uc?export=download&id=${fileId}`,\n };\n }\n\n // ==========================================\n // QUERY BUILDER\n // ==========================================\n\n /**\n * Returns a fluent search query builder\n */\n query(): DriveQueryBuilder {\n if (!this.driveClient) {\n throw new Error('DriveKit not initialized. Call await drive.init() first, or use an async method.');\n }\n return new DriveQueryBuilder(this.driveClient);\n }\n\n // ==========================================\n // FOLDER SYNC & BATCH UPLOAD\n // ==========================================\n\n /**\n * Recursively uploads a local folder to a Google Drive path with high concurrency\n */\n async syncFolder(\n localDir: string,\n remotePathOrId: string,\n options: {\n concurrency?: number;\n overwrite?: boolean;\n onFileStart?: (filePath: string, relativePath: string) => void;\n onFileComplete?: (filePath: string, fileId: string) => void;\n } = {}\n ): Promise<SyncResult> {\n await this.init();\n const startTime = Date.now();\n const concurrency = options.concurrency || this.options.concurrency || 4;\n const pool = new ConcurrencyPool(concurrency);\n\n const targetFolderId = await this.resolveId(remotePathOrId, true);\n\n const result: SyncResult = {\n uploaded: [],\n skipped: [],\n failed: [],\n totalBytes: 0,\n durationMs: 0,\n };\n\n // Recursively collect all local files\n const collectFiles = async (dir: string, base: string): Promise<{ fullPath: string; relPath: string; size: number }[]> => {\n const entries = await fs.promises.readdir(dir, { withFileTypes: true });\n const files: { fullPath: string; relPath: string; size: number }[] = [];\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n const relPath = path.join(base, entry.name);\n\n if (entry.isDirectory()) {\n const sub = await collectFiles(fullPath, relPath);\n files.push(...sub);\n } else if (entry.isFile()) {\n const stat = await fs.promises.stat(fullPath);\n files.push({ fullPath, relPath, size: stat.size });\n }\n }\n return files;\n };\n\n const allFiles = await collectFiles(localDir, '');\n\n // Directory ID cache for subfolders\n const remoteDirCache = new Map<string, string>();\n remoteDirCache.set('', targetFolderId);\n\n const ensureRemoteSubdir = async (relDir: string): Promise<string> => {\n if (remoteDirCache.has(relDir)) {\n return remoteDirCache.get(relDir)!;\n }\n\n const parts = relDir.split(path.sep).filter(Boolean);\n let currentParent = targetFolderId;\n let currentRel = '';\n\n for (const part of parts) {\n currentRel = currentRel ? path.join(currentRel, part) : part;\n if (remoteDirCache.has(currentRel)) {\n currentParent = remoteDirCache.get(currentRel)!;\n continue;\n }\n\n // Query or create\n const existing = await this.query()\n .inFolder(currentParent)\n .nameEquals(part)\n .isFolder()\n .notTrashed()\n .first();\n\n if (existing?.id) {\n currentParent = existing.id;\n } else {\n const raw = await this.getRawClient();\n const created = await withRetry(async () => {\n return await raw.files.create({\n requestBody: {\n name: part,\n mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,\n parents: [currentParent],\n },\n fields: 'id',\n supportsAllDrives: true,\n });\n });\n currentParent = created.data.id!;\n }\n\n remoteDirCache.set(currentRel, currentParent);\n }\n\n return currentParent;\n };\n\n // Upload files concurrently\n await pool.map(allFiles, async (fileItem) => {\n try {\n const relDir = path.dirname(fileItem.relPath);\n const fileName = path.basename(fileItem.relPath);\n const parentFolderId = await ensureRemoteSubdir(relDir === '.' ? '' : relDir);\n\n if (options.onFileStart) {\n options.onFileStart(fileItem.fullPath, fileItem.relPath);\n }\n\n const uploadedFile = await this.upload({\n source: fileItem.fullPath,\n name: fileName,\n parent: parentFolderId,\n overwrite: options.overwrite ?? false,\n });\n\n result.uploaded.push({\n localPath: fileItem.fullPath,\n fileId: uploadedFile.id!,\n name: fileName,\n });\n result.totalBytes += fileItem.size;\n\n if (options.onFileComplete) {\n options.onFileComplete(fileItem.fullPath, uploadedFile.id!);\n }\n } catch (err: any) {\n result.failed.push({\n localPath: fileItem.fullPath,\n error: err,\n });\n }\n });\n\n result.durationMs = Date.now() - startTime;\n return result;\n }\n\n // ==========================================\n // STORAGE & QUOTA\n // ==========================================\n\n /**\n * Retrieves Google Drive storage quota usage and limits\n */\n async getStorageQuota() {\n const raw = await this.getRawClient();\n const res = await withRetry(async () => {\n return await raw.about.get({\n fields: 'storageQuota, user',\n });\n });\n\n const quota = res.data.storageQuota || {};\n const limit = quota.limit ? parseInt(quota.limit, 10) : null;\n const usage = quota.usage ? parseInt(quota.usage, 10) : 0;\n const usageInDrive = quota.usageInDrive ? parseInt(quota.usageInDrive, 10) : 0;\n const usageInDriveTrash = quota.usageInDriveTrash ? parseInt(quota.usageInDriveTrash, 10) : 0;\n const percentUsed = limit && limit > 0 ? Math.round((usage / limit) * 1000) / 10 : null;\n\n return {\n user: res.data.user,\n limit,\n usage,\n usageInDrive,\n usageInDriveTrash,\n percentUsed,\n formattedUsage: formatBytes(usage),\n formattedLimit: limit ? formatBytes(limit) : 'Unlimited',\n };\n }\n\n // ==========================================\n // CHANGE WATCHER (REAL-TIME EVENTS)\n // ==========================================\n\n /**\n * Watches Google Drive or a specific folder for real-time changes, creations, and deletions\n */\n async watch(folderIdOrPath?: string, options: Omit<WatcherOptions, 'folderId'> = {}): Promise<DriveWatcher> {\n await this.init();\n let folderId: string | undefined = undefined;\n if (folderIdOrPath && folderIdOrPath !== '/') {\n folderId = await this.resolveId(folderIdOrPath);\n }\n\n const watcher = new DriveWatcher(this.driveClient!, {\n ...options,\n folderId,\n });\n\n await watcher.start();\n return watcher;\n }\n\n // ==========================================\n // STORAGE CLEANER & DUPLICATE FINDER\n // ==========================================\n\n /**\n * Finds the largest files consuming Google Drive storage\n */\n async findLargestFiles(limit = 10) {\n await this.init();\n const cleaner = new StorageCleaner(this.driveClient!);\n return await cleaner.findLargestFiles(limit);\n }\n\n /**\n * Finds duplicate files (by MD5 hash or exact file name)\n */\n async findDuplicates(options?: { by?: 'md5' | 'name'; maxScan?: number }) {\n await this.init();\n const cleaner = new StorageCleaner(this.driveClient!);\n return await cleaner.findDuplicates(options);\n }\n\n /**\n * Empties the entire trash bin in Google Drive\n */\n async emptyTrash(): Promise<void> {\n await this.init();\n const cleaner = new StorageCleaner(this.driveClient!);\n await cleaner.emptyTrash();\n }\n\n // ==========================================\n // SMART PULL & TWO-WAY SYNC\n // ==========================================\n\n /**\n * Pulls (downloads) an entire remote Google Drive directory down to a local folder with MD5 deduplication\n */\n async pull(\n remoteFolderIdOrPath: string,\n localDestinationDir: string,\n options: {\n concurrency?: number;\n overwrite?: boolean;\n onFileStart?: (remoteName: string, relativePath: string) => void;\n onFileComplete?: (remoteName: string, localPath: string) => void;\n } = {}\n ): Promise<PullResult> {\n await this.init();\n const folderId = await this.resolveId(remoteFolderIdOrPath);\n const engine = new SmartSyncEngine(this.driveClient!);\n return await engine.pullFolder(folderId, localDestinationDir, options);\n }\n\n // ==========================================\n // STREAMS & RANGE REQUESTS\n // ==========================================\n\n /**\n * Creates a readable stream for a file, supporting partial range requests\n */\n async createReadStream(\n pathOrId: string,\n options?: { start?: number; end?: number }\n ): Promise<NodeJS.ReadableStream> {\n const fileId = await this.resolveId(pathOrId);\n const downloader = await this.getDownloader();\n return await downloader.createReadStream(fileId, options);\n }\n\n /**\n * Creates a writable stream directly into Google Drive\n */\n async createWriteStream(\n remotePath: string,\n options: Omit<UploadOptions, 'source'> = {}\n ): Promise<NodeJS.WritableStream & { done: Promise<DriveApiFile> }> {\n await this.init();\n const { PassThrough } = await import('node:stream');\n const passThrough = new PassThrough({ highWaterMark: 1024 * 1024 });\n\n let resolveDone!: (file: DriveApiFile) => void;\n let rejectDone!: (err: Error) => void;\n const donePromise = new Promise<DriveApiFile>((resolve, reject) => {\n resolveDone = resolve;\n rejectDone = reject;\n });\n\n (passThrough as any).done = donePromise;\n\n const remoteDir = path.dirname(remotePath);\n const fileName = options.name || options.filename || path.basename(remotePath);\n const targetParentId = remoteDir === '.' || remoteDir === '/' ? this.rootFolderId : await this.mkdirp(remoteDir);\n const mimeType = options.mimeType || 'application/octet-stream';\n\n const raw = this.driveClient!;\n raw.files.create({\n requestBody: {\n name: fileName,\n parents: [targetParentId],\n description: options.description,\n },\n media: {\n mimeType,\n body: passThrough,\n },\n fields: 'id, name, mimeType, size, md5Checksum',\n supportsAllDrives: true,\n }).then((res) => {\n const file = res.data as DriveApiFile;\n if (file.id && this.metadataCacheInstance) {\n this.metadataCacheInstance.upsertFile({\n id: file.id,\n name: fileName,\n mimeType,\n parentId: targetParentId,\n path: remotePath,\n trashed: false,\n });\n }\n resolveDone(file);\n }).catch((err) => {\n passThrough.destroy(err);\n rejectDone(err);\n });\n\n return passThrough as any;\n }\n\n // ==========================================\n // METADATA CACHE OPERATIONS\n // ==========================================\n\n /**\n * Synchronous getter for the active metadata cache instance\n */\n get cache(): IMetadataCache | null {\n return this.metadataCacheInstance;\n }\n\n /**\n * Returns the active persistent metadata cache instance (SQLite/Memory)\n */\n async getMetadataCache(): Promise<IMetadataCache | null> {\n await this.init();\n return this.metadataCacheInstance;\n }\n\n /**\n * Returns cache statistics (total files, folders, size, last sync)\n */\n async getCacheStats(): Promise<CacheStats | null> {\n await this.init();\n return this.metadataCacheInstance ? this.metadataCacheInstance.getStats() : null;\n }\n\n /**\n * Clears the path and metadata cache\n */\n async clearCache(): Promise<void> {\n await this.init();\n if (this.pathResolverInstance) {\n this.pathResolverInstance.clearCache();\n }\n if (this.metadataCacheInstance) {\n this.metadataCacheInstance.clear();\n }\n }\n\n /**\n * Crawls and indexes Google Drive metadata into the local SQLite database for instant 0ms lookups\n */\n async syncCache(options?: {\n onProgress?: (scanned: number) => void;\n }): Promise<CacheStats> {\n await this.init();\n if (!this.metadataCacheInstance) {\n throw new Error('Persistent cache is disabled on this DriveKit instance');\n }\n\n const client = this.driveClient!;\n let pageToken: string | undefined = undefined;\n let totalScanned = 0;\n const rawFiles: drive_v3.Schema$File[] = [];\n\n do {\n const res = await withRetry(async () => {\n return await client.files.list({\n pageSize: 1000,\n pageToken,\n fields: 'nextPageToken, files(id, name, mimeType, size, parents, md5Checksum, trashed, modifiedTime)',\n spaces: 'drive',\n supportsAllDrives: true,\n includeItemsFromAllDrives: true,\n q: 'trashed = false',\n });\n });\n\n const files = res.data.files || [];\n for (const f of files) {\n if (f.id) rawFiles.push(f);\n }\n totalScanned += files.length;\n options?.onProgress?.(totalScanned);\n\n pageToken = res.data.nextPageToken || undefined;\n } while (pageToken);\n\n // Build hierarchical paths using memoization\n const fileMap = new Map<string, drive_v3.Schema$File>();\n for (const f of rawFiles) {\n fileMap.set(f.id!, f);\n }\n\n const pathMemo = new Map<string, string>();\n const rootId = this.rootFolderId;\n\n function computePath(id: string, visited = new Set<string>()): string {\n if (pathMemo.has(id)) return pathMemo.get(id)!;\n if (visited.has(id)) return ''; // cycle detection\n visited.add(id);\n\n const f = fileMap.get(id);\n if (!f || !f.name) return '';\n\n const parentId = f.parents?.[0];\n if (!parentId || parentId === 'root' || parentId === rootId) {\n const p = `/${f.name}`;\n pathMemo.set(id, p);\n return p;\n }\n\n const parentPath = computePath(parentId, visited);\n const fullPath = parentPath ? `${parentPath}/${f.name}` : `/${f.name}`;\n pathMemo.set(id, fullPath);\n return fullPath;\n }\n\n const entries: CacheFileEntry[] = rawFiles.map((f) => ({\n id: f.id!,\n name: f.name || 'untitled',\n mimeType: f.mimeType || '',\n size: f.size ? parseInt(f.size, 10) : undefined,\n parentId: f.parents?.[0],\n path: computePath(f.id!),\n md5Checksum: f.md5Checksum || undefined,\n trashed: !!f.trashed,\n modifiedTime: f.modifiedTime || undefined,\n }));\n\n // Upsert all and prune deleted entries\n this.metadataCacheInstance.upsertFiles(entries);\n this.metadataCacheInstance.pruneMissing(rawFiles.map((f) => f.id!));\n this.metadataCacheInstance.setMeta('last_sync_timestamp', new Date().toISOString());\n\n return this.metadataCacheInstance.getStats();\n }\n\n // ==========================================\n // SHARED DRIVES & ENTERPRISE PERMISSIONS\n // ==========================================\n\n /**\n * Lists all Google Workspace Shared Drives accessible by current user or service account\n */\n async listSharedDrives(options: { pageSize?: number } = {}): Promise<{ id: string; name: string }[]> {\n await this.init();\n const raw = await this.getRawClient();\n const res = await withRetry(async () => {\n return await raw.drives.list({\n pageSize: options.pageSize || 100,\n fields: 'drives(id, name)',\n });\n });\n return (res.data.drives || []).map((d) => ({ id: d.id!, name: d.name! }));\n }\n\n /**\n * Creates a scoped DriveKit client locked to a specific Shared Drive\n */\n sharedDrive(driveId: string): DriveKit {\n return new DriveKit({\n ...this.options,\n rootFolderId: driveId,\n });\n }\n\n /**\n * Grants access to a specific email with custom role and notification\n */\n async grantAccess(\n pathOrId: string,\n options: {\n email: string;\n role?: 'reader' | 'commenter' | 'writer';\n notify?: boolean;\n message?: string;\n }\n ): Promise<DriveApiPermission> {\n const fileId = await this.resolveId(pathOrId);\n const raw = await this.getRawClient();\n const res = await withRetry(async () => {\n return await raw.permissions.create({\n fileId,\n requestBody: {\n type: 'user',\n role: options.role || 'reader',\n emailAddress: options.email,\n },\n sendNotificationEmail: options.notify ?? true,\n emailMessage: options.message,\n fields: 'id, type, role, emailAddress, displayName',\n supportsAllDrives: true,\n });\n });\n return res.data;\n }\n\n /**\n * Revokes access for a specific permission ID or email address\n */\n async revokeAccess(pathOrId: string, permissionIdOrEmail: string): Promise<void> {\n const fileId = await this.resolveId(pathOrId);\n const raw = await this.getRawClient();\n let targetId = permissionIdOrEmail;\n\n if (permissionIdOrEmail.includes('@')) {\n const listRes = await this.listPermissions(fileId);\n const found = listRes.find((p) => p.emailAddress?.toLowerCase() === permissionIdOrEmail.toLowerCase());\n if (found && found.id) {\n targetId = found.id;\n }\n }\n\n await withRetry(async () => {\n return await raw.permissions.delete({\n fileId,\n permissionId: targetId,\n supportsAllDrives: true,\n });\n });\n }\n\n /**\n * Lists all active permissions on a file or folder\n */\n async listPermissions(pathOrId: string): Promise<DriveApiPermission[]> {\n const fileId = await this.resolveId(pathOrId);\n const raw = await this.getRawClient();\n const res = await withRetry(async () => {\n return await raw.permissions.list({\n fileId,\n fields: 'permissions(id, type, role, emailAddress, displayName)',\n supportsAllDrives: true,\n });\n });\n return res.data.permissions || [];\n }\n\n /**\n * Starts an embedded WebDAV server to mount DriveKit directly in macOS Finder or Windows Explorer\n */\n async serveWebDAV(options?: { port?: number; host?: string; auth?: { username?: string; password?: string } }) {\n const { startWebDAVServer } = await import('../server/webdav.js');\n return await startWebDAVServer(this, options);\n }\n\n /**\n * Calculates local file MD5 hash for integrity and deduplication checks\n */\n static async calculateFileMd5(filePath: string): Promise<string> {\n return await calculateFileMd5(filePath);\n }\n\n /**\n * Interactive 1-click browser OAuth login flow\n */\n static async loginWithBrowser(options: BrowserLoginOptions) {\n return await loginWithBrowser(options);\n }\n}\n\n","import fs from 'node:fs';\nimport { auth as googleAuth } from '@googleapis/drive';\nimport type { DriveKitAuthConfig } from '../types.js';\nimport { DriveAuthError } from '../errors.js';\nimport { getOptimizedHttpsAgent } from '../utils/http-agent.js';\n\nexport const DEFAULT_SCOPES = [\n 'https://www.googleapis.com/auth/drive',\n];\n\n/**\n * Handles Google Drive authentication across various methods\n */\nexport class DriveAuthenticator {\n private config: DriveKitAuthConfig;\n private authClient: any = null;\n\n constructor(config: DriveKitAuthConfig = {}) {\n this.config = config;\n }\n\n /**\n * Initializes and returns an authenticated Google client\n */\n async getAuthClient(): Promise<any> {\n if (this.authClient) {\n return this.authClient;\n }\n\n try {\n const scopes = this.config.scopes || DEFAULT_SCOPES;\n\n // 1. Direct Access Token provided\n if (this.config.accessToken) {\n const oauth2Client = new googleAuth.OAuth2();\n oauth2Client.setCredentials({ access_token: this.config.accessToken });\n this.authClient = oauth2Client;\n }\n\n // 2. Existing OAuth2Client instance provided\n else if (this.config.oauth2Client) {\n this.authClient = this.config.oauth2Client;\n }\n\n // 3. OAuth with Refresh Token\n else if (this.config.oauth) {\n const { clientId, clientSecret, redirectUri = 'http://localhost:3000/oauth2callback', refreshToken } = this.config.oauth;\n const oauth2Client = new googleAuth.OAuth2(clientId, clientSecret, redirectUri);\n if (refreshToken) {\n oauth2Client.setCredentials({ refresh_token: refreshToken });\n }\n this.authClient = oauth2Client;\n }\n\n // 4. Service Account Key File or Environment\n else if (this.config.keyFilePath || process.env.GDRIVE_SERVICE_ACCOUNT_PATH || process.env.GOOGLE_APPLICATION_CREDENTIALS) {\n const keyFile = this.config.keyFilePath ||\n process.env.GDRIVE_SERVICE_ACCOUNT_PATH ||\n process.env.GOOGLE_APPLICATION_CREDENTIALS;\n\n if (keyFile && !fs.existsSync(keyFile)) {\n throw new DriveAuthError(`Service account file not found at: ${keyFile}`);\n }\n const auth = new googleAuth.GoogleAuth({\n keyFile,\n scopes,\n });\n this.authClient = auth;\n }\n\n // 5. In-Memory Service Account Credentials\n else if (this.config.credentials || process.env.GDRIVE_CREDENTIALS_JSON) {\n const creds = this.config.credentials || (process.env.GDRIVE_CREDENTIALS_JSON ? JSON.parse(process.env.GDRIVE_CREDENTIALS_JSON) : null);\n const auth = new googleAuth.GoogleAuth({\n credentials: creds,\n scopes,\n });\n this.authClient = auth;\n }\n\n // 6. Fallback to Google Application Default Credentials (ADC)\n else {\n const auth = new googleAuth.GoogleAuth({ scopes });\n this.authClient = auth;\n }\n\n // Attach high-performance Keep-Alive connection agent\n if (this.authClient?.transporter?.defaults) {\n this.authClient.transporter.defaults.agent = getOptimizedHttpsAgent();\n }\n\n return this.authClient;\n } catch (err: any) {\n if (err instanceof DriveAuthError) throw err;\n throw new DriveAuthError(`Failed to authenticate with Google Drive: ${err.message}`, err);\n }\n }\n\n /**\n * Helper to generate OAuth2 Consent URL for user authorization\n */\n static generateAuthUrl(options: {\n clientId: string;\n clientSecret: string;\n redirectUri?: string;\n scopes?: string[];\n }): string {\n const oauth2Client = new googleAuth.OAuth2(\n options.clientId,\n options.clientSecret,\n options.redirectUri || 'urn:ietf:wg:oauth:2.0:oob'\n );\n\n return oauth2Client.generateAuthUrl({\n access_type: 'offline',\n prompt: 'consent',\n scope: options.scopes || DEFAULT_SCOPES,\n });\n }\n\n /**\n * Helper to exchange authorization code for tokens\n */\n static async exchangeCodeForTokens(options: {\n clientId: string;\n clientSecret: string;\n code: string;\n redirectUri?: string;\n }): Promise<{ access_token?: string | null; refresh_token?: string | null; expiry_date?: number | null }> {\n const oauth2Client = new googleAuth.OAuth2(\n options.clientId,\n options.clientSecret,\n options.redirectUri || 'urn:ietf:wg:oauth:2.0:oob'\n );\n\n const { tokens } = await oauth2Client.getToken(options.code);\n return tokens;\n }\n}\n","/**\n * Base DriveKit Error\n */\nexport class DriveKitError extends Error {\n public readonly code: string;\n public readonly originalError?: unknown;\n\n constructor(message: string, code = 'DRIVEKIT_ERROR', originalError?: unknown) {\n super(message);\n this.name = 'DriveKitError';\n this.code = code;\n this.originalError = originalError;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Authentication Error\n */\nexport class DriveAuthError extends DriveKitError {\n constructor(message: string, originalError?: unknown) {\n super(message, 'AUTH_ERROR', originalError);\n this.name = 'DriveAuthError';\n }\n}\n\n/**\n * Resource Not Found Error\n */\nexport class DriveNotFoundError extends DriveKitError {\n public readonly resourceIdOrPath: string;\n\n constructor(resourceIdOrPath: string, message?: string) {\n super(message || `Resource not found: \"${resourceIdOrPath}\"`, 'NOT_FOUND');\n this.name = 'DriveNotFoundError';\n this.resourceIdOrPath = resourceIdOrPath;\n }\n}\n\n/**\n * Rate limit / Quota exceeded Error\n */\nexport class DriveRateLimitError extends DriveKitError {\n public readonly retryAfterSeconds?: number;\n\n constructor(message: string, retryAfterSeconds?: number, originalError?: unknown) {\n super(message, 'RATE_LIMIT_EXCEEDED', originalError);\n this.name = 'DriveRateLimitError';\n this.retryAfterSeconds = retryAfterSeconds;\n }\n}\n\n/**\n * Upload Error (chunk or resumable session failure)\n */\nexport class DriveUploadError extends DriveKitError {\n public readonly bytesUploaded?: number;\n public readonly totalBytes?: number;\n\n constructor(message: string, bytesUploaded?: number, totalBytes?: number, originalError?: unknown) {\n super(message, 'UPLOAD_ERROR', originalError);\n this.name = 'DriveUploadError';\n this.bytesUploaded = bytesUploaded;\n this.totalBytes = totalBytes;\n }\n}\n\n","import https from 'node:https';\nimport http from 'node:http';\n\nlet sharedHttpsAgent: https.Agent | null = null;\nlet sharedHttpAgent: http.Agent | null = null;\n\nexport interface HttpAgentOptions {\n keepAlive?: boolean;\n maxSockets?: number;\n maxFreeSockets?: number;\n keepAliveMsecs?: number;\n timeout?: number;\n}\n\n/**\n * Returns a high-performance HTTPS Agent with persistent connection pooling\n * and Keep-Alive enabled to eliminate TCP/TLS handshake latency on Google APIs.\n */\nexport function getOptimizedHttpsAgent(options?: HttpAgentOptions): https.Agent {\n if (!sharedHttpsAgent) {\n sharedHttpsAgent = new https.Agent({\n keepAlive: options?.keepAlive ?? true,\n maxSockets: options?.maxSockets ?? 64,\n maxFreeSockets: options?.maxFreeSockets ?? 32,\n keepAliveMsecs: options?.keepAliveMsecs ?? 60000,\n timeout: options?.timeout ?? 30000,\n noDelay: true,\n });\n }\n return sharedHttpsAgent;\n}\n\n/**\n * Returns a high-performance HTTP Agent with connection pooling.\n */\nexport function getOptimizedHttpAgent(options?: HttpAgentOptions): http.Agent {\n if (!sharedHttpAgent) {\n sharedHttpAgent = new http.Agent({\n keepAlive: options?.keepAlive ?? true,\n maxSockets: options?.maxSockets ?? 64,\n maxFreeSockets: options?.maxFreeSockets ?? 32,\n keepAliveMsecs: options?.keepAliveMsecs ?? 60000,\n timeout: options?.timeout ?? 30000,\n noDelay: true,\n });\n }\n return sharedHttpAgent;\n}\n","import type { drive_v3 } from '@googleapis/drive';\nimport { GOOGLE_WORKSPACE_MIME_TYPES } from '../utils/mime.js';\nimport { DriveNotFoundError } from '../errors.js';\nimport { withRetry } from '../utils/retry.js';\nimport type { IMetadataCache } from './cache.js';\n\ninterface CacheEntry {\n id: string;\n name: string;\n mimeType: string;\n expiresAt: number;\n}\n\n/**\n * Resolves virtual hierarchical paths like \"/Projects/2026/file.pdf\" to Google Drive File/Folder IDs.\n */\nexport class PathResolver {\n private drive: drive_v3.Drive;\n private rootFolderId: string;\n private cache = new Map<string, CacheEntry>();\n private inFlightResolves = new Map<string, Promise<{ id: string; name: string; isFolder: boolean; mimeType: string }>>();\n private cacheTTL: number;\n private enableCache: boolean;\n private metadataCache?: IMetadataCache;\n\n constructor(\n drive: drive_v3.Drive,\n rootFolderId = 'root',\n options?: { enableCache?: boolean; cacheTTL?: number; metadataCache?: IMetadataCache }\n ) {\n this.drive = drive;\n this.rootFolderId = rootFolderId;\n this.enableCache = options?.enableCache ?? true;\n this.cacheTTL = options?.cacheTTL ?? 5 * 60 * 1000; // 5 minutes default\n this.metadataCache = options?.metadataCache;\n }\n\n /**\n * Normalizes a virtual path (e.g. \"///Backups//2026/\" -> \"/Backups/2026\")\n */\n public normalizePath(rawPath: string): string {\n if (!rawPath || rawPath.trim() === '' || rawPath === '/') {\n return '/';\n }\n const parts = rawPath\n .split('/')\n .map((p) => p.trim())\n .filter(Boolean);\n return `/${parts.join('/')}`;\n }\n\n /**\n * Gets cache key for a path\n */\n private getCacheKey(path: string): string {\n return `${this.rootFolderId}:${this.normalizePath(path)}`;\n }\n\n /**\n * Clears the path cache\n */\n public clearCache(): void {\n this.cache.clear();\n if (this.metadataCache) {\n this.metadataCache.clear();\n }\n }\n\n /**\n * Invalidate a single path from cache\n */\n public invalidatePath(path: string): void {\n const norm = this.normalizePath(path);\n const key = this.getCacheKey(norm);\n this.cache.delete(key);\n if (this.metadataCache) {\n const item = this.metadataCache.getByPath(norm);\n if (item) {\n this.metadataCache.deleteFile(item.id);\n }\n }\n }\n\n /**\n * Resolves a path to a Google Drive item (file or folder).\n * If createIfMissing is true, any missing intermediate directories will be automatically created (like mkdir -p).\n * Incorporates in-flight request coalescing to deduplicate concurrent resolutions of identical paths.\n */\n async resolve(\n virtualPath: string,\n options: { createIfMissing?: boolean } = {}\n ): Promise<{ id: string; name: string; isFolder: boolean; mimeType: string }> {\n const norm = this.normalizePath(virtualPath);\n\n if (norm === '/') {\n return {\n id: this.rootFolderId,\n name: 'root',\n isFolder: true,\n mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,\n };\n }\n\n if (this.metadataCache) {\n const persistentCached = this.metadataCache.getByPath(norm);\n if (persistentCached) {\n return {\n id: persistentCached.id,\n name: persistentCached.name,\n isFolder: persistentCached.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,\n mimeType: persistentCached.mimeType,\n };\n }\n }\n\n if (this.enableCache) {\n const cached = this.cache.get(this.getCacheKey(norm));\n if (cached && cached.expiresAt > Date.now()) {\n return {\n id: cached.id,\n name: cached.name,\n isFolder: cached.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,\n mimeType: cached.mimeType,\n };\n }\n }\n\n // Coalesce in-flight requests for the exact same path\n const flightKey = `${this.rootFolderId}:${norm}:${options.createIfMissing ? 'create' : 'read'}`;\n const inFlight = this.inFlightResolves.get(flightKey);\n if (inFlight) {\n return await inFlight;\n }\n\n const task = this.doResolve(virtualPath, norm, options);\n this.inFlightResolves.set(flightKey, task);\n try {\n return await task;\n } finally {\n this.inFlightResolves.delete(flightKey);\n }\n }\n\n private async doResolve(\n virtualPath: string,\n norm: string,\n options: { createIfMissing?: boolean }\n ): Promise<{ id: string; name: string; isFolder: boolean; mimeType: string }> {\n const segments = norm.split('/').filter(Boolean);\n let currentParentId = this.rootFolderId;\n let currentPath = '';\n\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n const isLast = i === segments.length - 1;\n currentPath += `/${segment}`;\n\n // Check persistent & in-memory cache for intermediate path\n if (this.metadataCache) {\n const pCached = this.metadataCache.getByPath(currentPath);\n if (pCached) {\n currentParentId = pCached.id;\n if (isLast) {\n return {\n id: pCached.id,\n name: pCached.name,\n isFolder: pCached.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,\n mimeType: pCached.mimeType,\n };\n }\n continue;\n }\n }\n\n if (this.enableCache) {\n const cached = this.cache.get(this.getCacheKey(currentPath));\n if (cached && cached.expiresAt > Date.now()) {\n currentParentId = cached.id;\n if (isLast) {\n return {\n id: cached.id,\n name: cached.name,\n isFolder: cached.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,\n mimeType: cached.mimeType,\n };\n }\n continue;\n }\n }\n\n // Query Google Drive for this segment under currentParentId\n const escapedName = segment.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\");\n const q = `'${currentParentId}' in parents and name = '${escapedName}' and trashed = false`;\n\n const response = await withRetry(async () => {\n return await this.drive.files.list({\n q,\n fields: 'files(id, name, mimeType, parents)',\n pageSize: 1,\n spaces: 'drive',\n supportsAllDrives: true,\n includeItemsFromAllDrives: true,\n });\n });\n\n let file = response.data.files?.[0];\n\n // If not found and at root level, check shared folders (e.g. shared with service account)\n if (!file && currentParentId === this.rootFolderId) {\n const sharedQ = `name = '${escapedName}' and sharedWithMe = true and trashed = false`;\n const sharedResponse = await withRetry(async () => {\n return await this.drive.files.list({\n q: sharedQ,\n fields: 'files(id, name, mimeType, parents)',\n pageSize: 1,\n spaces: 'drive',\n supportsAllDrives: true,\n includeItemsFromAllDrives: true,\n });\n });\n file = sharedResponse.data.files?.[0];\n }\n\n if (file && file.id) {\n const segmentParentId = currentParentId;\n currentParentId = file.id;\n\n if (this.metadataCache) {\n this.metadataCache.upsertFile({\n id: file.id,\n name: file.name || segment,\n mimeType: file.mimeType || '',\n parentId: segmentParentId,\n path: currentPath,\n trashed: false,\n });\n }\n\n if (this.enableCache) {\n this.cache.set(this.getCacheKey(currentPath), {\n id: file.id,\n name: file.name || segment,\n mimeType: file.mimeType || '',\n expiresAt: Date.now() + this.cacheTTL,\n });\n }\n\n if (isLast) {\n return {\n id: file.id,\n name: file.name || segment,\n isFolder: file.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,\n mimeType: file.mimeType || '',\n };\n }\n } else {\n // Not found\n if (options.createIfMissing) {\n // Create directory\n const createRes = await withRetry(async () => {\n return await this.drive.files.create({\n requestBody: {\n name: segment,\n mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,\n parents: [currentParentId],\n },\n fields: 'id, name, mimeType',\n supportsAllDrives: true,\n });\n });\n\n const newFolder = createRes.data;\n if (!newFolder.id) {\n throw new Error(`Failed to create folder \"${segment}\" under parent \"${currentParentId}\"`);\n }\n\n const segmentParentId = currentParentId;\n currentParentId = newFolder.id;\n\n if (this.metadataCache) {\n this.metadataCache.upsertFile({\n id: newFolder.id,\n name: segment,\n mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,\n parentId: segmentParentId,\n path: currentPath,\n trashed: false,\n });\n }\n\n if (this.enableCache) {\n this.cache.set(this.getCacheKey(currentPath), {\n id: newFolder.id,\n name: segment,\n mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,\n expiresAt: Date.now() + this.cacheTTL,\n });\n }\n\n if (isLast) {\n return {\n id: newFolder.id,\n name: segment,\n isFolder: true,\n mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,\n };\n }\n } else {\n throw new DriveNotFoundError(\n virtualPath,\n `Path segment \"${segment}\" not found in path \"${virtualPath}\" under folder ID \"${currentParentId}\"`\n );\n }\n }\n }\n\n throw new DriveNotFoundError(virtualPath);\n }\n\n /**\n * Ensures that a directory structure exists (like mkdir -p).\n */\n async mkdirp(virtualPath: string): Promise<string> {\n const res = await this.resolve(virtualPath, { createIfMissing: true });\n return res.id;\n }\n}\n\n","import path from 'node:path';\nimport mime from 'mime-types';\n\n/**\n * Standard Google Workspace MIME types\n */\nexport const GOOGLE_WORKSPACE_MIME_TYPES = {\n DOCUMENT: 'application/vnd.google-apps.document',\n SPREADSHEET: 'application/vnd.google-apps.spreadsheet',\n PRESENTATION: 'application/vnd.google-apps.presentation',\n DRAWING: 'application/vnd.google-apps.drawing',\n FORM: 'application/vnd.google-apps.form',\n SCRIPT: 'application/vnd.google-apps.script',\n FOLDER: 'application/vnd.google-apps.folder',\n SHORTCUT: 'application/vnd.google-apps.shortcut',\n} as const;\n\n/**\n * Default export MIME types for Google Docs, Sheets, Slides\n */\nexport const DEFAULT_EXPORT_MIMES: Record<string, { mimeType: string; extension: string }> = {\n [GOOGLE_WORKSPACE_MIME_TYPES.DOCUMENT]: {\n mimeType: 'application/pdf',\n extension: '.pdf',\n },\n [GOOGLE_WORKSPACE_MIME_TYPES.SPREADSHEET]: {\n mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n extension: '.xlsx',\n },\n [GOOGLE_WORKSPACE_MIME_TYPES.PRESENTATION]: {\n mimeType: 'application/pdf',\n extension: '.pdf',\n },\n [GOOGLE_WORKSPACE_MIME_TYPES.DRAWING]: {\n mimeType: 'image/png',\n extension: '.png',\n },\n};\n\n/**\n * Detects MIME type from file path or fallback to octet-stream\n */\nexport function lookupMimeType(filePath: string): string {\n const detected = mime.lookup(filePath);\n return detected || 'application/octet-stream';\n}\n\n/**\n * Returns extension for a given MIME type\n */\nexport function getExtensionForMime(mimeType: string): string {\n const ext = mime.extension(mimeType);\n return ext ? `.${ext}` : '';\n}\n\n/**\n * Checks if a MIME type is a native Google Workspace format\n */\nexport function isGoogleWorkspaceDoc(mimeType?: string | null): boolean {\n if (!mimeType) return false;\n return mimeType.startsWith('application/vnd.google-apps.') &&\n mimeType !== GOOGLE_WORKSPACE_MIME_TYPES.FOLDER &&\n mimeType !== GOOGLE_WORKSPACE_MIME_TYPES.SHORTCUT;\n}\n\n","import { DriveRateLimitError } from '../errors.js';\n\nexport interface RetryOptions {\n maxRetries?: number;\n baseDelayMs?: number;\n maxDelayMs?: number;\n shouldRetry?: (error: any) => boolean;\n}\n\nconst DEFAULT_RETRYABLE_STATUSES = new Set([408, 429, 500, 502, 503, 504]);\n\n/**\n * Checks if an error returned by Google Drive is retryable\n */\nexport function isRetryableError(error: any): boolean {\n if (!error) return false;\n\n const status = error.status || error.statusCode || error.response?.status;\n if (status && DEFAULT_RETRYABLE_STATUSES.has(status)) {\n return true;\n }\n\n // Check error message or Google error reasons\n const message = (error.message || '').toLowerCase();\n if (\n message.includes('rate limit') ||\n message.includes('quota') ||\n message.includes('userate') ||\n message.includes('backend error') ||\n message.includes('socket hang up') ||\n message.includes('econnreset') ||\n message.includes('etimedout')\n ) {\n return true;\n }\n\n const errors = error.errors || error.response?.data?.error?.errors;\n if (Array.isArray(errors)) {\n for (const e of errors) {\n if (e.reason === 'rateLimitExceeded' || e.reason === 'userRateLimitExceeded' || e.reason === 'backendError') {\n return true;\n }\n }\n }\n\n return false;\n}\n\n/**\n * Executes an async operation with exponential backoff and full jitter\n */\nexport async function withRetry<T>(\n fn: () => Promise<T>,\n options: RetryOptions = {}\n): Promise<T> {\n const maxRetries = options.maxRetries ?? 5;\n const baseDelayMs = options.baseDelayMs ?? 1000;\n const maxDelayMs = options.maxDelayMs ?? 32000;\n const shouldRetry = options.shouldRetry ?? isRetryableError;\n\n let attempt = 0;\n\n while (true) {\n try {\n return await fn();\n } catch (error: any) {\n attempt++;\n if (attempt > maxRetries || !shouldRetry(error)) {\n if (error?.status === 429 || error?.response?.status === 429) {\n throw new DriveRateLimitError(\n `Drive API rate limit exceeded after ${attempt} attempts.`,\n undefined,\n error\n );\n }\n throw error;\n }\n\n // Calculate exponential backoff with full jitter: delay = random_between(0, min(maxDelay, base * 2^attempt))\n const calculatedDelay = Math.min(maxDelayMs, baseDelayMs * Math.pow(2, attempt));\n const jitterDelay = Math.floor(Math.random() * calculatedDelay);\n\n await new Promise((resolve) => setTimeout(resolve, jitterDelay));\n }\n }\n}\n\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { Transform } from 'node:stream';\nimport type { drive_v3 } from '@googleapis/drive';\nimport type { UploadOptions, UploadProgress, DriveApiFile } from '../types.js';\nimport { DriveUploadError } from '../errors.js';\nimport { formatSpeed } from '../utils/format.js';\nimport { lookupMimeType } from '../utils/mime.js';\nimport { withRetry } from '../utils/retry.js';\nimport { getOptimizedHttpsAgent } from '../utils/http-agent.js';\n\n/** Minimum Google Drive chunk granularity: 256 KiB */\nexport const MIN_CHUNK_SIZE = 256 * 1024;\n/** Default chunk size: 8 MiB (must be multiple of 256 KiB) */\nexport const DEFAULT_CHUNK_SIZE = 8 * 1024 * 1024;\n/** Files smaller than this can use direct single-request multipart upload */\nexport const MULTIPART_THRESHOLD = 5 * 1024 * 1024;\n\nexport class ResumableUploader {\n private drive: drive_v3.Drive;\n private defaultChunkSize: number;\n\n constructor(drive: drive_v3.Drive, defaultChunkSize = DEFAULT_CHUNK_SIZE) {\n this.drive = drive;\n // Ensure chunk size is multiple of 256 KiB\n this.defaultChunkSize = Math.max(\n MIN_CHUNK_SIZE,\n Math.floor(defaultChunkSize / MIN_CHUNK_SIZE) * MIN_CHUNK_SIZE\n );\n }\n\n /**\n * Uploads a file with automatic selection of direct multipart (small files)\n * or resumable chunked upload with progress events (large files).\n */\n async upload(options: UploadOptions): Promise<DriveApiFile> {\n if (typeof options.source === 'string') {\n return await this.uploadFromPath(options.source, options);\n } else if (Buffer.isBuffer(options.source)) {\n return await this.uploadFromBuffer(options.source, options);\n } else {\n // Readable Stream: standard drive.files.create with stream\n return await this.uploadFromStream(options.source, options);\n }\n }\n\n /**\n * Upload from local file path with memory-efficient chunked streaming\n */\n private async uploadFromPath(filePath: string, options: UploadOptions): Promise<DriveApiFile> {\n if (!fs.existsSync(filePath)) {\n throw new Error(`File does not exist at path: \"${filePath}\"`);\n }\n\n const stat = await fs.promises.stat(filePath);\n const totalBytes = stat.size;\n const fileName = options.name || path.basename(filePath);\n const mimeType = options.mimeType || lookupMimeType(filePath);\n\n // Fast path: files <= MULTIPART_THRESHOLD (5 MB) use single-roundtrip direct multipart upload\n if (totalBytes <= MULTIPART_THRESHOLD) {\n const readStream = fs.createReadStream(filePath, { highWaterMark: 1024 * 1024 });\n const stream = options.onProgress\n ? this.wrapStreamWithProgress(readStream, totalBytes, options.onProgress)\n : readStream;\n return await this.directUpload(stream, {\n ...options,\n name: fileName,\n mimeType,\n });\n }\n\n return await this.chunkedUpload({\n filePath,\n totalBytes,\n fileName,\n mimeType,\n options,\n });\n }\n\n /**\n * Upload from in-memory Buffer\n */\n private async uploadFromBuffer(buffer: Buffer, options: UploadOptions): Promise<DriveApiFile> {\n const totalBytes = buffer.length;\n const fileName = options.name || 'untitled';\n const mimeType = options.mimeType || 'application/octet-stream';\n\n // Fast path: buffers <= MULTIPART_THRESHOLD (5 MB) use single-roundtrip direct multipart upload\n if (totalBytes <= MULTIPART_THRESHOLD) {\n const { Readable } = await import('node:stream');\n const baseStream = Readable.from(totalBytes === 0 ? [] : [buffer]);\n const stream = options.onProgress\n ? this.wrapStreamWithProgress(baseStream, totalBytes, options.onProgress)\n : baseStream;\n return await this.directUpload(stream, {\n ...options,\n name: fileName,\n mimeType,\n });\n }\n\n return await this.chunkedUploadBuffer({\n buffer,\n totalBytes,\n fileName,\n mimeType,\n options,\n });\n }\n\n /**\n * Upload from generic Readable Stream\n */\n private async uploadFromStream(stream: NodeJS.ReadableStream, options: UploadOptions): Promise<DriveApiFile> {\n const fileName = options.name || 'untitled';\n const mimeType = options.mimeType || 'application/octet-stream';\n\n return await this.directUpload(stream, {\n ...options,\n name: fileName,\n mimeType,\n });\n }\n\n /**\n * Calculates optimal chunk size based on file size for maximum throughput.\n */\n private computeAdaptiveChunkSize(totalBytes: number, explicitChunkSize?: number): number {\n if (explicitChunkSize) {\n return Math.max(MIN_CHUNK_SIZE, Math.floor(explicitChunkSize / MIN_CHUNK_SIZE) * MIN_CHUNK_SIZE);\n }\n if (totalBytes > 128 * 1024 * 1024) {\n return 32 * 1024 * 1024; // 32 MiB chunks for files > 128MB\n }\n if (totalBytes > 32 * 1024 * 1024) {\n return 16 * 1024 * 1024; // 16 MiB chunks for files > 32MB\n }\n return this.defaultChunkSize; // 8 MiB default\n }\n\n /**\n * Attaches real-time progress monitoring to direct stream uploads.\n */\n private wrapStreamWithProgress(\n stream: NodeJS.ReadableStream,\n totalBytes: number,\n onProgress: (progress: UploadProgress) => void\n ): NodeJS.ReadableStream {\n let bytesSent = 0;\n const startTime = Date.now();\n const progressTransform = new Transform({\n transform(chunk, _encoding, callback) {\n bytesSent += chunk.length;\n const elapsedSecs = (Date.now() - startTime) / 1000;\n const bytesPerSecond = elapsedSecs > 0 ? Math.round(bytesSent / elapsedSecs) : 0;\n const remainingBytes = Math.max(0, totalBytes - bytesSent);\n const estimatedTimeRemainingSeconds = bytesPerSecond > 0 ? Math.round(remainingBytes / bytesPerSecond) : 0;\n const percentage = totalBytes > 0 ? Math.min(100, Math.round((bytesSent / totalBytes) * 1000) / 10) : 100;\n\n onProgress({\n bytesSent,\n totalBytes,\n percentage,\n bytesPerSecond,\n speedFormatted: formatSpeed(bytesPerSecond),\n estimatedTimeRemainingSeconds,\n chunkIndex: 1,\n totalChunks: 1,\n });\n\n callback(null, chunk);\n },\n });\n\n return stream.pipe(progressTransform);\n }\n\n /**\n * Fast direct upload using googleapis multipart\n */\n private async directUpload(stream: NodeJS.ReadableStream, options: UploadOptions): Promise<DriveApiFile> {\n const requestBody: drive_v3.Schema$File = {\n name: options.name,\n mimeType: options.mimeType,\n description: options.description,\n properties: options.properties,\n appProperties: options.appProperties,\n };\n\n if (options.parent) {\n requestBody.parents = [options.parent];\n }\n\n const res = await withRetry(async () => {\n return await this.drive.files.create({\n requestBody,\n media: {\n mimeType: options.mimeType,\n body: stream,\n },\n fields: 'id, name, mimeType, size, webViewLink, webContentLink, createdTime, modifiedTime',\n supportsAllDrives: true,\n });\n });\n\n return res.data;\n }\n\n /**\n * Chunked resumable upload for local files with low memory footprint\n */\n private async chunkedUpload(params: {\n filePath: string;\n totalBytes: number;\n fileName: string;\n mimeType: string;\n options: UploadOptions;\n }): Promise<DriveApiFile> {\n const { filePath, totalBytes, fileName, mimeType, options } = params;\n const chunkSize = this.computeAdaptiveChunkSize(totalBytes, options.chunkSize);\n\n // 1. Initiate Resumable Upload Session\n const sessionUrl = await this.initiateResumableSession({\n fileName,\n mimeType,\n totalBytes,\n parent: options.parent,\n description: options.description,\n properties: options.properties,\n appProperties: options.appProperties,\n });\n\n // 2. Upload Chunks\n const fd = await fs.promises.open(filePath, 'r');\n let bytesSent = 0;\n const startTime = Date.now();\n const totalChunks = Math.ceil(totalBytes / chunkSize) || 1;\n let chunkIndex = 0;\n\n try {\n while (bytesSent < totalBytes) {\n if (options.signal?.aborted) {\n throw new Error('Upload aborted by user signal');\n }\n chunkIndex++;\n const currentChunkSize = Math.min(chunkSize, totalBytes - bytesSent);\n const buffer = Buffer.alloc(currentChunkSize);\n await fd.read(buffer, 0, currentChunkSize, bytesSent);\n\n const rangeStart = bytesSent;\n const rangeEnd = bytesSent + currentChunkSize - 1;\n\n const chunkResult = await this.uploadChunkWithRetry({\n sessionUrl,\n buffer,\n rangeStart,\n rangeEnd,\n totalBytes,\n });\n\n bytesSent += currentChunkSize;\n\n // Progress Calculation\n if (options.onProgress) {\n const elapsedSecs = (Date.now() - startTime) / 1000;\n const bytesPerSecond = elapsedSecs > 0 ? Math.round(bytesSent / elapsedSecs) : 0;\n const remainingBytes = totalBytes - bytesSent;\n const estimatedTimeRemainingSeconds = bytesPerSecond > 0 ? Math.round(remainingBytes / bytesPerSecond) : 0;\n const percentage = totalBytes > 0 ? Math.min(100, Math.round((bytesSent / totalBytes) * 1000) / 10) : 100;\n\n options.onProgress({\n bytesSent,\n totalBytes,\n percentage,\n bytesPerSecond,\n speedFormatted: formatSpeed(bytesPerSecond),\n estimatedTimeRemainingSeconds,\n chunkIndex,\n totalChunks,\n });\n }\n\n if (chunkResult.isComplete && chunkResult.file) {\n return chunkResult.file;\n }\n }\n } finally {\n await fd.close();\n }\n\n throw new DriveUploadError('Resumable upload loop ended without completion response', bytesSent, totalBytes);\n }\n\n /**\n * Chunked resumable upload for memory buffers\n */\n private async chunkedUploadBuffer(params: {\n buffer: Buffer;\n totalBytes: number;\n fileName: string;\n mimeType: string;\n options: UploadOptions;\n }): Promise<DriveApiFile> {\n const { buffer, totalBytes, fileName, mimeType, options } = params;\n const chunkSize = this.computeAdaptiveChunkSize(totalBytes, options.chunkSize);\n\n const sessionUrl = await this.initiateResumableSession({\n fileName,\n mimeType,\n totalBytes,\n parent: options.parent,\n description: options.description,\n properties: options.properties,\n appProperties: options.appProperties,\n });\n\n let bytesSent = 0;\n const startTime = Date.now();\n const totalChunks = Math.ceil(totalBytes / chunkSize) || 1;\n let chunkIndex = 0;\n\n while (bytesSent < totalBytes) {\n if (options.signal?.aborted) {\n throw new Error('Upload aborted by user signal');\n }\n chunkIndex++;\n const currentChunkSize = Math.min(chunkSize, totalBytes - bytesSent);\n const chunk = buffer.subarray(bytesSent, bytesSent + currentChunkSize);\n\n const rangeStart = bytesSent;\n const rangeEnd = bytesSent + currentChunkSize - 1;\n\n const chunkResult = await this.uploadChunkWithRetry({\n sessionUrl,\n buffer: chunk,\n rangeStart,\n rangeEnd,\n totalBytes,\n });\n\n bytesSent += currentChunkSize;\n\n if (options.onProgress) {\n const elapsedSecs = (Date.now() - startTime) / 1000;\n const bytesPerSecond = elapsedSecs > 0 ? Math.round(bytesSent / elapsedSecs) : 0;\n const remainingBytes = totalBytes - bytesSent;\n const estimatedTimeRemainingSeconds = bytesPerSecond > 0 ? Math.round(remainingBytes / bytesPerSecond) : 0;\n const percentage = totalBytes > 0 ? Math.min(100, Math.round((bytesSent / totalBytes) * 1000) / 10) : 100;\n\n options.onProgress({\n bytesSent,\n totalBytes,\n percentage,\n bytesPerSecond,\n speedFormatted: formatSpeed(bytesPerSecond),\n estimatedTimeRemainingSeconds,\n chunkIndex,\n totalChunks,\n });\n }\n\n if (chunkResult.isComplete && chunkResult.file) {\n return chunkResult.file;\n }\n }\n\n throw new DriveUploadError('Resumable buffer upload ended without completion', bytesSent, totalBytes);\n }\n\n /**\n * Request an upload session URI from Google Drive API\n */\n private async initiateResumableSession(meta: {\n fileName: string;\n mimeType: string;\n totalBytes: number;\n parent?: string;\n description?: string;\n properties?: Record<string, string>;\n appProperties?: Record<string, string>;\n }): Promise<string> {\n const authClient = (this.drive as any).context._options.auth;\n const headers: Record<string, string> = {\n 'X-Upload-Content-Type': meta.mimeType,\n 'X-Upload-Content-Length': meta.totalBytes.toString(),\n 'Content-Type': 'application/json; charset=UTF-8',\n };\n\n const metadata: any = {\n name: meta.fileName,\n mimeType: meta.mimeType,\n description: meta.description,\n properties: meta.properties,\n appProperties: meta.appProperties,\n };\n\n if (meta.parent) {\n metadata.parents = [meta.parent];\n }\n\n const res = await withRetry(async () => {\n return await authClient.request({\n url: 'https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&supportsAllDrives=true',\n method: 'POST',\n headers,\n data: metadata,\n agent: getOptimizedHttpsAgent(),\n });\n });\n\n const sessionUrl = res.headers?.get ? res.headers.get('location') : (res.headers?.location || res.headers?.['location']);\n if (!sessionUrl) {\n throw new DriveUploadError('Failed to initiate resumable upload session: No Location header in response');\n }\n\n return sessionUrl;\n }\n\n /**\n * Upload a chunk with exponential backoff on network failures\n */\n private async uploadChunkWithRetry(params: {\n sessionUrl: string;\n buffer: Buffer;\n rangeStart: number;\n rangeEnd: number;\n totalBytes: number;\n }): Promise<{ isComplete: boolean; file?: DriveApiFile }> {\n const { sessionUrl, buffer, rangeStart, rangeEnd, totalBytes } = params;\n const authClient = (this.drive as any).context._options.auth;\n\n const headers = {\n 'Content-Length': buffer.length.toString(),\n 'Content-Range': `bytes ${rangeStart}-${rangeEnd}/${totalBytes}`,\n };\n\n return await withRetry(async () => {\n try {\n const res = await authClient.request({\n url: sessionUrl,\n method: 'PUT',\n headers,\n data: buffer,\n agent: getOptimizedHttpsAgent(),\n validateStatus: (status: number) => (status >= 200 && status < 300) || status === 308,\n });\n\n if (res.status === 200 || res.status === 201) {\n return { isComplete: true, file: res.data };\n }\n\n if (res.status === 308) {\n return { isComplete: false };\n }\n\n throw new DriveUploadError(`Unexpected response status ${res.status} during chunk upload`);\n } catch (err: any) {\n if (err.status === 308) {\n return { isComplete: false };\n }\n const msg = err.message || err.response?.data?.error?.message || '';\n if (msg.includes('Service Accounts do not have storage quota') || msg.includes('storageQuotaExceeded')) {\n throw new DriveUploadError(\n 'Google Drive Policy: Service Accounts do not have file storage quota in personal Google accounts. To upload files, use an OAuth2 token or pass accessToken.',\n params.rangeStart,\n params.totalBytes,\n err\n );\n }\n throw err;\n }\n });\n }\n}\n\n","/**\n * Formats bytes to human-readable string (KB, MB, GB)\n */\nexport function formatBytes(bytes: number, decimals = 2): string {\n if (bytes === 0) return '0 B';\n const k = 1024;\n const dm = decimals < 0 ? 0 : decimals;\n const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`;\n}\n\n/**\n * Formats speed in bytes/sec to human readable format (e.g. 5.4 MB/s)\n */\nexport function formatSpeed(bytesPerSecond: number): string {\n return `${formatBytes(bytesPerSecond)}/s`;\n}\n\n/**\n * Formats seconds to mm:ss or hh:mm:ss\n */\nexport function formatDuration(seconds: number): string {\n if (!Number.isFinite(seconds) || seconds < 0) return '--:--';\n const totalSeconds = Math.round(seconds);\n const hrs = Math.floor(totalSeconds / 3600);\n const mins = Math.floor((totalSeconds % 3600) / 60);\n const secs = totalSeconds % 60;\n\n if (hrs > 0) {\n return `${hrs}h ${mins}m ${secs}s`;\n }\n return `${mins}m ${secs}s`;\n}\n\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { pipeline } from 'node:stream/promises';\nimport { Transform } from 'node:stream';\nimport type { drive_v3 } from '@googleapis/drive';\nimport type { DownloadOptions, DownloadProgress } from '../types.js';\nimport { isGoogleWorkspaceDoc, DEFAULT_EXPORT_MIMES, getExtensionForMime } from '../utils/mime.js';\nimport { formatSpeed } from '../utils/format.js';\nimport { withRetry } from '../utils/retry.js';\n\nexport class Downloader {\n private drive: drive_v3.Drive;\n\n constructor(drive: drive_v3.Drive) {\n this.drive = drive;\n }\n\n /**\n * Downloads a file from Google Drive to local destination path or returns a readable stream.\n */\n async download(fileId: string, options: DownloadOptions = {}): Promise<{\n filePath?: string;\n stream?: NodeJS.ReadableStream;\n name: string;\n mimeType: string;\n size?: number;\n }> {\n // 1. Check if metadata is pre-provided or needs remote fetch\n let name = options.metadata?.name;\n let mimeType = options.metadata?.mimeType;\n let totalBytes = options.metadata?.size;\n\n if (!name || !mimeType) {\n const metaRes = await withRetry(async () => {\n return await this.drive.files.get({\n fileId,\n fields: 'id, name, mimeType, size',\n supportsAllDrives: true,\n });\n });\n\n const file = metaRes.data;\n name = file.name || 'downloaded-file';\n mimeType = file.mimeType || 'application/octet-stream';\n totalBytes = file.size ? parseInt(file.size, 10) : undefined;\n }\n\n let downloadStream: NodeJS.ReadableStream;\n let finalFileName = name!;\n\n // 2. Determine if it's a Google Workspace document needing export\n if (isGoogleWorkspaceDoc(mimeType)) {\n const exportConfig = DEFAULT_EXPORT_MIMES[mimeType] || {\n mimeType: 'application/pdf',\n extension: '.pdf',\n };\n const targetMime = options.exportMimeType || exportConfig.mimeType;\n const ext = getExtensionForMime(targetMime) || exportConfig.extension;\n\n if (!finalFileName.endsWith(ext)) {\n finalFileName = `${finalFileName}${ext}`;\n }\n\n const res = await withRetry(async () => {\n return await this.drive.files.export(\n { fileId, mimeType: targetMime },\n { responseType: 'stream' }\n );\n });\n downloadStream = res.data as NodeJS.ReadableStream;\n } else {\n // Regular binary file download\n const res = await withRetry(async () => {\n return await this.drive.files.get(\n { fileId, alt: 'media', supportsAllDrives: true },\n { responseType: 'stream' }\n );\n });\n downloadStream = res.data as NodeJS.ReadableStream;\n }\n\n // 3. Attach progress tracker if requested\n let bytesRead = 0;\n const startTime = Date.now();\n\n const progressTracker = new Transform({\n transform(chunk, encoding, callback) {\n bytesRead += chunk.length;\n if (options.onProgress) {\n const elapsedSecs = (Date.now() - startTime) / 1000;\n const bytesPerSecond = elapsedSecs > 0 ? Math.round(bytesRead / elapsedSecs) : 0;\n const percentage = totalBytes ? Math.min(100, Math.round((bytesRead / totalBytes) * 1000) / 10) : undefined;\n\n options.onProgress({\n bytesRead,\n totalBytes,\n percentage,\n bytesPerSecond,\n speedFormatted: formatSpeed(bytesPerSecond),\n });\n }\n callback(null, chunk);\n },\n });\n\n const monitoredStream = downloadStream.pipe(progressTracker);\n\n // 4. Save to disk if destination provided, otherwise return stream\n if (options.destination) {\n let destPath = options.destination;\n // If destination is a directory, append finalFileName\n if (fs.existsSync(destPath) && fs.statSync(destPath).isDirectory()) {\n destPath = path.join(destPath, finalFileName);\n }\n\n await fs.promises.mkdir(path.dirname(destPath), { recursive: true });\n const writeStream = fs.createWriteStream(destPath, { highWaterMark: 1024 * 1024 });\n await pipeline(monitoredStream, writeStream);\n\n return {\n filePath: destPath,\n name: finalFileName,\n mimeType,\n size: bytesRead,\n };\n }\n\n return {\n stream: monitoredStream,\n name: finalFileName,\n mimeType,\n size: totalBytes,\n };\n }\n\n /**\n * Returns a raw ReadableStream for the file, supporting HTTP Range requests for partial content / streaming.\n */\n async createReadStream(\n fileId: string,\n options?: { start?: number; end?: number }\n ): Promise<NodeJS.ReadableStream> {\n const headers: Record<string, string> = {};\n if (options?.start !== undefined || options?.end !== undefined) {\n const start = options.start ?? 0;\n const end = options.end !== undefined ? options.end : '';\n headers['Range'] = `bytes=${start}-${end}`;\n }\n\n const res = await withRetry(async () => {\n return await this.drive.files.get(\n { fileId, alt: 'media', supportsAllDrives: true },\n { responseType: 'stream', headers }\n );\n });\n return res.data as NodeJS.ReadableStream;\n }\n}\n\n","import type { drive_v3 } from '@googleapis/drive';\nimport type { DriveApiFile } from '../types.js';\nimport { GOOGLE_WORKSPACE_MIME_TYPES } from '../utils/mime.js';\nimport { withRetry } from '../utils/retry.js';\n\nexport class DriveQueryBuilder {\n private drive: drive_v3.Drive;\n private conditions: string[] = [];\n private orderClauses: string[] = [];\n private limitNumber = 100;\n private requestedFields = 'nextPageToken, files(id, name, mimeType, size, modifiedTime, createdTime, parents, trashed, webViewLink, webContentLink, shared)';\n private spaces = 'drive';\n\n constructor(drive: drive_v3.Drive) {\n this.drive = drive;\n }\n\n /**\n * Escape single quotes and backslashes for Google Drive search queries\n */\n private escape(str: string): string {\n return str.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\");\n }\n\n /**\n * Filter: Exact file name match\n */\n nameEquals(name: string): this {\n this.conditions.push(`name = '${this.escape(name)}'`);\n return this;\n }\n\n /**\n * Filter: File name contains substring\n */\n nameContains(substring: string): this {\n this.conditions.push(`name contains '${this.escape(substring)}'`);\n return this;\n }\n\n /**\n * Filter: Specific MIME type\n */\n mimeType(mime: string): this {\n this.conditions.push(`mimeType = '${this.escape(mime)}'`);\n return this;\n }\n\n /**\n * Filter: Only folders\n */\n isFolder(): this {\n this.conditions.push(`mimeType = '${GOOGLE_WORKSPACE_MIME_TYPES.FOLDER}'`);\n return this;\n }\n\n /**\n * Filter: Exclude folders (only files)\n */\n isFile(): this {\n this.conditions.push(`mimeType != '${GOOGLE_WORKSPACE_MIME_TYPES.FOLDER}'`);\n return this;\n }\n\n /**\n * Filter: Direct parent folder ID\n */\n inFolder(folderId: string): this {\n this.conditions.push(`'${this.escape(folderId)}' in parents`);\n return this;\n }\n\n /**\n * Filter: Items not in trash (default recommended)\n */\n notTrashed(): this {\n this.conditions.push('trashed = false');\n return this;\n }\n\n /**\n * Filter: Only trashed items\n */\n onlyTrashed(): this {\n this.conditions.push('trashed = true');\n return this;\n }\n\n /**\n * Filter: Starred items\n */\n starred(isStarred = true): this {\n this.conditions.push(`starred = ${isStarred}`);\n return this;\n }\n\n /**\n * Filter: Shared with current user\n */\n sharedWithMe(): this {\n this.conditions.push('sharedWithMe = true');\n return this;\n }\n\n /**\n * Filter: Modified after timestamp or Date\n */\n modifiedAfter(date: Date | string): this {\n const iso = date instanceof Date ? date.toISOString() : new Date(date).toISOString();\n this.conditions.push(`modifiedTime > '${iso}'`);\n return this;\n }\n\n /**\n * Filter: Modified before timestamp or Date\n */\n modifiedBefore(date: Date | string): this {\n const iso = date instanceof Date ? date.toISOString() : new Date(date).toISOString();\n this.conditions.push(`modifiedTime < '${iso}'`);\n return this;\n }\n\n /**\n * Filter: Full-text search across content and name\n */\n fullText(term: string): this {\n this.conditions.push(`fullText contains '${this.escape(term)}'`);\n return this;\n }\n\n /**\n * Custom raw query condition\n */\n raw(condition: string): this {\n this.conditions.push(`(${condition})`);\n return this;\n }\n\n /**\n * Custom raw query condition (alias for raw)\n */\n custom(condition: string): this {\n return this.raw(condition);\n }\n\n /**\n * Filter: Exact MD5 checksum match\n */\n md5(checksum: string): this {\n this.conditions.push(`md5Checksum = '${this.escape(checksum)}'`);\n return this;\n }\n\n /**\n * Sort ordering (e.g. 'modifiedTime desc', 'name', 'folder,modifiedTime desc')\n */\n orderBy(order: string): this {\n this.orderClauses.push(order);\n return this;\n }\n\n /**\n * Maximum items to retrieve per page or query\n */\n pageSize(size: number): this {\n this.limitNumber = Math.min(1000, Math.max(1, size));\n return this;\n }\n\n /**\n * Custom fields to return from Drive API\n */\n fields(fieldsString: string): this {\n this.requestedFields = fieldsString;\n return this;\n }\n\n /**\n * Compiles the full query string\n */\n toQueryString(): string {\n return this.conditions.join(' and ');\n }\n\n /**\n * Executes query and returns array of matching files\n */\n async list(): Promise<DriveApiFile[]> {\n const q = this.toQueryString();\n const orderBy = this.orderClauses.join(', ');\n\n const res = await withRetry(async () => {\n return await this.drive.files.list({\n q: q || undefined,\n orderBy: orderBy || undefined,\n pageSize: this.limitNumber,\n fields: this.requestedFields,\n spaces: this.spaces,\n supportsAllDrives: true,\n includeItemsFromAllDrives: true,\n });\n });\n\n return res.data.files || [];\n }\n\n /**\n * Executes query and returns array of matching files (alias for list)\n */\n async execute(): Promise<DriveApiFile[]> {\n return await this.list();\n }\n\n /**\n * Returns the first matching file, or null if not found\n */\n async first(): Promise<DriveApiFile | null> {\n const originalLimit = this.limitNumber;\n this.limitNumber = 1;\n const items = await this.list();\n this.limitNumber = originalLimit;\n return items[0] || null;\n }\n\n /**\n * Counts matching items (up to 1000)\n */\n async count(): Promise<number> {\n const items = await this.list();\n return items.length;\n }\n\n /**\n * Async iterator to stream all pages automatically without loading all into memory\n */\n async *[Symbol.asyncIterator](): AsyncIterableIterator<DriveApiFile> {\n const q = this.toQueryString();\n const orderBy = this.orderClauses.join(', ');\n let pageToken: string | undefined = undefined;\n\n const effectiveFields = this.requestedFields.includes('nextPageToken')\n ? this.requestedFields\n : `nextPageToken, ${this.requestedFields}`;\n\n do {\n const res = await withRetry(async () => {\n return await this.drive.files.list({\n q: q || undefined,\n orderBy: orderBy || undefined,\n pageSize: this.limitNumber,\n pageToken,\n fields: effectiveFields,\n spaces: this.spaces,\n supportsAllDrives: true,\n includeItemsFromAllDrives: true,\n });\n });\n\n const files = res.data.files || [];\n for (const file of files) {\n yield file;\n }\n pageToken = res.data.nextPageToken || undefined;\n } while (pageToken);\n }\n}\n\n","/**\n * Lightweight asynchronous worker pool for concurrent operations\n */\nexport class ConcurrencyPool {\n private concurrency: number;\n private running = 0;\n private queue: (() => Promise<void>)[] = [];\n\n constructor(concurrency = 4) {\n this.concurrency = Math.max(1, concurrency);\n }\n\n /**\n * Run a task when a slot becomes available\n */\n async run<T>(task: () => Promise<T>): Promise<T> {\n if (this.running >= this.concurrency) {\n await new Promise<void>((resolve) => {\n this.queue.push(async () => {\n resolve();\n });\n });\n }\n\n this.running++;\n try {\n return await task();\n } finally {\n this.running--;\n if (this.queue.length > 0) {\n const next = this.queue.shift();\n if (next) next();\n }\n }\n }\n\n /**\n * Run all tasks in parallel bounded by concurrency limit\n */\n async all<T>(tasks: (() => Promise<T>)[]): Promise<T[]> {\n return Promise.all(tasks.map((task) => this.run(task)));\n }\n\n /**\n * Execute an array of items concurrently through an async mapper\n */\n async map<Item, Result>(\n items: Item[],\n fn: (item: Item, index: number) => Promise<Result>\n ): Promise<Result[]> {\n return Promise.all(items.map((item, index) => this.run(() => fn(item, index))));\n }\n}\n\n","import { EventEmitter } from 'node:events';\nimport type { drive_v3 } from '@googleapis/drive';\nimport type { DriveApiFile } from '../types.js';\nimport { withRetry } from '../utils/retry.js';\n\nexport interface WatcherOptions {\n /** Polling interval in milliseconds (default: 5000) */\n intervalMs?: number;\n /** Restrict changes to a specific folder ID or path */\n folderId?: string;\n /** Whether to emit initial existing files on startup (default: false) */\n emitInitial?: boolean;\n}\n\nexport interface FileChangeEvent {\n type: 'create' | 'modify' | 'delete';\n fileId: string;\n file?: DriveApiFile;\n removed?: boolean;\n time: Date;\n}\n\n/**\n * Real-time Google Drive Change Watcher\n * Listens for new files, updates, and deletions using the Google Drive Changes API.\n */\nexport class DriveWatcher extends EventEmitter {\n private drive: drive_v3.Drive;\n private options: WatcherOptions;\n private timer: NodeJS.Timeout | null = null;\n private isRunning = false;\n private pageToken: string | null = null;\n\n constructor(drive: drive_v3.Drive, options: WatcherOptions = {}) {\n super();\n this.drive = drive;\n this.options = {\n intervalMs: 5000,\n ...options,\n };\n }\n\n /**\n * Starts listening for changes\n */\n async start(): Promise<this> {\n if (this.isRunning) return this;\n this.isRunning = true;\n\n // Get initial start page token\n if (!this.pageToken) {\n const tokenRes = await withRetry(async () => {\n return await this.drive.changes.getStartPageToken({\n supportsAllDrives: true,\n });\n });\n this.pageToken = tokenRes.data.startPageToken || null;\n }\n\n this.poll();\n return this;\n }\n\n /**\n * Stops listening\n */\n stop(): void {\n this.isRunning = false;\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n this.emit('stop');\n }\n\n /**\n * Internal polling cycle\n */\n private async poll(): Promise<void> {\n if (!this.isRunning) return;\n\n try {\n if (!this.pageToken) {\n const tokenRes = await withRetry(async () => {\n return await this.drive.changes.getStartPageToken({\n supportsAllDrives: true,\n });\n });\n this.pageToken = tokenRes.data.startPageToken || null;\n }\n\n let nextPageToken = this.pageToken;\n\n do {\n const res = await withRetry(async () => {\n return await this.drive.changes.list({\n pageToken: nextPageToken!,\n fields: 'nextPageToken, newStartPageToken, changes(changeType, fileId, removed, time, file(id, name, mimeType, size, createdTime, modifiedTime, parents, trashed))',\n supportsAllDrives: true,\n includeItemsFromAllDrives: true,\n });\n });\n\n const changes = res.data.changes || [];\n\n for (const change of changes) {\n if (!change.fileId) continue;\n\n // If restricted to a folder, check parents\n if (this.options.folderId && change.file) {\n const parents = change.file.parents || [];\n if (!parents.includes(this.options.folderId)) {\n continue;\n }\n }\n\n let eventType: 'create' | 'modify' | 'delete' = 'modify';\n if (change.removed || change.file?.trashed) {\n eventType = 'delete';\n } else if (change.file?.createdTime && change.file?.modifiedTime) {\n const created = new Date(change.file.createdTime).getTime();\n const modified = new Date(change.file.modifiedTime).getTime();\n if (Math.abs(modified - created) < 2000) {\n eventType = 'create';\n }\n }\n\n const eventPayload: FileChangeEvent = {\n type: eventType,\n fileId: change.fileId,\n file: change.file || undefined,\n removed: change.removed || false,\n time: change.time ? new Date(change.time) : new Date(),\n };\n\n this.emit('change', eventPayload);\n this.emit(eventType, eventPayload);\n }\n\n if (res.data.newStartPageToken) {\n this.pageToken = res.data.newStartPageToken;\n break;\n }\n\n nextPageToken = res.data.nextPageToken || null;\n } while (nextPageToken);\n } catch (err) {\n this.emit('error', err);\n } finally {\n if (this.isRunning) {\n this.timer = setTimeout(() => this.poll(), this.options.intervalMs);\n }\n }\n }\n}\n\n","import type { drive_v3 } from '@googleapis/drive';\nimport type { DriveApiFile } from '../types.js';\nimport { withRetry } from '../utils/retry.js';\nimport { formatBytes } from '../utils/format.js';\n\nexport interface DuplicateGroup {\n name: string;\n count: number;\n totalSize: number;\n formattedTotalSize: string;\n files: { id: string; name: string; size: number; modifiedTime: string; md5Checksum?: string }[];\n}\n\nexport class StorageCleaner {\n private drive: drive_v3.Drive;\n\n constructor(drive: drive_v3.Drive) {\n this.drive = drive;\n }\n\n /**\n * Finds the largest files occupying space in the Google Drive account\n */\n async findLargestFiles(limit = 10): Promise<{\n id: string;\n name: string;\n size: number;\n formattedSize: string;\n mimeType: string;\n modifiedTime?: string;\n webViewLink?: string;\n }[]> {\n const res = await withRetry(async () => {\n return await this.drive.files.list({\n q: 'trashed = false and mimeType != \"application/vnd.google-apps.folder\"',\n orderBy: 'quotaBytesUsed desc',\n pageSize: Math.min(100, Math.max(1, limit)),\n fields: 'files(id, name, size, mimeType, modifiedTime, webViewLink, quotaBytesUsed)',\n supportsAllDrives: true,\n includeItemsFromAllDrives: true,\n });\n });\n\n const files = res.data.files || [];\n return files.map((f) => {\n const sizeBytes = parseInt(f.size || f.quotaBytesUsed || '0', 10);\n return {\n id: f.id!,\n name: f.name || 'untitled',\n size: sizeBytes,\n formattedSize: formatBytes(sizeBytes),\n mimeType: f.mimeType || 'unknown',\n modifiedTime: f.modifiedTime || undefined,\n webViewLink: f.webViewLink || undefined,\n };\n });\n }\n\n /**\n * Scans Google Drive and detects duplicate files (by MD5 hash or exact name)\n */\n async findDuplicates(options: { by?: 'md5' | 'name'; maxScan?: number } = {}): Promise<DuplicateGroup[]> {\n const mode = options.by || 'name';\n const maxScan = options.maxScan || 1000;\n\n const files: drive_v3.Schema$File[] = [];\n let pageToken: string | undefined = undefined;\n\n do {\n const remaining = maxScan - files.length;\n if (remaining <= 0) break;\n\n const res = await withRetry(async () => {\n return await this.drive.files.list({\n q: 'trashed = false and mimeType != \"application/vnd.google-apps.folder\"',\n pageSize: Math.min(1000, remaining),\n pageToken,\n fields: 'nextPageToken, files(id, name, size, md5Checksum, modifiedTime)',\n supportsAllDrives: true,\n includeItemsFromAllDrives: true,\n });\n });\n\n files.push(...(res.data.files || []));\n pageToken = res.data.nextPageToken || undefined;\n } while (pageToken && files.length < maxScan);\n const map = new Map<string, any[]>();\n\n for (const f of files) {\n if (!f.id) continue;\n const key = mode === 'md5' && f.md5Checksum ? f.md5Checksum : (f.name || '');\n if (!key) continue;\n\n if (!map.has(key)) {\n map.set(key, []);\n }\n map.get(key)!.push(f);\n }\n\n const duplicates: DuplicateGroup[] = [];\n for (const [key, group] of map.entries()) {\n if (group.length > 1) {\n let totalSize = 0;\n const mappedFiles = group.map((item) => {\n const s = parseInt(item.size || '0', 10);\n totalSize += s;\n return {\n id: item.id,\n name: item.name,\n size: s,\n modifiedTime: item.modifiedTime,\n md5Checksum: item.md5Checksum,\n };\n });\n\n duplicates.push({\n name: key,\n count: group.length,\n totalSize,\n formattedTotalSize: formatBytes(totalSize),\n files: mappedFiles,\n });\n }\n }\n\n return duplicates.sort((a, b) => b.totalSize - a.totalSize);\n }\n\n /**\n * Empties the entire trash in Google Drive\n */\n async emptyTrash(): Promise<void> {\n await withRetry(async () => {\n await this.drive.files.emptyTrash({});\n });\n }\n}\n\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport crypto from 'node:crypto';\nimport type { drive_v3 } from '@googleapis/drive';\nimport type { DriveApiFile } from '../types.js';\nimport { ConcurrencyPool } from './concurrency-pool.js';\nimport { Downloader } from './downloader.js';\nimport { withRetry } from '../utils/retry.js';\nimport { formatBytes } from '../utils/format.js';\n\n/**\n * Calculates MD5 checksum of a local file via streams (low memory)\n */\nexport async function calculateFileMd5(filePath: string): Promise<string> {\n return new Promise((resolve, reject) => {\n const hash = crypto.createHash('md5');\n const stream = fs.createReadStream(filePath);\n stream.on('data', (chunk) => hash.update(chunk));\n stream.on('end', () => resolve(hash.digest('hex')));\n stream.on('error', reject);\n });\n}\n\nexport interface PullResult {\n downloaded: { remoteId: string; remoteName: string; localPath: string; size: number }[];\n skipped: { remoteId: string; remoteName: string; reason: string }[];\n failed: { remoteId: string; remoteName: string; error: Error }[];\n totalBytes: number;\n durationMs: number;\n}\n\nexport class SmartSyncEngine {\n private drive: drive_v3.Drive;\n private downloader: Downloader;\n\n constructor(drive: drive_v3.Drive) {\n this.drive = drive;\n this.downloader = new Downloader(drive);\n }\n\n /**\n * Pulls (downloads) an entire Google Drive folder tree to a local directory\n */\n async pullFolder(\n remoteFolderId: string,\n localDestinationDir: string,\n options: {\n concurrency?: number;\n overwrite?: boolean;\n onFileStart?: (remoteName: string, relativePath: string) => void;\n onFileComplete?: (remoteName: string, localPath: string) => void;\n } = {}\n ): Promise<PullResult> {\n const startTime = Date.now();\n const concurrency = options.concurrency || 4;\n const pool = new ConcurrencyPool(concurrency);\n\n const result: PullResult = {\n downloaded: [],\n skipped: [],\n failed: [],\n totalBytes: 0,\n durationMs: 0,\n };\n\n await fs.promises.mkdir(localDestinationDir, { recursive: true });\n\n // Recursive remote listing\n const collectRemoteItems = async (folderId: string, relPath: string): Promise<{\n id: string;\n name: string;\n isFolder: boolean;\n relPath: string;\n size: number;\n md5Checksum?: string;\n }[]> => {\n const items: any[] = [];\n let pageToken: string | undefined = undefined;\n\n do {\n const res = await withRetry(async () => {\n return await this.drive.files.list({\n q: `'${folderId}' in parents and trashed = false`,\n fields: 'nextPageToken, files(id, name, mimeType, size, md5Checksum)',\n pageSize: 500,\n supportsAllDrives: true,\n includeItemsFromAllDrives: true,\n });\n });\n\n const files = res.data.files || [];\n for (const file of files) {\n if (!file.id || !file.name) continue;\n const isFolder = file.mimeType === 'application/vnd.google-apps.folder';\n const fileRel = relPath ? path.join(relPath, file.name) : file.name;\n\n if (isFolder) {\n const sub = await collectRemoteItems(file.id, fileRel);\n items.push(...sub);\n } else {\n items.push({\n id: file.id,\n name: file.name,\n isFolder: false,\n relPath: fileRel,\n size: parseInt(file.size || '0', 10),\n md5Checksum: file.md5Checksum,\n });\n }\n }\n pageToken = res.data.nextPageToken || undefined;\n } while (pageToken);\n\n return items;\n };\n\n const remoteFiles = await collectRemoteItems(remoteFolderId, '');\n\n await pool.map(remoteFiles, async (remoteItem) => {\n const localFilePath = path.join(localDestinationDir, remoteItem.relPath);\n\n // Check if local file already exists and matches MD5 or size\n if (!options.overwrite && fs.existsSync(localFilePath)) {\n const localStat = await fs.promises.stat(localFilePath);\n if (remoteItem.md5Checksum) {\n const localMd5 = await calculateFileMd5(localFilePath);\n if (localMd5.toLowerCase() === remoteItem.md5Checksum.toLowerCase()) {\n result.skipped.push({\n remoteId: remoteItem.id,\n remoteName: remoteItem.name,\n reason: 'Identical MD5 checksum matches local file',\n });\n return;\n }\n } else if (localStat.size === remoteItem.size && remoteItem.size > 0) {\n result.skipped.push({\n remoteId: remoteItem.id,\n remoteName: remoteItem.name,\n reason: 'Identical file size exists locally',\n });\n return;\n }\n }\n\n try {\n if (options.onFileStart) {\n options.onFileStart(remoteItem.name, remoteItem.relPath);\n }\n\n await this.downloader.download(remoteItem.id, {\n destination: localFilePath,\n });\n\n result.downloaded.push({\n remoteId: remoteItem.id,\n remoteName: remoteItem.name,\n localPath: localFilePath,\n size: remoteItem.size,\n });\n result.totalBytes += remoteItem.size;\n\n if (options.onFileComplete) {\n options.onFileComplete(remoteItem.name, localFilePath);\n }\n } catch (err: any) {\n result.failed.push({\n remoteId: remoteItem.id,\n remoteName: remoteItem.name,\n error: err,\n });\n }\n });\n\n result.durationMs = Date.now() - startTime;\n return result;\n }\n}\n\n","import http from 'node:http';\nimport { exec } from 'node:child_process';\nimport { auth as googleAuth } from '@googleapis/drive';\nimport { DEFAULT_SCOPES } from './authenticator.js';\n\nexport interface BrowserLoginOptions {\n clientId: string;\n clientSecret: string;\n port?: number;\n scopes?: string[];\n}\n\nexport interface LoginResult {\n tokens: {\n access_token?: string | null;\n refresh_token?: string | null;\n expiry_date?: number | null;\n token_type?: string | null;\n };\n client: any;\n}\n\n/**\n * Initiates interactive 1-click browser login flow:\n * 1. Starts ephemeral local callback server\n * 2. Opens default browser to Google OAuth consent\n * 3. Catches callback, exchanges code for tokens, and serves success page\n */\nexport async function loginWithBrowser(options: BrowserLoginOptions): Promise<LoginResult> {\n const port = options.port || 3000;\n const redirectUri = `http://localhost:${port}/oauth2callback`;\n const scopes = options.scopes || DEFAULT_SCOPES;\n\n const oauth2Client = new googleAuth.OAuth2(\n options.clientId,\n options.clientSecret,\n redirectUri\n );\n\n const authUrl = oauth2Client.generateAuthUrl({\n access_type: 'offline',\n prompt: 'consent',\n scope: scopes,\n });\n\n return new Promise((resolve, reject) => {\n const server = http.createServer(async (req, res) => {\n try {\n const reqUrl = new URL(req.url || '/', `http://localhost:${port}`);\n if (reqUrl.pathname === '/oauth2callback') {\n const code = reqUrl.searchParams.get('code');\n const error = reqUrl.searchParams.get('error');\n\n if (error) {\n res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });\n res.end(`<h2>❌ Authorization Failed</h2><p>${error}</p>`);\n server.close();\n return reject(new Error(`OAuth error: ${error}`));\n }\n\n if (!code) {\n res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });\n res.end('<h2>❌ Missing authorization code</h2>');\n return;\n }\n\n // Exchange code for tokens\n const { tokens } = await oauth2Client.getToken(code);\n oauth2Client.setCredentials(tokens);\n\n // Render Success Page\n res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });\n res.end(`\n <!DOCTYPE html>\n <html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n <title>DriveKit Authentication</title>\n <style>\n body {\n font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, sans-serif;\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100vh;\n margin: 0;\n background: #0f172a;\n color: #f8fafc;\n }\n .card {\n text-align: center;\n padding: 40px;\n background: #1e293b;\n border-radius: 16px;\n box-shadow: 0 10px 25px rgba(0,0,0,0.5);\n }\n .badge {\n font-size: 48px;\n margin-bottom: 12px;\n }\n h1 { color: #38bdf8; margin: 0 0 10px 0; }\n p { color: #94a3b8; font-size: 16px; }\n </style>\n </head>\n <body>\n <div class=\"card\">\n <div class=\"badge\">⚡</div>\n <h1>Authentication Successful!</h1>\n <p>DriveKit is now connected to your Google Drive account.</p>\n <p>You can close this window and return to your terminal.</p>\n </div>\n </body>\n </html>\n `);\n\n server.close();\n resolve({ tokens, client: oauth2Client });\n }\n } catch (err) {\n res.writeHead(500, { 'Content-Type': 'text/html; charset=utf-8' });\n res.end(`<h2>❌ Server Error</h2><p>${(err as any).message}</p>`);\n server.close();\n reject(err);\n }\n });\n\n server.listen(port, () => {\n // Launch browser\n const openCmd = process.platform === 'darwin'\n ? `open \"${authUrl}\"`\n : process.platform === 'win32'\n ? `start \"\" \"${authUrl}\"`\n : `xdg-open \"${authUrl}\"`;\n\n exec(openCmd, (err) => {\n if (err) {\n console.log(`\\nPlease open the following URL in your browser to sign in:\\n${authUrl}\\n`);\n }\n });\n });\n\n server.on('error', (err: any) => {\n if (err.code === 'EADDRINUSE') {\n reject(new Error(`Port ${port} is already in use by another process. Please specify an alternate port with --port <number>.`));\n } else {\n reject(err);\n }\n });\n });\n}\n\n","import type { DriveKit } from './client.js';\nimport type {\n DriveApiFile,\n DriveApiPermission,\n DownloadOptions,\n ShareOptions,\n UploadOptions,\n SyncResult,\n} from '../types.js';\nimport type { PullResult } from './smart-sync.js';\nimport type { WatcherOptions, DriveWatcher } from './watcher.js';\n\n/**\n * Fluent reference to a specific file in Google Drive\n */\nexport class DriveFileRef {\n private drive: DriveKit;\n public readonly pathOrId: string;\n\n constructor(drive: DriveKit, pathOrId: string) {\n this.drive = drive;\n this.pathOrId = pathOrId;\n }\n\n /** Gets file metadata */\n async get(): Promise<DriveApiFile> {\n return await this.drive.getFile(this.pathOrId);\n }\n\n /** Checks if the file exists */\n async exists(): Promise<boolean> {\n return await this.drive.exists(this.pathOrId);\n }\n\n /** Reads file as UTF-8 string */\n async getText(): Promise<string> {\n return await this.drive.getText(this.pathOrId);\n }\n\n /** Reads and parses JSON file */\n async getJson<T = any>(): Promise<T> {\n return await this.drive.getJson<T>(this.pathOrId);\n }\n\n /** Downloads the file to destination */\n async download(optionsOrDestination?: string | DownloadOptions) {\n const opts = typeof optionsOrDestination === 'string'\n ? { destination: optionsOrDestination }\n : optionsOrDestination;\n return await this.drive.download(this.pathOrId, opts);\n }\n\n /** Moves the file to a new folder path or ID */\n async moveTo(newParentPathOrId: string): Promise<DriveApiFile> {\n return await this.drive.move(this.pathOrId, newParentPathOrId);\n }\n\n /** Copies the file to a target directory */\n async copyTo(parentPathOrId?: string, newName?: string): Promise<DriveApiFile> {\n return await this.drive.copy(this.pathOrId, { parent: parentPathOrId, name: newName });\n }\n\n /** Renames the file */\n async rename(newName: string): Promise<DriveApiFile> {\n return await this.drive.rename(this.pathOrId, newName);\n }\n\n /** Deletes the file (or moves to trash if permanent is false) */\n async delete(permanent = false): Promise<void> {\n return await this.drive.delete(this.pathOrId, permanent);\n }\n\n /** Moves file to trash */\n async trash(): Promise<void> {\n return await this.drive.trash(this.pathOrId);\n }\n\n /** Shares file */\n async share(options: ShareOptions): Promise<DriveApiPermission> {\n return await this.drive.share(this.pathOrId, options);\n }\n\n /** Makes file publicly accessible */\n async sharePublic(role: 'reader' | 'commenter' | 'writer' = 'reader') {\n return await this.drive.sharePublic(this.pathOrId, role);\n }\n\n /** Gets public/preview links */\n async getLink() {\n return await this.drive.getShareableLink(this.pathOrId);\n }\n\n /** Returns a ReadableStream for this file, optionally with byte Range requests */\n async createReadStream(options?: { start?: number; end?: number }): Promise<NodeJS.ReadableStream> {\n return await this.drive.createReadStream(this.pathOrId, options);\n }\n\n /** Grants access to a specific email with custom role and notification */\n async grantAccess(options: {\n email: string;\n role?: 'reader' | 'commenter' | 'writer';\n notify?: boolean;\n message?: string;\n }): Promise<DriveApiPermission> {\n return await this.drive.grantAccess(this.pathOrId, options);\n }\n\n /** Revokes access by permission ID or user email */\n async revokeAccess(permissionIdOrEmail: string): Promise<void> {\n return await this.drive.revokeAccess(this.pathOrId, permissionIdOrEmail);\n }\n\n /** Lists all granted permissions on this file */\n async listPermissions(): Promise<DriveApiPermission[]> {\n return await this.drive.listPermissions(this.pathOrId);\n }\n}\n\n/**\n * Fluent reference to a specific folder in Google Drive\n */\nexport class DriveFolderRef {\n private drive: DriveKit;\n public readonly pathOrId: string;\n\n constructor(drive: DriveKit, pathOrId: string) {\n this.drive = drive;\n this.pathOrId = pathOrId;\n }\n\n /** Lists contents of this folder */\n async ls(): Promise<DriveApiFile[]> {\n return await this.drive.ls(this.pathOrId);\n }\n\n /** Ensures this folder and subpaths exist (mkdir -p) */\n async mkdirp(subPath?: string): Promise<string> {\n const target = subPath\n ? (this.pathOrId.endsWith('/') ? `${this.pathOrId}${subPath}` : `${this.pathOrId}/${subPath}`)\n : this.pathOrId;\n return await this.drive.mkdirp(target);\n }\n\n /** Uploads a file directly into this folder */\n async upload(source: UploadOptions['source'], options: Omit<UploadOptions, 'source' | 'parent'> = {}): Promise<DriveApiFile> {\n return await this.drive.upload({\n ...options,\n source,\n parent: this.pathOrId,\n });\n }\n\n /** Synchronizes a local directory into this remote folder */\n async syncFrom(localDir: string, options: Parameters<DriveKit['syncFolder']>[2] = {}): Promise<SyncResult> {\n return await this.drive.syncFolder(localDir, this.pathOrId, options);\n }\n\n /** Pulls this remote folder down to local directory */\n async pullTo(localDestinationDir: string, options: Parameters<DriveKit['pull']>[2] = {}): Promise<PullResult> {\n return await this.drive.pull(this.pathOrId, localDestinationDir, options);\n }\n\n /** Watches this folder for real-time changes */\n async watch(options: Omit<WatcherOptions, 'folderId'> = {}): Promise<DriveWatcher> {\n return await this.drive.watch(this.pathOrId, options);\n }\n\n /** Grants access to this entire folder */\n async grantAccess(options: {\n email: string;\n role?: 'reader' | 'commenter' | 'writer';\n notify?: boolean;\n message?: string;\n }): Promise<DriveApiPermission> {\n return await this.drive.grantAccess(this.pathOrId, options);\n }\n\n /** Creates a writable stream directly into a file inside this folder */\n async createWriteStream(\n fileName: string,\n options?: Omit<UploadOptions, 'source' | 'filename' | 'parent'>\n ): Promise<NodeJS.WritableStream> {\n const targetPath = this.pathOrId.endsWith('/') ? `${this.pathOrId}${fileName}` : `${this.pathOrId}/${fileName}`;\n return await this.drive.createWriteStream(targetPath, options);\n }\n}\n\n","import path from 'node:path';\nimport type { UploadOptions, DownloadOptions, DriveApiFile } from '../types.js';\n\nexport interface DriveKitPlugin {\n name: string;\n beforeUpload?: (options: UploadOptions) => Promise<UploadOptions | void> | UploadOptions | void;\n afterUpload?: (file: DriveApiFile) => Promise<DriveApiFile | void> | DriveApiFile | void;\n beforeDownload?: (fileId: string, options: DownloadOptions) => Promise<DownloadOptions | void> | DownloadOptions | void;\n afterDownload?: (result: any) => Promise<any | void> | any | void;\n}\n\nexport class PluginManager {\n private plugins: DriveKitPlugin[] = [];\n\n /**\n * Register a plugin. If a plugin with the same name already exists,\n * it replaces the old one to avoid duplicate side-effects.\n */\n use(plugin: DriveKitPlugin): this {\n this.plugins = this.plugins.filter((p) => p.name !== plugin.name);\n this.plugins.push(plugin);\n return this;\n }\n\n /**\n * Unregister a plugin by its name.\n * Returns true if a plugin was found and removed, false otherwise.\n */\n unuse(pluginName: string): boolean {\n const initialLen = this.plugins.length;\n this.plugins = this.plugins.filter((p) => p.name !== pluginName);\n return this.plugins.length < initialLen;\n }\n\n /**\n * Check if a plugin with given name is currently active\n */\n has(pluginName: string): boolean {\n return this.plugins.some((p) => p.name === pluginName);\n }\n\n /**\n * Returns all currently registered plugins\n */\n getPlugins(): readonly DriveKitPlugin[] {\n return [...this.plugins];\n }\n\n async runBeforeUpload(options: UploadOptions): Promise<UploadOptions> {\n let current = { ...options };\n for (const plugin of this.plugins) {\n if (plugin.beforeUpload) {\n const modified = await plugin.beforeUpload(current);\n if (modified) current = modified;\n }\n }\n return current;\n }\n\n async runAfterUpload(file: DriveApiFile): Promise<DriveApiFile> {\n let current = file;\n for (const plugin of this.plugins) {\n if (plugin.afterUpload) {\n const modified = await plugin.afterUpload(current);\n if (modified) current = modified;\n }\n }\n return current;\n }\n\n async runBeforeDownload(fileId: string, options: DownloadOptions): Promise<DownloadOptions> {\n let current = { ...options };\n for (const plugin of this.plugins) {\n if (plugin.beforeDownload) {\n const modified = await plugin.beforeDownload(fileId, current);\n if (modified) current = modified;\n }\n }\n return current;\n }\n\n async runAfterDownload(result: any): Promise<any> {\n let current = result;\n for (const plugin of this.plugins) {\n if (plugin.afterDownload) {\n const modified = await plugin.afterDownload(current);\n if (modified) current = modified;\n }\n }\n return current;\n }\n}\n\nexport interface WebhookPluginOptions {\n url: string;\n headers?: Record<string, string>;\n events?: ('upload' | 'download')[];\n timeout?: number;\n retries?: number;\n onError?: (err: Error, event: 'upload' | 'download') => void;\n}\n\n/**\n * Creates an official Webhook Plugin to notify external services (Slack, Discord, Telegram, Zapier)\n * when uploads or downloads finish. Includes configurable timeout, retry mechanism, and error callback.\n */\nexport function createWebhookPlugin(options: WebhookPluginOptions): DriveKitPlugin {\n const events = options.events || ['upload'];\n const timeoutMs = options.timeout ?? 5000;\n const maxRetries = options.retries ?? 0;\n\n const sendWebhook = async (event: 'upload' | 'download', payload: any) => {\n let lastError: Error | null = null;\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n let timeoutId: NodeJS.Timeout | undefined;\n const controller = new AbortController();\n timeoutId = setTimeout(() => controller.abort(), timeoutMs);\n\n try {\n const res = await fetch(options.url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...(options.headers || {}) },\n body: JSON.stringify(payload),\n signal: controller.signal,\n });\n clearTimeout(timeoutId);\n if (!res.ok) {\n throw new Error(`Webhook returned HTTP ${res.status}: ${res.statusText}`);\n }\n return; // Success\n } catch (err: any) {\n clearTimeout(timeoutId);\n lastError = err;\n if (attempt === maxRetries) {\n if (options.onError) {\n options.onError(lastError instanceof Error ? lastError : new Error(String(lastError)), event);\n }\n }\n }\n }\n };\n\n return {\n name: 'drivekit-official-webhook',\n async afterUpload(file) {\n if (!events.includes('upload')) return;\n await sendWebhook('upload', {\n event: 'drivekit:upload',\n timestamp: new Date().toISOString(),\n file: {\n id: file.id,\n name: file.name,\n size: file.size,\n mimeType: file.mimeType,\n },\n });\n },\n async afterDownload(result) {\n if (!events.includes('download')) return;\n await sendWebhook('download', {\n event: 'drivekit:download',\n timestamp: new Date().toISOString(),\n file: {\n name: result.name,\n size: result.size,\n },\n });\n },\n };\n}\n\n/**\n * Creates an Auto-Namer Plugin to automatically prefix/suffix or timestamp files\n */\nexport function createAutoNamePlugin(options: {\n prefix?: string;\n suffix?: string;\n appendTimestamp?: boolean;\n}): DriveKitPlugin {\n return {\n name: 'drivekit-official-autoname',\n beforeUpload(opts) {\n let name = opts.name || opts.filename;\n if (!name && typeof opts.source === 'string') {\n name = path.basename(opts.source);\n }\n if (!name) return opts;\n\n const ext = path.extname(name);\n const base = path.basename(name, ext);\n\n let finalName = base;\n if (options.prefix) finalName = `${options.prefix}${finalName}`;\n if (options.appendTimestamp) {\n finalName = `${finalName}_${Date.now()}`;\n }\n if (options.suffix) finalName = `${finalName}${options.suffix}`;\n finalName = `${finalName}${ext}`;\n\n return {\n ...opts,\n name: finalName,\n filename: finalName,\n };\n },\n };\n}\n","import os from 'node:os';\nimport path from 'node:path';\nimport fs from 'node:fs';\n\nexport interface CacheFileEntry {\n id: string;\n name: string;\n mimeType: string;\n size?: number;\n parentId?: string;\n path?: string;\n md5Checksum?: string;\n trashed: boolean;\n modifiedTime?: string;\n updatedAt?: number;\n}\n\nexport interface CacheStats {\n fileCount: number;\n folderCount: number;\n totalSizeBytes: number;\n lastSyncTime: string | null;\n databasePath: string;\n}\n\nexport interface IMetadataCache {\n init(): void;\n getById(id: string): CacheFileEntry | null;\n getByPath(normalizedPath: string): CacheFileEntry | null;\n getChildren(parentId: string): CacheFileEntry[];\n findByMd5(md5: string): CacheFileEntry | null;\n searchByName(query: string): CacheFileEntry[];\n upsertFile(entry: CacheFileEntry): void;\n upsertFiles(entries: CacheFileEntry[]): void;\n deleteFile(id: string): void;\n pruneMissing(activeIds: string[]): number;\n clear(): void;\n getMeta(key: string): string | null;\n setMeta(key: string, value: string): void;\n getStats(): CacheStats;\n close(): void;\n}\n\n/**\n * High-performance SQLite-backed persistent cache for DriveKit metadata.\n * Uses Node 22's built-in `node:sqlite` (DatabaseSync).\n */\nexport class SqliteMetadataCache implements IMetadataCache {\n private db: any = null;\n private dbPath: string;\n private initialized = false;\n private fallbackMemory?: MemoryMetadataCache;\n\n constructor(customPath?: string) {\n if (customPath) {\n this.dbPath = customPath;\n } else {\n const dir = path.join(os.homedir(), '.drivekit');\n if (!fs.existsSync(dir)) {\n try {\n fs.mkdirSync(dir, { recursive: true });\n } catch {\n // fallback if home dir isn't writable\n }\n }\n this.dbPath = path.join(dir, 'cache.db');\n }\n }\n\n public init(): void {\n if (this.initialized) return;\n\n try {\n // Dynamic require so older environments or non-node runtimes don't fail parsing\n // @ts-ignore\n const { DatabaseSync } = require('node:sqlite');\n if (!DatabaseSync) {\n throw new Error('DatabaseSync not available');\n }\n this.db = new DatabaseSync(this.dbPath);\n\n // Initialize Schema & Indexes\n this.db.exec(`\n PRAGMA journal_mode = WAL;\n PRAGMA synchronous = NORMAL;\n\n CREATE TABLE IF NOT EXISTS files (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n mimeType TEXT,\n size INTEGER,\n parentId TEXT,\n path TEXT,\n md5Checksum TEXT,\n trashed INTEGER DEFAULT 0,\n modifiedTime TEXT,\n updatedAt INTEGER\n );\n\n CREATE TABLE IF NOT EXISTS meta (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL\n );\n\n CREATE INDEX IF NOT EXISTS idx_files_path ON files(path);\n CREATE INDEX IF NOT EXISTS idx_files_parent ON files(parentId);\n CREATE INDEX IF NOT EXISTS idx_files_md5 ON files(md5Checksum);\n CREATE INDEX IF NOT EXISTS idx_files_name ON files(name);\n `);\n\n this.initialized = true;\n } catch (err) {\n // If node:sqlite is not available (Node < 22.5), transparently fallback to in-memory cache\n this.fallbackMemory = new MemoryMetadataCache();\n this.fallbackMemory.init();\n this.initialized = true;\n this.db = null;\n }\n }\n\n public getById(id: string): CacheFileEntry | null {\n if (this.fallbackMemory) return this.fallbackMemory.getById(id);\n if (!this.initialized || !this.db) return null;\n const stmt = this.db.prepare('SELECT * FROM files WHERE id = ?');\n const row = stmt.get(id);\n return row ? this.mapRow(row) : null;\n }\n\n public getByPath(normalizedPath: string): CacheFileEntry | null {\n if (this.fallbackMemory) return this.fallbackMemory.getByPath(normalizedPath);\n if (!this.initialized || !this.db) return null;\n const stmt = this.db.prepare('SELECT * FROM files WHERE path = ? AND trashed = 0 LIMIT 1');\n const row = stmt.get(normalizedPath);\n return row ? this.mapRow(row) : null;\n }\n\n public getChildren(parentId: string): CacheFileEntry[] {\n if (this.fallbackMemory) return this.fallbackMemory.getChildren(parentId);\n if (!this.initialized || !this.db) return [];\n const stmt = this.db.prepare('SELECT * FROM files WHERE parentId = ? AND trashed = 0 ORDER BY name ASC');\n const rows = stmt.all(parentId);\n return rows.map((r: any) => this.mapRow(r));\n }\n\n public findByMd5(md5: string): CacheFileEntry | null {\n if (this.fallbackMemory) return this.fallbackMemory.findByMd5(md5);\n if (!this.initialized || !this.db || !md5) return null;\n const stmt = this.db.prepare('SELECT * FROM files WHERE md5Checksum = ? AND trashed = 0 LIMIT 1');\n const row = stmt.get(md5.toLowerCase());\n return row ? this.mapRow(row) : null;\n }\n\n public searchByName(query: string): CacheFileEntry[] {\n if (this.fallbackMemory) return this.fallbackMemory.searchByName(query);\n if (!this.initialized || !this.db) return [];\n const stmt = this.db.prepare('SELECT * FROM files WHERE name LIKE ? AND trashed = 0 LIMIT 50');\n const rows = stmt.all(`%${query}%`);\n return rows.map((r: any) => this.mapRow(r));\n }\n\n public upsertFile(entry: CacheFileEntry): void {\n if (this.fallbackMemory) {\n this.fallbackMemory.upsertFile(entry);\n return;\n }\n if (!this.initialized || !this.db) return;\n const stmt = this.db.prepare(`\n INSERT INTO files (id, name, mimeType, size, parentId, path, md5Checksum, trashed, modifiedTime, updatedAt)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET\n name = excluded.name,\n mimeType = excluded.mimeType,\n size = excluded.size,\n parentId = excluded.parentId,\n path = COALESCE(excluded.path, files.path),\n md5Checksum = excluded.md5Checksum,\n trashed = excluded.trashed,\n modifiedTime = excluded.modifiedTime,\n updatedAt = excluded.updatedAt\n `);\n\n stmt.run(\n entry.id,\n entry.name,\n entry.mimeType ?? null,\n entry.size ?? null,\n entry.parentId ?? null,\n entry.path ?? null,\n entry.md5Checksum ? entry.md5Checksum.toLowerCase() : null,\n entry.trashed ? 1 : 0,\n entry.modifiedTime ?? null,\n entry.updatedAt ?? Date.now()\n );\n }\n\n public upsertFiles(entries: CacheFileEntry[]): void {\n if (this.fallbackMemory) {\n this.fallbackMemory.upsertFiles(entries);\n return;\n }\n if (!this.initialized || !this.db || entries.length === 0) return;\n\n // Prepare statement once for maximum bulk performance\n const stmt = this.db.prepare(`\n INSERT INTO files (id, name, mimeType, size, parentId, path, md5Checksum, trashed, modifiedTime, updatedAt)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET\n name = excluded.name,\n mimeType = excluded.mimeType,\n size = excluded.size,\n parentId = excluded.parentId,\n path = COALESCE(excluded.path, files.path),\n md5Checksum = excluded.md5Checksum,\n trashed = excluded.trashed,\n modifiedTime = excluded.modifiedTime,\n updatedAt = excluded.updatedAt\n `);\n\n // Execute inside a single transaction\n this.db.exec('BEGIN TRANSACTION;');\n try {\n for (const entry of entries) {\n stmt.run(\n entry.id,\n entry.name,\n entry.mimeType ?? null,\n entry.size ?? null,\n entry.parentId ?? null,\n entry.path ?? null,\n entry.md5Checksum ? entry.md5Checksum.toLowerCase() : null,\n entry.trashed ? 1 : 0,\n entry.modifiedTime ?? null,\n entry.updatedAt ?? Date.now()\n );\n }\n this.db.exec('COMMIT;');\n } catch (e) {\n this.db.exec('ROLLBACK;');\n throw e;\n }\n }\n\n public deleteFile(id: string): void {\n if (this.fallbackMemory) {\n this.fallbackMemory.deleteFile(id);\n return;\n }\n if (!this.initialized || !this.db) return;\n const stmt = this.db.prepare('DELETE FROM files WHERE id = ?');\n stmt.run(id);\n }\n\n public pruneMissing(activeIds: string[]): number {\n if (this.fallbackMemory) {\n return this.fallbackMemory.pruneMissing(activeIds);\n }\n if (!this.initialized || !this.db || activeIds.length === 0) return 0;\n const idSet = new Set(activeIds);\n const rows = this.db.prepare('SELECT id FROM files').all();\n let pruned = 0;\n this.db.exec('BEGIN TRANSACTION;');\n try {\n const deleteStmt = this.db.prepare('DELETE FROM files WHERE id = ?');\n for (const row of rows) {\n if (!idSet.has(row.id)) {\n deleteStmt.run(row.id);\n pruned++;\n }\n }\n this.db.exec('COMMIT;');\n return pruned;\n } catch (e) {\n this.db.exec('ROLLBACK;');\n throw e;\n }\n }\n\n public clear(): void {\n if (this.fallbackMemory) {\n this.fallbackMemory.clear();\n return;\n }\n if (!this.initialized || !this.db) return;\n this.db.exec('DELETE FROM files; DELETE FROM meta;');\n }\n\n public getMeta(key: string): string | null {\n if (this.fallbackMemory) return this.fallbackMemory.getMeta(key);\n if (!this.initialized || !this.db) return null;\n const stmt = this.db.prepare('SELECT value FROM meta WHERE key = ?');\n const row = stmt.get(key);\n return row ? (row as any).value : null;\n }\n\n public setMeta(key: string, value: string): void {\n if (this.fallbackMemory) {\n this.fallbackMemory.setMeta(key, value);\n return;\n }\n if (!this.initialized || !this.db) return;\n const stmt = this.db.prepare(`\n INSERT INTO meta (key, value) VALUES (?, ?)\n ON CONFLICT(key) DO UPDATE SET value = excluded.value\n `);\n stmt.run(key, value);\n }\n\n public getStats(): CacheStats {\n if (this.fallbackMemory) return this.fallbackMemory.getStats();\n if (!this.initialized || !this.db) {\n return {\n fileCount: 0,\n folderCount: 0,\n totalSizeBytes: 0,\n lastSyncTime: null,\n databasePath: this.dbPath,\n };\n }\n\n const fileCountRow: any = this.db.prepare(\n \"SELECT COUNT(*) as count FROM files WHERE mimeType != 'application/vnd.google-apps.folder' AND trashed = 0\"\n ).get();\n\n const folderCountRow: any = this.db.prepare(\n \"SELECT COUNT(*) as count FROM files WHERE mimeType = 'application/vnd.google-apps.folder' AND trashed = 0\"\n ).get();\n\n const totalSizeRow: any = this.db.prepare(\n 'SELECT SUM(size) as total FROM files WHERE trashed = 0'\n ).get();\n\n const lastSync = this.getMeta('last_sync_timestamp');\n\n return {\n fileCount: fileCountRow?.count || 0,\n folderCount: folderCountRow?.count || 0,\n totalSizeBytes: totalSizeRow?.total || 0,\n lastSyncTime: lastSync,\n databasePath: this.dbPath,\n };\n }\n\n public close(): void {\n if (this.fallbackMemory) {\n this.fallbackMemory.close();\n this.fallbackMemory = undefined;\n }\n if (this.db) {\n try {\n this.db.close();\n } catch {\n // ignore\n }\n this.initialized = false;\n this.db = null;\n }\n }\n\n private mapRow(row: any): CacheFileEntry {\n return {\n id: row.id,\n name: row.name,\n mimeType: row.mimeType,\n size: row.size != null ? Number(row.size) : undefined,\n parentId: row.parentId || undefined,\n path: row.path || undefined,\n md5Checksum: row.md5Checksum || undefined,\n trashed: row.trashed === 1,\n modifiedTime: row.modifiedTime || undefined,\n updatedAt: row.updatedAt != null ? Number(row.updatedAt) : undefined,\n };\n }\n}\n\n/**\n * Fallback in-memory cache if SQLite is unavailable\n */\nexport class MemoryMetadataCache implements IMetadataCache {\n private files = new Map<string, CacheFileEntry>();\n private meta = new Map<string, string>();\n\n public init(): void {}\n public getById(id: string): CacheFileEntry | null {\n return this.files.get(id) || null;\n }\n public getByPath(normalizedPath: string): CacheFileEntry | null {\n for (const f of this.files.values()) {\n if (f.path === normalizedPath && !f.trashed) return f;\n }\n return null;\n }\n public getChildren(parentId: string): CacheFileEntry[] {\n const list: CacheFileEntry[] = [];\n for (const f of this.files.values()) {\n if (f.parentId === parentId && !f.trashed) list.push(f);\n }\n return list;\n }\n public findByMd5(md5: string): CacheFileEntry | null {\n const target = md5.toLowerCase();\n for (const f of this.files.values()) {\n if (f.md5Checksum?.toLowerCase() === target && !f.trashed) return f;\n }\n return null;\n }\n public searchByName(query: string): CacheFileEntry[] {\n const q = query.toLowerCase();\n const list: CacheFileEntry[] = [];\n for (const f of this.files.values()) {\n if (f.name.toLowerCase().includes(q) && !f.trashed) list.push(f);\n }\n return list;\n }\n public upsertFile(entry: CacheFileEntry): void {\n this.files.set(entry.id, { ...entry, updatedAt: Date.now() });\n }\n public upsertFiles(entries: CacheFileEntry[]): void {\n for (const e of entries) this.upsertFile(e);\n }\n public deleteFile(id: string): void {\n this.files.delete(id);\n }\n public pruneMissing(activeIds: string[]): number {\n const idSet = new Set(activeIds);\n let pruned = 0;\n for (const id of Array.from(this.files.keys())) {\n if (!idSet.has(id)) {\n this.files.delete(id);\n pruned++;\n }\n }\n return pruned;\n }\n public clear(): void {\n this.files.clear();\n this.meta.clear();\n }\n public getMeta(key: string): string | null {\n return this.meta.get(key) || null;\n }\n public setMeta(key: string, value: string): void {\n this.meta.set(key, value);\n }\n public getStats(): CacheStats {\n let fileCount = 0;\n let folderCount = 0;\n let totalSizeBytes = 0;\n for (const f of this.files.values()) {\n if (f.trashed) continue;\n if (f.mimeType === 'application/vnd.google-apps.folder') folderCount++;\n else {\n fileCount++;\n totalSizeBytes += f.size || 0;\n }\n }\n return {\n fileCount,\n folderCount,\n totalSizeBytes,\n lastSyncTime: this.meta.get('last_sync_timestamp') || null,\n databasePath: ':memory:',\n };\n }\n public close(): void {\n this.clear();\n }\n}\n\n","import type { drive_v3 } from '@googleapis/drive';\nimport type { OAuth2Client } from 'google-auth-library';\n\nexport type DriveApiFile = drive_v3.Schema$File;\nexport type DriveApiFileList = drive_v3.Schema$FileList;\nexport type DriveApiPermission = drive_v3.Schema$Permission;\n\n/**\n * Authentication configuration options for DriveKit\n */\nexport interface DriveKitAuthConfig {\n /** Path to Google Service Account JSON file */\n keyFilePath?: string;\n /** Parsed Service Account JSON object */\n credentials?: {\n client_email?: string;\n private_key?: string;\n project_id?: string;\n [key: string]: any;\n };\n /** Pre-existing OAuth2Client or access token */\n oauth2Client?: OAuth2Client;\n /** Direct bearer access token */\n accessToken?: string;\n /** OAuth2 Client Credentials for OAuth flow */\n oauth?: {\n clientId: string;\n clientSecret: string;\n redirectUri?: string;\n refreshToken?: string;\n };\n /** Scopes (defaults to full drive scope: ['https://www.googleapis.com/auth/drive']) */\n scopes?: string[];\n}\n\n/**\n * Global configuration options for DriveKit instance\n */\nexport interface DriveKitOptions {\n auth?: DriveKitAuthConfig;\n /** Root folder ID to restrict operations (defaults to 'root') */\n rootFolderId?: string;\n /** Default chunk size in bytes for resumable uploads (default: 8MB) */\n uploadChunkSize?: number;\n /** Maximum parallel operations for batch/sync (default: 4) */\n concurrency?: number;\n /** Cache folder paths to reduce API queries (default: true) */\n enablePathCache?: boolean;\n /** Cache TTL in milliseconds (default: 5 minutes) */\n pathCacheTTL?: number;\n /** Enable persistent SQLite metadata cache for 0ms path resolution across sessions (default: true) */\n enablePersistentCache?: boolean;\n /** Custom path to the SQLite cache database file (default: ~/.drivekit/cache.db) */\n cacheDatabasePath?: string;\n /** Number of retry attempts for 429/5xx errors (default: 5) */\n maxRetries?: number;\n /** Base delay for exponential backoff in ms (default: 1000) */\n retryBaseDelayMs?: number;\n}\n\n/**\n * Upload progress event payload\n */\nexport interface UploadProgress {\n /** Bytes transferred so far */\n bytesSent: number;\n /** Total bytes of the file */\n totalBytes: number;\n /** Percentage completed (0 - 100) */\n percentage: number;\n /** Current transfer speed in bytes per second */\n bytesPerSecond: number;\n /** Formatted speed (e.g. \"4.2 MB/s\") */\n speedFormatted: string;\n /** Estimated time remaining in seconds */\n estimatedTimeRemainingSeconds: number;\n /** Chunk index currently sent */\n chunkIndex: number;\n /** Total chunks */\n totalChunks: number;\n}\n\n/**\n * Download progress event payload\n */\nexport interface DownloadProgress {\n bytesRead: number;\n totalBytes?: number;\n percentage?: number;\n bytesPerSecond: number;\n speedFormatted: string;\n}\n\n/**\n * File upload parameters\n */\nexport interface UploadOptions {\n /** Local file path, Buffer, or Readable stream */\n source: string | Buffer | NodeJS.ReadableStream;\n /** Target file name on Google Drive */\n name?: string;\n /** Target parent folder ID or virtual path (e.g. '/Backups/2026') */\n parent?: string;\n /** MIME type (inferred automatically if omitted) */\n mimeType?: string;\n /** File description */\n description?: string;\n /** Custom chunk size for this specific upload */\n chunkSize?: number;\n /** Progress callback */\n onProgress?: (progress: UploadProgress) => void;\n /** Whether to overwrite file with same name in destination */\n overwrite?: boolean;\n /** Whether to enable instant upload deduplication by file MD5 hash */\n deduplicate?: boolean;\n /** Alias for target file name */\n filename?: string;\n /** Custom properties / metadata */\n properties?: Record<string, string>;\n appProperties?: Record<string, string>;\n /** Optional AbortSignal for instant operation cancellation */\n signal?: AbortSignal;\n}\n\n/**\n * Writable stream for direct uploads into Google Drive with completion promise\n */\nexport interface DriveWriteStream extends NodeJS.WritableStream {\n /** Resolves with the uploaded file metadata upon completion, or rejects on upload failure */\n done: Promise<DriveApiFile>;\n}\n\n/**\n * File download parameters\n */\nexport interface DownloadOptions {\n /** Destination local file path (if saving to disk) */\n destination?: string;\n /** Progress callback */\n onProgress?: (progress: DownloadProgress) => void;\n /** Export MIME type for Google Workspace documents */\n exportMimeType?: string;\n /** Optional pre-resolved file metadata to skip extra Google API roundtrip */\n metadata?: { name?: string; mimeType?: string; size?: number };\n /** Optional AbortSignal for instant operation cancellation */\n signal?: AbortSignal;\n}\n\n/**\n * Writable stream for direct uploads into Google Drive with completion promise\n */\nexport interface DriveWriteStream extends NodeJS.WritableStream {\n /** Resolves with the uploaded file metadata upon completion, or rejects on upload failure */\n done: Promise<DriveApiFile>;\n}\n\n/**\n * Permission role types\n */\nexport type PermissionRole = 'owner' | 'organizer' | 'fileOrganizer' | 'writer' | 'commenter' | 'reader';\n\n/**\n * Permission grantee types\n */\nexport type PermissionType = 'user' | 'group' | 'domain' | 'anyone';\n\n/**\n * Share file options\n */\nexport interface ShareOptions {\n role?: PermissionRole;\n type?: PermissionType;\n emailAddress?: string;\n domain?: string;\n sendNotificationEmail?: boolean;\n emailMessage?: string;\n transferOwnership?: boolean;\n}\n\n/**\n * Directory sync summary\n */\nexport interface SyncResult {\n uploaded: { localPath: string; fileId: string; name: string }[];\n skipped: { localPath: string; name: string; reason: string }[];\n failed: { localPath: string; error: Error }[];\n totalBytes: number;\n durationMs: number;\n}\n\n","import readline from 'node:readline';\nimport chalk from 'chalk';\nimport type { DriveKit } from '../core/client.js';\nimport type { DriveApiFile } from '../types.js';\nimport { formatBytes } from '../utils/format.js';\n\n/**\n * Creates an OSC 8 clickable hyperlink in supported modern terminals (macOS Terminal, iTerm2, VS Code, etc.)\n */\nexport function terminalLink(text: string, url: string): string {\n // OSC 8 ; params ; url ST text OSC 8 ;; ST\n return `\\u001B]8;;${url}\\u0007${text}\\u001B]8;;\\u0007`;\n}\n\n/**\n * Renders a visually stunning, colored file table with clickable links\n */\nexport function renderFileRow(item: DriveApiFile, index?: number): string {\n const isDir = item.mimeType === 'application/vnd.google-apps.folder';\n const icon = isDir ? '📁' : getFileIcon(item.mimeType || '');\n const prefix = index !== undefined ? `${chalk.dim((index + 1).toString().padStart(2, ' ') + '.')} ` : '';\n\n let nameFormatted = isDir ? chalk.bold.blue(item.name || 'untitled') : chalk.white(item.name || 'untitled');\n if (item.webViewLink) {\n nameFormatted = terminalLink(nameFormatted, item.webViewLink);\n }\n\n const sizeFormatted = item.size\n ? chalk.dim(`[${formatBytes(parseInt(item.size, 10)).padStart(9, ' ')}]`)\n : chalk.dim(isDir ? '[ FOLDER ]' : '[ DOC ]');\n\n const idFormatted = chalk.dim(`ID: ${item.id}`);\n\n return `${prefix}${icon} ${nameFormatted.padEnd(45)} ${sizeFormatted} ${idFormatted}`;\n}\n\nexport function getFileIcon(mimeType: string): string {\n if (mimeType.includes('pdf')) return '📕';\n if (mimeType.includes('image')) return '🖼️ ';\n if (mimeType.includes('video')) return '🎬';\n if (mimeType.includes('audio')) return '🎵';\n if (mimeType.includes('zip') || mimeType.includes('compressed') || mimeType.includes('tar')) return '📦';\n if (mimeType.includes('spreadsheet') || mimeType.includes('excel')) return '📊';\n if (mimeType.includes('document') || mimeType.includes('word')) return '📝';\n if (mimeType.includes('presentation')) return '📽️ ';\n if (mimeType.includes('json') || mimeType.includes('javascript') || mimeType.includes('typescript')) return '⚙️ ';\n return '📄';\n}\n\n/**\n * Interactive Keyboard-driven Google Drive File Explorer (TUI)\n */\nexport async function runInteractiveExplorer(client: DriveKit, initialFolder = '/'): Promise<void> {\n let currentFolder = initialFolder;\n let items: DriveApiFile[] = [];\n let selectedIndex = 0;\n let history: string[] = [];\n\n const refreshItems = async () => {\n items = await client.ls(currentFolder);\n selectedIndex = Math.min(selectedIndex, Math.max(0, items.length - 1));\n };\n\n await refreshItems();\n\n if (!process.stdin.isTTY) {\n console.log(chalk.yellow('Interactive explorer requires a TTY terminal. Listing items instead:'));\n for (const item of items) {\n console.log(renderFileRow(item));\n }\n return;\n }\n\n readline.emitKeypressEvents(process.stdin);\n process.stdin.setRawMode(true);\n\n const renderScreen = () => {\n console.clear();\n console.log(chalk.bold.cyan('╔═══════════════════════════════════════════════════════════════════════════════════╗'));\n console.log(chalk.bold.cyan('║') + chalk.bold.yellow(' ⚡ DriveKit Interactive Terminal Explorer ') + chalk.bold.cyan('║'));\n console.log(chalk.bold.cyan('╠═══════════════════════════════════════════════════════════════════════════════════╣'));\n console.log(chalk.bold.cyan('║') + ` 📂 Path: ${chalk.bold.green(currentFolder.padEnd(72))} ` + chalk.bold.cyan('║'));\n console.log(chalk.bold.cyan('╚═══════════════════════════════════════════════════════════════════════════════════╝'));\n console.log(chalk.dim(' [↑/↓] Navigate • [Enter] Open Folder • [B] Back • [S] Share • [Q] Exit\\n'));\n\n if (items.length === 0) {\n console.log(chalk.dim(' (This folder is empty)\\n'));\n return;\n }\n\n const pageSize = 12;\n const startIdx = Math.max(0, Math.min(selectedIndex - Math.floor(pageSize / 2), items.length - pageSize));\n const endIdx = Math.min(items.length, startIdx + pageSize);\n\n for (let i = startIdx; i < endIdx; i++) {\n const isSelected = i === selectedIndex;\n const cursor = isSelected ? chalk.bold.cyan(' ► ') : ' ';\n const row = renderFileRow(items[i]);\n if (isSelected) {\n console.log(chalk.bgHex('#1e293b')(cursor + row));\n } else {\n console.log(cursor + row);\n }\n }\n\n console.log(chalk.dim(`\\n Item ${selectedIndex + 1} of ${items.length}`));\n };\n\n renderScreen();\n\n return new Promise((resolve) => {\n const onKeypress = async (str: string, key: any) => {\n if (key.ctrl && key.name === 'c') {\n cleanup();\n process.exit(0);\n }\n\n if (key.name === 'q' || (key.name === 'escape' && history.length === 0)) {\n cleanup();\n resolve();\n return;\n }\n\n if (key.name === 'up') {\n selectedIndex = selectedIndex > 0 ? selectedIndex - 1 : items.length - 1;\n renderScreen();\n } else if (key.name === 'down') {\n selectedIndex = selectedIndex < items.length - 1 ? selectedIndex + 1 : 0;\n renderScreen();\n } else if (key.name === 'return') {\n const item = items[selectedIndex];\n if (item && item.mimeType === 'application/vnd.google-apps.folder') {\n history.push(currentFolder);\n currentFolder = currentFolder === '/' ? `/${item.name}` : `${currentFolder}/${item.name}`;\n selectedIndex = 0;\n await refreshItems();\n renderScreen();\n } else if (item && item.webViewLink) {\n // Open link in browser\n const { exec } = await import('node:child_process');\n const openCmd = process.platform === 'darwin' ? `open \"${item.webViewLink}\"` : `xdg-open \"${item.webViewLink}\"`;\n exec(openCmd);\n renderScreen();\n }\n } else if (key.name === 'b' || key.name === 'backspace') {\n if (history.length > 0) {\n currentFolder = history.pop()!;\n selectedIndex = 0;\n await refreshItems();\n renderScreen();\n }\n } else if (str === 's' || str === 'S') {\n const item = items[selectedIndex];\n if (item && item.id) {\n process.stdin.pause();\n console.log(`\\n\\n${chalk.cyan('🔗 Getting shareable link for:')} ${chalk.bold(item.name)}...`);\n try {\n const links = await client.sharePublic(item.id);\n console.log(`Preview URL: ${chalk.underline(links.previewLink)}`);\n console.log(`Direct Download URL: ${chalk.underline(links.directDownloadLink)}`);\n console.log(chalk.dim('\\nPress any key to return to explorer...'));\n process.stdin.resume();\n process.stdin.once('data', () => {\n renderScreen();\n });\n } catch (err: any) {\n console.error(chalk.red(`Failed to share: ${err.message}`));\n setTimeout(renderScreen, 2000);\n }\n }\n }\n };\n\n const cleanup = () => {\n process.stdin.removeListener('keypress', onKeypress);\n if (process.stdin.setRawMode) {\n process.stdin.setRawMode(false);\n }\n process.stdin.pause();\n console.clear();\n console.log(chalk.green('👋 Exited DriveKit explorer.'));\n };\n\n process.stdin.on('keypress', onKeypress);\n });\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAAA;AAkBO,SAAS,UAAU,QAAwB;AAChD,SAAO,OACJ,QAAQ,MAAM,OAAO,EACrB,QAAQ,MAAM,MAAM,EACpB,QAAQ,MAAM,MAAM,EACpB,QAAQ,MAAM,QAAQ,EACtB,QAAQ,MAAM,QAAQ;AAC3B;AAMA,eAAsB,kBACpBA,QACA,UAA+B,CAAC,GAC2C;AAC3E,QAAM,OAAO,QAAQ,QAAQ;AAC7B,QAAM,OAAO,QAAQ,QAAQ;AAE7B,QAAMA,OAAM,KAAK;AAEjB,QAAM,SAAS,kBAAAC,QAAK,aAAa,OAAO,KAAK,QAAQ;AACnD,QAAI;AAEF,UAAI,QAAQ,MAAM,YAAY,QAAQ,MAAM,UAAU;AACpD,cAAM,aAAa,IAAI,QAAQ,eAAe;AAC9C,YAAI,CAAC,cAAc,CAAC,WAAW,WAAW,QAAQ,GAAG;AACnD,c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;ArBpKA,eAAsB,YAAY,SAA8C;AAC9E,QAAM,WAAW,IAAI,SAAS,OAAO;AACrC,QAAM,SAAS,KAAK;AACpB,SAAO;AACT;AAGA,IAAO,gBAAQ;","names":["drive","http","url","path","import_node_http","import_node_path","import_node_fs","import_node_path","import_drive","https","http","googleAuth","fs","mime","drive","path","import_node_fs","drive","fs","path","import_node_fs","import_node_path","import_node_stream","drive","fs","path","drive","mime","drive","drive","import_node_fs","import_node_path","crypto","fs","drive","path","import_node_http","import_drive","googleAuth","http","drive","import_node_path","path","import_node_path","import_node_fs","path","os","fs","path","fs","startWebDAVServer","url","chalk","readline","exec"]}