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
@@ -0,0 +1,1151 @@
1
+ 'use strict';
2
+
3
+ var chunkV5YNKKTG_cjs = require('./chunk-V5YNKKTG.cjs');
4
+ var chunkZDSQYCYV_cjs = require('./chunk-ZDSQYCYV.cjs');
5
+
6
+ // src/configuration.ts
7
+ var DEFAULT_EXCLUDED_PATHS = Object.freeze([
8
+ // Next.js / Vercel infrastructure noise
9
+ "/_next/*",
10
+ "/_vercel/*",
11
+ "/__nextjs_*",
12
+ // NextAuth.js / Auth.js — skip session-refresh polls and CSRF/provider
13
+ // metadata GETs (high-frequency, no business meaning), but CAPTURE
14
+ // POSTs (callbacks, signin, signout, register). The POSTs are the
15
+ // actual auth events users care about; the GETs are pure plumbing.
16
+ Object.freeze({ path: "/api/auth/*", methods: ["GET", "HEAD"] }),
17
+ // Generic infrastructure
18
+ "/health*",
19
+ "/api/health",
20
+ "/up",
21
+ "/alive",
22
+ "/ready",
23
+ "/metrics",
24
+ "/favicon.ico",
25
+ "/.well-known*",
26
+ "/robots.txt",
27
+ "/sitemap.xml",
28
+ "/*.hot-update.*",
29
+ // Auth routes (common patterns across Clerk, NextAuth, custom auth)
30
+ "*/login*",
31
+ "*/logout*",
32
+ "*/sign-in*",
33
+ "*/sign-out*",
34
+ "*/signin*",
35
+ "*/signout*",
36
+ "/session*"
37
+ ]);
38
+ var DEFAULT_EXCLUDED_EXTENSIONS = Object.freeze([
39
+ ".js",
40
+ ".css",
41
+ ".map",
42
+ ".png",
43
+ ".jpg",
44
+ ".jpeg",
45
+ ".gif",
46
+ ".svg",
47
+ ".ico",
48
+ ".webp",
49
+ ".woff",
50
+ ".woff2",
51
+ ".ttf",
52
+ ".eot",
53
+ ".otf"
54
+ ]);
55
+ var DEFAULT_EXCLUDED_TABLES = Object.freeze([
56
+ // Prisma migration ledger
57
+ "_prisma_migrations",
58
+ // Auth.js / NextAuth Prisma adapter — session/verification-token churn
59
+ // is auth machinery, not business activity. Account/User stay captured.
60
+ "Session",
61
+ "VerificationToken",
62
+ // Common cross-stack convention names for the same things
63
+ "sessions",
64
+ "session",
65
+ "verification_tokens"
66
+ ]);
67
+ var DEFAULT_EXCLUDED_JOB_CLASSES = Object.freeze([]);
68
+ var DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS = Object.freeze(["IntrospectionQuery", "__*"]);
69
+ var Configuration = class {
70
+ serverUrl = null;
71
+ projectToken = null;
72
+ captureHttp = true;
73
+ captureDb = true;
74
+ captureJobs = true;
75
+ bufferSize = 1e4;
76
+ /** Default 3000 ms — equivalent to Ruby's 3 seconds. */
77
+ sendInterval = 3e3;
78
+ retryAttempts = 3;
79
+ logLevel = "warn";
80
+ patchGlobalFetch = true;
81
+ actorFromSupabase = true;
82
+ allowInsecureTransport = false;
83
+ excludedPaths = [];
84
+ excludedTables = [];
85
+ excludedJobClasses = [];
86
+ excludedGraphqlOperations = [];
87
+ excludedGraphqlVariableKeys = [];
88
+ actorFromRequest = null;
89
+ displayNameFor = {};
90
+ isServerActionError = null;
91
+ databaseReader = null;
92
+ databaseUrl = null;
93
+ /**
94
+ * Tables that have the `ezlogs_audit` trigger attached. Detected once
95
+ * at agent startup by reading `information_schema.triggers`. The
96
+ * supabase / drizzle / prisma adapters use this to decide whether
97
+ * their per-mutation emit is redundant: if the table is trigger-
98
+ * tracked the audit-log reader will surface the same write with full
99
+ * old/new state, so the adapter's emit is suppressed. Tables NOT in
100
+ * this set fall through to the adapter so they're still captured.
101
+ *
102
+ * `null` means "detection hasn't run yet or failed" — in that state
103
+ * `databaseReader`-wired apps suppress every adapter emit (the
104
+ * original Phase 5 behavior). After detection completes the agent
105
+ * gives the more accurate per-table answer.
106
+ */
107
+ triggerTrackedTables = null;
108
+ apply(options) {
109
+ this.serverUrl = options.serverUrl;
110
+ this.projectToken = options.projectToken;
111
+ if (options.captureHttp !== void 0) this.captureHttp = options.captureHttp;
112
+ if (options.captureDb !== void 0) this.captureDb = options.captureDb;
113
+ if (options.captureJobs !== void 0) this.captureJobs = options.captureJobs;
114
+ if (options.bufferSize !== void 0) this.bufferSize = options.bufferSize;
115
+ if (options.sendInterval !== void 0) this.sendInterval = options.sendInterval;
116
+ if (options.retryAttempts !== void 0) this.retryAttempts = options.retryAttempts;
117
+ if (options.excludedPaths) this.excludedPaths = [...options.excludedPaths];
118
+ if (options.excludedTables) this.excludedTables = [...options.excludedTables];
119
+ if (options.excludedJobClasses) {
120
+ this.excludedJobClasses = [...options.excludedJobClasses];
121
+ }
122
+ if (options.excludedGraphqlOperations) {
123
+ this.excludedGraphqlOperations = [...options.excludedGraphqlOperations];
124
+ }
125
+ if (options.excludedGraphqlVariableKeys) {
126
+ this.excludedGraphqlVariableKeys = [...options.excludedGraphqlVariableKeys];
127
+ }
128
+ if (options.actorFromRequest) this.actorFromRequest = options.actorFromRequest;
129
+ if (options.displayNameFor) this.displayNameFor = { ...options.displayNameFor };
130
+ if (options.isServerActionError) this.isServerActionError = options.isServerActionError;
131
+ if (options.patchGlobalFetch !== void 0) {
132
+ this.patchGlobalFetch = options.patchGlobalFetch;
133
+ }
134
+ if (options.allowInsecureTransport !== void 0) {
135
+ this.allowInsecureTransport = options.allowInsecureTransport;
136
+ }
137
+ if (options.actorFromSupabase !== void 0) {
138
+ this.actorFromSupabase = options.actorFromSupabase;
139
+ }
140
+ if (options.databaseReader !== void 0) {
141
+ this.databaseReader = options.databaseReader;
142
+ }
143
+ if (options.databaseUrl !== void 0) {
144
+ this.databaseUrl = options.databaseUrl;
145
+ }
146
+ if (options.logLevel) this.logLevel = options.logLevel;
147
+ }
148
+ allExcludedPaths() {
149
+ return [...DEFAULT_EXCLUDED_PATHS, ...this.excludedPaths];
150
+ }
151
+ allExcludedTables() {
152
+ return [...DEFAULT_EXCLUDED_TABLES, ...this.excludedTables];
153
+ }
154
+ allExcludedJobClasses() {
155
+ return [...DEFAULT_EXCLUDED_JOB_CLASSES, ...this.excludedJobClasses];
156
+ }
157
+ allExcludedGraphqlOperations() {
158
+ return [...DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS, ...this.excludedGraphqlOperations];
159
+ }
160
+ };
161
+ var GLOBAL_CONFIG_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:configuration");
162
+ function configuration() {
163
+ const g = globalThis;
164
+ if (!g[GLOBAL_CONFIG_KEY]) {
165
+ g[GLOBAL_CONFIG_KEY] = new Configuration();
166
+ }
167
+ return g[GLOBAL_CONFIG_KEY];
168
+ }
169
+
170
+ // src/pipeline/buffer.ts
171
+ var buffer_exports = {};
172
+ chunkZDSQYCYV_cjs.__export(buffer_exports, {
173
+ bufferSize: () => bufferSize,
174
+ clearBuffer: () => clearBuffer,
175
+ drainEvents: () => drainEvents,
176
+ pushEvent: () => pushEvent
177
+ });
178
+ var GLOBAL_QUEUE_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:buffer-queue");
179
+ function getQueue() {
180
+ const g = globalThis;
181
+ if (!g[GLOBAL_QUEUE_KEY]) g[GLOBAL_QUEUE_KEY] = [];
182
+ return g[GLOBAL_QUEUE_KEY];
183
+ }
184
+ function pushEvent(event) {
185
+ try {
186
+ const queue = getQueue();
187
+ const max = maxSize();
188
+ if (queue.length >= max) {
189
+ queue.shift();
190
+ chunkV5YNKKTG_cjs.logger.warn(`Buffer full (${max}), dropped oldest event`);
191
+ }
192
+ queue.push(event);
193
+ } catch (error) {
194
+ chunkV5YNKKTG_cjs.logger.error(`pushEvent failed: ${describe(error)}`);
195
+ }
196
+ }
197
+ function drainEvents() {
198
+ try {
199
+ const queue = getQueue();
200
+ if (queue.length === 0) return [];
201
+ return queue.splice(0, queue.length);
202
+ } catch (error) {
203
+ chunkV5YNKKTG_cjs.logger.error(`drainEvents failed: ${describe(error)}`);
204
+ return [];
205
+ }
206
+ }
207
+ function bufferSize() {
208
+ return getQueue().length;
209
+ }
210
+ function clearBuffer() {
211
+ const queue = getQueue();
212
+ queue.length = 0;
213
+ }
214
+ function maxSize() {
215
+ try {
216
+ return configuration().bufferSize;
217
+ } catch {
218
+ return 1e4;
219
+ }
220
+ }
221
+ function describe(error) {
222
+ if (error instanceof Error) return `${error.name}: ${error.message}`;
223
+ return String(error);
224
+ }
225
+
226
+ // src/edge-fallback.ts
227
+ var ALS_CTOR = loadAsyncLocalStorage();
228
+ function loadAsyncLocalStorage() {
229
+ const fromGlobal = globalThis.AsyncLocalStorage;
230
+ if (typeof fromGlobal === "function") return fromGlobal;
231
+ try {
232
+ const req = typeof chunkZDSQYCYV_cjs.__require !== "undefined" ? chunkZDSQYCYV_cjs.__require : (
233
+ // In ESM, `createRequire` is the official escape hatch.
234
+ // We pull it via globalThis to avoid a static `import`
235
+ // that would itself be browser-bundled.
236
+ void 0
237
+ );
238
+ if (typeof req === "function") {
239
+ const moduleName = ["async", "hooks"].join("_");
240
+ const mod = req("node:" + moduleName);
241
+ if (typeof mod.AsyncLocalStorage === "function") return mod.AsyncLocalStorage;
242
+ }
243
+ } catch {
244
+ }
245
+ return null;
246
+ }
247
+ function makeAsyncContextCapture() {
248
+ if (!ALS_CTOR) return null;
249
+ const ctor = ALS_CTOR;
250
+ if (typeof ctor.snapshot !== "function") return null;
251
+ const snapshot = ctor.snapshot.bind(ctor);
252
+ return () => {
253
+ const runSnapshot = snapshot();
254
+ return (fn) => runSnapshot(fn);
255
+ };
256
+ }
257
+ function createScopedStorage(key = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:default-scoped-storage")) {
258
+ const globalStore = globalThis;
259
+ let entry = globalStore[key];
260
+ if (!entry) {
261
+ const als2 = (() => {
262
+ if (!ALS_CTOR) return null;
263
+ try {
264
+ return new ALS_CTOR();
265
+ } catch {
266
+ return null;
267
+ }
268
+ })();
269
+ entry = { als: als2, edgeFallback: null };
270
+ globalStore[key] = entry;
271
+ }
272
+ const als = entry.als;
273
+ const stateRef = entry;
274
+ return {
275
+ read() {
276
+ if (als) return als.getStore()?.value ?? null;
277
+ return stateRef.edgeFallback?.value ?? null;
278
+ },
279
+ run(value, callback) {
280
+ if (als) return als.run({ value }, callback);
281
+ const previous = stateRef.edgeFallback;
282
+ stateRef.edgeFallback = { value };
283
+ try {
284
+ return callback();
285
+ } finally {
286
+ stateRef.edgeFallback = previous;
287
+ }
288
+ },
289
+ update(value) {
290
+ if (als) {
291
+ const store = als.getStore();
292
+ if (store) store.value = value;
293
+ return;
294
+ }
295
+ stateRef.edgeFallback = { value };
296
+ },
297
+ _resetForTests() {
298
+ stateRef.edgeFallback = null;
299
+ },
300
+ _isAsyncLocalStorage() {
301
+ return als !== null;
302
+ }
303
+ };
304
+ }
305
+
306
+ // src/correlation.ts
307
+ var CORRELATION_HEADER = "x-ezlogs-correlation-id";
308
+ var PLATFORM_REQUEST_ID_HEADERS = [
309
+ "x-vercel-id",
310
+ "cf-ray",
311
+ "x-request-id"
312
+ ];
313
+ var storage = createScopedStorage(
314
+ /* @__PURE__ */ Symbol.for("ezlogs-nextjs:correlation-storage")
315
+ );
316
+ function generate() {
317
+ const ts = Date.now();
318
+ const hex = randomHexBytes(4);
319
+ return `ezl_${ts}_${hex}`;
320
+ }
321
+ function randomHexBytes(byteCount) {
322
+ const buf = new Uint8Array(byteCount);
323
+ globalThis.crypto.getRandomValues(buf);
324
+ let out = "";
325
+ for (let i = 0; i < buf.length; i++) {
326
+ out += buf[i].toString(16).padStart(2, "0");
327
+ }
328
+ return out;
329
+ }
330
+ function resolveCorrelation(headers) {
331
+ if (!headers) return generate();
332
+ const ezlogs = safeRead(headers, CORRELATION_HEADER);
333
+ if (ezlogs && isTrustedInboundId(ezlogs)) return ezlogs;
334
+ for (const name of PLATFORM_REQUEST_ID_HEADERS) {
335
+ const platformId = safeRead(headers, name);
336
+ if (platformId) return wrapPlatformId(platformId);
337
+ }
338
+ return generate();
339
+ }
340
+ var INBOUND_ID = /^ezl_(\d{13})_[0-9a-f]{8}$/;
341
+ var INBOUND_MAX_AGE_MS = 60 * 6e4;
342
+ function isTrustedInboundId(id) {
343
+ const match = INBOUND_ID.exec(id);
344
+ if (!match) return false;
345
+ const age = Date.now() - Number(match[1]);
346
+ return age <= INBOUND_MAX_AGE_MS && age >= -3e5;
347
+ }
348
+ function safeRead(headers, name) {
349
+ try {
350
+ const value = headers.get(name);
351
+ return typeof value === "string" && value.length > 0 ? value : null;
352
+ } catch {
353
+ return null;
354
+ }
355
+ }
356
+ function wrapPlatformId(platformId) {
357
+ const ts = Date.now();
358
+ const hex = fnv1aHex(platformId);
359
+ return `ezl_${ts}_${hex}`;
360
+ }
361
+ function fnv1aHex(input) {
362
+ let hash = 2166136261;
363
+ for (let i = 0; i < input.length; i++) {
364
+ hash ^= input.charCodeAt(i);
365
+ hash = Math.imul(hash, 16777619);
366
+ }
367
+ return (hash >>> 0).toString(16).padStart(8, "0");
368
+ }
369
+ function current() {
370
+ return storage.read();
371
+ }
372
+ function runWithCorrelation(correlationId, callback) {
373
+ return storage.run(correlationId, callback);
374
+ }
375
+
376
+ // src/event-builder.ts
377
+ var SENSITIVE_KEYS = Object.freeze([
378
+ "password",
379
+ "token",
380
+ "secret",
381
+ "api_key",
382
+ "credit_card"
383
+ ]);
384
+ var VALID_SOURCE_TYPES = [
385
+ "http_request",
386
+ "background_job",
387
+ "database_callback"
388
+ ];
389
+ var VALID_OUTCOMES = ["success", "failure"];
390
+ function build(input) {
391
+ const source_type = validateSourceType(input.source_type);
392
+ const source_data_raw = validateSourceData(input.source_data);
393
+ const outcome = validateOutcome(input.outcome);
394
+ const timestamp = validateTimestamp(input.timestamp ?? null);
395
+ const resource_ids = validateResourceIds(input.resource_ids ?? []);
396
+ const context_raw = validateContext(input.context ?? null);
397
+ const duration_ms = validateDurationMs(input.duration_ms ?? null);
398
+ const error_message = input.error_message ?? null;
399
+ validateOutcomeErrorConsistency(outcome, error_message);
400
+ const source_data = sanitizeRecord(source_data_raw);
401
+ const context = context_raw === null ? null : sanitizeRecord(context_raw);
402
+ const correlation_id = input.correlation_id ?? null;
403
+ const event = {
404
+ timestamp,
405
+ source_type,
406
+ source_data,
407
+ outcome,
408
+ correlation_id,
409
+ resource_ids,
410
+ context,
411
+ duration_ms,
412
+ error_message
413
+ };
414
+ return event;
415
+ }
416
+ function validateSourceType(value) {
417
+ if (value === null || value === void 0) {
418
+ throw new ArgError("source_type is required");
419
+ }
420
+ const normalized = String(value);
421
+ if (!VALID_SOURCE_TYPES.includes(normalized)) {
422
+ throw new ArgError(
423
+ `source_type must be one of ${VALID_SOURCE_TYPES.join(", ")}, got: ${normalized}`
424
+ );
425
+ }
426
+ return normalized;
427
+ }
428
+ function validateSourceData(value) {
429
+ if (value === null || value === void 0) {
430
+ throw new ArgError("source_data is required");
431
+ }
432
+ if (!isPlainObject(value)) {
433
+ throw new ArgError(
434
+ `source_data must be an object, got: ${describe2(value)}`
435
+ );
436
+ }
437
+ return value;
438
+ }
439
+ function validateOutcome(value) {
440
+ if (value === null || value === void 0) {
441
+ throw new ArgError("outcome is required");
442
+ }
443
+ const normalized = String(value);
444
+ if (!VALID_OUTCOMES.includes(normalized)) {
445
+ throw new ArgError(
446
+ `outcome must be one of ${VALID_OUTCOMES.join(", ")}, got: ${normalized}`
447
+ );
448
+ }
449
+ return normalized;
450
+ }
451
+ function validateTimestamp(value) {
452
+ if (value === null) {
453
+ return (/* @__PURE__ */ new Date()).toISOString();
454
+ }
455
+ if (typeof value === "string") {
456
+ const parsed = new Date(value);
457
+ if (Number.isNaN(parsed.getTime())) {
458
+ throw new ArgError(
459
+ `timestamp must be valid ISO 8601 format, got: ${value}`
460
+ );
461
+ }
462
+ return value;
463
+ }
464
+ if (value instanceof Date) {
465
+ if (Number.isNaN(value.getTime())) {
466
+ throw new ArgError("timestamp must be a valid Date");
467
+ }
468
+ return value.toISOString();
469
+ }
470
+ throw new ArgError(
471
+ `timestamp must be a string or Date, got: ${describe2(value)}`
472
+ );
473
+ }
474
+ function validateResourceIds(value) {
475
+ if (!Array.isArray(value)) {
476
+ throw new ArgError(`resource_ids must be an array, got: ${describe2(value)}`);
477
+ }
478
+ value.forEach((entry, index) => {
479
+ if (!isPlainObject(entry)) {
480
+ throw new ArgError(
481
+ `resource_ids[${index}] must be an object, got: ${describe2(entry)}`
482
+ );
483
+ }
484
+ const e = entry;
485
+ if (!("resource_type" in e) || !("resource_id" in e)) {
486
+ throw new ArgError(
487
+ `resource_ids[${index}] must have resource_type and resource_id keys, got: ${Object.keys(e).join(", ")}`
488
+ );
489
+ }
490
+ if (typeof e.resource_type !== "string") {
491
+ throw new ArgError(
492
+ `resource_ids[${index}].resource_type must be a string, got: ${describe2(e.resource_type)}`
493
+ );
494
+ }
495
+ if (typeof e.resource_id !== "string") {
496
+ throw new ArgError(
497
+ `resource_ids[${index}].resource_id must be a string, got: ${describe2(e.resource_id)}`
498
+ );
499
+ }
500
+ });
501
+ return value;
502
+ }
503
+ function validateContext(value) {
504
+ if (value === null) return null;
505
+ if (!isPlainObject(value)) {
506
+ throw new ArgError(
507
+ `context must be an object or null, got: ${describe2(value)}`
508
+ );
509
+ }
510
+ return value;
511
+ }
512
+ function validateDurationMs(value) {
513
+ if (value === null || value === void 0) return null;
514
+ if (typeof value !== "number" || !Number.isFinite(value)) {
515
+ throw new ArgError(`duration_ms must be a number, got: ${describe2(value)}`);
516
+ }
517
+ if (!Number.isInteger(value)) {
518
+ throw new ArgError(`duration_ms must be an integer, got: ${value}`);
519
+ }
520
+ if (value < 0) {
521
+ throw new ArgError(`duration_ms must be >= 0, got: ${value}`);
522
+ }
523
+ return value;
524
+ }
525
+ function validateOutcomeErrorConsistency(outcome, error_message) {
526
+ if (outcome === "failure") {
527
+ if (error_message === null || error_message === "") {
528
+ throw new ArgError("error_message is required when outcome is 'failure'");
529
+ }
530
+ } else if (outcome === "success") {
531
+ if (error_message !== null) {
532
+ throw new ArgError("error_message must be null when outcome is 'success'");
533
+ }
534
+ }
535
+ }
536
+ function sanitizeRecord(input) {
537
+ const result = {};
538
+ for (const key of Object.keys(input)) {
539
+ const value = input[key];
540
+ if (isSensitiveKey(key)) {
541
+ result[key] = "[FILTERED]";
542
+ } else if (isPlainObject(value)) {
543
+ result[key] = sanitizeRecord(value);
544
+ } else if (Array.isArray(value)) {
545
+ result[key] = value.map(
546
+ (item) => isPlainObject(item) ? sanitizeRecord(item) : item
547
+ );
548
+ } else {
549
+ result[key] = value;
550
+ }
551
+ }
552
+ return result;
553
+ }
554
+ function isSensitiveKey(key) {
555
+ const lower = key.toLowerCase();
556
+ return SENSITIVE_KEYS.some((p) => lower.includes(p));
557
+ }
558
+ function isPlainObject(value) {
559
+ if (value === null || typeof value !== "object") return false;
560
+ const proto = Object.getPrototypeOf(value);
561
+ return proto === Object.prototype || proto === null;
562
+ }
563
+ function describe2(value) {
564
+ if (value === null) return "null";
565
+ if (Array.isArray(value)) return "Array";
566
+ return typeof value;
567
+ }
568
+ var ArgError = class extends Error {
569
+ constructor(message) {
570
+ super(message);
571
+ this.name = "ArgError";
572
+ }
573
+ };
574
+
575
+ // src/actor.ts
576
+ var storage2 = createScopedStorage(
577
+ /* @__PURE__ */ Symbol.for("ezlogs-nextjs:actor-storage")
578
+ );
579
+ function getCurrentActor() {
580
+ return storage2.read();
581
+ }
582
+ function setActor(input) {
583
+ const sanitized = validateActor(input);
584
+ if (input != null && sanitized === null) {
585
+ chunkV5YNKKTG_cjs.logger.debug(`Actor: invalid actor structure ignored: ${describe3(input)}`);
586
+ }
587
+ storage2.update(sanitized);
588
+ return sanitized;
589
+ }
590
+ function runWithActorScope(callback) {
591
+ return storage2.run(null, callback);
592
+ }
593
+ var VALID_KINDS = /* @__PURE__ */ new Set(["human", "agent", "system", "hybrid"]);
594
+ function validateActor(input) {
595
+ if (input === null || input === void 0) return null;
596
+ if (typeof input !== "object") return null;
597
+ if (Array.isArray(input)) return null;
598
+ const obj = input;
599
+ const rawId = obj.id;
600
+ if (rawId === null || rawId === void 0) return null;
601
+ const id = String(rawId);
602
+ if (id === "") return null;
603
+ const result = { id };
604
+ if (obj.label !== void 0 && obj.label !== null) {
605
+ result.label = String(obj.label);
606
+ }
607
+ if (obj.kind !== void 0 && obj.kind !== null) {
608
+ const kind = String(obj.kind);
609
+ if (VALID_KINDS.has(kind)) {
610
+ result.kind = kind;
611
+ }
612
+ }
613
+ const principal = sanitizePrincipal(obj.principal);
614
+ if (principal) result.principal = principal;
615
+ return result;
616
+ }
617
+ function sanitizePrincipal(input) {
618
+ if (input === null || input === void 0) return null;
619
+ if (typeof input !== "object") return null;
620
+ if (Array.isArray(input)) return null;
621
+ const obj = input;
622
+ const rawId = obj.id;
623
+ if (rawId === null || rawId === void 0) return null;
624
+ const id = String(rawId);
625
+ if (id === "") return null;
626
+ const result = { id };
627
+ if (obj.label !== void 0 && obj.label !== null) {
628
+ result.label = String(obj.label);
629
+ }
630
+ return result;
631
+ }
632
+ function describe3(value) {
633
+ try {
634
+ return JSON.stringify(value);
635
+ } catch {
636
+ return Object.prototype.toString.call(value);
637
+ }
638
+ }
639
+
640
+ // src/http/sanitize.ts
641
+ var SENSITIVE_VARIABLE_PATTERNS = Object.freeze([
642
+ "password",
643
+ "passwd",
644
+ "pwd",
645
+ "token",
646
+ "access_token",
647
+ "refresh_token",
648
+ "api_token",
649
+ "auth_token",
650
+ "secret",
651
+ "api_secret",
652
+ "client_secret",
653
+ "api_key",
654
+ "apikey",
655
+ "private_key",
656
+ "privatekey",
657
+ "public_key",
658
+ "signing_key",
659
+ "secret_key",
660
+ "secretkey",
661
+ "credential",
662
+ "auth",
663
+ "authorization",
664
+ "encrypted",
665
+ "encrypted_data",
666
+ "ssn",
667
+ "social_security",
668
+ "credit_card",
669
+ "card_number",
670
+ "cvv",
671
+ "cvc",
672
+ // Crypto-material patterns — aligned with DB_SENSITIVE_PATTERNS
673
+ // (PR #45). Request bodies can carry the same key material as DB
674
+ // columns (a webhook POST containing a `signature` field, an HMAC
675
+ // header echoed into a JSON body, a `pem`-encoded cert blob, etc).
676
+ "pem",
677
+ "cipher",
678
+ "nonce",
679
+ "salt",
680
+ "digest",
681
+ "signature",
682
+ "hmac",
683
+ // 0.2.0 additions (not yet in the Rails gem's list).
684
+ "passcode",
685
+ "cardnumber"
686
+ ]);
687
+ var SENSITIVE_WORD_PATTERNS = Object.freeze([
688
+ "pin",
689
+ "otp",
690
+ "totp",
691
+ "iban",
692
+ "mfa",
693
+ "passphrase"
694
+ ]);
695
+ function snakeLower(key) {
696
+ return key.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
697
+ }
698
+ function matchesSensitiveKey(key, substringPatterns) {
699
+ const lower = key.toLowerCase();
700
+ const snake = snakeLower(key);
701
+ if (substringPatterns.some((p) => lower.includes(p) || snake.includes(p))) {
702
+ return true;
703
+ }
704
+ const words = snake.split(/[^a-z0-9]+/);
705
+ return SENSITIVE_WORD_PATTERNS.some((w) => words.includes(w));
706
+ }
707
+ var MAX_NESTING_DEPTH = 3;
708
+ var MAX_ARRAY_DISPLAY_SIZE = 5;
709
+ function sanitizeRequestParams(params, userPatterns = []) {
710
+ if (params === null || params === void 0) return null;
711
+ if (!isPlainObject2(params)) return null;
712
+ const obj = params;
713
+ const cleaned = {};
714
+ for (const key of Object.keys(obj)) {
715
+ if (FRAMEWORK_INTERNAL_KEYS.has(key)) continue;
716
+ cleaned[key] = obj[key];
717
+ }
718
+ if (Object.keys(cleaned).length === 0) return null;
719
+ const out = {};
720
+ for (const key of Object.keys(cleaned)) {
721
+ out[key] = sanitizeValue(key, cleaned[key], 0, userPatterns);
722
+ }
723
+ return out;
724
+ }
725
+ var FRAMEWORK_INTERNAL_KEYS = /* @__PURE__ */ new Set([
726
+ // Rails leftovers — kept for parity since users may funnel through a
727
+ // proxy that adds them, e.g. via a NextAuth credentials provider that
728
+ // forwards CSRF tokens.
729
+ "controller",
730
+ "action",
731
+ "format",
732
+ "authenticity_token",
733
+ "_method",
734
+ // Next.js / common JS conventions
735
+ "csrfToken",
736
+ "_csrf",
737
+ "_next"
738
+ ]);
739
+ function passesLuhn(digits) {
740
+ let sum = 0;
741
+ for (let i = 0; i < digits.length; i += 1) {
742
+ let d = Number(digits[digits.length - 1 - i]);
743
+ if (i % 2 === 1) {
744
+ d *= 2;
745
+ if (d > 9) d -= 9;
746
+ }
747
+ sum += d;
748
+ }
749
+ return sum % 10 === 0;
750
+ }
751
+ var SECRET_TEXT_PATTERNS = [
752
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,
753
+ /\beyJ[\w-]+\.[\w-]+\.[\w-]+/g,
754
+ /\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]+/g,
755
+ /\bsk-[A-Za-z0-9_-]{16,}/g,
756
+ /\bgh[pousr]_[A-Za-z0-9]{20,}/g,
757
+ /\bxox[abposr]-[A-Za-z0-9-]+/g,
758
+ /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g
759
+ ];
760
+ var EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;
761
+ function scrubSecretsInText(text, options = {}) {
762
+ let out = text;
763
+ for (const pattern of SECRET_TEXT_PATTERNS) out = out.replace(pattern, "[FILTERED]");
764
+ out = out.replace(/\b(Bearer|Basic)\s+[\w.~+/=-]+/gi, "$1 [FILTERED]").replace(/\b\d(?:[ -]?\d){12,18}\b/g, (match) => {
765
+ const digits = match.replace(/[ -]/g, "");
766
+ return (digits.length === 15 || digits.length === 16) && passesLuhn(digits) ? "[FILTERED]" : match;
767
+ });
768
+ return options.emails ? out.replace(EMAIL, "[FILTERED]") : out;
769
+ }
770
+ function sanitizeArgs(args, userPatterns = []) {
771
+ return sanitizeArrayValue(args, 0, userPatterns);
772
+ }
773
+ function sanitizeValue(key, value, depth, userPatterns) {
774
+ if (isSensitiveKey2(key, userPatterns)) return "[FILTERED]";
775
+ if (isPlainObject2(value)) {
776
+ return sanitizeNestedObject(value, depth, userPatterns);
777
+ }
778
+ if (Array.isArray(value)) {
779
+ return sanitizeArrayValue(value, depth, userPatterns);
780
+ }
781
+ return value;
782
+ }
783
+ function sanitizeNestedObject(hash, depth, userPatterns) {
784
+ if (depth >= MAX_NESTING_DEPTH) return "[Object]";
785
+ if (Object.keys(hash).length === 0) return {};
786
+ const out = {};
787
+ for (const k of Object.keys(hash)) {
788
+ out[k] = sanitizeValue(k, hash[k], depth + 1, userPatterns);
789
+ }
790
+ return out;
791
+ }
792
+ function sanitizeArrayValue(array, depth, userPatterns) {
793
+ if (array.length === 0) return [];
794
+ const allPrimitive = array.every(isPrimitive);
795
+ if (allPrimitive) {
796
+ if (array.length <= MAX_ARRAY_DISPLAY_SIZE) return array;
797
+ const preview = array.slice(0, MAX_ARRAY_DISPLAY_SIZE);
798
+ return `${JSON.stringify(preview)}... (${array.length} total)`;
799
+ }
800
+ if (array.length <= MAX_ARRAY_DISPLAY_SIZE) {
801
+ return array.map((item) => sanitizeArrayItem(item, depth, userPatterns));
802
+ }
803
+ return {
804
+ _truncated: true,
805
+ _count: array.length,
806
+ _preview: array.slice(0, MAX_ARRAY_DISPLAY_SIZE).map((item) => sanitizeArrayItem(item, depth, userPatterns))
807
+ };
808
+ }
809
+ function sanitizeArrayItem(item, depth, userPatterns) {
810
+ if (isPrimitive(item)) return item;
811
+ if (isPlainObject2(item)) {
812
+ return sanitizeNestedObject(item, depth + 1, userPatterns);
813
+ }
814
+ if (Array.isArray(item)) return sanitizeArrayValue(item, depth + 1, userPatterns);
815
+ return "[Object]";
816
+ }
817
+ function isSensitiveKey2(key, userPatterns) {
818
+ if (matchesSensitiveKey(key, SENSITIVE_VARIABLE_PATTERNS)) return true;
819
+ const lower = key.toLowerCase();
820
+ return userPatterns.some((p) => lower.includes(p.toLowerCase()));
821
+ }
822
+ function isPrimitive(value) {
823
+ return value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
824
+ }
825
+ function isPlainObject2(value) {
826
+ if (value === null || typeof value !== "object") return false;
827
+ const proto = Object.getPrototypeOf(value);
828
+ return proto === Object.prototype || proto === null;
829
+ }
830
+
831
+ // src/db/shared.ts
832
+ var IGNORED_ATTRIBUTES = Object.freeze([
833
+ "id",
834
+ "createdAt",
835
+ "created_at",
836
+ "updatedAt",
837
+ "updated_at",
838
+ // Auth.js / NextAuth standard columns
839
+ "emailVerified",
840
+ "expires"
841
+ ]);
842
+ var DB_SENSITIVE_PATTERNS = Object.freeze([
843
+ "password",
844
+ "token",
845
+ "secret",
846
+ "api_key",
847
+ "credit_card",
848
+ "ssn",
849
+ "social_security",
850
+ "encrypted",
851
+ "private_key",
852
+ "public_key",
853
+ "signing_key",
854
+ "pem",
855
+ "cipher",
856
+ "nonce",
857
+ "salt",
858
+ "digest",
859
+ "signature",
860
+ "hmac",
861
+ // 0.2.0 additions. `credential` / `passwd` / `apikey` were already in
862
+ // the HTTP list; `passcode` / `card_number` / `cardnumber` / `cvv` /
863
+ // `cvc` are new. Whole-word `pin` / `otp` / `totp` / `iban` come from
864
+ // SENSITIVE_WORD_PATTERNS. The SQL trigger mirrors this list.
865
+ "credential",
866
+ "passwd",
867
+ "passcode",
868
+ "apikey",
869
+ "card_number",
870
+ "cardnumber",
871
+ "cvv",
872
+ "cvc"
873
+ ]);
874
+ function emitDbEvent(input) {
875
+ try {
876
+ const config = configuration();
877
+ if (!config.captureDb) return;
878
+ if (config.allExcludedTables().includes(input.modelClass)) return;
879
+ if (config.databaseReader && !input._fromTrigger) {
880
+ const tracked = config.triggerTrackedTables;
881
+ if (tracked === null || tracked.has(input.table ?? input.modelClass)) return;
882
+ }
883
+ if (input.operation === "update") {
884
+ const meaningful = input.changes ? filterMeaningfulChanges(input.changes) : [];
885
+ if (meaningful.length === 0) return;
886
+ }
887
+ const resourceIdStr = input.resourceId === null || input.resourceId === void 0 ? null : String(input.resourceId);
888
+ const related = resourceIdStr === null ? input.relatedResourceIds ?? [] : [];
889
+ const context = buildContext(
890
+ related.length > 0 ? { ...input, displayName: null, modelInstance: null } : input
891
+ );
892
+ const event = build({
893
+ source_type: "database_callback",
894
+ source_data: {
895
+ model_class: input.modelClass,
896
+ operation: input.operation
897
+ },
898
+ outcome: "success",
899
+ correlation_id: current(),
900
+ resource_ids: resourceIdStr === null ? [...related] : [{ resource_type: input.modelClass, resource_id: resourceIdStr }],
901
+ context,
902
+ duration_ms: null,
903
+ timestamp: input.timestamp ?? null
904
+ });
905
+ pushEvent(event);
906
+ } catch (error) {
907
+ chunkV5YNKKTG_cjs.logger.debug(`db emit failed: ${describeError(error)}`);
908
+ }
909
+ }
910
+ function buildContext(input) {
911
+ const context = {};
912
+ const actor = getCurrentActor();
913
+ if (actor) context.actor = actor;
914
+ if ((input.operation === "create" || input.operation === "destroy") && input.initialAttributes) {
915
+ const filtered = filterMeaningfulAttributes(input.initialAttributes);
916
+ if (filtered !== null) context.initial_attributes = filtered;
917
+ }
918
+ if (input.operation === "update" && input.changes) {
919
+ const filtered = filterMeaningfulChanges(input.changes);
920
+ if (filtered.length > 0) {
921
+ context.changes = filtered.map((c) => {
922
+ const out = {
923
+ attribute: c.attribute,
924
+ to: formatForJson(c.to)
925
+ };
926
+ if (c.from !== void 0) out.from = formatForJson(c.from);
927
+ return out;
928
+ });
929
+ }
930
+ }
931
+ const displayName = input.displayName ?? (input.modelInstance ? resolveDisplayName(input.modelClass, input.modelInstance) : null);
932
+ if (displayName !== null) context.display_name = displayName;
933
+ return Object.keys(context).length === 0 ? null : context;
934
+ }
935
+ function filterMeaningfulAttributes(attrs) {
936
+ const out = {};
937
+ for (const key of Object.keys(attrs)) {
938
+ if (!isMeaningfulAttribute(key)) continue;
939
+ const value = attrs[key];
940
+ if (value === null || value === void 0) continue;
941
+ if (!isScalar(value)) continue;
942
+ out[key] = formatForJson(value);
943
+ }
944
+ return Object.keys(out).length === 0 ? null : out;
945
+ }
946
+ function filterMeaningfulChanges(changes) {
947
+ return flattenNestedChanges(changes).filter((c) => {
948
+ if (!isMeaningfulAttribute(c.attribute)) return false;
949
+ if (!isScalar(c.to)) return false;
950
+ if (c.from === void 0) return true;
951
+ if (!isScalar(c.from)) return false;
952
+ return valuesActuallyChanged(c.from, c.to);
953
+ });
954
+ }
955
+ var MAX_NESTED_DEPTH = 3;
956
+ var MAX_NESTED_LEAVES = 20;
957
+ var MAX_UNKNOWN_FROM_LEAVES = 5;
958
+ var MAX_SCANNED_LEAVES = 200;
959
+ var NESTED_BOOKKEEPING_KEYS = /* @__PURE__ */ new Set([
960
+ "created_at",
961
+ "createdAt",
962
+ "updated_at",
963
+ "updatedAt"
964
+ ]);
965
+ var NESTED_BOOKKEEPING_STAMP = /^(?:last_?)?(?:updated|modified|synced|refreshed|fetched|touched|cached)_?at$/i;
966
+ var NESTED_VERSION_COUNTER = /^(?:__v|version|lock_?version)$/i;
967
+ function isNestedBookkeeping(key, from, to) {
968
+ if (NESTED_BOOKKEEPING_KEYS.has(key) || NESTED_BOOKKEEPING_STAMP.test(key)) return true;
969
+ return NESTED_VERSION_COUNTER.test(key) && typeof to === "number" && (from === void 0 || from === null || typeof from === "number");
970
+ }
971
+ function leafRank(change) {
972
+ if (change.from === void 0) return 2;
973
+ return change.from === null || change.to === null ? 1 : 0;
974
+ }
975
+ function flattenNestedChanges(changes) {
976
+ if (!changes.some((c) => isPlainRecord(c.to) || isPlainRecord(c.from))) return changes;
977
+ const out = [];
978
+ const nested = [];
979
+ for (const c of changes) {
980
+ if (!isPlainRecord(c.to) && !isPlainRecord(c.from)) {
981
+ out.push(c);
982
+ continue;
983
+ }
984
+ if (!isMeaningfulAttribute(c.attribute)) continue;
985
+ const leaves = [];
986
+ collectLeafChanges(c.attribute, c.from, c.to, 1, leaves);
987
+ leaves.sort((a, b) => leafRank(a) - leafRank(b));
988
+ const cap = c.from === void 0 ? MAX_UNKNOWN_FROM_LEAVES : MAX_NESTED_LEAVES;
989
+ nested.push(...leaves.slice(0, cap).map(scrubLeaf));
990
+ }
991
+ return out.concat(nested);
992
+ }
993
+ function collectLeafChanges(path, from, to, depth, out) {
994
+ if (out.length >= MAX_SCANNED_LEAVES) return;
995
+ const fromObj = isPlainRecord(from);
996
+ const toObj = isPlainRecord(to);
997
+ if ((fromObj || toObj) && depth <= MAX_NESTED_DEPTH && (fromObj || from == null) && (toObj || to == null)) {
998
+ const f = fromObj ? from : {};
999
+ const t = toObj ? to : {};
1000
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(f), ...Object.keys(t)])) {
1001
+ const before = from === void 0 ? void 0 : f[key] ?? null;
1002
+ collectLeafChanges(`${path}.${key}`, before, t[key] ?? null, depth + 1, out);
1003
+ }
1004
+ return;
1005
+ }
1006
+ if (from !== void 0 && sameJson(from, to)) return;
1007
+ if (path.includes(".") && isNestedBookkeeping(path.slice(path.lastIndexOf(".") + 1), from, to)) return;
1008
+ out.push(from === void 0 ? { attribute: path, to } : { attribute: path, from, to });
1009
+ }
1010
+ function scrubLeaf(change) {
1011
+ const scrub = (v) => typeof v === "string" ? scrubSecretsInText(v) : v;
1012
+ const out = { attribute: change.attribute, to: scrub(change.to) };
1013
+ if (change.from !== void 0) out.from = scrub(change.from);
1014
+ return out;
1015
+ }
1016
+ function isPlainRecord(value) {
1017
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
1018
+ const proto = Object.getPrototypeOf(value);
1019
+ return proto === Object.prototype || proto === null;
1020
+ }
1021
+ function sameJson(a, b) {
1022
+ if (a === b) return true;
1023
+ try {
1024
+ return JSON.stringify(a) === JSON.stringify(b);
1025
+ } catch {
1026
+ return false;
1027
+ }
1028
+ }
1029
+ function isMeaningfulAttribute(name) {
1030
+ if (IGNORED_ATTRIBUTES.includes(name)) return false;
1031
+ if (isDbSensitive(name)) return false;
1032
+ return true;
1033
+ }
1034
+ function isDbSensitive(name) {
1035
+ return matchesSensitiveKey(name, DB_SENSITIVE_PATTERNS);
1036
+ }
1037
+ function isScalar(value) {
1038
+ if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint" || value instanceof Date) {
1039
+ return true;
1040
+ }
1041
+ if (isPrismaDecimal(value)) return true;
1042
+ if (Buffer.isBuffer?.(value)) return false;
1043
+ if (Array.isArray(value)) return value.every((v) => isScalar(v));
1044
+ return false;
1045
+ }
1046
+ function valuesActuallyChanged(from, to) {
1047
+ if (from === null && to === null) return false;
1048
+ if (from instanceof Date && to instanceof Date) {
1049
+ return from.getTime() !== to.getTime();
1050
+ }
1051
+ return from !== to;
1052
+ }
1053
+ function formatForJson(value) {
1054
+ if (value === null || value === void 0) return value;
1055
+ if (value instanceof Date) return value.toISOString();
1056
+ if (typeof value === "bigint") return value.toString();
1057
+ if (isPrismaDecimal(value)) return Number(value.toString());
1058
+ if (Array.isArray(value)) return value.map(formatForJson);
1059
+ return value;
1060
+ }
1061
+ function isPrismaDecimal(value) {
1062
+ if (value === null || typeof value !== "object") return false;
1063
+ const obj = value;
1064
+ return typeof obj.toString === "function" && typeof obj.toFixed === "function" && "d" in obj && "e" in obj && "s" in obj;
1065
+ }
1066
+ var DISPLAY_NAME_COLUMNS = ["name", "title", "number", "label"];
1067
+ var MAX_DISPLAY_NAME_LENGTH = 120;
1068
+ function resolveDisplayName(modelClass, instance) {
1069
+ try {
1070
+ const config = configuration();
1071
+ const resolver = config.displayNameFor[modelClass];
1072
+ const resolved = applyResolver(resolver, instance);
1073
+ if (resolved !== null) return resolved;
1074
+ const columns = /* @__PURE__ */ new Map();
1075
+ for (const key of Object.keys(instance)) {
1076
+ if (isDbSensitive(key)) continue;
1077
+ const norm = key.toLowerCase().replace(/_/g, "");
1078
+ if (!columns.has(norm)) columns.set(norm, instance[key]);
1079
+ }
1080
+ const text = (norm) => {
1081
+ const value = columns.get(norm);
1082
+ if (typeof value !== "string" && typeof value !== "number" && typeof value !== "bigint") {
1083
+ return null;
1084
+ }
1085
+ const str = String(value).trim();
1086
+ return str.length > 0 ? str.slice(0, MAX_DISPLAY_NAME_LENGTH) : null;
1087
+ };
1088
+ for (const column of DISPLAY_NAME_COLUMNS) {
1089
+ const value = text(column);
1090
+ if (value !== null) return value;
1091
+ }
1092
+ return text(`${singularNorm(modelClass)}number`);
1093
+ } catch {
1094
+ }
1095
+ return null;
1096
+ }
1097
+ function singularNorm(modelClass) {
1098
+ const norm = modelClass.toLowerCase().replace(/_/g, "");
1099
+ if (norm.endsWith("ies")) return norm.slice(0, -3) + "y";
1100
+ if (/(ss|us|is)$/.test(norm)) return norm;
1101
+ if (/(xes|ches|shes|sses)$/.test(norm)) return norm.slice(0, -2);
1102
+ return norm.endsWith("s") ? norm.slice(0, -1) : norm;
1103
+ }
1104
+ function applyResolver(resolver, instance) {
1105
+ if (typeof resolver === "string") {
1106
+ const value = instance[resolver];
1107
+ if (value !== null && value !== void 0 && String(value).length > 0) {
1108
+ return String(value);
1109
+ }
1110
+ return null;
1111
+ }
1112
+ if (typeof resolver === "function") {
1113
+ try {
1114
+ const value = resolver(instance);
1115
+ if (typeof value === "string" && value.length > 0) return value;
1116
+ if (value !== null && value !== void 0 && String(value).length > 0) {
1117
+ return String(value);
1118
+ }
1119
+ } catch {
1120
+ }
1121
+ }
1122
+ return null;
1123
+ }
1124
+ function describeError(error) {
1125
+ if (error instanceof Error) return `${error.name}: ${error.message}`;
1126
+ return String(error);
1127
+ }
1128
+
1129
+ exports.ArgError = ArgError;
1130
+ exports.DEFAULT_EXCLUDED_EXTENSIONS = DEFAULT_EXCLUDED_EXTENSIONS;
1131
+ exports.DEFAULT_EXCLUDED_TABLES = DEFAULT_EXCLUDED_TABLES;
1132
+ exports.buffer_exports = buffer_exports;
1133
+ exports.build = build;
1134
+ exports.configuration = configuration;
1135
+ exports.createScopedStorage = createScopedStorage;
1136
+ exports.current = current;
1137
+ exports.drainEvents = drainEvents;
1138
+ exports.emitDbEvent = emitDbEvent;
1139
+ exports.generate = generate;
1140
+ exports.getCurrentActor = getCurrentActor;
1141
+ exports.makeAsyncContextCapture = makeAsyncContextCapture;
1142
+ exports.passesLuhn = passesLuhn;
1143
+ exports.pushEvent = pushEvent;
1144
+ exports.resolveCorrelation = resolveCorrelation;
1145
+ exports.resolveDisplayName = resolveDisplayName;
1146
+ exports.runWithActorScope = runWithActorScope;
1147
+ exports.runWithCorrelation = runWithCorrelation;
1148
+ exports.sanitizeArgs = sanitizeArgs;
1149
+ exports.sanitizeRequestParams = sanitizeRequestParams;
1150
+ exports.scrubSecretsInText = scrubSecretsInText;
1151
+ exports.setActor = setActor;