ezlogs-nextjs 0.3.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 (43) hide show
  1. package/README.md +15 -2
  2. package/bin/install-triggers.cjs +33 -5
  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 -821
  18. package/dist/db/drizzle.js +5 -820
  19. package/dist/db/prisma.cjs +28 -853
  20. package/dist/db/prisma.js +14 -839
  21. package/dist/db/supabase.cjs +21 -836
  22. package/dist/db/supabase.js +14 -829
  23. package/dist/index.cjs +132 -2362
  24. package/dist/index.js +34 -2270
  25. package/dist/jobs/bullmq.cjs +13 -1465
  26. package/dist/jobs/bullmq.js +7 -1459
  27. package/dist/jobs/inngest.cjs +14 -1422
  28. package/dist/jobs/inngest.js +8 -1416
  29. package/dist/jobs/supabase-queues.cjs +15 -1467
  30. package/dist/jobs/supabase-queues.js +10 -1462
  31. package/dist/jobs/trigger.cjs +9 -1454
  32. package/dist/jobs/trigger.js +5 -1450
  33. package/dist/jobs/upstash-workflow.cjs +30 -1456
  34. package/dist/jobs/upstash-workflow.d.cts +2 -1
  35. package/dist/jobs/upstash-workflow.d.ts +2 -1
  36. package/dist/jobs/upstash-workflow.js +27 -1453
  37. package/dist/nextjs-plugin/index.cjs +1 -1
  38. package/dist/nextjs-plugin/index.js +1 -1
  39. package/dist/nextjs-plugin/loader.cjs +21 -25
  40. package/dist/nextjs-plugin/loader.js +1 -5
  41. package/dist/triggers/index.cjs +40 -1434
  42. package/dist/triggers/index.js +6 -1421
  43. package/package.json +2 -1
@@ -1,1456 +1,18 @@
1
1
  'use strict';
2
2
 
3
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
4
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
5
- }) : x)(function(x) {
6
- if (typeof require !== "undefined") return require.apply(this, arguments);
7
- throw Error('Dynamic require of "' + x + '" is not supported');
8
- });
9
-
10
- // src/logger.ts
11
- var LEVEL_RANK = {
12
- debug: 10,
13
- info: 20,
14
- warn: 30,
15
- error: 40,
16
- silent: 100
17
- };
18
- var LEVEL_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:log-level");
19
- function readLevel() {
20
- const g = globalThis;
21
- return g[LEVEL_KEY] ?? "warn";
22
- }
23
- function shouldLog(level) {
24
- return LEVEL_RANK[level] >= LEVEL_RANK[readLevel()];
25
- }
26
- function safeWrite(level, message) {
27
- try {
28
- if (!shouldLog(level)) return;
29
- const line = `[ezlogs] ${message}`;
30
- if (level === "error" || level === "warn") {
31
- console.error(line);
32
- } else {
33
- console.log(line);
34
- }
35
- } catch {
36
- }
37
- }
38
- var logger = {
39
- debug: (message) => safeWrite("debug", message),
40
- info: (message) => safeWrite("info", message),
41
- warn: (message) => safeWrite("warn", message),
42
- error: (message) => safeWrite("error", message)
43
- };
44
-
45
- // src/event-builder.ts
46
- var SENSITIVE_KEYS = Object.freeze([
47
- "password",
48
- "token",
49
- "secret",
50
- "api_key",
51
- "credit_card"
52
- ]);
53
- var VALID_SOURCE_TYPES = [
54
- "http_request",
55
- "background_job",
56
- "database_callback"
57
- ];
58
- var VALID_OUTCOMES = ["success", "failure"];
59
- function build(input) {
60
- const source_type = validateSourceType(input.source_type);
61
- const source_data_raw = validateSourceData(input.source_data);
62
- const outcome = validateOutcome(input.outcome);
63
- const timestamp = validateTimestamp(input.timestamp ?? null);
64
- const resource_ids = validateResourceIds(input.resource_ids ?? []);
65
- const context_raw = validateContext(input.context ?? null);
66
- const duration_ms = validateDurationMs(input.duration_ms ?? null);
67
- const error_message = input.error_message ?? null;
68
- validateOutcomeErrorConsistency(outcome, error_message);
69
- const source_data = sanitizeRecord(source_data_raw);
70
- const context = context_raw === null ? null : sanitizeRecord(context_raw);
71
- const correlation_id = input.correlation_id ?? null;
72
- const event = {
73
- timestamp,
74
- source_type,
75
- source_data,
76
- outcome,
77
- correlation_id,
78
- resource_ids,
79
- context,
80
- duration_ms,
81
- error_message
82
- };
83
- return event;
84
- }
85
- function validateSourceType(value) {
86
- if (value === null || value === void 0) {
87
- throw new ArgError("source_type is required");
88
- }
89
- const normalized = String(value);
90
- if (!VALID_SOURCE_TYPES.includes(normalized)) {
91
- throw new ArgError(
92
- `source_type must be one of ${VALID_SOURCE_TYPES.join(", ")}, got: ${normalized}`
93
- );
94
- }
95
- return normalized;
96
- }
97
- function validateSourceData(value) {
98
- if (value === null || value === void 0) {
99
- throw new ArgError("source_data is required");
100
- }
101
- if (!isPlainObject(value)) {
102
- throw new ArgError(
103
- `source_data must be an object, got: ${describe(value)}`
104
- );
105
- }
106
- return value;
107
- }
108
- function validateOutcome(value) {
109
- if (value === null || value === void 0) {
110
- throw new ArgError("outcome is required");
111
- }
112
- const normalized = String(value);
113
- if (!VALID_OUTCOMES.includes(normalized)) {
114
- throw new ArgError(
115
- `outcome must be one of ${VALID_OUTCOMES.join(", ")}, got: ${normalized}`
116
- );
117
- }
118
- return normalized;
119
- }
120
- function validateTimestamp(value) {
121
- if (value === null) {
122
- return (/* @__PURE__ */ new Date()).toISOString();
123
- }
124
- if (typeof value === "string") {
125
- const parsed = new Date(value);
126
- if (Number.isNaN(parsed.getTime())) {
127
- throw new ArgError(
128
- `timestamp must be valid ISO 8601 format, got: ${value}`
129
- );
130
- }
131
- return value;
132
- }
133
- if (value instanceof Date) {
134
- if (Number.isNaN(value.getTime())) {
135
- throw new ArgError("timestamp must be a valid Date");
136
- }
137
- return value.toISOString();
138
- }
139
- throw new ArgError(
140
- `timestamp must be a string or Date, got: ${describe(value)}`
141
- );
142
- }
143
- function validateResourceIds(value) {
144
- if (!Array.isArray(value)) {
145
- throw new ArgError(`resource_ids must be an array, got: ${describe(value)}`);
146
- }
147
- value.forEach((entry, index) => {
148
- if (!isPlainObject(entry)) {
149
- throw new ArgError(
150
- `resource_ids[${index}] must be an object, got: ${describe(entry)}`
151
- );
152
- }
153
- const e = entry;
154
- if (!("resource_type" in e) || !("resource_id" in e)) {
155
- throw new ArgError(
156
- `resource_ids[${index}] must have resource_type and resource_id keys, got: ${Object.keys(e).join(", ")}`
157
- );
158
- }
159
- if (typeof e.resource_type !== "string") {
160
- throw new ArgError(
161
- `resource_ids[${index}].resource_type must be a string, got: ${describe(e.resource_type)}`
162
- );
163
- }
164
- if (typeof e.resource_id !== "string") {
165
- throw new ArgError(
166
- `resource_ids[${index}].resource_id must be a string, got: ${describe(e.resource_id)}`
167
- );
168
- }
169
- });
170
- return value;
171
- }
172
- function validateContext(value) {
173
- if (value === null) return null;
174
- if (!isPlainObject(value)) {
175
- throw new ArgError(
176
- `context must be an object or null, got: ${describe(value)}`
177
- );
178
- }
179
- return value;
180
- }
181
- function validateDurationMs(value) {
182
- if (value === null || value === void 0) return null;
183
- if (typeof value !== "number" || !Number.isFinite(value)) {
184
- throw new ArgError(`duration_ms must be a number, got: ${describe(value)}`);
185
- }
186
- if (!Number.isInteger(value)) {
187
- throw new ArgError(`duration_ms must be an integer, got: ${value}`);
188
- }
189
- if (value < 0) {
190
- throw new ArgError(`duration_ms must be >= 0, got: ${value}`);
191
- }
192
- return value;
193
- }
194
- function validateOutcomeErrorConsistency(outcome, error_message) {
195
- if (outcome === "failure") {
196
- if (error_message === null || error_message === "") {
197
- throw new ArgError("error_message is required when outcome is 'failure'");
198
- }
199
- } else if (outcome === "success") {
200
- if (error_message !== null) {
201
- throw new ArgError("error_message must be null when outcome is 'success'");
202
- }
203
- }
204
- }
205
- function sanitizeRecord(input) {
206
- const result = {};
207
- for (const key of Object.keys(input)) {
208
- const value = input[key];
209
- if (isSensitiveKey(key)) {
210
- result[key] = "[FILTERED]";
211
- } else if (isPlainObject(value)) {
212
- result[key] = sanitizeRecord(value);
213
- } else if (Array.isArray(value)) {
214
- result[key] = value.map(
215
- (item) => isPlainObject(item) ? sanitizeRecord(item) : item
216
- );
217
- } else {
218
- result[key] = value;
219
- }
220
- }
221
- return result;
222
- }
223
- function isSensitiveKey(key) {
224
- const lower = key.toLowerCase();
225
- return SENSITIVE_KEYS.some((p) => lower.includes(p));
226
- }
227
- function isPlainObject(value) {
228
- if (value === null || typeof value !== "object") return false;
229
- const proto = Object.getPrototypeOf(value);
230
- return proto === Object.prototype || proto === null;
231
- }
232
- function describe(value) {
233
- if (value === null) return "null";
234
- if (Array.isArray(value)) return "Array";
235
- return typeof value;
236
- }
237
- var ArgError = class extends Error {
238
- constructor(message) {
239
- super(message);
240
- this.name = "ArgError";
241
- }
242
- };
243
-
244
- // src/configuration.ts
245
- var DEFAULT_EXCLUDED_PATHS = Object.freeze([
246
- // Next.js / Vercel infrastructure noise
247
- "/_next/*",
248
- "/_vercel/*",
249
- "/__nextjs_*",
250
- // NextAuth.js / Auth.js — skip session-refresh polls and CSRF/provider
251
- // metadata GETs (high-frequency, no business meaning), but CAPTURE
252
- // POSTs (callbacks, signin, signout, register). The POSTs are the
253
- // actual auth events users care about; the GETs are pure plumbing.
254
- Object.freeze({ path: "/api/auth/*", methods: ["GET", "HEAD"] }),
255
- // Generic infrastructure
256
- "/health*",
257
- "/api/health",
258
- "/up",
259
- "/alive",
260
- "/ready",
261
- "/metrics",
262
- "/favicon.ico",
263
- "/.well-known*",
264
- "/robots.txt",
265
- "/sitemap.xml",
266
- "/*.hot-update.*",
267
- // Auth routes (common patterns across Clerk, NextAuth, custom auth)
268
- "*/login*",
269
- "*/logout*",
270
- "*/sign-in*",
271
- "*/sign-out*",
272
- "*/signin*",
273
- "*/signout*",
274
- "/session*"
275
- ]);
276
- var DEFAULT_EXCLUDED_TABLES = Object.freeze([
277
- // Prisma migration ledger
278
- "_prisma_migrations",
279
- // Auth.js / NextAuth Prisma adapter — session/verification-token churn
280
- // is auth machinery, not business activity. Account/User stay captured.
281
- "Session",
282
- "VerificationToken",
283
- // Common cross-stack convention names for the same things
284
- "sessions",
285
- "session",
286
- "verification_tokens"
287
- ]);
288
- var DEFAULT_EXCLUDED_JOB_CLASSES = Object.freeze([]);
289
- var DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS = Object.freeze(["IntrospectionQuery", "__*"]);
290
- var Configuration = class {
291
- serverUrl = null;
292
- projectToken = null;
293
- captureHttp = true;
294
- captureDb = true;
295
- captureJobs = true;
296
- bufferSize = 1e4;
297
- /** Default 3000 ms — equivalent to Ruby's 3 seconds. */
298
- sendInterval = 3e3;
299
- retryAttempts = 3;
300
- logLevel = "warn";
301
- patchGlobalFetch = true;
302
- actorFromSupabase = true;
303
- allowInsecureTransport = false;
304
- excludedPaths = [];
305
- excludedTables = [];
306
- excludedJobClasses = [];
307
- excludedGraphqlOperations = [];
308
- excludedGraphqlVariableKeys = [];
309
- actorFromRequest = null;
310
- displayNameFor = {};
311
- isServerActionError = null;
312
- databaseReader = null;
313
- databaseUrl = null;
314
- /**
315
- * Tables that have the `ezlogs_audit` trigger attached. Detected once
316
- * at agent startup by reading `information_schema.triggers`. The
317
- * supabase / drizzle / prisma adapters use this to decide whether
318
- * their per-mutation emit is redundant: if the table is trigger-
319
- * tracked the audit-log reader will surface the same write with full
320
- * old/new state, so the adapter's emit is suppressed. Tables NOT in
321
- * this set fall through to the adapter so they're still captured.
322
- *
323
- * `null` means "detection hasn't run yet or failed" — in that state
324
- * `databaseReader`-wired apps suppress every adapter emit (the
325
- * original Phase 5 behavior). After detection completes the agent
326
- * gives the more accurate per-table answer.
327
- */
328
- triggerTrackedTables = null;
329
- apply(options) {
330
- this.serverUrl = options.serverUrl;
331
- this.projectToken = options.projectToken;
332
- if (options.captureHttp !== void 0) this.captureHttp = options.captureHttp;
333
- if (options.captureDb !== void 0) this.captureDb = options.captureDb;
334
- if (options.captureJobs !== void 0) this.captureJobs = options.captureJobs;
335
- if (options.bufferSize !== void 0) this.bufferSize = options.bufferSize;
336
- if (options.sendInterval !== void 0) this.sendInterval = options.sendInterval;
337
- if (options.retryAttempts !== void 0) this.retryAttempts = options.retryAttempts;
338
- if (options.excludedPaths) this.excludedPaths = [...options.excludedPaths];
339
- if (options.excludedTables) this.excludedTables = [...options.excludedTables];
340
- if (options.excludedJobClasses) {
341
- this.excludedJobClasses = [...options.excludedJobClasses];
342
- }
343
- if (options.excludedGraphqlOperations) {
344
- this.excludedGraphqlOperations = [...options.excludedGraphqlOperations];
345
- }
346
- if (options.excludedGraphqlVariableKeys) {
347
- this.excludedGraphqlVariableKeys = [...options.excludedGraphqlVariableKeys];
348
- }
349
- if (options.actorFromRequest) this.actorFromRequest = options.actorFromRequest;
350
- if (options.displayNameFor) this.displayNameFor = { ...options.displayNameFor };
351
- if (options.isServerActionError) this.isServerActionError = options.isServerActionError;
352
- if (options.patchGlobalFetch !== void 0) {
353
- this.patchGlobalFetch = options.patchGlobalFetch;
354
- }
355
- if (options.allowInsecureTransport !== void 0) {
356
- this.allowInsecureTransport = options.allowInsecureTransport;
357
- }
358
- if (options.actorFromSupabase !== void 0) {
359
- this.actorFromSupabase = options.actorFromSupabase;
360
- }
361
- if (options.databaseReader !== void 0) {
362
- this.databaseReader = options.databaseReader;
363
- }
364
- if (options.databaseUrl !== void 0) {
365
- this.databaseUrl = options.databaseUrl;
366
- }
367
- if (options.logLevel) this.logLevel = options.logLevel;
368
- }
369
- allExcludedPaths() {
370
- return [...DEFAULT_EXCLUDED_PATHS, ...this.excludedPaths];
371
- }
372
- allExcludedTables() {
373
- return [...DEFAULT_EXCLUDED_TABLES, ...this.excludedTables];
374
- }
375
- allExcludedJobClasses() {
376
- return [...DEFAULT_EXCLUDED_JOB_CLASSES, ...this.excludedJobClasses];
377
- }
378
- allExcludedGraphqlOperations() {
379
- return [...DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS, ...this.excludedGraphqlOperations];
380
- }
381
- };
382
- var GLOBAL_CONFIG_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:configuration");
383
- function configuration() {
384
- const g = globalThis;
385
- if (!g[GLOBAL_CONFIG_KEY]) {
386
- g[GLOBAL_CONFIG_KEY] = new Configuration();
387
- }
388
- return g[GLOBAL_CONFIG_KEY];
389
- }
390
-
391
- // src/pipeline/buffer.ts
392
- var GLOBAL_QUEUE_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:buffer-queue");
393
- function getQueue() {
394
- const g = globalThis;
395
- if (!g[GLOBAL_QUEUE_KEY]) g[GLOBAL_QUEUE_KEY] = [];
396
- return g[GLOBAL_QUEUE_KEY];
397
- }
398
- function pushEvent(event) {
399
- try {
400
- const queue = getQueue();
401
- const max = maxSize();
402
- if (queue.length >= max) {
403
- queue.shift();
404
- logger.warn(`Buffer full (${max}), dropped oldest event`);
405
- }
406
- queue.push(event);
407
- } catch (error) {
408
- logger.error(`pushEvent failed: ${describe2(error)}`);
409
- }
410
- }
411
- function maxSize() {
412
- try {
413
- return configuration().bufferSize;
414
- } catch {
415
- return 1e4;
416
- }
417
- }
418
- function describe2(error) {
419
- if (error instanceof Error) return `${error.name}: ${error.message}`;
420
- return String(error);
421
- }
422
-
423
- // src/edge-fallback.ts
424
- var ALS_CTOR = loadAsyncLocalStorage();
425
- function loadAsyncLocalStorage() {
426
- const fromGlobal = globalThis.AsyncLocalStorage;
427
- if (typeof fromGlobal === "function") return fromGlobal;
428
- try {
429
- const req = typeof __require !== "undefined" ? __require : (
430
- // In ESM, `createRequire` is the official escape hatch.
431
- // We pull it via globalThis to avoid a static `import`
432
- // that would itself be browser-bundled.
433
- void 0
434
- );
435
- if (typeof req === "function") {
436
- const moduleName = ["async", "hooks"].join("_");
437
- const mod = req("node:" + moduleName);
438
- if (typeof mod.AsyncLocalStorage === "function") return mod.AsyncLocalStorage;
439
- }
440
- } catch {
441
- }
442
- return null;
443
- }
444
- function createScopedStorage(key = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:default-scoped-storage")) {
445
- const globalStore = globalThis;
446
- let entry = globalStore[key];
447
- if (!entry) {
448
- const als2 = (() => {
449
- if (!ALS_CTOR) return null;
450
- try {
451
- return new ALS_CTOR();
452
- } catch {
453
- return null;
454
- }
455
- })();
456
- entry = { als: als2, edgeFallback: null };
457
- globalStore[key] = entry;
458
- }
459
- const als = entry.als;
460
- const stateRef = entry;
461
- return {
462
- read() {
463
- if (als) return als.getStore()?.value ?? null;
464
- return stateRef.edgeFallback?.value ?? null;
465
- },
466
- run(value, callback) {
467
- if (als) return als.run({ value }, callback);
468
- const previous = stateRef.edgeFallback;
469
- stateRef.edgeFallback = { value };
470
- try {
471
- return callback();
472
- } finally {
473
- stateRef.edgeFallback = previous;
474
- }
475
- },
476
- update(value) {
477
- if (als) {
478
- const store = als.getStore();
479
- if (store) store.value = value;
480
- return;
481
- }
482
- stateRef.edgeFallback = { value };
483
- },
484
- _resetForTests() {
485
- stateRef.edgeFallback = null;
486
- },
487
- _isAsyncLocalStorage() {
488
- return als !== null;
489
- }
490
- };
491
- }
492
-
493
- // src/correlation.ts
494
- var storage = createScopedStorage(
495
- /* @__PURE__ */ Symbol.for("ezlogs-nextjs:correlation-storage")
496
- );
497
- function generate() {
498
- const ts = Date.now();
499
- const hex = randomHexBytes(4);
500
- return `ezl_${ts}_${hex}`;
501
- }
502
- function randomHexBytes(byteCount) {
503
- const buf = new Uint8Array(byteCount);
504
- globalThis.crypto.getRandomValues(buf);
505
- let out = "";
506
- for (let i = 0; i < buf.length; i++) {
507
- out += buf[i].toString(16).padStart(2, "0");
508
- }
509
- return out;
510
- }
511
- function current() {
512
- return storage.read();
513
- }
514
- function runWithCorrelation(correlationId, callback) {
515
- return storage.run(correlationId, callback);
516
- }
517
-
518
- // src/http/sanitize.ts
519
- var SENSITIVE_VARIABLE_PATTERNS = Object.freeze([
520
- "password",
521
- "passwd",
522
- "pwd",
523
- "token",
524
- "access_token",
525
- "refresh_token",
526
- "api_token",
527
- "auth_token",
528
- "secret",
529
- "api_secret",
530
- "client_secret",
531
- "api_key",
532
- "apikey",
533
- "private_key",
534
- "privatekey",
535
- "public_key",
536
- "signing_key",
537
- "secret_key",
538
- "secretkey",
539
- "credential",
540
- "auth",
541
- "authorization",
542
- "encrypted",
543
- "encrypted_data",
544
- "ssn",
545
- "social_security",
546
- "credit_card",
547
- "card_number",
548
- "cvv",
549
- "cvc",
550
- // Crypto-material patterns — aligned with DB_SENSITIVE_PATTERNS
551
- // (PR #45). Request bodies can carry the same key material as DB
552
- // columns (a webhook POST containing a `signature` field, an HMAC
553
- // header echoed into a JSON body, a `pem`-encoded cert blob, etc).
554
- "pem",
555
- "cipher",
556
- "nonce",
557
- "salt",
558
- "digest",
559
- "signature",
560
- "hmac",
561
- // 0.2.0 additions (not yet in the Rails gem's list).
562
- "passcode",
563
- "cardnumber"
564
- ]);
565
- var SENSITIVE_WORD_PATTERNS = Object.freeze([
566
- "pin",
567
- "otp",
568
- "totp",
569
- "iban",
570
- "mfa",
571
- "passphrase"
572
- ]);
573
- function snakeLower(key) {
574
- return key.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
575
- }
576
- function matchesSensitiveKey(key, substringPatterns) {
577
- const lower = key.toLowerCase();
578
- const snake = snakeLower(key);
579
- if (substringPatterns.some((p) => lower.includes(p) || snake.includes(p))) {
580
- return true;
581
- }
582
- const words = snake.split(/[^a-z0-9]+/);
583
- return SENSITIVE_WORD_PATTERNS.some((w) => words.includes(w));
584
- }
585
- var MAX_NESTING_DEPTH = 3;
586
- var MAX_ARRAY_DISPLAY_SIZE = 5;
587
- function passesLuhn(digits) {
588
- let sum = 0;
589
- for (let i = 0; i < digits.length; i += 1) {
590
- let d = Number(digits[digits.length - 1 - i]);
591
- if (i % 2 === 1) {
592
- d *= 2;
593
- if (d > 9) d -= 9;
594
- }
595
- sum += d;
596
- }
597
- return sum % 10 === 0;
598
- }
599
- var SECRET_TEXT_PATTERNS = [
600
- /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,
601
- /\beyJ[\w-]+\.[\w-]+\.[\w-]+/g,
602
- /\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]+/g,
603
- /\bsk-[A-Za-z0-9_-]{16,}/g,
604
- /\bgh[pousr]_[A-Za-z0-9]{20,}/g,
605
- /\bxox[abposr]-[A-Za-z0-9-]+/g,
606
- /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g
607
- ];
608
- var EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;
609
- function scrubSecretsInText(text, options = {}) {
610
- let out = text;
611
- for (const pattern of SECRET_TEXT_PATTERNS) out = out.replace(pattern, "[FILTERED]");
612
- out = out.replace(/\b(Bearer|Basic)\s+[\w.~+/=-]+/gi, "$1 [FILTERED]").replace(/\b\d(?:[ -]?\d){12,18}\b/g, (match) => {
613
- const digits = match.replace(/[ -]/g, "");
614
- return (digits.length === 15 || digits.length === 16) && passesLuhn(digits) ? "[FILTERED]" : match;
615
- });
616
- return options.emails ? out.replace(EMAIL, "[FILTERED]") : out;
617
- }
618
- function sanitizeArgs(args, userPatterns = []) {
619
- return sanitizeArrayValue(args, 0, userPatterns);
620
- }
621
- function sanitizeValue(key, value, depth, userPatterns) {
622
- if (isSensitiveKey2(key, userPatterns)) return "[FILTERED]";
623
- if (isPlainObject2(value)) {
624
- return sanitizeNestedObject(value, depth, userPatterns);
625
- }
626
- if (Array.isArray(value)) {
627
- return sanitizeArrayValue(value, depth, userPatterns);
628
- }
629
- return value;
630
- }
631
- function sanitizeNestedObject(hash, depth, userPatterns) {
632
- if (depth >= MAX_NESTING_DEPTH) return "[Object]";
633
- if (Object.keys(hash).length === 0) return {};
634
- const out = {};
635
- for (const k of Object.keys(hash)) {
636
- out[k] = sanitizeValue(k, hash[k], depth + 1, userPatterns);
637
- }
638
- return out;
639
- }
640
- function sanitizeArrayValue(array, depth, userPatterns) {
641
- if (array.length === 0) return [];
642
- const allPrimitive = array.every(isPrimitive);
643
- if (allPrimitive) {
644
- if (array.length <= MAX_ARRAY_DISPLAY_SIZE) return array;
645
- const preview = array.slice(0, MAX_ARRAY_DISPLAY_SIZE);
646
- return `${JSON.stringify(preview)}... (${array.length} total)`;
647
- }
648
- if (array.length <= MAX_ARRAY_DISPLAY_SIZE) {
649
- return array.map((item) => sanitizeArrayItem(item, depth, userPatterns));
650
- }
651
- return {
652
- _truncated: true,
653
- _count: array.length,
654
- _preview: array.slice(0, MAX_ARRAY_DISPLAY_SIZE).map((item) => sanitizeArrayItem(item, depth, userPatterns))
655
- };
656
- }
657
- function sanitizeArrayItem(item, depth, userPatterns) {
658
- if (isPrimitive(item)) return item;
659
- if (isPlainObject2(item)) {
660
- return sanitizeNestedObject(item, depth + 1, userPatterns);
661
- }
662
- if (Array.isArray(item)) return sanitizeArrayValue(item, depth + 1, userPatterns);
663
- return "[Object]";
664
- }
665
- function isSensitiveKey2(key, userPatterns) {
666
- if (matchesSensitiveKey(key, SENSITIVE_VARIABLE_PATTERNS)) return true;
667
- const lower = key.toLowerCase();
668
- return userPatterns.some((p) => lower.includes(p.toLowerCase()));
669
- }
670
- function isPrimitive(value) {
671
- return value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
672
- }
673
- function isPlainObject2(value) {
674
- if (value === null || typeof value !== "object") return false;
675
- const proto = Object.getPrototypeOf(value);
676
- return proto === Object.prototype || proto === null;
677
- }
678
-
679
- // src/actor.ts
680
- var storage2 = createScopedStorage(
681
- /* @__PURE__ */ Symbol.for("ezlogs-nextjs:actor-storage")
682
- );
683
- function getCurrentActor() {
684
- return storage2.read();
685
- }
686
- function runWithActorScope(callback) {
687
- return storage2.run(null, callback);
688
- }
689
-
690
- // src/db/shared.ts
691
- var IGNORED_ATTRIBUTES = Object.freeze([
692
- "id",
693
- "createdAt",
694
- "created_at",
695
- "updatedAt",
696
- "updated_at",
697
- // Auth.js / NextAuth standard columns
698
- "emailVerified",
699
- "expires"
700
- ]);
701
- var DB_SENSITIVE_PATTERNS = Object.freeze([
702
- "password",
703
- "token",
704
- "secret",
705
- "api_key",
706
- "credit_card",
707
- "ssn",
708
- "social_security",
709
- "encrypted",
710
- "private_key",
711
- "public_key",
712
- "signing_key",
713
- "pem",
714
- "cipher",
715
- "nonce",
716
- "salt",
717
- "digest",
718
- "signature",
719
- "hmac",
720
- // 0.2.0 additions. `credential` / `passwd` / `apikey` were already in
721
- // the HTTP list; `passcode` / `card_number` / `cardnumber` / `cvv` /
722
- // `cvc` are new. Whole-word `pin` / `otp` / `totp` / `iban` come from
723
- // SENSITIVE_WORD_PATTERNS. The SQL trigger mirrors this list.
724
- "credential",
725
- "passwd",
726
- "passcode",
727
- "apikey",
728
- "card_number",
729
- "cardnumber",
730
- "cvv",
731
- "cvc"
732
- ]);
733
- function emitDbEvent(input) {
734
- try {
735
- const config = configuration();
736
- if (!config.captureDb) return;
737
- if (config.allExcludedTables().includes(input.modelClass)) return;
738
- if (config.databaseReader && !input._fromTrigger) {
739
- const tracked = config.triggerTrackedTables;
740
- if (tracked === null || tracked.has(input.table ?? input.modelClass)) return;
741
- }
742
- if (input.operation === "update") {
743
- const meaningful = input.changes ? filterMeaningfulChanges(input.changes) : [];
744
- if (meaningful.length === 0) return;
745
- }
746
- const resourceIdStr = input.resourceId === null || input.resourceId === void 0 ? null : String(input.resourceId);
747
- const related = resourceIdStr === null ? input.relatedResourceIds ?? [] : [];
748
- const context = buildContext(
749
- related.length > 0 ? { ...input, displayName: null, modelInstance: null } : input
750
- );
751
- const event = build({
752
- source_type: "database_callback",
753
- source_data: {
754
- model_class: input.modelClass,
755
- operation: input.operation
756
- },
757
- outcome: "success",
758
- correlation_id: current(),
759
- resource_ids: resourceIdStr === null ? [...related] : [{ resource_type: input.modelClass, resource_id: resourceIdStr }],
760
- context,
761
- duration_ms: null,
762
- timestamp: input.timestamp ?? null
763
- });
764
- pushEvent(event);
765
- } catch (error) {
766
- logger.debug(`db emit failed: ${describeError(error)}`);
767
- }
768
- }
769
- function buildContext(input) {
770
- const context = {};
771
- const actor = getCurrentActor();
772
- if (actor) context.actor = actor;
773
- if ((input.operation === "create" || input.operation === "destroy") && input.initialAttributes) {
774
- const filtered = filterMeaningfulAttributes(input.initialAttributes);
775
- if (filtered !== null) context.initial_attributes = filtered;
776
- }
777
- if (input.operation === "update" && input.changes) {
778
- const filtered = filterMeaningfulChanges(input.changes);
779
- if (filtered.length > 0) {
780
- context.changes = filtered.map((c) => {
781
- const out = {
782
- attribute: c.attribute,
783
- to: formatForJson(c.to)
784
- };
785
- if (c.from !== void 0) out.from = formatForJson(c.from);
786
- return out;
787
- });
788
- }
789
- }
790
- const displayName = input.displayName ?? (input.modelInstance ? resolveDisplayName(input.modelClass, input.modelInstance) : null);
791
- if (displayName !== null) context.display_name = displayName;
792
- return Object.keys(context).length === 0 ? null : context;
793
- }
794
- function filterMeaningfulAttributes(attrs) {
795
- const out = {};
796
- for (const key of Object.keys(attrs)) {
797
- if (!isMeaningfulAttribute(key)) continue;
798
- const value = attrs[key];
799
- if (value === null || value === void 0) continue;
800
- if (!isScalar(value)) continue;
801
- out[key] = formatForJson(value);
802
- }
803
- return Object.keys(out).length === 0 ? null : out;
804
- }
805
- function filterMeaningfulChanges(changes) {
806
- return flattenNestedChanges(changes).filter((c) => {
807
- if (!isMeaningfulAttribute(c.attribute)) return false;
808
- if (!isScalar(c.to)) return false;
809
- if (c.from === void 0) return true;
810
- if (!isScalar(c.from)) return false;
811
- return valuesActuallyChanged(c.from, c.to);
812
- });
813
- }
814
- var MAX_NESTED_DEPTH = 3;
815
- var MAX_NESTED_LEAVES = 20;
816
- var MAX_UNKNOWN_FROM_LEAVES = 5;
817
- function flattenNestedChanges(changes) {
818
- if (!changes.some((c) => isPlainRecord(c.to) || isPlainRecord(c.from))) return changes;
819
- const out = [];
820
- for (const c of changes) {
821
- if (!isPlainRecord(c.to) && !isPlainRecord(c.from)) {
822
- out.push(c);
823
- continue;
824
- }
825
- if (!isMeaningfulAttribute(c.attribute)) continue;
826
- const leaves = [];
827
- collectLeafChanges(c.attribute, c.from, c.to, 1, leaves);
828
- const cap = c.from === void 0 ? MAX_UNKNOWN_FROM_LEAVES : MAX_NESTED_LEAVES;
829
- out.push(...leaves.slice(0, cap).map(scrubLeaf));
830
- }
831
- return out;
832
- }
833
- function collectLeafChanges(path, from, to, depth, out) {
834
- if (out.length > MAX_NESTED_LEAVES) return;
835
- const fromObj = isPlainRecord(from);
836
- const toObj = isPlainRecord(to);
837
- if ((fromObj || toObj) && depth <= MAX_NESTED_DEPTH && (fromObj || from == null) && (toObj || to == null)) {
838
- const f = fromObj ? from : {};
839
- const t = toObj ? to : {};
840
- for (const key of /* @__PURE__ */ new Set([...Object.keys(f), ...Object.keys(t)])) {
841
- const before = from === void 0 ? void 0 : f[key] ?? null;
842
- collectLeafChanges(`${path}.${key}`, before, t[key] ?? null, depth + 1, out);
843
- }
844
- return;
845
- }
846
- if (from !== void 0 && sameJson(from, to)) return;
847
- out.push(from === void 0 ? { attribute: path, to } : { attribute: path, from, to });
848
- }
849
- function scrubLeaf(change) {
850
- const scrub = (v) => typeof v === "string" ? scrubSecretsInText(v) : v;
851
- const out = { attribute: change.attribute, to: scrub(change.to) };
852
- if (change.from !== void 0) out.from = scrub(change.from);
853
- return out;
854
- }
855
- function isPlainRecord(value) {
856
- if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
857
- const proto = Object.getPrototypeOf(value);
858
- return proto === Object.prototype || proto === null;
859
- }
860
- function sameJson(a, b) {
861
- if (a === b) return true;
862
- try {
863
- return JSON.stringify(a) === JSON.stringify(b);
864
- } catch {
865
- return false;
866
- }
867
- }
868
- function isMeaningfulAttribute(name) {
869
- if (IGNORED_ATTRIBUTES.includes(name)) return false;
870
- if (isDbSensitive(name)) return false;
871
- return true;
872
- }
873
- function isDbSensitive(name) {
874
- return matchesSensitiveKey(name, DB_SENSITIVE_PATTERNS);
875
- }
876
- function isScalar(value) {
877
- if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint" || value instanceof Date) {
878
- return true;
879
- }
880
- if (isPrismaDecimal(value)) return true;
881
- if (Buffer.isBuffer?.(value)) return false;
882
- if (Array.isArray(value)) return value.every((v) => isScalar(v));
883
- return false;
884
- }
885
- function valuesActuallyChanged(from, to) {
886
- if (from === null && to === null) return false;
887
- if (from instanceof Date && to instanceof Date) {
888
- return from.getTime() !== to.getTime();
889
- }
890
- return from !== to;
891
- }
892
- function formatForJson(value) {
893
- if (value === null || value === void 0) return value;
894
- if (value instanceof Date) return value.toISOString();
895
- if (typeof value === "bigint") return value.toString();
896
- if (isPrismaDecimal(value)) return Number(value.toString());
897
- if (Array.isArray(value)) return value.map(formatForJson);
898
- return value;
899
- }
900
- function isPrismaDecimal(value) {
901
- if (value === null || typeof value !== "object") return false;
902
- const obj = value;
903
- return typeof obj.toString === "function" && typeof obj.toFixed === "function" && "d" in obj && "e" in obj && "s" in obj;
904
- }
905
- var DISPLAY_NAME_COLUMNS = ["name", "title", "number", "label"];
906
- var MAX_DISPLAY_NAME_LENGTH = 120;
907
- function resolveDisplayName(modelClass, instance) {
908
- try {
909
- const config = configuration();
910
- const resolver = config.displayNameFor[modelClass];
911
- const resolved = applyResolver(resolver, instance);
912
- if (resolved !== null) return resolved;
913
- const columns = /* @__PURE__ */ new Map();
914
- for (const key of Object.keys(instance)) {
915
- if (isDbSensitive(key)) continue;
916
- const norm = key.toLowerCase().replace(/_/g, "");
917
- if (!columns.has(norm)) columns.set(norm, instance[key]);
918
- }
919
- const text = (norm) => {
920
- const value = columns.get(norm);
921
- if (typeof value !== "string" && typeof value !== "number" && typeof value !== "bigint") {
922
- return null;
923
- }
924
- const str = String(value).trim();
925
- return str.length > 0 ? str.slice(0, MAX_DISPLAY_NAME_LENGTH) : null;
926
- };
927
- for (const column of DISPLAY_NAME_COLUMNS) {
928
- const value = text(column);
929
- if (value !== null) return value;
930
- }
931
- return text(`${singularNorm(modelClass)}number`);
932
- } catch {
933
- }
934
- return null;
935
- }
936
- function singularNorm(modelClass) {
937
- const norm = modelClass.toLowerCase().replace(/_/g, "");
938
- if (norm.endsWith("ies")) return norm.slice(0, -3) + "y";
939
- if (/(ss|us|is)$/.test(norm)) return norm;
940
- if (/(xes|ches|shes|sses)$/.test(norm)) return norm.slice(0, -2);
941
- return norm.endsWith("s") ? norm.slice(0, -1) : norm;
942
- }
943
- function applyResolver(resolver, instance) {
944
- if (typeof resolver === "string") {
945
- const value = instance[resolver];
946
- if (value !== null && value !== void 0 && String(value).length > 0) {
947
- return String(value);
948
- }
949
- return null;
950
- }
951
- if (typeof resolver === "function") {
952
- try {
953
- const value = resolver(instance);
954
- if (typeof value === "string" && value.length > 0) return value;
955
- if (value !== null && value !== void 0 && String(value).length > 0) {
956
- return String(value);
957
- }
958
- } catch {
959
- }
960
- }
961
- return null;
962
- }
963
- function describeError(error) {
964
- if (error instanceof Error) return `${error.name}: ${error.message}`;
965
- return String(error);
966
- }
967
-
968
- // src/triggers/emit-dedup.ts
969
- var storage3 = createScopedStorage(
970
- /* @__PURE__ */ Symbol.for("ezlogs-nextjs:audit-emitted-ids-storage")
971
- );
972
- function currentEmittedAuditIds() {
973
- return storage3.read();
974
- }
975
-
976
- // src/triggers/reader.ts
977
- var COLUMNS = "id, table_name, op, old_row, new_row, resource_id, correlation_id, txid, captured_at";
978
- var ORPHAN_AGE = "5 minutes";
979
- var PRUNE_AGE = "24 hours";
980
- var SWEEP_BATCH = 100;
981
- var PRUNE_BATCH = 2e3;
982
- var SWEEP_INTERVAL_MS = 1e4;
983
- var PRUNE_INTERVAL_MS = 10 * 6e4;
984
- var lastSweepAt = 0;
985
- var lastPruneAt = 0;
986
- var deleteDenied = false;
987
- var txCorrelation = /* @__PURE__ */ new Map();
988
- async function readAuditRows(exec, correlationId, since = null) {
989
- const where = since ? "correlation_id = $1 AND captured_at >= $2" : "correlation_id = $1";
990
- const params = since ? [correlationId, since.toISOString()] : [correlationId];
991
- try {
992
- if (!deleteDenied) {
993
- try {
994
- return sortById(
995
- extractRows(
996
- await exec(
997
- `DELETE FROM ezlogs_audit_log WHERE ${where} RETURNING ${COLUMNS}`,
998
- params
999
- )
1000
- ).map(normalizeAuditRow)
1001
- );
1002
- } catch (err) {
1003
- if (!isPermissionDenied(err)) throw err;
1004
- deleteDenied = true;
1005
- logger.warn(
1006
- "the database role used by the agent cannot DELETE from ezlogs_audit_log. Rows will not be cleaned up after they are sent; grant DELETE or schedule `DELETE FROM ezlogs_audit_log WHERE captured_at < now() - interval '24 hours'`."
1007
- );
1008
- }
1009
- }
1010
- const result = await exec(
1011
- `SELECT ${COLUMNS} FROM ezlogs_audit_log WHERE ${where} ORDER BY id ASC`,
1012
- params
1013
- );
1014
- return extractRows(result).map(normalizeAuditRow);
1015
- } catch (err) {
1016
- logger.debug(
1017
- `readAuditRows failed: ${err instanceof Error ? err.message : String(err)}`
1018
- );
1019
- return [];
1020
- }
1021
- }
1022
- async function sweepAuditLog(exec) {
1023
- if (deleteDenied) return 0;
1024
- try {
1025
- const rows = sortById(
1026
- extractRows(
1027
- await exec(
1028
- `DELETE FROM ezlogs_audit_log
1029
- WHERE id IN (
1030
- SELECT id FROM ezlogs_audit_log
1031
- WHERE (correlation_id IS NULL
1032
- OR captured_at < now() - interval '${ORPHAN_AGE}')
1033
- -- Never resurface history: past the retention cap a
1034
- -- row is pruned, not sent as new activity.
1035
- AND captured_at > now() - interval '${PRUNE_AGE}'
1036
- ORDER BY id
1037
- LIMIT ${SWEEP_BATCH}
1038
- FOR UPDATE SKIP LOCKED)
1039
- RETURNING ${COLUMNS}`,
1040
- []
1041
- )
1042
- ).map(normalizeAuditRow)
1043
- );
1044
- await loadTableMeta(exec, rows);
1045
- for (const row of rows) {
1046
- const correlationId = row.correlation_id ?? correlationForTx(row.txid);
1047
- runWithCorrelation(
1048
- correlationId,
1049
- () => runWithActorScope(() => emitOne(row))
1050
- );
1051
- }
1052
- return rows.length;
1053
- } catch (err) {
1054
- logger.debug(
1055
- `sweepAuditLog failed: ${err instanceof Error ? err.message : String(err)}`
1056
- );
1057
- return 0;
1058
- }
1059
- }
1060
- async function pruneAuditLog(exec) {
1061
- if (deleteDenied) return;
1062
- try {
1063
- await exec(
1064
- `DELETE FROM ezlogs_audit_log
1065
- WHERE id IN (
1066
- SELECT id FROM ezlogs_audit_log
1067
- WHERE captured_at < now() - interval '${PRUNE_AGE}'
1068
- LIMIT ${PRUNE_BATCH})`,
1069
- []
1070
- );
1071
- } catch (err) {
1072
- logger.debug(
1073
- `pruneAuditLog failed: ${err instanceof Error ? err.message : String(err)}`
1074
- );
1075
- }
1076
- }
1077
- function emitAuditRows(rows) {
1078
- for (const row of rows) {
1079
- emitOne(row);
1080
- }
1081
- }
1082
- async function flushAuditLog(exec, options = {}) {
1083
- if (!exec) return;
1084
- const correlationId = current();
1085
- if (!correlationId) return;
1086
- const rows = await readAuditRows(exec, correlationId, options.since ?? null);
1087
- await loadTableMeta(exec, rows);
1088
- emitFresh(rows);
1089
- const now = Date.now();
1090
- if (now - lastPruneAt >= PRUNE_INTERVAL_MS) {
1091
- lastPruneAt = now;
1092
- await pruneAuditLog(exec);
1093
- }
1094
- if (now - lastSweepAt >= SWEEP_INTERVAL_MS) {
1095
- lastSweepAt = now;
1096
- await sweepAuditLog(exec);
1097
- }
1098
- }
1099
- var tableMeta = /* @__PURE__ */ new Map();
1100
- var META_RETRY_MS = 6e4;
1101
- var metaRetryAt = 0;
1102
- async function loadTableMeta(exec, rows) {
1103
- if (Date.now() < metaRetryAt) return;
1104
- const tables = [
1105
- ...new Set(rows.map((r) => r.table_name).filter((t) => t !== "" && !t.includes(",") && !tableMeta.has(t)))
1106
- ];
1107
- if (tables.length === 0) return;
1108
- const list = tables.join(",");
1109
- try {
1110
- const fkRows = extractRows(
1111
- await exec(
1112
- `SELECT cl.relname AS table_name, a.attname AS column_name, rf.relname AS ref_table
1113
- FROM pg_constraint c
1114
- JOIN pg_class cl ON cl.oid = c.conrelid
1115
- JOIN pg_namespace n ON n.oid = cl.relnamespace
1116
- JOIN pg_class rf ON rf.oid = c.confrelid
1117
- JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = c.conkey[1]
1118
- WHERE c.contype = 'f'
1119
- AND n.nspname = 'public'
1120
- AND array_length(c.conkey, 1) = 1
1121
- AND cl.relname = ANY(string_to_array($1, ','))
1122
- ORDER BY cl.relname, a.attnum`,
1123
- [list]
1124
- )
1125
- );
1126
- const tsRows = extractRows(
1127
- await exec(
1128
- `SELECT cl.relname AS table_name, a.attname AS column_name
1129
- FROM pg_attribute a
1130
- JOIN pg_class cl ON cl.oid = a.attrelid
1131
- JOIN pg_namespace n ON n.oid = cl.relnamespace
1132
- WHERE n.nspname = 'public'
1133
- AND cl.relname = ANY(string_to_array($1, ','))
1134
- AND a.attnum > 0
1135
- AND NOT a.attisdropped
1136
- AND a.atttypid = 'timestamp'::regtype`,
1137
- [list]
1138
- )
1139
- );
1140
- const fks = /* @__PURE__ */ new Map();
1141
- for (const raw of fkRows) {
1142
- const r = raw ?? {};
1143
- if (typeof r.table_name !== "string" || typeof r.column_name !== "string" || typeof r.ref_table !== "string") {
1144
- continue;
1145
- }
1146
- fks.set(r.table_name, [...fks.get(r.table_name) ?? [], { column: r.column_name, refTable: r.ref_table }]);
1147
- }
1148
- const timestamps = /* @__PURE__ */ new Map();
1149
- for (const raw of tsRows) {
1150
- const r = raw ?? {};
1151
- if (typeof r.table_name !== "string" || typeof r.column_name !== "string") continue;
1152
- timestamps.set(r.table_name, (timestamps.get(r.table_name) ?? /* @__PURE__ */ new Set()).add(r.column_name));
1153
- }
1154
- for (const table of tables) {
1155
- tableMeta.set(table, { fks: fks.get(table) ?? [], naiveTimestamps: timestamps.get(table) ?? /* @__PURE__ */ new Set() });
1156
- }
1157
- } catch (err) {
1158
- metaRetryAt = Date.now() + META_RETRY_MS;
1159
- logger.debug(`table metadata lookup failed: ${err instanceof Error ? err.message : String(err)}`);
1160
- }
1161
- }
1162
- function relatedResourceIds(table, row) {
1163
- const out = [];
1164
- for (const fk of tableMeta.get(table)?.fks ?? []) {
1165
- const value = row[fk.column];
1166
- if (typeof value === "string" || typeof value === "number") {
1167
- out.push({ resource_type: fk.refTable, resource_id: String(value) });
1168
- }
1169
- }
1170
- return out;
1171
- }
1172
- function emitFresh(rows) {
1173
- if (rows.length === 0) return;
1174
- const emitted = currentEmittedAuditIds();
1175
- if (emitted === null) {
1176
- emitAuditRows(rows);
1177
- return;
1178
- }
1179
- const fresh = [];
1180
- for (const row of rows) {
1181
- if (row.id === "" || emitted.has(row.id)) continue;
1182
- emitted.add(row.id);
1183
- fresh.push(row);
1184
- }
1185
- emitAuditRows(fresh);
1186
- }
1187
- function correlationForTx(txid) {
1188
- if (!txid) return generate();
1189
- let id = txCorrelation.get(txid);
1190
- if (!id) {
1191
- if (txCorrelation.size >= 1e3) txCorrelation.clear();
1192
- id = generate();
1193
- txCorrelation.set(txid, id);
1194
- }
1195
- return id;
1196
- }
1197
- function isPermissionDenied(err) {
1198
- return err?.code === "42501";
1199
- }
1200
- function sortById(rows) {
1201
- return rows.sort(
1202
- (a, b) => a.id.length !== b.id.length ? a.id.length - b.id.length : a.id < b.id ? -1 : a.id > b.id ? 1 : 0
1203
- );
1204
- }
1205
- function emitOne(row) {
1206
- const op = mapOp(row.op);
1207
- if (!op) return;
1208
- const naive = tableMeta.get(row.table_name)?.naiveTimestamps ?? null;
1209
- const oldRow = withUtcTimestamps(coerceJsonb(row.old_row), naive);
1210
- const newRow = withUtcTimestamps(coerceJsonb(row.new_row), naive);
1211
- const related = row.resource_id === null ? relatedResourceIds(row.table_name, newRow ?? oldRow ?? {}) : null;
1212
- if (op === "create" && newRow) {
1213
- emitDbEvent({
1214
- modelClass: row.table_name,
1215
- operation: "create",
1216
- resourceId: row.resource_id,
1217
- initialAttributes: newRow,
1218
- modelInstance: newRow,
1219
- displayName: null,
1220
- timestamp: row.captured_at ?? null,
1221
- relatedResourceIds: related,
1222
- _fromTrigger: true
1223
- });
1224
- return;
1225
- }
1226
- if (op === "update" && oldRow && newRow) {
1227
- const changes = computeChanges(oldRow, newRow);
1228
- if (changes.length === 0) {
1229
- return;
1230
- }
1231
- emitDbEvent({
1232
- modelClass: row.table_name,
1233
- operation: "update",
1234
- resourceId: row.resource_id,
1235
- changes,
1236
- // Prefer the post-state for the display name — that's what the
1237
- // user just told the system to call this row.
1238
- modelInstance: newRow,
1239
- displayName: null,
1240
- timestamp: row.captured_at ?? null,
1241
- relatedResourceIds: related,
1242
- _fromTrigger: true
1243
- });
1244
- return;
1245
- }
1246
- if (op === "destroy" && oldRow) {
1247
- emitDbEvent({
1248
- modelClass: row.table_name,
1249
- operation: "destroy",
1250
- resourceId: row.resource_id,
1251
- initialAttributes: oldRow,
1252
- modelInstance: oldRow,
1253
- displayName: null,
1254
- timestamp: row.captured_at ?? null,
1255
- relatedResourceIds: related,
1256
- _fromTrigger: true
1257
- });
1258
- return;
1259
- }
1260
- }
1261
- var NAIVE_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?$/;
1262
- function withUtcTimestamps(row, naiveColumns) {
1263
- if (!row) return row;
1264
- const out = {};
1265
- for (const [key, value] of Object.entries(row)) {
1266
- const isNaiveColumn = naiveColumns ? naiveColumns.has(key) : /(_at|At)$/.test(key);
1267
- out[key] = isNaiveColumn && typeof value === "string" && NAIVE_TIMESTAMP.test(value) ? `${value}Z` : value;
1268
- }
1269
- return out;
1270
- }
1271
- function mapOp(op) {
1272
- if (op === "INSERT") return "create";
1273
- if (op === "UPDATE") return "update";
1274
- if (op === "DELETE") return "destroy";
1275
- return null;
1276
- }
1277
- function computeChanges(oldRow, newRow) {
1278
- const out = [];
1279
- for (const key of Object.keys(newRow)) {
1280
- const before = oldRow[key];
1281
- const after = newRow[key];
1282
- if (deepEqual(before, after)) continue;
1283
- out.push({ attribute: key, from: before, to: after });
1284
- }
1285
- return out;
1286
- }
1287
- function deepEqual(a, b) {
1288
- if (a === b) return true;
1289
- if (a === null || b === null) return false;
1290
- if (typeof a !== typeof b) return false;
1291
- if (typeof a !== "object") return false;
1292
- try {
1293
- return stableStringify(a) === stableStringify(b);
1294
- } catch {
1295
- return false;
1296
- }
1297
- }
1298
- function stableStringify(value) {
1299
- if (value === null || typeof value !== "object") return JSON.stringify(value);
1300
- if (Array.isArray(value)) {
1301
- return "[" + value.map((v) => stableStringify(v)).join(",") + "]";
1302
- }
1303
- const entries = Object.keys(value).sort().map((k) => JSON.stringify(k) + ":" + stableStringify(value[k]));
1304
- return "{" + entries.join(",") + "}";
1305
- }
1306
- function extractRows(result) {
1307
- if (!result) return [];
1308
- if (Array.isArray(result)) return result;
1309
- if (typeof result === "object" && Array.isArray(result.rows)) {
1310
- return result.rows;
1311
- }
1312
- return [];
1313
- }
1314
- function toDate(value) {
1315
- if (value == null) return null;
1316
- const d = value instanceof Date ? value : new Date(String(value));
1317
- return Number.isNaN(d.getTime()) ? null : d;
1318
- }
1319
- function normalizeAuditRow(raw) {
1320
- const r = raw ?? {};
1321
- return {
1322
- id: r.id == null ? "" : String(r.id),
1323
- table_name: String(r.table_name ?? ""),
1324
- op: r.op,
1325
- old_row: r.old_row ?? null,
1326
- new_row: r.new_row ?? null,
1327
- resource_id: r.resource_id == null ? null : String(r.resource_id),
1328
- correlation_id: r.correlation_id == null ? null : String(r.correlation_id),
1329
- txid: r.txid == null ? null : String(r.txid),
1330
- captured_at: toDate(r.captured_at)
1331
- };
1332
- }
1333
- function coerceJsonb(value) {
1334
- if (value === null || value === void 0) return null;
1335
- if (typeof value === "string") {
1336
- try {
1337
- const parsed = JSON.parse(value);
1338
- return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
1339
- } catch {
1340
- return null;
1341
- }
1342
- }
1343
- if (typeof value === "object" && !Array.isArray(value)) return value;
1344
- return null;
1345
- }
1346
-
1347
- // src/jobs/shared.ts
1348
- var CORRELATION_PAYLOAD_KEY = "ezlogs_correlation_id";
1349
- function emitJobEvent(input) {
1350
- try {
1351
- const config = configuration();
1352
- if (!config.captureJobs) return;
1353
- if (config.allExcludedJobClasses().includes(input.jobClass)) return;
1354
- const sourceData = compactJobSourceData({
1355
- job_class: input.jobClass,
1356
- job_id: input.jobId ?? null,
1357
- queue: input.queue ?? null,
1358
- retry_count: input.retryCount ?? null,
1359
- arguments: jobArguments(input.payload)
1360
- });
1361
- const event = build({
1362
- source_type: "background_job",
1363
- source_data: sourceData,
1364
- outcome: input.outcome,
1365
- correlation_id: input.correlationId ?? current(),
1366
- resource_ids: [],
1367
- context: null,
1368
- duration_ms: input.durationMs ?? null,
1369
- error_message: input.errorMessage ?? null,
1370
- timestamp: input.startedAt
1371
- });
1372
- pushEvent(event);
1373
- } catch (error) {
1374
- logger.debug(`job emit failed: ${describeError2(error)}`);
1375
- }
1376
- }
1377
- async function runJobWithCapture(meta, work) {
1378
- const correlationId = meta.correlationId ?? generate();
1379
- return runWithCorrelation(correlationId, async () => {
1380
- const startedAt = /* @__PURE__ */ new Date();
1381
- const startMs = startedAt.getTime();
1382
- const baseMeta = {
1383
- jobClass: meta.jobClass,
1384
- jobId: meta.jobId ?? null,
1385
- queue: meta.queue ?? null,
1386
- retryCount: meta.retryCount ?? null,
1387
- correlationId,
1388
- startedAt,
1389
- payload: meta.payload
1390
- };
1391
- try {
1392
- const result = await work();
1393
- await flushJobAuditLog(startedAt);
1394
- emitJobEvent({
1395
- ...baseMeta,
1396
- outcome: "success",
1397
- durationMs: Date.now() - startMs
1398
- });
1399
- return result;
1400
- } catch (error) {
1401
- const message = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
1402
- await flushJobAuditLog(startedAt);
1403
- if (meta.isControlFlow?.(error)) throw error;
1404
- emitJobEvent({
1405
- ...baseMeta,
1406
- outcome: "failure",
1407
- errorMessage: message,
1408
- durationMs: Date.now() - startMs
1409
- });
1410
- throw error;
1411
- }
1412
- });
1413
- }
1414
- var JOB_FLUSH_SKEW_MS = 500;
1415
- async function flushJobAuditLog(startedAt) {
1416
- try {
1417
- await flushAuditLog(configuration().databaseReader, {
1418
- since: new Date(startedAt.getTime() - JOB_FLUSH_SKEW_MS)
1419
- });
1420
- } catch (error) {
1421
- logger.debug(`job audit flush failed: ${describeError2(error)}`);
1422
- }
1423
- }
1424
- function jobArguments(payload) {
1425
- if (payload === null || payload === void 0) return null;
1426
- const patterns = configuration().excludedGraphqlVariableKeys;
1427
- if (Array.isArray(payload)) return payload.length === 0 ? null : sanitizeArgs(payload, patterns);
1428
- if (typeof payload === "object" && Object.getPrototypeOf(payload) === Object.prototype) {
1429
- const rest = { ...payload };
1430
- delete rest[CORRELATION_PAYLOAD_KEY];
1431
- if (Object.keys(rest).length === 0) return null;
1432
- return sanitizeArgs([rest], patterns)[0];
1433
- }
1434
- return sanitizeArgs([payload], patterns);
1435
- }
1436
- function compactJobSourceData(data) {
1437
- const out = {};
1438
- for (const key of Object.keys(data)) {
1439
- const value = data[key];
1440
- if (value !== null && value !== void 0) out[key] = value;
1441
- }
1442
- return out;
1443
- }
1444
- function describeError2(error) {
1445
- if (error instanceof Error) return `${error.name}: ${error.message}`;
1446
- return String(error);
1447
- }
3
+ var chunkUWHYJH4M_cjs = require('../chunk-UWHYJH4M.cjs');
4
+ require('../chunk-YX2XPLOA.cjs');
5
+ var chunkWASXTDLW_cjs = require('../chunk-WASXTDLW.cjs');
6
+ var chunkV5YNKKTG_cjs = require('../chunk-V5YNKKTG.cjs');
7
+ require('../chunk-ZDSQYCYV.cjs');
1448
8
 
1449
9
  // src/jobs/upstash-workflow.ts
1450
10
  var FORWARD_PREFIX = "upstash-forward-";
1451
11
  var CORRELATION_HEADER = "x-ezlogs-correlation-id";
1452
12
  var LEGACY_CORRELATION_HEADER = "x-correlation-id";
1453
13
  var AGENT_CORRELATION_ID = /^ezl_(\d{13})_[0-9a-f]{8}$/;
14
+ var AGENT_RUN_ID = /^wfr_(ezl_\d{13}_[0-9a-f]{8})_[0-9a-f]{24}$/;
15
+ var RUN_ID_SUFFIX_BYTES = 12;
1454
16
  var STEP_ID_MAX_AGE_MS = 24 * 60 * 6e4;
1455
17
  function isAcceptableStepId(value) {
1456
18
  const match = AGENT_CORRELATION_ID.exec(value);
@@ -1474,13 +36,18 @@ function wrapWorkflowClient(client) {
1474
36
  return client;
1475
37
  }
1476
38
  function stampTriggerOptions(options) {
1477
- const id = current();
1478
- if (!id || !options || typeof options !== "object") return options;
39
+ const current2 = chunkWASXTDLW_cjs.current();
40
+ if (!current2 || !options || typeof options !== "object") return options;
1479
41
  const opts = options;
1480
42
  const headers = { ...opts.headers ?? {} };
1481
- if (Object.keys(headers).some((k) => k.toLowerCase() === CORRELATION_HEADER)) return options;
1482
- headers[CORRELATION_HEADER] = id;
1483
- return { ...opts, headers };
43
+ const supplied = Object.keys(headers).find((k) => k.toLowerCase() === CORRELATION_HEADER);
44
+ const id = supplied ? headers[supplied] : current2;
45
+ if (!supplied) headers[CORRELATION_HEADER] = id;
46
+ const stamped = { ...opts, headers };
47
+ if (opts.workflowRunId == null && AGENT_CORRELATION_ID.test(id)) {
48
+ stamped.workflowRunId = `${id}_${randomHex(RUN_ID_SUFFIX_BYTES)}`;
49
+ }
50
+ return stamped;
1484
51
  }
1485
52
  function wrapQStashClient(client) {
1486
53
  if (client[WRAPPED_FLAG]) return client;
@@ -1502,7 +69,7 @@ function wrapQStashClient(client) {
1502
69
  return client;
1503
70
  }
1504
71
  function stampPublishRequest(request) {
1505
- const id = current();
72
+ const id = chunkWASXTDLW_cjs.current();
1506
73
  if (!id) return request;
1507
74
  const headerKey = `${FORWARD_PREFIX}${CORRELATION_HEADER}`;
1508
75
  const headers = { ...request.headers ?? {} };
@@ -1522,7 +89,7 @@ async function captureWorkflowRequest(meta, work) {
1522
89
  const correlationId = readCorrelationFromHeaders(headers);
1523
90
  const runId = readHeader(headers, "upstash-workflow-runid");
1524
91
  const retried = parseRetried(readHeader(headers, "upstash-retried"));
1525
- return runJobWithCapture(
92
+ return chunkUWHYJH4M_cjs.runJobWithCapture(
1526
93
  {
1527
94
  jobClass: meta.workflowName,
1528
95
  jobId: runId,
@@ -1536,7 +103,7 @@ async function captureWorkflowRequest(meta, work) {
1536
103
  function emitUpstashWorkflowEvent(input) {
1537
104
  try {
1538
105
  const headers = input.request.headers;
1539
- emitJobEvent({
106
+ chunkUWHYJH4M_cjs.emitJobEvent({
1540
107
  jobClass: input.workflowName,
1541
108
  jobId: readHeader(headers, "upstash-workflow-runid"),
1542
109
  queue: input.workflowName,
@@ -1548,9 +115,14 @@ function emitUpstashWorkflowEvent(input) {
1548
115
  startedAt: input.startedAt ?? /* @__PURE__ */ new Date()
1549
116
  });
1550
117
  } catch (error) {
1551
- logger.debug(`upstash workflow capture failed: ${describeError3(error)}`);
118
+ chunkV5YNKKTG_cjs.logger.debug(`upstash workflow capture failed: ${describeError(error)}`);
1552
119
  }
1553
120
  }
121
+ function randomHex(bytes) {
122
+ const buf = new Uint8Array(bytes);
123
+ globalThis.crypto.getRandomValues(buf);
124
+ return Array.from(buf, (b) => b.toString(16).padStart(2, "0")).join("");
125
+ }
1554
126
  function readHeader(headers, name) {
1555
127
  try {
1556
128
  const value = headers.get(name);
@@ -1564,7 +136,9 @@ function readCorrelationFromHeaders(headers) {
1564
136
  const value = readHeader(headers, name) ?? readHeader(headers, `${FORWARD_PREFIX}${name}`);
1565
137
  if (value && isAcceptableStepId(value)) return value;
1566
138
  }
1567
- return null;
139
+ const runId = readHeader(headers, "upstash-workflow-runid");
140
+ const fromRunId = runId ? AGENT_RUN_ID.exec(runId)?.[1] : void 0;
141
+ return fromRunId && isAcceptableStepId(fromRunId) ? fromRunId : null;
1568
142
  }
1569
143
  function parseRetried(value) {
1570
144
  if (value === null) return null;
@@ -1572,7 +146,7 @@ function parseRetried(value) {
1572
146
  if (!Number.isFinite(parsed) || parsed < 0) return null;
1573
147
  return parsed;
1574
148
  }
1575
- function describeError3(error) {
149
+ function describeError(error) {
1576
150
  if (error instanceof Error) return `${error.name}: ${error.message}`;
1577
151
  return String(error);
1578
152
  }