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.
- package/README.md +106 -11
- package/bin/install-triggers.cjs +49 -11
- package/dist/actors/index.d.cts +1 -1
- package/dist/actors/index.d.ts +1 -1
- package/dist/{configuration-3Pei_XZ_.d.cts → configuration-OHLNivON.d.cts} +11 -20
- package/dist/{configuration-3Pei_XZ_.d.ts → configuration-OHLNivON.d.ts} +11 -20
- package/dist/db/drizzle.cjs +154 -18
- package/dist/db/drizzle.js +154 -18
- package/dist/db/prisma.cjs +242 -45
- package/dist/db/prisma.d.cts +39 -1
- package/dist/db/prisma.d.ts +39 -1
- package/dist/db/prisma.js +241 -46
- package/dist/db/supabase.cjs +154 -18
- package/dist/db/supabase.js +154 -18
- package/dist/index.cjs +761 -245
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +761 -245
- package/dist/jobs/bullmq.cjs +973 -16
- package/dist/jobs/bullmq.d.cts +8 -3
- package/dist/jobs/bullmq.d.ts +8 -3
- package/dist/jobs/bullmq.js +973 -16
- package/dist/jobs/inngest.cjs +880 -14
- package/dist/jobs/inngest.d.cts +7 -5
- package/dist/jobs/inngest.d.ts +7 -5
- package/dist/jobs/inngest.js +880 -14
- package/dist/jobs/supabase-queues.cjs +878 -16
- package/dist/jobs/supabase-queues.js +878 -16
- package/dist/jobs/trigger.cjs +914 -42
- package/dist/jobs/trigger.js +914 -42
- package/dist/jobs/upstash-workflow.cjs +914 -14
- package/dist/jobs/upstash-workflow.d.cts +16 -2
- package/dist/jobs/upstash-workflow.d.ts +16 -2
- package/dist/jobs/upstash-workflow.js +914 -15
- package/dist/triggers/index.cjs +405 -76
- package/dist/triggers/index.d.cts +36 -41
- package/dist/triggers/index.d.ts +36 -41
- package/dist/triggers/index.js +404 -74
- package/package.json +5 -1
- package/sql/postgres/00_install.sql +244 -21
package/dist/db/prisma.cjs
CHANGED
|
@@ -122,6 +122,14 @@ function createScopedStorage(key = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:def
|
|
|
122
122
|
};
|
|
123
123
|
}
|
|
124
124
|
|
|
125
|
+
// src/correlation.ts
|
|
126
|
+
var storage = createScopedStorage(
|
|
127
|
+
/* @__PURE__ */ Symbol.for("ezlogs-nextjs:correlation-storage")
|
|
128
|
+
);
|
|
129
|
+
function current() {
|
|
130
|
+
return storage.read();
|
|
131
|
+
}
|
|
132
|
+
|
|
125
133
|
// src/configuration.ts
|
|
126
134
|
var DEFAULT_EXCLUDED_PATHS = Object.freeze([
|
|
127
135
|
// Next.js / Vercel infrastructure noise
|
|
@@ -191,7 +199,6 @@ var Configuration = class {
|
|
|
191
199
|
displayNameFor = {};
|
|
192
200
|
isServerActionError = null;
|
|
193
201
|
databaseReader = null;
|
|
194
|
-
databaseSnapshotMode = false;
|
|
195
202
|
databaseUrl = null;
|
|
196
203
|
/**
|
|
197
204
|
* Tables that have the `ezlogs_audit` trigger attached. Detected once
|
|
@@ -243,9 +250,6 @@ var Configuration = class {
|
|
|
243
250
|
if (options.databaseReader !== void 0) {
|
|
244
251
|
this.databaseReader = options.databaseReader;
|
|
245
252
|
}
|
|
246
|
-
if (options.databaseSnapshotMode !== void 0) {
|
|
247
|
-
this.databaseSnapshotMode = options.databaseSnapshotMode;
|
|
248
|
-
}
|
|
249
253
|
if (options.databaseUrl !== void 0) {
|
|
250
254
|
this.databaseUrl = options.databaseUrl;
|
|
251
255
|
}
|
|
@@ -488,14 +492,6 @@ function describe2(error) {
|
|
|
488
492
|
return String(error);
|
|
489
493
|
}
|
|
490
494
|
|
|
491
|
-
// src/correlation.ts
|
|
492
|
-
var storage = createScopedStorage(
|
|
493
|
-
/* @__PURE__ */ Symbol.for("ezlogs-nextjs:correlation-storage")
|
|
494
|
-
);
|
|
495
|
-
function current() {
|
|
496
|
-
return storage.read();
|
|
497
|
-
}
|
|
498
|
-
|
|
499
495
|
// src/actor.ts
|
|
500
496
|
var storage2 = createScopedStorage(
|
|
501
497
|
/* @__PURE__ */ Symbol.for("ezlogs-nextjs:actor-storage")
|
|
@@ -503,6 +499,57 @@ var storage2 = createScopedStorage(
|
|
|
503
499
|
function getCurrentActor() {
|
|
504
500
|
return storage2.read();
|
|
505
501
|
}
|
|
502
|
+
var SENSITIVE_WORD_PATTERNS = Object.freeze([
|
|
503
|
+
"pin",
|
|
504
|
+
"otp",
|
|
505
|
+
"totp",
|
|
506
|
+
"iban",
|
|
507
|
+
"mfa",
|
|
508
|
+
"passphrase"
|
|
509
|
+
]);
|
|
510
|
+
function snakeLower(key) {
|
|
511
|
+
return key.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
|
|
512
|
+
}
|
|
513
|
+
function matchesSensitiveKey(key, substringPatterns) {
|
|
514
|
+
const lower = key.toLowerCase();
|
|
515
|
+
const snake = snakeLower(key);
|
|
516
|
+
if (substringPatterns.some((p) => lower.includes(p) || snake.includes(p))) {
|
|
517
|
+
return true;
|
|
518
|
+
}
|
|
519
|
+
const words = snake.split(/[^a-z0-9]+/);
|
|
520
|
+
return SENSITIVE_WORD_PATTERNS.some((w) => words.includes(w));
|
|
521
|
+
}
|
|
522
|
+
function passesLuhn(digits) {
|
|
523
|
+
let sum = 0;
|
|
524
|
+
for (let i = 0; i < digits.length; i += 1) {
|
|
525
|
+
let d = Number(digits[digits.length - 1 - i]);
|
|
526
|
+
if (i % 2 === 1) {
|
|
527
|
+
d *= 2;
|
|
528
|
+
if (d > 9) d -= 9;
|
|
529
|
+
}
|
|
530
|
+
sum += d;
|
|
531
|
+
}
|
|
532
|
+
return sum % 10 === 0;
|
|
533
|
+
}
|
|
534
|
+
var SECRET_TEXT_PATTERNS = [
|
|
535
|
+
/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,
|
|
536
|
+
/\beyJ[\w-]+\.[\w-]+\.[\w-]+/g,
|
|
537
|
+
/\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]+/g,
|
|
538
|
+
/\bsk-[A-Za-z0-9_-]{16,}/g,
|
|
539
|
+
/\bgh[pousr]_[A-Za-z0-9]{20,}/g,
|
|
540
|
+
/\bxox[abposr]-[A-Za-z0-9-]+/g,
|
|
541
|
+
/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g
|
|
542
|
+
];
|
|
543
|
+
var EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;
|
|
544
|
+
function scrubSecretsInText(text, options = {}) {
|
|
545
|
+
let out = text;
|
|
546
|
+
for (const pattern of SECRET_TEXT_PATTERNS) out = out.replace(pattern, "[FILTERED]");
|
|
547
|
+
out = out.replace(/\b(Bearer|Basic)\s+[\w.~+/=-]+/gi, "$1 [FILTERED]").replace(/\b\d(?:[ -]?\d){12,18}\b/g, (match) => {
|
|
548
|
+
const digits = match.replace(/[ -]/g, "");
|
|
549
|
+
return (digits.length === 15 || digits.length === 16) && passesLuhn(digits) ? "[FILTERED]" : match;
|
|
550
|
+
});
|
|
551
|
+
return options.emails ? out.replace(EMAIL, "[FILTERED]") : out;
|
|
552
|
+
}
|
|
506
553
|
|
|
507
554
|
// src/db/shared.ts
|
|
508
555
|
var IGNORED_ATTRIBUTES = Object.freeze([
|
|
@@ -511,8 +558,6 @@ var IGNORED_ATTRIBUTES = Object.freeze([
|
|
|
511
558
|
"created_at",
|
|
512
559
|
"updatedAt",
|
|
513
560
|
"updated_at",
|
|
514
|
-
"deletedAt",
|
|
515
|
-
"deleted_at",
|
|
516
561
|
// Auth.js / NextAuth standard columns
|
|
517
562
|
"emailVerified",
|
|
518
563
|
"expires"
|
|
@@ -535,7 +580,19 @@ var DB_SENSITIVE_PATTERNS = Object.freeze([
|
|
|
535
580
|
"salt",
|
|
536
581
|
"digest",
|
|
537
582
|
"signature",
|
|
538
|
-
"hmac"
|
|
583
|
+
"hmac",
|
|
584
|
+
// 0.2.0 additions. `credential` / `passwd` / `apikey` were already in
|
|
585
|
+
// the HTTP list; `passcode` / `card_number` / `cardnumber` / `cvv` /
|
|
586
|
+
// `cvc` are new. Whole-word `pin` / `otp` / `totp` / `iban` come from
|
|
587
|
+
// SENSITIVE_WORD_PATTERNS. The SQL trigger mirrors this list.
|
|
588
|
+
"credential",
|
|
589
|
+
"passwd",
|
|
590
|
+
"passcode",
|
|
591
|
+
"apikey",
|
|
592
|
+
"card_number",
|
|
593
|
+
"cardnumber",
|
|
594
|
+
"cvv",
|
|
595
|
+
"cvc"
|
|
539
596
|
]);
|
|
540
597
|
function emitDbEvent(input) {
|
|
541
598
|
try {
|
|
@@ -544,14 +601,17 @@ function emitDbEvent(input) {
|
|
|
544
601
|
if (config.allExcludedTables().includes(input.modelClass)) return;
|
|
545
602
|
if (config.databaseReader && !input._fromTrigger) {
|
|
546
603
|
const tracked = config.triggerTrackedTables;
|
|
547
|
-
if (tracked === null || tracked.has(input.modelClass)) return;
|
|
604
|
+
if (tracked === null || tracked.has(input.table ?? input.modelClass)) return;
|
|
548
605
|
}
|
|
549
606
|
if (input.operation === "update") {
|
|
550
607
|
const meaningful = input.changes ? filterMeaningfulChanges(input.changes) : [];
|
|
551
608
|
if (meaningful.length === 0) return;
|
|
552
609
|
}
|
|
553
610
|
const resourceIdStr = input.resourceId === null || input.resourceId === void 0 ? null : String(input.resourceId);
|
|
554
|
-
const
|
|
611
|
+
const related = resourceIdStr === null ? input.relatedResourceIds ?? [] : [];
|
|
612
|
+
const context = buildContext(
|
|
613
|
+
related.length > 0 ? { ...input, displayName: null, modelInstance: null } : input
|
|
614
|
+
);
|
|
555
615
|
const event = build({
|
|
556
616
|
source_type: "database_callback",
|
|
557
617
|
source_data: {
|
|
@@ -560,9 +620,10 @@ function emitDbEvent(input) {
|
|
|
560
620
|
},
|
|
561
621
|
outcome: "success",
|
|
562
622
|
correlation_id: current(),
|
|
563
|
-
resource_ids: resourceIdStr === null ? [] : [{ resource_type: input.modelClass, resource_id: resourceIdStr }],
|
|
623
|
+
resource_ids: resourceIdStr === null ? [...related] : [{ resource_type: input.modelClass, resource_id: resourceIdStr }],
|
|
564
624
|
context,
|
|
565
|
-
duration_ms: null
|
|
625
|
+
duration_ms: null,
|
|
626
|
+
timestamp: input.timestamp ?? null
|
|
566
627
|
});
|
|
567
628
|
pushEvent(event);
|
|
568
629
|
} catch (error) {
|
|
@@ -606,7 +667,7 @@ function filterMeaningfulAttributes(attrs) {
|
|
|
606
667
|
return Object.keys(out).length === 0 ? null : out;
|
|
607
668
|
}
|
|
608
669
|
function filterMeaningfulChanges(changes) {
|
|
609
|
-
return changes.filter((c) => {
|
|
670
|
+
return flattenNestedChanges(changes).filter((c) => {
|
|
610
671
|
if (!isMeaningfulAttribute(c.attribute)) return false;
|
|
611
672
|
if (!isScalar(c.to)) return false;
|
|
612
673
|
if (c.from === void 0) return true;
|
|
@@ -614,14 +675,67 @@ function filterMeaningfulChanges(changes) {
|
|
|
614
675
|
return valuesActuallyChanged(c.from, c.to);
|
|
615
676
|
});
|
|
616
677
|
}
|
|
678
|
+
var MAX_NESTED_DEPTH = 3;
|
|
679
|
+
var MAX_NESTED_LEAVES = 20;
|
|
680
|
+
var MAX_UNKNOWN_FROM_LEAVES = 5;
|
|
681
|
+
function flattenNestedChanges(changes) {
|
|
682
|
+
if (!changes.some((c) => isPlainRecord(c.to) || isPlainRecord(c.from))) return changes;
|
|
683
|
+
const out = [];
|
|
684
|
+
for (const c of changes) {
|
|
685
|
+
if (!isPlainRecord(c.to) && !isPlainRecord(c.from)) {
|
|
686
|
+
out.push(c);
|
|
687
|
+
continue;
|
|
688
|
+
}
|
|
689
|
+
if (!isMeaningfulAttribute(c.attribute)) continue;
|
|
690
|
+
const leaves = [];
|
|
691
|
+
collectLeafChanges(c.attribute, c.from, c.to, 1, leaves);
|
|
692
|
+
const cap = c.from === void 0 ? MAX_UNKNOWN_FROM_LEAVES : MAX_NESTED_LEAVES;
|
|
693
|
+
out.push(...leaves.slice(0, cap).map(scrubLeaf));
|
|
694
|
+
}
|
|
695
|
+
return out;
|
|
696
|
+
}
|
|
697
|
+
function collectLeafChanges(path, from, to, depth, out) {
|
|
698
|
+
if (out.length > MAX_NESTED_LEAVES) return;
|
|
699
|
+
const fromObj = isPlainRecord(from);
|
|
700
|
+
const toObj = isPlainRecord(to);
|
|
701
|
+
if ((fromObj || toObj) && depth <= MAX_NESTED_DEPTH && (fromObj || from == null) && (toObj || to == null)) {
|
|
702
|
+
const f = fromObj ? from : {};
|
|
703
|
+
const t = toObj ? to : {};
|
|
704
|
+
for (const key of /* @__PURE__ */ new Set([...Object.keys(f), ...Object.keys(t)])) {
|
|
705
|
+
const before = from === void 0 ? void 0 : f[key] ?? null;
|
|
706
|
+
collectLeafChanges(`${path}.${key}`, before, t[key] ?? null, depth + 1, out);
|
|
707
|
+
}
|
|
708
|
+
return;
|
|
709
|
+
}
|
|
710
|
+
if (from !== void 0 && sameJson(from, to)) return;
|
|
711
|
+
out.push(from === void 0 ? { attribute: path, to } : { attribute: path, from, to });
|
|
712
|
+
}
|
|
713
|
+
function scrubLeaf(change) {
|
|
714
|
+
const scrub = (v) => typeof v === "string" ? scrubSecretsInText(v) : v;
|
|
715
|
+
const out = { attribute: change.attribute, to: scrub(change.to) };
|
|
716
|
+
if (change.from !== void 0) out.from = scrub(change.from);
|
|
717
|
+
return out;
|
|
718
|
+
}
|
|
719
|
+
function isPlainRecord(value) {
|
|
720
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
721
|
+
const proto = Object.getPrototypeOf(value);
|
|
722
|
+
return proto === Object.prototype || proto === null;
|
|
723
|
+
}
|
|
724
|
+
function sameJson(a, b) {
|
|
725
|
+
if (a === b) return true;
|
|
726
|
+
try {
|
|
727
|
+
return JSON.stringify(a) === JSON.stringify(b);
|
|
728
|
+
} catch {
|
|
729
|
+
return false;
|
|
730
|
+
}
|
|
731
|
+
}
|
|
617
732
|
function isMeaningfulAttribute(name) {
|
|
618
733
|
if (IGNORED_ATTRIBUTES.includes(name)) return false;
|
|
619
734
|
if (isDbSensitive(name)) return false;
|
|
620
735
|
return true;
|
|
621
736
|
}
|
|
622
737
|
function isDbSensitive(name) {
|
|
623
|
-
|
|
624
|
-
return DB_SENSITIVE_PATTERNS.some((p) => lower.includes(p));
|
|
738
|
+
return matchesSensitiveKey(name, DB_SENSITIVE_PATTERNS);
|
|
625
739
|
}
|
|
626
740
|
function isScalar(value) {
|
|
627
741
|
if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint" || value instanceof Date) {
|
|
@@ -652,22 +766,44 @@ function isPrismaDecimal(value) {
|
|
|
652
766
|
const obj = value;
|
|
653
767
|
return typeof obj.toString === "function" && typeof obj.toFixed === "function" && "d" in obj && "e" in obj && "s" in obj;
|
|
654
768
|
}
|
|
769
|
+
var DISPLAY_NAME_COLUMNS = ["name", "title", "number", "label"];
|
|
770
|
+
var MAX_DISPLAY_NAME_LENGTH = 120;
|
|
655
771
|
function resolveDisplayName(modelClass, instance) {
|
|
656
772
|
try {
|
|
657
773
|
const config = configuration();
|
|
658
774
|
const resolver = config.displayNameFor[modelClass];
|
|
659
775
|
const resolved = applyResolver(resolver, instance);
|
|
660
776
|
if (resolved !== null) return resolved;
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
if (
|
|
664
|
-
|
|
777
|
+
const columns = /* @__PURE__ */ new Map();
|
|
778
|
+
for (const key of Object.keys(instance)) {
|
|
779
|
+
if (isDbSensitive(key)) continue;
|
|
780
|
+
const norm = key.toLowerCase().replace(/_/g, "");
|
|
781
|
+
if (!columns.has(norm)) columns.set(norm, instance[key]);
|
|
782
|
+
}
|
|
783
|
+
const text = (norm) => {
|
|
784
|
+
const value = columns.get(norm);
|
|
785
|
+
if (typeof value !== "string" && typeof value !== "number" && typeof value !== "bigint") {
|
|
786
|
+
return null;
|
|
665
787
|
}
|
|
788
|
+
const str = String(value).trim();
|
|
789
|
+
return str.length > 0 ? str.slice(0, MAX_DISPLAY_NAME_LENGTH) : null;
|
|
790
|
+
};
|
|
791
|
+
for (const column of DISPLAY_NAME_COLUMNS) {
|
|
792
|
+
const value = text(column);
|
|
793
|
+
if (value !== null) return value;
|
|
666
794
|
}
|
|
795
|
+
return text(`${singularNorm(modelClass)}number`);
|
|
667
796
|
} catch {
|
|
668
797
|
}
|
|
669
798
|
return null;
|
|
670
799
|
}
|
|
800
|
+
function singularNorm(modelClass) {
|
|
801
|
+
const norm = modelClass.toLowerCase().replace(/_/g, "");
|
|
802
|
+
if (norm.endsWith("ies")) return norm.slice(0, -3) + "y";
|
|
803
|
+
if (/(ss|us|is)$/.test(norm)) return norm;
|
|
804
|
+
if (/(xes|ches|shes|sses)$/.test(norm)) return norm.slice(0, -2);
|
|
805
|
+
return norm.endsWith("s") ? norm.slice(0, -1) : norm;
|
|
806
|
+
}
|
|
671
807
|
function applyResolver(resolver, instance) {
|
|
672
808
|
if (typeof resolver === "string") {
|
|
673
809
|
const value = instance[resolver];
|
|
@@ -715,6 +851,9 @@ var OPERATION_TO_DB_OPERATION = {
|
|
|
715
851
|
deleteMany: "destroy"
|
|
716
852
|
};
|
|
717
853
|
function ezlogsPrisma() {
|
|
854
|
+
return (client) => client.$extends(buildPrismaExtension(client));
|
|
855
|
+
}
|
|
856
|
+
function buildPrismaExtension(client, schemaClient = client) {
|
|
718
857
|
return {
|
|
719
858
|
name: "ezlogs",
|
|
720
859
|
query: {
|
|
@@ -723,24 +862,83 @@ function ezlogsPrisma() {
|
|
|
723
862
|
if (!CAPTURED_OPERATIONS.has(ctx.operation)) {
|
|
724
863
|
return ctx.query(ctx.args);
|
|
725
864
|
}
|
|
726
|
-
const result = await
|
|
865
|
+
const result = await runTagged(client, ctx);
|
|
727
866
|
try {
|
|
728
|
-
recordPrismaOperation(ctx, result);
|
|
867
|
+
recordPrismaOperation(ctx, result, tableNameFor(schemaClient, ctx.model));
|
|
729
868
|
} catch (error) {
|
|
730
869
|
logger.debug(`prisma capture failed: ${describeError2(error)}`);
|
|
731
870
|
}
|
|
732
871
|
return result;
|
|
733
872
|
}
|
|
873
|
+
},
|
|
874
|
+
// Raw writes (`$executeRaw\`UPDATE …\``) aren't model operations.
|
|
875
|
+
async $allOperations(ctx) {
|
|
876
|
+
if (ctx.operation !== "$executeRaw" && ctx.operation !== "$executeRawUnsafe") {
|
|
877
|
+
return ctx.query(ctx.args);
|
|
878
|
+
}
|
|
879
|
+
return runTagged(client, ctx);
|
|
734
880
|
}
|
|
735
881
|
}
|
|
736
882
|
};
|
|
737
883
|
}
|
|
738
|
-
|
|
884
|
+
var SET_CORRELATION_SQL = "SELECT set_config('ezlogs.correlation_id', $1, TRUE)";
|
|
885
|
+
async function runTagged(client, ctx) {
|
|
886
|
+
if (!shouldTag(client, ctx)) return ctx.query(ctx.args);
|
|
887
|
+
try {
|
|
888
|
+
const results = await client.$transaction([
|
|
889
|
+
client.$executeRawUnsafe(SET_CORRELATION_SQL, current()),
|
|
890
|
+
ctx.query(ctx.args)
|
|
891
|
+
]);
|
|
892
|
+
return results[1];
|
|
893
|
+
} catch (error) {
|
|
894
|
+
if (!isTransactionUnsupported(error)) throw error;
|
|
895
|
+
taggingDisabled.add(client);
|
|
896
|
+
logger.warn(
|
|
897
|
+
`this Prisma client can't run transactions, so DB writes won't be linked to their request (they still show up as their own actions): ${describeError2(error)}`
|
|
898
|
+
);
|
|
899
|
+
return ctx.query(ctx.args);
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
var taggingDisabled = /* @__PURE__ */ new WeakSet();
|
|
903
|
+
function _resetPrismaTaggingForTests() {
|
|
904
|
+
taggingDisabled = /* @__PURE__ */ new WeakSet();
|
|
905
|
+
}
|
|
906
|
+
function shouldTag(client, ctx) {
|
|
907
|
+
if (!client || taggingDisabled.has(client)) return false;
|
|
908
|
+
if (configuration().databaseReader == null) return false;
|
|
909
|
+
if (!isPostgresClient(client)) return false;
|
|
910
|
+
if (typeof client.$transaction !== "function" || typeof client.$executeRawUnsafe !== "function") {
|
|
911
|
+
return false;
|
|
912
|
+
}
|
|
913
|
+
if (!current()) return false;
|
|
914
|
+
const params = ctx.__internalParams;
|
|
915
|
+
return params != null && !params.transaction;
|
|
916
|
+
}
|
|
917
|
+
function isPostgresClient(client) {
|
|
918
|
+
const c = client;
|
|
919
|
+
const provider = c._activeProvider ?? c._engineConfig?.activeProvider;
|
|
920
|
+
if (typeof provider !== "string") return true;
|
|
921
|
+
return provider === "postgresql" || provider === "postgres";
|
|
922
|
+
}
|
|
923
|
+
function isTransactionUnsupported(error) {
|
|
924
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
925
|
+
return /transaction/i.test(message) && /not (?:be )?supported|unsupported|not available/i.test(message);
|
|
926
|
+
}
|
|
927
|
+
function tableNameFor(schemaClient, model) {
|
|
928
|
+
try {
|
|
929
|
+
const dbName = schemaClient?._runtimeDataModel?.models?.[model]?.dbName;
|
|
930
|
+
return typeof dbName === "string" && dbName.length > 0 ? dbName : model;
|
|
931
|
+
} catch {
|
|
932
|
+
return model;
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
function recordPrismaOperation(ctx, result, table) {
|
|
739
936
|
const dbOperation = OPERATION_TO_DB_OPERATION[ctx.operation];
|
|
740
937
|
if (!dbOperation) return;
|
|
741
938
|
if (isBatchResult(result)) {
|
|
742
939
|
emitDbEvent({
|
|
743
940
|
modelClass: ctx.model,
|
|
941
|
+
table,
|
|
744
942
|
operation: dbOperation,
|
|
745
943
|
resourceId: null,
|
|
746
944
|
// For batch updates we still capture the `args.data` shape so
|
|
@@ -757,16 +955,17 @@ function recordPrismaOperation(ctx, result) {
|
|
|
757
955
|
}
|
|
758
956
|
if (Array.isArray(result)) {
|
|
759
957
|
for (const row of result) {
|
|
760
|
-
emitSingleRowEvent(ctx, dbOperation, row);
|
|
958
|
+
emitSingleRowEvent(ctx, dbOperation, row, table);
|
|
761
959
|
}
|
|
762
960
|
return;
|
|
763
961
|
}
|
|
764
|
-
emitSingleRowEvent(ctx, dbOperation, result);
|
|
962
|
+
emitSingleRowEvent(ctx, dbOperation, result, table);
|
|
765
963
|
}
|
|
766
|
-
function emitSingleRowEvent(ctx, dbOperation, row) {
|
|
964
|
+
function emitSingleRowEvent(ctx, dbOperation, row, table) {
|
|
767
965
|
if (!isPlainObject2(row)) {
|
|
768
966
|
emitDbEvent({
|
|
769
967
|
modelClass: ctx.model,
|
|
968
|
+
table,
|
|
770
969
|
operation: dbOperation,
|
|
771
970
|
resourceId: null
|
|
772
971
|
});
|
|
@@ -778,9 +977,13 @@ function emitSingleRowEvent(ctx, dbOperation, row) {
|
|
|
778
977
|
if (dbOperation === "create") {
|
|
779
978
|
emitDbEvent({
|
|
780
979
|
modelClass: ctx.model,
|
|
980
|
+
table,
|
|
781
981
|
operation: "create",
|
|
782
982
|
resourceId,
|
|
783
|
-
initialAttributes:
|
|
983
|
+
initialAttributes: {
|
|
984
|
+
...isPlainObject2(ctx.args.data) ? ctx.args.data : {},
|
|
985
|
+
...rowObj
|
|
986
|
+
},
|
|
784
987
|
displayName,
|
|
785
988
|
modelInstance: rowObj
|
|
786
989
|
});
|
|
@@ -789,6 +992,7 @@ function emitSingleRowEvent(ctx, dbOperation, row) {
|
|
|
789
992
|
if (dbOperation === "update") {
|
|
790
993
|
emitDbEvent({
|
|
791
994
|
modelClass: ctx.model,
|
|
995
|
+
table,
|
|
792
996
|
operation: "update",
|
|
793
997
|
resourceId,
|
|
794
998
|
changes: extractUpdateChangesFromArgs(ctx, rowObj),
|
|
@@ -799,34 +1003,25 @@ function emitSingleRowEvent(ctx, dbOperation, row) {
|
|
|
799
1003
|
}
|
|
800
1004
|
emitDbEvent({
|
|
801
1005
|
modelClass: ctx.model,
|
|
1006
|
+
table,
|
|
802
1007
|
operation: "destroy",
|
|
803
1008
|
resourceId,
|
|
1009
|
+
initialAttributes: rowObj,
|
|
804
1010
|
displayName,
|
|
805
1011
|
modelInstance: rowObj
|
|
806
1012
|
});
|
|
807
1013
|
}
|
|
808
|
-
function extractCreateAttributes(ctx, resultRow) {
|
|
809
|
-
if (isPlainObject2(ctx.args.data)) {
|
|
810
|
-
return ctx.args.data;
|
|
811
|
-
}
|
|
812
|
-
if (ctx.operation === "upsert" && isPlainObject2(ctx.args.create)) {
|
|
813
|
-
return ctx.args.create;
|
|
814
|
-
}
|
|
815
|
-
return resultRow;
|
|
816
|
-
}
|
|
817
1014
|
function extractUpdateChangesFromArgs(ctx, resultRow) {
|
|
818
1015
|
const data = isPlainObject2(ctx.args.data) ? ctx.args.data : ctx.operation === "upsert" && isPlainObject2(ctx.args.update) ? ctx.args.update : null;
|
|
819
1016
|
if (!data) return [];
|
|
820
1017
|
return Object.keys(data).map((attribute) => ({
|
|
821
1018
|
attribute,
|
|
822
|
-
from: null,
|
|
823
1019
|
to: resultRow[attribute] ?? data[attribute]
|
|
824
1020
|
}));
|
|
825
1021
|
}
|
|
826
1022
|
function extractChangesFromUpdateData(data) {
|
|
827
1023
|
return Object.keys(data).map((attribute) => ({
|
|
828
1024
|
attribute,
|
|
829
|
-
from: null,
|
|
830
1025
|
to: data[attribute]
|
|
831
1026
|
}));
|
|
832
1027
|
}
|
|
@@ -923,7 +1118,7 @@ function applyEzlogsExtension(prisma) {
|
|
|
923
1118
|
return prisma;
|
|
924
1119
|
}
|
|
925
1120
|
try {
|
|
926
|
-
return client.$extends(
|
|
1121
|
+
return client.$extends(buildPrismaExtension(null, prisma));
|
|
927
1122
|
} catch (error) {
|
|
928
1123
|
logger.debug(`patchPrismaClient: $extends failed: ${describeError2(error)}`);
|
|
929
1124
|
return prisma;
|
|
@@ -1016,6 +1211,8 @@ function isLikelyModelDelegate(value) {
|
|
|
1016
1211
|
return typeof candidate.create === "function" && typeof candidate.findMany === "function";
|
|
1017
1212
|
}
|
|
1018
1213
|
|
|
1214
|
+
exports._resetPrismaTaggingForTests = _resetPrismaTaggingForTests;
|
|
1215
|
+
exports.buildPrismaExtension = buildPrismaExtension;
|
|
1019
1216
|
exports.ezlogsPrisma = ezlogsPrisma;
|
|
1020
1217
|
exports.patchPrismaClient = patchPrismaClient;
|
|
1021
1218
|
exports.patchPrismaPgAdapter = patchPrismaPgAdapter;
|
package/dist/db/prisma.d.cts
CHANGED
|
@@ -1,4 +1,42 @@
|
|
|
1
|
+
/** The parts of a PrismaClient the correlation tagging needs. */
|
|
2
|
+
interface TaggingClient {
|
|
3
|
+
$extends: (ext: unknown) => unknown;
|
|
4
|
+
$transaction: (queries: unknown[]) => Promise<unknown[]>;
|
|
5
|
+
$executeRawUnsafe: (sql: string, ...values: unknown[]) => unknown;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Public factory for `prisma.$extends(ezlogsPrisma())`.
|
|
9
|
+
*
|
|
10
|
+
* Returns Prisma's callback-form extension (what
|
|
11
|
+
* `Prisma.defineExtension((client) => …)` returns) so the hook can
|
|
12
|
+
* reach the client for correlation tagging: every write made inside a
|
|
13
|
+
* captured request runs as
|
|
14
|
+
*
|
|
15
|
+
* client.$transaction([
|
|
16
|
+
* client.$executeRawUnsafe("SELECT set_config('ezlogs.correlation_id', $1, TRUE)", id),
|
|
17
|
+
* query(args),
|
|
18
|
+
* ])
|
|
19
|
+
*
|
|
20
|
+
* — Prisma's documented RLS client-extension pattern. The audit
|
|
21
|
+
* trigger reads that setting, so rows from a plain `PrismaClient`
|
|
22
|
+
* (default engine, no driver adapter) join the right request. Reads
|
|
23
|
+
* pass through with no extra query.
|
|
24
|
+
*
|
|
25
|
+
* Not tagged (rows ship as their own actions, never misattributed):
|
|
26
|
+
* writes inside a user `$transaction` (batch or interactive) — Prisma
|
|
27
|
+
* can't nest a transaction there.
|
|
28
|
+
*/
|
|
1
29
|
declare function ezlogsPrisma(): unknown;
|
|
30
|
+
/**
|
|
31
|
+
* The extension descriptor. `client` null = capture only, no tagging
|
|
32
|
+
* (the adapter-pg path tags via the patched `pg` driver instead).
|
|
33
|
+
* `schemaClient` (defaults to `client`) is read for each model's table
|
|
34
|
+
* name (`@@map`).
|
|
35
|
+
* @internal exported for tests.
|
|
36
|
+
*/
|
|
37
|
+
declare function buildPrismaExtension(client: TaggingClient | null, schemaClient?: object | null): unknown;
|
|
38
|
+
/** @internal test-only */
|
|
39
|
+
declare function _resetPrismaTaggingForTests(): void;
|
|
2
40
|
/**
|
|
3
41
|
* Wrap a `PrismaPg` adapter so its queryRaw/executeRaw/transactionContext
|
|
4
42
|
* methods run inside a snapshot the partnered `patchPrismaClient` deposits.
|
|
@@ -37,4 +75,4 @@ declare function patchPrismaPgAdapter<A extends object>(adapter: A): A;
|
|
|
37
75
|
*/
|
|
38
76
|
declare function patchPrismaClient<T extends object>(prisma: T, adapter?: object): T;
|
|
39
77
|
|
|
40
|
-
export { ezlogsPrisma, patchPrismaClient, patchPrismaPgAdapter };
|
|
78
|
+
export { _resetPrismaTaggingForTests, buildPrismaExtension, ezlogsPrisma, patchPrismaClient, patchPrismaPgAdapter };
|
package/dist/db/prisma.d.ts
CHANGED
|
@@ -1,4 +1,42 @@
|
|
|
1
|
+
/** The parts of a PrismaClient the correlation tagging needs. */
|
|
2
|
+
interface TaggingClient {
|
|
3
|
+
$extends: (ext: unknown) => unknown;
|
|
4
|
+
$transaction: (queries: unknown[]) => Promise<unknown[]>;
|
|
5
|
+
$executeRawUnsafe: (sql: string, ...values: unknown[]) => unknown;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Public factory for `prisma.$extends(ezlogsPrisma())`.
|
|
9
|
+
*
|
|
10
|
+
* Returns Prisma's callback-form extension (what
|
|
11
|
+
* `Prisma.defineExtension((client) => …)` returns) so the hook can
|
|
12
|
+
* reach the client for correlation tagging: every write made inside a
|
|
13
|
+
* captured request runs as
|
|
14
|
+
*
|
|
15
|
+
* client.$transaction([
|
|
16
|
+
* client.$executeRawUnsafe("SELECT set_config('ezlogs.correlation_id', $1, TRUE)", id),
|
|
17
|
+
* query(args),
|
|
18
|
+
* ])
|
|
19
|
+
*
|
|
20
|
+
* — Prisma's documented RLS client-extension pattern. The audit
|
|
21
|
+
* trigger reads that setting, so rows from a plain `PrismaClient`
|
|
22
|
+
* (default engine, no driver adapter) join the right request. Reads
|
|
23
|
+
* pass through with no extra query.
|
|
24
|
+
*
|
|
25
|
+
* Not tagged (rows ship as their own actions, never misattributed):
|
|
26
|
+
* writes inside a user `$transaction` (batch or interactive) — Prisma
|
|
27
|
+
* can't nest a transaction there.
|
|
28
|
+
*/
|
|
1
29
|
declare function ezlogsPrisma(): unknown;
|
|
30
|
+
/**
|
|
31
|
+
* The extension descriptor. `client` null = capture only, no tagging
|
|
32
|
+
* (the adapter-pg path tags via the patched `pg` driver instead).
|
|
33
|
+
* `schemaClient` (defaults to `client`) is read for each model's table
|
|
34
|
+
* name (`@@map`).
|
|
35
|
+
* @internal exported for tests.
|
|
36
|
+
*/
|
|
37
|
+
declare function buildPrismaExtension(client: TaggingClient | null, schemaClient?: object | null): unknown;
|
|
38
|
+
/** @internal test-only */
|
|
39
|
+
declare function _resetPrismaTaggingForTests(): void;
|
|
2
40
|
/**
|
|
3
41
|
* Wrap a `PrismaPg` adapter so its queryRaw/executeRaw/transactionContext
|
|
4
42
|
* methods run inside a snapshot the partnered `patchPrismaClient` deposits.
|
|
@@ -37,4 +75,4 @@ declare function patchPrismaPgAdapter<A extends object>(adapter: A): A;
|
|
|
37
75
|
*/
|
|
38
76
|
declare function patchPrismaClient<T extends object>(prisma: T, adapter?: object): T;
|
|
39
77
|
|
|
40
|
-
export { ezlogsPrisma, patchPrismaClient, patchPrismaPgAdapter };
|
|
78
|
+
export { _resetPrismaTaggingForTests, buildPrismaExtension, ezlogsPrisma, patchPrismaClient, patchPrismaPgAdapter };
|