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,1027 @@
1
+ 'use strict';
2
+
3
+ require('crypto');
4
+
5
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
6
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
7
+ }) : x)(function(x) {
8
+ if (typeof require !== "undefined") return require.apply(this, arguments);
9
+ throw Error('Dynamic require of "' + x + '" is not supported');
10
+ });
11
+
12
+ // src/logger.ts
13
+ var LEVEL_RANK = {
14
+ debug: 10,
15
+ info: 20,
16
+ warn: 30,
17
+ error: 40,
18
+ silent: 100
19
+ };
20
+ var LEVEL_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:log-level");
21
+ function readLevel() {
22
+ const g = globalThis;
23
+ return g[LEVEL_KEY] ?? "warn";
24
+ }
25
+ function shouldLog(level) {
26
+ return LEVEL_RANK[level] >= LEVEL_RANK[readLevel()];
27
+ }
28
+ function safeWrite(level, message) {
29
+ try {
30
+ if (!shouldLog(level)) return;
31
+ const line = `[ezlogs] ${message}`;
32
+ if (level === "error" || level === "warn") {
33
+ console.error(line);
34
+ } else {
35
+ console.log(line);
36
+ }
37
+ } catch {
38
+ }
39
+ }
40
+ var logger = {
41
+ debug: (message) => safeWrite("debug", message),
42
+ info: (message) => safeWrite("info", message),
43
+ warn: (message) => safeWrite("warn", message),
44
+ error: (message) => safeWrite("error", message)
45
+ };
46
+
47
+ // src/configuration.ts
48
+ var DEFAULT_EXCLUDED_PATHS = Object.freeze([
49
+ // Next.js / Vercel infrastructure noise
50
+ "/_next/*",
51
+ "/_vercel/*",
52
+ "/__nextjs_*",
53
+ // NextAuth.js / Auth.js — skip session-refresh polls and CSRF/provider
54
+ // metadata GETs (high-frequency, no business meaning), but CAPTURE
55
+ // POSTs (callbacks, signin, signout, register). The POSTs are the
56
+ // actual auth events users care about; the GETs are pure plumbing.
57
+ Object.freeze({ path: "/api/auth/*", methods: ["GET", "HEAD"] }),
58
+ // Generic infrastructure
59
+ "/health*",
60
+ "/api/health",
61
+ "/up",
62
+ "/alive",
63
+ "/ready",
64
+ "/metrics",
65
+ "/favicon.ico",
66
+ "/.well-known*",
67
+ "/robots.txt",
68
+ "/sitemap.xml",
69
+ "/*.hot-update.*",
70
+ // Auth routes (common patterns across Clerk, NextAuth, custom auth)
71
+ "*/login*",
72
+ "*/logout*",
73
+ "*/sign-in*",
74
+ "*/sign-out*",
75
+ "*/signin*",
76
+ "*/signout*",
77
+ "/session*"
78
+ ]);
79
+ var DEFAULT_EXCLUDED_TABLES = Object.freeze([
80
+ // Prisma migration ledger
81
+ "_prisma_migrations",
82
+ // Auth.js / NextAuth Prisma adapter — session/verification-token churn
83
+ // is auth machinery, not business activity. Account/User stay captured.
84
+ "Session",
85
+ "VerificationToken",
86
+ // Common cross-stack convention names for the same things
87
+ "sessions",
88
+ "session",
89
+ "verification_tokens"
90
+ ]);
91
+ var DEFAULT_EXCLUDED_JOB_CLASSES = Object.freeze([]);
92
+ var DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS = Object.freeze(["IntrospectionQuery", "__*"]);
93
+ var DEFAULT_SERVER_URL = "https://app.ezlogs.io";
94
+ var Configuration = class {
95
+ serverUrl = DEFAULT_SERVER_URL;
96
+ projectToken = null;
97
+ captureHttp = true;
98
+ captureDb = true;
99
+ captureJobs = true;
100
+ bufferSize = 1e4;
101
+ /** Default 3000 ms — equivalent to Ruby's 3 seconds. */
102
+ sendInterval = 3e3;
103
+ retryAttempts = 3;
104
+ logLevel = "warn";
105
+ patchGlobalFetch = true;
106
+ actorFromSupabase = true;
107
+ excludedPaths = [];
108
+ excludedTables = [];
109
+ excludedJobClasses = [];
110
+ excludedGraphqlOperations = [];
111
+ excludedGraphqlVariableKeys = [];
112
+ actorFromRequest = null;
113
+ displayNameFor = {};
114
+ isServerActionError = null;
115
+ databaseReader = null;
116
+ databaseSnapshotMode = false;
117
+ databaseUrl = null;
118
+ /**
119
+ * Tables that have the `ezlogs_audit` trigger attached. Detected once
120
+ * at agent startup by reading `information_schema.triggers`. The
121
+ * supabase / drizzle / prisma adapters use this to decide whether
122
+ * their per-mutation emit is redundant: if the table is trigger-
123
+ * tracked the audit-log reader will surface the same write with full
124
+ * old/new state, so the adapter's emit is suppressed. Tables NOT in
125
+ * this set fall through to the adapter so they're still captured.
126
+ *
127
+ * `null` means "detection hasn't run yet or failed" — in that state
128
+ * `databaseReader`-wired apps suppress every adapter emit (the
129
+ * original Phase 5 behavior). After detection completes the agent
130
+ * gives the more accurate per-table answer.
131
+ */
132
+ triggerTrackedTables = null;
133
+ apply(options) {
134
+ if (options.serverUrl !== void 0) this.serverUrl = options.serverUrl;
135
+ this.projectToken = options.projectToken;
136
+ if (options.captureHttp !== void 0) this.captureHttp = options.captureHttp;
137
+ if (options.captureDb !== void 0) this.captureDb = options.captureDb;
138
+ if (options.captureJobs !== void 0) this.captureJobs = options.captureJobs;
139
+ if (options.bufferSize !== void 0) this.bufferSize = options.bufferSize;
140
+ if (options.sendInterval !== void 0) this.sendInterval = options.sendInterval;
141
+ if (options.retryAttempts !== void 0) this.retryAttempts = options.retryAttempts;
142
+ if (options.excludedPaths) this.excludedPaths = [...options.excludedPaths];
143
+ if (options.excludedTables) this.excludedTables = [...options.excludedTables];
144
+ if (options.excludedJobClasses) {
145
+ this.excludedJobClasses = [...options.excludedJobClasses];
146
+ }
147
+ if (options.excludedGraphqlOperations) {
148
+ this.excludedGraphqlOperations = [...options.excludedGraphqlOperations];
149
+ }
150
+ if (options.excludedGraphqlVariableKeys) {
151
+ this.excludedGraphqlVariableKeys = [...options.excludedGraphqlVariableKeys];
152
+ }
153
+ if (options.actorFromRequest) this.actorFromRequest = options.actorFromRequest;
154
+ if (options.displayNameFor) this.displayNameFor = { ...options.displayNameFor };
155
+ if (options.isServerActionError) this.isServerActionError = options.isServerActionError;
156
+ if (options.patchGlobalFetch !== void 0) {
157
+ this.patchGlobalFetch = options.patchGlobalFetch;
158
+ }
159
+ if (options.actorFromSupabase !== void 0) {
160
+ this.actorFromSupabase = options.actorFromSupabase;
161
+ }
162
+ if (options.databaseReader !== void 0) {
163
+ this.databaseReader = options.databaseReader;
164
+ }
165
+ if (options.databaseSnapshotMode !== void 0) {
166
+ this.databaseSnapshotMode = options.databaseSnapshotMode;
167
+ }
168
+ if (options.databaseUrl !== void 0) {
169
+ this.databaseUrl = options.databaseUrl;
170
+ }
171
+ if (options.logLevel) this.logLevel = options.logLevel;
172
+ }
173
+ allExcludedPaths() {
174
+ return [...DEFAULT_EXCLUDED_PATHS, ...this.excludedPaths];
175
+ }
176
+ allExcludedTables() {
177
+ return [...DEFAULT_EXCLUDED_TABLES, ...this.excludedTables];
178
+ }
179
+ allExcludedJobClasses() {
180
+ return [...DEFAULT_EXCLUDED_JOB_CLASSES, ...this.excludedJobClasses];
181
+ }
182
+ allExcludedGraphqlOperations() {
183
+ return [...DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS, ...this.excludedGraphqlOperations];
184
+ }
185
+ };
186
+ var GLOBAL_CONFIG_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:configuration");
187
+ function configuration() {
188
+ const g = globalThis;
189
+ if (!g[GLOBAL_CONFIG_KEY]) {
190
+ g[GLOBAL_CONFIG_KEY] = new Configuration();
191
+ }
192
+ return g[GLOBAL_CONFIG_KEY];
193
+ }
194
+
195
+ // src/event-builder.ts
196
+ var SENSITIVE_KEYS = Object.freeze([
197
+ "password",
198
+ "token",
199
+ "secret",
200
+ "api_key",
201
+ "credit_card"
202
+ ]);
203
+ var VALID_SOURCE_TYPES = [
204
+ "http_request",
205
+ "background_job",
206
+ "database_callback"
207
+ ];
208
+ var VALID_OUTCOMES = ["success", "failure"];
209
+ function build(input) {
210
+ const source_type = validateSourceType(input.source_type);
211
+ const source_data_raw = validateSourceData(input.source_data);
212
+ const outcome = validateOutcome(input.outcome);
213
+ const timestamp = validateTimestamp(input.timestamp ?? null);
214
+ const resource_ids = validateResourceIds(input.resource_ids ?? []);
215
+ const context_raw = validateContext(input.context ?? null);
216
+ const duration_ms = validateDurationMs();
217
+ const error_message = input.error_message ?? null;
218
+ validateOutcomeErrorConsistency(outcome, error_message);
219
+ const source_data = sanitizeRecord(source_data_raw);
220
+ const context = context_raw === null ? null : sanitizeRecord(context_raw);
221
+ const correlation_id = input.correlation_id ?? null;
222
+ const event = {
223
+ timestamp,
224
+ source_type,
225
+ source_data,
226
+ outcome,
227
+ correlation_id,
228
+ resource_ids,
229
+ context,
230
+ duration_ms,
231
+ error_message
232
+ };
233
+ return event;
234
+ }
235
+ function validateSourceType(value) {
236
+ const normalized = String(value);
237
+ if (!VALID_SOURCE_TYPES.includes(normalized)) {
238
+ throw new ArgError(
239
+ `source_type must be one of ${VALID_SOURCE_TYPES.join(", ")}, got: ${normalized}`
240
+ );
241
+ }
242
+ return normalized;
243
+ }
244
+ function validateSourceData(value) {
245
+ if (value === null || value === void 0) {
246
+ throw new ArgError("source_data is required");
247
+ }
248
+ if (!isPlainObject(value)) {
249
+ throw new ArgError(
250
+ `source_data must be an object, got: ${describe(value)}`
251
+ );
252
+ }
253
+ return value;
254
+ }
255
+ function validateOutcome(value) {
256
+ const normalized = String(value);
257
+ if (!VALID_OUTCOMES.includes(normalized)) {
258
+ throw new ArgError(
259
+ `outcome must be one of ${VALID_OUTCOMES.join(", ")}, got: ${normalized}`
260
+ );
261
+ }
262
+ return normalized;
263
+ }
264
+ function validateTimestamp(value) {
265
+ if (value === null) {
266
+ return (/* @__PURE__ */ new Date()).toISOString();
267
+ }
268
+ if (typeof value === "string") {
269
+ const parsed = new Date(value);
270
+ if (Number.isNaN(parsed.getTime())) {
271
+ throw new ArgError(
272
+ `timestamp must be valid ISO 8601 format, got: ${value}`
273
+ );
274
+ }
275
+ return value;
276
+ }
277
+ if (value instanceof Date) {
278
+ if (Number.isNaN(value.getTime())) {
279
+ throw new ArgError("timestamp must be a valid Date");
280
+ }
281
+ return value.toISOString();
282
+ }
283
+ throw new ArgError(
284
+ `timestamp must be a string or Date, got: ${describe(value)}`
285
+ );
286
+ }
287
+ function validateResourceIds(value) {
288
+ if (!Array.isArray(value)) {
289
+ throw new ArgError(`resource_ids must be an array, got: ${describe(value)}`);
290
+ }
291
+ value.forEach((entry, index) => {
292
+ if (!isPlainObject(entry)) {
293
+ throw new ArgError(
294
+ `resource_ids[${index}] must be an object, got: ${describe(entry)}`
295
+ );
296
+ }
297
+ const e = entry;
298
+ if (!("resource_type" in e) || !("resource_id" in e)) {
299
+ throw new ArgError(
300
+ `resource_ids[${index}] must have resource_type and resource_id keys, got: ${Object.keys(e).join(", ")}`
301
+ );
302
+ }
303
+ if (typeof e.resource_type !== "string") {
304
+ throw new ArgError(
305
+ `resource_ids[${index}].resource_type must be a string, got: ${describe(e.resource_type)}`
306
+ );
307
+ }
308
+ if (typeof e.resource_id !== "string") {
309
+ throw new ArgError(
310
+ `resource_ids[${index}].resource_id must be a string, got: ${describe(e.resource_id)}`
311
+ );
312
+ }
313
+ });
314
+ return value;
315
+ }
316
+ function validateContext(value) {
317
+ if (value === null) return null;
318
+ if (!isPlainObject(value)) {
319
+ throw new ArgError(
320
+ `context must be an object or null, got: ${describe(value)}`
321
+ );
322
+ }
323
+ return value;
324
+ }
325
+ function validateDurationMs(value) {
326
+ return null;
327
+ }
328
+ function validateOutcomeErrorConsistency(outcome, error_message) {
329
+ if (outcome === "failure") {
330
+ if (error_message === null || error_message === "") {
331
+ throw new ArgError("error_message is required when outcome is 'failure'");
332
+ }
333
+ } else if (outcome === "success") {
334
+ if (error_message !== null) {
335
+ throw new ArgError("error_message must be null when outcome is 'success'");
336
+ }
337
+ }
338
+ }
339
+ function sanitizeRecord(input) {
340
+ const result = {};
341
+ for (const key of Object.keys(input)) {
342
+ const value = input[key];
343
+ if (isSensitiveKey(key)) {
344
+ result[key] = "[FILTERED]";
345
+ } else if (isPlainObject(value)) {
346
+ result[key] = sanitizeRecord(value);
347
+ } else if (Array.isArray(value)) {
348
+ result[key] = value.map(
349
+ (item) => isPlainObject(item) ? sanitizeRecord(item) : item
350
+ );
351
+ } else {
352
+ result[key] = value;
353
+ }
354
+ }
355
+ return result;
356
+ }
357
+ function isSensitiveKey(key) {
358
+ const lower = key.toLowerCase();
359
+ return SENSITIVE_KEYS.some((p) => lower.includes(p));
360
+ }
361
+ function isPlainObject(value) {
362
+ if (value === null || typeof value !== "object") return false;
363
+ const proto = Object.getPrototypeOf(value);
364
+ return proto === Object.prototype || proto === null;
365
+ }
366
+ function describe(value) {
367
+ if (value === null) return "null";
368
+ if (Array.isArray(value)) return "Array";
369
+ return typeof value;
370
+ }
371
+ var ArgError = class extends Error {
372
+ constructor(message) {
373
+ super(message);
374
+ this.name = "ArgError";
375
+ }
376
+ };
377
+
378
+ // src/pipeline/buffer.ts
379
+ var GLOBAL_QUEUE_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:buffer-queue");
380
+ function getQueue() {
381
+ const g = globalThis;
382
+ if (!g[GLOBAL_QUEUE_KEY]) g[GLOBAL_QUEUE_KEY] = [];
383
+ return g[GLOBAL_QUEUE_KEY];
384
+ }
385
+ function pushEvent(event) {
386
+ try {
387
+ const queue = getQueue();
388
+ const max = maxSize();
389
+ if (queue.length >= max) {
390
+ queue.shift();
391
+ logger.warn(`Buffer full (${max}), dropped oldest event`);
392
+ }
393
+ queue.push(event);
394
+ } catch (error) {
395
+ logger.error(`pushEvent failed: ${describe2(error)}`);
396
+ }
397
+ }
398
+ function maxSize() {
399
+ try {
400
+ return configuration().bufferSize;
401
+ } catch {
402
+ return 1e4;
403
+ }
404
+ }
405
+ function describe2(error) {
406
+ if (error instanceof Error) return `${error.name}: ${error.message}`;
407
+ return String(error);
408
+ }
409
+
410
+ // src/edge-fallback.ts
411
+ var ALS_CTOR = loadAsyncLocalStorage();
412
+ function loadAsyncLocalStorage() {
413
+ const fromGlobal = globalThis.AsyncLocalStorage;
414
+ if (typeof fromGlobal === "function") return fromGlobal;
415
+ try {
416
+ const req = typeof __require !== "undefined" ? __require : (
417
+ // In ESM, `createRequire` is the official escape hatch.
418
+ // We pull it via globalThis to avoid a static `import`
419
+ // that would itself be browser-bundled.
420
+ void 0
421
+ );
422
+ if (typeof req === "function") {
423
+ const moduleName = ["async", "hooks"].join("_");
424
+ const mod = req("node:" + moduleName);
425
+ if (typeof mod.AsyncLocalStorage === "function") return mod.AsyncLocalStorage;
426
+ }
427
+ } catch {
428
+ }
429
+ return null;
430
+ }
431
+ function createScopedStorage(key = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:default-scoped-storage")) {
432
+ const globalStore = globalThis;
433
+ let entry = globalStore[key];
434
+ if (!entry) {
435
+ const als2 = (() => {
436
+ if (!ALS_CTOR) return null;
437
+ try {
438
+ return new ALS_CTOR();
439
+ } catch {
440
+ return null;
441
+ }
442
+ })();
443
+ entry = { als: als2, edgeFallback: null };
444
+ globalStore[key] = entry;
445
+ }
446
+ const als = entry.als;
447
+ const stateRef = entry;
448
+ return {
449
+ read() {
450
+ if (als) return als.getStore()?.value ?? null;
451
+ return stateRef.edgeFallback?.value ?? null;
452
+ },
453
+ run(value, callback) {
454
+ if (als) return als.run({ value }, callback);
455
+ const previous = stateRef.edgeFallback;
456
+ stateRef.edgeFallback = { value };
457
+ try {
458
+ return callback();
459
+ } finally {
460
+ stateRef.edgeFallback = previous;
461
+ }
462
+ },
463
+ update(value) {
464
+ if (als) {
465
+ const store = als.getStore();
466
+ if (store) store.value = value;
467
+ return;
468
+ }
469
+ stateRef.edgeFallback = { value };
470
+ },
471
+ _resetForTests() {
472
+ stateRef.edgeFallback = null;
473
+ },
474
+ _isAsyncLocalStorage() {
475
+ return als !== null;
476
+ }
477
+ };
478
+ }
479
+
480
+ // src/correlation.ts
481
+ var storage = createScopedStorage(
482
+ /* @__PURE__ */ Symbol.for("ezlogs-nextjs:correlation-storage")
483
+ );
484
+ function current() {
485
+ return storage.read();
486
+ }
487
+
488
+ // src/actor.ts
489
+ var storage2 = createScopedStorage(
490
+ /* @__PURE__ */ Symbol.for("ezlogs-nextjs:actor-storage")
491
+ );
492
+ function getCurrentActor() {
493
+ return storage2.read();
494
+ }
495
+
496
+ // src/db/shared.ts
497
+ var IGNORED_ATTRIBUTES = Object.freeze([
498
+ "id",
499
+ "createdAt",
500
+ "created_at",
501
+ "updatedAt",
502
+ "updated_at",
503
+ "deletedAt",
504
+ "deleted_at",
505
+ // Auth.js / NextAuth standard columns
506
+ "emailVerified",
507
+ "expires"
508
+ ]);
509
+ var DB_SENSITIVE_PATTERNS = Object.freeze([
510
+ "password",
511
+ "token",
512
+ "secret",
513
+ "api_key",
514
+ "credit_card",
515
+ "ssn",
516
+ "social_security",
517
+ "encrypted"
518
+ ]);
519
+ function emitDbEvent(input) {
520
+ try {
521
+ const config = configuration();
522
+ if (!config.captureDb) return;
523
+ if (config.allExcludedTables().includes(input.modelClass)) return;
524
+ if (config.databaseReader && !input._fromTrigger) {
525
+ const tracked = config.triggerTrackedTables;
526
+ if (tracked === null || tracked.has(input.modelClass)) return;
527
+ }
528
+ if (input.operation === "update") {
529
+ const meaningful = input.changes ? filterMeaningfulChanges(input.changes) : [];
530
+ if (meaningful.length === 0) return;
531
+ }
532
+ const resourceIdStr = input.resourceId === null || input.resourceId === void 0 ? null : String(input.resourceId);
533
+ const context = buildContext(input);
534
+ const event = build({
535
+ source_type: "database_callback",
536
+ source_data: {
537
+ model_class: input.modelClass,
538
+ operation: input.operation
539
+ },
540
+ outcome: "success",
541
+ correlation_id: current(),
542
+ resource_ids: resourceIdStr === null ? [] : [{ resource_type: input.modelClass, resource_id: resourceIdStr }],
543
+ context,
544
+ duration_ms: null
545
+ });
546
+ pushEvent(event);
547
+ } catch (error) {
548
+ logger.debug(`db emit failed: ${describeError(error)}`);
549
+ }
550
+ }
551
+ function buildContext(input) {
552
+ const context = {};
553
+ const actor = getCurrentActor();
554
+ if (actor) context.actor = actor;
555
+ if ((input.operation === "create" || input.operation === "destroy") && input.initialAttributes) {
556
+ const filtered = filterMeaningfulAttributes(input.initialAttributes);
557
+ if (filtered !== null) context.initial_attributes = filtered;
558
+ }
559
+ if (input.operation === "update" && input.changes) {
560
+ const filtered = filterMeaningfulChanges(input.changes);
561
+ if (filtered.length > 0) {
562
+ context.changes = filtered.map((c) => {
563
+ const out = {
564
+ attribute: c.attribute,
565
+ to: formatForJson(c.to)
566
+ };
567
+ if (c.from !== void 0) out.from = formatForJson(c.from);
568
+ return out;
569
+ });
570
+ }
571
+ }
572
+ const displayName = input.displayName ?? (input.modelInstance ? resolveDisplayName(input.modelClass, input.modelInstance) : null);
573
+ if (displayName !== null) context.display_name = displayName;
574
+ return Object.keys(context).length === 0 ? null : context;
575
+ }
576
+ function filterMeaningfulAttributes(attrs) {
577
+ const out = {};
578
+ for (const key of Object.keys(attrs)) {
579
+ if (!isMeaningfulAttribute(key)) continue;
580
+ const value = attrs[key];
581
+ if (value === null || value === void 0) continue;
582
+ if (!isScalar(value)) continue;
583
+ out[key] = formatForJson(value);
584
+ }
585
+ return Object.keys(out).length === 0 ? null : out;
586
+ }
587
+ function filterMeaningfulChanges(changes) {
588
+ return changes.filter((c) => {
589
+ if (!isMeaningfulAttribute(c.attribute)) return false;
590
+ if (!isScalar(c.to)) return false;
591
+ if (c.from === void 0) return true;
592
+ if (!isScalar(c.from)) return false;
593
+ return valuesActuallyChanged(c.from, c.to);
594
+ });
595
+ }
596
+ function isMeaningfulAttribute(name) {
597
+ if (IGNORED_ATTRIBUTES.includes(name)) return false;
598
+ if (isDbSensitive(name)) return false;
599
+ return true;
600
+ }
601
+ function isDbSensitive(name) {
602
+ const lower = name.toLowerCase();
603
+ return DB_SENSITIVE_PATTERNS.some((p) => lower.includes(p));
604
+ }
605
+ function isScalar(value) {
606
+ if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint" || value instanceof Date) {
607
+ return true;
608
+ }
609
+ if (isPrismaDecimal(value)) return true;
610
+ if (Buffer.isBuffer?.(value)) return false;
611
+ if (Array.isArray(value)) return value.every((v) => isScalar(v));
612
+ return false;
613
+ }
614
+ function valuesActuallyChanged(from, to) {
615
+ if (from === null && to === null) return false;
616
+ if (from instanceof Date && to instanceof Date) {
617
+ return from.getTime() !== to.getTime();
618
+ }
619
+ return from !== to;
620
+ }
621
+ function formatForJson(value) {
622
+ if (value === null || value === void 0) return value;
623
+ if (value instanceof Date) return value.toISOString();
624
+ if (typeof value === "bigint") return value.toString();
625
+ if (isPrismaDecimal(value)) return Number(value.toString());
626
+ if (Array.isArray(value)) return value.map(formatForJson);
627
+ return value;
628
+ }
629
+ function isPrismaDecimal(value) {
630
+ if (value === null || typeof value !== "object") return false;
631
+ const obj = value;
632
+ return typeof obj.toString === "function" && typeof obj.toFixed === "function" && "d" in obj && "e" in obj && "s" in obj;
633
+ }
634
+ function resolveDisplayName(modelClass, instance) {
635
+ try {
636
+ const config = configuration();
637
+ const resolver = config.displayNameFor[modelClass];
638
+ const resolved = applyResolver(resolver, instance);
639
+ if (resolved !== null) return resolved;
640
+ for (const field of ["name", "title", "number"]) {
641
+ const value = instance[field];
642
+ if (value !== null && value !== void 0 && String(value).length > 0) {
643
+ return String(value);
644
+ }
645
+ }
646
+ } catch {
647
+ }
648
+ return null;
649
+ }
650
+ function applyResolver(resolver, instance) {
651
+ if (typeof resolver === "string") {
652
+ const value = instance[resolver];
653
+ if (value !== null && value !== void 0 && String(value).length > 0) {
654
+ return String(value);
655
+ }
656
+ return null;
657
+ }
658
+ if (typeof resolver === "function") {
659
+ try {
660
+ const value = resolver(instance);
661
+ if (typeof value === "string" && value.length > 0) return value;
662
+ if (value !== null && value !== void 0 && String(value).length > 0) {
663
+ return String(value);
664
+ }
665
+ } catch {
666
+ }
667
+ }
668
+ return null;
669
+ }
670
+ function describeError(error) {
671
+ if (error instanceof Error) return `${error.name}: ${error.message}`;
672
+ return String(error);
673
+ }
674
+
675
+ // src/db/supabase.ts
676
+ function triggerPathWillCapture(table) {
677
+ const config = configuration();
678
+ if (!config.databaseReader) return false;
679
+ const tracked = config.triggerTrackedTables;
680
+ if (tracked === null) return false;
681
+ return tracked.has(table);
682
+ }
683
+ function wrapSupabase(client) {
684
+ if (client === null || typeof client !== "object") return client;
685
+ const obj = client;
686
+ if (obj.__ezlogsWrapped) return client;
687
+ if (typeof obj.from !== "function") return client;
688
+ const originalFrom = obj.from.bind(obj);
689
+ const prereadRow = async (table, filters) => {
690
+ try {
691
+ const queryBuilder = originalFrom(table);
692
+ if (typeof queryBuilder.select !== "function") return null;
693
+ let chain = queryBuilder.select("*");
694
+ for (const f of filters) {
695
+ if (typeof chain.eq !== "function") return null;
696
+ chain = chain.eq(
697
+ f.column,
698
+ f.value
699
+ );
700
+ }
701
+ if (typeof chain.maybeSingle === "function") {
702
+ chain = chain.maybeSingle();
703
+ } else if (typeof chain.limit === "function") {
704
+ chain = chain.limit(
705
+ 1
706
+ );
707
+ }
708
+ const result = await chain;
709
+ if (!result || result.error) return null;
710
+ if (Array.isArray(result.data)) {
711
+ const first = result.data[0];
712
+ return isPlainObject2(first) ? first : null;
713
+ }
714
+ return isPlainObject2(result.data) ? result.data : null;
715
+ } catch {
716
+ return null;
717
+ }
718
+ };
719
+ obj.from = ((table) => {
720
+ const builder = originalFrom(table);
721
+ return wrapBuilder(builder, table, prereadRow);
722
+ });
723
+ Object.defineProperty(obj, "__ezlogsWrapped", {
724
+ value: true,
725
+ enumerable: false,
726
+ configurable: false
727
+ });
728
+ registerActorSource(obj);
729
+ return client;
730
+ }
731
+ var GLOBAL_CLIENT_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:supabase-current-client");
732
+ function registerActorSource(client) {
733
+ try {
734
+ const g = globalThis;
735
+ g[GLOBAL_CLIENT_KEY] = client;
736
+ } catch {
737
+ }
738
+ }
739
+ async function tryExtractSupabaseActor() {
740
+ const g = globalThis;
741
+ const client = g[GLOBAL_CLIENT_KEY];
742
+ if (!client || typeof client.auth?.getUser !== "function") return null;
743
+ try {
744
+ const { data } = await client.auth.getUser();
745
+ const user = data?.user;
746
+ if (!user || typeof user.id !== "string" || !user.id) return null;
747
+ const label = user.user_metadata?.full_name ?? user.user_metadata?.name ?? user.email ?? void 0;
748
+ return label ? { id: user.id, label } : { id: user.id };
749
+ } catch {
750
+ return null;
751
+ }
752
+ }
753
+ function wrapBuilder(builder, table, preread) {
754
+ if (typeof builder.insert === "function") {
755
+ builder.insert = wrapMutation(
756
+ builder.insert.bind(builder),
757
+ { table, operation: "create" },
758
+ preread
759
+ );
760
+ }
761
+ if (typeof builder.upsert === "function") {
762
+ builder.upsert = wrapMutation(
763
+ builder.upsert.bind(builder),
764
+ { table, operation: "update" },
765
+ // supabase upsert is conceptually update-with-fallback
766
+ preread
767
+ );
768
+ }
769
+ if (typeof builder.update === "function") {
770
+ builder.update = wrapMutation(
771
+ builder.update.bind(builder),
772
+ { table, operation: "update" },
773
+ preread
774
+ );
775
+ }
776
+ if (typeof builder.delete === "function") {
777
+ builder.delete = wrapDeleteMutation(
778
+ builder.delete.bind(builder),
779
+ table,
780
+ preread
781
+ );
782
+ }
783
+ return builder;
784
+ }
785
+ function wrapMutation(original, ctx, preread) {
786
+ return (values, options) => {
787
+ const filterBuilder = original(values, options);
788
+ const filters = trackFilterChain(filterBuilder);
789
+ const beforeRowRef = { row: null };
790
+ return instrumentFilterBuilder(
791
+ filterBuilder,
792
+ (result) => emitFromMutation(ctx, values, result, filters, beforeRowRef.row),
793
+ async () => {
794
+ if (ctx.operation !== "update") return;
795
+ if (triggerPathWillCapture(ctx.table)) return;
796
+ const prereadFilters = prereadFiltersFromCaptured(filters);
797
+ if (prereadFilters !== null) {
798
+ beforeRowRef.row = await preread(ctx.table, prereadFilters);
799
+ }
800
+ }
801
+ );
802
+ };
803
+ }
804
+ function wrapDeleteMutation(original, table, preread) {
805
+ return (options) => {
806
+ const filterBuilder = original(options);
807
+ const filters = trackFilterChain(filterBuilder);
808
+ const beforeRowRef = { row: null };
809
+ return instrumentFilterBuilder(
810
+ filterBuilder,
811
+ (result) => emitFromDelete(table, result, filters, beforeRowRef.row),
812
+ async () => {
813
+ if (triggerPathWillCapture(table)) return;
814
+ const prereadFilters = prereadFiltersFromCaptured(filters);
815
+ if (prereadFilters !== null) {
816
+ beforeRowRef.row = await preread(table, prereadFilters);
817
+ }
818
+ }
819
+ );
820
+ };
821
+ }
822
+ function trackFilterChain(builder) {
823
+ const captured = { equals: {}, inLists: {} };
824
+ if (!builder || typeof builder !== "object") return captured;
825
+ const builderObj = builder;
826
+ const wrapEq = (orig) => {
827
+ if (typeof orig !== "function") return orig;
828
+ return function patchedEq(column, value) {
829
+ try {
830
+ if (typeof column === "string") captured.equals[column] = value;
831
+ } catch {
832
+ }
833
+ return orig.call(this, column, value);
834
+ };
835
+ };
836
+ const wrapIn = (orig) => {
837
+ if (typeof orig !== "function") return orig;
838
+ return function patchedIn(column, values) {
839
+ try {
840
+ if (typeof column === "string" && Array.isArray(values)) {
841
+ captured.inLists[column] = values;
842
+ }
843
+ } catch {
844
+ }
845
+ return orig.call(this, column, values);
846
+ };
847
+ };
848
+ const wrapMatch = (orig) => {
849
+ if (typeof orig !== "function") return orig;
850
+ return function patchedMatch(query) {
851
+ try {
852
+ if (isPlainObject2(query)) {
853
+ for (const [k, v] of Object.entries(query)) {
854
+ captured.equals[k] = v;
855
+ }
856
+ }
857
+ } catch {
858
+ }
859
+ return orig.call(this, query);
860
+ };
861
+ };
862
+ if ("eq" in builderObj) builderObj.eq = wrapEq(builderObj.eq);
863
+ if ("in" in builderObj) builderObj.in = wrapIn(builderObj.in);
864
+ if ("match" in builderObj) builderObj.match = wrapMatch(builderObj.match);
865
+ return captured;
866
+ }
867
+ function instrumentFilterBuilder(builder, onResolved, beforeFire) {
868
+ if (!builder || typeof builder !== "object") return builder;
869
+ const originalThen = builder.then?.bind(builder);
870
+ if (typeof originalThen !== "function") return builder;
871
+ const wrappedThen = function ezlogsThen(onfulfilled, onrejected) {
872
+ return new Promise((resolve, reject) => {
873
+ const proceed = () => {
874
+ originalThen(
875
+ (raw) => {
876
+ const result = raw;
877
+ try {
878
+ if (!result?.error) onResolved(result);
879
+ } catch (error) {
880
+ logger.debug(`supabase capture failed: ${describeError2(error)}`);
881
+ }
882
+ try {
883
+ const passthrough = onfulfilled ? onfulfilled(raw) : raw;
884
+ resolve(passthrough);
885
+ } catch (e) {
886
+ reject(e);
887
+ }
888
+ },
889
+ (reason) => {
890
+ try {
891
+ const passthrough = onrejected ? onrejected(reason) : Promise.reject(reason);
892
+ resolve(passthrough);
893
+ } catch (e) {
894
+ reject(e);
895
+ }
896
+ }
897
+ );
898
+ };
899
+ if (beforeFire) {
900
+ beforeFire().then(proceed, () => proceed());
901
+ } else {
902
+ proceed();
903
+ }
904
+ });
905
+ };
906
+ builder.then = wrappedThen;
907
+ return builder;
908
+ }
909
+ function emitFromMutation(ctx, values, result, filters, beforeRow) {
910
+ if (Array.isArray(values)) {
911
+ const resultRows = pickResultRows(result);
912
+ values.forEach((row, index) => {
913
+ if (!isPlainObject2(row)) return;
914
+ emitOneRow(ctx, row, resultRows[index] ?? null, filters, null);
915
+ });
916
+ return;
917
+ }
918
+ if (!isPlainObject2(values)) {
919
+ emitDbEvent({
920
+ modelClass: ctx.table,
921
+ operation: ctx.operation,
922
+ resourceId: idFromFilters(filters)
923
+ });
924
+ return;
925
+ }
926
+ const valueObj = values;
927
+ const resultRow = pickFirstResultRow(result);
928
+ emitOneRow(ctx, valueObj, resultRow, filters, beforeRow);
929
+ }
930
+ function emitOneRow(ctx, values, resultRow, filters, beforeRow) {
931
+ const resourceId = resultRow?.id ?? values.id ?? idFromFilters(filters) ?? null;
932
+ const merged = beforeRow ?? resultRow ?? values;
933
+ const displayName = resolveDisplayName(ctx.table, merged);
934
+ if (ctx.operation === "create") {
935
+ emitDbEvent({
936
+ modelClass: ctx.table,
937
+ operation: "create",
938
+ resourceId,
939
+ initialAttributes: values,
940
+ displayName,
941
+ modelInstance: merged
942
+ });
943
+ return;
944
+ }
945
+ if (ctx.operation === "update") {
946
+ const changes = buildUpdateChanges(values, beforeRow);
947
+ emitDbEvent({
948
+ modelClass: ctx.table,
949
+ operation: "update",
950
+ resourceId,
951
+ changes,
952
+ displayName,
953
+ modelInstance: merged
954
+ });
955
+ }
956
+ }
957
+ function emitFromDelete(table, result, filters, beforeRow) {
958
+ const resultRow = pickFirstResultRow(result);
959
+ const resourceId = resultRow?.id ?? beforeRow?.id ?? idFromFilters(filters) ?? null;
960
+ const richestRow = resultRow ?? beforeRow;
961
+ const displayName = richestRow ? resolveDisplayName(table, richestRow) : null;
962
+ emitDbEvent({
963
+ modelClass: table,
964
+ operation: "destroy",
965
+ resourceId,
966
+ displayName,
967
+ modelInstance: richestRow
968
+ });
969
+ }
970
+ function prereadFiltersFromCaptured(filters) {
971
+ const idValue = filters.equals["id"];
972
+ if (!isScalarFilterValue(idValue)) return null;
973
+ const out = [];
974
+ for (const column of Object.keys(filters.equals)) {
975
+ const value = filters.equals[column];
976
+ if (!isScalarFilterValue(value)) continue;
977
+ out.push({ column, value });
978
+ }
979
+ return out;
980
+ }
981
+ function idFromFilters(filters) {
982
+ const value = filters.equals["id"];
983
+ return isScalarFilterValue(value) ? value : null;
984
+ }
985
+ function isScalarFilterValue(value) {
986
+ return typeof value === "string" || typeof value === "number" || typeof value === "bigint";
987
+ }
988
+ function buildUpdateChanges(values, beforeRow) {
989
+ return Object.keys(values).map((attribute) => {
990
+ const change = {
991
+ attribute,
992
+ to: values[attribute]
993
+ };
994
+ if (beforeRow && Object.prototype.hasOwnProperty.call(beforeRow, attribute)) {
995
+ change.from = beforeRow[attribute];
996
+ }
997
+ return change;
998
+ });
999
+ }
1000
+ function pickFirstResultRow(result) {
1001
+ if (!result || result.error) return null;
1002
+ if (Array.isArray(result.data)) {
1003
+ const first = result.data[0];
1004
+ return isPlainObject2(first) ? first : null;
1005
+ }
1006
+ if (isPlainObject2(result.data)) return result.data;
1007
+ return null;
1008
+ }
1009
+ function pickResultRows(result) {
1010
+ if (!result || result.error || !Array.isArray(result.data)) return [];
1011
+ return result.data.map(
1012
+ (row) => isPlainObject2(row) ? row : void 0
1013
+ );
1014
+ }
1015
+ function isPlainObject2(value) {
1016
+ if (value === null || typeof value !== "object") return false;
1017
+ if (Array.isArray(value)) return false;
1018
+ if (value instanceof Date) return false;
1019
+ return true;
1020
+ }
1021
+ function describeError2(error) {
1022
+ if (error instanceof Error) return `${error.name}: ${error.message}`;
1023
+ return String(error);
1024
+ }
1025
+
1026
+ exports.tryExtractSupabaseActor = tryExtractSupabaseActor;
1027
+ exports.wrapSupabase = wrapSupabase;