ezlogs-nextjs 0.1.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 (59) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +779 -0
  3. package/bin/install-triggers.cjs +75 -0
  4. package/dist/actors/index.cjs +111 -0
  5. package/dist/actors/index.d.cts +52 -0
  6. package/dist/actors/index.d.ts +52 -0
  7. package/dist/actors/index.js +107 -0
  8. package/dist/configuration-D9x9Gvds.d.cts +190 -0
  9. package/dist/configuration-D9x9Gvds.d.ts +190 -0
  10. package/dist/db/drizzle.cjs +898 -0
  11. package/dist/db/drizzle.d.cts +68 -0
  12. package/dist/db/drizzle.d.ts +68 -0
  13. package/dist/db/drizzle.js +893 -0
  14. package/dist/db/prisma.cjs +826 -0
  15. package/dist/db/prisma.d.cts +3 -0
  16. package/dist/db/prisma.d.ts +3 -0
  17. package/dist/db/prisma.js +824 -0
  18. package/dist/db/supabase.cjs +1027 -0
  19. package/dist/db/supabase.d.cts +32 -0
  20. package/dist/db/supabase.d.ts +32 -0
  21. package/dist/db/supabase.js +1024 -0
  22. package/dist/index.cjs +3329 -0
  23. package/dist/index.d.cts +305 -0
  24. package/dist/index.d.ts +305 -0
  25. package/dist/index.js +3317 -0
  26. package/dist/jobs/bullmq.cjs +624 -0
  27. package/dist/jobs/bullmq.d.cts +33 -0
  28. package/dist/jobs/bullmq.d.ts +33 -0
  29. package/dist/jobs/bullmq.js +621 -0
  30. package/dist/jobs/inngest.cjs +645 -0
  31. package/dist/jobs/inngest.d.cts +21 -0
  32. package/dist/jobs/inngest.d.ts +21 -0
  33. package/dist/jobs/inngest.js +642 -0
  34. package/dist/jobs/supabase-queues.cjs +661 -0
  35. package/dist/jobs/supabase-queues.d.cts +37 -0
  36. package/dist/jobs/supabase-queues.d.ts +37 -0
  37. package/dist/jobs/supabase-queues.js +657 -0
  38. package/dist/jobs/trigger.cjs +622 -0
  39. package/dist/jobs/trigger.d.cts +46 -0
  40. package/dist/jobs/trigger.d.ts +46 -0
  41. package/dist/jobs/trigger.js +619 -0
  42. package/dist/jobs/upstash-workflow.cjs +673 -0
  43. package/dist/jobs/upstash-workflow.d.cts +57 -0
  44. package/dist/jobs/upstash-workflow.d.ts +57 -0
  45. package/dist/jobs/upstash-workflow.js +669 -0
  46. package/dist/nextjs-plugin/index.cjs +232 -0
  47. package/dist/nextjs-plugin/index.d.cts +68 -0
  48. package/dist/nextjs-plugin/index.d.ts +68 -0
  49. package/dist/nextjs-plugin/index.js +229 -0
  50. package/dist/nextjs-plugin/loader.cjs +16248 -0
  51. package/dist/nextjs-plugin/loader.d.cts +61 -0
  52. package/dist/nextjs-plugin/loader.d.ts +61 -0
  53. package/dist/nextjs-plugin/loader.js +16242 -0
  54. package/dist/triggers/index.cjs +1354 -0
  55. package/dist/triggers/index.d.cts +243 -0
  56. package/dist/triggers/index.d.ts +243 -0
  57. package/dist/triggers/index.js +1337 -0
  58. package/package.json +150 -0
  59. package/sql/postgres/00_install.sql +205 -0
@@ -0,0 +1,824 @@
1
+ import 'crypto';
2
+
3
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
4
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
5
+ }) : x)(function(x) {
6
+ if (typeof require !== "undefined") return require.apply(this, arguments);
7
+ throw Error('Dynamic require of "' + x + '" is not supported');
8
+ });
9
+
10
+ // src/logger.ts
11
+ var LEVEL_RANK = {
12
+ debug: 10,
13
+ info: 20,
14
+ warn: 30,
15
+ error: 40,
16
+ silent: 100
17
+ };
18
+ var LEVEL_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:log-level");
19
+ function readLevel() {
20
+ const g = globalThis;
21
+ return g[LEVEL_KEY] ?? "warn";
22
+ }
23
+ function shouldLog(level) {
24
+ return LEVEL_RANK[level] >= LEVEL_RANK[readLevel()];
25
+ }
26
+ function safeWrite(level, message) {
27
+ try {
28
+ if (!shouldLog(level)) return;
29
+ const line = `[ezlogs] ${message}`;
30
+ if (level === "error" || level === "warn") {
31
+ console.error(line);
32
+ } else {
33
+ console.log(line);
34
+ }
35
+ } catch {
36
+ }
37
+ }
38
+ var logger = {
39
+ debug: (message) => safeWrite("debug", message),
40
+ info: (message) => safeWrite("info", message),
41
+ warn: (message) => safeWrite("warn", message),
42
+ error: (message) => safeWrite("error", message)
43
+ };
44
+
45
+ // src/configuration.ts
46
+ var DEFAULT_EXCLUDED_PATHS = Object.freeze([
47
+ // Next.js / Vercel infrastructure noise
48
+ "/_next/*",
49
+ "/_vercel/*",
50
+ "/__nextjs_*",
51
+ // NextAuth.js / Auth.js — skip session-refresh polls and CSRF/provider
52
+ // metadata GETs (high-frequency, no business meaning), but CAPTURE
53
+ // POSTs (callbacks, signin, signout, register). The POSTs are the
54
+ // actual auth events users care about; the GETs are pure plumbing.
55
+ Object.freeze({ path: "/api/auth/*", methods: ["GET", "HEAD"] }),
56
+ // Generic infrastructure
57
+ "/health*",
58
+ "/api/health",
59
+ "/up",
60
+ "/alive",
61
+ "/ready",
62
+ "/metrics",
63
+ "/favicon.ico",
64
+ "/.well-known*",
65
+ "/robots.txt",
66
+ "/sitemap.xml",
67
+ "/*.hot-update.*",
68
+ // Auth routes (common patterns across Clerk, NextAuth, custom auth)
69
+ "*/login*",
70
+ "*/logout*",
71
+ "*/sign-in*",
72
+ "*/sign-out*",
73
+ "*/signin*",
74
+ "*/signout*",
75
+ "/session*"
76
+ ]);
77
+ var DEFAULT_EXCLUDED_TABLES = Object.freeze([
78
+ // Prisma migration ledger
79
+ "_prisma_migrations",
80
+ // Auth.js / NextAuth Prisma adapter — session/verification-token churn
81
+ // is auth machinery, not business activity. Account/User stay captured.
82
+ "Session",
83
+ "VerificationToken",
84
+ // Common cross-stack convention names for the same things
85
+ "sessions",
86
+ "session",
87
+ "verification_tokens"
88
+ ]);
89
+ var DEFAULT_EXCLUDED_JOB_CLASSES = Object.freeze([]);
90
+ var DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS = Object.freeze(["IntrospectionQuery", "__*"]);
91
+ var DEFAULT_SERVER_URL = "https://app.ezlogs.io";
92
+ var Configuration = class {
93
+ serverUrl = DEFAULT_SERVER_URL;
94
+ projectToken = null;
95
+ captureHttp = true;
96
+ captureDb = true;
97
+ captureJobs = true;
98
+ bufferSize = 1e4;
99
+ /** Default 3000 ms — equivalent to Ruby's 3 seconds. */
100
+ sendInterval = 3e3;
101
+ retryAttempts = 3;
102
+ logLevel = "warn";
103
+ patchGlobalFetch = true;
104
+ actorFromSupabase = true;
105
+ excludedPaths = [];
106
+ excludedTables = [];
107
+ excludedJobClasses = [];
108
+ excludedGraphqlOperations = [];
109
+ excludedGraphqlVariableKeys = [];
110
+ actorFromRequest = null;
111
+ displayNameFor = {};
112
+ isServerActionError = null;
113
+ databaseReader = null;
114
+ databaseSnapshotMode = false;
115
+ databaseUrl = null;
116
+ /**
117
+ * Tables that have the `ezlogs_audit` trigger attached. Detected once
118
+ * at agent startup by reading `information_schema.triggers`. The
119
+ * supabase / drizzle / prisma adapters use this to decide whether
120
+ * their per-mutation emit is redundant: if the table is trigger-
121
+ * tracked the audit-log reader will surface the same write with full
122
+ * old/new state, so the adapter's emit is suppressed. Tables NOT in
123
+ * this set fall through to the adapter so they're still captured.
124
+ *
125
+ * `null` means "detection hasn't run yet or failed" — in that state
126
+ * `databaseReader`-wired apps suppress every adapter emit (the
127
+ * original Phase 5 behavior). After detection completes the agent
128
+ * gives the more accurate per-table answer.
129
+ */
130
+ triggerTrackedTables = null;
131
+ apply(options) {
132
+ if (options.serverUrl !== void 0) this.serverUrl = options.serverUrl;
133
+ this.projectToken = options.projectToken;
134
+ if (options.captureHttp !== void 0) this.captureHttp = options.captureHttp;
135
+ if (options.captureDb !== void 0) this.captureDb = options.captureDb;
136
+ if (options.captureJobs !== void 0) this.captureJobs = options.captureJobs;
137
+ if (options.bufferSize !== void 0) this.bufferSize = options.bufferSize;
138
+ if (options.sendInterval !== void 0) this.sendInterval = options.sendInterval;
139
+ if (options.retryAttempts !== void 0) this.retryAttempts = options.retryAttempts;
140
+ if (options.excludedPaths) this.excludedPaths = [...options.excludedPaths];
141
+ if (options.excludedTables) this.excludedTables = [...options.excludedTables];
142
+ if (options.excludedJobClasses) {
143
+ this.excludedJobClasses = [...options.excludedJobClasses];
144
+ }
145
+ if (options.excludedGraphqlOperations) {
146
+ this.excludedGraphqlOperations = [...options.excludedGraphqlOperations];
147
+ }
148
+ if (options.excludedGraphqlVariableKeys) {
149
+ this.excludedGraphqlVariableKeys = [...options.excludedGraphqlVariableKeys];
150
+ }
151
+ if (options.actorFromRequest) this.actorFromRequest = options.actorFromRequest;
152
+ if (options.displayNameFor) this.displayNameFor = { ...options.displayNameFor };
153
+ if (options.isServerActionError) this.isServerActionError = options.isServerActionError;
154
+ if (options.patchGlobalFetch !== void 0) {
155
+ this.patchGlobalFetch = options.patchGlobalFetch;
156
+ }
157
+ if (options.actorFromSupabase !== void 0) {
158
+ this.actorFromSupabase = options.actorFromSupabase;
159
+ }
160
+ if (options.databaseReader !== void 0) {
161
+ this.databaseReader = options.databaseReader;
162
+ }
163
+ if (options.databaseSnapshotMode !== void 0) {
164
+ this.databaseSnapshotMode = options.databaseSnapshotMode;
165
+ }
166
+ if (options.databaseUrl !== void 0) {
167
+ this.databaseUrl = options.databaseUrl;
168
+ }
169
+ if (options.logLevel) this.logLevel = options.logLevel;
170
+ }
171
+ allExcludedPaths() {
172
+ return [...DEFAULT_EXCLUDED_PATHS, ...this.excludedPaths];
173
+ }
174
+ allExcludedTables() {
175
+ return [...DEFAULT_EXCLUDED_TABLES, ...this.excludedTables];
176
+ }
177
+ allExcludedJobClasses() {
178
+ return [...DEFAULT_EXCLUDED_JOB_CLASSES, ...this.excludedJobClasses];
179
+ }
180
+ allExcludedGraphqlOperations() {
181
+ return [...DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS, ...this.excludedGraphqlOperations];
182
+ }
183
+ };
184
+ var GLOBAL_CONFIG_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:configuration");
185
+ function configuration() {
186
+ const g = globalThis;
187
+ if (!g[GLOBAL_CONFIG_KEY]) {
188
+ g[GLOBAL_CONFIG_KEY] = new Configuration();
189
+ }
190
+ return g[GLOBAL_CONFIG_KEY];
191
+ }
192
+
193
+ // src/event-builder.ts
194
+ var SENSITIVE_KEYS = Object.freeze([
195
+ "password",
196
+ "token",
197
+ "secret",
198
+ "api_key",
199
+ "credit_card"
200
+ ]);
201
+ var VALID_SOURCE_TYPES = [
202
+ "http_request",
203
+ "background_job",
204
+ "database_callback"
205
+ ];
206
+ var VALID_OUTCOMES = ["success", "failure"];
207
+ function build(input) {
208
+ const source_type = validateSourceType(input.source_type);
209
+ const source_data_raw = validateSourceData(input.source_data);
210
+ const outcome = validateOutcome(input.outcome);
211
+ const timestamp = validateTimestamp(input.timestamp ?? null);
212
+ const resource_ids = validateResourceIds(input.resource_ids ?? []);
213
+ const context_raw = validateContext(input.context ?? null);
214
+ const duration_ms = validateDurationMs();
215
+ const error_message = input.error_message ?? null;
216
+ validateOutcomeErrorConsistency(outcome, error_message);
217
+ const source_data = sanitizeRecord(source_data_raw);
218
+ const context = context_raw === null ? null : sanitizeRecord(context_raw);
219
+ const correlation_id = input.correlation_id ?? null;
220
+ const event = {
221
+ timestamp,
222
+ source_type,
223
+ source_data,
224
+ outcome,
225
+ correlation_id,
226
+ resource_ids,
227
+ context,
228
+ duration_ms,
229
+ error_message
230
+ };
231
+ return event;
232
+ }
233
+ function validateSourceType(value) {
234
+ const normalized = String(value);
235
+ if (!VALID_SOURCE_TYPES.includes(normalized)) {
236
+ throw new ArgError(
237
+ `source_type must be one of ${VALID_SOURCE_TYPES.join(", ")}, got: ${normalized}`
238
+ );
239
+ }
240
+ return normalized;
241
+ }
242
+ function validateSourceData(value) {
243
+ if (value === null || value === void 0) {
244
+ throw new ArgError("source_data is required");
245
+ }
246
+ if (!isPlainObject(value)) {
247
+ throw new ArgError(
248
+ `source_data must be an object, got: ${describe(value)}`
249
+ );
250
+ }
251
+ return value;
252
+ }
253
+ function validateOutcome(value) {
254
+ const normalized = String(value);
255
+ if (!VALID_OUTCOMES.includes(normalized)) {
256
+ throw new ArgError(
257
+ `outcome must be one of ${VALID_OUTCOMES.join(", ")}, got: ${normalized}`
258
+ );
259
+ }
260
+ return normalized;
261
+ }
262
+ function validateTimestamp(value) {
263
+ if (value === null) {
264
+ return (/* @__PURE__ */ new Date()).toISOString();
265
+ }
266
+ if (typeof value === "string") {
267
+ const parsed = new Date(value);
268
+ if (Number.isNaN(parsed.getTime())) {
269
+ throw new ArgError(
270
+ `timestamp must be valid ISO 8601 format, got: ${value}`
271
+ );
272
+ }
273
+ return value;
274
+ }
275
+ if (value instanceof Date) {
276
+ if (Number.isNaN(value.getTime())) {
277
+ throw new ArgError("timestamp must be a valid Date");
278
+ }
279
+ return value.toISOString();
280
+ }
281
+ throw new ArgError(
282
+ `timestamp must be a string or Date, got: ${describe(value)}`
283
+ );
284
+ }
285
+ function validateResourceIds(value) {
286
+ if (!Array.isArray(value)) {
287
+ throw new ArgError(`resource_ids must be an array, got: ${describe(value)}`);
288
+ }
289
+ value.forEach((entry, index) => {
290
+ if (!isPlainObject(entry)) {
291
+ throw new ArgError(
292
+ `resource_ids[${index}] must be an object, got: ${describe(entry)}`
293
+ );
294
+ }
295
+ const e = entry;
296
+ if (!("resource_type" in e) || !("resource_id" in e)) {
297
+ throw new ArgError(
298
+ `resource_ids[${index}] must have resource_type and resource_id keys, got: ${Object.keys(e).join(", ")}`
299
+ );
300
+ }
301
+ if (typeof e.resource_type !== "string") {
302
+ throw new ArgError(
303
+ `resource_ids[${index}].resource_type must be a string, got: ${describe(e.resource_type)}`
304
+ );
305
+ }
306
+ if (typeof e.resource_id !== "string") {
307
+ throw new ArgError(
308
+ `resource_ids[${index}].resource_id must be a string, got: ${describe(e.resource_id)}`
309
+ );
310
+ }
311
+ });
312
+ return value;
313
+ }
314
+ function validateContext(value) {
315
+ if (value === null) return null;
316
+ if (!isPlainObject(value)) {
317
+ throw new ArgError(
318
+ `context must be an object or null, got: ${describe(value)}`
319
+ );
320
+ }
321
+ return value;
322
+ }
323
+ function validateDurationMs(value) {
324
+ return null;
325
+ }
326
+ function validateOutcomeErrorConsistency(outcome, error_message) {
327
+ if (outcome === "failure") {
328
+ if (error_message === null || error_message === "") {
329
+ throw new ArgError("error_message is required when outcome is 'failure'");
330
+ }
331
+ } else if (outcome === "success") {
332
+ if (error_message !== null) {
333
+ throw new ArgError("error_message must be null when outcome is 'success'");
334
+ }
335
+ }
336
+ }
337
+ function sanitizeRecord(input) {
338
+ const result = {};
339
+ for (const key of Object.keys(input)) {
340
+ const value = input[key];
341
+ if (isSensitiveKey(key)) {
342
+ result[key] = "[FILTERED]";
343
+ } else if (isPlainObject(value)) {
344
+ result[key] = sanitizeRecord(value);
345
+ } else if (Array.isArray(value)) {
346
+ result[key] = value.map(
347
+ (item) => isPlainObject(item) ? sanitizeRecord(item) : item
348
+ );
349
+ } else {
350
+ result[key] = value;
351
+ }
352
+ }
353
+ return result;
354
+ }
355
+ function isSensitiveKey(key) {
356
+ const lower = key.toLowerCase();
357
+ return SENSITIVE_KEYS.some((p) => lower.includes(p));
358
+ }
359
+ function isPlainObject(value) {
360
+ if (value === null || typeof value !== "object") return false;
361
+ const proto = Object.getPrototypeOf(value);
362
+ return proto === Object.prototype || proto === null;
363
+ }
364
+ function describe(value) {
365
+ if (value === null) return "null";
366
+ if (Array.isArray(value)) return "Array";
367
+ return typeof value;
368
+ }
369
+ var ArgError = class extends Error {
370
+ constructor(message) {
371
+ super(message);
372
+ this.name = "ArgError";
373
+ }
374
+ };
375
+
376
+ // src/pipeline/buffer.ts
377
+ var GLOBAL_QUEUE_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:buffer-queue");
378
+ function getQueue() {
379
+ const g = globalThis;
380
+ if (!g[GLOBAL_QUEUE_KEY]) g[GLOBAL_QUEUE_KEY] = [];
381
+ return g[GLOBAL_QUEUE_KEY];
382
+ }
383
+ function pushEvent(event) {
384
+ try {
385
+ const queue = getQueue();
386
+ const max = maxSize();
387
+ if (queue.length >= max) {
388
+ queue.shift();
389
+ logger.warn(`Buffer full (${max}), dropped oldest event`);
390
+ }
391
+ queue.push(event);
392
+ } catch (error) {
393
+ logger.error(`pushEvent failed: ${describe2(error)}`);
394
+ }
395
+ }
396
+ function maxSize() {
397
+ try {
398
+ return configuration().bufferSize;
399
+ } catch {
400
+ return 1e4;
401
+ }
402
+ }
403
+ function describe2(error) {
404
+ if (error instanceof Error) return `${error.name}: ${error.message}`;
405
+ return String(error);
406
+ }
407
+
408
+ // src/edge-fallback.ts
409
+ var ALS_CTOR = loadAsyncLocalStorage();
410
+ function loadAsyncLocalStorage() {
411
+ const fromGlobal = globalThis.AsyncLocalStorage;
412
+ if (typeof fromGlobal === "function") return fromGlobal;
413
+ try {
414
+ const req = typeof __require !== "undefined" ? __require : (
415
+ // In ESM, `createRequire` is the official escape hatch.
416
+ // We pull it via globalThis to avoid a static `import`
417
+ // that would itself be browser-bundled.
418
+ void 0
419
+ );
420
+ if (typeof req === "function") {
421
+ const moduleName = ["async", "hooks"].join("_");
422
+ const mod = req("node:" + moduleName);
423
+ if (typeof mod.AsyncLocalStorage === "function") return mod.AsyncLocalStorage;
424
+ }
425
+ } catch {
426
+ }
427
+ return null;
428
+ }
429
+ function createScopedStorage(key = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:default-scoped-storage")) {
430
+ const globalStore = globalThis;
431
+ let entry = globalStore[key];
432
+ if (!entry) {
433
+ const als2 = (() => {
434
+ if (!ALS_CTOR) return null;
435
+ try {
436
+ return new ALS_CTOR();
437
+ } catch {
438
+ return null;
439
+ }
440
+ })();
441
+ entry = { als: als2, edgeFallback: null };
442
+ globalStore[key] = entry;
443
+ }
444
+ const als = entry.als;
445
+ const stateRef = entry;
446
+ return {
447
+ read() {
448
+ if (als) return als.getStore()?.value ?? null;
449
+ return stateRef.edgeFallback?.value ?? null;
450
+ },
451
+ run(value, callback) {
452
+ if (als) return als.run({ value }, callback);
453
+ const previous = stateRef.edgeFallback;
454
+ stateRef.edgeFallback = { value };
455
+ try {
456
+ return callback();
457
+ } finally {
458
+ stateRef.edgeFallback = previous;
459
+ }
460
+ },
461
+ update(value) {
462
+ if (als) {
463
+ const store = als.getStore();
464
+ if (store) store.value = value;
465
+ return;
466
+ }
467
+ stateRef.edgeFallback = { value };
468
+ },
469
+ _resetForTests() {
470
+ stateRef.edgeFallback = null;
471
+ },
472
+ _isAsyncLocalStorage() {
473
+ return als !== null;
474
+ }
475
+ };
476
+ }
477
+
478
+ // src/correlation.ts
479
+ var storage = createScopedStorage(
480
+ /* @__PURE__ */ Symbol.for("ezlogs-nextjs:correlation-storage")
481
+ );
482
+ function current() {
483
+ return storage.read();
484
+ }
485
+
486
+ // src/actor.ts
487
+ var storage2 = createScopedStorage(
488
+ /* @__PURE__ */ Symbol.for("ezlogs-nextjs:actor-storage")
489
+ );
490
+ function getCurrentActor() {
491
+ return storage2.read();
492
+ }
493
+
494
+ // src/db/shared.ts
495
+ var IGNORED_ATTRIBUTES = Object.freeze([
496
+ "id",
497
+ "createdAt",
498
+ "created_at",
499
+ "updatedAt",
500
+ "updated_at",
501
+ "deletedAt",
502
+ "deleted_at",
503
+ // Auth.js / NextAuth standard columns
504
+ "emailVerified",
505
+ "expires"
506
+ ]);
507
+ var DB_SENSITIVE_PATTERNS = Object.freeze([
508
+ "password",
509
+ "token",
510
+ "secret",
511
+ "api_key",
512
+ "credit_card",
513
+ "ssn",
514
+ "social_security",
515
+ "encrypted"
516
+ ]);
517
+ function emitDbEvent(input) {
518
+ try {
519
+ const config = configuration();
520
+ if (!config.captureDb) return;
521
+ if (config.allExcludedTables().includes(input.modelClass)) return;
522
+ if (config.databaseReader && !input._fromTrigger) {
523
+ const tracked = config.triggerTrackedTables;
524
+ if (tracked === null || tracked.has(input.modelClass)) return;
525
+ }
526
+ if (input.operation === "update") {
527
+ const meaningful = input.changes ? filterMeaningfulChanges(input.changes) : [];
528
+ if (meaningful.length === 0) return;
529
+ }
530
+ const resourceIdStr = input.resourceId === null || input.resourceId === void 0 ? null : String(input.resourceId);
531
+ const context = buildContext(input);
532
+ const event = build({
533
+ source_type: "database_callback",
534
+ source_data: {
535
+ model_class: input.modelClass,
536
+ operation: input.operation
537
+ },
538
+ outcome: "success",
539
+ correlation_id: current(),
540
+ resource_ids: resourceIdStr === null ? [] : [{ resource_type: input.modelClass, resource_id: resourceIdStr }],
541
+ context,
542
+ duration_ms: null
543
+ });
544
+ pushEvent(event);
545
+ } catch (error) {
546
+ logger.debug(`db emit failed: ${describeError(error)}`);
547
+ }
548
+ }
549
+ function buildContext(input) {
550
+ const context = {};
551
+ const actor = getCurrentActor();
552
+ if (actor) context.actor = actor;
553
+ if ((input.operation === "create" || input.operation === "destroy") && input.initialAttributes) {
554
+ const filtered = filterMeaningfulAttributes(input.initialAttributes);
555
+ if (filtered !== null) context.initial_attributes = filtered;
556
+ }
557
+ if (input.operation === "update" && input.changes) {
558
+ const filtered = filterMeaningfulChanges(input.changes);
559
+ if (filtered.length > 0) {
560
+ context.changes = filtered.map((c) => {
561
+ const out = {
562
+ attribute: c.attribute,
563
+ to: formatForJson(c.to)
564
+ };
565
+ if (c.from !== void 0) out.from = formatForJson(c.from);
566
+ return out;
567
+ });
568
+ }
569
+ }
570
+ const displayName = input.displayName ?? (input.modelInstance ? resolveDisplayName(input.modelClass, input.modelInstance) : null);
571
+ if (displayName !== null) context.display_name = displayName;
572
+ return Object.keys(context).length === 0 ? null : context;
573
+ }
574
+ function filterMeaningfulAttributes(attrs) {
575
+ const out = {};
576
+ for (const key of Object.keys(attrs)) {
577
+ if (!isMeaningfulAttribute(key)) continue;
578
+ const value = attrs[key];
579
+ if (value === null || value === void 0) continue;
580
+ if (!isScalar(value)) continue;
581
+ out[key] = formatForJson(value);
582
+ }
583
+ return Object.keys(out).length === 0 ? null : out;
584
+ }
585
+ function filterMeaningfulChanges(changes) {
586
+ return changes.filter((c) => {
587
+ if (!isMeaningfulAttribute(c.attribute)) return false;
588
+ if (!isScalar(c.to)) return false;
589
+ if (c.from === void 0) return true;
590
+ if (!isScalar(c.from)) return false;
591
+ return valuesActuallyChanged(c.from, c.to);
592
+ });
593
+ }
594
+ function isMeaningfulAttribute(name) {
595
+ if (IGNORED_ATTRIBUTES.includes(name)) return false;
596
+ if (isDbSensitive(name)) return false;
597
+ return true;
598
+ }
599
+ function isDbSensitive(name) {
600
+ const lower = name.toLowerCase();
601
+ return DB_SENSITIVE_PATTERNS.some((p) => lower.includes(p));
602
+ }
603
+ function isScalar(value) {
604
+ if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint" || value instanceof Date) {
605
+ return true;
606
+ }
607
+ if (isPrismaDecimal(value)) return true;
608
+ if (Buffer.isBuffer?.(value)) return false;
609
+ if (Array.isArray(value)) return value.every((v) => isScalar(v));
610
+ return false;
611
+ }
612
+ function valuesActuallyChanged(from, to) {
613
+ if (from === null && to === null) return false;
614
+ if (from instanceof Date && to instanceof Date) {
615
+ return from.getTime() !== to.getTime();
616
+ }
617
+ return from !== to;
618
+ }
619
+ function formatForJson(value) {
620
+ if (value === null || value === void 0) return value;
621
+ if (value instanceof Date) return value.toISOString();
622
+ if (typeof value === "bigint") return value.toString();
623
+ if (isPrismaDecimal(value)) return Number(value.toString());
624
+ if (Array.isArray(value)) return value.map(formatForJson);
625
+ return value;
626
+ }
627
+ function isPrismaDecimal(value) {
628
+ if (value === null || typeof value !== "object") return false;
629
+ const obj = value;
630
+ return typeof obj.toString === "function" && typeof obj.toFixed === "function" && "d" in obj && "e" in obj && "s" in obj;
631
+ }
632
+ function resolveDisplayName(modelClass, instance) {
633
+ try {
634
+ const config = configuration();
635
+ const resolver = config.displayNameFor[modelClass];
636
+ const resolved = applyResolver(resolver, instance);
637
+ if (resolved !== null) return resolved;
638
+ for (const field of ["name", "title", "number"]) {
639
+ const value = instance[field];
640
+ if (value !== null && value !== void 0 && String(value).length > 0) {
641
+ return String(value);
642
+ }
643
+ }
644
+ } catch {
645
+ }
646
+ return null;
647
+ }
648
+ function applyResolver(resolver, instance) {
649
+ if (typeof resolver === "string") {
650
+ const value = instance[resolver];
651
+ if (value !== null && value !== void 0 && String(value).length > 0) {
652
+ return String(value);
653
+ }
654
+ return null;
655
+ }
656
+ if (typeof resolver === "function") {
657
+ try {
658
+ const value = resolver(instance);
659
+ if (typeof value === "string" && value.length > 0) return value;
660
+ if (value !== null && value !== void 0 && String(value).length > 0) {
661
+ return String(value);
662
+ }
663
+ } catch {
664
+ }
665
+ }
666
+ return null;
667
+ }
668
+ function describeError(error) {
669
+ if (error instanceof Error) return `${error.name}: ${error.message}`;
670
+ return String(error);
671
+ }
672
+
673
+ // src/db/prisma.ts
674
+ var CAPTURED_OPERATIONS = /* @__PURE__ */ new Set([
675
+ "create",
676
+ "createMany",
677
+ "createManyAndReturn",
678
+ "update",
679
+ "updateMany",
680
+ "upsert",
681
+ "delete",
682
+ "deleteMany"
683
+ ]);
684
+ var OPERATION_TO_DB_OPERATION = {
685
+ create: "create",
686
+ createMany: "create",
687
+ createManyAndReturn: "create",
688
+ update: "update",
689
+ updateMany: "update",
690
+ upsert: "update",
691
+ delete: "destroy",
692
+ deleteMany: "destroy"
693
+ };
694
+ function ezlogsPrisma() {
695
+ return {
696
+ name: "ezlogs",
697
+ query: {
698
+ $allModels: {
699
+ async $allOperations(ctx) {
700
+ if (!CAPTURED_OPERATIONS.has(ctx.operation)) {
701
+ return ctx.query(ctx.args);
702
+ }
703
+ const result = await ctx.query(ctx.args);
704
+ try {
705
+ recordPrismaOperation(ctx, result);
706
+ } catch (error) {
707
+ logger.debug(`prisma capture failed: ${describeError2(error)}`);
708
+ }
709
+ return result;
710
+ }
711
+ }
712
+ }
713
+ };
714
+ }
715
+ function recordPrismaOperation(ctx, result) {
716
+ const dbOperation = OPERATION_TO_DB_OPERATION[ctx.operation];
717
+ if (!dbOperation) return;
718
+ if (isBatchResult(result)) {
719
+ emitDbEvent({
720
+ modelClass: ctx.model,
721
+ operation: dbOperation,
722
+ resourceId: null,
723
+ // For batch updates we still capture the `args.data` shape so
724
+ // downstream sees what columns were touched even if we can't
725
+ // identify a specific row.
726
+ ...dbOperation === "update" && isPlainObject2(ctx.args.data) ? {
727
+ changes: extractChangesFromUpdateData(ctx.args.data)
728
+ } : {},
729
+ ...dbOperation === "create" && isPlainObject2(ctx.args.data) ? {
730
+ initialAttributes: ctx.args.data
731
+ } : {}
732
+ });
733
+ return;
734
+ }
735
+ if (Array.isArray(result)) {
736
+ for (const row of result) {
737
+ emitSingleRowEvent(ctx, dbOperation, row);
738
+ }
739
+ return;
740
+ }
741
+ emitSingleRowEvent(ctx, dbOperation, result);
742
+ }
743
+ function emitSingleRowEvent(ctx, dbOperation, row) {
744
+ if (!isPlainObject2(row)) {
745
+ emitDbEvent({
746
+ modelClass: ctx.model,
747
+ operation: dbOperation,
748
+ resourceId: null
749
+ });
750
+ return;
751
+ }
752
+ const rowObj = row;
753
+ const resourceId = rowObj.id ?? null;
754
+ const displayName = resolveDisplayName(ctx.model, rowObj);
755
+ if (dbOperation === "create") {
756
+ emitDbEvent({
757
+ modelClass: ctx.model,
758
+ operation: "create",
759
+ resourceId,
760
+ initialAttributes: extractCreateAttributes(ctx, rowObj),
761
+ displayName,
762
+ modelInstance: rowObj
763
+ });
764
+ return;
765
+ }
766
+ if (dbOperation === "update") {
767
+ emitDbEvent({
768
+ modelClass: ctx.model,
769
+ operation: "update",
770
+ resourceId,
771
+ changes: extractUpdateChangesFromArgs(ctx, rowObj),
772
+ displayName,
773
+ modelInstance: rowObj
774
+ });
775
+ return;
776
+ }
777
+ emitDbEvent({
778
+ modelClass: ctx.model,
779
+ operation: "destroy",
780
+ resourceId,
781
+ displayName,
782
+ modelInstance: rowObj
783
+ });
784
+ }
785
+ function extractCreateAttributes(ctx, resultRow) {
786
+ if (isPlainObject2(ctx.args.data)) {
787
+ return ctx.args.data;
788
+ }
789
+ if (ctx.operation === "upsert" && isPlainObject2(ctx.args.create)) {
790
+ return ctx.args.create;
791
+ }
792
+ return resultRow;
793
+ }
794
+ function extractUpdateChangesFromArgs(ctx, resultRow) {
795
+ const data = isPlainObject2(ctx.args.data) ? ctx.args.data : ctx.operation === "upsert" && isPlainObject2(ctx.args.update) ? ctx.args.update : null;
796
+ if (!data) return [];
797
+ return Object.keys(data).map((attribute) => ({
798
+ attribute,
799
+ from: null,
800
+ to: resultRow[attribute] ?? data[attribute]
801
+ }));
802
+ }
803
+ function extractChangesFromUpdateData(data) {
804
+ return Object.keys(data).map((attribute) => ({
805
+ attribute,
806
+ from: null,
807
+ to: data[attribute]
808
+ }));
809
+ }
810
+ function isBatchResult(value) {
811
+ return isPlainObject2(value) && typeof value.count === "number" && Object.keys(value).length === 1;
812
+ }
813
+ function isPlainObject2(value) {
814
+ if (value === null || typeof value !== "object") return false;
815
+ if (Array.isArray(value)) return false;
816
+ if (value instanceof Date) return false;
817
+ return true;
818
+ }
819
+ function describeError2(error) {
820
+ if (error instanceof Error) return `${error.name}: ${error.message}`;
821
+ return String(error);
822
+ }
823
+
824
+ export { ezlogsPrisma };