-
Alvaro Cabrera authoredAlvaro Cabrera authored
index.js 32.85 KiB
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var $RefParser = _interopDefault(require('json-schema-ref-parser'));
var deref = _interopDefault(require('deref'));
var tslib_1 = require('tslib');
// dynamic proxy for custom generators
function proxy(gen) {
return function (value, schema, property) {
var fn = value;
var args = [];
// support for nested object, first-key is the generator
if (typeof value === 'object') {
fn = Object.keys(value)[0];
// treat the given array as arguments,
if (Array.isArray(value[fn])) {
// if the generator is expecting arrays they should be nested, e.g. `[[1, 2, 3], true, ...]`
args = value[fn];
}
else {
args.push(value[fn]);
}
}
// support for keypaths, e.g. "internet.email"
var props = fn.split('.');
// retrieve a fresh dependency
var ctx = gen();
while (props.length > 1) {
ctx = ctx[props.shift()];
}
// retrieve last value from context object
value = typeof ctx === 'object' ? ctx[props[0]] : ctx;
// invoke dynamic generators
if (typeof value === 'function') {
value = value.apply(ctx, args);
}
// test for pending callbacks
if (Object.prototype.toString.call(value) === '[object Object]') {
for (var key in value) {
if (typeof value[key] === 'function') {
throw new Error('Cannot resolve value for "' + property + ': ' + fn + '", given: ' + value);
}
}
}
return value;
};
}
/**
* Container is used to wrap external generators (faker, chance, casual, etc.) and its dependencies.
*
* - `jsf.extend('faker')` will enhance or define the given dependency.
* - `jsf.define('faker')` will provide the "faker" keyword support.
*
* RandExp is not longer considered an "extension".
*/
var Container = (function () {
function Container() {
// dynamic requires - handle all dependencies
// they will NOT be included on the bundle
this.registry = {};
this.support = {};
}
/**
* Override dependency given by name
* @param name
* @param callback
*/
Container.prototype.extend = function (name, callback) {
var _this = this;
this.registry[name] = callback(this.registry[name]);