-
Notifications
You must be signed in to change notification settings - Fork 0
/
logical-config.js
297 lines (266 loc) · 8.95 KB
/
logical-config.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
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
/**
* Deter,ome of the provided item is callable. Callable items have the type
* function. These are normally either functions or classes.
*
* @param {any} item the item
* @returns True if the item is callable, false otherwise.
*/
const isCallable = item => typeof item === 'function';
/**
* Determine if the provided object is a function. You should first call the
* {@link isCallable} funuction to verify that the item is callable.
*
* @param {Function|class} item the class or function.
* @returns True if the provided object is a function.
*/
const isFunction = item => {
const propertyNames = Object.getOwnPropertyNames(item);
return !propertyNames.includes('prototype')
|| propertyNames.includes('arguments');
};
/**
* Attempts to resolve the specified `dotPath` down to the corresponding
* value in the `obj`.
*
* @param {string} dotPath The dot path to resolve.
* @param {object} obj The object to resolve the path in.
* @returns the value found, or undefined if one was not found
*/
const tryResolveDotPath = (dotPath, obj) =>
typeof dotPath === 'string' ? dotPath.split('.').reduce(
(a, b, ) => a ? a[b] : undefined, obj
) : undefined;
/**
* Determine if the specified string is a properly formatted short-hand path-object.
*
* @param {any} obj the object to test
* @returns true if the object is properly formatted, false otherwise.
*/
const isShortHand = obj => (
typeof obj === 'string'
&& /^\{[^;\n]{1,}(|;|;\[[^\n]*\])(|;|;(true|false))\}$/.test(obj)
);
/**
* Determines if the specified object is a valid path-object.
*
* @param {any} obj the object
* @returns true if the object is a valid path-object, false otherwise.
*/
const isValidPathObject = obj => (
obj
&& obj['$fill']
&& typeof obj['$fill'] === 'string'
&& (
typeof obj.call === 'boolean'
|| obj.call == undefined
)
&& (
(
typeof obj.parameters === 'object'
&& Array.isArray(obj.parameters)
) || obj.parameters === undefined
)
);
/**
* Parses a path-object.
*
* @param {any} obj the input object
* @returns a path-object provided that the input object is either a
* properly formatted short-hand path object, or an already
* parsed path-object.
*/
const parsePathObject = obj => {
let result;
if (isValidPathObject(obj)) {
result = { ...obj, supportsNested: true };
}
if (result === undefined && isShortHand(obj)) {
const elems = obj.slice(1, -1).split(';');
const [ path, params, call ] = elems;
const parameters = params && params.length > 0
? JSON.parse(params)
: undefined;
result = {
'$fill': path,
parameters,
call: ['true', 'false'].includes(call) ? call === 'true' : undefined
};
}
return result || {};
};
/**
* Retrieves the specified value.
*
* @param {} obj the value to retrieve
* @param {*} def the default to return if the value is undefined
* @returns the value
*/
const getDef = (obj, def = true) => obj === undefined ? def : obj;
/**
* Validates that the specified path-object has the required
* data to express the resolved symbol.
*
* @param {object} obj the path-object
* @param {any} resolved the resolved-symbol
* @returns true if the path-object expresses the symbol
* @throws if the path-object does not express the symbol
*/
const pathObjectExpressesSymbol = (obj, resolved) => {
if(resolved === undefined) {
throw new Error(`Referenced path '${obj['$fill'] || obj}' is not accessble.`);
}
if (!isCallable(resolved) && getDef(obj.call, false)) {
throw new Error(
`Referencing '${obj['$fill'] || obj}' with 'call' enabled, ` +
`but referenced path is not callable.`
);
}
if (isCallable(resolved) && getDef(obj.call, false)) {
const requiredLength = (
isFunction(resolved)
? /* function */ resolved
: /* class */ resolved.prototype.constructor || []
).length;
const providedLength = (obj.parameters || []).length
if (getDef(obj.call, true) && providedLength !== requiredLength) {
throw new Error(
`Referencing '${obj['$fill'] || obj}' but an invalid number of ` +
`parameters was passed to it. (provided ${providedLength}, ` +
`required ${requiredLength})`
);
}
}
return true;
};
/**
* Performs the required action described by the specified path-object
*
* @param {} obj the path-object.
* @param {*} resolved the resolved symbol
* @param {*} data the data in which the path-object can reference items
*
* @returns an indication as to whether or not the path-object can be used
* to to express the resolved symbol, and if so, an async function
* that can be called to retrieve the corresponding value.
*/
const tryMakeReferenceable = async (obj, resolved, data) => {
const REFERENCABLE = (cb) => ({ isReferenceable: true, getReference: cb})
const REFERENCABLE_AS_RESOLVED = REFERENCABLE(async () => resolved);
const NOT_REFERENCEABLE = { isReferenceable: false, getReference: undefined };
if (!isValidPathObject(obj)) {
return NOT_REFERENCEABLE;
}
if (!pathObjectExpressesSymbol(obj, resolved)) {
return NOT_REFERENCEABLE;
}
if (!isCallable(resolved)) {
return REFERENCABLE_AS_RESOLVED;
}
if(!getDef(obj.call, true)) {
return REFERENCABLE_AS_RESOLVED;
}
// Process references in parameters
if (obj.supportsNested && obj.parameters && obj.parameters.length > 0) {
obj.parameters = await fill({
input: obj.parameters,
data
});
}
if (isFunction(resolved)) {
/* call function */
return REFERENCABLE(
async () => await resolved(...(obj.parameters || []))
);
} else {
/* instantiate class */
return REFERENCABLE(
async () => new resolved(...(obj.parameters || []))
);
}
}
/**
* Recursively resolves all path-objects found in the input.
*
* @param {any} input the input object
* @param {object} data data in which path-objects can reference items
* @param {array} ignoredPaths an array of dot-paths that should be ignored
* @param {string} currentPath this is an internal variable and should not be set
*
* @returns the original input with all path-objects resolved
*/
const fill = async ({
input,
data,
ignoredPaths = [],
currentPath = []
}) => {
if (!['string', 'object'].includes(typeof input)) {
return input;
}
const parsed = parsePathObject(input);
const pathPointsTo = tryResolveDotPath(parsed['$fill'], data);
const {
isReferenceable: _isDataReferenceable,
getReference: _getDataReference
} = await tryMakeReferenceable(parsed, pathPointsTo, data);
if (_isDataReferenceable) {
return await _getDataReference();
}
if (typeof input === 'string') {
return input;
}
if (Array.isArray(input)) {
for (const [i, v] of input.entries()) {
input[i] = await (async (e, idx) => {
currentPath.push(idx);
let res;
if (!ignoredPaths.includes(currentPath.join('.'))) {
currentPath.pop();
res = await fill({
input: e,
data,
ignoredPaths,
currentPath: [...currentPath]
});
} else {
currentPath.pop();
res = Promise.resolve(e);
}
return res;
})(v, i)
}
return input;
}
const entries = Object.entries(input);
for(const [i,e] of entries.entries()) {
entries[i] = await (async ([k, v]) => {
currentPath.push(k);
if (!ignoredPaths.includes(currentPath.join('.'))) {
const parsed = parsePathObject(v);
const pathPointsTo = tryResolveDotPath(parsed['$fill'] || v, data);
const {
isReferenceable: _isItemReferenceable,
getReference: _getItemReference
} = await tryMakeReferenceable(parsed, pathPointsTo, data);
const res = [k, (
_isItemReferenceable
? await _getItemReference()
: await fill({
input: v,
data,
ignoredPaths,
currentPath: [...currentPath]
})
)];
currentPath.pop();
return res;
}
currentPath.pop();
return [k, v];
})(e)
}
return Object.fromEntries(
entries
);
}
module.exports = { fill, parsePathObject };