ezlogs-nextjs 0.3.1 → 0.4.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.
Files changed (76) hide show
  1. package/README.md +149 -30
  2. package/bin/install-triggers.cjs +7 -2
  3. package/dist/actors/index.cjs +4 -4
  4. package/dist/actors/index.d.cts +1 -1
  5. package/dist/actors/index.d.ts +1 -1
  6. package/dist/actors/index.js +1 -1
  7. package/dist/{chunk-C5OSM557.js → chunk-FCFVIRQF.js} +7 -0
  8. package/dist/chunk-GI6BM4MR.js +443 -0
  9. package/dist/{chunk-YX2XPLOA.cjs → chunk-GMHOUAKD.cjs} +63 -34
  10. package/dist/{chunk-CU45I2WR.js → chunk-MHBS5FEP.js} +48 -20
  11. package/dist/chunk-MMLQXSSD.cjs +461 -0
  12. package/dist/{chunk-CE3R7DVB.js → chunk-NINIAL7M.js} +60 -384
  13. package/dist/{chunk-Y5NSHKWQ.cjs → chunk-NX4EL7BY.cjs} +57 -7
  14. package/dist/chunk-PS4U2GFJ.cjs +52 -0
  15. package/dist/chunk-R6IWVTX3.cjs +212 -0
  16. package/dist/{chunk-V5YNKKTG.cjs → chunk-TWTG5ILJ.cjs} +7 -0
  17. package/dist/chunk-U22T7QYY.js +200 -0
  18. package/dist/chunk-YMIGZYFH.js +48 -0
  19. package/dist/{chunk-WASXTDLW.cjs → chunk-YXZZNZG6.cjs} +71 -403
  20. package/dist/{chunk-DKRNNI4I.js → chunk-Z2TM3LGG.js} +53 -3
  21. package/dist/{configuration-OHLNivON.d.ts → configuration-CJ5yKVlP.d.cts} +14 -8
  22. package/dist/{configuration-OHLNivON.d.cts → configuration-CJ5yKVlP.d.ts} +14 -8
  23. package/dist/db/drizzle.cjs +5 -4
  24. package/dist/db/drizzle.js +3 -2
  25. package/dist/db/postgres-js.cjs +98 -0
  26. package/dist/db/postgres-js.d.cts +11 -0
  27. package/dist/db/postgres-js.d.ts +11 -0
  28. package/dist/db/postgres-js.js +95 -0
  29. package/dist/db/prisma.cjs +21 -20
  30. package/dist/db/prisma.d.cts +19 -2
  31. package/dist/db/prisma.d.ts +19 -2
  32. package/dist/db/prisma.js +6 -5
  33. package/dist/db/supabase.cjs +19 -12
  34. package/dist/db/supabase.d.cts +3 -2
  35. package/dist/db/supabase.d.ts +3 -2
  36. package/dist/db/supabase.js +11 -4
  37. package/dist/index.cjs +596 -165
  38. package/dist/index.d.cts +5 -3
  39. package/dist/index.d.ts +5 -3
  40. package/dist/index.js +492 -62
  41. package/dist/jobs/bullmq.cjs +63 -18
  42. package/dist/jobs/bullmq.d.cts +0 -4
  43. package/dist/jobs/bullmq.d.ts +0 -4
  44. package/dist/jobs/bullmq.js +59 -14
  45. package/dist/jobs/inngest.cjs +61 -24
  46. package/dist/jobs/inngest.d.cts +5 -1
  47. package/dist/jobs/inngest.d.ts +5 -1
  48. package/dist/jobs/inngest.js +55 -18
  49. package/dist/jobs/supabase-queues.cjs +17 -15
  50. package/dist/jobs/supabase-queues.d.cts +1 -1
  51. package/dist/jobs/supabase-queues.d.ts +1 -1
  52. package/dist/jobs/supabase-queues.js +15 -13
  53. package/dist/jobs/trigger.cjs +11 -12
  54. package/dist/jobs/trigger.d.cts +4 -3
  55. package/dist/jobs/trigger.d.ts +4 -3
  56. package/dist/jobs/trigger.js +7 -8
  57. package/dist/jobs/upstash-workflow.cjs +43 -35
  58. package/dist/jobs/upstash-workflow.d.cts +2 -8
  59. package/dist/jobs/upstash-workflow.d.ts +2 -8
  60. package/dist/jobs/upstash-workflow.js +38 -30
  61. package/dist/nextjs-plugin/index.cjs +39 -3
  62. package/dist/nextjs-plugin/index.d.cts +8 -1
  63. package/dist/nextjs-plugin/index.d.ts +8 -1
  64. package/dist/nextjs-plugin/index.js +39 -3
  65. package/dist/nextjs-plugin/loader.cjs +41 -3
  66. package/dist/nextjs-plugin/loader.d.cts +1 -0
  67. package/dist/nextjs-plugin/loader.d.ts +1 -0
  68. package/dist/nextjs-plugin/loader.js +42 -4
  69. package/dist/triggers/index.cjs +145 -92
  70. package/dist/triggers/index.d.cts +20 -5
  71. package/dist/triggers/index.d.ts +20 -5
  72. package/dist/triggers/index.js +125 -82
  73. package/package.json +11 -1
  74. package/sql/postgres/00_install.sql +1 -1
  75. package/dist/chunk-UQHEW6ER.js +0 -119
  76. package/dist/chunk-UWHYJH4M.cjs +0 -126
@@ -30,7 +30,7 @@ declare function captureQueueMessage<T>(meta: {
30
30
  /**
31
31
  * Imperatively stamp the correlation id onto a pgmq message body
32
32
  * before passing it to a non-wrapped client. Available for users
33
- * who want explicit control.
33
+ * who want explicit control. Returns a stamped copy; send that one.
34
34
  */
35
35
  declare function stampPgmqPayload(message: unknown): unknown;
36
36
 
@@ -1,7 +1,8 @@
1
- import { extractCorrelationFromPayload, runJobWithCapture, stampCorrelationOnPayload } from '../chunk-UQHEW6ER.js';
2
- import '../chunk-CU45I2WR.js';
3
- import '../chunk-CE3R7DVB.js';
4
- import '../chunk-C5OSM557.js';
1
+ import { extractCorrelationFromPayload, runJobWithCapture, stampCorrelationOnPayload } from '../chunk-U22T7QYY.js';
2
+ import '../chunk-MHBS5FEP.js';
3
+ import '../chunk-NINIAL7M.js';
4
+ import '../chunk-GI6BM4MR.js';
5
+ import '../chunk-FCFVIRQF.js';
5
6
  import '../chunk-SIAA4J6H.js';
6
7
 
7
8
  // src/jobs/supabase-queues.ts
@@ -38,13 +39,15 @@ function wrapPgmqSchema(schema) {
38
39
  }
39
40
  function stampPgmqMessage(args) {
40
41
  if ("message" in args && isPlainObject(args.message)) {
41
- stampCorrelationOnPayload(args.message);
42
- } else if (Array.isArray(args.messages)) {
43
- for (const msg of args.messages) {
44
- if (isPlainObject(msg)) {
45
- stampCorrelationOnPayload(msg);
46
- }
47
- }
42
+ return { ...args, message: stampCorrelationOnPayload(args.message) };
43
+ }
44
+ if (Array.isArray(args.messages)) {
45
+ return {
46
+ ...args,
47
+ messages: args.messages.map(
48
+ (msg) => isPlainObject(msg) ? stampCorrelationOnPayload(msg) : msg
49
+ )
50
+ };
48
51
  }
49
52
  return args;
50
53
  }
@@ -64,8 +67,7 @@ async function captureQueueMessage(meta, work) {
64
67
  }
65
68
  function stampPgmqPayload(message) {
66
69
  if (!isPlainObject(message)) return message;
67
- stampCorrelationOnPayload(message);
68
- return message;
70
+ return stampCorrelationOnPayload(message);
69
71
  }
70
72
  function isPlainObject(value) {
71
73
  if (value === null || typeof value !== "object") return false;
@@ -1,9 +1,10 @@
1
1
  'use strict';
2
2
 
3
- var chunkUWHYJH4M_cjs = require('../chunk-UWHYJH4M.cjs');
4
- require('../chunk-YX2XPLOA.cjs');
5
- var chunkWASXTDLW_cjs = require('../chunk-WASXTDLW.cjs');
6
- var chunkV5YNKKTG_cjs = require('../chunk-V5YNKKTG.cjs');
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');
7
+ var chunkTWTG5ILJ_cjs = require('../chunk-TWTG5ILJ.cjs');
7
8
  require('../chunk-ZDSQYCYV.cjs');
8
9
 
9
10
  // src/jobs/trigger.ts
@@ -11,7 +12,7 @@ var REGISTERED_FLAG = "__ezlogsTriggerRegistered";
11
12
  function registerTriggerHooks(tasks) {
12
13
  if (tasks[REGISTERED_FLAG]) return;
13
14
  if (typeof tasks.middleware !== "function") {
14
- chunkV5YNKKTG_cjs.logger.debug("trigger.dev tasks.middleware not available \u2014 adapter not registered");
15
+ chunkTWTG5ILJ_cjs.logger.debug("trigger.dev tasks.middleware not available \u2014 adapter not registered");
15
16
  return;
16
17
  }
17
18
  tasks.middleware("ezlogs", async (params) => {
@@ -30,29 +31,27 @@ async function runWithEzlogsCapture(params) {
30
31
  const queueName = ctx.run?.queue?.name ?? null;
31
32
  const attemptNumber = ctx.attempt?.number ?? 1;
32
33
  const retryCount = Math.max(0, attemptNumber - 1);
33
- return chunkUWHYJH4M_cjs.runJobWithCapture(
34
+ return chunkR6IWVTX3_cjs.runJobWithCapture(
34
35
  {
35
36
  jobClass: taskId,
36
37
  jobId: runId,
37
38
  queue: queueName,
38
39
  retryCount,
39
- correlationId: chunkUWHYJH4M_cjs.extractCorrelationFromPayload(params.payload),
40
+ correlationId: chunkR6IWVTX3_cjs.extractCorrelationFromPayload(params.payload),
40
41
  payload: params.payload
41
42
  },
42
43
  () => params.next()
43
44
  );
44
45
  }
45
46
  function stampPayloadForTrigger(payload) {
46
- const id = chunkWASXTDLW_cjs.current();
47
+ const id = chunkMMLQXSSD_cjs.current();
47
48
  if (!id) return payload;
48
49
  if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
49
50
  return payload;
50
51
  }
51
52
  const obj = payload;
52
- if (typeof obj.ezlogs_correlation_id !== "string" || !obj.ezlogs_correlation_id) {
53
- obj.ezlogs_correlation_id = id;
54
- }
55
- return obj;
53
+ if (typeof obj.ezlogs_correlation_id === "string" && obj.ezlogs_correlation_id) return obj;
54
+ return { ...obj, ezlogs_correlation_id: id };
56
55
  }
57
56
 
58
57
  exports.registerTriggerHooks = registerTriggerHooks;
@@ -36,10 +36,11 @@ declare function registerTriggerHooks(tasks: TriggerTasksLike): void;
36
36
  * call to the Trigger.dev API server, but only the receiving
37
37
  * task's middleware sees that — not the payload's data slot),
38
38
  * OR
39
- * 2. Call `stampPayloadForTrigger(payload)` themselves before
40
- * invoking trigger().
39
+ * 2. Call `stampPayloadForTrigger(payload)` themselves and pass
40
+ * the returned payload to trigger().
41
41
  *
42
- * This helper exists for case 2.
42
+ * This helper exists for case 2. It returns a stamped copy; the
43
+ * payload passed in is not modified.
43
44
  */
44
45
  declare function stampPayloadForTrigger(payload: unknown): unknown;
45
46
 
@@ -36,10 +36,11 @@ declare function registerTriggerHooks(tasks: TriggerTasksLike): void;
36
36
  * call to the Trigger.dev API server, but only the receiving
37
37
  * task's middleware sees that — not the payload's data slot),
38
38
  * OR
39
- * 2. Call `stampPayloadForTrigger(payload)` themselves before
40
- * invoking trigger().
39
+ * 2. Call `stampPayloadForTrigger(payload)` themselves and pass
40
+ * the returned payload to trigger().
41
41
  *
42
- * This helper exists for case 2.
42
+ * This helper exists for case 2. It returns a stamped copy; the
43
+ * payload passed in is not modified.
43
44
  */
44
45
  declare function stampPayloadForTrigger(payload: unknown): unknown;
45
46
 
@@ -1,7 +1,8 @@
1
- import { runJobWithCapture, extractCorrelationFromPayload } from '../chunk-UQHEW6ER.js';
2
- import '../chunk-CU45I2WR.js';
3
- import { current } from '../chunk-CE3R7DVB.js';
4
- import { logger } from '../chunk-C5OSM557.js';
1
+ import { runJobWithCapture, extractCorrelationFromPayload } from '../chunk-U22T7QYY.js';
2
+ import '../chunk-MHBS5FEP.js';
3
+ import '../chunk-NINIAL7M.js';
4
+ import { current } from '../chunk-GI6BM4MR.js';
5
+ import { logger } from '../chunk-FCFVIRQF.js';
5
6
  import '../chunk-SIAA4J6H.js';
6
7
 
7
8
  // src/jobs/trigger.ts
@@ -47,10 +48,8 @@ function stampPayloadForTrigger(payload) {
47
48
  return payload;
48
49
  }
49
50
  const obj = payload;
50
- if (typeof obj.ezlogs_correlation_id !== "string" || !obj.ezlogs_correlation_id) {
51
- obj.ezlogs_correlation_id = id;
52
- }
53
- return obj;
51
+ if (typeof obj.ezlogs_correlation_id === "string" && obj.ezlogs_correlation_id) return obj;
52
+ return { ...obj, ezlogs_correlation_id: id };
54
53
  }
55
54
 
56
55
  export { registerTriggerHooks, stampPayloadForTrigger };
@@ -1,9 +1,10 @@
1
1
  'use strict';
2
2
 
3
- var chunkUWHYJH4M_cjs = require('../chunk-UWHYJH4M.cjs');
4
- require('../chunk-YX2XPLOA.cjs');
5
- var chunkWASXTDLW_cjs = require('../chunk-WASXTDLW.cjs');
6
- var chunkV5YNKKTG_cjs = require('../chunk-V5YNKKTG.cjs');
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');
7
+ var chunkTWTG5ILJ_cjs = require('../chunk-TWTG5ILJ.cjs');
7
8
  require('../chunk-ZDSQYCYV.cjs');
8
9
 
9
10
  // src/jobs/upstash-workflow.ts
@@ -11,7 +12,8 @@ var FORWARD_PREFIX = "upstash-forward-";
11
12
  var CORRELATION_HEADER = "x-ezlogs-correlation-id";
12
13
  var LEGACY_CORRELATION_HEADER = "x-correlation-id";
13
14
  var AGENT_CORRELATION_ID = /^ezl_(\d{13})_[0-9a-f]{8}$/;
14
- var AGENT_RUN_ID = /^wfr_(ezl_\d{13}_[0-9a-f]{8})_[0-9a-f]{24}$/;
15
+ var AGENT_RUN_ID = /^wfr_(ezl_\d{13}_[0-9a-f]{8})_[0-9a-f]{24}(?:_(a[0-9a-f]{2,128}_[0-9a-f]{16}))?$/;
16
+ var ACTOR_HEADER = "x-ezlogs-actor";
15
17
  var RUN_ID_SUFFIX_BYTES = 12;
16
18
  var STEP_ID_MAX_AGE_MS = 24 * 60 * 6e4;
17
19
  function isAcceptableStepId(value) {
@@ -26,7 +28,12 @@ function wrapWorkflowClient(client) {
26
28
  if (client[WORKFLOW_WRAPPED_FLAG]) return client;
27
29
  if (typeof client.trigger === "function") {
28
30
  const original = client.trigger.bind(client);
29
- client.trigger = (params) => original(Array.isArray(params) ? params.map(stampTriggerOptions) : stampTriggerOptions(params));
31
+ client.trigger = async (params) => {
32
+ if (chunkMMLQXSSD_cjs.current()) await chunkMMLQXSSD_cjs.maybeExtractSupabaseActor();
33
+ return original(
34
+ Array.isArray(params) ? await Promise.all(params.map(stampTriggerOptions)) : await stampTriggerOptions(params)
35
+ );
36
+ };
30
37
  }
31
38
  Object.defineProperty(client, WORKFLOW_WRAPPED_FLAG, {
32
39
  value: true,
@@ -35,31 +42,30 @@ function wrapWorkflowClient(client) {
35
42
  });
36
43
  return client;
37
44
  }
38
- function stampTriggerOptions(options) {
39
- const current2 = chunkWASXTDLW_cjs.current();
45
+ async function stampTriggerOptions(options) {
46
+ const current2 = chunkMMLQXSSD_cjs.current();
40
47
  if (!current2 || !options || typeof options !== "object") return options;
41
48
  const opts = options;
42
49
  const headers = { ...opts.headers ?? {} };
43
50
  const supplied = Object.keys(headers).find((k) => k.toLowerCase() === CORRELATION_HEADER);
44
51
  const id = supplied ? headers[supplied] : current2;
45
52
  if (!supplied) headers[CORRELATION_HEADER] = id;
53
+ const token = AGENT_CORRELATION_ID.test(id) ? await chunkR6IWVTX3_cjs.actorToken(id) : null;
54
+ if (token && !Object.keys(headers).some((k) => k.toLowerCase() === ACTOR_HEADER)) {
55
+ headers[ACTOR_HEADER] = token;
56
+ }
46
57
  const stamped = { ...opts, headers };
47
58
  if (opts.workflowRunId == null && AGENT_CORRELATION_ID.test(id)) {
48
- stamped.workflowRunId = `${id}_${randomHex(RUN_ID_SUFFIX_BYTES)}`;
59
+ stamped.workflowRunId = `${id}_${randomHex(RUN_ID_SUFFIX_BYTES)}${token ? `_${token}` : ""}`;
49
60
  }
50
61
  return stamped;
51
62
  }
52
63
  function wrapQStashClient(client) {
53
64
  if (client[WRAPPED_FLAG]) return client;
54
- if (typeof client.publishJSON === "function") {
55
- const original = client.publishJSON.bind(client);
56
- const wrapped = (request) => original(stampPublishRequest(request));
57
- client.publishJSON = wrapped;
58
- }
59
- if (typeof client.publish === "function") {
60
- const original = client.publish.bind(client);
61
- const wrapped = (request) => original(stampPublishRequest(request));
62
- client.publish = wrapped;
65
+ for (const method of ["publishJSON", "publish"]) {
66
+ if (typeof client[method] !== "function") continue;
67
+ const original = client[method].bind(client);
68
+ client[method] = async (request) => original(await stampPublishRequest(request));
63
69
  }
64
70
  Object.defineProperty(client, WRAPPED_FLAG, {
65
71
  value: true,
@@ -68,20 +74,17 @@ function wrapQStashClient(client) {
68
74
  });
69
75
  return client;
70
76
  }
71
- function stampPublishRequest(request) {
72
- const id = chunkWASXTDLW_cjs.current();
73
- if (!id) return request;
77
+ async function stampPublishRequest(request) {
78
+ const id = chunkMMLQXSSD_cjs.current();
79
+ if (!id || !request || typeof request !== "object") return request;
74
80
  const headerKey = `${FORWARD_PREFIX}${CORRELATION_HEADER}`;
75
- const headers = { ...request.headers ?? {} };
76
- const lower = Object.keys(headers).reduce(
77
- (acc, key) => {
78
- acc[key.toLowerCase()] = key;
79
- return acc;
80
- },
81
- {}
82
- );
83
- if (lower[headerKey]) return request;
81
+ const raw = request.headers;
82
+ const headers = raw instanceof Headers || Array.isArray(raw) ? Object.fromEntries(new Headers(raw)) : { ...raw ?? {} };
83
+ if (Object.keys(headers).some((key) => key.toLowerCase() === headerKey)) return request;
84
84
  headers[headerKey] = id;
85
+ await chunkMMLQXSSD_cjs.maybeExtractSupabaseActor();
86
+ const token = await chunkR6IWVTX3_cjs.actorToken(id);
87
+ if (token) headers[`${FORWARD_PREFIX}${ACTOR_HEADER}`] = token;
85
88
  return { ...request, headers };
86
89
  }
87
90
  async function captureWorkflowRequest(meta, work) {
@@ -89,13 +92,18 @@ async function captureWorkflowRequest(meta, work) {
89
92
  const correlationId = readCorrelationFromHeaders(headers);
90
93
  const runId = readHeader(headers, "upstash-workflow-runid");
91
94
  const retried = parseRetried(readHeader(headers, "upstash-retried"));
92
- return chunkUWHYJH4M_cjs.runJobWithCapture(
95
+ const actor = correlationId ? await chunkR6IWVTX3_cjs.readActorToken(
96
+ readHeader(headers, ACTOR_HEADER) ?? readHeader(headers, `${FORWARD_PREFIX}${ACTOR_HEADER}`),
97
+ correlationId
98
+ ) ?? await chunkR6IWVTX3_cjs.readActorToken(runId ? AGENT_RUN_ID.exec(runId)?.[2] : null, correlationId) : null;
99
+ return chunkR6IWVTX3_cjs.runJobWithCapture(
93
100
  {
94
101
  jobClass: meta.workflowName,
95
102
  jobId: runId,
96
103
  queue: meta.stepName ?? meta.workflowName,
97
104
  retryCount: retried,
98
- correlationId
105
+ correlationId,
106
+ actor
99
107
  },
100
108
  work
101
109
  );
@@ -103,7 +111,7 @@ async function captureWorkflowRequest(meta, work) {
103
111
  function emitUpstashWorkflowEvent(input) {
104
112
  try {
105
113
  const headers = input.request.headers;
106
- chunkUWHYJH4M_cjs.emitJobEvent({
114
+ chunkR6IWVTX3_cjs.emitJobEvent({
107
115
  jobClass: input.workflowName,
108
116
  jobId: readHeader(headers, "upstash-workflow-runid"),
109
117
  queue: input.workflowName,
@@ -115,13 +123,13 @@ function emitUpstashWorkflowEvent(input) {
115
123
  startedAt: input.startedAt ?? /* @__PURE__ */ new Date()
116
124
  });
117
125
  } catch (error) {
118
- chunkV5YNKKTG_cjs.logger.debug(`upstash workflow capture failed: ${describeError(error)}`);
126
+ chunkTWTG5ILJ_cjs.logger.debug(`upstash workflow capture failed: ${describeError(error)}`);
119
127
  }
120
128
  }
121
129
  function randomHex(bytes) {
122
130
  const buf = new Uint8Array(bytes);
123
131
  globalThis.crypto.getRandomValues(buf);
124
- return Array.from(buf, (b) => b.toString(16).padStart(2, "0")).join("");
132
+ return chunkR6IWVTX3_cjs.toHex(buf);
125
133
  }
126
134
  function readHeader(headers, name) {
127
135
  try {
@@ -1,12 +1,6 @@
1
1
  interface QStashClientLike {
2
- publishJSON?: (request: QStashPublishRequest) => Promise<unknown>;
3
- publish?: (request: QStashPublishRequest) => Promise<unknown>;
4
- }
5
- interface QStashPublishRequest {
6
- url?: string;
7
- topic?: string;
8
- body?: unknown;
9
- headers?: Record<string, string>;
2
+ publishJSON?: Function;
3
+ publish?: Function;
10
4
  }
11
5
  interface WorkflowClientLike {
12
6
  trigger?: Function;
@@ -1,12 +1,6 @@
1
1
  interface QStashClientLike {
2
- publishJSON?: (request: QStashPublishRequest) => Promise<unknown>;
3
- publish?: (request: QStashPublishRequest) => Promise<unknown>;
4
- }
5
- interface QStashPublishRequest {
6
- url?: string;
7
- topic?: string;
8
- body?: unknown;
9
- headers?: Record<string, string>;
2
+ publishJSON?: Function;
3
+ publish?: Function;
10
4
  }
11
5
  interface WorkflowClientLike {
12
6
  trigger?: Function;
@@ -1,7 +1,8 @@
1
- import { runJobWithCapture, emitJobEvent } from '../chunk-UQHEW6ER.js';
2
- import '../chunk-CU45I2WR.js';
3
- import { current } from '../chunk-CE3R7DVB.js';
4
- import { logger } from '../chunk-C5OSM557.js';
1
+ import { actorToken, readActorToken, runJobWithCapture, emitJobEvent, toHex } from '../chunk-U22T7QYY.js';
2
+ import '../chunk-MHBS5FEP.js';
3
+ import '../chunk-NINIAL7M.js';
4
+ import { current, maybeExtractSupabaseActor } from '../chunk-GI6BM4MR.js';
5
+ import { logger } from '../chunk-FCFVIRQF.js';
5
6
  import '../chunk-SIAA4J6H.js';
6
7
 
7
8
  // src/jobs/upstash-workflow.ts
@@ -9,7 +10,8 @@ var FORWARD_PREFIX = "upstash-forward-";
9
10
  var CORRELATION_HEADER = "x-ezlogs-correlation-id";
10
11
  var LEGACY_CORRELATION_HEADER = "x-correlation-id";
11
12
  var AGENT_CORRELATION_ID = /^ezl_(\d{13})_[0-9a-f]{8}$/;
12
- var AGENT_RUN_ID = /^wfr_(ezl_\d{13}_[0-9a-f]{8})_[0-9a-f]{24}$/;
13
+ var AGENT_RUN_ID = /^wfr_(ezl_\d{13}_[0-9a-f]{8})_[0-9a-f]{24}(?:_(a[0-9a-f]{2,128}_[0-9a-f]{16}))?$/;
14
+ var ACTOR_HEADER = "x-ezlogs-actor";
13
15
  var RUN_ID_SUFFIX_BYTES = 12;
14
16
  var STEP_ID_MAX_AGE_MS = 24 * 60 * 6e4;
15
17
  function isAcceptableStepId(value) {
@@ -24,7 +26,12 @@ function wrapWorkflowClient(client) {
24
26
  if (client[WORKFLOW_WRAPPED_FLAG]) return client;
25
27
  if (typeof client.trigger === "function") {
26
28
  const original = client.trigger.bind(client);
27
- client.trigger = (params) => original(Array.isArray(params) ? params.map(stampTriggerOptions) : stampTriggerOptions(params));
29
+ client.trigger = async (params) => {
30
+ if (current()) await maybeExtractSupabaseActor();
31
+ return original(
32
+ Array.isArray(params) ? await Promise.all(params.map(stampTriggerOptions)) : await stampTriggerOptions(params)
33
+ );
34
+ };
28
35
  }
29
36
  Object.defineProperty(client, WORKFLOW_WRAPPED_FLAG, {
30
37
  value: true,
@@ -33,7 +40,7 @@ function wrapWorkflowClient(client) {
33
40
  });
34
41
  return client;
35
42
  }
36
- function stampTriggerOptions(options) {
43
+ async function stampTriggerOptions(options) {
37
44
  const current2 = current();
38
45
  if (!current2 || !options || typeof options !== "object") return options;
39
46
  const opts = options;
@@ -41,23 +48,22 @@ function stampTriggerOptions(options) {
41
48
  const supplied = Object.keys(headers).find((k) => k.toLowerCase() === CORRELATION_HEADER);
42
49
  const id = supplied ? headers[supplied] : current2;
43
50
  if (!supplied) headers[CORRELATION_HEADER] = id;
51
+ const token = AGENT_CORRELATION_ID.test(id) ? await actorToken(id) : null;
52
+ if (token && !Object.keys(headers).some((k) => k.toLowerCase() === ACTOR_HEADER)) {
53
+ headers[ACTOR_HEADER] = token;
54
+ }
44
55
  const stamped = { ...opts, headers };
45
56
  if (opts.workflowRunId == null && AGENT_CORRELATION_ID.test(id)) {
46
- stamped.workflowRunId = `${id}_${randomHex(RUN_ID_SUFFIX_BYTES)}`;
57
+ stamped.workflowRunId = `${id}_${randomHex(RUN_ID_SUFFIX_BYTES)}${token ? `_${token}` : ""}`;
47
58
  }
48
59
  return stamped;
49
60
  }
50
61
  function wrapQStashClient(client) {
51
62
  if (client[WRAPPED_FLAG]) return client;
52
- if (typeof client.publishJSON === "function") {
53
- const original = client.publishJSON.bind(client);
54
- const wrapped = (request) => original(stampPublishRequest(request));
55
- client.publishJSON = wrapped;
56
- }
57
- if (typeof client.publish === "function") {
58
- const original = client.publish.bind(client);
59
- const wrapped = (request) => original(stampPublishRequest(request));
60
- client.publish = wrapped;
63
+ for (const method of ["publishJSON", "publish"]) {
64
+ if (typeof client[method] !== "function") continue;
65
+ const original = client[method].bind(client);
66
+ client[method] = async (request) => original(await stampPublishRequest(request));
61
67
  }
62
68
  Object.defineProperty(client, WRAPPED_FLAG, {
63
69
  value: true,
@@ -66,20 +72,17 @@ function wrapQStashClient(client) {
66
72
  });
67
73
  return client;
68
74
  }
69
- function stampPublishRequest(request) {
75
+ async function stampPublishRequest(request) {
70
76
  const id = current();
71
- if (!id) return request;
77
+ if (!id || !request || typeof request !== "object") return request;
72
78
  const headerKey = `${FORWARD_PREFIX}${CORRELATION_HEADER}`;
73
- const headers = { ...request.headers ?? {} };
74
- const lower = Object.keys(headers).reduce(
75
- (acc, key) => {
76
- acc[key.toLowerCase()] = key;
77
- return acc;
78
- },
79
- {}
80
- );
81
- if (lower[headerKey]) return request;
79
+ const raw = request.headers;
80
+ const headers = raw instanceof Headers || Array.isArray(raw) ? Object.fromEntries(new Headers(raw)) : { ...raw ?? {} };
81
+ if (Object.keys(headers).some((key) => key.toLowerCase() === headerKey)) return request;
82
82
  headers[headerKey] = id;
83
+ await maybeExtractSupabaseActor();
84
+ const token = await actorToken(id);
85
+ if (token) headers[`${FORWARD_PREFIX}${ACTOR_HEADER}`] = token;
83
86
  return { ...request, headers };
84
87
  }
85
88
  async function captureWorkflowRequest(meta, work) {
@@ -87,13 +90,18 @@ async function captureWorkflowRequest(meta, work) {
87
90
  const correlationId = readCorrelationFromHeaders(headers);
88
91
  const runId = readHeader(headers, "upstash-workflow-runid");
89
92
  const retried = parseRetried(readHeader(headers, "upstash-retried"));
93
+ const actor = correlationId ? await readActorToken(
94
+ readHeader(headers, ACTOR_HEADER) ?? readHeader(headers, `${FORWARD_PREFIX}${ACTOR_HEADER}`),
95
+ correlationId
96
+ ) ?? await readActorToken(runId ? AGENT_RUN_ID.exec(runId)?.[2] : null, correlationId) : null;
90
97
  return runJobWithCapture(
91
98
  {
92
99
  jobClass: meta.workflowName,
93
100
  jobId: runId,
94
101
  queue: meta.stepName ?? meta.workflowName,
95
102
  retryCount: retried,
96
- correlationId
103
+ correlationId,
104
+ actor
97
105
  },
98
106
  work
99
107
  );
@@ -119,7 +127,7 @@ function emitUpstashWorkflowEvent(input) {
119
127
  function randomHex(bytes) {
120
128
  const buf = new Uint8Array(bytes);
121
129
  globalThis.crypto.getRandomValues(buf);
122
- return Array.from(buf, (b) => b.toString(16).padStart(2, "0")).join("");
130
+ return toHex(buf);
123
131
  }
124
132
  function readHeader(headers, name) {
125
133
  try {
@@ -2,6 +2,8 @@
2
2
 
3
3
  require('../chunk-ZDSQYCYV.cjs');
4
4
  var path = require('path');
5
+ var fs = require('fs');
6
+ var module$1 = require('module');
5
7
  var url = require('url');
6
8
 
7
9
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
@@ -14,7 +16,8 @@ var INLINE_ROUTE_FILENAMES = [
14
16
  "default",
15
17
  "not-found"
16
18
  ];
17
- function withEzlogsConfig(nextConfig = {}) {
19
+ function withEzlogsConfig(userConfig) {
20
+ const nextConfig = userConfig ?? {};
18
21
  const userWebpack = nextConfig.webpack;
19
22
  const loaderPath = resolveLoaderPath();
20
23
  return {
@@ -36,7 +39,8 @@ function withEzlogsConfig(nextConfig = {}) {
36
39
  if (!options.isServer) return merged;
37
40
  return installLoaders(merged, options);
38
41
  },
39
- turbopack: mergeTurbopackConfig(nextConfig.turbopack, loaderPath)
42
+ // Next loads next.config from the project directory.
43
+ turbopack: mergeTurbopackConfig(nextConfig.turbopack, loaderPath, process.cwd())
40
44
  };
41
45
  }
42
46
  function mergeServerExternalPackages(user) {
@@ -45,7 +49,8 @@ function mergeServerExternalPackages(user) {
45
49
  if (user.includes(ezlogsPkg)) return [...user];
46
50
  return [...user, ezlogsPkg];
47
51
  }
48
- function mergeTurbopackConfig(userTurbopack, loaderPath) {
52
+ function mergeTurbopackConfig(userTurbopack, loaderPath, projectDir) {
53
+ const wrapProxy = nextMajorVersion(projectDir) >= 16;
49
54
  const ezlogsRules = {};
50
55
  for (const ext of ["ts", "tsx", "js", "jsx"]) {
51
56
  ezlogsRules[`**/{app,src/app}/**/route.${ext}`] = {
@@ -88,6 +93,17 @@ function mergeTurbopackConfig(userTurbopack, loaderPath) {
88
93
  ],
89
94
  as: `*.${ext}`
90
95
  };
96
+ if (wrapProxy) {
97
+ ezlogsRules[`**/proxy.${ext}`] = {
98
+ condition: { not: "browser" },
99
+ loaders: [
100
+ {
101
+ loader: loaderPath,
102
+ options: { kind: "proxy", projectDir }
103
+ }
104
+ ]
105
+ };
106
+ }
91
107
  const actionGlobs = [
92
108
  `**/{actions,src/actions}/**/*.${ext}`,
93
109
  `**/{app,src/app}/**/actions.${ext}`,
@@ -181,6 +197,17 @@ function installLoaders(config, context) {
181
197
  }
182
198
  ]
183
199
  });
200
+ if (nextMajorVersion(projectDir) >= 16) {
201
+ newRules.push({
202
+ test: new RegExp(`^${escapeRegex(projectDir)}[/\\\\](src[/\\\\])?proxy\\.(${extPattern})$`),
203
+ use: [
204
+ {
205
+ loader: loaderPath,
206
+ options: { kind: "proxy", projectDir }
207
+ }
208
+ ]
209
+ });
210
+ }
184
211
  const actionsActionsDir = path.resolve(projectDir, "actions");
185
212
  const srcActionsDir = path.resolve(projectDir, "src/actions");
186
213
  const appActionsDir = path.resolve(projectDir, "app/actions");
@@ -243,6 +270,15 @@ function resolveLoaderPath() {
243
270
  const here = typeof __dirname === "string" ? __dirname : path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))));
244
271
  return path.resolve(here, "loader.cjs");
245
272
  }
273
+ function nextMajorVersion(projectDir) {
274
+ try {
275
+ const req = module$1.createRequire(path.resolve(projectDir, "package.json"));
276
+ const pkg = JSON.parse(fs.readFileSync(req.resolve("next/package.json"), "utf8"));
277
+ return Number.parseInt(pkg.version ?? "", 10) || 0;
278
+ } catch {
279
+ return 0;
280
+ }
281
+ }
246
282
  function escapeRegex(input) {
247
283
  return input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
248
284
  }
@@ -63,6 +63,13 @@ interface WebpackContext {
63
63
  buildId: string;
64
64
  config: NextConfig;
65
65
  }
66
- declare function withEzlogsConfig(nextConfig?: NextConfig): NextConfig;
66
+ /**
67
+ * Generic over the caller's own config type, so the result is exactly
68
+ * what Next.js expects back (`import("next").NextConfig` in a typed
69
+ * `next.config.ts`, or a `checkJs` ESM `next.config.js`) — Next's own
70
+ * `webpack` is `NextJsWebpackConfig | null`, which the narrow shape
71
+ * below must not be asked to accept.
72
+ */
73
+ declare function withEzlogsConfig<T extends object = NextConfig>(userConfig?: T): T;
67
74
 
68
75
  export { withEzlogsConfig };
@@ -63,6 +63,13 @@ interface WebpackContext {
63
63
  buildId: string;
64
64
  config: NextConfig;
65
65
  }
66
- declare function withEzlogsConfig(nextConfig?: NextConfig): NextConfig;
66
+ /**
67
+ * Generic over the caller's own config type, so the result is exactly
68
+ * what Next.js expects back (`import("next").NextConfig` in a typed
69
+ * `next.config.ts`, or a `checkJs` ESM `next.config.js`) — Next's own
70
+ * `webpack` is `NextJsWebpackConfig | null`, which the narrow shape
71
+ * below must not be asked to accept.
72
+ */
73
+ declare function withEzlogsConfig<T extends object = NextConfig>(userConfig?: T): T;
67
74
 
68
75
  export { withEzlogsConfig };