@geekmidas/audit 0.0.2 → 0.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{DefaultAuditor-1HDUGMub.cjs → DefaultAuditor-JbZ_BQfh.cjs} +3 -25
- package/dist/{DefaultAuditor-1HDUGMub.cjs.map → DefaultAuditor-JbZ_BQfh.cjs.map} +1 -1
- package/dist/DefaultAuditor.cjs +1 -1
- package/dist/chunk-CUT6urMc.cjs +30 -0
- package/dist/index.cjs +1 -1
- package/dist/kysely.cjs +14 -8
- package/dist/kysely.cjs.map +1 -1
- package/dist/kysely.d.cts +33 -6
- package/dist/kysely.d.mts +33 -6
- package/dist/kysely.mjs +14 -8
- package/dist/kysely.mjs.map +1 -1
- package/package.json +1 -1
- package/src/__tests__/KyselyAuditStorage.spec.ts +87 -4
- package/src/kysely.ts +52 -25
|
@@ -1,27 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
var __defProp = Object.defineProperty;
|
|
4
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
-
var __copyProps = (to, from, except, desc) => {
|
|
9
|
-
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
10
|
-
key = keys[i];
|
|
11
|
-
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
|
|
12
|
-
get: ((k) => from[k]).bind(null, key),
|
|
13
|
-
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
14
|
-
});
|
|
15
|
-
}
|
|
16
|
-
return to;
|
|
17
|
-
};
|
|
18
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
19
|
-
value: mod,
|
|
20
|
-
enumerable: true
|
|
21
|
-
}) : target, mod));
|
|
22
|
-
|
|
23
|
-
//#endregion
|
|
24
|
-
const nanoid = __toESM(require("nanoid"));
|
|
1
|
+
const require_chunk = require('./chunk-CUT6urMc.cjs');
|
|
2
|
+
const nanoid = require_chunk.__toESM(require("nanoid"));
|
|
25
3
|
|
|
26
4
|
//#region src/DefaultAuditor.ts
|
|
27
5
|
/**
|
|
@@ -121,4 +99,4 @@ Object.defineProperty(exports, 'DefaultAuditor', {
|
|
|
121
99
|
return DefaultAuditor;
|
|
122
100
|
}
|
|
123
101
|
});
|
|
124
|
-
//# sourceMappingURL=DefaultAuditor-
|
|
102
|
+
//# sourceMappingURL=DefaultAuditor-JbZ_BQfh.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DefaultAuditor-
|
|
1
|
+
{"version":3,"file":"DefaultAuditor-JbZ_BQfh.cjs","names":["config: DefaultAuditorConfig","type: TType","payload: ExtractAuditPayload<TAuditAction, TType>","options?: AuditOptions","record: AuditRecord","record: Omit<AuditRecord, 'id' | 'timestamp' | 'actor'>","fullRecord: AuditRecord","trx?: TTransaction","trx: TTransaction","metadata: AuditMetadata"],"sources":["../src/DefaultAuditor.ts"],"sourcesContent":["import { nanoid } from 'nanoid';\nimport type { Auditor } from './Auditor';\nimport type { AuditStorage } from './storage';\nimport type {\n AuditActor,\n AuditMetadata,\n AuditOptions,\n AuditRecord,\n AuditableAction,\n ExtractAuditPayload,\n ExtractAuditType,\n} from './types';\n\n/**\n * Configuration for DefaultAuditor.\n */\nexport interface DefaultAuditorConfig {\n /** The actor performing audits (set at construction, immutable) */\n actor: AuditActor;\n /** Storage backend for persisting audits */\n storage: AuditStorage;\n /** Optional metadata to attach to all audits */\n metadata?: AuditMetadata;\n /** Optional custom ID generator (defaults to nanoid) */\n generateId?: () => string;\n}\n\n/**\n * Default implementation of the Auditor interface.\n * Collects audit records in memory and flushes to storage.\n *\n * @template TAuditAction - Union of all allowed audit action types\n * @template TTransaction - Transaction type (e.g., Kysely Transaction)\n *\n * @example\n * ```typescript\n * const auditor = new DefaultAuditor<AppAuditAction>({\n * actor: { id: 'user-123', type: 'user' },\n * storage: auditStorage,\n * metadata: { requestId: 'req-456', endpoint: '/users' },\n * });\n *\n * auditor.audit('user.created', { userId: '789', email: 'test@example.com' });\n *\n * // Flush inside transaction\n * await auditor.flush(trx);\n * ```\n */\nexport class DefaultAuditor<\n TAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n string,\n unknown\n >,\n TTransaction = unknown,\n> implements Auditor<TAuditAction, TTransaction>\n{\n readonly actor: AuditActor;\n private readonly storage: AuditStorage;\n private metadata?: AuditMetadata;\n private readonly generateId: () => string;\n private records: AuditRecord[] = [];\n private transaction?: TTransaction;\n\n constructor(config: DefaultAuditorConfig) {\n this.actor = config.actor;\n this.storage = config.storage;\n this.metadata = config.metadata;\n this.generateId = config.generateId ?? (() => nanoid());\n }\n\n audit<TType extends ExtractAuditType<TAuditAction>>(\n type: TType,\n payload: ExtractAuditPayload<TAuditAction, TType>,\n options?: AuditOptions,\n ): void {\n const record: AuditRecord = {\n id: this.generateId(),\n type,\n operation: options?.operation ?? 'CUSTOM',\n table: options?.table,\n entityId: options?.entityId,\n oldValues: options?.oldValues,\n newValues: options?.newValues,\n payload,\n timestamp: new Date(),\n actor: this.actor,\n metadata: this.metadata,\n };\n\n this.records.push(record);\n }\n\n record(record: Omit<AuditRecord, 'id' | 'timestamp' | 'actor'>): void {\n const fullRecord: AuditRecord = {\n ...record,\n id: this.generateId(),\n timestamp: new Date(),\n actor: this.actor,\n metadata: this.metadata\n ? { ...this.metadata, ...record.metadata }\n : record.metadata,\n };\n\n this.records.push(fullRecord);\n }\n\n getRecords(): AuditRecord[] {\n return [...this.records];\n }\n\n async flush(trx?: TTransaction): Promise<void> {\n if (this.records.length === 0) {\n return;\n }\n\n const recordsToFlush = [...this.records];\n this.records = [];\n\n // Use explicitly passed transaction, or fall back to stored transaction\n const transactionToUse = trx ?? this.transaction;\n await this.storage.write(recordsToFlush, transactionToUse);\n }\n\n setTransaction(trx: TTransaction): void {\n this.transaction = trx;\n }\n\n getTransaction(): TTransaction | undefined {\n return this.transaction;\n }\n\n clear(): void {\n this.records = [];\n }\n\n addMetadata(metadata: AuditMetadata): void {\n this.metadata = this.metadata\n ? { ...this.metadata, ...metadata }\n : metadata;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,IAAa,iBAAb,MAOA;CACE,AAAS;CACT,AAAiB;CACjB,AAAQ;CACR,AAAiB;CACjB,AAAQ,UAAyB,CAAE;CACnC,AAAQ;CAER,YAAYA,QAA8B;AACxC,OAAK,QAAQ,OAAO;AACpB,OAAK,UAAU,OAAO;AACtB,OAAK,WAAW,OAAO;AACvB,OAAK,aAAa,OAAO,eAAe,MAAM,oBAAQ;CACvD;CAED,MACEC,MACAC,SACAC,SACM;EACN,MAAMC,SAAsB;GAC1B,IAAI,KAAK,YAAY;GACrB;GACA,WAAW,SAAS,aAAa;GACjC,OAAO,SAAS;GAChB,UAAU,SAAS;GACnB,WAAW,SAAS;GACpB,WAAW,SAAS;GACpB;GACA,2BAAW,IAAI;GACf,OAAO,KAAK;GACZ,UAAU,KAAK;EAChB;AAED,OAAK,QAAQ,KAAK,OAAO;CAC1B;CAED,OAAOC,QAA+D;EACpE,MAAMC,aAA0B;GAC9B,GAAG;GACH,IAAI,KAAK,YAAY;GACrB,2BAAW,IAAI;GACf,OAAO,KAAK;GACZ,UAAU,KAAK,WACX;IAAE,GAAG,KAAK;IAAU,GAAG,OAAO;GAAU,IACxC,OAAO;EACZ;AAED,OAAK,QAAQ,KAAK,WAAW;CAC9B;CAED,aAA4B;AAC1B,SAAO,CAAC,GAAG,KAAK,OAAQ;CACzB;CAED,MAAM,MAAMC,KAAmC;AAC7C,MAAI,KAAK,QAAQ,WAAW,EAC1B;EAGF,MAAM,iBAAiB,CAAC,GAAG,KAAK,OAAQ;AACxC,OAAK,UAAU,CAAE;EAGjB,MAAM,mBAAmB,OAAO,KAAK;AACrC,QAAM,KAAK,QAAQ,MAAM,gBAAgB,iBAAiB;CAC3D;CAED,eAAeC,KAAyB;AACtC,OAAK,cAAc;CACpB;CAED,iBAA2C;AACzC,SAAO,KAAK;CACb;CAED,QAAc;AACZ,OAAK,UAAU,CAAE;CAClB;CAED,YAAYC,UAA+B;AACzC,OAAK,WAAW,KAAK,WACjB;GAAE,GAAG,KAAK;GAAU,GAAG;EAAU,IACjC;CACL;AACF"}
|
package/dist/DefaultAuditor.cjs
CHANGED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
//#region rolldown:runtime
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __copyProps = (to, from, except, desc) => {
|
|
9
|
+
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
10
|
+
key = keys[i];
|
|
11
|
+
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
|
|
12
|
+
get: ((k) => from[k]).bind(null, key),
|
|
13
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
19
|
+
value: mod,
|
|
20
|
+
enumerable: true
|
|
21
|
+
}) : target, mod));
|
|
22
|
+
|
|
23
|
+
//#endregion
|
|
24
|
+
|
|
25
|
+
Object.defineProperty(exports, '__toESM', {
|
|
26
|
+
enumerable: true,
|
|
27
|
+
get: function () {
|
|
28
|
+
return __toESM;
|
|
29
|
+
}
|
|
30
|
+
});
|
package/dist/index.cjs
CHANGED
package/dist/kysely.cjs
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
const require_chunk = require('./chunk-CUT6urMc.cjs');
|
|
2
|
+
const nanoid = require_chunk.__toESM(require("nanoid"));
|
|
1
3
|
|
|
2
4
|
//#region src/kysely.ts
|
|
3
5
|
/**
|
|
@@ -81,11 +83,13 @@ async function withAuditableTransaction(db, auditor, cb, settings) {
|
|
|
81
83
|
var KyselyAuditStorage = class {
|
|
82
84
|
db;
|
|
83
85
|
tableName;
|
|
86
|
+
autoId;
|
|
84
87
|
databaseServiceName;
|
|
85
88
|
constructor(config) {
|
|
86
89
|
this.db = config.db;
|
|
87
90
|
this.tableName = config.tableName;
|
|
88
91
|
this.databaseServiceName = config.databaseServiceName;
|
|
92
|
+
this.autoId = config.autoId ?? false;
|
|
89
93
|
}
|
|
90
94
|
async write(records, trx) {
|
|
91
95
|
if (records.length === 0) return;
|
|
@@ -131,20 +135,21 @@ var KyselyAuditStorage = class {
|
|
|
131
135
|
return query;
|
|
132
136
|
}
|
|
133
137
|
toRow(record) {
|
|
138
|
+
const id = record.id || (this.autoId ? void 0 : (0, nanoid.nanoid)());
|
|
134
139
|
return {
|
|
135
|
-
id
|
|
140
|
+
...id && { id },
|
|
136
141
|
type: record.type,
|
|
137
142
|
operation: record.operation,
|
|
138
143
|
table: record.table ?? null,
|
|
139
144
|
entityId: record.entityId === void 0 ? null : typeof record.entityId === "string" ? record.entityId : JSON.stringify(record.entityId),
|
|
140
|
-
oldValues: record.oldValues
|
|
141
|
-
newValues: record.newValues
|
|
142
|
-
payload: record.payload
|
|
145
|
+
oldValues: record.oldValues ?? null,
|
|
146
|
+
newValues: record.newValues ?? null,
|
|
147
|
+
payload: record.payload ?? null,
|
|
143
148
|
timestamp: record.timestamp,
|
|
144
149
|
actorId: record.actor?.id ?? null,
|
|
145
150
|
actorType: record.actor?.type ?? null,
|
|
146
|
-
actorData: record.actor !== void 0 ?
|
|
147
|
-
metadata: record.metadata
|
|
151
|
+
actorData: record.actor !== void 0 ? this.getActorData(record.actor) : null,
|
|
152
|
+
metadata: record.metadata ?? null
|
|
148
153
|
};
|
|
149
154
|
}
|
|
150
155
|
fromRow(row) {
|
|
@@ -171,8 +176,9 @@ var KyselyAuditStorage = class {
|
|
|
171
176
|
* Parse a JSON value that may already be parsed (e.g., from jsonb columns).
|
|
172
177
|
*/
|
|
173
178
|
parseJson(value) {
|
|
174
|
-
if (typeof value === "object") return value;
|
|
175
|
-
return JSON.parse(value);
|
|
179
|
+
if (typeof value === "object" && value !== null) return value;
|
|
180
|
+
if (typeof value === "string") return JSON.parse(value);
|
|
181
|
+
return {};
|
|
176
182
|
}
|
|
177
183
|
getActorData(actor) {
|
|
178
184
|
const { id, type,...rest } = actor;
|
package/dist/kysely.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"kysely.cjs","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","query: any","record: AuditRecord","value: string | object","actor: NonNullable<AuditRecord['actor']>","entityId: string"],"sources":["../src/kysely.ts"],"sourcesContent":["import type {\n ControlledTransaction,\n IsolationLevel,\n Kysely,\n Transaction,\n} from 'kysely';\nimport type { AuditQueryOptions, AuditStorage } from './storage';\nimport type { AuditRecord } from './types';\n\n/**\n * Minimal interface for transaction-aware audit flushing.\n * Use this when you need to flush audits within a database transaction.\n *\n * @template TTransaction - Transaction type (e.g., Kysely Transaction)\n *\n * @example\n * ```typescript\n * import { withAuditableTransaction } from '@geekmidas/audit/kysely';\n * import type { TransactionAwareAuditor } from '@geekmidas/audit/kysely';\n *\n * const result = await withAuditableTransaction(\n * db,\n * auditor as TransactionAwareAuditor<Transaction<DB>>,\n * async (trx) => {\n * // Your transactional operations\n * return result;\n * },\n * );\n * ```\n */\nexport interface TransactionAwareAuditor<TTransaction = unknown> {\n /** Register the transaction with the auditor for use during flush */\n setTransaction(trx: TTransaction): void;\n /** Flush all pending audits, optionally within a transaction */\n flush(trx?: TTransaction): Promise<void>;\n}\n\nexport interface TransactionSettings {\n isolationLevel?: IsolationLevel;\n}\n\nexport type DatabaseConnection<T> =\n | ControlledTransaction<T>\n | Kysely<T>\n | 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 db: DatabaseConnection<DB>,\n auditor: TransactionAwareAuditor<Transaction<DB>>,\n cb: (trx: Transaction<DB>) => Promise<T>,\n settings?: TransactionSettings,\n): Promise<T> {\n const execute = async (trx: Transaction<DB>): Promise<T> => {\n // Register transaction with auditor\n auditor.setTransaction(trx);\n\n // Execute the callback\n const result = await cb(trx);\n\n // Flush audits BEFORE transaction commits\n // If this fails, the transaction will roll back\n await auditor.flush(trx);\n\n return result;\n };\n\n // If already in a transaction, just run with it\n if (db.isTransaction) {\n return execute(db as Transaction<DB>);\n }\n\n const builder = db.transaction();\n\n if (settings?.isolationLevel) {\n return builder.setIsolationLevel(settings.isolationLevel).execute(execute);\n }\n\n return 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 * @example\n * ```typescript\n * interface Database {\n * audit_logs: AuditLogTable;\n * // ... other tables\n * }\n * ```\n */\nexport interface AuditLogTable {\n id: string;\n type: string;\n operation: string;\n table: string | null;\n entityId: string | null;\n oldValues: string | null;\n newValues: string | null;\n payload: string | null;\n timestamp: Date;\n actorId: string | null;\n actorType: string | null;\n actorData: string | null;\n metadata: string | null;\n}\n\n/**\n * Configuration for KyselyAuditStorage.\n */\nexport interface KyselyAuditStorageConfig<DB> {\n /** Kysely database instance */\n db: Kysely<DB>;\n /** Table name for audit logs (must be a key in DB that extends AuditLogTable) */\n tableName: keyof DB & string;\n /**\n * Service name of the database service.\n * When set, endpoint adaptors will automatically use the audit transaction as `db`\n * in the handler context if the endpoint's database service has the same name.\n */\n databaseServiceName?: string;\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 private readonly db: Kysely<DB>;\n private readonly tableName: keyof DB & string;\n readonly databaseServiceName?: string;\n\n constructor(config: KyselyAuditStorageConfig<DB>) {\n this.db = config.db;\n this.tableName = config.tableName;\n this.databaseServiceName = config.databaseServiceName;\n }\n\n async write(records: AuditRecord[], trx?: unknown): Promise<void> {\n if (records.length === 0) {\n return;\n }\n\n const db = (trx as Transaction<DB>) ?? this.db;\n const rows = records.map((record) => this.toRow(record));\n\n await (db as any).insertInto(this.tableName).values(rows).execute();\n }\n\n async query(options: AuditQueryOptions): Promise<AuditRecord[]> {\n let query = (this.db as any).selectFrom(this.tableName).selectAll();\n\n query = this.applyFilters(query, options);\n\n // Ordering\n const orderBy = options.orderBy ?? 'timestamp';\n const orderDirection = options.orderDirection ?? 'desc';\n query = query.orderBy(\n orderBy === 'timestamp' ? 'timestamp' : 'type',\n orderDirection,\n );\n\n // Pagination\n if (options.limit !== undefined) {\n query = query.limit(options.limit);\n }\n if (options.offset !== undefined) {\n query = query.offset(options.offset);\n }\n\n const rows = await query.execute();\n return rows.map((row: AuditLogTable) => this.fromRow(row));\n }\n\n async count(\n options: Omit<AuditQueryOptions, 'limit' | 'offset'>,\n ): Promise<number> {\n let query = (this.db as any)\n .selectFrom(this.tableName)\n .select((eb: any) => eb.fn.count('id').as('count'));\n\n query = this.applyFilters(query, options);\n\n const result = await query.executeTakeFirst();\n return Number(result?.count ?? 0);\n }\n\n /**\n * Get the Kysely database instance for transactional operations.\n * Used by endpoint adaptors to automatically wrap handlers in transactions.\n */\n getDatabase(): Kysely<DB> {\n return this.db;\n }\n\n private applyFilters(query: any, options: AuditQueryOptions): any {\n // Type filter\n if (options.type !== undefined) {\n if (Array.isArray(options.type)) {\n query = query.where('type', 'in', options.type);\n } else {\n query = query.where('type', '=', options.type);\n }\n }\n\n // Entity ID filter\n if (options.entityId !== undefined) {\n const entityId =\n typeof options.entityId === 'string'\n ? options.entityId\n : JSON.stringify(options.entityId);\n query = query.where('entityId', '=', entityId);\n }\n\n // Table filter\n if (options.table !== undefined) {\n query = query.where('table', '=', options.table);\n }\n\n // Actor ID filter\n if (options.actorId !== undefined) {\n query = query.where('actorId', '=', options.actorId);\n }\n\n // Date range filters\n if (options.from !== undefined) {\n query = query.where('timestamp', '>=', options.from);\n }\n if (options.to !== undefined) {\n query = query.where('timestamp', '<=', options.to);\n }\n\n return query;\n }\n\n private toRow(record: AuditRecord): AuditLogTable {\n return {\n id: record.id,\n type: record.type,\n operation: record.operation,\n table: record.table ?? null,\n entityId:\n record.entityId === undefined\n ? null\n : typeof record.entityId === 'string'\n ? record.entityId\n : JSON.stringify(record.entityId),\n oldValues:\n record.oldValues !== undefined\n ? JSON.stringify(record.oldValues)\n : null,\n newValues:\n record.newValues !== undefined\n ? JSON.stringify(record.newValues)\n : null,\n payload:\n record.payload !== undefined ? JSON.stringify(record.payload) : null,\n timestamp: record.timestamp,\n actorId: record.actor?.id ?? null,\n actorType: record.actor?.type ?? null,\n actorData:\n record.actor !== undefined\n ? JSON.stringify(this.getActorData(record.actor))\n : null,\n metadata:\n record.metadata !== undefined ? JSON.stringify(record.metadata) : null,\n };\n }\n\n private fromRow(row: AuditLogTable): AuditRecord {\n const actor =\n row.actorId !== null || row.actorType !== null\n ? {\n id: row.actorId ?? undefined,\n type: row.actorType ?? undefined,\n ...(row.actorData ? this.parseJson(row.actorData) : {}),\n }\n : undefined;\n\n return {\n id: row.id,\n type: row.type,\n operation: row.operation as AuditRecord['operation'],\n table: row.table ?? undefined,\n entityId: row.entityId ? this.parseEntityId(row.entityId) : undefined,\n oldValues: row.oldValues ? this.parseJson(row.oldValues) : undefined,\n newValues: row.newValues ? this.parseJson(row.newValues) : undefined,\n payload: row.payload ? this.parseJson(row.payload) : undefined,\n timestamp: row.timestamp,\n actor,\n metadata: row.metadata ? this.parseJson(row.metadata) : undefined,\n };\n }\n\n /**\n * Parse a JSON value that may already be parsed (e.g., from jsonb columns).\n */\n private parseJson(value: string | object): Record<string, unknown> {\n if (typeof value === 'object') {\n return value as Record<string, unknown>;\n }\n return JSON.parse(value);\n }\n\n private getActorData(\n actor: NonNullable<AuditRecord['actor']>,\n ): Record<string, unknown> {\n const { id, type, ...rest } = actor;\n return rest;\n }\n\n private parseEntityId(entityId: string): string | Record<string, unknown> {\n try {\n const parsed = JSON.parse(entityId);\n if (typeof parsed === 'object' && parsed !== null) {\n return parsed;\n }\n return entityId;\n } catch {\n return entityId;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyFA,eAAsB,yBACpBA,IACAC,SACAC,IACAC,UACY;CACZ,MAAM,UAAU,OAAOC,QAAqC;AAE1D,UAAQ,eAAe,IAAI;EAG3B,MAAM,SAAS,MAAM,GAAG,IAAI;AAI5B,QAAM,QAAQ,MAAM,IAAI;AAExB,SAAO;CACR;AAGD,KAAI,GAAG,cACL,QAAO,QAAQ,GAAsB;CAGvC,MAAM,UAAU,GAAG,aAAa;AAEhC,KAAI,UAAU,eACZ,QAAO,QAAQ,kBAAkB,SAAS,eAAe,CAAC,QAAQ,QAAQ;AAG5E,QAAO,QAAQ,QAAQ,QAAQ;AAChC;;;;;;;;;;;;;;;;;;;;;;;;AAqED,IAAa,qBAAb,MAA4D;CAC1D,AAAiB;CACjB,AAAiB;CACjB,AAAS;CAET,YAAYC,QAAsC;AAChD,OAAK,KAAK,OAAO;AACjB,OAAK,YAAY,OAAO;AACxB,OAAK,sBAAsB,OAAO;CACnC;CAED,MAAM,MAAMC,SAAwBC,KAA8B;AAChE,MAAI,QAAQ,WAAW,EACrB;EAGF,MAAM,KAAM,OAA2B,KAAK;EAC5C,MAAM,OAAO,QAAQ,IAAI,CAAC,WAAW,KAAK,MAAM,OAAO,CAAC;AAExD,QAAM,AAAC,GAAW,WAAW,KAAK,UAAU,CAAC,OAAO,KAAK,CAAC,SAAS;CACpE;CAED,MAAM,MAAMC,SA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W,IAAI;GACf;GACA,UAAU,IAAI,WAAW,KAAK,UAAU,IAAI,SAAS;EACtD;CACF;;;;CAKD,AAAQ,UAAUK,OAAiD;AACjE,aAAW,UAAU,SACnB,QAAO;AAET,SAAO,KAAK,MAAM,MAAM;CACzB;CAED,AAAQ,aACNC,OACyB;EACzB,MAAM,EAAE,IAAI,KAAM,GAAG,MAAM,GAAG;AAC9B,SAAO;CACR;CAED,AAAQ,cAAcC,UAAoD;AACxE,MAAI;GACF,MAAM,SAAS,KAAK,MAAM,SAAS;AACnC,cAAW,WAAW,YAAY,WAAW,KAC3C,QAAO;AAET,UAAO;EACR,QAAO;AACN,UAAO;EACR;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"kysely.cjs","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","query: any","record: AuditRecord","value: unknown","actor: NonNullable<AuditRecord['actor']>","entityId: string"],"sources":["../src/kysely.ts"],"sourcesContent":["import type {\n ControlledTransaction,\n IsolationLevel,\n Kysely,\n Transaction,\n} from 'kysely';\nimport { nanoid } from 'nanoid';\nimport type { AuditQueryOptions, AuditStorage } from './storage';\nimport type { AuditRecord } from './types';\n\n/**\n * Minimal interface for transaction-aware audit flushing.\n * Use this when you need to flush audits within a database transaction.\n *\n * @template TTransaction - Transaction type (e.g., Kysely Transaction)\n *\n * @example\n * ```typescript\n * import { withAuditableTransaction } from '@geekmidas/audit/kysely';\n * import type { TransactionAwareAuditor } from '@geekmidas/audit/kysely';\n *\n * const result = await withAuditableTransaction(\n * db,\n * auditor as TransactionAwareAuditor<Transaction<DB>>,\n * async (trx) => {\n * // Your transactional operations\n * return result;\n * },\n * );\n * ```\n */\nexport interface TransactionAwareAuditor<TTransaction = unknown> {\n /** Register the transaction with the auditor for use during flush */\n setTransaction(trx: TTransaction): void;\n /** Flush all pending audits, optionally within a transaction */\n flush(trx?: TTransaction): Promise<void>;\n}\n\nexport interface TransactionSettings {\n isolationLevel?: IsolationLevel;\n}\n\nexport type DatabaseConnection<T> =\n | ControlledTransaction<T>\n | Kysely<T>\n | 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 db: DatabaseConnection<DB>,\n auditor: TransactionAwareAuditor<Transaction<DB>>,\n cb: (trx: Transaction<DB>) => Promise<T>,\n settings?: TransactionSettings,\n): Promise<T> {\n const execute = async (trx: Transaction<DB>): Promise<T> => {\n // Register transaction with auditor\n auditor.setTransaction(trx);\n\n // Execute the callback\n const result = await cb(trx);\n\n // Flush audits BEFORE transaction commits\n // If this fails, the transaction will roll back\n await auditor.flush(trx);\n\n return result;\n };\n\n // If already in a transaction, just run with it\n if (db.isTransaction) {\n return execute(db as Transaction<DB>);\n }\n\n const builder = db.transaction();\n\n if (settings?.isolationLevel) {\n return builder.setIsolationLevel(settings.isolationLevel).execute(execute);\n }\n\n return 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 id: string;\n type: string;\n operation: string;\n table: string | null;\n entityId: string | null;\n oldValues: unknown | null;\n newValues: unknown | null;\n payload: unknown | null;\n timestamp: Date;\n actorId: string | null;\n actorType: string | null;\n actorData: unknown | null;\n metadata: 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 id?: string;\n};\n\n/**\n * Configuration for KyselyAuditStorage.\n */\nexport interface KyselyAuditStorageConfig<DB> {\n /** Kysely database instance */\n db: Kysely<DB>;\n /** Table name for audit logs (must be a key in DB that extends AuditLogTable) */\n tableName: keyof DB & string;\n /**\n * Service name of the database service.\n * When set, endpoint adaptors will automatically use the audit transaction as `db`\n * in the handler context if the endpoint's database service has the same name.\n */\n databaseServiceName?: string;\n /**\n * Let the database auto-generate IDs (e.g., via DEFAULT gen_random_uuid()).\n * When true, the ID field is omitted from inserts if not provided.\n * When false (default), IDs are generated using nanoid if not provided.\n * @default false\n */\n autoId?: 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 private readonly db: Kysely<DB>;\n private readonly tableName: keyof DB & string;\n private readonly autoId: boolean;\n readonly databaseServiceName?: string;\n\n constructor(config: KyselyAuditStorageConfig<DB>) {\n this.db = config.db;\n this.tableName = config.tableName;\n this.databaseServiceName = config.databaseServiceName;\n this.autoId = config.autoId ?? false;\n }\n\n async write(records: AuditRecord[], trx?: unknown): Promise<void> {\n if (records.length === 0) {\n return;\n }\n\n const db = (trx as Transaction<DB>) ?? this.db;\n const rows = records.map((record) => this.toRow(record));\n\n await (db as any).insertInto(this.tableName).values(rows).execute();\n }\n\n async query(options: AuditQueryOptions): Promise<AuditRecord[]> {\n let query = (this.db as any).selectFrom(this.tableName).selectAll();\n\n query = this.applyFilters(query, options);\n\n // Ordering\n const orderBy = options.orderBy ?? 'timestamp';\n const orderDirection = options.orderDirection ?? 'desc';\n query = query.orderBy(\n orderBy === 'timestamp' ? 'timestamp' : 'type',\n orderDirection,\n );\n\n // Pagination\n if (options.limit !== undefined) {\n query = query.limit(options.limit);\n }\n if (options.offset !== undefined) {\n query = query.offset(options.offset);\n }\n\n const rows = await query.execute();\n return rows.map((row: AuditLogTable) => this.fromRow(row));\n }\n\n async count(\n options: Omit<AuditQueryOptions, 'limit' | 'offset'>,\n ): Promise<number> {\n let query = (this.db as any)\n .selectFrom(this.tableName)\n .select((eb: any) => eb.fn.count('id').as('count'));\n\n query = this.applyFilters(query, options);\n\n const result = await query.executeTakeFirst();\n return Number(result?.count ?? 0);\n }\n\n /**\n * Get the Kysely database instance for transactional operations.\n * Used by endpoint adaptors to automatically wrap handlers in transactions.\n */\n getDatabase(): Kysely<DB> {\n return this.db;\n }\n\n private applyFilters(query: any, options: AuditQueryOptions): any {\n // Type filter\n if (options.type !== undefined) {\n if (Array.isArray(options.type)) {\n query = query.where('type', 'in', options.type);\n } else {\n query = query.where('type', '=', options.type);\n }\n }\n\n // Entity ID filter\n if (options.entityId !== undefined) {\n const entityId =\n typeof options.entityId === 'string'\n ? options.entityId\n : JSON.stringify(options.entityId);\n query = query.where('entityId', '=', entityId);\n }\n\n // Table filter\n if (options.table !== undefined) {\n query = query.where('table', '=', options.table);\n }\n\n // Actor ID filter\n if (options.actorId !== undefined) {\n query = query.where('actorId', '=', options.actorId);\n }\n\n // Date range filters\n if (options.from !== undefined) {\n query = query.where('timestamp', '>=', options.from);\n }\n if (options.to !== undefined) {\n query = query.where('timestamp', '<=', options.to);\n }\n\n return query;\n }\n\n private toRow(record: AuditRecord): AuditLogTable {\n // If autoId is true, let database generate ID (omit if not provided)\n // If autoId is false (default), generate with nanoid if not provided\n const id = record.id || (this.autoId ? undefined : nanoid());\n\n return {\n ...(id && { id }),\n type: record.type,\n operation: record.operation,\n table: record.table ?? null,\n entityId:\n record.entityId === undefined\n ? null\n : typeof record.entityId === 'string'\n ? record.entityId\n : JSON.stringify(record.entityId),\n oldValues: record.oldValues ?? null,\n newValues: record.newValues ?? null,\n payload: record.payload ?? null,\n timestamp: record.timestamp,\n actorId: record.actor?.id ?? null,\n actorType: record.actor?.type ?? null,\n actorData:\n record.actor !== undefined ? this.getActorData(record.actor) : null,\n metadata: record.metadata ?? null,\n } as AuditLogTable;\n }\n\n private fromRow(row: AuditLogTable): AuditRecord {\n const actor =\n row.actorId !== null || row.actorType !== null\n ? {\n id: row.actorId ?? undefined,\n type: row.actorType ?? undefined,\n ...(row.actorData ? this.parseJson(row.actorData) : {}),\n }\n : undefined;\n\n return {\n id: row.id,\n type: row.type,\n operation: row.operation as AuditRecord['operation'],\n table: row.table ?? undefined,\n entityId: row.entityId ? this.parseEntityId(row.entityId) : undefined,\n oldValues: row.oldValues ? this.parseJson(row.oldValues) : undefined,\n newValues: row.newValues ? this.parseJson(row.newValues) : undefined,\n payload: row.payload ? this.parseJson(row.payload) : undefined,\n timestamp: row.timestamp,\n actor,\n metadata: row.metadata ? this.parseJson(row.metadata) : undefined,\n };\n }\n\n /**\n * Parse a JSON value that may already be parsed (e.g., from jsonb columns).\n */\n private parseJson(value: unknown): Record<string, unknown> {\n if (typeof value === 'object' && value !== null) {\n return value as Record<string, unknown>;\n }\n if (typeof value === 'string') {\n return JSON.parse(value);\n }\n return {};\n }\n\n private getActorData(\n actor: NonNullable<AuditRecord['actor']>,\n ): Record<string, unknown> {\n const { id, type, ...rest } = actor;\n return rest;\n }\n\n private parseEntityId(entityId: string): string | Record<string, unknown> {\n try {\n const parsed = JSON.parse(entityId);\n if (typeof parsed === 'object' && parsed !== null) {\n return parsed;\n }\n return entityId;\n } catch {\n return entityId;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0FA,eAAsB,yBACpBA,IACAC,SACAC,IACAC,UACY;CACZ,MAAM,UAAU,OAAOC,QAAqC;AAE1D,UAAQ,eAAe,IAAI;EAG3B,MAAM,SAAS,MAAM,GAAG,IAAI;AAI5B,QAAM,QAAQ,MAAM,IAAI;AAExB,SAAO;CACR;AAGD,KAAI,GAAG,cACL,QAAO,QAAQ,GAAsB;CAGvC,MAAM,UAAU,GAAG,aAAa;AAEhC,KAAI,UAAU,eACZ,QAAO,QAAQ,kBAAkB,SAAS,eAAe,CAAC,QAAQ,QAAQ;AAG5E,QAAO,QAAQ,QAAQ,QAAQ;AAChC;;;;;;;;;;;;;;;;;;;;;;;;AAgGD,IAAa,qBAAb,MAA4D;CAC1D,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAS;CAET,YAAYC,QAAsC;AAChD,OAAK,KAAK,OAAO;AACjB,OAAK,YAAY,OAAO;AACxB,OAAK,sBAAsB,OAAO;AAClC,OAAK,SAAS,OAAO,UAAU;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IAAI;GACX,UAAU,IAAI,WAAW,KAAK,cAAc,IAAI,SAAS;GACzD,WAAW,IAAI,YAAY,KAAK,UAAU,IAAI,UAAU;GACxD,WAAW,IAAI,YAAY,KAAK,UAAU,IAAI,UAAU;GACxD,SAAS,IAAI,UAAU,KAAK,UAAU,IAAI,QAAQ;GAClD,WAAW,IAAI;GACf;GACA,UAAU,IAAI,WAAW,KAAK,UAAU,IAAI,SAAS;EACtD;CACF;;;;CAKD,AAAQ,UAAUK,OAAyC;AACzD,aAAW,UAAU,YAAY,UAAU,KACzC,QAAO;AAET,aAAW,UAAU,SACnB,QAAO,KAAK,MAAM,MAAM;AAE1B,SAAO,CAAE;CACV;CAED,AAAQ,aACNC,OACyB;EACzB,MAAM,EAAE,IAAI,KAAM,GAAG,MAAM,GAAG;AAC9B,SAAO;CACR;CAED,AAAQ,cAAcC,UAAoD;AACxE,MAAI;GACF,MAAM,SAAS,KAAK,MAAM,SAAS;AACnC,cAAW,WAAW,YAAY,WAAW,KAC3C,QAAO;AAET,UAAO;EACR,QAAO;AACN,UAAO;EACR;CACF;AACF"}
|
package/dist/kysely.d.cts
CHANGED
|
@@ -83,6 +83,8 @@ declare function withAuditableTransaction<DB, T>(db: DatabaseConnection<DB>, aud
|
|
|
83
83
|
* Database table interface for audit records.
|
|
84
84
|
* Use this to define your audit_logs table in your Kysely database schema.
|
|
85
85
|
*
|
|
86
|
+
* Column names use snake_case to match standard PostgreSQL conventions.
|
|
87
|
+
*
|
|
86
88
|
* @example
|
|
87
89
|
* ```typescript
|
|
88
90
|
* interface Database {
|
|
@@ -97,15 +99,32 @@ interface AuditLogTable {
|
|
|
97
99
|
operation: string;
|
|
98
100
|
table: string | null;
|
|
99
101
|
entityId: string | null;
|
|
100
|
-
oldValues:
|
|
101
|
-
newValues:
|
|
102
|
-
payload:
|
|
102
|
+
oldValues: unknown | null;
|
|
103
|
+
newValues: unknown | null;
|
|
104
|
+
payload: unknown | null;
|
|
103
105
|
timestamp: Date;
|
|
104
106
|
actorId: string | null;
|
|
105
107
|
actorType: string | null;
|
|
106
|
-
actorData:
|
|
107
|
-
metadata:
|
|
108
|
+
actorData: unknown | null;
|
|
109
|
+
metadata: unknown | null;
|
|
108
110
|
}
|
|
111
|
+
/**
|
|
112
|
+
* Insertable version of AuditLogTable where id is optional.
|
|
113
|
+
* Use this when your database auto-generates IDs or when using autoId option.
|
|
114
|
+
*
|
|
115
|
+
* @example
|
|
116
|
+
* ```typescript
|
|
117
|
+
* interface Database {
|
|
118
|
+
* audit_logs: AuditLogTable;
|
|
119
|
+
* }
|
|
120
|
+
*
|
|
121
|
+
* // For insertions where id is auto-generated
|
|
122
|
+
* type NewAuditLog = InsertableAuditLogTable;
|
|
123
|
+
* ```
|
|
124
|
+
*/
|
|
125
|
+
type InsertableAuditLogTable = Omit<AuditLogTable, 'id'> & {
|
|
126
|
+
id?: string;
|
|
127
|
+
};
|
|
109
128
|
/**
|
|
110
129
|
* Configuration for KyselyAuditStorage.
|
|
111
130
|
*/
|
|
@@ -120,6 +139,13 @@ interface KyselyAuditStorageConfig<DB> {
|
|
|
120
139
|
* in the handler context if the endpoint's database service has the same name.
|
|
121
140
|
*/
|
|
122
141
|
databaseServiceName?: string;
|
|
142
|
+
/**
|
|
143
|
+
* Let the database auto-generate IDs (e.g., via DEFAULT gen_random_uuid()).
|
|
144
|
+
* When true, the ID field is omitted from inserts if not provided.
|
|
145
|
+
* When false (default), IDs are generated using nanoid if not provided.
|
|
146
|
+
* @default false
|
|
147
|
+
*/
|
|
148
|
+
autoId?: boolean;
|
|
123
149
|
}
|
|
124
150
|
/**
|
|
125
151
|
* Kysely-based audit storage implementation.
|
|
@@ -147,6 +173,7 @@ interface KyselyAuditStorageConfig<DB> {
|
|
|
147
173
|
declare class KyselyAuditStorage<DB> implements AuditStorage {
|
|
148
174
|
private readonly db;
|
|
149
175
|
private readonly tableName;
|
|
176
|
+
private readonly autoId;
|
|
150
177
|
readonly databaseServiceName?: string;
|
|
151
178
|
constructor(config: KyselyAuditStorageConfig<DB>);
|
|
152
179
|
write(records: AuditRecord[], trx?: unknown): Promise<void>;
|
|
@@ -168,5 +195,5 @@ declare class KyselyAuditStorage<DB> implements AuditStorage {
|
|
|
168
195
|
private parseEntityId;
|
|
169
196
|
}
|
|
170
197
|
//#endregion
|
|
171
|
-
export { AuditLogTable, DatabaseConnection, KyselyAuditStorage, KyselyAuditStorageConfig, TransactionAwareAuditor, TransactionSettings, withAuditableTransaction };
|
|
198
|
+
export { AuditLogTable, DatabaseConnection, InsertableAuditLogTable, KyselyAuditStorage, KyselyAuditStorageConfig, TransactionAwareAuditor, TransactionSettings, withAuditableTransaction };
|
|
172
199
|
//# sourceMappingURL=kysely.d.cts.map
|
package/dist/kysely.d.mts
CHANGED
|
@@ -83,6 +83,8 @@ declare function withAuditableTransaction<DB, T>(db: DatabaseConnection<DB>, aud
|
|
|
83
83
|
* Database table interface for audit records.
|
|
84
84
|
* Use this to define your audit_logs table in your Kysely database schema.
|
|
85
85
|
*
|
|
86
|
+
* Column names use snake_case to match standard PostgreSQL conventions.
|
|
87
|
+
*
|
|
86
88
|
* @example
|
|
87
89
|
* ```typescript
|
|
88
90
|
* interface Database {
|
|
@@ -97,15 +99,32 @@ interface AuditLogTable {
|
|
|
97
99
|
operation: string;
|
|
98
100
|
table: string | null;
|
|
99
101
|
entityId: string | null;
|
|
100
|
-
oldValues:
|
|
101
|
-
newValues:
|
|
102
|
-
payload:
|
|
102
|
+
oldValues: unknown | null;
|
|
103
|
+
newValues: unknown | null;
|
|
104
|
+
payload: unknown | null;
|
|
103
105
|
timestamp: Date;
|
|
104
106
|
actorId: string | null;
|
|
105
107
|
actorType: string | null;
|
|
106
|
-
actorData:
|
|
107
|
-
metadata:
|
|
108
|
+
actorData: unknown | null;
|
|
109
|
+
metadata: unknown | null;
|
|
108
110
|
}
|
|
111
|
+
/**
|
|
112
|
+
* Insertable version of AuditLogTable where id is optional.
|
|
113
|
+
* Use this when your database auto-generates IDs or when using autoId option.
|
|
114
|
+
*
|
|
115
|
+
* @example
|
|
116
|
+
* ```typescript
|
|
117
|
+
* interface Database {
|
|
118
|
+
* audit_logs: AuditLogTable;
|
|
119
|
+
* }
|
|
120
|
+
*
|
|
121
|
+
* // For insertions where id is auto-generated
|
|
122
|
+
* type NewAuditLog = InsertableAuditLogTable;
|
|
123
|
+
* ```
|
|
124
|
+
*/
|
|
125
|
+
type InsertableAuditLogTable = Omit<AuditLogTable, 'id'> & {
|
|
126
|
+
id?: string;
|
|
127
|
+
};
|
|
109
128
|
/**
|
|
110
129
|
* Configuration for KyselyAuditStorage.
|
|
111
130
|
*/
|
|
@@ -120,6 +139,13 @@ interface KyselyAuditStorageConfig<DB> {
|
|
|
120
139
|
* in the handler context if the endpoint's database service has the same name.
|
|
121
140
|
*/
|
|
122
141
|
databaseServiceName?: string;
|
|
142
|
+
/**
|
|
143
|
+
* Let the database auto-generate IDs (e.g., via DEFAULT gen_random_uuid()).
|
|
144
|
+
* When true, the ID field is omitted from inserts if not provided.
|
|
145
|
+
* When false (default), IDs are generated using nanoid if not provided.
|
|
146
|
+
* @default false
|
|
147
|
+
*/
|
|
148
|
+
autoId?: boolean;
|
|
123
149
|
}
|
|
124
150
|
/**
|
|
125
151
|
* Kysely-based audit storage implementation.
|
|
@@ -147,6 +173,7 @@ interface KyselyAuditStorageConfig<DB> {
|
|
|
147
173
|
declare class KyselyAuditStorage<DB> implements AuditStorage {
|
|
148
174
|
private readonly db;
|
|
149
175
|
private readonly tableName;
|
|
176
|
+
private readonly autoId;
|
|
150
177
|
readonly databaseServiceName?: string;
|
|
151
178
|
constructor(config: KyselyAuditStorageConfig<DB>);
|
|
152
179
|
write(records: AuditRecord[], trx?: unknown): Promise<void>;
|
|
@@ -168,5 +195,5 @@ declare class KyselyAuditStorage<DB> implements AuditStorage {
|
|
|
168
195
|
private parseEntityId;
|
|
169
196
|
}
|
|
170
197
|
//#endregion
|
|
171
|
-
export { AuditLogTable, DatabaseConnection, KyselyAuditStorage, KyselyAuditStorageConfig, TransactionAwareAuditor, TransactionSettings, withAuditableTransaction };
|
|
198
|
+
export { AuditLogTable, DatabaseConnection, InsertableAuditLogTable, KyselyAuditStorage, KyselyAuditStorageConfig, TransactionAwareAuditor, TransactionSettings, withAuditableTransaction };
|
|
172
199
|
//# sourceMappingURL=kysely.d.mts.map
|
package/dist/kysely.mjs
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { nanoid } from "nanoid";
|
|
2
|
+
|
|
1
3
|
//#region src/kysely.ts
|
|
2
4
|
/**
|
|
3
5
|
* Execute a callback within a database transaction with automatic audit handling.
|
|
@@ -80,11 +82,13 @@ async function withAuditableTransaction(db, auditor, cb, settings) {
|
|
|
80
82
|
var KyselyAuditStorage = class {
|
|
81
83
|
db;
|
|
82
84
|
tableName;
|
|
85
|
+
autoId;
|
|
83
86
|
databaseServiceName;
|
|
84
87
|
constructor(config) {
|
|
85
88
|
this.db = config.db;
|
|
86
89
|
this.tableName = config.tableName;
|
|
87
90
|
this.databaseServiceName = config.databaseServiceName;
|
|
91
|
+
this.autoId = config.autoId ?? false;
|
|
88
92
|
}
|
|
89
93
|
async write(records, trx) {
|
|
90
94
|
if (records.length === 0) return;
|
|
@@ -130,20 +134,21 @@ var KyselyAuditStorage = class {
|
|
|
130
134
|
return query;
|
|
131
135
|
}
|
|
132
136
|
toRow(record) {
|
|
137
|
+
const id = record.id || (this.autoId ? void 0 : nanoid());
|
|
133
138
|
return {
|
|
134
|
-
id
|
|
139
|
+
...id && { id },
|
|
135
140
|
type: record.type,
|
|
136
141
|
operation: record.operation,
|
|
137
142
|
table: record.table ?? null,
|
|
138
143
|
entityId: record.entityId === void 0 ? null : typeof record.entityId === "string" ? record.entityId : JSON.stringify(record.entityId),
|
|
139
|
-
oldValues: record.oldValues
|
|
140
|
-
newValues: record.newValues
|
|
141
|
-
payload: record.payload
|
|
144
|
+
oldValues: record.oldValues ?? null,
|
|
145
|
+
newValues: record.newValues ?? null,
|
|
146
|
+
payload: record.payload ?? null,
|
|
142
147
|
timestamp: record.timestamp,
|
|
143
148
|
actorId: record.actor?.id ?? null,
|
|
144
149
|
actorType: record.actor?.type ?? null,
|
|
145
|
-
actorData: record.actor !== void 0 ?
|
|
146
|
-
metadata: record.metadata
|
|
150
|
+
actorData: record.actor !== void 0 ? this.getActorData(record.actor) : null,
|
|
151
|
+
metadata: record.metadata ?? null
|
|
147
152
|
};
|
|
148
153
|
}
|
|
149
154
|
fromRow(row) {
|
|
@@ -170,8 +175,9 @@ var KyselyAuditStorage = class {
|
|
|
170
175
|
* Parse a JSON value that may already be parsed (e.g., from jsonb columns).
|
|
171
176
|
*/
|
|
172
177
|
parseJson(value) {
|
|
173
|
-
if (typeof value === "object") return value;
|
|
174
|
-
return JSON.parse(value);
|
|
178
|
+
if (typeof value === "object" && value !== null) return value;
|
|
179
|
+
if (typeof value === "string") return JSON.parse(value);
|
|
180
|
+
return {};
|
|
175
181
|
}
|
|
176
182
|
getActorData(actor) {
|
|
177
183
|
const { id, type,...rest } = actor;
|
package/dist/kysely.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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","query: any","record: AuditRecord","value: string | object","actor: NonNullable<AuditRecord['actor']>","entityId: string"],"sources":["../src/kysely.ts"],"sourcesContent":["import type {\n ControlledTransaction,\n IsolationLevel,\n Kysely,\n Transaction,\n} from 'kysely';\nimport type { AuditQueryOptions, AuditStorage } from './storage';\nimport type { AuditRecord } from './types';\n\n/**\n * Minimal interface for transaction-aware audit flushing.\n * Use this when you need to flush audits within a database transaction.\n *\n * @template TTransaction - Transaction type (e.g., Kysely Transaction)\n *\n * @example\n * ```typescript\n * import { withAuditableTransaction } from '@geekmidas/audit/kysely';\n * import type { TransactionAwareAuditor } from '@geekmidas/audit/kysely';\n *\n * const result = await withAuditableTransaction(\n * db,\n * auditor as TransactionAwareAuditor<Transaction<DB>>,\n * async (trx) => {\n * // Your transactional operations\n * return result;\n * },\n * );\n * ```\n */\nexport interface TransactionAwareAuditor<TTransaction = unknown> {\n /** Register the transaction with the auditor for use during flush */\n setTransaction(trx: TTransaction): void;\n /** Flush all pending audits, optionally within a transaction */\n flush(trx?: TTransaction): Promise<void>;\n}\n\nexport interface TransactionSettings {\n isolationLevel?: IsolationLevel;\n}\n\nexport type DatabaseConnection<T> =\n | ControlledTransaction<T>\n | Kysely<T>\n | 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 db: DatabaseConnection<DB>,\n auditor: TransactionAwareAuditor<Transaction<DB>>,\n cb: (trx: Transaction<DB>) => Promise<T>,\n settings?: TransactionSettings,\n): Promise<T> {\n const execute = async (trx: Transaction<DB>): Promise<T> => {\n // Register transaction with auditor\n auditor.setTransaction(trx);\n\n // Execute the callback\n const result = await cb(trx);\n\n // Flush audits BEFORE transaction commits\n // If this fails, the transaction will roll back\n await auditor.flush(trx);\n\n return result;\n };\n\n // If already in a transaction, just run with it\n if (db.isTransaction) {\n return execute(db as Transaction<DB>);\n }\n\n const builder = db.transaction();\n\n if (settings?.isolationLevel) {\n return builder.setIsolationLevel(settings.isolationLevel).execute(execute);\n }\n\n return 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 * @example\n * ```typescript\n * interface Database {\n * audit_logs: AuditLogTable;\n * // ... other tables\n * }\n * ```\n */\nexport interface AuditLogTable {\n id: string;\n type: string;\n operation: string;\n table: string | null;\n entityId: string | null;\n oldValues: string | null;\n newValues: string | null;\n payload: string | null;\n timestamp: Date;\n actorId: string | null;\n actorType: string | null;\n actorData: string | null;\n metadata: string | null;\n}\n\n/**\n * Configuration for KyselyAuditStorage.\n */\nexport interface KyselyAuditStorageConfig<DB> {\n /** Kysely database instance */\n db: Kysely<DB>;\n /** Table name for audit logs (must be a key in DB that extends AuditLogTable) */\n tableName: keyof DB & string;\n /**\n * Service name of the database service.\n * When set, endpoint adaptors will automatically use the audit transaction as `db`\n * in the handler context if the endpoint's database service has the same name.\n */\n databaseServiceName?: string;\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 private readonly db: Kysely<DB>;\n private readonly tableName: keyof DB & string;\n readonly databaseServiceName?: string;\n\n constructor(config: KyselyAuditStorageConfig<DB>) {\n this.db = config.db;\n this.tableName = config.tableName;\n this.databaseServiceName = config.databaseServiceName;\n }\n\n async write(records: AuditRecord[], trx?: unknown): Promise<void> {\n if (records.length === 0) {\n return;\n }\n\n const db = (trx as Transaction<DB>) ?? this.db;\n const rows = records.map((record) => this.toRow(record));\n\n await (db as any).insertInto(this.tableName).values(rows).execute();\n }\n\n async query(options: AuditQueryOptions): Promise<AuditRecord[]> {\n let query = (this.db as any).selectFrom(this.tableName).selectAll();\n\n query = this.applyFilters(query, options);\n\n // Ordering\n const orderBy = options.orderBy ?? 'timestamp';\n const orderDirection = options.orderDirection ?? 'desc';\n query = query.orderBy(\n orderBy === 'timestamp' ? 'timestamp' : 'type',\n orderDirection,\n );\n\n // Pagination\n if (options.limit !== undefined) {\n query = query.limit(options.limit);\n }\n if (options.offset !== undefined) {\n query = query.offset(options.offset);\n }\n\n const rows = await query.execute();\n return rows.map((row: AuditLogTable) => this.fromRow(row));\n }\n\n async count(\n options: Omit<AuditQueryOptions, 'limit' | 'offset'>,\n ): Promise<number> {\n let query = (this.db as any)\n .selectFrom(this.tableName)\n .select((eb: any) => eb.fn.count('id').as('count'));\n\n query = this.applyFilters(query, options);\n\n const result = await query.executeTakeFirst();\n return Number(result?.count ?? 0);\n }\n\n /**\n * Get the Kysely database instance for transactional operations.\n * Used by endpoint adaptors to automatically wrap handlers in transactions.\n */\n getDatabase(): Kysely<DB> {\n return this.db;\n }\n\n private applyFilters(query: any, options: AuditQueryOptions): any {\n // Type filter\n if (options.type !== undefined) {\n if (Array.isArray(options.type)) {\n query = query.where('type', 'in', options.type);\n } else {\n query = query.where('type', '=', options.type);\n }\n }\n\n // Entity ID filter\n if (options.entityId !== undefined) {\n const entityId =\n typeof options.entityId === 'string'\n ? options.entityId\n : JSON.stringify(options.entityId);\n query = query.where('entityId', '=', entityId);\n }\n\n // Table filter\n if (options.table !== undefined) {\n query = query.where('table', '=', options.table);\n }\n\n // Actor ID filter\n if (options.actorId !== undefined) {\n query = query.where('actorId', '=', options.actorId);\n }\n\n // Date range filters\n if (options.from !== undefined) {\n query = query.where('timestamp', '>=', options.from);\n }\n if (options.to !== undefined) {\n query = query.where('timestamp', '<=', options.to);\n }\n\n return query;\n }\n\n private toRow(record: AuditRecord): AuditLogTable {\n return {\n id: record.id,\n type: record.type,\n operation: record.operation,\n table: record.table ?? null,\n entityId:\n record.entityId === undefined\n ? null\n : typeof record.entityId === 'string'\n ? record.entityId\n : JSON.stringify(record.entityId),\n oldValues:\n record.oldValues !== undefined\n ? JSON.stringify(record.oldValues)\n : null,\n newValues:\n record.newValues !== undefined\n ? JSON.stringify(record.newValues)\n : null,\n payload:\n record.payload !== undefined ? JSON.stringify(record.payload) : null,\n timestamp: record.timestamp,\n actorId: record.actor?.id ?? null,\n actorType: record.actor?.type ?? null,\n actorData:\n record.actor !== undefined\n ? JSON.stringify(this.getActorData(record.actor))\n : null,\n metadata:\n record.metadata !== undefined ? JSON.stringify(record.metadata) : null,\n };\n }\n\n private fromRow(row: AuditLogTable): AuditRecord {\n const actor =\n row.actorId !== null || row.actorType !== null\n ? {\n id: row.actorId ?? undefined,\n type: row.actorType ?? undefined,\n ...(row.actorData ? this.parseJson(row.actorData) : {}),\n }\n : undefined;\n\n return {\n id: row.id,\n type: row.type,\n operation: row.operation as AuditRecord['operation'],\n table: row.table ?? undefined,\n entityId: row.entityId ? this.parseEntityId(row.entityId) : undefined,\n oldValues: row.oldValues ? this.parseJson(row.oldValues) : undefined,\n newValues: row.newValues ? this.parseJson(row.newValues) : undefined,\n payload: row.payload ? this.parseJson(row.payload) : undefined,\n timestamp: row.timestamp,\n actor,\n metadata: row.metadata ? this.parseJson(row.metadata) : undefined,\n };\n }\n\n /**\n * Parse a JSON value that may already be parsed (e.g., from jsonb columns).\n */\n private parseJson(value: string | object): Record<string, unknown> {\n if (typeof value === 'object') {\n return value as Record<string, unknown>;\n }\n return JSON.parse(value);\n }\n\n private getActorData(\n actor: NonNullable<AuditRecord['actor']>,\n ): Record<string, unknown> {\n const { id, type, ...rest } = actor;\n return rest;\n }\n\n private parseEntityId(entityId: string): string | Record<string, unknown> {\n try {\n const parsed = JSON.parse(entityId);\n if (typeof parsed === 'object' && parsed !== null) {\n return parsed;\n }\n return entityId;\n } catch {\n return entityId;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyFA,eAAsB,yBACpBA,IACAC,SACAC,IACAC,UACY;CACZ,MAAM,UAAU,OAAOC,QAAqC;AAE1D,UAAQ,eAAe,IAAI;EAG3B,MAAM,SAAS,MAAM,GAAG,IAAI;AAI5B,QAAM,QAAQ,MAAM,IAAI;AAExB,SAAO;CACR;AAGD,KAAI,GAAG,cACL,QAAO,QAAQ,GAAsB;CAGvC,MAAM,UAAU,GAAG,aAAa;AAEhC,KAAI,UAAU,eACZ,QAAO,QAAQ,kBAAkB,SAAS,eAAe,CAAC,QAAQ,QAAQ;AAG5E,QAAO,QAAQ,QAAQ,QAAQ;AAChC;;;;;;;;;;;;;;;;;;;;;;;;AAqED,IAAa,qBAAb,MAA4D;CAC1D,AAAiB;CACjB,AAAiB;CACjB,AAAS;CAET,YAAYC,QAAsC;AAChD,OAAK,KAAK,OAAO;AACjB,OAAK,YAAY,OAAO;AACxB,OAAK,sBAAsB,OAAO;CACnC;CAED,MAAM,MAAMC,SAAwBC,KAA8B;AAChE,MAAI,QAAQ,WAAW,EACrB;EAGF,MAAM,KAAM,OAA2B,KAAK;EAC5C,MAAM,OAAO,QAAQ,IAAI,CAAC,WAAW,KAAK,MAAM,OAAO,CAAC;AAExD,QAAM,AAAC,GAAW,WAAW,KAAK,UAAU,CAAC,OAAO,KAAK,CAAC,SAAS;CACpE;CAED,MAAM,MAAMC,SAAoD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AAI;GACf;GACA,UAAU,IAAI,WAAW,KAAK,UAAU,IAAI,SAAS;EACtD;CACF;;;;CAKD,AAAQ,UAAUK,OAAiD;AACjE,aAAW,UAAU,SACnB,QAAO;AAET,SAAO,KAAK,MAAM,MAAM;CACzB;CAED,AAAQ,aACNC,OACyB;EACzB,MAAM,EAAE,IAAI,KAAM,GAAG,MAAM,GAAG;AAC9B,SAAO;CACR;CAED,AAAQ,cAAcC,UAAoD;AACxE,MAAI;GACF,MAAM,SAAS,KAAK,MAAM,SAAS;AACnC,cAAW,WAAW,YAAY,WAAW,KAC3C,QAAO;AAET,UAAO;EACR,QAAO;AACN,UAAO;EACR;CACF;AACF"}
|
|
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","query: any","record: AuditRecord","value: unknown","actor: NonNullable<AuditRecord['actor']>","entityId: string"],"sources":["../src/kysely.ts"],"sourcesContent":["import type {\n ControlledTransaction,\n IsolationLevel,\n Kysely,\n Transaction,\n} from 'kysely';\nimport { nanoid } from 'nanoid';\nimport type { AuditQueryOptions, AuditStorage } from './storage';\nimport type { AuditRecord } from './types';\n\n/**\n * Minimal interface for transaction-aware audit flushing.\n * Use this when you need to flush audits within a database transaction.\n *\n * @template TTransaction - Transaction type (e.g., Kysely Transaction)\n *\n * @example\n * ```typescript\n * import { withAuditableTransaction } from '@geekmidas/audit/kysely';\n * import type { TransactionAwareAuditor } from '@geekmidas/audit/kysely';\n *\n * const result = await withAuditableTransaction(\n * db,\n * auditor as TransactionAwareAuditor<Transaction<DB>>,\n * async (trx) => {\n * // Your transactional operations\n * return result;\n * },\n * );\n * ```\n */\nexport interface TransactionAwareAuditor<TTransaction = unknown> {\n /** Register the transaction with the auditor for use during flush */\n setTransaction(trx: TTransaction): void;\n /** Flush all pending audits, optionally within a transaction */\n flush(trx?: TTransaction): Promise<void>;\n}\n\nexport interface TransactionSettings {\n isolationLevel?: IsolationLevel;\n}\n\nexport type DatabaseConnection<T> =\n | ControlledTransaction<T>\n | Kysely<T>\n | 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 db: DatabaseConnection<DB>,\n auditor: TransactionAwareAuditor<Transaction<DB>>,\n cb: (trx: Transaction<DB>) => Promise<T>,\n settings?: TransactionSettings,\n): Promise<T> {\n const execute = async (trx: Transaction<DB>): Promise<T> => {\n // Register transaction with auditor\n auditor.setTransaction(trx);\n\n // Execute the callback\n const result = await cb(trx);\n\n // Flush audits BEFORE transaction commits\n // If this fails, the transaction will roll back\n await auditor.flush(trx);\n\n return result;\n };\n\n // If already in a transaction, just run with it\n if (db.isTransaction) {\n return execute(db as Transaction<DB>);\n }\n\n const builder = db.transaction();\n\n if (settings?.isolationLevel) {\n return builder.setIsolationLevel(settings.isolationLevel).execute(execute);\n }\n\n return 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 id: string;\n type: string;\n operation: string;\n table: string | null;\n entityId: string | null;\n oldValues: unknown | null;\n newValues: unknown | null;\n payload: unknown | null;\n timestamp: Date;\n actorId: string | null;\n actorType: string | null;\n actorData: unknown | null;\n metadata: 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 id?: string;\n};\n\n/**\n * Configuration for KyselyAuditStorage.\n */\nexport interface KyselyAuditStorageConfig<DB> {\n /** Kysely database instance */\n db: Kysely<DB>;\n /** Table name for audit logs (must be a key in DB that extends AuditLogTable) */\n tableName: keyof DB & string;\n /**\n * Service name of the database service.\n * When set, endpoint adaptors will automatically use the audit transaction as `db`\n * in the handler context if the endpoint's database service has the same name.\n */\n databaseServiceName?: string;\n /**\n * Let the database auto-generate IDs (e.g., via DEFAULT gen_random_uuid()).\n * When true, the ID field is omitted from inserts if not provided.\n * When false (default), IDs are generated using nanoid if not provided.\n * @default false\n */\n autoId?: 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 private readonly db: Kysely<DB>;\n private readonly tableName: keyof DB & string;\n private readonly autoId: boolean;\n readonly databaseServiceName?: string;\n\n constructor(config: KyselyAuditStorageConfig<DB>) {\n this.db = config.db;\n this.tableName = config.tableName;\n this.databaseServiceName = config.databaseServiceName;\n this.autoId = config.autoId ?? false;\n }\n\n async write(records: AuditRecord[], trx?: unknown): Promise<void> {\n if (records.length === 0) {\n return;\n }\n\n const db = (trx as Transaction<DB>) ?? this.db;\n const rows = records.map((record) => this.toRow(record));\n\n await (db as any).insertInto(this.tableName).values(rows).execute();\n }\n\n async query(options: AuditQueryOptions): Promise<AuditRecord[]> {\n let query = (this.db as any).selectFrom(this.tableName).selectAll();\n\n query = this.applyFilters(query, options);\n\n // Ordering\n const orderBy = options.orderBy ?? 'timestamp';\n const orderDirection = options.orderDirection ?? 'desc';\n query = query.orderBy(\n orderBy === 'timestamp' ? 'timestamp' : 'type',\n orderDirection,\n );\n\n // Pagination\n if (options.limit !== undefined) {\n query = query.limit(options.limit);\n }\n if (options.offset !== undefined) {\n query = query.offset(options.offset);\n }\n\n const rows = await query.execute();\n return rows.map((row: AuditLogTable) => this.fromRow(row));\n }\n\n async count(\n options: Omit<AuditQueryOptions, 'limit' | 'offset'>,\n ): Promise<number> {\n let query = (this.db as any)\n .selectFrom(this.tableName)\n .select((eb: any) => eb.fn.count('id').as('count'));\n\n query = this.applyFilters(query, options);\n\n const result = await query.executeTakeFirst();\n return Number(result?.count ?? 0);\n }\n\n /**\n * Get the Kysely database instance for transactional operations.\n * Used by endpoint adaptors to automatically wrap handlers in transactions.\n */\n getDatabase(): Kysely<DB> {\n return this.db;\n }\n\n private applyFilters(query: any, options: AuditQueryOptions): any {\n // Type filter\n if (options.type !== undefined) {\n if (Array.isArray(options.type)) {\n query = query.where('type', 'in', options.type);\n } else {\n query = query.where('type', '=', options.type);\n }\n }\n\n // Entity ID filter\n if (options.entityId !== undefined) {\n const entityId =\n typeof options.entityId === 'string'\n ? options.entityId\n : JSON.stringify(options.entityId);\n query = query.where('entityId', '=', entityId);\n }\n\n // Table filter\n if (options.table !== undefined) {\n query = query.where('table', '=', options.table);\n }\n\n // Actor ID filter\n if (options.actorId !== undefined) {\n query = query.where('actorId', '=', options.actorId);\n }\n\n // Date range filters\n if (options.from !== undefined) {\n query = query.where('timestamp', '>=', options.from);\n }\n if (options.to !== undefined) {\n query = query.where('timestamp', '<=', options.to);\n }\n\n return query;\n }\n\n private toRow(record: AuditRecord): AuditLogTable {\n // If autoId is true, let database generate ID (omit if not provided)\n // If autoId is false (default), generate with nanoid if not provided\n const id = record.id || (this.autoId ? undefined : nanoid());\n\n return {\n ...(id && { id }),\n type: record.type,\n operation: record.operation,\n table: record.table ?? null,\n entityId:\n record.entityId === undefined\n ? null\n : typeof record.entityId === 'string'\n ? record.entityId\n : JSON.stringify(record.entityId),\n oldValues: record.oldValues ?? null,\n newValues: record.newValues ?? null,\n payload: record.payload ?? null,\n timestamp: record.timestamp,\n actorId: record.actor?.id ?? null,\n actorType: record.actor?.type ?? null,\n actorData:\n record.actor !== undefined ? this.getActorData(record.actor) : null,\n metadata: record.metadata ?? null,\n } as AuditLogTable;\n }\n\n private fromRow(row: AuditLogTable): AuditRecord {\n const actor =\n row.actorId !== null || row.actorType !== null\n ? {\n id: row.actorId ?? undefined,\n type: row.actorType ?? undefined,\n ...(row.actorData ? this.parseJson(row.actorData) : {}),\n }\n : undefined;\n\n return {\n id: row.id,\n type: row.type,\n operation: row.operation as AuditRecord['operation'],\n table: row.table ?? undefined,\n entityId: row.entityId ? this.parseEntityId(row.entityId) : undefined,\n oldValues: row.oldValues ? this.parseJson(row.oldValues) : undefined,\n newValues: row.newValues ? this.parseJson(row.newValues) : undefined,\n payload: row.payload ? this.parseJson(row.payload) : undefined,\n timestamp: row.timestamp,\n actor,\n metadata: row.metadata ? this.parseJson(row.metadata) : undefined,\n };\n }\n\n /**\n * Parse a JSON value that may already be parsed (e.g., from jsonb columns).\n */\n private parseJson(value: unknown): Record<string, unknown> {\n if (typeof value === 'object' && value !== null) {\n return value as Record<string, unknown>;\n }\n if (typeof value === 'string') {\n return JSON.parse(value);\n }\n return {};\n }\n\n private getActorData(\n actor: NonNullable<AuditRecord['actor']>,\n ): Record<string, unknown> {\n const { id, type, ...rest } = actor;\n return rest;\n }\n\n private parseEntityId(entityId: string): string | Record<string, unknown> {\n try {\n const parsed = JSON.parse(entityId);\n if (typeof parsed === 'object' && parsed !== null) {\n return parsed;\n }\n return entityId;\n } catch {\n return entityId;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0FA,eAAsB,yBACpBA,IACAC,SACAC,IACAC,UACY;CACZ,MAAM,UAAU,OAAOC,QAAqC;AAE1D,UAAQ,eAAe,IAAI;EAG3B,MAAM,SAAS,MAAM,GAAG,IAAI;AAI5B,QAAM,QAAQ,MAAM,IAAI;AAExB,SAAO;CACR;AAGD,KAAI,GAAG,cACL,QAAO,QAAQ,GAAsB;CAGvC,MAAM,UAAU,GAAG,aAAa;AAEhC,KAAI,UAAU,eACZ,QAAO,QAAQ,kBAAkB,SAAS,eAAe,CAAC,QAAQ,QAAQ;AAG5E,QAAO,QAAQ,QAAQ,QAAQ;AAChC;;;;;;;;;;;;;;;;;;;;;;;;AAgGD,IAAa,qBAAb,MAA4D;CAC1D,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAS;CAET,YAAYC,QAAsC;AAChD,OAAK,KAAK,OAAO;AACjB,OAAK,YAAY,OAAO;AACxB,OAAK,sBAAsB,OAAO;AAClC,OAAK,SAAS,OAAO,UAAU;CAChC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GACX,UAAU,IAAI,WAAW,KAAK,cAAc,IAAI,SAAS;GACzD,WAAW,IAAI,YAAY,KAAK,UAAU,IAAI,UAAU;GACxD,WAAW,IAAI,YAAY,KAAK,UAAU,IAAI,UAAU;GACxD,SAAS,IAAI,UAAU,KAAK,UAAU,IAAI,QAAQ;GAClD,WAAW,IAAI;GACf;GACA,UAAU,IAAI,WAAW,KAAK,UAAU,IAAI,SAAS;EACtD;CACF;;;;CAKD,AAAQ,UAAUK,OAAyC;AACzD,aAAW,UAAU,YAAY,UAAU,KACzC,QAAO;AAET,aAAW,UAAU,SACnB,QAAO,KAAK,MAAM,MAAM;AAE1B,SAAO,CAAE;CACV;CAED,AAAQ,aACNC,OACyB;EACzB,MAAM,EAAE,IAAI,KAAM,GAAG,MAAM,GAAG;AAC9B,SAAO;CACR;CAED,AAAQ,cAAcC,UAAoD;AACxE,MAAI;GACF,MAAM,SAAS,KAAK,MAAM,SAAS;AACnC,cAAW,WAAW,YAAY,WAAW,KAC3C,QAAO;AAET,UAAO;EACR,QAAO;AACN,UAAO;EACR;CACF;AACF"}
|
package/package.json
CHANGED
|
@@ -76,10 +76,10 @@ describe('KyselyAuditStorage', () => {
|
|
|
76
76
|
operation: 'INSERT',
|
|
77
77
|
table: 'users',
|
|
78
78
|
entityId: 'user-123',
|
|
79
|
-
payload:
|
|
79
|
+
payload: { email: 'test@example.com' },
|
|
80
80
|
actorId: 'admin-1',
|
|
81
81
|
actorType: 'admin',
|
|
82
|
-
metadata:
|
|
82
|
+
metadata: { requestId: 'req-123' },
|
|
83
83
|
}),
|
|
84
84
|
]);
|
|
85
85
|
});
|
|
@@ -155,10 +155,93 @@ describe('KyselyAuditStorage', () => {
|
|
|
155
155
|
expect.objectContaining({
|
|
156
156
|
actorId: 'user-1',
|
|
157
157
|
actorType: 'user',
|
|
158
|
-
actorData:
|
|
158
|
+
actorData: {
|
|
159
159
|
email: 'user@example.com',
|
|
160
160
|
role: 'admin',
|
|
161
|
-
}
|
|
161
|
+
},
|
|
162
|
+
}),
|
|
163
|
+
]);
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
it('should generate ID with nanoid when autoId is false (default)', async () => {
|
|
167
|
+
const records: AuditRecord[] = [
|
|
168
|
+
{
|
|
169
|
+
id: '', // Empty ID
|
|
170
|
+
type: 'user.created',
|
|
171
|
+
operation: 'CUSTOM',
|
|
172
|
+
timestamp: new Date(),
|
|
173
|
+
},
|
|
174
|
+
];
|
|
175
|
+
|
|
176
|
+
await storage.write(records);
|
|
177
|
+
|
|
178
|
+
const calledValues = mockDb.insertBuilder.values.mock.calls[0][0];
|
|
179
|
+
expect(calledValues[0].id).toBeDefined();
|
|
180
|
+
expect(calledValues[0].id.length).toBeGreaterThan(0);
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
it('should use provided ID when autoId is false (default)', async () => {
|
|
184
|
+
const records: AuditRecord[] = [
|
|
185
|
+
{
|
|
186
|
+
id: 'my-custom-id',
|
|
187
|
+
type: 'user.created',
|
|
188
|
+
operation: 'CUSTOM',
|
|
189
|
+
timestamp: new Date(),
|
|
190
|
+
},
|
|
191
|
+
];
|
|
192
|
+
|
|
193
|
+
await storage.write(records);
|
|
194
|
+
|
|
195
|
+
expect(mockDb.insertBuilder.values).toHaveBeenCalledWith([
|
|
196
|
+
expect.objectContaining({
|
|
197
|
+
id: 'my-custom-id',
|
|
198
|
+
}),
|
|
199
|
+
]);
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
it('should omit ID when autoId is true and no ID provided', async () => {
|
|
203
|
+
const storageAutoId = new KyselyAuditStorage({
|
|
204
|
+
db: mockDb.db as any,
|
|
205
|
+
tableName: 'audit_logs',
|
|
206
|
+
autoId: true,
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
const records: AuditRecord[] = [
|
|
210
|
+
{
|
|
211
|
+
id: '', // Empty ID - let database generate
|
|
212
|
+
type: 'user.created',
|
|
213
|
+
operation: 'CUSTOM',
|
|
214
|
+
timestamp: new Date(),
|
|
215
|
+
},
|
|
216
|
+
];
|
|
217
|
+
|
|
218
|
+
await storageAutoId.write(records);
|
|
219
|
+
|
|
220
|
+
const calledValues = mockDb.insertBuilder.values.mock.calls[0][0];
|
|
221
|
+
expect(calledValues[0].id).toBeUndefined();
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
it('should use provided ID when autoId is true', async () => {
|
|
225
|
+
const storageAutoId = new KyselyAuditStorage({
|
|
226
|
+
db: mockDb.db as any,
|
|
227
|
+
tableName: 'audit_logs',
|
|
228
|
+
autoId: true,
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
const records: AuditRecord[] = [
|
|
232
|
+
{
|
|
233
|
+
id: 'explicit-id',
|
|
234
|
+
type: 'user.created',
|
|
235
|
+
operation: 'CUSTOM',
|
|
236
|
+
timestamp: new Date(),
|
|
237
|
+
},
|
|
238
|
+
];
|
|
239
|
+
|
|
240
|
+
await storageAutoId.write(records);
|
|
241
|
+
|
|
242
|
+
expect(mockDb.insertBuilder.values).toHaveBeenCalledWith([
|
|
243
|
+
expect.objectContaining({
|
|
244
|
+
id: 'explicit-id',
|
|
162
245
|
}),
|
|
163
246
|
]);
|
|
164
247
|
});
|
package/src/kysely.ts
CHANGED
|
@@ -4,6 +4,7 @@ import type {
|
|
|
4
4
|
Kysely,
|
|
5
5
|
Transaction,
|
|
6
6
|
} from 'kysely';
|
|
7
|
+
import { nanoid } from 'nanoid';
|
|
7
8
|
import type { AuditQueryOptions, AuditStorage } from './storage';
|
|
8
9
|
import type { AuditRecord } from './types';
|
|
9
10
|
|
|
@@ -125,6 +126,8 @@ export async function withAuditableTransaction<DB, T>(
|
|
|
125
126
|
* Database table interface for audit records.
|
|
126
127
|
* Use this to define your audit_logs table in your Kysely database schema.
|
|
127
128
|
*
|
|
129
|
+
* Column names use snake_case to match standard PostgreSQL conventions.
|
|
130
|
+
*
|
|
128
131
|
* @example
|
|
129
132
|
* ```typescript
|
|
130
133
|
* interface Database {
|
|
@@ -139,16 +142,34 @@ export interface AuditLogTable {
|
|
|
139
142
|
operation: string;
|
|
140
143
|
table: string | null;
|
|
141
144
|
entityId: string | null;
|
|
142
|
-
oldValues:
|
|
143
|
-
newValues:
|
|
144
|
-
payload:
|
|
145
|
+
oldValues: unknown | null;
|
|
146
|
+
newValues: unknown | null;
|
|
147
|
+
payload: unknown | null;
|
|
145
148
|
timestamp: Date;
|
|
146
149
|
actorId: string | null;
|
|
147
150
|
actorType: string | null;
|
|
148
|
-
actorData:
|
|
149
|
-
metadata:
|
|
151
|
+
actorData: unknown | null;
|
|
152
|
+
metadata: unknown | null;
|
|
150
153
|
}
|
|
151
154
|
|
|
155
|
+
/**
|
|
156
|
+
* Insertable version of AuditLogTable where id is optional.
|
|
157
|
+
* Use this when your database auto-generates IDs or when using autoId option.
|
|
158
|
+
*
|
|
159
|
+
* @example
|
|
160
|
+
* ```typescript
|
|
161
|
+
* interface Database {
|
|
162
|
+
* audit_logs: AuditLogTable;
|
|
163
|
+
* }
|
|
164
|
+
*
|
|
165
|
+
* // For insertions where id is auto-generated
|
|
166
|
+
* type NewAuditLog = InsertableAuditLogTable;
|
|
167
|
+
* ```
|
|
168
|
+
*/
|
|
169
|
+
export type InsertableAuditLogTable = Omit<AuditLogTable, 'id'> & {
|
|
170
|
+
id?: string;
|
|
171
|
+
};
|
|
172
|
+
|
|
152
173
|
/**
|
|
153
174
|
* Configuration for KyselyAuditStorage.
|
|
154
175
|
*/
|
|
@@ -163,6 +184,13 @@ export interface KyselyAuditStorageConfig<DB> {
|
|
|
163
184
|
* in the handler context if the endpoint's database service has the same name.
|
|
164
185
|
*/
|
|
165
186
|
databaseServiceName?: string;
|
|
187
|
+
/**
|
|
188
|
+
* Let the database auto-generate IDs (e.g., via DEFAULT gen_random_uuid()).
|
|
189
|
+
* When true, the ID field is omitted from inserts if not provided.
|
|
190
|
+
* When false (default), IDs are generated using nanoid if not provided.
|
|
191
|
+
* @default false
|
|
192
|
+
*/
|
|
193
|
+
autoId?: boolean;
|
|
166
194
|
}
|
|
167
195
|
|
|
168
196
|
/**
|
|
@@ -191,12 +219,14 @@ export interface KyselyAuditStorageConfig<DB> {
|
|
|
191
219
|
export class KyselyAuditStorage<DB> implements AuditStorage {
|
|
192
220
|
private readonly db: Kysely<DB>;
|
|
193
221
|
private readonly tableName: keyof DB & string;
|
|
222
|
+
private readonly autoId: boolean;
|
|
194
223
|
readonly databaseServiceName?: string;
|
|
195
224
|
|
|
196
225
|
constructor(config: KyselyAuditStorageConfig<DB>) {
|
|
197
226
|
this.db = config.db;
|
|
198
227
|
this.tableName = config.tableName;
|
|
199
228
|
this.databaseServiceName = config.databaseServiceName;
|
|
229
|
+
this.autoId = config.autoId ?? false;
|
|
200
230
|
}
|
|
201
231
|
|
|
202
232
|
async write(records: AuditRecord[], trx?: unknown): Promise<void> {
|
|
@@ -297,8 +327,12 @@ export class KyselyAuditStorage<DB> implements AuditStorage {
|
|
|
297
327
|
}
|
|
298
328
|
|
|
299
329
|
private toRow(record: AuditRecord): AuditLogTable {
|
|
330
|
+
// If autoId is true, let database generate ID (omit if not provided)
|
|
331
|
+
// If autoId is false (default), generate with nanoid if not provided
|
|
332
|
+
const id = record.id || (this.autoId ? undefined : nanoid());
|
|
333
|
+
|
|
300
334
|
return {
|
|
301
|
-
id
|
|
335
|
+
...(id && { id }),
|
|
302
336
|
type: record.type,
|
|
303
337
|
operation: record.operation,
|
|
304
338
|
table: record.table ?? null,
|
|
@@ -308,26 +342,16 @@ export class KyselyAuditStorage<DB> implements AuditStorage {
|
|
|
308
342
|
: typeof record.entityId === 'string'
|
|
309
343
|
? record.entityId
|
|
310
344
|
: JSON.stringify(record.entityId),
|
|
311
|
-
oldValues:
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
: null,
|
|
315
|
-
newValues:
|
|
316
|
-
record.newValues !== undefined
|
|
317
|
-
? JSON.stringify(record.newValues)
|
|
318
|
-
: null,
|
|
319
|
-
payload:
|
|
320
|
-
record.payload !== undefined ? JSON.stringify(record.payload) : null,
|
|
345
|
+
oldValues: record.oldValues ?? null,
|
|
346
|
+
newValues: record.newValues ?? null,
|
|
347
|
+
payload: record.payload ?? null,
|
|
321
348
|
timestamp: record.timestamp,
|
|
322
349
|
actorId: record.actor?.id ?? null,
|
|
323
350
|
actorType: record.actor?.type ?? null,
|
|
324
351
|
actorData:
|
|
325
|
-
record.actor !== undefined
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
metadata:
|
|
329
|
-
record.metadata !== undefined ? JSON.stringify(record.metadata) : null,
|
|
330
|
-
};
|
|
352
|
+
record.actor !== undefined ? this.getActorData(record.actor) : null,
|
|
353
|
+
metadata: record.metadata ?? null,
|
|
354
|
+
} as AuditLogTable;
|
|
331
355
|
}
|
|
332
356
|
|
|
333
357
|
private fromRow(row: AuditLogTable): AuditRecord {
|
|
@@ -358,11 +382,14 @@ export class KyselyAuditStorage<DB> implements AuditStorage {
|
|
|
358
382
|
/**
|
|
359
383
|
* Parse a JSON value that may already be parsed (e.g., from jsonb columns).
|
|
360
384
|
*/
|
|
361
|
-
private parseJson(value:
|
|
362
|
-
if (typeof value === 'object') {
|
|
385
|
+
private parseJson(value: unknown): Record<string, unknown> {
|
|
386
|
+
if (typeof value === 'object' && value !== null) {
|
|
363
387
|
return value as Record<string, unknown>;
|
|
364
388
|
}
|
|
365
|
-
|
|
389
|
+
if (typeof value === 'string') {
|
|
390
|
+
return JSON.parse(value);
|
|
391
|
+
}
|
|
392
|
+
return {};
|
|
366
393
|
}
|
|
367
394
|
|
|
368
395
|
private getActorData(
|