@geekmidas/audit 2.1.0 → 2.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -0
- package/README.md +74 -2
- package/dist/{Auditor-_Dn2dp8d.d.mts → Auditor-CW2NrfHS.d.mts} +30 -2
- package/dist/Auditor-CW2NrfHS.d.mts.map +1 -0
- package/dist/{Auditor-sW7YAJIA.d.cts → Auditor-DpBHXIJM.d.cts} +30 -2
- package/dist/Auditor-DpBHXIJM.d.cts.map +1 -0
- package/dist/Auditor.d.cts +1 -1
- package/dist/Auditor.d.mts +1 -1
- package/dist/{DefaultAuditor-BSYMwojG.d.cts → DefaultAuditor-DlJ1ENfx.d.mts} +2 -2
- package/dist/{DefaultAuditor-BSYMwojG.d.cts.map → DefaultAuditor-DlJ1ENfx.d.mts.map} +1 -1
- package/dist/{DefaultAuditor-CYE-uAry.d.mts → DefaultAuditor-GRFI86N_.d.cts} +2 -2
- package/dist/{DefaultAuditor-CYE-uAry.d.mts.map → DefaultAuditor-GRFI86N_.d.cts.map} +1 -1
- package/dist/DefaultAuditor.d.cts +2 -2
- package/dist/DefaultAuditor.d.mts +2 -2
- package/dist/{cache-2VI80Vao.d.mts → cache-Bih6HxY6.d.cts} +2 -2
- package/dist/{cache-2VI80Vao.d.mts.map → cache-Bih6HxY6.d.cts.map} +1 -1
- package/dist/{cache-CDHqXqcl.d.cts → cache-wET57t6d.d.mts} +2 -2
- package/dist/{cache-CDHqXqcl.d.cts.map → cache-wET57t6d.d.mts.map} +1 -1
- package/dist/cache.d.cts +2 -2
- package/dist/cache.d.mts +2 -2
- package/dist/index.d.cts +2 -2
- package/dist/index.d.mts +2 -2
- package/dist/knex.cjs +233 -0
- package/dist/knex.cjs.map +1 -0
- package/dist/knex.d.cts +178 -0
- package/dist/knex.d.cts.map +1 -0
- package/dist/knex.d.mts +178 -0
- package/dist/knex.d.mts.map +1 -0
- package/dist/knex.mjs +231 -0
- package/dist/knex.mjs.map +1 -0
- package/dist/kysely.cjs.map +1 -1
- package/dist/kysely.d.cts +1 -29
- package/dist/kysely.d.cts.map +1 -1
- package/dist/kysely.d.mts +1 -29
- package/dist/kysely.d.mts.map +1 -1
- package/dist/kysely.mjs.map +1 -1
- package/dist/memory.d.cts +2 -2
- package/dist/memory.d.mts +2 -2
- package/dist/storage.d.cts +2 -2
- package/dist/storage.d.mts +2 -2
- package/dist/types.d.cts +1 -1
- package/dist/types.d.mts +1 -1
- package/package.json +20 -5
- package/src/__tests__/KnexAuditStorage.integration.spec.ts +739 -0
- package/src/knex.ts +430 -0
- package/src/kysely.ts +6 -28
- package/src/storage.ts +28 -0
- package/dist/Auditor-_Dn2dp8d.d.mts.map +0 -1
- package/dist/Auditor-sW7YAJIA.d.cts.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"knex.cjs","names":["connection: DatabaseConnection","db: DatabaseConnection","auditor: TransactionAwareAuditor<Knex.Transaction>","cb: (trx: Knex.Transaction) => Promise<T>","settings?: TransactionSettings","trx: Knex.Transaction","config: KnexAuditStorageConfig","records: AuditRecord[]","trx?: unknown","options: AuditQueryOptions","row: AuditLogTable","options: Omit<AuditQueryOptions, 'limit' | 'offset'>","callback: () => Promise<T>","db?: DatabaseConnection","query: any","record: AuditRecord","value: unknown","actor: NonNullable<AuditRecord['actor']>","entityId: string"],"sources":["../src/knex.ts"],"sourcesContent":["import type { Knex } from 'knex';\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?: Knex.IsolationLevels;\n}\n\nexport type DatabaseConnection = Knex | Knex.Transaction;\n\n/**\n * Type guard for an active Knex transaction.\n *\n * Knex marks transaction instances with `isTransaction`, and a completed\n * transaction can no longer be used, so a settled transaction is treated as a\n * plain connection.\n */\nfunction isActiveTransaction(\n\tconnection: DatabaseConnection,\n): connection is Knex.Transaction {\n\treturn (\n\t\tconnection.isTransaction === true &&\n\t\t!(connection as Knex.Transaction).isCompleted()\n\t);\n}\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 (Knex instance or Transaction)\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/knex';\n *\n * const result = await withAuditableTransaction(\n * services.database,\n * auditor,\n * async (trx) => {\n * const [user] = await trx('users').insert(data).returning('*');\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<T>(\n\tdb: DatabaseConnection,\n\tauditor: TransactionAwareAuditor<Knex.Transaction>,\n\tcb: (trx: Knex.Transaction) => Promise<T>,\n\tsettings?: TransactionSettings,\n): Promise<T> {\n\tconst execute = async (trx: Knex.Transaction): 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\t// Knex would otherwise open a savepoint, which commits independently.\n\tif (isActiveTransaction(db)) {\n\t\treturn execute(db);\n\t}\n\n\treturn db.transaction(execute, settings);\n}\n\n/**\n * Shape of a row in the audit log table.\n * Use this to describe your audit table when declaring Knex table types.\n *\n * Property names are camelCase to match the Kysely storage. Pair this with\n * `knexSnakeCaseMappers()` if your database columns are snake_case.\n *\n * @example\n * ```typescript\n * import { knexSnakeCaseMappers } from 'objection';\n *\n * const db = knex({\n * client: 'pg',\n * connection: process.env.DATABASE_URL,\n * ...knexSnakeCaseMappers(),\n * });\n *\n * declare module 'knex/types/tables' {\n * interface Tables {\n * audit_logs: AuditLogTable;\n * }\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 the autoId option.\n */\nexport type InsertableAuditLogTable = Omit<AuditLogTable, 'id'> & {\n\tid?: string;\n};\n\n/**\n * Configuration for KnexAuditStorage.\n */\nexport interface KnexAuditStorageConfig {\n\t/** Knex database instance */\n\tdb: Knex;\n\t/** Table name for audit logs */\n\ttableName: 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 * Knex-based audit storage implementation.\n * Stores audit records in a database table using Knex.\n *\n * @example\n * ```typescript\n * const storage = new KnexAuditStorage({\n * db: knexDb,\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 KnexAuditStorage implements AuditStorage {\n\tprivate readonly db: Knex;\n\tprivate readonly tableName: string;\n\tprivate readonly autoId: boolean;\n\treadonly databaseServiceName?: string;\n\n\tconstructor(config: KnexAuditStorageConfig) {\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 Knex.Transaction) ?? this.db;\n\t\tconst rows = records.map((record) => this.toRow(record));\n\n\t\tawait db(this.tableName).insert(rows);\n\t}\n\n\tasync query(options: AuditQueryOptions): Promise<AuditRecord[]> {\n\t\tlet query = this.db(this.tableName).select('*');\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;\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(this.tableName).count({ count: 'id' });\n\n\t\tquery = this.applyFilters(query, options);\n\n\t\tconst result = await query.first();\n\t\treturn Number(result?.count ?? 0);\n\t}\n\n\t/**\n\t * Get the Knex database instance for transactional operations.\n\t * Used by endpoint adaptors to automatically wrap handlers in transactions.\n\t */\n\tgetDatabase(): Knex {\n\t\treturn this.db;\n\t}\n\n\t/**\n\t * Execute a callback within a Knex 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 opening a savepoint.\n\t */\n\tasync withTransaction<T>(\n\t\tauditor: TransactionAwareAuditor<Knex.Transaction>,\n\t\tcallback: () => Promise<T>,\n\t\tdb?: DatabaseConnection,\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 (isActiveTransaction(connection)) {\n\t\t\tauditor.setTransaction(connection);\n\t\t\tconst result = await callback();\n\t\t\tawait auditor.flush(connection);\n\t\t\treturn result;\n\t\t}\n\n\t\t// Create new transaction\n\t\treturn connection.transaction(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.whereIn('type', 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: this.toJsonColumn(record.oldValues),\n\t\t\tnewValues: this.toJsonColumn(record.newValues),\n\t\t\tpayload: this.toJsonColumn(record.payload),\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\n\t\t\t\t\t? this.toJsonColumn(this.getActorData(record.actor))\n\t\t\t\t\t: null,\n\t\t\tmetadata: this.toJsonColumn(record.metadata),\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 * Serialize a JSON value for insertion.\n\t *\n\t * Unlike Kysely, Knex has no per-column type information to tell a json/jsonb\n\t * column from an object it should bind as a composite value, so plain objects\n\t * are stringified before they reach the driver.\n\t */\n\tprivate toJsonColumn(value: unknown): string | null {\n\t\tif (value === undefined || value === null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn JSON.stringify(value);\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":";;;;;;;;;;;AAwBA,SAAS,oBACRA,YACiC;AACjC,QACC,WAAW,kBAAkB,SAC5B,AAAC,WAAgC,aAAa;AAEhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCD,eAAsB,yBACrBC,IACAC,SACAC,IACAC,UACa;CACb,MAAM,UAAU,OAAOC,QAAsC;AAE5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,KAAK,MAAM,MAAM;AAEzB,SAAO,CAAE;CACT;CAED,AAAQ,aACPC,OAC0B;EAC1B,MAAM,EAAE,IAAI,KAAM,GAAG,MAAM,GAAG;AAC9B,SAAO;CACP;CAED,AAAQ,cAAcC,UAAoD;AACzE,MAAI;GACH,MAAM,SAAS,KAAK,MAAM,SAAS;AACnC,cAAW,WAAW,YAAY,WAAW,KAC5C,QAAO;AAER,UAAO;EACP,QAAO;AACP,UAAO;EACP;CACD;AACD"}
|
package/dist/knex.d.cts
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import { AuditQueryOptions, AuditRecord, AuditStorage, TransactionAwareAuditor } from "./Auditor-DpBHXIJM.cjs";
|
|
2
|
+
import { Knex } from "knex";
|
|
3
|
+
|
|
4
|
+
//#region src/knex.d.ts
|
|
5
|
+
interface TransactionSettings {
|
|
6
|
+
isolationLevel?: Knex.IsolationLevels;
|
|
7
|
+
}
|
|
8
|
+
type DatabaseConnection = Knex | Knex.Transaction;
|
|
9
|
+
/**
|
|
10
|
+
* Execute a callback within a database transaction with automatic audit handling.
|
|
11
|
+
*
|
|
12
|
+
* This wrapper ensures that:
|
|
13
|
+
* 1. The transaction is automatically registered with the auditor
|
|
14
|
+
* 2. Manual audits (via `auditor.audit()`) are flushed BEFORE the transaction commits
|
|
15
|
+
* 3. If audit flush fails, the entire transaction rolls back
|
|
16
|
+
* 4. If the callback fails, audits are NOT written (atomic consistency)
|
|
17
|
+
*
|
|
18
|
+
* **Note:** Declarative audits (defined via `.audit([...])` on the endpoint builder)
|
|
19
|
+
* are processed AFTER the handler returns, so they run outside this transaction.
|
|
20
|
+
* If you need all audits to be atomic with your database operations, use manual
|
|
21
|
+
* audits via `auditor.audit()` inside this wrapper.
|
|
22
|
+
*
|
|
23
|
+
* @param db - Database connection (Knex instance or Transaction)
|
|
24
|
+
* @param auditor - Auditor instance that will receive the transaction
|
|
25
|
+
* @param cb - Callback to execute within the transaction
|
|
26
|
+
* @param settings - Optional transaction settings (isolation level)
|
|
27
|
+
* @returns The result of the callback
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* ```typescript
|
|
31
|
+
* import { withAuditableTransaction } from '@geekmidas/audit/knex';
|
|
32
|
+
*
|
|
33
|
+
* const result = await withAuditableTransaction(
|
|
34
|
+
* services.database,
|
|
35
|
+
* auditor,
|
|
36
|
+
* async (trx) => {
|
|
37
|
+
* const [user] = await trx('users').insert(data).returning('*');
|
|
38
|
+
*
|
|
39
|
+
* // Manual audits are atomic with the transaction
|
|
40
|
+
* auditor.audit('user.created', { userId: user.id, email: user.email });
|
|
41
|
+
*
|
|
42
|
+
* return user;
|
|
43
|
+
* },
|
|
44
|
+
* );
|
|
45
|
+
* // Audits are automatically flushed inside the transaction before commit
|
|
46
|
+
* ```
|
|
47
|
+
*/
|
|
48
|
+
declare function withAuditableTransaction<T>(db: DatabaseConnection, auditor: TransactionAwareAuditor<Knex.Transaction>, cb: (trx: Knex.Transaction) => Promise<T>, settings?: TransactionSettings): Promise<T>;
|
|
49
|
+
/**
|
|
50
|
+
* Shape of a row in the audit log table.
|
|
51
|
+
* Use this to describe your audit table when declaring Knex table types.
|
|
52
|
+
*
|
|
53
|
+
* Property names are camelCase to match the Kysely storage. Pair this with
|
|
54
|
+
* `knexSnakeCaseMappers()` if your database columns are snake_case.
|
|
55
|
+
*
|
|
56
|
+
* @example
|
|
57
|
+
* ```typescript
|
|
58
|
+
* import { knexSnakeCaseMappers } from 'objection';
|
|
59
|
+
*
|
|
60
|
+
* const db = knex({
|
|
61
|
+
* client: 'pg',
|
|
62
|
+
* connection: process.env.DATABASE_URL,
|
|
63
|
+
* ...knexSnakeCaseMappers(),
|
|
64
|
+
* });
|
|
65
|
+
*
|
|
66
|
+
* declare module 'knex/types/tables' {
|
|
67
|
+
* interface Tables {
|
|
68
|
+
* audit_logs: AuditLogTable;
|
|
69
|
+
* }
|
|
70
|
+
* }
|
|
71
|
+
* ```
|
|
72
|
+
*/
|
|
73
|
+
interface AuditLogTable {
|
|
74
|
+
id: string;
|
|
75
|
+
type: string;
|
|
76
|
+
operation: string;
|
|
77
|
+
table: string | null;
|
|
78
|
+
entityId: string | null;
|
|
79
|
+
oldValues: unknown | null;
|
|
80
|
+
newValues: unknown | null;
|
|
81
|
+
payload: unknown | null;
|
|
82
|
+
timestamp: Date;
|
|
83
|
+
actorId: string | null;
|
|
84
|
+
actorType: string | null;
|
|
85
|
+
actorData: unknown | null;
|
|
86
|
+
metadata: unknown | null;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Insertable version of AuditLogTable where id is optional.
|
|
90
|
+
* Use this when your database auto-generates IDs or when using the autoId option.
|
|
91
|
+
*/
|
|
92
|
+
type InsertableAuditLogTable = Omit<AuditLogTable, 'id'> & {
|
|
93
|
+
id?: string;
|
|
94
|
+
};
|
|
95
|
+
/**
|
|
96
|
+
* Configuration for KnexAuditStorage.
|
|
97
|
+
*/
|
|
98
|
+
interface KnexAuditStorageConfig {
|
|
99
|
+
/** Knex database instance */
|
|
100
|
+
db: Knex;
|
|
101
|
+
/** Table name for audit logs */
|
|
102
|
+
tableName: string;
|
|
103
|
+
/**
|
|
104
|
+
* Service name of the database service.
|
|
105
|
+
* When set, endpoint adaptors will automatically use the audit transaction as `db`
|
|
106
|
+
* in the handler context if the endpoint's database service has the same name.
|
|
107
|
+
*/
|
|
108
|
+
databaseServiceName?: string;
|
|
109
|
+
/**
|
|
110
|
+
* Let the database auto-generate IDs (e.g., via DEFAULT gen_random_uuid()).
|
|
111
|
+
* When true, the ID field is omitted from inserts if not provided.
|
|
112
|
+
* When false (default), IDs are generated using nanoid if not provided.
|
|
113
|
+
* @default false
|
|
114
|
+
*/
|
|
115
|
+
autoId?: boolean;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Knex-based audit storage implementation.
|
|
119
|
+
* Stores audit records in a database table using Knex.
|
|
120
|
+
*
|
|
121
|
+
* @example
|
|
122
|
+
* ```typescript
|
|
123
|
+
* const storage = new KnexAuditStorage({
|
|
124
|
+
* db: knexDb,
|
|
125
|
+
* tableName: 'audit_logs',
|
|
126
|
+
* });
|
|
127
|
+
*
|
|
128
|
+
* const auditor = new DefaultAuditor({
|
|
129
|
+
* actor: { id: 'user-123', type: 'user' },
|
|
130
|
+
* storage,
|
|
131
|
+
* });
|
|
132
|
+
* ```
|
|
133
|
+
*/
|
|
134
|
+
declare class KnexAuditStorage implements AuditStorage {
|
|
135
|
+
private readonly db;
|
|
136
|
+
private readonly tableName;
|
|
137
|
+
private readonly autoId;
|
|
138
|
+
readonly databaseServiceName?: string;
|
|
139
|
+
constructor(config: KnexAuditStorageConfig);
|
|
140
|
+
write(records: AuditRecord[], trx?: unknown): Promise<void>;
|
|
141
|
+
query(options: AuditQueryOptions): Promise<AuditRecord[]>;
|
|
142
|
+
count(options: Omit<AuditQueryOptions, 'limit' | 'offset'>): Promise<number>;
|
|
143
|
+
/**
|
|
144
|
+
* Get the Knex database instance for transactional operations.
|
|
145
|
+
* Used by endpoint adaptors to automatically wrap handlers in transactions.
|
|
146
|
+
*/
|
|
147
|
+
getDatabase(): Knex;
|
|
148
|
+
/**
|
|
149
|
+
* Execute a callback within a Knex transaction with automatic audit handling.
|
|
150
|
+
* The auditor is registered with the transaction and audits are flushed
|
|
151
|
+
* before the transaction commits.
|
|
152
|
+
*
|
|
153
|
+
* If the provided db connection is already a transaction, it will be reused
|
|
154
|
+
* instead of opening a savepoint.
|
|
155
|
+
*/
|
|
156
|
+
withTransaction<T>(auditor: TransactionAwareAuditor<Knex.Transaction>, callback: () => Promise<T>, db?: DatabaseConnection): Promise<T>;
|
|
157
|
+
private applyFilters;
|
|
158
|
+
private toRow;
|
|
159
|
+
private fromRow;
|
|
160
|
+
/**
|
|
161
|
+
* Serialize a JSON value for insertion.
|
|
162
|
+
*
|
|
163
|
+
* Unlike Kysely, Knex has no per-column type information to tell a json/jsonb
|
|
164
|
+
* column from an object it should bind as a composite value, so plain objects
|
|
165
|
+
* are stringified before they reach the driver.
|
|
166
|
+
*/
|
|
167
|
+
private toJsonColumn;
|
|
168
|
+
/**
|
|
169
|
+
* Parse a JSON value that may already be parsed (e.g., from jsonb columns).
|
|
170
|
+
*/
|
|
171
|
+
private parseJson;
|
|
172
|
+
private getActorData;
|
|
173
|
+
private parseEntityId;
|
|
174
|
+
}
|
|
175
|
+
//# sourceMappingURL=knex.d.ts.map
|
|
176
|
+
//#endregion
|
|
177
|
+
export { AuditLogTable, DatabaseConnection, InsertableAuditLogTable, KnexAuditStorage, KnexAuditStorageConfig, TransactionAwareAuditor, TransactionSettings, withAuditableTransaction };
|
|
178
|
+
//# sourceMappingURL=knex.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"knex.d.cts","names":[],"sources":["../src/knex.ts"],"sourcesContent":[],"mappings":";;;;AAWiB,UAAA,mBAAA,CACC;EAGN,cAAA,CAAA,EAHM,IAAA,CAAK,eAGO;;AAAG,KAArB,kBAAA,GAAqB,IAAA,GAAO,IAAA,CAAK,WAAZ;;AAAuB;AAyDxD;;;;;;;;;;;AAKU;AAgDV;AAoBA;;;;AAA0C;AAO1C;AAqCA;;;;;;;;;;;;;;;;;;AAgFI,iBArMkB,wBAqMlB,CAAA,CAAA,CAAA,CAAA,EAAA,EApMC,kBAoMD,EAAA,OAAA,EAnMM,uBAmMN,CAnM8B,IAAA,CAAK,WAmMnC,CAAA,EAAA,EAAA,EAAA,CAAA,GAAA,EAlMO,IAAA,CAAK,WAkMZ,EAAA,GAlM4B,OAkM5B,CAlMoC,CAkMpC,CAAA,EAAA,QAAA,CAAA,EAjMQ,mBAiMR,CAAA,EAhMD,OAgMC,CAhMO,CAgMP,CAAA;;AAhFiD;;;;;;;;;;;;;;;;;;;;;;;UAhEpC,aAAA;;;;;;;;;aASL;;;;;;;;;;KAWA,uBAAA,GAA0B,KAAK;;;;;;UAO1B,sBAAA;;MAEZ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAmCQ,gBAAA,YAA4B;;;;;sBAMpB;iBAOC,+BAA+B;iBAW/B,oBAAoB,QAAQ;iBA0BvC,KAAK,yCACZ;;;;;iBAaY;;;;;;;;;8BAaL,wBAAwB,IAAA,CAAK,8BACtB,QAAQ,SACnB,qBACH,QAAQ"}
|
package/dist/knex.d.mts
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import { AuditQueryOptions, AuditRecord, AuditStorage, TransactionAwareAuditor } from "./Auditor-CW2NrfHS.mjs";
|
|
2
|
+
import { Knex } from "knex";
|
|
3
|
+
|
|
4
|
+
//#region src/knex.d.ts
|
|
5
|
+
interface TransactionSettings {
|
|
6
|
+
isolationLevel?: Knex.IsolationLevels;
|
|
7
|
+
}
|
|
8
|
+
type DatabaseConnection = Knex | Knex.Transaction;
|
|
9
|
+
/**
|
|
10
|
+
* Execute a callback within a database transaction with automatic audit handling.
|
|
11
|
+
*
|
|
12
|
+
* This wrapper ensures that:
|
|
13
|
+
* 1. The transaction is automatically registered with the auditor
|
|
14
|
+
* 2. Manual audits (via `auditor.audit()`) are flushed BEFORE the transaction commits
|
|
15
|
+
* 3. If audit flush fails, the entire transaction rolls back
|
|
16
|
+
* 4. If the callback fails, audits are NOT written (atomic consistency)
|
|
17
|
+
*
|
|
18
|
+
* **Note:** Declarative audits (defined via `.audit([...])` on the endpoint builder)
|
|
19
|
+
* are processed AFTER the handler returns, so they run outside this transaction.
|
|
20
|
+
* If you need all audits to be atomic with your database operations, use manual
|
|
21
|
+
* audits via `auditor.audit()` inside this wrapper.
|
|
22
|
+
*
|
|
23
|
+
* @param db - Database connection (Knex instance or Transaction)
|
|
24
|
+
* @param auditor - Auditor instance that will receive the transaction
|
|
25
|
+
* @param cb - Callback to execute within the transaction
|
|
26
|
+
* @param settings - Optional transaction settings (isolation level)
|
|
27
|
+
* @returns The result of the callback
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* ```typescript
|
|
31
|
+
* import { withAuditableTransaction } from '@geekmidas/audit/knex';
|
|
32
|
+
*
|
|
33
|
+
* const result = await withAuditableTransaction(
|
|
34
|
+
* services.database,
|
|
35
|
+
* auditor,
|
|
36
|
+
* async (trx) => {
|
|
37
|
+
* const [user] = await trx('users').insert(data).returning('*');
|
|
38
|
+
*
|
|
39
|
+
* // Manual audits are atomic with the transaction
|
|
40
|
+
* auditor.audit('user.created', { userId: user.id, email: user.email });
|
|
41
|
+
*
|
|
42
|
+
* return user;
|
|
43
|
+
* },
|
|
44
|
+
* );
|
|
45
|
+
* // Audits are automatically flushed inside the transaction before commit
|
|
46
|
+
* ```
|
|
47
|
+
*/
|
|
48
|
+
declare function withAuditableTransaction<T>(db: DatabaseConnection, auditor: TransactionAwareAuditor<Knex.Transaction>, cb: (trx: Knex.Transaction) => Promise<T>, settings?: TransactionSettings): Promise<T>;
|
|
49
|
+
/**
|
|
50
|
+
* Shape of a row in the audit log table.
|
|
51
|
+
* Use this to describe your audit table when declaring Knex table types.
|
|
52
|
+
*
|
|
53
|
+
* Property names are camelCase to match the Kysely storage. Pair this with
|
|
54
|
+
* `knexSnakeCaseMappers()` if your database columns are snake_case.
|
|
55
|
+
*
|
|
56
|
+
* @example
|
|
57
|
+
* ```typescript
|
|
58
|
+
* import { knexSnakeCaseMappers } from 'objection';
|
|
59
|
+
*
|
|
60
|
+
* const db = knex({
|
|
61
|
+
* client: 'pg',
|
|
62
|
+
* connection: process.env.DATABASE_URL,
|
|
63
|
+
* ...knexSnakeCaseMappers(),
|
|
64
|
+
* });
|
|
65
|
+
*
|
|
66
|
+
* declare module 'knex/types/tables' {
|
|
67
|
+
* interface Tables {
|
|
68
|
+
* audit_logs: AuditLogTable;
|
|
69
|
+
* }
|
|
70
|
+
* }
|
|
71
|
+
* ```
|
|
72
|
+
*/
|
|
73
|
+
interface AuditLogTable {
|
|
74
|
+
id: string;
|
|
75
|
+
type: string;
|
|
76
|
+
operation: string;
|
|
77
|
+
table: string | null;
|
|
78
|
+
entityId: string | null;
|
|
79
|
+
oldValues: unknown | null;
|
|
80
|
+
newValues: unknown | null;
|
|
81
|
+
payload: unknown | null;
|
|
82
|
+
timestamp: Date;
|
|
83
|
+
actorId: string | null;
|
|
84
|
+
actorType: string | null;
|
|
85
|
+
actorData: unknown | null;
|
|
86
|
+
metadata: unknown | null;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Insertable version of AuditLogTable where id is optional.
|
|
90
|
+
* Use this when your database auto-generates IDs or when using the autoId option.
|
|
91
|
+
*/
|
|
92
|
+
type InsertableAuditLogTable = Omit<AuditLogTable, 'id'> & {
|
|
93
|
+
id?: string;
|
|
94
|
+
};
|
|
95
|
+
/**
|
|
96
|
+
* Configuration for KnexAuditStorage.
|
|
97
|
+
*/
|
|
98
|
+
interface KnexAuditStorageConfig {
|
|
99
|
+
/** Knex database instance */
|
|
100
|
+
db: Knex;
|
|
101
|
+
/** Table name for audit logs */
|
|
102
|
+
tableName: string;
|
|
103
|
+
/**
|
|
104
|
+
* Service name of the database service.
|
|
105
|
+
* When set, endpoint adaptors will automatically use the audit transaction as `db`
|
|
106
|
+
* in the handler context if the endpoint's database service has the same name.
|
|
107
|
+
*/
|
|
108
|
+
databaseServiceName?: string;
|
|
109
|
+
/**
|
|
110
|
+
* Let the database auto-generate IDs (e.g., via DEFAULT gen_random_uuid()).
|
|
111
|
+
* When true, the ID field is omitted from inserts if not provided.
|
|
112
|
+
* When false (default), IDs are generated using nanoid if not provided.
|
|
113
|
+
* @default false
|
|
114
|
+
*/
|
|
115
|
+
autoId?: boolean;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Knex-based audit storage implementation.
|
|
119
|
+
* Stores audit records in a database table using Knex.
|
|
120
|
+
*
|
|
121
|
+
* @example
|
|
122
|
+
* ```typescript
|
|
123
|
+
* const storage = new KnexAuditStorage({
|
|
124
|
+
* db: knexDb,
|
|
125
|
+
* tableName: 'audit_logs',
|
|
126
|
+
* });
|
|
127
|
+
*
|
|
128
|
+
* const auditor = new DefaultAuditor({
|
|
129
|
+
* actor: { id: 'user-123', type: 'user' },
|
|
130
|
+
* storage,
|
|
131
|
+
* });
|
|
132
|
+
* ```
|
|
133
|
+
*/
|
|
134
|
+
declare class KnexAuditStorage implements AuditStorage {
|
|
135
|
+
private readonly db;
|
|
136
|
+
private readonly tableName;
|
|
137
|
+
private readonly autoId;
|
|
138
|
+
readonly databaseServiceName?: string;
|
|
139
|
+
constructor(config: KnexAuditStorageConfig);
|
|
140
|
+
write(records: AuditRecord[], trx?: unknown): Promise<void>;
|
|
141
|
+
query(options: AuditQueryOptions): Promise<AuditRecord[]>;
|
|
142
|
+
count(options: Omit<AuditQueryOptions, 'limit' | 'offset'>): Promise<number>;
|
|
143
|
+
/**
|
|
144
|
+
* Get the Knex database instance for transactional operations.
|
|
145
|
+
* Used by endpoint adaptors to automatically wrap handlers in transactions.
|
|
146
|
+
*/
|
|
147
|
+
getDatabase(): Knex;
|
|
148
|
+
/**
|
|
149
|
+
* Execute a callback within a Knex transaction with automatic audit handling.
|
|
150
|
+
* The auditor is registered with the transaction and audits are flushed
|
|
151
|
+
* before the transaction commits.
|
|
152
|
+
*
|
|
153
|
+
* If the provided db connection is already a transaction, it will be reused
|
|
154
|
+
* instead of opening a savepoint.
|
|
155
|
+
*/
|
|
156
|
+
withTransaction<T>(auditor: TransactionAwareAuditor<Knex.Transaction>, callback: () => Promise<T>, db?: DatabaseConnection): Promise<T>;
|
|
157
|
+
private applyFilters;
|
|
158
|
+
private toRow;
|
|
159
|
+
private fromRow;
|
|
160
|
+
/**
|
|
161
|
+
* Serialize a JSON value for insertion.
|
|
162
|
+
*
|
|
163
|
+
* Unlike Kysely, Knex has no per-column type information to tell a json/jsonb
|
|
164
|
+
* column from an object it should bind as a composite value, so plain objects
|
|
165
|
+
* are stringified before they reach the driver.
|
|
166
|
+
*/
|
|
167
|
+
private toJsonColumn;
|
|
168
|
+
/**
|
|
169
|
+
* Parse a JSON value that may already be parsed (e.g., from jsonb columns).
|
|
170
|
+
*/
|
|
171
|
+
private parseJson;
|
|
172
|
+
private getActorData;
|
|
173
|
+
private parseEntityId;
|
|
174
|
+
}
|
|
175
|
+
//# sourceMappingURL=knex.d.ts.map
|
|
176
|
+
//#endregion
|
|
177
|
+
export { AuditLogTable, DatabaseConnection, InsertableAuditLogTable, KnexAuditStorage, KnexAuditStorageConfig, TransactionAwareAuditor, TransactionSettings, withAuditableTransaction };
|
|
178
|
+
//# sourceMappingURL=knex.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"knex.d.mts","names":[],"sources":["../src/knex.ts"],"sourcesContent":[],"mappings":";;;;AAWiB,UAAA,mBAAA,CACC;EAGN,cAAA,CAAA,EAHM,IAAA,CAAK,eAGO;;AAAG,KAArB,kBAAA,GAAqB,IAAA,GAAO,IAAA,CAAK,WAAZ;;AAAuB;AAyDxD;;;;;;;;;;;AAKU;AAgDV;AAoBA;;;;AAA0C;AAO1C;AAqCA;;;;;;;;;;;;;;;;;;AAgFI,iBArMkB,wBAqMlB,CAAA,CAAA,CAAA,CAAA,EAAA,EApMC,kBAoMD,EAAA,OAAA,EAnMM,uBAmMN,CAnM8B,IAAA,CAAK,WAmMnC,CAAA,EAAA,EAAA,EAAA,CAAA,GAAA,EAlMO,IAAA,CAAK,WAkMZ,EAAA,GAlM4B,OAkM5B,CAlMoC,CAkMpC,CAAA,EAAA,QAAA,CAAA,EAjMQ,mBAiMR,CAAA,EAhMD,OAgMC,CAhMO,CAgMP,CAAA;;AAhFiD;;;;;;;;;;;;;;;;;;;;;;;UAhEpC,aAAA;;;;;;;;;aASL;;;;;;;;;;KAWA,uBAAA,GAA0B,KAAK;;;;;;UAO1B,sBAAA;;MAEZ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAmCQ,gBAAA,YAA4B;;;;;sBAMpB;iBAOC,+BAA+B;iBAW/B,oBAAoB,QAAQ;iBA0BvC,KAAK,yCACZ;;;;;iBAaY;;;;;;;;;8BAaL,wBAAwB,IAAA,CAAK,8BACtB,QAAQ,SACnB,qBACH,QAAQ"}
|
package/dist/knex.mjs
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import { nanoid } from "nanoid";
|
|
2
|
+
|
|
3
|
+
//#region src/knex.ts
|
|
4
|
+
/**
|
|
5
|
+
* Type guard for an active Knex transaction.
|
|
6
|
+
*
|
|
7
|
+
* Knex marks transaction instances with `isTransaction`, and a completed
|
|
8
|
+
* transaction can no longer be used, so a settled transaction is treated as a
|
|
9
|
+
* plain connection.
|
|
10
|
+
*/
|
|
11
|
+
function isActiveTransaction(connection) {
|
|
12
|
+
return connection.isTransaction === true && !connection.isCompleted();
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Execute a callback within a database transaction with automatic audit handling.
|
|
16
|
+
*
|
|
17
|
+
* This wrapper ensures that:
|
|
18
|
+
* 1. The transaction is automatically registered with the auditor
|
|
19
|
+
* 2. Manual audits (via `auditor.audit()`) are flushed BEFORE the transaction commits
|
|
20
|
+
* 3. If audit flush fails, the entire transaction rolls back
|
|
21
|
+
* 4. If the callback fails, audits are NOT written (atomic consistency)
|
|
22
|
+
*
|
|
23
|
+
* **Note:** Declarative audits (defined via `.audit([...])` on the endpoint builder)
|
|
24
|
+
* are processed AFTER the handler returns, so they run outside this transaction.
|
|
25
|
+
* If you need all audits to be atomic with your database operations, use manual
|
|
26
|
+
* audits via `auditor.audit()` inside this wrapper.
|
|
27
|
+
*
|
|
28
|
+
* @param db - Database connection (Knex instance or Transaction)
|
|
29
|
+
* @param auditor - Auditor instance that will receive the transaction
|
|
30
|
+
* @param cb - Callback to execute within the transaction
|
|
31
|
+
* @param settings - Optional transaction settings (isolation level)
|
|
32
|
+
* @returns The result of the callback
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* ```typescript
|
|
36
|
+
* import { withAuditableTransaction } from '@geekmidas/audit/knex';
|
|
37
|
+
*
|
|
38
|
+
* const result = await withAuditableTransaction(
|
|
39
|
+
* services.database,
|
|
40
|
+
* auditor,
|
|
41
|
+
* async (trx) => {
|
|
42
|
+
* const [user] = await trx('users').insert(data).returning('*');
|
|
43
|
+
*
|
|
44
|
+
* // Manual audits are atomic with the transaction
|
|
45
|
+
* auditor.audit('user.created', { userId: user.id, email: user.email });
|
|
46
|
+
*
|
|
47
|
+
* return user;
|
|
48
|
+
* },
|
|
49
|
+
* );
|
|
50
|
+
* // Audits are automatically flushed inside the transaction before commit
|
|
51
|
+
* ```
|
|
52
|
+
*/
|
|
53
|
+
async function withAuditableTransaction(db, auditor, cb, settings) {
|
|
54
|
+
const execute = async (trx) => {
|
|
55
|
+
auditor.setTransaction(trx);
|
|
56
|
+
const result = await cb(trx);
|
|
57
|
+
await auditor.flush(trx);
|
|
58
|
+
return result;
|
|
59
|
+
};
|
|
60
|
+
if (isActiveTransaction(db)) return execute(db);
|
|
61
|
+
return db.transaction(execute, settings);
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Knex-based audit storage implementation.
|
|
65
|
+
* Stores audit records in a database table using Knex.
|
|
66
|
+
*
|
|
67
|
+
* @example
|
|
68
|
+
* ```typescript
|
|
69
|
+
* const storage = new KnexAuditStorage({
|
|
70
|
+
* db: knexDb,
|
|
71
|
+
* tableName: 'audit_logs',
|
|
72
|
+
* });
|
|
73
|
+
*
|
|
74
|
+
* const auditor = new DefaultAuditor({
|
|
75
|
+
* actor: { id: 'user-123', type: 'user' },
|
|
76
|
+
* storage,
|
|
77
|
+
* });
|
|
78
|
+
* ```
|
|
79
|
+
*/
|
|
80
|
+
var KnexAuditStorage = class {
|
|
81
|
+
db;
|
|
82
|
+
tableName;
|
|
83
|
+
autoId;
|
|
84
|
+
databaseServiceName;
|
|
85
|
+
constructor(config) {
|
|
86
|
+
this.db = config.db;
|
|
87
|
+
this.tableName = config.tableName;
|
|
88
|
+
this.databaseServiceName = config.databaseServiceName;
|
|
89
|
+
this.autoId = config.autoId ?? false;
|
|
90
|
+
}
|
|
91
|
+
async write(records, trx) {
|
|
92
|
+
if (records.length === 0) return;
|
|
93
|
+
const db = trx ?? this.db;
|
|
94
|
+
const rows = records.map((record) => this.toRow(record));
|
|
95
|
+
await db(this.tableName).insert(rows);
|
|
96
|
+
}
|
|
97
|
+
async query(options) {
|
|
98
|
+
let query = this.db(this.tableName).select("*");
|
|
99
|
+
query = this.applyFilters(query, options);
|
|
100
|
+
const orderBy = options.orderBy ?? "timestamp";
|
|
101
|
+
const orderDirection = options.orderDirection ?? "desc";
|
|
102
|
+
query = query.orderBy(orderBy === "timestamp" ? "timestamp" : "type", orderDirection);
|
|
103
|
+
if (options.limit !== void 0) query = query.limit(options.limit);
|
|
104
|
+
if (options.offset !== void 0) query = query.offset(options.offset);
|
|
105
|
+
const rows = await query;
|
|
106
|
+
return rows.map((row) => this.fromRow(row));
|
|
107
|
+
}
|
|
108
|
+
async count(options) {
|
|
109
|
+
let query = this.db(this.tableName).count({ count: "id" });
|
|
110
|
+
query = this.applyFilters(query, options);
|
|
111
|
+
const result = await query.first();
|
|
112
|
+
return Number(result?.count ?? 0);
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Get the Knex database instance for transactional operations.
|
|
116
|
+
* Used by endpoint adaptors to automatically wrap handlers in transactions.
|
|
117
|
+
*/
|
|
118
|
+
getDatabase() {
|
|
119
|
+
return this.db;
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Execute a callback within a Knex transaction with automatic audit handling.
|
|
123
|
+
* The auditor is registered with the transaction and audits are flushed
|
|
124
|
+
* before the transaction commits.
|
|
125
|
+
*
|
|
126
|
+
* If the provided db connection is already a transaction, it will be reused
|
|
127
|
+
* instead of opening a savepoint.
|
|
128
|
+
*/
|
|
129
|
+
async withTransaction(auditor, callback, db) {
|
|
130
|
+
const connection = db ?? this.db;
|
|
131
|
+
if (isActiveTransaction(connection)) {
|
|
132
|
+
auditor.setTransaction(connection);
|
|
133
|
+
const result = await callback();
|
|
134
|
+
await auditor.flush(connection);
|
|
135
|
+
return result;
|
|
136
|
+
}
|
|
137
|
+
return connection.transaction(async (trx) => {
|
|
138
|
+
auditor.setTransaction(trx);
|
|
139
|
+
const result = await callback();
|
|
140
|
+
await auditor.flush(trx);
|
|
141
|
+
return result;
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
applyFilters(query, options) {
|
|
145
|
+
if (options.type !== void 0) if (Array.isArray(options.type)) query = query.whereIn("type", options.type);
|
|
146
|
+
else query = query.where("type", options.type);
|
|
147
|
+
if (options.entityId !== void 0) {
|
|
148
|
+
const entityId = typeof options.entityId === "string" ? options.entityId : JSON.stringify(options.entityId);
|
|
149
|
+
query = query.where("entityId", entityId);
|
|
150
|
+
}
|
|
151
|
+
if (options.table !== void 0) query = query.where("table", options.table);
|
|
152
|
+
if (options.actorId !== void 0) query = query.where("actorId", options.actorId);
|
|
153
|
+
if (options.from !== void 0) query = query.where("timestamp", ">=", options.from);
|
|
154
|
+
if (options.to !== void 0) query = query.where("timestamp", "<=", options.to);
|
|
155
|
+
return query;
|
|
156
|
+
}
|
|
157
|
+
toRow(record) {
|
|
158
|
+
const id = this.autoId ? void 0 : record.id || nanoid();
|
|
159
|
+
return {
|
|
160
|
+
...id && { id },
|
|
161
|
+
type: record.type,
|
|
162
|
+
operation: record.operation,
|
|
163
|
+
table: record.table ?? null,
|
|
164
|
+
entityId: record.entityId === void 0 ? null : typeof record.entityId === "string" ? record.entityId : JSON.stringify(record.entityId),
|
|
165
|
+
oldValues: this.toJsonColumn(record.oldValues),
|
|
166
|
+
newValues: this.toJsonColumn(record.newValues),
|
|
167
|
+
payload: this.toJsonColumn(record.payload),
|
|
168
|
+
timestamp: record.timestamp,
|
|
169
|
+
actorId: record.actor?.id ?? null,
|
|
170
|
+
actorType: record.actor?.type ?? null,
|
|
171
|
+
actorData: record.actor !== void 0 ? this.toJsonColumn(this.getActorData(record.actor)) : null,
|
|
172
|
+
metadata: this.toJsonColumn(record.metadata)
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
fromRow(row) {
|
|
176
|
+
const actor = row.actorId !== null || row.actorType !== null ? {
|
|
177
|
+
id: row.actorId ?? void 0,
|
|
178
|
+
type: row.actorType ?? void 0,
|
|
179
|
+
...row.actorData ? this.parseJson(row.actorData) : {}
|
|
180
|
+
} : void 0;
|
|
181
|
+
return {
|
|
182
|
+
id: row.id,
|
|
183
|
+
type: row.type,
|
|
184
|
+
operation: row.operation,
|
|
185
|
+
table: row.table ?? void 0,
|
|
186
|
+
entityId: row.entityId ? this.parseEntityId(row.entityId) : void 0,
|
|
187
|
+
oldValues: row.oldValues ? this.parseJson(row.oldValues) : void 0,
|
|
188
|
+
newValues: row.newValues ? this.parseJson(row.newValues) : void 0,
|
|
189
|
+
payload: row.payload ? this.parseJson(row.payload) : void 0,
|
|
190
|
+
timestamp: row.timestamp,
|
|
191
|
+
actor,
|
|
192
|
+
metadata: row.metadata ? this.parseJson(row.metadata) : void 0
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Serialize a JSON value for insertion.
|
|
197
|
+
*
|
|
198
|
+
* Unlike Kysely, Knex has no per-column type information to tell a json/jsonb
|
|
199
|
+
* column from an object it should bind as a composite value, so plain objects
|
|
200
|
+
* are stringified before they reach the driver.
|
|
201
|
+
*/
|
|
202
|
+
toJsonColumn(value) {
|
|
203
|
+
if (value === void 0 || value === null) return null;
|
|
204
|
+
return JSON.stringify(value);
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Parse a JSON value that may already be parsed (e.g., from jsonb columns).
|
|
208
|
+
*/
|
|
209
|
+
parseJson(value) {
|
|
210
|
+
if (typeof value === "object" && value !== null) return value;
|
|
211
|
+
if (typeof value === "string") return JSON.parse(value);
|
|
212
|
+
return {};
|
|
213
|
+
}
|
|
214
|
+
getActorData(actor) {
|
|
215
|
+
const { id, type,...rest } = actor;
|
|
216
|
+
return rest;
|
|
217
|
+
}
|
|
218
|
+
parseEntityId(entityId) {
|
|
219
|
+
try {
|
|
220
|
+
const parsed = JSON.parse(entityId);
|
|
221
|
+
if (typeof parsed === "object" && parsed !== null) return parsed;
|
|
222
|
+
return entityId;
|
|
223
|
+
} catch {
|
|
224
|
+
return entityId;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
|
|
229
|
+
//#endregion
|
|
230
|
+
export { KnexAuditStorage, withAuditableTransaction };
|
|
231
|
+
//# sourceMappingURL=knex.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"knex.mjs","names":["connection: DatabaseConnection","db: DatabaseConnection","auditor: TransactionAwareAuditor<Knex.Transaction>","cb: (trx: Knex.Transaction) => Promise<T>","settings?: TransactionSettings","trx: Knex.Transaction","config: KnexAuditStorageConfig","records: AuditRecord[]","trx?: unknown","options: AuditQueryOptions","row: AuditLogTable","options: Omit<AuditQueryOptions, 'limit' | 'offset'>","callback: () => Promise<T>","db?: DatabaseConnection","query: any","record: AuditRecord","value: unknown","actor: NonNullable<AuditRecord['actor']>","entityId: string"],"sources":["../src/knex.ts"],"sourcesContent":["import type { Knex } from 'knex';\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?: Knex.IsolationLevels;\n}\n\nexport type DatabaseConnection = Knex | Knex.Transaction;\n\n/**\n * Type guard for an active Knex transaction.\n *\n * Knex marks transaction instances with `isTransaction`, and a completed\n * transaction can no longer be used, so a settled transaction is treated as a\n * plain connection.\n */\nfunction isActiveTransaction(\n\tconnection: DatabaseConnection,\n): connection is Knex.Transaction {\n\treturn (\n\t\tconnection.isTransaction === true &&\n\t\t!(connection as Knex.Transaction).isCompleted()\n\t);\n}\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 (Knex instance or Transaction)\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/knex';\n *\n * const result = await withAuditableTransaction(\n * services.database,\n * auditor,\n * async (trx) => {\n * const [user] = await trx('users').insert(data).returning('*');\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<T>(\n\tdb: DatabaseConnection,\n\tauditor: TransactionAwareAuditor<Knex.Transaction>,\n\tcb: (trx: Knex.Transaction) => Promise<T>,\n\tsettings?: TransactionSettings,\n): Promise<T> {\n\tconst execute = async (trx: Knex.Transaction): 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\t// Knex would otherwise open a savepoint, which commits independently.\n\tif (isActiveTransaction(db)) {\n\t\treturn execute(db);\n\t}\n\n\treturn db.transaction(execute, settings);\n}\n\n/**\n * Shape of a row in the audit log table.\n * Use this to describe your audit table when declaring Knex table types.\n *\n * Property names are camelCase to match the Kysely storage. Pair this with\n * `knexSnakeCaseMappers()` if your database columns are snake_case.\n *\n * @example\n * ```typescript\n * import { knexSnakeCaseMappers } from 'objection';\n *\n * const db = knex({\n * client: 'pg',\n * connection: process.env.DATABASE_URL,\n * ...knexSnakeCaseMappers(),\n * });\n *\n * declare module 'knex/types/tables' {\n * interface Tables {\n * audit_logs: AuditLogTable;\n * }\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 the autoId option.\n */\nexport type InsertableAuditLogTable = Omit<AuditLogTable, 'id'> & {\n\tid?: string;\n};\n\n/**\n * Configuration for KnexAuditStorage.\n */\nexport interface KnexAuditStorageConfig {\n\t/** Knex database instance */\n\tdb: Knex;\n\t/** Table name for audit logs */\n\ttableName: 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 * Knex-based audit storage implementation.\n * Stores audit records in a database table using Knex.\n *\n * @example\n * ```typescript\n * const storage = new KnexAuditStorage({\n * db: knexDb,\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 KnexAuditStorage implements AuditStorage {\n\tprivate readonly db: Knex;\n\tprivate readonly tableName: string;\n\tprivate readonly autoId: boolean;\n\treadonly databaseServiceName?: string;\n\n\tconstructor(config: KnexAuditStorageConfig) {\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 Knex.Transaction) ?? this.db;\n\t\tconst rows = records.map((record) => this.toRow(record));\n\n\t\tawait db(this.tableName).insert(rows);\n\t}\n\n\tasync query(options: AuditQueryOptions): Promise<AuditRecord[]> {\n\t\tlet query = this.db(this.tableName).select('*');\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;\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(this.tableName).count({ count: 'id' });\n\n\t\tquery = this.applyFilters(query, options);\n\n\t\tconst result = await query.first();\n\t\treturn Number(result?.count ?? 0);\n\t}\n\n\t/**\n\t * Get the Knex database instance for transactional operations.\n\t * Used by endpoint adaptors to automatically wrap handlers in transactions.\n\t */\n\tgetDatabase(): Knex {\n\t\treturn this.db;\n\t}\n\n\t/**\n\t * Execute a callback within a Knex 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 opening a savepoint.\n\t */\n\tasync withTransaction<T>(\n\t\tauditor: TransactionAwareAuditor<Knex.Transaction>,\n\t\tcallback: () => Promise<T>,\n\t\tdb?: DatabaseConnection,\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 (isActiveTransaction(connection)) {\n\t\t\tauditor.setTransaction(connection);\n\t\t\tconst result = await callback();\n\t\t\tawait auditor.flush(connection);\n\t\t\treturn result;\n\t\t}\n\n\t\t// Create new transaction\n\t\treturn connection.transaction(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.whereIn('type', 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: this.toJsonColumn(record.oldValues),\n\t\t\tnewValues: this.toJsonColumn(record.newValues),\n\t\t\tpayload: this.toJsonColumn(record.payload),\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\n\t\t\t\t\t? this.toJsonColumn(this.getActorData(record.actor))\n\t\t\t\t\t: null,\n\t\t\tmetadata: this.toJsonColumn(record.metadata),\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 * Serialize a JSON value for insertion.\n\t *\n\t * Unlike Kysely, Knex has no per-column type information to tell a json/jsonb\n\t * column from an object it should bind as a composite value, so plain objects\n\t * are stringified before they reach the driver.\n\t */\n\tprivate toJsonColumn(value: unknown): string | null {\n\t\tif (value === undefined || value === null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn JSON.stringify(value);\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":";;;;;;;;;;AAwBA,SAAS,oBACRA,YACiC;AACjC,QACC,WAAW,kBAAkB,SAC5B,AAAC,WAAgC,aAAa;AAEhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCD,eAAsB,yBACrBC,IACAC,SACAC,IACAC,UACa;CACb,MAAM,UAAU,OAAOC,QAAsC;AAE5D,UAAQ,eAAe,IAAI;EAG3B,MAAM,SAAS,MAAM,GAAG,IAAI;AAI5B,QAAM,QAAQ,MAAM,IAAI;AAExB,SAAO;CACP;AAID,KAAI,oBAAoB,GAAG,CAC1B,QAAO,QAAQ,GAAG;AAGnB,QAAO,GAAG,YAAY,SAAS,SAAS;AACxC;;;;;;;;;;;;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