@geekmidas/audit 0.0.8 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +397 -0
  2. package/dist/{Auditor-D3me-qKX.d.mts → Auditor-_Dn2dp8d.d.mts} +46 -1
  3. package/dist/Auditor-_Dn2dp8d.d.mts.map +1 -0
  4. package/dist/{Auditor-QYUMGJCH.d.cts → Auditor-sW7YAJIA.d.cts} +46 -1
  5. package/dist/Auditor-sW7YAJIA.d.cts.map +1 -0
  6. package/dist/Auditor.d.cts +1 -1
  7. package/dist/Auditor.d.mts +1 -1
  8. package/dist/DefaultAuditor-BAVnNmRh.mjs.map +1 -1
  9. package/dist/{DefaultAuditor-BTuMMiWh.d.cts → DefaultAuditor-BSYMwojG.d.cts} +3 -2
  10. package/dist/DefaultAuditor-BSYMwojG.d.cts.map +1 -0
  11. package/dist/{DefaultAuditor-C1FWrJg6.d.mts → DefaultAuditor-CYE-uAry.d.mts} +3 -2
  12. package/dist/DefaultAuditor-CYE-uAry.d.mts.map +1 -0
  13. package/dist/DefaultAuditor-JbZ_BQfh.cjs.map +1 -1
  14. package/dist/DefaultAuditor.d.cts +2 -2
  15. package/dist/DefaultAuditor.d.mts +2 -2
  16. package/dist/cache-2VI80Vao.d.mts +96 -0
  17. package/dist/cache-2VI80Vao.d.mts.map +1 -0
  18. package/dist/cache-BbIl31RL.mjs +167 -0
  19. package/dist/cache-BbIl31RL.mjs.map +1 -0
  20. package/dist/cache-CDHqXqcl.d.cts +96 -0
  21. package/dist/cache-CDHqXqcl.d.cts.map +1 -0
  22. package/dist/cache-l7jAptBl.cjs +173 -0
  23. package/dist/cache-l7jAptBl.cjs.map +1 -0
  24. package/dist/cache.cjs +3 -0
  25. package/dist/cache.d.cts +3 -0
  26. package/dist/cache.d.mts +3 -0
  27. package/dist/cache.mjs +3 -0
  28. package/dist/index.d.cts +2 -2
  29. package/dist/index.d.mts +2 -2
  30. package/dist/kysely.cjs +24 -0
  31. package/dist/kysely.cjs.map +1 -1
  32. package/dist/kysely.d.cts +11 -1
  33. package/dist/kysely.d.cts.map +1 -0
  34. package/dist/kysely.d.mts +11 -1
  35. package/dist/kysely.d.mts.map +1 -0
  36. package/dist/kysely.mjs +24 -0
  37. package/dist/kysely.mjs.map +1 -1
  38. package/dist/memory.cjs +49 -0
  39. package/dist/memory.cjs.map +1 -0
  40. package/dist/memory.d.cts +44 -0
  41. package/dist/memory.d.cts.map +1 -0
  42. package/dist/memory.d.mts +44 -0
  43. package/dist/memory.d.mts.map +1 -0
  44. package/dist/memory.mjs +48 -0
  45. package/dist/memory.mjs.map +1 -0
  46. package/dist/storage.d.cts +1 -1
  47. package/dist/storage.d.mts +1 -1
  48. package/dist/types.d.cts +1 -1
  49. package/dist/types.d.mts +1 -1
  50. package/package.json +33 -5
  51. package/src/Auditor.ts +121 -121
  52. package/src/DefaultAuditor.ts +91 -91
  53. package/src/__tests__/CacheAuditStorage.spec.ts +382 -0
  54. package/src/__tests__/DefaultAuditor.spec.ts +520 -462
  55. package/src/__tests__/InMemoryAuditStorage.spec.ts +317 -0
  56. package/src/__tests__/KyselyAuditStorage.integration.spec.ts +500 -496
  57. package/src/__tests__/KyselyAuditStorage.spec.ts +433 -433
  58. package/src/cache.ts +263 -0
  59. package/src/index.ts +14 -15
  60. package/src/kysely.ts +292 -259
  61. package/src/memory.ts +50 -0
  62. package/src/storage.ts +132 -85
  63. package/src/types.ts +73 -74
  64. package/tsconfig.json +9 -0
@@ -1,3 +1,3 @@
1
- import "./Auditor-D3me-qKX.mjs";
2
- import { DefaultAuditor, DefaultAuditorConfig } from "./DefaultAuditor-C1FWrJg6.mjs";
1
+ import "./Auditor-_Dn2dp8d.mjs";
2
+ import { DefaultAuditor, DefaultAuditorConfig } from "./DefaultAuditor-CYE-uAry.mjs";
3
3
  export { DefaultAuditor, DefaultAuditorConfig };
@@ -0,0 +1,96 @@
1
+ import { AuditQueryOptions, AuditRecord, AuditStorage, AuditableAction } from "./Auditor-_Dn2dp8d.mjs";
2
+ import { Cache } from "@geekmidas/cache";
3
+
4
+ //#region src/cache.d.ts
5
+
6
+ /**
7
+ * Configuration for CacheAuditStorage.
8
+ */
9
+ interface CacheAuditStorageConfig {
10
+ /** Cache instance to use for storage */
11
+ cache: Cache;
12
+ /**
13
+ * Key prefix for audit records.
14
+ * Records are stored as `${prefix}:${id}`.
15
+ * @default 'audit'
16
+ */
17
+ prefix?: string;
18
+ /**
19
+ * TTL (time-to-live) in seconds for audit records.
20
+ * If not set, records use the cache's default TTL.
21
+ */
22
+ ttl?: number;
23
+ }
24
+ /**
25
+ * Cache-based audit storage implementation.
26
+ * Uses any @geekmidas/cache implementation for storage.
27
+ *
28
+ * Best suited for:
29
+ * - Development and testing
30
+ * - Temporary audit logs that don't need persistence
31
+ * - Applications with existing cache infrastructure
32
+ * - Distributed systems needing shared audit state (with Redis/Upstash)
33
+ *
34
+ * Note: Query performance may degrade with large numbers of records
35
+ * since filtering happens in memory after fetching all records.
36
+ *
37
+ * @template TAuditAction - Optional type parameter for type-safe audit actions.
38
+ *
39
+ * @example
40
+ * ```typescript
41
+ * import { CacheAuditStorage } from '@geekmidas/audit/cache';
42
+ * import { InMemoryCache } from '@geekmidas/cache/memory';
43
+ * import { UpstashCache } from '@geekmidas/cache/upstash';
44
+ *
45
+ * // With in-memory cache (development/testing)
46
+ * const storage = new CacheAuditStorage({
47
+ * cache: new InMemoryCache(),
48
+ * ttl: 86400, // 24 hours
49
+ * });
50
+ *
51
+ * // With Upstash Redis (production)
52
+ * const storage = new CacheAuditStorage({
53
+ * cache: new UpstashCache({
54
+ * url: process.env.UPSTASH_REDIS_URL,
55
+ * token: process.env.UPSTASH_REDIS_TOKEN,
56
+ * }),
57
+ * ttl: 604800, // 7 days
58
+ * });
59
+ * ```
60
+ */
61
+ declare class CacheAuditStorage<TAuditAction extends AuditableAction<string, unknown> = AuditableAction<string, unknown>> implements AuditStorage<TAuditAction> {
62
+ private readonly cache;
63
+ private readonly prefix;
64
+ private readonly ttl?;
65
+ private readonly indexKey;
66
+ constructor(config: CacheAuditStorageConfig);
67
+ /**
68
+ * Write audit records to cache.
69
+ */
70
+ write(records: AuditRecord[]): Promise<void>;
71
+ /**
72
+ * Query audit records from cache.
73
+ */
74
+ query(options: AuditQueryOptions): Promise<AuditRecord[]>;
75
+ /**
76
+ * Count audit records matching filters.
77
+ */
78
+ count(options: Omit<AuditQueryOptions, 'limit' | 'offset'>): Promise<number>;
79
+ /**
80
+ * Get all stored records (for testing/debugging).
81
+ */
82
+ getRecords(): Promise<AuditRecord[]>;
83
+ /**
84
+ * Clear all stored records.
85
+ */
86
+ clear(): Promise<void>;
87
+ private getRecordKey;
88
+ private getAllRecords;
89
+ private serializeRecord;
90
+ private deserializeRecord;
91
+ private applyFilters;
92
+ }
93
+ //# sourceMappingURL=cache.d.ts.map
94
+ //#endregion
95
+ export { CacheAuditStorage, CacheAuditStorageConfig };
96
+ //# sourceMappingURL=cache-2VI80Vao.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache-2VI80Vao.d.mts","names":[],"sources":["../src/cache.ts"],"sourcesContent":[],"mappings":";;;;;;AAOA;AAqDA;AAA8B,UArDb,uBAAA,CAqDa;EAAA;EACO,KAAoB,EApDjD,KAoDiD;EAAe;;;;;EA+CjC,MAAW,CAAA,EAAA,MAAA;EAAW;;;;EA+BlD,GAQkB,CAAA,EAAA,MAAA;;;;AAlFJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cALZ,uCACS,mCAAmC,6CAI5C,aAAa;;;;;sBAOL;;;;iBAUC,gBAAgB;;;;iBA0BhB,oBAAoB,QAAQ;;;;iBA8BvC,KAAK,yCACZ;;;;gBAQiB,QAAQ;;;;WAOb"}
@@ -0,0 +1,167 @@
1
+ //#region src/cache.ts
2
+ /**
3
+ * Cache-based audit storage implementation.
4
+ * Uses any @geekmidas/cache implementation for storage.
5
+ *
6
+ * Best suited for:
7
+ * - Development and testing
8
+ * - Temporary audit logs that don't need persistence
9
+ * - Applications with existing cache infrastructure
10
+ * - Distributed systems needing shared audit state (with Redis/Upstash)
11
+ *
12
+ * Note: Query performance may degrade with large numbers of records
13
+ * since filtering happens in memory after fetching all records.
14
+ *
15
+ * @template TAuditAction - Optional type parameter for type-safe audit actions.
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * import { CacheAuditStorage } from '@geekmidas/audit/cache';
20
+ * import { InMemoryCache } from '@geekmidas/cache/memory';
21
+ * import { UpstashCache } from '@geekmidas/cache/upstash';
22
+ *
23
+ * // With in-memory cache (development/testing)
24
+ * const storage = new CacheAuditStorage({
25
+ * cache: new InMemoryCache(),
26
+ * ttl: 86400, // 24 hours
27
+ * });
28
+ *
29
+ * // With Upstash Redis (production)
30
+ * const storage = new CacheAuditStorage({
31
+ * cache: new UpstashCache({
32
+ * url: process.env.UPSTASH_REDIS_URL,
33
+ * token: process.env.UPSTASH_REDIS_TOKEN,
34
+ * }),
35
+ * ttl: 604800, // 7 days
36
+ * });
37
+ * ```
38
+ */
39
+ var CacheAuditStorage = class {
40
+ cache;
41
+ prefix;
42
+ ttl;
43
+ indexKey;
44
+ constructor(config) {
45
+ this.cache = config.cache;
46
+ this.prefix = config.prefix ?? "audit";
47
+ this.ttl = config.ttl;
48
+ this.indexKey = `${this.prefix}:__index__`;
49
+ }
50
+ /**
51
+ * Write audit records to cache.
52
+ */
53
+ async write(records) {
54
+ if (records.length === 0) return;
55
+ const existingIds = await this.cache.get(this.indexKey) ?? [];
56
+ const newIds = [];
57
+ for (const record of records) {
58
+ const key = this.getRecordKey(record.id);
59
+ const serialized = this.serializeRecord(record);
60
+ await this.cache.set(key, serialized, this.ttl);
61
+ newIds.push(record.id);
62
+ }
63
+ const updatedIds = [...existingIds, ...newIds];
64
+ await this.cache.set(this.indexKey, updatedIds, this.ttl);
65
+ }
66
+ /**
67
+ * Query audit records from cache.
68
+ */
69
+ async query(options) {
70
+ const allRecords = await this.getAllRecords();
71
+ let results = this.applyFilters(allRecords, options);
72
+ const orderBy = options.orderBy ?? "timestamp";
73
+ const orderDirection = options.orderDirection ?? "desc";
74
+ results.sort((a, b) => {
75
+ const aValue = orderBy === "timestamp" ? a.timestamp.getTime() : a.type;
76
+ const bValue = orderBy === "timestamp" ? b.timestamp.getTime() : b.type;
77
+ if (aValue < bValue) return orderDirection === "asc" ? -1 : 1;
78
+ if (aValue > bValue) return orderDirection === "asc" ? 1 : -1;
79
+ return 0;
80
+ });
81
+ if (options.offset !== void 0) results = results.slice(options.offset);
82
+ if (options.limit !== void 0) results = results.slice(0, options.limit);
83
+ return results;
84
+ }
85
+ /**
86
+ * Count audit records matching filters.
87
+ */
88
+ async count(options) {
89
+ const allRecords = await this.getAllRecords();
90
+ return this.applyFilters(allRecords, options).length;
91
+ }
92
+ /**
93
+ * Get all stored records (for testing/debugging).
94
+ */
95
+ async getRecords() {
96
+ return this.getAllRecords();
97
+ }
98
+ /**
99
+ * Clear all stored records.
100
+ */
101
+ async clear() {
102
+ const ids = await this.cache.get(this.indexKey) ?? [];
103
+ for (const id of ids) await this.cache.delete(this.getRecordKey(id));
104
+ await this.cache.delete(this.indexKey);
105
+ }
106
+ getRecordKey(id) {
107
+ return `${this.prefix}:${id}`;
108
+ }
109
+ async getAllRecords() {
110
+ const ids = await this.cache.get(this.indexKey) ?? [];
111
+ const records = [];
112
+ const validIds = [];
113
+ for (const id of ids) {
114
+ const key = this.getRecordKey(id);
115
+ const serialized = await this.cache.get(key);
116
+ if (serialized) {
117
+ records.push(this.deserializeRecord(serialized));
118
+ validIds.push(id);
119
+ }
120
+ }
121
+ if (validIds.length !== ids.length) await this.cache.set(this.indexKey, validIds, this.ttl);
122
+ return records;
123
+ }
124
+ serializeRecord(record) {
125
+ return {
126
+ ...record,
127
+ timestamp: record.timestamp.toISOString()
128
+ };
129
+ }
130
+ deserializeRecord(serialized) {
131
+ return {
132
+ ...serialized,
133
+ timestamp: new Date(serialized.timestamp)
134
+ };
135
+ }
136
+ applyFilters(records, options) {
137
+ return records.filter((record) => {
138
+ if (options.type !== void 0) {
139
+ if (Array.isArray(options.type)) {
140
+ if (!options.type.includes(record.type)) return false;
141
+ } else if (record.type !== options.type) return false;
142
+ }
143
+ if (options.entityId !== void 0) {
144
+ const entityId = typeof options.entityId === "string" ? options.entityId : JSON.stringify(options.entityId);
145
+ const recordEntityId = typeof record.entityId === "string" ? record.entityId : JSON.stringify(record.entityId);
146
+ if (recordEntityId !== entityId) return false;
147
+ }
148
+ if (options.table !== void 0) {
149
+ if (record.table !== options.table) return false;
150
+ }
151
+ if (options.actorId !== void 0) {
152
+ if (record.actor?.id !== options.actorId) return false;
153
+ }
154
+ if (options.from !== void 0) {
155
+ if (record.timestamp < options.from) return false;
156
+ }
157
+ if (options.to !== void 0) {
158
+ if (record.timestamp > options.to) return false;
159
+ }
160
+ return true;
161
+ });
162
+ }
163
+ };
164
+
165
+ //#endregion
166
+ export { CacheAuditStorage };
167
+ //# sourceMappingURL=cache-BbIl31RL.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache-BbIl31RL.mjs","names":["config: CacheAuditStorageConfig","records: AuditRecord[]","newIds: string[]","options: AuditQueryOptions","options: Omit<AuditQueryOptions, 'limit' | 'offset'>","id: string","validIds: string[]","record: AuditRecord","serialized: SerializedAuditRecord"],"sources":["../src/cache.ts"],"sourcesContent":["import type { Cache } from '@geekmidas/cache';\nimport type { AuditQueryOptions, AuditStorage } from './storage';\nimport type { AuditableAction, AuditRecord } from './types';\n\n/**\n * Configuration for CacheAuditStorage.\n */\nexport interface CacheAuditStorageConfig {\n\t/** Cache instance to use for storage */\n\tcache: Cache;\n\t/**\n\t * Key prefix for audit records.\n\t * Records are stored as `${prefix}:${id}`.\n\t * @default 'audit'\n\t */\n\tprefix?: string;\n\t/**\n\t * TTL (time-to-live) in seconds for audit records.\n\t * If not set, records use the cache's default TTL.\n\t */\n\tttl?: number;\n}\n\n/**\n * Cache-based audit storage implementation.\n * Uses any @geekmidas/cache implementation for storage.\n *\n * Best suited for:\n * - Development and testing\n * - Temporary audit logs that don't need persistence\n * - Applications with existing cache infrastructure\n * - Distributed systems needing shared audit state (with Redis/Upstash)\n *\n * Note: Query performance may degrade with large numbers of records\n * since filtering happens in memory after fetching all records.\n *\n * @template TAuditAction - Optional type parameter for type-safe audit actions.\n *\n * @example\n * ```typescript\n * import { CacheAuditStorage } from '@geekmidas/audit/cache';\n * import { InMemoryCache } from '@geekmidas/cache/memory';\n * import { UpstashCache } from '@geekmidas/cache/upstash';\n *\n * // With in-memory cache (development/testing)\n * const storage = new CacheAuditStorage({\n * cache: new InMemoryCache(),\n * ttl: 86400, // 24 hours\n * });\n *\n * // With Upstash Redis (production)\n * const storage = new CacheAuditStorage({\n * cache: new UpstashCache({\n * url: process.env.UPSTASH_REDIS_URL,\n * token: process.env.UPSTASH_REDIS_TOKEN,\n * }),\n * ttl: 604800, // 7 days\n * });\n * ```\n */\nexport class CacheAuditStorage<\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n> implements AuditStorage<TAuditAction>\n{\n\tprivate readonly cache: Cache;\n\tprivate readonly prefix: string;\n\tprivate readonly ttl?: number;\n\tprivate readonly indexKey: string;\n\n\tconstructor(config: CacheAuditStorageConfig) {\n\t\tthis.cache = config.cache;\n\t\tthis.prefix = config.prefix ?? 'audit';\n\t\tthis.ttl = config.ttl;\n\t\tthis.indexKey = `${this.prefix}:__index__`;\n\t}\n\n\t/**\n\t * Write audit records to cache.\n\t */\n\tasync write(records: AuditRecord[]): Promise<void> {\n\t\tif (records.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Get existing index\n\t\tconst existingIds = (await this.cache.get<string[]>(this.indexKey)) ?? [];\n\t\tconst newIds: string[] = [];\n\n\t\t// Write each record\n\t\tfor (const record of records) {\n\t\t\tconst key = this.getRecordKey(record.id);\n\t\t\t// Serialize Date to ISO string for cache storage\n\t\t\tconst serialized = this.serializeRecord(record);\n\t\t\tawait this.cache.set(key, serialized, this.ttl);\n\t\t\tnewIds.push(record.id);\n\t\t}\n\n\t\t// Update index with new IDs\n\t\tconst updatedIds = [...existingIds, ...newIds];\n\t\tawait this.cache.set(this.indexKey, updatedIds, this.ttl);\n\t}\n\n\t/**\n\t * Query audit records from cache.\n\t */\n\tasync query(options: AuditQueryOptions): Promise<AuditRecord[]> {\n\t\tconst allRecords = await this.getAllRecords();\n\t\tlet results = this.applyFilters(allRecords, options);\n\n\t\t// Ordering\n\t\tconst orderBy = options.orderBy ?? 'timestamp';\n\t\tconst orderDirection = options.orderDirection ?? 'desc';\n\t\tresults.sort((a, b) => {\n\t\t\tconst aValue = orderBy === 'timestamp' ? a.timestamp.getTime() : a.type;\n\t\t\tconst bValue = orderBy === 'timestamp' ? b.timestamp.getTime() : b.type;\n\t\t\tif (aValue < bValue) return orderDirection === 'asc' ? -1 : 1;\n\t\t\tif (aValue > bValue) return orderDirection === 'asc' ? 1 : -1;\n\t\t\treturn 0;\n\t\t});\n\n\t\t// Pagination\n\t\tif (options.offset !== undefined) {\n\t\t\tresults = results.slice(options.offset);\n\t\t}\n\t\tif (options.limit !== undefined) {\n\t\t\tresults = results.slice(0, options.limit);\n\t\t}\n\n\t\treturn results;\n\t}\n\n\t/**\n\t * Count audit records matching filters.\n\t */\n\tasync count(\n\t\toptions: Omit<AuditQueryOptions, 'limit' | 'offset'>,\n\t): Promise<number> {\n\t\tconst allRecords = await this.getAllRecords();\n\t\treturn this.applyFilters(allRecords, options).length;\n\t}\n\n\t/**\n\t * Get all stored records (for testing/debugging).\n\t */\n\tasync getRecords(): Promise<AuditRecord[]> {\n\t\treturn this.getAllRecords();\n\t}\n\n\t/**\n\t * Clear all stored records.\n\t */\n\tasync clear(): Promise<void> {\n\t\tconst ids = (await this.cache.get<string[]>(this.indexKey)) ?? [];\n\n\t\t// Delete all records\n\t\tfor (const id of ids) {\n\t\t\tawait this.cache.delete(this.getRecordKey(id));\n\t\t}\n\n\t\t// Delete index\n\t\tawait this.cache.delete(this.indexKey);\n\t}\n\n\tprivate getRecordKey(id: string): string {\n\t\treturn `${this.prefix}:${id}`;\n\t}\n\n\tprivate async getAllRecords(): Promise<AuditRecord[]> {\n\t\tconst ids = (await this.cache.get<string[]>(this.indexKey)) ?? [];\n\t\tconst records: AuditRecord[] = [];\n\t\tconst validIds: string[] = [];\n\n\t\tfor (const id of ids) {\n\t\t\tconst key = this.getRecordKey(id);\n\t\t\tconst serialized = await this.cache.get<SerializedAuditRecord>(key);\n\t\t\tif (serialized) {\n\t\t\t\trecords.push(this.deserializeRecord(serialized));\n\t\t\t\tvalidIds.push(id);\n\t\t\t}\n\t\t}\n\n\t\t// Clean up index if some records expired\n\t\tif (validIds.length !== ids.length) {\n\t\t\tawait this.cache.set(this.indexKey, validIds, this.ttl);\n\t\t}\n\n\t\treturn records;\n\t}\n\n\tprivate serializeRecord(record: AuditRecord): SerializedAuditRecord {\n\t\treturn {\n\t\t\t...record,\n\t\t\ttimestamp: record.timestamp.toISOString(),\n\t\t};\n\t}\n\n\tprivate deserializeRecord(serialized: SerializedAuditRecord): AuditRecord {\n\t\treturn {\n\t\t\t...serialized,\n\t\t\ttimestamp: new Date(serialized.timestamp),\n\t\t};\n\t}\n\n\tprivate applyFilters(\n\t\trecords: AuditRecord[],\n\t\toptions: AuditQueryOptions,\n\t): AuditRecord[] {\n\t\treturn records.filter((record) => {\n\t\t\t// Type filter\n\t\t\tif (options.type !== undefined) {\n\t\t\t\tif (Array.isArray(options.type)) {\n\t\t\t\t\tif (!options.type.includes(record.type)) return false;\n\t\t\t\t} else {\n\t\t\t\t\tif (record.type !== options.type) return false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Entity ID filter\n\t\t\tif (options.entityId !== undefined) {\n\t\t\t\tconst entityId =\n\t\t\t\t\ttypeof options.entityId === 'string'\n\t\t\t\t\t\t? options.entityId\n\t\t\t\t\t\t: JSON.stringify(options.entityId);\n\t\t\t\tconst recordEntityId =\n\t\t\t\t\ttypeof 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\t\tif (recordEntityId !== entityId) return false;\n\t\t\t}\n\n\t\t\t// Table filter\n\t\t\tif (options.table !== undefined) {\n\t\t\t\tif (record.table !== options.table) return false;\n\t\t\t}\n\n\t\t\t// Actor ID filter\n\t\t\tif (options.actorId !== undefined) {\n\t\t\t\tif (record.actor?.id !== options.actorId) return false;\n\t\t\t}\n\n\t\t\t// Date range filters\n\t\t\tif (options.from !== undefined) {\n\t\t\t\tif (record.timestamp < options.from) return false;\n\t\t\t}\n\t\t\tif (options.to !== undefined) {\n\t\t\t\tif (record.timestamp > options.to) return false;\n\t\t\t}\n\n\t\t\treturn true;\n\t\t});\n\t}\n}\n\n/**\n * Serialized version of AuditRecord for cache storage.\n * Dates are stored as ISO strings.\n */\ntype SerializedAuditRecord = Omit<AuditRecord, 'timestamp'> & {\n\ttimestamp: string;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4DA,IAAa,oBAAb,MAMA;CACC,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CAEjB,YAAYA,QAAiC;AAC5C,OAAK,QAAQ,OAAO;AACpB,OAAK,SAAS,OAAO,UAAU;AAC/B,OAAK,MAAM,OAAO;AAClB,OAAK,YAAY,EAAE,KAAK,OAAO;CAC/B;;;;CAKD,MAAM,MAAMC,SAAuC;AAClD,MAAI,QAAQ,WAAW,EACtB;EAID,MAAM,cAAe,MAAM,KAAK,MAAM,IAAc,KAAK,SAAS,IAAK,CAAE;EACzE,MAAMC,SAAmB,CAAE;AAG3B,OAAK,MAAM,UAAU,SAAS;GAC7B,MAAM,MAAM,KAAK,aAAa,OAAO,GAAG;GAExC,MAAM,aAAa,KAAK,gBAAgB,OAAO;AAC/C,SAAM,KAAK,MAAM,IAAI,KAAK,YAAY,KAAK,IAAI;AAC/C,UAAO,K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AAQ,iBACX;QAAI,OAAO,YAAY,QAAQ,KAAM,QAAO;GAAM;AAEnD,OAAI,QAAQ,eACX;QAAI,OAAO,YAAY,QAAQ,GAAI,QAAO;GAAM;AAGjD,UAAO;EACP,EAAC;CACF;AACD"}
@@ -0,0 +1,96 @@
1
+ import { AuditQueryOptions, AuditRecord, AuditStorage, AuditableAction } from "./Auditor-sW7YAJIA.cjs";
2
+ import { Cache } from "@geekmidas/cache";
3
+
4
+ //#region src/cache.d.ts
5
+
6
+ /**
7
+ * Configuration for CacheAuditStorage.
8
+ */
9
+ interface CacheAuditStorageConfig {
10
+ /** Cache instance to use for storage */
11
+ cache: Cache;
12
+ /**
13
+ * Key prefix for audit records.
14
+ * Records are stored as `${prefix}:${id}`.
15
+ * @default 'audit'
16
+ */
17
+ prefix?: string;
18
+ /**
19
+ * TTL (time-to-live) in seconds for audit records.
20
+ * If not set, records use the cache's default TTL.
21
+ */
22
+ ttl?: number;
23
+ }
24
+ /**
25
+ * Cache-based audit storage implementation.
26
+ * Uses any @geekmidas/cache implementation for storage.
27
+ *
28
+ * Best suited for:
29
+ * - Development and testing
30
+ * - Temporary audit logs that don't need persistence
31
+ * - Applications with existing cache infrastructure
32
+ * - Distributed systems needing shared audit state (with Redis/Upstash)
33
+ *
34
+ * Note: Query performance may degrade with large numbers of records
35
+ * since filtering happens in memory after fetching all records.
36
+ *
37
+ * @template TAuditAction - Optional type parameter for type-safe audit actions.
38
+ *
39
+ * @example
40
+ * ```typescript
41
+ * import { CacheAuditStorage } from '@geekmidas/audit/cache';
42
+ * import { InMemoryCache } from '@geekmidas/cache/memory';
43
+ * import { UpstashCache } from '@geekmidas/cache/upstash';
44
+ *
45
+ * // With in-memory cache (development/testing)
46
+ * const storage = new CacheAuditStorage({
47
+ * cache: new InMemoryCache(),
48
+ * ttl: 86400, // 24 hours
49
+ * });
50
+ *
51
+ * // With Upstash Redis (production)
52
+ * const storage = new CacheAuditStorage({
53
+ * cache: new UpstashCache({
54
+ * url: process.env.UPSTASH_REDIS_URL,
55
+ * token: process.env.UPSTASH_REDIS_TOKEN,
56
+ * }),
57
+ * ttl: 604800, // 7 days
58
+ * });
59
+ * ```
60
+ */
61
+ declare class CacheAuditStorage<TAuditAction extends AuditableAction<string, unknown> = AuditableAction<string, unknown>> implements AuditStorage<TAuditAction> {
62
+ private readonly cache;
63
+ private readonly prefix;
64
+ private readonly ttl?;
65
+ private readonly indexKey;
66
+ constructor(config: CacheAuditStorageConfig);
67
+ /**
68
+ * Write audit records to cache.
69
+ */
70
+ write(records: AuditRecord[]): Promise<void>;
71
+ /**
72
+ * Query audit records from cache.
73
+ */
74
+ query(options: AuditQueryOptions): Promise<AuditRecord[]>;
75
+ /**
76
+ * Count audit records matching filters.
77
+ */
78
+ count(options: Omit<AuditQueryOptions, 'limit' | 'offset'>): Promise<number>;
79
+ /**
80
+ * Get all stored records (for testing/debugging).
81
+ */
82
+ getRecords(): Promise<AuditRecord[]>;
83
+ /**
84
+ * Clear all stored records.
85
+ */
86
+ clear(): Promise<void>;
87
+ private getRecordKey;
88
+ private getAllRecords;
89
+ private serializeRecord;
90
+ private deserializeRecord;
91
+ private applyFilters;
92
+ }
93
+ //# sourceMappingURL=cache.d.ts.map
94
+ //#endregion
95
+ export { CacheAuditStorage, CacheAuditStorageConfig };
96
+ //# sourceMappingURL=cache-CDHqXqcl.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache-CDHqXqcl.d.cts","names":[],"sources":["../src/cache.ts"],"sourcesContent":[],"mappings":";;;;;;AAOA;AAqDA;AAA8B,UArDb,uBAAA,CAqDa;EAAA;EACO,KAAoB,EApDjD,KAoDiD;EAAe;;;;;EA+CjC,MAAW,CAAA,EAAA,MAAA;EAAW;;;;EA+BlD,GAQkB,CAAA,EAAA,MAAA;;;;AAlFJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cALZ,uCACS,mCAAmC,6CAI5C,aAAa;;;;;sBAOL;;;;iBAUC,gBAAgB;;;;iBA0BhB,oBAAoB,QAAQ;;;;iBA8BvC,KAAK,yCACZ;;;;gBAQiB,QAAQ;;;;WAOb"}
@@ -0,0 +1,173 @@
1
+
2
+ //#region src/cache.ts
3
+ /**
4
+ * Cache-based audit storage implementation.
5
+ * Uses any @geekmidas/cache implementation for storage.
6
+ *
7
+ * Best suited for:
8
+ * - Development and testing
9
+ * - Temporary audit logs that don't need persistence
10
+ * - Applications with existing cache infrastructure
11
+ * - Distributed systems needing shared audit state (with Redis/Upstash)
12
+ *
13
+ * Note: Query performance may degrade with large numbers of records
14
+ * since filtering happens in memory after fetching all records.
15
+ *
16
+ * @template TAuditAction - Optional type parameter for type-safe audit actions.
17
+ *
18
+ * @example
19
+ * ```typescript
20
+ * import { CacheAuditStorage } from '@geekmidas/audit/cache';
21
+ * import { InMemoryCache } from '@geekmidas/cache/memory';
22
+ * import { UpstashCache } from '@geekmidas/cache/upstash';
23
+ *
24
+ * // With in-memory cache (development/testing)
25
+ * const storage = new CacheAuditStorage({
26
+ * cache: new InMemoryCache(),
27
+ * ttl: 86400, // 24 hours
28
+ * });
29
+ *
30
+ * // With Upstash Redis (production)
31
+ * const storage = new CacheAuditStorage({
32
+ * cache: new UpstashCache({
33
+ * url: process.env.UPSTASH_REDIS_URL,
34
+ * token: process.env.UPSTASH_REDIS_TOKEN,
35
+ * }),
36
+ * ttl: 604800, // 7 days
37
+ * });
38
+ * ```
39
+ */
40
+ var CacheAuditStorage = class {
41
+ cache;
42
+ prefix;
43
+ ttl;
44
+ indexKey;
45
+ constructor(config) {
46
+ this.cache = config.cache;
47
+ this.prefix = config.prefix ?? "audit";
48
+ this.ttl = config.ttl;
49
+ this.indexKey = `${this.prefix}:__index__`;
50
+ }
51
+ /**
52
+ * Write audit records to cache.
53
+ */
54
+ async write(records) {
55
+ if (records.length === 0) return;
56
+ const existingIds = await this.cache.get(this.indexKey) ?? [];
57
+ const newIds = [];
58
+ for (const record of records) {
59
+ const key = this.getRecordKey(record.id);
60
+ const serialized = this.serializeRecord(record);
61
+ await this.cache.set(key, serialized, this.ttl);
62
+ newIds.push(record.id);
63
+ }
64
+ const updatedIds = [...existingIds, ...newIds];
65
+ await this.cache.set(this.indexKey, updatedIds, this.ttl);
66
+ }
67
+ /**
68
+ * Query audit records from cache.
69
+ */
70
+ async query(options) {
71
+ const allRecords = await this.getAllRecords();
72
+ let results = this.applyFilters(allRecords, options);
73
+ const orderBy = options.orderBy ?? "timestamp";
74
+ const orderDirection = options.orderDirection ?? "desc";
75
+ results.sort((a, b) => {
76
+ const aValue = orderBy === "timestamp" ? a.timestamp.getTime() : a.type;
77
+ const bValue = orderBy === "timestamp" ? b.timestamp.getTime() : b.type;
78
+ if (aValue < bValue) return orderDirection === "asc" ? -1 : 1;
79
+ if (aValue > bValue) return orderDirection === "asc" ? 1 : -1;
80
+ return 0;
81
+ });
82
+ if (options.offset !== void 0) results = results.slice(options.offset);
83
+ if (options.limit !== void 0) results = results.slice(0, options.limit);
84
+ return results;
85
+ }
86
+ /**
87
+ * Count audit records matching filters.
88
+ */
89
+ async count(options) {
90
+ const allRecords = await this.getAllRecords();
91
+ return this.applyFilters(allRecords, options).length;
92
+ }
93
+ /**
94
+ * Get all stored records (for testing/debugging).
95
+ */
96
+ async getRecords() {
97
+ return this.getAllRecords();
98
+ }
99
+ /**
100
+ * Clear all stored records.
101
+ */
102
+ async clear() {
103
+ const ids = await this.cache.get(this.indexKey) ?? [];
104
+ for (const id of ids) await this.cache.delete(this.getRecordKey(id));
105
+ await this.cache.delete(this.indexKey);
106
+ }
107
+ getRecordKey(id) {
108
+ return `${this.prefix}:${id}`;
109
+ }
110
+ async getAllRecords() {
111
+ const ids = await this.cache.get(this.indexKey) ?? [];
112
+ const records = [];
113
+ const validIds = [];
114
+ for (const id of ids) {
115
+ const key = this.getRecordKey(id);
116
+ const serialized = await this.cache.get(key);
117
+ if (serialized) {
118
+ records.push(this.deserializeRecord(serialized));
119
+ validIds.push(id);
120
+ }
121
+ }
122
+ if (validIds.length !== ids.length) await this.cache.set(this.indexKey, validIds, this.ttl);
123
+ return records;
124
+ }
125
+ serializeRecord(record) {
126
+ return {
127
+ ...record,
128
+ timestamp: record.timestamp.toISOString()
129
+ };
130
+ }
131
+ deserializeRecord(serialized) {
132
+ return {
133
+ ...serialized,
134
+ timestamp: new Date(serialized.timestamp)
135
+ };
136
+ }
137
+ applyFilters(records, options) {
138
+ return records.filter((record) => {
139
+ if (options.type !== void 0) {
140
+ if (Array.isArray(options.type)) {
141
+ if (!options.type.includes(record.type)) return false;
142
+ } else if (record.type !== options.type) return false;
143
+ }
144
+ if (options.entityId !== void 0) {
145
+ const entityId = typeof options.entityId === "string" ? options.entityId : JSON.stringify(options.entityId);
146
+ const recordEntityId = typeof record.entityId === "string" ? record.entityId : JSON.stringify(record.entityId);
147
+ if (recordEntityId !== entityId) return false;
148
+ }
149
+ if (options.table !== void 0) {
150
+ if (record.table !== options.table) return false;
151
+ }
152
+ if (options.actorId !== void 0) {
153
+ if (record.actor?.id !== options.actorId) return false;
154
+ }
155
+ if (options.from !== void 0) {
156
+ if (record.timestamp < options.from) return false;
157
+ }
158
+ if (options.to !== void 0) {
159
+ if (record.timestamp > options.to) return false;
160
+ }
161
+ return true;
162
+ });
163
+ }
164
+ };
165
+
166
+ //#endregion
167
+ Object.defineProperty(exports, 'CacheAuditStorage', {
168
+ enumerable: true,
169
+ get: function () {
170
+ return CacheAuditStorage;
171
+ }
172
+ });
173
+ //# sourceMappingURL=cache-l7jAptBl.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache-l7jAptBl.cjs","names":["config: CacheAuditStorageConfig","records: AuditRecord[]","newIds: string[]","options: AuditQueryOptions","options: Omit<AuditQueryOptions, 'limit' | 'offset'>","id: string","validIds: string[]","record: AuditRecord","serialized: SerializedAuditRecord"],"sources":["../src/cache.ts"],"sourcesContent":["import type { Cache } from '@geekmidas/cache';\nimport type { AuditQueryOptions, AuditStorage } from './storage';\nimport type { AuditableAction, AuditRecord } from './types';\n\n/**\n * Configuration for CacheAuditStorage.\n */\nexport interface CacheAuditStorageConfig {\n\t/** Cache instance to use for storage */\n\tcache: Cache;\n\t/**\n\t * Key prefix for audit records.\n\t * Records are stored as `${prefix}:${id}`.\n\t * @default 'audit'\n\t */\n\tprefix?: string;\n\t/**\n\t * TTL (time-to-live) in seconds for audit records.\n\t * If not set, records use the cache's default TTL.\n\t */\n\tttl?: number;\n}\n\n/**\n * Cache-based audit storage implementation.\n * Uses any @geekmidas/cache implementation for storage.\n *\n * Best suited for:\n * - Development and testing\n * - Temporary audit logs that don't need persistence\n * - Applications with existing cache infrastructure\n * - Distributed systems needing shared audit state (with Redis/Upstash)\n *\n * Note: Query performance may degrade with large numbers of records\n * since filtering happens in memory after fetching all records.\n *\n * @template TAuditAction - Optional type parameter for type-safe audit actions.\n *\n * @example\n * ```typescript\n * import { CacheAuditStorage } from '@geekmidas/audit/cache';\n * import { InMemoryCache } from '@geekmidas/cache/memory';\n * import { UpstashCache } from '@geekmidas/cache/upstash';\n *\n * // With in-memory cache (development/testing)\n * const storage = new CacheAuditStorage({\n * cache: new InMemoryCache(),\n * ttl: 86400, // 24 hours\n * });\n *\n * // With Upstash Redis (production)\n * const storage = new CacheAuditStorage({\n * cache: new UpstashCache({\n * url: process.env.UPSTASH_REDIS_URL,\n * token: process.env.UPSTASH_REDIS_TOKEN,\n * }),\n * ttl: 604800, // 7 days\n * });\n * ```\n */\nexport class CacheAuditStorage<\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n> implements AuditStorage<TAuditAction>\n{\n\tprivate readonly cache: Cache;\n\tprivate readonly prefix: string;\n\tprivate readonly ttl?: number;\n\tprivate readonly indexKey: string;\n\n\tconstructor(config: CacheAuditStorageConfig) {\n\t\tthis.cache = config.cache;\n\t\tthis.prefix = config.prefix ?? 'audit';\n\t\tthis.ttl = config.ttl;\n\t\tthis.indexKey = `${this.prefix}:__index__`;\n\t}\n\n\t/**\n\t * Write audit records to cache.\n\t */\n\tasync write(records: AuditRecord[]): Promise<void> {\n\t\tif (records.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Get existing index\n\t\tconst existingIds = (await this.cache.get<string[]>(this.indexKey)) ?? [];\n\t\tconst newIds: string[] = [];\n\n\t\t// Write each record\n\t\tfor (const record of records) {\n\t\t\tconst key = this.getRecordKey(record.id);\n\t\t\t// Serialize Date to ISO string for cache storage\n\t\t\tconst serialized = this.serializeRecord(record);\n\t\t\tawait this.cache.set(key, serialized, this.ttl);\n\t\t\tnewIds.push(record.id);\n\t\t}\n\n\t\t// Update index with new IDs\n\t\tconst updatedIds = [...existingIds, ...newIds];\n\t\tawait this.cache.set(this.indexKey, updatedIds, this.ttl);\n\t}\n\n\t/**\n\t * Query audit records from cache.\n\t */\n\tasync query(options: AuditQueryOptions): Promise<AuditRecord[]> {\n\t\tconst allRecords = await this.getAllRecords();\n\t\tlet results = this.applyFilters(allRecords, options);\n\n\t\t// Ordering\n\t\tconst orderBy = options.orderBy ?? 'timestamp';\n\t\tconst orderDirection = options.orderDirection ?? 'desc';\n\t\tresults.sort((a, b) => {\n\t\t\tconst aValue = orderBy === 'timestamp' ? a.timestamp.getTime() : a.type;\n\t\t\tconst bValue = orderBy === 'timestamp' ? b.timestamp.getTime() : b.type;\n\t\t\tif (aValue < bValue) return orderDirection === 'asc' ? -1 : 1;\n\t\t\tif (aValue > bValue) return orderDirection === 'asc' ? 1 : -1;\n\t\t\treturn 0;\n\t\t});\n\n\t\t// Pagination\n\t\tif (options.offset !== undefined) {\n\t\t\tresults = results.slice(options.offset);\n\t\t}\n\t\tif (options.limit !== undefined) {\n\t\t\tresults = results.slice(0, options.limit);\n\t\t}\n\n\t\treturn results;\n\t}\n\n\t/**\n\t * Count audit records matching filters.\n\t */\n\tasync count(\n\t\toptions: Omit<AuditQueryOptions, 'limit' | 'offset'>,\n\t): Promise<number> {\n\t\tconst allRecords = await this.getAllRecords();\n\t\treturn this.applyFilters(allRecords, options).length;\n\t}\n\n\t/**\n\t * Get all stored records (for testing/debugging).\n\t */\n\tasync getRecords(): Promise<AuditRecord[]> {\n\t\treturn this.getAllRecords();\n\t}\n\n\t/**\n\t * Clear all stored records.\n\t */\n\tasync clear(): Promise<void> {\n\t\tconst ids = (await this.cache.get<string[]>(this.indexKey)) ?? [];\n\n\t\t// Delete all records\n\t\tfor (const id of ids) {\n\t\t\tawait this.cache.delete(this.getRecordKey(id));\n\t\t}\n\n\t\t// Delete index\n\t\tawait this.cache.delete(this.indexKey);\n\t}\n\n\tprivate getRecordKey(id: string): string {\n\t\treturn `${this.prefix}:${id}`;\n\t}\n\n\tprivate async getAllRecords(): Promise<AuditRecord[]> {\n\t\tconst ids = (await this.cache.get<string[]>(this.indexKey)) ?? [];\n\t\tconst records: AuditRecord[] = [];\n\t\tconst validIds: string[] = [];\n\n\t\tfor (const id of ids) {\n\t\t\tconst key = this.getRecordKey(id);\n\t\t\tconst serialized = await this.cache.get<SerializedAuditRecord>(key);\n\t\t\tif (serialized) {\n\t\t\t\trecords.push(this.deserializeRecord(serialized));\n\t\t\t\tvalidIds.push(id);\n\t\t\t}\n\t\t}\n\n\t\t// Clean up index if some records expired\n\t\tif (validIds.length !== ids.length) {\n\t\t\tawait this.cache.set(this.indexKey, validIds, this.ttl);\n\t\t}\n\n\t\treturn records;\n\t}\n\n\tprivate serializeRecord(record: AuditRecord): SerializedAuditRecord {\n\t\treturn {\n\t\t\t...record,\n\t\t\ttimestamp: record.timestamp.toISOString(),\n\t\t};\n\t}\n\n\tprivate deserializeRecord(serialized: SerializedAuditRecord): AuditRecord {\n\t\treturn {\n\t\t\t...serialized,\n\t\t\ttimestamp: new Date(serialized.timestamp),\n\t\t};\n\t}\n\n\tprivate applyFilters(\n\t\trecords: AuditRecord[],\n\t\toptions: AuditQueryOptions,\n\t): AuditRecord[] {\n\t\treturn records.filter((record) => {\n\t\t\t// Type filter\n\t\t\tif (options.type !== undefined) {\n\t\t\t\tif (Array.isArray(options.type)) {\n\t\t\t\t\tif (!options.type.includes(record.type)) return false;\n\t\t\t\t} else {\n\t\t\t\t\tif (record.type !== options.type) return false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Entity ID filter\n\t\t\tif (options.entityId !== undefined) {\n\t\t\t\tconst entityId =\n\t\t\t\t\ttypeof options.entityId === 'string'\n\t\t\t\t\t\t? options.entityId\n\t\t\t\t\t\t: JSON.stringify(options.entityId);\n\t\t\t\tconst recordEntityId =\n\t\t\t\t\ttypeof 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\t\tif (recordEntityId !== entityId) return false;\n\t\t\t}\n\n\t\t\t// Table filter\n\t\t\tif (options.table !== undefined) {\n\t\t\t\tif (record.table !== options.table) return false;\n\t\t\t}\n\n\t\t\t// Actor ID filter\n\t\t\tif (options.actorId !== undefined) {\n\t\t\t\tif (record.actor?.id !== options.actorId) return false;\n\t\t\t}\n\n\t\t\t// Date range filters\n\t\t\tif (options.from !== undefined) {\n\t\t\t\tif (record.timestamp < options.from) return false;\n\t\t\t}\n\t\t\tif (options.to !== undefined) {\n\t\t\t\tif (record.timestamp > options.to) return false;\n\t\t\t}\n\n\t\t\treturn true;\n\t\t});\n\t}\n}\n\n/**\n * Serialized version of AuditRecord for cache storage.\n * Dates are stored as ISO strings.\n */\ntype SerializedAuditRecord = Omit<AuditRecord, 'timestamp'> & {\n\ttimestamp: string;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4DA,IAAa,oBAAb,MAMA;CACC,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CAEjB,YAAYA,QAAiC;AAC5C,OAAK,QAAQ,OAAO;AACpB,OAAK,SAAS,OAAO,UAAU;AAC/B,OAAK,MAAM,OAAO;AAClB,OAAK,YAAY,EAAE,KAAK,OAAO;CAC/B;;;;CAKD,MAAM,MAAMC,SAAuC;AAClD,MAAI,QAAQ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,UAAU,QAAQ,SAAS;IACpC,MAAM,wBACE,OAAO,aAAa,WACxB,OAAO,WACP,KAAK,UAAU,OAAO,SAAS;AACnC,QAAI,mBAAmB,SAAU,QAAO;GACxC;AAGD,OAAI,QAAQ,kBACX;QAAI,OAAO,UAAU,QAAQ,MAAO,QAAO;GAAM;AAIlD,OAAI,QAAQ,oBACX;QAAI,OAAO,OAAO,OAAO,QAAQ,QAAS,QAAO;GAAM;AAIxD,OAAI,QAAQ,iBACX;QAAI,OAAO,YAAY,QAAQ,KAAM,QAAO;GAAM;AAEnD,OAAI,QAAQ,eACX;QAAI,OAAO,YAAY,QAAQ,GAAI,QAAO;GAAM;AAGjD,UAAO;EACP,EAAC;CACF;AACD"}
package/dist/cache.cjs ADDED
@@ -0,0 +1,3 @@
1
+ const require_cache = require('./cache-l7jAptBl.cjs');
2
+
3
+ exports.CacheAuditStorage = require_cache.CacheAuditStorage;
@@ -0,0 +1,3 @@
1
+ import "./Auditor-sW7YAJIA.cjs";
2
+ import { CacheAuditStorage, CacheAuditStorageConfig } from "./cache-CDHqXqcl.cjs";
3
+ export { CacheAuditStorage, CacheAuditStorageConfig };
@@ -0,0 +1,3 @@
1
+ import "./Auditor-_Dn2dp8d.mjs";
2
+ import { CacheAuditStorage, CacheAuditStorageConfig } from "./cache-2VI80Vao.mjs";
3
+ export { CacheAuditStorage, CacheAuditStorageConfig };
package/dist/cache.mjs ADDED
@@ -0,0 +1,3 @@
1
+ import { CacheAuditStorage } from "./cache-BbIl31RL.mjs";
2
+
3
+ export { CacheAuditStorage };
package/dist/index.d.cts CHANGED
@@ -1,3 +1,3 @@
1
- import { AuditActor, AuditMetadata, AuditOperation, AuditOptions, AuditQueryOptions, AuditRecord, AuditStorage, AuditableAction, Auditor, ExtractAuditPayload, ExtractAuditType, ExtractAuditorAction, ExtractStorageAuditAction, MappedAudit } from "./Auditor-QYUMGJCH.cjs";
2
- import { DefaultAuditor, DefaultAuditorConfig } from "./DefaultAuditor-BTuMMiWh.cjs";
1
+ import { AuditActor, AuditMetadata, AuditOperation, AuditOptions, AuditQueryOptions, AuditRecord, AuditStorage, AuditableAction, Auditor, ExtractAuditPayload, ExtractAuditType, ExtractAuditorAction, ExtractStorageAuditAction, MappedAudit } from "./Auditor-sW7YAJIA.cjs";
2
+ import { DefaultAuditor, DefaultAuditorConfig } from "./DefaultAuditor-BSYMwojG.cjs";
3
3
  export { AuditActor, AuditMetadata, AuditOperation, AuditOptions, AuditQueryOptions, AuditRecord, AuditStorage, AuditableAction, Auditor, DefaultAuditor, DefaultAuditorConfig, ExtractAuditPayload, ExtractAuditType, ExtractAuditorAction, ExtractStorageAuditAction, MappedAudit };
package/dist/index.d.mts CHANGED
@@ -1,3 +1,3 @@
1
- import { AuditActor, AuditMetadata, AuditOperation, AuditOptions, AuditQueryOptions, AuditRecord, AuditStorage, AuditableAction, Auditor, ExtractAuditPayload, ExtractAuditType, ExtractAuditorAction, ExtractStorageAuditAction, MappedAudit } from "./Auditor-D3me-qKX.mjs";
2
- import { DefaultAuditor, DefaultAuditorConfig } from "./DefaultAuditor-C1FWrJg6.mjs";
1
+ import { AuditActor, AuditMetadata, AuditOperation, AuditOptions, AuditQueryOptions, AuditRecord, AuditStorage, AuditableAction, Auditor, ExtractAuditPayload, ExtractAuditType, ExtractAuditorAction, ExtractStorageAuditAction, MappedAudit } from "./Auditor-_Dn2dp8d.mjs";
2
+ import { DefaultAuditor, DefaultAuditorConfig } from "./DefaultAuditor-CYE-uAry.mjs";
3
3
  export { AuditActor, AuditMetadata, AuditOperation, AuditOptions, AuditQueryOptions, AuditRecord, AuditStorage, AuditableAction, Auditor, DefaultAuditor, DefaultAuditorConfig, ExtractAuditPayload, ExtractAuditType, ExtractAuditorAction, ExtractStorageAuditAction, MappedAudit };
package/dist/kysely.cjs CHANGED
@@ -121,6 +121,30 @@ var KyselyAuditStorage = class {
121
121
  getDatabase() {
122
122
  return this.db;
123
123
  }
124
+ /**
125
+ * Execute a callback within a Kysely transaction with automatic audit handling.
126
+ * The auditor is registered with the transaction and audits are flushed
127
+ * before the transaction commits.
128
+ *
129
+ * If the provided db connection is already a transaction, it will be reused
130
+ * instead of creating a nested transaction.
131
+ */
132
+ async withTransaction(auditor, callback, db) {
133
+ const connection = db ?? this.db;
134
+ if (connection.isTransaction) {
135
+ const trx = connection;
136
+ auditor.setTransaction(trx);
137
+ const result = await callback();
138
+ await auditor.flush(trx);
139
+ return result;
140
+ }
141
+ return connection.transaction().execute(async (trx) => {
142
+ auditor.setTransaction(trx);
143
+ const result = await callback();
144
+ await auditor.flush(trx);
145
+ return result;
146
+ });
147
+ }
124
148
  applyFilters(query, options) {
125
149
  if (options.type !== void 0) if (Array.isArray(options.type)) query = query.where("type", "in", options.type);
126
150
  else query = query.where("type", "=", options.type);