ezlogs-nextjs 0.2.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 (51) hide show
  1. package/README.md +53 -16
  2. package/bin/install-triggers.cjs +73 -11
  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 -713
  18. package/dist/db/drizzle.js +5 -712
  19. package/dist/db/prisma.cjs +52 -763
  20. package/dist/db/prisma.d.cts +3 -1
  21. package/dist/db/prisma.d.ts +3 -1
  22. package/dist/db/prisma.js +38 -749
  23. package/dist/db/supabase.cjs +21 -728
  24. package/dist/db/supabase.js +14 -721
  25. package/dist/index.cjs +204 -2181
  26. package/dist/index.js +107 -2090
  27. package/dist/jobs/bullmq.cjs +61 -552
  28. package/dist/jobs/bullmq.d.cts +8 -3
  29. package/dist/jobs/bullmq.d.ts +8 -3
  30. package/dist/jobs/bullmq.js +58 -549
  31. package/dist/jobs/inngest.cjs +23 -561
  32. package/dist/jobs/inngest.d.cts +7 -5
  33. package/dist/jobs/inngest.d.ts +7 -5
  34. package/dist/jobs/inngest.js +19 -557
  35. package/dist/jobs/supabase-queues.cjs +17 -603
  36. package/dist/jobs/supabase-queues.js +12 -598
  37. package/dist/jobs/trigger.cjs +18 -587
  38. package/dist/jobs/trigger.js +16 -585
  39. package/dist/jobs/upstash-workflow.cjs +62 -584
  40. package/dist/jobs/upstash-workflow.d.cts +17 -2
  41. package/dist/jobs/upstash-workflow.d.ts +17 -2
  42. package/dist/jobs/upstash-workflow.js +59 -582
  43. package/dist/nextjs-plugin/index.cjs +1 -1
  44. package/dist/nextjs-plugin/index.js +1 -1
  45. package/dist/nextjs-plugin/loader.cjs +21 -25
  46. package/dist/nextjs-plugin/loader.js +1 -5
  47. package/dist/triggers/index.cjs +40 -1234
  48. package/dist/triggers/index.d.cts +7 -2
  49. package/dist/triggers/index.d.ts +7 -2
  50. package/dist/triggers/index.js +6 -1221
  51. package/package.json +4 -1
package/dist/index.js CHANGED
@@ -1,1478 +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 sanitizeValue(key, value, depth, userPatterns) {
750
- if (isSensitiveKey2(key, userPatterns)) return "[FILTERED]";
751
- if (isPlainObject2(value)) {
752
- return sanitizeNestedObject(value, depth, userPatterns);
753
- }
754
- if (Array.isArray(value)) {
755
- return sanitizeArrayValue(value, depth, userPatterns);
756
- }
757
- return value;
758
- }
759
- function sanitizeNestedObject(hash, depth, userPatterns) {
760
- if (depth >= MAX_NESTING_DEPTH) return "[Object]";
761
- if (Object.keys(hash).length === 0) return {};
762
- const out = {};
763
- for (const k of Object.keys(hash)) {
764
- out[k] = sanitizeValue(k, hash[k], depth + 1, userPatterns);
765
- }
766
- return out;
767
- }
768
- function sanitizeArrayValue(array, depth, userPatterns) {
769
- if (array.length === 0) return [];
770
- const allPrimitive = array.every(isPrimitive);
771
- if (allPrimitive) {
772
- if (array.length <= MAX_ARRAY_DISPLAY_SIZE) return array;
773
- const preview = array.slice(0, MAX_ARRAY_DISPLAY_SIZE);
774
- return `${JSON.stringify(preview)}... (${array.length} total)`;
775
- }
776
- if (array.length <= MAX_ARRAY_DISPLAY_SIZE) {
777
- return array.map((item) => sanitizeArrayItem(item, depth, userPatterns));
778
- }
779
- return {
780
- _truncated: true,
781
- _count: array.length,
782
- _preview: array.slice(0, MAX_ARRAY_DISPLAY_SIZE).map((item) => sanitizeArrayItem(item, depth, userPatterns))
783
- };
784
- }
785
- function sanitizeArrayItem(item, depth, userPatterns) {
786
- if (isPrimitive(item)) return item;
787
- if (isPlainObject2(item)) {
788
- return sanitizeNestedObject(item, depth + 1, userPatterns);
789
- }
790
- if (Array.isArray(item)) return sanitizeArrayValue(item, depth + 1, userPatterns);
791
- return "[Object]";
792
- }
793
- function isSensitiveKey2(key, userPatterns) {
794
- if (matchesSensitiveKey(key, SENSITIVE_VARIABLE_PATTERNS)) return true;
795
- const lower = key.toLowerCase();
796
- return userPatterns.some((p) => lower.includes(p.toLowerCase()));
797
- }
798
- function isPrimitive(value) {
799
- return value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
800
- }
801
- function isPlainObject2(value) {
802
- if (value === null || typeof value !== "object") return false;
803
- const proto = Object.getPrototypeOf(value);
804
- return proto === Object.prototype || proto === null;
805
- }
806
- var SENSITIVE_VARIABLE_PATTERNS, SENSITIVE_WORD_PATTERNS, MAX_NESTING_DEPTH, MAX_ARRAY_DISPLAY_SIZE, FRAMEWORK_INTERNAL_KEYS;
807
- var init_sanitize = __esm({
808
- "src/http/sanitize.ts"() {
809
- SENSITIVE_VARIABLE_PATTERNS = Object.freeze([
810
- "password",
811
- "passwd",
812
- "pwd",
813
- "token",
814
- "access_token",
815
- "refresh_token",
816
- "api_token",
817
- "auth_token",
818
- "secret",
819
- "api_secret",
820
- "client_secret",
821
- "api_key",
822
- "apikey",
823
- "private_key",
824
- "privatekey",
825
- "public_key",
826
- "signing_key",
827
- "secret_key",
828
- "secretkey",
829
- "credential",
830
- "auth",
831
- "authorization",
832
- "encrypted",
833
- "encrypted_data",
834
- "ssn",
835
- "social_security",
836
- "credit_card",
837
- "card_number",
838
- "cvv",
839
- "cvc",
840
- // Crypto-material patterns — aligned with DB_SENSITIVE_PATTERNS
841
- // (PR #45). Request bodies can carry the same key material as DB
842
- // columns (a webhook POST containing a `signature` field, an HMAC
843
- // header echoed into a JSON body, a `pem`-encoded cert blob, etc).
844
- "pem",
845
- "cipher",
846
- "nonce",
847
- "salt",
848
- "digest",
849
- "signature",
850
- "hmac",
851
- // 0.2.0 additions (not yet in the Rails gem's list).
852
- "passcode",
853
- "cardnumber"
854
- ]);
855
- SENSITIVE_WORD_PATTERNS = Object.freeze([
856
- "pin",
857
- "otp",
858
- "totp",
859
- "iban",
860
- "mfa",
861
- "passphrase"
862
- ]);
863
- MAX_NESTING_DEPTH = 3;
864
- MAX_ARRAY_DISPLAY_SIZE = 5;
865
- FRAMEWORK_INTERNAL_KEYS = /* @__PURE__ */ new Set([
866
- // Rails leftovers — kept for parity since users may funnel through a
867
- // proxy that adds them, e.g. via a NextAuth credentials provider that
868
- // forwards CSRF tokens.
869
- "controller",
870
- "action",
871
- "format",
872
- "authenticity_token",
873
- "_method",
874
- // Next.js / common JS conventions
875
- "csrfToken",
876
- "_csrf",
877
- "_next"
878
- ]);
879
- }
880
- });
881
-
882
- // src/db/shared.ts
883
- function emitDbEvent(input) {
884
- try {
885
- const config = configuration();
886
- if (!config.captureDb) return;
887
- if (config.allExcludedTables().includes(input.modelClass)) return;
888
- if (config.databaseReader && !input._fromTrigger) {
889
- const tracked = config.triggerTrackedTables;
890
- if (tracked === null || tracked.has(input.modelClass)) return;
891
- }
892
- if (input.operation === "update") {
893
- const meaningful = input.changes ? filterMeaningfulChanges(input.changes) : [];
894
- if (meaningful.length === 0) return;
895
- }
896
- const resourceIdStr = input.resourceId === null || input.resourceId === void 0 ? null : String(input.resourceId);
897
- const context = buildContext(input);
898
- const event = build({
899
- source_type: "database_callback",
900
- source_data: {
901
- model_class: input.modelClass,
902
- operation: input.operation
903
- },
904
- outcome: "success",
905
- correlation_id: current(),
906
- resource_ids: resourceIdStr === null ? [] : [{ resource_type: input.modelClass, resource_id: resourceIdStr }],
907
- context,
908
- duration_ms: null,
909
- timestamp: input.timestamp ?? null
910
- });
911
- pushEvent(event);
912
- } catch (error) {
913
- logger.debug(`db emit failed: ${describeError5(error)}`);
914
- }
915
- }
916
- function buildContext(input) {
917
- const context = {};
918
- const actor = getCurrentActor();
919
- if (actor) context.actor = actor;
920
- if ((input.operation === "create" || input.operation === "destroy") && input.initialAttributes) {
921
- const filtered = filterMeaningfulAttributes(input.initialAttributes);
922
- if (filtered !== null) context.initial_attributes = filtered;
923
- }
924
- if (input.operation === "update" && input.changes) {
925
- const filtered = filterMeaningfulChanges(input.changes);
926
- if (filtered.length > 0) {
927
- context.changes = filtered.map((c) => {
928
- const out = {
929
- attribute: c.attribute,
930
- to: formatForJson(c.to)
931
- };
932
- if (c.from !== void 0) out.from = formatForJson(c.from);
933
- return out;
934
- });
935
- }
936
- }
937
- const displayName = input.displayName ?? (input.modelInstance ? resolveDisplayName(input.modelClass, input.modelInstance) : null);
938
- if (displayName !== null) context.display_name = displayName;
939
- return Object.keys(context).length === 0 ? null : context;
940
- }
941
- function filterMeaningfulAttributes(attrs) {
942
- const out = {};
943
- for (const key of Object.keys(attrs)) {
944
- if (!isMeaningfulAttribute(key)) continue;
945
- const value = attrs[key];
946
- if (value === null || value === void 0) continue;
947
- if (!isScalar(value)) continue;
948
- out[key] = formatForJson(value);
949
- }
950
- return Object.keys(out).length === 0 ? null : out;
951
- }
952
- function filterMeaningfulChanges(changes) {
953
- return changes.filter((c) => {
954
- if (!isMeaningfulAttribute(c.attribute)) return false;
955
- if (!isScalar(c.to)) return false;
956
- if (c.from === void 0) return true;
957
- if (!isScalar(c.from)) return false;
958
- return valuesActuallyChanged(c.from, c.to);
959
- });
960
- }
961
- function isMeaningfulAttribute(name) {
962
- if (IGNORED_ATTRIBUTES.includes(name)) return false;
963
- if (isDbSensitive(name)) return false;
964
- return true;
965
- }
966
- function isDbSensitive(name) {
967
- return matchesSensitiveKey(name, DB_SENSITIVE_PATTERNS);
968
- }
969
- function isScalar(value) {
970
- if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint" || value instanceof Date) {
971
- return true;
972
- }
973
- if (isPrismaDecimal(value)) return true;
974
- if (Buffer.isBuffer?.(value)) return false;
975
- if (Array.isArray(value)) return value.every((v) => isScalar(v));
976
- return false;
977
- }
978
- function valuesActuallyChanged(from, to) {
979
- if (from === null && to === null) return false;
980
- if (from instanceof Date && to instanceof Date) {
981
- return from.getTime() !== to.getTime();
982
- }
983
- return from !== to;
984
- }
985
- function formatForJson(value) {
986
- if (value === null || value === void 0) return value;
987
- if (value instanceof Date) return value.toISOString();
988
- if (typeof value === "bigint") return value.toString();
989
- if (isPrismaDecimal(value)) return Number(value.toString());
990
- if (Array.isArray(value)) return value.map(formatForJson);
991
- return value;
992
- }
993
- function isPrismaDecimal(value) {
994
- if (value === null || typeof value !== "object") return false;
995
- const obj = value;
996
- return typeof obj.toString === "function" && typeof obj.toFixed === "function" && "d" in obj && "e" in obj && "s" in obj;
997
- }
998
- function resolveDisplayName(modelClass, instance) {
999
- try {
1000
- const config = configuration();
1001
- const resolver = config.displayNameFor[modelClass];
1002
- const resolved = applyResolver(resolver, instance);
1003
- if (resolved !== null) return resolved;
1004
- for (const field of ["name", "title", "number"]) {
1005
- const value = instance[field];
1006
- if (value !== null && value !== void 0 && String(value).length > 0) {
1007
- return String(value);
1008
- }
1009
- }
1010
- } catch {
1011
- }
1012
- return null;
1013
- }
1014
- function applyResolver(resolver, instance) {
1015
- if (typeof resolver === "string") {
1016
- const value = instance[resolver];
1017
- if (value !== null && value !== void 0 && String(value).length > 0) {
1018
- return String(value);
1019
- }
1020
- return null;
1021
- }
1022
- if (typeof resolver === "function") {
1023
- try {
1024
- const value = resolver(instance);
1025
- if (typeof value === "string" && value.length > 0) return value;
1026
- if (value !== null && value !== void 0 && String(value).length > 0) {
1027
- return String(value);
1028
- }
1029
- } catch {
1030
- }
1031
- }
1032
- return null;
1033
- }
1034
- function describeError5(error) {
1035
- if (error instanceof Error) return `${error.name}: ${error.message}`;
1036
- return String(error);
1037
- }
1038
- var IGNORED_ATTRIBUTES, DB_SENSITIVE_PATTERNS;
1039
- var init_shared = __esm({
1040
- "src/db/shared.ts"() {
1041
- init_configuration();
1042
- init_logger();
1043
- init_event_builder();
1044
- init_buffer();
1045
- init_correlation();
1046
- init_actor();
1047
- init_sanitize();
1048
- IGNORED_ATTRIBUTES = Object.freeze([
1049
- "id",
1050
- "createdAt",
1051
- "created_at",
1052
- "updatedAt",
1053
- "updated_at",
1054
- "deletedAt",
1055
- "deleted_at",
1056
- // Auth.js / NextAuth standard columns
1057
- "emailVerified",
1058
- "expires"
1059
- ]);
1060
- DB_SENSITIVE_PATTERNS = Object.freeze([
1061
- "password",
1062
- "token",
1063
- "secret",
1064
- "api_key",
1065
- "credit_card",
1066
- "ssn",
1067
- "social_security",
1068
- "encrypted",
1069
- "private_key",
1070
- "public_key",
1071
- "signing_key",
1072
- "pem",
1073
- "cipher",
1074
- "nonce",
1075
- "salt",
1076
- "digest",
1077
- "signature",
1078
- "hmac",
1079
- // 0.2.0 additions. `credential` / `passwd` / `apikey` were already in
1080
- // the HTTP list; `passcode` / `card_number` / `cardnumber` / `cvv` /
1081
- // `cvc` are new. Whole-word `pin` / `otp` / `totp` / `iban` come from
1082
- // SENSITIVE_WORD_PATTERNS. The SQL trigger mirrors this list.
1083
- "credential",
1084
- "passwd",
1085
- "passcode",
1086
- "apikey",
1087
- "card_number",
1088
- "cardnumber",
1089
- "cvv",
1090
- "cvc"
1091
- ]);
1092
- }
1093
- });
1094
-
1095
- // src/db/supabase.ts
1096
- var supabase_exports = {};
1097
- __export(supabase_exports, {
1098
- tryExtractSupabaseActor: () => tryExtractSupabaseActor,
1099
- wrapSupabase: () => wrapSupabase
1100
- });
1101
- function triggerPathWillCapture(table) {
1102
- const config = configuration();
1103
- if (!config.databaseReader) return false;
1104
- const tracked = config.triggerTrackedTables;
1105
- if (tracked === null) return false;
1106
- return tracked.has(table);
1107
- }
1108
- function wrapSupabase(client) {
1109
- if (client === null || typeof client !== "object") return client;
1110
- const obj = client;
1111
- if (obj.__ezlogsWrapped) return client;
1112
- if (typeof obj.from !== "function") return client;
1113
- const originalFrom = obj.from.bind(obj);
1114
- const prereadRow = async (table, filters) => {
1115
- try {
1116
- const queryBuilder = originalFrom(table);
1117
- if (typeof queryBuilder.select !== "function") return null;
1118
- let chain = queryBuilder.select("*");
1119
- for (const f of filters) {
1120
- if (typeof chain.eq !== "function") return null;
1121
- chain = chain.eq(
1122
- f.column,
1123
- f.value
1124
- );
1125
- }
1126
- if (typeof chain.maybeSingle === "function") {
1127
- chain = chain.maybeSingle();
1128
- } else if (typeof chain.limit === "function") {
1129
- chain = chain.limit(
1130
- 1
1131
- );
1132
- }
1133
- const result = await chain;
1134
- if (!result || result.error) return null;
1135
- if (Array.isArray(result.data)) {
1136
- const first = result.data[0];
1137
- return isPlainObject4(first) ? first : null;
1138
- }
1139
- return isPlainObject4(result.data) ? result.data : null;
1140
- } catch {
1141
- return null;
1142
- }
1143
- };
1144
- obj.from = ((table) => {
1145
- const builder = originalFrom(table);
1146
- return wrapBuilder(builder, table, prereadRow);
1147
- });
1148
- Object.defineProperty(obj, "__ezlogsWrapped", {
1149
- value: true,
1150
- enumerable: false,
1151
- configurable: false
1152
- });
1153
- registerActorSource(obj);
1154
- return client;
1155
- }
1156
- function registerActorSource(client) {
1157
- try {
1158
- const g = globalThis;
1159
- g[GLOBAL_CLIENT_KEY] = client;
1160
- } catch {
1161
- }
1162
- }
1163
- async function tryExtractSupabaseActor() {
1164
- const g = globalThis;
1165
- const client = g[GLOBAL_CLIENT_KEY];
1166
- if (!client || typeof client.auth?.getUser !== "function") return null;
1167
- try {
1168
- const { data } = await client.auth.getUser();
1169
- const user = data?.user;
1170
- if (!user || typeof user.id !== "string" || !user.id) return null;
1171
- const label = user.user_metadata?.full_name ?? user.user_metadata?.name ?? user.email ?? void 0;
1172
- return label ? { id: user.id, label } : { id: user.id };
1173
- } catch {
1174
- return null;
1175
- }
1176
- }
1177
- function wrapBuilder(builder, table, preread) {
1178
- if (typeof builder.insert === "function") {
1179
- builder.insert = wrapMutation(
1180
- builder.insert.bind(builder),
1181
- { table, operation: "create" },
1182
- preread
1183
- );
1184
- }
1185
- if (typeof builder.upsert === "function") {
1186
- builder.upsert = wrapMutation(
1187
- builder.upsert.bind(builder),
1188
- { table, operation: "update" },
1189
- // supabase upsert is conceptually update-with-fallback
1190
- preread
1191
- );
1192
- }
1193
- if (typeof builder.update === "function") {
1194
- builder.update = wrapMutation(
1195
- builder.update.bind(builder),
1196
- { table, operation: "update" },
1197
- preread
1198
- );
1199
- }
1200
- if (typeof builder.delete === "function") {
1201
- builder.delete = wrapDeleteMutation(
1202
- builder.delete.bind(builder),
1203
- table,
1204
- preread
1205
- );
1206
- }
1207
- return builder;
1208
- }
1209
- function wrapMutation(original, ctx, preread) {
1210
- return (values, options) => {
1211
- const filterBuilder = original(values, options);
1212
- const filters = trackFilterChain(filterBuilder);
1213
- const beforeRowRef = { row: null };
1214
- return instrumentFilterBuilder(
1215
- filterBuilder,
1216
- (result) => emitFromMutation(ctx, values, result, filters, beforeRowRef.row),
1217
- async () => {
1218
- if (ctx.operation !== "update") return;
1219
- if (triggerPathWillCapture(ctx.table)) return;
1220
- const prereadFilters = prereadFiltersFromCaptured(filters);
1221
- if (prereadFilters !== null) {
1222
- beforeRowRef.row = await preread(ctx.table, prereadFilters);
1223
- }
1224
- }
1225
- );
1226
- };
1227
- }
1228
- function wrapDeleteMutation(original, table, preread) {
1229
- return (options) => {
1230
- const filterBuilder = original(options);
1231
- const filters = trackFilterChain(filterBuilder);
1232
- const beforeRowRef = { row: null };
1233
- return instrumentFilterBuilder(
1234
- filterBuilder,
1235
- (result) => emitFromDelete(table, result, filters, beforeRowRef.row),
1236
- async () => {
1237
- if (triggerPathWillCapture(table)) return;
1238
- const prereadFilters = prereadFiltersFromCaptured(filters);
1239
- if (prereadFilters !== null) {
1240
- beforeRowRef.row = await preread(table, prereadFilters);
1241
- }
1242
- }
1243
- );
1244
- };
1245
- }
1246
- function trackFilterChain(builder) {
1247
- const captured = { equals: {}, inLists: {} };
1248
- if (!builder || typeof builder !== "object") return captured;
1249
- const builderObj = builder;
1250
- const wrapEq = (orig) => {
1251
- if (typeof orig !== "function") return orig;
1252
- return function patchedEq(column, value) {
1253
- try {
1254
- if (typeof column === "string") captured.equals[column] = value;
1255
- } catch {
1256
- }
1257
- return orig.call(this, column, value);
1258
- };
1259
- };
1260
- const wrapIn = (orig) => {
1261
- if (typeof orig !== "function") return orig;
1262
- return function patchedIn(column, values) {
1263
- try {
1264
- if (typeof column === "string" && Array.isArray(values)) {
1265
- captured.inLists[column] = values;
1266
- }
1267
- } catch {
1268
- }
1269
- return orig.call(this, column, values);
1270
- };
1271
- };
1272
- const wrapMatch = (orig) => {
1273
- if (typeof orig !== "function") return orig;
1274
- return function patchedMatch(query) {
1275
- try {
1276
- if (isPlainObject4(query)) {
1277
- for (const [k, v] of Object.entries(query)) {
1278
- captured.equals[k] = v;
1279
- }
1280
- }
1281
- } catch {
1282
- }
1283
- return orig.call(this, query);
1284
- };
1285
- };
1286
- if ("eq" in builderObj) builderObj.eq = wrapEq(builderObj.eq);
1287
- if ("in" in builderObj) builderObj.in = wrapIn(builderObj.in);
1288
- if ("match" in builderObj) builderObj.match = wrapMatch(builderObj.match);
1289
- return captured;
1290
- }
1291
- function instrumentFilterBuilder(builder, onResolved, beforeFire) {
1292
- if (!builder || typeof builder !== "object") return builder;
1293
- const originalThen = builder.then?.bind(builder);
1294
- if (typeof originalThen !== "function") return builder;
1295
- const wrappedThen = function ezlogsThen(onfulfilled, onrejected) {
1296
- return new Promise((resolve, reject) => {
1297
- const proceed = () => {
1298
- originalThen(
1299
- (raw) => {
1300
- const result = raw;
1301
- try {
1302
- if (!result?.error) onResolved(result);
1303
- } catch (error) {
1304
- logger.debug(`supabase capture failed: ${describeError6(error)}`);
1305
- }
1306
- try {
1307
- const passthrough = onfulfilled ? onfulfilled(raw) : raw;
1308
- resolve(passthrough);
1309
- } catch (e) {
1310
- reject(e);
1311
- }
1312
- },
1313
- (reason) => {
1314
- try {
1315
- const passthrough = onrejected ? onrejected(reason) : Promise.reject(reason);
1316
- resolve(passthrough);
1317
- } catch (e) {
1318
- reject(e);
1319
- }
1320
- }
1321
- );
1322
- };
1323
- if (beforeFire) {
1324
- beforeFire().then(proceed, () => proceed());
1325
- } else {
1326
- proceed();
1327
- }
1328
- });
1329
- };
1330
- builder.then = wrappedThen;
1331
- return builder;
1332
- }
1333
- function emitFromMutation(ctx, values, result, filters, beforeRow) {
1334
- if (Array.isArray(values)) {
1335
- const resultRows = pickResultRows(result);
1336
- values.forEach((row, index) => {
1337
- if (!isPlainObject4(row)) return;
1338
- emitOneRow(ctx, row, resultRows[index] ?? null, filters, null);
1339
- });
1340
- return;
1341
- }
1342
- if (!isPlainObject4(values)) {
1343
- emitDbEvent({
1344
- modelClass: ctx.table,
1345
- operation: ctx.operation,
1346
- resourceId: idFromFilters(filters)
1347
- });
1348
- return;
1349
- }
1350
- const valueObj = values;
1351
- const resultRow = pickFirstResultRow(result);
1352
- emitOneRow(ctx, valueObj, resultRow, filters, beforeRow);
1353
- }
1354
- function emitOneRow(ctx, values, resultRow, filters, beforeRow) {
1355
- const resourceId = resultRow?.id ?? values.id ?? idFromFilters(filters) ?? null;
1356
- const merged = beforeRow ?? resultRow ?? values;
1357
- const displayName = resolveDisplayName(ctx.table, merged);
1358
- if (ctx.operation === "create") {
1359
- emitDbEvent({
1360
- modelClass: ctx.table,
1361
- operation: "create",
1362
- resourceId,
1363
- initialAttributes: values,
1364
- displayName,
1365
- modelInstance: merged
1366
- });
1367
- return;
1368
- }
1369
- if (ctx.operation === "update") {
1370
- const changes = buildUpdateChanges(values, beforeRow);
1371
- emitDbEvent({
1372
- modelClass: ctx.table,
1373
- operation: "update",
1374
- resourceId,
1375
- changes,
1376
- displayName,
1377
- modelInstance: merged
1378
- });
1379
- }
1380
- }
1381
- function emitFromDelete(table, result, filters, beforeRow) {
1382
- const resultRow = pickFirstResultRow(result);
1383
- const resourceId = resultRow?.id ?? beforeRow?.id ?? idFromFilters(filters) ?? null;
1384
- const richestRow = resultRow ?? beforeRow;
1385
- const displayName = richestRow ? resolveDisplayName(table, richestRow) : null;
1386
- emitDbEvent({
1387
- modelClass: table,
1388
- operation: "destroy",
1389
- resourceId,
1390
- displayName,
1391
- modelInstance: richestRow
1392
- });
1393
- }
1394
- function prereadFiltersFromCaptured(filters) {
1395
- const idValue = filters.equals["id"];
1396
- if (!isScalarFilterValue(idValue)) return null;
1397
- const out = [];
1398
- for (const column of Object.keys(filters.equals)) {
1399
- const value = filters.equals[column];
1400
- if (!isScalarFilterValue(value)) continue;
1401
- out.push({ column, value });
1402
- }
1403
- return out;
1404
- }
1405
- function idFromFilters(filters) {
1406
- const value = filters.equals["id"];
1407
- return isScalarFilterValue(value) ? value : null;
1408
- }
1409
- function isScalarFilterValue(value) {
1410
- return typeof value === "string" || typeof value === "number" || typeof value === "bigint";
1411
- }
1412
- function buildUpdateChanges(values, beforeRow) {
1413
- return Object.keys(values).map((attribute) => {
1414
- const change = {
1415
- attribute,
1416
- to: values[attribute]
1417
- };
1418
- if (beforeRow && Object.prototype.hasOwnProperty.call(beforeRow, attribute)) {
1419
- change.from = beforeRow[attribute];
1420
- }
1421
- return change;
1422
- });
1423
- }
1424
- function pickFirstResultRow(result) {
1425
- if (!result || result.error) return null;
1426
- if (Array.isArray(result.data)) {
1427
- const first = result.data[0];
1428
- return isPlainObject4(first) ? first : null;
1429
- }
1430
- if (isPlainObject4(result.data)) return result.data;
1431
- return null;
1432
- }
1433
- function pickResultRows(result) {
1434
- if (!result || result.error || !Array.isArray(result.data)) return [];
1435
- return result.data.map(
1436
- (row) => isPlainObject4(row) ? row : void 0
1437
- );
1438
- }
1439
- function isPlainObject4(value) {
1440
- if (value === null || typeof value !== "object") return false;
1441
- if (Array.isArray(value)) return false;
1442
- if (value instanceof Date) return false;
1443
- return true;
1444
- }
1445
- function describeError6(error) {
1446
- if (error instanceof Error) return `${error.name}: ${error.message}`;
1447
- return String(error);
1448
- }
1449
- var GLOBAL_CLIENT_KEY;
1450
- var init_supabase = __esm({
1451
- "src/db/supabase.ts"() {
1452
- init_logger();
1453
- init_configuration();
1454
- init_shared();
1455
- GLOBAL_CLIENT_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:supabase-current-client");
1456
- }
1457
- });
1458
-
1459
- // src/index.ts
1460
- init_configuration();
1461
- init_logger();
1462
- init_buffer();
1463
-
1464
- // src/pipeline/flush-scheduler.ts
1465
- init_configuration();
1466
- init_logger();
1467
- init_buffer();
1468
-
1469
- // src/pipeline/retry-sender.ts
1470
- init_configuration();
1471
- 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';
1472
7
 
1473
8
  // src/pipeline/transport.ts
1474
- init_configuration();
1475
- init_logger();
1476
9
  var REQUEST_TIMEOUT_MS = 1e4;
1477
10
  var transport = {
1478
11
  async send(events) {
@@ -1652,8 +185,6 @@ function describeError3(error) {
1652
185
  }
1653
186
 
1654
187
  // src/http/outgoing-fetch.ts
1655
- init_correlation();
1656
- init_logger();
1657
188
  var HEADER = "x-correlation-id";
1658
189
  var originalFetch = null;
1659
190
  var patched = false;
@@ -1704,561 +235,6 @@ function describeError4(error) {
1704
235
  return String(error);
1705
236
  }
1706
237
 
1707
- // src/triggers/patch-pg.ts
1708
- init_actor();
1709
- init_correlation();
1710
- init_logger();
1711
- var txState = /* @__PURE__ */ new WeakMap();
1712
- function patchPgClient(pgModule) {
1713
- if (!pgModule || !pgModule.Client || !pgModule.Client.prototype) {
1714
- logger.debug("patchPgClient: not a recognized pg module shape, skipping");
1715
- return;
1716
- }
1717
- const proto = pgModule.Client.prototype;
1718
- if (proto._ezlogsPatched) return;
1719
- const originalQuery = proto.query;
1720
- proto.query = function patchedQuery(config, values, callback) {
1721
- return runPatchedQuery(
1722
- this,
1723
- originalQuery,
1724
- config,
1725
- values,
1726
- callback
1727
- );
1728
- };
1729
- proto._ezlogsPatched = true;
1730
- }
1731
- function runPatchedQuery(client, original, config, values, callback) {
1732
- const state2 = ensureState(client);
1733
- const text = extractQueryText(config);
1734
- const verb = leadingVerb(text);
1735
- if (verb === "BEGIN" || verb === "START") {
1736
- state2.inTx = true;
1737
- state2.injected = false;
1738
- return original.call(client, config, values, callback);
1739
- }
1740
- if (verb === "COMMIT" || verb === "ROLLBACK" || verb === "END") {
1741
- const result = original.call(client, config, values, callback);
1742
- state2.inTx = false;
1743
- state2.injected = false;
1744
- return result;
1745
- }
1746
- if (state2.inTx) {
1747
- if (state2.injected) {
1748
- return original.call(client, config, values, callback);
1749
- }
1750
- const ctx2 = snapshotContext();
1751
- if (!ctx2.actorId && !ctx2.correlationId) {
1752
- state2.injected = true;
1753
- return original.call(client, config, values, callback);
1754
- }
1755
- state2.injected = true;
1756
- return injectAndRun(client, original, config, values, callback, ctx2);
1757
- }
1758
- const ctx = snapshotContext();
1759
- if (!ctx.actorId && !ctx.correlationId) {
1760
- return original.call(client, config, values, callback);
1761
- }
1762
- return wrapInTx(client, original, config, values, callback, ctx);
1763
- }
1764
- function snapshotContext() {
1765
- const actor = getCurrentActor();
1766
- return {
1767
- actorId: actor && actor.id ? actor.id : null,
1768
- correlationId: current()
1769
- };
1770
- }
1771
- async function injectAndRun(client, original, config, values, callback, ctx) {
1772
- if (ctx.actorId) {
1773
- await safeSet(client, original, {
1774
- text: "SELECT set_config('ezlogs.actor_id', $1, true)",
1775
- values: [ctx.actorId]
1776
- });
1777
- }
1778
- if (ctx.correlationId) {
1779
- await safeSet(client, original, {
1780
- text: "SELECT set_config('ezlogs.correlation_id', $1, true)",
1781
- values: [ctx.correlationId]
1782
- });
1783
- }
1784
- return original.call(client, config, values, callback);
1785
- }
1786
- async function safeSet(client, original, cfg) {
1787
- try {
1788
- const result = original.call(client, cfg);
1789
- if (result && typeof result.then === "function") {
1790
- await result;
1791
- }
1792
- } catch (err) {
1793
- logger.debug(
1794
- `patchPgClient: SET LOCAL failed (continuing): ${err instanceof Error ? err.message : String(err)}`
1795
- );
1796
- }
1797
- }
1798
- function wrapInTx(client, original, config, values, callback, ctx) {
1799
- const state2 = ensureState(client);
1800
- let userCb = null;
1801
- let realValues = values;
1802
- if (typeof callback === "function") {
1803
- userCb = callback;
1804
- } else if (typeof values === "function") {
1805
- userCb = values;
1806
- realValues = void 0;
1807
- }
1808
- const begin = original.call(client, "BEGIN");
1809
- if (!begin || typeof begin.then !== "function") {
1810
- return original.call(client, config, values, callback);
1811
- }
1812
- const wrapped = begin.then(async () => {
1813
- state2.inTx = true;
1814
- state2.injected = true;
1815
- if (ctx.actorId) {
1816
- await original.call(client, {
1817
- text: "SELECT set_config('ezlogs.actor_id', $1, true)",
1818
- values: [ctx.actorId]
1819
- });
1820
- }
1821
- if (ctx.correlationId) {
1822
- await original.call(client, {
1823
- text: "SELECT set_config('ezlogs.correlation_id', $1, true)",
1824
- values: [ctx.correlationId]
1825
- });
1826
- }
1827
- }).then(
1828
- () => (
1829
- // Run the user's actual query in promise mode — DO NOT forward
1830
- // the caller's callback. See comment above.
1831
- original.call(client, config, realValues)
1832
- )
1833
- ).then(
1834
- async (result) => {
1835
- await original.call(client, "COMMIT");
1836
- state2.inTx = false;
1837
- state2.injected = false;
1838
- return result;
1839
- },
1840
- async (err) => {
1841
- try {
1842
- await original.call(client, "ROLLBACK");
1843
- } catch {
1844
- }
1845
- state2.inTx = false;
1846
- state2.injected = false;
1847
- throw err;
1848
- }
1849
- );
1850
- if (userCb) {
1851
- wrapped.then(
1852
- (result) => userCb(null, result),
1853
- (err) => userCb(err instanceof Error ? err : new Error(String(err)))
1854
- );
1855
- return void 0;
1856
- }
1857
- return wrapped;
1858
- }
1859
- function ensureState(client) {
1860
- let s = txState.get(client);
1861
- if (!s) {
1862
- s = { inTx: false, injected: false };
1863
- txState.set(client, s);
1864
- }
1865
- return s;
1866
- }
1867
- function extractQueryText(config) {
1868
- if (typeof config === "string") return config;
1869
- if (config && typeof config === "object" && typeof config.text === "string") {
1870
- return config.text;
1871
- }
1872
- return "";
1873
- }
1874
- function leadingVerb(text) {
1875
- let s = text;
1876
- while (true) {
1877
- const before = s.length;
1878
- s = s.replace(/^\s+/, "");
1879
- s = s.replace(/^--[^\n]*\n?/, "");
1880
- if (s.length === before) break;
1881
- }
1882
- const m = /^[A-Za-z]+/.exec(s);
1883
- return m ? m[0].toUpperCase() : "";
1884
- }
1885
-
1886
- // src/triggers/reader.ts
1887
- init_logger();
1888
- init_shared();
1889
- init_correlation();
1890
- init_actor();
1891
-
1892
- // src/triggers/emit-dedup.ts
1893
- init_edge_fallback();
1894
- var storage3 = createScopedStorage(
1895
- /* @__PURE__ */ Symbol.for("ezlogs-nextjs:audit-emitted-ids-storage")
1896
- );
1897
- function currentEmittedAuditIds() {
1898
- return storage3.read();
1899
- }
1900
- function runWithEmittedAuditIdsScope(callback) {
1901
- const existing = storage3.read();
1902
- if (existing !== null) return callback();
1903
- return storage3.run(/* @__PURE__ */ new Set(), callback);
1904
- }
1905
-
1906
- // src/triggers/reader.ts
1907
- var COLUMNS = "id, table_name, op, old_row, new_row, resource_id, correlation_id, txid, captured_at";
1908
- var ORPHAN_AGE = "5 minutes";
1909
- var PRUNE_AGE = "24 hours";
1910
- var SWEEP_BATCH = 100;
1911
- var PRUNE_BATCH = 2e3;
1912
- var SWEEP_INTERVAL_MS = 1e4;
1913
- var PRUNE_INTERVAL_MS = 10 * 6e4;
1914
- var lastSweepAt = 0;
1915
- var lastPruneAt = 0;
1916
- var deleteDenied = false;
1917
- var txCorrelation = /* @__PURE__ */ new Map();
1918
- async function readAuditRows(exec, correlationId) {
1919
- try {
1920
- if (!deleteDenied) {
1921
- try {
1922
- return sortById(
1923
- extractRows(
1924
- await exec(
1925
- `DELETE FROM ezlogs_audit_log WHERE correlation_id = $1 RETURNING ${COLUMNS}`,
1926
- [correlationId]
1927
- )
1928
- ).map(normalizeAuditRow)
1929
- );
1930
- } catch (err) {
1931
- if (!isPermissionDenied(err)) throw err;
1932
- deleteDenied = true;
1933
- logger.warn(
1934
- "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'`."
1935
- );
1936
- }
1937
- }
1938
- const result = await exec(
1939
- `SELECT ${COLUMNS} FROM ezlogs_audit_log WHERE correlation_id = $1 ORDER BY id ASC`,
1940
- [correlationId]
1941
- );
1942
- return extractRows(result).map(normalizeAuditRow);
1943
- } catch (err) {
1944
- logger.debug(
1945
- `readAuditRows failed: ${err instanceof Error ? err.message : String(err)}`
1946
- );
1947
- return [];
1948
- }
1949
- }
1950
- async function sweepAuditLog(exec) {
1951
- if (deleteDenied) return 0;
1952
- try {
1953
- const rows = sortById(
1954
- extractRows(
1955
- await exec(
1956
- `DELETE FROM ezlogs_audit_log
1957
- WHERE id IN (
1958
- SELECT id FROM ezlogs_audit_log
1959
- WHERE (correlation_id IS NULL
1960
- OR captured_at < now() - interval '${ORPHAN_AGE}')
1961
- -- Never resurface history: past the retention cap a
1962
- -- row is pruned, not sent as new activity.
1963
- AND captured_at > now() - interval '${PRUNE_AGE}'
1964
- ORDER BY id
1965
- LIMIT ${SWEEP_BATCH}
1966
- FOR UPDATE SKIP LOCKED)
1967
- RETURNING ${COLUMNS}`,
1968
- []
1969
- )
1970
- ).map(normalizeAuditRow)
1971
- );
1972
- for (const row of rows) {
1973
- const correlationId = row.correlation_id ?? correlationForTx(row.txid);
1974
- runWithCorrelation(
1975
- correlationId,
1976
- () => runWithActorScope(() => emitOne(row))
1977
- );
1978
- }
1979
- return rows.length;
1980
- } catch (err) {
1981
- logger.debug(
1982
- `sweepAuditLog failed: ${err instanceof Error ? err.message : String(err)}`
1983
- );
1984
- return 0;
1985
- }
1986
- }
1987
- async function pruneAuditLog(exec) {
1988
- if (deleteDenied) return;
1989
- try {
1990
- await exec(
1991
- `DELETE FROM ezlogs_audit_log
1992
- WHERE id IN (
1993
- SELECT id FROM ezlogs_audit_log
1994
- WHERE captured_at < now() - interval '${PRUNE_AGE}'
1995
- LIMIT ${PRUNE_BATCH})`,
1996
- []
1997
- );
1998
- } catch (err) {
1999
- logger.debug(
2000
- `pruneAuditLog failed: ${err instanceof Error ? err.message : String(err)}`
2001
- );
2002
- }
2003
- }
2004
- async function auditLogInstalled(exec) {
2005
- try {
2006
- const rows = extractRows(
2007
- await exec(
2008
- `SELECT to_regclass('public.ezlogs_audit_log') IS NOT NULL AS installed`,
2009
- []
2010
- )
2011
- );
2012
- const installed = rows[0]?.installed;
2013
- return typeof installed === "boolean" ? installed : null;
2014
- } catch {
2015
- return null;
2016
- }
2017
- }
2018
- async function checkAuditLogAccess(exec) {
2019
- try {
2020
- const rows = extractRows(
2021
- await exec(
2022
- `SELECT current_user AS role
2023
- FROM pg_class c
2024
- JOIN pg_roles r ON r.rolname = current_user
2025
- WHERE c.oid = 'public.ezlogs_audit_log'::regclass
2026
- AND c.relrowsecurity
2027
- AND NOT r.rolsuper
2028
- AND NOT r.rolbypassrls
2029
- AND NOT pg_has_role(current_user, c.relowner, 'MEMBER')
2030
- AND NOT EXISTS (SELECT 1 FROM pg_policies p
2031
- WHERE p.schemaname = 'public'
2032
- AND p.tablename = 'ezlogs_audit_log')`,
2033
- []
2034
- )
2035
- );
2036
- const role = rows[0]?.role;
2037
- if (typeof role !== "string") return false;
2038
- logger.warn(
2039
- `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);`
2040
- );
2041
- return true;
2042
- } catch {
2043
- return false;
2044
- }
2045
- }
2046
- async function detectTriggerTrackedTables(exec) {
2047
- try {
2048
- const result = await exec(
2049
- `SELECT event_object_table AS table_name
2050
- FROM information_schema.triggers
2051
- WHERE trigger_name = 'ezlogs_audit'
2052
- AND trigger_schema = 'public'`,
2053
- []
2054
- );
2055
- const rows = extractRows(result);
2056
- const tables = /* @__PURE__ */ new Set();
2057
- for (const row of rows) {
2058
- const r = row ?? {};
2059
- if (typeof r.table_name === "string" && r.table_name.length > 0) {
2060
- tables.add(r.table_name);
2061
- }
2062
- }
2063
- return tables;
2064
- } catch (err) {
2065
- logger.debug(
2066
- `detectTriggerTrackedTables failed: ${err instanceof Error ? err.message : String(err)}`
2067
- );
2068
- return null;
2069
- }
2070
- }
2071
- function emitAuditRows(rows) {
2072
- for (const row of rows) {
2073
- emitOne(row);
2074
- }
2075
- }
2076
- async function flushAuditLog(exec) {
2077
- if (!exec) return;
2078
- const correlationId = current();
2079
- if (!correlationId) return;
2080
- const rows = await readAuditRows(exec, correlationId);
2081
- emitFresh(rows);
2082
- const now = Date.now();
2083
- if (now - lastPruneAt >= PRUNE_INTERVAL_MS) {
2084
- lastPruneAt = now;
2085
- await pruneAuditLog(exec);
2086
- }
2087
- if (now - lastSweepAt >= SWEEP_INTERVAL_MS) {
2088
- lastSweepAt = now;
2089
- await sweepAuditLog(exec);
2090
- }
2091
- }
2092
- function emitFresh(rows) {
2093
- if (rows.length === 0) return;
2094
- const emitted = currentEmittedAuditIds();
2095
- if (emitted === null) {
2096
- emitAuditRows(rows);
2097
- return;
2098
- }
2099
- const fresh = [];
2100
- for (const row of rows) {
2101
- if (row.id === "" || emitted.has(row.id)) continue;
2102
- emitted.add(row.id);
2103
- fresh.push(row);
2104
- }
2105
- emitAuditRows(fresh);
2106
- }
2107
- function correlationForTx(txid) {
2108
- if (!txid) return generate();
2109
- let id = txCorrelation.get(txid);
2110
- if (!id) {
2111
- if (txCorrelation.size >= 1e3) txCorrelation.clear();
2112
- id = generate();
2113
- txCorrelation.set(txid, id);
2114
- }
2115
- return id;
2116
- }
2117
- function isPermissionDenied(err) {
2118
- return err?.code === "42501";
2119
- }
2120
- function sortById(rows) {
2121
- return rows.sort(
2122
- (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
2123
- );
2124
- }
2125
- function emitOne(row) {
2126
- const op = mapOp(row.op);
2127
- if (!op) return;
2128
- const oldRow = coerceJsonb(row.old_row);
2129
- const newRow = coerceJsonb(row.new_row);
2130
- if (op === "create" && newRow) {
2131
- emitDbEvent({
2132
- modelClass: row.table_name,
2133
- operation: "create",
2134
- resourceId: row.resource_id,
2135
- initialAttributes: newRow,
2136
- modelInstance: newRow,
2137
- displayName: null,
2138
- timestamp: row.captured_at ?? null,
2139
- _fromTrigger: true
2140
- });
2141
- return;
2142
- }
2143
- if (op === "update" && oldRow && newRow) {
2144
- const changes = computeChanges(oldRow, newRow);
2145
- if (changes.length === 0) {
2146
- return;
2147
- }
2148
- emitDbEvent({
2149
- modelClass: row.table_name,
2150
- operation: "update",
2151
- resourceId: row.resource_id,
2152
- changes,
2153
- // Prefer the post-state for the display name — that's what the
2154
- // user just told the system to call this row.
2155
- modelInstance: newRow,
2156
- displayName: null,
2157
- timestamp: row.captured_at ?? null,
2158
- _fromTrigger: true
2159
- });
2160
- return;
2161
- }
2162
- if (op === "destroy" && oldRow) {
2163
- emitDbEvent({
2164
- modelClass: row.table_name,
2165
- operation: "destroy",
2166
- resourceId: row.resource_id,
2167
- initialAttributes: oldRow,
2168
- modelInstance: oldRow,
2169
- displayName: null,
2170
- timestamp: row.captured_at ?? null,
2171
- _fromTrigger: true
2172
- });
2173
- return;
2174
- }
2175
- }
2176
- function mapOp(op) {
2177
- if (op === "INSERT") return "create";
2178
- if (op === "UPDATE") return "update";
2179
- if (op === "DELETE") return "destroy";
2180
- return null;
2181
- }
2182
- function computeChanges(oldRow, newRow) {
2183
- const out = [];
2184
- for (const key of Object.keys(newRow)) {
2185
- const before = oldRow[key];
2186
- const after = newRow[key];
2187
- if (deepEqual(before, after)) continue;
2188
- out.push({ attribute: key, from: before, to: after });
2189
- }
2190
- return out;
2191
- }
2192
- function deepEqual(a, b) {
2193
- if (a === b) return true;
2194
- if (a === null || b === null) return false;
2195
- if (typeof a !== typeof b) return false;
2196
- if (typeof a !== "object") return false;
2197
- try {
2198
- return stableStringify(a) === stableStringify(b);
2199
- } catch {
2200
- return false;
2201
- }
2202
- }
2203
- function stableStringify(value) {
2204
- if (value === null || typeof value !== "object") return JSON.stringify(value);
2205
- if (Array.isArray(value)) {
2206
- return "[" + value.map((v) => stableStringify(v)).join(",") + "]";
2207
- }
2208
- const entries = Object.keys(value).sort().map((k) => JSON.stringify(k) + ":" + stableStringify(value[k]));
2209
- return "{" + entries.join(",") + "}";
2210
- }
2211
- function extractRows(result) {
2212
- if (!result) return [];
2213
- if (Array.isArray(result)) return result;
2214
- if (typeof result === "object" && Array.isArray(result.rows)) {
2215
- return result.rows;
2216
- }
2217
- return [];
2218
- }
2219
- function toDate(value) {
2220
- if (value == null) return null;
2221
- const d = value instanceof Date ? value : new Date(String(value));
2222
- return Number.isNaN(d.getTime()) ? null : d;
2223
- }
2224
- function normalizeAuditRow(raw) {
2225
- const r = raw ?? {};
2226
- return {
2227
- id: r.id == null ? "" : String(r.id),
2228
- table_name: String(r.table_name ?? ""),
2229
- op: r.op,
2230
- old_row: r.old_row ?? null,
2231
- new_row: r.new_row ?? null,
2232
- resource_id: r.resource_id == null ? null : String(r.resource_id),
2233
- correlation_id: r.correlation_id == null ? null : String(r.correlation_id),
2234
- txid: r.txid == null ? null : String(r.txid),
2235
- captured_at: toDate(r.captured_at)
2236
- };
2237
- }
2238
- function coerceJsonb(value) {
2239
- if (value === null || value === void 0) return null;
2240
- if (typeof value === "string") {
2241
- try {
2242
- const parsed = JSON.parse(value);
2243
- return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
2244
- } catch {
2245
- return null;
2246
- }
2247
- }
2248
- if (typeof value === "object" && !Array.isArray(value)) return value;
2249
- return null;
2250
- }
2251
-
2252
- // src/index.ts
2253
- init_logger();
2254
- init_event_builder();
2255
-
2256
- // src/http/capture.ts
2257
- init_configuration();
2258
- init_logger();
2259
- init_event_builder();
2260
- init_buffer();
2261
-
2262
238
  // src/pipeline/serverless.ts
2263
239
  var cachedFlag = null;
2264
240
  function isServerless() {
@@ -2278,9 +254,6 @@ function detect() {
2278
254
  return false;
2279
255
  }
2280
256
 
2281
- // src/http/capture.ts
2282
- init_actor();
2283
-
2284
257
  // src/user-agent-detector.ts
2285
258
  var PATTERNS = [
2286
259
  { prefix: "claude-", vendor: "claude", label: "Claude" },
@@ -2304,9 +277,6 @@ function classifyUserAgent(userAgent) {
2304
277
  };
2305
278
  }
2306
279
 
2307
- // src/http/capture.ts
2308
- init_correlation();
2309
-
2310
280
  // src/http/path-matcher.ts
2311
281
  function pathMatches(path, pattern) {
2312
282
  const startsWithStar = pattern.startsWith("*");
@@ -2330,11 +300,7 @@ function hasExcludedExtension(path, extensions) {
2330
300
  return extensions.some((ext) => path.endsWith(ext));
2331
301
  }
2332
302
 
2333
- // src/http/capture.ts
2334
- init_configuration();
2335
-
2336
303
  // src/http/source-data.ts
2337
- init_sanitize();
2338
304
  function buildHttpSourceData(input) {
2339
305
  const { controller, action } = resolveControllerAction(input);
2340
306
  const source = {
@@ -2491,7 +457,7 @@ function compact(obj) {
2491
457
  }
2492
458
  return out;
2493
459
  }
2494
- function determineOutcome(statusCode, exception, graphqlResponseErrors) {
460
+ function determineOutcome(statusCode, exception, graphqlResponseErrors, responseError = null) {
2495
461
  if (exception) {
2496
462
  return {
2497
463
  outcome: "failure",
@@ -2499,7 +465,7 @@ function determineOutcome(statusCode, exception, graphqlResponseErrors) {
2499
465
  };
2500
466
  }
2501
467
  if (statusCode !== null && statusCode >= 400) {
2502
- return { outcome: "failure", error_message: `HTTP ${statusCode}` };
468
+ return { outcome: "failure", error_message: responseError ?? `HTTP ${statusCode}` };
2503
469
  }
2504
470
  if (graphqlResponseErrors) {
2505
471
  return { outcome: "failure", error_message: graphqlResponseErrors };
@@ -2508,14 +474,13 @@ function determineOutcome(statusCode, exception, graphqlResponseErrors) {
2508
474
  }
2509
475
 
2510
476
  // src/http/graphql.ts
2511
- init_sanitize();
2512
477
  var QUERY_PREFIXES = ["Get", "Fetch", "List", "Find", "Load", "Search", "Query"];
2513
478
  var MUTATION_PREFIXES = ["Create", "Update", "Delete", "Remove", "Add", "Set", "Upsert"];
2514
479
  function isGraphqlPath(path) {
2515
480
  return path === "/graphql" || path.startsWith("/graphql/");
2516
481
  }
2517
482
  function parseGraphqlBody(body, excludedOperations, excludedVariableKeys) {
2518
- if (!isPlainObject3(body)) return { metadata: null };
483
+ if (!isPlainObject(body)) return { metadata: null };
2519
484
  const obj = body;
2520
485
  const queryString = typeof obj.query === "string" ? obj.query : null;
2521
486
  let operationName = typeof obj.operationName === "string" ? obj.operationName : null;
@@ -2562,14 +527,14 @@ function isExcludedOperation(name, patterns) {
2562
527
  });
2563
528
  }
2564
529
  function extractGraphqlErrorsFromBody(parsed) {
2565
- if (!isPlainObject3(parsed)) return null;
530
+ if (!isPlainObject(parsed)) return null;
2566
531
  const errors = parsed.errors;
2567
532
  if (!Array.isArray(errors) || errors.length === 0) return null;
2568
- 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);
2569
534
  if (messages.length === 0) return null;
2570
535
  return messages.length === 1 ? messages[0] : messages.join("; ");
2571
536
  }
2572
- function isPlainObject3(value) {
537
+ function isPlainObject(value) {
2573
538
  if (value === null || typeof value !== "object") return false;
2574
539
  const proto = Object.getPrototypeOf(value);
2575
540
  return proto === Object.prototype || proto === null;
@@ -2593,6 +558,7 @@ function captureRoute(handler, context = {}) {
2593
558
  }
2594
559
  const snapshot = await snapshotRequest(request);
2595
560
  if (snapshot === null) return Promise.resolve(runHandler(...args));
561
+ snapshot.rawParams = mergeRouteParams(snapshot.rawParams, await readRouteParams(args[1]));
2596
562
  const correlationId = resolveCorrelation(request.headers ?? null);
2597
563
  return await runWithCorrelation(
2598
564
  correlationId,
@@ -2603,15 +569,23 @@ function captureRoute(handler, context = {}) {
2603
569
  let response = null;
2604
570
  let exception = null;
2605
571
  let graphqlErrorMessage = null;
572
+ let responseErrorMessage = null;
2606
573
  try {
2607
574
  response = await Promise.resolve(runHandler(...args));
2608
575
  statusCode = response.status;
2609
576
  if (snapshot.graphqlBody !== null && response.status === 200) {
2610
577
  graphqlErrorMessage = await readGraphqlErrors(response);
2611
578
  }
579
+ responseErrorMessage = await readResponseErrorMessage(response);
2612
580
  return response;
2613
581
  } catch (e) {
582
+ const controlStatus = nextControlFlowStatus(e);
583
+ if (controlStatus !== null) {
584
+ statusCode = controlStatus;
585
+ throw e;
586
+ }
2614
587
  exception = e instanceof Error ? e : new Error(String(e));
588
+ statusCode = 500;
2615
589
  throw e;
2616
590
  } finally {
2617
591
  await maybeExtractSupabaseActor();
@@ -2621,6 +595,7 @@ function captureRoute(handler, context = {}) {
2621
595
  statusCode,
2622
596
  exception,
2623
597
  graphqlErrorMessage,
598
+ responseErrorMessage,
2624
599
  durationMs: Date.now() - startMs,
2625
600
  startedAt: new Date(startMs)
2626
601
  });
@@ -2634,13 +609,13 @@ function captureRoute(handler, context = {}) {
2634
609
  } catch (preCaptureError) {
2635
610
  if (handlerInvoked) throw preCaptureError;
2636
611
  logger.warn(
2637
- `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`
2638
613
  );
2639
614
  return Promise.resolve(handler(...args));
2640
615
  }
2641
616
  };
2642
617
  }
2643
- var CORRELATION_HEADER2 = "x-ezlogs-correlation-id";
618
+ var CORRELATION_HEADER = "x-ezlogs-correlation-id";
2644
619
  function withMiddlewareCapture(middleware) {
2645
620
  return async (request, ...rest) => {
2646
621
  let middlewareInvoked = false;
@@ -2651,7 +626,7 @@ function withMiddlewareCapture(middleware) {
2651
626
  try {
2652
627
  const correlationId = resolveCorrelation(request.headers);
2653
628
  try {
2654
- request.headers.set(CORRELATION_HEADER2, correlationId);
629
+ request.headers.set(CORRELATION_HEADER, correlationId);
2655
630
  } catch {
2656
631
  }
2657
632
  return await runWithCorrelation(
@@ -2662,7 +637,7 @@ function withMiddlewareCapture(middleware) {
2662
637
  const response = await Promise.resolve(runMiddleware(request, ...rest));
2663
638
  try {
2664
639
  if (response?.headers && typeof response.headers.set === "function") {
2665
- response.headers.set(CORRELATION_HEADER2, correlationId);
640
+ response.headers.set(CORRELATION_HEADER, correlationId);
2666
641
  }
2667
642
  } catch {
2668
643
  }
@@ -2678,7 +653,7 @@ function withMiddlewareCapture(middleware) {
2678
653
  });
2679
654
  }
2680
655
  } catch (error) {
2681
- logger.debug(`page navigation capture failed: ${describeError7(error)}`);
656
+ logger.debug(`page navigation capture failed: ${describeError5(error)}`);
2682
657
  }
2683
658
  return response;
2684
659
  })
@@ -2686,7 +661,7 @@ function withMiddlewareCapture(middleware) {
2686
661
  } catch (preCaptureError) {
2687
662
  if (middlewareInvoked) throw preCaptureError;
2688
663
  logger.warn(
2689
- `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`
2690
665
  );
2691
666
  return await Promise.resolve(middleware(request, ...rest));
2692
667
  }
@@ -2746,7 +721,7 @@ async function emitPageNavigationEvent(input) {
2746
721
  });
2747
722
  pushEvent(event);
2748
723
  } catch (error) {
2749
- logger.error(`page navigation emit failed: ${describeError7(error)}`);
724
+ logger.error(`page navigation emit failed: ${describeError5(error)}`);
2750
725
  }
2751
726
  }
2752
727
  function pageControllerFromPath(pathname) {
@@ -2812,7 +787,7 @@ function capturePagesApi(handler, context = {}) {
2812
787
  } catch (preCaptureError) {
2813
788
  if (handlerInvoked) throw preCaptureError;
2814
789
  logger.warn(
2815
- `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`
2816
791
  );
2817
792
  return Promise.resolve(handler(...args));
2818
793
  }
@@ -2844,7 +819,10 @@ function captureServerAction(action, actionName) {
2844
819
  const failure = classifyServerActionResult(result);
2845
820
  await emitServerActionEvent({
2846
821
  actionName,
2847
- statusCode: failure ? 500 : 200,
822
+ // A returned failure (`{ success: false, error }`) is a
823
+ // handled refusal, not a crash: no HTTP status is
824
+ // invented; outcome + error_message carry it.
825
+ statusCode: failure ? null : 200,
2848
826
  exception: failure ? new Error(failure.errorMessage) : null,
2849
827
  durationMs: Date.now() - startMs,
2850
828
  startedAt,
@@ -2854,9 +832,12 @@ function captureServerAction(action, actionName) {
2854
832
  } catch (e) {
2855
833
  if (isNextControlFlowError(e)) {
2856
834
  await maybeExtractSupabaseActor();
835
+ const controlStatus = nextControlFlowStatus(e) ?? 200;
2857
836
  await emitServerActionEvent({
2858
837
  actionName,
2859
- statusCode: 200,
838
+ // redirect() is a success; notFound() / forbidden()
839
+ // keep their 4xx.
840
+ statusCode: controlStatus >= 400 ? controlStatus : 200,
2860
841
  exception: null,
2861
842
  durationMs: Date.now() - startMs,
2862
843
  startedAt,
@@ -2885,7 +866,7 @@ function captureServerAction(action, actionName) {
2885
866
  } catch (preCaptureError) {
2886
867
  if (actionInvoked) throw preCaptureError;
2887
868
  logger.warn(
2888
- `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`
2889
870
  );
2890
871
  return Promise.resolve(action(...args));
2891
872
  }
@@ -2917,7 +898,7 @@ function classifyServerActionResult(result) {
2917
898
  return verdict;
2918
899
  }
2919
900
  } catch (error) {
2920
- logger.debug(`isServerActionError classifier threw: ${describeError7(error)}`);
901
+ logger.debug(`isServerActionError classifier threw: ${describeError5(error)}`);
2921
902
  }
2922
903
  }
2923
904
  if (Array.isArray(result) && result.length === 2 && result[0] === null && isZsaError(result[1])) {
@@ -3038,10 +1019,23 @@ function conformErrorMessage(result) {
3038
1019
  return "Form submission failed";
3039
1020
  }
3040
1021
  function isNextControlFlowError(error) {
3041
- if (!error || typeof error !== "object") return false;
1022
+ return nextControlFlowStatus(error) !== null;
1023
+ }
1024
+ function nextControlFlowStatus(error) {
1025
+ if (!error || typeof error !== "object") return null;
3042
1026
  const digest = error.digest;
3043
- if (typeof digest !== "string") return false;
3044
- return digest.startsWith("NEXT_REDIRECT") || digest.startsWith("NEXT_NOT_FOUND");
1027
+ if (typeof digest !== "string") return null;
1028
+ const parts = digest.split(";");
1029
+ if (parts[0] === "NEXT_REDIRECT") {
1030
+ const status = Number(parts[3]);
1031
+ return status >= 300 && status < 400 ? status : 307;
1032
+ }
1033
+ if (parts[0] === "NEXT_NOT_FOUND") return 404;
1034
+ if (parts[0] === "NEXT_HTTP_ERROR_FALLBACK") {
1035
+ const status = Number(parts[1]);
1036
+ return status >= 400 && status < 500 ? status : 404;
1037
+ }
1038
+ return null;
3045
1039
  }
3046
1040
  async function emitServerActionEvent(input) {
3047
1041
  try {
@@ -3063,7 +1057,7 @@ async function emitServerActionEvent(input) {
3063
1057
  rawParams: requestParams,
3064
1058
  serverActionName: input.actionName,
3065
1059
  userAgent,
3066
- remoteIp: null,
1060
+ remoteIp: extractRemoteIp(await readNextHeadersAsAdapter()),
3067
1061
  contentType: null,
3068
1062
  excludedVariableKeys: configuration().excludedGraphqlVariableKeys
3069
1063
  });
@@ -3085,7 +1079,7 @@ async function emitServerActionEvent(input) {
3085
1079
  });
3086
1080
  pushEvent(event);
3087
1081
  } catch (error) {
3088
- logger.error(`server-action capture emit failed: ${describeError7(error)}`);
1082
+ logger.error(`server-action capture emit failed: ${describeError5(error)}`);
3089
1083
  }
3090
1084
  }
3091
1085
  function extractServerActionArgs(args, actionName) {
@@ -3165,18 +1159,6 @@ var PAYMENT_ACTION_WORDS = /* @__PURE__ */ new Set([
3165
1159
  function actionWords(name) {
3166
1160
  return name.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/([a-zA-Z])(\d)/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
3167
1161
  }
3168
- function passesLuhn(digits) {
3169
- let sum = 0;
3170
- for (let i = 0; i < digits.length; i += 1) {
3171
- let d = Number(digits[digits.length - 1 - i]);
3172
- if (i % 2 === 1) {
3173
- d *= 2;
3174
- if (d > 9) d -= 9;
3175
- }
3176
- sum += d;
3177
- }
3178
- return sum % 10 === 0;
3179
- }
3180
1162
  function looksLikeCardNumber(digits, paymentAction) {
3181
1163
  if (digits.length < 13 || digits.length > 19 || !passesLuhn(digits)) return false;
3182
1164
  return paymentAction || digits.length === 15 || digits.length === 16;
@@ -3327,7 +1309,7 @@ async function snapshotRequest(request) {
3327
1309
  }
3328
1310
  }
3329
1311
  } catch (error) {
3330
- logger.debug(`http snapshot body-parse failed: ${describeError7(error)}`);
1312
+ logger.debug(`http snapshot body-parse failed: ${describeError5(error)}`);
3331
1313
  }
3332
1314
  return { method, url, userAgent, remoteIp, contentType, rawParams, graphqlBody, serverActionId };
3333
1315
  }
@@ -3338,7 +1320,7 @@ async function maybeRunActorHook(request) {
3338
1320
  try {
3339
1321
  hookResult = await Promise.resolve(hook(request));
3340
1322
  } catch (error) {
3341
- logger.debug(`actorFromRequest hook failed: ${describeError7(error)}`);
1323
+ logger.debug(`actorFromRequest hook failed: ${describeError5(error)}`);
3342
1324
  }
3343
1325
  }
3344
1326
  const userAgent = safeGetHeader(request.headers, "user-agent");
@@ -3351,7 +1333,7 @@ async function maybeRunActorHookFromPages(req) {
3351
1333
  try {
3352
1334
  hookResult = await Promise.resolve(hook(req));
3353
1335
  } catch (error) {
3354
- logger.debug(`actorFromRequest hook (pages) failed: ${describeError7(error)}`);
1336
+ logger.debug(`actorFromRequest hook (pages) failed: ${describeError5(error)}`);
3355
1337
  }
3356
1338
  }
3357
1339
  const userAgent = readPagesHeader(req, "user-agent");
@@ -3379,7 +1361,7 @@ async function maybeRunActorHookFromServerAction() {
3379
1361
  );
3380
1362
  } catch (error) {
3381
1363
  logger.debug(
3382
- `actorFromRequest hook (server action) failed: ${describeError7(error)}`
1364
+ `actorFromRequest hook (server action) failed: ${describeError5(error)}`
3383
1365
  );
3384
1366
  }
3385
1367
  }
@@ -3392,11 +1374,11 @@ async function maybeExtractSupabaseActor() {
3392
1374
  if (!config.actorFromSupabase) return;
3393
1375
  if (getCurrentActor()) return;
3394
1376
  try {
3395
- const mod = await Promise.resolve().then(() => (init_supabase(), supabase_exports));
1377
+ const mod = await import('./db/supabase.js');
3396
1378
  const actor = await mod.tryExtractSupabaseActor();
3397
1379
  if (actor) setActor(actor);
3398
1380
  } catch (error) {
3399
- logger.debug(`actorFromSupabase failed: ${describeError7(error)}`);
1381
+ logger.debug(`actorFromSupabase failed: ${describeError5(error)}`);
3400
1382
  }
3401
1383
  }
3402
1384
  function snapshotPagesRequest(req) {
@@ -3473,7 +1455,7 @@ async function loadNextHeaders() {
3473
1455
  try {
3474
1456
  return await Promise.resolve(mod.headers());
3475
1457
  } catch (error) {
3476
- logger.debug(`loadNextHeaders mod.headers() failed: ${describeError7(error)}`);
1458
+ logger.debug(`loadNextHeaders mod.headers() failed: ${describeError5(error)}`);
3477
1459
  return null;
3478
1460
  }
3479
1461
  }
@@ -3485,7 +1467,7 @@ async function tryLoadNextHeadersModule() {
3485
1467
  return await import('next/headers.js');
3486
1468
  } catch (secondError) {
3487
1469
  logger.debug(
3488
- `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)})`
3489
1471
  );
3490
1472
  return null;
3491
1473
  }
@@ -3532,9 +1514,10 @@ async function emitEvent(input) {
3532
1514
  const { outcome, error_message } = determineOutcome(
3533
1515
  input.statusCode,
3534
1516
  input.exception,
3535
- input.graphqlErrorMessage
1517
+ input.graphqlErrorMessage,
1518
+ input.responseErrorMessage ?? null
3536
1519
  );
3537
- const contextValue = buildContext2();
1520
+ const contextValue = buildContext();
3538
1521
  const event = build({
3539
1522
  source_type: "http_request",
3540
1523
  source_data: sourceData,
@@ -3550,10 +1533,10 @@ async function emitEvent(input) {
3550
1533
  } catch (error) {
3551
1534
  const cid = current();
3552
1535
  const cidLabel = cid ? ` (correlation_id=${cid})` : "";
3553
- logger.error(`http capture emit failed${cidLabel}: ${describeError7(error)}`);
1536
+ logger.error(`http capture emit failed${cidLabel}: ${describeError5(error)}`);
3554
1537
  }
3555
1538
  }
3556
- function buildContext2() {
1539
+ function buildContext() {
3557
1540
  const currentActor = getCurrentActor();
3558
1541
  if (!currentActor) return null;
3559
1542
  return { actor: currentActor };
@@ -3604,6 +1587,40 @@ function safeJsonParse(text) {
3604
1587
  return null;
3605
1588
  }
3606
1589
  }
1590
+ async function readRouteParams(routeContext) {
1591
+ try {
1592
+ const params = await routeContext?.params;
1593
+ if (!params || typeof params !== "object" || Array.isArray(params)) return null;
1594
+ return Object.keys(params).length > 0 ? params : null;
1595
+ } catch {
1596
+ return null;
1597
+ }
1598
+ }
1599
+ function mergeRouteParams(rawParams, routeParams) {
1600
+ if (!routeParams) return rawParams;
1601
+ if (rawParams === null || rawParams === void 0) return { ...routeParams };
1602
+ if (typeof rawParams !== "object" || Array.isArray(rawParams)) return rawParams;
1603
+ return { ...routeParams, ...rawParams };
1604
+ }
1605
+ var MAX_ERROR_BODY_LENGTH = 16384;
1606
+ async function readResponseErrorMessage(response) {
1607
+ try {
1608
+ if (response.status < 400) return null;
1609
+ if (!(response.headers.get("content-type") ?? "").includes("json")) return null;
1610
+ if (Number(response.headers.get("content-length") ?? 0) > MAX_ERROR_BODY_LENGTH) return null;
1611
+ const text = await response.clone().text();
1612
+ if (!text || text.length > MAX_ERROR_BODY_LENGTH) return null;
1613
+ const body = safeJsonParse(text);
1614
+ if (!body || typeof body !== "object") return null;
1615
+ const nested = body.error;
1616
+ const raw = [body.error, body.message, nested?.message].find(
1617
+ (v) => typeof v === "string" && v.trim().length > 0
1618
+ );
1619
+ return raw ? truncate(scrubSecretsInText(raw.trim(), { emails: true })) : null;
1620
+ } catch {
1621
+ return null;
1622
+ }
1623
+ }
3607
1624
  async function readGraphqlErrors(response) {
3608
1625
  try {
3609
1626
  const cloned = response.clone();
@@ -3615,7 +1632,7 @@ async function readGraphqlErrors(response) {
3615
1632
  return null;
3616
1633
  }
3617
1634
  }
3618
- function describeError7(error) {
1635
+ function describeError5(error) {
3619
1636
  if (error instanceof Error) return `${error.name}: ${error.message}`;
3620
1637
  return String(error);
3621
1638
  }
@@ -3831,4 +1848,4 @@ function _internalsForTests() {
3831
1848
  return { buffer: buffer_exports, flushScheduler };
3832
1849
  }
3833
1850
 
3834
- 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 };