@zfadhli/tokrec 0.15.2 → 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 (56) hide show
  1. package/dist/app/config.mjs.map +1 -1
  2. package/dist/app/job.mjs +39 -17
  3. package/dist/app/job.mjs.map +1 -1
  4. package/dist/app/logger.mjs +8 -16
  5. package/dist/app/logger.mjs.map +1 -1
  6. package/dist/app/loop.mjs +6 -3
  7. package/dist/app/loop.mjs.map +1 -1
  8. package/dist/app/recorder.d.mts.map +1 -1
  9. package/dist/app/recorder.mjs +25 -29
  10. package/dist/app/recorder.mjs.map +1 -1
  11. package/dist/core/plan.mjs.map +1 -1
  12. package/dist/core/verdict.d.mts +1 -1
  13. package/dist/core/verdict.mjs.map +1 -1
  14. package/dist/io/http.mjs +16 -24
  15. package/dist/io/http.mjs.map +1 -1
  16. package/dist/io/media/download.mjs +1 -1
  17. package/dist/io/media/ffmpeg.mjs +52 -6
  18. package/dist/io/media/ffmpeg.mjs.map +1 -1
  19. package/dist/io/tiktok/client.mjs +9 -12
  20. package/dist/io/tiktok/client.mjs.map +1 -1
  21. package/dist/io/tiktok/discovery/chain.mjs +14 -17
  22. package/dist/io/tiktok/discovery/chain.mjs.map +1 -1
  23. package/dist/io/tiktok/discovery/page.mjs +38 -52
  24. package/dist/io/tiktok/discovery/page.mjs.map +1 -1
  25. package/dist/io/tiktok/parse.mjs +24 -31
  26. package/dist/io/tiktok/parse.mjs.map +1 -1
  27. package/dist/io/tiktok/webcast.mjs +15 -29
  28. package/dist/io/tiktok/webcast.mjs.map +1 -1
  29. package/package.json +1 -1
  30. package/src/app/config.ts +5 -19
  31. package/src/app/job.ts +61 -27
  32. package/src/app/logger.ts +9 -23
  33. package/src/app/loop.ts +12 -11
  34. package/src/app/recorder.ts +44 -47
  35. package/src/core/plan.ts +1 -1
  36. package/src/core/verdict.ts +1 -1
  37. package/src/index.ts +1 -1
  38. package/src/io/http.ts +24 -49
  39. package/src/io/media/ffmpeg.ts +65 -7
  40. package/src/io/tiktok/client.ts +13 -24
  41. package/src/io/tiktok/discovery/chain.ts +15 -24
  42. package/src/io/tiktok/discovery/page.ts +51 -90
  43. package/src/io/tiktok/parse.ts +38 -48
  44. package/src/io/tiktok/webcast.ts +30 -41
  45. package/dist/app/abort.mjs +0 -14
  46. package/dist/app/abort.mjs.map +0 -1
  47. package/dist/app/events.mjs +0 -36
  48. package/dist/app/events.mjs.map +0 -1
  49. package/dist/io/media/convert.mjs +0 -60
  50. package/dist/io/media/convert.mjs.map +0 -1
  51. package/dist/io/media/normalize.mjs +0 -32
  52. package/dist/io/media/normalize.mjs.map +0 -1
  53. package/src/app/abort.ts +0 -18
  54. package/src/app/events.ts +0 -46
  55. package/src/io/media/convert.ts +0 -69
  56. package/src/io/media/normalize.ts +0 -64
@@ -6,14 +6,8 @@ import {
6
6
  extractUserFromUniversalData,
7
7
  findStreamUrlRecursively,
8
8
  } from "../parse"
9
- import {
10
- type Candidate,
11
- type DiscoverySource,
12
- fromRoomInfo,
13
- miss,
14
- type ResolveContext,
15
- withStream,
16
- } from "./chain"
9
+ import type { Candidate, DiscoverySource, ResolveContext } from "./chain"
10
+ import { fromRoomInfo, miss, withStream } from "./chain"
17
11
 
18
12
  /**
19
13
  * Page source: server-rendered SIGI_STATE first, then the async-loaded legacy
@@ -24,90 +18,63 @@ export function createPageSource(): DiscoverySource {
24
18
  return {
25
19
  id: "page",
26
20
  async find(ctx: ResolveContext): Promise<Candidate> {
27
- let sigi: SigiState | null = null
28
- let html = ""
29
- // A `failed` sub-step is not terminal: legacy + universal-data fallbacks
30
- // still get their chance. It is returned only if nothing else hit.
21
+ const page = await ctx.fetchPage(ctx.user, "/live")
22
+ const html = page?.html ?? ""
23
+ ctx.debug(
24
+ page
25
+ ? `fetchLiveInfo: /live returned ${html.length} bytes (${page.baseUrl})`
26
+ : "fetchLiveInfo: all domains blocked for /live page",
27
+ )
28
+
29
+ // A `failed` sub-step is not terminal: later paths still get their chance.
30
+ // It is returned only if nothing else hit.
31
31
  let failure: Extract<Candidate, { kind: "failed" }> | null = null
32
- const take = (candidate: Candidate): Candidate | null => {
32
+ const attempt = async (pending: Promise<Candidate>): Promise<Candidate | null> => {
33
+ const candidate = await pending
33
34
  if (candidate.kind === "room" || candidate.kind === "denied") return candidate
34
35
  if (candidate.kind === "failed") failure ??= candidate
35
36
  return null
36
37
  }
37
38
 
38
- const page = await ctx.fetchPage(ctx.user, "/live")
39
- if (!page) {
40
- ctx.debug("fetchLiveInfo: all domains blocked for /live page")
41
- // Fall through to universal data / profile page fallback
42
- html = ""
43
- } else {
44
- html = page.html
45
- ctx.debug(
46
- `fetchLiveInfo: /live returned ${html.length} bytes (${page.baseUrl}), first 300: ${html.slice(0, 300).replace(/\n/g, "\\n")}`,
47
- )
48
-
49
- sigi = extractSigiState(html)
50
- ctx.debug(`fetchLiveInfo: SIGI_STATE ${sigi ? "found" : "not found"}`)
51
-
52
- if (sigi) {
53
- const liveRoom = sigi.LiveRoom?.liveRoomUserInfo?.liveRoom
54
- const userInfo = sigi.LiveRoom?.liveRoomUserInfo?.user
55
-
56
- ctx.debug(
57
- `fetchLiveInfo: liveRoom=${!!liveRoom}, userInfo=${!!userInfo}, userInfo.roomId=${userInfo?.roomId ?? "null"}`,
58
- )
59
-
60
- // ── Primary path: liveRoom is populated (server-rendered) ──
61
- if (liveRoom && userInfo?.roomId) {
62
- const room: RoomRef = {
63
- id: String(userInfo.roomId),
64
- title: liveRoom.title ?? null,
65
- live: liveRoom.status === 2, // 2 = live, 4 = offline
66
- }
67
- ctx.debug(
68
- `fetchLiveInfo: primary path — roomId=${room.id}, status=${liveRoom.status}, live=${room.live}`,
69
- )
70
- if (!room.live) return { kind: "room", room, stream: null, source: "sigi" }
39
+ const sigi: SigiState | null = page ? extractSigiState(html) : null
40
+ ctx.debug(`fetchLiveInfo: SIGI_STATE ${sigi ? "found" : "not found"}`)
41
+ const liveRoom = sigi?.LiveRoom?.liveRoomUserInfo?.liveRoom
42
+ const roomId = sigi?.LiveRoom?.liveRoomUserInfo?.user?.roomId
43
+ const id = roomId ? String(roomId) : null
71
44
 
72
- // Extract stream URL: try SIGI_STATE first, then Webcast API fallback
73
- const knownUrl = extractStreamUrlFast(liveRoom) ?? findStreamUrlRecursively(sigi)
74
- return withStream(ctx, room, "sigi", knownUrl)
75
- }
45
+ // 1. Server-rendered liveRoom wins — no extra request needed.
46
+ if (liveRoom && id) {
47
+ const room: RoomRef = {
48
+ id,
49
+ title: liveRoom.title ?? null,
50
+ live: liveRoom.status === 2, // 2 = live, 4 = offline
51
+ }
52
+ ctx.debug(`fetchLiveInfo: primary path — roomId=${room.id}, live=${room.live}`)
53
+ if (!room.live) return { kind: "room", room, stream: null, source: "sigi" }
54
+ const knownUrl = extractStreamUrlFast(liveRoom) ?? findStreamUrlRecursively(sigi)
55
+ return withStream(ctx, room, "sigi", knownUrl)
56
+ }
76
57
 
77
- // ── Fallback: userInfo has roomId, but liveRoom is async-loaded ──
78
- // TikTok may omit liveRoom from the server-rendered page and load it
79
- // via JavaScript. Query the Webcast API directly — it's authoritative.
80
- if (userInfo?.roomId) {
81
- const roomId = String(userInfo.roomId)
82
- ctx.debug(`fetchLiveInfo: userInfo fallback — roomId=${roomId}, querying Webcast API`)
83
- const found = take(await fromRoomInfo(ctx, roomId, "room-info"))
84
- ctx.debug(
85
- `fetchLiveInfo: Webcast API ${found ? "returned room info" : "returned null"}`,
86
- )
87
- if (found) return found
88
- }
58
+ // 2. roomId present but liveRoom async-loaded: the Webcast API is authoritative.
59
+ if (id) {
60
+ const found = await attempt(fromRoomInfo(ctx, id, "room-info"))
61
+ if (found) return found
62
+ }
89
63
 
90
- // ── Legacy fallback: async-loaded SIGI_STATE ──
91
- ctx.debug("fetchLiveInfo: trying legacy fallback (UserModule)")
92
- const legacy = take(await sigiLegacy(sigi, ctx))
93
- ctx.debug(`fetchLiveInfo: legacy fallback ${legacy ? "succeeded" : "returned null"}`)
94
- if (legacy) return legacy
95
- } // end if (sigi)
96
- } // end else (page loaded)
64
+ // 3. Legacy async-loaded SIGI_STATE.
65
+ if (sigi) {
66
+ const found = await attempt(sigiLegacy(sigi, ctx))
67
+ if (found) return found
68
+ }
97
69
 
98
- // ── Universal data from the already-fetched /live html ──
99
- // TikTok migrated from SIGI_STATE to __UNIVERSAL_DATA_FOR_REHYDRATION__.
100
- // The /live page may not have it, so try the main profile page.
101
- ctx.debug(`fetchLiveInfo: trying universal data fallback (html length ${html.length})`)
102
- const { roomId } = extractUserFromUniversalData(html)
103
- ctx.debug(`fetchLiveInfo: universal data roomId=${roomId ?? "null"}`)
104
- if (roomId) {
105
- const found = take(await fromRoomInfo(ctx, roomId, "room-info"))
106
- ctx.debug(
107
- `fetchLiveInfo: universal data Webcast API ${found ? "succeeded" : "returned null"}`,
108
- )
70
+ // 4. Universal data — SIGI_STATE's successor, from the already-fetched page.
71
+ const universalRoomId = extractUserFromUniversalData(html).roomId
72
+ ctx.debug(`fetchLiveInfo: universal data roomId=${universalRoomId ?? "null"}`)
73
+ if (universalRoomId) {
74
+ const found = await attempt(fromRoomInfo(ctx, universalRoomId, "room-info"))
109
75
  if (found) return found
110
76
  }
77
+
111
78
  return failure ?? miss("page: no room id")
112
79
  },
113
80
  }
@@ -122,16 +89,10 @@ export function createPageSource(): DiscoverySource {
122
89
  async function sigiLegacy(sigi: SigiState, ctx: ResolveContext): Promise<Candidate> {
123
90
  const isLive = sigi.LiveRoom?.liveRoomStatus === 2 // 2 = live
124
91
 
125
- // Try to get roomId from UserModule (usually populated even when LiveRoom is not)
126
- const userModule = sigi.UserModule?.users?.[ctx.user]
127
- let roomId: string | null = null
128
-
129
- if (userModule?.roomId) {
130
- roomId =
131
- typeof userModule.roomId === "object"
132
- ? String((userModule.roomId as { id: string }).id ?? "")
133
- : String(userModule.roomId)
134
- }
92
+ // UserModule is usually populated even when LiveRoom is not.
93
+ const owner = sigi.UserModule?.users?.[ctx.user]
94
+ const raw = owner?.roomId
95
+ const roomId = raw ? String(typeof raw === "object" ? (raw.id ?? "") : raw) : ""
135
96
 
136
97
  // No roomId available — treat as offline (room/enter was unreliable).
137
98
  if (!roomId) return miss("sigi-legacy: no roomId")
@@ -31,19 +31,27 @@ export interface SigiState {
31
31
 
32
32
  // ─── HTML parsing ──────────────────────────────────────────
33
33
 
34
- /**
35
- * @public Exported for testing.
36
- */
37
- export function extractSigiState(html: string): SigiState | null {
38
- const match = html.match(/<script\s+id="SIGI_STATE"\s+type="application\/json">(.*?)<\/script>/)
34
+ /** Pull a `<script id="…" type="application/json">` block out of the page. */
35
+ function embeddedJson(html: string, marker: RegExp): Record<string, unknown> | null {
36
+ const match = html.match(marker)
39
37
  if (!match?.[1]) return null
40
38
  try {
41
- return JSON.parse(match[1]) as SigiState
39
+ return JSON.parse(match[1]) as Record<string, unknown>
42
40
  } catch {
43
41
  return null
44
42
  }
45
43
  }
46
44
 
45
+ /**
46
+ * @public Exported for testing.
47
+ */
48
+ export function extractSigiState(html: string): SigiState | null {
49
+ return embeddedJson(
50
+ html,
51
+ /<script\s+id="SIGI_STATE"\s+type="application\/json">(.*?)<\/script>/,
52
+ ) as SigiState | null
53
+ }
54
+
47
55
  /**
48
56
  * Extract the numeric user ID and optional room ID from TikTok's new
49
57
  * page structure (__UNIVERSAL_DATA_FOR_REHYDRATION__).
@@ -61,20 +69,19 @@ export function extractUserFromUniversalData(html: string): {
61
69
  userId: string | null
62
70
  roomId: string | null
63
71
  } {
64
- const match = html.match(
72
+ const data = embeddedJson(
73
+ html,
65
74
  /<script\s+id="__UNIVERSAL_DATA_FOR_REHYDRATION__"\s+type="application\/json">(.*?)<\/script>/,
66
75
  )
67
- if (!match?.[1]) return { userId: null, roomId: null }
68
- try {
69
- const data = JSON.parse(match[1])
70
- const scope = (data as Record<string, unknown>).__DEFAULT_SCOPE__ ?? data
71
- const userDetail = scope?.["webapp.user-detail"]
72
- const user = userDetail?.userInfo?.user
73
- const userId = user?.id ? String(user.id) : null
74
- const roomId = user?.roomId ? String(user.roomId) : null
75
- return { userId, roomId }
76
- } catch {
77
- return { userId: null, roomId: null }
76
+ if (!data) return { userId: null, roomId: null }
77
+ const scope = (data.__DEFAULT_SCOPE__ ?? data) as Record<string, unknown>
78
+ const userDetail = scope["webapp.user-detail"] as
79
+ | { userInfo?: { user?: { id?: unknown; roomId?: unknown } } }
80
+ | undefined
81
+ const user = userDetail?.userInfo?.user
82
+ return {
83
+ userId: user?.id ? String(user.id) : null,
84
+ roomId: user?.roomId ? String(user.roomId) : null,
78
85
  }
79
86
  }
80
87
 
@@ -92,15 +99,17 @@ export function extractStreamUrlFast(
92
99
  try {
93
100
  const raw = liveRoom?.streamData?.pull_data?.stream_data
94
101
  if (!raw) return null
95
- const parsed = JSON.parse(raw) as Record<string, unknown>
96
- const data = (parsed as Record<string, unknown>)?.data as Record<string, unknown> | undefined
102
+ const parsed = JSON.parse(raw) as {
103
+ data?: Record<string, { main?: { flv?: string; hls?: string } }>
104
+ }
105
+ const data = parsed.data
97
106
  if (!data) return null
98
107
 
99
108
  // Try all known quality keys, preferring higher quality.
100
109
  // FLV is preferred (lower latency); HLS is the fallback.
101
110
  const qualities = ["origin", "fhd", "uhd", "hd", "sd", "ld"]
102
111
  for (const q of qualities) {
103
- const entry = data[q] as { main?: { flv?: string; hls?: string } } | undefined
112
+ const entry = data[q]
104
113
  // Prefer FLV over HLS when both are available
105
114
  const url = entry?.main?.flv ?? entry?.main?.hls
106
115
  if (url) return url
@@ -120,22 +129,15 @@ export function extractStreamUrlFast(
120
129
  * Inspired by PR #430 (Michele0303/tiktok-live-recorder).
121
130
  */
122
131
  export function findStreamUrlRecursively(obj: unknown): string | null {
123
- // Collect all candidate URLs with their preference
124
- const flvUrls: string[] = []
125
- const m3u8Urls: string[] = []
132
+ // First FLV wins; HLS is only a fallback.
133
+ let flv: string | null = null
134
+ let hls: string | null = null
126
135
 
127
136
  function walk(value: unknown): void {
128
137
  if (typeof value === "string") {
129
- // Direct URL match
130
- if (
131
- (value.startsWith("http://") || value.startsWith("https://")) &&
132
- (value.includes(".flv") || value.includes(".m3u8"))
133
- ) {
134
- if (value.includes(".flv")) {
135
- flvUrls.push(value)
136
- } else {
137
- m3u8Urls.push(value)
138
- }
138
+ if (value.startsWith("http://") || value.startsWith("https://")) {
139
+ if (value.includes(".flv")) flv ??= value
140
+ else if (value.includes(".m3u8")) hls ??= value
139
141
  return
140
142
  }
141
143
  // JSON-encoded string — parse and recurse
@@ -150,22 +152,10 @@ export function findStreamUrlRecursively(obj: unknown): string | null {
150
152
  }
151
153
 
152
154
  if (value && typeof value === "object") {
153
- if (Array.isArray(value)) {
154
- for (const item of value) {
155
- walk(item)
156
- }
157
- } else {
158
- for (const val of Object.values(value as Record<string, unknown>)) {
159
- walk(val)
160
- }
161
- }
155
+ for (const val of Object.values(value as Record<string, unknown>)) walk(val)
162
156
  }
163
157
  }
164
158
 
165
159
  walk(obj)
166
-
167
- // Prefer FLV (lower latency) over HLS
168
- if (flvUrls.length > 0) return flvUrls[0] as string
169
- if (m3u8Urls.length > 0) return m3u8Urls[0] as string
170
- return null
160
+ return flv ?? hls
171
161
  }
@@ -39,72 +39,61 @@ export function createWebcastApi(
39
39
  signal?: AbortSignal,
40
40
  ): WebcastReader {
41
41
  /**
42
- * Shared boilerplate for Webcast room/info API calls.
43
- * Handles URL construction, HTTP GET, JSON parsing, and error handling.
44
- * Room-gate refusals (status_code 4003110) are reported to the caller
45
- * instead of being collapsed into null; callers map failures.
46
- * The caller provides an extractor for the response data.
42
+ * GET → JSON with the contract every Webcast call shares: gate refusals
43
+ * (status_code 4003110) and transport failures come back as `{ ok: false }`
44
+ * instead of collapsing into null. `statusCode: 0` = threw before a status.
47
45
  */
48
- async function fetchFromRoomApi<T>(
49
- roomId: string,
46
+ async function fetchJson<T>(
47
+ url: string,
48
+ label: string,
50
49
  extract: (data: Record<string, unknown>) => T | null,
51
50
  ): Promise<RoomApiResult<T>> {
52
51
  try {
53
- const url = `${WEBCAST_BASE}/webcast/room/info/?aid=1988&room_id=${roomId}&type=live`
54
52
  const res = await http.get(url, signal)
55
- debug(`fetchFromRoomApi: roomId=${roomId} status=${res.status}, ok=${res.ok}`)
53
+ debug(`${label} status=${res.status}, ok=${res.ok}`)
56
54
  if (!res.ok) return { ok: false, statusCode: res.status, body: "" }
57
55
 
58
56
  const text = await res.text()
59
- debug(`fetchFromRoomApi: roomId=${roomId} returned ${text.length} bytes`)
57
+ debug(`${label} returned ${text.length} bytes`)
60
58
  if (text.length === 0) return { ok: true, value: null }
61
59
 
62
60
  const data = JSON.parse(text) as Record<string, unknown>
63
-
64
61
  // status_code 4003110 = age-protected/restricted room: report it
65
- if ((data as { status_code?: unknown }).status_code === 4003110) {
66
- return { ok: false, statusCode: 4003110, body: text }
67
- }
62
+ if (data.status_code === 4003110) return { ok: false, statusCode: 4003110, body: text }
68
63
 
69
64
  return { ok: true, value: extract(data) }
70
65
  } catch {
71
- // statusCode 0 = transport/parse failure before a status was available.
72
66
  return { ok: false, statusCode: 0, body: "" }
73
67
  }
74
68
  }
75
69
 
70
+ async function fetchFromRoomApi<T>(
71
+ roomId: string,
72
+ extract: (data: Record<string, unknown>) => T | null,
73
+ ): Promise<RoomApiResult<T>> {
74
+ return fetchJson(
75
+ `${WEBCAST_BASE}/webcast/room/info/?aid=1988&room_id=${roomId}&type=live`,
76
+ `fetchFromRoomApi: roomId=${roomId}`,
77
+ extract,
78
+ )
79
+ }
80
+
76
81
  /**
77
- * Check if a room is currently alive using the lightweight
78
- * /webcast/room/check_alive/ endpoint.
79
- *
80
- * This is faster and cheaper than fetching the full room/info response.
81
- * Returns `true` if the room is live, `false` otherwise (including errors).
82
+ * Lightweight liveness probe: cheaper than the full room/info response.
83
+ * Failures read as `false`.
82
84
  *
83
85
  * Endpoint: /webcast/room/check_alive/?aid=1988&region=CH&room_ids={id}&user_is_login=true
84
86
  * Response: { "data": [{ "alive": true/false, "room_id": "..." }] }
85
87
  */
86
88
  async function fetchCheckAlive(roomId: string): Promise<boolean> {
87
- try {
88
- const url = `${WEBCAST_BASE}/webcast/room/check_alive/?aid=1988&region=CH&room_ids=${roomId}&user_is_login=true`
89
- const res = await http.get(url, signal)
90
- debug(`fetchCheckAlive: roomId=${roomId} status=${res.status}, ok=${res.ok}`)
91
- if (!res.ok) return false
92
-
93
- const text = await res.text()
94
- debug(`fetchCheckAlive: roomId=${roomId} returned ${text.length} bytes`)
95
- if (text.length === 0) return false
96
-
97
- const data = JSON.parse(text) as Record<string, unknown>
98
- const items = data?.data as Array<Record<string, unknown>> | undefined
99
- const alive = items?.[0]?.alive === true
100
- debug(`fetchCheckAlive: roomId=${roomId} alive=${alive}`)
101
- return alive
102
- } catch (err) {
103
- debug(
104
- `fetchCheckAlive: roomId=${roomId} error — ${err instanceof Error ? err.message : String(err)}`,
105
- )
106
- return false
107
- }
89
+ const res = await fetchJson(
90
+ `${WEBCAST_BASE}/webcast/room/check_alive/?aid=1988&region=CH&room_ids=${roomId}&user_is_login=true`,
91
+ `fetchCheckAlive: roomId=${roomId}`,
92
+ (data) => (data.data as Array<{ alive?: boolean }> | undefined)?.[0]?.alive === true,
93
+ )
94
+ const alive = res.ok && res.value === true
95
+ debug(`fetchCheckAlive: roomId=${roomId} alive=${alive}`)
96
+ return alive
108
97
  }
109
98
 
110
99
  /**
@@ -1,14 +0,0 @@
1
- //#region src/app/abort.ts
2
- function abortScope(parent) {
3
- const controller = new AbortController();
4
- if (parent) if (parent.aborted) controller.abort(parent.reason);
5
- else parent.addEventListener("abort", () => controller.abort(parent.reason), { once: true });
6
- return {
7
- signal: controller.signal,
8
- close: (reason) => controller.abort(reason)
9
- };
10
- }
11
- //#endregion
12
- export { abortScope };
13
-
14
- //# sourceMappingURL=abort.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"abort.mjs","names":[],"sources":["../../src/app/abort.ts"],"sourcesContent":["/**\n * One cancellation scope per recorder run. Everything that can block accepts\n * `scope.signal`; `close()` aborts in-flight work immediately.\n */\n\nexport interface AbortScope {\n readonly signal: AbortSignal\n close(reason?: string): void\n}\n\nexport function abortScope(parent?: AbortSignal): AbortScope {\n const controller = new AbortController()\n if (parent) {\n if (parent.aborted) controller.abort(parent.reason)\n else parent.addEventListener(\"abort\", () => controller.abort(parent.reason), { once: true })\n }\n return { signal: controller.signal, close: (reason) => controller.abort(reason) }\n}\n"],"mappings":";AAUA,SAAgB,WAAW,QAAkC;CAC3D,MAAM,aAAa,IAAI,gBAAgB;CACvC,IAAI,QACF,IAAI,OAAO,SAAS,WAAW,MAAM,OAAO,MAAM;MAC7C,OAAO,iBAAiB,eAAe,WAAW,MAAM,OAAO,MAAM,GAAG,EAAE,MAAM,KAAK,CAAC;CAE7F,OAAO;EAAE,QAAQ,WAAW;EAAQ,QAAQ,WAAW,WAAW,MAAM,MAAM;CAAE;AAClF"}
@@ -1,36 +0,0 @@
1
- import { EventEmitter } from "node:events";
2
- //#region src/app/events.ts
3
- /**
4
- * Typed emitter over `node:events` — the four-channel recorder contract
5
- * (`verdict`, `record`, `progress`, `failure`) with no listener bookkeeping of
6
- * our own. `emit` swallows handler throws: a bad subscriber must not kill a
7
- * recording.
8
- */
9
- function createEventEmitter() {
10
- const emitter = new EventEmitter();
11
- const asListener = (handler) => handler;
12
- function on(event, handler) {
13
- emitter.on(event, asListener(handler));
14
- }
15
- function off(event, handler) {
16
- emitter.off(event, asListener(handler));
17
- }
18
- function emit(event, ...args) {
19
- try {
20
- emitter.emit(event, ...args);
21
- } catch {}
22
- }
23
- function clear() {
24
- emitter.removeAllListeners();
25
- }
26
- return {
27
- on,
28
- off,
29
- emit,
30
- clear
31
- };
32
- }
33
- //#endregion
34
- export { createEventEmitter };
35
-
36
- //# sourceMappingURL=events.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"events.mjs","names":[],"sources":["../../src/app/events.ts"],"sourcesContent":["/**\n * Typed emitter over `node:events` — the four-channel recorder contract\n * (`verdict`, `record`, `progress`, `failure`) with no listener bookkeeping of\n * our own. `emit` swallows handler throws: a bad subscriber must not kill a\n * recording.\n */\n\nimport { EventEmitter } from \"node:events\"\nimport type { RecorderEvent, RecorderEventHandler } from \"./config\"\n\nexport interface RecorderEventEmitter {\n on<E extends RecorderEvent>(event: E, handler: RecorderEventHandler[E]): void\n off<E extends RecorderEvent>(event: E, handler: RecorderEventHandler[E]): void\n emit<E extends RecorderEvent>(event: E, ...args: Parameters<RecorderEventHandler[E]>): void\n clear(): void\n}\n\nexport function createEventEmitter(): RecorderEventEmitter {\n const emitter = new EventEmitter()\n const asListener = (handler: unknown) => handler as (...args: unknown[]) => void\n\n function on<E extends RecorderEvent>(event: E, handler: RecorderEventHandler[E]): void {\n emitter.on(event, asListener(handler))\n }\n\n function off<E extends RecorderEvent>(event: E, handler: RecorderEventHandler[E]): void {\n emitter.off(event, asListener(handler))\n }\n\n function emit<E extends RecorderEvent>(\n event: E,\n ...args: Parameters<RecorderEventHandler[E]>\n ): void {\n try {\n emitter.emit(event, ...args)\n } catch {\n // Never let an event handler crash the recorder.\n }\n }\n\n function clear(): void {\n emitter.removeAllListeners()\n }\n\n return { on, off, emit, clear }\n}\n"],"mappings":";;;;;;;;AAiBA,SAAgB,qBAA2C;CACzD,MAAM,UAAU,IAAI,aAAa;CACjC,MAAM,cAAc,YAAqB;CAEzC,SAAS,GAA4B,OAAU,SAAwC;EACrF,QAAQ,GAAG,OAAO,WAAW,OAAO,CAAC;CACvC;CAEA,SAAS,IAA6B,OAAU,SAAwC;EACtF,QAAQ,IAAI,OAAO,WAAW,OAAO,CAAC;CACxC;CAEA,SAAS,KACP,OACA,GAAG,MACG;EACN,IAAI;GACF,QAAQ,KAAK,OAAO,GAAG,IAAI;EAC7B,QAAQ,CAER;CACF;CAEA,SAAS,QAAc;EACrB,QAAQ,mBAAmB;CAC7B;CAEA,OAAO;EAAE;EAAI;EAAK;EAAM;CAAM;AAChC"}
@@ -1,60 +0,0 @@
1
- import { runFfmpeg } from "./ffmpeg.mjs";
2
- import { unlinkSync } from "node:fs";
3
- //#region src/io/media/convert.ts
4
- /**
5
- * Converter — the media-processing capability `RecordingJob` depends on.
6
- *
7
- * Remux (TS → MP4) and segment both delegate to `ffmpeg-utils.runFfmpeg`, so
8
- * the job never builds an FFmpeg command line.
9
- */
10
- function createConverter(logger, signal) {
11
- async function convert(input) {
12
- const output = input.replace(/\.(flv|ts)$/i, ".mp4");
13
- logger?.info(`Converting: ${input} → ${output}`);
14
- await runFfmpeg([
15
- "-i",
16
- input,
17
- "-c",
18
- "copy",
19
- "-y",
20
- output
21
- ], signal);
22
- try {
23
- unlinkSync(input);
24
- logger?.info(`Deleted original: ${input}`);
25
- } catch {
26
- logger?.warn(`Could not delete original: ${input}`);
27
- }
28
- logger?.info(`Converted: ${output}`);
29
- return output;
30
- }
31
- async function segment(input, segmentSeconds, outputPattern) {
32
- return runFfmpeg([
33
- "-i",
34
- input,
35
- "-c",
36
- "copy",
37
- "-f",
38
- "segment",
39
- "-segment_time",
40
- String(segmentSeconds),
41
- "-reset_timestamps",
42
- "1",
43
- "-segment_start_number",
44
- "1",
45
- "-segment_list",
46
- "pipe:1",
47
- "-segment_list_type",
48
- "csv",
49
- outputPattern
50
- ], signal);
51
- }
52
- return {
53
- convert,
54
- segment
55
- };
56
- }
57
- //#endregion
58
- export { createConverter };
59
-
60
- //# sourceMappingURL=convert.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"convert.mjs","names":[],"sources":["../../../src/io/media/convert.ts"],"sourcesContent":["/**\n * Converter — the media-processing capability `RecordingJob` depends on.\n *\n * Remux (TS → MP4) and segment both delegate to `ffmpeg-utils.runFfmpeg`, so\n * the job never builds an FFmpeg command line.\n */\n\nimport { unlinkSync } from \"node:fs\"\nimport type { Logger } from \"../../core/log\"\nimport { runFfmpeg } from \"./ffmpeg\"\n\nexport interface Converter {\n /** Convert a TS file to MP4 (stream copy). Deletes the original on success. */\n convert: (input: string) => Promise<string>\n /** Split a file into `<name>_partN.mp4`; returns FFmpeg's CSV segment listing. */\n segment: (input: string, segmentSeconds: number, outputPattern: string) => Promise<string>\n}\n\nexport function createConverter(logger?: Logger, signal?: AbortSignal): Converter {\n async function convert(input: string): Promise<string> {\n const output = input.replace(/\\.(flv|ts)$/i, \".mp4\")\n\n logger?.info(`Converting: ${input} → ${output}`)\n\n await runFfmpeg([\"-i\", input, \"-c\", \"copy\", \"-y\", output], signal)\n\n // Delete original TS\n try {\n unlinkSync(input)\n logger?.info(`Deleted original: ${input}`)\n } catch {\n logger?.warn(`Could not delete original: ${input}`)\n }\n\n logger?.info(`Converted: ${output}`)\n return output\n }\n\n async function segment(\n input: string,\n segmentSeconds: number,\n outputPattern: string,\n ): Promise<string> {\n return runFfmpeg(\n [\n \"-i\",\n input,\n \"-c\",\n \"copy\",\n \"-f\",\n \"segment\",\n \"-segment_time\",\n String(segmentSeconds),\n \"-reset_timestamps\",\n \"1\",\n \"-segment_start_number\",\n \"1\",\n \"-segment_list\",\n \"pipe:1\",\n \"-segment_list_type\",\n \"csv\",\n outputPattern,\n ],\n signal,\n )\n }\n\n return { convert, segment }\n}\n"],"mappings":";;;;;;;;;AAkBA,SAAgB,gBAAgB,QAAiB,QAAiC;CAChF,eAAe,QAAQ,OAAgC;EACrD,MAAM,SAAS,MAAM,QAAQ,gBAAgB,MAAM;EAEnD,QAAQ,KAAK,eAAe,MAAM,KAAK,QAAQ;EAE/C,MAAM,UAAU;GAAC;GAAM;GAAO;GAAM;GAAQ;GAAM;EAAM,GAAG,MAAM;EAGjE,IAAI;GACF,WAAW,KAAK;GAChB,QAAQ,KAAK,qBAAqB,OAAO;EAC3C,QAAQ;GACN,QAAQ,KAAK,8BAA8B,OAAO;EACpD;EAEA,QAAQ,KAAK,cAAc,QAAQ;EACnC,OAAO;CACT;CAEA,eAAe,QACb,OACA,gBACA,eACiB;EACjB,OAAO,UACL;GACE;GACA;GACA;GACA;GACA;GACA;GACA;GACA,OAAO,cAAc;GACrB;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;EACF,GACA,MACF;CACF;CAEA,OAAO;EAAE;EAAS;CAAQ;AAC5B"}
@@ -1,32 +0,0 @@
1
- import { normalizeFile } from "peaknorm";
2
- //#region src/io/media/normalize.ts
3
- function createAudioNormalizer(opts, logger) {
4
- return { async normalize(file) {
5
- logger?.info(`Normalizing audio: ${file}`);
6
- opts.onStart?.(file);
7
- try {
8
- const normalizeOpts = {
9
- loudness: opts.loudness,
10
- backup: false,
11
- onFileProgress: (f, percent, phase) => {
12
- opts.onProgress?.(f, percent, phase);
13
- }
14
- };
15
- if (opts.audioCodec !== void 0) normalizeOpts.audioCodec = opts.audioCodec;
16
- if (opts.audioBitrate !== void 0) normalizeOpts.audioBitrate = opts.audioBitrate;
17
- const result = await normalizeFile(file, normalizeOpts);
18
- logger?.info(`Audio normalized: ${result.output}`);
19
- opts.onComplete?.(result);
20
- return result;
21
- } catch (err) {
22
- const error = err instanceof Error ? err : new Error(String(err));
23
- logger?.error(`Audio normalization failed: ${error.message}`);
24
- opts.onError?.(file, error);
25
- throw error;
26
- }
27
- } };
28
- }
29
- //#endregion
30
- export { createAudioNormalizer };
31
-
32
- //# sourceMappingURL=normalize.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"normalize.mjs","names":[],"sources":["../../../src/io/media/normalize.ts"],"sourcesContent":["/**\n * Audio normalizer — wraps peaknorm's EBU R128 loudness normalization.\n * Runs after conversion/segmenting to normalize the final MP4 audio.\n */\n\nimport type { NormalizeOptions, NormalizeResult } from \"peaknorm\"\nimport { normalizeFile } from \"peaknorm\"\nimport type { Logger } from \"../../core/log\"\n\nexport interface AudioNormalizer {\n /** Normalize a single audio/video file. Returns the normalize result. */\n normalize(file: string): Promise<NormalizeResult>\n}\n\nexport interface AudioNormalizerOptions {\n /** Target loudness in LUFS (default: -14). */\n loudness: number\n /** Audio codec for output (default: peaknorm's default, \"libopus\"). */\n audioCodec?: string\n /** Audio bitrate for output (default: peaknorm's default, \"96k\"). */\n audioBitrate?: string\n /** Called when a file starts normalization. */\n onStart?: (file: string) => void\n /** Called with progress updates (percent 0-100, phase \"analyzing\"|\"normalizing\"). */\n onProgress?: (file: string, percent: number, phase: string) => void\n /** Called when a file completes normalization successfully. */\n onComplete?: (result: NormalizeResult) => void\n /** Called when a file errors during normalization. */\n onError?: (file: string, error: Error) => void\n}\n\nexport function createAudioNormalizer(\n opts: AudioNormalizerOptions,\n logger?: Logger,\n): AudioNormalizer {\n return {\n async normalize(file: string): Promise<NormalizeResult> {\n logger?.info(`Normalizing audio: ${file}`)\n opts.onStart?.(file)\n\n try {\n const normalizeOpts: NormalizeOptions = {\n loudness: opts.loudness,\n backup: false,\n onFileProgress: (f, percent, phase) => {\n opts.onProgress?.(f, percent, phase)\n },\n }\n if (opts.audioCodec !== undefined) normalizeOpts.audioCodec = opts.audioCodec\n if (opts.audioBitrate !== undefined) normalizeOpts.audioBitrate = opts.audioBitrate\n const result = await normalizeFile(file, normalizeOpts)\n\n logger?.info(`Audio normalized: ${result.output}`)\n opts.onComplete?.(result)\n return result\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err))\n logger?.error(`Audio normalization failed: ${error.message}`)\n opts.onError?.(file, error)\n throw error\n }\n },\n }\n}\n"],"mappings":";;AA+BA,SAAgB,sBACd,MACA,QACiB;CACjB,OAAO,EACL,MAAM,UAAU,MAAwC;EACtD,QAAQ,KAAK,sBAAsB,MAAM;EACzC,KAAK,UAAU,IAAI;EAEnB,IAAI;GACF,MAAM,gBAAkC;IACtC,UAAU,KAAK;IACf,QAAQ;IACR,iBAAiB,GAAG,SAAS,UAAU;KACrC,KAAK,aAAa,GAAG,SAAS,KAAK;IACrC;GACF;GACA,IAAI,KAAK,eAAe,KAAA,GAAW,cAAc,aAAa,KAAK;GACnE,IAAI,KAAK,iBAAiB,KAAA,GAAW,cAAc,eAAe,KAAK;GACvE,MAAM,SAAS,MAAM,cAAc,MAAM,aAAa;GAEtD,QAAQ,KAAK,qBAAqB,OAAO,QAAQ;GACjD,KAAK,aAAa,MAAM;GACxB,OAAO;EACT,SAAS,KAAK;GACZ,MAAM,QAAQ,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,GAAG,CAAC;GAChE,QAAQ,MAAM,+BAA+B,MAAM,SAAS;GAC5D,KAAK,UAAU,MAAM,KAAK;GAC1B,MAAM;EACR;CACF,EACF;AACF"}
package/src/app/abort.ts DELETED
@@ -1,18 +0,0 @@
1
- /**
2
- * One cancellation scope per recorder run. Everything that can block accepts
3
- * `scope.signal`; `close()` aborts in-flight work immediately.
4
- */
5
-
6
- export interface AbortScope {
7
- readonly signal: AbortSignal
8
- close(reason?: string): void
9
- }
10
-
11
- export function abortScope(parent?: AbortSignal): AbortScope {
12
- const controller = new AbortController()
13
- if (parent) {
14
- if (parent.aborted) controller.abort(parent.reason)
15
- else parent.addEventListener("abort", () => controller.abort(parent.reason), { once: true })
16
- }
17
- return { signal: controller.signal, close: (reason) => controller.abort(reason) }
18
- }