ezlogs-nextjs 0.3.1 → 0.4.2

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 (76) hide show
  1. package/README.md +149 -30
  2. package/bin/install-triggers.cjs +7 -2
  3. package/dist/actors/index.cjs +4 -4
  4. package/dist/actors/index.d.cts +1 -1
  5. package/dist/actors/index.d.ts +1 -1
  6. package/dist/actors/index.js +1 -1
  7. package/dist/{chunk-C5OSM557.js → chunk-FCFVIRQF.js} +7 -0
  8. package/dist/chunk-GI6BM4MR.js +443 -0
  9. package/dist/{chunk-YX2XPLOA.cjs → chunk-GMHOUAKD.cjs} +63 -34
  10. package/dist/{chunk-CU45I2WR.js → chunk-MHBS5FEP.js} +48 -20
  11. package/dist/chunk-MMLQXSSD.cjs +461 -0
  12. package/dist/{chunk-CE3R7DVB.js → chunk-NINIAL7M.js} +60 -384
  13. package/dist/{chunk-Y5NSHKWQ.cjs → chunk-NX4EL7BY.cjs} +57 -7
  14. package/dist/chunk-PS4U2GFJ.cjs +52 -0
  15. package/dist/chunk-R6IWVTX3.cjs +212 -0
  16. package/dist/{chunk-V5YNKKTG.cjs → chunk-TWTG5ILJ.cjs} +7 -0
  17. package/dist/chunk-U22T7QYY.js +200 -0
  18. package/dist/chunk-YMIGZYFH.js +48 -0
  19. package/dist/{chunk-WASXTDLW.cjs → chunk-YXZZNZG6.cjs} +71 -403
  20. package/dist/{chunk-DKRNNI4I.js → chunk-Z2TM3LGG.js} +53 -3
  21. package/dist/{configuration-OHLNivON.d.ts → configuration-CJ5yKVlP.d.cts} +14 -8
  22. package/dist/{configuration-OHLNivON.d.cts → configuration-CJ5yKVlP.d.ts} +14 -8
  23. package/dist/db/drizzle.cjs +5 -4
  24. package/dist/db/drizzle.js +3 -2
  25. package/dist/db/postgres-js.cjs +98 -0
  26. package/dist/db/postgres-js.d.cts +11 -0
  27. package/dist/db/postgres-js.d.ts +11 -0
  28. package/dist/db/postgres-js.js +95 -0
  29. package/dist/db/prisma.cjs +21 -20
  30. package/dist/db/prisma.d.cts +19 -2
  31. package/dist/db/prisma.d.ts +19 -2
  32. package/dist/db/prisma.js +6 -5
  33. package/dist/db/supabase.cjs +19 -12
  34. package/dist/db/supabase.d.cts +3 -2
  35. package/dist/db/supabase.d.ts +3 -2
  36. package/dist/db/supabase.js +11 -4
  37. package/dist/index.cjs +596 -165
  38. package/dist/index.d.cts +5 -3
  39. package/dist/index.d.ts +5 -3
  40. package/dist/index.js +492 -62
  41. package/dist/jobs/bullmq.cjs +63 -18
  42. package/dist/jobs/bullmq.d.cts +0 -4
  43. package/dist/jobs/bullmq.d.ts +0 -4
  44. package/dist/jobs/bullmq.js +59 -14
  45. package/dist/jobs/inngest.cjs +61 -24
  46. package/dist/jobs/inngest.d.cts +5 -1
  47. package/dist/jobs/inngest.d.ts +5 -1
  48. package/dist/jobs/inngest.js +55 -18
  49. package/dist/jobs/supabase-queues.cjs +17 -15
  50. package/dist/jobs/supabase-queues.d.cts +1 -1
  51. package/dist/jobs/supabase-queues.d.ts +1 -1
  52. package/dist/jobs/supabase-queues.js +15 -13
  53. package/dist/jobs/trigger.cjs +11 -12
  54. package/dist/jobs/trigger.d.cts +4 -3
  55. package/dist/jobs/trigger.d.ts +4 -3
  56. package/dist/jobs/trigger.js +7 -8
  57. package/dist/jobs/upstash-workflow.cjs +43 -35
  58. package/dist/jobs/upstash-workflow.d.cts +2 -8
  59. package/dist/jobs/upstash-workflow.d.ts +2 -8
  60. package/dist/jobs/upstash-workflow.js +38 -30
  61. package/dist/nextjs-plugin/index.cjs +39 -3
  62. package/dist/nextjs-plugin/index.d.cts +8 -1
  63. package/dist/nextjs-plugin/index.d.ts +8 -1
  64. package/dist/nextjs-plugin/index.js +39 -3
  65. package/dist/nextjs-plugin/loader.cjs +41 -3
  66. package/dist/nextjs-plugin/loader.d.cts +1 -0
  67. package/dist/nextjs-plugin/loader.d.ts +1 -0
  68. package/dist/nextjs-plugin/loader.js +42 -4
  69. package/dist/triggers/index.cjs +145 -92
  70. package/dist/triggers/index.d.cts +20 -5
  71. package/dist/triggers/index.d.ts +20 -5
  72. package/dist/triggers/index.js +125 -82
  73. package/package.json +11 -1
  74. package/sql/postgres/00_install.sql +1 -1
  75. package/dist/chunk-UQHEW6ER.js +0 -119
  76. package/dist/chunk-UWHYJH4M.cjs +0 -126
@@ -0,0 +1,443 @@
1
+ import { logger } from './chunk-FCFVIRQF.js';
2
+ import { __require } from './chunk-SIAA4J6H.js';
3
+
4
+ // src/configuration.ts
5
+ var DEFAULT_EXCLUDED_PATHS = Object.freeze([
6
+ // Next.js / Vercel infrastructure noise
7
+ "/_next/*",
8
+ "/_vercel/*",
9
+ "/__nextjs_*",
10
+ // NextAuth.js / Auth.js — skip session-refresh polls and CSRF/provider
11
+ // metadata GETs (high-frequency, no business meaning), but CAPTURE
12
+ // POSTs (callbacks, signin, signout, register). The POSTs are the
13
+ // actual auth events users care about; the GETs are pure plumbing.
14
+ Object.freeze({ path: "/api/auth/*", methods: ["GET", "HEAD"] }),
15
+ // Generic infrastructure
16
+ "/health*",
17
+ "/api/health",
18
+ "/up",
19
+ "/alive",
20
+ "/ready",
21
+ "/metrics",
22
+ "/favicon.ico",
23
+ "/.well-known*",
24
+ "/robots.txt",
25
+ "/sitemap.xml",
26
+ "/*.hot-update.*",
27
+ // Auth.js / NextAuth plumbing that is never a user action, any method:
28
+ // session refresh (`update()` POSTs too), CSRF token, provider list,
29
+ // client log relay.
30
+ "/api/auth/session",
31
+ "/api/auth/csrf",
32
+ "/api/auth/providers",
33
+ "/api/auth/_log",
34
+ // Auth routes (common patterns across Clerk, NextAuth, custom auth):
35
+ // the GETs are page loads, probes and OAuth / email-link callbacks;
36
+ // the POSTs are sign-in / sign-up / sign-out attempts (succeeded or
37
+ // failed) and ARE captured. Passwords and tokens in the body are
38
+ // filtered by the usual param sanitization.
39
+ ...["*/login*", "*/logout*", "*/sign-in*", "*/sign-out*", "*/signin*", "*/signout*", "/session*"].map(
40
+ (path) => Object.freeze({ path, methods: ["GET", "HEAD"] })
41
+ )
42
+ ]);
43
+ var DEFAULT_EXCLUDED_EXTENSIONS = Object.freeze([
44
+ ".js",
45
+ ".css",
46
+ ".map",
47
+ ".png",
48
+ ".jpg",
49
+ ".jpeg",
50
+ ".gif",
51
+ ".svg",
52
+ ".ico",
53
+ ".webp",
54
+ ".woff",
55
+ ".woff2",
56
+ ".ttf",
57
+ ".eot",
58
+ ".otf"
59
+ ]);
60
+ var DEFAULT_EXCLUDED_TABLES = Object.freeze([
61
+ // Prisma migration ledger
62
+ "_prisma_migrations",
63
+ // Auth.js / NextAuth Prisma adapter — session/verification-token churn
64
+ // is auth machinery, not business activity. Account/User stay captured.
65
+ "Session",
66
+ "VerificationToken",
67
+ // Common cross-stack convention names for the same things
68
+ "sessions",
69
+ "session",
70
+ "verification_tokens"
71
+ ]);
72
+ var AUTH_SESSION_TABLE_NAMES = /^(sessions?|user_?sessions?|auth_?sessions?|verification_?tokens?|verifications?)$/i;
73
+ function isSessionStoreColumn(column) {
74
+ if (/token|expir/i.test(column)) return true;
75
+ return ["sess", "data", "payload", "lastactivity"].includes(column.toLowerCase().replace(/_/g, ""));
76
+ }
77
+ var DEFAULT_EXCLUDED_JOB_CLASSES = Object.freeze([]);
78
+ var DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS = Object.freeze(["IntrospectionQuery", "__*"]);
79
+ var DEFAULT_SERVER_URL = "https://app.ezlogs.io";
80
+ var Configuration = class {
81
+ serverUrl = null;
82
+ projectToken = null;
83
+ captureHttp = true;
84
+ captureDb = true;
85
+ captureJobs = true;
86
+ bufferSize = 1e4;
87
+ /** Default 3000 ms — equivalent to Ruby's 3 seconds. */
88
+ sendInterval = 3e3;
89
+ retryAttempts = 3;
90
+ logLevel = "warn";
91
+ patchGlobalFetch = true;
92
+ actorFromSupabase = true;
93
+ allowInsecureTransport = false;
94
+ excludedPaths = [];
95
+ excludedTables = [];
96
+ excludedJobClasses = [];
97
+ excludedGraphqlOperations = [];
98
+ excludedGraphqlVariableKeys = [];
99
+ actorFromRequest = null;
100
+ displayNameFor = {};
101
+ isServerActionError = null;
102
+ databaseReader = null;
103
+ databaseUrl = null;
104
+ /**
105
+ * Tables that have the `ezlogs_audit` trigger attached. Detected once
106
+ * at agent startup by reading `information_schema.triggers`. The
107
+ * supabase / drizzle / prisma adapters use this to decide whether
108
+ * their per-mutation emit is redundant: if the table is trigger-
109
+ * tracked the audit-log reader will surface the same write with full
110
+ * old/new state, so the adapter's emit is suppressed. Tables NOT in
111
+ * this set fall through to the adapter so they're still captured.
112
+ *
113
+ * `null` means "detection hasn't run yet or failed" — in that state
114
+ * `databaseReader`-wired apps suppress every adapter emit (the
115
+ * original Phase 5 behavior). After detection completes the agent
116
+ * gives the more accurate per-table answer.
117
+ */
118
+ triggerTrackedTables = null;
119
+ apply(options) {
120
+ this.serverUrl = options.serverUrl || (typeof process !== "undefined" ? process.env?.EZLOGS_SERVER_URL : void 0) || DEFAULT_SERVER_URL;
121
+ this.projectToken = options.projectToken;
122
+ if (options.captureHttp !== void 0) this.captureHttp = options.captureHttp;
123
+ if (options.captureDb !== void 0) this.captureDb = options.captureDb;
124
+ if (options.captureJobs !== void 0) this.captureJobs = options.captureJobs;
125
+ if (options.bufferSize !== void 0) this.bufferSize = options.bufferSize;
126
+ if (options.sendInterval !== void 0) this.sendInterval = options.sendInterval;
127
+ if (options.retryAttempts !== void 0) this.retryAttempts = options.retryAttempts;
128
+ if (options.excludedPaths) this.excludedPaths = [...options.excludedPaths];
129
+ if (options.excludedTables) this.excludedTables = [...options.excludedTables];
130
+ if (options.excludedJobClasses) {
131
+ this.excludedJobClasses = [...options.excludedJobClasses];
132
+ }
133
+ if (options.excludedGraphqlOperations) {
134
+ this.excludedGraphqlOperations = [...options.excludedGraphqlOperations];
135
+ }
136
+ if (options.excludedGraphqlVariableKeys) {
137
+ this.excludedGraphqlVariableKeys = [...options.excludedGraphqlVariableKeys];
138
+ }
139
+ if (options.actorFromRequest) this.actorFromRequest = options.actorFromRequest;
140
+ if (options.displayNameFor) this.displayNameFor = { ...options.displayNameFor };
141
+ if (options.isServerActionError) this.isServerActionError = options.isServerActionError;
142
+ if (options.patchGlobalFetch !== void 0) {
143
+ this.patchGlobalFetch = options.patchGlobalFetch;
144
+ }
145
+ if (options.allowInsecureTransport !== void 0) {
146
+ this.allowInsecureTransport = options.allowInsecureTransport;
147
+ }
148
+ if (options.actorFromSupabase !== void 0) {
149
+ this.actorFromSupabase = options.actorFromSupabase;
150
+ }
151
+ if (options.databaseReader !== void 0) {
152
+ this.databaseReader = options.databaseReader;
153
+ }
154
+ if (options.databaseUrl !== void 0) {
155
+ this.databaseUrl = options.databaseUrl;
156
+ }
157
+ if (options.logLevel) this.logLevel = options.logLevel;
158
+ }
159
+ allExcludedPaths() {
160
+ return [...DEFAULT_EXCLUDED_PATHS, ...this.excludedPaths];
161
+ }
162
+ allExcludedTables() {
163
+ return [...DEFAULT_EXCLUDED_TABLES, ...this.excludedTables];
164
+ }
165
+ allExcludedJobClasses() {
166
+ return [...DEFAULT_EXCLUDED_JOB_CLASSES, ...this.excludedJobClasses];
167
+ }
168
+ allExcludedGraphqlOperations() {
169
+ return [...DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS, ...this.excludedGraphqlOperations];
170
+ }
171
+ };
172
+ var GLOBAL_CONFIG_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:configuration");
173
+ function configuration() {
174
+ const g = globalThis;
175
+ if (!g[GLOBAL_CONFIG_KEY]) {
176
+ g[GLOBAL_CONFIG_KEY] = new Configuration();
177
+ }
178
+ return g[GLOBAL_CONFIG_KEY];
179
+ }
180
+
181
+ // src/edge-fallback.ts
182
+ var ALS_CTOR = loadAsyncLocalStorage();
183
+ function loadAsyncLocalStorage() {
184
+ const fromGlobal = globalThis.AsyncLocalStorage;
185
+ if (typeof fromGlobal === "function") return fromGlobal;
186
+ const moduleName = "node:" + ["async", "hooks"].join("_");
187
+ try {
188
+ const getBuiltin = globalThis.process?.getBuiltinModule;
189
+ if (typeof getBuiltin === "function") {
190
+ const mod = getBuiltin(moduleName);
191
+ if (typeof mod?.AsyncLocalStorage === "function") return mod.AsyncLocalStorage;
192
+ }
193
+ } catch {
194
+ }
195
+ try {
196
+ const req = typeof __require !== "undefined" ? __require : void 0;
197
+ if (typeof req === "function") {
198
+ const mod = req(moduleName);
199
+ if (typeof mod.AsyncLocalStorage === "function") return mod.AsyncLocalStorage;
200
+ }
201
+ } catch {
202
+ }
203
+ warnNoAsyncLocalStorageOnNode();
204
+ return null;
205
+ }
206
+ function warnNoAsyncLocalStorageOnNode() {
207
+ const WARNED_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:no-als-warned");
208
+ const g = globalThis;
209
+ if (g.EdgeRuntime !== void 0 || !g.process?.versions?.node) return;
210
+ if (g[WARNED_KEY]) return;
211
+ g[WARNED_KEY] = true;
212
+ console.warn(
213
+ `[ezlogs] AsyncLocalStorage is unavailable on Node ${g.process.versions.node}. Concurrent requests and jobs will share one correlation id and actor, so events can be grouped into the wrong action. Upgrade to Node >= 20.16 (or >= 22.3), or load ezlogs-nextjs through CommonJS (require).`
214
+ );
215
+ }
216
+ function makeAsyncContextCapture() {
217
+ if (!ALS_CTOR) return null;
218
+ const ctor = ALS_CTOR;
219
+ if (typeof ctor.snapshot !== "function") return null;
220
+ const snapshot = ctor.snapshot.bind(ctor);
221
+ return () => {
222
+ const runSnapshot = snapshot();
223
+ return (fn) => runSnapshot(fn);
224
+ };
225
+ }
226
+ function createScopedStorage(key = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:default-scoped-storage")) {
227
+ const globalStore = globalThis;
228
+ let entry = globalStore[key];
229
+ if (!entry) {
230
+ const als2 = (() => {
231
+ if (!ALS_CTOR) return null;
232
+ try {
233
+ return new ALS_CTOR();
234
+ } catch {
235
+ return null;
236
+ }
237
+ })();
238
+ entry = { als: als2, edgeFallback: null };
239
+ globalStore[key] = entry;
240
+ }
241
+ const als = entry.als;
242
+ const stateRef = entry;
243
+ return {
244
+ read() {
245
+ if (als) return als.getStore()?.value ?? null;
246
+ return stateRef.edgeFallback?.value ?? null;
247
+ },
248
+ run(value, callback) {
249
+ if (als) return als.run({ value }, callback);
250
+ const previous = stateRef.edgeFallback;
251
+ stateRef.edgeFallback = { value };
252
+ try {
253
+ return callback();
254
+ } finally {
255
+ stateRef.edgeFallback = previous;
256
+ }
257
+ },
258
+ update(value) {
259
+ if (als) {
260
+ const store = als.getStore();
261
+ if (store) store.value = value;
262
+ return;
263
+ }
264
+ stateRef.edgeFallback = { value };
265
+ },
266
+ _resetForTests() {
267
+ stateRef.edgeFallback = null;
268
+ },
269
+ _isAsyncLocalStorage() {
270
+ return als !== null;
271
+ }
272
+ };
273
+ }
274
+
275
+ // src/correlation.ts
276
+ var CORRELATION_HEADER = "x-ezlogs-correlation-id";
277
+ var PLATFORM_REQUEST_ID_HEADERS = [
278
+ "x-vercel-id",
279
+ "cf-ray",
280
+ "x-request-id"
281
+ ];
282
+ var storage = createScopedStorage(
283
+ /* @__PURE__ */ Symbol.for("ezlogs-nextjs:correlation-storage")
284
+ );
285
+ var REQUEST_GRACE_MS = 6e4;
286
+ var graceMs = REQUEST_GRACE_MS;
287
+ function generate() {
288
+ const ts = Date.now();
289
+ const hex = randomHexBytes(4);
290
+ return `ezl_${ts}_${hex}`;
291
+ }
292
+ function randomHexBytes(byteCount) {
293
+ const buf = new Uint8Array(byteCount);
294
+ globalThis.crypto.getRandomValues(buf);
295
+ let out = "";
296
+ for (let i = 0; i < buf.length; i++) {
297
+ out += buf[i].toString(16).padStart(2, "0");
298
+ }
299
+ return out;
300
+ }
301
+ function resolveCorrelation(headers) {
302
+ if (!headers) return generate();
303
+ const ezlogs = safeRead(headers, CORRELATION_HEADER);
304
+ if (ezlogs && isTrustedInboundId(ezlogs)) return ezlogs;
305
+ for (const name of PLATFORM_REQUEST_ID_HEADERS) {
306
+ const platformId = safeRead(headers, name);
307
+ if (platformId) return wrapPlatformId(platformId);
308
+ }
309
+ return generate();
310
+ }
311
+ var INBOUND_ID = /^ezl_(\d{13})_[0-9a-f]{8}$/;
312
+ var INBOUND_MAX_AGE_MS = 60 * 6e4;
313
+ function isTrustedInboundId(id) {
314
+ const match = INBOUND_ID.exec(id);
315
+ if (!match) return false;
316
+ const age = Date.now() - Number(match[1]);
317
+ return age <= INBOUND_MAX_AGE_MS && age >= -3e5;
318
+ }
319
+ function safeRead(headers, name) {
320
+ try {
321
+ const value = headers.get(name);
322
+ return typeof value === "string" && value.length > 0 ? value : null;
323
+ } catch {
324
+ return null;
325
+ }
326
+ }
327
+ function wrapPlatformId(platformId) {
328
+ const ts = Date.now();
329
+ const hex = fnv1aHex(platformId);
330
+ return `ezl_${ts}_${hex}`;
331
+ }
332
+ function fnv1aHex(input) {
333
+ let hash = 2166136261;
334
+ for (let i = 0; i < input.length; i++) {
335
+ hash ^= input.charCodeAt(i);
336
+ hash = Math.imul(hash, 16777619);
337
+ }
338
+ return (hash >>> 0).toString(16).padStart(8, "0");
339
+ }
340
+ function current() {
341
+ const scope = storage.read();
342
+ return scope && Date.now() <= scope.expiresAt ? scope.id : null;
343
+ }
344
+ function scopeExpired() {
345
+ const scope = storage.read();
346
+ return scope !== null && Date.now() > scope.expiresAt;
347
+ }
348
+ function endCorrelationScope() {
349
+ const scope = storage.read();
350
+ if (scope && scope.expiresAt === Infinity) scope.expiresAt = Date.now() + graceMs;
351
+ }
352
+ function runWithCorrelation(correlationId, callback) {
353
+ return storage.run({ id: correlationId, expiresAt: Infinity }, () => runWithActorScope(callback));
354
+ }
355
+
356
+ // src/actor.ts
357
+ var storage2 = createScopedStorage(
358
+ /* @__PURE__ */ Symbol.for("ezlogs-nextjs:actor-storage")
359
+ );
360
+ function getCurrentActor() {
361
+ if (scopeExpired()) return null;
362
+ return storage2.read();
363
+ }
364
+ function setActor(input) {
365
+ const sanitized = validateActor(input);
366
+ if (input != null && sanitized === null) {
367
+ logger.debug(`Actor: invalid actor structure ignored: ${describe(input)}`);
368
+ }
369
+ storage2.update(sanitized);
370
+ return sanitized;
371
+ }
372
+ var sourceStorage = createScopedStorage(
373
+ /* @__PURE__ */ Symbol.for("ezlogs-nextjs:actor-source-storage")
374
+ );
375
+ function currentActorSource() {
376
+ return sourceStorage.read();
377
+ }
378
+ function runWithActorScope(callback, actor = null) {
379
+ return storage2.run(actor, () => sourceStorage.run({}, callback));
380
+ }
381
+ async function maybeExtractSupabaseActor() {
382
+ const config = configuration();
383
+ if (!config.actorFromSupabase) return;
384
+ if (getCurrentActor()) return;
385
+ const slot = currentActorSource();
386
+ if (slot?.tried) return;
387
+ try {
388
+ const mod = await import('./db/supabase.js');
389
+ const actor = await mod.tryExtractSupabaseActor();
390
+ if (slot) slot.tried = true;
391
+ if (actor) setActor(actor);
392
+ } catch (error) {
393
+ logger.debug(`actorFromSupabase failed: ${describe(error)}`);
394
+ }
395
+ }
396
+ var VALID_KINDS = /* @__PURE__ */ new Set(["human", "agent", "system", "hybrid"]);
397
+ function validateActor(input) {
398
+ if (input === null || input === void 0) return null;
399
+ if (typeof input !== "object") return null;
400
+ if (Array.isArray(input)) return null;
401
+ const obj = input;
402
+ const rawId = obj.id;
403
+ if (rawId === null || rawId === void 0) return null;
404
+ const id = String(rawId);
405
+ if (id === "") return null;
406
+ const result = { id };
407
+ if (obj.label !== void 0 && obj.label !== null) {
408
+ result.label = String(obj.label);
409
+ }
410
+ if (obj.kind !== void 0 && obj.kind !== null) {
411
+ const kind = String(obj.kind);
412
+ if (VALID_KINDS.has(kind)) {
413
+ result.kind = kind;
414
+ }
415
+ }
416
+ const principal = sanitizePrincipal(obj.principal);
417
+ if (principal) result.principal = principal;
418
+ return result;
419
+ }
420
+ function sanitizePrincipal(input) {
421
+ if (input === null || input === void 0) return null;
422
+ if (typeof input !== "object") return null;
423
+ if (Array.isArray(input)) return null;
424
+ const obj = input;
425
+ const rawId = obj.id;
426
+ if (rawId === null || rawId === void 0) return null;
427
+ const id = String(rawId);
428
+ if (id === "") return null;
429
+ const result = { id };
430
+ if (obj.label !== void 0 && obj.label !== null) {
431
+ result.label = String(obj.label);
432
+ }
433
+ return result;
434
+ }
435
+ function describe(value) {
436
+ try {
437
+ return JSON.stringify(value);
438
+ } catch {
439
+ return Object.prototype.toString.call(value);
440
+ }
441
+ }
442
+
443
+ export { AUTH_SESSION_TABLE_NAMES, DEFAULT_EXCLUDED_EXTENSIONS, DEFAULT_EXCLUDED_TABLES, configuration, createScopedStorage, current, currentActorSource, endCorrelationScope, generate, getCurrentActor, isSessionStoreColumn, makeAsyncContextCapture, maybeExtractSupabaseActor, resolveCorrelation, runWithActorScope, runWithCorrelation, setActor };
@@ -1,10 +1,11 @@
1
1
  'use strict';
2
2
 
3
- var chunkWASXTDLW_cjs = require('./chunk-WASXTDLW.cjs');
4
- var chunkV5YNKKTG_cjs = require('./chunk-V5YNKKTG.cjs');
3
+ var chunkYXZZNZG6_cjs = require('./chunk-YXZZNZG6.cjs');
4
+ var chunkMMLQXSSD_cjs = require('./chunk-MMLQXSSD.cjs');
5
+ var chunkTWTG5ILJ_cjs = require('./chunk-TWTG5ILJ.cjs');
5
6
 
6
7
  // src/triggers/emit-dedup.ts
7
- var storage = chunkWASXTDLW_cjs.createScopedStorage(
8
+ var storage = chunkMMLQXSSD_cjs.createScopedStorage(
8
9
  /* @__PURE__ */ Symbol.for("ezlogs-nextjs:audit-emitted-ids-storage")
9
10
  );
10
11
  function currentEmittedAuditIds() {
@@ -17,15 +18,18 @@ function runWithEmittedAuditIdsScope(callback) {
17
18
  }
18
19
 
19
20
  // src/triggers/reader.ts
20
- var COLUMNS = "id, table_name, op, old_row, new_row, resource_id, correlation_id, txid, captured_at";
21
+ var COLUMNS = "id, table_name, op, old_row, new_row, resource_id, correlation_id, txid, captured_at, actor_id";
21
22
  var ORPHAN_AGE = "5 minutes";
22
- var PRUNE_AGE = "24 hours";
23
+ var ORPHAN_AGE_MS = 5 * 6e4;
24
+ var PRUNE_AGE = "7 days";
23
25
  var SWEEP_BATCH = 100;
24
26
  var PRUNE_BATCH = 2e3;
25
27
  var SWEEP_INTERVAL_MS = 1e4;
26
28
  var PRUNE_INTERVAL_MS = 10 * 6e4;
27
29
  var lastSweepAt = 0;
28
30
  var lastPruneAt = 0;
31
+ var pruneBacklogWarned = false;
32
+ var lastRequestFlushAt = 0;
29
33
  var deleteDenied = false;
30
34
  var txCorrelation = /* @__PURE__ */ new Map();
31
35
  var UNTAGGED_STRIKES = 5;
@@ -57,8 +61,8 @@ async function readAuditRows(exec, correlationId, since = null) {
57
61
  } catch (err) {
58
62
  if (!isPermissionDenied(err)) throw err;
59
63
  deleteDenied = true;
60
- chunkV5YNKKTG_cjs.logger.warn(
61
- "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'`."
64
+ chunkTWTG5ILJ_cjs.logger.warn(
65
+ "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 '7 days'`."
62
66
  );
63
67
  }
64
68
  }
@@ -68,7 +72,7 @@ async function readAuditRows(exec, correlationId, since = null) {
68
72
  );
69
73
  return extractRows(result).map(normalizeAuditRow);
70
74
  } catch (err) {
71
- chunkV5YNKKTG_cjs.logger.debug(
75
+ chunkTWTG5ILJ_cjs.logger.debug(
72
76
  `readAuditRows failed: ${err instanceof Error ? err.message : String(err)}`
73
77
  );
74
78
  return [];
@@ -99,14 +103,11 @@ async function sweepAuditLog(exec) {
99
103
  await loadTableMeta(exec, rows);
100
104
  for (const row of rows) {
101
105
  const correlationId = row.correlation_id ?? correlationForTx(row.txid);
102
- chunkWASXTDLW_cjs.runWithCorrelation(
103
- correlationId,
104
- () => chunkWASXTDLW_cjs.runWithActorScope(() => emitOne(row))
105
- );
106
+ chunkMMLQXSSD_cjs.runWithCorrelation(correlationId, () => emitWithRowActor(row));
106
107
  }
107
108
  return rows.length;
108
109
  } catch (err) {
109
- chunkV5YNKKTG_cjs.logger.debug(
110
+ chunkTWTG5ILJ_cjs.logger.debug(
110
111
  `sweepAuditLog failed: ${err instanceof Error ? err.message : String(err)}`
111
112
  );
112
113
  return 0;
@@ -115,16 +116,28 @@ async function sweepAuditLog(exec) {
115
116
  async function pruneAuditLog(exec) {
116
117
  if (deleteDenied) return;
117
118
  try {
118
- await exec(
119
- `DELETE FROM ezlogs_audit_log
120
- WHERE id IN (
121
- SELECT id FROM ezlogs_audit_log
122
- WHERE captured_at < now() - interval '${PRUNE_AGE}'
123
- LIMIT ${PRUNE_BATCH})`,
124
- []
119
+ const rows = extractRows(
120
+ await exec(
121
+ `WITH pruned AS (
122
+ DELETE FROM ezlogs_audit_log
123
+ WHERE id IN (
124
+ SELECT id FROM ezlogs_audit_log
125
+ WHERE captured_at < now() - interval '${PRUNE_AGE}'
126
+ LIMIT ${PRUNE_BATCH})
127
+ RETURNING 1)
128
+ SELECT count(*)::int AS n FROM pruned`,
129
+ []
130
+ )
125
131
  );
132
+ const pruned = Number(rows[0]?.n ?? 0);
133
+ if (pruned >= PRUNE_BATCH && !pruneBacklogWarned) {
134
+ pruneBacklogWarned = true;
135
+ chunkTWTG5ILJ_cjs.logger.warn(
136
+ `deleted ${pruned} ezlogs_audit_log rows older than ${PRUNE_AGE} unsent; more may remain. The agent only sends rows while requests run; rows written while the app was idle for ${PRUNE_AGE}, or faster than the sweep sends them, are dropped.`
137
+ );
138
+ }
126
139
  } catch (err) {
127
- chunkV5YNKKTG_cjs.logger.debug(
140
+ chunkTWTG5ILJ_cjs.logger.debug(
128
141
  `pruneAuditLog failed: ${err instanceof Error ? err.message : String(err)}`
129
142
  );
130
143
  }
@@ -163,7 +176,7 @@ async function checkAuditLogAccess(exec) {
163
176
  );
164
177
  const role = rows[0]?.role;
165
178
  if (typeof role !== "string") return false;
166
- chunkV5YNKKTG_cjs.logger.warn(
179
+ chunkTWTG5ILJ_cjs.logger.warn(
167
180
  `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);`
168
181
  );
169
182
  return true;
@@ -190,7 +203,7 @@ async function detectTriggerTrackedTables(exec) {
190
203
  }
191
204
  return tables;
192
205
  } catch (err) {
193
- chunkV5YNKKTG_cjs.logger.debug(
206
+ chunkTWTG5ILJ_cjs.logger.debug(
194
207
  `detectTriggerTrackedTables failed: ${err instanceof Error ? err.message : String(err)}`
195
208
  );
196
209
  return null;
@@ -198,18 +211,32 @@ async function detectTriggerTrackedTables(exec) {
198
211
  }
199
212
  function emitAuditRows(rows) {
200
213
  for (const row of rows) {
201
- emitOne(row);
214
+ emitWithRowActor(row);
202
215
  }
203
216
  }
217
+ function emitWithRowActor(row) {
218
+ const stored = row.actor_id || null;
219
+ const claimer = chunkMMLQXSSD_cjs.getCurrentActor();
220
+ const actor = stored ? claimer?.id === stored ? claimer : { id: stored } : null;
221
+ chunkMMLQXSSD_cjs.runWithActorScope(() => emitOne(row), actor);
222
+ }
204
223
  async function flushAuditLog(exec, options = {}) {
205
224
  if (!exec) return;
206
- const correlationId = chunkWASXTDLW_cjs.current();
225
+ const correlationId = chunkMMLQXSSD_cjs.current();
207
226
  if (!correlationId) return;
227
+ lastRequestFlushAt = Date.now();
208
228
  const rows = await readAuditRows(exec, correlationId, options.since ?? null);
209
229
  await loadTableMeta(exec, rows);
210
230
  emitFresh(rows);
211
231
  if (rows.length > 0) taggedRowSeen = true;
212
232
  else await checkUntaggedWrites(exec, correlationId, options.since ?? null);
233
+ await maintainAuditLog(exec);
234
+ }
235
+ async function maintainAuditLogAfterRequests(exec) {
236
+ if (Date.now() - lastRequestFlushAt >= ORPHAN_AGE_MS + SWEEP_INTERVAL_MS) return;
237
+ await maintainAuditLog(exec);
238
+ }
239
+ async function maintainAuditLog(exec) {
213
240
  const now = Date.now();
214
241
  if (now - lastPruneAt >= PRUNE_INTERVAL_MS) {
215
242
  lastPruneAt = now;
@@ -245,8 +272,8 @@ async function checkUntaggedWrites(exec, correlationId, since) {
245
272
  if (untaggedWarned) return;
246
273
  untaggedWarned = true;
247
274
  const where = since ? "background jobs" : "requests";
248
- chunkV5YNKKTG_cjs.logger.warn(
249
- `database writes made while ${where} ran in this process reached ezlogs_audit_log with no request tag, and this process has never sent a tagged row. They show up as separate actions with no actor (they are never guessed onto a request). Most likely the database client this app writes with is not tagged (or another process wrote them during these windows). Prisma: \`new PrismaClient().$extends(ezlogsPrisma())\` (from "ezlogs-nextjs/prisma"). Drizzle / node-postgres: let the agent patch \`pg\` (set DATABASE_URL, or \`ezlogs.init({ patchDatabaseClient: pg })\` with your app's \`pg\`). In a worker process (BullMQ, \u2026), call \`ezlogs.init\` there too and build the client the same way. Writes inside your own \`prisma.$transaction(...)\` stay untagged either way. See README, "Database changes".`
275
+ chunkTWTG5ILJ_cjs.logger.warn(
276
+ `database writes made while ${where} ran in this process reached ezlogs_audit_log with no request tag, and this process has never sent a tagged row. They show up as separate actions with no actor (they are never guessed onto a request). Most likely the database client this app writes with is not tagged (or another process wrote them during these windows). Prisma: \`new PrismaClient().$extends(ezlogsPrisma())\` (from "ezlogs-nextjs/prisma"). Drizzle / node-postgres: let the agent patch \`pg\` (set DATABASE_URL, or \`ezlogs.init({ patchDatabaseClient: pg })\` with your app's \`pg\`). postgres.js / Drizzle postgres-js: \`wrapPostgresJs(postgres(url))\` (from "ezlogs-nextjs/postgres"). In a worker process (BullMQ, \u2026), call \`ezlogs.init\` there too and build the client the same way. Writes inside your own \`prisma.$transaction(...)\` stay untagged either way. See README, "Database changes".`
250
277
  );
251
278
  }
252
279
  var tableMeta = /* @__PURE__ */ new Map();
@@ -309,7 +336,7 @@ async function loadTableMeta(exec, rows) {
309
336
  }
310
337
  } catch (err) {
311
338
  metaRetryAt = Date.now() + META_RETRY_MS;
312
- chunkV5YNKKTG_cjs.logger.debug(`table metadata lookup failed: ${err instanceof Error ? err.message : String(err)}`);
339
+ chunkTWTG5ILJ_cjs.logger.debug(`table metadata lookup failed: ${err instanceof Error ? err.message : String(err)}`);
313
340
  }
314
341
  }
315
342
  function relatedResourceIds(table, row) {
@@ -338,11 +365,11 @@ function emitFresh(rows) {
338
365
  emitAuditRows(fresh);
339
366
  }
340
367
  function correlationForTx(txid) {
341
- if (!txid) return chunkWASXTDLW_cjs.generate();
368
+ if (!txid) return chunkMMLQXSSD_cjs.generate();
342
369
  let id = txCorrelation.get(txid);
343
370
  if (!id) {
344
371
  if (txCorrelation.size >= 1e3) txCorrelation.clear();
345
- id = chunkWASXTDLW_cjs.generate();
372
+ id = chunkMMLQXSSD_cjs.generate();
346
373
  txCorrelation.set(txid, id);
347
374
  }
348
375
  return id;
@@ -363,7 +390,7 @@ function emitOne(row) {
363
390
  const newRow = withUtcTimestamps(coerceJsonb(row.new_row), naive);
364
391
  const related = row.resource_id === null ? relatedResourceIds(row.table_name, newRow ?? oldRow ?? {}) : null;
365
392
  if (op === "create" && newRow) {
366
- chunkWASXTDLW_cjs.emitDbEvent({
393
+ chunkYXZZNZG6_cjs.emitDbEvent({
367
394
  modelClass: row.table_name,
368
395
  operation: "create",
369
396
  resourceId: row.resource_id,
@@ -381,7 +408,7 @@ function emitOne(row) {
381
408
  if (changes.length === 0) {
382
409
  return;
383
410
  }
384
- chunkWASXTDLW_cjs.emitDbEvent({
411
+ chunkYXZZNZG6_cjs.emitDbEvent({
385
412
  modelClass: row.table_name,
386
413
  operation: "update",
387
414
  resourceId: row.resource_id,
@@ -397,7 +424,7 @@ function emitOne(row) {
397
424
  return;
398
425
  }
399
426
  if (op === "destroy" && oldRow) {
400
- chunkWASXTDLW_cjs.emitDbEvent({
427
+ chunkYXZZNZG6_cjs.emitDbEvent({
401
428
  modelClass: row.table_name,
402
429
  operation: "destroy",
403
430
  resourceId: row.resource_id,
@@ -480,7 +507,8 @@ function normalizeAuditRow(raw) {
480
507
  resource_id: r.resource_id == null ? null : String(r.resource_id),
481
508
  correlation_id: r.correlation_id == null ? null : String(r.correlation_id),
482
509
  txid: r.txid == null ? null : String(r.txid),
483
- captured_at: toDate(r.captured_at)
510
+ captured_at: toDate(r.captured_at),
511
+ actor_id: r.actor_id == null ? null : String(r.actor_id)
484
512
  };
485
513
  }
486
514
  function coerceJsonb(value) {
@@ -502,6 +530,7 @@ exports.checkAuditLogAccess = checkAuditLogAccess;
502
530
  exports.detectTriggerTrackedTables = detectTriggerTrackedTables;
503
531
  exports.emitAuditRows = emitAuditRows;
504
532
  exports.flushAuditLog = flushAuditLog;
533
+ exports.maintainAuditLogAfterRequests = maintainAuditLogAfterRequests;
505
534
  exports.pruneAuditLog = pruneAuditLog;
506
535
  exports.readAuditRows = readAuditRows;
507
536
  exports.runWithEmittedAuditIdsScope = runWithEmittedAuditIdsScope;