ytdlp-nodejs
Version:
A TypeScript wrapper for the yt-dlp executable
6 lines (5 loc) • 45 kB
JavaScript
"use strict";var Oe=Object.create;var N=Object.defineProperty;var Ve=Object.getOwnPropertyDescriptor;var Ce=Object.getOwnPropertyNames;var Ne=Object.getPrototypeOf,$e=Object.prototype.hasOwnProperty;var Le=(e,r)=>{for(var t in r)N(e,t,{get:r[t],enumerable:!0})},oe=(e,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of Ce(r))!$e.call(e,i)&&i!==t&&N(e,i,{get:()=>r[i],enumerable:!(s=Ve(r,i))||s.enumerable});return e};var c=(e,r,t)=>(t=e!=null?Oe(Ne(e)):{},oe(r||!e||!e.__esModule?N(t,"default",{value:e,enumerable:!0}):t,e)),je=e=>oe(N({},"__esModule",{value:!0}),e);var rr={};Le(rr,{BIN_DIR:()=>y,Download:()=>k,Exec:()=>x,Stream:()=>D,YtDlp:()=>ie,createDownload:()=>Ae,createExec:()=>Ee,createStreamBuilder:()=>Se,helpers:()=>er});module.exports=je(rr);var S=require("child_process"),se=c(require("fs")),Re=c(require("path")),Be=require("buffer"),Te=require("stream");function $(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 s of e.pluginDirs)r.push("--plugin-dirs",s);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);let t=e.jsRuntime??"node";if(t&&r.push("--js-runtime",t),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.retrySleepByType)for(let[s,i]of Object.entries(e.retrySleepByType))r.push("--retry-sleep",`${s}:${i}`);if(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[s,i]of Object.entries(e.paths))r.push("--paths",`${s}:${i}`);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[s,i]of Object.entries(e.addHeaders))r.push("--add-header",`${s}:${i}`);if(e.headers)for(let[s,i]of Object.entries(e.headers))r.push("--add-header",`${s}:${i}`);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[s,i]of Object.entries(e.extractorArgs))r.push("--extractor-args",`${s}:${i.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.referer&&r.push("--referer",e.referer),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[s,i]of Object.entries(e.postprocessorArgs))r.push("--postprocessor-args",`${s}:${i.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[s,i]of Object.entries(e.parseMetadata))r.push("--parse-metadata",`${s}:${i}`);if(e.replaceInMetadata)for(let[s,[i,n]]of Object.entries(e.replaceInMetadata))r.push("--replace-in-metadata",`${s} ${i} ${n}`);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 s of e.usePostProcessor)r.push("--use-postprocessor",s);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),e.rawArgs&&e.rawArgs.length>0&&r.push(...e.rawArgs),r}function ae(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 ue={"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*"},le=["audioonly","videoonly","audioandvideo","mergevideo"];function T(e){let r,t,s;if(!e)return[];if(typeof e=="string"&&!le.includes(e))return["-f",e];if(typeof e=="string"&&le.includes(e)&&(r=e),Object.keys(e).length===0||!e||typeof e!="object")return["-f","bv*+ba"];typeof e=="object"&&(r=e.filter,t=e.type,s=e.quality);let i=[];return r==="audioonly"&&(i=["-x","--audio-format",t||"mp3","--audio-quality",s?s.toString():"5"]),r==="videoonly"&&(i=["-f",(s?ue[s]:"bv*")+"[acodec=none]"]),r==="audioandvideo"&&(i=["-f",(s=="lowest"?"w*":"b*")+"[vcodec!=none][acodec!=none][ext="+(t||"mp4")+"]"]),r==="mergevideo"&&(i=["-f",`${s?ue[s]:"bv*"}+ba`],t&&i.push("--merge-output-format",t)),i}function Y(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/mp3";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 q(e){if(!e||typeof e=="string")return"mp4";let{filter:r,type:t}=e;return t||(r==="audioonly"?"mp3":"mp4")}function fe(e){if(!e?.extractAudio)return null;switch(e.audioFormat||"mp3"){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"}}function de(e){return e?.extractAudio?e.audioFormat||"mp3":null}var L="~ytdlp-progress-%(progress)#j";function Q(e,r=2){let t=Number(e);if(t===0||isNaN(t))return t+" Bytes";let s=1024,i=r<0?0:r,n=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],o=Math.floor(Math.log(t)/Math.log(s));return parseFloat((t/Math.pow(s,o)).toFixed(i))+" "+n[o]}function Ke(e,r,t){let s=Math.pow(t||10,r);return Math.round(e*s)/s}function Me(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, "):"",n=t>0?t+(t==1?" minute, ":" minutes, "):"",o=s>=0?s+(s==1?" second":" seconds"):"";return i+n+o}function m(e){try{if(!e.includes("~ytdlp-progress-"))throw new Error;let r=e.trim().replace("~ytdlp-progress-","");if(!r)throw new Error;let t=JSON.parse(r),s=l=>{if(l==null||l==="NA")return;let f=Number(l);return isNaN(f)?void 0:f},i=s(t.downloaded_bytes),n=s(t.total_bytes)??s(t.total_bytes_estimate),o=s(t.speed),a=s(t.eta),u=i!==void 0&&n!==void 0&&n>0?Ke(100*i/n,2):void 0;return{filename:t.filename,status:t.status,downloaded:i,downloaded_str:i!==void 0?Q(i):void 0,total:n,total_str:n!==void 0?Q(n):void 0,speed:o,speed_str:o!==void 0?Q(o)+"/s":void 0,eta:a,eta_str:a!==void 0?Me(a):void 0,percentage:u,percentage_str:u!==void 0?u+"%":void 0}}catch{return}}var j=c(require("path")),I=c(require("fs"));var We=c(require("https")),Ue=c(require("http")),G=require("url"),b=c(require("fs"));function H(e,r={}){return new Promise((t,s)=>{let o=(new G.URL(e).protocol==="https:"?We:Ue).get(e,r,a=>{if(a.statusCode>=300&&a.statusCode<400&&a.headers.location){let u=new G.URL(a.headers.location,e).toString();H(u,r).then(t).catch(s);return}t(a)});o.on("error",s),o.setTimeout(3e4,()=>{o.destroy(),s(new Error("Request timed out"))})})}async function _(e,r){try{let t=b.createWriteStream(r),s=await H(e);if(s.statusCode!==200)throw t.close(),b.unlinkSync(r),new Error(`Failed to download file: ${s.statusCode} ${s.statusMessage}`);let i=parseInt(s.headers["content-length"]||"0",10),n=0;return s.on("data",o=>{n+=o.length;let a=n/i*100;process.stdout.write(`Progress: ${Math.round(a)}%\r`)}),s.pipe(t),new Promise((o,a)=>{t.on("finish",()=>{t.close(),console.log(`
Download complete!`),o()}),t.on("error",u=>{t.close(),b.unlinkSync(r),a(u)}),s.on("error",u=>{t.close(),b.unlinkSync(r),a(u)})})}catch(t){throw b.existsSync(r)&&b.unlinkSync(r),t}}async function he(e,r={}){let t=await H(e,r);if(t.statusCode!==200)throw new Error(`Failed to fetch text: ${t.statusCode} ${t.statusMessage}`);return new Promise((s,i)=>{let n="";t.setEncoding("utf8"),t.on("data",o=>{n+=o}),t.on("end",()=>s(n)),t.on("error",i)})}var ce=c(require("fs")),E=c(require("path"));function ze(e){let r=e;for(;;){if(ce.existsSync(E.join(r,"package.json")))return r;let t=E.dirname(r);if(t===r)return e;r=t}}var me=ze(__dirname),y=E.join(me,"bin"),mr=E.join(me,"package.json");var Je="https://github.com/iqbal-rashed/ytdlp-nodejs/releases/download/ffmpeg-latest",Z={win32:{x64:["win-x64-ffmpeg.exe","win-x64-ffprobe.exe"],ia32:["win-ia32-ffmpeg.exe","win-ia32-ffprobe.exe"],arm64:["win-arm64-ffmpeg.exe","win-arm64-ffprobe.exe"]},linux:{x64:["linux-x64-ffmpeg","linux-x64-ffprobe"],arm64:["linux-arm64-ffmpeg","linux-arm64-ffprobe"]},darwin:{x64:["macos-x64-ffmpeg","macos-x64-ffprobe"],arm64:["macos-arm64-ffmpeg","macos-arm64-ffprobe"]},android:{arm64:["linux-arm64-ffmpeg","linux-arm64-ffprobe"]}};function pe(){let e=process.platform,r=process.arch;if(!Z[e]||!Z[e][r])throw new Error(`No FFmpeg build available for platform: ${e}, architecture: ${r}`);return Z[e][r]}async function X(e){let r=e||y,t=F();if(t)return t;try{let s=pe();if(!s.length)throw new Error;let i=s.map(o=>`${Je}/${o}`),n=s.map(o=>j.default.join(r,String(o.split("-").pop())));I.default.existsSync(r)||I.default.mkdirSync(r,{recursive:!0}),console.log("Downloading FFmpeg and FFprobe...");for(let o=0;o<s.length;o++){let a=i[o],u=n[o];console.log("Downloading...",j.default.basename(a)),await _(a,u)}if(process.platform!=="win32")for(let o of n)I.default.chmodSync(o,493);return F()}catch(s){throw console.error(`Download failed: ${s}`),s}}function F(){try{let e=pe();if(!e.length)throw new Error;let r=j.default.join(y,String(e[0].split("-").pop()));if(!I.default.existsSync(r))throw new Error("FFmpeg binary not found. Please download it first.");return r}catch{return}}var g=c(require("fs")),O=c(require("path"));var ge=c(require("crypto")),be="https://github.com/yt-dlp/yt-dlp/releases/latest/download",K={win32:{x64:"yt-dlp.exe",ia32:"yt-dlp_x86.exe"},linux:{x64:"yt-dlp",armv7l:"yt-dlp_linux_armv7l",aarch64:"yt-dlp_linux_aarch64",arm64:"yt-dlp"},darwin:{x64:"yt-dlp_macos",arm64:"yt-dlp_macos"},android:{arm64:"yt-dlp"}};function Ye(){let e=process.platform,r=process.arch;if(!K[e]||!K[e][r])throw new Error(`No yt-dlp build available for ${e} ${r}`);return K[e][r]}async function M(e){let r=e||y,t=Ye(),s=`${be}/${t}`,i=O.join(r,t);if(g.existsSync(i))return i;console.log("Downloading yt-dlp...",s),g.existsSync(r)||g.mkdirSync(r,{recursive:!0});try{return await _(s,i),console.log(`yt-dlp downloaded successfully to: ${i}`),process.platform!=="win32"&&g.chmodSync(i,493),i}catch(o){throw console.error(`Download failed: ${o}`),o}}async function qe(e){return new Promise((r,t)=>{let s=ge.default.createHash("sha256"),i=g.createReadStream(e);i.on("data",n=>s.update(n)),i.on("end",()=>r(s.digest("hex"))),i.on("error",t)})}async function Qe(e){try{let s=(await he(`${be}/SHA2-256SUMS`)).split(/\r?\n/).find(n=>n.includes(e));if(!s)return;let[i]=s.trim().split(/\s+/);return i||void 0}catch{return}}async function ee(e){let r=await M(e),t=O.basename(r),s=await Qe(t);if(!s)return{path:r,verified:!1};let i=await qe(r);if(i.toLowerCase()!==s.toLowerCase())throw new Error(`Checksum mismatch for ${t}. Expected ${s}, got ${i}`);return{path:r,verified:!0,checksum:s}}function V(){let e=process.platform,r=process.arch;try{let t=K[e][r],s=O.join(y,t);if(!g.existsSync(s))throw new Error("Ytdlp binary not found. Please download it first.");return s}catch{return}}function W(e){return e.replace(/~ytdlp-progress-\{[\s\S]*?\}\n?/g,"").split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>!r.includes("__YTDLP_FILEPATH__:")).filter(r=>!r.includes("__YTDLP_VIDEO_INFO__:")).filter(r=>!r.includes("__YTDLP_BEFORE_DL__:")).join(`
`)}function U(e){let r=[],t=e.split(/\r?\n/);for(let s of t){let i=s.trim();if(i.startsWith("__YTDLP_VIDEO_INFO__:")){let n=i.replace("__YTDLP_VIDEO_INFO__:","").trim();try{let o=n.replace(/:"N\/A"/g,":null").replace(/:"NA"/g,":null").replace(/:""/g,':"NA"'),a=JSON.parse(o),u={};for(let[l,f]of Object.entries(a))if(f==="NA")u[l]=null;else if(typeof f=="string"&&f==="N/A")u[l]=null;else if((l.includes("_count")||l.includes("_timestamp")||l==="autonumber"||l==="video_autonumber"||l==="n_entries"||l==="playlist_count"||l==="release_year"||l==="start_time"||l==="end_time"||l==="epoch"||l==="duration"||l==="age_limit")&&typeof f=="string"){let d=Number(f);u[l]=isNaN(d)?null:d}else(l==="is_live"||l==="was_live"||l==="channel_is_verified")&&typeof f=="string"?u[l]=f==="true"||f==="True":(l==="categories"||l==="tags"||l==="creators"||l==="cast")&&typeof f=="string"?f==="NA"||f==="N/A"||f===""?u[l]=null:u[l]=f.split(",").map(d=>d.trim()):u[l]=f;r.push(u)}catch{}}}return r}function w(e){let r=e.trim();if(!r.startsWith("__YTDLP_BEFORE_DL__:"))return null;let t=r.replace("__YTDLP_BEFORE_DL__:","").trim();try{let s=t.replace(/:"N\/A"/g,":null").replace(/:"NA"/g,":null").replace(/:""/,':"NA"'),i=JSON.parse(s),n={};for(let[o,a]of Object.entries(i))if(a==="NA"||a==="N/A")n[o]=null;else if((o.includes("_count")||o.includes("_timestamp")||o==="autonumber"||o==="video_autonumber"||o==="n_entries"||o==="playlist_count"||o==="release_year"||o==="start_time"||o==="end_time"||o==="epoch"||o==="duration"||o==="age_limit")&&typeof a=="string"){let u=Number(a);n[o]=isNaN(u)?null:u}else(o==="is_live"||o==="was_live"||o==="channel_is_verified")&&typeof a=="string"?n[o]=a==="true"||a==="True":(o==="categories"||o==="tags"||o==="creators"||o==="cast")&&typeof a=="string"?a==="NA"||a==="N/A"||a===""?n[o]=null:n[o]=a.split(",").map(u=>u.trim()):n[o]=a;return n}catch{return null}}var Ge=/^ERROR:\s*(?:\[.+?\]\s*)?(.+)/m,He=[/ERROR:\s*\[.*?\]\s*.*?:\s*Sign in to confirm/i,/ERROR:\s*\[.*?\]\s*Unable to extract/i,/ERROR:\s*\[.*?\]\s*This video is unavailable/i,/ERROR:\s*\[.*?\]\s*Video unavailable/i,/ERROR:\s*\[.*?\]\s*Private video/i,/ERROR:\s*\[.*?\]\s*.*?requires premium/i,/ERROR:\s*\[.*?\]\s*This live event has ended/i,/ERROR:\s*\[.*?\]\s*.*?is not available/i,/ERROR:\s*No video formats found/i,/ERROR:\s*Unsupported URL/i];function we(e){if(!e)return{hasError:!1};let r=e.match(Ge);return r?{hasError:!0,message:r[1]?.trim(),fullError:r[0]}:{hasError:!1}}function Ze(e){return e?He.some(r=>r.test(e)):!1}function ye(e,r){let s=we(e).message||"Unknown yt-dlp error";return r!=null&&r!==0&&(s=`yt-dlp exited with code ${r}: ${s}`),new Error(s)}function A(e,r,t){let{exitCodeOnly:s=!1,fatalOnly:i=!1}=t||{};if(r!==0&&r!==null)return ye(e,r);if(s)return;if(we(e).hasError)return i&&!Ze(e)?void 0:ye(e)}var Pe=require("events");function xe({url:e,options:r,ffmpegPath:t,withProgressTemplate:s,extra:i}){let n=$(r||{});return t&&n.push("--ffmpeg-location",t),s&&n.push("--progress-template",L),i&&i.length>0&&n.push(...i),e&&n.push("--",e),n}var re=c(require("fs")),P=class extends Pe.EventEmitter{constructor(t,s){super();this.binaryPath="";this.videoUrl="";this.extraArgs={};this.rawArgs=[];this.videoUrl=t,this.binaryPath=s?.binaryPath||V()||"",this.ffmpegPath=s?.ffmpegPath||F(),(!this.binaryPath||!re.default.existsSync(this.binaryPath))&&console.error(new Error("yt-dlp binary not found. Please install yt-dlp or specify correct binaryPath in options.")),this.ffmpegPath&&!re.default.existsSync(this.ffmpegPath)&&console.error(new Error(`FFmpeg binary not found at: ${this.ffmpegPath}. Please install FFmpeg or specify correct ffmpegPath.`))}setBinaryPath(t){return this.binaryPath=t,this}setFfmpegPath(t){return this.ffmpegPath=t,this}format(t){return this.formatValue=t,this}filter(t){let s=typeof this.formatValue=="object"?this.formatValue:{};return this.formatValue={...s,filter:t},this}quality(t){let s=typeof this.formatValue=="object"?this.formatValue:{};return this.formatValue={filter:this.formatValue,...s,quality:t},this}type(t){let s=typeof this.formatValue=="object"?this.formatValue:{};return this.formatValue={filter:this.formatValue,...s,type:t},this}options(t){return this.extraArgs={...this.extraArgs,...t},this}rateLimit(t){return this.extraArgs.limitRate=t,this}cookies(t){return this.extraArgs.cookies=t,this}cookiesFromBrowser(t){return this.extraArgs.cookiesFromBrowser=t,this}proxy(t){return this.extraArgs.proxy=t,this}addOption(t,s){return this.extraArgs[t]=s,this}addArgs(...t){return this.rawArgs.push(...t),this}extractAudio(t){return this.extraArgs.extractAudio=!0,t&&(this.extraArgs.audioFormat=t),this}audioFormat(t){return this.extraArgs.audioFormat=t,this}audioQuality(t){return this.extraArgs.audioQuality=t,this}embedThumbnail(){return this.extraArgs.embedThumbnail=!0,this}embedSubs(){return this.extraArgs.embedSubs=!0,this}embedMetadata(){return this.extraArgs.embedMetadata=!0,this}writeSubs(){return this.extraArgs.writeSubs=!0,this}writeAutoSubs(){return this.extraArgs.writeAutoSubs=!0,this}subLangs(t){return this.extraArgs.subLangs=t,this}writeThumbnail(){return this.extraArgs.writeThumbnail=!0,this}username(t){return this.extraArgs.username=t,this}password(t){return this.extraArgs.password=t,this}playlistStart(t){return this.extraArgs.playlistStart=t,this}playlistEnd(t){return this.extraArgs.playlistEnd=t,this}playlistItems(t){return this.extraArgs.playlistItems=t,this}buildFormatArgs(){return this.formatValue?T(this.formatValue):[]}buildBaseArgs(t=[]){if(!this.videoUrl)throw new Error("URL is required.");let s=this.buildFormatArgs();return xe({url:this.videoUrl,options:this.extraArgs,ffmpegPath:this.ffmpegPath,withProgressTemplate:!0,extra:[...s,...t,...this.rawArgs]})}debugPrint(t=!0){return this.extraArgs.debugPrintCommandLine=t,this}getCommand(){let t=this.buildArgs();return`${this.binaryPath} ${t.join(" ")}`}getArguments(){return this.buildArgs()}toString(){return this.getCommand()}printDebugCommandLine(t){if(this.extraArgs.debugPrintCommandLine){let s=`${this.binaryPath} ${t.join(" ")}`;console.error(`[ytdlp-nodejs] Command: ${s}`)}}validateBinaryPath(){if(!this.binaryPath)throw new Error("Binary path is required. Use .setBinaryPath() or pass it in constructor.")}kill(t){return this.process?.kill(t)??!1}get pid(){return this.process?.pid}};var ve=["id","title","fulltitle","ext","alt_title","description","display_id","uploader","uploader_id","uploader_url","license","creators","creator","timestamp","upload_date","release_timestamp","release_date","release_year","modified_timestamp","modified_date","channel","channel_id","channel_url","channel_follower_count","channel_is_verified","location","duration","duration_string","view_count","concurrent_view_count","like_count","dislike_count","repost_count","average_rating","comment_count","save_count","age_limit","live_status","is_live","was_live","playable_in_embed","availability","media_type","start_time","end_time","extractor","extractor_key","epoch","autonumber","video_autonumber","n_entries","playlist_id","playlist_title","playlist","playlist_count","playlist_index","playlist_autonumber","playlist_uploader","playlist_uploader_id","playlist_channel","playlist_channel_id","playlist_webpage_url","webpage_url","webpage_url_basename","webpage_url_domain","original_url","categories","tags","cast","filepath"];function Xe(){return`after_move:__YTDLP_VIDEO_INFO__:{${ve.map(r=>`"${r}":%(${r}|null)j`).join(",")}}`}function R(){return`before_dl:__YTDLP_BEFORE_DL__:{${ve.map(r=>`"${r}":%(${r}|null)j`).join(",")}}`}function z(){return["--print",Xe(),"--progress","--newline"]}var Fe=require("child_process"),k=class extends P{constructor(r,t){super(r,t),this.on("error",()=>{})}on(r,t){return super.on(r,t)}once(r,t){return super.once(r,t)}emit(r,...t){return super.emit(r,...t)}output(r){return this.outputDir=r,this}setOutputTemplate(r){return this.outputPath=r,this}skipDownload(){return this.extraArgs.skipDownload=!0,this}buildArgs(){let r={...this.extraArgs};this.outputDir&&(r.output=`${this.outputDir}/%(title)s.%(ext)s`),this.outputPath&&(r.output=this.outputPath);let t=this.extraArgs;this.extraArgs=r;let s=[...z()];this.listenerCount("beforeDownload")>0&&s.unshift("--print",R());let i=this.buildBaseArgs(s);return this.extraArgs=t,i}run(){return this.resultPromise?this.resultPromise:(this.resultPromise=new Promise((r,t)=>{try{this.validateBinaryPath();let s=this.buildArgs(),i=`${this.binaryPath} ${s.join(" ")}`;this.printDebugCommandLine(s),this.process=(0,Fe.spawn)(this.binaryPath,s),this.emit("start",i);let n="",o="";this.process.stdout?.on("data",a=>{let u=a.toString();n+=u,this.emit("stdout",u);let l=w(u);l&&this.emit("beforeDownload",l);let f=m(u);f&&this.emit("progress",f)}),this.process.stderr?.on("data",a=>{let u=a.toString();o+=u,this.emit("stderr",u);let l=m(u);l&&this.emit("progress",l)}),this.process.on("error",a=>{this.emit("error",a),t(a)}),this.process.on("close",a=>{let u=A(o,a);if(u){this.emit("error",u),t(u);return}let l=W(n),f=U(n),d={output:l,filePaths:f.map(p=>p?.filepath??"").filter(Boolean),info:f,stderr:o};this.emit("finish",d),r(d)})}catch(s){t(s)}}),this.resultPromise)}then(r,t){return this.run().then(r,t)}catch(r){return this.run().catch(r)}finally(r){return this.run().finally(r)}};function Ae(e,r){return new k(e,r)}var ke=require("stream");var De=require("child_process"),D=class extends P{constructor(t,s){super(t,s);this.totalBytes=0;this.started=!1;this.on("error",()=>{})}on(t,s){return super.on(t,s)}once(t,s){return super.once(t,s)}emit(t,...s){return super.emit(t,...s)}buildArgs(){let t=["-o","-","--no-playlist","--progress","--no-quiet"];return this.listenerCount("beforeDownload")>0&&t.push("--print",R()),this.buildBaseArgs(t)}startStream(){if(this.started)return this.passThrough;this.validateBinaryPath(),this.started=!0,this.passThrough=new ke.PassThrough;let t=this.buildArgs(),s=`${this.binaryPath} ${t.join(" ")}`;this.printDebugCommandLine(t),this.process=(0,De.spawn)(this.binaryPath,t,{shell:!1}),this.emit("start",s),this.process.stdout?.on("data",n=>{this.totalBytes+=n.length,this.passThrough.write(n),this.emit("data",n)});let i="";return this.process.stderr?.on("data",n=>{let o=n.toString();i+=o,this.emit("stderr",o);let a=w(o);a&&this.emit("beforeDownload",a);let u=m(o);u&&this.emit("progress",u)}),this.process.on("error",n=>{this.emit("error",n),this.passThrough.destroy(n)}),this.process.on("close",n=>{let o=A(i,n);o?(this.emit("error",o),this.passThrough.destroy(o)):(this.passThrough.end(),this.emit("end"))}),this.passThrough}pipe(t,s){let i=Date.now(),n=this.startStream();return new Promise((o,a)=>{n.pipe(t,s),t.on("finish",()=>{o({bytes:this.totalBytes,duration:Date.now()-i})}),t.on("error",a),this.passThrough.on("error",a)})}pipeAsync(t,s){return this.pipe(t,s)}async toBuffer(){let t=[];return new Promise((s,i)=>{let n=this.startStream();n.on("data",o=>{t.push(o)}),n.on("end",()=>{s(Buffer.concat(t))}),n.on("error",i)})}getStream(){return this.startStream()}};function Se(e,r){return new D(e,r)}var _e=require("stream");var te=require("child_process");var x=class extends P{constructor(t,s){super(t,s);this.totalBytes=0;this.started=!1;this.output="";this.on("error",()=>{})}on(t,s){return super.on(t,s)}once(t,s){return super.once(t,s)}emit(t,...s){return super.emit(t,...s)}buildArgs(){let t=[],s=[...z()];return this.listenerCount("beforeDownload")>0&&s.unshift("--print",R()),this.listenerCount("afterDownload")>0&&s.push("--print","after_move:filepath"),this.buildBaseArgs([...t,...s])}startStream(){if(this.started)return this.passThrough;this.validateBinaryPath(),this.started=!0,this.passThrough=new _e.PassThrough,this.output="";let t=this.buildArgs();t.includes("--no-playlist")||(t=["--no-playlist",...t]);let s=`${this.binaryPath} ${t.join(" ")}`;return this.printDebugCommandLine(t),this.process=(0,te.spawn)(this.binaryPath,t,{shell:!1}),this.emit("start",s),this.process.stdout?.on("data",i=>{this.totalBytes+=i.length,this.passThrough.write(i),this.emit("data",i);let n=i.toString();this.emit("stdout",n);let o=w(n);o&&(this.beforeDownloadInfo=o,this.emit("beforeDownload",this.beforeDownloadInfo));let a=m(n);a&&this.emit("progress",a)}),this.process.stderr?.on("data",i=>{let n=i.toString();this.emit("stderr",n),this.output+=n;let o=w(n);o&&(this.beforeDownloadInfo=o,this.emit("beforeDownload",this.beforeDownloadInfo));let a=m(n);a&&(this.emit("progress",a),a.status==="finished"&&this.beforeDownloadInfo&&(this.afterDownloadInfo={...this.beforeDownloadInfo,filepath:a.filename},this.emit("afterDownload",this.afterDownloadInfo)))}),this.process.on("error",i=>{this.emit("error",i),this.passThrough.destroy(i)}),this.process.on("close",i=>{let n=A(this.output,i);n?(this.emit("error",n),this.passThrough.destroy(n)):(this.passThrough.end(),this.emit("end"))}),this.passThrough}pipe(t,s){let i=Date.now(),n=this.startStream();return new Promise((o,a)=>{n.pipe(t,s),t.on("finish",()=>{o({bytes:this.totalBytes,duration:Date.now()-i,info:this.afterDownloadInfo,output:this.output})}),t.on("error",a),this.passThrough.on("error",a)})}pipeAsync(t,s){return this.pipe(t,s)}async toBuffer(){let t=[];return new Promise((s,i)=>{let n=this.startStream();n.on("data",o=>{t.push(o)}),n.on("end",()=>{s(Buffer.concat(t))}),n.on("error",i)})}getStream(){return this.startStream()}exec(){return this.resultPromise?this.resultPromise:(this.resultPromise=new Promise((t,s)=>{try{this.validateBinaryPath();let i=this.buildArgs(),n=`${this.binaryPath} ${i.join(" ")}`;this.printDebugCommandLine(i),this.process=(0,te.spawn)(this.binaryPath,i,{shell:!1}),this.emit("start",n);let o="",a="";this.process.stdout?.on("data",u=>{let l=u.toString();o+=l,this.emit("stdout",l);let f=w(l);f&&(this.beforeDownloadInfo=f,this.emit("beforeDownload",this.beforeDownloadInfo)),this.emit("data",u);let d=m(l);d&&(this.emit("progress",d),d.status==="finished"&&this.beforeDownloadInfo&&(this.afterDownloadInfo={...this.beforeDownloadInfo,filepath:d.filename},this.emit("afterDownload",this.afterDownloadInfo)))}),this.process.stderr?.on("data",u=>{let l=u.toString();a+=l,this.emit("stderr",l);let f=w(l);f&&(this.beforeDownloadInfo=f,this.emit("beforeDownload",this.beforeDownloadInfo));let d=m(l);d&&(this.emit("progress",d),d.status==="finished"&&this.beforeDownloadInfo&&(this.afterDownloadInfo={...this.beforeDownloadInfo,filepath:d.filename},this.emit("afterDownload",this.afterDownloadInfo)))}),this.process.on("error",u=>{this.emit("error",u),s(u)}),this.process.on("close",u=>{let l=A(a,u);if(l){this.emit("error",l),s(l);return}let f=W(o),d=U(o),p={stdout:o,stderr:a,exitCode:u,command:n,info:d,output:f,filePaths:d.map(B=>B?.filepath??"").filter(Boolean)};this.emit("complete",p),this.emit("end"),t(p)})}catch(i){s(i)}}),this.resultPromise)}run(){return this.exec()}then(t,s){return this.exec().then(t,s)}catch(t){return this.exec().catch(t)}finally(t){return this.exec().finally(t)}};function Ee(e,r){return new x(e,r)}var ie=class{constructor(r){this.binaryPath=r?.binaryPath||V()||"",this.ffmpegPath=r?.ffmpegPath||F(),(!this.binaryPath||!se.existsSync(this.binaryPath))&&console.error(new Error("yt-dlp binary not found. Please install yt-dlp or specify correct binaryPath in options.")),this.ffmpegPath&&!se.existsSync(this.ffmpegPath)&&console.error(new Error(`FFmpeg binary not found at: ${this.ffmpegPath}. Please install FFmpeg or specify correct ffmpegPath.`))}async checkInstallationAsync(r){return new Promise((t,s)=>{if(r?.ffmpeg&&!this.ffmpegPath)return s(new Error("FFmpeg path is not set"));let i=(0,S.spawn)(this.binaryPath,["--version"]),n=!1,o=!r?.ffmpeg;i.on("error",()=>n=!1),i.on("exit",a=>{if(n=a===0,r?.ffmpeg){let u=(0,S.spawn)(this.ffmpegPath,["-version"]);u.on("error",()=>o=!1),u.on("exit",l=>{o=l===0,t(n&&o)})}else t(n)})})}checkInstallation(r){if(r?.ffmpeg&&!this.ffmpegPath)throw new Error("FFmpeg path is not set");let t=(0,S.spawnSync)(this.binaryPath,["--version"],{stdio:"ignore"}),s=r?.ffmpeg?(0,S.spawnSync)(this.ffmpegPath,["-version"],{stdio:"ignore"}):{status:0};return t.status===0&&s.status===0}async getInfoAsync(r,t){let s=await this.execAsync(r,{dumpSingleJson:!0,flatPlaylist:!0,...t});return JSON.parse(s.output)}async execAsync(r,t){let s=new x(r,{binaryPath:this.binaryPath,ffmpegPath:this.ffmpegPath}),{onData:i,onProgress:n,onBeforeDownload:o,pipeTo:a,...u}=t||{};return u&&s.options(u),i&&s.on("stdout",i),n&&s.on("progress",n),o&&s.on("beforeDownload",o),a?s.pipe(a):s.exec()}exec(r,t){let s=new x(r,{binaryPath:this.binaryPath,ffmpegPath:this.ffmpegPath});return t&&s.options(t),s}download(r,t){let s=new k(r,{binaryPath:this.binaryPath,ffmpegPath:this.ffmpegPath}),{format:i,...n}=t||{};return i&&s.format(i),n&&s.options(n),s}async downloadAsync(r,t){let{onProgress:s,beforeDownload:i,...n}=t||{},o=this.download(r,n);s&&o.on("progress",s),i&&o.on("beforeDownload",i);let a=await o.run();return{output:a.output,filePaths:a.filePaths,info:a.info}}stream(r,t){let s=new D(r,{binaryPath:this.binaryPath,ffmpegPath:this.ffmpegPath}),{format:i,...n}=t||{};return i&&s.format(i),n&&s.options(n),s}execBuilder(r,t){let s=new x(r,{binaryPath:this.binaryPath,ffmpegPath:this.ffmpegPath}),{format:i,...n}=t||{};return i&&s.format(i),n&&s.options(n),s}async downloadAudio(r,t="mp3",s){let i=["aac","flac","mp3","m4a","opus","vorbis","wav","alac"];if(!i.includes(t))throw new Error(`Invalid audio format: ${t}. Supported: ${i.join(", ")}`);return this.downloadAsync(r,{...s,extractAudio:!0,audioFormat:t})}async downloadVideo(r,t="best",s){let i=["best","2160p","1440p","1080p","720p","480p","360p","240p","144p","highest","lowest"];if(!i.includes(t))throw new Error(`Invalid video quality: ${t}. Supported: ${i.join(", ")}`);let n=t==="best"?"bestvideo+bestaudio/best":`bestvideo[height<=${parseInt(t)||1080}]+bestaudio/best[height<=${parseInt(t)||1080}]`;return this.downloadAsync(r,{...s,format:n})}async getSubtitles(r,t){return(await this.execAsync(r,{...t,listSubs:!0,skipDownload:!0})).output?[]:[]}async getComments(r,t=20,s){let i=await this.execAsync(r,{...s,writeComments:!0,dumpSingleJson:!0,skipDownload:!0,extractorArgs:{youtube:[`max_comments=${t}`,"player_skip=webpage"]}});try{return JSON.parse(i.output).comments||[]}catch{return[]}}async getDirectUrlsAsync(r,t){return(await this.getInfoAsync(r,t)).formats.map(i=>i.url)}async getFormatsAsync(r,t){let s=await this.getInfoAsync(r,t);return{source:"json",info:s,formats:s.formats}}async getThumbnailsAsync(r){return(await this.getInfoAsync(r)).thumbnails}async getTitleAsync(r){return(await this.execAsync(r,{print:"title"})).output.trim()}async getVersionAsync(){return(await this.execAsync("",{printVersion:!0})).output.trim()}async downloadFFmpeg(){return X()}async getFileAsync(r,t){let s,{onBeforeDownload:i,onProgress:n,filename:o,metadata:a,format:u,...l}=t||{},f=[],d=new Te.PassThrough;d.on("data",v=>f.push(Buffer.from(v)));let p=T(u),B={...l};if(p.length>=2&&p[0]==="-f"&&(B.format=p[1]),p.includes("--merge-output-format")){let v=p.indexOf("--merge-output-format");B.mergeOutputFormat=p[v+1]}await this.execAsync(r,{...B,noPlaylist:!0,pipeTo:d,onProgress:n,onBeforeDownload:v=>{s=v,i?.(v)},output:"-"});let C,J;u&&typeof u=="object"?(C=Y(u),J=q(u)):(C=fe(l)||"video/mp4",J=de(l)||"mp4");let Ie=new Be.Blob(f,{type:C}),ne={name:o||`${s?.title||"download"}.${J}`,type:C,size:Ie.size,...a};return new File([Buffer.concat(f)],ne.name,{type:ne.type})}async getUrlsAsync(r,t){return(await this.execAsync(r,{...t,print:"urls"})).output.split(`
`).filter(Boolean)}async updateYtDlpAsync(r){if(r?.preferBuiltIn!==!1&&this.binaryPath)try{await this.execAsync("",{update:!0});let a=await this.getVersionAsync().catch(()=>{});return{method:"built-in",binaryPath:this.binaryPath,version:a}}catch{}let s=r?.outDir||(this.binaryPath?Re.default.dirname(this.binaryPath):void 0);if(r?.verifyChecksum!==!1){let a=await ee(s),u=await this.getVersionAsyncUsingBinary(a.path).catch(()=>{});return{method:"download",binaryPath:a.path,version:u,verified:a.verified}}let n=await M(s),o=await this.getVersionAsyncUsingBinary(n).catch(()=>{});return{method:"download",binaryPath:n,version:o,verified:!1}}async getVersionAsyncUsingBinary(r){return new Promise((t,s)=>{let i=(0,S.spawn)(r,["--version"]),n="",o="";i.stdout?.on("data",a=>{n+=a.toString()}),i.stderr?.on("data",a=>{o+=a.toString()}),i.on("close",a=>{a===0?t(n.trim()):s(new Error(`Failed to get version: ${o}`))}),i.on("error",s)})}},er={downloadFFmpeg:X,findFFmpegBinary:F,PROGRESS_STRING:L,getContentType:Y,getFileExtension:q,parseFormatOptions:T,stringToProgress:m,createArgs:$,extractThumbnails:ae,downloadFile:_,BIN_DIR:y,downloadYtDlp:M,downloadYtDlpVerified:ee,findYtdlpBinary:V};0&&(module.exports={BIN_DIR,Download,Exec,Stream,YtDlp,createDownload,createExec,createStreamBuilder,helpers});