-
-
Notifications
You must be signed in to change notification settings - Fork 118
/
Pair.ts
310 lines (289 loc) · 9.12 KB
/
Pair.ts
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
import { createNode, CreateNodeContext } from '../doc/createNode.js'
import { warn } from '../log.js'
import { addComment } from '../stringify/addComment.js'
import {
createStringifyContext,
stringify,
StringifyContext
} from '../stringify/stringify.js'
import { Scalar } from './Scalar.js'
import { toJS, ToJSContext } from './toJS.js'
import {
isAlias,
isCollection,
isMap,
isNode,
isScalar,
isSeq,
Node,
NodeBase,
PAIR
} from './Node.js'
export function createPair(
key: unknown,
value: unknown,
ctx: CreateNodeContext
) {
const k = createNode(key, undefined, ctx)
const v = createNode(value, undefined, ctx)
return new Pair(k, v)
}
const isMergeKey = (key: unknown) =>
key === Pair.MERGE_KEY ||
(isScalar(key) &&
key.value === Pair.MERGE_KEY &&
(!key.type || key.type === Scalar.PLAIN))
// If the value associated with a merge key is a single mapping node, each of
// its key/value pairs is inserted into the current mapping, unless the key
// already exists in it. If the value associated with the merge key is a
// sequence, then this sequence is expected to contain mapping nodes and each
// of these nodes is merged in turn according to its order in the sequence.
// Keys in mapping nodes earlier in the sequence override keys specified in
// later mapping nodes. -- http://yaml.org/type/merge.html
function mergeToJSMap(
ctx: ToJSContext | undefined,
map:
| Map<unknown, unknown>
| Set<unknown>
| Record<string | number | symbol, unknown>,
value: unknown
) {
if (!isAlias(value) || !isMap(value.source))
throw new Error('Merge sources must be map aliases')
const srcMap = value.source.toJSON(null, ctx, Map)
for (const [key, value] of srcMap) {
if (map instanceof Map) {
if (!map.has(key)) map.set(key, value)
} else if (map instanceof Set) {
map.add(key)
} else if (!Object.prototype.hasOwnProperty.call(map, key)) {
Object.defineProperty(map, key, {
value,
writable: true,
enumerable: true,
configurable: true
})
}
}
return map
}
export class Pair<K = unknown, V = unknown> extends NodeBase {
static readonly MERGE_KEY = '<<'
/** Always Node or null when parsed, but can be set to anything. */
key: K
/** Always Node or null when parsed, but can be set to anything. */
value: V | null
constructor(key: K, value: V | null = null) {
super(PAIR)
this.key = key
this.value = value
}
// @ts-ignore This is fine.
get commentBefore() {
return isNode(this.key) ? this.key.commentBefore : undefined
}
set commentBefore(cb) {
if (this.key == null) this.key = new Scalar(null) as any // FIXME
if (isNode(this.key)) this.key.commentBefore = cb
else {
const msg =
'Pair.commentBefore is an alias for Pair.key.commentBefore. To set it, the key must be a Node.'
throw new Error(msg)
}
}
// @ts-ignore This is fine.
get spaceBefore() {
return isNode(this.key) ? this.key.spaceBefore : undefined
}
set spaceBefore(sb) {
if (this.key == null) this.key = new Scalar(null) as any // FIXME
if (isNode(this.key)) this.key.spaceBefore = sb
else {
const msg =
'Pair.spaceBefore is an alias for Pair.key.spaceBefore. To set it, the key must be a Node.'
throw new Error(msg)
}
}
addToJSMap(
ctx: ToJSContext | undefined,
map:
| Map<unknown, unknown>
| Set<unknown>
| Record<string | number | symbol, unknown>
) {
if (ctx && ctx.doc.schema.merge && isMergeKey(this.key)) {
if (isSeq(this.value))
for (const it of this.value.items) mergeToJSMap(ctx, map, it)
else if (Array.isArray(this.value))
for (const it of this.value) mergeToJSMap(ctx, map, it)
else mergeToJSMap(ctx, map, this.value)
} else {
const key = toJS(this.key, '', ctx)
if (map instanceof Map) {
const value = toJS(this.value, key, ctx)
map.set(key, value)
} else if (map instanceof Set) {
map.add(key)
} else {
const stringKey = stringifyKey(this.key, key, ctx)
const value = toJS(this.value, stringKey, ctx)
if (stringKey in map)
Object.defineProperty(map, stringKey, {
value,
writable: true,
enumerable: true,
configurable: true
})
else map[stringKey] = value
}
}
return map
}
toJSON(_?: unknown, ctx?: ToJSContext) {
const pair = ctx && ctx.mapAsMap ? new Map() : {}
return this.addToJSMap(ctx, pair)
}
toString(
ctx?: StringifyContext,
onComment?: () => void,
onChompKeep?: () => void
) {
if (!ctx || !ctx.doc) return JSON.stringify(this)
const {
allNullValues,
doc,
indent,
indentStep,
options: { indentSeq, simpleKeys }
} = ctx
let { key, value }: { key: K; value: V | Node | null } = this
let keyComment = (isNode(key) && key.comment) || null
if (simpleKeys) {
if (keyComment) {
throw new Error('With simple keys, key nodes cannot have comments')
}
if (isCollection(key)) {
const msg = 'With simple keys, collection cannot be used as a key value'
throw new Error(msg)
}
}
let explicitKey =
!simpleKeys &&
(!key ||
(keyComment && value == null) ||
isCollection(key) ||
(isScalar(key)
? key.type === Scalar.BLOCK_FOLDED || key.type === Scalar.BLOCK_LITERAL
: typeof key === 'object'))
ctx = Object.assign({}, ctx, {
allNullValues: false,
implicitKey: !explicitKey && (simpleKeys || !allNullValues),
indent: indent + indentStep
})
let chompKeep = false
let str = stringify(
key,
ctx,
() => (keyComment = null),
() => (chompKeep = true)
)
if (!explicitKey && !ctx.inFlow && str.length > 1024) {
if (simpleKeys)
throw new Error(
'With simple keys, single line scalar must not span more than 1024 characters'
)
explicitKey = true
}
if (
(allNullValues && (!simpleKeys || ctx.inFlow)) ||
(value == null && (explicitKey || ctx.inFlow))
) {
str = addComment(str, ctx.indent, keyComment)
if (this.comment) {
if (keyComment && !this.comment.includes('\n'))
str += `\n${ctx.indent || ''}#${this.comment}`
else str = addComment(str, ctx.indent, this.comment)
if (onComment) onComment()
} else if (chompKeep && !keyComment && onChompKeep) onChompKeep()
return ctx.inFlow && !explicitKey ? str : `? ${str}`
}
str = explicitKey
? `? ${addComment(str, ctx.indent, keyComment)}\n${indent}:`
: addComment(`${str}:`, ctx.indent, keyComment)
if (this.comment) {
if (keyComment && !explicitKey && !this.comment.includes('\n'))
str += `\n${ctx.indent || ''}#${this.comment}`
else str = addComment(str, ctx.indent, this.comment)
if (onComment) onComment()
}
let vcb = ''
let valueComment = null
if (isNode(value)) {
if (value.spaceBefore) vcb = '\n'
if (value.commentBefore) {
const cs = value.commentBefore.replace(/^/gm, `${ctx.indent}#`)
vcb += `\n${cs}`
}
valueComment = value.comment
} else if (value && typeof value === 'object') {
value = doc.createNode(value)
}
ctx.implicitKey = false
if (!explicitKey && !keyComment && !this.comment && isScalar(value))
ctx.indentAtStart = str.length + 1
chompKeep = false
if (
!indentSeq &&
indentStep.length >= 2 &&
!ctx.inFlow &&
!explicitKey &&
isSeq(value) &&
!value.flow &&
!value.tag &&
!doc.anchors.getName(value)
) {
// If indentSeq === false, consider '- ' as part of indentation where possible
ctx.indent = ctx.indent.substr(2)
}
const valueStr = stringify(
value,
ctx,
() => (valueComment = null),
() => (chompKeep = true)
)
let ws = ' '
if (vcb || keyComment || this.comment) {
ws = `${vcb}\n${ctx.indent}`
} else if (!explicitKey && isCollection(value)) {
const flow = valueStr[0] === '[' || valueStr[0] === '{'
if (!flow || valueStr.includes('\n')) ws = `\n${ctx.indent}`
} else if (valueStr[0] === '\n') ws = ''
if (chompKeep && !valueComment && onChompKeep) onChompKeep()
return addComment(str + ws + valueStr, ctx.indent, valueComment)
}
}
function stringifyKey(
key: unknown,
jsKey: unknown,
ctx: ToJSContext | undefined
) {
if (jsKey === null) return ''
if (typeof jsKey !== 'object') return String(jsKey)
if (isNode(key) && ctx && ctx.doc) {
const strCtx = createStringifyContext(ctx.doc, {})
strCtx.inFlow = true
strCtx.inStringifyKey = true
const strKey = key.toString(strCtx)
if (!ctx.mapKeyWarned) {
let jsonStr = JSON.stringify(strKey)
if (jsonStr.length > 40) jsonStr = jsonStr.substring(0, 36) + '..."'
warn(
ctx.doc.options.logLevel,
`Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`
)
ctx.mapKeyWarned = true
}
return strKey
}
return JSON.stringify(jsKey)
}