ezlogs-nextjs 0.2.0 → 0.3.1

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 (51) hide show
  1. package/README.md +53 -16
  2. package/bin/install-triggers.cjs +73 -11
  3. package/dist/actors/index.cjs +5 -37
  4. package/dist/actors/index.js +2 -34
  5. package/dist/chunk-C5OSM557.js +39 -0
  6. package/dist/chunk-CE3R7DVB.js +1127 -0
  7. package/dist/chunk-CU45I2WR.js +498 -0
  8. package/dist/chunk-DKRNNI4I.js +180 -0
  9. package/dist/chunk-SIAA4J6H.js +17 -0
  10. package/dist/chunk-UQHEW6ER.js +119 -0
  11. package/dist/chunk-UWHYJH4M.cjs +126 -0
  12. package/dist/chunk-V5YNKKTG.cjs +42 -0
  13. package/dist/chunk-WASXTDLW.cjs +1151 -0
  14. package/dist/chunk-Y5NSHKWQ.cjs +182 -0
  15. package/dist/chunk-YX2XPLOA.cjs +508 -0
  16. package/dist/chunk-ZDSQYCYV.cjs +21 -0
  17. package/dist/db/drizzle.cjs +6 -713
  18. package/dist/db/drizzle.js +5 -712
  19. package/dist/db/prisma.cjs +52 -763
  20. package/dist/db/prisma.d.cts +3 -1
  21. package/dist/db/prisma.d.ts +3 -1
  22. package/dist/db/prisma.js +38 -749
  23. package/dist/db/supabase.cjs +21 -728
  24. package/dist/db/supabase.js +14 -721
  25. package/dist/index.cjs +204 -2181
  26. package/dist/index.js +107 -2090
  27. package/dist/jobs/bullmq.cjs +61 -552
  28. package/dist/jobs/bullmq.d.cts +8 -3
  29. package/dist/jobs/bullmq.d.ts +8 -3
  30. package/dist/jobs/bullmq.js +58 -549
  31. package/dist/jobs/inngest.cjs +23 -561
  32. package/dist/jobs/inngest.d.cts +7 -5
  33. package/dist/jobs/inngest.d.ts +7 -5
  34. package/dist/jobs/inngest.js +19 -557
  35. package/dist/jobs/supabase-queues.cjs +17 -603
  36. package/dist/jobs/supabase-queues.js +12 -598
  37. package/dist/jobs/trigger.cjs +18 -587
  38. package/dist/jobs/trigger.js +16 -585
  39. package/dist/jobs/upstash-workflow.cjs +62 -584
  40. package/dist/jobs/upstash-workflow.d.cts +17 -2
  41. package/dist/jobs/upstash-workflow.d.ts +17 -2
  42. package/dist/jobs/upstash-workflow.js +59 -582
  43. package/dist/nextjs-plugin/index.cjs +1 -1
  44. package/dist/nextjs-plugin/index.js +1 -1
  45. package/dist/nextjs-plugin/loader.cjs +21 -25
  46. package/dist/nextjs-plugin/loader.js +1 -5
  47. package/dist/triggers/index.cjs +40 -1234
  48. package/dist/triggers/index.d.cts +7 -2
  49. package/dist/triggers/index.d.ts +7 -2
  50. package/dist/triggers/index.js +6 -1221
  51. package/package.json +4 -1
@@ -19,6 +19,10 @@ interface BullWorkerLike {
19
19
  on: Function;
20
20
  off?: Function;
21
21
  name?: string;
22
+ /** BullMQ internal: the processor `callProcessJob` invokes. */
23
+ processFn?: Function;
24
+ /** BullMQ internal: calls `this.processFn(job, token, signal)`. */
25
+ callProcessJob?: Function;
22
26
  }
23
27
  /**
24
28
  * Patches `queue.add` (and `queue.addBulk` when present) so each
@@ -30,9 +34,10 @@ interface BullWorkerLike {
30
34
  */
31
35
  declare function wrapBullQueue<T extends BullQueueLike>(queue: T): T;
32
36
  /**
33
- * Subscribes capture listeners to a BullMQ Worker. Each completed /
34
- * failed job emits one event. We use `attemptsMade` for retry_count
35
- * (parity with Sidekiq's `retry_count`).
37
+ * Captures a BullMQ Worker's jobs: one event per run, with the
38
+ * processor running inside the job's correlation scope (see the file
39
+ * header). Sandboxed processors (a file path) run in a child process:
40
+ * the job event is still captured, their DB writes are not tagged.
36
41
  *
37
42
  * Idempotent — calling on the same worker twice is a no-op.
38
43
  */
@@ -1,545 +1,8 @@
1
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
- }) : x)(function(x) {
4
- if (typeof require !== "undefined") return require.apply(this, arguments);
5
- throw Error('Dynamic require of "' + x + '" is not supported');
6
- });
7
-
8
- // src/logger.ts
9
- var LEVEL_RANK = {
10
- debug: 10,
11
- info: 20,
12
- warn: 30,
13
- error: 40,
14
- silent: 100
15
- };
16
- var LEVEL_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:log-level");
17
- function readLevel() {
18
- const g = globalThis;
19
- return g[LEVEL_KEY] ?? "warn";
20
- }
21
- function shouldLog(level) {
22
- return LEVEL_RANK[level] >= LEVEL_RANK[readLevel()];
23
- }
24
- function safeWrite(level, message) {
25
- try {
26
- if (!shouldLog(level)) return;
27
- const line = `[ezlogs] ${message}`;
28
- if (level === "error" || level === "warn") {
29
- console.error(line);
30
- } else {
31
- console.log(line);
32
- }
33
- } catch {
34
- }
35
- }
36
- var logger = {
37
- debug: (message) => safeWrite("debug", message),
38
- info: (message) => safeWrite("info", message),
39
- warn: (message) => safeWrite("warn", message),
40
- error: (message) => safeWrite("error", message)
41
- };
42
-
43
- // src/event-builder.ts
44
- var SENSITIVE_KEYS = Object.freeze([
45
- "password",
46
- "token",
47
- "secret",
48
- "api_key",
49
- "credit_card"
50
- ]);
51
- var VALID_SOURCE_TYPES = [
52
- "http_request",
53
- "background_job",
54
- "database_callback"
55
- ];
56
- var VALID_OUTCOMES = ["success", "failure"];
57
- function build(input) {
58
- const source_type = validateSourceType(input.source_type);
59
- const source_data_raw = validateSourceData(input.source_data);
60
- const outcome = validateOutcome(input.outcome);
61
- const timestamp = validateTimestamp(input.timestamp ?? null);
62
- const resource_ids = validateResourceIds(input.resource_ids ?? []);
63
- const context_raw = validateContext();
64
- const duration_ms = validateDurationMs(input.duration_ms ?? null);
65
- const error_message = input.error_message ?? null;
66
- validateOutcomeErrorConsistency(outcome, error_message);
67
- const source_data = sanitizeRecord(source_data_raw);
68
- const context = context_raw === null ? null : sanitizeRecord(context_raw);
69
- const correlation_id = input.correlation_id ?? null;
70
- const event = {
71
- timestamp,
72
- source_type,
73
- source_data,
74
- outcome,
75
- correlation_id,
76
- resource_ids,
77
- context,
78
- duration_ms,
79
- error_message
80
- };
81
- return event;
82
- }
83
- function validateSourceType(value) {
84
- const normalized = String(value);
85
- if (!VALID_SOURCE_TYPES.includes(normalized)) {
86
- throw new ArgError(
87
- `source_type must be one of ${VALID_SOURCE_TYPES.join(", ")}, got: ${normalized}`
88
- );
89
- }
90
- return normalized;
91
- }
92
- function validateSourceData(value) {
93
- if (value === null || value === void 0) {
94
- throw new ArgError("source_data is required");
95
- }
96
- if (!isPlainObject(value)) {
97
- throw new ArgError(
98
- `source_data must be an object, got: ${describe(value)}`
99
- );
100
- }
101
- return value;
102
- }
103
- function validateOutcome(value) {
104
- if (value === null || value === void 0) {
105
- throw new ArgError("outcome is required");
106
- }
107
- const normalized = String(value);
108
- if (!VALID_OUTCOMES.includes(normalized)) {
109
- throw new ArgError(
110
- `outcome must be one of ${VALID_OUTCOMES.join(", ")}, got: ${normalized}`
111
- );
112
- }
113
- return normalized;
114
- }
115
- function validateTimestamp(value) {
116
- if (value === null) {
117
- return (/* @__PURE__ */ new Date()).toISOString();
118
- }
119
- if (typeof value === "string") {
120
- const parsed = new Date(value);
121
- if (Number.isNaN(parsed.getTime())) {
122
- throw new ArgError(
123
- `timestamp must be valid ISO 8601 format, got: ${value}`
124
- );
125
- }
126
- return value;
127
- }
128
- if (value instanceof Date) {
129
- if (Number.isNaN(value.getTime())) {
130
- throw new ArgError("timestamp must be a valid Date");
131
- }
132
- return value.toISOString();
133
- }
134
- throw new ArgError(
135
- `timestamp must be a string or Date, got: ${describe(value)}`
136
- );
137
- }
138
- function validateResourceIds(value) {
139
- if (!Array.isArray(value)) {
140
- throw new ArgError(`resource_ids must be an array, got: ${describe(value)}`);
141
- }
142
- value.forEach((entry, index) => {
143
- if (!isPlainObject(entry)) {
144
- throw new ArgError(
145
- `resource_ids[${index}] must be an object, got: ${describe(entry)}`
146
- );
147
- }
148
- const e = entry;
149
- if (!("resource_type" in e) || !("resource_id" in e)) {
150
- throw new ArgError(
151
- `resource_ids[${index}] must have resource_type and resource_id keys, got: ${Object.keys(e).join(", ")}`
152
- );
153
- }
154
- if (typeof e.resource_type !== "string") {
155
- throw new ArgError(
156
- `resource_ids[${index}].resource_type must be a string, got: ${describe(e.resource_type)}`
157
- );
158
- }
159
- if (typeof e.resource_id !== "string") {
160
- throw new ArgError(
161
- `resource_ids[${index}].resource_id must be a string, got: ${describe(e.resource_id)}`
162
- );
163
- }
164
- });
165
- return value;
166
- }
167
- function validateContext(value) {
168
- return null;
169
- }
170
- function validateDurationMs(value) {
171
- if (value === null || value === void 0) return null;
172
- if (typeof value !== "number" || !Number.isFinite(value)) {
173
- throw new ArgError(`duration_ms must be a number, got: ${describe(value)}`);
174
- }
175
- if (!Number.isInteger(value)) {
176
- throw new ArgError(`duration_ms must be an integer, got: ${value}`);
177
- }
178
- if (value < 0) {
179
- throw new ArgError(`duration_ms must be >= 0, got: ${value}`);
180
- }
181
- return value;
182
- }
183
- function validateOutcomeErrorConsistency(outcome, error_message) {
184
- if (outcome === "failure") {
185
- if (error_message === null || error_message === "") {
186
- throw new ArgError("error_message is required when outcome is 'failure'");
187
- }
188
- } else if (outcome === "success") {
189
- if (error_message !== null) {
190
- throw new ArgError("error_message must be null when outcome is 'success'");
191
- }
192
- }
193
- }
194
- function sanitizeRecord(input) {
195
- const result = {};
196
- for (const key of Object.keys(input)) {
197
- const value = input[key];
198
- if (isSensitiveKey(key)) {
199
- result[key] = "[FILTERED]";
200
- } else if (isPlainObject(value)) {
201
- result[key] = sanitizeRecord(value);
202
- } else if (Array.isArray(value)) {
203
- result[key] = value.map(
204
- (item) => isPlainObject(item) ? sanitizeRecord(item) : item
205
- );
206
- } else {
207
- result[key] = value;
208
- }
209
- }
210
- return result;
211
- }
212
- function isSensitiveKey(key) {
213
- const lower = key.toLowerCase();
214
- return SENSITIVE_KEYS.some((p) => lower.includes(p));
215
- }
216
- function isPlainObject(value) {
217
- if (value === null || typeof value !== "object") return false;
218
- const proto = Object.getPrototypeOf(value);
219
- return proto === Object.prototype || proto === null;
220
- }
221
- function describe(value) {
222
- if (value === null) return "null";
223
- if (Array.isArray(value)) return "Array";
224
- return typeof value;
225
- }
226
- var ArgError = class extends Error {
227
- constructor(message) {
228
- super(message);
229
- this.name = "ArgError";
230
- }
231
- };
232
-
233
- // src/configuration.ts
234
- var DEFAULT_EXCLUDED_PATHS = Object.freeze([
235
- // Next.js / Vercel infrastructure noise
236
- "/_next/*",
237
- "/_vercel/*",
238
- "/__nextjs_*",
239
- // NextAuth.js / Auth.js — skip session-refresh polls and CSRF/provider
240
- // metadata GETs (high-frequency, no business meaning), but CAPTURE
241
- // POSTs (callbacks, signin, signout, register). The POSTs are the
242
- // actual auth events users care about; the GETs are pure plumbing.
243
- Object.freeze({ path: "/api/auth/*", methods: ["GET", "HEAD"] }),
244
- // Generic infrastructure
245
- "/health*",
246
- "/api/health",
247
- "/up",
248
- "/alive",
249
- "/ready",
250
- "/metrics",
251
- "/favicon.ico",
252
- "/.well-known*",
253
- "/robots.txt",
254
- "/sitemap.xml",
255
- "/*.hot-update.*",
256
- // Auth routes (common patterns across Clerk, NextAuth, custom auth)
257
- "*/login*",
258
- "*/logout*",
259
- "*/sign-in*",
260
- "*/sign-out*",
261
- "*/signin*",
262
- "*/signout*",
263
- "/session*"
264
- ]);
265
- var DEFAULT_EXCLUDED_TABLES = Object.freeze([
266
- // Prisma migration ledger
267
- "_prisma_migrations",
268
- // Auth.js / NextAuth Prisma adapter — session/verification-token churn
269
- // is auth machinery, not business activity. Account/User stay captured.
270
- "Session",
271
- "VerificationToken",
272
- // Common cross-stack convention names for the same things
273
- "sessions",
274
- "session",
275
- "verification_tokens"
276
- ]);
277
- var DEFAULT_EXCLUDED_JOB_CLASSES = Object.freeze([]);
278
- var DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS = Object.freeze(["IntrospectionQuery", "__*"]);
279
- var Configuration = class {
280
- serverUrl = null;
281
- projectToken = null;
282
- captureHttp = true;
283
- captureDb = true;
284
- captureJobs = true;
285
- bufferSize = 1e4;
286
- /** Default 3000 ms — equivalent to Ruby's 3 seconds. */
287
- sendInterval = 3e3;
288
- retryAttempts = 3;
289
- logLevel = "warn";
290
- patchGlobalFetch = true;
291
- actorFromSupabase = true;
292
- allowInsecureTransport = false;
293
- excludedPaths = [];
294
- excludedTables = [];
295
- excludedJobClasses = [];
296
- excludedGraphqlOperations = [];
297
- excludedGraphqlVariableKeys = [];
298
- actorFromRequest = null;
299
- displayNameFor = {};
300
- isServerActionError = null;
301
- databaseReader = null;
302
- databaseUrl = null;
303
- /**
304
- * Tables that have the `ezlogs_audit` trigger attached. Detected once
305
- * at agent startup by reading `information_schema.triggers`. The
306
- * supabase / drizzle / prisma adapters use this to decide whether
307
- * their per-mutation emit is redundant: if the table is trigger-
308
- * tracked the audit-log reader will surface the same write with full
309
- * old/new state, so the adapter's emit is suppressed. Tables NOT in
310
- * this set fall through to the adapter so they're still captured.
311
- *
312
- * `null` means "detection hasn't run yet or failed" — in that state
313
- * `databaseReader`-wired apps suppress every adapter emit (the
314
- * original Phase 5 behavior). After detection completes the agent
315
- * gives the more accurate per-table answer.
316
- */
317
- triggerTrackedTables = null;
318
- apply(options) {
319
- this.serverUrl = options.serverUrl;
320
- this.projectToken = options.projectToken;
321
- if (options.captureHttp !== void 0) this.captureHttp = options.captureHttp;
322
- if (options.captureDb !== void 0) this.captureDb = options.captureDb;
323
- if (options.captureJobs !== void 0) this.captureJobs = options.captureJobs;
324
- if (options.bufferSize !== void 0) this.bufferSize = options.bufferSize;
325
- if (options.sendInterval !== void 0) this.sendInterval = options.sendInterval;
326
- if (options.retryAttempts !== void 0) this.retryAttempts = options.retryAttempts;
327
- if (options.excludedPaths) this.excludedPaths = [...options.excludedPaths];
328
- if (options.excludedTables) this.excludedTables = [...options.excludedTables];
329
- if (options.excludedJobClasses) {
330
- this.excludedJobClasses = [...options.excludedJobClasses];
331
- }
332
- if (options.excludedGraphqlOperations) {
333
- this.excludedGraphqlOperations = [...options.excludedGraphqlOperations];
334
- }
335
- if (options.excludedGraphqlVariableKeys) {
336
- this.excludedGraphqlVariableKeys = [...options.excludedGraphqlVariableKeys];
337
- }
338
- if (options.actorFromRequest) this.actorFromRequest = options.actorFromRequest;
339
- if (options.displayNameFor) this.displayNameFor = { ...options.displayNameFor };
340
- if (options.isServerActionError) this.isServerActionError = options.isServerActionError;
341
- if (options.patchGlobalFetch !== void 0) {
342
- this.patchGlobalFetch = options.patchGlobalFetch;
343
- }
344
- if (options.allowInsecureTransport !== void 0) {
345
- this.allowInsecureTransport = options.allowInsecureTransport;
346
- }
347
- if (options.actorFromSupabase !== void 0) {
348
- this.actorFromSupabase = options.actorFromSupabase;
349
- }
350
- if (options.databaseReader !== void 0) {
351
- this.databaseReader = options.databaseReader;
352
- }
353
- if (options.databaseUrl !== void 0) {
354
- this.databaseUrl = options.databaseUrl;
355
- }
356
- if (options.logLevel) this.logLevel = options.logLevel;
357
- }
358
- allExcludedPaths() {
359
- return [...DEFAULT_EXCLUDED_PATHS, ...this.excludedPaths];
360
- }
361
- allExcludedTables() {
362
- return [...DEFAULT_EXCLUDED_TABLES, ...this.excludedTables];
363
- }
364
- allExcludedJobClasses() {
365
- return [...DEFAULT_EXCLUDED_JOB_CLASSES, ...this.excludedJobClasses];
366
- }
367
- allExcludedGraphqlOperations() {
368
- return [...DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS, ...this.excludedGraphqlOperations];
369
- }
370
- };
371
- var GLOBAL_CONFIG_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:configuration");
372
- function configuration() {
373
- const g = globalThis;
374
- if (!g[GLOBAL_CONFIG_KEY]) {
375
- g[GLOBAL_CONFIG_KEY] = new Configuration();
376
- }
377
- return g[GLOBAL_CONFIG_KEY];
378
- }
379
-
380
- // src/pipeline/buffer.ts
381
- var GLOBAL_QUEUE_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:buffer-queue");
382
- function getQueue() {
383
- const g = globalThis;
384
- if (!g[GLOBAL_QUEUE_KEY]) g[GLOBAL_QUEUE_KEY] = [];
385
- return g[GLOBAL_QUEUE_KEY];
386
- }
387
- function pushEvent(event) {
388
- try {
389
- const queue = getQueue();
390
- const max = maxSize();
391
- if (queue.length >= max) {
392
- queue.shift();
393
- logger.warn(`Buffer full (${max}), dropped oldest event`);
394
- }
395
- queue.push(event);
396
- } catch (error) {
397
- logger.error(`pushEvent failed: ${describe2(error)}`);
398
- }
399
- }
400
- function maxSize() {
401
- try {
402
- return configuration().bufferSize;
403
- } catch {
404
- return 1e4;
405
- }
406
- }
407
- function describe2(error) {
408
- if (error instanceof Error) return `${error.name}: ${error.message}`;
409
- return String(error);
410
- }
411
-
412
- // src/edge-fallback.ts
413
- var ALS_CTOR = loadAsyncLocalStorage();
414
- function loadAsyncLocalStorage() {
415
- const fromGlobal = globalThis.AsyncLocalStorage;
416
- if (typeof fromGlobal === "function") return fromGlobal;
417
- try {
418
- const req = typeof __require !== "undefined" ? __require : (
419
- // In ESM, `createRequire` is the official escape hatch.
420
- // We pull it via globalThis to avoid a static `import`
421
- // that would itself be browser-bundled.
422
- void 0
423
- );
424
- if (typeof req === "function") {
425
- const moduleName = ["async", "hooks"].join("_");
426
- const mod = req("node:" + moduleName);
427
- if (typeof mod.AsyncLocalStorage === "function") return mod.AsyncLocalStorage;
428
- }
429
- } catch {
430
- }
431
- return null;
432
- }
433
- function createScopedStorage(key = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:default-scoped-storage")) {
434
- const globalStore = globalThis;
435
- let entry = globalStore[key];
436
- if (!entry) {
437
- const als2 = (() => {
438
- if (!ALS_CTOR) return null;
439
- try {
440
- return new ALS_CTOR();
441
- } catch {
442
- return null;
443
- }
444
- })();
445
- entry = { als: als2, edgeFallback: null };
446
- globalStore[key] = entry;
447
- }
448
- const als = entry.als;
449
- const stateRef = entry;
450
- return {
451
- read() {
452
- if (als) return als.getStore()?.value ?? null;
453
- return stateRef.edgeFallback?.value ?? null;
454
- },
455
- run(value, callback) {
456
- if (als) return als.run({ value }, callback);
457
- const previous = stateRef.edgeFallback;
458
- stateRef.edgeFallback = { value };
459
- try {
460
- return callback();
461
- } finally {
462
- stateRef.edgeFallback = previous;
463
- }
464
- },
465
- update(value) {
466
- if (als) {
467
- const store = als.getStore();
468
- if (store) store.value = value;
469
- return;
470
- }
471
- stateRef.edgeFallback = { value };
472
- },
473
- _resetForTests() {
474
- stateRef.edgeFallback = null;
475
- },
476
- _isAsyncLocalStorage() {
477
- return als !== null;
478
- }
479
- };
480
- }
481
-
482
- // src/correlation.ts
483
- var storage = createScopedStorage(
484
- /* @__PURE__ */ Symbol.for("ezlogs-nextjs:correlation-storage")
485
- );
486
- function current() {
487
- return storage.read();
488
- }
489
-
490
- // src/jobs/shared.ts
491
- var CORRELATION_PAYLOAD_KEY = "ezlogs_correlation_id";
492
- function emitJobEvent(input) {
493
- try {
494
- const config = configuration();
495
- if (!config.captureJobs) return;
496
- if (config.allExcludedJobClasses().includes(input.jobClass)) return;
497
- const sourceData = compactJobSourceData({
498
- job_class: input.jobClass,
499
- job_id: input.jobId ?? null,
500
- queue: input.queue ?? null,
501
- retry_count: input.retryCount ?? null
502
- });
503
- const event = build({
504
- source_type: "background_job",
505
- source_data: sourceData,
506
- outcome: input.outcome,
507
- correlation_id: input.correlationId ?? current(),
508
- resource_ids: [],
509
- context: null,
510
- duration_ms: input.durationMs ?? null,
511
- error_message: input.errorMessage ?? null,
512
- timestamp: input.startedAt
513
- });
514
- pushEvent(event);
515
- } catch (error) {
516
- logger.debug(`job emit failed: ${describeError(error)}`);
517
- }
518
- }
519
- function extractCorrelationFromPayload(payload, key = CORRELATION_PAYLOAD_KEY) {
520
- if (payload === null || typeof payload !== "object") return null;
521
- const value = payload[key];
522
- return typeof value === "string" && value.length > 0 ? value : null;
523
- }
524
- function stampCorrelationOnPayload(payload, key = CORRELATION_PAYLOAD_KEY) {
525
- if (!payload || typeof payload !== "object") return;
526
- if (typeof payload[key] === "string" && payload[key]) return;
527
- const id = current();
528
- if (!id) return;
529
- payload[key] = id;
530
- }
531
- function compactJobSourceData(data) {
532
- const out = {};
533
- for (const key of Object.keys(data)) {
534
- const value = data[key];
535
- if (value !== null && value !== void 0) out[key] = value;
536
- }
537
- return out;
538
- }
539
- function describeError(error) {
540
- if (error instanceof Error) return `${error.name}: ${error.message}`;
541
- return String(error);
542
- }
1
+ import { runJobWithCapture, extractCorrelationFromPayload, emitJobEvent, stampCorrelationOnPayload, CORRELATION_PAYLOAD_KEY } from '../chunk-UQHEW6ER.js';
2
+ import '../chunk-CU45I2WR.js';
3
+ import '../chunk-CE3R7DVB.js';
4
+ import { logger } from '../chunk-C5OSM557.js';
5
+ import '../chunk-SIAA4J6H.js';
543
6
 
544
7
  // src/jobs/bullmq.ts
545
8
  var WRAPPED_FLAG = "__ezlogsBullWrapped";
@@ -563,6 +26,41 @@ function wrapBullQueue(queue) {
563
26
  }
564
27
  function wrapBullWorker(worker) {
565
28
  if (worker[WRAPPED_FLAG]) return worker;
29
+ const canWrapProcessor = typeof worker.processFn === "function" && typeof worker.callProcessJob === "function";
30
+ if (!canWrapProcessor && !warnedNoProcessor) {
31
+ warnedNoProcessor = true;
32
+ logger.debug(
33
+ "wrapBullWorker: this BullMQ Worker has no processFn/callProcessJob; capturing job events from completed/failed only (DB writes inside jobs are not linked)."
34
+ );
35
+ }
36
+ if (canWrapProcessor) {
37
+ const original = worker.processFn;
38
+ const reported = /* @__PURE__ */ new WeakSet();
39
+ worker.processFn = function ezlogsProcess(...args) {
40
+ const job = args[0] ?? {};
41
+ if (typeof args[0] === "object" && args[0] !== null) reported.add(args[0]);
42
+ return runJobWithCapture(
43
+ {
44
+ jobClass: job.name ?? worker.name ?? "BullMQJob",
45
+ jobId: job.id !== void 0 && job.id !== null ? String(job.id) : null,
46
+ queue: job.queueName ?? worker.name ?? null,
47
+ // attemptsMade counts finished attempts: 0 on the first run.
48
+ retryCount: typeof job.attemptsMade === "number" ? job.attemptsMade : null,
49
+ correlationId: extractCorrelationFromPayload(job.data),
50
+ payload: job.data,
51
+ isControlFlow: isBullControlFlow
52
+ },
53
+ () => Promise.resolve(original.apply(this, args))
54
+ );
55
+ };
56
+ worker.on("failed", (...args) => {
57
+ const job = args[0];
58
+ if (!job || reported.has(job)) return;
59
+ captureJob(job, worker, "failure", describeFailure(args[1]));
60
+ });
61
+ markWrapped(worker);
62
+ return worker;
63
+ }
566
64
  worker.on("completed", (...args) => {
567
65
  const job = args[0];
568
66
  if (!job) return;
@@ -570,17 +68,27 @@ function wrapBullWorker(worker) {
570
68
  });
571
69
  worker.on("failed", (...args) => {
572
70
  const job = args[0];
573
- const error = args[1];
574
71
  if (!job) return;
575
- const message = error ? `${error.name ?? "Error"}: ${error.message ?? String(error)}` : "Error: job failed";
576
- captureJob(job, worker, "failure", message);
72
+ captureJob(job, worker, "failure", describeFailure(args[1]));
577
73
  });
74
+ markWrapped(worker);
75
+ return worker;
76
+ }
77
+ var warnedNoProcessor = false;
78
+ function describeFailure(error) {
79
+ return error ? `${error.name ?? "Error"}: ${error.message ?? String(error)}` : "Error: job failed";
80
+ }
81
+ var BULL_CONTROL_FLOW_ERRORS = /* @__PURE__ */ new Set(["DelayedError", "WaitingError", "WaitingChildrenError"]);
82
+ function isBullControlFlow(error) {
83
+ const e = error;
84
+ return typeof e?.name === "string" && BULL_CONTROL_FLOW_ERRORS.has(e.name) || e?.message === "bullmq:rateLimitExceeded";
85
+ }
86
+ function markWrapped(worker) {
578
87
  Object.defineProperty(worker, WRAPPED_FLAG, {
579
88
  value: true,
580
89
  enumerable: false,
581
90
  configurable: false
582
91
  });
583
- return worker;
584
92
  }
585
93
  function captureJob(job, worker, outcome, errorMessage) {
586
94
  try {
@@ -596,10 +104,11 @@ function captureJob(job, worker, outcome, errorMessage) {
596
104
  outcome,
597
105
  errorMessage,
598
106
  durationMs,
599
- startedAt
107
+ startedAt,
108
+ payload: job.data
600
109
  });
601
110
  } catch (error) {
602
- logger.debug(`bullmq capture failed: ${describeError2(error)}`);
111
+ logger.debug(`bullmq capture failed: ${describeError(error)}`);
603
112
  }
604
113
  }
605
114
  function stampPayload(data) {
@@ -610,7 +119,7 @@ function stampPayload(data) {
610
119
  stampCorrelationOnPayload(obj, CORRELATION_PAYLOAD_KEY);
611
120
  return obj;
612
121
  }
613
- function describeError2(error) {
122
+ function describeError(error) {
614
123
  if (error instanceof Error) return `${error.name}: ${error.message}`;
615
124
  return String(error);
616
125
  }