@geekmidas/audit 10.0.0-alpha.99 → 10.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/CHANGELOG.md +109 -0
  2. package/README.md +2 -2
  3. package/TECHNICAL.md +937 -0
  4. package/dist/{Auditor-BBXXCD0v.d.cts → Auditor-CW2NrfHS.d.mts} +7 -2
  5. package/dist/Auditor-CW2NrfHS.d.mts.map +1 -0
  6. package/dist/{Auditor-BBXXCD0v.d.mts → Auditor-DpBHXIJM.d.cts} +7 -2
  7. package/dist/Auditor-DpBHXIJM.d.cts.map +1 -0
  8. package/dist/Auditor.d.cts +1 -1
  9. package/dist/Auditor.d.mts +1 -1
  10. package/dist/Auditor.mjs +0 -1
  11. package/dist/DefaultAuditor-BAVnNmRh.mjs +96 -0
  12. package/dist/DefaultAuditor-BAVnNmRh.mjs.map +1 -0
  13. package/dist/DefaultAuditor-DlJ1ENfx.d.mts +59 -0
  14. package/dist/DefaultAuditor-DlJ1ENfx.d.mts.map +1 -0
  15. package/dist/DefaultAuditor-GRFI86N_.d.cts +59 -0
  16. package/dist/DefaultAuditor-GRFI86N_.d.cts.map +1 -0
  17. package/dist/DefaultAuditor-JbZ_BQfh.cjs +102 -0
  18. package/dist/DefaultAuditor-JbZ_BQfh.cjs.map +1 -0
  19. package/dist/DefaultAuditor.cjs +2 -95
  20. package/dist/DefaultAuditor.d.cts +3 -55
  21. package/dist/DefaultAuditor.d.mts +3 -55
  22. package/dist/DefaultAuditor.mjs +2 -94
  23. package/dist/cache-BbIl31RL.mjs +167 -0
  24. package/dist/cache-BbIl31RL.mjs.map +1 -0
  25. package/dist/cache-Bih6HxY6.d.cts +96 -0
  26. package/dist/cache-Bih6HxY6.d.cts.map +1 -0
  27. package/dist/cache-l7jAptBl.cjs +173 -0
  28. package/dist/cache-l7jAptBl.cjs.map +1 -0
  29. package/dist/cache-wET57t6d.d.mts +96 -0
  30. package/dist/cache-wET57t6d.d.mts.map +1 -0
  31. package/dist/cache.cjs +2 -166
  32. package/dist/cache.d.cts +3 -92
  33. package/dist/cache.d.mts +3 -92
  34. package/dist/cache.mjs +2 -165
  35. package/dist/chunk-CUT6urMc.cjs +30 -0
  36. package/dist/index.cjs +3 -3
  37. package/dist/index.d.cts +3 -3
  38. package/dist/index.d.mts +3 -3
  39. package/dist/index.mjs +3 -2
  40. package/dist/knex.cjs +9 -9
  41. package/dist/knex.cjs.map +1 -1
  42. package/dist/knex.d.cts +11 -9
  43. package/dist/knex.d.cts.map +1 -1
  44. package/dist/knex.d.mts +11 -9
  45. package/dist/knex.d.mts.map +1 -1
  46. package/dist/knex.mjs +7 -7
  47. package/dist/knex.mjs.map +1 -1
  48. package/dist/kysely.cjs +9 -9
  49. package/dist/kysely.cjs.map +1 -1
  50. package/dist/kysely.d.cts +11 -9
  51. package/dist/kysely.d.cts.map +1 -1
  52. package/dist/kysely.d.mts +11 -9
  53. package/dist/kysely.d.mts.map +1 -1
  54. package/dist/kysely.mjs +7 -7
  55. package/dist/kysely.mjs.map +1 -1
  56. package/dist/memory.cjs +7 -6
  57. package/dist/memory.cjs.map +1 -1
  58. package/dist/memory.d.cts +7 -3
  59. package/dist/memory.d.cts.map +1 -1
  60. package/dist/memory.d.mts +7 -3
  61. package/dist/memory.d.mts.map +1 -1
  62. package/dist/memory.mjs +4 -3
  63. package/dist/memory.mjs.map +1 -1
  64. package/dist/storage.d.cts +1 -1
  65. package/dist/storage.d.mts +1 -1
  66. package/dist/storage.mjs +0 -1
  67. package/dist/types.d.cts +1 -1
  68. package/dist/types.d.mts +1 -1
  69. package/dist/types.mjs +0 -1
  70. package/package.json +13 -19
  71. package/src/Auditor.ts +157 -0
  72. package/src/DefaultAuditor.ts +141 -0
  73. package/src/__tests__/CacheAuditStorage.spec.ts +382 -0
  74. package/src/__tests__/DefaultAuditor.spec.ts +529 -0
  75. package/src/__tests__/InMemoryAuditStorage.spec.ts +317 -0
  76. package/src/__tests__/KnexAuditStorage.integration.spec.ts +739 -0
  77. package/src/__tests__/KyselyAuditStorage.integration.spec.ts +518 -0
  78. package/src/__tests__/KyselyAuditStorage.spec.ts +443 -0
  79. package/src/cache.ts +263 -0
  80. package/src/index.ts +23 -0
  81. package/src/knex.ts +430 -0
  82. package/src/kysely.ts +424 -0
  83. package/src/memory.ts +50 -0
  84. package/src/storage.ts +203 -0
  85. package/src/types.ts +154 -0
  86. package/tsconfig.json +9 -0
  87. package/dist/Auditor-BBXXCD0v.d.cts.map +0 -1
  88. package/dist/Auditor-BBXXCD0v.d.mts.map +0 -1
  89. package/dist/DefaultAuditor.cjs.map +0 -1
  90. package/dist/DefaultAuditor.d.cts.map +0 -1
  91. package/dist/DefaultAuditor.d.mts.map +0 -1
  92. package/dist/DefaultAuditor.mjs.map +0 -1
  93. package/dist/cache.cjs.map +0 -1
  94. package/dist/cache.d.cts.map +0 -1
  95. package/dist/cache.d.mts.map +0 -1
  96. package/dist/cache.mjs.map +0 -1
package/dist/kysely.d.mts CHANGED
@@ -1,10 +1,11 @@
1
- import { h as TransactionAwareAuditor, m as AuditStorage, o as AuditRecord, p as AuditQueryOptions } from "./Auditor-BBXXCD0v.mjs";
1
+ import { AuditQueryOptions, AuditRecord, AuditStorage, TransactionAwareAuditor } from "./Auditor-CW2NrfHS.mjs";
2
2
  import { ControlledTransaction, IsolationLevel, Kysely, Transaction } from "kysely";
3
+
3
4
  //#region src/kysely.d.ts
4
- export interface TransactionSettings {
5
+ interface TransactionSettings {
5
6
  isolationLevel?: IsolationLevel;
6
7
  }
7
- export type DatabaseConnection<T> = ControlledTransaction<T> | Kysely<T> | Transaction<T>;
8
+ type DatabaseConnection<T> = ControlledTransaction<T> | Kysely<T> | Transaction<T>;
8
9
  /**
9
10
  * Execute a callback within a database transaction with automatic audit handling.
10
11
  *
@@ -48,7 +49,7 @@ export type DatabaseConnection<T> = ControlledTransaction<T> | Kysely<T> | Trans
48
49
  * // Audits are automatically flushed inside the transaction before commit
49
50
  * ```
50
51
  */
51
- export declare function withAuditableTransaction<DB, T>(db: DatabaseConnection<DB>, auditor: TransactionAwareAuditor<Transaction<DB>>, cb: (trx: Transaction<DB>) => Promise<T>, settings?: TransactionSettings): Promise<T>;
52
+ declare function withAuditableTransaction<DB, T>(db: DatabaseConnection<DB>, auditor: TransactionAwareAuditor<Transaction<DB>>, cb: (trx: Transaction<DB>) => Promise<T>, settings?: TransactionSettings): Promise<T>;
52
53
  /**
53
54
  * Database table interface for audit records.
54
55
  * Use this to define your audit_logs table in your Kysely database schema.
@@ -63,7 +64,7 @@ export declare function withAuditableTransaction<DB, T>(db: DatabaseConnection<D
63
64
  * }
64
65
  * ```
65
66
  */
66
- export interface AuditLogTable {
67
+ interface AuditLogTable {
67
68
  id: string;
68
69
  type: string;
69
70
  operation: string;
@@ -92,13 +93,13 @@ export interface AuditLogTable {
92
93
  * type NewAuditLog = InsertableAuditLogTable;
93
94
  * ```
94
95
  */
95
- export type InsertableAuditLogTable = Omit<AuditLogTable, 'id'> & {
96
+ type InsertableAuditLogTable = Omit<AuditLogTable, 'id'> & {
96
97
  id?: string;
97
98
  };
98
99
  /**
99
100
  * Configuration for KyselyAuditStorage.
100
101
  */
101
- export interface KyselyAuditStorageConfig<DB> {
102
+ interface KyselyAuditStorageConfig<DB> {
102
103
  /** Kysely database instance */
103
104
  db: Kysely<DB>;
104
105
  /** Table name for audit logs (must be a key in DB that extends AuditLogTable) */
@@ -140,7 +141,7 @@ export interface KyselyAuditStorageConfig<DB> {
140
141
  * });
141
142
  * ```
142
143
  */
143
- export declare class KyselyAuditStorage<DB> implements AuditStorage {
144
+ declare class KyselyAuditStorage<DB> implements AuditStorage {
144
145
  private readonly db;
145
146
  private readonly tableName;
146
147
  private readonly autoId;
@@ -173,6 +174,7 @@ export declare class KyselyAuditStorage<DB> implements AuditStorage {
173
174
  private getActorData;
174
175
  private parseEntityId;
175
176
  }
177
+ //# sourceMappingURL=kysely.d.ts.map
176
178
  //#endregion
177
- export type { TransactionAwareAuditor };
179
+ export { AuditLogTable, DatabaseConnection, InsertableAuditLogTable, KyselyAuditStorage, KyselyAuditStorageConfig, TransactionAwareAuditor, TransactionSettings, withAuditableTransaction };
178
180
  //# sourceMappingURL=kysely.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"kysely.d.mts","names":[],"sources":["../src/kysely.ts"],"mappings":";;;iBAgBiB;EAChB,iBAAiB;;YAGN,mBAAmB,KAC5B,sBAAsB,KACtB,OAAO,KACP,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBA6CO,yBAAyB,IAAI,GAClD,IAAI,mBAAmB,KACvB,SAAS,wBAAwB,YAAY,MAC7C,KAAK,KAAK,YAAY,QAAQ,QAAQ,IACtC,WAAW,sBACT,QAAQ;;;;;;;;;;;;;;;iBA2CM;EAChB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,WAAW;EACX;EACA;EACA;EACA;;;;;;;;;;;;;;;;YAiBW,0BAA0B,KAAK;EAC1C;;;;;iBAMgB,yBAAyB;;EAEzC,IAAI,OAAO;;EAEX,iBAAiB;;;;;;EAMjB;;;;;;;EAOA;;;;;;;;;;;;;;;;;;;;;;;;;qBA0BY,mBAAmB,eAAe;mBAC7B;mBACA;mBACA;WACR;EAET,YAAY,QAAQ,yBAAyB;EAOvC,MAAM,SAAS,eAAe,gBAAgB;EAW9C,MAAM,SAAS,oBAAoB,QAAQ;EAyB3C,MACL,SAAS,KAAK,yCACZ;;;;;EAeH,eAAe,OAAO;;;;;;;;;EAYhB,gBAAgB,GACrB,SAAS,wBAAwB,YAAY,MAC7C,gBAAgB,QAAQ,IACxB,KAAK,mBAAmB,MACtB,QAAQ;UAqBH;UAwCA;UA4BA;;;;UA4BA;UAUA;UAOA"}
1
+ {"version":3,"file":"kysely.d.mts","names":[],"sources":["../src/kysely.ts"],"sourcesContent":[],"mappings":";;;;AAgBiB,UAAA,mBAAA,CACC;EAGN,cAAA,CAAA,EAHM,cAGY;;AACL,KADb,kBACa,CAAA,CAAA,CAAA,GAAtB,qBAAsB,CAAA,CAAA,CAAA,GACtB,MADsB,CACf,CADe,CAAA,GAEtB,WAFsB,CAEV,CAFU,CAAA;;;;;;AAEX;AA6Cd;;;;;;;;;;;;;;AAKU;AA2CV;AA8BA;;;;AAA0C;AAO1C;;;;;AAIoB;AAuCpB;;;;;;;;;;AAkDW,iBAlLW,wBAkLX,CAAA,EAAA,EAAA,CAAA,CAAA,CAAA,EAAA,EAjLN,kBAiLM,CAjLa,EAiLb,CAAA,EAAA,OAAA,EAhLD,uBAgLC,CAhLuB,WAgLvB,CAhLmC,EAgLnC,CAAA,CAAA,EAAA,EAAA,EAAA,CAAA,GAAA,EA/KA,WA+KA,CA/KY,EA+KZ,CAAA,EAAA,GA/KoB,OA+KpB,CA/K4B,CA+K5B,CAAA,EAAA,QAAA,CAAA,EA9KC,mBA8KD,CAAA,EA7KR,OA6KQ,CA7KA,CA6KA,CAAA;;;;;;;;;;;;;;AAlDgD;UAhF1C,aAAA;;;;;;;;;aASL;;;;;;;;;;;;;;;;;;;;KAqBA,uBAAA,GAA0B,KAAK;;;;;;UAO1B;;MAEZ,OAAO;;mBAEM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAuCL,kCAAkC;;;;;sBAM1B,yBAAyB;iBAOxB,+BAA+B;iBAW/B,oBAAoB,QAAQ;iBA0BvC,KAAK,yCACZ;;;;;iBAeY,OAAO;;;;;;;;;8BAaZ,wBAAwB,YAAY,sBAC7B,QAAQ,SACnB,mBAAmB,MACtB,QAAQ"}
package/dist/kysely.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import { nanoid } from "nanoid";
2
+
2
3
  //#region src/kysely.ts
3
4
  /**
4
5
  * Execute a callback within a database transaction with automatic audit handling.
@@ -103,7 +104,8 @@ var KyselyAuditStorage = class {
103
104
  query = query.orderBy(orderBy === "timestamp" ? "timestamp" : "type", orderDirection);
104
105
  if (options.limit !== void 0) query = query.limit(options.limit);
105
106
  if (options.offset !== void 0) query = query.offset(options.offset);
106
- return (await query.execute()).map((row) => this.fromRow(row));
107
+ const rows = await query.execute();
108
+ return rows.map((row) => this.fromRow(row));
107
109
  }
108
110
  async count(options) {
109
111
  let query = this.db.selectFrom(this.tableName).select((eb) => eb.fn.count("id").as("count"));
@@ -143,10 +145,8 @@ var KyselyAuditStorage = class {
143
145
  });
144
146
  }
145
147
  applyFilters(query, options) {
146
- if (options.type !== void 0) {
147
- if (Array.isArray(options.type)) query = query.where("type", "in", options.type);
148
- else query = query.where("type", "=", options.type);
149
- }
148
+ if (options.type !== void 0) if (Array.isArray(options.type)) query = query.where("type", "in", options.type);
149
+ else query = query.where("type", "=", options.type);
150
150
  if (options.entityId !== void 0) {
151
151
  const entityId = typeof options.entityId === "string" ? options.entityId : JSON.stringify(options.entityId);
152
152
  query = query.where("entityId", "=", entityId);
@@ -204,7 +204,7 @@ var KyselyAuditStorage = class {
204
204
  return {};
205
205
  }
206
206
  getActorData(actor) {
207
- const { id, type, ...rest } = actor;
207
+ const { id, type,...rest } = actor;
208
208
  return rest;
209
209
  }
210
210
  parseEntityId(entityId) {
@@ -217,7 +217,7 @@ var KyselyAuditStorage = class {
217
217
  }
218
218
  }
219
219
  };
220
+
220
221
  //#endregion
221
222
  export { KyselyAuditStorage, withAuditableTransaction };
222
-
223
223
  //# sourceMappingURL=kysely.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"kysely.mjs","names":[],"sources":["../src/kysely.ts"],"sourcesContent":["import type {\n\tControlledTransaction,\n\tIsolationLevel,\n\tKysely,\n\tTransaction,\n} from 'kysely';\nimport { nanoid } from 'nanoid';\nimport type {\n\tAuditQueryOptions,\n\tAuditStorage,\n\tTransactionAwareAuditor,\n} from './storage';\nimport type { AuditRecord } from './types';\n\nexport type { TransactionAwareAuditor };\n\nexport interface TransactionSettings {\n\tisolationLevel?: IsolationLevel;\n}\n\nexport type DatabaseConnection<T> =\n\t| ControlledTransaction<T>\n\t| Kysely<T>\n\t| Transaction<T>;\n\n/**\n * Execute a callback within a database transaction with automatic audit handling.\n *\n * This wrapper ensures that:\n * 1. The transaction is automatically registered with the auditor\n * 2. Manual audits (via `auditor.audit()`) are flushed BEFORE the transaction commits\n * 3. If audit flush fails, the entire transaction rolls back\n * 4. If the callback fails, audits are NOT written (atomic consistency)\n *\n * **Note:** Declarative audits (defined via `.audit([...])` on the endpoint builder)\n * are processed AFTER the handler returns, so they run outside this transaction.\n * If you need all audits to be atomic with your database operations, use manual\n * audits via `auditor.audit()` inside this wrapper.\n *\n * @param db - Database connection (Kysely, Transaction, or ControlledTransaction)\n * @param auditor - Auditor instance that will receive the transaction\n * @param cb - Callback to execute within the transaction\n * @param settings - Optional transaction settings (isolation level)\n * @returns The result of the callback\n *\n * @example\n * ```typescript\n * import { withAuditableTransaction } from '@geekmidas/audit/kysely';\n *\n * const result = await withAuditableTransaction(\n * services.database,\n * auditor,\n * async (trx) => {\n * const user = await trx\n * .insertInto('users')\n * .values(data)\n * .returningAll()\n * .executeTakeFirstOrThrow();\n *\n * // Manual audits are atomic with the transaction\n * auditor.audit('user.created', { userId: user.id, email: user.email });\n *\n * return user;\n * },\n * );\n * // Audits are automatically flushed inside the transaction before commit\n * ```\n */\nexport async function withAuditableTransaction<DB, T>(\n\tdb: DatabaseConnection<DB>,\n\tauditor: TransactionAwareAuditor<Transaction<DB>>,\n\tcb: (trx: Transaction<DB>) => Promise<T>,\n\tsettings?: TransactionSettings,\n): Promise<T> {\n\tconst execute = async (trx: Transaction<DB>): Promise<T> => {\n\t\t// Register transaction with auditor\n\t\tauditor.setTransaction(trx);\n\n\t\t// Execute the callback\n\t\tconst result = await cb(trx);\n\n\t\t// Flush audits BEFORE transaction commits\n\t\t// If this fails, the transaction will roll back\n\t\tawait auditor.flush(trx);\n\n\t\treturn result;\n\t};\n\n\t// If already in a transaction, just run with it\n\tif (db.isTransaction) {\n\t\treturn execute(db as Transaction<DB>);\n\t}\n\n\tconst builder = db.transaction();\n\n\tif (settings?.isolationLevel) {\n\t\treturn builder.setIsolationLevel(settings.isolationLevel).execute(execute);\n\t}\n\n\treturn builder.execute(execute);\n}\n\n/**\n * Database table interface for audit records.\n * Use this to define your audit_logs table in your Kysely database schema.\n *\n * Column names use snake_case to match standard PostgreSQL conventions.\n *\n * @example\n * ```typescript\n * interface Database {\n * audit_logs: AuditLogTable;\n * // ... other tables\n * }\n * ```\n */\nexport interface AuditLogTable {\n\tid: string;\n\ttype: string;\n\toperation: string;\n\ttable: string | null;\n\tentityId: string | null;\n\toldValues: unknown | null;\n\tnewValues: unknown | null;\n\tpayload: unknown | null;\n\ttimestamp: Date;\n\tactorId: string | null;\n\tactorType: string | null;\n\tactorData: unknown | null;\n\tmetadata: unknown | null;\n}\n\n/**\n * Insertable version of AuditLogTable where id is optional.\n * Use this when your database auto-generates IDs or when using autoId option.\n *\n * @example\n * ```typescript\n * interface Database {\n * audit_logs: AuditLogTable;\n * }\n *\n * // For insertions where id is auto-generated\n * type NewAuditLog = InsertableAuditLogTable;\n * ```\n */\nexport type InsertableAuditLogTable = Omit<AuditLogTable, 'id'> & {\n\tid?: string;\n};\n\n/**\n * Configuration for KyselyAuditStorage.\n */\nexport interface KyselyAuditStorageConfig<DB> {\n\t/** Kysely database instance */\n\tdb: Kysely<DB>;\n\t/** Table name for audit logs (must be a key in DB that extends AuditLogTable) */\n\ttableName: keyof DB & string;\n\t/**\n\t * Service name of the database service.\n\t * When set, endpoint adaptors will automatically use the audit transaction as `db`\n\t * in the handler context if the endpoint's database service has the same name.\n\t */\n\tdatabaseServiceName?: string;\n\t/**\n\t * Let the database auto-generate IDs (e.g., via DEFAULT gen_random_uuid()).\n\t * When true, the ID field is omitted from inserts if not provided.\n\t * When false (default), IDs are generated using nanoid if not provided.\n\t * @default false\n\t */\n\tautoId?: boolean;\n}\n\n/**\n * Kysely-based audit storage implementation.\n * Stores audit records in a database table using Kysely.\n *\n * @template DB - Your Kysely database schema\n *\n * @example\n * ```typescript\n * interface Database {\n * audit_logs: AuditLogTable;\n * }\n *\n * const storage = new KyselyAuditStorage({\n * db: kyselyDb,\n * tableName: 'audit_logs',\n * });\n *\n * const auditor = new DefaultAuditor({\n * actor: { id: 'user-123', type: 'user' },\n * storage,\n * });\n * ```\n */\nexport class KyselyAuditStorage<DB> implements AuditStorage {\n\tprivate readonly db: Kysely<DB>;\n\tprivate readonly tableName: keyof DB & string;\n\tprivate readonly autoId: boolean;\n\treadonly databaseServiceName?: string;\n\n\tconstructor(config: KyselyAuditStorageConfig<DB>) {\n\t\tthis.db = config.db;\n\t\tthis.tableName = config.tableName;\n\t\tthis.databaseServiceName = config.databaseServiceName;\n\t\tthis.autoId = config.autoId ?? false;\n\t}\n\n\tasync write(records: AuditRecord[], trx?: unknown): Promise<void> {\n\t\tif (records.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst db = (trx as Transaction<DB>) ?? this.db;\n\t\tconst rows = records.map((record) => this.toRow(record));\n\n\t\tawait (db as any).insertInto(this.tableName).values(rows).execute();\n\t}\n\n\tasync query(options: AuditQueryOptions): Promise<AuditRecord[]> {\n\t\tlet query = (this.db as any).selectFrom(this.tableName).selectAll();\n\n\t\tquery = this.applyFilters(query, options);\n\n\t\t// Ordering\n\t\tconst orderBy = options.orderBy ?? 'timestamp';\n\t\tconst orderDirection = options.orderDirection ?? 'desc';\n\t\tquery = query.orderBy(\n\t\t\torderBy === 'timestamp' ? 'timestamp' : 'type',\n\t\t\torderDirection,\n\t\t);\n\n\t\t// Pagination\n\t\tif (options.limit !== undefined) {\n\t\t\tquery = query.limit(options.limit);\n\t\t}\n\t\tif (options.offset !== undefined) {\n\t\t\tquery = query.offset(options.offset);\n\t\t}\n\n\t\tconst rows = await query.execute();\n\t\treturn rows.map((row: AuditLogTable) => this.fromRow(row));\n\t}\n\n\tasync count(\n\t\toptions: Omit<AuditQueryOptions, 'limit' | 'offset'>,\n\t): Promise<number> {\n\t\tlet query = (this.db as any)\n\t\t\t.selectFrom(this.tableName)\n\t\t\t.select((eb: any) => eb.fn.count('id').as('count'));\n\n\t\tquery = this.applyFilters(query, options);\n\n\t\tconst result = await query.executeTakeFirst();\n\t\treturn Number(result?.count ?? 0);\n\t}\n\n\t/**\n\t * Get the Kysely database instance for transactional operations.\n\t * Used by endpoint adaptors to automatically wrap handlers in transactions.\n\t */\n\tgetDatabase(): Kysely<DB> {\n\t\treturn this.db;\n\t}\n\n\t/**\n\t * Execute a callback within a Kysely transaction with automatic audit handling.\n\t * The auditor is registered with the transaction and audits are flushed\n\t * before the transaction commits.\n\t *\n\t * If the provided db connection is already a transaction, it will be reused\n\t * instead of creating a nested transaction.\n\t */\n\tasync withTransaction<T>(\n\t\tauditor: TransactionAwareAuditor<Transaction<DB>>,\n\t\tcallback: () => Promise<T>,\n\t\tdb?: DatabaseConnection<DB>,\n\t): Promise<T> {\n\t\tconst connection = db ?? this.db;\n\n\t\t// If already in a transaction, reuse it\n\t\tif (connection.isTransaction) {\n\t\t\tconst trx = connection as Transaction<DB>;\n\t\t\tauditor.setTransaction(trx);\n\t\t\tconst result = await callback();\n\t\t\tawait auditor.flush(trx);\n\t\t\treturn result;\n\t\t}\n\n\t\t// Create new transaction\n\t\treturn connection.transaction().execute(async (trx) => {\n\t\t\tauditor.setTransaction(trx);\n\t\t\tconst result = await callback();\n\t\t\tawait auditor.flush(trx);\n\t\t\treturn result;\n\t\t});\n\t}\n\n\tprivate applyFilters(query: any, options: AuditQueryOptions): any {\n\t\t// Type filter\n\t\tif (options.type !== undefined) {\n\t\t\tif (Array.isArray(options.type)) {\n\t\t\t\tquery = query.where('type', 'in', options.type);\n\t\t\t} else {\n\t\t\t\tquery = query.where('type', '=', options.type);\n\t\t\t}\n\t\t}\n\n\t\t// Entity ID filter\n\t\tif (options.entityId !== undefined) {\n\t\t\tconst entityId =\n\t\t\t\ttypeof options.entityId === 'string'\n\t\t\t\t\t? options.entityId\n\t\t\t\t\t: JSON.stringify(options.entityId);\n\t\t\tquery = query.where('entityId', '=', entityId);\n\t\t}\n\n\t\t// Table filter\n\t\tif (options.table !== undefined) {\n\t\t\tquery = query.where('table', '=', options.table);\n\t\t}\n\n\t\t// Actor ID filter\n\t\tif (options.actorId !== undefined) {\n\t\t\tquery = query.where('actorId', '=', options.actorId);\n\t\t}\n\n\t\t// Date range filters\n\t\tif (options.from !== undefined) {\n\t\t\tquery = query.where('timestamp', '>=', options.from);\n\t\t}\n\t\tif (options.to !== undefined) {\n\t\t\tquery = query.where('timestamp', '<=', options.to);\n\t\t}\n\n\t\treturn query;\n\t}\n\n\tprivate toRow(record: AuditRecord): AuditLogTable {\n\t\t// If autoId is true, let database generate ID (ignore record.id)\n\t\t// If autoId is false (default), use record.id or generate with nanoid\n\t\tconst id = this.autoId ? undefined : record.id || nanoid();\n\n\t\treturn {\n\t\t\t...(id && { id }),\n\t\t\ttype: record.type,\n\t\t\toperation: record.operation,\n\t\t\ttable: record.table ?? null,\n\t\t\tentityId:\n\t\t\t\trecord.entityId === undefined\n\t\t\t\t\t? null\n\t\t\t\t\t: typeof record.entityId === 'string'\n\t\t\t\t\t\t? record.entityId\n\t\t\t\t\t\t: JSON.stringify(record.entityId),\n\t\t\toldValues: record.oldValues ?? null,\n\t\t\tnewValues: record.newValues ?? null,\n\t\t\tpayload: record.payload ?? null,\n\t\t\ttimestamp: record.timestamp,\n\t\t\tactorId: record.actor?.id ?? null,\n\t\t\tactorType: record.actor?.type ?? null,\n\t\t\tactorData:\n\t\t\t\trecord.actor !== undefined ? this.getActorData(record.actor) : null,\n\t\t\tmetadata: record.metadata ?? null,\n\t\t} as AuditLogTable;\n\t}\n\n\tprivate fromRow(row: AuditLogTable): AuditRecord {\n\t\tconst actor =\n\t\t\trow.actorId !== null || row.actorType !== null\n\t\t\t\t? {\n\t\t\t\t\t\tid: row.actorId ?? undefined,\n\t\t\t\t\t\ttype: row.actorType ?? undefined,\n\t\t\t\t\t\t...(row.actorData ? this.parseJson(row.actorData) : {}),\n\t\t\t\t\t}\n\t\t\t\t: undefined;\n\n\t\treturn {\n\t\t\tid: row.id,\n\t\t\ttype: row.type,\n\t\t\toperation: row.operation as AuditRecord['operation'],\n\t\t\ttable: row.table ?? undefined,\n\t\t\tentityId: row.entityId ? this.parseEntityId(row.entityId) : undefined,\n\t\t\toldValues: row.oldValues ? this.parseJson(row.oldValues) : undefined,\n\t\t\tnewValues: row.newValues ? this.parseJson(row.newValues) : undefined,\n\t\t\tpayload: row.payload ? this.parseJson(row.payload) : undefined,\n\t\t\ttimestamp: row.timestamp,\n\t\t\tactor,\n\t\t\tmetadata: row.metadata ? this.parseJson(row.metadata) : undefined,\n\t\t};\n\t}\n\n\t/**\n\t * Parse a JSON value that may already be parsed (e.g., from jsonb columns).\n\t */\n\tprivate parseJson(value: unknown): Record<string, unknown> {\n\t\tif (typeof value === 'object' && value !== null) {\n\t\t\treturn value as Record<string, unknown>;\n\t\t}\n\t\tif (typeof value === 'string') {\n\t\t\treturn JSON.parse(value);\n\t\t}\n\t\treturn {};\n\t}\n\n\tprivate getActorData(\n\t\tactor: NonNullable<AuditRecord['actor']>,\n\t): Record<string, unknown> {\n\t\tconst { id, type, ...rest } = actor;\n\t\treturn rest;\n\t}\n\n\tprivate parseEntityId(entityId: string): string | Record<string, unknown> {\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(entityId);\n\t\t\tif (typeof parsed === 'object' && parsed !== null) {\n\t\t\t\treturn parsed;\n\t\t\t}\n\t\t\treturn entityId;\n\t\t} catch {\n\t\t\treturn entityId;\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoEA,eAAsB,yBACrB,IACA,SACA,IACA,UACa;CACb,MAAM,UAAU,OAAO,QAAqC;EAE3D,QAAQ,eAAe,GAAG;EAG1B,MAAM,SAAS,MAAM,GAAG,GAAG;EAI3B,MAAM,QAAQ,MAAM,GAAG;EAEvB,OAAO;CACR;CAGA,IAAI,GAAG,eACN,OAAO,QAAQ,EAAqB;CAGrC,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EACzD;CACD;;;;CAKA,UAAkB,OAAyC;EAC1D,IAAI,OAAO,UAAU,YAAY,UAAU,MAC1C,OAAO;EAER,IAAI,OAAO,UAAU,UACpB,OAAO,KAAK,MAAM,KAAK;EAExB,OAAO,CAAC;CACT;CAEA,aACC,OAC0B;EAC1B,MAAM,EAAE,IAAI,MAAM,GAAG,SAAS;EAC9B,OAAO;CACR;CAEA,cAAsB,UAAoD;EACzE,IAAI;GACH,MAAM,SAAS,KAAK,MAAM,QAAQ;GAClC,IAAI,OAAO,WAAW,YAAY,WAAW,MAC5C,OAAO;GAER,OAAO;EACR,QAAQ;GACP,OAAO;EACR;CACD;AACD"}
1
+ {"version":3,"file":"kysely.mjs","names":["db: DatabaseConnection<DB>","auditor: TransactionAwareAuditor<Transaction<DB>>","cb: (trx: Transaction<DB>) => Promise<T>","settings?: TransactionSettings","trx: Transaction<DB>","config: KyselyAuditStorageConfig<DB>","records: AuditRecord[]","trx?: unknown","options: AuditQueryOptions","row: AuditLogTable","options: Omit<AuditQueryOptions, 'limit' | 'offset'>","eb: any","callback: () => Promise<T>","db?: DatabaseConnection<DB>","query: any","record: AuditRecord","value: unknown","actor: NonNullable<AuditRecord['actor']>","entityId: string"],"sources":["../src/kysely.ts"],"sourcesContent":["import type {\n\tControlledTransaction,\n\tIsolationLevel,\n\tKysely,\n\tTransaction,\n} from 'kysely';\nimport { nanoid } from 'nanoid';\nimport type {\n\tAuditQueryOptions,\n\tAuditStorage,\n\tTransactionAwareAuditor,\n} from './storage';\nimport type { AuditRecord } from './types';\n\nexport type { TransactionAwareAuditor };\n\nexport interface TransactionSettings {\n\tisolationLevel?: IsolationLevel;\n}\n\nexport type DatabaseConnection<T> =\n\t| ControlledTransaction<T>\n\t| Kysely<T>\n\t| Transaction<T>;\n\n/**\n * Execute a callback within a database transaction with automatic audit handling.\n *\n * This wrapper ensures that:\n * 1. The transaction is automatically registered with the auditor\n * 2. Manual audits (via `auditor.audit()`) are flushed BEFORE the transaction commits\n * 3. If audit flush fails, the entire transaction rolls back\n * 4. If the callback fails, audits are NOT written (atomic consistency)\n *\n * **Note:** Declarative audits (defined via `.audit([...])` on the endpoint builder)\n * are processed AFTER the handler returns, so they run outside this transaction.\n * If you need all audits to be atomic with your database operations, use manual\n * audits via `auditor.audit()` inside this wrapper.\n *\n * @param db - Database connection (Kysely, Transaction, or ControlledTransaction)\n * @param auditor - Auditor instance that will receive the transaction\n * @param cb - Callback to execute within the transaction\n * @param settings - Optional transaction settings (isolation level)\n * @returns The result of the callback\n *\n * @example\n * ```typescript\n * import { withAuditableTransaction } from '@geekmidas/audit/kysely';\n *\n * const result = await withAuditableTransaction(\n * services.database,\n * auditor,\n * async (trx) => {\n * const user = await trx\n * .insertInto('users')\n * .values(data)\n * .returningAll()\n * .executeTakeFirstOrThrow();\n *\n * // Manual audits are atomic with the transaction\n * auditor.audit('user.created', { userId: user.id, email: user.email });\n *\n * return user;\n * },\n * );\n * // Audits are automatically flushed inside the transaction before commit\n * ```\n */\nexport async function withAuditableTransaction<DB, T>(\n\tdb: DatabaseConnection<DB>,\n\tauditor: TransactionAwareAuditor<Transaction<DB>>,\n\tcb: (trx: Transaction<DB>) => Promise<T>,\n\tsettings?: TransactionSettings,\n): Promise<T> {\n\tconst execute = async (trx: Transaction<DB>): Promise<T> => {\n\t\t// Register transaction with auditor\n\t\tauditor.setTransaction(trx);\n\n\t\t// Execute the callback\n\t\tconst result = await cb(trx);\n\n\t\t// Flush audits BEFORE transaction commits\n\t\t// If this fails, the transaction will roll back\n\t\tawait auditor.flush(trx);\n\n\t\treturn result;\n\t};\n\n\t// If already in a transaction, just run with it\n\tif (db.isTransaction) {\n\t\treturn execute(db as Transaction<DB>);\n\t}\n\n\tconst builder = db.transaction();\n\n\tif (settings?.isolationLevel) {\n\t\treturn builder.setIsolationLevel(settings.isolationLevel).execute(execute);\n\t}\n\n\treturn builder.execute(execute);\n}\n\n/**\n * Database table interface for audit records.\n * Use this to define your audit_logs table in your Kysely database schema.\n *\n * Column names use snake_case to match standard PostgreSQL conventions.\n *\n * @example\n * ```typescript\n * interface Database {\n * audit_logs: AuditLogTable;\n * // ... other tables\n * }\n * ```\n */\nexport interface AuditLogTable {\n\tid: string;\n\ttype: string;\n\toperation: string;\n\ttable: string | null;\n\tentityId: string | null;\n\toldValues: unknown | null;\n\tnewValues: unknown | null;\n\tpayload: unknown | null;\n\ttimestamp: Date;\n\tactorId: string | null;\n\tactorType: string | null;\n\tactorData: unknown | null;\n\tmetadata: unknown | null;\n}\n\n/**\n * Insertable version of AuditLogTable where id is optional.\n * Use this when your database auto-generates IDs or when using autoId option.\n *\n * @example\n * ```typescript\n * interface Database {\n * audit_logs: AuditLogTable;\n * }\n *\n * // For insertions where id is auto-generated\n * type NewAuditLog = InsertableAuditLogTable;\n * ```\n */\nexport type InsertableAuditLogTable = Omit<AuditLogTable, 'id'> & {\n\tid?: string;\n};\n\n/**\n * Configuration for KyselyAuditStorage.\n */\nexport interface KyselyAuditStorageConfig<DB> {\n\t/** Kysely database instance */\n\tdb: Kysely<DB>;\n\t/** Table name for audit logs (must be a key in DB that extends AuditLogTable) */\n\ttableName: keyof DB & string;\n\t/**\n\t * Service name of the database service.\n\t * When set, endpoint adaptors will automatically use the audit transaction as `db`\n\t * in the handler context if the endpoint's database service has the same name.\n\t */\n\tdatabaseServiceName?: string;\n\t/**\n\t * Let the database auto-generate IDs (e.g., via DEFAULT gen_random_uuid()).\n\t * When true, the ID field is omitted from inserts if not provided.\n\t * When false (default), IDs are generated using nanoid if not provided.\n\t * @default false\n\t */\n\tautoId?: boolean;\n}\n\n/**\n * Kysely-based audit storage implementation.\n * Stores audit records in a database table using Kysely.\n *\n * @template DB - Your Kysely database schema\n *\n * @example\n * ```typescript\n * interface Database {\n * audit_logs: AuditLogTable;\n * }\n *\n * const storage = new KyselyAuditStorage({\n * db: kyselyDb,\n * tableName: 'audit_logs',\n * });\n *\n * const auditor = new DefaultAuditor({\n * actor: { id: 'user-123', type: 'user' },\n * storage,\n * });\n * ```\n */\nexport class KyselyAuditStorage<DB> implements AuditStorage {\n\tprivate readonly db: Kysely<DB>;\n\tprivate readonly tableName: keyof DB & string;\n\tprivate readonly autoId: boolean;\n\treadonly databaseServiceName?: string;\n\n\tconstructor(config: KyselyAuditStorageConfig<DB>) {\n\t\tthis.db = config.db;\n\t\tthis.tableName = config.tableName;\n\t\tthis.databaseServiceName = config.databaseServiceName;\n\t\tthis.autoId = config.autoId ?? false;\n\t}\n\n\tasync write(records: AuditRecord[], trx?: unknown): Promise<void> {\n\t\tif (records.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst db = (trx as Transaction<DB>) ?? this.db;\n\t\tconst rows = records.map((record) => this.toRow(record));\n\n\t\tawait (db as any).insertInto(this.tableName).values(rows).execute();\n\t}\n\n\tasync query(options: AuditQueryOptions): Promise<AuditRecord[]> {\n\t\tlet query = (this.db as any).selectFrom(this.tableName).selectAll();\n\n\t\tquery = this.applyFilters(query, options);\n\n\t\t// Ordering\n\t\tconst orderBy = options.orderBy ?? 'timestamp';\n\t\tconst orderDirection = options.orderDirection ?? 'desc';\n\t\tquery = query.orderBy(\n\t\t\torderBy === 'timestamp' ? 'timestamp' : 'type',\n\t\t\torderDirection,\n\t\t);\n\n\t\t// Pagination\n\t\tif (options.limit !== undefined) {\n\t\t\tquery = query.limit(options.limit);\n\t\t}\n\t\tif (options.offset !== undefined) {\n\t\t\tquery = query.offset(options.offset);\n\t\t}\n\n\t\tconst rows = await query.execute();\n\t\treturn rows.map((row: AuditLogTable) => this.fromRow(row));\n\t}\n\n\tasync count(\n\t\toptions: Omit<AuditQueryOptions, 'limit' | 'offset'>,\n\t): Promise<number> {\n\t\tlet query = (this.db as any)\n\t\t\t.selectFrom(this.tableName)\n\t\t\t.select((eb: any) => eb.fn.count('id').as('count'));\n\n\t\tquery = this.applyFilters(query, options);\n\n\t\tconst result = await query.executeTakeFirst();\n\t\treturn Number(result?.count ?? 0);\n\t}\n\n\t/**\n\t * Get the Kysely database instance for transactional operations.\n\t * Used by endpoint adaptors to automatically wrap handlers in transactions.\n\t */\n\tgetDatabase(): Kysely<DB> {\n\t\treturn this.db;\n\t}\n\n\t/**\n\t * Execute a callback within a Kysely transaction with automatic audit handling.\n\t * The auditor is registered with the transaction and audits are flushed\n\t * before the transaction commits.\n\t *\n\t * If the provided db connection is already a transaction, it will be reused\n\t * instead of creating a nested transaction.\n\t */\n\tasync withTransaction<T>(\n\t\tauditor: TransactionAwareAuditor<Transaction<DB>>,\n\t\tcallback: () => Promise<T>,\n\t\tdb?: DatabaseConnection<DB>,\n\t): Promise<T> {\n\t\tconst connection = db ?? this.db;\n\n\t\t// If already in a transaction, reuse it\n\t\tif (connection.isTransaction) {\n\t\t\tconst trx = connection as Transaction<DB>;\n\t\t\tauditor.setTransaction(trx);\n\t\t\tconst result = await callback();\n\t\t\tawait auditor.flush(trx);\n\t\t\treturn result;\n\t\t}\n\n\t\t// Create new transaction\n\t\treturn connection.transaction().execute(async (trx) => {\n\t\t\tauditor.setTransaction(trx);\n\t\t\tconst result = await callback();\n\t\t\tawait auditor.flush(trx);\n\t\t\treturn result;\n\t\t});\n\t}\n\n\tprivate applyFilters(query: any, options: AuditQueryOptions): any {\n\t\t// Type filter\n\t\tif (options.type !== undefined) {\n\t\t\tif (Array.isArray(options.type)) {\n\t\t\t\tquery = query.where('type', 'in', options.type);\n\t\t\t} else {\n\t\t\t\tquery = query.where('type', '=', options.type);\n\t\t\t}\n\t\t}\n\n\t\t// Entity ID filter\n\t\tif (options.entityId !== undefined) {\n\t\t\tconst entityId =\n\t\t\t\ttypeof options.entityId === 'string'\n\t\t\t\t\t? options.entityId\n\t\t\t\t\t: JSON.stringify(options.entityId);\n\t\t\tquery = query.where('entityId', '=', entityId);\n\t\t}\n\n\t\t// Table filter\n\t\tif (options.table !== undefined) {\n\t\t\tquery = query.where('table', '=', options.table);\n\t\t}\n\n\t\t// Actor ID filter\n\t\tif (options.actorId !== undefined) {\n\t\t\tquery = query.where('actorId', '=', options.actorId);\n\t\t}\n\n\t\t// Date range filters\n\t\tif (options.from !== undefined) {\n\t\t\tquery = query.where('timestamp', '>=', options.from);\n\t\t}\n\t\tif (options.to !== undefined) {\n\t\t\tquery = query.where('timestamp', '<=', options.to);\n\t\t}\n\n\t\treturn query;\n\t}\n\n\tprivate toRow(record: AuditRecord): AuditLogTable {\n\t\t// If autoId is true, let database generate ID (ignore record.id)\n\t\t// If autoId is false (default), use record.id or generate with nanoid\n\t\tconst id = this.autoId ? undefined : record.id || nanoid();\n\n\t\treturn {\n\t\t\t...(id && { id }),\n\t\t\ttype: record.type,\n\t\t\toperation: record.operation,\n\t\t\ttable: record.table ?? null,\n\t\t\tentityId:\n\t\t\t\trecord.entityId === undefined\n\t\t\t\t\t? null\n\t\t\t\t\t: typeof record.entityId === 'string'\n\t\t\t\t\t\t? record.entityId\n\t\t\t\t\t\t: JSON.stringify(record.entityId),\n\t\t\toldValues: record.oldValues ?? null,\n\t\t\tnewValues: record.newValues ?? null,\n\t\t\tpayload: record.payload ?? null,\n\t\t\ttimestamp: record.timestamp,\n\t\t\tactorId: record.actor?.id ?? null,\n\t\t\tactorType: record.actor?.type ?? null,\n\t\t\tactorData:\n\t\t\t\trecord.actor !== undefined ? this.getActorData(record.actor) : null,\n\t\t\tmetadata: record.metadata ?? null,\n\t\t} as AuditLogTable;\n\t}\n\n\tprivate fromRow(row: AuditLogTable): AuditRecord {\n\t\tconst actor =\n\t\t\trow.actorId !== null || row.actorType !== null\n\t\t\t\t? {\n\t\t\t\t\t\tid: row.actorId ?? undefined,\n\t\t\t\t\t\ttype: row.actorType ?? undefined,\n\t\t\t\t\t\t...(row.actorData ? this.parseJson(row.actorData) : {}),\n\t\t\t\t\t}\n\t\t\t\t: undefined;\n\n\t\treturn {\n\t\t\tid: row.id,\n\t\t\ttype: row.type,\n\t\t\toperation: row.operation as AuditRecord['operation'],\n\t\t\ttable: row.table ?? undefined,\n\t\t\tentityId: row.entityId ? this.parseEntityId(row.entityId) : undefined,\n\t\t\toldValues: row.oldValues ? this.parseJson(row.oldValues) : undefined,\n\t\t\tnewValues: row.newValues ? this.parseJson(row.newValues) : undefined,\n\t\t\tpayload: row.payload ? this.parseJson(row.payload) : undefined,\n\t\t\ttimestamp: row.timestamp,\n\t\t\tactor,\n\t\t\tmetadata: row.metadata ? this.parseJson(row.metadata) : undefined,\n\t\t};\n\t}\n\n\t/**\n\t * Parse a JSON value that may already be parsed (e.g., from jsonb columns).\n\t */\n\tprivate parseJson(value: unknown): Record<string, unknown> {\n\t\tif (typeof value === 'object' && value !== null) {\n\t\t\treturn value as Record<string, unknown>;\n\t\t}\n\t\tif (typeof value === 'string') {\n\t\t\treturn JSON.parse(value);\n\t\t}\n\t\treturn {};\n\t}\n\n\tprivate getActorData(\n\t\tactor: NonNullable<AuditRecord['actor']>,\n\t): Record<string, unknown> {\n\t\tconst { id, type, ...rest } = actor;\n\t\treturn rest;\n\t}\n\n\tprivate parseEntityId(entityId: string): string | Record<string, unknown> {\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(entityId);\n\t\t\tif (typeof parsed === 'object' && parsed !== null) {\n\t\t\t\treturn parsed;\n\t\t\t}\n\t\t\treturn entityId;\n\t\t} catch {\n\t\t\treturn entityId;\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoEA,eAAsB,yBACrBA,IACAC,SACAC,IACAC,UACa;CACb,MAAM,UAAU,OAAOC,QAAqC;AAE3D,UAAQ,eAAe,IAAI;EAG3B,MAAM,SAAS,MAAM,GAAG,IAAI;AAI5B,QAAM,QAAQ,MAAM,IAAI;AAExB,SAAO;CACP;AAGD,KAAI,GAAG,cACN,QAAO,QAAQ,GAAsB;CAGtC,MAAM,UAAU,GAAG,aAAa;AAEhC,KAAI,UAAU,eACb,QAAO,QAAQ,kBAAkB,SAAS,eAAe,CAAC,QAAQ,QAAQ;AAG3E,QAAO,QAAQ,QAAQ,QAAQ;AAC/B;;;;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YAAY,WAAW,KAC5C,QAAO;AAER,UAAO;EACP,QAAO;AACP,UAAO;EACP;CACD;AACD"}
package/dist/memory.cjs CHANGED
@@ -1,6 +1,7 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_cache = require("./cache.cjs");
3
- let _geekmidas_cache_memory = require("@geekmidas/cache/memory");
1
+ const require_chunk = require('./chunk-CUT6urMc.cjs');
2
+ const require_cache = require('./cache-l7jAptBl.cjs');
3
+ const __geekmidas_cache_memory = require_chunk.__toESM(require("@geekmidas/cache/memory"));
4
+
4
5
  //#region src/memory.ts
5
6
  /**
6
7
  * In-memory audit storage implementation.
@@ -37,12 +38,12 @@ let _geekmidas_cache_memory = require("@geekmidas/cache/memory");
37
38
  var InMemoryAuditStorage = class extends require_cache.CacheAuditStorage {
38
39
  constructor() {
39
40
  super({
40
- cache: new _geekmidas_cache_memory.InMemoryCache(),
41
- ttl: 31536e3
41
+ cache: new __geekmidas_cache_memory.InMemoryCache(),
42
+ ttl: 86400 * 365
42
43
  });
43
44
  }
44
45
  };
46
+
45
47
  //#endregion
46
48
  exports.InMemoryAuditStorage = InMemoryAuditStorage;
47
-
48
49
  //# sourceMappingURL=memory.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"memory.cjs","names":["CacheAuditStorage","InMemoryCache"],"sources":["../src/memory.ts"],"sourcesContent":["import { InMemoryCache } from '@geekmidas/cache/memory';\nimport { CacheAuditStorage } from './cache';\nimport type { AuditableAction } from './types';\n\n/**\n * In-memory audit storage implementation.\n * Convenience wrapper around CacheAuditStorage with InMemoryCache.\n *\n * Useful for testing, development, and applications that don't need persistent audit logs.\n *\n * @template TAuditAction - Optional type parameter for type-safe audit actions.\n *\n * @example\n * ```typescript\n * import { InMemoryAuditStorage } from '@geekmidas/audit/memory';\n * import { DefaultAuditor } from '@geekmidas/audit';\n *\n * const storage = new InMemoryAuditStorage();\n * const auditor = new DefaultAuditor({\n * actor: { id: 'user-123', type: 'user' },\n * storage,\n * });\n *\n * auditor.audit('user.created', { userId: '789', email: 'test@example.com' });\n * await auditor.flush();\n *\n * // Query stored records\n * const records = await storage.query({ type: 'user.created' });\n *\n * // Get all records (for testing)\n * const all = await storage.getRecords();\n *\n * // Clear for next test\n * await storage.clear();\n * ```\n */\nexport class InMemoryAuditStorage<\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n> extends CacheAuditStorage<TAuditAction> {\n\tconstructor() {\n\t\tsuper({\n\t\t\tcache: new InMemoryCache(),\n\t\t\t// Use a long TTL since in-memory cache expires items\n\t\t\tttl: 86400 * 365, // 1 year\n\t\t});\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,IAAa,uBAAb,cAKUA,cAAAA,kBAAgC;CACzC,cAAc;EACb,MAAM;GACL,OAAO,IAAIC,wBAAAA,cAAc;GAEzB,KAAK;EACN,CAAC;CACF;AACD"}
1
+ {"version":3,"file":"memory.cjs","names":["CacheAuditStorage","InMemoryCache"],"sources":["../src/memory.ts"],"sourcesContent":["import { InMemoryCache } from '@geekmidas/cache/memory';\nimport { CacheAuditStorage } from './cache';\nimport type { AuditableAction } from './types';\n\n/**\n * In-memory audit storage implementation.\n * Convenience wrapper around CacheAuditStorage with InMemoryCache.\n *\n * Useful for testing, development, and applications that don't need persistent audit logs.\n *\n * @template TAuditAction - Optional type parameter for type-safe audit actions.\n *\n * @example\n * ```typescript\n * import { InMemoryAuditStorage } from '@geekmidas/audit/memory';\n * import { DefaultAuditor } from '@geekmidas/audit';\n *\n * const storage = new InMemoryAuditStorage();\n * const auditor = new DefaultAuditor({\n * actor: { id: 'user-123', type: 'user' },\n * storage,\n * });\n *\n * auditor.audit('user.created', { userId: '789', email: 'test@example.com' });\n * await auditor.flush();\n *\n * // Query stored records\n * const records = await storage.query({ type: 'user.created' });\n *\n * // Get all records (for testing)\n * const all = await storage.getRecords();\n *\n * // Clear for next test\n * await storage.clear();\n * ```\n */\nexport class InMemoryAuditStorage<\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n> extends CacheAuditStorage<TAuditAction> {\n\tconstructor() {\n\t\tsuper({\n\t\t\tcache: new InMemoryCache(),\n\t\t\t// Use a long TTL since in-memory cache expires items\n\t\t\tttl: 86400 * 365, // 1 year\n\t\t});\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,IAAa,uBAAb,cAKUA,gCAAgC;CACzC,cAAc;AACb,QAAM;GACL,OAAO,IAAIC;GAEX,KAAK,QAAQ;EACb,EAAC;CACF;AACD"}
package/dist/memory.d.cts CHANGED
@@ -1,6 +1,8 @@
1
- import { s as AuditableAction } from "./Auditor-BBXXCD0v.cjs";
2
- import { CacheAuditStorage } from "./cache.cjs";
1
+ import { AuditableAction } from "./Auditor-DpBHXIJM.cjs";
2
+ import { CacheAuditStorage } from "./cache-Bih6HxY6.cjs";
3
+
3
4
  //#region src/memory.d.ts
5
+
4
6
  /**
5
7
  * In-memory audit storage implementation.
6
8
  * Convenience wrapper around CacheAuditStorage with InMemoryCache.
@@ -33,8 +35,10 @@ import { CacheAuditStorage } from "./cache.cjs";
33
35
  * await storage.clear();
34
36
  * ```
35
37
  */
36
- export declare class InMemoryAuditStorage<TAuditAction extends AuditableAction<string, unknown> = AuditableAction<string, unknown>> extends CacheAuditStorage<TAuditAction> {
38
+ declare class InMemoryAuditStorage<TAuditAction extends AuditableAction<string, unknown> = AuditableAction<string, unknown>> extends CacheAuditStorage<TAuditAction> {
37
39
  constructor();
38
40
  }
41
+ //# sourceMappingURL=memory.d.ts.map
39
42
  //#endregion
43
+ export { InMemoryAuditStorage };
40
44
  //# sourceMappingURL=memory.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"memory.d.cts","names":[],"sources":["../src/memory.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAoCa,qBACZ,qBAAqB,mCAAmC,0CAI/C,kBAAkB;EAC3B"}
1
+ {"version":3,"file":"memory.d.cts","names":[],"sources":["../src/memory.ts"],"sourcesContent":[],"mappings":";;;;;;;AAoCA;;;;;;AAK2B;;;;;;;;;;;;;;;;;;;;;;;;cALd,0CACS,mCAAmC,0CAI/C,kBAAkB"}
package/dist/memory.d.mts CHANGED
@@ -1,6 +1,8 @@
1
- import { s as AuditableAction } from "./Auditor-BBXXCD0v.mjs";
2
- import { CacheAuditStorage } from "./cache.mjs";
1
+ import { AuditableAction } from "./Auditor-CW2NrfHS.mjs";
2
+ import { CacheAuditStorage } from "./cache-wET57t6d.mjs";
3
+
3
4
  //#region src/memory.d.ts
5
+
4
6
  /**
5
7
  * In-memory audit storage implementation.
6
8
  * Convenience wrapper around CacheAuditStorage with InMemoryCache.
@@ -33,8 +35,10 @@ import { CacheAuditStorage } from "./cache.mjs";
33
35
  * await storage.clear();
34
36
  * ```
35
37
  */
36
- export declare class InMemoryAuditStorage<TAuditAction extends AuditableAction<string, unknown> = AuditableAction<string, unknown>> extends CacheAuditStorage<TAuditAction> {
38
+ declare class InMemoryAuditStorage<TAuditAction extends AuditableAction<string, unknown> = AuditableAction<string, unknown>> extends CacheAuditStorage<TAuditAction> {
37
39
  constructor();
38
40
  }
41
+ //# sourceMappingURL=memory.d.ts.map
39
42
  //#endregion
43
+ export { InMemoryAuditStorage };
40
44
  //# sourceMappingURL=memory.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"memory.d.mts","names":[],"sources":["../src/memory.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAoCa,qBACZ,qBAAqB,mCAAmC,0CAI/C,kBAAkB;EAC3B"}
1
+ {"version":3,"file":"memory.d.mts","names":[],"sources":["../src/memory.ts"],"sourcesContent":[],"mappings":";;;;;;;AAoCA;;;;;;AAK2B;;;;;;;;;;;;;;;;;;;;;;;;cALd,0CACS,mCAAmC,0CAI/C,kBAAkB"}
package/dist/memory.mjs CHANGED
@@ -1,5 +1,6 @@
1
- import { CacheAuditStorage } from "./cache.mjs";
1
+ import { CacheAuditStorage } from "./cache-BbIl31RL.mjs";
2
2
  import { InMemoryCache } from "@geekmidas/cache/memory";
3
+
3
4
  //#region src/memory.ts
4
5
  /**
5
6
  * In-memory audit storage implementation.
@@ -37,11 +38,11 @@ var InMemoryAuditStorage = class extends CacheAuditStorage {
37
38
  constructor() {
38
39
  super({
39
40
  cache: new InMemoryCache(),
40
- ttl: 31536e3
41
+ ttl: 86400 * 365
41
42
  });
42
43
  }
43
44
  };
45
+
44
46
  //#endregion
45
47
  export { InMemoryAuditStorage };
46
-
47
48
  //# sourceMappingURL=memory.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"memory.mjs","names":[],"sources":["../src/memory.ts"],"sourcesContent":["import { InMemoryCache } from '@geekmidas/cache/memory';\nimport { CacheAuditStorage } from './cache';\nimport type { AuditableAction } from './types';\n\n/**\n * In-memory audit storage implementation.\n * Convenience wrapper around CacheAuditStorage with InMemoryCache.\n *\n * Useful for testing, development, and applications that don't need persistent audit logs.\n *\n * @template TAuditAction - Optional type parameter for type-safe audit actions.\n *\n * @example\n * ```typescript\n * import { InMemoryAuditStorage } from '@geekmidas/audit/memory';\n * import { DefaultAuditor } from '@geekmidas/audit';\n *\n * const storage = new InMemoryAuditStorage();\n * const auditor = new DefaultAuditor({\n * actor: { id: 'user-123', type: 'user' },\n * storage,\n * });\n *\n * auditor.audit('user.created', { userId: '789', email: 'test@example.com' });\n * await auditor.flush();\n *\n * // Query stored records\n * const records = await storage.query({ type: 'user.created' });\n *\n * // Get all records (for testing)\n * const all = await storage.getRecords();\n *\n * // Clear for next test\n * await storage.clear();\n * ```\n */\nexport class InMemoryAuditStorage<\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n> extends CacheAuditStorage<TAuditAction> {\n\tconstructor() {\n\t\tsuper({\n\t\t\tcache: new InMemoryCache(),\n\t\t\t// Use a long TTL since in-memory cache expires items\n\t\t\tttl: 86400 * 365, // 1 year\n\t\t});\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,IAAa,uBAAb,cAKU,kBAAgC;CACzC,cAAc;EACb,MAAM;GACL,OAAO,IAAI,cAAc;GAEzB,KAAK;EACN,CAAC;CACF;AACD"}
1
+ {"version":3,"file":"memory.mjs","names":[],"sources":["../src/memory.ts"],"sourcesContent":["import { InMemoryCache } from '@geekmidas/cache/memory';\nimport { CacheAuditStorage } from './cache';\nimport type { AuditableAction } from './types';\n\n/**\n * In-memory audit storage implementation.\n * Convenience wrapper around CacheAuditStorage with InMemoryCache.\n *\n * Useful for testing, development, and applications that don't need persistent audit logs.\n *\n * @template TAuditAction - Optional type parameter for type-safe audit actions.\n *\n * @example\n * ```typescript\n * import { InMemoryAuditStorage } from '@geekmidas/audit/memory';\n * import { DefaultAuditor } from '@geekmidas/audit';\n *\n * const storage = new InMemoryAuditStorage();\n * const auditor = new DefaultAuditor({\n * actor: { id: 'user-123', type: 'user' },\n * storage,\n * });\n *\n * auditor.audit('user.created', { userId: '789', email: 'test@example.com' });\n * await auditor.flush();\n *\n * // Query stored records\n * const records = await storage.query({ type: 'user.created' });\n *\n * // Get all records (for testing)\n * const all = await storage.getRecords();\n *\n * // Clear for next test\n * await storage.clear();\n * ```\n */\nexport class InMemoryAuditStorage<\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n> extends CacheAuditStorage<TAuditAction> {\n\tconstructor() {\n\t\tsuper({\n\t\t\tcache: new InMemoryCache(),\n\t\t\t// Use a long TTL since in-memory cache expires items\n\t\t\tttl: 86400 * 365, // 1 year\n\t\t});\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,IAAa,uBAAb,cAKU,kBAAgC;CACzC,cAAc;AACb,QAAM;GACL,OAAO,IAAI;GAEX,KAAK,QAAQ;EACb,EAAC;CACF;AACD"}
@@ -1,2 +1,2 @@
1
- import { h as TransactionAwareAuditor, m as AuditStorage, p as AuditQueryOptions } from "./Auditor-BBXXCD0v.cjs";
1
+ import { AuditQueryOptions, AuditStorage, TransactionAwareAuditor } from "./Auditor-DpBHXIJM.cjs";
2
2
  export { AuditQueryOptions, AuditStorage, TransactionAwareAuditor };
@@ -1,2 +1,2 @@
1
- import { h as TransactionAwareAuditor, m as AuditStorage, p as AuditQueryOptions } from "./Auditor-BBXXCD0v.mjs";
1
+ import { AuditQueryOptions, AuditStorage, TransactionAwareAuditor } from "./Auditor-CW2NrfHS.mjs";
2
2
  export { AuditQueryOptions, AuditStorage, TransactionAwareAuditor };
package/dist/storage.mjs CHANGED
@@ -1 +0,0 @@
1
- export {};
package/dist/types.d.cts CHANGED
@@ -1,2 +1,2 @@
1
- import { a as AuditOptions, c as ExtractAuditPayload, d as ExtractStorageAuditAction, f as MappedAudit, i as AuditOperation, l as ExtractAuditType, n as AuditActor, o as AuditRecord, r as AuditMetadata, s as AuditableAction, u as ExtractAuditorAction } from "./Auditor-BBXXCD0v.cjs";
1
+ import { AuditActor, AuditMetadata, AuditOperation, AuditOptions, AuditRecord, AuditableAction, ExtractAuditPayload, ExtractAuditType, ExtractAuditorAction, ExtractStorageAuditAction, MappedAudit } from "./Auditor-DpBHXIJM.cjs";
2
2
  export { AuditActor, AuditMetadata, AuditOperation, AuditOptions, AuditRecord, AuditableAction, ExtractAuditPayload, ExtractAuditType, ExtractAuditorAction, ExtractStorageAuditAction, MappedAudit };
package/dist/types.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { a as AuditOptions, c as ExtractAuditPayload, d as ExtractStorageAuditAction, f as MappedAudit, i as AuditOperation, l as ExtractAuditType, n as AuditActor, o as AuditRecord, r as AuditMetadata, s as AuditableAction, u as ExtractAuditorAction } from "./Auditor-BBXXCD0v.mjs";
1
+ import { AuditActor, AuditMetadata, AuditOperation, AuditOptions, AuditRecord, AuditableAction, ExtractAuditPayload, ExtractAuditType, ExtractAuditorAction, ExtractStorageAuditAction, MappedAudit } from "./Auditor-CW2NrfHS.mjs";
2
2
  export { AuditActor, AuditMetadata, AuditOperation, AuditOptions, AuditRecord, AuditableAction, ExtractAuditPayload, ExtractAuditType, ExtractAuditorAction, ExtractStorageAuditAction, MappedAudit };
package/dist/types.mjs CHANGED
@@ -1 +0,0 @@
1
- export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geekmidas/audit",
3
- "version": "10.0.0-alpha.99",
3
+ "version": "10.0.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -54,9 +54,6 @@
54
54
  }
55
55
  }
56
56
  },
57
- "files": [
58
- "dist"
59
- ],
60
57
  "repository": {
61
58
  "type": "git",
62
59
  "url": "https://github.com/geekmidas/toolbox"
@@ -66,14 +63,14 @@
66
63
  "access": "public"
67
64
  },
68
65
  "dependencies": {
69
- "@standard-schema/spec": "~1.1.0",
70
- "nanoid": "~6.0.1"
66
+ "@standard-schema/spec": "~1.0.0",
67
+ "nanoid": "~5.1.5"
71
68
  },
72
69
  "peerDependencies": {
73
- "kysely": "~0.29.6",
74
- "knex": ">=3.3.0",
75
- "@geekmidas/cache": "^10.0.0-alpha.99",
76
- "@geekmidas/schema": "^10.0.0-alpha.99"
70
+ "kysely": ">=0.28.2 <0.30.0",
71
+ "knex": ">=3.0.0 <4.0.0",
72
+ "@geekmidas/cache": "^10.0.0",
73
+ "@geekmidas/schema": "^10.0.0"
77
74
  },
78
75
  "peerDependenciesMeta": {
79
76
  "@geekmidas/cache": {
@@ -90,14 +87,11 @@
90
87
  }
91
88
  },
92
89
  "devDependencies": {
93
- "kysely": "~0.29.6",
94
- "pg": "~8.23.0",
95
- "@types/pg": "~8.23.1",
96
- "knex": "~3.3.0",
97
- "@geekmidas/cache": "^10.0.0-alpha.99",
98
- "@geekmidas/schema": "^10.0.0-alpha.99"
99
- },
100
- "scripts": {
101
- "build": "tsdown --config ../../tsdown.config.ts --filter ."
90
+ "kysely": "~0.29.4",
91
+ "pg": "~8.16.0",
92
+ "@types/pg": "~8.15.6",
93
+ "knex": "~3.1.0",
94
+ "@geekmidas/cache": "^10.0.0",
95
+ "@geekmidas/schema": "^10.0.0"
102
96
  }
103
97
  }
package/src/Auditor.ts ADDED
@@ -0,0 +1,157 @@
1
+ import type {
2
+ AuditActor,
3
+ AuditableAction,
4
+ AuditMetadata,
5
+ AuditOptions,
6
+ AuditRecord,
7
+ ExtractAuditPayload,
8
+ ExtractAuditType,
9
+ } from './types';
10
+
11
+ /**
12
+ * Interface for audit collection and flushing.
13
+ * Generic over audit action types for full type safety.
14
+ *
15
+ * @template TAuditAction - Union of all allowed audit action types
16
+ * @template TTransaction - Transaction type (e.g., Kysely Transaction)
17
+ *
18
+ * @example
19
+ * ```typescript
20
+ * type AppAuditAction =
21
+ * | AuditableAction<'user.created', { userId: string; email: string }>
22
+ * | AuditableAction<'user.updated', { userId: string; changes: string[] }>;
23
+ *
24
+ * // In endpoint handler
25
+ * const auditor: Auditor<AppAuditAction> = ...;
26
+ *
27
+ * // Type-safe audit calls
28
+ * auditor.audit('user.created', { userId: '123', email: 'test@example.com' }); // ✅
29
+ * auditor.audit('user.created', { orderId: '123' }); // ❌ Type error
30
+ * auditor.audit('unknown.type', {}); // ❌ Type error
31
+ * ```
32
+ */
33
+ export interface Auditor<
34
+ TAuditAction extends AuditableAction<string, unknown> = AuditableAction<
35
+ string,
36
+ unknown
37
+ >,
38
+ TTransaction = unknown,
39
+ > {
40
+ /**
41
+ * The actor for all audits in this context.
42
+ * Set at construction time, immutable throughout the request.
43
+ */
44
+ readonly actor: AuditActor;
45
+
46
+ /**
47
+ * Record a type-safe audit entry.
48
+ * The payload type is inferred from the audit type.
49
+ *
50
+ * @param type - The audit type (must be a valid type from TAuditAction)
51
+ * @param payload - The audit payload (shape enforced by type)
52
+ * @param options - Optional audit metadata
53
+ *
54
+ * @example
55
+ * ```typescript
56
+ * auditor.audit('user.created', {
57
+ * userId: '123',
58
+ * email: 'test@example.com',
59
+ * });
60
+ *
61
+ * auditor.audit('order.placed', {
62
+ * orderId: 'order-456',
63
+ * total: 99.99,
64
+ * }, {
65
+ * entityId: 'order-456',
66
+ * table: 'orders',
67
+ * });
68
+ * ```
69
+ */
70
+ audit<TType extends ExtractAuditType<TAuditAction>>(
71
+ type: TType,
72
+ payload: ExtractAuditPayload<TAuditAction, TType>,
73
+ options?: AuditOptions,
74
+ ): void;
75
+
76
+ /**
77
+ * Record a raw audit record.
78
+ * Use this when you need full control over the audit structure,
79
+ * bypassing type safety.
80
+ *
81
+ * @param record - The audit record (id, timestamp, actor added automatically)
82
+ */
83
+ record(record: Omit<AuditRecord, 'id' | 'timestamp' | 'actor'>): void;
84
+
85
+ /**
86
+ * Get all collected audit records.
87
+ * Useful for inspection or custom processing.
88
+ */
89
+ getRecords(): AuditRecord[];
90
+
91
+ /**
92
+ * Flush all collected audits to storage.
93
+ * Called automatically by the endpoint adaptor inside the transaction.
94
+ *
95
+ * @param trx - Optional transaction context for atomic writes
96
+ */
97
+ flush(trx?: TTransaction): Promise<void>;
98
+
99
+ /**
100
+ * Clear all collected audit records without flushing.
101
+ * Use with caution - collected audits will be lost.
102
+ */
103
+ clear(): void;
104
+
105
+ /**
106
+ * Add metadata to all future audit records.
107
+ * Merges with existing metadata (new values override existing).
108
+ * Typically called by adaptors to add request context.
109
+ *
110
+ * @param metadata - Metadata to add (requestId, endpoint, method, ip, etc.)
111
+ *
112
+ * @example
113
+ * ```typescript
114
+ * // In endpoint adaptor
115
+ * auditor.addMetadata({
116
+ * requestId: 'req-123',
117
+ * endpoint: '/users',
118
+ * method: 'POST',
119
+ * ip: '192.168.1.1',
120
+ * });
121
+ * ```
122
+ */
123
+ addMetadata(metadata: AuditMetadata): void;
124
+
125
+ /**
126
+ * Set the transaction context for audit flushing.
127
+ * When set, flush() will use this transaction instead of requiring
128
+ * it to be passed explicitly. This enables declarative audits to
129
+ * participate in the same transaction as the handler's database operations.
130
+ *
131
+ * @param trx - The transaction context (e.g., Kysely Transaction)
132
+ *
133
+ * @example
134
+ * ```typescript
135
+ * // In handler with explicit transaction management
136
+ * const result = await withTransaction(services.database.raw, async (trx) => {
137
+ * // Register transaction with auditor so declarative audits use it
138
+ * auditor.setTransaction(trx);
139
+ *
140
+ * const user = await trx.insertInto('users').values(data).returningAll().executeTakeFirstOrThrow();
141
+ *
142
+ * // Manual audits will also use this transaction when flush() is called
143
+ * auditor.audit('user.created', { userId: user.id });
144
+ *
145
+ * return user;
146
+ * });
147
+ * // After handler, adaptor calls auditor.flush() which uses the stored transaction
148
+ * ```
149
+ */
150
+ setTransaction(trx: TTransaction): void;
151
+
152
+ /**
153
+ * Get the currently set transaction context.
154
+ * Returns undefined if no transaction has been set.
155
+ */
156
+ getTransaction(): TTransaction | undefined;
157
+ }