@zfadhli/tokrec 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +126 -0
  2. package/dist/app/config.mjs.map +1 -1
  3. package/dist/app/job.mjs +39 -17
  4. package/dist/app/job.mjs.map +1 -1
  5. package/dist/app/logger.mjs +8 -16
  6. package/dist/app/logger.mjs.map +1 -1
  7. package/dist/app/loop.mjs +6 -3
  8. package/dist/app/loop.mjs.map +1 -1
  9. package/dist/app/recorder.d.mts.map +1 -1
  10. package/dist/app/recorder.mjs +25 -29
  11. package/dist/app/recorder.mjs.map +1 -1
  12. package/dist/core/plan.mjs.map +1 -1
  13. package/dist/core/verdict.d.mts +1 -1
  14. package/dist/core/verdict.mjs.map +1 -1
  15. package/dist/io/http.mjs +16 -24
  16. package/dist/io/http.mjs.map +1 -1
  17. package/dist/io/media/download.mjs +1 -1
  18. package/dist/io/media/ffmpeg.mjs +52 -6
  19. package/dist/io/media/ffmpeg.mjs.map +1 -1
  20. package/dist/io/tiktok/client.mjs +9 -12
  21. package/dist/io/tiktok/client.mjs.map +1 -1
  22. package/dist/io/tiktok/discovery/chain.mjs +14 -17
  23. package/dist/io/tiktok/discovery/chain.mjs.map +1 -1
  24. package/dist/io/tiktok/discovery/page.mjs +38 -52
  25. package/dist/io/tiktok/discovery/page.mjs.map +1 -1
  26. package/dist/io/tiktok/parse.mjs +24 -31
  27. package/dist/io/tiktok/parse.mjs.map +1 -1
  28. package/dist/io/tiktok/webcast.mjs +15 -29
  29. package/dist/io/tiktok/webcast.mjs.map +1 -1
  30. package/package.json +1 -1
  31. package/src/app/config.ts +5 -19
  32. package/src/app/job.ts +61 -27
  33. package/src/app/logger.ts +9 -23
  34. package/src/app/loop.ts +12 -11
  35. package/src/app/recorder.ts +44 -47
  36. package/src/core/plan.ts +1 -1
  37. package/src/core/verdict.ts +1 -1
  38. package/src/index.ts +1 -1
  39. package/src/io/http.ts +24 -49
  40. package/src/io/media/ffmpeg.ts +65 -7
  41. package/src/io/tiktok/client.ts +13 -24
  42. package/src/io/tiktok/discovery/chain.ts +15 -24
  43. package/src/io/tiktok/discovery/page.ts +51 -90
  44. package/src/io/tiktok/parse.ts +38 -48
  45. package/src/io/tiktok/webcast.ts +30 -41
  46. package/dist/app/abort.mjs +0 -14
  47. package/dist/app/abort.mjs.map +0 -1
  48. package/dist/app/events.mjs +0 -36
  49. package/dist/app/events.mjs.map +0 -1
  50. package/dist/io/media/convert.mjs +0 -60
  51. package/dist/io/media/convert.mjs.map +0 -1
  52. package/dist/io/media/normalize.mjs +0 -32
  53. package/dist/io/media/normalize.mjs.map +0 -1
  54. package/src/app/abort.ts +0 -18
  55. package/src/app/events.ts +0 -46
  56. package/src/io/media/convert.ts +0 -69
  57. package/src/io/media/normalize.ts +0 -64
@@ -1 +1 @@
1
- {"version":3,"file":"page.mjs","names":[],"sources":["../../../../src/io/tiktok/discovery/page.ts"],"sourcesContent":["import type { RoomRef } from \"../../../core/verdict\"\nimport type { SigiState } from \"../parse\"\nimport {\n extractSigiState,\n extractStreamUrlFast,\n extractUserFromUniversalData,\n findStreamUrlRecursively,\n} from \"../parse\"\nimport {\n type Candidate,\n type DiscoverySource,\n fromRoomInfo,\n miss,\n type ResolveContext,\n withStream,\n} from \"./chain\"\n\n/**\n * Page source: server-rendered SIGI_STATE first, then the async-loaded legacy\n * module, then `__UNIVERSAL_DATA_FOR_REHYDRATION__`. Throws propagate to the\n * chain, which records them and moves on — never a dead end.\n */\nexport function createPageSource(): DiscoverySource {\n return {\n id: \"page\",\n async find(ctx: ResolveContext): Promise<Candidate> {\n let sigi: SigiState | null = null\n let html = \"\"\n // A `failed` sub-step is not terminal: legacy + universal-data fallbacks\n // still get their chance. It is returned only if nothing else hit.\n let failure: Extract<Candidate, { kind: \"failed\" }> | null = null\n const take = (candidate: Candidate): Candidate | null => {\n if (candidate.kind === \"room\" || candidate.kind === \"denied\") return candidate\n if (candidate.kind === \"failed\") failure ??= candidate\n return null\n }\n\n const page = await ctx.fetchPage(ctx.user, \"/live\")\n if (!page) {\n ctx.debug(\"fetchLiveInfo: all domains blocked for /live page\")\n // Fall through to universal data / profile page fallback\n html = \"\"\n } else {\n html = page.html\n ctx.debug(\n `fetchLiveInfo: /live returned ${html.length} bytes (${page.baseUrl}), first 300: ${html.slice(0, 300).replace(/\\n/g, \"\\\\n\")}`,\n )\n\n sigi = extractSigiState(html)\n ctx.debug(`fetchLiveInfo: SIGI_STATE ${sigi ? \"found\" : \"not found\"}`)\n\n if (sigi) {\n const liveRoom = sigi.LiveRoom?.liveRoomUserInfo?.liveRoom\n const userInfo = sigi.LiveRoom?.liveRoomUserInfo?.user\n\n ctx.debug(\n `fetchLiveInfo: liveRoom=${!!liveRoom}, userInfo=${!!userInfo}, userInfo.roomId=${userInfo?.roomId ?? \"null\"}`,\n )\n\n // ── Primary path: liveRoom is populated (server-rendered) ──\n if (liveRoom && userInfo?.roomId) {\n const room: RoomRef = {\n id: String(userInfo.roomId),\n title: liveRoom.title ?? null,\n live: liveRoom.status === 2, // 2 = live, 4 = offline\n }\n ctx.debug(\n `fetchLiveInfo: primary path — roomId=${room.id}, status=${liveRoom.status}, live=${room.live}`,\n )\n if (!room.live) return { kind: \"room\", room, stream: null, source: \"sigi\" }\n\n // Extract stream URL: try SIGI_STATE first, then Webcast API fallback\n const knownUrl = extractStreamUrlFast(liveRoom) ?? findStreamUrlRecursively(sigi)\n return withStream(ctx, room, \"sigi\", knownUrl)\n }\n\n // ── Fallback: userInfo has roomId, but liveRoom is async-loaded ──\n // TikTok may omit liveRoom from the server-rendered page and load it\n // via JavaScript. Query the Webcast API directly — it's authoritative.\n if (userInfo?.roomId) {\n const roomId = String(userInfo.roomId)\n ctx.debug(`fetchLiveInfo: userInfo fallback — roomId=${roomId}, querying Webcast API`)\n const found = take(await fromRoomInfo(ctx, roomId, \"room-info\"))\n ctx.debug(\n `fetchLiveInfo: Webcast API ${found ? \"returned room info\" : \"returned null\"}`,\n )\n if (found) return found\n }\n\n // ── Legacy fallback: async-loaded SIGI_STATE ──\n ctx.debug(\"fetchLiveInfo: trying legacy fallback (UserModule)\")\n const legacy = take(await sigiLegacy(sigi, ctx))\n ctx.debug(`fetchLiveInfo: legacy fallback ${legacy ? \"succeeded\" : \"returned null\"}`)\n if (legacy) return legacy\n } // end if (sigi)\n } // end else (page loaded)\n\n // ── Universal data from the already-fetched /live html ──\n // TikTok migrated from SIGI_STATE to __UNIVERSAL_DATA_FOR_REHYDRATION__.\n // The /live page may not have it, so try the main profile page.\n ctx.debug(`fetchLiveInfo: trying universal data fallback (html length ${html.length})`)\n const { roomId } = extractUserFromUniversalData(html)\n ctx.debug(`fetchLiveInfo: universal data roomId=${roomId ?? \"null\"}`)\n if (roomId) {\n const found = take(await fromRoomInfo(ctx, roomId, \"room-info\"))\n ctx.debug(\n `fetchLiveInfo: universal data Webcast API ${found ? \"succeeded\" : \"returned null\"}`,\n )\n if (found) return found\n }\n return failure ?? miss(\"page: no room id\")\n },\n }\n}\n\n/**\n * Secondary live-info extraction when SIGI_STATE's LiveRoom data is\n * async-loaded. Uses LiveRoom.liveRoomStatus for the live flag and\n * UserModule.users[user].roomId for the room ID. Stream URL comes from the\n * Webcast API (room/info/) as a final fallback.\n */\nasync function sigiLegacy(sigi: SigiState, ctx: ResolveContext): Promise<Candidate> {\n const isLive = sigi.LiveRoom?.liveRoomStatus === 2 // 2 = live\n\n // Try to get roomId from UserModule (usually populated even when LiveRoom is not)\n const userModule = sigi.UserModule?.users?.[ctx.user]\n let roomId: string | null = null\n\n if (userModule?.roomId) {\n roomId =\n typeof userModule.roomId === \"object\"\n ? String((userModule.roomId as { id: string }).id ?? \"\")\n : String(userModule.roomId)\n }\n\n // No roomId available — treat as offline (room/enter was unreliable).\n if (!roomId) return miss(\"sigi-legacy: no roomId\")\n\n const room: RoomRef = { id: roomId, title: null, live: isLive }\n if (!isLive) return { kind: \"room\", room, stream: null, source: \"sigi\" }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"}
1
+ {"version":3,"file":"page.mjs","names":[],"sources":["../../../../src/io/tiktok/discovery/page.ts"],"sourcesContent":["import type { RoomRef } from \"../../../core/verdict\"\nimport type { SigiState } from \"../parse\"\nimport {\n extractSigiState,\n extractStreamUrlFast,\n extractUserFromUniversalData,\n findStreamUrlRecursively,\n} from \"../parse\"\nimport type { Candidate, DiscoverySource, ResolveContext } from \"./chain\"\nimport { fromRoomInfo, miss, withStream } from \"./chain\"\n\n/**\n * Page source: server-rendered SIGI_STATE first, then the async-loaded legacy\n * module, then `__UNIVERSAL_DATA_FOR_REHYDRATION__`. Throws propagate to the\n * chain, which records them and moves on — never a dead end.\n */\nexport function createPageSource(): DiscoverySource {\n return {\n id: \"page\",\n async find(ctx: ResolveContext): Promise<Candidate> {\n const page = await ctx.fetchPage(ctx.user, \"/live\")\n const html = page?.html ?? \"\"\n ctx.debug(\n page\n ? `fetchLiveInfo: /live returned ${html.length} bytes (${page.baseUrl})`\n : \"fetchLiveInfo: all domains blocked for /live page\",\n )\n\n // A `failed` sub-step is not terminal: later paths still get their chance.\n // It is returned only if nothing else hit.\n let failure: Extract<Candidate, { kind: \"failed\" }> | null = null\n const attempt = async (pending: Promise<Candidate>): Promise<Candidate | null> => {\n const candidate = await pending\n if (candidate.kind === \"room\" || candidate.kind === \"denied\") return candidate\n if (candidate.kind === \"failed\") failure ??= candidate\n return null\n }\n\n const sigi: SigiState | null = page ? extractSigiState(html) : null\n ctx.debug(`fetchLiveInfo: SIGI_STATE ${sigi ? \"found\" : \"not found\"}`)\n const liveRoom = sigi?.LiveRoom?.liveRoomUserInfo?.liveRoom\n const roomId = sigi?.LiveRoom?.liveRoomUserInfo?.user?.roomId\n const id = roomId ? String(roomId) : null\n\n // 1. Server-rendered liveRoom wins — no extra request needed.\n if (liveRoom && id) {\n const room: RoomRef = {\n id,\n title: liveRoom.title ?? null,\n live: liveRoom.status === 2, // 2 = live, 4 = offline\n }\n ctx.debug(`fetchLiveInfo: primary path — roomId=${room.id}, live=${room.live}`)\n if (!room.live) return { kind: \"room\", room, stream: null, source: \"sigi\" }\n const knownUrl = extractStreamUrlFast(liveRoom) ?? findStreamUrlRecursively(sigi)\n return withStream(ctx, room, \"sigi\", knownUrl)\n }\n\n // 2. roomId present but liveRoom async-loaded: the Webcast API is authoritative.\n if (id) {\n const found = await attempt(fromRoomInfo(ctx, id, \"room-info\"))\n if (found) return found\n }\n\n // 3. Legacy async-loaded SIGI_STATE.\n if (sigi) {\n const found = await attempt(sigiLegacy(sigi, ctx))\n if (found) return found\n }\n\n // 4. Universal data — SIGI_STATE's successor, from the already-fetched page.\n const universalRoomId = extractUserFromUniversalData(html).roomId\n ctx.debug(`fetchLiveInfo: universal data roomId=${universalRoomId ?? \"null\"}`)\n if (universalRoomId) {\n const found = await attempt(fromRoomInfo(ctx, universalRoomId, \"room-info\"))\n if (found) return found\n }\n\n return failure ?? miss(\"page: no room id\")\n },\n }\n}\n\n/**\n * Secondary live-info extraction when SIGI_STATE's LiveRoom data is\n * async-loaded. Uses LiveRoom.liveRoomStatus for the live flag and\n * UserModule.users[user].roomId for the room ID. Stream URL comes from the\n * Webcast API (room/info/) as a final fallback.\n */\nasync function sigiLegacy(sigi: SigiState, ctx: ResolveContext): Promise<Candidate> {\n const isLive = sigi.LiveRoom?.liveRoomStatus === 2 // 2 = live\n\n // UserModule is usually populated even when LiveRoom is not.\n const owner = sigi.UserModule?.users?.[ctx.user]\n const raw = owner?.roomId\n const roomId = raw ? String(typeof raw === \"object\" ? (raw.id ?? \"\") : raw) : \"\"\n\n // No roomId available — treat as offline (room/enter was unreliable).\n if (!roomId) return miss(\"sigi-legacy: no roomId\")\n\n const room: RoomRef = { id: roomId, title: null, live: isLive }\n if (!isLive) return { kind: \"room\", room, stream: null, source: \"sigi\" }\n return withStream(ctx, room, \"sigi\", null)\n}\n"],"mappings":";;;;;;;;AAgBA,SAAgB,mBAAoC;CAClD,OAAO;EACL,IAAI;EACJ,MAAM,KAAK,KAAyC;GAClD,MAAM,O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M,QAAQ,aAAa,KAAK,iBAAiB,WAAW,CAAC;IAC3E,IAAI,OAAO,OAAO;GACpB;GAEA,OAAO,WAAW,KAAK,kBAAkB;EAC3C;CACF;AACF;;;;;;;AAQA,eAAe,WAAW,MAAiB,KAAyC;CAClF,MAAM,SAAS,KAAK,UAAU,mBAAmB;CAIjD,MAAM,OADQ,KAAK,YAAY,QAAQ,IAAI,MAAA,EACxB;CACnB,MAAM,SAAS,MAAM,OAAO,OAAO,QAAQ,WAAY,IAAI,MAAM,KAAM,GAAG,IAAI;CAG9E,IAAI,CAAC,QAAQ,OAAO,KAAK,wBAAwB;CAEjD,MAAM,OAAgB;EAAE,IAAI;EAAQ,OAAO;EAAM,MAAM;CAAO;CAC9D,IAAI,CAAC,QAAQ,OAAO;EAAE,MAAM;EAAQ;EAAM,QAAQ;EAAM,QAAQ;CAAO;CACvE,OAAO,WAAW,KAAK,MAAM,QAAQ,IAAI;AAC3C"}
@@ -1,9 +1,7 @@
1
1
  //#region src/io/tiktok/parse.ts
2
- /**
3
- * @public Exported for testing.
4
- */
5
- function extractSigiState(html) {
6
- const match = html.match(/<script\s+id="SIGI_STATE"\s+type="application\/json">(.*?)<\/script>/);
2
+ /** Pull a `<script id="…" type="application/json">` block out of the page. */
3
+ function embeddedJson(html, marker) {
4
+ const match = html.match(marker);
7
5
  if (!match?.[1]) return null;
8
6
  try {
9
7
  return JSON.parse(match[1]);
@@ -12,6 +10,12 @@ function extractSigiState(html) {
12
10
  }
13
11
  }
14
12
  /**
13
+ * @public Exported for testing.
14
+ */
15
+ function extractSigiState(html) {
16
+ return embeddedJson(html, /<script\s+id="SIGI_STATE"\s+type="application\/json">(.*?)<\/script>/);
17
+ }
18
+ /**
15
19
  * Extract the numeric user ID and optional room ID from TikTok's new
16
20
  * page structure (__UNIVERSAL_DATA_FOR_REHYDRATION__).
17
21
  *
@@ -25,24 +29,16 @@ function extractSigiState(html) {
25
29
  * @public Exported for testing and fixture capture.
26
30
  */
27
31
  function extractUserFromUniversalData(html) {
28
- const match = html.match(/<script\s+id="__UNIVERSAL_DATA_FOR_REHYDRATION__"\s+type="application\/json">(.*?)<\/script>/);
29
- if (!match?.[1]) return {
32
+ const data = embeddedJson(html, /<script\s+id="__UNIVERSAL_DATA_FOR_REHYDRATION__"\s+type="application\/json">(.*?)<\/script>/);
33
+ if (!data) return {
30
34
  userId: null,
31
35
  roomId: null
32
36
  };
33
- try {
34
- const data = JSON.parse(match[1]);
35
- const user = ((data.__DEFAULT_SCOPE__ ?? data)?.["webapp.user-detail"])?.userInfo?.user;
36
- return {
37
- userId: user?.id ? String(user.id) : null,
38
- roomId: user?.roomId ? String(user.roomId) : null
39
- };
40
- } catch {
41
- return {
42
- userId: null,
43
- roomId: null
44
- };
45
- }
37
+ const user = (data.__DEFAULT_SCOPE__ ?? data)["webapp.user-detail"]?.userInfo?.user;
38
+ return {
39
+ userId: user?.id ? String(user.id) : null,
40
+ roomId: user?.roomId ? String(user.roomId) : null
41
+ };
46
42
  }
47
43
  /**
48
44
  * Fast-path: extract stream URL from the known SIGI_STATE location.
@@ -54,7 +50,7 @@ function extractStreamUrlFast(liveRoom) {
54
50
  try {
55
51
  const raw = liveRoom?.streamData?.pull_data?.stream_data;
56
52
  if (!raw) return null;
57
- const data = JSON.parse(raw)?.data;
53
+ const data = JSON.parse(raw).data;
58
54
  if (!data) return null;
59
55
  for (const q of [
60
56
  "origin",
@@ -82,13 +78,13 @@ function extractStreamUrlFast(liveRoom) {
82
78
  * Inspired by PR #430 (Michele0303/tiktok-live-recorder).
83
79
  */
84
80
  function findStreamUrlRecursively(obj) {
85
- const flvUrls = [];
86
- const m3u8Urls = [];
81
+ let flv = null;
82
+ let hls = null;
87
83
  function walk(value) {
88
84
  if (typeof value === "string") {
89
- if ((value.startsWith("http://") || value.startsWith("https://")) && (value.includes(".flv") || value.includes(".m3u8"))) {
90
- if (value.includes(".flv")) flvUrls.push(value);
91
- else m3u8Urls.push(value);
85
+ if (value.startsWith("http://") || value.startsWith("https://")) {
86
+ if (value.includes(".flv")) flv ??= value;
87
+ else if (value.includes(".m3u8")) hls ??= value;
92
88
  return;
93
89
  }
94
90
  if (value.startsWith("{") || value.startsWith("[")) try {
@@ -96,13 +92,10 @@ function findStreamUrlRecursively(obj) {
96
92
  } catch {}
97
93
  return;
98
94
  }
99
- if (value && typeof value === "object") if (Array.isArray(value)) for (const item of value) walk(item);
100
- else for (const val of Object.values(value)) walk(val);
95
+ if (value && typeof value === "object") for (const val of Object.values(value)) walk(val);
101
96
  }
102
97
  walk(obj);
103
- if (flvUrls.length > 0) return flvUrls[0];
104
- if (m3u8Urls.length > 0) return m3u8Urls[0];
105
- return null;
98
+ return flv ?? hls;
106
99
  }
107
100
  //#endregion
108
101
  export { extractSigiState, extractStreamUrlFast, extractUserFromUniversalData, findStreamUrlRecursively };
@@ -1 +1 @@
1
- {"version":3,"file":"parse.mjs","names":[],"sources":["../../../src/io/tiktok/parse.ts"],"sourcesContent":["export interface SigiState {\n LiveRoom?: {\n liveRoomStatus?: number\n liveRoomUserInfo?: {\n user?: {\n id?: string | number\n roomId?: string | number\n }\n liveRoom?: {\n status?: number // 2 = live, 4 = offline\n title?: string\n startTime?: number\n streamData?: {\n pull_data?: {\n stream_data?: string // JSON string with FLV/HLS URLs\n }\n }\n }\n }\n }\n UserModule?: {\n users?: {\n [username: string]: {\n id?: string // numeric user ID\n uniqueId?: string\n roomId?: string | { id: string }\n }\n }\n }\n}\n\n// ─── HTML parsing ──────────────────────────────────────────\n\n/**\n * @public Exported for testing.\n */\nexport function extractSigiState(html: string): SigiState | null {\n const match = html.match(/<script\\s+id=\"SIGI_STATE\"\\s+type=\"application\\/json\">(.*?)<\\/script>/)\n if (!match?.[1]) return null\n try {\n return JSON.parse(match[1]) as SigiState\n } catch {\n return null\n }\n}\n\n/**\n * Extract the numeric user ID and optional room ID from TikTok's new\n * page structure (__UNIVERSAL_DATA_FOR_REHYDRATION__).\n *\n * The profile page (/@user) includes \"webapp.user-detail\" which\n * contains the user's numeric ID. When the user is live, the roomId\n * is also embedded here.\n *\n * Returns { userId, roomId } where userId is always set when the data\n * is found, and roomId is set only when the user is currently live.\n *\n * @public Exported for testing and fixture capture.\n */\nexport function extractUserFromUniversalData(html: string): {\n userId: string | null\n roomId: string | null\n} {\n const match = html.match(\n /<script\\s+id=\"__UNIVERSAL_DATA_FOR_REHYDRATION__\"\\s+type=\"application\\/json\">(.*?)<\\/script>/,\n )\n if (!match?.[1]) return { userId: null, roomId: null }\n try {\n const data = JSON.parse(match[1])\n const scope = (data as Record<string, unknown>).__DEFAULT_SCOPE__ ?? data\n const userDetail = scope?.[\"webapp.user-detail\"]\n const user = userDetail?.userInfo?.user\n const userId = user?.id ? String(user.id) : null\n const roomId = user?.roomId ? String(user.roomId) : null\n return { userId, roomId }\n } catch {\n return { userId: null, roomId: null }\n }\n}\n\n// ─── Stream URL extraction ─────────────────────────────────\n\n/**\n * Fast-path: extract stream URL from the known SIGI_STATE location.\n * This covers ~95% of cases without needing a full recursive search.\n *\n * Prefers FLV (lower latency) over HLS/other protocols.\n */\nexport function extractStreamUrlFast(\n liveRoom: NonNullable<NonNullable<SigiState[\"LiveRoom\"]>[\"liveRoomUserInfo\"]>[\"liveRoom\"],\n): string | null {\n try {\n const raw = liveRoom?.streamData?.pull_data?.stream_data\n if (!raw) return null\n const parsed = JSON.parse(raw) as Record<string, unknown>\n const data = (parsed as Record<string, unknown>)?.data as Record<string, unknown> | undefined\n if (!data) return null\n\n // Try all known quality keys, preferring higher quality.\n // FLV is preferred (lower latency); HLS is the fallback.\n const qualities = [\"origin\", \"fhd\", \"uhd\", \"hd\", \"sd\", \"ld\"]\n for (const q of qualities) {\n const entry = data[q] as { main?: { flv?: string; hls?: string } } | undefined\n // Prefer FLV over HLS when both are available\n const url = entry?.main?.flv ?? entry?.main?.hls\n if (url) return url\n }\n return null\n } catch {\n return null\n }\n}\n\n/**\n * Brute-force recursive search for a stream URL anywhere in a JSON value.\n * Survives TikTok changing key names or nesting structure.\n *\n * Prefers FLV over HLS when both are present in the response.\n *\n * Inspired by PR #430 (Michele0303/tiktok-live-recorder).\n */\nexport function findStreamUrlRecursively(obj: unknown): string | null {\n // Collect all candidate URLs with their preference\n const flvUrls: string[] = []\n const m3u8Urls: string[] = []\n\n function walk(value: unknown): void {\n if (typeof value === \"string\") {\n // Direct URL match\n if (\n (value.startsWith(\"http://\") || value.startsWith(\"https://\")) &&\n (value.includes(\".flv\") || value.includes(\".m3u8\"))\n ) {\n if (value.includes(\".flv\")) {\n flvUrls.push(value)\n } else {\n m3u8Urls.push(value)\n }\n return\n }\n // JSON-encoded string — parse and recurse\n if (value.startsWith(\"{\") || value.startsWith(\"[\")) {\n try {\n walk(JSON.parse(value))\n } catch {\n // skip\n }\n }\n return\n }\n\n if (value && typeof value === \"object\") {\n if (Array.isArray(value)) {\n for (const item of value) {\n walk(item)\n }\n } else {\n for (const val of Object.values(value as Record<string, unknown>)) {\n walk(val)\n }\n }\n }\n }\n\n walk(obj)\n\n // Prefer FLV (lower latency) over HLS\n if (flvUrls.length > 0) return flvUrls[0] as string\n if (m3u8Urls.length > 0) return m3u8Urls[0] as string\n return null\n}\n"],"mappings":";;;;AAoCA,SAAgB,iBAAiB,MAAgC;CAC/D,MAAM,QAAQ,KAAK,MAAM,sEAAsE;CAC/F,IAAI,CAAC,QAAQ,IAAI,OAAO;CACxB,IAAI;EACF,OAAO,KAAK,MAAM,MAAM,EAAE;CAC5B,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;;;;;;;;AAeA,SAAgB,6BAA6B,MAG3C;CACA,MAAM,QAAQ,KAAK,MACjB,8FACF;CACA,IAAI,CAAC,QAAQ,IAAI,OAAO;EAAE,QAAQ;EAAM,QAAQ;CAAK;CACrD,IAAI;EACF,MAAM,OAAO,KAAK,MAAM,MAAM,EAAE;EAGhC,MAAM,SAFS,KAAiC,qBAAqB,KAAA,GAC1C,sBAAA,EACF,UAAU;EAGnC,OAAO;GAAE,QAFM,MAAM,KAAK,OAAO,KA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QAAQ,SAAS,GAAG,OAAO,QAAQ;CACvC,IAAI,SAAS,SAAS,GAAG,OAAO,SAAS;CACzC,OAAO;AACT"}
1
+ {"version":3,"file":"parse.mjs","names":[],"sources":["../../../src/io/tiktok/parse.ts"],"sourcesContent":["export interface SigiState {\n LiveRoom?: {\n liveRoomStatus?: number\n liveRoomUserInfo?: {\n user?: {\n id?: string | number\n roomId?: string | number\n }\n liveRoom?: {\n status?: number // 2 = live, 4 = offline\n title?: string\n startTime?: number\n streamData?: {\n pull_data?: {\n stream_data?: string // JSON string with FLV/HLS URLs\n }\n }\n }\n }\n }\n UserModule?: {\n users?: {\n [username: string]: {\n id?: string // numeric user ID\n uniqueId?: string\n roomId?: string | { id: string }\n }\n }\n }\n}\n\n// ─── HTML parsing ──────────────────────────────────────────\n\n/** Pull a `<script id=\"…\" type=\"application/json\">` block out of the page. */\nfunction embeddedJson(html: string, marker: RegExp): Record<string, unknown> | null {\n const match = html.match(marker)\n if (!match?.[1]) return null\n try {\n return JSON.parse(match[1]) as Record<string, unknown>\n } catch {\n return null\n }\n}\n\n/**\n * @public Exported for testing.\n */\nexport function extractSigiState(html: string): SigiState | null {\n return embeddedJson(\n html,\n /<script\\s+id=\"SIGI_STATE\"\\s+type=\"application\\/json\">(.*?)<\\/script>/,\n ) as SigiState | null\n}\n\n/**\n * Extract the numeric user ID and optional room ID from TikTok's new\n * page structure (__UNIVERSAL_DATA_FOR_REHYDRATION__).\n *\n * The profile page (/@user) includes \"webapp.user-detail\" which\n * contains the user's numeric ID. When the user is live, the roomId\n * is also embedded here.\n *\n * Returns { userId, roomId } where userId is always set when the data\n * is found, and roomId is set only when the user is currently live.\n *\n * @public Exported for testing and fixture capture.\n */\nexport function extractUserFromUniversalData(html: string): {\n userId: string | null\n roomId: string | null\n} {\n const data = embeddedJson(\n html,\n /<script\\s+id=\"__UNIVERSAL_DATA_FOR_REHYDRATION__\"\\s+type=\"application\\/json\">(.*?)<\\/script>/,\n )\n if (!data) return { userId: null, roomId: null }\n const scope = (data.__DEFAULT_SCOPE__ ?? data) as Record<string, unknown>\n const userDetail = scope[\"webapp.user-detail\"] as\n | { userInfo?: { user?: { id?: unknown; roomId?: unknown } } }\n | undefined\n const user = userDetail?.userInfo?.user\n return {\n userId: user?.id ? String(user.id) : null,\n roomId: user?.roomId ? String(user.roomId) : null,\n }\n}\n\n// ─── Stream URL extraction ─────────────────────────────────\n\n/**\n * Fast-path: extract stream URL from the known SIGI_STATE location.\n * This covers ~95% of cases without needing a full recursive search.\n *\n * Prefers FLV (lower latency) over HLS/other protocols.\n */\nexport function extractStreamUrlFast(\n liveRoom: NonNullable<NonNullable<SigiState[\"LiveRoom\"]>[\"liveRoomUserInfo\"]>[\"liveRoom\"],\n): string | null {\n try {\n const raw = liveRoom?.streamData?.pull_data?.stream_data\n if (!raw) return null\n const parsed = JSON.parse(raw) as {\n data?: Record<string, { main?: { flv?: string; hls?: string } }>\n }\n const data = parsed.data\n if (!data) return null\n\n // Try all known quality keys, preferring higher quality.\n // FLV is preferred (lower latency); HLS is the fallback.\n const qualities = [\"origin\", \"fhd\", \"uhd\", \"hd\", \"sd\", \"ld\"]\n for (const q of qualities) {\n const entry = data[q]\n // Prefer FLV over HLS when both are available\n const url = entry?.main?.flv ?? entry?.main?.hls\n if (url) return url\n }\n return null\n } catch {\n return null\n }\n}\n\n/**\n * Brute-force recursive search for a stream URL anywhere in a JSON value.\n * Survives TikTok changing key names or nesting structure.\n *\n * Prefers FLV over HLS when both are present in the response.\n *\n * Inspired by PR #430 (Michele0303/tiktok-live-recorder).\n */\nexport function findStreamUrlRecursively(obj: unknown): string | null {\n // First FLV wins; HLS is only a fallback.\n let flv: string | null = null\n let hls: string | null = null\n\n function walk(value: unknown): void {\n if (typeof value === \"string\") {\n if (value.startsWith(\"http://\") || value.startsWith(\"https://\")) {\n if (value.includes(\".flv\")) flv ??= value\n else if (value.includes(\".m3u8\")) hls ??= value\n return\n }\n // JSON-encoded string — parse and recurse\n if (value.startsWith(\"{\") || value.startsWith(\"[\")) {\n try {\n walk(JSON.parse(value))\n } catch {\n // skip\n }\n }\n return\n }\n\n if (value && typeof value === \"object\") {\n for (const val of Object.values(value as Record<string, unknown>)) walk(val)\n }\n }\n\n walk(obj)\n return flv ?? hls\n}\n"],"mappings":";;AAkCA,SAAS,aAAa,MAAc,QAAgD;CAClF,MAAM,QAAQ,KAAK,MAAM,MAAM;CAC/B,IAAI,CAAC,QAAQ,IAAI,OAAO;CACxB,IAAI;EACF,OAAO,KAAK,MAAM,MAAM,EAAE;CAC5B,QAAQ;EACN,OAAO;CACT;AACF;;;;AAKA,SAAgB,iBAAiB,MAAgC;CAC/D,OAAO,aACL,MACA,sEACF;AACF;;;;;;;;;;;;;;AAeA,SAAgB,6BAA6B,MAG3C;CACA,MAAM,OAAO,aACX,MACA,8FACF;CACA,IAAI,CAAC,MAAM,OAAO;EAAE,QAAQ;EAAM,QAAQ;CAAK;CAK/C,MAAM,QAJS,KAAK,qBAAqB,KAAA,CAChB,qBAGF,EAAE,UAAU;CACnC,OAAO;EACL,QAAQ,MAAM,KAAK,OAAO,KAAK,EAAE,IAAI;EACrC,QAAQ,MAAM,SAAS,OAAO,KAAK,MAAM,IAAI;CAC/C;AACF;;;;;;;AAUA,SAAgB,qBACd,UACe;CACf,IAAI;EACF,MAAM,MAAM,UAAU,YAAY,WAAW;EAC7C,IAAI,CAAC,KAAK,OAAO;EAIjB,MAAM,OAHS,KAAK,MAAM,GAGR,CAAC,CAAC;EACpB,IAAI,CAAC,MAAM,OAAO;EAKlB,KAAK,MAAM,KAAK;GADG;GAAU;GAAO;GAAO;GAAM;GAAM;EAC/B,GAAG;GACzB,MAAM,QAAQ,KAAK;GAEnB,MAAM,MAAM,OAAO,MAAM,OAAO,OAAO,MAAM;GAC7C,IAAI,KAAK,OAAO;EAClB;EACA,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;;;AAUA,SAAgB,yBAAyB,KAA6B;CAEpE,IAAI,MAAqB;CACzB,IAAI,MAAqB;CAEzB,SAAS,KAAK,OAAsB;EAClC,IAAI,OAAO,UAAU,UAAU;GAC7B,IAAI,MAAM,WAAW,SAAS,KAAK,MAAM,WAAW,UAAU,GAAG;IAC/D,IAAI,MAAM,SAAS,MAAM,GAAG,QAAQ;SAC/B,IAAI,MAAM,SAAS,OAAO,GAAG,QAAQ;IAC1C;GACF;GAEA,IAAI,MAAM,WAAW,GAAG,KAAK,MAAM,WAAW,GAAG,GAC/C,IAAI;IACF,KAAK,KAAK,MAAM,KAAK,CAAC;GACxB,QAAQ,CAER;GAEF;EACF;EAEA,IAAI,SAAS,OAAO,UAAU,UAC5B,KAAK,MAAM,OAAO,OAAO,OAAO,KAAgC,GAAG,KAAK,GAAG;CAE/E;CAEA,KAAK,GAAG;CACR,OAAO,OAAO;AAChB"}
@@ -3,24 +3,21 @@ import { findStreamUrlRecursively } from "./parse.mjs";
3
3
  const WEBCAST_BASE = "https://webcast.tiktok.com";
4
4
  function createWebcastApi(http, debug, signal) {
5
5
  /**
6
- * Shared boilerplate for Webcast room/info API calls.
7
- * Handles URL construction, HTTP GET, JSON parsing, and error handling.
8
- * Room-gate refusals (status_code 4003110) are reported to the caller
9
- * instead of being collapsed into null; callers map failures.
10
- * The caller provides an extractor for the response data.
6
+ * GET → JSON with the contract every Webcast call shares: gate refusals
7
+ * (status_code 4003110) and transport failures come back as `{ ok: false }`
8
+ * instead of collapsing into null. `statusCode: 0` = threw before a status.
11
9
  */
12
- async function fetchFromRoomApi(roomId, extract) {
10
+ async function fetchJson(url, label, extract) {
13
11
  try {
14
- const url = `${WEBCAST_BASE}/webcast/room/info/?aid=1988&room_id=${roomId}&type=live`;
15
12
  const res = await http.get(url, signal);
16
- debug(`fetchFromRoomApi: roomId=${roomId} status=${res.status}, ok=${res.ok}`);
13
+ debug(`${label} status=${res.status}, ok=${res.ok}`);
17
14
  if (!res.ok) return {
18
15
  ok: false,
19
16
  statusCode: res.status,
20
17
  body: ""
21
18
  };
22
19
  const text = await res.text();
23
- debug(`fetchFromRoomApi: roomId=${roomId} returned ${text.length} bytes`);
20
+ debug(`${label} returned ${text.length} bytes`);
24
21
  if (text.length === 0) return {
25
22
  ok: true,
26
23
  value: null
@@ -43,32 +40,21 @@ function createWebcastApi(http, debug, signal) {
43
40
  };
44
41
  }
45
42
  }
43
+ async function fetchFromRoomApi(roomId, extract) {
44
+ return fetchJson(`${WEBCAST_BASE}/webcast/room/info/?aid=1988&room_id=${roomId}&type=live`, `fetchFromRoomApi: roomId=${roomId}`, extract);
45
+ }
46
46
  /**
47
- * Check if a room is currently alive using the lightweight
48
- * /webcast/room/check_alive/ endpoint.
49
- *
50
- * This is faster and cheaper than fetching the full room/info response.
51
- * Returns `true` if the room is live, `false` otherwise (including errors).
47
+ * Lightweight liveness probe: cheaper than the full room/info response.
48
+ * Failures read as `false`.
52
49
  *
53
50
  * Endpoint: /webcast/room/check_alive/?aid=1988&region=CH&room_ids={id}&user_is_login=true
54
51
  * Response: { "data": [{ "alive": true/false, "room_id": "..." }] }
55
52
  */
56
53
  async function fetchCheckAlive(roomId) {
57
- try {
58
- const url = `${WEBCAST_BASE}/webcast/room/check_alive/?aid=1988&region=CH&room_ids=${roomId}&user_is_login=true`;
59
- const res = await http.get(url, signal);
60
- debug(`fetchCheckAlive: roomId=${roomId} status=${res.status}, ok=${res.ok}`);
61
- if (!res.ok) return false;
62
- const text = await res.text();
63
- debug(`fetchCheckAlive: roomId=${roomId} returned ${text.length} bytes`);
64
- if (text.length === 0) return false;
65
- const alive = (JSON.parse(text)?.data)?.[0]?.alive === true;
66
- debug(`fetchCheckAlive: roomId=${roomId} alive=${alive}`);
67
- return alive;
68
- } catch (err) {
69
- debug(`fetchCheckAlive: roomId=${roomId} error — ${err instanceof Error ? err.message : String(err)}`);
70
- return false;
71
- }
54
+ const res = await fetchJson(`${WEBCAST_BASE}/webcast/room/check_alive/?aid=1988&region=CH&room_ids=${roomId}&user_is_login=true`, `fetchCheckAlive: roomId=${roomId}`, (data) => data.data?.[0]?.alive === true);
55
+ const alive = res.ok && res.value === true;
56
+ debug(`fetchCheckAlive: roomId=${roomId} alive=${alive}`);
57
+ return alive;
72
58
  }
73
59
  /**
74
60
  * Resolve a 4003110 room-gate refusal via check_alive: the room is live
@@ -1 +1 @@
1
- {"version":3,"file":"webcast.mjs","names":[],"sources":["../../../src/io/tiktok/webcast.ts"],"sourcesContent":["import type { RoomRef, StreamRef } from \"../../core/verdict\"\nimport type { HttpClient } from \"../http\"\nimport { findStreamUrlRecursively } from \"./parse\"\n\nconst WEBCAST_BASE = \"https://webcast.tiktok.com\"\n\n/**\n * Discriminated room/info result: refusals (notably status_code 4003110)\n * and transport failures surface as `{ ok: false }` instead of null.\n * `statusCode: 0` means the request threw before a status was read.\n */\nexport type RoomApiResult<T> =\n | { ok: true; value: T | null }\n | { ok: false; statusCode: number; body: string }\n\n/** Authoritative room/info facts: the room plus its stream URL when present. */\nexport interface RoomFacts {\n readonly room: RoomRef\n readonly stream: StreamRef | null\n}\n\n/** What discovery sources consume. `createWebcastApi` is the only implementation. */\nexport interface WebcastReader {\n fetchFromRoomApi: <T>(\n roomId: string,\n extract: (data: Record<string, unknown>) => T | null,\n ) => Promise<RoomApiResult<T>>\n fetchCheckAlive: (roomId: string) => Promise<boolean>\n fetchStreamUrlFromApi: (roomId: string) => Promise<RoomApiResult<string>>\n /** room/info as domain facts; 4003110 comes back as `{ ok: false }`. */\n roomInfo: (roomId: string) => Promise<RoomApiResult<RoomFacts>>\n /** Resolve a 4003110 refusal: alive → restricted candidate, else offline. */\n refusedRoom: (roomId: string, title: string | null) => Promise<RoomRef>\n}\n\nexport function createWebcastApi(\n http: HttpClient,\n debug: (msg: string) => void,\n signal?: AbortSignal,\n): WebcastReader {\n /**\n * Shared boilerplate for Webcast room/info API calls.\n * Handles URL construction, HTTP GET, JSON parsing, and error handling.\n * Room-gate refusals (status_code 4003110) are reported to the caller\n * instead of being collapsed into null; callers map failures.\n * The caller provides an extractor for the response data.\n */\n async function fetchFromRoomApi<T>(\n roomId: string,\n extract: (data: Record<string, unknown>) => T | null,\n ): Promise<RoomApiResult<T>> {\n try {\n const url = `${WEBCAST_BASE}/webcast/room/info/?aid=1988&room_id=${roomId}&type=live`\n const res = await http.get(url, signal)\n debug(`fetchFromRoomApi: roomId=${roomId} status=${res.status}, ok=${res.ok}`)\n if (!res.ok) return { ok: false, statusCode: res.status, body: \"\" }\n\n const text = await res.text()\n debug(`fetchFromRoomApi: roomId=${roomId} returned ${text.length} bytes`)\n if (text.length === 0) return { ok: true, value: null }\n\n const data = JSON.parse(text) as Record<string, unknown>\n\n // status_code 4003110 = age-protected/restricted room: report it\n if ((data as { status_code?: unknown }).status_code === 4003110) {\n return { ok: false, statusCode: 4003110, body: text }\n }\n\n return { ok: true, value: extract(data) }\n } catch {\n // statusCode 0 = transport/parse failure before a status was available.\n return { ok: false, statusCode: 0, body: \"\" }\n }\n }\n\n /**\n * Check if a room is currently alive using the lightweight\n * /webcast/room/check_alive/ endpoint.\n *\n * This is faster and cheaper than fetching the full room/info response.\n * Returns `true` if the room is live, `false` otherwise (including errors).\n *\n * Endpoint: /webcast/room/check_alive/?aid=1988&region=CH&room_ids={id}&user_is_login=true\n * Response: { \"data\": [{ \"alive\": true/false, \"room_id\": \"...\" }] }\n */\n async function fetchCheckAlive(roomId: string): Promise<boolean> {\n try {\n const url = `${WEBCAST_BASE}/webcast/room/check_alive/?aid=1988&region=CH&room_ids=${roomId}&user_is_login=true`\n const res = await http.get(url, signal)\n debug(`fetchCheckAlive: roomId=${roomId} status=${res.status}, ok=${res.ok}`)\n if (!res.ok) return false\n\n const text = await res.text()\n debug(`fetchCheckAlive: roomId=${roomId} returned ${text.length} bytes`)\n if (text.length === 0) return false\n\n const data = JSON.parse(text) as Record<string, unknown>\n const items = data?.data as Array<Record<string, unknown>> | undefined\n const alive = items?.[0]?.alive === true\n debug(`fetchCheckAlive: roomId=${roomId} alive=${alive}`)\n return alive\n } catch (err) {\n debug(\n `fetchCheckAlive: roomId=${roomId} error — ${err instanceof Error ? err.message : String(err)}`,\n )\n return false\n }\n }\n\n /**\n * Resolve a 4003110 room-gate refusal via check_alive: the room is live\n * (restricted) when alive, offline otherwise. Single home for this mapping.\n */\n async function refusedRoom(roomId: string, title: string | null): Promise<RoomRef> {\n debug(`refusedRoom: room/info refused roomId=${roomId} (status_code 4003110)`)\n const live = await fetchCheckAlive(roomId)\n return { id: roomId, title, live }\n }\n\n /**\n * Fetch room/info as domain facts. Requires a known roomId. A 4003110\n * refusal stays `{ ok: false, statusCode: 4003110 }` for the caller to map\n * via `refusedRoom`.\n */\n async function roomInfo(roomId: string): Promise<RoomApiResult<RoomFacts>> {\n const res = await fetchFromRoomApi<Record<string, unknown>>(\n roomId,\n (data) => (data as { data?: Record<string, unknown> }).data ?? null,\n )\n if (!res.ok) return res\n const roomData = res.value\n if (!roomData) return { ok: true, value: null }\n\n const title = (roomData.title as string | undefined) ?? null\n const streamUrl = findStreamUrlRecursively(roomData)\n return {\n ok: true,\n value: {\n room: { id: roomId, title, live: (roomData.status ?? 4) === 2 },\n stream: streamUrl ? { url: streamUrl } : null,\n },\n }\n }\n\n /**\n * Fetch stream URL from the Webcast API.\n * Covers cases where SIGI_STATE doesn't include stream data.\n * Refusals (4003110) and transport failures are reported so callers\n * can distinguish restricted rooms from missing URLs.\n */\n async function fetchStreamUrlFromApi(roomId: string): Promise<RoomApiResult<string>> {\n return fetchFromRoomApi(roomId, (data) => findStreamUrlRecursively(data))\n }\n\n return {\n fetchFromRoomApi,\n fetchCheckAlive,\n fetchStreamUrlFromApi,\n roomInfo,\n refusedRoom,\n }\n}\n"],"mappings":";;AAIA,MAAM,eAAe;AA+BrB,SAAgB,iBACd,MACA,OACA,QACe;;;;;;;;CAQf,eAAe,iBACb,QACA,SAC2B;EAC3B,IAAI;GACF,MAAM,MAAM,GAAG,aAAa,uCAAuC,OAAO;GAC1E,MAAM,MAAM,MAAM,KAAK,IAAI,KAAK,MAAM;GACtC,MAAM,4BAA4B,O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AO;GAAE,IAAI;GAAQ;GAAO,MAAA,MADT,gBAAgB,MAAM;EACR;CACnC;;;;;;CAOA,eAAe,SAAS,QAAmD;EACzE,MAAM,MAAM,MAAM,iBAChB,SACC,SAAU,KAA4C,QAAQ,IACjE;EACA,IAAI,CAAC,IAAI,IAAI,OAAO;EACpB,MAAM,WAAW,IAAI;EACrB,IAAI,CAAC,UAAU,OAAO;GAAE,IAAI;GAAM,OAAO;EAAK;EAE9C,MAAM,QAAS,SAAS,SAAgC;EACxD,MAAM,YAAY,yBAAyB,QAAQ;EACnD,OAAO;GACL,IAAI;GACJ,OAAO;IACL,MAAM;KAAE,IAAI;KAAQ;KAAO,OAAO,SAAS,UAAU,OAAO;IAAE;IAC9D,QAAQ,YAAY,EAAE,KAAK,UAAU,IAAI;GAC3C;EACF;CACF;;;;;;;CAQA,eAAe,sBAAsB,QAAgD;EACnF,OAAO,iBAAiB,SAAS,SAAS,yBAAyB,IAAI,CAAC;CAC1E;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;CACF;AACF"}
1
+ {"version":3,"file":"webcast.mjs","names":[],"sources":["../../../src/io/tiktok/webcast.ts"],"sourcesContent":["import type { RoomRef, StreamRef } from \"../../core/verdict\"\nimport type { HttpClient } from \"../http\"\nimport { findStreamUrlRecursively } from \"./parse\"\n\nconst WEBCAST_BASE = \"https://webcast.tiktok.com\"\n\n/**\n * Discriminated room/info result: refusals (notably status_code 4003110)\n * and transport failures surface as `{ ok: false }` instead of null.\n * `statusCode: 0` means the request threw before a status was read.\n */\nexport type RoomApiResult<T> =\n | { ok: true; value: T | null }\n | { ok: false; statusCode: number; body: string }\n\n/** Authoritative room/info facts: the room plus its stream URL when present. */\nexport interface RoomFacts {\n readonly room: RoomRef\n readonly stream: StreamRef | null\n}\n\n/** What discovery sources consume. `createWebcastApi` is the only implementation. */\nexport interface WebcastReader {\n fetchFromRoomApi: <T>(\n roomId: string,\n extract: (data: Record<string, unknown>) => T | null,\n ) => Promise<RoomApiResult<T>>\n fetchCheckAlive: (roomId: string) => Promise<boolean>\n fetchStreamUrlFromApi: (roomId: string) => Promise<RoomApiResult<string>>\n /** room/info as domain facts; 4003110 comes back as `{ ok: false }`. */\n roomInfo: (roomId: string) => Promise<RoomApiResult<RoomFacts>>\n /** Resolve a 4003110 refusal: alive → restricted candidate, else offline. */\n refusedRoom: (roomId: string, title: string | null) => Promise<RoomRef>\n}\n\nexport function createWebcastApi(\n http: HttpClient,\n debug: (msg: string) => void,\n signal?: AbortSignal,\n): WebcastReader {\n /**\n * GET → JSON with the contract every Webcast call shares: gate refusals\n * (status_code 4003110) and transport failures come back as `{ ok: false }`\n * instead of collapsing into null. `statusCode: 0` = threw before a status.\n */\n async function fetchJson<T>(\n url: string,\n label: string,\n extract: (data: Record<string, unknown>) => T | null,\n ): Promise<RoomApiResult<T>> {\n try {\n const res = await http.get(url, signal)\n debug(`${label} status=${res.status}, ok=${res.ok}`)\n if (!res.ok) return { ok: false, statusCode: res.status, body: \"\" }\n\n const text = await res.text()\n debug(`${label} returned ${text.length} bytes`)\n if (text.length === 0) return { ok: true, value: null }\n\n const data = JSON.parse(text) as Record<string, unknown>\n // status_code 4003110 = age-protected/restricted room: report it\n if (data.status_code === 4003110) return { ok: false, statusCode: 4003110, body: text }\n\n return { ok: true, value: extract(data) }\n } catch {\n return { ok: false, statusCode: 0, body: \"\" }\n }\n }\n\n async function fetchFromRoomApi<T>(\n roomId: string,\n extract: (data: Record<string, unknown>) => T | null,\n ): Promise<RoomApiResult<T>> {\n return fetchJson(\n `${WEBCAST_BASE}/webcast/room/info/?aid=1988&room_id=${roomId}&type=live`,\n `fetchFromRoomApi: roomId=${roomId}`,\n extract,\n )\n }\n\n /**\n * Lightweight liveness probe: cheaper than the full room/info response.\n * Failures read as `false`.\n *\n * Endpoint: /webcast/room/check_alive/?aid=1988&region=CH&room_ids={id}&user_is_login=true\n * Response: { \"data\": [{ \"alive\": true/false, \"room_id\": \"...\" }] }\n */\n async function fetchCheckAlive(roomId: string): Promise<boolean> {\n const res = await fetchJson(\n `${WEBCAST_BASE}/webcast/room/check_alive/?aid=1988&region=CH&room_ids=${roomId}&user_is_login=true`,\n `fetchCheckAlive: roomId=${roomId}`,\n (data) => (data.data as Array<{ alive?: boolean }> | undefined)?.[0]?.alive === true,\n )\n const alive = res.ok && res.value === true\n debug(`fetchCheckAlive: roomId=${roomId} alive=${alive}`)\n return alive\n }\n\n /**\n * Resolve a 4003110 room-gate refusal via check_alive: the room is live\n * (restricted) when alive, offline otherwise. Single home for this mapping.\n */\n async function refusedRoom(roomId: string, title: string | null): Promise<RoomRef> {\n debug(`refusedRoom: room/info refused roomId=${roomId} (status_code 4003110)`)\n const live = await fetchCheckAlive(roomId)\n return { id: roomId, title, live }\n }\n\n /**\n * Fetch room/info as domain facts. Requires a known roomId. A 4003110\n * refusal stays `{ ok: false, statusCode: 4003110 }` for the caller to map\n * via `refusedRoom`.\n */\n async function roomInfo(roomId: string): Promise<RoomApiResult<RoomFacts>> {\n const res = await fetchFromRoomApi<Record<string, unknown>>(\n roomId,\n (data) => (data as { data?: Record<string, unknown> }).data ?? null,\n )\n if (!res.ok) return res\n const roomData = res.value\n if (!roomData) return { ok: true, value: null }\n\n const title = (roomData.title as string | undefined) ?? null\n const streamUrl = findStreamUrlRecursively(roomData)\n return {\n ok: true,\n value: {\n room: { id: roomId, title, live: (roomData.status ?? 4) === 2 },\n stream: streamUrl ? { url: streamUrl } : null,\n },\n }\n }\n\n /**\n * Fetch stream URL from the Webcast API.\n * Covers cases where SIGI_STATE doesn't include stream data.\n * Refusals (4003110) and transport failures are reported so callers\n * can distinguish restricted rooms from missing URLs.\n */\n async function fetchStreamUrlFromApi(roomId: string): Promise<RoomApiResult<string>> {\n return fetchFromRoomApi(roomId, (data) => findStreamUrlRecursively(data))\n }\n\n return {\n fetchFromRoomApi,\n fetchCheckAlive,\n fetchStreamUrlFromApi,\n roomInfo,\n refusedRoom,\n }\n}\n"],"mappings":";;AAIA,MAAM,eAAe;AA+Br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AAM,MAAM,MAAM,iBAChB,SACC,SAAU,KAA4C,QAAQ,IACjE;EACA,IAAI,CAAC,IAAI,IAAI,OAAO;EACpB,MAAM,WAAW,IAAI;EACrB,IAAI,CAAC,UAAU,OAAO;GAAE,IAAI;GAAM,OAAO;EAAK;EAE9C,MAAM,QAAS,SAAS,SAAgC;EACxD,MAAM,YAAY,yBAAyB,QAAQ;EACnD,OAAO;GACL,IAAI;GACJ,OAAO;IACL,MAAM;KAAE,IAAI;KAAQ;KAAO,OAAO,SAAS,UAAU,OAAO;IAAE;IAC9D,QAAQ,YAAY,EAAE,KAAK,UAAU,IAAI;GAC3C;EACF;CACF;;;;;;;CAQA,eAAe,sBAAsB,QAAgD;EACnF,OAAO,iBAAiB,SAAS,SAAS,yBAAyB,IAAI,CAAC;CAC1E;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;CACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zfadhli/tokrec",
3
- "version": "0.15.0",
3
+ "version": "0.16.0",
4
4
  "description": "Minimal TikTok live stream recorder — Bun + TypeScript",
5
5
  "type": "module",
6
6
  "main": "./dist/index.mjs",
package/src/app/config.ts CHANGED
@@ -16,7 +16,7 @@ export type CookieAuth = Record<string, string>
16
16
  export type LogLevel = "debug" | "info" | "warn" | "error"
17
17
 
18
18
  /**
19
- * Machine-readable reason for a LIVE status verdict — lives in `domain/verdict.ts`.
19
+ * Machine-readable reason for a LIVE status verdict — lives in `core/verdict.ts`.
20
20
  */
21
21
  export type { LiveReason } from "../core/verdict"
22
22
 
@@ -124,24 +124,10 @@ export interface RecorderEventHandler {
124
124
  }
125
125
 
126
126
  /** A `RecorderConfig` with every default applied — what the recorder runs on. */
127
- export interface ResolvedConfig {
128
- user: string
129
- outputDir: string
130
- interval: number
131
- duration: number
132
- proxy?: string
133
- cookiesPath?: string
134
- cookies?: CookieAuth
135
- logLevel: LogLevel
136
- logConsole: boolean
137
- segmentMinutes: number
138
- normalizeAudio: boolean
139
- normalizeLoudness: number
140
- normalizeCodec?: string
141
- normalizeBitrate?: string
142
- ratePerSecond: number
143
- debug: boolean
144
- }
127
+ export type ResolvedConfig = Required<
128
+ Omit<RecorderConfig, "proxy" | "cookies" | "cookiesPath" | "normalizeCodec" | "normalizeBitrate">
129
+ > &
130
+ Pick<RecorderConfig, "proxy" | "cookies" | "cookiesPath" | "normalizeCodec" | "normalizeBitrate">
145
131
 
146
132
  /** Apply defaults once, at the entry point; nothing downstream re-reads `??`. */
147
133
  export function resolveConfig(config: RecorderConfig): ResolvedConfig {
package/src/app/job.ts CHANGED
@@ -5,11 +5,11 @@
5
5
  */
6
6
 
7
7
  import { statSync, unlinkSync, utimesSync } from "node:fs"
8
- import { join, parse } from "node:path"
8
+ import { isAbsolute, join, parse } from "node:path"
9
+ import { type NormalizeOptions, type NormalizeResult, normalizeFile } from "peaknorm"
9
10
  import { TikTokError } from "../core/errors"
10
11
  import type { Logger } from "../core/log"
11
- import type { Converter } from "../io/media/convert"
12
- import type { AudioNormalizer } from "../io/media/normalize"
12
+ import type { MediaConverter } from "../io/media/ffmpeg"
13
13
  import type {
14
14
  ProgressEvent,
15
15
  RecordEvent,
@@ -25,10 +25,16 @@ export interface RecordingJob {
25
25
 
26
26
  export interface RecordingJobDeps {
27
27
  result: RecordedFile
28
- cfg: Pick<RecorderConfig, "segmentMinutes">
28
+ cfg: Pick<
29
+ RecorderConfig,
30
+ | "segmentMinutes"
31
+ | "normalizeAudio"
32
+ | "normalizeLoudness"
33
+ | "normalizeCodec"
34
+ | "normalizeBitrate"
35
+ >
29
36
  logger: Logger
30
- converter: Converter
31
- audioNormalizer: AudioNormalizer | null
37
+ converter: MediaConverter
32
38
  signal: AbortSignal
33
39
  emitRecord: (event: RecordEvent) => void
34
40
  emitProgress: (event: ProgressEvent) => void
@@ -75,12 +81,11 @@ async function run(deps: RecordingJobDeps): Promise<RecordedFile[]> {
75
81
  async function segment(deps: RecordingJobDeps): Promise<RecordedFile[]> {
76
82
  const { result, cfg, logger, signal } = deps
77
83
  const parsed = parse(result.file)
78
- const segmentTime = Math.max(1, (cfg.segmentMinutes ?? 20) * 60)
84
+ const segmentMinutes = cfg.segmentMinutes ?? 20
85
+ const segmentTime = Math.max(1, segmentMinutes * 60)
79
86
  const outputPattern = join(parsed.dir, `${parsed.name}_part%d.mp4`)
80
87
 
81
- logger.info(
82
- `Segmenting: ${parsed.base} → ${parsed.name}_partN.mp4 (${cfg.segmentMinutes ?? 20} min each)`,
83
- )
88
+ logger.info(`Segmenting: ${parsed.base} → ${parsed.name}_partN.mp4 (${segmentMinutes} min each)`)
84
89
  deps.setState({ state: "segmenting" })
85
90
  deps.emitRecord({
86
91
  phase: "segment",
@@ -100,7 +105,7 @@ async function segment(deps: RecordingJobDeps): Promise<RecordedFile[]> {
100
105
  return convert(deps)
101
106
  }
102
107
 
103
- const segments = parseSegmentList(listing, segmentTime)
108
+ const segments = parseSegmentList(listing, segmentTime, parsed.dir)
104
109
  if (segments.length === 0) {
105
110
  logger.warn("Segmenting produced no files — falling back to whole-file conversion")
106
111
  return convert(deps)
@@ -109,13 +114,6 @@ async function segment(deps: RecordingJobDeps): Promise<RecordedFile[]> {
109
114
  const fileMtimeMs = statSync(result.file).mtimeMs
110
115
  const recStartMs = fileMtimeMs - result.duration * 1000
111
116
 
112
- try {
113
- unlinkSync(result.file)
114
- logger.info(`Deleted original: ${parsed.base}`)
115
- } catch {
116
- logger.warn(`Could not delete original: ${parsed.base}`)
117
- }
118
-
119
117
  const files: RecordedFile[] = []
120
118
  for (let i = 0; i < segments.length; i++) {
121
119
  const seg = segments[i]
@@ -141,10 +139,17 @@ async function segment(deps: RecordingJobDeps): Promise<RecordedFile[]> {
141
139
 
142
140
  deps.emitRecord({ phase: "segment", status: "end", segments: files.length })
143
141
 
144
- if (deps.audioNormalizer) {
145
- for (const recorded of files) {
146
- await normalize(deps, recorded.file)
147
- }
142
+ // Only now that every part is on disk and readable is the crash-safe source
143
+ // expendable; an earlier unlink loses the recording if a part stat fails.
144
+ try {
145
+ unlinkSync(result.file)
146
+ logger.info(`Deleted original: ${parsed.base}`)
147
+ } catch {
148
+ logger.warn(`Could not delete original: ${parsed.base}`)
149
+ }
150
+
151
+ for (const recorded of files) {
152
+ await normalize(deps, recorded.file)
148
153
  }
149
154
 
150
155
  deps.setState({
@@ -174,7 +179,7 @@ async function convert(deps: RecordingJobDeps): Promise<RecordedFile[]> {
174
179
  }
175
180
  deps.emitRecord({ phase: "end", ...recorded })
176
181
 
177
- if (deps.audioNormalizer) await normalize(deps, mp4File)
182
+ await normalize(deps, mp4File)
178
183
 
179
184
  deps.emitRecord({
180
185
  phase: "convert",
@@ -188,10 +193,32 @@ async function convert(deps: RecordingJobDeps): Promise<RecordedFile[]> {
188
193
  }
189
194
 
190
195
  async function normalize(deps: RecordingJobDeps, file: string): Promise<void> {
191
- if (!deps.audioNormalizer) return
196
+ const { cfg, logger, signal } = deps
197
+ if (!cfg.normalizeAudio || signal.aborted) return
192
198
  deps.emitRecord({ phase: "normalize", status: "start", file })
199
+ logger.info(`Normalizing audio: ${file}`)
193
200
  try {
194
- const result = await deps.audioNormalizer.normalize(file)
201
+ const opts: NormalizeOptions = {
202
+ loudness: cfg.normalizeLoudness ?? -14,
203
+ backup: false,
204
+ // Post-processing outlives a user stop only until POST_REMUX_GRACE_MS;
205
+ // forwarding the signal is what lets that cap bound a loudnorm pass.
206
+ signal,
207
+ onFileProgress: (f, percent, phase) =>
208
+ deps.emitProgress({
209
+ kind: "normalize",
210
+ file: f,
211
+ percent,
212
+ phase: phase as "analyzing" | "normalizing",
213
+ }),
214
+ }
215
+ if (cfg.normalizeCodec !== undefined) opts.audioCodec = cfg.normalizeCodec
216
+ if (cfg.normalizeBitrate !== undefined) opts.audioBitrate = cfg.normalizeBitrate
217
+ const result: NormalizeResult = await normalizeFile(file, opts)
218
+ // peaknorm resolves (not rejects) when its signal aborts, leaving the file
219
+ // untouched — so an abort must not be reported as a completed normalize.
220
+ if (signal.aborted) return
221
+ logger.info(`Audio normalized: ${result.output}`)
195
222
  deps.emitRecord({
196
223
  phase: "normalize",
197
224
  status: "done",
@@ -199,7 +226,10 @@ async function normalize(deps: RecordingJobDeps, file: string): Promise<void> {
199
226
  output: result.output,
200
227
  })
201
228
  } catch (err) {
229
+ // A stop-time abort is not a normalization failure — say nothing.
230
+ if (signal.aborted) return
202
231
  const message = err instanceof Error ? err.message : String(err)
232
+ logger.error(`Audio normalization failed: ${message}`)
203
233
  deps.emitRecord({
204
234
  phase: "normalize",
205
235
  status: "error",
@@ -212,14 +242,18 @@ async function normalize(deps: RecordingJobDeps, file: string): Promise<void> {
212
242
  function parseSegmentList(
213
243
  listing: string,
214
244
  fallbackDuration: number,
245
+ dir: string,
215
246
  ): { file: string; duration: number }[] {
216
247
  return listing
217
248
  .split("\n")
218
249
  .map((line) => line.trim())
219
250
  .filter((line) => line.length > 0)
220
251
  .flatMap((line) => {
221
- const [file, start, end] = line.split(",").map((field) => field.replace(/^"|"$/g, ""))
222
- if (!file) return []
252
+ const [name, start, end] = line.split(",").map((field) => field.replace(/^"|"$/g, ""))
253
+ if (!name) return []
254
+ // ffmpeg lists segment basenames even when handed an absolute pattern,
255
+ // so resolve against the directory the recording lives in.
256
+ const file = isAbsolute(name) ? name : join(dir, name)
223
257
  const duration = Number(end) - Number(start)
224
258
  return [
225
259
  { file, duration: Number.isFinite(duration) && duration > 0 ? duration : fallbackDuration },
package/src/app/logger.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  /**
2
2
  * Logger — rotating file + console with levels.
3
- * Zero-dependency minimal implementation (~60 lines).
4
3
  */
5
4
 
6
5
  import { appendFileSync, existsSync, mkdirSync, renameSync, statSync, writeFileSync } from "node:fs"
@@ -96,18 +95,12 @@ export function createLogger(opts: {
96
95
  const ts = new Date().toISOString()
97
96
  const suffix = args.length > 0 ? ` ${args.map((a) => String(a)).join(" ")}` : ""
98
97
  const line = `[${ts}] [${level.toUpperCase()}] ${msg}${suffix}`
99
- const formatted = `[${ts}] [${level.toUpperCase()}] ${msg}${suffix}`
100
98
 
101
- // Console (optional — can be suppressed for file-only logging)
102
99
  if (showConsole) {
103
- if (level === "error") {
104
- process.stderr.write(`${LEVEL_COLORS[level]}${formatted}${RESET}\n`)
105
- } else {
106
- process.stdout.write(`${LEVEL_COLORS[level]}${formatted}${RESET}\n`)
107
- }
100
+ const sink = level === "error" ? process.stderr : process.stdout
101
+ sink.write(`${LEVEL_COLORS[level]}${line}${RESET}\n`)
108
102
  }
109
103
 
110
- // File
111
104
  try {
112
105
  rotateIfNeeded()
113
106
  appendFileSync(logFile, `${line}\n`, "utf-8")
@@ -116,18 +109,11 @@ export function createLogger(opts: {
116
109
  }
117
110
  }
118
111
 
119
- return {
120
- debug: (msg, ...args) => {
121
- if (LEVEL_ORDER.debug >= LEVEL_ORDER[level]) write("debug", msg, args)
122
- },
123
- info: (msg, ...args) => {
124
- if (LEVEL_ORDER.info >= LEVEL_ORDER[level]) write("info", msg, args)
125
- },
126
- warn: (msg, ...args) => {
127
- if (LEVEL_ORDER.warn >= LEVEL_ORDER[level]) write("warn", msg, args)
128
- },
129
- error: (msg, ...args) => {
130
- if (LEVEL_ORDER.error >= LEVEL_ORDER[level]) write("error", msg, args)
131
- },
132
- }
112
+ const log =
113
+ (lvl: LogLevel) =>
114
+ (msg: string, ...args: unknown[]): void => {
115
+ if (LEVEL_ORDER[lvl] >= LEVEL_ORDER[level]) write(lvl, msg, args)
116
+ }
117
+
118
+ return { debug: log("debug"), info: log("info"), warn: log("warn"), error: log("error") }
133
119
  }
package/src/app/loop.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  * Polling monitor — calls a tick function on a configurable interval.
3
3
  * Fires the first tick immediately, then every N minutes.
4
4
  *
5
- * One external `AbortSignal` (the session's AbortScope) interrupts both the
5
+ * One external `AbortSignal` (the recorder's scope) interrupts both the
6
6
  * sleep and any in-flight tick; there is no private controller.
7
7
  */
8
8
 
@@ -15,17 +15,18 @@ function sleep(ms: number, signal?: AbortSignal): Promise<void> {
15
15
  resolve()
16
16
  return
17
17
  }
18
- const timer = setTimeout(resolve, ms)
19
- if (signal) {
20
- signal.addEventListener(
21
- "abort",
22
- () => {
23
- clearTimeout(timer)
24
- resolve()
25
- },
26
- { once: true },
27
- )
18
+
19
+ let timer: ReturnType<typeof setTimeout>
20
+ // One exit path: clear the timer, drop the listener, resolve. Without the
21
+ // removal a long-lived signal accumulates one listener per poll interval.
22
+ const done = (): void => {
23
+ clearTimeout(timer)
24
+ signal?.removeEventListener("abort", done)
25
+ resolve()
28
26
  }
27
+
28
+ timer = setTimeout(done, ms)
29
+ signal?.addEventListener("abort", done, { once: true })
29
30
  })
30
31
  }
31
32