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
@@ -1,23 +1,19 @@
1
1
  'use strict';
2
2
 
3
- var chunkR6IWVTX3_cjs = require('../chunk-R6IWVTX3.cjs');
4
- require('../chunk-GMHOUAKD.cjs');
5
- require('../chunk-YXZZNZG6.cjs');
6
- var chunkMMLQXSSD_cjs = require('../chunk-MMLQXSSD.cjs');
3
+ var chunkCHVJ4WPM_cjs = require('../chunk-CHVJ4WPM.cjs');
4
+ var chunkVJR4VB4B_cjs = require('../chunk-VJR4VB4B.cjs');
5
+ var chunkKOFR5OC3_cjs = require('../chunk-KOFR5OC3.cjs');
6
+ require('../chunk-EXGEA4KE.cjs');
7
+ require('../chunk-UC2KS5EG.cjs');
8
+ var chunk2YCQFLXW_cjs = require('../chunk-2YCQFLXW.cjs');
7
9
  var chunkTWTG5ILJ_cjs = require('../chunk-TWTG5ILJ.cjs');
8
10
  require('../chunk-ZDSQYCYV.cjs');
9
11
 
10
12
  // src/jobs/inngest.ts
11
- var warnedUnsupported = false;
13
+ var insideV4Run = chunk2YCQFLXW_cjs.createScopedStorage(/* @__PURE__ */ Symbol.for("ezlogs-nextjs:inngest-v4-run"));
12
14
  function ezlogsInngestMiddleware() {
13
15
  const middleware = function ezlogsInngestV4() {
14
- if (!warnedUnsupported) {
15
- warnedUnsupported = true;
16
- chunkTWTG5ILJ_cjs.logger.warn(
17
- "ezlogsInngestMiddleware supports Inngest v3 only; on this Inngest version it does nothing (jobs are not captured)"
18
- );
19
- }
20
- return {};
16
+ return inngestV4Hooks();
21
17
  };
22
18
  Object.defineProperty(middleware, "name", { value: "ezlogs-nextjs" });
23
19
  return Object.assign(middleware, {
@@ -27,27 +23,31 @@ function ezlogsInngestMiddleware() {
27
23
  // one function). Returns per-run hooks that fire as the run
28
24
  // proceeds. We track the run via closure-scoped state.
29
25
  onFunctionRun(args) {
26
+ chunkCHVJ4WPM_cjs.markJobDelivery();
30
27
  const fnId = functionId(args.fn) ?? "inngest-function";
31
28
  const runId = args.ctx?.runId ?? null;
32
29
  const attempt = typeof args.ctx?.attempt === "number" ? args.ctx.attempt : 0;
33
30
  const eventName = args.ctx?.event?.name ?? null;
34
31
  const eventData = args.ctx?.event?.data;
35
- const correlationId = chunkR6IWVTX3_cjs.extractCorrelationFromPayload(args.ctx?.event?.data) ?? chunkMMLQXSSD_cjs.generate();
32
+ const correlationId = chunkKOFR5OC3_cjs.extractCorrelationFromPayload(args.ctx?.event?.data) ?? chunk2YCQFLXW_cjs.generate();
36
33
  const startedAt = /* @__PURE__ */ new Date();
37
34
  const startMs = startedAt.getTime();
38
35
  return {
39
36
  // Inngest calls this once after the function body returns
40
37
  // (success) or throws (failure surfaces via result.error).
38
+ // `step`: the step this execution ran (none on the one where the function returns).
41
39
  transformOutput(args2) {
42
40
  try {
43
41
  const result = args2.result;
44
42
  const error = result?.error;
45
43
  const outcome = error ? "failure" : "success";
46
44
  const errorMessage = error ? formatError(error) : null;
47
- chunkR6IWVTX3_cjs.emitJobEvent({
45
+ const ranStep = args2.step?.displayName ?? args2.step?.name;
46
+ chunkKOFR5OC3_cjs.emitJobEvent({
48
47
  jobClass: fnId,
49
48
  jobId: runId,
50
49
  queue: eventName,
50
+ step: typeof ranStep === "string" && ranStep ? ranStep : null,
51
51
  retryCount: attempt,
52
52
  correlationId,
53
53
  outcome,
@@ -72,33 +72,7 @@ function ezlogsInngestMiddleware() {
72
72
  // objects are never written (one reused across requests
73
73
  // would carry the first request's id and actor).
74
74
  transformInput(args) {
75
- try {
76
- const id = chunkMMLQXSSD_cjs.current();
77
- if (!id) return;
78
- if (!Array.isArray(args.payloads)) return;
79
- const stamped = [];
80
- const payloads = args.payloads.map((payload) => {
81
- if (!payload || typeof payload !== "object") return payload;
82
- const data = payload.data ?? {};
83
- if (typeof data !== "object" || data === null || Array.isArray(data)) {
84
- return payload;
85
- }
86
- if (typeof data.ezlogs_correlation_id === "string") {
87
- return payload;
88
- }
89
- const copy = { ...data, ezlogs_correlation_id: id };
90
- if (!(chunkR6IWVTX3_cjs.ACTOR_PAYLOAD_KEY in copy)) stamped.push(copy);
91
- return { ...payload, data: copy };
92
- });
93
- const pending = stamped.length > 0 ? chunkR6IWVTX3_cjs.signedActorToken(id) : null;
94
- if (!pending) return { payloads };
95
- return pending.then((token) => {
96
- if (token) for (const data of stamped) data[chunkR6IWVTX3_cjs.ACTOR_PAYLOAD_KEY] = token;
97
- return { payloads };
98
- });
99
- } catch (error) {
100
- chunkTWTG5ILJ_cjs.logger.debug(`inngest send-stamp failed: ${describeError(error)}`);
101
- }
75
+ return stampSendEvents(args.payloads, (payloads) => ({ payloads }));
102
76
  }
103
77
  };
104
78
  }
@@ -106,21 +80,157 @@ function ezlogsInngestMiddleware() {
106
80
  }
107
81
  });
108
82
  }
83
+ function inngestV4Hooks() {
84
+ let runError = null;
85
+ let ranStep = null;
86
+ let executed = false;
87
+ return {
88
+ id: "ezlogs-nextjs",
89
+ // Before the function sees (and Inngest validates) its events: our keys
90
+ // are removed, so a trigger or `waitForEvent` with a strict schema
91
+ // still accepts them. The scope was opened from the request body.
92
+ transformFunctionInput(arg) {
93
+ executed = true;
94
+ try {
95
+ return withoutCarriedKeysInInput(arg);
96
+ } catch (error) {
97
+ chunkTWTG5ILJ_cjs.logger.debug(`inngest input strip failed: ${describeError(error)}`);
98
+ return arg;
99
+ }
100
+ },
101
+ // Called for `inngest.send` and `step.sendEvent`; returns the arg with stamped copies.
102
+ transformSendEvent(args) {
103
+ return stampSendEvents(args?.events, (events) => ({ ...args, events })) ?? args;
104
+ },
105
+ // Only for steps that run in this request (`step.run`, `step.sendEvent`), not memoized ones.
106
+ onStepStart(args) {
107
+ const options = args?.stepInfo?.options;
108
+ const name = options?.name ?? options?.id;
109
+ ranStep = typeof name === "string" && name ? name : null;
110
+ },
111
+ onStepError(args) {
112
+ runError = args?.error ?? runError;
113
+ },
114
+ onRunError(args) {
115
+ runError = args?.error ?? runError;
116
+ },
117
+ async wrapRequest(args) {
118
+ let nextCalled = false;
119
+ const next = () => {
120
+ nextCalled = true;
121
+ return args.next();
122
+ };
123
+ try {
124
+ const body = args.fn ? await args.requestInfo?.body?.() : null;
125
+ if (!body || typeof body !== "object") return await next();
126
+ const fnId = functionId(args.fn) ?? "inngest-function";
127
+ const event = body.event;
128
+ const attempt = typeof body.ctx?.attempt === "number" ? body.ctx.attempt : 0;
129
+ const runId = args.runId || body.ctx?.run_id || null;
130
+ return await runInsideInngestCorrelation(event, () => insideV4Run.run(true, async () => {
131
+ const startedAt = /* @__PURE__ */ new Date();
132
+ try {
133
+ return await next();
134
+ } catch (error) {
135
+ runError = error;
136
+ throw error;
137
+ } finally {
138
+ if (executed) {
139
+ chunkCHVJ4WPM_cjs.markJobDelivery();
140
+ chunkKOFR5OC3_cjs.emitJobEvent({
141
+ jobClass: fnId,
142
+ jobId: runId,
143
+ queue: event?.name ?? null,
144
+ step: ranStep,
145
+ retryCount: attempt,
146
+ outcome: runError ? "failure" : "success",
147
+ errorMessage: runError ? formatError(runError) : null,
148
+ durationMs: Date.now() - startedAt.getTime(),
149
+ startedAt,
150
+ payload: event?.data
151
+ });
152
+ }
153
+ }
154
+ }));
155
+ } catch (error) {
156
+ if (nextCalled) throw error;
157
+ chunkTWTG5ILJ_cjs.logger.debug(`inngest capture failed: ${describeError(error)}`);
158
+ return args.next();
159
+ }
160
+ }
161
+ };
162
+ }
163
+ function withoutCarriedKeysInInput(arg) {
164
+ const ctx = arg?.ctx;
165
+ if (!ctx) return arg;
166
+ let changed = false;
167
+ const strip = (value) => {
168
+ const out = withoutCarriedKeys(value);
169
+ if (out !== value) changed = true;
170
+ return out;
171
+ };
172
+ const event = strip(ctx.event);
173
+ const events = Array.isArray(ctx.events) ? ctx.events.map(strip) : ctx.events;
174
+ const steps = {};
175
+ for (const [id, step] of Object.entries(arg.steps ?? {})) {
176
+ steps[id] = step?.type === "data" ? { ...step, data: strip(step.data) } : step;
177
+ }
178
+ return changed ? { ...arg, ctx: { ...ctx, event, events }, steps } : arg;
179
+ }
180
+ function withoutCarriedKeys(event) {
181
+ const data = event?.data;
182
+ if (!data || typeof data !== "object" || Array.isArray(data)) return event;
183
+ if (!(chunkKOFR5OC3_cjs.CORRELATION_PAYLOAD_KEY in data) && !(chunkKOFR5OC3_cjs.ACTOR_PAYLOAD_KEY in data)) return event;
184
+ const rest = { ...data };
185
+ delete rest[chunkKOFR5OC3_cjs.CORRELATION_PAYLOAD_KEY];
186
+ delete rest[chunkKOFR5OC3_cjs.ACTOR_PAYLOAD_KEY];
187
+ return { ...event, data: rest };
188
+ }
189
+ function stampSendEvents(events, wrap) {
190
+ try {
191
+ const id = chunk2YCQFLXW_cjs.current();
192
+ if (!id) return;
193
+ if (!Array.isArray(events)) return;
194
+ const stamped = [];
195
+ const payloads = events.map((payload) => {
196
+ if (!payload || typeof payload !== "object") return payload;
197
+ const data = payload.data ?? {};
198
+ if (typeof data !== "object" || data === null || Array.isArray(data)) {
199
+ return payload;
200
+ }
201
+ if (typeof data.ezlogs_correlation_id === "string") {
202
+ return payload;
203
+ }
204
+ const copy = { ...data, ezlogs_correlation_id: id };
205
+ if (!(chunkKOFR5OC3_cjs.ACTOR_PAYLOAD_KEY in copy)) stamped.push(copy);
206
+ return { ...payload, data: copy };
207
+ });
208
+ const pending = stamped.length > 0 ? chunkKOFR5OC3_cjs.signedActorToken(id) : null;
209
+ if (!pending) return wrap(payloads);
210
+ return pending.then((token) => {
211
+ if (token) for (const data of stamped) data[chunkKOFR5OC3_cjs.ACTOR_PAYLOAD_KEY] = token;
212
+ return wrap(payloads);
213
+ });
214
+ } catch (error) {
215
+ chunkTWTG5ILJ_cjs.logger.debug(`inngest send-stamp failed: ${describeError(error)}`);
216
+ }
217
+ }
109
218
  async function runInsideInngestCorrelation(event, callback) {
110
- const carried = chunkR6IWVTX3_cjs.extractCorrelationFromPayload(event?.data);
111
- const id = carried ?? chunkMMLQXSSD_cjs.generate();
112
- const token = event?.data?.[chunkR6IWVTX3_cjs.ACTOR_PAYLOAD_KEY];
113
- const actor = carried && token !== void 0 ? await chunkR6IWVTX3_cjs.readActorToken(token, carried) : null;
219
+ if (insideV4Run.read()) return callback();
220
+ const carried = chunkKOFR5OC3_cjs.extractCorrelationFromPayload(event?.data);
221
+ const id = carried ?? chunk2YCQFLXW_cjs.generate();
222
+ const token = event?.data?.[chunkKOFR5OC3_cjs.ACTOR_PAYLOAD_KEY];
223
+ const actor = carried && token !== void 0 ? await chunkKOFR5OC3_cjs.readActorToken(token, carried) : null;
114
224
  const startedAt = /* @__PURE__ */ new Date();
115
225
  const body = async () => {
116
226
  try {
117
227
  return await callback();
118
228
  } finally {
119
- await chunkR6IWVTX3_cjs.flushJobAuditLog(startedAt);
229
+ await chunkKOFR5OC3_cjs.flushJobAuditLog(startedAt);
120
230
  }
121
231
  };
122
- const scoped = () => body().finally(chunkMMLQXSSD_cjs.endCorrelationScope);
123
- return chunkMMLQXSSD_cjs.runWithCorrelation(id, () => chunkMMLQXSSD_cjs.runWithActorScope(scoped, actor));
232
+ const scoped = () => body().finally(chunk2YCQFLXW_cjs.endCorrelationScope);
233
+ return chunk2YCQFLXW_cjs.runWithCorrelation(id, () => chunk2YCQFLXW_cjs.runWithActorScope(scoped, actor));
124
234
  }
125
235
  function functionId(fn) {
126
236
  try {
@@ -145,6 +255,19 @@ function describeError(error) {
145
255
  if (error instanceof Error) return `${error.name}: ${error.message}`;
146
256
  return String(error);
147
257
  }
258
+ function withEzlogsMiddleware(args) {
259
+ const [options, ...rest] = args;
260
+ if (!options || typeof options !== "object" || Array.isArray(options)) return args;
261
+ const opts = options;
262
+ const existing = Array.isArray(opts.middleware) ? opts.middleware : opts.middleware == null ? [] : null;
263
+ if (existing === null) return args;
264
+ if (existing.some((m) => m?.name === "ezlogs-nextjs")) return args;
265
+ return [{ ...opts, middleware: [...existing, ezlogsInngestMiddleware()] }, ...rest];
266
+ }
267
+ var __ezlogsInstrument = chunkVJR4VB4B_cjs.instrumentFrom({
268
+ "inngest#Inngest": (original) => chunkVJR4VB4B_cjs.instrumentClass(original, (client) => client, withEzlogsMiddleware)
269
+ });
148
270
 
271
+ exports.__ezlogsInstrument = __ezlogsInstrument;
149
272
  exports.ezlogsInngestMiddleware = ezlogsInngestMiddleware;
150
273
  exports.runInsideInngestCorrelation = runInsideInngestCorrelation;
@@ -1,21 +1,21 @@
1
1
  /**
2
- * Returns an Inngest v3 middleware. Pass it via:
2
+ * Returns an Inngest middleware for v3 and v4. Pass it via:
3
3
  * new Inngest({ middleware: [ezlogsInngestMiddleware()] })
4
4
  *
5
5
  * Returned `unknown` because Inngest's `Middleware` type is parameterized
6
6
  * over the client and we don't want to take a hard type dep.
7
7
  *
8
- * Inngest v4 has a different middleware API (a class it calls `new`
9
- * on) that this adapter doesn't support. There the middleware does
10
- * nothing and warns once, instead of crashing `inngest.send`.
8
+ * v3 reads `name` and calls `init()`. v4 calls `new` on it (one
9
+ * instance per request or send), which returns the v4 hooks.
11
10
  */
12
11
  declare function ezlogsInngestMiddleware(): unknown;
13
12
  /**
14
13
  * Run an Inngest function body (or a step) inside the run's
15
14
  * correlation scope, so its DB writes are tagged and emitted under the
16
- * action that sent the event. Inngest middleware can't wrap the body
15
+ * action that sent the event. Inngest v3 middleware can't wrap the body
17
16
  * itself, so without this the job event is captured but the body's DB
18
- * writes ship as their own actions:
17
+ * writes ship as their own actions. Not needed on v4 (the middleware
18
+ * wraps the run), where it is harmless:
19
19
  *
20
20
  * inngest.createFunction({ id: "send-invoice" }, { event: "invoice/created" },
21
21
  * ({ event, step }) => runInsideInngestCorrelation(event, async () => { ... }))
@@ -23,5 +23,11 @@ declare function ezlogsInngestMiddleware(): unknown;
23
23
  declare function runInsideInngestCorrelation<T>(event: {
24
24
  data?: unknown;
25
25
  } | undefined, callback: () => Promise<T>): Promise<T>;
26
+ /**
27
+ * Replacements for the plugin's instrumented imports (instrument.ts):
28
+ * every Inngest client the app's server code constructs gets
29
+ * ezlogsInngestMiddleware. Internal: called by build-time generated code.
30
+ */
31
+ declare const __ezlogsInstrument: (key: string, original: unknown) => unknown;
26
32
 
27
- export { ezlogsInngestMiddleware, runInsideInngestCorrelation };
33
+ export { __ezlogsInstrument, ezlogsInngestMiddleware, runInsideInngestCorrelation };
@@ -1,21 +1,21 @@
1
1
  /**
2
- * Returns an Inngest v3 middleware. Pass it via:
2
+ * Returns an Inngest middleware for v3 and v4. Pass it via:
3
3
  * new Inngest({ middleware: [ezlogsInngestMiddleware()] })
4
4
  *
5
5
  * Returned `unknown` because Inngest's `Middleware` type is parameterized
6
6
  * over the client and we don't want to take a hard type dep.
7
7
  *
8
- * Inngest v4 has a different middleware API (a class it calls `new`
9
- * on) that this adapter doesn't support. There the middleware does
10
- * nothing and warns once, instead of crashing `inngest.send`.
8
+ * v3 reads `name` and calls `init()`. v4 calls `new` on it (one
9
+ * instance per request or send), which returns the v4 hooks.
11
10
  */
12
11
  declare function ezlogsInngestMiddleware(): unknown;
13
12
  /**
14
13
  * Run an Inngest function body (or a step) inside the run's
15
14
  * correlation scope, so its DB writes are tagged and emitted under the
16
- * action that sent the event. Inngest middleware can't wrap the body
15
+ * action that sent the event. Inngest v3 middleware can't wrap the body
17
16
  * itself, so without this the job event is captured but the body's DB
18
- * writes ship as their own actions:
17
+ * writes ship as their own actions. Not needed on v4 (the middleware
18
+ * wraps the run), where it is harmless:
19
19
  *
20
20
  * inngest.createFunction({ id: "send-invoice" }, { event: "invoice/created" },
21
21
  * ({ event, step }) => runInsideInngestCorrelation(event, async () => { ... }))
@@ -23,5 +23,11 @@ declare function ezlogsInngestMiddleware(): unknown;
23
23
  declare function runInsideInngestCorrelation<T>(event: {
24
24
  data?: unknown;
25
25
  } | undefined, callback: () => Promise<T>): Promise<T>;
26
+ /**
27
+ * Replacements for the plugin's instrumented imports (instrument.ts):
28
+ * every Inngest client the app's server code constructs gets
29
+ * ezlogsInngestMiddleware. Internal: called by build-time generated code.
30
+ */
31
+ declare const __ezlogsInstrument: (key: string, original: unknown) => unknown;
26
32
 
27
- export { ezlogsInngestMiddleware, runInsideInngestCorrelation };
33
+ export { __ezlogsInstrument, ezlogsInngestMiddleware, runInsideInngestCorrelation };
@@ -1,21 +1,17 @@
1
- import { ACTOR_PAYLOAD_KEY, signedActorToken, extractCorrelationFromPayload, emitJobEvent, readActorToken, flushJobAuditLog } from '../chunk-U22T7QYY.js';
2
- import '../chunk-MHBS5FEP.js';
3
- import '../chunk-NINIAL7M.js';
4
- import { current, generate, runWithCorrelation, runWithActorScope, endCorrelationScope } from '../chunk-GI6BM4MR.js';
1
+ import { markJobDelivery } from '../chunk-BE3RCFNP.js';
2
+ import { instrumentFrom, instrumentClass } from '../chunk-JWJKFZBW.js';
3
+ import { extractCorrelationFromPayload, emitJobEvent, ACTOR_PAYLOAD_KEY, signedActorToken, readActorToken, flushJobAuditLog, CORRELATION_PAYLOAD_KEY } from '../chunk-Q3HRVWCS.js';
4
+ import '../chunk-CYAFYBKF.js';
5
+ import '../chunk-AXIQTU52.js';
6
+ import { createScopedStorage, generate, current, runWithCorrelation, runWithActorScope, endCorrelationScope } from '../chunk-7MFKEYDN.js';
5
7
  import { logger } from '../chunk-FCFVIRQF.js';
6
8
  import '../chunk-SIAA4J6H.js';
7
9
 
8
10
  // src/jobs/inngest.ts
9
- var warnedUnsupported = false;
11
+ var insideV4Run = createScopedStorage(/* @__PURE__ */ Symbol.for("ezlogs-nextjs:inngest-v4-run"));
10
12
  function ezlogsInngestMiddleware() {
11
13
  const middleware = function ezlogsInngestV4() {
12
- if (!warnedUnsupported) {
13
- warnedUnsupported = true;
14
- logger.warn(
15
- "ezlogsInngestMiddleware supports Inngest v3 only; on this Inngest version it does nothing (jobs are not captured)"
16
- );
17
- }
18
- return {};
14
+ return inngestV4Hooks();
19
15
  };
20
16
  Object.defineProperty(middleware, "name", { value: "ezlogs-nextjs" });
21
17
  return Object.assign(middleware, {
@@ -25,6 +21,7 @@ function ezlogsInngestMiddleware() {
25
21
  // one function). Returns per-run hooks that fire as the run
26
22
  // proceeds. We track the run via closure-scoped state.
27
23
  onFunctionRun(args) {
24
+ markJobDelivery();
28
25
  const fnId = functionId(args.fn) ?? "inngest-function";
29
26
  const runId = args.ctx?.runId ?? null;
30
27
  const attempt = typeof args.ctx?.attempt === "number" ? args.ctx.attempt : 0;
@@ -36,16 +33,19 @@ function ezlogsInngestMiddleware() {
36
33
  return {
37
34
  // Inngest calls this once after the function body returns
38
35
  // (success) or throws (failure surfaces via result.error).
36
+ // `step`: the step this execution ran (none on the one where the function returns).
39
37
  transformOutput(args2) {
40
38
  try {
41
39
  const result = args2.result;
42
40
  const error = result?.error;
43
41
  const outcome = error ? "failure" : "success";
44
42
  const errorMessage = error ? formatError(error) : null;
43
+ const ranStep = args2.step?.displayName ?? args2.step?.name;
45
44
  emitJobEvent({
46
45
  jobClass: fnId,
47
46
  jobId: runId,
48
47
  queue: eventName,
48
+ step: typeof ranStep === "string" && ranStep ? ranStep : null,
49
49
  retryCount: attempt,
50
50
  correlationId,
51
51
  outcome,
@@ -70,33 +70,7 @@ function ezlogsInngestMiddleware() {
70
70
  // objects are never written (one reused across requests
71
71
  // would carry the first request's id and actor).
72
72
  transformInput(args) {
73
- try {
74
- const id = current();
75
- if (!id) return;
76
- if (!Array.isArray(args.payloads)) return;
77
- const stamped = [];
78
- const payloads = args.payloads.map((payload) => {
79
- if (!payload || typeof payload !== "object") return payload;
80
- const data = payload.data ?? {};
81
- if (typeof data !== "object" || data === null || Array.isArray(data)) {
82
- return payload;
83
- }
84
- if (typeof data.ezlogs_correlation_id === "string") {
85
- return payload;
86
- }
87
- const copy = { ...data, ezlogs_correlation_id: id };
88
- if (!(ACTOR_PAYLOAD_KEY in copy)) stamped.push(copy);
89
- return { ...payload, data: copy };
90
- });
91
- const pending = stamped.length > 0 ? signedActorToken(id) : null;
92
- if (!pending) return { payloads };
93
- return pending.then((token) => {
94
- if (token) for (const data of stamped) data[ACTOR_PAYLOAD_KEY] = token;
95
- return { payloads };
96
- });
97
- } catch (error) {
98
- logger.debug(`inngest send-stamp failed: ${describeError(error)}`);
99
- }
73
+ return stampSendEvents(args.payloads, (payloads) => ({ payloads }));
100
74
  }
101
75
  };
102
76
  }
@@ -104,7 +78,143 @@ function ezlogsInngestMiddleware() {
104
78
  }
105
79
  });
106
80
  }
81
+ function inngestV4Hooks() {
82
+ let runError = null;
83
+ let ranStep = null;
84
+ let executed = false;
85
+ return {
86
+ id: "ezlogs-nextjs",
87
+ // Before the function sees (and Inngest validates) its events: our keys
88
+ // are removed, so a trigger or `waitForEvent` with a strict schema
89
+ // still accepts them. The scope was opened from the request body.
90
+ transformFunctionInput(arg) {
91
+ executed = true;
92
+ try {
93
+ return withoutCarriedKeysInInput(arg);
94
+ } catch (error) {
95
+ logger.debug(`inngest input strip failed: ${describeError(error)}`);
96
+ return arg;
97
+ }
98
+ },
99
+ // Called for `inngest.send` and `step.sendEvent`; returns the arg with stamped copies.
100
+ transformSendEvent(args) {
101
+ return stampSendEvents(args?.events, (events) => ({ ...args, events })) ?? args;
102
+ },
103
+ // Only for steps that run in this request (`step.run`, `step.sendEvent`), not memoized ones.
104
+ onStepStart(args) {
105
+ const options = args?.stepInfo?.options;
106
+ const name = options?.name ?? options?.id;
107
+ ranStep = typeof name === "string" && name ? name : null;
108
+ },
109
+ onStepError(args) {
110
+ runError = args?.error ?? runError;
111
+ },
112
+ onRunError(args) {
113
+ runError = args?.error ?? runError;
114
+ },
115
+ async wrapRequest(args) {
116
+ let nextCalled = false;
117
+ const next = () => {
118
+ nextCalled = true;
119
+ return args.next();
120
+ };
121
+ try {
122
+ const body = args.fn ? await args.requestInfo?.body?.() : null;
123
+ if (!body || typeof body !== "object") return await next();
124
+ const fnId = functionId(args.fn) ?? "inngest-function";
125
+ const event = body.event;
126
+ const attempt = typeof body.ctx?.attempt === "number" ? body.ctx.attempt : 0;
127
+ const runId = args.runId || body.ctx?.run_id || null;
128
+ return await runInsideInngestCorrelation(event, () => insideV4Run.run(true, async () => {
129
+ const startedAt = /* @__PURE__ */ new Date();
130
+ try {
131
+ return await next();
132
+ } catch (error) {
133
+ runError = error;
134
+ throw error;
135
+ } finally {
136
+ if (executed) {
137
+ markJobDelivery();
138
+ emitJobEvent({
139
+ jobClass: fnId,
140
+ jobId: runId,
141
+ queue: event?.name ?? null,
142
+ step: ranStep,
143
+ retryCount: attempt,
144
+ outcome: runError ? "failure" : "success",
145
+ errorMessage: runError ? formatError(runError) : null,
146
+ durationMs: Date.now() - startedAt.getTime(),
147
+ startedAt,
148
+ payload: event?.data
149
+ });
150
+ }
151
+ }
152
+ }));
153
+ } catch (error) {
154
+ if (nextCalled) throw error;
155
+ logger.debug(`inngest capture failed: ${describeError(error)}`);
156
+ return args.next();
157
+ }
158
+ }
159
+ };
160
+ }
161
+ function withoutCarriedKeysInInput(arg) {
162
+ const ctx = arg?.ctx;
163
+ if (!ctx) return arg;
164
+ let changed = false;
165
+ const strip = (value) => {
166
+ const out = withoutCarriedKeys(value);
167
+ if (out !== value) changed = true;
168
+ return out;
169
+ };
170
+ const event = strip(ctx.event);
171
+ const events = Array.isArray(ctx.events) ? ctx.events.map(strip) : ctx.events;
172
+ const steps = {};
173
+ for (const [id, step] of Object.entries(arg.steps ?? {})) {
174
+ steps[id] = step?.type === "data" ? { ...step, data: strip(step.data) } : step;
175
+ }
176
+ return changed ? { ...arg, ctx: { ...ctx, event, events }, steps } : arg;
177
+ }
178
+ function withoutCarriedKeys(event) {
179
+ const data = event?.data;
180
+ if (!data || typeof data !== "object" || Array.isArray(data)) return event;
181
+ if (!(CORRELATION_PAYLOAD_KEY in data) && !(ACTOR_PAYLOAD_KEY in data)) return event;
182
+ const rest = { ...data };
183
+ delete rest[CORRELATION_PAYLOAD_KEY];
184
+ delete rest[ACTOR_PAYLOAD_KEY];
185
+ return { ...event, data: rest };
186
+ }
187
+ function stampSendEvents(events, wrap) {
188
+ try {
189
+ const id = current();
190
+ if (!id) return;
191
+ if (!Array.isArray(events)) return;
192
+ const stamped = [];
193
+ const payloads = events.map((payload) => {
194
+ if (!payload || typeof payload !== "object") return payload;
195
+ const data = payload.data ?? {};
196
+ if (typeof data !== "object" || data === null || Array.isArray(data)) {
197
+ return payload;
198
+ }
199
+ if (typeof data.ezlogs_correlation_id === "string") {
200
+ return payload;
201
+ }
202
+ const copy = { ...data, ezlogs_correlation_id: id };
203
+ if (!(ACTOR_PAYLOAD_KEY in copy)) stamped.push(copy);
204
+ return { ...payload, data: copy };
205
+ });
206
+ const pending = stamped.length > 0 ? signedActorToken(id) : null;
207
+ if (!pending) return wrap(payloads);
208
+ return pending.then((token) => {
209
+ if (token) for (const data of stamped) data[ACTOR_PAYLOAD_KEY] = token;
210
+ return wrap(payloads);
211
+ });
212
+ } catch (error) {
213
+ logger.debug(`inngest send-stamp failed: ${describeError(error)}`);
214
+ }
215
+ }
107
216
  async function runInsideInngestCorrelation(event, callback) {
217
+ if (insideV4Run.read()) return callback();
108
218
  const carried = extractCorrelationFromPayload(event?.data);
109
219
  const id = carried ?? generate();
110
220
  const token = event?.data?.[ACTOR_PAYLOAD_KEY];
@@ -143,5 +253,17 @@ function describeError(error) {
143
253
  if (error instanceof Error) return `${error.name}: ${error.message}`;
144
254
  return String(error);
145
255
  }
256
+ function withEzlogsMiddleware(args) {
257
+ const [options, ...rest] = args;
258
+ if (!options || typeof options !== "object" || Array.isArray(options)) return args;
259
+ const opts = options;
260
+ const existing = Array.isArray(opts.middleware) ? opts.middleware : opts.middleware == null ? [] : null;
261
+ if (existing === null) return args;
262
+ if (existing.some((m) => m?.name === "ezlogs-nextjs")) return args;
263
+ return [{ ...opts, middleware: [...existing, ezlogsInngestMiddleware()] }, ...rest];
264
+ }
265
+ var __ezlogsInstrument = instrumentFrom({
266
+ "inngest#Inngest": (original) => instrumentClass(original, (client) => client, withEzlogsMiddleware)
267
+ });
146
268
 
147
- export { ezlogsInngestMiddleware, runInsideInngestCorrelation };
269
+ export { __ezlogsInstrument, ezlogsInngestMiddleware, runInsideInngestCorrelation };
@@ -1,9 +1,9 @@
1
1
  'use strict';
2
2
 
3
- var chunkR6IWVTX3_cjs = require('../chunk-R6IWVTX3.cjs');
4
- require('../chunk-GMHOUAKD.cjs');
5
- require('../chunk-YXZZNZG6.cjs');
6
- require('../chunk-MMLQXSSD.cjs');
3
+ var chunkKOFR5OC3_cjs = require('../chunk-KOFR5OC3.cjs');
4
+ require('../chunk-EXGEA4KE.cjs');
5
+ require('../chunk-UC2KS5EG.cjs');
6
+ require('../chunk-2YCQFLXW.cjs');
7
7
  require('../chunk-TWTG5ILJ.cjs');
8
8
  require('../chunk-ZDSQYCYV.cjs');
9
9
 
@@ -41,21 +41,21 @@ function wrapPgmqSchema(schema) {
41
41
  }
42
42
  function stampPgmqMessage(args) {
43
43
  if ("message" in args && isPlainObject(args.message)) {
44
- return { ...args, message: chunkR6IWVTX3_cjs.stampCorrelationOnPayload(args.message) };
44
+ return { ...args, message: chunkKOFR5OC3_cjs.stampCorrelationOnPayload(args.message) };
45
45
  }
46
46
  if (Array.isArray(args.messages)) {
47
47
  return {
48
48
  ...args,
49
49
  messages: args.messages.map(
50
- (msg) => isPlainObject(msg) ? chunkR6IWVTX3_cjs.stampCorrelationOnPayload(msg) : msg
50
+ (msg) => isPlainObject(msg) ? chunkKOFR5OC3_cjs.stampCorrelationOnPayload(msg) : msg
51
51
  )
52
52
  };
53
53
  }
54
54
  return args;
55
55
  }
56
56
  async function captureQueueMessage(meta, work) {
57
- const correlationId = chunkR6IWVTX3_cjs.extractCorrelationFromPayload(meta.message);
58
- return chunkR6IWVTX3_cjs.runJobWithCapture(
57
+ const correlationId = chunkKOFR5OC3_cjs.extractCorrelationFromPayload(meta.message);
58
+ return chunkKOFR5OC3_cjs.runJobWithCapture(
59
59
  {
60
60
  jobClass: meta.queueName,
61
61
  jobId: meta.messageId !== void 0 && meta.messageId !== null ? String(meta.messageId) : null,
@@ -69,7 +69,7 @@ async function captureQueueMessage(meta, work) {
69
69
  }
70
70
  function stampPgmqPayload(message) {
71
71
  if (!isPlainObject(message)) return message;
72
- return chunkR6IWVTX3_cjs.stampCorrelationOnPayload(message);
72
+ return chunkKOFR5OC3_cjs.stampCorrelationOnPayload(message);
73
73
  }
74
74
  function isPlainObject(value) {
75
75
  if (value === null || typeof value !== "object") return false;