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