@zfadhli/tokrec-cli 0.0.0-stage → 0.15.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/dist/bin.mjs +148 -0
- package/dist/bin.mjs.map +1 -0
- package/dist/browser-cookies.mjs +129 -0
- package/dist/browser-cookies.mjs.map +1 -0
- package/dist/cli.mjs +195 -0
- package/dist/cli.mjs.map +1 -0
- package/dist/package.mjs +6 -0
- package/dist/package.mjs.map +1 -0
- package/dist/tmux.mjs +84 -0
- package/dist/tmux.mjs.map +1 -0
- package/dist/ui.mjs +213 -0
- package/dist/ui.mjs.map +1 -0
- package/package.json +33 -4
- package/README.md +0 -3
package/dist/bin.mjs
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
import { extractTikTokCookiesFromFirefox, loadCookiesFile } from "./browser-cookies.mjs";
|
|
3
|
+
import { parseArgs } from "./cli.mjs";
|
|
4
|
+
import { tmuxStart, tmuxStatus, tmuxStop } from "./tmux.mjs";
|
|
5
|
+
import { attachDisplay, createDisplay } from "./ui.mjs";
|
|
6
|
+
import { existsSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { TikTokError, createRecorder } from "@zfadhli/tokrec";
|
|
9
|
+
import * as color from "yoctocolors";
|
|
10
|
+
//#region src/bin.ts
|
|
11
|
+
/**
|
|
12
|
+
* Entry point — parses CLI args, creates the recorder, and handles signals.
|
|
13
|
+
* The record flow's output wiring lives in `ui.attachDisplay`.
|
|
14
|
+
*/
|
|
15
|
+
async function main() {
|
|
16
|
+
let result;
|
|
17
|
+
try {
|
|
18
|
+
result = parseArgs();
|
|
19
|
+
} catch (err) {
|
|
20
|
+
if (err instanceof TikTokError && err.code === "config-error") {
|
|
21
|
+
console.error(`${color.red("Error:")} ${err.message}`);
|
|
22
|
+
process.exit(1);
|
|
23
|
+
}
|
|
24
|
+
throw err;
|
|
25
|
+
}
|
|
26
|
+
if (result.command === "start") {
|
|
27
|
+
const userMatch = result.args.find((_, i, a) => a[i - 1] === "--user" || a[i - 1] === "-u");
|
|
28
|
+
if (!userMatch) {
|
|
29
|
+
console.error(`${color.red("Error:")} --user is required for "start" command`);
|
|
30
|
+
process.exit(1);
|
|
31
|
+
}
|
|
32
|
+
const cmd = `tokrec ${result.args.join(" ")}`;
|
|
33
|
+
try {
|
|
34
|
+
await tmuxStart(userMatch, cmd);
|
|
35
|
+
console.log(`${color.green("✓")} Session "tokrec-${userMatch}" started in background`);
|
|
36
|
+
console.log(` tmux attach -t tokrec-${userMatch} — view live output`);
|
|
37
|
+
console.log(` tokrec stop -u ${userMatch} — stop recording`);
|
|
38
|
+
} catch (err) {
|
|
39
|
+
console.error(`${color.red("Error:")} ${err instanceof Error ? err.message : String(err)}`);
|
|
40
|
+
process.exit(1);
|
|
41
|
+
}
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
if (result.command === "stop") {
|
|
45
|
+
try {
|
|
46
|
+
await tmuxStop(result.user);
|
|
47
|
+
if (result.user) console.log(`${color.green("✓")} Session "tokrec-${result.user}" stopped`);
|
|
48
|
+
else console.log(`${color.green("✓")} All tokrec sessions stopped`);
|
|
49
|
+
} catch (err) {
|
|
50
|
+
console.error(`${color.red("Error:")} ${err instanceof Error ? err.message : String(err)}`);
|
|
51
|
+
process.exit(1);
|
|
52
|
+
}
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
if (result.command === "status") {
|
|
56
|
+
const sessions = await tmuxStatus(result.user);
|
|
57
|
+
if (sessions.length === 0) console.log(`${color.gray("○")} No active session${result.user ? ` for "${result.user}"` : ""}`);
|
|
58
|
+
else for (const s of sessions) {
|
|
59
|
+
console.log(`${color.green("●")} tokrec-${s.user}`);
|
|
60
|
+
console.log(` tmux attach -t ${s.session} — view live output`);
|
|
61
|
+
}
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
if (result.command === "setup") {
|
|
65
|
+
const firefoxCookies = extractTikTokCookiesFromFirefox();
|
|
66
|
+
if (firefoxCookies) {
|
|
67
|
+
const names = Object.keys(firefoxCookies);
|
|
68
|
+
const detail = names.length > 1 ? ` (${names.length} cookies)` : "";
|
|
69
|
+
console.log(`${color.green("✓")} Firefox cookies detected${detail}`);
|
|
70
|
+
console.log(` No setup needed — tokrec auto-detects Firefox cookies.`);
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
const cookiesPath = join(process.cwd(), "cookies.json");
|
|
74
|
+
if (existsSync(cookiesPath)) {
|
|
75
|
+
if (loadCookiesFile(cookiesPath)) {
|
|
76
|
+
console.log(`${color.green("✓")} cookies.json found at ./cookies.json`);
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
console.log(`${color.yellow("⚠")} No TikTok cookies found.`);
|
|
81
|
+
console.log();
|
|
82
|
+
console.log(`You need a valid sessionid_ss cookie to bypass TikTok's WAF.`);
|
|
83
|
+
console.log(`Either log in to TikTok in Firefox (auto-detected), or enter manually:`);
|
|
84
|
+
console.log();
|
|
85
|
+
const sessionid = prompt(" sessionid_ss cookie value:");
|
|
86
|
+
if (!sessionid || sessionid.trim().length === 0) {
|
|
87
|
+
console.log(`${color.red("✗")} No cookie provided. Setup cancelled.`);
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
const cookies = { sessionid_ss: sessionid.trim() };
|
|
91
|
+
const idc = prompt(" tt-target-idc (optional, press Enter to skip):");
|
|
92
|
+
if (idc && idc.trim().length > 0) cookies["tt-target-idc"] = idc.trim();
|
|
93
|
+
writeFileSync(cookiesPath, `${JSON.stringify(cookies, null, 2)}\n`);
|
|
94
|
+
console.log();
|
|
95
|
+
console.log(`${color.green("✓")} cookies.json created at ./cookies.json`);
|
|
96
|
+
console.log(` You can now run: tokrec -u <username>`);
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
const config = result.config;
|
|
100
|
+
const firefoxCookies = extractTikTokCookiesFromFirefox();
|
|
101
|
+
config.cookies = firefoxCookies ?? loadCookiesFile(config.cookiesPath) ?? void 0;
|
|
102
|
+
config.logConsole = false;
|
|
103
|
+
const display = createDisplay();
|
|
104
|
+
if (config.cookies) {
|
|
105
|
+
const source = firefoxCookies ? "Firefox" : "cookies.json";
|
|
106
|
+
const names = Object.keys(config.cookies);
|
|
107
|
+
const detail = names.length > 1 ? ` (${names.length} cookies)` : "";
|
|
108
|
+
display.showInfo(`${source} cookies loaded${detail}`);
|
|
109
|
+
} else display.showWarning("No TikTok cookies found — log in at tiktok.com in Firefox or create cookies.json");
|
|
110
|
+
const recorder = createRecorder(config);
|
|
111
|
+
attachDisplay(display, recorder, config.user);
|
|
112
|
+
let stopping = false;
|
|
113
|
+
const handleSignal = async () => {
|
|
114
|
+
if (stopping) return;
|
|
115
|
+
stopping = true;
|
|
116
|
+
process.off("SIGINT", handleSignal);
|
|
117
|
+
process.off("SIGTERM", handleSignal);
|
|
118
|
+
process.off("SIGHUP", handleSignal);
|
|
119
|
+
display.showInfo("Shutting down gracefully...");
|
|
120
|
+
await recorder.stop();
|
|
121
|
+
display.stop();
|
|
122
|
+
process.exit(0);
|
|
123
|
+
};
|
|
124
|
+
process.on("SIGINT", handleSignal);
|
|
125
|
+
process.on("SIGTERM", handleSignal);
|
|
126
|
+
process.on("SIGHUP", handleSignal);
|
|
127
|
+
display.pollingStarted(config.interval ?? 3);
|
|
128
|
+
try {
|
|
129
|
+
await recorder.start();
|
|
130
|
+
} catch (err) {
|
|
131
|
+
if (err instanceof TikTokError) display.showError(`[${err.code}] ${err.message}`);
|
|
132
|
+
else display.showError(`Unexpected error: ${err instanceof Error ? err.message : String(err)}`);
|
|
133
|
+
process.off("SIGINT", handleSignal);
|
|
134
|
+
process.off("SIGTERM", handleSignal);
|
|
135
|
+
process.off("SIGHUP", handleSignal);
|
|
136
|
+
await recorder.stop();
|
|
137
|
+
display.stop();
|
|
138
|
+
process.exit(1);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
main().catch((err) => {
|
|
142
|
+
console.error("Fatal:", err instanceof Error ? err.message : String(err));
|
|
143
|
+
process.exit(1);
|
|
144
|
+
});
|
|
145
|
+
//#endregion
|
|
146
|
+
export {};
|
|
147
|
+
|
|
148
|
+
//# sourceMappingURL=bin.mjs.map
|
package/dist/bin.mjs.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bin.mjs","names":[],"sources":["../src/bin.ts"],"sourcesContent":["#!/usr/bin/env bun\n/**\n * Entry point — parses CLI args, creates the recorder, and handles signals.\n * The record flow's output wiring lives in `ui.attachDisplay`.\n */\n\nimport { existsSync, writeFileSync } from \"node:fs\"\nimport { join } from \"node:path\"\nimport type { RecorderConfig } from \"@zfadhli/tokrec\"\nimport { createRecorder, TikTokError } from \"@zfadhli/tokrec\"\nimport * as color from \"yoctocolors\"\nimport { extractTikTokCookiesFromFirefox, loadCookiesFile } from \"./browser-cookies\"\nimport { type CLIResult, parseArgs } from \"./cli\"\nimport { tmuxStart, tmuxStatus, tmuxStop } from \"./tmux\"\nimport { attachDisplay, createDisplay } from \"./ui\"\n\nasync function main(): Promise<void> {\n let result: CLIResult\n\n try {\n result = parseArgs()\n } catch (err) {\n if (err instanceof TikTokError && err.code === \"config-error\") {\n console.error(`${color.red(\"Error:\")} ${err.message}`)\n process.exit(1)\n }\n throw err\n }\n\n // Handle tmux subcommands\n if (result.command === \"start\") {\n // Extract user from args to build session name\n const userMatch = result.args.find((_, i, a) => a[i - 1] === \"--user\" || a[i - 1] === \"-u\")\n if (!userMatch) {\n console.error(`${color.red(\"Error:\")} --user is required for \"start\" command`)\n process.exit(1)\n }\n const cmd = `tokrec ${result.args.join(\" \")}`\n try {\n await tmuxStart(userMatch, cmd)\n console.log(`${color.green(\"✓\")} Session \"tokrec-${userMatch}\" started in background`)\n console.log(` tmux attach -t tokrec-${userMatch} — view live output`)\n console.log(` tokrec stop -u ${userMatch} — stop recording`)\n } catch (err) {\n console.error(`${color.red(\"Error:\")} ${err instanceof Error ? err.message : String(err)}`)\n process.exit(1)\n }\n return\n }\n\n if (result.command === \"stop\") {\n try {\n await tmuxStop(result.user)\n if (result.user) {\n console.log(`${color.green(\"✓\")} Session \"tokrec-${result.user}\" stopped`)\n } else {\n console.log(`${color.green(\"✓\")} All tokrec sessions stopped`)\n }\n } catch (err) {\n console.error(`${color.red(\"Error:\")} ${err instanceof Error ? err.message : String(err)}`)\n process.exit(1)\n }\n return\n }\n\n if (result.command === \"status\") {\n const sessions = await tmuxStatus(result.user)\n if (sessions.length === 0) {\n console.log(\n `${color.gray(\"○\")} No active session${result.user ? ` for \"${result.user}\"` : \"\"}`,\n )\n } else {\n for (const s of sessions) {\n console.log(`${color.green(\"●\")} tokrec-${s.user}`)\n console.log(` tmux attach -t ${s.session} — view live output`)\n }\n }\n return\n }\n\n if (result.command === \"setup\") {\n // 1. Check Firefox cookies\n const firefoxCookies = extractTikTokCookiesFromFirefox()\n if (firefoxCookies) {\n const names = Object.keys(firefoxCookies)\n const detail = names.length > 1 ? ` (${names.length} cookies)` : \"\"\n console.log(`${color.green(\"✓\")} Firefox cookies detected${detail}`)\n console.log(` No setup needed — tokrec auto-detects Firefox cookies.`)\n return\n }\n\n // 2. Check cookies.json\n const cookiesPath = join(process.cwd(), \"cookies.json\")\n if (existsSync(cookiesPath)) {\n const fromFile = loadCookiesFile(cookiesPath)\n if (fromFile) {\n console.log(`${color.green(\"✓\")} cookies.json found at ./cookies.json`)\n return\n }\n }\n\n // 3. No cookies found — interactive setup\n console.log(`${color.yellow(\"⚠\")} No TikTok cookies found.`)\n console.log()\n console.log(`You need a valid sessionid_ss cookie to bypass TikTok's WAF.`)\n console.log(`Either log in to TikTok in Firefox (auto-detected), or enter manually:`)\n console.log()\n\n const sessionid = prompt(\" sessionid_ss cookie value:\")\n if (!sessionid || sessionid.trim().length === 0) {\n console.log(`${color.red(\"✗\")} No cookie provided. Setup cancelled.`)\n return\n }\n\n const cookies: Record<string, string> = { sessionid_ss: sessionid.trim() }\n\n const idc = prompt(\" tt-target-idc (optional, press Enter to skip):\")\n if (idc && idc.trim().length > 0) {\n cookies[\"tt-target-idc\"] = idc.trim()\n }\n\n writeFileSync(cookiesPath, `${JSON.stringify(cookies, null, 2)}\\n`)\n console.log()\n console.log(`${color.green(\"✓\")} cookies.json created at ./cookies.json`)\n console.log(` You can now run: tokrec -u <username>`)\n return\n }\n\n // Record command — full recorder flow\n const config: RecorderConfig = result.config\n\n // Load cookies: try Firefox browser first, then fall back to cookies.json\n const firefoxCookies = extractTikTokCookiesFromFirefox()\n config.cookies = firefoxCookies ?? loadCookiesFile(config.cookiesPath) ?? undefined\n\n // Suppress internal logger's console output — the Display owns the terminal\n config.logConsole = false\n\n // Beautiful terminal display\n const display = createDisplay()\n\n if (config.cookies) {\n const source = firefoxCookies ? \"Firefox\" : \"cookies.json\"\n const names = Object.keys(config.cookies)\n const detail = names.length > 1 ? ` (${names.length} cookies)` : \"\"\n display.showInfo(`${source} cookies loaded${detail}`)\n } else {\n display.showWarning(\n \"No TikTok cookies found — log in at tiktok.com in Firefox or create cookies.json\",\n )\n }\n\n const recorder = createRecorder(config)\n attachDisplay(display, recorder, config.user)\n\n // Signal handling\n let stopping = false\n const handleSignal = async () => {\n if (stopping) return // ignore duplicate signals (e.g. SIGINT + SIGTERM from one Ctrl-C)\n stopping = true\n // Remove signal handlers so they don't accumulate if main() is called again\n process.off(\"SIGINT\", handleSignal)\n process.off(\"SIGTERM\", handleSignal)\n process.off(\"SIGHUP\", handleSignal)\n display.showInfo(\"Shutting down gracefully...\")\n await recorder.stop()\n display.stop()\n process.exit(0)\n }\n\n process.on(\"SIGINT\", handleSignal)\n process.on(\"SIGTERM\", handleSignal)\n process.on(\"SIGHUP\", handleSignal)\n\n // Show initial status and start the recorder\n display.pollingStarted(config.interval ?? 3)\n try {\n await recorder.start()\n } catch (err) {\n if (err instanceof TikTokError) {\n display.showError(`[${err.code}] ${err.message}`)\n } else {\n display.showError(`Unexpected error: ${err instanceof Error ? err.message : String(err)}`)\n }\n process.off(\"SIGINT\", handleSignal)\n process.off(\"SIGTERM\", handleSignal)\n process.off(\"SIGHUP\", handleSignal)\n await recorder.stop()\n display.stop()\n process.exit(1)\n }\n}\n\nmain().catch((err) => {\n console.error(\"Fatal:\", err instanceof Error ? err.message : String(err))\n process.exit(1)\n})\n"],"mappings":";;;;;;;;;;;;;;AAgBA,eAAe,OAAsB;CACnC,IAAI;CAEJ,IAAI;EACF,SAAS,UAAU;CACrB,SAAS,KAAK;EACZ,IAAI,eAAe,eAAe,IAAI,SAAS,gBAAgB;GAC7D,QAAQ,MAAM,GAAG,MAAM,IAAI,QAAQ,EAAE,GAAG,IAAI,SAAS;GACrD,QAAQ,KAAK,CAAC;EAChB;EACA,MAAM;CACR;CAGA,IAAI,OAAO,YAAY,SAAS;EAE9B,MAAM,YAAY,OAAO,KAAK,MAAM,GAAG,GAAG,MAAM,EAAE,IAAI,OAAO,YAAY,EAAE,IAAI,OAAO,IAAI;EAC1F,IAAI,CAAC,WAAW;GACd,QAAQ,MAAM,GAAG,MAAM,IAAI,QAAQ,EAAE,wCAAwC;GAC7E,QAAQ,KAAK,CAAC;EAChB;EACA,MAAM,MAAM,UAAU,OAAO,KAAK,KAAK,GAAG;EAC1C,IAAI;GACF,MAAM,UAAU,WAAW,GAAG;GAC9B,QAAQ,IAAI,GAAG,MAAM,MAAM,GAAG,EAAE,mBAAmB,UAAU,wBAAwB;GACrF,QAAQ,IAAI,2BAA2B,UAAU,sBAAsB;GACvE,QAAQ,IAAI,oBAAoB,UAAU,8BAA8B;EAC1E,SAAS,KAAK;GACZ,QAAQ,MAAM,GAAG,MAAM,IAAI,QAAQ,EAAE,GAAG,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,GAAG;GAC1F,QAAQ,KAAK,CAAC;EAChB;EACA;CACF;CAEA,IAAI,OAAO,YAAY,QAAQ;EAC7B,IAAI;GACF,MAAM,SAAS,OAAO,IAAI;GAC1B,IAAI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pB,QAAQ,KAAK;EACb,QAAQ,KAAK,CAAC;CAChB;CAEA,QAAQ,GAAG,UAAU,YAAY;CACjC,QAAQ,GAAG,WAAW,YAAY;CAClC,QAAQ,GAAG,UAAU,YAAY;CAGjC,QAAQ,eAAe,OAAO,YAAY,CAAC;CAC3C,IAAI;EACF,MAAM,SAAS,MAAM;CACvB,SAAS,KAAK;EACZ,IAAI,eAAe,aACjB,QAAQ,UAAU,IAAI,IAAI,KAAK,IAAI,IAAI,SAAS;OAEhD,QAAQ,UAAU,qBAAqB,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,GAAG;EAE3F,QAAQ,IAAI,UAAU,YAAY;EAClC,QAAQ,IAAI,WAAW,YAAY;EACnC,QAAQ,IAAI,UAAU,YAAY;EAClC,MAAM,SAAS,KAAK;EACpB,QAAQ,KAAK;EACb,QAAQ,KAAK,CAAC;CAChB;AACF;AAEA,KAAK,CAAC,CAAC,OAAO,QAAQ;CACpB,QAAQ,MAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;CACxE,QAAQ,KAAK,CAAC;AAChB,CAAC"}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { existsSync, readFileSync, readdirSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { Database } from "bun:sqlite";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
//#region src/browser-cookies.ts
|
|
6
|
+
/**
|
|
7
|
+
* Browser cookie extraction — reads TikTok session cookies from Firefox's
|
|
8
|
+
* cookie store using bun:sqlite (no external dependencies).
|
|
9
|
+
*
|
|
10
|
+
* Falls back to cookies.json if Firefox isn't available or if no TikTok
|
|
11
|
+
* login session is found.
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* Load `{ sessionid_ss, ... }` from a cookies.json path (default
|
|
15
|
+
* `./cookies.json`). Returns null when the file is missing, unparseable, or
|
|
16
|
+
* carries no session cookie — the caller decides whether to warn or prompt.
|
|
17
|
+
*/
|
|
18
|
+
function loadCookiesFile(cookiesPath) {
|
|
19
|
+
const path = cookiesPath ?? join(process.cwd(), "cookies.json");
|
|
20
|
+
if (!existsSync(path)) return null;
|
|
21
|
+
try {
|
|
22
|
+
const data = JSON.parse(readFileSync(path, "utf-8"));
|
|
23
|
+
if (data.sessionid_ss && data.sessionid_ss.length > 0) return data;
|
|
24
|
+
return null;
|
|
25
|
+
} catch {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Extract TikTok session cookies from Firefox's cookie store.
|
|
31
|
+
*
|
|
32
|
+
* Queries ALL cookies for TikTok domains from Firefox, including the
|
|
33
|
+
* Slardar WAF challenge cookie which is needed to bypass bot detection.
|
|
34
|
+
*
|
|
35
|
+
* Returns null if Firefox isn't found, cookies can't be read, or no
|
|
36
|
+
* sessionid_ss cookie exists (without which the session is useless).
|
|
37
|
+
*/
|
|
38
|
+
function extractTikTokCookiesFromFirefox() {
|
|
39
|
+
const dbPath = findFirefoxCookieDb();
|
|
40
|
+
if (!dbPath) return null;
|
|
41
|
+
try {
|
|
42
|
+
const db = new Database(dbPath, { readonly: true });
|
|
43
|
+
try {
|
|
44
|
+
const rows = db.query(`SELECT name, value FROM moz_cookies
|
|
45
|
+
WHERE host LIKE '%.tiktok.com' OR host LIKE '%.tiktokv.com'`).all();
|
|
46
|
+
if (!rows.some((r) => r.name === "sessionid_ss")) return null;
|
|
47
|
+
const cookies = {};
|
|
48
|
+
for (const row of rows) cookies[row.name] = row.value;
|
|
49
|
+
return cookies;
|
|
50
|
+
} finally {
|
|
51
|
+
db.close();
|
|
52
|
+
}
|
|
53
|
+
} catch {
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Locate the Firefox cookies.sqlite by scanning profile directories.
|
|
59
|
+
*
|
|
60
|
+
* Strategy:
|
|
61
|
+
* 1. Check ~/.mozilla/firefox/ for profiles.ini and parse the default profile.
|
|
62
|
+
* 2. Fall back to scanning directory entries that look like Firefox profiles
|
|
63
|
+
* (contain a cookies.sqlite file).
|
|
64
|
+
*/
|
|
65
|
+
/** @public Exported for testing */
|
|
66
|
+
function findFirefoxCookieDb() {
|
|
67
|
+
const firefoxDir = join(homedir(), ".mozilla", "firefox");
|
|
68
|
+
if (!existsSync(firefoxDir)) return null;
|
|
69
|
+
const iniPath = join(firefoxDir, "profiles.ini");
|
|
70
|
+
if (existsSync(iniPath)) try {
|
|
71
|
+
const profilePath = parseFirefoxProfilesIni(iniPath, firefoxDir);
|
|
72
|
+
if (profilePath) {
|
|
73
|
+
const dbPath = join(profilePath, "cookies.sqlite");
|
|
74
|
+
if (existsSync(dbPath)) return dbPath;
|
|
75
|
+
}
|
|
76
|
+
} catch {}
|
|
77
|
+
const entries = readdirSync(firefoxDir, { withFileTypes: true });
|
|
78
|
+
for (const entry of entries) {
|
|
79
|
+
if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
|
|
80
|
+
const dbPath = join(firefoxDir, entry.name, "cookies.sqlite");
|
|
81
|
+
if (existsSync(dbPath)) return dbPath;
|
|
82
|
+
}
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Parse Firefox's profiles.ini to find the default profile path.
|
|
87
|
+
*
|
|
88
|
+
* The INI format looks like:
|
|
89
|
+
* [Profile0]
|
|
90
|
+
* Name=default
|
|
91
|
+
* IsRelative=1
|
|
92
|
+
* Path=1pese0rl.default-release
|
|
93
|
+
* Default=1
|
|
94
|
+
*/
|
|
95
|
+
/** @public Exported for testing */
|
|
96
|
+
function parseFirefoxProfilesIni(iniPath, firefoxDir) {
|
|
97
|
+
const text = readFileSync(iniPath, "utf-8");
|
|
98
|
+
let defaultPath = null;
|
|
99
|
+
let isRelative = true;
|
|
100
|
+
let inProfile = false;
|
|
101
|
+
for (const line of text.split("\n")) {
|
|
102
|
+
const trimmed = line.trim();
|
|
103
|
+
if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
|
|
104
|
+
if (inProfile && defaultPath) break;
|
|
105
|
+
inProfile = trimmed.toLowerCase().startsWith("[profile");
|
|
106
|
+
if (inProfile) {
|
|
107
|
+
defaultPath = null;
|
|
108
|
+
isRelative = true;
|
|
109
|
+
}
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
if (!inProfile) continue;
|
|
113
|
+
const lower = trimmed.toLowerCase();
|
|
114
|
+
if (lower.startsWith("path=")) defaultPath = trimmed.slice(5);
|
|
115
|
+
else if (lower.startsWith("isrelative=")) isRelative = trimmed.slice(11).trim() !== "0";
|
|
116
|
+
else if (lower.startsWith("default=")) {
|
|
117
|
+
if (trimmed.slice(8).trim() !== "1") {
|
|
118
|
+
inProfile = false;
|
|
119
|
+
defaultPath = null;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
if (!defaultPath) return null;
|
|
124
|
+
return isRelative ? join(firefoxDir, defaultPath) : defaultPath;
|
|
125
|
+
}
|
|
126
|
+
//#endregion
|
|
127
|
+
export { extractTikTokCookiesFromFirefox, loadCookiesFile };
|
|
128
|
+
|
|
129
|
+
//# sourceMappingURL=browser-cookies.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"browser-cookies.mjs","names":[],"sources":["../src/browser-cookies.ts"],"sourcesContent":["/**\n * Browser cookie extraction — reads TikTok session cookies from Firefox's\n * cookie store using bun:sqlite (no external dependencies).\n *\n * Falls back to cookies.json if Firefox isn't available or if no TikTok\n * login session is found.\n */\n\nimport { Database } from \"bun:sqlite\"\nimport { existsSync, readdirSync, readFileSync } from \"node:fs\"\nimport { homedir } from \"node:os\"\nimport { join } from \"node:path\"\n\n/**\n * Load `{ sessionid_ss, ... }` from a cookies.json path (default\n * `./cookies.json`). Returns null when the file is missing, unparseable, or\n * carries no session cookie — the caller decides whether to warn or prompt.\n */\nexport function loadCookiesFile(cookiesPath?: string): Record<string, string> | null {\n const path = cookiesPath ?? join(process.cwd(), \"cookies.json\")\n if (!existsSync(path)) return null\n try {\n const data = JSON.parse(readFileSync(path, \"utf-8\")) as Record<string, string | undefined>\n if (data.sessionid_ss && data.sessionid_ss.length > 0) {\n return data as Record<string, string>\n }\n return null\n } catch {\n return null\n }\n}\n\n/**\n * Extract TikTok session cookies from Firefox's cookie store.\n *\n * Queries ALL cookies for TikTok domains from Firefox, including the\n * Slardar WAF challenge cookie which is needed to bypass bot detection.\n *\n * Returns null if Firefox isn't found, cookies can't be read, or no\n * sessionid_ss cookie exists (without which the session is useless).\n */\nexport function extractTikTokCookiesFromFirefox(): Record<string, string> | null {\n const dbPath = findFirefoxCookieDb()\n if (!dbPath) return null\n\n try {\n const db = new Database(dbPath, { readonly: true })\n try {\n const rows = db\n .query(\n `SELECT name, value FROM moz_cookies\n WHERE host LIKE '%.tiktok.com' OR host LIKE '%.tiktokv.com'`,\n )\n .all() as Array<{ name: string; value: string }>\n\n // Require sessionid_ss — without it the session is useless\n const hasSession = rows.some((r) => r.name === \"sessionid_ss\")\n if (!hasSession) return null\n\n const cookies: Record<string, string> = {}\n for (const row of rows) {\n cookies[row.name] = row.value\n }\n return cookies\n } finally {\n db.close()\n }\n } catch {\n return null\n }\n}\n\n/**\n * Locate the Firefox cookies.sqlite by scanning profile directories.\n *\n * Strategy:\n * 1. Check ~/.mozilla/firefox/ for profiles.ini and parse the default profile.\n * 2. Fall back to scanning directory entries that look like Firefox profiles\n * (contain a cookies.sqlite file).\n */\n/** @public Exported for testing */\nexport function findFirefoxCookieDb(): string | null {\n const firefoxDir = join(homedir(), \".mozilla\", \"firefox\")\n if (!existsSync(firefoxDir)) return null\n\n // Try profiles.ini first for a reliable default-profile path\n const iniPath = join(firefoxDir, \"profiles.ini\")\n if (existsSync(iniPath)) {\n try {\n const profilePath = parseFirefoxProfilesIni(iniPath, firefoxDir)\n if (profilePath) {\n const dbPath = join(profilePath, \"cookies.sqlite\")\n if (existsSync(dbPath)) return dbPath\n }\n } catch {\n // fall through to directory scan\n }\n }\n\n // Fallback: scan for any directory containing cookies.sqlite\n const entries = readdirSync(firefoxDir, { withFileTypes: true })\n for (const entry of entries) {\n if (!entry.isDirectory() && !entry.isSymbolicLink()) continue\n const dbPath = join(firefoxDir, entry.name, \"cookies.sqlite\")\n if (existsSync(dbPath)) return dbPath\n }\n\n return null\n}\n\n/**\n * Parse Firefox's profiles.ini to find the default profile path.\n *\n * The INI format looks like:\n * [Profile0]\n * Name=default\n * IsRelative=1\n * Path=1pese0rl.default-release\n * Default=1\n */\n/** @public Exported for testing */\nexport function parseFirefoxProfilesIni(iniPath: string, firefoxDir: string): string | null {\n const text = readFileSync(iniPath, \"utf-8\")\n\n let defaultPath: string | null = null\n let isRelative = true\n let inProfile = false\n\n for (const line of text.split(\"\\n\")) {\n const trimmed = line.trim()\n\n // Section header\n if (trimmed.startsWith(\"[\") && trimmed.endsWith(\"]\")) {\n if (inProfile && defaultPath) break // found it\n inProfile = trimmed.toLowerCase().startsWith(\"[profile\")\n if (inProfile) {\n defaultPath = null\n isRelative = true\n }\n continue\n }\n\n if (!inProfile) continue\n\n const lower = trimmed.toLowerCase()\n if (lower.startsWith(\"path=\")) {\n defaultPath = trimmed.slice(5)\n } else if (lower.startsWith(\"isrelative=\")) {\n isRelative = trimmed.slice(11).trim() !== \"0\"\n } else if (lower.startsWith(\"default=\")) {\n if (trimmed.slice(8).trim() !== \"1\") {\n // Not the default profile — skip\n inProfile = false\n defaultPath = null\n }\n }\n }\n\n if (!defaultPath) return null\n return isRelative ? join(firefoxDir, defaultPath) : defaultPath\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAkBA,SAAgB,gBAAgB,aAAqD;CACnF,MAAM,OAAO,eAAe,KAAK,QAAQ,IAAI,GAAG,cAAc;CAC9D,IAAI,CAAC,WAAW,IAAI,GAAG,OAAO;CAC9B,IAAI;EACF,MAAM,OAAO,KAAK,MAAM,aAAa,MAAM,OAAO,CAAC;EACnD,IAAI,KAAK,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E1C,IAAI,cAA6B;CACjC,IAAI,aAAa;CACjB,IAAI,YAAY;CAEhB,KAAK,MAAM,QAAQ,KAAK,MAAM,IAAI,GAAG;EACnC,MAAM,UAAU,KAAK,KAAK;EAG1B,IAAI,QAAQ,WAAW,GAAG,KAAK,QAAQ,SAAS,GAAG,GAAG;GACpD,IAAI,aAAa,aAAa;GAC9B,YAAY,QAAQ,YAAY,CAAC,CAAC,WAAW,UAAU;GACvD,IAAI,WAAW;IACb,cAAc;IACd,aAAa;GACf;GACA;EACF;EAEA,IAAI,CAAC,WAAW;EAEhB,MAAM,QAAQ,QAAQ,YAAY;EAClC,IAAI,MAAM,WAAW,OAAO,GAC1B,cAAc,QAAQ,MAAM,CAAC;OACxB,IAAI,MAAM,WAAW,aAAa,GACvC,aAAa,QAAQ,MAAM,EAAE,CAAC,CAAC,KAAK,MAAM;OACrC,IAAI,MAAM,WAAW,UAAU;OAChC,QAAQ,MAAM,CAAC,CAAC,CAAC,KAAK,MAAM,KAAK;IAEnC,YAAY;IACZ,cAAc;GAChB;;CAEJ;CAEA,IAAI,CAAC,aAAa,OAAO;CACzB,OAAO,aAAa,KAAK,YAAY,WAAW,IAAI;AACtD"}
|
package/dist/cli.mjs
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { version } from "./package.mjs";
|
|
2
|
+
import { TikTokError, sanitizeUser } from "@zfadhli/tokrec";
|
|
3
|
+
import * as color from "yoctocolors";
|
|
4
|
+
import cac from "cac";
|
|
5
|
+
//#region src/cli.ts
|
|
6
|
+
const LOG_LEVELS = [
|
|
7
|
+
"debug",
|
|
8
|
+
"info",
|
|
9
|
+
"warn",
|
|
10
|
+
"error"
|
|
11
|
+
];
|
|
12
|
+
/** `-i, --interval <minutes>` → `interval`, the key cac writes into `opts`. */
|
|
13
|
+
function optsKey(flags) {
|
|
14
|
+
return ((flags.split(",").at(-1)?.trim() ?? flags).replace(/^--/, "").split(" ")[0] ?? "").replace(/-([a-z])/g, (_, ch) => ch.toUpperCase());
|
|
15
|
+
}
|
|
16
|
+
/** Typed setter: coerce the raw argv string, then write the named field. */
|
|
17
|
+
function set(key, parse) {
|
|
18
|
+
return (config, raw) => {
|
|
19
|
+
config[key] = parse(String(raw));
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
function numberOf(raw, message) {
|
|
23
|
+
const n = Number(raw);
|
|
24
|
+
if (!Number.isFinite(n)) throw new TikTokError("config-error", message);
|
|
25
|
+
return n;
|
|
26
|
+
}
|
|
27
|
+
/** Parse `raw`, require `>= min`, optionally scale (minutes → seconds). */
|
|
28
|
+
function atLeast(min, message, scale = 1) {
|
|
29
|
+
return (raw) => {
|
|
30
|
+
const n = numberOf(raw, message);
|
|
31
|
+
if (n < min) throw new TikTokError("config-error", message);
|
|
32
|
+
return n * scale;
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
const OPTIONS = [
|
|
36
|
+
{
|
|
37
|
+
flags: "-o, --output <dir>",
|
|
38
|
+
description: "Output directory",
|
|
39
|
+
default: ".",
|
|
40
|
+
apply: set("outputDir", (raw) => raw)
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
flags: "-i, --interval <minutes>",
|
|
44
|
+
description: "Polling interval in minutes",
|
|
45
|
+
default: "3",
|
|
46
|
+
apply: set("interval", atLeast(1, "--interval must be a number >= 1"))
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
flags: "-d, --duration <minutes>",
|
|
50
|
+
description: "Max recording duration in minutes",
|
|
51
|
+
apply: set("duration", atLeast(0, "--duration must be a number >= 0 (minutes)", 60))
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
flags: "-p, --proxy <url>",
|
|
55
|
+
description: "HTTP proxy (e.g. http://127.0.0.1:8080)",
|
|
56
|
+
apply: set("proxy", (raw) => raw)
|
|
57
|
+
},
|
|
58
|
+
{
|
|
59
|
+
flags: "-l, --log-level <level>",
|
|
60
|
+
description: "Log level: debug | info | warn | error",
|
|
61
|
+
apply: set("logLevel", (raw) => {
|
|
62
|
+
if (!LOG_LEVELS.includes(raw)) throw new TikTokError("config-error", `--log-level must be one of: ${LOG_LEVELS.join(", ")}`);
|
|
63
|
+
return raw;
|
|
64
|
+
})
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
flags: "-c, --cookies <path>",
|
|
68
|
+
description: "Path to cookies.json",
|
|
69
|
+
apply: set("cookiesPath", (raw) => raw)
|
|
70
|
+
},
|
|
71
|
+
{
|
|
72
|
+
flags: "-s, --segment-minutes <minutes>",
|
|
73
|
+
description: "Segment duration in minutes (default: disabled). Split recording into segments of this length.",
|
|
74
|
+
apply: set("segmentMinutes", atLeast(0, "--segment-minutes must be a number >= 0"))
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
flags: "--normalize",
|
|
78
|
+
description: "Normalize audio loudness (EBU R128)",
|
|
79
|
+
apply: (config) => {
|
|
80
|
+
config.normalizeAudio = true;
|
|
81
|
+
}
|
|
82
|
+
},
|
|
83
|
+
{
|
|
84
|
+
flags: "--normalize-loudness <num>",
|
|
85
|
+
description: "Target loudness in LUFS (default: -14)",
|
|
86
|
+
apply: set("normalizeLoudness", (raw) => numberOf(raw, "--normalize-loudness must be a number"))
|
|
87
|
+
},
|
|
88
|
+
{
|
|
89
|
+
flags: "--normalize-codec <name>",
|
|
90
|
+
description: "Audio codec for normalized output (default: libopus)",
|
|
91
|
+
apply: set("normalizeCodec", (raw) => raw)
|
|
92
|
+
},
|
|
93
|
+
{
|
|
94
|
+
flags: "--normalize-bitrate <str>",
|
|
95
|
+
description: "Audio bitrate for normalized output (default: 96k)",
|
|
96
|
+
apply: set("normalizeBitrate", (raw) => raw)
|
|
97
|
+
},
|
|
98
|
+
{
|
|
99
|
+
flags: "--rate <n>",
|
|
100
|
+
description: "Max API requests per second (default: 5). Set 0 for unlimited.",
|
|
101
|
+
apply: set("ratePerSecond", atLeast(0, "--rate must be a number >= 0"))
|
|
102
|
+
},
|
|
103
|
+
{
|
|
104
|
+
flags: "--debug",
|
|
105
|
+
description: "Show API debug logging on stderr for troubleshooting",
|
|
106
|
+
apply: (config) => {
|
|
107
|
+
config.debug = true;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
];
|
|
111
|
+
/** Shared recorder options for both default and start commands. */
|
|
112
|
+
function registerRecorderOptions(cmd) {
|
|
113
|
+
cmd.option("-u, --user <name>", "TikTok username (or pass as first argument)");
|
|
114
|
+
for (const option of OPTIONS) cmd.option(option.flags, option.description, option.default === void 0 ? {} : { default: option.default });
|
|
115
|
+
}
|
|
116
|
+
function parseRecorderOpts(opts) {
|
|
117
|
+
const user = opts.user;
|
|
118
|
+
if (!user) throw new TikTokError("config-error", "<user> is required (--user or -u)");
|
|
119
|
+
const parsed = { user: sanitizeUser(user) };
|
|
120
|
+
for (const option of OPTIONS) {
|
|
121
|
+
const raw = opts[optsKey(option.flags)];
|
|
122
|
+
if (raw === void 0) continue;
|
|
123
|
+
option.apply(parsed, raw);
|
|
124
|
+
}
|
|
125
|
+
return parsed;
|
|
126
|
+
}
|
|
127
|
+
/** styled startup banner, printed before each command action (stderr) */
|
|
128
|
+
function banner() {
|
|
129
|
+
console.error(`${color.bold(color.cyan("tokrec"))} ${color.yellow(`v${version}`)}`);
|
|
130
|
+
}
|
|
131
|
+
function parseArgs(argv = process.argv) {
|
|
132
|
+
let result;
|
|
133
|
+
let error;
|
|
134
|
+
const cli = cac("tokrec");
|
|
135
|
+
cli.version(version);
|
|
136
|
+
cli.help();
|
|
137
|
+
cli.usage("Minimal TikTok live stream recorder — Bun + TypeScript");
|
|
138
|
+
const record = cli.command("", "Record a TikTok live stream");
|
|
139
|
+
registerRecorderOptions(record);
|
|
140
|
+
record.action((opts) => {
|
|
141
|
+
banner();
|
|
142
|
+
try {
|
|
143
|
+
result = {
|
|
144
|
+
command: "record",
|
|
145
|
+
config: parseRecorderOpts(opts)
|
|
146
|
+
};
|
|
147
|
+
} catch (err) {
|
|
148
|
+
error = err instanceof Error ? err.message : String(err);
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
const start = cli.command("start", "Start recorder in a tmux session (survives terminal close)");
|
|
152
|
+
registerRecorderOptions(start);
|
|
153
|
+
start.action((opts) => {
|
|
154
|
+
banner();
|
|
155
|
+
try {
|
|
156
|
+
parseRecorderOpts(opts);
|
|
157
|
+
result = {
|
|
158
|
+
command: "start",
|
|
159
|
+
args: argv.slice(2).filter((a) => a !== "start")
|
|
160
|
+
};
|
|
161
|
+
} catch (err) {
|
|
162
|
+
error = err instanceof Error ? err.message : String(err);
|
|
163
|
+
}
|
|
164
|
+
});
|
|
165
|
+
const stop = cli.command("stop", "Stop background tmux session(s)");
|
|
166
|
+
stop.option("-u, --user <name>", "Stop a specific user's session (omit to stop all)");
|
|
167
|
+
stop.action((opts) => {
|
|
168
|
+
banner();
|
|
169
|
+
result = {
|
|
170
|
+
command: "stop",
|
|
171
|
+
user: opts.user
|
|
172
|
+
};
|
|
173
|
+
});
|
|
174
|
+
const status = cli.command("status", "Check tmux session(s)");
|
|
175
|
+
status.option("-u, --user <name>", "Check a specific user's session (omit to show all)");
|
|
176
|
+
status.action((opts) => {
|
|
177
|
+
banner();
|
|
178
|
+
result = {
|
|
179
|
+
command: "status",
|
|
180
|
+
user: opts.user
|
|
181
|
+
};
|
|
182
|
+
});
|
|
183
|
+
cli.command("setup", "Check cookie status or create cookies.json interactively").action(() => {
|
|
184
|
+
banner();
|
|
185
|
+
result = { command: "setup" };
|
|
186
|
+
});
|
|
187
|
+
cli.parse(argv);
|
|
188
|
+
if (error) throw new TikTokError("config-error", error);
|
|
189
|
+
if (!result) throw new TikTokError("config-error", "<user> is required (--user or -u). Use --help for usage.");
|
|
190
|
+
return result;
|
|
191
|
+
}
|
|
192
|
+
//#endregion
|
|
193
|
+
export { parseArgs };
|
|
194
|
+
|
|
195
|
+
//# sourceMappingURL=cli.mjs.map
|
package/dist/cli.mjs.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli.mjs","names":["pkg.version"],"sources":["../src/cli.ts"],"sourcesContent":["/**\n * CLI argument parser — thin wrapper over cac.\n * Exports a single parseArgs() function.\n */\n\nimport type { LogLevel, RecorderConfig } from \"@zfadhli/tokrec\"\nimport { sanitizeUser, TikTokError } from \"@zfadhli/tokrec\"\nimport cac, { type Command } from \"cac\"\nimport * as color from \"yoctocolors\"\nimport pkg from \"../package.json\"\n\nexport type CLIResult =\n | { command: \"record\"; config: RecorderConfig }\n | { command: \"start\"; args: string[] }\n | { command: \"stop\"; user?: string }\n | { command: \"status\"; user?: string }\n | { command: \"setup\" }\n\nconst LOG_LEVELS: readonly LogLevel[] = [\"debug\", \"info\", \"warn\", \"error\"]\n\n/**\n * One row per `RecorderConfig` field the CLI exposes. The flag string is the\n * only declaration: `cmd.option()` and the argv → config mapping both read this\n * table, so a new option is one row instead of two edits in two shapes.\n */\ninterface OptionSpec {\n flags: string\n description: string\n /** cac default, passed through to `cmd.option`. */\n default?: string\n /** Merge into the config. Only called when argv carried the option. */\n apply: (config: RecorderConfig, raw: unknown) => void\n}\n\n/** `-i, --interval <minutes>` → `interval`, the key cac writes into `opts`. */\nfunction optsKey(flags: string): string {\n const long = flags.split(\",\").at(-1)?.trim() ?? flags\n const name = long.replace(/^--/, \"\").split(\" \")[0] ?? \"\"\n return name.replace(/-([a-z])/g, (_, ch: string) => ch.toUpperCase())\n}\n\n/** Typed setter: coerce the raw argv string, then write the named field. */\nfunction set<K extends keyof RecorderConfig>(\n key: K,\n parse: (raw: string) => RecorderConfig[K],\n): OptionSpec[\"apply\"] {\n return (config, raw) => {\n config[key] = parse(String(raw))\n }\n}\n\nfunction numberOf(raw: string, message: string): number {\n const n = Number(raw)\n if (!Number.isFinite(n)) throw new TikTokError(\"config-error\", message)\n return n\n}\n\n/** Parse `raw`, require `>= min`, optionally scale (minutes → seconds). */\nfunction atLeast(min: number, message: string, scale = 1) {\n return (raw: string): number => {\n const n = numberOf(raw, message)\n if (n < min) throw new TikTokError(\"config-error\", message)\n return n * scale\n }\n}\n\nconst OPTIONS: OptionSpec[] = [\n {\n flags: \"-o, --output <dir>\",\n description: \"Output directory\",\n default: \".\",\n apply: set(\"outputDir\", (raw) => raw),\n },\n {\n flags: \"-i, --interval <minutes>\",\n description: \"Polling interval in minutes\",\n default: \"3\",\n apply: set(\"interval\", atLeast(1, \"--interval must be a number >= 1\")),\n },\n {\n flags: \"-d, --duration <minutes>\",\n description: \"Max recording duration in minutes\",\n apply: set(\"duration\", atLeast(0, \"--duration must be a number >= 0 (minutes)\", 60)),\n },\n {\n flags: \"-p, --proxy <url>\",\n description: \"HTTP proxy (e.g. http://127.0.0.1:8080)\",\n apply: set(\"proxy\", (raw) => raw),\n },\n {\n flags: \"-l, --log-level <level>\",\n description: \"Log level: debug | info | warn | error\",\n apply: set(\"logLevel\", (raw) => {\n if (!LOG_LEVELS.includes(raw as LogLevel)) {\n throw new TikTokError(\n \"config-error\",\n `--log-level must be one of: ${LOG_LEVELS.join(\", \")}`,\n )\n }\n return raw as LogLevel\n }),\n },\n {\n flags: \"-c, --cookies <path>\",\n description: \"Path to cookies.json\",\n apply: set(\"cookiesPath\", (raw) => raw),\n },\n {\n flags: \"-s, --segment-minutes <minutes>\",\n description:\n \"Segment duration in minutes (default: disabled). Split recording into segments of this length.\",\n apply: set(\"segmentMinutes\", atLeast(0, \"--segment-minutes must be a number >= 0\")),\n },\n {\n flags: \"--normalize\",\n description: \"Normalize audio loudness (EBU R128)\",\n apply: (config) => {\n config.normalizeAudio = true\n },\n },\n {\n flags: \"--normalize-loudness <num>\",\n description: \"Target loudness in LUFS (default: -14)\",\n apply: set(\"normalizeLoudness\", (raw) =>\n numberOf(raw, \"--normalize-loudness must be a number\"),\n ),\n },\n {\n flags: \"--normalize-codec <name>\",\n description: \"Audio codec for normalized output (default: libopus)\",\n apply: set(\"normalizeCodec\", (raw) => raw),\n },\n {\n flags: \"--normalize-bitrate <str>\",\n description: \"Audio bitrate for normalized output (default: 96k)\",\n apply: set(\"normalizeBitrate\", (raw) => raw),\n },\n {\n flags: \"--rate <n>\",\n description: \"Max API requests per second (default: 5). Set 0 for unlimited.\",\n apply: set(\"ratePerSecond\", atLeast(0, \"--rate must be a number >= 0\")),\n },\n {\n flags: \"--debug\",\n description: \"Show API debug logging on stderr for troubleshooting\",\n apply: (config) => {\n config.debug = true\n },\n },\n]\n\n/** Shared recorder options for both default and start commands. */\nfunction registerRecorderOptions(cmd: Command): void {\n cmd.option(\"-u, --user <name>\", \"TikTok username (or pass as first argument)\")\n for (const option of OPTIONS) {\n cmd.option(\n option.flags,\n option.description,\n option.default === undefined ? {} : { default: option.default },\n )\n }\n}\n\nfunction parseRecorderOpts(opts: Record<string, unknown>): RecorderConfig {\n const user = opts.user as string | undefined\n if (!user) {\n throw new TikTokError(\"config-error\", \"<user> is required (--user or -u)\")\n }\n\n const parsed: RecorderConfig = { user: sanitizeUser(user) }\n for (const option of OPTIONS) {\n const raw = opts[optsKey(option.flags)]\n if (raw === undefined) continue\n option.apply(parsed, raw)\n }\n return parsed\n}\n\n/** styled startup banner, printed before each command action (stderr) */\nfunction banner(): void {\n console.error(`${color.bold(color.cyan(\"tokrec\"))} ${color.yellow(`v${pkg.version}`)}`)\n}\n\nexport function parseArgs(argv: string[] = process.argv): CLIResult {\n let result: CLIResult | undefined\n let error: string | undefined\n\n const cli = cac(\"tokrec\")\n cli.version(pkg.version)\n cli.help()\n cli.usage(\"Minimal TikTok live stream recorder — Bun + TypeScript\")\n\n const record = cli.command(\"\", \"Record a TikTok live stream\")\n registerRecorderOptions(record)\n record.action((opts: Record<string, unknown>) => {\n banner()\n try {\n result = { command: \"record\", config: parseRecorderOpts(opts) }\n } catch (err) {\n error = err instanceof Error ? err.message : String(err)\n }\n })\n\n const start = cli.command(\"start\", \"Start recorder in a tmux session (survives terminal close)\")\n registerRecorderOptions(start)\n start.action((opts: Record<string, unknown>) => {\n banner()\n try {\n parseRecorderOpts(opts)\n // Pass through original args (minus 'start') to the inner tokrec process\n const args = argv.slice(2).filter((a) => a !== \"start\")\n result = { command: \"start\", args }\n } catch (err) {\n error = err instanceof Error ? err.message : String(err)\n }\n })\n\n const stop = cli.command(\"stop\", \"Stop background tmux session(s)\")\n stop.option(\"-u, --user <name>\", \"Stop a specific user's session (omit to stop all)\")\n stop.action((opts: Record<string, unknown>) => {\n banner()\n result = { command: \"stop\", user: opts.user as string | undefined }\n })\n\n const status = cli.command(\"status\", \"Check tmux session(s)\")\n status.option(\"-u, --user <name>\", \"Check a specific user's session (omit to show all)\")\n status.action((opts: Record<string, unknown>) => {\n banner()\n result = { command: \"status\", user: opts.user as string | undefined }\n })\n\n const setup = cli.command(\"setup\", \"Check cookie status or create cookies.json interactively\")\n setup.action(() => {\n banner()\n result = { command: \"setup\" }\n })\n\n cli.parse(argv)\n\n if (error) {\n throw new TikTokError(\"config-error\", error)\n }\n\n if (!result) {\n throw new TikTokError(\n \"config-error\",\n \"<user> is required (--user or -u). Use --help for usage.\",\n )\n }\n\n return result\n}\n"],"mappings":";;;;;AAkBA,MAAM,aAAkC;CAAC;CAAS;CAAQ;CAAQ;AAAO;;AAiBzE,SAAS,QAAQ,OAAuB;CAGtC,SAFa,MAAM,MAAM,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC,EAAE,KAAK,KAAK,MAAA,CAC9B,QAAQ,OAAO,EAAE,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM,GAAA,CAC1C,QAAQ,cAAc,GAAG,OAAe,GAAG,YAAY,CAAC;AACtE;;AAGA,SAAS,IACP,KACA,OACqB;CACrB,QAAQ,QAAQ,QAAQ;EACtB,OAAO,OAAO,MAAM,OAAO,GAAG,CAAC;CACjC;AACF;AAEA,SAAS,SAAS,KAAa,SAAyB;CACtD,MAAM,IAAI,OAAO,GAAG;CACpB,IAAI,CAAC,OAAO,SAAS,CAAC,GAAG,MAAM,IAAI,YAAY,gBAAgB,OAAO;CACtE,OAAO;AACT;;AAGA,SAAS,QAAQ,KAAa,SAAiB,QAAQ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AK;CAC7B,MAAM,QAAQ,SAAkC;EAC9C,OAAO;EACP,IAAI;GACF,kBAAkB,IAAI;GAGtB,SAAS;IAAE,SAAS;IAAS,MADhB,KAAK,MAAM,CAAC,CAAC,CAAC,QAAQ,MAAM,MAAM,OACf;GAAE;EACpC,SAAS,KAAK;GACZ,QAAQ,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;EACzD;CACF,CAAC;CAED,MAAM,OAAO,IAAI,QAAQ,QAAQ,iCAAiC;CAClE,KAAK,OAAO,qBAAqB,mDAAmD;CACpF,KAAK,QAAQ,SAAkC;EAC7C,OAAO;EACP,SAAS;GAAE,SAAS;GAAQ,MAAM,KAAK;EAA2B;CACpE,CAAC;CAED,MAAM,SAAS,IAAI,QAAQ,UAAU,uBAAuB;CAC5D,OAAO,OAAO,qBAAqB,oDAAoD;CACvF,OAAO,QAAQ,SAAkC;EAC/C,OAAO;EACP,SAAS;GAAE,SAAS;GAAU,MAAM,KAAK;EAA2B;CACtE,CAAC;CAGD,IADkB,QAAQ,SAAS,0DAC/B,CAAC,CAAC,aAAa;EACjB,OAAO;EACP,SAAS,EAAE,SAAS,QAAQ;CAC9B,CAAC;CAED,IAAI,MAAM,IAAI;CAEd,IAAI,OACF,MAAM,IAAI,YAAY,gBAAgB,KAAK;CAG7C,IAAI,CAAC,QACH,MAAM,IAAI,YACR,gBACA,0DACF;CAGF,OAAO;AACT"}
|
package/dist/package.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"package.mjs","names":[],"sources":["../package.json"],"sourcesContent":[""],"mappings":""}
|
package/dist/tmux.mjs
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { execa } from "execa";
|
|
2
|
+
//#region src/tmux.ts
|
|
3
|
+
/**
|
|
4
|
+
* tmux session helpers — per-user start/stop/status for background recording.
|
|
5
|
+
*
|
|
6
|
+
* Session naming: "tokrec-{user}" — each user gets an independent tmux session.
|
|
7
|
+
*/
|
|
8
|
+
function sessionName(user) {
|
|
9
|
+
return `tokrec-${user}`;
|
|
10
|
+
}
|
|
11
|
+
async function hasSession(name) {
|
|
12
|
+
const { exitCode } = await execa("tmux", [
|
|
13
|
+
"has-session",
|
|
14
|
+
"-t",
|
|
15
|
+
name
|
|
16
|
+
], { reject: false });
|
|
17
|
+
return exitCode === 0;
|
|
18
|
+
}
|
|
19
|
+
async function tmuxStart(user, command) {
|
|
20
|
+
const name = sessionName(user);
|
|
21
|
+
if (await hasSession(name)) throw new Error(`Session "${name}" already exists. Run "tokrec stop -u ${user}" first.`);
|
|
22
|
+
await execa("tmux", [
|
|
23
|
+
"new-session",
|
|
24
|
+
"-d",
|
|
25
|
+
"-s",
|
|
26
|
+
name,
|
|
27
|
+
command
|
|
28
|
+
]);
|
|
29
|
+
}
|
|
30
|
+
async function tmuxStop(user) {
|
|
31
|
+
if (user) {
|
|
32
|
+
const name = sessionName(user);
|
|
33
|
+
if (!await hasSession(name)) throw new Error(`No session "${name}" found.`);
|
|
34
|
+
await gracefulStop(name);
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
const { stdout } = await execa("tmux", [
|
|
38
|
+
"list-sessions",
|
|
39
|
+
"-F",
|
|
40
|
+
"#{session_name}"
|
|
41
|
+
], { reject: false });
|
|
42
|
+
const sessions = stdout.split("\n").filter((s) => s.startsWith("tokrec-"));
|
|
43
|
+
if (sessions.length === 0) throw new Error("No active tokrec sessions found.");
|
|
44
|
+
for (const s of sessions) await gracefulStop(s);
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Send Ctrl-C to the tmux session and wait for it to exit.
|
|
48
|
+
* Falls back to kill-session after the timeout.
|
|
49
|
+
*/
|
|
50
|
+
async function gracefulStop(name) {
|
|
51
|
+
await execa("tmux", [
|
|
52
|
+
"send-keys",
|
|
53
|
+
"-t",
|
|
54
|
+
name,
|
|
55
|
+
"C-c"
|
|
56
|
+
]);
|
|
57
|
+
const deadline = Date.now() + 66e4;
|
|
58
|
+
while (Date.now() < deadline) {
|
|
59
|
+
if (!await hasSession(name)) return;
|
|
60
|
+
await new Promise((r) => setTimeout(r, 500));
|
|
61
|
+
}
|
|
62
|
+
if (await hasSession(name)) await execa("tmux", [
|
|
63
|
+
"kill-session",
|
|
64
|
+
"-t",
|
|
65
|
+
name
|
|
66
|
+
]);
|
|
67
|
+
}
|
|
68
|
+
async function tmuxStatus(user) {
|
|
69
|
+
const { stdout } = await execa("tmux", [
|
|
70
|
+
"list-sessions",
|
|
71
|
+
"-F",
|
|
72
|
+
"#{session_name}"
|
|
73
|
+
], { reject: false });
|
|
74
|
+
const all = stdout.split("\n").filter((s) => s.startsWith("tokrec-")).map((s) => ({
|
|
75
|
+
user: s.slice(7),
|
|
76
|
+
session: s
|
|
77
|
+
}));
|
|
78
|
+
if (user) return all.filter((s) => s.user === user);
|
|
79
|
+
return all;
|
|
80
|
+
}
|
|
81
|
+
//#endregion
|
|
82
|
+
export { tmuxStart, tmuxStatus, tmuxStop };
|
|
83
|
+
|
|
84
|
+
//# sourceMappingURL=tmux.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tmux.mjs","names":[],"sources":["../src/tmux.ts"],"sourcesContent":["/**\n * tmux session helpers — per-user start/stop/status for background recording.\n *\n * Session naming: \"tokrec-{user}\" — each user gets an independent tmux session.\n */\n\nimport { execa } from \"execa\"\n\nfunction sessionName(user: string): string {\n return `tokrec-${user}`\n}\n\nasync function hasSession(name: string): Promise<boolean> {\n const { exitCode } = await execa(\"tmux\", [\"has-session\", \"-t\", name], { reject: false })\n return exitCode === 0\n}\n\nexport async function tmuxStart(user: string, command: string): Promise<void> {\n const name = sessionName(user)\n if (await hasSession(name)) {\n throw new Error(`Session \"${name}\" already exists. Run \"tokrec stop -u ${user}\" first.`)\n }\n\n await execa(\"tmux\", [\"new-session\", \"-d\", \"-s\", name, command])\n}\n\nexport async function tmuxStop(user?: string): Promise<void> {\n if (user) {\n const name = sessionName(user)\n if (!(await hasSession(name))) {\n throw new Error(`No session \"${name}\" found.`)\n }\n await gracefulStop(name)\n return\n }\n\n // Stop all tokrec-* sessions\n const { stdout } = await execa(\"tmux\", [\"list-sessions\", \"-F\", \"#{session_name}\"], {\n reject: false,\n })\n const sessions = stdout.split(\"\\n\").filter((s) => s.startsWith(\"tokrec-\"))\n\n if (sessions.length === 0) {\n throw new Error(\"No active tokrec sessions found.\")\n }\n\n for (const s of sessions) {\n await gracefulStop(s)\n }\n}\n\n/**\n * Send Ctrl-C to the tmux session and wait for it to exit.\n * Falls back to kill-session after the timeout.\n */\nasync function gracefulStop(name: string): Promise<void> {\n // Send SIGINT via Ctrl-C\n await execa(\"tmux\", [\"send-keys\", \"-t\", name, \"C-c\"])\n\n // Wait up to 11 min for graceful shutdown (10 min pending conversion timeout + margin)\n const deadline = Date.now() + 660_000\n while (Date.now() < deadline) {\n if (!(await hasSession(name))) return\n await new Promise((r) => setTimeout(r, 500))\n }\n\n // Force kill if still alive\n if (await hasSession(name)) {\n await execa(\"tmux\", [\"kill-session\", \"-t\", name])\n }\n}\n\nexport interface SessionInfo {\n user: string\n session: string\n}\n\nexport async function tmuxStatus(user?: string): Promise<SessionInfo[]> {\n const { stdout } = await execa(\"tmux\", [\"list-sessions\", \"-F\", \"#{session_name}\"], {\n reject: false,\n })\n\n const all = stdout\n .split(\"\\n\")\n .filter((s) => s.startsWith(\"tokrec-\"))\n .map((s) => ({ user: s.slice(\"tokrec-\".length), session: s }))\n\n if (user) {\n return all.filter((s) => s.user === user)\n }\n\n return all\n}\n"],"mappings":";;;;;;;AAQA,SAAS,YAAY,MAAsB;CACzC,OAAO,UAAU;AACnB;AAEA,eAAe,WAAW,MAAgC;CACxD,MAAM,EAAE,aAAa,MAAM,MAAM,QAAQ;EAAC;EAAe;EAAM;CAAI,GAAG,EAAE,QAAQ,MAAM,CAAC;CACvF,OAAO,aAAa;AACtB;AAEA,eAAsB,UAAU,MAAc,SAAgC;CAC5E,MAAM,OAAO,YAAY,IAAI;C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C,KAAK,OAAO;EAAE,MAAM,EAAE,MAAM,CAAgB;EAAG,SAAS;CAAE,EAAE;CAE/D,IAAI,MACF,OAAO,IAAI,QAAQ,MAAM,EAAE,SAAS,IAAI;CAG1C,OAAO;AACT"}
|
package/dist/ui.mjs
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import { bytesToHuman, formatDuration, isLiveReason, relativeTime } from "@zfadhli/tokrec";
|
|
2
|
+
import * as color from "yoctocolors";
|
|
3
|
+
import yoctoSpinner from "yocto-spinner";
|
|
4
|
+
//#region src/ui.ts
|
|
5
|
+
/**
|
|
6
|
+
* Terminal Display Manager — console output via yocto-spinner and yoctocolors.
|
|
7
|
+
*
|
|
8
|
+
* This module owns the terminal and should be the only thing writing to
|
|
9
|
+
* stdout/stderr (the file logger handles persistent logs).
|
|
10
|
+
*/
|
|
11
|
+
const tag = {
|
|
12
|
+
ok: color.bold(color.green("[OK] ")),
|
|
13
|
+
done: color.bold(color.green("[DONE] ")),
|
|
14
|
+
live: color.bold(color.green("[LIVE] ")),
|
|
15
|
+
info: color.bold(color.blue("[INFO] ")),
|
|
16
|
+
off: color.bold(color.blue("[OFF] ")),
|
|
17
|
+
lock: color.bold(color.yellow("[LOCK] ")),
|
|
18
|
+
warn: color.bold(color.yellow("[WARN] ")),
|
|
19
|
+
err: color.bold(color.red("[ERR] "))
|
|
20
|
+
};
|
|
21
|
+
function createDisplay() {
|
|
22
|
+
const stream = process.stdout;
|
|
23
|
+
const animated = Boolean(stream.isTTY && process.env.TERM !== "dumb" && !("CI" in process.env));
|
|
24
|
+
const spin = (text) => yoctoSpinner({
|
|
25
|
+
text,
|
|
26
|
+
stream,
|
|
27
|
+
handleSignals: false
|
|
28
|
+
});
|
|
29
|
+
let activeSpinner = null;
|
|
30
|
+
let offlineLineShown = false;
|
|
31
|
+
let recordingStartTime = null;
|
|
32
|
+
let recordingTimer = null;
|
|
33
|
+
/** Stop the currently active spinner (if any) without printing anything. */
|
|
34
|
+
function clearSpinner() {
|
|
35
|
+
if (recordingTimer) {
|
|
36
|
+
clearInterval(recordingTimer);
|
|
37
|
+
recordingTimer = null;
|
|
38
|
+
}
|
|
39
|
+
if (activeSpinner?.isSpinning) activeSpinner.stop();
|
|
40
|
+
activeSpinner = null;
|
|
41
|
+
}
|
|
42
|
+
/** Stop the current spinner and print a one-liner with the given tag prefix. */
|
|
43
|
+
function finalize(prefix, text) {
|
|
44
|
+
clearSpinner();
|
|
45
|
+
process.stdout.write(`${prefix}${text}\n`);
|
|
46
|
+
}
|
|
47
|
+
return {
|
|
48
|
+
pollingStarted(intervalMinutes) {
|
|
49
|
+
finalize(tag.info, `${color.dim("Polling started (every ")}${color.bold(color.yellow(String(intervalMinutes)))}${color.dim(" min)")}`);
|
|
50
|
+
},
|
|
51
|
+
checkingUser(user) {
|
|
52
|
+
clearSpinner();
|
|
53
|
+
activeSpinner = spin(color.cyan(`Checking @${user}...`));
|
|
54
|
+
activeSpinner.start();
|
|
55
|
+
},
|
|
56
|
+
userOffline(user) {
|
|
57
|
+
finalize(tag.off, `${color.bold(color.yellow(`@${user}`))}${color.dim(" is offline")}`);
|
|
58
|
+
offlineLineShown = true;
|
|
59
|
+
},
|
|
60
|
+
userOfflineRepeat(user, lastCheck) {
|
|
61
|
+
clearSpinner();
|
|
62
|
+
const text = `${tag.off}${color.bold(color.yellow(`@${user}`))}${color.dim(" is offline")} ${color.dim(`[last online: ${color.bold(color.yellow(lastCheck))}]`)}`;
|
|
63
|
+
if (offlineLineShown) process.stdout.write(`\x1b[1A\r${text}\x1b[K\n`);
|
|
64
|
+
else {
|
|
65
|
+
process.stdout.write(`${text}\n`);
|
|
66
|
+
offlineLineShown = true;
|
|
67
|
+
}
|
|
68
|
+
},
|
|
69
|
+
userLive(user, roomId) {
|
|
70
|
+
clearSpinner();
|
|
71
|
+
offlineLineShown = false;
|
|
72
|
+
process.stdout.write(`${tag.live}${color.bold(color.green(`@${user}`))} ${color.dim(`(room: ${color.bold(color.yellow(roomId))})`)}\n`);
|
|
73
|
+
},
|
|
74
|
+
userRestricted(user) {
|
|
75
|
+
clearSpinner();
|
|
76
|
+
offlineLineShown = false;
|
|
77
|
+
process.stdout.write(`${tag.lock}${color.bold(color.yellow(`@${user}`))}${color.dim(" is live but age-protected/restricted — stream unavailable to this session")}\n`);
|
|
78
|
+
},
|
|
79
|
+
userLiveNoStream(user, roomId) {
|
|
80
|
+
clearSpinner();
|
|
81
|
+
offlineLineShown = false;
|
|
82
|
+
process.stdout.write(`${tag.live}${color.bold(color.green(`@${user}`))} ${color.dim(`(room: ${color.bold(color.yellow(roomId))}) \u2014 no stream URL found`)}\n`);
|
|
83
|
+
},
|
|
84
|
+
startRecording() {
|
|
85
|
+
clearSpinner();
|
|
86
|
+
recordingStartTime = Date.now();
|
|
87
|
+
activeSpinner = spin(`${color.cyan("Recording...")} ${color.dim(`[${color.bold(color.yellow("0s"))}]`)}`);
|
|
88
|
+
activeSpinner.start();
|
|
89
|
+
recordingTimer = setInterval(() => {
|
|
90
|
+
if (!animated || !activeSpinner?.isSpinning || !recordingStartTime) return;
|
|
91
|
+
const elapsed = (Date.now() - recordingStartTime) / 1e3;
|
|
92
|
+
activeSpinner.text = `${color.cyan("Recording...")} ${color.dim(`[${color.bold(color.yellow(formatDuration(elapsed)))}]`)}`;
|
|
93
|
+
}, 1e3);
|
|
94
|
+
},
|
|
95
|
+
finishRecording(filename, duration, size) {
|
|
96
|
+
finalize(tag.done, `${color.cyan(filename)}${color.dim(" — ")}${color.bold(color.yellow(size))}${color.dim(` in ${color.bold(color.yellow(formatDuration(duration)))}`)}`);
|
|
97
|
+
},
|
|
98
|
+
recordingError(message) {
|
|
99
|
+
finalize(tag.err, color.red(`Recording failed: ${message}`));
|
|
100
|
+
},
|
|
101
|
+
startSegmenting() {
|
|
102
|
+
clearSpinner();
|
|
103
|
+
activeSpinner = spin(color.cyan("Segmenting..."));
|
|
104
|
+
activeSpinner.start();
|
|
105
|
+
},
|
|
106
|
+
segmentsCreated(count) {
|
|
107
|
+
finalize(tag.ok, `${color.dim("Created ")}${color.bold(color.yellow(String(count)))}${color.dim(` MP4 segment${count !== 1 ? "s" : ""}`)}`);
|
|
108
|
+
},
|
|
109
|
+
startConverting() {
|
|
110
|
+
clearSpinner();
|
|
111
|
+
activeSpinner = spin(color.cyan("Converting to MP4..."));
|
|
112
|
+
activeSpinner.start();
|
|
113
|
+
},
|
|
114
|
+
conversionDone(output) {
|
|
115
|
+
finalize(tag.done, `${color.cyan(output)}`);
|
|
116
|
+
},
|
|
117
|
+
normalizeStart() {
|
|
118
|
+
clearSpinner();
|
|
119
|
+
activeSpinner = spin(color.cyan("Normalizing audio..."));
|
|
120
|
+
activeSpinner.start();
|
|
121
|
+
},
|
|
122
|
+
normalizeProgress(percent, phase) {
|
|
123
|
+
if (!animated || !activeSpinner?.isSpinning) return;
|
|
124
|
+
activeSpinner.text = ` ${phase === "analyzing" ? "Analyzing" : "Normalizing"}... ${color.bold(color.yellow(`${percent}%`))}`;
|
|
125
|
+
},
|
|
126
|
+
normalizeComplete() {
|
|
127
|
+
finalize(tag.ok, color.green("Audio normalized"));
|
|
128
|
+
},
|
|
129
|
+
normalizeError(message) {
|
|
130
|
+
finalize(tag.err, color.red(`Normalization failed: ${message}`));
|
|
131
|
+
},
|
|
132
|
+
showVersion(name, version) {
|
|
133
|
+
clearSpinner();
|
|
134
|
+
offlineLineShown = false;
|
|
135
|
+
process.stdout.write(`${color.dim(`${name} ${version}`)}\n`);
|
|
136
|
+
},
|
|
137
|
+
showError(message) {
|
|
138
|
+
clearSpinner();
|
|
139
|
+
offlineLineShown = false;
|
|
140
|
+
process.stdout.write(`${tag.err}${color.red(message)}\n`);
|
|
141
|
+
},
|
|
142
|
+
showInfo(message) {
|
|
143
|
+
clearSpinner();
|
|
144
|
+
offlineLineShown = false;
|
|
145
|
+
process.stdout.write(`${tag.info}${color.dim(message)}\n`);
|
|
146
|
+
},
|
|
147
|
+
showWarning(message) {
|
|
148
|
+
clearSpinner();
|
|
149
|
+
offlineLineShown = false;
|
|
150
|
+
process.stdout.write(`${tag.warn}${color.yellow(message)}\n`);
|
|
151
|
+
},
|
|
152
|
+
stop() {
|
|
153
|
+
clearSpinner();
|
|
154
|
+
offlineLineShown = false;
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Wire the recorder's four event channels to the terminal.
|
|
160
|
+
*
|
|
161
|
+
* Lives next to the display it drives: the mapping from recorder phase to
|
|
162
|
+
* terminal line is presentation, so `bin.ts` should not carry it.
|
|
163
|
+
*/
|
|
164
|
+
function attachDisplay(display, recorder, user) {
|
|
165
|
+
let lastWasLive = null;
|
|
166
|
+
let firstOfflineTime = 0;
|
|
167
|
+
recorder.on("verdict", (verdict) => {
|
|
168
|
+
if (verdict.reason === "restricted") display.userRestricted(user);
|
|
169
|
+
else if (verdict.reason === "no-stream-url") display.userLiveNoStream(user, verdict.room?.id ?? "?");
|
|
170
|
+
else if (isLiveReason(verdict.reason)) display.userLive(user, verdict.room?.id ?? "?");
|
|
171
|
+
else if (lastWasLive === null || lastWasLive === true) {
|
|
172
|
+
display.userOffline(user);
|
|
173
|
+
firstOfflineTime = Date.now();
|
|
174
|
+
} else display.userOfflineRepeat(user, relativeTime(Date.now() - firstOfflineTime));
|
|
175
|
+
lastWasLive = isLiveReason(verdict.reason);
|
|
176
|
+
});
|
|
177
|
+
recorder.on("record", (event) => {
|
|
178
|
+
switch (event.phase) {
|
|
179
|
+
case "start":
|
|
180
|
+
display.startRecording();
|
|
181
|
+
break;
|
|
182
|
+
case "download": {
|
|
183
|
+
const parsed = event.file.split("/").pop() ?? event.file;
|
|
184
|
+
display.finishRecording(parsed, event.duration, bytesToHuman(event.size));
|
|
185
|
+
break;
|
|
186
|
+
}
|
|
187
|
+
case "segment":
|
|
188
|
+
if (event.status === "start") display.startSegmenting();
|
|
189
|
+
else display.segmentsCreated(event.segments);
|
|
190
|
+
break;
|
|
191
|
+
case "convert":
|
|
192
|
+
if (event.status === "start") display.startConverting();
|
|
193
|
+
else display.conversionDone(event.output.split("/").pop() ?? event.output);
|
|
194
|
+
break;
|
|
195
|
+
case "normalize":
|
|
196
|
+
if (event.status === "start") display.normalizeStart();
|
|
197
|
+
else if (event.status === "done") display.normalizeComplete();
|
|
198
|
+
else display.normalizeError(event.error);
|
|
199
|
+
break;
|
|
200
|
+
case "end": break;
|
|
201
|
+
}
|
|
202
|
+
});
|
|
203
|
+
recorder.on("progress", (event) => {
|
|
204
|
+
if (event.kind === "normalize") display.normalizeProgress(event.percent, event.phase);
|
|
205
|
+
});
|
|
206
|
+
recorder.on("failure", (err) => {
|
|
207
|
+
display.showError(`[${err.code}] ${err.message}`);
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
//#endregion
|
|
211
|
+
export { attachDisplay, createDisplay };
|
|
212
|
+
|
|
213
|
+
//# sourceMappingURL=ui.mjs.map
|
package/dist/ui.mjs.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ui.mjs","names":[],"sources":["../src/ui.ts"],"sourcesContent":["/**\n * Terminal Display Manager — console output via yocto-spinner and yoctocolors.\n *\n * This module owns the terminal and should be the only thing writing to\n * stdout/stderr (the file logger handles persistent logs).\n */\n\nimport {\n bytesToHuman,\n formatDuration,\n isLiveReason,\n type RecorderController,\n relativeTime,\n} from \"@zfadhli/tokrec\"\nimport yoctoSpinner, { type Spinner } from \"yocto-spinner\"\nimport * as color from \"yoctocolors\"\n\n// ─── Tag helpers ──────────────────────────────────────────\nconst tag = {\n ok: color.bold(color.green(\"[OK] \")),\n done: color.bold(color.green(\"[DONE] \")),\n live: color.bold(color.green(\"[LIVE] \")),\n info: color.bold(color.blue(\"[INFO] \")),\n off: color.bold(color.blue(\"[OFF] \")),\n lock: color.bold(color.yellow(\"[LOCK] \")),\n warn: color.bold(color.yellow(\"[WARN] \")),\n err: color.bold(color.red(\"[ERR] \")),\n}\n\nexport interface Display {\n /** Called once when polling begins. */\n pollingStarted(intervalMinutes: number): void\n /** Spinner while checking if a user is live. */\n checkingUser(user: string): void\n /** User is offline (no active display). */\n userOffline(user: string): void\n /** User is still offline — updates the previous offline line with a timestamp. */\n userOfflineRepeat(user: string, lastCheck: string): void\n /** User is live! Clears the checking spinner. */\n userLive(user: string, roomId: string): void\n /** User is live but age-protected/restricted — stream unavailable. */\n userRestricted(user: string): void\n /** User is live but no stream URL was resolved. */\n userLiveNoStream(user: string, roomId: string): void\n\n /** Recording starts: spinner without filename (known only post-download). */\n startRecording(): void\n /** Recording finished successfully. Shows filename from the result. */\n finishRecording(filename: string, duration: number, size: string): void\n /** Recording encountered a non-fatal error. */\n recordingError(message: string): void\n\n /** FFmpeg segmenting starts. */\n startSegmenting(): void\n /** FFmpeg segmenting done. */\n segmentsCreated(count: number): void\n\n /** FFmpeg simple conversion starts (fallback path). */\n startConverting(): void\n /** Simple conversion done. */\n conversionDone(output: string): void\n\n /** Audio normalization starts (EBU R128 via peaknorm). */\n normalizeStart(): void\n /** Audio normalization progress update. */\n normalizeProgress(percent: number, phase: string): void\n /** Audio normalization completed successfully. */\n normalizeComplete(): void\n /** Audio normalization failed. */\n normalizeError(message: string): void\n\n /** Show version banner at startup. */\n showVersion(name: string, version: string): void\n\n /** General-purpose status helpers. */\n showError(message: string): void\n showInfo(message: string): void\n showWarning(message: string): void\n\n /** Stop all active spinners and clean up the terminal. */\n stop(): void\n}\n\nexport function createDisplay(): Display {\n // yocto-spinner with handleSignals off: bin.ts owns SIGINT/SIGTERM teardown.\n const stream = process.stdout\n // Mirrors yocto-spinner's internal isInteractive(); spinner.text writes a full\n // line when non-interactive, so per-tick updates must be skipped there.\n const animated = Boolean(stream.isTTY && process.env.TERM !== \"dumb\" && !(\"CI\" in process.env))\n const spin = (text: string): Spinner => yoctoSpinner({ text, stream, handleSignals: false })\n\n let activeSpinner: Spinner | null = null\n let offlineLineShown = false\n\n // Recording timer state\n let recordingStartTime: number | null = null\n let recordingTimer: ReturnType<typeof setInterval> | null = null\n\n /** Stop the currently active spinner (if any) without printing anything. */\n function clearSpinner(): void {\n if (recordingTimer) {\n clearInterval(recordingTimer)\n recordingTimer = null\n }\n if (activeSpinner?.isSpinning) {\n activeSpinner.stop()\n }\n activeSpinner = null\n }\n\n /** Stop the current spinner and print a one-liner with the given tag prefix. */\n function finalize(prefix: string, text: string): void {\n clearSpinner()\n process.stdout.write(`${prefix}${text}\\n`)\n }\n\n return {\n pollingStarted(intervalMinutes: number): void {\n finalize(\n tag.info,\n `${color.dim(\"Polling started (every \")}${color.bold(color.yellow(String(intervalMinutes)))}${color.dim(\" min)\")}`,\n )\n },\n\n checkingUser(user: string): void {\n clearSpinner()\n activeSpinner = spin(color.cyan(`Checking @${user}...`))\n activeSpinner.start()\n },\n\n userOffline(user: string): void {\n finalize(tag.off, `${color.bold(color.yellow(`@${user}`))}${color.dim(\" is offline\")}`)\n offlineLineShown = true\n },\n\n userOfflineRepeat(user: string, lastCheck: string): void {\n clearSpinner()\n const text = `${tag.off}${color.bold(color.yellow(`@${user}`))}${color.dim(\" is offline\")} ${color.dim(`[last online: ${color.bold(color.yellow(lastCheck))}]`)}`\n if (offlineLineShown) {\n // Move cursor up one line and overwrite the previous offline message\n process.stdout.write(`\\x1b[1A\\r${text}\\x1b[K\\n`)\n } else {\n process.stdout.write(`${text}\\n`)\n offlineLineShown = true\n }\n },\n\n userLive(user: string, roomId: string): void {\n clearSpinner()\n offlineLineShown = false\n process.stdout.write(\n `${tag.live}${color.bold(color.green(`@${user}`))} ${color.dim(`(room: ${color.bold(color.yellow(roomId))})`)}\\n`,\n )\n },\n\n userRestricted(user: string): void {\n clearSpinner()\n offlineLineShown = false\n process.stdout.write(\n `${tag.lock}${color.bold(color.yellow(`@${user}`))}${color.dim(\" is live but age-protected/restricted \\u2014 stream unavailable to this session\")}\\n`,\n )\n },\n\n userLiveNoStream(user: string, roomId: string): void {\n clearSpinner()\n offlineLineShown = false\n process.stdout.write(\n `${tag.live}${color.bold(color.green(`@${user}`))} ${color.dim(`(room: ${color.bold(color.yellow(roomId))}) \\u2014 no stream URL found`)}\\n`,\n )\n },\n\n startRecording(): void {\n clearSpinner()\n recordingStartTime = Date.now()\n activeSpinner = spin(\n `${color.cyan(\"Recording...\")} ${color.dim(`[${color.bold(color.yellow(\"0s\"))}]`)}`,\n )\n activeSpinner.start()\n\n recordingTimer = setInterval(() => {\n if (!animated || !activeSpinner?.isSpinning || !recordingStartTime) return\n const elapsed = (Date.now() - recordingStartTime) / 1000\n activeSpinner.text = `${color.cyan(\"Recording...\")} ${color.dim(`[${color.bold(color.yellow(formatDuration(elapsed)))}]`)}`\n }, 1000)\n },\n\n finishRecording(filename: string, duration: number, size: string): void {\n finalize(\n tag.done,\n `${color.cyan(filename)}${color.dim(\" — \")}${color.bold(color.yellow(size))}${color.dim(` in ${color.bold(color.yellow(formatDuration(duration)))}`)}`,\n )\n },\n\n recordingError(message: string): void {\n finalize(tag.err, color.red(`Recording failed: ${message}`))\n },\n\n startSegmenting(): void {\n clearSpinner()\n activeSpinner = spin(color.cyan(\"Segmenting...\"))\n activeSpinner.start()\n },\n\n segmentsCreated(count: number): void {\n finalize(\n tag.ok,\n `${color.dim(\"Created \")}${color.bold(color.yellow(String(count)))}${color.dim(` MP4 segment${count !== 1 ? \"s\" : \"\"}`)}`,\n )\n },\n\n startConverting(): void {\n clearSpinner()\n activeSpinner = spin(color.cyan(\"Converting to MP4...\"))\n activeSpinner.start()\n },\n\n conversionDone(output: string): void {\n finalize(tag.done, `${color.cyan(output)}`)\n },\n\n normalizeStart(): void {\n clearSpinner()\n activeSpinner = spin(color.cyan(\"Normalizing audio...\"))\n activeSpinner.start()\n },\n\n normalizeProgress(percent: number, phase: string): void {\n if (!animated || !activeSpinner?.isSpinning) return\n const label = phase === \"analyzing\" ? \"Analyzing\" : \"Normalizing\"\n activeSpinner.text = ` ${label}... ${color.bold(color.yellow(`${percent}%`))}`\n },\n\n normalizeComplete(): void {\n finalize(tag.ok, color.green(\"Audio normalized\"))\n },\n\n normalizeError(message: string): void {\n finalize(tag.err, color.red(`Normalization failed: ${message}`))\n },\n\n showVersion(name: string, version: string): void {\n clearSpinner()\n offlineLineShown = false\n process.stdout.write(`${color.dim(`${name} ${version}`)}\\n`)\n },\n\n showError(message: string): void {\n clearSpinner()\n offlineLineShown = false\n process.stdout.write(`${tag.err}${color.red(message)}\\n`)\n },\n\n showInfo(message: string): void {\n clearSpinner()\n offlineLineShown = false\n process.stdout.write(`${tag.info}${color.dim(message)}\\n`)\n },\n\n showWarning(message: string): void {\n clearSpinner()\n offlineLineShown = false\n process.stdout.write(`${tag.warn}${color.yellow(message)}\\n`)\n },\n\n stop(): void {\n clearSpinner()\n offlineLineShown = false\n },\n }\n}\n\n/**\n * Wire the recorder's four event channels to the terminal.\n *\n * Lives next to the display it drives: the mapping from recorder phase to\n * terminal line is presentation, so `bin.ts` should not carry it.\n */\nexport function attachDisplay(\n display: Display,\n recorder: Pick<RecorderController, \"on\">,\n user: string,\n): void {\n let lastWasLive: boolean | null = null\n let firstOfflineTime = 0\n\n recorder.on(\"verdict\", (verdict) => {\n if (verdict.reason === \"restricted\") {\n display.userRestricted(user)\n } else if (verdict.reason === \"no-stream-url\") {\n display.userLiveNoStream(user, verdict.room?.id ?? \"?\")\n } else if (isLiveReason(verdict.reason)) {\n display.userLive(user, verdict.room?.id ?? \"?\")\n } else if (lastWasLive === null || lastWasLive === true) {\n display.userOffline(user)\n firstOfflineTime = Date.now()\n } else {\n display.userOfflineRepeat(user, relativeTime(Date.now() - firstOfflineTime))\n }\n lastWasLive = isLiveReason(verdict.reason)\n })\n\n recorder.on(\"record\", (event) => {\n switch (event.phase) {\n case \"start\":\n display.startRecording()\n break\n case \"download\": {\n const parsed = event.file.split(\"/\").pop() ?? event.file\n display.finishRecording(parsed, event.duration, bytesToHuman(event.size))\n break\n }\n case \"segment\":\n if (event.status === \"start\") display.startSegmenting()\n else display.segmentsCreated(event.segments)\n break\n case \"convert\":\n if (event.status === \"start\") display.startConverting()\n else display.conversionDone(event.output.split(\"/\").pop() ?? event.output)\n break\n case \"normalize\":\n if (event.status === \"start\") display.normalizeStart()\n else if (event.status === \"done\") display.normalizeComplete()\n else display.normalizeError(event.error)\n break\n case \"end\":\n break\n }\n })\n\n recorder.on(\"progress\", (event) => {\n if (event.kind === \"normalize\") display.normalizeProgress(event.percent, event.phase)\n })\n\n recorder.on(\"failure\", (err) => {\n display.showError(`[${err.code}] ${err.message}`)\n })\n}\n"],"mappings":";;;;;;;;;;AAkBA,MAAM,MAAM;CACV,IAAI,MAAM,KAAK,MAAM,MAAM,OAAO,CAAC;CACnC,MAAM,MAAM,KAAK,MAAM,MAAM,SAAS,CAAC;CACvC,MAAM,MAAM,KAAK,MAAM,MAAM,SAAS,CAAC;CACvC,MAAM,MAAM,KAAK,MAAM,KAAK,SAAS,CAAC;CACtC,KAAK,MAAM,KAAK,MAAM,KAAK,QAAQ,CAAC;CACpC,MAAM,MAAM,KAAK,MAAM,OAAO,SAAS,CAAC;CACxC,MAAM,MAAM,KAAK,MAAM,OAAO,SAAS,CAAC;CACxC,KAAK,MAAM,KAAK,MAAM,IAAI,QAAQ,CAAC;AACrC;AAwDA,SAAgB,gBAAyB;CAEvC,MAAM,SAAS,QAAQ;CAGvB,MAAM,WAAW,QAAQ,OAAO,SAAS,QAAQ,IAAI,SAAS,UAAU,EAAE,QAAQ,QAAQ,IAAI;CAC9F,MAAM,QAAQ,SAA0B,aAAa;EAAE;EAAM;EAAQ,eAAe;CAAM,CAAC;CAE3F,IAAI,gBAAgC;CACpC,IAAI,mBAAmB;CAGvB,IAAI,qBAAoC;CACxC,IAAI,iBAAwD;;CAG5D,SAAS,eAAqB;EAC5B,IAAI,gBAAgB;GAClB,cAAc,cAAc;GAC5B,iBAAiB;EACnB;EACA,IAAI,eAAe,YACjB,cAAc,KAAK;EAErB,gBAAgB;CAClB;;CAGA,SAAS,SAAS,QAAgB,MAAoB;EACpD,aAAa;EACb,QAAQ,OAAO,MAAM,GAAG,SAA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AAI,MAAM,SAAS,aAAa,QAAQ,kBAAkB,MAAM,SAAS,MAAM,KAAK;CACtF,CAAC;CAED,SAAS,GAAG,YAAY,QAAQ;EAC9B,QAAQ,UAAU,IAAI,IAAI,KAAK,IAAI,IAAI,SAAS;CAClD,CAAC;AACH"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,35 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zfadhli/tokrec-cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.15.0",
|
|
4
|
+
"description": "TikTok live stream recorder CLI",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"tokrec": "./dist/bin.mjs"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"dist"
|
|
11
|
+
],
|
|
12
|
+
"scripts": {
|
|
13
|
+
"build": "tsdown",
|
|
14
|
+
"typecheck": "tsc --noEmit"
|
|
15
|
+
},
|
|
16
|
+
"dependencies": {
|
|
17
|
+
"@zfadhli/tokrec": "workspace:^",
|
|
18
|
+
"cac": "^7.0.0",
|
|
19
|
+
"execa": "^9.6.1",
|
|
20
|
+
"yocto-spinner": "^1.2.2",
|
|
21
|
+
"yoctocolors": "^2.2.0"
|
|
22
|
+
},
|
|
23
|
+
"license": "MIT",
|
|
24
|
+
"repository": {
|
|
25
|
+
"type": "git",
|
|
26
|
+
"url": "https://github.com/zfadhli/tokrec.git"
|
|
27
|
+
},
|
|
28
|
+
"bugs": {
|
|
29
|
+
"url": "https://github.com/zfadhli/tokrec/issues"
|
|
30
|
+
},
|
|
31
|
+
"homepage": "https://github.com/zfadhli/tokrec",
|
|
32
|
+
"publishConfig": {
|
|
33
|
+
"access": "public"
|
|
34
|
+
}
|
|
35
|
+
}
|
package/README.md
DELETED