ezlogs-nextjs 0.1.4 → 0.3.0

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 (40) hide show
  1. package/README.md +106 -11
  2. package/bin/install-triggers.cjs +49 -11
  3. package/dist/actors/index.d.cts +1 -1
  4. package/dist/actors/index.d.ts +1 -1
  5. package/dist/{configuration-3Pei_XZ_.d.cts → configuration-OHLNivON.d.cts} +11 -20
  6. package/dist/{configuration-3Pei_XZ_.d.ts → configuration-OHLNivON.d.ts} +11 -20
  7. package/dist/db/drizzle.cjs +154 -18
  8. package/dist/db/drizzle.js +154 -18
  9. package/dist/db/prisma.cjs +242 -45
  10. package/dist/db/prisma.d.cts +39 -1
  11. package/dist/db/prisma.d.ts +39 -1
  12. package/dist/db/prisma.js +241 -46
  13. package/dist/db/supabase.cjs +154 -18
  14. package/dist/db/supabase.js +154 -18
  15. package/dist/index.cjs +761 -245
  16. package/dist/index.d.cts +2 -2
  17. package/dist/index.d.ts +2 -2
  18. package/dist/index.js +761 -245
  19. package/dist/jobs/bullmq.cjs +973 -16
  20. package/dist/jobs/bullmq.d.cts +8 -3
  21. package/dist/jobs/bullmq.d.ts +8 -3
  22. package/dist/jobs/bullmq.js +973 -16
  23. package/dist/jobs/inngest.cjs +880 -14
  24. package/dist/jobs/inngest.d.cts +7 -5
  25. package/dist/jobs/inngest.d.ts +7 -5
  26. package/dist/jobs/inngest.js +880 -14
  27. package/dist/jobs/supabase-queues.cjs +878 -16
  28. package/dist/jobs/supabase-queues.js +878 -16
  29. package/dist/jobs/trigger.cjs +914 -42
  30. package/dist/jobs/trigger.js +914 -42
  31. package/dist/jobs/upstash-workflow.cjs +914 -14
  32. package/dist/jobs/upstash-workflow.d.cts +16 -2
  33. package/dist/jobs/upstash-workflow.d.ts +16 -2
  34. package/dist/jobs/upstash-workflow.js +914 -15
  35. package/dist/triggers/index.cjs +405 -76
  36. package/dist/triggers/index.d.cts +36 -41
  37. package/dist/triggers/index.d.ts +36 -41
  38. package/dist/triggers/index.js +404 -74
  39. package/package.json +5 -1
  40. package/sql/postgres/00_install.sql +244 -21
@@ -60,7 +60,7 @@ function build(input) {
60
60
  const outcome = validateOutcome(input.outcome);
61
61
  const timestamp = validateTimestamp(input.timestamp ?? null);
62
62
  const resource_ids = validateResourceIds(input.resource_ids ?? []);
63
- const context_raw = validateContext();
63
+ const context_raw = validateContext(input.context ?? null);
64
64
  const duration_ms = validateDurationMs(input.duration_ms ?? null);
65
65
  const error_message = input.error_message ?? null;
66
66
  validateOutcomeErrorConsistency(outcome, error_message);
@@ -81,6 +81,9 @@ function build(input) {
81
81
  return event;
82
82
  }
83
83
  function validateSourceType(value) {
84
+ if (value === null || value === void 0) {
85
+ throw new ArgError("source_type is required");
86
+ }
84
87
  const normalized = String(value);
85
88
  if (!VALID_SOURCE_TYPES.includes(normalized)) {
86
89
  throw new ArgError(
@@ -165,7 +168,13 @@ function validateResourceIds(value) {
165
168
  return value;
166
169
  }
167
170
  function validateContext(value) {
168
- return null;
171
+ if (value === null) return null;
172
+ if (!isPlainObject(value)) {
173
+ throw new ArgError(
174
+ `context must be an object or null, got: ${describe(value)}`
175
+ );
176
+ }
177
+ return value;
169
178
  }
170
179
  function validateDurationMs(value) {
171
180
  if (value === null || value === void 0) return null;
@@ -299,7 +308,6 @@ var Configuration = class {
299
308
  displayNameFor = {};
300
309
  isServerActionError = null;
301
310
  databaseReader = null;
302
- databaseSnapshotMode = false;
303
311
  databaseUrl = null;
304
312
  /**
305
313
  * Tables that have the `ezlogs_audit` trigger attached. Detected once
@@ -351,9 +359,6 @@ var Configuration = class {
351
359
  if (options.databaseReader !== void 0) {
352
360
  this.databaseReader = options.databaseReader;
353
361
  }
354
- if (options.databaseSnapshotMode !== void 0) {
355
- this.databaseSnapshotMode = options.databaseSnapshotMode;
356
- }
357
362
  if (options.databaseUrl !== void 0) {
358
363
  this.databaseUrl = options.databaseUrl;
359
364
  }
@@ -508,6 +513,835 @@ function runWithCorrelation(correlationId, callback) {
508
513
  return storage.run(correlationId, callback);
509
514
  }
510
515
 
516
+ // src/http/sanitize.ts
517
+ var SENSITIVE_VARIABLE_PATTERNS = Object.freeze([
518
+ "password",
519
+ "passwd",
520
+ "pwd",
521
+ "token",
522
+ "access_token",
523
+ "refresh_token",
524
+ "api_token",
525
+ "auth_token",
526
+ "secret",
527
+ "api_secret",
528
+ "client_secret",
529
+ "api_key",
530
+ "apikey",
531
+ "private_key",
532
+ "privatekey",
533
+ "public_key",
534
+ "signing_key",
535
+ "secret_key",
536
+ "secretkey",
537
+ "credential",
538
+ "auth",
539
+ "authorization",
540
+ "encrypted",
541
+ "encrypted_data",
542
+ "ssn",
543
+ "social_security",
544
+ "credit_card",
545
+ "card_number",
546
+ "cvv",
547
+ "cvc",
548
+ // Crypto-material patterns — aligned with DB_SENSITIVE_PATTERNS
549
+ // (PR #45). Request bodies can carry the same key material as DB
550
+ // columns (a webhook POST containing a `signature` field, an HMAC
551
+ // header echoed into a JSON body, a `pem`-encoded cert blob, etc).
552
+ "pem",
553
+ "cipher",
554
+ "nonce",
555
+ "salt",
556
+ "digest",
557
+ "signature",
558
+ "hmac",
559
+ // 0.2.0 additions (not yet in the Rails gem's list).
560
+ "passcode",
561
+ "cardnumber"
562
+ ]);
563
+ var SENSITIVE_WORD_PATTERNS = Object.freeze([
564
+ "pin",
565
+ "otp",
566
+ "totp",
567
+ "iban",
568
+ "mfa",
569
+ "passphrase"
570
+ ]);
571
+ function snakeLower(key) {
572
+ return key.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
573
+ }
574
+ function matchesSensitiveKey(key, substringPatterns) {
575
+ const lower = key.toLowerCase();
576
+ const snake = snakeLower(key);
577
+ if (substringPatterns.some((p) => lower.includes(p) || snake.includes(p))) {
578
+ return true;
579
+ }
580
+ const words = snake.split(/[^a-z0-9]+/);
581
+ return SENSITIVE_WORD_PATTERNS.some((w) => words.includes(w));
582
+ }
583
+ var MAX_NESTING_DEPTH = 3;
584
+ var MAX_ARRAY_DISPLAY_SIZE = 5;
585
+ function passesLuhn(digits) {
586
+ let sum = 0;
587
+ for (let i = 0; i < digits.length; i += 1) {
588
+ let d = Number(digits[digits.length - 1 - i]);
589
+ if (i % 2 === 1) {
590
+ d *= 2;
591
+ if (d > 9) d -= 9;
592
+ }
593
+ sum += d;
594
+ }
595
+ return sum % 10 === 0;
596
+ }
597
+ var SECRET_TEXT_PATTERNS = [
598
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,
599
+ /\beyJ[\w-]+\.[\w-]+\.[\w-]+/g,
600
+ /\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]+/g,
601
+ /\bsk-[A-Za-z0-9_-]{16,}/g,
602
+ /\bgh[pousr]_[A-Za-z0-9]{20,}/g,
603
+ /\bxox[abposr]-[A-Za-z0-9-]+/g,
604
+ /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g
605
+ ];
606
+ var EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;
607
+ function scrubSecretsInText(text, options = {}) {
608
+ let out = text;
609
+ for (const pattern of SECRET_TEXT_PATTERNS) out = out.replace(pattern, "[FILTERED]");
610
+ out = out.replace(/\b(Bearer|Basic)\s+[\w.~+/=-]+/gi, "$1 [FILTERED]").replace(/\b\d(?:[ -]?\d){12,18}\b/g, (match) => {
611
+ const digits = match.replace(/[ -]/g, "");
612
+ return (digits.length === 15 || digits.length === 16) && passesLuhn(digits) ? "[FILTERED]" : match;
613
+ });
614
+ return options.emails ? out.replace(EMAIL, "[FILTERED]") : out;
615
+ }
616
+ function sanitizeArgs(args, userPatterns = []) {
617
+ return sanitizeArrayValue(args, 0, userPatterns);
618
+ }
619
+ function sanitizeValue(key, value, depth, userPatterns) {
620
+ if (isSensitiveKey2(key, userPatterns)) return "[FILTERED]";
621
+ if (isPlainObject2(value)) {
622
+ return sanitizeNestedObject(value, depth, userPatterns);
623
+ }
624
+ if (Array.isArray(value)) {
625
+ return sanitizeArrayValue(value, depth, userPatterns);
626
+ }
627
+ return value;
628
+ }
629
+ function sanitizeNestedObject(hash, depth, userPatterns) {
630
+ if (depth >= MAX_NESTING_DEPTH) return "[Object]";
631
+ if (Object.keys(hash).length === 0) return {};
632
+ const out = {};
633
+ for (const k of Object.keys(hash)) {
634
+ out[k] = sanitizeValue(k, hash[k], depth + 1, userPatterns);
635
+ }
636
+ return out;
637
+ }
638
+ function sanitizeArrayValue(array, depth, userPatterns) {
639
+ if (array.length === 0) return [];
640
+ const allPrimitive = array.every(isPrimitive);
641
+ if (allPrimitive) {
642
+ if (array.length <= MAX_ARRAY_DISPLAY_SIZE) return array;
643
+ const preview = array.slice(0, MAX_ARRAY_DISPLAY_SIZE);
644
+ return `${JSON.stringify(preview)}... (${array.length} total)`;
645
+ }
646
+ if (array.length <= MAX_ARRAY_DISPLAY_SIZE) {
647
+ return array.map((item) => sanitizeArrayItem(item, depth, userPatterns));
648
+ }
649
+ return {
650
+ _truncated: true,
651
+ _count: array.length,
652
+ _preview: array.slice(0, MAX_ARRAY_DISPLAY_SIZE).map((item) => sanitizeArrayItem(item, depth, userPatterns))
653
+ };
654
+ }
655
+ function sanitizeArrayItem(item, depth, userPatterns) {
656
+ if (isPrimitive(item)) return item;
657
+ if (isPlainObject2(item)) {
658
+ return sanitizeNestedObject(item, depth + 1, userPatterns);
659
+ }
660
+ if (Array.isArray(item)) return sanitizeArrayValue(item, depth + 1, userPatterns);
661
+ return "[Object]";
662
+ }
663
+ function isSensitiveKey2(key, userPatterns) {
664
+ if (matchesSensitiveKey(key, SENSITIVE_VARIABLE_PATTERNS)) return true;
665
+ const lower = key.toLowerCase();
666
+ return userPatterns.some((p) => lower.includes(p.toLowerCase()));
667
+ }
668
+ function isPrimitive(value) {
669
+ return value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
670
+ }
671
+ function isPlainObject2(value) {
672
+ if (value === null || typeof value !== "object") return false;
673
+ const proto = Object.getPrototypeOf(value);
674
+ return proto === Object.prototype || proto === null;
675
+ }
676
+
677
+ // src/actor.ts
678
+ var storage2 = createScopedStorage(
679
+ /* @__PURE__ */ Symbol.for("ezlogs-nextjs:actor-storage")
680
+ );
681
+ function getCurrentActor() {
682
+ return storage2.read();
683
+ }
684
+ function runWithActorScope(callback) {
685
+ return storage2.run(null, callback);
686
+ }
687
+
688
+ // src/db/shared.ts
689
+ var IGNORED_ATTRIBUTES = Object.freeze([
690
+ "id",
691
+ "createdAt",
692
+ "created_at",
693
+ "updatedAt",
694
+ "updated_at",
695
+ // Auth.js / NextAuth standard columns
696
+ "emailVerified",
697
+ "expires"
698
+ ]);
699
+ var DB_SENSITIVE_PATTERNS = Object.freeze([
700
+ "password",
701
+ "token",
702
+ "secret",
703
+ "api_key",
704
+ "credit_card",
705
+ "ssn",
706
+ "social_security",
707
+ "encrypted",
708
+ "private_key",
709
+ "public_key",
710
+ "signing_key",
711
+ "pem",
712
+ "cipher",
713
+ "nonce",
714
+ "salt",
715
+ "digest",
716
+ "signature",
717
+ "hmac",
718
+ // 0.2.0 additions. `credential` / `passwd` / `apikey` were already in
719
+ // the HTTP list; `passcode` / `card_number` / `cardnumber` / `cvv` /
720
+ // `cvc` are new. Whole-word `pin` / `otp` / `totp` / `iban` come from
721
+ // SENSITIVE_WORD_PATTERNS. The SQL trigger mirrors this list.
722
+ "credential",
723
+ "passwd",
724
+ "passcode",
725
+ "apikey",
726
+ "card_number",
727
+ "cardnumber",
728
+ "cvv",
729
+ "cvc"
730
+ ]);
731
+ function emitDbEvent(input) {
732
+ try {
733
+ const config = configuration();
734
+ if (!config.captureDb) return;
735
+ if (config.allExcludedTables().includes(input.modelClass)) return;
736
+ if (config.databaseReader && !input._fromTrigger) {
737
+ const tracked = config.triggerTrackedTables;
738
+ if (tracked === null || tracked.has(input.table ?? input.modelClass)) return;
739
+ }
740
+ if (input.operation === "update") {
741
+ const meaningful = input.changes ? filterMeaningfulChanges(input.changes) : [];
742
+ if (meaningful.length === 0) return;
743
+ }
744
+ const resourceIdStr = input.resourceId === null || input.resourceId === void 0 ? null : String(input.resourceId);
745
+ const related = resourceIdStr === null ? input.relatedResourceIds ?? [] : [];
746
+ const context = buildContext(
747
+ related.length > 0 ? { ...input, displayName: null, modelInstance: null } : input
748
+ );
749
+ const event = build({
750
+ source_type: "database_callback",
751
+ source_data: {
752
+ model_class: input.modelClass,
753
+ operation: input.operation
754
+ },
755
+ outcome: "success",
756
+ correlation_id: current(),
757
+ resource_ids: resourceIdStr === null ? [...related] : [{ resource_type: input.modelClass, resource_id: resourceIdStr }],
758
+ context,
759
+ duration_ms: null,
760
+ timestamp: input.timestamp ?? null
761
+ });
762
+ pushEvent(event);
763
+ } catch (error) {
764
+ logger.debug(`db emit failed: ${describeError(error)}`);
765
+ }
766
+ }
767
+ function buildContext(input) {
768
+ const context = {};
769
+ const actor = getCurrentActor();
770
+ if (actor) context.actor = actor;
771
+ if ((input.operation === "create" || input.operation === "destroy") && input.initialAttributes) {
772
+ const filtered = filterMeaningfulAttributes(input.initialAttributes);
773
+ if (filtered !== null) context.initial_attributes = filtered;
774
+ }
775
+ if (input.operation === "update" && input.changes) {
776
+ const filtered = filterMeaningfulChanges(input.changes);
777
+ if (filtered.length > 0) {
778
+ context.changes = filtered.map((c) => {
779
+ const out = {
780
+ attribute: c.attribute,
781
+ to: formatForJson(c.to)
782
+ };
783
+ if (c.from !== void 0) out.from = formatForJson(c.from);
784
+ return out;
785
+ });
786
+ }
787
+ }
788
+ const displayName = input.displayName ?? (input.modelInstance ? resolveDisplayName(input.modelClass, input.modelInstance) : null);
789
+ if (displayName !== null) context.display_name = displayName;
790
+ return Object.keys(context).length === 0 ? null : context;
791
+ }
792
+ function filterMeaningfulAttributes(attrs) {
793
+ const out = {};
794
+ for (const key of Object.keys(attrs)) {
795
+ if (!isMeaningfulAttribute(key)) continue;
796
+ const value = attrs[key];
797
+ if (value === null || value === void 0) continue;
798
+ if (!isScalar(value)) continue;
799
+ out[key] = formatForJson(value);
800
+ }
801
+ return Object.keys(out).length === 0 ? null : out;
802
+ }
803
+ function filterMeaningfulChanges(changes) {
804
+ return flattenNestedChanges(changes).filter((c) => {
805
+ if (!isMeaningfulAttribute(c.attribute)) return false;
806
+ if (!isScalar(c.to)) return false;
807
+ if (c.from === void 0) return true;
808
+ if (!isScalar(c.from)) return false;
809
+ return valuesActuallyChanged(c.from, c.to);
810
+ });
811
+ }
812
+ var MAX_NESTED_DEPTH = 3;
813
+ var MAX_NESTED_LEAVES = 20;
814
+ var MAX_UNKNOWN_FROM_LEAVES = 5;
815
+ function flattenNestedChanges(changes) {
816
+ if (!changes.some((c) => isPlainRecord(c.to) || isPlainRecord(c.from))) return changes;
817
+ const out = [];
818
+ for (const c of changes) {
819
+ if (!isPlainRecord(c.to) && !isPlainRecord(c.from)) {
820
+ out.push(c);
821
+ continue;
822
+ }
823
+ if (!isMeaningfulAttribute(c.attribute)) continue;
824
+ const leaves = [];
825
+ collectLeafChanges(c.attribute, c.from, c.to, 1, leaves);
826
+ const cap = c.from === void 0 ? MAX_UNKNOWN_FROM_LEAVES : MAX_NESTED_LEAVES;
827
+ out.push(...leaves.slice(0, cap).map(scrubLeaf));
828
+ }
829
+ return out;
830
+ }
831
+ function collectLeafChanges(path, from, to, depth, out) {
832
+ if (out.length > MAX_NESTED_LEAVES) return;
833
+ const fromObj = isPlainRecord(from);
834
+ const toObj = isPlainRecord(to);
835
+ if ((fromObj || toObj) && depth <= MAX_NESTED_DEPTH && (fromObj || from == null) && (toObj || to == null)) {
836
+ const f = fromObj ? from : {};
837
+ const t = toObj ? to : {};
838
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(f), ...Object.keys(t)])) {
839
+ const before = from === void 0 ? void 0 : f[key] ?? null;
840
+ collectLeafChanges(`${path}.${key}`, before, t[key] ?? null, depth + 1, out);
841
+ }
842
+ return;
843
+ }
844
+ if (from !== void 0 && sameJson(from, to)) return;
845
+ out.push(from === void 0 ? { attribute: path, to } : { attribute: path, from, to });
846
+ }
847
+ function scrubLeaf(change) {
848
+ const scrub = (v) => typeof v === "string" ? scrubSecretsInText(v) : v;
849
+ const out = { attribute: change.attribute, to: scrub(change.to) };
850
+ if (change.from !== void 0) out.from = scrub(change.from);
851
+ return out;
852
+ }
853
+ function isPlainRecord(value) {
854
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
855
+ const proto = Object.getPrototypeOf(value);
856
+ return proto === Object.prototype || proto === null;
857
+ }
858
+ function sameJson(a, b) {
859
+ if (a === b) return true;
860
+ try {
861
+ return JSON.stringify(a) === JSON.stringify(b);
862
+ } catch {
863
+ return false;
864
+ }
865
+ }
866
+ function isMeaningfulAttribute(name) {
867
+ if (IGNORED_ATTRIBUTES.includes(name)) return false;
868
+ if (isDbSensitive(name)) return false;
869
+ return true;
870
+ }
871
+ function isDbSensitive(name) {
872
+ return matchesSensitiveKey(name, DB_SENSITIVE_PATTERNS);
873
+ }
874
+ function isScalar(value) {
875
+ if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint" || value instanceof Date) {
876
+ return true;
877
+ }
878
+ if (isPrismaDecimal(value)) return true;
879
+ if (Buffer.isBuffer?.(value)) return false;
880
+ if (Array.isArray(value)) return value.every((v) => isScalar(v));
881
+ return false;
882
+ }
883
+ function valuesActuallyChanged(from, to) {
884
+ if (from === null && to === null) return false;
885
+ if (from instanceof Date && to instanceof Date) {
886
+ return from.getTime() !== to.getTime();
887
+ }
888
+ return from !== to;
889
+ }
890
+ function formatForJson(value) {
891
+ if (value === null || value === void 0) return value;
892
+ if (value instanceof Date) return value.toISOString();
893
+ if (typeof value === "bigint") return value.toString();
894
+ if (isPrismaDecimal(value)) return Number(value.toString());
895
+ if (Array.isArray(value)) return value.map(formatForJson);
896
+ return value;
897
+ }
898
+ function isPrismaDecimal(value) {
899
+ if (value === null || typeof value !== "object") return false;
900
+ const obj = value;
901
+ return typeof obj.toString === "function" && typeof obj.toFixed === "function" && "d" in obj && "e" in obj && "s" in obj;
902
+ }
903
+ var DISPLAY_NAME_COLUMNS = ["name", "title", "number", "label"];
904
+ var MAX_DISPLAY_NAME_LENGTH = 120;
905
+ function resolveDisplayName(modelClass, instance) {
906
+ try {
907
+ const config = configuration();
908
+ const resolver = config.displayNameFor[modelClass];
909
+ const resolved = applyResolver(resolver, instance);
910
+ if (resolved !== null) return resolved;
911
+ const columns = /* @__PURE__ */ new Map();
912
+ for (const key of Object.keys(instance)) {
913
+ if (isDbSensitive(key)) continue;
914
+ const norm = key.toLowerCase().replace(/_/g, "");
915
+ if (!columns.has(norm)) columns.set(norm, instance[key]);
916
+ }
917
+ const text = (norm) => {
918
+ const value = columns.get(norm);
919
+ if (typeof value !== "string" && typeof value !== "number" && typeof value !== "bigint") {
920
+ return null;
921
+ }
922
+ const str = String(value).trim();
923
+ return str.length > 0 ? str.slice(0, MAX_DISPLAY_NAME_LENGTH) : null;
924
+ };
925
+ for (const column of DISPLAY_NAME_COLUMNS) {
926
+ const value = text(column);
927
+ if (value !== null) return value;
928
+ }
929
+ return text(`${singularNorm(modelClass)}number`);
930
+ } catch {
931
+ }
932
+ return null;
933
+ }
934
+ function singularNorm(modelClass) {
935
+ const norm = modelClass.toLowerCase().replace(/_/g, "");
936
+ if (norm.endsWith("ies")) return norm.slice(0, -3) + "y";
937
+ if (/(ss|us|is)$/.test(norm)) return norm;
938
+ if (/(xes|ches|shes|sses)$/.test(norm)) return norm.slice(0, -2);
939
+ return norm.endsWith("s") ? norm.slice(0, -1) : norm;
940
+ }
941
+ function applyResolver(resolver, instance) {
942
+ if (typeof resolver === "string") {
943
+ const value = instance[resolver];
944
+ if (value !== null && value !== void 0 && String(value).length > 0) {
945
+ return String(value);
946
+ }
947
+ return null;
948
+ }
949
+ if (typeof resolver === "function") {
950
+ try {
951
+ const value = resolver(instance);
952
+ if (typeof value === "string" && value.length > 0) return value;
953
+ if (value !== null && value !== void 0 && String(value).length > 0) {
954
+ return String(value);
955
+ }
956
+ } catch {
957
+ }
958
+ }
959
+ return null;
960
+ }
961
+ function describeError(error) {
962
+ if (error instanceof Error) return `${error.name}: ${error.message}`;
963
+ return String(error);
964
+ }
965
+
966
+ // src/triggers/emit-dedup.ts
967
+ var storage3 = createScopedStorage(
968
+ /* @__PURE__ */ Symbol.for("ezlogs-nextjs:audit-emitted-ids-storage")
969
+ );
970
+ function currentEmittedAuditIds() {
971
+ return storage3.read();
972
+ }
973
+
974
+ // src/triggers/reader.ts
975
+ var COLUMNS = "id, table_name, op, old_row, new_row, resource_id, correlation_id, txid, captured_at";
976
+ var ORPHAN_AGE = "5 minutes";
977
+ var PRUNE_AGE = "24 hours";
978
+ var SWEEP_BATCH = 100;
979
+ var PRUNE_BATCH = 2e3;
980
+ var SWEEP_INTERVAL_MS = 1e4;
981
+ var PRUNE_INTERVAL_MS = 10 * 6e4;
982
+ var lastSweepAt = 0;
983
+ var lastPruneAt = 0;
984
+ var deleteDenied = false;
985
+ var txCorrelation = /* @__PURE__ */ new Map();
986
+ async function readAuditRows(exec, correlationId, since = null) {
987
+ const where = since ? "correlation_id = $1 AND captured_at >= $2" : "correlation_id = $1";
988
+ const params = since ? [correlationId, since.toISOString()] : [correlationId];
989
+ try {
990
+ if (!deleteDenied) {
991
+ try {
992
+ return sortById(
993
+ extractRows(
994
+ await exec(
995
+ `DELETE FROM ezlogs_audit_log WHERE ${where} RETURNING ${COLUMNS}`,
996
+ params
997
+ )
998
+ ).map(normalizeAuditRow)
999
+ );
1000
+ } catch (err) {
1001
+ if (!isPermissionDenied(err)) throw err;
1002
+ deleteDenied = true;
1003
+ logger.warn(
1004
+ "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'`."
1005
+ );
1006
+ }
1007
+ }
1008
+ const result = await exec(
1009
+ `SELECT ${COLUMNS} FROM ezlogs_audit_log WHERE ${where} ORDER BY id ASC`,
1010
+ params
1011
+ );
1012
+ return extractRows(result).map(normalizeAuditRow);
1013
+ } catch (err) {
1014
+ logger.debug(
1015
+ `readAuditRows failed: ${err instanceof Error ? err.message : String(err)}`
1016
+ );
1017
+ return [];
1018
+ }
1019
+ }
1020
+ async function sweepAuditLog(exec) {
1021
+ if (deleteDenied) return 0;
1022
+ try {
1023
+ const rows = sortById(
1024
+ extractRows(
1025
+ await exec(
1026
+ `DELETE FROM ezlogs_audit_log
1027
+ WHERE id IN (
1028
+ SELECT id FROM ezlogs_audit_log
1029
+ WHERE (correlation_id IS NULL
1030
+ OR captured_at < now() - interval '${ORPHAN_AGE}')
1031
+ -- Never resurface history: past the retention cap a
1032
+ -- row is pruned, not sent as new activity.
1033
+ AND captured_at > now() - interval '${PRUNE_AGE}'
1034
+ ORDER BY id
1035
+ LIMIT ${SWEEP_BATCH}
1036
+ FOR UPDATE SKIP LOCKED)
1037
+ RETURNING ${COLUMNS}`,
1038
+ []
1039
+ )
1040
+ ).map(normalizeAuditRow)
1041
+ );
1042
+ await loadTableMeta(exec, rows);
1043
+ for (const row of rows) {
1044
+ const correlationId = row.correlation_id ?? correlationForTx(row.txid);
1045
+ runWithCorrelation(
1046
+ correlationId,
1047
+ () => runWithActorScope(() => emitOne(row))
1048
+ );
1049
+ }
1050
+ return rows.length;
1051
+ } catch (err) {
1052
+ logger.debug(
1053
+ `sweepAuditLog failed: ${err instanceof Error ? err.message : String(err)}`
1054
+ );
1055
+ return 0;
1056
+ }
1057
+ }
1058
+ async function pruneAuditLog(exec) {
1059
+ if (deleteDenied) return;
1060
+ try {
1061
+ await exec(
1062
+ `DELETE FROM ezlogs_audit_log
1063
+ WHERE id IN (
1064
+ SELECT id FROM ezlogs_audit_log
1065
+ WHERE captured_at < now() - interval '${PRUNE_AGE}'
1066
+ LIMIT ${PRUNE_BATCH})`,
1067
+ []
1068
+ );
1069
+ } catch (err) {
1070
+ logger.debug(
1071
+ `pruneAuditLog failed: ${err instanceof Error ? err.message : String(err)}`
1072
+ );
1073
+ }
1074
+ }
1075
+ function emitAuditRows(rows) {
1076
+ for (const row of rows) {
1077
+ emitOne(row);
1078
+ }
1079
+ }
1080
+ async function flushAuditLog(exec, options = {}) {
1081
+ if (!exec) return;
1082
+ const correlationId = current();
1083
+ if (!correlationId) return;
1084
+ const rows = await readAuditRows(exec, correlationId, options.since ?? null);
1085
+ await loadTableMeta(exec, rows);
1086
+ emitFresh(rows);
1087
+ const now = Date.now();
1088
+ if (now - lastPruneAt >= PRUNE_INTERVAL_MS) {
1089
+ lastPruneAt = now;
1090
+ await pruneAuditLog(exec);
1091
+ }
1092
+ if (now - lastSweepAt >= SWEEP_INTERVAL_MS) {
1093
+ lastSweepAt = now;
1094
+ await sweepAuditLog(exec);
1095
+ }
1096
+ }
1097
+ var tableMeta = /* @__PURE__ */ new Map();
1098
+ var META_RETRY_MS = 6e4;
1099
+ var metaRetryAt = 0;
1100
+ async function loadTableMeta(exec, rows) {
1101
+ if (Date.now() < metaRetryAt) return;
1102
+ const tables = [
1103
+ ...new Set(rows.map((r) => r.table_name).filter((t) => t !== "" && !t.includes(",") && !tableMeta.has(t)))
1104
+ ];
1105
+ if (tables.length === 0) return;
1106
+ const list = tables.join(",");
1107
+ try {
1108
+ const fkRows = extractRows(
1109
+ await exec(
1110
+ `SELECT cl.relname AS table_name, a.attname AS column_name, rf.relname AS ref_table
1111
+ FROM pg_constraint c
1112
+ JOIN pg_class cl ON cl.oid = c.conrelid
1113
+ JOIN pg_namespace n ON n.oid = cl.relnamespace
1114
+ JOIN pg_class rf ON rf.oid = c.confrelid
1115
+ JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = c.conkey[1]
1116
+ WHERE c.contype = 'f'
1117
+ AND n.nspname = 'public'
1118
+ AND array_length(c.conkey, 1) = 1
1119
+ AND cl.relname = ANY(string_to_array($1, ','))
1120
+ ORDER BY cl.relname, a.attnum`,
1121
+ [list]
1122
+ )
1123
+ );
1124
+ const tsRows = extractRows(
1125
+ await exec(
1126
+ `SELECT cl.relname AS table_name, a.attname AS column_name
1127
+ FROM pg_attribute a
1128
+ JOIN pg_class cl ON cl.oid = a.attrelid
1129
+ JOIN pg_namespace n ON n.oid = cl.relnamespace
1130
+ WHERE n.nspname = 'public'
1131
+ AND cl.relname = ANY(string_to_array($1, ','))
1132
+ AND a.attnum > 0
1133
+ AND NOT a.attisdropped
1134
+ AND a.atttypid = 'timestamp'::regtype`,
1135
+ [list]
1136
+ )
1137
+ );
1138
+ const fks = /* @__PURE__ */ new Map();
1139
+ for (const raw of fkRows) {
1140
+ const r = raw ?? {};
1141
+ if (typeof r.table_name !== "string" || typeof r.column_name !== "string" || typeof r.ref_table !== "string") {
1142
+ continue;
1143
+ }
1144
+ fks.set(r.table_name, [...fks.get(r.table_name) ?? [], { column: r.column_name, refTable: r.ref_table }]);
1145
+ }
1146
+ const timestamps = /* @__PURE__ */ new Map();
1147
+ for (const raw of tsRows) {
1148
+ const r = raw ?? {};
1149
+ if (typeof r.table_name !== "string" || typeof r.column_name !== "string") continue;
1150
+ timestamps.set(r.table_name, (timestamps.get(r.table_name) ?? /* @__PURE__ */ new Set()).add(r.column_name));
1151
+ }
1152
+ for (const table of tables) {
1153
+ tableMeta.set(table, { fks: fks.get(table) ?? [], naiveTimestamps: timestamps.get(table) ?? /* @__PURE__ */ new Set() });
1154
+ }
1155
+ } catch (err) {
1156
+ metaRetryAt = Date.now() + META_RETRY_MS;
1157
+ logger.debug(`table metadata lookup failed: ${err instanceof Error ? err.message : String(err)}`);
1158
+ }
1159
+ }
1160
+ function relatedResourceIds(table, row) {
1161
+ const out = [];
1162
+ for (const fk of tableMeta.get(table)?.fks ?? []) {
1163
+ const value = row[fk.column];
1164
+ if (typeof value === "string" || typeof value === "number") {
1165
+ out.push({ resource_type: fk.refTable, resource_id: String(value) });
1166
+ }
1167
+ }
1168
+ return out;
1169
+ }
1170
+ function emitFresh(rows) {
1171
+ if (rows.length === 0) return;
1172
+ const emitted = currentEmittedAuditIds();
1173
+ if (emitted === null) {
1174
+ emitAuditRows(rows);
1175
+ return;
1176
+ }
1177
+ const fresh = [];
1178
+ for (const row of rows) {
1179
+ if (row.id === "" || emitted.has(row.id)) continue;
1180
+ emitted.add(row.id);
1181
+ fresh.push(row);
1182
+ }
1183
+ emitAuditRows(fresh);
1184
+ }
1185
+ function correlationForTx(txid) {
1186
+ if (!txid) return generate();
1187
+ let id = txCorrelation.get(txid);
1188
+ if (!id) {
1189
+ if (txCorrelation.size >= 1e3) txCorrelation.clear();
1190
+ id = generate();
1191
+ txCorrelation.set(txid, id);
1192
+ }
1193
+ return id;
1194
+ }
1195
+ function isPermissionDenied(err) {
1196
+ return err?.code === "42501";
1197
+ }
1198
+ function sortById(rows) {
1199
+ return rows.sort(
1200
+ (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
1201
+ );
1202
+ }
1203
+ function emitOne(row) {
1204
+ const op = mapOp(row.op);
1205
+ if (!op) return;
1206
+ const naive = tableMeta.get(row.table_name)?.naiveTimestamps ?? null;
1207
+ const oldRow = withUtcTimestamps(coerceJsonb(row.old_row), naive);
1208
+ const newRow = withUtcTimestamps(coerceJsonb(row.new_row), naive);
1209
+ const related = row.resource_id === null ? relatedResourceIds(row.table_name, newRow ?? oldRow ?? {}) : null;
1210
+ if (op === "create" && newRow) {
1211
+ emitDbEvent({
1212
+ modelClass: row.table_name,
1213
+ operation: "create",
1214
+ resourceId: row.resource_id,
1215
+ initialAttributes: newRow,
1216
+ modelInstance: newRow,
1217
+ displayName: null,
1218
+ timestamp: row.captured_at ?? null,
1219
+ relatedResourceIds: related,
1220
+ _fromTrigger: true
1221
+ });
1222
+ return;
1223
+ }
1224
+ if (op === "update" && oldRow && newRow) {
1225
+ const changes = computeChanges(oldRow, newRow);
1226
+ if (changes.length === 0) {
1227
+ return;
1228
+ }
1229
+ emitDbEvent({
1230
+ modelClass: row.table_name,
1231
+ operation: "update",
1232
+ resourceId: row.resource_id,
1233
+ changes,
1234
+ // Prefer the post-state for the display name — that's what the
1235
+ // user just told the system to call this row.
1236
+ modelInstance: newRow,
1237
+ displayName: null,
1238
+ timestamp: row.captured_at ?? null,
1239
+ relatedResourceIds: related,
1240
+ _fromTrigger: true
1241
+ });
1242
+ return;
1243
+ }
1244
+ if (op === "destroy" && oldRow) {
1245
+ emitDbEvent({
1246
+ modelClass: row.table_name,
1247
+ operation: "destroy",
1248
+ resourceId: row.resource_id,
1249
+ initialAttributes: oldRow,
1250
+ modelInstance: oldRow,
1251
+ displayName: null,
1252
+ timestamp: row.captured_at ?? null,
1253
+ relatedResourceIds: related,
1254
+ _fromTrigger: true
1255
+ });
1256
+ return;
1257
+ }
1258
+ }
1259
+ var NAIVE_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?$/;
1260
+ function withUtcTimestamps(row, naiveColumns) {
1261
+ if (!row) return row;
1262
+ const out = {};
1263
+ for (const [key, value] of Object.entries(row)) {
1264
+ const isNaiveColumn = naiveColumns ? naiveColumns.has(key) : /(_at|At)$/.test(key);
1265
+ out[key] = isNaiveColumn && typeof value === "string" && NAIVE_TIMESTAMP.test(value) ? `${value}Z` : value;
1266
+ }
1267
+ return out;
1268
+ }
1269
+ function mapOp(op) {
1270
+ if (op === "INSERT") return "create";
1271
+ if (op === "UPDATE") return "update";
1272
+ if (op === "DELETE") return "destroy";
1273
+ return null;
1274
+ }
1275
+ function computeChanges(oldRow, newRow) {
1276
+ const out = [];
1277
+ for (const key of Object.keys(newRow)) {
1278
+ const before = oldRow[key];
1279
+ const after = newRow[key];
1280
+ if (deepEqual(before, after)) continue;
1281
+ out.push({ attribute: key, from: before, to: after });
1282
+ }
1283
+ return out;
1284
+ }
1285
+ function deepEqual(a, b) {
1286
+ if (a === b) return true;
1287
+ if (a === null || b === null) return false;
1288
+ if (typeof a !== typeof b) return false;
1289
+ if (typeof a !== "object") return false;
1290
+ try {
1291
+ return stableStringify(a) === stableStringify(b);
1292
+ } catch {
1293
+ return false;
1294
+ }
1295
+ }
1296
+ function stableStringify(value) {
1297
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
1298
+ if (Array.isArray(value)) {
1299
+ return "[" + value.map((v) => stableStringify(v)).join(",") + "]";
1300
+ }
1301
+ const entries = Object.keys(value).sort().map((k) => JSON.stringify(k) + ":" + stableStringify(value[k]));
1302
+ return "{" + entries.join(",") + "}";
1303
+ }
1304
+ function extractRows(result) {
1305
+ if (!result) return [];
1306
+ if (Array.isArray(result)) return result;
1307
+ if (typeof result === "object" && Array.isArray(result.rows)) {
1308
+ return result.rows;
1309
+ }
1310
+ return [];
1311
+ }
1312
+ function toDate(value) {
1313
+ if (value == null) return null;
1314
+ const d = value instanceof Date ? value : new Date(String(value));
1315
+ return Number.isNaN(d.getTime()) ? null : d;
1316
+ }
1317
+ function normalizeAuditRow(raw) {
1318
+ const r = raw ?? {};
1319
+ return {
1320
+ id: r.id == null ? "" : String(r.id),
1321
+ table_name: String(r.table_name ?? ""),
1322
+ op: r.op,
1323
+ old_row: r.old_row ?? null,
1324
+ new_row: r.new_row ?? null,
1325
+ resource_id: r.resource_id == null ? null : String(r.resource_id),
1326
+ correlation_id: r.correlation_id == null ? null : String(r.correlation_id),
1327
+ txid: r.txid == null ? null : String(r.txid),
1328
+ captured_at: toDate(r.captured_at)
1329
+ };
1330
+ }
1331
+ function coerceJsonb(value) {
1332
+ if (value === null || value === void 0) return null;
1333
+ if (typeof value === "string") {
1334
+ try {
1335
+ const parsed = JSON.parse(value);
1336
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
1337
+ } catch {
1338
+ return null;
1339
+ }
1340
+ }
1341
+ if (typeof value === "object" && !Array.isArray(value)) return value;
1342
+ return null;
1343
+ }
1344
+
511
1345
  // src/jobs/shared.ts
512
1346
  var CORRELATION_PAYLOAD_KEY = "ezlogs_correlation_id";
513
1347
  function emitJobEvent(input) {
@@ -519,7 +1353,8 @@ function emitJobEvent(input) {
519
1353
  job_class: input.jobClass,
520
1354
  job_id: input.jobId ?? null,
521
1355
  queue: input.queue ?? null,
522
- retry_count: input.retryCount ?? null
1356
+ retry_count: input.retryCount ?? null,
1357
+ arguments: jobArguments(input.payload)
523
1358
  });
524
1359
  const event = build({
525
1360
  source_type: "background_job",
@@ -534,9 +1369,31 @@ function emitJobEvent(input) {
534
1369
  });
535
1370
  pushEvent(event);
536
1371
  } catch (error) {
537
- logger.debug(`job emit failed: ${describeError(error)}`);
1372
+ logger.debug(`job emit failed: ${describeError2(error)}`);
1373
+ }
1374
+ }
1375
+ var JOB_FLUSH_SKEW_MS = 500;
1376
+ async function flushJobAuditLog(startedAt) {
1377
+ try {
1378
+ await flushAuditLog(configuration().databaseReader, {
1379
+ since: new Date(startedAt.getTime() - JOB_FLUSH_SKEW_MS)
1380
+ });
1381
+ } catch (error) {
1382
+ logger.debug(`job audit flush failed: ${describeError2(error)}`);
538
1383
  }
539
1384
  }
1385
+ function jobArguments(payload) {
1386
+ if (payload === null || payload === void 0) return null;
1387
+ const patterns = configuration().excludedGraphqlVariableKeys;
1388
+ if (Array.isArray(payload)) return payload.length === 0 ? null : sanitizeArgs(payload, patterns);
1389
+ if (typeof payload === "object" && Object.getPrototypeOf(payload) === Object.prototype) {
1390
+ const rest = { ...payload };
1391
+ delete rest[CORRELATION_PAYLOAD_KEY];
1392
+ if (Object.keys(rest).length === 0) return null;
1393
+ return sanitizeArgs([rest], patterns)[0];
1394
+ }
1395
+ return sanitizeArgs([payload], patterns);
1396
+ }
540
1397
  function extractCorrelationFromPayload(payload, key = CORRELATION_PAYLOAD_KEY) {
541
1398
  if (payload === null || typeof payload !== "object") return null;
542
1399
  const value = payload[key];
@@ -550,7 +1407,7 @@ function compactJobSourceData(data) {
550
1407
  }
551
1408
  return out;
552
1409
  }
553
- function describeError(error) {
1410
+ function describeError2(error) {
554
1411
  if (error instanceof Error) return `${error.name}: ${error.message}`;
555
1412
  return String(error);
556
1413
  }
@@ -569,6 +1426,7 @@ function ezlogsInngestMiddleware() {
569
1426
  const runId = args.ctx?.runId ?? null;
570
1427
  const attempt = typeof args.ctx?.attempt === "number" ? args.ctx.attempt : 0;
571
1428
  const eventName = args.ctx?.event?.name ?? null;
1429
+ const eventData = args.ctx?.event?.data;
572
1430
  const correlationId = extractCorrelationFromPayload(args.ctx?.event?.data) ?? generate();
573
1431
  const startedAt = /* @__PURE__ */ new Date();
574
1432
  const startMs = startedAt.getTime();
@@ -590,10 +1448,11 @@ function ezlogsInngestMiddleware() {
590
1448
  outcome,
591
1449
  errorMessage,
592
1450
  durationMs: Date.now() - startMs,
593
- startedAt
1451
+ startedAt,
1452
+ payload: eventData
594
1453
  });
595
1454
  } catch (error) {
596
- logger.debug(`inngest capture failed: ${describeError2(error)}`);
1455
+ logger.debug(`inngest capture failed: ${describeError3(error)}`);
597
1456
  }
598
1457
  }
599
1458
  };
@@ -621,7 +1480,7 @@ function ezlogsInngestMiddleware() {
621
1480
  payload.data = data;
622
1481
  }
623
1482
  } catch (error) {
624
- logger.debug(`inngest send-stamp failed: ${describeError2(error)}`);
1483
+ logger.debug(`inngest send-stamp failed: ${describeError3(error)}`);
625
1484
  }
626
1485
  }
627
1486
  };
@@ -632,7 +1491,14 @@ function ezlogsInngestMiddleware() {
632
1491
  }
633
1492
  async function runInsideInngestCorrelation(event, callback) {
634
1493
  const id = extractCorrelationFromPayload(event?.data) ?? generate();
635
- return runWithCorrelation(id, callback);
1494
+ const startedAt = /* @__PURE__ */ new Date();
1495
+ return runWithCorrelation(id, async () => {
1496
+ try {
1497
+ return await callback();
1498
+ } finally {
1499
+ await flushJobAuditLog(startedAt);
1500
+ }
1501
+ });
636
1502
  }
637
1503
  function formatError(error) {
638
1504
  if (error instanceof Error) {
@@ -644,7 +1510,7 @@ function formatError(error) {
644
1510
  }
645
1511
  return String(error);
646
1512
  }
647
- function describeError2(error) {
1513
+ function describeError3(error) {
648
1514
  if (error instanceof Error) return `${error.name}: ${error.message}`;
649
1515
  return String(error);
650
1516
  }