@boy-offi9-inc/tidepull 0.5.0 → 0.7.0

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.
Files changed (60) hide show
  1. package/README.md +5 -5
  2. package/dist/cliutil.d.ts +0 -8
  3. package/dist/cliutil.js +0 -10
  4. package/dist/cookies.d.ts +0 -5
  5. package/dist/cookies.js +0 -10
  6. package/dist/core/downloader.d.ts +1 -10
  7. package/dist/core/downloader.js +44 -9
  8. package/dist/core/errors.d.ts +0 -2
  9. package/dist/core/errors.js +0 -2
  10. package/dist/core/events.d.ts +0 -2
  11. package/dist/core/hls.d.ts +0 -2
  12. package/dist/core/hls.js +2 -3
  13. package/dist/core/http.d.ts +0 -13
  14. package/dist/core/http.js +0 -7
  15. package/dist/core/meter.d.ts +0 -1
  16. package/dist/core/meter.js +0 -1
  17. package/dist/core/pipeline.d.ts +1 -13
  18. package/dist/core/pipeline.js +16 -8
  19. package/dist/core/selector.d.ts +0 -10
  20. package/dist/core/selector.js +0 -1
  21. package/dist/core/template.d.ts +0 -1
  22. package/dist/core/template.js +0 -1
  23. package/dist/core/types.d.ts +7 -13
  24. package/dist/dash/index.js +43 -9
  25. package/dist/dash/parse.d.ts +1 -3
  26. package/dist/dash/parse.js +83 -83
  27. package/dist/dash/xml.js +0 -1
  28. package/dist/extractors/direct.js +0 -1
  29. package/dist/extractors/generic.d.ts +0 -1
  30. package/dist/extractors/generic.js +0 -2
  31. package/dist/extractors/hls.js +6 -3
  32. package/dist/extractors/index.d.ts +0 -1
  33. package/dist/extractors/index.js +0 -1
  34. package/dist/feeds.d.ts +0 -2
  35. package/dist/feeds.js +0 -9
  36. package/dist/index.d.ts +0 -1
  37. package/dist/index.js +0 -1
  38. package/dist/loader.d.ts +0 -2
  39. package/dist/loader.js +0 -3
  40. package/dist/main.d.ts +0 -1
  41. package/dist/main.js +3 -8
  42. package/dist/playlist.d.ts +0 -18
  43. package/dist/playlist.js +0 -15
  44. package/dist/plugins.d.ts +0 -2
  45. package/dist/plugins.js +0 -2
  46. package/dist/tidepull.d.ts +0 -21
  47. package/dist/tidepull.js +0 -18
  48. package/dist/ui/banner.d.ts +0 -1
  49. package/dist/ui/banner.js +0 -2
  50. package/dist/ui/format.d.ts +0 -1
  51. package/dist/ui/format.js +0 -1
  52. package/dist/ui/log.d.ts +0 -2
  53. package/dist/ui/log.js +0 -2
  54. package/dist/ui/render.d.ts +0 -2
  55. package/dist/ui/render.js +0 -3
  56. package/dist/ui/spinner.d.ts +0 -5
  57. package/dist/ui/spinner.js +0 -5
  58. package/dist/ui/theme.d.ts +0 -5
  59. package/dist/ui/theme.js +0 -2
  60. package/package.json +1 -1
package/README.md CHANGED
@@ -183,15 +183,15 @@ From a clone, `node src/cli.ts <args>` runs the TypeScript source directly (Node
183
183
  - No site-specific extractors are built in. Platforms such as YouTube hide their media behind scripts and tokens and need a plugin
184
184
  - No DRM: protected streams (Widevine, PlayReady, FairPlay, encrypted DASH) are not supported and will not be
185
185
  - No circumvention: it cannot get past logins, paywalls or geo-blocks. With `--cookies` it only fetches what your own session can already see
186
- - Not implemented yet: live streams, multi-period DASH (first period only), SAMPLE-AES, subtitles, playlists from video sites (they need a plugin), a proxy option
186
+ - Not implemented yet: live streams, SAMPLE-AES, fMP4 subtitle tracks (WebVTT segment playlists only), playlists from video sites (they need a plugin), a proxy option
187
187
  - Cookies are read-only: `Set-Cookie` responses are not stored
188
188
 
189
189
  ### Details
190
190
  | Area | Behavior |
191
191
  |---|---|
192
192
  | Direct files | resumable (`.part` + `Range`), retries with backoff |
193
- | HLS VOD | master + media playlists, parallel segments written in order, AES-128 (explicit/default IV), fMP4 init maps, `EXT-X-BYTERANGE` segments and ranged init maps, separate audio renditions |
194
- | DASH VOD (`.mpd`), opt-in via `@boy-offi9-inc/tidepull/dash` (built into the CLI) | `SegmentTemplate` (`$Number%05d$`, `$Time$`, timelines, durations), `SegmentList`, single-file `SegmentBase`, nested `BaseURL`; encrypted (`ContentProtection`) representations are skipped, never decrypted |
193
+ | HLS VOD | master + media playlists, parallel segments written in order, AES-128 (explicit/default IV), fMP4 init maps, `EXT-X-BYTERANGE` segments and ranged init maps, separate audio renditions, `SUBTITLES` renditions with `--write-subs` (WebVTT segments joined into one `.vtt` per language) |
194
+ | DASH VOD (`.mpd`), opt-in via `@boy-offi9-inc/tidepull/dash` (built into the CLI) | `SegmentTemplate` (`$Number%05d$`, `$Time$`, timelines, durations), `SegmentList`, single-file `SegmentBase`, nested `BaseURL`; multiple `Period`s merged by representation (fragments concatenated in order, init from the first period); encrypted (`ContentProtection`) representations are skipped, never decrypted |
195
195
  | Generic page extractor | `og:video`, `<video>/<source>`, bare media URLs in HTML/JSON |
196
196
  | Format selector | `b bv bv* ba ba* w wv wa`, `+` merge, `/` fallback, `()` groups, `[height<=720]` `[filesize<?50M]` `[ext=mp4]` |
197
197
  | Output templates | `%(title)s`, `%(x\|default)s`, `%(title).50s`, `%(n)02d`, sanitized |
@@ -205,8 +205,8 @@ The core does only what every user needs: extract → select → download, event
205
205
 
206
206
  | Import | Files | Raw | Gzip | Minified (gzip) |
207
207
  |---|---|---|---|---|
208
- | `@boy-offi9-inc/tidepull` (core: direct, HLS, generic page, selector, templates, resume, merge, playlists contract) | 18 | 49.2 KB | 14.7 KB | 24 KB (9.8 KB) |
209
- | `@boy-offi9-inc/tidepull/dash` (adds XML + MPD parsing) | +6 | +14 KB | +4.7 KB | +6.7 KB (+3.1 KB) |
208
+ | `@boy-offi9-inc/tidepull` (core: direct, HLS, generic page, selector, templates, resume, merge, playlists contract) | 18 | 49.6 KB | 13.7 KB | 23 KB (9.7 KB) |
209
+ | `@boy-offi9-inc/tidepull/dash` (adds XML + MPD parsing) | +6 | +14 KB | +4.7 KB | +7.1 KB (+3.3 KB) |
210
210
  | `@boy-offi9-inc/tidepull/feeds` (RSS/Atom + .m3u; shares the XML parser with dash) | +5 | +9 KB | +3.3 KB | +3.8 KB (+1.9 KB) |
211
211
  | `@boy-offi9-inc/tidepull/playlist` (`pullAll`, item selection) | +1 | +3.9 KB | +1.5 KB | +1.9 KB (+1.0 KB) |
212
212
  | `@boy-offi9-inc/tidepull/cookies` (cookies.txt) | +2 | +3.8 KB | +1.6 KB | +1.6 KB (+0.9 KB) |
package/dist/cliutil.d.ts CHANGED
@@ -1,17 +1,9 @@
1
1
  import type { Info } from "./core/types.js";
2
- /** "500K", "1.5M", "2G" or plain bytes per second. */
3
2
  export declare function parseRate(s: string): number;
4
- /** Splits a config line into arguments. Supports 'single' and "double" quotes and \" inside double quotes. */
5
3
  export declare function splitArgs(line: string): string[];
6
- /** One URL per line; blank lines and lines starting with # are ignored. "-" reads stdin. */
7
4
  export declare function readUrlList(file: string): string[];
8
5
  export declare function defaultConfigPath(env?: NodeJS.ProcessEnv): string;
9
- /**
10
- * Arguments from the config file: one or more options per line, # starts a comment.
11
- * Placed before the command line so the command line wins. Returns [] when disabled or absent.
12
- */
13
6
  export declare function configArgs(argv: string[], env?: NodeJS.ProcessEnv): string[];
14
- /** Remembers finished downloads so later runs skip them. One key per line. */
15
7
  export declare class Archive {
16
8
  private file;
17
9
  private keys;
package/dist/cliutil.js CHANGED
@@ -1,9 +1,7 @@
1
- /** CLI-only helpers: config file, batch input, download archive, rate parsing. Not part of the library entry point. */
2
1
  import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
3
2
  import os from "node:os";
4
3
  import path from "node:path";
5
4
  import { TidepullError, errMsg } from "./core/errors.js";
6
- /** "500K", "1.5M", "2G" or plain bytes per second. */
7
5
  export function parseRate(s) {
8
6
  const m = /^(\d+(?:\.\d+)?)([KMG])?$/i.exec(s.trim());
9
7
  if (!m || !(Number(m[1]) > 0))
@@ -11,7 +9,6 @@ export function parseRate(s) {
11
9
  const mult = { K: 1024, M: 1024 ** 2, G: 1024 ** 3 }[(m[2] ?? "").toUpperCase()] ?? 1;
12
10
  return Math.round(Number(m[1]) * mult);
13
11
  }
14
- /** Splits a config line into arguments. Supports 'single' and "double" quotes and \" inside double quotes. */
15
12
  export function splitArgs(line) {
16
13
  const out = [];
17
14
  let cur = "";
@@ -46,7 +43,6 @@ export function splitArgs(line) {
46
43
  out.push(cur);
47
44
  return out;
48
45
  }
49
- /** One URL per line; blank lines and lines starting with # are ignored. "-" reads stdin. */
50
46
  export function readUrlList(file) {
51
47
  let text;
52
48
  try {
@@ -60,10 +56,6 @@ export function readUrlList(file) {
60
56
  export function defaultConfigPath(env = process.env) {
61
57
  return path.join(env.XDG_CONFIG_HOME ?? path.join(os.homedir(), ".config"), "tidepull", "config");
62
58
  }
63
- /**
64
- * Arguments from the config file: one or more options per line, # starts a comment.
65
- * Placed before the command line so the command line wins. Returns [] when disabled or absent.
66
- */
67
59
  export function configArgs(argv, env = process.env) {
68
60
  if (argv.includes("--no-config"))
69
61
  return [];
@@ -87,9 +79,7 @@ export function configArgs(argv, env = process.env) {
87
79
  }
88
80
  return out;
89
81
  }
90
- /** Extractors whose ids are not globally unique (a file name, a playlist path): key them by URL instead. */
91
82
  const BY_URL = new Set(["direct", "hls", "dash", "generic"]);
92
- /** Remembers finished downloads so later runs skip them. One key per line. */
93
83
  export class Archive {
94
84
  file;
95
85
  keys;
package/dist/cookies.d.ts CHANGED
@@ -1,20 +1,15 @@
1
1
  export interface Cookie {
2
2
  domain: string;
3
- /** also valid for subdomains of `domain` */
4
3
  subdomains: boolean;
5
4
  path: string;
6
5
  secure: boolean;
7
- /** seconds since epoch, 0 for a session cookie */
8
6
  expires: number;
9
7
  name: string;
10
8
  value: string;
11
9
  }
12
10
  export declare function parseCookies(text: string): Cookie[];
13
- /** The Cookie header value for `url`, or undefined when no cookie applies. */
14
11
  export declare function cookieHeader(cookies: readonly Cookie[], url: URL, now?: number): string | undefined;
15
- /** Plug into the HTTP client: `createTidepull({ http: { cookies: cookieJar(cookies) } })`. */
16
12
  export declare const cookieJar: (cookies: readonly Cookie[]) => (url: URL) => string | undefined;
17
- /** Reads a cookies.txt file. The warning (if any) says the file is readable by other users. */
18
13
  export declare function loadCookieFile(file: string): {
19
14
  cookies: Cookie[];
20
15
  warning?: string;
package/dist/cookies.js CHANGED
@@ -1,8 +1,3 @@
1
- /**
2
- * Netscape cookies.txt support (opt-in: "@boy-offi9-inc/tidepull/cookies").
3
- * Cookies are sent only to the hosts, paths and schemes they were issued for, and are re-evaluated on every redirect hop.
4
- * Read-only: Set-Cookie responses are not stored. No public-suffix list: only a single-label domain guard.
5
- */
6
1
  import { readFileSync, statSync } from "node:fs";
7
2
  import { TidepullError, errMsg } from "./core/errors.js";
8
3
  export function parseCookies(text) {
@@ -22,14 +17,12 @@ export function parseCookies(text) {
22
17
  const bare = domain.replace(/^\./, "").toLowerCase();
23
18
  if (!bare || !name)
24
19
  continue;
25
- // A domain without a dot ("com") must not match every site under it.
26
20
  const subdomains = (flag.toUpperCase() === "TRUE" || domain.startsWith(".")) && bare.includes(".");
27
21
  out.push({ domain: bare, subdomains, path: path || "/", secure: secure.toUpperCase() === "TRUE", expires: Number(expires) || 0, name, value: rest.join("\t") });
28
22
  }
29
23
  return out;
30
24
  }
31
25
  const pathMatch = (reqPath, cookiePath) => reqPath === cookiePath || (reqPath.startsWith(cookiePath) && (cookiePath.endsWith("/") || reqPath[cookiePath.length] === "/"));
32
- /** The Cookie header value for `url`, or undefined when no cookie applies. */
33
26
  export function cookieHeader(cookies, url, now = Date.now() / 1000) {
34
27
  const host = url.hostname.toLowerCase();
35
28
  const isIp = /^[\d.]+$/.test(host) || host.includes(":");
@@ -41,9 +34,7 @@ export function cookieHeader(cookies, url, now = Date.now() / 1000) {
41
34
  return undefined;
42
35
  return hits.sort((a, b) => b.path.length - a.path.length).map((c) => `${c.name}=${c.value}`).join("; ");
43
36
  }
44
- /** Plug into the HTTP client: `createTidepull({ http: { cookies: cookieJar(cookies) } })`. */
45
37
  export const cookieJar = (cookies) => (url) => cookieHeader(cookies, url);
46
- /** Reads a cookies.txt file. The warning (if any) says the file is readable by other users. */
47
38
  export function loadCookieFile(file) {
48
39
  let text;
49
40
  try {
@@ -61,7 +52,6 @@ export function loadCookieFile(file) {
61
52
  warning = `${file} is readable by other users; run: chmod 600 ${file}`;
62
53
  }
63
54
  catch {
64
- /* permissions are advisory */
65
55
  }
66
56
  return { cookies, warning };
67
57
  }
@@ -3,10 +3,8 @@ import { type HlsKey } from "./hls.js";
3
3
  export interface Progress {
4
4
  downloaded: number;
5
5
  total?: number;
6
- /** total is a guess (HLS: extrapolated from finished segments) */
7
6
  estimated?: boolean;
8
7
  }
9
- /** Caps average throughput at `rate` bytes per second by delaying callers. */
10
8
  export declare class RateLimiter {
11
9
  private rate;
12
10
  private start;
@@ -21,43 +19,36 @@ export interface DownloadOpts {
21
19
  limiter?: RateLimiter;
22
20
  onProgress: (p: Progress) => void;
23
21
  }
24
- /** Plain HTTP download. Resumes from `<dest>.part` with Range requests. */
25
22
  export declare function downloadHttp(url: string, dest: string, o: DownloadOpts & {
26
23
  resume: boolean;
27
24
  }): Promise<void>;
28
25
  export interface HlsOpts extends DownloadOpts {
29
26
  concurrency: number;
30
27
  }
31
- /** A fragment to fetch. HLS segments and DASH fragments both reduce to this. */
32
28
  export interface SegmentRef {
33
29
  url: string;
34
30
  seq: number;
35
31
  key?: HlsKey;
36
- /** init segment (fMP4); written whenever it changes */
37
32
  map?: string;
38
- /** byte range within `url` (HLS EXT-X-BYTERANGE) */
39
33
  range?: {
40
34
  start: number;
41
35
  length: number;
42
36
  };
43
- /** byte range within the init segment */
44
37
  mapRange?: {
45
38
  start: number;
46
39
  length: number;
47
40
  };
48
41
  }
49
- /** Fetches fragments in parallel, writes them in order (bounded memory), decrypts AES-128. Returns the container ext. */
50
42
  export declare function downloadSegments(segments: SegmentRef[], dest: string, o: HlsOpts): Promise<{
51
43
  ext: "ts" | "mp4";
52
44
  }>;
53
- /** HLS VOD: parse the media playlist, then hand the segments to the shared engine. */
54
45
  export declare function downloadHls(url: string, dest: string, o: HlsOpts): Promise<{
55
46
  ext: "ts" | "mp4";
56
47
  }>;
57
- /** DASH: fragments were already expanded by the extractor (format.init + format.fragments). */
58
48
  export declare function downloadDash(f: {
59
49
  init?: string;
60
50
  fragments?: string[];
61
51
  }, dest: string, o: HlsOpts): Promise<{
62
52
  ext: "ts" | "mp4";
63
53
  }>;
54
+ export declare function downloadHlsSubtitles(url: string, dest: string, o: HlsOpts): Promise<void>;
@@ -6,7 +6,6 @@ import { Readable, Transform } from "node:stream";
6
6
  import { pipeline } from "node:stream/promises";
7
7
  import { TidepullError } from "./errors.js";
8
8
  import { isMasterPlaylist, parseMedia } from "./hls.js";
9
- /** Caps average throughput at `rate` bytes per second by delaying callers. */
10
9
  export class RateLimiter {
11
10
  rate;
12
11
  start = Date.now();
@@ -21,7 +20,6 @@ export class RateLimiter {
21
20
  await sleep(wait, undefined, { signal });
22
21
  }
23
22
  }
24
- /** Plain HTTP download. Resumes from `<dest>.part` with Range requests. */
25
23
  export async function downloadHttp(url, dest, o) {
26
24
  const part = dest + ".part";
27
25
  let offset = 0;
@@ -32,7 +30,6 @@ export async function downloadHttp(url, dest, o) {
32
30
  headers.Range = `bytes=${offset}-`;
33
31
  const res = await o.http.request(url, { headers, signal: o.signal });
34
32
  if (res.status === 416) {
35
- // Range not satisfiable: the .part is either complete or stale.
36
33
  await res.body?.cancel();
37
34
  const total = /\*\/(\d+)/.exec(res.headers.get("content-range") ?? "")?.[1];
38
35
  if (total && Number(total) === offset) {
@@ -56,7 +53,7 @@ export async function downloadHttp(url, dest, o) {
56
53
  total = m ? Number(m[2]) : undefined;
57
54
  }
58
55
  else {
59
- offset = 0; // no usable Range response: start over
56
+ offset = 0;
60
57
  const cl = res.headers.get("content-length");
61
58
  total = cl ? Number(cl) : undefined;
62
59
  }
@@ -86,7 +83,6 @@ export async function downloadHttp(url, dest, o) {
86
83
  }
87
84
  await rename(part, dest);
88
85
  }
89
- /** Fetches fragments in parallel, writes them in order (bounded memory), decrypts AES-128. Returns the container ext. */
90
86
  export async function downloadSegments(segments, dest, o) {
91
87
  if (!segments.length)
92
88
  throw new TidepullError("No segments to download");
@@ -125,7 +121,7 @@ export async function downloadSegments(segments, dest, o) {
125
121
  const key = await getKey(seg.key.uri);
126
122
  let iv = seg.key.iv;
127
123
  if (!iv) {
128
- iv = Buffer.alloc(16); // default IV = segment sequence number, big-endian
124
+ iv = Buffer.alloc(16);
129
125
  iv.writeUInt32BE(seg.seq >>> 0, 12);
130
126
  }
131
127
  const d = createDecipheriv("aes-128-cbc", key, iv);
@@ -140,7 +136,7 @@ export async function downloadSegments(segments, dest, o) {
140
136
  const inflight = new Array(n);
141
137
  const start = (i) => {
142
138
  inflight[i] = fetchSeg(i);
143
- inflight[i].catch(() => { }); // handled when awaited in order
139
+ inflight[i].catch(() => { });
144
140
  };
145
141
  let ext = "ts";
146
142
  let lastMap;
@@ -178,7 +174,6 @@ export async function downloadSegments(segments, dest, o) {
178
174
  await rename(part, dest);
179
175
  return { ext };
180
176
  }
181
- /** HLS VOD: parse the media playlist, then hand the segments to the shared engine. */
182
177
  export async function downloadHls(url, dest, o) {
183
178
  const { text, finalUrl } = await o.http.text(url, { headers: o.headers, signal: o.signal });
184
179
  if (isMasterPlaylist(text))
@@ -188,9 +183,49 @@ export async function downloadHls(url, dest, o) {
188
183
  throw new TidepullError("Live HLS streams are not supported yet");
189
184
  return downloadSegments(media.segments, dest, o);
190
185
  }
191
- /** DASH: fragments were already expanded by the extractor (format.init + format.fragments). */
192
186
  export function downloadDash(f, dest, o) {
193
187
  if (!f.fragments?.length)
194
188
  throw new TidepullError("DASH format has no fragments");
195
189
  return downloadSegments(f.fragments.map((url, seq) => ({ url, seq, map: f.init })), dest, o);
196
190
  }
191
+ export async function downloadHlsSubtitles(url, dest, o) {
192
+ const { text, finalUrl } = await o.http.text(url, { headers: o.headers, signal: o.signal });
193
+ if (isMasterPlaylist(text))
194
+ throw new TidepullError("Expected a subtitle media playlist, got a master playlist");
195
+ const media = parseMedia(text, finalUrl);
196
+ if (!media.endList)
197
+ throw new TidepullError("Live subtitle streams are not supported yet");
198
+ const part = dest + ".part";
199
+ const out = createWriteStream(part);
200
+ const write = (s) => new Promise((res, rej) => out.write(s, (e) => (e ? rej(e) : res())));
201
+ try {
202
+ let header = "";
203
+ let lastMap;
204
+ for (const seg of media.segments) {
205
+ if (seg.map && seg.map !== lastMap) {
206
+ out.destroy();
207
+ await rm(part, { force: true });
208
+ throw new TidepullError("fMP4 subtitle tracks (EXT-X-MAP) are not supported yet; only WebVTT segment playlists are");
209
+ }
210
+ const r = await o.http.request(seg.url, { headers: o.headers, signal: o.signal });
211
+ if (!r.ok) {
212
+ await r.body?.cancel();
213
+ throw new TidepullError(`HTTP ${r.status} for subtitle segment ${seg.url}`);
214
+ }
215
+ const body = await r.text();
216
+ if (!header) {
217
+ header = body.slice(0, body.indexOf("\n\n") + 1);
218
+ await write(header);
219
+ }
220
+ const cues = body.startsWith("WEBVTT") ? body.slice(body.indexOf("\n\n") + 2) : body;
221
+ await write(cues.endsWith("\n") ? cues : cues + "\n");
222
+ }
223
+ await new Promise((res, rej) => out.end((e) => (e ? rej(e) : res())));
224
+ }
225
+ catch (e) {
226
+ out.destroy();
227
+ await rm(part, { force: true });
228
+ throw e;
229
+ }
230
+ await rename(part, dest);
231
+ }
@@ -3,9 +3,7 @@ export declare class TidepullError extends Error {
3
3
  constructor(message: string, exitCode?: number);
4
4
  }
5
5
  export declare const errMsg: (e: unknown) => string;
6
- /** Thrown when a caller's AbortSignal fires. name === "AbortError" so it works with standard abort handling. */
7
6
  export declare function abortError(): TidepullError;
8
- /** Redirect policy violations. Never retried. */
9
7
  export declare class RedirectError extends TidepullError {
10
8
  constructor(message: string);
11
9
  }
@@ -7,13 +7,11 @@ export class TidepullError extends Error {
7
7
  }
8
8
  }
9
9
  export const errMsg = (e) => (e instanceof Error ? e.message : String(e));
10
- /** Thrown when a caller's AbortSignal fires. name === "AbortError" so it works with standard abort handling. */
11
10
  export function abortError() {
12
11
  const e = new TidepullError("Aborted", 130);
13
12
  e.name = "AbortError";
14
13
  return e;
15
14
  }
16
- /** Redirect policy violations. Never retried. */
17
15
  export class RedirectError extends TidepullError {
18
16
  constructor(message) {
19
17
  super(message);
@@ -1,5 +1,4 @@
1
1
  export type LogLevel = "debug" | "info" | "warn";
2
- /** Everything the engine reports. Plain JSON-serializable objects, so they can be piped, logged or sent over IPC. */
3
2
  export type TidepullEvent = {
4
3
  type: "log";
5
4
  level: LogLevel;
@@ -54,7 +53,6 @@ export type TidepullEvent = {
54
53
  url?: string;
55
54
  };
56
55
  export type Emit = (e: TidepullEvent) => void;
57
- /** Logging interface exposed to extractors. */
58
56
  export interface Log {
59
57
  debug(msg: string): void;
60
58
  info(tag: string, msg: string): void;
@@ -30,12 +30,10 @@ export interface HlsSegment {
30
30
  seq: number;
31
31
  key?: HlsKey;
32
32
  map?: string;
33
- /** byte range within `url` (EXT-X-BYTERANGE) */
34
33
  range?: {
35
34
  start: number;
36
35
  length: number;
37
36
  };
38
- /** byte range within the init segment (`EXT-X-MAP` BYTERANGE attribute) */
39
37
  mapRange?: {
40
38
  start: number;
41
39
  length: number;
package/dist/core/hls.js CHANGED
@@ -68,10 +68,9 @@ export function parseMedia(text, base) {
68
68
  let key;
69
69
  let map;
70
70
  let mapRange;
71
- /** pending EXT-X-BYTERANGE: [length, offset] (offset absent => previous segment end + 1) */
72
71
  let brLen;
73
72
  let brOffset;
74
- let lastEnd = 0; // exclusive end offset of the previous ranged segment within its resource
73
+ let lastEnd = 0;
75
74
  const segments = [];
76
75
  for (const line of ls) {
77
76
  if (line.startsWith("#EXT-X-MEDIA-SEQUENCE:"))
@@ -123,7 +122,7 @@ export function parseMedia(text, base) {
123
122
  brOffset = undefined;
124
123
  }
125
124
  else {
126
- lastEnd = 0; // unranged segment resets the subsequence
125
+ lastEnd = 0;
127
126
  }
128
127
  segments.push({
129
128
  url: new URL(line, base).href,
@@ -4,15 +4,7 @@ export interface HttpOptions {
4
4
  retries?: number;
5
5
  timeoutMs?: number;
6
6
  maxRedirects?: number;
7
- /**
8
- * Scope for non-trivial custom headers (Authorization, Cookie, API tokens...).
9
- * undefined = legacy/low-level mode: headers go to the origin each request starts at.
10
- * string[] = scoped mode: they go ONLY to origins passed to `trust()` plus these host patterns
11
- * ("cdn.example.com" or "*.example.com"). Tidepull uses scoped mode.
12
- * Referer, Origin, User-Agent, Accept-* and Range are never considered secret and are always sent.
13
- */
14
7
  headerHosts?: string[];
15
- /** Returns the Cookie header value for a URL (see "@boy-offi9-inc/tidepull/cookies"). Called on every request and redirect hop. */
16
8
  cookies?: (url: URL) => string | undefined;
17
9
  }
18
10
  export interface RequestInitLite {
@@ -21,9 +13,7 @@ export interface RequestInitLite {
21
13
  signal?: AbortSignal;
22
14
  }
23
15
  export declare class Http {
24
- /** non-secret defaults (UA, Accept-Language, Referer...), always sent */
25
16
  headers: Record<string, string>;
26
- /** custom headers that may be secret; sent only to trusted origins (scoped mode) */
27
17
  private secret;
28
18
  private scopedMode;
29
19
  private hostPatterns;
@@ -34,12 +24,9 @@ export declare class Http {
34
24
  maxRedirects: number;
35
25
  private defaultSignal?;
36
26
  constructor(o?: HttpOptions);
37
- /** Allow scoped headers to be sent to this URL's origin (scoped mode only). Tidepull calls this for every URL you give it. */
38
27
  trust(url: string | URL): void;
39
28
  private headersFor;
40
- /** A view of this client whose requests are cancelled by `signal` (so extractors don't need to pass it around). */
41
29
  scoped(signal?: AbortSignal): Http;
42
- /** fetch with manual, origin-aware redirects + retry (network errors, 5xx, 429) with backoff. The timeout covers headers only. */
43
30
  request(url: string, init?: RequestInitLite): Promise<Response>;
44
31
  private follow;
45
32
  text(url: string, init?: RequestInitLite): Promise<{
package/dist/core/http.js CHANGED
@@ -1,13 +1,10 @@
1
1
  import { TidepullError, RedirectError, errMsg } from "./errors.js";
2
2
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
3
3
  const REDIRECT = new Set([301, 302, 303, 307, 308]);
4
- /** Sent to every host. All other custom headers are scoped (see HttpOptions.headerHosts). */
5
4
  const OPEN_HEADERS = new Set(["user-agent", "accept", "accept-language", "accept-encoding", "range", "referer", "origin"]);
6
5
  const hostMatches = (pattern, host) => pattern.startsWith("*.") ? host === pattern.slice(2) || host.endsWith(pattern.slice(1)) : host === pattern;
7
6
  export class Http {
8
- /** non-secret defaults (UA, Accept-Language, Referer...), always sent */
9
7
  headers;
10
- /** custom headers that may be secret; sent only to trusted origins (scoped mode) */
11
8
  secret;
12
9
  scopedMode;
13
10
  hostPatterns;
@@ -36,7 +33,6 @@ export class Http {
36
33
  this.timeoutMs = o.timeoutMs ?? 30_000;
37
34
  this.maxRedirects = o.maxRedirects ?? 10;
38
35
  }
39
- /** Allow scoped headers to be sent to this URL's origin (scoped mode only). Tidepull calls this for every URL you give it. */
40
36
  trust(url) {
41
37
  this.trusted.add(new URL(url).origin);
42
38
  }
@@ -44,7 +40,6 @@ export class Http {
44
40
  const send = this.scopedMode ? this.trusted.has(u.origin) || this.hostPatterns.some((p) => hostMatches(p, u.hostname)) : u.origin === start.origin;
45
41
  return send ? { ...this.headers, ...this.secret } : { ...this.headers };
46
42
  }
47
- /** A view of this client whose requests are cancelled by `signal` (so extractors don't need to pass it around). */
48
43
  scoped(signal) {
49
44
  if (!signal)
50
45
  return this;
@@ -52,7 +47,6 @@ export class Http {
52
47
  h.defaultSignal = signal;
53
48
  return h;
54
49
  }
55
- /** fetch with manual, origin-aware redirects + retry (network errors, 5xx, 429) with backoff. The timeout covers headers only. */
56
50
  async request(url, init = {}) {
57
51
  init = { ...init, signal: init.signal ?? this.defaultSignal };
58
52
  let lastErr;
@@ -81,7 +75,6 @@ export class Http {
81
75
  const start = new URL(url);
82
76
  let cur = start;
83
77
  for (let hop = 0;; hop++) {
84
- // per-request headers (Range, extractor-supplied Referer/Cookie...) only travel with the start origin; Range goes everywhere
85
78
  const own = Object.fromEntries(Object.entries(init.headers ?? {}).filter(([k]) => cur.origin === start.origin || k.toLowerCase() === "range"));
86
79
  const headers = { ...this.headersFor(cur, start), ...own };
87
80
  const cookie = this.cookies?.(cur);
@@ -1,4 +1,3 @@
1
- /** Speed over a sliding ~3s window. */
2
1
  export declare class Meter {
3
2
  private samples;
4
3
  startBytes: number | undefined;
@@ -1,4 +1,3 @@
1
- /** Speed over a sliding ~3s window. */
2
1
  export class Meter {
3
2
  samples = [];
4
3
  startBytes;
@@ -1,33 +1,21 @@
1
1
  import type { Ctx, Info, Playlist } from "./types.js";
2
2
  export declare const DEFAULT_OUTPUT = "%(title)s [%(id)s].%(ext)s";
3
3
  export interface DownloadOptions {
4
- /** format selector, default "bv*+ba/b" */
5
4
  format: string;
6
- /** output template. Default: "%(title)s [%(id)s].%(ext)s", or just the title when the id is identical (typical for direct files) */
7
5
  output?: string;
8
- /** base directory */
9
6
  paths: string;
10
- /** resume from .part files */
11
7
  resume: boolean;
12
8
  overwrite: boolean;
13
- /** HLS segments fetched in parallel */
14
9
  concurrency: number;
15
- /** container used when merging video+audio */
16
10
  mergeFormat: string;
17
11
  remuxVideo?: string;
18
- /** ffmpeg binary or its directory (default: search PATH) */
19
12
  ffmpeg?: string;
20
- /** extra request headers for the media downloads */
21
13
  headers: Record<string, string>;
22
- /** maximum average download speed in bytes per second (applies to each file) */
23
14
  limitRate?: number;
24
- /** extra output-template fields (playlist downloads set playlist, playlist_id, playlist_index, playlist_count) */
25
15
  fields?: Record<string, string | number>;
16
+ writeSubs?: boolean;
26
17
  }
27
18
  export declare const isPlaylist: (x: Info | Playlist) => x is Playlist;
28
- /** Resolves a URL with the first matching extractor: a single item (Info) or a Playlist. */
29
19
  export declare function resolveUrl(rawUrl: string, ctx: Ctx): Promise<Info | Playlist>;
30
- /** Like resolveUrl, but a playlist is an error (callers that need one item). */
31
20
  export declare function extractInfo(rawUrl: string, ctx: Ctx): Promise<Info>;
32
- /** Selects formats per opts.format, downloads them, merges/remuxes with ffmpeg if needed. Returns the final file path. */
33
21
  export declare function downloadInfo(info: Info, opts: DownloadOptions, ctx: Ctx): Promise<string>;
@@ -1,6 +1,6 @@
1
1
  import { mkdir, rename, rm, stat } from "node:fs/promises";
2
2
  import path from "node:path";
3
- import { downloadDash, downloadHls, downloadHttp, RateLimiter } from "./downloader.js";
3
+ import { downloadDash, downloadHls, downloadHlsSubtitles, downloadHttp, RateLimiter } from "./downloader.js";
4
4
  import { TidepullError } from "./errors.js";
5
5
  import { findFfmpeg, mergeStreams, remux } from "./ffmpeg.js";
6
6
  import { Meter } from "./meter.js";
@@ -8,7 +8,6 @@ import { selectFormats } from "./selector.js";
8
8
  import { renderTemplate } from "./template.js";
9
9
  export const DEFAULT_OUTPUT = "%(title)s [%(id)s].%(ext)s";
10
10
  export const isPlaylist = (x) => x.kind === "playlist";
11
- /** Resolves a URL with the first matching extractor: a single item (Info) or a Playlist. */
12
11
  export async function resolveUrl(rawUrl, ctx) {
13
12
  let url;
14
13
  try {
@@ -32,7 +31,6 @@ export async function resolveUrl(rawUrl, ctx) {
32
31
  throw new TidepullError(`Extractor "${ex.name}" returned no formats`);
33
32
  return result;
34
33
  }
35
- /** Like resolveUrl, but a playlist is an error (callers that need one item). */
36
34
  export async function extractInfo(rawUrl, ctx) {
37
35
  const result = await resolveUrl(rawUrl, ctx);
38
36
  if (isPlaylist(result)) {
@@ -40,14 +38,15 @@ export async function extractInfo(rawUrl, ctx) {
40
38
  }
41
39
  return result;
42
40
  }
43
- /** Drops undefined keys so events serialize cleanly. */
44
41
  const compact = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
45
42
  const scalars = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => ["string", "number", "boolean"].includes(typeof v)));
46
- /** Selects formats per opts.format, downloads them, merges/remuxes with ffmpeg if needed. Returns the final file path. */
47
43
  export async function downloadInfo(info, opts, ctx) {
48
44
  const chosen = selectFormats(opts.format, info.formats);
49
45
  if (!chosen)
50
46
  throw new TidepullError(`Requested format is not available: ${opts.format} (try --list-formats)`);
47
+ if (opts.writeSubs && !info.subtitles?.length) {
48
+ ctx.log.info("download", "no subtitle tracks are available for this media");
49
+ }
51
50
  const ffmpeg = findFfmpeg(opts.ffmpeg);
52
51
  const merging = chosen.length > 1;
53
52
  if (merging && !ffmpeg) {
@@ -62,7 +61,6 @@ export async function downloadInfo(info, opts, ctx) {
62
61
  resolution: chosen[0].height ? `${chosen[0].width ?? "?"}x${chosen[0].height}` : "audio only",
63
62
  ext: predictedExt,
64
63
  };
65
- // Default name: just the title when it equals the id (direct files); playlist items get their number in front.
66
64
  const defaultName = String(info.title) === String(info.id) ? "%(title)s.%(ext)s" : DEFAULT_OUTPUT;
67
65
  const template = opts.output ?? (opts.fields?.playlist_index !== undefined ? `%(playlist_index)02d - ${defaultName}` : defaultName);
68
66
  let target = path.resolve(opts.paths, renderTemplate(template, fields));
@@ -106,7 +104,7 @@ export async function downloadInfo(info, opts, ctx) {
106
104
  if (!merging) {
107
105
  const ext = await fetchOne(chosen[0], target);
108
106
  if (ext !== path.extname(target).slice(1)) {
109
- const fixed = `${base}.${ext}`; // the real container can differ from the predicted one (e.g. fMP4 HLS)
107
+ const fixed = `${base}.${ext}`;
110
108
  await rename(target, fixed);
111
109
  target = fixed;
112
110
  }
@@ -119,7 +117,6 @@ export async function downloadInfo(info, opts, ctx) {
119
117
  tmp.push(dest);
120
118
  await fetchOne(f, dest);
121
119
  }
122
- // video stream first, audio second
123
120
  const [v, a] = chosen[0].vcodec !== "none" ? [tmp[0], tmp[1]] : [tmp[1], tmp[0]];
124
121
  ctx.emit({ type: "merge", output: target });
125
122
  await mergeStreams(ffmpeg, v, a, target);
@@ -141,5 +138,16 @@ export async function downloadInfo(info, opts, ctx) {
141
138
  await rm(target, { force: true });
142
139
  target = out;
143
140
  }
141
+ if (opts.writeSubs && info.subtitles?.length) {
142
+ const stemBase = target.slice(0, target.length - path.extname(target).length);
143
+ for (const sub of info.subtitles) {
144
+ const dest = `${stemBase}.${sub.lang.replace(/\W+/g, "_")}.vtt`;
145
+ ctx.emit({ type: "start", format_id: `subtitle-${sub.lang}`, dest });
146
+ await downloadHlsSubtitles(sub.url, dest, {
147
+ http: ctx.http, headers: opts.headers, signal: ctx.signal, onProgress: () => { }, concurrency: 1,
148
+ });
149
+ ctx.emit({ type: "finish", format_id: `subtitle-${sub.lang}`, bytes: 0, seconds: 0 });
150
+ }
151
+ }
144
152
  return target;
145
153
  }
@@ -1,12 +1,3 @@
1
- /**
2
- * Format selector syntax.
3
- * b / best best pre-merged format bv / bestvideo best video-only
4
- * w / worst worst pre-merged format ba / bestaudio best audio-only
5
- * bv* / ba* best with video / with audio <format_id> exact id
6
- * a+b merge two formats a/b fallback if a unavailable
7
- * x[height<=720] filters: <= >= < > = != (add ? after the op to also accept missing fields)
8
- * (a/b)+c grouping
9
- */
10
1
  import type { Format } from "./types.js";
11
2
  export declare const DEFAULT_FORMAT = "bv*+ba/b";
12
3
  interface Filter {
@@ -27,6 +18,5 @@ type Node = {
27
18
  options: Node[];
28
19
  };
29
20
  export declare function parseSelector(sel: string): Node;
30
- /** Returns the chosen formats (2+ means "merge these"), or undefined if nothing matches. */
31
21
  export declare function selectFormats(selector: string, formats: Format[]): Format[] | undefined;
32
22
  export {};
@@ -160,7 +160,6 @@ function evaluate(n, fs) {
160
160
  return undefined;
161
161
  }
162
162
  }
163
- /** Returns the chosen formats (2+ means "merge these"), or undefined if nothing matches. */
164
163
  export function selectFormats(selector, formats) {
165
164
  return evaluate(parseSelector(selector), formats);
166
165
  }