New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

mocker-data-generator

Package Overview
Dependencies
Maintainers
1
Versions
68
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

mocker-data-generator - npm Package Compare versions

Comparing version

to
3.0.1

build/main/lib/types.d.ts

17

build/main/bench.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var fakerJS = require("faker");
var Generator_1 = require("./lib/Generator");

@@ -7,19 +8,7 @@ var gen = new Generator_1.Generator();

console.time('faker new');
res = gen.faker({ faker: 'lorem.words' });
res = gen.custom({ generator: fakerJS, input: 'lorem.words' });
console.timeEnd('faker new');
console.time('faker eval');
res = gen.faker({ faker: 'lorem.words', eval: true });
res = gen.custom({ generator: fakerJS, input: 'lorem.words', eval: true });
console.timeEnd('faker eval');
console.time('chance new');
res = gen.chance({ chance: 'integer' });
console.timeEnd('chance new');
console.time('chance eval');
res = gen.chance({ chance: 'integer', eval: true });
console.timeEnd('chance eval');
console.time('casual new');
res = gen.casual({ casual: 'country' });
console.timeEnd('casual new');
console.time('casual eval');
res = gen.casual({ casual: 'country', eval: true });
console.timeEnd('casual eval');
//# sourceMappingURL=bench.js.map

@@ -5,3 +5,3 @@ "use strict";

var _1 = require("./"), lib = _1;
ava_1.default('functions can be used without es imports', function (t) {
(0, ava_1.default)('functions can be used without es imports', function (t) {
t.true(typeof _1.default === 'function');

@@ -13,4 +13,4 @@ t.true(typeof lib.mocker === 'function');

});
ava_1.default('Mocker: exists all methods', function (t) {
var m = _1.default();
(0, ava_1.default)('Mocker: exists all methods', function (t) {
var m = (0, _1.default)();
var methods = ['schema', 'build', 'reset', 'restart'];

@@ -17,0 +17,0 @@ methods.forEach(function (method) { return t.true(typeof m[method] === 'function'); });

@@ -0,1 +1,2 @@

import { CustomGeneratorRun } from './types';
export declare class Generator<T> {

@@ -14,18 +15,3 @@ name: string;

virtualPaths: string[];
faker(cfg: {
locale?: string;
faker: string;
eval?: boolean;
}): any;
chance(cfg: {
chance: string;
eval?: boolean;
}): any;
casual(cfg: {
eval?: boolean;
casual: string;
}): any;
randexp(cfg: {
randexp: any;
}): string;
generators: {};
self(cfg: {

@@ -39,2 +25,9 @@ self: any;

}): any;
custom(cfg: {
generator: any;
input: string | RegExp;
run?: CustomGeneratorRun;
adapter?: (generator: any, input: string | RegExp) => any;
eval?: boolean;
}): any;
eval(cfg: {

@@ -41,0 +34,0 @@ eval: string;

@@ -5,86 +5,6 @@ "use strict";

var tslib_1 = require("tslib");
// import * as c from 'casual-browserify'
var chance_1 = require("chance");
var f = require("faker");
var R = require("randexp");
var utils_1 = require("./utils");
var c = require('casual-browserify');
var ch = new chance_1.Chance();
var Generator = /** @class */ (function () {
function Generator() {
}
Generator.prototype.faker = function (cfg) {
var faker = f;
var db = this.DB;
var object = this.object;
var re;
var matches;
var strFn;
if (cfg.locale === '') {
throw "Locale is empty \"" + cfg.locale + "\".";
}
if (cfg.locale) {
var supportedLocales = Object.keys(faker.locales);
if (supportedLocales.indexOf(cfg.locale) === -1) {
throw "Locale \"" + cfg.locale + "\" is not supported by faker.";
}
faker = require('faker/locale/' + cfg.locale);
}
if (cfg.eval) {
re = /(^[a-zA-Z.]*)/; // aZ.aZ
matches = re.exec(cfg.faker);
if (matches && matches.length === 2) {
strFn = 'faker.' + cfg.faker;
}
re = /\((.*?)\)/; // Match ()
matches = re.exec(cfg.faker);
if (!matches) {
strFn = 'faker.' + cfg.faker + '()';
}
return eval(strFn);
}
else {
return utils_1.fnParser('faker', faker, cfg.faker);
}
};
Generator.prototype.chance = function (cfg) {
var chance = ch;
if (cfg.eval) {
var db = this.DB;
var object = this.object;
var re = /(^[a-zA-Z.]*)/; // aZ.aZ
var matches = re.exec(cfg.chance);
var strFn = void 0;
if (matches && matches.length === 2) {
strFn = 'chance.' + cfg.chance;
}
re = /\((.*?)\)/; // Match ()
matches = re.exec(cfg.chance);
if (!matches) {
strFn = 'chance.' + cfg.chance + '()';
}
return eval(strFn);
}
else {
return utils_1.fnParser.call(chance, 'chance', chance, cfg.chance);
}
};
Generator.prototype.casual = function (cfg) {
var casual = c;
if (cfg.eval) {
var re = /(^[a-zA-Z.]*)/; // aZ.aZ
var matches = re.exec(cfg.casual);
var strFn = void 0;
if (matches && matches.length === 2) {
strFn = 'casual.' + cfg.casual;
}
return eval(strFn);
}
else {
return utils_1.fnParser.call(casual, 'casual', casual, cfg.casual);
}
};
Generator.prototype.randexp = function (cfg) {
return new R(cfg.randexp).gen();
};
Generator.prototype.self = function (cfg) {

@@ -94,3 +14,3 @@ var object = this.object;

? eval('object.' + cfg.self)
: utils_1.loopInside(this.object, cfg.self);
: (0, utils_1.loopInside)(this.object, cfg.self);
};

@@ -103,12 +23,26 @@ Generator.prototype.db = function (cfg) {

else {
return utils_1.loopInside(this.DB, cfg.db);
return (0, utils_1.loopInside)(this.DB, cfg.db);
}
};
Generator.prototype.custom = function (cfg) {
var db = this.DB;
var object = this.object;
var re;
var matches;
var strFn;
var generator = cfg.generator;
if (cfg.run) {
return cfg.run(generator, cfg.input);
}
else if (cfg.eval) {
return eval('generator.' + cfg.input);
}
else {
return utils_1.stringToPathOrCall.call(generator, 'generator', generator, cfg.input);
}
};
Generator.prototype.eval = function (cfg) {
var db = this.DB;
var object = this.object;
var faker = f;
var chance = ch;
var casual = c;
var randexp = R;
var generators = this.generators;
return eval(cfg.eval);

@@ -128,7 +62,4 @@ };

var db = this.DB;
var faker = f;
var chance = ch;
var casual = c;
var randexp = R;
return (_a = cfg.function).call.apply(_a, tslib_1.__spreadArrays([{ object: object, db: db, faker: faker, chance: chance, casual: casual, randexp: randexp }], args));
var generators = this.generators;
return (_a = cfg.function).call.apply(_a, tslib_1.__spreadArray([{ object: object, db: db, generators: generators }], args, false));
};

@@ -159,3 +90,3 @@ Generator.prototype.static = function (cfg) {

? eval('element.' + cfg.get)
: utils_1.loopInside(element, cfg.get)
: (0, utils_1.loopInside)(element, cfg.get)
: element;

@@ -169,3 +100,3 @@ if (cfg.uniqueDB.length === 0 ||

if (entity === null) {
throw "Can\u00B4t get unique data. Source \"" + cfg.hasOne + "\" has not enough data";
throw "Can\u00B4t get unique data. Source \"".concat(cfg.hasOne, "\" has not enough data");
}

@@ -179,3 +110,3 @@ }

? eval('entity.' + cfg.get)
: utils_1.loopInside(entity, cfg.get)
: (0, utils_1.loopInside)(entity, cfg.get)
: entity;

@@ -203,5 +134,5 @@ }

return cfg.unique
? Array.from(new Array(amount)).reduce(function (acc, val) { return tslib_1.__spreadArrays(acc, [
? Array.from(new Array(amount)).reduce(function (acc, val) { return tslib_1.__spreadArray(tslib_1.__spreadArray([], acc, true), [
_this.hasOne(tslib_1.__assign(tslib_1.__assign({}, newCfg), { uniqueDB: acc }))
]); }, [])
], false); }, [])
: Array.from(new Array(amount)).map(function () { return _this.hasOne(newCfg); });

@@ -208,0 +139,0 @@ };

import { Schema } from './Schema';
export declare type PromiseCb = Promise<any> | void;
export declare type IDB = {
import { CustomGeneratorRun, Generators } from './types';
export type PromiseCb = Promise<any> | void;
export type IDB = {
[key: string]: any[];

@@ -10,4 +11,6 @@ };

options: {};
generators: Generators;
constructor(options?: {});
seed(name: string, data: any[]): Mocker;
addGenerator(name: string, library: any, run: CustomGeneratorRun): Mocker;
schema(name: string, schema: {}, options?: {}): Mocker;

@@ -14,0 +17,0 @@ reset(): Mocker;

@@ -12,2 +12,3 @@ "use strict";

this.options = {};
this.generators = {};
this.options = options;

@@ -20,2 +21,6 @@ this.DB = {};

};
Mocker.prototype.addGenerator = function (name, library, run) {
this.generators[name] = { library: library, run: run };
return this;
};
Mocker.prototype.schema = function (name, schema, options) {

@@ -35,6 +40,7 @@ this.schemas.push(new Schema_1.Schema(name, schema, options));

Mocker.prototype._buildSync = function () {
var _this = this;
this.schemas.reduce(function (acc, schema) {
var instances;
try {
instances = schema.build(acc);
instances = schema.build(_this.generators, acc);
}

@@ -47,3 +53,3 @@ catch (e) {

instances.forEach(function (x) {
return utils_1.cleanVirtuals(schema.virtualPaths, x, {
return (0, utils_1.cleanVirtuals)(schema.virtualPaths, x, {
strict: true,

@@ -50,0 +56,0 @@ symbol: ','

import { Generator } from './Generator';
import { Generators } from './types';
export declare class Schema extends Generator<any> {
constructor(name: string, cfg: any, options: any);
proccessLeaf(field: any): any;
generateField(cfg: any, ...args: any[]): {};
constructor(name: string, cfg: any, options: any, generators?: Generators);
proccessLeaf(field: any, fieldName?: any): any;
generateField(fieldName: any, cfg: any, ...args: any[]): {};
buildSingle(schema: any): void;
build(db?: {}): any;
build(generators?: Generators, db?: {}): any;
}

@@ -16,5 +16,5 @@ "use strict";

path.push(k);
if (utils_1.iamLastParent(value)) {
if ((0, utils_1.iamLastParent)(value)) {
if (path) {
if (utils_1.isArray(value)) {
if ((0, utils_1.isArray)(value)) {
if (value[0] && value[0].virtual) {

@@ -31,3 +31,3 @@ _this.virtualPaths.push(path.toString());

var key = '';
if (!utils_1.isConditional(k)) {
if (!(0, utils_1.isConditional)(k)) {
key = k;

@@ -37,3 +37,3 @@ }

var keykey = k.split(',');
if (utils_1.evalWithContextData(keykey[0], _this.object)) {
if ((0, utils_1.evalWithContextData)(keykey[0], _this.object, _this.DB, _this.generators)) {
key = keykey[1];

@@ -43,3 +43,3 @@ }

if (key !== '') {
res[key] = _this.proccessLeaf(value);
res[key] = _this.proccessLeaf(value, key);
}

@@ -55,3 +55,4 @@ }

tslib_1.__extends(Schema, _super);
function Schema(name, cfg, options) {
function Schema(name, cfg, options, generators) {
if (generators === void 0) { generators = {}; }
var _this = _super.call(this) || this;

@@ -61,2 +62,3 @@ _this.schema = cfg;

_this.options = options;
_this.generators = generators;
// Temp fields

@@ -68,5 +70,5 @@ _this.DB = {};

}
Schema.prototype.proccessLeaf = function (field) {
Schema.prototype.proccessLeaf = function (field, fieldName) {
var _this = this;
if (utils_1.isArray(field)) {
if ((0, utils_1.isArray)(field)) {
var fieldConfig_1 = field[0];

@@ -78,11 +80,11 @@ if (field.length > 1) {

if (fieldConfig_1.concat) {
na = utils_1.evalWithContextData(fieldConfig_1.concat, this.object, this.DB);
na = (0, utils_1.evalWithContextData)(fieldConfig_1.concat, this.object, this.DB, this.generators);
// Strict Mode
na = fieldConfig_1.concatStrict
? tslib_1.__spreadArrays(Array.from(new Set(na))) : na;
? tslib_1.__spreadArray([], Array.from(new Set(na)), true) : na;
}
var length_1 = utils_1.fieldArrayCalcLength(fieldConfig_1, na.length, this);
var length_1 = (0, utils_1.fieldArrayCalcLength)(field.length > 1 ? fieldConfig_1.values : fieldConfig_1, na.length, this);
var array = Array.from(new Array(length_1)).reduce(function (acc, el, index) {
var self = acc.slice(0);
acc.push(_this.generateField(fieldConfig_1, index, length_1, self));
acc.push(_this.generateField(fieldName, fieldConfig_1, index, length_1, self));
return acc;

@@ -93,16 +95,14 @@ }, []);

else {
return this.generateField(field);
return this.generateField(fieldName, field);
}
};
Schema.prototype.generateField = function (cfg) {
Schema.prototype.generateField = function (fieldName, cfg) {
var _a, _b;
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
var result = {};
var generators = [
'faker',
'chance',
'casual',
'randexp',
var customGenerators = Object.keys(this.generators);
var ownedByMocker = [
'self',

@@ -117,2 +117,3 @@ 'db',

];
var generators = tslib_1.__spreadArray(tslib_1.__spreadArray([], ownedByMocker, true), customGenerators, true);
var keys = Object.keys(cfg);

@@ -126,3 +127,3 @@ var key = keys.reduce(function (acc, val) {

if (key === 'noKey' && !keys.includes('eval')) {
throw "Error: Cant find key, please check model and use one of this [" + generators.join(',') + "]";
throw "Error: Invalid or missing generator".concat(fieldName !== 'root' ? " on field ".concat(fieldName) : '', ". Please use one of this generators [").concat(generators.join(','), "], note that if your generator doesnt appear in the list maybe you forgot to add it.");
}

@@ -133,3 +134,10 @@ if (keys.includes('eval') && keys.length === 1) {

try {
result = this[key].apply(this, tslib_1.__spreadArrays([cfg], args));
result = customGenerators.includes(key)
? this.custom({
generator: (_a = this.generators[key]) === null || _a === void 0 ? void 0 : _a.library,
run: (_b = this.generators[key]) === null || _b === void 0 ? void 0 : _b.run,
input: cfg[key],
eval: cfg.eval
})
: this[key].apply(this, tslib_1.__spreadArray([tslib_1.__assign(tslib_1.__assign({}, cfg), { generators: this.generators })], args, false));
}

@@ -142,4 +150,4 @@ catch (e) {

Schema.prototype.buildSingle = function (schema) {
if (utils_1.iamLastParent(schema)) {
this.object = this.proccessLeaf(schema);
if ((0, utils_1.iamLastParent)(schema)) {
this.object = this.proccessLeaf(schema, 'root');
}

@@ -150,5 +158,7 @@ else {

};
Schema.prototype.build = function (db) {
Schema.prototype.build = function (generators, db) {
var _this = this;
if (generators === void 0) { generators = {}; }
if (db === void 0) { db = {}; }
this.generators = generators;
this.object = {};

@@ -164,3 +174,3 @@ this.DB = db ? db : {};

}
else if (utils_1.isObject(this.options) && this.options.max) {
else if ((0, utils_1.isObject)(this.options) && this.options.max) {
var max = this.options.max;

@@ -175,3 +185,3 @@ var min = this.options.min ? this.options.min : 0;

}
else if (utils_1.isObject(this.options) && this.options.uniqueField) {
else if ((0, utils_1.isObject)(this.options) && this.options.uniqueField) {
var f_1 = this.options.uniqueField;

@@ -185,3 +195,3 @@ var entityConfig_1 = this.schema;

if (this.schema[f_1]) {
if (utils_1.isArray(this.schema[f_1].values)) {
if ((0, utils_1.isArray)(this.schema[f_1].values)) {
possibleValues = this.schema[f_1].values;

@@ -194,6 +204,6 @@ }

else {
throw "The field \"" + f_1 + "\" not exists.";
throw "The field \"".concat(f_1, "\" not exists.");
}
}
if (!utils_1.isArray(possibleValues)) {
if (!(0, utils_1.isArray)(possibleValues)) {
throw "The posible values value is not an Array";

@@ -212,3 +222,3 @@ }

else {
throw "An string \"" + this.options + "\" is not recognized as a parameter.";
throw "An string \"".concat(this.options, "\" is not recognized as a parameter.");
}

@@ -215,0 +225,0 @@ return this.DB[this.name];

export declare const isArray: (arg: any) => boolean;
export declare const isObject: (arg: any) => boolean;
export declare const evalWithContextData: (key: string, object: {}, db?: any) => any;
export declare const evalWithContextData: (key: string, object: {}, db: {}, generators: {}) => any;
export declare const fieldArrayCalcLength: (config: any, fixedArrayLength: any, schema: any) => any;

@@ -9,3 +9,3 @@ export declare const iamLastChild: (parent: any, k: any) => boolean;

export declare const cleanVirtuals: (paths: any, object: any, options: any) => any;
export declare const fnParser: (name: any, fn: any, cfg: any) => any;
export declare const stringToPathOrCall: (name: any, fn: any, cfg: any) => any;
export declare const loopInside: (object: any, path: string) => any;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.loopInside = exports.fnParser = exports.cleanVirtuals = exports.isConditional = exports.iamLastParent = exports.iamLastChild = exports.fieldArrayCalcLength = exports.evalWithContextData = exports.isObject = exports.isArray = void 0;
exports.loopInside = exports.stringToPathOrCall = exports.cleanVirtuals = exports.isConditional = exports.iamLastParent = exports.iamLastChild = exports.fieldArrayCalcLength = exports.evalWithContextData = exports.isObject = exports.isArray = void 0;
var tslib_1 = require("tslib");

@@ -13,3 +13,3 @@ var isArray = function (arg) {

exports.isObject = isObject;
var evalWithContextData = function (key, object, db) {
var evalWithContextData = function (key, object, db, generators) {
// In this (way, we can pass object and use inside the eval string

@@ -34,3 +34,3 @@ return eval(key);

var iamLastChild = function (parent, k) {
if (exports.isArray(parent[k])) {
if ((0, exports.isArray)(parent[k])) {
var last = false;

@@ -42,3 +42,3 @@ if (parent[k].length === 0) {

var el = parent[k][i];
last = !exports.isObject(el);
last = !(0, exports.isObject)(el);
if (last) {

@@ -51,3 +51,3 @@ break;

else {
return !exports.isObject(parent[k]);
return !(0, exports.isObject)(parent[k]);
}

@@ -58,7 +58,7 @@ };

var last = false;
if (exports.isObject(obj)) {
if ((0, exports.isObject)(obj)) {
var ks = Object.keys(obj);
for (var i = 0; i < ks.length; i++) {
var k = ks[i];
last = exports.iamLastChild(obj, k);
last = (0, exports.iamLastChild)(obj, k);
if (!last) {

@@ -176,3 +176,3 @@ break;

exports.cleanVirtuals = cleanVirtuals;
var fnParser = function (name, fn, cfg) {
var stringToPathOrCall = function (name, fn, cfg) {
var _a = cfg.split('('), body = _a[0], args = _a[1];

@@ -182,3 +182,3 @@ body = body.split('.');

if (!acc[val]) {
throw "This " + name + " method doesnt exists '" + cfg + "'.";
throw "This ".concat(name, " method doesnt exists '").concat(cfg, "'.");
}

@@ -201,3 +201,3 @@ return acc[val];

: [];
var result = func.call.apply(func, tslib_1.__spreadArrays([this], args));
var result = func.call.apply(func, tslib_1.__spreadArray([this], args, false));
if (!mods || mods === '') {

@@ -213,3 +213,3 @@ return result;

if (!acc[val]) {
throw "'" + acc + "' doesnt have key '" + val + "'.";
throw "'".concat(acc, "' doesnt have key '").concat(val, "'.");
}

@@ -219,3 +219,3 @@ return acc[val];

};
exports.fnParser = fnParser;
exports.stringToPathOrCall = stringToPathOrCall;
var loopInside = function (object, path) {

@@ -225,3 +225,3 @@ var p = path.split('.');

if (acc[val] === null) {
throw "'" + acc + "' doesnt have key '" + val + "'.";
throw "'".concat(acc, "' doesnt have key '").concat(val, "'.");
}

@@ -228,0 +228,0 @@ return acc[val];

@@ -0,1 +1,2 @@

import * as fakerJS from 'faker';
import { Generator } from './lib/Generator';

@@ -5,19 +6,7 @@ var gen = new Generator();

console.time('faker new');
res = gen.faker({ faker: 'lorem.words' });
res = gen.custom({ generator: fakerJS, input: 'lorem.words' });
console.timeEnd('faker new');
console.time('faker eval');
res = gen.faker({ faker: 'lorem.words', eval: true });
res = gen.custom({ generator: fakerJS, input: 'lorem.words', eval: true });
console.timeEnd('faker eval');
console.time('chance new');
res = gen.chance({ chance: 'integer' });
console.timeEnd('chance new');
console.time('chance eval');
res = gen.chance({ chance: 'integer', eval: true });
console.timeEnd('chance eval');
console.time('casual new');
res = gen.casual({ casual: 'country' });
console.timeEnd('casual new');
console.time('casual eval');
res = gen.casual({ casual: 'country', eval: true });
console.timeEnd('casual eval');
//# sourceMappingURL=bench.js.map

@@ -1,86 +0,6 @@

import { __assign, __spreadArrays } from "tslib";
// import * as c from 'casual-browserify'
import { Chance } from 'chance';
import * as f from 'faker';
import * as R from 'randexp';
import { fnParser, loopInside } from './utils';
var c = require('casual-browserify');
var ch = new Chance();
import { __assign, __spreadArray } from "tslib";
import { loopInside, stringToPathOrCall } from './utils';
var Generator = /** @class */ (function () {
function Generator() {
}
Generator.prototype.faker = function (cfg) {
var faker = f;
var db = this.DB;
var object = this.object;
var re;
var matches;
var strFn;
if (cfg.locale === '') {
throw "Locale is empty \"" + cfg.locale + "\".";
}
if (cfg.locale) {
var supportedLocales = Object.keys(faker.locales);
if (supportedLocales.indexOf(cfg.locale) === -1) {
throw "Locale \"" + cfg.locale + "\" is not supported by faker.";
}
faker = require('faker/locale/' + cfg.locale);
}
if (cfg.eval) {
re = /(^[a-zA-Z.]*)/; // aZ.aZ
matches = re.exec(cfg.faker);
if (matches && matches.length === 2) {
strFn = 'faker.' + cfg.faker;
}
re = /\((.*?)\)/; // Match ()
matches = re.exec(cfg.faker);
if (!matches) {
strFn = 'faker.' + cfg.faker + '()';
}
return eval(strFn);
}
else {
return fnParser('faker', faker, cfg.faker);
}
};
Generator.prototype.chance = function (cfg) {
var chance = ch;
if (cfg.eval) {
var db = this.DB;
var object = this.object;
var re = /(^[a-zA-Z.]*)/; // aZ.aZ
var matches = re.exec(cfg.chance);
var strFn = void 0;
if (matches && matches.length === 2) {
strFn = 'chance.' + cfg.chance;
}
re = /\((.*?)\)/; // Match ()
matches = re.exec(cfg.chance);
if (!matches) {
strFn = 'chance.' + cfg.chance + '()';
}
return eval(strFn);
}
else {
return fnParser.call(chance, 'chance', chance, cfg.chance);
}
};
Generator.prototype.casual = function (cfg) {
var casual = c;
if (cfg.eval) {
var re = /(^[a-zA-Z.]*)/; // aZ.aZ
var matches = re.exec(cfg.casual);
var strFn = void 0;
if (matches && matches.length === 2) {
strFn = 'casual.' + cfg.casual;
}
return eval(strFn);
}
else {
return fnParser.call(casual, 'casual', casual, cfg.casual);
}
};
Generator.prototype.randexp = function (cfg) {
return new R(cfg.randexp).gen();
};
Generator.prototype.self = function (cfg) {

@@ -101,9 +21,23 @@ var object = this.object;

};
Generator.prototype.custom = function (cfg) {
var db = this.DB;
var object = this.object;
var re;
var matches;
var strFn;
var generator = cfg.generator;
if (cfg.run) {
return cfg.run(generator, cfg.input);
}
else if (cfg.eval) {
return eval('generator.' + cfg.input);
}
else {
return stringToPathOrCall.call(generator, 'generator', generator, cfg.input);
}
};
Generator.prototype.eval = function (cfg) {
var db = this.DB;
var object = this.object;
var faker = f;
var chance = ch;
var casual = c;
var randexp = R;
var generators = this.generators;
return eval(cfg.eval);

@@ -123,7 +57,4 @@ };

var db = this.DB;
var faker = f;
var chance = ch;
var casual = c;
var randexp = R;
return (_a = cfg.function).call.apply(_a, __spreadArrays([{ object: object, db: db, faker: faker, chance: chance, casual: casual, randexp: randexp }], args));
var generators = this.generators;
return (_a = cfg.function).call.apply(_a, __spreadArray([{ object: object, db: db, generators: generators }], args, false));
};

@@ -163,3 +94,3 @@ Generator.prototype.static = function (cfg) {

if (entity === null) {
throw "Can\u00B4t get unique data. Source \"" + cfg.hasOne + "\" has not enough data";
throw "Can\u00B4t get unique data. Source \"".concat(cfg.hasOne, "\" has not enough data");
}

@@ -196,5 +127,5 @@ }

return cfg.unique
? Array.from(new Array(amount)).reduce(function (acc, val) { return __spreadArrays(acc, [
? Array.from(new Array(amount)).reduce(function (acc, val) { return __spreadArray(__spreadArray([], acc, true), [
_this.hasOne(__assign(__assign({}, newCfg), { uniqueDB: acc }))
]); }, [])
], false); }, [])
: Array.from(new Array(amount)).map(function () { return _this.hasOne(newCfg); });

@@ -201,0 +132,0 @@ };

@@ -9,2 +9,3 @@ import { Schema } from './Schema';

this.options = {};
this.generators = {};
this.options = options;

@@ -17,2 +18,6 @@ this.DB = {};

};
Mocker.prototype.addGenerator = function (name, library, run) {
this.generators[name] = { library: library, run: run };
return this;
};
Mocker.prototype.schema = function (name, schema, options) {

@@ -32,6 +37,7 @@ this.schemas.push(new Schema(name, schema, options));

Mocker.prototype._buildSync = function () {
var _this = this;
this.schemas.reduce(function (acc, schema) {
var instances;
try {
instances = schema.build(acc);
instances = schema.build(_this.generators, acc);
}

@@ -38,0 +44,0 @@ catch (e) {

@@ -1,2 +0,2 @@

import { __extends, __spreadArrays } from "tslib";
import { __assign, __extends, __spreadArray } from "tslib";
import { Generator } from './Generator';

@@ -32,3 +32,3 @@ import { evalWithContextData, fieldArrayCalcLength, iamLastParent, isArray, isConditional, isObject } from './utils';

var keykey = k.split(',');
if (evalWithContextData(keykey[0], _this.object)) {
if (evalWithContextData(keykey[0], _this.object, _this.DB, _this.generators)) {
key = keykey[1];

@@ -38,3 +38,3 @@ }

if (key !== '') {
res[key] = _this.proccessLeaf(value);
res[key] = _this.proccessLeaf(value, key);
}

@@ -50,3 +50,4 @@ }

__extends(Schema, _super);
function Schema(name, cfg, options) {
function Schema(name, cfg, options, generators) {
if (generators === void 0) { generators = {}; }
var _this = _super.call(this) || this;

@@ -56,2 +57,3 @@ _this.schema = cfg;

_this.options = options;
_this.generators = generators;
// Temp fields

@@ -63,3 +65,3 @@ _this.DB = {};

}
Schema.prototype.proccessLeaf = function (field) {
Schema.prototype.proccessLeaf = function (field, fieldName) {
var _this = this;

@@ -73,11 +75,11 @@ if (isArray(field)) {

if (fieldConfig_1.concat) {
na = evalWithContextData(fieldConfig_1.concat, this.object, this.DB);
na = evalWithContextData(fieldConfig_1.concat, this.object, this.DB, this.generators);
// Strict Mode
na = fieldConfig_1.concatStrict
? __spreadArrays(Array.from(new Set(na))) : na;
? __spreadArray([], Array.from(new Set(na)), true) : na;
}
var length_1 = fieldArrayCalcLength(fieldConfig_1, na.length, this);
var length_1 = fieldArrayCalcLength(field.length > 1 ? fieldConfig_1.values : fieldConfig_1, na.length, this);
var array = Array.from(new Array(length_1)).reduce(function (acc, el, index) {
var self = acc.slice(0);
acc.push(_this.generateField(fieldConfig_1, index, length_1, self));
acc.push(_this.generateField(fieldName, fieldConfig_1, index, length_1, self));
return acc;

@@ -88,16 +90,14 @@ }, []);

else {
return this.generateField(field);
return this.generateField(fieldName, field);
}
};
Schema.prototype.generateField = function (cfg) {
Schema.prototype.generateField = function (fieldName, cfg) {
var _a, _b;
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
var result = {};
var generators = [
'faker',
'chance',
'casual',
'randexp',
var customGenerators = Object.keys(this.generators);
var ownedByMocker = [
'self',

@@ -112,2 +112,3 @@ 'db',

];
var generators = __spreadArray(__spreadArray([], ownedByMocker, true), customGenerators, true);
var keys = Object.keys(cfg);

@@ -121,3 +122,3 @@ var key = keys.reduce(function (acc, val) {

if (key === 'noKey' && !keys.includes('eval')) {
throw "Error: Cant find key, please check model and use one of this [" + generators.join(',') + "]";
throw "Error: Invalid or missing generator".concat(fieldName !== 'root' ? " on field ".concat(fieldName) : '', ". Please use one of this generators [").concat(generators.join(','), "], note that if your generator doesnt appear in the list maybe you forgot to add it.");
}

@@ -128,3 +129,10 @@ if (keys.includes('eval') && keys.length === 1) {

try {
result = this[key].apply(this, __spreadArrays([cfg], args));
result = customGenerators.includes(key)
? this.custom({
generator: (_a = this.generators[key]) === null || _a === void 0 ? void 0 : _a.library,
run: (_b = this.generators[key]) === null || _b === void 0 ? void 0 : _b.run,
input: cfg[key],
eval: cfg.eval
})
: this[key].apply(this, __spreadArray([__assign(__assign({}, cfg), { generators: this.generators })], args, false));
}

@@ -138,3 +146,3 @@ catch (e) {

if (iamLastParent(schema)) {
this.object = this.proccessLeaf(schema);
this.object = this.proccessLeaf(schema, 'root');
}

@@ -145,5 +153,7 @@ else {

};
Schema.prototype.build = function (db) {
Schema.prototype.build = function (generators, db) {
var _this = this;
if (generators === void 0) { generators = {}; }
if (db === void 0) { db = {}; }
this.generators = generators;
this.object = {};

@@ -186,3 +196,3 @@ this.DB = db ? db : {};

else {
throw "The field \"" + f_1 + "\" not exists.";
throw "The field \"".concat(f_1, "\" not exists.");
}

@@ -204,3 +214,3 @@ }

else {
throw "An string \"" + this.options + "\" is not recognized as a parameter.";
throw "An string \"".concat(this.options, "\" is not recognized as a parameter.");
}

@@ -207,0 +217,0 @@ return this.DB[this.name];

@@ -1,2 +0,2 @@

import { __generator, __spreadArrays, __values } from "tslib";
import { __generator, __spreadArray, __values } from "tslib";
export var isArray = function (arg) {

@@ -8,3 +8,3 @@ return Object.prototype.toString.call(arg) === '[object Array]';

};
export var evalWithContextData = function (key, object, db) {
export var evalWithContextData = function (key, object, db, generators) {
// In this (way, we can pass object and use inside the eval string

@@ -161,3 +161,3 @@ return eval(key);

};
export var fnParser = function (name, fn, cfg) {
export var stringToPathOrCall = function (name, fn, cfg) {
var _a = cfg.split('('), body = _a[0], args = _a[1];

@@ -167,3 +167,3 @@ body = body.split('.');

if (!acc[val]) {
throw "This " + name + " method doesnt exists '" + cfg + "'.";
throw "This ".concat(name, " method doesnt exists '").concat(cfg, "'.");
}

@@ -186,3 +186,3 @@ return acc[val];

: [];
var result = func.call.apply(func, __spreadArrays([this], args));
var result = func.call.apply(func, __spreadArray([this], args, false));
if (!mods || mods === '') {

@@ -198,3 +198,3 @@ return result;

if (!acc[val]) {
throw "'" + acc + "' doesnt have key '" + val + "'.";
throw "'".concat(acc, "' doesnt have key '").concat(val, "'.");
}

@@ -208,3 +208,3 @@ return acc[val];

if (acc[val] === null) {
throw "'" + acc + "' doesnt have key '" + val + "'.";
throw "'".concat(acc, "' doesnt have key '").concat(val, "'.");
}

@@ -211,0 +211,0 @@ return acc[val];

@@ -5,4 +5,14 @@ # Changelog

### [3.0.1](https://github.com/danibram/mocker-data-generator/compare/v3.0.0...v3.0.1) (2022-12-30)
## [3.0.0](https://github.com/danibram/mocker-data-generator/compare/v2.12.0...v3.0.0) (2022-12-30)
### Breaking changes!
- **generators:** Now mocker remove thirdparty generators from it. Now you should provide to the library, check the readme
- **string-parser:** Now to unify logic, and reduce complexity. The fast eval function not call the function. So if in the past with faker you use: `lorem.paragraph` now its important to use `lorem.paragraph()` because eval function is not doing more magic than the necesary
Thank you all for you patient, this release was planned maybe a year ago, but I didnt have time to work on it.
## [2.12.0](https://github.com/danibram/mocker-data-generator/compare/v2.10.0...v2.12.0) (2021-02-03)
### Features

@@ -9,0 +19,0 @@

{
"name": "mocker-data-generator",
"version": "2.12.0",
"version": "3.0.1",
"description": "A simplified way to generate mock data, builds using a simple schema and with the FakerJs",

@@ -60,2 +60,3 @@ "main": "build/main/index.js",

"release:minor": "standard-version --release-as minor",
"release:major": "standard-version --release-as major",
"release-github": "source .env.sh && conventional-github-releaser -p angular -r 1",

@@ -90,10 +91,11 @@ "prett": "prettier 'src/**/*.ts' --write",

"devDependencies": {
"@types/chance": "^1.1.1",
"@types/faker": "^5.1.6",
"@types/node": "^14.14.22",
"ava": "^3.15.0",
"codecov": "^3.8.1",
"ava": "^5.1.0",
"codecov": "^3.8.2",
"conventional-github-releaser": "^3.1.5",
"gh-pages": "^3.1.0",
"http-server": "^0.12.3",
"casual-browserify": "^1.5.19",
"chance": "^1.1.7",
"faker": "^5.3.1",
"randexp": "^0.5.3",
"gh-pages": "^4.0.0",
"http-server": "^14.1.1",
"multiview": "^3.0.1",

@@ -103,18 +105,13 @@ "npm-scripts-info": "^0.3.9",

"opn-cli": "^5.0.0",
"prettier": "^2.2.1",
"standard-version": "^9.1.0",
"trash-cli": "^4.0.0",
"ts-node": "^9.1.1",
"prettier": "^2.8.1",
"standard-version": "^9.5.0",
"trash-cli": "^5.0.0",
"ts-node": "^10.9.1",
"tslint": "^6.1.3",
"tslint-config-standard": "^9.0.0",
"typedoc": "^0.20.20",
"typescript": "^4.1.3"
"typedoc": "^0.23.23",
"typescript": "^4.9.4",
"tslib": "^2.4.1"
},
"dependencies": {
"casual-browserify": "^1.5.19",
"chance": "^1.1.7",
"faker": "^5.3.1",
"randexp": "^0.5.3",
"tslib": "^2.1.0"
},
"dependencies": {},
"nyc": {

@@ -121,0 +118,0 @@ "exclude": [

@@ -23,4 +23,4 @@ # mocker-data-generator [![Tweet](https://img.shields.io/twitter/url/http/shields.io.svg?style=social)](https://twitter.com/intent/tweet?text=Im%20testing%20mocker-data-generator%20is%20awesome!&via=danibram&url=http://bit.ly/2ziE8qT&hashtags=mock,javascript,developers)

Install the module with:
`npm install mocker-data-generator`
Install the module and the awesome generator you want:
`npm install mocker-data-generator faker`

@@ -30,7 +30,10 @@ Import it

```javascript
var mocker = require('mocker-data-generator').default (vainilla way)
var mocker = require('mocker-data-generator').default // (vanilla way)
var faker = require('faker')
or
import mocker from 'mocker-data-generator' (ES6 or Typescript way)
// or
import mocker from 'mocker-data-generator' // (ES6 or Typescript way)
import * as faker from 'faker'
```

@@ -43,15 +46,15 @@

firstName: {
faker: 'name.firstName'
faker: 'name.firstName()'
},
lastName: {
faker: 'name.lastName'
faker: 'name.lastName()'
},
country: {
faker: 'address.country'
faker: 'address.country()'
},
createdAt: {
faker: 'date.past'
faker: 'date.past()'
},
username: {
function: function() {
function: function () {
return (

@@ -67,8 +70,9 @@ this.object.lastName.substring(0, 5) +

description: {
faker: 'lorem.paragraph'
faker: 'lorem.paragraph()'
},
users: [
{
function: function() {
return this.faker.random.arrayElement(this.db.user).username
function: function () {
return this.generators.faker.random.arrayElement(this.db.user)
.username
},

@@ -85,6 +89,6 @@ length: 10,

'object.type=="HOUSE",location': {
faker: 'address.city'
faker: 'address.city()'
},
'object.type=="CAR"||object.type=="MOTORBIKE",speed': {
faker: 'random.number'
faker: 'random.number()'
}

@@ -96,6 +100,7 @@ }

mocker()
.addGenerator('faker', faker)
.schema('user', user, 2)
.schema('group', group, 2)
.schema('conditionalField', conditionalField, 2)
.build(function(error, data) {
.build(function (error, data) {
if (error) {

@@ -105,3 +110,3 @@ throw error

console.log(util.inspect(data, { depth: 10 }))
// This returns an object

@@ -118,2 +123,3 @@ // {

mocker()
.addGenerator('faker', faker)
.schema('user', user, 2)

@@ -145,2 +151,3 @@ .schema('group', group, 2)

var data = mocker()
.addGenerator('faker', faker)
.schema('user', user, 2)

@@ -153,2 +160,5 @@ .schema('group', group, 2)

```
NOTE:
For the demo above you will also need to import util i.e.
`var util = require('util') or import util from 'util'`

@@ -161,2 +171,8 @@ ## Documentation

* **_addGenerator(name, generator, runFn)_**: Add a new generator, now generators are not included in the package, so you have to add whathever generator you want.
* name (String): key of the generator this should match with the key in the schema.
* generator (library): Library if the generator
* runFN (function) (Optional) (generator: any, input: any) => any : It compose a exec function for the selected generator, only for custom generators, see randexp in the examples folder
* **_schema(name, schema, generationType)_**: Add a new schema, you must specify this params:

@@ -195,3 +211,3 @@

* **_eval_** (Optional): Also now you can pass, eval to true, to use like like in versions < 2.6.0
* **_eval_** (Optional): Also now you can pass, eval to true, to use like in versions < 2.6.0

@@ -203,3 +219,3 @@

} //will get the id of the generated entity
{

@@ -213,3 +229,3 @@ self: 'id',

* **_eval_** (Optional): Also now you can pass, fast to true, eval to true, to use like like in versions < 2.6.0
* **_eval_** (Optional): Also now you can pass, fast to true, eval to true, to use like in versions < 2.6.0

@@ -228,3 +244,3 @@

* **_eval_**: evaluate the current string, remember that i inject all the awesome methods, faker, chance, casual, randexp, and also the db and object methods. With this eval field, **_you must pass an exactly JSON syntax_**:
* **_eval_**: evaluate the current string, remember that all context are injected (generators, db the actual object). With this eval field, **_you must pass an exactly JSON syntax_**:

@@ -257,3 +273,3 @@ ```javascript

{
hasOne: 'user'
hasOne: 'user'
} // this populate the field with one random user

@@ -265,5 +281,6 @@

hasOne: 'user',
get: 'id'
get: 'id'
} // this populate the field with one id of a random user
// OR:

@@ -274,3 +291,3 @@

get: 'id',
eval: true
eval: true
} // this populate the field with one id of a random user with eval string

@@ -296,4 +313,4 @@ ```

// OR:
{

@@ -305,3 +322,3 @@ hasMany: 'user',

// OR:
{

@@ -313,4 +330,4 @@ hasMany: 'user',

// OR:
{

@@ -338,26 +355,22 @@ hasMany: 'user',

* **_funcion_**: No params are passed, only context (`this`), in this you have `{db, object, faker, chance}`, and you can use faker or chance functions, object (the specified model), db (actual data generated)
* **_function_**: No params are passed, only context (`this`), in this you have `{db, object, faker, chance}`, and you can use faker or chance functions, object (the specified model), db (actual data generated)
```javascript
{ function: function(){
// this.db
// this.object
// this.faker
// this.chance
// this.casual
// this.generators
return yourValue
} }
//OR:
// OR:
{ function(){
// this.db
// this.object
// this.faker
// this.chance
// this.casual
// this.generators
return yourValue

@@ -367,78 +380,2 @@ } }

* **_faker_**: you can use directly faker functions like: (note that, db (actual entities generated), object (actual entity generated) are injected), **_you must pass an exactly JSON syntax_**, now also the multilang is supported by the property locale (Thanks @sleicht for the inspiration. By default I take English locale. This are the locales supported: [https://github.com/marak/Faker.js/#localization](https://github.com/marak/Faker.js/#localization)).
* **_eval_** (Optional): You can use like in versions < 2.6.0, su with this true, it will turn faker field string into an evaluable string, also loosing speed
```javascript
{ faker: 'lorem.words' } // Run faker.lorem.words()
{ faker: 'lorem.words()' } // Run faker.lorem.words()
{ faker: 'lorem.words(1)' } // Run faker.lorem.words(1)
{ faker: 'integer({"min": 1, "max": 10})' } // Run faker.lorem.words(1) and take the first
{ faker: 'random.arrayElement(db.users)' } // Run faker.arrayElement over a generated user entity
{ faker: 'random.arrayElement(db.users)["userId"]' } // Run faker.arrayElement over a generated user entity and take the userId only
{ faker: 'address.streetAddress', locale: 'zh_CN' } // Got 711 蔡 街
{ faker: 'address.streetAddress' } // Got 5036 Daniel Village
{ faker: 'address.streetAddress', eval: true } // Got 5036 Daniel Village
```
* **_chance_**: you can use directly chance functions, you can do: (note that, db (actual entities generated), object (actual entity generated) are injected), **_you must pass an exactly JSON syntax_**:
* **_eval_** (Optional): You can use like in versions < 2.6.0, su with this true, it will turn chance field string into an evaluable string, also loosing speed
```javascript
{
chance: 'integer'
} // Run chance.integer()
{
chance: 'integer()'
} // Run chance.integer()
{
chance: 'integer({"min": 1, "max": 10})'
} // Run chance.integer({"min": 1, "max": 10})
{
chance: 'street_suffixes()[0]["name"]'
} // Run chance.street_suffixes() takes first result and the name inside
{
chance: 'street_suffixes()[0]["name"]',
eval: true
} // Run chance.street_suffixes() takes first result and the name inside
```
* **_casual_**: you can use directly use casualJs functions, you can do: (note that, db (actual entities generated), object (actual entity generated) are injected), **_you must pass an exactly JSON syntax_**:
* **_eval_** (Optional): You can use like in versions < 2.6.0, su with this true, it will turn casual field string into an evaluable string, also loosing speed
```javascript
{
casual: 'country'
}
{
chance: 'array_of_digits()'
}
{
casual: 'array_of_digits(3)[0]',
eval: true
}
{
casual: 'array_of_digits(3)[0]',
eval: true
}
```
* **_randexp_**: pass a regexp string to use randexp generator.
```javascript
{
randexp: /hello+ (world|to you)/
}
```
* **_[Array]_**: you can pass an array that indicates an array of data you can create, passing in the first field the generator (function, faker, or array(not Tested)), and in the second field pass a config object (length, fixedLentgh)

@@ -455,5 +392,5 @@

// Faker
[name of the generator injected]: 'path inside the generator'
// If faker is injected with .addGenerator('faker', faker) then you can use:
faker: 'random.arrayElement(db.users).userId'
// Chance
chance: 'integer'
// Function that has included index, length and self that refers at the actual array generation

@@ -472,2 +409,35 @@ function: function (index, length, self){ return /**/ }

### Custom generators
It happens!Mocker now is independant of the generators so I hope this will give you more freedom. This is an example that you can check on the examples folder, where 2 generators are used:
```javascript
var mocker = require('../build/main').default
var faker = require('faker')
var Randexp = require('randexp')
var util = require('util')
var user = {
firstName: {
faker: 'name.firstName()'
},
notes: {
randexp: /hello+ (world|to you)/
}
}
mocker()
.addGenerator('faker', faker)
.addGenerator('randexp', Randexp, function (generator, input) {
return new generator(input).gen()
})
.schema('user', user, 2)
.build(function (error, data) {
if (error) {
throw error
}
console.log(util.inspect(data, { depth: 10 }))
})
```
### Optional fields

@@ -481,5 +451,5 @@

// Faker
faker: 'random.arrayElement(db.users)[userId]'
// Chance
chance: 'integer'
[name of the generator injected]: 'path inside the generator'
// If faker is injected with .addGenerator('faker', faker) then you can use:
faker: 'random.arrayElement(db.users).userId'
// Static

@@ -502,2 +472,3 @@ static: 'any static field'

mocker()
.addGenerator('faker', faker)
.schema('user', user, 2)

@@ -530,2 +501,3 @@ .schema('group', group, 2)

var m = mocker()
.addGenerator('faker', faker)
.schema('cat', cat, 10)

@@ -545,2 +517,3 @@ .schema('cat2', cat, { uniqueField: 'name' })

var m = mocker()
.addGenerator('faker', faker)
.schema('cat', cat, 10)

@@ -594,3 +567,3 @@ .schema('cat2', cat, { uniqueField: 'name' })

Licensed under the MIT license. 2017
Licensed under the MIT license. 2022

@@ -597,0 +570,0 @@ [paypal-badge]: https://img.shields.io/badge/❤%20support-paypal-blue.svg?style=flat-square

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet