-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvargate.js
571 lines (564 loc) · 22.9 KB
/
vargate.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
/**!
* vargate v0.9.4 <https://github.com/jperezov/vargate>
* Copyright (c) 2018 Jonathan Perez.
* Licensed under the MIT License.
*/
(function(window) {
"use strict";
/** @type {boolean} */
let squelch = false;
//noinspection UnnecessaryLocalVariableJS
/**
* @type {Object<Function>}
*/
const util = {
/**
* Conditionally logs warnings or throws errors depending on the DEV_MODE setting.
* @param {string} string
*/
throw: function (string) {
// Namespace the message
/** @type {string} */
const message = 'VarGate Error: ' + string;
switch (window['DEV_MODE']) {
case 'warn':
try {
console['error'](message);
} catch (e) {
// Looks like we can't warn anyone
}
break;
case 'strict':
throw message;
default:
// do nothing
}
},
/**
* Conditionally logs messages to help debug based on the value of DEBUG_MODE
* @param {Array|string} message
* @param {boolean=} important
*/
log: function (message, important) {
/** @type {string} */
const prefix = 'VarGate SG1 Log:';
/** @type {Array} */
let args = [];
if (window['DEBUG_MODE']) {
if (typeof message !== 'string' && message.length) {
args = message;
} else {
args.push(message);
}
args.unshift(prefix);
try {
switch (window['DEBUG_MODE']) {
case 'verbose':
console['warn'].apply(console, args);
break;
case 'static':
console['warn'].apply(console, JSON.parse(JSON.stringify(args)));
break;
case 'minimal':
if (important) console['warn'].apply(console, args);
break;
default:
// do nothing
}
} catch (e) {
// Looks like we can't log anything
}
}
},
/**
* Used to squelch the log / throw functions. This allows existing functions to be re-used
* when creating explicit functions to override expected behaviors.
* @param {boolean=} bool
* @returns {boolean}
*/
squelch: function (bool) {
if (typeof bool === 'boolean') {
squelch = bool;
}
return squelch;
},
/**
* Generates a unique ID
* @Function
* @returns {string}
*/
guid: (function () {
/** @type {Array<string>} */
const lut = [];
for (let i = 0; i < 256; i ++) {
/** @type {string} */
lut[i] = (i < 16 ? '0' : '') + (i).toString(16);
}
return function () {
/** @type {number} */
const d0 = Math.random() * 0xffffffff | 0;
/** @type {number} */
const d1 = Math.random() * 0xffffffff | 0;
/** @type {number} */
const d2 = Math.random() * 0xffffffff | 0;
/** @type {number} */
const d3 = Math.random() * 0xffffffff | 0;
return lut[d0 & 0xff] + lut[d0 >> 8 & 0xff] + lut[d0 >> 16 & 0xff] + lut[d0 >> 24 & 0xff] + '-' +
lut[d1 & 0xff] + lut[d1 >> 8 & 0xff] + '-' + lut[d1 >> 16 & 0x0f | 0x40] + lut[d1 >> 24 & 0xff] + '-' +
lut[d2 & 0x3f | 0x80] + lut[d2 >> 8 & 0xff] + '-' + lut[d2 >> 16 & 0xff] + lut[d2 >> 24 & 0xff] +
lut[d3 & 0xff] + lut[d3 >> 8 & 0xff] + lut[d3 >> 16 & 0xff] + lut[d3 >> 24 & 0xff];
}
})()
};
/**
* VarGate constructor
* @param {string} moduleName
* @param {VarGate=} parent
* @constructor
*/
function VarGate(moduleName, parent) {
/** @type {VarGate} */
const self = this;
/** @type {Object} */
const children = {};
/** @type {Object} */
const data = {};
/** @type {Object} */
const gate = {};
/** @type {Object} */
const gateMap = {};
/** @type {number} */
let subKeyWaitCount = 0;
/** @type {string} */
this.moduleName = moduleName;
/**
* Registers a child module, which will be able to access, but not set,
* the data available for this module.
* @param {string} module
* @param {Object<VarGate>=} contextualChildren
* @returns {VarGate}
*/
this.register = function(module, contextualChildren) {
/** @type {Object} */
const sourceChildren = contextualChildren || children;
/** @type {string} */
const namespacedModule = this.moduleName === self.moduleName ? `${self.moduleName}.${module}` : module;
if (parent) {
// All modules should be registered with the top-level parent
return parent.register.call(this, namespacedModule, sourceChildren);
}
util.log(`Registering "${namespacedModule}"`, true);
// This ensures parents are properly associated with nested modules *and* the top-level parent
children[namespacedModule] = sourceChildren[namespacedModule] = new VarGate(namespacedModule, this);
return children[namespacedModule];
};
/**
* Returns a new top-level VarGate instance with a separate namespace.
* @param {string} module
* @returns {VarGate}
*/
this.new = function(module) {
util.log(`Creating new "${module}"`, true);
return new VarGate(module);
};
/**
* Shorthand notation for `VarGate.when(vars, [fn, true], context)`.
* Creates a `when` listener that triggers whenever a `set` occurs
* and the conditions for `vars` evaluate to true.
* @param {string|Array} vars
* @param {Function} fn
* @param {VarGate=} context
*/
this.on = function(vars, fn, context) {
this.when(vars, [fn, true], context);
};
/**
* Executes a given function when data is set or meets a condition.
* Executes immediately if conditions have already been met.
* @param {string|Array} vars
* @param {Function|Array} fn
* @param {VarGate=} context
*/
this.when = function(vars, fn, context) {
// Used to associate data with its callback
/** @type {string} */
const namespace = `${this.moduleName}.${util.guid()}`;
if (parent) {
parent.when.call(this, vars, fn, context);
} else if (vars.length && typeof vars !== 'string') {
util.log([`Waiting in "${this.moduleName}" for`, vars], true);
for (let i = 0; i < vars.length; i ++) {
addCallback.call(this, namespace, vars[i], fn, context || this);
// Try to see if this should already execute
}
this.unlock(vars[0]);
} else {
util.log([`Waiting in "${this.moduleName}" for`, vars], true);
addCallback.call(this, namespace, vars, fn, context || this);
// Try to see if this should already execute
this.unlock(vars + ''); // Concatenating a string so that GCC stops thinking this could be an array
}
};
/**
* Sets a value for a given key within the current module.
* Cannot overwrite keys set for the parent module.
* @param {string} key
* @param {*=} val
* @param {Object=} contextualData
* @param {string=} contextualKey
*/
this.set = function(key, val, contextualData, contextualKey) {
/** @type {Object} */
const sourceData = contextualData || data;
// Grab the namespaced key
/** @type {string} */
const sourceKey = (this.moduleName === self.moduleName? `${this.moduleName}.${key}` : contextualKey) + '';
/** @type {Array} */
const subKey = key.split('.');
if (subKey && subKey.length > 1) {
// Allow parent to set data for submodules
children[`${this.moduleName}.${subKey[0]}`].set(subKey.splice(1).join('.'), val, sourceData, sourceKey);
} else if (parent) {
checkDefined.call(this, key);
parent.set.call(this, key, val, sourceData, sourceKey);
} else {
data[sourceKey] = sourceData[sourceKey] = val;
checkValue.call(this, key, val);
util.log([`${Set} "${sourceKey}" to value`, val]);
this.unlock(key);
}
};
/**
* Used to override a key set by the parent within a given module.
* Will not throw a warning or error, as this is explicitly meant to be an override.
* @param {string} key
* @param {*} val
*/
this.override = function(key, val) {
checkValue.call(this, key, val);
util.squelch(true);
this.set(key, val);
util.squelch(false);
};
/**
* Shorthand to explicitly set a value to undefined.
* @param {string} key
*/
this.unset = function(key) {
checkDefined.call(this, key);
util.squelch(true);
const ret = this.set(key);
util.squelch(false);
return ret;
};
/**
* Gets the data for a given key from the appropriate module
* @param {string} key
* @returns {*}
*/
this.get = function(key) {
const subModuleData = data[`${self.moduleName}.${key}`];
if (typeof subModuleData !== 'undefined') {
return subModuleData;
} else if (parent) {
return parent.get.call(this, key);
} else {
return data[`${this.moduleName}.${key}`];
}
};
/**
* Clears all data for the current module
* @param {Object=} contextualData
*/
this.clear = function(contextualData) {
/** @type {Object} */
const dataArr = (self.moduleName === this.moduleName ? data : contextualData) || {};
if (parent) {
parent.clear.call(this, dataArr);
} else {
const keyRegex = new RegExp(`^${this.moduleName}\.[^\.]*$`);
for (const key in dataArr) {
// Clear data for the module
if (dataArr.hasOwnProperty(key) && key.match(keyRegex)) {
delete dataArr[key];
// Clear data for the top-level parent
if (data.hasOwnProperty(key)) {
delete data[key];
}
}
}
}
};
/**
* Clears all data for the current module and all sub-modules
*/
this.clearAll = function() {
this.clear();
for (const child in children) {
if (children.hasOwnProperty(child)) {
children[child].clearAll();
}
}
};
/**
* Unlocks a given key
* @param {string} key
* @param {boolean=} skipSubKeyCheck
*/
this.unlock = function(key, skipSubKeyCheck) {
if (parent) {
parent.unlock.call(this, key, skipSubKeyCheck);
} else if (typeof gateMap[key] === 'object') {
/** @type {RegExp} */
const valRegex = /^@\w+$/;
for (const namespace in gateMap[key].namespace) {
if (! gateMap[key].namespace.hasOwnProperty(namespace)) continue;
/** @type {Object} */
const gateObj = gate[namespace];
/** @type {Object} */
const conditions = gateObj.cond;
/** @type {number} */
let count = 0;
/** @type {string} */
let cond;
for (cond in conditions) {
if (! conditions.hasOwnProperty(cond)) continue;
/** @type {Object} */
const c = conditions[cond];
/** @type {*} */
const left = gateObj.module.get(cond);
/** @type {*} */
const right = (c.val && c.val.toString().match(valRegex)) ? gateObj.module.get(c.val.slice(1)) : c.val;
try {
if ((new Function('l', 'r', `return eval('l ${c.operator} r')`))(left, right)) {
count ++;
}
} catch (e) {
util.throw(e);
}
}
if (count === gateObj.vars.length) {
util.log(`Conditions [${gateObj.vars.join(',')}] met for "${gateObj.module.moduleName}".`, true);
/** @type {Array} */
const args = [];
for (let i = 0; i < gateObj.vars.length; i ++) {
args.push(gateObj.module.get(gateObj.vars[i]));
}
if (gateObj.fn.length && gateObj.fn[1]) {
// do something when persisting
gateObj.fn[0].apply(gateObj.context, args);
} else {
// Remove future callbacks of this function if not persistent
for (cond in conditions) {
if (! conditions.hasOwnProperty(cond)) continue;
delete gateMap[cond].namespace[namespace];
gateMap[cond].deps --;
if (cond.indexOf('.') !== -1) {
subKeyWaitCount --;
}
if (gateMap[cond].deps === 0) {
delete gateMap[cond];
}
}
delete gate[namespace];
gateObj.fn.apply(gateObj.context, args);
}
}
}
} else if (subKeyWaitCount && ! skipSubKeyCheck) {
for (const gateKey in gateMap) {
if (! gateMap.hasOwnProperty(gateKey)) continue;
/** @type {Array} */
const split = gateKey.split('.');
if (split && split.length && split[split.length - 1] === key) {
self.unlock(gateKey, true);
}
}
}
};
//================+
// Helper Functions
//================+
/**
* Sets up the gate and gateMap to fire the provided callback when the conditions are met.
* @param {string} namespace
* @param {string|Array} prop
* @param {Function|Array} fn
* @param {VarGate} context
* @param {boolean=} stop
*/
function addCallback(namespace, prop, fn, context, stop) {
/** @type {string|null} */
let key;
/** @type {*} */
let val;
/** @type {string} */
let operator;
context = context || this;
if (typeof gate[namespace] === 'undefined') {
// Define the property if this is the first time--otherwise re-use the old definition
gate[namespace] = {
/** @type {Array} */
vars: [],
/** @type {Object} */
cond: {},
/** @type {Function|Array} */
fn: fn,
/** @type {VarGate} */
module: this,
/** @type {VarGate|undefined} */
context: context
};
}
if (Array.isArray(prop)) {
if (prop.length === 2) {
key = `${util.guid()}:${prop[1].replace(/\./g, '-')}`;
operator = '!==';
val = undefined;
assignNestedPropertyListener(prop[0], prop[1], key, context);
} else if (prop.length === 3) {
key = prop[0];
operator = prop[1];
val = prop[2];
if ((val && val.toString().match(/^@\w+$/)) && stop !== true) {
// We're comparing two values--reverse and re-add to watch for both values
addCallback(namespace, [val.slice(1), operator, '@' + key], fn, context, true);
}
} else {
util.throw(`Invalid number of arguments passed through: [${prop.join(',')}] (should be [key, operator, condition])`);
}
} else {
key = prop;
operator = '!==';
val = undefined;
}
try {
gate[namespace].vars.push(key);
gate[namespace].cond[key] = {
/** @type {string} */
operator: operator,
/** @type {*} */
val: val
};
if (typeof gateMap[key] === 'undefined') {
gateMap[key] = {
/** @type {number} */
deps: 0,
/** @type {Object<string>} */
namespace: {}
};
}
gateMap[key].namespace[namespace] = true;
gateMap[key].deps ++;
if (key.indexOf('.') !== -1) {
subKeyWaitCount ++;
}
} catch (e) {
util.throw(`Cannot set "${JSON.stringify(prop)}" as a property`);
}
}
/**
* Used to prevent the user from setting a value to `undefined` without explicitly calling `unset`.
* Only works when `window.DEV_MODE` is 'strict' or 'warn'
* @param {string} key
* @param {*} val
*/
function checkValue(key, val) {
if (typeof val === 'undefined' && ! util.squelch()) {
util.throw(`"${key}" set to 'undefined'. Was this intentional? Use 'unset("${key}")' if it was.`);
}
}
/**
* Used to prevent users from overriding a key without using a function meant to explicitly do so.
* Only works when `window.DEV_MODE` is 'strict' or 'warn'
* @param {string} key
*/
function checkDefined(key) {
//noinspection JSPotentiallyInvalidUsageOfThis
if (! data[`${this.moduleName}.${key}`] && typeof parent.get(key) !== 'undefined' && ! util.squelch()) {
// Not allowing sub-modules to name variables already defined in the parent (unless using override).
// Things get weird when expecting a variable defined in two places.
//noinspection JSPotentiallyInvalidUsageOfThis
util.throw(`In "${this.moduleName}" variable "${key}" defined in module "${parent.moduleName}". Choose a different name.`);
}
}
/**
* Listens and marks when a property is available
* @param {Object} object
* @param {string} key
* @param {string} fullKey
* @param {VarGate} context
*/
function assignNestedPropertyListener(object, key, fullKey, context) {
/** @type {Array} */
const pathArray = key.split('.');
if (pathArray.length === 1 && typeof key === 'string') {
// Sanitize `key`
key = key.replace(/[^\w$]/g, '');
if (object[key] === undefined) {
// Create a watch on the property, and run once it's been set
Object.defineProperty(object, key, {
/** @type {boolean} */
'configurable': true,
/** @param {*} val */
'set': function(val) {
delete object[key];
object[key] = val;
context.set(fullKey, object);
}
});
} else {
// The property's already been defined. Trigger it.
context.set(fullKey, object);
}
} else {
assignNestedPropertyListener(object[pathArray[0]], pathArray.splice(1).join('.'), fullKey, context);
}
}
// Exports for Google Closure Compiler
/** @type {VarGate|undefined} */
this['parent'] = parent;
/** @type {Object<VarGate>} */
this['children'] = children;
/** @type {Object} */
this['data'] = data;
/** @type {Object} */
this['gate'] = gate;
/** @type {Object} */
this['gateMap'] = gateMap;
/** @type {number} */
this['subKeyWaitCount'] = subKeyWaitCount;
/** @Function */
this['register'] = this.register;
/** @Function */
this['new'] = this.new;
/** @Function */
this['on'] = this.on;
/** @Function */
this['when'] = this.when;
/** @Function */
this['set'] = this.set;
/** @Function */
this['override'] = this.override;
/** @Function */
this['unset'] = this.unset;
/** @Function */
this['get'] = this.get;
/** @Function */
this['clearAll'] = this.clearAll;
/** @Function */
this['unlock'] = this.unlock;
}
const Gate = new VarGate('vargate');
if (typeof window['define'] === 'function' && window['define']['amd']) {
// Remain anonymous if AMD library is available
window['define'](function() {
return Gate;
});
} else if (typeof window['module'] === 'object' && window['module']['exports']) {
// Use CommonJS / ES6 if available
window['module']['exports'] = Gate;
} else {
window['VarGate'] = Gate;
}
}(typeof window !== 'undefined' ? window : this));