// Conversion is confined to local imports. Existing VTT bytes stay unchanged. export function localTranscriptFingerprint(name: string, text: string): string { return /\.srt$/i.test(name) ? JSON.stringify(["srt-v1", name, text]) : text; } export function localTranscriptVtt(name: string, text: string): string { return /\.srt$/i.test(name) ? srtToVtt(text) : text; } // Reject malformed blocks rather than quietly dropping dialogue. No subprocess, // guessed duration, cue reordering, or timestamp stretching is involved. export function srtToVtt(source: string): string { const text = source.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n").trim(); if (!text || text.includes("\uFFFD") || text.includes("\0")) throw new Error("SRT is empty or has unsupported text encoding"); const timestamp = "(\\d{2,}):([0-5]\\d):([0-5]\\d),([0-9]{3})"; const timing = new RegExp("^" + timestamp + "[ \\t]+-->[ \\t]+" + timestamp + "[ \\t]*$"); const output: string[] = []; let positive = false; for (const block of text.split(/\n[ \t]*\n+/)) { const lines = block.split("\n"); if (/^\d+[ \t]*$/.test(lines[0])) lines.shift(); const match = lines.shift()?.match(timing); if (!match || !lines.some(line => line.trim())) throw new Error("SRT has an invalid timing line or empty cue"); const seconds = (offset: number) => Number(match[offset]) * 3600 + Number(match[offset + 1]) * 60 + Number(match[offset + 2]) + Number(match[offset + 3]) / 1000; const start = seconds(1), end = seconds(5); if (!Number.isFinite(start) || !Number.isFinite(end) || end < start) throw new Error("SRT has an invalid cue interval"); positive ||= end > start; // Keep supported emphasis. Escape other angle brackets so literal dialogue // cannot become VTT timestamps, cue markup, or a block directive. const body = lines.map(line => line.replace(/&(?!amp;|lt;|gt;|nbsp;|lrm;|rlm;)/g, "&") .replace(/<(?!\/?(?:b|i|u)>)/g, "<")).join("\n"); const stamp = (offset: number) => `${match[offset]}:${match[offset + 1]}:${match[offset + 2]}.${match[offset + 3]}`; output.push(`${stamp(1)} --> ${stamp(5)}\n${body}`); } if (!positive) throw new Error("SRT has no positive-duration cues"); return "WEBVTT\n\n" + output.join("\n\n") + "\n"; }