@trigger.dev/sdk 2.2.4 → 2.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -57,12 +57,15 @@ __export(src_exports, {
57
57
  CronTrigger: () => CronTrigger,
58
58
  DynamicSchedule: () => DynamicSchedule,
59
59
  DynamicTrigger: () => DynamicTrigger,
60
+ EventSpecificationExampleSchema: () => EventSpecificationExampleSchema,
60
61
  EventTrigger: () => EventTrigger,
61
62
  ExternalSource: () => ExternalSource,
62
63
  ExternalSourceTrigger: () => ExternalSourceTrigger,
63
64
  IO: () => IO,
64
65
  IOLogger: () => IOLogger,
65
66
  IntervalTrigger: () => IntervalTrigger,
67
+ InvokeTrigger: () => InvokeTrigger,
68
+ JSONOutputSerializer: () => JSONOutputSerializer,
66
69
  Job: () => Job,
67
70
  MissingConnectionNotification: () => MissingConnectionNotification,
68
71
  MissingConnectionResolvedNotification: () => MissingConnectionResolvedNotification,
@@ -70,12 +73,16 @@ __export(src_exports, {
70
73
  cronTrigger: () => cronTrigger,
71
74
  eventTrigger: () => eventTrigger,
72
75
  intervalTrigger: () => intervalTrigger,
76
+ invokeTrigger: () => invokeTrigger,
73
77
  isTriggerError: () => isTriggerError,
74
78
  missingConnectionNotification: () => missingConnectionNotification,
75
79
  missingConnectionResolvedNotification: () => missingConnectionResolvedNotification,
76
80
  omit: () => omit,
77
81
  redactString: () => redactString,
78
- retry: () => retry
82
+ retry: () => retry,
83
+ verifyHmacSha256: () => verifyHmacSha256,
84
+ verifyRequestSignature: () => verifyRequestSignature,
85
+ waitForEventSchema: () => waitForEventSchema
79
86
  });
80
87
  module.exports = __toCommonJS(src_exports);
81
88
 
@@ -87,6 +94,24 @@ function slugifyId(input) {
87
94
  }
88
95
  __name(slugifyId, "slugifyId");
89
96
 
97
+ // src/utils/typedAsyncLocalStorage.ts
98
+ var import_node_async_hooks = require("async_hooks");
99
+ var TypedAsyncLocalStorage = class {
100
+ constructor() {
101
+ this.storage = new import_node_async_hooks.AsyncLocalStorage();
102
+ }
103
+ runWith(context, fn) {
104
+ return this.storage.run(context, fn);
105
+ }
106
+ getStore() {
107
+ return this.storage.getStore();
108
+ }
109
+ };
110
+ __name(TypedAsyncLocalStorage, "TypedAsyncLocalStorage");
111
+
112
+ // src/runLocalStorage.ts
113
+ var runLocalStorage = new TypedAsyncLocalStorage();
114
+
90
115
  // src/job.ts
91
116
  var _validate, validate_fn;
92
117
  var Job = class {
@@ -141,6 +166,118 @@ var Job = class {
141
166
  internal
142
167
  };
143
168
  }
169
+ async invoke(param1, param2 = void 0, param3 = void 0) {
170
+ const runStore = runLocalStorage.getStore();
171
+ if (typeof param1 === "string") {
172
+ if (!runStore) {
173
+ throw new Error("Cannot invoke a job from outside of a run when passing a cacheKey. Make sure you are running the job from within a run or use the invoke method without the cacheKey.");
174
+ }
175
+ const options = param3 ?? {};
176
+ return await runStore.io.runTask(param1, async (task) => {
177
+ const result = await this.client.invokeJob(this.id, param2, {
178
+ idempotencyKey: task.idempotencyKey,
179
+ ...options
180
+ });
181
+ task.outputProperties = [
182
+ {
183
+ label: "Run",
184
+ text: result.id,
185
+ url: `/orgs/${runStore.ctx.organization.slug}/projects/${runStore.ctx.project.slug}/jobs/${this.id}/runs/${result.id}/trigger`
186
+ }
187
+ ];
188
+ return result;
189
+ }, {
190
+ name: `Manually Invoke '${this.name}'`,
191
+ params: param2,
192
+ properties: [
193
+ {
194
+ label: "Job",
195
+ text: this.id,
196
+ url: `/orgs/${runStore.ctx.organization.slug}/projects/${runStore.ctx.project.slug}/jobs/${this.id}`
197
+ },
198
+ {
199
+ label: "Env",
200
+ text: runStore.ctx.environment.slug
201
+ }
202
+ ]
203
+ });
204
+ }
205
+ if (runStore) {
206
+ throw new Error("Cannot invoke a job from within a run without a cacheKey.");
207
+ }
208
+ return await this.client.invokeJob(this.id, param1, param3);
209
+ }
210
+ async invokeAndWaitForCompletion(cacheKey, payload, timeoutInSeconds = 60 * 60, options = {}) {
211
+ const runStore = runLocalStorage.getStore();
212
+ if (!runStore) {
213
+ throw new Error("Cannot invoke a job from outside of a run using invokeAndWaitForCompletion. Make sure you are running the job from within a run or use the invoke method instead.");
214
+ }
215
+ const { io, ctx } = runStore;
216
+ return await io.runTask(cacheKey, async (task) => {
217
+ const parsedPayload = this.trigger.event.parseInvokePayload ? this.trigger.event.parseInvokePayload(payload) ? payload : void 0 : payload;
218
+ const result = await this.client.invokeJob(this.id, parsedPayload, {
219
+ idempotencyKey: task.idempotencyKey,
220
+ callbackUrl: task.callbackUrl ?? void 0,
221
+ ...options
222
+ });
223
+ task.outputProperties = [
224
+ {
225
+ label: "Run",
226
+ text: result.id,
227
+ url: `/orgs/${ctx.organization.slug}/projects/${ctx.project.slug}/jobs/${this.id}/runs/${result.id}/trigger`
228
+ }
229
+ ];
230
+ return {};
231
+ }, {
232
+ name: `Manually Invoke '${this.name}' and wait for completion`,
233
+ params: payload,
234
+ properties: [
235
+ {
236
+ label: "Job",
237
+ text: this.id,
238
+ url: `/orgs/${ctx.organization.slug}/projects/${ctx.project.slug}/jobs/${this.id}`
239
+ },
240
+ {
241
+ label: "Env",
242
+ text: ctx.environment.slug
243
+ }
244
+ ],
245
+ callback: {
246
+ enabled: true,
247
+ timeoutInSeconds
248
+ }
249
+ });
250
+ }
251
+ async batchInvokeAndWaitForCompletion(cacheKey, batch) {
252
+ const runStore = runLocalStorage.getStore();
253
+ if (!runStore) {
254
+ throw new Error("Cannot invoke a job from outside of a run using batchInvokeAndWaitForCompletion.");
255
+ }
256
+ if (batch.length === 0) {
257
+ return [];
258
+ }
259
+ if (batch.length > 25) {
260
+ throw new Error(`Cannot batch invoke more than 25 items. You tried to batch invoke ${batch.length} items.`);
261
+ }
262
+ const { io, ctx } = runStore;
263
+ const results = await io.parallel(cacheKey, batch, async (item, index) => {
264
+ return await this.invokeAndWaitForCompletion(String(index), item.payload, item.timeoutInSeconds ?? 60 * 60, item.options);
265
+ }, {
266
+ name: `Batch Invoke '${this.name}'`,
267
+ properties: [
268
+ {
269
+ label: "Job",
270
+ text: this.id,
271
+ url: `/orgs/${ctx.organization.slug}/projects/${ctx.project.slug}/jobs/${this.id}`
272
+ },
273
+ {
274
+ label: "Env",
275
+ text: ctx.environment.slug
276
+ }
277
+ ]
278
+ });
279
+ return results;
280
+ }
144
281
  };
145
282
  __name(Job, "Job");
146
283
  _validate = new WeakSet();
@@ -151,7 +288,8 @@ validate_fn = /* @__PURE__ */ __name(function() {
151
288
  }, "#validate");
152
289
 
153
290
  // src/triggerClient.ts
154
- var import_core7 = require("@trigger.dev/core");
291
+ var import_core8 = require("@trigger.dev/core");
292
+ var import_colorette = require("colorette");
155
293
 
156
294
  // src/apiClient.ts
157
295
  var import_core = require("@trigger.dev/core");
@@ -221,7 +359,8 @@ var ApiClient = class {
221
359
  method: "POST",
222
360
  headers: {
223
361
  "Content-Type": "application/json",
224
- Authorization: `Bearer ${apiKey}`
362
+ Authorization: `Bearer ${apiKey}`,
363
+ "Trigger-Version": import_core.API_VERSIONS.SERIALIZED_TASK_OUTPUT
225
364
  },
226
365
  body: JSON.stringify(task)
227
366
  });
@@ -259,6 +398,23 @@ var ApiClient = class {
259
398
  })
260
399
  });
261
400
  }
401
+ async sendEvents(events, options = {}) {
402
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
403
+ __privateGet(this, _logger).debug("Sending multiple events", {
404
+ events
405
+ });
406
+ return await zodfetch(import_core.ApiEventLogSchema.array(), `${__privateGet(this, _apiUrl)}/api/v1/events/bulk`, {
407
+ method: "POST",
408
+ headers: {
409
+ "Content-Type": "application/json",
410
+ Authorization: `Bearer ${apiKey}`
411
+ },
412
+ body: JSON.stringify({
413
+ events,
414
+ options
415
+ })
416
+ });
417
+ }
262
418
  async cancelEvent(eventId) {
263
419
  const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
264
420
  __privateGet(this, _logger).debug("Cancelling event", {
@@ -447,6 +603,46 @@ var ApiClient = class {
447
603
  }
448
604
  });
449
605
  }
606
+ async invokeJob(jobId, payload, options = {}) {
607
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
608
+ __privateGet(this, _logger).debug("Invoking Job", {
609
+ jobId
610
+ });
611
+ const body = {
612
+ payload,
613
+ context: options.context ?? {},
614
+ options: {
615
+ accountId: options.accountId,
616
+ callbackUrl: options.callbackUrl
617
+ }
618
+ };
619
+ return await zodfetch(import_core.InvokeJobResponseSchema, `${__privateGet(this, _apiUrl)}/api/v1/jobs/${jobId}/invoke`, {
620
+ method: "POST",
621
+ headers: {
622
+ "Content-Type": "application/json",
623
+ Authorization: `Bearer ${apiKey}`,
624
+ ...options.idempotencyKey ? {
625
+ "Idempotency-Key": options.idempotencyKey
626
+ } : {}
627
+ },
628
+ body: JSON.stringify(body)
629
+ });
630
+ }
631
+ async createEphemeralEventDispatcher(payload) {
632
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
633
+ __privateGet(this, _logger).debug("Creating ephemeral event dispatcher", {
634
+ payload
635
+ });
636
+ const response = await zodfetch(import_core.EphemeralEventDispatcherResponseBodySchema, `${__privateGet(this, _apiUrl)}/api/v1/event-dispatchers/ephemeral`, {
637
+ method: "POST",
638
+ headers: {
639
+ "Content-Type": "application/json",
640
+ Authorization: `Bearer ${apiKey}`
641
+ },
642
+ body: JSON.stringify(payload)
643
+ });
644
+ return response;
645
+ }
450
646
  };
451
647
  __name(ApiClient, "ApiClient");
452
648
  _apiUrl = new WeakMap();
@@ -482,8 +678,11 @@ function getApiKey(key) {
482
678
  };
483
679
  }
484
680
  __name(getApiKey, "getApiKey");
485
- async function zodfetchWithVersions(versionedSchemaMap, unversionedSchema, url, requestInit, options) {
486
- const response = await fetch(url, requestInit);
681
+ async function zodfetchWithVersions(versionedSchemaMap, unversionedSchema, url, requestInit, options, retryCount = 0) {
682
+ const response = await fetch(url, {
683
+ ...requestInit,
684
+ cache: "no-cache"
685
+ });
487
686
  if ((!requestInit || requestInit.method === "GET") && response.status === 404 && options?.optional) {
488
687
  return;
489
688
  }
@@ -491,6 +690,11 @@ async function zodfetchWithVersions(versionedSchemaMap, unversionedSchema, url,
491
690
  const body = await response.json();
492
691
  throw new Error(body.error);
493
692
  }
693
+ if (response.status >= 500 && retryCount < 6) {
694
+ const delay = exponentialBackoff(retryCount + 1, 2, 50, 1150, 50);
695
+ await new Promise((resolve) => setTimeout(resolve, delay));
696
+ return zodfetchWithVersions(versionedSchemaMap, unversionedSchema, url, requestInit, options, retryCount + 1);
697
+ }
494
698
  if (response.status !== 200) {
495
699
  throw new Error(options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`);
496
700
  }
@@ -512,8 +716,11 @@ async function zodfetchWithVersions(versionedSchemaMap, unversionedSchema, url,
512
716
  };
513
717
  }
514
718
  __name(zodfetchWithVersions, "zodfetchWithVersions");
515
- async function zodfetch(schema, url, requestInit, options) {
516
- const response = await fetch(url, requestInit);
719
+ async function zodfetch(schema, url, requestInit, options, retryCount = 0) {
720
+ const response = await fetch(url, {
721
+ ...requestInit,
722
+ cache: "no-cache"
723
+ });
517
724
  if ((!requestInit || requestInit.method === "GET") && response.status === 404 && options?.optional) {
518
725
  return;
519
726
  }
@@ -521,6 +728,11 @@ async function zodfetch(schema, url, requestInit, options) {
521
728
  const body = await response.json();
522
729
  throw new Error(body.error);
523
730
  }
731
+ if (response.status >= 500 && retryCount < 6) {
732
+ const delay = exponentialBackoff(retryCount + 1, 2, 50, 1150, 50);
733
+ await new Promise((resolve) => setTimeout(resolve, delay));
734
+ return zodfetch(schema, url, requestInit, options, retryCount + 1);
735
+ }
524
736
  if (response.status !== 200) {
525
737
  throw new Error(options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`);
526
738
  }
@@ -528,6 +740,12 @@ async function zodfetch(schema, url, requestInit, options) {
528
740
  return schema.parse(jsonBody);
529
741
  }
530
742
  __name(zodfetch, "zodfetch");
743
+ function exponentialBackoff(retryCount, exponential, minDelay, maxDelay, jitter) {
744
+ const delay = Math.min(Math.pow(exponential, retryCount) * minDelay, maxDelay);
745
+ const jitterValue = Math.random() * jitter;
746
+ return delay + jitterValue;
747
+ }
748
+ __name(exponentialBackoff, "exponentialBackoff");
531
749
 
532
750
  // src/errors.ts
533
751
  var ResumeWithTaskError = class {
@@ -536,6 +754,13 @@ var ResumeWithTaskError = class {
536
754
  }
537
755
  };
538
756
  __name(ResumeWithTaskError, "ResumeWithTaskError");
757
+ var ResumeWithParallelTaskError = class {
758
+ constructor(task, childErrors) {
759
+ this.task = task;
760
+ this.childErrors = childErrors;
761
+ }
762
+ };
763
+ __name(ResumeWithParallelTaskError, "ResumeWithParallelTaskError");
539
764
  var RetryWithTaskError = class {
540
765
  constructor(cause, task, retryAt) {
541
766
  this.cause = cause;
@@ -565,11 +790,11 @@ var AutoYieldExecutionError = class {
565
790
  };
566
791
  __name(AutoYieldExecutionError, "AutoYieldExecutionError");
567
792
  var AutoYieldWithCompletedTaskExecutionError = class {
568
- constructor(id, properties, output, data) {
793
+ constructor(id, properties, data, output) {
569
794
  this.id = id;
570
795
  this.properties = properties;
571
- this.output = output;
572
796
  this.data = data;
797
+ this.output = output;
573
798
  }
574
799
  };
575
800
  __name(AutoYieldWithCompletedTaskExecutionError, "AutoYieldWithCompletedTaskExecutionError");
@@ -580,18 +805,160 @@ var ParsedPayloadSchemaError = class {
580
805
  };
581
806
  __name(ParsedPayloadSchemaError, "ParsedPayloadSchemaError");
582
807
  function isTriggerError(err) {
583
- return err instanceof ResumeWithTaskError || err instanceof RetryWithTaskError || err instanceof CanceledWithTaskError || err instanceof YieldExecutionError || err instanceof AutoYieldExecutionError || err instanceof AutoYieldWithCompletedTaskExecutionError;
808
+ return err instanceof ResumeWithTaskError || err instanceof RetryWithTaskError || err instanceof CanceledWithTaskError || err instanceof YieldExecutionError || err instanceof AutoYieldExecutionError || err instanceof AutoYieldWithCompletedTaskExecutionError || err instanceof ResumeWithParallelTaskError;
584
809
  }
585
810
  __name(isTriggerError, "isTriggerError");
811
+ var ErrorWithTask = class extends Error {
812
+ constructor(cause, message) {
813
+ super(message);
814
+ this.cause = cause;
815
+ }
816
+ };
817
+ __name(ErrorWithTask, "ErrorWithTask");
818
+
819
+ // src/httpEndpoint.ts
820
+ var import_core2 = require("@trigger.dev/core");
821
+
822
+ // src/utils/formatSchemaErrors.ts
823
+ function formatSchemaErrors(errors) {
824
+ return errors.map((error) => {
825
+ const { path, message } = error;
826
+ return {
827
+ path: path.map(String),
828
+ message
829
+ };
830
+ });
831
+ }
832
+ __name(formatSchemaErrors, "formatSchemaErrors");
833
+
834
+ // src/httpEndpoint.ts
835
+ var HttpEndpoint = class {
836
+ constructor(options) {
837
+ this.options = options;
838
+ }
839
+ get id() {
840
+ return this.options.id;
841
+ }
842
+ onRequest(options) {
843
+ return new HttpTrigger({
844
+ endpointId: this.id,
845
+ event: this.options.event,
846
+ filter: options?.filter,
847
+ verify: this.options.verify
848
+ });
849
+ }
850
+ async handleRequest(request) {
851
+ if (!this.options.respondWith)
852
+ return;
853
+ return this.options.respondWith.handler(request, () => {
854
+ const clonedRequest = request.clone();
855
+ return this.options.verify(clonedRequest);
856
+ });
857
+ }
858
+ toJSON() {
859
+ return {
860
+ id: this.id,
861
+ icon: this.options.event.icon,
862
+ version: "1",
863
+ enabled: this.options.enabled ?? true,
864
+ event: this.options.event,
865
+ immediateResponseFilter: this.options.respondWith?.filter,
866
+ skipTriggeringRuns: this.options.respondWith?.skipTriggeringRuns,
867
+ source: this.options.event.source
868
+ };
869
+ }
870
+ };
871
+ __name(HttpEndpoint, "HttpEndpoint");
872
+ var HttpTrigger = /* @__PURE__ */ __name(class HttpTrigger2 {
873
+ constructor(options) {
874
+ this.options = options;
875
+ }
876
+ toJSON() {
877
+ return {
878
+ type: "static",
879
+ title: this.options.endpointId,
880
+ properties: this.options.event.properties,
881
+ rule: {
882
+ event: `httpendpoint.${this.options.endpointId}`,
883
+ payload: this.options.filter ?? {},
884
+ source: this.options.event.source
885
+ },
886
+ link: `http-endpoints/${this.options.endpointId}`,
887
+ help: {
888
+ noRuns: {
889
+ text: "To start triggering runs click here to setup your HTTP Endpoint with the external API service you want to receive webhooks from.",
890
+ link: `http-endpoints/${this.options.endpointId}`
891
+ }
892
+ }
893
+ };
894
+ }
895
+ get event() {
896
+ return this.options.event;
897
+ }
898
+ attachToJob(triggerClient, job) {
899
+ }
900
+ get preprocessRuns() {
901
+ return false;
902
+ }
903
+ async verifyPayload(payload) {
904
+ const clonedRequest = payload.clone();
905
+ return this.options.verify(clonedRequest);
906
+ }
907
+ }, "HttpTrigger");
908
+ function httpEndpoint(options) {
909
+ const id = slugifyId(options.id);
910
+ return new HttpEndpoint({
911
+ id,
912
+ enabled: options.enabled,
913
+ respondWith: options.respondWith,
914
+ verify: options.verify,
915
+ event: {
916
+ name: id,
917
+ title: options.title ?? "HTTP Trigger",
918
+ source: options.source,
919
+ icon: options.icon ?? "webhook",
920
+ properties: options.properties,
921
+ examples: options.examples ? options.examples : [
922
+ {
923
+ id: "basic-request",
924
+ name: "Basic Request",
925
+ icon: "http-post",
926
+ payload: {
927
+ url: "https://cloud.trigger.dev",
928
+ method: "POST",
929
+ headers: {
930
+ "Content-Type": "application/json"
931
+ },
932
+ rawBody: JSON.stringify({
933
+ foo: "bar"
934
+ })
935
+ }
936
+ }
937
+ ],
938
+ parsePayload: (rawPayload) => {
939
+ const result = import_core2.RequestWithRawBodySchema.safeParse(rawPayload);
940
+ if (!result.success) {
941
+ throw new ParsedPayloadSchemaError(formatSchemaErrors(result.error.issues));
942
+ }
943
+ return new Request(new URL(result.data.url), {
944
+ method: result.data.method,
945
+ headers: result.data.headers,
946
+ body: result.data.rawBody
947
+ });
948
+ }
949
+ }
950
+ });
951
+ }
952
+ __name(httpEndpoint, "httpEndpoint");
586
953
 
587
954
  // src/io.ts
588
- var import_core3 = require("@trigger.dev/core");
955
+ var import_core4 = require("@trigger.dev/core");
589
956
  var import_core_backend = require("@trigger.dev/core-backend");
590
- var import_node_async_hooks = require("async_hooks");
957
+ var import_node_async_hooks2 = require("async_hooks");
591
958
  var import_node_crypto = require("crypto");
592
959
 
593
960
  // src/retry.ts
594
- var import_core2 = require("@trigger.dev/core");
961
+ var import_core3 = require("@trigger.dev/core");
595
962
  var retry = {
596
963
  standardBackoff: {
597
964
  limit: 8,
@@ -599,6 +966,13 @@ var retry = {
599
966
  minTimeoutInMs: 500,
600
967
  maxTimeoutInMs: 3e4,
601
968
  randomize: true
969
+ },
970
+ exponentialBackoff: {
971
+ limit: 8,
972
+ factor: 2,
973
+ minTimeoutInMs: 1e3,
974
+ maxTimeoutInMs: 3e4,
975
+ randomize: true
602
976
  }
603
977
  };
604
978
 
@@ -636,7 +1010,38 @@ var TriggerStatus = class {
636
1010
  };
637
1011
  __name(TriggerStatus, "TriggerStatus");
638
1012
 
1013
+ // src/types.ts
1014
+ var import_zod2 = require("zod");
1015
+ var EventSpecificationExampleSchema = import_zod2.z.object({
1016
+ id: import_zod2.z.string(),
1017
+ name: import_zod2.z.string(),
1018
+ icon: import_zod2.z.string().optional(),
1019
+ payload: import_zod2.z.any()
1020
+ });
1021
+ function waitForEventSchema(schema) {
1022
+ return import_zod2.z.object({
1023
+ id: import_zod2.z.string(),
1024
+ name: import_zod2.z.string(),
1025
+ source: import_zod2.z.string(),
1026
+ payload: schema,
1027
+ timestamp: import_zod2.z.coerce.date(),
1028
+ context: import_zod2.z.any().optional(),
1029
+ accountId: import_zod2.z.string().optional()
1030
+ });
1031
+ }
1032
+ __name(waitForEventSchema, "waitForEventSchema");
1033
+
639
1034
  // src/io.ts
1035
+ var import_zod3 = require("zod");
1036
+ var JSONOutputSerializer = class {
1037
+ serialize(value) {
1038
+ return JSON.stringify(value);
1039
+ }
1040
+ deserialize(value) {
1041
+ return value ? JSON.parse(value) : void 0;
1042
+ }
1043
+ };
1044
+ __name(JSONOutputSerializer, "JSONOutputSerializer");
640
1045
  var _addToCachedTasks, addToCachedTasks_fn, _detectAutoYield, detectAutoYield_fn, _forceYield, forceYield_fn, _getTimeElapsed, getTimeElapsed_fn, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn;
641
1046
  var IO = class {
642
1047
  constructor(options) {
@@ -645,11 +1050,13 @@ var IO = class {
645
1050
  __privateAdd(this, _forceYield);
646
1051
  __privateAdd(this, _getTimeElapsed);
647
1052
  __privateAdd(this, _getRemainingTimeInMillis);
1053
+ __publicField(this, "_outputSerializer", new JSONOutputSerializer());
1054
+ __publicField(this, "_visitedCacheKeys", /* @__PURE__ */ new Set());
648
1055
  __publicField(this, "brb", this.yield.bind(this));
649
1056
  this._id = options.id;
650
1057
  this._apiClient = options.apiClient;
651
1058
  this._triggerClient = options.client;
652
- this._logger = options.logger ?? new import_core3.Logger("trigger.dev", options.logLevel);
1059
+ this._logger = options.logger ?? new import_core4.Logger("trigger.dev", options.logLevel);
653
1060
  this._cachedTasks = /* @__PURE__ */ new Map();
654
1061
  this._jobLogger = options.jobLogger;
655
1062
  this._jobLogLevel = options.jobLogLevel;
@@ -670,7 +1077,7 @@ var IO = class {
670
1077
  });
671
1078
  this._stats.initialCachedTasks = options.cachedTasks.length;
672
1079
  }
673
- this._taskStorage = new import_node_async_hooks.AsyncLocalStorage();
1080
+ this._taskStorage = new import_node_async_hooks2.AsyncLocalStorage();
674
1081
  this._context = options.context;
675
1082
  this._yieldedExecutions = options.yieldedExecutions ?? [];
676
1083
  if (options.noopTasksSet) {
@@ -691,7 +1098,7 @@ var IO = class {
691
1098
  get logger() {
692
1099
  return new IOLogger(async (level, message, data) => {
693
1100
  let logLevel = "info";
694
- if (import_core3.Logger.satisfiesLogLevel(logLevel, this._jobLogLevel)) {
1101
+ if (import_core4.Logger.satisfiesLogLevel(logLevel, this._jobLogLevel)) {
695
1102
  await this.runTask([
696
1103
  message,
697
1104
  level
@@ -743,6 +1150,56 @@ var IO = class {
743
1150
  }
744
1151
  });
745
1152
  }
1153
+ async random(cacheKey, { min = 0, max = 1, round = false } = {}) {
1154
+ return await this.runTask(cacheKey, async (task) => {
1155
+ if (min > max) {
1156
+ throw new Error(`Lower bound can't be higher than upper bound - min: ${min}, max: ${max}`);
1157
+ }
1158
+ if (min === max) {
1159
+ await this.logger.warn(`Lower and upper bounds are identical. The return value is not random and will always be: ${min}`);
1160
+ }
1161
+ const withinBounds = (max - min) * Math.random() + min;
1162
+ if (!round) {
1163
+ return withinBounds;
1164
+ }
1165
+ if (!Number.isInteger(min) || !Number.isInteger(max)) {
1166
+ await this.logger.warn("Rounding enabled with floating-point bounds. This may cause unexpected skew and boundary inclusivity.");
1167
+ }
1168
+ const rounded = Math.round(withinBounds);
1169
+ return rounded;
1170
+ }, {
1171
+ name: "random",
1172
+ icon: "dice-5-filled",
1173
+ params: {
1174
+ min,
1175
+ max,
1176
+ round
1177
+ },
1178
+ properties: [
1179
+ ...min === 0 ? [] : [
1180
+ {
1181
+ label: "min",
1182
+ text: String(min)
1183
+ }
1184
+ ],
1185
+ ...max === 1 ? [] : [
1186
+ {
1187
+ label: "max",
1188
+ text: String(max)
1189
+ }
1190
+ ],
1191
+ ...round === false ? [] : [
1192
+ {
1193
+ label: "round",
1194
+ text: String(round)
1195
+ }
1196
+ ]
1197
+ ],
1198
+ style: {
1199
+ style: "minimal"
1200
+ }
1201
+ });
1202
+ }
746
1203
  async wait(cacheKey, seconds) {
747
1204
  return await this.runTask(cacheKey, async (task) => {
748
1205
  }, {
@@ -758,22 +1215,109 @@ var IO = class {
758
1215
  }
759
1216
  });
760
1217
  }
1218
+ async waitForEvent(cacheKey, event, options) {
1219
+ const timeoutInSeconds = options?.timeoutInSeconds ?? 60 * 60;
1220
+ return await this.runTask(cacheKey, async (task, io) => {
1221
+ if (!task.callbackUrl) {
1222
+ throw new Error("No callbackUrl found on task");
1223
+ }
1224
+ await this.triggerClient.createEphemeralEventDispatcher({
1225
+ url: task.callbackUrl,
1226
+ name: event.name,
1227
+ filter: event.filter,
1228
+ contextFilter: event.contextFilter,
1229
+ source: event.source,
1230
+ accountId: event.accountId,
1231
+ timeoutInSeconds
1232
+ });
1233
+ return {};
1234
+ }, {
1235
+ name: "Wait for Event",
1236
+ icon: "custom-event",
1237
+ params: {
1238
+ name: event.name,
1239
+ source: event.source,
1240
+ filter: event.filter,
1241
+ contextFilter: event.contextFilter,
1242
+ accountId: event.accountId
1243
+ },
1244
+ callback: {
1245
+ enabled: true,
1246
+ timeoutInSeconds
1247
+ },
1248
+ properties: [
1249
+ {
1250
+ label: "Event",
1251
+ text: event.name
1252
+ },
1253
+ {
1254
+ label: "Timeout",
1255
+ text: `${timeoutInSeconds}s`
1256
+ },
1257
+ ...event.source ? [
1258
+ {
1259
+ label: "Source",
1260
+ text: event.source
1261
+ }
1262
+ ] : [],
1263
+ ...event.accountId ? [
1264
+ {
1265
+ label: "Account ID",
1266
+ text: event.accountId
1267
+ }
1268
+ ] : []
1269
+ ],
1270
+ parseOutput: (output) => {
1271
+ return waitForEventSchema(event.schema ?? import_zod3.z.any()).parse(output);
1272
+ }
1273
+ });
1274
+ }
1275
+ async waitForRequest(cacheKey, callback, options) {
1276
+ const timeoutInSeconds = options?.timeoutInSeconds ?? 60 * 60;
1277
+ return await this.runTask(cacheKey, async (task, io) => {
1278
+ if (!task.callbackUrl) {
1279
+ throw new Error("No callbackUrl found on task");
1280
+ }
1281
+ task.outputProperties = [
1282
+ {
1283
+ label: "Callback URL",
1284
+ text: task.callbackUrl
1285
+ }
1286
+ ];
1287
+ return callback(task.callbackUrl);
1288
+ }, {
1289
+ name: "Wait for Request",
1290
+ icon: "clock",
1291
+ callback: {
1292
+ enabled: true,
1293
+ timeoutInSeconds: options?.timeoutInSeconds
1294
+ },
1295
+ properties: [
1296
+ {
1297
+ label: "Timeout",
1298
+ text: `${timeoutInSeconds}s`
1299
+ }
1300
+ ]
1301
+ });
1302
+ }
761
1303
  async createStatus(cacheKey, initialStatus) {
762
1304
  const id = typeof cacheKey === "string" ? cacheKey : cacheKey.join("-");
763
1305
  const status = new TriggerStatus(id, this);
764
1306
  await status.update(cacheKey, initialStatus);
765
1307
  return status;
766
1308
  }
767
- async backgroundFetch(cacheKey, url, requestInit, retry2) {
1309
+ async backgroundFetch(cacheKey, url, requestInit, options) {
768
1310
  const urlObject = new URL(url);
769
1311
  return await this.runTask(cacheKey, async (task) => {
1312
+ console.log("task context", task.context);
770
1313
  return task.output;
771
1314
  }, {
772
1315
  name: `fetch ${urlObject.hostname}${urlObject.pathname}`,
773
1316
  params: {
774
1317
  url,
775
1318
  requestInit,
776
- retry: retry2
1319
+ retry: options?.retry,
1320
+ timeout: options?.timeout
777
1321
  },
778
1322
  operation: "fetch",
779
1323
  icon: "background",
@@ -791,8 +1335,87 @@ var IO = class {
791
1335
  {
792
1336
  label: "background",
793
1337
  text: "true"
1338
+ },
1339
+ ...options?.timeout ? [
1340
+ {
1341
+ label: "timeout",
1342
+ text: `${options.timeout.durationInMs}ms`
1343
+ }
1344
+ ] : []
1345
+ ],
1346
+ retry: {
1347
+ limit: 0
1348
+ }
1349
+ });
1350
+ }
1351
+ async backgroundPoll(cacheKey, params) {
1352
+ const urlObject = new URL(params.url);
1353
+ return await this.runTask(cacheKey, async (task) => {
1354
+ return task.output;
1355
+ }, {
1356
+ name: `poll ${urlObject.hostname}${urlObject.pathname}`,
1357
+ params,
1358
+ operation: "fetch-poll",
1359
+ icon: "clock-bolt",
1360
+ noop: false,
1361
+ properties: [
1362
+ {
1363
+ label: "url",
1364
+ text: params.url
1365
+ },
1366
+ {
1367
+ label: "interval",
1368
+ text: `${params.interval}s`
1369
+ },
1370
+ {
1371
+ label: "timeout",
1372
+ text: `${params.timeout}s`
794
1373
  }
795
- ]
1374
+ ],
1375
+ retry: {
1376
+ limit: 0
1377
+ }
1378
+ });
1379
+ }
1380
+ async backgroundFetchResponse(cacheKey, url, requestInit, options) {
1381
+ const urlObject = new URL(url);
1382
+ return await this.runTask(cacheKey, async (task) => {
1383
+ return task.output;
1384
+ }, {
1385
+ name: `fetch response ${urlObject.hostname}${urlObject.pathname}`,
1386
+ params: {
1387
+ url,
1388
+ requestInit,
1389
+ retry: options?.retry,
1390
+ timeout: options?.timeout
1391
+ },
1392
+ operation: "fetch-response",
1393
+ icon: "background",
1394
+ noop: false,
1395
+ properties: [
1396
+ {
1397
+ label: "url",
1398
+ text: url,
1399
+ url
1400
+ },
1401
+ {
1402
+ label: "method",
1403
+ text: requestInit?.method ?? "GET"
1404
+ },
1405
+ {
1406
+ label: "background",
1407
+ text: "true"
1408
+ },
1409
+ ...options?.timeout ? [
1410
+ {
1411
+ label: "timeout",
1412
+ text: `${options.timeout.durationInMs}ms`
1413
+ }
1414
+ ] : []
1415
+ ],
1416
+ retry: {
1417
+ limit: 0
1418
+ }
796
1419
  });
797
1420
  }
798
1421
  async sendEvent(cacheKey, event, options) {
@@ -814,7 +1437,26 @@ var IO = class {
814
1437
  label: "ID",
815
1438
  text: event.id
816
1439
  }
817
- ] : []
1440
+ ] : [],
1441
+ ...sendEventOptionsProperties(options)
1442
+ ]
1443
+ });
1444
+ }
1445
+ async sendEvents(cacheKey, events, options) {
1446
+ return await this.runTask(cacheKey, async (task) => {
1447
+ return await this._triggerClient.sendEvents(events, options);
1448
+ }, {
1449
+ name: "sendEvents",
1450
+ params: {
1451
+ events,
1452
+ options
1453
+ },
1454
+ properties: [
1455
+ {
1456
+ label: "Total Events",
1457
+ text: String(events.length)
1458
+ },
1459
+ ...sendEventOptionsProperties(options)
818
1460
  ]
819
1461
  });
820
1462
  }
@@ -990,6 +1632,25 @@ var IO = class {
990
1632
  name: "get-auth"
991
1633
  });
992
1634
  }
1635
+ async parallel(cacheKey, items, callback, options) {
1636
+ const results = await this.runTask(cacheKey, async (task) => {
1637
+ const outcomes = await Promise.allSettled(items.map((item, index) => spaceOut(() => callback(item, index), index, 15)));
1638
+ if (outcomes.every((outcome) => outcome.status === "fulfilled")) {
1639
+ return outcomes.map((outcome) => outcome.value);
1640
+ }
1641
+ const nonInternalErrors = outcomes.filter((outcome) => outcome.status === "rejected" && !isTriggerError(outcome.reason)).map((outcome) => outcome);
1642
+ if (nonInternalErrors.length > 0) {
1643
+ throw nonInternalErrors[0].reason;
1644
+ }
1645
+ const internalErrors = outcomes.filter((outcome) => outcome.status === "rejected" && isTriggerError(outcome.reason)).map((outcome) => outcome).map((outcome) => outcome.reason);
1646
+ throw new ResumeWithParallelTaskError(task, internalErrors);
1647
+ }, {
1648
+ name: "parallel",
1649
+ parallel: true,
1650
+ ...options ?? {}
1651
+ });
1652
+ return results;
1653
+ }
993
1654
  async runTask(cacheKey, callback, options, onError) {
994
1655
  __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "start_task", 500);
995
1656
  const parentId = this._taskStorage.getStore()?.taskId;
@@ -1005,13 +1666,21 @@ var IO = class {
1005
1666
  parentId ?? "",
1006
1667
  cacheKey
1007
1668
  ].flat());
1669
+ if (this._visitedCacheKeys.has(idempotencyKey)) {
1670
+ if (typeof cacheKey === "string") {
1671
+ throw new Error(`Task with cacheKey "${cacheKey}" has already been executed in this run. Each task must have a unique cacheKey.`);
1672
+ } else {
1673
+ throw new Error(`Task with cacheKey "${cacheKey.join("-")}" has already been executed in this run. Each task must have a unique cacheKey.`);
1674
+ }
1675
+ }
1676
+ this._visitedCacheKeys.add(idempotencyKey);
1008
1677
  const cachedTask = this._cachedTasks.get(idempotencyKey);
1009
1678
  if (cachedTask && cachedTask.status === "COMPLETED") {
1010
1679
  this._logger.debug("Using completed cached task", {
1011
1680
  idempotencyKey
1012
1681
  });
1013
1682
  this._stats.cachedTaskHits++;
1014
- return cachedTask.output;
1683
+ return options?.parseOutput ? options.parseOutput(cachedTask.output) : cachedTask.output;
1015
1684
  }
1016
1685
  if (options?.noop && this._noopTasksBloomFilter) {
1017
1686
  if (this._noopTasksBloomFilter.test(idempotencyKey)) {
@@ -1022,23 +1691,27 @@ var IO = class {
1022
1691
  return {};
1023
1692
  }
1024
1693
  }
1694
+ const runOptions = {
1695
+ ...options ?? {},
1696
+ parseOutput: void 0
1697
+ };
1025
1698
  const response = await this._apiClient.runTask(this._id, {
1026
1699
  idempotencyKey,
1027
1700
  displayKey: typeof cacheKey === "string" ? cacheKey : void 0,
1028
1701
  noop: false,
1029
- ...options ?? {},
1702
+ ...runOptions ?? {},
1030
1703
  parentId
1031
1704
  }, {
1032
1705
  cachedTasksCursor: this._cachedTasksCursor
1033
1706
  });
1034
- const task = response.version === import_core3.API_VERSIONS.LAZY_LOADED_CACHED_TASKS ? response.body.task : response.body;
1707
+ const task = response.version === import_core4.API_VERSIONS.LAZY_LOADED_CACHED_TASKS ? response.body.task : response.body;
1035
1708
  if (task.forceYield) {
1036
1709
  this._logger.debug("Forcing yield after run task", {
1037
1710
  idempotencyKey
1038
1711
  });
1039
1712
  __privateMethod(this, _forceYield, forceYield_fn).call(this, "after_run_task");
1040
1713
  }
1041
- if (response.version === import_core3.API_VERSIONS.LAZY_LOADED_CACHED_TASKS) {
1714
+ if (response.version === import_core4.API_VERSIONS.LAZY_LOADED_CACHED_TASKS) {
1042
1715
  this._cachedTasksCursor = response.body.cachedTasks?.cursor;
1043
1716
  for (const cachedTask2 of response.body.cachedTasks?.tasks ?? []) {
1044
1717
  if (!this._cachedTasks.has(cachedTask2.idempotencyKey)) {
@@ -1070,14 +1743,14 @@ var IO = class {
1070
1743
  this._stats.cachedTaskMisses++;
1071
1744
  __privateMethod(this, _addToCachedTasks, addToCachedTasks_fn).call(this, task);
1072
1745
  }
1073
- return task.output;
1746
+ return options?.parseOutput ? options.parseOutput(task.output) : task.output;
1074
1747
  }
1075
1748
  if (task.status === "ERRORED") {
1076
1749
  this._logger.debug("Task errored", {
1077
1750
  idempotencyKey,
1078
1751
  task
1079
1752
  });
1080
- throw new Error(task.error ?? task?.output ? JSON.stringify(task.output) : "Task errored");
1753
+ throw new ErrorWithTask(task, task.error ?? task?.output ? JSON.stringify(task.output) : "Task errored");
1081
1754
  }
1082
1755
  __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "before_execute_task", 1500);
1083
1756
  const executeTask = /* @__PURE__ */ __name(async () => {
@@ -1090,14 +1763,14 @@ var IO = class {
1090
1763
  });
1091
1764
  return {};
1092
1765
  }
1093
- const output = import_core3.SerializableJsonSchema.parse(result);
1766
+ const output = this._outputSerializer.serialize(result);
1094
1767
  this._logger.debug("Completing using output", {
1095
1768
  idempotencyKey,
1096
1769
  task
1097
1770
  });
1098
1771
  __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "before_complete_task", 500, task, output);
1099
1772
  const completedTask = await this._apiClient.completeTask(this._id, task.id, {
1100
- output: output ?? void 0,
1773
+ output,
1101
1774
  properties: task.outputProperties ?? void 0
1102
1775
  });
1103
1776
  if (completedTask.forceYield) {
@@ -1111,7 +1784,8 @@ var IO = class {
1111
1784
  throw new CanceledWithTaskError(completedTask);
1112
1785
  }
1113
1786
  __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "after_complete_task", 500);
1114
- return output;
1787
+ const deserializedOutput = this._outputSerializer.deserialize(output);
1788
+ return options?.parseOutput ? options.parseOutput(deserializedOutput) : deserializedOutput;
1115
1789
  } catch (error) {
1116
1790
  if (isTriggerError(error)) {
1117
1791
  throw error;
@@ -1126,7 +1800,7 @@ var IO = class {
1126
1800
  } else {
1127
1801
  skipRetrying = !!onErrorResult.skipRetrying;
1128
1802
  if (onErrorResult.retryAt && !skipRetrying) {
1129
- const parsedError2 = import_core3.ErrorWithStackSchema.safeParse(onErrorResult.error);
1803
+ const parsedError2 = import_core4.ErrorWithStackSchema.safeParse(onErrorResult.error);
1130
1804
  throw new RetryWithTaskError(parsedError2.success ? parsedError2.data : {
1131
1805
  message: "Unknown error"
1132
1806
  }, task, onErrorResult.retryAt);
@@ -1140,9 +1814,14 @@ var IO = class {
1140
1814
  error = innerError;
1141
1815
  }
1142
1816
  }
1143
- const parsedError = import_core3.ErrorWithStackSchema.safeParse(error);
1817
+ if (error instanceof ErrorWithTask) {
1818
+ await this._apiClient.failTask(this._id, task.id, {
1819
+ error: error.cause.output
1820
+ });
1821
+ }
1822
+ const parsedError = import_core4.ErrorWithStackSchema.safeParse(error);
1144
1823
  if (options?.retry && !skipRetrying) {
1145
- const retryAt = (0, import_core2.calculateRetryAt)(options.retry, task.attempts - 1);
1824
+ const retryAt = (0, import_core3.calculateRetryAt)(options.retry, task.attempts - 1);
1146
1825
  if (retryAt) {
1147
1826
  throw new RetryWithTaskError(parsedError.success ? parsedError.data : {
1148
1827
  message: "Unknown error"
@@ -1189,7 +1868,7 @@ var IO = class {
1189
1868
  }, executeTask);
1190
1869
  }
1191
1870
  yield(cacheKey) {
1192
- if (!(0, import_core3.supportsFeature)("yieldExecution", this._serverVersion)) {
1871
+ if (!(0, import_core4.supportsFeature)("yieldExecution", this._serverVersion)) {
1193
1872
  console.warn("[trigger.dev] io.yield() is not support by the version of the Trigger.dev server you are using, you will need to upgrade your self-hosted Trigger.dev instance.");
1194
1873
  return;
1195
1874
  }
@@ -1219,11 +1898,11 @@ detectAutoYield_fn = /* @__PURE__ */ __name(function(location, threshold = 1500,
1219
1898
  const timeRemaining = __privateMethod(this, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn).call(this);
1220
1899
  if (timeRemaining && timeRemaining < threshold) {
1221
1900
  if (task1) {
1222
- throw new AutoYieldWithCompletedTaskExecutionError(task1.id, task1.outputProperties ?? [], output, {
1901
+ throw new AutoYieldWithCompletedTaskExecutionError(task1.id, task1.outputProperties ?? [], {
1223
1902
  location,
1224
1903
  timeRemaining,
1225
1904
  timeElapsed: __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this)
1226
- });
1905
+ }, output);
1227
1906
  } else {
1228
1907
  throw new AutoYieldExecutionError(location, timeRemaining, __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this));
1229
1908
  }
@@ -1300,6 +1979,34 @@ var IOLogger = class {
1300
1979
  }
1301
1980
  };
1302
1981
  __name(IOLogger, "IOLogger");
1982
+ async function spaceOut(callback, index, delay) {
1983
+ await new Promise((resolve) => setTimeout(resolve, index * delay));
1984
+ return await callback();
1985
+ }
1986
+ __name(spaceOut, "spaceOut");
1987
+ function sendEventOptionsProperties(options) {
1988
+ return [
1989
+ ...options?.accountId ? [
1990
+ {
1991
+ label: "Account ID",
1992
+ text: options.accountId
1993
+ }
1994
+ ] : [],
1995
+ ...options?.deliverAfter ? [
1996
+ {
1997
+ label: "Deliver After",
1998
+ text: `${options.deliverAfter}s`
1999
+ }
2000
+ ] : [],
2001
+ ...options?.deliverAt ? [
2002
+ {
2003
+ label: "Deliver At",
2004
+ text: options.deliverAt.toISOString()
2005
+ }
2006
+ ] : []
2007
+ ];
2008
+ }
2009
+ __name(sendEventOptionsProperties, "sendEventOptionsProperties");
1303
2010
 
1304
2011
  // src/ioWithIntegrations.ts
1305
2012
  function createIOWithIntegrations(io, auths, integrations) {
@@ -1330,26 +2037,8 @@ function createIOWithIntegrations(io, auths, integrations) {
1330
2037
  }
1331
2038
  __name(createIOWithIntegrations, "createIOWithIntegrations");
1332
2039
 
1333
- // src/utils/typedAsyncLocalStorage.ts
1334
- var import_node_async_hooks2 = require("async_hooks");
1335
- var TypedAsyncLocalStorage = class {
1336
- constructor() {
1337
- this.storage = new import_node_async_hooks2.AsyncLocalStorage();
1338
- }
1339
- runWith(context, fn) {
1340
- return this.storage.run(context, fn);
1341
- }
1342
- getStore() {
1343
- return this.storage.getStore();
1344
- }
1345
- };
1346
- __name(TypedAsyncLocalStorage, "TypedAsyncLocalStorage");
1347
-
1348
- // src/runLocalStorage.ts
1349
- var runLocalStorage = new TypedAsyncLocalStorage();
1350
-
1351
2040
  // src/triggers/dynamic.ts
1352
- var import_core4 = require("@trigger.dev/core");
2041
+ var import_core5 = require("@trigger.dev/core");
1353
2042
  var _client, _options2;
1354
2043
  var DynamicTrigger = class {
1355
2044
  constructor(client, options) {
@@ -1378,7 +2067,7 @@ var DynamicTrigger = class {
1378
2067
  rule: {
1379
2068
  event: this.event.name,
1380
2069
  source: this.event.source,
1381
- payload: (0, import_core4.deepMergeFilters)(this.source.filter(params), this.event.filter ?? {}, options.filter ?? {})
2070
+ payload: (0, import_core5.deepMergeFilters)(this.source.filter(params), this.event.filter ?? {}, options.filter ?? {})
1382
2071
  },
1383
2072
  source: {
1384
2073
  version: "2",
@@ -1431,27 +2120,18 @@ var DynamicTrigger = class {
1431
2120
  get preprocessRuns() {
1432
2121
  return true;
1433
2122
  }
2123
+ async verifyPayload(payload) {
2124
+ return {
2125
+ success: true
2126
+ };
2127
+ }
1434
2128
  };
1435
2129
  __name(DynamicTrigger, "DynamicTrigger");
1436
2130
  _client = new WeakMap();
1437
2131
  _options2 = new WeakMap();
1438
2132
 
1439
2133
  // src/triggers/eventTrigger.ts
1440
- var import_core5 = require("@trigger.dev/core");
1441
-
1442
- // src/utils/formatSchemaErrors.ts
1443
- function formatSchemaErrors(errors) {
1444
- return errors.map((error) => {
1445
- const { path, message } = error;
1446
- return {
1447
- path: path.map(String),
1448
- message
1449
- };
1450
- });
1451
- }
1452
- __name(formatSchemaErrors, "formatSchemaErrors");
1453
-
1454
- // src/triggers/eventTrigger.ts
2134
+ var import_core6 = require("@trigger.dev/core");
1455
2135
  var _options3;
1456
2136
  var EventTrigger = class {
1457
2137
  constructor(options) {
@@ -1465,7 +2145,7 @@ var EventTrigger = class {
1465
2145
  rule: {
1466
2146
  event: __privateGet(this, _options3).name ?? __privateGet(this, _options3).event.name,
1467
2147
  source: __privateGet(this, _options3).source ?? "trigger.dev",
1468
- payload: (0, import_core5.deepMergeFilters)(__privateGet(this, _options3).filter ?? {}, __privateGet(this, _options3).event.filter ?? {})
2148
+ payload: (0, import_core6.deepMergeFilters)(__privateGet(this, _options3).filter ?? {}, __privateGet(this, _options3).event.filter ?? {})
1469
2149
  }
1470
2150
  };
1471
2151
  }
@@ -1477,6 +2157,11 @@ var EventTrigger = class {
1477
2157
  get preprocessRuns() {
1478
2158
  return false;
1479
2159
  }
2160
+ async verifyPayload(payload) {
2161
+ return {
2162
+ success: true
2163
+ };
2164
+ }
1480
2165
  };
1481
2166
  __name(EventTrigger, "EventTrigger");
1482
2167
  _options3 = new WeakMap();
@@ -1506,7 +2191,7 @@ function eventTrigger(options) {
1506
2191
  __name(eventTrigger, "eventTrigger");
1507
2192
 
1508
2193
  // src/triggers/scheduled.ts
1509
- var import_core6 = require("@trigger.dev/core");
2194
+ var import_core7 = require("@trigger.dev/core");
1510
2195
  var import_cronstrue = __toESM(require("cronstrue"));
1511
2196
  var examples = [
1512
2197
  {
@@ -1514,8 +2199,8 @@ var examples = [
1514
2199
  name: "Now",
1515
2200
  icon: "clock",
1516
2201
  payload: {
1517
- ts: import_core6.currentDate.marker,
1518
- lastTimestamp: import_core6.currentDate.marker
2202
+ ts: import_core7.currentDate.marker,
2203
+ lastTimestamp: import_core7.currentDate.marker
1519
2204
  }
1520
2205
  }
1521
2206
  ];
@@ -1530,7 +2215,7 @@ var IntervalTrigger = class {
1530
2215
  source: "trigger.dev",
1531
2216
  icon: "schedule-interval",
1532
2217
  examples,
1533
- parsePayload: import_core6.ScheduledPayloadSchema.parse,
2218
+ parsePayload: import_core7.ScheduledPayloadSchema.parse,
1534
2219
  properties: [
1535
2220
  {
1536
2221
  label: "Interval",
@@ -1544,6 +2229,11 @@ var IntervalTrigger = class {
1544
2229
  get preprocessRuns() {
1545
2230
  return false;
1546
2231
  }
2232
+ async verifyPayload(payload) {
2233
+ return {
2234
+ success: true
2235
+ };
2236
+ }
1547
2237
  toJSON() {
1548
2238
  return {
1549
2239
  type: "scheduled",
@@ -1575,7 +2265,7 @@ var CronTrigger = class {
1575
2265
  source: "trigger.dev",
1576
2266
  icon: "schedule-cron",
1577
2267
  examples,
1578
- parsePayload: import_core6.ScheduledPayloadSchema.parse,
2268
+ parsePayload: import_core7.ScheduledPayloadSchema.parse,
1579
2269
  properties: [
1580
2270
  {
1581
2271
  label: "cron",
@@ -1593,6 +2283,11 @@ var CronTrigger = class {
1593
2283
  get preprocessRuns() {
1594
2284
  return false;
1595
2285
  }
2286
+ async verifyPayload(payload) {
2287
+ return {
2288
+ success: true
2289
+ };
2290
+ }
1596
2291
  toJSON() {
1597
2292
  return {
1598
2293
  type: "scheduled",
@@ -1626,7 +2321,7 @@ var DynamicSchedule = class {
1626
2321
  source: "trigger.dev",
1627
2322
  icon: "schedule-dynamic",
1628
2323
  examples,
1629
- parsePayload: import_core6.ScheduledPayloadSchema.parse
2324
+ parsePayload: import_core7.ScheduledPayloadSchema.parse
1630
2325
  };
1631
2326
  }
1632
2327
  async register(key, metadata) {
@@ -1688,6 +2383,11 @@ var DynamicSchedule = class {
1688
2383
  get preprocessRuns() {
1689
2384
  return false;
1690
2385
  }
2386
+ async verifyPayload(payload) {
2387
+ return {
2388
+ success: true
2389
+ };
2390
+ }
1691
2391
  toJSON() {
1692
2392
  return {
1693
2393
  type: "dynamic",
@@ -1698,24 +2398,26 @@ var DynamicSchedule = class {
1698
2398
  __name(DynamicSchedule, "DynamicSchedule");
1699
2399
 
1700
2400
  // package.json
1701
- var version = "2.2.4";
2401
+ var version = "2.2.6";
1702
2402
 
1703
2403
  // src/triggerClient.ts
1704
2404
  var registerSourceEvent = {
1705
- name: import_core7.REGISTER_SOURCE_EVENT_V2,
2405
+ name: import_core8.REGISTER_SOURCE_EVENT_V2,
1706
2406
  title: "Register Source",
1707
2407
  source: "internal",
1708
2408
  icon: "register-source",
1709
- parsePayload: import_core7.RegisterSourceEventSchemaV2.parse
2409
+ parsePayload: import_core8.RegisterSourceEventSchemaV2.parse
1710
2410
  };
1711
- var _options4, _registeredJobs, _registeredSources, _registeredHttpSourceHandlers, _registeredDynamicTriggers, _jobMetadataByDynamicTriggers, _registeredSchedules, _authResolvers, _client2, _internalLogger, _preprocessRun, preprocessRun_fn, _executeJob, executeJob_fn, _createRunContext, createRunContext_fn, _createPreprocessRunContext, createPreprocessRunContext_fn, _handleHttpSourceRequest, handleHttpSourceRequest_fn, _resolveConnections, resolveConnections_fn, _resolveConnection, resolveConnection_fn, _buildJobsIndex, buildJobsIndex_fn, _buildJobIndex, buildJobIndex_fn, _buildJobIntegrations, buildJobIntegrations_fn, _buildJobIntegration, buildJobIntegration_fn, _logIOStats, logIOStats_fn, _standardResponseHeaders, standardResponseHeaders_fn;
2411
+ var _options4, _registeredJobs, _registeredSources, _registeredHttpSourceHandlers, _registeredDynamicTriggers, _jobMetadataByDynamicTriggers, _registeredSchedules, _registeredHttpEndpoints, _authResolvers, _client2, _internalLogger, _preprocessRun, preprocessRun_fn, _executeJob, executeJob_fn, _convertErrorToExecutionResponse, convertErrorToExecutionResponse_fn, _createRunContext, createRunContext_fn, _createPreprocessRunContext, createPreprocessRunContext_fn, _handleHttpSourceRequest, handleHttpSourceRequest_fn, _handleHttpEndpointRequestForResponse, handleHttpEndpointRequestForResponse_fn, _resolveConnections, resolveConnections_fn, _resolveConnection, resolveConnection_fn, _buildJobsIndex, buildJobsIndex_fn, _buildJobIndex, buildJobIndex_fn, _buildJobIntegrations, buildJobIntegrations_fn, _buildJobIntegration, buildJobIntegration_fn, _logIOStats, logIOStats_fn, _standardResponseHeaders, standardResponseHeaders_fn;
1712
2412
  var TriggerClient = class {
1713
2413
  constructor(options) {
1714
2414
  __privateAdd(this, _preprocessRun);
1715
2415
  __privateAdd(this, _executeJob);
2416
+ __privateAdd(this, _convertErrorToExecutionResponse);
1716
2417
  __privateAdd(this, _createRunContext);
1717
2418
  __privateAdd(this, _createPreprocessRunContext);
1718
2419
  __privateAdd(this, _handleHttpSourceRequest);
2420
+ __privateAdd(this, _handleHttpEndpointRequestForResponse);
1719
2421
  __privateAdd(this, _resolveConnections);
1720
2422
  __privateAdd(this, _resolveConnection);
1721
2423
  __privateAdd(this, _buildJobsIndex);
@@ -1731,13 +2433,14 @@ var TriggerClient = class {
1731
2433
  __privateAdd(this, _registeredDynamicTriggers, {});
1732
2434
  __privateAdd(this, _jobMetadataByDynamicTriggers, {});
1733
2435
  __privateAdd(this, _registeredSchedules, {});
2436
+ __privateAdd(this, _registeredHttpEndpoints, {});
1734
2437
  __privateAdd(this, _authResolvers, {});
1735
2438
  __privateAdd(this, _client2, void 0);
1736
2439
  __privateAdd(this, _internalLogger, void 0);
1737
2440
  this.id = options.id;
1738
2441
  __privateSet(this, _options4, options);
1739
2442
  __privateSet(this, _client2, new ApiClient(__privateGet(this, _options4)));
1740
- __privateSet(this, _internalLogger, new import_core7.Logger("trigger.dev", __privateGet(this, _options4).verbose ? "debug" : "log", [
2443
+ __privateSet(this, _internalLogger, new import_core8.Logger("trigger.dev", __privateGet(this, _options4).verbose ? "debug" : "log", [
1741
2444
  "output",
1742
2445
  "noopTasksSet"
1743
2446
  ]));
@@ -1848,7 +2551,8 @@ var TriggerClient = class {
1848
2551
  dynamicSchedules: Object.entries(__privateGet(this, _registeredSchedules)).map(([id, jobs]) => ({
1849
2552
  id,
1850
2553
  jobs
1851
- }))
2554
+ })),
2555
+ httpEndpoints: Object.entries(__privateGet(this, _registeredHttpEndpoints)).map(([id, endpoint]) => endpoint.toJSON())
1852
2556
  };
1853
2557
  return {
1854
2558
  status: 200,
@@ -1858,7 +2562,7 @@ var TriggerClient = class {
1858
2562
  }
1859
2563
  case "INITIALIZE_TRIGGER": {
1860
2564
  const json = await request.json();
1861
- const body = import_core7.InitializeTriggerBodySchema.safeParse(json);
2565
+ const body = import_core8.InitializeTriggerBodySchema.safeParse(json);
1862
2566
  if (!body.success) {
1863
2567
  return {
1864
2568
  status: 400,
@@ -1884,7 +2588,7 @@ var TriggerClient = class {
1884
2588
  }
1885
2589
  case "EXECUTE_JOB": {
1886
2590
  const json = await request.json();
1887
- const execution = import_core7.RunJobBodySchema.safeParse(json);
2591
+ const execution = import_core8.RunJobBodySchema.safeParse(json);
1888
2592
  if (!execution.success) {
1889
2593
  return {
1890
2594
  status: 400,
@@ -1903,6 +2607,12 @@ var TriggerClient = class {
1903
2607
  };
1904
2608
  }
1905
2609
  const results = await __privateMethod(this, _executeJob, executeJob_fn).call(this, execution.data, job, timeOrigin, triggerVersion);
2610
+ __privateGet(this, _internalLogger).debug("executed job", {
2611
+ results,
2612
+ job: job.id,
2613
+ version: job.version,
2614
+ triggerVersion
2615
+ });
1906
2616
  return {
1907
2617
  status: 200,
1908
2618
  body: results,
@@ -1911,7 +2621,7 @@ var TriggerClient = class {
1911
2621
  }
1912
2622
  case "PREPROCESS_RUN": {
1913
2623
  const json = await request.json();
1914
- const body = import_core7.PreprocessRunBodySchema.safeParse(json);
2624
+ const body = import_core8.PreprocessRunBodySchema.safeParse(json);
1915
2625
  if (!body.success) {
1916
2626
  return {
1917
2627
  status: 400,
@@ -1940,7 +2650,7 @@ var TriggerClient = class {
1940
2650
  };
1941
2651
  }
1942
2652
  case "DELIVER_HTTP_SOURCE_REQUEST": {
1943
- const headers = import_core7.HttpSourceRequestHeadersSchema.safeParse(Object.fromEntries(request.headers.entries()));
2653
+ const headers = import_core8.HttpSourceRequestHeadersSchema.safeParse(Object.fromEntries(request.headers.entries()));
1944
2654
  if (!headers.success) {
1945
2655
  return {
1946
2656
  status: 400,
@@ -1989,6 +2699,39 @@ var TriggerClient = class {
1989
2699
  headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1990
2700
  };
1991
2701
  }
2702
+ case "DELIVER_HTTP_ENDPOINT_REQUEST_FOR_RESPONSE": {
2703
+ const headers = import_core8.HttpEndpointRequestHeadersSchema.safeParse(Object.fromEntries(request.headers.entries()));
2704
+ if (!headers.success) {
2705
+ return {
2706
+ status: 400,
2707
+ body: {
2708
+ message: "Invalid headers"
2709
+ }
2710
+ };
2711
+ }
2712
+ const sourceRequestNeedsBody = headers.data["x-ts-http-method"] !== "GET";
2713
+ const sourceRequestInit = {
2714
+ method: headers.data["x-ts-http-method"],
2715
+ headers: headers.data["x-ts-http-headers"],
2716
+ body: sourceRequestNeedsBody ? request.body : void 0
2717
+ };
2718
+ if (sourceRequestNeedsBody) {
2719
+ try {
2720
+ sourceRequestInit.duplex = "half";
2721
+ } catch (error) {
2722
+ }
2723
+ }
2724
+ const sourceRequest = new Request(headers.data["x-ts-http-url"], sourceRequestInit);
2725
+ const key = headers.data["x-ts-key"];
2726
+ const { response } = await __privateMethod(this, _handleHttpEndpointRequestForResponse, handleHttpEndpointRequestForResponse_fn).call(this, {
2727
+ key
2728
+ }, sourceRequest);
2729
+ return {
2730
+ status: 200,
2731
+ body: response,
2732
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
2733
+ };
2734
+ }
1992
2735
  case "VALIDATE": {
1993
2736
  return {
1994
2737
  status: 200,
@@ -2021,6 +2764,10 @@ var TriggerClient = class {
2021
2764
  };
2022
2765
  }
2023
2766
  defineJob(options) {
2767
+ const existingRegisteredJob = __privateGet(this, _registeredJobs)[options.id];
2768
+ if (existingRegisteredJob) {
2769
+ console.warn((0, import_colorette.yellow)(`[@trigger.dev/sdk] Warning: The Job "${existingRegisteredJob.id}" you're attempting to define has already been defined. Please assign a different ID to the job.`));
2770
+ }
2024
2771
  return new Job(this, options);
2025
2772
  }
2026
2773
  defineAuthResolver(integration, resolver) {
@@ -2033,6 +2780,15 @@ var TriggerClient = class {
2033
2780
  defineDynamicTrigger(options) {
2034
2781
  return new DynamicTrigger(this, options);
2035
2782
  }
2783
+ defineHttpEndpoint(options) {
2784
+ const existingHttpEndpoint = __privateGet(this, _registeredHttpEndpoints)[options.id];
2785
+ if (existingHttpEndpoint) {
2786
+ console.warn((0, import_colorette.yellow)(`[@trigger.dev/sdk] Warning: The HttpEndpoint "${existingHttpEndpoint.id}" you're attempting to define has already been defined. Please assign a different ID to the HttpEndpoint.`));
2787
+ }
2788
+ const endpoint = httpEndpoint(options);
2789
+ __privateGet(this, _registeredHttpEndpoints)[endpoint.id] = endpoint;
2790
+ return endpoint;
2791
+ }
2036
2792
  attach(job) {
2037
2793
  __privateGet(this, _registeredJobs)[job.id] = job;
2038
2794
  job.trigger.attachToJob(this, job);
@@ -2156,6 +2912,9 @@ var TriggerClient = class {
2156
2912
  async sendEvent(event, options) {
2157
2913
  return __privateGet(this, _client2).sendEvent(event, options);
2158
2914
  }
2915
+ async sendEvents(events, options) {
2916
+ return __privateGet(this, _client2).sendEvents(events, options);
2917
+ }
2159
2918
  async cancelEvent(eventId) {
2160
2919
  return __privateGet(this, _client2).cancelEvent(eventId);
2161
2920
  }
@@ -2186,6 +2945,12 @@ var TriggerClient = class {
2186
2945
  async getRunStatuses(runId) {
2187
2946
  return __privateGet(this, _client2).getRunStatuses(runId);
2188
2947
  }
2948
+ async invokeJob(jobId, payload, options) {
2949
+ return __privateGet(this, _client2).invokeJob(jobId, payload, options);
2950
+ }
2951
+ async createEphemeralEventDispatcher(payload) {
2952
+ return __privateGet(this, _client2).createEphemeralEventDispatcher(payload);
2953
+ }
2189
2954
  authorized(apiKey) {
2190
2955
  if (typeof apiKey !== "string") {
2191
2956
  return "missing-header";
@@ -2208,6 +2973,7 @@ _registeredHttpSourceHandlers = new WeakMap();
2208
2973
  _registeredDynamicTriggers = new WeakMap();
2209
2974
  _jobMetadataByDynamicTriggers = new WeakMap();
2210
2975
  _registeredSchedules = new WeakMap();
2976
+ _registeredHttpEndpoints = new WeakMap();
2211
2977
  _authResolvers = new WeakMap();
2212
2978
  _client2 = new WeakMap();
2213
2979
  _internalLogger = new WeakMap();
@@ -2241,7 +3007,7 @@ executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1, timeOrigin, t
2241
3007
  client: this,
2242
3008
  context,
2243
3009
  jobLogLevel: job1.logLevel ?? __privateGet(this, _options4).logLevel ?? "info",
2244
- jobLogger: __privateGet(this, _options4).ioLogLocalEnabled ? new import_core7.Logger(job1.id, job1.logLevel ?? __privateGet(this, _options4).logLevel ?? "info") : void 0,
3010
+ jobLogger: __privateGet(this, _options4).ioLogLocalEnabled ? new import_core8.Logger(job1.id, job1.logLevel ?? __privateGet(this, _options4).logLevel ?? "info") : void 0,
2245
3011
  serverVersion: triggerVersion,
2246
3012
  timeOrigin,
2247
3013
  executionTimeout: body1.runChunkExecutionLimit
@@ -2255,11 +3021,23 @@ executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1, timeOrigin, t
2255
3021
  }
2256
3022
  const ioWithConnections = createIOWithIntegrations(io, resolvedConnections.data, job1.options.integrations);
2257
3023
  try {
3024
+ const parsedPayload = job1.trigger.event.parsePayload(body1.event.payload ?? {});
3025
+ if (!context.run.isTest) {
3026
+ const verified = await job1.trigger.verifyPayload(parsedPayload);
3027
+ if (!verified.success) {
3028
+ return {
3029
+ status: "ERROR",
3030
+ error: {
3031
+ message: `Payload verification failed. ${verified.reason}`
3032
+ }
3033
+ };
3034
+ }
3035
+ }
2258
3036
  const output = await runLocalStorage.runWith({
2259
3037
  io,
2260
3038
  ctx: context
2261
3039
  }, () => {
2262
- return job1.options.run(job1.trigger.event.parsePayload(body1.event.payload ?? {}), ioWithConnections, context);
3040
+ return job1.options.run(parsedPayload, ioWithConnections, context);
2263
3041
  });
2264
3042
  if (__privateGet(this, _options4).verbose) {
2265
3043
  __privateMethod(this, _logIOStats, logIOStats_fn).call(this, io.stats);
@@ -2272,96 +3050,126 @@ executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1, timeOrigin, t
2272
3050
  if (__privateGet(this, _options4).verbose) {
2273
3051
  __privateMethod(this, _logIOStats, logIOStats_fn).call(this, io.stats);
2274
3052
  }
2275
- if (error instanceof AutoYieldExecutionError) {
2276
- return {
2277
- status: "AUTO_YIELD_EXECUTION",
2278
- location: error.location,
2279
- timeRemaining: error.timeRemaining,
2280
- timeElapsed: error.timeElapsed,
2281
- limit: body1.runChunkExecutionLimit
2282
- };
2283
- }
2284
- if (error instanceof AutoYieldWithCompletedTaskExecutionError) {
2285
- return {
2286
- status: "AUTO_YIELD_EXECUTION_WITH_COMPLETED_TASK",
2287
- id: error.id,
2288
- properties: error.properties,
2289
- output: error.output,
2290
- data: {
2291
- ...error.data,
2292
- limit: body1.runChunkExecutionLimit
2293
- }
2294
- };
2295
- }
2296
- if (error instanceof YieldExecutionError) {
2297
- return {
2298
- status: "YIELD_EXECUTION",
2299
- key: error.key
2300
- };
2301
- }
2302
- if (error instanceof ParsedPayloadSchemaError) {
3053
+ if (error instanceof ResumeWithParallelTaskError) {
2303
3054
  return {
2304
- status: "INVALID_PAYLOAD",
2305
- errors: error.schemaErrors
2306
- };
2307
- }
2308
- if (error instanceof ResumeWithTaskError) {
2309
- return {
2310
- status: "RESUME_WITH_TASK",
2311
- task: error.task
2312
- };
2313
- }
2314
- if (error instanceof RetryWithTaskError) {
2315
- return {
2316
- status: "RETRY_WITH_TASK",
3055
+ status: "RESUME_WITH_PARALLEL_TASK",
2317
3056
  task: error.task,
2318
- error: error.cause,
2319
- retryAt: error.retryAt
2320
- };
2321
- }
2322
- if (error instanceof CanceledWithTaskError) {
2323
- return {
2324
- status: "CANCELED",
2325
- task: error.task
3057
+ childErrors: error.childErrors.map((childError) => {
3058
+ return __privateMethod(this, _convertErrorToExecutionResponse, convertErrorToExecutionResponse_fn).call(this, childError, body1);
3059
+ })
2326
3060
  };
2327
3061
  }
2328
- if (error instanceof RetryWithTaskError) {
2329
- const errorWithStack2 = import_core7.ErrorWithStackSchema.safeParse(error.cause);
2330
- if (errorWithStack2.success) {
2331
- return {
2332
- status: "ERROR",
2333
- error: errorWithStack2.data,
2334
- task: error.task
2335
- };
3062
+ return __privateMethod(this, _convertErrorToExecutionResponse, convertErrorToExecutionResponse_fn).call(this, error, body1);
3063
+ }
3064
+ }, "#executeJob");
3065
+ _convertErrorToExecutionResponse = new WeakSet();
3066
+ convertErrorToExecutionResponse_fn = /* @__PURE__ */ __name(function(error, body2) {
3067
+ if (error instanceof AutoYieldExecutionError) {
3068
+ return {
3069
+ status: "AUTO_YIELD_EXECUTION",
3070
+ location: error.location,
3071
+ timeRemaining: error.timeRemaining,
3072
+ timeElapsed: error.timeElapsed,
3073
+ limit: body2.runChunkExecutionLimit
3074
+ };
3075
+ }
3076
+ if (error instanceof AutoYieldWithCompletedTaskExecutionError) {
3077
+ return {
3078
+ status: "AUTO_YIELD_EXECUTION_WITH_COMPLETED_TASK",
3079
+ id: error.id,
3080
+ properties: error.properties,
3081
+ output: error.output,
3082
+ data: {
3083
+ ...error.data,
3084
+ limit: body2.runChunkExecutionLimit
2336
3085
  }
3086
+ };
3087
+ }
3088
+ if (error instanceof YieldExecutionError) {
3089
+ return {
3090
+ status: "YIELD_EXECUTION",
3091
+ key: error.key
3092
+ };
3093
+ }
3094
+ if (error instanceof ParsedPayloadSchemaError) {
3095
+ return {
3096
+ status: "INVALID_PAYLOAD",
3097
+ errors: error.schemaErrors
3098
+ };
3099
+ }
3100
+ if (error instanceof ResumeWithTaskError) {
3101
+ return {
3102
+ status: "RESUME_WITH_TASK",
3103
+ task: error.task
3104
+ };
3105
+ }
3106
+ if (error instanceof RetryWithTaskError) {
3107
+ return {
3108
+ status: "RETRY_WITH_TASK",
3109
+ task: error.task,
3110
+ error: error.cause,
3111
+ retryAt: error.retryAt
3112
+ };
3113
+ }
3114
+ if (error instanceof CanceledWithTaskError) {
3115
+ return {
3116
+ status: "CANCELED",
3117
+ task: error.task
3118
+ };
3119
+ }
3120
+ if (error instanceof ErrorWithTask) {
3121
+ const errorWithStack2 = import_core8.ErrorWithStackSchema.safeParse(error.cause.output);
3122
+ if (errorWithStack2.success) {
2337
3123
  return {
2338
3124
  status: "ERROR",
2339
- error: {
2340
- message: "Unknown error"
2341
- },
2342
- task: error.task
3125
+ error: errorWithStack2.data,
3126
+ task: error.cause
2343
3127
  };
2344
3128
  }
2345
- const errorWithStack = import_core7.ErrorWithStackSchema.safeParse(error);
2346
- if (errorWithStack.success) {
3129
+ return {
3130
+ status: "ERROR",
3131
+ error: {
3132
+ message: JSON.stringify(error.cause.output)
3133
+ },
3134
+ task: error.cause
3135
+ };
3136
+ }
3137
+ if (error instanceof RetryWithTaskError) {
3138
+ const errorWithStack2 = import_core8.ErrorWithStackSchema.safeParse(error.cause);
3139
+ if (errorWithStack2.success) {
2347
3140
  return {
2348
3141
  status: "ERROR",
2349
- error: errorWithStack.data
3142
+ error: errorWithStack2.data,
3143
+ task: error.task
2350
3144
  };
2351
3145
  }
2352
- const message = typeof error === "string" ? error : JSON.stringify(error);
2353
3146
  return {
2354
3147
  status: "ERROR",
2355
3148
  error: {
2356
- name: "Unknown error",
2357
- message
2358
- }
3149
+ message: "Unknown error"
3150
+ },
3151
+ task: error.task
2359
3152
  };
2360
3153
  }
2361
- }, "#executeJob");
3154
+ const errorWithStack = import_core8.ErrorWithStackSchema.safeParse(error);
3155
+ if (errorWithStack.success) {
3156
+ return {
3157
+ status: "ERROR",
3158
+ error: errorWithStack.data
3159
+ };
3160
+ }
3161
+ const message = typeof error === "string" ? error : JSON.stringify(error);
3162
+ return {
3163
+ status: "ERROR",
3164
+ error: {
3165
+ name: "Unknown error",
3166
+ message
3167
+ }
3168
+ };
3169
+ }, "#convertErrorToExecutionResponse");
2362
3170
  _createRunContext = new WeakSet();
2363
3171
  createRunContext_fn = /* @__PURE__ */ __name(function(execution) {
2364
- const { event, organization, environment, job, run, source } = execution;
3172
+ const { event, organization, project, environment, job, run, source } = execution;
2365
3173
  return {
2366
3174
  event: {
2367
3175
  id: event.id,
@@ -2370,6 +3178,11 @@ createRunContext_fn = /* @__PURE__ */ __name(function(execution) {
2370
3178
  timestamp: event.timestamp
2371
3179
  },
2372
3180
  organization,
3181
+ project: project ?? {
3182
+ id: "unknown",
3183
+ name: "unknown",
3184
+ slug: "unknown"
3185
+ },
2373
3186
  environment,
2374
3187
  job,
2375
3188
  run,
@@ -2378,8 +3191,8 @@ createRunContext_fn = /* @__PURE__ */ __name(function(execution) {
2378
3191
  };
2379
3192
  }, "#createRunContext");
2380
3193
  _createPreprocessRunContext = new WeakSet();
2381
- createPreprocessRunContext_fn = /* @__PURE__ */ __name(function(body2) {
2382
- const { event, organization, environment, job, run, account } = body2;
3194
+ createPreprocessRunContext_fn = /* @__PURE__ */ __name(function(body3) {
3195
+ const { event, organization, environment, job, run, account } = body3;
2383
3196
  return {
2384
3197
  event: {
2385
3198
  id: event.id,
@@ -2476,6 +3289,59 @@ handleHttpSourceRequest_fn = /* @__PURE__ */ __name(async function(source, sourc
2476
3289
  metadata: results.metadata
2477
3290
  };
2478
3291
  }, "#handleHttpSourceRequest");
3292
+ _handleHttpEndpointRequestForResponse = new WeakSet();
3293
+ handleHttpEndpointRequestForResponse_fn = /* @__PURE__ */ __name(async function(data, sourceRequest1) {
3294
+ __privateGet(this, _internalLogger).debug("Handling HTTP Endpoint request for response", {
3295
+ data
3296
+ });
3297
+ const httpEndpoint2 = __privateGet(this, _registeredHttpEndpoints)[data.key];
3298
+ if (!httpEndpoint2) {
3299
+ __privateGet(this, _internalLogger).debug("No handler registered for HTTP Endpoint", {
3300
+ data
3301
+ });
3302
+ return {
3303
+ response: {
3304
+ status: 200,
3305
+ body: {
3306
+ ok: true
3307
+ }
3308
+ }
3309
+ };
3310
+ }
3311
+ const handledResponse = await httpEndpoint2.handleRequest(sourceRequest1);
3312
+ if (!handledResponse) {
3313
+ __privateGet(this, _internalLogger).debug("There's no HTTP Endpoint respondWith.handler()", {
3314
+ data
3315
+ });
3316
+ return {
3317
+ response: {
3318
+ status: 200,
3319
+ body: {
3320
+ ok: true
3321
+ }
3322
+ }
3323
+ };
3324
+ }
3325
+ let body;
3326
+ try {
3327
+ body = await handledResponse.text();
3328
+ } catch (error) {
3329
+ __privateGet(this, _internalLogger).error(`Error reading httpEndpoint ${httpEndpoint2.id} respondWith.handler Response`, {
3330
+ error
3331
+ });
3332
+ }
3333
+ const response = {
3334
+ status: handledResponse.status,
3335
+ headers: handledResponse.headers ? Object.fromEntries(handledResponse.headers.entries()) : void 0,
3336
+ body
3337
+ };
3338
+ __privateGet(this, _internalLogger).info(`httpEndpoint ${httpEndpoint2.id} respondWith.handler response`, {
3339
+ response
3340
+ });
3341
+ return {
3342
+ response
3343
+ };
3344
+ }, "#handleHttpEndpointRequestForResponse");
2479
3345
  _resolveConnections = new WeakSet();
2480
3346
  resolveConnections_fn = /* @__PURE__ */ __name(async function(ctx, integrations, connections) {
2481
3347
  if (!integrations) {
@@ -2633,7 +3499,7 @@ logIOStats_fn = /* @__PURE__ */ __name(function(stats) {
2633
3499
  _standardResponseHeaders = new WeakSet();
2634
3500
  standardResponseHeaders_fn = /* @__PURE__ */ __name(function(start) {
2635
3501
  return {
2636
- "Trigger-Version": import_core7.API_VERSIONS.LAZY_LOADED_CACHED_TASKS,
3502
+ "Trigger-Version": import_core8.API_VERSIONS.LAZY_LOADED_CACHED_TASKS,
2637
3503
  "Trigger-SDK-Version": version,
2638
3504
  "X-Trigger-Request-Timing": `dur=${performance.now() - start / 1e3}`
2639
3505
  };
@@ -2663,7 +3529,7 @@ function deepMergeOptions(obj1, obj2) {
2663
3529
  __name(deepMergeOptions, "deepMergeOptions");
2664
3530
 
2665
3531
  // src/triggers/externalSource.ts
2666
- var import_core8 = require("@trigger.dev/core");
3532
+ var import_core9 = require("@trigger.dev/core");
2667
3533
  var ExternalSource = class {
2668
3534
  constructor(channel, options) {
2669
3535
  this.options = options;
@@ -2737,7 +3603,7 @@ var ExternalSourceTrigger = class {
2737
3603
  title: "External Source",
2738
3604
  rule: {
2739
3605
  event: this.event.name,
2740
- payload: (0, import_core8.deepMergeFilters)(this.options.source.filter(this.options.params, this.options.options), this.event.filter ?? {}, this.options.params.filter ?? {}),
3606
+ payload: (0, import_core9.deepMergeFilters)(this.options.source.filter(this.options.params, this.options.options), this.event.filter ?? {}, this.options.params.filter ?? {}),
2741
3607
  source: this.event.source
2742
3608
  },
2743
3609
  properties: this.options.source.properties(this.options.params)
@@ -2755,6 +3621,11 @@ var ExternalSourceTrigger = class {
2755
3621
  get preprocessRuns() {
2756
3622
  return true;
2757
3623
  }
3624
+ async verifyPayload(payload) {
3625
+ return {
3626
+ success: true
3627
+ };
3628
+ }
2758
3629
  };
2759
3630
  __name(ExternalSourceTrigger, "ExternalSourceTrigger");
2760
3631
  function omit(obj, key) {
@@ -2772,7 +3643,7 @@ function omit(obj, key) {
2772
3643
  __name(omit, "omit");
2773
3644
 
2774
3645
  // src/triggers/notifications.ts
2775
- var import_core9 = require("@trigger.dev/core");
3646
+ var import_core10 = require("@trigger.dev/core");
2776
3647
  function missingConnectionNotification(integrations) {
2777
3648
  return new MissingConnectionNotification({
2778
3649
  integrations
@@ -2791,11 +3662,11 @@ var MissingConnectionNotification = class {
2791
3662
  }
2792
3663
  get event() {
2793
3664
  return {
2794
- name: import_core9.MISSING_CONNECTION_NOTIFICATION,
3665
+ name: import_core10.MISSING_CONNECTION_NOTIFICATION,
2795
3666
  title: "Missing Connection Notification",
2796
3667
  source: "trigger.dev",
2797
3668
  icon: "connection-alert",
2798
- parsePayload: import_core9.MissingConnectionNotificationPayloadSchema.parse,
3669
+ parsePayload: import_core10.MissingConnectionNotificationPayloadSchema.parse,
2799
3670
  properties: [
2800
3671
  {
2801
3672
  label: "Integrations",
@@ -2809,6 +3680,11 @@ var MissingConnectionNotification = class {
2809
3680
  get preprocessRuns() {
2810
3681
  return false;
2811
3682
  }
3683
+ async verifyPayload(payload) {
3684
+ return {
3685
+ success: true
3686
+ };
3687
+ }
2812
3688
  toJSON() {
2813
3689
  return {
2814
3690
  type: "static",
@@ -2832,11 +3708,11 @@ var MissingConnectionResolvedNotification = class {
2832
3708
  }
2833
3709
  get event() {
2834
3710
  return {
2835
- name: import_core9.MISSING_CONNECTION_RESOLVED_NOTIFICATION,
3711
+ name: import_core10.MISSING_CONNECTION_RESOLVED_NOTIFICATION,
2836
3712
  title: "Missing Connection Resolved Notification",
2837
3713
  source: "trigger.dev",
2838
3714
  icon: "connection-alert",
2839
- parsePayload: import_core9.MissingConnectionResolvedNotificationPayloadSchema.parse,
3715
+ parsePayload: import_core10.MissingConnectionResolvedNotificationPayloadSchema.parse,
2840
3716
  properties: [
2841
3717
  {
2842
3718
  label: "Integrations",
@@ -2850,6 +3726,11 @@ var MissingConnectionResolvedNotification = class {
2850
3726
  get preprocessRuns() {
2851
3727
  return false;
2852
3728
  }
3729
+ async verifyPayload(payload) {
3730
+ return {
3731
+ success: true
3732
+ };
3733
+ }
2853
3734
  toJSON() {
2854
3735
  return {
2855
3736
  type: "static",
@@ -2868,6 +3749,106 @@ var MissingConnectionResolvedNotification = class {
2868
3749
  };
2869
3750
  __name(MissingConnectionResolvedNotification, "MissingConnectionResolvedNotification");
2870
3751
 
3752
+ // src/triggers/invokeTrigger.ts
3753
+ var _options5;
3754
+ var InvokeTrigger = class {
3755
+ constructor(options) {
3756
+ __privateAdd(this, _options5, void 0);
3757
+ __privateSet(this, _options5, options);
3758
+ }
3759
+ toJSON() {
3760
+ return {
3761
+ type: "invoke"
3762
+ };
3763
+ }
3764
+ get event() {
3765
+ return {
3766
+ name: "invoke",
3767
+ title: "Manual Invoke",
3768
+ source: "trigger.dev",
3769
+ examples: __privateGet(this, _options5).examples ?? [],
3770
+ icon: "trigger",
3771
+ parsePayload: (rawPayload) => {
3772
+ if (__privateGet(this, _options5).schema) {
3773
+ const results = __privateGet(this, _options5).schema.safeParse(rawPayload);
3774
+ if (!results.success) {
3775
+ throw new ParsedPayloadSchemaError(formatSchemaErrors(results.error.issues));
3776
+ }
3777
+ return results.data;
3778
+ }
3779
+ return rawPayload;
3780
+ },
3781
+ parseInvokePayload: (rawPayload) => {
3782
+ if (__privateGet(this, _options5).schema) {
3783
+ const results = __privateGet(this, _options5).schema.safeParse(rawPayload);
3784
+ if (!results.success) {
3785
+ throw new ParsedPayloadSchemaError(formatSchemaErrors(results.error.issues));
3786
+ }
3787
+ return results.data;
3788
+ }
3789
+ return rawPayload;
3790
+ }
3791
+ };
3792
+ }
3793
+ attachToJob(triggerClient, job) {
3794
+ }
3795
+ get preprocessRuns() {
3796
+ return false;
3797
+ }
3798
+ async verifyPayload() {
3799
+ return {
3800
+ success: true
3801
+ };
3802
+ }
3803
+ };
3804
+ __name(InvokeTrigger, "InvokeTrigger");
3805
+ _options5 = new WeakMap();
3806
+ function invokeTrigger(options) {
3807
+ return new InvokeTrigger(options ?? {});
3808
+ }
3809
+ __name(invokeTrigger, "invokeTrigger");
3810
+
3811
+ // src/security.ts
3812
+ var import_crypto = __toESM(require("crypto"));
3813
+ async function verifyRequestSignature({ request, headerName, secret, algorithm }) {
3814
+ if (!secret) {
3815
+ return {
3816
+ success: false,
3817
+ reason: "Missing secret \u2013 you've probably not set an environment variable."
3818
+ };
3819
+ }
3820
+ const headerValue = request.headers.get(headerName);
3821
+ if (!headerValue) {
3822
+ return {
3823
+ success: false,
3824
+ reason: "Missing header"
3825
+ };
3826
+ }
3827
+ switch (algorithm) {
3828
+ case "sha256":
3829
+ const success = verifyHmacSha256(headerValue, secret, await request.text());
3830
+ if (success) {
3831
+ return {
3832
+ success
3833
+ };
3834
+ } else {
3835
+ return {
3836
+ success: false,
3837
+ reason: "Failed sha256 verification"
3838
+ };
3839
+ }
3840
+ default:
3841
+ throw new Error(`Unsupported algorithm: ${algorithm}`);
3842
+ }
3843
+ }
3844
+ __name(verifyRequestSignature, "verifyRequestSignature");
3845
+ function verifyHmacSha256(headerValue, secret, body) {
3846
+ const bodyDigest = import_crypto.default.createHmac("sha256", secret).update(body).digest("hex");
3847
+ const signature = headerValue?.replace("sha256=", "") ?? "";
3848
+ return signature === bodyDigest;
3849
+ }
3850
+ __name(verifyHmacSha256, "verifyHmacSha256");
3851
+
2871
3852
  // src/index.ts
2872
3853
  function redactString(strings, ...interpolations) {
2873
3854
  return {
@@ -2882,12 +3863,15 @@ __name(redactString, "redactString");
2882
3863
  CronTrigger,
2883
3864
  DynamicSchedule,
2884
3865
  DynamicTrigger,
3866
+ EventSpecificationExampleSchema,
2885
3867
  EventTrigger,
2886
3868
  ExternalSource,
2887
3869
  ExternalSourceTrigger,
2888
3870
  IO,
2889
3871
  IOLogger,
2890
3872
  IntervalTrigger,
3873
+ InvokeTrigger,
3874
+ JSONOutputSerializer,
2891
3875
  Job,
2892
3876
  MissingConnectionNotification,
2893
3877
  MissingConnectionResolvedNotification,
@@ -2895,11 +3879,15 @@ __name(redactString, "redactString");
2895
3879
  cronTrigger,
2896
3880
  eventTrigger,
2897
3881
  intervalTrigger,
3882
+ invokeTrigger,
2898
3883
  isTriggerError,
2899
3884
  missingConnectionNotification,
2900
3885
  missingConnectionResolvedNotification,
2901
3886
  omit,
2902
3887
  redactString,
2903
- retry
3888
+ retry,
3889
+ verifyHmacSha256,
3890
+ verifyRequestSignature,
3891
+ waitForEventSchema
2904
3892
  });
2905
3893
  //# sourceMappingURL=index.js.map