UNPKG

2.55 kBJavaScriptView Raw
1'use strict';
2
3var identity = require('../../nodes/identity.js');
4var Scalar = require('../../nodes/Scalar.js');
5
6// If the value associated with a merge key is a single mapping node, each of
7// its key/value pairs is inserted into the current mapping, unless the key
8// already exists in it. If the value associated with the merge key is a
9// sequence, then this sequence is expected to contain mapping nodes and each
10// of these nodes is merged in turn according to its order in the sequence.
11// Keys in mapping nodes earlier in the sequence override keys specified in
12// later mapping nodes. -- http://yaml.org/type/merge.html
13const MERGE_KEY = '<<';
14const merge = {
15 identify: value => value === MERGE_KEY ||
16 (typeof value === 'symbol' && value.description === MERGE_KEY),
17 default: 'key',
18 tag: 'tag:yaml.org,2002:merge',
19 test: /^<<$/,
20 resolve: () => Object.assign(new Scalar.Scalar(Symbol(MERGE_KEY)), {
21 addToJSMap: addMergeToJSMap
22 }),
23 stringify: () => MERGE_KEY
24};
25const isMergeKey = (ctx, key) => (merge.identify(key) ||
26 (identity.isScalar(key) &&
27 (!key.type || key.type === Scalar.Scalar.PLAIN) &&
28 merge.identify(key.value))) &&
29 ctx?.doc.schema.tags.some(tag => tag.tag === merge.tag && tag.default);
30function addMergeToJSMap(ctx, map, value) {
31 value = ctx && identity.isAlias(value) ? value.resolve(ctx.doc) : value;
32 if (identity.isSeq(value))
33 for (const it of value.items)
34 mergeValue(ctx, map, it);
35 else if (Array.isArray(value))
36 for (const it of value)
37 mergeValue(ctx, map, it);
38 else
39 mergeValue(ctx, map, value);
40}
41function mergeValue(ctx, map, value) {
42 const source = ctx && identity.isAlias(value) ? value.resolve(ctx.doc) : value;
43 if (!identity.isMap(source))
44 throw new Error('Merge sources must be maps or map aliases');
45 const srcMap = source.toJSON(null, ctx, Map);
46 for (const [key, value] of srcMap) {
47 if (map instanceof Map) {
48 if (!map.has(key))
49 map.set(key, value);
50 }
51 else if (map instanceof Set) {
52 map.add(key);
53 }
54 else if (!Object.prototype.hasOwnProperty.call(map, key)) {
55 Object.defineProperty(map, key, {
56 value,
57 writable: true,
58 enumerable: true,
59 configurable: true
60 });
61 }
62 }
63 return map;
64}
65
66exports.addMergeToJSMap = addMergeToJSMap;
67exports.isMergeKey = isMergeKey;
68exports.merge = merge;