@autofleet/sadot 1.6.18-beta.7 → 1.6.18
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.
- package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/decorate.cjs +1 -11
- package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/decorate.js +1 -10
- package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/decorateMetadata.cjs +1 -8
- package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/decorateMetadata.js +1 -7
- package/dist/_virtual/rolldown_runtime.cjs +1 -43
- package/dist/_virtual/rolldown_runtime.js +1 -21
- package/dist/api/index.cjs +2 -12
- package/dist/api/index.cjs.map +1 -0
- package/dist/api/index.js +2 -11
- package/dist/api/index.js.map +1 -0
- package/dist/api/v1/definition/index.cjs +2 -113
- package/dist/api/v1/definition/index.cjs.map +1 -0
- package/dist/api/v1/definition/index.js +2 -112
- package/dist/api/v1/definition/index.js.map +1 -0
- package/dist/api/v1/definition/validations.cjs +2 -128
- package/dist/api/v1/definition/validations.cjs.map +1 -0
- package/dist/api/v1/definition/validations.js +2 -125
- package/dist/api/v1/definition/validations.js.map +1 -0
- package/dist/api/v1/errors.cjs +2 -14
- package/dist/api/v1/errors.cjs.map +1 -0
- package/dist/api/v1/errors.js +2 -13
- package/dist/api/v1/errors.js.map +1 -0
- package/dist/api/v1/index.cjs +2 -16
- package/dist/api/v1/index.cjs.map +1 -0
- package/dist/api/v1/index.js +2 -15
- package/dist/api/v1/index.js.map +1 -0
- package/dist/api/v1/validator/index.cjs +2 -115
- package/dist/api/v1/validator/index.cjs.map +1 -0
- package/dist/api/v1/validator/index.js +2 -114
- package/dist/api/v1/validator/index.js.map +1 -0
- package/dist/api/v1/validator/validations.cjs +2 -40
- package/dist/api/v1/validator/validations.cjs.map +1 -0
- package/dist/api/v1/validator/validations.d.cts +2 -1
- package/dist/api/v1/validator/validations.d.ts +2 -1
- package/dist/api/v1/validator/validations.js +2 -38
- package/dist/api/v1/validator/validations.js.map +1 -0
- package/dist/errors/index.cjs +3 -62
- package/dist/errors/index.cjs.map +1 -0
- package/dist/errors/index.js +3 -55
- package/dist/errors/index.js.map +1 -0
- package/dist/events/index.cjs +2 -52
- package/dist/events/index.cjs.map +1 -0
- package/dist/events/index.js +2 -50
- package/dist/events/index.js.map +1 -0
- package/dist/hooks/enrich.cjs +2 -175
- package/dist/hooks/enrich.cjs.map +1 -0
- package/dist/hooks/enrich.js +2 -175
- package/dist/hooks/enrich.js.map +1 -0
- package/dist/hooks/find.cjs +2 -22
- package/dist/hooks/find.cjs.map +1 -0
- package/dist/hooks/find.js +2 -22
- package/dist/hooks/find.js.map +1 -0
- package/dist/hooks/hooks.cjs +2 -310
- package/dist/hooks/hooks.cjs.map +1 -0
- package/dist/hooks/hooks.js +2 -302
- package/dist/hooks/hooks.js.map +1 -0
- package/dist/hooks/index.cjs +1 -3
- package/dist/hooks/index.js +1 -5
- package/dist/hooks/utils/updateInstanceValues.cjs +2 -27
- package/dist/hooks/utils/updateInstanceValues.cjs.map +1 -0
- package/dist/hooks/utils/updateInstanceValues.js +2 -27
- package/dist/hooks/utils/updateInstanceValues.js.map +1 -0
- package/dist/index.cjs +2 -83
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +2 -3
- package/dist/index.js +2 -62
- package/dist/index.js.map +1 -0
- package/dist/init-state.cjs +2 -56
- package/dist/init-state.cjs.map +1 -0
- package/dist/init-state.d.cts +2 -1
- package/dist/init-state.d.ts +2 -1
- package/dist/init-state.js +2 -55
- package/dist/init-state.js.map +1 -0
- package/dist/mat-path-state.cjs +2 -10
- package/dist/mat-path-state.cjs.map +1 -0
- package/dist/mat-path-state.js +2 -9
- package/dist/mat-path-state.js.map +1 -0
- package/dist/migrations/001-create-core-tables.cjs +7 -25
- package/dist/migrations/001-create-core-tables.cjs.map +1 -0
- package/dist/migrations/001-create-core-tables.js +7 -23
- package/dist/migrations/001-create-core-tables.js.map +1 -0
- package/dist/migrations/002-create-custom-field-entries.cjs +4 -16
- package/dist/migrations/002-create-custom-field-entries.cjs.map +1 -0
- package/dist/migrations/002-create-custom-field-entries.js +4 -14
- package/dist/migrations/002-create-custom-field-entries.js.map +1 -0
- package/dist/migrations/003-create-custom-field-model-type-map.cjs +6 -20
- package/dist/migrations/003-create-custom-field-model-type-map.cjs.map +1 -0
- package/dist/migrations/003-create-custom-field-model-type-map.js +6 -18
- package/dist/migrations/003-create-custom-field-model-type-map.js.map +1 -0
- package/dist/migrations/index.cjs +2 -88
- package/dist/migrations/index.cjs.map +1 -0
- package/dist/migrations/index.js +2 -89
- package/dist/migrations/index.js.map +1 -0
- package/dist/models/CustomFieldDefinition.cjs +2 -147
- package/dist/models/CustomFieldDefinition.cjs.map +1 -0
- package/dist/models/CustomFieldDefinition.d.cts +2 -1
- package/dist/models/CustomFieldDefinition.d.ts +2 -1
- package/dist/models/CustomFieldDefinition.js +2 -146
- package/dist/models/CustomFieldDefinition.js.map +1 -0
- package/dist/models/CustomFieldEntries.cjs +2 -71
- package/dist/models/CustomFieldEntries.cjs.map +1 -0
- package/dist/models/CustomFieldEntries.d.cts +2 -1
- package/dist/models/CustomFieldEntries.d.ts +2 -1
- package/dist/models/CustomFieldEntries.js +2 -70
- package/dist/models/CustomFieldEntries.js.map +1 -0
- package/dist/models/CustomFieldModelTypeMap.cjs +2 -62
- package/dist/models/CustomFieldModelTypeMap.cjs.map +1 -0
- package/dist/models/CustomFieldModelTypeMap.d.cts +2 -1
- package/dist/models/CustomFieldModelTypeMap.d.ts +2 -1
- package/dist/models/CustomFieldModelTypeMap.js +2 -61
- package/dist/models/CustomFieldModelTypeMap.js.map +1 -0
- package/dist/models/CustomFieldValue.cjs +2 -109
- package/dist/models/CustomFieldValue.cjs.map +1 -0
- package/dist/models/CustomFieldValue.d.cts +2 -1
- package/dist/models/CustomFieldValue.d.ts +2 -1
- package/dist/models/CustomFieldValue.js +2 -108
- package/dist/models/CustomFieldValue.js.map +1 -0
- package/dist/models/CustomValidator.cjs +2 -68
- package/dist/models/CustomValidator.cjs.map +1 -0
- package/dist/models/CustomValidator.d.cts +2 -1
- package/dist/models/CustomValidator.d.ts +2 -1
- package/dist/models/CustomValidator.js +2 -67
- package/dist/models/CustomValidator.js.map +1 -0
- package/dist/models/index.cjs +2 -163
- package/dist/models/index.cjs.map +1 -0
- package/dist/models/index.d.cts +7 -0
- package/dist/models/index.d.ts +0 -4
- package/dist/models/index.js +2 -161
- package/dist/models/index.js.map +1 -0
- package/dist/models/tests/AssociatedTestModel.cjs +2 -51
- package/dist/models/tests/AssociatedTestModel.cjs.map +1 -0
- package/dist/models/tests/AssociatedTestModel.js +2 -50
- package/dist/models/tests/AssociatedTestModel.js.map +1 -0
- package/dist/models/tests/TestModel.cjs +2 -43
- package/dist/models/tests/TestModel.cjs.map +1 -0
- package/dist/models/tests/TestModel.js +2 -42
- package/dist/models/tests/TestModel.js.map +1 -0
- package/dist/models/tests/contextAwareModels/ContextAwareTestModel.cjs +2 -35
- package/dist/models/tests/contextAwareModels/ContextAwareTestModel.cjs.map +1 -0
- package/dist/models/tests/contextAwareModels/ContextAwareTestModel.js +2 -34
- package/dist/models/tests/contextAwareModels/ContextAwareTestModel.js.map +1 -0
- package/dist/models/tests/contextAwareModels/ContextTestModel.cjs +2 -33
- package/dist/models/tests/contextAwareModels/ContextTestModel.cjs.map +1 -0
- package/dist/models/tests/contextAwareModels/ContextTestModel.js +2 -32
- package/dist/models/tests/contextAwareModels/ContextTestModel.js.map +1 -0
- package/dist/repository/definition.cjs +2 -221
- package/dist/repository/definition.cjs.map +1 -0
- package/dist/repository/definition.js +2 -212
- package/dist/repository/definition.js.map +1 -0
- package/dist/repository/entries.cjs +2 -69
- package/dist/repository/entries.cjs.map +1 -0
- package/dist/repository/entries.js +2 -67
- package/dist/repository/entries.js.map +1 -0
- package/dist/repository/utils/formatValues.cjs +2 -14
- package/dist/repository/utils/formatValues.cjs.map +1 -0
- package/dist/repository/utils/formatValues.js +2 -14
- package/dist/repository/utils/formatValues.js.map +1 -0
- package/dist/repository/validator.cjs +2 -58
- package/dist/repository/validator.cjs.map +1 -0
- package/dist/repository/validator.js +2 -54
- package/dist/repository/validator.js.map +1 -0
- package/dist/repository/value.cjs +2 -77
- package/dist/repository/value.cjs.map +1 -0
- package/dist/repository/value.js +2 -76
- package/dist/repository/value.js.map +1 -0
- package/dist/scopes/filter.cjs +2 -56
- package/dist/scopes/filter.cjs.map +1 -0
- package/dist/scopes/filter.d.cts +2 -1
- package/dist/scopes/filter.d.ts +2 -1
- package/dist/scopes/filter.js +2 -54
- package/dist/scopes/filter.js.map +1 -0
- package/dist/scopes/helpers/filter.helpers.cjs +25 -131
- package/dist/scopes/helpers/filter.helpers.cjs.map +1 -0
- package/dist/scopes/helpers/filter.helpers.d.cts +2 -1
- package/dist/scopes/helpers/filter.helpers.d.ts +2 -1
- package/dist/scopes/helpers/filter.helpers.js +25 -126
- package/dist/scopes/helpers/filter.helpers.js.map +1 -0
- package/dist/scopes/index.cjs +1 -1
- package/dist/scopes/index.js +1 -3
- package/dist/types/index.d.cts +4 -2
- package/dist/types/index.d.ts +4 -2
- package/dist/utils/constants/index.cjs +2 -32
- package/dist/utils/constants/index.cjs.map +1 -0
- package/dist/utils/constants/index.d.cts +2 -1
- package/dist/utils/constants/index.d.ts +2 -1
- package/dist/utils/constants/index.js +2 -29
- package/dist/utils/constants/index.js.map +1 -0
- package/dist/utils/db/index.cjs +2 -15
- package/dist/utils/db/index.cjs.map +1 -0
- package/dist/utils/db/index.js +2 -14
- package/dist/utils/db/index.js.map +1 -0
- package/dist/utils/helpers/index.cjs +2 -23
- package/dist/utils/helpers/index.cjs.map +1 -0
- package/dist/utils/helpers/index.d.cts +2 -1
- package/dist/utils/helpers/index.d.ts +2 -1
- package/dist/utils/helpers/index.js +2 -21
- package/dist/utils/helpers/index.js.map +1 -0
- package/dist/utils/init.cjs +2 -115
- package/dist/utils/init.cjs.map +1 -0
- package/dist/utils/init.js +2 -111
- package/dist/utils/init.js.map +1 -0
- package/dist/utils/logger/index.cjs +2 -15
- package/dist/utils/logger/index.cjs.map +1 -0
- package/dist/utils/logger/index.js +2 -12
- package/dist/utils/logger/index.js.map +1 -0
- package/dist/utils/scopeAttributes.cjs +2 -12
- package/dist/utils/scopeAttributes.cjs.map +1 -0
- package/dist/utils/scopeAttributes.js +2 -11
- package/dist/utils/scopeAttributes.js.map +1 -0
- package/dist/utils/validations/index.cjs +2 -34
- package/dist/utils/validations/index.cjs.map +1 -0
- package/dist/utils/validations/index.js +2 -32
- package/dist/utils/validations/index.js.map +1 -0
- package/dist/utils/validations/schema/custom-fields.cjs +2 -9
- package/dist/utils/validations/schema/custom-fields.cjs.map +1 -0
- package/dist/utils/validations/schema/custom-fields.d.cts +2 -1
- package/dist/utils/validations/schema/custom-fields.d.ts +2 -1
- package/dist/utils/validations/schema/custom-fields.js +2 -7
- package/dist/utils/validations/schema/custom-fields.js.map +1 -0
- package/dist/utils/validations/schema/validator-schema.cjs +2 -102
- package/dist/utils/validations/schema/validator-schema.cjs.map +1 -0
- package/dist/utils/validations/schema/validator-schema.js +2 -99
- package/dist/utils/validations/schema/validator-schema.js.map +1 -0
- package/dist/utils/validations/validators/index.cjs +2 -45
- package/dist/utils/validations/validators/index.cjs.map +1 -0
- package/dist/utils/validations/validators/index.js +2 -42
- package/dist/utils/validations/validators/index.js.map +1 -0
- package/dist/utils/validations/validators/multi-select-dropdown.validator.cjs +2 -7
- package/dist/utils/validations/validators/multi-select-dropdown.validator.cjs.map +1 -0
- package/dist/utils/validations/validators/multi-select-dropdown.validator.js +2 -7
- package/dist/utils/validations/validators/multi-select-dropdown.validator.js.map +1 -0
- package/dist/utils/validations/validators/multi-select-status.validator.cjs +2 -10
- package/dist/utils/validations/validators/multi-select-status.validator.cjs.map +1 -0
- package/dist/utils/validations/validators/multi-select-status.validator.js +2 -10
- package/dist/utils/validations/validators/multi-select-status.validator.js.map +1 -0
- package/dist/utils/validations/validators/multi-select.helpers.cjs +2 -12
- package/dist/utils/validations/validators/multi-select.helpers.cjs.map +1 -0
- package/dist/utils/validations/validators/multi-select.helpers.js +2 -10
- package/dist/utils/validations/validators/multi-select.helpers.js.map +1 -0
- package/dist/utils/validations/validators/select.validator.cjs +2 -12
- package/dist/utils/validations/validators/select.validator.cjs.map +1 -0
- package/dist/utils/validations/validators/select.validator.js +2 -10
- package/dist/utils/validations/validators/select.validator.js.map +1 -0
- package/dist/utils/validations/validators/status.validator.cjs +2 -12
- package/dist/utils/validations/validators/status.validator.cjs.map +1 -0
- package/dist/utils/validations/validators/status.validator.js +2 -10
- package/dist/utils/validations/validators/status.validator.js.map +1 -0
- package/package.json +3 -3
- package/dist/api/v1/field-policies/index.cjs +0 -84
- package/dist/api/v1/field-policies/index.js +0 -83
- package/dist/migrations/004-create-field-policy-tables.cjs +0 -29
- package/dist/migrations/004-create-field-policy-tables.js +0 -27
- package/dist/models/FieldPolicy.cjs +0 -50
- package/dist/models/FieldPolicy.d.cts +0 -23
- package/dist/models/FieldPolicy.d.ts +0 -23
- package/dist/models/FieldPolicy.js +0 -49
- package/dist/models/tests/AssociatedTestModel.d.ts +0 -2
- package/dist/models/tests/TestModel.d.ts +0 -2
- package/dist/models/tests/contextAwareModels/ContextAwareTestModel.d.ts +0 -2
- package/dist/models/tests/contextAwareModels/ContextTestModel.d.ts +0 -1
- package/dist/repository/field-policy.cjs +0 -46
- package/dist/repository/field-policy.d.cts +0 -31
- package/dist/repository/field-policy.d.ts +0 -31
- package/dist/repository/field-policy.js +0 -37
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validations.js","names":["validationSchemas: ValidationSchemas"],"sources":["../../../../src/api/v1/validator/validations.ts"],"sourcesContent":["import Joi from 'joi';\n\nconst jsonSchemaValidation = Joi.object().unknown(true);\n\nexport interface SchemaObject {\n type: 'object';\n properties?: {\n before?: object;\n after?: object;\n };\n required?: string[];\n allOf?: object[];\n anyOf?: object[];\n oneOf?: object[];\n additionalProperties?: boolean | object;\n $id?: string;\n $schema?: string;\n if?: object;\n then?: object;\n else?: object;\n}\n\nconst schemaObject = Joi.object<SchemaObject>({\n type: Joi.string().valid('object'),\n properties: Joi.object({\n before: jsonSchemaValidation,\n after: jsonSchemaValidation,\n }).required(),\n required: Joi.array().items(Joi.string()),\n allOf: Joi.array().items(Joi.object()),\n anyOf: Joi.array().items(Joi.object()),\n oneOf: Joi.array().items(Joi.object()),\n additionalProperties: Joi.alternatives().try(Joi.boolean(), Joi.object()),\n $id: Joi.string(),\n $schema: Joi.string(),\n if: Joi.object(),\n then: Joi.object(),\n else: Joi.object(),\n});\n\nexport interface CreateValidatorPayload {\n entityId: string;\n entityType: string;\n schema: SchemaObject;\n}\n\nexport interface UpdateValidatorPayload extends Partial<CreateValidatorPayload> {\n disabled?: boolean;\n}\n\ninterface ValidationSchemas {\n create: Joi.ObjectSchema<CreateValidatorPayload>;\n update: Joi.ObjectSchema<UpdateValidatorPayload>;\n}\n\nconst validationSchemas: ValidationSchemas = {\n create: Joi.object<CreateValidatorPayload>({\n entityId: Joi.string().uuid().required(),\n entityType: Joi.string().required(),\n schema: schemaObject.required(),\n }),\n\n update: Joi.object<UpdateValidatorPayload>({\n entityId: Joi.string().uuid(),\n entityType: Joi.string(),\n schema: schemaObject,\n disabled: Joi.boolean(),\n }).min(1),\n};\n\nexport default validationSchemas;\n"],"mappings":"mBAEA,MAAM,EAAuB,EAAI,QAAQ,CAAC,QAAQ,GAAK,CAoBjD,EAAe,EAAI,OAAqB,CAC5C,KAAM,EAAI,QAAQ,CAAC,MAAM,SAAS,CAClC,WAAY,EAAI,OAAO,CACrB,OAAQ,EACR,MAAO,EACR,CAAC,CAAC,UAAU,CACb,SAAU,EAAI,OAAO,CAAC,MAAM,EAAI,QAAQ,CAAC,CACzC,MAAO,EAAI,OAAO,CAAC,MAAM,EAAI,QAAQ,CAAC,CACtC,MAAO,EAAI,OAAO,CAAC,MAAM,EAAI,QAAQ,CAAC,CACtC,MAAO,EAAI,OAAO,CAAC,MAAM,EAAI,QAAQ,CAAC,CACtC,qBAAsB,EAAI,cAAc,CAAC,IAAI,EAAI,SAAS,CAAE,EAAI,QAAQ,CAAC,CACzE,IAAK,EAAI,QAAQ,CACjB,QAAS,EAAI,QAAQ,CACrB,GAAI,EAAI,QAAQ,CAChB,KAAM,EAAI,QAAQ,CAClB,KAAM,EAAI,QAAQ,CACnB,CAAC,CAgCF,IAAA,EAf6C,CAC3C,OAAQ,EAAI,OAA+B,CACzC,SAAU,EAAI,QAAQ,CAAC,MAAM,CAAC,UAAU,CACxC,WAAY,EAAI,QAAQ,CAAC,UAAU,CACnC,OAAQ,EAAa,UAAU,CAChC,CAAC,CAEF,OAAQ,EAAI,OAA+B,CACzC,SAAU,EAAI,QAAQ,CAAC,MAAM,CAC7B,WAAY,EAAI,QAAQ,CACxB,OAAQ,EACR,SAAU,EAAI,SAAS,CACxB,CAAC,CAAC,IAAI,EAAE,CACV"}
|
package/dist/errors/index.cjs
CHANGED
|
@@ -1,62 +1,3 @@
|
|
|
1
|
-
const
|
|
2
|
-
let
|
|
3
|
-
|
|
4
|
-
//#region src/errors/index.ts
|
|
5
|
-
var MissingRequiredCustomFieldError = class extends _autofleet_errors.BadRequest {
|
|
6
|
-
constructor(missingFields) {
|
|
7
|
-
const err = /* @__PURE__ */ new Error(`The following custom fields are required: ${missingFields.join(",")}`);
|
|
8
|
-
super([err], void 0, missingFields);
|
|
9
|
-
this.message = "MISSING_REQUIRED_CUSTOM_FIELDS";
|
|
10
|
-
}
|
|
11
|
-
};
|
|
12
|
-
var UnsupportedCustomFieldTypeError = class extends _autofleet_errors.BadRequest {
|
|
13
|
-
constructor(fieldType) {
|
|
14
|
-
const err = /* @__PURE__ */ new Error(`Type "${fieldType}" is not supported`);
|
|
15
|
-
super([err], void 0, null);
|
|
16
|
-
this.message = "UNSUPPORTED_CUSTOM_FIELD_TYPE";
|
|
17
|
-
}
|
|
18
|
-
};
|
|
19
|
-
var UnsupportedCustomValidationError = class extends _autofleet_errors.BadRequest {
|
|
20
|
-
constructor(fieldType) {
|
|
21
|
-
const err = /* @__PURE__ */ new Error(`Validation for "${fieldType}" is not supported`);
|
|
22
|
-
super([err], void 0, null);
|
|
23
|
-
this.message = "UNSUPPORTED_CUSTOM_VALIDATION_TYPE";
|
|
24
|
-
}
|
|
25
|
-
};
|
|
26
|
-
var InvalidFieldTypeError = class extends _autofleet_errors.BadRequest {
|
|
27
|
-
constructor(fieldType) {
|
|
28
|
-
const err = /* @__PURE__ */ new Error(`Invalid field type ${fieldType}`);
|
|
29
|
-
super([err], void 0, null);
|
|
30
|
-
this.message = "INVALID_FIELD_TYPE";
|
|
31
|
-
}
|
|
32
|
-
};
|
|
33
|
-
var InvalidValueError = class extends _autofleet_errors.BadRequest {
|
|
34
|
-
constructor(value, fieldDefinitionName, joiValidationError) {
|
|
35
|
-
const invalidValueMessage = `Invalid Value on field '${fieldDefinitionName}'. ${joiValidationError.message.replace(/"/g, "").replace("value", `'${fieldDefinitionName}'`)}. received: '${typeof value === "object" ? JSON.stringify(value) : value}'`;
|
|
36
|
-
super([new Error(invalidValueMessage)], void 0, null);
|
|
37
|
-
this.message = invalidValueMessage;
|
|
38
|
-
}
|
|
39
|
-
};
|
|
40
|
-
var InvalidEntriesError = class extends _autofleet_errors.BadRequest {
|
|
41
|
-
constructor(modelId, validationErrors) {
|
|
42
|
-
const errors = validationErrors.map((validationError) => new InvalidValueError(validationError.value, validationError.fieldDefinitionName, validationError.joiValidationError));
|
|
43
|
-
super(errors, void 0, null);
|
|
44
|
-
this.message = `Invalid entries on ${modelId}\n${validationErrors.map((validationError) => `${validationError.fieldDefinitionName} - ${validationError.joiValidationError.message}`).join("\n")}`;
|
|
45
|
-
}
|
|
46
|
-
};
|
|
47
|
-
var MissingDefinitionError = class extends _autofleet_errors.BadRequest {
|
|
48
|
-
constructor(fieldNames) {
|
|
49
|
-
const err = /* @__PURE__ */ new Error(`Missing custom field definition for field ${fieldNames.join(",")}`);
|
|
50
|
-
super([err], void 0, null);
|
|
51
|
-
this.message = "MISSING_DEFINITION";
|
|
52
|
-
}
|
|
53
|
-
};
|
|
54
|
-
|
|
55
|
-
//#endregion
|
|
56
|
-
exports.InvalidEntriesError = InvalidEntriesError;
|
|
57
|
-
exports.InvalidFieldTypeError = InvalidFieldTypeError;
|
|
58
|
-
exports.InvalidValueError = InvalidValueError;
|
|
59
|
-
exports.MissingDefinitionError = MissingDefinitionError;
|
|
60
|
-
exports.MissingRequiredCustomFieldError = MissingRequiredCustomFieldError;
|
|
61
|
-
exports.UnsupportedCustomFieldTypeError = UnsupportedCustomFieldTypeError;
|
|
62
|
-
exports.UnsupportedCustomValidationError = UnsupportedCustomValidationError;
|
|
1
|
+
const e=require(`../_virtual/rolldown_runtime.cjs`);let t=require(`@autofleet/errors`);var n=class extends t.BadRequest{constructor(e){let t=Error(`The following custom fields are required: ${e.join(`,`)}`);super([t],void 0,e),this.message=`MISSING_REQUIRED_CUSTOM_FIELDS`}},r=class extends t.BadRequest{constructor(e){let t=Error(`Type "${e}" is not supported`);super([t],void 0,null),this.message=`UNSUPPORTED_CUSTOM_FIELD_TYPE`}},i=class extends t.BadRequest{constructor(e){let t=Error(`Validation for "${e}" is not supported`);super([t],void 0,null),this.message=`UNSUPPORTED_CUSTOM_VALIDATION_TYPE`}},a=class extends t.BadRequest{constructor(e){let t=Error(`Invalid field type ${e}`);super([t],void 0,null),this.message=`INVALID_FIELD_TYPE`}},o=class extends t.BadRequest{constructor(e,t,n){let r=`Invalid Value on field '${t}'. ${n.message.replace(/"/g,``).replace(`value`,`'${t}'`)}. received: '${typeof e==`object`?JSON.stringify(e):e}'`;super([Error(r)],void 0,null),this.message=r}},s=class extends t.BadRequest{constructor(e,t){let n=t.map(e=>new o(e.value,e.fieldDefinitionName,e.joiValidationError));super(n,void 0,null),this.message=`Invalid entries on ${e}\n${t.map(e=>`${e.fieldDefinitionName} - ${e.joiValidationError.message}`).join(`
|
|
2
|
+
`)}`}},c=class extends t.BadRequest{constructor(e){let t=Error(`Missing custom field definition for field ${e.join(`,`)}`);super([t],void 0,null),this.message=`MISSING_DEFINITION`}};exports.InvalidEntriesError=s,exports.InvalidFieldTypeError=a,exports.InvalidValueError=o,exports.MissingDefinitionError=c,exports.MissingRequiredCustomFieldError=n,exports.UnsupportedCustomFieldTypeError=r,exports.UnsupportedCustomValidationError=i;
|
|
3
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["BadRequest"],"sources":["../../src/errors/index.ts"],"sourcesContent":["import { BadRequest } from '@autofleet/errors';\nimport type { ValidationError } from 'joi';\nimport type { EntriesValidationError } from '../types/entries';\n\nexport class MissingRequiredCustomFieldError extends BadRequest {\n constructor(missingFields: string[]) {\n const err = new Error(`The following custom fields are required: ${missingFields.join(',')}`);\n super([err], undefined, missingFields);\n this.message = 'MISSING_REQUIRED_CUSTOM_FIELDS';\n }\n}\n\nexport class UnsupportedCustomFieldTypeError extends BadRequest {\n constructor(fieldType: string) {\n const err = new Error(`Type \"${fieldType}\" is not supported`);\n super([err], undefined, null);\n this.message = 'UNSUPPORTED_CUSTOM_FIELD_TYPE';\n }\n}\n\nexport class UnsupportedCustomValidationError extends BadRequest {\n constructor(fieldType: string) {\n const err = new Error(`Validation for \"${fieldType}\" is not supported`);\n super([err], undefined, null);\n this.message = 'UNSUPPORTED_CUSTOM_VALIDATION_TYPE';\n }\n}\n\nexport class InvalidFieldTypeError extends BadRequest {\n constructor(fieldType: string) {\n const err = new Error(`Invalid field type ${fieldType}`);\n super([err], undefined, null);\n this.message = 'INVALID_FIELD_TYPE';\n }\n}\n\nexport class InvalidValueError extends BadRequest {\n constructor(value: any, fieldDefinitionName: string, joiValidationError: ValidationError) {\n const formattedErrorMessage = joiValidationError.message\n .replace(/\"/g, '')\n .replace('value', `'${fieldDefinitionName}'`);\n\n const formattedValue = typeof value === 'object' ? JSON.stringify(value) : value;\n\n const invalidValueMessage = `Invalid Value on field '${fieldDefinitionName}'. ${formattedErrorMessage}. received: '${formattedValue}'`;\n\n const err = new Error(invalidValueMessage);\n super([err], undefined, null);\n this.message = invalidValueMessage;\n }\n}\n\nexport class InvalidEntriesError extends BadRequest {\n constructor(modelId: string, validationErrors: EntriesValidationError[]) {\n const errors = validationErrors.map(validationError => new InvalidValueError(validationError.value, validationError.fieldDefinitionName, validationError.joiValidationError));\n super(errors, undefined, null);\n this.message = `Invalid entries on ${modelId}\\n${validationErrors.map(validationError => (\n `${validationError.fieldDefinitionName} - ${validationError.joiValidationError.message}`\n )).join('\\n')}`;\n }\n}\n\nexport class MissingDefinitionError extends BadRequest {\n constructor(fieldNames: string[]) {\n const err = new Error(`Missing custom field definition for field ${fieldNames.join(',')}`);\n super([err], undefined, null);\n this.message = 'MISSING_DEFINITION';\n }\n}\n"],"mappings":"uFAIA,IAAa,EAAb,cAAqDA,EAAAA,UAAW,CAC9D,YAAY,EAAyB,CACnC,IAAM,EAAU,MAAM,6CAA6C,EAAc,KAAK,IAAI,GAAG,CAC7F,MAAM,CAAC,EAAI,CAAE,IAAA,GAAW,EAAc,CACtC,KAAK,QAAU,mCAIN,EAAb,cAAqDA,EAAAA,UAAW,CAC9D,YAAY,EAAmB,CAC7B,IAAM,EAAU,MAAM,SAAS,EAAU,oBAAoB,CAC7D,MAAM,CAAC,EAAI,CAAE,IAAA,GAAW,KAAK,CAC7B,KAAK,QAAU,kCAIN,EAAb,cAAsDA,EAAAA,UAAW,CAC/D,YAAY,EAAmB,CAC7B,IAAM,EAAU,MAAM,mBAAmB,EAAU,oBAAoB,CACvE,MAAM,CAAC,EAAI,CAAE,IAAA,GAAW,KAAK,CAC7B,KAAK,QAAU,uCAIN,EAAb,cAA2CA,EAAAA,UAAW,CACpD,YAAY,EAAmB,CAC7B,IAAM,EAAU,MAAM,sBAAsB,IAAY,CACxD,MAAM,CAAC,EAAI,CAAE,IAAA,GAAW,KAAK,CAC7B,KAAK,QAAU,uBAIN,EAAb,cAAuCA,EAAAA,UAAW,CAChD,YAAY,EAAY,EAA6B,EAAqC,CAOxF,IAAM,EAAsB,2BAA2B,EAAoB,KAN7C,EAAmB,QAC9C,QAAQ,KAAM,GAAG,CACjB,QAAQ,QAAS,IAAI,EAAoB,GAAG,CAIuD,eAF/E,OAAO,GAAU,SAAW,KAAK,UAAU,EAAM,CAAG,EAEyD,GAGpI,MAAM,CADU,MAAM,EAAoB,CAC/B,CAAE,IAAA,GAAW,KAAK,CAC7B,KAAK,QAAU,IAIN,EAAb,cAAyCA,EAAAA,UAAW,CAClD,YAAY,EAAiB,EAA4C,CACvE,IAAM,EAAS,EAAiB,IAAI,GAAmB,IAAI,EAAkB,EAAgB,MAAO,EAAgB,oBAAqB,EAAgB,mBAAmB,CAAC,CAC7K,MAAM,EAAQ,IAAA,GAAW,KAAK,CAC9B,KAAK,QAAU,sBAAsB,EAAQ,IAAI,EAAiB,IAAI,GACpE,GAAG,EAAgB,oBAAoB,KAAK,EAAgB,mBAAmB,UAC/E,CAAC,KAAK;EAAK,KAIJ,EAAb,cAA4CA,EAAAA,UAAW,CACrD,YAAY,EAAsB,CAChC,IAAM,EAAU,MAAM,6CAA6C,EAAW,KAAK,IAAI,GAAG,CAC1F,MAAM,CAAC,EAAI,CAAE,IAAA,GAAW,KAAK,CAC7B,KAAK,QAAU"}
|
package/dist/errors/index.js
CHANGED
|
@@ -1,55 +1,3 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
//#
|
|
4
|
-
var MissingRequiredCustomFieldError = class extends BadRequest {
|
|
5
|
-
constructor(missingFields) {
|
|
6
|
-
const err = /* @__PURE__ */ new Error(`The following custom fields are required: ${missingFields.join(",")}`);
|
|
7
|
-
super([err], void 0, missingFields);
|
|
8
|
-
this.message = "MISSING_REQUIRED_CUSTOM_FIELDS";
|
|
9
|
-
}
|
|
10
|
-
};
|
|
11
|
-
var UnsupportedCustomFieldTypeError = class extends BadRequest {
|
|
12
|
-
constructor(fieldType) {
|
|
13
|
-
const err = /* @__PURE__ */ new Error(`Type "${fieldType}" is not supported`);
|
|
14
|
-
super([err], void 0, null);
|
|
15
|
-
this.message = "UNSUPPORTED_CUSTOM_FIELD_TYPE";
|
|
16
|
-
}
|
|
17
|
-
};
|
|
18
|
-
var UnsupportedCustomValidationError = class extends BadRequest {
|
|
19
|
-
constructor(fieldType) {
|
|
20
|
-
const err = /* @__PURE__ */ new Error(`Validation for "${fieldType}" is not supported`);
|
|
21
|
-
super([err], void 0, null);
|
|
22
|
-
this.message = "UNSUPPORTED_CUSTOM_VALIDATION_TYPE";
|
|
23
|
-
}
|
|
24
|
-
};
|
|
25
|
-
var InvalidFieldTypeError = class extends BadRequest {
|
|
26
|
-
constructor(fieldType) {
|
|
27
|
-
const err = /* @__PURE__ */ new Error(`Invalid field type ${fieldType}`);
|
|
28
|
-
super([err], void 0, null);
|
|
29
|
-
this.message = "INVALID_FIELD_TYPE";
|
|
30
|
-
}
|
|
31
|
-
};
|
|
32
|
-
var InvalidValueError = class extends BadRequest {
|
|
33
|
-
constructor(value, fieldDefinitionName, joiValidationError) {
|
|
34
|
-
const invalidValueMessage = `Invalid Value on field '${fieldDefinitionName}'. ${joiValidationError.message.replace(/"/g, "").replace("value", `'${fieldDefinitionName}'`)}. received: '${typeof value === "object" ? JSON.stringify(value) : value}'`;
|
|
35
|
-
super([new Error(invalidValueMessage)], void 0, null);
|
|
36
|
-
this.message = invalidValueMessage;
|
|
37
|
-
}
|
|
38
|
-
};
|
|
39
|
-
var InvalidEntriesError = class extends BadRequest {
|
|
40
|
-
constructor(modelId, validationErrors) {
|
|
41
|
-
const errors = validationErrors.map((validationError) => new InvalidValueError(validationError.value, validationError.fieldDefinitionName, validationError.joiValidationError));
|
|
42
|
-
super(errors, void 0, null);
|
|
43
|
-
this.message = `Invalid entries on ${modelId}\n${validationErrors.map((validationError) => `${validationError.fieldDefinitionName} - ${validationError.joiValidationError.message}`).join("\n")}`;
|
|
44
|
-
}
|
|
45
|
-
};
|
|
46
|
-
var MissingDefinitionError = class extends BadRequest {
|
|
47
|
-
constructor(fieldNames) {
|
|
48
|
-
const err = /* @__PURE__ */ new Error(`Missing custom field definition for field ${fieldNames.join(",")}`);
|
|
49
|
-
super([err], void 0, null);
|
|
50
|
-
this.message = "MISSING_DEFINITION";
|
|
51
|
-
}
|
|
52
|
-
};
|
|
53
|
-
|
|
54
|
-
//#endregion
|
|
55
|
-
export { InvalidEntriesError, InvalidFieldTypeError, InvalidValueError, MissingDefinitionError, MissingRequiredCustomFieldError, UnsupportedCustomFieldTypeError, UnsupportedCustomValidationError };
|
|
1
|
+
import{BadRequest as e}from"@autofleet/errors";var t=class extends e{constructor(e){let t=Error(`The following custom fields are required: ${e.join(`,`)}`);super([t],void 0,e),this.message=`MISSING_REQUIRED_CUSTOM_FIELDS`}},n=class extends e{constructor(e){let t=Error(`Type "${e}" is not supported`);super([t],void 0,null),this.message=`UNSUPPORTED_CUSTOM_FIELD_TYPE`}},r=class extends e{constructor(e){let t=Error(`Validation for "${e}" is not supported`);super([t],void 0,null),this.message=`UNSUPPORTED_CUSTOM_VALIDATION_TYPE`}},i=class extends e{constructor(e){let t=Error(`Invalid field type ${e}`);super([t],void 0,null),this.message=`INVALID_FIELD_TYPE`}},a=class extends e{constructor(e,t,n){let r=`Invalid Value on field '${t}'. ${n.message.replace(/"/g,``).replace(`value`,`'${t}'`)}. received: '${typeof e==`object`?JSON.stringify(e):e}'`;super([Error(r)],void 0,null),this.message=r}},o=class extends e{constructor(e,t){let n=t.map(e=>new a(e.value,e.fieldDefinitionName,e.joiValidationError));super(n,void 0,null),this.message=`Invalid entries on ${e}\n${t.map(e=>`${e.fieldDefinitionName} - ${e.joiValidationError.message}`).join(`
|
|
2
|
+
`)}`}},s=class extends e{constructor(e){let t=Error(`Missing custom field definition for field ${e.join(`,`)}`);super([t],void 0,null),this.message=`MISSING_DEFINITION`}};export{o as InvalidEntriesError,i as InvalidFieldTypeError,a as InvalidValueError,s as MissingDefinitionError,t as MissingRequiredCustomFieldError,n as UnsupportedCustomFieldTypeError,r as UnsupportedCustomValidationError};
|
|
3
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/errors/index.ts"],"sourcesContent":["import { BadRequest } from '@autofleet/errors';\nimport type { ValidationError } from 'joi';\nimport type { EntriesValidationError } from '../types/entries';\n\nexport class MissingRequiredCustomFieldError extends BadRequest {\n constructor(missingFields: string[]) {\n const err = new Error(`The following custom fields are required: ${missingFields.join(',')}`);\n super([err], undefined, missingFields);\n this.message = 'MISSING_REQUIRED_CUSTOM_FIELDS';\n }\n}\n\nexport class UnsupportedCustomFieldTypeError extends BadRequest {\n constructor(fieldType: string) {\n const err = new Error(`Type \"${fieldType}\" is not supported`);\n super([err], undefined, null);\n this.message = 'UNSUPPORTED_CUSTOM_FIELD_TYPE';\n }\n}\n\nexport class UnsupportedCustomValidationError extends BadRequest {\n constructor(fieldType: string) {\n const err = new Error(`Validation for \"${fieldType}\" is not supported`);\n super([err], undefined, null);\n this.message = 'UNSUPPORTED_CUSTOM_VALIDATION_TYPE';\n }\n}\n\nexport class InvalidFieldTypeError extends BadRequest {\n constructor(fieldType: string) {\n const err = new Error(`Invalid field type ${fieldType}`);\n super([err], undefined, null);\n this.message = 'INVALID_FIELD_TYPE';\n }\n}\n\nexport class InvalidValueError extends BadRequest {\n constructor(value: any, fieldDefinitionName: string, joiValidationError: ValidationError) {\n const formattedErrorMessage = joiValidationError.message\n .replace(/\"/g, '')\n .replace('value', `'${fieldDefinitionName}'`);\n\n const formattedValue = typeof value === 'object' ? JSON.stringify(value) : value;\n\n const invalidValueMessage = `Invalid Value on field '${fieldDefinitionName}'. ${formattedErrorMessage}. received: '${formattedValue}'`;\n\n const err = new Error(invalidValueMessage);\n super([err], undefined, null);\n this.message = invalidValueMessage;\n }\n}\n\nexport class InvalidEntriesError extends BadRequest {\n constructor(modelId: string, validationErrors: EntriesValidationError[]) {\n const errors = validationErrors.map(validationError => new InvalidValueError(validationError.value, validationError.fieldDefinitionName, validationError.joiValidationError));\n super(errors, undefined, null);\n this.message = `Invalid entries on ${modelId}\\n${validationErrors.map(validationError => (\n `${validationError.fieldDefinitionName} - ${validationError.joiValidationError.message}`\n )).join('\\n')}`;\n }\n}\n\nexport class MissingDefinitionError extends BadRequest {\n constructor(fieldNames: string[]) {\n const err = new Error(`Missing custom field definition for field ${fieldNames.join(',')}`);\n super([err], undefined, null);\n this.message = 'MISSING_DEFINITION';\n }\n}\n"],"mappings":"+CAIA,IAAa,EAAb,cAAqD,CAAW,CAC9D,YAAY,EAAyB,CACnC,IAAM,EAAU,MAAM,6CAA6C,EAAc,KAAK,IAAI,GAAG,CAC7F,MAAM,CAAC,EAAI,CAAE,IAAA,GAAW,EAAc,CACtC,KAAK,QAAU,mCAIN,EAAb,cAAqD,CAAW,CAC9D,YAAY,EAAmB,CAC7B,IAAM,EAAU,MAAM,SAAS,EAAU,oBAAoB,CAC7D,MAAM,CAAC,EAAI,CAAE,IAAA,GAAW,KAAK,CAC7B,KAAK,QAAU,kCAIN,EAAb,cAAsD,CAAW,CAC/D,YAAY,EAAmB,CAC7B,IAAM,EAAU,MAAM,mBAAmB,EAAU,oBAAoB,CACvE,MAAM,CAAC,EAAI,CAAE,IAAA,GAAW,KAAK,CAC7B,KAAK,QAAU,uCAIN,EAAb,cAA2C,CAAW,CACpD,YAAY,EAAmB,CAC7B,IAAM,EAAU,MAAM,sBAAsB,IAAY,CACxD,MAAM,CAAC,EAAI,CAAE,IAAA,GAAW,KAAK,CAC7B,KAAK,QAAU,uBAIN,EAAb,cAAuC,CAAW,CAChD,YAAY,EAAY,EAA6B,EAAqC,CAOxF,IAAM,EAAsB,2BAA2B,EAAoB,KAN7C,EAAmB,QAC9C,QAAQ,KAAM,GAAG,CACjB,QAAQ,QAAS,IAAI,EAAoB,GAAG,CAIuD,eAF/E,OAAO,GAAU,SAAW,KAAK,UAAU,EAAM,CAAG,EAEyD,GAGpI,MAAM,CADU,MAAM,EAAoB,CAC/B,CAAE,IAAA,GAAW,KAAK,CAC7B,KAAK,QAAU,IAIN,EAAb,cAAyC,CAAW,CAClD,YAAY,EAAiB,EAA4C,CACvE,IAAM,EAAS,EAAiB,IAAI,GAAmB,IAAI,EAAkB,EAAgB,MAAO,EAAgB,oBAAqB,EAAgB,mBAAmB,CAAC,CAC7K,MAAM,EAAQ,IAAA,GAAW,KAAK,CAC9B,KAAK,QAAU,sBAAsB,EAAQ,IAAI,EAAiB,IAAI,GACpE,GAAG,EAAgB,oBAAoB,KAAK,EAAgB,mBAAmB,UAC/E,CAAC,KAAK;EAAK,KAIJ,EAAb,cAA4C,CAAW,CACrD,YAAY,EAAsB,CAChC,IAAM,EAAU,MAAM,6CAA6C,EAAW,KAAK,IAAI,GAAG,CAC1F,MAAM,CAAC,EAAI,CAAE,IAAA,GAAW,KAAK,CAC7B,KAAK,QAAU"}
|
package/dist/events/index.cjs
CHANGED
|
@@ -1,52 +1,2 @@
|
|
|
1
|
-
const
|
|
2
|
-
|
|
3
|
-
let _autofleet_zehut = require("@autofleet/zehut");
|
|
4
|
-
let _autofleet_events = require("@autofleet/events");
|
|
5
|
-
_autofleet_events = require_rolldown_runtime.__toESM(_autofleet_events);
|
|
6
|
-
|
|
7
|
-
//#region src/events/index.ts
|
|
8
|
-
const events = new _autofleet_events.default({
|
|
9
|
-
logger: require_index.default,
|
|
10
|
-
getUserId: (payload) => payload?.user_id ?? (0, _autofleet_zehut.getUser)()?.id ?? null
|
|
11
|
-
});
|
|
12
|
-
const KEYS_TO_CONVERT = [
|
|
13
|
-
"value",
|
|
14
|
-
"defaultValue",
|
|
15
|
-
"blockEditingFromUI"
|
|
16
|
-
];
|
|
17
|
-
const stringifyBooleans = (savedObject, keysToConvert) => {
|
|
18
|
-
const savedObjectKeySet = new Set(Object.keys(savedObject));
|
|
19
|
-
if (keysToConvert.every((key) => !savedObjectKeySet.has(key))) return savedObject;
|
|
20
|
-
return {
|
|
21
|
-
...savedObject,
|
|
22
|
-
...Object.fromEntries(keysToConvert.map((key) => [key, typeof savedObject[key] === "boolean" ? savedObject[key].toString() : savedObject[key]]))
|
|
23
|
-
};
|
|
24
|
-
};
|
|
25
|
-
const modelTableMapping = {
|
|
26
|
-
CustomFieldDefinition: {
|
|
27
|
-
tableName: "dim_custom_field_definition",
|
|
28
|
-
eventVersion: "1"
|
|
29
|
-
},
|
|
30
|
-
CustomFieldValue: {
|
|
31
|
-
tableName: "dim_custom_field_value",
|
|
32
|
-
eventVersion: "1"
|
|
33
|
-
},
|
|
34
|
-
CustomFieldEntries: {
|
|
35
|
-
tableName: "dim_custom_field_entries",
|
|
36
|
-
eventVersion: "1"
|
|
37
|
-
}
|
|
38
|
-
};
|
|
39
|
-
const sendDimEvent = (instance) => {
|
|
40
|
-
const mapping = modelTableMapping[instance.constructor.name];
|
|
41
|
-
if (!mapping) return;
|
|
42
|
-
let objectToSend = instance.get();
|
|
43
|
-
try {
|
|
44
|
-
objectToSend = stringifyBooleans(instance.get(), KEYS_TO_CONVERT);
|
|
45
|
-
} catch (err) {
|
|
46
|
-
require_index.default.error("Failed to convert booleans in dim event payload", err);
|
|
47
|
-
}
|
|
48
|
-
events.sendObject(mapping.tableName, mapping.eventVersion, objectToSend).catch(() => null);
|
|
49
|
-
};
|
|
50
|
-
|
|
51
|
-
//#endregion
|
|
52
|
-
exports.sendDimEvent = sendDimEvent;
|
|
1
|
+
const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../utils/logger/index.cjs`);let n=require(`@autofleet/zehut`),r=require(`@autofleet/events`);r=e.__toESM(r);const i=new r.default({logger:t.default,getUserId:e=>e?.user_id??(0,n.getUser)()?.id??null}),a=[`value`,`defaultValue`,`blockEditingFromUI`],o=(e,t)=>{let n=new Set(Object.keys(e));return t.every(e=>!n.has(e))?e:{...e,...Object.fromEntries(t.map(t=>[t,typeof e[t]==`boolean`?e[t].toString():e[t]]))}},s={CustomFieldDefinition:{tableName:`dim_custom_field_definition`,eventVersion:`1`},CustomFieldValue:{tableName:`dim_custom_field_value`,eventVersion:`1`},CustomFieldEntries:{tableName:`dim_custom_field_entries`,eventVersion:`1`}},c=e=>{let n=s[e.constructor.name];if(!n)return;let r=e.get();try{r=o(e.get(),a)}catch(e){t.default.error(`Failed to convert booleans in dim event payload`,e)}i.sendObject(n.tableName,n.eventVersion,r).catch(()=>null)};exports.sendDimEvent=c;
|
|
2
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["events: Events","Events"],"sources":["../../src/events/index.ts"],"sourcesContent":["import Events from '@autofleet/events';\nimport { getUser } from '@autofleet/zehut';\nimport logger from '../utils/logger';\nimport type {\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomFieldValue,\n CustomValidator,\n} from '../models';\n\nconst events: Events = new Events({\n logger,\n getUserId: payload => payload?.user_id ?? getUser()?.id ?? null,\n});\n\nconst KEYS_TO_CONVERT = ['value', 'defaultValue', 'blockEditingFromUI'];\n\nconst stringifyBooleans = (savedObject: any, keysToConvert: string[]) => {\n const savedObjectKeySet = new Set(Object.keys(savedObject));\n if (keysToConvert.every(key => !savedObjectKeySet.has(key))) {\n return savedObject;\n }\n return {\n ...savedObject,\n ...Object.fromEntries(keysToConvert.map(key => [key, typeof savedObject[key] === 'boolean' ? savedObject[key].toString() : savedObject[key]])),\n };\n};\n\nconst modelTableMapping = {\n CustomFieldDefinition: {\n tableName: 'dim_custom_field_definition',\n eventVersion: '1',\n },\n CustomFieldValue: {\n tableName: 'dim_custom_field_value',\n eventVersion: '1',\n },\n CustomFieldEntries: {\n tableName: 'dim_custom_field_entries',\n eventVersion: '1',\n },\n};\n\nexport const sendDimEvent = (instance: CustomFieldDefinition | CustomFieldValue | CustomFieldEntries | CustomValidator): void => {\n const mapping = modelTableMapping[instance.constructor.name as keyof typeof modelTableMapping];\n if (!mapping) {\n return;\n }\n let objectToSend = instance.get();\n try {\n objectToSend = stringifyBooleans(instance.get(), KEYS_TO_CONVERT);\n } catch (err) {\n logger.error('Failed to convert booleans in dim event payload', err);\n }\n\n events.sendObject(\n mapping.tableName,\n mapping.eventVersion,\n objectToSend,\n ).catch(() => null);\n};\n\nexport default events;\n"],"mappings":"2KAUA,MAAMA,EAAiB,IAAIC,EAAAA,QAAO,CAChC,OAAA,EAAA,QACA,UAAW,GAAW,GAAS,UAAA,EAAA,EAAA,UAAoB,EAAE,IAAM,KAC5D,CAAC,CAEI,EAAkB,CAAC,QAAS,eAAgB,qBAAqB,CAEjE,GAAqB,EAAkB,IAA4B,CACvE,IAAM,EAAoB,IAAI,IAAI,OAAO,KAAK,EAAY,CAAC,CAI3D,OAHI,EAAc,MAAM,GAAO,CAAC,EAAkB,IAAI,EAAI,CAAC,CAClD,EAEF,CACL,GAAG,EACH,GAAG,OAAO,YAAY,EAAc,IAAI,GAAO,CAAC,EAAK,OAAO,EAAY,IAAS,UAAY,EAAY,GAAK,UAAU,CAAG,EAAY,GAAK,CAAC,CAAC,CAC/I,EAGG,EAAoB,CACxB,sBAAuB,CACrB,UAAW,8BACX,aAAc,IACf,CACD,iBAAkB,CAChB,UAAW,yBACX,aAAc,IACf,CACD,mBAAoB,CAClB,UAAW,2BACX,aAAc,IACf,CACF,CAEY,EAAgB,GAAoG,CAC/H,IAAM,EAAU,EAAkB,EAAS,YAAY,MACvD,GAAI,CAAC,EACH,OAEF,IAAI,EAAe,EAAS,KAAK,CACjC,GAAI,CACF,EAAe,EAAkB,EAAS,KAAK,CAAE,EAAgB,OAC1D,EAAK,CACZ,EAAA,QAAO,MAAM,kDAAmD,EAAI,CAGtE,EAAO,WACL,EAAQ,UACR,EAAQ,aACR,EACD,CAAC,UAAY,KAAK"}
|
package/dist/events/index.js
CHANGED
|
@@ -1,50 +1,2 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
import Events from "@autofleet/events";
|
|
4
|
-
|
|
5
|
-
//#region src/events/index.ts
|
|
6
|
-
const events = new Events({
|
|
7
|
-
logger: logger_default,
|
|
8
|
-
getUserId: (payload) => payload?.user_id ?? getUser()?.id ?? null
|
|
9
|
-
});
|
|
10
|
-
const KEYS_TO_CONVERT = [
|
|
11
|
-
"value",
|
|
12
|
-
"defaultValue",
|
|
13
|
-
"blockEditingFromUI"
|
|
14
|
-
];
|
|
15
|
-
const stringifyBooleans = (savedObject, keysToConvert) => {
|
|
16
|
-
const savedObjectKeySet = new Set(Object.keys(savedObject));
|
|
17
|
-
if (keysToConvert.every((key) => !savedObjectKeySet.has(key))) return savedObject;
|
|
18
|
-
return {
|
|
19
|
-
...savedObject,
|
|
20
|
-
...Object.fromEntries(keysToConvert.map((key) => [key, typeof savedObject[key] === "boolean" ? savedObject[key].toString() : savedObject[key]]))
|
|
21
|
-
};
|
|
22
|
-
};
|
|
23
|
-
const modelTableMapping = {
|
|
24
|
-
CustomFieldDefinition: {
|
|
25
|
-
tableName: "dim_custom_field_definition",
|
|
26
|
-
eventVersion: "1"
|
|
27
|
-
},
|
|
28
|
-
CustomFieldValue: {
|
|
29
|
-
tableName: "dim_custom_field_value",
|
|
30
|
-
eventVersion: "1"
|
|
31
|
-
},
|
|
32
|
-
CustomFieldEntries: {
|
|
33
|
-
tableName: "dim_custom_field_entries",
|
|
34
|
-
eventVersion: "1"
|
|
35
|
-
}
|
|
36
|
-
};
|
|
37
|
-
const sendDimEvent = (instance) => {
|
|
38
|
-
const mapping = modelTableMapping[instance.constructor.name];
|
|
39
|
-
if (!mapping) return;
|
|
40
|
-
let objectToSend = instance.get();
|
|
41
|
-
try {
|
|
42
|
-
objectToSend = stringifyBooleans(instance.get(), KEYS_TO_CONVERT);
|
|
43
|
-
} catch (err) {
|
|
44
|
-
logger_default.error("Failed to convert booleans in dim event payload", err);
|
|
45
|
-
}
|
|
46
|
-
events.sendObject(mapping.tableName, mapping.eventVersion, objectToSend).catch(() => null);
|
|
47
|
-
};
|
|
48
|
-
|
|
49
|
-
//#endregion
|
|
50
|
-
export { sendDimEvent };
|
|
1
|
+
import e from"../utils/logger/index.js";import{getUser as t}from"@autofleet/zehut";import n from"@autofleet/events";const r=new n({logger:e,getUserId:e=>e?.user_id??t()?.id??null}),i=[`value`,`defaultValue`,`blockEditingFromUI`],a=(e,t)=>{let n=new Set(Object.keys(e));return t.every(e=>!n.has(e))?e:{...e,...Object.fromEntries(t.map(t=>[t,typeof e[t]==`boolean`?e[t].toString():e[t]]))}},o={CustomFieldDefinition:{tableName:`dim_custom_field_definition`,eventVersion:`1`},CustomFieldValue:{tableName:`dim_custom_field_value`,eventVersion:`1`},CustomFieldEntries:{tableName:`dim_custom_field_entries`,eventVersion:`1`}},s=t=>{let n=o[t.constructor.name];if(!n)return;let s=t.get();try{s=a(t.get(),i)}catch(t){e.error(`Failed to convert booleans in dim event payload`,t)}r.sendObject(n.tableName,n.eventVersion,s).catch(()=>null)};export{s as sendDimEvent};
|
|
2
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["events: Events"],"sources":["../../src/events/index.ts"],"sourcesContent":["import Events from '@autofleet/events';\nimport { getUser } from '@autofleet/zehut';\nimport logger from '../utils/logger';\nimport type {\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomFieldValue,\n CustomValidator,\n} from '../models';\n\nconst events: Events = new Events({\n logger,\n getUserId: payload => payload?.user_id ?? getUser()?.id ?? null,\n});\n\nconst KEYS_TO_CONVERT = ['value', 'defaultValue', 'blockEditingFromUI'];\n\nconst stringifyBooleans = (savedObject: any, keysToConvert: string[]) => {\n const savedObjectKeySet = new Set(Object.keys(savedObject));\n if (keysToConvert.every(key => !savedObjectKeySet.has(key))) {\n return savedObject;\n }\n return {\n ...savedObject,\n ...Object.fromEntries(keysToConvert.map(key => [key, typeof savedObject[key] === 'boolean' ? savedObject[key].toString() : savedObject[key]])),\n };\n};\n\nconst modelTableMapping = {\n CustomFieldDefinition: {\n tableName: 'dim_custom_field_definition',\n eventVersion: '1',\n },\n CustomFieldValue: {\n tableName: 'dim_custom_field_value',\n eventVersion: '1',\n },\n CustomFieldEntries: {\n tableName: 'dim_custom_field_entries',\n eventVersion: '1',\n },\n};\n\nexport const sendDimEvent = (instance: CustomFieldDefinition | CustomFieldValue | CustomFieldEntries | CustomValidator): void => {\n const mapping = modelTableMapping[instance.constructor.name as keyof typeof modelTableMapping];\n if (!mapping) {\n return;\n }\n let objectToSend = instance.get();\n try {\n objectToSend = stringifyBooleans(instance.get(), KEYS_TO_CONVERT);\n } catch (err) {\n logger.error('Failed to convert booleans in dim event payload', err);\n }\n\n events.sendObject(\n mapping.tableName,\n mapping.eventVersion,\n objectToSend,\n ).catch(() => null);\n};\n\nexport default events;\n"],"mappings":"oHAUA,MAAMA,EAAiB,IAAI,EAAO,CAChC,OAAA,EACA,UAAW,GAAW,GAAS,SAAW,GAAS,EAAE,IAAM,KAC5D,CAAC,CAEI,EAAkB,CAAC,QAAS,eAAgB,qBAAqB,CAEjE,GAAqB,EAAkB,IAA4B,CACvE,IAAM,EAAoB,IAAI,IAAI,OAAO,KAAK,EAAY,CAAC,CAI3D,OAHI,EAAc,MAAM,GAAO,CAAC,EAAkB,IAAI,EAAI,CAAC,CAClD,EAEF,CACL,GAAG,EACH,GAAG,OAAO,YAAY,EAAc,IAAI,GAAO,CAAC,EAAK,OAAO,EAAY,IAAS,UAAY,EAAY,GAAK,UAAU,CAAG,EAAY,GAAK,CAAC,CAAC,CAC/I,EAGG,EAAoB,CACxB,sBAAuB,CACrB,UAAW,8BACX,aAAc,IACf,CACD,iBAAkB,CAChB,UAAW,yBACX,aAAc,IACf,CACD,mBAAoB,CAClB,UAAW,2BACX,aAAc,IACf,CACF,CAEY,EAAgB,GAAoG,CAC/H,IAAM,EAAU,EAAkB,EAAS,YAAY,MACvD,GAAI,CAAC,EACH,OAEF,IAAI,EAAe,EAAS,KAAK,CACjC,GAAI,CACF,EAAe,EAAkB,EAAS,KAAK,CAAE,EAAgB,OAC1D,EAAK,CACZ,EAAO,MAAM,kDAAmD,EAAI,CAGtE,EAAO,WACL,EAAQ,UACR,EAAQ,aACR,EACD,CAAC,UAAY,KAAK"}
|
package/dist/hooks/enrich.cjs
CHANGED
|
@@ -1,175 +1,2 @@
|
|
|
1
|
-
const
|
|
2
|
-
|
|
3
|
-
const require_entries = require('../repository/entries.cjs');
|
|
4
|
-
const require_scopeAttributes = require('../utils/scopeAttributes.cjs');
|
|
5
|
-
|
|
6
|
-
//#region src/hooks/enrich.ts
|
|
7
|
-
const CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL = [
|
|
8
|
-
"id",
|
|
9
|
-
"name",
|
|
10
|
-
"entityId",
|
|
11
|
-
"fieldType",
|
|
12
|
-
"displayName",
|
|
13
|
-
"validation",
|
|
14
|
-
"entityType",
|
|
15
|
-
"modelType",
|
|
16
|
-
"required",
|
|
17
|
-
"disabled",
|
|
18
|
-
"defaultValue"
|
|
19
|
-
];
|
|
20
|
-
const getCustomFieldEntriesByInstanceId = async ({ instancesIds, options, sadotOptions }) => {
|
|
21
|
-
if (!sadotOptions.useCustomFieldsEntries) return {};
|
|
22
|
-
const customFieldEntries = await require_entries.findEntriesByModelIds(instancesIds, options ?? {});
|
|
23
|
-
const customFieldEntriesByInstanceId = Object.fromEntries(customFieldEntries.map((instanceEntries) => {
|
|
24
|
-
const { modelId, customFields } = instanceEntries?.dataValues ?? {};
|
|
25
|
-
if (!modelId) return;
|
|
26
|
-
return [modelId, customFields];
|
|
27
|
-
}).filter((v) => v !== void 0));
|
|
28
|
-
instancesIds.forEach((instanceId) => {
|
|
29
|
-
customFieldEntriesByInstanceId[instanceId] ??= {};
|
|
30
|
-
});
|
|
31
|
-
return customFieldEntriesByInstanceId;
|
|
32
|
-
};
|
|
33
|
-
const getValuesGroupByInstance = async ({ instancesIds, options, sadotOptions }) => {
|
|
34
|
-
if (sadotOptions.useCustomFieldsEntries) return {};
|
|
35
|
-
return (await require_value.findValuesByModelIds(instancesIds, options ?? {})).reduce((acc, v) => {
|
|
36
|
-
const { modelId } = v;
|
|
37
|
-
acc[modelId] ??= [];
|
|
38
|
-
acc[modelId].push(v);
|
|
39
|
-
return acc;
|
|
40
|
-
}, {});
|
|
41
|
-
};
|
|
42
|
-
/**
|
|
43
|
-
* Serialize custom fields value into the format of {[name] -> [fieldData]}
|
|
44
|
-
*/
|
|
45
|
-
const serializeCustomFields = (customFieldValues, customFieldDefinitionsHash) => {
|
|
46
|
-
return customFieldValues.reduce((acc, cfv) => ({
|
|
47
|
-
...acc,
|
|
48
|
-
...customFieldDefinitionsHash[cfv.customFieldDefinitionId] && { [customFieldDefinitionsHash[cfv.customFieldDefinitionId].name]: cfv.value }
|
|
49
|
-
}), {});
|
|
50
|
-
};
|
|
51
|
-
/**
|
|
52
|
-
* A hook to attach the custom fields when fetching a model instances.
|
|
53
|
-
*/
|
|
54
|
-
const enrichResults = (modelType, scopeAttributes, hookType, modelOptions = {}, sadotOptions = {
|
|
55
|
-
useCustomFieldsEntries: false,
|
|
56
|
-
hasTypeId: false
|
|
57
|
-
}) => async (instancesOrInstance, options) => {
|
|
58
|
-
if (options.originalAttributes?.length > 0 && !options.originalAttributes?.includes?.("customFields")) return;
|
|
59
|
-
const primaryKey = "id";
|
|
60
|
-
let instances = Array.isArray(instancesOrInstance) ? instancesOrInstance : [instancesOrInstance];
|
|
61
|
-
instances = instances.filter(Boolean);
|
|
62
|
-
const identifiers = require_scopeAttributes.default(instances, scopeAttributes);
|
|
63
|
-
const uniqueIdentifiers = [...new Set(identifiers)].filter(Boolean);
|
|
64
|
-
const identifierCustomFieldDefinitionsMapping = uniqueIdentifiers.reduce((map, identifier) => ({
|
|
65
|
-
...map,
|
|
66
|
-
[identifier]: []
|
|
67
|
-
}), {});
|
|
68
|
-
let customFieldDefinitionsPromise;
|
|
69
|
-
let cacheKey;
|
|
70
|
-
if (options.transaction) {
|
|
71
|
-
options.transaction.definitionCache ??= /* @__PURE__ */ new Map();
|
|
72
|
-
cacheKey = `${modelType}:${uniqueIdentifiers.slice().sort().join(",")}`;
|
|
73
|
-
customFieldDefinitionsPromise = options.transaction.definitionCache.get(cacheKey);
|
|
74
|
-
}
|
|
75
|
-
let modelTypeDefinitionsMap;
|
|
76
|
-
if (!customFieldDefinitionsPromise) {
|
|
77
|
-
const shouldApplyTypeFiltering = sadotOptions.hasTypeId && instances.length > 0 && instances[0].typeId;
|
|
78
|
-
const fetchDefinitions = async (transaction = options.transaction) => {
|
|
79
|
-
if (shouldApplyTypeFiltering) {
|
|
80
|
-
const uniqueTypeIds = [...new Set(instances.map((instance) => instance.typeId).filter(Boolean))];
|
|
81
|
-
modelTypeDefinitionsMap = /* @__PURE__ */ new Map();
|
|
82
|
-
uniqueTypeIds.forEach((typeId) => modelTypeDefinitionsMap.set(typeId, /* @__PURE__ */ new Set()));
|
|
83
|
-
const allDefinitions = (await Promise.all(uniqueTypeIds.map(async (typeId) => {
|
|
84
|
-
const defs = await require_definition.findByModelTypeId(typeId, {
|
|
85
|
-
withDisabled: false,
|
|
86
|
-
entityIds: uniqueIdentifiers,
|
|
87
|
-
modelType,
|
|
88
|
-
modelOptions,
|
|
89
|
-
transaction
|
|
90
|
-
});
|
|
91
|
-
defs.forEach((def) => modelTypeDefinitionsMap.get(typeId).add(def.id));
|
|
92
|
-
return defs;
|
|
93
|
-
}))).flat();
|
|
94
|
-
const uniqueDefinitionsMap = /* @__PURE__ */ new Map();
|
|
95
|
-
allDefinitions.forEach((def) => {
|
|
96
|
-
uniqueDefinitionsMap.set(def.id, def);
|
|
97
|
-
});
|
|
98
|
-
return Array.from(uniqueDefinitionsMap.values());
|
|
99
|
-
}
|
|
100
|
-
return require_definition.findByEntityIds(modelType, uniqueIdentifiers, {
|
|
101
|
-
transaction,
|
|
102
|
-
modelOptions,
|
|
103
|
-
attributes: CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL
|
|
104
|
-
});
|
|
105
|
-
};
|
|
106
|
-
customFieldDefinitionsPromise = fetchDefinitions();
|
|
107
|
-
if (!shouldApplyTypeFiltering) options.transaction?.definitionCache?.set(cacheKey, customFieldDefinitionsPromise);
|
|
108
|
-
}
|
|
109
|
-
const customFieldDefinitions = await customFieldDefinitionsPromise;
|
|
110
|
-
if (customFieldDefinitions.length === 0) {
|
|
111
|
-
instances.forEach((instance) => {
|
|
112
|
-
instance.customFields = {};
|
|
113
|
-
});
|
|
114
|
-
return;
|
|
115
|
-
}
|
|
116
|
-
if (modelOptions?.include && modelOptions.useEntityIdFromInclude) modelOptions.include(identifiers).forEach(({ model }) => {
|
|
117
|
-
customFieldDefinitions.forEach((cfd) => {
|
|
118
|
-
const entityId = cfd[model.name]?.entityId || cfd[`${model.name}.entityId`];
|
|
119
|
-
if (entityId && !identifierCustomFieldDefinitionsMapping[entityId]) identifierCustomFieldDefinitionsMapping[entityId] = [];
|
|
120
|
-
});
|
|
121
|
-
});
|
|
122
|
-
const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({
|
|
123
|
-
...map,
|
|
124
|
-
[definition.id]: definition
|
|
125
|
-
}), {});
|
|
126
|
-
customFieldDefinitions.forEach((cfd) => {
|
|
127
|
-
let entityIdToUse = cfd.entityId;
|
|
128
|
-
if (modelOptions?.useEntityIdFromInclude && modelOptions.include) {
|
|
129
|
-
const contextIncludes = modelOptions.include(identifiers);
|
|
130
|
-
for (const { model } of contextIncludes) {
|
|
131
|
-
const joinedEntityId = cfd[model.name]?.entityId || cfd[`${model.name}.entityId`];
|
|
132
|
-
if (joinedEntityId) {
|
|
133
|
-
entityIdToUse = joinedEntityId;
|
|
134
|
-
break;
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
if (identifierCustomFieldDefinitionsMapping[entityIdToUse]) identifierCustomFieldDefinitionsMapping[entityIdToUse].push(cfd);
|
|
139
|
-
});
|
|
140
|
-
const instancesIds = instances.map((i) => i[primaryKey]);
|
|
141
|
-
const [valuesGroupByInstance, customFieldEntriesByInstanceId] = await Promise.all([getValuesGroupByInstance({
|
|
142
|
-
instancesIds,
|
|
143
|
-
options,
|
|
144
|
-
sadotOptions
|
|
145
|
-
}), getCustomFieldEntriesByInstanceId({
|
|
146
|
-
instancesIds,
|
|
147
|
-
options,
|
|
148
|
-
sadotOptions
|
|
149
|
-
})]);
|
|
150
|
-
instances.forEach((instance) => {
|
|
151
|
-
const { id } = instance;
|
|
152
|
-
const instanceValues = valuesGroupByInstance[id];
|
|
153
|
-
const serializedCustomFieldsValues = instanceValues ? serializeCustomFields(instanceValues, definitionsMap) : {};
|
|
154
|
-
const customFields = sadotOptions.useCustomFieldsEntries ? customFieldEntriesByInstanceId[id] : serializedCustomFieldsValues;
|
|
155
|
-
scopeAttributes.forEach((attribute) => {
|
|
156
|
-
const entityCustomFieldDefinitions = identifierCustomFieldDefinitionsMapping[instance[attribute]];
|
|
157
|
-
if (entityCustomFieldDefinitions && entityCustomFieldDefinitions.length > 0) entityCustomFieldDefinitions.forEach((customFieldDefinition) => {
|
|
158
|
-
if (modelTypeDefinitionsMap) {
|
|
159
|
-
if (!modelTypeDefinitionsMap.get(instance.typeId)?.has(customFieldDefinition.id)) return;
|
|
160
|
-
}
|
|
161
|
-
if (customFields[customFieldDefinition.name] === void 0) customFields[customFieldDefinition.name] = null;
|
|
162
|
-
});
|
|
163
|
-
});
|
|
164
|
-
instance.customFields = customFields;
|
|
165
|
-
options.attributesToRemove?.forEach?.((attribute) => {
|
|
166
|
-
delete instance.dataValues?.[attribute];
|
|
167
|
-
delete instance?.[attribute];
|
|
168
|
-
});
|
|
169
|
-
if (hookType === "afterFind") instance?.changed?.("customFields", false);
|
|
170
|
-
});
|
|
171
|
-
};
|
|
172
|
-
var enrich_default = enrichResults;
|
|
173
|
-
|
|
174
|
-
//#endregion
|
|
175
|
-
exports.default = enrich_default;
|
|
1
|
+
const e=require(`../repository/definition.cjs`),t=require(`../repository/value.cjs`),n=require(`../repository/entries.cjs`),r=require(`../utils/scopeAttributes.cjs`),i=[`id`,`name`,`entityId`,`fieldType`,`displayName`,`validation`,`entityType`,`modelType`,`required`,`disabled`,`defaultValue`],a=async({instancesIds:e,options:t,sadotOptions:r})=>{if(!r.useCustomFieldsEntries)return{};let i=await n.findEntriesByModelIds(e,t??{}),a=Object.fromEntries(i.map(e=>{let{modelId:t,customFields:n}=e?.dataValues??{};if(t)return[t,n]}).filter(e=>e!==void 0));return e.forEach(e=>{a[e]??={}}),a},o=async({instancesIds:e,options:n,sadotOptions:r})=>r.useCustomFieldsEntries?{}:(await t.findValuesByModelIds(e,n??{})).reduce((e,t)=>{let{modelId:n}=t;return e[n]??=[],e[n].push(t),e},{}),s=(e,t)=>e.reduce((e,n)=>({...e,...t[n.customFieldDefinitionId]&&{[t[n.customFieldDefinitionId].name]:n.value}}),{}),c=(t,n,c,l={},u={useCustomFieldsEntries:!1,hasTypeId:!1})=>async(d,f)=>{if(f.originalAttributes?.length>0&&!f.originalAttributes?.includes?.(`customFields`))return;let p=Array.isArray(d)?d:[d];p=p.filter(Boolean);let m=r.default(p,n),h=[...new Set(m)].filter(Boolean),g=h.reduce((e,t)=>({...e,[t]:[]}),{}),_,v;f.transaction&&(f.transaction.definitionCache??=new Map,v=`${t}:${h.slice().sort().join(`,`)}`,_=f.transaction.definitionCache.get(v));let y;if(!_){let n=u.hasTypeId&&p.length>0&&p[0].typeId;_=(async(r=f.transaction)=>{if(n){let n=[...new Set(p.map(e=>e.typeId).filter(Boolean))];y=new Map,n.forEach(e=>y.set(e,new Set));let i=(await Promise.all(n.map(async n=>{let i=await e.findByModelTypeId(n,{withDisabled:!1,entityIds:h,modelType:t,modelOptions:l,transaction:r});return i.forEach(e=>y.get(n).add(e.id)),i}))).flat(),a=new Map;return i.forEach(e=>{a.set(e.id,e)}),Array.from(a.values())}return e.findByEntityIds(t,h,{transaction:r,modelOptions:l,attributes:i})})(),n||f.transaction?.definitionCache?.set(v,_)}let b=await _;if(b.length===0){p.forEach(e=>{e.customFields={}});return}l?.include&&l.useEntityIdFromInclude&&l.include(m).forEach(({model:e})=>{b.forEach(t=>{let n=t[e.name]?.entityId||t[`${e.name}.entityId`];n&&!g[n]&&(g[n]=[])})});let x=b.reduce((e,t)=>({...e,[t.id]:t}),{});b.forEach(e=>{let t=e.entityId;if(l?.useEntityIdFromInclude&&l.include){let n=l.include(m);for(let{model:r}of n){let n=e[r.name]?.entityId||e[`${r.name}.entityId`];if(n){t=n;break}}}g[t]&&g[t].push(e)});let S=p.map(e=>e.id),[C,w]=await Promise.all([o({instancesIds:S,options:f,sadotOptions:u}),a({instancesIds:S,options:f,sadotOptions:u})]);p.forEach(e=>{let{id:t}=e,r=C[t],i=r?s(r,x):{},a=u.useCustomFieldsEntries?w[t]:i;n.forEach(t=>{let n=g[e[t]];n&&n.length>0&&n.forEach(t=>{y&&!y.get(e.typeId)?.has(t.id)||a[t.name]===void 0&&(a[t.name]=null)})}),e.customFields=a,f.attributesToRemove?.forEach?.(t=>{delete e.dataValues?.[t],delete e?.[t]}),c===`afterFind`&&e?.changed?.(`customFields`,!1)})};var l=c;exports.default=l;
|
|
2
|
+
//# sourceMappingURL=enrich.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"enrich.cjs","names":["applyScopeToInstance","cacheKey: string | undefined","modelTypeDefinitionsMap: Map<string, Set<string>> | undefined"],"sources":["../../src/hooks/enrich.ts"],"sourcesContent":["import * as ValueRepo from '../repository/value';\nimport * as DefinitionRepo from '../repository/definition';\nimport * as EntriesRepo from '../repository/entries';\nimport type CustomFieldValue from '../models/CustomFieldValue';\nimport type CustomFieldDefinition from '../models/CustomFieldDefinition';\nimport type { SerializedCustomFields } from '../types/definition';\nimport type { CustomFieldOptions, ModelOptions, TransactionOptions } from '../types';\nimport applyScopeToInstance from '../utils/scopeAttributes';\n\n// Include all required fields for proper functioning\nconst CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL = [\n 'id',\n 'name',\n 'entityId',\n 'fieldType',\n 'displayName',\n 'validation',\n 'entityType',\n 'modelType',\n 'required',\n 'disabled',\n 'defaultValue',\n];\n\ntype SupportedHookTypes = 'afterFind' | 'afterCreate' | 'afterUpdate';\n\ntype CustomFieldEntries = Record<string, any>;\n\n// eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style\ninterface GetValuesGroupByInstanceResponse {\n [modelId: string]: CustomFieldValue[];\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style\ninterface GetCustomFieldEntriesByInstanceIdResponse {\n [modelId: string]: CustomFieldEntries;\n}\n\nexport const getCustomFieldEntriesByInstanceId = async ({\n instancesIds,\n options,\n sadotOptions,\n}: {\n instancesIds: string[];\n options?: TransactionOptions;\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>;\n}): Promise<GetCustomFieldEntriesByInstanceIdResponse> => {\n if (!sadotOptions.useCustomFieldsEntries) {\n return {};\n }\n\n const customFieldEntries = await EntriesRepo.findEntriesByModelIds(\n instancesIds,\n options ?? {},\n );\n\n const customFieldEntriesByInstanceId = Object.fromEntries(customFieldEntries.map((instanceEntries) => {\n const { modelId, customFields } = instanceEntries?.dataValues ?? {};\n if (!modelId) {\n return undefined;\n }\n return [modelId, customFields];\n }).filter(v => v !== undefined));\n\n instancesIds.forEach((instanceId) => {\n customFieldEntriesByInstanceId[instanceId] ??= {};\n });\n\n return customFieldEntriesByInstanceId;\n};\n\nexport const getValuesGroupByInstance = async ({\n instancesIds,\n options,\n sadotOptions,\n}: {\n instancesIds: string[];\n options?: TransactionOptions;\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>;\n}): Promise<GetValuesGroupByInstanceResponse> => {\n if (sadotOptions.useCustomFieldsEntries) {\n return {};\n }\n\n const customFieldValues = await ValueRepo.findValuesByModelIds(\n instancesIds,\n options ?? {},\n );\n\n // Group fields by modelId\n return customFieldValues.reduce<Record<string, CustomFieldValue[]>>((acc, v) => {\n const { modelId } = v;\n acc[modelId] ??= [];\n acc[modelId].push(v);\n return acc;\n }, {});\n};\n\n/**\n * Serialize custom fields value into the format of {[name] -> [fieldData]}\n */\nconst serializeCustomFields = (\n customFieldValues: CustomFieldValue[],\n customFieldDefinitionsHash: Record<string, CustomFieldDefinition>,\n): SerializedCustomFields => {\n const customFields = customFieldValues.reduce((acc, cfv) => ({\n ...acc,\n ...(\n customFieldDefinitionsHash[cfv.customFieldDefinitionId]\n && { [customFieldDefinitionsHash[cfv.customFieldDefinitionId].name]: cfv.value }\n ),\n }), {});\n return customFields;\n};\n/**\n * A hook to attach the custom fields when fetching a model instances.\n */\nconst enrichResults = (\n modelType: string,\n scopeAttributes: string[],\n hookType?: SupportedHookTypes,\n modelOptions: ModelOptions = {},\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries' | 'hasTypeId'> = { useCustomFieldsEntries: false, hasTypeId: false },\n) => async (\n instancesOrInstance: any | any[],\n options: TransactionOptions,\n): Promise<void> => {\n if (options.originalAttributes?.length > 0 && !options.originalAttributes?.includes?.('customFields')) {\n return;\n }\n\n const primaryKey = 'id';\n let instances = Array.isArray(instancesOrInstance)\n ? instancesOrInstance\n : [instancesOrInstance];\n\n instances = instances.filter(Boolean);\n\n const identifiers = applyScopeToInstance(instances, scopeAttributes);\n\n const uniqueIdentifiers = [...new Set(identifiers)].filter(Boolean);\n\n const identifierCustomFieldDefinitionsMapping = uniqueIdentifiers.reduce((map, identifier) => ({\n ...map,\n [identifier]: [],\n }), {});\n\n // Cache for definitions by model type and transaction to avoid redundant DB queries\n let customFieldDefinitionsPromise;\n let cacheKey: string | undefined;\n\n if (options.transaction) {\n // Initialize definition cache Map if not already present directly on the transaction object\n options.transaction.definitionCache ??= new Map();\n cacheKey = `${modelType}:${uniqueIdentifiers.slice().sort().join(',')}`;\n customFieldDefinitionsPromise = options.transaction.definitionCache.get(cacheKey);\n }\n\n let modelTypeDefinitionsMap: Map<string, Set<string>> | undefined;\n\n // Fetch from database (either first time in this transaction or no transaction).\n if (!customFieldDefinitionsPromise) {\n const shouldApplyTypeFiltering = sadotOptions.hasTypeId && instances.length > 0 && instances[0].typeId;\n\n const fetchDefinitions = async (transaction = options.transaction) => {\n if (shouldApplyTypeFiltering) {\n const uniqueTypeIds = [...new Set(instances.map(instance => instance.typeId).filter(Boolean))];\n\n modelTypeDefinitionsMap = new Map<string, Set<string>>();\n uniqueTypeIds.forEach(typeId => modelTypeDefinitionsMap!.set(typeId, new Set()));\n\n const definitionsResults = await Promise.all(\n uniqueTypeIds.map(async (typeId) => {\n const defs = await DefinitionRepo.findByModelTypeId(typeId, { withDisabled: false, entityIds: uniqueIdentifiers, modelType, modelOptions, transaction });\n defs.forEach(def => modelTypeDefinitionsMap!.get(typeId)!.add(def.id));\n return defs;\n }),\n );\n\n const allDefinitions = definitionsResults.flat();\n const uniqueDefinitionsMap = new Map();\n allDefinitions.forEach((def) => {\n uniqueDefinitionsMap.set(def.id, def);\n });\n return Array.from(uniqueDefinitionsMap.values());\n }\n return DefinitionRepo.findByEntityIds(\n modelType,\n uniqueIdentifiers,\n { transaction, modelOptions, attributes: CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL },\n );\n };\n\n customFieldDefinitionsPromise = fetchDefinitions();\n\n if (!shouldApplyTypeFiltering) {\n options.transaction?.definitionCache?.set(cacheKey!, customFieldDefinitionsPromise);\n }\n }\n const customFieldDefinitions = await customFieldDefinitionsPromise;\n\n if (customFieldDefinitions.length === 0) {\n // if no custom fields, we can return\n instances.forEach((instance) => {\n instance.customFields = {};\n });\n return;\n }\n\n if (modelOptions?.include && modelOptions.useEntityIdFromInclude) {\n // if we pass useEntityIdFromInclude,\n // map the entity from the options to the identifierCustomFieldDefinitionsMapping\n modelOptions.include(identifiers).forEach(({ model }) => {\n customFieldDefinitions.forEach((cfd: any) => {\n // try 2 ways to get the entityId from the joined model - for raw and non-raw\n const entityId = cfd[model!.name]?.entityId || cfd[`${model!.name}.entityId` as keyof CustomFieldDefinition];\n if (entityId && !identifierCustomFieldDefinitionsMapping[entityId]) {\n identifierCustomFieldDefinitionsMapping[entityId] = [];\n }\n });\n });\n }\n\n const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({\n ...map,\n [definition.id]: definition,\n }), {});\n\n customFieldDefinitions.forEach((cfd: any) => {\n let entityIdToUse = cfd.entityId;\n\n if (modelOptions?.useEntityIdFromInclude && modelOptions.include) {\n const contextIncludes = modelOptions.include(identifiers);\n for (const { model } of contextIncludes) {\n const joinedEntityId = cfd[model!.name]?.entityId || cfd[`${model!.name}.entityId` as keyof CustomFieldDefinition];\n if (joinedEntityId) {\n entityIdToUse = joinedEntityId;\n break;\n }\n }\n }\n\n if (identifierCustomFieldDefinitionsMapping[entityIdToUse]) {\n identifierCustomFieldDefinitionsMapping[entityIdToUse].push(cfd);\n }\n });\n\n // Get the values per instates ids:\n const instancesIds = instances.map(i => i[primaryKey]);\n\n // Group fields by modelId\n const [valuesGroupByInstance, customFieldEntriesByInstanceId] = await Promise.all([\n getValuesGroupByInstance({\n instancesIds,\n options,\n sadotOptions,\n }),\n getCustomFieldEntriesByInstanceId({\n instancesIds,\n options,\n sadotOptions,\n }),\n ]);\n\n // Attach custom fields to the instances\n instances.forEach((instance) => {\n const { id } = instance;\n\n const instanceValues = valuesGroupByInstance[id];\n const serializedCustomFieldsValues = instanceValues ? serializeCustomFields(instanceValues, definitionsMap) : {};\n\n const customFields = sadotOptions.useCustomFieldsEntries\n ? customFieldEntriesByInstanceId[id]\n : serializedCustomFieldsValues;\n\n scopeAttributes.forEach((attribute) => {\n const identifier = instance[attribute];\n\n const entityCustomFieldDefinitions = identifierCustomFieldDefinitionsMapping[identifier] as CustomFieldDefinition[] | undefined;\n if (entityCustomFieldDefinitions && entityCustomFieldDefinitions.length > 0) {\n entityCustomFieldDefinitions.forEach((customFieldDefinition) => {\n if (modelTypeDefinitionsMap) {\n const applicableDefinitionIds = modelTypeDefinitionsMap.get(instance.typeId);\n if (!applicableDefinitionIds?.has(customFieldDefinition.id)) {\n return;\n }\n }\n\n if (customFields[customFieldDefinition.name] === undefined) {\n customFields[customFieldDefinition.name] = null;\n }\n });\n }\n });\n instance.customFields = customFields;\n (options.attributesToRemove as string[] | undefined)?.forEach?.((attribute) => {\n delete instance.dataValues?.[attribute];\n // if raw:\n delete instance?.[attribute];\n });\n // sequelize will think customFields changed also in 'find', so we need to mark it as unchanged\n if (hookType === 'afterFind') {\n // changed() could be undefined, i.e in raw: true\n instance?.changed?.('customFields', false);\n }\n });\n};\n\nexport default enrichResults;\n"],"mappings":"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"}
|