functional-models 3.10.0 → 3.11.0

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 (83) hide show
  1. package/cjs/errors.cjs +38 -0
  2. package/cjs/errors.cjs.map +7 -0
  3. package/cjs/index.cjs +2426 -0
  4. package/cjs/index.cjs.map +7 -0
  5. package/cjs/lib.cjs +431 -0
  6. package/cjs/lib.cjs.map +7 -0
  7. package/cjs/models.cjs +571 -0
  8. package/cjs/models.cjs.map +7 -0
  9. package/cjs/orm/index.cjs +1765 -0
  10. package/cjs/orm/index.cjs.map +7 -0
  11. package/cjs/orm/internal-libs.cjs +136 -0
  12. package/cjs/orm/internal-libs.cjs.map +7 -0
  13. package/cjs/orm/libs.cjs +88 -0
  14. package/cjs/orm/libs.cjs.map +7 -0
  15. package/cjs/orm/models.cjs +1027 -0
  16. package/cjs/orm/models.cjs.map +7 -0
  17. package/cjs/orm/properties.cjs +989 -0
  18. package/cjs/orm/properties.cjs.map +7 -0
  19. package/cjs/orm/query.cjs +376 -0
  20. package/cjs/orm/query.cjs.map +7 -0
  21. package/cjs/orm/types.cjs +59 -0
  22. package/cjs/orm/types.cjs.map +7 -0
  23. package/cjs/orm/validation.cjs +301 -0
  24. package/cjs/orm/validation.cjs.map +7 -0
  25. package/cjs/properties.cjs +998 -0
  26. package/cjs/properties.cjs.map +7 -0
  27. package/cjs/serialization.cjs +75 -0
  28. package/cjs/serialization.cjs.map +7 -0
  29. package/cjs/types.cjs +65 -0
  30. package/cjs/types.cjs.map +7 -0
  31. package/cjs/utils.cjs +187 -0
  32. package/cjs/utils.cjs.map +7 -0
  33. package/cjs/validation.cjs +431 -0
  34. package/cjs/validation.cjs.map +7 -0
  35. package/errors.js +3 -4
  36. package/errors.js.map +1 -1
  37. package/index.d.ts +13 -13
  38. package/index.js +13 -52
  39. package/index.js.map +1 -1
  40. package/lib.d.ts +2 -2
  41. package/lib.js +45 -65
  42. package/lib.js.map +1 -1
  43. package/models.d.ts +1 -1
  44. package/models.js +22 -30
  45. package/models.js.map +1 -1
  46. package/orm/index.d.ts +9 -9
  47. package/orm/index.js +9 -48
  48. package/orm/index.js.map +1 -1
  49. package/orm/internal-libs.js +7 -11
  50. package/orm/internal-libs.js.map +1 -1
  51. package/orm/libs.d.ts +1 -1
  52. package/orm/libs.js +8 -16
  53. package/orm/libs.js.map +1 -1
  54. package/orm/models.d.ts +2 -2
  55. package/orm/models.js +20 -26
  56. package/orm/models.js.map +1 -1
  57. package/orm/properties.d.ts +22 -22
  58. package/orm/properties.js +26 -36
  59. package/orm/properties.js.map +1 -1
  60. package/orm/query.d.ts +1 -1
  61. package/orm/query.js +31 -52
  62. package/orm/query.js.map +1 -1
  63. package/orm/types.d.ts +1 -1
  64. package/orm/types.js +7 -10
  65. package/orm/types.js.map +1 -1
  66. package/orm/validation.d.ts +2 -2
  67. package/orm/validation.js +5 -13
  68. package/orm/validation.js.map +1 -1
  69. package/package.json +50 -65
  70. package/properties.d.ts +21 -21
  71. package/properties.js +65 -94
  72. package/properties.js.map +1 -1
  73. package/serialization.d.ts +1 -1
  74. package/serialization.js +3 -9
  75. package/serialization.js.map +1 -1
  76. package/types.js +4 -6
  77. package/types.js.map +1 -1
  78. package/utils.d.ts +2 -1
  79. package/utils.js +8 -23
  80. package/utils.js.map +1 -1
  81. package/validation.d.ts +1 -1
  82. package/validation.js +19 -50
  83. package/validation.js.map +1 -1
@@ -0,0 +1,989 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/orm/properties.ts
31
+ var properties_exports = {};
32
+ __export(properties_exports, {
33
+ ForeignKeyProperty: () => ForeignKeyProperty,
34
+ LastModifiedDateProperty: () => LastModifiedDateProperty,
35
+ PrimaryKeyProperty: () => PrimaryKeyProperty,
36
+ ormPropertyConfig: () => ormPropertyConfig
37
+ });
38
+ module.exports = __toCommonJS(properties_exports);
39
+ var import_merge5 = __toESM(require("lodash/merge.js"), 1);
40
+ var import_identity = __toESM(require("lodash/identity.js"), 1);
41
+
42
+ // src/properties.ts
43
+ var import_merge3 = __toESM(require("lodash/merge.js"), 1);
44
+ var import_get3 = __toESM(require("lodash/get.js"), 1);
45
+
46
+ // node_modules/uuid/dist-node/stringify.js
47
+ var byteToHex = [];
48
+ for (let i = 0; i < 256; ++i) {
49
+ byteToHex.push((i + 256).toString(16).slice(1));
50
+ }
51
+ function unsafeStringify(arr, offset = 0) {
52
+ return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
53
+ }
54
+
55
+ // node_modules/uuid/dist-node/rng.js
56
+ var rnds8 = new Uint8Array(16);
57
+ function rng() {
58
+ return crypto.getRandomValues(rnds8);
59
+ }
60
+
61
+ // node_modules/uuid/dist-node/v4.js
62
+ function v4(options, buf, offset) {
63
+ if (!buf && !options && crypto.randomUUID) {
64
+ return crypto.randomUUID();
65
+ }
66
+ return _v4(options, buf, offset);
67
+ }
68
+ function _v4(options, buf, offset) {
69
+ options = options || {};
70
+ const rnds = options.random ?? options.rng?.() ?? rng();
71
+ if (rnds.length < 16) {
72
+ throw new Error("Random bytes length must be >= 16");
73
+ }
74
+ rnds[6] = rnds[6] & 15 | 64;
75
+ rnds[8] = rnds[8] & 63 | 128;
76
+ if (buf) {
77
+ offset = offset || 0;
78
+ if (offset < 0 || offset + 16 > buf.length) {
79
+ throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);
80
+ }
81
+ for (let i = 0; i < 16; ++i) {
82
+ buf[offset + i] = rnds[i];
83
+ }
84
+ return buf;
85
+ }
86
+ return unsafeStringify(rnds);
87
+ }
88
+ var v4_default = v4;
89
+
90
+ // src/validation.ts
91
+ var import_isEmpty = __toESM(require("lodash/isEmpty.js"), 1);
92
+ var import_merge = __toESM(require("lodash/merge.js"), 1);
93
+ var import_flatMap = __toESM(require("lodash/flatMap.js"), 1);
94
+ var import_get = __toESM(require("lodash/get.js"), 1);
95
+
96
+ // src/utils.ts
97
+ var import_async_lock = __toESM(require("async-lock"), 1);
98
+ var import_get_random_values = __toESM(require("get-random-values"), 1);
99
+ var getRandomValues = () => {
100
+ const array = new Uint8Array(1);
101
+ if (typeof window !== "undefined") {
102
+ if (window.crypto) {
103
+ return window.crypto.getRandomValues(array);
104
+ }
105
+ if (window.msCrypto) {
106
+ return window.msCrypto.getRandomValues(array);
107
+ }
108
+ }
109
+ return (0, import_get_random_values.default)(array);
110
+ };
111
+ var PluralEndings = /* @__PURE__ */ ((PluralEndings2) => {
112
+ PluralEndings2["ves"] = "fe";
113
+ PluralEndings2["ies"] = "y";
114
+ PluralEndings2["i"] = "us";
115
+ PluralEndings2["zes"] = "ze";
116
+ PluralEndings2["ses"] = "s";
117
+ PluralEndings2["es"] = "e";
118
+ PluralEndings2["s"] = "";
119
+ return PluralEndings2;
120
+ })(PluralEndings || {});
121
+ var _singularizingRe = new RegExp(
122
+ `(${Object.keys(PluralEndings).join("|")})$`,
123
+ "u"
124
+ );
125
+ var flowFindFirst = (funcs) => (input) => {
126
+ return funcs.reduce((acc, func) => {
127
+ if (acc) {
128
+ return acc;
129
+ }
130
+ return func(input);
131
+ }, void 0);
132
+ };
133
+ var memoizeSync = (method) => {
134
+ let value = void 0;
135
+ let called = false;
136
+ return (...args) => {
137
+ if (!called) {
138
+ called = true;
139
+ value = method(...args);
140
+ }
141
+ return value;
142
+ };
143
+ };
144
+ var memoizeAsync = (method) => {
145
+ const key = v4_default();
146
+ const lock = new import_async_lock.default();
147
+ let value = void 0;
148
+ let called = false;
149
+ return async (...args) => {
150
+ return lock.acquire(key, async () => {
151
+ if (!called) {
152
+ called = true;
153
+ value = await method(...args);
154
+ }
155
+ return value;
156
+ });
157
+ };
158
+ };
159
+ var createUuid = v4_default;
160
+
161
+ // src/validation.ts
162
+ var multiValidator = (validators) => {
163
+ const flow3 = flowFindFirst(
164
+ validators
165
+ );
166
+ return flow3;
167
+ };
168
+ var filterEmpty = (array) => {
169
+ return array.filter((x) => x);
170
+ };
171
+ var _trueOrError = (method, error) => (value) => {
172
+ if (method(value) === false) {
173
+ return error;
174
+ }
175
+ return void 0;
176
+ };
177
+ var _typeOrError = (type, errorMessage) => (value) => {
178
+ if (typeof value !== type) {
179
+ return errorMessage;
180
+ }
181
+ return void 0;
182
+ };
183
+ var isType = (type) => (value) => {
184
+ return _typeOrError(type, `Must be a ${type}`)(value);
185
+ };
186
+ var isNumber = isType("number");
187
+ var isInteger = _trueOrError(Number.isInteger, "Must be an integer");
188
+ var isObject = multiValidator([
189
+ isType("object"),
190
+ (x) => Array.isArray(x) ? "Must be an object, but got an array" : void 0
191
+ ]);
192
+ var isBoolean = isType("boolean");
193
+ var isString = isType("string");
194
+ var isArray = _trueOrError(
195
+ (v) => Array.isArray(v),
196
+ "Value is not an array"
197
+ );
198
+ var PRIMITIVE_TO_SPECIAL_TYPE_VALIDATOR = {
199
+ ["boolean" /* boolean */]: isBoolean,
200
+ ["string" /* string */]: isString,
201
+ ["integer" /* integer */]: isInteger,
202
+ ["number" /* number */]: isNumber,
203
+ ["object" /* object */]: isObject
204
+ };
205
+ var meetsRegex = (regex, flags, errorMessage = "Format was invalid") => (value) => {
206
+ const reg = new RegExp(regex, flags);
207
+ return _trueOrError((v) => reg.test(v), errorMessage)(value);
208
+ };
209
+ var choices = (choiceArray) => (value) => {
210
+ if (Array.isArray(value)) {
211
+ const bad = value.find((v) => !choiceArray.includes(v));
212
+ if (bad) {
213
+ return `${bad} is not a valid choice`;
214
+ }
215
+ } else {
216
+ if (!choiceArray.includes(value)) {
217
+ return `${value} is not a valid choice`;
218
+ }
219
+ }
220
+ return void 0;
221
+ };
222
+ var isDate = (value) => {
223
+ if (!value) {
224
+ return "Date value is empty";
225
+ }
226
+ if (!value.toISOString) {
227
+ return "Value is not a date";
228
+ }
229
+ return void 0;
230
+ };
231
+ var isRequired = (value) => {
232
+ if (value === true || value === false) {
233
+ return void 0;
234
+ }
235
+ if (isNumber(value) === void 0) {
236
+ return void 0;
237
+ }
238
+ const empty = (0, import_isEmpty.default)(value);
239
+ if (empty) {
240
+ if (isDate(value)) {
241
+ return "A value is required";
242
+ }
243
+ }
244
+ return void 0;
245
+ };
246
+ var maxNumber = (max) => (value) => {
247
+ const numberError = isNumber(value);
248
+ if (numberError) {
249
+ return numberError;
250
+ }
251
+ if (value && value > max) {
252
+ return `The maximum is ${max}`;
253
+ }
254
+ return void 0;
255
+ };
256
+ var minNumber = (min) => (value) => {
257
+ const numberError = isNumber(value);
258
+ if (numberError) {
259
+ return numberError;
260
+ }
261
+ if (value && value < min) {
262
+ return `The minimum is ${min}`;
263
+ }
264
+ return void 0;
265
+ };
266
+ var maxTextLength = (max) => (value) => {
267
+ const stringError = isString(value);
268
+ if (stringError) {
269
+ return stringError;
270
+ }
271
+ if (value && value.length > max) {
272
+ return `The maximum length is ${max}`;
273
+ }
274
+ return void 0;
275
+ };
276
+ var minTextLength = (min) => (value) => {
277
+ const stringError = isString(value);
278
+ if (stringError) {
279
+ return stringError;
280
+ }
281
+ if (value && value.length < min) {
282
+ return `The minimum length is ${min}`;
283
+ }
284
+ return void 0;
285
+ };
286
+ var aggregateValidator = (value, methodOrMethods) => {
287
+ const toDo = Array.isArray(methodOrMethods) ? methodOrMethods : [methodOrMethods];
288
+ const _aggregativeValidator = async (model, instanceData, propertyConfiguration) => {
289
+ const values = await Promise.all(
290
+ toDo.map((method) => {
291
+ return method(value, model, instanceData, propertyConfiguration);
292
+ })
293
+ );
294
+ return filterEmpty(values);
295
+ };
296
+ return _aggregativeValidator;
297
+ };
298
+ var emptyValidator = () => void 0;
299
+ var _boolChoice = (method) => (configValue) => {
300
+ const func = method(configValue);
301
+ const validatorWrapper = func;
302
+ return validatorWrapper;
303
+ };
304
+ var simpleFuncWrap = (validator) => () => {
305
+ return validator;
306
+ };
307
+ var includeOrDont = (method) => (configValue) => {
308
+ if (configValue === false) {
309
+ return emptyValidator;
310
+ }
311
+ const func = method();
312
+ const validatorWrapper = func;
313
+ return validatorWrapper;
314
+ };
315
+ var CONFIG_TO_VALIDATE_METHOD = () => ({
316
+ required: includeOrDont(simpleFuncWrap(isRequired)),
317
+ isInteger: _boolChoice(simpleFuncWrap(isInteger)),
318
+ isNumber: _boolChoice(simpleFuncWrap(isNumber)),
319
+ isString: _boolChoice(simpleFuncWrap(isString)),
320
+ isArray: _boolChoice(simpleFuncWrap(isArray)),
321
+ isBoolean: _boolChoice(simpleFuncWrap(isBoolean)),
322
+ choices: _boolChoice(choices)
323
+ });
324
+ var createPropertyValidator = (valueGetter, config) => {
325
+ const _propertyValidator = async (model, instanceData, propertyConfiguration) => {
326
+ return Promise.resolve().then(async () => {
327
+ const configToValidateMethod = CONFIG_TO_VALIDATE_METHOD();
328
+ if (!config) {
329
+ config = {};
330
+ }
331
+ const validators = [
332
+ ...Object.entries(config).map(([key, value2]) => {
333
+ const method = configToValidateMethod[key];
334
+ if (method) {
335
+ return method(value2);
336
+ }
337
+ return emptyValidator;
338
+ }),
339
+ ...config.validators ? config.validators : []
340
+ ].filter((x) => x);
341
+ const value = await valueGetter();
342
+ const isRequiredValue = config.required ? true : validators.includes(isRequired);
343
+ if (!value && !isRequiredValue) {
344
+ return [];
345
+ }
346
+ const validator = aggregateValidator(value, validators);
347
+ const errors = await validator(model, instanceData, propertyConfiguration);
348
+ return [...new Set((0, import_flatMap.default)(errors))];
349
+ });
350
+ };
351
+ return _propertyValidator;
352
+ };
353
+ var optionalValidator = (validator) => {
354
+ return (v) => {
355
+ if (v === void 0 || v === null) {
356
+ return void 0;
357
+ }
358
+ return validator(v);
359
+ };
360
+ };
361
+ var UUID_VALIDATOR = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;
362
+ var isValidUuid = (uuid) => {
363
+ const stringError = isString(uuid);
364
+ if (stringError) {
365
+ return stringError;
366
+ }
367
+ return meetsRegex(UUID_VALIDATOR, "g", "Invalid UUID format")(uuid);
368
+ };
369
+
370
+ // src/lib.ts
371
+ var import_openapi_types = require("openapi-types");
372
+ var import_kebabCase = __toESM(require("lodash/kebabCase.js"), 1);
373
+ var import_flow = __toESM(require("lodash/flow.js"), 1);
374
+ var import_merge2 = __toESM(require("lodash/merge.js"), 1);
375
+ var import_get2 = __toESM(require("lodash/get.js"), 1);
376
+ var import_zod = require("zod");
377
+ var HttpMethods = import_openapi_types.OpenAPIV3.HttpMethods;
378
+ var NULL_METHOD = HttpMethods.HEAD;
379
+ var ID_KEY = ":id";
380
+ var getCommonTextValidators = (config) => {
381
+ return [
382
+ getValidatorFromConfigElseEmpty(config?.maxLength, maxTextLength),
383
+ getValidatorFromConfigElseEmpty(config?.minLength, minTextLength)
384
+ ];
385
+ };
386
+ var getValidatorFromConfigElseEmpty = (input, validatorGetter) => {
387
+ if (input !== void 0) {
388
+ const validator = validatorGetter(input);
389
+ return validator;
390
+ }
391
+ return emptyValidator;
392
+ };
393
+ var getCommonNumberValidators = (config) => {
394
+ return [
395
+ getValidatorFromConfigElseEmpty(config?.minValue, minNumber),
396
+ getValidatorFromConfigElseEmpty(config?.maxValue, maxNumber)
397
+ ];
398
+ };
399
+ var mergeValidators = (config, ...validators) => {
400
+ return [...validators, ...config?.validators ? config.validators : []];
401
+ };
402
+ var buildValidEndpoint = (...components) => {
403
+ const suffix = components.map((x) => {
404
+ if (x === ID_KEY) {
405
+ return x;
406
+ }
407
+ return (0, import_kebabCase.default)(x);
408
+ }).map((s) => s.toLowerCase()).join("/");
409
+ return `/${suffix}`;
410
+ };
411
+ var _generateRestInfo = (method, withId, ...additional) => (pluralName, namespace) => (existing) => {
412
+ if (existing) {
413
+ return {
414
+ // Default add security, then override it.
415
+ security: {},
416
+ ...existing
417
+ };
418
+ }
419
+ const endpoint = withId ? buildValidEndpoint(namespace, pluralName, ID_KEY) : buildValidEndpoint(namespace, pluralName, ...additional);
420
+ return {
421
+ method,
422
+ endpoint,
423
+ // We cannot auto create security.
424
+ security: {}
425
+ };
426
+ };
427
+ var _apiMethodToRestInfoGenerator = {
428
+ ["create" /* create */]: _generateRestInfo(HttpMethods.POST, false),
429
+ ["retrieve" /* retrieve */]: _generateRestInfo(HttpMethods.GET, true),
430
+ ["update" /* update */]: _generateRestInfo(HttpMethods.PUT, true),
431
+ ["delete" /* delete */]: _generateRestInfo(HttpMethods.DELETE, true),
432
+ ["search" /* search */]: _generateRestInfo(HttpMethods.POST, false, "search")
433
+ };
434
+ var createZodForProperty = (propertyType, config) => () => {
435
+ const myConfig = config || {};
436
+ const provided = myConfig.zod;
437
+ if (provided) {
438
+ return provided;
439
+ }
440
+ const _getZodForPropertyType = (pt) => {
441
+ if (myConfig.choices) {
442
+ return import_zod.z.enum(myConfig.choices);
443
+ }
444
+ switch (pt) {
445
+ case "UniqueId":
446
+ return import_zod.z.string();
447
+ case "Date":
448
+ case "Datetime":
449
+ return import_zod.z.union([import_zod.z.string(), import_zod.z.date()]);
450
+ case "Integer":
451
+ return import_zod.z.number().int();
452
+ case "Number":
453
+ return import_zod.z.number();
454
+ case "Boolean":
455
+ return import_zod.z.boolean();
456
+ case "Array":
457
+ return import_zod.z.array(import_zod.z.any());
458
+ case "Object":
459
+ return import_zod.z.object().loose();
460
+ case "Email":
461
+ return import_zod.z.email();
462
+ case "Text":
463
+ case "BigText":
464
+ return import_zod.z.string();
465
+ case "ModelReference":
466
+ return import_zod.z.union([import_zod.z.string(), import_zod.z.number()]);
467
+ default:
468
+ return import_zod.z.any();
469
+ }
470
+ };
471
+ const baseSchema = _getZodForPropertyType(propertyType);
472
+ const choices2 = config?.choices;
473
+ const schemaFromChoices = choices2 && Array.isArray(choices2) && choices2.length > 0 ? import_zod.z.union(choices2.map((c) => import_zod.z.literal(c))) : baseSchema;
474
+ const finalSchema = (0, import_flow.default)([
475
+ (s) => typeof myConfig.minValue === "number" ? s.min(myConfig.minValue) : s,
476
+ (s) => typeof myConfig.maxValue === "number" ? s.max(myConfig.maxValue) : s,
477
+ (s) => typeof myConfig.minLength === "number" ? s.min(myConfig.minLength) : s,
478
+ (s) => typeof myConfig.maxLength === "number" ? s.max(myConfig.maxLength) : s,
479
+ (s) => myConfig.defaultValue !== void 0 ? s.default(myConfig.defaultValue) : s,
480
+ (s) => myConfig.required ? s : s.optional(),
481
+ // Attach description for Zod consumers and OpenAPI generators.
482
+ (s) => {
483
+ if (myConfig.description) {
484
+ if (typeof s.openapi === "function") {
485
+ return s.openapi({ description: myConfig.description });
486
+ }
487
+ return s.meta ? s.meta({ description: myConfig.description }) : s.describe(myConfig.description);
488
+ }
489
+ return s;
490
+ }
491
+ ])(schemaFromChoices);
492
+ return finalSchema;
493
+ };
494
+
495
+ // src/properties.ts
496
+ var Property = (propertyType, config = {}, additionalMetadata = {}) => {
497
+ if (!propertyType && !config?.typeOverride) {
498
+ throw new Error(`Property type must be provided.`);
499
+ }
500
+ if (config?.typeOverride) {
501
+ propertyType = config.typeOverride;
502
+ }
503
+ const getConstantValue = () => config?.value !== void 0 ? config.value : void 0;
504
+ const getDefaultValue = () => config?.defaultValue !== void 0 ? config.defaultValue : void 0;
505
+ const getChoices = () => config?.choices || [];
506
+ const lazyLoadMethod = config?.lazyLoadMethod || false;
507
+ const valueSelector = config?.valueSelector || ((x) => x);
508
+ if (typeof valueSelector !== "function") {
509
+ throw new Error(`valueSelector must be a function`);
510
+ }
511
+ const createGetter = (instanceValue, modelData, instance) => {
512
+ const constantValue = getConstantValue();
513
+ if (constantValue !== void 0) {
514
+ return () => constantValue;
515
+ }
516
+ const defaultValue = getDefaultValue();
517
+ if (defaultValue !== void 0 && (instanceValue === null || instanceValue === void 0)) {
518
+ return () => defaultValue;
519
+ }
520
+ const method = lazyLoadMethod ? lazyLoadMethod : config.lazyLoadMethodAtomic ? memoizeAsync(config.lazyLoadMethodAtomic) : typeof instanceValue === "function" ? instanceValue : () => instanceValue;
521
+ const valueGetter = memoizeSync(() => {
522
+ const result = method(
523
+ instanceValue,
524
+ modelData,
525
+ // @ts-ignore
526
+ instance
527
+ );
528
+ return valueSelector(result);
529
+ });
530
+ return valueGetter;
531
+ };
532
+ const getValidator = (valueGetter) => {
533
+ const validator = createPropertyValidator(valueGetter, config);
534
+ const _propertyValidatorWrapper = async (model, instanceData, propertyConfiguration) => {
535
+ return validator(model, instanceData, propertyConfiguration);
536
+ };
537
+ return _propertyValidatorWrapper;
538
+ };
539
+ const getZod = () => {
540
+ const provided = config?.zod;
541
+ if (provided) {
542
+ return provided;
543
+ }
544
+ return createZodForProperty(propertyType, config)();
545
+ };
546
+ const propertyInstance = {
547
+ ...additionalMetadata,
548
+ getConfig: () => config || {},
549
+ getChoices,
550
+ getDefaultValue,
551
+ getConstantValue,
552
+ getPropertyType: () => propertyType,
553
+ createGetter,
554
+ getZod,
555
+ getValidator
556
+ };
557
+ return propertyInstance;
558
+ };
559
+ var isDate2 = (value) => {
560
+ if (value === null) {
561
+ return false;
562
+ }
563
+ return typeof value === "object" && value.toISOString;
564
+ };
565
+ var DatetimeProperty = (config = {}, additionalMetadata = {}) => Property(
566
+ "Datetime" /* Datetime */,
567
+ (0, import_merge3.default)(
568
+ {
569
+ lazyLoadMethod: (value) => {
570
+ if (isDate2(value)) {
571
+ if (config.formatFunction) {
572
+ return config.formatFunction(value, config.format);
573
+ }
574
+ return value.toISOString();
575
+ }
576
+ if (!value && config?.autoNow) {
577
+ const date = /* @__PURE__ */ new Date();
578
+ if (config.formatFunction) {
579
+ return config.formatFunction(date, config.format);
580
+ }
581
+ return date.toISOString();
582
+ }
583
+ return value;
584
+ }
585
+ },
586
+ config
587
+ ),
588
+ additionalMetadata
589
+ );
590
+ var TextProperty = (config = {}, additionalMetadata = {}) => Property(
591
+ "Text" /* Text */,
592
+ (0, import_merge3.default)(config, {
593
+ isString: true,
594
+ // @ts-ignore
595
+ validators: mergeValidators(config, ...getCommonTextValidators(config))
596
+ }),
597
+ additionalMetadata
598
+ );
599
+ var IntegerProperty = (config = {}, additionalMetadata = {}) => Property(
600
+ "Integer" /* Integer */,
601
+ (0, import_merge3.default)(config, {
602
+ isInteger: true,
603
+ validators: mergeValidators(
604
+ config,
605
+ ...getCommonNumberValidators(config)
606
+ )
607
+ }),
608
+ additionalMetadata
609
+ );
610
+ var UuidProperty = (config = {}, additionalMetadata = {}) => Property(
611
+ "UniqueId" /* UniqueId */,
612
+ (0, import_merge3.default)(config, {
613
+ isString: true,
614
+ validators: mergeValidators(
615
+ config,
616
+ config.required ? isValidUuid : optionalValidator(isValidUuid)
617
+ ),
618
+ lazyLoadMethod: (value) => {
619
+ if (!value) {
620
+ if (config.autoNow) {
621
+ return v4_default();
622
+ }
623
+ }
624
+ return value;
625
+ }
626
+ }),
627
+ additionalMetadata
628
+ );
629
+
630
+ // src/orm/validation.ts
631
+ var import_flow2 = __toESM(require("lodash/flow.js"), 1);
632
+
633
+ // src/orm/query.ts
634
+ var import_merge4 = __toESM(require("lodash/merge.js"), 1);
635
+ var import_omit = __toESM(require("lodash/omit.js"), 1);
636
+
637
+ // src/orm/types.ts
638
+ var EqualitySymbol = /* @__PURE__ */ ((EqualitySymbol2) => {
639
+ EqualitySymbol2["eq"] = "=";
640
+ EqualitySymbol2["lt"] = "<";
641
+ EqualitySymbol2["lte"] = "<=";
642
+ EqualitySymbol2["gt"] = ">";
643
+ EqualitySymbol2["gte"] = ">=";
644
+ EqualitySymbol2["ne"] = "!=";
645
+ return EqualitySymbol2;
646
+ })(EqualitySymbol || {});
647
+ var AllowableEqualitySymbols = Object.values(EqualitySymbol);
648
+
649
+ // src/orm/query.ts
650
+ var _objectize = (key, value) => {
651
+ return value ? {
652
+ [key]: value
653
+ } : {};
654
+ };
655
+ var _additionalLink = (data) => {
656
+ const inner = _builderV2(data);
657
+ const partialLink = (0, import_omit.default)(_link(data), ["and", "or"]);
658
+ return {
659
+ ...inner,
660
+ ...partialLink
661
+ };
662
+ };
663
+ var _link = (data) => {
664
+ return {
665
+ and: () => {
666
+ return _queryBuilder({ ...data, query: data.query.concat("AND") });
667
+ },
668
+ or: () => {
669
+ return _queryBuilder({ ...data, query: data.query.concat("OR") });
670
+ },
671
+ compile: () => {
672
+ return data;
673
+ },
674
+ take: (num) => {
675
+ return _additionalLink({ ...data, take: take(num) });
676
+ },
677
+ sort: (key, order = "asc" /* asc */) => {
678
+ return _additionalLink({ ...data, sort: sort(key, order) });
679
+ },
680
+ pagination: (value) => {
681
+ return _additionalLink({ ...data, page: pagination(value) });
682
+ }
683
+ };
684
+ };
685
+ var _canCompile = (obj) => {
686
+ return Boolean(obj.compile);
687
+ };
688
+ var _builderV2 = (data) => {
689
+ const _myProperty = (name, value, options) => {
690
+ const p = property(name, value, options);
691
+ return _link((0, import_merge4.default)(data, { query: data.query.concat(p) }));
692
+ };
693
+ const complex = (subBuilderFunc) => {
694
+ const subBuilder = _queryBuilder();
695
+ const result = subBuilderFunc(subBuilder);
696
+ if (_canCompile(result)) {
697
+ const queryTokens = [result.compile().query];
698
+ return _link(
699
+ (0, import_merge4.default)(data, {
700
+ query: data.query.concat(queryTokens)
701
+ })
702
+ );
703
+ }
704
+ return _link((0, import_merge4.default)(data, { query: data.query.concat([result.query]) }));
705
+ };
706
+ const thisDatesBefore = (key, jsDate, { valueType = "date" /* date */, equalToAndBefore = true } = {}) => {
707
+ const p = datesBefore(key, jsDate, { valueType, equalToAndBefore });
708
+ return _link((0, import_merge4.default)(data, { query: data.query.concat(p) }));
709
+ };
710
+ const thisDatesAfter = (key, jsDate, { valueType = "date" /* date */, equalToAndAfter = true } = {}) => {
711
+ const p = datesAfter(key, jsDate, { valueType, equalToAndAfter });
712
+ return _link((0, import_merge4.default)(data, { query: data.query.concat(p) }));
713
+ };
714
+ return {
715
+ datesBefore: thisDatesBefore,
716
+ datesAfter: thisDatesAfter,
717
+ complex,
718
+ property: _myProperty
719
+ };
720
+ };
721
+ var _queryBuilder = (data = void 0) => {
722
+ const theData = (0, import_merge4.default)(
723
+ {
724
+ query: []
725
+ },
726
+ data
727
+ );
728
+ const builder = _builderV2(theData);
729
+ const linkData = _additionalLink(theData);
730
+ return {
731
+ ...builder,
732
+ ...linkData,
733
+ compile: () => {
734
+ return {
735
+ ..._objectize("take", theData.take),
736
+ ..._objectize("sort", theData.sort),
737
+ ..._objectize("page", theData.page),
738
+ query: []
739
+ };
740
+ }
741
+ };
742
+ };
743
+ var property = (key, value, options = {}) => {
744
+ const {
745
+ equalitySymbol = "=" /* eq */,
746
+ caseSensitive,
747
+ startsWith,
748
+ endsWith,
749
+ includes,
750
+ type
751
+ } = options;
752
+ const typeToUse = type || "string" /* string */;
753
+ if (!AllowableEqualitySymbols.includes(equalitySymbol)) {
754
+ throw new Error(`${equalitySymbol} is not a valid symbol`);
755
+ }
756
+ if (equalitySymbol !== "=" /* eq */ && equalitySymbol !== "!=" /* ne */ && typeToUse === "string" /* string */) {
757
+ throw new Error(`Cannot use a non = symbol for a string type`);
758
+ }
759
+ const propertyEntry = {
760
+ type: "property",
761
+ key,
762
+ value,
763
+ valueType: typeToUse,
764
+ equalitySymbol,
765
+ options: {
766
+ ..._objectize("caseSensitive", caseSensitive),
767
+ ..._objectize("startsWith", startsWith),
768
+ ..._objectize("endsWith", endsWith),
769
+ ..._objectize("includes", includes)
770
+ }
771
+ };
772
+ return propertyEntry;
773
+ };
774
+ var take = (max) => {
775
+ const parsed = parseInt(`${max}`, 10);
776
+ if (Number.isNaN(parsed)) {
777
+ throw new Error(`Number "${max}" is not integerable`);
778
+ }
779
+ return parsed;
780
+ };
781
+ var sort = (key, order = "asc" /* asc */) => {
782
+ if (order !== "asc" /* asc */ && order !== "dsc" /* dsc */) {
783
+ throw new Error("Sort must be either asc or dsc");
784
+ }
785
+ return {
786
+ key,
787
+ order
788
+ };
789
+ };
790
+ var pagination = (value) => {
791
+ return value;
792
+ };
793
+ var datesAfter = (key, jsDate, options = {
794
+ valueType: "date" /* date */,
795
+ equalToAndAfter: true
796
+ }) => {
797
+ const { valueType = "date" /* date */, equalToAndAfter = true } = options;
798
+ return {
799
+ type: "datesAfter",
800
+ key,
801
+ date: isDate3(jsDate) ? jsDate.toISOString() : jsDate,
802
+ valueType,
803
+ options: {
804
+ equalToAndAfter
805
+ }
806
+ };
807
+ };
808
+ var isDate3 = (obj) => {
809
+ return Boolean(obj.toISOString);
810
+ };
811
+ var datesBefore = (key, jsDate, options = {
812
+ valueType: "date" /* date */,
813
+ equalToAndBefore: true
814
+ }) => {
815
+ const { valueType = "date" /* date */, equalToAndBefore = true } = options;
816
+ return {
817
+ type: "datesBefore",
818
+ key,
819
+ date: isDate3(jsDate) ? jsDate.toISOString() : jsDate,
820
+ valueType,
821
+ options: {
822
+ equalToAndBefore
823
+ }
824
+ };
825
+ };
826
+ var queryBuilder = () => {
827
+ return _queryBuilder();
828
+ };
829
+
830
+ // src/orm/validation.ts
831
+ var _doUniqueCheck = async (query, model, instanceData, buildErrorMessage) => {
832
+ const results = await model.search(query);
833
+ const resultsLength = results.instances.length;
834
+ if (resultsLength < 1) {
835
+ return void 0;
836
+ }
837
+ const ids = await Promise.all(
838
+ results.instances.map((x) => x.getPrimaryKey())
839
+ );
840
+ const instanceId = instanceData[model.getModelDefinition().primaryKeyName];
841
+ if (ids.length === 1 && ids[0] === instanceId) {
842
+ return void 0;
843
+ }
844
+ if (ids.length > 1) {
845
+ if (ids.find((x) => x === instanceId)) {
846
+ return void 0;
847
+ }
848
+ }
849
+ return buildErrorMessage();
850
+ };
851
+ var uniqueTogether = (propertyKeyArray) => {
852
+ const _uniqueTogether = async (model, instanceData, options) => {
853
+ if (options?.noOrmValidation) {
854
+ return void 0;
855
+ }
856
+ const properties = propertyKeyArray.map((key) => {
857
+ return [key, instanceData[key]];
858
+ });
859
+ const query = (0, import_flow2.default)(
860
+ properties.map(([key, value], index) => {
861
+ return (b) => {
862
+ if (index + 1 >= properties.length) {
863
+ return b.property(key, value, { caseSensitive: false });
864
+ }
865
+ return b.property(key, value, { caseSensitive: false }).and();
866
+ };
867
+ })
868
+ )(queryBuilder().take(2)).compile();
869
+ return _doUniqueCheck(query, model, instanceData, () => {
870
+ return propertyKeyArray.length > 1 ? `${propertyKeyArray.join(
871
+ ","
872
+ )} must be unique together. Another instance found.` : `${propertyKeyArray[0]} must be unique. Another instance found.`;
873
+ });
874
+ };
875
+ return _uniqueTogether;
876
+ };
877
+ var unique = (propertyKey) => {
878
+ const _unique = (value, model, instanceData, options) => {
879
+ return uniqueTogether([propertyKey])(model, instanceData, options);
880
+ };
881
+ return _unique;
882
+ };
883
+
884
+ // src/orm/internal-libs.ts
885
+ var _getModelIdPropertyType = (config = {}) => {
886
+ return config.dataType || "UniqueId" /* UniqueId */;
887
+ };
888
+ var getPrimaryKeyGenerator = (config = {}) => {
889
+ const custom = config.primaryKeyGenerator;
890
+ if (custom) {
891
+ return custom;
892
+ }
893
+ const idType = _getModelIdPropertyType(config);
894
+ switch (idType) {
895
+ case "Integer" /* Integer */:
896
+ return () => Promise.resolve(getRandomValues()[0]);
897
+ default: {
898
+ return () => Promise.resolve(createUuid());
899
+ }
900
+ }
901
+ };
902
+
903
+ // src/orm/properties.ts
904
+ var _defaultPropertyConfig = {
905
+ unique: void 0
906
+ };
907
+ var LastModifiedDateProperty = (config = {}) => {
908
+ const additionalMetadata = { lastModifiedUpdateMethod: () => /* @__PURE__ */ new Date() };
909
+ return DatetimeProperty(config, additionalMetadata);
910
+ };
911
+ var ForeignKeyProperty = (model, config = {}) => {
912
+ const _getModel = () => {
913
+ if (typeof model === "function") {
914
+ return model();
915
+ }
916
+ return model;
917
+ };
918
+ const _getProperty = () => {
919
+ if (config.dataType === "UniqueId" /* UniqueId */) {
920
+ return UuidProperty(
921
+ (0, import_merge5.default)(config, {
922
+ autoNow: false
923
+ })
924
+ );
925
+ }
926
+ if (config.dataType === "Integer" /* Integer */) {
927
+ return IntegerProperty(config);
928
+ }
929
+ return TextProperty(config);
930
+ };
931
+ const property2 = _getProperty();
932
+ return (0, import_merge5.default)(property2, {
933
+ getReferencedId: (instanceValues) => {
934
+ return instanceValues;
935
+ },
936
+ getReferencedModel: _getModel
937
+ });
938
+ };
939
+ var PrimaryKeyProperty = (config = {}) => {
940
+ const _getProperty = () => {
941
+ const auto = config.auto === void 0 ? true : config.auto ? true : false;
942
+ const lazyLoadMethod = (value, modelData, instance) => {
943
+ if (config.primaryKeyGenerator) {
944
+ return config.primaryKeyGenerator(value, modelData, instance);
945
+ }
946
+ if (auto) {
947
+ return getPrimaryKeyGenerator(config)(value, modelData, instance);
948
+ }
949
+ return value;
950
+ };
951
+ if (config.dataType === "UniqueId" /* UniqueId */) {
952
+ return UuidProperty(
953
+ (0, import_merge5.default)(config, {
954
+ autoNow: auto,
955
+ lazyLoadMethod
956
+ })
957
+ );
958
+ }
959
+ if (config.dataType === "Integer" /* Integer */) {
960
+ return IntegerProperty(
961
+ (0, import_merge5.default)(config, {
962
+ lazyLoadMethod
963
+ })
964
+ );
965
+ }
966
+ return TextProperty(
967
+ (0, import_merge5.default)(config, {
968
+ lazyLoadMethod
969
+ })
970
+ );
971
+ };
972
+ return _getProperty();
973
+ };
974
+ var ormPropertyConfig = (config = _defaultPropertyConfig) => {
975
+ return (0, import_merge5.default)(config, {
976
+ validators: [
977
+ ...config.validators ? config.validators : [],
978
+ config.unique ? unique(config.unique) : null
979
+ ].filter(import_identity.default)
980
+ });
981
+ };
982
+ // Annotate the CommonJS export names for ESM import in node:
983
+ 0 && (module.exports = {
984
+ ForeignKeyProperty,
985
+ LastModifiedDateProperty,
986
+ PrimaryKeyProperty,
987
+ ormPropertyConfig
988
+ });
989
+ //# sourceMappingURL=properties.cjs.map