ytdlp-nodejs
Version:
A TypeScript wrapper for the yt-dlp executable
4 lines (3 loc) • 25.1 kB
JavaScript
import{fileURLToPath as ee}from"url";import re from"path";var te=()=>ee(import.meta.url),se=()=>re.dirname(te()),c=se();import{spawn as S,spawnSync as Q}from"child_process";import*as b from"fs";import*as I from"path";import*as X from"os";import{Blob as he}from"buffer";function C(e){let r=[];if(e.printHelp&&r.push("--help"),e.printVersion&&r.push("--version"),e.update&&r.push("--update"),e.noUpdate&&r.push("--no-update"),e.updateTo&&r.push("--update-to",e.updateTo),e.ignoreErrors&&r.push("--ignore-errors"),e.noAbortOnError&&r.push("--no-abort-on-error"),e.abortOnError&&r.push("--abort-on-error"),e.dumpUserAgent&&r.push("--dump-user-agent"),e.listExtractors&&r.push("--list-extractors"),e.extractorDescriptions&&r.push("--extractor-descriptions"),e.useExtractors&&e.useExtractors.length>0&&r.push("--use-extractors",e.useExtractors.join(",")),e.defaultSearch&&r.push("--default-search",e.defaultSearch),e.ignoreConfig&&r.push("--ignore-config"),e.noConfigLocations&&r.push("--no-config-location"),e.configLocations&&e.configLocations.length>0&&r.push("--config-locations",...e.configLocations),e.pluginDirs&&e.pluginDirs.length>0)for(let t of e.pluginDirs)r.push("--plugin-dirs",t);if(e.noPluginDirs&&r.push("--no-plugin-dirs"),e.flatPlaylist&&r.push("--flat-playlist"),e.noFlatPlaylist&&r.push("--no-flat-playlist"),e.liveFromStart&&r.push("--live-from-start"),e.noLiveFromStart&&r.push("--no-live-from-start"),e.waitForVideo&&r.push("--wait-for-video",e.waitForVideo.toString()),e.noWaitForVideo&&r.push("--no-wait-for-video"),e.markWatched&&r.push("--mark-watched"),e.noMarkWatched&&r.push("--no-mark-watched"),e.color&&r.push("--color",e.color),e.compatOptions&&e.compatOptions.length>0&&r.push("--compat-options",e.compatOptions.join(",")),e.aliases&&e.aliases.length>0&&r.push("--alias",...e.aliases),e.proxy&&r.push("--proxy",e.proxy),e.socketTimeout&&r.push("--socket-timeout",e.socketTimeout.toString()),e.sourceAddress&&r.push("--source-address",e.sourceAddress),e.impersonate&&e.impersonate.length>0&&r.push("--impersonate",e.impersonate.join(",")),e.listImpersonateTargets&&r.push("--list-impersonate-targets"),e.forceIpv4&&r.push("--force-ipv4"),e.forceIpv6&&r.push("--force-ipv6"),e.enableFileUrls&&r.push("--enable-file-urls"),e.geoVerificationProxy&&r.push("--geo-verification-proxy",e.geoVerificationProxy),e.xff&&r.push("--xff",e.xff),e.playlistItems&&r.push("--playlist-items",e.playlistItems),e.minFilesize&&r.push("--min-filesize",e.minFilesize),e.maxFilesize&&r.push("--max-filesize",e.maxFilesize),e.date&&r.push("--date",e.date),e.dateBefore&&r.push("--datebefore",e.dateBefore),e.dateAfter&&r.push("--dateafter",e.dateAfter),e.matchFilter&&r.push("--match-filter",e.matchFilter),e.noMatchFilters&&r.push("--no-match-filters"),e.breakMatchFilters&&r.push("--break-match-filters",e.breakMatchFilters),e.noBreakMatchFilters&&r.push("--no-break-match-filters"),e.noPlaylist&&r.push("--no-playlist"),e.yesPlaylist&&r.push("--yes-playlist"),e.ageLimit&&r.push("--age-limit",e.ageLimit.toString()),e.downloadArchive&&r.push("--download-archive",e.downloadArchive),e.noDownloadArchive&&r.push("--no-download-archive"),e.maxDownloads&&r.push("--max-downloads",e.maxDownloads.toString()),e.breakOnExisting&&r.push("--break-on-existing"),e.noBreakOnExisting&&r.push("--no-break-on-existing"),e.breakPerInput&&r.push("--break-per-input"),e.noBreakPerInput&&r.push("--break-per-input"),e.skipPlaylistAfterErrors&&r.push("--skip-playlist-after-errors",e.skipPlaylistAfterErrors.toString()),e.concurrentFragments&&r.push("--concurrent-fragments",e.concurrentFragments.toString()),e.limitRate&&r.push("--limit-rate",e.limitRate),e.throttledRate&&r.push("--throttled-rate",e.throttledRate),e.retries&&r.push("--retries",e.retries.toString()),e.fileAccessRetries&&r.push("--file-access-retries",e.fileAccessRetries.toString()),e.fragmentRetries&&r.push("--fragment-retries",e.fragmentRetries.toString()),e.retrySleep&&r.push("--retry-sleep",e.retrySleep.toString()),e.skipUnavailableFragments&&r.push("--skip-unavailable-fragments"),e.abortOnUnavailableFragment&&r.push("--abort-on-unavailable-fragment"),e.keepFragments&&r.push("--keep-fragments"),e.noKeepFragments&&r.push("--no-keep-fragments"),e.bufferSize&&r.push("--buffer-size",e.bufferSize),e.resizeBuffer&&r.push("--resize-buffer"),e.noResizeBuffer&&r.push("--no-resize-buffer"),e.httpChunkSize&&r.push("--http-chunk-size",e.httpChunkSize),e.playlistRandom&&r.push("--playlist-random"),e.lazyPlaylist&&r.push("--lazy-playlist"),e.noLazyPlaylist&&r.push("--no-lazy-playlist"),e.xattrSetFilesize&&r.push("--xattr-set-filesize"),e.hlsUseMpegts&&r.push("--hls-use-mpegts"),e.noHlsUseMpegts&&r.push("--no-hls-use-mpegts"),e.downloadSections&&r.push("--download-sections",e.downloadSections.toString()),e.downloader&&r.push("--downloader",e.downloader),e.downloaderArgs&&r.push("--downloader-args",e.downloaderArgs),e.batchFile&&r.push("--batch-file",e.batchFile),e.noBatchFile&&r.push("--no-batch-file"),e.paths)if(typeof e.paths=="string")r.push("--paths",e.paths);else for(let[t,s]of Object.entries(e.paths))r.push("--paths",`${t}:${s}`);if(e.output&&r.push("-o",e.output),e.outputNaPlaceholder&&r.push("--output-na-placeholder",e.outputNaPlaceholder),e.restrictFilenames&&r.push("--restrict-filenames"),e.noRestrictFilenames&&r.push("--no-restrict-filenames"),e.windowsFilenames&&r.push("--windows-filenames"),e.noWindowsFilenames&&r.push("--no-windows-filenames"),e.trimFileNames&&r.push("--trim-file-names",e.trimFileNames.toString()),e.noOverwrites&&r.push("--no-overwrites"),e.forceOverwrites&&r.push("--force-overwrites"),e.noForceOverwrites&&r.push("--no-force-overwrites"),e.continue&&r.push("--continue"),e.noContinue&&r.push("--no-continue"),e.part&&r.push("--part"),e.noPart&&r.push("--no-part"),e.mtime&&r.push("--mtime"),e.noMtime&&r.push("--no-mtime"),e.writeDescription&&r.push("--write-description"),e.noWriteDescription&&r.push("--no-write-description"),e.writeInfoJson&&r.push("--write-info-json"),e.noWriteInfoJson&&r.push("--no-write-info-json"),e.writePlaylistMetafiles&&r.push("--write-playlist-metafiles"),e.noWritePlaylistMetafiles&&r.push("--no-write-playlist-metafiles"),e.cleanInfoJson&&r.push("--clean-info-json"),e.noCleanInfoJson&&r.push("--no-clean-info-json"),e.writeComments&&r.push("--write-comments"),e.noWriteComments&&r.push("--no-write-comments"),e.loadInfoJson&&r.push("--load-info-json",e.loadInfoJson.toString()),e.cookies&&r.push("--cookies",e.cookies),e.noCookies&&r.push("--no-cookies"),e.cookiesFromBrowser&&r.push("--cookies-from-browser",e.cookiesFromBrowser),e.noCookiesFromBrowser&&r.push("--no-cookies-from-browser"),e.cacheDir&&r.push("--cache-dir",e.cacheDir),e.noCacheDir&&r.push("--no-cache-dir"),e.rmCacheDir&&r.push("--rm-cache-dir"),e.writeThumbnail&&r.push("--write-thumbnail"),e.noWriteThumbnails&&r.push("--no-write-thumbnails"),e.writeAllThumbnails&&r.push("--write-all-thumbnails"),e.listThumbnails&&r.push("--list-thumbnails"),e.writeLink&&r.push("--write-link"),e.writeUrlLink&&r.push("--write-url-link"),e.writeWeblocLink&&r.push("--write-webloc-link"),e.writeDesktopLink&&r.push("--write-desktop-link"),e.quiet&&r.push("--quiet"),e.noQuiet&&r.push("--no-quiet"),e.noWarnings&&r.push("--no-warnings"),e.simulate&&r.push("--simulate"),e.noSimulate&&r.push("--no-simulate"),e.ignoreNoFormatsError&&r.push("--ignore-no-formats-error"),e.noIgnoreNoFormatsError&&r.push("--no-ignore-no-formats-error"),e.skipDownload&&r.push("--skip-download"),e.print&&r.push("--print",e.print),e.printToFile&&r.push("--print-to-file",e.printToFile),e.dumpJson&&r.push("--dump-json"),e.dumpSingleJson&&r.push("--dump-single-json"),e.forceWriteArchive&&r.push("--force-write-archive"),e.newline&&r.push("--newline"),e.noProgress&&r.push("--no-progress"),e.progress&&r.push("--progress"),e.consoleTitle&&r.push("--console-title"),e.progressTemplate&&r.push("--progress-template",e.progressTemplate),e.progressDelta&&r.push("--progress-delta",e.progressDelta.toString()),e.verbose&&r.push("--verbose"),e.dumpPages&&r.push("--dump-pages"),e.writePages&&r.push("--write-pages"),e.printTraffic&&r.push("--print-traffic"),e.encoding&&r.push("--encoding",e.encoding),e.legacyServerConnect&&r.push("--legacy-server-connect"),e.noCheckCertificates&&r.push("--no-check-certificates"),e.preferInsecure&&r.push("--prefer-insecure"),e.addHeaders)for(let[t,s]of Object.entries(e.addHeaders))r.push("--add-headers",`${t}:${s}`);if(e.bidiWorkaround&&r.push("--bidi-workaround"),e.sleepRequests&&r.push("--sleep-requests",e.sleepRequests.toString()),e.sleepInterval&&r.push("--sleep-interval",e.sleepInterval.toString()),e.maxSleepInterval&&r.push("--max-sleep-interval",e.maxSleepInterval.toString()),e.sleepSubtitles&&r.push("--sleep-subtitles",e.sleepSubtitles.toString()),e.format&&r.push("-f",e.format),e.formatSort&&e.formatSort.length>0&&r.push("--format-sort",e.formatSort.join(",")),e.formatSortForce&&r.push("--format-sort-force"),e.noFormatSortForce&&r.push("--no-format-sort-force"),e.videoMultiStreams&&r.push("--video-multistreams"),e.noVideoMultiStreams&&r.push("--no-video-multistreams"),e.audioMultiStreams&&r.push("--audio-multistreams"),e.noAudioMultiStreams&&r.push("--no-audio-multistreams"),e.preferFreeFormats&&r.push("--prefer-free-formats"),e.noPreferFreeFormats&&r.push("--no-prefer-free-formats"),e.checkFormats&&r.push("--check-formats"),e.checkAllFormats&&r.push("--check-all-formats"),e.noCheckFormats&&r.push("--no-check-formats"),e.listFormats&&r.push("--list-formats"),e.mergeOutputFormat&&r.push("--merge-output-format",e.mergeOutputFormat),e.writeSubs&&r.push("--write-subs"),e.noWriteSubs&&r.push("--no-write-subs"),e.writeAutoSubs&&r.push("--write-auto-subs"),e.writeAllSubs&&r.push("--all-subs"),e.listSubs&&r.push("--list-subs"),e.subFormat&&r.push("--sub-format",e.subFormat),e.subLangs&&e.subLangs.length>0&&r.push("--sub-langs",e.subLangs.join(",")),e.username&&r.push("--username",e.username),e.password&&r.push("--password",e.password),e.twoFactor&&r.push("--twofactor",e.twoFactor),e.netrc&&r.push("--netrc"),e.videoPassword&&r.push("--video-password",e.videoPassword),e.apMso&&r.push("--ap-mso",e.apMso),e.apUsername&&r.push("--ap-username",e.apUsername),e.apPassword&&r.push("--ap-password",e.apPassword),e.netrcLocation&&r.push("--netrc-location",e.netrcLocation),e.netrcCmd&&r.push("--netrc-cmd",e.netrcCmd),e.apListMso&&r.push("--ap-list-mso"),e.clientCertificate&&r.push("--client-certificate",e.clientCertificate),e.clientCertificateKey&&r.push("--client-certificate-key",e.clientCertificateKey),e.clientCertificatePassword&&r.push("--client-certificate-password",e.clientCertificatePassword),e.extractorRetries!==void 0&&r.push("--extractor-retries",e.extractorRetries.toString()),e.allowDynamicMpd&&r.push("--allow-dynamic-mpd"),e.ignoreDynamicMpd&&r.push("--ignore-dynamic-mpd"),e.hlsSplitDiscontinuity&&r.push("--hls-split-discontinuity"),e.noHlsSplitDiscontinuity&&r.push("--no-hls-split-discontinuity"),e.extractorArgs)for(let[t,s]of Object.entries(e.extractorArgs))r.push("--extractor-args",`${t}:${s.join(" ")}`);if(e.playlistStart!==void 0&&r.push("--playlist-start",e.playlistStart.toString()),e.playlistEnd!==void 0&&r.push("--playlist-end",e.playlistEnd.toString()),e.matchTitle&&r.push("--match-title",e.matchTitle),e.rejectTitle&&r.push("--reject-title",e.rejectTitle),e.includeAds&&r.push("--include-ads"),e.breakOnReject&&r.push("--break-on-reject"),e.noDownload&&r.push("--no-download"),e.playlistReverse&&r.push("--playlist-reverse"),e.geoBypass&&r.push("--geo-bypass"),e.geoBypassCountry&&r.push("--geo-bypass-country",e.geoBypassCountry),e.geoBypassIpBlock&&r.push("--geo-bypass-ip-block",e.geoBypassIpBlock),e.convertThumbnails&&r.push("--convert-thumbnails",e.convertThumbnails),e.writeLink&&r.push("--write-link"),e.writeUrlLink&&r.push("--write-url-link"),e.writeWeblocLink&&r.push("--write-webloc-link"),e.writeLnkLink&&r.push("--write-lnk-link"),e.userAgent&&r.push("--user-agent",e.userAgent),e.extractAudio&&r.push("--extract-audio"),e.audioFormat&&r.push("--audio-format",e.audioFormat),e.audioQuality&&r.push("--audio-quality",e.audioQuality),e.remuxVideo&&r.push("--remux-video",e.remuxVideo),e.recodeVideo&&r.push("--recode-video",e.recodeVideo),e.postprocessorArgs)for(let[t,s]of Object.entries(e.postprocessorArgs))r.push("--postprocessor-args",`${t}:${s.join(" ")}`);if(e.keepVideo&&r.push("--keep-video"),e.noKeepVideo&&r.push("--no-keep-video"),e.postOverwrites&&r.push("--post-overwrites"),e.noPostOverwrites&&r.push("--no-post-overwrites"),e.embedSubs&&r.push("--embed-subs"),e.noEmbedSubs&&r.push("--no-embed-subs"),e.embedThumbnail&&r.push("--embed-thumbnail"),e.noEmbedThumbnail&&r.push("--no-embed-thumbnail"),e.embedMetadata&&r.push("--embed-metadata"),e.noEmbedMetadata&&r.push("--no-embed-metadata"),e.embedChapters&&r.push("--embed-chapters"),e.noEmbedChapters&&r.push("--no-embed-chapters"),e.embedInfoJson&&r.push("--embed-info-json"),e.noEmbedInfoJson&&r.push("--no-embed-info-json"),e.parseMetadata)for(let[t,s]of Object.entries(e.parseMetadata))r.push("--parse-metadata",`${t}:${s}`);if(e.replaceInMetadata)for(let[t,[s,i]]of Object.entries(e.replaceInMetadata))r.push("--replace-in-metadata",`${t} ${s} ${i}`);if(e.xattrs&&r.push("--xattrs"),e.concatPlaylist&&r.push("--concat-playlist",e.concatPlaylist),e.fixup&&r.push("--fixup",e.fixup),e.ffmpegLocation&&r.push("--ffmpeg-location",e.ffmpegLocation),e.exec&&r.push("--exec",e.exec),e.noExec&&r.push("--no-exec"),e.convertSubs&&r.push("--convert-subs",e.convertSubs),e.convertThumbnails&&r.push("--convert-thumbnails",e.convertThumbnails),e.splitChapters&&r.push("--split-chapters"),e.noSplitChapters&&r.push("--no-split-chapters"),e.removeChapters&&r.push("--remove-chapters",e.removeChapters),e.noRemoveChapters&&r.push("--no-remove-chapters"),e.forceKeyframesAtCuts&&r.push("--force-keyframes-at-cuts"),e.noForceKeyframesAtCuts&&r.push("--no-force-keyframes-at-cuts"),e.usePostProcessor&&e.usePostProcessor.length>0)for(let t of e.usePostProcessor)r.push("--use-postprocessor",t);return e.sponsorblockMark&&e.sponsorblockMark.length>0&&r.push("--sponsorblock-mark",e.sponsorblockMark.join(",")),e.sponsorblockRemove&&e.sponsorblockRemove.length>0&&r.push("--sponsorblock-remove",e.sponsorblockRemove.join(",")),e.sponsorblockChapterTitle&&r.push("--sponsorblock-chapter-title",e.sponsorblockChapterTitle),e.noSponsorblock&&r.push("--no-sponsorblock"),e.sponsorblockApi&&r.push("--sponsorblock-api",e.sponsorblockApi),e.additionalOptions&&e.additionalOptions.length>0&&r.push(...e.additionalOptions),r}function N(e){let r=[],t=e.split(`
`).slice(1);for(let s of t){let i=s.match(/(\d+)\s+(\S+)\s+(\S+)\s+(https:\/\/[\S]+)/);i&&r.push({id:parseInt(i[1],10),width:i[2]==="unknown"?"unknown":parseInt(i[2],10),height:i[3]==="unknown"?"unknown":parseInt(i[3],10),url:i[4]})}return r}var D={"2160p":"bv*[height<=2160]","1440p":"bv*[height<=1440]","1080p":"bv*[height<=1080]","720p":"bv*[height<=720]","480p":"bv*[height<=480]","360p":"bv*[height<=360]","240p":"bv*[height<=240]","144p":"bv*[height<=133]",highest:"bv*",lowest:"wv*"};function y(e){if(!e)return[];if(typeof e=="string")return["-f",e];if(Object.keys(e).length===0)return["-f","bv*+ba"];let r=[],{filter:t,quality:s,type:i}=e;return t==="audioonly"&&(r=["-x","--audio-format",i||"mp3","--audio-quality",s?s.toString():"5"]),t==="videoonly"&&(r=["-f",(s?D[s]:"bv*")+"[acodec=none]"]),t==="audioandvideo"&&(r=["-f",(s=="lowest"?"w*":"b*")+"[vcodec!=none][acodec!=none][ext="+(i||"mp4")+"]"]),t==="mergevideo"&&(r=["-f",(s?D[s]:"bv*")+"+ba"]),r}function $(e){if(!e)return[];if(typeof e=="string")return["-f",e];if(Object.keys(e).length===0)return["-f","b*[vcode!=none][acodec!=none]"];let r=[],{filter:t,quality:s}=e;return t==="audioonly"&&(r=["-f",s=="lowest"?"wa":"ba"]),t==="videoonly"&&(r=["-f",(s?D[s]:"bv*")+"[acodec=none]"]),t==="audioandvideo"&&(r=["-f",(s=="lowest"?"w*":"b*")+"[vcodec!=none][acodec!=none]"]),r}function O(e){if(!e||typeof e=="string")return"video/mp4";let{filter:r,type:t}=e;switch(r){case"videoonly":case"audioandvideo":switch(t){case"mp4":return"video/mp4";case"webm":return"video/webm";default:return"video/mp4"}case"audioonly":switch(t){case"aac":return"audio/aac";case"flac":return"audio/flac";case"mp3":return"audio/mpeg";case"m4a":return"audio/mp4";case"opus":return"audio/opus";case"vorbis":return"audio/vorbis";case"wav":return"audio/wav";case"alac":return"audio/mp4";default:return"audio/mpeg"}case"mergevideo":switch(t){case"webm":return"video/webm";case"mkv":return"video/x-matroska";case"ogg":return"video/ogg";case"flv":return"video/x-flv";default:return"video/mp4"}}}function j(e){if(!e||typeof e=="string")return"mp4";let{filter:r,type:t}=e;return t||(r==="audioonly"?"mp3":"mp4")}var W='bright-{"status":"%(progress.status)s","downloaded":"%(progress.downloaded_bytes)s","total":"%(progress.total_bytes)s","total_estimate":"%(progress.total_bytes_estimate)s","speed":"%(progress.speed)s","eta":"%(progress.eta)s"}';function z(e,r=2){let t=Number(e);if(t===0||isNaN(t))return t+" Bytes";let s=1024,i=r<0?0:r,a=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],n=Math.floor(Math.log(t)/Math.log(s));return parseFloat((t/Math.pow(s,n)).toFixed(i))+" "+a[n]}function ie(e,r,t){let s=Math.pow(t||10,r);return Math.round(e*s)/s}function _(e,r){return ie(100*Number(e)/Number(r),2)}function ae(e){e=Number(e);let r=Math.floor(e/3600),t=Math.floor(e%3600/60),s=Math.floor(e%3600%60),i=r>0?r+(r==1?" hour, ":" hours, "):"",a=t>0?t+(t==1?" minute, ":" minutes, "):"",n=s>=0?s+(s==1?" second":" seconds"):"";return i+a+n}function p(e){try{if(!e.includes("bright"))throw new Error;let r=e.split("\r")?.[1]?.trim()?.split("-")?.[1];if(!r)throw new Error;let t=JSON.parse(r),s=isNaN(Number(t.total))?Number(t.total_estimate):Number(t.total);return{status:t.status,downloaded:Number(t.downloaded),downloaded_str:z(t.downloaded),total:s,total_str:z(s),speed:Number(t.speed),speed_str:z(t.speed)+"/s",eta:Number(t.eta),eta_str:ae(t.eta),percentage:_(t.downloaded,s),percentage_str:_(t.downloaded,s)+"%"}}catch{return}}import{PassThrough as Y}from"stream";import m from"path";import w from"fs";import*as ne from"https";import*as oe from"http";import{URL as L}from"url";import*as h from"fs";function V(e,r={}){return new Promise((t,s)=>{let n=(new L(e).protocol==="https:"?ne:oe).get(e,r,o=>{if(o.statusCode>=300&&o.statusCode<400&&o.headers.location){let f=new L(o.headers.location,e).toString();V(f,r).then(t).catch(s);return}t(o)});n.on("error",s),n.setTimeout(3e4,()=>{n.destroy(),s(new Error("Request timed out"))})})}async function x(e,r){try{let t=h.createWriteStream(r),s=await V(e);if(s.statusCode!==200)throw t.close(),h.unlinkSync(r),new Error(`Failed to download file: ${s.statusCode} ${s.statusMessage}`);let i=parseInt(s.headers["content-length"]||"0",10),a=0;return s.on("data",n=>{a+=n.length;let o=a/i*100;process.stdout.write(`Progress: ${Math.round(o)}%\r`)}),s.pipe(t),new Promise((n,o)=>{t.on("finish",()=>{t.close(),console.log(`
Download complete!`),n()}),t.on("error",f=>{t.close(),h.unlinkSync(r),o(f)}),s.on("error",f=>{t.close(),h.unlinkSync(r),o(f)})})}catch(t){throw h.existsSync(r)&&h.unlinkSync(r),t}}import K from"path";import v from"fs";var fe="https://github.com/develar/7zip-bin/raw/refs/heads/update-7zip",T={win32:{x64:["win/x64","7za.exe"],ia32:["win/ia32","7za.exe"],arm64:["win/arm64","7za.exe"]},linux:{x64:["linux/x64","7zz"],arm64:["linux/arm64","7zz"],arm:["linux/arm","7zz"],ia32:["linux/ia32","7zz"]},darwin:{x64:["mac/x64","7zz"],arm64:["mac/arm64","7zz"]}};function U(){let e=process.platform,r=process.arch;if(!T[e]||!T[e][r])throw new Error(`No 7zip build available for ${e} ${r}`);return T[e][r]}async function q(){let e=ue();if(e)return e;let r=U(),t=`${fe}/${r[0]}/${r[1]}`,s=K.join(l,r[1]);v.existsSync(l)||v.mkdirSync(l,{recursive:!0}),console.log("Downloading 7zip...");try{await x(t,s),console.log(`7zip downloaded successfully to: ${s}`);try{v.chmodSync(s,493)}catch{console.log("Error while chmod")}return s}catch(i){throw console.error(`Download failed: ${i}`),i}}function ue(){let e=U(),r=K.join(l,e[1]);return v.existsSync(r)?r:void 0}import{execSync as B}from"child_process";var le="https://github.com/yt-dlp/FFmpeg-Builds/releases/download/latest",R={win32:{x64:"ffmpeg-master-latest-win64-gpl.zip",ia32:"ffmpeg-master-latest-win32-gpl.zip",arm64:"ffmpeg-master-latest-winarm64-gpl.zip"},linux:{x64:"ffmpeg-master-latest-linux64-gpl.tar.xz",arm64:"ffmpeg-master-latest-linuxarm64-gpl.tar.xz"},darwin:{x64:"ffmpeg-master-latest-macos64-gpl.zip",arm64:"ffmpeg-master-latest-macosarm64-gpl.zip"}};function J(){let e=process.platform,r=process.arch;if(!R[e]||!R[e][r])throw new Error(`No FFmpeg build available for ${e} ${r}`);return R[e][r]}async function G(){let e=k();if(e)return e;let r=J(),t=`${le}/${r}`,s=m.join(l,r);w.existsSync(l)||w.mkdirSync(l,{recursive:!0}),console.log("Downloading ffmpeg...");try{await x(t,s),console.log(`ffmpeg downloaded successfully to: ${s}`);try{w.chmodSync(s,493)}catch{console.log("Error while chmod")}return await ce(s,l),w.unlinkSync(s),k()}catch(i){throw console.error(`Download failed: ${i}`),i}}function k(){try{let e=process.platform,r=J(),t=e==="win32"?"ffmpeg.exe":"ffmpeg",s=H(r),i=m.join(l,s,"bin",t);if(w.existsSync(i))return i;throw new Error("FFmpeg binary not found. Please download it first.")}catch{return}}async function ce(e,r){try{let t=await q();e.includes("tar.xz")?(B(`"${t}" x "${e}" -aoa -o"${r}"`),B(`"${t}" x "${m.join(r,m.basename(e,m.extname(e)))}" -aoa -o"${r}"`)):B(`"${t}" x "${e}" -aoa -o"${r}"`)}catch(t){throw console.error("Error extracting file:",t),t}}function H(e){let r=m.basename(e,m.extname(e));return m.extname(r)&&(r=H(r)),r}var l=I.join(c,"..","bin"),Z=class{constructor(r){this.binaryPath=r?.binaryPath||this.getDefaultBinaryPath(),this.ffmpegPath=r?.ffmpegPath;let t=k();if(t&&(this.ffmpegPath=t),!b.existsSync(this.binaryPath))throw new Error("yt-dlp binary not found");if(b.chmodSync(this.binaryPath,493),this.ffmpegPath&&!b.existsSync(this.ffmpegPath))throw new Error("ffmpeg binary not found")}getDefaultBinaryPath(){return I.join(l,X.platform()==="win32"?"yt-dlp.exe":"yt-dlp")}async checkInstallationAsync(r){return new Promise((t,s)=>{if(r?.ffmpeg&&!this.ffmpegPath)return s(new Error("FFmpeg path is not set"));let i=S(this.binaryPath,["--version"]),a=r?.ffmpeg?S(this.ffmpegPath,["--version"]):null,n=!1,o=!r?.ffmpeg;i.on("error",()=>n=!1),i.on("exit",f=>{n=f===0,n&&o&&t(!0)}),a&&(a.on("error",()=>o=!1),a.on("exit",f=>{o=f===0,n&&o&&t(!0)}))})}checkInstallation(r){if(r?.ffmpeg&&!this.ffmpegPath)throw new Error("FFmpeg path is not set");let t=Q(this.binaryPath,["--version"],{stdio:"ignore"}),s=r?.ffmpeg?Q(this.ffmpegPath,["--version"],{stdio:"ignore"}):{status:0};return t.status===0&&s.status===0}async execAsync(r,t){let s=this.buildArgs(r,t||{}),i=a=>{if(t?.onData?.(a),t?.onProgress){let n=p(a);n&&t.onProgress?.(n)}};return this._executeAsync(s,i)}exec(r,t){let s=this.buildArgs(r,t||{},!0);return this._execute(s)}_execute(r){let t=S(this.binaryPath,r);return t.stderr.on("data",s=>{let i=Buffer.from(s).toString(),a=p(i);a&&t.emit("progress",a)}),t.stdout.on("data",s=>{let i=Buffer.from(s).toString(),a=p(i);a&&t.emit("progress",a)}),t}async _executeAsync(r,t,s){return new Promise((i,a)=>{let n=S(this.binaryPath,r),o="",f="";n.stdout.on("data",u=>{o+=u.toString(),t?.(Buffer.from(u).toString())}),n.stderr.on("data",u=>{f+=u.toString(),t?.(Buffer.from(u).toString())}),s&&n.stdout.pipe(s),n.on("close",u=>{u===0?i(o):a(new Error(`yt-dlp exited with code ${u}: ${f}`))}),n.on("error",u=>{a(new Error(`Failed to start yt-dlp process: ${u.message}`))})})}buildArgs(r,t,s,i){let a=C(t);return this.ffmpegPath&&a.push("--ffmpeg-location",this.ffmpegPath),s&&a.push("--progress-template",W),i&&a.push(...i),a.concat(r)}download(r,t){let{format:s,...i}=t||{},a=this.buildArgs(r,i,!0,y(s));return this._execute(a)}async downloadAsync(r,t){let{format:s,onProgress:i,...a}=t||{},n=this.buildArgs(r,a,i,y(s));return this._executeAsync(n,o=>{let f=p(o);f&&i?.(f)})}stream(r,t){let{format:s,onProgress:i,...a}=t||{},n=this.buildArgs(r,a,i,[...$(s),"-o","-"]),o=new Y;return this._executeAsync(n,f=>{let u=p(f);u&&i?.(u)},o),{pipe:(f,u)=>o.pipe(f,u),pipeAsync:(f,u)=>new Promise((g,F)=>{let P=o.pipe(f,u);f.on("finish",()=>g(P)),f.on("error",F)})}}async getInfoAsync(r){let t=["--dump-json","--quiet",r],s=await this._executeAsync(t);return JSON.parse(s)}async getThumbnailsAsync(r){let t=["--list-thumbnails","--quiet",r],s=await this._executeAsync(t);return N(s)}async getTitleAsync(r){let t=["--print","title",r];return await this._executeAsync(t)}async downloadFFmpeg(){return G()}async getFileAsync(r,t){let s=await this.getInfoAsync(r),{format:i,filename:a,metadata:n,onProgress:o,...f}=t||{},u=new Y,g=[];u.on("data",A=>g.push(Buffer.from(A)));let F=this.buildArgs(r,f,!!o,[...y(i),"-o","-"]);await this._executeAsync(F,A=>{if(o){let E=p(A);E&&o(E)}},u);let P=new he(g,{type:O(i)}),M={name:a||`${s.title}.${j(i)}`,type:O(i),size:P.size,...n};return new File([Buffer.concat(g)],M.name,{type:M.type})}};export{l as BIN_DIR,Z as YtDlp};