@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,23 @@
1
+ import { customFields } from "@autofleet/common-types";
2
+
3
+ //#region src/utils/constants/index.d.ts
4
+ declare const supportedEntities: readonly ["businessModelId", "fleetId", "demandSourceId"];
5
+ /**
6
+ * Supported custom field types
7
+ */
8
+ declare enum CustomFieldDefinitionType {
9
+ NUMBER = "number",
10
+ BOOLEAN = "boolean",
11
+ DATE = "date",
12
+ DATETIME = "datetime",
13
+ TEXT = "text",
14
+ IMAGE = "image",
15
+ SELECT = "select",
16
+ STATUS = "status",
17
+ FILE = "file",
18
+ MULTI_SELECT_STATUS = "multi-select-status",
19
+ MULTI_SELECT_DROPDOWN = "multi-select-dropdown",
20
+ }
21
+ declare const CUSTOM_FIELDS_FILTER_SCOPE: typeof customFields.CUSTOM_FIELDS_FILTER_SCOPE;
22
+ //#endregion
23
+ export { CUSTOM_FIELDS_FILTER_SCOPE, CustomFieldDefinitionType, supportedEntities };
@@ -0,0 +1,29 @@
1
+ import { customFields } from "@autofleet/common-types";
2
+
3
+ //#region src/utils/constants/index.ts
4
+ const supportedEntities = [
5
+ "businessModelId",
6
+ "fleetId",
7
+ "demandSourceId"
8
+ ];
9
+ /**
10
+ * Supported custom field types
11
+ */
12
+ let CustomFieldDefinitionType = /* @__PURE__ */ function(CustomFieldDefinitionType$1) {
13
+ CustomFieldDefinitionType$1["NUMBER"] = "number";
14
+ CustomFieldDefinitionType$1["BOOLEAN"] = "boolean";
15
+ CustomFieldDefinitionType$1["DATE"] = "date";
16
+ CustomFieldDefinitionType$1["DATETIME"] = "datetime";
17
+ CustomFieldDefinitionType$1["TEXT"] = "text";
18
+ CustomFieldDefinitionType$1["IMAGE"] = "image";
19
+ CustomFieldDefinitionType$1["SELECT"] = "select";
20
+ CustomFieldDefinitionType$1["STATUS"] = "status";
21
+ CustomFieldDefinitionType$1["FILE"] = "file";
22
+ CustomFieldDefinitionType$1["MULTI_SELECT_STATUS"] = "multi-select-status";
23
+ CustomFieldDefinitionType$1["MULTI_SELECT_DROPDOWN"] = "multi-select-dropdown";
24
+ return CustomFieldDefinitionType$1;
25
+ }({});
26
+ const CUSTOM_FIELDS_FILTER_SCOPE = customFields.CUSTOM_FIELDS_FILTER_SCOPE;
27
+
28
+ //#endregion
29
+ export { CUSTOM_FIELDS_FILTER_SCOPE, CustomFieldDefinitionType, supportedEntities };
@@ -0,0 +1,15 @@
1
+ const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
2
+ let sequelize = require("sequelize");
3
+ let sequelize_typescript = require("sequelize-typescript");
4
+
5
+ //#region src/utils/db/index.ts
6
+ var db_default = (databaseConfig) => {
7
+ const config = databaseConfig[process.env.NODE_ENV || "test"];
8
+ let sequelize$1;
9
+ if (config.use_env_variable) sequelize$1 = new sequelize_typescript.Sequelize(process.env[config.use_env_variable], config);
10
+ else sequelize$1 = new sequelize_typescript.Sequelize(config.database, config.username, config.password, config);
11
+ return sequelize$1;
12
+ };
13
+
14
+ //#endregion
15
+ exports.default = db_default;
@@ -0,0 +1,14 @@
1
+ import { QueryTypes } from "sequelize";
2
+ import { Sequelize } from "sequelize-typescript";
3
+
4
+ //#region src/utils/db/index.ts
5
+ var db_default = (databaseConfig) => {
6
+ const config = databaseConfig[process.env.NODE_ENV || "test"];
7
+ let sequelize;
8
+ if (config.use_env_variable) sequelize = new Sequelize(process.env[config.use_env_variable], config);
9
+ else sequelize = new Sequelize(config.database, config.username, config.password, config);
10
+ return sequelize;
11
+ };
12
+
13
+ //#endregion
14
+ export { db_default as default };
@@ -0,0 +1,23 @@
1
+ const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
2
+ const require_index = require('../constants/index.cjs');
3
+ let sequelize = require("sequelize");
4
+ let sequelize_typescript = require("sequelize-typescript");
5
+ let node_crypto = require("node:crypto");
6
+
7
+ //#region src/utils/helpers/index.ts
8
+ const generateRandomString = (length = 5) => {
9
+ const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
10
+ return Array.from({ length }, () => characters.charAt((0, node_crypto.randomInt)(52))).join("");
11
+ };
12
+ const generateCustomFieldSearchQueryPayload = (searchTerm, model, entityId, customFieldsTypesToExclude = [require_index.CustomFieldDefinitionType.DATETIME, require_index.CustomFieldDefinitionType.DATE]) => {
13
+ const excludedTypesString = customFieldsTypesToExclude.map((type) => `'${type}'`).join(",");
14
+ const subQuery = `SELECT cv.model_id FROM "custom_field_values" AS cv INNER JOIN custom_field_definitions AS cd ON cv.custom_field_definition_id = cd.id AND cd.entity_id = '${entityId}' AND cd.model_type = '${model.name}' AND cd.deleted_at IS NULL` + (excludedTypesString ? ` AND cd.field_type NOT IN (${excludedTypesString})` : "") + " WHERE cv.deleted_at IS NULL AND CAST(cv.value AS TEXT) ILIKE :searchTerm";
15
+ return {
16
+ where: { id: { [sequelize.Op.in]: sequelize_typescript.Sequelize.literal(`(${subQuery})`) } },
17
+ replacements: { searchTerm: `%${searchTerm}%` }
18
+ };
19
+ };
20
+
21
+ //#endregion
22
+ exports.generateCustomFieldSearchQueryPayload = generateCustomFieldSearchQueryPayload;
23
+ exports.generateRandomString = generateRandomString;
@@ -0,0 +1,30 @@
1
+ import { CustomFieldDefinitionType } from "../constants/index.cjs";
2
+ import { ModelStatic } from "sequelize-typescript";
3
+ import { BindOrReplacements, WhereOptions } from "sequelize";
4
+
5
+ //#region src/utils/helpers/index.d.ts
6
+
7
+ /**
8
+ * Builds a WHERE clause and replacements for free-text search by custom fields.
9
+ *
10
+ * This function constructs a WHERE clause and replacement bindings that allow searching
11
+ * for a given term within custom fields associated with a specific model type and entity ID.
12
+ * The WHERE clause and replacements are designed to be added to the main query.
13
+ *
14
+ * @param {string} searchTerm - The term to search for within custom fields.
15
+ * @param {ModelStatic} model - The Sequelize model representing the entity type to search for.
16
+ * @param {string} entityId - The entity ID to filter the custom fields by.
17
+ * @param {CustomFieldDefinitionType[]} excludedCustomFieldsTypes - An array of custom field types
18
+ * to exclude from the search
19
+ *
20
+ * @returns {CustomFieldsSearchPayload} - An object containing the WHERE clause and replacements
21
+ * for Sequelize.
22
+ */
23
+ interface CustomFieldsSearchPayload {
24
+ where: WhereOptions;
25
+ replacements: BindOrReplacements;
26
+ }
27
+ declare const generateRandomString: (length?: number) => string;
28
+ declare const generateCustomFieldSearchQueryPayload: (searchTerm: string, model: ModelStatic, entityId: string, customFieldsTypesToExclude?: CustomFieldDefinitionType[]) => CustomFieldsSearchPayload;
29
+ //#endregion
30
+ export { generateCustomFieldSearchQueryPayload, generateRandomString };
@@ -0,0 +1,30 @@
1
+ import { CustomFieldDefinitionType } from "../constants/index.js";
2
+ import { BindOrReplacements, WhereOptions } from "sequelize";
3
+ import { ModelStatic } from "sequelize-typescript";
4
+
5
+ //#region src/utils/helpers/index.d.ts
6
+
7
+ /**
8
+ * Builds a WHERE clause and replacements for free-text search by custom fields.
9
+ *
10
+ * This function constructs a WHERE clause and replacement bindings that allow searching
11
+ * for a given term within custom fields associated with a specific model type and entity ID.
12
+ * The WHERE clause and replacements are designed to be added to the main query.
13
+ *
14
+ * @param {string} searchTerm - The term to search for within custom fields.
15
+ * @param {ModelStatic} model - The Sequelize model representing the entity type to search for.
16
+ * @param {string} entityId - The entity ID to filter the custom fields by.
17
+ * @param {CustomFieldDefinitionType[]} excludedCustomFieldsTypes - An array of custom field types
18
+ * to exclude from the search
19
+ *
20
+ * @returns {CustomFieldsSearchPayload} - An object containing the WHERE clause and replacements
21
+ * for Sequelize.
22
+ */
23
+ interface CustomFieldsSearchPayload {
24
+ where: WhereOptions;
25
+ replacements: BindOrReplacements;
26
+ }
27
+ declare const generateRandomString: (length?: number) => string;
28
+ declare const generateCustomFieldSearchQueryPayload: (searchTerm: string, model: ModelStatic, entityId: string, customFieldsTypesToExclude?: CustomFieldDefinitionType[]) => CustomFieldsSearchPayload;
29
+ //#endregion
30
+ export { generateCustomFieldSearchQueryPayload, generateRandomString };
@@ -0,0 +1,21 @@
1
+ import { CustomFieldDefinitionType } from "../constants/index.js";
2
+ import { Op } from "sequelize";
3
+ import { Sequelize } from "sequelize-typescript";
4
+ import { randomInt } from "node:crypto";
5
+
6
+ //#region src/utils/helpers/index.ts
7
+ const generateRandomString = (length = 5) => {
8
+ const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
9
+ return Array.from({ length }, () => characters.charAt(randomInt(52))).join("");
10
+ };
11
+ const generateCustomFieldSearchQueryPayload = (searchTerm, model, entityId, customFieldsTypesToExclude = [CustomFieldDefinitionType.DATETIME, CustomFieldDefinitionType.DATE]) => {
12
+ const excludedTypesString = customFieldsTypesToExclude.map((type) => `'${type}'`).join(",");
13
+ const subQuery = `SELECT cv.model_id FROM "custom_field_values" AS cv INNER JOIN custom_field_definitions AS cd ON cv.custom_field_definition_id = cd.id AND cd.entity_id = '${entityId}' AND cd.model_type = '${model.name}' AND cd.deleted_at IS NULL` + (excludedTypesString ? ` AND cd.field_type NOT IN (${excludedTypesString})` : "") + " WHERE cv.deleted_at IS NULL AND CAST(cv.value AS TEXT) ILIKE :searchTerm";
14
+ return {
15
+ where: { id: { [Op.in]: Sequelize.literal(`(${subQuery})`) } },
16
+ replacements: { searchTerm: `%${searchTerm}%` }
17
+ };
18
+ };
19
+
20
+ //#endregion
21
+ export { generateCustomFieldSearchQueryPayload, generateRandomString };
@@ -0,0 +1,115 @@
1
+ const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
2
+ const require_index = require('./logger/index.cjs');
3
+ const require_CustomFieldValue = require('../models/CustomFieldValue.cjs');
4
+ const require_CustomFieldDefinition = require('../models/CustomFieldDefinition.cjs');
5
+ const require_CustomValidator = require('../models/CustomValidator.cjs');
6
+ require('../models/index.cjs');
7
+ const require_enrich = require('../hooks/enrich.cjs');
8
+ const require_find = require('../hooks/find.cjs');
9
+ const require_hooks = require('../hooks/hooks.cjs');
10
+ require('../hooks/index.cjs');
11
+ const require_filter = require('../scopes/filter.cjs');
12
+ require('../scopes/index.cjs');
13
+ let sequelize = require("sequelize");
14
+ let _autofleet_common_types = require("@autofleet/common-types");
15
+ let _autofleet_common_types_lib_custom_fields = require("@autofleet/common-types/lib/custom-fields");
16
+
17
+ //#region src/utils/init.ts
18
+ const { CUSTOM_FIELDS_FILTER_SCOPE } = _autofleet_common_types.customFields;
19
+ const addHooks = (models, getModel, sadotOptions = { useCustomFieldsEntries: false }) => {
20
+ models.forEach(async ({ name, scopeAttributes, modelOptions, hasTypeId, getRequiredCustomFields }) => {
21
+ try {
22
+ const model = getModel(name);
23
+ if (!model) {
24
+ require_index.default.warn("sadot - tried to addHooks to a model that does not exist yet", {
25
+ name,
26
+ scopeAttributes
27
+ });
28
+ return;
29
+ }
30
+ model.rawAttributes.customFields = { type: sequelize.DataTypes.VIRTUAL };
31
+ model.refreshAttributes();
32
+ const enrichOptions = {
33
+ ...sadotOptions,
34
+ hasTypeId: hasTypeId ?? false,
35
+ getRequiredCustomFields
36
+ };
37
+ model.addHook("beforeFind", "sadot-beforeFind", require_find.beforeFind(scopeAttributes));
38
+ model.addHook("beforeBulkCreate", "sadot-beforeBulkCreate", require_hooks.beforeBulkCreate);
39
+ model.addHook("beforeBulkUpdate", "sadot-beforeBulkUpdate", require_hooks.beforeBulkUpdate);
40
+ model.addHook("beforeCreate", "sadot-beforeCreate", require_hooks.beforeCreate(scopeAttributes, modelOptions, enrichOptions));
41
+ model.addHook("beforeUpdate", "sadot-beforeUpdate", require_hooks.beforeUpdate(scopeAttributes, modelOptions, enrichOptions));
42
+ model.addHook("afterFind", "sadot-afterFind", require_enrich.default(name, scopeAttributes, "afterFind", modelOptions, enrichOptions));
43
+ model.addHook("afterUpdate", "sadot-afterUpdate", require_enrich.default(name, scopeAttributes, void 0, modelOptions, enrichOptions));
44
+ model.addHook("afterCreate", "sadot-afterCreate", require_enrich.default(name, scopeAttributes, void 0, modelOptions, enrichOptions));
45
+ } catch (e) {
46
+ require_index.default.error(`Could not add custom fields hook to model ${name}. `, e);
47
+ }
48
+ });
49
+ };
50
+ const removeHooks = (models, getModel) => {
51
+ models.forEach(async ({ name }) => {
52
+ try {
53
+ const model = getModel(name);
54
+ if (!model) return;
55
+ if (model.rawAttributes.customFields) {
56
+ delete model.rawAttributes.customFields;
57
+ model.refreshAttributes();
58
+ }
59
+ model.removeHook("beforeFind", "sadot-beforeFind");
60
+ model.removeHook("beforeBulkCreate", "sadot-beforeBulkCreate");
61
+ model.removeHook("beforeBulkUpdate", "sadot-beforeBulkUpdate");
62
+ model.removeHook("beforeCreate", "sadot-beforeCreate");
63
+ model.removeHook("beforeUpdate", "sadot-beforeUpdate");
64
+ model.removeHook("afterFind", "sadot-afterFind");
65
+ model.removeHook("afterUpdate", "sadot-afterUpdate");
66
+ } catch (e) {
67
+ require_index.default.error(`Could not add custom fields hook to model ${name}. `, e);
68
+ }
69
+ });
70
+ };
71
+ /**
72
+ * Necessary associations for the {@link customFieldsFilterScope} scope
73
+ */
74
+ const addAssociations = (model, modelName, options) => {
75
+ if (options?.useCustomFieldsEntries) return;
76
+ model.hasMany(require_CustomFieldValue.default, {
77
+ foreignKey: "modelId",
78
+ as: "customFieldValue"
79
+ });
80
+ require_CustomFieldValue.default.belongsTo(model, {
81
+ foreignKey: "modelId",
82
+ as: modelName
83
+ });
84
+ };
85
+ const addScopes = (models, getModel, options = { useCustomFieldsEntries: false }) => {
86
+ models.forEach(async ({ name, scopeAttributes }) => {
87
+ try {
88
+ const model = getModel(name);
89
+ if (!model) {
90
+ require_index.default.warn("sadot - tried to addScopes to a model that does not exist yet", {
91
+ name,
92
+ scopeAttributes
93
+ });
94
+ return;
95
+ }
96
+ addAssociations(model, name, options);
97
+ model.addScope(CUSTOM_FIELDS_FILTER_SCOPE, require_filter.customFieldsFilterScope(name, options));
98
+ model.addScope(_autofleet_common_types_lib_custom_fields.CUSTOM_FIELDS_SORT_SCOPE, require_filter.customFieldsSortScope(name, options));
99
+ } catch (e) {
100
+ require_index.default.error(`Could not add custom fields scopes to model ${name}. `, e);
101
+ }
102
+ });
103
+ };
104
+ const applyCustomAssociation = (models) => {
105
+ models.forEach(({ modelOptions }) => {
106
+ modelOptions?.customAssociation?.(require_CustomFieldDefinition.default);
107
+ modelOptions?.customAssociation?.(require_CustomValidator.default);
108
+ });
109
+ };
110
+
111
+ //#endregion
112
+ exports.addHooks = addHooks;
113
+ exports.addScopes = addScopes;
114
+ exports.applyCustomAssociation = applyCustomAssociation;
115
+ exports.removeHooks = removeHooks;
@@ -0,0 +1,111 @@
1
+ import logger_default from "./logger/index.js";
2
+ import CustomFieldValue_default from "../models/CustomFieldValue.js";
3
+ import CustomFieldDefinition_default from "../models/CustomFieldDefinition.js";
4
+ import CustomValidator_default from "../models/CustomValidator.js";
5
+ import "../models/index.js";
6
+ import enrich_default from "../hooks/enrich.js";
7
+ import { beforeFind } from "../hooks/find.js";
8
+ import { beforeBulkCreate, beforeBulkUpdate, beforeCreate, beforeUpdate } from "../hooks/hooks.js";
9
+ import "../hooks/index.js";
10
+ import { customFieldsFilterScope, customFieldsSortScope } from "../scopes/filter.js";
11
+ import "../scopes/index.js";
12
+ import { DataTypes } from "sequelize";
13
+ import { customFields } from "@autofleet/common-types";
14
+ import { CUSTOM_FIELDS_SORT_SCOPE } from "@autofleet/common-types/lib/custom-fields";
15
+
16
+ //#region src/utils/init.ts
17
+ const { CUSTOM_FIELDS_FILTER_SCOPE } = customFields;
18
+ const addHooks = (models, getModel, sadotOptions = { useCustomFieldsEntries: false }) => {
19
+ models.forEach(async ({ name, scopeAttributes, modelOptions, hasTypeId, getRequiredCustomFields }) => {
20
+ try {
21
+ const model = getModel(name);
22
+ if (!model) {
23
+ logger_default.warn("sadot - tried to addHooks to a model that does not exist yet", {
24
+ name,
25
+ scopeAttributes
26
+ });
27
+ return;
28
+ }
29
+ model.rawAttributes.customFields = { type: DataTypes.VIRTUAL };
30
+ model.refreshAttributes();
31
+ const enrichOptions = {
32
+ ...sadotOptions,
33
+ hasTypeId: hasTypeId ?? false,
34
+ getRequiredCustomFields
35
+ };
36
+ model.addHook("beforeFind", "sadot-beforeFind", beforeFind(scopeAttributes));
37
+ model.addHook("beforeBulkCreate", "sadot-beforeBulkCreate", beforeBulkCreate);
38
+ model.addHook("beforeBulkUpdate", "sadot-beforeBulkUpdate", beforeBulkUpdate);
39
+ model.addHook("beforeCreate", "sadot-beforeCreate", beforeCreate(scopeAttributes, modelOptions, enrichOptions));
40
+ model.addHook("beforeUpdate", "sadot-beforeUpdate", beforeUpdate(scopeAttributes, modelOptions, enrichOptions));
41
+ model.addHook("afterFind", "sadot-afterFind", enrich_default(name, scopeAttributes, "afterFind", modelOptions, enrichOptions));
42
+ model.addHook("afterUpdate", "sadot-afterUpdate", enrich_default(name, scopeAttributes, void 0, modelOptions, enrichOptions));
43
+ model.addHook("afterCreate", "sadot-afterCreate", enrich_default(name, scopeAttributes, void 0, modelOptions, enrichOptions));
44
+ } catch (e) {
45
+ logger_default.error(`Could not add custom fields hook to model ${name}. `, e);
46
+ }
47
+ });
48
+ };
49
+ const removeHooks = (models, getModel) => {
50
+ models.forEach(async ({ name }) => {
51
+ try {
52
+ const model = getModel(name);
53
+ if (!model) return;
54
+ if (model.rawAttributes.customFields) {
55
+ delete model.rawAttributes.customFields;
56
+ model.refreshAttributes();
57
+ }
58
+ model.removeHook("beforeFind", "sadot-beforeFind");
59
+ model.removeHook("beforeBulkCreate", "sadot-beforeBulkCreate");
60
+ model.removeHook("beforeBulkUpdate", "sadot-beforeBulkUpdate");
61
+ model.removeHook("beforeCreate", "sadot-beforeCreate");
62
+ model.removeHook("beforeUpdate", "sadot-beforeUpdate");
63
+ model.removeHook("afterFind", "sadot-afterFind");
64
+ model.removeHook("afterUpdate", "sadot-afterUpdate");
65
+ } catch (e) {
66
+ logger_default.error(`Could not add custom fields hook to model ${name}. `, e);
67
+ }
68
+ });
69
+ };
70
+ /**
71
+ * Necessary associations for the {@link customFieldsFilterScope} scope
72
+ */
73
+ const addAssociations = (model, modelName, options) => {
74
+ if (options?.useCustomFieldsEntries) return;
75
+ model.hasMany(CustomFieldValue_default, {
76
+ foreignKey: "modelId",
77
+ as: "customFieldValue"
78
+ });
79
+ CustomFieldValue_default.belongsTo(model, {
80
+ foreignKey: "modelId",
81
+ as: modelName
82
+ });
83
+ };
84
+ const addScopes = (models, getModel, options = { useCustomFieldsEntries: false }) => {
85
+ models.forEach(async ({ name, scopeAttributes }) => {
86
+ try {
87
+ const model = getModel(name);
88
+ if (!model) {
89
+ logger_default.warn("sadot - tried to addScopes to a model that does not exist yet", {
90
+ name,
91
+ scopeAttributes
92
+ });
93
+ return;
94
+ }
95
+ addAssociations(model, name, options);
96
+ model.addScope(CUSTOM_FIELDS_FILTER_SCOPE, customFieldsFilterScope(name, options));
97
+ model.addScope(CUSTOM_FIELDS_SORT_SCOPE, customFieldsSortScope(name, options));
98
+ } catch (e) {
99
+ logger_default.error(`Could not add custom fields scopes to model ${name}. `, e);
100
+ }
101
+ });
102
+ };
103
+ const applyCustomAssociation = (models) => {
104
+ models.forEach(({ modelOptions }) => {
105
+ modelOptions?.customAssociation?.(CustomFieldDefinition_default);
106
+ modelOptions?.customAssociation?.(CustomValidator_default);
107
+ });
108
+ };
109
+
110
+ //#endregion
111
+ export { addHooks, addScopes, applyCustomAssociation, removeHooks };
@@ -0,0 +1,15 @@
1
+ const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
2
+ let _autofleet_zehut = require("@autofleet/zehut");
3
+ let _autofleet_logger = require("@autofleet/logger");
4
+ _autofleet_logger = require_rolldown_runtime.__toESM(_autofleet_logger);
5
+
6
+ //#region src/utils/logger/index.ts
7
+ const logger = (0, _autofleet_logger.default)();
8
+ function tryAddingTraceIdMiddleware() {
9
+ logger.addContextMiddleware(() => ({ traceId: _autofleet_zehut.outbreak.getCurrentContextTraceId() }));
10
+ }
11
+ var logger_default = logger;
12
+
13
+ //#endregion
14
+ exports.default = logger_default;
15
+ exports.tryAddingTraceIdMiddleware = tryAddingTraceIdMiddleware;
@@ -0,0 +1,12 @@
1
+ import { outbreak } from "@autofleet/zehut";
2
+ import Logger from "@autofleet/logger";
3
+
4
+ //#region src/utils/logger/index.ts
5
+ const logger = Logger();
6
+ function tryAddingTraceIdMiddleware() {
7
+ logger.addContextMiddleware(() => ({ traceId: outbreak.getCurrentContextTraceId() }));
8
+ }
9
+ var logger_default = logger;
10
+
11
+ //#endregion
12
+ export { logger_default as default, tryAddingTraceIdMiddleware };
@@ -0,0 +1,12 @@
1
+
2
+ //#region src/utils/scopeAttributes.ts
3
+ const mapAttributeToInstance = (scopeAttributes, instance) => scopeAttributes.map((attr) => instance[attr]);
4
+ const applyScopeToInstance = (instance, scopeAttributes) => {
5
+ const uniqueAttributes = Array.from(new Set(scopeAttributes));
6
+ if (Array.isArray(instance)) return instance.flatMap((ins) => mapAttributeToInstance(uniqueAttributes, ins));
7
+ return mapAttributeToInstance(uniqueAttributes, instance);
8
+ };
9
+ var scopeAttributes_default = applyScopeToInstance;
10
+
11
+ //#endregion
12
+ exports.default = scopeAttributes_default;
@@ -0,0 +1,11 @@
1
+ //#region src/utils/scopeAttributes.ts
2
+ const mapAttributeToInstance = (scopeAttributes, instance) => scopeAttributes.map((attr) => instance[attr]);
3
+ const applyScopeToInstance = (instance, scopeAttributes) => {
4
+ const uniqueAttributes = Array.from(new Set(scopeAttributes));
5
+ if (Array.isArray(instance)) return instance.flatMap((ins) => mapAttributeToInstance(uniqueAttributes, ins));
6
+ return mapAttributeToInstance(uniqueAttributes, instance);
7
+ };
8
+ var scopeAttributes_default = applyScopeToInstance;
9
+
10
+ //#endregion
11
+ export { scopeAttributes_default as default };
@@ -0,0 +1,34 @@
1
+ const require_index = require('./validators/index.cjs');
2
+ const require_index$1 = require('../../errors/index.cjs');
3
+
4
+ //#region src/utils/validations/index.ts
5
+ const validateFieldType = (type) => Object.keys(require_index.validators).includes(type);
6
+ const validateValue = (value, valueType, validation) => {
7
+ const validator = require_index.validators[valueType];
8
+ return validator(value, validation);
9
+ /** TODO: Add validation for required fields
10
+ * @example
11
+ * if (validations.required && !value) {
12
+ * return false;
13
+ * }
14
+ */
15
+ };
16
+ const validateInstanceCustomFieldEntries = (instance, definitionsByName, _validateValue = validateValue) => {
17
+ const validationErrors = Object.entries(instance.customFields).map(([customFieldName, value]) => {
18
+ if (value === null) return null;
19
+ const { validation, fieldType } = definitionsByName[customFieldName];
20
+ const result = _validateValue(value, fieldType, validation);
21
+ if (result?.error) return {
22
+ joiValidationError: result.error,
23
+ fieldDefinitionName: customFieldName,
24
+ value
25
+ };
26
+ return null;
27
+ }).filter((result) => !!result);
28
+ if (validationErrors?.length) throw new require_index$1.InvalidEntriesError(instance.modelId, validationErrors);
29
+ };
30
+
31
+ //#endregion
32
+ exports.validateFieldType = validateFieldType;
33
+ exports.validateInstanceCustomFieldEntries = validateInstanceCustomFieldEntries;
34
+ exports.validateValue = validateValue;
@@ -0,0 +1,32 @@
1
+ import { validators } from "./validators/index.js";
2
+ import { InvalidEntriesError } from "../../errors/index.js";
3
+
4
+ //#region src/utils/validations/index.ts
5
+ const validateFieldType = (type) => Object.keys(validators).includes(type);
6
+ const validateValue = (value, valueType, validation) => {
7
+ const validator = validators[valueType];
8
+ return validator(value, validation);
9
+ /** TODO: Add validation for required fields
10
+ * @example
11
+ * if (validations.required && !value) {
12
+ * return false;
13
+ * }
14
+ */
15
+ };
16
+ const validateInstanceCustomFieldEntries = (instance, definitionsByName, _validateValue = validateValue) => {
17
+ const validationErrors = Object.entries(instance.customFields).map(([customFieldName, value]) => {
18
+ if (value === null) return null;
19
+ const { validation, fieldType } = definitionsByName[customFieldName];
20
+ const result = _validateValue(value, fieldType, validation);
21
+ if (result?.error) return {
22
+ joiValidationError: result.error,
23
+ fieldDefinitionName: customFieldName,
24
+ value
25
+ };
26
+ return null;
27
+ }).filter((result) => !!result);
28
+ if (validationErrors?.length) throw new InvalidEntriesError(instance.modelId, validationErrors);
29
+ };
30
+
31
+ //#endregion
32
+ export { validateFieldType, validateInstanceCustomFieldEntries, validateValue };
@@ -0,0 +1,9 @@
1
+ const require_rolldown_runtime = require('../../../_virtual/rolldown_runtime.cjs');
2
+ let joi = require("joi");
3
+ joi = require_rolldown_runtime.__toESM(joi);
4
+
5
+ //#region src/utils/validations/schema/custom-fields.ts
6
+ const CustomFieldsSchema = joi.default.object().pattern(joi.default.string(), joi.default.any());
7
+
8
+ //#endregion
9
+ exports.CustomFieldsSchema = CustomFieldsSchema;
@@ -0,0 +1,6 @@
1
+ import Joi from "joi";
2
+
3
+ //#region src/utils/validations/schema/custom-fields.d.ts
4
+ declare const CustomFieldsSchema: Joi.ObjectSchema<Record<string, any>>;
5
+ //#endregion
6
+ export { CustomFieldsSchema };
@@ -0,0 +1,6 @@
1
+ import Joi from "joi";
2
+
3
+ //#region src/utils/validations/schema/custom-fields.d.ts
4
+ declare const CustomFieldsSchema: Joi.ObjectSchema<Record<string, any>>;
5
+ //#endregion
6
+ export { CustomFieldsSchema };
@@ -0,0 +1,7 @@
1
+ import Joi from "joi";
2
+
3
+ //#region src/utils/validations/schema/custom-fields.ts
4
+ const CustomFieldsSchema = Joi.object().pattern(Joi.string(), Joi.any());
5
+
6
+ //#endregion
7
+ export { CustomFieldsSchema };