ezlogs-nextjs 0.4.4 → 0.4.7

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 (65) hide show
  1. package/README.md +73 -13
  2. package/dist/actors/index.d.cts +1 -1
  3. package/dist/actors/index.d.ts +1 -1
  4. package/dist/{chunk-MMLQXSSD.cjs → chunk-2YCQFLXW.cjs} +21 -11
  5. package/dist/{chunk-YMIGZYFH.js → chunk-343ZGTMH.js} +1 -1
  6. package/dist/{chunk-Z2TM3LGG.js → chunk-5ZMOWEBY.js} +1 -1
  7. package/dist/{chunk-GI6BM4MR.js → chunk-7MFKEYDN.js} +21 -12
  8. package/dist/{chunk-NINIAL7M.js → chunk-AXIQTU52.js} +1 -1
  9. package/dist/chunk-BE3RCFNP.js +13 -0
  10. package/dist/chunk-CHVJ4WPM.cjs +16 -0
  11. package/dist/{chunk-MHBS5FEP.js → chunk-CYAFYBKF.js} +27 -4
  12. package/dist/chunk-DRE2VXFX.js +19 -0
  13. package/dist/{chunk-GMHOUAKD.cjs → chunk-EXGEA4KE.cjs} +37 -13
  14. package/dist/{chunk-PS4U2GFJ.cjs → chunk-JB4UYCZI.cjs} +5 -5
  15. package/dist/chunk-JWJKFZBW.js +52 -0
  16. package/dist/{chunk-R6IWVTX3.cjs → chunk-KOFR5OC3.cjs} +31 -21
  17. package/dist/chunk-NFZ5OKF3.cjs +22 -0
  18. package/dist/{chunk-U22T7QYY.js → chunk-Q3HRVWCS.js} +13 -3
  19. package/dist/{chunk-YXZZNZG6.cjs → chunk-UC2KS5EG.cjs} +9 -9
  20. package/dist/chunk-VJR4VB4B.cjs +56 -0
  21. package/dist/{chunk-NX4EL7BY.cjs → chunk-XWEBKN65.cjs} +4 -4
  22. package/dist/{configuration-CJ5yKVlP.d.cts → configuration-b9pImwFB.d.cts} +2 -2
  23. package/dist/{configuration-CJ5yKVlP.d.ts → configuration-b9pImwFB.d.ts} +2 -2
  24. package/dist/db/drizzle.cjs +3 -3
  25. package/dist/db/drizzle.js +2 -2
  26. package/dist/db/postgres-js.cjs +4 -4
  27. package/dist/db/postgres-js.js +2 -2
  28. package/dist/db/prisma.cjs +12 -12
  29. package/dist/db/prisma.js +2 -2
  30. package/dist/db/supabase.cjs +42 -17
  31. package/dist/db/supabase.d.cts +11 -5
  32. package/dist/db/supabase.d.ts +11 -5
  33. package/dist/db/supabase.js +33 -9
  34. package/dist/index.cjs +303 -142
  35. package/dist/index.d.cts +2 -2
  36. package/dist/index.d.ts +2 -2
  37. package/dist/index.js +213 -52
  38. package/dist/jobs/bullmq.cjs +44 -16
  39. package/dist/jobs/bullmq.d.cts +7 -1
  40. package/dist/jobs/bullmq.d.ts +7 -1
  41. package/dist/jobs/bullmq.js +33 -6
  42. package/dist/jobs/inngest.cjs +171 -48
  43. package/dist/jobs/inngest.d.cts +13 -7
  44. package/dist/jobs/inngest.d.ts +13 -7
  45. package/dist/jobs/inngest.js +162 -40
  46. package/dist/jobs/supabase-queues.cjs +9 -9
  47. package/dist/jobs/supabase-queues.js +4 -4
  48. package/dist/jobs/trigger.cjs +7 -7
  49. package/dist/jobs/trigger.js +4 -4
  50. package/dist/jobs/upstash-workflow.cjs +139 -23
  51. package/dist/jobs/upstash-workflow.d.cts +20 -2
  52. package/dist/jobs/upstash-workflow.d.ts +20 -2
  53. package/dist/jobs/upstash-workflow.js +129 -14
  54. package/dist/nextjs-plugin/index.cjs +46 -29
  55. package/dist/nextjs-plugin/index.js +46 -29
  56. package/dist/nextjs-plugin/loader.cjs +104 -65
  57. package/dist/nextjs-plugin/loader.d.cts +18 -1
  58. package/dist/nextjs-plugin/loader.d.ts +18 -1
  59. package/dist/nextjs-plugin/loader.js +104 -66
  60. package/dist/triggers/index.cjs +22 -16
  61. package/dist/triggers/index.d.cts +0 -10
  62. package/dist/triggers/index.d.ts +0 -10
  63. package/dist/triggers/index.js +11 -5
  64. package/package.json +1 -1
  65. package/sql/postgres/00_install.sql +20 -3
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { I as InitOptions } from './configuration-CJ5yKVlP.cjs';
2
- export { A as ActorContext, a as ActorFromRequest, b as ActorPrincipal, D as DisplayNameMap } from './configuration-CJ5yKVlP.cjs';
1
+ import { I as InitOptions } from './configuration-b9pImwFB.cjs';
2
+ export { a as ActorContext, A as ActorFromRequest, b as ActorPrincipal, D as DisplayNameMap } from './configuration-b9pImwFB.cjs';
3
3
 
4
4
  /**
5
5
  * EventBuilder — port of ez_logs_agent/lib/ez_logs_agent/event_builder.rb.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { I as InitOptions } from './configuration-CJ5yKVlP.js';
2
- export { A as ActorContext, a as ActorFromRequest, b as ActorPrincipal, D as DisplayNameMap } from './configuration-CJ5yKVlP.js';
1
+ import { I as InitOptions } from './configuration-b9pImwFB.js';
2
+ export { a as ActorContext, A as ActorFromRequest, b as ActorPrincipal, D as DisplayNameMap } from './configuration-b9pImwFB.js';
3
3
 
4
4
  /**
5
5
  * EventBuilder — port of ez_logs_agent/lib/ez_logs_agent/event_builder.rb.
package/dist/index.js CHANGED
@@ -1,8 +1,9 @@
1
- import { patchPgClient } from './chunk-Z2TM3LGG.js';
2
- import { flushAuditLog, runWithEmittedAuditIdsScope, auditLogInstalled, checkAuditLogAccess, detectTriggerTrackedTables, maintainAuditLogAfterRequests } from './chunk-MHBS5FEP.js';
3
- import { build, pushEvent, maskAuthParams, isAuthActionName, isAuthPath, scrubSecretsInText, buffer_exports, sanitizeRequestParams, passesLuhn, isSensitiveKey, drainEvents } from './chunk-NINIAL7M.js';
4
- export { ArgError, build as buildEvent } from './chunk-NINIAL7M.js';
5
- import { configuration, resolveCorrelation, runWithCorrelation, maybeExtractSupabaseActor, endCorrelationScope, getCurrentActor, current, makeAsyncContextCapture, runWithActorScope, setActor, DEFAULT_EXCLUDED_EXTENSIONS } from './chunk-GI6BM4MR.js';
1
+ import { patchPgClient } from './chunk-5ZMOWEBY.js';
2
+ import { runWithDeliverySlot } from './chunk-BE3RCFNP.js';
3
+ import { flushAuditLog, runWithEmittedAuditIdsScope, auditLogInstalled, checkAuditLogAccess, detectTriggerTrackedTables, settleAuditFlushes, maintainAuditLogAfterRequests } from './chunk-CYAFYBKF.js';
4
+ import { build, pushEvent, maskAuthParams, isAuthActionName, isAuthPath, scrubSecretsInText, buffer_exports, sanitizeRequestParams, passesLuhn, isSensitiveKey, drainEvents } from './chunk-AXIQTU52.js';
5
+ export { ArgError, build as buildEvent } from './chunk-AXIQTU52.js';
6
+ import { configuration, resolveCorrelation, runWithCorrelation, maybeExtractSupabaseActor, endCorrelationScope, getCurrentActor, current, makeAsyncContextCapture, runWithActorScope, setActor, loadNodeBuiltin, DEFAULT_EXCLUDED_EXTENSIONS } from './chunk-7MFKEYDN.js';
6
7
  import { logger, setLogLevel } from './chunk-FCFVIRQF.js';
7
8
  import './chunk-SIAA4J6H.js';
8
9
 
@@ -141,6 +142,7 @@ var flushScheduler = {
141
142
  },
142
143
  async stop() {
143
144
  const s = state();
145
+ await settleAuditFlushes();
144
146
  if (s.timer === null) return;
145
147
  clearInterval(s.timer);
146
148
  s.timer = null;
@@ -159,17 +161,20 @@ var flushScheduler = {
159
161
  * builds a queue.
160
162
  */
161
163
  flushNow() {
162
- const s = state();
163
- if (!s.inFlight || !s.current) return tick();
164
- if (!s.followUp) {
165
- s.followUp = s.current.then(() => {
166
- s.followUp = null;
167
- return tick();
168
- });
169
- }
170
- return s.followUp;
164
+ return settleAuditFlushes().then(() => sendNow());
171
165
  }
172
166
  };
167
+ function sendNow() {
168
+ const s = state();
169
+ if (!s.inFlight || !s.current) return tick();
170
+ if (!s.followUp) {
171
+ s.followUp = s.current.then(() => {
172
+ s.followUp = null;
173
+ return tick();
174
+ });
175
+ }
176
+ return s.followUp;
177
+ }
173
178
  function tick() {
174
179
  const s = state();
175
180
  if (s.inFlight && s.current) return s.current;
@@ -230,12 +235,50 @@ function patchGlobalFetch() {
230
235
  };
231
236
  globalThis.fetch = wrapped;
232
237
  patched = true;
238
+ subscribeUndiciRequests();
239
+ }
240
+ var subscribed = false;
241
+ function subscribeUndiciRequests() {
242
+ if (subscribed) return;
243
+ const channel = loadDiagnosticsChannel();
244
+ if (!channel) return;
245
+ channel.subscribe("undici:request:create", onUndiciRequest);
246
+ subscribed = true;
247
+ }
248
+ function onUndiciRequest(message) {
249
+ try {
250
+ const request = message?.request;
251
+ if (!request || typeof request.addHeader !== "function") return;
252
+ const id = current();
253
+ if (!id || hasCorrelationHeader(request.headers)) return;
254
+ request.addHeader(HEADER, id);
255
+ } catch (error) {
256
+ logger.debug(`outgoing request header injection failed: ${describeError4(error)}`);
257
+ }
258
+ }
259
+ function hasCorrelationHeader(headers) {
260
+ if (Array.isArray(headers)) {
261
+ for (let i = 0; i < headers.length; i += 2) {
262
+ if (String(headers[i]).toLowerCase() === HEADER) return true;
263
+ }
264
+ return false;
265
+ }
266
+ if (typeof headers === "string") return headers.toLowerCase().includes(`${HEADER}:`);
267
+ return false;
268
+ }
269
+ function loadDiagnosticsChannel() {
270
+ const mod = loadNodeBuiltin(["diagnostics", "channel"].join("_"));
271
+ return typeof mod?.subscribe === "function" ? mod : null;
233
272
  }
234
273
  function unpatchGlobalFetch() {
235
274
  if (!patched || originalFetch === null) return;
236
275
  globalThis.fetch = originalFetch;
237
276
  originalFetch = null;
238
277
  patched = false;
278
+ if (subscribed) {
279
+ loadDiagnosticsChannel()?.unsubscribe("undici:request:create", onUndiciRequest);
280
+ subscribed = false;
281
+ }
239
282
  }
240
283
  function injectHeader(input, init, correlationId) {
241
284
  if (input instanceof Request && !init) {
@@ -454,11 +497,38 @@ function parseServerActionName(name) {
454
497
  }
455
498
  const canonical = KNOWN_VERBS.get(leading);
456
499
  if (!canonical) return { verb: null, entity: null };
457
- const entityTokens = tokens.slice(entityStart);
500
+ let rest = tokens.slice(entityStart);
501
+ const isConnector = (t) => CONNECTORS.has(t.toLowerCase());
502
+ if (rest.length > 0 && COMPOUND.has(rest[0].toLowerCase())) {
503
+ rest = rest.slice(2);
504
+ if (rest.length > 0 && isConnector(rest[0])) {
505
+ rest = rest.slice(rest.map(isConnector).lastIndexOf(true) + 1);
506
+ }
507
+ }
508
+ const firstConnector = rest.findIndex(isConnector);
509
+ const entityTokens = firstConnector === -1 ? rest : rest.slice(0, firstConnector);
458
510
  if (entityTokens.length === 0) return { verb: canonical, entity: null };
459
511
  const entity = entityTokens.join("");
460
512
  return { verb: canonical, entity: stripTrailingS(entity) || entity };
461
513
  }
514
+ var COMPOUND = /* @__PURE__ */ new Set(["and", "or", "then"]);
515
+ var CONNECTORS = /* @__PURE__ */ new Set([
516
+ ...COMPOUND,
517
+ "to",
518
+ "with",
519
+ "without",
520
+ "for",
521
+ "from",
522
+ "by",
523
+ "in",
524
+ "into",
525
+ "on",
526
+ "of",
527
+ "via",
528
+ "using",
529
+ "as",
530
+ "at"
531
+ ]);
462
532
  function stripTrailingS(entity) {
463
533
  if (entity.length <= 1) return entity;
464
534
  if (entity.endsWith("ies")) return `${entity.slice(0, -3)}y`;
@@ -794,9 +864,11 @@ function captureRoute(handler, context = {}) {
794
864
  if (snapshot === null) return Promise.resolve(runHandler(...args));
795
865
  snapshot.rawParams = mergeRouteParams(snapshot.rawParams, await readRouteParams(args[1]));
796
866
  const correlationId = resolveCorrelation(request.headers ?? null);
867
+ const delivery = { jobDelivery: false };
868
+ const inngestServerKind = request.headers?.get?.(INNGEST_SERVER_KIND) ?? null;
797
869
  return await runWithCorrelation(
798
870
  correlationId,
799
- () => runWithActorAndAuditScope(async () => {
871
+ () => runWithDeliverySlot(delivery, () => runWithActorAndAuditScope(async () => {
800
872
  await maybeRunActorHook(request);
801
873
  const startMs = Date.now();
802
874
  let statusCode = null;
@@ -808,6 +880,9 @@ function captureRoute(handler, context = {}) {
808
880
  let handlerMs = null;
809
881
  const finish = async () => {
810
882
  await maybeExtractSupabaseActor();
883
+ if (isJobRunnerSync(snapshot.method, inngestServerKind, response?.headers?.get?.(INNGEST_SDK) ?? null)) {
884
+ delivery.jobDelivery = true;
885
+ }
811
886
  await emitEvent({
812
887
  snapshot,
813
888
  context,
@@ -816,7 +891,8 @@ function captureRoute(handler, context = {}) {
816
891
  graphqlErrorMessage,
817
892
  responseErrorMessage,
818
893
  durationMs: handlerMs ?? Date.now() - startMs,
819
- startedAt: new Date(startMs)
894
+ startedAt: new Date(startMs),
895
+ jobDelivery: delivery.jobDelivery
820
896
  });
821
897
  await flushOnServerless();
822
898
  endCorrelationScope();
@@ -829,7 +905,7 @@ function captureRoute(handler, context = {}) {
829
905
  graphqlErrorMessage = await readGraphqlErrors(response);
830
906
  }
831
907
  const trpcRoute = isTrpcRoute(snapshot.rawParams, context.routeModulePath ?? null);
832
- responseErrorMessage = await readResponseErrorMessage(response, trpcRoute);
908
+ responseErrorMessage = await readResponseErrorMessage(response, trpcRoute) ?? authRedirectError(snapshot.url, response.status, response.headers.get("location"));
833
909
  const trpcStream = responseErrorMessage === null && trpcRoute ? trpcStreamErrorScanner(configuration().excludedGraphqlVariableKeys) : null;
834
910
  const followedResponse = followBody(
835
911
  response,
@@ -856,9 +932,12 @@ function captureRoute(handler, context = {}) {
856
932
  statusCode = 500;
857
933
  throw e;
858
934
  } finally {
859
- if (!followed) await finish();
935
+ if (!followed) {
936
+ await maybeExtractSupabaseActor();
937
+ await offTheResponse(finish);
938
+ }
860
939
  }
861
- })
940
+ }))
862
941
  );
863
942
  } catch (preCaptureError) {
864
943
  if (handlerInvoked) throw preCaptureError;
@@ -897,14 +976,21 @@ function withMiddlewareCapture(middleware) {
897
976
  }
898
977
  try {
899
978
  if (shouldEmitPageNavigation(request)) {
979
+ const durationMs = Date.now() - startMs;
900
980
  await maybeRunActorHook(request);
901
981
  await maybeExtractSupabaseActor();
902
- await emitPageNavigationEvent({
903
- request,
904
- statusCode: typeof response?.status === "number" ? response.status : null,
905
- durationMs: Date.now() - startMs,
906
- startedAt
907
- });
982
+ const event = rest[0];
983
+ await offTheResponse(
984
+ async () => {
985
+ await emitPageNavigationEvent({
986
+ request,
987
+ statusCode: typeof response?.status === "number" ? response.status : null,
988
+ durationMs,
989
+ startedAt
990
+ });
991
+ },
992
+ typeof event?.waitUntil === "function" ? event.waitUntil.bind(event) : null
993
+ );
908
994
  }
909
995
  } catch (error) {
910
996
  logger.debug(`page navigation capture failed: ${describeError5(error)}`);
@@ -1025,9 +1111,11 @@ function capturePagesApi(handler, context = {}) {
1025
1111
  const correlationId = resolveCorrelation({
1026
1112
  get: (name) => readPagesHeader(req, name)
1027
1113
  });
1114
+ const delivery = { jobDelivery: false };
1115
+ const inngestServerKind = readPagesHeader(req, INNGEST_SERVER_KIND);
1028
1116
  return await runWithCorrelation(
1029
1117
  correlationId,
1030
- () => runWithActorAndAuditScope(async () => {
1118
+ () => runWithDeliverySlot(delivery, () => runWithActorAndAuditScope(async () => {
1031
1119
  await maybeRunActorHookFromPages(req);
1032
1120
  const startMs = Date.now();
1033
1121
  let exception = null;
@@ -1039,19 +1127,32 @@ function capturePagesApi(handler, context = {}) {
1039
1127
  throw e;
1040
1128
  } finally {
1041
1129
  await maybeExtractSupabaseActor();
1130
+ const status = typeof res.statusCode === "number" ? res.statusCode : null;
1131
+ const getHeader = res.getHeader;
1132
+ const sdkHeader = typeof getHeader === "function" ? getHeader.call(res, INNGEST_SDK) : null;
1133
+ if (isJobRunnerSync(snapshot.method, inngestServerKind, sdkHeader ? String(sdkHeader) : null)) {
1134
+ delivery.jobDelivery = true;
1135
+ }
1042
1136
  await emitEvent({
1043
1137
  snapshot,
1044
1138
  context,
1045
- statusCode: typeof res.statusCode === "number" ? res.statusCode : null,
1139
+ statusCode: status,
1046
1140
  exception,
1047
1141
  graphqlErrorMessage: null,
1142
+ // NextAuth v4 under pages/api/auth: a failed sign-in redirects to ?error=.
1143
+ responseErrorMessage: authRedirectError(
1144
+ snapshot.url,
1145
+ status,
1146
+ typeof getHeader === "function" ? getHeader.call(res, "location") : null
1147
+ ),
1048
1148
  durationMs: Date.now() - startMs,
1049
- startedAt: new Date(startMs)
1149
+ startedAt: new Date(startMs),
1150
+ jobDelivery: delivery.jobDelivery
1050
1151
  });
1051
1152
  await flushOnServerless();
1052
1153
  endCorrelationScope();
1053
1154
  }
1054
- })
1155
+ }))
1055
1156
  );
1056
1157
  } catch (preCaptureError) {
1057
1158
  if (handlerInvoked) throw preCaptureError;
@@ -1082,27 +1183,21 @@ function captureServerAction(action, actionName) {
1082
1183
  const startedAt = new Date(startMs);
1083
1184
  let exception = null;
1084
1185
  await maybeRunActorHookFromServerAction();
1085
- try {
1086
- const result = await Promise.resolve(runAction(...args));
1186
+ const record = async (input) => {
1087
1187
  await maybeExtractSupabaseActor();
1088
- const failure = classifyServerActionResult(result);
1089
- await emitServerActionEvent({
1090
- actionName,
1091
- // A returned failure (`{ success: false, error }`) is a
1092
- // handled refusal, not a crash: no HTTP status is
1093
- // invented; outcome + error_message carry it.
1094
- statusCode: failure ? null : 200,
1095
- exception: failure ? new Error(failure.errorMessage) : null,
1096
- durationMs: Date.now() - startMs,
1097
- startedAt,
1098
- args
1188
+ await offTheResponse(async () => {
1189
+ await emitServerActionEvent(input);
1190
+ await flushOnServerless();
1191
+ endCorrelationScope();
1099
1192
  });
1100
- return result;
1193
+ };
1194
+ let result;
1195
+ try {
1196
+ result = await Promise.resolve(runAction(...args));
1101
1197
  } catch (e) {
1102
1198
  if (isNextControlFlowError(e)) {
1103
- await maybeExtractSupabaseActor();
1104
1199
  const controlStatus = nextControlFlowStatus(e) ?? 200;
1105
- await emitServerActionEvent({
1200
+ await record({
1106
1201
  actionName,
1107
1202
  // redirect() is a success; notFound() / forbidden()
1108
1203
  // keep their 4xx.
@@ -1116,8 +1211,7 @@ function captureServerAction(action, actionName) {
1116
1211
  throw e;
1117
1212
  }
1118
1213
  exception = e instanceof Error ? e : new Error(String(e));
1119
- await maybeExtractSupabaseActor();
1120
- await emitServerActionEvent({
1214
+ await record({
1121
1215
  actionName,
1122
1216
  statusCode: 500,
1123
1217
  exception,
@@ -1126,10 +1220,25 @@ function captureServerAction(action, actionName) {
1126
1220
  args
1127
1221
  });
1128
1222
  throw e;
1129
- } finally {
1130
- await flushOnServerless();
1131
- endCorrelationScope();
1132
1223
  }
1224
+ let failure = null;
1225
+ try {
1226
+ failure = classifyServerActionResult(result);
1227
+ } catch (e) {
1228
+ logger.debug(`server action result classification failed: ${describeError5(e)}`);
1229
+ }
1230
+ await record({
1231
+ actionName,
1232
+ // A returned failure (`{ success: false, error }`) is a
1233
+ // handled refusal, not a crash: no HTTP status is
1234
+ // invented; outcome + error_message carry it.
1235
+ statusCode: failure ? null : 200,
1236
+ exception: failure ? new Error(failure.errorMessage) : null,
1237
+ durationMs: Date.now() - startMs,
1238
+ startedAt,
1239
+ args
1240
+ });
1241
+ return result;
1133
1242
  })
1134
1243
  );
1135
1244
  } catch (preCaptureError) {
@@ -1827,9 +1936,16 @@ function readPagesHeader(req, name) {
1827
1936
  if (Array.isArray(value)) return value[0] ?? null;
1828
1937
  return null;
1829
1938
  }
1939
+ var INNGEST_SERVER_KIND = "x-inngest-server-kind";
1940
+ var INNGEST_SDK = "x-inngest-sdk";
1941
+ function isJobRunnerSync(method, inngestServerKind, sdkResponseHeader) {
1942
+ const m = (method ?? "").toUpperCase();
1943
+ return inngestServerKind !== null && sdkResponseHeader !== null && (m === "GET" || m === "PUT");
1944
+ }
1830
1945
  async function emitEvent(input) {
1831
1946
  try {
1832
1947
  await flushTriggerAuditLog();
1948
+ if (input.jobDelivery) return;
1833
1949
  const config = configuration();
1834
1950
  let graphql = null;
1835
1951
  if (input.snapshot.graphqlBody !== null) {
@@ -1941,6 +2057,26 @@ function followBody(response, method, onDone, onChunk) {
1941
2057
  return null;
1942
2058
  }
1943
2059
  }
2060
+ async function offTheResponse(work, waitUntil = null) {
2061
+ const done = work().catch((e) => logger.debug(`capture failed: ${describeError5(e)}`));
2062
+ if (!isServerless()) return;
2063
+ try {
2064
+ const keepAlive = waitUntil ?? platformWaitUntil();
2065
+ if (keepAlive) {
2066
+ keepAlive(done);
2067
+ return;
2068
+ }
2069
+ } catch (e) {
2070
+ logger.debug(`waitUntil unavailable, recording inline: ${describeError5(e)}`);
2071
+ }
2072
+ let timer;
2073
+ await Promise.race([
2074
+ done,
2075
+ new Promise((resolve) => {
2076
+ timer = setTimeout(resolve, SERVERLESS_INLINE_FLUSH_MS);
2077
+ })
2078
+ ]).finally(() => clearTimeout(timer));
2079
+ }
1944
2080
  var SERVERLESS_INLINE_FLUSH_MS = 2e3;
1945
2081
  async function flushOnServerless() {
1946
2082
  if (!isServerless()) return;
@@ -1985,7 +2121,22 @@ function buildContext() {
1985
2121
  async function flushTriggerAuditLog() {
1986
2122
  const reader = configuration().databaseReader;
1987
2123
  if (!reader) return;
1988
- await flushAuditLog(reader);
2124
+ const work = flushAuditLog(reader).catch(
2125
+ (e) => logger.debug(`trigger audit flush failed: ${describeError5(e)}`)
2126
+ );
2127
+ if (!isServerless()) return;
2128
+ const waitUntil = platformWaitUntil();
2129
+ if (waitUntil) {
2130
+ waitUntil(work.then(() => flushScheduler.flushNow()));
2131
+ return;
2132
+ }
2133
+ let timer;
2134
+ await Promise.race([
2135
+ work,
2136
+ new Promise((resolve) => {
2137
+ timer = setTimeout(resolve, SERVERLESS_INLINE_FLUSH_MS);
2138
+ })
2139
+ ]).finally(() => clearTimeout(timer));
1989
2140
  }
1990
2141
  function runWithActorAndAuditScope(callback) {
1991
2142
  if (configuration().databaseReader == null) {
@@ -2044,6 +2195,16 @@ function mergeRouteParams(rawParams, routeParams) {
2044
2195
  return { ...routeParams, ...rawParams };
2045
2196
  }
2046
2197
  var MAX_ERROR_BODY_LENGTH = 16384;
2198
+ function authRedirectError(url, status, location) {
2199
+ try {
2200
+ if (typeof status !== "number" || status < 300 || status >= 400 || !isAuthPath(url.pathname)) return null;
2201
+ if (typeof location !== "string" || !location) return null;
2202
+ const reason = new URL(location, url).searchParams.get("error");
2203
+ return reason ? capErrorText(reason) : null;
2204
+ } catch {
2205
+ return null;
2206
+ }
2207
+ }
2047
2208
  async function readResponseErrorMessage(response, trpcRoute = false) {
2048
2209
  try {
2049
2210
  if (response.status < 400 && response.status !== 207) return null;
@@ -1,9 +1,10 @@
1
1
  'use strict';
2
2
 
3
- var chunkR6IWVTX3_cjs = require('../chunk-R6IWVTX3.cjs');
4
- require('../chunk-GMHOUAKD.cjs');
5
- require('../chunk-YXZZNZG6.cjs');
6
- var chunkMMLQXSSD_cjs = require('../chunk-MMLQXSSD.cjs');
3
+ var chunkVJR4VB4B_cjs = require('../chunk-VJR4VB4B.cjs');
4
+ var chunkKOFR5OC3_cjs = require('../chunk-KOFR5OC3.cjs');
5
+ require('../chunk-EXGEA4KE.cjs');
6
+ require('../chunk-UC2KS5EG.cjs');
7
+ var chunk2YCQFLXW_cjs = require('../chunk-2YCQFLXW.cjs');
7
8
  var chunkTWTG5ILJ_cjs = require('../chunk-TWTG5ILJ.cjs');
8
9
  require('../chunk-ZDSQYCYV.cjs');
9
10
 
@@ -39,7 +40,7 @@ function wrapBullQueue(queue) {
39
40
  const wrappedAddBulk = (jobs) => {
40
41
  const stamped = jobs.map((j) => ({ ...j, data: stampPayload(j.data) }));
41
42
  const ours = stamped.map((j) => isOurs(j.data));
42
- const token = ours.includes(true) ? chunkR6IWVTX3_cjs.signedActorToken(chunkMMLQXSSD_cjs.current()) : null;
43
+ const token = ours.includes(true) ? chunkKOFR5OC3_cjs.signedActorToken(chunk2YCQFLXW_cjs.current()) : null;
43
44
  return inOrder(
44
45
  token,
45
46
  (t) => originalAddBulk(stamped.map((j, i) => ours[i] ? { ...j, data: withActor(j.data, t) } : j))
@@ -70,8 +71,10 @@ function wrapBullWorker(worker) {
70
71
  internals.processFn = function ezlogsProcess(...args) {
71
72
  const job = args[0] ?? {};
72
73
  if (typeof args[0] === "object" && args[0] !== null) reported.add(args[0]);
73
- const correlationId = chunkR6IWVTX3_cjs.extractCorrelationFromPayload(job.data);
74
- const run = (actor) => chunkR6IWVTX3_cjs.runJobWithCapture(
74
+ const correlationId = chunkKOFR5OC3_cjs.extractCorrelationFromPayload(job.data);
75
+ const token = job.data?.[chunkKOFR5OC3_cjs.ACTOR_PAYLOAD_KEY];
76
+ if (typeof args[0] === "object" && args[0] !== null) hideAgentKeys(job);
77
+ const run = (actor) => chunkKOFR5OC3_cjs.runJobWithCapture(
75
78
  {
76
79
  jobClass: job.name ?? worker.name ?? "BullMQJob",
77
80
  jobId: job.id !== void 0 && job.id !== null ? String(job.id) : null,
@@ -86,9 +89,8 @@ function wrapBullWorker(worker) {
86
89
  },
87
90
  () => Promise.resolve(original.apply(this, args))
88
91
  );
89
- const token = job.data?.[chunkR6IWVTX3_cjs.ACTOR_PAYLOAD_KEY];
90
92
  if (!correlationId || token === void 0) return run(null);
91
- return chunkR6IWVTX3_cjs.readActorToken(token, correlationId).then(run);
93
+ return chunkKOFR5OC3_cjs.readActorToken(token, correlationId).then(run);
92
94
  };
93
95
  worker.on("failed", (...args) => {
94
96
  const job = args[0];
@@ -129,10 +131,10 @@ function markWrapped(worker) {
129
131
  }
130
132
  function captureJob(job, worker, outcome, errorMessage) {
131
133
  try {
132
- const correlationId = chunkR6IWVTX3_cjs.extractCorrelationFromPayload(job.data);
134
+ const correlationId = chunkKOFR5OC3_cjs.extractCorrelationFromPayload(job.data);
133
135
  const startedAt = typeof job.timestamp === "number" ? new Date(job.timestamp) : /* @__PURE__ */ new Date();
134
136
  const durationMs = job.timestamp ? Date.now() - job.timestamp : null;
135
- chunkR6IWVTX3_cjs.emitJobEvent({
137
+ chunkKOFR5OC3_cjs.emitJobEvent({
136
138
  jobClass: job.name ?? worker.name ?? "BullMQJob",
137
139
  jobId: job.id !== void 0 && job.id !== null ? String(job.id) : null,
138
140
  queue: job.queueName ?? worker.name ?? null,
@@ -149,27 +151,53 @@ function captureJob(job, worker, outcome, errorMessage) {
149
151
  }
150
152
  }
151
153
  function pendingActorTokenFor(data) {
152
- return isOurs(data) ? chunkR6IWVTX3_cjs.signedActorToken(chunkMMLQXSSD_cjs.current()) : null;
154
+ return isOurs(data) ? chunkKOFR5OC3_cjs.signedActorToken(chunk2YCQFLXW_cjs.current()) : null;
153
155
  }
154
156
  function isOurs(data) {
155
157
  if (data === null || typeof data !== "object" || Array.isArray(data)) return false;
156
158
  const obj = data;
157
- const id = chunkMMLQXSSD_cjs.current();
158
- return Boolean(id) && obj[chunkR6IWVTX3_cjs.CORRELATION_PAYLOAD_KEY] === id && !(chunkR6IWVTX3_cjs.ACTOR_PAYLOAD_KEY in obj);
159
+ const id = chunk2YCQFLXW_cjs.current();
160
+ return Boolean(id) && obj[chunkKOFR5OC3_cjs.CORRELATION_PAYLOAD_KEY] === id && !(chunkKOFR5OC3_cjs.ACTOR_PAYLOAD_KEY in obj);
161
+ }
162
+ var AGENT_KEYS = [chunkKOFR5OC3_cjs.CORRELATION_PAYLOAD_KEY, chunkKOFR5OC3_cjs.ACTOR_PAYLOAD_KEY];
163
+ function hideAgentKeys(job) {
164
+ try {
165
+ const data = job.data;
166
+ if (data === null || typeof data !== "object" || Array.isArray(data)) return;
167
+ const carried = Object.fromEntries(AGENT_KEYS.filter((k) => k in data).map((k) => [k, data[k]]));
168
+ if (Object.keys(carried).length === 0) return;
169
+ const rest = { ...data };
170
+ for (const k of AGENT_KEYS) delete rest[k];
171
+ job.data = rest;
172
+ const save = job.updateData;
173
+ if (typeof save !== "function") return;
174
+ job.updateData = async function ezlogsUpdateData(next, ...more) {
175
+ const stamped = next !== null && typeof next === "object" && !Array.isArray(next) ? { ...carried, ...next } : next;
176
+ const result = await save.call(job, stamped, ...more);
177
+ job.data = next;
178
+ return result;
179
+ };
180
+ } catch {
181
+ }
159
182
  }
160
183
  function withActor(data, token) {
161
- return token ? { ...data, [chunkR6IWVTX3_cjs.ACTOR_PAYLOAD_KEY]: token } : data;
184
+ return token ? { ...data, [chunkKOFR5OC3_cjs.ACTOR_PAYLOAD_KEY]: token } : data;
162
185
  }
163
186
  function stampPayload(data) {
164
187
  if (data === null || typeof data !== "object" || Array.isArray(data)) {
165
188
  return data;
166
189
  }
167
- return chunkR6IWVTX3_cjs.stampCorrelationOnPayload(data, chunkR6IWVTX3_cjs.CORRELATION_PAYLOAD_KEY);
190
+ return chunkKOFR5OC3_cjs.stampCorrelationOnPayload(data, chunkKOFR5OC3_cjs.CORRELATION_PAYLOAD_KEY);
168
191
  }
169
192
  function describeError(error) {
170
193
  if (error instanceof Error) return `${error.name}: ${error.message}`;
171
194
  return String(error);
172
195
  }
196
+ var __ezlogsInstrument = chunkVJR4VB4B_cjs.instrumentFrom({
197
+ "bullmq#Queue": (original) => chunkVJR4VB4B_cjs.instrumentClass(original, (queue) => wrapBullQueue(queue)),
198
+ "bullmq#Worker": (original) => chunkVJR4VB4B_cjs.instrumentClass(original, (worker) => wrapBullWorker(worker))
199
+ });
173
200
 
201
+ exports.__ezlogsInstrument = __ezlogsInstrument;
174
202
  exports.wrapBullQueue = wrapBullQueue;
175
203
  exports.wrapBullWorker = wrapBullWorker;
@@ -38,5 +38,11 @@ declare function wrapBullQueue<T extends BullQueueLike>(queue: T): T;
38
38
  * Idempotent — calling on the same worker twice is a no-op.
39
39
  */
40
40
  declare function wrapBullWorker<T extends BullWorkerLike>(worker: T): T;
41
+ /**
42
+ * Replacements for the plugin's instrumented imports (instrument.ts):
43
+ * every Queue and Worker the app's server code constructs is wrapped.
44
+ * Internal: called by build-time generated code, not by apps.
45
+ */
46
+ declare const __ezlogsInstrument: (key: string, original: unknown) => unknown;
41
47
 
42
- export { wrapBullQueue, wrapBullWorker };
48
+ export { __ezlogsInstrument, wrapBullQueue, wrapBullWorker };
@@ -38,5 +38,11 @@ declare function wrapBullQueue<T extends BullQueueLike>(queue: T): T;
38
38
  * Idempotent — calling on the same worker twice is a no-op.
39
39
  */
40
40
  declare function wrapBullWorker<T extends BullWorkerLike>(worker: T): T;
41
+ /**
42
+ * Replacements for the plugin's instrumented imports (instrument.ts):
43
+ * every Queue and Worker the app's server code constructs is wrapped.
44
+ * Internal: called by build-time generated code, not by apps.
45
+ */
46
+ declare const __ezlogsInstrument: (key: string, original: unknown) => unknown;
41
47
 
42
- export { wrapBullQueue, wrapBullWorker };
48
+ export { __ezlogsInstrument, wrapBullQueue, wrapBullWorker };
@@ -1,7 +1,8 @@
1
- import { extractCorrelationFromPayload, ACTOR_PAYLOAD_KEY, readActorToken, emitJobEvent, signedActorToken, CORRELATION_PAYLOAD_KEY, stampCorrelationOnPayload, runJobWithCapture } from '../chunk-U22T7QYY.js';
2
- import '../chunk-MHBS5FEP.js';
3
- import '../chunk-NINIAL7M.js';
4
- import { current } from '../chunk-GI6BM4MR.js';
1
+ import { instrumentFrom, instrumentClass } from '../chunk-JWJKFZBW.js';
2
+ import { extractCorrelationFromPayload, ACTOR_PAYLOAD_KEY, readActorToken, CORRELATION_PAYLOAD_KEY, runJobWithCapture, emitJobEvent, stampCorrelationOnPayload, signedActorToken } from '../chunk-Q3HRVWCS.js';
3
+ import '../chunk-CYAFYBKF.js';
4
+ import '../chunk-AXIQTU52.js';
5
+ import { current } from '../chunk-7MFKEYDN.js';
5
6
  import { logger } from '../chunk-FCFVIRQF.js';
6
7
  import '../chunk-SIAA4J6H.js';
7
8
 
@@ -69,6 +70,8 @@ function wrapBullWorker(worker) {
69
70
  const job = args[0] ?? {};
70
71
  if (typeof args[0] === "object" && args[0] !== null) reported.add(args[0]);
71
72
  const correlationId = extractCorrelationFromPayload(job.data);
73
+ const token = job.data?.[ACTOR_PAYLOAD_KEY];
74
+ if (typeof args[0] === "object" && args[0] !== null) hideAgentKeys(job);
72
75
  const run = (actor) => runJobWithCapture(
73
76
  {
74
77
  jobClass: job.name ?? worker.name ?? "BullMQJob",
@@ -84,7 +87,6 @@ function wrapBullWorker(worker) {
84
87
  },
85
88
  () => Promise.resolve(original.apply(this, args))
86
89
  );
87
- const token = job.data?.[ACTOR_PAYLOAD_KEY];
88
90
  if (!correlationId || token === void 0) return run(null);
89
91
  return readActorToken(token, correlationId).then(run);
90
92
  };
@@ -155,6 +157,27 @@ function isOurs(data) {
155
157
  const id = current();
156
158
  return Boolean(id) && obj[CORRELATION_PAYLOAD_KEY] === id && !(ACTOR_PAYLOAD_KEY in obj);
157
159
  }
160
+ var AGENT_KEYS = [CORRELATION_PAYLOAD_KEY, ACTOR_PAYLOAD_KEY];
161
+ function hideAgentKeys(job) {
162
+ try {
163
+ const data = job.data;
164
+ if (data === null || typeof data !== "object" || Array.isArray(data)) return;
165
+ const carried = Object.fromEntries(AGENT_KEYS.filter((k) => k in data).map((k) => [k, data[k]]));
166
+ if (Object.keys(carried).length === 0) return;
167
+ const rest = { ...data };
168
+ for (const k of AGENT_KEYS) delete rest[k];
169
+ job.data = rest;
170
+ const save = job.updateData;
171
+ if (typeof save !== "function") return;
172
+ job.updateData = async function ezlogsUpdateData(next, ...more) {
173
+ const stamped = next !== null && typeof next === "object" && !Array.isArray(next) ? { ...carried, ...next } : next;
174
+ const result = await save.call(job, stamped, ...more);
175
+ job.data = next;
176
+ return result;
177
+ };
178
+ } catch {
179
+ }
180
+ }
158
181
  function withActor(data, token) {
159
182
  return token ? { ...data, [ACTOR_PAYLOAD_KEY]: token } : data;
160
183
  }
@@ -168,5 +191,9 @@ function describeError(error) {
168
191
  if (error instanceof Error) return `${error.name}: ${error.message}`;
169
192
  return String(error);
170
193
  }
194
+ var __ezlogsInstrument = instrumentFrom({
195
+ "bullmq#Queue": (original) => instrumentClass(original, (queue) => wrapBullQueue(queue)),
196
+ "bullmq#Worker": (original) => instrumentClass(original, (worker) => wrapBullWorker(worker))
197
+ });
171
198
 
172
- export { wrapBullQueue, wrapBullWorker };
199
+ export { __ezlogsInstrument, wrapBullQueue, wrapBullWorker };