ezlogs-nextjs 0.4.4 → 0.4.7

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 +73 -13
  2. package/dist/actors/index.d.cts +1 -1
  3. package/dist/actors/index.d.ts +1 -1
  4. package/dist/{chunk-MMLQXSSD.cjs → chunk-2YCQFLXW.cjs} +21 -11
  5. package/dist/{chunk-YMIGZYFH.js → chunk-343ZGTMH.js} +1 -1
  6. package/dist/{chunk-Z2TM3LGG.js → chunk-5ZMOWEBY.js} +1 -1
  7. package/dist/{chunk-GI6BM4MR.js → chunk-7MFKEYDN.js} +21 -12
  8. package/dist/{chunk-NINIAL7M.js → chunk-AXIQTU52.js} +1 -1
  9. package/dist/chunk-BE3RCFNP.js +13 -0
  10. package/dist/chunk-CHVJ4WPM.cjs +16 -0
  11. package/dist/{chunk-MHBS5FEP.js → chunk-CYAFYBKF.js} +27 -4
  12. package/dist/chunk-DRE2VXFX.js +19 -0
  13. package/dist/{chunk-GMHOUAKD.cjs → chunk-EXGEA4KE.cjs} +37 -13
  14. package/dist/{chunk-PS4U2GFJ.cjs → chunk-JB4UYCZI.cjs} +5 -5
  15. package/dist/chunk-JWJKFZBW.js +52 -0
  16. package/dist/{chunk-R6IWVTX3.cjs → chunk-KOFR5OC3.cjs} +31 -21
  17. package/dist/chunk-NFZ5OKF3.cjs +22 -0
  18. package/dist/{chunk-U22T7QYY.js → chunk-Q3HRVWCS.js} +13 -3
  19. package/dist/{chunk-YXZZNZG6.cjs → chunk-UC2KS5EG.cjs} +9 -9
  20. package/dist/chunk-VJR4VB4B.cjs +56 -0
  21. package/dist/{chunk-NX4EL7BY.cjs → chunk-XWEBKN65.cjs} +4 -4
  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 +303 -142
  35. package/dist/index.d.cts +2 -2
  36. package/dist/index.d.ts +2 -2
  37. package/dist/index.js +213 -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 +171 -48
  43. package/dist/jobs/inngest.d.cts +13 -7
  44. package/dist/jobs/inngest.d.ts +13 -7
  45. package/dist/jobs/inngest.js +162 -40
  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 +104 -65
  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 +104 -66
  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
@@ -53,6 +53,10 @@ npm install ezlogs-nextjs
53
53
  # or: pnpm add ezlogs-nextjs / bun add ezlogs-nextjs
54
54
  ```
55
55
 
56
+ On a Next.js canary or release candidate, npm stops with `ERESOLVE`
57
+ (npm never counts a pre-release as matching the `next >=14` peer range).
58
+ Add `--legacy-peer-deps` to that install; pnpm and bun only warn.
59
+
56
60
  ### 2. Add `instrumentation.ts`
57
61
 
58
62
  Starts the agent when your server boots. Put it at the project root
@@ -73,6 +77,35 @@ export async function register() {
73
77
  `serverUrl` is optional: it defaults to `process.env.EZLOGS_SERVER_URL`
74
78
  if set, otherwise `https://app.ezlogs.io`. Set it only if you self-host.
75
79
 
80
+ **Who did it.** Every action shows the signed-in person. With Supabase
81
+ Auth there is nothing to add. Otherwise add one line to `ezlogs.init`:
82
+
83
+ | Your sign-in | Add to `ezlogs.init({ … })` |
84
+ |---|---|
85
+ | Auth.js (NextAuth v5) | `actorFromRequest: authJsActor({ auth })` (your `auth` from `auth.ts`) |
86
+ | NextAuth v4 | `actorFromRequest: nextAuthActor({ authOptions })` |
87
+ | Clerk | `actorFromRequest: clerkActor()` |
88
+ | Your own session or JWT | a small function, see [docs/auth.md](./docs/auth.md) |
89
+
90
+ ```ts
91
+ import { authJsActor } from "ezlogs-nextjs/actors"; // or nextAuthActor / clerkActor
92
+ ```
93
+
94
+ Import your own `auth` / `authOptions` inside the `nodejs` branch, with
95
+ `await import`: `instrumentation.ts` is also built for the Edge runtime,
96
+ and an auth module that loads your database client (Prisma, `pg`) breaks
97
+ that build when imported at the top of the file.
98
+
99
+ ```ts
100
+ if (process.env.NEXT_RUNTIME === "nodejs") {
101
+ const { auth } = await import("@/auth"); // or: const { authOptions } = await import("@/lib/auth");
102
+ ezlogs.init({
103
+ projectToken: process.env.EZLOGS_PROJECT_TOKEN!,
104
+ actorFromRequest: authJsActor({ auth }),
105
+ });
106
+ }
107
+ ```
108
+
76
109
  ### 3. Wrap your Next config
77
110
 
78
111
  Registers the build-time loaders that auto-wrap your routes and Server
@@ -158,11 +191,15 @@ If `projectToken` is missing you get this instead:
158
191
  [ezlogs] not capturing: projectToken missing in ezlogs.init() (check EZLOGS_PROJECT_TOKEN)
159
192
  ```
160
193
 
161
- Sending to a local EZLogs server over plain `http://` (development)?
162
- Events are still sent, but the agent warns on every start; pass
194
+ Sending to a local EZLogs server over a non-localhost plain `http://`
195
+ address? Events are still sent, but the agent warns on every start; pass
163
196
  `allowInsecureTransport: true` to `ezlogs.init` to silence it. Keep
164
197
  `https://` in production.
165
198
 
199
+ `next dev` keeps reloading the page after you installed or upgraded the
200
+ agent? Stop it, delete the `.next` folder, and start it again: a dev
201
+ cache built before the change can keep invalidating itself.
202
+
166
203
  More in [docs/troubleshooting.md](./docs/troubleshooting.md).
167
204
 
168
205
  </details>
@@ -191,6 +228,9 @@ npm i pg # the trigger installer and reader need it
191
228
  npx ezlogs-nextjs install-triggers
192
229
  ```
193
230
 
231
+ The trigger path needs Postgres 10 or newer (Supabase, Neon, RDS and
232
+ every currently supported Postgres qualify).
233
+
194
234
  Supabase, Drizzle on node-postgres and raw `pg` need nothing else: the
195
235
  agent tags their writes itself, and the triggers record every write
196
236
  (supabase-js `.from()`, `.rpc()`, bulk) linked to its request.
@@ -233,7 +273,9 @@ agent tags their writes itself, and the triggers record every write
233
273
 
234
274
  Triggers **plus** this extension (plain `new PrismaClient()`, or with a
235
275
  driver adapter such as `@prisma/adapter-pg`). It tags each write with
236
- the request, so the change joins the right action and person.
276
+ the request, so the change joins the right action and person. Add
277
+ `.$extends(ezlogsPrisma())` where your app creates its client, and keep
278
+ your own import path (T3 apps import from `generated/prisma`).
237
279
 
238
280
  ```ts
239
281
  // lib/prisma.ts
@@ -306,17 +348,32 @@ at a quiet moment. Details in [CHANGELOG.md](./CHANGELOG.md).
306
348
 
307
349
  ### 6. Capture background jobs
308
350
 
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:
351
+ Nothing to add for the runners below. The Next config wrapper from step 3
352
+ instruments them where your server code imports them (aliases such as
353
+ `Client as WorkflowClient` included). Each job then shows up in the same
354
+ action as the request that started it, with the database changes the job
355
+ made:
312
356
 
313
- | Runner | Add (snippets in [docs/jobs.md](./docs/jobs.md)) |
357
+ | Runner | Instrumented imports |
358
+ |---|---|
359
+ | Upstash Workflow | `serve`, `servePagesRouter`, `createWorkflow`, `serveMany` from `@upstash/workflow/nextjs`; `Client` from `@upstash/workflow` |
360
+ | QStash | `Client` from `@upstash/qstash` |
361
+ | BullMQ | `Queue`, `Worker` from `bullmq` |
362
+ | Inngest (v3, v4) | `Inngest` from `inngest` (gets `ezlogsInngestMiddleware()`); on v3, wrap a function body in `runInsideInngestCorrelation` to link its writes |
363
+
364
+ A workflow step or QStash delivery is one job event: the agent does not
365
+ also record the POST that delivered it.
366
+
367
+ Add these by hand ([docs/jobs.md](./docs/jobs.md)):
368
+
369
+ | Runner | Add |
314
370
  |---|---|
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
371
  | Trigger.dev | `registerTriggerHooks(tasks)` from `ezlogs-nextjs/trigger` |
318
372
  | Supabase Queues (pgmq) | `wrapSupabaseQueueClient` + `captureQueueMessage` from `ezlogs-nextjs/supabase-queues` |
319
- | Upstash Workflow / QStash | `wrapWorkflowClient` / `wrapQStashClient` + `captureWorkflowRequest` from `ezlogs-nextjs/upstash-workflow` |
373
+ | 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)) |
374
+
375
+ Wrapping by hand where the agent already instruments is harmless: each
376
+ job is still recorded once.
320
377
 
321
378
  **Jobs that run in a separate worker process** (for example a BullMQ
322
379
  worker you start with `node worker.js`) don't load `instrumentation.ts`.
@@ -350,8 +407,9 @@ ezlogs.init({
350
407
  });
351
408
  ```
352
409
 
353
- The key is the table name for trigger-captured changes (`users`) and
354
- the model name for the per-ORM adapters (`User`). Without it, the
410
+ The key is the database table name (`users`) and the row has the
411
+ database column names; only the Prisma adapter used without triggers
412
+ keys by the model name (`User`). Without it, the
355
413
  record shows by its id.
356
414
 
357
415
  ---
@@ -380,7 +438,9 @@ logout / sign-in / sign-out / signin / signout / `/session*` path
380
438
  **Auth events are captured:** `POST`s to sign-in, sign-up, sign-out,
381
439
  login and logout routes (NextAuth / Auth.js `/api/auth/*`, custom
382
440
  `/api/login`, …) and auth Server Actions, including failed attempts
383
- (a 4xx response or a returned error). Passwords, tokens and other
441
+ (a 4xx response, a returned error, or a redirect whose target carries
442
+ `error=`, which is how Auth.js and NextAuth report a failed sign-in
443
+ from their API routes). Passwords, tokens and other
384
444
  sensitive params are sent as `"[FILTERED]"`; on auth routes and auth
385
445
  Server Actions (`signIn`, `verifyOtp`, …) one-time codes and OAuth
386
446
  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
@@ -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
  }
@@ -276,6 +282,7 @@ function createScopedStorage(key = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:def
276
282
 
277
283
  // src/correlation.ts
278
284
  var CORRELATION_HEADER = "x-ezlogs-correlation-id";
285
+ var CROSS_SERVICE_HEADER = "x-correlation-id";
279
286
  var PLATFORM_REQUEST_ID_HEADERS = [
280
287
  "x-vercel-id",
281
288
  "cf-ray",
@@ -304,6 +311,8 @@ function resolveCorrelation(headers) {
304
311
  if (!headers) return generate();
305
312
  const ezlogs = safeRead(headers, CORRELATION_HEADER);
306
313
  if (ezlogs && isTrustedInboundId(ezlogs)) return ezlogs;
314
+ const crossService = safeRead(headers, CROSS_SERVICE_HEADER);
315
+ if (crossService && isTrustedInboundId(crossService)) return crossService;
307
316
  for (const name of PLATFORM_REQUEST_ID_HEADERS) {
308
317
  const platformId = safeRead(headers, name);
309
318
  if (platformId) return wrapPlatformId(platformId);
@@ -453,6 +462,7 @@ exports.endCorrelationScope = endCorrelationScope;
453
462
  exports.generate = generate;
454
463
  exports.getCurrentActor = getCurrentActor;
455
464
  exports.isSessionStoreColumn = isSessionStoreColumn;
465
+ exports.loadNodeBuiltin = loadNodeBuiltin;
456
466
  exports.makeAsyncContextCapture = makeAsyncContextCapture;
457
467
  exports.maybeExtractSupabaseActor = maybeExtractSupabaseActor;
458
468
  exports.resolveCorrelation = resolveCorrelation;
@@ -1,4 +1,4 @@
1
- import { getCurrentActor, current } from './chunk-GI6BM4MR.js';
1
+ import { getCurrentActor, current } from './chunk-7MFKEYDN.js';
2
2
  import { logger } from './chunk-FCFVIRQF.js';
3
3
 
4
4
  // src/triggers/context.ts
@@ -1,4 +1,4 @@
1
- import { makeAsyncContextCapture, getCurrentActor, current } from './chunk-GI6BM4MR.js';
1
+ import { makeAsyncContextCapture, getCurrentActor, current } from './chunk-7MFKEYDN.js';
2
2
  import { logger } from './chunk-FCFVIRQF.js';
3
3
 
4
4
  // src/triggers/patch-pg.ts
@@ -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
  }
@@ -274,6 +280,7 @@ function createScopedStorage(key = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:def
274
280
 
275
281
  // src/correlation.ts
276
282
  var CORRELATION_HEADER = "x-ezlogs-correlation-id";
283
+ var CROSS_SERVICE_HEADER = "x-correlation-id";
277
284
  var PLATFORM_REQUEST_ID_HEADERS = [
278
285
  "x-vercel-id",
279
286
  "cf-ray",
@@ -302,6 +309,8 @@ function resolveCorrelation(headers) {
302
309
  if (!headers) return generate();
303
310
  const ezlogs = safeRead(headers, CORRELATION_HEADER);
304
311
  if (ezlogs && isTrustedInboundId(ezlogs)) return ezlogs;
312
+ const crossService = safeRead(headers, CROSS_SERVICE_HEADER);
313
+ if (crossService && isTrustedInboundId(crossService)) return crossService;
305
314
  for (const name of PLATFORM_REQUEST_ID_HEADERS) {
306
315
  const platformId = safeRead(headers, name);
307
316
  if (platformId) return wrapPlatformId(platformId);
@@ -440,4 +449,4 @@ function describe(value) {
440
449
  }
441
450
  }
442
451
 
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 };
452
+ 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 };
@@ -1,4 +1,4 @@
1
- import { configuration, DEFAULT_EXCLUDED_TABLES, current, getCurrentActor, AUTH_SESSION_TABLE_NAMES, isSessionStoreColumn } from './chunk-GI6BM4MR.js';
1
+ import { configuration, DEFAULT_EXCLUDED_TABLES, current, getCurrentActor, AUTH_SESSION_TABLE_NAMES, isSessionStoreColumn } from './chunk-7MFKEYDN.js';
2
2
  import { logger } from './chunk-FCFVIRQF.js';
3
3
  import { __export } from './chunk-SIAA4J6H.js';
4
4
 
@@ -0,0 +1,13 @@
1
+ import { createScopedStorage } from './chunk-7MFKEYDN.js';
2
+
3
+ // src/job-delivery.ts
4
+ var storage = createScopedStorage(/* @__PURE__ */ Symbol.for("ezlogs-nextjs:job-delivery"));
5
+ function runWithDeliverySlot(slot, callback) {
6
+ return storage.run(slot, callback);
7
+ }
8
+ function markJobDelivery() {
9
+ const slot = storage.read();
10
+ if (slot) slot.jobDelivery = true;
11
+ }
12
+
13
+ export { markJobDelivery, runWithDeliverySlot };
@@ -0,0 +1,16 @@
1
+ 'use strict';
2
+
3
+ var chunk2YCQFLXW_cjs = require('./chunk-2YCQFLXW.cjs');
4
+
5
+ // src/job-delivery.ts
6
+ var storage = chunk2YCQFLXW_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;
@@ -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-AXIQTU52.js';
2
+ import { createScopedStorage, runWithCorrelation, getCurrentActor, runWithActorScope, current, generate } from './chunk-7MFKEYDN.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,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 };
@@ -1,11 +1,11 @@
1
1
  'use strict';
2
2
 
3
- var chunkYXZZNZG6_cjs = require('./chunk-YXZZNZG6.cjs');
4
- var chunkMMLQXSSD_cjs = require('./chunk-MMLQXSSD.cjs');
3
+ var chunkUC2KS5EG_cjs = require('./chunk-UC2KS5EG.cjs');
4
+ var chunk2YCQFLXW_cjs = require('./chunk-2YCQFLXW.cjs');
5
5
  var chunkTWTG5ILJ_cjs = require('./chunk-TWTG5ILJ.cjs');
6
6
 
7
7
  // src/triggers/emit-dedup.ts
8
- var storage = chunkMMLQXSSD_cjs.createScopedStorage(
8
+ var storage = chunk2YCQFLXW_cjs.createScopedStorage(
9
9
  /* @__PURE__ */ Symbol.for("ezlogs-nextjs:audit-emitted-ids-storage")
10
10
  );
11
11
  function currentEmittedAuditIds() {
@@ -103,7 +103,7 @@ async function sweepAuditLog(exec) {
103
103
  await loadTableMeta(exec, rows);
104
104
  for (const row of rows) {
105
105
  const correlationId = row.correlation_id ?? correlationForTx(row.txid);
106
- chunkMMLQXSSD_cjs.runWithCorrelation(correlationId, () => emitWithRowActor(row));
106
+ chunk2YCQFLXW_cjs.runWithCorrelation(correlationId, () => emitWithRowActor(row));
107
107
  }
108
108
  return rows.length;
109
109
  } catch (err) {
@@ -216,13 +216,36 @@ function emitAuditRows(rows) {
216
216
  }
217
217
  function emitWithRowActor(row) {
218
218
  const stored = row.actor_id || null;
219
- const claimer = chunkMMLQXSSD_cjs.getCurrentActor();
219
+ const claimer = chunk2YCQFLXW_cjs.getCurrentActor();
220
220
  const actor = stored ? claimer?.id === stored ? claimer : { id: stored } : null;
221
- chunkMMLQXSSD_cjs.runWithActorScope(() => emitOne(row), actor);
221
+ chunk2YCQFLXW_cjs.runWithActorScope(() => emitOne(row), actor);
222
222
  }
223
- async function flushAuditLog(exec, options = {}) {
223
+ var inFlightFlushes = /* @__PURE__ */ new Set();
224
+ var IN_FLIGHT_MAX_MS = 5e3;
225
+ function settleAuditFlushes(maxMs = IN_FLIGHT_MAX_MS) {
226
+ if (inFlightFlushes.size === 0) return Promise.resolve();
227
+ let timer;
228
+ return Promise.race([
229
+ Promise.allSettled([...inFlightFlushes]).then(() => void 0),
230
+ new Promise((resolve) => {
231
+ timer = setTimeout(resolve, maxMs);
232
+ timer.unref?.();
233
+ })
234
+ ]).finally(() => clearTimeout(timer));
235
+ }
236
+ function flushAuditLog(exec, options = {}) {
237
+ const work = readAndEmit(exec, options);
238
+ inFlightFlushes.add(work);
239
+ const done = () => inFlightFlushes.delete(work);
240
+ work.then(done, done);
241
+ const forget = setTimeout(done, IN_FLIGHT_MAX_MS);
242
+ forget.unref?.();
243
+ work.then(() => clearTimeout(forget), () => clearTimeout(forget));
244
+ return work;
245
+ }
246
+ async function readAndEmit(exec, options) {
224
247
  if (!exec) return;
225
- const correlationId = chunkMMLQXSSD_cjs.current();
248
+ const correlationId = chunk2YCQFLXW_cjs.current();
226
249
  if (!correlationId) return;
227
250
  lastRequestFlushAt = Date.now();
228
251
  const rows = await readAuditRows(exec, correlationId, options.since ?? null);
@@ -365,11 +388,11 @@ function emitFresh(rows) {
365
388
  emitAuditRows(fresh);
366
389
  }
367
390
  function correlationForTx(txid) {
368
- if (!txid) return chunkMMLQXSSD_cjs.generate();
391
+ if (!txid) return chunk2YCQFLXW_cjs.generate();
369
392
  let id = txCorrelation.get(txid);
370
393
  if (!id) {
371
394
  if (txCorrelation.size >= 1e3) txCorrelation.clear();
372
- id = chunkMMLQXSSD_cjs.generate();
395
+ id = chunk2YCQFLXW_cjs.generate();
373
396
  txCorrelation.set(txid, id);
374
397
  }
375
398
  return id;
@@ -390,7 +413,7 @@ function emitOne(row) {
390
413
  const newRow = withUtcTimestamps(coerceJsonb(row.new_row), naive);
391
414
  const related = row.resource_id === null ? relatedResourceIds(row.table_name, newRow ?? oldRow ?? {}) : null;
392
415
  if (op === "create" && newRow) {
393
- chunkYXZZNZG6_cjs.emitDbEvent({
416
+ chunkUC2KS5EG_cjs.emitDbEvent({
394
417
  modelClass: row.table_name,
395
418
  operation: "create",
396
419
  resourceId: row.resource_id,
@@ -408,7 +431,7 @@ function emitOne(row) {
408
431
  if (changes.length === 0) {
409
432
  return;
410
433
  }
411
- chunkYXZZNZG6_cjs.emitDbEvent({
434
+ chunkUC2KS5EG_cjs.emitDbEvent({
412
435
  modelClass: row.table_name,
413
436
  operation: "update",
414
437
  resourceId: row.resource_id,
@@ -424,7 +447,7 @@ function emitOne(row) {
424
447
  return;
425
448
  }
426
449
  if (op === "destroy" && oldRow) {
427
- chunkYXZZNZG6_cjs.emitDbEvent({
450
+ chunkUC2KS5EG_cjs.emitDbEvent({
428
451
  modelClass: row.table_name,
429
452
  operation: "destroy",
430
453
  resourceId: row.resource_id,
@@ -534,4 +557,5 @@ exports.maintainAuditLogAfterRequests = maintainAuditLogAfterRequests;
534
557
  exports.pruneAuditLog = pruneAuditLog;
535
558
  exports.readAuditRows = readAuditRows;
536
559
  exports.runWithEmittedAuditIdsScope = runWithEmittedAuditIdsScope;
560
+ exports.settleAuditFlushes = settleAuditFlushes;
537
561
  exports.sweepAuditLog = sweepAuditLog;
@@ -1,19 +1,19 @@
1
1
  'use strict';
2
2
 
3
- var chunkMMLQXSSD_cjs = require('./chunk-MMLQXSSD.cjs');
3
+ var chunk2YCQFLXW_cjs = require('./chunk-2YCQFLXW.cjs');
4
4
  var chunkTWTG5ILJ_cjs = require('./chunk-TWTG5ILJ.cjs');
5
5
 
6
6
  // src/triggers/context.ts
7
7
  function getDatabaseContext() {
8
- const actor = chunkMMLQXSSD_cjs.getCurrentActor();
8
+ const actor = chunk2YCQFLXW_cjs.getCurrentActor();
9
9
  return {
10
10
  actorId: actor && actor.id ? actor.id : null,
11
- correlationId: chunkMMLQXSSD_cjs.current()
11
+ correlationId: chunk2YCQFLXW_cjs.current()
12
12
  };
13
13
  }
14
14
  async function applyDatabaseContext(exec) {
15
- const actor = chunkMMLQXSSD_cjs.getCurrentActor();
16
- const correlationId = chunkMMLQXSSD_cjs.current();
15
+ const actor = chunk2YCQFLXW_cjs.getCurrentActor();
16
+ const correlationId = chunk2YCQFLXW_cjs.current();
17
17
  if (!actor && !correlationId) return;
18
18
  try {
19
19
  if (actor && actor.id) {
@@ -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 };