/
Collection.ts
213 lines (192 loc) · 5.91 KB
/
Collection.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
import { createNode } from '../doc/createNode.js'
import type { Schema } from '../schema/Schema.js'
import {
isCollection,
isNode,
isPair,
isScalar,
NodeBase,
NODE_TYPE
} from './Node.js'
export function collectionFromPath(
schema: Schema,
path: unknown[],
value: unknown
) {
let v = value
for (let i = path.length - 1; i >= 0; --i) {
const k = path[i]
if (typeof k === 'number' && Number.isInteger(k) && k >= 0) {
const a: unknown[] = []
a[k] = v
v = a
} else {
v = new Map<unknown, unknown>([[k, v]])
}
}
return createNode(v, undefined, {
aliasDuplicateObjects: false,
keepUndefined: false,
onAnchor: () => {
throw new Error('This should not happen, please report a bug.')
},
schema,
sourceObjects: new Map()
})
}
// Type guard is intentionally a little wrong so as to be more useful,
// as it does not cover untypable empty non-string iterables (e.g. []).
export const isEmptyPath = (
path: Iterable<unknown> | null | undefined
): path is null | undefined =>
path == null ||
(typeof path === 'object' && !!path[Symbol.iterator]().next().done)
export abstract class Collection extends NodeBase {
static maxFlowStringSingleLineLength = 60
schema: Schema | undefined;
declare [NODE_TYPE]: symbol
declare items: unknown[]
/** An optional anchor on this node. Used by alias nodes. */
declare anchor?: string
/**
* If true, stringify this and all child nodes using flow rather than
* block styles.
*/
declare flow?: boolean
constructor(type: symbol, schema?: Schema) {
super(type)
Object.defineProperty(this, 'schema', {
value: schema,
configurable: true,
enumerable: false,
writable: true
})
}
/**
* Create a copy of this collection.
*
* @param schema - If defined, overwrites the original's schema
*/
clone(schema?: Schema): Collection {
const copy: Collection = Object.create(
Object.getPrototypeOf(this),
Object.getOwnPropertyDescriptors(this)
)
if (schema) copy.schema = schema
copy.items = copy.items.map(it =>
isNode(it) || isPair(it) ? it.clone(schema) : it
)
if (this.range) copy.range = this.range.slice() as NodeBase['range']
return copy
}
/** Adds a value to the collection. */
abstract add(value: unknown): void
/**
* Removes a value from the collection.
* @returns `true` if the item was found and removed.
*/
abstract delete(key: unknown): boolean
/**
* Returns item at `key`, or `undefined` if not found. By default unwraps
* scalar values from their surrounding node; to disable set `keepScalar` to
* `true` (collections are always returned intact).
*/
abstract get(key: unknown, keepScalar?: boolean): unknown
/**
* Checks if the collection includes a value with the key `key`.
*/
abstract has(key: unknown): boolean
/**
* Sets a value in this collection. For `!!set`, `value` needs to be a
* boolean to add/remove the item from the set.
*/
abstract set(key: unknown, value: unknown): void
/**
* Adds a value to the collection. For `!!map` and `!!omap` the value must
* be a Pair instance or a `{ key, value }` object, which may not have a key
* that already exists in the map.
*/
addIn(path: Iterable<unknown>, value: unknown) {
if (isEmptyPath(path)) this.add(value)
else {
const [key, ...rest] = path
const node = this.get(key, true)
if (isCollection(node)) node.addIn(rest, value)
else if (node === undefined && this.schema)
this.set(key, collectionFromPath(this.schema, rest, value))
else
throw new Error(
`Expected YAML collection at ${key}. Remaining path: ${rest}`
)
}
}
/**
* Removes a value from the collection.
* @returns `true` if the item was found and removed.
*/
deleteIn(path: Iterable<unknown>): boolean {
const [key, ...rest] = path
if (rest.length === 0) return this.delete(key)
const node = this.get(key, true)
if (isCollection(node)) return node.deleteIn(rest)
else
throw new Error(
`Expected YAML collection at ${key}. Remaining path: ${rest}`
)
}
/**
* Returns item at `key`, or `undefined` if not found. By default unwraps
* scalar values from their surrounding node; to disable set `keepScalar` to
* `true` (collections are always returned intact).
*/
getIn(path: Iterable<unknown>, keepScalar?: boolean): unknown {
const [key, ...rest] = path
const node = this.get(key, true)
if (rest.length === 0)
return !keepScalar && isScalar(node) ? node.value : node
else return isCollection(node) ? node.getIn(rest, keepScalar) : undefined
}
hasAllNullValues(allowScalar?: boolean) {
return this.items.every(node => {
if (!isPair(node)) return false
const n = node.value
return (
n == null ||
(allowScalar &&
isScalar(n) &&
n.value == null &&
!n.commentBefore &&
!n.comment &&
!n.tag)
)
})
}
/**
* Checks if the collection includes a value with the key `key`.
*/
hasIn(path: Iterable<unknown>): boolean {
const [key, ...rest] = path
if (rest.length === 0) return this.has(key)
const node = this.get(key, true)
return isCollection(node) ? node.hasIn(rest) : false
}
/**
* Sets a value in this collection. For `!!set`, `value` needs to be a
* boolean to add/remove the item from the set.
*/
setIn(path: Iterable<unknown>, value: unknown) {
const [key, ...rest] = path
if (rest.length === 0) {
this.set(key, value)
} else {
const node = this.get(key, true)
if (isCollection(node)) node.setIn(rest, value)
else if (node === undefined && this.schema)
this.set(key, collectionFromPath(this.schema, rest, value))
else
throw new Error(
`Expected YAML collection at ${key}. Remaining path: ${rest}`
)
}
}
}