ezlogs-nextjs 0.1.0 → 0.1.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 (43) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +98 -688
  3. package/bin/install-triggers.cjs +1 -1
  4. package/dist/actors/index.d.cts +1 -1
  5. package/dist/actors/index.d.ts +1 -1
  6. package/dist/{configuration-D9x9Gvds.d.cts → configuration-aUYgA8-h.d.cts} +20 -3
  7. package/dist/{configuration-D9x9Gvds.d.ts → configuration-aUYgA8-h.d.ts} +20 -3
  8. package/dist/db/drizzle.cjs +17 -6
  9. package/dist/db/drizzle.js +17 -6
  10. package/dist/db/prisma.cjs +271 -76
  11. package/dist/db/prisma.d.cts +38 -1
  12. package/dist/db/prisma.d.ts +38 -1
  13. package/dist/db/prisma.js +270 -77
  14. package/dist/db/supabase.cjs +17 -6
  15. package/dist/db/supabase.js +17 -6
  16. package/dist/index.cjs +459 -222
  17. package/dist/index.d.cts +2 -2
  18. package/dist/index.d.ts +2 -2
  19. package/dist/index.js +459 -222
  20. package/dist/jobs/bullmq.cjs +6 -5
  21. package/dist/jobs/bullmq.d.cts +16 -8
  22. package/dist/jobs/bullmq.d.ts +16 -8
  23. package/dist/jobs/bullmq.js +6 -5
  24. package/dist/jobs/inngest.cjs +16 -6
  25. package/dist/jobs/inngest.js +16 -6
  26. package/dist/jobs/supabase-queues.cjs +16 -6
  27. package/dist/jobs/supabase-queues.js +16 -6
  28. package/dist/jobs/trigger.cjs +16 -6
  29. package/dist/jobs/trigger.js +16 -6
  30. package/dist/jobs/upstash-workflow.cjs +16 -6
  31. package/dist/jobs/upstash-workflow.js +16 -6
  32. package/dist/nextjs-plugin/index.cjs +18 -0
  33. package/dist/nextjs-plugin/index.js +18 -0
  34. package/dist/nextjs-plugin/loader.cjs +44 -34
  35. package/dist/nextjs-plugin/loader.d.cts +10 -0
  36. package/dist/nextjs-plugin/loader.d.ts +10 -0
  37. package/dist/nextjs-plugin/loader.js +44 -34
  38. package/dist/triggers/index.cjs +43 -8
  39. package/dist/triggers/index.d.cts +7 -0
  40. package/dist/triggers/index.d.ts +7 -0
  41. package/dist/triggers/index.js +43 -8
  42. package/package.json +3 -4
  43. package/sql/postgres/00_install.sql +1 -1
package/dist/index.js CHANGED
@@ -1,5 +1,3 @@
1
- import { randomBytes, createHash } from 'crypto';
2
-
3
1
  var __defProp = Object.defineProperty;
4
2
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
3
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
@@ -24,7 +22,7 @@ function configuration() {
24
22
  }
25
23
  return g[GLOBAL_CONFIG_KEY];
26
24
  }
27
- var DEFAULT_EXCLUDED_PATHS, DEFAULT_EXCLUDED_EXTENSIONS, DEFAULT_EXCLUDED_TABLES, DEFAULT_EXCLUDED_JOB_CLASSES, DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS, DEFAULT_SERVER_URL, Configuration, GLOBAL_CONFIG_KEY;
25
+ var DEFAULT_EXCLUDED_PATHS, DEFAULT_EXCLUDED_EXTENSIONS, DEFAULT_EXCLUDED_TABLES, DEFAULT_EXCLUDED_JOB_CLASSES, DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS, Configuration, GLOBAL_CONFIG_KEY;
28
26
  var init_configuration = __esm({
29
27
  "src/configuration.ts"() {
30
28
  DEFAULT_EXCLUDED_PATHS = Object.freeze([
@@ -89,9 +87,8 @@ var init_configuration = __esm({
89
87
  ]);
90
88
  DEFAULT_EXCLUDED_JOB_CLASSES = Object.freeze([]);
91
89
  DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS = Object.freeze(["IntrospectionQuery", "__*"]);
92
- DEFAULT_SERVER_URL = "https://app.ezlogs.io";
93
90
  Configuration = class {
94
- serverUrl = DEFAULT_SERVER_URL;
91
+ serverUrl = null;
95
92
  projectToken = null;
96
93
  captureHttp = true;
97
94
  captureDb = true;
@@ -103,6 +100,7 @@ var init_configuration = __esm({
103
100
  logLevel = "warn";
104
101
  patchGlobalFetch = true;
105
102
  actorFromSupabase = true;
103
+ allowInsecureTransport = false;
106
104
  excludedPaths = [];
107
105
  excludedTables = [];
108
106
  excludedJobClasses = [];
@@ -130,7 +128,7 @@ var init_configuration = __esm({
130
128
  */
131
129
  triggerTrackedTables = null;
132
130
  apply(options) {
133
- if (options.serverUrl !== void 0) this.serverUrl = options.serverUrl;
131
+ this.serverUrl = options.serverUrl;
134
132
  this.projectToken = options.projectToken;
135
133
  if (options.captureHttp !== void 0) this.captureHttp = options.captureHttp;
136
134
  if (options.captureDb !== void 0) this.captureDb = options.captureDb;
@@ -155,6 +153,9 @@ var init_configuration = __esm({
155
153
  if (options.patchGlobalFetch !== void 0) {
156
154
  this.patchGlobalFetch = options.patchGlobalFetch;
157
155
  }
156
+ if (options.allowInsecureTransport !== void 0) {
157
+ this.allowInsecureTransport = options.allowInsecureTransport;
158
+ }
158
159
  if (options.actorFromSupabase !== void 0) {
159
160
  this.actorFromSupabase = options.actorFromSupabase;
160
161
  }
@@ -366,11 +367,22 @@ var init_edge_fallback = __esm({
366
367
  ALS_CTOR = loadAsyncLocalStorage();
367
368
  }
368
369
  });
370
+
371
+ // src/correlation.ts
369
372
  function generate() {
370
373
  const ts = Date.now();
371
- const hex = randomBytes(4).toString("hex");
374
+ const hex = randomHexBytes(4);
372
375
  return `ezl_${ts}_${hex}`;
373
376
  }
377
+ function randomHexBytes(byteCount) {
378
+ const buf = new Uint8Array(byteCount);
379
+ globalThis.crypto.getRandomValues(buf);
380
+ let out = "";
381
+ for (let i = 0; i < buf.length; i++) {
382
+ out += buf[i].toString(16).padStart(2, "0");
383
+ }
384
+ return out;
385
+ }
374
386
  function resolveCorrelation(headers) {
375
387
  if (!headers) return generate();
376
388
  const ezlogs2 = safeRead(headers, CORRELATION_HEADER);
@@ -391,9 +403,17 @@ function safeRead(headers, name) {
391
403
  }
392
404
  function wrapPlatformId(platformId) {
393
405
  const ts = Date.now();
394
- const hex = createHash("sha1").update(platformId).digest("hex").slice(0, 8);
406
+ const hex = fnv1aHex(platformId);
395
407
  return `ezl_${ts}_${hex}`;
396
408
  }
409
+ function fnv1aHex(input) {
410
+ let hash = 2166136261;
411
+ for (let i = 0; i < input.length; i++) {
412
+ hash ^= input.charCodeAt(i);
413
+ hash = Math.imul(hash, 16777619);
414
+ }
415
+ return (hash >>> 0).toString(16).padStart(8, "0");
416
+ }
397
417
  function current() {
398
418
  return storage.read();
399
419
  }
@@ -444,6 +464,12 @@ function validateActor(input) {
444
464
  if (obj.label !== void 0 && obj.label !== null) {
445
465
  result.label = String(obj.label);
446
466
  }
467
+ if (obj.kind !== void 0 && obj.kind !== null) {
468
+ const kind = String(obj.kind);
469
+ if (VALID_KINDS.has(kind)) {
470
+ result.kind = kind;
471
+ }
472
+ }
447
473
  return result;
448
474
  }
449
475
  function describe2(value) {
@@ -453,7 +479,7 @@ function describe2(value) {
453
479
  return Object.prototype.toString.call(value);
454
480
  }
455
481
  }
456
- var storage2;
482
+ var storage2, VALID_KINDS;
457
483
  var init_actor = __esm({
458
484
  "src/actor.ts"() {
459
485
  init_logger();
@@ -461,6 +487,7 @@ var init_actor = __esm({
461
487
  storage2 = createScopedStorage(
462
488
  /* @__PURE__ */ Symbol.for("ezlogs-nextjs:actor-storage")
463
489
  );
490
+ VALID_KINDS = /* @__PURE__ */ new Set(["human", "agent", "system", "hybrid"]);
464
491
  }
465
492
  });
466
493
 
@@ -853,7 +880,17 @@ var init_shared = __esm({
853
880
  "credit_card",
854
881
  "ssn",
855
882
  "social_security",
856
- "encrypted"
883
+ "encrypted",
884
+ "private_key",
885
+ "public_key",
886
+ "signing_key",
887
+ "pem",
888
+ "cipher",
889
+ "nonce",
890
+ "salt",
891
+ "digest",
892
+ "signature",
893
+ "hmac"
857
894
  ]);
858
895
  }
859
896
  });
@@ -1669,13 +1706,27 @@ function runWithAuditSnapshotScope(callback) {
1669
1706
  return storage3.run(0n, callback);
1670
1707
  }
1671
1708
 
1709
+ // src/triggers/emit-dedup.ts
1710
+ init_edge_fallback();
1711
+ var storage4 = createScopedStorage(
1712
+ /* @__PURE__ */ Symbol.for("ezlogs-nextjs:audit-emitted-ids-storage")
1713
+ );
1714
+ function currentEmittedAuditIds() {
1715
+ return storage4.read();
1716
+ }
1717
+ function runWithEmittedAuditIdsScope(callback) {
1718
+ const existing = storage4.read();
1719
+ if (existing !== null) return callback();
1720
+ return storage4.run(/* @__PURE__ */ new Set(), callback);
1721
+ }
1722
+
1672
1723
  // src/triggers/reader.ts
1673
1724
  async function readAuditRows(exec, correlationId, snapshotMaxId = null) {
1674
1725
  try {
1675
- const sql = snapshotMaxId === null ? `SELECT table_name, op, old_row, new_row, resource_id
1726
+ const sql = snapshotMaxId === null ? `SELECT id, table_name, op, old_row, new_row, resource_id
1676
1727
  FROM ezlogs_audit_log
1677
1728
  WHERE correlation_id = $1
1678
- ORDER BY id ASC` : `SELECT table_name, op, old_row, new_row, resource_id
1729
+ ORDER BY id ASC` : `SELECT id, table_name, op, old_row, new_row, resource_id
1679
1730
  FROM ezlogs_audit_log
1680
1731
  WHERE correlation_id = $1
1681
1732
  OR (correlation_id IS NULL AND id > $2)
@@ -1746,7 +1797,19 @@ async function flushAuditLog(exec) {
1746
1797
  const snapshot = currentAuditSnapshot();
1747
1798
  const rows = await readAuditRows(exec, correlationId, snapshot);
1748
1799
  if (rows.length === 0) return;
1749
- emitAuditRows(rows);
1800
+ const emitted = currentEmittedAuditIds();
1801
+ if (emitted === null) {
1802
+ emitAuditRows(rows);
1803
+ return;
1804
+ }
1805
+ const fresh = [];
1806
+ for (const row of rows) {
1807
+ if (row.id === "" || emitted.has(row.id)) continue;
1808
+ emitted.add(row.id);
1809
+ fresh.push(row);
1810
+ }
1811
+ if (fresh.length === 0) return;
1812
+ emitAuditRows(fresh);
1750
1813
  }
1751
1814
  function emitOne(row) {
1752
1815
  const op = mapOp(row.op);
@@ -1842,6 +1905,7 @@ function extractRows(result) {
1842
1905
  function normalizeAuditRow(raw) {
1843
1906
  const r = raw ?? {};
1844
1907
  return {
1908
+ id: r.id == null ? "" : String(r.id),
1845
1909
  table_name: String(r.table_name ?? ""),
1846
1910
  op: r.op,
1847
1911
  old_row: r.old_row ?? null,
@@ -1894,6 +1958,31 @@ function detect() {
1894
1958
 
1895
1959
  // src/http/capture.ts
1896
1960
  init_actor();
1961
+
1962
+ // src/user-agent-detector.ts
1963
+ var PATTERNS = [
1964
+ { prefix: "claude-", vendor: "claude", label: "Claude" },
1965
+ { prefix: "anthropic-", vendor: "claude", label: "Claude" },
1966
+ { prefix: "gpt-", vendor: "openai", label: "ChatGPT" },
1967
+ { prefix: "chatgpt-", vendor: "openai", label: "ChatGPT" },
1968
+ { prefix: "openai-", vendor: "openai", label: "ChatGPT" },
1969
+ { prefix: "cursor-", vendor: "cursor", label: "Cursor" },
1970
+ { prefix: "windsurf-", vendor: "windsurf", label: "Windsurf" }
1971
+ ];
1972
+ function classifyUserAgent(userAgent) {
1973
+ if (typeof userAgent !== "string" || userAgent.length === 0) return null;
1974
+ const ua = userAgent.toLowerCase();
1975
+ const match = PATTERNS.find((p) => ua.startsWith(p.prefix));
1976
+ if (!match) return null;
1977
+ return {
1978
+ kind: "agent",
1979
+ vendor: match.vendor,
1980
+ label: match.label,
1981
+ suggestedId: `agent:${match.vendor}`
1982
+ };
1983
+ }
1984
+
1985
+ // src/http/capture.ts
1897
1986
  init_correlation();
1898
1987
 
1899
1988
  // src/http/path-matcher.ts
@@ -1939,6 +2028,8 @@ var SENSITIVE_VARIABLE_PATTERNS = Object.freeze([
1939
2028
  "apikey",
1940
2029
  "private_key",
1941
2030
  "privatekey",
2031
+ "public_key",
2032
+ "signing_key",
1942
2033
  "secret_key",
1943
2034
  "secretkey",
1944
2035
  "credential",
@@ -1951,7 +2042,18 @@ var SENSITIVE_VARIABLE_PATTERNS = Object.freeze([
1951
2042
  "credit_card",
1952
2043
  "card_number",
1953
2044
  "cvv",
1954
- "cvc"
2045
+ "cvc",
2046
+ // Crypto-material patterns — aligned with DB_SENSITIVE_PATTERNS
2047
+ // (PR #45). Request bodies can carry the same key material as DB
2048
+ // columns (a webhook POST containing a `signature` field, an HMAC
2049
+ // header echoed into a JSON body, a `pem`-encoded cert blob, etc).
2050
+ "pem",
2051
+ "cipher",
2052
+ "nonce",
2053
+ "salt",
2054
+ "digest",
2055
+ "signature",
2056
+ "hmac"
1955
2057
  ]);
1956
2058
  var MAX_NESTING_DEPTH = 3;
1957
2059
  var MAX_ARRAY_DISPLAY_SIZE = 5;
@@ -2286,92 +2388,118 @@ function isPlainObject3(value) {
2286
2388
  // src/http/capture.ts
2287
2389
  function captureRoute(handler, context = {}) {
2288
2390
  return async (...args) => {
2289
- if (!configuration().captureHttp) {
2290
- return Promise.resolve(handler(...args));
2291
- }
2292
- const request = args[0];
2293
- if (!request || typeof request !== "object" || !("url" in request)) {
2294
- return Promise.resolve(handler(...args));
2295
- }
2296
- const snapshot = await snapshotRequest(request);
2297
- if (snapshot === null) return Promise.resolve(handler(...args));
2298
- const correlationId = resolveCorrelation(request.headers ?? null);
2299
- return runWithCorrelation(
2300
- correlationId,
2301
- () => runWithActorAndAuditScope(async () => {
2302
- await maybeRunActorHook(request);
2303
- const startMs = Date.now();
2304
- let statusCode = null;
2305
- let response = null;
2306
- let exception = null;
2307
- let graphqlErrorMessage = null;
2308
- try {
2309
- response = await Promise.resolve(handler(...args));
2310
- statusCode = response.status;
2311
- if (snapshot.graphqlBody !== null && response.status === 200) {
2312
- graphqlErrorMessage = await readGraphqlErrors(response);
2313
- }
2314
- return response;
2315
- } catch (e) {
2316
- exception = e instanceof Error ? e : new Error(String(e));
2317
- throw e;
2318
- } finally {
2319
- await maybeExtractSupabaseActor();
2320
- await emitEvent({
2321
- snapshot,
2322
- context,
2323
- statusCode,
2324
- exception,
2325
- graphqlErrorMessage,
2326
- durationMs: Date.now() - startMs,
2327
- startedAt: new Date(startMs)
2328
- });
2329
- if (isServerless()) {
2330
- await flushScheduler.flushNow().catch(() => {
2391
+ let handlerInvoked = false;
2392
+ const runHandler = (...invokeArgs) => {
2393
+ handlerInvoked = true;
2394
+ return handler(...invokeArgs);
2395
+ };
2396
+ try {
2397
+ if (!configuration().captureHttp) {
2398
+ return Promise.resolve(runHandler(...args));
2399
+ }
2400
+ const request = args[0];
2401
+ if (!request || typeof request !== "object" || !("url" in request)) {
2402
+ return Promise.resolve(runHandler(...args));
2403
+ }
2404
+ const snapshot = await snapshotRequest(request);
2405
+ if (snapshot === null) return Promise.resolve(runHandler(...args));
2406
+ const correlationId = resolveCorrelation(request.headers ?? null);
2407
+ return await runWithCorrelation(
2408
+ correlationId,
2409
+ () => runWithActorAndAuditScope(async () => {
2410
+ await maybeRunActorHook(request);
2411
+ const startMs = Date.now();
2412
+ let statusCode = null;
2413
+ let response = null;
2414
+ let exception = null;
2415
+ let graphqlErrorMessage = null;
2416
+ try {
2417
+ response = await Promise.resolve(runHandler(...args));
2418
+ statusCode = response.status;
2419
+ if (snapshot.graphqlBody !== null && response.status === 200) {
2420
+ graphqlErrorMessage = await readGraphqlErrors(response);
2421
+ }
2422
+ return response;
2423
+ } catch (e) {
2424
+ exception = e instanceof Error ? e : new Error(String(e));
2425
+ throw e;
2426
+ } finally {
2427
+ await maybeExtractSupabaseActor();
2428
+ await emitEvent({
2429
+ snapshot,
2430
+ context,
2431
+ statusCode,
2432
+ exception,
2433
+ graphqlErrorMessage,
2434
+ durationMs: Date.now() - startMs,
2435
+ startedAt: new Date(startMs)
2331
2436
  });
2437
+ if (isServerless()) {
2438
+ await flushScheduler.flushNow().catch(() => {
2439
+ });
2440
+ }
2332
2441
  }
2333
- }
2334
- })
2335
- );
2442
+ })
2443
+ );
2444
+ } catch (preCaptureError) {
2445
+ if (handlerInvoked) throw preCaptureError;
2446
+ logger.warn(
2447
+ `captureRoute pre-handler setup failed (${describeError7(preCaptureError)}); bypassing capture for this request`
2448
+ );
2449
+ return Promise.resolve(handler(...args));
2450
+ }
2336
2451
  };
2337
2452
  }
2338
2453
  var CORRELATION_HEADER2 = "x-ezlogs-correlation-id";
2339
2454
  function withMiddlewareCapture(middleware) {
2340
2455
  return async (request, ...rest) => {
2341
- const correlationId = resolveCorrelation(request.headers);
2456
+ let middlewareInvoked = false;
2457
+ const runMiddleware = (req, ...mRest) => {
2458
+ middlewareInvoked = true;
2459
+ return middleware(req, ...mRest);
2460
+ };
2342
2461
  try {
2343
- request.headers.set(CORRELATION_HEADER2, correlationId);
2344
- } catch {
2345
- }
2346
- return runWithCorrelation(
2347
- correlationId,
2348
- () => runWithActorAndAuditScope(async () => {
2349
- const startMs = Date.now();
2350
- const startedAt = new Date(startMs);
2351
- const response = await Promise.resolve(middleware(request, ...rest));
2352
- try {
2353
- if (response?.headers && typeof response.headers.set === "function") {
2354
- response.headers.set(CORRELATION_HEADER2, correlationId);
2462
+ const correlationId = resolveCorrelation(request.headers);
2463
+ try {
2464
+ request.headers.set(CORRELATION_HEADER2, correlationId);
2465
+ } catch {
2466
+ }
2467
+ return await runWithCorrelation(
2468
+ correlationId,
2469
+ () => runWithActorAndAuditScope(async () => {
2470
+ const startMs = Date.now();
2471
+ const startedAt = new Date(startMs);
2472
+ const response = await Promise.resolve(runMiddleware(request, ...rest));
2473
+ try {
2474
+ if (response?.headers && typeof response.headers.set === "function") {
2475
+ response.headers.set(CORRELATION_HEADER2, correlationId);
2476
+ }
2477
+ } catch {
2355
2478
  }
2356
- } catch {
2357
- }
2358
- try {
2359
- if (shouldEmitPageNavigation(request)) {
2360
- await maybeRunActorHook(request);
2361
- await maybeExtractSupabaseActor();
2362
- await emitPageNavigationEvent({
2363
- request,
2364
- statusCode: typeof response?.status === "number" ? response.status : null,
2365
- durationMs: Date.now() - startMs,
2366
- startedAt
2367
- });
2479
+ try {
2480
+ if (shouldEmitPageNavigation(request)) {
2481
+ await maybeRunActorHook(request);
2482
+ await maybeExtractSupabaseActor();
2483
+ await emitPageNavigationEvent({
2484
+ request,
2485
+ statusCode: typeof response?.status === "number" ? response.status : null,
2486
+ durationMs: Date.now() - startMs,
2487
+ startedAt
2488
+ });
2489
+ }
2490
+ } catch (error) {
2491
+ logger.debug(`page navigation capture failed: ${describeError7(error)}`);
2368
2492
  }
2369
- } catch (error) {
2370
- logger.debug(`page navigation capture failed: ${describeError7(error)}`);
2371
- }
2372
- return response;
2373
- })
2374
- );
2493
+ return response;
2494
+ })
2495
+ );
2496
+ } catch (preCaptureError) {
2497
+ if (middlewareInvoked) throw preCaptureError;
2498
+ logger.warn(
2499
+ `withMiddlewareCapture pre-handler setup failed (${describeError7(preCaptureError)}); bypassing capture for this request`
2500
+ );
2501
+ return await Promise.resolve(middleware(request, ...rest));
2502
+ }
2375
2503
  };
2376
2504
  }
2377
2505
  function shouldEmitPageNavigation(request) {
@@ -2445,106 +2573,132 @@ function pageControllerFromPath(pathname) {
2445
2573
  }
2446
2574
  function capturePagesApi(handler, context = {}) {
2447
2575
  return async (...args) => {
2448
- if (!configuration().captureHttp) {
2576
+ let handlerInvoked = false;
2577
+ const runHandler = (...invokeArgs) => {
2578
+ handlerInvoked = true;
2579
+ return handler(...invokeArgs);
2580
+ };
2581
+ try {
2582
+ if (!configuration().captureHttp) {
2583
+ return Promise.resolve(runHandler(...args));
2584
+ }
2585
+ const req = args[0];
2586
+ const res = args[1];
2587
+ if (!req || !res) return Promise.resolve(runHandler(...args));
2588
+ const snapshot = snapshotPagesRequest(req);
2589
+ if (snapshot === null) return Promise.resolve(runHandler(...args));
2590
+ const correlationId = resolveCorrelation({
2591
+ get: (name) => readPagesHeader(req, name)
2592
+ });
2593
+ return await runWithCorrelation(
2594
+ correlationId,
2595
+ () => runWithActorAndAuditScope(async () => {
2596
+ await maybeRunActorHookFromPages(req);
2597
+ const startMs = Date.now();
2598
+ let exception = null;
2599
+ try {
2600
+ const result = await Promise.resolve(runHandler(...args));
2601
+ return result;
2602
+ } catch (e) {
2603
+ exception = e instanceof Error ? e : new Error(String(e));
2604
+ throw e;
2605
+ } finally {
2606
+ await maybeExtractSupabaseActor();
2607
+ await emitEvent({
2608
+ snapshot,
2609
+ context,
2610
+ statusCode: typeof res.statusCode === "number" ? res.statusCode : null,
2611
+ exception,
2612
+ graphqlErrorMessage: null,
2613
+ durationMs: Date.now() - startMs,
2614
+ startedAt: new Date(startMs)
2615
+ });
2616
+ if (isServerless()) {
2617
+ await flushScheduler.flushNow().catch(() => void 0);
2618
+ }
2619
+ }
2620
+ })
2621
+ );
2622
+ } catch (preCaptureError) {
2623
+ if (handlerInvoked) throw preCaptureError;
2624
+ logger.warn(
2625
+ `capturePagesApi pre-handler setup failed (${describeError7(preCaptureError)}); bypassing capture for this request`
2626
+ );
2449
2627
  return Promise.resolve(handler(...args));
2450
2628
  }
2451
- const req = args[0];
2452
- const res = args[1];
2453
- if (!req || !res) return Promise.resolve(handler(...args));
2454
- const snapshot = snapshotPagesRequest(req);
2455
- if (snapshot === null) return Promise.resolve(handler(...args));
2456
- const correlationId = resolveCorrelation({
2457
- get: (name) => readPagesHeader(req, name)
2458
- });
2459
- return runWithCorrelation(
2460
- correlationId,
2461
- () => runWithActorAndAuditScope(async () => {
2462
- await maybeRunActorHookFromPages(req);
2463
- const startMs = Date.now();
2464
- let exception = null;
2465
- try {
2466
- const result = await Promise.resolve(handler(...args));
2467
- return result;
2468
- } catch (e) {
2469
- exception = e instanceof Error ? e : new Error(String(e));
2470
- throw e;
2471
- } finally {
2472
- await maybeExtractSupabaseActor();
2473
- await emitEvent({
2474
- snapshot,
2475
- context,
2476
- statusCode: typeof res.statusCode === "number" ? res.statusCode : null,
2477
- exception,
2478
- graphqlErrorMessage: null,
2479
- durationMs: Date.now() - startMs,
2480
- startedAt: new Date(startMs)
2481
- });
2482
- if (isServerless()) {
2483
- await flushScheduler.flushNow().catch(() => void 0);
2484
- }
2485
- }
2486
- })
2487
- );
2488
2629
  };
2489
2630
  }
2490
2631
  function captureServerAction(action, actionName) {
2491
2632
  return async (...args) => {
2492
- if (!configuration().captureHttp) {
2493
- return Promise.resolve(action(...args));
2494
- }
2495
- const headersAdapter = await readNextHeadersAsAdapter();
2496
- const correlationId = resolveCorrelation(headersAdapter);
2497
- return runWithCorrelation(
2498
- correlationId,
2499
- () => runWithActorAndAuditScope(async () => {
2500
- const startMs = Date.now();
2501
- const startedAt = new Date(startMs);
2502
- let exception = null;
2503
- await maybeRunActorHookFromServerAction();
2504
- try {
2505
- const result = await Promise.resolve(action(...args));
2506
- await maybeExtractSupabaseActor();
2507
- const failure = classifyServerActionResult(result);
2508
- await emitServerActionEvent({
2509
- actionName,
2510
- statusCode: failure ? 500 : 200,
2511
- exception: failure ? new Error(failure.errorMessage) : null,
2512
- durationMs: Date.now() - startMs,
2513
- startedAt,
2514
- args
2515
- });
2516
- return result;
2517
- } catch (e) {
2518
- if (isNextControlFlowError(e)) {
2633
+ let actionInvoked = false;
2634
+ const runAction = (...invokeArgs) => {
2635
+ actionInvoked = true;
2636
+ return action(...invokeArgs);
2637
+ };
2638
+ try {
2639
+ if (!configuration().captureHttp) {
2640
+ return Promise.resolve(runAction(...args));
2641
+ }
2642
+ const headersAdapter = await readNextHeadersAsAdapter();
2643
+ const correlationId = resolveCorrelation(headersAdapter);
2644
+ return await runWithCorrelation(
2645
+ correlationId,
2646
+ () => runWithActorAndAuditScope(async () => {
2647
+ const startMs = Date.now();
2648
+ const startedAt = new Date(startMs);
2649
+ let exception = null;
2650
+ await maybeRunActorHookFromServerAction();
2651
+ try {
2652
+ const result = await Promise.resolve(runAction(...args));
2519
2653
  await maybeExtractSupabaseActor();
2654
+ const failure = classifyServerActionResult(result);
2520
2655
  await emitServerActionEvent({
2521
2656
  actionName,
2522
- statusCode: 200,
2523
- exception: null,
2657
+ statusCode: failure ? 500 : 200,
2658
+ exception: failure ? new Error(failure.errorMessage) : null,
2659
+ durationMs: Date.now() - startMs,
2660
+ startedAt,
2661
+ args
2662
+ });
2663
+ return result;
2664
+ } catch (e) {
2665
+ if (isNextControlFlowError(e)) {
2666
+ await maybeExtractSupabaseActor();
2667
+ await emitServerActionEvent({
2668
+ actionName,
2669
+ statusCode: 200,
2670
+ exception: null,
2671
+ durationMs: Date.now() - startMs,
2672
+ startedAt,
2673
+ args
2674
+ });
2675
+ throw e;
2676
+ }
2677
+ exception = e instanceof Error ? e : new Error(String(e));
2678
+ await maybeExtractSupabaseActor();
2679
+ await emitServerActionEvent({
2680
+ actionName,
2681
+ statusCode: 500,
2682
+ exception,
2524
2683
  durationMs: Date.now() - startMs,
2525
2684
  startedAt,
2526
2685
  args
2527
2686
  });
2528
2687
  throw e;
2688
+ } finally {
2689
+ if (isServerless()) {
2690
+ await flushScheduler.flushNow().catch(() => void 0);
2691
+ }
2529
2692
  }
2530
- exception = e instanceof Error ? e : new Error(String(e));
2531
- await maybeExtractSupabaseActor();
2532
- await emitServerActionEvent({
2533
- actionName,
2534
- statusCode: 500,
2535
- exception,
2536
- durationMs: Date.now() - startMs,
2537
- startedAt,
2538
- args
2539
- });
2540
- throw e;
2541
- } finally {
2542
- if (isServerless()) {
2543
- await flushScheduler.flushNow().catch(() => void 0);
2544
- }
2545
- }
2546
- })
2547
- );
2693
+ })
2694
+ );
2695
+ } catch (preCaptureError) {
2696
+ if (actionInvoked) throw preCaptureError;
2697
+ logger.warn(
2698
+ `captureServerAction pre-handler setup failed (${describeError7(preCaptureError)}); bypassing capture for this action`
2699
+ );
2700
+ return Promise.resolve(action(...args));
2701
+ }
2548
2702
  };
2549
2703
  }
2550
2704
  function captureServerActionExport(value, actionName) {
@@ -2905,59 +3059,59 @@ async function snapshotRequest(request) {
2905
3059
  }
2906
3060
  async function maybeRunActorHook(request) {
2907
3061
  const hook = configuration().actorFromRequest;
2908
- if (!hook) return;
2909
- try {
2910
- const result = await Promise.resolve(hook(request));
2911
- setActor(result ?? null);
2912
- } catch (error) {
2913
- logger.debug(`actorFromRequest hook failed: ${describeError7(error)}`);
3062
+ let hookResult = null;
3063
+ if (hook) {
3064
+ try {
3065
+ hookResult = await Promise.resolve(hook(request));
3066
+ } catch (error) {
3067
+ logger.debug(`actorFromRequest hook failed: ${describeError7(error)}`);
3068
+ }
2914
3069
  }
3070
+ const userAgent = safeGetHeader(request.headers, "user-agent");
3071
+ applyActorFromHookAndUa(hookResult, userAgent);
2915
3072
  }
2916
3073
  async function maybeRunActorHookFromPages(req) {
2917
3074
  const hook = configuration().actorFromRequest;
2918
- if (!hook) return;
2919
- try {
2920
- const result = await Promise.resolve(hook(req));
2921
- setActor(result ?? null);
2922
- } catch (error) {
2923
- logger.debug(`actorFromRequest hook (pages) failed: ${describeError7(error)}`);
3075
+ let hookResult = null;
3076
+ if (hook) {
3077
+ try {
3078
+ hookResult = await Promise.resolve(hook(req));
3079
+ } catch (error) {
3080
+ logger.debug(`actorFromRequest hook (pages) failed: ${describeError7(error)}`);
3081
+ }
2924
3082
  }
3083
+ const userAgent = readPagesHeader(req, "user-agent");
3084
+ applyActorFromHookAndUa(hookResult, userAgent);
2925
3085
  }
2926
3086
  async function maybeRunActorHookFromServerAction() {
2927
3087
  const hook = configuration().actorFromRequest;
2928
- if (!hook) {
2929
- logger.debug("actorFromRequest hook (server action): no hook configured");
2930
- return;
2931
- }
2932
3088
  const headers = await loadNextHeaders();
2933
- if (!headers) {
2934
- logger.debug(
2935
- "actorFromRequest hook (server action): skipped, no next/headers available"
2936
- );
3089
+ if (!hook && !headers) {
3090
+ logger.debug("actorFromRequest (server action): no hook + no next/headers");
2937
3091
  return;
2938
3092
  }
2939
- const facade = {
2940
- headers,
2941
- method: "POST",
2942
- url: ""
2943
- };
2944
- try {
2945
- const result = await Promise.resolve(hook(facade));
2946
- if (result) {
3093
+ let hookResult = null;
3094
+ if (hook) {
3095
+ if (!headers) {
2947
3096
  logger.debug(
2948
- `actorFromRequest hook (server action): set actor id=${result.id ?? "?"}`
3097
+ "actorFromRequest hook (server action): skipped, no next/headers available"
2949
3098
  );
2950
3099
  } else {
2951
- logger.debug(
2952
- "actorFromRequest hook (server action): returned null/undefined"
2953
- );
3100
+ const facade = { headers, method: "POST", url: "" };
3101
+ try {
3102
+ hookResult = await Promise.resolve(hook(facade));
3103
+ logger.debug(
3104
+ hookResult ? `actorFromRequest hook (server action): set actor id=${hookResult.id ?? "?"}` : "actorFromRequest hook (server action): returned null/undefined"
3105
+ );
3106
+ } catch (error) {
3107
+ logger.debug(
3108
+ `actorFromRequest hook (server action) failed: ${describeError7(error)}`
3109
+ );
3110
+ }
2954
3111
  }
2955
- setActor(result ?? null);
2956
- } catch (error) {
2957
- logger.debug(
2958
- `actorFromRequest hook (server action) failed: ${describeError7(error)}`
2959
- );
2960
3112
  }
3113
+ const userAgent = headers ? safeGetHeader(headers, "user-agent") : null;
3114
+ applyActorFromHookAndUa(hookResult, userAgent);
2961
3115
  }
2962
3116
  async function maybeExtractSupabaseActor() {
2963
3117
  const config = configuration();
@@ -3040,14 +3194,29 @@ async function readNextHeadersAsAdapter() {
3040
3194
  };
3041
3195
  }
3042
3196
  async function loadNextHeaders() {
3197
+ const mod = await tryLoadNextHeadersModule();
3198
+ if (!mod) return null;
3043
3199
  try {
3044
- const mod = await import('next/headers');
3045
3200
  return await Promise.resolve(mod.headers());
3046
3201
  } catch (error) {
3047
- logger.debug(`loadNextHeaders failed: ${describeError7(error)}`);
3202
+ logger.debug(`loadNextHeaders mod.headers() failed: ${describeError7(error)}`);
3048
3203
  return null;
3049
3204
  }
3050
3205
  }
3206
+ async function tryLoadNextHeadersModule() {
3207
+ try {
3208
+ return await import('next/headers');
3209
+ } catch (firstError) {
3210
+ try {
3211
+ return await import('next/headers.js');
3212
+ } catch (secondError) {
3213
+ logger.debug(
3214
+ `loadNextHeaders: neither "next/headers" nor "next/headers.js" resolved (${describeError7(firstError)}; ${describeError7(secondError)})`
3215
+ );
3216
+ return null;
3217
+ }
3218
+ }
3219
+ }
3051
3220
  function readPagesHeader(req, name) {
3052
3221
  const raw = req.headers;
3053
3222
  if (raw instanceof Headers) return raw.get(name);
@@ -3105,7 +3274,9 @@ async function emitEvent(input) {
3105
3274
  });
3106
3275
  pushEvent(event);
3107
3276
  } catch (error) {
3108
- logger.error(`http capture emit failed: ${describeError7(error)}`);
3277
+ const cid = current();
3278
+ const cidLabel = cid ? ` (correlation_id=${cid})` : "";
3279
+ logger.error(`http capture emit failed${cidLabel}: ${describeError7(error)}`);
3109
3280
  }
3110
3281
  }
3111
3282
  function buildContext2() {
@@ -3125,13 +3296,19 @@ async function takeTriggerAuditSnapshotIfEnabled() {
3125
3296
  await takeAuditSnapshot(config.databaseReader);
3126
3297
  }
3127
3298
  function runWithActorAndAuditScope(callback) {
3128
- if (!configuration().databaseSnapshotMode) {
3299
+ const config = configuration();
3300
+ const hasReader = config.databaseReader != null;
3301
+ const snapshotEnabled = config.databaseSnapshotMode;
3302
+ if (!hasReader) {
3129
3303
  return runWithActorScope(callback);
3130
3304
  }
3131
3305
  return runWithActorScope(
3132
- () => runWithAuditSnapshotScope(async () => {
3133
- await takeTriggerAuditSnapshotIfEnabled();
3134
- return callback();
3306
+ () => runWithEmittedAuditIdsScope(() => {
3307
+ if (!snapshotEnabled) return callback();
3308
+ return runWithAuditSnapshotScope(async () => {
3309
+ await takeTriggerAuditSnapshotIfEnabled();
3310
+ return callback();
3311
+ });
3135
3312
  })
3136
3313
  );
3137
3314
  }
@@ -3185,15 +3362,58 @@ function describeError7(error) {
3185
3362
  if (error instanceof Error) return `${error.name}: ${error.message}`;
3186
3363
  return String(error);
3187
3364
  }
3365
+ function applyActorFromHookAndUa(hookResult, userAgent) {
3366
+ const uaMatch = classifyUserAgent(userAgent);
3367
+ if (hookResult != null && typeof hookResult === "object" && !Array.isArray(hookResult)) {
3368
+ if (uaMatch === null) {
3369
+ setActor(hookResult);
3370
+ return;
3371
+ }
3372
+ const hookObj = hookResult;
3373
+ const existingKind = hookObj.kind;
3374
+ if (typeof existingKind === "string" && existingKind.length > 0) {
3375
+ setActor(hookObj);
3376
+ return;
3377
+ }
3378
+ setActor({ ...hookObj, kind: uaMatch.kind });
3379
+ return;
3380
+ }
3381
+ if (uaMatch !== null) {
3382
+ setActor(synthesizeAgentActor(uaMatch));
3383
+ return;
3384
+ }
3385
+ setActor(null);
3386
+ }
3387
+ function synthesizeAgentActor(detection) {
3388
+ return {
3389
+ id: detection.suggestedId,
3390
+ label: detection.label,
3391
+ kind: detection.kind
3392
+ };
3393
+ }
3394
+ function safeGetHeader(headers, name) {
3395
+ try {
3396
+ return headers.get(name);
3397
+ } catch {
3398
+ return null;
3399
+ }
3400
+ }
3188
3401
 
3189
3402
  // src/index.ts
3190
3403
  var initialized = false;
3191
- var beforeExitInstalled = false;
3404
+ var BEFORE_EXIT_INSTALLED_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:beforeExitInstalled");
3405
+ function isBeforeExitInstalled() {
3406
+ return globalThis[BEFORE_EXIT_INSTALLED_KEY] === true;
3407
+ }
3408
+ function markBeforeExitInstalled() {
3409
+ globalThis[BEFORE_EXIT_INSTALLED_KEY] = true;
3410
+ }
3192
3411
  var ezlogs = {
3193
3412
  init(options) {
3194
3413
  const config = configuration();
3195
3414
  config.apply(options);
3196
3415
  if (options.logLevel) setLogLevel(options.logLevel);
3416
+ warnIfInsecureServerUrl(config.serverUrl, config.allowInsecureTransport);
3197
3417
  flushScheduler.start();
3198
3418
  if (config.patchGlobalFetch) patchGlobalFetch();
3199
3419
  const resolvedDbUrl = options.databaseUrl ?? detectDatabaseUrlFromEnv();
@@ -3303,12 +3523,29 @@ function runTriggerTrackedTablesDetection() {
3303
3523
  });
3304
3524
  }
3305
3525
  function installBeforeExitHook() {
3306
- if (beforeExitInstalled) return;
3526
+ if (isBeforeExitInstalled()) return;
3307
3527
  if (typeof process === "undefined" || !process.on) return;
3308
3528
  process.on("beforeExit", () => {
3309
3529
  void flushScheduler.flushNow();
3310
3530
  });
3311
- beforeExitInstalled = true;
3531
+ markBeforeExitInstalled();
3532
+ }
3533
+ function warnIfInsecureServerUrl(serverUrl, allowInsecure) {
3534
+ if (!serverUrl || allowInsecure) return;
3535
+ let parsed;
3536
+ try {
3537
+ parsed = new URL(serverUrl);
3538
+ } catch {
3539
+ return;
3540
+ }
3541
+ if (parsed.protocol === "https:") return;
3542
+ const host = parsed.hostname.toLowerCase();
3543
+ if (host === "localhost" || host === "127.0.0.1" || host === "[::1]" || host === "::1" || host.endsWith(".local")) {
3544
+ return;
3545
+ }
3546
+ console.warn(
3547
+ `[ezlogs] serverUrl is not HTTPS (${serverUrl}); events will be sent in cleartext. Set allowInsecureTransport: true to suppress this warning.`
3548
+ );
3312
3549
  }
3313
3550
  function _internalsForTests() {
3314
3551
  return { buffer: buffer_exports, flushScheduler };