subcraft 0.0.0-stage → 0.2.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.
package/dist/index.cjs ADDED
@@ -0,0 +1,417 @@
1
+ 'use strict';
2
+
3
+ // src/types.ts
4
+ var getCueDuration = (cue) => cue.end - cue.start;
5
+
6
+ // src/timecode.ts
7
+ var TIMECODE_REGEX = /^(?:(?:(\d{1,2}):)?(\d{2}):)?(\d{2})[,.](\d{3})$/;
8
+ function timecodeToMs(timecode) {
9
+ const trimmed = timecode.trim();
10
+ const match = trimmed.match(TIMECODE_REGEX);
11
+ if (!match) {
12
+ throw new Error(
13
+ `Invalid timecode format: "${timecode}". Expected "HH:MM:SS,mmm" or "HH:MM:SS.mmm".`
14
+ );
15
+ }
16
+ const hours = match[1] ? parseInt(match[1], 10) : 0;
17
+ const minutes = match[2] ? parseInt(match[2], 10) : 0;
18
+ const seconds = parseInt(match[3] ?? "0", 10);
19
+ const milliseconds = parseInt(match[4] ?? "0", 10);
20
+ return hours * 36e5 + minutes * 6e4 + seconds * 1e3 + milliseconds;
21
+ }
22
+ function msToTimecode(ms, format = "srt") {
23
+ const safeMs = Math.max(0, Math.floor(ms));
24
+ const hours = Math.floor(safeMs / 36e5);
25
+ const minutes = Math.floor(safeMs % 36e5 / 6e4);
26
+ const seconds = Math.floor(safeMs % 6e4 / 1e3);
27
+ const remainderMs = safeMs % 1e3;
28
+ const hh = String(hours).padStart(2, "0");
29
+ const mm = String(minutes).padStart(2, "0");
30
+ const ss = String(seconds).padStart(2, "0");
31
+ const mmm = String(remainderMs).padStart(3, "0");
32
+ const delimiter = format === "vtt" ? "." : ",";
33
+ return `${hh}:${mm}:${ss}${delimiter}${mmm}`;
34
+ }
35
+ function shiftTimecodes(cues, offsetMs) {
36
+ return cues.map((cue) => ({
37
+ ...cue,
38
+ start: Math.max(0, cue.start + offsetMs),
39
+ end: Math.max(0, cue.end + offsetMs)
40
+ }));
41
+ }
42
+ function retime(cues, ratio) {
43
+ if (ratio <= 0) {
44
+ throw new Error(`Retime ratio must be greater than 0. Received: ${ratio}`);
45
+ }
46
+ return cues.map((cue) => ({
47
+ ...cue,
48
+ start: Math.round(cue.start * ratio),
49
+ end: Math.round(cue.end * ratio)
50
+ }));
51
+ }
52
+
53
+ // src/parser.ts
54
+ var ARROW_REGEX = /((?:\d{1,2}:)?\d{2}:\d{2}[,.]\d{3})\s*-->\s*((?:\d{1,2}:)?\d{2}:\d{2}[,.]\d{3})/;
55
+ function parseSRT(rawText) {
56
+ const cues = [];
57
+ const errors = [];
58
+ if (!rawText || !rawText.trim()) {
59
+ return { cues, errors };
60
+ }
61
+ const cleanText = rawText.replace(/^\uFEFF/, "");
62
+ const normalized = cleanText.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
63
+ const rawBlocks = normalized.trim().split(/\n\s*\n+/);
64
+ let fallbackIndex = 1;
65
+ for (let bIndex = 0; bIndex < rawBlocks.length; bIndex++) {
66
+ const rawBlock = rawBlocks[bIndex]?.trim();
67
+ if (!rawBlock) continue;
68
+ const lines = rawBlock.split("\n");
69
+ let id;
70
+ let timecodeLine;
71
+ let textLines;
72
+ if (lines[0] && ARROW_REGEX.test(lines[0])) {
73
+ id = String(fallbackIndex);
74
+ timecodeLine = lines[0];
75
+ textLines = lines.slice(1);
76
+ } else if (lines[1] && ARROW_REGEX.test(lines[1])) {
77
+ id = lines[0]?.trim() || String(fallbackIndex);
78
+ timecodeLine = lines[1];
79
+ textLines = lines.slice(2);
80
+ } else {
81
+ errors.push({
82
+ index: fallbackIndex,
83
+ rawBlock,
84
+ message: 'Invalid block format. Expected timecode arrow "-->" on line 1 or 2.'
85
+ });
86
+ continue;
87
+ }
88
+ const match = timecodeLine.match(ARROW_REGEX);
89
+ if (!match || !match[1] || !match[2]) {
90
+ errors.push({
91
+ index: fallbackIndex,
92
+ rawBlock,
93
+ message: `Failed to extract start and end timestamps from: "${timecodeLine}".`
94
+ });
95
+ continue;
96
+ }
97
+ try {
98
+ const start = timecodeToMs(match[1]);
99
+ const end = timecodeToMs(match[2]);
100
+ const text = textLines.join("\n").trim();
101
+ cues.push({
102
+ id,
103
+ start,
104
+ end,
105
+ text
106
+ });
107
+ fallbackIndex++;
108
+ } catch (err) {
109
+ errors.push({
110
+ index: fallbackIndex,
111
+ rawBlock,
112
+ message: err instanceof Error ? err.message : String(err)
113
+ });
114
+ }
115
+ }
116
+ return { cues, errors };
117
+ }
118
+
119
+ // src/serializer.ts
120
+ function stringifySRT(cues) {
121
+ if (!cues || cues.length === 0) {
122
+ return "";
123
+ }
124
+ const blocks = cues.map((cue, idx) => {
125
+ const id = cue.id ? String(cue.id) : String(idx + 1);
126
+ const startStr = msToTimecode(cue.start, "srt");
127
+ const endStr = msToTimecode(cue.end, "srt");
128
+ const text = cue.text ?? "";
129
+ return `${id}
130
+ ${startStr} --> ${endStr}
131
+ ${text}`;
132
+ });
133
+ return blocks.join("\n\n") + "\n";
134
+ }
135
+
136
+ // src/vtt.ts
137
+ var VTT_ARROW_REGEX = /((?:\d{1,2}:)?\d{2}:\d{2}[,.]\d{3})\s*-->\s*((?:\d{1,2}:)?\d{2}:\d{2}[,.]\d{3})(?:[ \t]+([^\r\n]+))?/;
138
+ function parseVTT(rawText) {
139
+ const cues = [];
140
+ const errors = [];
141
+ if (!rawText || !rawText.trim()) {
142
+ return { cues, errors };
143
+ }
144
+ const clean = rawText.replace(/^\uFEFF/, "");
145
+ const normalized = clean.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
146
+ if (!normalized.startsWith("WEBVTT")) {
147
+ errors.push({
148
+ rawBlock: normalized.slice(0, 50),
149
+ message: 'Missing standard "WEBVTT" signature at the beginning of the file.'
150
+ });
151
+ }
152
+ const rawBlocks = normalized.trim().split(/\n\s*\n+/);
153
+ let fallbackIndex = 1;
154
+ for (let bIndex = 0; bIndex < rawBlocks.length; bIndex++) {
155
+ const rawBlock = rawBlocks[bIndex]?.trim();
156
+ if (!rawBlock) continue;
157
+ if (bIndex === 0 && rawBlock.startsWith("WEBVTT")) {
158
+ continue;
159
+ }
160
+ if (rawBlock.startsWith("NOTE")) {
161
+ continue;
162
+ }
163
+ if (rawBlock.startsWith("STYLE") || rawBlock.startsWith("REGION")) {
164
+ continue;
165
+ }
166
+ const lines = rawBlock.split("\n");
167
+ let id;
168
+ let timecodeLine;
169
+ let textLines;
170
+ if (lines[0] && VTT_ARROW_REGEX.test(lines[0])) {
171
+ id = String(fallbackIndex);
172
+ timecodeLine = lines[0];
173
+ textLines = lines.slice(1);
174
+ } else if (lines[1] && VTT_ARROW_REGEX.test(lines[1])) {
175
+ id = lines[0]?.trim() || String(fallbackIndex);
176
+ timecodeLine = lines[1];
177
+ textLines = lines.slice(2);
178
+ } else {
179
+ errors.push({
180
+ index: fallbackIndex,
181
+ rawBlock,
182
+ message: 'Invalid WebVTT cue block. Missing timecode arrow "-->".'
183
+ });
184
+ continue;
185
+ }
186
+ const match = timecodeLine.match(VTT_ARROW_REGEX);
187
+ if (!match || !match[1] || !match[2]) {
188
+ errors.push({
189
+ index: fallbackIndex,
190
+ rawBlock,
191
+ message: `Failed to parse timestamps from WebVTT cue: "${timecodeLine}".`
192
+ });
193
+ continue;
194
+ }
195
+ try {
196
+ const start = timecodeToMs(match[1]);
197
+ const end = timecodeToMs(match[2]);
198
+ const settings = match[3]?.trim();
199
+ const text = textLines.join("\n").trim();
200
+ const cue = {
201
+ id,
202
+ start,
203
+ end,
204
+ text
205
+ };
206
+ if (settings) {
207
+ cue.settings = settings;
208
+ }
209
+ cues.push(cue);
210
+ fallbackIndex++;
211
+ } catch (err) {
212
+ errors.push({
213
+ index: fallbackIndex,
214
+ rawBlock,
215
+ message: err instanceof Error ? err.message : String(err)
216
+ });
217
+ }
218
+ }
219
+ return { cues, errors };
220
+ }
221
+ function stringifyVTT(cues, options) {
222
+ const header = options?.header ? `WEBVTT - ${options.header}` : "WEBVTT";
223
+ if (!cues || cues.length === 0) {
224
+ return `${header}
225
+ `;
226
+ }
227
+ const includeIds = options?.includeIds ?? false;
228
+ const blocks = cues.map((cue, idx) => {
229
+ const id = cue.id ? String(cue.id) : String(idx + 1);
230
+ const startStr = msToTimecode(cue.start, "vtt");
231
+ const endStr = msToTimecode(cue.end, "vtt");
232
+ const settingsStr = cue.settings ? ` ${cue.settings}` : "";
233
+ const timeLine = `${startStr} --> ${endStr}${settingsStr}`;
234
+ const text = cue.text ?? "";
235
+ if (includeIds) {
236
+ return `${id}
237
+ ${timeLine}
238
+ ${text}`;
239
+ }
240
+ return `${timeLine}
241
+ ${text}`;
242
+ });
243
+ return `${header}
244
+
245
+ ${blocks.join("\n\n")}
246
+ `;
247
+ }
248
+ function srtToVTT(srtText, options) {
249
+ const { cues } = parseSRT(srtText);
250
+ return stringifyVTT(cues, options);
251
+ }
252
+ function vttToSRT(vttText) {
253
+ const { cues } = parseVTT(vttText);
254
+ return stringifySRT(cues);
255
+ }
256
+
257
+ // src/linter.ts
258
+ var DEFAULT_PROFILES = {
259
+ standardLatin: {
260
+ name: "Standard Latin (Netflix/BBC Style Guide)",
261
+ locale: "en",
262
+ maxCps: 20,
263
+ maxCpl: 42,
264
+ minDurationMs: 800,
265
+ maxDurationMs: 7e3,
266
+ includeSpaces: true
267
+ },
268
+ indicKannada: {
269
+ name: "Indic - Kannada Locale",
270
+ locale: "kn",
271
+ maxCps: 15,
272
+ maxCpl: 35,
273
+ minDurationMs: 800,
274
+ maxDurationMs: 7e3,
275
+ includeSpaces: true
276
+ }
277
+ };
278
+ function stripFormattingTags(text) {
279
+ return text.replace(/<[^>]*>/g, "");
280
+ }
281
+ function countGraphemes(text, locale = "en") {
282
+ if (!text) return 0;
283
+ if (typeof Intl !== "undefined" && "Segmenter" in Intl) {
284
+ const segmenter = new Intl.Segmenter(locale, { granularity: "grapheme" });
285
+ let count = 0;
286
+ for (const _ of segmenter.segment(text)) {
287
+ count++;
288
+ }
289
+ return count;
290
+ }
291
+ return [...text].length;
292
+ }
293
+ function lintCues(cues, customProfile) {
294
+ const diagnostics = [];
295
+ if (!cues || cues.length === 0) return diagnostics;
296
+ const profile = {
297
+ ...DEFAULT_PROFILES["standardLatin"],
298
+ ...customProfile
299
+ };
300
+ const {
301
+ locale = "en",
302
+ maxCps,
303
+ maxCpl,
304
+ minDurationMs,
305
+ maxDurationMs,
306
+ includeSpaces = true
307
+ } = profile;
308
+ for (let i = 0; i < cues.length; i++) {
309
+ const cue = cues[i];
310
+ if (!cue) continue;
311
+ const prevCue = i > 0 ? cues[i - 1] : void 0;
312
+ const duration = cue.end - cue.start;
313
+ if (prevCue && cue.start < prevCue.start) {
314
+ diagnostics.push({
315
+ cueId: cue.id,
316
+ rule: "out-of-order",
317
+ severity: "error",
318
+ message: `Cue starts at ${cue.start}ms before previous cue start of ${prevCue.start}ms.`,
319
+ expected: `start >= ${prevCue.start}`,
320
+ actual: `start = ${cue.start}`
321
+ });
322
+ }
323
+ if (cue.end <= cue.start) {
324
+ diagnostics.push({
325
+ cueId: cue.id,
326
+ rule: "zero-or-negative-duration",
327
+ severity: "error",
328
+ message: `Cue has invalid duration (${duration}ms). End timestamp must be greater than start timestamp.`,
329
+ expected: `end > ${cue.start}`,
330
+ actual: `end = ${cue.end}`
331
+ });
332
+ }
333
+ if (prevCue && cue.start < prevCue.end && cue.start >= prevCue.start) {
334
+ const overlapMs = prevCue.end - cue.start;
335
+ diagnostics.push({
336
+ cueId: cue.id,
337
+ rule: "overlap",
338
+ severity: "error",
339
+ message: `Cue overlaps with previous cue by ${overlapMs}ms.`,
340
+ expected: `start >= ${prevCue.end}`,
341
+ actual: `start = ${cue.start}`
342
+ });
343
+ }
344
+ if (duration > 0 && duration < minDurationMs) {
345
+ diagnostics.push({
346
+ cueId: cue.id,
347
+ rule: "min-duration",
348
+ severity: "warning",
349
+ message: `Cue duration of ${duration}ms is below the minimum threshold of ${minDurationMs}ms.`,
350
+ expected: minDurationMs,
351
+ actual: duration
352
+ });
353
+ }
354
+ if (duration > maxDurationMs) {
355
+ diagnostics.push({
356
+ cueId: cue.id,
357
+ rule: "max-duration",
358
+ severity: "warning",
359
+ message: `Cue duration of ${duration}ms exceeds the maximum threshold of ${maxDurationMs}ms.`,
360
+ expected: maxDurationMs,
361
+ actual: duration
362
+ });
363
+ }
364
+ const rawText = cue.text || "";
365
+ const cleanText = stripFormattingTags(rawText);
366
+ const lines = cleanText.split("\n");
367
+ for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
368
+ const line = lines[lineIndex];
369
+ if (!line) continue;
370
+ const cpl = countGraphemes(line, locale);
371
+ if (cpl > maxCpl) {
372
+ diagnostics.push({
373
+ cueId: cue.id,
374
+ rule: "max-cpl",
375
+ severity: "warning",
376
+ message: `Line ${lineIndex + 1} has ${cpl} characters, exceeding the maximum limit of ${maxCpl} CPL.`,
377
+ expected: maxCpl,
378
+ actual: cpl
379
+ });
380
+ }
381
+ }
382
+ if (duration > 0) {
383
+ const textToMeasure = includeSpaces ? cleanText : cleanText.replace(/\s+/g, "");
384
+ const totalGraphemes = countGraphemes(textToMeasure, locale);
385
+ const cps = Number((totalGraphemes / duration * 1e3).toFixed(1));
386
+ if (cps > maxCps) {
387
+ diagnostics.push({
388
+ cueId: cue.id,
389
+ rule: "max-cps",
390
+ severity: "warning",
391
+ message: `Reading speed of ${cps} CPS exceeds maximum limit of ${maxCps} CPS.`,
392
+ expected: maxCps,
393
+ actual: cps
394
+ });
395
+ }
396
+ }
397
+ }
398
+ return diagnostics;
399
+ }
400
+
401
+ exports.DEFAULT_PROFILES = DEFAULT_PROFILES;
402
+ exports.countGraphemes = countGraphemes;
403
+ exports.getCueDuration = getCueDuration;
404
+ exports.lintCues = lintCues;
405
+ exports.msToTimecode = msToTimecode;
406
+ exports.parseSRT = parseSRT;
407
+ exports.parseVTT = parseVTT;
408
+ exports.retime = retime;
409
+ exports.shiftTimecodes = shiftTimecodes;
410
+ exports.srtToVTT = srtToVTT;
411
+ exports.stringifySRT = stringifySRT;
412
+ exports.stringifyVTT = stringifyVTT;
413
+ exports.stripFormattingTags = stripFormattingTags;
414
+ exports.timecodeToMs = timecodeToMs;
415
+ exports.vttToSRT = vttToSRT;
416
+ //# sourceMappingURL=index.cjs.map
417
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/types.ts","../src/timecode.ts","../src/parser.ts","../src/serializer.ts","../src/vtt.ts","../src/linter.ts"],"names":[],"mappings":";;;AAqBO,IAAM,cAAA,GAAiB,CAAC,GAAA,KAA6B,GAAA,CAAI,MAAM,GAAA,CAAI;;;ACb1E,IAAM,cAAA,GAAiB,kDAAA;AAYhB,SAAS,aAAa,QAAA,EAA0B;AACrD,EAAA,MAAM,OAAA,GAAU,SAAS,IAAA,EAAK;AAC9B,EAAA,MAAM,KAAA,GAAQ,OAAA,CAAQ,KAAA,CAAM,cAAc,CAAA;AAE1C,EAAA,IAAI,CAAC,KAAA,EAAO;AACV,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,6BAA6B,QAAQ,CAAA,6CAAA;AAAA,KACvC;AAAA,EACF;AAEA,EAAA,MAAM,KAAA,GAAQ,MAAM,CAAC,CAAA,GAAI,SAAS,KAAA,CAAM,CAAC,CAAA,EAAG,EAAE,CAAA,GAAI,CAAA;AAClD,EAAA,MAAM,OAAA,GAAU,MAAM,CAAC,CAAA,GAAI,SAAS,KAAA,CAAM,CAAC,CAAA,EAAG,EAAE,CAAA,GAAI,CAAA;AACpD,EAAA,MAAM,UAAU,QAAA,CAAS,KAAA,CAAM,CAAC,CAAA,IAAK,KAAK,EAAE,CAAA;AAC5C,EAAA,MAAM,eAAe,QAAA,CAAS,KAAA,CAAM,CAAC,CAAA,IAAK,KAAK,EAAE,CAAA;AAEjD,EAAA,OACE,KAAA,GAAQ,IAAA,GACR,OAAA,GAAU,GAAA,GACV,UAAU,GAAA,GACV,YAAA;AAEJ;AAYO,SAAS,YAAA,CAAa,EAAA,EAAY,MAAA,GAAyB,KAAA,EAAe;AAC/E,EAAA,MAAM,SAAS,IAAA,CAAK,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CAAA,EAAG;AAChB,MAAA,MAAM,gBAAgB,aAAA,GAClB,SAAA,GACA,SAAA,CAAU,OAAA,CAAQ,QAAQ,EAAE,CAAA;AAEhC,MAAA,MAAM,cAAA,GAAiB,cAAA,CAAe,aAAA,EAAe,MAAM,CAAA;AAC3D,MAAA,MAAM,MAAM,MAAA,CAAA,CAAS,cAAA,GAAiB,WAAY,GAAA,EAAM,OAAA,CAAQ,CAAC,CAAC,CAAA;AAElE,MAAA,IAAI,MAAM,MAAA,EAAQ;AAChB,QAAA,WAAA,CAAY,IAAA,CAAK;AAAA,UACf,OAAO,GAAA,CAAI,EAAA;AAAA,UACX,IAAA,EAAM,SAAA;AAAA,UACN,QAAA,EAAU,SAAA;AAAA,UACV,OAAA,EAAS,CAAA,iBAAA,EAAoB,GAAG,CAAA,8BAAA,EAAiC,MAAM,CAAA,KAAA,CAAA;AAAA,UACvE,QAAA,EAAU,MAAA;AAAA,UACV,MAAA,EAAQ;AAAA,SACT,CAAA;AAAA,MACH;AAAA,IACF;AAAA,EACF;AAEA,EAAA,OAAO,WAAA;AACT","file":"index.cjs","sourcesContent":["/**\n * Core normalized representation of a single subtitle cue.\n * Timestamps are strictly stored in integer milliseconds.\n */\nexport interface SubtitleCue {\n /** Unique sequential identifier (e.g. \"1\", \"2\") */\n id: string;\n /** Start time in integer milliseconds */\n start: number;\n /** End time in integer milliseconds */\n end: number;\n /** Raw subtitle text content (may contain newlines) */\n text: string;\n /** Optional WebVTT cue placement/styling settings (e.g., \"align:middle line:90%\") */\n settings?: string;\n}\n\n/**\n * Calculates the duration of a cue in milliseconds.\n * Derived helper function to keep the core data model minimal and immutable.\n */\nexport const getCueDuration = (cue: SubtitleCue): number => cue.end - cue.start;\n\n/** Supported subtitle file formats */\nexport type TimecodeFormat = 'srt' | 'vtt';\n\n/**\n * Detailed error reported when a cue block fails parsing syntax rules.\n */\nexport interface ParseError {\n index?: number;\n rawBlock: string;\n message: string;\n}\n\n/**\n * Resilient parser result returning successfully parsed cues\n * alongside any syntax errors encountered without throwing.\n */\nexport interface ParseResult {\n cues: SubtitleCue[];\n errors: ParseError[];\n}\n\n/** Severity levels for lint diagnostics */\nexport type LintSeverity = 'error' | 'warning';\n\n/** Quality rules enforced by the linter */\nexport type LintRule =\n | 'out-of-order'\n | 'overlap'\n | 'zero-or-negative-duration'\n | 'min-duration'\n | 'max-duration'\n | 'max-cpl'\n | 'max-cps';\n\n/**\n * Diagnostic report produced when a cue violates a quality rule.\n */\nexport interface LintDiagnostic {\n cueId: string;\n rule: LintRule;\n severity: LintSeverity;\n message: string;\n expected?: number | string;\n actual?: number | string;\n}\n\n/**\n * Configuration options for locale-aware subtitle validation.\n */\nexport interface LintProfile {\n name: string;\n locale?: string;\n maxCps: number;\n maxCpl: number;\n minDurationMs: number;\n maxDurationMs: number;\n includeSpaces?: boolean;\n}\n","import type { SubtitleCue, TimecodeFormat } from './types.js';\n\n/**\n * Regular expression to match both SRT (comma) and WebVTT (dot) timecodes.\n * Supports:\n * - HH:MM:SS,mmm or HH:MM:SS.mmm\n * - MM:SS.mmm (WebVTT short format)\n */\nconst TIMECODE_REGEX = /^(?:(?:(\\d{1,2}):)?(\\d{2}):)?(\\d{2})[,.](\\d{3})$/;\n\n/**\n * Converts a formatted timecode string into integer milliseconds.\n *\n * Supported formats:\n * - \"01:23:45,678\" (SRT standard)\n * - \"01:23:45.678\" (WebVTT standard)\n * - \"23:45.678\" (WebVTT short form without hours)\n *\n * @throws {Error} if timecode format is invalid\n */\nexport function timecodeToMs(timecode: string): number {\n const trimmed = timecode.trim();\n const match = trimmed.match(TIMECODE_REGEX);\n\n if (!match) {\n throw new Error(\n `Invalid timecode format: \"${timecode}\". Expected \"HH:MM:SS,mmm\" or \"HH:MM:SS.mmm\".`\n );\n }\n\n const hours = match[1] ? parseInt(match[1], 10) : 0;\n const minutes = match[2] ? parseInt(match[2], 10) : 0;\n const seconds = parseInt(match[3] ?? '0', 10);\n const milliseconds = parseInt(match[4] ?? '0', 10);\n\n return (\n hours * 3_600_000 +\n minutes * 60_000 +\n seconds * 1_000 +\n milliseconds\n );\n}\n\n/**\n * Converts integer milliseconds into a standard formatted timecode string.\n *\n * @param ms - Non-negative integer milliseconds (negative values clamped to 0)\n * @param format - 'srt' (uses comma delimiter) or 'vtt' (uses dot delimiter)\n *\n * @example\n * msToTimecode(83456, 'srt') // \"00:01:23,456\"\n * msToTimecode(83456, 'vtt') // \"00:01:23.456\"\n */\nexport function msToTimecode(ms: number, format: TimecodeFormat = 'srt'): string {\n const safeMs = Math.max(0, Math.floor(ms));\n\n const hours = Math.floor(safeMs / 3_600_000);\n const minutes = Math.floor((safeMs % 3_600_000) / 60_000);\n const seconds = Math.floor((safeMs % 60_000) / 1_000);\n const remainderMs = safeMs % 1_000;\n\n const hh = String(hours).padStart(2, '0');\n const mm = String(minutes).padStart(2, '0');\n const ss = String(seconds).padStart(2, '0');\n const mmm = String(remainderMs).padStart(3, '0');\n\n const delimiter = format === 'vtt' ? '.' : ',';\n return `${hh}:${mm}:${ss}${delimiter}${mmm}`;\n}\n\n/**\n * Linearly shifts timecodes by a constant millisecond offset.\n * Used to correct audio-sync delay or advance.\n * Clamps negative results to 0.\n *\n * @param cues - Array of SubtitleCue objects\n * @param offsetMs - Offset in milliseconds (positive advances, negative delays)\n * @returns A new immutable array of shifted cues\n */\nexport function shiftTimecodes(\n cues: readonly SubtitleCue[],\n offsetMs: number\n): SubtitleCue[] {\n return cues.map((cue) => ({\n ...cue,\n start: Math.max(0, cue.start + offsetMs),\n end: Math.max(0, cue.end + offsetMs),\n }));\n}\n\n/**\n * Scales all cue timecodes by a multiplicative ratio.\n * Used for frame-rate drift compensation between video standards.\n * All results are strictly rounded to integer milliseconds with Math.round.\n *\n * Direction definition:\n * targetTimestamp = Math.round(sourceTimestamp * ratio)\n *\n * @example\n * // 24 fps to 25 fps (PAL speed-up): video is ~4% faster, timecodes compress\n * const palCues = retime(filmCues, 24 / 25); // ratio = 0.96\n *\n * @example\n * // 25 fps to 24 fps (Slow-down): video is ~4% slower, timecodes stretch\n * const filmCues = retime(palCues, 25 / 24); // ratio = 1.04167\n *\n * @param cues - Array of SubtitleCue objects\n * @param ratio - Positive scaling multiplier (e.g., 24/25 or 25/24)\n * @returns A new immutable array of retimed cues\n */\nexport function retime(\n cues: readonly SubtitleCue[],\n ratio: number\n): SubtitleCue[] {\n if (ratio <= 0) {\n throw new Error(`Retime ratio must be greater than 0. Received: ${ratio}`);\n }\n\n return cues.map((cue) => ({\n ...cue,\n start: Math.round(cue.start * ratio),\n end: Math.round(cue.end * ratio),\n }));\n}\n","import { timecodeToMs } from './timecode.js';\nimport type { SubtitleCue, ParseError, ParseResult } from './types.js';\n\n/** Matches the standard SRT timestamp line: 00:00:00,000 --> 00:00:00,000 */\nconst ARROW_REGEX =\n /((?:\\d{1,2}:)?\\d{2}:\\d{2}[,.]\\d{3})\\s*-->\\s*((?:\\d{1,2}:)?\\d{2}:\\d{2}[,.]\\d{3})/;\n\n/**\n * Parses raw SRT subtitle text into structured SubtitleCue objects.\n * Resilient parser that collects syntax errors without throwing unhandled exceptions.\n *\n * Handles:\n * - UTF-8 Byte Order Marks (BOM `\\uFEFF`)\n * - Windows (CRLF), Unix (LF), and legacy Mac (CR) line endings\n * - Optional or missing cue numeric index headers\n * - Multi-line subtitle texts\n * - Trailing and irregular blank lines\n *\n * @param rawText - Raw SRT file content as a string\n * @returns {ParseResult} Object containing successfully parsed cues and any block errors\n */\nexport function parseSRT(rawText: string): ParseResult {\n const cues: SubtitleCue[] = [];\n const errors: ParseError[] = [];\n\n if (!rawText || !rawText.trim()) {\n return { cues, errors };\n }\n\n // 1. Strip UTF-8 Byte Order Mark (BOM)\n const cleanText = rawText.replace(/^\\uFEFF/, '');\n\n // 2. Normalize CRLF and CR to standard Unix LF\n const normalized = cleanText.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n');\n\n // 3. Split by 2 or more consecutive newlines into cue blocks\n const rawBlocks = normalized.trim().split(/\\n\\s*\\n+/);\n\n let fallbackIndex = 1;\n\n for (let bIndex = 0; bIndex < rawBlocks.length; bIndex++) {\n const rawBlock = rawBlocks[bIndex]?.trim();\n if (!rawBlock) continue;\n\n const lines = rawBlock.split('\\n');\n\n let id: string;\n let timecodeLine: string;\n let textLines: string[];\n\n // Check if line 0 is the timecode arrow (missing numeric index)\n if (lines[0] && ARROW_REGEX.test(lines[0])) {\n id = String(fallbackIndex);\n timecodeLine = lines[0];\n textLines = lines.slice(1);\n } else if (lines[1] && ARROW_REGEX.test(lines[1])) {\n // Standard SRT: line 0 is ID, line 1 is timecode\n id = lines[0]?.trim() || String(fallbackIndex);\n timecodeLine = lines[1];\n textLines = lines.slice(2);\n } else {\n errors.push({\n index: fallbackIndex,\n rawBlock,\n message:\n 'Invalid block format. Expected timecode arrow \"-->\" on line 1 or 2.',\n });\n continue;\n }\n\n const match = timecodeLine.match(ARROW_REGEX);\n if (!match || !match[1] || !match[2]) {\n errors.push({\n index: fallbackIndex,\n rawBlock,\n message: `Failed to extract start and end timestamps from: \"${timecodeLine}\".`,\n });\n continue;\n }\n\n try {\n const start = timecodeToMs(match[1]);\n const end = timecodeToMs(match[2]);\n const text = textLines.join('\\n').trim();\n\n cues.push({\n id,\n start,\n end,\n text,\n });\n\n fallbackIndex++;\n } catch (err) {\n errors.push({\n index: fallbackIndex,\n rawBlock,\n message: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n return { cues, errors };\n}\n","import { msToTimecode } from './timecode.js';\nimport type { SubtitleCue } from './types.js';\n\n/**\n * Serializes an array of SubtitleCue objects into standard SRT file format.\n *\n * Output format:\n * 1\n * 00:00:20,000 --> 00:00:24,000\n * Subtitle text\n *\n * @param cues - Array of SubtitleCue objects to format\n * @returns Standard formatted SRT string\n */\nexport function stringifySRT(cues: readonly SubtitleCue[]): string {\n if (!cues || cues.length === 0) {\n return '';\n }\n\n const blocks = cues.map((cue, idx) => {\n const id = cue.id ? String(cue.id) : String(idx + 1);\n const startStr = msToTimecode(cue.start, 'srt');\n const endStr = msToTimecode(cue.end, 'srt');\n const text = cue.text ?? '';\n\n return `${id}\\n${startStr} --> ${endStr}\\n${text}`;\n });\n\n return blocks.join('\\n\\n') + '\\n';\n}\n","import { timecodeToMs, msToTimecode } from './timecode.js';\nimport { parseSRT } from './parser.js';\nimport { stringifySRT } from './serializer.js';\nimport type { SubtitleCue, ParseError, ParseResult } from './types.js';\n\n/**\n * Matches the WebVTT timestamp line with optional cue settings:\n * 00:01:20.500 --> 00:01:23.000 align:middle line:90%\n */\nconst VTT_ARROW_REGEX =\n /((?:\\d{1,2}:)?\\d{2}:\\d{2}[,.]\\d{3})\\s*-->\\s*((?:\\d{1,2}:)?\\d{2}:\\d{2}[,.]\\d{3})(?:[ \\t]+([^\\r\\n]+))?/;\n\nexport interface StringifyVTTOptions {\n /** Optional custom header line after WEBVTT (e.g. \"WEBVTT - Commentary Track\") */\n header?: string;\n /** Whether to output cue numeric ID headers (default: false for standard clean WebVTT) */\n includeIds?: boolean;\n}\n\n/**\n * Parses raw WebVTT (.vtt) subtitle text into structured SubtitleCue objects.\n *\n * Handles:\n * - UTF-8 Byte Order Marks (BOM \\uFEFF)\n * - WEBVTT header and metadata blocks\n * - NOTE comment blocks (skipped automatically)\n * - Dot-separated milliseconds (00:01:20.500) and comma-separated fallback\n * - Short timecodes without hours (MM:SS.mmm)\n * - Cue placement/styling settings (e.g. align:middle line:90%)\n * - Optional cue identifiers\n *\n * @param rawText - Raw WebVTT file content as a string\n * @returns {ParseResult} Successfully parsed cues and any block errors\n */\nexport function parseVTT(rawText: string): ParseResult {\n const cues: SubtitleCue[] = [];\n const errors: ParseError[] = [];\n\n if (!rawText || !rawText.trim()) {\n return { cues, errors };\n }\n\n // 1. Strip BOM & normalize newlines\n const clean = rawText.replace(/^\\uFEFF/, '');\n const normalized = clean.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n');\n\n // 2. Validate and strip WEBVTT header\n if (!normalized.startsWith('WEBVTT')) {\n errors.push({\n rawBlock: normalized.slice(0, 50),\n message: 'Missing standard \"WEBVTT\" signature at the beginning of the file.',\n });\n }\n\n // Split into blocks by double newlines\n const rawBlocks = normalized.trim().split(/\\n\\s*\\n+/);\n let fallbackIndex = 1;\n\n for (let bIndex = 0; bIndex < rawBlocks.length; bIndex++) {\n const rawBlock = rawBlocks[bIndex]?.trim();\n if (!rawBlock) continue;\n\n // Skip the very first block if it is just the WEBVTT header line\n if (bIndex === 0 && rawBlock.startsWith('WEBVTT')) {\n continue;\n }\n\n // Skip NOTE comment blocks\n if (rawBlock.startsWith('NOTE')) {\n continue;\n }\n\n // Skip STYLE or REGION metadata blocks if encountered\n if (rawBlock.startsWith('STYLE') || rawBlock.startsWith('REGION')) {\n continue;\n }\n\n const lines = rawBlock.split('\\n');\n let id: string;\n let timecodeLine: string;\n let textLines: string[];\n\n // Case 1: First line is the timestamp arrow (no cue ID header)\n if (lines[0] && VTT_ARROW_REGEX.test(lines[0])) {\n id = String(fallbackIndex);\n timecodeLine = lines[0];\n textLines = lines.slice(1);\n } else if (lines[1] && VTT_ARROW_REGEX.test(lines[1])) {\n // Case 2: Line 0 is ID header, line 1 is timestamp\n id = lines[0]?.trim() || String(fallbackIndex);\n timecodeLine = lines[1];\n textLines = lines.slice(2);\n } else {\n errors.push({\n index: fallbackIndex,\n rawBlock,\n message: 'Invalid WebVTT cue block. Missing timecode arrow \"-->\".',\n });\n continue;\n }\n\n const match = timecodeLine.match(VTT_ARROW_REGEX);\n if (!match || !match[1] || !match[2]) {\n errors.push({\n index: fallbackIndex,\n rawBlock,\n message: `Failed to parse timestamps from WebVTT cue: \"${timecodeLine}\".`,\n });\n continue;\n }\n\n try {\n const start = timecodeToMs(match[1]);\n const end = timecodeToMs(match[2]);\n const settings = match[3]?.trim();\n const text = textLines.join('\\n').trim();\n\n const cue: SubtitleCue = {\n id,\n start,\n end,\n text,\n };\n\n if (settings) {\n cue.settings = settings;\n }\n\n cues.push(cue);\n fallbackIndex++;\n } catch (err) {\n errors.push({\n index: fallbackIndex,\n rawBlock,\n message: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n return { cues, errors };\n}\n\n/**\n * Serializes an array of SubtitleCue objects into standard WebVTT (.vtt) file format.\n *\n * @param cues - Array of SubtitleCue objects to format\n * @param options - Formatting options (header title, inclusion of cue IDs)\n * @returns Formatted WebVTT string\n */\nexport function stringifyVTT(\n cues: readonly SubtitleCue[],\n options?: StringifyVTTOptions\n): string {\n const header = options?.header ? `WEBVTT - ${options.header}` : 'WEBVTT';\n\n if (!cues || cues.length === 0) {\n return `${header}\\n`;\n }\n\n const includeIds = options?.includeIds ?? false;\n\n const blocks = cues.map((cue, idx) => {\n const id = cue.id ? String(cue.id) : String(idx + 1);\n const startStr = msToTimecode(cue.start, 'vtt');\n const endStr = msToTimecode(cue.end, 'vtt');\n const settingsStr = cue.settings ? ` ${cue.settings}` : '';\n const timeLine = `${startStr} --> ${endStr}${settingsStr}`;\n const text = cue.text ?? '';\n\n if (includeIds) {\n return `${id}\\n${timeLine}\\n${text}`;\n }\n return `${timeLine}\\n${text}`;\n });\n\n return `${header}\\n\\n${blocks.join('\\n\\n')}\\n`;\n}\n\n/**\n * Converts raw SRT subtitle text directly into a valid WebVTT (.vtt) string.\n *\n * @param srtText - Raw SubRip (.srt) text content\n * @param options - WebVTT formatting options\n * @returns Formatted WebVTT string\n */\nexport function srtToVTT(\n srtText: string,\n options?: StringifyVTTOptions\n): string {\n const { cues } = parseSRT(srtText);\n return stringifyVTT(cues, options);\n}\n\n/**\n * Converts raw WebVTT subtitle text directly into a standard SRT (.srt) string.\n *\n * @param vttText - Raw WebVTT (.vtt) text content\n * @returns Standard SubRip (.srt) string\n */\nexport function vttToSRT(vttText: string): string {\n const { cues } = parseVTT(vttText);\n return stringifySRT(cues);\n}\n","import type {\n SubtitleCue,\n LintDiagnostic,\n LintProfile,\n} from './types.js';\n\n/** Default quality profiles for subtitle verification */\nexport const DEFAULT_PROFILES: Record<string, LintProfile> = {\n standardLatin: {\n name: 'Standard Latin (Netflix/BBC Style Guide)',\n locale: 'en',\n maxCps: 20,\n maxCpl: 42,\n minDurationMs: 800,\n maxDurationMs: 7000,\n includeSpaces: true,\n },\n indicKannada: {\n name: 'Indic - Kannada Locale',\n locale: 'kn',\n maxCps: 15,\n maxCpl: 35,\n minDurationMs: 800,\n maxDurationMs: 7000,\n includeSpaces: true,\n },\n};\n\n/**\n * Strips HTML formatting tags from subtitle text before measuring character limits.\n * Handles <i>, <b>, <u>, <font color=\"...\">, etc.\n */\nexport function stripFormattingTags(text: string): string {\n return text.replace(/<[^>]*>/g, '');\n}\n\n/**\n * Counts user-perceived grapheme clusters using native ECMAScript Intl.Segmenter.\n * Accurately measures multi-byte conjuncts and vowel modifiers in Indic scripts (Kannada, Hindi),\n * as well as emojis and complex Unicode characters without UTF-16 code unit inflation.\n */\nexport function countGraphemes(text: string, locale: string = 'en'): number {\n if (!text) return 0;\n\n if (typeof Intl !== 'undefined' && 'Segmenter' in Intl) {\n const segmenter = new Intl.Segmenter(locale, { granularity: 'grapheme' });\n let count = 0;\n // Iterate over segments efficiently without allocating full array\n for (const _ of segmenter.segment(text)) {\n count++;\n }\n return count;\n }\n\n // Fallback for environments lacking Intl.Segmenter\n return [...text].length;\n}\n\n/**\n * Inspects an array of SubtitleCues against timing, structural, and reading speed rules.\n *\n * Rules verified:\n * - out-of-order: Cues not in ascending chronological order\n * - zero-or-negative-duration: Cues where end <= start\n * - overlap: Cues overlapping chronologically with preceding cues\n * - min-duration: Cues flashing too fast for comprehension (< 800ms)\n * - max-duration: Cues remaining on screen too long (> 7000ms)\n * - max-cpl: Any line exceeding characters-per-line limit\n * - max-cps: Reading speed exceeding characters-per-second limit\n *\n * @param cues - Array of SubtitleCue objects to inspect\n * @param customProfile - Optional custom thresholds or language profile\n * @returns Array of LintDiagnostic reports\n */\nexport function lintCues(\n cues: readonly SubtitleCue[],\n customProfile?: Partial<LintProfile>\n): LintDiagnostic[] {\n const diagnostics: LintDiagnostic[] = [];\n if (!cues || cues.length === 0) return diagnostics;\n\n const profile: LintProfile = {\n ...DEFAULT_PROFILES['standardLatin']!,\n ...customProfile,\n };\n\n const {\n locale = 'en',\n maxCps,\n maxCpl,\n minDurationMs,\n maxDurationMs,\n includeSpaces = true,\n } = profile;\n\n for (let i = 0; i < cues.length; i++) {\n const cue = cues[i];\n if (!cue) continue;\n\n const prevCue = i > 0 ? cues[i - 1] : undefined;\n const duration = cue.end - cue.start;\n\n // --- TIMING RULES ---\n\n // 1. Out-of-order check\n if (prevCue && cue.start < prevCue.start) {\n diagnostics.push({\n cueId: cue.id,\n rule: 'out-of-order',\n severity: 'error',\n message: `Cue starts at ${cue.start}ms before previous cue start of ${prevCue.start}ms.`,\n expected: `start >= ${prevCue.start}`,\n actual: `start = ${cue.start}`,\n });\n }\n\n // 2. Zero or negative duration check\n if (cue.end <= cue.start) {\n diagnostics.push({\n cueId: cue.id,\n rule: 'zero-or-negative-duration',\n severity: 'error',\n message: `Cue has invalid duration (${duration}ms). End timestamp must be greater than start timestamp.`,\n expected: `end > ${cue.start}`,\n actual: `end = ${cue.end}`,\n });\n }\n\n // 3. Overlap check (only if not out-of-order)\n if (prevCue && cue.start < prevCue.end && cue.start >= prevCue.start) {\n const overlapMs = prevCue.end - cue.start;\n diagnostics.push({\n cueId: cue.id,\n rule: 'overlap',\n severity: 'error',\n message: `Cue overlaps with previous cue by ${overlapMs}ms.`,\n expected: `start >= ${prevCue.end}`,\n actual: `start = ${cue.start}`,\n });\n }\n\n // 4. Min duration check (only if duration is positive)\n if (duration > 0 && duration < minDurationMs) {\n diagnostics.push({\n cueId: cue.id,\n rule: 'min-duration',\n severity: 'warning',\n message: `Cue duration of ${duration}ms is below the minimum threshold of ${minDurationMs}ms.`,\n expected: minDurationMs,\n actual: duration,\n });\n }\n\n // 5. Max duration check\n if (duration > maxDurationMs) {\n diagnostics.push({\n cueId: cue.id,\n rule: 'max-duration',\n severity: 'warning',\n message: `Cue duration of ${duration}ms exceeds the maximum threshold of ${maxDurationMs}ms.`,\n expected: maxDurationMs,\n actual: duration,\n });\n }\n\n // --- TEXT & PERCEPTION RULES ---\n\n const rawText = cue.text || '';\n const cleanText = stripFormattingTags(rawText);\n\n // 6. Characters Per Line (CPL) check\n const lines = cleanText.split('\\n');\n for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {\n const line = lines[lineIndex];\n if (!line) continue;\n\n const cpl = countGraphemes(line, locale);\n if (cpl > maxCpl) {\n diagnostics.push({\n cueId: cue.id,\n rule: 'max-cpl',\n severity: 'warning',\n message: `Line ${lineIndex + 1} has ${cpl} characters, exceeding the maximum limit of ${maxCpl} CPL.`,\n expected: maxCpl,\n actual: cpl,\n });\n }\n }\n\n // 7. Characters Per Second (CPS) reading speed check\n if (duration > 0) {\n const textToMeasure = includeSpaces\n ? cleanText\n : cleanText.replace(/\\s+/g, '');\n\n const totalGraphemes = countGraphemes(textToMeasure, locale);\n const cps = Number(((totalGraphemes / duration) * 1000).toFixed(1));\n\n if (cps > maxCps) {\n diagnostics.push({\n cueId: cue.id,\n rule: 'max-cps',\n severity: 'warning',\n message: `Reading speed of ${cps} CPS exceeds maximum limit of ${maxCps} CPS.`,\n expected: maxCps,\n actual: cps,\n });\n }\n }\n }\n\n return diagnostics;\n}\n"]}