@autofleet/sadot 1.1.7 → 1.1.9-beta-cfcc9e5b.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/dist/api/v1/definition/index.cjs +1 -1
  2. package/dist/api/v1/definition/index.cjs.map +1 -1
  3. package/dist/api/v1/definition/index.js +1 -1
  4. package/dist/api/v1/definition/index.js.map +1 -1
  5. package/dist/api/v1/definition/validations.cjs +1 -1
  6. package/dist/api/v1/definition/validations.cjs.map +1 -1
  7. package/dist/api/v1/definition/validations.js +1 -1
  8. package/dist/api/v1/definition/validations.js.map +1 -1
  9. package/dist/hooks/enrich.cjs +1 -1
  10. package/dist/hooks/enrich.cjs.map +1 -1
  11. package/dist/hooks/enrich.js +1 -1
  12. package/dist/hooks/enrich.js.map +1 -1
  13. package/dist/index.cjs +1 -1
  14. package/dist/index.cjs.map +1 -1
  15. package/dist/index.js +1 -1
  16. package/dist/index.js.map +1 -1
  17. package/dist/models/CustomFieldDefinition.cjs +1 -1
  18. package/dist/models/CustomFieldDefinition.cjs.map +1 -1
  19. package/dist/models/CustomFieldDefinition.d.cts +3 -0
  20. package/dist/models/CustomFieldDefinition.d.ts +3 -0
  21. package/dist/models/CustomFieldDefinition.js +1 -1
  22. package/dist/models/CustomFieldDefinition.js.map +1 -1
  23. package/dist/models/CustomFieldEntries.cjs +1 -1
  24. package/dist/models/CustomFieldEntries.cjs.map +1 -1
  25. package/dist/models/CustomFieldEntries.js +1 -1
  26. package/dist/models/CustomFieldEntries.js.map +1 -1
  27. package/dist/models/CustomFieldModelTypeMap.cjs +2 -0
  28. package/dist/models/CustomFieldModelTypeMap.cjs.map +1 -0
  29. package/dist/models/CustomFieldModelTypeMap.d.cts +15 -0
  30. package/dist/models/CustomFieldModelTypeMap.d.ts +15 -0
  31. package/dist/models/CustomFieldModelTypeMap.js +2 -0
  32. package/dist/models/CustomFieldModelTypeMap.js.map +1 -0
  33. package/dist/models/CustomFieldValue.cjs +1 -1
  34. package/dist/models/CustomFieldValue.cjs.map +1 -1
  35. package/dist/models/CustomFieldValue.js +1 -1
  36. package/dist/models/CustomFieldValue.js.map +1 -1
  37. package/dist/models/CustomValidator.cjs +1 -1
  38. package/dist/models/CustomValidator.cjs.map +1 -1
  39. package/dist/models/CustomValidator.js +1 -1
  40. package/dist/models/CustomValidator.js.map +1 -1
  41. package/dist/models/index.cjs +1 -1
  42. package/dist/models/index.cjs.map +1 -1
  43. package/dist/models/index.d.cts +1 -0
  44. package/dist/models/index.d.ts +1 -0
  45. package/dist/models/index.js +1 -1
  46. package/dist/models/index.js.map +1 -1
  47. package/dist/models/tests/AssociatedTestModel.cjs +1 -1
  48. package/dist/models/tests/AssociatedTestModel.cjs.map +1 -1
  49. package/dist/models/tests/AssociatedTestModel.js +1 -1
  50. package/dist/models/tests/AssociatedTestModel.js.map +1 -1
  51. package/dist/models/tests/TestModel.cjs +1 -1
  52. package/dist/models/tests/TestModel.cjs.map +1 -1
  53. package/dist/models/tests/TestModel.js +1 -1
  54. package/dist/models/tests/TestModel.js.map +1 -1
  55. package/dist/models/tests/contextAwareModels/ContextAwareTestModel.cjs +1 -1
  56. package/dist/models/tests/contextAwareModels/ContextAwareTestModel.cjs.map +1 -1
  57. package/dist/models/tests/contextAwareModels/ContextAwareTestModel.js +1 -1
  58. package/dist/models/tests/contextAwareModels/ContextAwareTestModel.js.map +1 -1
  59. package/dist/models/tests/contextAwareModels/ContextTestModel.cjs +1 -1
  60. package/dist/models/tests/contextAwareModels/ContextTestModel.cjs.map +1 -1
  61. package/dist/models/tests/contextAwareModels/ContextTestModel.js +1 -1
  62. package/dist/models/tests/contextAwareModels/ContextTestModel.js.map +1 -1
  63. package/dist/repository/definition.cjs +1 -1
  64. package/dist/repository/definition.cjs.map +1 -1
  65. package/dist/repository/definition.js +1 -1
  66. package/dist/repository/definition.js.map +1 -1
  67. package/dist/types/index.d.cts +3 -0
  68. package/dist/types/index.d.ts +3 -0
  69. package/dist/utils/init.cjs +1 -1
  70. package/dist/utils/init.cjs.map +1 -1
  71. package/dist/utils/init.js +1 -1
  72. package/dist/utils/init.js.map +1 -1
  73. package/package.json +22 -22
  74. /package/dist/_virtual/{_@oxc-project_runtime@0.103.0 → _@oxc-project_runtime@0.97.0}/helpers/decorate.cjs +0 -0
  75. /package/dist/_virtual/{_@oxc-project_runtime@0.103.0 → _@oxc-project_runtime@0.97.0}/helpers/decorate.js +0 -0
  76. /package/dist/_virtual/{_@oxc-project_runtime@0.103.0 → _@oxc-project_runtime@0.97.0}/helpers/decorateMetadata.cjs +0 -0
  77. /package/dist/_virtual/{_@oxc-project_runtime@0.103.0 → _@oxc-project_runtime@0.97.0}/helpers/decorateMetadata.js +0 -0
@@ -1,2 +1,2 @@
1
- const e=require(`../../../_virtual/rolldown_runtime.cjs`),t=require(`../../../utils/logger/index.cjs`),n=require(`../../../repository/definition.cjs`),r=require(`../errors.cjs`),i=require(`./validations.cjs`);let a=require(`@autofleet/errors`),o=require(`@autofleet/node-common`);const s=(0,o.Router)({logger:t.default}),c=`CustomFieldDefinition`,l=e=>e.replace(/(^\w|-\w)/g,e=>e.replace(/-/,``).toUpperCase());s.post(`/`,async(e,a)=>{let{modelName:o}=e.params,s=l(o);try{let t=await i.validateCustomFieldDefinitionCreation(e.body),r=await n.create({...t,modelType:s});return a.status(201).json(r)}catch(e){return t.default.error(`Failed to create custom field definition`,e),r.default(e,a,{logger:t.default,message:`Error in create ${c} request`})}}),s.get(`/:customFieldDefinitionId`,async(e,i)=>{let{customFieldDefinitionId:o}=e.params;try{let e=await n.findById(o);if(!e)throw new a.ResourceNotFoundError;return i.json(e)}catch(e){return t.default.error(`Failed to fetch custom field definition`,e),r.default(e,i,{logger:t.default,message:`Error in get ${c} request`})}}),s.get(`/`,async(e,i)=>{let{params:{modelName:a},query:{entityIds:o}}=e,s=l(a);try{let e={modelType:s,...o&&o.length>0&&{entityId:o}},t=await n.findAll(e,{withDisabled:!0});return i.json(t)}catch(e){return t.default.error(`Failed to fetch custom field definitions`,e),r.default(e,i,{logger:t.default,message:`Error in get all ${c} request`})}}),s.patch(`/:customFieldDefinitionId`,async(e,o)=>{let{customFieldDefinitionId:s,modelName:u}=e.params,d=l(u);try{let t=await i.validateCustomFieldDefinitionUpdate(e.body);if(!await n.findByWhere({id:s,modelType:d}))throw new a.ResourceNotFoundError;let r=await n.update(s,{...t,modelType:d});return o.status(200).json(r)}catch(e){return t.default.error(`Failed to patch custom field definition`,e),r.default(e,o,{logger:t.default,message:`Error in update ${c} request`})}});var u=s;exports.default=u;
1
+ const e=require(`../../../_virtual/rolldown_runtime.cjs`),t=require(`../../../utils/logger/index.cjs`),n=require(`../../../repository/definition.cjs`),r=require(`../errors.cjs`),i=require(`./validations.cjs`);let a=require(`@autofleet/errors`),o=require(`@autofleet/node-common`);const s=(0,o.Router)({logger:t.default}),c=`CustomFieldDefinition`,l=e=>e.replace(/(^\w|-\w)/g,e=>e.replace(/-/,``).toUpperCase());s.post(`/`,async(e,a)=>{let{modelName:o}=e.params,s=l(o);try{let t=await i.validateCustomFieldDefinitionCreation(e.body),r=await n.create({...t,modelType:s});return a.status(201).json(r)}catch(e){return t.default.error(`Failed to create custom field definition`,e),r.default(e,a,{logger:t.default,message:`Error in create ${c} request`})}}),s.get(`/:customFieldDefinitionId`,async(e,i)=>{let{customFieldDefinitionId:o}=e.params;try{let e=await n.findById(o);if(!e)throw new a.ResourceNotFoundError;return i.json(e)}catch(e){return t.default.error(`Failed to fetch custom field definition`,e),r.default(e,i,{logger:t.default,message:`Error in get ${c} request`})}}),s.get(`/`,async(e,i)=>{let{params:{modelName:a},query:{entityIds:o,modelTypeId:s}}=e,u=l(a);try{if(s){let e=await n.findByModelTypeId(s,{withDisabled:!0,modelType:u});return i.json(e)}let e={modelType:u,...o&&o.length>0&&{entityId:o}},t=await n.findAll(e,{withDisabled:!0,enrichWithModelTypeIds:!0});return i.json(t)}catch(e){return t.default.error(`Failed to fetch custom field definitions`,e),r.default(e,i,{logger:t.default,message:`Error in get all ${c} request`})}}),s.patch(`/:customFieldDefinitionId`,async(e,o)=>{let{customFieldDefinitionId:s,modelName:u}=e.params,d=l(u);try{let t=await i.validateCustomFieldDefinitionUpdate(e.body);if(!await n.findByWhere({id:s,modelType:d}))throw new a.ResourceNotFoundError;let r=await n.update(s,{...t,modelType:d});return o.status(200).json(r)}catch(e){return t.default.error(`Failed to patch custom field definition`,e),r.default(e,o,{logger:t.default,message:`Error in update ${c} request`})}});var u=s;exports.default=u;
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["router: ReturnType<typeof Router>","validatedPayload: CreateCustomFieldDefinition","validateCustomFieldDefinitionCreation","handleError","ResourceNotFoundError","validatedPayload: UpdateCustomFieldDefinition","validateCustomFieldDefinitionUpdate"],"sources":["../../../../src/api/v1/definition/index.ts"],"sourcesContent":["import { ResourceNotFoundError } from '@autofleet/errors';\nimport { Router } from '@autofleet/node-common';\nimport handleError from '../errors';\nimport * as DefinitionRepo from '../../../repository/definition';\nimport type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../../../types/definition';\nimport { validateCustomFieldDefinitionCreation, validateCustomFieldDefinitionUpdate } from './validations';\nimport logger from '../../../utils/logger';\nimport type { CustomFieldDefinition } from '../../../models';\n\nconst router: ReturnType<typeof Router> = Router({ logger });\nconst ENTITY = 'CustomFieldDefinition';\n\nconst toPascalCase = (str: string): string => str.replace(/(^\\w|-\\w)/g, subStr => subStr.replace(/-/, '').toUpperCase());\n\n/**\n * Create\n */\nrouter.post<{ modelName: string; }>('/', async (req, res) => {\n const { modelName } = req.params;\n const modelType = toPascalCase(modelName);\n try {\n const validatedPayload: CreateCustomFieldDefinition = await validateCustomFieldDefinitionCreation(req.body);\n\n const customFieldDefinition = await DefinitionRepo.create({\n ...validatedPayload,\n modelType,\n });\n return res.status(201).json(customFieldDefinition);\n } catch (err) {\n logger.error('Failed to create custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in create ${ENTITY} request` });\n }\n});\n\n/**\n * Get by id\n */\nrouter.get<{ modelName: string; customFieldDefinitionId: string; }, CustomFieldDefinition>('/:customFieldDefinitionId', async (req, res) => {\n const { customFieldDefinitionId } = req.params;\n try {\n const customFieldDefinition = await DefinitionRepo.findById(customFieldDefinitionId);\n\n if (!customFieldDefinition) {\n throw new ResourceNotFoundError();\n }\n\n return res.json(customFieldDefinition);\n } catch (err) {\n logger.error('Failed to fetch custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in get ${ENTITY} request` });\n }\n});\n\n/**\n * Get all\n */\nrouter.get<{ modelName: string; }, CustomFieldDefinition[], never, { entityIds?: string[]; }>('/', async (req, res) => {\n const { params: { modelName }, query: { entityIds } } = req;\n\n const modelType = toPascalCase(modelName);\n try {\n const where = {\n modelType,\n ...(entityIds && entityIds.length > 0 && { entityId: entityIds }),\n };\n const customFieldDefinitions = await DefinitionRepo.findAll(where, { withDisabled: true });\n return res.json(customFieldDefinitions);\n } catch (err) {\n logger.error('Failed to fetch custom field definitions', err);\n return handleError(err as Error, res, { logger, message: `Error in get all ${ENTITY} request` });\n }\n});\n\n/**\n * Update\n */\nrouter.patch<{ modelName: string; customFieldDefinitionId: string; }, CustomFieldDefinition>('/:customFieldDefinitionId', async (req, res) => {\n const { customFieldDefinitionId, modelName } = req.params;\n const modelType = toPascalCase(modelName);\n try {\n const validatedPayload: UpdateCustomFieldDefinition = await validateCustomFieldDefinitionUpdate(req.body);\n\n const customFieldDefinition = await DefinitionRepo.findByWhere({\n id: customFieldDefinitionId,\n modelType,\n });\n\n if (!customFieldDefinition) {\n throw new ResourceNotFoundError();\n }\n\n const updatedCustomFieldDefinition = await DefinitionRepo.update(\n customFieldDefinitionId,\n { ...validatedPayload, modelType },\n );\n\n return res.status(200).json(updatedCustomFieldDefinition);\n } catch (err) {\n logger.error('Failed to patch custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in update ${ENTITY} request` });\n }\n});\n\nexport default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A,QAA6B,EAAO,CAAE,aAAc,GAAM,CAAC,CAC1F,OAAO,EAAI,KAAK,EAAuB,OAChC,EAAK,CAEZ,OADA,EAAA,QAAO,MAAM,2CAA4C,EAAI,CACtDA,EAAAA,QAAY,EAAc,EAAK,CAAE,OAAA,EAAA,QAAQ,QAAS,oBAAoB,EAAO,UAAW,CAAC,GAElG,CAKF,EAAO,MAAsF,4BAA6B,MAAO,EAAK,IAAQ,CAC5I,GAAM,CAAE,0BAAyB,aAAc,EAAI,OAC7C,EAAY,EAAa,EAAU,CACzC,GAAI,CACF,IAAME,EAAgD,MAAMC,EAAAA,oCAAoC,EAAI,KAAK,CAOzG,GAAI,CAL0B,MAAA,EAAA,YAAiC,CAC7D,GAAI,EACJ,YACD,CAAC,CAGA,MAAM,IAAIF,EAAAA,sBAGZ,IAAM,EAA+B,MAAA,EAAA,OACnC,EACA,CAAE,GAAG,EAAkB,YAAW,CACnC,CAED,OAAO,EAAI,OAAO,IAAI,CAAC,KAAK,EAA6B,OAClD,EAAK,CAEZ,OADA,EAAA,QAAO,MAAM,0CAA2C,EAAI,CACrDD,EAAAA,QAAY,EAAc,EAAK,CAAE,OAAA,EAAA,QAAQ,QAAS,mBAAmB,EAAO,UAAW,CAAC,GAEjG,CAEF,IAAA,EAAe"}
1
+ {"version":3,"file":"index.cjs","names":["router: ReturnType<typeof Router>","validatedPayload: CreateCustomFieldDefinition","validateCustomFieldDefinitionCreation","handleError","ResourceNotFoundError","customFieldDefinitions","validatedPayload: UpdateCustomFieldDefinition","validateCustomFieldDefinitionUpdate"],"sources":["../../../../src/api/v1/definition/index.ts"],"sourcesContent":["import { ResourceNotFoundError } from '@autofleet/errors';\nimport { Router } from '@autofleet/node-common';\nimport handleError from '../errors';\nimport * as DefinitionRepo from '../../../repository/definition';\nimport type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../../../types/definition';\nimport { validateCustomFieldDefinitionCreation, validateCustomFieldDefinitionUpdate } from './validations';\nimport logger from '../../../utils/logger';\nimport type { CustomFieldDefinition } from '../../../models';\n\nconst router: ReturnType<typeof Router> = Router({ logger });\nconst ENTITY = 'CustomFieldDefinition';\n\nconst toPascalCase = (str: string): string => str.replace(/(^\\w|-\\w)/g, subStr => subStr.replace(/-/, '').toUpperCase());\n\n/**\n * Create\n */\nrouter.post<{ modelName: string; }>('/', async (req, res) => {\n const { modelName } = req.params;\n const modelType = toPascalCase(modelName);\n try {\n const validatedPayload: CreateCustomFieldDefinition = await validateCustomFieldDefinitionCreation(req.body);\n\n const customFieldDefinition = await DefinitionRepo.create({\n ...validatedPayload,\n modelType,\n });\n return res.status(201).json(customFieldDefinition);\n } catch (err) {\n logger.error('Failed to create custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in create ${ENTITY} request` });\n }\n});\n\n/**\n * Get by id\n */\nrouter.get<{ modelName: string; customFieldDefinitionId: string; }, CustomFieldDefinition>('/:customFieldDefinitionId', async (req, res) => {\n const { customFieldDefinitionId } = req.params;\n try {\n const customFieldDefinition = await DefinitionRepo.findById(customFieldDefinitionId);\n\n if (!customFieldDefinition) {\n throw new ResourceNotFoundError();\n }\n\n return res.json(customFieldDefinition);\n } catch (err) {\n logger.error('Failed to fetch custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in get ${ENTITY} request` });\n }\n});\n\n/**\n * Get all\n */\nrouter.get<{ modelName: string; }, CustomFieldDefinition[], never, { entityIds?: string[]; modelTypeId?: string; }>('/', async (req, res) => {\n const { params: { modelName }, query: { entityIds, modelTypeId } } = req;\n\n const modelType = toPascalCase(modelName);\n try {\n // If modelTypeId is provided, get definitions applicable to that specific type instance\n if (modelTypeId) {\n const customFieldDefinitions = await DefinitionRepo.findByModelTypeId(modelTypeId, { withDisabled: true, modelType });\n return res.json(customFieldDefinitions);\n }\n\n const where = {\n modelType,\n ...(entityIds && entityIds.length > 0 && { entityId: entityIds }),\n };\n const customFieldDefinitions = await DefinitionRepo.findAll(where, { withDisabled: true, enrichWithModelTypeIds: true });\n return res.json(customFieldDefinitions);\n } catch (err) {\n logger.error('Failed to fetch custom field definitions', err);\n return handleError(err as Error, res, { logger, message: `Error in get all ${ENTITY} request` });\n }\n});\n\n/**\n * Update\n */\nrouter.patch<{ modelName: string; customFieldDefinitionId: string; }, CustomFieldDefinition>('/:customFieldDefinitionId', async (req, res) => {\n const { customFieldDefinitionId, modelName } = req.params;\n const modelType = toPascalCase(modelName);\n try {\n const validatedPayload: UpdateCustomFieldDefinition = await validateCustomFieldDefinitionUpdate(req.body);\n\n const customFieldDefinition = await DefinitionRepo.findByWhere({\n id: customFieldDefinitionId,\n modelType,\n });\n\n if (!customFieldDefinition) {\n throw new ResourceNotFoundError();\n }\n\n const updatedCustomFieldDefinition = await DefinitionRepo.update(\n customFieldDefinitionId,\n { ...validatedPayload, modelType },\n );\n\n return res.status(200).json(updatedCustomFieldDefinition);\n } catch (err) {\n logger.error('Failed to patch custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in update ${ENTITY} request` });\n }\n});\n\nexport default router;\n"],"mappings":"wRASA,MAAMA,GAAAA,EAAAA,EAAAA,QAA2C,CAAE,OAAA,EAAA,QAAQ,CAAC,CACtD,EAAS,wBAET,EAAgB,GAAwB,EAAI,QAAQ,aAAc,GAAU,EAAO,QAAQ,IAAK,GAAG,CAAC,aAAa,CAAC,CAKxH,EAAO,KAA6B,IAAK,MAAO,EAAK,IAAQ,CAC3D,GAAM,CAAE,aAAc,EAAI,OACpB,EAAY,EAAa,EAAU,CACzC,GAAI,CACF,IAAMC,EAAgD,MAAMC,EAAAA,sCAAsC,EAAI,KAAK,CAErG,EAAwB,MAAA,EAAA,OAA4B,CACxD,GAAG,EACH,YACD,CAAC,CACF,OAAO,EAAI,OAAO,IAAI,CAAC,KAAK,EAAsB,OAC3C,EAAK,CAEZ,OADA,EAAA,QAAO,MAAM,2CAA4C,EAAI,CACtDC,EAAAA,QAAY,EAAc,EAAK,CAAE,OAAA,EAAA,QAAQ,QAAS,mBAAmB,EAAO,UAAW,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EACJ,YACD,CAAC,CAGA,MAAM,IAAIH,EAAAA,sBAGZ,IAAM,EAA+B,MAAA,EAAA,OACnC,EACA,CAAE,GAAG,EAAkB,YAAW,CACnC,CAED,OAAO,EAAI,OAAO,IAAI,CAAC,KAAK,EAA6B,OAClD,EAAK,CAEZ,OADA,EAAA,QAAO,MAAM,0CAA2C,EAAI,CACrDD,EAAAA,QAAY,EAAc,EAAK,CAAE,OAAA,EAAA,QAAQ,QAAS,mBAAmB,EAAO,UAAW,CAAC,GAEjG,CAEF,IAAA,EAAe"}
@@ -1,2 +1,2 @@
1
- import e from"../../../utils/logger/index.js";import{create as t,findAll as n,findById as r,findByWhere as i,update as a}from"../../../repository/definition.js";import o from"../errors.js";import{validateCustomFieldDefinitionCreation as s,validateCustomFieldDefinitionUpdate as c}from"./validations.js";import{ResourceNotFoundError as l}from"@autofleet/errors";import{Router as u}from"@autofleet/node-common";const d=u({logger:e}),f=`CustomFieldDefinition`,p=e=>e.replace(/(^\w|-\w)/g,e=>e.replace(/-/,``).toUpperCase());d.post(`/`,async(n,r)=>{let{modelName:i}=n.params,a=p(i);try{let e=await t({...await s(n.body),modelType:a});return r.status(201).json(e)}catch(t){return e.error(`Failed to create custom field definition`,t),o(t,r,{logger:e,message:`Error in create ${f} request`})}}),d.get(`/:customFieldDefinitionId`,async(t,n)=>{let{customFieldDefinitionId:i}=t.params;try{let e=await r(i);if(!e)throw new l;return n.json(e)}catch(t){return e.error(`Failed to fetch custom field definition`,t),o(t,n,{logger:e,message:`Error in get ${f} request`})}}),d.get(`/`,async(t,r)=>{let{params:{modelName:i},query:{entityIds:a}}=t,s=p(i);try{let e=await n({modelType:s,...a&&a.length>0&&{entityId:a}},{withDisabled:!0});return r.json(e)}catch(t){return e.error(`Failed to fetch custom field definitions`,t),o(t,r,{logger:e,message:`Error in get all ${f} request`})}}),d.patch(`/:customFieldDefinitionId`,async(t,n)=>{let{customFieldDefinitionId:r,modelName:s}=t.params,u=p(s);try{let e=await c(t.body);if(!await i({id:r,modelType:u}))throw new l;let o=await a(r,{...e,modelType:u});return n.status(200).json(o)}catch(t){return e.error(`Failed to patch custom field definition`,t),o(t,n,{logger:e,message:`Error in update ${f} request`})}});var m=d;export{m as default};
1
+ import e from"../../../utils/logger/index.js";import{create as t,findAll as n,findById as r,findByModelTypeId as i,findByWhere as a,update as o}from"../../../repository/definition.js";import s from"../errors.js";import{validateCustomFieldDefinitionCreation as c,validateCustomFieldDefinitionUpdate as l}from"./validations.js";import{ResourceNotFoundError as u}from"@autofleet/errors";import{Router as d}from"@autofleet/node-common";const f=d({logger:e}),p=`CustomFieldDefinition`,m=e=>e.replace(/(^\w|-\w)/g,e=>e.replace(/-/,``).toUpperCase());f.post(`/`,async(n,r)=>{let{modelName:i}=n.params,a=m(i);try{let e=await t({...await c(n.body),modelType:a});return r.status(201).json(e)}catch(t){return e.error(`Failed to create custom field definition`,t),s(t,r,{logger:e,message:`Error in create ${p} request`})}}),f.get(`/:customFieldDefinitionId`,async(t,n)=>{let{customFieldDefinitionId:i}=t.params;try{let e=await r(i);if(!e)throw new u;return n.json(e)}catch(t){return e.error(`Failed to fetch custom field definition`,t),s(t,n,{logger:e,message:`Error in get ${p} request`})}}),f.get(`/`,async(t,r)=>{let{params:{modelName:a},query:{entityIds:o,modelTypeId:c}}=t,l=m(a);try{if(c){let e=await i(c,{withDisabled:!0,modelType:l});return r.json(e)}let e=await n({modelType:l,...o&&o.length>0&&{entityId:o}},{withDisabled:!0,enrichWithModelTypeIds:!0});return r.json(e)}catch(t){return e.error(`Failed to fetch custom field definitions`,t),s(t,r,{logger:e,message:`Error in get all ${p} request`})}}),f.patch(`/:customFieldDefinitionId`,async(t,n)=>{let{customFieldDefinitionId:r,modelName:i}=t.params,c=m(i);try{let e=await l(t.body);if(!await a({id:r,modelType:c}))throw new u;let i=await o(r,{...e,modelType:c});return n.status(200).json(i)}catch(t){return e.error(`Failed to patch custom field definition`,t),s(t,n,{logger:e,message:`Error in update ${p} request`})}});var h=f;export{h as default};
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["router: ReturnType<typeof Router>","validatedPayload: CreateCustomFieldDefinition","DefinitionRepo.create","handleError","DefinitionRepo.findById","DefinitionRepo.findAll","validatedPayload: UpdateCustomFieldDefinition","DefinitionRepo.findByWhere","DefinitionRepo.update"],"sources":["../../../../src/api/v1/definition/index.ts"],"sourcesContent":["import { ResourceNotFoundError } from '@autofleet/errors';\nimport { Router } from '@autofleet/node-common';\nimport handleError from '../errors';\nimport * as DefinitionRepo from '../../../repository/definition';\nimport type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../../../types/definition';\nimport { validateCustomFieldDefinitionCreation, validateCustomFieldDefinitionUpdate } from './validations';\nimport logger from '../../../utils/logger';\nimport type { CustomFieldDefinition } from '../../../models';\n\nconst router: ReturnType<typeof Router> = Router({ logger });\nconst ENTITY = 'CustomFieldDefinition';\n\nconst toPascalCase = (str: string): string => str.replace(/(^\\w|-\\w)/g, subStr => subStr.replace(/-/, '').toUpperCase());\n\n/**\n * Create\n */\nrouter.post<{ modelName: string; }>('/', async (req, res) => {\n const { modelName } = req.params;\n const modelType = toPascalCase(modelName);\n try {\n const validatedPayload: CreateCustomFieldDefinition = await validateCustomFieldDefinitionCreation(req.body);\n\n const customFieldDefinition = await DefinitionRepo.create({\n ...validatedPayload,\n modelType,\n });\n return res.status(201).json(customFieldDefinition);\n } catch (err) {\n logger.error('Failed to create custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in create ${ENTITY} request` });\n }\n});\n\n/**\n * Get by id\n */\nrouter.get<{ modelName: string; customFieldDefinitionId: string; }, CustomFieldDefinition>('/:customFieldDefinitionId', async (req, res) => {\n const { customFieldDefinitionId } = req.params;\n try {\n const customFieldDefinition = await DefinitionRepo.findById(customFieldDefinitionId);\n\n if (!customFieldDefinition) {\n throw new ResourceNotFoundError();\n }\n\n return res.json(customFieldDefinition);\n } catch (err) {\n logger.error('Failed to fetch custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in get ${ENTITY} request` });\n }\n});\n\n/**\n * Get all\n */\nrouter.get<{ modelName: string; }, CustomFieldDefinition[], never, { entityIds?: string[]; }>('/', async (req, res) => {\n const { params: { modelName }, query: { entityIds } } = req;\n\n const modelType = toPascalCase(modelName);\n try {\n const where = {\n modelType,\n ...(entityIds && entityIds.length > 0 && { entityId: entityIds }),\n };\n const customFieldDefinitions = await DefinitionRepo.findAll(where, { withDisabled: true });\n return res.json(customFieldDefinitions);\n } catch (err) {\n logger.error('Failed to fetch custom field definitions', err);\n return handleError(err as Error, res, { logger, message: `Error in get all ${ENTITY} request` });\n }\n});\n\n/**\n * Update\n */\nrouter.patch<{ modelName: string; customFieldDefinitionId: string; }, CustomFieldDefinition>('/:customFieldDefinitionId', async (req, res) => {\n const { customFieldDefinitionId, modelName } = req.params;\n const modelType = toPascalCase(modelName);\n try {\n const validatedPayload: UpdateCustomFieldDefinition = await validateCustomFieldDefinitionUpdate(req.body);\n\n const customFieldDefinition = await DefinitionRepo.findByWhere({\n id: customFieldDefinitionId,\n modelType,\n });\n\n if (!customFieldDefinition) {\n throw new ResourceNotFoundError();\n }\n\n const updatedCustomFieldDefinition = await DefinitionRepo.update(\n customFieldDefinitionId,\n { ...validatedPayload, modelType },\n );\n\n return res.status(200).json(updatedCustomFieldDefinition);\n } catch (err) {\n logger.error('Failed to patch custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in update ${ENTITY} request` });\n }\n});\n\nexport default router;\n"],"mappings":"yZASA,MAAMA,EAAoC,EAAO,CAAE,OAAA,EAAQ,CAAC,CACtD,EAAS,wBAET,EAAgB,GAAwB,EAAI,QAAQ,aAAc,GAAU,EAAO,QAAQ,IAAK,GAAG,CAAC,aAAa,CAAC,CAKxH,EAAO,KAA6B,IAAK,MAAO,EAAK,IAAQ,CAC3D,GAAM,CAAE,aAAc,EAAI,OACpB,EAAY,EAAa,EAAU,CACzC,GAAI,CAGF,IAAM,EAA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7D,GAAI,EACJ,YACD,CAAC,CAGA,MAAM,IAAI,EAGZ,IAAM,EAA+B,MAAMC,EACzC,EACA,CAAE,GAAG,EAAkB,YAAW,CACnC,CAED,OAAO,EAAI,OAAO,IAAI,CAAC,KAAK,EAA6B,OAClD,EAAK,CAEZ,OADA,EAAO,MAAM,0CAA2C,EAAI,CACrDL,EAAY,EAAc,EAAK,CAAE,OAAA,EAAQ,QAAS,mBAAmB,EAAO,UAAW,CAAC,GAEjG,CAEF,IAAA,EAAe"}
1
+ {"version":3,"file":"index.js","names":["router: ReturnType<typeof Router>","validatedPayload: CreateCustomFieldDefinition","DefinitionRepo.create","handleError","DefinitionRepo.findById","customFieldDefinitions","DefinitionRepo.findByModelTypeId","DefinitionRepo.findAll","validatedPayload: UpdateCustomFieldDefinition","DefinitionRepo.findByWhere","DefinitionRepo.update"],"sources":["../../../../src/api/v1/definition/index.ts"],"sourcesContent":["import { ResourceNotFoundError } from '@autofleet/errors';\nimport { Router } from '@autofleet/node-common';\nimport handleError from '../errors';\nimport * as DefinitionRepo from '../../../repository/definition';\nimport type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../../../types/definition';\nimport { validateCustomFieldDefinitionCreation, validateCustomFieldDefinitionUpdate } from './validations';\nimport logger from '../../../utils/logger';\nimport type { CustomFieldDefinition } from '../../../models';\n\nconst router: ReturnType<typeof Router> = Router({ logger });\nconst ENTITY = 'CustomFieldDefinition';\n\nconst toPascalCase = (str: string): string => str.replace(/(^\\w|-\\w)/g, subStr => subStr.replace(/-/, '').toUpperCase());\n\n/**\n * Create\n */\nrouter.post<{ modelName: string; }>('/', async (req, res) => {\n const { modelName } = req.params;\n const modelType = toPascalCase(modelName);\n try {\n const validatedPayload: CreateCustomFieldDefinition = await validateCustomFieldDefinitionCreation(req.body);\n\n const customFieldDefinition = await DefinitionRepo.create({\n ...validatedPayload,\n modelType,\n });\n return res.status(201).json(customFieldDefinition);\n } catch (err) {\n logger.error('Failed to create custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in create ${ENTITY} request` });\n }\n});\n\n/**\n * Get by id\n */\nrouter.get<{ modelName: string; customFieldDefinitionId: string; }, CustomFieldDefinition>('/:customFieldDefinitionId', async (req, res) => {\n const { customFieldDefinitionId } = req.params;\n try {\n const customFieldDefinition = await DefinitionRepo.findById(customFieldDefinitionId);\n\n if (!customFieldDefinition) {\n throw new ResourceNotFoundError();\n }\n\n return res.json(customFieldDefinition);\n } catch (err) {\n logger.error('Failed to fetch custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in get ${ENTITY} request` });\n }\n});\n\n/**\n * Get all\n */\nrouter.get<{ modelName: string; }, CustomFieldDefinition[], never, { entityIds?: string[]; modelTypeId?: string; }>('/', async (req, res) => {\n const { params: { modelName }, query: { entityIds, modelTypeId } } = req;\n\n const modelType = toPascalCase(modelName);\n try {\n // If modelTypeId is provided, get definitions applicable to that specific type instance\n if (modelTypeId) {\n const customFieldDefinitions = await DefinitionRepo.findByModelTypeId(modelTypeId, { withDisabled: true, modelType });\n return res.json(customFieldDefinitions);\n }\n\n const where = {\n modelType,\n ...(entityIds && entityIds.length > 0 && { entityId: entityIds }),\n };\n const customFieldDefinitions = await DefinitionRepo.findAll(where, { withDisabled: true, enrichWithModelTypeIds: true });\n return res.json(customFieldDefinitions);\n } catch (err) {\n logger.error('Failed to fetch custom field definitions', err);\n return handleError(err as Error, res, { logger, message: `Error in get all ${ENTITY} request` });\n }\n});\n\n/**\n * Update\n */\nrouter.patch<{ modelName: string; customFieldDefinitionId: string; }, CustomFieldDefinition>('/:customFieldDefinitionId', async (req, res) => {\n const { customFieldDefinitionId, modelName } = req.params;\n const modelType = toPascalCase(modelName);\n try {\n const validatedPayload: UpdateCustomFieldDefinition = await validateCustomFieldDefinitionUpdate(req.body);\n\n const customFieldDefinition = await DefinitionRepo.findByWhere({\n id: customFieldDefinitionId,\n modelType,\n });\n\n if (!customFieldDefinition) {\n throw new ResourceNotFoundError();\n }\n\n const updatedCustomFieldDefinition = await DefinitionRepo.update(\n customFieldDefinitionId,\n { ...validatedPayload, modelType },\n );\n\n return res.status(200).json(updatedCustomFieldDefinition);\n } catch (err) {\n logger.error('Failed to patch custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in update ${ENTITY} request` });\n }\n});\n\nexport default router;\n"],"mappings":"gbASA,MAAMA,EAAoC,EAAO,CAAE,OAAA,EAAQ,CAAC,CACtD,EAAS,wBAET,EAAgB,GAAwB,EAAI,QAAQ,aAAc,GAAU,EAAO,QAAQ,IAAK,GAAG,CAAC,aAAa,CAAC,CAKxH,EAAO,KAA6B,IAAK,MAAO,EAAK,IAAQ,CAC3D,GAAM,CAAE,aAAc,EAAI,OACpB,EAAY,EAAa,EAAU,CACzC,GAAI,CAGF,IAAM,EAAwB,MAAME,EAAsB,CACxD,GAHoD,MAAM,EAAsC,EAAI,KAAK,CAIzG,YACD,CAAC,CACF,OAAO,EAAI,OAAO,IAAI,CAAC,KAAK,EAAsB,OAC3C,EAAK,CAEZ,OADA,EAAO,MAAM,2CAA4C,EAAI,CACtDC,EAAY,EAAc,EAAK,CAAE,OAAA,EAAQ,QAAS,mBAAmB,EAAO,UAAW,CAAC,GAEjG,CAKF,EAAO,IAAoF,4BAA6B,MAAO,EAAK,IAAQ,CAC1I,GAAM,CAAE,2BAA4B,EAAI,OACxC,GAAI,CACF,IAAM,EAAwB,MAAMC,EAAwB,EAAwB,CAEpF,GAAI,CAAC,EACH,MAAM,IAAI,EAGZ,OAAO,EAAI,KAAK,EAAsB,OAC/B,EAAK,CAEZ,OADA,EAAO,MAAM,0CAA2C,EAAI,CACrDD,EAAY,EAAc,EAAK,CAAE,OAAA,EAAQ,QAAS,gBAAgB,EAAO,UAAW,CAAC,GAE9F,CAKF,EAAO,IAA6G,IAAK,MAAO,EAAK,IAAQ,CAC3I,GAAM,CAAE,OAAQ,CAAE,aAAa,MAAO,CAAE,YAAW,gBAAkB,EAE/D,EAAY,EAAa,EAAU,CACzC,GAAI,CAEF,GAAI,EAAa,CACf,IAAME,EAAyB,MAAMC,EAAiC,EAAa,CAAE,aAAc,GAAM,YAAW,CAAC,CACrH,OAAO,EAAI,KAAKD,EAAuB,CAOzC,IAAM,EAAyB,MAAME,EAJvB,CACZ,YACA,GAAI,GAAa,EAAU,OAAS,GAAK,CAAE,SAAU,EAAW,CACjE,CACkE,CAAE,aAAc,GAAM,uBAAwB,GAAM,CAAC,CACxH,OAAO,EAAI,KAAK,EAAuB,OAChC,EAAK,CAEZ,OADA,EAAO,MAAM,2CAA4C,EAAI,CACtDJ,EAAY,EAAc,EAAK,CAAE,OAAA,EAAQ,QAAS,oBAAoB,EAAO,UAAW,CAAC,GAElG,CAKF,EAAO,MAAsF,4BAA6B,MAAO,EAAK,IAAQ,CAC5I,GAAM,CAAE,0BAAyB,aAAc,EAAI,OAC7C,EAAY,EAAa,EAAU,CACzC,GAAI,CACF,IAAMK,EAAgD,MAAM,EAAoC,EAAI,KAAK,CAOzG,GAAI,CAL0B,MAAMC,EAA2B,CAC7D,GAAI,EACJ,YACD,CAAC,CAGA,MAAM,IAAI,EAGZ,IAAM,EAA+B,MAAMC,EACzC,EACA,CAAE,GAAG,EAAkB,YAAW,CACnC,CAED,OAAO,EAAI,OAAO,IAAI,CAAC,KAAK,EAA6B,OAClD,EAAK,CAEZ,OADA,EAAO,MAAM,0CAA2C,EAAI,CACrDP,EAAY,EAAc,EAAK,CAAE,OAAA,EAAQ,QAAS,mBAAmB,EAAO,UAAW,CAAC,GAEjG,CAEF,IAAA,EAAe"}
@@ -1,2 +1,2 @@
1
- const e=require(`../../../_virtual/rolldown_runtime.cjs`),t=require(`../../../utils/constants/index.cjs`);let n=require(`joi`);n=e.__toESM(n);const r=n.default.object({name:n.default.string().required(),type:n.default.string(),size:n.default.string(),addedBy:n.default.string().uuid()}),i=n.default.object({value:n.default.string().required(),color:n.default.string().required()}),a=n.default.when(`fieldType`,{is:t.CustomFieldDefinitionType.SELECT,then:n.default.array().required().items(n.default.string()).min(1).unique(),otherwise:n.default.when(`fieldType`,{is:t.CustomFieldDefinitionType.STATUS,then:n.default.array().required().items(i).min(1).unique(`value`),otherwise:n.default.forbidden()})}),o=n.default.when(`fieldType`,{switch:[{is:t.CustomFieldDefinitionType.BOOLEAN,then:n.default.boolean().allow(null)},{is:t.CustomFieldDefinitionType.DATE,then:n.default.date().allow(null)},{is:t.CustomFieldDefinitionType.DATETIME,then:n.default.date().allow(null)},{is:t.CustomFieldDefinitionType.FILE,then:n.default.array().items(r).allow(null)},{is:t.CustomFieldDefinitionType.IMAGE,then:n.default.array().items(n.default.string().uri()).allow(null)},{is:t.CustomFieldDefinitionType.NUMBER,then:n.default.number().allow(null)},{is:t.CustomFieldDefinitionType.SELECT,then:n.default.string().allow(null)},{is:t.CustomFieldDefinitionType.STATUS,then:n.default.string().allow(null)},{is:t.CustomFieldDefinitionType.TEXT,then:n.default.string().allow(null)}]}),s=n.default.object({name:n.default.string().required(),displayName:n.default.string().required(),validation:a,defaultValue:o,fieldType:n.default.string().valid(...Object.values(t.CustomFieldDefinitionType)).required(),entityId:n.default.string().guid().required(),entityType:n.default.string().required(),description:n.default.string(),required:n.default.boolean(),disabled:n.default.boolean(),blockEditingFromUI:n.default.boolean()}).oxor(`required`,`blockEditingFromUI`,{isPresent:e=>e===!0}),c=n.default.object({displayName:n.default.string(),validation:a,defaultValue:o,fieldType:n.default.string().valid(...Object.values(t.CustomFieldDefinitionType)),description:n.default.string().allow(null),required:n.default.boolean(),disabled:n.default.boolean(),blockEditingFromUI:n.default.boolean()}).oxor(`required`,`blockEditingFromUI`,{isPresent:e=>e===!0}),l=e=>s.validateAsync(e,{abortEarly:!1}),u=e=>c.validateAsync(e,{abortEarly:!1});exports.validateCustomFieldDefinitionCreation=l,exports.validateCustomFieldDefinitionUpdate=u;
1
+ const e=require(`../../../_virtual/rolldown_runtime.cjs`),t=require(`../../../utils/constants/index.cjs`);let n=require(`joi`);n=e.__toESM(n);const r=n.default.object({name:n.default.string().required(),type:n.default.string(),size:n.default.string(),addedBy:n.default.string().uuid()}),i=n.default.object({value:n.default.string().required(),color:n.default.string().required()}),a=n.default.when(`fieldType`,{is:t.CustomFieldDefinitionType.SELECT,then:n.default.array().required().items(n.default.string()).min(1).unique(),otherwise:n.default.when(`fieldType`,{is:t.CustomFieldDefinitionType.STATUS,then:n.default.array().required().items(i).min(1).unique(`value`),otherwise:n.default.forbidden()})}),o=n.default.when(`fieldType`,{switch:[{is:t.CustomFieldDefinitionType.BOOLEAN,then:n.default.boolean().allow(null)},{is:t.CustomFieldDefinitionType.DATE,then:n.default.date().allow(null)},{is:t.CustomFieldDefinitionType.DATETIME,then:n.default.date().allow(null)},{is:t.CustomFieldDefinitionType.FILE,then:n.default.array().items(r).allow(null)},{is:t.CustomFieldDefinitionType.IMAGE,then:n.default.array().items(n.default.string().uri()).allow(null)},{is:t.CustomFieldDefinitionType.NUMBER,then:n.default.number().allow(null)},{is:t.CustomFieldDefinitionType.SELECT,then:n.default.string().allow(null)},{is:t.CustomFieldDefinitionType.STATUS,then:n.default.string().allow(null)},{is:t.CustomFieldDefinitionType.TEXT,then:n.default.string().allow(null)}]}),s=n.default.object({name:n.default.string().required(),displayName:n.default.string().required(),validation:a,defaultValue:o,fieldType:n.default.string().valid(...Object.values(t.CustomFieldDefinitionType)).required(),entityId:n.default.string().guid().required(),entityType:n.default.string().required(),description:n.default.string(),required:n.default.boolean(),disabled:n.default.boolean(),blockEditingFromUI:n.default.boolean(),modelTypeIds:n.default.array().items(n.default.string().guid())}).oxor(`required`,`blockEditingFromUI`,{isPresent:e=>e===!0}),c=n.default.object({displayName:n.default.string(),validation:a,defaultValue:o,fieldType:n.default.string().valid(...Object.values(t.CustomFieldDefinitionType)),description:n.default.string().allow(null),required:n.default.boolean(),disabled:n.default.boolean(),blockEditingFromUI:n.default.boolean(),modelTypeIds:n.default.array().items(n.default.string().guid())}).oxor(`required`,`blockEditingFromUI`,{isPresent:e=>e===!0}),l=e=>s.validateAsync(e,{abortEarly:!1}),u=e=>c.validateAsync(e,{abortEarly:!1});exports.validateCustomFieldDefinitionCreation=l,exports.validateCustomFieldDefinitionUpdate=u;
2
2
  //# sourceMappingURL=validations.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"validations.cjs","names":["Joi","CustomFieldDefinitionType"],"sources":["../../../../src/api/v1/definition/validations.ts"],"sourcesContent":["import Joi from 'joi';\nimport { CustomFieldDefinitionType } from '../../../utils/constants';\nimport type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../../../types/definition';\n\nconst FileValidationSchema = Joi.object({\n name: Joi.string().required(),\n type: Joi.string(),\n size: Joi.string(),\n addedBy: Joi.string().uuid(),\n});\nconst statusValidationObject = Joi.object({\n value: Joi.string().required(),\n color: Joi.string().required(),\n});\n/**\n * Schema for the validation of custom field definition\n * The only custom validation is for\n * {@link CustomFieldDefinitionType.SELECT SELECT}\n * and\n * {@link CustomFieldDefinitionType.STATUS STATUS}\n * field types.\n * The rest of the field types are validated by Joi\n */\nconst ValidationSchema = Joi.when('fieldType', {\n is: CustomFieldDefinitionType.SELECT,\n then: Joi.array().required().items(Joi.string()).min(1).unique(),\n otherwise: Joi.when('fieldType', {\n is: CustomFieldDefinitionType.STATUS,\n then: Joi.array().required().items(statusValidationObject).min(1).unique('value'),\n otherwise: Joi.forbidden(),\n }),\n});\n\nconst DefaultValueSchema = Joi.when('fieldType', {\n switch: [\n { is: CustomFieldDefinitionType.BOOLEAN, then: Joi.boolean().allow(null) },\n { is: CustomFieldDefinitionType.DATE, then: Joi.date().allow(null) },\n { is: CustomFieldDefinitionType.DATETIME, then: Joi.date().allow(null) },\n { is: CustomFieldDefinitionType.FILE, then: Joi.array().items(FileValidationSchema).allow(null) },\n { is: CustomFieldDefinitionType.IMAGE, then: Joi.array().items(Joi.string().uri()).allow(null) },\n { is: CustomFieldDefinitionType.NUMBER, then: Joi.number().allow(null) },\n { is: CustomFieldDefinitionType.SELECT, then: Joi.string().allow(null) },\n { is: CustomFieldDefinitionType.STATUS, then: Joi.string().allow(null) },\n { is: CustomFieldDefinitionType.TEXT, then: Joi.string().allow(null) },\n ],\n});\n\nconst CustomFieldDefinitionCreationSchema = Joi.object({\n name: Joi.string().required(),\n displayName: Joi.string().required(),\n validation: ValidationSchema,\n defaultValue: DefaultValueSchema,\n fieldType: Joi.string().valid(...Object.values(CustomFieldDefinitionType)).required(),\n entityId: Joi.string().guid().required(),\n entityType: Joi.string().required(),\n description: Joi.string(),\n required: Joi.boolean(),\n disabled: Joi.boolean(),\n blockEditingFromUI: Joi.boolean(),\n}).oxor('required', 'blockEditingFromUI', { isPresent: value => value === true });\n\nconst CustomFieldDefinitionUpdateSchema = Joi.object({\n displayName: Joi.string(),\n validation: ValidationSchema,\n defaultValue: DefaultValueSchema,\n fieldType: Joi.string().valid(...Object.values(CustomFieldDefinitionType)),\n description: Joi.string().allow(null),\n required: Joi.boolean(),\n disabled: Joi.boolean(),\n blockEditingFromUI: Joi.boolean(),\n}).oxor('required', 'blockEditingFromUI', { isPresent: value => value === true });\n\nexport const validateCustomFieldDefinitionCreation = (payload: unknown): Promise<CreateCustomFieldDefinition> =>\n CustomFieldDefinitionCreationSchema.validateAsync(payload, { abortEarly: false });\n\nexport const validateCustomFieldDefinitionUpdate = (payload: unknown): Promise<UpdateCustomFieldDefinition> =>\n CustomFieldDefinitionUpdateSchema.validateAsync(payload, { abortEarly: false });\n"],"mappings":"8IAIA,MAAM,EAAuBA,EAAAA,QAAI,OAAO,CACtC,KAAMA,EAAAA,QAAI,QAAQ,CAAC,UAAU,CAC7B,KAAMA,EAAAA,QAAI,QAAQ,CAClB,KAAMA,EAAAA,QAAI,QAAQ,CAClB,QAASA,EAAAA,QAAI,QAAQ,CAAC,MAAM,CAC7B,CAAC,CACI,EAAyBA,EAAAA,QAAI,OAAO,CACxC,MAAOA,EAAAA,QAAI,QAAQ,CAAC,UAAU,CAC9B,MAAOA,EAAAA,QAAI,QAAQ,CAAC,UAAU,CAC/B,CAAC,CAUI,EAAmBA,EAAAA,Q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{"version":3,"file":"validations.cjs","names":["Joi","CustomFieldDefinitionType"],"sources":["../../../../src/api/v1/definition/validations.ts"],"sourcesContent":["import Joi from 'joi';\nimport { CustomFieldDefinitionType } from '../../../utils/constants';\nimport type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../../../types/definition';\n\nconst FileValidationSchema = Joi.object({\n name: Joi.string().required(),\n type: Joi.string(),\n size: Joi.string(),\n addedBy: Joi.string().uuid(),\n});\nconst statusValidationObject = Joi.object({\n value: Joi.string().required(),\n color: Joi.string().required(),\n});\n/**\n * Schema for the validation of custom field definition\n * The only custom validation is for\n * {@link CustomFieldDefinitionType.SELECT SELECT}\n * and\n * {@link CustomFieldDefinitionType.STATUS STATUS}\n * field types.\n * The rest of the field types are validated by Joi\n */\nconst ValidationSchema = Joi.when('fieldType', {\n is: CustomFieldDefinitionType.SELECT,\n then: Joi.array().required().items(Joi.string()).min(1).unique(),\n otherwise: Joi.when('fieldType', {\n is: CustomFieldDefinitionType.STATUS,\n then: Joi.array().required().items(statusValidationObject).min(1).unique('value'),\n otherwise: Joi.forbidden(),\n }),\n});\n\nconst DefaultValueSchema = Joi.when('fieldType', {\n switch: [\n { is: CustomFieldDefinitionType.BOOLEAN, then: Joi.boolean().allow(null) },\n { is: CustomFieldDefinitionType.DATE, then: Joi.date().allow(null) },\n { is: CustomFieldDefinitionType.DATETIME, then: Joi.date().allow(null) },\n { is: CustomFieldDefinitionType.FILE, then: Joi.array().items(FileValidationSchema).allow(null) },\n { is: CustomFieldDefinitionType.IMAGE, then: Joi.array().items(Joi.string().uri()).allow(null) },\n { is: CustomFieldDefinitionType.NUMBER, then: Joi.number().allow(null) },\n { is: CustomFieldDefinitionType.SELECT, then: Joi.string().allow(null) },\n { is: CustomFieldDefinitionType.STATUS, then: Joi.string().allow(null) },\n { is: CustomFieldDefinitionType.TEXT, then: Joi.string().allow(null) },\n ],\n});\n\nconst CustomFieldDefinitionCreationSchema = Joi.object({\n name: Joi.string().required(),\n displayName: Joi.string().required(),\n validation: ValidationSchema,\n defaultValue: DefaultValueSchema,\n fieldType: Joi.string().valid(...Object.values(CustomFieldDefinitionType)).required(),\n entityId: Joi.string().guid().required(),\n entityType: Joi.string().required(),\n description: Joi.string(),\n required: Joi.boolean(),\n disabled: Joi.boolean(),\n blockEditingFromUI: Joi.boolean(),\n modelTypeIds: Joi.array().items(Joi.string().guid()),\n}).oxor('required', 'blockEditingFromUI', { isPresent: value => value === true });\n\nconst CustomFieldDefinitionUpdateSchema = Joi.object({\n displayName: Joi.string(),\n validation: ValidationSchema,\n defaultValue: DefaultValueSchema,\n fieldType: Joi.string().valid(...Object.values(CustomFieldDefinitionType)),\n description: Joi.string().allow(null),\n required: Joi.boolean(),\n disabled: Joi.boolean(),\n blockEditingFromUI: Joi.boolean(),\n modelTypeIds: Joi.array().items(Joi.string().guid()),\n}).oxor('required', 'blockEditingFromUI', { isPresent: value => value === true });\n\nexport const validateCustomFieldDefinitionCreation = (payload: unknown): Promise<CreateCustomFieldDefinition> =>\n CustomFieldDefinitionCreationSchema.validateAsync(payload, { abortEarly: false });\n\nexport const validateCustomFieldDefinitionUpdate = (payload: unknown): Promise<UpdateCustomFieldDefinition> =>\n CustomFieldDefinitionUpdateSchema.validateAsync(payload, { abortEarly: false });\n"],"mappings":"8IAIA,MAAM,EAAuBA,EAAAA,QAAI,OAAO,CACtC,KAAMA,EAAAA,QAAI,QAAQ,CAAC,UAAU,CAC7B,KAAMA,EAAAA,QAAI,QAAQ,CAClB,KAAMA,EAAAA,QAAI,QAAQ,CAClB,QAASA,EAAAA,QAAI,QAAQ,CAAC,MAAM,CAC7B,CAAC,CACI,EAAyBA,EAAAA,QAAI,OAAO,CACxC,MAAOA,EAAAA,QAAI,QAAQ,CAAC,UAAU,CAC9B,MAAOA,EAAAA,QAAI,QAAQ,CAAC,UAAU,CAC/B,CAAC,CAUI,EAAmBA,EAAAA,QAAI,KAAK,YAAa,CAC7C,GAAIC,EAAAA,0BAA0B,OAC9B,KAAMD,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cAAc,EAAS,CAAE,WAAY,GAAO,CAAC,CAEtE,EAAuC,GAClD,EAAkC,cAAc,EAAS,CAAE,WAAY,GAAO,CAAC"}
@@ -1,2 +1,2 @@
1
- import{CustomFieldDefinitionType as e}from"../../../utils/constants/index.js";import t from"joi";const n=t.object({name:t.string().required(),type:t.string(),size:t.string(),addedBy:t.string().uuid()}),r=t.object({value:t.string().required(),color:t.string().required()}),i=t.when(`fieldType`,{is:e.SELECT,then:t.array().required().items(t.string()).min(1).unique(),otherwise:t.when(`fieldType`,{is:e.STATUS,then:t.array().required().items(r).min(1).unique(`value`),otherwise:t.forbidden()})}),a=t.when(`fieldType`,{switch:[{is:e.BOOLEAN,then:t.boolean().allow(null)},{is:e.DATE,then:t.date().allow(null)},{is:e.DATETIME,then:t.date().allow(null)},{is:e.FILE,then:t.array().items(n).allow(null)},{is:e.IMAGE,then:t.array().items(t.string().uri()).allow(null)},{is:e.NUMBER,then:t.number().allow(null)},{is:e.SELECT,then:t.string().allow(null)},{is:e.STATUS,then:t.string().allow(null)},{is:e.TEXT,then:t.string().allow(null)}]}),o=t.object({name:t.string().required(),displayName:t.string().required(),validation:i,defaultValue:a,fieldType:t.string().valid(...Object.values(e)).required(),entityId:t.string().guid().required(),entityType:t.string().required(),description:t.string(),required:t.boolean(),disabled:t.boolean(),blockEditingFromUI:t.boolean()}).oxor(`required`,`blockEditingFromUI`,{isPresent:e=>e===!0}),s=t.object({displayName:t.string(),validation:i,defaultValue:a,fieldType:t.string().valid(...Object.values(e)),description:t.string().allow(null),required:t.boolean(),disabled:t.boolean(),blockEditingFromUI:t.boolean()}).oxor(`required`,`blockEditingFromUI`,{isPresent:e=>e===!0}),c=e=>o.validateAsync(e,{abortEarly:!1}),l=e=>s.validateAsync(e,{abortEarly:!1});export{c as validateCustomFieldDefinitionCreation,l as validateCustomFieldDefinitionUpdate};
1
+ import{CustomFieldDefinitionType as e}from"../../../utils/constants/index.js";import t from"joi";const n=t.object({name:t.string().required(),type:t.string(),size:t.string(),addedBy:t.string().uuid()}),r=t.object({value:t.string().required(),color:t.string().required()}),i=t.when(`fieldType`,{is:e.SELECT,then:t.array().required().items(t.string()).min(1).unique(),otherwise:t.when(`fieldType`,{is:e.STATUS,then:t.array().required().items(r).min(1).unique(`value`),otherwise:t.forbidden()})}),a=t.when(`fieldType`,{switch:[{is:e.BOOLEAN,then:t.boolean().allow(null)},{is:e.DATE,then:t.date().allow(null)},{is:e.DATETIME,then:t.date().allow(null)},{is:e.FILE,then:t.array().items(n).allow(null)},{is:e.IMAGE,then:t.array().items(t.string().uri()).allow(null)},{is:e.NUMBER,then:t.number().allow(null)},{is:e.SELECT,then:t.string().allow(null)},{is:e.STATUS,then:t.string().allow(null)},{is:e.TEXT,then:t.string().allow(null)}]}),o=t.object({name:t.string().required(),displayName:t.string().required(),validation:i,defaultValue:a,fieldType:t.string().valid(...Object.values(e)).required(),entityId:t.string().guid().required(),entityType:t.string().required(),description:t.string(),required:t.boolean(),disabled:t.boolean(),blockEditingFromUI:t.boolean(),modelTypeIds:t.array().items(t.string().guid())}).oxor(`required`,`blockEditingFromUI`,{isPresent:e=>e===!0}),s=t.object({displayName:t.string(),validation:i,defaultValue:a,fieldType:t.string().valid(...Object.values(e)),description:t.string().allow(null),required:t.boolean(),disabled:t.boolean(),blockEditingFromUI:t.boolean(),modelTypeIds:t.array().items(t.string().guid())}).oxor(`required`,`blockEditingFromUI`,{isPresent:e=>e===!0}),c=e=>o.validateAsync(e,{abortEarly:!1}),l=e=>s.validateAsync(e,{abortEarly:!1});export{c as validateCustomFieldDefinitionCreation,l as validateCustomFieldDefinitionUpdate};
2
2
  //# sourceMappingURL=validations.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"validations.js","names":[],"sources":["../../../../src/api/v1/definition/validations.ts"],"sourcesContent":["import Joi from 'joi';\nimport { CustomFieldDefinitionType } from '../../../utils/constants';\nimport type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../../../types/definition';\n\nconst FileValidationSchema = Joi.object({\n name: Joi.string().required(),\n type: Joi.string(),\n size: Joi.string(),\n addedBy: Joi.string().uuid(),\n});\nconst statusValidationObject = Joi.object({\n value: Joi.string().required(),\n color: Joi.string().required(),\n});\n/**\n * Schema for the validation of custom field definition\n * The only custom validation is for\n * {@link CustomFieldDefinitionType.SELECT SELECT}\n * and\n * {@link CustomFieldDefinitionType.STATUS STATUS}\n * field types.\n * The rest of the field types are validated by Joi\n */\nconst ValidationSchema = Joi.when('fieldType', {\n is: CustomFieldDefinitionType.SELECT,\n then: Joi.array().required().items(Joi.string()).min(1).unique(),\n otherwise: Joi.when('fieldType', {\n is: CustomFieldDefinitionType.STATUS,\n then: Joi.array().required().items(statusValidationObject).min(1).unique('value'),\n otherwise: Joi.forbidden(),\n }),\n});\n\nconst DefaultValueSchema = Joi.when('fieldType', {\n switch: [\n { is: CustomFieldDefinitionType.BOOLEAN, then: Joi.boolean().allow(null) },\n { is: CustomFieldDefinitionType.DATE, then: Joi.date().allow(null) },\n { is: CustomFieldDefinitionType.DATETIME, then: Joi.date().allow(null) },\n { is: CustomFieldDefinitionType.FILE, then: Joi.array().items(FileValidationSchema).allow(null) },\n { is: CustomFieldDefinitionType.IMAGE, then: Joi.array().items(Joi.string().uri()).allow(null) },\n { is: CustomFieldDefinitionType.NUMBER, then: Joi.number().allow(null) },\n { is: CustomFieldDefinitionType.SELECT, then: Joi.string().allow(null) },\n { is: CustomFieldDefinitionType.STATUS, then: Joi.string().allow(null) },\n { is: CustomFieldDefinitionType.TEXT, then: Joi.string().allow(null) },\n ],\n});\n\nconst CustomFieldDefinitionCreationSchema = Joi.object({\n name: Joi.string().required(),\n displayName: Joi.string().required(),\n validation: ValidationSchema,\n defaultValue: DefaultValueSchema,\n fieldType: Joi.string().valid(...Object.values(CustomFieldDefinitionType)).required(),\n entityId: Joi.string().guid().required(),\n entityType: Joi.string().required(),\n description: Joi.string(),\n required: Joi.boolean(),\n disabled: Joi.boolean(),\n blockEditingFromUI: Joi.boolean(),\n}).oxor('required', 'blockEditingFromUI', { isPresent: value => value === true });\n\nconst CustomFieldDefinitionUpdateSchema = Joi.object({\n displayName: Joi.string(),\n validation: ValidationSchema,\n defaultValue: DefaultValueSchema,\n fieldType: Joi.string().valid(...Object.values(CustomFieldDefinitionType)),\n description: Joi.string().allow(null),\n required: Joi.boolean(),\n disabled: Joi.boolean(),\n blockEditingFromUI: Joi.boolean(),\n}).oxor('required', 'blockEditingFromUI', { isPresent: value => value === true });\n\nexport const validateCustomFieldDefinitionCreation = (payload: unknown): Promise<CreateCustomFieldDefinition> =>\n CustomFieldDefinitionCreationSchema.validateAsync(payload, { abortEarly: false });\n\nexport const validateCustomFieldDefinitionUpdate = (payload: unknown): Promise<UpdateCustomFieldDefinition> =>\n CustomFieldDefinitionUpdateSchema.validateAsync(payload, { abortEarly: false });\n"],"mappings":"iGAIA,MAAM,EAAuB,EAAI,OAAO,CACtC,KAAM,EAAI,QAAQ,CAAC,UAAU,CAC7B,KAAM,EAAI,QAAQ,CAClB,KAAM,EAAI,QAAQ,CAClB,QAAS,EAAI,QAAQ,CAAC,MAAM,CAC7B,CAAC,CACI,EAAyB,EAAI,OAAO,CACxC,MAAO,EAAI,QAAQ,CAAC,UAAU,CAC9B,MAAO,EAAI,QAAQ,CAAC,UAAU,CAC/B,CAAC,CAUI,EAAmB,EAAI,KAAK,YAAa,CAC7C,GAAI,EAA0B,OAC9B,KAAM,EAAI,OAAO,CAAC,UAAU,CAAC,MAAM,EAAI,QAAQ,CAAC,CAAC,IAAI,EAAE,CAAC,QAAQ,CAChE,UAAW,EAAI,KAAK,YAAa,CAC/B,GAAI,EAA0B,OAC9B,KAAM,EAAI,OAAO,CAAC,UAAU,CAAC,MAAM,EAAuB,CAAC,IAAI,EAAE,CAAC,OAAO,QAAQ,CACjF,UAAW,EAAI,WAAW,CAC3B,CAAC,CACH,CAAC,CAEI,EAAqB,EAAI,KAAK,YAAa,CAC/C,OAAQ,CACN,CAAE,GAAI,EAA0B,QAAS,KAAM,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zB,WAAY,EACZ,aAAc,EACd,UAAW,EAAI,QAAQ,CAAC,MAAM,GAAG,OAAO,OAAO,EAA0B,CAAC,CAC1E,YAAa,EAAI,QAAQ,CAAC,MAAM,KAAK,CACrC,SAAU,EAAI,SAAS,CACvB,SAAU,EAAI,SAAS,CACvB,mBAAoB,EAAI,SAAS,CAClC,CAAC,CAAC,KAAK,WAAY,qBAAsB,CAAE,UAAW,GAAS,IAAU,GAAM,CAAC,CAEpE,EAAyC,GACpD,EAAoC,cAAc,EAAS,CAAE,WAAY,GAAO,CAAC,CAEtE,EAAuC,GAClD,EAAkC,cAAc,EAAS,CAAE,WAAY,GAAO,CAAC"}
1
+ {"version":3,"file":"validations.js","names":[],"sources":["../../../../src/api/v1/definition/validations.ts"],"sourcesContent":["import Joi from 'joi';\nimport { CustomFieldDefinitionType } from '../../../utils/constants';\nimport type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../../../types/definition';\n\nconst FileValidationSchema = Joi.object({\n name: Joi.string().required(),\n type: Joi.string(),\n size: Joi.string(),\n addedBy: Joi.string().uuid(),\n});\nconst statusValidationObject = Joi.object({\n value: Joi.string().required(),\n color: Joi.string().required(),\n});\n/**\n * Schema for the validation of custom field definition\n * The only custom validation is for\n * {@link CustomFieldDefinitionType.SELECT SELECT}\n * and\n * {@link CustomFieldDefinitionType.STATUS STATUS}\n * field types.\n * The rest of the field types are validated by Joi\n */\nconst ValidationSchema = Joi.when('fieldType', {\n is: CustomFieldDefinitionType.SELECT,\n then: Joi.array().required().items(Joi.string()).min(1).unique(),\n otherwise: Joi.when('fieldType', {\n is: CustomFieldDefinitionType.STATUS,\n then: Joi.array().required().items(statusValidationObject).min(1).unique('value'),\n otherwise: Joi.forbidden(),\n }),\n});\n\nconst DefaultValueSchema = Joi.when('fieldType', {\n switch: [\n { is: CustomFieldDefinitionType.BOOLEAN, then: Joi.boolean().allow(null) },\n { is: CustomFieldDefinitionType.DATE, then: Joi.date().allow(null) },\n { is: CustomFieldDefinitionType.DATETIME, then: Joi.date().allow(null) },\n { is: CustomFieldDefinitionType.FILE, then: Joi.array().items(FileValidationSchema).allow(null) },\n { is: CustomFieldDefinitionType.IMAGE, then: Joi.array().items(Joi.string().uri()).allow(null) },\n { is: CustomFieldDefinitionType.NUMBER, then: Joi.number().allow(null) },\n { is: CustomFieldDefinitionType.SELECT, then: Joi.string().allow(null) },\n { is: CustomFieldDefinitionType.STATUS, then: Joi.string().allow(null) },\n { is: CustomFieldDefinitionType.TEXT, then: Joi.string().allow(null) },\n ],\n});\n\nconst CustomFieldDefinitionCreationSchema = Joi.object({\n name: Joi.string().required(),\n displayName: Joi.string().required(),\n validation: ValidationSchema,\n defaultValue: DefaultValueSchema,\n fieldType: Joi.string().valid(...Object.values(CustomFieldDefinitionType)).required(),\n entityId: Joi.string().guid().required(),\n entityType: Joi.string().required(),\n description: Joi.string(),\n required: Joi.boolean(),\n disabled: Joi.boolean(),\n blockEditingFromUI: Joi.boolean(),\n modelTypeIds: Joi.array().items(Joi.string().guid()),\n}).oxor('required', 'blockEditingFromUI', { isPresent: value => value === true });\n\nconst CustomFieldDefinitionUpdateSchema = Joi.object({\n displayName: Joi.string(),\n validation: ValidationSchema,\n defaultValue: DefaultValueSchema,\n fieldType: Joi.string().valid(...Object.values(CustomFieldDefinitionType)),\n description: Joi.string().allow(null),\n required: Joi.boolean(),\n disabled: Joi.boolean(),\n blockEditingFromUI: Joi.boolean(),\n modelTypeIds: Joi.array().items(Joi.string().guid()),\n}).oxor('required', 'blockEditingFromUI', { isPresent: value => value === true });\n\nexport const validateCustomFieldDefinitionCreation = (payload: unknown): Promise<CreateCustomFieldDefinition> =>\n CustomFieldDefinitionCreationSchema.validateAsync(payload, { abortEarly: false });\n\nexport const validateCustomFieldDefinitionUpdate = (payload: unknown): Promise<UpdateCustomFieldDefinition> =>\n CustomFieldDefinitionUpdateSchema.validateAsync(payload, { abortEarly: false });\n"],"mappings":"iGAIA,MAAM,EAAuB,EAAI,OAAO,CACtC,KA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 @@
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})=>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)),_||(_=e.findByEntityIds(t,h,{transaction:f.transaction,modelOptions:l,attributes:i}),f.transaction?.definitionCache?.set(v,_));let y=await _;if(y.length===0){p.forEach(e=>{e.customFields={}});return}l?.include&&l.useEntityIdFromInclude&&l.include(m).forEach(({model:e})=>{y.forEach(t=>{let n=t[`${e.name}.entityId`];g[n]=[]})});let b=y.reduce((e,t)=>({...e,[t.id]:t}),{});y.forEach(e=>{g[e.entityId].push(e)});let x=p.map(e=>e.id),[S,C]=await Promise.all([o({instancesIds:x,options:f,sadotOptions:u}),a({instancesIds:x,options:f,sadotOptions:u})]);p.forEach(e=>{let{id:t}=e,r=S[t],i=r?s(r,b):{},a=u.useCustomFieldsEntries?C[t]:i;n.forEach(t=>{let n=g[e[t]];n&&n.length>0&&n.forEach(e=>{a[e.name]===void 0&&(a[e.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;
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(!_)if(u.hasTypeId&&p.length>0&&p[0].typeId){let n=[...new Set(p.map(e=>e.typeId).filter(Boolean))];y=new Map,n.forEach(e=>y.set(e,new Set));let r=(await Promise.all(n.map(async n=>{let r=await e.findByModelTypeId(n,{withDisabled:!1,entityIds:h,modelType:t,modelOptions:l});return r.forEach(e=>y.get(n).add(e.id)),r}))).flat(),i=new Map;r.forEach(e=>{i.set(e.id,e)}),_=Promise.resolve(Array.from(i.values()))}else _=e.findByEntityIds(t,h,{transaction:f.transaction,modelOptions:l,attributes:i}),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
2
  //# sourceMappingURL=enrich.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"enrich.cjs","names":["applyScopeToInstance","cacheKey: 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'> = { useCustomFieldsEntries: 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 if (!customFieldDefinitionsPromise) {\n // Fetch from database (either first time in this transaction or no transaction)\n customFieldDefinitionsPromise = DefinitionRepo.findByEntityIds(\n modelType,\n uniqueIdentifiers,\n { transaction: options.transaction, modelOptions, attributes: CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL },\n );\n\n options.transaction?.definitionCache?.set(cacheKey!, customFieldDefinitionsPromise);\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) => {\n const entityId = cfd[`${model!.name}.entityId` as keyof CustomFieldDefinition];\n identifierCustomFieldDefinitionsMapping[entityId] = [];\n });\n });\n }\n\n const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({\n ...map,\n [definition.id]: definition,\n }), {});\n\n customFieldDefinitions.forEach((cfd) => {\n identifierCustomFieldDefinitionsMapping[cfd.entityId].push(cfd);\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 (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":"sKAUM,EAA6C,CACjD,KACA,OACA,WACA,YACA,cACA,aACA,aACA,YACA,WACA,WACA,eACD,CAgBY,EAAoC,MAAO,CACtD,eACA,UACA,kBAKwD,CACxD,GAAI,CAAC,EAAa,uBAChB,MAAO,EAAE,CAGX,IAAM,EAAqB,MAAA,EAAA,sBACzB,EACA,GAAW,EAAE,CACd,CAEK,EAAiC,OAAO,YAAY,EAAmB,IAAK,GAAoB,CACpG,GAAM,CAAE,UAAS,gBAAiB,GAAiB,YAAc,EAAE,CAC9D,KAGL,MAAO,CAAC,EAAS,EAAa,EAC9B,CAAC,OAAO,GAAK,IAAM,IAAA,GAAU,CAAC,CAMhC,OAJA,EAAa,QAAS,GAAe,CACnC,EAA+B,KAAgB,EAAE,EACjD,CAEK,GAGI,EAA2B,MAAO,CAC7C,eACA,UACA,kBAMI,EAAa,uBACR,EAAE,EAGe,MAAA,EAAA,qBACxB,EACA,GAAW,EAAE,CACd,EAGwB,QAA4C,E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BAGxC,EAAa,QAAQ,EAAY,CAAC,SAAS,CAAE,WAAY,CACvD,EAAuB,QAAS,GAAQ,CACtC,IAAM,EAAW,EAAI,GAAG,EAAO,KAAK,YACpC,EAAwC,GAAY,EAAE,EACtD,EACF,CAGJ,IAAM,EAAiB,EAAuB,QAAQ,EAAK,KAAgB,CACzE,GAAG,GACF,EAAW,IAAK,EAClB,EAAG,EAAE,CAAC,CAEP,EAAuB,QAAS,GAAQ,CACtC,EAAwC,EAAI,UAAU,KAAK,EAAI,EAC/D,CAGF,IAAM,EAAe,EAAU,IAAI,GAAK,EAAE,GAAY,CAGhD,CAAC,EAAuB,GAAkC,MAAM,QAAQ,IAAI,CAChF,EAAyB,CACvB,eACA,UACA,eACD,CAAC,CACF,EAAkC,CAChC,eACA,UACA,eACD,CAAC,CACH,CAAC,CAGF,EAAU,QAAS,GAAa,CAC9B,GAAM,CAAE,MAAO,EAET,EAAiB,EAAsB,GACvC,EAA+B,EAAiB,EAAsB,EAAgB,EAAe,CAAG,EAAE,CAE1G,EAAe,EAAa,uBAC9B,EAA+B,GAC/B,EAEJ,EAAgB,QAAS,GAAc,CAGrC,IAAM,EAA+B,EAFlB,EAAS,IAGxB,GAAgC,EAA6B,OAAS,GACxE,EAA6B,QAAS,GAA0B,CAC1D,EAAa,EAAsB,QAAU,IAAA,KAC/C,EAAa,EAAsB,MAAQ,OAE7C,EAEJ,CACF,EAAS,aAAe,EACvB,EAAQ,oBAA6C,UAAW,GAAc,CAC7E,OAAO,EAAS,aAAa,GAE7B,OAAO,IAAW,IAClB,CAEE,IAAa,aAEf,GAAU,UAAU,eAAgB,GAAM,EAE5C,EAGJ,IAAA,EAAe"}
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 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 });\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 customFieldDefinitionsPromise = Promise.resolve(Array.from(uniqueDefinitionsMap.values()));\n } else {\n customFieldDefinitionsPromise = DefinitionRepo.findByEntityIds(\n modelType,\n uniqueIdentifiers,\n { transaction: options.transaction, modelOptions, attributes: CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL },\n );\n\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":"sKAUM,EAA6C,CACjD,KACA,OACA,WACA,YACA,cACA,aACA,aACA,YACA,WACA,WACA,eACD,CAgBY,EAAoC,MAAO,CACtD,eACA,UACA,kBAKwD,CACxD,GAAI,CAAC,EAAa,uBAChB,MAAO,EAAE,CAGX,IAAM,EAAqB,MAAA,EAAA,sBACzB,EACA,GAAW,EAAE,CACd,CAEK,EAAiC,OAAO,YAAY,EAAmB,IAAK,GAAoB,CACpG,GAAM,CAAE,UAAS,gBAAiB,GAAiB,YAAc,EAAE,CAC9D,KAGL,MAAO,CAAC,EAAS,EAAa,EAC9B,CAAC,OAAO,GAAK,IAAM,IAAA,GAAU,CAAC,CAMhC,OAJA,EAAa,QAAS,GAAe,CACnC,EAA+B,KAAgB,EAAE,EACjD,CAEK,GAGI,EAA2B,MAAO,CAC7C,eACA,UACA,kBAMI,EAAa,uBACR,EAAE,EAGe,MAAA,EAAA,qBACxB,EACA,GAAW,EAAE,CACd,EAGwB,QAA4C,EAAK,IAAM,CAC9E,GAAM,CAAE,WAAY,EAGpB,MAFA,GAAI,KAAa,EAAE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KF,EAAwC,IAC1C,EAAwC,GAAe,KAAK,EAAI,EAElE,CAGF,IAAM,EAAe,EAAU,IAAI,GAAK,EAAE,GAAY,CAGhD,CAAC,EAAuB,GAAkC,MAAM,QAAQ,IAAI,CAChF,EAAyB,CACvB,eACA,UACA,eACD,CAAC,CACF,EAAkC,CAChC,eACA,UACA,eACD,CAAC,CACH,CAAC,CAGF,EAAU,QAAS,GAAa,CAC9B,GAAM,CAAE,MAAO,EAET,EAAiB,EAAsB,GACvC,EAA+B,EAAiB,EAAsB,EAAgB,EAAe,CAAG,EAAE,CAE1G,EAAe,EAAa,uBAC9B,EAA+B,GAC/B,EAEJ,EAAgB,QAAS,GAAc,CAGrC,IAAM,EAA+B,EAFlB,EAAS,IAGxB,GAAgC,EAA6B,OAAS,GACxE,EAA6B,QAAS,GAA0B,CAC1D,GAEE,CAD4B,EAAwB,IAAI,EAAS,OAAO,EAC9C,IAAI,EAAsB,GAAG,EAKzD,EAAa,EAAsB,QAAU,IAAA,KAC/C,EAAa,EAAsB,MAAQ,OAE7C,EAEJ,CACF,EAAS,aAAe,EACvB,EAAQ,oBAA6C,UAAW,GAAc,CAC7E,OAAO,EAAS,aAAa,GAE7B,OAAO,IAAW,IAClB,CAEE,IAAa,aAEf,GAAU,UAAU,eAAgB,GAAM,EAE5C,EAGJ,IAAA,EAAe"}
@@ -1,2 +1,2 @@
1
- import{findByEntityIds as e}from"../repository/definition.js";import{findValuesByModelIds as t}from"../repository/value.js";import{findEntriesByModelIds as n}from"../repository/entries.js";import r from"../utils/scopeAttributes.js";const 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(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(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}}),{});var c=(t,n,c,l={},u={useCustomFieldsEntries:!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(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)),_||(_=e(t,h,{transaction:f.transaction,modelOptions:l,attributes:i}),f.transaction?.definitionCache?.set(v,_));let y=await _;if(y.length===0){p.forEach(e=>{e.customFields={}});return}l?.include&&l.useEntityIdFromInclude&&l.include(m).forEach(({model:e})=>{y.forEach(t=>{let n=t[`${e.name}.entityId`];g[n]=[]})});let b=y.reduce((e,t)=>({...e,[t.id]:t}),{});y.forEach(e=>{g[e.entityId].push(e)});let x=p.map(e=>e.id),[S,C]=await Promise.all([o({instancesIds:x,options:f,sadotOptions:u}),a({instancesIds:x,options:f,sadotOptions:u})]);p.forEach(e=>{let{id:t}=e,r=S[t],i=r?s(r,b):{},a=u.useCustomFieldsEntries?C[t]:i;n.forEach(t=>{let n=g[e[t]];n&&n.length>0&&n.forEach(e=>{a[e.name]===void 0&&(a[e.name]=null)})}),e.customFields=a,f.attributesToRemove?.forEach?.(t=>{delete e.dataValues?.[t],delete e?.[t]}),c===`afterFind`&&e?.changed?.(`customFields`,!1)})};export{c as default};
1
+ import{findByEntityIds as e,findByModelTypeId as t}from"../repository/definition.js";import{findValuesByModelIds as n}from"../repository/value.js";import{findEntriesByModelIds as r}from"../repository/entries.js";import i from"../utils/scopeAttributes.js";const a=[`id`,`name`,`entityId`,`fieldType`,`displayName`,`validation`,`entityType`,`modelType`,`required`,`disabled`,`defaultValue`],o=async({instancesIds:e,options:t,sadotOptions:n})=>{if(!n.useCustomFieldsEntries)return{};let i=await r(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},s=async({instancesIds:e,options:t,sadotOptions:r})=>r.useCustomFieldsEntries?{}:(await n(e,t??{})).reduce((e,t)=>{let{modelId:n}=t;return e[n]??=[],e[n].push(t),e},{}),c=(e,t)=>e.reduce((e,n)=>({...e,...t[n.customFieldDefinitionId]&&{[t[n.customFieldDefinitionId].name]:n.value}}),{});var l=(n,r,l,u={},d={useCustomFieldsEntries:!1,hasTypeId:!1})=>async(f,p)=>{if(p.originalAttributes?.length>0&&!p.originalAttributes?.includes?.(`customFields`))return;let m=Array.isArray(f)?f:[f];m=m.filter(Boolean);let h=i(m,r),g=[...new Set(h)].filter(Boolean),_=g.reduce((e,t)=>({...e,[t]:[]}),{}),v,y;p.transaction&&(p.transaction.definitionCache??=new Map,y=`${n}:${g.slice().sort().join(`,`)}`,v=p.transaction.definitionCache.get(y));let b;if(!v)if(d.hasTypeId&&m.length>0&&m[0].typeId){let e=[...new Set(m.map(e=>e.typeId).filter(Boolean))];b=new Map,e.forEach(e=>b.set(e,new Set));let r=(await Promise.all(e.map(async e=>{let r=await t(e,{withDisabled:!1,entityIds:g,modelType:n,modelOptions:u});return r.forEach(t=>b.get(e).add(t.id)),r}))).flat(),i=new Map;r.forEach(e=>{i.set(e.id,e)}),v=Promise.resolve(Array.from(i.values()))}else v=e(n,g,{transaction:p.transaction,modelOptions:u,attributes:a}),p.transaction?.definitionCache?.set(y,v);let x=await v;if(x.length===0){m.forEach(e=>{e.customFields={}});return}u?.include&&u.useEntityIdFromInclude&&u.include(h).forEach(({model:e})=>{x.forEach(t=>{let n=t[e.name]?.entityId||t[`${e.name}.entityId`];n&&!_[n]&&(_[n]=[])})});let S=x.reduce((e,t)=>({...e,[t.id]:t}),{});x.forEach(e=>{let t=e.entityId;if(u?.useEntityIdFromInclude&&u.include){let n=u.include(h);for(let{model:r}of n){let n=e[r.name]?.entityId||e[`${r.name}.entityId`];if(n){t=n;break}}}_[t]&&_[t].push(e)});let C=m.map(e=>e.id),[w,T]=await Promise.all([s({instancesIds:C,options:p,sadotOptions:d}),o({instancesIds:C,options:p,sadotOptions:d})]);m.forEach(e=>{let{id:t}=e,n=w[t],i=n?c(n,S):{},a=d.useCustomFieldsEntries?T[t]:i;r.forEach(t=>{let n=_[e[t]];n&&n.length>0&&n.forEach(t=>{b&&!b.get(e.typeId)?.has(t.id)||a[t.name]===void 0&&(a[t.name]=null)})}),e.customFields=a,p.attributesToRemove?.forEach?.(t=>{delete e.dataValues?.[t],delete e?.[t]}),l===`afterFind`&&e?.changed?.(`customFields`,!1)})};export{l as default};
2
2
  //# sourceMappingURL=enrich.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"enrich.js","names":["EntriesRepo.findEntriesByModelIds","ValueRepo.findValuesByModelIds","applyScopeToInstance","cacheKey: string | undefined","DefinitionRepo.findByEntityIds"],"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'> = { useCustomFieldsEntries: 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 if (!customFieldDefinitionsPromise) {\n // Fetch from database (either first time in this transaction or no transaction)\n customFieldDefinitionsPromise = DefinitionRepo.findByEntityIds(\n modelType,\n uniqueIdentifiers,\n { transaction: options.transaction, modelOptions, attributes: CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL },\n );\n\n options.transaction?.definitionCache?.set(cacheKey!, customFieldDefinitionsPromise);\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) => {\n const entityId = cfd[`${model!.name}.entityId` as keyof CustomFieldDefinition];\n identifierCustomFieldDefinitionsMapping[entityId] = [];\n });\n });\n }\n\n const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({\n ...map,\n [definition.id]: definition,\n }), {});\n\n customFieldDefinitions.forEach((cfd) => {\n identifierCustomFieldDefinitionsMapping[cfd.entityId].push(cfd);\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 (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":"wOAUA,MAAM,EAA6C,CACjD,KACA,OACA,WACA,YACA,cACA,aACA,aACA,YACA,WACA,WACA,eACD,CAgBY,EAAoC,MAAO,CACtD,eACA,UACA,kBAKwD,CACxD,GAAI,CAAC,EAAa,uBAChB,MAAO,EAAE,CAGX,IAAM,EAAqB,MAAMA,EAC/B,EACA,GAAW,EAAE,CACd,CAEK,EAAiC,OAAO,YAAY,EAAmB,IAAK,GAAoB,CACpG,GAAM,CAAE,UAAS,gBAAiB,GAAiB,YAAc,EAAE,CAC9D,KAGL,MAAO,CAAC,EAAS,EAAa,EAC9B,CAAC,OAAO,GAAK,IAAM,IAAA,GAAU,CAAC,CAMhC,OAJA,EAAa,QAAS,GAAe,CACnC,EAA+B,KAAgB,EAAE,EACjD,CAEK,GAGI,EAA2B,MAAO,CAC7C,eACA,UACA,kBAMI,EAAa,uBACR,EAAE,EAGe,MAAMC,EAC9B,EACA,GAAW,EAAE,CACd,EAGwB,QAA4C,EAAK,IAAM,CAC9E,GAAM,CAAE,WAAY,EAGpB,MAFA,GAAI,KAAa,EAAE,CACnB,EAAI,GAAS,KAAK,EAAE,CACb,GACN,EAAE,CAAC,CAMF,GACJ,EACA,IAEqB,EAAkB,QAAQ,EAAK,KAAS,CAC3D,GAAG,EACH,GACE,EAA2B,EAAI,0BAC5B,EAAG,EAA2B,EAAI,yBAAyB,MAAO,EAAI,MAAO,CAEnF,EAAG,EAAE,CAAC,CA6IT,IAAA,GAtIE,EACA,EACA,EACA,EAA6B,EAAE,CAC/B,EAAmE,CAAE,uBAAwB,GAAO,GACj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Y,CAGhD,CAAC,EAAuB,GAAkC,MAAM,QAAQ,IAAI,CAChF,EAAyB,CACvB,eACA,UACA,eACD,CAAC,CACF,EAAkC,CAChC,eACA,UACA,eACD,CAAC,CACH,CAAC,CAGF,EAAU,QAAS,GAAa,CAC9B,GAAM,CAAE,MAAO,EAET,EAAiB,EAAsB,GACvC,EAA+B,EAAiB,EAAsB,EAAgB,EAAe,CAAG,EAAE,CAE1G,EAAe,EAAa,uBAC9B,EAA+B,GAC/B,EAEJ,EAAgB,QAAS,GAAc,CAGrC,IAAM,EAA+B,EAFlB,EAAS,IAGxB,GAAgC,EAA6B,OAAS,GACxE,EAA6B,QAAS,GAA0B,CAC1D,EAAa,EAAsB,QAAU,IAAA,KAC/C,EAAa,EAAsB,MAAQ,OAE7C,EAEJ,CACF,EAAS,aAAe,EACvB,EAAQ,oBAA6C,UAAW,GAAc,CAC7E,OAAO,EAAS,aAAa,GAE7B,OAAO,IAAW,IAClB,CAEE,IAAa,aAEf,GAAU,UAAU,eAAgB,GAAM,EAE5C"}
1
+ {"version":3,"file":"enrich.js","names":["EntriesRepo.findEntriesByModelIds","ValueRepo.findValuesByModelIds","applyScopeToInstance","cacheKey: string | undefined","modelTypeDefinitionsMap: Map<string, Set<string>> | undefined","DefinitionRepo.findByModelTypeId","DefinitionRepo.findByEntityIds"],"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 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 });\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 customFieldDefinitionsPromise = Promise.resolve(Array.from(uniqueDefinitionsMap.values()));\n } else {\n customFieldDefinitionsPromise = DefinitionRepo.findByEntityIds(\n modelType,\n uniqueIdentifiers,\n { transaction: options.transaction, modelOptions, attributes: CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL },\n );\n\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":"+PAUA,MAAM,EAA6C,CACjD,KACA,OACA,WACA,YACA,cACA,aACA,aACA,YACA,WACA,WACA,eACD,CAgBY,EAAoC,MAAO,CACtD,eACA,UACA,kBAKwD,CACxD,GAAI,CAAC,EAAa,uBAChB,MAAO,EAAE,CAGX,IAAM,EAAqB,MAAMA,EAC/B,EACA,GAAW,EAAE,CACd,CAEK,EAAiC,OAAO,YAAY,EAAmB,IAAK,GAAoB,CACpG,GAAM,CAAE,UAAS,gBAAiB,GAAiB,YAAc,EAAE,CAC9D,KAGL,MAAO,CAAC,EAAS,EAAa,EAC9B,CAAC,OAAO,GAAK,IAAM,IAAA,GAAU,CAAC,CAMhC,OAJA,EAAa,QAAS,GAAe,CACnC,EAA+B,KAAgB,EAAE,EACjD,CAEK,GAGI,EAA2B,MAAO,CAC7C,eACA,UACA,kBAMI,EAAa,uBACR,EAAE,EAGe,MAAMC,EAC9B,EACA,GAAW,EAAE,CACd,EAGwB,QAA4C,EAAK,IAAM,CAC9E,GAAM,CAAE,WAAY,EAGpB,MAFA,GAAI,KAAa,EAAE,CACnB,EAAI,GAAS,KAAK,EAAE,CACb,GACN,EAAE,CAAC,CAMF,GACJ,EACA,IAEqB,EAAkB,QAAQ,EAAK,KAAS,CAC3D,GAAG,EACH,GACE,EAA2B,EAAI,0BAC5B,EAAG,EAA2B,EAAI,yBAAyB,MAAO,EAAI,MAAO,CAEnF,EAAG,EAAE,CAAC,CAgMT,IAAA,GAzLE,EACA,EACA,EACA,EAA6B,EAAE,CAC/B,EAAiF,CAAE,uBAAwB,GAAO,UAAW,GAAO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B,EAAsB,EAAgB,EAAe,CAAG,EAAE,CAE1G,EAAe,EAAa,uBAC9B,EAA+B,GAC/B,EAEJ,EAAgB,QAAS,GAAc,CAGrC,IAAM,EAA+B,EAFlB,EAAS,IAGxB,GAAgC,EAA6B,OAAS,GACxE,EAA6B,QAAS,GAA0B,CAC1D,GAEE,CAD4B,EAAwB,IAAI,EAAS,OAAO,EAC9C,IAAI,EAAsB,GAAG,EAKzD,EAAa,EAAsB,QAAU,IAAA,KAC/C,EAAa,EAAsB,MAAQ,OAE7C,EAEJ,CACF,EAAS,aAAe,EACvB,EAAQ,oBAA6C,UAAW,GAAc,CAC7E,OAAO,EAAS,aAAa,GAE7B,OAAO,IAAW,IAClB,CAEE,IAAa,aAEf,GAAU,UAAU,eAAgB,GAAM,EAE5C"}
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,`__esModule`,{value:!0});const e=require(`./utils/logger/index.cjs`),t=require(`./utils/constants/index.cjs`),n=require(`./models/CustomFieldDefinition.cjs`),r=require(`./models/CustomFieldValue.cjs`),i=require(`./models/CustomFieldEntries.cjs`),a=require(`./models/CustomValidator.cjs`),o=require(`./models/index.cjs`),s=require(`./api/index.cjs`),c=require(`./utils/db/index.cjs`),l=require(`./utils/helpers/index.cjs`),u=require(`./scopes/filter.cjs`),d=require(`./utils/init.cjs`),f=require(`./utils/validations/schema/custom-fields.cjs`),p=async(t,n,r)=>{e.tryAddingTraceIdMiddleware();let{models:i,useCustomFieldsEntries:a}=r;t&&t.use(`/api`,s.default);let l=r.sequelize??c.default(r.databaseConfig);return process.env.NODE_ENV===`test`&&await o.initTestModels(l),d.addHooks(i,n,{useCustomFieldsEntries:a}),await o.initTables(l,r.getUser,{useCustomFieldsEntries:a}),d.addScopes(i,n,{useCustomFieldsEntries:a}),d.applyCustomAssociation(i),e.default.debug(`sadot - custom fields finished initializing with models`,i),l};var m=p;const h=(e,t)=>{d.removeHooks(e,t)};exports.CUSTOM_FIELDS_FILTER_SCOPE=t.CUSTOM_FIELDS_FILTER_SCOPE,exports.CustomFieldDefinition=n,exports.CustomFieldDefinitionType=t.CustomFieldDefinitionType,exports.CustomFieldEntries=i,exports.CustomFieldValue=r,exports.CustomFieldsSchema=f.CustomFieldsSchema,exports.CustomValidator=a,exports.customFieldsSortScope=u.customFieldsSortScope,exports.default=m,exports.disableCustomFields=h,exports.generateCustomFieldSearchQueryPayload=l.generateCustomFieldSearchQueryPayload,exports.generateRandomString=l.generateRandomString,exports.supportedEntities=t.supportedEntities;
1
+ Object.defineProperty(exports,`__esModule`,{value:!0});const e=require(`./utils/logger/index.cjs`),t=require(`./utils/constants/index.cjs`),n=require(`./models/CustomFieldDefinition.cjs`),r=require(`./models/CustomFieldValue.cjs`),i=require(`./models/CustomFieldEntries.cjs`),a=require(`./models/CustomValidator.cjs`),o=require(`./models/index.cjs`),s=require(`./api/index.cjs`),c=require(`./utils/db/index.cjs`),l=require(`./utils/helpers/index.cjs`),u=require(`./scopes/filter.cjs`),d=require(`./utils/init.cjs`),f=require(`./utils/validations/schema/custom-fields.cjs`),p=async(t,n,r)=>{e.tryAddingTraceIdMiddleware();let{models:i,useCustomFieldsEntries:a,useModelTypeMapping:l}=r;t&&t.use(`/api`,s.default);let u=r.sequelize??c.default(r.databaseConfig);return process.env.NODE_ENV===`test`&&await o.initTestModels(u),d.addHooks(i,n,{useCustomFieldsEntries:a}),await o.initTables(u,r.getUser,{useCustomFieldsEntries:a,useModelTypeMapping:l}),d.addScopes(i,n,{useCustomFieldsEntries:a}),d.applyCustomAssociation(i),e.default.debug(`sadot - custom fields finished initializing with models`,i),u};var m=p;const h=(e,t)=>{d.removeHooks(e,t)};exports.CUSTOM_FIELDS_FILTER_SCOPE=t.CUSTOM_FIELDS_FILTER_SCOPE,exports.CustomFieldDefinition=n.default,exports.CustomFieldDefinitionType=t.CustomFieldDefinitionType,exports.CustomFieldEntries=i.default,exports.CustomFieldValue=r.default,exports.CustomFieldsSchema=f.CustomFieldsSchema,exports.CustomValidator=a.default,exports.customFieldsSortScope=u.customFieldsSortScope,exports.default=m,exports.disableCustomFields=h,exports.generateCustomFieldSearchQueryPayload=l.generateCustomFieldSearchQueryPayload,exports.generateRandomString=l.generateRandomString,exports.supportedEntities=t.supportedEntities;
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["api","initDB","initTestModels","initTables"],"sources":["../src/index.ts"],"sourcesContent":["import type { Application } from 'express';\nimport type { Sequelize } from 'sequelize-typescript';\nimport {\n initTables, initTestModels,\n} from './models';\nimport api from './api';\nimport initDB from './utils/db';\nimport logger, { tryAddingTraceIdMiddleware } from './utils/logger';\nimport type { CustomFieldOptions, ModelFetcher, Models } from './types';\nimport {\n addHooks, addScopes, applyCustomAssociation, removeHooks,\n} from './utils/init';\n\nexport * from './utils/validations/schema/custom-fields';\n\nexport * from './utils/constants';\n\nexport * from './utils/helpers';\n\nexport { customFieldsSortScope } from './scopes/filter';\nexport {\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomFieldValue,\n CustomValidator,\n} from './models';\n\n/**\n * Adding custom fields enrichment to the models inside the MODELS_FILE_NAME json file\n * @see {@link 'custom-fields/config'} for configurations\n */\nconst useCustomFields = async (\n app: Pick<Application, 'use'> | null,\n getModel: ModelFetcher,\n options: CustomFieldOptions,\n): Promise<Sequelize> => {\n tryAddingTraceIdMiddleware();\n const { models, useCustomFieldsEntries } = options;\n if (app) {\n app.use('/api', api);\n }\n const sequelize = options.sequelize ?? initDB(options.databaseConfig);\n if (process.env.NODE_ENV === 'test') {\n await initTestModels(sequelize);\n }\n // The order is important\n addHooks(models, getModel, { useCustomFieldsEntries });\n await initTables(sequelize, options.getUser, { useCustomFieldsEntries });\n addScopes(models, getModel, { useCustomFieldsEntries });\n applyCustomAssociation(models);\n\n logger.debug('sadot - custom fields finished initializing with models', models);\n return sequelize;\n};\n\nexport default useCustomFields;\n\nexport const disableCustomFields = (models: Models[], getModel: ModelFetcher): void => {\n removeHooks(models, getModel);\n};\n"],"mappings":"6jBA+BM,EAAkB,MACtB,EACA,EACA,IACuB,CACvB,EAAA,4BAA4B,CAC5B,GAAM,CAAE,SAAQ,0BAA2B,EACvC,GACF,EAAI,IAAI,OAAQA,EAAAA,QAAI,CAEtB,IAAM,EAAY,EAAQ,WAAaC,EAAAA,QAAO,EAAQ,eAAe,CAWrE,OAVI,QAAQ,IAAI,WAAa,QAC3B,MAAMC,EAAAA,eAAe,EAAU,CAGjC,EAAA,SAAS,EAAQ,EAAU,CAAE,yBAAwB,CAAC,CACtD,MAAMC,EAAAA,WAAW,EAAW,EAAQ,QAAS,CAAE,yBAAwB,CAAC,CACxE,EAAA,UAAU,EAAQ,EAAU,CAAE,yBAAwB,CAAC,CACvD,EAAA,uBAAuB,EAAO,CAE9B,EAAA,QAAO,MAAM,0DAA2D,EAAO,CACxE,GAGT,IAAA,EAAe,EAEf,MAAa,GAAuB,EAAkB,IAAiC,CACrF,EAAA,YAAY,EAAQ,EAAS"}
1
+ {"version":3,"file":"index.cjs","names":["api","initDB","initTestModels","initTables"],"sources":["../src/index.ts"],"sourcesContent":["import type { Application } from 'express';\nimport type { Sequelize } from 'sequelize-typescript';\nimport {\n initTables, initTestModels,\n} from './models';\nimport api from './api';\nimport initDB from './utils/db';\nimport logger, { tryAddingTraceIdMiddleware } from './utils/logger';\nimport type { CustomFieldOptions, ModelFetcher, Models } from './types';\nimport {\n addHooks, addScopes, applyCustomAssociation, removeHooks,\n} from './utils/init';\n\nexport * from './utils/validations/schema/custom-fields';\n\nexport * from './utils/constants';\n\nexport * from './utils/helpers';\n\nexport { customFieldsSortScope } from './scopes/filter';\nexport {\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomFieldValue,\n CustomValidator,\n} from './models';\n\n/**\n * Adding custom fields enrichment to the models inside the MODELS_FILE_NAME json file\n * @see {@link 'custom-fields/config'} for configurations\n */\nconst useCustomFields = async (\n app: Pick<Application, 'use'> | null,\n getModel: ModelFetcher,\n options: CustomFieldOptions,\n): Promise<Sequelize> => {\n tryAddingTraceIdMiddleware();\n const { models, useCustomFieldsEntries, useModelTypeMapping } = options;\n if (app) {\n app.use('/api', api);\n }\n const sequelize = options.sequelize ?? initDB(options.databaseConfig);\n if (process.env.NODE_ENV === 'test') {\n await initTestModels(sequelize);\n }\n // The order is important\n addHooks(models, getModel, { useCustomFieldsEntries });\n await initTables(sequelize, options.getUser, { useCustomFieldsEntries, useModelTypeMapping });\n addScopes(models, getModel, { useCustomFieldsEntries });\n applyCustomAssociation(models);\n\n logger.debug('sadot - custom fields finished initializing with models', models);\n return sequelize;\n};\n\nexport default useCustomFields;\n\nexport const disableCustomFields = (models: Models[], getModel: ModelFetcher): void => {\n removeHooks(models, getModel);\n};\n"],"mappings":"6jBA+BM,EAAkB,MACtB,EACA,EACA,IACuB,CACvB,EAAA,4BAA4B,CAC5B,GAAM,CAAE,SAAQ,yBAAwB,uBAAwB,EAC5D,GACF,EAAI,IAAI,OAAQA,EAAAA,QAAI,CAEtB,IAAM,EAAY,EAAQ,WAAaC,EAAAA,QAAO,EAAQ,eAAe,CAWrE,OAVI,QAAQ,IAAI,WAAa,QAC3B,MAAMC,EAAAA,eAAe,EAAU,CAGjC,EAAA,SAAS,EAAQ,EAAU,CAAE,yBAAwB,CAAC,CACtD,MAAMC,EAAAA,WAAW,EAAW,EAAQ,QAAS,CAAE,yBAAwB,sBAAqB,CAAC,CAC7F,EAAA,UAAU,EAAQ,EAAU,CAAE,yBAAwB,CAAC,CACvD,EAAA,uBAAuB,EAAO,CAE9B,EAAA,QAAO,MAAM,0DAA2D,EAAO,CACxE,GAGT,IAAA,EAAe,EAEf,MAAa,GAAuB,EAAkB,IAAiC,CACrF,EAAA,YAAY,EAAQ,EAAS"}
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import e,{tryAddingTraceIdMiddleware as t}from"./utils/logger/index.js";import{CUSTOM_FIELDS_FILTER_SCOPE as n,CustomFieldDefinitionType as r,supportedEntities as i}from"./utils/constants/index.js";import a from"./models/CustomFieldDefinition.js";import o from"./models/CustomFieldValue.js";import s from"./models/CustomFieldEntries.js";import c from"./models/CustomValidator.js";import{initTables as l,initTestModels as u}from"./models/index.js";import d from"./api/index.js";import f from"./utils/db/index.js";import{generateCustomFieldSearchQueryPayload as p,generateRandomString as m}from"./utils/helpers/index.js";import{customFieldsSortScope as h}from"./scopes/filter.js";import{addHooks as g,addScopes as _,applyCustomAssociation as v,removeHooks as y}from"./utils/init.js";import{CustomFieldsSchema as b}from"./utils/validations/schema/custom-fields.js";var x=async(n,r,i)=>{t();let{models:a,useCustomFieldsEntries:o}=i;n&&n.use(`/api`,d);let s=i.sequelize??f(i.databaseConfig);return process.env.NODE_ENV===`test`&&await u(s),g(a,r,{useCustomFieldsEntries:o}),await l(s,i.getUser,{useCustomFieldsEntries:o}),_(a,r,{useCustomFieldsEntries:o}),v(a),e.debug(`sadot - custom fields finished initializing with models`,a),s};const S=(e,t)=>{y(e,t)};export{n as CUSTOM_FIELDS_FILTER_SCOPE,a as CustomFieldDefinition,r as CustomFieldDefinitionType,s as CustomFieldEntries,o as CustomFieldValue,b as CustomFieldsSchema,c as CustomValidator,h as customFieldsSortScope,x as default,S as disableCustomFields,p as generateCustomFieldSearchQueryPayload,m as generateRandomString,i as supportedEntities};
1
+ import e,{tryAddingTraceIdMiddleware as t}from"./utils/logger/index.js";import{CUSTOM_FIELDS_FILTER_SCOPE as n,CustomFieldDefinitionType as r,supportedEntities as i}from"./utils/constants/index.js";import a from"./models/CustomFieldDefinition.js";import o from"./models/CustomFieldValue.js";import s from"./models/CustomFieldEntries.js";import c from"./models/CustomValidator.js";import{initTables as l,initTestModels as u}from"./models/index.js";import d from"./api/index.js";import f from"./utils/db/index.js";import{generateCustomFieldSearchQueryPayload as p,generateRandomString as m}from"./utils/helpers/index.js";import{customFieldsSortScope as h}from"./scopes/filter.js";import{addHooks as g,addScopes as _,applyCustomAssociation as v,removeHooks as y}from"./utils/init.js";import{CustomFieldsSchema as b}from"./utils/validations/schema/custom-fields.js";var x=async(n,r,i)=>{t();let{models:a,useCustomFieldsEntries:o,useModelTypeMapping:s}=i;n&&n.use(`/api`,d);let c=i.sequelize??f(i.databaseConfig);return process.env.NODE_ENV===`test`&&await u(c),g(a,r,{useCustomFieldsEntries:o}),await l(c,i.getUser,{useCustomFieldsEntries:o,useModelTypeMapping:s}),_(a,r,{useCustomFieldsEntries:o}),v(a),e.debug(`sadot - custom fields finished initializing with models`,a),c};const S=(e,t)=>{y(e,t)};export{n as CUSTOM_FIELDS_FILTER_SCOPE,a as CustomFieldDefinition,r as CustomFieldDefinitionType,s as CustomFieldEntries,o as CustomFieldValue,b as CustomFieldsSchema,c as CustomValidator,h as customFieldsSortScope,x as default,S as disableCustomFields,p as generateCustomFieldSearchQueryPayload,m as generateRandomString,i as supportedEntities};
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["api","initDB"],"sources":["../src/index.ts"],"sourcesContent":["import type { Application } from 'express';\nimport type { Sequelize } from 'sequelize-typescript';\nimport {\n initTables, initTestModels,\n} from './models';\nimport api from './api';\nimport initDB from './utils/db';\nimport logger, { tryAddingTraceIdMiddleware } from './utils/logger';\nimport type { CustomFieldOptions, ModelFetcher, Models } from './types';\nimport {\n addHooks, addScopes, applyCustomAssociation, removeHooks,\n} from './utils/init';\n\nexport * from './utils/validations/schema/custom-fields';\n\nexport * from './utils/constants';\n\nexport * from './utils/helpers';\n\nexport { customFieldsSortScope } from './scopes/filter';\nexport {\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomFieldValue,\n CustomValidator,\n} from './models';\n\n/**\n * Adding custom fields enrichment to the models inside the MODELS_FILE_NAME json file\n * @see {@link 'custom-fields/config'} for configurations\n */\nconst useCustomFields = async (\n app: Pick<Application, 'use'> | null,\n getModel: ModelFetcher,\n options: CustomFieldOptions,\n): Promise<Sequelize> => {\n tryAddingTraceIdMiddleware();\n const { models, useCustomFieldsEntries } = options;\n if (app) {\n app.use('/api', api);\n }\n const sequelize = options.sequelize ?? initDB(options.databaseConfig);\n if (process.env.NODE_ENV === 'test') {\n await initTestModels(sequelize);\n }\n // The order is important\n addHooks(models, getModel, { useCustomFieldsEntries });\n await initTables(sequelize, options.getUser, { useCustomFieldsEntries });\n addScopes(models, getModel, { useCustomFieldsEntries });\n applyCustomAssociation(models);\n\n logger.debug('sadot - custom fields finished initializing with models', models);\n return sequelize;\n};\n\nexport default useCustomFields;\n\nexport const disableCustomFields = (models: Models[], getModel: ModelFetcher): void => {\n removeHooks(models, getModel);\n};\n"],"mappings":"81BAuDA,IAAA,EAxBwB,MACtB,EACA,EACA,IACuB,CACvB,GAA4B,CAC5B,GAAM,CAAE,SAAQ,0BAA2B,EACvC,GACF,EAAI,IAAI,OAAQA,EAAI,CAEtB,IAAM,EAAY,EAAQ,WAAaC,EAAO,EAAQ,eAAe,CAWrE,OAVI,QAAQ,IAAI,WAAa,QAC3B,MAAM,EAAe,EAAU,CAGjC,EAAS,EAAQ,EAAU,CAAE,yBAAwB,CAAC,CACtD,MAAM,EAAW,EAAW,EAAQ,QAAS,CAAE,yBAAwB,CAAC,CACxE,EAAU,EAAQ,EAAU,CAAE,yBAAwB,CAAC,CACvD,EAAuB,EAAO,CAE9B,EAAO,MAAM,0DAA2D,EAAO,CACxE,GAKT,MAAa,GAAuB,EAAkB,IAAiC,CACrF,EAAY,EAAQ,EAAS"}
1
+ {"version":3,"file":"index.js","names":["api","initDB"],"sources":["../src/index.ts"],"sourcesContent":["import type { Application } from 'express';\nimport type { Sequelize } from 'sequelize-typescript';\nimport {\n initTables, initTestModels,\n} from './models';\nimport api from './api';\nimport initDB from './utils/db';\nimport logger, { tryAddingTraceIdMiddleware } from './utils/logger';\nimport type { CustomFieldOptions, ModelFetcher, Models } from './types';\nimport {\n addHooks, addScopes, applyCustomAssociation, removeHooks,\n} from './utils/init';\n\nexport * from './utils/validations/schema/custom-fields';\n\nexport * from './utils/constants';\n\nexport * from './utils/helpers';\n\nexport { customFieldsSortScope } from './scopes/filter';\nexport {\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomFieldValue,\n CustomValidator,\n} from './models';\n\n/**\n * Adding custom fields enrichment to the models inside the MODELS_FILE_NAME json file\n * @see {@link 'custom-fields/config'} for configurations\n */\nconst useCustomFields = async (\n app: Pick<Application, 'use'> | null,\n getModel: ModelFetcher,\n options: CustomFieldOptions,\n): Promise<Sequelize> => {\n tryAddingTraceIdMiddleware();\n const { models, useCustomFieldsEntries, useModelTypeMapping } = options;\n if (app) {\n app.use('/api', api);\n }\n const sequelize = options.sequelize ?? initDB(options.databaseConfig);\n if (process.env.NODE_ENV === 'test') {\n await initTestModels(sequelize);\n }\n // The order is important\n addHooks(models, getModel, { useCustomFieldsEntries });\n await initTables(sequelize, options.getUser, { useCustomFieldsEntries, useModelTypeMapping });\n addScopes(models, getModel, { useCustomFieldsEntries });\n applyCustomAssociation(models);\n\n logger.debug('sadot - custom fields finished initializing with models', models);\n return sequelize;\n};\n\nexport default useCustomFields;\n\nexport const disableCustomFields = (models: Models[], getModel: ModelFetcher): void => {\n removeHooks(models, getModel);\n};\n"],"mappings":"81BAuDA,IAAA,EAxBwB,MACtB,EACA,EACA,IACuB,CACvB,GAA4B,CAC5B,GAAM,CAAE,SAAQ,yBAAwB,uBAAwB,EAC5D,GACF,EAAI,IAAI,OAAQA,EAAI,CAEtB,IAAM,EAAY,EAAQ,WAAaC,EAAO,EAAQ,eAAe,CAWrE,OAVI,QAAQ,IAAI,WAAa,QAC3B,MAAM,EAAe,EAAU,CAGjC,EAAS,EAAQ,EAAU,CAAE,yBAAwB,CAAC,CACtD,MAAM,EAAW,EAAW,EAAQ,QAAS,CAAE,yBAAwB,sBAAqB,CAAC,CAC7F,EAAU,EAAQ,EAAU,CAAE,yBAAwB,CAAC,CACvD,EAAuB,EAAO,CAE9B,EAAO,MAAM,0DAA2D,EAAO,CACxE,GAKT,MAAa,GAAuB,EAAkB,IAAiC,CACrF,EAAY,EAAQ,EAAS"}
@@ -1,2 +1,2 @@
1
- const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../utils/logger/index.cjs`),n=require(`../utils/constants/index.cjs`),r=require(`../utils/validations/validators/index.cjs`),i=require(`../events/index.cjs`),a=require(`../errors/index.cjs`),o=require(`../utils/validations/index.cjs`),s=require(`../_virtual/_@oxc-project_runtime@0.103.0/helpers/decorateMetadata.cjs`),c=require(`../_virtual/_@oxc-project_runtime@0.103.0/helpers/decorate.cjs`),l=require(`./CustomFieldValue.cjs`);require(`./index.cjs`);let u=require(`sequelize-typescript`);var d,f,p,m,h,g;let _=class extends u.Model{static displayNameDefaultValue(e){if(e?.displayName||(e.displayName=e.name),![null,void 0].includes(e.defaultValue)){let t=o.validateValue(e.defaultValue,e.fieldType,e.validation);if(t.error)throw new a.InvalidValueError(e.defaultValue,e.name,t.error)}}static afterSaveHandler(e,t){t.transaction?t.transaction.afterCommit(()=>i.sendDimEvent(e)):i.sendDimEvent(e)}};c.__decorate([u.PrimaryKey,(0,u.Column)({type:u.DataType.UUID,defaultValue:u.DataType.UUIDV4,allowNull:!1}),s.__decorateMetadata(`design:type`,String)],_.prototype,`id`,void 0),c.__decorate([(0,u.Column)({type:u.DataType.STRING,allowNull:!1}),s.__decorateMetadata(`design:type`,String)],_.prototype,`name`,void 0),c.__decorate([(0,u.Column)({type:u.DataType.STRING}),s.__decorateMetadata(`design:type`,String)],_.prototype,`displayName`,void 0),c.__decorate([(0,u.Is)(`SupportedType`,e=>{if(!Object.values(n.CustomFieldDefinitionType).includes(e))throw new a.UnsupportedCustomFieldTypeError(`"${e}" is not a supported type.`)}),(0,u.Column)({type:u.DataType.STRING,allowNull:!1}),s.__decorateMetadata(`design:type`,typeof(d=n.CustomFieldDefinitionType!==void 0&&n.CustomFieldDefinitionType)==`function`?d:Object)],_.prototype,`fieldType`,void 0),c.__decorate([(0,u.Column)({type:u.DataType.JSONB}),s.__decorateMetadata(`design:type`,Object)],_.prototype,`validation`,void 0),c.__decorate([(0,u.Column)({type:u.DataType.UUID,allowNull:!1}),s.__decorateMetadata(`design:type`,String)],_.prototype,`entityId`,void 0),c.__decorate([(0,u.Column)({type:u.DataType.STRING,allowNull:!1}),s.__decorateMetadata(`design:type`,String)],_.prototype,`entityType`,void 0),c.__decorate([(0,u.Column)({type:u.DataType.STRING,allowNull:!1}),s.__decorateMetadata(`design:type`,String)],_.prototype,`modelType`,void 0),c.__decorate([(0,u.Column)({type:u.DataType.TEXT}),s.__decorateMetadata(`design:type`,String)],_.prototype,`description`,void 0),c.__decorate([(0,u.Column)({type:u.DataType.BOOLEAN,defaultValue:!1}),s.__decorateMetadata(`design:type`,Boolean)],_.prototype,`required`,void 0),c.__decorate([(0,u.Column)({type:u.DataType.BOOLEAN,defaultValue:!1}),s.__decorateMetadata(`design:type`,Boolean)],_.prototype,`disabled`,void 0),c.__decorate([(0,u.Column)({type:u.DataType.JSONB,allowNull:!0}),s.__decorateMetadata(`design:type`,Object)],_.prototype,`defaultValue`,void 0),c.__decorate([(0,u.Column)({type:u.DataType.DATE,allowNull:!1}),s.__decorateMetadata(`design:type`,typeof(f=typeof Date<`u`&&Date)==`function`?f:Object)],_.prototype,`createdAt`,void 0),c.__decorate([(0,u.Column)({type:u.DataType.DATE,allowNull:!0}),s.__decorateMetadata(`design:type`,typeof(p=typeof Date<`u`&&Date)==`function`?p:Object)],_.prototype,`updatedAt`,void 0),c.__decorate([(0,u.Column)({type:u.DataType.DATE,allowNull:!0}),s.__decorateMetadata(`design:type`,typeof(m=typeof Date<`u`&&Date)==`function`?m:Object)],_.prototype,`deletedAt`,void 0),c.__decorate([(0,u.Column)({type:u.DataType.BOOLEAN,defaultValue:!1,allowNull:!1}),s.__decorateMetadata(`design:type`,Boolean)],_.prototype,`blockEditingFromUI`,void 0),c.__decorate([(0,u.HasMany)(()=>l.default),s.__decorateMetadata(`design:type`,Array)],_.prototype,`values`,void 0),c.__decorate([u.BeforeCreate,s.__decorateMetadata(`design:type`,Function),s.__decorateMetadata(`design:paramtypes`,[typeof(h=_!==void 0&&_)==`function`?h:Object]),s.__decorateMetadata(`design:returntype`,void 0)],_,`displayNameDefaultValue`,null),c.__decorate([u.AfterSave,s.__decorateMetadata(`design:type`,Function),s.__decorateMetadata(`design:paramtypes`,[typeof(g=_!==void 0&&_)==`function`?g:Object,Object]),s.__decorateMetadata(`design:returntype`,void 0)],_,`afterSaveHandler`,null),_=c.__decorate([(0,u.DefaultScope)(()=>({where:{disabled:!1}})),(0,u.Table)({tableName:`custom_field_definitions`,modelName:`CustomFieldDefinition`,indexes:[{name:`unique_name_model_type`,fields:[`model_type`,`entity_id`,`name`],unique:!0}],timestamps:!0,validate:{validationByType(){if(!this.validation&&r.CustomValidationTypes[this.fieldType])throw t.default.error(`No custom validation for custom field type ${this.fieldType} found`),new a.UnsupportedCustomValidationError(`Validation provided for "${this.fieldType}" is not supported`)}}})],_);var v=_;exports.default=v;
1
+ const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../utils/logger/index.cjs`),n=require(`../utils/constants/index.cjs`),r=require(`../utils/validations/validators/index.cjs`),i=require(`../events/index.cjs`),a=require(`../errors/index.cjs`),o=require(`../utils/validations/index.cjs`),s=require(`../_virtual/_@oxc-project_runtime@0.97.0/helpers/decorateMetadata.cjs`),c=require(`../_virtual/_@oxc-project_runtime@0.97.0/helpers/decorate.cjs`),l=require(`./CustomFieldValue.cjs`);require(`./index.cjs`);let u=require(`sequelize-typescript`);var d,f,p,m,h,g;let _=class extends u.Model{static displayNameDefaultValue(e){if(e?.displayName||(e.displayName=e.name),![null,void 0].includes(e.defaultValue)){let t=o.validateValue(e.defaultValue,e.fieldType,e.validation);if(t.error)throw new a.InvalidValueError(e.defaultValue,e.name,t.error)}}static afterSaveHandler(e,t){t.transaction?t.transaction.afterCommit(()=>i.sendDimEvent(e)):i.sendDimEvent(e)}};c.__decorate([u.PrimaryKey,(0,u.Column)({type:u.DataType.UUID,defaultValue:u.DataType.UUIDV4,allowNull:!1}),s.__decorateMetadata(`design:type`,String)],_.prototype,`id`,void 0),c.__decorate([(0,u.Column)({type:u.DataType.STRING,allowNull:!1}),s.__decorateMetadata(`design:type`,String)],_.prototype,`name`,void 0),c.__decorate([(0,u.Column)({type:u.DataType.STRING}),s.__decorateMetadata(`design:type`,String)],_.prototype,`displayName`,void 0),c.__decorate([(0,u.Is)(`SupportedType`,e=>{if(!Object.values(n.CustomFieldDefinitionType).includes(e))throw new a.UnsupportedCustomFieldTypeError(`"${e}" is not a supported type.`)}),(0,u.Column)({type:u.DataType.STRING,allowNull:!1}),s.__decorateMetadata(`design:type`,typeof(d=n.CustomFieldDefinitionType!==void 0&&n.CustomFieldDefinitionType)==`function`?d:Object)],_.prototype,`fieldType`,void 0),c.__decorate([(0,u.Column)({type:u.DataType.JSONB}),s.__decorateMetadata(`design:type`,Object)],_.prototype,`validation`,void 0),c.__decorate([(0,u.Column)({type:u.DataType.UUID,allowNull:!1}),s.__decorateMetadata(`design:type`,String)],_.prototype,`entityId`,void 0),c.__decorate([(0,u.Column)({type:u.DataType.STRING,allowNull:!1}),s.__decorateMetadata(`design:type`,String)],_.prototype,`entityType`,void 0),c.__decorate([(0,u.Column)({type:u.DataType.STRING,allowNull:!1}),s.__decorateMetadata(`design:type`,String)],_.prototype,`modelType`,void 0),c.__decorate([(0,u.Column)({type:u.DataType.TEXT}),s.__decorateMetadata(`design:type`,String)],_.prototype,`description`,void 0),c.__decorate([(0,u.Column)({type:u.DataType.BOOLEAN,defaultValue:!1}),s.__decorateMetadata(`design:type`,Boolean)],_.prototype,`required`,void 0),c.__decorate([(0,u.Column)({type:u.DataType.BOOLEAN,defaultValue:!1}),s.__decorateMetadata(`design:type`,Boolean)],_.prototype,`disabled`,void 0),c.__decorate([(0,u.Column)({type:u.DataType.JSONB,allowNull:!0}),s.__decorateMetadata(`design:type`,Object)],_.prototype,`defaultValue`,void 0),c.__decorate([(0,u.Column)({type:u.DataType.DATE,allowNull:!1}),s.__decorateMetadata(`design:type`,typeof(f=typeof Date<`u`&&Date)==`function`?f:Object)],_.prototype,`createdAt`,void 0),c.__decorate([(0,u.Column)({type:u.DataType.DATE,allowNull:!0}),s.__decorateMetadata(`design:type`,typeof(p=typeof Date<`u`&&Date)==`function`?p:Object)],_.prototype,`updatedAt`,void 0),c.__decorate([(0,u.Column)({type:u.DataType.DATE,allowNull:!0}),s.__decorateMetadata(`design:type`,typeof(m=typeof Date<`u`&&Date)==`function`?m:Object)],_.prototype,`deletedAt`,void 0),c.__decorate([(0,u.Column)({type:u.DataType.BOOLEAN,defaultValue:!1,allowNull:!1}),s.__decorateMetadata(`design:type`,Boolean)],_.prototype,`blockEditingFromUI`,void 0),c.__decorate([(0,u.HasMany)(()=>l.default),s.__decorateMetadata(`design:type`,Array)],_.prototype,`values`,void 0),c.__decorate([u.BeforeCreate,s.__decorateMetadata(`design:type`,Function),s.__decorateMetadata(`design:paramtypes`,[typeof(h=_!==void 0&&_)==`function`?h:Object]),s.__decorateMetadata(`design:returntype`,void 0)],_,`displayNameDefaultValue`,null),c.__decorate([u.AfterSave,s.__decorateMetadata(`design:type`,Function),s.__decorateMetadata(`design:paramtypes`,[typeof(g=_!==void 0&&_)==`function`?g:Object,Object]),s.__decorateMetadata(`design:returntype`,void 0)],_,`afterSaveHandler`,null),_=c.__decorate([(0,u.DefaultScope)(()=>({where:{disabled:!1}})),(0,u.Table)({tableName:`custom_field_definitions`,modelName:`CustomFieldDefinition`,indexes:[{name:`unique_name_model_type`,fields:[`model_type`,`entity_id`,`name`],unique:!0}],timestamps:!0,validate:{validationByType(){if(!this.validation&&r.CustomValidationTypes[this.fieldType])throw t.default.error(`No custom validation for custom field type ${this.fieldType} found`),new a.UnsupportedCustomValidationError(`Validation provided for "${this.fieldType}" is not supported`)}}})],_);var v=_;exports.default=v;
2
2
  //# sourceMappingURL=CustomFieldDefinition.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"CustomFieldDefinition.cjs","names":["CustomFieldDefinition","Model","validateValue","InvalidValueError","sendDimEvent","PrimaryKey","DataType","CustomFieldDefinitionType","UnsupportedCustomFieldTypeError","CustomFieldValue","BeforeCreate","AfterSave","CustomValidationTypes","UnsupportedCustomValidationError"],"sources":["../../src/models/CustomFieldDefinition.ts"],"sourcesContent":["import {\n Table,\n Column,\n Model,\n DataType,\n HasMany,\n PrimaryKey,\n BeforeCreate,\n DefaultScope,\n AfterSave,\n Is,\n} from 'sequelize-typescript';\nimport type { CreateOptions } from 'sequelize';\nimport { CustomFieldDefinitionType } from '../utils/constants';\nimport { CustomValidationTypes } from '../utils/validations/validators';\nimport { CustomFieldValue } from '.';\nimport { sendDimEvent } from '../events';\nimport { InvalidValueError, UnsupportedCustomFieldTypeError, UnsupportedCustomValidationError } from '../errors';\nimport logger from '../utils/logger';\nimport { validateValue } from '../utils/validations';\n\n@DefaultScope(() => ({ where: { disabled: false } }))\n@Table({\n tableName: 'custom_field_definitions',\n modelName: 'CustomFieldDefinition',\n indexes: [\n {\n name: 'unique_name_model_type',\n fields: ['model_type', 'entity_id', 'name'],\n unique: true,\n },\n ],\n timestamps: true,\n validate: {\n validationByType(this: CustomFieldDefinition) {\n // Verify the validation is provided if needed\n if (!this.validation && CustomValidationTypes[this.fieldType as keyof typeof CustomValidationTypes]) {\n // TODO: enforce the validation-object schema based on the fieldType\n logger.error(`No custom validation for custom field type ${this.fieldType} found`);\n throw new UnsupportedCustomValidationError(`Validation provided for \"${this.fieldType}\" is not supported`);\n }\n },\n },\n})\nclass CustomFieldDefinition extends Model {\n @PrimaryKey\n @Column({\n type: DataType.UUID,\n defaultValue: DataType.UUIDV4,\n allowNull: false,\n })\n declare id: string;\n\n @Column({\n type: DataType.STRING,\n allowNull: false,\n })\n name!: string;\n\n @Column({\n type: DataType.STRING,\n })\n displayName?: string; // Defaulted to name with beforeCreate hook\n\n @Is('SupportedType', (value) => {\n if (!Object.values(CustomFieldDefinitionType).includes(value as CustomFieldDefinitionType)) {\n throw new UnsupportedCustomFieldTypeError(`\"${value}\" is not a supported type.`);\n }\n })\n @Column({\n type: DataType.STRING,\n allowNull: false,\n })\n fieldType!: CustomFieldDefinitionType;\n\n @Column({\n type: DataType.JSONB,\n })\n validation?: any;\n\n @Column({\n type: DataType.UUID,\n allowNull: false,\n })\n entityId!: string; /** Client association entity id */\n\n @Column({\n type: DataType.STRING,\n allowNull: false,\n })\n entityType!: string; /** Client association entity type (demand source / fleet / etc.) */\n\n @Column({\n type: DataType.STRING,\n allowNull: false,\n })\n modelType!: string; /** Model type. e.g. Vehicle / StopPoint / etc. */\n\n @Column({\n type: DataType.TEXT,\n })\n description?: string;\n\n @Column({\n type: DataType.BOOLEAN,\n defaultValue: false,\n })\n required?: boolean;\n\n @Column({\n type: DataType.BOOLEAN,\n defaultValue: false,\n })\n disabled?: boolean;\n\n @Column({\n type: DataType.JSONB,\n allowNull: true,\n })\n defaultValue?: any;\n\n @Column({\n type: DataType.DATE,\n allowNull: false,\n })\n declare createdAt?: Date;\n\n @Column({\n type: DataType.DATE,\n allowNull: true,\n })\n declare updatedAt?: Date;\n\n @Column({\n type: DataType.DATE,\n allowNull: true,\n })\n declare deletedAt?: Date;\n\n @Column({\n type: DataType.BOOLEAN,\n defaultValue: false,\n allowNull: false,\n })\n blockEditingFromUI!: boolean;\n\n @HasMany(() => CustomFieldValue)\n declare values: CustomFieldValue[];\n\n @BeforeCreate\n static displayNameDefaultValue(instance: CustomFieldDefinition): void {\n if (!instance?.displayName) {\n instance.displayName = instance.name;\n }\n if (![null, undefined].includes(instance.defaultValue)) {\n const isValid = validateValue(instance.defaultValue, instance.fieldType, instance.validation);\n if (isValid.error) {\n throw new InvalidValueError(instance.defaultValue, instance.name, isValid.error);\n }\n }\n }\n\n @AfterSave\n static afterSaveHandler(instance: CustomFieldDefinition, options: CreateOptions): void {\n if (options.transaction) {\n options.transaction.afterCommit(() => sendDimEvent(instance));\n } else {\n sendDimEvent(instance);\n }\n }\n}\n\nexport default CustomFieldDefinition;\n"],"mappings":"2jBAqBA,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A,KAAA,KAAA,OAAA,WAAA,EAAA,OAAA,CAAA,CAAA,EAAA,UAAA,YAAA,IAAA,GAAA,4BAGM,CACN,KAAMA,EAAAA,SAAS,QACf,aAAc,GACd,UAAW,GACZ,CAAC,CAAA,EAAA,mBAAA,cAAA,QAAA,CAAA,CAAA,EAAA,UAAA,qBAAA,IAAA,GAAA,iCAGaG,EAAAA,QAAiB,CAAA,EAAA,mBAAA,cAAA,MAAA,CAAA,CAAA,EAAA,UAAA,SAAA,IAAA,GAAA,eAG/BC,EAAAA,qPAaAC,EAAAA,4QA7IkB,CAAE,MAAO,CAAE,SAAU,GAAO,CAAE,EAAE,EAAA,EAAA,EAAA,OAC9C,CACL,UAAW,2BACX,UAAW,wBACX,QAAS,CACP,CACE,KAAM,yBACN,OAAQ,CAAC,aAAc,YAAa,OAAO,CAC3C,OAAQ,GACT,CACF,CACD,WAAY,GACZ,SAAU,CACR,kBAA8C,CAE5C,GAAI,CAAC,KAAK,YAAcC,EAAAA,sBAAsB,KAAK,WAGjD,MADA,EAAA,QAAO,MAAM,8CAA8C,KAAK,UAAU,QAAQ,CAC5E,IAAIC,EAAAA,iCAAiC,4BAA4B,KAAK,UAAU,oBAAoB,EAG/G,CACF,CAAC,CAAA,CAAA,EAAA,CAiIF,IAAA,EAAe"}
1
+ {"version":3,"file":"CustomFieldDefinition.cjs","names":["CustomFieldDefinition","Model","validateValue","InvalidValueError","sendDimEvent","PrimaryKey","DataType","CustomFieldDefinitionType","UnsupportedCustomFieldTypeError","CustomFieldValue","BeforeCreate","AfterSave","CustomValidationTypes","UnsupportedCustomValidationError"],"sources":["../../src/models/CustomFieldDefinition.ts"],"sourcesContent":["import {\n Table,\n Column,\n Model,\n DataType,\n HasMany,\n PrimaryKey,\n BeforeCreate,\n DefaultScope,\n AfterSave,\n Is,\n} from 'sequelize-typescript';\nimport type { CreateOptions } from 'sequelize';\nimport { CustomFieldDefinitionType } from '../utils/constants';\nimport { CustomValidationTypes } from '../utils/validations/validators';\nimport { CustomFieldValue } from '.';\nimport CustomFieldModelTypeMap from './CustomFieldModelTypeMap';\nimport { sendDimEvent } from '../events';\nimport { InvalidValueError, UnsupportedCustomFieldTypeError, UnsupportedCustomValidationError } from '../errors';\nimport logger from '../utils/logger';\nimport { validateValue } from '../utils/validations';\n\n@DefaultScope(() => ({ where: { disabled: false } }))\n@Table({\n tableName: 'custom_field_definitions',\n modelName: 'CustomFieldDefinition',\n indexes: [\n {\n name: 'unique_name_model_type',\n fields: ['model_type', 'entity_id', 'name'],\n unique: true,\n },\n ],\n timestamps: true,\n validate: {\n validationByType(this: CustomFieldDefinition) {\n // Verify the validation is provided if needed\n if (!this.validation && CustomValidationTypes[this.fieldType as keyof typeof CustomValidationTypes]) {\n // TODO: enforce the validation-object schema based on the fieldType\n logger.error(`No custom validation for custom field type ${this.fieldType} found`);\n throw new UnsupportedCustomValidationError(`Validation provided for \"${this.fieldType}\" is not supported`);\n }\n },\n },\n})\nclass CustomFieldDefinition extends Model {\n @PrimaryKey\n @Column({\n type: DataType.UUID,\n defaultValue: DataType.UUIDV4,\n allowNull: false,\n })\n declare id: string;\n\n @Column({\n type: DataType.STRING,\n allowNull: false,\n })\n name!: string;\n\n @Column({\n type: DataType.STRING,\n })\n displayName?: string; // Defaulted to name with beforeCreate hook\n\n @Is('SupportedType', (value) => {\n if (!Object.values(CustomFieldDefinitionType).includes(value as CustomFieldDefinitionType)) {\n throw new UnsupportedCustomFieldTypeError(`\"${value}\" is not a supported type.`);\n }\n })\n @Column({\n type: DataType.STRING,\n allowNull: false,\n })\n fieldType!: CustomFieldDefinitionType;\n\n @Column({\n type: DataType.JSONB,\n })\n validation?: any;\n\n @Column({\n type: DataType.UUID,\n allowNull: false,\n })\n entityId!: string; /** Client association entity id */\n\n @Column({\n type: DataType.STRING,\n allowNull: false,\n })\n entityType!: string; /** Client association entity type (demand source / fleet / etc.) */\n\n @Column({\n type: DataType.STRING,\n allowNull: false,\n })\n modelType!: string; /** Model type. e.g. Vehicle / StopPoint / etc. */\n\n @Column({\n type: DataType.TEXT,\n })\n description?: string;\n\n @Column({\n type: DataType.BOOLEAN,\n defaultValue: false,\n })\n required?: boolean;\n\n @Column({\n type: DataType.BOOLEAN,\n defaultValue: false,\n })\n disabled?: boolean;\n\n @Column({\n type: DataType.JSONB,\n allowNull: true,\n })\n defaultValue?: any;\n\n @Column({\n type: DataType.DATE,\n allowNull: false,\n })\n declare createdAt?: Date;\n\n @Column({\n type: DataType.DATE,\n allowNull: true,\n })\n declare updatedAt?: Date;\n\n @Column({\n type: DataType.DATE,\n allowNull: true,\n })\n declare deletedAt?: Date;\n\n @Column({\n type: DataType.BOOLEAN,\n defaultValue: false,\n allowNull: false,\n })\n blockEditingFromUI!: boolean;\n\n @HasMany(() => CustomFieldValue)\n declare values: CustomFieldValue[];\n\n // Association added programmatically when useModelTypeMapping is enabled\n declare modelTypeMappings?: CustomFieldModelTypeMap[];\n\n // Virtual property added by enrichWithModelTypeIds\n declare modelTypeIds?: string[];\n\n @BeforeCreate\n static displayNameDefaultValue(instance: CustomFieldDefinition): void {\n if (!instance?.displayName) {\n instance.displayName = instance.name;\n }\n if (![null, undefined].includes(instance.defaultValue)) {\n const isValid = validateValue(instance.defaultValue, instance.fieldType, instance.validation);\n if (isValid.error) {\n throw new InvalidValueError(instance.defaultValue, instance.name, isValid.error);\n }\n }\n }\n\n @AfterSave\n static afterSaveHandler(instance: CustomFieldDefinition, options: CreateOptions): void {\n if (options.transaction) {\n options.transaction.afterCommit(() => sendDimEvent(instance));\n } else {\n sendDimEvent(instance);\n }\n }\n}\n\nexport default CustomFieldDefinition;\n"],"mappings":"yjBAsBA,IAAA,EAAA,cAuBoCC,EAAAA,KAAM,CA+GxC,OACO,wBAAwB,EAAuC,CAIpE,GAHK,GAAU,cACb,EAAS,YAAc,EAAS,MAE9B,CAAC,CAAC,KAAM,IAAA,GAAU,CAAC,SAAS,EAAS,aAAa,CAAE,CACtD,IAAM,EAAUC,EAAAA,cAAc,EAAS,aAAc,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AA,iCAGaG,EAAAA,QAAiB,CAAA,EAAA,mBAAA,cAAA,MAAA,CAAA,CAAA,EAAA,UAAA,SAAA,IAAA,GAAA,eAS/BC,EAAAA,qPAaAC,EAAAA,4QAnJkB,CAAE,MAAO,CAAE,SAAU,GAAO,CAAE,EAAE,EAAA,EAAA,EAAA,OAC9C,CACL,UAAW,2BACX,UAAW,wBACX,QAAS,CACP,CACE,KAAM,yBACN,OAAQ,CAAC,aAAc,YAAa,OAAO,CAC3C,OAAQ,GACT,CACF,CACD,WAAY,GACZ,SAAU,CACR,kBAA8C,CAE5C,GAAI,CAAC,KAAK,YAAcC,EAAAA,sBAAsB,KAAK,WAGjD,MADA,EAAA,QAAO,MAAM,8CAA8C,KAAK,UAAU,QAAQ,CAC5E,IAAIC,EAAAA,iCAAiC,4BAA4B,KAAK,UAAU,oBAAoB,EAG/G,CACF,CAAC,CAAA,CAAA,EAAA,CAuIF,IAAA,EAAe"}
@@ -1,5 +1,6 @@
1
1
  import { CustomFieldDefinitionType } from "../utils/constants/index.cjs";
2
2
  import { CustomFieldValue } from "./CustomFieldValue.cjs";
3
+ import { CustomFieldModelTypeMap } from "./CustomFieldModelTypeMap.cjs";
3
4
  import "./index.cjs";
4
5
  import { Model } from "sequelize-typescript";
5
6
  import { CreateOptions } from "sequelize";
@@ -23,6 +24,8 @@ declare class CustomFieldDefinition extends Model {
23
24
  deletedAt?: Date;
24
25
  blockEditingFromUI: boolean;
25
26
  values: CustomFieldValue[];
27
+ modelTypeMappings?: CustomFieldModelTypeMap[];
28
+ modelTypeIds?: string[];
26
29
  static displayNameDefaultValue(instance: CustomFieldDefinition): void;
27
30
  static afterSaveHandler(instance: CustomFieldDefinition, options: CreateOptions): void;
28
31
  }
@@ -1,5 +1,6 @@
1
1
  import { CustomFieldDefinitionType } from "../utils/constants/index.js";
2
2
  import { CustomFieldValue } from "./CustomFieldValue.js";
3
+ import { CustomFieldModelTypeMap } from "./CustomFieldModelTypeMap.js";
3
4
  import "./index.js";
4
5
  import { CreateOptions } from "sequelize";
5
6
  import { Model } from "sequelize-typescript";
@@ -23,6 +24,8 @@ declare class CustomFieldDefinition extends Model {
23
24
  deletedAt?: Date;
24
25
  blockEditingFromUI: boolean;
25
26
  values: CustomFieldValue[];
27
+ modelTypeMappings?: CustomFieldModelTypeMap[];
28
+ modelTypeIds?: string[];
26
29
  static displayNameDefaultValue(instance: CustomFieldDefinition): void;
27
30
  static afterSaveHandler(instance: CustomFieldDefinition, options: CreateOptions): void;
28
31
  }
@@ -1,2 +1,2 @@
1
- import e from"../utils/logger/index.js";import{CustomFieldDefinitionType as t}from"../utils/constants/index.js";import{CustomValidationTypes as n}from"../utils/validations/validators/index.js";import{sendDimEvent as r}from"../events/index.js";import{InvalidValueError as i,UnsupportedCustomFieldTypeError as a,UnsupportedCustomValidationError as o}from"../errors/index.js";import{validateValue as s}from"../utils/validations/index.js";import{__decorateMetadata as c}from"../_virtual/_@oxc-project_runtime@0.103.0/helpers/decorateMetadata.js";import{__decorate as l}from"../_virtual/_@oxc-project_runtime@0.103.0/helpers/decorate.js";import u from"./CustomFieldValue.js";import"./index.js";import{AfterSave as d,BeforeCreate as f,Column as p,DataType as m,DefaultScope as h,HasMany as g,Is as _,Model as v,PrimaryKey as y,Table as b}from"sequelize-typescript";var x,S,C,w,T,E;let D=class extends v{static displayNameDefaultValue(e){if(e?.displayName||(e.displayName=e.name),![null,void 0].includes(e.defaultValue)){let t=s(e.defaultValue,e.fieldType,e.validation);if(t.error)throw new i(e.defaultValue,e.name,t.error)}}static afterSaveHandler(e,t){t.transaction?t.transaction.afterCommit(()=>r(e)):r(e)}};l([y,p({type:m.UUID,defaultValue:m.UUIDV4,allowNull:!1}),c(`design:type`,String)],D.prototype,`id`,void 0),l([p({type:m.STRING,allowNull:!1}),c(`design:type`,String)],D.prototype,`name`,void 0),l([p({type:m.STRING}),c(`design:type`,String)],D.prototype,`displayName`,void 0),l([_(`SupportedType`,e=>{if(!Object.values(t).includes(e))throw new a(`"${e}" is not a supported type.`)}),p({type:m.STRING,allowNull:!1}),c(`design:type`,typeof(x=t!==void 0&&t)==`function`?x:Object)],D.prototype,`fieldType`,void 0),l([p({type:m.JSONB}),c(`design:type`,Object)],D.prototype,`validation`,void 0),l([p({type:m.UUID,allowNull:!1}),c(`design:type`,String)],D.prototype,`entityId`,void 0),l([p({type:m.STRING,allowNull:!1}),c(`design:type`,String)],D.prototype,`entityType`,void 0),l([p({type:m.STRING,allowNull:!1}),c(`design:type`,String)],D.prototype,`modelType`,void 0),l([p({type:m.TEXT}),c(`design:type`,String)],D.prototype,`description`,void 0),l([p({type:m.BOOLEAN,defaultValue:!1}),c(`design:type`,Boolean)],D.prototype,`required`,void 0),l([p({type:m.BOOLEAN,defaultValue:!1}),c(`design:type`,Boolean)],D.prototype,`disabled`,void 0),l([p({type:m.JSONB,allowNull:!0}),c(`design:type`,Object)],D.prototype,`defaultValue`,void 0),l([p({type:m.DATE,allowNull:!1}),c(`design:type`,typeof(S=typeof Date<`u`&&Date)==`function`?S:Object)],D.prototype,`createdAt`,void 0),l([p({type:m.DATE,allowNull:!0}),c(`design:type`,typeof(C=typeof Date<`u`&&Date)==`function`?C:Object)],D.prototype,`updatedAt`,void 0),l([p({type:m.DATE,allowNull:!0}),c(`design:type`,typeof(w=typeof Date<`u`&&Date)==`function`?w:Object)],D.prototype,`deletedAt`,void 0),l([p({type:m.BOOLEAN,defaultValue:!1,allowNull:!1}),c(`design:type`,Boolean)],D.prototype,`blockEditingFromUI`,void 0),l([g(()=>u),c(`design:type`,Array)],D.prototype,`values`,void 0),l([f,c(`design:type`,Function),c(`design:paramtypes`,[typeof(T=D!==void 0&&D)==`function`?T:Object]),c(`design:returntype`,void 0)],D,`displayNameDefaultValue`,null),l([d,c(`design:type`,Function),c(`design:paramtypes`,[typeof(E=D!==void 0&&D)==`function`?E:Object,Object]),c(`design:returntype`,void 0)],D,`afterSaveHandler`,null),D=l([h(()=>({where:{disabled:!1}})),b({tableName:`custom_field_definitions`,modelName:`CustomFieldDefinition`,indexes:[{name:`unique_name_model_type`,fields:[`model_type`,`entity_id`,`name`],unique:!0}],timestamps:!0,validate:{validationByType(){if(!this.validation&&n[this.fieldType])throw e.error(`No custom validation for custom field type ${this.fieldType} found`),new o(`Validation provided for "${this.fieldType}" is not supported`)}}})],D);var O=D;export{O as default};
1
+ import e from"../utils/logger/index.js";import{CustomFieldDefinitionType as t}from"../utils/constants/index.js";import{CustomValidationTypes as n}from"../utils/validations/validators/index.js";import{sendDimEvent as r}from"../events/index.js";import{InvalidValueError as i,UnsupportedCustomFieldTypeError as a,UnsupportedCustomValidationError as o}from"../errors/index.js";import{validateValue as s}from"../utils/validations/index.js";import{__decorateMetadata as c}from"../_virtual/_@oxc-project_runtime@0.97.0/helpers/decorateMetadata.js";import{__decorate as l}from"../_virtual/_@oxc-project_runtime@0.97.0/helpers/decorate.js";import u from"./CustomFieldValue.js";import"./index.js";import{AfterSave as d,BeforeCreate as f,Column as p,DataType as m,DefaultScope as h,HasMany as g,Is as _,Model as v,PrimaryKey as y,Table as b}from"sequelize-typescript";var x,S,C,w,T,E;let D=class extends v{static displayNameDefaultValue(e){if(e?.displayName||(e.displayName=e.name),![null,void 0].includes(e.defaultValue)){let t=s(e.defaultValue,e.fieldType,e.validation);if(t.error)throw new i(e.defaultValue,e.name,t.error)}}static afterSaveHandler(e,t){t.transaction?t.transaction.afterCommit(()=>r(e)):r(e)}};l([y,p({type:m.UUID,defaultValue:m.UUIDV4,allowNull:!1}),c(`design:type`,String)],D.prototype,`id`,void 0),l([p({type:m.STRING,allowNull:!1}),c(`design:type`,String)],D.prototype,`name`,void 0),l([p({type:m.STRING}),c(`design:type`,String)],D.prototype,`displayName`,void 0),l([_(`SupportedType`,e=>{if(!Object.values(t).includes(e))throw new a(`"${e}" is not a supported type.`)}),p({type:m.STRING,allowNull:!1}),c(`design:type`,typeof(x=t!==void 0&&t)==`function`?x:Object)],D.prototype,`fieldType`,void 0),l([p({type:m.JSONB}),c(`design:type`,Object)],D.prototype,`validation`,void 0),l([p({type:m.UUID,allowNull:!1}),c(`design:type`,String)],D.prototype,`entityId`,void 0),l([p({type:m.STRING,allowNull:!1}),c(`design:type`,String)],D.prototype,`entityType`,void 0),l([p({type:m.STRING,allowNull:!1}),c(`design:type`,String)],D.prototype,`modelType`,void 0),l([p({type:m.TEXT}),c(`design:type`,String)],D.prototype,`description`,void 0),l([p({type:m.BOOLEAN,defaultValue:!1}),c(`design:type`,Boolean)],D.prototype,`required`,void 0),l([p({type:m.BOOLEAN,defaultValue:!1}),c(`design:type`,Boolean)],D.prototype,`disabled`,void 0),l([p({type:m.JSONB,allowNull:!0}),c(`design:type`,Object)],D.prototype,`defaultValue`,void 0),l([p({type:m.DATE,allowNull:!1}),c(`design:type`,typeof(S=typeof Date<`u`&&Date)==`function`?S:Object)],D.prototype,`createdAt`,void 0),l([p({type:m.DATE,allowNull:!0}),c(`design:type`,typeof(C=typeof Date<`u`&&Date)==`function`?C:Object)],D.prototype,`updatedAt`,void 0),l([p({type:m.DATE,allowNull:!0}),c(`design:type`,typeof(w=typeof Date<`u`&&Date)==`function`?w:Object)],D.prototype,`deletedAt`,void 0),l([p({type:m.BOOLEAN,defaultValue:!1,allowNull:!1}),c(`design:type`,Boolean)],D.prototype,`blockEditingFromUI`,void 0),l([g(()=>u),c(`design:type`,Array)],D.prototype,`values`,void 0),l([f,c(`design:type`,Function),c(`design:paramtypes`,[typeof(T=D!==void 0&&D)==`function`?T:Object]),c(`design:returntype`,void 0)],D,`displayNameDefaultValue`,null),l([d,c(`design:type`,Function),c(`design:paramtypes`,[typeof(E=D!==void 0&&D)==`function`?E:Object,Object]),c(`design:returntype`,void 0)],D,`afterSaveHandler`,null),D=l([h(()=>({where:{disabled:!1}})),b({tableName:`custom_field_definitions`,modelName:`CustomFieldDefinition`,indexes:[{name:`unique_name_model_type`,fields:[`model_type`,`entity_id`,`name`],unique:!0}],timestamps:!0,validate:{validationByType(){if(!this.validation&&n[this.fieldType])throw e.error(`No custom validation for custom field type ${this.fieldType} found`),new o(`Validation provided for "${this.fieldType}" is not supported`)}}})],D);var O=D;export{O as default};
2
2
  //# sourceMappingURL=CustomFieldDefinition.js.map