-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
640 lines (559 loc) · 20.3 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
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
/*
* Copyright (c) 2011-2013, Yahoo! Inc. All rights reserved.
* Copyrights licensed under the New BSD License.
* See the accompanying LICENSE file for terms.
*/
/*jslint anon:true, node:true, nomen:true*/
'use strict';
var VERSION = '1.0.2',
DEFAULT = '*',
SEPARATOR = '/',
SUBMATCH = /\$\$[a-zA-Z0-9.-_]*\$\$/;
//---------------------------------------------------------------
// UTILITY FUNCTIONS
function objectMerge(from, to) {
var key;
for (key in from) {
if (from.hasOwnProperty(key)) {
if (to.hasOwnProperty(key)) {
// Property in destination object set; update its value.
if (from[key] && from[key].constructor === Object) {
to[key] = objectMerge(from[key], to[key]);
} else {
to[key] = from[key];
}
} else {
// Property in destination object not set; create it and set its value.
to[key] = from[key];
}
}
}
return to;
}
function extract(bag, key, def) {
var keys,
cur = bag,
i;
if (!key) {
return bag || {};
}
keys = key.split('.');
for (i = 0; i < keys.length; i += 1) {
if (cur[keys[i]]) {
cur = cur[keys[i]];
} else {
return def;
}
}
return cur;
}
//---------------------------------------------------------------
// OBJECT ORIENTED INTERFACE
function Ycb(bundle, options) {
this.options = options || {};
this.dimensions = {};
this.settings = {};
this.schema = {};
this.dimsUsed = {}; // dim name: value: true
this._processRawBundle(bundle, this.options);
}
Ycb.prototype = {
/**
* Returns the dimensions in the YCB file.
* @method getDimensions
* @return {object} the dimensions
*/
getDimensions: function () {
return this._cloneObj(this.dimensions);
},
/**
* Iterates over all the setting sections in the YCB file, calling the
* callback for each section.
* @method walkSettings
* @param callback {function(settings, config)}
* @param callback.settings {object} the condition under which section will be used
* @param callback.config {object} the configuration in the section
* @param callback.return {boolean} if the callback returns false, then walking is stopped
* @return {nothing} results returned via callback
*/
walkSettings: function (callback) {
var path,
context;
for (path in this.settings) {
if (this.settings.hasOwnProperty(path)) {
context = this._getContextFromLookupPath(path);
// clone, so that noone mutates us
if (!callback(context, this._cloneObj(this.settings[path]))) {
break;
}
}
}
},
/**
* Read the file.
* @method read
* @param context {object}
* @param options {object}
* @return {object}
*/
read: function (context, options) {
var lookupPaths,
path,
config = {};
context = context || {};
options = objectMerge(this.options, options || {});
lookupPaths = this._getLookupPaths(context, options);
if (options.debug) {
console.log(JSON.stringify(context, null, 4));
console.log(JSON.stringify(this.dimensions, null, 4));
console.log(JSON.stringify(this.settings, null, 4));
console.log(JSON.stringify(this.schema, null, 4));
console.log(JSON.stringify(lookupPaths, null, 4));
}
// Now we simply merge each macting settings section we find into the config
for (path = 0; path < lookupPaths.length; path += 1) {
if (this.settings[lookupPaths[path]]) {
if (options.debug) {
console.log('----USING---- ' + lookupPaths[path]);
console.log(JSON.stringify(this.settings[lookupPaths[path]], null, 4));
}
// merge a copy so that we don't modify the source
config = objectMerge(this._cloneObj(this.settings[lookupPaths[path]]), config);
}
}
this._applySubstitutions(config);
if (options.validate) {
console.log('The YCB option "validate" is not implemented yet.');
}
return config;
},
/**
* Like read(), but doesn't merge the found sections.
* Also, doesn't do substitutions.
*
* @method readNoMerge
* @param context {object}
* @param options {object}
* @return {array of objects}
*/
readNoMerge: function (context, options) {
var lookupPaths,
path,
config = [];
context = context || {};
lookupPaths = this._getLookupPaths(context, options);
if (options.debug) {
console.log(JSON.stringify(context, null, 4));
console.log(JSON.stringify(this.dimensions, null, 4));
console.log(JSON.stringify(this.settings, null, 4));
console.log(JSON.stringify(this.schema, null, 4));
console.log(JSON.stringify(lookupPaths, null, 4));
}
// Now we simply merge each macting settings section we find into the config
for (path = 0; path < lookupPaths.length; path += 1) {
if (this.settings[lookupPaths[path]]) {
if (options.debug) {
console.log('----USING---- ' + lookupPaths[path]);
console.log(JSON.stringify(this.settings[lookupPaths[path]], null, 4));
}
config.push(this._cloneObj(this.settings[lookupPaths[path]]));
}
}
return config;
},
/**
* This is a first pass at hairball of a funciton.
*
* @private
* @method _applySubstitutions
* @param config {object}
* @param base {object}
* @param parent {object}
* @return void
*/
_applySubstitutions: function (config, base, parent) {
var key,
sub,
find,
item;
base = base || config;
parent = parent || {ref: config, key: null};
for (key in config) {
if (config.hasOwnProperty(key)) {
// If the value is an "Object" or an "Array" drill into it
if (config[key] && (config[key].constructor === Object || config[key].constructor === Array)) {
// The whole {ref: config, key: key} is needed only when replacing "keys"
this._applySubstitutions(config[key], base, {ref: config, key: key});
} else {
// Test if the key is a "substitution" key
if (SUBMATCH.test(key)) {
// We have a matching so lets do some work
sub = SUBMATCH.exec(key);
// Is it the whole key or just something odd
if (sub[0] === key) {
// Pull out he key to "find"
find = extract(base, sub[0].slice(2, -2), null);
if (find.constructor === Object) {
// Remove the "substitution" key
delete config[key];
// Add the keys founds
// This should be inline at the point where the "substitution" key was.
// Currently they will be added out of order on the end of the map.
for (item in find) {
if (find.hasOwnProperty(item)) {
if (!parent.ref[parent.key]) {
parent.ref[item] = find[item];
} else {
parent.ref[parent.key][item] = find[item];
}
}
}
} else {
config[key] = '--YCB-SUBSTITUTION-ERROR--';
}
}
} else if (SUBMATCH.test(config[key])) {
// Test if the value is a "substitution" value
// We have a match so lets use it
sub = SUBMATCH.exec(config[key]);
// Pull out he key to "find"
find = sub[0].slice(2, -2);
// First see if it is the whole value
if (sub[0] === config[key]) {
// Replace the whole value with the value found by the sub string
find = extract(base, find, null);
// If we have an array in an array do it "special like"
if (find.constructor === Array && config.constructor === Array) {
// This has to be done on the parent or the referance is lost
// The whole {ref: config, key: key} is needed only when replacing "keys"
parent.ref[parent.key] = config.slice(0, parseInt(key, 10))
.concat(find)
.concat(config.slice(parseInt(key, 10) + 1));
} else {
config[key] = find;
}
} else {
// If not it's just part of the whole value
config[key] = config[key].replace(sub[0], extract(base, find, null));
}
}
}
}
}
},
/**
* @private
* @method _getLookupPaths
* @param context {object} Key/Value list
* @param options {object} runtime options
* @return {Array}
*/
_getLookupPaths: function (context, options) {
var values = this._makeOrderedLookupList(context, options),
lookupList = Object.keys(values),
path = [],
paths = [],
pos,
current = lookupList.length - 1,
combination = [];
// This is our combination that we will tumble over
for (pos = 0; pos < lookupList.length; pos += 1) {
combination.push({
current: 0,
total: values[lookupList[pos]].length - 1
});
}
function tumble(combination, location) {
// If the location is not found return
if (!combination[location]) {
return false;
}
// Move along to the next item
combination[location].current += 1;
// If the next item is not found move to the prev location
if (combination[location].current > combination[location].total) {
combination[location].current = 0;
return tumble(combination, location - 1);
}
return true;
}
do {
path = [];
for (pos = 0; pos < lookupList.length; pos += 1) {
path.push(values[lookupList[pos]][combination[pos].current]);
}
paths.push(path.join(SEPARATOR));
} while (tumble(combination, current));
return paths.reverse();
},
/**
* @private
* @method _processRawBundle
* @param bundle {object}
* @param options {object}
* @return {nothing}
*/
_processRawBundle: function (bundle, options) {
var pos,
section,
part,
kv,
context,
key;
// Extract each section from the bundle
for (pos = 0; pos < bundle.length; pos += 1) {
section = bundle[pos];
if (section.dimensions) {
this.dimensions = section.dimensions;
this._flattenDimensions();
} else if (section.schema) {
this.schema = section.schema;
} else if (section.settings) {
context = {};
for (part = 0; part < section.settings.length; part += 1) {
kv = section.settings[part].split(':');
if ('master' !== section.settings[0]) {
if (!this.dimsUsed[kv[0]]) {
this.dimsUsed[kv[0]] = {};
}
this.dimsUsed[kv[0]][kv[1]] = true;
}
context[kv[0]] = kv[1];
}
// Remove the settings key now we are done with it
delete section.settings;
// Build the full context path
key = this._getLookupPath(context, options);
// Add the section to the settings list with it's full key
// IMY Bug 5439377 configuration does not accept neither null nor false values?
if (!this.settings[key]) {
this.settings[key] = section;
} else {
throw new Error("The settings group '" + JSON.stringify(context) +
"' has already been added.");
}
}
}
},
/**
* @private
* @method _getContextPath
* @param context {object} Key/Value list
* @param options {object}
* @return {string}
*/
_getLookupPath: function (context, options) {
var lookupList = this._makeOrderedLookupList(context, options),
name,
list,
lookup = {},
item,
path = [];
for (name in lookupList) {
if (lookupList.hasOwnProperty(name)) {
if (context[name]) {
for (list = 0; list < lookupList[name].length; list += 1) {
if (lookupList[name][list] === context[name]) {
lookup[name] = lookupList[name][list];
}
}
}
// If there was no match set to default
if (!lookup[name]) {
lookup[name] = DEFAULT;
}
}
}
for (item in lookup) {
if (lookup.hasOwnProperty(item)) {
path.push(lookup[item]);
}
}
return path.join(SEPARATOR);
},
/**
* @private
* @method _getContextFromLookupPath
* @param path {string} the path
* @return {object} the cooresponding context (really a partial context)
*/
_getContextFromLookupPath: function (path) {
var parts = path.split(SEPARATOR),
p,
part,
dimName,
ctx = {};
for (p = 0; p < this.dimensions.length; p += 1) {
part = parts[p];
if ('*' !== part) {
// Having more than one key in the dimensions structure is against
// the YCB spec.
dimName = Object.keys(this.dimensions[p])[0];
ctx[dimName] = part;
}
}
return ctx;
},
/**
* @private
* @method _makeOrderedLookupList
* @param context {object} Key/Value list
* @param options {object}
* @return {object} list of lists
*/
_makeOrderedLookupList: function (context, options) {
var pos,
name,
path,
value,
used,
parts,
i,
chains = {};
for (pos = 0; pos < this.dimensions.length; pos += 1) {
for (name in this.dimensions[pos]) {
if (this.dimensions[pos].hasOwnProperty(name)) {
for (path in this._dimensionPaths[name]) {
if (this._dimensionPaths[name].hasOwnProperty(path)) {
value = this._dimensionPaths[name][path];
used = options.useAllDimensions || false;
if (!options.useAllDimensions && this.dimsUsed[name]) {
parts = path.split(SEPARATOR);
for (i = 0; i < parts.length; i += 1) {
if (this.dimsUsed[name][parts[i]]) {
used = true;
}
}
}
if (used && value === context[name]) {
chains[name] = path;
}
}
}
if (chains[name]) {
// Convert to an ordered list
chains[name] = chains[name].split(SEPARATOR).reverse().concat(DEFAULT);
} else {
// If there was no match set to default
chains[name] = [DEFAULT];
}
}
}
}
return chains;
},
/**
* @private
* @method _flattenDimension
* @param prefix {string}
* @param dimension {object} A single YCB dimension structured object
* @param build {string}
* @return {object} k/v map
*/
_flattenDimension: function (prefix, dimension, build) {
var key,
newPrefix,
nextDimension;
build = build || {};
if (typeof dimension === 'object') {
for (key in dimension) {
if (dimension.hasOwnProperty(key)) {
nextDimension = dimension[key];
newPrefix = (prefix ? prefix + SEPARATOR + key : key);
build[newPrefix] = key;
if (typeof nextDimension === 'object') {
build = this._flattenDimension(newPrefix, nextDimension, build);
}
}
}
}
return build;
},
/**
* @private
* @method _flattenDimensions
* @return {nothing}
*/
_flattenDimensions: function () {
var pos,
name;
this._dimensionPaths = {};
for (pos = 0; pos < this.dimensions.length; pos += 1) {
for (name in this.dimensions[pos]) {
if (this.dimensions[pos].hasOwnProperty(name)) {
this._dimensionPaths[name] = this._flattenDimension('', this.dimensions[pos][name]);
}
}
}
},
/**
* @private
* @method _cloneObj
* @param {object} o object to clone
* @return {object} a copy of the object
*/
_cloneObj: function (o) {
var newO,
i;
if (typeof o !== 'object') {
return o;
}
if (!o) {
return o;
}
if ('[object Array]' === Object.prototype.toString.apply(o)) {
newO = [];
for (i = 0; i < o.length; i += 1) {
newO[i] = this._cloneObj(o[i]);
}
return newO;
}
newO = {};
for (i in o) {
if (o.hasOwnProperty(i)) {
newO[i] = this._cloneObj(o[i]);
}
}
return newO;
}
};
//---------------------------------------------------------------
// MODULE INTERFACE
module.exports = {
version: VERSION,
// object-oriented interface
Ycb: Ycb,
/*
* Processes an Object representing a YCB 2.0 Bundle as defined in the spec.
*
* @method read
* @param bundle {object}
* @param context {object}
* @param validate {boolean}
* @param debug {boolean}
* @return {object}
*/
read: function (bundle, context, validate, debug) {
var ycb = new Ycb(bundle),
opts = {
validate: validate,
debug: debug
};
return ycb.read(context, opts);
},
/*
* Like read(), but doesn't merge the found sections.
*
* @method readNoMerge
* @param bundle {object}
* @param context {object}
* @param validate {boolean}
* @param debug {boolean}
* @return {array of objects}
*/
readNoMerge: function (bundle, context, validate, debug) {
var ycb = new Ycb(bundle),
opts = { debug: debug };
return ycb.readNoMerge(context, opts);
}
};