@autofleet/shtinker 3.4.0 → 3.4.1

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,2 @@
1
+ import{isDeepStrictEqual as e}from"node:util";import{getCurrentPayload as t,getUser as n,outbreak as r}from"@autofleet/zehut";import i from"@autofleet/logger";import a from"@autofleet/network";let o=function(e){return e.CREATE=`create`,e.BULK_CREATE=`bulk-create`,e.BULK_EDIT=`bulk-edit`,e.DELETE=`delete`,e.UPDATE=`update`,e.CANCEL=`cancel`,e.FAIL=`fail`,e.UNASSIGN=`unassign`,e.BULK_ASSIGN=`bulk-assign`,e.REASSIGN=`reassign`,e.DISPATCH=`dispatch`,e.BULK_DISPATCH=`bulk-dispatch`,e.BULK_UPSERT=`bulk-upsert`,e.UPSERT=`upsert`,e.JOIN=`join`,e.MOVE=`move`,e.REOPTIMIZATION=`reoptimization`,e}({}),s=function(e){return e.RIDE=`Ride`,e.VEHICLE=`Vehicle`,e.DRIVER=`Driver`,e.PRICE_CALCULATION=`PriceCalculation`,e}({}),c=function(e){return e.USER=`user`,e.AUTOMATION=`automation`,e}({});const l=`audit-log-context`,u=`audit-log-rows`,d=`auditLogContext`,f=`x-af-automation-id`,p=i();p.addContextMiddleware(()=>({traceId:r.getCurrentContextTraceId()}));var m=p;const h=`customFields`,g=()=>{let e=t(),n=e?.nonHeaderContext?.get(d);return n},_={[o.BULK_CREATE]:o.BULK_CREATE,[o.BULK_EDIT]:o.BULK_EDIT,[o.BULK_ASSIGN]:o.BULK_ASSIGN,[o.BULK_DISPATCH]:o.BULK_DISPATCH,[o.BULK_UPSERT]:o.BULK_UPSERT},v=e=>[null,void 0].includes(e)?!0:Array.isArray(e)?e.length===0:typeof e==`object`&&!(e instanceof Date)?Object.keys(e).length===0:!1,y=e=>Object.hasOwn(_,e),b=(e,t)=>e.filter(e=>!v(t.get(e))||!v(t.previous(e))),x=(e,t)=>{let n=t.returning?t.fields:e.changed(),r=b(n.filter(e=>e!==h),e);return r.map(t=>({property:t,previousValue:e.previous(t),newValue:e.get(t)}))},S=t=>{let n=t.changed(),r=n&&n.includes(h);if(!r)return[];let i=t.get(h),a=t.previous(h),o=Object.keys(i).filter(t=>{let n=i?.[t],r=a?.[t];return(!v(n)||!v(r))&&!e(n,r)});return o.map(e=>({property:`${h}.${e}`,previousValue:a?.[e],newValue:i?.[e]}))};var C=class{rabbit;sequelize;logger;excludeModels;constructor(e){this.rabbit=e.rabbit,this.sequelize=e.sequelize,this.logger=e.logger||m,this.excludeModels=e.excludeModels??[]}async manualSendAuditLog({auditContext:e,...t}){if(e??=g(),e)try{e?.entityType?.toLowerCase()===t.entityType?.toLowerCase()&&y(e.action)&&(e.entityId=t.entityId),await this.sendAuditLogRows(t)}catch(e){let{entityType:n,entityId:r}=t;this.logger.error(`Failed to send audit log rows`,{entityType:n,entityId:r,error:e})}}registerHooks(){Object.entries(this.sequelize.models).forEach(([e,t])=>{this.excludeModels.includes(e)||t.addHook(`afterSave`,async(t,n)=>{let r=g();if(!r)return;let{id:i}=t;await this.manualSendAuditLog({entityId:i,auditContext:r,entityType:e,rows:[...x(t,n),...S(t)]})})})}async sendAuditLogContext(e){try{await this.rabbit.sendToQueue(l,e)}catch(e){this.logger.error(`Failed to send audit log context`,e)}}async sendAuditLogRows(e){try{await this.rabbit.sendToQueue(u,e)}catch(e){this.logger.error(`Failed to send audit log rows`,e)}}},w=C;const T=new a({serviceName:`AUDIT_MS`,timeout:6e4,logger:m}),E=async e=>{let{data:t}=await T.get(`api/v1/audit-logs/${e}`);return t},D={getByEntityId:E};var O=D;let k;const A=e=>process.env.DISABLE_AUDIT_LOGS===`true`?!1:(k=new w(e),k.registerHooks(),!0),j=({action:e,endpoint:n,entityType:r,method:i,automationId:a,userId:o})=>{let s=o||(a??null),l=o&&c.USER||a&&c.AUTOMATION||null,u={entityType:r,action:e,endpoint:n,method:i,performedBy:s,actionOrigin:l},f=t();return f.nonHeaderContext.set(d,u),u},M=async(e,t,r,i)=>{try{if(process.env.DISABLE_AUDIT_LOGS===`true`||!k)return;let a=j({action:i,endpoint:e.url,entityType:r,method:e.method,userId:n()?.id,automationId:e.headers[f]});if(!y(i)){await k.sendAuditLogContext(a);return}let o=async()=>{t.off(`finish`,o),t.off(`close`,o),t.off(`error`,o),await k?.sendAuditLogContext(a)};t.once(`finish`,o),t.once(`close`,o),t.once(`error`,o)}catch(e){m.error(`couldn't set audit context`,e)}},N=(e,t)=>async(n,{userId:r,automationId:i})=>{if(process.env.DISABLE_AUDIT_LOGS===`true`||!k)return;let a=j({action:t,endpoint:n,entityType:e,method:`rabbit`,userId:r,automationId:i});await k.sendAuditLogContext(a)};export{d as AUDIT_LOG_CONTEXT_KEY,l as AUDIT_LOG_CONTEXT_QUEUE,u as AUDIT_LOG_ROWS_QUEUE,f as AUTOMATION_ID_HEADER,o as Action,c as ActionOrigin,s as EntityType,w as audit_logger_default,O as audit_ms_default,A as innerEnableAuditing,M as innerSetAuditContext,N as setRabbitAuditContext};
2
+ //# sourceMappingURL=common-DcTpGBvn.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"common-DcTpGBvn.js","names":["logger: LoggerInstanceManager","getCurrentTrace","field: unknown","action: string","fields: string[]","instance: Model","options: CreateOptions | InstanceUpdateOptions","changedFields: string[]","property: string","options: AuditLoggerOptions","logger","context: AuditLogContext","payload: AuditLogPayload","entityId: string","exportObj: { getByEntityId: typeof getByEntityId }","auditLogger: AuditLogger | undefined","options: AuditLoggerOptions","AuditLogger","auditLogContext: AuditLogContext","req: PartialRequest","res: Writable","entityType: string","action: string","logger","endpoint: string"],"sources":["../src/types.ts","../src/const.ts","../src/logger.ts","../src/audit-logger.ts","../src/audit-ms.ts","../src/common.ts"],"sourcesContent":["import type { ModelStatic, Model } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport type RabbitMq from '@autofleet/rabbit';\nimport type { LoggerInstanceManager } from '@autofleet/logger';\nimport type { IRouter } from 'express';\nimport type { FastifyInstance } from 'fastify';\n\nexport type AuditLoggerOptions = {\n rabbit: RabbitMq;\n sequelize: Sequelize;\n logger: LoggerInstanceManager;\n router?: IRouter;\n fastify?: FastifyInstance;\n excludeModels?: string[];\n entityScopedModelMap?: { [modelName: string]: ModelStatic<Model> };\n};\n\nexport interface AuditLogContext {\n entityType: string;\n entityId?: string;\n action: string;\n performedBy: string | null;\n endpoint: string;\n method: string;\n actionOrigin?: string | null;\n}\n\nexport interface AuditLogRow {\n property: string;\n previousValue: unknown;\n newValue: unknown;\n}\n\nexport interface AuditLogPayload {\n entityType: string;\n entityId: string;\n rows: readonly AuditLogRow[];\n}\n\nexport enum Action {\n CREATE = 'create',\n BULK_CREATE = 'bulk-create',\n BULK_EDIT = 'bulk-edit',\n DELETE = 'delete',\n UPDATE = 'update',\n CANCEL = 'cancel',\n FAIL = 'fail',\n UNASSIGN = 'unassign',\n BULK_ASSIGN = 'bulk-assign',\n REASSIGN = 'reassign',\n DISPATCH = 'dispatch',\n BULK_DISPATCH = 'bulk-dispatch',\n BULK_UPSERT = 'bulk-upsert',\n UPSERT = 'upsert',\n JOIN = 'join',\n MOVE = 'move',\n REOPTIMIZATION = 'reoptimization',\n}\n\nexport enum EntityType {\n RIDE = 'Ride',\n VEHICLE = 'Vehicle',\n DRIVER = 'Driver',\n PRICE_CALCULATION = 'PriceCalculation',\n}\n\nexport const enum ActionOrigin {\n USER = 'user',\n AUTOMATION = 'automation',\n}\n","export const AUDIT_LOG_CONTEXT_QUEUE = 'audit-log-context';\nexport const AUDIT_LOG_ROWS_QUEUE = 'audit-log-rows';\nexport const AUDIT_LOG_CONTEXT_KEY = 'auditLogContext';\nexport const AUTOMATION_ID_HEADER = 'x-af-automation-id';\n","import { outbreak } from '@autofleet/zehut';\nimport Logger, { type LoggerInstanceManager } from '@autofleet/logger';\n\nconst logger: LoggerInstanceManager = Logger();\nlogger.addContextMiddleware(() => ({ traceId: outbreak.getCurrentContextTraceId() }));\nexport default logger;\n","import { isDeepStrictEqual } from 'node:util';\nimport type RabbitMq from '@autofleet/rabbit';\nimport type { LoggerInstanceManager } from '@autofleet/logger';\nimport { getCurrentPayload as getCurrentTrace } from '@autofleet/zehut';\nimport type {\n CreateOptions, InstanceUpdateOptions, Model, Sequelize,\n} from 'sequelize';\nimport {\n type AuditLogPayload, type AuditLoggerOptions, type AuditLogContext, Action, type AuditLogRow,\n} from './types';\nimport { AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUDIT_LOG_CONTEXT_KEY } from './const';\nimport logger from './logger';\n\nconst CUSTOM_FIELDS_PROPERTY = 'customFields';\n\nconst getAuditContext = () => {\n const currentTrace = getCurrentTrace();\n const auditContext = currentTrace?.nonHeaderContext?.get(AUDIT_LOG_CONTEXT_KEY);\n return auditContext as AuditLogContext;\n};\n\nconst ACTIONS_TO_OMIT_ENTITY_ID_FROM_CONTEXT = {\n [Action.BULK_CREATE]: Action.BULK_CREATE,\n [Action.BULK_EDIT]: Action.BULK_EDIT,\n [Action.BULK_ASSIGN]: Action.BULK_ASSIGN,\n [Action.BULK_DISPATCH]: Action.BULK_DISPATCH,\n [Action.BULK_UPSERT]: Action.BULK_UPSERT,\n};\n\nconst isEmpty = (field: unknown): boolean => {\n if ([null, undefined].includes(field as undefined)) {\n return true;\n }\n if (Array.isArray(field)) {\n return field.length === 0;\n }\n if (typeof field === 'object' && !(field instanceof Date)) {\n return Object.keys(field as Record<string, unknown>).length === 0;\n }\n return false;\n};\n\nexport const isEntityIdRequired = (action: string): boolean => Object.hasOwn(ACTIONS_TO_OMIT_ENTITY_ID_FROM_CONTEXT, action);\n\nconst filterOutEmptyFields = (fields: string[], instance: Model) => fields.filter((field) => !isEmpty(instance.get(field)) || !isEmpty(instance.previous(field)));\n\nconst getChangedFieldsRows = (instance: Model, options: CreateOptions | InstanceUpdateOptions): AuditLogRow[] => {\n // When bulk updating in sequelize using the \"returning\" option, the instance.changed() stops working.\n // It's a known issue with sequelize.\n const changedFields: string[] = options.returning ? options.fields as string[] : instance.changed() as string[];\n // Filter customFields - we'll handle them later\n const filteredChangedFields = filterOutEmptyFields(changedFields.filter((field) => field !== CUSTOM_FIELDS_PROPERTY), instance);\n return filteredChangedFields.map((property: string) => ({\n property,\n previousValue: instance.previous(property),\n newValue: instance.get(property),\n }));\n};\n\nconst getChangedCustomFieldsRows = (instance: Model): AuditLogRow[] => {\n const changed = instance.changed();\n const customFieldsChanged = changed && changed.includes(CUSTOM_FIELDS_PROPERTY);\n if (!customFieldsChanged) {\n return [];\n }\n\n const customFields = instance.get(CUSTOM_FIELDS_PROPERTY) as Record<string, unknown>;\n const previousCustomFields = instance.previous(CUSTOM_FIELDS_PROPERTY);\n const changedCustomFields = Object.keys(customFields).filter((field) => {\n const newValue = customFields?.[field];\n const oldValue = previousCustomFields?.[field];\n return (!isEmpty(newValue) || !isEmpty(oldValue)) && !isDeepStrictEqual(newValue, oldValue);\n });\n return changedCustomFields.map((changedCustomField) => ({\n property: `${CUSTOM_FIELDS_PROPERTY}.${changedCustomField}`,\n previousValue: previousCustomFields?.[changedCustomField],\n newValue: customFields?.[changedCustomField],\n }));\n};\n\ninterface AuditLogSendData extends AuditLogPayload {\n auditContext?: AuditLogContext;\n}\n\nclass AuditLogger {\n private readonly rabbit: RabbitMq;\n\n private readonly sequelize: Sequelize;\n\n private readonly logger: LoggerInstanceManager;\n\n private readonly excludeModels: string[];\n\n constructor(options: AuditLoggerOptions) {\n this.rabbit = options.rabbit;\n this.sequelize = options.sequelize;\n this.logger = options.logger || logger;\n this.excludeModels = options.excludeModels ?? [];\n }\n\n public async manualSendAuditLog({\n auditContext, ...payload\n }: AuditLogSendData): Promise<void> {\n auditContext ??= getAuditContext();\n if (!auditContext) {\n return;\n }\n try {\n // Make sure the current entity being changed it the \"main\" entity in the current audit context, and if so mark it as the \"entityId\".\n if (auditContext?.entityType?.toLowerCase() === payload.entityType?.toLowerCase() && isEntityIdRequired(auditContext.action)) {\n auditContext.entityId = payload.entityId;\n }\n await this.sendAuditLogRows(payload);\n } catch (error) {\n const { entityType, entityId } = payload;\n this.logger.error('Failed to send audit log rows', { entityType, entityId, error });\n }\n }\n\n public registerHooks(): void {\n Object.entries(this.sequelize.models).forEach(([modelName, modelType]) => {\n if (this.excludeModels.includes(modelName)) {\n return;\n }\n modelType.addHook('afterSave', async (instance, options) => {\n const auditContext = getAuditContext();\n if (!auditContext) return;\n\n const { id: entityId } = instance as unknown as { id: string; };\n await this.manualSendAuditLog({\n entityId,\n auditContext,\n entityType: modelName,\n rows: [...getChangedFieldsRows(instance, options), ...getChangedCustomFieldsRows(instance)],\n });\n });\n });\n }\n\n public async sendAuditLogContext(context: AuditLogContext): Promise<void> {\n try {\n await this.rabbit.sendToQueue(AUDIT_LOG_CONTEXT_QUEUE, context);\n } catch (err) {\n this.logger.error('Failed to send audit log context', err);\n }\n }\n\n private async sendAuditLogRows(payload: AuditLogPayload): Promise<void> {\n try {\n await this.rabbit.sendToQueue(AUDIT_LOG_ROWS_QUEUE, payload);\n } catch (err) {\n this.logger.error('Failed to send audit log rows', err);\n }\n }\n}\n\nexport default AuditLogger;\n","import Network from '@autofleet/network';\nimport logger from './logger';\n\nconst auditMs = new Network({ serviceName: 'AUDIT_MS', timeout: 60_000, logger });\n\nconst getByEntityId = async (entityId: string): Promise<any> => {\n const { data } = await auditMs.get(`api/v1/audit-logs/${entityId}`);\n return data;\n};\n\nconst exportObj: { getByEntityId: typeof getByEntityId } = { getByEntityId };\n\nexport default exportObj;\n","import type { Writable } from 'node:stream';\nimport type { IncomingHttpHeaders } from 'node:http';\nimport { getCurrentPayload, getUser } from '@autofleet/zehut';\nimport logger from './logger';\nimport AuditLogger, { isEntityIdRequired } from './audit-logger';\nimport { AUDIT_LOG_CONTEXT_KEY, AUTOMATION_ID_HEADER } from './const';\nimport { ActionOrigin, type AuditLogContext, type AuditLoggerOptions } from './types';\n\nlet auditLogger: AuditLogger | undefined;\n\nexport const innerEnableAuditing = (options: AuditLoggerOptions): boolean => {\n if (process.env.DISABLE_AUDIT_LOGS === 'true') {\n return false;\n }\n auditLogger = new AuditLogger(options);\n auditLogger.registerHooks();\n return true;\n};\n\ninterface GetAuditLogContextParams {\n action: string;\n endpoint: string;\n entityType: string;\n method: string;\n automationId?: string;\n userId?: string;\n}\nconst getAuditLogContextAndSetToContext = ({\n action, endpoint, entityType, method, automationId, userId,\n}: GetAuditLogContextParams): AuditLogContext => {\n const performedBy = userId || (automationId ?? null);\n const actionOrigin = (userId && ActionOrigin.USER) || (automationId && ActionOrigin.AUTOMATION) || null;\n\n const auditLogContext: AuditLogContext = {\n entityType,\n action,\n endpoint,\n method,\n performedBy,\n actionOrigin,\n };\n const currentTrace = getCurrentPayload();\n currentTrace.nonHeaderContext.set(AUDIT_LOG_CONTEXT_KEY, auditLogContext);\n\n return auditLogContext;\n};\n\ninterface PartialRequest {\n url: string;\n method: string;\n headers: IncomingHttpHeaders;\n}\n\nexport const innerSetAuditContext = async (req: PartialRequest, res: Writable, entityType: string, action: string): Promise<void> => {\n try {\n if (process.env.DISABLE_AUDIT_LOGS === 'true' || !auditLogger) {\n return;\n }\n const auditLogContext = getAuditLogContextAndSetToContext({\n action,\n endpoint: req.url,\n entityType,\n method: req.method,\n userId: getUser()?.id,\n automationId: req.headers[AUTOMATION_ID_HEADER] as string | undefined,\n });\n\n if (!isEntityIdRequired(action)) { // if it's a bulk action, we don't want to wait for the response to add the entity id\n await auditLogger.sendAuditLogContext(auditLogContext);\n return;\n }\n\n const sendAuditLogContextEvent = async () => {\n res.off('finish', sendAuditLogContextEvent);\n res.off('close', sendAuditLogContextEvent);\n res.off('error', sendAuditLogContextEvent);\n await auditLogger?.sendAuditLogContext(auditLogContext);\n };\n res.once('finish', sendAuditLogContextEvent);\n res.once('close', sendAuditLogContextEvent);\n res.once('error', sendAuditLogContextEvent);\n } catch (err) {\n logger.error('couldn\\'t set audit context', err);\n }\n};\n\nexport const setRabbitAuditContext = (entityType: string, action: string) => async (endpoint: string, { userId, automationId }: { userId:string; automationId:string; }): Promise<void> => {\n if (process.env.DISABLE_AUDIT_LOGS === 'true' || !auditLogger) {\n return;\n }\n const auditLogContext = getAuditLogContextAndSetToContext({\n action,\n endpoint,\n entityType,\n method: 'rabbit',\n userId,\n automationId,\n });\n\n await auditLogger.sendAuditLogContext(auditLogContext);\n};\n"],"mappings":"iMAuCA,IAAY,EAAA,SAAA,EAAL,6XAkBN,EAAA,CAAA,EAAA,CAEW,EAAA,SAAA,EAAL,oGAKN,EAAA,CAAA,EAAA,CAEiB,EAAA,SAAA,EAAX,iDAGN,EAAA,CAAA,EAAA,CCrED,MAAa,EAA0B,oBAC1B,EAAuB,iBACvB,EAAwB,kBACxB,EAAuB,qBCA9BA,EAAgC,GAAQ,CAC9C,EAAO,qBAAqB,KAAO,CAAE,QAAS,EAAS,0BAA0B,AAAE,GAAE,CACrF,IAAA,EAAe,ECQf,MAAM,EAAyB,eAEzB,EAAkB,IAAM,CAC5B,IAAM,EAAeC,GAAiB,CAChC,EAAe,GAAc,kBAAkB,IAAI,EAAsB,CAC/E,OAAO,CACR,EAEK,EAAyC,EAC5C,EAAO,aAAc,EAAO,aAC5B,EAAO,WAAY,EAAO,WAC1B,EAAO,aAAc,EAAO,aAC5B,EAAO,eAAgB,EAAO,eAC9B,EAAO,aAAc,EAAO,WAC9B,EAEK,EAAU,AAACC,GACX,CAAC,KAAM,IAAA,EAAU,EAAC,SAAS,EAAmB,CACzC,GAEL,MAAM,QAAQ,EAAM,CACf,EAAM,SAAW,EAEtB,OAAO,GAAU,UAAY,EAAE,aAAiB,MAC3C,OAAO,KAAK,EAAiC,CAAC,SAAW,EAE3D,GAGI,EAAqB,AAACoB,GAA4B,OAAO,OAAO,EAAwC,EAAO,CAEtH,EAAuB,CAAClB,EAAkBC,IAAoB,EAAO,OAAO,AAAC,GAAU,CAAC,EAAQ,EAAS,IAAI,EAAM,CAAC,EAAI,CAAC,EAAQ,EAAS,SAAS,EAAM,CAAC,CAAC,CAE3J,EAAuB,CAACA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var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));const c=s(require(`node:util`)),l=s(require(`@autofleet/zehut`)),u=s(require(`@autofleet/logger`)),d=s(require(`@autofleet/network`));let f=function(e){return e.CREATE=`create`,e.BULK_CREATE=`bulk-create`,e.BULK_EDIT=`bulk-edit`,e.DELETE=`delete`,e.UPDATE=`update`,e.CANCEL=`cancel`,e.FAIL=`fail`,e.UNASSIGN=`unassign`,e.BULK_ASSIGN=`bulk-assign`,e.REASSIGN=`reassign`,e.DISPATCH=`dispatch`,e.BULK_DISPATCH=`bulk-dispatch`,e.BULK_UPSERT=`bulk-upsert`,e.UPSERT=`upsert`,e.JOIN=`join`,e.MOVE=`move`,e.REOPTIMIZATION=`reoptimization`,e}({}),p=function(e){return e.RIDE=`Ride`,e.VEHICLE=`Vehicle`,e.DRIVER=`Driver`,e.PRICE_CALCULATION=`PriceCalculation`,e}({}),m=function(e){return e.USER=`user`,e.AUTOMATION=`automation`,e}({});const h=`audit-log-context`,g=`audit-log-rows`,_=`auditLogContext`,v=`x-af-automation-id`,y=(0,u.default)();y.addContextMiddleware(()=>({traceId:l.outbreak.getCurrentContextTraceId()}));var b=y;const x=`customFields`,S=()=>{let e=(0,l.getCurrentPayload)(),t=e?.nonHeaderContext?.get(_);return t},C={[f.BULK_CREATE]:f.BULK_CREATE,[f.BULK_EDIT]:f.BULK_EDIT,[f.BULK_ASSIGN]:f.BULK_ASSIGN,[f.BULK_DISPATCH]:f.BULK_DISPATCH,[f.BULK_UPSERT]:f.BULK_UPSERT},w=e=>[null,void 0].includes(e)?!0:Array.isArray(e)?e.length===0:typeof e==`object`&&!(e instanceof Date)?Object.keys(e).length===0:!1,T=e=>Object.hasOwn(C,e),E=(e,t)=>e.filter(e=>!w(t.get(e))||!w(t.previous(e))),D=(e,t)=>{let n=t.returning?t.fields:e.changed(),r=E(n.filter(e=>e!==x),e);return r.map(t=>({property:t,previousValue:e.previous(t),newValue:e.get(t)}))},O=e=>{let t=e.changed(),n=t&&t.includes(x);if(!n)return[];let r=e.get(x),i=e.previous(x),a=Object.keys(r).filter(e=>{let t=r?.[e],n=i?.[e];return(!w(t)||!w(n))&&!(0,c.isDeepStrictEqual)(t,n)});return a.map(e=>({property:`${x}.${e}`,previousValue:i?.[e],newValue:r?.[e]}))};var k=class{rabbit;sequelize;logger;excludeModels;constructor(e){this.rabbit=e.rabbit,this.sequelize=e.sequelize,this.logger=e.logger||b,this.excludeModels=e.excludeModels??[]}async manualSendAuditLog({auditContext:e,...t}){if(e??=S(),e)try{e?.entityType?.toLowerCase()===t.entityType?.toLowerCase()&&T(e.action)&&(e.entityId=t.entityId),await this.sendAuditLogRows(t)}catch(e){let{entityType:n,entityId:r}=t;this.logger.error(`Failed to send audit log rows`,{entityType:n,entityId:r,error:e})}}registerHooks(){Object.entries(this.sequelize.models).forEach(([e,t])=>{this.excludeModels.includes(e)||t.addHook(`afterSave`,async(t,n)=>{let r=S();if(!r)return;let{id:i}=t;await this.manualSendAuditLog({entityId:i,auditContext:r,entityType:e,rows:[...D(t,n),...O(t)]})})})}async sendAuditLogContext(e){try{await this.rabbit.sendToQueue(h,e)}catch(e){this.logger.error(`Failed to send audit log context`,e)}}async sendAuditLogRows(e){try{await this.rabbit.sendToQueue(g,e)}catch(e){this.logger.error(`Failed to send audit log rows`,e)}}},A=k;const j=new d.default({serviceName:`AUDIT_MS`,timeout:6e4,logger:b}),M=async e=>{let{data:t}=await j.get(`api/v1/audit-logs/${e}`);return t},N={getByEntityId:M};var P=N;let F;const I=e=>process.env.DISABLE_AUDIT_LOGS===`true`?!1:(F=new A(e),F.registerHooks(),!0),L=({action:e,endpoint:t,entityType:n,method:r,automationId:i,userId:a})=>{let o=a||(i??null),s=a&&m.USER||i&&m.AUTOMATION||null,c={entityType:n,action:e,endpoint:t,method:r,performedBy:o,actionOrigin:s},u=(0,l.getCurrentPayload)();return u.nonHeaderContext.set(_,c),c},R=async(e,t,n,r)=>{try{if(process.env.DISABLE_AUDIT_LOGS===`true`||!F)return;let i=L({action:r,endpoint:e.url,entityType:n,method:e.method,userId:(0,l.getUser)()?.id,automationId:e.headers[v]});if(!T(r)){await F.sendAuditLogContext(i);return}let a=async()=>{t.off(`finish`,a),t.off(`close`,a),t.off(`error`,a),await F?.sendAuditLogContext(i)};t.once(`finish`,a),t.once(`close`,a),t.once(`error`,a)}catch(e){b.error(`couldn't set audit context`,e)}},z=(e,t)=>async(n,{userId:r,automationId:i})=>{if(process.env.DISABLE_AUDIT_LOGS===`true`||!F)return;let a=L({action:t,endpoint:n,entityType:e,method:`rabbit`,userId:r,automationId:i});await F.sendAuditLogContext(a)};Object.defineProperty(exports,`AUDIT_LOG_CONTEXT_KEY`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,`AUDIT_LOG_CONTEXT_QUEUE`,{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,`AUDIT_LOG_ROWS_QUEUE`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,`AUTOMATION_ID_HEADER`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,`Action`,{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,`ActionOrigin`,{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,`EntityType`,{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,`__toESM`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`audit_logger_default`,{enumerable:!0,get:function(){return A}}),Object.defineProperty(exports,`audit_ms_default`,{enumerable:!0,get:function(){return P}}),Object.defineProperty(exports,`innerEnableAuditing`,{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,`innerSetAuditContext`,{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,`setRabbitAuditContext`,{enumerable:!0,get:function(){return z}});
2
+ //# sourceMappingURL=common-kvWo0enA.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"common-kvWo0enA.cjs","names":["logger: LoggerInstanceManager","outbreak","field: unknown","action: string","fields: string[]","instance: Model","options: CreateOptions | InstanceUpdateOptions","changedFields: string[]","property: string","options: AuditLoggerOptions","logger","context: AuditLogContext","payload: AuditLogPayload","Network","entityId: string","exportObj: { getByEntityId: typeof getByEntityId }","auditLogger: AuditLogger | undefined","options: AuditLoggerOptions","AuditLogger","auditLogContext: AuditLogContext","req: PartialRequest","res: Writable","entityType: string","action: string","logger","endpoint: string"],"sources":["../src/types.ts","../src/const.ts","../src/logger.ts","../src/audit-logger.ts","../src/audit-ms.ts","../src/common.ts"],"sourcesContent":["import type { ModelStatic, Model } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport type RabbitMq from '@autofleet/rabbit';\nimport type { LoggerInstanceManager } from '@autofleet/logger';\nimport type { IRouter } from 'express';\nimport type { FastifyInstance } from 'fastify';\n\nexport type AuditLoggerOptions = {\n rabbit: RabbitMq;\n sequelize: Sequelize;\n logger: LoggerInstanceManager;\n router?: IRouter;\n fastify?: FastifyInstance;\n excludeModels?: string[];\n entityScopedModelMap?: { [modelName: string]: ModelStatic<Model> };\n};\n\nexport interface AuditLogContext {\n entityType: string;\n entityId?: string;\n action: string;\n performedBy: string | null;\n endpoint: string;\n method: string;\n actionOrigin?: string | null;\n}\n\nexport interface AuditLogRow {\n property: string;\n previousValue: unknown;\n newValue: unknown;\n}\n\nexport interface AuditLogPayload {\n entityType: string;\n entityId: string;\n rows: readonly AuditLogRow[];\n}\n\nexport enum Action {\n CREATE = 'create',\n BULK_CREATE = 'bulk-create',\n BULK_EDIT = 'bulk-edit',\n DELETE = 'delete',\n UPDATE = 'update',\n CANCEL = 'cancel',\n FAIL = 'fail',\n UNASSIGN = 'unassign',\n BULK_ASSIGN = 'bulk-assign',\n REASSIGN = 'reassign',\n DISPATCH = 'dispatch',\n BULK_DISPATCH = 'bulk-dispatch',\n BULK_UPSERT = 'bulk-upsert',\n UPSERT = 'upsert',\n JOIN = 'join',\n MOVE = 'move',\n REOPTIMIZATION = 'reoptimization',\n}\n\nexport enum EntityType {\n RIDE = 'Ride',\n VEHICLE = 'Vehicle',\n DRIVER = 'Driver',\n PRICE_CALCULATION = 'PriceCalculation',\n}\n\nexport const enum ActionOrigin {\n USER = 'user',\n AUTOMATION = 'automation',\n}\n","export const AUDIT_LOG_CONTEXT_QUEUE = 'audit-log-context';\nexport const AUDIT_LOG_ROWS_QUEUE = 'audit-log-rows';\nexport const AUDIT_LOG_CONTEXT_KEY = 'auditLogContext';\nexport const AUTOMATION_ID_HEADER = 'x-af-automation-id';\n","import { outbreak } from '@autofleet/zehut';\nimport Logger, { type LoggerInstanceManager } from '@autofleet/logger';\n\nconst logger: LoggerInstanceManager = Logger();\nlogger.addContextMiddleware(() => ({ traceId: outbreak.getCurrentContextTraceId() }));\nexport default logger;\n","import { isDeepStrictEqual } from 'node:util';\nimport type RabbitMq from '@autofleet/rabbit';\nimport type { LoggerInstanceManager } from '@autofleet/logger';\nimport { getCurrentPayload as getCurrentTrace } from '@autofleet/zehut';\nimport type {\n CreateOptions, InstanceUpdateOptions, Model, Sequelize,\n} from 'sequelize';\nimport {\n type AuditLogPayload, type AuditLoggerOptions, type AuditLogContext, Action, type AuditLogRow,\n} from './types';\nimport { AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUDIT_LOG_CONTEXT_KEY } from './const';\nimport logger from './logger';\n\nconst CUSTOM_FIELDS_PROPERTY = 'customFields';\n\nconst getAuditContext = () => {\n const currentTrace = getCurrentTrace();\n const auditContext = currentTrace?.nonHeaderContext?.get(AUDIT_LOG_CONTEXT_KEY);\n return auditContext as AuditLogContext;\n};\n\nconst ACTIONS_TO_OMIT_ENTITY_ID_FROM_CONTEXT = {\n [Action.BULK_CREATE]: Action.BULK_CREATE,\n [Action.BULK_EDIT]: Action.BULK_EDIT,\n [Action.BULK_ASSIGN]: Action.BULK_ASSIGN,\n [Action.BULK_DISPATCH]: Action.BULK_DISPATCH,\n [Action.BULK_UPSERT]: Action.BULK_UPSERT,\n};\n\nconst isEmpty = (field: unknown): boolean => {\n if ([null, undefined].includes(field as undefined)) {\n return true;\n }\n if (Array.isArray(field)) {\n return field.length === 0;\n }\n if (typeof field === 'object' && !(field instanceof Date)) {\n return Object.keys(field as Record<string, unknown>).length === 0;\n }\n return false;\n};\n\nexport const isEntityIdRequired = (action: string): boolean => Object.hasOwn(ACTIONS_TO_OMIT_ENTITY_ID_FROM_CONTEXT, action);\n\nconst filterOutEmptyFields = (fields: string[], instance: Model) => fields.filter((field) => !isEmpty(instance.get(field)) || !isEmpty(instance.previous(field)));\n\nconst getChangedFieldsRows = (instance: Model, options: CreateOptions | InstanceUpdateOptions): AuditLogRow[] => {\n // When bulk updating in sequelize using the \"returning\" option, the instance.changed() stops working.\n // It's a known issue with sequelize.\n const changedFields: string[] = options.returning ? options.fields as string[] : instance.changed() as string[];\n // Filter customFields - we'll handle them later\n const filteredChangedFields = filterOutEmptyFields(changedFields.filter((field) => field !== CUSTOM_FIELDS_PROPERTY), instance);\n return filteredChangedFields.map((property: string) => ({\n property,\n previousValue: instance.previous(property),\n newValue: instance.get(property),\n }));\n};\n\nconst getChangedCustomFieldsRows = (instance: Model): AuditLogRow[] => {\n const changed = instance.changed();\n const customFieldsChanged = changed && changed.includes(CUSTOM_FIELDS_PROPERTY);\n if (!customFieldsChanged) {\n return [];\n }\n\n const customFields = instance.get(CUSTOM_FIELDS_PROPERTY) as Record<string, unknown>;\n const previousCustomFields = instance.previous(CUSTOM_FIELDS_PROPERTY);\n const changedCustomFields = Object.keys(customFields).filter((field) => {\n const newValue = customFields?.[field];\n const oldValue = previousCustomFields?.[field];\n return (!isEmpty(newValue) || !isEmpty(oldValue)) && !isDeepStrictEqual(newValue, oldValue);\n });\n return changedCustomFields.map((changedCustomField) => ({\n property: `${CUSTOM_FIELDS_PROPERTY}.${changedCustomField}`,\n previousValue: previousCustomFields?.[changedCustomField],\n newValue: customFields?.[changedCustomField],\n }));\n};\n\ninterface AuditLogSendData extends AuditLogPayload {\n auditContext?: AuditLogContext;\n}\n\nclass AuditLogger {\n private readonly rabbit: RabbitMq;\n\n private readonly sequelize: Sequelize;\n\n private readonly logger: LoggerInstanceManager;\n\n private readonly excludeModels: string[];\n\n constructor(options: AuditLoggerOptions) {\n this.rabbit = options.rabbit;\n this.sequelize = options.sequelize;\n this.logger = options.logger || logger;\n this.excludeModels = options.excludeModels ?? [];\n }\n\n public async manualSendAuditLog({\n auditContext, ...payload\n }: AuditLogSendData): Promise<void> {\n auditContext ??= getAuditContext();\n if (!auditContext) {\n return;\n }\n try {\n // Make sure the current entity being changed it the \"main\" entity in the current audit context, and if so mark it as the \"entityId\".\n if (auditContext?.entityType?.toLowerCase() === payload.entityType?.toLowerCase() && isEntityIdRequired(auditContext.action)) {\n auditContext.entityId = payload.entityId;\n }\n await this.sendAuditLogRows(payload);\n } catch (error) {\n const { entityType, entityId } = payload;\n this.logger.error('Failed to send audit log rows', { entityType, entityId, error });\n }\n }\n\n public registerHooks(): void {\n Object.entries(this.sequelize.models).forEach(([modelName, modelType]) => {\n if (this.excludeModels.includes(modelName)) {\n return;\n }\n modelType.addHook('afterSave', async (instance, options) => {\n const auditContext = getAuditContext();\n if (!auditContext) return;\n\n const { id: entityId } = instance as unknown as { id: string; };\n await this.manualSendAuditLog({\n entityId,\n auditContext,\n entityType: modelName,\n rows: [...getChangedFieldsRows(instance, options), ...getChangedCustomFieldsRows(instance)],\n });\n });\n });\n }\n\n public async sendAuditLogContext(context: AuditLogContext): Promise<void> {\n try {\n await this.rabbit.sendToQueue(AUDIT_LOG_CONTEXT_QUEUE, context);\n } catch (err) {\n this.logger.error('Failed to send audit log context', err);\n }\n }\n\n private async sendAuditLogRows(payload: AuditLogPayload): Promise<void> {\n try {\n await this.rabbit.sendToQueue(AUDIT_LOG_ROWS_QUEUE, payload);\n } catch (err) {\n this.logger.error('Failed to send audit log rows', err);\n }\n }\n}\n\nexport default AuditLogger;\n","import Network from '@autofleet/network';\nimport logger from './logger';\n\nconst auditMs = new Network({ serviceName: 'AUDIT_MS', timeout: 60_000, logger });\n\nconst getByEntityId = async (entityId: string): Promise<any> => {\n const { data } = await auditMs.get(`api/v1/audit-logs/${entityId}`);\n return data;\n};\n\nconst exportObj: { getByEntityId: typeof getByEntityId } = { getByEntityId };\n\nexport default exportObj;\n","import type { Writable } from 'node:stream';\nimport type { IncomingHttpHeaders } from 'node:http';\nimport { getCurrentPayload, getUser } from '@autofleet/zehut';\nimport logger from './logger';\nimport AuditLogger, { isEntityIdRequired } from './audit-logger';\nimport { AUDIT_LOG_CONTEXT_KEY, AUTOMATION_ID_HEADER } from './const';\nimport { ActionOrigin, type AuditLogContext, type AuditLoggerOptions } from './types';\n\nlet auditLogger: AuditLogger | undefined;\n\nexport const innerEnableAuditing = (options: AuditLoggerOptions): boolean => {\n if (process.env.DISABLE_AUDIT_LOGS === 'true') {\n return false;\n }\n auditLogger = new AuditLogger(options);\n auditLogger.registerHooks();\n return true;\n};\n\ninterface GetAuditLogContextParams {\n action: string;\n endpoint: string;\n entityType: string;\n method: string;\n automationId?: string;\n userId?: string;\n}\nconst getAuditLogContextAndSetToContext = ({\n action, endpoint, entityType, method, automationId, userId,\n}: GetAuditLogContextParams): AuditLogContext => {\n const performedBy = userId || (automationId ?? null);\n const actionOrigin = (userId && ActionOrigin.USER) || (automationId && ActionOrigin.AUTOMATION) || null;\n\n const auditLogContext: AuditLogContext = {\n entityType,\n action,\n endpoint,\n method,\n performedBy,\n actionOrigin,\n };\n const currentTrace = getCurrentPayload();\n currentTrace.nonHeaderContext.set(AUDIT_LOG_CONTEXT_KEY, auditLogContext);\n\n return auditLogContext;\n};\n\ninterface PartialRequest {\n url: string;\n method: string;\n headers: IncomingHttpHeaders;\n}\n\nexport const innerSetAuditContext = async (req: PartialRequest, res: Writable, entityType: string, action: string): Promise<void> => {\n try {\n if (process.env.DISABLE_AUDIT_LOGS === 'true' || !auditLogger) {\n return;\n }\n const auditLogContext = getAuditLogContextAndSetToContext({\n action,\n endpoint: req.url,\n entityType,\n method: req.method,\n userId: getUser()?.id,\n automationId: req.headers[AUTOMATION_ID_HEADER] as string | undefined,\n });\n\n if (!isEntityIdRequired(action)) { // if it's a bulk action, we don't want to wait for the response to add the entity id\n await auditLogger.sendAuditLogContext(auditLogContext);\n return;\n }\n\n const sendAuditLogContextEvent = async () => {\n res.off('finish', sendAuditLogContextEvent);\n res.off('close', sendAuditLogContextEvent);\n res.off('error', sendAuditLogContextEvent);\n await auditLogger?.sendAuditLogContext(auditLogContext);\n };\n res.once('finish', sendAuditLogContextEvent);\n res.once('close', sendAuditLogContextEvent);\n res.once('error', sendAuditLogContextEvent);\n } catch (err) {\n logger.error('couldn\\'t set audit context', err);\n }\n};\n\nexport const setRabbitAuditContext = (entityType: string, action: string) => async (endpoint: string, { userId, automationId }: { userId:string; automationId:string; }): Promise<void> => {\n if (process.env.DISABLE_AUDIT_LOGS === 'true' || !auditLogger) {\n return;\n }\n const auditLogContext = getAuditLogContextAndSetToContext({\n action,\n endpoint,\n entityType,\n method: 'rabbit',\n userId,\n automationId,\n });\n\n await auditLogger.sendAuditLogContext(auditLogContext);\n};\n"],"mappings":"omBAuCA,IAAY,EAAA,SAAA,EAAL,6XAkBN,EAAA,CAAA,EAAA,CAEW,EAAA,SAAA,EAAL,oGAKN,EAAA,CAAA,EAAA,CAEiB,EAAA,SAAA,EAAX,iDAGN,EAAA,CAAA,EAAA,CCrED,MAAa,EAA0B,oBAC1B,EAAuB,iBACvB,EAAwB,kBACxB,EAAuB,qBCA9BA,GAAAA,EAAAA,EAAAA,UAAwC,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,QAAU,CAAC,EAChD,OAEF,IAAM,EAAkB,EAAkC,CACxD,SACA,SAAU,EAAI,IACd,aACA,OAAQ,EAAI,OACZ,QAAA,EAAA,EAAA,UAAiB,EAAE,GACnB,aAAc,EAAI,QAAQ,EAC3B,EAAC,CAEF,GAAI,CAAC,EAAmB,EAAO,CAAE,CAC/B,MAAM,EAAY,oBAAoB,EAAgB,CACtD,MACD,CAED,IAAM,EAA2B,SAAY,CAC3C,EAAI,IAAI,SAAU,EAAyB,CAC3C,EAAI,IAAI,QAAS,EAAyB,CAC1C,EAAI,IAAI,QAAS,EAAyB,CAC1C,MAAM,GAAa,oBAAoB,EAAgB,AACxD,EACD,EAAI,KAAK,SAAU,EAAyB,CAC5C,EAAI,KAAK,QAAS,EAAyB,CAC3C,EAAI,KAAK,QAAS,EAAyB,AAC5C,OAAQ,EAAK,CACZC,EAAO,MAAM,6BAA+B,EAAI,AACjD,CACF,EAEY,EAAwB,CAACF,EAAoBC,IAAmB,MAAOE,EAAkB,CAAE,SAAQ,eAAuD,GAAoB,CACzL,GAAI,QAAQ,IAAI,qBAAuB,QAAU,CAAC,EAChD,OAEF,IAAM,EAAkB,EAAkC,CACxD,SACA,WACA,aACA,OAAQ,SACR,SACA,cACD,EAAC,CAEF,MAAM,EAAY,oBAAoB,EAAgB,AACvD"}
@@ -1,8 +1,8 @@
1
+ import { LoggerInstanceManager } from "@autofleet/logger";
1
2
  import { FastifyInstance } from "fastify";
2
3
  import { Model, ModelStatic } from "sequelize";
3
4
  import { Sequelize } from "sequelize-typescript";
4
5
  import RabbitMq from "@autofleet/rabbit";
5
- import { LoggerInstanceManager } from "@autofleet/logger";
6
6
  import { IRouter } from "express";
7
7
 
8
8
  //#region src/types.d.ts
@@ -64,16 +64,17 @@ declare enum EntityType {
64
64
  declare const enum ActionOrigin {
65
65
  USER = "user",
66
66
  AUTOMATION = "automation",
67
- } //#endregion
67
+ }
68
+ //#endregion
68
69
  //#region src/audit-logger.d.ts
69
70
  interface AuditLogSendData extends AuditLogPayload {
70
71
  auditContext?: AuditLogContext;
71
72
  }
72
73
  declare class AuditLogger {
73
- private rabbit;
74
- private sequelize;
75
- private logger;
76
- private excludeModels;
74
+ private readonly rabbit;
75
+ private readonly sequelize;
76
+ private readonly logger;
77
+ private readonly excludeModels;
77
78
  constructor(options: AuditLoggerOptions);
78
79
  manualSendAuditLog({
79
80
  auditContext,
@@ -83,7 +84,6 @@ declare class AuditLogger {
83
84
  sendAuditLogContext(context: AuditLogContext): Promise<void>;
84
85
  private sendAuditLogRows;
85
86
  }
86
-
87
87
  //#endregion
88
88
  //#region src/common.d.ts
89
89
  declare const setRabbitAuditContext: (entityType: string, action: string) => (endpoint: string, {
@@ -93,14 +93,12 @@ declare const setRabbitAuditContext: (entityType: string, action: string) => (en
93
93
  userId: string;
94
94
  automationId: string;
95
95
  }) => Promise<void>;
96
-
97
96
  //#endregion
98
97
  //#region src/const.d.ts
99
98
  declare const AUDIT_LOG_CONTEXT_QUEUE = "audit-log-context";
100
99
  declare const AUDIT_LOG_ROWS_QUEUE = "audit-log-rows";
101
100
  declare const AUDIT_LOG_CONTEXT_KEY = "auditLogContext";
102
101
  declare const AUTOMATION_ID_HEADER = "x-af-automation-id";
103
-
104
102
  //#endregion
105
103
  export { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType, setRabbitAuditContext };
106
- //# sourceMappingURL=const-ByTOLhRM.d.cts.map
104
+ //# sourceMappingURL=const-CaukuTPn.d.ts.map
@@ -1,8 +1,8 @@
1
- import { LoggerInstanceManager } from "@autofleet/logger";
2
1
  import { FastifyInstance } from "fastify";
3
2
  import { Model, ModelStatic } from "sequelize";
4
3
  import { Sequelize } from "sequelize-typescript";
5
4
  import RabbitMq from "@autofleet/rabbit";
5
+ import { LoggerInstanceManager } from "@autofleet/logger";
6
6
  import { IRouter } from "express";
7
7
 
8
8
  //#region src/types.d.ts
@@ -64,16 +64,17 @@ declare enum EntityType {
64
64
  declare const enum ActionOrigin {
65
65
  USER = "user",
66
66
  AUTOMATION = "automation",
67
- } //#endregion
67
+ }
68
+ //#endregion
68
69
  //#region src/audit-logger.d.ts
69
70
  interface AuditLogSendData extends AuditLogPayload {
70
71
  auditContext?: AuditLogContext;
71
72
  }
72
73
  declare class AuditLogger {
73
- private rabbit;
74
- private sequelize;
75
- private logger;
76
- private excludeModels;
74
+ private readonly rabbit;
75
+ private readonly sequelize;
76
+ private readonly logger;
77
+ private readonly excludeModels;
77
78
  constructor(options: AuditLoggerOptions);
78
79
  manualSendAuditLog({
79
80
  auditContext,
@@ -83,7 +84,6 @@ declare class AuditLogger {
83
84
  sendAuditLogContext(context: AuditLogContext): Promise<void>;
84
85
  private sendAuditLogRows;
85
86
  }
86
-
87
87
  //#endregion
88
88
  //#region src/common.d.ts
89
89
  declare const setRabbitAuditContext: (entityType: string, action: string) => (endpoint: string, {
@@ -93,14 +93,12 @@ declare const setRabbitAuditContext: (entityType: string, action: string) => (en
93
93
  userId: string;
94
94
  automationId: string;
95
95
  }) => Promise<void>;
96
-
97
96
  //#endregion
98
97
  //#region src/const.d.ts
99
98
  declare const AUDIT_LOG_CONTEXT_QUEUE = "audit-log-context";
100
99
  declare const AUDIT_LOG_ROWS_QUEUE = "audit-log-rows";
101
100
  declare const AUDIT_LOG_CONTEXT_KEY = "auditLogContext";
102
101
  declare const AUTOMATION_ID_HEADER = "x-af-automation-id";
103
-
104
102
  //#endregion
105
- export { AUDIT_LOG_CONTEXT_KEY as AUDIT_LOG_CONTEXT_KEY$1, AUDIT_LOG_CONTEXT_QUEUE as AUDIT_LOG_CONTEXT_QUEUE$1, AUDIT_LOG_ROWS_QUEUE as AUDIT_LOG_ROWS_QUEUE$1, AUTOMATION_ID_HEADER as AUTOMATION_ID_HEADER$1, Action as Action$1, ActionOrigin as ActionOrigin$1, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType as EntityType$1, setRabbitAuditContext as setRabbitAuditContext$1 };
106
- //# sourceMappingURL=const-DTsi7GAD.d.ts.map
103
+ export { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType, setRabbitAuditContext };
104
+ //# sourceMappingURL=const-CsCfdvC8.d.cts.map
package/dist/fastify.cjs CHANGED
@@ -1,11 +1,2 @@
1
- "use strict";Object.defineProperty(exports,`__esModule`,{value:!0});
2
- /** Swagger tag for audit logs API. Add this to the `tags` array passed into the options of `fastify-plugin`. */
3
- const e=require(`./common-DLsvf3zA.cjs`),t=e.__toESM(require(`@autofleet/errors`)),n={name:`audit`,description:`Audit logs API`};async function r({fastify:r,logger:i,entityScopedModelMap:a}){!a||!r||Object.entries(a).forEach(([a,o])=>{r.get(`/api/v1/${a}/:id/audit`,{schema:{tags:[n.name],description:`Get audit logs for ${a} by ID`,params:{type:`object`,properties:{id:{type:`string`}},required:[`id`]}}},async n=>{let{id:r}=n.params,s=await o.findByPk(r);if(!s){let e=new t.ResourceNotFoundError;throw i.error(`Entity ${a} with id ${r} not found`,{err:e}),e}return e.audit_ms_default.getByEntityId(r)})})}
4
- /**
5
- * A builder of `onRequest` hook for the request handler, which sets the audit context for the request lifecycle.
6
- * @param entityType The type of the entity being audited.
7
- * @param action The action being performed on the entity.
8
- * @returns A Fastify `onRequest` hook.
9
- */
10
- const i=t=>{let n=e.innerEnableAuditing(t);n&&r(t)},a=(t,n)=>async(r,i)=>{await e.innerSetAuditContext(r,i.raw,t,n)};var o=e.audit_logger_default;exports.AUDIT_LOG_CONTEXT_KEY=e.AUDIT_LOG_CONTEXT_KEY,exports.AUDIT_LOG_CONTEXT_QUEUE=e.AUDIT_LOG_CONTEXT_QUEUE,exports.AUDIT_LOG_ROWS_QUEUE=e.AUDIT_LOG_ROWS_QUEUE,exports.AUTOMATION_ID_HEADER=e.AUTOMATION_ID_HEADER,exports.Action=e.Action,exports.ActionOrigin=e.ActionOrigin,exports.EntityType=e.EntityType,exports.SWAGGER_TAG=n,exports.default=o,exports.enableAuditing=i,exports.setAuditContext=a,exports.setRabbitAuditContext=e.setRabbitAuditContext;
1
+ Object.defineProperty(exports,`__esModule`,{value:!0});const e=require(`./common-kvWo0enA.cjs`),t=e.__toESM(require(`@autofleet/errors`)),n={name:`audit`,description:`Audit logs API`};async function r({fastify:r,logger:i,entityScopedModelMap:a}){!a||!r||Object.entries(a).forEach(([a,o])=>{r.get(`/api/v1/${a}/:id/audit`,{schema:{tags:[n.name],description:`Get audit logs for ${a} by ID`,params:{type:`object`,properties:{id:{type:`string`}},required:[`id`]}}},async n=>{let{id:r}=n.params,s=await o.findByPk(r);if(!s){let e=new t.ResourceNotFoundError;throw i.error(`Entity ${a} with id ${r} not found`,{err:e}),e}return e.audit_ms_default.getByEntityId(r)})})}const i=t=>{let n=e.innerEnableAuditing(t);n&&r(t)},a=(t,n)=>async(r,i)=>{await e.innerSetAuditContext(r,i.raw,t,n)};var o=e.audit_logger_default;exports.AUDIT_LOG_CONTEXT_KEY=e.AUDIT_LOG_CONTEXT_KEY,exports.AUDIT_LOG_CONTEXT_QUEUE=e.AUDIT_LOG_CONTEXT_QUEUE,exports.AUDIT_LOG_ROWS_QUEUE=e.AUDIT_LOG_ROWS_QUEUE,exports.AUTOMATION_ID_HEADER=e.AUTOMATION_ID_HEADER,exports.Action=e.Action,exports.ActionOrigin=e.ActionOrigin,exports.EntityType=e.EntityType,exports.SWAGGER_TAG=n,exports.default=o,exports.enableAuditing=i,exports.setAuditContext=a,exports.setRabbitAuditContext=e.setRabbitAuditContext;
11
2
  //# sourceMappingURL=fastify.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"fastify.cjs","names":["options: AuditLoggerOptions","entityType: string","action: string"],"sources":["../src/audit-api/fastify.ts","../src/fastify.ts"],"sourcesContent":["import { ResourceNotFoundError } from '@autofleet/errors';\nimport auditMs from '../audit-ms';\nimport type { AuditLoggerOptions } from '../types';\n\n/** Swagger tag for audit logs API. Add this to the `tags` array passed into the options of `fastify-plugin`. */\nexport const SWAGGER_TAG = { name: 'audit', description: 'Audit logs API' };\n\nexport async function addAuditApi({ fastify, logger, entityScopedModelMap }: AuditLoggerOptions): Promise<void> {\n if (!entityScopedModelMap || !fastify) {\n return;\n }\n Object.entries(entityScopedModelMap).forEach(([entity, ScopedModel]) => {\n fastify.get(\n `/api/v1/${entity}/:id/audit`,\n {\n schema: {\n tags: [SWAGGER_TAG.name],\n description: `Get audit logs for ${entity} by ID`,\n params: {\n type: 'object',\n properties: {\n id: { type: 'string' },\n },\n required: ['id'],\n },\n },\n },\n async (req) => {\n const { id } = req.params as { id: string; };\n const entityData = await ScopedModel.findByPk(id);\n if (!entityData) {\n const err = new ResourceNotFoundError();\n logger.error(`Entity ${entity} with id ${id} not found`, { err });\n throw err;\n }\n return auditMs.getByEntityId(id);\n },\n );\n });\n}\n","import type { onRequestAsyncHookHandler } from 'fastify';\nimport AuditLogger from './audit-logger';\nimport { addAuditApi, SWAGGER_TAG } from './audit-api/fastify';\nimport type { AuditLoggerOptions } from './types';\nimport { innerEnableAuditing, innerSetAuditContext, setRabbitAuditContext } from './common';\n\nexport const enableAuditing = (options: AuditLoggerOptions): void => {\n const addApi = innerEnableAuditing(options);\n if (!addApi) {\n return;\n }\n addAuditApi(options);\n};\n\n/**\n * A builder of `onRequest` hook for the request handler, which sets the audit context for the request lifecycle.\n * @param entityType The type of the entity being audited.\n * @param action The action being performed on the entity.\n * @returns A Fastify `onRequest` hook.\n */\nexport const setAuditContext = (entityType: string, action: string): onRequestAsyncHookHandler => async (request, reply) => {\n await innerSetAuditContext(request, reply.raw, entityType, action);\n};\n\nexport { setRabbitAuditContext, SWAGGER_TAG };\n\nexport * from './types';\nexport * from './const';\n\nexport default AuditLogger;\n"],"mappings":";;AAKA,mFAAa,EAAc,CAAE,KAAM,QAAS,YAAa,gBAAkB,EAE3E,eAAsB,EAAY,CAAE,UAAS,SAAQ,uBAA0C,CAAiB,CAC9G,CAAK,IAAyB,GAG9B,OAAO,QAAQ,EAAqB,CAAC,QAAQ,CAAC,CAAC,EAAQ,EAAY,GAAK,CACtE,EAAQ,KACL,UAAU,EAAO,YAClB,CACE,OAAQ,CACN,KAAM,CAAC,EAAY,IAAK,EACxB,aAAc,qBAAqB,EAAO,QAC1C,OAAQ,CACN,KAAM,SACN,WAAY,CACV,GAAI,CAAE,KAAM,QAAU,CACvB,EACD,SAAU,CAAC,IAAK,CACjB,CACF,CACF,EACD,MAAO,GAAQ,CAEb,GADM,CAAE,KAAI,CAAG,EAAI,OACb,EAAa,KAAM,GAAY,SAAS,EAAG,CACjD,IAAK,EAAY,CACf,IAAM,EAAM,IAAI,EAAA,sBAEhB,KADA,GAAO,OAAO,SAAS,EAAO,WAAW,EAAG,YAAa,CAAE,KAAK,EAAC,CAC3D,CACP,CACD,MAAO,GAAA,iBAAQ,cAAc,EAAG,AACjC,EACF,AACF,EAAC,AACH;;;;;;;ACnBD,MAda,EAAiB,AAACA,GAAsC,CACnE,IAAM,EAAS,EAAA,oBAAoB,EAAQ,CACtC,GAGL,EAAY,EAAQ,AACrB,EAQY,EAAkB,CAACC,EAAoBC,IAA8C,MAAO,EAAS,IAAU,CAC1H,KAAM,GAAA,qBAAqB,EAAS,EAAM,IAAK,EAAY,EAAO,AACnE,EAOD,IAAA,EAAe,EAAA"}
1
+ {"version":3,"file":"fastify.cjs","names":["ResourceNotFoundError","auditMs","options: AuditLoggerOptions","innerEnableAuditing","entityType: string","action: string","innerSetAuditContext","AuditLogger"],"sources":["../src/audit-api/fastify.ts","../src/fastify.ts"],"sourcesContent":["import { ResourceNotFoundError } from '@autofleet/errors';\nimport auditMs from '../audit-ms';\nimport type { AuditLoggerOptions } from '../types';\n\n/** Swagger tag for audit logs API. Add this to the `tags` array passed into the options of `fastify-plugin`. */\nexport const SWAGGER_TAG = { name: 'audit', description: 'Audit logs API' };\n\nexport async function addAuditApi({ fastify, logger, entityScopedModelMap }: AuditLoggerOptions): Promise<void> {\n if (!entityScopedModelMap || !fastify) {\n return;\n }\n Object.entries(entityScopedModelMap).forEach(([entity, ScopedModel]) => {\n fastify.get(\n `/api/v1/${entity}/:id/audit`,\n {\n schema: {\n tags: [SWAGGER_TAG.name],\n description: `Get audit logs for ${entity} by ID`,\n params: {\n type: 'object',\n properties: {\n id: { type: 'string' },\n },\n required: ['id'],\n },\n },\n },\n async (req) => {\n const { id } = req.params as { id: string; };\n const entityData = await ScopedModel.findByPk(id);\n if (!entityData) {\n const err = new ResourceNotFoundError();\n logger.error(`Entity ${entity} with id ${id} not found`, { err });\n throw err;\n }\n return auditMs.getByEntityId(id);\n },\n );\n });\n}\n","import type { onRequestAsyncHookHandler } from 'fastify';\nimport AuditLogger from './audit-logger';\nimport { addAuditApi, SWAGGER_TAG } from './audit-api/fastify';\nimport type { AuditLoggerOptions } from './types';\nimport { innerEnableAuditing, innerSetAuditContext, setRabbitAuditContext } from './common';\n\nexport const enableAuditing = (options: AuditLoggerOptions): void => {\n const addApi = innerEnableAuditing(options);\n if (!addApi) {\n return;\n }\n addAuditApi(options);\n};\n\n/**\n * A builder of `onRequest` hook for the request handler, which sets the audit context for the request lifecycle.\n * @param entityType The type of the entity being audited.\n * @param action The action being performed on the entity.\n * @returns A Fastify `onRequest` hook.\n */\nexport const setAuditContext = (entityType: string, action: string): onRequestAsyncHookHandler => async (request, reply) => {\n await innerSetAuditContext(request, reply.raw, entityType, action);\n};\n\nexport { setRabbitAuditContext, SWAGGER_TAG };\n\nexport * from './types';\nexport * from './const';\n\nexport default AuditLogger;\n"],"mappings":"0IAKa,EAAc,CAAE,KAAM,QAAS,YAAa,gBAAkB,EAE3E,eAAsB,EAAY,CAAE,UAAS,SAAQ,uBAA0C,CAAiB,CAC1G,CAAC,GAAwB,CAAC,GAG9B,OAAO,QAAQ,EAAqB,CAAC,QAAQ,CAAC,CAAC,EAAQ,EAAY,GAAK,CACtE,EAAQ,IACN,CAAC,QAAQ,EAAE,EAAO,UAAU,CAAC,CAC7B,CACE,OAAQ,CACN,KAAM,CAAC,EAAY,IAAK,EACxB,YAAa,CAAC,mBAAmB,EAAE,EAAO,MAAM,CAAC,CACjD,OAAQ,CACN,KAAM,SACN,WAAY,CACV,GAAI,CAAE,KAAM,QAAU,CACvB,EACD,SAAU,CAAC,IAAK,CACjB,CACF,CACF,EACD,MAAO,GAAQ,CACb,GAAM,CAAE,KAAI,CAAG,EAAI,OACb,EAAa,MAAM,EAAY,SAAS,EAAG,CACjD,GAAI,CAAC,EAAY,CACf,IAAM,EAAM,IAAIA,EAAAA,sBAEhB,MADA,EAAO,MAAM,CAAC,OAAO,EAAE,EAAO,SAAS,EAAE,EAAG,UAAU,CAAC,CAAE,CAAE,KAAK,EAAC,CAC3D,CACP,CACD,OAAOC,EAAAA,iBAAQ,cAAc,EAAG,AACjC,EACF,AACF,EAAC,AACH,CCjCD,MAAa,EAAiB,AAACC,GAAsC,CACnE,IAAM,EAASC,EAAAA,oBAAoB,EAAQ,CACtC,GAGL,EAAY,EAAQ,AACrB,EAQY,EAAkB,CAACC,EAAoBC,IAA8C,MAAO,EAAS,IAAU,CAC1H,MAAMC,EAAAA,qBAAqB,EAAS,EAAM,IAAK,EAAY,EAAO,AACnE,EAOD,IAAA,EAAeC,EAAAA"}
@@ -1,14 +1,12 @@
1
- import { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType, setRabbitAuditContext } from "./const-ByTOLhRM.cjs";
1
+ import { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType, setRabbitAuditContext } from "./const-CsCfdvC8.cjs";
2
2
  import { onRequestAsyncHookHandler } from "fastify";
3
3
 
4
4
  //#region src/audit-api/fastify.d.ts
5
5
  /** Swagger tag for audit logs API. Add this to the `tags` array passed into the options of `fastify-plugin`. */
6
- /** Swagger tag for audit logs API. Add this to the `tags` array passed into the options of `fastify-plugin`. */
7
6
  declare const SWAGGER_TAG: {
8
7
  name: string;
9
8
  description: string;
10
9
  };
11
-
12
10
  //#endregion
13
11
  //#region src/fastify.d.ts
14
12
  declare const enableAuditing: (options: AuditLoggerOptions) => void;
@@ -19,7 +17,6 @@ declare const enableAuditing: (options: AuditLoggerOptions) => void;
19
17
  * @returns A Fastify `onRequest` hook.
20
18
  */
21
19
  declare const setAuditContext: (entityType: string, action: string) => onRequestAsyncHookHandler;
22
-
23
20
  //#endregion
24
21
  export { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLoggerOptions, EntityType, SWAGGER_TAG, AuditLogger as default, enableAuditing, setAuditContext, setRabbitAuditContext };
25
22
  //# sourceMappingURL=fastify.d.cts.map
package/dist/fastify.d.ts CHANGED
@@ -1,14 +1,12 @@
1
- import { AUDIT_LOG_CONTEXT_KEY$1 as AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE$1 as AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE$1 as AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER$1 as AUTOMATION_ID_HEADER, Action$1 as Action, ActionOrigin$1 as ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType$1 as EntityType, setRabbitAuditContext$1 as setRabbitAuditContext } from "./const-DTsi7GAD.js";
1
+ import { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType, setRabbitAuditContext } from "./const-CaukuTPn.js";
2
2
  import { onRequestAsyncHookHandler } from "fastify";
3
3
 
4
4
  //#region src/audit-api/fastify.d.ts
5
5
  /** Swagger tag for audit logs API. Add this to the `tags` array passed into the options of `fastify-plugin`. */
6
- /** Swagger tag for audit logs API. Add this to the `tags` array passed into the options of `fastify-plugin`. */
7
6
  declare const SWAGGER_TAG: {
8
7
  name: string;
9
8
  description: string;
10
9
  };
11
-
12
10
  //#endregion
13
11
  //#region src/fastify.d.ts
14
12
  declare const enableAuditing: (options: AuditLoggerOptions) => void;
@@ -19,7 +17,6 @@ declare const enableAuditing: (options: AuditLoggerOptions) => void;
19
17
  * @returns A Fastify `onRequest` hook.
20
18
  */
21
19
  declare const setAuditContext: (entityType: string, action: string) => onRequestAsyncHookHandler;
22
-
23
20
  //#endregion
24
21
  export { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLoggerOptions, EntityType, SWAGGER_TAG, AuditLogger as default, enableAuditing, setAuditContext, setRabbitAuditContext };
25
22
  //# sourceMappingURL=fastify.d.ts.map
package/dist/fastify.js CHANGED
@@ -1,11 +1,2 @@
1
- import{AUDIT_LOG_CONTEXT_KEY as e,AUDIT_LOG_CONTEXT_QUEUE as t,AUDIT_LOG_ROWS_QUEUE as n,AUTOMATION_ID_HEADER as r,Action as i,ActionOrigin as a,EntityType as o,audit_logger_default as s,audit_ms_default as c,innerEnableAuditing as l,innerSetAuditContext as u,setRabbitAuditContext as d}from"./common-oy2ugNvX.js";import{ResourceNotFoundError as f}from"@autofleet/errors";
2
- /** Swagger tag for audit logs API. Add this to the `tags` array passed into the options of `fastify-plugin`. */
3
- const p={name:`audit`,description:`Audit logs API`};async function m({fastify:e,logger:t,entityScopedModelMap:n}){!n||!e||Object.entries(n).forEach(([n,r])=>{e.get(`/api/v1/${n}/:id/audit`,{schema:{tags:[p.name],description:`Get audit logs for ${n} by ID`,params:{type:`object`,properties:{id:{type:`string`}},required:[`id`]}}},async e=>{let{id:i}=e.params,a=await r.findByPk(i);if(!a){let e=new f;throw t.error(`Entity ${n} with id ${i} not found`,{err:e}),e}return c.getByEntityId(i)})})}
4
- /**
5
- * A builder of `onRequest` hook for the request handler, which sets the audit context for the request lifecycle.
6
- * @param entityType The type of the entity being audited.
7
- * @param action The action being performed on the entity.
8
- * @returns A Fastify `onRequest` hook.
9
- */
10
- const h=e=>{let t=l(e);t&&m(e)},g=(e,t)=>async(n,r)=>{await u(n,r.raw,e,t)};var _=s;export{e as AUDIT_LOG_CONTEXT_KEY,t as AUDIT_LOG_CONTEXT_QUEUE,n as AUDIT_LOG_ROWS_QUEUE,r as AUTOMATION_ID_HEADER,i as Action,a as ActionOrigin,o as EntityType,p as SWAGGER_TAG,_ as default,h as enableAuditing,g as setAuditContext,d as setRabbitAuditContext};
1
+ import{AUDIT_LOG_CONTEXT_KEY as e,AUDIT_LOG_CONTEXT_QUEUE as t,AUDIT_LOG_ROWS_QUEUE as n,AUTOMATION_ID_HEADER as r,Action as i,ActionOrigin as a,EntityType as o,audit_logger_default as s,audit_ms_default as c,innerEnableAuditing as l,innerSetAuditContext as u,setRabbitAuditContext as d}from"./common-DcTpGBvn.js";import{ResourceNotFoundError as f}from"@autofleet/errors";const p={name:`audit`,description:`Audit logs API`};async function m({fastify:e,logger:t,entityScopedModelMap:n}){!n||!e||Object.entries(n).forEach(([n,r])=>{e.get(`/api/v1/${n}/:id/audit`,{schema:{tags:[p.name],description:`Get audit logs for ${n} by ID`,params:{type:`object`,properties:{id:{type:`string`}},required:[`id`]}}},async e=>{let{id:i}=e.params,a=await r.findByPk(i);if(!a){let e=new f;throw t.error(`Entity ${n} with id ${i} not found`,{err:e}),e}return c.getByEntityId(i)})})}const h=e=>{let t=l(e);t&&m(e)},g=(e,t)=>async(n,r)=>{await u(n,r.raw,e,t)};var _=s;export{e as AUDIT_LOG_CONTEXT_KEY,t as AUDIT_LOG_CONTEXT_QUEUE,n as AUDIT_LOG_ROWS_QUEUE,r as AUTOMATION_ID_HEADER,i as Action,a as ActionOrigin,o as EntityType,p as SWAGGER_TAG,_ as default,h as enableAuditing,g as setAuditContext,d as setRabbitAuditContext};
11
2
  //# sourceMappingURL=fastify.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"fastify.js","names":["options: AuditLoggerOptions","entityType: string","action: string"],"sources":["../src/audit-api/fastify.ts","../src/fastify.ts"],"sourcesContent":["import { ResourceNotFoundError } from '@autofleet/errors';\nimport auditMs from '../audit-ms';\nimport type { AuditLoggerOptions } from '../types';\n\n/** Swagger tag for audit logs API. Add this to the `tags` array passed into the options of `fastify-plugin`. */\nexport const SWAGGER_TAG = { name: 'audit', description: 'Audit logs API' };\n\nexport async function addAuditApi({ fastify, logger, entityScopedModelMap }: AuditLoggerOptions): Promise<void> {\n if (!entityScopedModelMap || !fastify) {\n return;\n }\n Object.entries(entityScopedModelMap).forEach(([entity, ScopedModel]) => {\n fastify.get(\n `/api/v1/${entity}/:id/audit`,\n {\n schema: {\n tags: [SWAGGER_TAG.name],\n description: `Get audit logs for ${entity} by ID`,\n params: {\n type: 'object',\n properties: {\n id: { type: 'string' },\n },\n required: ['id'],\n },\n },\n },\n async (req) => {\n const { id } = req.params as { id: string; };\n const entityData = await ScopedModel.findByPk(id);\n if (!entityData) {\n const err = new ResourceNotFoundError();\n logger.error(`Entity ${entity} with id ${id} not found`, { err });\n throw err;\n }\n return auditMs.getByEntityId(id);\n },\n );\n });\n}\n","import type { onRequestAsyncHookHandler } from 'fastify';\nimport AuditLogger from './audit-logger';\nimport { addAuditApi, SWAGGER_TAG } from './audit-api/fastify';\nimport type { AuditLoggerOptions } from './types';\nimport { innerEnableAuditing, innerSetAuditContext, setRabbitAuditContext } from './common';\n\nexport const enableAuditing = (options: AuditLoggerOptions): void => {\n const addApi = innerEnableAuditing(options);\n if (!addApi) {\n return;\n }\n addAuditApi(options);\n};\n\n/**\n * A builder of `onRequest` hook for the request handler, which sets the audit context for the request lifecycle.\n * @param entityType The type of the entity being audited.\n * @param action The action being performed on the entity.\n * @returns A Fastify `onRequest` hook.\n */\nexport const setAuditContext = (entityType: string, action: string): onRequestAsyncHookHandler => async (request, reply) => {\n await innerSetAuditContext(request, reply.raw, entityType, action);\n};\n\nexport { setRabbitAuditContext, SWAGGER_TAG };\n\nexport * from './types';\nexport * from './const';\n\nexport default AuditLogger;\n"],"mappings":";;AAKA,MAAa,EAAc,CAAE,KAAM,QAAS,YAAa,gBAAkB,EAE3E,eAAsB,EAAY,CAAE,UAAS,SAAQ,uBAA0C,CAAiB,CAC9G,CAAK,IAAyB,GAG9B,OAAO,QAAQ,EAAqB,CAAC,QAAQ,CAAC,CAAC,EAAQ,EAAY,GAAK,CACtE,EAAQ,KACL,UAAU,EAAO,YAClB,CACE,OAAQ,CACN,KAAM,CAAC,EAAY,IAAK,EACxB,aAAc,qBAAqB,EAAO,QAC1C,OAAQ,CACN,KAAM,SACN,WAAY,CACV,GAAI,CAAE,KAAM,QAAU,CACvB,EACD,SAAU,CAAC,IAAK,CACjB,CACF,CACF,EACD,MAAO,GAAQ,CAEb,GADM,CAAE,KAAI,CAAG,EAAI,OACb,EAAa,KAAM,GAAY,SAAS,EAAG,CACjD,IAAK,EAAY,CACf,IAAM,EAAM,IAAI,EAEhB,KADA,GAAO,OAAO,SAAS,EAAO,WAAW,EAAG,YAAa,CAAE,KAAK,EAAC,CAC3D,CACP,CACD,MAAO,GAAQ,cAAc,EAAG,AACjC,EACF,AACF,EAAC,AACH;;;;;;;ACnBD,MAda,EAAiB,AAACA,GAAsC,CACnE,IAAM,EAAS,EAAoB,EAAQ,CACtC,GAGL,EAAY,EAAQ,AACrB,EAQY,EAAkB,CAACC,EAAoBC,IAA8C,MAAO,EAAS,IAAU,CAC1H,KAAM,GAAqB,EAAS,EAAM,IAAK,EAAY,EAAO,AACnE,EAOD,IAAA,EAAe"}
1
+ {"version":3,"file":"fastify.js","names":["auditMs","options: AuditLoggerOptions","entityType: string","action: string","AuditLogger"],"sources":["../src/audit-api/fastify.ts","../src/fastify.ts"],"sourcesContent":["import { ResourceNotFoundError } from '@autofleet/errors';\nimport auditMs from '../audit-ms';\nimport type { AuditLoggerOptions } from '../types';\n\n/** Swagger tag for audit logs API. Add this to the `tags` array passed into the options of `fastify-plugin`. */\nexport const SWAGGER_TAG = { name: 'audit', description: 'Audit logs API' };\n\nexport async function addAuditApi({ fastify, logger, entityScopedModelMap }: AuditLoggerOptions): Promise<void> {\n if (!entityScopedModelMap || !fastify) {\n return;\n }\n Object.entries(entityScopedModelMap).forEach(([entity, ScopedModel]) => {\n fastify.get(\n `/api/v1/${entity}/:id/audit`,\n {\n schema: {\n tags: [SWAGGER_TAG.name],\n description: `Get audit logs for ${entity} by ID`,\n params: {\n type: 'object',\n properties: {\n id: { type: 'string' },\n },\n required: ['id'],\n },\n },\n },\n async (req) => {\n const { id } = req.params as { id: string; };\n const entityData = await ScopedModel.findByPk(id);\n if (!entityData) {\n const err = new ResourceNotFoundError();\n logger.error(`Entity ${entity} with id ${id} not found`, { err });\n throw err;\n }\n return auditMs.getByEntityId(id);\n },\n );\n });\n}\n","import type { onRequestAsyncHookHandler } from 'fastify';\nimport AuditLogger from './audit-logger';\nimport { addAuditApi, SWAGGER_TAG } from './audit-api/fastify';\nimport type { AuditLoggerOptions } from './types';\nimport { innerEnableAuditing, innerSetAuditContext, setRabbitAuditContext } from './common';\n\nexport const enableAuditing = (options: AuditLoggerOptions): void => {\n const addApi = innerEnableAuditing(options);\n if (!addApi) {\n return;\n }\n addAuditApi(options);\n};\n\n/**\n * A builder of `onRequest` hook for the request handler, which sets the audit context for the request lifecycle.\n * @param entityType The type of the entity being audited.\n * @param action The action being performed on the entity.\n * @returns A Fastify `onRequest` hook.\n */\nexport const setAuditContext = (entityType: string, action: string): onRequestAsyncHookHandler => async (request, reply) => {\n await innerSetAuditContext(request, reply.raw, entityType, action);\n};\n\nexport { setRabbitAuditContext, SWAGGER_TAG };\n\nexport * from './types';\nexport * from './const';\n\nexport default AuditLogger;\n"],"mappings":"oXAKA,MAAa,EAAc,CAAE,KAAM,QAAS,YAAa,gBAAkB,EAE3E,eAAsB,EAAY,CAAE,UAAS,SAAQ,uBAA0C,CAAiB,CAC1G,CAAC,GAAwB,CAAC,GAG9B,OAAO,QAAQ,EAAqB,CAAC,QAAQ,CAAC,CAAC,EAAQ,EAAY,GAAK,CACtE,EAAQ,IACN,CAAC,QAAQ,EAAE,EAAO,UAAU,CAAC,CAC7B,CACE,OAAQ,CACN,KAAM,CAAC,EAAY,IAAK,EACxB,YAAa,CAAC,mBAAmB,EAAE,EAAO,MAAM,CAAC,CACjD,OAAQ,CACN,KAAM,SACN,WAAY,CACV,GAAI,CAAE,KAAM,QAAU,CACvB,EACD,SAAU,CAAC,IAAK,CACjB,CACF,CACF,EACD,MAAO,GAAQ,CACb,GAAM,CAAE,KAAI,CAAG,EAAI,OACb,EAAa,MAAM,EAAY,SAAS,EAAG,CACjD,GAAI,CAAC,EAAY,CACf,IAAM,EAAM,IAAI,EAEhB,MADA,EAAO,MAAM,CAAC,OAAO,EAAE,EAAO,SAAS,EAAE,EAAG,UAAU,CAAC,CAAE,CAAE,KAAK,EAAC,CAC3D,CACP,CACD,OAAOA,EAAQ,cAAc,EAAG,AACjC,EACF,AACF,EAAC,AACH,CCjCD,MAAa,EAAiB,AAACC,GAAsC,CACnE,IAAM,EAAS,EAAoB,EAAQ,CACtC,GAGL,EAAY,EAAQ,AACrB,EAQY,EAAkB,CAACC,EAAoBC,IAA8C,MAAO,EAAS,IAAU,CAC1H,MAAM,EAAqB,EAAS,EAAM,IAAK,EAAY,EAAO,AACnE,EAOD,IAAA,EAAeC"}
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,`__esModule`,{value:!0});const e=require(`./common-DLsvf3zA.cjs`),t=e.__toESM(require(`@autofleet/errors`));async function n({router:n,logger:r,entityScopedModelMap:i}){!i||!n||Object.entries(i).forEach(([i,a])=>{n.get(`${i}/:id/audit`,async(n,o)=>{try{let{id:s}=n.params,c=await a.findByPk(s);if(!c)return(0,t.handleError)(new t.ResourceNotFoundError,o,{logger:r,message:`Entity ${i} with id ${s} not found`});let l=e.audit_ms_default.getByEntityId(s);return o.json(l)}catch(e){return(0,t.handleError)(new t.UnexpectedError(e),o,{logger:r})}})})}const r=t=>{let r=e.innerEnableAuditing(t);r&&n(t)},i=(t,n)=>async(r,i,a)=>(e.innerSetAuditContext(r,i,t,n),a());var a=e.audit_logger_default;exports.AUDIT_LOG_CONTEXT_KEY=e.AUDIT_LOG_CONTEXT_KEY,exports.AUDIT_LOG_CONTEXT_QUEUE=e.AUDIT_LOG_CONTEXT_QUEUE,exports.AUDIT_LOG_ROWS_QUEUE=e.AUDIT_LOG_ROWS_QUEUE,exports.AUTOMATION_ID_HEADER=e.AUTOMATION_ID_HEADER,exports.Action=e.Action,exports.ActionOrigin=e.ActionOrigin,exports.EntityType=e.EntityType,exports.default=a,exports.enableAuditing=r,exports.setAuditContext=i,exports.setRabbitAuditContext=e.setRabbitAuditContext;
1
+ Object.defineProperty(exports,`__esModule`,{value:!0});const e=require(`./common-kvWo0enA.cjs`),t=e.__toESM(require(`@autofleet/errors`));async function n({router:n,logger:r,entityScopedModelMap:i}){!i||!n||Object.entries(i).forEach(([i,a])=>{n.get(`${i}/:id/audit`,async(n,o)=>{try{let{id:s}=n.params,c=await a.findByPk(s);if(!c)return(0,t.handleError)(new t.ResourceNotFoundError,o,{logger:r,message:`Entity ${i} with id ${s} not found`});let l=e.audit_ms_default.getByEntityId(s);return o.json(l)}catch(e){return(0,t.handleError)(new t.UnexpectedError(e),o,{logger:r})}})})}const r=t=>{let r=e.innerEnableAuditing(t);r&&n(t)},i=(t,n)=>async(r,i,a)=>(e.innerSetAuditContext(r,i,t,n),a());var a=e.audit_logger_default;exports.AUDIT_LOG_CONTEXT_KEY=e.AUDIT_LOG_CONTEXT_KEY,exports.AUDIT_LOG_CONTEXT_QUEUE=e.AUDIT_LOG_CONTEXT_QUEUE,exports.AUDIT_LOG_ROWS_QUEUE=e.AUDIT_LOG_ROWS_QUEUE,exports.AUTOMATION_ID_HEADER=e.AUTOMATION_ID_HEADER,exports.Action=e.Action,exports.ActionOrigin=e.ActionOrigin,exports.EntityType=e.EntityType,exports.default=a,exports.enableAuditing=r,exports.setAuditContext=i,exports.setRabbitAuditContext=e.setRabbitAuditContext;
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["options: AuditLoggerOptions","entityType: string","action: string","req: Request","res: Response","next: NextFunction"],"sources":["../src/audit-api/express.ts","../src/index.ts"],"sourcesContent":["import { handleError, ResourceNotFoundError, UnexpectedError } from '@autofleet/errors';\nimport auditMs from '../audit-ms';\nimport type { AuditLoggerOptions } from '../types';\n\nexport async function addAuditApi({ router, logger, entityScopedModelMap }: AuditLoggerOptions): Promise<void> {\n if (!entityScopedModelMap || !router) {\n return;\n }\n Object.entries(entityScopedModelMap).forEach(([entity, ScopedModel]) => {\n router.get(`${entity}/:id/audit`, async (req, res) => {\n try {\n const { id } = req.params;\n const entityData = await ScopedModel.findByPk(id);\n if (!entityData) {\n return handleError(new ResourceNotFoundError(), res, { logger, message: `Entity ${entity} with id ${id} not found` });\n }\n const auditData = auditMs.getByEntityId(id);\n return res.json(auditData);\n } catch (err) {\n return handleError(new UnexpectedError(err as Error), res, { logger });\n }\n });\n });\n}\n","import type { Request, Response, NextFunction } from 'express';\nimport AuditLogger from './audit-logger';\nimport { addAuditApi } from './audit-api/express';\nimport type { AuditLoggerOptions } from './types';\nimport { innerEnableAuditing, innerSetAuditContext, setRabbitAuditContext } from './common';\n\nexport const enableAuditing = (options: AuditLoggerOptions): void => {\n const addApi = innerEnableAuditing(options);\n if (!addApi) {\n return;\n }\n addAuditApi(options);\n};\n\nexport const setAuditContext = (entityType: string, action: string) => async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n innerSetAuditContext(req, res, entityType, action);\n return next();\n};\n\nexport { setRabbitAuditContext };\n\nexport * from './types';\nexport * from './const';\n\nexport default AuditLogger;\n"],"mappings":"uJAIA,eAAsB,EAAY,CAAE,SAAQ,SAAQ,uBAA0C,CAAiB,CAC7G,CAAK,IAAyB,GAG9B,OAAO,QAAQ,EAAqB,CAAC,QAAQ,CAAC,CAAC,EAAQ,EAAY,GAAK,CACtE,EAAO,KAAK,EAAE,EAAO,YAAa,MAAO,EAAK,IAAQ,CACpD,GAAI,CAEF,GADM,CAAE,KAAI,CAAG,EAAI,OACb,EAAa,KAAM,GAAY,SAAS,EAAG,CACjD,IAAK,EACH,MAAO,CAAA,EAAA,EAAA,aAAY,IAAI,EAAA,sBAAyB,EAAK,CAAE,SAAQ,SAAU,SAAS,EAAO,WAAW,EAAG,WAAa,EAAC,CAEvH,IAAM,EAAY,EAAA,iBAAQ,cAAc,EAAG,CAC3C,MAAO,GAAI,KAAK,EAAU,AAC3B,OAAQ,EAAK,CACZ,MAAO,CAAA,EAAA,EAAA,aAAY,IAAI,EAAA,gBAAgB,GAAe,EAAK,CAAE,QAAQ,EAAC,AACvE,CACF,EAAC,AACH,EAAC,AACH,CCTD,MARa,EAAiB,AAACA,GAAsC,CACnE,IAAM,EAAS,EAAA,oBAAoB,EAAQ,CACtC,GAGL,EAAY,EAAQ,AACrB,EAEY,EAAkB,CAACC,EAAoBC,IAAmB,MAAOC,EAAcC,EAAeC,KACzG,EAAA,qBAAqB,EAAK,EAAK,EAAY,EAAO,CAC3C,GAAM,EAQf,IAAA,EAAe,EAAA"}
1
+ {"version":3,"file":"index.cjs","names":["ResourceNotFoundError","auditMs","UnexpectedError","options: AuditLoggerOptions","innerEnableAuditing","entityType: string","action: string","req: Request","res: Response","next: NextFunction","innerSetAuditContext","AuditLogger"],"sources":["../src/audit-api/express.ts","../src/index.ts"],"sourcesContent":["import { handleError, ResourceNotFoundError, UnexpectedError } from '@autofleet/errors';\nimport auditMs from '../audit-ms';\nimport type { AuditLoggerOptions } from '../types';\n\nexport async function addAuditApi({ router, logger, entityScopedModelMap }: AuditLoggerOptions): Promise<void> {\n if (!entityScopedModelMap || !router) {\n return;\n }\n Object.entries(entityScopedModelMap).forEach(([entity, ScopedModel]) => {\n router.get(`${entity}/:id/audit`, async (req, res) => {\n try {\n const { id } = req.params;\n const entityData = await ScopedModel.findByPk(id);\n if (!entityData) {\n return handleError(new ResourceNotFoundError(), res, { logger, message: `Entity ${entity} with id ${id} not found` });\n }\n const auditData = auditMs.getByEntityId(id);\n return res.json(auditData);\n } catch (err) {\n return handleError(new UnexpectedError(err as Error), res, { logger });\n }\n });\n });\n}\n","import type { Request, Response, NextFunction } from 'express';\nimport AuditLogger from './audit-logger';\nimport { addAuditApi } from './audit-api/express';\nimport type { AuditLoggerOptions } from './types';\nimport { innerEnableAuditing, innerSetAuditContext, setRabbitAuditContext } from './common';\n\nexport const enableAuditing = (options: AuditLoggerOptions): void => {\n const addApi = innerEnableAuditing(options);\n if (!addApi) {\n return;\n }\n addAuditApi(options);\n};\n\nexport const setAuditContext = (entityType: string, action: string) => async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n innerSetAuditContext(req, res, entityType, action);\n return next();\n};\n\nexport { setRabbitAuditContext };\n\nexport * from './types';\nexport * from './const';\n\nexport default AuditLogger;\n"],"mappings":"0IAIA,eAAsB,EAAY,CAAE,SAAQ,SAAQ,uBAA0C,CAAiB,CACzG,CAAC,GAAwB,CAAC,GAG9B,OAAO,QAAQ,EAAqB,CAAC,QAAQ,CAAC,CAAC,EAAQ,EAAY,GAAK,CACtE,EAAO,IAAI,GAAG,EAAO,UAAU,CAAC,CAAE,MAAO,EAAK,IAAQ,CACpD,GAAI,CACF,GAAM,CAAE,KAAI,CAAG,EAAI,OACb,EAAa,MAAM,EAAY,SAAS,EAAG,CACjD,GAAI,CAAC,EACH,OAAA,EAAA,EAAA,aAAmB,IAAIA,EAAAA,sBAAyB,EAAK,CAAE,SAAQ,QAAS,CAAC,OAAO,EAAE,EAAO,SAAS,EAAE,EAAG,UAAU,CAAC,AAAE,EAAC,CAEvH,IAAM,EAAYC,EAAAA,iBAAQ,cAAc,EAAG,CAC3C,OAAO,EAAI,KAAK,EAAU,AAC3B,OAAQ,EAAK,CACZ,OAAA,EAAA,EAAA,aAAmB,IAAIC,EAAAA,gBAAgB,GAAe,EAAK,CAAE,QAAQ,EAAC,AACvE,CACF,EAAC,AACH,EAAC,AACH,CCjBD,MAAa,EAAiB,AAACC,GAAsC,CACnE,IAAM,EAASC,EAAAA,oBAAoB,EAAQ,CACtC,GAGL,EAAY,EAAQ,AACrB,EAEY,EAAkB,CAACC,EAAoBC,IAAmB,MAAOC,EAAcC,EAAeC,KACzGC,EAAAA,qBAAqB,EAAK,EAAK,EAAY,EAAO,CAC3C,GAAM,EAQf,IAAA,EAAeC,EAAAA"}
package/dist/index.d.cts CHANGED
@@ -1,10 +1,9 @@
1
- import { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType, setRabbitAuditContext } from "./const-ByTOLhRM.cjs";
1
+ import { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType, setRabbitAuditContext } from "./const-CsCfdvC8.cjs";
2
2
  import { NextFunction, Request, Response } from "express";
3
3
 
4
4
  //#region src/index.d.ts
5
5
  declare const enableAuditing: (options: AuditLoggerOptions) => void;
6
6
  declare const setAuditContext: (entityType: string, action: string) => (req: Request, res: Response, next: NextFunction) => Promise<void>;
7
-
8
7
  //#endregion
9
8
  export { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLoggerOptions, EntityType, AuditLogger as default, enableAuditing, setAuditContext, setRabbitAuditContext };
10
9
  //# sourceMappingURL=index.d.cts.map
package/dist/index.d.ts CHANGED
@@ -1,10 +1,9 @@
1
- import { AUDIT_LOG_CONTEXT_KEY$1 as AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE$1 as AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE$1 as AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER$1 as AUTOMATION_ID_HEADER, Action$1 as Action, ActionOrigin$1 as ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType$1 as EntityType, setRabbitAuditContext$1 as setRabbitAuditContext } from "./const-DTsi7GAD.js";
1
+ import { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType, setRabbitAuditContext } from "./const-CaukuTPn.js";
2
2
  import { NextFunction, Request, Response } from "express";
3
3
 
4
4
  //#region src/index.d.ts
5
5
  declare const enableAuditing: (options: AuditLoggerOptions) => void;
6
6
  declare const setAuditContext: (entityType: string, action: string) => (req: Request, res: Response, next: NextFunction) => Promise<void>;
7
-
8
7
  //#endregion
9
8
  export { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLoggerOptions, EntityType, AuditLogger as default, enableAuditing, setAuditContext, setRabbitAuditContext };
10
9
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{AUDIT_LOG_CONTEXT_KEY as e,AUDIT_LOG_CONTEXT_QUEUE as t,AUDIT_LOG_ROWS_QUEUE as n,AUTOMATION_ID_HEADER as r,Action as i,ActionOrigin as a,EntityType as o,audit_logger_default as s,audit_ms_default as c,innerEnableAuditing as l,innerSetAuditContext as u,setRabbitAuditContext as d}from"./common-oy2ugNvX.js";import{ResourceNotFoundError as f,UnexpectedError as p,handleError as m}from"@autofleet/errors";async function h({router:e,logger:t,entityScopedModelMap:n}){!n||!e||Object.entries(n).forEach(([n,r])=>{e.get(`${n}/:id/audit`,async(e,i)=>{try{let{id:a}=e.params,o=await r.findByPk(a);if(!o)return m(new f,i,{logger:t,message:`Entity ${n} with id ${a} not found`});let s=c.getByEntityId(a);return i.json(s)}catch(e){return m(new p(e),i,{logger:t})}})})}const g=e=>{let t=l(e);t&&h(e)},_=(e,t)=>async(n,r,i)=>(u(n,r,e,t),i());var v=s;export{e as AUDIT_LOG_CONTEXT_KEY,t as AUDIT_LOG_CONTEXT_QUEUE,n as AUDIT_LOG_ROWS_QUEUE,r as AUTOMATION_ID_HEADER,i as Action,a as ActionOrigin,o as EntityType,v as default,g as enableAuditing,_ as setAuditContext,d as setRabbitAuditContext};
1
+ import{AUDIT_LOG_CONTEXT_KEY as e,AUDIT_LOG_CONTEXT_QUEUE as t,AUDIT_LOG_ROWS_QUEUE as n,AUTOMATION_ID_HEADER as r,Action as i,ActionOrigin as a,EntityType as o,audit_logger_default as s,audit_ms_default as c,innerEnableAuditing as l,innerSetAuditContext as u,setRabbitAuditContext as d}from"./common-DcTpGBvn.js";import{ResourceNotFoundError as f,UnexpectedError as p,handleError as m}from"@autofleet/errors";async function h({router:e,logger:t,entityScopedModelMap:n}){!n||!e||Object.entries(n).forEach(([n,r])=>{e.get(`${n}/:id/audit`,async(e,i)=>{try{let{id:a}=e.params,o=await r.findByPk(a);if(!o)return m(new f,i,{logger:t,message:`Entity ${n} with id ${a} not found`});let s=c.getByEntityId(a);return i.json(s)}catch(e){return m(new p(e),i,{logger:t})}})})}const g=e=>{let t=l(e);t&&h(e)},_=(e,t)=>async(n,r,i)=>(u(n,r,e,t),i());var v=s;export{e as AUDIT_LOG_CONTEXT_KEY,t as AUDIT_LOG_CONTEXT_QUEUE,n as AUDIT_LOG_ROWS_QUEUE,r as AUTOMATION_ID_HEADER,i as Action,a as ActionOrigin,o as EntityType,v as default,g as enableAuditing,_ as setAuditContext,d as setRabbitAuditContext};
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["options: AuditLoggerOptions","entityType: string","action: string","req: Request","res: Response","next: NextFunction"],"sources":["../src/audit-api/express.ts","../src/index.ts"],"sourcesContent":["import { handleError, ResourceNotFoundError, UnexpectedError } from '@autofleet/errors';\nimport auditMs from '../audit-ms';\nimport type { AuditLoggerOptions } from '../types';\n\nexport async function addAuditApi({ router, logger, entityScopedModelMap }: AuditLoggerOptions): Promise<void> {\n if (!entityScopedModelMap || !router) {\n return;\n }\n Object.entries(entityScopedModelMap).forEach(([entity, ScopedModel]) => {\n router.get(`${entity}/:id/audit`, async (req, res) => {\n try {\n const { id } = req.params;\n const entityData = await ScopedModel.findByPk(id);\n if (!entityData) {\n return handleError(new ResourceNotFoundError(), res, { logger, message: `Entity ${entity} with id ${id} not found` });\n }\n const auditData = auditMs.getByEntityId(id);\n return res.json(auditData);\n } catch (err) {\n return handleError(new UnexpectedError(err as Error), res, { logger });\n }\n });\n });\n}\n","import type { Request, Response, NextFunction } from 'express';\nimport AuditLogger from './audit-logger';\nimport { addAuditApi } from './audit-api/express';\nimport type { AuditLoggerOptions } from './types';\nimport { innerEnableAuditing, innerSetAuditContext, setRabbitAuditContext } from './common';\n\nexport const enableAuditing = (options: AuditLoggerOptions): void => {\n const addApi = innerEnableAuditing(options);\n if (!addApi) {\n return;\n }\n addAuditApi(options);\n};\n\nexport const setAuditContext = (entityType: string, action: string) => async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n innerSetAuditContext(req, res, entityType, action);\n return next();\n};\n\nexport { setRabbitAuditContext };\n\nexport * from './types';\nexport * from './const';\n\nexport default AuditLogger;\n"],"mappings":"0ZAIA,eAAsB,EAAY,CAAE,SAAQ,SAAQ,uBAA0C,CAAiB,CAC7G,CAAK,IAAyB,GAG9B,OAAO,QAAQ,EAAqB,CAAC,QAAQ,CAAC,CAAC,EAAQ,EAAY,GAAK,CACtE,EAAO,KAAK,EAAE,EAAO,YAAa,MAAO,EAAK,IAAQ,CACpD,GAAI,CAEF,GADM,CAAE,KAAI,CAAG,EAAI,OACb,EAAa,KAAM,GAAY,SAAS,EAAG,CACjD,IAAK,EACH,MAAO,GAAY,IAAI,EAAyB,EAAK,CAAE,SAAQ,SAAU,SAAS,EAAO,WAAW,EAAG,WAAa,EAAC,CAEvH,IAAM,EAAY,EAAQ,cAAc,EAAG,CAC3C,MAAO,GAAI,KAAK,EAAU,AAC3B,OAAQ,EAAK,CACZ,MAAO,GAAY,IAAI,EAAgB,GAAe,EAAK,CAAE,QAAQ,EAAC,AACvE,CACF,EAAC,AACH,EAAC,AACH,CCTD,MARa,EAAiB,AAACA,GAAsC,CACnE,IAAM,EAAS,EAAoB,EAAQ,CACtC,GAGL,EAAY,EAAQ,AACrB,EAEY,EAAkB,CAACC,EAAoBC,IAAmB,MAAOC,EAAcC,EAAeC,KACzG,EAAqB,EAAK,EAAK,EAAY,EAAO,CAC3C,GAAM,EAQf,IAAA,EAAe"}
1
+ {"version":3,"file":"index.js","names":["auditMs","options: AuditLoggerOptions","entityType: string","action: string","req: Request","res: Response","next: NextFunction","AuditLogger"],"sources":["../src/audit-api/express.ts","../src/index.ts"],"sourcesContent":["import { handleError, ResourceNotFoundError, UnexpectedError } from '@autofleet/errors';\nimport auditMs from '../audit-ms';\nimport type { AuditLoggerOptions } from '../types';\n\nexport async function addAuditApi({ router, logger, entityScopedModelMap }: AuditLoggerOptions): Promise<void> {\n if (!entityScopedModelMap || !router) {\n return;\n }\n Object.entries(entityScopedModelMap).forEach(([entity, ScopedModel]) => {\n router.get(`${entity}/:id/audit`, async (req, res) => {\n try {\n const { id } = req.params;\n const entityData = await ScopedModel.findByPk(id);\n if (!entityData) {\n return handleError(new ResourceNotFoundError(), res, { logger, message: `Entity ${entity} with id ${id} not found` });\n }\n const auditData = auditMs.getByEntityId(id);\n return res.json(auditData);\n } catch (err) {\n return handleError(new UnexpectedError(err as Error), res, { logger });\n }\n });\n });\n}\n","import type { Request, Response, NextFunction } from 'express';\nimport AuditLogger from './audit-logger';\nimport { addAuditApi } from './audit-api/express';\nimport type { AuditLoggerOptions } from './types';\nimport { innerEnableAuditing, innerSetAuditContext, setRabbitAuditContext } from './common';\n\nexport const enableAuditing = (options: AuditLoggerOptions): void => {\n const addApi = innerEnableAuditing(options);\n if (!addApi) {\n return;\n }\n addAuditApi(options);\n};\n\nexport const setAuditContext = (entityType: string, action: string) => async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n innerSetAuditContext(req, res, entityType, action);\n return next();\n};\n\nexport { setRabbitAuditContext };\n\nexport * from './types';\nexport * from './const';\n\nexport default AuditLogger;\n"],"mappings":"0ZAIA,eAAsB,EAAY,CAAE,SAAQ,SAAQ,uBAA0C,CAAiB,CACzG,CAAC,GAAwB,CAAC,GAG9B,OAAO,QAAQ,EAAqB,CAAC,QAAQ,CAAC,CAAC,EAAQ,EAAY,GAAK,CACtE,EAAO,IAAI,GAAG,EAAO,UAAU,CAAC,CAAE,MAAO,EAAK,IAAQ,CACpD,GAAI,CACF,GAAM,CAAE,KAAI,CAAG,EAAI,OACb,EAAa,MAAM,EAAY,SAAS,EAAG,CACjD,GAAI,CAAC,EACH,OAAO,EAAY,IAAI,EAAyB,EAAK,CAAE,SAAQ,QAAS,CAAC,OAAO,EAAE,EAAO,SAAS,EAAE,EAAG,UAAU,CAAC,AAAE,EAAC,CAEvH,IAAM,EAAYA,EAAQ,cAAc,EAAG,CAC3C,OAAO,EAAI,KAAK,EAAU,AAC3B,OAAQ,EAAK,CACZ,OAAO,EAAY,IAAI,EAAgB,GAAe,EAAK,CAAE,QAAQ,EAAC,AACvE,CACF,EAAC,AACH,EAAC,AACH,CCjBD,MAAa,EAAiB,AAACC,GAAsC,CACnE,IAAM,EAAS,EAAoB,EAAQ,CACtC,GAGL,EAAY,EAAQ,AACrB,EAEY,EAAkB,CAACC,EAAoBC,IAAmB,MAAOC,EAAcC,EAAeC,KACzG,EAAqB,EAAK,EAAK,EAAY,EAAO,CAC3C,GAAM,EAQf,IAAA,EAAeC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@autofleet/shtinker",
3
- "version": "3.4.0",
3
+ "version": "3.4.1",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -53,7 +53,7 @@
53
53
  "sequelize": "^6.37.6",
54
54
  "sequelize-typescript": "^2.1.6",
55
55
  "ts-node": "^10.9.1",
56
- "tsdown": "^0.11.3",
56
+ "tsdown": "^0.13.3",
57
57
  "typescript": "^5.8.3",
58
58
  "vitest": "^3.1.3"
59
59
  },
@@ -1,2 +0,0 @@
1
- "use strict";var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));const c=s(require(`node:util`)),l=s(require(`@autofleet/zehut`)),u=s(require(`@autofleet/outbreak`)),d=s(require(`@autofleet/logger`)),f=s(require(`@autofleet/network`));let p=/* @__PURE__ */ function(e){return e.CREATE=`create`,e.BULK_CREATE=`bulk-create`,e.BULK_EDIT=`bulk-edit`,e.DELETE=`delete`,e.UPDATE=`update`,e.CANCEL=`cancel`,e.FAIL=`fail`,e.UNASSIGN=`unassign`,e.BULK_ASSIGN=`bulk-assign`,e.REASSIGN=`reassign`,e.DISPATCH=`dispatch`,e.BULK_DISPATCH=`bulk-dispatch`,e.BULK_UPSERT=`bulk-upsert`,e.UPSERT=`upsert`,e.JOIN=`join`,e.MOVE=`move`,e.REOPTIMIZATION=`reoptimization`,e}({}),m=/* @__PURE__ */ function(e){return e.RIDE=`Ride`,e.VEHICLE=`Vehicle`,e.DRIVER=`Driver`,e.PRICE_CALCULATION=`PriceCalculation`,e}({}),h=/* @__PURE__ */ function(e){return e.USER=`user`,e.AUTOMATION=`automation`,e}({});const g=`audit-log-context`,_=`audit-log-rows`,v=`auditLogContext`,y=`x-af-automation-id`,b=(0,d.default)();b.addContextMiddleware(()=>({traceId:(0,u.getCurrentContextTraceId)()}));var x=b;const S=`customFields`,C=()=>{let e=(0,l.getCurrentPayload)(),t=e?.nonHeaderContext?.get(v);return t},w={[p.BULK_CREATE]:p.BULK_CREATE,[p.BULK_EDIT]:p.BULK_EDIT,[p.BULK_ASSIGN]:p.BULK_ASSIGN,[p.BULK_DISPATCH]:p.BULK_DISPATCH,[p.BULK_UPSERT]:p.BULK_UPSERT},T=e=>[null,void 0].includes(e)?!0:Array.isArray(e)?e.length===0:typeof e==`object`&&!(e instanceof Date)?Object.keys(e).length===0:!1,E=e=>Object.hasOwn(w,e),D=(e,t)=>e.filter(e=>!T(t.get(e))||!T(t.previous(e))),O=(e,t)=>{let n=t.returning?t.fields:e.changed(),r=D(n.filter(e=>e!==S),e);return r.map(t=>({property:t,previousValue:e.previous(t),newValue:e.get(t)}))},k=e=>{let t=e.changed(),n=t&&t.includes(S);if(!n)return[];let r=e.get(S),i=e.previous(S),a=Object.keys(r).filter(e=>{let t=r?.[e],n=i?.[e];return(!T(t)||!T(n))&&!(0,c.isDeepStrictEqual)(t,n)});return a.map(e=>({property:`${S}.${e}`,previousValue:i?.[e],newValue:r?.[e]}))};var A=class{constructor(e){this.rabbit=e.rabbit,this.sequelize=e.sequelize,this.logger=e.logger||x,this.excludeModels=e.excludeModels??[]}async manualSendAuditLog({auditContext:e,...t}){if(e??=C(),e)try{e?.entityType?.toLowerCase()===t.entityType?.toLowerCase()&&E(e.action)&&(e.entityId=t.entityId),await this.sendAuditLogRows(t)}catch(e){let{entityType:n,entityId:r}=t;this.logger.error(`Failed to send audit log rows`,{entityType:n,entityId:r,error:e})}}registerHooks(){Object.entries(this.sequelize.models).forEach(([e,t])=>{this.excludeModels.includes(e)||t.addHook(`afterSave`,async(t,n)=>{let r=C();if(!r)return;let{id:i}=t;await this.manualSendAuditLog({entityId:i,auditContext:r,entityType:e,rows:[...O(t,n),...k(t)]})})})}async sendAuditLogContext(e){try{await this.rabbit.sendToQueue(g,e)}catch(e){this.logger.error(`Failed to send audit log context`,e)}}async sendAuditLogRows(e){try{await this.rabbit.sendToQueue(_,e)}catch(e){this.logger.error(`Failed to send audit log rows`,e)}}},j=A;const M=new f.default({serviceName:`AUDIT_MS`,timeout:6e4,logger:x}),N=async e=>{let{data:t}=await M.get(`api/v1/audit-logs/${e}`);return t},P={getByEntityId:N};var F=P;let I;const L=e=>process.env.DISABLE_AUDIT_LOGS===`true`?!1:(I=new j(e),I.registerHooks(),!0),R=({action:e,endpoint:t,entityType:n,method:r,automationId:i,userId:a})=>{let o=a||(i??null),s=a&&h.USER||i&&h.AUTOMATION||null,c={entityType:n,action:e,endpoint:t,method:r,performedBy:o,actionOrigin:s},u=(0,l.getCurrentPayload)();return u.nonHeaderContext.set(v,c),c},z=async(e,t,n,r)=>{try{if(process.env.DISABLE_AUDIT_LOGS===`true`||!I)return;let i=R({action:r,endpoint:e.url,entityType:n,method:e.method,userId:(0,l.getUser)()?.id,automationId:e.headers[y]});if(!E(r)){await I.sendAuditLogContext(i);return}let a=async()=>{t.off(`finish`,a),t.off(`close`,a),t.off(`error`,a),await I?.sendAuditLogContext(i)};t.once(`finish`,a),t.once(`close`,a),t.once(`error`,a)}catch(e){x.error(`couldn't set audit context`,e)}},B=(e,t)=>async(n,{userId:r,automationId:i})=>{if(process.env.DISABLE_AUDIT_LOGS===`true`||!I)return;let a=R({action:t,endpoint:n,entityType:e,method:`rabbit`,userId:r,automationId:i});await I.sendAuditLogContext(a)};Object.defineProperty(exports,`AUDIT_LOG_CONTEXT_KEY`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,`AUDIT_LOG_CONTEXT_QUEUE`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,`AUDIT_LOG_ROWS_QUEUE`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,`AUTOMATION_ID_HEADER`,{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,`Action`,{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,`ActionOrigin`,{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,`EntityType`,{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,`__toESM`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`audit_logger_default`,{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,`audit_ms_default`,{enumerable:!0,get:function(){return F}}),Object.defineProperty(exports,`innerEnableAuditing`,{enumerable:!0,get:function(){return L}}),Object.defineProperty(exports,`innerSetAuditContext`,{enumerable:!0,get:function(){return z}}),Object.defineProperty(exports,`setRabbitAuditContext`,{enumerable:!0,get:function(){return B}});
2
- //# sourceMappingURL=common-DLsvf3zA.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"common-DLsvf3zA.cjs","names":["logger: LoggerInstanceManager","field: unknown","action: string","fields: string[]","instance: Model","options: CreateOptions | InstanceUpdateOptions","changedFields: string[]","property: string","options: AuditLoggerOptions","context: AuditLogContext","payload: AuditLogPayload","entityId: string","exportObj: { getByEntityId: typeof getByEntityId }","auditLogger: AuditLogger | undefined","options: AuditLoggerOptions","auditLogContext: AuditLogContext","req: PartialRequest","res: Writable","entityType: string","action: string","endpoint: string"],"sources":["../src/types.ts","../src/const.ts","../src/logger.ts","../src/audit-logger.ts","../src/audit-ms.ts","../src/common.ts"],"sourcesContent":["import type { ModelStatic, Model } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport type RabbitMq from '@autofleet/rabbit';\nimport type { LoggerInstanceManager } from '@autofleet/logger';\nimport type { IRouter } from 'express';\nimport type { FastifyInstance } from 'fastify';\n\nexport type AuditLoggerOptions = {\n rabbit: RabbitMq;\n sequelize: Sequelize;\n logger: LoggerInstanceManager;\n router?: IRouter;\n fastify?: FastifyInstance;\n excludeModels?: string[];\n entityScopedModelMap?: { [modelName: string]: ModelStatic<Model> };\n};\n\nexport interface AuditLogContext {\n entityType: string;\n entityId?: string;\n action: string;\n performedBy: string | null;\n endpoint: string;\n method: string;\n actionOrigin?: string | null;\n}\n\nexport interface AuditLogRow {\n property: string;\n previousValue: unknown;\n newValue: unknown;\n}\n\nexport interface AuditLogPayload {\n entityType: string;\n entityId: string;\n rows: readonly AuditLogRow[];\n}\n\nexport enum Action {\n CREATE = 'create',\n BULK_CREATE = 'bulk-create',\n BULK_EDIT = 'bulk-edit',\n DELETE = 'delete',\n UPDATE = 'update',\n CANCEL = 'cancel',\n FAIL = 'fail',\n UNASSIGN = 'unassign',\n BULK_ASSIGN = 'bulk-assign',\n REASSIGN = 'reassign',\n DISPATCH = 'dispatch',\n BULK_DISPATCH = 'bulk-dispatch',\n BULK_UPSERT = 'bulk-upsert',\n UPSERT = 'upsert',\n JOIN = 'join',\n MOVE = 'move',\n REOPTIMIZATION = 'reoptimization',\n}\n\nexport enum EntityType {\n RIDE = 'Ride',\n VEHICLE = 'Vehicle',\n DRIVER = 'Driver',\n PRICE_CALCULATION = 'PriceCalculation',\n}\n\nexport const enum ActionOrigin {\n USER = 'user',\n AUTOMATION = 'automation',\n}\n","export const AUDIT_LOG_CONTEXT_QUEUE = 'audit-log-context';\nexport const AUDIT_LOG_ROWS_QUEUE = 'audit-log-rows';\nexport const AUDIT_LOG_CONTEXT_KEY = 'auditLogContext';\nexport const AUTOMATION_ID_HEADER = 'x-af-automation-id';\n","import { getCurrentContextTraceId } from '@autofleet/outbreak';\nimport Logger, { type LoggerInstanceManager } from '@autofleet/logger';\n\nconst logger: LoggerInstanceManager = Logger();\nlogger.addContextMiddleware(() => ({ traceId: getCurrentContextTraceId() }));\nexport default logger;\n","import { isDeepStrictEqual } from 'node:util';\nimport type RabbitMq from '@autofleet/rabbit';\nimport type { LoggerInstanceManager } from '@autofleet/logger';\nimport { getCurrentPayload as getCurrentTrace } from '@autofleet/zehut';\nimport type {\n CreateOptions, InstanceUpdateOptions, Model, Sequelize,\n} from 'sequelize';\nimport {\n type AuditLogPayload, type AuditLoggerOptions, type AuditLogContext, Action, type AuditLogRow,\n} from './types';\nimport { AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUDIT_LOG_CONTEXT_KEY } from './const';\nimport logger from './logger';\n\nconst CUSTOM_FIELDS_PROPERTY = 'customFields';\n\nconst getAuditContext = () => {\n const currentTrace = getCurrentTrace();\n const auditContext = currentTrace?.nonHeaderContext?.get(AUDIT_LOG_CONTEXT_KEY);\n return auditContext as AuditLogContext;\n};\n\nconst ACTIONS_TO_OMIT_ENTITY_ID_FROM_CONTEXT = {\n [Action.BULK_CREATE]: Action.BULK_CREATE,\n [Action.BULK_EDIT]: Action.BULK_EDIT,\n [Action.BULK_ASSIGN]: Action.BULK_ASSIGN,\n [Action.BULK_DISPATCH]: Action.BULK_DISPATCH,\n [Action.BULK_UPSERT]: Action.BULK_UPSERT,\n};\n\nconst isEmpty = (field: unknown): boolean => {\n if ([null, undefined].includes(field as undefined)) {\n return true;\n }\n if (Array.isArray(field)) {\n return field.length === 0;\n }\n if (typeof field === 'object' && !(field instanceof Date)) {\n return Object.keys(field as Record<string, unknown>).length === 0;\n }\n return false;\n};\n\nexport const isEntityIdRequired = (action: string): boolean => Object.hasOwn(ACTIONS_TO_OMIT_ENTITY_ID_FROM_CONTEXT, action);\n\nconst filterOutEmptyFields = (fields: string[], instance: Model) => fields.filter((field) => !isEmpty(instance.get(field)) || !isEmpty(instance.previous(field)));\n\nconst getChangedFieldsRows = (instance: Model, options: CreateOptions | InstanceUpdateOptions): AuditLogRow[] => {\n // When bulk updating in sequelize using the \"returning\" option, the instance.changed() stops working.\n // It's a known issue with sequelize.\n const changedFields: string[] = options.returning ? options.fields as string[] : instance.changed() as string[];\n // Filter customFields - we'll handle them later\n const filteredChangedFields = filterOutEmptyFields(changedFields.filter((field) => field !== CUSTOM_FIELDS_PROPERTY), instance);\n return filteredChangedFields.map((property: string) => ({\n property,\n previousValue: instance.previous(property),\n newValue: instance.get(property),\n }));\n};\n\nconst getChangedCustomFieldsRows = (instance: Model): AuditLogRow[] => {\n const changed = instance.changed();\n const customFieldsChanged = changed && changed.includes(CUSTOM_FIELDS_PROPERTY);\n if (!customFieldsChanged) {\n return [];\n }\n\n const customFields = instance.get(CUSTOM_FIELDS_PROPERTY) as Record<string, unknown>;\n const previousCustomFields = instance.previous(CUSTOM_FIELDS_PROPERTY);\n const changedCustomFields = Object.keys(customFields).filter((field) => {\n const newValue = customFields?.[field];\n const oldValue = previousCustomFields?.[field];\n return (!isEmpty(newValue) || !isEmpty(oldValue)) && !isDeepStrictEqual(newValue, oldValue);\n });\n return changedCustomFields.map((changedCustomField) => ({\n property: `${CUSTOM_FIELDS_PROPERTY}.${changedCustomField}`,\n previousValue: previousCustomFields?.[changedCustomField],\n newValue: customFields?.[changedCustomField],\n }));\n};\n\ninterface AuditLogSendData extends AuditLogPayload {\n auditContext?: AuditLogContext;\n}\n\nclass AuditLogger {\n private rabbit: RabbitMq;\n\n private sequelize: Sequelize;\n\n private logger: LoggerInstanceManager;\n\n private excludeModels: string[];\n\n constructor(options: AuditLoggerOptions) {\n this.rabbit = options.rabbit;\n this.sequelize = options.sequelize;\n this.logger = options.logger || logger;\n this.excludeModels = options.excludeModels ?? [];\n }\n\n public async manualSendAuditLog({\n auditContext, ...payload\n }: AuditLogSendData): Promise<void> {\n auditContext ??= getAuditContext();\n if (!auditContext) {\n return;\n }\n try {\n // Make sure the current entity being changed it the \"main\" entity in the current audit context, and if so mark it as the \"entityId\".\n if (auditContext?.entityType?.toLowerCase() === payload.entityType?.toLowerCase() && isEntityIdRequired(auditContext.action)) {\n auditContext.entityId = payload.entityId;\n }\n await this.sendAuditLogRows(payload);\n } catch (error) {\n const { entityType, entityId } = payload;\n this.logger.error('Failed to send audit log rows', { entityType, entityId, error });\n }\n }\n\n public registerHooks(): void {\n Object.entries(this.sequelize.models).forEach(([modelName, modelType]) => {\n if (this.excludeModels.includes(modelName)) {\n return;\n }\n modelType.addHook('afterSave', async (instance, options) => {\n const auditContext = getAuditContext();\n if (!auditContext) return;\n\n const { id: entityId } = instance as unknown as { id: string; };\n await this.manualSendAuditLog({\n entityId,\n auditContext,\n entityType: modelName,\n rows: [...getChangedFieldsRows(instance, options), ...getChangedCustomFieldsRows(instance)],\n });\n });\n });\n }\n\n public async sendAuditLogContext(context: AuditLogContext): Promise<void> {\n try {\n await this.rabbit.sendToQueue(AUDIT_LOG_CONTEXT_QUEUE, context);\n } catch (err) {\n this.logger.error('Failed to send audit log context', err);\n }\n }\n\n private async sendAuditLogRows(payload: AuditLogPayload): Promise<void> {\n try {\n await this.rabbit.sendToQueue(AUDIT_LOG_ROWS_QUEUE, payload);\n } catch (err) {\n this.logger.error('Failed to send audit log rows', err);\n }\n }\n}\n\nexport default AuditLogger;\n","import Network from '@autofleet/network';\nimport logger from './logger';\n\nconst auditMs = new Network({ serviceName: 'AUDIT_MS', timeout: 60_000, logger });\n\nconst getByEntityId = async (entityId: string): Promise<any> => {\n const { data } = await auditMs.get(`api/v1/audit-logs/${entityId}`);\n return data;\n};\n\nconst exportObj: { getByEntityId: typeof getByEntityId } = { getByEntityId };\n\nexport default exportObj;\n","import type { Writable } from 'node:stream';\nimport type { IncomingHttpHeaders } from 'node:http';\nimport { getCurrentPayload, getUser } from '@autofleet/zehut';\nimport logger from './logger';\nimport AuditLogger, { isEntityIdRequired } from './audit-logger';\nimport { AUDIT_LOG_CONTEXT_KEY, AUTOMATION_ID_HEADER } from './const';\nimport { ActionOrigin, type AuditLogContext, type AuditLoggerOptions } from './types';\n\nlet auditLogger: AuditLogger | undefined;\n\nexport const innerEnableAuditing = (options: AuditLoggerOptions): boolean => {\n if (process.env.DISABLE_AUDIT_LOGS === 'true') {\n return false;\n }\n auditLogger = new AuditLogger(options);\n auditLogger.registerHooks();\n return true;\n};\n\ninterface GetAuditLogContextParams {\n action: string;\n endpoint: string;\n entityType: string;\n method: string;\n automationId?: string;\n userId?: string;\n}\nconst getAuditLogContextAndSetToContext = ({\n action, endpoint, entityType, method, automationId, userId,\n}: GetAuditLogContextParams): AuditLogContext => {\n const performedBy = userId || (automationId ?? null);\n const actionOrigin = (userId && ActionOrigin.USER) || (automationId && ActionOrigin.AUTOMATION) || null;\n\n const auditLogContext: AuditLogContext = {\n entityType,\n action,\n endpoint,\n method,\n performedBy,\n actionOrigin,\n };\n const currentTrace = getCurrentPayload();\n currentTrace.nonHeaderContext.set(AUDIT_LOG_CONTEXT_KEY, auditLogContext);\n\n return auditLogContext;\n};\n\ninterface PartialRequest {\n url: string;\n method: string;\n headers: IncomingHttpHeaders;\n}\n\nexport const innerSetAuditContext = async (req: PartialRequest, res: Writable, entityType: string, action: string): Promise<void> => {\n try {\n if (process.env.DISABLE_AUDIT_LOGS === 'true' || !auditLogger) {\n return;\n }\n const auditLogContext = getAuditLogContextAndSetToContext({\n action,\n endpoint: req.url,\n entityType,\n method: req.method,\n userId: getUser()?.id,\n automationId: req.headers[AUTOMATION_ID_HEADER] as string | undefined,\n });\n\n if (!isEntityIdRequired(action)) { // if it's a bulk action, we don't want to wait for the response to add the entity id\n await auditLogger.sendAuditLogContext(auditLogContext);\n return;\n }\n\n const sendAuditLogContextEvent = async () => {\n res.off('finish', sendAuditLogContextEvent);\n res.off('close', sendAuditLogContextEvent);\n res.off('error', sendAuditLogContextEvent);\n await auditLogger?.sendAuditLogContext(auditLogContext);\n };\n res.once('finish', sendAuditLogContextEvent);\n res.once('close', sendAuditLogContextEvent);\n res.once('error', sendAuditLogContextEvent);\n } catch (err) {\n logger.error('couldn\\'t set audit context', err);\n }\n};\n\nexport const setRabbitAuditContext = (entityType: string, action: string) => async (endpoint: string, { userId, automationId }: { userId:string; automationId:string; }): Promise<void> => {\n if (process.env.DISABLE_AUDIT_LOGS === 'true' || !auditLogger) {\n return;\n }\n const auditLogContext = getAuditLogContextAndSetToContext({\n action,\n endpoint,\n entityType,\n method: 'rabbit',\n userId,\n automationId,\n });\n\n await auditLogger.sendAuditLogContext(auditLogContext);\n};\n"],"mappings":"qpBAkEA,IA3BY,kBAAA,SAAA,EAAL,QACL,EAAA,OAAA,SACA,EAAA,YAAA,cACA,EAAA,UAAA,YACA,EAAA,OAAA,SACA,EAAA,OAAA,SACA,EAAA,OAAA,SACA,EAAA,KAAA,OACA,EAAA,SAAA,WACA,EAAA,YAAA,cACA,EAAA,SAAA,WACA,EAAA,SAAA,WACA,EAAA,cAAA,gBACA,EAAA,YAAA,cACA,EAAA,OAAA,SACA,EAAA,KAAA,OACA,EAAA,KAAA,OACA,EAAA,eAAA,kBACD,EAAA,CAAA,EAAA,CAEW,kBAAA,SAAA,EAAL,QACL,EAAA,KAAA,OACA,EAAA,QAAA,UACA,EAAA,OAAA,SACA,EAAA,kBAAA,oBACD,EAAA,CAAA,EAAA,CAEiB,kBAAA,SAAA,EAAX,QACL,EAAA,KA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MAAOC,EAAqBC,EAAeC,EAAoBC,IAAkC,CACnI,GAAI,CACF,GAAI,QAAQ,IAAI,qBAAuB,SAAW,EAChD,OAEF,IAAM,EAAkB,EAAkC,CACxD,SACA,SAAU,EAAI,IACd,aACA,OAAQ,EAAI,OACZ,OAAQ,CAAA,EAAA,EAAA,UAAS,EAAE,GACnB,aAAc,EAAI,QAAQ,EAC3B,EAAC,CAEF,IAAK,EAAmB,EAAO,CAAE,CAC/B,KAAM,GAAY,oBAAoB,EAAgB,CACtD,MACD,CAED,IAAM,EAA2B,SAAY,CAI3C,AAHA,EAAI,IAAI,SAAU,EAAyB,CAC3C,EAAI,IAAI,QAAS,EAAyB,CAC1C,EAAI,IAAI,QAAS,EAAyB,CAC1C,KAAM,IAAa,oBAAoB,EAAgB,AACxD,EAGD,AAFA,EAAI,KAAK,SAAU,EAAyB,CAC5C,EAAI,KAAK,QAAS,EAAyB,CAC3C,EAAI,KAAK,QAAS,EAAyB,AAC5C,OAAQ,EAAK,CACZ,EAAO,MAAM,6BAA+B,EAAI,AACjD,CACF,EAEY,EAAwB,CAACD,EAAoBC,IAAmB,MAAOC,EAAkB,CAAE,SAAQ,eAAuD,GAAoB,CACzL,GAAI,QAAQ,IAAI,qBAAuB,SAAW,EAChD,OAEF,IAAM,EAAkB,EAAkC,CACxD,SACA,WACA,aACA,OAAQ,SACR,SACA,cACD,EAAC,CAEF,KAAM,GAAY,oBAAoB,EAAgB,AACvD"}
@@ -1,2 +0,0 @@
1
- import{isDeepStrictEqual as e}from"node:util";import{getCurrentPayload as t,getUser as n}from"@autofleet/zehut";import{getCurrentContextTraceId as r}from"@autofleet/outbreak";import i from"@autofleet/logger";import a from"@autofleet/network";let o=/* @__PURE__ */ function(e){return e.CREATE=`create`,e.BULK_CREATE=`bulk-create`,e.BULK_EDIT=`bulk-edit`,e.DELETE=`delete`,e.UPDATE=`update`,e.CANCEL=`cancel`,e.FAIL=`fail`,e.UNASSIGN=`unassign`,e.BULK_ASSIGN=`bulk-assign`,e.REASSIGN=`reassign`,e.DISPATCH=`dispatch`,e.BULK_DISPATCH=`bulk-dispatch`,e.BULK_UPSERT=`bulk-upsert`,e.UPSERT=`upsert`,e.JOIN=`join`,e.MOVE=`move`,e.REOPTIMIZATION=`reoptimization`,e}({}),s=/* @__PURE__ */ function(e){return e.RIDE=`Ride`,e.VEHICLE=`Vehicle`,e.DRIVER=`Driver`,e.PRICE_CALCULATION=`PriceCalculation`,e}({}),c=/* @__PURE__ */ function(e){return e.USER=`user`,e.AUTOMATION=`automation`,e}({});const l=`audit-log-context`,u=`audit-log-rows`,d=`auditLogContext`,f=`x-af-automation-id`,p=i();p.addContextMiddleware(()=>({traceId:r()}));var m=p;const h=`customFields`,g=()=>{let e=t(),n=e?.nonHeaderContext?.get(d);return n},_={[o.BULK_CREATE]:o.BULK_CREATE,[o.BULK_EDIT]:o.BULK_EDIT,[o.BULK_ASSIGN]:o.BULK_ASSIGN,[o.BULK_DISPATCH]:o.BULK_DISPATCH,[o.BULK_UPSERT]:o.BULK_UPSERT},v=e=>[null,void 0].includes(e)?!0:Array.isArray(e)?e.length===0:typeof e==`object`&&!(e instanceof Date)?Object.keys(e).length===0:!1,y=e=>Object.hasOwn(_,e),b=(e,t)=>e.filter(e=>!v(t.get(e))||!v(t.previous(e))),x=(e,t)=>{let n=t.returning?t.fields:e.changed(),r=b(n.filter(e=>e!==h),e);return r.map(t=>({property:t,previousValue:e.previous(t),newValue:e.get(t)}))},S=t=>{let n=t.changed(),r=n&&n.includes(h);if(!r)return[];let i=t.get(h),a=t.previous(h),o=Object.keys(i).filter(t=>{let n=i?.[t],r=a?.[t];return(!v(n)||!v(r))&&!e(n,r)});return o.map(e=>({property:`${h}.${e}`,previousValue:a?.[e],newValue:i?.[e]}))};var C=class{constructor(e){this.rabbit=e.rabbit,this.sequelize=e.sequelize,this.logger=e.logger||m,this.excludeModels=e.excludeModels??[]}async manualSendAuditLog({auditContext:e,...t}){if(e??=g(),e)try{e?.entityType?.toLowerCase()===t.entityType?.toLowerCase()&&y(e.action)&&(e.entityId=t.entityId),await this.sendAuditLogRows(t)}catch(e){let{entityType:n,entityId:r}=t;this.logger.error(`Failed to send audit log rows`,{entityType:n,entityId:r,error:e})}}registerHooks(){Object.entries(this.sequelize.models).forEach(([e,t])=>{this.excludeModels.includes(e)||t.addHook(`afterSave`,async(t,n)=>{let r=g();if(!r)return;let{id:i}=t;await this.manualSendAuditLog({entityId:i,auditContext:r,entityType:e,rows:[...x(t,n),...S(t)]})})})}async sendAuditLogContext(e){try{await this.rabbit.sendToQueue(l,e)}catch(e){this.logger.error(`Failed to send audit log context`,e)}}async sendAuditLogRows(e){try{await this.rabbit.sendToQueue(u,e)}catch(e){this.logger.error(`Failed to send audit log rows`,e)}}},w=C;const T=new a({serviceName:`AUDIT_MS`,timeout:6e4,logger:m}),E=async e=>{let{data:t}=await T.get(`api/v1/audit-logs/${e}`);return t},D={getByEntityId:E};var O=D;let k;const A=e=>process.env.DISABLE_AUDIT_LOGS===`true`?!1:(k=new w(e),k.registerHooks(),!0),j=({action:e,endpoint:n,entityType:r,method:i,automationId:a,userId:o})=>{let s=o||(a??null),l=o&&c.USER||a&&c.AUTOMATION||null,u={entityType:r,action:e,endpoint:n,method:i,performedBy:s,actionOrigin:l},f=t();return f.nonHeaderContext.set(d,u),u},M=async(e,t,r,i)=>{try{if(process.env.DISABLE_AUDIT_LOGS===`true`||!k)return;let a=j({action:i,endpoint:e.url,entityType:r,method:e.method,userId:n()?.id,automationId:e.headers[f]});if(!y(i)){await k.sendAuditLogContext(a);return}let o=async()=>{t.off(`finish`,o),t.off(`close`,o),t.off(`error`,o),await k?.sendAuditLogContext(a)};t.once(`finish`,o),t.once(`close`,o),t.once(`error`,o)}catch(e){m.error(`couldn't set audit context`,e)}},N=(e,t)=>async(n,{userId:r,automationId:i})=>{if(process.env.DISABLE_AUDIT_LOGS===`true`||!k)return;let a=j({action:t,endpoint:n,entityType:e,method:`rabbit`,userId:r,automationId:i});await k.sendAuditLogContext(a)};export{d as AUDIT_LOG_CONTEXT_KEY,l as AUDIT_LOG_CONTEXT_QUEUE,u as AUDIT_LOG_ROWS_QUEUE,f as AUTOMATION_ID_HEADER,o as Action,c as ActionOrigin,s as EntityType,w as audit_logger_default,O as audit_ms_default,A as innerEnableAuditing,M as innerSetAuditContext,N as setRabbitAuditContext};
2
- //# sourceMappingURL=common-oy2ugNvX.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"common-oy2ugNvX.js","names":["logger: LoggerInstanceManager","field: unknown","action: string","fields: string[]","instance: Model","options: CreateOptions | InstanceUpdateOptions","changedFields: string[]","property: string","options: AuditLoggerOptions","context: AuditLogContext","payload: AuditLogPayload","entityId: string","exportObj: { getByEntityId: typeof getByEntityId }","auditLogger: AuditLogger | undefined","options: AuditLoggerOptions","auditLogContext: AuditLogContext","req: PartialRequest","res: Writable","entityType: string","action: string","endpoint: string"],"sources":["../src/types.ts","../src/const.ts","../src/logger.ts","../src/audit-logger.ts","../src/audit-ms.ts","../src/common.ts"],"sourcesContent":["import type { ModelStatic, Model } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport type RabbitMq from '@autofleet/rabbit';\nimport type { LoggerInstanceManager } from '@autofleet/logger';\nimport type { IRouter } from 'express';\nimport type { FastifyInstance } from 'fastify';\n\nexport type AuditLoggerOptions = {\n rabbit: RabbitMq;\n sequelize: Sequelize;\n logger: LoggerInstanceManager;\n router?: IRouter;\n fastify?: FastifyInstance;\n excludeModels?: string[];\n entityScopedModelMap?: { [modelName: string]: ModelStatic<Model> };\n};\n\nexport interface AuditLogContext {\n entityType: string;\n entityId?: string;\n action: string;\n performedBy: string | null;\n endpoint: string;\n method: string;\n actionOrigin?: string | null;\n}\n\nexport interface AuditLogRow {\n property: string;\n previousValue: unknown;\n newValue: unknown;\n}\n\nexport interface AuditLogPayload {\n entityType: string;\n entityId: string;\n rows: readonly AuditLogRow[];\n}\n\nexport enum Action {\n CREATE = 'create',\n BULK_CREATE = 'bulk-create',\n BULK_EDIT = 'bulk-edit',\n DELETE = 'delete',\n UPDATE = 'update',\n CANCEL = 'cancel',\n FAIL = 'fail',\n UNASSIGN = 'unassign',\n BULK_ASSIGN = 'bulk-assign',\n REASSIGN = 'reassign',\n DISPATCH = 'dispatch',\n BULK_DISPATCH = 'bulk-dispatch',\n BULK_UPSERT = 'bulk-upsert',\n UPSERT = 'upsert',\n JOIN = 'join',\n MOVE = 'move',\n REOPTIMIZATION = 'reoptimization',\n}\n\nexport enum EntityType {\n RIDE = 'Ride',\n VEHICLE = 'Vehicle',\n DRIVER = 'Driver',\n PRICE_CALCULATION = 'PriceCalculation',\n}\n\nexport const enum ActionOrigin {\n USER = 'user',\n AUTOMATION = 'automation',\n}\n","export const AUDIT_LOG_CONTEXT_QUEUE = 'audit-log-context';\nexport const AUDIT_LOG_ROWS_QUEUE = 'audit-log-rows';\nexport const AUDIT_LOG_CONTEXT_KEY = 'auditLogContext';\nexport const AUTOMATION_ID_HEADER = 'x-af-automation-id';\n","import { getCurrentContextTraceId } from '@autofleet/outbreak';\nimport Logger, { type LoggerInstanceManager } from '@autofleet/logger';\n\nconst logger: LoggerInstanceManager = Logger();\nlogger.addContextMiddleware(() => ({ traceId: getCurrentContextTraceId() }));\nexport default logger;\n","import { isDeepStrictEqual } from 'node:util';\nimport type RabbitMq from '@autofleet/rabbit';\nimport type { LoggerInstanceManager } from '@autofleet/logger';\nimport { getCurrentPayload as getCurrentTrace } from '@autofleet/zehut';\nimport type {\n CreateOptions, InstanceUpdateOptions, Model, Sequelize,\n} from 'sequelize';\nimport {\n type AuditLogPayload, type AuditLoggerOptions, type AuditLogContext, Action, type AuditLogRow,\n} from './types';\nimport { AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUDIT_LOG_CONTEXT_KEY } from './const';\nimport logger from './logger';\n\nconst CUSTOM_FIELDS_PROPERTY = 'customFields';\n\nconst getAuditContext = () => {\n const currentTrace = getCurrentTrace();\n const auditContext = currentTrace?.nonHeaderContext?.get(AUDIT_LOG_CONTEXT_KEY);\n return auditContext as AuditLogContext;\n};\n\nconst ACTIONS_TO_OMIT_ENTITY_ID_FROM_CONTEXT = {\n [Action.BULK_CREATE]: Action.BULK_CREATE,\n [Action.BULK_EDIT]: Action.BULK_EDIT,\n [Action.BULK_ASSIGN]: Action.BULK_ASSIGN,\n [Action.BULK_DISPATCH]: Action.BULK_DISPATCH,\n [Action.BULK_UPSERT]: Action.BULK_UPSERT,\n};\n\nconst isEmpty = (field: unknown): boolean => {\n if ([null, undefined].includes(field as undefined)) {\n return true;\n }\n if (Array.isArray(field)) {\n return field.length === 0;\n }\n if (typeof field === 'object' && !(field instanceof Date)) {\n return Object.keys(field as Record<string, unknown>).length === 0;\n }\n return false;\n};\n\nexport const isEntityIdRequired = (action: string): boolean => Object.hasOwn(ACTIONS_TO_OMIT_ENTITY_ID_FROM_CONTEXT, action);\n\nconst filterOutEmptyFields = (fields: string[], instance: Model) => fields.filter((field) => !isEmpty(instance.get(field)) || !isEmpty(instance.previous(field)));\n\nconst getChangedFieldsRows = (instance: Model, options: CreateOptions | InstanceUpdateOptions): AuditLogRow[] => {\n // When bulk updating in sequelize using the \"returning\" option, the instance.changed() stops working.\n // It's a known issue with sequelize.\n const changedFields: string[] = options.returning ? options.fields as string[] : instance.changed() as string[];\n // Filter customFields - we'll handle them later\n const filteredChangedFields = filterOutEmptyFields(changedFields.filter((field) => field !== CUSTOM_FIELDS_PROPERTY), instance);\n return filteredChangedFields.map((property: string) => ({\n property,\n previousValue: instance.previous(property),\n newValue: instance.get(property),\n }));\n};\n\nconst getChangedCustomFieldsRows = (instance: Model): AuditLogRow[] => {\n const changed = instance.changed();\n const customFieldsChanged = changed && changed.includes(CUSTOM_FIELDS_PROPERTY);\n if (!customFieldsChanged) {\n return [];\n }\n\n const customFields = instance.get(CUSTOM_FIELDS_PROPERTY) as Record<string, unknown>;\n const previousCustomFields = instance.previous(CUSTOM_FIELDS_PROPERTY);\n const changedCustomFields = Object.keys(customFields).filter((field) => {\n const newValue = customFields?.[field];\n const oldValue = previousCustomFields?.[field];\n return (!isEmpty(newValue) || !isEmpty(oldValue)) && !isDeepStrictEqual(newValue, oldValue);\n });\n return changedCustomFields.map((changedCustomField) => ({\n property: `${CUSTOM_FIELDS_PROPERTY}.${changedCustomField}`,\n previousValue: previousCustomFields?.[changedCustomField],\n newValue: customFields?.[changedCustomField],\n }));\n};\n\ninterface AuditLogSendData extends AuditLogPayload {\n auditContext?: AuditLogContext;\n}\n\nclass AuditLogger {\n private rabbit: RabbitMq;\n\n private sequelize: Sequelize;\n\n private logger: LoggerInstanceManager;\n\n private excludeModels: string[];\n\n constructor(options: AuditLoggerOptions) {\n this.rabbit = options.rabbit;\n this.sequelize = options.sequelize;\n this.logger = options.logger || logger;\n this.excludeModels = options.excludeModels ?? [];\n }\n\n public async manualSendAuditLog({\n auditContext, ...payload\n }: AuditLogSendData): Promise<void> {\n auditContext ??= getAuditContext();\n if (!auditContext) {\n return;\n }\n try {\n // Make sure the current entity being changed it the \"main\" entity in the current audit context, and if so mark it as the \"entityId\".\n if (auditContext?.entityType?.toLowerCase() === payload.entityType?.toLowerCase() && isEntityIdRequired(auditContext.action)) {\n auditContext.entityId = payload.entityId;\n }\n await this.sendAuditLogRows(payload);\n } catch (error) {\n const { entityType, entityId } = payload;\n this.logger.error('Failed to send audit log rows', { entityType, entityId, error });\n }\n }\n\n public registerHooks(): void {\n Object.entries(this.sequelize.models).forEach(([modelName, modelType]) => {\n if (this.excludeModels.includes(modelName)) {\n return;\n }\n modelType.addHook('afterSave', async (instance, options) => {\n const auditContext = getAuditContext();\n if (!auditContext) return;\n\n const { id: entityId } = instance as unknown as { id: string; };\n await this.manualSendAuditLog({\n entityId,\n auditContext,\n entityType: modelName,\n rows: [...getChangedFieldsRows(instance, options), ...getChangedCustomFieldsRows(instance)],\n });\n });\n });\n }\n\n public async sendAuditLogContext(context: AuditLogContext): Promise<void> {\n try {\n await this.rabbit.sendToQueue(AUDIT_LOG_CONTEXT_QUEUE, context);\n } catch (err) {\n this.logger.error('Failed to send audit log context', err);\n }\n }\n\n private async sendAuditLogRows(payload: AuditLogPayload): Promise<void> {\n try {\n await this.rabbit.sendToQueue(AUDIT_LOG_ROWS_QUEUE, payload);\n } catch (err) {\n this.logger.error('Failed to send audit log rows', err);\n }\n }\n}\n\nexport default AuditLogger;\n","import Network from '@autofleet/network';\nimport logger from './logger';\n\nconst auditMs = new Network({ serviceName: 'AUDIT_MS', timeout: 60_000, logger });\n\nconst getByEntityId = async (entityId: string): Promise<any> => {\n const { data } = await auditMs.get(`api/v1/audit-logs/${entityId}`);\n return data;\n};\n\nconst exportObj: { getByEntityId: typeof getByEntityId } = { getByEntityId };\n\nexport default exportObj;\n","import type { Writable } from 'node:stream';\nimport type { IncomingHttpHeaders } from 'node:http';\nimport { getCurrentPayload, getUser } from '@autofleet/zehut';\nimport logger from './logger';\nimport AuditLogger, { isEntityIdRequired } from './audit-logger';\nimport { AUDIT_LOG_CONTEXT_KEY, AUTOMATION_ID_HEADER } from './const';\nimport { ActionOrigin, type AuditLogContext, type AuditLoggerOptions } from './types';\n\nlet auditLogger: AuditLogger | undefined;\n\nexport const innerEnableAuditing = (options: AuditLoggerOptions): boolean => {\n if (process.env.DISABLE_AUDIT_LOGS === 'true') {\n return false;\n }\n auditLogger = new AuditLogger(options);\n auditLogger.registerHooks();\n return true;\n};\n\ninterface GetAuditLogContextParams {\n action: string;\n endpoint: string;\n entityType: string;\n method: string;\n automationId?: string;\n userId?: string;\n}\nconst getAuditLogContextAndSetToContext = ({\n action, endpoint, entityType, method, automationId, userId,\n}: GetAuditLogContextParams): AuditLogContext => {\n const performedBy = userId || (automationId ?? null);\n const actionOrigin = (userId && ActionOrigin.USER) || (automationId && ActionOrigin.AUTOMATION) || null;\n\n const auditLogContext: AuditLogContext = {\n entityType,\n action,\n endpoint,\n method,\n performedBy,\n actionOrigin,\n };\n const currentTrace = getCurrentPayload();\n currentTrace.nonHeaderContext.set(AUDIT_LOG_CONTEXT_KEY, auditLogContext);\n\n return auditLogContext;\n};\n\ninterface PartialRequest {\n url: string;\n method: string;\n headers: IncomingHttpHeaders;\n}\n\nexport const innerSetAuditContext = async (req: PartialRequest, res: Writable, entityType: string, action: string): Promise<void> => {\n try {\n if (process.env.DISABLE_AUDIT_LOGS === 'true' || !auditLogger) {\n return;\n }\n const auditLogContext = getAuditLogContextAndSetToContext({\n action,\n endpoint: req.url,\n entityType,\n method: req.method,\n userId: getUser()?.id,\n automationId: req.headers[AUTOMATION_ID_HEADER] as string | undefined,\n });\n\n if (!isEntityIdRequired(action)) { // if it's a bulk action, we don't want to wait for the response to add the entity id\n await auditLogger.sendAuditLogContext(auditLogContext);\n return;\n }\n\n const sendAuditLogContextEvent = async () => {\n res.off('finish', sendAuditLogContextEvent);\n res.off('close', sendAuditLogContextEvent);\n res.off('error', sendAuditLogContextEvent);\n await auditLogger?.sendAuditLogContext(auditLogContext);\n };\n res.once('finish', sendAuditLogContextEvent);\n res.once('close', sendAuditLogContextEvent);\n res.once('error', sendAuditLogContextEvent);\n } catch (err) {\n logger.error('couldn\\'t set audit context', err);\n }\n};\n\nexport const setRabbitAuditContext = (entityType: string, action: string) => async (endpoint: string, { userId, automationId }: { userId:string; automationId:string; }): Promise<void> => {\n if (process.env.DISABLE_AUDIT_LOGS === 'true' || !auditLogger) {\n return;\n }\n const auditLogContext = getAuditLogContextAndSetToContext({\n action,\n endpoint,\n entityType,\n method: 'rabbit',\n userId,\n automationId,\n });\n\n await auditLogger.sendAuditLogContext(auditLogContext);\n};\n"],"mappings":"kPAkEA,IA3BY,kBAAA,SAAA,EAAL,QACL,EAAA,OAAA,SACA,EAAA,YAAA,cACA,EAAA,UAAA,YACA,EAAA,OAAA,SACA,EAAA,OAAA,SACA,EAAA,OAAA,SACA,EAAA,KAAA,OACA,EAAA,SAAA,WACA,EAAA,YAAA,cACA,EAAA,SAAA,WACA,EAAA,SAAA,WACA,EAAA,cAAA,gBACA,EAAA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