@decaf-ts/decorator-validation 1.5.5 → 1.5.7

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 (130) hide show
  1. package/dist/decorator-validation.js +1 -1
  2. package/dist/esm/decorator-validation.js +1 -1
  3. package/lib/esm/index.d.ts +1 -1
  4. package/lib/esm/index.js +1 -3
  5. package/lib/esm/model/Model.js +0 -2
  6. package/lib/esm/model/ModelErrorDefinition.js +0 -2
  7. package/lib/esm/model/Registry.js +0 -2
  8. package/lib/esm/model/constants.js +0 -2
  9. package/lib/esm/model/construction.js +0 -2
  10. package/lib/esm/model/decorators.js +0 -2
  11. package/lib/esm/model/index.js +0 -2
  12. package/lib/esm/model/types.js +0 -2
  13. package/lib/esm/model/utils.js +0 -2
  14. package/lib/esm/model/validation.js +0 -2
  15. package/lib/esm/utils/constants.js +0 -2
  16. package/lib/esm/utils/dates.js +0 -2
  17. package/lib/esm/utils/decorators.js +0 -2
  18. package/lib/esm/utils/hashing.js +0 -2
  19. package/lib/esm/utils/index.js +0 -2
  20. package/lib/esm/utils/registry.js +0 -2
  21. package/lib/esm/utils/serialization.js +0 -2
  22. package/lib/esm/utils/strings.js +0 -2
  23. package/lib/esm/validation/Validation.js +0 -2
  24. package/lib/esm/validation/Validators/DateValidator.js +0 -2
  25. package/lib/esm/validation/Validators/EmailValidator.js +0 -2
  26. package/lib/esm/validation/Validators/ListValidator.js +0 -2
  27. package/lib/esm/validation/Validators/MaxLengthValidator.js +0 -2
  28. package/lib/esm/validation/Validators/MaxValidator.js +0 -2
  29. package/lib/esm/validation/Validators/MinLengthValidator.js +0 -2
  30. package/lib/esm/validation/Validators/MinValidator.js +0 -2
  31. package/lib/esm/validation/Validators/PasswordValidator.js +0 -2
  32. package/lib/esm/validation/Validators/PatternValidator.js +0 -2
  33. package/lib/esm/validation/Validators/RequiredValidator.js +0 -2
  34. package/lib/esm/validation/Validators/StepValidator.js +0 -2
  35. package/lib/esm/validation/Validators/TypeValidator.js +0 -2
  36. package/lib/esm/validation/Validators/URLValidator.js +0 -2
  37. package/lib/esm/validation/Validators/Validator.js +0 -2
  38. package/lib/esm/validation/Validators/ValidatorRegistry.js +0 -2
  39. package/lib/esm/validation/Validators/constants.js +0 -2
  40. package/lib/esm/validation/Validators/decorators.js +0 -2
  41. package/lib/esm/validation/Validators/index.js +0 -2
  42. package/lib/esm/validation/Validators/types.js +0 -2
  43. package/lib/esm/validation/decorators.js +0 -2
  44. package/lib/esm/validation/index.js +0 -2
  45. package/lib/esm/validation/types.js +0 -2
  46. package/lib/index.d.ts +1 -1
  47. package/lib/index.js +59 -0
  48. package/lib/model/Model.js +300 -0
  49. package/lib/model/ModelErrorDefinition.js +56 -0
  50. package/lib/model/Registry.js +78 -0
  51. package/lib/model/constants.js +72 -0
  52. package/lib/model/construction.js +68 -0
  53. package/lib/model/decorators.js +67 -0
  54. package/lib/{validation/index.cjs → model/index.js} +9 -6
  55. package/lib/model/types.js +2 -0
  56. package/lib/model/utils.js +29 -0
  57. package/lib/model/validation.js +138 -0
  58. package/lib/utils/constants.js +30 -0
  59. package/lib/utils/dates.js +251 -0
  60. package/lib/utils/decorators.js +22 -0
  61. package/lib/utils/hashing.js +106 -0
  62. package/lib/utils/index.js +23 -0
  63. package/lib/utils/registry.js +2 -0
  64. package/lib/utils/serialization.js +93 -0
  65. package/lib/utils/strings.js +35 -0
  66. package/lib/validation/Validation.js +75 -0
  67. package/lib/validation/Validators/DateValidator.js +57 -0
  68. package/lib/validation/Validators/EmailValidator.js +53 -0
  69. package/lib/validation/Validators/ListValidator.js +70 -0
  70. package/lib/validation/Validators/MaxLengthValidator.js +55 -0
  71. package/lib/validation/Validators/MaxValidator.js +60 -0
  72. package/lib/validation/Validators/MinLengthValidator.js +55 -0
  73. package/lib/validation/Validators/MinValidator.js +60 -0
  74. package/lib/validation/Validators/PasswordValidator.js +53 -0
  75. package/lib/validation/Validators/PatternValidator.js +73 -0
  76. package/lib/validation/Validators/RequiredValidator.js +60 -0
  77. package/lib/validation/Validators/StepValidator.js +55 -0
  78. package/lib/validation/Validators/TypeValidator.js +63 -0
  79. package/lib/validation/Validators/URLValidator.js +52 -0
  80. package/lib/validation/Validators/Validator.js +51 -0
  81. package/lib/validation/Validators/ValidatorRegistry.js +85 -0
  82. package/lib/validation/Validators/constants.js +137 -0
  83. package/lib/validation/Validators/decorators.js +28 -0
  84. package/lib/validation/Validators/index.js +69 -0
  85. package/lib/validation/Validators/types.js +2 -0
  86. package/lib/validation/decorators.js +304 -0
  87. package/lib/validation/index.js +20 -0
  88. package/lib/validation/types.js +2 -0
  89. package/package.json +1 -1
  90. package/lib/index.cjs +0 -61
  91. package/lib/model/Model.cjs +0 -302
  92. package/lib/model/ModelErrorDefinition.cjs +0 -58
  93. package/lib/model/Registry.cjs +0 -80
  94. package/lib/model/constants.cjs +0 -74
  95. package/lib/model/construction.cjs +0 -70
  96. package/lib/model/decorators.cjs +0 -69
  97. package/lib/model/index.cjs +0 -27
  98. package/lib/model/types.cjs +0 -4
  99. package/lib/model/utils.cjs +0 -31
  100. package/lib/model/validation.cjs +0 -140
  101. package/lib/utils/constants.cjs +0 -32
  102. package/lib/utils/dates.cjs +0 -253
  103. package/lib/utils/decorators.cjs +0 -24
  104. package/lib/utils/hashing.cjs +0 -108
  105. package/lib/utils/index.cjs +0 -25
  106. package/lib/utils/registry.cjs +0 -4
  107. package/lib/utils/serialization.cjs +0 -95
  108. package/lib/utils/strings.cjs +0 -37
  109. package/lib/validation/Validation.cjs +0 -77
  110. package/lib/validation/Validators/DateValidator.cjs +0 -59
  111. package/lib/validation/Validators/EmailValidator.cjs +0 -55
  112. package/lib/validation/Validators/ListValidator.cjs +0 -72
  113. package/lib/validation/Validators/MaxLengthValidator.cjs +0 -57
  114. package/lib/validation/Validators/MaxValidator.cjs +0 -62
  115. package/lib/validation/Validators/MinLengthValidator.cjs +0 -57
  116. package/lib/validation/Validators/MinValidator.cjs +0 -62
  117. package/lib/validation/Validators/PasswordValidator.cjs +0 -55
  118. package/lib/validation/Validators/PatternValidator.cjs +0 -75
  119. package/lib/validation/Validators/RequiredValidator.cjs +0 -62
  120. package/lib/validation/Validators/StepValidator.cjs +0 -57
  121. package/lib/validation/Validators/TypeValidator.cjs +0 -65
  122. package/lib/validation/Validators/URLValidator.cjs +0 -54
  123. package/lib/validation/Validators/Validator.cjs +0 -53
  124. package/lib/validation/Validators/ValidatorRegistry.cjs +0 -87
  125. package/lib/validation/Validators/constants.cjs +0 -139
  126. package/lib/validation/Validators/decorators.cjs +0 -30
  127. package/lib/validation/Validators/index.cjs +0 -71
  128. package/lib/validation/Validators/types.d.ts +0 -88
  129. package/lib/validation/decorators.cjs +0 -306
  130. package/lib/validation/types.cjs +0 -4
package/lib/index.js ADDED
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ /**
3
+ * @module decorator-validation
4
+ */
5
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ var desc = Object.getOwnPropertyDescriptor(m, k);
8
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9
+ desc = { enumerable: true, get: function() { return m[k]; } };
10
+ }
11
+ Object.defineProperty(o, k2, desc);
12
+ }) : (function(o, m, k, k2) {
13
+ if (k2 === undefined) k2 = k;
14
+ o[k2] = m[k];
15
+ }));
16
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
17
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
18
+ };
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.VERSION = void 0;
21
+ /**
22
+ * @summary Model definition functionality
23
+ * @description defines the base class and related functionality
24
+ *
25
+ * @namespace Model
26
+ * @memberOf module:decorator-validation
27
+ */
28
+ /**
29
+ * @summary Holds all the supported decorators
30
+ * @namespace Decorators
31
+ * @memberOf module:decorator-validation
32
+ */
33
+ /**
34
+ * @summary Validation related functionality
35
+ * @description Defines the Model validation apis and base classes for validators
36
+ *
37
+ * @namespace Validation
38
+ * @memberOf module:decorator-validation
39
+ */
40
+ /**
41
+ * @namespace Dates
42
+ * @memberOf module:decorator-validation
43
+ */
44
+ /**
45
+ * @namespace Hashing
46
+ * @memberOf module:decorator-validation
47
+ */
48
+ /**
49
+ * @namespace Serialization
50
+ * @memberOf module:decorator-validation
51
+ */
52
+ /**
53
+ * @namespace Format
54
+ * @memberOf module:decorator-validation
55
+ */
56
+ __exportStar(require("./utils"), exports);
57
+ __exportStar(require("./validation"), exports);
58
+ __exportStar(require("./model"), exports);
59
+ exports.VERSION = "1.5.6";
@@ -0,0 +1,300 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Model = void 0;
4
+ const serialization_1 = require("../utils/serialization");
5
+ const Registry_1 = require("./Registry");
6
+ const reflection_1 = require("@decaf-ts/reflection");
7
+ const validation_1 = require("./validation");
8
+ const hashing_1 = require("../utils/hashing");
9
+ const utils_1 = require("./utils");
10
+ const constants_1 = require("../utils/constants");
11
+ const constants_2 = require("../validation/Validators/constants");
12
+ const strings_1 = require("../utils/strings");
13
+ const constants_3 = require("./constants");
14
+ let modelBuilderFunction;
15
+ let actingModelRegistry;
16
+ /**
17
+ * @summary Abstract class representing a Validatable Model object
18
+ * @description Meant to be used as a base class for all Model classes
19
+ *
20
+ * Model objects must:
21
+ * - Have all their required properties marked with '!';
22
+ * - Have all their optional properties marked as '?':
23
+ *
24
+ * @param {Model | {}} model base object from which to populate properties from
25
+ *
26
+ * @class Model
27
+ * @abstract
28
+ * @implements Validatable
29
+ * @implements Serializable
30
+ *
31
+ * @example
32
+ * class ClassName {
33
+ * @required()
34
+ * requiredPropertyName!: PropertyType;
35
+ *
36
+ * optionalPropertyName?: PropertyType;
37
+ * }
38
+ */
39
+ class Model {
40
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
41
+ constructor(arg) { }
42
+ /**
43
+ * @summary Validates the object according to its decorated properties
44
+ *
45
+ * @param {any[]} [exceptions] properties in the object to be ignored for the validation. Marked as 'any' to allow for extension but expects strings
46
+ */
47
+ hasErrors(...exceptions) {
48
+ return (0, validation_1.validate)(this, ...exceptions);
49
+ }
50
+ /**
51
+ * @summary Compare object equality recursively
52
+ * @param {any} obj object to compare to
53
+ * @param {string} [exceptions] property names to be excluded from the comparison
54
+ */
55
+ equals(obj, ...exceptions) {
56
+ return (0, reflection_1.isEqual)(this, obj, ...exceptions);
57
+ }
58
+ /**
59
+ * @summary Returns the serialized model according to the currently defined {@link Serializer}
60
+ */
61
+ serialize() {
62
+ return Model.serialize(this);
63
+ }
64
+ /**
65
+ * @summary Override the implementation for js's 'toString()' which sucks...
66
+ * @override
67
+ */
68
+ toString() {
69
+ return this.constructor.name + ": " + JSON.stringify(this, undefined, 2);
70
+ }
71
+ /**
72
+ * @summary Defines a default implementation for object hash. Relies on a very basic implementation based on Java's string hash;
73
+ */
74
+ hash() {
75
+ return Model.hash(this);
76
+ }
77
+ /**
78
+ * @summary Deserializes a Model
79
+ * @param {string} str
80
+ *
81
+ * @throws {Error} If it fails to parse the string, or if it fails to build the model
82
+ */
83
+ static deserialize(str) {
84
+ const metadata = Reflect.getMetadata(Model.key(constants_1.ModelKeys.SERIALIZATION), this.constructor);
85
+ if (metadata && metadata.serializer)
86
+ return serialization_1.Serialization.deserialize(str, metadata.serializer, ...(metadata.args || []));
87
+ return serialization_1.Serialization.deserialize(str);
88
+ }
89
+ /**
90
+ * @summary Repopulates the Object properties with the ones from the new object
91
+ * @description Iterates all common properties of obj (if existing) and self, and copies them onto self
92
+ *
93
+ * @param {T} self
94
+ * @param {T | Record<string, any>} [obj]
95
+ *
96
+ */
97
+ static fromObject(self, obj) {
98
+ if (!obj)
99
+ obj = {};
100
+ for (const prop of Model.getAttributes(self)) {
101
+ self[prop] = obj[prop] || undefined;
102
+ }
103
+ return self;
104
+ }
105
+ /**
106
+ * @summary Repopulates the instance with the ones from the new Model Object
107
+ * @description Iterates all common properties of obj (if existing) and self, and copies them onto self.
108
+ * Is aware of nested Model Objects and rebuilds them also.
109
+ * When List properties are decorated with {@link list}, they list items will also be rebuilt
110
+ *
111
+ * @param {T} self
112
+ * @param {T | Record<string, any>} [obj]
113
+ *
114
+ */
115
+ static fromModel(self, obj) {
116
+ if (!obj)
117
+ obj = {};
118
+ let decorators, dec;
119
+ const props = Model.getAttributes(self);
120
+ for (const prop of props) {
121
+ self[prop] =
122
+ obj[prop] || undefined;
123
+ if (typeof self[prop] !== "object")
124
+ continue;
125
+ const propM = (0, utils_1.isPropertyModel)(self, prop);
126
+ if (propM) {
127
+ try {
128
+ self[prop] = Model.build(self[prop], typeof propM === "string" ? propM : undefined);
129
+ }
130
+ catch (e) {
131
+ console.log(e);
132
+ }
133
+ continue;
134
+ }
135
+ const allDecorators = reflection_1.Reflection.getPropertyDecorators(constants_2.ValidationKeys.REFLECT, self, prop).decorators;
136
+ decorators = allDecorators.filter((d) => [constants_1.ModelKeys.TYPE, constants_2.ValidationKeys.TYPE].indexOf(d.key) !== -1);
137
+ if (!decorators || !decorators.length)
138
+ throw new Error((0, strings_1.sf)("failed to find decorators for property {0}", prop));
139
+ dec = decorators.pop();
140
+ const clazz = dec.props.name
141
+ ? [dec.props.name]
142
+ : Array.isArray(dec.props.customTypes)
143
+ ? dec.props.customTypes
144
+ : [dec.props.customTypes];
145
+ const reserved = Object.values(constants_3.ReservedModels).map((v) => v.toLowerCase());
146
+ clazz.forEach((c) => {
147
+ if (reserved.indexOf(c.toLowerCase()) === -1)
148
+ try {
149
+ switch (c) {
150
+ case "Array":
151
+ case "Set":
152
+ if (allDecorators.length) {
153
+ const listDec = allDecorators.find((d) => d.key === constants_2.ValidationKeys.LIST);
154
+ if (listDec) {
155
+ const clazzName = listDec.props.clazz.find((t) => !constants_3.jsTypes.includes(t.toLowerCase()));
156
+ if (c === "Array")
157
+ self[prop] = self[prop].map((el) => {
158
+ return ["object", "function"].includes(typeof el) &&
159
+ clazzName
160
+ ? Model.build(el, clazzName)
161
+ : el;
162
+ });
163
+ if (c === "Set") {
164
+ const s = new Set();
165
+ for (const v of self[prop]) {
166
+ if (["object", "function"].includes(typeof v) &&
167
+ clazzName) {
168
+ s.add(Model.build(v, clazzName));
169
+ }
170
+ else {
171
+ s.add(v);
172
+ }
173
+ }
174
+ self[prop] = s;
175
+ }
176
+ }
177
+ }
178
+ break;
179
+ default:
180
+ if (self[prop])
181
+ self[prop] = Model.build(self[prop], c);
182
+ }
183
+ }
184
+ catch (e) {
185
+ console.log(e);
186
+ // do nothing. we have no registry of this class
187
+ }
188
+ });
189
+ }
190
+ return self;
191
+ }
192
+ /**
193
+ * @summary Sets the Global {@link ModelBuilderFunction}
194
+ * @param {ModelBuilderFunction} [builder]
195
+ */
196
+ static setBuilder(builder) {
197
+ modelBuilderFunction = builder;
198
+ }
199
+ /**
200
+ * @summary Retrieves the current global {@link ModelBuilderFunction}
201
+ */
202
+ static getBuilder() {
203
+ return modelBuilderFunction;
204
+ }
205
+ /**
206
+ * Returns the current {@link ModelRegistryManager}
207
+ *
208
+ * @return ModelRegistry, defaults to {@link ModelRegistryManager}
209
+ */
210
+ static getRegistry() {
211
+ if (!actingModelRegistry)
212
+ actingModelRegistry = new Registry_1.ModelRegistryManager();
213
+ return actingModelRegistry;
214
+ }
215
+ /**
216
+ * Returns the current actingModelRegistry
217
+ *
218
+ * @param {BuilderRegistry} modelRegistry the new implementation of Registry
219
+ */
220
+ static setRegistry(modelRegistry) {
221
+ actingModelRegistry = modelRegistry;
222
+ }
223
+ /**
224
+ * @summary register new Models
225
+ * @param {any} constructor
226
+ * @param {string} [name] when not defined, the name of the constructor will be used
227
+ *
228
+ * @see ModelRegistry
229
+ */
230
+ static register(constructor, name) {
231
+ return Model.getRegistry().register(constructor, name);
232
+ }
233
+ /**
234
+ * @summary Gets a registered Model {@link ModelConstructor}
235
+ * @param {string} name
236
+ *
237
+ * @see ModelRegistry
238
+ */
239
+ static get(name) {
240
+ return Model.getRegistry().get(name);
241
+ }
242
+ /**
243
+ * @param {Record<string, any>} obj
244
+ * @param {string} [clazz] when provided, it will attempt to find the matching constructor
245
+ *
246
+ * @throws Error If clazz is not found, or obj is not a {@link Model} meaning it has no {@link ModelKeys.ANCHOR} property
247
+ *
248
+ * @see ModelRegistry
249
+ */
250
+ static build(obj = {}, clazz) {
251
+ return Model.getRegistry().build(obj, clazz);
252
+ }
253
+ static getMetadata(model) {
254
+ const metadata = Reflect.getMetadata(Model.key(constants_1.ModelKeys.MODEL), model.constructor);
255
+ if (!metadata)
256
+ throw new Error("could not find metadata for provided " + model.constructor.name);
257
+ return metadata;
258
+ }
259
+ static getAttributes(model) {
260
+ const result = [];
261
+ let prototype = model instanceof Model
262
+ ? Object.getPrototypeOf(model)
263
+ : model.prototype;
264
+ while (prototype != null) {
265
+ const props = prototype[constants_1.ModelKeys.ATTRIBUTE];
266
+ if (props) {
267
+ result.push(...props);
268
+ }
269
+ prototype = Object.getPrototypeOf(prototype);
270
+ }
271
+ return result;
272
+ }
273
+ static equals(obj1, obj2, ...exceptions) {
274
+ return (0, reflection_1.isEqual)(obj1, obj2, ...exceptions);
275
+ }
276
+ static hasErrors(model, ...propsToIgnore) {
277
+ return (0, validation_1.validate)(model, ...propsToIgnore);
278
+ }
279
+ static serialize(model) {
280
+ const metadata = Reflect.getMetadata(Model.key(constants_1.ModelKeys.SERIALIZATION), model.constructor);
281
+ if (metadata && metadata.serializer)
282
+ return serialization_1.Serialization.serialize(this, metadata.serializer, ...(metadata.args || []));
283
+ return serialization_1.Serialization.serialize(model);
284
+ }
285
+ static hash(model) {
286
+ const metadata = Reflect.getMetadata(Model.key(constants_1.ModelKeys.HASHING), model.constructor);
287
+ if (metadata && metadata.algorithm)
288
+ return hashing_1.Hashing.hash(model, metadata.algorithm, ...(metadata.args || []));
289
+ return hashing_1.Hashing.hash(model);
290
+ }
291
+ /**
292
+ * @summary Builds the key to store as Metadata under Reflections
293
+ * @description concatenates {@link ModelKeys#REFLECT} with the provided key
294
+ * @param {string} str
295
+ */
296
+ static key(str) {
297
+ return constants_1.ModelKeys.REFLECT + str;
298
+ }
299
+ }
300
+ exports.Model = Model;
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ModelErrorDefinition = void 0;
4
+ /**
5
+ * @summary Helper Class to hold the error results
6
+ * @description holds error results in an 'indexable' manner
7
+ * while still providing the same result on toString
8
+ *
9
+ * @param {ModelErrors} errors
10
+ *
11
+ * @class ModelErrorDefinition
12
+ *
13
+ * @category Model
14
+ */
15
+ class ModelErrorDefinition {
16
+ constructor(errors) {
17
+ for (const prop in errors) {
18
+ if (Object.prototype.hasOwnProperty.call(errors, prop) && errors[prop])
19
+ Object.defineProperty(this, prop, {
20
+ enumerable: true,
21
+ configurable: false,
22
+ value: errors[prop],
23
+ writable: false,
24
+ });
25
+ }
26
+ }
27
+ /**
28
+ * @summary Outputs the class to a nice readable string
29
+ *
30
+ * @override
31
+ */
32
+ toString() {
33
+ const self = this;
34
+ return Object.keys(self)
35
+ .filter((k) => Object.prototype.hasOwnProperty.call(self, k) &&
36
+ typeof self[k] !== "function")
37
+ .reduce((accum, prop) => {
38
+ let propError = Object.keys(self[prop]).reduce((propAccum, key) => {
39
+ if (!propAccum)
40
+ propAccum = self[prop][key];
41
+ else
42
+ propAccum += `\n${self[prop][key]}`;
43
+ return propAccum;
44
+ }, undefined);
45
+ if (propError) {
46
+ propError = `${prop} - ${propError}`;
47
+ if (!accum)
48
+ accum = propError;
49
+ else
50
+ accum += `\n${propError}`;
51
+ }
52
+ return accum;
53
+ }, "");
54
+ }
55
+ }
56
+ exports.ModelErrorDefinition = ModelErrorDefinition;
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ModelRegistryManager = void 0;
4
+ exports.bulkModelRegister = bulkModelRegister;
5
+ const Model_1 = require("./Model");
6
+ const strings_1 = require("../utils/strings");
7
+ const utils_1 = require("./utils");
8
+ /**
9
+ * @summary Util class to enable serialization and correct rebuilding
10
+ *
11
+ * @param {string} anchorKey defaults to {@link ModelKeys.ANCHOR}. The property name where the registered class name is stored;
12
+ * @param {function(Record<string, any>): boolean} [testFunction] method to test if the provided object is a Model Object. defaults to {@link isModel}
13
+ *
14
+ * @class ModelRegistryManager
15
+ * @implements ModelRegistry
16
+ *
17
+ * @category Model
18
+ */
19
+ class ModelRegistryManager {
20
+ constructor(testFunction = utils_1.isModel) {
21
+ this.cache = {};
22
+ this.testFunction = testFunction;
23
+ }
24
+ /**
25
+ * @summary register new Models
26
+ * @param {any} constructor
27
+ * @param {string} [name] when not defined, the name of the constructor will be used
28
+ */
29
+ register(constructor, name) {
30
+ if (typeof constructor !== "function")
31
+ throw new Error("Model registering failed. Missing Class name or constructor");
32
+ name = name || constructor.name;
33
+ this.cache[name] = constructor;
34
+ }
35
+ /**
36
+ * @summary Gets a registered Model {@link ModelConstructor}
37
+ * @param {string} name
38
+ */
39
+ get(name) {
40
+ try {
41
+ return this.cache[name];
42
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
43
+ }
44
+ catch (e) {
45
+ return undefined;
46
+ }
47
+ }
48
+ /**
49
+ * @param {Record<string, any>} obj
50
+ * @param {string} [clazz] when provided, it will attempt to find the matching constructor
51
+ *
52
+ * @throws Error If clazz is not found, or obj is not a {@link Model} meaning it has no {@link ModelKeys.ANCHOR} property
53
+ */
54
+ build(obj = {}, clazz) {
55
+ if (!clazz && !this.testFunction(obj))
56
+ throw new Error("Provided obj is not a Model object");
57
+ const name = clazz || Model_1.Model.getMetadata(obj);
58
+ if (!(name in this.cache))
59
+ throw new Error((0, strings_1.sf)("Provided class {0} is not a registered Model object", name));
60
+ return new this.cache[name](obj);
61
+ }
62
+ }
63
+ exports.ModelRegistryManager = ModelRegistryManager;
64
+ /**
65
+ * @summary Bulk Registers Models
66
+ * @description Useful when using bundlers that might not evaluate all the code at once
67
+ *
68
+ * @param {Array<Constructor<T>> | Array<{name: string, constructor: Constructor<T>}>} [models]
69
+ *
70
+ * @memberOf module:decorator-validation.Model
71
+ * @category Model
72
+ */
73
+ function bulkModelRegister(...models) {
74
+ models.forEach((m) => {
75
+ const constructor = (m.constructor ? m.constructor : m);
76
+ Model_1.Model.register(constructor, m.name);
77
+ });
78
+ }
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.jsTypes = exports.ReservedModels = exports.Primitives = void 0;
4
+ /**
5
+ * @summary References the relevant JS primitives
6
+ *
7
+ * @property {string} STRING references the string primitive
8
+ * @property {string} NUMBER references the number primitive
9
+ * @property {string} BOOLEAN references the boolean primitive
10
+ * @property {string} BIGINT references the bigint primitive
11
+ *
12
+ * @constant Primitives
13
+ * @memberOf module:decorator-validation.Model
14
+ */
15
+ var Primitives;
16
+ (function (Primitives) {
17
+ Primitives["STRING"] = "string";
18
+ Primitives["NUMBER"] = "number";
19
+ Primitives["BOOLEAN"] = "boolean";
20
+ Primitives["BIGINT"] = "bigint";
21
+ })(Primitives || (exports.Primitives = Primitives = {}));
22
+ /**
23
+ * @summary References the Reserved model names to ignore during Model rebuilding
24
+ *
25
+ * @property {string} STRING
26
+ * @property {string} OBJECT
27
+ * @property {string} NUMBER
28
+ * @property {string} BOOLEAN
29
+ * @property {string} BIGINT
30
+ * @property {string} DATE
31
+ *
32
+ * @constant ReservedModels
33
+ * @memberOf module:decorator-validation.Model
34
+ */
35
+ var ReservedModels;
36
+ (function (ReservedModels) {
37
+ ReservedModels["STRING"] = "string";
38
+ ReservedModels["OBJECT"] = "object";
39
+ ReservedModels["NUMBER"] = "number";
40
+ ReservedModels["BOOLEAN"] = "boolean";
41
+ ReservedModels["BIGINT"] = "bigint";
42
+ ReservedModels["DATE"] = "date";
43
+ })(ReservedModels || (exports.ReservedModels = ReservedModels = {}));
44
+ /**
45
+ * @summary References the basic supported js types
46
+ *
47
+ * @property {string} string
48
+ * @property {string} array
49
+ * @property {string} number
50
+ * @property {string} boolean
51
+ * @property {string} symbol
52
+ * @property {string} function
53
+ * @property {string} object
54
+ * @property {string} undefined
55
+ * @property {string} null
56
+ * @property {string} BIGINT
57
+ *
58
+ * @constant jsTypes
59
+ * @memberOf module:decorator-validation.Model
60
+ */
61
+ exports.jsTypes = [
62
+ "string",
63
+ "array",
64
+ "number",
65
+ "boolean",
66
+ "symbol",
67
+ "function",
68
+ "object",
69
+ "undefined",
70
+ "null",
71
+ "bigint",
72
+ ];
@@ -0,0 +1,68 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.construct = construct;
4
+ exports.findLastProtoBeforeObject = findLastProtoBeforeObject;
5
+ exports.bindModelPrototype = bindModelPrototype;
6
+ const Model_1 = require("./Model");
7
+ /**
8
+ * @summary Helper Function to override constructors
9
+ *
10
+ * @param {Function} constructor
11
+ * @param {any[]} [args]
12
+ * @return {T} the new instance
13
+ *
14
+ * @function construct
15
+ * @memberOf module:decorator-validation.Construction
16
+ */
17
+ function construct(constructor, ...args) {
18
+ const _constr = (...argz) => new constructor(...argz);
19
+ _constr.prototype = constructor.prototype;
20
+ return _constr(...args);
21
+ }
22
+ /**
23
+ * @summary Recursively finds the last prototype before Object
24
+ * @param {object} obj
25
+ *
26
+ * @function findLastProtoBeforeObject
27
+ * @memberOf module:decorator-validation.Construction
28
+ */
29
+ function findLastProtoBeforeObject(obj) {
30
+ let prototype = Object.getPrototypeOf(obj);
31
+ if (prototype === Object.prototype)
32
+ return obj;
33
+ while (prototype !== Object.prototype) {
34
+ prototype = Object.getPrototypeOf(prototype);
35
+ if (prototype === Object.prototype)
36
+ return prototype;
37
+ if (Object.getPrototypeOf(prototype) === Object.prototype)
38
+ return prototype;
39
+ }
40
+ throw new Error("Could not find proper prototype");
41
+ }
42
+ /**
43
+ * @sumary binds the {@link Model} class as a root prototype of the provided instance
44
+ *
45
+ * @param {unknown} obj
46
+ *
47
+ * @function bindModelPrototype
48
+ * @memberOf module:decorator-validation.Construction
49
+ */
50
+ function bindModelPrototype(obj) {
51
+ if (obj instanceof Model_1.Model)
52
+ return;
53
+ function bindPrototype(objToOverride, prototype) {
54
+ Object.setPrototypeOf(objToOverride, prototype);
55
+ }
56
+ const prototype = Object.getPrototypeOf(obj);
57
+ if (prototype === Object.prototype) {
58
+ return bindPrototype(obj, Model_1.Model.prototype);
59
+ }
60
+ while (prototype !== Object.prototype) {
61
+ const prot = Object.getPrototypeOf(prototype);
62
+ if (prot === Object.prototype ||
63
+ Object.getPrototypeOf(prot) === Object.prototype) {
64
+ return bindPrototype(prototype, Model_1.Model.prototype);
65
+ }
66
+ }
67
+ throw new Error("Could not find proper prototype to bind");
68
+ }