Skip to content

Commit a1dc96f

Browse files
committed
fix: Improve error when parsing a non-string value (fixes #459)
1 parent edc623d commit a1dc96f

File tree

3 files changed

+18
-4
lines changed

3 files changed

+18
-4
lines changed

docs/04_documents.md

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,14 @@ doc.contents
4040
// range: [ 0, 180, 180 ] }
4141
```
4242

43+
These functions should never throw,
44+
provided that `str` is a string and the `options` are valid.
45+
Errors and warnings are included in the documents' `errors` and `warnings` arrays.
46+
In particular, if `errors` is not empty
47+
it's likely that the document's parsed `contents` are not entirely correct.
48+
49+
The `contents` of a parsed document will always consist of `Scalar`, `Map`, `Seq` or `null` values.
50+
4351
#### `parseDocument(str, options = {}): Document`
4452

4553
Parses a single `Document` from the input `str`; used internally by `parse`.
@@ -56,10 +64,6 @@ See [Options](#options) for more information on the second parameter.
5664

5765
<br/>
5866

59-
These functions should never throw; errors and warnings are included in the documents' `errors` and `warnings` arrays. In particular, if `errors` is not empty it's likely that the document's parsed `contents` are not entirely correct.
60-
61-
The `contents` of a parsed document will always consist of `Scalar`, `Map`, `Seq` or `null` values.
62-
6367
## Creating Documents
6468

6569
#### `new Document(value, replacer?, options = {})`

src/parse/lexer.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,7 @@ export class Lexer {
174174
*/
175175
*lex(source: string, incomplete = false) {
176176
if (source) {
177+
if (typeof source !== 'string') throw TypeError('source is not a string')
177178
this.buffer = this.buffer ? this.buffer + source : source
178179
this.lineEndPos = null
179180
}

tests/doc/parse.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,15 @@ aliases:
154154
})
155155
})
156156

157+
test('buffer as source (eemeli/yaml#459)', () => {
158+
const buffer = readFileSync(
159+
resolve(__dirname, '../artifacts/prettier-circleci-config.yml')
160+
)
161+
expect(() => YAML.parseDocument(buffer as any)).toThrow(
162+
'source is not a string'
163+
)
164+
})
165+
157166
describe('eemeli/yaml#19', () => {
158167
test('map', () => {
159168
const src = 'a:\n # 123'

0 commit comments

Comments
 (0)