ezlogs-nextjs 0.4.4 → 0.4.6

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 (65) hide show
  1. package/README.md +51 -11
  2. package/dist/actors/index.d.cts +1 -1
  3. package/dist/actors/index.d.ts +1 -1
  4. package/dist/{chunk-Z2TM3LGG.js → chunk-2NFJOT6Q.js} +1 -1
  5. package/dist/{chunk-R6IWVTX3.cjs → chunk-65HRY3PW.cjs} +31 -21
  6. package/dist/{chunk-YXZZNZG6.cjs → chunk-B3WST6ES.cjs} +9 -9
  7. package/dist/{chunk-MMLQXSSD.cjs → chunk-B5ZUQULZ.cjs} +18 -11
  8. package/dist/{chunk-NX4EL7BY.cjs → chunk-DM2EAOSF.cjs} +4 -4
  9. package/dist/chunk-DRE2VXFX.js +19 -0
  10. package/dist/chunk-H3FC5HMW.cjs +16 -0
  11. package/dist/{chunk-GI6BM4MR.js → chunk-IBSNHBUC.js} +18 -12
  12. package/dist/chunk-JWJKFZBW.js +52 -0
  13. package/dist/{chunk-MHBS5FEP.js → chunk-M3VBQ5KT.js} +27 -4
  14. package/dist/chunk-NFZ5OKF3.cjs +22 -0
  15. package/dist/{chunk-GMHOUAKD.cjs → chunk-O7SFYXJC.cjs} +37 -13
  16. package/dist/{chunk-U22T7QYY.js → chunk-PK2Z2ABL.js} +13 -3
  17. package/dist/{chunk-YMIGZYFH.js → chunk-RD47JECJ.js} +1 -1
  18. package/dist/chunk-RMKGMIV2.js +13 -0
  19. package/dist/{chunk-NINIAL7M.js → chunk-U3IJV5EJ.js} +1 -1
  20. package/dist/chunk-VJR4VB4B.cjs +56 -0
  21. package/dist/{chunk-PS4U2GFJ.cjs → chunk-YO6E763S.cjs} +5 -5
  22. package/dist/{configuration-CJ5yKVlP.d.cts → configuration-b9pImwFB.d.cts} +2 -2
  23. package/dist/{configuration-CJ5yKVlP.d.ts → configuration-b9pImwFB.d.ts} +2 -2
  24. package/dist/db/drizzle.cjs +3 -3
  25. package/dist/db/drizzle.js +2 -2
  26. package/dist/db/postgres-js.cjs +4 -4
  27. package/dist/db/postgres-js.js +2 -2
  28. package/dist/db/prisma.cjs +12 -12
  29. package/dist/db/prisma.js +2 -2
  30. package/dist/db/supabase.cjs +42 -17
  31. package/dist/db/supabase.d.cts +11 -5
  32. package/dist/db/supabase.d.ts +11 -5
  33. package/dist/db/supabase.js +33 -9
  34. package/dist/index.cjs +288 -142
  35. package/dist/index.d.cts +2 -2
  36. package/dist/index.d.ts +2 -2
  37. package/dist/index.js +198 -52
  38. package/dist/jobs/bullmq.cjs +44 -16
  39. package/dist/jobs/bullmq.d.cts +7 -1
  40. package/dist/jobs/bullmq.d.ts +7 -1
  41. package/dist/jobs/bullmq.js +33 -6
  42. package/dist/jobs/inngest.cjs +36 -17
  43. package/dist/jobs/inngest.d.cts +7 -1
  44. package/dist/jobs/inngest.d.ts +7 -1
  45. package/dist/jobs/inngest.js +23 -5
  46. package/dist/jobs/supabase-queues.cjs +9 -9
  47. package/dist/jobs/supabase-queues.js +4 -4
  48. package/dist/jobs/trigger.cjs +7 -7
  49. package/dist/jobs/trigger.js +4 -4
  50. package/dist/jobs/upstash-workflow.cjs +139 -23
  51. package/dist/jobs/upstash-workflow.d.cts +20 -2
  52. package/dist/jobs/upstash-workflow.d.ts +20 -2
  53. package/dist/jobs/upstash-workflow.js +129 -14
  54. package/dist/nextjs-plugin/index.cjs +46 -29
  55. package/dist/nextjs-plugin/index.js +46 -29
  56. package/dist/nextjs-plugin/loader.cjs +70 -60
  57. package/dist/nextjs-plugin/loader.d.cts +18 -1
  58. package/dist/nextjs-plugin/loader.d.ts +18 -1
  59. package/dist/nextjs-plugin/loader.js +70 -61
  60. package/dist/triggers/index.cjs +22 -16
  61. package/dist/triggers/index.d.cts +0 -10
  62. package/dist/triggers/index.d.ts +0 -10
  63. package/dist/triggers/index.js +11 -5
  64. package/package.json +1 -1
  65. package/sql/postgres/00_install.sql +20 -3
package/README.md CHANGED
@@ -73,6 +73,20 @@ export async function register() {
73
73
  `serverUrl` is optional: it defaults to `process.env.EZLOGS_SERVER_URL`
74
74
  if set, otherwise `https://app.ezlogs.io`. Set it only if you self-host.
75
75
 
76
+ **Who did it.** Every action shows the signed-in person. With Supabase
77
+ Auth there is nothing to add. Otherwise add one line to `ezlogs.init`:
78
+
79
+ | Your sign-in | Add to `ezlogs.init({ … })` |
80
+ |---|---|
81
+ | Auth.js (NextAuth v5) | `actorFromRequest: authJsActor({ auth })` (your `auth` from `auth.ts`) |
82
+ | NextAuth v4 | `actorFromRequest: nextAuthActor({ authOptions })` |
83
+ | Clerk | `actorFromRequest: clerkActor()` |
84
+ | Your own session or JWT | a small function, see [docs/auth.md](./docs/auth.md) |
85
+
86
+ ```ts
87
+ import { authJsActor } from "ezlogs-nextjs/actors"; // or nextAuthActor / clerkActor
88
+ ```
89
+
76
90
  ### 3. Wrap your Next config
77
91
 
78
92
  Registers the build-time loaders that auto-wrap your routes and Server
@@ -158,11 +172,15 @@ If `projectToken` is missing you get this instead:
158
172
  [ezlogs] not capturing: projectToken missing in ezlogs.init() (check EZLOGS_PROJECT_TOKEN)
159
173
  ```
160
174
 
161
- Sending to a local EZLogs server over plain `http://` (development)?
162
- Events are still sent, but the agent warns on every start; pass
175
+ Sending to a local EZLogs server over a non-localhost plain `http://`
176
+ address? Events are still sent, but the agent warns on every start; pass
163
177
  `allowInsecureTransport: true` to `ezlogs.init` to silence it. Keep
164
178
  `https://` in production.
165
179
 
180
+ `next dev` keeps reloading the page after you installed or upgraded the
181
+ agent? Stop it, delete the `.next` folder, and start it again: a dev
182
+ cache built before the change can keep invalidating itself.
183
+
166
184
  More in [docs/troubleshooting.md](./docs/troubleshooting.md).
167
185
 
168
186
  </details>
@@ -191,6 +209,9 @@ npm i pg # the trigger installer and reader need it
191
209
  npx ezlogs-nextjs install-triggers
192
210
  ```
193
211
 
212
+ The trigger path needs Postgres 10 or newer (Supabase, Neon, RDS and
213
+ every currently supported Postgres qualify).
214
+
194
215
  Supabase, Drizzle on node-postgres and raw `pg` need nothing else: the
195
216
  agent tags their writes itself, and the triggers record every write
196
217
  (supabase-js `.from()`, `.rpc()`, bulk) linked to its request.
@@ -233,7 +254,9 @@ agent tags their writes itself, and the triggers record every write
233
254
 
234
255
  Triggers **plus** this extension (plain `new PrismaClient()`, or with a
235
256
  driver adapter such as `@prisma/adapter-pg`). It tags each write with
236
- the request, so the change joins the right action and person.
257
+ the request, so the change joins the right action and person. Add
258
+ `.$extends(ezlogsPrisma())` where your app creates its client, and keep
259
+ your own import path (T3 apps import from `generated/prisma`).
237
260
 
238
261
  ```ts
239
262
  // lib/prisma.ts
@@ -306,17 +329,32 @@ at a quiet moment. Details in [CHANGELOG.md](./CHANGELOG.md).
306
329
 
307
330
  ### 6. Capture background jobs
308
331
 
309
- Only if you use a job runner. Wrap it once, and each job shows up in the
310
- same action as the request that started it, with the database changes
311
- the job made:
332
+ Nothing to add for the runners below. The Next config wrapper from step 3
333
+ instruments them where your server code imports them (aliases such as
334
+ `Client as WorkflowClient` included). Each job then shows up in the same
335
+ action as the request that started it, with the database changes the job
336
+ made:
337
+
338
+ | Runner | Instrumented imports |
339
+ |---|---|
340
+ | Upstash Workflow | `serve`, `servePagesRouter`, `createWorkflow`, `serveMany` from `@upstash/workflow/nextjs`; `Client` from `@upstash/workflow` |
341
+ | QStash | `Client` from `@upstash/qstash` |
342
+ | BullMQ | `Queue`, `Worker` from `bullmq` |
343
+ | Inngest (v3) | `Inngest` from `inngest` (gets `ezlogsInngestMiddleware()`); wrap a function body in `runInsideInngestCorrelation` to link its writes |
344
+
345
+ A workflow step or QStash delivery is one job event: the agent does not
346
+ also record the POST that delivered it.
347
+
348
+ Add these by hand ([docs/jobs.md](./docs/jobs.md)):
312
349
 
313
- | Runner | Add (snippets in [docs/jobs.md](./docs/jobs.md)) |
350
+ | Runner | Add |
314
351
  |---|---|
315
- | BullMQ | `wrapBullQueue` + `wrapBullWorker` from `ezlogs-nextjs/bullmq` |
316
- | Inngest (v3) | `ezlogsInngestMiddleware()` from `ezlogs-nextjs/inngest`, + `runInsideInngestCorrelation` around the body to link its writes |
317
352
  | Trigger.dev | `registerTriggerHooks(tasks)` from `ezlogs-nextjs/trigger` |
318
353
  | Supabase Queues (pgmq) | `wrapSupabaseQueueClient` + `captureQueueMessage` from `ezlogs-nextjs/supabase-queues` |
319
- | Upstash Workflow / QStash | `wrapWorkflowClient` / `wrapQStashClient` + `captureWorkflowRequest` from `ezlogs-nextjs/upstash-workflow` |
354
+ | Code Next doesn't build (a worker started with `node worker.js`), or `import * as` / `require()` | the same runner's wrapper: `wrapBullWorker`, `wrapWorkflowClient`, … (listed in [docs/jobs.md](./docs/jobs.md)) |
355
+
356
+ Wrapping by hand where the agent already instruments is harmless: each
357
+ job is still recorded once.
320
358
 
321
359
  **Jobs that run in a separate worker process** (for example a BullMQ
322
360
  worker you start with `node worker.js`) don't load `instrumentation.ts`.
@@ -380,7 +418,9 @@ logout / sign-in / sign-out / signin / signout / `/session*` path
380
418
  **Auth events are captured:** `POST`s to sign-in, sign-up, sign-out,
381
419
  login and logout routes (NextAuth / Auth.js `/api/auth/*`, custom
382
420
  `/api/login`, …) and auth Server Actions, including failed attempts
383
- (a 4xx response or a returned error). Passwords, tokens and other
421
+ (a 4xx response, a returned error, or a redirect whose target carries
422
+ `error=`, which is how Auth.js and NextAuth report a failed sign-in
423
+ from their API routes). Passwords, tokens and other
384
424
  sensitive params are sent as `"[FILTERED]"`; on auth routes and auth
385
425
  Server Actions (`signIn`, `verifyOtp`, …) one-time codes and OAuth
386
426
  state are too (`code`, `state`, `verification_code`, `otp*`, `pin`,
@@ -1,4 +1,4 @@
1
- import { a as ActorFromRequest } from '../configuration-CJ5yKVlP.cjs';
1
+ import { A as ActorFromRequest } from '../configuration-b9pImwFB.cjs';
2
2
 
3
3
  /**
4
4
  * Returns an `ActorFromRequest` that pulls the current user from
@@ -1,4 +1,4 @@
1
- import { a as ActorFromRequest } from '../configuration-CJ5yKVlP.js';
1
+ import { A as ActorFromRequest } from '../configuration-b9pImwFB.js';
2
2
 
3
3
  /**
4
4
  * Returns an `ActorFromRequest` that pulls the current user from
@@ -1,4 +1,4 @@
1
- import { makeAsyncContextCapture, getCurrentActor, current } from './chunk-GI6BM4MR.js';
1
+ import { makeAsyncContextCapture, getCurrentActor, current } from './chunk-IBSNHBUC.js';
2
2
  import { logger } from './chunk-FCFVIRQF.js';
3
3
 
4
4
  // src/triggers/patch-pg.ts
@@ -1,8 +1,8 @@
1
1
  'use strict';
2
2
 
3
- var chunkGMHOUAKD_cjs = require('./chunk-GMHOUAKD.cjs');
4
- var chunkYXZZNZG6_cjs = require('./chunk-YXZZNZG6.cjs');
5
- var chunkMMLQXSSD_cjs = require('./chunk-MMLQXSSD.cjs');
3
+ var chunkO7SFYXJC_cjs = require('./chunk-O7SFYXJC.cjs');
4
+ var chunkB3WST6ES_cjs = require('./chunk-B3WST6ES.cjs');
5
+ var chunkB5ZUQULZ_cjs = require('./chunk-B5ZUQULZ.cjs');
6
6
  var chunkTWTG5ILJ_cjs = require('./chunk-TWTG5ILJ.cjs');
7
7
 
8
8
  // src/jobs/shared.ts
@@ -12,7 +12,7 @@ var ACTOR_TOKEN = /^a([0-9a-f]{2,128})_([0-9a-f]{16})$/;
12
12
  var ACTOR_ID_MAX_BYTES = 64;
13
13
  function emitJobEvent(input) {
14
14
  try {
15
- const config = chunkMMLQXSSD_cjs.configuration();
15
+ const config = chunkB5ZUQULZ_cjs.configuration();
16
16
  if (!config.captureJobs) return;
17
17
  if (config.allExcludedJobClasses().includes(input.jobClass)) return;
18
18
  const sourceData = compactJobSourceData({
@@ -20,33 +20,39 @@ function emitJobEvent(input) {
20
20
  job_id: input.jobId ?? null,
21
21
  queue: input.queue ?? null,
22
22
  retry_count: input.retryCount ?? null,
23
+ step: input.step ?? null,
23
24
  arguments: jobArguments(input.payload)
24
25
  });
25
- const event = chunkYXZZNZG6_cjs.build({
26
+ const event = chunkB3WST6ES_cjs.build({
26
27
  source_type: "background_job",
27
28
  source_data: sourceData,
28
29
  outcome: input.outcome,
29
- correlation_id: input.correlationId ?? chunkMMLQXSSD_cjs.current(),
30
+ correlation_id: input.correlationId ?? chunkB5ZUQULZ_cjs.current(),
30
31
  resource_ids: [],
31
32
  context: null,
32
33
  duration_ms: input.durationMs ?? null,
33
34
  error_message: input.errorMessage ?? null,
34
35
  timestamp: input.startedAt
35
36
  });
36
- chunkYXZZNZG6_cjs.pushEvent(event);
37
+ chunkB3WST6ES_cjs.pushEvent(event);
37
38
  } catch (error) {
38
39
  chunkTWTG5ILJ_cjs.logger.debug(`job emit failed: ${describeError(error)}`);
39
40
  }
40
41
  }
41
42
  async function runJobWithCapture(meta, work) {
42
- const correlationId = meta.correlationId ?? chunkMMLQXSSD_cjs.generate();
43
+ const correlationId = meta.correlationId ?? chunkB5ZUQULZ_cjs.generate();
43
44
  const body = async () => {
44
45
  const startedAt = /* @__PURE__ */ new Date();
45
46
  const startMs = startedAt.getTime();
47
+ const step = meta.step;
46
48
  const baseMeta = {
47
49
  jobClass: meta.jobClass,
48
50
  jobId: meta.jobId ?? null,
49
51
  queue: meta.queue ?? null,
52
+ // Read when the event is built (after the run): the step it executed.
53
+ get step() {
54
+ return (typeof step === "function" ? step() : step) ?? null;
55
+ },
50
56
  retryCount: meta.retryCount ?? null,
51
57
  correlationId,
52
58
  startedAt,
@@ -65,6 +71,10 @@ async function runJobWithCapture(meta, work) {
65
71
  const message = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
66
72
  await flushJobAuditLog(startedAt);
67
73
  if (meta.isControlFlow?.(error)) throw error;
74
+ if (meta.isSuccessfulExit?.(error)) {
75
+ emitJobEvent({ ...baseMeta, outcome: "success", durationMs: Date.now() - startMs });
76
+ throw error;
77
+ }
68
78
  emitJobEvent({
69
79
  ...baseMeta,
70
80
  outcome: "failure",
@@ -74,13 +84,13 @@ async function runJobWithCapture(meta, work) {
74
84
  throw error;
75
85
  }
76
86
  };
77
- const scoped = () => body().finally(chunkMMLQXSSD_cjs.endCorrelationScope);
78
- return chunkMMLQXSSD_cjs.runWithCorrelation(correlationId, () => chunkMMLQXSSD_cjs.runWithActorScope(scoped, meta.actor ?? null));
87
+ const scoped = () => body().finally(chunkB5ZUQULZ_cjs.endCorrelationScope);
88
+ return chunkB5ZUQULZ_cjs.runWithCorrelation(correlationId, () => chunkB5ZUQULZ_cjs.runWithActorScope(scoped, meta.actor ?? null));
79
89
  }
80
90
  var JOB_FLUSH_SKEW_MS = 500;
81
91
  async function flushJobAuditLog(startedAt) {
82
92
  try {
83
- await chunkGMHOUAKD_cjs.flushAuditLog(chunkMMLQXSSD_cjs.configuration().databaseReader, {
93
+ await chunkO7SFYXJC_cjs.flushAuditLog(chunkB5ZUQULZ_cjs.configuration().databaseReader, {
84
94
  since: new Date(startedAt.getTime() - JOB_FLUSH_SKEW_MS)
85
95
  });
86
96
  } catch (error) {
@@ -89,16 +99,16 @@ async function flushJobAuditLog(startedAt) {
89
99
  }
90
100
  function jobArguments(payload) {
91
101
  if (payload === null || payload === void 0) return null;
92
- const patterns = chunkMMLQXSSD_cjs.configuration().excludedGraphqlVariableKeys;
93
- if (Array.isArray(payload)) return payload.length === 0 ? null : chunkYXZZNZG6_cjs.sanitizeArgs(payload, patterns);
102
+ const patterns = chunkB5ZUQULZ_cjs.configuration().excludedGraphqlVariableKeys;
103
+ if (Array.isArray(payload)) return payload.length === 0 ? null : chunkB3WST6ES_cjs.sanitizeArgs(payload, patterns);
94
104
  if (typeof payload === "object" && Object.getPrototypeOf(payload) === Object.prototype) {
95
105
  const rest = { ...payload };
96
106
  delete rest[CORRELATION_PAYLOAD_KEY];
97
107
  delete rest[ACTOR_PAYLOAD_KEY];
98
108
  if (Object.keys(rest).length === 0) return null;
99
- return chunkYXZZNZG6_cjs.sanitizeArgs([rest], patterns)[0];
109
+ return chunkB3WST6ES_cjs.sanitizeArgs([rest], patterns)[0];
100
110
  }
101
- return chunkYXZZNZG6_cjs.sanitizeArgs([payload], patterns);
111
+ return chunkB3WST6ES_cjs.sanitizeArgs([payload], patterns);
102
112
  }
103
113
  function extractCorrelationFromPayload(payload, key = CORRELATION_PAYLOAD_KEY) {
104
114
  if (payload === null || typeof payload !== "object") return null;
@@ -108,7 +118,7 @@ function extractCorrelationFromPayload(payload, key = CORRELATION_PAYLOAD_KEY) {
108
118
  function stampCorrelationOnPayload(payload, key = CORRELATION_PAYLOAD_KEY) {
109
119
  if (!payload || typeof payload !== "object") return payload;
110
120
  if (typeof payload[key] === "string" && payload[key]) return payload;
111
- const id = chunkMMLQXSSD_cjs.current();
121
+ const id = chunkB5ZUQULZ_cjs.current();
112
122
  if (!id) return payload;
113
123
  return { ...payload, [key]: id };
114
124
  }
@@ -126,10 +136,10 @@ function describeError(error) {
126
136
  }
127
137
  function pendingActorToken(correlationId) {
128
138
  try {
129
- const actor = chunkMMLQXSSD_cjs.getCurrentActor();
139
+ const actor = chunkB5ZUQULZ_cjs.getCurrentActor();
130
140
  if (!actor || actor.kind && actor.kind !== "human" || actor.principal) return null;
131
141
  const actorId = actor.id;
132
- const key = chunkMMLQXSSD_cjs.configuration().projectToken;
142
+ const key = chunkB5ZUQULZ_cjs.configuration().projectToken;
133
143
  if (!actorId || !key) return null;
134
144
  const bytes = new TextEncoder().encode(actorId);
135
145
  if (bytes.length > ACTOR_ID_MAX_BYTES) return null;
@@ -157,8 +167,8 @@ ${actorId}`;
157
167
  var tokenMemo = /* @__PURE__ */ new Map();
158
168
  function signedActorToken(correlationId) {
159
169
  const now = pendingActorToken(correlationId);
160
- if (now || chunkMMLQXSSD_cjs.getCurrentActor() || !chunkMMLQXSSD_cjs.configuration().actorFromSupabase) return now;
161
- return chunkMMLQXSSD_cjs.maybeExtractSupabaseActor().then(
170
+ if (now || chunkB5ZUQULZ_cjs.getCurrentActor() || !chunkB5ZUQULZ_cjs.configuration().actorFromSupabase) return now;
171
+ return chunkB5ZUQULZ_cjs.maybeExtractSupabaseActor().then(
162
172
  () => pendingActorToken(correlationId),
163
173
  () => null
164
174
  );
@@ -169,7 +179,7 @@ async function actorToken(correlationId) {
169
179
  async function readActorToken(token, correlationId) {
170
180
  try {
171
181
  const match = typeof token === "string" ? ACTOR_TOKEN.exec(token) : null;
172
- const key = chunkMMLQXSSD_cjs.configuration().projectToken;
182
+ const key = chunkB5ZUQULZ_cjs.configuration().projectToken;
173
183
  if (!match || !key || match[1].length % 2 !== 0) return null;
174
184
  const bytes = new Uint8Array(match[1].match(/../g).map((h) => parseInt(h, 16)));
175
185
  const actorId = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkMMLQXSSD_cjs = require('./chunk-MMLQXSSD.cjs');
3
+ var chunkB5ZUQULZ_cjs = require('./chunk-B5ZUQULZ.cjs');
4
4
  var chunkTWTG5ILJ_cjs = require('./chunk-TWTG5ILJ.cjs');
5
5
  var chunkZDSQYCYV_cjs = require('./chunk-ZDSQYCYV.cjs');
6
6
 
@@ -50,7 +50,7 @@ function clearBuffer() {
50
50
  }
51
51
  function maxSize() {
52
52
  try {
53
- return chunkMMLQXSSD_cjs.configuration().bufferSize;
53
+ return chunkB5ZUQULZ_cjs.configuration().bufferSize;
54
54
  } catch {
55
55
  return 1e4;
56
56
  }
@@ -541,10 +541,10 @@ var DB_SENSITIVE_PATTERNS = Object.freeze([
541
541
  ]);
542
542
  function emitDbEvent(input) {
543
543
  try {
544
- const config = chunkMMLQXSSD_cjs.configuration();
544
+ const config = chunkB5ZUQULZ_cjs.configuration();
545
545
  if (!config.captureDb) return;
546
546
  if (config.excludedTables.includes(input.modelClass)) return;
547
- if (chunkMMLQXSSD_cjs.DEFAULT_EXCLUDED_TABLES.includes(input.modelClass) && !(input._fromTrigger && isBusinessSessionRow(input.modelClass, input.modelInstance))) {
547
+ if (chunkB5ZUQULZ_cjs.DEFAULT_EXCLUDED_TABLES.includes(input.modelClass) && !(input._fromTrigger && isBusinessSessionRow(input.modelClass, input.modelInstance))) {
548
548
  return;
549
549
  }
550
550
  if (config.databaseReader && !input._fromTrigger) {
@@ -567,7 +567,7 @@ function emitDbEvent(input) {
567
567
  operation: input.operation
568
568
  },
569
569
  outcome: "success",
570
- correlation_id: chunkMMLQXSSD_cjs.current(),
570
+ correlation_id: chunkB5ZUQULZ_cjs.current(),
571
571
  resource_ids: resourceIdStr === null ? [...related] : [{ resource_type: input.modelClass, resource_id: resourceIdStr }],
572
572
  context,
573
573
  duration_ms: null,
@@ -580,7 +580,7 @@ function emitDbEvent(input) {
580
580
  }
581
581
  function buildContext(input) {
582
582
  const context = {};
583
- const actor = chunkMMLQXSSD_cjs.getCurrentActor();
583
+ const actor = chunkB5ZUQULZ_cjs.getCurrentActor();
584
584
  if (actor) context.actor = actor;
585
585
  if ((input.operation === "create" || input.operation === "destroy") && input.initialAttributes) {
586
586
  const filtered = filterMeaningfulAttributes(input.initialAttributes);
@@ -735,15 +735,15 @@ function isPrismaDecimal(value) {
735
735
  return typeof obj.toString === "function" && typeof obj.toFixed === "function" && "d" in obj && "e" in obj && "s" in obj;
736
736
  }
737
737
  function isBusinessSessionRow(table, row) {
738
- if (!chunkMMLQXSSD_cjs.AUTH_SESSION_TABLE_NAMES.test(table) || /verif/i.test(table) || !row) return false;
738
+ if (!chunkB5ZUQULZ_cjs.AUTH_SESSION_TABLE_NAMES.test(table) || /verif/i.test(table) || !row) return false;
739
739
  const columns = Object.keys(row);
740
- return columns.length > 0 && !columns.some(chunkMMLQXSSD_cjs.isSessionStoreColumn);
740
+ return columns.length > 0 && !columns.some(chunkB5ZUQULZ_cjs.isSessionStoreColumn);
741
741
  }
742
742
  var DISPLAY_NAME_COLUMNS = ["name", "title", "number", "label"];
743
743
  var MAX_DISPLAY_NAME_LENGTH = 120;
744
744
  function resolveDisplayName(modelClass, instance) {
745
745
  try {
746
- const config = chunkMMLQXSSD_cjs.configuration();
746
+ const config = chunkB5ZUQULZ_cjs.configuration();
747
747
  const resolver = config.displayNameFor[modelClass];
748
748
  const resolved = applyResolver(resolver, instance);
749
749
  if (resolved !== null) return resolved;
@@ -180,28 +180,34 @@ function configuration() {
180
180
  return g[GLOBAL_CONFIG_KEY];
181
181
  }
182
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("_");
183
+ // src/node-builtin.ts
184
+ function loadNodeBuiltin(name) {
185
+ const moduleName = "node:" + name;
189
186
  try {
190
187
  const getBuiltin = globalThis.process?.getBuiltinModule;
191
188
  if (typeof getBuiltin === "function") {
192
189
  const mod = getBuiltin(moduleName);
193
- if (typeof mod?.AsyncLocalStorage === "function") return mod.AsyncLocalStorage;
190
+ if (mod) return mod;
194
191
  }
195
192
  } catch {
196
193
  }
197
194
  try {
198
195
  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
- }
196
+ if (typeof req === "function") return req(moduleName);
203
197
  } catch {
204
198
  }
199
+ return null;
200
+ }
201
+
202
+ // src/edge-fallback.ts
203
+ var ALS_CTOR = loadAsyncLocalStorage();
204
+ function loadAsyncLocalStorage() {
205
+ const fromGlobal = globalThis.AsyncLocalStorage;
206
+ if (typeof fromGlobal === "function") return fromGlobal;
207
+ const mod = loadNodeBuiltin(
208
+ ["async", "hooks"].join("_")
209
+ );
210
+ if (typeof mod?.AsyncLocalStorage === "function") return mod.AsyncLocalStorage;
205
211
  warnNoAsyncLocalStorageOnNode();
206
212
  return null;
207
213
  }
@@ -453,6 +459,7 @@ exports.endCorrelationScope = endCorrelationScope;
453
459
  exports.generate = generate;
454
460
  exports.getCurrentActor = getCurrentActor;
455
461
  exports.isSessionStoreColumn = isSessionStoreColumn;
462
+ exports.loadNodeBuiltin = loadNodeBuiltin;
456
463
  exports.makeAsyncContextCapture = makeAsyncContextCapture;
457
464
  exports.maybeExtractSupabaseActor = maybeExtractSupabaseActor;
458
465
  exports.resolveCorrelation = resolveCorrelation;
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkMMLQXSSD_cjs = require('./chunk-MMLQXSSD.cjs');
3
+ var chunkB5ZUQULZ_cjs = require('./chunk-B5ZUQULZ.cjs');
4
4
  var chunkTWTG5ILJ_cjs = require('./chunk-TWTG5ILJ.cjs');
5
5
 
6
6
  // src/triggers/patch-pg.ts
@@ -28,7 +28,7 @@ function patchPgClient(pgModule) {
28
28
  function patchPgPool(Pool) {
29
29
  const proto = Pool?.prototype;
30
30
  if (!proto || typeof proto.connect !== "function" || proto._ezlogsPoolPatched) return;
31
- const captureAndRun = chunkMMLQXSSD_cjs.makeAsyncContextCapture();
31
+ const captureAndRun = chunkB5ZUQULZ_cjs.makeAsyncContextCapture();
32
32
  if (!captureAndRun) return;
33
33
  const originalConnect = proto.connect;
34
34
  proto.connect = function patchedConnect(...args) {
@@ -95,10 +95,10 @@ function runPatchedQuery(client, original, config, values, callback) {
95
95
  return wrapInTx(client, original, config, values, callback, ctx);
96
96
  }
97
97
  function snapshotContext() {
98
- const actor = chunkMMLQXSSD_cjs.getCurrentActor();
98
+ const actor = chunkB5ZUQULZ_cjs.getCurrentActor();
99
99
  return {
100
100
  actorId: actor && actor.id ? actor.id : null,
101
- correlationId: chunkMMLQXSSD_cjs.current()
101
+ correlationId: chunkB5ZUQULZ_cjs.current()
102
102
  };
103
103
  }
104
104
  async function injectAndRun(client, original, config, values, callback, ctx) {
@@ -0,0 +1,19 @@
1
+ // src/nextjs-plugin/instrumented-imports.ts
2
+ var INSTRUMENTED_IMPORTS = [
3
+ {
4
+ module: "@upstash/workflow/nextjs",
5
+ names: ["serve", "servePagesRouter", "createWorkflow", "createWorkflowPagesRouter", "serveMany", "serveManyPagesRouter"],
6
+ via: "upstash-workflow"
7
+ },
8
+ { module: "@upstash/workflow", names: ["serve", "Client"], via: "upstash-workflow" },
9
+ { module: "@upstash/qstash", names: ["Client"], via: "upstash-workflow" },
10
+ { module: "bullmq", names: ["Queue", "Worker"], via: "bullmq" },
11
+ { module: "inngest", names: ["Inngest"], via: "inngest" },
12
+ { module: "@supabase/supabase-js", names: ["createClient"], via: "supabase" },
13
+ { module: "@supabase/ssr", names: ["createServerClient"], via: "supabase" }
14
+ ];
15
+ var INSTRUMENTED_IMPORT_CONTENT = new RegExp(
16
+ `from\\s*["'](?:${[...new Set(INSTRUMENTED_IMPORTS.map((e) => e.module))].map((m) => m.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")).join("|")})["']`
17
+ );
18
+
19
+ export { INSTRUMENTED_IMPORTS, INSTRUMENTED_IMPORT_CONTENT };
@@ -0,0 +1,16 @@
1
+ 'use strict';
2
+
3
+ var chunkB5ZUQULZ_cjs = require('./chunk-B5ZUQULZ.cjs');
4
+
5
+ // src/job-delivery.ts
6
+ var storage = chunkB5ZUQULZ_cjs.createScopedStorage(/* @__PURE__ */ Symbol.for("ezlogs-nextjs:job-delivery"));
7
+ function runWithDeliverySlot(slot, callback) {
8
+ return storage.run(slot, callback);
9
+ }
10
+ function markJobDelivery() {
11
+ const slot = storage.read();
12
+ if (slot) slot.jobDelivery = true;
13
+ }
14
+
15
+ exports.markJobDelivery = markJobDelivery;
16
+ exports.runWithDeliverySlot = runWithDeliverySlot;
@@ -178,28 +178,34 @@ function configuration() {
178
178
  return g[GLOBAL_CONFIG_KEY];
179
179
  }
180
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("_");
181
+ // src/node-builtin.ts
182
+ function loadNodeBuiltin(name) {
183
+ const moduleName = "node:" + name;
187
184
  try {
188
185
  const getBuiltin = globalThis.process?.getBuiltinModule;
189
186
  if (typeof getBuiltin === "function") {
190
187
  const mod = getBuiltin(moduleName);
191
- if (typeof mod?.AsyncLocalStorage === "function") return mod.AsyncLocalStorage;
188
+ if (mod) return mod;
192
189
  }
193
190
  } catch {
194
191
  }
195
192
  try {
196
193
  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
- }
194
+ if (typeof req === "function") return req(moduleName);
201
195
  } catch {
202
196
  }
197
+ return null;
198
+ }
199
+
200
+ // src/edge-fallback.ts
201
+ var ALS_CTOR = loadAsyncLocalStorage();
202
+ function loadAsyncLocalStorage() {
203
+ const fromGlobal = globalThis.AsyncLocalStorage;
204
+ if (typeof fromGlobal === "function") return fromGlobal;
205
+ const mod = loadNodeBuiltin(
206
+ ["async", "hooks"].join("_")
207
+ );
208
+ if (typeof mod?.AsyncLocalStorage === "function") return mod.AsyncLocalStorage;
203
209
  warnNoAsyncLocalStorageOnNode();
204
210
  return null;
205
211
  }
@@ -440,4 +446,4 @@ function describe(value) {
440
446
  }
441
447
  }
442
448
 
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 };
449
+ export { AUTH_SESSION_TABLE_NAMES, DEFAULT_EXCLUDED_EXTENSIONS, DEFAULT_EXCLUDED_TABLES, configuration, createScopedStorage, current, currentActorSource, endCorrelationScope, generate, getCurrentActor, isSessionStoreColumn, loadNodeBuiltin, makeAsyncContextCapture, maybeExtractSupabaseActor, resolveCorrelation, runWithActorScope, runWithCorrelation, setActor };
@@ -0,0 +1,52 @@
1
+ import { logger } from './chunk-FCFVIRQF.js';
2
+
3
+ // src/instrument.ts
4
+ function instrumentFrom(replacements) {
5
+ return (key, original) => {
6
+ const replace = Object.prototype.hasOwnProperty.call(replacements, key) ? replacements[key] : void 0;
7
+ if (!replace) return original;
8
+ try {
9
+ return replace(original) ?? original;
10
+ } catch (error) {
11
+ logger.debug(`instrument ${key} failed (${error instanceof Error ? error.message : String(error)}); using the original`);
12
+ return original;
13
+ }
14
+ };
15
+ }
16
+ function instrumentClass(original, wrapInstance, mapArgs) {
17
+ if (typeof original !== "function") return original;
18
+ return new Proxy(original, {
19
+ construct(target, args, newTarget) {
20
+ let callArgs = args;
21
+ if (mapArgs) {
22
+ try {
23
+ callArgs = mapArgs(args);
24
+ } catch {
25
+ callArgs = args;
26
+ }
27
+ }
28
+ const instance = Reflect.construct(target, callArgs, newTarget);
29
+ try {
30
+ return wrapInstance(instance) ?? instance;
31
+ } catch {
32
+ return instance;
33
+ }
34
+ }
35
+ });
36
+ }
37
+ function instrumentFactory(original, wrapResult) {
38
+ if (typeof original !== "function") return original;
39
+ const factory = original;
40
+ return new Proxy(factory, {
41
+ apply(target, thisArg, args) {
42
+ const value = Reflect.apply(target, thisArg, args);
43
+ try {
44
+ return wrapResult(value) ?? value;
45
+ } catch {
46
+ return value;
47
+ }
48
+ }
49
+ });
50
+ }
51
+
52
+ export { instrumentClass, instrumentFactory, instrumentFrom };
@@ -1,5 +1,5 @@
1
- import { emitDbEvent } from './chunk-NINIAL7M.js';
2
- import { createScopedStorage, runWithCorrelation, getCurrentActor, runWithActorScope, current, generate } from './chunk-GI6BM4MR.js';
1
+ import { emitDbEvent } from './chunk-U3IJV5EJ.js';
2
+ import { createScopedStorage, runWithCorrelation, getCurrentActor, runWithActorScope, current, generate } from './chunk-IBSNHBUC.js';
3
3
  import { logger } from './chunk-FCFVIRQF.js';
4
4
 
5
5
  // src/triggers/emit-dedup.ts
@@ -218,7 +218,30 @@ function emitWithRowActor(row) {
218
218
  const actor = stored ? claimer?.id === stored ? claimer : { id: stored } : null;
219
219
  runWithActorScope(() => emitOne(row), actor);
220
220
  }
221
- async function flushAuditLog(exec, options = {}) {
221
+ var inFlightFlushes = /* @__PURE__ */ new Set();
222
+ var IN_FLIGHT_MAX_MS = 5e3;
223
+ function settleAuditFlushes(maxMs = IN_FLIGHT_MAX_MS) {
224
+ if (inFlightFlushes.size === 0) return Promise.resolve();
225
+ let timer;
226
+ return Promise.race([
227
+ Promise.allSettled([...inFlightFlushes]).then(() => void 0),
228
+ new Promise((resolve) => {
229
+ timer = setTimeout(resolve, maxMs);
230
+ timer.unref?.();
231
+ })
232
+ ]).finally(() => clearTimeout(timer));
233
+ }
234
+ function flushAuditLog(exec, options = {}) {
235
+ const work = readAndEmit(exec, options);
236
+ inFlightFlushes.add(work);
237
+ const done = () => inFlightFlushes.delete(work);
238
+ work.then(done, done);
239
+ const forget = setTimeout(done, IN_FLIGHT_MAX_MS);
240
+ forget.unref?.();
241
+ work.then(() => clearTimeout(forget), () => clearTimeout(forget));
242
+ return work;
243
+ }
244
+ async function readAndEmit(exec, options) {
222
245
  if (!exec) return;
223
246
  const correlationId = current();
224
247
  if (!correlationId) return;
@@ -523,4 +546,4 @@ function coerceJsonb(value) {
523
546
  return null;
524
547
  }
525
548
 
526
- export { auditLogInstalled, checkAuditLogAccess, detectTriggerTrackedTables, emitAuditRows, flushAuditLog, maintainAuditLogAfterRequests, pruneAuditLog, readAuditRows, runWithEmittedAuditIdsScope, sweepAuditLog };
549
+ export { auditLogInstalled, checkAuditLogAccess, detectTriggerTrackedTables, emitAuditRows, flushAuditLog, maintainAuditLogAfterRequests, pruneAuditLog, readAuditRows, runWithEmittedAuditIdsScope, settleAuditFlushes, sweepAuditLog };
@@ -0,0 +1,22 @@
1
+ 'use strict';
2
+
3
+ // src/nextjs-plugin/instrumented-imports.ts
4
+ var INSTRUMENTED_IMPORTS = [
5
+ {
6
+ module: "@upstash/workflow/nextjs",
7
+ names: ["serve", "servePagesRouter", "createWorkflow", "createWorkflowPagesRouter", "serveMany", "serveManyPagesRouter"],
8
+ via: "upstash-workflow"
9
+ },
10
+ { module: "@upstash/workflow", names: ["serve", "Client"], via: "upstash-workflow" },
11
+ { module: "@upstash/qstash", names: ["Client"], via: "upstash-workflow" },
12
+ { module: "bullmq", names: ["Queue", "Worker"], via: "bullmq" },
13
+ { module: "inngest", names: ["Inngest"], via: "inngest" },
14
+ { module: "@supabase/supabase-js", names: ["createClient"], via: "supabase" },
15
+ { module: "@supabase/ssr", names: ["createServerClient"], via: "supabase" }
16
+ ];
17
+ var INSTRUMENTED_IMPORT_CONTENT = new RegExp(
18
+ `from\\s*["'](?:${[...new Set(INSTRUMENTED_IMPORTS.map((e) => e.module))].map((m) => m.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")).join("|")})["']`
19
+ );
20
+
21
+ exports.INSTRUMENTED_IMPORTS = INSTRUMENTED_IMPORTS;
22
+ exports.INSTRUMENTED_IMPORT_CONTENT = INSTRUMENTED_IMPORT_CONTENT;