@autofleet/sadot 1.5.2 → 1.6.0-alpha.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.
@@ -0,0 +1 @@
1
+ import{createRequire as e}from"node:module";var t=e(import.meta.url);export{t as __require};
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/CustomFieldValue.cjs`),r=require(`./models/CustomFieldDefinition.cjs`),i=require(`./models/CustomFieldEntries.cjs`),a=require(`./models/CustomValidator.cjs`),o=require(`./models/index.cjs`),s=require(`./mat-path-state.cjs`),c=require(`./api/index.cjs`),l=require(`./utils/db/index.cjs`),u=require(`./utils/helpers/index.cjs`),d=require(`./scopes/filter.cjs`),f=require(`./utils/init.cjs`),p=require(`./init-state.cjs`),m=require(`./utils/validations/schema/custom-fields.cjs`),h=new p.SadotInitializationState,g=async(t,n,r)=>{e.tryAddingTraceIdMiddleware();let{models:i,useCustomFieldsEntries:a,useModelTypeMapping:u,isMatPathEnabled:d}=r;s.matPathState.isMatPathEnabled=d,t&&t.use(`/api`,c.default);let p=r.sequelize??l.default(r.databaseConfig);return process.env.NODE_ENV===`test`&&await o.initTestModels(p),f.addHooks(i,n,{useCustomFieldsEntries:a}),await o.initTables(p,r.getUser,{useCustomFieldsEntries:a,useModelTypeMapping:u,isMatPathEnabled:d}),f.addScopes(i,n,{useCustomFieldsEntries:a}),f.applyCustomAssociation(i),e.default.debug(`sadot - custom fields finished initializing with models`,i),p},_=async(e,t,n)=>{let r=g(e,t,n);return h.setInitPromise(r,!n.sequelize),await r};var v=_;const y=(e,t)=>{f.removeHooks(e,t)};exports.CUSTOM_FIELDS_FILTER_SCOPE=t.CUSTOM_FIELDS_FILTER_SCOPE,exports.CustomFieldDefinition=r.default,exports.CustomFieldDefinitionType=t.CustomFieldDefinitionType,exports.CustomFieldEntries=i.default,exports.CustomFieldValue=n.default,exports.CustomFieldsSchema=m.CustomFieldsSchema,exports.CustomValidator=a.default,exports.customFieldsSortScope=d.customFieldsSortScope,exports.default=v,exports.disableCustomFields=y,exports.generateCustomFieldSearchQueryPayload=u.generateCustomFieldSearchQueryPayload,exports.generateRandomString=u.generateRandomString,exports.sadotInitState=h,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/CustomFieldValue.cjs`),r=require(`./models/CustomFieldDefinition.cjs`),i=require(`./models/CustomFieldEntries.cjs`),a=require(`./models/CustomValidator.cjs`),o=require(`./models/index.cjs`),s=require(`./mat-path-state.cjs`),c=require(`./api/index.cjs`),l=require(`./utils/db/index.cjs`),u=require(`./utils/helpers/index.cjs`),d=require(`./scopes/filter.cjs`),f=require(`./utils/init.cjs`),p=require(`./init-state.cjs`),m=require(`./utils/validations/schema/custom-fields.cjs`),h=new p.SadotInitializationState,g=async(t,n,r)=>{e.tryAddingTraceIdMiddleware();let{models:i,useCustomFieldsEntries:a,useModelTypeMapping:u,isMatPathEnabled:d,useUmzugMigrations:p}=r;s.matPathState.isMatPathEnabled=d,t&&t.use(`/api`,c.default);let m=r.sequelize??l.default(r.databaseConfig);return process.env.NODE_ENV===`test`&&await o.initTestModels(m),f.addHooks(i,n,{useCustomFieldsEntries:a}),await o.initTables(m,r.getUser,{useCustomFieldsEntries:a,useModelTypeMapping:u,isMatPathEnabled:d,useUmzugMigrations:p}),f.addScopes(i,n,{useCustomFieldsEntries:a}),f.applyCustomAssociation(i),e.default.debug(`sadot - custom fields finished initializing with models`,i),m},_=async(e,t,n)=>{let r=g(e,t,n);return h.setInitPromise(r,!n.sequelize),await r};var v=_;const y=(e,t)=>{f.removeHooks(e,t)};exports.CUSTOM_FIELDS_FILTER_SCOPE=t.CUSTOM_FIELDS_FILTER_SCOPE,exports.CustomFieldDefinition=r.default,exports.CustomFieldDefinitionType=t.CustomFieldDefinitionType,exports.CustomFieldEntries=i.default,exports.CustomFieldValue=n.default,exports.CustomFieldsSchema=m.CustomFieldsSchema,exports.CustomValidator=a.default,exports.customFieldsSortScope=d.customFieldsSortScope,exports.default=v,exports.disableCustomFields=y,exports.generateCustomFieldSearchQueryPayload=u.generateCustomFieldSearchQueryPayload,exports.generateRandomString=u.generateRandomString,exports.sadotInitState=h,exports.supportedEntities=t.supportedEntities;
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["sadotInitState: SadotInitializationState","SadotInitializationState","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';\nimport { SadotInitializationState } from './init-state';\nimport { matPathState } from './mat-path-state';\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\nexport const sadotInitState: SadotInitializationState = new SadotInitializationState();\n\n/**\n * Internal implementation of custom fields initialization\n * Contains all the business logic without state tracking\n */\nconst internalUseCustomFields = async (\n app: Pick<Application, 'use'> | null,\n getModel: ModelFetcher,\n options: CustomFieldOptions,\n): Promise<Sequelize> => {\n tryAddingTraceIdMiddleware();\n const { models, useCustomFieldsEntries, useModelTypeMapping, isMatPathEnabled } = options;\n matPathState.isMatPathEnabled = isMatPathEnabled;\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, isMatPathEnabled });\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\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 const initPromise = internalUseCustomFields(app, getModel, options);\n\n sadotInitState.setInitPromise(initPromise, !options.sequelize);\n\n return await initPromise;\n};\n\nexport default useCustomFields;\n\nexport const disableCustomFields = (models: Models[], getModel: ModelFetcher): void => {\n removeHooks(models, getModel);\n};\n"],"mappings":"6nBA6BaA,EAA2C,IAAIC,EAAAA,yBAMtD,EAA0B,MAC9B,EACA,EACA,IACuB,CACvB,EAAA,4BAA4B,CAC5B,GAAM,CAAE,SAAQ,yBAAwB,sBAAqB,oBAAqB,EAClF,EAAA,aAAa,iBAAmB,EAC5B,GACF,EAAI,IAAI,OAAQC,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,mBAAkB,CAAC,CAC/G,EAAA,UAAU,EAAQ,EAAU,CAAE,yBAAwB,CAAC,CACvD,EAAA,uBAAuB,EAAO,CAE9B,EAAA,QAAO,MAAM,0DAA2D,EAAO,CACxE,GAOH,EAAkB,MACtB,EACA,EACA,IACuB,CACvB,IAAM,EAAc,EAAwB,EAAK,EAAU,EAAQ,CAInE,OAFA,EAAe,eAAe,EAAa,CAAC,EAAQ,UAAU,CAEvD,MAAM,GAGf,IAAA,EAAe,EAEf,MAAa,GAAuB,EAAkB,IAAiC,CACrF,EAAA,YAAY,EAAQ,EAAS"}
1
+ {"version":3,"file":"index.cjs","names":["sadotInitState: SadotInitializationState","SadotInitializationState","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';\nimport { SadotInitializationState } from './init-state';\nimport { matPathState } from './mat-path-state';\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\nexport const sadotInitState: SadotInitializationState = new SadotInitializationState();\n\n/**\n * Internal implementation of custom fields initialization\n * Contains all the business logic without state tracking\n */\nconst internalUseCustomFields = async (\n app: Pick<Application, 'use'> | null,\n getModel: ModelFetcher,\n options: CustomFieldOptions,\n): Promise<Sequelize> => {\n tryAddingTraceIdMiddleware();\n const { models, useCustomFieldsEntries, useModelTypeMapping, isMatPathEnabled, useUmzugMigrations } = options;\n matPathState.isMatPathEnabled = isMatPathEnabled;\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, isMatPathEnabled, useUmzugMigrations });\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\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 const initPromise = internalUseCustomFields(app, getModel, options);\n\n sadotInitState.setInitPromise(initPromise, !options.sequelize);\n\n return await initPromise;\n};\n\nexport default useCustomFields;\n\nexport const disableCustomFields = (models: Models[], getModel: ModelFetcher): void => {\n removeHooks(models, getModel);\n};\n"],"mappings":"6nBA6BaA,EAA2C,IAAIC,EAAAA,yBAMtD,EAA0B,MAC9B,EACA,EACA,IACuB,CACvB,EAAA,4BAA4B,CAC5B,GAAM,CAAE,SAAQ,yBAAwB,sBAAqB,mBAAkB,sBAAuB,EACtG,EAAA,aAAa,iBAAmB,EAC5B,GACF,EAAI,IAAI,OAAQC,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,mBAAkB,qBAAoB,CAAC,CACnI,EAAA,UAAU,EAAQ,EAAU,CAAE,yBAAwB,CAAC,CACvD,EAAA,uBAAuB,EAAO,CAE9B,EAAA,QAAO,MAAM,0DAA2D,EAAO,CACxE,GAOH,EAAkB,MACtB,EACA,EACA,IACuB,CACvB,IAAM,EAAc,EAAwB,EAAK,EAAU,EAAQ,CAInE,OAFA,EAAe,eAAe,EAAa,CAAC,EAAQ,UAAU,CAEvD,MAAM,GAGf,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/CustomFieldValue.js";import o from"./models/CustomFieldDefinition.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{matPathState as d}from"./mat-path-state.js";import f from"./api/index.js";import p from"./utils/db/index.js";import{generateCustomFieldSearchQueryPayload as m,generateRandomString as h}from"./utils/helpers/index.js";import{customFieldsSortScope as g}from"./scopes/filter.js";import{addHooks as _,addScopes as v,applyCustomAssociation as y,removeHooks as b}from"./utils/init.js";import{SadotInitializationState as x}from"./init-state.js";import{CustomFieldsSchema as S}from"./utils/validations/schema/custom-fields.js";const C=new x,w=async(n,r,i)=>{t();let{models:a,useCustomFieldsEntries:o,useModelTypeMapping:s,isMatPathEnabled:c}=i;d.isMatPathEnabled=c,n&&n.use(`/api`,f);let m=i.sequelize??p(i.databaseConfig);return process.env.NODE_ENV===`test`&&await u(m),_(a,r,{useCustomFieldsEntries:o}),await l(m,i.getUser,{useCustomFieldsEntries:o,useModelTypeMapping:s,isMatPathEnabled:c}),v(a,r,{useCustomFieldsEntries:o}),y(a),e.debug(`sadot - custom fields finished initializing with models`,a),m};var T=async(e,t,n)=>{let r=w(e,t,n);return C.setInitPromise(r,!n.sequelize),await r};const E=(e,t)=>{b(e,t)};export{n as CUSTOM_FIELDS_FILTER_SCOPE,o as CustomFieldDefinition,r as CustomFieldDefinitionType,s as CustomFieldEntries,a as CustomFieldValue,S as CustomFieldsSchema,c as CustomValidator,g as customFieldsSortScope,T as default,E as disableCustomFields,m as generateCustomFieldSearchQueryPayload,h as generateRandomString,C as sadotInitState,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/CustomFieldValue.js";import o from"./models/CustomFieldDefinition.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{matPathState as d}from"./mat-path-state.js";import f from"./api/index.js";import p from"./utils/db/index.js";import{generateCustomFieldSearchQueryPayload as m,generateRandomString as h}from"./utils/helpers/index.js";import{customFieldsSortScope as g}from"./scopes/filter.js";import{addHooks as _,addScopes as v,applyCustomAssociation as y,removeHooks as b}from"./utils/init.js";import{SadotInitializationState as x}from"./init-state.js";import{CustomFieldsSchema as S}from"./utils/validations/schema/custom-fields.js";const C=new x,w=async(n,r,i)=>{t();let{models:a,useCustomFieldsEntries:o,useModelTypeMapping:s,isMatPathEnabled:c,useUmzugMigrations:m}=i;d.isMatPathEnabled=c,n&&n.use(`/api`,f);let h=i.sequelize??p(i.databaseConfig);return process.env.NODE_ENV===`test`&&await u(h),_(a,r,{useCustomFieldsEntries:o}),await l(h,i.getUser,{useCustomFieldsEntries:o,useModelTypeMapping:s,isMatPathEnabled:c,useUmzugMigrations:m}),v(a,r,{useCustomFieldsEntries:o}),y(a),e.debug(`sadot - custom fields finished initializing with models`,a),h};var T=async(e,t,n)=>{let r=w(e,t,n);return C.setInitPromise(r,!n.sequelize),await r};const E=(e,t)=>{b(e,t)};export{n as CUSTOM_FIELDS_FILTER_SCOPE,o as CustomFieldDefinition,r as CustomFieldDefinitionType,s as CustomFieldEntries,a as CustomFieldValue,S as CustomFieldsSchema,c as CustomValidator,g as customFieldsSortScope,T as default,E as disableCustomFields,m as generateCustomFieldSearchQueryPayload,h as generateRandomString,C as sadotInitState,i as supportedEntities};
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["sadotInitState: SadotInitializationState","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';\nimport { SadotInitializationState } from './init-state';\nimport { matPathState } from './mat-path-state';\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\nexport const sadotInitState: SadotInitializationState = new SadotInitializationState();\n\n/**\n * Internal implementation of custom fields initialization\n * Contains all the business logic without state tracking\n */\nconst internalUseCustomFields = async (\n app: Pick<Application, 'use'> | null,\n getModel: ModelFetcher,\n options: CustomFieldOptions,\n): Promise<Sequelize> => {\n tryAddingTraceIdMiddleware();\n const { models, useCustomFieldsEntries, useModelTypeMapping, isMatPathEnabled } = options;\n matPathState.isMatPathEnabled = isMatPathEnabled;\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, isMatPathEnabled });\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\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 const initPromise = internalUseCustomFields(app, getModel, options);\n\n sadotInitState.setInitPromise(initPromise, !options.sequelize);\n\n return await initPromise;\n};\n\nexport default useCustomFields;\n\nexport const disableCustomFields = (models: Models[], getModel: ModelFetcher): void => {\n removeHooks(models, getModel);\n};\n"],"mappings":"48BA6BA,MAAaA,EAA2C,IAAI,EAMtD,EAA0B,MAC9B,EACA,EACA,IACuB,CACvB,GAA4B,CAC5B,GAAM,CAAE,SAAQ,yBAAwB,sBAAqB,oBAAqB,EAClF,EAAa,iBAAmB,EAC5B,GACF,EAAI,IAAI,OAAQC,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,mBAAkB,CAAC,CAC/G,EAAU,EAAQ,EAAU,CAAE,yBAAwB,CAAC,CACvD,EAAuB,EAAO,CAE9B,EAAO,MAAM,0DAA2D,EAAO,CACxE,GAmBT,IAAA,EAZwB,MACtB,EACA,EACA,IACuB,CACvB,IAAM,EAAc,EAAwB,EAAK,EAAU,EAAQ,CAInE,OAFA,EAAe,eAAe,EAAa,CAAC,EAAQ,UAAU,CAEvD,MAAM,GAKf,MAAa,GAAuB,EAAkB,IAAiC,CACrF,EAAY,EAAQ,EAAS"}
1
+ {"version":3,"file":"index.js","names":["sadotInitState: SadotInitializationState","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';\nimport { SadotInitializationState } from './init-state';\nimport { matPathState } from './mat-path-state';\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\nexport const sadotInitState: SadotInitializationState = new SadotInitializationState();\n\n/**\n * Internal implementation of custom fields initialization\n * Contains all the business logic without state tracking\n */\nconst internalUseCustomFields = async (\n app: Pick<Application, 'use'> | null,\n getModel: ModelFetcher,\n options: CustomFieldOptions,\n): Promise<Sequelize> => {\n tryAddingTraceIdMiddleware();\n const { models, useCustomFieldsEntries, useModelTypeMapping, isMatPathEnabled, useUmzugMigrations } = options;\n matPathState.isMatPathEnabled = isMatPathEnabled;\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, isMatPathEnabled, useUmzugMigrations });\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\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 const initPromise = internalUseCustomFields(app, getModel, options);\n\n sadotInitState.setInitPromise(initPromise, !options.sequelize);\n\n return await initPromise;\n};\n\nexport default useCustomFields;\n\nexport const disableCustomFields = (models: Models[], getModel: ModelFetcher): void => {\n removeHooks(models, getModel);\n};\n"],"mappings":"48BA6BA,MAAaA,EAA2C,IAAI,EAMtD,EAA0B,MAC9B,EACA,EACA,IACuB,CACvB,GAA4B,CAC5B,GAAM,CAAE,SAAQ,yBAAwB,sBAAqB,mBAAkB,sBAAuB,EACtG,EAAa,iBAAmB,EAC5B,GACF,EAAI,IAAI,OAAQC,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,mBAAkB,qBAAoB,CAAC,CACnI,EAAU,EAAQ,EAAU,CAAE,yBAAwB,CAAC,CACvD,EAAuB,EAAO,CAE9B,EAAO,MAAM,0DAA2D,EAAO,CACxE,GAmBT,IAAA,EAZwB,MACtB,EACA,EACA,IACuB,CACvB,IAAM,EAAc,EAAwB,EAAK,EAAU,EAAQ,CAInE,OAFA,EAAe,eAAe,EAAa,CAAC,EAAQ,UAAU,CAEvD,MAAM,GAKf,MAAa,GAAuB,EAAkB,IAAiC,CACrF,EAAY,EAAQ,EAAS"}
@@ -0,0 +1,52 @@
1
+ const e=async({context:e})=>{let{sequelize:t}=e;await t.query(`
2
+ CREATE TABLE IF NOT EXISTS "custom_field_definitions" (
3
+ "id" UUID NOT NULL DEFAULT gen_random_uuid(),
4
+ "name" VARCHAR NOT NULL,
5
+ "display_name" VARCHAR,
6
+ "field_type" VARCHAR NOT NULL,
7
+ "validation" JSONB,
8
+ "entity_id" UUID NOT NULL,
9
+ "entity_type" VARCHAR NOT NULL,
10
+ "model_type" VARCHAR NOT NULL,
11
+ "description" TEXT,
12
+ "required" BOOLEAN DEFAULT false,
13
+ "disabled" BOOLEAN DEFAULT false,
14
+ "default_value" JSONB,
15
+ "block_editing_from_ui" BOOLEAN NOT NULL DEFAULT false,
16
+ "created_at" TIMESTAMPTZ NOT NULL,
17
+ "updated_at" TIMESTAMPTZ,
18
+ "deleted_at" TIMESTAMPTZ,
19
+ PRIMARY KEY ("id")
20
+ )
21
+ `),await t.query(`
22
+ CREATE UNIQUE INDEX IF NOT EXISTS "unique_name_model_type"
23
+ ON "custom_field_definitions" ("model_type", "entity_id", "name")
24
+ `),await t.query(`
25
+ CREATE TABLE IF NOT EXISTS "custom_field_values" (
26
+ "model_id" UUID NOT NULL,
27
+ "custom_field_definition_id" UUID NOT NULL
28
+ REFERENCES "custom_field_definitions" ("id"),
29
+ "value" JSONB,
30
+ "created_at" TIMESTAMPTZ NOT NULL,
31
+ "updated_at" TIMESTAMPTZ,
32
+ "deleted_at" TIMESTAMPTZ,
33
+ PRIMARY KEY ("model_id", "custom_field_definition_id")
34
+ )
35
+ `),await t.query(`
36
+ CREATE INDEX IF NOT EXISTS "idx_custom_field_values_active_definition_id"
37
+ ON "custom_field_values" ("custom_field_definition_id")
38
+ WHERE "deleted_at" IS NULL
39
+ `),await t.query(`
40
+ CREATE TABLE IF NOT EXISTS "custom_validators" (
41
+ "id" UUID NOT NULL DEFAULT gen_random_uuid(),
42
+ "entity_id" UUID NOT NULL,
43
+ "entity_type" VARCHAR NOT NULL,
44
+ "model_type" VARCHAR NOT NULL,
45
+ "schema" JSONB NOT NULL,
46
+ "disabled" BOOLEAN NOT NULL DEFAULT false,
47
+ "created_at" TIMESTAMPTZ NOT NULL,
48
+ "updated_at" TIMESTAMPTZ,
49
+ PRIMARY KEY ("id")
50
+ )
51
+ `)},t=async({context:e})=>{let{sequelize:t}=e;await t.query(`DROP TABLE IF EXISTS "custom_field_values"`),await t.query(`DROP TABLE IF EXISTS "custom_field_definitions"`),await t.query(`DROP TABLE IF EXISTS "custom_validators"`)};exports.down=t,exports.up=e;
52
+ //# sourceMappingURL=001-create-core-tables.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"001-create-core-tables.cjs","names":["up: MigrationFn<QueryInterface>","down: MigrationFn<QueryInterface>"],"sources":["../../src/migrations/001-create-core-tables.ts"],"sourcesContent":["import type { MigrationFn } from 'umzug';\nimport type { QueryInterface } from 'sequelize';\n\nexport const up: MigrationFn<QueryInterface> = async ({ context: queryInterface }) => {\n const { sequelize } = queryInterface;\n\n await sequelize.query(`\n CREATE TABLE IF NOT EXISTS \"custom_field_definitions\" (\n \"id\" UUID NOT NULL DEFAULT gen_random_uuid(),\n \"name\" VARCHAR NOT NULL,\n \"display_name\" VARCHAR,\n \"field_type\" VARCHAR NOT NULL,\n \"validation\" JSONB,\n \"entity_id\" UUID NOT NULL,\n \"entity_type\" VARCHAR NOT NULL,\n \"model_type\" VARCHAR NOT NULL,\n \"description\" TEXT,\n \"required\" BOOLEAN DEFAULT false,\n \"disabled\" BOOLEAN DEFAULT false,\n \"default_value\" JSONB,\n \"block_editing_from_ui\" BOOLEAN NOT NULL DEFAULT false,\n \"created_at\" TIMESTAMPTZ NOT NULL,\n \"updated_at\" TIMESTAMPTZ,\n \"deleted_at\" TIMESTAMPTZ,\n PRIMARY KEY (\"id\")\n )\n `);\n\n await sequelize.query(`\n CREATE UNIQUE INDEX IF NOT EXISTS \"unique_name_model_type\"\n ON \"custom_field_definitions\" (\"model_type\", \"entity_id\", \"name\")\n `);\n\n await sequelize.query(`\n CREATE TABLE IF NOT EXISTS \"custom_field_values\" (\n \"model_id\" UUID NOT NULL,\n \"custom_field_definition_id\" UUID NOT NULL\n REFERENCES \"custom_field_definitions\" (\"id\"),\n \"value\" JSONB,\n \"created_at\" TIMESTAMPTZ NOT NULL,\n \"updated_at\" TIMESTAMPTZ,\n \"deleted_at\" TIMESTAMPTZ,\n PRIMARY KEY (\"model_id\", \"custom_field_definition_id\")\n )\n `);\n\n await sequelize.query(`\n CREATE INDEX IF NOT EXISTS \"idx_custom_field_values_active_definition_id\"\n ON \"custom_field_values\" (\"custom_field_definition_id\")\n WHERE \"deleted_at\" IS NULL\n `);\n\n await sequelize.query(`\n CREATE TABLE IF NOT EXISTS \"custom_validators\" (\n \"id\" UUID NOT NULL DEFAULT gen_random_uuid(),\n \"entity_id\" UUID NOT NULL,\n \"entity_type\" VARCHAR NOT NULL,\n \"model_type\" VARCHAR NOT NULL,\n \"schema\" JSONB NOT NULL,\n \"disabled\" BOOLEAN NOT NULL DEFAULT false,\n \"created_at\" TIMESTAMPTZ NOT NULL,\n \"updated_at\" TIMESTAMPTZ,\n PRIMARY KEY (\"id\")\n )\n `);\n};\n\nexport const down: MigrationFn<QueryInterface> = async ({ context: queryInterface }) => {\n const { sequelize } = queryInterface;\n await sequelize.query('DROP TABLE IF EXISTS \"custom_field_values\"');\n await sequelize.query('DROP TABLE IF EXISTS \"custom_field_definitions\"');\n await sequelize.query('DROP TABLE IF EXISTS \"custom_validators\"');\n};\n"],"mappings":"AAGA,MAAaA,EAAkC,MAAO,CAAE,QAAS,KAAqB,CACpF,GAAM,CAAE,aAAc,EAEtB,MAAM,EAAU,MAAM;;;;;;;;;;;;;;;;;;;;IAoBpB,CAEF,MAAM,EAAU,MAAM;;;IAGpB,CAEF,MAAM,EAAU,MAAM;;;;;;;;;;;IAWpB,CAEF,MAAM,EAAU,MAAM;;;;IAIpB,CAEF,MAAM,EAAU,MAAM;;;;;;;;;;;;IAYpB,EAGSC,EAAoC,MAAO,CAAE,QAAS,KAAqB,CACtF,GAAM,CAAE,aAAc,EACtB,MAAM,EAAU,MAAM,6CAA6C,CACnE,MAAM,EAAU,MAAM,kDAAkD,CACxE,MAAM,EAAU,MAAM,2CAA2C"}
@@ -0,0 +1,52 @@
1
+ const e=async({context:e})=>{let{sequelize:t}=e;await t.query(`
2
+ CREATE TABLE IF NOT EXISTS "custom_field_definitions" (
3
+ "id" UUID NOT NULL DEFAULT gen_random_uuid(),
4
+ "name" VARCHAR NOT NULL,
5
+ "display_name" VARCHAR,
6
+ "field_type" VARCHAR NOT NULL,
7
+ "validation" JSONB,
8
+ "entity_id" UUID NOT NULL,
9
+ "entity_type" VARCHAR NOT NULL,
10
+ "model_type" VARCHAR NOT NULL,
11
+ "description" TEXT,
12
+ "required" BOOLEAN DEFAULT false,
13
+ "disabled" BOOLEAN DEFAULT false,
14
+ "default_value" JSONB,
15
+ "block_editing_from_ui" BOOLEAN NOT NULL DEFAULT false,
16
+ "created_at" TIMESTAMPTZ NOT NULL,
17
+ "updated_at" TIMESTAMPTZ,
18
+ "deleted_at" TIMESTAMPTZ,
19
+ PRIMARY KEY ("id")
20
+ )
21
+ `),await t.query(`
22
+ CREATE UNIQUE INDEX IF NOT EXISTS "unique_name_model_type"
23
+ ON "custom_field_definitions" ("model_type", "entity_id", "name")
24
+ `),await t.query(`
25
+ CREATE TABLE IF NOT EXISTS "custom_field_values" (
26
+ "model_id" UUID NOT NULL,
27
+ "custom_field_definition_id" UUID NOT NULL
28
+ REFERENCES "custom_field_definitions" ("id"),
29
+ "value" JSONB,
30
+ "created_at" TIMESTAMPTZ NOT NULL,
31
+ "updated_at" TIMESTAMPTZ,
32
+ "deleted_at" TIMESTAMPTZ,
33
+ PRIMARY KEY ("model_id", "custom_field_definition_id")
34
+ )
35
+ `),await t.query(`
36
+ CREATE INDEX IF NOT EXISTS "idx_custom_field_values_active_definition_id"
37
+ ON "custom_field_values" ("custom_field_definition_id")
38
+ WHERE "deleted_at" IS NULL
39
+ `),await t.query(`
40
+ CREATE TABLE IF NOT EXISTS "custom_validators" (
41
+ "id" UUID NOT NULL DEFAULT gen_random_uuid(),
42
+ "entity_id" UUID NOT NULL,
43
+ "entity_type" VARCHAR NOT NULL,
44
+ "model_type" VARCHAR NOT NULL,
45
+ "schema" JSONB NOT NULL,
46
+ "disabled" BOOLEAN NOT NULL DEFAULT false,
47
+ "created_at" TIMESTAMPTZ NOT NULL,
48
+ "updated_at" TIMESTAMPTZ,
49
+ PRIMARY KEY ("id")
50
+ )
51
+ `)},t=async({context:e})=>{let{sequelize:t}=e;await t.query(`DROP TABLE IF EXISTS "custom_field_values"`),await t.query(`DROP TABLE IF EXISTS "custom_field_definitions"`),await t.query(`DROP TABLE IF EXISTS "custom_validators"`)};export{t as down,e as up};
52
+ //# sourceMappingURL=001-create-core-tables.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"001-create-core-tables.js","names":["up: MigrationFn<QueryInterface>","down: MigrationFn<QueryInterface>"],"sources":["../../src/migrations/001-create-core-tables.ts"],"sourcesContent":["import type { MigrationFn } from 'umzug';\nimport type { QueryInterface } from 'sequelize';\n\nexport const up: MigrationFn<QueryInterface> = async ({ context: queryInterface }) => {\n const { sequelize } = queryInterface;\n\n await sequelize.query(`\n CREATE TABLE IF NOT EXISTS \"custom_field_definitions\" (\n \"id\" UUID NOT NULL DEFAULT gen_random_uuid(),\n \"name\" VARCHAR NOT NULL,\n \"display_name\" VARCHAR,\n \"field_type\" VARCHAR NOT NULL,\n \"validation\" JSONB,\n \"entity_id\" UUID NOT NULL,\n \"entity_type\" VARCHAR NOT NULL,\n \"model_type\" VARCHAR NOT NULL,\n \"description\" TEXT,\n \"required\" BOOLEAN DEFAULT false,\n \"disabled\" BOOLEAN DEFAULT false,\n \"default_value\" JSONB,\n \"block_editing_from_ui\" BOOLEAN NOT NULL DEFAULT false,\n \"created_at\" TIMESTAMPTZ NOT NULL,\n \"updated_at\" TIMESTAMPTZ,\n \"deleted_at\" TIMESTAMPTZ,\n PRIMARY KEY (\"id\")\n )\n `);\n\n await sequelize.query(`\n CREATE UNIQUE INDEX IF NOT EXISTS \"unique_name_model_type\"\n ON \"custom_field_definitions\" (\"model_type\", \"entity_id\", \"name\")\n `);\n\n await sequelize.query(`\n CREATE TABLE IF NOT EXISTS \"custom_field_values\" (\n \"model_id\" UUID NOT NULL,\n \"custom_field_definition_id\" UUID NOT NULL\n REFERENCES \"custom_field_definitions\" (\"id\"),\n \"value\" JSONB,\n \"created_at\" TIMESTAMPTZ NOT NULL,\n \"updated_at\" TIMESTAMPTZ,\n \"deleted_at\" TIMESTAMPTZ,\n PRIMARY KEY (\"model_id\", \"custom_field_definition_id\")\n )\n `);\n\n await sequelize.query(`\n CREATE INDEX IF NOT EXISTS \"idx_custom_field_values_active_definition_id\"\n ON \"custom_field_values\" (\"custom_field_definition_id\")\n WHERE \"deleted_at\" IS NULL\n `);\n\n await sequelize.query(`\n CREATE TABLE IF NOT EXISTS \"custom_validators\" (\n \"id\" UUID NOT NULL DEFAULT gen_random_uuid(),\n \"entity_id\" UUID NOT NULL,\n \"entity_type\" VARCHAR NOT NULL,\n \"model_type\" VARCHAR NOT NULL,\n \"schema\" JSONB NOT NULL,\n \"disabled\" BOOLEAN NOT NULL DEFAULT false,\n \"created_at\" TIMESTAMPTZ NOT NULL,\n \"updated_at\" TIMESTAMPTZ,\n PRIMARY KEY (\"id\")\n )\n `);\n};\n\nexport const down: MigrationFn<QueryInterface> = async ({ context: queryInterface }) => {\n const { sequelize } = queryInterface;\n await sequelize.query('DROP TABLE IF EXISTS \"custom_field_values\"');\n await sequelize.query('DROP TABLE IF EXISTS \"custom_field_definitions\"');\n await sequelize.query('DROP TABLE IF EXISTS \"custom_validators\"');\n};\n"],"mappings":"AAGA,MAAaA,EAAkC,MAAO,CAAE,QAAS,KAAqB,CACpF,GAAM,CAAE,aAAc,EAEtB,MAAM,EAAU,MAAM;;;;;;;;;;;;;;;;;;;;IAoBpB,CAEF,MAAM,EAAU,MAAM;;;IAGpB,CAEF,MAAM,EAAU,MAAM;;;;;;;;;;;IAWpB,CAEF,MAAM,EAAU,MAAM;;;;IAIpB,CAEF,MAAM,EAAU,MAAM;;;;;;;;;;;;IAYpB,EAGSC,EAAoC,MAAO,CAAE,QAAS,KAAqB,CACtF,GAAM,CAAE,aAAc,EACtB,MAAM,EAAU,MAAM,6CAA6C,CACnE,MAAM,EAAU,MAAM,kDAAkD,CACxE,MAAM,EAAU,MAAM,2CAA2C"}
@@ -0,0 +1,15 @@
1
+ const e=async({context:e})=>{let{sequelize:t}=e;await t.query(`
2
+ CREATE TABLE IF NOT EXISTS "custom_field_entries" (
3
+ "model_id" UUID NOT NULL,
4
+ "entity_id" UUID NOT NULL,
5
+ "custom_fields" JSONB NOT NULL DEFAULT '{}',
6
+ "model_type" VARCHAR NOT NULL,
7
+ "created_at" TIMESTAMPTZ NOT NULL,
8
+ "updated_at" TIMESTAMPTZ,
9
+ PRIMARY KEY ("model_id")
10
+ )
11
+ `),await t.query(`
12
+ CREATE INDEX IF NOT EXISTS "idx_cfe_custom_fields"
13
+ ON "custom_field_entries" USING gin ("custom_fields" jsonb_path_ops)
14
+ `)},t=async({context:e})=>{await e.sequelize.query(`DROP TABLE IF EXISTS "custom_field_entries"`)};exports.down=t,exports.up=e;
15
+ //# sourceMappingURL=002-create-custom-field-entries.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"002-create-custom-field-entries.cjs","names":["up: MigrationFn<QueryInterface>","down: MigrationFn<QueryInterface>"],"sources":["../../src/migrations/002-create-custom-field-entries.ts"],"sourcesContent":["import type { MigrationFn } from 'umzug';\nimport type { QueryInterface } from 'sequelize';\n\nexport const up: MigrationFn<QueryInterface> = async ({ context: queryInterface }) => {\n const { sequelize } = queryInterface;\n\n await sequelize.query(`\n CREATE TABLE IF NOT EXISTS \"custom_field_entries\" (\n \"model_id\" UUID NOT NULL,\n \"entity_id\" UUID NOT NULL,\n \"custom_fields\" JSONB NOT NULL DEFAULT '{}',\n \"model_type\" VARCHAR NOT NULL,\n \"created_at\" TIMESTAMPTZ NOT NULL,\n \"updated_at\" TIMESTAMPTZ,\n PRIMARY KEY (\"model_id\")\n )\n `);\n\n await sequelize.query(`\n CREATE INDEX IF NOT EXISTS \"idx_cfe_custom_fields\"\n ON \"custom_field_entries\" USING gin (\"custom_fields\" jsonb_path_ops)\n `);\n};\n\nexport const down: MigrationFn<QueryInterface> = async ({ context: queryInterface }) => {\n await queryInterface.sequelize.query('DROP TABLE IF EXISTS \"custom_field_entries\"');\n};\n"],"mappings":"AAGA,MAAaA,EAAkC,MAAO,CAAE,QAAS,KAAqB,CACpF,GAAM,CAAE,aAAc,EAEtB,MAAM,EAAU,MAAM;;;;;;;;;;IAUpB,CAEF,MAAM,EAAU,MAAM;;;IAGpB,EAGSC,EAAoC,MAAO,CAAE,QAAS,KAAqB,CACtF,MAAM,EAAe,UAAU,MAAM,8CAA8C"}
@@ -0,0 +1,15 @@
1
+ const e=async({context:e})=>{let{sequelize:t}=e;await t.query(`
2
+ CREATE TABLE IF NOT EXISTS "custom_field_entries" (
3
+ "model_id" UUID NOT NULL,
4
+ "entity_id" UUID NOT NULL,
5
+ "custom_fields" JSONB NOT NULL DEFAULT '{}',
6
+ "model_type" VARCHAR NOT NULL,
7
+ "created_at" TIMESTAMPTZ NOT NULL,
8
+ "updated_at" TIMESTAMPTZ,
9
+ PRIMARY KEY ("model_id")
10
+ )
11
+ `),await t.query(`
12
+ CREATE INDEX IF NOT EXISTS "idx_cfe_custom_fields"
13
+ ON "custom_field_entries" USING gin ("custom_fields" jsonb_path_ops)
14
+ `)},t=async({context:e})=>{await e.sequelize.query(`DROP TABLE IF EXISTS "custom_field_entries"`)};export{t as down,e as up};
15
+ //# sourceMappingURL=002-create-custom-field-entries.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"002-create-custom-field-entries.js","names":["up: MigrationFn<QueryInterface>","down: MigrationFn<QueryInterface>"],"sources":["../../src/migrations/002-create-custom-field-entries.ts"],"sourcesContent":["import type { MigrationFn } from 'umzug';\nimport type { QueryInterface } from 'sequelize';\n\nexport const up: MigrationFn<QueryInterface> = async ({ context: queryInterface }) => {\n const { sequelize } = queryInterface;\n\n await sequelize.query(`\n CREATE TABLE IF NOT EXISTS \"custom_field_entries\" (\n \"model_id\" UUID NOT NULL,\n \"entity_id\" UUID NOT NULL,\n \"custom_fields\" JSONB NOT NULL DEFAULT '{}',\n \"model_type\" VARCHAR NOT NULL,\n \"created_at\" TIMESTAMPTZ NOT NULL,\n \"updated_at\" TIMESTAMPTZ,\n PRIMARY KEY (\"model_id\")\n )\n `);\n\n await sequelize.query(`\n CREATE INDEX IF NOT EXISTS \"idx_cfe_custom_fields\"\n ON \"custom_field_entries\" USING gin (\"custom_fields\" jsonb_path_ops)\n `);\n};\n\nexport const down: MigrationFn<QueryInterface> = async ({ context: queryInterface }) => {\n await queryInterface.sequelize.query('DROP TABLE IF EXISTS \"custom_field_entries\"');\n};\n"],"mappings":"AAGA,MAAaA,EAAkC,MAAO,CAAE,QAAS,KAAqB,CACpF,GAAM,CAAE,aAAc,EAEtB,MAAM,EAAU,MAAM;;;;;;;;;;IAUpB,CAEF,MAAM,EAAU,MAAM;;;IAGpB,EAGSC,EAAoC,MAAO,CAAE,QAAS,KAAqB,CACtF,MAAM,EAAe,UAAU,MAAM,8CAA8C"}
@@ -0,0 +1,21 @@
1
+ const e=async({context:e})=>{let{sequelize:t}=e;await t.query(`
2
+ CREATE TABLE IF NOT EXISTS "custom_field_model_type_map" (
3
+ "id" UUID NOT NULL DEFAULT gen_random_uuid(),
4
+ "model_type_id" UUID NOT NULL,
5
+ "custom_field_definition_id" UUID NOT NULL
6
+ REFERENCES "custom_field_definitions" ("id"),
7
+ "created_at" TIMESTAMPTZ NOT NULL,
8
+ "updated_at" TIMESTAMPTZ NOT NULL,
9
+ PRIMARY KEY ("id")
10
+ )
11
+ `),await t.query(`
12
+ CREATE UNIQUE INDEX IF NOT EXISTS "unique_model_type_custom_field"
13
+ ON "custom_field_model_type_map" ("model_type_id", "custom_field_definition_id")
14
+ `),await t.query(`
15
+ CREATE INDEX IF NOT EXISTS "idx_custom_field_model_type_map_definition_id"
16
+ ON "custom_field_model_type_map" ("custom_field_definition_id")
17
+ `),await t.query(`
18
+ CREATE INDEX IF NOT EXISTS "idx_custom_field_model_type_map_type_id"
19
+ ON "custom_field_model_type_map" ("model_type_id")
20
+ `)},t=async({context:e})=>{await e.sequelize.query(`DROP TABLE IF EXISTS "custom_field_model_type_map"`)};exports.down=t,exports.up=e;
21
+ //# sourceMappingURL=003-create-custom-field-model-type-map.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"003-create-custom-field-model-type-map.cjs","names":["up: MigrationFn<QueryInterface>","down: MigrationFn<QueryInterface>"],"sources":["../../src/migrations/003-create-custom-field-model-type-map.ts"],"sourcesContent":["import type { MigrationFn } from 'umzug';\nimport type { QueryInterface } from 'sequelize';\n\nexport const up: MigrationFn<QueryInterface> = async ({ context: queryInterface }) => {\n const { sequelize } = queryInterface;\n\n await sequelize.query(`\n CREATE TABLE IF NOT EXISTS \"custom_field_model_type_map\" (\n \"id\" UUID NOT NULL DEFAULT gen_random_uuid(),\n \"model_type_id\" UUID NOT NULL,\n \"custom_field_definition_id\" UUID NOT NULL\n REFERENCES \"custom_field_definitions\" (\"id\"),\n \"created_at\" TIMESTAMPTZ NOT NULL,\n \"updated_at\" TIMESTAMPTZ NOT NULL,\n PRIMARY KEY (\"id\")\n )\n `);\n\n await sequelize.query(`\n CREATE UNIQUE INDEX IF NOT EXISTS \"unique_model_type_custom_field\"\n ON \"custom_field_model_type_map\" (\"model_type_id\", \"custom_field_definition_id\")\n `);\n\n await sequelize.query(`\n CREATE INDEX IF NOT EXISTS \"idx_custom_field_model_type_map_definition_id\"\n ON \"custom_field_model_type_map\" (\"custom_field_definition_id\")\n `);\n\n await sequelize.query(`\n CREATE INDEX IF NOT EXISTS \"idx_custom_field_model_type_map_type_id\"\n ON \"custom_field_model_type_map\" (\"model_type_id\")\n `);\n};\n\nexport const down: MigrationFn<QueryInterface> = async ({ context: queryInterface }) => {\n await queryInterface.sequelize.query('DROP TABLE IF EXISTS \"custom_field_model_type_map\"');\n};\n"],"mappings":"AAGA,MAAaA,EAAkC,MAAO,CAAE,QAAS,KAAqB,CACpF,GAAM,CAAE,aAAc,EAEtB,MAAM,EAAU,MAAM;;;;;;;;;;IAUpB,CAEF,MAAM,EAAU,MAAM;;;IAGpB,CAEF,MAAM,EAAU,MAAM;;;IAGpB,CAEF,MAAM,EAAU,MAAM;;;IAGpB,EAGSC,EAAoC,MAAO,CAAE,QAAS,KAAqB,CACtF,MAAM,EAAe,UAAU,MAAM,qDAAqD"}
@@ -0,0 +1,21 @@
1
+ const e=async({context:e})=>{let{sequelize:t}=e;await t.query(`
2
+ CREATE TABLE IF NOT EXISTS "custom_field_model_type_map" (
3
+ "id" UUID NOT NULL DEFAULT gen_random_uuid(),
4
+ "model_type_id" UUID NOT NULL,
5
+ "custom_field_definition_id" UUID NOT NULL
6
+ REFERENCES "custom_field_definitions" ("id"),
7
+ "created_at" TIMESTAMPTZ NOT NULL,
8
+ "updated_at" TIMESTAMPTZ NOT NULL,
9
+ PRIMARY KEY ("id")
10
+ )
11
+ `),await t.query(`
12
+ CREATE UNIQUE INDEX IF NOT EXISTS "unique_model_type_custom_field"
13
+ ON "custom_field_model_type_map" ("model_type_id", "custom_field_definition_id")
14
+ `),await t.query(`
15
+ CREATE INDEX IF NOT EXISTS "idx_custom_field_model_type_map_definition_id"
16
+ ON "custom_field_model_type_map" ("custom_field_definition_id")
17
+ `),await t.query(`
18
+ CREATE INDEX IF NOT EXISTS "idx_custom_field_model_type_map_type_id"
19
+ ON "custom_field_model_type_map" ("model_type_id")
20
+ `)},t=async({context:e})=>{await e.sequelize.query(`DROP TABLE IF EXISTS "custom_field_model_type_map"`)};export{t as down,e as up};
21
+ //# sourceMappingURL=003-create-custom-field-model-type-map.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"003-create-custom-field-model-type-map.js","names":["up: MigrationFn<QueryInterface>","down: MigrationFn<QueryInterface>"],"sources":["../../src/migrations/003-create-custom-field-model-type-map.ts"],"sourcesContent":["import type { MigrationFn } from 'umzug';\nimport type { QueryInterface } from 'sequelize';\n\nexport const up: MigrationFn<QueryInterface> = async ({ context: queryInterface }) => {\n const { sequelize } = queryInterface;\n\n await sequelize.query(`\n CREATE TABLE IF NOT EXISTS \"custom_field_model_type_map\" (\n \"id\" UUID NOT NULL DEFAULT gen_random_uuid(),\n \"model_type_id\" UUID NOT NULL,\n \"custom_field_definition_id\" UUID NOT NULL\n REFERENCES \"custom_field_definitions\" (\"id\"),\n \"created_at\" TIMESTAMPTZ NOT NULL,\n \"updated_at\" TIMESTAMPTZ NOT NULL,\n PRIMARY KEY (\"id\")\n )\n `);\n\n await sequelize.query(`\n CREATE UNIQUE INDEX IF NOT EXISTS \"unique_model_type_custom_field\"\n ON \"custom_field_model_type_map\" (\"model_type_id\", \"custom_field_definition_id\")\n `);\n\n await sequelize.query(`\n CREATE INDEX IF NOT EXISTS \"idx_custom_field_model_type_map_definition_id\"\n ON \"custom_field_model_type_map\" (\"custom_field_definition_id\")\n `);\n\n await sequelize.query(`\n CREATE INDEX IF NOT EXISTS \"idx_custom_field_model_type_map_type_id\"\n ON \"custom_field_model_type_map\" (\"model_type_id\")\n `);\n};\n\nexport const down: MigrationFn<QueryInterface> = async ({ context: queryInterface }) => {\n await queryInterface.sequelize.query('DROP TABLE IF EXISTS \"custom_field_model_type_map\"');\n};\n"],"mappings":"AAGA,MAAaA,EAAkC,MAAO,CAAE,QAAS,KAAqB,CACpF,GAAM,CAAE,aAAc,EAEtB,MAAM,EAAU,MAAM;;;;;;;;;;IAUpB,CAEF,MAAM,EAAU,MAAM;;;IAGpB,CAEF,MAAM,EAAU,MAAM;;;IAGpB,CAEF,MAAM,EAAU,MAAM;;;IAGpB,EAGSC,EAAoC,MAAO,CAAE,QAAS,KAAqB,CACtF,MAAM,EAAe,UAAU,MAAM,qDAAqD"}
@@ -0,0 +1,2 @@
1
+ const e=require(`../utils/logger/index.cjs`),t=require(`./001-create-core-tables.cjs`),n=require(`./002-create-custom-field-entries.cjs`),r=require(`./003-create-custom-field-model-type-map.cjs`),{Umzug:i,SequelizeStorage:a}=require(`umzug`),o=e=>{let{useCustomFieldsEntries:i=!1,useModelTypeMapping:a=!1}=e;return[{name:`001-create-core-tables`,up:t.up,down:t.down},...i?[{name:`002-create-custom-field-entries`,up:n.up,down:n.down}]:[],...a?[{name:`003-create-custom-field-model-type-map`,up:r.up,down:r.down}]:[]]},s=async(t,n={})=>{let r=t.getQueryInterface(),s=new a({sequelize:t,tableName:`sadot_migrations`});await new i({migrations:o(n),context:r,storage:s,logger:{info:t=>e.default.info(`[umzug] ${JSON.stringify(t)}`),warn:t=>e.default.warn(`[umzug] ${JSON.stringify(t)}`),error:t=>e.default.error(`[umzug] ${JSON.stringify(t)}`),debug:t=>e.default.debug(`[umzug] ${JSON.stringify(t)}`)}}).up()};exports.runSadotMigrations=s;
2
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":["logger"],"sources":["../../src/migrations/index.ts"],"sourcesContent":["import type { InputMigrations } from 'umzug';\nimport type { QueryInterface } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport logger from '../utils/logger';\nimport * as migration001 from './001-create-core-tables';\nimport * as migration002 from './002-create-custom-field-entries';\nimport * as migration003 from './003-create-custom-field-model-type-map';\n\n// umzug is CJS. Static ESM named imports break in vitest after vi.resetModules()\n// because Vite's SSR transform re-evaluates the module outside the inline bundle.\n// require() goes through Node's native CJS loader and is stable across resets.\n\n// eslint-disable-next-line import/no-commonjs, @typescript-eslint/no-require-imports\nconst { Umzug, SequelizeStorage } = require('umzug') as typeof import('umzug');\n\ninterface MigratorOptions {\n useCustomFieldsEntries?: boolean;\n useModelTypeMapping?: boolean;\n}\n\nconst buildMigrationList = (options: MigratorOptions): InputMigrations<QueryInterface> => {\n const { useCustomFieldsEntries = false, useModelTypeMapping = false } = options;\n return [\n { name: '001-create-core-tables', up: migration001.up, down: migration001.down },\n ...(useCustomFieldsEntries ? [{ name: '002-create-custom-field-entries', up: migration002.up, down: migration002.down }] : []),\n ...(useModelTypeMapping ? [{ name: '003-create-custom-field-model-type-map', up: migration003.up, down: migration003.down }] : []),\n ];\n};\n\n/**\n * Runs sadot migrations via umzug. All migrations use IF NOT EXISTS / IF EXISTS,\n * so they are fully idempotent — safe to run against both fresh and existing\n * databases (including DBs previously managed by the legacy sync() path).\n */\nconst runSadotMigrations = async (sequelize: Sequelize, options: MigratorOptions = {}): Promise<void> => {\n const queryInterface = sequelize.getQueryInterface() as unknown as QueryInterface;\n const storage = new SequelizeStorage({ sequelize: sequelize as never, tableName: 'sadot_migrations' });\n\n const migrator = new Umzug<QueryInterface>({\n migrations: buildMigrationList(options),\n context: queryInterface,\n storage,\n logger: {\n info: msg => logger.info(`[umzug] ${JSON.stringify(msg)}`),\n warn: msg => logger.warn(`[umzug] ${JSON.stringify(msg)}`),\n error: msg => logger.error(`[umzug] ${JSON.stringify(msg)}`),\n debug: msg => logger.debug(`[umzug] ${JSON.stringify(msg)}`),\n },\n });\n\n await migrator.up();\n};\n\nexport { runSadotMigrations };\n"],"mappings":"oMAaM,CAAE,QAAO,oBAAqB,QAAQ,QAAQ,CAO9C,EAAsB,GAA8D,CACxF,GAAM,CAAE,yBAAyB,GAAO,sBAAsB,IAAU,EACxE,MAAO,CACL,CAAE,KAAM,yBAA0B,GAAA,EAAA,GAAqB,KAAA,EAAA,KAAyB,CAChF,GAAI,EAAyB,CAAC,CAAE,KAAM,kCAAmC,GAAA,EAAA,GAAqB,KAAA,EAAA,KAAyB,CAAC,CAAG,EAAE,CAC7H,GAAI,EAAsB,CAAC,CAAE,KAAM,yCAA0C,GAAA,EAAA,GAAqB,KAAA,EAAA,KAAyB,CAAC,CAAG,EAAE,CAClI,EAQG,EAAqB,MAAO,EAAsB,EAA2B,EAAE,GAAoB,CACvG,IAAM,EAAiB,EAAU,mBAAmB,CAC9C,EAAU,IAAI,EAAiB,CAAa,YAAoB,UAAW,mBAAoB,CAAC,CActG,MAZiB,IAAI,EAAsB,CACzC,WAAY,EAAmB,EAAQ,CACvC,QAAS,EACT,UACA,OAAQ,CACN,KAAM,GAAOA,EAAAA,QAAO,KAAK,WAAW,KAAK,UAAU,EAAI,GAAG,CAC1D,KAAM,GAAOA,EAAAA,QAAO,KAAK,WAAW,KAAK,UAAU,EAAI,GAAG,CAC1D,MAAO,GAAOA,EAAAA,QAAO,MAAM,WAAW,KAAK,UAAU,EAAI,GAAG,CAC5D,MAAO,GAAOA,EAAAA,QAAO,MAAM,WAAW,KAAK,UAAU,EAAI,GAAG,CAC7D,CACF,CAAC,CAEa,IAAI"}
@@ -0,0 +1,2 @@
1
+ import{__require as e}from"../_virtual/rolldown_runtime.js";import t from"../utils/logger/index.js";import{down as n,up as r}from"./001-create-core-tables.js";import{down as i,up as a}from"./002-create-custom-field-entries.js";import{down as o,up as s}from"./003-create-custom-field-model-type-map.js";const{Umzug:c,SequelizeStorage:l}=e(`umzug`),u=e=>{let{useCustomFieldsEntries:t=!1,useModelTypeMapping:c=!1}=e;return[{name:`001-create-core-tables`,up:r,down:n},...t?[{name:`002-create-custom-field-entries`,up:a,down:i}]:[],...c?[{name:`003-create-custom-field-model-type-map`,up:s,down:o}]:[]]},d=async(e,n={})=>{let r=e.getQueryInterface(),i=new l({sequelize:e,tableName:`sadot_migrations`});await new c({migrations:u(n),context:r,storage:i,logger:{info:e=>t.info(`[umzug] ${JSON.stringify(e)}`),warn:e=>t.warn(`[umzug] ${JSON.stringify(e)}`),error:e=>t.error(`[umzug] ${JSON.stringify(e)}`),debug:e=>t.debug(`[umzug] ${JSON.stringify(e)}`)}}).up()};export{d as runSadotMigrations};
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["migration001.up","migration001.down","migration002.up","migration002.down","migration003.up","migration003.down","logger"],"sources":["../../src/migrations/index.ts"],"sourcesContent":["import type { InputMigrations } from 'umzug';\nimport type { QueryInterface } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport logger from '../utils/logger';\nimport * as migration001 from './001-create-core-tables';\nimport * as migration002 from './002-create-custom-field-entries';\nimport * as migration003 from './003-create-custom-field-model-type-map';\n\n// umzug is CJS. Static ESM named imports break in vitest after vi.resetModules()\n// because Vite's SSR transform re-evaluates the module outside the inline bundle.\n// require() goes through Node's native CJS loader and is stable across resets.\n\n// eslint-disable-next-line import/no-commonjs, @typescript-eslint/no-require-imports\nconst { Umzug, SequelizeStorage } = require('umzug') as typeof import('umzug');\n\ninterface MigratorOptions {\n useCustomFieldsEntries?: boolean;\n useModelTypeMapping?: boolean;\n}\n\nconst buildMigrationList = (options: MigratorOptions): InputMigrations<QueryInterface> => {\n const { useCustomFieldsEntries = false, useModelTypeMapping = false } = options;\n return [\n { name: '001-create-core-tables', up: migration001.up, down: migration001.down },\n ...(useCustomFieldsEntries ? [{ name: '002-create-custom-field-entries', up: migration002.up, down: migration002.down }] : []),\n ...(useModelTypeMapping ? [{ name: '003-create-custom-field-model-type-map', up: migration003.up, down: migration003.down }] : []),\n ];\n};\n\n/**\n * Runs sadot migrations via umzug. All migrations use IF NOT EXISTS / IF EXISTS,\n * so they are fully idempotent — safe to run against both fresh and existing\n * databases (including DBs previously managed by the legacy sync() path).\n */\nconst runSadotMigrations = async (sequelize: Sequelize, options: MigratorOptions = {}): Promise<void> => {\n const queryInterface = sequelize.getQueryInterface() as unknown as QueryInterface;\n const storage = new SequelizeStorage({ sequelize: sequelize as never, tableName: 'sadot_migrations' });\n\n const migrator = new Umzug<QueryInterface>({\n migrations: buildMigrationList(options),\n context: queryInterface,\n storage,\n logger: {\n info: msg => logger.info(`[umzug] ${JSON.stringify(msg)}`),\n warn: msg => logger.warn(`[umzug] ${JSON.stringify(msg)}`),\n error: msg => logger.error(`[umzug] ${JSON.stringify(msg)}`),\n debug: msg => logger.debug(`[umzug] ${JSON.stringify(msg)}`),\n },\n });\n\n await migrator.up();\n};\n\nexport { runSadotMigrations };\n"],"mappings":"8SAaA,KAAM,CAAE,QAAO,oBAAA,EAA6B,QAAQ,CAO9C,EAAsB,GAA8D,CACxF,GAAM,CAAE,yBAAyB,GAAO,sBAAsB,IAAU,EACxE,MAAO,CACL,CAAE,KAAM,yBAA8BA,KAAuBC,OAAmB,CAChF,GAAI,EAAyB,CAAC,CAAE,KAAM,kCAAmC,GAAIC,EAAiB,KAAMC,EAAmB,CAAC,CAAG,EAAE,CAC7H,GAAI,EAAsB,CAAC,CAAE,KAAM,yCAA0C,GAAIC,EAAiB,KAAMC,EAAmB,CAAC,CAAG,EAAE,CAClI,EAQG,EAAqB,MAAO,EAAsB,EAA2B,EAAE,GAAoB,CACvG,IAAM,EAAiB,EAAU,mBAAmB,CAC9C,EAAU,IAAI,EAAiB,CAAa,YAAoB,UAAW,mBAAoB,CAAC,CActG,MAZiB,IAAI,EAAsB,CACzC,WAAY,EAAmB,EAAQ,CACvC,QAAS,EACT,UACA,OAAQ,CACN,KAAM,GAAOC,EAAO,KAAK,WAAW,KAAK,UAAU,EAAI,GAAG,CAC1D,KAAM,GAAOA,EAAO,KAAK,WAAW,KAAK,UAAU,EAAI,GAAG,CAC1D,MAAO,GAAOA,EAAO,MAAM,WAAW,KAAK,UAAU,EAAI,GAAG,CAC5D,MAAO,GAAOA,EAAO,MAAM,WAAW,KAAK,UAAU,EAAI,GAAG,CAC7D,CACF,CAAC,CAEa,IAAI"}
@@ -1,2 +1,2 @@
1
- const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../utils/logger/index.cjs`),n=require(`./CustomFieldValue.cjs`),r=require(`./CustomFieldDefinition.cjs`),i=require(`./tests/AssociatedTestModel.cjs`),a=require(`./tests/TestModel.cjs`),o=require(`./tests/contextAwareModels/ContextTestModel.cjs`),s=require(`./tests/contextAwareModels/ContextAwareTestModel.cjs`),c=require(`./CustomFieldEntries.cjs`),l=require(`./CustomValidator.cjs`),u=require(`./CustomFieldModelTypeMap.cjs`);let d=require(`sequelize`);const f=[a.default,i.default,s.default,o.default],p=`sadot-migration`,m=`5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1`,h=async(e,i,{schemaPrefix:a=`sadot-migration`,schemaVersion:o=`5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1`,useCustomFieldsEntries:s=!1,useModelTypeMapping:f=!1,isMatPathEnabled:p}={})=>{let m=`${a}_${o}${s?`_withEntries`:``}${f?`_withTypeMapping`:``}`;if(t.default.info(`custom-fields: initialize custom-fields tables`),!e.addModels)throw Error(`sequelize instance must have addModels function`);let h=[r.default,n.default,l.default,...s?[c.default]:[],...f?[u.default]:[]];e.addModels(h),f&&(r.default.hasMany(u.default,{foreignKey:`customFieldDefinitionId`,as:`modelTypeMappings`}),u.default.belongsTo(r.default,{foreignKey:`customFieldDefinitionId`,as:`customFieldDefinition`})),r.default.addScope(`userScope`,()=>{if(p?.())return{};let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),l.default.addScope(`userScope`,()=>{if(p?.())return{};let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),t.default.info(`custom-fields: models added`);let g=e.define(`SequelizeMeta`,{name:{type:d.DataTypes.STRING,allowNull:!1,unique:!0,primaryKey:!0,autoIncrement:!1}},{tableName:`SequelizeMeta`,timestamps:!1,schema:`public`});t.default.info(`custom-fields: starting migrations`);let _=await g.findAll({where:{name:{[d.Op.like]:`${a}%`}},raw:!0}),v=_.at(-1),y=_.findIndex(e=>e.name===m);if(t.default.info(`custom-fields: migrations`,{currentMigrations:_,currentSadotSchemaVersion:v,newSadotSchemaVersion:m,expectedSchemaVersionIndex:y}),!v||v.name!==m){t.default.info(`custom-fields: syncing models`);try{if(await r.default.sync({alter:!0}),t.default.info(`custom-fields: CustomFieldDefinition synced successfully`),await n.default.sync({alter:!0}),t.default.info(`custom-fields: CustomFieldValue synced successfully`),await l.default.sync({alter:!0}),t.default.info(`custom-fields: CustomValidator synced successfully`),s&&(await c.default.sync({alter:!0}),t.default.info(`custom-fields: CustomFieldEntries synced successfully`)),f&&(await u.default.sync({alter:!0}),t.default.info(`custom-fields: CustomFieldModelTypeMap synced successfully`)),y===-1&&(await g.create({name:m}),t.default.info(`custom-fields: SequelizeMeta entry created successfully`)),t.default.info(`custom-fields: models synced`),_.length&&y!==-1&&y<_.length-1){let e=_.slice(y+1);t.default.info(`custom-fields: deleting newer migrations during down migration`,{count:e.length}),await g.destroy({where:{name:{[d.Op.in]:e.map(e=>e.name)}}}),t.default.info(`custom-fields: newer migrations deleted successfully`)}}catch(e){throw t.default.error(`custom-fields: failed to sync models`,{error:e}),e}}},g=async e=>{if(t.default.info(`custom-fields: initialize custom-fields test models`),!e.addModels)throw Error(`sequelize instance must have addModels function`);e.addModels(f),await e.dropSchema(`custom-fields`,{logging:!1}),await e.createSchema(`custom-fields`,{logging:!1}),t.default.info(`custom-fields: test models added`),await a.default.sync({alter:!0}),await i.default.sync({alter:!0}),await o.default.sync({alter:!0}),await s.default.sync({alter:!0}),t.default.info(`custom-fields: test models synced`)};exports.initTables=h,exports.initTestModels=g;
1
+ const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../utils/logger/index.cjs`),n=require(`./CustomFieldValue.cjs`),r=require(`./CustomFieldDefinition.cjs`),i=require(`./tests/AssociatedTestModel.cjs`),a=require(`./tests/TestModel.cjs`),o=require(`./tests/contextAwareModels/ContextTestModel.cjs`),s=require(`./tests/contextAwareModels/ContextAwareTestModel.cjs`),c=require(`./CustomFieldEntries.cjs`),l=require(`./CustomValidator.cjs`),u=require(`./CustomFieldModelTypeMap.cjs`),d=require(`../migrations/index.cjs`);let f=require(`sequelize`);const p=[a.default,i.default,s.default,o.default],m=`sadot-migration`,h=`5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1`,g=async(e,i,{schemaPrefix:a=`sadot-migration`,schemaVersion:o=`5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1`,useCustomFieldsEntries:s=!1,useModelTypeMapping:p=!1,useUmzugMigrations:m=!1,isMatPathEnabled:h}={})=>{let g=`${a}_${o}${s?`_withEntries`:``}${p?`_withTypeMapping`:``}`;if(t.default.info(`custom-fields: initialize custom-fields tables`),!e.addModels)throw Error(`sequelize instance must have addModels function`);let _=[r.default,n.default,l.default,...s?[c.default]:[],...p?[u.default]:[]];if(e.addModels(_),p&&(r.default.hasMany(u.default,{foreignKey:`customFieldDefinitionId`,as:`modelTypeMappings`}),u.default.belongsTo(r.default,{foreignKey:`customFieldDefinitionId`,as:`customFieldDefinition`})),r.default.addScope(`userScope`,()=>{if(h?.())return{};let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),l.default.addScope(`userScope`,()=>{if(h?.())return{};let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),t.default.info(`custom-fields: models added`),m){t.default.info(`custom-fields: starting umzug migrations`),await d.runSadotMigrations(e,{useCustomFieldsEntries:s,useModelTypeMapping:p}),t.default.info(`custom-fields: umzug migrations complete`);return}let v=e.define(`SequelizeMeta`,{name:{type:f.DataTypes.STRING,allowNull:!1,unique:!0,primaryKey:!0,autoIncrement:!1}},{tableName:`SequelizeMeta`,timestamps:!1,schema:`public`});t.default.info(`custom-fields: starting migrations`);let y=await v.findAll({where:{name:{[f.Op.like]:`${a}%`}},raw:!0}),b=y.at(-1),x=y.findIndex(e=>e.name===g);if(t.default.info(`custom-fields: migrations`,{currentMigrations:y,currentSadotSchemaVersion:b,newSadotSchemaVersion:g,expectedSchemaVersionIndex:x}),!b||b.name!==g){t.default.info(`custom-fields: syncing models`);try{if(await r.default.sync({alter:!0}),t.default.info(`custom-fields: CustomFieldDefinition synced successfully`),await n.default.sync({alter:!0}),t.default.info(`custom-fields: CustomFieldValue synced successfully`),await l.default.sync({alter:!0}),t.default.info(`custom-fields: CustomValidator synced successfully`),s&&(await c.default.sync({alter:!0}),t.default.info(`custom-fields: CustomFieldEntries synced successfully`)),p&&(await u.default.sync({alter:!0}),t.default.info(`custom-fields: CustomFieldModelTypeMap synced successfully`)),x===-1&&(await v.create({name:g}),t.default.info(`custom-fields: SequelizeMeta entry created successfully`)),t.default.info(`custom-fields: models synced`),y.length&&x!==-1&&x<y.length-1){let e=y.slice(x+1);t.default.info(`custom-fields: deleting newer migrations during down migration`,{count:e.length}),await v.destroy({where:{name:{[f.Op.in]:e.map(e=>e.name)}}}),t.default.info(`custom-fields: newer migrations deleted successfully`)}}catch(e){throw t.default.error(`custom-fields: failed to sync models`,{error:e}),e}}},_=async e=>{if(t.default.info(`custom-fields: initialize custom-fields test models`),!e.addModels)throw Error(`sequelize instance must have addModels function`);e.addModels(p),await e.dropSchema(`custom-fields`,{logging:!1}),await e.createSchema(`custom-fields`,{logging:!1}),t.default.info(`custom-fields: test models added`),await a.default.sync({alter:!0}),await i.default.sync({alter:!0}),await o.default.sync({alter:!0}),await s.default.sync({alter:!0}),t.default.info(`custom-fields: test models synced`)};exports.initTables=g,exports.initTestModels=_;
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["TestModel","AssociatedTestModel","ContextAwareTestModel","ContextTestModel","sequelize","productionModels: ProductionModel[]","CustomFieldDefinition","CustomFieldValue","CustomValidator","CustomFieldEntries","CustomFieldModelTypeMap","DataTypes","Op"],"sources":["../../src/models/index.ts"],"sourcesContent":["import { DataTypes, Op } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport logger from '../utils/logger';\nimport CustomFieldDefinition from './CustomFieldDefinition';\nimport CustomFieldValue from './CustomFieldValue';\nimport TestModel from './tests/TestModel';\nimport ContextAwareTestModel from './tests/contextAwareModels/ContextAwareTestModel';\nimport ContextTestModel from './tests/contextAwareModels/ContextTestModel';\nimport AssociatedTestModel from './tests/AssociatedTestModel';\nimport type { CustomFieldOptions } from '../types';\nimport CustomFieldEntries from './CustomFieldEntries';\nimport CustomValidator from './CustomValidator';\nimport CustomFieldModelTypeMap from './CustomFieldModelTypeMap';\n\ntype ProductionModel = typeof CustomFieldDefinition | typeof CustomFieldValue | typeof CustomFieldEntries | typeof CustomValidator | typeof CustomFieldModelTypeMap;\ninterface InitTablesOptions {\n schemaPrefix?: string;\n schemaVersion?: string;\n useCustomFieldsEntries?: boolean;\n useModelTypeMapping?: boolean;\n isMatPathEnabled?: CustomFieldOptions['isMatPathEnabled'];\n}\n\nconst testModels = [TestModel, AssociatedTestModel, ContextAwareTestModel, ContextTestModel];\n\nconst SADOT_MIGRATION_PREFIX = 'sadot-migration';\nconst SCHEMA_VERSION = '5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1';\n\nconst initTables = async (\n sequelize: Sequelize,\n getUser: CustomFieldOptions['getUser'],\n {\n schemaPrefix = SADOT_MIGRATION_PREFIX,\n schemaVersion = SCHEMA_VERSION,\n useCustomFieldsEntries = false,\n useModelTypeMapping = false,\n isMatPathEnabled,\n }: InitTablesOptions = {},\n): Promise<void> => {\n const CUSTOM_FIELDS_SCHEMA_VERSION = `${schemaPrefix}_${schemaVersion}${useCustomFieldsEntries ? '_withEntries' : ''}${useModelTypeMapping ? '_withTypeMapping' : ''}`;\n logger.info('custom-fields: initialize custom-fields tables');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n const productionModels: ProductionModel[] = [\n CustomFieldDefinition,\n CustomFieldValue,\n CustomValidator,\n ...(useCustomFieldsEntries ? [CustomFieldEntries] : []),\n ...(useModelTypeMapping ? [CustomFieldModelTypeMap] : []),\n ];\n\n sequelize.addModels(productionModels);\n\n // Add the association only when useModelTypeMapping is enabled\n if (useModelTypeMapping) {\n CustomFieldDefinition.hasMany(CustomFieldModelTypeMap, {\n foreignKey: 'customFieldDefinitionId',\n as: 'modelTypeMappings',\n });\n CustomFieldModelTypeMap.belongsTo(CustomFieldDefinition, {\n foreignKey: 'customFieldDefinitionId',\n as: 'customFieldDefinition',\n });\n }\n\n CustomFieldDefinition.addScope('userScope', () => {\n // When mat-path is active, the consumer is responsible for restricting entityIds\n // (typically by expanding the request's entityIds to include ancestor paths the\n // caller can see). Bypass the legacy permission filter so partner/ancestor\n // entityIds are not dropped.\n if (isMatPathEnabled?.()) return {};\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n CustomValidator.addScope('userScope', () => {\n if (isMatPathEnabled?.()) return {};\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n logger.info('custom-fields: models added');\n\n const SequelizeMeta = sequelize.define(\n 'SequelizeMeta',\n {\n name: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: true,\n primaryKey: true,\n autoIncrement: false,\n },\n },\n {\n tableName: 'SequelizeMeta',\n timestamps: false,\n schema: 'public',\n },\n );\n\n logger.info('custom-fields: starting migrations');\n const migrations = await SequelizeMeta.findAll({ where: { name: { [Op.like]: `${schemaPrefix}%` } }, raw: true });\n const currentSadotSchemaVersion = migrations.at(-1);\n const expectedSchemaVersionIndex = migrations.findIndex(m => (m as any).name === CUSTOM_FIELDS_SCHEMA_VERSION);\n\n logger.info('custom-fields: migrations', {\n currentMigrations: migrations,\n currentSadotSchemaVersion,\n newSadotSchemaVersion: CUSTOM_FIELDS_SCHEMA_VERSION,\n expectedSchemaVersionIndex,\n });\n if (!currentSadotSchemaVersion || (currentSadotSchemaVersion as any).name !== CUSTOM_FIELDS_SCHEMA_VERSION) {\n logger.info('custom-fields: syncing models');\n try {\n await CustomFieldDefinition.sync({ alter: true });\n logger.info('custom-fields: CustomFieldDefinition synced successfully');\n\n await CustomFieldValue.sync({ alter: true });\n logger.info('custom-fields: CustomFieldValue synced successfully');\n\n await CustomValidator.sync({ alter: true });\n logger.info('custom-fields: CustomValidator synced successfully');\n\n // T.Y TODO: Remove the if statement once we're ready to add the new entries table for all MS\n if (useCustomFieldsEntries) {\n await CustomFieldEntries.sync({ alter: true });\n logger.info('custom-fields: CustomFieldEntries synced successfully');\n }\n\n if (useModelTypeMapping) {\n await CustomFieldModelTypeMap.sync({ alter: true });\n logger.info('custom-fields: CustomFieldModelTypeMap synced successfully');\n }\n\n if (expectedSchemaVersionIndex === -1) {\n await SequelizeMeta.create({ name: CUSTOM_FIELDS_SCHEMA_VERSION });\n logger.info('custom-fields: SequelizeMeta entry created successfully');\n }\n\n logger.info('custom-fields: models synced');\n if (migrations.length && expectedSchemaVersionIndex !== -1 && expectedSchemaVersionIndex < migrations.length - 1) {\n // We have existing migrations, and we are calling `sync`.\n // This means we are in a `down` migration, and hence we should delete newer migrations to ensure we can reapply them.\n const migrationsToDelete = migrations.slice(expectedSchemaVersionIndex + 1);\n logger.info('custom-fields: deleting newer migrations during down migration', { count: migrationsToDelete.length });\n await SequelizeMeta.destroy({ where: { name: { [Op.in]: migrationsToDelete.map(m => (m as any).name) } } });\n logger.info('custom-fields: newer migrations deleted successfully');\n }\n } catch (error) {\n logger.error('custom-fields: failed to sync models', { error });\n throw error;\n }\n }\n};\n\nconst initTestModels = async (sequelize: Sequelize): Promise<void> => {\n logger.info('custom-fields: initialize custom-fields test models');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n\n sequelize.addModels(testModels);\n await sequelize.dropSchema('custom-fields', { logging: false });\n await sequelize.createSchema('custom-fields', { logging: false });\n\n logger.info('custom-fields: test models added');\n await TestModel.sync({ alter: true });\n await AssociatedTestModel.sync({ alter: true });\n await ContextTestModel.sync({ alter: true });\n await ContextAwareTestModel.sync({ alter: true });\n logger.info('custom-fields: test models synced');\n};\n\nexport {\n CustomFieldValue,\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomValidator,\n CustomFieldModelTypeMap,\n TestModel,\n AssociatedTestModel,\n ContextAwareTestModel,\n ContextTestModel,\n initTables,\n initTestModels,\n};\n"],"mappings":"sgBAuBA,MAAM,EAAa,CAACA,EAAAA,QAAWC,EAAAA,QAAqBC,EAAAA,QAAuBC,EAAAA,QAAiB,CAEtF,EAAyB,kBACzB,EAAiB,uCAEjB,EAAa,MACjB,EACA,EACA,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AA+B,CACvC,EAAW,QAAU,IAA+B,IAAM,EAA6B,EAAW,OAAS,EAAG,CAGhH,IAAM,EAAqB,EAAW,MAAM,EAA6B,EAAE,CAC3E,EAAA,QAAO,KAAK,iEAAkE,CAAE,MAAO,EAAmB,OAAQ,CAAC,CACnH,MAAM,EAAc,QAAQ,CAAE,MAAO,CAAE,KAAM,EAAGE,EAAAA,GAAG,IAAK,EAAmB,IAAI,GAAM,EAAU,KAAK,CAAE,CAAE,CAAE,CAAC,CAC3G,EAAA,QAAO,KAAK,uDAAuD,QAE9D,EAAO,CAEd,MADA,EAAA,QAAO,MAAM,uCAAwC,CAAE,QAAO,CAAC,CACzD,KAKN,EAAiB,KAAO,IAAwC,CAGpE,GAFA,EAAA,QAAO,KAAK,sDAAsD,CAE9D,CAACR,EAAU,UACb,MAAU,MAAM,kDAAkD,CAGpE,EAAU,UAAU,EAAW,CAC/B,MAAMA,EAAU,WAAW,gBAAiB,CAAE,QAAS,GAAO,CAAC,CAC/D,MAAMA,EAAU,aAAa,gBAAiB,CAAE,QAAS,GAAO,CAAC,CAEjE,EAAA,QAAO,KAAK,mCAAmC,CAC/C,MAAMJ,EAAAA,QAAU,KAAK,CAAE,MAAO,GAAM,CAAC,CACrC,MAAMC,EAAAA,QAAoB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC/C,MAAME,EAAAA,QAAiB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC5C,MAAMD,EAAAA,QAAsB,KAAK,CAAE,MAAO,GAAM,CAAC,CACjD,EAAA,QAAO,KAAK,oCAAoC"}
1
+ {"version":3,"file":"index.cjs","names":["TestModel","AssociatedTestModel","ContextAwareTestModel","ContextTestModel","sequelize","productionModels: ProductionModel[]","CustomFieldDefinition","CustomFieldValue","CustomValidator","CustomFieldEntries","CustomFieldModelTypeMap","runSadotMigrations","DataTypes","Op"],"sources":["../../src/models/index.ts"],"sourcesContent":["import { DataTypes, Op } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport logger from '../utils/logger';\nimport CustomFieldDefinition from './CustomFieldDefinition';\nimport CustomFieldValue from './CustomFieldValue';\nimport TestModel from './tests/TestModel';\nimport ContextAwareTestModel from './tests/contextAwareModels/ContextAwareTestModel';\nimport ContextTestModel from './tests/contextAwareModels/ContextTestModel';\nimport AssociatedTestModel from './tests/AssociatedTestModel';\nimport type { CustomFieldOptions } from '../types';\nimport CustomFieldEntries from './CustomFieldEntries';\nimport CustomValidator from './CustomValidator';\nimport CustomFieldModelTypeMap from './CustomFieldModelTypeMap';\nimport { runSadotMigrations } from '../migrations';\n\ntype ProductionModel = typeof CustomFieldDefinition | typeof CustomFieldValue | typeof CustomFieldEntries | typeof CustomValidator | typeof CustomFieldModelTypeMap;\ninterface InitTablesOptions {\n schemaPrefix?: string;\n schemaVersion?: string;\n useCustomFieldsEntries?: boolean;\n useModelTypeMapping?: boolean;\n useUmzugMigrations?: boolean;\n isMatPathEnabled?: CustomFieldOptions['isMatPathEnabled'];\n}\n\nconst testModels = [TestModel, AssociatedTestModel, ContextAwareTestModel, ContextTestModel];\n\nconst SADOT_MIGRATION_PREFIX = 'sadot-migration';\nconst SCHEMA_VERSION = '5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1';\n\nconst initTables = async (\n sequelize: Sequelize,\n getUser: CustomFieldOptions['getUser'],\n {\n schemaPrefix = SADOT_MIGRATION_PREFIX,\n schemaVersion = SCHEMA_VERSION,\n useCustomFieldsEntries = false,\n useModelTypeMapping = false,\n useUmzugMigrations = false,\n isMatPathEnabled,\n }: InitTablesOptions = {},\n): Promise<void> => {\n const CUSTOM_FIELDS_SCHEMA_VERSION = `${schemaPrefix}_${schemaVersion}${useCustomFieldsEntries ? '_withEntries' : ''}${useModelTypeMapping ? '_withTypeMapping' : ''}`;\n logger.info('custom-fields: initialize custom-fields tables');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n const productionModels: ProductionModel[] = [\n CustomFieldDefinition,\n CustomFieldValue,\n CustomValidator,\n ...(useCustomFieldsEntries ? [CustomFieldEntries] : []),\n ...(useModelTypeMapping ? [CustomFieldModelTypeMap] : []),\n ];\n\n sequelize.addModels(productionModels);\n\n // Add the association only when useModelTypeMapping is enabled\n if (useModelTypeMapping) {\n CustomFieldDefinition.hasMany(CustomFieldModelTypeMap, {\n foreignKey: 'customFieldDefinitionId',\n as: 'modelTypeMappings',\n });\n CustomFieldModelTypeMap.belongsTo(CustomFieldDefinition, {\n foreignKey: 'customFieldDefinitionId',\n as: 'customFieldDefinition',\n });\n }\n\n CustomFieldDefinition.addScope('userScope', () => {\n // When mat-path is active, the consumer is responsible for restricting entityIds\n // (typically by expanding the request's entityIds to include ancestor paths the\n // caller can see). Bypass the legacy permission filter so partner/ancestor\n // entityIds are not dropped.\n if (isMatPathEnabled?.()) return {};\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n CustomValidator.addScope('userScope', () => {\n if (isMatPathEnabled?.()) return {};\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n logger.info('custom-fields: models added');\n\n if (useUmzugMigrations) {\n logger.info('custom-fields: starting umzug migrations');\n await runSadotMigrations(sequelize, { useCustomFieldsEntries, useModelTypeMapping });\n logger.info('custom-fields: umzug migrations complete');\n return;\n }\n\n const SequelizeMeta = sequelize.define(\n 'SequelizeMeta',\n {\n name: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: true,\n primaryKey: true,\n autoIncrement: false,\n },\n },\n {\n tableName: 'SequelizeMeta',\n timestamps: false,\n schema: 'public',\n },\n );\n\n logger.info('custom-fields: starting migrations');\n const migrations = await SequelizeMeta.findAll({ where: { name: { [Op.like]: `${schemaPrefix}%` } }, raw: true });\n const currentSadotSchemaVersion = migrations.at(-1);\n const expectedSchemaVersionIndex = migrations.findIndex(m => (m as any).name === CUSTOM_FIELDS_SCHEMA_VERSION);\n\n logger.info('custom-fields: migrations', {\n currentMigrations: migrations,\n currentSadotSchemaVersion,\n newSadotSchemaVersion: CUSTOM_FIELDS_SCHEMA_VERSION,\n expectedSchemaVersionIndex,\n });\n if (!currentSadotSchemaVersion || (currentSadotSchemaVersion as any).name !== CUSTOM_FIELDS_SCHEMA_VERSION) {\n logger.info('custom-fields: syncing models');\n try {\n await CustomFieldDefinition.sync({ alter: true });\n logger.info('custom-fields: CustomFieldDefinition synced successfully');\n\n await CustomFieldValue.sync({ alter: true });\n logger.info('custom-fields: CustomFieldValue synced successfully');\n\n await CustomValidator.sync({ alter: true });\n logger.info('custom-fields: CustomValidator synced successfully');\n\n // T.Y TODO: Remove the if statement once we're ready to add the new entries table for all MS\n if (useCustomFieldsEntries) {\n await CustomFieldEntries.sync({ alter: true });\n logger.info('custom-fields: CustomFieldEntries synced successfully');\n }\n\n if (useModelTypeMapping) {\n await CustomFieldModelTypeMap.sync({ alter: true });\n logger.info('custom-fields: CustomFieldModelTypeMap synced successfully');\n }\n\n if (expectedSchemaVersionIndex === -1) {\n await SequelizeMeta.create({ name: CUSTOM_FIELDS_SCHEMA_VERSION });\n logger.info('custom-fields: SequelizeMeta entry created successfully');\n }\n\n logger.info('custom-fields: models synced');\n if (migrations.length && expectedSchemaVersionIndex !== -1 && expectedSchemaVersionIndex < migrations.length - 1) {\n // We have existing migrations, and we are calling `sync`.\n // This means we are in a `down` migration, and hence we should delete newer migrations to ensure we can reapply them.\n const migrationsToDelete = migrations.slice(expectedSchemaVersionIndex + 1);\n logger.info('custom-fields: deleting newer migrations during down migration', { count: migrationsToDelete.length });\n await SequelizeMeta.destroy({ where: { name: { [Op.in]: migrationsToDelete.map(m => (m as any).name) } } });\n logger.info('custom-fields: newer migrations deleted successfully');\n }\n } catch (error) {\n logger.error('custom-fields: failed to sync models', { error });\n throw error;\n }\n }\n};\n\nconst initTestModels = async (sequelize: Sequelize): Promise<void> => {\n logger.info('custom-fields: initialize custom-fields test models');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n\n sequelize.addModels(testModels);\n await sequelize.dropSchema('custom-fields', { logging: false });\n await sequelize.createSchema('custom-fields', { logging: false });\n\n logger.info('custom-fields: test models added');\n await TestModel.sync({ alter: true });\n await AssociatedTestModel.sync({ alter: true });\n await ContextTestModel.sync({ alter: true });\n await ContextAwareTestModel.sync({ alter: true });\n logger.info('custom-fields: test models synced');\n};\n\nexport {\n CustomFieldValue,\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomValidator,\n CustomFieldModelTypeMap,\n TestModel,\n AssociatedTestModel,\n ContextAwareTestModel,\n ContextTestModel,\n initTables,\n initTestModels,\n};\n"],"mappings":"2iBAyBA,MAAM,EAAa,CAACA,EAAAA,QAAWC,EAAAA,QAAqBC,EAAAA,QAAuBC,EAAAA,QAAiB,CAEtF,EAAyB,kBACzB,EAAiB,uCAEjB,EAAa,MACjB,EACA,EACA,CACE,eAAe,kBACf,gBAAgB,uCAChB,yBAAyB,GACzB,sBAAsB,GACtB,qBAAqB,GACrB,oBACqB,EAAE,GACP,CAClB,IAAM,EAA+B,GAAG,EAAa,GAAG,IAAgB,EAAyB,eAAiB,KAAK,EAAsB,mBAAqB,KAGlK,GAFA,EAAA,QAAO,KAAK,iDAAiD,CAEzD,CAACC,EAAU,UACb,MAAU,MAAM,kDAAkD,CAEpE,IAAMC,EAAsC,CAC1CC,EAAAA,QACAC,EAAAA,QACAC,EAAAA,QACA,GAAI,EAAyB,CAACC,EAAAA,QAAmB,CAAG,EAAE,CACtD,GAAI,EAAsB,CAACC,EAAAA,QAAwB,CAAG,EAAE,CACzD,CAwDD,GAtDA,EAAU,UAAU,EAAiB,CAGjC,IACF,EAAA,QAAsB,Q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A,QAAO,KAAK,uDAAuD,QAE9D,EAAO,CAEd,MADA,EAAA,QAAO,MAAM,uCAAwC,CAAE,QAAO,CAAC,CACzD,KAKN,EAAiB,KAAO,IAAwC,CAGpE,GAFA,EAAA,QAAO,KAAK,sDAAsD,CAE9D,CAACT,EAAU,UACb,MAAU,MAAM,kDAAkD,CAGpE,EAAU,UAAU,EAAW,CAC/B,MAAMA,EAAU,WAAW,gBAAiB,CAAE,QAAS,GAAO,CAAC,CAC/D,MAAMA,EAAU,aAAa,gBAAiB,CAAE,QAAS,GAAO,CAAC,CAEjE,EAAA,QAAO,KAAK,mCAAmC,CAC/C,MAAMJ,EAAAA,QAAU,KAAK,CAAE,MAAO,GAAM,CAAC,CACrC,MAAMC,EAAAA,QAAoB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC/C,MAAME,EAAAA,QAAiB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC5C,MAAMD,EAAAA,QAAsB,KAAK,CAAE,MAAO,GAAM,CAAC,CACjD,EAAA,QAAO,KAAK,oCAAoC"}
@@ -1,2 +1,2 @@
1
- import e from"../utils/logger/index.js";import t from"./CustomFieldValue.js";import n from"./CustomFieldDefinition.js";import r from"./tests/AssociatedTestModel.js";import i from"./tests/TestModel.js";import a from"./tests/contextAwareModels/ContextTestModel.js";import o from"./tests/contextAwareModels/ContextAwareTestModel.js";import s from"./CustomFieldEntries.js";import c from"./CustomValidator.js";import l from"./CustomFieldModelTypeMap.js";import{DataTypes as u,Op as d}from"sequelize";const f=[i,r,o,a],p=async(r,i,{schemaPrefix:a=`sadot-migration`,schemaVersion:o=`5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1`,useCustomFieldsEntries:f=!1,useModelTypeMapping:p=!1,isMatPathEnabled:m}={})=>{let h=`${a}_${o}${f?`_withEntries`:``}${p?`_withTypeMapping`:``}`;if(e.info(`custom-fields: initialize custom-fields tables`),!r.addModels)throw Error(`sequelize instance must have addModels function`);let g=[n,t,c,...f?[s]:[],...p?[l]:[]];r.addModels(g),p&&(n.hasMany(l,{foreignKey:`customFieldDefinitionId`,as:`modelTypeMappings`}),l.belongsTo(n,{foreignKey:`customFieldDefinitionId`,as:`customFieldDefinition`})),n.addScope(`userScope`,()=>{if(m?.())return{};let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),c.addScope(`userScope`,()=>{if(m?.())return{};let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),e.info(`custom-fields: models added`);let _=r.define(`SequelizeMeta`,{name:{type:u.STRING,allowNull:!1,unique:!0,primaryKey:!0,autoIncrement:!1}},{tableName:`SequelizeMeta`,timestamps:!1,schema:`public`});e.info(`custom-fields: starting migrations`);let v=await _.findAll({where:{name:{[d.like]:`${a}%`}},raw:!0}),y=v.at(-1),b=v.findIndex(e=>e.name===h);if(e.info(`custom-fields: migrations`,{currentMigrations:v,currentSadotSchemaVersion:y,newSadotSchemaVersion:h,expectedSchemaVersionIndex:b}),!y||y.name!==h){e.info(`custom-fields: syncing models`);try{if(await n.sync({alter:!0}),e.info(`custom-fields: CustomFieldDefinition synced successfully`),await t.sync({alter:!0}),e.info(`custom-fields: CustomFieldValue synced successfully`),await c.sync({alter:!0}),e.info(`custom-fields: CustomValidator synced successfully`),f&&(await s.sync({alter:!0}),e.info(`custom-fields: CustomFieldEntries synced successfully`)),p&&(await l.sync({alter:!0}),e.info(`custom-fields: CustomFieldModelTypeMap synced successfully`)),b===-1&&(await _.create({name:h}),e.info(`custom-fields: SequelizeMeta entry created successfully`)),e.info(`custom-fields: models synced`),v.length&&b!==-1&&b<v.length-1){let t=v.slice(b+1);e.info(`custom-fields: deleting newer migrations during down migration`,{count:t.length}),await _.destroy({where:{name:{[d.in]:t.map(e=>e.name)}}}),e.info(`custom-fields: newer migrations deleted successfully`)}}catch(t){throw e.error(`custom-fields: failed to sync models`,{error:t}),t}}},m=async t=>{if(e.info(`custom-fields: initialize custom-fields test models`),!t.addModels)throw Error(`sequelize instance must have addModels function`);t.addModels(f),await t.dropSchema(`custom-fields`,{logging:!1}),await t.createSchema(`custom-fields`,{logging:!1}),e.info(`custom-fields: test models added`),await i.sync({alter:!0}),await r.sync({alter:!0}),await a.sync({alter:!0}),await o.sync({alter:!0}),e.info(`custom-fields: test models synced`)};export{p as initTables,m as initTestModels};
1
+ import e from"../utils/logger/index.js";import t from"./CustomFieldValue.js";import n from"./CustomFieldDefinition.js";import r from"./tests/AssociatedTestModel.js";import i from"./tests/TestModel.js";import a from"./tests/contextAwareModels/ContextTestModel.js";import o from"./tests/contextAwareModels/ContextAwareTestModel.js";import s from"./CustomFieldEntries.js";import c from"./CustomValidator.js";import l from"./CustomFieldModelTypeMap.js";import{runSadotMigrations as u}from"../migrations/index.js";import{DataTypes as d,Op as f}from"sequelize";const p=[i,r,o,a],m=async(r,i,{schemaPrefix:a=`sadot-migration`,schemaVersion:o=`5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1`,useCustomFieldsEntries:p=!1,useModelTypeMapping:m=!1,useUmzugMigrations:h=!1,isMatPathEnabled:g}={})=>{let _=`${a}_${o}${p?`_withEntries`:``}${m?`_withTypeMapping`:``}`;if(e.info(`custom-fields: initialize custom-fields tables`),!r.addModels)throw Error(`sequelize instance must have addModels function`);let v=[n,t,c,...p?[s]:[],...m?[l]:[]];if(r.addModels(v),m&&(n.hasMany(l,{foreignKey:`customFieldDefinitionId`,as:`modelTypeMappings`}),l.belongsTo(n,{foreignKey:`customFieldDefinitionId`,as:`customFieldDefinition`})),n.addScope(`userScope`,()=>{if(g?.())return{};let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),c.addScope(`userScope`,()=>{if(g?.())return{};let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),e.info(`custom-fields: models added`),h){e.info(`custom-fields: starting umzug migrations`),await u(r,{useCustomFieldsEntries:p,useModelTypeMapping:m}),e.info(`custom-fields: umzug migrations complete`);return}let y=r.define(`SequelizeMeta`,{name:{type:d.STRING,allowNull:!1,unique:!0,primaryKey:!0,autoIncrement:!1}},{tableName:`SequelizeMeta`,timestamps:!1,schema:`public`});e.info(`custom-fields: starting migrations`);let b=await y.findAll({where:{name:{[f.like]:`${a}%`}},raw:!0}),x=b.at(-1),S=b.findIndex(e=>e.name===_);if(e.info(`custom-fields: migrations`,{currentMigrations:b,currentSadotSchemaVersion:x,newSadotSchemaVersion:_,expectedSchemaVersionIndex:S}),!x||x.name!==_){e.info(`custom-fields: syncing models`);try{if(await n.sync({alter:!0}),e.info(`custom-fields: CustomFieldDefinition synced successfully`),await t.sync({alter:!0}),e.info(`custom-fields: CustomFieldValue synced successfully`),await c.sync({alter:!0}),e.info(`custom-fields: CustomValidator synced successfully`),p&&(await s.sync({alter:!0}),e.info(`custom-fields: CustomFieldEntries synced successfully`)),m&&(await l.sync({alter:!0}),e.info(`custom-fields: CustomFieldModelTypeMap synced successfully`)),S===-1&&(await y.create({name:_}),e.info(`custom-fields: SequelizeMeta entry created successfully`)),e.info(`custom-fields: models synced`),b.length&&S!==-1&&S<b.length-1){let t=b.slice(S+1);e.info(`custom-fields: deleting newer migrations during down migration`,{count:t.length}),await y.destroy({where:{name:{[f.in]:t.map(e=>e.name)}}}),e.info(`custom-fields: newer migrations deleted successfully`)}}catch(t){throw e.error(`custom-fields: failed to sync models`,{error:t}),t}}},h=async t=>{if(e.info(`custom-fields: initialize custom-fields test models`),!t.addModels)throw Error(`sequelize instance must have addModels function`);t.addModels(p),await t.dropSchema(`custom-fields`,{logging:!1}),await t.createSchema(`custom-fields`,{logging:!1}),e.info(`custom-fields: test models added`),await i.sync({alter:!0}),await r.sync({alter:!0}),await a.sync({alter:!0}),await o.sync({alter:!0}),e.info(`custom-fields: test models synced`)};export{m as initTables,h as initTestModels};
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["TestModel","AssociatedTestModel","ContextAwareTestModel","ContextTestModel","productionModels: ProductionModel[]","CustomFieldDefinition","CustomFieldValue","CustomValidator","CustomFieldEntries","CustomFieldModelTypeMap"],"sources":["../../src/models/index.ts"],"sourcesContent":["import { DataTypes, Op } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport logger from '../utils/logger';\nimport CustomFieldDefinition from './CustomFieldDefinition';\nimport CustomFieldValue from './CustomFieldValue';\nimport TestModel from './tests/TestModel';\nimport ContextAwareTestModel from './tests/contextAwareModels/ContextAwareTestModel';\nimport ContextTestModel from './tests/contextAwareModels/ContextTestModel';\nimport AssociatedTestModel from './tests/AssociatedTestModel';\nimport type { CustomFieldOptions } from '../types';\nimport CustomFieldEntries from './CustomFieldEntries';\nimport CustomValidator from './CustomValidator';\nimport CustomFieldModelTypeMap from './CustomFieldModelTypeMap';\n\ntype ProductionModel = typeof CustomFieldDefinition | typeof CustomFieldValue | typeof CustomFieldEntries | typeof CustomValidator | typeof CustomFieldModelTypeMap;\ninterface InitTablesOptions {\n schemaPrefix?: string;\n schemaVersion?: string;\n useCustomFieldsEntries?: boolean;\n useModelTypeMapping?: boolean;\n isMatPathEnabled?: CustomFieldOptions['isMatPathEnabled'];\n}\n\nconst testModels = [TestModel, AssociatedTestModel, ContextAwareTestModel, ContextTestModel];\n\nconst SADOT_MIGRATION_PREFIX = 'sadot-migration';\nconst SCHEMA_VERSION = '5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1';\n\nconst initTables = async (\n sequelize: Sequelize,\n getUser: CustomFieldOptions['getUser'],\n {\n schemaPrefix = SADOT_MIGRATION_PREFIX,\n schemaVersion = SCHEMA_VERSION,\n useCustomFieldsEntries = false,\n useModelTypeMapping = false,\n isMatPathEnabled,\n }: InitTablesOptions = {},\n): Promise<void> => {\n const CUSTOM_FIELDS_SCHEMA_VERSION = `${schemaPrefix}_${schemaVersion}${useCustomFieldsEntries ? '_withEntries' : ''}${useModelTypeMapping ? '_withTypeMapping' : ''}`;\n logger.info('custom-fields: initialize custom-fields tables');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n const productionModels: ProductionModel[] = [\n CustomFieldDefinition,\n CustomFieldValue,\n CustomValidator,\n ...(useCustomFieldsEntries ? [CustomFieldEntries] : []),\n ...(useModelTypeMapping ? [CustomFieldModelTypeMap] : []),\n ];\n\n sequelize.addModels(productionModels);\n\n // Add the association only when useModelTypeMapping is enabled\n if (useModelTypeMapping) {\n CustomFieldDefinition.hasMany(CustomFieldModelTypeMap, {\n foreignKey: 'customFieldDefinitionId',\n as: 'modelTypeMappings',\n });\n CustomFieldModelTypeMap.belongsTo(CustomFieldDefinition, {\n foreignKey: 'customFieldDefinitionId',\n as: 'customFieldDefinition',\n });\n }\n\n CustomFieldDefinition.addScope('userScope', () => {\n // When mat-path is active, the consumer is responsible for restricting entityIds\n // (typically by expanding the request's entityIds to include ancestor paths the\n // caller can see). Bypass the legacy permission filter so partner/ancestor\n // entityIds are not dropped.\n if (isMatPathEnabled?.()) return {};\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n CustomValidator.addScope('userScope', () => {\n if (isMatPathEnabled?.()) return {};\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n logger.info('custom-fields: models added');\n\n const SequelizeMeta = sequelize.define(\n 'SequelizeMeta',\n {\n name: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: true,\n primaryKey: true,\n autoIncrement: false,\n },\n },\n {\n tableName: 'SequelizeMeta',\n timestamps: false,\n schema: 'public',\n },\n );\n\n logger.info('custom-fields: starting migrations');\n const migrations = await SequelizeMeta.findAll({ where: { name: { [Op.like]: `${schemaPrefix}%` } }, raw: true });\n const currentSadotSchemaVersion = migrations.at(-1);\n const expectedSchemaVersionIndex = migrations.findIndex(m => (m as any).name === CUSTOM_FIELDS_SCHEMA_VERSION);\n\n logger.info('custom-fields: migrations', {\n currentMigrations: migrations,\n currentSadotSchemaVersion,\n newSadotSchemaVersion: CUSTOM_FIELDS_SCHEMA_VERSION,\n expectedSchemaVersionIndex,\n });\n if (!currentSadotSchemaVersion || (currentSadotSchemaVersion as any).name !== CUSTOM_FIELDS_SCHEMA_VERSION) {\n logger.info('custom-fields: syncing models');\n try {\n await CustomFieldDefinition.sync({ alter: true });\n logger.info('custom-fields: CustomFieldDefinition synced successfully');\n\n await CustomFieldValue.sync({ alter: true });\n logger.info('custom-fields: CustomFieldValue synced successfully');\n\n await CustomValidator.sync({ alter: true });\n logger.info('custom-fields: CustomValidator synced successfully');\n\n // T.Y TODO: Remove the if statement once we're ready to add the new entries table for all MS\n if (useCustomFieldsEntries) {\n await CustomFieldEntries.sync({ alter: true });\n logger.info('custom-fields: CustomFieldEntries synced successfully');\n }\n\n if (useModelTypeMapping) {\n await CustomFieldModelTypeMap.sync({ alter: true });\n logger.info('custom-fields: CustomFieldModelTypeMap synced successfully');\n }\n\n if (expectedSchemaVersionIndex === -1) {\n await SequelizeMeta.create({ name: CUSTOM_FIELDS_SCHEMA_VERSION });\n logger.info('custom-fields: SequelizeMeta entry created successfully');\n }\n\n logger.info('custom-fields: models synced');\n if (migrations.length && expectedSchemaVersionIndex !== -1 && expectedSchemaVersionIndex < migrations.length - 1) {\n // We have existing migrations, and we are calling `sync`.\n // This means we are in a `down` migration, and hence we should delete newer migrations to ensure we can reapply them.\n const migrationsToDelete = migrations.slice(expectedSchemaVersionIndex + 1);\n logger.info('custom-fields: deleting newer migrations during down migration', { count: migrationsToDelete.length });\n await SequelizeMeta.destroy({ where: { name: { [Op.in]: migrationsToDelete.map(m => (m as any).name) } } });\n logger.info('custom-fields: newer migrations deleted successfully');\n }\n } catch (error) {\n logger.error('custom-fields: failed to sync models', { error });\n throw error;\n }\n }\n};\n\nconst initTestModels = async (sequelize: Sequelize): Promise<void> => {\n logger.info('custom-fields: initialize custom-fields test models');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n\n sequelize.addModels(testModels);\n await sequelize.dropSchema('custom-fields', { logging: false });\n await sequelize.createSchema('custom-fields', { logging: false });\n\n logger.info('custom-fields: test models added');\n await TestModel.sync({ alter: true });\n await AssociatedTestModel.sync({ alter: true });\n await ContextTestModel.sync({ alter: true });\n await ContextAwareTestModel.sync({ alter: true });\n logger.info('custom-fields: test models synced');\n};\n\nexport {\n CustomFieldValue,\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomValidator,\n CustomFieldModelTypeMap,\n TestModel,\n AssociatedTestModel,\n ContextAwareTestModel,\n ContextTestModel,\n initTables,\n initTestModels,\n};\n"],"mappings":"+eAuBA,MAAM,EAAa,CAACA,EAAWC,EAAqBC,EAAuBC,EAAiB,CAKtF,EAAa,MACjB,EACA,EACA,CACE,eAAe,kBACf,gBAAgB,uCAChB,yBAAyB,GACzB,sBAAsB,GACtB,oBACqB,EAAE,GACP,CAClB,IAAM,EAA+B,GAAG,EAAa,GAAG,IAAgB,EAAyB,eAAiB,KAAK,EAAsB,mBAAqB,KAGlK,GAFA,EAAO,KAAK,iDAAiD,CAEzD,CAAC,EAAU,UACb,MAAU,MAAM,kDAAkD,CAEpE,IAAMC,EAAsC,CAC1CC,EACAC,EACAC,EACA,GAAI,EAAyB,CAACC,EAAmB,CAAG,EAAE,CACtD,GAAI,EAAsB,CAACC,EAAwB,CAAG,EAAE,CACzD,CAED,EAAU,UAAU,EAA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AAa,gBAAiB,CAAE,QAAS,GAAO,CAAC,CAEjE,EAAO,KAAK,mCAAmC,CAC/C,MAAMT,EAAU,KAAK,CAAE,MAAO,GAAM,CAAC,CACrC,MAAMC,EAAoB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC/C,MAAME,EAAiB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC5C,MAAMD,EAAsB,KAAK,CAAE,MAAO,GAAM,CAAC,CACjD,EAAO,KAAK,oCAAoC"}
1
+ {"version":3,"file":"index.js","names":["TestModel","AssociatedTestModel","ContextAwareTestModel","ContextTestModel","productionModels: ProductionModel[]","CustomFieldDefinition","CustomFieldValue","CustomValidator","CustomFieldEntries","CustomFieldModelTypeMap"],"sources":["../../src/models/index.ts"],"sourcesContent":["import { DataTypes, Op } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport logger from '../utils/logger';\nimport CustomFieldDefinition from './CustomFieldDefinition';\nimport CustomFieldValue from './CustomFieldValue';\nimport TestModel from './tests/TestModel';\nimport ContextAwareTestModel from './tests/contextAwareModels/ContextAwareTestModel';\nimport ContextTestModel from './tests/contextAwareModels/ContextTestModel';\nimport AssociatedTestModel from './tests/AssociatedTestModel';\nimport type { CustomFieldOptions } from '../types';\nimport CustomFieldEntries from './CustomFieldEntries';\nimport CustomValidator from './CustomValidator';\nimport CustomFieldModelTypeMap from './CustomFieldModelTypeMap';\nimport { runSadotMigrations } from '../migrations';\n\ntype ProductionModel = typeof CustomFieldDefinition | typeof CustomFieldValue | typeof CustomFieldEntries | typeof CustomValidator | typeof CustomFieldModelTypeMap;\ninterface InitTablesOptions {\n schemaPrefix?: string;\n schemaVersion?: string;\n useCustomFieldsEntries?: boolean;\n useModelTypeMapping?: boolean;\n useUmzugMigrations?: boolean;\n isMatPathEnabled?: CustomFieldOptions['isMatPathEnabled'];\n}\n\nconst testModels = [TestModel, AssociatedTestModel, ContextAwareTestModel, ContextTestModel];\n\nconst SADOT_MIGRATION_PREFIX = 'sadot-migration';\nconst SCHEMA_VERSION = '5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1';\n\nconst initTables = async (\n sequelize: Sequelize,\n getUser: CustomFieldOptions['getUser'],\n {\n schemaPrefix = SADOT_MIGRATION_PREFIX,\n schemaVersion = SCHEMA_VERSION,\n useCustomFieldsEntries = false,\n useModelTypeMapping = false,\n useUmzugMigrations = false,\n isMatPathEnabled,\n }: InitTablesOptions = {},\n): Promise<void> => {\n const CUSTOM_FIELDS_SCHEMA_VERSION = `${schemaPrefix}_${schemaVersion}${useCustomFieldsEntries ? '_withEntries' : ''}${useModelTypeMapping ? '_withTypeMapping' : ''}`;\n logger.info('custom-fields: initialize custom-fields tables');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n const productionModels: ProductionModel[] = [\n CustomFieldDefinition,\n CustomFieldValue,\n CustomValidator,\n ...(useCustomFieldsEntries ? [CustomFieldEntries] : []),\n ...(useModelTypeMapping ? [CustomFieldModelTypeMap] : []),\n ];\n\n sequelize.addModels(productionModels);\n\n // Add the association only when useModelTypeMapping is enabled\n if (useModelTypeMapping) {\n CustomFieldDefinition.hasMany(CustomFieldModelTypeMap, {\n foreignKey: 'customFieldDefinitionId',\n as: 'modelTypeMappings',\n });\n CustomFieldModelTypeMap.belongsTo(CustomFieldDefinition, {\n foreignKey: 'customFieldDefinitionId',\n as: 'customFieldDefinition',\n });\n }\n\n CustomFieldDefinition.addScope('userScope', () => {\n // When mat-path is active, the consumer is responsible for restricting entityIds\n // (typically by expanding the request's entityIds to include ancestor paths the\n // caller can see). Bypass the legacy permission filter so partner/ancestor\n // entityIds are not dropped.\n if (isMatPathEnabled?.()) return {};\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n CustomValidator.addScope('userScope', () => {\n if (isMatPathEnabled?.()) return {};\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n logger.info('custom-fields: models added');\n\n if (useUmzugMigrations) {\n logger.info('custom-fields: starting umzug migrations');\n await runSadotMigrations(sequelize, { useCustomFieldsEntries, useModelTypeMapping });\n logger.info('custom-fields: umzug migrations complete');\n return;\n }\n\n const SequelizeMeta = sequelize.define(\n 'SequelizeMeta',\n {\n name: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: true,\n primaryKey: true,\n autoIncrement: false,\n },\n },\n {\n tableName: 'SequelizeMeta',\n timestamps: false,\n schema: 'public',\n },\n );\n\n logger.info('custom-fields: starting migrations');\n const migrations = await SequelizeMeta.findAll({ where: { name: { [Op.like]: `${schemaPrefix}%` } }, raw: true });\n const currentSadotSchemaVersion = migrations.at(-1);\n const expectedSchemaVersionIndex = migrations.findIndex(m => (m as any).name === CUSTOM_FIELDS_SCHEMA_VERSION);\n\n logger.info('custom-fields: migrations', {\n currentMigrations: migrations,\n currentSadotSchemaVersion,\n newSadotSchemaVersion: CUSTOM_FIELDS_SCHEMA_VERSION,\n expectedSchemaVersionIndex,\n });\n if (!currentSadotSchemaVersion || (currentSadotSchemaVersion as any).name !== CUSTOM_FIELDS_SCHEMA_VERSION) {\n logger.info('custom-fields: syncing models');\n try {\n await CustomFieldDefinition.sync({ alter: true });\n logger.info('custom-fields: CustomFieldDefinition synced successfully');\n\n await CustomFieldValue.sync({ alter: true });\n logger.info('custom-fields: CustomFieldValue synced successfully');\n\n await CustomValidator.sync({ alter: true });\n logger.info('custom-fields: CustomValidator synced successfully');\n\n // T.Y TODO: Remove the if statement once we're ready to add the new entries table for all MS\n if (useCustomFieldsEntries) {\n await CustomFieldEntries.sync({ alter: true });\n logger.info('custom-fields: CustomFieldEntries synced successfully');\n }\n\n if (useModelTypeMapping) {\n await CustomFieldModelTypeMap.sync({ alter: true });\n logger.info('custom-fields: CustomFieldModelTypeMap synced successfully');\n }\n\n if (expectedSchemaVersionIndex === -1) {\n await SequelizeMeta.create({ name: CUSTOM_FIELDS_SCHEMA_VERSION });\n logger.info('custom-fields: SequelizeMeta entry created successfully');\n }\n\n logger.info('custom-fields: models synced');\n if (migrations.length && expectedSchemaVersionIndex !== -1 && expectedSchemaVersionIndex < migrations.length - 1) {\n // We have existing migrations, and we are calling `sync`.\n // This means we are in a `down` migration, and hence we should delete newer migrations to ensure we can reapply them.\n const migrationsToDelete = migrations.slice(expectedSchemaVersionIndex + 1);\n logger.info('custom-fields: deleting newer migrations during down migration', { count: migrationsToDelete.length });\n await SequelizeMeta.destroy({ where: { name: { [Op.in]: migrationsToDelete.map(m => (m as any).name) } } });\n logger.info('custom-fields: newer migrations deleted successfully');\n }\n } catch (error) {\n logger.error('custom-fields: failed to sync models', { error });\n throw error;\n }\n }\n};\n\nconst initTestModels = async (sequelize: Sequelize): Promise<void> => {\n logger.info('custom-fields: initialize custom-fields test models');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n\n sequelize.addModels(testModels);\n await sequelize.dropSchema('custom-fields', { logging: false });\n await sequelize.createSchema('custom-fields', { logging: false });\n\n logger.info('custom-fields: test models added');\n await TestModel.sync({ alter: true });\n await AssociatedTestModel.sync({ alter: true });\n await ContextTestModel.sync({ alter: true });\n await ContextAwareTestModel.sync({ alter: true });\n logger.info('custom-fields: test models synced');\n};\n\nexport {\n CustomFieldValue,\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomValidator,\n CustomFieldModelTypeMap,\n TestModel,\n AssociatedTestModel,\n ContextAwareTestModel,\n ContextTestModel,\n initTables,\n initTestModels,\n};\n"],"mappings":"2iBAyBA,MAAM,EAAa,CAACA,EAAWC,EAAqBC,EAAuBC,EAAiB,CAKtF,EAAa,MACjB,EACA,EACA,CACE,eAAe,kBACf,gBA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AAM,EAAqB,EAAW,MAAM,EAA6B,EAAE,CAC3E,EAAO,KAAK,iEAAkE,CAAE,MAAO,EAAmB,OAAQ,CAAC,CACnH,MAAM,EAAc,QAAQ,CAAE,MAAO,CAAE,KAAM,EAAG,EAAG,IAAK,EAAmB,IAAI,GAAM,EAAU,KAAK,CAAE,CAAE,CAAE,CAAC,CAC3G,EAAO,KAAK,uDAAuD,QAE9D,EAAO,CAEd,MADA,EAAO,MAAM,uCAAwC,CAAE,QAAO,CAAC,CACzD,KAKN,EAAiB,KAAO,IAAwC,CAGpE,GAFA,EAAO,KAAK,sDAAsD,CAE9D,CAAC,EAAU,UACb,MAAU,MAAM,kDAAkD,CAGpE,EAAU,UAAU,EAAW,CAC/B,MAAM,EAAU,WAAW,gBAAiB,CAAE,QAAS,GAAO,CAAC,CAC/D,MAAM,EAAU,aAAa,gBAAiB,CAAE,QAAS,GAAO,CAAC,CAEjE,EAAO,KAAK,mCAAmC,CAC/C,MAAMT,EAAU,KAAK,CAAE,MAAO,GAAM,CAAC,CACrC,MAAMC,EAAoB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC/C,MAAME,EAAiB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC5C,MAAMD,EAAsB,KAAK,CAAE,MAAO,GAAM,CAAC,CACjD,EAAO,KAAK,oCAAoC"}
@@ -51,6 +51,12 @@ interface CustomFieldOptions {
51
51
  useCustomFieldsEntries?: boolean;
52
52
  useValidators?: boolean;
53
53
  useModelTypeMapping?: boolean;
54
+ /**
55
+ * When true, use umzug to manage migrations via a dedicated `sadot_migrations`
56
+ * table instead of the legacy `sync({ alter: true })` approach.
57
+ * Defaults to false for backwards compatibility.
58
+ */
59
+ useUmzugMigrations?: boolean;
54
60
  getRequiredCustomFields?: (instance: any, fieldDefinitions: CustomFieldDefinition[], options: any) => Promise<string[]> | string[];
55
61
  /**
56
62
  * Optional predicate that returns true when materialized-path RLS is active for the current
@@ -52,6 +52,12 @@ interface CustomFieldOptions {
52
52
  useCustomFieldsEntries?: boolean;
53
53
  useValidators?: boolean;
54
54
  useModelTypeMapping?: boolean;
55
+ /**
56
+ * When true, use umzug to manage migrations via a dedicated `sadot_migrations`
57
+ * table instead of the legacy `sync({ alter: true })` approach.
58
+ * Defaults to false for backwards compatibility.
59
+ */
60
+ useUmzugMigrations?: boolean;
55
61
  getRequiredCustomFields?: (instance: any, fieldDefinitions: CustomFieldDefinition[], options: any) => Promise<string[]> | string[];
56
62
  /**
57
63
  * Optional predicate that returns true when materialized-path RLS is active for the current
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@autofleet/sadot",
3
- "version": "1.5.2",
3
+ "version": "1.6.0-alpha.0",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -45,6 +45,7 @@
45
45
  "reflect-metadata": "^0.1.13",
46
46
  "sequelize": "^6.37.7",
47
47
  "sequelize-typescript": "^2.1.6",
48
+ "umzug": "^3.8.3",
48
49
  "@autofleet/events": "^5.3.13"
49
50
  },
50
51
  "devDependencies": {
@@ -52,10 +53,10 @@
52
53
  "express": "^4.21.2",
53
54
  "npm-watch": "^0.11.0",
54
55
  "supertest": "^7.0.0",
55
- "@autofleet/logger": "^4.5.1",
56
- "@autofleet/node-common": "^4.3.13",
56
+ "@autofleet/errors": "^3.1.53",
57
57
  "@autofleet/zehut": "^4.12.8",
58
- "@autofleet/errors": "^3.1.53"
58
+ "@autofleet/logger": "^4.5.1",
59
+ "@autofleet/node-common": "^4.3.13"
59
60
  },
60
61
  "peerDependencies": {
61
62
  "@autofleet/errors": "^3",