@boy-offi9-inc/tidepull 0.0.0-stage → 0.1.0-rc.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/LICENSE +21 -0
- package/README.md +108 -2
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +3 -0
- package/dist/core/downloader.d.ts +44 -0
- package/dist/core/downloader.js +160 -0
- package/dist/core/errors.d.ts +11 -0
- package/dist/core/errors.js +22 -0
- package/dist/core/events.d.ts +51 -0
- package/dist/core/events.js +5 -0
- package/dist/core/ffmpeg.d.ts +3 -0
- package/dist/core/ffmpeg.js +38 -0
- package/dist/core/hls.d.ts +41 -0
- package/dist/core/hls.js +102 -0
- package/dist/core/http.d.ts +46 -0
- package/dist/core/http.js +120 -0
- package/dist/core/meter.d.ts +6 -0
- package/dist/core/meter.js +17 -0
- package/dist/core/pipeline.d.ts +25 -0
- package/dist/core/pipeline.js +128 -0
- package/dist/core/selector.d.ts +32 -0
- package/dist/core/selector.js +166 -0
- package/dist/core/template.d.ts +3 -0
- package/dist/core/template.js +20 -0
- package/dist/core/types.d.ts +56 -0
- package/dist/core/types.js +1 -0
- package/dist/dash/index.d.ts +7 -0
- package/dist/dash/index.js +70 -0
- package/dist/dash/parse.d.ts +31 -0
- package/dist/dash/parse.js +140 -0
- package/dist/dash/xml.d.ts +9 -0
- package/dist/dash/xml.js +56 -0
- package/dist/extractors/direct.d.ts +3 -0
- package/dist/extractors/direct.js +34 -0
- package/dist/extractors/generic.d.ts +3 -0
- package/dist/extractors/generic.js +104 -0
- package/dist/extractors/hls.d.ts +3 -0
- package/dist/extractors/hls.js +72 -0
- package/dist/extractors/index.d.ts +5 -0
- package/dist/extractors/index.js +9 -0
- package/dist/extractors/util.d.ts +7 -0
- package/dist/extractors/util.js +13 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +8 -0
- package/dist/loader.d.ts +7 -0
- package/dist/loader.js +76 -0
- package/dist/main.d.ts +3 -0
- package/dist/main.js +244 -0
- package/dist/plugins.d.ts +10 -0
- package/dist/plugins.js +4 -0
- package/dist/tidepull.d.ts +48 -0
- package/dist/tidepull.js +106 -0
- package/dist/ui/format.d.ts +4 -0
- package/dist/ui/format.js +26 -0
- package/dist/ui/log.d.ts +19 -0
- package/dist/ui/log.js +37 -0
- package/dist/ui/render.d.ts +9 -0
- package/dist/ui/render.js +71 -0
- 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
package/dist/main.js
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
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
|
+
/** Package version, read from package.json. */
|
|
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
|
+
or just the title when the id is the same)
|
|
25
|
+
-P, --paths DIR Download directory (default: .)
|
|
26
|
+
-w, --overwrite Overwrite existing files
|
|
27
|
+
--no-continue Do not resume partial downloads
|
|
28
|
+
--merge-output-format Container when merging video+audio (default: mp4)
|
|
29
|
+
--remux-video EXT Remux the result into EXT with ffmpeg (e.g. mp4)
|
|
30
|
+
--ffmpeg-location PATH ffmpeg binary or directory
|
|
31
|
+
|
|
32
|
+
Info only (nothing is downloaded):
|
|
33
|
+
-j, --dump-json Print the info dict as JSON
|
|
34
|
+
-g, --get-url Print the selected format URL(s)
|
|
35
|
+
-s, --simulate Extract only
|
|
36
|
+
--print-path After downloading, print the final file path on stdout
|
|
37
|
+
--list-extractors List extractors and exit
|
|
38
|
+
|
|
39
|
+
Plugins:
|
|
40
|
+
--plugin PATH Load a plugin file or directory (repeatable). Plugins run with your privileges!
|
|
41
|
+
--no-plugins Skip auto-loading ~/.config/tidepull/plugins (or $TIDEPULL_PLUGIN_DIR)
|
|
42
|
+
|
|
43
|
+
Network:
|
|
44
|
+
-N, --concurrent-fragments N HLS segments fetched in parallel (default: 4)
|
|
45
|
+
-R, --retries N Retries per request (default: 3)
|
|
46
|
+
--header "Name: value" Extra request header (repeatable). Secret-looking headers (Authorization,
|
|
47
|
+
Cookie, tokens...) are sent only to the URL's own origin...
|
|
48
|
+
--header-host HOST ...plus these hosts ("cdn.example.com" or "*.example.com"), repeatable
|
|
49
|
+
--user-agent UA Custom User-Agent
|
|
50
|
+
|
|
51
|
+
General:
|
|
52
|
+
-q, --quiet Only print errors/warnings
|
|
53
|
+
-v, --verbose Debug output
|
|
54
|
+
--no-progress Disable the progress line
|
|
55
|
+
--progress-json Emit engine events as NDJSON on stdout (for GUIs/scripts)
|
|
56
|
+
--no-color Disable colors (also honors NO_COLOR)
|
|
57
|
+
-h, --help Show this help
|
|
58
|
+
--version Show version
|
|
59
|
+
|
|
60
|
+
stdout carries data only (-j, -F, -g, --print-path, --progress-json). Everything else goes to stderr.
|
|
61
|
+
Exit codes: 0 ok, 1 error, 2 usage error, 130 interrupted.`;
|
|
62
|
+
function listFormats(info) {
|
|
63
|
+
const rows = [["ID", "EXT", "RESOLUTION", "FPS", "│", "SIZE", "TBR", "PROTO", "│", "VCODEC", "ACODEC", "NOTE"]];
|
|
64
|
+
const sorted = [...info.formats].sort((a, b) => (a.height ?? 0) - (b.height ?? 0) || (a.tbr ?? 0) - (b.tbr ?? 0));
|
|
65
|
+
for (const f of sorted) {
|
|
66
|
+
rows.push([
|
|
67
|
+
f.format_id,
|
|
68
|
+
f.ext,
|
|
69
|
+
f.height ? `${f.width ?? "?"}x${f.height}` : f.vcodec === "none" ? "audio only" : "unknown",
|
|
70
|
+
f.fps ? String(f.fps) : "",
|
|
71
|
+
"│",
|
|
72
|
+
f.filesize ? fmtBytes(f.filesize) : "",
|
|
73
|
+
f.tbr ? `${f.tbr}k` : "",
|
|
74
|
+
f.protocol,
|
|
75
|
+
"│",
|
|
76
|
+
f.vcodec === "none" ? "audio only" : f.vcodec,
|
|
77
|
+
f.acodec === "none" ? "video only" : f.acodec,
|
|
78
|
+
f.format_note ?? "",
|
|
79
|
+
]);
|
|
80
|
+
}
|
|
81
|
+
return table(rows);
|
|
82
|
+
}
|
|
83
|
+
export async function main(argv) {
|
|
84
|
+
let values;
|
|
85
|
+
let positionals;
|
|
86
|
+
function parse() {
|
|
87
|
+
return parseArgs({
|
|
88
|
+
args: argv,
|
|
89
|
+
allowPositionals: true,
|
|
90
|
+
options: {
|
|
91
|
+
format: { type: "string", short: "f" },
|
|
92
|
+
"list-formats": { type: "boolean", short: "F" },
|
|
93
|
+
output: { type: "string", short: "o" },
|
|
94
|
+
paths: { type: "string", short: "P" },
|
|
95
|
+
overwrite: { type: "boolean", short: "w" },
|
|
96
|
+
"no-continue": { type: "boolean" },
|
|
97
|
+
"merge-output-format": { type: "string" },
|
|
98
|
+
"remux-video": { type: "string" },
|
|
99
|
+
"ffmpeg-location": { type: "string" },
|
|
100
|
+
"dump-json": { type: "boolean", short: "j" },
|
|
101
|
+
"get-url": { type: "boolean", short: "g" },
|
|
102
|
+
simulate: { type: "boolean", short: "s" },
|
|
103
|
+
"print-path": { type: "boolean" },
|
|
104
|
+
"list-extractors": { type: "boolean" },
|
|
105
|
+
"concurrent-fragments": { type: "string", short: "N" },
|
|
106
|
+
retries: { type: "string", short: "R" },
|
|
107
|
+
header: { type: "string", multiple: true },
|
|
108
|
+
"header-host": { type: "string", multiple: true },
|
|
109
|
+
"user-agent": { type: "string" },
|
|
110
|
+
quiet: { type: "boolean", short: "q" },
|
|
111
|
+
verbose: { type: "boolean", short: "v" },
|
|
112
|
+
"no-progress": { type: "boolean" },
|
|
113
|
+
"progress-json": { type: "boolean" },
|
|
114
|
+
plugin: { type: "string", multiple: true },
|
|
115
|
+
"no-plugins": { type: "boolean" },
|
|
116
|
+
"no-color": { type: "boolean" },
|
|
117
|
+
help: { type: "boolean", short: "h" },
|
|
118
|
+
version: { type: "boolean" },
|
|
119
|
+
},
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
try {
|
|
123
|
+
({ values, positionals } = parse());
|
|
124
|
+
}
|
|
125
|
+
catch (e) {
|
|
126
|
+
process.stderr.write(`ERROR: ${errMsg(e)}\nTry 'tidepull --help'.\n`);
|
|
127
|
+
return 2;
|
|
128
|
+
}
|
|
129
|
+
if (values.help)
|
|
130
|
+
return void process.stdout.write(HELP + "\n"), 0;
|
|
131
|
+
if (values.version)
|
|
132
|
+
return void process.stdout.write(VERSION + "\n"), 0;
|
|
133
|
+
const log = new Logger({
|
|
134
|
+
quiet: values.quiet,
|
|
135
|
+
verbose: values.verbose,
|
|
136
|
+
color: !values["no-color"] && shouldUseColor(),
|
|
137
|
+
});
|
|
138
|
+
if (!positionals.length && !values["list-extractors"]) {
|
|
139
|
+
log.error("You must provide at least one URL. Try 'tidepull --help'.");
|
|
140
|
+
return 2;
|
|
141
|
+
}
|
|
142
|
+
const headers = {};
|
|
143
|
+
for (const h of values.header ?? []) {
|
|
144
|
+
const i = h.indexOf(":");
|
|
145
|
+
if (i < 1) {
|
|
146
|
+
log.error(`Bad --header "${h}" (expected "Name: value")`);
|
|
147
|
+
return 2;
|
|
148
|
+
}
|
|
149
|
+
headers[h.slice(0, i).trim()] = h.slice(i + 1).trim();
|
|
150
|
+
}
|
|
151
|
+
const num = (v, d) => (v !== undefined && Number.isFinite(Number(v)) && Number(v) >= 0 ? Number(v) : d);
|
|
152
|
+
// plugins: explicit --plugin paths, plus the default dir unless disabled
|
|
153
|
+
const pluginPaths = [...(values.plugin ?? [])];
|
|
154
|
+
const defDir = defaultPluginDir();
|
|
155
|
+
if (!values["no-plugins"] && existsSync(defDir))
|
|
156
|
+
pluginPaths.unshift(defDir);
|
|
157
|
+
let plugins = [];
|
|
158
|
+
try {
|
|
159
|
+
plugins = await loadPlugins(pluginPaths);
|
|
160
|
+
}
|
|
161
|
+
catch (e) {
|
|
162
|
+
log.error(errMsg(e));
|
|
163
|
+
return e instanceof TidepullError ? e.exitCode : 1;
|
|
164
|
+
}
|
|
165
|
+
const tp = createTidepull({
|
|
166
|
+
http: { headers, headerHosts: values["header-host"] ?? [], userAgent: values["user-agent"], retries: num(values.retries, 3) },
|
|
167
|
+
plugins: [...plugins, dash],
|
|
168
|
+
ffmpeg: values["ffmpeg-location"],
|
|
169
|
+
});
|
|
170
|
+
tp.on(values["progress-json"] ? jsonRenderer() : humanRenderer(log, { progress: !values["no-progress"] && !values.quiet }));
|
|
171
|
+
for (const p of plugins)
|
|
172
|
+
log.debug(`Loaded plugin "${p.name}" (${p.extractors?.length ?? 0} extractor(s))`);
|
|
173
|
+
if (values["list-extractors"]) {
|
|
174
|
+
process.stdout.write(tp.extractors.join("\n") + "\n");
|
|
175
|
+
return 0;
|
|
176
|
+
}
|
|
177
|
+
const opts = {
|
|
178
|
+
format: values.format ?? DEFAULT_FORMAT,
|
|
179
|
+
output: values.output,
|
|
180
|
+
paths: values.paths,
|
|
181
|
+
resume: !values["no-continue"],
|
|
182
|
+
overwrite: !!values.overwrite,
|
|
183
|
+
concurrency: Math.max(1, num(values["concurrent-fragments"], 4)),
|
|
184
|
+
mergeFormat: values["merge-output-format"],
|
|
185
|
+
remuxVideo: values["remux-video"],
|
|
186
|
+
headers,
|
|
187
|
+
};
|
|
188
|
+
for (const k of Object.keys(opts))
|
|
189
|
+
if (opts[k] === undefined)
|
|
190
|
+
delete opts[k];
|
|
191
|
+
// Ctrl-C cancels in-flight work cleanly (partial .part files are kept for resume)
|
|
192
|
+
const ctl = new AbortController();
|
|
193
|
+
const onSigint = () => ctl.abort();
|
|
194
|
+
process.once("SIGINT", onSigint);
|
|
195
|
+
let code = 0;
|
|
196
|
+
try {
|
|
197
|
+
for (const url of positionals) {
|
|
198
|
+
try {
|
|
199
|
+
const info = await tp.extract(url, { signal: ctl.signal });
|
|
200
|
+
if (values["dump-json"])
|
|
201
|
+
process.stdout.write(JSON.stringify(info) + "\n");
|
|
202
|
+
else if (values["list-formats"]) {
|
|
203
|
+
log.tag("info", `Available formats for ${info.id}:`);
|
|
204
|
+
process.stdout.write(listFormats(info) + "\n");
|
|
205
|
+
}
|
|
206
|
+
else if (values["get-url"]) {
|
|
207
|
+
const chosen = tp.select(info, opts.format);
|
|
208
|
+
if (!chosen)
|
|
209
|
+
throw new TidepullError(`Requested format is not available: ${opts.format}`);
|
|
210
|
+
for (const f of chosen)
|
|
211
|
+
process.stdout.write(f.url + "\n");
|
|
212
|
+
}
|
|
213
|
+
else if (values.simulate) {
|
|
214
|
+
log.tag("info", `${info.title} (${info.formats.length} format(s))`);
|
|
215
|
+
}
|
|
216
|
+
else {
|
|
217
|
+
const file = await tp.download(info, { ...opts, signal: ctl.signal });
|
|
218
|
+
if (values["print-path"])
|
|
219
|
+
process.stdout.write(file + "\n");
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
catch (e) {
|
|
223
|
+
if (ctl.signal.aborted) {
|
|
224
|
+
process.stderr.write("\n");
|
|
225
|
+
log.error("Interrupted by user (partial files kept, re-run to resume)");
|
|
226
|
+
if (values["progress-json"])
|
|
227
|
+
process.stdout.write(JSON.stringify({ type: "error", message: "interrupted", url }) + "\n");
|
|
228
|
+
code = 130;
|
|
229
|
+
break;
|
|
230
|
+
}
|
|
231
|
+
log.error(errMsg(e));
|
|
232
|
+
if (values["progress-json"])
|
|
233
|
+
process.stdout.write(JSON.stringify({ type: "error", message: errMsg(e), url }) + "\n");
|
|
234
|
+
if (values.verbose && e instanceof Error && e.stack)
|
|
235
|
+
process.stderr.write(e.stack + "\n");
|
|
236
|
+
code = Math.max(code, e instanceof TidepullError ? e.exitCode : 1);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
finally {
|
|
241
|
+
process.removeListener("SIGINT", onSigint);
|
|
242
|
+
}
|
|
243
|
+
return code;
|
|
244
|
+
}
|
|
@@ -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;
|
package/dist/plugins.js
ADDED
|
@@ -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
|
+
/** Which format(s) the selector picks (two or more means merge), or undefined if none 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;
|
package/dist/tidepull.js
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { downloadInfo, extractInfo } 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
|
+
/** Which format(s) the selector picks (two or more means merge), or undefined if none 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
|
+
paths: ".",
|
|
86
|
+
resume: true,
|
|
87
|
+
overwrite: false,
|
|
88
|
+
concurrency: 4,
|
|
89
|
+
mergeFormat: "mp4",
|
|
90
|
+
ffmpeg: this.ffmpeg,
|
|
91
|
+
headers: {},
|
|
92
|
+
...rest,
|
|
93
|
+
};
|
|
94
|
+
const ctx = this.ctx(signal);
|
|
95
|
+
return this.guard(signal, async () => {
|
|
96
|
+
const file = await downloadInfo(info, opts, ctx);
|
|
97
|
+
ctx.emit({ type: "done", file });
|
|
98
|
+
return file;
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
/** extract + download */
|
|
102
|
+
async pull(url, o = {}) {
|
|
103
|
+
return this.download(await this.extract(url, o), o);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
export const createTidepull = (o) => new Tidepull(o);
|
|
@@ -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
|
+
}
|
package/dist/ui/log.d.ts
ADDED
|
@@ -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
|
+
/** Renders engine events as terminal output on stderr, redrawing 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
|
+
/** Writes one JSON event per line to stdout (NDJSON). */
|
|
9
|
+
export declare const jsonRenderer: () => ((e: TidepullEvent) => void);
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { fmtBytes, fmtTime } from "./format.js";
|
|
2
|
+
/** Renders engine events as terminal output on stderr, redrawing 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 cols = stream.columns || 80;
|
|
33
|
+
const pct = e.total ? `${((e.downloaded / e.total) * 100).toFixed(1).padStart(5)}%` : "";
|
|
34
|
+
const size = e.total ? ` of ${e.estimated ? "~" : ""}${fmtBytes(e.total)}` : ` ${fmtBytes(e.downloaded)}`;
|
|
35
|
+
const rate = e.speed ? ` at ${fmtBytes(e.speed)}/s` : "";
|
|
36
|
+
const eta = e.eta !== undefined ? ` ETA ${fmtTime(e.eta)}` : "";
|
|
37
|
+
// Keep the line narrower than the terminal: a wrapped line cannot be redrawn in place.
|
|
38
|
+
let line = `[download] ${pct}${size}${rate}${eta}`;
|
|
39
|
+
if (line.length >= cols)
|
|
40
|
+
line = `[download] ${pct}${size}${rate}`;
|
|
41
|
+
if (line.length >= cols)
|
|
42
|
+
line = `${pct}${size}${rate}`.trim();
|
|
43
|
+
if (line.length >= cols)
|
|
44
|
+
line = `${pct}${size}`.trim();
|
|
45
|
+
if (line.length >= cols)
|
|
46
|
+
line = (pct || fmtBytes(e.downloaded)).trim();
|
|
47
|
+
stream.write(`\r\x1b[K${line.slice(0, Math.max(1, cols - 1))}`);
|
|
48
|
+
drawn = true;
|
|
49
|
+
break;
|
|
50
|
+
}
|
|
51
|
+
case "finish":
|
|
52
|
+
clear();
|
|
53
|
+
log.tag("download", `100% of ${fmtBytes(e.bytes)} in ${fmtTime(e.seconds)}${e.speed ? ` at ${fmtBytes(e.speed)}/s` : ""}`);
|
|
54
|
+
break;
|
|
55
|
+
case "merge":
|
|
56
|
+
log.tag("merger", `Merging formats into "${e.output}"`);
|
|
57
|
+
break;
|
|
58
|
+
case "remux":
|
|
59
|
+
log.tag("remux", `Remuxing to "${e.output}"`);
|
|
60
|
+
break;
|
|
61
|
+
case "done":
|
|
62
|
+
log.tag("done", e.file);
|
|
63
|
+
break;
|
|
64
|
+
case "error":
|
|
65
|
+
clear();
|
|
66
|
+
break;
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
/** Writes one JSON event per line to stdout (NDJSON). */
|
|
71
|
+
export const jsonRenderer = () => (e) => void process.stdout.write(JSON.stringify(e) + "\n");
|