### Install SRT/VTT Parser
Source: https://github.com/plussub/srt-vtt-parser/blob/master/README.md
Install the parser using npm. This is the initial step before using the library in your project.
```bash
npm i @plussub/srt-vtt-parser
```
--------------------------------
### Entry Example
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/types.md
An example of how an `Entry` object is structured, demonstrating the expected data types for each field.
```typescript
const entry: Entry = {
id: "1",
from: 102821,
to: 104289,
text: "(SIREN WAILING IN DISTANCE)\
multiline text"
};
```
--------------------------------
### Successful Test Output Example
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/TESTING_GUIDE.md
Example of the console output indicating a successful test run, showing passed tests and summary.
```text
✓ test/index.test.ts (n tests)
✓ parse function works with various formats
✓ handles multiline text
✓ preserves inline tags
... (more tests)
n tests passed
```
--------------------------------
### VTT Subtitle Format Example
Source: https://github.com/plussub/srt-vtt-parser/blob/master/README.md
An example of the VTT (WebVTT) subtitle format, demonstrating standard cue formatting and timestamps.
```vtt
WEBVTT
1
00:01:42.821 --> 00:01:44.289
(SIREN WAILING IN DISTANCE)
multiline test
2
00:01:45.365 --> 00:01:48.084
DRIVER: There's 100,000 streets in this city.
3
00:01:49.077 --> 00:01:51.421
You don't need to know the route.
```
--------------------------------
### Basic WebVTT Example
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/FORMATS.md
A simple WebVTT file demonstrating the WEBVTT header and sequential cue blocks with timestamps and text.
```vtt
WEBVTT
1
00:00:10.500 --> 00:00:13.000
Welcome to the movie
2
00:00:14.000 --> 00:00:18.000
This is the second subtitle
with multiple lines
3
00:00:19.000 --> 00:00:23.000
And this is the third one
```
--------------------------------
### Create New Test Input File
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/TESTING_GUIDE.md
Example of how to create an input file for a new test case in TypeScript.
```typescript
// test/myNewCase.ts
export const myNewCaseInput = `...test data...`;
```
--------------------------------
### Legacy VTT Headers Example
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/FORMATS.md
Shows a WebVTT file with legacy header metadata lines, which are recognized and skipped by the parser.
```vtt
WEBVTT
Kind: captions
Language: en
Title: My Video Subtitles
00:00:00.000 --> 00:00:05.000
First subtitle
```
--------------------------------
### SRT File Example
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/FORMATS.md
A typical example of an SRT subtitle file, showing sequence numbers, timestamps, and subtitle text, including multi-line entries.
```text
1
00:00:10,500 --> 00:00:13,000
Welcome to the movie
2
00:00:14,000 --> 00:00:18,000
This is the second subtitle
with multiple lines
3
00:00:19,000 --> 00:00:23,000
And this is the third one
```
--------------------------------
### TypeScript Usage Example
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/README.md
Import and use the parse function with TypeScript types. This example demonstrates parsing content and iterating over the resulting entries.
```typescript
import { parse, Entry, ParsedResult } from '@plussub/srt-vtt-parser';
const result: ParsedResult = parse(content);
result.entries.forEach((entry: Entry) => {
console.log(entry.text);
});
```
--------------------------------
### Millisecond Precision Examples
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/FORMATS.md
Shows various timestamp formats and their conversion to milliseconds, demonstrating the parser's unified output for millisecond precision.
```text
00:00:05,123 → 5123 ms
00:00:05.123 → 5123 ms
00:01:30,000 → 90000 ms
00:01:30.000 → 90000 ms
01:30:00,000 → 5400000 ms
```
--------------------------------
### VTT to Milliseconds Time Conversion Example
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/README.md
Illustrates the conversion of VTT time format (HH:MM:SS.ms) to milliseconds.
```text
00:01:30.500 (VTT) → 90500 ms
```
--------------------------------
### CommonJS Usage Example
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/IMPORTS.md
Example of using the `parse` function with CommonJS `require()`. This works even though the package is configured as an ES module.
```javascript
const { parse } = require('@plussub/srt-vtt-parser');
const { entries } = parse(content);
```
--------------------------------
### Create New Test Expected Output File
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/TESTING_GUIDE.md
Example of how to create an expected output file for a new test case in TypeScript.
```typescript
// test/result-myNewCase.ts
export const myNewCaseResult = {
entries: [ /* ... */ ]
};
```
--------------------------------
### SRT Subtitle Format Example
Source: https://github.com/plussub/srt-vtt-parser/blob/master/README.md
An example of the SRT (SubRip) subtitle format, including multiline text and speaker identification.
```srt
00:01:42,821 --> 00:01:44,289
(SIREN WAILING IN DISTANCE)
multiline test
2
00:01:45,365 --> 00:01:48,084
DRIVER: There's 100,000 streets in this city.
3
00:01:49,077 --> 00:01:51,421
You don't need to know the route.
```
--------------------------------
### SRT to Milliseconds Time Conversion Example
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/README.md
Illustrates the conversion of SRT time format (HH:MM:SS,ms) to milliseconds.
```text
00:01:30,500 (SRT) → 90500 ms
```
--------------------------------
### VTT with STYLE and NOTE Blocks
Source: https://github.com/plussub/srt-vtt-parser/blob/master/README.md
Example of a VTT file containing STYLE and NOTE blocks, demonstrating how the parser respects these elements while extracting subtitle entries.
```vtt
WEBVTT
STYLE
::cue {
background-image: linear-gradient(to bottom, dimgray, lightgray);
color: papayawhip;
}
/* Style blocks cannot use blank lines nor "dash dash greater than" */
NOTE comment blocks can be used between style blocks.
00:01:42.821 --> 00:01:44.289
(SIREN WAILING IN DISTANCE)
multiline test
NOTE style blocks cannot appear after the first cue.
this is a multiline note block
some identifier
00:01:45.365 --> 00:01:48.084
DRIVER: There's 100,000 streets in this city.
00:01:49.077 --> 00:01:51.421
You don't need to know the route.
```
--------------------------------
### WebVTT Inline Styling Tags
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/FORMATS.md
Examples of using inline styling tags like , , , , and within cue text for formatting.
```vtt
WEBVTT
00:00:00.000 --> 00:00:05.000
This is spoken dialogue
00:00:05.000 --> 00:00:10.000
Styled text
00:00:10.000 --> 00:00:15.000
Italic, bold, underline
```
--------------------------------
### Short Time to Milliseconds Conversion Example
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/README.md
Illustrates the conversion of a short SRT time format (HH:MM:SS,ms) to milliseconds.
```text
00:00:05,000 (SRT) → 5000 ms
```
--------------------------------
### FSM Main Loop Implementation
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/STATE_MACHINES.md
This is the core FSM loop used in both SRT and VTT parsers. It initializes the starting state and parameters, then iteratively calls the current state's function until the FINISH state is reached. Ensure the input is a string and the initial state is correctly set.
```typescript
start(raw: string): Entry[] {
let currentTransition: TransitionNames = TRANSITION_NAMES.ID; // or HEADER for VTT
let params: TransitionParams = {
tokens: raw.split(/\n/),
pos: 0,
result: [],
current: {}
};
while (currentTransition !== TRANSITION_NAMES.FINISH) {
const result = this[currentTransition](params);
params = result.params;
currentTransition = result.next;
}
return params.result;
}
```
--------------------------------
### SRT Timestamp Format Example
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/FORMATS.md
Illustrates the standard timestamp format used in SRT files, including hours, minutes, seconds, and milliseconds separated by a comma.
```text
HH:MM:SS,mmm --> HH:MM:SS,mmm
```
--------------------------------
### TypeScript Usage with Parsed Result
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/IMPORTS.md
Example demonstrating the usage of `parse`, `Entry`, and `ParsedResult` in a TypeScript project to process VTT content and log entry details.
```typescript
import { parse, Entry, ParsedResult } from '@plussub/srt-vtt-parser';
const result: ParsedResult = parse(vttContent);
result.entries.forEach((entry: Entry) => {
console.log(`${entry.from}ms - ${entry.to}ms: ${entry.text}`);
});
```
--------------------------------
### Parsed SRT/VTT Output Example
Source: https://github.com/plussub/srt-vtt-parser/blob/master/README.md
The expected JSON output structure after parsing SRT or VTT subtitle content, showing 'from', 'to', 'text', and 'id' for each entry.
```json
{
"entries": [
{
"from": 102821,
"id": "1",
"text": "(SIREN WAILING IN DISTANCE)\nmultiline test",
"to": 104289
},
{
"from": 105365,
"id": "2",
"text": "DRIVER: There's 100,000 streets in this city.",
"to": 108084
},
{
"from": 109077,
"id": "3",
"text": "You don't need to know the route.",
"to": 111421
}
]
}
```
--------------------------------
### Accessing Timestamps in Milliseconds
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/QUICK_START.md
Shows how to access start and end times of subtitle entries, which are provided in milliseconds. Includes conversion to seconds.
```typescript
const { entries } = parse(content);
// All times are milliseconds since start
console.log(entries[0].from); // e.g., 10500 (10.5 seconds)
console.log(entries[0].to); // e.g., 13000 (13 seconds)
// Convert to seconds
const startSeconds = entries[0].from / 1000;
const endSeconds = entries[0].to / 1000;
```
--------------------------------
### SRT/VTT Format Detection Logic
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/README.md
Demonstrates the heuristic used to detect whether an input string is SRT or VTT based on its starting characters.
```typescript
if (raw.startsWith('WEBVTT')) {
// Use VTT parser
} else {
// Use SRT parser
}
```
--------------------------------
### Iterate Through All Entries
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/USAGE_PATTERNS.md
Loops through all parsed subtitle entries, accessing their ID, start time (from), end time (to), and text content.
```typescript
const { entries } = parse(content);
entries.forEach(({ id, from, to, text }) => {
console.log(`[${id}] ${from}ms - ${to}ms: ${text}`);
});
```
--------------------------------
### Add New Test Case to Suite
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/TESTING_GUIDE.md
Example of adding a new test case to the test suite using the 'it' block and 'expect' assertion.
```typescript
import { parse } from './index';
import { myNewCaseInput } from './myNewCase';
import { myNewCaseResult } from './result-myNewCase';
it('should handle my new case', () => {
expect(parse(myNewCaseInput)).toEqual(myNewCaseResult);
});
```
--------------------------------
### Basic VTT Parsing
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/api-reference/vttParser.md
Parses a simple VTT string into an array of cue entries. Each entry includes an ID, start and end times in milliseconds, and the subtitle text.
```typescript
import { vttParser } from '@plussub/srt-vtt-parser';
const vttContent = `WEBVTT
1
00:00:10.500 --> 00:00:13.000
Subtitle one
2
00:00:14.000 --> 00:00:18.000
Subtitle two
`;
const { entries } = vttParser(vttContent);
console.log(entries[0]);
// Output:
// {
// id: "1",
// from: 10500,
// to: 13000,
// text: "Subtitle one"
// }
```
--------------------------------
### Example Invalid VTT Input
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/errors.md
An invalid VTT format where a cue is followed by a blank line without text content. This triggers a 'Parsing error current not complete' error.
```vtt
WEBVTT
cue-1
00:00:00.000 --> 00:00:05.000
(blank line immediately follows without text)
```
--------------------------------
### Entry Interface Definition
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/types.md
Defines the structure for a single subtitle or caption entry, including its ID, start and end times, and text content.
```typescript
interface Entry {
id: string;
from: number;
to: number;
text: string;
}
```
--------------------------------
### ParsedResult Usage Example
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/types.md
Demonstrates how to use the `parse()` function and access the `entries` array from the `ParsedResult`. This snippet shows how to import the function and iterate over the parsed subtitle entries.
```typescript
import { parse } from '@plussub/srt-vtt-parser';
const result: ParsedResult = parse(vttContent);
console.log(result.entries.length); // Number of subtitles
result.entries.forEach(entry => {
console.log(`${entry.id}: ${entry.text}`);
});
```
--------------------------------
### vttParser Function
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/api-reference/vttParser.md
Parses raw VTT (WebVTT) subtitle file content into a structured object. It expects the input string to start with a 'WEBVTT' header and handles timestamps in HH:MM:SS.mmm format.
```APIDOC
## vttParser(raw: string): ParsedResult
### Description
Parses raw VTT (WebVTT) subtitle file content into a structured object. It expects the input string to start with a 'WEBVTT' header and handles timestamps in HH:MM:SS.mmm format.
### Parameters
#### Parameters
- **raw** (string) - Required - Raw VTT (WebVTT) subtitle file content as a string. Must start with the WEBVTT header. Timestamps use the format HH:MM:SS.mmm (period-separated milliseconds).
### Return Type
`ParsedResult` — An object containing an `entries` array with parsed subtitle data.
```
--------------------------------
### Module Organization
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/ARCHITECTURE.md
The library is structured into five main modules: the main entry point, type definitions, SRT parser, VTT parser, and utility functions.
```tree
src/
├── index.ts # Main entry point (1 exported function)
├── types.ts # Type definitions and type guards
├── srtParser.ts # SRT format state machine
├── vttParser.ts # VTT format state machine
└── util.ts # Utility functions
```
--------------------------------
### WebVTT with STYLE Blocks
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/FORMATS.md
Shows how to use STYLE blocks to apply CSS styling to cues in a WebVTT file. These blocks are skipped during parsing.
```vtt
WEBVTT
STYLE
::cue {
background-image: linear-gradient(to bottom, dimgray, lightgray);
color: papayawhip;
font-size: 1.2em;
}
00:00:00.000 --> 00:00:05.000
Styled subtitle
```
--------------------------------
### Enable Verbose Output for Tests
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/TESTING_GUIDE.md
Use this command to run tests with detailed reporter output, aiding in debugging.
```bash
npm test -- --reporter=verbose
```
--------------------------------
### VTT Timestamp Conversion Example
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/ARCHITECTURE.md
VTT timestamps in HH:MM:SS.mmm format are converted to milliseconds. Supports optional hours.
```typescript
"00:01:42.821" → 102821 milliseconds
```
--------------------------------
### LEGACY_HEADER State Transition
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/STATE_MACHINES.md
Skips optional VTT header metadata lines. Loops on lines containing ':' but not '-->', otherwise transitions to ID_OR_NOTE_OR_STYLE_OR_REGION. Transitions to FINISH at end of file.
```typescript
[TRANSITION_NAMES.LEGACY_HEADER](params: TransitionParams): TransitionResult {
const { tokens, pos } = params;
if (tokens.length <= pos) {
return { next: TRANSITION_NAMES.FINISH, params };
} else if(tokens[pos].includes(":") && !tokens[pos].includes("-->") ){
return { next: TRANSITION_NAMES.LEGACY_HEADER, params: { ...params, pos: pos + 1 } };
} else {
return { next: TRANSITION_NAMES.ID_OR_NOTE_OR_STYLE_OR_REGION, params };
}
}
```
--------------------------------
### Count Total Subtitle Entries
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/QUICK_START.md
Get the total number of parsed subtitle entries by accessing the `length` property of the `entries` array.
```typescript
const { entries } = parse(content);
console.log(`Total subtitles: ${entries.length}`);
```
--------------------------------
### SRT Timestamp Conversion Example
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/ARCHITECTURE.md
SRT timestamps in HH:MM:SS,mmm format are converted to milliseconds. Supports optional hours.
```typescript
"00:01:42,821" → 102821 milliseconds
```
--------------------------------
### FSM Machine Type Definition
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/STATE_MACHINES.md
Defines the structure of a state machine, including transition names and the start function for parsing raw input.
```typescript
type Machine = Record TransitionResult> & {
start: (raw: string) => Entry[];
};
const SomeParser: () => Machine = () => ({
start(raw: string): Entry[] { /* ... */ },
[STATE1](params: TransitionParams): TransitionResult { /* ... */ },
[STATE2](params: TransitionParams): TransitionResult { /* ... */ },
// ... more states
});
export const someParser = (raw: string) => {
return { entries: SomeParser().start(raw) };
};
```
--------------------------------
### WebVTT with REGION Blocks
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/FORMATS.md
Demonstrates the use of REGION blocks to define layout and positioning for subtitle areas. These blocks are ignored by the parser.
```vtt
WEBVTT
REGION
id=bottom
width=100%
lines=3
regionanchor=50%,100%
viewportanchor=50%,90%
00:00:00.000 --> 00:00:05.000
position:0%,align:start
Subtitle positioned at bottom
```
--------------------------------
### HEADER State Transition
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/STATE_MACHINES.md
Handles the initial HEADER state, always transitioning to LEGACY_HEADER. Increments the position counter.
```typescript
[TRANSITION_NAMES.HEADER](params: TransitionParams): TransitionResult {
return { next: TRANSITION_NAMES.LEGACY_HEADER, params: { ...params, pos: params.pos + 1 } };
}
```
--------------------------------
### Time Shift All Subtitles
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/USAGE_PATTERNS.md
Shifts the start and end times of all subtitle entries by a specified offset in milliseconds. Creates a new array with the adjusted times.
```typescript
const { entries } = parse(content);
// Shift all subtitles by +5 seconds (5000 ms)
const offset = 5000;
const shifted = entries.map(entry => ({
...entry,
from: entry.from + offset,
to: entry.to + offset
}));
```
--------------------------------
### WebVTT with NOTE Blocks
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/FORMATS.md
Illustrates the use of NOTE blocks for comments within a WebVTT file. These blocks are ignored by the parser.
```vtt
WEBVTT
NOTE This is a comment
It can span multiple lines
00:00:00.000 --> 00:00:05.000
First cue
NOTE Another comment
explaining something about the next cue
00:00:05.000 --> 00:00:10.000
Second cue
```
--------------------------------
### Example Invalid SRT Input
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/errors.md
An invalid SRT format where a subtitle entry is missing a timestamp line. This triggers a 'Parsing error current not complete' error.
```srt
1
(no timestamp here)
Some text
```
--------------------------------
### Format-Specific Parsers: srtParser and vttParser
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/IMPORTS.md
For direct use without auto-detection, you can import `srtParser` and `vttParser`. These are less commonly needed as the main `parse` function handles detection.
```APIDOC
## Format-Specific Parsers
```typescript
import { srtParser, vttParser } from '@plussub/srt-vtt-parser';
```
These exports allow direct use of format-specific parsers without auto-detection. Not commonly needed since `parse()` handles detection automatically.
```
--------------------------------
### ID_OR_NOTE_OR_STYLE_OR_REGION State Transition
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/STATE_MACHINES.md
Routes parsing based on the content of the current line. Handles blank lines, NOTE, STYLE, REGION, or ID blocks. Transitions to FINISH at end of file.
```typescript
[TRANSITION_NAMES.ID_OR_NOTE_OR_STYLE_OR_REGION](params: TransitionParams): TransitionResult {
const { tokens, pos } = params;
if (tokens.length <= pos) {
return { next: TRANSITION_NAMES.FINISH, params };
} else if (isBlank(tokens[pos])) {
return { next: TRANSITION_NAMES.ID_OR_NOTE_OR_STYLE_OR_REGION, params: { ...params, pos: pos + 1 } };
} else if (tokens[pos].toUpperCase().includes('NOTE')) {
return { next: TRANSITION_NAMES.NOTE, params };
} else if (tokens[pos].toUpperCase().includes('STYLE')) {
return { next: TRANSITION_NAMES.STYLE, params };
} else if (tokens[pos].toUpperCase().includes('REGION')) {
return { next: TRANSITION_NAMES.REGION, params };
} else {
return { next: TRANSITION_NAMES.ID, params };
}
}
```
--------------------------------
### Run TypeScript Type Checking
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/TESTING_GUIDE.md
Execute this command to verify type correctness in test files, ensure all imports resolve, and validate return types and type usage.
```bash
npm run ts-check
```
--------------------------------
### Get Subtitle Entry at Specific Time
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/USAGE_PATTERNS.md
Find a subtitle entry that is active at a given millisecond timestamp. Assumes `parse(content)` has been called and `entries` is available.
```typescript
const { entries } = parse(content);
function getEntryAtTime(timeMs) {
return entries.find(entry => entry.from <= timeMs && timeMs <= entry.to);
}
// Get subtitle at 2 minutes 30 seconds
const subtitle = getEntryAtTime(2 * 60 * 1000 + 30 * 1000);
console.log(subtitle?.text);
```
--------------------------------
### Handling SRT and VTT IDs
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/QUICK_START.md
Illustrates how the parser handles cue IDs for both SRT and VTT formats. IDs are extracted if present, otherwise an empty string is used.
```text
SRT:
1
00:00:00,000 --> 00:00:05,000
Text
→ `id: "1"`
00:00:00,000 --> 00:00:05,000
Text
→ `id: ""`
VTT:
cue-1
00:00:00.000 --> 00:00:05.000
Text
→ `id: "cue-1"`
00:00:00.000 --> 00:00:05.000
Text
→ `id: ""`
```
--------------------------------
### Primary Export: parse() function
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/IMPORTS.md
The recommended way to use the library is by importing the `parse` function. It automatically detects the subtitle format (SRT or VTT) and returns the parsed entries.
```APIDOC
## Main Package Entry Point
**Package:** `@plussub/srt-vtt-parser`
### Primary Export
```typescript
import { parse } from '@plussub/srt-vtt-parser';
```
This is the recommended way to use the library. The `parse()` function automatically detects the subtitle format and returns parsed entries.
### CommonJS Usage
If your project uses CommonJS instead of ES modules:
```javascript
const { parse } = require('@plussub/srt-vtt-parser');
const { entries } = parse(content);
```
```
--------------------------------
### WebVTT Cue Identifier Format
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/FORMATS.md
Demonstrates how to include optional cue identifiers before the timestamp for specific cue referencing.
```vtt
WEBVTT
cue-1
00:00:00.000 --> 00:00:05.000
First cue with ID
00:00:05.000 --> 00:00:10.000
Second cue without ID
my-special-id
00:00:10.000 --> 00:00:15.000
Third cue with custom ID
```
--------------------------------
### Format-Specific Parsers Import
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/IMPORTS.md
Import `srtParser` or `vttParser` for direct use of format-specific parsing without auto-detection. These are less commonly needed as `parse()` handles detection.
```typescript
import { srtParser, vttParser } from '@plussub/srt-vtt-parser';
```
--------------------------------
### SRT TIME_LINE State Transition
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/STATE_MACHINES.md
Parses the timestamp line and converts the start and end times into milliseconds. This state always transitions to the TEXT state after successful parsing.
```typescript
[TRANSITION_NAMES.TIME_LINE](params: TransitionParams): TransitionResult {
const { tokens, pos, current } = params;
const timeLine = tokens[pos];
const [from, to] = timeLine.split('-->');
current.from = timestampToMillisecond(from);
current.to = timestampToMillisecond(to);
return { next: TRANSITION_NAMES.TEXT, params: { ...params, current, pos: pos + 1 } };
}
```
--------------------------------
### SRT ID State Transition
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/STATE_MACHINES.md
Handles parsing the optional cue identifier or detecting the start of a timestamp line. It manages transitions based on blank lines, timestamp indicators, or custom IDs.
```typescript
[TRANSITION_NAMES.ID](params: TransitionParams): TransitionResult {
const { tokens, pos, current } = params;
if (tokens.length <= pos) {
return { next: TRANSITION_NAMES.FINISH, params };
}
if (isBlank(tokens[pos])) {
return { next: TRANSITION_NAMES.ID, params: { ...params, pos: pos + 1 } };
}
const idDoesNotExists = tokens[pos].includes('-->');
current.id = idDoesNotExists ? '' : tokens[pos];
return {
next: TRANSITION_NAMES.TIME_LINE,
params: {
...params,
current,
tokens,
pos: idDoesNotExists ? pos : pos + 1
}
};
}
```
--------------------------------
### Parsed VTT with STYLE/NOTE Blocks Output
Source: https://github.com/plussub/srt-vtt-parser/blob/master/README.md
The resulting JSON from parsing a VTT file that includes STYLE and NOTE blocks. Note that STYLE and NOTE content is ignored in the output entries, and IDs are extracted correctly.
```json
{
"entries": [
{
"from": 102821,
"id": "",
"text": "(SIREN WAILING IN DISTANCE)\nmultiline test",
"to": 104289
},
{
"from": 105365,
"id": "some identifier",
"text": "DRIVER: There's 100,000 streets in this city.",
"to": 108084
},
{
"from": 109077,
"id": "",
"text": "You don't need to know the route.",
"to": 111421
}
]
}
```
--------------------------------
### Run a Single Test with Filtering
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/TESTING_GUIDE.md
Execute this command to run only tests matching a specific pattern, useful for focused debugging.
```bash
npm test -- --grep "should parse"
```
--------------------------------
### Get Current and Next Subtitle Entries
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/QUICK_START.md
Determine the current subtitle entry at a specific time and the subsequent one using `findIndex`. Accessing `entries[currentIndex + 1]` provides the next entry.
```typescript
const { entries } = parse(content);
function getCurrentAndNext(timeMs) {
const currentIndex = entries.findIndex(
e => e.from <= timeMs && timeMs <= e.to
);
return {
current: entries[currentIndex],
next: entries[currentIndex + 1]
};
}
const { current, next } = getCurrentAndNext(5000);
```
--------------------------------
### Primary Parse Function Import
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/IMPORTS.md
Import the main `parse` function for automatic subtitle format detection. This is the recommended way to use the library.
```typescript
import { parse } from '@plussub/srt-vtt-parser';
```
--------------------------------
### Get Subtitle Entries Visible During Time Range
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/USAGE_PATTERNS.md
Retrieve all subtitle entries that are at least partially visible within a specified time range (startMs to endMs). Assumes `parse(content)` has been called and `entries` is available.
```typescript
const { entries } = parse(content);
function getEntriesInRange(startMs, endMs) {
return entries.filter(entry =>
(entry.from >= startMs && entry.from < endMs) ||
(entry.to > startMs && entry.to <= endMs) ||
(entry.from <= startMs && entry.to >= endMs)
);
}
const visible = getEntriesInRange(10000, 20000);
```
--------------------------------
### Parsing VTT with STYLE Blocks
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/api-reference/vttParser.md
Shows how the parser handles STYLE blocks within VTT content. These blocks are skipped, and only the subtitle text is extracted.
```typescript
import { vttParser } from '@plussub/srt-vtt-parser';
const vttContent = `WEBVTT
STYLE
::cue {
background-image: linear-gradient(to bottom, dimgray, lightgray);
color: papayawhip;
}
00:00:00.000 --> 00:00:05.000
Styled subtitle
`;
const { entries } = vttParser(vttContent);
// STYLE blocks are skipped
console.log(entries[0].text); // "Styled subtitle"
```
--------------------------------
### Parsing VTT with NOTE Blocks
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/api-reference/vttParser.md
Demonstrates parsing VTT content that includes NOTE blocks. These blocks are ignored by the parser, and only the actual subtitle cues are returned.
```typescript
import { vttParser } from '@plussub/srt-vtt-parser';
const vttContent = `WEBVTT
NOTE This is a comment
Multiple lines can go here
This is still the note
00:00:00.000 --> 00:00:05.000
First cue
NOTE Another comment
00:00:05.000 --> 00:00:10.000
Second cue
`;
const { entries } = vttParser(vttContent);
// NOTE blocks are skipped entirely
console.log(entries.length); // 2
console.log(entries[0].text); // "First cue"
```
--------------------------------
### Fetch Subtitles from URL
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/QUICK_START.md
Fetch subtitle content from a URL using the fetch API and then parse it.
```typescript
import { parse } from '@plussub/srt-vtt-parser';
async function loadSubtitles(url) {
const response = await fetch(url);
const content = await response.text();
const { entries } = parse(content);
return entries;
}
const subtitles = await loadSubtitles('https://example.com/video.vtt');
```
--------------------------------
### NOTE State Transition
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/STATE_MACHINES.md
Skips NOTE blocks (comments). Transitions to ID_OR_NOTE_OR_STYLE_OR_REGION on a blank line, otherwise transitions to STYLE to continue skipping.
```typescript
[TRANSITION_NAMES.NOTE](params: TransitionParams): TransitionResult {
const { tokens, pos } = params;
if (isBlank(tokens[pos])) {
return { next: TRANSITION_NAMES.ID_OR_NOTE_OR_STYLE_OR_REGION, params: { ...params, pos: pos + 1 } };
}
return { next: TRANSITION_NAMES.STYLE, params: { ...params, pos: pos + 1 } };
}
```
--------------------------------
### Run Tests in Watch Mode
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/TESTING_GUIDE.md
Utilize this command to automatically rerun tests whenever file changes are detected, streamlining the development feedback loop.
```bash
npm test -- --watch
```
--------------------------------
### Error Handling in Consumer Code
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/errors.md
Demonstrates how to wrap calls to the parse function in a try-catch block to handle potential parsing errors gracefully. Includes type checking for the error object.
```typescript
import { parse } from '@plussub/srt-vtt-parser';
try {
const { entries } = parse(rawContent);
entries.forEach(entry => {
console.log(entry);
});
} catch (error) {
if (error instanceof Error) {
console.error('Subtitle parsing failed:', error.message);
// Handle the parsing error
}
}
```
--------------------------------
### Import and Parse Subtitle Content
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/README.md
Import the parse function from the library and use it to parse subtitle content. The result contains an array of entries.
```typescript
import { parse } from '@plussub/srt-vtt-parser';
const { entries } = parse(subtitleContent);
```
--------------------------------
### Read Subtitles from Disk
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/QUICK_START.md
Use the 'fs' module to read a subtitle file from disk and then parse its content.
```typescript
import fs from 'fs';
import { parse } from '@plussub/srt-vtt-parser';
const fileContent = fs.readFileSync('subtitles.srt', 'utf8');
const { entries } = parse(fileContent);
entries.forEach(({ id, from, to, text }) => {
console.log(`${id}: [${from}ms - ${to}ms] ${text}`);
});
```
--------------------------------
### SRT State Machine States
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/ARCHITECTURE.md
The SRT parser follows a finite state machine with states for ID, TIME_LINE, TEXT, MULTI_LINE_TEXT, FIN_ENTRY, and FINISH.
```tree
ID → TIME_LINE → TEXT → MULTI_LINE_TEXT → FIN_ENTRY → ID (loop)
↓ ↓
└──────────────────────── FINISH ─────────────────→
```
--------------------------------
### Optional Utility Export: isBlank
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/IMPORTS.md
The `isBlank` utility function is exported for internal parser use to check if a string is empty or contains only whitespace.
```APIDOC
## Optional Utility Export
```typescript
import { isBlank } from '@plussub/srt-vtt-parser';
```
The `isBlank()` utility function is exported but not documented in the main README. It's primarily for internal parser use:
```typescript
import { isBlank } from '@plussub/srt-vtt-parser';
isBlank(' '); // true
isBlank('text'); // false
```
```
--------------------------------
### isBlank(str: string): boolean
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/INDEX.md
Checks if a given string is blank (empty, null, undefined, or contains only whitespace). Returns true if the string is blank, false otherwise.
```APIDOC
## isBlank(str: string): boolean
### Description
Checks if a given string is blank (empty, null, undefined, or contains only whitespace). Returns true if the string is blank, false otherwise.
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Method
N/A (Function Call)
### Endpoint
N/A (Function Call)
### Request Example
```javascript
const parser = require('@plussub/srt-vtt-parser');
console.log(parser.isBlank('')); // true
console.log(parser.isBlank(' ')); // true
console.log(parser.isBlank('hello')); // false
```
### Response
#### Success Response (boolean)
- **result** (boolean) - True if the string is blank, false otherwise.
#### Response Example
```json
true
```
```
--------------------------------
### WebVTT Timestamp Format
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/FORMATS.md
Defines the structure for timestamps in WebVTT files, using hours, minutes, seconds, and milliseconds separated by a period.
```text
HH:MM:SS.mmm --> HH:MM:SS.mmm
```
--------------------------------
### Parsing Cues Without Identifiers
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/api-reference/vttParser.md
Demonstrates parsing VTT content where cues do not have explicit identifiers. The parser assigns an empty string as the ID for such cues.
```typescript
import { vttParser } from '@plussub/srt-vtt-parser';
const vttContent = `WEBVTT
00:00:00.000 --> 00:00:05.000
Cue without ID
00:00:05.000 --> 00:00:10.000
Another cue without ID
`;
const { entries } = vttParser(vttContent);
console.log(entries[0].id); // ""
console.log(entries[1].id); // ""
```
--------------------------------
### REGION State Transition
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/STATE_MACHINES.md
Skips REGION blocks (layout definitions). Transitions to ID_OR_NOTE_OR_STYLE_OR_REGION on a blank line, otherwise continues to loop in the REGION state.
```typescript
[TRANSITION_NAMES.REGION](params: TransitionParams): TransitionResult {
const { tokens, pos } = params;
if (isBlank(tokens[pos])) {
return { next: TRANSITION_NAMES.ID_OR_NOTE_OR_STYLE_OR_REGION, params: { ...params, pos: pos + 1 } };
}
return { next: TRANSITION_NAMES.REGION, params: { ...params, pos: pos + 1 } };
}
```
--------------------------------
### Parse Basic SRT Format
Source: https://github.com/plussub/srt-vtt-parser/blob/master/_autodocs/TESTING_GUIDE.md
Tests the parser's ability to handle standard SRT subtitle entries with sequential IDs and simple text content.
```typescript
// SRT format
1
00:00:10,500 --> 00:00:13,000
First subtitle
2
00:00:14,000 --> 00:00:18,000
Second subtitle
```
```typescript
{
entries: [
{ id: "1", from: 10500, to: 13000, text: "First subtitle" },
{ id: "2", from: 14000, to: 18000, text: "Second subtitle" }
]
}
```