hlsdownloader 5.0.3 โ†’ 6.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -39,15 +39,16 @@ Downloads HLS Playlist file and TS chunks. You can use it for content pre-fetchi
39
39
 
40
40
  ## Features
41
41
 
42
+ - **Event Based:** Event based API
42
43
  - **Modern ESM**: Optimized for Node.js 20+ environments using native modules.
43
- - **Retryable**: Built-in resilience that automatically retries failed segment requests to ensure download completion.
44
+ - **TypeScript Native:** Built with strong typing for mission-critical applications.
45
+ - **Resilient Networking and Retryable**: Built-in resilience that automatically retries with exponential backoff of failed segment requests to ensure download completion.
44
46
  - **Promise Based**: Fully asynchronous API designed for seamless integration with `async/await` and modern control flows.
45
47
  - **Support for HTTP/2**: Leverages multiplexing to download multiple segments over a single connection for reduced overhead.
46
48
  - **Overwrite Protection**: Safeguards your local data by preventing accidental overwriting of existing files unless explicitly enabled.
47
49
  - **Support for Custom HTTP Headers**: Allows injection of custom headers for handling authentication, user-agents, or session tokens.
48
- - **Support for Custom HTTP Client**: Modular architecture that lets you swap the default engine for any custom client implementation.
49
- - **Bring Your Own Progress Bar**: Exposed event hooks and lifecycle data allow you to hook in any CLI or GUI progress visualization.
50
50
  - **Concurrent Downloads**: Maximizes bandwidth by fetching multiple HLS segments simultaneously through parallel HTTP connections.
51
+ - **Proxy and NoProxy Support:** Proxy support and No Proxy support (undici integration).
51
52
  - **Professional Docs**: Integrated JSDoc-to-HTML pipeline using TypeDoc and the Fresh theme.
52
53
 
53
54
  ---
@@ -60,70 +61,109 @@ npm install hlsdownloader
60
61
 
61
62
  ## Examples
62
63
 
63
- ### Basic Usage
64
+ #### Example 1: Basic Download with Event Monitoring
64
65
 
65
- ```ts
66
- import HLSDowloader from 'hlsdownloader';
66
+ This is the standard implementation for saving a remote HLS stream to a local directory.
67
67
 
68
- const downloader = new HLSDownloader({
69
- playlistURL: '[https://example.com/stream/master.m3u8](https://example.com/stream/master.m3u8)',
70
- destination: './downloads/my-video',
71
- });
68
+ ```ts
69
+ import { HLSDownloader } from 'hlsdownloader';
70
+
71
+ async function downloadStream() {
72
+ const downloader = new HLSDownloader({
73
+ playlistURL: 'https://example.com/video/master.m3u8',
74
+ destination: './downloads/my-video',
75
+ overwrite: true,
76
+ concurrency: 5, // Process 5 segments simultaneously
77
+ retry: { limit: 3, delay: 1000 },
78
+ timeout: 15000,
79
+ });
80
+
81
+ downloader.on('start', ({ total }) => console.log(`start downloading assets...`));
82
+
83
+ // Listen to progress updates
84
+ downloader.on('progress', data => {
85
+ const percent = ((data.total / data.total) * 100).toFixed(2); // Simple logic for example
86
+ console.log(`[Progress] Downloaded: ${data.url}`);
87
+ });
88
+
89
+ // Handle errors for specific segments
90
+ downloader.on('error', err => {
91
+ console.error(`[Segment Error] Failed to fetch ${err.url}: ${err.message}`);
92
+ });
93
+
94
+ // Final summary
95
+ const summary = await downloader.startDownload();
96
+ console.log(`Finished! Total items: ${summary.total}. Errors: ${summary.errors.length}`);
97
+ }
72
98
 
73
- const summary = await downloader.startDownload();
74
- console.log(`Downloaded ${summary.total} segments to ${summary.path}`);
99
+ downloadStream();
75
100
  ```
76
101
 
77
- ### Using as CDN Primer
102
+ #### Example 2: "Dry-Run" / CDN Priming (No File Writing)
78
103
 
79
- ```ts
80
- import HLSDowloader from 'hlsdownloader';
104
+ If the destination is omitted, the library fetches streams but doesn't write to disk. This is excellent for `CDN Priming` or `validating manifest health`.
81
105
 
82
- const downloader = new HLSDownloader({
83
- playlistURL: '[https://example.com/stream/master.m3u8](https://example.com/stream/master.m3u8)',
84
- });
106
+ ```ts
107
+ import { HLSDownloader } from 'hlsdownloader';
108
+
109
+ async function primeCDN() {
110
+ const downloader = new HLSDownloader({
111
+ playlistURL: 'https://cdn.provider.com/live/stream.m3u8',
112
+ // destination is omitted -> results in memory-only stream fetch
113
+ concurrency: 10,
114
+ headers: {
115
+ Authorization: 'Bearer internal-token-123',
116
+ 'X-Custom-Source': 'Prewarm-Service',
117
+ },
118
+ });
119
+
120
+ downloader.on('start', ({ total }) => console.log(`Priming ${total} assets...`));
121
+
122
+ const result = await downloader.startDownload();
123
+
124
+ if (result.errors.length === 0) {
125
+ console.log('CDN Cache successfully warmed.');
126
+ } else {
127
+ console.error('Priming failed for some chunks', result.errors);
128
+ }
129
+ }
85
130
 
86
- const summary = await downloader.startDownload();
87
- console.log(`Fetching ${summary.total} segments to Edge servers`);
131
+ primeCDN();
88
132
  ```
89
133
 
90
- ### Advanced Usage
134
+ #### Example 3: Corporate Proxy & Advanced Networking
135
+
136
+ If you are using behind corporate proxy, pass the proxy and no proxy configuration as follows
91
137
 
92
138
  ```ts
93
- import { HLSDownloader } from 'hlsdownloader-ts';
139
+ import { HLSDownloader } from 'hlsdownloader';
94
140
 
95
141
  const downloader = new HLSDownloader({
96
- playlistURL: 'https://example.com/video.m3u8',
97
- concurrency: 10, // 10 simultaneous downloads (optional: 1)
98
- destination: './output', // path to downlod (optional: '')
99
- overwrite: true, // Overwrite existing files. (optional: false)
142
+ playlistURL: 'https://secure-stream.corp.internal/index.m3u8',
143
+ destination: '/mnt/storage/archive',
144
+ proxy: 'http://proxy.corporate.net:8080',
145
+ noProxy: '.internal.com,localhost', // Bypass proxy for internal domains
146
+ headers: {
147
+ Cookie: 'session_id=abc123',
148
+ 'User-Agent': 'MediaArchiver/1.0',
149
+ },
100
150
  });
101
151
 
102
- const { total, errors } = await downloader.startDownload();
152
+ downloader.on('start', ({ total }) => console.log(`Priming ${total} assets...`));
103
153
 
104
- if (errors.length > 0) {
105
- console.error(`${errors.length} segments failed.`, errors);
106
- }
107
- ```
154
+ // Listen to progress updates
155
+ downloader.on('progress', data => {
156
+ const percent = ((data.total / data.total) * 100).toFixed(2); // Simple logic for example
157
+ console.log(`[Progress] Downloaded: ${data.url}`);
158
+ });
108
159
 
109
- HLSDownloader supports all [Ky API](https://github.com/sindresorhus/ky?tab=readme-ov-file#api) except these options given below
110
-
111
- - uri
112
- - url
113
- - json
114
- - form
115
- - body
116
- - method
117
- - setHost
118
- - isStream
119
- - parseJson
120
- - prefixUrl
121
- - cookieJar
122
- - playlistURL
123
- - concurrency
124
- - allowGetBody
125
- - stringifyJson
126
- - methodRewriting
160
+ // Handle errors for specific segments
161
+ downloader.on('error', err => {
162
+ console.error(`[Segment Error] Failed to fetch ${err.url}: ${err.message}`);
163
+ });
164
+
165
+ const summary = await downloader.startDownload();
166
+ ```
127
167
 
128
168
  ## API Documentation
129
169
 
@@ -139,24 +179,36 @@ The main service orchestrator for fetching HLS content.
139
179
 
140
180
  ### DownloaderOptions (Interface)
141
181
 
142
- | Property | Type | Default | Description |
143
- | ----------- | ---------- | ------------- | ------------------------------------------------------- |
144
- | playlistURL | `string` | **Required** | The absolute URL to the M3U8 file. |
145
- | destination | `string` | `''` | Local path to save files. |
146
- | concurrency | `number` | `os.cpus - 1` | Max parallel network requests. |
147
- | overwrite | `boolean` | `false` | Indicates whether existing files should be overwritten. |
148
- | onData | `callback` | `null` | The local directory where files will be saved. |
149
- | onError | `callback` | `null` | The local directory where files will be saved. |
182
+ | Option | Type | Default | Description |
183
+ | ----------- | --------- | ------------------------ | ------------------------------------------------------------------------------------------ |
184
+ | playlistURL | `string` | Required | The source .m3u8 URL. |
185
+ | destination | `string` | undefined | Local path to save files. Omit for "dry-run" mode. |
186
+ | concurrency | `number` | os.cpus().length | Simultaneous segment downloads. |
187
+ | overwrite | `boolean` | false | Overwrite existing files in the destination. |
188
+ | headers | `object` | {} | Custom headers to pass |
189
+ | timeout | `number` | 10000 | Network request timeout in ms. |
190
+ | retry | `object` | { limit: 1, delay: 500 } | Exponential backoff settings. |
191
+ | proxy | `string` | undefined | Corporate proxy URL. Also reads URLs for `HTTP_PROXY`, `HTTPS_PROXY` environment variables |
192
+ | noProxy | `string` | undefined | Corporate No Proxy Urls. Also reads urls from `NO_PROXY` environment vriable |
193
+
194
+ ### DownloaderEvents (Interface)
195
+
196
+ | Event Name | Description |
197
+ | ---------- | -------------------------------------------- |
198
+ | start | emits when download started |
199
+ | progress | emits for each segement downloded |
200
+ | error | emits when a segement downlod error occurred |
201
+ | end | emits when download ended |
150
202
 
151
203
  ### DownloadSummary (Interface)
152
204
 
153
- | Property | Type | Description | Description |
154
- | -------- | ----------------- | ------------------------------------- | ---------------------------------- |
155
- | total | `number` | Count of successfully saved segments. | The absolute URL to the M3U8 file. |
156
- | path | `string` | The final output directory. | Local path to save files. |
157
- | errors | `DownloadError[]` | Array of detailed failure objects. | Max parallel network requests. |
205
+ | Property | Type | Description |
206
+ | -------- | ----------------- | ------------------------------------- |
207
+ | total | `number` | Count of successfully saved segments. |
208
+ | message | `string` | User friendly message. |
209
+ | errors | `DownloadError[]` | Array of detailed failure objects. |
158
210
 
159
- ### SegmentDownloadedData (Interface) - `onData` Hook
211
+ ### SegmentDownloadedData (Interface) - emits on `progress` events
160
212
 
161
213
  | Property | Type | Description |
162
214
  | -------- | -------- | -------------------------------------------------------------------------- |
@@ -166,7 +218,7 @@ The main service orchestrator for fetching HLS content.
166
218
 
167
219
  ---
168
220
 
169
- ### SegmentDownloadErrorData (Interface) - `onError` Hook
221
+ ### SegmentDownloadErrorData (Interface) - emits on `error` events
170
222
 
171
223
  | Property | Type | Description |
172
224
  | -------- | -------- | ---------------------------------------------------------- |
@@ -188,10 +240,11 @@ Contributions are welcome! This project enforces strict quality standards to mai
188
240
  Fork & Clone: Get the repo locally.
189
241
 
190
242
  - `Install`: `npm install`
243
+ - `Test`: `npm run test` (Must pass without warnings)
191
244
  - `Lint`: `npm run lint` (Must pass without warnings)
192
- - `Test`: `npm run test:coverage` (Must maintain 100% coverage)
193
245
  - `Build`: `npm run build` (Generates `./dist` and bundled types)
194
246
  - `Docs`: `npm run docs` (Generates TypeDoc HTML)
247
+ - `Test with Coverage Report`: `npm run test:coverage` (Must maintain 100% coverage)
195
248
 
196
249
  ### Guidelines
197
250
 
@@ -205,10 +258,6 @@ Contributions, issues and feature requests are welcome!<br />Feel free to check
205
258
 
206
259
  Give a โญ๏ธ if this project helped you!. I will be grateful if you all help me to improve this package by giving your suggestions, feature request and pull requests. I am all ears!!
207
260
 
208
- ## Special Thanks to
209
-
210
- - [Ky Team](https://www.npmjs.com/package/ky)
211
-
212
261
  ## License
213
262
 
214
263
  Copyright ยฉ 2026 [Nur Rony](https://github.com/nurrony).<br />
package/dist/index.d.ts CHANGED
@@ -1,5 +1,26 @@
1
1
  // Generated by dts-bundle-generator v9.5.1
2
2
 
3
+ import { EventEmitter } from 'node:events';
4
+
5
+ export interface HttpClientOptions {
6
+ timeout?: number;
7
+ retry?: {
8
+ limit: number;
9
+ delay: number;
10
+ };
11
+ proxy?: string;
12
+ noProxy?: string[];
13
+ headers?: Record<string, string>;
14
+ }
15
+ export interface DownloaderEvents {
16
+ start: (data: {
17
+ total: number;
18
+ destination: string;
19
+ }) => void;
20
+ progress: (data: SegmentDownloadedData) => void;
21
+ error: (error: DownloadError) => void;
22
+ end: (summary: DownloadSummary) => void;
23
+ }
3
24
  export interface DownloadError {
4
25
  url: string;
5
26
  name: string;
@@ -15,13 +36,11 @@ export interface SegmentDownloadErrorData {
15
36
  name: string;
16
37
  message: string;
17
38
  }
18
- export interface DownloaderOptions {
39
+ export interface DownloaderOptions extends HttpClientOptions {
19
40
  playlistURL: string;
20
41
  destination?: string;
21
42
  overwrite?: boolean;
22
43
  concurrency?: number;
23
- onData?: (data: SegmentDownloadedData) => void;
24
- onError?: (error: SegmentDownloadErrorData) => void;
25
44
  [key: string]: any;
26
45
  }
27
46
  export interface DownloadSummary {
@@ -29,19 +48,18 @@ export interface DownloadSummary {
29
48
  errors: DownloadError[];
30
49
  message: string;
31
50
  }
32
- declare class Downloader {
51
+ declare class Downloader extends EventEmitter {
33
52
  private options;
53
+ private items;
34
54
  private playlistURL;
35
- private onData;
36
- private onError;
37
55
  private pool;
38
56
  private http;
39
57
  private fileService;
40
- private items;
41
58
  private errors;
42
59
  private concurrency;
43
60
  constructor(options: DownloaderOptions);
44
61
  startDownload(): Promise<DownloadSummary>;
62
+ emit(event: string | symbol, ...args: any[]): boolean;
45
63
  private processQueue;
46
64
  private downloadFile;
47
65
  private handleError;
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{cpus as k}from"node:os";import F from"p-limit";import{URL as w}from"node:url";var m=class s extends Error{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,s.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},f=m;var a=class{static isValidUrl(t,r=["http:","https:","ftp:","sftp:"]){let{protocol:e}=new w(t);if(e&&!r.includes(e))throw new f(`${e} is not supported. Supported protocols are ${r.join(", ")}`);return!0}static stripFirstSlash(t){return t.startsWith("/")?t.substring(1):t}static isValidPlaylist(t){return/^#EXTM3U/im.test(t)}static parseUrl(t){return new w(t)}static omit(t,...r){let e=new Set(r.flat());return Object.fromEntries(Object.entries(t).filter(([o])=>!e.has(o)))}static isNotFunction(t){return typeof t!="function"}};import{constants as L,createWriteStream as U}from"node:fs";import*as n from"node:fs/promises";import S from"node:path";import{Readable as R}from"node:stream";import{pipeline as T}from"node:stream/promises";var h=class{destination;overwrite;constructor(t,r=!1){this.destination=t,this.overwrite=r}async getTargetPath(t){let{pathname:r}=a.parseUrl(t);return S.join(this.destination,a.stripFirstSlash(r))}async prepareDirectory(t){let r=await this.getTargetPath(t),e=S.dirname(r);return await n.mkdir(e,{recursive:!0}),r}async canWrite(t){try{let r=await this.getTargetPath(t);return await n.access(r,L.F_OK),this.overwrite}catch(r){if(r.code==="ENOENT")return!0;throw r}}async saveStream(t,r){let e=R.fromWeb(t),o=U(r);try{await T(e,o)}catch(i){throw await n.unlink(r).catch(()=>{}),i}}},D=h;import E from"ky";var d=class s extends Error{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,s.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},v=d;var u=class s{options;static defaultKyOptions={retry:{limit:0}};static unSupportedOptions=["uri","url","json","form","body","method","setHost","isStream","parseJson","prefixUrl","cookieJar","playlistURL","concurrency","allowGetBody","stringifyJson","methodRewriting"];constructor(t={}){this.options=Object.assign({},s.defaultKyOptions,a.omit(t,...s.unSupportedOptions))}async fetchText(t){let r=await E.get(t,{...this.options}).text();if(!a.isValidPlaylist(r))throw new v("Invalid playlist");return r}async getStream(t){let r=await E.get(t,{...this.options});if(!r.body)throw new Error("Response body is null");return r.body}},P=u;import{URL as x}from"node:url";var g=class s{static HLS_PLAYLIST_EXT=".m3u8";parse(t,r){return r.replace(/^#[\s\S].*/gim,"").split(/\r?\n/).filter(e=>e.trim()!=="").map(e=>new x(e,t).href)}isPlaylist(t){return t.toLowerCase().endsWith(s.HLS_PLAYLIST_EXT)}},c=new g;var y=class{constructor(t){this.options=t;let{onData:r,onError:e,destination:o="",playlistURL:i="",overwrite:p=!1,concurrency:l=Math.max(1,k().length-1),...O}=t||{};this.onData=r,this.onError=e,this.playlistURL=i,this.pool=F(l),this.concurrency=l,this.http=new P(O),this.fileService=new D(o,p),this.items=[i]}playlistURL;onData;onError;pool;http;fileService;items;errors=[];concurrency=1;async startDownload(){try{a.isValidUrl(this.playlistURL);let t=await this.http.fetchText(this.playlistURL),r=c.parse(this.playlistURL,t);this.items.push(...r);let e=r.filter(i=>c.isPlaylist(i));return(await Promise.allSettled(e.map(i=>this.http.fetchText(i)))).forEach((i,p)=>{if(i.status==="fulfilled"){let l=c.parse(e[p],i.value);this.items.push(...l)}}),await this.processQueue(),this.generateSummary()}catch(t){return this.handleError(this.playlistURL,t),this.generateSummary()}}async processQueue(){let t=this.items.length;if(this.fileService.destination){if(!await this.fileService.canWrite(this.playlistURL))throw new Error("Directory already exists and overwrite is disabled");let e=this.items.map(o=>this.pool(()=>this.downloadFile(o)));return Promise.allSettled(e)}let r=this.items.map(e=>this.pool(async()=>{try{let o=await this.http.getStream(e);return this.onData&&this.onData({url:e,total:t}),o}catch(o){this.handleError(e,o)}}));return Promise.allSettled(r)}async downloadFile(t){try{let r=await this.http.getStream(t),e=await this.fileService.prepareDirectory(t);await this.fileService.saveStream(r,e),this.onData&&this.onData({url:t,path:e,total:this.items.length})}catch(r){this.handleError(t,r)}}handleError(t,r){let e={url:t,name:r.name,message:r.message};this.errors.push(e),this.onError&&this.onError(e)}generateSummary(){return{errors:this.errors,total:this.items.length,message:this.errors.length>0?"Download ended with errors":"Downloaded successfully"}}},b=y;var mt=b;export{b as HLSDownloader,mt as default};
1
+ import{EventEmitter as k}from"node:events";import{cpus as A}from"node:os";import C from"p-limit";import{URL as v}from"node:url";var h=class l extends Error{constructor(r){super(r),this.name=this.constructor.name,Object.setPrototypeOf(this,l.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},f=h;var n=class{static isValidUrl(r,t=["http:","https:","ftp:","sftp:"]){let{protocol:e}=new v(r);if(e&&!t.includes(e))throw new f(`${e} is not supported. Supported protocols are ${t.join(", ")}`);return!0}static stripFirstSlash(r){return r.startsWith("/")?r.substring(1):r}static isValidPlaylist(r){return/^#EXTM3U/im.test(r)}static parseUrl(r){return new v(r)}static omit(r,...t){let e=new Set(t.flat());return Object.fromEntries(Object.entries(r).filter(([s])=>!e.has(s)))}static isNotFunction(r){return typeof r!="function"}static async sleep(r){return new Promise(t=>setTimeout(t,r))}};import{constants as x,createWriteStream as O}from"node:fs";import*as m from"node:fs/promises";import S from"node:path";import{Readable as L}from"node:stream";import{pipeline as T}from"node:stream/promises";var d=class{destination;overwrite;constructor(r,t=!1){this.destination=r,this.overwrite=t}async getTargetPath(r){let{pathname:t}=n.parseUrl(r);return S.join(this.destination,n.stripFirstSlash(t))}async prepareDirectory(r){let t=await this.getTargetPath(r),e=S.dirname(t);return await m.mkdir(e,{recursive:!0}),t}async canWrite(r){try{let t=await this.getTargetPath(r);return await m.access(t,x.F_OK),this.overwrite}catch(t){if(t.code==="ENOENT")return!0;throw t}}async saveStream(r,t){let e=L.fromWeb(r),s=O(t);try{await T(e,s)}catch(i){throw await m.unlink(t).catch(()=>{}),i}}},D=d;import{ProxyAgent as U}from"undici";var u=class l extends Error{constructor(r){super(r),this.name=this.constructor.name,Object.setPrototypeOf(this,l.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},P=u;var y=class{options;primaryOrigin=null;sensitiveHeaders=["authorization","cookie","x-auth-token"];timeout;retryOptions;dispatcher;noProxy=[];constructor(r={}){if(this.options={method:"GET",headers:{"User-Agent":"HLSDownloader"}},r.headers){let s={};for(let[i,o]of Object.entries(r.headers))s[i.toLowerCase()]=o;this.options.headers={"User-Agent":"HLSDownloader",...this.options.headers,...s}}this.timeout=r.timeout??5e3,this.retryOptions=r.retry??{limit:1,delay:500};let t=process.env.NO_PROXY||process.env.no_proxy||"";this.noProxy=r.noProxy??t.split(",").map(s=>s.trim()).filter(Boolean);let e=r.proxy||process.env.HTTPS_PROXY||process.env.HTTP_PROXY;e&&(this.dispatcher=new U({uri:e}))}setPrimaryOrigin(r){try{this.primaryOrigin=new URL(r).origin}catch{this.primaryOrigin=null}}getRequestHeaders(r){let t={...this.options.headers};try{let e=new URL(r).origin;this.primaryOrigin&&e!==this.primaryOrigin&&this.sensitiveHeaders.forEach(s=>{delete t[s]})}catch{}return t}shouldBypassProxy(r){if(!this.dispatcher)return!0;let t=new URL(r).hostname;return this.noProxy.some(e=>t===e||e.startsWith(".")&&t.endsWith(e))}async requestWithRetry(r,t=0){let e=new AbortController,s=setTimeout(()=>e.abort(),this.timeout);try{let i=await fetch(r,{...this.options,headers:this.getRequestHeaders(r),signal:e.signal,dispatcher:this.shouldBypassProxy(r)?void 0:this.dispatcher});return clearTimeout(s),!i.ok&&(i.status>=500||i.status===429)&&t<this.retryOptions.limit?this.handleRetry(r,t):i}catch(i){if(clearTimeout(s),(i.name==="AbortError"||i.name==="TypeError"||i.status&&i.status>=500)&&t<this.retryOptions.limit)return this.handleRetry(r,t);throw i}}async handleRetry(r,t){let e=this.retryOptions.delay*Math.pow(2,t);return await n.sleep(e),this.requestWithRetry(r,t+1)}async fetchText(r){let e=await(await this.requestWithRetry(r)).text();if(!n.isValidPlaylist(e))throw new P("Invalid playlist");return e}async getStream(r){let t=await this.requestWithRetry(r);if(!t.body)throw new Error("Response body is null");return t.body}},b=y;import{URL as H}from"node:url";var g=class l{static HLS_PLAYLIST_EXT=".m3u8";parse(r,t){return t.replace(/^#[\s\S].*/gim,"").split(/\r?\n/).filter(e=>e.trim()!=="").map(e=>new H(e,r).href)}isPlaylist(r){return r.toLowerCase().endsWith(l.HLS_PLAYLIST_EXT)}},p=new g;var w=class extends k{constructor(t){super();this.options=t;let{destination:e="",playlistURL:s="",overwrite:i=!1,concurrency:o=Math.max(1,A().length-1),headers:a={},...c}=t||{};this.playlistURL=s,this.pool=C(o),this.concurrency=o,this.http=new b({headers:a,...c}),this.http.setPrimaryOrigin(this.playlistURL),this.fileService=new D(e,i),this.items.add(this.playlistURL)}items=new Set;playlistURL;pool;http;fileService;errors=[];concurrency=1;async startDownload(){try{n.isValidUrl(this.playlistURL);let t=await this.http.fetchText(this.playlistURL),e=p.parse(this.playlistURL,t);e.forEach(a=>this.items.add(a));let s=e.filter(a=>p.isPlaylist(a));(await Promise.allSettled(s.map(a=>this.http.fetchText(a)))).forEach((a,c)=>{a.status==="fulfilled"&&p.parse(s[c],a.value).forEach(E=>this.items.add(E))}),this.emit("start",{total:this.items.size,destination:this.options.destination}),await this.processQueue();let o=this.generateSummary();return this.emit("end",o),o}catch(t){return this.handleError(this.playlistURL,t),this.generateSummary()}}emit(t,...e){return super.emit(t,...e)}async processQueue(){let t=this.items.size,e=Array.from(this.items);if(this.fileService.destination){if(!await this.fileService.canWrite(this.playlistURL))throw new Error("Directory already exists and overwrite is disabled");let i=e.map(o=>this.pool(()=>this.downloadFile(o)));return Promise.allSettled(i)}let s=e.map(i=>this.pool(async()=>{try{let o=await this.http.getStream(i);return this.emit("progress",{url:i,total:t}),o}catch(o){this.handleError(i,o)}}));return Promise.allSettled(s)}async downloadFile(t){try{let e=await this.http.getStream(t),s=await this.fileService.prepareDirectory(t);await this.fileService.saveStream(e,s),this.emit("progress",{url:t,path:s,total:this.items.size})}catch(e){this.handleError(t,e)}}handleError(t,e){let s={url:t,name:e.name,message:e.message};this.errors.push(s),this.emit("error",s)}generateSummary(){return{errors:this.errors,total:this.items.size,message:this.errors.length>0?"Download ended with errors":"Downloaded successfully"}}},R=w;var gt=R;export{R as HLSDownloader,gt as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hlsdownloader",
3
- "version": "5.0.3",
3
+ "version": "6.0.1",
4
4
  "description": "Downloads HLS Playlist file and TS chunks",
5
5
  "snyk": true,
6
6
  "main": "./dist/index.js",
@@ -25,13 +25,13 @@
25
25
  "prepublishOnly": "echo '๐Ÿš€ Release: Final automated validation gate before NPM publishing.' && npm run build",
26
26
  "build:types": "echo '๐Ÿท๏ธ Generating Types' && dts-bundle-generator -o dist/index.d.ts src/index.ts --no-check --silent",
27
27
  "docs": "rimraf -fr ./docs && echo '๐Ÿงน All documentation has been cleaned.' && echo '๐Ÿ“ Generating documentation...' && jsdoc -c jsdoc.json",
28
- "build:bundle": "esbuild src/index.ts --bundle --packages=external --platform=node --format=esm --target=node20 --minify --tree-shaking=true --outfile=dist/index.js",
28
+ "build:bundle": "esbuild src/index.ts --bundle --packages=external --external:undici --platform=node --format=esm --target=node20 --minify --tree-shaking=true --outfile=dist/index.js",
29
29
  "build": "echo '๐Ÿ“ฆ Bundles ESM source and generates minified distribution files.' && npm run typecheck && rimraf -fr ./dist && npm run build:types && npm run build:bundle",
30
30
  "test:coverage": "rimraf -fr ./coverage && echo '๐Ÿงน All test coverage reports has been cleaned.' && c8 npm test && echo '๐Ÿ“Š Coverage: Validates 100% code coverage across all source files successfully.'"
31
31
  },
32
32
  "dependencies": {
33
- "ky": "^1.14.3",
34
- "p-limit": "^7.3.0"
33
+ "p-limit": "^7.3.0",
34
+ "undici": "^7.22.0"
35
35
  },
36
36
  "devDependencies": {
37
37
  "@babel/core": "^7.29.0",
@@ -39,14 +39,14 @@
39
39
  "@commitlint/cli": "^20.4.2",
40
40
  "@commitlint/config-conventional": "^20.4.2",
41
41
  "@eslint/js": "^10.0.1",
42
- "@types/node": "^25.3.0",
42
+ "@types/node": "^25.3.2",
43
43
  "@types/web": "^0.0.338",
44
44
  "c8": "^11.0.0",
45
45
  "clean-jsdoc-theme": "^4.3.0",
46
46
  "cz-conventional-changelog": "^3.3.0",
47
47
  "dts-bundle-generator": "^9.5.1",
48
- "eslint": "^10.0.1",
49
- "eslint-plugin-jsdoc": "^62.7.0",
48
+ "eslint": "^10.0.2",
49
+ "eslint-plugin-jsdoc": "^62.7.1",
50
50
  "jsdoc": "^4.0.5",
51
51
  "jsdoc-babel": "^0.5.0",
52
52
  "lefthook": "^2.1.1",