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
package/cjs/index.cjs ADDED
@@ -0,0 +1,2426 @@
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/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ AdvancedModelReferenceProperty: () => AdvancedModelReferenceProperty,
34
+ AllowableEqualitySymbols: () => AllowableEqualitySymbols,
35
+ ApiMethod: () => ApiMethod,
36
+ ArrayProperty: () => ArrayProperty,
37
+ BigTextProperty: () => BigTextProperty,
38
+ BooleanProperty: () => BooleanProperty,
39
+ ConstantValueProperty: () => ConstantValueProperty,
40
+ DatastoreValueType: () => DatastoreValueType,
41
+ DateProperty: () => DateProperty,
42
+ DatetimeProperty: () => DatetimeProperty,
43
+ DenormalizedIntegerProperty: () => DenormalizedIntegerProperty,
44
+ DenormalizedNumberProperty: () => DenormalizedNumberProperty,
45
+ DenormalizedProperty: () => DenormalizedProperty,
46
+ DenormalizedTextProperty: () => DenormalizedTextProperty,
47
+ EmailProperty: () => EmailProperty,
48
+ EqualitySymbol: () => EqualitySymbol,
49
+ ForeignKeyProperty: () => ForeignKeyProperty,
50
+ IntegerProperty: () => IntegerProperty,
51
+ LastModifiedDateProperty: () => LastModifiedDateProperty,
52
+ Model: () => Model,
53
+ ModelReferenceProperty: () => ModelReferenceProperty,
54
+ NaturalIdProperty: () => NaturalIdProperty,
55
+ NumberProperty: () => NumberProperty,
56
+ ObjectProperty: () => ObjectProperty,
57
+ PrimaryKeyProperty: () => PrimaryKeyProperty,
58
+ PrimaryKeyUuidProperty: () => PrimaryKeyUuidProperty,
59
+ PrimitiveValueType: () => PrimitiveValueType,
60
+ Property: () => Property,
61
+ PropertyType: () => PropertyType,
62
+ SingleTypeArrayProperty: () => SingleTypeArrayProperty,
63
+ SortOrder: () => SortOrder,
64
+ TextProperty: () => TextProperty,
65
+ UuidProperty: () => UuidProperty,
66
+ ValidationError: () => ValidationError,
67
+ YearProperty: () => YearProperty,
68
+ aggregateValidator: () => aggregateValidator,
69
+ and: () => and,
70
+ arrayType: () => arrayType,
71
+ booleanQuery: () => booleanQuery,
72
+ buildOrmValidatorContext: () => buildOrmValidatorContext,
73
+ choices: () => choices,
74
+ createModelValidator: () => createModelValidator,
75
+ createOrm: () => createOrm,
76
+ createPropertyValidator: () => createPropertyValidator,
77
+ datesAfter: () => datesAfter,
78
+ datesBefore: () => datesBefore,
79
+ emptyValidator: () => emptyValidator,
80
+ errors: () => errors_exports,
81
+ isALinkToken: () => isALinkToken,
82
+ isArray: () => isArray,
83
+ isBoolean: () => isBoolean,
84
+ isDate: () => isDate,
85
+ isInteger: () => isInteger,
86
+ isNullRestInfo: () => isNullRestInfo,
87
+ isNumber: () => isNumber,
88
+ isObject: () => isObject,
89
+ isPropertyBasedQuery: () => isPropertyBasedQuery,
90
+ isRequired: () => isRequired,
91
+ isString: () => isString,
92
+ isType: () => isType,
93
+ isValid: () => isValid,
94
+ isValidUuid: () => isValidUuid,
95
+ maxNumber: () => maxNumber,
96
+ maxTextLength: () => maxTextLength,
97
+ meetsRegex: () => meetsRegex,
98
+ minNumber: () => minNumber,
99
+ minTextLength: () => minTextLength,
100
+ models: () => models_exports,
101
+ multiValidator: () => multiValidator,
102
+ multipleAndQuery: () => multipleAndQuery,
103
+ multipleOrQuery: () => multipleOrQuery,
104
+ noFetch: () => noFetch,
105
+ numberQuery: () => numberQuery,
106
+ objectValidator: () => objectValidator,
107
+ optionalValidator: () => optionalValidator,
108
+ or: () => or,
109
+ orm: () => orm_exports,
110
+ ormPropertyConfig: () => ormPropertyConfig,
111
+ pagination: () => pagination,
112
+ properties: () => properties_exports,
113
+ property: () => property,
114
+ query: () => query_exports,
115
+ queryBuilder: () => queryBuilder,
116
+ referenceTypeMatch: () => referenceTypeMatch,
117
+ sort: () => sort,
118
+ take: () => take,
119
+ textQuery: () => textQuery,
120
+ threeitize: () => threeitize,
121
+ types: () => types_exports,
122
+ unique: () => unique,
123
+ uniqueTogether: () => uniqueTogether,
124
+ validateOrmSearch: () => validateOrmSearch,
125
+ validation: () => validation_exports
126
+ });
127
+ module.exports = __toCommonJS(index_exports);
128
+
129
+ // src/types.ts
130
+ var types_exports = {};
131
+ __export(types_exports, {
132
+ ApiMethod: () => ApiMethod,
133
+ PrimitiveValueType: () => PrimitiveValueType,
134
+ PropertyType: () => PropertyType
135
+ });
136
+ var ApiMethod = /* @__PURE__ */ ((ApiMethod2) => {
137
+ ApiMethod2["create"] = "create";
138
+ ApiMethod2["retrieve"] = "retrieve";
139
+ ApiMethod2["update"] = "update";
140
+ ApiMethod2["delete"] = "delete";
141
+ ApiMethod2["search"] = "search";
142
+ return ApiMethod2;
143
+ })(ApiMethod || {});
144
+ var PropertyType = /* @__PURE__ */ ((PropertyType2) => {
145
+ PropertyType2["UniqueId"] = "UniqueId";
146
+ PropertyType2["Date"] = "Date";
147
+ PropertyType2["Datetime"] = "Datetime";
148
+ PropertyType2["Array"] = "Array";
149
+ PropertyType2["ModelReference"] = "ModelReference";
150
+ PropertyType2["Integer"] = "Integer";
151
+ PropertyType2["Text"] = "Text";
152
+ PropertyType2["BigText"] = "BigText";
153
+ PropertyType2["Number"] = "Number";
154
+ PropertyType2["Object"] = "Object";
155
+ PropertyType2["Email"] = "Email";
156
+ PropertyType2["Boolean"] = "Boolean";
157
+ return PropertyType2;
158
+ })(PropertyType || {});
159
+ var PrimitiveValueType = /* @__PURE__ */ ((PrimitiveValueType3) => {
160
+ PrimitiveValueType3["boolean"] = "boolean";
161
+ PrimitiveValueType3["string"] = "string";
162
+ PrimitiveValueType3["object"] = "object";
163
+ PrimitiveValueType3["number"] = "number";
164
+ PrimitiveValueType3["integer"] = "integer";
165
+ return PrimitiveValueType3;
166
+ })(PrimitiveValueType || {});
167
+
168
+ // src/models.ts
169
+ var models_exports = {};
170
+ __export(models_exports, {
171
+ Model: () => Model,
172
+ isNullRestInfo: () => isNullRestInfo,
173
+ noFetch: () => noFetch
174
+ });
175
+ var import_merge4 = __toESM(require("lodash/merge.js"), 1);
176
+ var import_zod2 = __toESM(require("zod"), 1);
177
+
178
+ // src/serialization.ts
179
+ var import_merge = __toESM(require("lodash/merge.js"), 1);
180
+ var isModelInstance = (obj) => {
181
+ return Boolean(obj.toObj);
182
+ };
183
+ var _getValue = async (value) => {
184
+ if (value === void 0) {
185
+ return void 0;
186
+ }
187
+ if (value === null) {
188
+ return null;
189
+ }
190
+ const type = typeof value;
191
+ const asFunction = value;
192
+ if (type === "function") {
193
+ return _getValue(await asFunction());
194
+ }
195
+ if (isModelInstance(value)) {
196
+ return _getValue(await value.toObj());
197
+ }
198
+ const asDate = value;
199
+ if (type === "object" && asDate.toISOString) {
200
+ return _getValue(asDate.toISOString());
201
+ }
202
+ return value;
203
+ };
204
+ var toJsonAble = (keyToFunc) => () => {
205
+ return Object.entries(keyToFunc).reduce(async (acc, [key, value]) => {
206
+ const realAcc = await acc;
207
+ const trueValue = await _getValue(await value);
208
+ if (trueValue === void 0) {
209
+ return realAcc;
210
+ }
211
+ return (0, import_merge.default)(realAcc, { [key]: trueValue });
212
+ }, Promise.resolve({}));
213
+ };
214
+
215
+ // src/validation.ts
216
+ var validation_exports = {};
217
+ __export(validation_exports, {
218
+ aggregateValidator: () => aggregateValidator,
219
+ arrayType: () => arrayType,
220
+ choices: () => choices,
221
+ createModelValidator: () => createModelValidator,
222
+ createPropertyValidator: () => createPropertyValidator,
223
+ emptyValidator: () => emptyValidator,
224
+ isArray: () => isArray,
225
+ isBoolean: () => isBoolean,
226
+ isDate: () => isDate,
227
+ isInteger: () => isInteger,
228
+ isNumber: () => isNumber,
229
+ isObject: () => isObject,
230
+ isRequired: () => isRequired,
231
+ isString: () => isString,
232
+ isType: () => isType,
233
+ isValid: () => isValid,
234
+ isValidUuid: () => isValidUuid,
235
+ maxNumber: () => maxNumber,
236
+ maxTextLength: () => maxTextLength,
237
+ meetsRegex: () => meetsRegex,
238
+ minNumber: () => minNumber,
239
+ minTextLength: () => minTextLength,
240
+ multiValidator: () => multiValidator,
241
+ objectValidator: () => objectValidator,
242
+ optionalValidator: () => optionalValidator,
243
+ referenceTypeMatch: () => referenceTypeMatch
244
+ });
245
+ var import_isEmpty = __toESM(require("lodash/isEmpty.js"), 1);
246
+ var import_merge2 = __toESM(require("lodash/merge.js"), 1);
247
+ var import_flatMap = __toESM(require("lodash/flatMap.js"), 1);
248
+ var import_get = __toESM(require("lodash/get.js"), 1);
249
+
250
+ // src/utils.ts
251
+ var import_async_lock = __toESM(require("async-lock"), 1);
252
+
253
+ // node_modules/uuid/dist-node/stringify.js
254
+ var byteToHex = [];
255
+ for (let i = 0; i < 256; ++i) {
256
+ byteToHex.push((i + 256).toString(16).slice(1));
257
+ }
258
+ function unsafeStringify(arr, offset = 0) {
259
+ 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();
260
+ }
261
+
262
+ // node_modules/uuid/dist-node/rng.js
263
+ var rnds8 = new Uint8Array(16);
264
+ function rng() {
265
+ return crypto.getRandomValues(rnds8);
266
+ }
267
+
268
+ // node_modules/uuid/dist-node/v4.js
269
+ function v4(options, buf, offset) {
270
+ if (!buf && !options && crypto.randomUUID) {
271
+ return crypto.randomUUID();
272
+ }
273
+ return _v4(options, buf, offset);
274
+ }
275
+ function _v4(options, buf, offset) {
276
+ options = options || {};
277
+ const rnds = options.random ?? options.rng?.() ?? rng();
278
+ if (rnds.length < 16) {
279
+ throw new Error("Random bytes length must be >= 16");
280
+ }
281
+ rnds[6] = rnds[6] & 15 | 64;
282
+ rnds[8] = rnds[8] & 63 | 128;
283
+ if (buf) {
284
+ offset = offset || 0;
285
+ if (offset < 0 || offset + 16 > buf.length) {
286
+ throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);
287
+ }
288
+ for (let i = 0; i < 16; ++i) {
289
+ buf[offset + i] = rnds[i];
290
+ }
291
+ return buf;
292
+ }
293
+ return unsafeStringify(rnds);
294
+ }
295
+ var v4_default = v4;
296
+
297
+ // src/utils.ts
298
+ var import_get_random_values = __toESM(require("get-random-values"), 1);
299
+ var getRandomValues = () => {
300
+ const array = new Uint8Array(1);
301
+ if (typeof window !== "undefined") {
302
+ if (window.crypto) {
303
+ return window.crypto.getRandomValues(array);
304
+ }
305
+ if (window.msCrypto) {
306
+ return window.msCrypto.getRandomValues(array);
307
+ }
308
+ }
309
+ return (0, import_get_random_values.default)(array);
310
+ };
311
+ var toTitleCase = (string) => {
312
+ return `${string.slice(0, 1).toUpperCase()}${string.slice(1)}`;
313
+ };
314
+ var PluralEndings = /* @__PURE__ */ ((PluralEndings2) => {
315
+ PluralEndings2["ves"] = "fe";
316
+ PluralEndings2["ies"] = "y";
317
+ PluralEndings2["i"] = "us";
318
+ PluralEndings2["zes"] = "ze";
319
+ PluralEndings2["ses"] = "s";
320
+ PluralEndings2["es"] = "e";
321
+ PluralEndings2["s"] = "";
322
+ return PluralEndings2;
323
+ })(PluralEndings || {});
324
+ var _singularizingRe = new RegExp(
325
+ `(${Object.keys(PluralEndings).join("|")})$`,
326
+ "u"
327
+ );
328
+ var singularize = (word) => {
329
+ return word.replace(_singularizingRe, (r) => PluralEndings[r]);
330
+ };
331
+ var createHeadAndTail = (values, joiner) => {
332
+ const head = values[0];
333
+ const tail = values.slice(1).join(joiner);
334
+ return [head, tail];
335
+ };
336
+ var flowFindFirst = (funcs) => (input) => {
337
+ return funcs.reduce((acc, func) => {
338
+ if (acc) {
339
+ return acc;
340
+ }
341
+ return func(input);
342
+ }, void 0);
343
+ };
344
+ var memoizeSync = (method) => {
345
+ let value = void 0;
346
+ let called = false;
347
+ return (...args) => {
348
+ if (!called) {
349
+ called = true;
350
+ value = method(...args);
351
+ }
352
+ return value;
353
+ };
354
+ };
355
+ var memoizeAsync = (method) => {
356
+ const key = v4_default();
357
+ const lock = new import_async_lock.default();
358
+ let value = void 0;
359
+ let called = false;
360
+ return async (...args) => {
361
+ return lock.acquire(key, async () => {
362
+ if (!called) {
363
+ called = true;
364
+ value = await method(...args);
365
+ }
366
+ return value;
367
+ });
368
+ };
369
+ };
370
+ var createUuid = v4_default;
371
+
372
+ // src/validation.ts
373
+ var multiValidator = (validators) => {
374
+ const flow4 = flowFindFirst(
375
+ validators
376
+ );
377
+ return flow4;
378
+ };
379
+ var filterEmpty = (array) => {
380
+ return array.filter((x) => x);
381
+ };
382
+ var _trueOrError = (method, error) => (value) => {
383
+ if (method(value) === false) {
384
+ return error;
385
+ }
386
+ return void 0;
387
+ };
388
+ var _typeOrError = (type, errorMessage) => (value) => {
389
+ if (typeof value !== type) {
390
+ return errorMessage;
391
+ }
392
+ return void 0;
393
+ };
394
+ var isType = (type) => (value) => {
395
+ return _typeOrError(type, `Must be a ${type}`)(value);
396
+ };
397
+ var isNumber = isType("number");
398
+ var isInteger = _trueOrError(Number.isInteger, "Must be an integer");
399
+ var isObject = multiValidator([
400
+ isType("object"),
401
+ (x) => Array.isArray(x) ? "Must be an object, but got an array" : void 0
402
+ ]);
403
+ var isBoolean = isType("boolean");
404
+ var isString = isType("string");
405
+ var isArray = _trueOrError(
406
+ (v) => Array.isArray(v),
407
+ "Value is not an array"
408
+ );
409
+ var PRIMITIVE_TO_SPECIAL_TYPE_VALIDATOR = {
410
+ ["boolean" /* boolean */]: isBoolean,
411
+ ["string" /* string */]: isString,
412
+ ["integer" /* integer */]: isInteger,
413
+ ["number" /* number */]: isNumber,
414
+ ["object" /* object */]: isObject
415
+ };
416
+ var arrayType = (type) => (value) => {
417
+ const arrayError = isArray(value);
418
+ if (arrayError) {
419
+ return arrayError;
420
+ }
421
+ const validator = PRIMITIVE_TO_SPECIAL_TYPE_VALIDATOR[type] || isType(type);
422
+ return value.reduce(
423
+ (acc, v) => {
424
+ if (acc) {
425
+ return acc;
426
+ }
427
+ return validator(v);
428
+ },
429
+ void 0
430
+ );
431
+ };
432
+ var meetsRegex = (regex, flags, errorMessage = "Format was invalid") => (value) => {
433
+ const reg = new RegExp(regex, flags);
434
+ return _trueOrError((v) => reg.test(v), errorMessage)(value);
435
+ };
436
+ var choices = (choiceArray) => (value) => {
437
+ if (Array.isArray(value)) {
438
+ const bad = value.find((v) => !choiceArray.includes(v));
439
+ if (bad) {
440
+ return `${bad} is not a valid choice`;
441
+ }
442
+ } else {
443
+ if (!choiceArray.includes(value)) {
444
+ return `${value} is not a valid choice`;
445
+ }
446
+ }
447
+ return void 0;
448
+ };
449
+ var isDate = (value) => {
450
+ if (!value) {
451
+ return "Date value is empty";
452
+ }
453
+ if (!value.toISOString) {
454
+ return "Value is not a date";
455
+ }
456
+ return void 0;
457
+ };
458
+ var isRequired = (value) => {
459
+ if (value === true || value === false) {
460
+ return void 0;
461
+ }
462
+ if (isNumber(value) === void 0) {
463
+ return void 0;
464
+ }
465
+ const empty = (0, import_isEmpty.default)(value);
466
+ if (empty) {
467
+ if (isDate(value)) {
468
+ return "A value is required";
469
+ }
470
+ }
471
+ return void 0;
472
+ };
473
+ var maxNumber = (max) => (value) => {
474
+ const numberError = isNumber(value);
475
+ if (numberError) {
476
+ return numberError;
477
+ }
478
+ if (value && value > max) {
479
+ return `The maximum is ${max}`;
480
+ }
481
+ return void 0;
482
+ };
483
+ var minNumber = (min) => (value) => {
484
+ const numberError = isNumber(value);
485
+ if (numberError) {
486
+ return numberError;
487
+ }
488
+ if (value && value < min) {
489
+ return `The minimum is ${min}`;
490
+ }
491
+ return void 0;
492
+ };
493
+ var maxTextLength = (max) => (value) => {
494
+ const stringError = isString(value);
495
+ if (stringError) {
496
+ return stringError;
497
+ }
498
+ if (value && value.length > max) {
499
+ return `The maximum length is ${max}`;
500
+ }
501
+ return void 0;
502
+ };
503
+ var minTextLength = (min) => (value) => {
504
+ const stringError = isString(value);
505
+ if (stringError) {
506
+ return stringError;
507
+ }
508
+ if (value && value.length < min) {
509
+ return `The minimum length is ${min}`;
510
+ }
511
+ return void 0;
512
+ };
513
+ var aggregateValidator = (value, methodOrMethods) => {
514
+ const toDo = Array.isArray(methodOrMethods) ? methodOrMethods : [methodOrMethods];
515
+ const _aggregativeValidator = async (model, instanceData, propertyConfiguration) => {
516
+ const values = await Promise.all(
517
+ toDo.map((method) => {
518
+ return method(value, model, instanceData, propertyConfiguration);
519
+ })
520
+ );
521
+ return filterEmpty(values);
522
+ };
523
+ return _aggregativeValidator;
524
+ };
525
+ var emptyValidator = () => void 0;
526
+ var _boolChoice = (method) => (configValue) => {
527
+ const func = method(configValue);
528
+ const validatorWrapper = func;
529
+ return validatorWrapper;
530
+ };
531
+ var simpleFuncWrap = (validator) => () => {
532
+ return validator;
533
+ };
534
+ var includeOrDont = (method) => (configValue) => {
535
+ if (configValue === false) {
536
+ return emptyValidator;
537
+ }
538
+ const func = method();
539
+ const validatorWrapper = func;
540
+ return validatorWrapper;
541
+ };
542
+ var CONFIG_TO_VALIDATE_METHOD = () => ({
543
+ required: includeOrDont(simpleFuncWrap(isRequired)),
544
+ isInteger: _boolChoice(simpleFuncWrap(isInteger)),
545
+ isNumber: _boolChoice(simpleFuncWrap(isNumber)),
546
+ isString: _boolChoice(simpleFuncWrap(isString)),
547
+ isArray: _boolChoice(simpleFuncWrap(isArray)),
548
+ isBoolean: _boolChoice(simpleFuncWrap(isBoolean)),
549
+ choices: _boolChoice(choices)
550
+ });
551
+ var createPropertyValidator = (valueGetter, config) => {
552
+ const _propertyValidator = async (model, instanceData, propertyConfiguration) => {
553
+ return Promise.resolve().then(async () => {
554
+ const configToValidateMethod = CONFIG_TO_VALIDATE_METHOD();
555
+ if (!config) {
556
+ config = {};
557
+ }
558
+ const validators = [
559
+ ...Object.entries(config).map(([key, value2]) => {
560
+ const method = configToValidateMethod[key];
561
+ if (method) {
562
+ return method(value2);
563
+ }
564
+ return emptyValidator;
565
+ }),
566
+ ...config.validators ? config.validators : []
567
+ ].filter((x) => x);
568
+ const value = await valueGetter();
569
+ const isRequiredValue = config.required ? true : validators.includes(isRequired);
570
+ if (!value && !isRequiredValue) {
571
+ return [];
572
+ }
573
+ const validator = aggregateValidator(value, validators);
574
+ const errors = await validator(model, instanceData, propertyConfiguration);
575
+ return [...new Set((0, import_flatMap.default)(errors))];
576
+ });
577
+ };
578
+ return _propertyValidator;
579
+ };
580
+ var createModelValidator = (validators, modelValidators) => {
581
+ const _modelValidator = async (instance, propertyConfiguration) => {
582
+ return Promise.resolve().then(async () => {
583
+ if (!instance) {
584
+ throw new Error(`Instance cannot be empty`);
585
+ }
586
+ const model = instance.getModel();
587
+ const keysAndFunctions = Object.entries(validators);
588
+ const instanceData = await instance.toObj();
589
+ const propertyValidationErrors = await Promise.all(
590
+ keysAndFunctions.map(async ([key, validator]) => {
591
+ return [
592
+ key,
593
+ await validator(model, instanceData, propertyConfiguration)
594
+ ];
595
+ })
596
+ );
597
+ const modelValidationErrors = (await Promise.all(
598
+ modelValidators ? modelValidators.map((validator) => {
599
+ return validator(model, instanceData, propertyConfiguration);
600
+ }) : []
601
+ )).filter((x) => x);
602
+ const propertyErrors = propertyValidationErrors.filter(([, errors]) => Boolean(errors) && errors.length > 0).reduce((acc, [key, errors]) => {
603
+ return (0, import_merge2.default)(acc, { [String(key)]: errors });
604
+ }, {});
605
+ const final = modelValidationErrors.length > 0 ? (0, import_merge2.default)(propertyErrors, { overall: modelValidationErrors }) : propertyErrors;
606
+ if ((0, import_isEmpty.default)(final)) {
607
+ return void 0;
608
+ }
609
+ return final;
610
+ });
611
+ };
612
+ return _modelValidator;
613
+ };
614
+ var isValid = (errors) => {
615
+ return Object.keys(errors).length < 1;
616
+ };
617
+ var referenceTypeMatch = (referencedModel) => {
618
+ return (value) => {
619
+ const theType = typeof value;
620
+ switch (theType) {
621
+ case "string":
622
+ case "number":
623
+ case "undefined":
624
+ return void 0;
625
+ default:
626
+ break;
627
+ }
628
+ if (value === null) {
629
+ return void 0;
630
+ }
631
+ const model = typeof referencedModel === "function" ? referencedModel() : referencedModel;
632
+ const eModel = model.getName();
633
+ const aModel = value.getModel().getName();
634
+ if (eModel !== aModel) {
635
+ return `Model should be ${eModel} instead, received ${aModel}`;
636
+ }
637
+ return void 0;
638
+ };
639
+ };
640
+ var objectValidator = ({
641
+ required,
642
+ keyToValidators
643
+ }) => {
644
+ return (obj) => {
645
+ if (!obj) {
646
+ if (required) {
647
+ return "Must include a value";
648
+ }
649
+ return void 0;
650
+ }
651
+ const isNotObj = isObject(obj);
652
+ if (isNotObj) {
653
+ return isNotObj;
654
+ }
655
+ return Object.entries(keyToValidators).reduce((acc, [key, validator]) => {
656
+ const theValidator = Array.isArray(validator) ? multiValidator(validator) : validator;
657
+ const value = (0, import_get.default)(obj, key);
658
+ const error = theValidator(value);
659
+ if (error) {
660
+ return acc.concat(`${key}: ${error}`);
661
+ }
662
+ return acc;
663
+ }, []).join(", ") || void 0;
664
+ };
665
+ };
666
+ var optionalValidator = (validator) => {
667
+ return (v) => {
668
+ if (v === void 0 || v === null) {
669
+ return void 0;
670
+ }
671
+ return validator(v);
672
+ };
673
+ };
674
+ 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;
675
+ var isValidUuid = (uuid) => {
676
+ const stringError = isString(uuid);
677
+ if (stringError) {
678
+ return stringError;
679
+ }
680
+ return meetsRegex(UUID_VALIDATOR, "g", "Invalid UUID format")(uuid);
681
+ };
682
+
683
+ // src/lib.ts
684
+ var import_openapi_types = require("openapi-types");
685
+ var import_kebabCase = __toESM(require("lodash/kebabCase.js"), 1);
686
+ var import_flow = __toESM(require("lodash/flow.js"), 1);
687
+ var import_merge3 = __toESM(require("lodash/merge.js"), 1);
688
+ var import_get2 = __toESM(require("lodash/get.js"), 1);
689
+ var import_zod = require("zod");
690
+ var HttpMethods = import_openapi_types.OpenAPIV3.HttpMethods;
691
+ var NULL_ENDPOINT = "NULL";
692
+ var NULL_METHOD = HttpMethods.HEAD;
693
+ var ID_KEY = ":id";
694
+ var getValueForReferencedModel = async (modelInstance, path) => {
695
+ const [head, tail] = createHeadAndTail(path.split("."), ".");
696
+ if (!tail) {
697
+ return modelInstance.getReferences()[head]();
698
+ }
699
+ const modelReference = await modelInstance.get[head]();
700
+ if (modelReference.toObj) {
701
+ const [nestedHead, nestedTail] = createHeadAndTail(tail.split("."), ".");
702
+ const value = await modelReference.get[nestedHead]();
703
+ if (nestedTail) {
704
+ return (0, import_get2.default)(value, nestedTail);
705
+ }
706
+ return value;
707
+ }
708
+ return (0, import_get2.default)(modelReference, tail);
709
+ };
710
+ var getValueForModelInstance = async (modelInstance, path) => {
711
+ const [head, tail] = createHeadAndTail(path.split("."), ".");
712
+ const value = await modelInstance.get[head]();
713
+ return tail ? (0, import_get2.default)(value, tail) : value;
714
+ };
715
+ var isReferencedProperty = (modelInstance, key) => {
716
+ return modelInstance.getReferences()[key];
717
+ };
718
+ var getCommonTextValidators = (config) => {
719
+ return [
720
+ getValidatorFromConfigElseEmpty(config?.maxLength, maxTextLength),
721
+ getValidatorFromConfigElseEmpty(config?.minLength, minTextLength)
722
+ ];
723
+ };
724
+ var getValidatorFromConfigElseEmpty = (input, validatorGetter) => {
725
+ if (input !== void 0) {
726
+ const validator = validatorGetter(input);
727
+ return validator;
728
+ }
729
+ return emptyValidator;
730
+ };
731
+ var getCommonNumberValidators = (config) => {
732
+ return [
733
+ getValidatorFromConfigElseEmpty(config?.minValue, minNumber),
734
+ getValidatorFromConfigElseEmpty(config?.maxValue, maxNumber)
735
+ ];
736
+ };
737
+ var mergeValidators = (config, ...validators) => {
738
+ return [...validators, ...config?.validators ? config.validators : []];
739
+ };
740
+ var isModelInstance2 = (obj) => {
741
+ return Boolean(obj && obj.getPrimaryKey);
742
+ };
743
+ var getModelName = (namespace, pluralName) => {
744
+ return `${namespace}/${pluralName}`;
745
+ };
746
+ var buildValidEndpoint = (...components) => {
747
+ const suffix = components.map((x) => {
748
+ if (x === ID_KEY) {
749
+ return x;
750
+ }
751
+ return (0, import_kebabCase.default)(x);
752
+ }).map((s) => s.toLowerCase()).join("/");
753
+ return `/${suffix}`;
754
+ };
755
+ var _generateRestInfo = (method, withId, ...additional) => (pluralName, namespace) => (existing) => {
756
+ if (existing) {
757
+ return {
758
+ // Default add security, then override it.
759
+ security: {},
760
+ ...existing
761
+ };
762
+ }
763
+ const endpoint = withId ? buildValidEndpoint(namespace, pluralName, ID_KEY) : buildValidEndpoint(namespace, pluralName, ...additional);
764
+ return {
765
+ method,
766
+ endpoint,
767
+ // We cannot auto create security.
768
+ security: {}
769
+ };
770
+ };
771
+ var _apiMethodToRestInfoGenerator = {
772
+ ["create" /* create */]: _generateRestInfo(HttpMethods.POST, false),
773
+ ["retrieve" /* retrieve */]: _generateRestInfo(HttpMethods.GET, true),
774
+ ["update" /* update */]: _generateRestInfo(HttpMethods.PUT, true),
775
+ ["delete" /* delete */]: _generateRestInfo(HttpMethods.DELETE, true),
776
+ ["search" /* search */]: _generateRestInfo(HttpMethods.POST, false, "search")
777
+ };
778
+ var getNullRestInfo = () => {
779
+ return {
780
+ endpoint: NULL_ENDPOINT,
781
+ method: NULL_METHOD,
782
+ security: {}
783
+ };
784
+ };
785
+ var _fillOutRestInfo = (pluralName, namespace, partial, nullRest) => {
786
+ const finishedRestInfo = Object.entries(
787
+ ApiMethod
788
+ ).reduce(
789
+ (acc, [, method]) => {
790
+ const existing = partial && partial.rest && partial.rest[method] ? partial.rest[method] : void 0;
791
+ const restInfo = _apiMethodToRestInfoGenerator[method](
792
+ pluralName,
793
+ namespace
794
+ )(existing);
795
+ return (0, import_merge3.default)(acc, {
796
+ [method]: restInfo
797
+ });
798
+ },
799
+ nullRest
800
+ );
801
+ return {
802
+ noPublish: false,
803
+ onlyPublish: [],
804
+ rest: finishedRestInfo,
805
+ createOnlyOne: partial?.createOnlyOne || false
806
+ };
807
+ };
808
+ var populateApiInformation = (pluralName, namespace, partial) => {
809
+ const nullRest = {
810
+ delete: getNullRestInfo(),
811
+ search: getNullRestInfo(),
812
+ update: getNullRestInfo(),
813
+ retrieve: getNullRestInfo(),
814
+ create: getNullRestInfo()
815
+ };
816
+ if (!partial) {
817
+ return _fillOutRestInfo(pluralName, namespace, partial, nullRest);
818
+ }
819
+ if (partial.noPublish) {
820
+ return {
821
+ onlyPublish: [],
822
+ noPublish: true,
823
+ rest: nullRest,
824
+ createOnlyOne: false
825
+ };
826
+ }
827
+ const rest = partial.rest || {};
828
+ if (partial.onlyPublish && partial.onlyPublish.length > 0) {
829
+ return partial.onlyPublish.reduce(
830
+ (acc, method) => {
831
+ const restInfo = _apiMethodToRestInfoGenerator[method](
832
+ pluralName,
833
+ namespace
834
+ )(rest[method]);
835
+ return (0, import_merge3.default)(acc, {
836
+ rest: {
837
+ [method]: restInfo
838
+ }
839
+ });
840
+ },
841
+ {
842
+ noPublish: false,
843
+ onlyPublish: partial.onlyPublish,
844
+ createOnlyOne: Boolean(partial.createOnlyOne),
845
+ rest: nullRest
846
+ }
847
+ );
848
+ }
849
+ return _fillOutRestInfo(pluralName, namespace, partial, nullRest);
850
+ };
851
+ var createZodForProperty = (propertyType, config) => () => {
852
+ const myConfig = config || {};
853
+ const provided = myConfig.zod;
854
+ if (provided) {
855
+ return provided;
856
+ }
857
+ const _getZodForPropertyType = (pt) => {
858
+ if (myConfig.choices) {
859
+ return import_zod.z.enum(myConfig.choices);
860
+ }
861
+ switch (pt) {
862
+ case "UniqueId":
863
+ return import_zod.z.string();
864
+ case "Date":
865
+ case "Datetime":
866
+ return import_zod.z.union([import_zod.z.string(), import_zod.z.date()]);
867
+ case "Integer":
868
+ return import_zod.z.number().int();
869
+ case "Number":
870
+ return import_zod.z.number();
871
+ case "Boolean":
872
+ return import_zod.z.boolean();
873
+ case "Array":
874
+ return import_zod.z.array(import_zod.z.any());
875
+ case "Object":
876
+ return import_zod.z.object().loose();
877
+ case "Email":
878
+ return import_zod.z.email();
879
+ case "Text":
880
+ case "BigText":
881
+ return import_zod.z.string();
882
+ case "ModelReference":
883
+ return import_zod.z.union([import_zod.z.string(), import_zod.z.number()]);
884
+ default:
885
+ return import_zod.z.any();
886
+ }
887
+ };
888
+ const baseSchema = _getZodForPropertyType(propertyType);
889
+ const choices2 = config?.choices;
890
+ const schemaFromChoices = choices2 && Array.isArray(choices2) && choices2.length > 0 ? import_zod.z.union(choices2.map((c) => import_zod.z.literal(c))) : baseSchema;
891
+ const finalSchema = (0, import_flow.default)([
892
+ (s) => typeof myConfig.minValue === "number" ? s.min(myConfig.minValue) : s,
893
+ (s) => typeof myConfig.maxValue === "number" ? s.max(myConfig.maxValue) : s,
894
+ (s) => typeof myConfig.minLength === "number" ? s.min(myConfig.minLength) : s,
895
+ (s) => typeof myConfig.maxLength === "number" ? s.max(myConfig.maxLength) : s,
896
+ (s) => myConfig.defaultValue !== void 0 ? s.default(myConfig.defaultValue) : s,
897
+ (s) => myConfig.required ? s : s.optional(),
898
+ // Attach description for Zod consumers and OpenAPI generators.
899
+ (s) => {
900
+ if (myConfig.description) {
901
+ if (typeof s.openapi === "function") {
902
+ return s.openapi({ description: myConfig.description });
903
+ }
904
+ return s.meta ? s.meta({ description: myConfig.description }) : s.describe(myConfig.description);
905
+ }
906
+ return s;
907
+ }
908
+ ])(schemaFromChoices);
909
+ return finalSchema;
910
+ };
911
+
912
+ // src/models.ts
913
+ var _defaultOptions = () => ({
914
+ instanceCreatedCallback: void 0
915
+ });
916
+ var _convertOptions = (options) => {
917
+ const r = (0, import_merge4.default)({}, _defaultOptions(), options);
918
+ return r;
919
+ };
920
+ var _addDescription = (schema, description) => {
921
+ if (!description) {
922
+ return schema;
923
+ }
924
+ if (typeof schema.openapi === "function") {
925
+ return schema.openapi({ description });
926
+ }
927
+ return schema.meta ? schema.meta({ description }) : schema.describe(description);
928
+ };
929
+ var _createZod = (modelDefinition) => {
930
+ if (modelDefinition.schema) {
931
+ return _addDescription(modelDefinition.schema, modelDefinition.description);
932
+ }
933
+ const properties = Object.entries(modelDefinition.properties).reduce(
934
+ (acc, [key, property2]) => {
935
+ const asProp = property2;
936
+ return (0, import_merge4.default)(acc, {
937
+ [key]: asProp.getZod()
938
+ });
939
+ },
940
+ {}
941
+ );
942
+ const obj = import_zod2.default.object(properties);
943
+ return _addDescription(obj, modelDefinition.description);
944
+ };
945
+ var _toModelDefinition = (minimal) => {
946
+ return {
947
+ singularName: singularize(minimal.pluralName),
948
+ displayName: toTitleCase(minimal.pluralName),
949
+ description: "",
950
+ primaryKeyName: "id",
951
+ modelValidators: [],
952
+ schema: _createZod(minimal),
953
+ ...minimal
954
+ };
955
+ };
956
+ var _validateModelDefinition = (modelDefinition) => {
957
+ const primaryKeyName = modelDefinition.primaryKeyName || "id";
958
+ const primaryKeyProperty = (
959
+ // @ts-ignore
960
+ modelDefinition.properties[primaryKeyName]
961
+ );
962
+ if (!primaryKeyProperty) {
963
+ throw new Error(`Property missing for primaryKey named ${primaryKeyName}`);
964
+ }
965
+ if (!modelDefinition.pluralName) {
966
+ throw new Error(`Must include pluralName for model.`);
967
+ }
968
+ if (!modelDefinition.namespace) {
969
+ throw new Error(`Must include namespace for model.`);
970
+ }
971
+ };
972
+ var Model = (minimalModelDefinitions, options) => {
973
+ _validateModelDefinition(minimalModelDefinitions);
974
+ let model = null;
975
+ const theOptions = _convertOptions(options);
976
+ const modelDefinition = _toModelDefinition(minimalModelDefinitions);
977
+ const getPrimaryKeyName = () => modelDefinition.primaryKeyName;
978
+ const getPrimaryKey = (loadedInternals) => {
979
+ const property2 = loadedInternals.get[getPrimaryKeyName()];
980
+ return property2();
981
+ };
982
+ const create = (instanceValues) => {
983
+ let instance = null;
984
+ const startingInternals = {
985
+ get: {},
986
+ validators: {},
987
+ references: {}
988
+ };
989
+ const prop = Object.entries(
990
+ modelDefinition.properties
991
+ );
992
+ const loadedInternals = prop.reduce(
993
+ (acc, [key, property2]) => {
994
+ const propertyGetter = memoizeSync(
995
+ () => property2.createGetter(
996
+ //@ts-ignore
997
+ instanceValues[key],
998
+ instanceValues,
999
+ // NOTE: By the time it gets here, it has already been implemented.
1000
+ instance
1001
+ )()
1002
+ );
1003
+ const propertyValidator = property2.getValidator(propertyGetter);
1004
+ const fleshedOutInstanceProperties = {
1005
+ get: {
1006
+ [key]: () => propertyGetter()
1007
+ },
1008
+ validators: {
1009
+ [key]: propertyValidator
1010
+ }
1011
+ };
1012
+ const asReferenced = property2;
1013
+ const referencedProperty = asReferenced.getReferencedId ? {
1014
+ references: {
1015
+ [key]: () => asReferenced.getReferencedId(
1016
+ // @ts-ignore
1017
+ instanceValues[key]
1018
+ )
1019
+ }
1020
+ } : {};
1021
+ return (0, import_merge4.default)(
1022
+ acc,
1023
+ fleshedOutInstanceProperties,
1024
+ referencedProperty
1025
+ );
1026
+ },
1027
+ startingInternals
1028
+ );
1029
+ const getModel = () => model;
1030
+ const toObj = memoizeAsync(() => {
1031
+ return toJsonAble(loadedInternals.get)();
1032
+ });
1033
+ const validate = memoizeAsync((options2 = {}) => {
1034
+ return Promise.resolve().then(() => {
1035
+ return createModelValidator(
1036
+ loadedInternals.validators,
1037
+ modelDefinition.modelValidators
1038
+ )(instance, options2);
1039
+ });
1040
+ });
1041
+ const getReferences = () => loadedInternals.references;
1042
+ const getValidators = () => loadedInternals.validators;
1043
+ instance = {
1044
+ get: loadedInternals.get,
1045
+ getReferences,
1046
+ getValidators,
1047
+ getModel,
1048
+ toObj,
1049
+ getPrimaryKey: () => getPrimaryKey(loadedInternals),
1050
+ validate
1051
+ };
1052
+ if (theOptions.instanceCreatedCallback) {
1053
+ const toCall = Array.isArray(theOptions.instanceCreatedCallback) ? theOptions.instanceCreatedCallback : [theOptions.instanceCreatedCallback];
1054
+ toCall.map((func) => func(instance));
1055
+ }
1056
+ return instance;
1057
+ };
1058
+ const getApiInfo = memoizeSync(() => {
1059
+ return populateApiInformation(
1060
+ modelDefinition.pluralName,
1061
+ modelDefinition.namespace,
1062
+ modelDefinition.api
1063
+ );
1064
+ });
1065
+ model = {
1066
+ /**
1067
+ * Creates a model instance.
1068
+ */
1069
+ create,
1070
+ getName: () => getModelName(modelDefinition.namespace, modelDefinition.pluralName),
1071
+ getModelDefinition: memoizeSync(() => modelDefinition),
1072
+ getPrimaryKey,
1073
+ getApiInfo
1074
+ };
1075
+ return model;
1076
+ };
1077
+ var isNullRestInfo = (restInfo) => {
1078
+ return restInfo.method === NULL_METHOD && restInfo.endpoint === NULL_ENDPOINT;
1079
+ };
1080
+ var noFetch = () => {
1081
+ return Promise.resolve(void 0);
1082
+ };
1083
+
1084
+ // src/properties.ts
1085
+ var properties_exports = {};
1086
+ __export(properties_exports, {
1087
+ AdvancedModelReferenceProperty: () => AdvancedModelReferenceProperty,
1088
+ ArrayProperty: () => ArrayProperty,
1089
+ BigTextProperty: () => BigTextProperty,
1090
+ BooleanProperty: () => BooleanProperty,
1091
+ ConstantValueProperty: () => ConstantValueProperty,
1092
+ DateProperty: () => DateProperty,
1093
+ DatetimeProperty: () => DatetimeProperty,
1094
+ DenormalizedIntegerProperty: () => DenormalizedIntegerProperty,
1095
+ DenormalizedNumberProperty: () => DenormalizedNumberProperty,
1096
+ DenormalizedProperty: () => DenormalizedProperty,
1097
+ DenormalizedTextProperty: () => DenormalizedTextProperty,
1098
+ EmailProperty: () => EmailProperty,
1099
+ IntegerProperty: () => IntegerProperty,
1100
+ ModelReferenceProperty: () => ModelReferenceProperty,
1101
+ NaturalIdProperty: () => NaturalIdProperty,
1102
+ NumberProperty: () => NumberProperty,
1103
+ ObjectProperty: () => ObjectProperty,
1104
+ PrimaryKeyUuidProperty: () => PrimaryKeyUuidProperty,
1105
+ Property: () => Property,
1106
+ SingleTypeArrayProperty: () => SingleTypeArrayProperty,
1107
+ TextProperty: () => TextProperty,
1108
+ UuidProperty: () => UuidProperty,
1109
+ YearProperty: () => YearProperty
1110
+ });
1111
+ var import_merge5 = __toESM(require("lodash/merge.js"), 1);
1112
+ var import_get3 = __toESM(require("lodash/get.js"), 1);
1113
+ var MAX_YEAR = 3e3;
1114
+ var EMAIL_REGEX = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/u;
1115
+ var Property = (propertyType, config = {}, additionalMetadata = {}) => {
1116
+ if (!propertyType && !config?.typeOverride) {
1117
+ throw new Error(`Property type must be provided.`);
1118
+ }
1119
+ if (config?.typeOverride) {
1120
+ propertyType = config.typeOverride;
1121
+ }
1122
+ const getConstantValue = () => config?.value !== void 0 ? config.value : void 0;
1123
+ const getDefaultValue = () => config?.defaultValue !== void 0 ? config.defaultValue : void 0;
1124
+ const getChoices = () => config?.choices || [];
1125
+ const lazyLoadMethod = config?.lazyLoadMethod || false;
1126
+ const valueSelector = config?.valueSelector || ((x) => x);
1127
+ if (typeof valueSelector !== "function") {
1128
+ throw new Error(`valueSelector must be a function`);
1129
+ }
1130
+ const createGetter = (instanceValue, modelData, instance) => {
1131
+ const constantValue = getConstantValue();
1132
+ if (constantValue !== void 0) {
1133
+ return () => constantValue;
1134
+ }
1135
+ const defaultValue = getDefaultValue();
1136
+ if (defaultValue !== void 0 && (instanceValue === null || instanceValue === void 0)) {
1137
+ return () => defaultValue;
1138
+ }
1139
+ const method = lazyLoadMethod ? lazyLoadMethod : config.lazyLoadMethodAtomic ? memoizeAsync(config.lazyLoadMethodAtomic) : typeof instanceValue === "function" ? instanceValue : () => instanceValue;
1140
+ const valueGetter = memoizeSync(() => {
1141
+ const result = method(
1142
+ instanceValue,
1143
+ modelData,
1144
+ // @ts-ignore
1145
+ instance
1146
+ );
1147
+ return valueSelector(result);
1148
+ });
1149
+ return valueGetter;
1150
+ };
1151
+ const getValidator = (valueGetter) => {
1152
+ const validator = createPropertyValidator(valueGetter, config);
1153
+ const _propertyValidatorWrapper = async (model, instanceData, propertyConfiguration) => {
1154
+ return validator(model, instanceData, propertyConfiguration);
1155
+ };
1156
+ return _propertyValidatorWrapper;
1157
+ };
1158
+ const getZod = () => {
1159
+ const provided = config?.zod;
1160
+ if (provided) {
1161
+ return provided;
1162
+ }
1163
+ return createZodForProperty(propertyType, config)();
1164
+ };
1165
+ const propertyInstance = {
1166
+ ...additionalMetadata,
1167
+ getConfig: () => config || {},
1168
+ getChoices,
1169
+ getDefaultValue,
1170
+ getConstantValue,
1171
+ getPropertyType: () => propertyType,
1172
+ createGetter,
1173
+ getZod,
1174
+ getValidator
1175
+ };
1176
+ return propertyInstance;
1177
+ };
1178
+ var isDate2 = (value) => {
1179
+ if (value === null) {
1180
+ return false;
1181
+ }
1182
+ return typeof value === "object" && value.toISOString;
1183
+ };
1184
+ var DateProperty = (config = {}, additionalMetadata = {}) => Property(
1185
+ "Date" /* Date */,
1186
+ (0, import_merge5.default)(
1187
+ {
1188
+ lazyLoadMethod: (value) => {
1189
+ if (isDate2(value)) {
1190
+ if (config.formatFunction) {
1191
+ return config.formatFunction(value, config.format);
1192
+ }
1193
+ return value.toISOString().split("T")[0];
1194
+ }
1195
+ if (!value && config?.autoNow) {
1196
+ const date = /* @__PURE__ */ new Date();
1197
+ if (config.formatFunction) {
1198
+ return config.formatFunction(date, config.format);
1199
+ }
1200
+ return date.toISOString().split("T")[0];
1201
+ }
1202
+ return value;
1203
+ }
1204
+ },
1205
+ config
1206
+ ),
1207
+ additionalMetadata
1208
+ );
1209
+ var DatetimeProperty = (config = {}, additionalMetadata = {}) => Property(
1210
+ "Datetime" /* Datetime */,
1211
+ (0, import_merge5.default)(
1212
+ {
1213
+ lazyLoadMethod: (value) => {
1214
+ if (isDate2(value)) {
1215
+ if (config.formatFunction) {
1216
+ return config.formatFunction(value, config.format);
1217
+ }
1218
+ return value.toISOString();
1219
+ }
1220
+ if (!value && config?.autoNow) {
1221
+ const date = /* @__PURE__ */ new Date();
1222
+ if (config.formatFunction) {
1223
+ return config.formatFunction(date, config.format);
1224
+ }
1225
+ return date.toISOString();
1226
+ }
1227
+ return value;
1228
+ }
1229
+ },
1230
+ config
1231
+ ),
1232
+ additionalMetadata
1233
+ );
1234
+ var ArrayProperty = (config = {}, additionalMetadata = {}) => Property(
1235
+ "Array" /* Array */,
1236
+ {
1237
+ defaultValue: [],
1238
+ ...config,
1239
+ isArray: true
1240
+ },
1241
+ additionalMetadata
1242
+ );
1243
+ var SingleTypeArrayProperty = (valueType, config = {}, additionalMetadata = {}) => Property(
1244
+ "Array" /* Array */,
1245
+ {
1246
+ defaultValue: [],
1247
+ ...config,
1248
+ isArray: true,
1249
+ validators: mergeValidators(
1250
+ config,
1251
+ // @ts-ignore
1252
+ arrayType(valueType)
1253
+ )
1254
+ },
1255
+ additionalMetadata
1256
+ );
1257
+ var ObjectProperty = (config = {}, additionalMetadata = {}) => Property(
1258
+ "Object" /* Object */,
1259
+ (0, import_merge5.default)(config, {
1260
+ validators: mergeValidators(config, isType("object"))
1261
+ }),
1262
+ additionalMetadata
1263
+ );
1264
+ var TextProperty = (config = {}, additionalMetadata = {}) => Property(
1265
+ "Text" /* Text */,
1266
+ (0, import_merge5.default)(config, {
1267
+ isString: true,
1268
+ // @ts-ignore
1269
+ validators: mergeValidators(config, ...getCommonTextValidators(config))
1270
+ }),
1271
+ additionalMetadata
1272
+ );
1273
+ var BigTextProperty = (config = {}, additionalMetadata = {}) => Property(
1274
+ "BigText" /* BigText */,
1275
+ (0, import_merge5.default)(config, {
1276
+ isString: true,
1277
+ validators: mergeValidators(
1278
+ config,
1279
+ ...getCommonTextValidators(config)
1280
+ )
1281
+ }),
1282
+ additionalMetadata
1283
+ );
1284
+ var IntegerProperty = (config = {}, additionalMetadata = {}) => Property(
1285
+ "Integer" /* Integer */,
1286
+ (0, import_merge5.default)(config, {
1287
+ isInteger: true,
1288
+ validators: mergeValidators(
1289
+ config,
1290
+ ...getCommonNumberValidators(config)
1291
+ )
1292
+ }),
1293
+ additionalMetadata
1294
+ );
1295
+ var YearProperty = (config = {}, additionalMetadata = {}) => Property(
1296
+ "Integer" /* Integer */,
1297
+ (0, import_merge5.default)(config, {
1298
+ isInteger: true,
1299
+ validators: mergeValidators(
1300
+ config,
1301
+ ...getCommonNumberValidators(config),
1302
+ minNumber(0),
1303
+ maxNumber(MAX_YEAR)
1304
+ )
1305
+ }),
1306
+ additionalMetadata
1307
+ );
1308
+ var NumberProperty = (config = {}, additionalMetadata = {}) => Property(
1309
+ "Number" /* Number */,
1310
+ (0, import_merge5.default)(config, {
1311
+ isNumber: true,
1312
+ validators: mergeValidators(config, ...getCommonNumberValidators(config))
1313
+ }),
1314
+ additionalMetadata
1315
+ );
1316
+ var ConstantValueProperty = (valueType, value, config = {}, additionalMetadata = {}) => Property(
1317
+ valueType,
1318
+ (0, import_merge5.default)(config, {
1319
+ value
1320
+ }),
1321
+ additionalMetadata
1322
+ );
1323
+ var EmailProperty = (config = {}, additionalMetadata = {}) => TextProperty(
1324
+ (0, import_merge5.default)(config, {
1325
+ type: "Email" /* Email */,
1326
+ validators: mergeValidators(config, meetsRegex(EMAIL_REGEX))
1327
+ }),
1328
+ additionalMetadata
1329
+ );
1330
+ var BooleanProperty = (config = {}, additionalMetadata = {}) => Property(
1331
+ "Boolean" /* Boolean */,
1332
+ (0, import_merge5.default)(config, {
1333
+ isBoolean: true
1334
+ }),
1335
+ additionalMetadata
1336
+ );
1337
+ var PrimaryKeyUuidProperty = (config = {}, additionalMetadata = {}) => Property(
1338
+ "UniqueId" /* UniqueId */,
1339
+ (0, import_merge5.default)(config, {
1340
+ required: true,
1341
+ isString: true,
1342
+ validators: mergeValidators(config, isValidUuid),
1343
+ lazyLoadMethod: (value) => {
1344
+ if (!value) {
1345
+ return v4_default();
1346
+ }
1347
+ return value;
1348
+ }
1349
+ }),
1350
+ additionalMetadata
1351
+ );
1352
+ var UuidProperty = (config = {}, additionalMetadata = {}) => Property(
1353
+ "UniqueId" /* UniqueId */,
1354
+ (0, import_merge5.default)(config, {
1355
+ isString: true,
1356
+ validators: mergeValidators(
1357
+ config,
1358
+ config.required ? isValidUuid : optionalValidator(isValidUuid)
1359
+ ),
1360
+ lazyLoadMethod: (value) => {
1361
+ if (!value) {
1362
+ if (config.autoNow) {
1363
+ return v4_default();
1364
+ }
1365
+ }
1366
+ return value;
1367
+ }
1368
+ }),
1369
+ additionalMetadata
1370
+ );
1371
+ var ModelReferenceProperty = (model, config = {}, additionalMetadata = {}) => AdvancedModelReferenceProperty(model, config, additionalMetadata);
1372
+ var AdvancedModelReferenceProperty = (model, config = {}, additionalMetadata = {}) => {
1373
+ if (!model) {
1374
+ throw new Error("Must include the referenced model");
1375
+ }
1376
+ const _getModel = () => {
1377
+ if (typeof model === "function") {
1378
+ return model();
1379
+ }
1380
+ return model;
1381
+ };
1382
+ const validator = referenceTypeMatch(model);
1383
+ const validators = mergeValidators(config, validator);
1384
+ const _getId = (instanceValues) => () => {
1385
+ if (!instanceValues) {
1386
+ return void 0;
1387
+ }
1388
+ if (typeof instanceValues === "number") {
1389
+ return instanceValues;
1390
+ }
1391
+ if (typeof instanceValues === "string") {
1392
+ return instanceValues;
1393
+ }
1394
+ if (instanceValues.getPrimaryKey) {
1395
+ return instanceValues.getPrimaryKey();
1396
+ }
1397
+ const theModel = _getModel();
1398
+ const primaryKey = theModel.getModelDefinition().primaryKeyName;
1399
+ return instanceValues[primaryKey];
1400
+ };
1401
+ const lazyLoadMethodAtomic = async (instanceValues) => {
1402
+ const valueIsModelInstance = isModelInstance2(instanceValues);
1403
+ const _getInstanceReturn = (objToUse) => {
1404
+ const objIsModelInstance = isModelInstance2(objToUse);
1405
+ const instance = objIsModelInstance ? objToUse : (
1406
+ // @ts-ignore
1407
+ _getModel().create(objToUse)
1408
+ );
1409
+ return (0, import_merge5.default)({}, instance, {
1410
+ toObj: memoizeAsync(_getId(instanceValues))
1411
+ });
1412
+ };
1413
+ if (valueIsModelInstance) {
1414
+ return _getInstanceReturn(instanceValues);
1415
+ }
1416
+ const theModel = _getModel();
1417
+ const primaryKey = theModel.getModelDefinition().primaryKeyName;
1418
+ if ((0, import_get3.default)(instanceValues, primaryKey)) {
1419
+ return _getInstanceReturn(instanceValues);
1420
+ }
1421
+ if (config?.fetcher) {
1422
+ const id = await _getId(instanceValues)();
1423
+ const model2 = _getModel();
1424
+ if (id !== null && id !== void 0) {
1425
+ const obj = await config.fetcher(model2, id);
1426
+ return _getInstanceReturn(obj);
1427
+ }
1428
+ return null;
1429
+ }
1430
+ return _getId(instanceValues)();
1431
+ };
1432
+ const p = (0, import_merge5.default)(
1433
+ Property(
1434
+ "ModelReference" /* ModelReference */,
1435
+ (0, import_merge5.default)({}, config, {
1436
+ validators,
1437
+ lazyLoadMethodAtomic
1438
+ }),
1439
+ additionalMetadata
1440
+ ),
1441
+ {
1442
+ getReferencedId: (instanceValues) => _getId(instanceValues)(),
1443
+ getReferencedModel: _getModel
1444
+ }
1445
+ );
1446
+ return p;
1447
+ };
1448
+ var DenormalizedProperty = (propertyType, calculate, config = {}, additionalMetadata = {}) => {
1449
+ const property2 = Property(
1450
+ propertyType,
1451
+ (0, import_merge5.default)(config, {
1452
+ isDenormalized: true,
1453
+ lazyLoadMethodAtomic: async (value, modelData, modelInstance) => {
1454
+ if (value !== void 0) {
1455
+ return value;
1456
+ }
1457
+ return calculate(modelData, modelInstance);
1458
+ }
1459
+ }),
1460
+ additionalMetadata
1461
+ );
1462
+ return (0, import_merge5.default)(property2, {
1463
+ calculate
1464
+ });
1465
+ };
1466
+ var DenormalizedTextProperty = (calculate, config = {}, additionalMetadata = {}) => DenormalizedProperty(
1467
+ "Text" /* Text */,
1468
+ calculate,
1469
+ (0, import_merge5.default)(config, {
1470
+ isString: true,
1471
+ validators: mergeValidators(
1472
+ config,
1473
+ ...getCommonTextValidators(config)
1474
+ )
1475
+ }),
1476
+ additionalMetadata
1477
+ );
1478
+ var DenormalizedNumberProperty = (calculate, config = {}, additionalMetadata = {}) => DenormalizedProperty(
1479
+ "Number" /* Number */,
1480
+ calculate,
1481
+ (0, import_merge5.default)(config, {
1482
+ isNumber: true,
1483
+ validators: mergeValidators(config, ...getCommonNumberValidators(config))
1484
+ }),
1485
+ additionalMetadata
1486
+ );
1487
+ var DenormalizedIntegerProperty = (calculate, config = {}, additionalMetadata = {}) => DenormalizedProperty(
1488
+ "Integer" /* Integer */,
1489
+ calculate,
1490
+ (0, import_merge5.default)(config, {
1491
+ isInteger: true,
1492
+ validators: mergeValidators(config, ...getCommonNumberValidators(config))
1493
+ }),
1494
+ additionalMetadata
1495
+ );
1496
+ var NaturalIdProperty = (propertyKeys, joiner, config = {}, additionalMetadata = {}) => Property(
1497
+ "Text" /* Text */,
1498
+ (0, import_merge5.default)(config, {
1499
+ isString: true,
1500
+ validators: mergeValidators(config, ...getCommonTextValidators(config)),
1501
+ lazyLoadMethodAtomic: async (value, model, modelInstance) => {
1502
+ const data = await propertyKeys.reduce(async (accP, key) => {
1503
+ const acc = await accP;
1504
+ const [head] = createHeadAndTail(key.split("."), ".");
1505
+ const value2 = await (isReferencedProperty(modelInstance, head) ? getValueForReferencedModel(modelInstance, key) : getValueForModelInstance(modelInstance, key));
1506
+ return acc.concat(value2);
1507
+ }, Promise.resolve([]));
1508
+ if (data.some((value2) => value2 === void 0)) {
1509
+ return void 0;
1510
+ }
1511
+ return data.join(joiner);
1512
+ }
1513
+ }),
1514
+ additionalMetadata
1515
+ );
1516
+
1517
+ // src/errors.ts
1518
+ var errors_exports = {};
1519
+ __export(errors_exports, {
1520
+ ValidationError: () => ValidationError
1521
+ });
1522
+ var ValidationError = class extends Error {
1523
+ constructor(modelName, keysToErrors) {
1524
+ super(`${modelName} did not pass validation`);
1525
+ this.name = "ValidationError";
1526
+ this.modelName = modelName;
1527
+ this.keysToErrors = keysToErrors;
1528
+ }
1529
+ };
1530
+
1531
+ // src/orm/index.ts
1532
+ var orm_exports = {};
1533
+ __export(orm_exports, {
1534
+ AllowableEqualitySymbols: () => AllowableEqualitySymbols,
1535
+ DatastoreValueType: () => DatastoreValueType,
1536
+ EqualitySymbol: () => EqualitySymbol,
1537
+ ForeignKeyProperty: () => ForeignKeyProperty,
1538
+ LastModifiedDateProperty: () => LastModifiedDateProperty,
1539
+ PrimaryKeyProperty: () => PrimaryKeyProperty,
1540
+ SortOrder: () => SortOrder,
1541
+ and: () => and,
1542
+ booleanQuery: () => booleanQuery,
1543
+ buildOrmValidatorContext: () => buildOrmValidatorContext,
1544
+ createOrm: () => createOrm,
1545
+ datesAfter: () => datesAfter,
1546
+ datesBefore: () => datesBefore,
1547
+ isALinkToken: () => isALinkToken,
1548
+ isPropertyBasedQuery: () => isPropertyBasedQuery,
1549
+ numberQuery: () => numberQuery,
1550
+ or: () => or,
1551
+ ormPropertyConfig: () => ormPropertyConfig,
1552
+ pagination: () => pagination,
1553
+ properties: () => properties_exports2,
1554
+ property: () => property,
1555
+ query: () => query_exports,
1556
+ queryBuilder: () => queryBuilder,
1557
+ sort: () => sort,
1558
+ take: () => take,
1559
+ textQuery: () => textQuery,
1560
+ threeitize: () => threeitize,
1561
+ types: () => types_exports2,
1562
+ unique: () => unique,
1563
+ uniqueTogether: () => uniqueTogether,
1564
+ validateOrmSearch: () => validateOrmSearch,
1565
+ validation: () => validation_exports2
1566
+ });
1567
+
1568
+ // src/orm/query.ts
1569
+ var query_exports = {};
1570
+ __export(query_exports, {
1571
+ and: () => and,
1572
+ booleanQuery: () => booleanQuery,
1573
+ datesAfter: () => datesAfter,
1574
+ datesBefore: () => datesBefore,
1575
+ isALinkToken: () => isALinkToken,
1576
+ isPropertyBasedQuery: () => isPropertyBasedQuery,
1577
+ numberQuery: () => numberQuery,
1578
+ or: () => or,
1579
+ pagination: () => pagination,
1580
+ property: () => property,
1581
+ queryBuilder: () => queryBuilder,
1582
+ sort: () => sort,
1583
+ take: () => take,
1584
+ textQuery: () => textQuery,
1585
+ threeitize: () => threeitize,
1586
+ validateOrmSearch: () => validateOrmSearch
1587
+ });
1588
+ var import_merge6 = __toESM(require("lodash/merge.js"), 1);
1589
+ var import_omit = __toESM(require("lodash/omit.js"), 1);
1590
+
1591
+ // src/orm/types.ts
1592
+ var types_exports2 = {};
1593
+ __export(types_exports2, {
1594
+ AllowableEqualitySymbols: () => AllowableEqualitySymbols,
1595
+ DatastoreValueType: () => DatastoreValueType,
1596
+ EqualitySymbol: () => EqualitySymbol,
1597
+ SortOrder: () => SortOrder
1598
+ });
1599
+ var EqualitySymbol = /* @__PURE__ */ ((EqualitySymbol2) => {
1600
+ EqualitySymbol2["eq"] = "=";
1601
+ EqualitySymbol2["lt"] = "<";
1602
+ EqualitySymbol2["lte"] = "<=";
1603
+ EqualitySymbol2["gt"] = ">";
1604
+ EqualitySymbol2["gte"] = ">=";
1605
+ EqualitySymbol2["ne"] = "!=";
1606
+ return EqualitySymbol2;
1607
+ })(EqualitySymbol || {});
1608
+ var DatastoreValueType = /* @__PURE__ */ ((DatastoreValueType2) => {
1609
+ DatastoreValueType2["string"] = "string";
1610
+ DatastoreValueType2["number"] = "number";
1611
+ DatastoreValueType2["date"] = "date";
1612
+ DatastoreValueType2["object"] = "object";
1613
+ DatastoreValueType2["boolean"] = "boolean";
1614
+ return DatastoreValueType2;
1615
+ })(DatastoreValueType || {});
1616
+ var AllowableEqualitySymbols = Object.values(EqualitySymbol);
1617
+ var SortOrder = /* @__PURE__ */ ((SortOrder2) => {
1618
+ SortOrder2["asc"] = "asc";
1619
+ SortOrder2["dsc"] = "dsc";
1620
+ return SortOrder2;
1621
+ })(SortOrder || {});
1622
+
1623
+ // src/orm/query.ts
1624
+ var THREE = 3;
1625
+ var _objectize = (key, value) => {
1626
+ return value ? {
1627
+ [key]: value
1628
+ } : {};
1629
+ };
1630
+ var _additionalLink = (data) => {
1631
+ const inner = _builderV2(data);
1632
+ const partialLink = (0, import_omit.default)(_link(data), ["and", "or"]);
1633
+ return {
1634
+ ...inner,
1635
+ ...partialLink
1636
+ };
1637
+ };
1638
+ var _link = (data) => {
1639
+ return {
1640
+ and: () => {
1641
+ return _queryBuilder({ ...data, query: data.query.concat("AND") });
1642
+ },
1643
+ or: () => {
1644
+ return _queryBuilder({ ...data, query: data.query.concat("OR") });
1645
+ },
1646
+ compile: () => {
1647
+ return data;
1648
+ },
1649
+ take: (num) => {
1650
+ return _additionalLink({ ...data, take: take(num) });
1651
+ },
1652
+ sort: (key, order = "asc" /* asc */) => {
1653
+ return _additionalLink({ ...data, sort: sort(key, order) });
1654
+ },
1655
+ pagination: (value) => {
1656
+ return _additionalLink({ ...data, page: pagination(value) });
1657
+ }
1658
+ };
1659
+ };
1660
+ var _canCompile = (obj) => {
1661
+ return Boolean(obj.compile);
1662
+ };
1663
+ var _builderV2 = (data) => {
1664
+ const _myProperty = (name, value, options) => {
1665
+ const p = property(name, value, options);
1666
+ return _link((0, import_merge6.default)(data, { query: data.query.concat(p) }));
1667
+ };
1668
+ const complex = (subBuilderFunc) => {
1669
+ const subBuilder = _queryBuilder();
1670
+ const result = subBuilderFunc(subBuilder);
1671
+ if (_canCompile(result)) {
1672
+ const queryTokens = [result.compile().query];
1673
+ return _link(
1674
+ (0, import_merge6.default)(data, {
1675
+ query: data.query.concat(queryTokens)
1676
+ })
1677
+ );
1678
+ }
1679
+ return _link((0, import_merge6.default)(data, { query: data.query.concat([result.query]) }));
1680
+ };
1681
+ const thisDatesBefore = (key, jsDate, { valueType = "date" /* date */, equalToAndBefore = true } = {}) => {
1682
+ const p = datesBefore(key, jsDate, { valueType, equalToAndBefore });
1683
+ return _link((0, import_merge6.default)(data, { query: data.query.concat(p) }));
1684
+ };
1685
+ const thisDatesAfter = (key, jsDate, { valueType = "date" /* date */, equalToAndAfter = true } = {}) => {
1686
+ const p = datesAfter(key, jsDate, { valueType, equalToAndAfter });
1687
+ return _link((0, import_merge6.default)(data, { query: data.query.concat(p) }));
1688
+ };
1689
+ return {
1690
+ datesBefore: thisDatesBefore,
1691
+ datesAfter: thisDatesAfter,
1692
+ complex,
1693
+ property: _myProperty
1694
+ };
1695
+ };
1696
+ var _queryBuilder = (data = void 0) => {
1697
+ const theData = (0, import_merge6.default)(
1698
+ {
1699
+ query: []
1700
+ },
1701
+ data
1702
+ );
1703
+ const builder = _builderV2(theData);
1704
+ const linkData = _additionalLink(theData);
1705
+ return {
1706
+ ...builder,
1707
+ ...linkData,
1708
+ compile: () => {
1709
+ return {
1710
+ ..._objectize("take", theData.take),
1711
+ ..._objectize("sort", theData.sort),
1712
+ ..._objectize("page", theData.page),
1713
+ query: []
1714
+ };
1715
+ }
1716
+ };
1717
+ };
1718
+ var property = (key, value, options = {}) => {
1719
+ const {
1720
+ equalitySymbol = "=" /* eq */,
1721
+ caseSensitive,
1722
+ startsWith,
1723
+ endsWith,
1724
+ includes,
1725
+ type
1726
+ } = options;
1727
+ const typeToUse = type || "string" /* string */;
1728
+ if (!AllowableEqualitySymbols.includes(equalitySymbol)) {
1729
+ throw new Error(`${equalitySymbol} is not a valid symbol`);
1730
+ }
1731
+ if (equalitySymbol !== "=" /* eq */ && equalitySymbol !== "!=" /* ne */ && typeToUse === "string" /* string */) {
1732
+ throw new Error(`Cannot use a non = symbol for a string type`);
1733
+ }
1734
+ const propertyEntry = {
1735
+ type: "property",
1736
+ key,
1737
+ value,
1738
+ valueType: typeToUse,
1739
+ equalitySymbol,
1740
+ options: {
1741
+ ..._objectize("caseSensitive", caseSensitive),
1742
+ ..._objectize("startsWith", startsWith),
1743
+ ..._objectize("endsWith", endsWith),
1744
+ ..._objectize("includes", includes)
1745
+ }
1746
+ };
1747
+ return propertyEntry;
1748
+ };
1749
+ var take = (max) => {
1750
+ const parsed = parseInt(`${max}`, 10);
1751
+ if (Number.isNaN(parsed)) {
1752
+ throw new Error(`Number "${max}" is not integerable`);
1753
+ }
1754
+ return parsed;
1755
+ };
1756
+ var sort = (key, order = "asc" /* asc */) => {
1757
+ if (order !== "asc" /* asc */ && order !== "dsc" /* dsc */) {
1758
+ throw new Error("Sort must be either asc or dsc");
1759
+ }
1760
+ return {
1761
+ key,
1762
+ order
1763
+ };
1764
+ };
1765
+ var pagination = (value) => {
1766
+ return value;
1767
+ };
1768
+ var datesAfter = (key, jsDate, options = {
1769
+ valueType: "date" /* date */,
1770
+ equalToAndAfter: true
1771
+ }) => {
1772
+ const { valueType = "date" /* date */, equalToAndAfter = true } = options;
1773
+ return {
1774
+ type: "datesAfter",
1775
+ key,
1776
+ date: isDate3(jsDate) ? jsDate.toISOString() : jsDate,
1777
+ valueType,
1778
+ options: {
1779
+ equalToAndAfter
1780
+ }
1781
+ };
1782
+ };
1783
+ var isDate3 = (obj) => {
1784
+ return Boolean(obj.toISOString);
1785
+ };
1786
+ var datesBefore = (key, jsDate, options = {
1787
+ valueType: "date" /* date */,
1788
+ equalToAndBefore: true
1789
+ }) => {
1790
+ const { valueType = "date" /* date */, equalToAndBefore = true } = options;
1791
+ return {
1792
+ type: "datesBefore",
1793
+ key,
1794
+ date: isDate3(jsDate) ? jsDate.toISOString() : jsDate,
1795
+ valueType,
1796
+ options: {
1797
+ equalToAndBefore
1798
+ }
1799
+ };
1800
+ };
1801
+ var queryBuilder = () => {
1802
+ return _queryBuilder();
1803
+ };
1804
+ var isPropertyBasedQuery = (value) => {
1805
+ if (!value || !value.type) {
1806
+ return false;
1807
+ }
1808
+ return value.type === "property" || value.type === "datesBefore" || value.type === "datesAfter";
1809
+ };
1810
+ var isALinkToken = (value) => {
1811
+ if (!value) {
1812
+ return false;
1813
+ }
1814
+ if (typeof value !== "string") {
1815
+ return false;
1816
+ }
1817
+ value = value.toLowerCase();
1818
+ return value === "and" || value === "or";
1819
+ };
1820
+ var and = () => "AND";
1821
+ var or = () => "OR";
1822
+ var textQuery = (key, value, options) => property(
1823
+ key,
1824
+ value,
1825
+ Object.assign({}, options, {
1826
+ equalitySymbol: void 0,
1827
+ type: "string" /* string */
1828
+ })
1829
+ );
1830
+ var numberQuery = (key, value, equalitySymbol = "=" /* eq */) => property(key, value, {
1831
+ equalitySymbol,
1832
+ type: "number" /* number */
1833
+ });
1834
+ var booleanQuery = (key, value) => property(key, value, {
1835
+ type: "boolean" /* boolean */,
1836
+ equalitySymbol: "=" /* eq */
1837
+ });
1838
+ var threeitize = (data) => {
1839
+ if (data.length === 0 || data.length === 1) {
1840
+ return [];
1841
+ }
1842
+ if (data.length % 2 === 0) {
1843
+ throw new Error("Must be an odd number of 3 or greater.");
1844
+ }
1845
+ const three = data.slice(0, THREE);
1846
+ const rest = data.slice(2);
1847
+ const moreThrees = threeitize(rest);
1848
+ return [three, ...moreThrees];
1849
+ };
1850
+ var _validateTokenTypes = (token) => {
1851
+ if (Array.isArray(token)) {
1852
+ token.forEach(_validateTokenTypes);
1853
+ return;
1854
+ }
1855
+ if (isPropertyBasedQuery(token)) {
1856
+ return;
1857
+ }
1858
+ if (isALinkToken(token)) {
1859
+ return;
1860
+ }
1861
+ throw new Error(`Unknown token type ${token}`);
1862
+ };
1863
+ var _validateTokenStructure = (o) => {
1864
+ const first = o[0];
1865
+ if (first === "AND" || first === "OR") {
1866
+ throw new Error("Cannot have AND or OR at the very start.");
1867
+ }
1868
+ const last = o[o.length - 1];
1869
+ if (last === "AND" || last === "OR") {
1870
+ throw new Error("Cannot have AND or OR at the very end.");
1871
+ }
1872
+ if (o.every((x) => x !== "AND" && x !== "OR")) {
1873
+ o.every(_validateArrayOrQuery);
1874
+ return;
1875
+ }
1876
+ const totalLinks = o.filter((x) => x === "AND" || x === "OR");
1877
+ const nonLinks = o.filter((x) => x !== "AND" && x !== "OR");
1878
+ if (totalLinks.length !== nonLinks.length - 1) {
1879
+ throw new Error("Must separate each statement with an AND or OR");
1880
+ }
1881
+ const threes = threeitize(o).reverse();
1882
+ threes.forEach(([a, l, b]) => {
1883
+ if (l !== "AND" && l !== "OR") {
1884
+ if (isPropertyBasedQuery(l)) {
1885
+ throw new Error("Must have AND/OR between property queries");
1886
+ }
1887
+ throw new Error("Must have AND/OR between nested queries");
1888
+ }
1889
+ _validateArrayOrQuery(a);
1890
+ _validateArrayOrQuery(b);
1891
+ });
1892
+ return;
1893
+ };
1894
+ var _validateArrayOrQuery = (o) => {
1895
+ if (Array.isArray(o)) {
1896
+ _validateTokenStructure(o);
1897
+ return;
1898
+ }
1899
+ if (isPropertyBasedQuery(o)) {
1900
+ return;
1901
+ }
1902
+ throw new Error("Order of link tokens and queries invalid");
1903
+ };
1904
+ var validateOrmSearch = (search) => {
1905
+ if (Array.isArray(search.query) === false) {
1906
+ throw new Error(`Query must be an array`);
1907
+ }
1908
+ if (search.query.length < 1) {
1909
+ return;
1910
+ }
1911
+ _validateTokenTypes(search.query);
1912
+ _validateTokenStructure(search.query);
1913
+ };
1914
+
1915
+ // src/orm/validation.ts
1916
+ var validation_exports2 = {};
1917
+ __export(validation_exports2, {
1918
+ buildOrmValidatorContext: () => buildOrmValidatorContext,
1919
+ unique: () => unique,
1920
+ uniqueTogether: () => uniqueTogether
1921
+ });
1922
+ var import_flow2 = __toESM(require("lodash/flow.js"), 1);
1923
+ var _doUniqueCheck = async (query, model, instanceData, buildErrorMessage) => {
1924
+ const results = await model.search(query);
1925
+ const resultsLength = results.instances.length;
1926
+ if (resultsLength < 1) {
1927
+ return void 0;
1928
+ }
1929
+ const ids = await Promise.all(
1930
+ results.instances.map((x) => x.getPrimaryKey())
1931
+ );
1932
+ const instanceId = instanceData[model.getModelDefinition().primaryKeyName];
1933
+ if (ids.length === 1 && ids[0] === instanceId) {
1934
+ return void 0;
1935
+ }
1936
+ if (ids.length > 1) {
1937
+ if (ids.find((x) => x === instanceId)) {
1938
+ return void 0;
1939
+ }
1940
+ }
1941
+ return buildErrorMessage();
1942
+ };
1943
+ var uniqueTogether = (propertyKeyArray) => {
1944
+ const _uniqueTogether = async (model, instanceData, options) => {
1945
+ if (options?.noOrmValidation) {
1946
+ return void 0;
1947
+ }
1948
+ const properties = propertyKeyArray.map((key) => {
1949
+ return [key, instanceData[key]];
1950
+ });
1951
+ const query = (0, import_flow2.default)(
1952
+ properties.map(([key, value], index) => {
1953
+ return (b) => {
1954
+ if (index + 1 >= properties.length) {
1955
+ return b.property(key, value, { caseSensitive: false });
1956
+ }
1957
+ return b.property(key, value, { caseSensitive: false }).and();
1958
+ };
1959
+ })
1960
+ )(queryBuilder().take(2)).compile();
1961
+ return _doUniqueCheck(query, model, instanceData, () => {
1962
+ return propertyKeyArray.length > 1 ? `${propertyKeyArray.join(
1963
+ ","
1964
+ )} must be unique together. Another instance found.` : `${propertyKeyArray[0]} must be unique. Another instance found.`;
1965
+ });
1966
+ };
1967
+ return _uniqueTogether;
1968
+ };
1969
+ var unique = (propertyKey) => {
1970
+ const _unique = (value, model, instanceData, options) => {
1971
+ return uniqueTogether([propertyKey])(model, instanceData, options);
1972
+ };
1973
+ return _unique;
1974
+ };
1975
+ var buildOrmValidatorContext = ({
1976
+ noOrmValidation = false
1977
+ }) => ({
1978
+ noOrmValidation
1979
+ });
1980
+
1981
+ // src/orm/properties.ts
1982
+ var properties_exports2 = {};
1983
+ __export(properties_exports2, {
1984
+ ForeignKeyProperty: () => ForeignKeyProperty,
1985
+ LastModifiedDateProperty: () => LastModifiedDateProperty,
1986
+ PrimaryKeyProperty: () => PrimaryKeyProperty,
1987
+ ormPropertyConfig: () => ormPropertyConfig
1988
+ });
1989
+ var import_merge7 = __toESM(require("lodash/merge.js"), 1);
1990
+ var import_identity = __toESM(require("lodash/identity.js"), 1);
1991
+
1992
+ // src/orm/internal-libs.ts
1993
+ var _getModelIdPropertyType = (config = {}) => {
1994
+ return config.dataType || "UniqueId" /* UniqueId */;
1995
+ };
1996
+ var getPrimaryKeyGenerator = (config = {}) => {
1997
+ const custom = config.primaryKeyGenerator;
1998
+ if (custom) {
1999
+ return custom;
2000
+ }
2001
+ const idType = _getModelIdPropertyType(config);
2002
+ switch (idType) {
2003
+ case "Integer" /* Integer */:
2004
+ return () => Promise.resolve(getRandomValues()[0]);
2005
+ default: {
2006
+ return () => Promise.resolve(createUuid());
2007
+ }
2008
+ }
2009
+ };
2010
+
2011
+ // src/orm/properties.ts
2012
+ var _defaultPropertyConfig = {
2013
+ unique: void 0
2014
+ };
2015
+ var LastModifiedDateProperty = (config = {}) => {
2016
+ const additionalMetadata = { lastModifiedUpdateMethod: () => /* @__PURE__ */ new Date() };
2017
+ return DatetimeProperty(config, additionalMetadata);
2018
+ };
2019
+ var ForeignKeyProperty = (model, config = {}) => {
2020
+ const _getModel = () => {
2021
+ if (typeof model === "function") {
2022
+ return model();
2023
+ }
2024
+ return model;
2025
+ };
2026
+ const _getProperty = () => {
2027
+ if (config.dataType === "UniqueId" /* UniqueId */) {
2028
+ return UuidProperty(
2029
+ (0, import_merge7.default)(config, {
2030
+ autoNow: false
2031
+ })
2032
+ );
2033
+ }
2034
+ if (config.dataType === "Integer" /* Integer */) {
2035
+ return IntegerProperty(config);
2036
+ }
2037
+ return TextProperty(config);
2038
+ };
2039
+ const property2 = _getProperty();
2040
+ return (0, import_merge7.default)(property2, {
2041
+ getReferencedId: (instanceValues) => {
2042
+ return instanceValues;
2043
+ },
2044
+ getReferencedModel: _getModel
2045
+ });
2046
+ };
2047
+ var PrimaryKeyProperty = (config = {}) => {
2048
+ const _getProperty = () => {
2049
+ const auto = config.auto === void 0 ? true : config.auto ? true : false;
2050
+ const lazyLoadMethod = (value, modelData, instance) => {
2051
+ if (config.primaryKeyGenerator) {
2052
+ return config.primaryKeyGenerator(value, modelData, instance);
2053
+ }
2054
+ if (auto) {
2055
+ return getPrimaryKeyGenerator(config)(value, modelData, instance);
2056
+ }
2057
+ return value;
2058
+ };
2059
+ if (config.dataType === "UniqueId" /* UniqueId */) {
2060
+ return UuidProperty(
2061
+ (0, import_merge7.default)(config, {
2062
+ autoNow: auto,
2063
+ lazyLoadMethod
2064
+ })
2065
+ );
2066
+ }
2067
+ if (config.dataType === "Integer" /* Integer */) {
2068
+ return IntegerProperty(
2069
+ (0, import_merge7.default)(config, {
2070
+ lazyLoadMethod
2071
+ })
2072
+ );
2073
+ }
2074
+ return TextProperty(
2075
+ (0, import_merge7.default)(config, {
2076
+ lazyLoadMethod
2077
+ })
2078
+ );
2079
+ };
2080
+ return _getProperty();
2081
+ };
2082
+ var ormPropertyConfig = (config = _defaultPropertyConfig) => {
2083
+ return (0, import_merge7.default)(config, {
2084
+ validators: [
2085
+ ...config.validators ? config.validators : [],
2086
+ config.unique ? unique(config.unique) : null
2087
+ ].filter(import_identity.default)
2088
+ });
2089
+ };
2090
+
2091
+ // src/orm/models.ts
2092
+ var import_merge8 = __toESM(require("lodash/merge.js"), 1);
2093
+ var import_modern_async = require("modern-async");
2094
+ var createOrm = ({
2095
+ datastoreAdapter,
2096
+ Model: Model2 = Model
2097
+ }) => {
2098
+ if (!datastoreAdapter) {
2099
+ throw new Error(`Must include a datastoreAdapter`);
2100
+ }
2101
+ const _retrievedObjToModel = (model) => (obj) => {
2102
+ return model.create(obj);
2103
+ };
2104
+ const fetcher = async (model, id) => {
2105
+ const x = retrieve(
2106
+ model,
2107
+ id
2108
+ );
2109
+ return x;
2110
+ };
2111
+ const retrieve = async (model, id) => {
2112
+ const obj = await datastoreAdapter.retrieve(model, id);
2113
+ if (!obj) {
2114
+ return void 0;
2115
+ }
2116
+ return _retrievedObjToModel(model)(obj);
2117
+ };
2118
+ const _defaultOptions2 = () => ({
2119
+ instanceCreatedCallback: void 0
2120
+ });
2121
+ const _convertOptions2 = (options) => {
2122
+ const r = (0, import_merge8.default)(
2123
+ {},
2124
+ _defaultOptions2(),
2125
+ options
2126
+ );
2127
+ return r;
2128
+ };
2129
+ const ThisModel = (modelDefinition, options) => {
2130
+ let model = null;
2131
+ const theOptions = _convertOptions2(options);
2132
+ const search = (ormQuery) => {
2133
+ return datastoreAdapter.search(model, ormQuery).then((result) => {
2134
+ const conversionFunc = _retrievedObjToModel(model);
2135
+ return {
2136
+ // @ts-ignore
2137
+ instances: result.instances.map(conversionFunc),
2138
+ page: result.page
2139
+ };
2140
+ });
2141
+ };
2142
+ const searchOne = (ormQuery) => {
2143
+ ormQuery = (0, import_merge8.default)(ormQuery, { take: 1 });
2144
+ return search(ormQuery).then(({ instances }) => {
2145
+ return instances[0];
2146
+ });
2147
+ };
2148
+ const bulkInsert = async (instances) => {
2149
+ if (datastoreAdapter.bulkInsert) {
2150
+ await datastoreAdapter.bulkInsert(model, instances);
2151
+ return void 0;
2152
+ }
2153
+ await (0, import_modern_async.asyncMap)(instances, (x) => x.save());
2154
+ return void 0;
2155
+ };
2156
+ const bulkDelete = async (keysOrInstances) => {
2157
+ const ids = typeof keysOrInstances[0] === "object" ? keysOrInstances.map(
2158
+ (x) => x.getPrimaryKey()
2159
+ ) : keysOrInstances;
2160
+ if (datastoreAdapter.bulkDelete) {
2161
+ await datastoreAdapter.bulkDelete(model, ids);
2162
+ return void 0;
2163
+ }
2164
+ await (0, import_modern_async.asyncMap)(ids, (id) => model.delete(id));
2165
+ return void 0;
2166
+ };
2167
+ const loadedRetrieve = (id) => {
2168
+ return retrieve(model, id);
2169
+ };
2170
+ const modelValidators = modelDefinition?.uniqueTogether ? (modelDefinition.modelValidators || []).concat(
2171
+ // @ts-ignore
2172
+ uniqueTogether(modelDefinition.uniqueTogether)
2173
+ ) : modelDefinition.modelValidators;
2174
+ const ormModelDefinition = (0, import_merge8.default)({}, modelDefinition, {
2175
+ modelValidators
2176
+ });
2177
+ const _updateLastModifiedIfExistsReturnNewObj = async (instance) => {
2178
+ const hasLastModified = Object.entries(
2179
+ instance.getModel().getModelDefinition().properties
2180
+ ).filter((propertyEntry) => {
2181
+ const property2 = propertyEntry[1];
2182
+ return Boolean("lastModifiedUpdateMethod" in property2);
2183
+ })[0];
2184
+ const doLastModified = async () => {
2185
+ const obj = await instance.toObj();
2186
+ const newInstance = model.create(
2187
+ // @ts-ignore
2188
+ (0, import_merge8.default)(obj, {
2189
+ [hasLastModified[0]]: (
2190
+ // @ts-ignore
2191
+ hasLastModified[1].lastModifiedUpdateMethod()
2192
+ )
2193
+ })
2194
+ );
2195
+ return newInstance;
2196
+ };
2197
+ return hasLastModified ? doLastModified() : instance;
2198
+ };
2199
+ const save = async (instance) => {
2200
+ return Promise.resolve().then(async () => {
2201
+ const newInstance = await _updateLastModifiedIfExistsReturnNewObj(instance);
2202
+ const invalid = await newInstance.validate();
2203
+ if (invalid) {
2204
+ throw new ValidationError(model.getName(), invalid);
2205
+ }
2206
+ const savedObj = await datastoreAdapter.save(newInstance);
2207
+ return _retrievedObjToModel(model)(savedObj);
2208
+ });
2209
+ };
2210
+ const createAndSave = async (data) => {
2211
+ if (datastoreAdapter.createAndSave) {
2212
+ const response = await datastoreAdapter.createAndSave(data);
2213
+ return _retrievedObjToModel(model)(response);
2214
+ }
2215
+ const instance = model.create(await data.toObj());
2216
+ return instance.save();
2217
+ };
2218
+ const deleteObj = (id) => {
2219
+ return Promise.resolve().then(async () => {
2220
+ await datastoreAdapter.delete(model, id);
2221
+ });
2222
+ };
2223
+ const _getSave = (instance) => {
2224
+ if (theOptions.save !== void 0) {
2225
+ return () => theOptions.save(save, instance);
2226
+ }
2227
+ return () => save(instance);
2228
+ };
2229
+ const _getDelete = (instance) => {
2230
+ if (theOptions.delete) {
2231
+ return () => theOptions.delete(deleteObj, instance);
2232
+ }
2233
+ return () => deleteObj(instance.getPrimaryKey());
2234
+ };
2235
+ const instanceCreatedCallback = (instance) => {
2236
+ instance.save = _getSave(instance);
2237
+ instance.delete = _getDelete(instance);
2238
+ if (theOptions.instanceCreatedCallback) {
2239
+ const callbacks = Array.isArray(theOptions.instanceCreatedCallback) ? theOptions.instanceCreatedCallback : [theOptions.instanceCreatedCallback];
2240
+ callbacks.forEach((x) => x(instance));
2241
+ }
2242
+ };
2243
+ const overridedOptions = (0, import_merge8.default)({}, theOptions, {
2244
+ instanceCreatedCallback: [instanceCreatedCallback]
2245
+ });
2246
+ const baseModel = Model2(ormModelDefinition, overridedOptions);
2247
+ const lowerLevelCreate = baseModel.create;
2248
+ const _convertModelInstance = (instance) => {
2249
+ return (0, import_merge8.default)(instance, {
2250
+ create,
2251
+ getModel: () => model,
2252
+ save: _getSave(instance),
2253
+ delete: _getDelete(instance)
2254
+ });
2255
+ };
2256
+ const create = (data) => {
2257
+ const result = lowerLevelCreate(data);
2258
+ return _convertModelInstance(result);
2259
+ };
2260
+ const _countRecursive = async (page = null) => {
2261
+ const results = await model.search(
2262
+ queryBuilder().pagination(page).compile()
2263
+ );
2264
+ const length1 = results.instances.length;
2265
+ if (results.page && results.page !== page) {
2266
+ const length2 = await _countRecursive(results.page);
2267
+ return length1 + length2;
2268
+ }
2269
+ return length1;
2270
+ };
2271
+ const count = async () => {
2272
+ if (datastoreAdapter.count) {
2273
+ return datastoreAdapter.count(model);
2274
+ }
2275
+ return _countRecursive();
2276
+ };
2277
+ model = (0, import_merge8.default)(baseModel, {
2278
+ create,
2279
+ save,
2280
+ delete: deleteObj,
2281
+ retrieve: loadedRetrieve,
2282
+ search,
2283
+ searchOne,
2284
+ createAndSave,
2285
+ bulkInsert,
2286
+ bulkDelete,
2287
+ count
2288
+ });
2289
+ return model;
2290
+ };
2291
+ return {
2292
+ Model: ThisModel,
2293
+ fetcher
2294
+ };
2295
+ };
2296
+
2297
+ // src/orm/libs.ts
2298
+ var import_flow3 = __toESM(require("lodash/flow.js"), 1);
2299
+ var multipleOrQuery = (queryBuilder2, propertyKey, values, propertyType, propertyOptions) => {
2300
+ if (values.length === 0) {
2301
+ return queryBuilder2;
2302
+ }
2303
+ return (0, import_flow3.default)(
2304
+ values.map((v, index) => {
2305
+ return (qb) => {
2306
+ const withProperty = qb.property(propertyKey, v, {
2307
+ ...propertyOptions || {},
2308
+ type: propertyType || "string" /* string */
2309
+ });
2310
+ return index < values.length - 1 ? withProperty.or() : withProperty;
2311
+ };
2312
+ })
2313
+ )(queryBuilder2);
2314
+ };
2315
+ var multipleAndQuery = (queryBuilder2, propertyKey, values, propertyType) => {
2316
+ if (values.length === 0) {
2317
+ return queryBuilder2;
2318
+ }
2319
+ return (0, import_flow3.default)(
2320
+ values.map((v, index) => {
2321
+ return (qb) => {
2322
+ const withProperty = qb.property(propertyKey, v, {
2323
+ type: propertyType || "string" /* string */
2324
+ });
2325
+ return index < values.length - 1 ? withProperty.and() : withProperty;
2326
+ };
2327
+ })
2328
+ )(queryBuilder2);
2329
+ };
2330
+ // Annotate the CommonJS export names for ESM import in node:
2331
+ 0 && (module.exports = {
2332
+ AdvancedModelReferenceProperty,
2333
+ AllowableEqualitySymbols,
2334
+ ApiMethod,
2335
+ ArrayProperty,
2336
+ BigTextProperty,
2337
+ BooleanProperty,
2338
+ ConstantValueProperty,
2339
+ DatastoreValueType,
2340
+ DateProperty,
2341
+ DatetimeProperty,
2342
+ DenormalizedIntegerProperty,
2343
+ DenormalizedNumberProperty,
2344
+ DenormalizedProperty,
2345
+ DenormalizedTextProperty,
2346
+ EmailProperty,
2347
+ EqualitySymbol,
2348
+ ForeignKeyProperty,
2349
+ IntegerProperty,
2350
+ LastModifiedDateProperty,
2351
+ Model,
2352
+ ModelReferenceProperty,
2353
+ NaturalIdProperty,
2354
+ NumberProperty,
2355
+ ObjectProperty,
2356
+ PrimaryKeyProperty,
2357
+ PrimaryKeyUuidProperty,
2358
+ PrimitiveValueType,
2359
+ Property,
2360
+ PropertyType,
2361
+ SingleTypeArrayProperty,
2362
+ SortOrder,
2363
+ TextProperty,
2364
+ UuidProperty,
2365
+ ValidationError,
2366
+ YearProperty,
2367
+ aggregateValidator,
2368
+ and,
2369
+ arrayType,
2370
+ booleanQuery,
2371
+ buildOrmValidatorContext,
2372
+ choices,
2373
+ createModelValidator,
2374
+ createOrm,
2375
+ createPropertyValidator,
2376
+ datesAfter,
2377
+ datesBefore,
2378
+ emptyValidator,
2379
+ errors,
2380
+ isALinkToken,
2381
+ isArray,
2382
+ isBoolean,
2383
+ isDate,
2384
+ isInteger,
2385
+ isNullRestInfo,
2386
+ isNumber,
2387
+ isObject,
2388
+ isPropertyBasedQuery,
2389
+ isRequired,
2390
+ isString,
2391
+ isType,
2392
+ isValid,
2393
+ isValidUuid,
2394
+ maxNumber,
2395
+ maxTextLength,
2396
+ meetsRegex,
2397
+ minNumber,
2398
+ minTextLength,
2399
+ models,
2400
+ multiValidator,
2401
+ multipleAndQuery,
2402
+ multipleOrQuery,
2403
+ noFetch,
2404
+ numberQuery,
2405
+ objectValidator,
2406
+ optionalValidator,
2407
+ or,
2408
+ orm,
2409
+ ormPropertyConfig,
2410
+ pagination,
2411
+ properties,
2412
+ property,
2413
+ query,
2414
+ queryBuilder,
2415
+ referenceTypeMatch,
2416
+ sort,
2417
+ take,
2418
+ textQuery,
2419
+ threeitize,
2420
+ types,
2421
+ unique,
2422
+ uniqueTogether,
2423
+ validateOrmSearch,
2424
+ validation
2425
+ });
2426
+ //# sourceMappingURL=index.cjs.map