valgen 3.2.0 → 4.0.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +12 -7
  3. package/cjs/core/constants.js +5 -0
  4. package/cjs/core/context.js +65 -0
  5. package/cjs/core/index.js +21 -0
  6. package/cjs/core/types.js +2 -0
  7. package/cjs/core/validation-error.js +11 -0
  8. package/cjs/core/validator.js +61 -0
  9. package/cjs/helpers/object.utils.js +19 -0
  10. package/cjs/helpers/string.utils.js +9 -0
  11. package/cjs/index.js +18 -0
  12. package/cjs/package.json +3 -0
  13. package/cjs/rules/index.js +38 -0
  14. package/cjs/rules/is-any.js +12 -0
  15. package/cjs/rules/is-array.js +38 -0
  16. package/cjs/rules/is-boolean.js +30 -0
  17. package/cjs/rules/is-date.js +63 -0
  18. package/cjs/rules/is-empty.js +68 -0
  19. package/cjs/rules/is-enum.js +30 -0
  20. package/cjs/rules/is-integer.js +26 -0
  21. package/cjs/rules/is-matches.js +24 -0
  22. package/cjs/rules/is-null.js +40 -0
  23. package/cjs/rules/is-number.js +26 -0
  24. package/cjs/rules/is-object-id.js +28 -0
  25. package/cjs/rules/is-object.js +103 -0
  26. package/cjs/rules/is-record.js +41 -0
  27. package/cjs/rules/is-string.js +79 -0
  28. package/cjs/rules/is-tuple.js +32 -0
  29. package/cjs/rules/length.js +41 -0
  30. package/cjs/rules/optional.js +44 -0
  31. package/cjs/rules/pipe.js +43 -0
  32. package/cjs/rules/range.js +89 -0
  33. package/cjs/rules/string-formats.js +296 -0
  34. package/cjs/rules/union.js +31 -0
  35. package/cjs/rules/utilities.js +31 -0
  36. package/esm/core/constants.js +2 -0
  37. package/esm/core/context.js +61 -0
  38. package/esm/core/index.js +5 -0
  39. package/esm/core/types.js +1 -0
  40. package/esm/core/validation-error.js +7 -0
  41. package/esm/core/validator.js +56 -0
  42. package/esm/helpers/object.utils.js +14 -0
  43. package/esm/helpers/string.utils.js +5 -0
  44. package/esm/index.js +2 -0
  45. package/esm/rules/index.js +22 -0
  46. package/esm/rules/is-any.js +8 -0
  47. package/esm/rules/is-array.js +34 -0
  48. package/esm/rules/is-boolean.js +26 -0
  49. package/esm/rules/is-date.js +55 -0
  50. package/esm/rules/is-empty.js +63 -0
  51. package/esm/rules/is-enum.js +26 -0
  52. package/esm/rules/is-integer.js +22 -0
  53. package/esm/rules/is-matches.js +20 -0
  54. package/esm/rules/is-null.js +34 -0
  55. package/esm/rules/is-number.js +22 -0
  56. package/esm/rules/is-object-id.js +21 -0
  57. package/esm/rules/is-object.js +99 -0
  58. package/esm/rules/is-record.js +37 -0
  59. package/esm/rules/is-string.js +70 -0
  60. package/esm/rules/is-tuple.js +28 -0
  61. package/esm/rules/length.js +35 -0
  62. package/esm/rules/optional.js +38 -0
  63. package/esm/rules/pipe.js +38 -0
  64. package/esm/rules/range.js +81 -0
  65. package/esm/rules/string-formats.js +266 -0
  66. package/esm/rules/union.js +27 -0
  67. package/esm/rules/utilities.js +26 -0
  68. package/package.json +33 -37
  69. package/typings/core/constants.d.ts +2 -0
  70. package/typings/core/context.d.ts +26 -0
  71. package/typings/core/index.d.ts +6 -0
  72. package/typings/core/types.d.ts +18 -0
  73. package/typings/core/validation-error.d.ts +5 -0
  74. package/typings/core/validator.d.ts +18 -0
  75. package/typings/helpers/object.utils.d.ts +2 -0
  76. package/typings/helpers/string.utils.d.ts +1 -0
  77. package/typings/index.d.ts +2 -0
  78. package/typings/rules/index.d.ts +22 -0
  79. package/typings/rules/is-any.d.ts +5 -0
  80. package/typings/rules/is-array.d.ts +7 -0
  81. package/typings/rules/is-boolean.d.ts +7 -0
  82. package/typings/rules/is-date.d.ts +19 -0
  83. package/typings/rules/is-empty.d.ts +13 -0
  84. package/typings/rules/is-enum.d.ts +9 -0
  85. package/typings/rules/is-integer.d.ts +7 -0
  86. package/typings/rules/is-matches.d.ts +9 -0
  87. package/typings/rules/is-null.d.ts +16 -0
  88. package/typings/rules/is-number.d.ts +7 -0
  89. package/typings/rules/is-object-id.d.ts +10 -0
  90. package/typings/rules/is-object.d.ts +22 -0
  91. package/typings/rules/is-record.d.ts +7 -0
  92. package/typings/rules/is-string.d.ts +42 -0
  93. package/typings/rules/is-tuple.d.ts +27 -0
  94. package/typings/rules/length.d.ts +21 -0
  95. package/typings/rules/optional.d.ts +17 -0
  96. package/typings/rules/pipe.d.ts +11 -0
  97. package/typings/rules/range.d.ts +48 -0
  98. package/typings/rules/string-formats.d.ts +140 -0
  99. package/typings/rules/union.d.ts +5 -0
  100. package/typings/rules/utilities.d.ts +11 -0
  101. package/lib/ArrayType.d.ts +0 -5
  102. package/lib/ArrayType.js +0 -43
  103. package/lib/DataType.d.ts +0 -25
  104. package/lib/DataType.js +0 -214
  105. package/lib/ObjectType.d.ts +0 -5
  106. package/lib/ObjectType.js +0 -78
  107. package/lib/SchemaError.d.ts +0 -3
  108. package/lib/SchemaError.js +0 -17
  109. package/lib/UnionType.d.ts +0 -5
  110. package/lib/UnionType.js +0 -54
  111. package/lib/Valgen.d.ts +0 -88
  112. package/lib/Valgen.js +0 -289
  113. package/lib/ValidationError.d.ts +0 -2
  114. package/lib/ValidationError.js +0 -4
  115. package/lib/factories/AnyFactory.d.ts +0 -28
  116. package/lib/factories/AnyFactory.js +0 -73
  117. package/lib/factories/ArrayFactory.d.ts +0 -16
  118. package/lib/factories/ArrayFactory.js +0 -148
  119. package/lib/factories/Base64Factory.d.ts +0 -12
  120. package/lib/factories/Base64Factory.js +0 -31
  121. package/lib/factories/BooleanFactory.d.ts +0 -12
  122. package/lib/factories/BooleanFactory.js +0 -49
  123. package/lib/factories/DateFactory.d.ts +0 -40
  124. package/lib/factories/DateFactory.js +0 -239
  125. package/lib/factories/FunctionFactory.d.ts +0 -12
  126. package/lib/factories/FunctionFactory.js +0 -28
  127. package/lib/factories/IntegerFactory.d.ts +0 -14
  128. package/lib/factories/IntegerFactory.js +0 -33
  129. package/lib/factories/NilFactory.d.ts +0 -4
  130. package/lib/factories/NilFactory.js +0 -20
  131. package/lib/factories/NumberFactory.d.ts +0 -36
  132. package/lib/factories/NumberFactory.js +0 -178
  133. package/lib/factories/ObjectFactory.d.ts +0 -38
  134. package/lib/factories/ObjectFactory.js +0 -326
  135. package/lib/factories/StringFactory.d.ts +0 -16
  136. package/lib/factories/StringFactory.js +0 -94
  137. package/lib/factories/UnionFactory.d.ts +0 -13
  138. package/lib/factories/UnionFactory.js +0 -62
  139. package/lib/index.d.ts +0 -19
  140. package/lib/index.js +0 -37
package/lib/ObjectType.js DELETED
@@ -1,78 +0,0 @@
1
- 'use strict';
2
-
3
- const {DataType} = require('./DataType');
4
-
5
- const PROPERTY_NAME_PATTERN = /^([^?!]+)([?|!])?$/;
6
- const REQUIRED_PROPERTY_PATTERN = /^([^?!]+)([?|!])?$/;
7
-
8
- /**
9
- *
10
- * @class ObjectType
11
- */
12
- class ObjectType extends DataType {
13
-
14
- create(instance, schema) {
15
- instance = super.create(instance, schema);
16
- if (schema.properties) {
17
- instance.properties = {};
18
- const library = this.library;
19
- const stack = library._stack;
20
- stack.push('properties');
21
- for (const [k, p] of Object.entries(schema.properties)) {
22
- const m = k.match(REQUIRED_PROPERTY_PATTERN);
23
- stack.push(m[1]);
24
- const sch = library.normalizeSchema(p);
25
- const t = library.getType(sch);
26
- t.propertyName = m[1];
27
- if (m[2] === '!')
28
- t.required = true;
29
- else if (m[2] === '?')
30
- t.required = false;
31
- else if (typeof p === 'object' && p.required != null)
32
- t.required = p.required;
33
- if (typeof t.required === 'string')
34
- t.required = t.required.split(/\s*,\s*/);
35
- instance.properties[m[1]] = t;
36
- }
37
- stack.pop();
38
- }
39
- return instance;
40
- }
41
-
42
- get(attr) {
43
- if (attr.startsWith('properties.') && this.properties) {
44
- const p = this.properties[attr.substring(11)];
45
- if (p)
46
- return p;
47
- }
48
- return super.get(attr);
49
- }
50
-
51
- normalizeSchema(schema) {
52
- const normalized = super.normalizeSchema(schema);
53
- const properties = normalized.properties;
54
- if (properties) {
55
- const stack = this.library._stack;
56
- stack.push('properties');
57
- normalized.properties = {};
58
- for (const [k, sch] of Object.entries(properties)) {
59
- const m = k.match(PROPERTY_NAME_PATTERN);
60
- stack.push(k);
61
- const v = this.library.normalizeSchema(sch);
62
- if (v !== undefined) {
63
- normalized.properties[m[1]] = v;
64
- if (m[2] === '!')
65
- v.required = true;
66
- if (m[2] === '?')
67
- v.required = false;
68
- }
69
- stack.pop();
70
- }
71
- stack.pop();
72
- }
73
- return normalized;
74
- }
75
-
76
- }
77
-
78
- module.exports = {ObjectType};
@@ -1,3 +0,0 @@
1
- export class SchemaError extends Error {
2
- constructor(msg: string | Error, schemaStack: string[]);
3
- }
@@ -1,17 +0,0 @@
1
- class SchemaError extends Error {
2
- constructor(msg, schemaStack) {
3
- super(
4
- (schemaStack ? 'Schema error at ' + schemaStack.join('.') + '. ' :
5
- /* istanbul ignore next */ '') +
6
- (msg instanceof Error ? msg.message :
7
- /* istanbul ignore next */ msg));
8
- /* istanbul ignore else */
9
- if (schemaStack)
10
- this.schemaStack = schemaStack;
11
- /* istanbul ignore else */
12
- if (msg instanceof Error)
13
- this.stack = msg.stack;
14
- }
15
- }
16
-
17
- module.exports = {SchemaError};
@@ -1,5 +0,0 @@
1
- import {DataType} from './DataType';
2
-
3
- export class UnionType extends DataType {
4
- anyOf?: DataType[];
5
- }
package/lib/UnionType.js DELETED
@@ -1,54 +0,0 @@
1
- 'use strict';
2
- const merge = require('putil-merge');
3
- const {DataType} = require('./DataType');
4
-
5
- /**
6
- *
7
- * @class UnionType
8
- */
9
- class UnionType extends DataType {
10
-
11
- create(instance, schema) {
12
- instance = super.create(instance, schema);
13
- const library = this.library;
14
- const stack = library._stack;
15
- stack.push('anyOf');
16
-
17
- const additionalAttributes = merge({}, schema, {
18
- filter: (o, n) => !['name', 'type', 'anyOf'].includes(n)
19
- });
20
- const hasAdditionalAttributes = Object.keys(additionalAttributes).length;
21
- instance.anyOf = schema.anyOf.map(x => {
22
- if (hasAdditionalAttributes) {
23
- const sch = typeof x === 'string' ?
24
- {type: x, ...additionalAttributes} : {...x, ...additionalAttributes};
25
- return library.getType(sch);
26
- }
27
- return library.getType(x);
28
- });
29
-
30
- stack.pop();
31
- return instance;
32
- }
33
-
34
- get(attr) {
35
- if (attr === 'anyOf' && this.anyOf)
36
- return this.anyOf;
37
- return super.get(attr);
38
- }
39
-
40
- normalizeSchema(schema) {
41
- const normalized = super.normalizeSchema(schema);
42
- const items = normalized.items;
43
- if (items) {
44
- const stack = this.library._stack;
45
- stack.push('items');
46
- normalized.items = this.library.normalizeSchema(items);
47
- stack.pop();
48
- }
49
- return normalized;
50
- }
51
-
52
- }
53
-
54
- module.exports = {UnionType};
package/lib/Valgen.d.ts DELETED
@@ -1,88 +0,0 @@
1
- import {DataType} from "./DataType";
2
-
3
- export namespace Valgen {
4
- export type TypeSchemaDef = string | ITypeSchema;
5
- export type TypeLookupMethod = (typeName: string) => TypeSchemaDef;
6
-
7
- export interface ITypeSchema {
8
- type: string;
9
-
10
- [key: string]: any;
11
- }
12
-
13
- export interface ITypeFactory {
14
- generate: (base: DataType, options?: IGenerateOptions) => ValidateFunction;
15
- }
16
-
17
- export interface IGenerateOptions {
18
- resolvePromises?: boolean;
19
- strictFormat?: boolean;
20
- coerceTypes?: boolean;
21
- convertDates?: boolean;
22
- throwOnError?: boolean
23
- maxArrayErrors?: number;
24
- maxObjectErrors?: number;
25
- removeAdditional?: boolean | 'all';
26
- removeNull?: boolean;
27
- operation?: string; // 'get' | 'create' | 'update' | 'patch' | 'delete'
28
- }
29
-
30
- export type ValidateFunction = (value: any) => IValidationResult;
31
-
32
- export interface IValidationResult {
33
- valid: boolean;
34
- value?: any;
35
- errors?: IValidationError[];
36
- }
37
-
38
- export interface IValidationError {
39
- message: string;
40
- errorType?: string;
41
- path?: string;
42
-
43
- [index: string]: any;
44
- }
45
-
46
- export interface IOptions {
47
- defaultType?: string;
48
- throwOnError?: boolean;
49
- schemaLookup?: TypeLookupMethod;
50
- }
51
- }
52
-
53
- export class Valgen implements Valgen.IOptions {
54
- protected _instances: { [name: string]: DataType };
55
- protected _lookupSchemas: { [name: string]: Valgen.ITypeSchema };
56
- protected _stacks: string[][];
57
- private _idSeq: number;
58
- defaultType: string;
59
- baseTypes: { [name: string]: DataType };
60
- schemaLookup?: Valgen.TypeLookupMethod;
61
- schemas: { [index: string]: Valgen.TypeSchemaDef };
62
- throwOnError?: boolean;
63
-
64
- constructor(options?: Valgen.IOptions);
65
-
66
- addSchema(name: string, schema: Valgen.TypeSchemaDef);
67
-
68
- clearCache();
69
-
70
- generate(schema: Valgen.TypeSchemaDef, options?: Valgen.IGenerateOptions): Valgen.ValidateFunction;
71
-
72
- define(name: string, factory: Valgen.ITypeFactory): DataType;
73
-
74
- normalizeSchema(schema: Valgen.TypeSchemaDef): Valgen.ITypeSchema;
75
-
76
- getType(name: Valgen.TypeSchemaDef): DataType;
77
-
78
- setOption(key: string, value: any): void;
79
-
80
- protected _lookupForSchema(name: string): Valgen.TypeSchemaDef;
81
-
82
- protected _getBaseTypeName(schema: Valgen.TypeSchemaDef): string;
83
-
84
- protected _parseTypeName(v: string): Valgen.TypeSchemaDef;
85
-
86
- protected get _stack(): string[];
87
-
88
- }
package/lib/Valgen.js DELETED
@@ -1,289 +0,0 @@
1
- const {DataType} = require('./DataType');
2
- const {ObjectType} = require('./ObjectType');
3
- const {ArrayType} = require('./ArrayType');
4
- const {UnionType} = require('./UnionType');
5
- const {AnyFactory} = require('./factories/AnyFactory');
6
- const {BooleanFactory} = require('./factories/BooleanFactory');
7
- const {NumberFactory} = require('./factories/NumberFactory');
8
- const {IntegerFactory} = require('./factories/IntegerFactory');
9
- const {StringFactory} = require('./factories/StringFactory');
10
- const {ArrayFactory} = require('./factories/ArrayFactory');
11
- const {ObjectFactory} = require('./factories/ObjectFactory');
12
- const {UnionFactory} = require('./factories/UnionFactory');
13
- const {DateFactory} = require('./factories/DateFactory');
14
- const {NilFactory} = require('./factories/NilFactory');
15
- const {FunctionFactory} = require('./factories/FunctionFactory');
16
- const {Base64Factory} = require('./factories/Base64Factory');
17
- const {SchemaError} = require('./SchemaError');
18
-
19
- const SQUARE_BRACKETS_PATTERN = /^\[([^\]]+)]$/;
20
-
21
- class Valgen {
22
-
23
- constructor(options = {}) {
24
- this._instances = {};
25
- this._lookupSchemas = {};
26
- this._stacks = [];
27
- this._idSeq = 0;
28
- this.baseTypes = {};
29
- this.defaultType = options.defaultType;
30
- this.schemaLookup = options.schemaLookup;
31
- this.schemas = {};
32
- this.throwOnError = options.throwOnError;
33
- this.baseTypes.object = new ObjectType(this, 'object', new ObjectFactory());
34
- this.baseTypes.array = new ArrayType(this, 'array', new ArrayFactory());
35
- this.baseTypes.union = new UnionType(this, 'union', new UnionFactory());
36
- this.define('any', new AnyFactory());
37
- this.define('boolean', new BooleanFactory());
38
- this.define('number', new NumberFactory());
39
- this.define('string', new StringFactory());
40
- this.define('integer', new IntegerFactory());
41
- this.define('nil', new NilFactory());
42
- this.define('function', new FunctionFactory());
43
- this.define('base64', new Base64Factory());
44
- this.define('datetime', new DateFactory({
45
- dateFormats: {},
46
- format: 'datetime'
47
- }));
48
- this.define('date', new DateFactory({
49
- dateFormats: {},
50
- format: 'date'
51
- }));
52
- this.define('time', new DateFactory({
53
- dateFormats: {},
54
- format: 'time'
55
- }));
56
- }
57
-
58
- addSchema(name, schema) {
59
- if (arguments.length <= 1) {
60
- if (typeof name !== 'object')
61
- throw new TypeError(`You must provide object instance as first argument.`);
62
- schema = name;
63
- name = schema.name;
64
- } else if (typeof schema === 'string')
65
- schema = this._parseTypeName(schema);
66
- else {
67
- if (typeof schema !== 'object')
68
- throw new TypeError(`Second argument must be an object or string.`);
69
- schema = {...schema, name};
70
- }
71
-
72
- if (!(name && typeof name === 'string'))
73
- throw new Error('You must provide type name');
74
-
75
- if (this.schemas[schema.name])
76
- throw new Error(`Schema "${schema.name}" already defined.`);
77
-
78
- this.schemas[name] = schema;
79
- }
80
-
81
- clearCache() {
82
- this._instances = {};
83
- this._lookupSchemas = {};
84
- Object.keys(this.baseTypes).forEach(k => this.baseTypes[k]._fnCache = {});
85
- }
86
-
87
- define(typeName, factory) {
88
- if (!factory)
89
- delete this.baseTypes[typeName];
90
- return this.baseTypes[typeName] = new DataType(this, typeName, factory);
91
- }
92
-
93
- generate(schema, options = {}) {
94
- return this.getType(schema)
95
- .generate(options);
96
- }
97
-
98
- normalizeSchema(schema) {
99
- const baseTypeName = this._getBaseTypeName(schema);
100
- const baseType = this.baseTypes[baseTypeName];
101
- if (!baseType)
102
- throw new Error(`Unable to determine base type.`);
103
-
104
- if (typeof schema === 'string') {
105
- schema = this._parseTypeName(schema);
106
- } else schema = {...schema};
107
-
108
- if (typeof schema === 'string')
109
- schema = {type: schema};
110
- else {
111
- if (schema.type) {
112
- if (Array.isArray(schema.type)) {
113
- schema.type = schema.type.map(t => {
114
- if (typeof t === 'string')
115
- return this._parseTypeName(t);
116
- return this.normalizeSchema(t);
117
- });
118
- if (schema.type.length <= 1)
119
- schema.type = schema.type[0];
120
- } else {
121
- const x = this.normalizeSchema(schema.type);
122
- if (x !== schema.type) {
123
- Object.assign(schema, x);
124
- }
125
- }
126
- }
127
- if (!schema.type)
128
- schema.type = baseTypeName;
129
- }
130
-
131
- return baseType.normalizeSchema(schema);
132
- }
133
-
134
- getType(schemaOrName) {
135
- if (!schemaOrName)
136
- throw new TypeError('Invalid argument');
137
-
138
- if (schemaOrName instanceof DataType)
139
- return schemaOrName;
140
-
141
- let name;
142
- let cacheId;
143
- let schema;
144
- let baseType;
145
- if (typeof schemaOrName === 'string') {
146
- schema = this._parseTypeName(schemaOrName);
147
- if (typeof schema === 'string') {
148
- name = schema;
149
- // Return previously cached type
150
- const t = this._instances[name];
151
- if (t) return t;
152
-
153
- // Check if it is an internal type
154
- baseType = this.baseTypes[name];
155
- if (!baseType) {
156
- // Lookup for schema by name
157
- schema = this.schemas[name] || this._lookupForSchema(name);
158
- if (!schema || schema === name)
159
- throw new TypeError(`Unknown type schema "${name}"`);
160
- if (typeof schema === 'string')
161
- schema = {name, type: schema};
162
- }
163
-
164
- } else
165
- name = schema.name;
166
- cacheId = name;
167
- } else {
168
- schema = schemaOrName;
169
- name = schema.name;
170
- }
171
-
172
- const stack = [name || '(anonymous)'];
173
- this._stacks.push(stack);
174
- try {
175
- if (!baseType) {
176
- const baseTypeName = this._getBaseTypeName(schema);
177
- baseType = this.baseTypes[baseTypeName];
178
- }
179
- const instance = {id: ++this._idSeq, name};
180
- if (cacheId)
181
- this._instances[cacheId] = instance;
182
- baseType.create(instance, schema);
183
- if (baseType.factory.create)
184
- baseType.factory.create(instance);
185
- return instance;
186
- } catch (e) {
187
- delete this._instances[name];
188
- if (e instanceof SchemaError)
189
- throw e;
190
- throw new SchemaError(e, stack);
191
- } finally {
192
- this._stacks.pop();
193
- }
194
- }
195
-
196
- setOption(key, v) {
197
- const m = key.match(/^([^.]+)(?:\.(.+))?$/);
198
- if (m) {
199
- const t = this.baseTypes[m[1]];
200
- if (!t)
201
- return;
202
- if (v === undefined)
203
- delete t.options[m[2]];
204
- else
205
- t.options[m[2]] = v;
206
- }
207
- }
208
-
209
- _lookupForSchema(name) {
210
- let schema = this.schemas[name] || this._lookupSchemas[name];
211
- if (schema)
212
- return schema;
213
- schema = this.schemaLookup && this.schemaLookup(name);
214
- if (schema)
215
- return this._lookupSchemas[name] = schema;
216
- }
217
-
218
- _getBaseTypeName(schema) {
219
- const stack = [];
220
- const getTypeName = (schema) => {
221
- if (typeof schema === 'string')
222
- schema = this._parseTypeName(schema);
223
-
224
- if (typeof schema === 'string') {
225
- if (stack.includes(schema))
226
- throw new Error('Circular reference detected');
227
- const t = this.baseTypes[schema] || this._instances[schema];
228
- if (t)
229
- return t.typeName;
230
- const sch = this._lookupForSchema(schema);
231
- if (!sch || sch === schema)
232
- throw new Error(`Unknown type "${schema}"`);
233
- stack.push(schema);
234
- return getTypeName(sch);
235
- }
236
- let h = (Array.isArray(schema.type) ? schema.type[0] : schema.type);
237
- if (!h) {
238
- if (schema.items)
239
- h = 'array';
240
- else if (schema.properties)
241
- h = 'object';
242
- else if (schema.anyOf)
243
- h = 'union';
244
- else h = this.defaultType || 'any';
245
- }
246
- return getTypeName(h);
247
- };
248
- return getTypeName(schema);
249
- }
250
-
251
- _parseTypeName(v) {
252
- let m = v.match(SQUARE_BRACKETS_PATTERN);
253
- if (m)
254
- v = m[1];
255
- if (v.includes(',')) {
256
- return {
257
- type: v.split(/\s*,\s*/).map(x => this._parseTypeName(x))
258
- };
259
- }
260
- if (v.includes('|')) {
261
- return {
262
- type: 'union',
263
- anyOf: v.split(/\s*\|\s*/).map(x => this._parseTypeName(x))
264
- };
265
- }
266
- if (v.endsWith('[]')) {
267
- const n = this._parseTypeName(v.substring(0, v.length - 2));
268
- return {
269
- type: 'array',
270
- items: n
271
- };
272
- }
273
- if (v.endsWith('{}')) {
274
- const n = this._parseTypeName(v.substring(0, v.length - 2));
275
- return {
276
- type: 'object',
277
- additionalProperties: n
278
- };
279
- }
280
- return v;
281
- }
282
-
283
- get _stack() {
284
- return this._stacks[this._stacks.length - 1];
285
- }
286
-
287
- }
288
-
289
- module.exports = {Valgen};
@@ -1,2 +0,0 @@
1
- export class ValidationError extends Error {
2
- }
@@ -1,4 +0,0 @@
1
- class ValidationError extends Error {
2
- }
3
-
4
- module.exports = ValidationError;
@@ -1,28 +0,0 @@
1
- import {Valgen} from "../Valgen";
2
- import {DataType} from "../DataType";
3
-
4
- export namespace AnyFactory {
5
- export interface FunctionData {
6
- code: string;
7
- variables?: {
8
- [index: string]: any;
9
- };
10
- }
11
- export interface TypeSchema extends Valgen.ITypeSchema {
12
- default?: any;
13
- }
14
- }
15
-
16
- export class AnyFactory implements Valgen.ITypeFactory {
17
-
18
- schema: AnyFactory.TypeSchema;
19
- options: any;
20
-
21
- generate(type: DataType, options?: Valgen.IGenerateOptions): Valgen.ValidateFunction;
22
-
23
- normalizeAttribute: (attr: string, value: any) => any;
24
-
25
- normalizeCompileOptions(options?: Valgen.IGenerateOptions): Valgen.IGenerateOptions;
26
-
27
- protected _generateValidationCode(dataType: DataType, options: Valgen.IGenerateOptions): AnyFactory.FunctionData;
28
- }
@@ -1,73 +0,0 @@
1
- 'use strict';
2
-
3
- const {coerceToBoolean, coerceToString} = require('putil-varhelpers');
4
-
5
- const Failed = Symbol.for('Failed');
6
-
7
- /**
8
- *
9
- * @class AnyFactory
10
- */
11
- class AnyFactory {
12
-
13
- normalizeCompileOptions(options) {
14
- return {
15
- displayName: coerceToString(options.displayName),
16
- resolvePromises: coerceToBoolean(options.resolvePromises),
17
- throwOnError: coerceToBoolean(options.throwOnError)
18
- };
19
- }
20
-
21
- normalizeAttribute(attr, v) {
22
- switch (attr) {
23
- case 'default':
24
- return v;
25
- }
26
- }
27
-
28
- generate(dataType, options) {
29
- const defaultValue = dataType.get('default');
30
- const varNames = ['dataType', 'Failed', 'defaultValue'];
31
- const varValues = [dataType, Failed, defaultValue];
32
- const o = this._generateValidationCode(dataType, options);
33
- /* istanbul ignore else */
34
- if (o.variables)
35
- for (const n of Object.keys(o.variables)) {
36
- varNames.push(n);
37
- varValues.push(o.variables[n]);
38
- }
39
- const code = `return (value, ctx) => {
40
- ${defaultValue !== undefined ?
41
- 'if (value == null) value = defaultValue;' : ''}
42
- ${o.code}
43
- return value;
44
- }`;
45
- return new Function(...varNames, code)(...varValues);
46
- }
47
-
48
- _generateValidationCode(dataType, options) {
49
- const data = {code: '', variables: {}};
50
- data.variables.name = options.displayName || dataType.name;
51
-
52
- data.code += `
53
- if (value == null) return value;
54
- const typeCheck = ctx && ctx.typeCheck;
55
- `;
56
-
57
- const enumValues = dataType.get('enum');
58
- if (enumValues) {
59
- data.variables.enums = new Set(enumValues);
60
- data.code += `
61
- if (!enums.has(value))
62
- return typeCheck ? Failed : ctx.logError({
63
- message: 'Value must be a one of the enumerated values.',
64
- errorType: 'invalid-enum-value'
65
- });`;
66
- }
67
-
68
- return data;
69
- }
70
-
71
- }
72
-
73
- module.exports = {AnyFactory};
@@ -1,16 +0,0 @@
1
- import {AnyFactory} from './AnyFactory';
2
- import {Valgen} from '../Valgen';
3
-
4
- export namespace ArrayFactory {
5
- export interface ITypeSchema extends Valgen.ITypeSchema {
6
- default?: any[];
7
- items?: string | Valgen.ITypeSchema;
8
- minItems?: number;
9
- maxItems?: number;
10
- }
11
- }
12
-
13
-
14
- export class ArrayFactory extends AnyFactory {
15
- schema: ArrayFactory.ITypeSchema;
16
- }