ezlogs-nextjs 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +15 -2
  2. package/bin/install-triggers.cjs +33 -5
  3. package/dist/actors/index.cjs +5 -37
  4. package/dist/actors/index.js +2 -34
  5. package/dist/chunk-C5OSM557.js +39 -0
  6. package/dist/chunk-CE3R7DVB.js +1127 -0
  7. package/dist/chunk-CU45I2WR.js +498 -0
  8. package/dist/chunk-DKRNNI4I.js +180 -0
  9. package/dist/chunk-SIAA4J6H.js +17 -0
  10. package/dist/chunk-UQHEW6ER.js +119 -0
  11. package/dist/chunk-UWHYJH4M.cjs +126 -0
  12. package/dist/chunk-V5YNKKTG.cjs +42 -0
  13. package/dist/chunk-WASXTDLW.cjs +1151 -0
  14. package/dist/chunk-Y5NSHKWQ.cjs +182 -0
  15. package/dist/chunk-YX2XPLOA.cjs +508 -0
  16. package/dist/chunk-ZDSQYCYV.cjs +21 -0
  17. package/dist/db/drizzle.cjs +6 -821
  18. package/dist/db/drizzle.js +5 -820
  19. package/dist/db/prisma.cjs +28 -853
  20. package/dist/db/prisma.js +14 -839
  21. package/dist/db/supabase.cjs +21 -836
  22. package/dist/db/supabase.js +14 -829
  23. package/dist/index.cjs +132 -2362
  24. package/dist/index.js +34 -2270
  25. package/dist/jobs/bullmq.cjs +13 -1465
  26. package/dist/jobs/bullmq.js +7 -1459
  27. package/dist/jobs/inngest.cjs +14 -1422
  28. package/dist/jobs/inngest.js +8 -1416
  29. package/dist/jobs/supabase-queues.cjs +15 -1467
  30. package/dist/jobs/supabase-queues.js +10 -1462
  31. package/dist/jobs/trigger.cjs +9 -1454
  32. package/dist/jobs/trigger.js +5 -1450
  33. package/dist/jobs/upstash-workflow.cjs +30 -1456
  34. package/dist/jobs/upstash-workflow.d.cts +2 -1
  35. package/dist/jobs/upstash-workflow.d.ts +2 -1
  36. package/dist/jobs/upstash-workflow.js +27 -1453
  37. package/dist/nextjs-plugin/index.cjs +1 -1
  38. package/dist/nextjs-plugin/index.js +1 -1
  39. package/dist/nextjs-plugin/loader.cjs +21 -25
  40. package/dist/nextjs-plugin/loader.js +1 -5
  41. package/dist/triggers/index.cjs +40 -1434
  42. package/dist/triggers/index.js +6 -1421
  43. package/package.json +2 -1
package/dist/index.js CHANGED
@@ -1,1586 +1,11 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropNames = Object.getOwnPropertyNames;
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
- var __esm = (fn, res) => function __init() {
10
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
- };
12
- var __export = (target, all) => {
13
- for (var name in all)
14
- __defProp(target, name, { get: all[name], enumerable: true });
15
- };
16
-
17
- // src/configuration.ts
18
- function configuration() {
19
- const g = globalThis;
20
- if (!g[GLOBAL_CONFIG_KEY]) {
21
- g[GLOBAL_CONFIG_KEY] = new Configuration();
22
- }
23
- return g[GLOBAL_CONFIG_KEY];
24
- }
25
- var DEFAULT_EXCLUDED_PATHS, DEFAULT_EXCLUDED_EXTENSIONS, DEFAULT_EXCLUDED_TABLES, DEFAULT_EXCLUDED_JOB_CLASSES, DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS, Configuration, GLOBAL_CONFIG_KEY;
26
- var init_configuration = __esm({
27
- "src/configuration.ts"() {
28
- DEFAULT_EXCLUDED_PATHS = Object.freeze([
29
- // Next.js / Vercel infrastructure noise
30
- "/_next/*",
31
- "/_vercel/*",
32
- "/__nextjs_*",
33
- // NextAuth.js / Auth.js — skip session-refresh polls and CSRF/provider
34
- // metadata GETs (high-frequency, no business meaning), but CAPTURE
35
- // POSTs (callbacks, signin, signout, register). The POSTs are the
36
- // actual auth events users care about; the GETs are pure plumbing.
37
- Object.freeze({ path: "/api/auth/*", methods: ["GET", "HEAD"] }),
38
- // Generic infrastructure
39
- "/health*",
40
- "/api/health",
41
- "/up",
42
- "/alive",
43
- "/ready",
44
- "/metrics",
45
- "/favicon.ico",
46
- "/.well-known*",
47
- "/robots.txt",
48
- "/sitemap.xml",
49
- "/*.hot-update.*",
50
- // Auth routes (common patterns across Clerk, NextAuth, custom auth)
51
- "*/login*",
52
- "*/logout*",
53
- "*/sign-in*",
54
- "*/sign-out*",
55
- "*/signin*",
56
- "*/signout*",
57
- "/session*"
58
- ]);
59
- DEFAULT_EXCLUDED_EXTENSIONS = Object.freeze([
60
- ".js",
61
- ".css",
62
- ".map",
63
- ".png",
64
- ".jpg",
65
- ".jpeg",
66
- ".gif",
67
- ".svg",
68
- ".ico",
69
- ".webp",
70
- ".woff",
71
- ".woff2",
72
- ".ttf",
73
- ".eot",
74
- ".otf"
75
- ]);
76
- DEFAULT_EXCLUDED_TABLES = Object.freeze([
77
- // Prisma migration ledger
78
- "_prisma_migrations",
79
- // Auth.js / NextAuth Prisma adapter — session/verification-token churn
80
- // is auth machinery, not business activity. Account/User stay captured.
81
- "Session",
82
- "VerificationToken",
83
- // Common cross-stack convention names for the same things
84
- "sessions",
85
- "session",
86
- "verification_tokens"
87
- ]);
88
- DEFAULT_EXCLUDED_JOB_CLASSES = Object.freeze([]);
89
- DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS = Object.freeze(["IntrospectionQuery", "__*"]);
90
- Configuration = class {
91
- serverUrl = null;
92
- projectToken = null;
93
- captureHttp = true;
94
- captureDb = true;
95
- captureJobs = true;
96
- bufferSize = 1e4;
97
- /** Default 3000 ms — equivalent to Ruby's 3 seconds. */
98
- sendInterval = 3e3;
99
- retryAttempts = 3;
100
- logLevel = "warn";
101
- patchGlobalFetch = true;
102
- actorFromSupabase = true;
103
- allowInsecureTransport = false;
104
- excludedPaths = [];
105
- excludedTables = [];
106
- excludedJobClasses = [];
107
- excludedGraphqlOperations = [];
108
- excludedGraphqlVariableKeys = [];
109
- actorFromRequest = null;
110
- displayNameFor = {};
111
- isServerActionError = null;
112
- databaseReader = null;
113
- databaseUrl = null;
114
- /**
115
- * Tables that have the `ezlogs_audit` trigger attached. Detected once
116
- * at agent startup by reading `information_schema.triggers`. The
117
- * supabase / drizzle / prisma adapters use this to decide whether
118
- * their per-mutation emit is redundant: if the table is trigger-
119
- * tracked the audit-log reader will surface the same write with full
120
- * old/new state, so the adapter's emit is suppressed. Tables NOT in
121
- * this set fall through to the adapter so they're still captured.
122
- *
123
- * `null` means "detection hasn't run yet or failed" — in that state
124
- * `databaseReader`-wired apps suppress every adapter emit (the
125
- * original Phase 5 behavior). After detection completes the agent
126
- * gives the more accurate per-table answer.
127
- */
128
- triggerTrackedTables = null;
129
- apply(options) {
130
- this.serverUrl = options.serverUrl;
131
- this.projectToken = options.projectToken;
132
- if (options.captureHttp !== void 0) this.captureHttp = options.captureHttp;
133
- if (options.captureDb !== void 0) this.captureDb = options.captureDb;
134
- if (options.captureJobs !== void 0) this.captureJobs = options.captureJobs;
135
- if (options.bufferSize !== void 0) this.bufferSize = options.bufferSize;
136
- if (options.sendInterval !== void 0) this.sendInterval = options.sendInterval;
137
- if (options.retryAttempts !== void 0) this.retryAttempts = options.retryAttempts;
138
- if (options.excludedPaths) this.excludedPaths = [...options.excludedPaths];
139
- if (options.excludedTables) this.excludedTables = [...options.excludedTables];
140
- if (options.excludedJobClasses) {
141
- this.excludedJobClasses = [...options.excludedJobClasses];
142
- }
143
- if (options.excludedGraphqlOperations) {
144
- this.excludedGraphqlOperations = [...options.excludedGraphqlOperations];
145
- }
146
- if (options.excludedGraphqlVariableKeys) {
147
- this.excludedGraphqlVariableKeys = [...options.excludedGraphqlVariableKeys];
148
- }
149
- if (options.actorFromRequest) this.actorFromRequest = options.actorFromRequest;
150
- if (options.displayNameFor) this.displayNameFor = { ...options.displayNameFor };
151
- if (options.isServerActionError) this.isServerActionError = options.isServerActionError;
152
- if (options.patchGlobalFetch !== void 0) {
153
- this.patchGlobalFetch = options.patchGlobalFetch;
154
- }
155
- if (options.allowInsecureTransport !== void 0) {
156
- this.allowInsecureTransport = options.allowInsecureTransport;
157
- }
158
- if (options.actorFromSupabase !== void 0) {
159
- this.actorFromSupabase = options.actorFromSupabase;
160
- }
161
- if (options.databaseReader !== void 0) {
162
- this.databaseReader = options.databaseReader;
163
- }
164
- if (options.databaseUrl !== void 0) {
165
- this.databaseUrl = options.databaseUrl;
166
- }
167
- if (options.logLevel) this.logLevel = options.logLevel;
168
- }
169
- allExcludedPaths() {
170
- return [...DEFAULT_EXCLUDED_PATHS, ...this.excludedPaths];
171
- }
172
- allExcludedTables() {
173
- return [...DEFAULT_EXCLUDED_TABLES, ...this.excludedTables];
174
- }
175
- allExcludedJobClasses() {
176
- return [...DEFAULT_EXCLUDED_JOB_CLASSES, ...this.excludedJobClasses];
177
- }
178
- allExcludedGraphqlOperations() {
179
- return [...DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS, ...this.excludedGraphqlOperations];
180
- }
181
- };
182
- GLOBAL_CONFIG_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:configuration");
183
- }
184
- });
185
-
186
- // src/logger.ts
187
- function readLevel() {
188
- const g = globalThis;
189
- return g[LEVEL_KEY] ?? "warn";
190
- }
191
- function setLogLevel(level) {
192
- globalThis[LEVEL_KEY] = level;
193
- }
194
- function shouldLog(level) {
195
- return LEVEL_RANK[level] >= LEVEL_RANK[readLevel()];
196
- }
197
- function safeWrite(level, message) {
198
- try {
199
- if (!shouldLog(level)) return;
200
- const line = `[ezlogs] ${message}`;
201
- if (level === "error" || level === "warn") {
202
- console.error(line);
203
- } else {
204
- console.log(line);
205
- }
206
- } catch {
207
- }
208
- }
209
- var LEVEL_RANK, LEVEL_KEY, logger;
210
- var init_logger = __esm({
211
- "src/logger.ts"() {
212
- LEVEL_RANK = {
213
- debug: 10,
214
- info: 20,
215
- warn: 30,
216
- error: 40,
217
- silent: 100
218
- };
219
- LEVEL_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:log-level");
220
- logger = {
221
- debug: (message) => safeWrite("debug", message),
222
- info: (message) => safeWrite("info", message),
223
- warn: (message) => safeWrite("warn", message),
224
- error: (message) => safeWrite("error", message)
225
- };
226
- }
227
- });
228
-
229
- // src/pipeline/buffer.ts
230
- var buffer_exports = {};
231
- __export(buffer_exports, {
232
- bufferSize: () => bufferSize,
233
- clearBuffer: () => clearBuffer,
234
- drainEvents: () => drainEvents,
235
- pushEvent: () => pushEvent
236
- });
237
- function getQueue() {
238
- const g = globalThis;
239
- if (!g[GLOBAL_QUEUE_KEY]) g[GLOBAL_QUEUE_KEY] = [];
240
- return g[GLOBAL_QUEUE_KEY];
241
- }
242
- function pushEvent(event) {
243
- try {
244
- const queue = getQueue();
245
- const max = maxSize();
246
- if (queue.length >= max) {
247
- queue.shift();
248
- logger.warn(`Buffer full (${max}), dropped oldest event`);
249
- }
250
- queue.push(event);
251
- } catch (error) {
252
- logger.error(`pushEvent failed: ${describe(error)}`);
253
- }
254
- }
255
- function drainEvents() {
256
- try {
257
- const queue = getQueue();
258
- if (queue.length === 0) return [];
259
- return queue.splice(0, queue.length);
260
- } catch (error) {
261
- logger.error(`drainEvents failed: ${describe(error)}`);
262
- return [];
263
- }
264
- }
265
- function bufferSize() {
266
- return getQueue().length;
267
- }
268
- function clearBuffer() {
269
- const queue = getQueue();
270
- queue.length = 0;
271
- }
272
- function maxSize() {
273
- try {
274
- return configuration().bufferSize;
275
- } catch {
276
- return 1e4;
277
- }
278
- }
279
- function describe(error) {
280
- if (error instanceof Error) return `${error.name}: ${error.message}`;
281
- return String(error);
282
- }
283
- var GLOBAL_QUEUE_KEY;
284
- var init_buffer = __esm({
285
- "src/pipeline/buffer.ts"() {
286
- init_configuration();
287
- init_logger();
288
- GLOBAL_QUEUE_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:buffer-queue");
289
- }
290
- });
291
-
292
- // src/edge-fallback.ts
293
- function loadAsyncLocalStorage() {
294
- const fromGlobal = globalThis.AsyncLocalStorage;
295
- if (typeof fromGlobal === "function") return fromGlobal;
296
- try {
297
- const req = typeof __require !== "undefined" ? __require : (
298
- // In ESM, `createRequire` is the official escape hatch.
299
- // We pull it via globalThis to avoid a static `import`
300
- // that would itself be browser-bundled.
301
- void 0
302
- );
303
- if (typeof req === "function") {
304
- const moduleName = ["async", "hooks"].join("_");
305
- const mod = req("node:" + moduleName);
306
- if (typeof mod.AsyncLocalStorage === "function") return mod.AsyncLocalStorage;
307
- }
308
- } catch {
309
- }
310
- return null;
311
- }
312
- function createScopedStorage(key = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:default-scoped-storage")) {
313
- const globalStore = globalThis;
314
- let entry = globalStore[key];
315
- if (!entry) {
316
- const als2 = (() => {
317
- if (!ALS_CTOR) return null;
318
- try {
319
- return new ALS_CTOR();
320
- } catch {
321
- return null;
322
- }
323
- })();
324
- entry = { als: als2, edgeFallback: null };
325
- globalStore[key] = entry;
326
- }
327
- const als = entry.als;
328
- const stateRef = entry;
329
- return {
330
- read() {
331
- if (als) return als.getStore()?.value ?? null;
332
- return stateRef.edgeFallback?.value ?? null;
333
- },
334
- run(value, callback) {
335
- if (als) return als.run({ value }, callback);
336
- const previous = stateRef.edgeFallback;
337
- stateRef.edgeFallback = { value };
338
- try {
339
- return callback();
340
- } finally {
341
- stateRef.edgeFallback = previous;
342
- }
343
- },
344
- update(value) {
345
- if (als) {
346
- const store = als.getStore();
347
- if (store) store.value = value;
348
- return;
349
- }
350
- stateRef.edgeFallback = { value };
351
- },
352
- _resetForTests() {
353
- stateRef.edgeFallback = null;
354
- },
355
- _isAsyncLocalStorage() {
356
- return als !== null;
357
- }
358
- };
359
- }
360
- var ALS_CTOR;
361
- var init_edge_fallback = __esm({
362
- "src/edge-fallback.ts"() {
363
- ALS_CTOR = loadAsyncLocalStorage();
364
- }
365
- });
366
-
367
- // src/correlation.ts
368
- function generate() {
369
- const ts = Date.now();
370
- const hex = randomHexBytes(4);
371
- return `ezl_${ts}_${hex}`;
372
- }
373
- function randomHexBytes(byteCount) {
374
- const buf = new Uint8Array(byteCount);
375
- globalThis.crypto.getRandomValues(buf);
376
- let out = "";
377
- for (let i = 0; i < buf.length; i++) {
378
- out += buf[i].toString(16).padStart(2, "0");
379
- }
380
- return out;
381
- }
382
- function resolveCorrelation(headers) {
383
- if (!headers) return generate();
384
- const ezlogs2 = safeRead(headers, CORRELATION_HEADER);
385
- if (ezlogs2 && isTrustedInboundId(ezlogs2)) return ezlogs2;
386
- for (const name of PLATFORM_REQUEST_ID_HEADERS) {
387
- const platformId = safeRead(headers, name);
388
- if (platformId) return wrapPlatformId(platformId);
389
- }
390
- return generate();
391
- }
392
- function isTrustedInboundId(id) {
393
- const match = INBOUND_ID.exec(id);
394
- if (!match) return false;
395
- const age = Date.now() - Number(match[1]);
396
- return age <= INBOUND_MAX_AGE_MS && age >= -INBOUND_MAX_SKEW_MS;
397
- }
398
- function safeRead(headers, name) {
399
- try {
400
- const value = headers.get(name);
401
- return typeof value === "string" && value.length > 0 ? value : null;
402
- } catch {
403
- return null;
404
- }
405
- }
406
- function wrapPlatformId(platformId) {
407
- const ts = Date.now();
408
- const hex = fnv1aHex(platformId);
409
- return `ezl_${ts}_${hex}`;
410
- }
411
- function fnv1aHex(input) {
412
- let hash = 2166136261;
413
- for (let i = 0; i < input.length; i++) {
414
- hash ^= input.charCodeAt(i);
415
- hash = Math.imul(hash, 16777619);
416
- }
417
- return (hash >>> 0).toString(16).padStart(8, "0");
418
- }
419
- function current() {
420
- return storage.read();
421
- }
422
- function runWithCorrelation(correlationId, callback) {
423
- return storage.run(correlationId, callback);
424
- }
425
- var CORRELATION_HEADER, PLATFORM_REQUEST_ID_HEADERS, storage, INBOUND_ID, INBOUND_MAX_AGE_MS, INBOUND_MAX_SKEW_MS;
426
- var init_correlation = __esm({
427
- "src/correlation.ts"() {
428
- init_edge_fallback();
429
- CORRELATION_HEADER = "x-ezlogs-correlation-id";
430
- PLATFORM_REQUEST_ID_HEADERS = [
431
- "x-vercel-id",
432
- "cf-ray",
433
- "x-request-id"
434
- ];
435
- storage = createScopedStorage(
436
- /* @__PURE__ */ Symbol.for("ezlogs-nextjs:correlation-storage")
437
- );
438
- INBOUND_ID = /^ezl_(\d{13})_[0-9a-f]{8}$/;
439
- INBOUND_MAX_AGE_MS = 60 * 6e4;
440
- INBOUND_MAX_SKEW_MS = 5 * 6e4;
441
- }
442
- });
443
-
444
- // src/actor.ts
445
- function getCurrentActor() {
446
- return storage2.read();
447
- }
448
- function setActor(input) {
449
- const sanitized = validateActor(input);
450
- if (input != null && sanitized === null) {
451
- logger.debug(`Actor: invalid actor structure ignored: ${describe2(input)}`);
452
- }
453
- storage2.update(sanitized);
454
- return sanitized;
455
- }
456
- function runWithActorScope(callback) {
457
- return storage2.run(null, callback);
458
- }
459
- function validateActor(input) {
460
- if (input === null || input === void 0) return null;
461
- if (typeof input !== "object") return null;
462
- if (Array.isArray(input)) return null;
463
- const obj = input;
464
- const rawId = obj.id;
465
- if (rawId === null || rawId === void 0) return null;
466
- const id = String(rawId);
467
- if (id === "") return null;
468
- const result = { id };
469
- if (obj.label !== void 0 && obj.label !== null) {
470
- result.label = String(obj.label);
471
- }
472
- if (obj.kind !== void 0 && obj.kind !== null) {
473
- const kind = String(obj.kind);
474
- if (VALID_KINDS.has(kind)) {
475
- result.kind = kind;
476
- }
477
- }
478
- const principal = sanitizePrincipal(obj.principal);
479
- if (principal) result.principal = principal;
480
- return result;
481
- }
482
- function sanitizePrincipal(input) {
483
- if (input === null || input === void 0) return null;
484
- if (typeof input !== "object") return null;
485
- if (Array.isArray(input)) return null;
486
- const obj = input;
487
- const rawId = obj.id;
488
- if (rawId === null || rawId === void 0) return null;
489
- const id = String(rawId);
490
- if (id === "") return null;
491
- const result = { id };
492
- if (obj.label !== void 0 && obj.label !== null) {
493
- result.label = String(obj.label);
494
- }
495
- return result;
496
- }
497
- function describe2(value) {
498
- try {
499
- return JSON.stringify(value);
500
- } catch {
501
- return Object.prototype.toString.call(value);
502
- }
503
- }
504
- var storage2, VALID_KINDS;
505
- var init_actor = __esm({
506
- "src/actor.ts"() {
507
- init_logger();
508
- init_edge_fallback();
509
- storage2 = createScopedStorage(
510
- /* @__PURE__ */ Symbol.for("ezlogs-nextjs:actor-storage")
511
- );
512
- VALID_KINDS = /* @__PURE__ */ new Set(["human", "agent", "system", "hybrid"]);
513
- }
514
- });
515
-
516
- // src/event-builder.ts
517
- function build(input) {
518
- const source_type = validateSourceType(input.source_type);
519
- const source_data_raw = validateSourceData(input.source_data);
520
- const outcome = validateOutcome(input.outcome);
521
- const timestamp = validateTimestamp(input.timestamp ?? null);
522
- const resource_ids = validateResourceIds(input.resource_ids ?? []);
523
- const context_raw = validateContext(input.context ?? null);
524
- const duration_ms = validateDurationMs(input.duration_ms ?? null);
525
- const error_message = input.error_message ?? null;
526
- validateOutcomeErrorConsistency(outcome, error_message);
527
- const source_data = sanitizeRecord(source_data_raw);
528
- const context = context_raw === null ? null : sanitizeRecord(context_raw);
529
- const correlation_id = input.correlation_id ?? null;
530
- const event = {
531
- timestamp,
532
- source_type,
533
- source_data,
534
- outcome,
535
- correlation_id,
536
- resource_ids,
537
- context,
538
- duration_ms,
539
- error_message
540
- };
541
- return event;
542
- }
543
- function validateSourceType(value) {
544
- if (value === null || value === void 0) {
545
- throw new ArgError("source_type is required");
546
- }
547
- const normalized = String(value);
548
- if (!VALID_SOURCE_TYPES.includes(normalized)) {
549
- throw new ArgError(
550
- `source_type must be one of ${VALID_SOURCE_TYPES.join(", ")}, got: ${normalized}`
551
- );
552
- }
553
- return normalized;
554
- }
555
- function validateSourceData(value) {
556
- if (value === null || value === void 0) {
557
- throw new ArgError("source_data is required");
558
- }
559
- if (!isPlainObject(value)) {
560
- throw new ArgError(
561
- `source_data must be an object, got: ${describe3(value)}`
562
- );
563
- }
564
- return value;
565
- }
566
- function validateOutcome(value) {
567
- if (value === null || value === void 0) {
568
- throw new ArgError("outcome is required");
569
- }
570
- const normalized = String(value);
571
- if (!VALID_OUTCOMES.includes(normalized)) {
572
- throw new ArgError(
573
- `outcome must be one of ${VALID_OUTCOMES.join(", ")}, got: ${normalized}`
574
- );
575
- }
576
- return normalized;
577
- }
578
- function validateTimestamp(value) {
579
- if (value === null) {
580
- return (/* @__PURE__ */ new Date()).toISOString();
581
- }
582
- if (typeof value === "string") {
583
- const parsed = new Date(value);
584
- if (Number.isNaN(parsed.getTime())) {
585
- throw new ArgError(
586
- `timestamp must be valid ISO 8601 format, got: ${value}`
587
- );
588
- }
589
- return value;
590
- }
591
- if (value instanceof Date) {
592
- if (Number.isNaN(value.getTime())) {
593
- throw new ArgError("timestamp must be a valid Date");
594
- }
595
- return value.toISOString();
596
- }
597
- throw new ArgError(
598
- `timestamp must be a string or Date, got: ${describe3(value)}`
599
- );
600
- }
601
- function validateResourceIds(value) {
602
- if (!Array.isArray(value)) {
603
- throw new ArgError(`resource_ids must be an array, got: ${describe3(value)}`);
604
- }
605
- value.forEach((entry, index) => {
606
- if (!isPlainObject(entry)) {
607
- throw new ArgError(
608
- `resource_ids[${index}] must be an object, got: ${describe3(entry)}`
609
- );
610
- }
611
- const e = entry;
612
- if (!("resource_type" in e) || !("resource_id" in e)) {
613
- throw new ArgError(
614
- `resource_ids[${index}] must have resource_type and resource_id keys, got: ${Object.keys(e).join(", ")}`
615
- );
616
- }
617
- if (typeof e.resource_type !== "string") {
618
- throw new ArgError(
619
- `resource_ids[${index}].resource_type must be a string, got: ${describe3(e.resource_type)}`
620
- );
621
- }
622
- if (typeof e.resource_id !== "string") {
623
- throw new ArgError(
624
- `resource_ids[${index}].resource_id must be a string, got: ${describe3(e.resource_id)}`
625
- );
626
- }
627
- });
628
- return value;
629
- }
630
- function validateContext(value) {
631
- if (value === null) return null;
632
- if (!isPlainObject(value)) {
633
- throw new ArgError(
634
- `context must be an object or null, got: ${describe3(value)}`
635
- );
636
- }
637
- return value;
638
- }
639
- function validateDurationMs(value) {
640
- if (value === null || value === void 0) return null;
641
- if (typeof value !== "number" || !Number.isFinite(value)) {
642
- throw new ArgError(`duration_ms must be a number, got: ${describe3(value)}`);
643
- }
644
- if (!Number.isInteger(value)) {
645
- throw new ArgError(`duration_ms must be an integer, got: ${value}`);
646
- }
647
- if (value < 0) {
648
- throw new ArgError(`duration_ms must be >= 0, got: ${value}`);
649
- }
650
- return value;
651
- }
652
- function validateOutcomeErrorConsistency(outcome, error_message) {
653
- if (outcome === "failure") {
654
- if (error_message === null || error_message === "") {
655
- throw new ArgError("error_message is required when outcome is 'failure'");
656
- }
657
- } else if (outcome === "success") {
658
- if (error_message !== null) {
659
- throw new ArgError("error_message must be null when outcome is 'success'");
660
- }
661
- }
662
- }
663
- function sanitizeRecord(input) {
664
- const result = {};
665
- for (const key of Object.keys(input)) {
666
- const value = input[key];
667
- if (isSensitiveKey(key)) {
668
- result[key] = "[FILTERED]";
669
- } else if (isPlainObject(value)) {
670
- result[key] = sanitizeRecord(value);
671
- } else if (Array.isArray(value)) {
672
- result[key] = value.map(
673
- (item) => isPlainObject(item) ? sanitizeRecord(item) : item
674
- );
675
- } else {
676
- result[key] = value;
677
- }
678
- }
679
- return result;
680
- }
681
- function isSensitiveKey(key) {
682
- const lower = key.toLowerCase();
683
- return SENSITIVE_KEYS.some((p) => lower.includes(p));
684
- }
685
- function isPlainObject(value) {
686
- if (value === null || typeof value !== "object") return false;
687
- const proto = Object.getPrototypeOf(value);
688
- return proto === Object.prototype || proto === null;
689
- }
690
- function describe3(value) {
691
- if (value === null) return "null";
692
- if (Array.isArray(value)) return "Array";
693
- return typeof value;
694
- }
695
- var SENSITIVE_KEYS, VALID_SOURCE_TYPES, VALID_OUTCOMES, ArgError;
696
- var init_event_builder = __esm({
697
- "src/event-builder.ts"() {
698
- SENSITIVE_KEYS = Object.freeze([
699
- "password",
700
- "token",
701
- "secret",
702
- "api_key",
703
- "credit_card"
704
- ]);
705
- VALID_SOURCE_TYPES = [
706
- "http_request",
707
- "background_job",
708
- "database_callback"
709
- ];
710
- VALID_OUTCOMES = ["success", "failure"];
711
- ArgError = class extends Error {
712
- constructor(message) {
713
- super(message);
714
- this.name = "ArgError";
715
- }
716
- };
717
- }
718
- });
719
-
720
- // src/http/sanitize.ts
721
- function snakeLower(key) {
722
- return key.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
723
- }
724
- function matchesSensitiveKey(key, substringPatterns) {
725
- const lower = key.toLowerCase();
726
- const snake = snakeLower(key);
727
- if (substringPatterns.some((p) => lower.includes(p) || snake.includes(p))) {
728
- return true;
729
- }
730
- const words = snake.split(/[^a-z0-9]+/);
731
- return SENSITIVE_WORD_PATTERNS.some((w) => words.includes(w));
732
- }
733
- function sanitizeRequestParams(params, userPatterns = []) {
734
- if (params === null || params === void 0) return null;
735
- if (!isPlainObject2(params)) return null;
736
- const obj = params;
737
- const cleaned = {};
738
- for (const key of Object.keys(obj)) {
739
- if (FRAMEWORK_INTERNAL_KEYS.has(key)) continue;
740
- cleaned[key] = obj[key];
741
- }
742
- if (Object.keys(cleaned).length === 0) return null;
743
- const out = {};
744
- for (const key of Object.keys(cleaned)) {
745
- out[key] = sanitizeValue(key, cleaned[key], 0, userPatterns);
746
- }
747
- return out;
748
- }
749
- function passesLuhn(digits) {
750
- let sum = 0;
751
- for (let i = 0; i < digits.length; i += 1) {
752
- let d = Number(digits[digits.length - 1 - i]);
753
- if (i % 2 === 1) {
754
- d *= 2;
755
- if (d > 9) d -= 9;
756
- }
757
- sum += d;
758
- }
759
- return sum % 10 === 0;
760
- }
761
- function scrubSecretsInText(text, options = {}) {
762
- let out = text;
763
- for (const pattern of SECRET_TEXT_PATTERNS) out = out.replace(pattern, "[FILTERED]");
764
- out = out.replace(/\b(Bearer|Basic)\s+[\w.~+/=-]+/gi, "$1 [FILTERED]").replace(/\b\d(?:[ -]?\d){12,18}\b/g, (match) => {
765
- const digits = match.replace(/[ -]/g, "");
766
- return (digits.length === 15 || digits.length === 16) && passesLuhn(digits) ? "[FILTERED]" : match;
767
- });
768
- return options.emails ? out.replace(EMAIL, "[FILTERED]") : out;
769
- }
770
- function sanitizeValue(key, value, depth, userPatterns) {
771
- if (isSensitiveKey2(key, userPatterns)) return "[FILTERED]";
772
- if (isPlainObject2(value)) {
773
- return sanitizeNestedObject(value, depth, userPatterns);
774
- }
775
- if (Array.isArray(value)) {
776
- return sanitizeArrayValue(value, depth, userPatterns);
777
- }
778
- return value;
779
- }
780
- function sanitizeNestedObject(hash, depth, userPatterns) {
781
- if (depth >= MAX_NESTING_DEPTH) return "[Object]";
782
- if (Object.keys(hash).length === 0) return {};
783
- const out = {};
784
- for (const k of Object.keys(hash)) {
785
- out[k] = sanitizeValue(k, hash[k], depth + 1, userPatterns);
786
- }
787
- return out;
788
- }
789
- function sanitizeArrayValue(array, depth, userPatterns) {
790
- if (array.length === 0) return [];
791
- const allPrimitive = array.every(isPrimitive);
792
- if (allPrimitive) {
793
- if (array.length <= MAX_ARRAY_DISPLAY_SIZE) return array;
794
- const preview = array.slice(0, MAX_ARRAY_DISPLAY_SIZE);
795
- return `${JSON.stringify(preview)}... (${array.length} total)`;
796
- }
797
- if (array.length <= MAX_ARRAY_DISPLAY_SIZE) {
798
- return array.map((item) => sanitizeArrayItem(item, depth, userPatterns));
799
- }
800
- return {
801
- _truncated: true,
802
- _count: array.length,
803
- _preview: array.slice(0, MAX_ARRAY_DISPLAY_SIZE).map((item) => sanitizeArrayItem(item, depth, userPatterns))
804
- };
805
- }
806
- function sanitizeArrayItem(item, depth, userPatterns) {
807
- if (isPrimitive(item)) return item;
808
- if (isPlainObject2(item)) {
809
- return sanitizeNestedObject(item, depth + 1, userPatterns);
810
- }
811
- if (Array.isArray(item)) return sanitizeArrayValue(item, depth + 1, userPatterns);
812
- return "[Object]";
813
- }
814
- function isSensitiveKey2(key, userPatterns) {
815
- if (matchesSensitiveKey(key, SENSITIVE_VARIABLE_PATTERNS)) return true;
816
- const lower = key.toLowerCase();
817
- return userPatterns.some((p) => lower.includes(p.toLowerCase()));
818
- }
819
- function isPrimitive(value) {
820
- return value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
821
- }
822
- function isPlainObject2(value) {
823
- if (value === null || typeof value !== "object") return false;
824
- const proto = Object.getPrototypeOf(value);
825
- return proto === Object.prototype || proto === null;
826
- }
827
- var SENSITIVE_VARIABLE_PATTERNS, SENSITIVE_WORD_PATTERNS, MAX_NESTING_DEPTH, MAX_ARRAY_DISPLAY_SIZE, FRAMEWORK_INTERNAL_KEYS, SECRET_TEXT_PATTERNS, EMAIL;
828
- var init_sanitize = __esm({
829
- "src/http/sanitize.ts"() {
830
- SENSITIVE_VARIABLE_PATTERNS = Object.freeze([
831
- "password",
832
- "passwd",
833
- "pwd",
834
- "token",
835
- "access_token",
836
- "refresh_token",
837
- "api_token",
838
- "auth_token",
839
- "secret",
840
- "api_secret",
841
- "client_secret",
842
- "api_key",
843
- "apikey",
844
- "private_key",
845
- "privatekey",
846
- "public_key",
847
- "signing_key",
848
- "secret_key",
849
- "secretkey",
850
- "credential",
851
- "auth",
852
- "authorization",
853
- "encrypted",
854
- "encrypted_data",
855
- "ssn",
856
- "social_security",
857
- "credit_card",
858
- "card_number",
859
- "cvv",
860
- "cvc",
861
- // Crypto-material patterns — aligned with DB_SENSITIVE_PATTERNS
862
- // (PR #45). Request bodies can carry the same key material as DB
863
- // columns (a webhook POST containing a `signature` field, an HMAC
864
- // header echoed into a JSON body, a `pem`-encoded cert blob, etc).
865
- "pem",
866
- "cipher",
867
- "nonce",
868
- "salt",
869
- "digest",
870
- "signature",
871
- "hmac",
872
- // 0.2.0 additions (not yet in the Rails gem's list).
873
- "passcode",
874
- "cardnumber"
875
- ]);
876
- SENSITIVE_WORD_PATTERNS = Object.freeze([
877
- "pin",
878
- "otp",
879
- "totp",
880
- "iban",
881
- "mfa",
882
- "passphrase"
883
- ]);
884
- MAX_NESTING_DEPTH = 3;
885
- MAX_ARRAY_DISPLAY_SIZE = 5;
886
- FRAMEWORK_INTERNAL_KEYS = /* @__PURE__ */ new Set([
887
- // Rails leftovers — kept for parity since users may funnel through a
888
- // proxy that adds them, e.g. via a NextAuth credentials provider that
889
- // forwards CSRF tokens.
890
- "controller",
891
- "action",
892
- "format",
893
- "authenticity_token",
894
- "_method",
895
- // Next.js / common JS conventions
896
- "csrfToken",
897
- "_csrf",
898
- "_next"
899
- ]);
900
- SECRET_TEXT_PATTERNS = [
901
- /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,
902
- /\beyJ[\w-]+\.[\w-]+\.[\w-]+/g,
903
- /\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]+/g,
904
- /\bsk-[A-Za-z0-9_-]{16,}/g,
905
- /\bgh[pousr]_[A-Za-z0-9]{20,}/g,
906
- /\bxox[abposr]-[A-Za-z0-9-]+/g,
907
- /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g
908
- ];
909
- EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;
910
- }
911
- });
912
-
913
- // src/db/shared.ts
914
- function emitDbEvent(input) {
915
- try {
916
- const config = configuration();
917
- if (!config.captureDb) return;
918
- if (config.allExcludedTables().includes(input.modelClass)) return;
919
- if (config.databaseReader && !input._fromTrigger) {
920
- const tracked = config.triggerTrackedTables;
921
- if (tracked === null || tracked.has(input.table ?? input.modelClass)) return;
922
- }
923
- if (input.operation === "update") {
924
- const meaningful = input.changes ? filterMeaningfulChanges(input.changes) : [];
925
- if (meaningful.length === 0) return;
926
- }
927
- const resourceIdStr = input.resourceId === null || input.resourceId === void 0 ? null : String(input.resourceId);
928
- const related = resourceIdStr === null ? input.relatedResourceIds ?? [] : [];
929
- const context = buildContext(
930
- related.length > 0 ? { ...input, displayName: null, modelInstance: null } : input
931
- );
932
- const event = build({
933
- source_type: "database_callback",
934
- source_data: {
935
- model_class: input.modelClass,
936
- operation: input.operation
937
- },
938
- outcome: "success",
939
- correlation_id: current(),
940
- resource_ids: resourceIdStr === null ? [...related] : [{ resource_type: input.modelClass, resource_id: resourceIdStr }],
941
- context,
942
- duration_ms: null,
943
- timestamp: input.timestamp ?? null
944
- });
945
- pushEvent(event);
946
- } catch (error) {
947
- logger.debug(`db emit failed: ${describeError5(error)}`);
948
- }
949
- }
950
- function buildContext(input) {
951
- const context = {};
952
- const actor = getCurrentActor();
953
- if (actor) context.actor = actor;
954
- if ((input.operation === "create" || input.operation === "destroy") && input.initialAttributes) {
955
- const filtered = filterMeaningfulAttributes(input.initialAttributes);
956
- if (filtered !== null) context.initial_attributes = filtered;
957
- }
958
- if (input.operation === "update" && input.changes) {
959
- const filtered = filterMeaningfulChanges(input.changes);
960
- if (filtered.length > 0) {
961
- context.changes = filtered.map((c) => {
962
- const out = {
963
- attribute: c.attribute,
964
- to: formatForJson(c.to)
965
- };
966
- if (c.from !== void 0) out.from = formatForJson(c.from);
967
- return out;
968
- });
969
- }
970
- }
971
- const displayName = input.displayName ?? (input.modelInstance ? resolveDisplayName(input.modelClass, input.modelInstance) : null);
972
- if (displayName !== null) context.display_name = displayName;
973
- return Object.keys(context).length === 0 ? null : context;
974
- }
975
- function filterMeaningfulAttributes(attrs) {
976
- const out = {};
977
- for (const key of Object.keys(attrs)) {
978
- if (!isMeaningfulAttribute(key)) continue;
979
- const value = attrs[key];
980
- if (value === null || value === void 0) continue;
981
- if (!isScalar(value)) continue;
982
- out[key] = formatForJson(value);
983
- }
984
- return Object.keys(out).length === 0 ? null : out;
985
- }
986
- function filterMeaningfulChanges(changes) {
987
- return flattenNestedChanges(changes).filter((c) => {
988
- if (!isMeaningfulAttribute(c.attribute)) return false;
989
- if (!isScalar(c.to)) return false;
990
- if (c.from === void 0) return true;
991
- if (!isScalar(c.from)) return false;
992
- return valuesActuallyChanged(c.from, c.to);
993
- });
994
- }
995
- function flattenNestedChanges(changes) {
996
- if (!changes.some((c) => isPlainRecord(c.to) || isPlainRecord(c.from))) return changes;
997
- const out = [];
998
- for (const c of changes) {
999
- if (!isPlainRecord(c.to) && !isPlainRecord(c.from)) {
1000
- out.push(c);
1001
- continue;
1002
- }
1003
- if (!isMeaningfulAttribute(c.attribute)) continue;
1004
- const leaves = [];
1005
- collectLeafChanges(c.attribute, c.from, c.to, 1, leaves);
1006
- const cap = c.from === void 0 ? MAX_UNKNOWN_FROM_LEAVES : MAX_NESTED_LEAVES;
1007
- out.push(...leaves.slice(0, cap).map(scrubLeaf));
1008
- }
1009
- return out;
1010
- }
1011
- function collectLeafChanges(path, from, to, depth, out) {
1012
- if (out.length > MAX_NESTED_LEAVES) return;
1013
- const fromObj = isPlainRecord(from);
1014
- const toObj = isPlainRecord(to);
1015
- if ((fromObj || toObj) && depth <= MAX_NESTED_DEPTH && (fromObj || from == null) && (toObj || to == null)) {
1016
- const f = fromObj ? from : {};
1017
- const t = toObj ? to : {};
1018
- for (const key of /* @__PURE__ */ new Set([...Object.keys(f), ...Object.keys(t)])) {
1019
- const before = from === void 0 ? void 0 : f[key] ?? null;
1020
- collectLeafChanges(`${path}.${key}`, before, t[key] ?? null, depth + 1, out);
1021
- }
1022
- return;
1023
- }
1024
- if (from !== void 0 && sameJson(from, to)) return;
1025
- out.push(from === void 0 ? { attribute: path, to } : { attribute: path, from, to });
1026
- }
1027
- function scrubLeaf(change) {
1028
- const scrub = (v) => typeof v === "string" ? scrubSecretsInText(v) : v;
1029
- const out = { attribute: change.attribute, to: scrub(change.to) };
1030
- if (change.from !== void 0) out.from = scrub(change.from);
1031
- return out;
1032
- }
1033
- function isPlainRecord(value) {
1034
- if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
1035
- const proto = Object.getPrototypeOf(value);
1036
- return proto === Object.prototype || proto === null;
1037
- }
1038
- function sameJson(a, b) {
1039
- if (a === b) return true;
1040
- try {
1041
- return JSON.stringify(a) === JSON.stringify(b);
1042
- } catch {
1043
- return false;
1044
- }
1045
- }
1046
- function isMeaningfulAttribute(name) {
1047
- if (IGNORED_ATTRIBUTES.includes(name)) return false;
1048
- if (isDbSensitive(name)) return false;
1049
- return true;
1050
- }
1051
- function isDbSensitive(name) {
1052
- return matchesSensitiveKey(name, DB_SENSITIVE_PATTERNS);
1053
- }
1054
- function isScalar(value) {
1055
- if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint" || value instanceof Date) {
1056
- return true;
1057
- }
1058
- if (isPrismaDecimal(value)) return true;
1059
- if (Buffer.isBuffer?.(value)) return false;
1060
- if (Array.isArray(value)) return value.every((v) => isScalar(v));
1061
- return false;
1062
- }
1063
- function valuesActuallyChanged(from, to) {
1064
- if (from === null && to === null) return false;
1065
- if (from instanceof Date && to instanceof Date) {
1066
- return from.getTime() !== to.getTime();
1067
- }
1068
- return from !== to;
1069
- }
1070
- function formatForJson(value) {
1071
- if (value === null || value === void 0) return value;
1072
- if (value instanceof Date) return value.toISOString();
1073
- if (typeof value === "bigint") return value.toString();
1074
- if (isPrismaDecimal(value)) return Number(value.toString());
1075
- if (Array.isArray(value)) return value.map(formatForJson);
1076
- return value;
1077
- }
1078
- function isPrismaDecimal(value) {
1079
- if (value === null || typeof value !== "object") return false;
1080
- const obj = value;
1081
- return typeof obj.toString === "function" && typeof obj.toFixed === "function" && "d" in obj && "e" in obj && "s" in obj;
1082
- }
1083
- function resolveDisplayName(modelClass, instance) {
1084
- try {
1085
- const config = configuration();
1086
- const resolver = config.displayNameFor[modelClass];
1087
- const resolved = applyResolver(resolver, instance);
1088
- if (resolved !== null) return resolved;
1089
- const columns = /* @__PURE__ */ new Map();
1090
- for (const key of Object.keys(instance)) {
1091
- if (isDbSensitive(key)) continue;
1092
- const norm = key.toLowerCase().replace(/_/g, "");
1093
- if (!columns.has(norm)) columns.set(norm, instance[key]);
1094
- }
1095
- const text = (norm) => {
1096
- const value = columns.get(norm);
1097
- if (typeof value !== "string" && typeof value !== "number" && typeof value !== "bigint") {
1098
- return null;
1099
- }
1100
- const str = String(value).trim();
1101
- return str.length > 0 ? str.slice(0, MAX_DISPLAY_NAME_LENGTH) : null;
1102
- };
1103
- for (const column of DISPLAY_NAME_COLUMNS) {
1104
- const value = text(column);
1105
- if (value !== null) return value;
1106
- }
1107
- return text(`${singularNorm(modelClass)}number`);
1108
- } catch {
1109
- }
1110
- return null;
1111
- }
1112
- function singularNorm(modelClass) {
1113
- const norm = modelClass.toLowerCase().replace(/_/g, "");
1114
- if (norm.endsWith("ies")) return norm.slice(0, -3) + "y";
1115
- if (/(ss|us|is)$/.test(norm)) return norm;
1116
- if (/(xes|ches|shes|sses)$/.test(norm)) return norm.slice(0, -2);
1117
- return norm.endsWith("s") ? norm.slice(0, -1) : norm;
1118
- }
1119
- function applyResolver(resolver, instance) {
1120
- if (typeof resolver === "string") {
1121
- const value = instance[resolver];
1122
- if (value !== null && value !== void 0 && String(value).length > 0) {
1123
- return String(value);
1124
- }
1125
- return null;
1126
- }
1127
- if (typeof resolver === "function") {
1128
- try {
1129
- const value = resolver(instance);
1130
- if (typeof value === "string" && value.length > 0) return value;
1131
- if (value !== null && value !== void 0 && String(value).length > 0) {
1132
- return String(value);
1133
- }
1134
- } catch {
1135
- }
1136
- }
1137
- return null;
1138
- }
1139
- function describeError5(error) {
1140
- if (error instanceof Error) return `${error.name}: ${error.message}`;
1141
- return String(error);
1142
- }
1143
- var IGNORED_ATTRIBUTES, DB_SENSITIVE_PATTERNS, MAX_NESTED_DEPTH, MAX_NESTED_LEAVES, MAX_UNKNOWN_FROM_LEAVES, DISPLAY_NAME_COLUMNS, MAX_DISPLAY_NAME_LENGTH;
1144
- var init_shared = __esm({
1145
- "src/db/shared.ts"() {
1146
- init_configuration();
1147
- init_logger();
1148
- init_event_builder();
1149
- init_buffer();
1150
- init_correlation();
1151
- init_actor();
1152
- init_sanitize();
1153
- IGNORED_ATTRIBUTES = Object.freeze([
1154
- "id",
1155
- "createdAt",
1156
- "created_at",
1157
- "updatedAt",
1158
- "updated_at",
1159
- // Auth.js / NextAuth standard columns
1160
- "emailVerified",
1161
- "expires"
1162
- ]);
1163
- DB_SENSITIVE_PATTERNS = Object.freeze([
1164
- "password",
1165
- "token",
1166
- "secret",
1167
- "api_key",
1168
- "credit_card",
1169
- "ssn",
1170
- "social_security",
1171
- "encrypted",
1172
- "private_key",
1173
- "public_key",
1174
- "signing_key",
1175
- "pem",
1176
- "cipher",
1177
- "nonce",
1178
- "salt",
1179
- "digest",
1180
- "signature",
1181
- "hmac",
1182
- // 0.2.0 additions. `credential` / `passwd` / `apikey` were already in
1183
- // the HTTP list; `passcode` / `card_number` / `cardnumber` / `cvv` /
1184
- // `cvc` are new. Whole-word `pin` / `otp` / `totp` / `iban` come from
1185
- // SENSITIVE_WORD_PATTERNS. The SQL trigger mirrors this list.
1186
- "credential",
1187
- "passwd",
1188
- "passcode",
1189
- "apikey",
1190
- "card_number",
1191
- "cardnumber",
1192
- "cvv",
1193
- "cvc"
1194
- ]);
1195
- MAX_NESTED_DEPTH = 3;
1196
- MAX_NESTED_LEAVES = 20;
1197
- MAX_UNKNOWN_FROM_LEAVES = 5;
1198
- DISPLAY_NAME_COLUMNS = ["name", "title", "number", "label"];
1199
- MAX_DISPLAY_NAME_LENGTH = 120;
1200
- }
1201
- });
1202
-
1203
- // src/db/supabase.ts
1204
- var supabase_exports = {};
1205
- __export(supabase_exports, {
1206
- tryExtractSupabaseActor: () => tryExtractSupabaseActor,
1207
- wrapSupabase: () => wrapSupabase
1208
- });
1209
- function triggerPathWillCapture(table) {
1210
- const config = configuration();
1211
- if (!config.databaseReader) return false;
1212
- const tracked = config.triggerTrackedTables;
1213
- if (tracked === null) return false;
1214
- return tracked.has(table);
1215
- }
1216
- function wrapSupabase(client) {
1217
- if (client === null || typeof client !== "object") return client;
1218
- const obj = client;
1219
- if (obj.__ezlogsWrapped) return client;
1220
- if (typeof obj.from !== "function") return client;
1221
- const originalFrom = obj.from.bind(obj);
1222
- const prereadRow = async (table, filters) => {
1223
- try {
1224
- const queryBuilder = originalFrom(table);
1225
- if (typeof queryBuilder.select !== "function") return null;
1226
- let chain = queryBuilder.select("*");
1227
- for (const f of filters) {
1228
- if (typeof chain.eq !== "function") return null;
1229
- chain = chain.eq(
1230
- f.column,
1231
- f.value
1232
- );
1233
- }
1234
- if (typeof chain.maybeSingle === "function") {
1235
- chain = chain.maybeSingle();
1236
- } else if (typeof chain.limit === "function") {
1237
- chain = chain.limit(
1238
- 1
1239
- );
1240
- }
1241
- const result = await chain;
1242
- if (!result || result.error) return null;
1243
- if (Array.isArray(result.data)) {
1244
- const first = result.data[0];
1245
- return isPlainObject4(first) ? first : null;
1246
- }
1247
- return isPlainObject4(result.data) ? result.data : null;
1248
- } catch {
1249
- return null;
1250
- }
1251
- };
1252
- obj.from = ((table) => {
1253
- const builder = originalFrom(table);
1254
- return wrapBuilder(builder, table, prereadRow);
1255
- });
1256
- Object.defineProperty(obj, "__ezlogsWrapped", {
1257
- value: true,
1258
- enumerable: false,
1259
- configurable: false
1260
- });
1261
- registerActorSource(obj);
1262
- return client;
1263
- }
1264
- function registerActorSource(client) {
1265
- try {
1266
- const g = globalThis;
1267
- g[GLOBAL_CLIENT_KEY] = client;
1268
- } catch {
1269
- }
1270
- }
1271
- async function tryExtractSupabaseActor() {
1272
- const g = globalThis;
1273
- const client = g[GLOBAL_CLIENT_KEY];
1274
- if (!client || typeof client.auth?.getUser !== "function") return null;
1275
- try {
1276
- const { data } = await client.auth.getUser();
1277
- const user = data?.user;
1278
- if (!user || typeof user.id !== "string" || !user.id) return null;
1279
- const label = user.user_metadata?.full_name ?? user.user_metadata?.name ?? user.email ?? void 0;
1280
- return label ? { id: user.id, label } : { id: user.id };
1281
- } catch {
1282
- return null;
1283
- }
1284
- }
1285
- function wrapBuilder(builder, table, preread) {
1286
- if (typeof builder.insert === "function") {
1287
- builder.insert = wrapMutation(
1288
- builder.insert.bind(builder),
1289
- { table, operation: "create" },
1290
- preread
1291
- );
1292
- }
1293
- if (typeof builder.upsert === "function") {
1294
- builder.upsert = wrapMutation(
1295
- builder.upsert.bind(builder),
1296
- { table, operation: "update" },
1297
- // supabase upsert is conceptually update-with-fallback
1298
- preread
1299
- );
1300
- }
1301
- if (typeof builder.update === "function") {
1302
- builder.update = wrapMutation(
1303
- builder.update.bind(builder),
1304
- { table, operation: "update" },
1305
- preread
1306
- );
1307
- }
1308
- if (typeof builder.delete === "function") {
1309
- builder.delete = wrapDeleteMutation(
1310
- builder.delete.bind(builder),
1311
- table,
1312
- preread
1313
- );
1314
- }
1315
- return builder;
1316
- }
1317
- function wrapMutation(original, ctx, preread) {
1318
- return (values, options) => {
1319
- const filterBuilder = original(values, options);
1320
- const filters = trackFilterChain(filterBuilder);
1321
- const beforeRowRef = { row: null };
1322
- return instrumentFilterBuilder(
1323
- filterBuilder,
1324
- (result) => emitFromMutation(ctx, values, result, filters, beforeRowRef.row),
1325
- async () => {
1326
- if (ctx.operation !== "update") return;
1327
- if (triggerPathWillCapture(ctx.table)) return;
1328
- const prereadFilters = prereadFiltersFromCaptured(filters);
1329
- if (prereadFilters !== null) {
1330
- beforeRowRef.row = await preread(ctx.table, prereadFilters);
1331
- }
1332
- }
1333
- );
1334
- };
1335
- }
1336
- function wrapDeleteMutation(original, table, preread) {
1337
- return (options) => {
1338
- const filterBuilder = original(options);
1339
- const filters = trackFilterChain(filterBuilder);
1340
- const beforeRowRef = { row: null };
1341
- return instrumentFilterBuilder(
1342
- filterBuilder,
1343
- (result) => emitFromDelete(table, result, filters, beforeRowRef.row),
1344
- async () => {
1345
- if (triggerPathWillCapture(table)) return;
1346
- const prereadFilters = prereadFiltersFromCaptured(filters);
1347
- if (prereadFilters !== null) {
1348
- beforeRowRef.row = await preread(table, prereadFilters);
1349
- }
1350
- }
1351
- );
1352
- };
1353
- }
1354
- function trackFilterChain(builder) {
1355
- const captured = { equals: {}, inLists: {} };
1356
- if (!builder || typeof builder !== "object") return captured;
1357
- const builderObj = builder;
1358
- const wrapEq = (orig) => {
1359
- if (typeof orig !== "function") return orig;
1360
- return function patchedEq(column, value) {
1361
- try {
1362
- if (typeof column === "string") captured.equals[column] = value;
1363
- } catch {
1364
- }
1365
- return orig.call(this, column, value);
1366
- };
1367
- };
1368
- const wrapIn = (orig) => {
1369
- if (typeof orig !== "function") return orig;
1370
- return function patchedIn(column, values) {
1371
- try {
1372
- if (typeof column === "string" && Array.isArray(values)) {
1373
- captured.inLists[column] = values;
1374
- }
1375
- } catch {
1376
- }
1377
- return orig.call(this, column, values);
1378
- };
1379
- };
1380
- const wrapMatch = (orig) => {
1381
- if (typeof orig !== "function") return orig;
1382
- return function patchedMatch(query) {
1383
- try {
1384
- if (isPlainObject4(query)) {
1385
- for (const [k, v] of Object.entries(query)) {
1386
- captured.equals[k] = v;
1387
- }
1388
- }
1389
- } catch {
1390
- }
1391
- return orig.call(this, query);
1392
- };
1393
- };
1394
- if ("eq" in builderObj) builderObj.eq = wrapEq(builderObj.eq);
1395
- if ("in" in builderObj) builderObj.in = wrapIn(builderObj.in);
1396
- if ("match" in builderObj) builderObj.match = wrapMatch(builderObj.match);
1397
- return captured;
1398
- }
1399
- function instrumentFilterBuilder(builder, onResolved, beforeFire) {
1400
- if (!builder || typeof builder !== "object") return builder;
1401
- const originalThen = builder.then?.bind(builder);
1402
- if (typeof originalThen !== "function") return builder;
1403
- const wrappedThen = function ezlogsThen(onfulfilled, onrejected) {
1404
- return new Promise((resolve, reject) => {
1405
- const proceed = () => {
1406
- originalThen(
1407
- (raw) => {
1408
- const result = raw;
1409
- try {
1410
- if (!result?.error) onResolved(result);
1411
- } catch (error) {
1412
- logger.debug(`supabase capture failed: ${describeError6(error)}`);
1413
- }
1414
- try {
1415
- const passthrough = onfulfilled ? onfulfilled(raw) : raw;
1416
- resolve(passthrough);
1417
- } catch (e) {
1418
- reject(e);
1419
- }
1420
- },
1421
- (reason) => {
1422
- try {
1423
- const passthrough = onrejected ? onrejected(reason) : Promise.reject(reason);
1424
- resolve(passthrough);
1425
- } catch (e) {
1426
- reject(e);
1427
- }
1428
- }
1429
- );
1430
- };
1431
- if (beforeFire) {
1432
- beforeFire().then(proceed, () => proceed());
1433
- } else {
1434
- proceed();
1435
- }
1436
- });
1437
- };
1438
- builder.then = wrappedThen;
1439
- return builder;
1440
- }
1441
- function emitFromMutation(ctx, values, result, filters, beforeRow) {
1442
- if (Array.isArray(values)) {
1443
- const resultRows = pickResultRows(result);
1444
- values.forEach((row, index) => {
1445
- if (!isPlainObject4(row)) return;
1446
- emitOneRow(ctx, row, resultRows[index] ?? null, filters, null);
1447
- });
1448
- return;
1449
- }
1450
- if (!isPlainObject4(values)) {
1451
- emitDbEvent({
1452
- modelClass: ctx.table,
1453
- operation: ctx.operation,
1454
- resourceId: idFromFilters(filters)
1455
- });
1456
- return;
1457
- }
1458
- const valueObj = values;
1459
- const resultRow = pickFirstResultRow(result);
1460
- emitOneRow(ctx, valueObj, resultRow, filters, beforeRow);
1461
- }
1462
- function emitOneRow(ctx, values, resultRow, filters, beforeRow) {
1463
- const resourceId = resultRow?.id ?? values.id ?? idFromFilters(filters) ?? null;
1464
- const merged = beforeRow ?? resultRow ?? values;
1465
- const displayName = resolveDisplayName(ctx.table, merged);
1466
- if (ctx.operation === "create") {
1467
- emitDbEvent({
1468
- modelClass: ctx.table,
1469
- operation: "create",
1470
- resourceId,
1471
- initialAttributes: values,
1472
- displayName,
1473
- modelInstance: merged
1474
- });
1475
- return;
1476
- }
1477
- if (ctx.operation === "update") {
1478
- const changes = buildUpdateChanges(values, beforeRow);
1479
- emitDbEvent({
1480
- modelClass: ctx.table,
1481
- operation: "update",
1482
- resourceId,
1483
- changes,
1484
- displayName,
1485
- modelInstance: merged
1486
- });
1487
- }
1488
- }
1489
- function emitFromDelete(table, result, filters, beforeRow) {
1490
- const resultRow = pickFirstResultRow(result);
1491
- const resourceId = resultRow?.id ?? beforeRow?.id ?? idFromFilters(filters) ?? null;
1492
- const richestRow = resultRow ?? beforeRow;
1493
- const displayName = richestRow ? resolveDisplayName(table, richestRow) : null;
1494
- emitDbEvent({
1495
- modelClass: table,
1496
- operation: "destroy",
1497
- resourceId,
1498
- displayName,
1499
- modelInstance: richestRow
1500
- });
1501
- }
1502
- function prereadFiltersFromCaptured(filters) {
1503
- const idValue = filters.equals["id"];
1504
- if (!isScalarFilterValue(idValue)) return null;
1505
- const out = [];
1506
- for (const column of Object.keys(filters.equals)) {
1507
- const value = filters.equals[column];
1508
- if (!isScalarFilterValue(value)) continue;
1509
- out.push({ column, value });
1510
- }
1511
- return out;
1512
- }
1513
- function idFromFilters(filters) {
1514
- const value = filters.equals["id"];
1515
- return isScalarFilterValue(value) ? value : null;
1516
- }
1517
- function isScalarFilterValue(value) {
1518
- return typeof value === "string" || typeof value === "number" || typeof value === "bigint";
1519
- }
1520
- function buildUpdateChanges(values, beforeRow) {
1521
- return Object.keys(values).map((attribute) => {
1522
- const change = {
1523
- attribute,
1524
- to: values[attribute]
1525
- };
1526
- if (beforeRow && Object.prototype.hasOwnProperty.call(beforeRow, attribute)) {
1527
- change.from = beforeRow[attribute];
1528
- }
1529
- return change;
1530
- });
1531
- }
1532
- function pickFirstResultRow(result) {
1533
- if (!result || result.error) return null;
1534
- if (Array.isArray(result.data)) {
1535
- const first = result.data[0];
1536
- return isPlainObject4(first) ? first : null;
1537
- }
1538
- if (isPlainObject4(result.data)) return result.data;
1539
- return null;
1540
- }
1541
- function pickResultRows(result) {
1542
- if (!result || result.error || !Array.isArray(result.data)) return [];
1543
- return result.data.map(
1544
- (row) => isPlainObject4(row) ? row : void 0
1545
- );
1546
- }
1547
- function isPlainObject4(value) {
1548
- if (value === null || typeof value !== "object") return false;
1549
- if (Array.isArray(value)) return false;
1550
- if (value instanceof Date) return false;
1551
- return true;
1552
- }
1553
- function describeError6(error) {
1554
- if (error instanceof Error) return `${error.name}: ${error.message}`;
1555
- return String(error);
1556
- }
1557
- var GLOBAL_CLIENT_KEY;
1558
- var init_supabase = __esm({
1559
- "src/db/supabase.ts"() {
1560
- init_logger();
1561
- init_configuration();
1562
- init_shared();
1563
- GLOBAL_CLIENT_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:supabase-current-client");
1564
- }
1565
- });
1566
-
1567
- // src/index.ts
1568
- init_configuration();
1569
- init_logger();
1570
- init_buffer();
1571
-
1572
- // src/pipeline/flush-scheduler.ts
1573
- init_configuration();
1574
- init_logger();
1575
- init_buffer();
1576
-
1577
- // src/pipeline/retry-sender.ts
1578
- init_configuration();
1579
- init_logger();
1
+ import { patchPgClient } from './chunk-DKRNNI4I.js';
2
+ import { flushAuditLog, runWithEmittedAuditIdsScope, auditLogInstalled, checkAuditLogAccess, detectTriggerTrackedTables } from './chunk-CU45I2WR.js';
3
+ import { configuration, resolveCorrelation, runWithCorrelation, build, getCurrentActor, current, pushEvent, setActor, runWithActorScope, scrubSecretsInText, buffer_exports, sanitizeRequestParams, passesLuhn, drainEvents, DEFAULT_EXCLUDED_EXTENSIONS } from './chunk-CE3R7DVB.js';
4
+ export { ArgError, build as buildEvent } from './chunk-CE3R7DVB.js';
5
+ import { logger, setLogLevel } from './chunk-C5OSM557.js';
6
+ import './chunk-SIAA4J6H.js';
1580
7
 
1581
8
  // src/pipeline/transport.ts
1582
- init_configuration();
1583
- init_logger();
1584
9
  var REQUEST_TIMEOUT_MS = 1e4;
1585
10
  var transport = {
1586
11
  async send(events) {
@@ -1760,8 +185,6 @@ function describeError3(error) {
1760
185
  }
1761
186
 
1762
187
  // src/http/outgoing-fetch.ts
1763
- init_correlation();
1764
- init_logger();
1765
188
  var HEADER = "x-correlation-id";
1766
189
  var originalFetch = null;
1767
190
  var patched = false;
@@ -1812,653 +235,6 @@ function describeError4(error) {
1812
235
  return String(error);
1813
236
  }
1814
237
 
1815
- // src/triggers/patch-pg.ts
1816
- init_actor();
1817
- init_correlation();
1818
- init_logger();
1819
- var txState = /* @__PURE__ */ new WeakMap();
1820
- function patchPgClient(pgModule) {
1821
- if (!pgModule || !pgModule.Client || !pgModule.Client.prototype) {
1822
- logger.debug("patchPgClient: not a recognized pg module shape, skipping");
1823
- return;
1824
- }
1825
- const proto = pgModule.Client.prototype;
1826
- if (proto._ezlogsPatched) return;
1827
- const originalQuery = proto.query;
1828
- proto.query = function patchedQuery(config, values, callback) {
1829
- return runPatchedQuery(
1830
- this,
1831
- originalQuery,
1832
- config,
1833
- values,
1834
- callback
1835
- );
1836
- };
1837
- proto._ezlogsPatched = true;
1838
- }
1839
- function runPatchedQuery(client, original, config, values, callback) {
1840
- const state2 = ensureState(client);
1841
- const text = extractQueryText(config);
1842
- const verb = leadingVerb(text);
1843
- if (verb === "BEGIN" || verb === "START") {
1844
- state2.inTx = true;
1845
- state2.injected = false;
1846
- return original.call(client, config, values, callback);
1847
- }
1848
- if (verb === "COMMIT" || verb === "ROLLBACK" || verb === "END") {
1849
- const result = original.call(client, config, values, callback);
1850
- state2.inTx = false;
1851
- state2.injected = false;
1852
- return result;
1853
- }
1854
- if (state2.inTx) {
1855
- if (state2.injected) {
1856
- return original.call(client, config, values, callback);
1857
- }
1858
- const ctx2 = snapshotContext();
1859
- if (!ctx2.actorId && !ctx2.correlationId) {
1860
- state2.injected = true;
1861
- return original.call(client, config, values, callback);
1862
- }
1863
- state2.injected = true;
1864
- return injectAndRun(client, original, config, values, callback, ctx2);
1865
- }
1866
- const ctx = snapshotContext();
1867
- if (!ctx.actorId && !ctx.correlationId) {
1868
- return original.call(client, config, values, callback);
1869
- }
1870
- return wrapInTx(client, original, config, values, callback, ctx);
1871
- }
1872
- function snapshotContext() {
1873
- const actor = getCurrentActor();
1874
- return {
1875
- actorId: actor && actor.id ? actor.id : null,
1876
- correlationId: current()
1877
- };
1878
- }
1879
- async function injectAndRun(client, original, config, values, callback, ctx) {
1880
- if (ctx.actorId) {
1881
- await safeSet(client, original, {
1882
- text: "SELECT set_config('ezlogs.actor_id', $1, true)",
1883
- values: [ctx.actorId]
1884
- });
1885
- }
1886
- if (ctx.correlationId) {
1887
- await safeSet(client, original, {
1888
- text: "SELECT set_config('ezlogs.correlation_id', $1, true)",
1889
- values: [ctx.correlationId]
1890
- });
1891
- }
1892
- return original.call(client, config, values, callback);
1893
- }
1894
- async function safeSet(client, original, cfg) {
1895
- try {
1896
- const result = original.call(client, cfg);
1897
- if (result && typeof result.then === "function") {
1898
- await result;
1899
- }
1900
- } catch (err) {
1901
- logger.debug(
1902
- `patchPgClient: SET LOCAL failed (continuing): ${err instanceof Error ? err.message : String(err)}`
1903
- );
1904
- }
1905
- }
1906
- function wrapInTx(client, original, config, values, callback, ctx) {
1907
- const state2 = ensureState(client);
1908
- let userCb = null;
1909
- let realValues = values;
1910
- if (typeof callback === "function") {
1911
- userCb = callback;
1912
- } else if (typeof values === "function") {
1913
- userCb = values;
1914
- realValues = void 0;
1915
- }
1916
- const begin = original.call(client, "BEGIN");
1917
- if (!begin || typeof begin.then !== "function") {
1918
- return original.call(client, config, values, callback);
1919
- }
1920
- const wrapped = begin.then(async () => {
1921
- state2.inTx = true;
1922
- state2.injected = true;
1923
- if (ctx.actorId) {
1924
- await original.call(client, {
1925
- text: "SELECT set_config('ezlogs.actor_id', $1, true)",
1926
- values: [ctx.actorId]
1927
- });
1928
- }
1929
- if (ctx.correlationId) {
1930
- await original.call(client, {
1931
- text: "SELECT set_config('ezlogs.correlation_id', $1, true)",
1932
- values: [ctx.correlationId]
1933
- });
1934
- }
1935
- }).then(
1936
- () => (
1937
- // Run the user's actual query in promise mode — DO NOT forward
1938
- // the caller's callback. See comment above.
1939
- original.call(client, config, realValues)
1940
- )
1941
- ).then(
1942
- async (result) => {
1943
- await original.call(client, "COMMIT");
1944
- state2.inTx = false;
1945
- state2.injected = false;
1946
- return result;
1947
- },
1948
- async (err) => {
1949
- try {
1950
- await original.call(client, "ROLLBACK");
1951
- } catch {
1952
- }
1953
- state2.inTx = false;
1954
- state2.injected = false;
1955
- throw err;
1956
- }
1957
- );
1958
- if (userCb) {
1959
- wrapped.then(
1960
- (result) => userCb(null, result),
1961
- (err) => userCb(err instanceof Error ? err : new Error(String(err)))
1962
- );
1963
- return void 0;
1964
- }
1965
- return wrapped;
1966
- }
1967
- function ensureState(client) {
1968
- let s = txState.get(client);
1969
- if (!s) {
1970
- s = { inTx: false, injected: false };
1971
- txState.set(client, s);
1972
- }
1973
- return s;
1974
- }
1975
- function extractQueryText(config) {
1976
- if (typeof config === "string") return config;
1977
- if (config && typeof config === "object" && typeof config.text === "string") {
1978
- return config.text;
1979
- }
1980
- return "";
1981
- }
1982
- function leadingVerb(text) {
1983
- let s = text;
1984
- while (true) {
1985
- const before = s.length;
1986
- s = s.replace(/^\s+/, "");
1987
- s = s.replace(/^--[^\n]*\n?/, "");
1988
- if (s.length === before) break;
1989
- }
1990
- const m = /^[A-Za-z]+/.exec(s);
1991
- return m ? m[0].toUpperCase() : "";
1992
- }
1993
-
1994
- // src/triggers/reader.ts
1995
- init_logger();
1996
- init_shared();
1997
- init_correlation();
1998
- init_actor();
1999
-
2000
- // src/triggers/emit-dedup.ts
2001
- init_edge_fallback();
2002
- var storage3 = createScopedStorage(
2003
- /* @__PURE__ */ Symbol.for("ezlogs-nextjs:audit-emitted-ids-storage")
2004
- );
2005
- function currentEmittedAuditIds() {
2006
- return storage3.read();
2007
- }
2008
- function runWithEmittedAuditIdsScope(callback) {
2009
- const existing = storage3.read();
2010
- if (existing !== null) return callback();
2011
- return storage3.run(/* @__PURE__ */ new Set(), callback);
2012
- }
2013
-
2014
- // src/triggers/reader.ts
2015
- var COLUMNS = "id, table_name, op, old_row, new_row, resource_id, correlation_id, txid, captured_at";
2016
- var ORPHAN_AGE = "5 minutes";
2017
- var PRUNE_AGE = "24 hours";
2018
- var SWEEP_BATCH = 100;
2019
- var PRUNE_BATCH = 2e3;
2020
- var SWEEP_INTERVAL_MS = 1e4;
2021
- var PRUNE_INTERVAL_MS = 10 * 6e4;
2022
- var lastSweepAt = 0;
2023
- var lastPruneAt = 0;
2024
- var deleteDenied = false;
2025
- var txCorrelation = /* @__PURE__ */ new Map();
2026
- async function readAuditRows(exec, correlationId, since = null) {
2027
- const where = since ? "correlation_id = $1 AND captured_at >= $2" : "correlation_id = $1";
2028
- const params = since ? [correlationId, since.toISOString()] : [correlationId];
2029
- try {
2030
- if (!deleteDenied) {
2031
- try {
2032
- return sortById(
2033
- extractRows(
2034
- await exec(
2035
- `DELETE FROM ezlogs_audit_log WHERE ${where} RETURNING ${COLUMNS}`,
2036
- params
2037
- )
2038
- ).map(normalizeAuditRow)
2039
- );
2040
- } catch (err) {
2041
- if (!isPermissionDenied(err)) throw err;
2042
- deleteDenied = true;
2043
- logger.warn(
2044
- "the database role used by the agent cannot DELETE from ezlogs_audit_log. Rows will not be cleaned up after they are sent; grant DELETE or schedule `DELETE FROM ezlogs_audit_log WHERE captured_at < now() - interval '24 hours'`."
2045
- );
2046
- }
2047
- }
2048
- const result = await exec(
2049
- `SELECT ${COLUMNS} FROM ezlogs_audit_log WHERE ${where} ORDER BY id ASC`,
2050
- params
2051
- );
2052
- return extractRows(result).map(normalizeAuditRow);
2053
- } catch (err) {
2054
- logger.debug(
2055
- `readAuditRows failed: ${err instanceof Error ? err.message : String(err)}`
2056
- );
2057
- return [];
2058
- }
2059
- }
2060
- async function sweepAuditLog(exec) {
2061
- if (deleteDenied) return 0;
2062
- try {
2063
- const rows = sortById(
2064
- extractRows(
2065
- await exec(
2066
- `DELETE FROM ezlogs_audit_log
2067
- WHERE id IN (
2068
- SELECT id FROM ezlogs_audit_log
2069
- WHERE (correlation_id IS NULL
2070
- OR captured_at < now() - interval '${ORPHAN_AGE}')
2071
- -- Never resurface history: past the retention cap a
2072
- -- row is pruned, not sent as new activity.
2073
- AND captured_at > now() - interval '${PRUNE_AGE}'
2074
- ORDER BY id
2075
- LIMIT ${SWEEP_BATCH}
2076
- FOR UPDATE SKIP LOCKED)
2077
- RETURNING ${COLUMNS}`,
2078
- []
2079
- )
2080
- ).map(normalizeAuditRow)
2081
- );
2082
- await loadTableMeta(exec, rows);
2083
- for (const row of rows) {
2084
- const correlationId = row.correlation_id ?? correlationForTx(row.txid);
2085
- runWithCorrelation(
2086
- correlationId,
2087
- () => runWithActorScope(() => emitOne(row))
2088
- );
2089
- }
2090
- return rows.length;
2091
- } catch (err) {
2092
- logger.debug(
2093
- `sweepAuditLog failed: ${err instanceof Error ? err.message : String(err)}`
2094
- );
2095
- return 0;
2096
- }
2097
- }
2098
- async function pruneAuditLog(exec) {
2099
- if (deleteDenied) return;
2100
- try {
2101
- await exec(
2102
- `DELETE FROM ezlogs_audit_log
2103
- WHERE id IN (
2104
- SELECT id FROM ezlogs_audit_log
2105
- WHERE captured_at < now() - interval '${PRUNE_AGE}'
2106
- LIMIT ${PRUNE_BATCH})`,
2107
- []
2108
- );
2109
- } catch (err) {
2110
- logger.debug(
2111
- `pruneAuditLog failed: ${err instanceof Error ? err.message : String(err)}`
2112
- );
2113
- }
2114
- }
2115
- async function auditLogInstalled(exec) {
2116
- try {
2117
- const rows = extractRows(
2118
- await exec(
2119
- `SELECT to_regclass('public.ezlogs_audit_log') IS NOT NULL AS installed`,
2120
- []
2121
- )
2122
- );
2123
- const installed = rows[0]?.installed;
2124
- return typeof installed === "boolean" ? installed : null;
2125
- } catch {
2126
- return null;
2127
- }
2128
- }
2129
- async function checkAuditLogAccess(exec) {
2130
- try {
2131
- const rows = extractRows(
2132
- await exec(
2133
- `SELECT current_user AS role
2134
- FROM pg_class c
2135
- JOIN pg_roles r ON r.rolname = current_user
2136
- WHERE c.oid = 'public.ezlogs_audit_log'::regclass
2137
- AND c.relrowsecurity
2138
- AND NOT r.rolsuper
2139
- AND NOT r.rolbypassrls
2140
- AND NOT pg_has_role(current_user, c.relowner, 'MEMBER')
2141
- AND NOT EXISTS (SELECT 1 FROM pg_policies p
2142
- WHERE p.schemaname = 'public'
2143
- AND p.tablename = 'ezlogs_audit_log')`,
2144
- []
2145
- )
2146
- );
2147
- const role = rows[0]?.role;
2148
- if (typeof role !== "string") return false;
2149
- logger.warn(
2150
- `the database role "${role}" is not the owner of ezlogs_audit_log, which has row-level security, so the agent reads 0 rows and no DB changes are sent. As the table owner, run: GRANT SELECT, DELETE ON ezlogs_audit_log TO "${role}"; CREATE POLICY ezlogs_reader ON ezlogs_audit_log TO "${role}" USING (true);`
2151
- );
2152
- return true;
2153
- } catch {
2154
- return false;
2155
- }
2156
- }
2157
- async function detectTriggerTrackedTables(exec) {
2158
- try {
2159
- const result = await exec(
2160
- `SELECT event_object_table AS table_name
2161
- FROM information_schema.triggers
2162
- WHERE trigger_name = 'ezlogs_audit'
2163
- AND trigger_schema = 'public'`,
2164
- []
2165
- );
2166
- const rows = extractRows(result);
2167
- const tables = /* @__PURE__ */ new Set();
2168
- for (const row of rows) {
2169
- const r = row ?? {};
2170
- if (typeof r.table_name === "string" && r.table_name.length > 0) {
2171
- tables.add(r.table_name);
2172
- }
2173
- }
2174
- return tables;
2175
- } catch (err) {
2176
- logger.debug(
2177
- `detectTriggerTrackedTables failed: ${err instanceof Error ? err.message : String(err)}`
2178
- );
2179
- return null;
2180
- }
2181
- }
2182
- function emitAuditRows(rows) {
2183
- for (const row of rows) {
2184
- emitOne(row);
2185
- }
2186
- }
2187
- async function flushAuditLog(exec, options = {}) {
2188
- if (!exec) return;
2189
- const correlationId = current();
2190
- if (!correlationId) return;
2191
- const rows = await readAuditRows(exec, correlationId, options.since ?? null);
2192
- await loadTableMeta(exec, rows);
2193
- emitFresh(rows);
2194
- const now = Date.now();
2195
- if (now - lastPruneAt >= PRUNE_INTERVAL_MS) {
2196
- lastPruneAt = now;
2197
- await pruneAuditLog(exec);
2198
- }
2199
- if (now - lastSweepAt >= SWEEP_INTERVAL_MS) {
2200
- lastSweepAt = now;
2201
- await sweepAuditLog(exec);
2202
- }
2203
- }
2204
- var tableMeta = /* @__PURE__ */ new Map();
2205
- var META_RETRY_MS = 6e4;
2206
- var metaRetryAt = 0;
2207
- async function loadTableMeta(exec, rows) {
2208
- if (Date.now() < metaRetryAt) return;
2209
- const tables = [
2210
- ...new Set(rows.map((r) => r.table_name).filter((t) => t !== "" && !t.includes(",") && !tableMeta.has(t)))
2211
- ];
2212
- if (tables.length === 0) return;
2213
- const list = tables.join(",");
2214
- try {
2215
- const fkRows = extractRows(
2216
- await exec(
2217
- `SELECT cl.relname AS table_name, a.attname AS column_name, rf.relname AS ref_table
2218
- FROM pg_constraint c
2219
- JOIN pg_class cl ON cl.oid = c.conrelid
2220
- JOIN pg_namespace n ON n.oid = cl.relnamespace
2221
- JOIN pg_class rf ON rf.oid = c.confrelid
2222
- JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = c.conkey[1]
2223
- WHERE c.contype = 'f'
2224
- AND n.nspname = 'public'
2225
- AND array_length(c.conkey, 1) = 1
2226
- AND cl.relname = ANY(string_to_array($1, ','))
2227
- ORDER BY cl.relname, a.attnum`,
2228
- [list]
2229
- )
2230
- );
2231
- const tsRows = extractRows(
2232
- await exec(
2233
- `SELECT cl.relname AS table_name, a.attname AS column_name
2234
- FROM pg_attribute a
2235
- JOIN pg_class cl ON cl.oid = a.attrelid
2236
- JOIN pg_namespace n ON n.oid = cl.relnamespace
2237
- WHERE n.nspname = 'public'
2238
- AND cl.relname = ANY(string_to_array($1, ','))
2239
- AND a.attnum > 0
2240
- AND NOT a.attisdropped
2241
- AND a.atttypid = 'timestamp'::regtype`,
2242
- [list]
2243
- )
2244
- );
2245
- const fks = /* @__PURE__ */ new Map();
2246
- for (const raw of fkRows) {
2247
- const r = raw ?? {};
2248
- if (typeof r.table_name !== "string" || typeof r.column_name !== "string" || typeof r.ref_table !== "string") {
2249
- continue;
2250
- }
2251
- fks.set(r.table_name, [...fks.get(r.table_name) ?? [], { column: r.column_name, refTable: r.ref_table }]);
2252
- }
2253
- const timestamps = /* @__PURE__ */ new Map();
2254
- for (const raw of tsRows) {
2255
- const r = raw ?? {};
2256
- if (typeof r.table_name !== "string" || typeof r.column_name !== "string") continue;
2257
- timestamps.set(r.table_name, (timestamps.get(r.table_name) ?? /* @__PURE__ */ new Set()).add(r.column_name));
2258
- }
2259
- for (const table of tables) {
2260
- tableMeta.set(table, { fks: fks.get(table) ?? [], naiveTimestamps: timestamps.get(table) ?? /* @__PURE__ */ new Set() });
2261
- }
2262
- } catch (err) {
2263
- metaRetryAt = Date.now() + META_RETRY_MS;
2264
- logger.debug(`table metadata lookup failed: ${err instanceof Error ? err.message : String(err)}`);
2265
- }
2266
- }
2267
- function relatedResourceIds(table, row) {
2268
- const out = [];
2269
- for (const fk of tableMeta.get(table)?.fks ?? []) {
2270
- const value = row[fk.column];
2271
- if (typeof value === "string" || typeof value === "number") {
2272
- out.push({ resource_type: fk.refTable, resource_id: String(value) });
2273
- }
2274
- }
2275
- return out;
2276
- }
2277
- function emitFresh(rows) {
2278
- if (rows.length === 0) return;
2279
- const emitted = currentEmittedAuditIds();
2280
- if (emitted === null) {
2281
- emitAuditRows(rows);
2282
- return;
2283
- }
2284
- const fresh = [];
2285
- for (const row of rows) {
2286
- if (row.id === "" || emitted.has(row.id)) continue;
2287
- emitted.add(row.id);
2288
- fresh.push(row);
2289
- }
2290
- emitAuditRows(fresh);
2291
- }
2292
- function correlationForTx(txid) {
2293
- if (!txid) return generate();
2294
- let id = txCorrelation.get(txid);
2295
- if (!id) {
2296
- if (txCorrelation.size >= 1e3) txCorrelation.clear();
2297
- id = generate();
2298
- txCorrelation.set(txid, id);
2299
- }
2300
- return id;
2301
- }
2302
- function isPermissionDenied(err) {
2303
- return err?.code === "42501";
2304
- }
2305
- function sortById(rows) {
2306
- return rows.sort(
2307
- (a, b) => a.id.length !== b.id.length ? a.id.length - b.id.length : a.id < b.id ? -1 : a.id > b.id ? 1 : 0
2308
- );
2309
- }
2310
- function emitOne(row) {
2311
- const op = mapOp(row.op);
2312
- if (!op) return;
2313
- const naive = tableMeta.get(row.table_name)?.naiveTimestamps ?? null;
2314
- const oldRow = withUtcTimestamps(coerceJsonb(row.old_row), naive);
2315
- const newRow = withUtcTimestamps(coerceJsonb(row.new_row), naive);
2316
- const related = row.resource_id === null ? relatedResourceIds(row.table_name, newRow ?? oldRow ?? {}) : null;
2317
- if (op === "create" && newRow) {
2318
- emitDbEvent({
2319
- modelClass: row.table_name,
2320
- operation: "create",
2321
- resourceId: row.resource_id,
2322
- initialAttributes: newRow,
2323
- modelInstance: newRow,
2324
- displayName: null,
2325
- timestamp: row.captured_at ?? null,
2326
- relatedResourceIds: related,
2327
- _fromTrigger: true
2328
- });
2329
- return;
2330
- }
2331
- if (op === "update" && oldRow && newRow) {
2332
- const changes = computeChanges(oldRow, newRow);
2333
- if (changes.length === 0) {
2334
- return;
2335
- }
2336
- emitDbEvent({
2337
- modelClass: row.table_name,
2338
- operation: "update",
2339
- resourceId: row.resource_id,
2340
- changes,
2341
- // Prefer the post-state for the display name — that's what the
2342
- // user just told the system to call this row.
2343
- modelInstance: newRow,
2344
- displayName: null,
2345
- timestamp: row.captured_at ?? null,
2346
- relatedResourceIds: related,
2347
- _fromTrigger: true
2348
- });
2349
- return;
2350
- }
2351
- if (op === "destroy" && oldRow) {
2352
- emitDbEvent({
2353
- modelClass: row.table_name,
2354
- operation: "destroy",
2355
- resourceId: row.resource_id,
2356
- initialAttributes: oldRow,
2357
- modelInstance: oldRow,
2358
- displayName: null,
2359
- timestamp: row.captured_at ?? null,
2360
- relatedResourceIds: related,
2361
- _fromTrigger: true
2362
- });
2363
- return;
2364
- }
2365
- }
2366
- var NAIVE_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?$/;
2367
- function withUtcTimestamps(row, naiveColumns) {
2368
- if (!row) return row;
2369
- const out = {};
2370
- for (const [key, value] of Object.entries(row)) {
2371
- const isNaiveColumn = naiveColumns ? naiveColumns.has(key) : /(_at|At)$/.test(key);
2372
- out[key] = isNaiveColumn && typeof value === "string" && NAIVE_TIMESTAMP.test(value) ? `${value}Z` : value;
2373
- }
2374
- return out;
2375
- }
2376
- function mapOp(op) {
2377
- if (op === "INSERT") return "create";
2378
- if (op === "UPDATE") return "update";
2379
- if (op === "DELETE") return "destroy";
2380
- return null;
2381
- }
2382
- function computeChanges(oldRow, newRow) {
2383
- const out = [];
2384
- for (const key of Object.keys(newRow)) {
2385
- const before = oldRow[key];
2386
- const after = newRow[key];
2387
- if (deepEqual(before, after)) continue;
2388
- out.push({ attribute: key, from: before, to: after });
2389
- }
2390
- return out;
2391
- }
2392
- function deepEqual(a, b) {
2393
- if (a === b) return true;
2394
- if (a === null || b === null) return false;
2395
- if (typeof a !== typeof b) return false;
2396
- if (typeof a !== "object") return false;
2397
- try {
2398
- return stableStringify(a) === stableStringify(b);
2399
- } catch {
2400
- return false;
2401
- }
2402
- }
2403
- function stableStringify(value) {
2404
- if (value === null || typeof value !== "object") return JSON.stringify(value);
2405
- if (Array.isArray(value)) {
2406
- return "[" + value.map((v) => stableStringify(v)).join(",") + "]";
2407
- }
2408
- const entries = Object.keys(value).sort().map((k) => JSON.stringify(k) + ":" + stableStringify(value[k]));
2409
- return "{" + entries.join(",") + "}";
2410
- }
2411
- function extractRows(result) {
2412
- if (!result) return [];
2413
- if (Array.isArray(result)) return result;
2414
- if (typeof result === "object" && Array.isArray(result.rows)) {
2415
- return result.rows;
2416
- }
2417
- return [];
2418
- }
2419
- function toDate(value) {
2420
- if (value == null) return null;
2421
- const d = value instanceof Date ? value : new Date(String(value));
2422
- return Number.isNaN(d.getTime()) ? null : d;
2423
- }
2424
- function normalizeAuditRow(raw) {
2425
- const r = raw ?? {};
2426
- return {
2427
- id: r.id == null ? "" : String(r.id),
2428
- table_name: String(r.table_name ?? ""),
2429
- op: r.op,
2430
- old_row: r.old_row ?? null,
2431
- new_row: r.new_row ?? null,
2432
- resource_id: r.resource_id == null ? null : String(r.resource_id),
2433
- correlation_id: r.correlation_id == null ? null : String(r.correlation_id),
2434
- txid: r.txid == null ? null : String(r.txid),
2435
- captured_at: toDate(r.captured_at)
2436
- };
2437
- }
2438
- function coerceJsonb(value) {
2439
- if (value === null || value === void 0) return null;
2440
- if (typeof value === "string") {
2441
- try {
2442
- const parsed = JSON.parse(value);
2443
- return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
2444
- } catch {
2445
- return null;
2446
- }
2447
- }
2448
- if (typeof value === "object" && !Array.isArray(value)) return value;
2449
- return null;
2450
- }
2451
-
2452
- // src/index.ts
2453
- init_logger();
2454
- init_event_builder();
2455
-
2456
- // src/http/capture.ts
2457
- init_configuration();
2458
- init_logger();
2459
- init_event_builder();
2460
- init_buffer();
2461
-
2462
238
  // src/pipeline/serverless.ts
2463
239
  var cachedFlag = null;
2464
240
  function isServerless() {
@@ -2478,9 +254,6 @@ function detect() {
2478
254
  return false;
2479
255
  }
2480
256
 
2481
- // src/http/capture.ts
2482
- init_actor();
2483
-
2484
257
  // src/user-agent-detector.ts
2485
258
  var PATTERNS = [
2486
259
  { prefix: "claude-", vendor: "claude", label: "Claude" },
@@ -2504,10 +277,6 @@ function classifyUserAgent(userAgent) {
2504
277
  };
2505
278
  }
2506
279
 
2507
- // src/http/capture.ts
2508
- init_correlation();
2509
- init_sanitize();
2510
-
2511
280
  // src/http/path-matcher.ts
2512
281
  function pathMatches(path, pattern) {
2513
282
  const startsWithStar = pattern.startsWith("*");
@@ -2531,11 +300,7 @@ function hasExcludedExtension(path, extensions) {
2531
300
  return extensions.some((ext) => path.endsWith(ext));
2532
301
  }
2533
302
 
2534
- // src/http/capture.ts
2535
- init_configuration();
2536
-
2537
303
  // src/http/source-data.ts
2538
- init_sanitize();
2539
304
  function buildHttpSourceData(input) {
2540
305
  const { controller, action } = resolveControllerAction(input);
2541
306
  const source = {
@@ -2709,14 +474,13 @@ function determineOutcome(statusCode, exception, graphqlResponseErrors, response
2709
474
  }
2710
475
 
2711
476
  // src/http/graphql.ts
2712
- init_sanitize();
2713
477
  var QUERY_PREFIXES = ["Get", "Fetch", "List", "Find", "Load", "Search", "Query"];
2714
478
  var MUTATION_PREFIXES = ["Create", "Update", "Delete", "Remove", "Add", "Set", "Upsert"];
2715
479
  function isGraphqlPath(path) {
2716
480
  return path === "/graphql" || path.startsWith("/graphql/");
2717
481
  }
2718
482
  function parseGraphqlBody(body, excludedOperations, excludedVariableKeys) {
2719
- if (!isPlainObject3(body)) return { metadata: null };
483
+ if (!isPlainObject(body)) return { metadata: null };
2720
484
  const obj = body;
2721
485
  const queryString = typeof obj.query === "string" ? obj.query : null;
2722
486
  let operationName = typeof obj.operationName === "string" ? obj.operationName : null;
@@ -2763,14 +527,14 @@ function isExcludedOperation(name, patterns) {
2763
527
  });
2764
528
  }
2765
529
  function extractGraphqlErrorsFromBody(parsed) {
2766
- if (!isPlainObject3(parsed)) return null;
530
+ if (!isPlainObject(parsed)) return null;
2767
531
  const errors = parsed.errors;
2768
532
  if (!Array.isArray(errors) || errors.length === 0) return null;
2769
- const messages = errors.map((err) => isPlainObject3(err) ? err.message : null).filter((m) => typeof m === "string" && m.length > 0);
533
+ const messages = errors.map((err) => isPlainObject(err) ? err.message : null).filter((m) => typeof m === "string" && m.length > 0);
2770
534
  if (messages.length === 0) return null;
2771
535
  return messages.length === 1 ? messages[0] : messages.join("; ");
2772
536
  }
2773
- function isPlainObject3(value) {
537
+ function isPlainObject(value) {
2774
538
  if (value === null || typeof value !== "object") return false;
2775
539
  const proto = Object.getPrototypeOf(value);
2776
540
  return proto === Object.prototype || proto === null;
@@ -2845,13 +609,13 @@ function captureRoute(handler, context = {}) {
2845
609
  } catch (preCaptureError) {
2846
610
  if (handlerInvoked) throw preCaptureError;
2847
611
  logger.warn(
2848
- `captureRoute pre-handler setup failed (${describeError7(preCaptureError)}); bypassing capture for this request`
612
+ `captureRoute pre-handler setup failed (${describeError5(preCaptureError)}); bypassing capture for this request`
2849
613
  );
2850
614
  return Promise.resolve(handler(...args));
2851
615
  }
2852
616
  };
2853
617
  }
2854
- var CORRELATION_HEADER2 = "x-ezlogs-correlation-id";
618
+ var CORRELATION_HEADER = "x-ezlogs-correlation-id";
2855
619
  function withMiddlewareCapture(middleware) {
2856
620
  return async (request, ...rest) => {
2857
621
  let middlewareInvoked = false;
@@ -2862,7 +626,7 @@ function withMiddlewareCapture(middleware) {
2862
626
  try {
2863
627
  const correlationId = resolveCorrelation(request.headers);
2864
628
  try {
2865
- request.headers.set(CORRELATION_HEADER2, correlationId);
629
+ request.headers.set(CORRELATION_HEADER, correlationId);
2866
630
  } catch {
2867
631
  }
2868
632
  return await runWithCorrelation(
@@ -2873,7 +637,7 @@ function withMiddlewareCapture(middleware) {
2873
637
  const response = await Promise.resolve(runMiddleware(request, ...rest));
2874
638
  try {
2875
639
  if (response?.headers && typeof response.headers.set === "function") {
2876
- response.headers.set(CORRELATION_HEADER2, correlationId);
640
+ response.headers.set(CORRELATION_HEADER, correlationId);
2877
641
  }
2878
642
  } catch {
2879
643
  }
@@ -2889,7 +653,7 @@ function withMiddlewareCapture(middleware) {
2889
653
  });
2890
654
  }
2891
655
  } catch (error) {
2892
- logger.debug(`page navigation capture failed: ${describeError7(error)}`);
656
+ logger.debug(`page navigation capture failed: ${describeError5(error)}`);
2893
657
  }
2894
658
  return response;
2895
659
  })
@@ -2897,7 +661,7 @@ function withMiddlewareCapture(middleware) {
2897
661
  } catch (preCaptureError) {
2898
662
  if (middlewareInvoked) throw preCaptureError;
2899
663
  logger.warn(
2900
- `withMiddlewareCapture pre-handler setup failed (${describeError7(preCaptureError)}); bypassing capture for this request`
664
+ `withMiddlewareCapture pre-handler setup failed (${describeError5(preCaptureError)}); bypassing capture for this request`
2901
665
  );
2902
666
  return await Promise.resolve(middleware(request, ...rest));
2903
667
  }
@@ -2957,7 +721,7 @@ async function emitPageNavigationEvent(input) {
2957
721
  });
2958
722
  pushEvent(event);
2959
723
  } catch (error) {
2960
- logger.error(`page navigation emit failed: ${describeError7(error)}`);
724
+ logger.error(`page navigation emit failed: ${describeError5(error)}`);
2961
725
  }
2962
726
  }
2963
727
  function pageControllerFromPath(pathname) {
@@ -3023,7 +787,7 @@ function capturePagesApi(handler, context = {}) {
3023
787
  } catch (preCaptureError) {
3024
788
  if (handlerInvoked) throw preCaptureError;
3025
789
  logger.warn(
3026
- `capturePagesApi pre-handler setup failed (${describeError7(preCaptureError)}); bypassing capture for this request`
790
+ `capturePagesApi pre-handler setup failed (${describeError5(preCaptureError)}); bypassing capture for this request`
3027
791
  );
3028
792
  return Promise.resolve(handler(...args));
3029
793
  }
@@ -3102,7 +866,7 @@ function captureServerAction(action, actionName) {
3102
866
  } catch (preCaptureError) {
3103
867
  if (actionInvoked) throw preCaptureError;
3104
868
  logger.warn(
3105
- `captureServerAction pre-handler setup failed (${describeError7(preCaptureError)}); bypassing capture for this action`
869
+ `captureServerAction pre-handler setup failed (${describeError5(preCaptureError)}); bypassing capture for this action`
3106
870
  );
3107
871
  return Promise.resolve(action(...args));
3108
872
  }
@@ -3134,7 +898,7 @@ function classifyServerActionResult(result) {
3134
898
  return verdict;
3135
899
  }
3136
900
  } catch (error) {
3137
- logger.debug(`isServerActionError classifier threw: ${describeError7(error)}`);
901
+ logger.debug(`isServerActionError classifier threw: ${describeError5(error)}`);
3138
902
  }
3139
903
  }
3140
904
  if (Array.isArray(result) && result.length === 2 && result[0] === null && isZsaError(result[1])) {
@@ -3315,7 +1079,7 @@ async function emitServerActionEvent(input) {
3315
1079
  });
3316
1080
  pushEvent(event);
3317
1081
  } catch (error) {
3318
- logger.error(`server-action capture emit failed: ${describeError7(error)}`);
1082
+ logger.error(`server-action capture emit failed: ${describeError5(error)}`);
3319
1083
  }
3320
1084
  }
3321
1085
  function extractServerActionArgs(args, actionName) {
@@ -3545,7 +1309,7 @@ async function snapshotRequest(request) {
3545
1309
  }
3546
1310
  }
3547
1311
  } catch (error) {
3548
- logger.debug(`http snapshot body-parse failed: ${describeError7(error)}`);
1312
+ logger.debug(`http snapshot body-parse failed: ${describeError5(error)}`);
3549
1313
  }
3550
1314
  return { method, url, userAgent, remoteIp, contentType, rawParams, graphqlBody, serverActionId };
3551
1315
  }
@@ -3556,7 +1320,7 @@ async function maybeRunActorHook(request) {
3556
1320
  try {
3557
1321
  hookResult = await Promise.resolve(hook(request));
3558
1322
  } catch (error) {
3559
- logger.debug(`actorFromRequest hook failed: ${describeError7(error)}`);
1323
+ logger.debug(`actorFromRequest hook failed: ${describeError5(error)}`);
3560
1324
  }
3561
1325
  }
3562
1326
  const userAgent = safeGetHeader(request.headers, "user-agent");
@@ -3569,7 +1333,7 @@ async function maybeRunActorHookFromPages(req) {
3569
1333
  try {
3570
1334
  hookResult = await Promise.resolve(hook(req));
3571
1335
  } catch (error) {
3572
- logger.debug(`actorFromRequest hook (pages) failed: ${describeError7(error)}`);
1336
+ logger.debug(`actorFromRequest hook (pages) failed: ${describeError5(error)}`);
3573
1337
  }
3574
1338
  }
3575
1339
  const userAgent = readPagesHeader(req, "user-agent");
@@ -3597,7 +1361,7 @@ async function maybeRunActorHookFromServerAction() {
3597
1361
  );
3598
1362
  } catch (error) {
3599
1363
  logger.debug(
3600
- `actorFromRequest hook (server action) failed: ${describeError7(error)}`
1364
+ `actorFromRequest hook (server action) failed: ${describeError5(error)}`
3601
1365
  );
3602
1366
  }
3603
1367
  }
@@ -3610,11 +1374,11 @@ async function maybeExtractSupabaseActor() {
3610
1374
  if (!config.actorFromSupabase) return;
3611
1375
  if (getCurrentActor()) return;
3612
1376
  try {
3613
- const mod = await Promise.resolve().then(() => (init_supabase(), supabase_exports));
1377
+ const mod = await import('./db/supabase.js');
3614
1378
  const actor = await mod.tryExtractSupabaseActor();
3615
1379
  if (actor) setActor(actor);
3616
1380
  } catch (error) {
3617
- logger.debug(`actorFromSupabase failed: ${describeError7(error)}`);
1381
+ logger.debug(`actorFromSupabase failed: ${describeError5(error)}`);
3618
1382
  }
3619
1383
  }
3620
1384
  function snapshotPagesRequest(req) {
@@ -3691,7 +1455,7 @@ async function loadNextHeaders() {
3691
1455
  try {
3692
1456
  return await Promise.resolve(mod.headers());
3693
1457
  } catch (error) {
3694
- logger.debug(`loadNextHeaders mod.headers() failed: ${describeError7(error)}`);
1458
+ logger.debug(`loadNextHeaders mod.headers() failed: ${describeError5(error)}`);
3695
1459
  return null;
3696
1460
  }
3697
1461
  }
@@ -3703,7 +1467,7 @@ async function tryLoadNextHeadersModule() {
3703
1467
  return await import('next/headers.js');
3704
1468
  } catch (secondError) {
3705
1469
  logger.debug(
3706
- `loadNextHeaders: neither "next/headers" nor "next/headers.js" resolved (${describeError7(firstError)}; ${describeError7(secondError)})`
1470
+ `loadNextHeaders: neither "next/headers" nor "next/headers.js" resolved (${describeError5(firstError)}; ${describeError5(secondError)})`
3707
1471
  );
3708
1472
  return null;
3709
1473
  }
@@ -3753,7 +1517,7 @@ async function emitEvent(input) {
3753
1517
  input.graphqlErrorMessage,
3754
1518
  input.responseErrorMessage ?? null
3755
1519
  );
3756
- const contextValue = buildContext2();
1520
+ const contextValue = buildContext();
3757
1521
  const event = build({
3758
1522
  source_type: "http_request",
3759
1523
  source_data: sourceData,
@@ -3769,10 +1533,10 @@ async function emitEvent(input) {
3769
1533
  } catch (error) {
3770
1534
  const cid = current();
3771
1535
  const cidLabel = cid ? ` (correlation_id=${cid})` : "";
3772
- logger.error(`http capture emit failed${cidLabel}: ${describeError7(error)}`);
1536
+ logger.error(`http capture emit failed${cidLabel}: ${describeError5(error)}`);
3773
1537
  }
3774
1538
  }
3775
- function buildContext2() {
1539
+ function buildContext() {
3776
1540
  const currentActor = getCurrentActor();
3777
1541
  if (!currentActor) return null;
3778
1542
  return { actor: currentActor };
@@ -3868,7 +1632,7 @@ async function readGraphqlErrors(response) {
3868
1632
  return null;
3869
1633
  }
3870
1634
  }
3871
- function describeError7(error) {
1635
+ function describeError5(error) {
3872
1636
  if (error instanceof Error) return `${error.name}: ${error.message}`;
3873
1637
  return String(error);
3874
1638
  }
@@ -4084,4 +1848,4 @@ function _internalsForTests() {
4084
1848
  return { buffer: buffer_exports, flushScheduler };
4085
1849
  }
4086
1850
 
4087
- export { ArgError, __ezlogs_run_inline_server_action, _detectDatabaseUrlFromEnvForTests, _internalsForTests, build as buildEvent, captureHttpEvent, capturePagesApi, captureRoute, captureServerAction, captureServerActionExport, ezlogs, withMiddlewareCapture };
1851
+ export { __ezlogs_run_inline_server_action, _detectDatabaseUrlFromEnvForTests, _internalsForTests, captureHttpEvent, capturePagesApi, captureRoute, captureServerAction, captureServerActionExport, ezlogs, withMiddlewareCapture };