@boy-offi9-inc/tidepull 0.0.0-stage → 0.1.0-rc.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 (59) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +107 -2
  3. package/dist/cli.d.ts +2 -0
  4. package/dist/cli.js +3 -0
  5. package/dist/core/downloader.d.ts +44 -0
  6. package/dist/core/downloader.js +160 -0
  7. package/dist/core/errors.d.ts +11 -0
  8. package/dist/core/errors.js +22 -0
  9. package/dist/core/events.d.ts +51 -0
  10. package/dist/core/events.js +5 -0
  11. package/dist/core/ffmpeg.d.ts +3 -0
  12. package/dist/core/ffmpeg.js +38 -0
  13. package/dist/core/hls.d.ts +41 -0
  14. package/dist/core/hls.js +102 -0
  15. package/dist/core/http.d.ts +46 -0
  16. package/dist/core/http.js +120 -0
  17. package/dist/core/meter.d.ts +6 -0
  18. package/dist/core/meter.js +17 -0
  19. package/dist/core/pipeline.d.ts +25 -0
  20. package/dist/core/pipeline.js +126 -0
  21. package/dist/core/selector.d.ts +32 -0
  22. package/dist/core/selector.js +166 -0
  23. package/dist/core/template.d.ts +3 -0
  24. package/dist/core/template.js +20 -0
  25. package/dist/core/types.d.ts +56 -0
  26. package/dist/core/types.js +1 -0
  27. package/dist/dash/index.d.ts +7 -0
  28. package/dist/dash/index.js +70 -0
  29. package/dist/dash/parse.d.ts +31 -0
  30. package/dist/dash/parse.js +140 -0
  31. package/dist/dash/xml.d.ts +9 -0
  32. package/dist/dash/xml.js +56 -0
  33. package/dist/extractors/direct.d.ts +3 -0
  34. package/dist/extractors/direct.js +34 -0
  35. package/dist/extractors/generic.d.ts +3 -0
  36. package/dist/extractors/generic.js +103 -0
  37. package/dist/extractors/hls.d.ts +3 -0
  38. package/dist/extractors/hls.js +72 -0
  39. package/dist/extractors/index.d.ts +5 -0
  40. package/dist/extractors/index.js +9 -0
  41. package/dist/extractors/util.d.ts +7 -0
  42. package/dist/extractors/util.js +13 -0
  43. package/dist/index.d.ts +14 -0
  44. package/dist/index.js +8 -0
  45. package/dist/loader.d.ts +7 -0
  46. package/dist/loader.js +76 -0
  47. package/dist/main.d.ts +3 -0
  48. package/dist/main.js +243 -0
  49. package/dist/plugins.d.ts +10 -0
  50. package/dist/plugins.js +4 -0
  51. package/dist/tidepull.d.ts +48 -0
  52. package/dist/tidepull.js +107 -0
  53. package/dist/ui/format.d.ts +4 -0
  54. package/dist/ui/format.js +26 -0
  55. package/dist/ui/log.d.ts +19 -0
  56. package/dist/ui/log.js +37 -0
  57. package/dist/ui/render.d.ts +9 -0
  58. package/dist/ui/render.js +60 -0
  59. package/package.json +66 -4
package/dist/loader.js ADDED
@@ -0,0 +1,76 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ /** Loads plugins from disk (Node only). Opt-in: `import { loadPlugins } from "@boy-offi9-inc/tidepull/loader"`. */
10
+ import { readdir, stat } from "node:fs/promises";
11
+ import os from "node:os";
12
+ import path from "node:path";
13
+ import { pathToFileURL } from "node:url";
14
+ import { TidepullError, errMsg } from "./core/errors.js";
15
+ import { PLUGIN_API_VERSION } from "./plugins.js";
16
+ export function validatePlugin(p, source) {
17
+ if (!p || typeof p !== "object")
18
+ throw new TidepullError(`Plugin ${source}: default export must be a plugin object (use definePlugin)`);
19
+ const o = p;
20
+ if (typeof o.name !== "string" || !o.name)
21
+ throw new TidepullError(`Plugin ${source}: missing "name"`);
22
+ if (o.apiVersion !== PLUGIN_API_VERSION) {
23
+ throw new TidepullError(`Plugin "${o.name}" (${source}) targets apiVersion ${String(o.apiVersion)}, but this tidepull supports ${PLUGIN_API_VERSION}`);
24
+ }
25
+ for (const e of o.extractors ?? []) {
26
+ if (!e || typeof e.name !== "string" || typeof e.suitable !== "function" || typeof e.extract !== "function") {
27
+ throw new TidepullError(`Plugin "${o.name}" (${source}): every extractor needs name, suitable() and extract()`);
28
+ }
29
+ }
30
+ return o;
31
+ }
32
+ /** SECURITY: this executes the file's code with your privileges. Only load plugins you trust. */
33
+ export async function loadPlugin(file) {
34
+ let mod;
35
+ try {
36
+ mod = await import(__rewriteRelativeImportExtension(pathToFileURL(path.resolve(file)).href));
37
+ }
38
+ catch (e) {
39
+ throw new TidepullError(`Failed to load plugin ${file}: ${errMsg(e)}`);
40
+ }
41
+ return validatePlugin(mod.default ?? mod.plugin, file);
42
+ }
43
+ const FILE_RE = /\.(?:m?js|cjs|mts|ts)$/;
44
+ const INDEX_RE = /^index\.(?:m?js|mts|ts)$/;
45
+ /** Each path may be a plugin file, or a directory of plugin files and/or `<name>/index.*` folders (not recursive). */
46
+ export async function loadPlugins(paths) {
47
+ const out = [];
48
+ for (const p of paths) {
49
+ const s = await stat(p).catch(() => undefined);
50
+ if (!s)
51
+ throw new TidepullError(`Plugin path not found: ${p}`);
52
+ if (s.isFile()) {
53
+ out.push(await loadPlugin(p));
54
+ continue;
55
+ }
56
+ for (const name of (await readdir(p)).sort()) {
57
+ if (name.startsWith("_") || name.startsWith(".") || name.endsWith(".d.ts"))
58
+ continue;
59
+ const full = path.join(p, name);
60
+ const fs = await stat(full);
61
+ if (fs.isFile() && FILE_RE.test(name))
62
+ out.push(await loadPlugin(full));
63
+ else if (fs.isDirectory()) {
64
+ const idx = (await readdir(full)).find((f) => INDEX_RE.test(f));
65
+ if (idx)
66
+ out.push(await loadPlugin(path.join(full, idx)));
67
+ }
68
+ }
69
+ }
70
+ return out;
71
+ }
72
+ export function defaultPluginDir(env = process.env) {
73
+ if (env.TIDEPULL_PLUGIN_DIR)
74
+ return env.TIDEPULL_PLUGIN_DIR;
75
+ return path.join(env.XDG_CONFIG_HOME ?? path.join(os.homedir(), ".config"), "tidepull", "plugins");
76
+ }
package/dist/main.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ /** Read from package.json so it can never drift from the published version (works from src/ and dist/). */
2
+ export declare const VERSION: string;
3
+ export declare function main(argv: string[]): Promise<number>;
package/dist/main.js ADDED
@@ -0,0 +1,243 @@
1
+ import { parseArgs } from "node:util";
2
+ import { DEFAULT_FORMAT, selectFormats } from "./core/selector.js";
3
+ import { TidepullError, errMsg } from "./core/errors.js";
4
+ import { existsSync, readFileSync } from "node:fs";
5
+ import { createTidepull } from "./tidepull.js";
6
+ import dash from "./dash/index.js";
7
+ import { defaultPluginDir, loadPlugins } from "./loader.js";
8
+ import { table, fmtBytes } from "./ui/format.js";
9
+ import { Logger, shouldUseColor } from "./ui/log.js";
10
+ import { humanRenderer, jsonRenderer } from "./ui/render.js";
11
+ /** Read from package.json so it can never drift from the published version (works from src/ and dist/). */
12
+ export const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
13
+ const HELP = `tidepull ${VERSION}: a minimal media downloader
14
+
15
+ Usage: tidepull [options] URL [URL...]
16
+
17
+ Selection:
18
+ -f, --format FORMAT Format selector (default: ${DEFAULT_FORMAT})
19
+ e.g. "bv*[height<=720]+ba/b", "ba", "hls-1200"
20
+ -F, --list-formats List available formats and exit
21
+
22
+ Output:
23
+ -o, --output TEMPLATE Output template (default: "%(title)s [%(id)s].%(ext)s")
24
+ -P, --paths DIR Download directory (default: .)
25
+ -w, --overwrite Overwrite existing files
26
+ --no-continue Do not resume partial downloads
27
+ --merge-output-format Container when merging video+audio (default: mp4)
28
+ --remux-video EXT Remux the result into EXT with ffmpeg (e.g. mp4)
29
+ --ffmpeg-location PATH ffmpeg binary or directory
30
+
31
+ Info only (nothing is downloaded):
32
+ -j, --dump-json Print the info dict as JSON
33
+ -g, --get-url Print the selected format URL(s)
34
+ -s, --simulate Extract only
35
+ --print-path After downloading, print the final file path on stdout
36
+ --list-extractors List extractors and exit
37
+
38
+ Plugins:
39
+ --plugin PATH Load a plugin file or directory (repeatable). Plugins run with your privileges!
40
+ --no-plugins Skip auto-loading ~/.config/tidepull/plugins (or $TIDEPULL_PLUGIN_DIR)
41
+
42
+ Network:
43
+ -N, --concurrent-fragments N HLS segments fetched in parallel (default: 4)
44
+ -R, --retries N Retries per request (default: 3)
45
+ --header "Name: value" Extra request header (repeatable). Secret-looking headers (Authorization,
46
+ Cookie, tokens...) are sent only to the URL's own origin...
47
+ --header-host HOST ...plus these hosts ("cdn.example.com" or "*.example.com"), repeatable
48
+ --user-agent UA Custom User-Agent
49
+
50
+ General:
51
+ -q, --quiet Only print errors/warnings
52
+ -v, --verbose Debug output
53
+ --no-progress Disable the progress line
54
+ --progress-json Emit engine events as NDJSON on stdout (for GUIs/scripts)
55
+ --no-color Disable colors (also honors NO_COLOR)
56
+ -h, --help Show this help
57
+ --version Show version
58
+
59
+ stdout carries data only (-j, -F, -g, --print-path, --progress-json). Everything else goes to stderr.
60
+ Exit codes: 0 ok, 1 error, 2 usage error, 130 interrupted.`;
61
+ function listFormats(info) {
62
+ const rows = [["ID", "EXT", "RESOLUTION", "FPS", "│", "SIZE", "TBR", "PROTO", "│", "VCODEC", "ACODEC", "NOTE"]];
63
+ const sorted = [...info.formats].sort((a, b) => (a.height ?? 0) - (b.height ?? 0) || (a.tbr ?? 0) - (b.tbr ?? 0));
64
+ for (const f of sorted) {
65
+ rows.push([
66
+ f.format_id,
67
+ f.ext,
68
+ f.height ? `${f.width ?? "?"}x${f.height}` : f.vcodec === "none" ? "audio only" : "unknown",
69
+ f.fps ? String(f.fps) : "",
70
+ "│",
71
+ f.filesize ? fmtBytes(f.filesize) : "",
72
+ f.tbr ? `${f.tbr}k` : "",
73
+ f.protocol,
74
+ "│",
75
+ f.vcodec === "none" ? "audio only" : f.vcodec,
76
+ f.acodec === "none" ? "video only" : f.acodec,
77
+ f.format_note ?? "",
78
+ ]);
79
+ }
80
+ return table(rows);
81
+ }
82
+ export async function main(argv) {
83
+ let values;
84
+ let positionals;
85
+ function parse() {
86
+ return parseArgs({
87
+ args: argv,
88
+ allowPositionals: true,
89
+ options: {
90
+ format: { type: "string", short: "f" },
91
+ "list-formats": { type: "boolean", short: "F" },
92
+ output: { type: "string", short: "o" },
93
+ paths: { type: "string", short: "P" },
94
+ overwrite: { type: "boolean", short: "w" },
95
+ "no-continue": { type: "boolean" },
96
+ "merge-output-format": { type: "string" },
97
+ "remux-video": { type: "string" },
98
+ "ffmpeg-location": { type: "string" },
99
+ "dump-json": { type: "boolean", short: "j" },
100
+ "get-url": { type: "boolean", short: "g" },
101
+ simulate: { type: "boolean", short: "s" },
102
+ "print-path": { type: "boolean" },
103
+ "list-extractors": { type: "boolean" },
104
+ "concurrent-fragments": { type: "string", short: "N" },
105
+ retries: { type: "string", short: "R" },
106
+ header: { type: "string", multiple: true },
107
+ "header-host": { type: "string", multiple: true },
108
+ "user-agent": { type: "string" },
109
+ quiet: { type: "boolean", short: "q" },
110
+ verbose: { type: "boolean", short: "v" },
111
+ "no-progress": { type: "boolean" },
112
+ "progress-json": { type: "boolean" },
113
+ plugin: { type: "string", multiple: true },
114
+ "no-plugins": { type: "boolean" },
115
+ "no-color": { type: "boolean" },
116
+ help: { type: "boolean", short: "h" },
117
+ version: { type: "boolean" },
118
+ },
119
+ });
120
+ }
121
+ try {
122
+ ({ values, positionals } = parse());
123
+ }
124
+ catch (e) {
125
+ process.stderr.write(`ERROR: ${errMsg(e)}\nTry 'tidepull --help'.\n`);
126
+ return 2;
127
+ }
128
+ if (values.help)
129
+ return void process.stdout.write(HELP + "\n"), 0;
130
+ if (values.version)
131
+ return void process.stdout.write(VERSION + "\n"), 0;
132
+ const log = new Logger({
133
+ quiet: values.quiet,
134
+ verbose: values.verbose,
135
+ color: !values["no-color"] && shouldUseColor(),
136
+ });
137
+ if (!positionals.length && !values["list-extractors"]) {
138
+ log.error("You must provide at least one URL. Try 'tidepull --help'.");
139
+ return 2;
140
+ }
141
+ const headers = {};
142
+ for (const h of values.header ?? []) {
143
+ const i = h.indexOf(":");
144
+ if (i < 1) {
145
+ log.error(`Bad --header "${h}" (expected "Name: value")`);
146
+ return 2;
147
+ }
148
+ headers[h.slice(0, i).trim()] = h.slice(i + 1).trim();
149
+ }
150
+ const num = (v, d) => (v !== undefined && Number.isFinite(Number(v)) && Number(v) >= 0 ? Number(v) : d);
151
+ // plugins: explicit --plugin paths, plus the default dir unless disabled
152
+ const pluginPaths = [...(values.plugin ?? [])];
153
+ const defDir = defaultPluginDir();
154
+ if (!values["no-plugins"] && existsSync(defDir))
155
+ pluginPaths.unshift(defDir);
156
+ let plugins = [];
157
+ try {
158
+ plugins = await loadPlugins(pluginPaths);
159
+ }
160
+ catch (e) {
161
+ log.error(errMsg(e));
162
+ return e instanceof TidepullError ? e.exitCode : 1;
163
+ }
164
+ const tp = createTidepull({
165
+ http: { headers, headerHosts: values["header-host"] ?? [], userAgent: values["user-agent"], retries: num(values.retries, 3) },
166
+ plugins: [...plugins, dash],
167
+ ffmpeg: values["ffmpeg-location"],
168
+ });
169
+ tp.on(values["progress-json"] ? jsonRenderer() : humanRenderer(log, { progress: !values["no-progress"] && !values.quiet }));
170
+ for (const p of plugins)
171
+ log.debug(`Loaded plugin "${p.name}" (${p.extractors?.length ?? 0} extractor(s))`);
172
+ if (values["list-extractors"]) {
173
+ process.stdout.write(tp.extractors.join("\n") + "\n");
174
+ return 0;
175
+ }
176
+ const opts = {
177
+ format: values.format ?? DEFAULT_FORMAT,
178
+ output: values.output,
179
+ paths: values.paths,
180
+ resume: !values["no-continue"],
181
+ overwrite: !!values.overwrite,
182
+ concurrency: Math.max(1, num(values["concurrent-fragments"], 4)),
183
+ mergeFormat: values["merge-output-format"],
184
+ remuxVideo: values["remux-video"],
185
+ headers,
186
+ };
187
+ for (const k of Object.keys(opts))
188
+ if (opts[k] === undefined)
189
+ delete opts[k];
190
+ // Ctrl-C cancels in-flight work cleanly (partial .part files are kept for resume)
191
+ const ctl = new AbortController();
192
+ const onSigint = () => ctl.abort();
193
+ process.once("SIGINT", onSigint);
194
+ let code = 0;
195
+ try {
196
+ for (const url of positionals) {
197
+ try {
198
+ const info = await tp.extract(url, { signal: ctl.signal });
199
+ if (values["dump-json"])
200
+ process.stdout.write(JSON.stringify(info) + "\n");
201
+ else if (values["list-formats"]) {
202
+ log.tag("info", `Available formats for ${info.id}:`);
203
+ process.stdout.write(listFormats(info) + "\n");
204
+ }
205
+ else if (values["get-url"]) {
206
+ const chosen = tp.select(info, opts.format);
207
+ if (!chosen)
208
+ throw new TidepullError(`Requested format is not available: ${opts.format}`);
209
+ for (const f of chosen)
210
+ process.stdout.write(f.url + "\n");
211
+ }
212
+ else if (values.simulate) {
213
+ log.tag("info", `${info.title} (${info.formats.length} format(s))`);
214
+ }
215
+ else {
216
+ const file = await tp.download(info, { ...opts, signal: ctl.signal });
217
+ if (values["print-path"])
218
+ process.stdout.write(file + "\n");
219
+ }
220
+ }
221
+ catch (e) {
222
+ if (ctl.signal.aborted) {
223
+ process.stderr.write("\n");
224
+ log.error("Interrupted by user (partial files kept, re-run to resume)");
225
+ if (values["progress-json"])
226
+ process.stdout.write(JSON.stringify({ type: "error", message: "interrupted", url }) + "\n");
227
+ code = 130;
228
+ break;
229
+ }
230
+ log.error(errMsg(e));
231
+ if (values["progress-json"])
232
+ process.stdout.write(JSON.stringify({ type: "error", message: errMsg(e), url }) + "\n");
233
+ if (values.verbose && e instanceof Error && e.stack)
234
+ process.stderr.write(e.stack + "\n");
235
+ code = Math.max(code, e instanceof TidepullError ? e.exitCode : 1);
236
+ }
237
+ }
238
+ }
239
+ finally {
240
+ process.removeListener("SIGINT", onSigint);
241
+ }
242
+ return code;
243
+ }
@@ -0,0 +1,10 @@
1
+ import type { Extractor } from "./core/types.js";
2
+ /** Bump when the plugin contract changes in a breaking way. Plugins declare which version they target. */
3
+ export declare const PLUGIN_API_VERSION = 1;
4
+ export interface TidepullPlugin {
5
+ name: string;
6
+ apiVersion: number;
7
+ extractors?: Extractor[];
8
+ }
9
+ /** Typed identity helper for plugin authors: `export default definePlugin({...})` */
10
+ export declare const definePlugin: (p: TidepullPlugin) => TidepullPlugin;
@@ -0,0 +1,4 @@
1
+ /** Bump when the plugin contract changes in a breaking way. Plugins declare which version they target. */
2
+ export const PLUGIN_API_VERSION = 1;
3
+ /** Typed identity helper for plugin authors: `export default definePlugin({...})` */
4
+ export const definePlugin = (p) => p;
@@ -0,0 +1,48 @@
1
+ import { type DownloadOptions } from "./core/pipeline.js";
2
+ import { type TidepullEvent } from "./core/events.js";
3
+ import { Http, type HttpOptions } from "./core/http.js";
4
+ import type { Format, Info } from "./core/types.js";
5
+ import type { TidepullPlugin } from "./plugins.js";
6
+ export type Listener = (e: TidepullEvent) => void;
7
+ export interface TidepullOptions {
8
+ http?: HttpOptions;
9
+ plugins?: TidepullPlugin[];
10
+ /** ffmpeg binary or directory (default: search PATH) */
11
+ ffmpeg?: string;
12
+ onEvent?: Listener;
13
+ }
14
+ export interface CallOptions {
15
+ signal?: AbortSignal;
16
+ }
17
+ /**
18
+ * The library entry point. No terminal I/O: everything observable goes through events.
19
+ *
20
+ * const g = createTidepull();
21
+ * g.on((e) => e.type === "progress" && console.log(e.downloaded, e.total));
22
+ * const info = await g.extract(url);
23
+ * const file = await g.download(info, { format: "bv*[height<=720]+ba/b", paths: "./out" });
24
+ */
25
+ export declare class Tidepull {
26
+ readonly http: Http;
27
+ private plugins;
28
+ private registry;
29
+ private listeners;
30
+ private ffmpeg?;
31
+ constructor(o?: TidepullOptions);
32
+ /** Subscribe to events. Returns an unsubscribe function. A throwing listener never breaks a download. */
33
+ on(fn: Listener): () => void;
34
+ /** Extractor names in priority order. */
35
+ get extractors(): string[];
36
+ /** Register a plugin (takes priority over built-in extractors). */
37
+ use(plugin: TidepullPlugin): this;
38
+ private ctx;
39
+ private guard;
40
+ extract(url: string, o?: CallOptions): Promise<Info>;
41
+ /** Pure function: which format(s) would this selector pick? 2+ means "merge". undefined = no match. */
42
+ select(info: Info, selector?: string): Format[] | undefined;
43
+ /** Downloads the selected format(s). Resolves to the final file path. */
44
+ download(info: Info, o?: Partial<DownloadOptions> & CallOptions): Promise<string>;
45
+ /** extract + download */
46
+ pull(url: string, o?: Partial<DownloadOptions> & CallOptions): Promise<string>;
47
+ }
48
+ export declare const createTidepull: (o?: TidepullOptions) => Tidepull;
@@ -0,0 +1,107 @@
1
+ import { downloadInfo, extractInfo, DEFAULT_OUTPUT } from "./core/pipeline.js";
2
+ import { abortError } from "./core/errors.js";
3
+ import { makeLog } from "./core/events.js";
4
+ import { Http } from "./core/http.js";
5
+ import { DEFAULT_FORMAT, selectFormats } from "./core/selector.js";
6
+ import { buildRegistry } from "./extractors/index.js";
7
+ /**
8
+ * The library entry point. No terminal I/O: everything observable goes through events.
9
+ *
10
+ * const g = createTidepull();
11
+ * g.on((e) => e.type === "progress" && console.log(e.downloaded, e.total));
12
+ * const info = await g.extract(url);
13
+ * const file = await g.download(info, { format: "bv*[height<=720]+ba/b", paths: "./out" });
14
+ */
15
+ export class Tidepull {
16
+ http;
17
+ plugins;
18
+ registry;
19
+ listeners = new Set();
20
+ ffmpeg;
21
+ constructor(o = {}) {
22
+ this.http = new Http({ headerHosts: [], ...o.http });
23
+ this.plugins = [...(o.plugins ?? [])];
24
+ this.registry = buildRegistry(this.plugins);
25
+ this.ffmpeg = o.ffmpeg;
26
+ if (o.onEvent)
27
+ this.listeners.add(o.onEvent);
28
+ }
29
+ /** Subscribe to events. Returns an unsubscribe function. A throwing listener never breaks a download. */
30
+ on(fn) {
31
+ this.listeners.add(fn);
32
+ return () => void this.listeners.delete(fn);
33
+ }
34
+ /** Extractor names in priority order. */
35
+ get extractors() {
36
+ return this.registry.map((e) => e.name);
37
+ }
38
+ /** Register a plugin (takes priority over built-in extractors). */
39
+ use(plugin) {
40
+ this.plugins.push(plugin);
41
+ this.registry = buildRegistry(this.plugins);
42
+ return this;
43
+ }
44
+ ctx(signal) {
45
+ const emit = (e) => {
46
+ for (const l of this.listeners) {
47
+ try {
48
+ l(e);
49
+ }
50
+ catch {
51
+ /* listeners must not break the engine */
52
+ }
53
+ }
54
+ };
55
+ return { http: this.http.scoped(signal), emit, log: makeLog(emit), extractors: this.registry, signal };
56
+ }
57
+ async guard(signal, fn) {
58
+ try {
59
+ return await fn();
60
+ }
61
+ catch (e) {
62
+ if (signal?.aborted)
63
+ throw abortError();
64
+ throw e;
65
+ }
66
+ }
67
+ extract(url, o = {}) {
68
+ try {
69
+ this.http.trust(/^[a-z][a-z0-9+.-]*:\/\//i.test(url) ? url : `https://${url}`);
70
+ }
71
+ catch {
72
+ /* invalid URL: extractInfo reports it */
73
+ }
74
+ return this.guard(o.signal, () => extractInfo(url, this.ctx(o.signal)));
75
+ }
76
+ /** Pure function: which format(s) would this selector pick? 2+ means "merge". undefined = no match. */
77
+ select(info, selector = DEFAULT_FORMAT) {
78
+ return selectFormats(selector, info.formats);
79
+ }
80
+ /** Downloads the selected format(s). Resolves to the final file path. */
81
+ download(info, o = {}) {
82
+ const { signal, ...rest } = o;
83
+ const opts = {
84
+ format: DEFAULT_FORMAT,
85
+ output: DEFAULT_OUTPUT,
86
+ paths: ".",
87
+ resume: true,
88
+ overwrite: false,
89
+ concurrency: 4,
90
+ mergeFormat: "mp4",
91
+ ffmpeg: this.ffmpeg,
92
+ headers: {},
93
+ ...rest,
94
+ };
95
+ const ctx = this.ctx(signal);
96
+ return this.guard(signal, async () => {
97
+ const file = await downloadInfo(info, opts, ctx);
98
+ ctx.emit({ type: "done", file });
99
+ return file;
100
+ });
101
+ }
102
+ /** extract + download */
103
+ async pull(url, o = {}) {
104
+ return this.download(await this.extract(url, o), o);
105
+ }
106
+ }
107
+ export const createTidepull = (o) => new Tidepull(o);
@@ -0,0 +1,4 @@
1
+ export declare function fmtBytes(n: number): string;
2
+ export declare function fmtTime(sec: number): string;
3
+ /** Simple left-aligned table. */
4
+ export declare function table(rows: string[][]): string;
@@ -0,0 +1,26 @@
1
+ export function fmtBytes(n) {
2
+ if (n < 1024)
3
+ return `${n}B`;
4
+ const units = ["KiB", "MiB", "GiB", "TiB"];
5
+ let v = n / 1024;
6
+ let i = 0;
7
+ while (v >= 1024 && i < units.length - 1) {
8
+ v /= 1024;
9
+ i++;
10
+ }
11
+ return `${v.toFixed(2)}${units[i]}`;
12
+ }
13
+ export function fmtTime(sec) {
14
+ if (!Number.isFinite(sec) || sec < 0)
15
+ return "--:--";
16
+ const s = Math.round(sec);
17
+ const h = Math.floor(s / 3600);
18
+ const m = String(Math.floor((s % 3600) / 60)).padStart(2, "0");
19
+ const ss = String(s % 60).padStart(2, "0");
20
+ return h ? `${h}:${m}:${ss}` : `${m}:${ss}`;
21
+ }
22
+ /** Simple left-aligned table. */
23
+ export function table(rows) {
24
+ const widths = rows[0].map((_, c) => Math.max(...rows.map((r) => (r[c] ?? "").length)));
25
+ return rows.map((r) => r.map((cell, c) => (cell ?? "").padEnd(widths[c])).join(" ").trimEnd()).join("\n");
26
+ }
@@ -0,0 +1,19 @@
1
+ export interface LoggerOptions {
2
+ quiet?: boolean;
3
+ verbose?: boolean;
4
+ color?: boolean;
5
+ }
6
+ /** Honors NO_COLOR / FORCE_COLOR, and only colors a real terminal. */
7
+ export declare function shouldUseColor(env?: NodeJS.ProcessEnv, isTTY?: boolean): boolean;
8
+ /** All human-facing output goes to stderr. stdout is reserved for data you can pipe. */
9
+ export declare class Logger {
10
+ quiet: boolean;
11
+ verbose: boolean;
12
+ color: boolean;
13
+ constructor(o?: LoggerOptions);
14
+ private paint;
15
+ tag(tag: string, msg: string): void;
16
+ debug(msg: string): void;
17
+ warn(msg: string): void;
18
+ error(msg: string): void;
19
+ }
package/dist/ui/log.js ADDED
@@ -0,0 +1,37 @@
1
+ const C = { red: "\x1b[31m", yellow: "\x1b[33m", cyan: "\x1b[36m", dim: "\x1b[2m", reset: "\x1b[0m" };
2
+ /** Honors NO_COLOR / FORCE_COLOR, and only colors a real terminal. */
3
+ export function shouldUseColor(env = process.env, isTTY = !!process.stderr.isTTY) {
4
+ if (env.NO_COLOR)
5
+ return false;
6
+ if (env.FORCE_COLOR)
7
+ return true;
8
+ return isTTY && env.TERM !== "dumb";
9
+ }
10
+ /** All human-facing output goes to stderr. stdout is reserved for data you can pipe. */
11
+ export class Logger {
12
+ quiet;
13
+ verbose;
14
+ color;
15
+ constructor(o = {}) {
16
+ this.quiet = o.quiet ?? false;
17
+ this.verbose = o.verbose ?? false;
18
+ this.color = o.color ?? false;
19
+ }
20
+ paint(c, s) {
21
+ return this.color ? c + s + C.reset : s;
22
+ }
23
+ tag(tag, msg) {
24
+ if (!this.quiet)
25
+ process.stderr.write(`${this.paint(C.cyan, `[${tag}]`)} ${msg}\n`);
26
+ }
27
+ debug(msg) {
28
+ if (this.verbose)
29
+ process.stderr.write(`${this.paint(C.dim, "[debug]")} ${msg}\n`);
30
+ }
31
+ warn(msg) {
32
+ process.stderr.write(`${this.paint(C.yellow, "WARNING:")} ${msg}\n`);
33
+ }
34
+ error(msg) {
35
+ process.stderr.write(`${this.paint(C.red, "ERROR:")} ${msg}\n`);
36
+ }
37
+ }
@@ -0,0 +1,9 @@
1
+ import type { TidepullEvent } from "../core/events.js";
2
+ import type { Logger } from "./log.js";
3
+ /** Human renderer: turns engine events into yt-dlp-style terminal output (stderr). Redraws one progress line on a TTY. */
4
+ export declare function humanRenderer(log: Logger, o: {
5
+ progress: boolean;
6
+ stream?: NodeJS.WriteStream;
7
+ }): (e: TidepullEvent) => void;
8
+ /** Machine renderer: one JSON event per line on stdout (NDJSON). */
9
+ export declare const jsonRenderer: () => ((e: TidepullEvent) => void);
@@ -0,0 +1,60 @@
1
+ import { fmtBytes, fmtTime } from "./format.js";
2
+ /** Human renderer: turns engine events into yt-dlp-style terminal output (stderr). Redraws one progress line on a TTY. */
3
+ export function humanRenderer(log, o) {
4
+ const stream = o.stream ?? process.stderr;
5
+ const live = o.progress && !!stream.isTTY;
6
+ let drawn = false;
7
+ const clear = () => {
8
+ if (drawn)
9
+ stream.write("\r\x1b[K");
10
+ drawn = false;
11
+ };
12
+ return (e) => {
13
+ switch (e.type) {
14
+ case "log":
15
+ clear();
16
+ if (e.level === "debug")
17
+ log.debug(e.message);
18
+ else if (e.level === "warn")
19
+ log.warn(e.message);
20
+ else
21
+ log.tag(e.tag ?? "info", e.message);
22
+ break;
23
+ case "extract":
24
+ log.tag(e.extractor, `Extracting URL: ${e.url}`);
25
+ break;
26
+ case "start":
27
+ log.tag("download", `Destination: ${e.dest}`);
28
+ break;
29
+ case "progress": {
30
+ if (!live)
31
+ break;
32
+ const pct = e.total ? `${((e.downloaded / e.total) * 100).toFixed(1).padStart(5)}%` : "";
33
+ const size = e.total ? ` of ${e.estimated ? "~" : ""}${fmtBytes(e.total)}` : ` ${fmtBytes(e.downloaded)}`;
34
+ const rate = e.speed ? ` at ${fmtBytes(e.speed)}/s` : "";
35
+ const eta = e.eta !== undefined ? ` ETA ${fmtTime(e.eta)}` : "";
36
+ stream.write(`\r\x1b[K[download] ${pct}${size}${rate}${eta}`);
37
+ drawn = true;
38
+ break;
39
+ }
40
+ case "finish":
41
+ clear();
42
+ log.tag("download", `100% of ${fmtBytes(e.bytes)} in ${fmtTime(e.seconds)}${e.speed ? ` at ${fmtBytes(e.speed)}/s` : ""}`);
43
+ break;
44
+ case "merge":
45
+ log.tag("merger", `Merging formats into "${e.output}"`);
46
+ break;
47
+ case "remux":
48
+ log.tag("remux", `Remuxing to "${e.output}"`);
49
+ break;
50
+ case "done":
51
+ log.tag("done", e.file);
52
+ break;
53
+ case "error":
54
+ clear();
55
+ break;
56
+ }
57
+ };
58
+ }
59
+ /** Machine renderer: one JSON event per line on stdout (NDJSON). */
60
+ export const jsonRenderer = () => (e) => void process.stdout.write(JSON.stringify(e) + "\n");