ezlogs-nextjs 0.4.2 → 0.4.4

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.
package/README.md CHANGED
@@ -24,21 +24,39 @@ Status: Completed successfully
24
24
 
25
25
  ---
26
26
 
27
- ## Install
27
+ ## Install: paste the prompt into your coding AI, or do it by hand
28
28
 
29
- ```bash
30
- npm install ezlogs-nextjs
31
- # or: pnpm add ezlogs-nextjs / bun add ezlogs-nextjs
29
+ **1. Fastest: let your coding AI do it.** Paste this into Cursor,
30
+ Claude Code, v0, Replit or any coding AI:
31
+
32
+ ```text
33
+ Install EZLogs in this app by following https://app.ezlogs.io/install/nextjs.md
32
34
  ```
33
35
 
36
+ The AI does every step below (package, `instrumentation.ts`, config,
37
+ key, database, jobs) and then checks that capture works. It asks you for
38
+ your API key. Signed in at [app.ezlogs.io](https://app.ezlogs.io), the
39
+ prompt shown under a new key in **Settings → API keys** already has your
40
+ key in it.
41
+
42
+ **2. By hand:** follow the [quick start](#quick-start-by-hand) below.
43
+ Steps 1-4 take a few minutes; steps 5-7 depend on your stack.
44
+
45
+ ## Quick start (by hand)
46
+
34
47
  Requires Node 18.17+ and Next.js 14+.
35
48
 
36
- ## Quick start
49
+ ### 1. Install the package
37
50
 
38
- ### 1. Create `instrumentation.ts`
51
+ ```bash
52
+ npm install ezlogs-nextjs
53
+ # or: pnpm add ezlogs-nextjs / bun add ezlogs-nextjs
54
+ ```
39
55
 
40
- At your project root (or `src/instrumentation.ts` if you use the
41
- `src/` layout):
56
+ ### 2. Add `instrumentation.ts`
57
+
58
+ Starts the agent when your server boots. Put it at the project root
59
+ (or `src/instrumentation.ts` if you use the `src/` layout):
42
60
 
43
61
  ```ts
44
62
  import { ezlogs } from "ezlogs-nextjs";
@@ -55,19 +73,14 @@ export async function register() {
55
73
  `serverUrl` is optional: it defaults to `process.env.EZLOGS_SERVER_URL`
56
74
  if set, otherwise `https://app.ezlogs.io`. Set it only if you self-host.
57
75
 
58
- ### 2. Wrap your Next config
59
-
60
- `withEzlogsConfig(...)` is a transparent wrapper around your existing
61
- config object. It doesn't add EZLogs-specific settings to your Next
62
- config — every EZLogs option goes in `ezlogs.init({...})`. The wrapper
63
- just registers the build-time loaders that auto-wrap your routes and
64
- Server Actions.
65
-
66
- Pick the snippet matching your config file:
76
+ ### 3. Wrap your Next config
67
77
 
68
- **`next.config.ts`** (TypeScript — Next 14+ default):
78
+ Registers the build-time loaders that auto-wrap your routes and Server
79
+ Actions. It adds no EZLogs settings to your config; every EZLogs option
80
+ goes in `ezlogs.init({...})`.
69
81
 
70
82
  ```ts
83
+ // next.config.ts
71
84
  import type { NextConfig } from "next";
72
85
  import { withEzlogsConfig } from "ezlogs-nextjs/plugin";
73
86
 
@@ -78,8 +91,8 @@ const nextConfig: NextConfig = {
78
91
  export default withEzlogsConfig(nextConfig);
79
92
  ```
80
93
 
81
- **`next.config.mjs`** / ESM **`next.config.js`** (also type-checks
82
- under `checkJs`, e.g. create-t3-app):
94
+ <details>
95
+ <summary><code>next.config.mjs</code> / ESM <code>next.config.js</code> (also type-checks under <code>checkJs</code>, e.g. create-t3-app)</summary>
83
96
 
84
97
  ```js
85
98
  import { withEzlogsConfig } from "ezlogs-nextjs/plugin";
@@ -89,15 +102,22 @@ const nextConfig = { /* your options */ };
89
102
  export default withEzlogsConfig(nextConfig);
90
103
  ```
91
104
 
92
- **`next.config.js`** (CommonJS):
105
+ </details>
106
+
107
+ <details>
108
+ <summary><code>next.config.js</code> (CommonJS)</summary>
93
109
 
94
110
  ```js
95
111
  const { withEzlogsConfig } = require("ezlogs-nextjs/plugin");
96
112
  module.exports = withEzlogsConfig({ /* your options */ });
97
113
  ```
98
114
 
99
- **Already have an `instrumentation.ts` or a wrapped config?** Keep
100
- yours and add to it:
115
+ </details>
116
+
117
+ <details>
118
+ <summary>Already have an <code>instrumentation.ts</code> or a wrapped config?</summary>
119
+
120
+ Keep yours and add to it:
101
121
 
102
122
  - `instrumentation.ts`: put the `ezlogs.init({...})` call inside your
103
123
  existing `register()`, in the `NEXT_RUNTIME === "nodejs"` branch
@@ -108,81 +128,112 @@ yours and add to it:
108
128
  `export default withNextIntl(withEzlogsConfig(nextConfig))` or
109
129
  `withSentryConfig(withEzlogsConfig(nextConfig), { ... })`.
110
130
 
111
- ### 3. Set env vars, restart, verify
131
+ </details>
132
+
133
+ ### 4. Add your key, restart, check
112
134
 
113
135
  ```bash
114
136
  # .env.local
115
137
  EZLOGS_PROJECT_TOKEN=ezl_your_api_key_here
116
138
  ```
117
139
 
118
- Restart your dev server and look for this line in the terminal (one
119
- per server process, at the default log level):
140
+ Restart your dev server. The terminal shows this line once per server
141
+ process:
120
142
 
121
143
  ```
122
144
  [ezlogs] capturing → app.ezlogs.io (key ezl_a1b2c3d4…)
123
145
  ```
124
146
 
147
+ Call an API route or submit a Server Action; events appear in your
148
+ EZLogs dashboard within a few seconds. Opening a page is not a reliable
149
+ check: page views are recorded only when the app has a `middleware.ts`
150
+ (or `proxy.ts` on Next 16).
151
+
152
+ <details>
153
+ <summary>Not seeing the line?</summary>
154
+
125
155
  If `projectToken` is missing you get this instead:
126
156
 
127
157
  ```
128
158
  [ezlogs] not capturing: projectToken missing in ezlogs.init() (check EZLOGS_PROJECT_TOKEN)
129
159
  ```
130
160
 
131
- Call an API route or submit a Server Action; events appear in your
132
- EZLogs dashboard within a few seconds. Page views are only recorded when
133
- the app has a `middleware.ts` (or `proxy.ts` on Next 16), so opening a
134
- page is not a reliable check.
135
-
136
161
  Sending to a local EZLogs server over plain `http://` (development)?
137
162
  Events are still sent, but the agent warns on every start; pass
138
163
  `allowInsecureTransport: true` to `ezlogs.init` to silence it. Keep
139
164
  `https://` in production.
140
165
 
141
- ### 4. Database changes
166
+ More in [docs/troubleshooting.md](./docs/troubleshooting.md).
142
167
 
143
- Steps 1-3 capture requests, Server Actions and jobs. Database changes
144
- need one more step, depending on your stack:
168
+ </details>
145
169
 
146
- | Your app writes with | Do this | You get |
147
- |---|---|---|
148
- | **Supabase** (supabase-js) | `npm i pg`, set `DATABASE_URL` to the Postgres connection string, run `npx ezlogs-nextjs install-triggers`. Nothing to wrap: the agent tags supabase-js requests and the trigger reads the tag. | Every write (`.from()`, `.rpc()`, bulk) with from→to diffs, linked to its request |
149
- | **Prisma** on Postgres | triggers (as above) + `new PrismaClient().$extends(ezlogsPrisma())` (below) | Same |
150
- | **Drizzle** (node-postgres) or raw **`pg`** | triggers (as above). With `DATABASE_URL` set, the agent patches `pg` itself; if your app loads its own copy of `pg` (monorepos), pass it: `ezlogs.init({ ..., patchDatabaseClient: pg })`. | Same |
151
- | **postgres.js** or **Drizzle** on postgres-js | triggers (as above) + `wrapPostgresJs(postgres(url))` (below) | Same |
152
- | Neon HTTP, scripts | triggers (as above) | Writes show up as their own actions, not linked to the request |
153
- | MySQL, SQLite, PlanetScale, no trigger access | a per-ORM adapter: `ezlogsPrisma()`, `ezlogsDrizzleLogger`, `wrapSupabase` ([docs/database.md](./docs/database.md)) | New values only, no before-values |
170
+ ### 5. Capture database changes
171
+
172
+ Steps 1-4 capture requests and Server Actions. This step adds what
173
+ changed in your database: which record, each column from → to, and the
174
+ request and person that made the change. Pick your stack:
175
+
176
+ | Your app writes with | Do this |
177
+ |---|---|
178
+ | **Supabase** (supabase-js), **Drizzle** on node-postgres, raw **`pg`** | [Triggers](#triggers) only |
179
+ | **Prisma** on Postgres | [Triggers](#triggers) + [Prisma extension](#prisma) |
180
+ | **postgres.js**, or **Drizzle** on postgres-js | [Triggers](#triggers) + [wrap `sql`](#postgresjs) |
181
+ | Neon HTTP, scripts | [Triggers](#triggers) (writes show up as their own actions, not linked to the request) |
182
+ | MySQL, SQLite, PlanetScale, no trigger access | A per-ORM adapter: `ezlogsPrisma()`, `ezlogsDrizzleLogger`, `wrapSupabase` ([docs/database.md](./docs/database.md)). New values only, no before-values |
183
+
184
+ #### Triggers
185
+
186
+ Set `DATABASE_URL` (or `POSTGRES_URL`) to your Postgres connection
187
+ string, then run this once from your app's directory:
154
188
 
155
189
  ```bash
156
190
  npm i pg # the trigger installer and reader need it
157
191
  npx ezlogs-nextjs install-triggers
158
192
  ```
159
193
 
160
- Run it from your app's directory with the package installed there
161
- (with bun: `bunx ezlogs-nextjs install-triggers` or
162
- `./node_modules/.bin/ezlogs-nextjs install-triggers`); if the package
163
- isn't installed locally, npx / bunx download whatever version is
164
- published, and the CLI warns. They also download it when your
165
- lockfile's bin entries predate 0.3.0 (seen with bun and a `file:`
166
- dependency); the CLI then prints the command that runs your project's
167
- copy: `node node_modules/ezlogs-nextjs/bin/install-triggers.cjs install-triggers`.
168
- The CLI reads `DATABASE_URL` / `POSTGRES_URL` from your shell or from
169
- `.env`, `.env.local` and `.env.[mode]` (loaded the way Next.js loads
170
- them, incl. `${VAR}` expansion; a variable already set in the shell
171
- wins). Migration tables, database internals, the agent's own audit
172
- table, verification-token tables and session stores (a
173
- `session(s)`-style name **and** a token, expiry, `sess`, `data`,
174
- `payload` or `last_activity` column: Auth.js, Lucia, Rails, Laravel,
175
- connect-pg-simple) are skipped; the output lists each skipped table
176
- with the reason. A `session` table without such columns (analytics
177
- visits, bookings) is tracked. If `pg` or the
178
- audit table is missing at runtime, the agent logs one warning at
179
- startup and leaves the trigger path off.
180
-
181
- **Recommended setup for Prisma** (plain `new PrismaClient()`, or with
182
- a driver adapter such as `@prisma/adapter-pg`): triggers **plus** the
183
- extension, which tags each write with the request so DB changes join
184
- the right action and actor. (`patchPrismaPgAdapter` /
185
- `patchPrismaClient` are legacy; see [docs/database.md](./docs/database.md).)
194
+ Supabase, Drizzle on node-postgres and raw `pg` need nothing else: the
195
+ agent tags their writes itself, and the triggers record every write
196
+ (supabase-js `.from()`, `.rpc()`, bulk) linked to its request.
197
+
198
+ <details>
199
+ <summary>Trigger details: bun, monorepos, which tables are skipped</summary>
200
+
201
+ - **Monorepos:** with `DATABASE_URL` set, the agent patches `pg`
202
+ itself. If your app loads its own copy of `pg`, pass it:
203
+ `ezlogs.init({ ..., patchDatabaseClient: pg })`.
204
+ - **Run it where the package is installed.** With bun:
205
+ `bunx ezlogs-nextjs install-triggers` or
206
+ `./node_modules/.bin/ezlogs-nextjs install-triggers`. If the package
207
+ isn't installed locally, npx / bunx download whatever version is
208
+ published, and the CLI warns. They also download it when your
209
+ lockfile's bin entries predate 0.3.0 (seen with bun and a `file:`
210
+ dependency); the CLI then prints the command that runs your project's
211
+ copy: `node node_modules/ezlogs-nextjs/bin/install-triggers.cjs install-triggers`.
212
+ - **Env files:** the CLI reads `DATABASE_URL` / `POSTGRES_URL` from your
213
+ shell or from `.env`, `.env.local` and `.env.[mode]` (loaded the way
214
+ Next.js loads them, incl. `${VAR}` expansion; a variable already set
215
+ in the shell wins).
216
+ - **Skipped tables:** migration tables, database internals, the agent's
217
+ own audit table, verification-token tables and session stores (a
218
+ `session(s)`-style name **and** a token, expiry, `sess`, `data`,
219
+ `payload` or `last_activity` column: Auth.js, Lucia, Rails, Laravel,
220
+ connect-pg-simple). The output lists each skipped table with the
221
+ reason. A `session` table without such columns (analytics visits,
222
+ bookings) is tracked.
223
+ - If `pg` or the audit table is missing at runtime, the agent logs one
224
+ warning at startup and leaves the trigger path off.
225
+ - **Self-check:** if writes made while requests or jobs run in a
226
+ process keep arriving untagged, and that process has never sent a
227
+ tagged row, the agent logs one warning naming the fix. It never
228
+ guesses which request an untagged row belongs to.
229
+
230
+ </details>
231
+
232
+ #### Prisma
233
+
234
+ Triggers **plus** this extension (plain `new PrismaClient()`, or with a
235
+ driver adapter such as `@prisma/adapter-pg`). It tags each write with
236
+ the request, so the change joins the right action and person.
186
237
 
187
238
  ```ts
188
239
  // lib/prisma.ts
@@ -192,6 +243,9 @@ import { ezlogsPrisma } from "ezlogs-nextjs/prisma";
192
243
  export const prisma = new PrismaClient().$extends(ezlogsPrisma());
193
244
  ```
194
245
 
246
+ <details>
247
+ <summary>How the Prisma extension works</summary>
248
+
195
249
  Each write inside a captured request runs as
196
250
  `$transaction([set_config(correlation id, actor id), your query])` (Prisma's
197
251
  documented RLS-extension pattern); reads are untouched. Writes inside
@@ -199,7 +253,19 @@ your own `prisma.$transaction(...)` are not tagged: they still show up,
199
253
  as separate actions without an actor. Without the extension, a plain
200
254
  PrismaClient's writes are never tagged.
201
255
 
202
- **postgres.js / Drizzle on postgres-js** (Vercel Postgres templates,
256
+ Without triggers, the extension still sends Prisma writes itself (new
257
+ values only — Prisma doesn't expose the old row). With triggers it
258
+ sends nothing for tracked tables; the trigger rows are the single
259
+ source, so there are no duplicates (also for `@@map`-ed models).
260
+
261
+ `patchPrismaPgAdapter` / `patchPrismaClient` are legacy; see
262
+ [docs/database.md](./docs/database.md).
263
+
264
+ </details>
265
+
266
+ #### postgres.js
267
+
268
+ For postgres.js and Drizzle on postgres-js (Vercel Postgres templates,
203
269
  `nextjs/saas-starter`): triggers **plus** wrap the `sql` instance once.
204
270
 
205
271
  ```ts
@@ -212,6 +278,9 @@ export const sql = wrapPostgresJs(postgres(process.env.DATABASE_URL!));
212
278
  export const db = drizzle(sql); // Drizzle: pass the wrapped instance
213
279
  ```
214
280
 
281
+ <details>
282
+ <summary>How the postgres.js wrapper works (and its latency cost)</summary>
283
+
215
284
  Each write inside a captured request (``sql`insert …` ``, `sql.unsafe`,
216
285
  Drizzle inserts / updates / deletes) runs as BEGIN; set_config
217
286
  (correlation id, actor); your write; COMMIT on one pooled connection,
@@ -222,28 +291,50 @@ tagged: those writes show up as their own actions. Each tagged write
222
291
  is its own transaction (4 round trips instead of 1), so write latency
223
292
  grows with your database round-trip time.
224
293
 
225
- **Background workers** (BullMQ and other job processes) are separate
226
- processes: call `ezlogs.init` there too and build the database client
227
- the same way (extension for Prisma), or the job's writes show up as
228
- separate actions without an actor.
294
+ </details>
229
295
 
230
- **Self-check:** if writes made while requests or jobs run in a process
231
- keep arriving untagged, and that process has never sent a tagged row,
232
- the agent logs one warning naming the fix. It never guesses which
233
- request an untagged row belongs to.
296
+ <details>
297
+ <summary>Upgrading from an older version</summary>
234
298
 
235
- Without triggers, the extension still sends Prisma writes itself (new
236
- values only — Prisma doesn't expose the old row). With triggers it
237
- sends nothing for tracked tables; the trigger rows are the single
238
- source, so there are no duplicates (also for `@@map`-ed models).
239
-
240
- **Upgrading:** from 0.2.x or 0.3.x there is nothing to re-run before
241
- deploying. From 0.1.x, run `npx ezlogs-nextjs install-triggers --tables=none`
299
+ From 0.2.x or 0.3.x there is nothing to re-run before deploying. From
300
+ 0.1.x, run `npx ezlogs-nextjs install-triggers --tables=none`
242
301
  **before** deploying the new agent (functions only, no table locks),
243
302
  deploy right after, and later re-run `npx ezlogs-nextjs install-triggers`
244
303
  at a quiet moment. Details in [CHANGELOG.md](./CHANGELOG.md).
245
304
 
246
- ### 5. Name your records
305
+ </details>
306
+
307
+ ### 6. Capture background jobs
308
+
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:
312
+
313
+ | Runner | Add (snippets in [docs/jobs.md](./docs/jobs.md)) |
314
+ |---|---|
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
+ | Trigger.dev | `registerTriggerHooks(tasks)` from `ezlogs-nextjs/trigger` |
318
+ | Supabase Queues (pgmq) | `wrapSupabaseQueueClient` + `captureQueueMessage` from `ezlogs-nextjs/supabase-queues` |
319
+ | Upstash Workflow / QStash | `wrapWorkflowClient` / `wrapQStashClient` + `captureWorkflowRequest` from `ezlogs-nextjs/upstash-workflow` |
320
+
321
+ **Jobs that run in a separate worker process** (for example a BullMQ
322
+ worker you start with `node worker.js`) don't load `instrumentation.ts`.
323
+ In that worker's entry file, start the agent before the worker starts,
324
+ and create the database client the same way as in step 5:
325
+
326
+ ```ts
327
+ // worker.ts (your worker's entry file)
328
+ import { ezlogs } from "ezlogs-nextjs";
329
+
330
+ ezlogs.init({ projectToken: process.env.EZLOGS_PROJECT_TOKEN! });
331
+ // ...then create your Worker as usual
332
+ ```
333
+
334
+ Otherwise the job's database changes show up as separate actions,
335
+ without who made them.
336
+
337
+ ### 7. Name your records
247
338
 
248
339
  Database changes are titled with the record's `name`, `title`,
249
340
  `number` or `label` column. Records of people (users, members,
@@ -317,8 +408,14 @@ The agent is designed to be **invisible** to your application.
317
408
 
318
409
  - **Never throws** into the host — every public surface wraps its work
319
410
  in `try/catch`.
320
- - **Never blocks** requests — sending is asynchronous on a background
321
- flush scheduler.
411
+ - **Doesn't hold up responses** — on a long-running server, events are
412
+ sent by a background flush scheduler, never on the request path. On
413
+ serverless hosts (Vercel, AWS Lambda, Netlify, Cloudflare Pages) the
414
+ function can freeze once the response is sent, so each request's
415
+ events are sent as it finishes: through the platform's `waitUntil`
416
+ when there is one (Vercel, and Next.js runtimes that provide it), after the response; without
417
+ it, the request waits at most 2 seconds, and events not sent by then
418
+ are best-effort (sent only if the function stays warm).
322
419
  - **Build-safe** — the build-time loader wraps every transform in
323
420
  try/catch and returns source unchanged on any error, so a regression
324
421
  in the loader can't break `next build`.
@@ -0,0 +1,27 @@
1
+ # Third-party licenses
2
+
3
+ `ezlogs-nextjs` bundles part of [sucrase](https://github.com/alangpierce/sucrase) (its parser, 3.35.1) into `dist/nextjs-plugin/loader.*`. Its license:
4
+
5
+ ```
6
+ The MIT License (MIT)
7
+
8
+ Copyright (c) 2012-2018 various contributors (see AUTHORS)
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+ ```
package/dist/index.cjs CHANGED
@@ -123,7 +123,7 @@ var GLOBAL_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:flush-scheduler-state
123
123
  function state() {
124
124
  const g = globalThis;
125
125
  if (!g[GLOBAL_KEY]) {
126
- g[GLOBAL_KEY] = { timer: null, inFlight: false };
126
+ g[GLOBAL_KEY] = { timer: null, inFlight: false, current: null, followUp: null };
127
127
  }
128
128
  return g[GLOBAL_KEY];
129
129
  }
@@ -151,15 +151,37 @@ var flushScheduler = {
151
151
  isRunning() {
152
152
  return state().timer !== null;
153
153
  },
154
- /** Force a single drain-and-send cycle. Used by serverless flush + tests. */
155
- async flushNow() {
156
- await tick();
154
+ /**
155
+ * Drain and send now; resolves once this caller's events are sent (or
156
+ * dropped). If a send is already running, one more drain is queued after
157
+ * it, so events buffered since that send started are covered too: on
158
+ * serverless, overlapping requests each hand this promise to waitUntil.
159
+ * Concurrent callers share that single follow-up, so a slow server never
160
+ * builds a queue.
161
+ */
162
+ flushNow() {
163
+ const s = state();
164
+ if (!s.inFlight || !s.current) return tick();
165
+ if (!s.followUp) {
166
+ s.followUp = s.current.then(() => {
167
+ s.followUp = null;
168
+ return tick();
169
+ });
170
+ }
171
+ return s.followUp;
157
172
  }
158
173
  };
159
- async function tick() {
174
+ function tick() {
160
175
  const s = state();
161
- if (s.inFlight) return;
176
+ if (s.inFlight && s.current) return s.current;
162
177
  s.inFlight = true;
178
+ s.current = runTick().finally(() => {
179
+ s.inFlight = false;
180
+ s.current = null;
181
+ });
182
+ return s.current;
183
+ }
184
+ async function runTick() {
163
185
  try {
164
186
  const events = chunkYXZZNZG6_cjs.drainEvents();
165
187
  if (events.length > 0) await retrySender.send(events);
@@ -170,8 +192,6 @@ async function tick() {
170
192
  if (swept.length > 0) await retrySender.send(swept);
171
193
  } catch (error) {
172
194
  chunkTWTG5ILJ_cjs.logger.error(`FlushScheduler tick failed: ${describeError3(error)}`);
173
- } finally {
174
- s.inFlight = false;
175
195
  }
176
196
  }
177
197
  function sendInterval() {
@@ -799,10 +819,7 @@ function captureRoute(handler, context = {}) {
799
819
  durationMs: handlerMs ?? Date.now() - startMs,
800
820
  startedAt: new Date(startMs)
801
821
  });
802
- if (isServerless()) {
803
- await flushScheduler.flushNow().catch(() => {
804
- });
805
- }
822
+ await flushOnServerless();
806
823
  chunkMMLQXSSD_cjs.endCorrelationScope();
807
824
  };
808
825
  try {
@@ -1032,9 +1049,7 @@ function capturePagesApi(handler, context = {}) {
1032
1049
  durationMs: Date.now() - startMs,
1033
1050
  startedAt: new Date(startMs)
1034
1051
  });
1035
- if (isServerless()) {
1036
- await flushScheduler.flushNow().catch(() => void 0);
1037
- }
1052
+ await flushOnServerless();
1038
1053
  chunkMMLQXSSD_cjs.endCorrelationScope();
1039
1054
  }
1040
1055
  })
@@ -1113,9 +1128,7 @@ function captureServerAction(action, actionName) {
1113
1128
  });
1114
1129
  throw e;
1115
1130
  } finally {
1116
- if (isServerless()) {
1117
- await flushScheduler.flushNow().catch(() => void 0);
1118
- }
1131
+ await flushOnServerless();
1119
1132
  chunkMMLQXSSD_cjs.endCorrelationScope();
1120
1133
  }
1121
1134
  })
@@ -1929,6 +1942,31 @@ function followBody(response, method, onDone, onChunk) {
1929
1942
  return null;
1930
1943
  }
1931
1944
  }
1945
+ var SERVERLESS_INLINE_FLUSH_MS = 2e3;
1946
+ async function flushOnServerless() {
1947
+ if (!isServerless()) return;
1948
+ try {
1949
+ const waitUntil = platformWaitUntil();
1950
+ if (waitUntil) {
1951
+ waitUntil(flushScheduler.flushNow());
1952
+ return;
1953
+ }
1954
+ } catch (e) {
1955
+ chunkTWTG5ILJ_cjs.logger.debug(`waitUntil unavailable, flushing inline: ${describeError5(e)}`);
1956
+ }
1957
+ let timer;
1958
+ try {
1959
+ await Promise.race([
1960
+ flushScheduler.flushNow(),
1961
+ new Promise((resolve) => {
1962
+ timer = setTimeout(resolve, SERVERLESS_INLINE_FLUSH_MS);
1963
+ })
1964
+ ]);
1965
+ } catch {
1966
+ } finally {
1967
+ clearTimeout(timer);
1968
+ }
1969
+ }
1932
1970
  function platformWaitUntil() {
1933
1971
  for (const key of ["@next/request-context", "@vercel/request-context"]) {
1934
1972
  try {
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { patchPgClient } from './chunk-Z2TM3LGG.js';
2
2
  import { flushAuditLog, runWithEmittedAuditIdsScope, auditLogInstalled, checkAuditLogAccess, detectTriggerTrackedTables, maintainAuditLogAfterRequests } from './chunk-MHBS5FEP.js';
3
- import { build, pushEvent, maskAuthParams, isAuthActionName, isAuthPath, scrubSecretsInText, buffer_exports, sanitizeRequestParams, passesLuhn, drainEvents, isSensitiveKey } from './chunk-NINIAL7M.js';
3
+ import { build, pushEvent, maskAuthParams, isAuthActionName, isAuthPath, scrubSecretsInText, buffer_exports, sanitizeRequestParams, passesLuhn, isSensitiveKey, drainEvents } from './chunk-NINIAL7M.js';
4
4
  export { ArgError, build as buildEvent } from './chunk-NINIAL7M.js';
5
5
  import { configuration, resolveCorrelation, runWithCorrelation, maybeExtractSupabaseActor, endCorrelationScope, getCurrentActor, current, makeAsyncContextCapture, runWithActorScope, setActor, DEFAULT_EXCLUDED_EXTENSIONS } from './chunk-GI6BM4MR.js';
6
6
  import { logger, setLogLevel } from './chunk-FCFVIRQF.js';
@@ -122,7 +122,7 @@ var GLOBAL_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:flush-scheduler-state
122
122
  function state() {
123
123
  const g = globalThis;
124
124
  if (!g[GLOBAL_KEY]) {
125
- g[GLOBAL_KEY] = { timer: null, inFlight: false };
125
+ g[GLOBAL_KEY] = { timer: null, inFlight: false, current: null, followUp: null };
126
126
  }
127
127
  return g[GLOBAL_KEY];
128
128
  }
@@ -150,15 +150,37 @@ var flushScheduler = {
150
150
  isRunning() {
151
151
  return state().timer !== null;
152
152
  },
153
- /** Force a single drain-and-send cycle. Used by serverless flush + tests. */
154
- async flushNow() {
155
- await tick();
153
+ /**
154
+ * Drain and send now; resolves once this caller's events are sent (or
155
+ * dropped). If a send is already running, one more drain is queued after
156
+ * it, so events buffered since that send started are covered too: on
157
+ * serverless, overlapping requests each hand this promise to waitUntil.
158
+ * Concurrent callers share that single follow-up, so a slow server never
159
+ * builds a queue.
160
+ */
161
+ flushNow() {
162
+ const s = state();
163
+ if (!s.inFlight || !s.current) return tick();
164
+ if (!s.followUp) {
165
+ s.followUp = s.current.then(() => {
166
+ s.followUp = null;
167
+ return tick();
168
+ });
169
+ }
170
+ return s.followUp;
156
171
  }
157
172
  };
158
- async function tick() {
173
+ function tick() {
159
174
  const s = state();
160
- if (s.inFlight) return;
175
+ if (s.inFlight && s.current) return s.current;
161
176
  s.inFlight = true;
177
+ s.current = runTick().finally(() => {
178
+ s.inFlight = false;
179
+ s.current = null;
180
+ });
181
+ return s.current;
182
+ }
183
+ async function runTick() {
162
184
  try {
163
185
  const events = drainEvents();
164
186
  if (events.length > 0) await retrySender.send(events);
@@ -169,8 +191,6 @@ async function tick() {
169
191
  if (swept.length > 0) await retrySender.send(swept);
170
192
  } catch (error) {
171
193
  logger.error(`FlushScheduler tick failed: ${describeError3(error)}`);
172
- } finally {
173
- s.inFlight = false;
174
194
  }
175
195
  }
176
196
  function sendInterval() {
@@ -798,10 +818,7 @@ function captureRoute(handler, context = {}) {
798
818
  durationMs: handlerMs ?? Date.now() - startMs,
799
819
  startedAt: new Date(startMs)
800
820
  });
801
- if (isServerless()) {
802
- await flushScheduler.flushNow().catch(() => {
803
- });
804
- }
821
+ await flushOnServerless();
805
822
  endCorrelationScope();
806
823
  };
807
824
  try {
@@ -1031,9 +1048,7 @@ function capturePagesApi(handler, context = {}) {
1031
1048
  durationMs: Date.now() - startMs,
1032
1049
  startedAt: new Date(startMs)
1033
1050
  });
1034
- if (isServerless()) {
1035
- await flushScheduler.flushNow().catch(() => void 0);
1036
- }
1051
+ await flushOnServerless();
1037
1052
  endCorrelationScope();
1038
1053
  }
1039
1054
  })
@@ -1112,9 +1127,7 @@ function captureServerAction(action, actionName) {
1112
1127
  });
1113
1128
  throw e;
1114
1129
  } finally {
1115
- if (isServerless()) {
1116
- await flushScheduler.flushNow().catch(() => void 0);
1117
- }
1130
+ await flushOnServerless();
1118
1131
  endCorrelationScope();
1119
1132
  }
1120
1133
  })
@@ -1928,6 +1941,31 @@ function followBody(response, method, onDone, onChunk) {
1928
1941
  return null;
1929
1942
  }
1930
1943
  }
1944
+ var SERVERLESS_INLINE_FLUSH_MS = 2e3;
1945
+ async function flushOnServerless() {
1946
+ if (!isServerless()) return;
1947
+ try {
1948
+ const waitUntil = platformWaitUntil();
1949
+ if (waitUntil) {
1950
+ waitUntil(flushScheduler.flushNow());
1951
+ return;
1952
+ }
1953
+ } catch (e) {
1954
+ logger.debug(`waitUntil unavailable, flushing inline: ${describeError5(e)}`);
1955
+ }
1956
+ let timer;
1957
+ try {
1958
+ await Promise.race([
1959
+ flushScheduler.flushNow(),
1960
+ new Promise((resolve) => {
1961
+ timer = setTimeout(resolve, SERVERLESS_INLINE_FLUSH_MS);
1962
+ })
1963
+ ]);
1964
+ } catch {
1965
+ } finally {
1966
+ clearTimeout(timer);
1967
+ }
1968
+ }
1931
1969
  function platformWaitUntil() {
1932
1970
  for (const key of ["@next/request-context", "@vercel/request-context"]) {
1933
1971
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ezlogs-nextjs",
3
- "version": "0.4.2",
3
+ "version": "0.4.4",
4
4
  "description": "EZLogs agent for Next.js — capture HTTP, database, and background-job events as plain-English Action cards.",
5
5
  "license": "MIT",
6
6
  "author": "EZLogs",
@@ -21,7 +21,8 @@
21
21
  "dist",
22
22
  "sql",
23
23
  "bin",
24
- "README.md"
24
+ "README.md",
25
+ "THIRD_PARTY_LICENSES.md"
25
26
  ],
26
27
  "bin": {
27
28
  "ezlogs-nextjs": "./bin/install-triggers.cjs",
@@ -150,15 +151,15 @@
150
151
  "@upstash/qstash": "^2.12.2",
151
152
  "@upstash/workflow": "^1.3.3",
152
153
  "bullmq": "^5.76.10",
153
- "drizzle-orm": "^0.43.1",
154
+ "drizzle-orm": "^0.45.4",
154
155
  "pg": "^8.20.0",
155
156
  "pg-cursor": "^2.22.1",
156
157
  "pg-query-stream": "^4.17.1",
157
158
  "postgres": "^3.4.9",
158
159
  "prisma": "^5.22.0",
159
160
  "sucrase": "^3.35.0",
160
- "tsup": "^8.0.2",
161
+ "tsup": "^8.5.1",
161
162
  "typescript": "^5.4.0",
162
- "vitest": "^1.4.0"
163
+ "vitest": "^4.1.12"
163
164
  }
164
165
  }