@autofleet/sadot 1.6.18-beta.2 → 1.6.18-beta.21

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 (162) hide show
  1. package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/decorate.cjs +11 -0
  2. package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/decorate.js +10 -0
  3. package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/decorateMetadata.cjs +8 -0
  4. package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/decorateMetadata.js +7 -0
  5. package/dist/_virtual/rolldown_runtime.cjs +43 -0
  6. package/dist/{chunk-DJulfCLt.js → _virtual/rolldown_runtime.js} +1 -2
  7. package/dist/api/index.cjs +12 -0
  8. package/dist/api/index.js +11 -0
  9. package/dist/api/v1/definition/index.cjs +113 -0
  10. package/dist/api/v1/definition/index.js +112 -0
  11. package/dist/api/v1/definition/validations.cjs +128 -0
  12. package/dist/api/v1/definition/validations.js +125 -0
  13. package/dist/api/v1/errors.cjs +14 -0
  14. package/dist/api/v1/errors.js +13 -0
  15. package/dist/api/v1/field-policies/index.cjs +104 -0
  16. package/dist/api/v1/field-policies/index.js +103 -0
  17. package/dist/api/v1/index.cjs +16 -0
  18. package/dist/api/v1/index.js +15 -0
  19. package/dist/api/v1/validator/index.cjs +132 -0
  20. package/dist/api/v1/validator/index.js +131 -0
  21. package/dist/api/v1/validator/validations.cjs +40 -0
  22. package/dist/api/v1/validator/validations.d.cts +22 -0
  23. package/dist/api/v1/validator/validations.d.ts +22 -0
  24. package/dist/api/v1/validator/validations.js +38 -0
  25. package/dist/errors/index.cjs +62 -0
  26. package/dist/errors/index.js +55 -0
  27. package/dist/events/index.cjs +52 -0
  28. package/dist/events/index.js +50 -0
  29. package/dist/hooks/enrich.cjs +175 -0
  30. package/dist/hooks/enrich.js +175 -0
  31. package/dist/hooks/find.cjs +22 -0
  32. package/dist/hooks/find.js +22 -0
  33. package/dist/hooks/hooks.cjs +310 -0
  34. package/dist/hooks/hooks.js +302 -0
  35. package/dist/hooks/index.cjs +3 -0
  36. package/dist/hooks/index.js +5 -0
  37. package/dist/hooks/utils/updateInstanceValues.cjs +27 -0
  38. package/dist/hooks/utils/updateInstanceValues.js +27 -0
  39. package/dist/index.cjs +48 -33508
  40. package/dist/index.d.cts +13 -396
  41. package/dist/index.d.ts +14 -394
  42. package/dist/index.js +21 -33435
  43. package/dist/init-state.cjs +56 -0
  44. package/dist/init-state.d.cts +35 -0
  45. package/dist/init-state.d.ts +35 -0
  46. package/dist/init-state.js +55 -0
  47. package/dist/mat-path-state.cjs +10 -0
  48. package/dist/mat-path-state.js +9 -0
  49. package/dist/migrations/001-create-core-tables.cjs +70 -0
  50. package/dist/migrations/001-create-core-tables.js +68 -0
  51. package/dist/migrations/002-create-custom-field-entries.cjs +27 -0
  52. package/dist/migrations/002-create-custom-field-entries.js +25 -0
  53. package/dist/migrations/003-create-custom-field-model-type-map.cjs +35 -0
  54. package/dist/migrations/003-create-custom-field-model-type-map.js +33 -0
  55. package/dist/migrations/004-create-field-policy-tables.cjs +29 -0
  56. package/dist/migrations/004-create-field-policy-tables.js +27 -0
  57. package/dist/migrations/005-add-entity-type-to-field-policies.cjs +20 -0
  58. package/dist/migrations/005-add-entity-type-to-field-policies.js +18 -0
  59. package/dist/migrations/index.cjs +94 -0
  60. package/dist/migrations/index.js +95 -0
  61. package/dist/models/CustomFieldDefinition.cjs +147 -0
  62. package/dist/models/CustomFieldDefinition.d.cts +40 -0
  63. package/dist/models/CustomFieldDefinition.d.ts +40 -0
  64. package/dist/models/CustomFieldDefinition.js +146 -0
  65. package/dist/models/CustomFieldEntries.cjs +71 -0
  66. package/dist/models/CustomFieldEntries.d.cts +15 -0
  67. package/dist/models/CustomFieldEntries.d.ts +15 -0
  68. package/dist/models/CustomFieldEntries.js +70 -0
  69. package/dist/models/CustomFieldModelTypeMap.cjs +62 -0
  70. package/dist/models/CustomFieldModelTypeMap.d.cts +14 -0
  71. package/dist/models/CustomFieldModelTypeMap.d.ts +14 -0
  72. package/dist/models/CustomFieldModelTypeMap.js +61 -0
  73. package/dist/models/CustomFieldValue.cjs +109 -0
  74. package/dist/models/CustomFieldValue.d.cts +20 -0
  75. package/dist/models/CustomFieldValue.d.ts +20 -0
  76. package/dist/models/CustomFieldValue.js +108 -0
  77. package/dist/models/CustomValidator.cjs +68 -0
  78. package/dist/models/CustomValidator.d.cts +18 -0
  79. package/dist/models/CustomValidator.d.ts +18 -0
  80. package/dist/models/CustomValidator.js +67 -0
  81. package/dist/models/FieldPolicy.cjs +54 -0
  82. package/dist/models/FieldPolicy.d.cts +25 -0
  83. package/dist/models/FieldPolicy.d.ts +25 -0
  84. package/dist/models/FieldPolicy.js +53 -0
  85. package/dist/models/index.cjs +163 -0
  86. package/dist/models/index.d.ts +11 -0
  87. package/dist/models/index.js +161 -0
  88. package/dist/models/tests/AssociatedTestModel.cjs +51 -0
  89. package/dist/models/tests/AssociatedTestModel.d.ts +2 -0
  90. package/dist/models/tests/AssociatedTestModel.js +50 -0
  91. package/dist/models/tests/TestModel.cjs +43 -0
  92. package/dist/models/tests/TestModel.d.ts +2 -0
  93. package/dist/models/tests/TestModel.js +42 -0
  94. package/dist/models/tests/contextAwareModels/ContextAwareTestModel.cjs +35 -0
  95. package/dist/models/tests/contextAwareModels/ContextAwareTestModel.d.ts +2 -0
  96. package/dist/models/tests/contextAwareModels/ContextAwareTestModel.js +34 -0
  97. package/dist/models/tests/contextAwareModels/ContextTestModel.cjs +33 -0
  98. package/dist/models/tests/contextAwareModels/ContextTestModel.d.ts +1 -0
  99. package/dist/models/tests/contextAwareModels/ContextTestModel.js +32 -0
  100. package/dist/repository/definition.cjs +221 -0
  101. package/dist/repository/definition.js +212 -0
  102. package/dist/repository/entries.cjs +69 -0
  103. package/dist/repository/entries.js +67 -0
  104. package/dist/repository/field-policy.cjs +69 -0
  105. package/dist/repository/field-policy.d.cts +35 -0
  106. package/dist/repository/field-policy.d.ts +35 -0
  107. package/dist/repository/field-policy.js +59 -0
  108. package/dist/repository/utils/formatValues.cjs +14 -0
  109. package/dist/repository/utils/formatValues.js +14 -0
  110. package/dist/repository/validator.cjs +85 -0
  111. package/dist/repository/validator.js +78 -0
  112. package/dist/repository/value.cjs +77 -0
  113. package/dist/repository/value.js +76 -0
  114. package/dist/scopes/filter.cjs +56 -0
  115. package/dist/scopes/filter.d.cts +22 -0
  116. package/dist/scopes/filter.d.ts +22 -0
  117. package/dist/scopes/filter.js +54 -0
  118. package/dist/scopes/helpers/filter.helpers.cjs +152 -0
  119. package/dist/scopes/helpers/filter.helpers.d.cts +16 -0
  120. package/dist/scopes/helpers/filter.helpers.d.ts +16 -0
  121. package/dist/scopes/helpers/filter.helpers.js +147 -0
  122. package/dist/scopes/index.cjs +1 -0
  123. package/dist/scopes/index.js +3 -0
  124. package/dist/types/index.d.cts +75 -0
  125. package/dist/types/index.d.ts +76 -0
  126. package/dist/utils/constants/index.cjs +32 -0
  127. package/dist/utils/constants/index.d.cts +23 -0
  128. package/dist/utils/constants/index.d.ts +23 -0
  129. package/dist/utils/constants/index.js +29 -0
  130. package/dist/utils/db/index.cjs +15 -0
  131. package/dist/utils/db/index.js +14 -0
  132. package/dist/utils/helpers/index.cjs +23 -0
  133. package/dist/utils/helpers/index.d.cts +30 -0
  134. package/dist/utils/helpers/index.d.ts +30 -0
  135. package/dist/utils/helpers/index.js +21 -0
  136. package/dist/utils/init.cjs +115 -0
  137. package/dist/utils/init.js +111 -0
  138. package/dist/utils/logger/index.cjs +15 -0
  139. package/dist/utils/logger/index.js +12 -0
  140. package/dist/utils/scopeAttributes.cjs +12 -0
  141. package/dist/utils/scopeAttributes.js +11 -0
  142. package/dist/utils/validations/index.cjs +34 -0
  143. package/dist/utils/validations/index.js +32 -0
  144. package/dist/utils/validations/schema/custom-fields.cjs +9 -0
  145. package/dist/utils/validations/schema/custom-fields.d.cts +6 -0
  146. package/dist/utils/validations/schema/custom-fields.d.ts +6 -0
  147. package/dist/utils/validations/schema/custom-fields.js +7 -0
  148. package/dist/utils/validations/schema/validator-schema.cjs +102 -0
  149. package/dist/utils/validations/schema/validator-schema.js +99 -0
  150. package/dist/utils/validations/validators/index.cjs +45 -0
  151. package/dist/utils/validations/validators/index.js +42 -0
  152. package/dist/utils/validations/validators/multi-select-dropdown.validator.cjs +7 -0
  153. package/dist/utils/validations/validators/multi-select-dropdown.validator.js +7 -0
  154. package/dist/utils/validations/validators/multi-select-status.validator.cjs +10 -0
  155. package/dist/utils/validations/validators/multi-select-status.validator.js +10 -0
  156. package/dist/utils/validations/validators/multi-select.helpers.cjs +12 -0
  157. package/dist/utils/validations/validators/multi-select.helpers.js +10 -0
  158. package/dist/utils/validations/validators/select.validator.cjs +12 -0
  159. package/dist/utils/validations/validators/select.validator.js +10 -0
  160. package/dist/utils/validations/validators/status.validator.cjs +12 -0
  161. package/dist/utils/validations/validators/status.validator.js +10 -0
  162. package/package.json +4 -4
@@ -0,0 +1,310 @@
1
+ const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
2
+ const require_index = require('../utils/logger/index.cjs');
3
+ const require_index$1 = require('../utils/constants/index.cjs');
4
+ const require_index$2 = require('../errors/index.cjs');
5
+ const require_definition = require('../repository/definition.cjs');
6
+ const require_validator = require('../repository/validator.cjs');
7
+ const require_scopeAttributes = require('../utils/scopeAttributes.cjs');
8
+ const require_updateInstanceValues = require('./utils/updateInstanceValues.cjs');
9
+ let joi = require("joi");
10
+ joi = require_rolldown_runtime.__toESM(joi);
11
+ let _autofleet_errors = require("@autofleet/errors");
12
+ let ajv = require("ajv");
13
+ ajv = require_rolldown_runtime.__toESM(ajv);
14
+ let ajv_formats = require("ajv-formats");
15
+ ajv_formats = require_rolldown_runtime.__toESM(ajv_formats);
16
+ let ajv_errors = require("ajv-errors");
17
+ ajv_errors = require_rolldown_runtime.__toESM(ajv_errors);
18
+
19
+ //#region src/hooks/hooks.ts
20
+ const CUSTOM_VALIDATOR_ATTRIBUTES_TO_PULL = [
21
+ "id",
22
+ "schema",
23
+ "modelType",
24
+ "entityId",
25
+ "disabled"
26
+ ];
27
+ const ajv$1 = new ajv.default({
28
+ allErrors: true,
29
+ strict: false,
30
+ strictTypes: false,
31
+ $data: true
32
+ });
33
+ (0, ajv_formats.default)(ajv$1);
34
+ (0, ajv_errors.default)(ajv$1);
35
+ /**
36
+ * Helper function to manually copy object properties
37
+ * This is more efficient for large objects and avoids excessive object creation
38
+ */
39
+ const manualObjectCopy = (sourceObj, additionalProps) => ({
40
+ __proto__: null,
41
+ ...sourceObj,
42
+ ...additionalProps
43
+ });
44
+ /**
45
+ * Fetches complete custom fields for an instance by merging DB values with update values
46
+ * This is needed for partial updates to ensure all related fields are available for validation
47
+ */
48
+ const getCompleteCustomFields = async (instance, options) => {
49
+ if (!instance.id || !instance.customFields || Object.keys(instance.customFields).length === 0) return instance.customFields || {};
50
+ try {
51
+ const currentCustomFields = await instance.constructor.findOne({
52
+ where: { id: instance.id },
53
+ attributes: ["customFields"],
54
+ transaction: options.transaction,
55
+ raw: true
56
+ });
57
+ if (currentCustomFields?.customFields) {
58
+ const completeFields = manualObjectCopy(currentCustomFields.customFields, instance.customFields);
59
+ require_index.default.debug("sadot - fetched complete custom fields for validation", {
60
+ fieldsCount: Object.keys(completeFields).length,
61
+ updateFieldsCount: Object.keys(instance.customFields).length
62
+ });
63
+ return completeFields;
64
+ }
65
+ } catch (error) {
66
+ require_index.default.error("sadot - error fetching complete model for validation", { error });
67
+ }
68
+ return instance.customFields || {};
69
+ };
70
+ const buildPreChangeState = (instance) => {
71
+ const beforeFull = { ...instance.dataValues };
72
+ (instance.changed?.() || []).forEach((key) => {
73
+ const prevVal = instance.previous?.(key);
74
+ if (prevVal !== void 0) beforeFull[key] = prevVal;
75
+ });
76
+ const prevCF = instance.previous?.("customFields");
77
+ if (prevCF !== void 0) beforeFull.customFields = prevCF;
78
+ return beforeFull;
79
+ };
80
+ const formatAjvErrors = (errors) => errors.reduce((acc, err) => {
81
+ const key = ((err.instancePath || "").split("/").filter(Boolean).join(".").replace(/^after\./, "") + (err.keyword === "required" ? `.${err.params?.missingProperty}` : "")).replace(/^\./, "") || "root";
82
+ acc[key] = err.message || "Invalid value";
83
+ return acc;
84
+ }, {});
85
+ /**
86
+ * Validates the model using custom validators
87
+ */
88
+ const validateModel = async (instance, options, scopeAttributes, modelOptions = {}, isCreate = false) => {
89
+ const modelType = instance.constructor.name;
90
+ require_index.default.debug("sadot - validating model", {
91
+ isCreate,
92
+ modelType
93
+ });
94
+ const identifiers = require_scopeAttributes.default(instance, scopeAttributes);
95
+ require_index.default.debug("sadot - identifiers", { identifiers });
96
+ if (!identifiers || Object.keys(identifiers).length === 0) {
97
+ require_index.default.debug("sadot - skipping validation: no identifiers");
98
+ return;
99
+ }
100
+ const entityId = Object.values(identifiers)[0];
101
+ require_index.default.debug("sadot - entityId", { entityId });
102
+ if (!entityId) {
103
+ require_index.default.debug("sadot - skipping validation: no entityId");
104
+ return;
105
+ }
106
+ let validatorsPromise;
107
+ let cacheKey;
108
+ if (options.transaction) {
109
+ options.transaction.validationsCache ??= /* @__PURE__ */ new Map();
110
+ cacheKey = `${modelType}-${entityId}`;
111
+ validatorsPromise = options.transaction.validationsCache.get(cacheKey);
112
+ }
113
+ if (!validatorsPromise) {
114
+ validatorsPromise = require_validator.findAllByModelType(modelType, entityId, {
115
+ transaction: options.transaction,
116
+ attributes: CUSTOM_VALIDATOR_ATTRIBUTES_TO_PULL,
117
+ modelOptions
118
+ });
119
+ if (options.transaction) options?.transaction?.validationsCache.set(cacheKey, validatorsPromise);
120
+ }
121
+ const validators = await validatorsPromise;
122
+ require_index.default.debug("sadot - validators found", { count: validators.length });
123
+ if (!validators.length) {
124
+ require_index.default.debug("sadot - skipping validation: no validators found");
125
+ return;
126
+ }
127
+ let originalValues = null;
128
+ if (!isCreate) originalValues = buildPreChangeState(instance);
129
+ const completeCustomFields = !isCreate ? await getCompleteCustomFields(instance, options) : instance.customFields || {};
130
+ for (const validator of validators) {
131
+ const { schema } = validator;
132
+ const typedSchema = schema;
133
+ require_index.default.debug("sadot - validating with schema", {
134
+ schema,
135
+ hasAfterProps: !!typedSchema.properties?.after,
136
+ hasBeforeProps: !!typedSchema.properties?.before
137
+ });
138
+ if (isCreate) {
139
+ if (typedSchema.properties?.after) {
140
+ const validateSchema = ajv$1.compile({
141
+ ...schema,
142
+ properties: { after: typedSchema.properties.after }
143
+ });
144
+ if (!validateSchema(JSON.parse(JSON.stringify({ after: {
145
+ ...instance.dataValues,
146
+ customFields: completeCustomFields
147
+ } })))) {
148
+ const errorDetails = validateSchema.errors?.map((err) => `${err.instancePath || ""} ${err.message || "Invalid value"}`).join(", ");
149
+ const formattedErrors = formatAjvErrors(validateSchema.errors);
150
+ throw new _autofleet_errors.BadRequest([/* @__PURE__ */ new Error(`Validation failed for ${modelType}: ${errorDetails}`)], void 0, { customError: formattedErrors });
151
+ }
152
+ }
153
+ } else {
154
+ const validateSchema = ajv$1.compile(typedSchema);
155
+ const afterObj = manualObjectCopy(instance.dataValues);
156
+ afterObj.customFields = completeCustomFields;
157
+ const payload = {
158
+ before: originalValues,
159
+ after: afterObj
160
+ };
161
+ const isValid = validateSchema(JSON.parse(JSON.stringify(payload)));
162
+ require_index.default.debug("sadot - validation result", {
163
+ isValid,
164
+ test: {
165
+ before: originalValues,
166
+ after: afterObj
167
+ }
168
+ });
169
+ if (!isValid) {
170
+ const errorDetails = validateSchema.errors?.map((err) => `${err.instancePath || ""} ${err.message || "Invalid value"}`).join(", ");
171
+ const formattedErrors = formatAjvErrors(validateSchema.errors);
172
+ throw new _autofleet_errors.BadRequest([/* @__PURE__ */ new Error(`Validation failed for ${modelType}: ${errorDetails}`)], void 0, { customError: formattedErrors });
173
+ }
174
+ }
175
+ }
176
+ };
177
+ const getFieldDefinitions = async ({ modelType, modelOptions, identifiers, options, instance, sadotOptions }) => {
178
+ const { include, useEntityIdFromInclude } = modelOptions;
179
+ if (sadotOptions.hasTypeId && instance?.typeId) return require_definition.findByModelTypeId(instance.typeId, {
180
+ withDisabled: false,
181
+ transaction: options.transaction,
182
+ entityIds: identifiers,
183
+ modelType,
184
+ modelOptions
185
+ });
186
+ const where = {
187
+ modelType,
188
+ disabled: false,
189
+ ...!useEntityIdFromInclude && { entityId: identifiers }
190
+ };
191
+ return require_definition.findAll(where, {
192
+ withDisabled: false,
193
+ transaction: options.transaction,
194
+ include: include?.(identifiers)
195
+ });
196
+ };
197
+ const formatDates = (fieldDefinitions, instance) => {
198
+ (fieldDefinitions || []).forEach((fieldDefinition) => {
199
+ const { fieldType, name } = fieldDefinition;
200
+ if ([require_index$1.CustomFieldDefinitionType.DATE, require_index$1.CustomFieldDefinitionType.DATETIME].includes(fieldType)) {
201
+ const value = instance.customFields?.[name];
202
+ if (value) {
203
+ const { value: joiValue, error: validationError } = joi.default.date().validate(value);
204
+ if (validationError) throw new require_index$2.InvalidValueError(value, name, validationError);
205
+ instance.customFields[name] = joiValue.toISOString();
206
+ }
207
+ }
208
+ });
209
+ };
210
+ /**
211
+ * Hook to handle validation and custom fields during creation
212
+ */
213
+ const beforeCreate = (scopeAttributes, modelOptions = {}, sadotOptions = { useCustomFieldsEntries: false }) => async (instance, options) => {
214
+ require_index.default.debug("sadot - before create hook");
215
+ const { fields } = options;
216
+ const modelType = instance.constructor.name;
217
+ const identifiers = require_scopeAttributes.default(instance, scopeAttributes);
218
+ const fieldDefinitions = await getFieldDefinitions({
219
+ modelType,
220
+ modelOptions,
221
+ identifiers,
222
+ options,
223
+ instance,
224
+ sadotOptions
225
+ });
226
+ const fieldsWithDefaultValue = fieldDefinitions.filter((def) => ![null, void 0].includes(def.defaultValue));
227
+ if (fieldsWithDefaultValue.length) {
228
+ instance.customFields ||= {};
229
+ fieldsWithDefaultValue.filter((def) => instance.customFields?.[def.name] === void 0).forEach(({ name, defaultValue }) => {
230
+ instance.customFields[name] = defaultValue;
231
+ });
232
+ }
233
+ let requiredFieldsNames;
234
+ if (sadotOptions.getRequiredCustomFields) requiredFieldsNames = await Promise.resolve(sadotOptions.getRequiredCustomFields(instance, fieldDefinitions, options));
235
+ else requiredFieldsNames = Array.from(new Set(fieldDefinitions.filter(({ required }) => required).map(({ name }) => name)));
236
+ const { customFields } = instance;
237
+ const fieldsNames = Object.keys(customFields ?? {});
238
+ const missingFields = requiredFieldsNames.filter((name) => !fieldsNames.includes(name));
239
+ if (missingFields?.length) throw new require_index$2.MissingRequiredCustomFieldError(missingFields);
240
+ await validateModel(instance, options, scopeAttributes, modelOptions, true);
241
+ formatDates(fieldDefinitions, instance);
242
+ const customFieldsIdx = fields.indexOf("customFields");
243
+ if (customFieldsIdx === -1 || !customFields || !Object.keys(customFields).length) return;
244
+ await require_updateInstanceValues.default({
245
+ modelId: instance.id,
246
+ modelType,
247
+ identifiers,
248
+ customFields,
249
+ options: {
250
+ useCustomFieldsEntries: sadotOptions.useCustomFieldsEntries,
251
+ transaction: options.transaction,
252
+ modelOptions
253
+ }
254
+ });
255
+ fields.splice(customFieldsIdx, 1);
256
+ };
257
+ /**
258
+ * Hook to handle validation and custom fields during update
259
+ */
260
+ const beforeUpdate = (scopeAttributes, modelOptions = {}, sadotOptions = { useCustomFieldsEntries: false }) => async (instance, options) => {
261
+ require_index.default.debug("sadot - before update hook");
262
+ const { fields } = options;
263
+ const modelType = instance.constructor.name;
264
+ const identifiers = require_scopeAttributes.default(instance, scopeAttributes);
265
+ const fieldDefinitions = await getFieldDefinitions({
266
+ modelType,
267
+ modelOptions,
268
+ identifiers,
269
+ options,
270
+ instance,
271
+ sadotOptions
272
+ });
273
+ await validateModel(instance, options, scopeAttributes, modelOptions, false);
274
+ formatDates(fieldDefinitions, instance);
275
+ const customFieldsIdx = fields.indexOf("customFields");
276
+ if (customFieldsIdx > -1) {
277
+ const { customFields } = instance;
278
+ if (!Object.keys(customFields).length) return;
279
+ await require_updateInstanceValues.default({
280
+ modelId: instance.id,
281
+ modelType,
282
+ identifiers,
283
+ customFields,
284
+ options: {
285
+ useCustomFieldsEntries: sadotOptions.useCustomFieldsEntries,
286
+ transaction: options.transaction,
287
+ modelOptions
288
+ }
289
+ });
290
+ fields.splice(customFieldsIdx, 1);
291
+ }
292
+ };
293
+ /**
294
+ * Hook to enable individual hooks for bulk create operations
295
+ */
296
+ const beforeBulkCreate = (options) => {
297
+ options.individualHooks = true;
298
+ };
299
+ /**
300
+ * Hook to enable individual hooks for bulk update operations
301
+ */
302
+ const beforeBulkUpdate = (options) => {
303
+ options.individualHooks = true;
304
+ };
305
+
306
+ //#endregion
307
+ exports.beforeBulkCreate = beforeBulkCreate;
308
+ exports.beforeBulkUpdate = beforeBulkUpdate;
309
+ exports.beforeCreate = beforeCreate;
310
+ exports.beforeUpdate = beforeUpdate;
@@ -0,0 +1,302 @@
1
+ import logger_default from "../utils/logger/index.js";
2
+ import { CustomFieldDefinitionType } from "../utils/constants/index.js";
3
+ import { InvalidValueError, MissingRequiredCustomFieldError } from "../errors/index.js";
4
+ import { findAll, findByModelTypeId } from "../repository/definition.js";
5
+ import { findAllByModelType } from "../repository/validator.js";
6
+ import scopeAttributes_default from "../utils/scopeAttributes.js";
7
+ import updateInstanceValues_default from "./utils/updateInstanceValues.js";
8
+ import Joi from "joi";
9
+ import { BadRequest } from "@autofleet/errors";
10
+ import Ajv from "ajv";
11
+ import addFormats from "ajv-formats";
12
+ import ajvErrors from "ajv-errors";
13
+
14
+ //#region src/hooks/hooks.ts
15
+ const CUSTOM_VALIDATOR_ATTRIBUTES_TO_PULL = [
16
+ "id",
17
+ "schema",
18
+ "modelType",
19
+ "entityId",
20
+ "disabled"
21
+ ];
22
+ const ajv = new Ajv({
23
+ allErrors: true,
24
+ strict: false,
25
+ strictTypes: false,
26
+ $data: true
27
+ });
28
+ addFormats(ajv);
29
+ ajvErrors(ajv);
30
+ /**
31
+ * Helper function to manually copy object properties
32
+ * This is more efficient for large objects and avoids excessive object creation
33
+ */
34
+ const manualObjectCopy = (sourceObj, additionalProps) => ({
35
+ __proto__: null,
36
+ ...sourceObj,
37
+ ...additionalProps
38
+ });
39
+ /**
40
+ * Fetches complete custom fields for an instance by merging DB values with update values
41
+ * This is needed for partial updates to ensure all related fields are available for validation
42
+ */
43
+ const getCompleteCustomFields = async (instance, options) => {
44
+ if (!instance.id || !instance.customFields || Object.keys(instance.customFields).length === 0) return instance.customFields || {};
45
+ try {
46
+ const currentCustomFields = await instance.constructor.findOne({
47
+ where: { id: instance.id },
48
+ attributes: ["customFields"],
49
+ transaction: options.transaction,
50
+ raw: true
51
+ });
52
+ if (currentCustomFields?.customFields) {
53
+ const completeFields = manualObjectCopy(currentCustomFields.customFields, instance.customFields);
54
+ logger_default.debug("sadot - fetched complete custom fields for validation", {
55
+ fieldsCount: Object.keys(completeFields).length,
56
+ updateFieldsCount: Object.keys(instance.customFields).length
57
+ });
58
+ return completeFields;
59
+ }
60
+ } catch (error) {
61
+ logger_default.error("sadot - error fetching complete model for validation", { error });
62
+ }
63
+ return instance.customFields || {};
64
+ };
65
+ const buildPreChangeState = (instance) => {
66
+ const beforeFull = { ...instance.dataValues };
67
+ (instance.changed?.() || []).forEach((key) => {
68
+ const prevVal = instance.previous?.(key);
69
+ if (prevVal !== void 0) beforeFull[key] = prevVal;
70
+ });
71
+ const prevCF = instance.previous?.("customFields");
72
+ if (prevCF !== void 0) beforeFull.customFields = prevCF;
73
+ return beforeFull;
74
+ };
75
+ const formatAjvErrors = (errors) => errors.reduce((acc, err) => {
76
+ const key = ((err.instancePath || "").split("/").filter(Boolean).join(".").replace(/^after\./, "") + (err.keyword === "required" ? `.${err.params?.missingProperty}` : "")).replace(/^\./, "") || "root";
77
+ acc[key] = err.message || "Invalid value";
78
+ return acc;
79
+ }, {});
80
+ /**
81
+ * Validates the model using custom validators
82
+ */
83
+ const validateModel = async (instance, options, scopeAttributes, modelOptions = {}, isCreate = false) => {
84
+ const modelType = instance.constructor.name;
85
+ logger_default.debug("sadot - validating model", {
86
+ isCreate,
87
+ modelType
88
+ });
89
+ const identifiers = scopeAttributes_default(instance, scopeAttributes);
90
+ logger_default.debug("sadot - identifiers", { identifiers });
91
+ if (!identifiers || Object.keys(identifiers).length === 0) {
92
+ logger_default.debug("sadot - skipping validation: no identifiers");
93
+ return;
94
+ }
95
+ const entityId = Object.values(identifiers)[0];
96
+ logger_default.debug("sadot - entityId", { entityId });
97
+ if (!entityId) {
98
+ logger_default.debug("sadot - skipping validation: no entityId");
99
+ return;
100
+ }
101
+ let validatorsPromise;
102
+ let cacheKey;
103
+ if (options.transaction) {
104
+ options.transaction.validationsCache ??= /* @__PURE__ */ new Map();
105
+ cacheKey = `${modelType}-${entityId}`;
106
+ validatorsPromise = options.transaction.validationsCache.get(cacheKey);
107
+ }
108
+ if (!validatorsPromise) {
109
+ validatorsPromise = findAllByModelType(modelType, entityId, {
110
+ transaction: options.transaction,
111
+ attributes: CUSTOM_VALIDATOR_ATTRIBUTES_TO_PULL,
112
+ modelOptions
113
+ });
114
+ if (options.transaction) options?.transaction?.validationsCache.set(cacheKey, validatorsPromise);
115
+ }
116
+ const validators = await validatorsPromise;
117
+ logger_default.debug("sadot - validators found", { count: validators.length });
118
+ if (!validators.length) {
119
+ logger_default.debug("sadot - skipping validation: no validators found");
120
+ return;
121
+ }
122
+ let originalValues = null;
123
+ if (!isCreate) originalValues = buildPreChangeState(instance);
124
+ const completeCustomFields = !isCreate ? await getCompleteCustomFields(instance, options) : instance.customFields || {};
125
+ for (const validator of validators) {
126
+ const { schema } = validator;
127
+ const typedSchema = schema;
128
+ logger_default.debug("sadot - validating with schema", {
129
+ schema,
130
+ hasAfterProps: !!typedSchema.properties?.after,
131
+ hasBeforeProps: !!typedSchema.properties?.before
132
+ });
133
+ if (isCreate) {
134
+ if (typedSchema.properties?.after) {
135
+ const validateSchema = ajv.compile({
136
+ ...schema,
137
+ properties: { after: typedSchema.properties.after }
138
+ });
139
+ if (!validateSchema(JSON.parse(JSON.stringify({ after: {
140
+ ...instance.dataValues,
141
+ customFields: completeCustomFields
142
+ } })))) {
143
+ const errorDetails = validateSchema.errors?.map((err) => `${err.instancePath || ""} ${err.message || "Invalid value"}`).join(", ");
144
+ const formattedErrors = formatAjvErrors(validateSchema.errors);
145
+ throw new BadRequest([/* @__PURE__ */ new Error(`Validation failed for ${modelType}: ${errorDetails}`)], void 0, { customError: formattedErrors });
146
+ }
147
+ }
148
+ } else {
149
+ const validateSchema = ajv.compile(typedSchema);
150
+ const afterObj = manualObjectCopy(instance.dataValues);
151
+ afterObj.customFields = completeCustomFields;
152
+ const payload = {
153
+ before: originalValues,
154
+ after: afterObj
155
+ };
156
+ const isValid = validateSchema(JSON.parse(JSON.stringify(payload)));
157
+ logger_default.debug("sadot - validation result", {
158
+ isValid,
159
+ test: {
160
+ before: originalValues,
161
+ after: afterObj
162
+ }
163
+ });
164
+ if (!isValid) {
165
+ const errorDetails = validateSchema.errors?.map((err) => `${err.instancePath || ""} ${err.message || "Invalid value"}`).join(", ");
166
+ const formattedErrors = formatAjvErrors(validateSchema.errors);
167
+ throw new BadRequest([/* @__PURE__ */ new Error(`Validation failed for ${modelType}: ${errorDetails}`)], void 0, { customError: formattedErrors });
168
+ }
169
+ }
170
+ }
171
+ };
172
+ const getFieldDefinitions = async ({ modelType, modelOptions, identifiers, options, instance, sadotOptions }) => {
173
+ const { include, useEntityIdFromInclude } = modelOptions;
174
+ if (sadotOptions.hasTypeId && instance?.typeId) return findByModelTypeId(instance.typeId, {
175
+ withDisabled: false,
176
+ transaction: options.transaction,
177
+ entityIds: identifiers,
178
+ modelType,
179
+ modelOptions
180
+ });
181
+ const where = {
182
+ modelType,
183
+ disabled: false,
184
+ ...!useEntityIdFromInclude && { entityId: identifiers }
185
+ };
186
+ return findAll(where, {
187
+ withDisabled: false,
188
+ transaction: options.transaction,
189
+ include: include?.(identifiers)
190
+ });
191
+ };
192
+ const formatDates = (fieldDefinitions, instance) => {
193
+ (fieldDefinitions || []).forEach((fieldDefinition) => {
194
+ const { fieldType, name } = fieldDefinition;
195
+ if ([CustomFieldDefinitionType.DATE, CustomFieldDefinitionType.DATETIME].includes(fieldType)) {
196
+ const value = instance.customFields?.[name];
197
+ if (value) {
198
+ const { value: joiValue, error: validationError } = Joi.date().validate(value);
199
+ if (validationError) throw new InvalidValueError(value, name, validationError);
200
+ instance.customFields[name] = joiValue.toISOString();
201
+ }
202
+ }
203
+ });
204
+ };
205
+ /**
206
+ * Hook to handle validation and custom fields during creation
207
+ */
208
+ const beforeCreate = (scopeAttributes, modelOptions = {}, sadotOptions = { useCustomFieldsEntries: false }) => async (instance, options) => {
209
+ logger_default.debug("sadot - before create hook");
210
+ const { fields } = options;
211
+ const modelType = instance.constructor.name;
212
+ const identifiers = scopeAttributes_default(instance, scopeAttributes);
213
+ const fieldDefinitions = await getFieldDefinitions({
214
+ modelType,
215
+ modelOptions,
216
+ identifiers,
217
+ options,
218
+ instance,
219
+ sadotOptions
220
+ });
221
+ const fieldsWithDefaultValue = fieldDefinitions.filter((def) => ![null, void 0].includes(def.defaultValue));
222
+ if (fieldsWithDefaultValue.length) {
223
+ instance.customFields ||= {};
224
+ fieldsWithDefaultValue.filter((def) => instance.customFields?.[def.name] === void 0).forEach(({ name, defaultValue }) => {
225
+ instance.customFields[name] = defaultValue;
226
+ });
227
+ }
228
+ let requiredFieldsNames;
229
+ if (sadotOptions.getRequiredCustomFields) requiredFieldsNames = await Promise.resolve(sadotOptions.getRequiredCustomFields(instance, fieldDefinitions, options));
230
+ else requiredFieldsNames = Array.from(new Set(fieldDefinitions.filter(({ required }) => required).map(({ name }) => name)));
231
+ const { customFields } = instance;
232
+ const fieldsNames = Object.keys(customFields ?? {});
233
+ const missingFields = requiredFieldsNames.filter((name) => !fieldsNames.includes(name));
234
+ if (missingFields?.length) throw new MissingRequiredCustomFieldError(missingFields);
235
+ await validateModel(instance, options, scopeAttributes, modelOptions, true);
236
+ formatDates(fieldDefinitions, instance);
237
+ const customFieldsIdx = fields.indexOf("customFields");
238
+ if (customFieldsIdx === -1 || !customFields || !Object.keys(customFields).length) return;
239
+ await updateInstanceValues_default({
240
+ modelId: instance.id,
241
+ modelType,
242
+ identifiers,
243
+ customFields,
244
+ options: {
245
+ useCustomFieldsEntries: sadotOptions.useCustomFieldsEntries,
246
+ transaction: options.transaction,
247
+ modelOptions
248
+ }
249
+ });
250
+ fields.splice(customFieldsIdx, 1);
251
+ };
252
+ /**
253
+ * Hook to handle validation and custom fields during update
254
+ */
255
+ const beforeUpdate = (scopeAttributes, modelOptions = {}, sadotOptions = { useCustomFieldsEntries: false }) => async (instance, options) => {
256
+ logger_default.debug("sadot - before update hook");
257
+ const { fields } = options;
258
+ const modelType = instance.constructor.name;
259
+ const identifiers = scopeAttributes_default(instance, scopeAttributes);
260
+ const fieldDefinitions = await getFieldDefinitions({
261
+ modelType,
262
+ modelOptions,
263
+ identifiers,
264
+ options,
265
+ instance,
266
+ sadotOptions
267
+ });
268
+ await validateModel(instance, options, scopeAttributes, modelOptions, false);
269
+ formatDates(fieldDefinitions, instance);
270
+ const customFieldsIdx = fields.indexOf("customFields");
271
+ if (customFieldsIdx > -1) {
272
+ const { customFields } = instance;
273
+ if (!Object.keys(customFields).length) return;
274
+ await updateInstanceValues_default({
275
+ modelId: instance.id,
276
+ modelType,
277
+ identifiers,
278
+ customFields,
279
+ options: {
280
+ useCustomFieldsEntries: sadotOptions.useCustomFieldsEntries,
281
+ transaction: options.transaction,
282
+ modelOptions
283
+ }
284
+ });
285
+ fields.splice(customFieldsIdx, 1);
286
+ }
287
+ };
288
+ /**
289
+ * Hook to enable individual hooks for bulk create operations
290
+ */
291
+ const beforeBulkCreate = (options) => {
292
+ options.individualHooks = true;
293
+ };
294
+ /**
295
+ * Hook to enable individual hooks for bulk update operations
296
+ */
297
+ const beforeBulkUpdate = (options) => {
298
+ options.individualHooks = true;
299
+ };
300
+
301
+ //#endregion
302
+ export { beforeBulkCreate, beforeBulkUpdate, beforeCreate, beforeUpdate };
@@ -0,0 +1,3 @@
1
+ const require_enrich = require('./enrich.cjs');
2
+ const require_find = require('./find.cjs');
3
+ const require_hooks = require('./hooks.cjs');
@@ -0,0 +1,5 @@
1
+ import enrich_default from "./enrich.js";
2
+ import { beforeFind } from "./find.js";
3
+ import { beforeBulkCreate, beforeBulkUpdate, beforeCreate, beforeUpdate } from "./hooks.js";
4
+
5
+ export { };
@@ -0,0 +1,27 @@
1
+ const require_value = require('../../repository/value.cjs');
2
+ const require_entries = require('../../repository/entries.cjs');
3
+
4
+ //#region src/hooks/utils/updateInstanceValues.ts
5
+ const updateInstanceValues = async ({ modelId, modelType, identifiers, customFields, options = {
6
+ modelOptions: {},
7
+ useCustomFieldsEntries: false
8
+ } }) => {
9
+ await require_value.updateValues(modelType, modelId, identifiers, customFields, {
10
+ ...options,
11
+ modelOptions: options.modelOptions ?? {}
12
+ });
13
+ if (!options?.useCustomFieldsEntries) return;
14
+ const { dataValues: { customFields: oldCustomFields } } = await require_entries.findEntriesByModelId(modelId, options) ?? { dataValues: {} };
15
+ const newCustomFields = {
16
+ ...oldCustomFields,
17
+ ...customFields
18
+ };
19
+ await require_entries.updateEntries(modelId, modelType, newCustomFields, identifiers, {
20
+ ...options,
21
+ modelOptions: options.modelOptions ?? {}
22
+ });
23
+ };
24
+ var updateInstanceValues_default = updateInstanceValues;
25
+
26
+ //#endregion
27
+ exports.default = updateInstanceValues_default;
@@ -0,0 +1,27 @@
1
+ import { updateValues } from "../../repository/value.js";
2
+ import { findEntriesByModelId, updateEntries } from "../../repository/entries.js";
3
+
4
+ //#region src/hooks/utils/updateInstanceValues.ts
5
+ const updateInstanceValues = async ({ modelId, modelType, identifiers, customFields, options = {
6
+ modelOptions: {},
7
+ useCustomFieldsEntries: false
8
+ } }) => {
9
+ await updateValues(modelType, modelId, identifiers, customFields, {
10
+ ...options,
11
+ modelOptions: options.modelOptions ?? {}
12
+ });
13
+ if (!options?.useCustomFieldsEntries) return;
14
+ const { dataValues: { customFields: oldCustomFields } } = await findEntriesByModelId(modelId, options) ?? { dataValues: {} };
15
+ const newCustomFields = {
16
+ ...oldCustomFields,
17
+ ...customFields
18
+ };
19
+ await updateEntries(modelId, modelType, newCustomFields, identifiers, {
20
+ ...options,
21
+ modelOptions: options.modelOptions ?? {}
22
+ });
23
+ };
24
+ var updateInstanceValues_default = updateInstanceValues;
25
+
26
+ //#endregion
27
+ export { updateInstanceValues_default as default };