* Parses a JS array literal containing `{ text, start, end }` objects. * * Handles: * - Double-quoted and single-quoted string values * - Trailing commas after the last element or property * - Unquoted property keys (standard JS object literal syntax) * - Numeric values for start/end
(arrayLiteral: string)
| 272 | * - Numeric values for start/end |
| 273 | */ |
| 274 | function parseTranscriptArray(arrayLiteral: string): TranscriptWord[] { |
| 275 | // Try parsing as-is first (handles already-valid JSON) |
| 276 | let parsed: unknown; |
| 277 | try { |
| 278 | parsed = JSON.parse(arrayLiteral); |
| 279 | } catch { |
| 280 | // Not valid JSON — normalize single quotes, unquoted keys, trailing commas |
| 281 | let normalized = arrayLiteral; |
| 282 | normalized = normalized.replace(/'((?:[^'\\]|\\.)*)'/g, (_match, inner) => { |
| 283 | const escaped = inner.replace(/\\'/g, "'").replace(/"/g, '\\"'); |
| 284 | return `"${escaped}"`; |
| 285 | }); |
| 286 | normalized = normalized.replace(/([{,]\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)\s*:/g, '$1"$2":'); |
| 287 | normalized = normalized.replace(/,(\s*[}\]])/g, "$1"); |
| 288 | parsed = JSON.parse(normalized); |
| 289 | } |
| 290 | |
| 291 | if (!Array.isArray(parsed)) { |
| 292 | return []; |
| 293 | } |
| 294 | |
| 295 | const words: TranscriptWord[] = []; |
| 296 | for (const item of parsed) { |
| 297 | if ( |
| 298 | item !== null && |
| 299 | typeof item === "object" && |
| 300 | typeof (item as Record<string, unknown>).text === "string" && |
| 301 | typeof (item as Record<string, unknown>).start === "number" && |
| 302 | typeof (item as Record<string, unknown>).end === "number" |
| 303 | ) { |
| 304 | const entry = item as Record<string, unknown>; |
| 305 | words.push({ |
| 306 | ...(typeof entry.id === "string" ? { id: entry.id } : {}), |
| 307 | text: entry.text as string, |
| 308 | start: entry.start as number, |
| 309 | end: entry.end as number, |
| 310 | }); |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | return words; |
| 315 | } |