@boy-offi9-inc/tidepull 0.4.1 → 0.5.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.
package/README.md CHANGED
@@ -164,6 +164,8 @@ TIDEPULL_THEME=high-contrast tidepull URL # --theme still wins if you also
164
164
 
165
165
  A theme only decides *which* codes are emitted: `--no-color`, `NO_COLOR` and a non-TTY stderr still strip every escape sequence, so redirected output and CI logs stay plain text.
166
166
 
167
+ On an interactive terminal the CLI shows a launch banner and a spinner while resolving a URL; quiet, JSON, `-g`, simulate and non-TTY modes suppress both so piped output stays data-only.
168
+
167
169
  From a clone, `node src/cli.ts <args>` runs the TypeScript source directly (Node >= 22.18); `npm run build` emits JS + `.d.ts`.
168
170
 
169
171
  ## Capabilities and limits
@@ -181,14 +183,14 @@ From a clone, `node src/cli.ts <args>` runs the TypeScript source directly (Node
181
183
  - No site-specific extractors are built in. Platforms such as YouTube hide their media behind scripts and tokens and need a plugin
182
184
  - No DRM: protected streams (Widevine, PlayReady, FairPlay, encrypted DASH) are not supported and will not be
183
185
  - No circumvention: it cannot get past logins, paywalls or geo-blocks. With `--cookies` it only fetches what your own session can already see
184
- - Not implemented yet: live streams, multi-period DASH (first period only), SAMPLE-AES, byte-range HLS/DASH, subtitles, playlists from video sites (they need a plugin), a proxy option
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
185
187
  - Cookies are read-only: `Set-Cookie` responses are not stored
186
188
 
187
189
  ### Details
188
190
  | Area | Behavior |
189
191
  |---|---|
190
192
  | Direct files | resumable (`.part` + `Range`), retries with backoff |
191
- | HLS VOD | master + media playlists, parallel segments written in order, AES-128 (explicit/default IV), fMP4 init maps, separate audio renditions |
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 |
192
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
195
  | Generic page extractor | `og:video`, `<video>/<source>`, bare media URLs in HTML/JSON |
194
196
  | Format selector | `b bv bv* ba ba* w wv wa`, `+` merge, `/` fallback, `()` groups, `[height<=720]` `[filesize<?50M]` `[ext=mp4]` |
@@ -35,6 +35,16 @@ export interface SegmentRef {
35
35
  key?: HlsKey;
36
36
  /** init segment (fMP4); written whenever it changes */
37
37
  map?: string;
38
+ /** byte range within `url` (HLS EXT-X-BYTERANGE) */
39
+ range?: {
40
+ start: number;
41
+ length: number;
42
+ };
43
+ /** byte range within the init segment */
44
+ mapRange?: {
45
+ start: number;
46
+ length: number;
47
+ };
38
48
  }
39
49
  /** Fetches fragments in parallel, writes them in order (bounded memory), decrypts AES-128. Returns the container ext. */
40
50
  export declare function downloadSegments(segments: SegmentRef[], dest: string, o: HlsOpts): Promise<{
@@ -103,17 +103,24 @@ export async function downloadSegments(segments, dest, o) {
103
103
  }
104
104
  return p;
105
105
  };
106
- const fetchBuf = async (u) => {
107
- const r = await o.http.request(u, { headers: o.headers, signal: o.signal });
106
+ const fetchBuf = async (u, range) => {
107
+ const headers = { ...o.headers };
108
+ if (range)
109
+ headers.Range = `bytes=${range.start}-${range.start + range.length - 1}`;
110
+ const r = await o.http.request(u, { headers, signal: o.signal });
108
111
  if (!r.ok) {
109
112
  await r.body?.cancel();
110
113
  throw new TidepullError(`HTTP ${r.status} for segment ${u}`);
111
114
  }
112
- return Buffer.from(await r.arrayBuffer());
115
+ const buf = Buffer.from(await r.arrayBuffer());
116
+ if (range && buf.length !== range.length) {
117
+ throw new TidepullError(`Segment byte range mismatch for ${u}: expected ${range.length} bytes, got ${buf.length}`);
118
+ }
119
+ return buf;
113
120
  };
114
121
  const fetchSeg = async (i) => {
115
122
  const seg = segments[i];
116
- let buf = await fetchBuf(seg.url);
123
+ let buf = await fetchBuf(seg.url, seg.range);
117
124
  if (seg.key) {
118
125
  const key = await getKey(seg.key.uri);
119
126
  let iv = seg.key.iv;
@@ -148,7 +155,7 @@ export async function downloadSegments(segments, dest, o) {
148
155
  inflight[i] = undefined;
149
156
  const map = segments[i].map;
150
157
  if (map && map !== lastMap) {
151
- const init = await fetchBuf(map);
158
+ const init = await fetchBuf(map, segments[i].mapRange);
152
159
  await write(init);
153
160
  bytes += init.length;
154
161
  lastMap = map;
@@ -30,6 +30,16 @@ export interface HlsSegment {
30
30
  seq: number;
31
31
  key?: HlsKey;
32
32
  map?: string;
33
+ /** byte range within `url` (EXT-X-BYTERANGE) */
34
+ range?: {
35
+ start: number;
36
+ length: number;
37
+ };
38
+ /** byte range within the init segment (`EXT-X-MAP` BYTERANGE attribute) */
39
+ mapRange?: {
40
+ start: number;
41
+ length: number;
42
+ };
33
43
  }
34
44
  export interface HlsMedia {
35
45
  segments: HlsSegment[];
package/dist/core/hls.js CHANGED
@@ -67,6 +67,11 @@ export function parseMedia(text, base) {
67
67
  let endList = false;
68
68
  let key;
69
69
  let map;
70
+ let mapRange;
71
+ /** pending EXT-X-BYTERANGE: [length, offset] (offset absent => previous segment end + 1) */
72
+ let brLen;
73
+ let brOffset;
74
+ let lastEnd = 0; // exclusive end offset of the previous ranged segment within its resource
70
75
  const segments = [];
71
76
  for (const line of ls) {
72
77
  if (line.startsWith("#EXT-X-MEDIA-SEQUENCE:"))
@@ -75,8 +80,15 @@ export function parseMedia(text, base) {
75
80
  dur = parseFloat(val(line)) || 0;
76
81
  else if (line.startsWith("#EXT-X-ENDLIST"))
77
82
  endList = true;
78
- else if (line.startsWith("#EXT-X-BYTERANGE"))
79
- throw new TidepullError("HLS byte-range segments are not supported yet");
83
+ else if (line.startsWith("#EXT-X-BYTERANGE")) {
84
+ const spec = val(line).split("@");
85
+ brLen = Number(spec[0]);
86
+ if (!brLen || brLen < 0)
87
+ throw new TidepullError(`Invalid EXT-X-BYTERANGE: ${val(line)}`);
88
+ brOffset = spec[1] !== undefined ? Number(spec[1]) : undefined;
89
+ if (spec[1] !== undefined && (Number.isNaN(brOffset) || brOffset < 0))
90
+ throw new TidepullError(`Invalid EXT-X-BYTERANGE offset: ${val(line)}`);
91
+ }
80
92
  else if (line.startsWith("#EXT-X-KEY:")) {
81
93
  const a = parseAttributes(val(line));
82
94
  if (a.METHOD === "NONE")
@@ -89,12 +101,39 @@ export function parseMedia(text, base) {
89
101
  }
90
102
  else if (line.startsWith("#EXT-X-MAP:")) {
91
103
  const a = parseAttributes(val(line));
92
- if (a.BYTERANGE)
93
- throw new TidepullError("HLS byte-range init segments are not supported yet");
94
104
  map = a.URI ? new URL(a.URI, base).href : undefined;
105
+ if (a.BYTERANGE) {
106
+ const [len, off] = a.BYTERANGE.split("@");
107
+ const length = Number(len);
108
+ const start = Number(off ?? 0);
109
+ if (!length || start < 0)
110
+ throw new TidepullError(`Invalid EXT-X-MAP BYTERANGE: ${a.BYTERANGE}`);
111
+ mapRange = { start, length };
112
+ }
113
+ else
114
+ mapRange = undefined;
95
115
  }
96
116
  else if (!line.startsWith("#")) {
97
- segments.push({ url: new URL(line, base).href, duration: dur, seq: seq + segments.length, key, map });
117
+ let range;
118
+ if (brLen !== undefined) {
119
+ const start = brOffset ?? lastEnd;
120
+ range = { start, length: brLen };
121
+ lastEnd = start + brLen;
122
+ brLen = undefined;
123
+ brOffset = undefined;
124
+ }
125
+ else {
126
+ lastEnd = 0; // unranged segment resets the subsequence
127
+ }
128
+ segments.push({
129
+ url: new URL(line, base).href,
130
+ duration: dur,
131
+ seq: seq + segments.length,
132
+ key,
133
+ map,
134
+ ...(map && mapRange ? { mapRange } : {}),
135
+ ...(range ? { range } : {}),
136
+ });
98
137
  dur = 0;
99
138
  }
100
139
  }
package/dist/main.js CHANGED
@@ -13,7 +13,9 @@ import { defaultPluginDir, loadPlugins } from "./loader.js";
13
13
  import { table, fmtBytes } from "./ui/format.js";
14
14
  import { Logger, shouldUseColor } from "./ui/log.js";
15
15
  import { humanRenderer, jsonRenderer } from "./ui/render.js";
16
+ import { renderBanner } from "./ui/banner.js";
16
17
  import { pickTheme, THEME_NAMES } from "./ui/theme.js";
18
+ import { Spinner } from "./ui/spinner.js";
17
19
  /** Package version, read from package.json. */
18
20
  export const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
19
21
  const HELP = `tidepull ${VERSION}: a minimal media downloader
@@ -177,6 +179,12 @@ export async function main(argv) {
177
179
  process.stderr.write(`ERROR: ${errMsg(e)}\n`);
178
180
  return 2;
179
181
  }
182
+ // Banner: interactive terminals only. Anything machine-facing (quiet, json,
183
+ // get-url, simulate, progress-json) or non-TTY stdout suppresses it.
184
+ const machineMode = values.quiet || values["dump-json"] || values["get-url"] || values.simulate || values["progress-json"];
185
+ if (process.stdout.isTTY && !machineMode) {
186
+ process.stderr.write(renderBanner(VERSION, theme, !values["no-color"] && shouldUseColor()) + "\n");
187
+ }
180
188
  const log = new Logger({
181
189
  quiet: values.quiet,
182
190
  verbose: values.verbose,
@@ -272,6 +280,14 @@ export async function main(argv) {
272
280
  process.stderr.write(e.stack + "\n");
273
281
  code = Math.max(code, e instanceof TidepullError ? e.exitCode : 1);
274
282
  };
283
+ // Spinner for the resolve/extract phase: TTY stderr only, machine modes never see it.
284
+ const interactive = process.stdout.isTTY && !machineMode && !values["no-progress"];
285
+ const spinner = new Spinner({ text: "extracting…", env: process.env });
286
+ const spin = () => {
287
+ if (interactive)
288
+ spinner.start();
289
+ };
290
+ const stopSpin = (final) => spinner.stop(final);
275
291
  /** What to do with one extracted item: print info, list formats, print URLs, or download it. */
276
292
  const handle = async (info, fields) => {
277
293
  if (values["dump-json"])
@@ -303,8 +319,10 @@ export async function main(argv) {
303
319
  try {
304
320
  for (const url of urls) {
305
321
  try {
322
+ spin();
306
323
  const resolved = await tp.resolve(url, { signal: ctl.signal });
307
324
  if (isPlaylist(resolved) && (values["dump-json"] || values["list-formats"])) {
325
+ stopSpin(`${resolved.title}: ${resolved.entries.length} item(s)`);
308
326
  // listing a playlist needs no request per entry
309
327
  if (values["dump-json"])
310
328
  process.stdout.write(JSON.stringify(resolved) + "\n");
@@ -315,6 +333,7 @@ export async function main(argv) {
315
333
  continue;
316
334
  }
317
335
  for await (const item of resolveItems(tp, resolved, { signal: ctl.signal, items: values["playlist-items"] })) {
336
+ stopSpin();
318
337
  try {
319
338
  if (item.error)
320
339
  throw item.error;
@@ -328,6 +347,7 @@ export async function main(argv) {
328
347
  }
329
348
  }
330
349
  catch (e) {
350
+ stopSpin();
331
351
  if (ctl.signal.aborted) {
332
352
  process.stderr.write("\n");
333
353
  log.error("Interrupted by user (partial files kept, re-run to resume)");
@@ -341,6 +361,7 @@ export async function main(argv) {
341
361
  }
342
362
  }
343
363
  finally {
364
+ stopSpin();
344
365
  process.removeListener("SIGINT", onSigint);
345
366
  }
346
367
  return code;
@@ -0,0 +1,3 @@
1
+ import type { Theme } from "./theme.js";
2
+ /** Launch banner for interactive terminals; version dimmed beside the logo. */
3
+ export declare function renderBanner(version: string, theme: Theme, color?: boolean): string;
@@ -0,0 +1,28 @@
1
+ const GLYPHS = {
2
+ t: ["| |_ ", "| __|", "| |_ ", " \\__|"],
3
+ i: ["|_ _|", " | | ", " | | ", "|___|"],
4
+ d: [" __| |", " / _` |", "| (_| |", " \\__,_|"],
5
+ e: [" ___ ", " / _ \\", "| __/", " \\___|"],
6
+ p: ["| '_ \\ ", "| |_) |", "| .__/ ", "|_| "],
7
+ u: ["| | ", "| | ", "| | ", "|_| "],
8
+ l: ["| |", "| |", "| |", "|_|"],
9
+ };
10
+ /** Block-letter logo, assembled row by row so the letters are correct by construction. */
11
+ function logo() {
12
+ const rows = ["", "", "", ""];
13
+ for (const ch of "tidepull") {
14
+ const g = GLYPHS[ch];
15
+ for (let r = 0; r < 4; r++)
16
+ rows[r] += g[r] + (r === 0 && ch !== "l" ? " " : " ");
17
+ }
18
+ return rows.map((r) => r.trimEnd());
19
+ }
20
+ /** Launch banner for interactive terminals; version dimmed beside the logo. */
21
+ export function renderBanner(version, theme, color = true) {
22
+ const plain = !color || !!process.env.NO_COLOR || theme.name === "mono";
23
+ const paint = (c, s) => (plain ? s : c + s + theme.reset);
24
+ const dim = (s) => (plain ? s : theme.dim + s + theme.reset);
25
+ const rows = logo();
26
+ rows[3] = paint(theme.accent, rows[3]) + " " + dim(`v${version}`);
27
+ return rows.map((r, i) => (i === 3 ? r : paint(theme.accent, r))).join("\n");
28
+ }
@@ -0,0 +1,24 @@
1
+ export interface SpinnerOptions {
2
+ text?: string;
3
+ stream?: NodeJS.WriteStream;
4
+ env?: NodeJS.ProcessEnv;
5
+ interval?: number;
6
+ }
7
+ /**
8
+ * Single-line activity spinner on stderr. Never touches stdout, and never
9
+ * starts at all when stderr is not a TTY or CI is detected: machine modes
10
+ * must see zero bytes from it.
11
+ */
12
+ export declare class Spinner {
13
+ private timer;
14
+ private frame;
15
+ private text;
16
+ private readonly stream;
17
+ private readonly env;
18
+ private readonly interval;
19
+ constructor(o?: SpinnerOptions);
20
+ get active(): boolean;
21
+ start(): this;
22
+ stop(finalLine?: string): this;
23
+ private render;
24
+ }
@@ -0,0 +1,49 @@
1
+ const FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧"];
2
+ /**
3
+ * Single-line activity spinner on stderr. Never touches stdout, and never
4
+ * starts at all when stderr is not a TTY or CI is detected: machine modes
5
+ * must see zero bytes from it.
6
+ */
7
+ export class Spinner {
8
+ timer;
9
+ frame = 0;
10
+ text;
11
+ stream;
12
+ env;
13
+ interval;
14
+ constructor(o = {}) {
15
+ this.text = o.text ?? "extracting…";
16
+ this.stream = o.stream ?? process.stderr;
17
+ this.env = o.env ?? process.env;
18
+ this.interval = o.interval ?? 80;
19
+ }
20
+ get active() {
21
+ return this.timer !== undefined;
22
+ }
23
+ start() {
24
+ if (this.timer || !this.stream.isTTY || this.env.CI)
25
+ return this;
26
+ this.render();
27
+ this.timer = setInterval(() => {
28
+ this.frame = (this.frame + 1) % FRAMES.length;
29
+ this.render();
30
+ }, this.interval);
31
+ this.timer.unref();
32
+ return this;
33
+ }
34
+ stop(finalLine) {
35
+ if (!this.timer)
36
+ return this;
37
+ clearInterval(this.timer);
38
+ this.timer = undefined;
39
+ this.stream.write(`\r\x1b[K`);
40
+ if (finalLine) {
41
+ const dim = this.env.NO_COLOR ? "" : "\x1b[2m";
42
+ this.stream.write(`${dim}${finalLine}\x1b[0m\n`);
43
+ }
44
+ return this;
45
+ }
46
+ render() {
47
+ this.stream.write(`\r\x1b[K${FRAMES[this.frame]} ${this.text}`);
48
+ }
49
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@boy-offi9-inc/tidepull",
3
- "version": "0.4.1",
3
+ "version": "0.5.0",
4
4
  "description": "A minimal, from-scratch media downloader library: extractor plugins, yt-dlp-style format selection, resumable downloads.",
5
5
  "type": "module",
6
6
  "license": "MIT",