forked from eemeli/yaml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
67 lines (61 loc) · 2.03 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { LogLevel } from './constants.js'
import { parse as parseCST } from './cst/parse.js'
import { Document } from './doc/Document.js'
import { YAMLSemanticError } from './errors.js'
import { warn } from './log.js'
export { defaultOptions, scalarOptions } from './options.js'
export { visit } from './visit.js'
export { Document, parseCST }
export function parseAllDocuments(src, options) {
const stream = []
let prev
const cst = parseCST(src)
if (options && options.setOrigRanges) cst.setOrigRanges()
for (const cstDoc of cst) {
const doc = new Document(undefined, null, options)
doc.parse(cstDoc, prev)
stream.push(doc)
prev = doc
}
return stream
}
export function parseDocument(src, options) {
const cst = parseCST(src)
if (options && options.setOrigRanges) cst.setOrigRanges()
const doc = new Document(cst[0], null, options)
if (
cst.length > 1 &&
LogLevel.indexOf(doc.options.logLevel) >= LogLevel.ERROR
) {
const errMsg =
'Source contains multiple documents; please use YAML.parseAllDocuments()'
doc.errors.unshift(new YAMLSemanticError(cst[1], errMsg))
}
return doc
}
export function parse(src, reviver, options) {
if (options === undefined && reviver && typeof reviver === 'object') {
options = reviver
reviver = undefined
}
const doc = parseDocument(src, options)
doc.warnings.forEach(warning => warn(doc.options.logLevel, warning))
if (doc.errors.length > 0) {
if (LogLevel.indexOf(doc.options.logLevel) >= LogLevel.ERROR)
throw doc.errors[0]
else doc.errors = []
}
return doc.toJS({ reviver })
}
export function stringify(value, replacer, options) {
if (typeof options === 'string') options = options.length
if (typeof options === 'number') {
const indent = Math.round(options)
options = indent < 1 ? undefined : indent > 8 ? { indent: 8 } : { indent }
}
if (value === undefined) {
const { keepUndefined } = options || replacer || {}
if (!keepUndefined) return undefined
}
return new Document(value, replacer, options).toString()
}