@yt-kit/core 1.0.4 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  // Generated by dts-bundle-generator v9.5.1
2
2
 
3
- export type CacheKey = "formats:" | (string & {});
3
+ export type CacheKey = "formats:${ytId}" | (string & {});
4
4
  export interface CachedData {
5
5
  content: string;
6
6
  timestamp: number;
@@ -150,7 +150,7 @@ export declare function resolveFilenamePattern({ filename, id, ytId }: ResolverP
150
150
  export type Pattern = typeof PATTERNS[keyof typeof PATTERNS];
151
151
  export type PatternData = string;
152
152
  export declare function expandPattern(pattern: string, patternMap: Map<Pattern, PatternData>): string;
153
- export declare function resolvePath(path: string): string;
153
+ export declare function resolvePath(input: string): string;
154
154
  export type CommandKey = keyof typeof COMMANDS;
155
155
  export type Command = typeof COMMANDS[keyof typeof COMMANDS];
156
156
 
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- class A{store=new Map;get(t){let e=this.store.get(t);if(!e)return null;return e}set(t,e){this.store.set(t,e)}delete(t){this.store.delete(t)}}var l=new A;var V={day:86400000,hrs:3600000,min:60000,sec:1000,nano:0.001};function _(t,e){if(!V[e])return t;return t*V[e]}function Y(t){if(typeof t!=="string")return!1;return!0}import{readFile as W}from"node:fs/promises";import{homedir as J}from"node:os";function c(t){return t.replace("~",J())}async function T(t){let e=l.get("cache")?.cacheLocation;if(!e)return;let r=c(e),o;try{o=await W(r,"utf8")}catch{}if(o)try{o=JSON.parse(o)}catch(s){console.error(`Error convirtiendo la caché de ${t} a JSON:`,s)}if(!o)return;return o}import{rm as L}from"node:fs/promises";async function q(t){let e=l.get("cache")?.cacheLocation;if(!e)return;let r=c(e);try{await L(r)}catch(o){console.error(`Error borrando la caché de ${t} en el almacenamiento:`,o)}}import{mkdir as Q,writeFile as G}from"node:fs/promises";import{dirname as H}from"node:path";async function C(t,e){let r=l.get("cache")?.cacheLocation;if(!r)return;let o=c(r),s=H(o);try{Q(s,{recursive:!0}),await G(o,JSON.stringify(e),"utf8")}catch(a){console.error(`Error cacheando ${t} en el almacenamiento:`,a)}}class E{store=new Map;defaultTtl=_(10,"day");async get(t){if(!Y(t))throw Error("CacheKey inválida",{cause:t});let e=l.get("cache")?.method??"memory",r=null;if(e==="memory")r=this.store.get(t);if(e==="disk")r=await T(t);if(e==="hybrid"){if(r=this.store.get(t),!r)r=await T(t)}if(!r)return null;if(Date.now()-r.timestamp>this.defaultTtl){if(e!=="disk")this.delete(t);if(e==="disk")q(t);return null}return r}async set(t,e){if(!Y(t))throw Error("CacheKey inválida",{cause:t});let r=l.get("cache")?.method??"memory",o={...e,timestamp:Date.now()};if(r==="memory")this.store.set(t,o);if(r==="disk")await C(t,o);if(r==="hybrid")this.store.set(t,o),await C(t,o)}delete(t){this.store.delete(t)}}var g=new E;var X=[18,144,240,360,480,720,1080,1440,2160],v={"yt-dlp":"yt-dlp"},U="%(ytId)s.%(ext)s",M={ID:"%(id)s",YT_ID:"%(ytId)s"};function d(t){return`https://youtube.com/watch?v=${t}`}import{spawn as I}from"node:child_process";import{stdout as Z,stderr as j}from"node:process";function O(t,e){(t==="data"?Z:j).write(e)}function D(t,e,r){let o=v[t];return new Promise((s,a)=>{let p=I(o,e),u="",m="";p.stdout.on("data",(i)=>{u+=i;let f=i.toString();if(r)O("data",f)}),p.stderr.on("data",(i)=>{m+=i;let f=i.toString();if(r)O("err",f)}),p.on("close",(i)=>{if(i===0)s(u.toString());else a(Error(m.toString()))}),p.on("error",(i)=>{a(i)})})}function P(t,e){let r=t;for(let[o,s]of e)r=r.replaceAll(o,s);return r}function B(t){return t.replaceAll("/","⁄")}function N({filename:t,id:e,ytId:r}){let o=new Map([[M.ID,e],[M.YT_ID,r]]),s=P(t,o);return B(s)}class S{async download(t,e,r){let o=this.buildYtDlpArgs(t,e,r);return await D("yt-dlp",o,!0),{duration:-1,path:"unknown"}}buildYtDlpArgs(t,e,r){let{id:o,type:s}=r,a=s==="video",p=r.outputPath,u=N({filename:r.filename,id:r.id,ytId:e}),m="aac";return["-f",o,...a?[]:["-x","--audio-format","aac"],"-o",u,"-P",p,t]}}async function b(t,e){if(!t||!e.id)return;let r=d(t),o=$("video",e);return new S().download(r,t,o)}async function k(t,e){if(!t||!e.id)return;let r=d(t),o=$("audio",e);return new S().download(r,t,o)}function $(t,e){return{id:e.id,type:t,outputPath:e.outputPath??".",filename:e.filename??U}}function z({a:t,b:e,compareResolution:r,type:o}){let s=o==="video"&&r&&t.quality!==null&&e.quality!==null,a=o==="video"&&r&&t.height!==null&&e.height!==null,p=o==="video"&&t.fps!==null&&e.fps!==null,u=o==="audio"&&t.asr!==null&&e.asr!==null,m=t.tbr!==null&&e.tbr!==null,i=0,f=0;if(s){if((t.quality??0)>(e.quality??0))i+=3;else if((t.quality??0)<(e.quality??0))f+=3}if(a){if((t.height??0)>(e.height??0))i+=3;else if((t.height??0)<(e.height??0))f+=3}if(p){if((t.fps??0)>(e.fps??0))i+=2;else if((t.fps??0)<(e.fps??0))f+=2}if(u){if((t.asr??0)>(e.asr??0))i+=2;else if((t.asr??0)<(e.asr??0))f+=2}if(m){if((t.tbr??0)>(e.tbr??0))i+=1;else if((t.tbr??0)<(e.tbr??0))f+=1}return{aScore:i,bScore:f}}function h(t,e,{type:r,compareResolution:o}){if(!t||!e)return;let{aScore:s,bScore:a}=z({a:t,b:e,type:r,compareResolution:o});return s>a?t:e}function x(t,e,{type:r,compareResolution:o}){if(!t||!e)return;let{aScore:s,bScore:a}=z({a:t,b:e,type:r,compareResolution:o});return s>a?e:t}async function tt(t,e){let r=d(t),o=`formats-${t}`,s=Boolean(e.match(/\d/)),a=s?!1:"N/A",p=["--print","%(formats)j",r],m=(await g.get(o))?.content??"";if(!m){let n;try{n=await D("yt-dlp",p)}catch(R){throw console.error("Error consiguiendo el ID del formato"),R}if(typeof n!=="string")throw Error("La salida del proceso es de tipo inválido (se esperaba string)");m=n,g.set(o,{content:m})}let i=[];try{i=JSON.parse(m)}catch(n){throw console.error("Error convirtiendo la salida de yt-dlp a JSON"),n}if(!Array.isArray(i))throw Error("Se esperaba que los formatos fuesen un array. Puede que el contenido cacheado esté corrupto o sea inválido.");let f=void 0,K=void 0,w=void 0,F=void 0,y=void 0;for(let n of i){let R=n.resolution==="audio only";if(s&&n.format_note===e){a=!0,y=h(y,n,{compareResolution:!1,type:"video"})??n;continue}if(R)w=h(w,n,{compareResolution:!1,type:"audio"})??n,F=x(F,n,{compareResolution:!1,type:"audio"})??n;else f=h(f,n,{compareResolution:!0,type:"video"})??n,K=x(K,n,{compareResolution:!0,type:"video"})??n}if(!s)y={"best-video":f,"worst-video":K,"best-audio":w,"worst-audio":F}[e];return{foundSpecific:a,formatId:y?.format_id,desiredFormat:y}}export{C as saveInDisk,c as resolvePath,N as resolveFilenamePattern,x as getWorstFormat,T as getFromDisk,h as getBetterFormat,d as formYoutubeUrl,tt as findFormatId,P as expandPattern,b as downloadVideo,k as downloadAudio,l as config,g as cache,X as STANDARD_RESOLUTIONS,A as Configuration,E as CacheManager};
1
+ class F{store=new Map;get(t){let e=this.store.get(t);if(!e)return null;return e}set(t,e){this.store.set(t,e)}delete(t){this.store.delete(t)}}var l=new F;var N={day:86400000,hrs:3600000,min:60000,sec:1000,nano:0.001};function O(t,e){if(!N[e])return t;return t*N[e]}function K(t){if(typeof t!=="string")return!1;return!0}import{readFile as J}from"node:fs/promises";import{homedir as B}from"node:os";import{join as $,resolve as z,sep as W}from"node:path";function d(t){if(!t)return"";if(t.match(/~[^/]+/))throw Error("Ruta inválida. Ten más cuidado usando '~'");if(t.includes(" "))throw Error("La ruta no puede tener espacios");if(t==="."||t==="..")throw Error(`'${t}' No es una ruta válida. Tal vez faltó agregar '/'?`);let e=t;if(t.startsWith("~"))e=$(B(),W,t.slice(1));return z(e)}import{join as Q}from"node:path";async function T(t){let e=l.get("cache")?.cacheLocation;if(!e)return;let r=d(e);if(t.includes("formats:")){let s=t.split(":")[1];if(!s)throw Error(`Falta especificar ytId en ${t}`);r=Q(d(e),"formats",s)}let o;try{o=await J(r,"utf8")}catch{}if(o)try{o=JSON.parse(o)}catch(s){console.error(`Error convirtiendo la caché de ${t} a JSON:`,s)}if(!o)return;return o}import{rm as G}from"node:fs/promises";async function V(t){let e=l.get("cache")?.cacheLocation;if(!e)return;let r=d(e);try{await G(r)}catch(o){console.error(`Error borrando la caché de ${t} en el almacenamiento:`,o)}}import{mkdir as H,writeFile as L}from"node:fs/promises";import{dirname as X,join as Z}from"node:path";async function h(t,e){let r=l.get("cache")?.cacheLocation;if(!r)return;let o=d(r);if(t.includes("formats:")){let n=t.split(":")[1];if(!n)throw Error(`Falta especificar ytId en ${t}`);o=Z(d(r),"formats",n)}let s=X(o);try{H(s,{recursive:!0}),await L(o,JSON.stringify(e),"utf8")}catch(n){console.error(`Error cacheando ${t} en el almacenamiento:`,n)}}class E{store=new Map;defaultTtl=O(10,"day");async get(t){if(!K(t))throw Error("CacheKey inválida",{cause:t});let e=l.get("cache")?.method??"memory",r=null;if(e==="memory")r=this.store.get(t);if(e==="disk")r=await T(t);if(e==="hybrid"){if(r=this.store.get(t),!r)r=await T(t)}if(!r)return null;if(Date.now()-r.timestamp>this.defaultTtl){if(e!=="disk")this.delete(t);if(e==="disk")V(t);return null}return r}async set(t,e){if(!K(t))throw Error("CacheKey inválida",{cause:t});let r=l.get("cache")?.method??"memory",o={...e,timestamp:Date.now()};if(r==="memory")this.store.set(t,o);if(r==="disk")await h(t,o);if(r==="hybrid")this.store.set(t,o),await h(t,o)}delete(t){this.store.delete(t)}}var g=new E;var j=[18,144,240,360,480,720,1080,1440,2160],_={"yt-dlp":"yt-dlp"},q="%(ytId)s.%(ext)s",R={ID:"%(id)s",YT_ID:"%(ytId)s"};import{spawn as k}from"node:child_process";import{stdout as b,stderr as I}from"node:process";function Y(t,e){(t==="data"?b:I).write(e)}function w(t,e,r){let o=_[t];return new Promise((s,n)=>{let m=k(o,e),p="",u="";m.stdout.on("data",(i)=>{p+=i;let a=i.toString();if(r)Y("data",a)}),m.stderr.on("data",(i)=>{u+=i;let a=i.toString();if(r)Y("err",a)}),m.on("close",(i)=>{if(i===0)s(p.toString());else n(Error(u.toString()))}),m.on("error",(i)=>{n(i)})})}function A(t,e){let r=t;for(let[o,s]of e)r=r.replaceAll(o,s);return r}function v(t){return t.replaceAll("/","⁄")}function M({filename:t,id:e,ytId:r}){let o=new Map([[R.ID,e],[R.YT_ID,r]]),s=A(t,o);return v(s)}class C{async download(t,e,r){let o=this.buildYtDlpArgs(t,e,r);return await w("yt-dlp",o,!0),{duration:-1,path:"unknown"}}buildYtDlpArgs(t,e,r){let{id:o,type:s}=r,n=s==="video",m=r.outputPath,p=M({filename:r.filename,id:r.id,ytId:e}),u="aac";return["-f",o,...n?[]:["-x","--audio-format","aac"],"-o",p,"-P",m,t]}}async function tt(t,e){if(!t||!e.id)return;let r=P("video",e);return new C().download(t,t,r)}async function et(t,e){if(!t||!e.id)return;let r=P("audio",e);return new C().download(t,t,r)}function P(t,e){return{id:e.id,type:t,outputPath:e.outputPath??".",filename:e.filename??q}}function U({a:t,b:e,compareResolution:r,type:o}){let s=o==="video"&&r&&t.quality!==null&&e.quality!==null,n=o==="video"&&r&&t.height!==null&&e.height!==null,m=o==="video"&&t.fps!==null&&e.fps!==null,p=o==="audio"&&t.asr!==null&&e.asr!==null,u=t.tbr!==null&&e.tbr!==null,i=0,a=0;if(s){if((t.quality??0)>(e.quality??0))i+=3;else if((t.quality??0)<(e.quality??0))a+=3}if(n){if((t.height??0)>(e.height??0))i+=3;else if((t.height??0)<(e.height??0))a+=3}if(m){if((t.fps??0)>(e.fps??0))i+=2;else if((t.fps??0)<(e.fps??0))a+=2}if(p){if((t.asr??0)>(e.asr??0))i+=2;else if((t.asr??0)<(e.asr??0))a+=2}if(u){if((t.tbr??0)>(e.tbr??0))i+=1;else if((t.tbr??0)<(e.tbr??0))a+=1}return{aScore:i,bScore:a}}function y(t,e,{type:r,compareResolution:o}){if(!t||!e)return;let{aScore:s,bScore:n}=U({a:t,b:e,type:r,compareResolution:o});return s>n?t:e}function D(t,e,{type:r,compareResolution:o}){if(!t||!e)return;let{aScore:s,bScore:n}=U({a:t,b:e,type:r,compareResolution:o});return s>n?e:t}async function rt(t,e){let r=Boolean(e.match(/\d/)),o=r?!1:"N/A",s=["--print","%(formats)j",t],m=(await g.get(`formats:${t}`))?.content??"";if(!m){let f;try{f=await w("yt-dlp",s)}catch(S){throw console.error("Error consiguiendo el ID del formato"),S}if(typeof f!=="string")throw Error("La salida del proceso es de tipo inválido (se esperaba string)");m=f,g.set(`formats:${t}`,{content:m})}let p=[];try{p=JSON.parse(m)}catch(f){throw console.error("Error convirtiendo la salida de yt-dlp a JSON"),f}if(!Array.isArray(p))throw Error("Se esperaba que los formatos fuesen un array. Puede que el contenido cacheado esté corrupto o sea inválido.");let u=void 0,i=void 0,a=void 0,x=void 0,c=void 0;for(let f of p){let S=f.resolution==="audio only";if(r&&f.format_note===e){o=!0,c=y(c,f,{compareResolution:!1,type:"video"})??f;continue}if(S)a=y(a,f,{compareResolution:!1,type:"audio"})??f,x=D(x,f,{compareResolution:!1,type:"audio"})??f;else u=y(u,f,{compareResolution:!0,type:"video"})??f,i=D(i,f,{compareResolution:!0,type:"video"})??f}if(!r)c={"best-video":u,"worst-video":i,"best-audio":a,"worst-audio":x}[e];return{foundSpecific:o,formatId:c?.format_id,desiredFormat:c}}function ot(t){return`https://youtube.com/watch?v=${t}`}export{h as saveInDisk,d as resolvePath,M as resolveFilenamePattern,D as getWorstFormat,T as getFromDisk,y as getBetterFormat,ot as formYoutubeUrl,rt as findFormatId,A as expandPattern,tt as downloadVideo,et as downloadAudio,l as config,g as cache,j as STANDARD_RESOLUTIONS,F as Configuration,E as CacheManager};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yt-kit/core",
3
- "version": "1.0.4",
3
+ "version": "1.0.5",
4
4
  "type": "module",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -13,7 +13,7 @@
13
13
  },
14
14
  "repository": {
15
15
  "type": "git",
16
- "url": "https://github.com/ubiufboeuf/yt-kit.git"
16
+ "url": "git+https://github.com/ubiufboeuf/yt-kit.git"
17
17
  },
18
18
  "bugs": {
19
19
  "url": "https://github.com/ubiufboeuf/yt-kit/issues"