Skip to content

Commit

Permalink
Add metadata to compile output, fixes #30
Browse files Browse the repository at this point in the history
  • Loading branch information
osk committed Dec 30, 2019
1 parent 7fb5fdd commit 09b0247
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 1 deletion.
32 changes: 31 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -166,11 +166,41 @@ If no metadata is available, `meta` will be set to `null` in the result if the o

### Compiling

Compiles JSON from the above format back into a WebVTT string.
Compiles JSON from the above format back into a WebVTT string. If a `meta` key is in the input,
it will be compiled as well. The `meta` value must be an object and each key and value must be a string.

If the object is missing any attributes, the compiler will throw a `CompilerError` exception. So
for safety, calls to `compile` should be in `try catch`.

```javascript
const input = {
meta: {
Kind: 'captions',
Language: 'en'
},
cues: [{
end: 140,
identifier: '1',
start: 135.001,
text: 'Hello world',
styles: ''
}],
valid: true
};

const result = compile(input);

/*
WEBVTT
Kind: captions
Language: en
1
00:02:15.001 --> 00:02:20.000
Hello world
*/
```

### Segmenting

Segments a subtitle according to how it should be segmented for HLS subtitles.
Expand Down
14 changes: 14 additions & 0 deletions lib/compiler.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,20 @@ function compile (input) {

let output = 'WEBVTT\n';

if (input.meta) {
if (typeof input.meta !== 'object' || Array.isArray(input.meta)) {
throw new CompilerError('Metadata must be an object');
}

Object.entries(input.meta).forEach((i) => {
if (typeof i[1] !== 'string') {
throw new CompilerError(`Metadata value for "${i[0]}" must be string`);
}

output += `${i[0]}: ${i[1]}\n`;
});
}

input.cues.forEach((cue) => {
output += '\n';
output += compileCue(cue);
Expand Down
42 changes: 42 additions & 0 deletions test/compiler.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -405,4 +405,46 @@ Hello world

compile(input).should.equal(output);
});

it('should compile metadata', () => {
const input = {
meta: {
Kind: 'captions',
Language: 'en'
},
cues: [{
end: 140,
identifier: '1',
start: 135.001,
text: 'Hello world',
styles: ''
}],
valid: true
};

const output = `WEBVTT
Kind: captions
Language: en
1
00:02:15.001 --> 00:02:20.000
Hello world
`;

compile(input).should.equal(output);
});

it('should not compile non-object metadata', () => {
(() => {
compile({ meta: [], cues: [], valid: true });
})
.should.throw(compilerError, /Metadata must be an object/);
});

it('should not compile non-string metadata values', () => {
(() => {
compile({ meta: { foo: [] }, cues: [], valid: true });
})
.should.throw(compilerError, /Metadata value for "foo" must be string/);
});
});

0 comments on commit 09b0247

Please sign in to comment.