ezlogs-nextjs 0.1.1 → 0.1.2

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.
@@ -42,6 +42,86 @@ var logger = {
42
42
  error: (message) => safeWrite("error", message)
43
43
  };
44
44
 
45
+ // src/edge-fallback.ts
46
+ var ALS_CTOR = loadAsyncLocalStorage();
47
+ function loadAsyncLocalStorage() {
48
+ const fromGlobal = globalThis.AsyncLocalStorage;
49
+ if (typeof fromGlobal === "function") return fromGlobal;
50
+ try {
51
+ const req = typeof __require !== "undefined" ? __require : (
52
+ // In ESM, `createRequire` is the official escape hatch.
53
+ // We pull it via globalThis to avoid a static `import`
54
+ // that would itself be browser-bundled.
55
+ void 0
56
+ );
57
+ if (typeof req === "function") {
58
+ const moduleName = ["async", "hooks"].join("_");
59
+ const mod = req("node:" + moduleName);
60
+ if (typeof mod.AsyncLocalStorage === "function") return mod.AsyncLocalStorage;
61
+ }
62
+ } catch {
63
+ }
64
+ return null;
65
+ }
66
+ function makeAsyncContextCapture() {
67
+ if (!ALS_CTOR) return null;
68
+ const ctor = ALS_CTOR;
69
+ if (typeof ctor.snapshot !== "function") return null;
70
+ const snapshot = ctor.snapshot.bind(ctor);
71
+ return () => {
72
+ const runSnapshot = snapshot();
73
+ return (fn) => runSnapshot(fn);
74
+ };
75
+ }
76
+ function createScopedStorage(key = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:default-scoped-storage")) {
77
+ const globalStore = globalThis;
78
+ let entry = globalStore[key];
79
+ if (!entry) {
80
+ const als2 = (() => {
81
+ if (!ALS_CTOR) return null;
82
+ try {
83
+ return new ALS_CTOR();
84
+ } catch {
85
+ return null;
86
+ }
87
+ })();
88
+ entry = { als: als2, edgeFallback: null };
89
+ globalStore[key] = entry;
90
+ }
91
+ const als = entry.als;
92
+ const stateRef = entry;
93
+ return {
94
+ read() {
95
+ if (als) return als.getStore()?.value ?? null;
96
+ return stateRef.edgeFallback?.value ?? null;
97
+ },
98
+ run(value, callback) {
99
+ if (als) return als.run({ value }, callback);
100
+ const previous = stateRef.edgeFallback;
101
+ stateRef.edgeFallback = { value };
102
+ try {
103
+ return callback();
104
+ } finally {
105
+ stateRef.edgeFallback = previous;
106
+ }
107
+ },
108
+ update(value) {
109
+ if (als) {
110
+ const store = als.getStore();
111
+ if (store) store.value = value;
112
+ return;
113
+ }
114
+ stateRef.edgeFallback = { value };
115
+ },
116
+ _resetForTests() {
117
+ stateRef.edgeFallback = null;
118
+ },
119
+ _isAsyncLocalStorage() {
120
+ return als !== null;
121
+ }
122
+ };
123
+ }
124
+
45
125
  // src/configuration.ts
46
126
  var DEFAULT_EXCLUDED_PATHS = Object.freeze([
47
127
  // Next.js / Vercel infrastructure noise
@@ -408,76 +488,6 @@ function describe2(error) {
408
488
  return String(error);
409
489
  }
410
490
 
411
- // src/edge-fallback.ts
412
- var ALS_CTOR = loadAsyncLocalStorage();
413
- function loadAsyncLocalStorage() {
414
- const fromGlobal = globalThis.AsyncLocalStorage;
415
- if (typeof fromGlobal === "function") return fromGlobal;
416
- try {
417
- const req = typeof __require !== "undefined" ? __require : (
418
- // In ESM, `createRequire` is the official escape hatch.
419
- // We pull it via globalThis to avoid a static `import`
420
- // that would itself be browser-bundled.
421
- void 0
422
- );
423
- if (typeof req === "function") {
424
- const moduleName = ["async", "hooks"].join("_");
425
- const mod = req("node:" + moduleName);
426
- if (typeof mod.AsyncLocalStorage === "function") return mod.AsyncLocalStorage;
427
- }
428
- } catch {
429
- }
430
- return null;
431
- }
432
- function createScopedStorage(key = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:default-scoped-storage")) {
433
- const globalStore = globalThis;
434
- let entry = globalStore[key];
435
- if (!entry) {
436
- const als2 = (() => {
437
- if (!ALS_CTOR) return null;
438
- try {
439
- return new ALS_CTOR();
440
- } catch {
441
- return null;
442
- }
443
- })();
444
- entry = { als: als2, edgeFallback: null };
445
- globalStore[key] = entry;
446
- }
447
- const als = entry.als;
448
- const stateRef = entry;
449
- return {
450
- read() {
451
- if (als) return als.getStore()?.value ?? null;
452
- return stateRef.edgeFallback?.value ?? null;
453
- },
454
- run(value, callback) {
455
- if (als) return als.run({ value }, callback);
456
- const previous = stateRef.edgeFallback;
457
- stateRef.edgeFallback = { value };
458
- try {
459
- return callback();
460
- } finally {
461
- stateRef.edgeFallback = previous;
462
- }
463
- },
464
- update(value) {
465
- if (als) {
466
- const store = als.getStore();
467
- if (store) store.value = value;
468
- return;
469
- }
470
- stateRef.edgeFallback = { value };
471
- },
472
- _resetForTests() {
473
- stateRef.edgeFallback = null;
474
- },
475
- _isAsyncLocalStorage() {
476
- return als !== null;
477
- }
478
- };
479
- }
480
-
481
491
  // src/correlation.ts
482
492
  var storage = createScopedStorage(
483
493
  /* @__PURE__ */ Symbol.for("ezlogs-nextjs:correlation-storage")
@@ -833,5 +843,179 @@ function describeError2(error) {
833
843
  if (error instanceof Error) return `${error.name}: ${error.message}`;
834
844
  return String(error);
835
845
  }
846
+ var EZLOGS_PRISMA_BRAND = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:prismaPatched");
847
+ var EZLOGS_ADAPTER_BRAND = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:prismaPgAdapterPatched");
848
+ var ADAPTER_SNAPSHOT_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:prismaPgSnapshot");
849
+ var ADAPTER_MUTEX_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:prismaPgMutex");
850
+ var RAW_METHODS = /* @__PURE__ */ new Set([
851
+ "$transaction",
852
+ "$queryRaw",
853
+ "$queryRawUnsafe",
854
+ "$executeRaw",
855
+ "$executeRawUnsafe",
856
+ "$runCommandRaw"
857
+ ]);
858
+ var MODEL_METHODS = /* @__PURE__ */ new Set([
859
+ "create",
860
+ "createMany",
861
+ "createManyAndReturn",
862
+ "findUnique",
863
+ "findUniqueOrThrow",
864
+ "findFirst",
865
+ "findFirstOrThrow",
866
+ "findMany",
867
+ "update",
868
+ "updateMany",
869
+ "upsert",
870
+ "delete",
871
+ "deleteMany",
872
+ "count",
873
+ "aggregate",
874
+ "groupBy"
875
+ ]);
876
+ function patchPrismaPgAdapter(adapter) {
877
+ if (!adapter || typeof adapter !== "object") return adapter;
878
+ const adapterRec = adapter;
879
+ if (adapterRec[EZLOGS_ADAPTER_BRAND] === true) return adapter;
880
+ for (const method of ["queryRaw", "executeRaw", "transactionContext"]) {
881
+ const original = adapterRec[method];
882
+ if (typeof original !== "function") continue;
883
+ adapterRec[method] = function ezlogsPatchedAdapterMethod(...args) {
884
+ const snapshot = adapterRec[ADAPTER_SNAPSHOT_KEY];
885
+ const invoke = () => original.apply(this, args);
886
+ if (snapshot) return snapshot(invoke);
887
+ return invoke();
888
+ };
889
+ }
890
+ adapterRec[EZLOGS_ADAPTER_BRAND] = true;
891
+ return adapter;
892
+ }
893
+ function patchPrismaClient(prisma, adapter) {
894
+ if (!prisma || typeof prisma !== "object") {
895
+ return prisma;
896
+ }
897
+ if (prisma[EZLOGS_PRISMA_BRAND] === true) {
898
+ return prisma;
899
+ }
900
+ const captureAndRun = makeAsyncContextCapture();
901
+ if (!captureAndRun) {
902
+ logger.debug(
903
+ "patchPrismaClient: AsyncLocalStorage.snapshot() unavailable; skipping ALS bind, applying ezlogsPrisma() only."
904
+ );
905
+ return applyEzlogsExtension(prisma);
906
+ }
907
+ const patchedAdapter = adapter && typeof adapter === "object" && adapter[EZLOGS_ADAPTER_BRAND] === true ? adapter : null;
908
+ if (adapter && !patchedAdapter) {
909
+ logger.debug(
910
+ "patchPrismaClient: adapter is not the output of patchPrismaPgAdapter(). Correlation_id will be NULL on concurrent requests. Wrap the adapter first."
911
+ );
912
+ }
913
+ const extended = applyEzlogsExtension(prisma);
914
+ const wrapped = buildClientProxy(extended, captureAndRun, patchedAdapter);
915
+ return wrapped;
916
+ }
917
+ function applyEzlogsExtension(prisma) {
918
+ const client = prisma;
919
+ if (typeof client.$extends !== "function") {
920
+ logger.debug(
921
+ "patchPrismaClient: client has no $extends; skipping ezlogsPrisma extension."
922
+ );
923
+ return prisma;
924
+ }
925
+ try {
926
+ return client.$extends(ezlogsPrisma());
927
+ } catch (error) {
928
+ logger.debug(`patchPrismaClient: $extends failed: ${describeError2(error)}`);
929
+ return prisma;
930
+ }
931
+ }
932
+ function buildClientProxy(client, captureAndRun, adapter) {
933
+ const modelProxyCache = /* @__PURE__ */ new WeakMap();
934
+ return new Proxy(client, {
935
+ get(target, prop, receiver) {
936
+ if (prop === EZLOGS_PRISMA_BRAND) return true;
937
+ const value = Reflect.get(target, prop, receiver);
938
+ if (typeof prop !== "string") return value;
939
+ if (RAW_METHODS.has(prop) && typeof value === "function") {
940
+ return bindFunctionInSnapshot(value, target, captureAndRun, adapter);
941
+ }
942
+ if (isLikelyModelDelegate(value)) {
943
+ const cached = modelProxyCache.get(value);
944
+ if (cached) return cached;
945
+ const wrappedDelegate = buildModelProxy(value, captureAndRun, adapter);
946
+ modelProxyCache.set(value, wrappedDelegate);
947
+ return wrappedDelegate;
948
+ }
949
+ return value;
950
+ }
951
+ });
952
+ }
953
+ function buildModelProxy(delegate, captureAndRun, adapter) {
954
+ return new Proxy(delegate, {
955
+ get(target, prop, receiver) {
956
+ const value = Reflect.get(target, prop, receiver);
957
+ if (typeof prop === "string" && MODEL_METHODS.has(prop) && typeof value === "function") {
958
+ return bindFunctionInSnapshot(value, target, captureAndRun, adapter);
959
+ }
960
+ return value;
961
+ }
962
+ });
963
+ }
964
+ function bindFunctionInSnapshot(fn, thisArg, captureAndRun, adapter) {
965
+ return function bound(...args) {
966
+ const run = captureAndRun();
967
+ const boundArgs = args.map(
968
+ (a) => typeof a === "function" ? wrapCallbackInSnapshot(a, run) : a
969
+ );
970
+ const invoke = () => Reflect.apply(fn, thisArg, boundArgs);
971
+ if (!adapter) return run(invoke);
972
+ return enterAdapterMutex(
973
+ adapter,
974
+ () => run(() => {
975
+ adapter[ADAPTER_SNAPSHOT_KEY] = run;
976
+ let result;
977
+ try {
978
+ result = invoke();
979
+ } catch (sync) {
980
+ adapter[ADAPTER_SNAPSHOT_KEY] = null;
981
+ throw sync;
982
+ }
983
+ if (isThenable(result)) {
984
+ return result.finally(() => {
985
+ adapter[ADAPTER_SNAPSHOT_KEY] = null;
986
+ });
987
+ }
988
+ adapter[ADAPTER_SNAPSHOT_KEY] = null;
989
+ return result;
990
+ })
991
+ );
992
+ };
993
+ }
994
+ function enterAdapterMutex(adapter, body) {
995
+ const prev = adapter[ADAPTER_MUTEX_KEY] ?? Promise.resolve();
996
+ const next = prev.then(() => body());
997
+ adapter[ADAPTER_MUTEX_KEY] = next.then(
998
+ () => void 0,
999
+ () => void 0
1000
+ );
1001
+ return next;
1002
+ }
1003
+ function isThenable(value) {
1004
+ return value !== null && typeof value === "object" && typeof value.then === "function";
1005
+ }
1006
+ function wrapCallbackInSnapshot(cb, run) {
1007
+ return function wrapped(...args) {
1008
+ return run(() => Reflect.apply(cb, this, args));
1009
+ };
1010
+ }
1011
+ function isLikelyModelDelegate(value) {
1012
+ if (!value || typeof value !== "object") return false;
1013
+ if (Array.isArray(value)) return false;
1014
+ if (value instanceof Date) return false;
1015
+ const candidate = value;
1016
+ return typeof candidate.create === "function" && typeof candidate.findMany === "function";
1017
+ }
836
1018
 
837
1019
  exports.ezlogsPrisma = ezlogsPrisma;
1020
+ exports.patchPrismaClient = patchPrismaClient;
1021
+ exports.patchPrismaPgAdapter = patchPrismaPgAdapter;
@@ -1,3 +1,40 @@
1
1
  declare function ezlogsPrisma(): unknown;
2
+ /**
3
+ * Wrap a `PrismaPg` adapter so its queryRaw/executeRaw/transactionContext
4
+ * methods run inside a snapshot the partnered `patchPrismaClient` deposits.
5
+ * Idempotent — passing a previously-wrapped adapter returns it unchanged.
6
+ *
7
+ * Customer wires this BEFORE constructing the PrismaClient:
8
+ *
9
+ * const adapter = patchPrismaPgAdapter(new PrismaPg(pool));
10
+ * const prisma = patchPrismaClient(new PrismaClient({ adapter }), adapter);
11
+ *
12
+ * Without this wrap, the snapshot we capture at the Prisma call site
13
+ * dies at the engine's NAPI boundary before adapter-pg's pool.query
14
+ * runs — the production bug. With it, the wrap reads the synchronously-
15
+ * deposited snapshot off the adapter and re-enters it just before
16
+ * the wrapped method delegates to the real adapter, restoring the
17
+ * agent's correlation/actor frames for the eventual SET LOCAL.
18
+ */
19
+ declare function patchPrismaPgAdapter<A extends object>(adapter: A): A;
20
+ /**
21
+ * Wrap a PrismaClient so every async method preserves the caller's
22
+ * AsyncLocalStorage context across the engine boundary. Idempotent.
23
+ *
24
+ * Composes `prisma.$extends(ezlogsPrisma())` internally so customers
25
+ * only have to write one wiring line for capture. If `adapter` is
26
+ * passed and is the result of `patchPrismaPgAdapter`, the Proxy uses
27
+ * an adapter-level serialization mutex to deposit the snapshot on the
28
+ * adapter synchronously before each method call and clear it after —
29
+ * the only correct way to thread per-call context through Prisma's
30
+ * NAPI engine boundary. Without the adapter arg, the wrapper still
31
+ * applies the capture extension but cannot fix the correlation bug;
32
+ * see `patchPrismaPgAdapter`'s docstring for the explanation.
33
+ *
34
+ * The returned value is typed as the same shape as the input. We
35
+ * cast back to `T` because runtime Proxy preserves the surface but
36
+ * TypeScript can't follow this through a generic.
37
+ */
38
+ declare function patchPrismaClient<T extends object>(prisma: T, adapter?: object): T;
2
39
 
3
- export { ezlogsPrisma };
40
+ export { ezlogsPrisma, patchPrismaClient, patchPrismaPgAdapter };
@@ -1,3 +1,40 @@
1
1
  declare function ezlogsPrisma(): unknown;
2
+ /**
3
+ * Wrap a `PrismaPg` adapter so its queryRaw/executeRaw/transactionContext
4
+ * methods run inside a snapshot the partnered `patchPrismaClient` deposits.
5
+ * Idempotent — passing a previously-wrapped adapter returns it unchanged.
6
+ *
7
+ * Customer wires this BEFORE constructing the PrismaClient:
8
+ *
9
+ * const adapter = patchPrismaPgAdapter(new PrismaPg(pool));
10
+ * const prisma = patchPrismaClient(new PrismaClient({ adapter }), adapter);
11
+ *
12
+ * Without this wrap, the snapshot we capture at the Prisma call site
13
+ * dies at the engine's NAPI boundary before adapter-pg's pool.query
14
+ * runs — the production bug. With it, the wrap reads the synchronously-
15
+ * deposited snapshot off the adapter and re-enters it just before
16
+ * the wrapped method delegates to the real adapter, restoring the
17
+ * agent's correlation/actor frames for the eventual SET LOCAL.
18
+ */
19
+ declare function patchPrismaPgAdapter<A extends object>(adapter: A): A;
20
+ /**
21
+ * Wrap a PrismaClient so every async method preserves the caller's
22
+ * AsyncLocalStorage context across the engine boundary. Idempotent.
23
+ *
24
+ * Composes `prisma.$extends(ezlogsPrisma())` internally so customers
25
+ * only have to write one wiring line for capture. If `adapter` is
26
+ * passed and is the result of `patchPrismaPgAdapter`, the Proxy uses
27
+ * an adapter-level serialization mutex to deposit the snapshot on the
28
+ * adapter synchronously before each method call and clear it after —
29
+ * the only correct way to thread per-call context through Prisma's
30
+ * NAPI engine boundary. Without the adapter arg, the wrapper still
31
+ * applies the capture extension but cannot fix the correlation bug;
32
+ * see `patchPrismaPgAdapter`'s docstring for the explanation.
33
+ *
34
+ * The returned value is typed as the same shape as the input. We
35
+ * cast back to `T` because runtime Proxy preserves the surface but
36
+ * TypeScript can't follow this through a generic.
37
+ */
38
+ declare function patchPrismaClient<T extends object>(prisma: T, adapter?: object): T;
2
39
 
3
- export { ezlogsPrisma };
40
+ export { ezlogsPrisma, patchPrismaClient, patchPrismaPgAdapter };
package/dist/db/prisma.js CHANGED
@@ -40,6 +40,86 @@ var logger = {
40
40
  error: (message) => safeWrite("error", message)
41
41
  };
42
42
 
43
+ // src/edge-fallback.ts
44
+ var ALS_CTOR = loadAsyncLocalStorage();
45
+ function loadAsyncLocalStorage() {
46
+ const fromGlobal = globalThis.AsyncLocalStorage;
47
+ if (typeof fromGlobal === "function") return fromGlobal;
48
+ try {
49
+ const req = typeof __require !== "undefined" ? __require : (
50
+ // In ESM, `createRequire` is the official escape hatch.
51
+ // We pull it via globalThis to avoid a static `import`
52
+ // that would itself be browser-bundled.
53
+ void 0
54
+ );
55
+ if (typeof req === "function") {
56
+ const moduleName = ["async", "hooks"].join("_");
57
+ const mod = req("node:" + moduleName);
58
+ if (typeof mod.AsyncLocalStorage === "function") return mod.AsyncLocalStorage;
59
+ }
60
+ } catch {
61
+ }
62
+ return null;
63
+ }
64
+ function makeAsyncContextCapture() {
65
+ if (!ALS_CTOR) return null;
66
+ const ctor = ALS_CTOR;
67
+ if (typeof ctor.snapshot !== "function") return null;
68
+ const snapshot = ctor.snapshot.bind(ctor);
69
+ return () => {
70
+ const runSnapshot = snapshot();
71
+ return (fn) => runSnapshot(fn);
72
+ };
73
+ }
74
+ function createScopedStorage(key = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:default-scoped-storage")) {
75
+ const globalStore = globalThis;
76
+ let entry = globalStore[key];
77
+ if (!entry) {
78
+ const als2 = (() => {
79
+ if (!ALS_CTOR) return null;
80
+ try {
81
+ return new ALS_CTOR();
82
+ } catch {
83
+ return null;
84
+ }
85
+ })();
86
+ entry = { als: als2, edgeFallback: null };
87
+ globalStore[key] = entry;
88
+ }
89
+ const als = entry.als;
90
+ const stateRef = entry;
91
+ return {
92
+ read() {
93
+ if (als) return als.getStore()?.value ?? null;
94
+ return stateRef.edgeFallback?.value ?? null;
95
+ },
96
+ run(value, callback) {
97
+ if (als) return als.run({ value }, callback);
98
+ const previous = stateRef.edgeFallback;
99
+ stateRef.edgeFallback = { value };
100
+ try {
101
+ return callback();
102
+ } finally {
103
+ stateRef.edgeFallback = previous;
104
+ }
105
+ },
106
+ update(value) {
107
+ if (als) {
108
+ const store = als.getStore();
109
+ if (store) store.value = value;
110
+ return;
111
+ }
112
+ stateRef.edgeFallback = { value };
113
+ },
114
+ _resetForTests() {
115
+ stateRef.edgeFallback = null;
116
+ },
117
+ _isAsyncLocalStorage() {
118
+ return als !== null;
119
+ }
120
+ };
121
+ }
122
+
43
123
  // src/configuration.ts
44
124
  var DEFAULT_EXCLUDED_PATHS = Object.freeze([
45
125
  // Next.js / Vercel infrastructure noise
@@ -406,76 +486,6 @@ function describe2(error) {
406
486
  return String(error);
407
487
  }
408
488
 
409
- // src/edge-fallback.ts
410
- var ALS_CTOR = loadAsyncLocalStorage();
411
- function loadAsyncLocalStorage() {
412
- const fromGlobal = globalThis.AsyncLocalStorage;
413
- if (typeof fromGlobal === "function") return fromGlobal;
414
- try {
415
- const req = typeof __require !== "undefined" ? __require : (
416
- // In ESM, `createRequire` is the official escape hatch.
417
- // We pull it via globalThis to avoid a static `import`
418
- // that would itself be browser-bundled.
419
- void 0
420
- );
421
- if (typeof req === "function") {
422
- const moduleName = ["async", "hooks"].join("_");
423
- const mod = req("node:" + moduleName);
424
- if (typeof mod.AsyncLocalStorage === "function") return mod.AsyncLocalStorage;
425
- }
426
- } catch {
427
- }
428
- return null;
429
- }
430
- function createScopedStorage(key = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:default-scoped-storage")) {
431
- const globalStore = globalThis;
432
- let entry = globalStore[key];
433
- if (!entry) {
434
- const als2 = (() => {
435
- if (!ALS_CTOR) return null;
436
- try {
437
- return new ALS_CTOR();
438
- } catch {
439
- return null;
440
- }
441
- })();
442
- entry = { als: als2, edgeFallback: null };
443
- globalStore[key] = entry;
444
- }
445
- const als = entry.als;
446
- const stateRef = entry;
447
- return {
448
- read() {
449
- if (als) return als.getStore()?.value ?? null;
450
- return stateRef.edgeFallback?.value ?? null;
451
- },
452
- run(value, callback) {
453
- if (als) return als.run({ value }, callback);
454
- const previous = stateRef.edgeFallback;
455
- stateRef.edgeFallback = { value };
456
- try {
457
- return callback();
458
- } finally {
459
- stateRef.edgeFallback = previous;
460
- }
461
- },
462
- update(value) {
463
- if (als) {
464
- const store = als.getStore();
465
- if (store) store.value = value;
466
- return;
467
- }
468
- stateRef.edgeFallback = { value };
469
- },
470
- _resetForTests() {
471
- stateRef.edgeFallback = null;
472
- },
473
- _isAsyncLocalStorage() {
474
- return als !== null;
475
- }
476
- };
477
- }
478
-
479
489
  // src/correlation.ts
480
490
  var storage = createScopedStorage(
481
491
  /* @__PURE__ */ Symbol.for("ezlogs-nextjs:correlation-storage")
@@ -831,5 +841,177 @@ function describeError2(error) {
831
841
  if (error instanceof Error) return `${error.name}: ${error.message}`;
832
842
  return String(error);
833
843
  }
844
+ var EZLOGS_PRISMA_BRAND = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:prismaPatched");
845
+ var EZLOGS_ADAPTER_BRAND = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:prismaPgAdapterPatched");
846
+ var ADAPTER_SNAPSHOT_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:prismaPgSnapshot");
847
+ var ADAPTER_MUTEX_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:prismaPgMutex");
848
+ var RAW_METHODS = /* @__PURE__ */ new Set([
849
+ "$transaction",
850
+ "$queryRaw",
851
+ "$queryRawUnsafe",
852
+ "$executeRaw",
853
+ "$executeRawUnsafe",
854
+ "$runCommandRaw"
855
+ ]);
856
+ var MODEL_METHODS = /* @__PURE__ */ new Set([
857
+ "create",
858
+ "createMany",
859
+ "createManyAndReturn",
860
+ "findUnique",
861
+ "findUniqueOrThrow",
862
+ "findFirst",
863
+ "findFirstOrThrow",
864
+ "findMany",
865
+ "update",
866
+ "updateMany",
867
+ "upsert",
868
+ "delete",
869
+ "deleteMany",
870
+ "count",
871
+ "aggregate",
872
+ "groupBy"
873
+ ]);
874
+ function patchPrismaPgAdapter(adapter) {
875
+ if (!adapter || typeof adapter !== "object") return adapter;
876
+ const adapterRec = adapter;
877
+ if (adapterRec[EZLOGS_ADAPTER_BRAND] === true) return adapter;
878
+ for (const method of ["queryRaw", "executeRaw", "transactionContext"]) {
879
+ const original = adapterRec[method];
880
+ if (typeof original !== "function") continue;
881
+ adapterRec[method] = function ezlogsPatchedAdapterMethod(...args) {
882
+ const snapshot = adapterRec[ADAPTER_SNAPSHOT_KEY];
883
+ const invoke = () => original.apply(this, args);
884
+ if (snapshot) return snapshot(invoke);
885
+ return invoke();
886
+ };
887
+ }
888
+ adapterRec[EZLOGS_ADAPTER_BRAND] = true;
889
+ return adapter;
890
+ }
891
+ function patchPrismaClient(prisma, adapter) {
892
+ if (!prisma || typeof prisma !== "object") {
893
+ return prisma;
894
+ }
895
+ if (prisma[EZLOGS_PRISMA_BRAND] === true) {
896
+ return prisma;
897
+ }
898
+ const captureAndRun = makeAsyncContextCapture();
899
+ if (!captureAndRun) {
900
+ logger.debug(
901
+ "patchPrismaClient: AsyncLocalStorage.snapshot() unavailable; skipping ALS bind, applying ezlogsPrisma() only."
902
+ );
903
+ return applyEzlogsExtension(prisma);
904
+ }
905
+ const patchedAdapter = adapter && typeof adapter === "object" && adapter[EZLOGS_ADAPTER_BRAND] === true ? adapter : null;
906
+ if (adapter && !patchedAdapter) {
907
+ logger.debug(
908
+ "patchPrismaClient: adapter is not the output of patchPrismaPgAdapter(). Correlation_id will be NULL on concurrent requests. Wrap the adapter first."
909
+ );
910
+ }
911
+ const extended = applyEzlogsExtension(prisma);
912
+ const wrapped = buildClientProxy(extended, captureAndRun, patchedAdapter);
913
+ return wrapped;
914
+ }
915
+ function applyEzlogsExtension(prisma) {
916
+ const client = prisma;
917
+ if (typeof client.$extends !== "function") {
918
+ logger.debug(
919
+ "patchPrismaClient: client has no $extends; skipping ezlogsPrisma extension."
920
+ );
921
+ return prisma;
922
+ }
923
+ try {
924
+ return client.$extends(ezlogsPrisma());
925
+ } catch (error) {
926
+ logger.debug(`patchPrismaClient: $extends failed: ${describeError2(error)}`);
927
+ return prisma;
928
+ }
929
+ }
930
+ function buildClientProxy(client, captureAndRun, adapter) {
931
+ const modelProxyCache = /* @__PURE__ */ new WeakMap();
932
+ return new Proxy(client, {
933
+ get(target, prop, receiver) {
934
+ if (prop === EZLOGS_PRISMA_BRAND) return true;
935
+ const value = Reflect.get(target, prop, receiver);
936
+ if (typeof prop !== "string") return value;
937
+ if (RAW_METHODS.has(prop) && typeof value === "function") {
938
+ return bindFunctionInSnapshot(value, target, captureAndRun, adapter);
939
+ }
940
+ if (isLikelyModelDelegate(value)) {
941
+ const cached = modelProxyCache.get(value);
942
+ if (cached) return cached;
943
+ const wrappedDelegate = buildModelProxy(value, captureAndRun, adapter);
944
+ modelProxyCache.set(value, wrappedDelegate);
945
+ return wrappedDelegate;
946
+ }
947
+ return value;
948
+ }
949
+ });
950
+ }
951
+ function buildModelProxy(delegate, captureAndRun, adapter) {
952
+ return new Proxy(delegate, {
953
+ get(target, prop, receiver) {
954
+ const value = Reflect.get(target, prop, receiver);
955
+ if (typeof prop === "string" && MODEL_METHODS.has(prop) && typeof value === "function") {
956
+ return bindFunctionInSnapshot(value, target, captureAndRun, adapter);
957
+ }
958
+ return value;
959
+ }
960
+ });
961
+ }
962
+ function bindFunctionInSnapshot(fn, thisArg, captureAndRun, adapter) {
963
+ return function bound(...args) {
964
+ const run = captureAndRun();
965
+ const boundArgs = args.map(
966
+ (a) => typeof a === "function" ? wrapCallbackInSnapshot(a, run) : a
967
+ );
968
+ const invoke = () => Reflect.apply(fn, thisArg, boundArgs);
969
+ if (!adapter) return run(invoke);
970
+ return enterAdapterMutex(
971
+ adapter,
972
+ () => run(() => {
973
+ adapter[ADAPTER_SNAPSHOT_KEY] = run;
974
+ let result;
975
+ try {
976
+ result = invoke();
977
+ } catch (sync) {
978
+ adapter[ADAPTER_SNAPSHOT_KEY] = null;
979
+ throw sync;
980
+ }
981
+ if (isThenable(result)) {
982
+ return result.finally(() => {
983
+ adapter[ADAPTER_SNAPSHOT_KEY] = null;
984
+ });
985
+ }
986
+ adapter[ADAPTER_SNAPSHOT_KEY] = null;
987
+ return result;
988
+ })
989
+ );
990
+ };
991
+ }
992
+ function enterAdapterMutex(adapter, body) {
993
+ const prev = adapter[ADAPTER_MUTEX_KEY] ?? Promise.resolve();
994
+ const next = prev.then(() => body());
995
+ adapter[ADAPTER_MUTEX_KEY] = next.then(
996
+ () => void 0,
997
+ () => void 0
998
+ );
999
+ return next;
1000
+ }
1001
+ function isThenable(value) {
1002
+ return value !== null && typeof value === "object" && typeof value.then === "function";
1003
+ }
1004
+ function wrapCallbackInSnapshot(cb, run) {
1005
+ return function wrapped(...args) {
1006
+ return run(() => Reflect.apply(cb, this, args));
1007
+ };
1008
+ }
1009
+ function isLikelyModelDelegate(value) {
1010
+ if (!value || typeof value !== "object") return false;
1011
+ if (Array.isArray(value)) return false;
1012
+ if (value instanceof Date) return false;
1013
+ const candidate = value;
1014
+ return typeof candidate.create === "function" && typeof candidate.findMany === "function";
1015
+ }
834
1016
 
835
- export { ezlogsPrisma };
1017
+ export { ezlogsPrisma, patchPrismaClient, patchPrismaPgAdapter };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ezlogs-nextjs",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "EZLogs agent for Next.js — capture HTTP, database, and background-job events as plain-English Action cards.",
5
5
  "license": "MIT",
6
6
  "author": "EZLogs",