@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":"recorder.mjs","names":[],"sources":["../../src/app/recorder.ts"],"sourcesContent":["/**\n * Recorder orchestrator — wires the TikTok client, stream download, and\n * RecordingJob into a single RecorderController.\n *\n * Policy lives in `policy/tick.ts`; this file maps a TickPlan to effects and\n * owns the session state those effects mutate. Everything a tick needs is\n * constructed as a `const` in `start()` and passed in, so no call site has to\n * assert a non-null module-level `let` back into existence.\n */\n\nimport { planTick, type TickFacts } from \"../core/plan\"\nimport { verdictOf } from \"../core/verdict\"\nimport { createHttpClient, type HttpClient } from \"../io/http\"\nimport { type Converter, createConverter } from \"../io/media/convert\"\nimport { downloadStream } from \"../io/media/download\"\nimport { type AudioNormalizer, createAudioNormalizer } from \"../io/media/normalize\"\nimport { createTikTokClient, type TikTokClient } from \"../io/tiktok/client\"\nimport { type AbortScope, abortScope } from \"./abort\"\nimport type { RecorderConfig, RecorderController, RecorderStatus } from \"./config\"\nimport { resolveConfig } from \"./config\"\nimport { createEventEmitter } from \"./events\"\nimport { createRecordingJob, type RecordingJob } from \"./job\"\nimport { createLogger } from \"./logger\"\nimport { createPollingMonitor, type PollingMonitor } from \"./loop\"\n\n/** Max wait for a stop-time remux before aborting it (matches the pre-#32 cap). */\nconst POST_REMUX_GRACE_MS = 10 * 60 * 1000\n\n/** Everything one poll tick needs, built by `start()` before the tick can run. */\ninterface TickDeps {\n client: TikTokClient\n monitor: PollingMonitor\n scope: AbortScope\n post: AbortScope\n converter: Converter\n audioNormalizer: AudioNormalizer | null\n}\n\n/** What `stop()` has to join and release. */\ninterface Running {\n monitor: PollingMonitor\n http: HttpClient\n scope: AbortScope\n}\n\nexport function createRecorder(config: RecorderConfig): RecorderController {\n const cfg = resolveConfig(config)\n const logger = createLogger({\n level: cfg.logLevel,\n logFile: \"tiktok-recorder.log\",\n console: cfg.logConsole,\n })\n\n const emitter = createEventEmitter()\n\n // Session state — written by ticks and by the job lifecycle, read by getStatus().\n const status: RecorderStatus = { state: \"idle\", user: cfg.user }\n let running: Running | null = null\n let postScope: AbortScope | null = null\n let currentJob: RecordingJob | null = null\n let recordedSec = 0\n let consecutiveErrors = 0\n\n function setState(partial: Partial<RecorderStatus>): void {\n const prev = status.state\n Object.assign(status, partial)\n if (partial.state !== undefined && partial.state !== prev) {\n logger.info(`State: ${prev} → ${partial.state}`)\n if (partial.state === \"polling\") status.lastPollTime = new Date().toISOString()\n }\n }\n\n async function tick(d: TickDeps): Promise<void> {\n const { client, monitor, scope, post } = d\n if (scope.signal.aborted) return\n const user = cfg.user\n\n client.invalidateCache()\n logger.info(`Checking @${user}...`)\n\n const verdict = await client.getVerdict(user)\n const facts: TickFacts = {\n recording: currentJob !== null,\n recordedSec,\n oneShot: cfg.duration > 0,\n consecutiveErrors,\n }\n consecutiveErrors =\n verdict.reason === \"error\" || verdict.reason === \"no-room-id\" ? consecutiveErrors + 1 : 0\n\n emitter.emit(\"verdict\", verdict)\n const plan = planTick(verdict, facts)\n\n switch (plan.kind) {\n case \"poll\": {\n logger.info(\n `@${user} ${plan.note} (reason: ${verdict.reason}, source: ${lastSource(verdict)})`,\n )\n return\n }\n case \"hold\": {\n if (plan.reason === \"restricted\") {\n logger.warn(\n `@${user} is live but age-protected/restricted — stream unavailable (reason: restricted, status_code 4003110, room: ${plan.room.id})`,\n )\n } else {\n logger.warn(\n `@${user} is live but no stream URL found (reason: no-stream-url, room: ${plan.room.id})`,\n )\n }\n return\n }\n case \"stop\": {\n if (plan.why === \"one-shot\") {\n logger.info(\"Duration limit reached — exiting\")\n monitor.stopAfterCurrentTick()\n } else if (plan.why === \"gave-up\") {\n logger.error(`@${user} gave up after ${consecutiveErrors} consecutive errors`)\n monitor.stopAfterCurrentTick()\n }\n return\n }\n case \"record\": {\n const { room, stream } = plan\n logger.info(`@${user} is LIVE! (room: ${room.id}, reason: live)`)\n setState({ state: \"recording\" })\n emitter.emit(\"record\", { phase: \"start\", user, file: \"\" })\n\n const getNextUrl = async (): Promise<string | null> => {\n if (scope.signal.aborted) return null\n // Use the lightweight check_alive endpoint first — avoids a full\n // page re-scan + room/info call when the stream is still active.\n const alive = await client.isRoomAlive(room.id)\n if (!alive) {\n logger.info(`@${user} is no longer live — stopping`)\n return null\n }\n client.invalidateCache()\n return client.getLiveUrl(room.id)\n }\n\n const result = await downloadStream(\n stream.url,\n user,\n cfg.outputDir,\n cfg.duration,\n (info) => emitter.emit(\"progress\", { kind: \"download\", ...info }),\n getNextUrl,\n scope.signal,\n logger,\n cfg.cookies,\n )\n\n emitter.emit(\"record\", { phase: \"download\", ...result })\n recordedSec += result.duration\n\n const job = createRecordingJob({\n result,\n cfg: { segmentMinutes: cfg.segmentMinutes },\n logger,\n converter: d.converter,\n audioNormalizer: d.audioNormalizer,\n signal: post.signal,\n emitRecord: (event) => emitter.emit(\"record\", event),\n emitProgress: (event) => emitter.emit(\"progress\", event),\n emitFailure: (err) => emitter.emit(\"failure\", err),\n setState,\n })\n currentJob = job\n try {\n await job.finish()\n } finally {\n currentJob = null\n }\n\n // One-shot mode: if a duration was set, stop after this recording\n if (cfg.duration > 0) {\n logger.info(\"Duration limit reached — exiting\")\n monitor.stopAfterCurrentTick()\n } else if (!scope.signal.aborted) {\n // Recording ended because the stream went offline (not user-initiated\n // stop). Immediately re-check via the lightweight endpoint.\n const alive = await client.isRoomAlive(room.id)\n if (!alive) {\n logger.info(`@${user} is offline`)\n emitter.emit(\n \"verdict\",\n verdictOf({ room: { ...room, live: false }, evidence: verdict.evidence }),\n )\n }\n }\n return\n }\n }\n }\n\n async function start(): Promise<void> {\n if (status.state !== \"idle\") {\n logger.warn(`start() ignored: already in state ${status.state}`)\n return\n }\n const scope = abortScope()\n // Post-processing outlives a user stop: Ctrl+C aborts the download, but the\n // partial .ts is still remuxed to .mp4 before the process exits.\n const post = abortScope()\n postScope = post\n currentJob = null\n recordedSec = 0\n consecutiveErrors = 0\n\n logger.info(`Starting recorder for @${cfg.user}`)\n const http = await createHttpClient(cfg)\n const client = createTikTokClient(http, logger, cfg.debug, scope.signal)\n const converter = createConverter(logger, post.signal)\n const audioNormalizer = cfg.normalizeAudio\n ? createAudioNormalizer(\n {\n loudness: cfg.normalizeLoudness,\n audioCodec: cfg.normalizeCodec,\n audioBitrate: cfg.normalizeBitrate,\n onProgress: (file, percent, phase) =>\n emitter.emit(\"progress\", {\n kind: \"normalize\",\n file,\n percent,\n phase: phase as \"analyzing\" | \"normalizing\",\n }),\n },\n logger,\n )\n : null\n\n // Self-reference inside `onTick` is safe: the monitor calls it from\n // `start()`, never during construction.\n let monitor: PollingMonitor\n monitor = createPollingMonitor({\n intervalMinutes: cfg.interval,\n signal: scope.signal,\n logger,\n onTick: () => tick({ client, monitor, scope, post, converter, audioNormalizer }),\n })\n running = { monitor, http, scope }\n\n setState({ state: \"polling\" })\n await monitor.start()\n }\n\n async function stop(): Promise<void> {\n if (status.state === \"stopped\") {\n logger.warn(`stop() ignored: already stopped`)\n return\n }\n logger.info(\"Stopping recorder...\")\n running?.scope.close(\"user\")\n\n const grace = setTimeout(() => postScope?.close(\"stop-timeout\"), POST_REMUX_GRACE_MS)\n try {\n const job = currentJob\n if (job) {\n logger.info(\"Waiting for active recording to finish...\")\n await job.finish()\n }\n\n if (running) await running.monitor.stop()\n } finally {\n clearTimeout(grace)\n }\n if (running) await running.http.close()\n emitter.clear()\n setState({ state: \"stopped\" })\n logger.info(\"Recorder stopped\")\n }\n\n return {\n start,\n stop,\n getStatus: () => ({ ...status }),\n on: emitter.on,\n off: emitter.off,\n }\n}\n\nfunction lastSource(verdict: ReturnType<typeof verdictOf>): string {\n return (\n [...verdict.evidence].reverse().find((e) => e.outcome === \"hit\" || e.outcome === \"denied\")\n ?.source ?? \"none\"\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAM,sBAAsB,MAAU;AAmBtC,SAAgB,eAAe,QAA4C;CACzE,MAAM,MAAM,cAAc,MAAM;CAChC,MAAM,SAAS,aAAa;EAC1B,OAAO,IAAI;EACX,SAAS;EACT,SAAS,IAAI;CACf,CAAC;CAED,MAAM,UAAU,mBAAmB;CAGnC,MAAM,SAAyB;EAAE,OAAO;EAAQ,MAAM,IAAI;CAAK;CAC/D,IAAI,UAA0B;CAC9B,IAAI,YAA+B;CACnC,IAAI,aAAkC;CACtC,IAAI,cAAc;CAClB,IAAI,oBAAoB;CAExB,SAAS,SAAS,SAAwC;EACxD,MAAM,OAAO,OAAO;EACpB,OAAO,OAAO,QAAQ,OAAO;EAC7B,IAAI,QAAQ,UAAU,KAAA,KAAa,QAAQ,UAAU,MAAM;GACzD,OAAO,KAAK,UAAU,KAAK,KAAK,QAAQ,OAAO;GAC/C,IAAI,QAAQ,UAAU,WAAW,OAAO,gCAAe,IAAI,KAAK,EAAA,CAAE,YAAY;EAChF;CACF;CAEA,eAAe,KAAK,GAA4B;EAC9C,MAAM,EAAE,QAAQ,SAAS,OAAO,SAAS;EACzC,IAAI,MAAM,OAAO,SAAS;EAC1B,MAAM,OAAO,IAAI;EAEjB,OAAO,gBAAgB;EACvB,OAAO,KAAK,aAAa,KAAK,IAAI;EAElC,MAAM,UAAU,MAAM,OAAO,WAAW,IAAI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YAAY,SAAS,EAAE,YAAY,QAAQ,CAAC,EACtF,UAAU;AAElB"}
1
+ {"version":3,"file":"recorder.mjs","names":[],"sources":["../../src/app/recorder.ts"],"sourcesContent":["/**\n * Recorder orchestrator — wires the TikTok client, stream download, and\n * RecordingJob into a single RecorderController.\n *\n * Policy lives in `core/plan.ts`; this file maps a TickPlan to effects and\n * owns the session state those effects mutate. Everything a tick needs is\n * constructed as a `const` in `start()` and passed in, so no call site has to\n * assert a non-null module-level `let` back into existence.\n */\n\nimport { EventEmitter } from \"node:events\"\nimport { planTick, type TickFacts } from \"../core/plan\"\nimport { verdictOf } from \"../core/verdict\"\nimport { createHttpClient, type HttpClient } from \"../io/http\"\nimport { downloadStream } from \"../io/media/download\"\nimport { createMediaConverter, type MediaConverter } from \"../io/media/ffmpeg\"\nimport { createTikTokClient, type TikTokClient } from \"../io/tiktok/client\"\nimport type {\n RecorderConfig,\n RecorderController,\n RecorderEvent,\n RecorderEventHandler,\n RecorderStatus,\n} from \"./config\"\nimport { resolveConfig } from \"./config\"\nimport { createRecordingJob, type RecordingJob } from \"./job\"\nimport { createLogger } from \"./logger\"\nimport { createPollingMonitor, type PollingMonitor } from \"./loop\"\n\n/** Max wait for a stop-time remux before aborting it (matches the pre-#32 cap). */\nconst POST_REMUX_GRACE_MS = 10 * 60 * 1000\n\n/** Everything one poll tick needs, built by `start()` before the tick can run. */\ninterface TickDeps {\n client: TikTokClient\n monitor: PollingMonitor\n scope: AbortController\n post: AbortController\n converter: MediaConverter\n}\n\n/** What `stop()` has to join and release. */\ninterface Running {\n monitor: PollingMonitor\n http: HttpClient\n scope: AbortController\n}\n\nexport function createRecorder(config: RecorderConfig): RecorderController {\n const cfg = resolveConfig(config)\n const logger = createLogger({\n level: cfg.logLevel,\n logFile: \"tiktok-recorder.log\",\n console: cfg.logConsole,\n })\n\n // Typed over `node:events`; a throwing subscriber must not kill a recording.\n const bus = new EventEmitter()\n const emitter = {\n on: bus.on.bind(bus) as RecorderController[\"on\"],\n off: bus.off.bind(bus) as RecorderController[\"off\"],\n emit: <E extends RecorderEvent>(\n event: E,\n ...args: Parameters<RecorderEventHandler[E]>\n ): void => {\n try {\n bus.emit(event, ...args)\n } catch {\n // ignore — a bad subscriber must never crash the recorder\n }\n },\n clear: () => bus.removeAllListeners(),\n }\n\n // Session state — written by ticks and by the job lifecycle, read by getStatus().\n const status: RecorderStatus = { state: \"idle\", user: cfg.user }\n let running: Running | null = null\n let postScope: AbortController | null = null\n let currentJob: RecordingJob | null = null\n let recordedSec = 0\n let consecutiveErrors = 0\n\n function setState(partial: Partial<RecorderStatus>): void {\n const prev = status.state\n Object.assign(status, partial)\n if (partial.state !== undefined && partial.state !== prev) {\n logger.info(`State: ${prev} → ${partial.state}`)\n if (partial.state === \"polling\") status.lastPollTime = new Date().toISOString()\n }\n }\n\n async function tick(d: TickDeps): Promise<void> {\n const { client, monitor, scope, post } = d\n if (scope.signal.aborted) return\n const user = cfg.user\n\n client.invalidateCache()\n logger.info(`Checking @${user}...`)\n\n const verdict = await client.getVerdict(user)\n const facts: TickFacts = {\n recording: currentJob !== null,\n recordedSec,\n oneShot: cfg.duration > 0,\n consecutiveErrors,\n }\n consecutiveErrors =\n verdict.reason === \"error\" || verdict.reason === \"no-room-id\" ? consecutiveErrors + 1 : 0\n\n emitter.emit(\"verdict\", verdict)\n const plan = planTick(verdict, facts)\n\n switch (plan.kind) {\n case \"poll\": {\n logger.info(\n `@${user} ${plan.note} (reason: ${verdict.reason}, source: ${lastSource(verdict)})`,\n )\n return\n }\n case \"hold\": {\n const why =\n plan.reason === \"restricted\"\n ? \"age-protected/restricted — stream unavailable (reason: restricted, status_code 4003110\"\n : \"no stream URL found (reason: no-stream-url\"\n logger.warn(`@${user} is live but ${why}, room: ${plan.room.id})`)\n return\n }\n case \"stop\": {\n if (plan.why === \"one-shot\") {\n logger.info(\"Duration limit reached — exiting\")\n monitor.stopAfterCurrentTick()\n } else if (plan.why === \"gave-up\") {\n logger.error(`@${user} gave up after ${consecutiveErrors} consecutive errors`)\n monitor.stopAfterCurrentTick()\n }\n return\n }\n case \"record\": {\n const { room, stream } = plan\n logger.info(`@${user} is LIVE! (room: ${room.id}, reason: live)`)\n setState({ state: \"recording\" })\n emitter.emit(\"record\", { phase: \"start\", user, file: \"\" })\n\n const getNextUrl = async (): Promise<string | null> => {\n if (scope.signal.aborted) return null\n // Use the lightweight check_alive endpoint first — avoids a full\n // page re-scan + room/info call when the stream is still active.\n const alive = await client.isRoomAlive(room.id)\n if (!alive) {\n logger.info(`@${user} is no longer live — stopping`)\n return null\n }\n client.invalidateCache()\n return client.getLiveUrl(room.id)\n }\n\n const result = await downloadStream(\n stream.url,\n user,\n cfg.outputDir,\n cfg.duration,\n (info) => emitter.emit(\"progress\", { kind: \"download\", ...info }),\n getNextUrl,\n scope.signal,\n logger,\n cfg.cookies,\n )\n\n emitter.emit(\"record\", { phase: \"download\", ...result })\n recordedSec += result.duration\n\n const job = createRecordingJob({\n result,\n cfg,\n logger,\n converter: d.converter,\n signal: post.signal,\n emitRecord: (event) => emitter.emit(\"record\", event),\n emitProgress: (event) => emitter.emit(\"progress\", event),\n emitFailure: (err) => emitter.emit(\"failure\", err),\n setState,\n })\n currentJob = job\n try {\n await job.finish()\n } finally {\n currentJob = null\n }\n\n // One-shot mode: if a duration was set, stop after this recording\n if (cfg.duration > 0) {\n logger.info(\"Duration limit reached — exiting\")\n monitor.stopAfterCurrentTick()\n } else if (!scope.signal.aborted) {\n // Recording ended because the stream went offline (not user-initiated\n // stop). Immediately re-check via the lightweight endpoint.\n const alive = await client.isRoomAlive(room.id)\n if (!alive) {\n logger.info(`@${user} is offline`)\n emitter.emit(\n \"verdict\",\n verdictOf({ room: { ...room, live: false }, evidence: verdict.evidence }),\n )\n }\n }\n return\n }\n }\n }\n\n async function start(): Promise<void> {\n if (status.state !== \"idle\") {\n logger.warn(`start() ignored: already in state ${status.state}`)\n return\n }\n const scope = new AbortController()\n // Post-processing outlives a user stop: Ctrl+C aborts the download, but the\n // partial .ts is still remuxed to .mp4 before the process exits.\n const post = new AbortController()\n postScope = post\n currentJob = null\n recordedSec = 0\n consecutiveErrors = 0\n\n logger.info(`Starting recorder for @${cfg.user}`)\n const http = await createHttpClient(cfg)\n const client = createTikTokClient(http, logger, cfg.debug, scope.signal)\n const converter = createMediaConverter(logger, post.signal)\n\n // Self-reference inside `onTick` is safe: the monitor calls it from\n // `start()`, never during construction.\n let monitor: PollingMonitor\n monitor = createPollingMonitor({\n intervalMinutes: cfg.interval,\n signal: scope.signal,\n logger,\n onTick: () => tick({ client, monitor, scope, post, converter }),\n })\n running = { monitor, http, scope }\n\n setState({ state: \"polling\" })\n await monitor.start()\n }\n\n async function stop(): Promise<void> {\n if (status.state === \"stopped\") {\n logger.warn(`stop() ignored: already stopped`)\n return\n }\n logger.info(\"Stopping recorder...\")\n running?.scope.abort(\"user\")\n\n const grace = setTimeout(() => postScope?.abort(\"stop-timeout\"), POST_REMUX_GRACE_MS)\n try {\n const job = currentJob\n if (job) {\n logger.info(\"Waiting for active recording to finish...\")\n await job.finish()\n }\n\n if (running) await running.monitor.stop()\n } finally {\n clearTimeout(grace)\n }\n if (running) await running.http.close()\n emitter.clear()\n setState({ state: \"stopped\" })\n logger.info(\"Recorder stopped\")\n }\n\n return {\n start,\n stop,\n getStatus: () => ({ ...status }),\n on: emitter.on,\n off: emitter.off,\n }\n}\n\nfunction lastSource(verdict: ReturnType<typeof verdictOf>): string {\n return (\n [...verdict.evidence].reverse().find((e) => e.outcome === \"hit\" || e.outcome === \"denied\")\n ?.source ?? \"none\"\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA8BA,MAAM,sBAAsB,MAAU;AAkBtC,SAAgB,eAAe,QAA4C;CACzE,MAAM,MAAM,cAAc,MAAM;CAChC,MAAM,SAAS,aAAa;EAC1B,OAAO,IAAI;EACX,SAAS;EACT,SAAS,IAAI;CACf,CAAC;CAGD,MAAM,MAAM,IAAI,aAAa;CAC7B,MAAM,UAAU;E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,MAAM,QAAQ,iBAAiB,WAAW,MAAM,cAAc,GAAG,mBAAmB;EACpF,IAAI;GACF,MAAM,MAAM;GACZ,IAAI,KAAK;IACP,OAAO,KAAK,2CAA2C;IACvD,MAAM,IAAI,OAAO;GACnB;GAEA,IAAI,SAAS,MAAM,QAAQ,QAAQ,KAAK;EAC1C,UAAU;GACR,aAAa,KAAK;EACpB;EACA,IAAI,SAAS,MAAM,QAAQ,KAAK,MAAM;EACtC,QAAQ,MAAM;EACd,SAAS,EAAE,OAAO,UAAU,CAAC;EAC7B,OAAO,KAAK,kBAAkB;CAChC;CAEA,OAAO;EACL;EACA;EACA,kBAAkB,EAAE,GAAG,OAAO;EAC9B,IAAI,QAAQ;EACZ,KAAK,QAAQ;CACf;AACF;AAEA,SAAS,WAAW,SAA+C;CACjE,OACE,CAAC,GAAG,QAAQ,QAAQ,CAAC,CAAC,QAAQ,CAAC,CAAC,MAAM,MAAM,EAAE,YAAY,SAAS,EAAE,YAAY,QAAQ,CAAC,EACtF,UAAU;AAElB"}
@@ -1 +1 @@
1
- {"version":3,"file":"plan.mjs","names":[],"sources":["../../src/core/plan.ts"],"sourcesContent":["/**\n * Tick policy — pure mapping from a `Verdict` plus facts to an action.\n *\n * No I/O, no clock, no promises. `session/` executes the returned plan.\n */\n\nimport type { RoomRef, StreamRef, Verdict } from \"./verdict\"\n\nexport interface TickFacts {\n readonly recording: boolean\n readonly recordedSec: number\n readonly oneShot: boolean\n readonly consecutiveErrors: number\n}\n\nexport type TickPlan =\n | { kind: \"poll\"; note: string }\n | { kind: \"hold\"; reason: \"restricted\" | \"no-stream-url\"; room: RoomRef }\n | { kind: \"record\"; room: RoomRef; stream: StreamRef }\n | { kind: \"stop\"; why: \"one-shot\" | \"gave-up\" }\n\nexport function planTick(v: Verdict, f: TickFacts): TickPlan {\n // No user-stop arm: `stop()` aborts the scope, which ends the poll loop before\n // the next tick. A user stop is a signal, never a verdict.\n switch (v.reason) {\n case \"live\":\n if (f.recording) return { kind: \"poll\", note: \"already recording\" }\n if (!v.room || !v.stream) return { kind: \"poll\", note: \"live without refs\" }\n return { kind: \"record\", room: v.room, stream: v.stream }\n\n case \"no-stream-url\":\n case \"restricted\":\n if (!v.room) return { kind: \"poll\", note: \"missing room\" }\n return { kind: \"hold\", reason: v.reason, room: v.room }\n\n case \"offline\":\n return f.oneShot && f.recordedSec > 0\n ? { kind: \"stop\", why: \"one-shot\" }\n : { kind: \"poll\", note: \"offline\" }\n\n case \"no-room-id\":\n return f.consecutiveErrors >= 10\n ? { kind: \"stop\", why: \"gave-up\" }\n : { kind: \"poll\", note: \"no room\" }\n\n case \"error\":\n return { kind: \"poll\", note: v.failure?.message ?? \"error\" }\n }\n}\n"],"mappings":";AAqBA,SAAgB,SAAS,GAAY,GAAwB;CAG3D,QAAQ,EAAE,QAAV;EACE,KAAK;GACH,IAAI,EAAE,WAAW,OAAO;IAAE,MAAM;IAAQ,MAAM;GAAoB;GAClE,IAAI,CAAC,EAAE,QAAQ,CAAC,EAAE,QAAQ,OAAO;IAAE,MAAM;IAAQ,MAAM;GAAoB;GAC3E,OAAO;IAAE,MAAM;IAAU,MAAM,EAAE;IAAM,QAAQ,EAAE;GAAO;EAE1D,KAAK;EACL,KAAK;GACH,IAAI,CAAC,EAAE,MAAM,OAAO;IAAE,MAAM;IAAQ,MAAM;GAAe;GACzD,OAAO;IAAE,MAAM;IAAQ,QAAQ,EAAE;IAAQ,MAAM,EAAE;GAAK;EAExD,KAAK,WACH,OAAO,EAAE,WAAW,EAAE,cAAc,IAChC;GAAE,MAAM;GAAQ,KAAK;EAAW,IAChC;GAAE,MAAM;GAAQ,MAAM;EAAU;EAEtC,KAAK,cACH,OAAO,EAAE,qBAAqB,KAC1B;GAAE,MAAM;GAAQ,KAAK;EAAU,IAC/B;GAAE,MAAM;GAAQ,MAAM;EAAU;EAEtC,KAAK,SACH,OAAO;GAAE,MAAM;GAAQ,MAAM,EAAE,SAAS,WAAW;EAAQ;CAC/D;AACF"}
1
+ {"version":3,"file":"plan.mjs","names":[],"sources":["../../src/core/plan.ts"],"sourcesContent":["/**\n * Tick policy — pure mapping from a `Verdict` plus facts to an action.\n *\n * No I/O, no clock, no promises. `app/recorder.ts` executes the returned plan.\n */\n\nimport type { RoomRef, StreamRef, Verdict } from \"./verdict\"\n\nexport interface TickFacts {\n readonly recording: boolean\n readonly recordedSec: number\n readonly oneShot: boolean\n readonly consecutiveErrors: number\n}\n\nexport type TickPlan =\n | { kind: \"poll\"; note: string }\n | { kind: \"hold\"; reason: \"restricted\" | \"no-stream-url\"; room: RoomRef }\n | { kind: \"record\"; room: RoomRef; stream: StreamRef }\n | { kind: \"stop\"; why: \"one-shot\" | \"gave-up\" }\n\nexport function planTick(v: Verdict, f: TickFacts): TickPlan {\n // No user-stop arm: `stop()` aborts the scope, which ends the poll loop before\n // the next tick. A user stop is a signal, never a verdict.\n switch (v.reason) {\n case \"live\":\n if (f.recording) return { kind: \"poll\", note: \"already recording\" }\n if (!v.room || !v.stream) return { kind: \"poll\", note: \"live without refs\" }\n return { kind: \"record\", room: v.room, stream: v.stream }\n\n case \"no-stream-url\":\n case \"restricted\":\n if (!v.room) return { kind: \"poll\", note: \"missing room\" }\n return { kind: \"hold\", reason: v.reason, room: v.room }\n\n case \"offline\":\n return f.oneShot && f.recordedSec > 0\n ? { kind: \"stop\", why: \"one-shot\" }\n : { kind: \"poll\", note: \"offline\" }\n\n case \"no-room-id\":\n return f.consecutiveErrors >= 10\n ? { kind: \"stop\", why: \"gave-up\" }\n : { kind: \"poll\", note: \"no room\" }\n\n case \"error\":\n return { kind: \"poll\", note: v.failure?.message ?? \"error\" }\n }\n}\n"],"mappings":";AAqBA,SAAgB,SAAS,GAAY,GAAwB;CAG3D,QAAQ,EAAE,QAAV;EACE,KAAK;GACH,IAAI,EAAE,WAAW,OAAO;IAAE,MAAM;IAAQ,MAAM;GAAoB;GAClE,IAAI,CAAC,EAAE,QAAQ,CAAC,EAAE,QAAQ,OAAO;IAAE,MAAM;IAAQ,MAAM;GAAoB;GAC3E,OAAO;IAAE,MAAM;IAAU,MAAM,EAAE;IAAM,QAAQ,EAAE;GAAO;EAE1D,KAAK;EACL,KAAK;GACH,IAAI,CAAC,EAAE,MAAM,OAAO;IAAE,MAAM;IAAQ,MAAM;GAAe;GACzD,OAAO;IAAE,MAAM;IAAQ,QAAQ,EAAE;IAAQ,MAAM,EAAE;GAAK;EAExD,KAAK,WACH,OAAO,EAAE,WAAW,EAAE,cAAc,IAChC;GAAE,MAAM;GAAQ,KAAK;EAAW,IAChC;GAAE,MAAM;GAAQ,MAAM;EAAU;EAEtC,KAAK,cACH,OAAO,EAAE,qBAAqB,KAC1B;GAAE,MAAM;GAAQ,KAAK;EAAU,IAC/B;GAAE,MAAM;GAAQ,MAAM;EAAU;EAEtC,KAAK,SACH,OAAO;GAAE,MAAM;GAAQ,MAAM,EAAE,SAAS,WAAW;EAAQ;CAC/D;AACF"}
@@ -2,7 +2,7 @@
2
2
  /**
3
3
  * Verdict — the per-tick liveness result and its machine-readable reason.
4
4
  *
5
- * Pure domain type: no I/O, no imports outside `domain/`. `reason` is derived
5
+ * Pure domain type: no I/O, no imports outside `core/`. `reason` is derived
6
6
  * by `verdictOf`, never passed by callers; discovery reports facts, one total
7
7
  * function decides what they mean.
8
8
  */
@@ -1 +1 @@
1
- {"version":3,"file":"verdict.mjs","names":[],"sources":["../../src/core/verdict.ts"],"sourcesContent":["/**\n * Verdict — the per-tick liveness result and its machine-readable reason.\n *\n * Pure domain type: no I/O, no imports outside `domain/`. `reason` is derived\n * by `verdictOf`, never passed by callers; discovery reports facts, one total\n * function decides what they mean.\n */\n\n/**\n * Machine-readable reason for a LIVE status verdict.\n * \"live\" = stream URL resolved; \"offline\" = room not live;\n * \"restricted\" = live but age-protected/gated (stream refused);\n * \"no-stream-url\" = live but no URL and no gate evidence;\n * \"no-room-id\" = no discovery path produced a room ID;\n * \"error\" = network/parse failure across paths.\n */\nexport type LiveReason =\n | \"live\"\n | \"offline\"\n | \"restricted\"\n | \"no-stream-url\"\n | \"no-room-id\"\n | \"error\"\n\nexport interface RoomRef {\n readonly id: string\n readonly title: string | null\n readonly live: boolean\n}\n\nexport interface StreamRef {\n readonly url: string\n}\n\n/** Where a fact came from. Legacy `LiveInfo.source` values stay valid. */\nexport type SourceId = \"page\" | \"sigi\" | \"room-info\" | \"api-live\" | \"profile\" | \"none\"\n\nexport type EvidenceOutcome = \"hit\" | \"miss\" | \"denied\" | \"error\"\n\nexport interface Evidence {\n readonly source: SourceId\n readonly outcome: EvidenceOutcome\n}\n\nexport interface Verdict {\n readonly reason: LiveReason\n readonly room: RoomRef | null\n readonly stream: StreamRef | null\n readonly evidence: readonly Evidence[]\n readonly failure: Error | null\n}\n\n/** Whether a reason means the room itself is live (holding or recording). */\nexport function isLiveReason(reason: LiveReason): boolean {\n return reason === \"live\" || reason === \"restricted\" || reason === \"no-stream-url\"\n}\n\n/**\n * The single constructor for `Verdict`. Six branches cover every reason;\n * precedence is failure → no room → offline → denied → live → no URL.\n */\nexport function verdictOf(x: {\n room?: RoomRef | null\n stream?: StreamRef | null\n denied?: boolean\n failure?: Error | null\n evidence?: readonly Evidence[]\n}): Verdict {\n const room = x.room ?? null\n const stream = x.stream ?? null\n const base = { room, stream, evidence: x.evidence ?? [], failure: x.failure ?? null }\n\n if (x.failure) return { ...base, reason: \"error\" }\n if (!room) return { ...base, reason: \"no-room-id\" }\n if (!room.live) return { ...base, reason: \"offline\" }\n if (x.denied) return { ...base, reason: \"restricted\" }\n if (stream) return { ...base, reason: \"live\" }\n return { ...base, reason: \"no-stream-url\" }\n}\n"],"mappings":";;AAqDA,SAAgB,aAAa,QAA6B;CACxD,OAAO,WAAW,UAAU,WAAW,gBAAgB,WAAW;AACpE;;;;;AAMA,SAAgB,UAAU,GAMd;CACV,MAAM,OAAO,EAAE,QAAQ;CACvB,MAAM,SAAS,EAAE,UAAU;CAC3B,MAAM,OAAO;EAAE;EAAM;EAAQ,UAAU,EAAE,YAAY,CAAC;EAAG,SAAS,EAAE,WAAW;CAAK;CAEpF,IAAI,EAAE,SAAS,OAAO;EAAE,GAAG;EAAM,QAAQ;CAAQ;CACjD,IAAI,CAAC,MAAM,OAAO;EAAE,GAAG;EAAM,QAAQ;CAAa;CAClD,IAAI,CAAC,KAAK,MAAM,OAAO;EAAE,GAAG;EAAM,QAAQ;CAAU;CACpD,IAAI,EAAE,QAAQ,OAAO;EAAE,GAAG;EAAM,QAAQ;CAAa;CACrD,IAAI,QAAQ,OAAO;EAAE,GAAG;EAAM,QAAQ;CAAO;CAC7C,OAAO;EAAE,GAAG;EAAM,QAAQ;CAAgB;AAC5C"}
1
+ {"version":3,"file":"verdict.mjs","names":[],"sources":["../../src/core/verdict.ts"],"sourcesContent":["/**\n * Verdict — the per-tick liveness result and its machine-readable reason.\n *\n * Pure domain type: no I/O, no imports outside `core/`. `reason` is derived\n * by `verdictOf`, never passed by callers; discovery reports facts, one total\n * function decides what they mean.\n */\n\n/**\n * Machine-readable reason for a LIVE status verdict.\n * \"live\" = stream URL resolved; \"offline\" = room not live;\n * \"restricted\" = live but age-protected/gated (stream refused);\n * \"no-stream-url\" = live but no URL and no gate evidence;\n * \"no-room-id\" = no discovery path produced a room ID;\n * \"error\" = network/parse failure across paths.\n */\nexport type LiveReason =\n | \"live\"\n | \"offline\"\n | \"restricted\"\n | \"no-stream-url\"\n | \"no-room-id\"\n | \"error\"\n\nexport interface RoomRef {\n readonly id: string\n readonly title: string | null\n readonly live: boolean\n}\n\nexport interface StreamRef {\n readonly url: string\n}\n\n/** Where a fact came from. Legacy `LiveInfo.source` values stay valid. */\nexport type SourceId = \"page\" | \"sigi\" | \"room-info\" | \"api-live\" | \"profile\" | \"none\"\n\nexport type EvidenceOutcome = \"hit\" | \"miss\" | \"denied\" | \"error\"\n\nexport interface Evidence {\n readonly source: SourceId\n readonly outcome: EvidenceOutcome\n}\n\nexport interface Verdict {\n readonly reason: LiveReason\n readonly room: RoomRef | null\n readonly stream: StreamRef | null\n readonly evidence: readonly Evidence[]\n readonly failure: Error | null\n}\n\n/** Whether a reason means the room itself is live (holding or recording). */\nexport function isLiveReason(reason: LiveReason): boolean {\n return reason === \"live\" || reason === \"restricted\" || reason === \"no-stream-url\"\n}\n\n/**\n * The single constructor for `Verdict`. Six branches cover every reason;\n * precedence is failure → no room → offline → denied → live → no URL.\n */\nexport function verdictOf(x: {\n room?: RoomRef | null\n stream?: StreamRef | null\n denied?: boolean\n failure?: Error | null\n evidence?: readonly Evidence[]\n}): Verdict {\n const room = x.room ?? null\n const stream = x.stream ?? null\n const base = { room, stream, evidence: x.evidence ?? [], failure: x.failure ?? null }\n\n if (x.failure) return { ...base, reason: \"error\" }\n if (!room) return { ...base, reason: \"no-room-id\" }\n if (!room.live) return { ...base, reason: \"offline\" }\n if (x.denied) return { ...base, reason: \"restricted\" }\n if (stream) return { ...base, reason: \"live\" }\n return { ...base, reason: \"no-stream-url\" }\n}\n"],"mappings":";;AAqDA,SAAgB,aAAa,QAA6B;CACxD,OAAO,WAAW,UAAU,WAAW,gBAAgB,WAAW;AACpE;;;;;AAMA,SAAgB,UAAU,GAMd;CACV,MAAM,OAAO,EAAE,QAAQ;CACvB,MAAM,SAAS,EAAE,UAAU;CAC3B,MAAM,OAAO;EAAE;EAAM;EAAQ,UAAU,EAAE,YAAY,CAAC;EAAG,SAAS,EAAE,WAAW;CAAK;CAEpF,IAAI,EAAE,SAAS,OAAO;EAAE,GAAG;EAAM,QAAQ;CAAQ;CACjD,IAAI,CAAC,MAAM,OAAO;EAAE,GAAG;EAAM,QAAQ;CAAa;CAClD,IAAI,CAAC,KAAK,MAAM,OAAO;EAAE,GAAG;EAAM,QAAQ;CAAU;CACpD,IAAI,EAAE,QAAQ,OAAO;EAAE,GAAG;EAAM,QAAQ;CAAa;CACrD,IAAI,QAAQ,OAAO;EAAE,GAAG;EAAM,QAAQ;CAAO;CAC7C,OAAO;EAAE,GAAG;EAAM,QAAQ;CAAgB;AAC5C"}
package/dist/io/http.mjs CHANGED
@@ -32,7 +32,21 @@ async function createHttpClient(config) {
32
32
  "https://webcast.tiktok.com",
33
33
  "https://m.tiktok.com"
34
34
  ]) for (const [name, value] of Object.entries(config.cookies)) session.setCookie(name, value, domain);
35
- const rateLimiter = createRateLimiter(config.ratePerSecond ?? 5);
35
+ const minIntervalMs = config.ratePerSecond ? 1e3 / config.ratePerSecond : 0;
36
+ let lastTokenTime = 0;
37
+ /** Wait for the next rate-limit token, abort-aware so a stop does not wait one out. */
38
+ async function waitForToken(signal) {
39
+ if (minIntervalMs <= 0 || signal.aborted) return;
40
+ const waitTime = Math.max(0, lastTokenTime + minIntervalMs - Date.now());
41
+ if (waitTime > 0) await new Promise((resolve) => {
42
+ const timer = setTimeout(resolve, waitTime);
43
+ signal.addEventListener("abort", () => {
44
+ clearTimeout(timer);
45
+ resolve();
46
+ }, { once: true });
47
+ });
48
+ lastTokenTime = Date.now();
49
+ }
36
50
  async function rateLimitedFetch(url, options, external) {
37
51
  const controller = new AbortController();
38
52
  const onAbort = () => controller.abort(external?.reason);
@@ -40,7 +54,7 @@ async function createHttpClient(config) {
40
54
  else external?.addEventListener("abort", onAbort, { once: true });
41
55
  const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
42
56
  try {
43
- await rateLimiter.acquire(controller.signal);
57
+ await waitForToken(controller.signal);
44
58
  return await session.fetch(url, {
45
59
  method: options?.method,
46
60
  body: options?.body,
@@ -70,28 +84,6 @@ async function createHttpClient(config) {
70
84
  }
71
85
  };
72
86
  }
73
- /**
74
- * Token bucket: a minimum interval between requests. `0` or less is unlimited.
75
- * Abort-aware, so a stop does not wait out a pending token.
76
- */
77
- function createRateLimiter(tokensPerSecond) {
78
- if (tokensPerSecond <= 0) return { acquire: async () => {} };
79
- const MIN_INTERVAL_MS = 1e3 / tokensPerSecond;
80
- let lastTokenTime = 0;
81
- return { async acquire(signal) {
82
- if (signal?.aborted) return;
83
- const now = Date.now();
84
- const waitTime = Math.max(0, lastTokenTime + MIN_INTERVAL_MS - now);
85
- if (waitTime > 0) await new Promise((resolve) => {
86
- const timer = setTimeout(resolve, waitTime);
87
- if (signal) signal.addEventListener("abort", () => {
88
- clearTimeout(timer);
89
- resolve();
90
- }, { once: true });
91
- });
92
- lastTokenTime = Date.now();
93
- } };
94
- }
95
87
  //#endregion
96
88
  export { createHttpClient };
97
89
 
@@ -1 +1 @@
1
- {"version":3,"file":"http.mjs","names":[],"sources":["../../src/io/http.ts"],"sourcesContent":["/**\n * HTTP — the transport layer in one file: the wreq-js session (TLS fingerprint\n * impersonation, cookie jar, proxy) and the token-bucket rate limiter that\n * keeps polling from tripping TikTok's WAF.\n *\n * This file owns the `HttpClient` contract: it is the seam every adapter and\n * `test/utils/mock-http.ts` implement. There is no second definition.\n */\n\nimport { createSession, type Session } from \"wreq-js\"\nimport type { RecorderConfig } from \"../app/config\"\n\n// BodyInit is only available inside declare module \"bun\" in bun-types, not as a global\n// under the ES2022 lib. We explicitly import it to keep core/ focused on ES2022.\nexport type HttpBody = import(\"bun\").BodyInit\n\nexport interface HttpClient {\n get: (url: string, signal?: AbortSignal) => Promise<Response>\n post: (\n url: string,\n body?: HttpBody,\n headers?: Record<string, string>,\n signal?: AbortSignal,\n ) => Promise<Response>\n close: () => Promise<void>\n}\n\nconst REQUEST_TIMEOUT_MS = 15_000\n\n/** Standard browser headers to avoid TikTok WAF detection. */\nconst BROWSER_HEADERS: Record<string, string> = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:149.0) Gecko/20100101 Firefox/149.0\",\n Accept: \"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8\",\n \"Accept-Language\": \"en-US,en;q=0.5\",\n \"Accept-Encoding\": \"gzip, deflate, br\",\n \"Upgrade-Insecure-Requests\": \"1\",\n \"Sec-Fetch-Dest\": \"document\",\n \"Sec-Fetch-Mode\": \"navigate\",\n \"Sec-Fetch-Site\": \"none\",\n \"Sec-Fetch-User\": \"?1\",\n}\n\nexport async function createHttpClient(config: RecorderConfig): Promise<HttpClient> {\n const session: Session = await createSession({\n browser: \"firefox_149\",\n os: \"windows\",\n proxy: config.proxy,\n })\n\n // Seed cookies into the session jar so all subsequent requests are authenticated.\n // NOTE: Using a Cookie header does NOT populate wreq-js's cookie jar —\n // we must use session.setCookie() instead.\n // Seed for all TikTok domains since cookies may not propagate across\n // subdomains automatically in wreq-js's cookie jar.\n if (config.cookies && \"sessionid_ss\" in config.cookies) {\n const domains = [\"https://www.tiktok.com\", \"https://webcast.tiktok.com\", \"https://m.tiktok.com\"]\n for (const domain of domains) {\n for (const [name, value] of Object.entries(config.cookies)) {\n session.setCookie(name, value, domain)\n }\n }\n }\n\n const rateLimiter = createRateLimiter(config.ratePerSecond ?? 5)\n\n async function rateLimitedFetch(\n url: string,\n options?: { method?: string; body?: unknown; headers?: Record<string, string> },\n external?: AbortSignal,\n ): Promise<Response> {\n const controller = new AbortController()\n const onAbort = () => controller.abort(external?.reason)\n if (external?.aborted) controller.abort(external.reason)\n else external?.addEventListener(\"abort\", onAbort, { once: true })\n const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS)\n try {\n await rateLimiter.acquire(controller.signal)\n const res = await session.fetch(url, {\n method: options?.method,\n body: options?.body as never,\n headers: {\n ...BROWSER_HEADERS,\n ...options?.headers,\n },\n signal: controller.signal,\n })\n // SAFETY: wreq-js returns its own Response-compatible object; the port only\n // needs the standard `status`, `ok`, and `text()` surface.\n return res as unknown as Response\n } finally {\n clearTimeout(timeout)\n external?.removeEventListener(\"abort\", onAbort)\n }\n }\n\n return {\n get: async (url: string, signal?: AbortSignal) => rateLimitedFetch(url, undefined, signal),\n post: async (\n url: string,\n body?: HttpBody,\n headers?: Record<string, string>,\n signal?: AbortSignal,\n ) =>\n rateLimitedFetch(\n url,\n {\n method: \"POST\",\n body: body as never,\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded; charset=UTF-8\",\n ...headers,\n },\n },\n signal,\n ),\n close: async () => {\n await session.close()\n },\n }\n}\n\n// ─── rate limiting ─────────────────────────────────────────\n\ninterface RateLimiter {\n /** Wait until a rate-limit token is available, then consume it. */\n acquire(signal?: AbortSignal): Promise<void>\n}\n\n/**\n * Token bucket: a minimum interval between requests. `0` or less is unlimited.\n * Abort-aware, so a stop does not wait out a pending token.\n */\nfunction createRateLimiter(tokensPerSecond: number): RateLimiter {\n if (tokensPerSecond <= 0) {\n return { acquire: async () => {} }\n }\n\n const MIN_INTERVAL_MS = 1000 / tokensPerSecond\n let lastTokenTime = 0\n\n return {\n async acquire(signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) return\n\n const now = Date.now()\n const waitTime = Math.max(0, lastTokenTime + MIN_INTERVAL_MS - now)\n\n if (waitTime > 0) {\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, waitTime)\n if (signal) {\n signal.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timer)\n resolve()\n },\n { once: true },\n )\n }\n })\n }\n\n lastTokenTime = Date.now()\n },\n }\n}\n"],"mappings":";;;;;;;;;;AA2BA,MAAM,qBAAqB;;AAG3B,MAAM,kBAA0C;CAC9C,cAAc;CACd,QAAQ;CACR,mBAAmB;CACnB,mBAAmB;CACnB,6BAA6B;CAC7B,kBAAkB;CAClB,kBAAkB;CAClB,kBAAkB;CAClB,kBAAkB;AACpB;AAEA,eAAsB,iBAAiB,QAA6C;CAClF,MAAM,UAAmB,MAAM,cAAc;EAC3C,SAAS;EACT,IAAI;EACJ,OAAO,OAAO;CAChB,CAAC;CAOD,IAAI,OAAO,WAAW,kBAAkB,OAAO,SAE7C,KAAK,MAAM,UAAU;EADJ;EAA0B;EAA8B;CAC9C,GACzB,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,OAAO,OAAO,GACvD,QAAQ,UAAU,MAAM,OAAO,MAAM;CAK3C,MAAM,cAAc,kBAAkB,OAAO,iBAAiB,CAAC;CAE/D,eAAe,iBACb,KACA,SACA,UACmB;EACnB,MAAM,aAAa,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AAC;EAGH,gBAAgB,KAAK,IAAI;CAC3B,EACF;AACF"}
1
+ {"version":3,"file":"http.mjs","names":[],"sources":["../../src/io/http.ts"],"sourcesContent":["/**\n * HTTP — the transport layer in one file: the wreq-js session (TLS fingerprint\n * impersonation, cookie jar, proxy) and the token-bucket rate limiter that\n * keeps polling from tripping TikTok's WAF.\n *\n * This file owns the `HttpClient` contract: it is the seam every adapter and\n * `test/utils/mock-http.ts` implement. There is no second definition.\n */\n\nimport { createSession, type Session } from \"wreq-js\"\nimport type { RecorderConfig } from \"../app/config\"\n\n// BodyInit is only available inside declare module \"bun\" in bun-types, not as a global\n// under the ES2022 lib. We explicitly import it to keep core/ focused on ES2022.\nexport type HttpBody = import(\"bun\").BodyInit\n\nexport interface HttpClient {\n get: (url: string, signal?: AbortSignal) => Promise<Response>\n post: (\n url: string,\n body?: HttpBody,\n headers?: Record<string, string>,\n signal?: AbortSignal,\n ) => Promise<Response>\n close: () => Promise<void>\n}\n\nconst REQUEST_TIMEOUT_MS = 15_000\n\n/** Standard browser headers to avoid TikTok WAF detection. */\nconst BROWSER_HEADERS: Record<string, string> = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:149.0) Gecko/20100101 Firefox/149.0\",\n Accept: \"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8\",\n \"Accept-Language\": \"en-US,en;q=0.5\",\n \"Accept-Encoding\": \"gzip, deflate, br\",\n \"Upgrade-Insecure-Requests\": \"1\",\n \"Sec-Fetch-Dest\": \"document\",\n \"Sec-Fetch-Mode\": \"navigate\",\n \"Sec-Fetch-Site\": \"none\",\n \"Sec-Fetch-User\": \"?1\",\n}\n\nexport async function createHttpClient(config: RecorderConfig): Promise<HttpClient> {\n const session: Session = await createSession({\n browser: \"firefox_149\",\n os: \"windows\",\n proxy: config.proxy,\n })\n\n // Seed cookies into the session jar so all subsequent requests are authenticated.\n // NOTE: Using a Cookie header does NOT populate wreq-js's cookie jar —\n // we must use session.setCookie() instead.\n // Seed for all TikTok domains since cookies may not propagate across\n // subdomains automatically in wreq-js's cookie jar.\n if (config.cookies && \"sessionid_ss\" in config.cookies) {\n const domains = [\"https://www.tiktok.com\", \"https://webcast.tiktok.com\", \"https://m.tiktok.com\"]\n for (const domain of domains) {\n for (const [name, value] of Object.entries(config.cookies)) {\n session.setCookie(name, value, domain)\n }\n }\n }\n\n // Token bucket: a minimum interval between requests. `0` or less is unlimited.\n const minIntervalMs = config.ratePerSecond ? 1000 / config.ratePerSecond : 0\n let lastTokenTime = 0\n\n /** Wait for the next rate-limit token, abort-aware so a stop does not wait one out. */\n async function waitForToken(signal: AbortSignal): Promise<void> {\n if (minIntervalMs <= 0 || signal.aborted) return\n const waitTime = Math.max(0, lastTokenTime + minIntervalMs - Date.now())\n if (waitTime > 0) {\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, waitTime)\n signal.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timer)\n resolve()\n },\n { once: true },\n )\n })\n }\n lastTokenTime = Date.now()\n }\n\n async function rateLimitedFetch(\n url: string,\n options?: { method?: string; body?: unknown; headers?: Record<string, string> },\n external?: AbortSignal,\n ): Promise<Response> {\n const controller = new AbortController()\n const onAbort = () => controller.abort(external?.reason)\n if (external?.aborted) controller.abort(external.reason)\n else external?.addEventListener(\"abort\", onAbort, { once: true })\n const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS)\n try {\n await waitForToken(controller.signal)\n const res = await session.fetch(url, {\n method: options?.method,\n body: options?.body as never,\n headers: {\n ...BROWSER_HEADERS,\n ...options?.headers,\n },\n signal: controller.signal,\n })\n // SAFETY: wreq-js returns its own Response-compatible object; the port only\n // needs the standard `status`, `ok`, and `text()` surface.\n return res as unknown as Response\n } finally {\n clearTimeout(timeout)\n external?.removeEventListener(\"abort\", onAbort)\n }\n }\n\n return {\n get: async (url: string, signal?: AbortSignal) => rateLimitedFetch(url, undefined, signal),\n post: async (\n url: string,\n body?: HttpBody,\n headers?: Record<string, string>,\n signal?: AbortSignal,\n ) =>\n rateLimitedFetch(\n url,\n {\n method: \"POST\",\n body: body as never,\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded; charset=UTF-8\",\n ...headers,\n },\n },\n signal,\n ),\n close: async () => {\n await session.close()\n },\n }\n}\n"],"mappings":";;;;;;;;;;AA2BA,MAAM,qBAAqB;;AAG3B,MAAM,kBAA0C;CAC9C,cAAc;CACd,QAAQ;CACR,mBAAmB;CACnB,mBAAmB;CACnB,6BAA6B;CAC7B,kBAAkB;CAClB,kBAAkB;CAClB,kBAAkB;CAClB,kBAAkB;AACpB;AAEA,eAAsB,iBAAiB,QAA6C;CAClF,MAAM,UAAmB,MAAM,cAAc;EAC3C,SAAS;EACT,IAAI;EACJ,OAAO,OAAO;CAChB,CAAC;CAOD,IAAI,OAAO,WAAW,kBAAkB,OAAO,SAE7C,KAAK,MAAM,UAAU;EADJ;EAA0B;EAA8B;CAC9C,GACzB,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,OAAO,OAAO,GACvD,QAAQ,UAAU,MAAM,OAAO,MAAM;CAM3C,MAAM,gBAAgB,OAAO,gBAAgB,MAAO,OAAO,gBAAgB;CAC3E,IAAI,gBAAgB;;CAGpB,eAAe,aAAa,QAAoC;EAC9D,IAAI,iBAAiB,KAAK,OAAO,SAAS;EAC1C,MAAM,WAAW,KAAK,IAAI,GAAG,gBAAgB,gBAAgB,KAAK,IAAI,CAAC;EACvE,IAAI,WAAW,GACb,MAAM,IAAI,SAAe,YAAY;GACnC,MAAM,QAAQ,WAAW,SAAS,QAAQ;GAC1C,OAAO,iBACL,eACM;IACJ,aAAa,KAAK;IAClB,QAAQ;GACV,GACA,EAAE,MAAM,KAAK,CACf;EACF,CAAC;EAEH,gBAAgB,KAAK,IAAI;CAC3B;CAEA,eAAe,iBACb,KACA,SACA,UACmB;EACnB,MAAM,aAAa,IAAI,gBAAgB;EACvC,MAAM,gBAAgB,WAAW,MAAM,UAAU,MAAM;EACvD,IAAI,UAAU,SAAS,WAAW,MAAM,SAAS,MAAM;OAClD,UAAU,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;EAChE,MAAM,UAAU,iBAAiB,WAAW,MAAM,GAAG,kBAAkB;EACvE,IAAI;GACF,MAAM,aAAa,WAAW,MAAM;GAYpC,OAAO,MAXW,QAAQ,MAAM,KAAK;IACnC,QAAQ,SAAS;IACjB,MAAM,SAAS;IACf,SAAS;KACP,GAAG;KACH,GAAG,SAAS;IACd;IACA,QAAQ,WAAW;GACrB,CAAC;EAIH,UAAU;GACR,aAAa,OAAO;GACpB,UAAU,oBAAoB,SAAS,OAAO;EAChD;CACF;CAEA,OAAO;EACL,KAAK,OAAO,KAAa,WAAyB,iBAAiB,KAAK,KAAA,GAAW,MAAM;EACzF,MAAM,OACJ,KACA,MACA,SACA,WAEA,iBACE,KACA;GACE,QAAQ;GACF;GACN,SAAS;IACP,gBAAgB;IAChB,GAAG;GACL;EACF,GACA,MACF;EACF,OAAO,YAAY;GACjB,MAAM,QAAQ,MAAM;EACtB;CACF;AACF"}
@@ -1,6 +1,6 @@
1
1
  import { TikTokError } from "../../core/errors.mjs";
2
- import { findFfmpegPath, pipeFfmpegSegment } from "./ffmpeg.mjs";
3
2
  import { bytesToHuman, formatDuration, formatFilename } from "../../core/format.mjs";
3
+ import { findFfmpegPath, pipeFfmpegSegment } from "./ffmpeg.mjs";
4
4
  import { createWriteStream, mkdirSync, statSync } from "node:fs";
5
5
  import { join } from "node:path";
6
6
  //#region src/io/media/download.ts
@@ -1,15 +1,15 @@
1
1
  import { TikTokError } from "../../core/errors.mjs";
2
- import { statSync } from "node:fs";
2
+ import { statSync, unlinkSync } from "node:fs";
3
3
  import { spawn } from "node:child_process";
4
4
  import { execa } from "execa";
5
5
  //#region src/io/media/ffmpeg.ts
6
6
  /**
7
7
  * FFmpeg — the single home for process invocation.
8
8
  *
9
- * Two modes: `pipeFfmpegSegment` streams stdout into a `WriteStream` (live
10
- * capture), `runFfmpeg` runs to completion and returns stdout (remux,
11
- * segment). Locating the binary lives here too, so no caller reimplements a
12
- * PATH lookup.
9
+ * Two entry points: `pipeFfmpegSegment` streams stdout into a `WriteStream`
10
+ * (live capture) and `createMediaConverter` builds the remux/segment capability
11
+ * the job consumes. Locating the binary lives here too, so no caller
12
+ * reimplements a PATH lookup.
13
13
  */
14
14
  /** Kill FFmpeg if no output is received within this window after spawn. */
15
15
  const FFMPEG_STARTUP_TIMEOUT = 3e4;
@@ -46,6 +46,52 @@ async function runFfmpeg(args, signal) {
46
46
  throw new TikTokError("ffmpeg-error", `FFmpeg failed: ${err instanceof Error ? err.message : String(err)}`);
47
47
  }
48
48
  }
49
+ function createMediaConverter(logger, signal) {
50
+ async function convert(input) {
51
+ const output = input.replace(/\.(flv|ts)$/i, ".mp4");
52
+ logger?.info(`Converting: ${input} → ${output}`);
53
+ await runFfmpeg([
54
+ "-i",
55
+ input,
56
+ "-c",
57
+ "copy",
58
+ "-y",
59
+ output
60
+ ], signal);
61
+ try {
62
+ unlinkSync(input);
63
+ logger?.info(`Deleted original: ${input}`);
64
+ } catch {
65
+ logger?.warn(`Could not delete original: ${input}`);
66
+ }
67
+ return output;
68
+ }
69
+ async function segment(input, segmentSeconds, outputPattern) {
70
+ return runFfmpeg([
71
+ "-i",
72
+ input,
73
+ "-c",
74
+ "copy",
75
+ "-f",
76
+ "segment",
77
+ "-segment_time",
78
+ String(segmentSeconds),
79
+ "-reset_timestamps",
80
+ "1",
81
+ "-segment_start_number",
82
+ "1",
83
+ "-segment_list",
84
+ "pipe:1",
85
+ "-segment_list_type",
86
+ "csv",
87
+ outputPattern
88
+ ], signal);
89
+ }
90
+ return {
91
+ convert,
92
+ segment
93
+ };
94
+ }
49
95
  /**
50
96
  * Build FFmpeg HTTP option arguments for cookies and headers.
51
97
  * TikTok's CDN requires session cookies and a Referer to serve the stream.
@@ -151,6 +197,6 @@ async function pipeFfmpegSegment(ffmpegPath, url, writer, signal, maxDuration, c
151
197
  });
152
198
  }
153
199
  //#endregion
154
- export { findFfmpegPath, pipeFfmpegSegment, runFfmpeg };
200
+ export { createMediaConverter, findFfmpegPath, pipeFfmpegSegment };
155
201
 
156
202
  //# sourceMappingURL=ffmpeg.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"ffmpeg.mjs","names":[],"sources":["../../../src/io/media/ffmpeg.ts"],"sourcesContent":["/**\n * FFmpeg — the single home for process invocation.\n *\n * Two modes: `pipeFfmpegSegment` streams stdout into a `WriteStream` (live\n * capture), `runFfmpeg` runs to completion and returns stdout (remux,\n * segment). Locating the binary lives here too, so no caller reimplements a\n * PATH lookup.\n */\n\nimport { type ChildProcess, spawn } from \"node:child_process\"\nimport type { WriteStream } from \"node:fs\"\nimport { statSync } from \"node:fs\"\nimport { execa } from \"execa\"\nimport { TikTokError } from \"../../core/errors\"\n\n/** Kill FFmpeg if no output is received within this window after spawn. */\nexport const FFMPEG_STARTUP_TIMEOUT = 30_000\n\n/** Find the FFmpeg binary via `Bun.which()` or a PATH search. */\nexport function findFfmpegPath(): string | null {\n const bunWhich = (globalThis as { Bun?: { which?: (cmd: string) => string | null } }).Bun?.which\n if (typeof bunWhich === \"function\") {\n return (bunWhich(\"ffmpeg\") as string) ?? null\n }\n const paths = process.env.PATH?.split(\":\") ?? []\n for (const dir of paths) {\n try {\n const full = `${dir}/ffmpeg`\n statSync(full)\n return full\n } catch {\n // not found in this directory\n }\n }\n return null\n}\n\n/**\n * Run FFmpeg to completion and return stdout — for output that is a file\n * rather than a pipe (the segment muxer's `-segment_list pipe:1`).\n */\nexport async function runFfmpeg(args: string[], signal?: AbortSignal): Promise<string> {\n const ffmpegPath = findFfmpegPath()\n if (!ffmpegPath) {\n throw new TikTokError(\n \"ffmpeg-not-found\",\n \"FFmpeg not found. Install it:\\n\" +\n \" Linux: apt install ffmpeg / brew install ffmpeg / pacman -S ffmpeg\\n\" +\n \" macOS: brew install ffmpeg\\n\" +\n \" Windows: choco install ffmpeg\",\n )\n }\n try {\n const result = await execa(ffmpegPath, args, {\n cancelSignal: signal,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n })\n return result.stdout ?? \"\"\n } catch (err: unknown) {\n if (signal?.aborted) {\n throw new TikTokError(\"aborted\", \"Aborted by user\")\n }\n const message = err instanceof Error ? err.message : String(err)\n throw new TikTokError(\"ffmpeg-error\", `FFmpeg failed: ${message}`)\n }\n}\n\n/**\n * Build FFmpeg HTTP option arguments for cookies and headers.\n * TikTok's CDN requires session cookies and a Referer to serve the stream.\n */\nfunction buildHttpArgs(cookies?: Record<string, string>): string[] {\n const args: string[] = []\n\n // ponytail: user-agent header, CDNs tend to be picky\n args.push(\n \"-user_agent\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:149.0) Gecko/20100101 Firefox/149.0\",\n )\n args.push(\"-headers\", \"Referer: https://www.tiktok.com/\\r\\n\")\n\n if (cookies && Object.keys(cookies).length > 0) {\n const cookieStr = Object.entries(cookies)\n .map(([k, v]) => `${k}=${v}`)\n .join(\"\\r\\n\")\n args.push(\"-cookies\", cookieStr)\n }\n\n return args\n}\n\n/** Standard FFmpeg reconnect + mpegts pipe arguments. */\nconst FFMPEG_BASE_ARGS = [\n \"-reconnect\",\n \"1\",\n \"-reconnect_at_eof\",\n \"1\",\n \"-reconnect_streamed\",\n \"1\",\n \"-reconnect_delay_max\",\n \"5\",\n \"-c\",\n \"copy\",\n \"-f\",\n \"mpegts\",\n \"pipe:1\",\n]\n\n/**\n * Spawn an FFmpeg process to download from `url` and pipe its stdout to\n * `writer` with backpressure handling.\n *\n * Uses child_process.spawn directly (not execa) because execa v9 defaults\n * to encoding stdout as UTF-8, which corrupts binary MPEG-TS data.\n */\nexport async function pipeFfmpegSegment(\n ffmpegPath: string,\n url: string,\n writer: WriteStream,\n signal: AbortSignal,\n maxDuration?: number,\n cookies?: Record<string, string>,\n): Promise<void> {\n const durationArgs = maxDuration ? [\"-t\", String(maxDuration)] : []\n const httpArgs = buildHttpArgs(cookies)\n // ponytail: input options (-headers, -cookies, -user_agent) must come before -i\n const args = [...httpArgs, \"-i\", url, ...durationArgs, ...FFMPEG_BASE_ARGS]\n const proc: ChildProcess = spawn(ffmpegPath, args, {\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n })\n\n let stderr = \"\"\n let firstDataTimer: ReturnType<typeof setTimeout> | null = null\n\n const clearStartupTimer = () => {\n if (firstDataTimer) {\n clearTimeout(firstDataTimer)\n firstDataTimer = null\n }\n }\n\n // Forward abort signal to process\n const onAbort = () => {\n if (!proc.killed) proc.kill(\"SIGTERM\")\n }\n signal.addEventListener(\"abort\", onAbort, { once: true })\n\n proc.stderr?.on(\"data\", (chunk: Buffer) => {\n clearStartupTimer()\n stderr += chunk.toString()\n if (stderr.length > 10000) stderr = stderr.slice(-5000)\n })\n\n proc.stdout?.on(\"data\", (chunk: Buffer) => {\n clearStartupTimer()\n const canContinue = writer.write(chunk)\n if (!canContinue) {\n proc.stdout?.pause()\n writer.once(\"drain\", () => proc.stdout?.resume())\n }\n })\n\n await new Promise<void>((resolve, reject) => {\n firstDataTimer = setTimeout(() => {\n if (!proc.killed) {\n proc.kill(\"SIGTERM\")\n setTimeout(() => {\n if (!proc.killed) proc.kill(\"SIGKILL\")\n }, 2000)\n }\n reject(\n new TikTokError(\n \"ffmpeg-error\",\n `FFmpeg startup timed out after ${FFMPEG_STARTUP_TIMEOUT / 1000}s\\n${stderr.slice(-500)}`,\n ),\n )\n }, FFMPEG_STARTUP_TIMEOUT)\n\n proc.on(\"close\", (code) => {\n clearStartupTimer()\n signal.removeEventListener(\"abort\", onAbort)\n if (signal.aborted) {\n resolve()\n return\n }\n if (code === 0 || code === null) {\n resolve()\n return\n }\n reject(\n new TikTokError(\"ffmpeg-error\", `FFmpeg exited with code ${code}\\n${stderr.slice(-500)}`),\n )\n })\n\n proc.on(\"error\", (err) => {\n clearStartupTimer()\n signal.removeEventListener(\"abort\", onAbort)\n reject(err)\n })\n })\n}\n"],"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,SAAS;IAClB,QAAQ;IACR;GACF;GACA,IAAI,SAAS,KAAK,SAAS,MAAM;IAC/B,QAAQ;IACR;GACF;GACA,OACE,IAAI,YAAY,gBAAgB,2BAA2B,KAAK,IAAI,OAAO,MAAM,IAAI,GAAG,CAC1F;EACF,CAAC;EAED,KAAK,GAAG,UAAU,QAAQ;GACxB,kBAAkB;GAClB,OAAO,oBAAoB,SAAS,OAAO;GAC3C,OAAO,GAAG;EACZ,CAAC;CACH,CAAC;AACH"}
1
+ {"version":3,"file":"ffmpeg.mjs","names":[],"sources":["../../../src/io/media/ffmpeg.ts"],"sourcesContent":["/**\n * FFmpeg — the single home for process invocation.\n *\n * Two entry points: `pipeFfmpegSegment` streams stdout into a `WriteStream`\n * (live capture) and `createMediaConverter` builds the remux/segment capability\n * the job consumes. Locating the binary lives here too, so no caller\n * reimplements a PATH lookup.\n */\n\nimport { type ChildProcess, spawn } from \"node:child_process\"\nimport type { WriteStream } from \"node:fs\"\nimport { statSync, unlinkSync } from \"node:fs\"\nimport { execa } from \"execa\"\nimport { TikTokError } from \"../../core/errors\"\nimport type { Logger } from \"../../core/log\"\n\n/** Kill FFmpeg if no output is received within this window after spawn. */\nconst FFMPEG_STARTUP_TIMEOUT = 30_000\n\n/** Find the FFmpeg binary via `Bun.which()` or a PATH search. */\nexport function findFfmpegPath(): string | null {\n const bunWhich = (globalThis as { Bun?: { which?: (cmd: string) => string | null } }).Bun?.which\n if (typeof bunWhich === \"function\") {\n return (bunWhich(\"ffmpeg\") as string) ?? null\n }\n const paths = process.env.PATH?.split(\":\") ?? []\n for (const dir of paths) {\n try {\n const full = `${dir}/ffmpeg`\n statSync(full)\n return full\n } catch {\n // not found in this directory\n }\n }\n return null\n}\n\n/**\n * Run FFmpeg to completion and return stdout — for output that is a file\n * rather than a pipe (the segment muxer's `-segment_list pipe:1`).\n */\nasync function runFfmpeg(args: string[], signal?: AbortSignal): Promise<string> {\n const ffmpegPath = findFfmpegPath()\n if (!ffmpegPath) {\n throw new TikTokError(\n \"ffmpeg-not-found\",\n \"FFmpeg not found. Install it:\\n\" +\n \" Linux: apt install ffmpeg / brew install ffmpeg / pacman -S ffmpeg\\n\" +\n \" macOS: brew install ffmpeg\\n\" +\n \" Windows: choco install ffmpeg\",\n )\n }\n try {\n const result = await execa(ffmpegPath, args, {\n cancelSignal: signal,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n })\n return result.stdout ?? \"\"\n } catch (err: unknown) {\n if (signal?.aborted) {\n throw new TikTokError(\"aborted\", \"Aborted by user\")\n }\n const message = err instanceof Error ? err.message : String(err)\n throw new TikTokError(\"ffmpeg-error\", `FFmpeg failed: ${message}`)\n }\n}\n\n/** The media-processing capability `RecordingJob` depends on. */\nexport interface MediaConverter {\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 createMediaConverter(logger?: Logger, signal?: AbortSignal): MediaConverter {\n async function convert(input: string): Promise<string> {\n const output = input.replace(/\\.(flv|ts)$/i, \".mp4\")\n logger?.info(`Converting: ${input} → ${output}`)\n\n await runFfmpeg([\"-i\", input, \"-c\", \"copy\", \"-y\", output], signal)\n\n try {\n unlinkSync(input)\n logger?.info(`Deleted original: ${input}`)\n } catch {\n logger?.warn(`Could not delete original: ${input}`)\n }\n\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\n/**\n * Build FFmpeg HTTP option arguments for cookies and headers.\n * TikTok's CDN requires session cookies and a Referer to serve the stream.\n */\nfunction buildHttpArgs(cookies?: Record<string, string>): string[] {\n const args: string[] = []\n\n // ponytail: user-agent header, CDNs tend to be picky\n args.push(\n \"-user_agent\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:149.0) Gecko/20100101 Firefox/149.0\",\n )\n args.push(\"-headers\", \"Referer: https://www.tiktok.com/\\r\\n\")\n\n if (cookies && Object.keys(cookies).length > 0) {\n const cookieStr = Object.entries(cookies)\n .map(([k, v]) => `${k}=${v}`)\n .join(\"\\r\\n\")\n args.push(\"-cookies\", cookieStr)\n }\n\n return args\n}\n\n/** Standard FFmpeg reconnect + mpegts pipe arguments. */\nconst FFMPEG_BASE_ARGS = [\n \"-reconnect\",\n \"1\",\n \"-reconnect_at_eof\",\n \"1\",\n \"-reconnect_streamed\",\n \"1\",\n \"-reconnect_delay_max\",\n \"5\",\n \"-c\",\n \"copy\",\n \"-f\",\n \"mpegts\",\n \"pipe:1\",\n]\n\n/**\n * Spawn an FFmpeg process to download from `url` and pipe its stdout to\n * `writer` with backpressure handling.\n *\n * Uses child_process.spawn directly (not execa) because execa v9 defaults\n * to encoding stdout as UTF-8, which corrupts binary MPEG-TS data.\n */\nexport async function pipeFfmpegSegment(\n ffmpegPath: string,\n url: string,\n writer: WriteStream,\n signal: AbortSignal,\n maxDuration?: number,\n cookies?: Record<string, string>,\n): Promise<void> {\n const durationArgs = maxDuration ? [\"-t\", String(maxDuration)] : []\n const httpArgs = buildHttpArgs(cookies)\n // ponytail: input options (-headers, -cookies, -user_agent) must come before -i\n const args = [...httpArgs, \"-i\", url, ...durationArgs, ...FFMPEG_BASE_ARGS]\n const proc: ChildProcess = spawn(ffmpegPath, args, {\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n })\n\n let stderr = \"\"\n let firstDataTimer: ReturnType<typeof setTimeout> | null = null\n\n const clearStartupTimer = () => {\n if (firstDataTimer) {\n clearTimeout(firstDataTimer)\n firstDataTimer = null\n }\n }\n\n // Forward abort signal to process\n const onAbort = () => {\n if (!proc.killed) proc.kill(\"SIGTERM\")\n }\n signal.addEventListener(\"abort\", onAbort, { once: true })\n\n proc.stderr?.on(\"data\", (chunk: Buffer) => {\n clearStartupTimer()\n stderr += chunk.toString()\n if (stderr.length > 10000) stderr = stderr.slice(-5000)\n })\n\n proc.stdout?.on(\"data\", (chunk: Buffer) => {\n clearStartupTimer()\n const canContinue = writer.write(chunk)\n if (!canContinue) {\n proc.stdout?.pause()\n writer.once(\"drain\", () => proc.stdout?.resume())\n }\n })\n\n await new Promise<void>((resolve, reject) => {\n firstDataTimer = setTimeout(() => {\n if (!proc.killed) {\n proc.kill(\"SIGTERM\")\n setTimeout(() => {\n if (!proc.killed) proc.kill(\"SIGKILL\")\n }, 2000)\n }\n reject(\n new TikTokError(\n \"ffmpeg-error\",\n `FFmpeg startup timed out after ${FFMPEG_STARTUP_TIMEOUT / 1000}s\\n${stderr.slice(-500)}`,\n ),\n )\n }, FFMPEG_STARTUP_TIMEOUT)\n\n proc.on(\"close\", (code) => {\n clearStartupTimer()\n signal.removeEventListener(\"abort\", onAbort)\n if (signal.aborted) {\n resolve()\n return\n }\n if (code === 0 || code === null) {\n resolve()\n return\n }\n reject(\n new TikTokError(\"ffmpeg-error\", `FFmpeg exited with code ${code}\\n${stderr.slice(-500)}`),\n )\n })\n\n proc.on(\"error\", (err) => {\n clearStartupTimer()\n signal.removeEventListener(\"abort\", onAbort)\n reject(err)\n })\n })\n}\n"],"mappings":";;;;;;;;;;;;;;AAiBA,MAAM,yBAAyB;;AAG/B,SAAgB,iBAAgC;CAC9C,MAAM,WAAY,WAAoE,KAAK;CAC3F,IAAI,OAAO,aAAa,YACtB,OAAQ,SAAS,QAAQ,KAAgB;CAE3C,MAAM,QAAQ,QAAQ,IAAI,MAAM,MAAM,GAAG,KAAK,CAAC;CAC/C,KAAK,MAAM,OAAO,OAChB,IAAI;EACF,MAAM,OAAO,GAAG,IAAI;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AAiB;KACf,IAAI,CAAC,KAAK,QAAQ,KAAK,KAAK,SAAS;IACvC,GAAG,GAAI;GACT;GACA,OACE,IAAI,YACF,gBACA,kCAAkC,yBAAyB,IAAK,KAAK,OAAO,MAAM,IAAI,GACxF,CACF;EACF,GAAG,sBAAsB;EAEzB,KAAK,GAAG,UAAU,SAAS;GACzB,kBAAkB;GAClB,OAAO,oBAAoB,SAAS,OAAO;GAC3C,IAAI,OAAO,SAAS;IAClB,QAAQ;IACR;GACF;GACA,IAAI,SAAS,KAAK,SAAS,MAAM;IAC/B,QAAQ;IACR;GACF;GACA,OACE,IAAI,YAAY,gBAAgB,2BAA2B,KAAK,IAAI,OAAO,MAAM,IAAI,GAAG,CAC1F;EACF,CAAC;EAED,KAAK,GAAG,UAAU,QAAQ;GACxB,kBAAkB;GAClB,OAAO,oBAAoB,SAAS,OAAO;GAC3C,OAAO,GAAG;EACZ,CAAC;CACH,CAAC;AACH"}
@@ -19,20 +19,17 @@ function createTikTokClient(http, logger, showDebug, signal) {
19
19
  createApiLiveSource(),
20
20
  createProfileSource()
21
21
  ];
22
- async function ensureCache(user) {
23
- if (cached && cachedUser === user) return cached;
24
- cached = await resolveVerdict(user);
25
- cachedUser = user;
26
- return cached;
27
- }
28
- function invalidateCache() {
29
- cached = null;
30
- cachedUser = "";
31
- }
32
22
  return {
33
- invalidateCache,
23
+ invalidateCache() {
24
+ cached = null;
25
+ cachedUser = "";
26
+ },
34
27
  async getVerdict(user) {
35
- return ensureCache(user);
28
+ if (!cached || cachedUser !== user) {
29
+ cached = await resolveVerdict(user);
30
+ cachedUser = user;
31
+ }
32
+ return cached;
36
33
  },
37
34
  async isRoomAlive(roomId) {
38
35
  if (cached?.room && String(cached.room.id) === String(roomId)) return isLiveReason(cached.reason);
@@ -1 +1 @@
1
- {"version":3,"file":"client.mjs","names":[],"sources":["../../../src/io/tiktok/client.ts"],"sourcesContent":["/**\n * TikTok API — resolves room IDs, live status, and stream URLs.\n *\n * `createTikTokClient` is a thin orchestrator: per-user cache, cache invalidation,\n * and `discover()` over sources returning `Candidate`s. The chain turns\n * failures into evidence instead of aborting. `getVerdict` is the only\n * public verdict surface.\n *\n * Architecture:\n * createTikTokClient(httpClient) → { isRoomAlive, getLiveUrl, getVerdict }\n *\n * All public methods share a per-tick cache so the page is fetched at most once\n * per poll cycle. The optional `signal` aborts in-flight HTTP requests.\n *\n * Note: The room/enter Webcast endpoint has been deprecated due to frequent\n * 403 errors. All lookups go through room/info (reliable for live + offline).\n */\n\nimport type { Logger } from \"../../core/log\"\nimport { isLiveReason, type Verdict, verdictOf } from \"../../core/verdict\"\nimport type { HttpClient } from \"../http\"\nimport { type DiscoverySource, discover, type ResolveContext } from \"./discovery/chain\"\nimport { createApiLiveSource, createProfileSource } from \"./discovery/fallback\"\nimport { createPageSource } from \"./discovery/page\"\nimport { createPageFetcher } from \"./page\"\nimport { createWebcastApi } from \"./webcast\"\n\nexport interface TikTokClient {\n /** Check if a room is currently live. */\n isRoomAlive(roomId: string): Promise<boolean>\n /** Get the best-quality FLV stream URL for a room. Returns null on failure. */\n getLiveUrl(roomId: string): Promise<string | null>\n /** Full per-tick verdict with reason, refs, evidence trail, and failure. */\n getVerdict(user: string): Promise<Verdict>\n /** Invalidate per-tick cache (call at start of each poll tick). */\n invalidateCache(): void\n}\n\nexport function createTikTokClient(\n http: HttpClient,\n logger?: Logger,\n showDebug?: boolean,\n signal?: AbortSignal,\n): TikTokClient {\n // Debug logging helper — writes to stderr only when --debug is passed.\n const debug = (msg: string) => {\n logger?.debug(msg)\n if (showDebug) process.stderr.write(`[API_DEBUG] ${msg}\\n`)\n }\n let cached: Verdict | null = null\n let cachedUser = \"\"\n const webcast = createWebcastApi(http, debug, signal)\n const tryFetchPage = createPageFetcher(http, debug, signal)\n const sources: DiscoverySource[] = [\n createPageSource(),\n createApiLiveSource(),\n createProfileSource(),\n ]\n\n async function ensureCache(user: string): Promise<Verdict> {\n if (cached && cachedUser === user) return cached\n cached = await resolveVerdict(user)\n cachedUser = user\n return cached\n }\n\n function invalidateCache(): void {\n cached = null\n cachedUser = \"\"\n }\n\n return {\n invalidateCache,\n\n async getVerdict(user: string): Promise<Verdict> {\n return ensureCache(user)\n },\n\n async isRoomAlive(roomId: string): Promise<boolean> {\n if (cached?.room && String(cached.room.id) === String(roomId)) {\n return isLiveReason(cached.reason)\n }\n // Use the lightweight check_alive endpoint instead of re-fetching\n // the full room/info response.\n return webcast.fetchCheckAlive(roomId)\n },\n\n async getLiveUrl(roomId: string): Promise<string | null> {\n if (cached?.room && String(cached.room.id) === String(roomId) && cached.stream) {\n return cached.stream.url\n }\n // Room ID, not a username: never route this through ensureCache.\n const res = await webcast.fetchStreamUrlFromApi(roomId)\n return res.ok ? res.value : null\n },\n }\n\n // ─── Internal: discovery chain → one verdict ───\n\n async function resolveVerdict(user: string): Promise<Verdict> {\n const ctx: ResolveContext = { user, http, debug, fetchPage: tryFetchPage, webcast }\n const { candidate, evidence } = await discover(sources, ctx)\n switch (candidate.kind) {\n case \"room\":\n return verdictOf({ room: candidate.room, stream: candidate.stream, evidence })\n case \"denied\":\n return verdictOf({ room: candidate.room, denied: true, evidence })\n case \"failed\":\n return verdictOf({ failure: candidate.error, evidence })\n case \"miss\":\n return verdictOf({ evidence })\n }\n }\n}\n"],"mappings":";;;;;;;AAsCA,SAAgB,mBACd,MACA,QACA,WACA,QACc;CAEd,MAAM,SAAS,QAAgB;EAC7B,QAAQ,MAAM,GAAG;EACjB,IAAI,WAAW,QAAQ,OAAO,MAAM,eAAe,IAAI,GAAG;CAC5D;CACA,IAAI,SAAyB;CAC7B,IAAI,aAAa;CACjB,MAAM,UAAU,iBAAiB,MAAM,OAAO,MAAM;CACpD,MAAM,eAAe,kBAAkB,MAAM,OAAO,MAAM;CAC1D,MAAM,UAA6B;EACjC,iBAAiB;EACjB,oBAAoB;EACpB,oBAAoB;CACtB;CAEA,eAAe,YAAY,MAAgC;EACzD,IAAI,UAAU,eAAe,MAAM,OAAO;EAC1C,SAAS,MAAM,eAAe,IAAI;EAClC,aAAa;EACb,OAAO;CACT;CAEA,SAAS,kBAAwB;EAC/B,SAAS;EACT,aAAa;CACf;CAEA,OAAO;EACL;EAEA,MAAM,WAAW,MAAgC;GAC/C,OAAO,YAAY,IAAI;EACzB;EAEA,MAAM,YAAY,QAAkC;GAClD,IAAI,QAAQ,QAAQ,OAAO,OAAO,KAAK,EAAE,MAAM,OAAO,MAAM,GAC1D,OAAO,aAAa,OAAO,MAAM;GAInC,OAAO,QAAQ,gBAAgB,MAAM;EACvC;EAEA,MAAM,WAAW,QAAwC;GACvD,IAAI,QAAQ,QAAQ,OAAO,OAAO,KAAK,EAAE,MAAM,OAAO,MAAM,KAAK,OAAO,QACtE,OAAO,OAAO,OAAO;GAGvB,MAAM,MAAM,MAAM,QAAQ,sBAAsB,MAAM;GACtD,OAAO,IAAI,KAAK,IAAI,QAAQ;EAC9B;CACF;CAIA,eAAe,eAAe,MAAgC;EAE5D,MAAM,EAAE,WAAW,aAAa,MAAM,SAAS,SAAS;GAD1B;GAAM;GAAM;GAAO,WAAW;GAAc;EAChB,CAAC;EAC3D,QAAQ,UAAU,MAAlB;GACE,KAAK,QACH,OAAO,UAAU;IAAE,MAAM,UAAU;IAAM,QAAQ,UAAU;IAAQ;GAAS,CAAC;GAC/E,KAAK,UACH,OAAO,UAAU;IAAE,MAAM,UAAU;IAAM,QAAQ;IAAM;GAAS,CAAC;GACnE,KAAK,UACH,OAAO,UAAU;IAAE,SAAS,UAAU;IAAO;GAAS,CAAC;GACzD,KAAK,QACH,OAAO,UAAU,EAAE,SAAS,CAAC;EACjC;CACF;AACF"}
1
+ {"version":3,"file":"client.mjs","names":[],"sources":["../../../src/io/tiktok/client.ts"],"sourcesContent":["/**\n * TikTok API — resolves room IDs, live status, and stream URLs.\n *\n * `createTikTokClient` is a thin orchestrator: per-tick cache, cache\n * invalidation, and `discover()` over sources returning `Candidate`s. The chain\n * turns failures into evidence instead of aborting. `getVerdict` is the only\n * public verdict surface.\n *\n * All public methods share a per-tick cache so the page is fetched at most once\n * per poll cycle. The optional `signal` aborts in-flight HTTP requests.\n */\n\nimport type { Logger } from \"../../core/log\"\nimport { isLiveReason, type Verdict, verdictOf } from \"../../core/verdict\"\nimport type { HttpClient } from \"../http\"\nimport { type DiscoverySource, discover, type ResolveContext } from \"./discovery/chain\"\nimport { createApiLiveSource, createProfileSource } from \"./discovery/fallback\"\nimport { createPageSource } from \"./discovery/page\"\nimport { createPageFetcher } from \"./page\"\nimport { createWebcastApi } from \"./webcast\"\n\nexport interface TikTokClient {\n /** Check if a room is currently live. */\n isRoomAlive(roomId: string): Promise<boolean>\n /** Get the best-quality FLV stream URL for a room. Returns null on failure. */\n getLiveUrl(roomId: string): Promise<string | null>\n /** Full per-tick verdict with reason, refs, evidence trail, and failure. */\n getVerdict(user: string): Promise<Verdict>\n /** Invalidate per-tick cache (call at start of each poll tick). */\n invalidateCache(): void\n}\n\nexport function createTikTokClient(\n http: HttpClient,\n logger?: Logger,\n showDebug?: boolean,\n signal?: AbortSignal,\n): TikTokClient {\n // Debug logging helper — writes to stderr only when --debug is passed.\n const debug = (msg: string) => {\n logger?.debug(msg)\n if (showDebug) process.stderr.write(`[API_DEBUG] ${msg}\\n`)\n }\n let cached: Verdict | null = null\n let cachedUser = \"\"\n const webcast = createWebcastApi(http, debug, signal)\n const tryFetchPage = createPageFetcher(http, debug, signal)\n const sources: DiscoverySource[] = [\n createPageSource(),\n createApiLiveSource(),\n createProfileSource(),\n ]\n\n return {\n invalidateCache() {\n cached = null\n cachedUser = \"\"\n },\n\n async getVerdict(user: string): Promise<Verdict> {\n if (!cached || cachedUser !== user) {\n cached = await resolveVerdict(user)\n cachedUser = user\n }\n return cached\n },\n\n async isRoomAlive(roomId: string): Promise<boolean> {\n if (cached?.room && String(cached.room.id) === String(roomId)) {\n return isLiveReason(cached.reason)\n }\n // Use the lightweight check_alive endpoint instead of re-fetching\n // the full room/info response.\n return webcast.fetchCheckAlive(roomId)\n },\n\n async getLiveUrl(roomId: string): Promise<string | null> {\n if (cached?.room && String(cached.room.id) === String(roomId) && cached.stream) {\n return cached.stream.url\n }\n // Room ID, not a username: never route this through the user cache.\n const res = await webcast.fetchStreamUrlFromApi(roomId)\n return res.ok ? res.value : null\n },\n }\n\n // ─── Internal: discovery chain → one verdict ───\n\n async function resolveVerdict(user: string): Promise<Verdict> {\n const ctx: ResolveContext = { user, http, debug, fetchPage: tryFetchPage, webcast }\n const { candidate, evidence } = await discover(sources, ctx)\n switch (candidate.kind) {\n case \"room\":\n return verdictOf({ room: candidate.room, stream: candidate.stream, evidence })\n case \"denied\":\n return verdictOf({ room: candidate.room, denied: true, evidence })\n case \"failed\":\n return verdictOf({ failure: candidate.error, evidence })\n case \"miss\":\n return verdictOf({ evidence })\n }\n }\n}\n"],"mappings":";;;;;;;AAgCA,SAAgB,mBACd,MACA,QACA,WACA,QACc;CAEd,MAAM,SAAS,QAAgB;EAC7B,QAAQ,MAAM,GAAG;EACjB,IAAI,WAAW,QAAQ,OAAO,MAAM,eAAe,IAAI,GAAG;CAC5D;CACA,IAAI,SAAyB;CAC7B,IAAI,aAAa;CACjB,MAAM,UAAU,iBAAiB,MAAM,OAAO,MAAM;CACpD,MAAM,eAAe,kBAAkB,MAAM,OAAO,MAAM;CAC1D,MAAM,UAA6B;EACjC,iBAAiB;EACjB,oBAAoB;EACpB,oBAAoB;CACtB;CAEA,OAAO;EACL,kBAAkB;GAChB,SAAS;GACT,aAAa;EACf;EAEA,MAAM,WAAW,MAAgC;GAC/C,IAAI,CAAC,UAAU,eAAe,MAAM;IAClC,SAAS,MAAM,eAAe,IAAI;IAClC,aAAa;GACf;GACA,OAAO;EACT;EAEA,MAAM,YAAY,QAAkC;GAClD,IAAI,QAAQ,QAAQ,OAAO,OAAO,KAAK,EAAE,MAAM,OAAO,MAAM,GAC1D,OAAO,aAAa,OAAO,MAAM;GAInC,OAAO,QAAQ,gBAAgB,MAAM;EACvC;EAEA,MAAM,WAAW,QAAwC;GACvD,IAAI,QAAQ,QAAQ,OAAO,OAAO,KAAK,EAAE,MAAM,OAAO,MAAM,KAAK,OAAO,QACtE,OAAO,OAAO,OAAO;GAGvB,MAAM,MAAM,MAAM,QAAQ,sBAAsB,MAAM;GACtD,OAAO,IAAI,KAAK,IAAI,QAAQ;EAC9B;CACF;CAIA,eAAe,eAAe,MAAgC;EAE5D,MAAM,EAAE,WAAW,aAAa,MAAM,SAAS,SAAS;GAD1B;GAAM;GAAM;GAAO,WAAW;GAAc;EAChB,CAAC;EAC3D,QAAQ,UAAU,MAAlB;GACE,KAAK,QACH,OAAO,UAAU;IAAE,MAAM,UAAU;IAAM,QAAQ,UAAU;IAAQ;GAAS,CAAC;GAC/E,KAAK,UACH,OAAO,UAAU;IAAE,MAAM,UAAU;IAAM,QAAQ;IAAM;GAAS,CAAC;GACnE,KAAK,UACH,OAAO,UAAU;IAAE,SAAS,UAAU;IAAO;GAAS,CAAC;GACzD,KAAK,QACH,OAAO,UAAU,EAAE,SAAS,CAAC;EACjC;CACF;AACF"}
@@ -65,13 +65,14 @@ async function refused(ctx, roomId, title, source) {
65
65
  };
66
66
  }
67
67
  function outcomeOf(candidate) {
68
- switch (candidate.kind) {
69
- case "room": return "hit";
70
- case "denied": return "denied";
71
- case "failed": return "error";
72
- case "miss": return "miss";
73
- }
68
+ return OUTCOME[candidate.kind];
74
69
  }
70
+ const OUTCOME = {
71
+ room: "hit",
72
+ denied: "denied",
73
+ failed: "error",
74
+ miss: "miss"
75
+ };
75
76
  /**
76
77
  * Run discovery sources in order. A throw — sync or async — becomes a
77
78
  * `failed` candidate and the chain continues: the `probe.ts:154` dead end,
@@ -85,17 +86,13 @@ async function discover(sources, ctx) {
85
86
  note: "no sources configured"
86
87
  };
87
88
  for (const source of sources) {
88
- const candidate = await (async () => {
89
- try {
90
- return await source.find(ctx);
91
- } catch (error) {
92
- ctx.debug(`discover: ${source.id} threw — ${error instanceof Error ? error.message : error}`);
93
- return {
94
- kind: "failed",
95
- error: error instanceof Error ? error : new Error(String(error))
96
- };
97
- }
98
- })();
89
+ let candidate;
90
+ try {
91
+ candidate = await source.find(ctx);
92
+ } catch (error) {
93
+ ctx.debug(`discover: ${source.id} threw — ${error instanceof Error ? error.message : error}`);
94
+ candidate = failed(error);
95
+ }
99
96
  evidence.push({
100
97
  source: candidate.kind === "room" || candidate.kind === "denied" ? candidate.source : source.id,
101
98
  outcome: outcomeOf(candidate)
@@ -1 +1 @@
1
- {"version":3,"file":"chain.mjs","names":[],"sources":["../../../../src/io/tiktok/discovery/chain.ts"],"sourcesContent":["/**\n * Discovery chain — one idea in one file: a source reports facts, the chain\n * turns every outcome (including a throw) into evidence, and the first room or\n * gate refusal ends it.\n *\n * Types, candidate constructors, and the runner live together because they are\n * a single contract; splitting them across `types.ts` and `candidates.ts` only\n * added import edges.\n */\n\nimport type { Evidence, EvidenceOutcome, RoomRef, SourceId, StreamRef } from \"../../../core/verdict\"\nimport type { HttpClient } from \"../../http\"\nimport type { WebcastReader } from \"../webcast\"\n\n/**\n * What one discovery source found. `room`/`denied` end the chain; `miss` and\n * `failed` let the next source try — a throw is evidence, never a dead end.\n */\nexport type Candidate =\n | { kind: \"room\"; room: RoomRef; stream: StreamRef | null; source: SourceId }\n | { kind: \"denied\"; room: RoomRef; code: number; source: SourceId }\n | { kind: \"miss\"; note: string }\n | { kind: \"failed\"; error: Error }\n\nexport interface ResolveContext {\n user: string\n http: HttpClient\n debug: (msg: string) => void\n fetchPage: (user: string, path: string) => Promise<{ html: string; baseUrl: string } | null>\n webcast: WebcastReader\n}\n\nexport interface DiscoverySource {\n readonly id: \"page\" | \"api-live\" | \"profile\"\n find(ctx: ResolveContext): Promise<Candidate>\n}\n\n// ─── candidate constructors ────────────────────────────────\n\n/** Nothing found here — let the next source try. */\nexport function miss(note: string): Candidate {\n return { kind: \"miss\", note }\n}\n\n/** A transport/parse failure. The chain keeps going; it only wins over a miss. */\nexport function failed(error: unknown): Candidate {\n return { kind: \"failed\", error: error instanceof Error ? error : new Error(String(error)) }\n}\n\n/**\n * Room live with a stream URL. Uses `knownUrl` when the page already carried\n * it; otherwise asks the Webcast API. A 4003110 refusal becomes `denied`.\n */\nexport async function withStream(\n ctx: ResolveContext,\n room: RoomRef,\n source: SourceId,\n knownUrl: string | null,\n): Promise<Candidate> {\n if (knownUrl) return { kind: \"room\", room, stream: { url: knownUrl }, source }\n const res = await ctx.webcast.fetchStreamUrlFromApi(room.id)\n if (res.ok) {\n return { kind: \"room\", room, stream: res.value ? { url: res.value } : null, source }\n }\n if (res.statusCode === 4003110) return refused(ctx, room.id, room.title, source)\n return { kind: \"room\", room, stream: null, source }\n}\n\n/** Authoritative room/info lookup: the single 4003110 consumer for room IDs. */\nexport async function fromRoomInfo(\n ctx: ResolveContext,\n roomId: string,\n source: SourceId,\n): Promise<Candidate> {\n const res = await ctx.webcast.roomInfo(roomId)\n if (res.ok) {\n if (!res.value) return miss(`room/info returned no data for ${roomId}`)\n return { kind: \"room\", room: res.value.room, stream: res.value.stream, source }\n }\n if (res.statusCode === 4003110) return refused(ctx, roomId, null, source)\n if (res.statusCode === 0) return failed(new Error(`room/info transport failure for ${roomId}`))\n return miss(`room/info HTTP ${res.statusCode} for ${roomId}`)\n}\n\n/** Gate refusal: check_alive decides whether the room is live (restricted) or offline. */\nexport async function refused(\n ctx: ResolveContext,\n roomId: string,\n title: string | null,\n source: SourceId,\n): Promise<Candidate> {\n const room = await ctx.webcast.refusedRoom(roomId, title)\n return { kind: \"denied\", room, code: 4003110, source }\n}\n\n// ─── runner ────────────────────────────────────────────────\n\nfunction outcomeOf(candidate: Candidate): EvidenceOutcome {\n switch (candidate.kind) {\n case \"room\":\n return \"hit\"\n case \"denied\":\n return \"denied\"\n case \"failed\":\n return \"error\"\n case \"miss\":\n return \"miss\"\n }\n}\n\n/**\n * Run discovery sources in order. A throw — sync or async — becomes a\n * `failed` candidate and the chain continues: the `probe.ts:154` dead end,\n * inverted. A room or a gate refusal ends the chain; the first failure\n * outranks a later miss.\n */\nexport async function discover(\n sources: readonly DiscoverySource[],\n ctx: ResolveContext,\n): Promise<{ candidate: Candidate; evidence: Evidence[] }> {\n const evidence: Evidence[] = []\n let best: Candidate = { kind: \"miss\", note: \"no sources configured\" }\n\n for (const source of sources) {\n const candidate = await (async (): Promise<Candidate> => {\n try {\n return await source.find(ctx)\n } catch (error) {\n ctx.debug(\n `discover: ${source.id} threw — ${error instanceof Error ? error.message : error}`,\n )\n return { kind: \"failed\", error: error instanceof Error ? error : new Error(String(error)) }\n }\n })()\n evidence.push({\n source:\n candidate.kind === \"room\" || candidate.kind === \"denied\" ? candidate.source : source.id,\n outcome: outcomeOf(candidate),\n })\n if (candidate.kind === \"room\" || candidate.kind === \"denied\") return { candidate, evidence }\n // First failure is the root cause; a later failure must not overwrite it.\n if (candidate.kind === \"failed\" && best.kind !== \"failed\") best = candidate\n }\n\n return { candidate: best, evidence }\n}\n"],"mappings":";;AAwCA,SAAgB,KAAK,MAAyB;CAC5C,OAAO;EAAE,MAAM;EAAQ;CAAK;AAC9B;;AAGA,SAAgB,OAAO,OAA2B;CAChD,OAAO;EAAE,MAAM;EAAU,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;CAAE;AAC5F;;;;;AAMA,eAAsB,WACpB,KACA,MACA,QACA,UACoB;CACpB,IAAI,UAAU,OAAO;EAAE,MAAM;EAAQ;EAAM,QAAQ,EAAE,KAAK,SAAS;EAAG;CAAO;CAC7E,MAAM,MAAM,MAAM,IAAI,QAAQ,sBAAsB,KAAK,EAAE;CAC3D,IAAI,IAAI,IACN,OAAO;EAAE,MAAM;EAAQ;EAAM,QAAQ,IAAI,QAAQ,EAAE,KAAK,IAAI,MAAM,IAAI;EAAM;CAAO;CAErF,IAAI,IAAI,eAAe,SAAS,OAAO,QAAQ,KAAK,KAAK,IAAI,KAAK,OAAO,MAAM;CAC/E,OAAO;EAAE,MAAM;EAAQ;EAAM,QAAQ;EAAM;CAAO;AACpD;;AAGA,eAAsB,aAC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SAAS,WAAW,UAAU,SAAS,OAAO;GACvF,SAAS,UAAU,SAAS;EAC9B,CAAC;EACD,IAAI,UAAU,SAAS,UAAU,UAAU,SAAS,UAAU,OAAO;GAAE;GAAW;EAAS;EAE3F,IAAI,UAAU,SAAS,YAAY,KAAK,SAAS,UAAU,OAAO;CACpE;CAEA,OAAO;EAAE,WAAW;EAAM;CAAS;AACrC"}
1
+ {"version":3,"file":"chain.mjs","names":[],"sources":["../../../../src/io/tiktok/discovery/chain.ts"],"sourcesContent":["/**\n * Discovery chain — one idea in one file: a source reports facts, the chain\n * turns every outcome (including a throw) into evidence, and the first room or\n * gate refusal ends it.\n */\n\nimport type { Evidence, EvidenceOutcome, RoomRef, SourceId, StreamRef } from \"../../../core/verdict\"\nimport type { HttpClient } from \"../../http\"\nimport type { WebcastReader } from \"../webcast\"\n\n/**\n * What one discovery source found. `room`/`denied` end the chain; `miss` and\n * `failed` let the next source try — a throw is evidence, never a dead end.\n */\nexport type Candidate =\n | { kind: \"room\"; room: RoomRef; stream: StreamRef | null; source: SourceId }\n | { kind: \"denied\"; room: RoomRef; code: number; source: SourceId }\n | { kind: \"miss\"; note: string }\n | { kind: \"failed\"; error: Error }\n\nexport interface ResolveContext {\n user: string\n http: HttpClient\n debug: (msg: string) => void\n fetchPage: (user: string, path: string) => Promise<{ html: string; baseUrl: string } | null>\n webcast: WebcastReader\n}\n\nexport interface DiscoverySource {\n readonly id: \"page\" | \"api-live\" | \"profile\"\n find(ctx: ResolveContext): Promise<Candidate>\n}\n\n// ─── candidate constructors ────────────────────────────────\n\n/** Nothing found here — let the next source try. */\nexport function miss(note: string): Candidate {\n return { kind: \"miss\", note }\n}\n\n/** A transport/parse failure. The chain keeps going; it only wins over a miss. */\nexport function failed(error: unknown): Candidate {\n return { kind: \"failed\", error: error instanceof Error ? error : new Error(String(error)) }\n}\n\n/**\n * Room live with a stream URL. Uses `knownUrl` when the page already carried\n * it; otherwise asks the Webcast API. A 4003110 refusal becomes `denied`.\n */\nexport async function withStream(\n ctx: ResolveContext,\n room: RoomRef,\n source: SourceId,\n knownUrl: string | null,\n): Promise<Candidate> {\n if (knownUrl) return { kind: \"room\", room, stream: { url: knownUrl }, source }\n const res = await ctx.webcast.fetchStreamUrlFromApi(room.id)\n if (res.ok) {\n return { kind: \"room\", room, stream: res.value ? { url: res.value } : null, source }\n }\n if (res.statusCode === 4003110) return refused(ctx, room.id, room.title, source)\n return { kind: \"room\", room, stream: null, source }\n}\n\n/** Authoritative room/info lookup: the single 4003110 consumer for room IDs. */\nexport async function fromRoomInfo(\n ctx: ResolveContext,\n roomId: string,\n source: SourceId,\n): Promise<Candidate> {\n const res = await ctx.webcast.roomInfo(roomId)\n if (res.ok) {\n if (!res.value) return miss(`room/info returned no data for ${roomId}`)\n return { kind: \"room\", room: res.value.room, stream: res.value.stream, source }\n }\n if (res.statusCode === 4003110) return refused(ctx, roomId, null, source)\n if (res.statusCode === 0) return failed(new Error(`room/info transport failure for ${roomId}`))\n return miss(`room/info HTTP ${res.statusCode} for ${roomId}`)\n}\n\n/** Gate refusal: check_alive decides whether the room is live (restricted) or offline. */\nexport async function refused(\n ctx: ResolveContext,\n roomId: string,\n title: string | null,\n source: SourceId,\n): Promise<Candidate> {\n const room = await ctx.webcast.refusedRoom(roomId, title)\n return { kind: \"denied\", room, code: 4003110, source }\n}\n\n// ─── runner ────────────────────────────────────────────────\n\nfunction outcomeOf(candidate: Candidate): EvidenceOutcome {\n return OUTCOME[candidate.kind]\n}\n\nconst OUTCOME = {\n room: \"hit\",\n denied: \"denied\",\n failed: \"error\",\n miss: \"miss\",\n} satisfies Record<Candidate[\"kind\"], EvidenceOutcome>\n\n/**\n * Run discovery sources in order. A throw — sync or async — becomes a\n * `failed` candidate and the chain continues: the `probe.ts:154` dead end,\n * inverted. A room or a gate refusal ends the chain; the first failure\n * outranks a later miss.\n */\nexport async function discover(\n sources: readonly DiscoverySource[],\n ctx: ResolveContext,\n): Promise<{ candidate: Candidate; evidence: Evidence[] }> {\n const evidence: Evidence[] = []\n let best: Candidate = { kind: \"miss\", note: \"no sources configured\" }\n\n for (const source of sources) {\n let candidate: Candidate\n try {\n candidate = await source.find(ctx)\n } catch (error) {\n ctx.debug(`discover: ${source.id} threw — ${error instanceof Error ? error.message : error}`)\n candidate = failed(error)\n }\n evidence.push({\n source:\n candidate.kind === \"room\" || candidate.kind === \"denied\" ? candidate.source : source.id,\n outcome: outcomeOf(candidate),\n })\n if (candidate.kind === \"room\" || candidate.kind === \"denied\") return { candidate, evidence }\n // First failure is the root cause; a later failure must not overwrite it.\n if (candidate.kind === \"failed\" && best.kind !== \"failed\") best = candidate\n }\n\n return { candidate: best, evidence }\n}\n"],"mappings":";;AAoCA,SAAgB,KAAK,MAAyB;CAC5C,OAAO;EAAE,MAAM;EAAQ;CAAK;AAC9B;;AAGA,SAAgB,OAAO,OAA2B;CAChD,OAAO;EAAE,MAAM;EAAU,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;CAAE;AAC5F;;;;;AAMA,eAAsB,WACpB,KACA,MACA,QACA,UACoB;CACpB,IAAI,UAAU,OAAO;EAAE,MAAM;EAAQ;EAAM,QAAQ,EAAE,KAAK,SAAS;EAAG;CAAO;CAC7E,MAAM,MAAM,MAAM,IAAI,QAAQ,sBAAsB,KAAK,EAAE;CAC3D,IAAI,IAAI,IACN,OAAO;EAAE,MAAM;EAAQ;EAAM,QAAQ,IAAI,QAAQ,EAAE,KAAK,IAAI,MAAM,IAAI;EAAM;CAAO;CAErF,IAAI,IAAI,eAAe,SAAS,OAAO,QAAQ,KAAK,KAAK,IAAI,KAAK,OAAO,MAAM;CAC/E,OAAO;EAAE,MAAM;EAAQ;EAAM,QAAQ;EAAM;CAAO;AACpD;;AAGA,eAAsB,aACpB,KACA,QACA,QACoB;CACpB,MAAM,MAAM,MAAM,IAAI,QAAQ,SAAS,MAAM;CAC7C,IAAI,IAAI,IAAI;EACV,IAAI,CAAC,IAAI,OAAO,OAAO,KA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 @@ function createPageSource() {
10
10
  return {
11
11
  id: "page",
12
12
  async find(ctx) {
13
- let sigi = null;
14
- let html = "";
13
+ const page = await ctx.fetchPage(ctx.user, "/live");
14
+ const html = page?.html ?? "";
15
+ ctx.debug(page ? `fetchLiveInfo: /live returned ${html.length} bytes (${page.baseUrl})` : "fetchLiveInfo: all domains blocked for /live page");
15
16
  let failure = null;
16
- const take = (candidate) => {
17
+ const attempt = async (pending) => {
18
+ const candidate = await pending;
17
19
  if (candidate.kind === "room" || candidate.kind === "denied") return candidate;
18
20
  if (candidate.kind === "failed") failure ??= candidate;
19
21
  return null;
20
22
  };
21
- const page = await ctx.fetchPage(ctx.user, "/live");
22
- if (!page) {
23
- ctx.debug("fetchLiveInfo: all domains blocked for /live page");
24
- html = "";
25
- } else {
26
- html = page.html;
27
- ctx.debug(`fetchLiveInfo: /live returned ${html.length} bytes (${page.baseUrl}), first 300: ${html.slice(0, 300).replace(/\n/g, "\\n")}`);
28
- sigi = extractSigiState(html);
29
- ctx.debug(`fetchLiveInfo: SIGI_STATE ${sigi ? "found" : "not found"}`);
30
- if (sigi) {
31
- const liveRoom = sigi.LiveRoom?.liveRoomUserInfo?.liveRoom;
32
- const userInfo = sigi.LiveRoom?.liveRoomUserInfo?.user;
33
- ctx.debug(`fetchLiveInfo: liveRoom=${!!liveRoom}, userInfo=${!!userInfo}, userInfo.roomId=${userInfo?.roomId ?? "null"}`);
34
- if (liveRoom && userInfo?.roomId) {
35
- const room = {
36
- id: String(userInfo.roomId),
37
- title: liveRoom.title ?? null,
38
- live: liveRoom.status === 2
39
- };
40
- ctx.debug(`fetchLiveInfo: primary path — roomId=${room.id}, status=${liveRoom.status}, live=${room.live}`);
41
- if (!room.live) return {
42
- kind: "room",
43
- room,
44
- stream: null,
45
- source: "sigi"
46
- };
47
- return withStream(ctx, room, "sigi", extractStreamUrlFast(liveRoom) ?? findStreamUrlRecursively(sigi));
48
- }
49
- if (userInfo?.roomId) {
50
- const roomId = String(userInfo.roomId);
51
- ctx.debug(`fetchLiveInfo: userInfo fallback — roomId=${roomId}, querying Webcast API`);
52
- const found = take(await fromRoomInfo(ctx, roomId, "room-info"));
53
- ctx.debug(`fetchLiveInfo: Webcast API ${found ? "returned room info" : "returned null"}`);
54
- if (found) return found;
55
- }
56
- ctx.debug("fetchLiveInfo: trying legacy fallback (UserModule)");
57
- const legacy = take(await sigiLegacy(sigi, ctx));
58
- ctx.debug(`fetchLiveInfo: legacy fallback ${legacy ? "succeeded" : "returned null"}`);
59
- if (legacy) return legacy;
60
- }
23
+ const sigi = page ? extractSigiState(html) : null;
24
+ ctx.debug(`fetchLiveInfo: SIGI_STATE ${sigi ? "found" : "not found"}`);
25
+ const liveRoom = sigi?.LiveRoom?.liveRoomUserInfo?.liveRoom;
26
+ const roomId = sigi?.LiveRoom?.liveRoomUserInfo?.user?.roomId;
27
+ const id = roomId ? String(roomId) : null;
28
+ if (liveRoom && id) {
29
+ const room = {
30
+ id,
31
+ title: liveRoom.title ?? null,
32
+ live: liveRoom.status === 2
33
+ };
34
+ ctx.debug(`fetchLiveInfo: primary path — roomId=${room.id}, live=${room.live}`);
35
+ if (!room.live) return {
36
+ kind: "room",
37
+ room,
38
+ stream: null,
39
+ source: "sigi"
40
+ };
41
+ return withStream(ctx, room, "sigi", extractStreamUrlFast(liveRoom) ?? findStreamUrlRecursively(sigi));
42
+ }
43
+ if (id) {
44
+ const found = await attempt(fromRoomInfo(ctx, id, "room-info"));
45
+ if (found) return found;
46
+ }
47
+ if (sigi) {
48
+ const found = await attempt(sigiLegacy(sigi, ctx));
49
+ if (found) return found;
61
50
  }
62
- ctx.debug(`fetchLiveInfo: trying universal data fallback (html length ${html.length})`);
63
- const { roomId } = extractUserFromUniversalData(html);
64
- ctx.debug(`fetchLiveInfo: universal data roomId=${roomId ?? "null"}`);
65
- if (roomId) {
66
- const found = take(await fromRoomInfo(ctx, roomId, "room-info"));
67
- ctx.debug(`fetchLiveInfo: universal data Webcast API ${found ? "succeeded" : "returned null"}`);
51
+ const universalRoomId = extractUserFromUniversalData(html).roomId;
52
+ ctx.debug(`fetchLiveInfo: universal data roomId=${universalRoomId ?? "null"}`);
53
+ if (universalRoomId) {
54
+ const found = await attempt(fromRoomInfo(ctx, universalRoomId, "room-info"));
68
55
  if (found) return found;
69
56
  }
70
57
  return failure ?? miss("page: no room id");
@@ -79,9 +66,8 @@ function createPageSource() {
79
66
  */
80
67
  async function sigiLegacy(sigi, ctx) {
81
68
  const isLive = sigi.LiveRoom?.liveRoomStatus === 2;
82
- const userModule = sigi.UserModule?.users?.[ctx.user];
83
- let roomId = null;
84
- if (userModule?.roomId) roomId = typeof userModule.roomId === "object" ? String(userModule.roomId.id ?? "") : String(userModule.roomId);
69
+ const raw = (sigi.UserModule?.users?.[ctx.user])?.roomId;
70
+ const roomId = raw ? String(typeof raw === "object" ? raw.id ?? "" : raw) : "";
85
71
  if (!roomId) return miss("sigi-legacy: no roomId");
86
72
  const room = {
87
73
  id: roomId,