@trigger.dev/sdk 0.0.0-dev-20231004120419 → 0.0.0-invoke-trigger-20231103104037

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
@@ -63,6 +63,8 @@ __export(src_exports, {
63
63
  IO: () => IO,
64
64
  IOLogger: () => IOLogger,
65
65
  IntervalTrigger: () => IntervalTrigger,
66
+ InvokeTrigger: () => InvokeTrigger,
67
+ JSONOutputSerializer: () => JSONOutputSerializer,
66
68
  Job: () => Job,
67
69
  MissingConnectionNotification: () => MissingConnectionNotification,
68
70
  MissingConnectionResolvedNotification: () => MissingConnectionResolvedNotification,
@@ -70,6 +72,7 @@ __export(src_exports, {
70
72
  cronTrigger: () => cronTrigger,
71
73
  eventTrigger: () => eventTrigger,
72
74
  intervalTrigger: () => intervalTrigger,
75
+ invokeTrigger: () => invokeTrigger,
73
76
  isTriggerError: () => isTriggerError,
74
77
  missingConnectionNotification: () => missingConnectionNotification,
75
78
  missingConnectionResolvedNotification: () => missingConnectionResolvedNotification,
@@ -87,6 +90,24 @@ function slugifyId(input) {
87
90
  }
88
91
  __name(slugifyId, "slugifyId");
89
92
 
93
+ // src/utils/typedAsyncLocalStorage.ts
94
+ var import_node_async_hooks = require("async_hooks");
95
+ var TypedAsyncLocalStorage = class {
96
+ constructor() {
97
+ this.storage = new import_node_async_hooks.AsyncLocalStorage();
98
+ }
99
+ runWith(context, fn) {
100
+ return this.storage.run(context, fn);
101
+ }
102
+ getStore() {
103
+ return this.storage.getStore();
104
+ }
105
+ };
106
+ __name(TypedAsyncLocalStorage, "TypedAsyncLocalStorage");
107
+
108
+ // src/runLocalStorage.ts
109
+ var runLocalStorage = new TypedAsyncLocalStorage();
110
+
90
111
  // src/job.ts
91
112
  var _validate, validate_fn;
92
113
  var Job = class {
@@ -141,6 +162,118 @@ var Job = class {
141
162
  internal
142
163
  };
143
164
  }
165
+ async invoke(param1, param2 = void 0, param3 = void 0) {
166
+ const runStore = runLocalStorage.getStore();
167
+ if (typeof param1 === "string") {
168
+ if (!runStore) {
169
+ 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.");
170
+ }
171
+ const options = param3 ?? {};
172
+ return await runStore.io.runTask(param1, async (task) => {
173
+ const result = await this.client.invokeJob(this.id, param2, {
174
+ idempotencyKey: task.idempotencyKey,
175
+ ...options
176
+ });
177
+ task.outputProperties = [
178
+ {
179
+ label: "Run",
180
+ text: result.id,
181
+ url: `/orgs/${runStore.ctx.organization.slug}/projects/${runStore.ctx.project.slug}/jobs/${this.id}/runs/${result.id}/trigger`
182
+ }
183
+ ];
184
+ return result;
185
+ }, {
186
+ name: `Manually Invoke '${this.name}'`,
187
+ params: param2,
188
+ properties: [
189
+ {
190
+ label: "Job",
191
+ text: this.id,
192
+ url: `/orgs/${runStore.ctx.organization.slug}/projects/${runStore.ctx.project.slug}/jobs/${this.id}`
193
+ },
194
+ {
195
+ label: "Env",
196
+ text: runStore.ctx.environment.slug
197
+ }
198
+ ]
199
+ });
200
+ }
201
+ if (runStore) {
202
+ throw new Error("Cannot invoke a job from within a run without a cacheKey.");
203
+ }
204
+ return await this.client.invokeJob(this.id, param1, param3);
205
+ }
206
+ async invokeAndWaitForCompletion(cacheKey, payload, timeoutInSeconds = 60 * 60, options = {}) {
207
+ const runStore = runLocalStorage.getStore();
208
+ if (!runStore) {
209
+ 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.");
210
+ }
211
+ const { io, ctx } = runStore;
212
+ return await io.runTask(cacheKey, async (task) => {
213
+ const parsedPayload = this.trigger.event.parseInvokePayload ? this.trigger.event.parseInvokePayload(payload) ? payload : void 0 : payload;
214
+ const result = await this.client.invokeJob(this.id, parsedPayload, {
215
+ idempotencyKey: task.idempotencyKey,
216
+ callbackUrl: task.callbackUrl ?? void 0,
217
+ ...options
218
+ });
219
+ task.outputProperties = [
220
+ {
221
+ label: "Run",
222
+ text: result.id,
223
+ url: `/orgs/${ctx.organization.slug}/projects/${ctx.project.slug}/jobs/${this.id}/runs/${result.id}/trigger`
224
+ }
225
+ ];
226
+ return {};
227
+ }, {
228
+ name: `Manually Invoke '${this.name}' and wait for completion`,
229
+ params: payload,
230
+ properties: [
231
+ {
232
+ label: "Job",
233
+ text: this.id,
234
+ url: `/orgs/${ctx.organization.slug}/projects/${ctx.project.slug}/jobs/${this.id}`
235
+ },
236
+ {
237
+ label: "Env",
238
+ text: ctx.environment.slug
239
+ }
240
+ ],
241
+ callback: {
242
+ enabled: true,
243
+ timeoutInSeconds
244
+ }
245
+ });
246
+ }
247
+ async batchInvokeAndWaitForCompletion(cacheKey, batch) {
248
+ const runStore = runLocalStorage.getStore();
249
+ if (!runStore) {
250
+ throw new Error("Cannot invoke a job from outside of a run using batchInvokeAndWaitForCompletion.");
251
+ }
252
+ if (batch.length === 0) {
253
+ return [];
254
+ }
255
+ if (batch.length > 25) {
256
+ throw new Error(`Cannot batch invoke more than 25 items. You tried to batch invoke ${batch.length} items.`);
257
+ }
258
+ const { io, ctx } = runStore;
259
+ const results = await io.parallel(cacheKey, batch, async (item, index) => {
260
+ return await this.invokeAndWaitForCompletion(String(index), item.payload, item.timeoutInSeconds ?? 60 * 60, item.options);
261
+ }, {
262
+ name: `Batch Invoke '${this.name}'`,
263
+ properties: [
264
+ {
265
+ label: "Job",
266
+ text: this.id,
267
+ url: `/orgs/${ctx.organization.slug}/projects/${ctx.project.slug}/jobs/${this.id}`
268
+ },
269
+ {
270
+ label: "Env",
271
+ text: ctx.environment.slug
272
+ }
273
+ ]
274
+ });
275
+ return results;
276
+ }
144
277
  };
145
278
  __name(Job, "Job");
146
279
  _validate = new WeakSet();
@@ -155,7 +288,6 @@ var import_core7 = require("@trigger.dev/core");
155
288
 
156
289
  // src/apiClient.ts
157
290
  var import_core = require("@trigger.dev/core");
158
- var import_node_fetch = __toESM(require("node-fetch"));
159
291
  var import_zod = require("zod");
160
292
  var _apiUrl, _options, _logger, _apiKey, apiKey_fn;
161
293
  var ApiClient = class {
@@ -174,7 +306,7 @@ var ApiClient = class {
174
306
  url: options.url,
175
307
  name: options.name
176
308
  });
177
- const response = await (0, import_node_fetch.default)(`${__privateGet(this, _apiUrl)}/api/v1/endpoints`, {
309
+ const response = await fetch(`${__privateGet(this, _apiUrl)}/api/v1/endpoints`, {
178
310
  method: "POST",
179
311
  headers: {
180
312
  "Content-Type": "application/json",
@@ -222,7 +354,8 @@ var ApiClient = class {
222
354
  method: "POST",
223
355
  headers: {
224
356
  "Content-Type": "application/json",
225
- Authorization: `Bearer ${apiKey}`
357
+ Authorization: `Bearer ${apiKey}`,
358
+ "Trigger-Version": import_core.API_VERSIONS.SERIALIZED_TASK_OUTPUT
226
359
  },
227
360
  body: JSON.stringify(task)
228
361
  });
@@ -273,6 +406,19 @@ var ApiClient = class {
273
406
  }
274
407
  });
275
408
  }
409
+ async cancelRunsForEvent(eventId) {
410
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
411
+ __privateGet(this, _logger).debug("Cancelling runs for event", {
412
+ eventId
413
+ });
414
+ return await zodfetch(import_core.CancelRunsForEventSchema, `${__privateGet(this, _apiUrl)}/api/v1/events/${eventId}/cancel-runs`, {
415
+ method: "POST",
416
+ headers: {
417
+ "Content-Type": "application/json",
418
+ Authorization: `Bearer ${apiKey}`
419
+ }
420
+ });
421
+ }
276
422
  async updateStatus(runId, id, status) {
277
423
  const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
278
424
  __privateGet(this, _logger).debug("Update status", {
@@ -303,18 +449,22 @@ var ApiClient = class {
303
449
  });
304
450
  return response;
305
451
  }
306
- async registerTrigger(client, id, key, payload) {
452
+ async registerTrigger(client, id, key, payload, idempotencyKey) {
307
453
  const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
308
454
  __privateGet(this, _logger).debug("registering trigger", {
309
455
  id,
310
456
  payload
311
457
  });
458
+ const headers = {
459
+ "Content-Type": "application/json",
460
+ Authorization: `Bearer ${apiKey}`
461
+ };
462
+ if (idempotencyKey) {
463
+ headers["Idempotency-Key"] = idempotencyKey;
464
+ }
312
465
  const response = await zodfetch(import_core.RegisterSourceEventSchemaV2, `${__privateGet(this, _apiUrl)}/api/v2/${client}/triggers/${id}/registrations/${key}`, {
313
466
  method: "PUT",
314
- headers: {
315
- "Content-Type": "application/json",
316
- Authorization: `Bearer ${apiKey}`
317
- },
467
+ headers,
318
468
  body: JSON.stringify(payload)
319
469
  });
320
470
  return response;
@@ -394,6 +544,19 @@ var ApiClient = class {
394
544
  }
395
545
  });
396
546
  }
547
+ async cancelRun(runId) {
548
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
549
+ __privateGet(this, _logger).debug("Cancelling Run", {
550
+ runId
551
+ });
552
+ return await zodfetch(import_core.GetRunSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/cancel`, {
553
+ method: "POST",
554
+ headers: {
555
+ "Content-Type": "application/json",
556
+ Authorization: `Bearer ${apiKey}`
557
+ }
558
+ });
559
+ }
397
560
  async getRunStatuses(runId) {
398
561
  const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
399
562
  __privateGet(this, _logger).debug("Getting Run statuses", {
@@ -418,6 +581,31 @@ var ApiClient = class {
418
581
  }
419
582
  });
420
583
  }
584
+ async invokeJob(jobId, payload, options = {}) {
585
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
586
+ __privateGet(this, _logger).debug("Invoking Job", {
587
+ jobId
588
+ });
589
+ const body = {
590
+ payload,
591
+ context: options.context ?? {},
592
+ options: {
593
+ accountId: options.accountId,
594
+ callbackUrl: options.callbackUrl
595
+ }
596
+ };
597
+ return await zodfetch(import_core.InvokeJobResponseSchema, `${__privateGet(this, _apiUrl)}/api/v1/jobs/${jobId}/invoke`, {
598
+ method: "POST",
599
+ headers: {
600
+ "Content-Type": "application/json",
601
+ Authorization: `Bearer ${apiKey}`,
602
+ ...options.idempotencyKey ? {
603
+ "Idempotency-Key": options.idempotencyKey
604
+ } : {}
605
+ },
606
+ body: JSON.stringify(body)
607
+ });
608
+ }
421
609
  };
422
610
  __name(ApiClient, "ApiClient");
423
611
  _apiUrl = new WeakMap();
@@ -453,8 +641,8 @@ function getApiKey(key) {
453
641
  };
454
642
  }
455
643
  __name(getApiKey, "getApiKey");
456
- async function zodfetchWithVersions(versionedSchemaMap, unversionedSchema, url, requestInit, options) {
457
- const response = await (0, import_node_fetch.default)(url, requestInit);
644
+ async function zodfetchWithVersions(versionedSchemaMap, unversionedSchema, url, requestInit, options, retryCount = 0) {
645
+ const response = await fetch(url, requestInit);
458
646
  if ((!requestInit || requestInit.method === "GET") && response.status === 404 && options?.optional) {
459
647
  return;
460
648
  }
@@ -462,29 +650,34 @@ async function zodfetchWithVersions(versionedSchemaMap, unversionedSchema, url,
462
650
  const body = await response.json();
463
651
  throw new Error(body.error);
464
652
  }
653
+ if (response.status >= 500 && retryCount < 6) {
654
+ const delay = exponentialBackoff(retryCount + 1, 2, 50, 1150, 50);
655
+ await new Promise((resolve) => setTimeout(resolve, delay));
656
+ return zodfetchWithVersions(versionedSchemaMap, unversionedSchema, url, requestInit, options, retryCount + 1);
657
+ }
465
658
  if (response.status !== 200) {
466
659
  throw new Error(options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`);
467
660
  }
468
661
  const jsonBody = await response.json();
469
- const version = response.headers.get("trigger-version");
470
- if (!version) {
662
+ const version2 = response.headers.get("trigger-version");
663
+ if (!version2) {
471
664
  return {
472
665
  version: "unversioned",
473
666
  body: unversionedSchema.parse(jsonBody)
474
667
  };
475
668
  }
476
- const versionedSchema = versionedSchemaMap[version];
669
+ const versionedSchema = versionedSchemaMap[version2];
477
670
  if (!versionedSchema) {
478
- throw new Error(`Unknown version ${version}`);
671
+ throw new Error(`Unknown version ${version2}`);
479
672
  }
480
673
  return {
481
- version,
674
+ version: version2,
482
675
  body: versionedSchema.parse(jsonBody)
483
676
  };
484
677
  }
485
678
  __name(zodfetchWithVersions, "zodfetchWithVersions");
486
- async function zodfetch(schema, url, requestInit, options) {
487
- const response = await (0, import_node_fetch.default)(url, requestInit);
679
+ async function zodfetch(schema, url, requestInit, options, retryCount = 0) {
680
+ const response = await fetch(url, requestInit);
488
681
  if ((!requestInit || requestInit.method === "GET") && response.status === 404 && options?.optional) {
489
682
  return;
490
683
  }
@@ -492,6 +685,11 @@ async function zodfetch(schema, url, requestInit, options) {
492
685
  const body = await response.json();
493
686
  throw new Error(body.error);
494
687
  }
688
+ if (response.status >= 500 && retryCount < 6) {
689
+ const delay = exponentialBackoff(retryCount + 1, 2, 50, 1150, 50);
690
+ await new Promise((resolve) => setTimeout(resolve, delay));
691
+ return zodfetch(schema, url, requestInit, options, retryCount + 1);
692
+ }
495
693
  if (response.status !== 200) {
496
694
  throw new Error(options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`);
497
695
  }
@@ -499,6 +697,12 @@ async function zodfetch(schema, url, requestInit, options) {
499
697
  return schema.parse(jsonBody);
500
698
  }
501
699
  __name(zodfetch, "zodfetch");
700
+ function exponentialBackoff(retryCount, exponential, minDelay, maxDelay, jitter) {
701
+ const delay = Math.min(Math.pow(exponential, retryCount) * minDelay, maxDelay);
702
+ const jitterValue = Math.random() * jitter;
703
+ return delay + jitterValue;
704
+ }
705
+ __name(exponentialBackoff, "exponentialBackoff");
502
706
 
503
707
  // src/errors.ts
504
708
  var ResumeWithTaskError = class {
@@ -507,6 +711,13 @@ var ResumeWithTaskError = class {
507
711
  }
508
712
  };
509
713
  __name(ResumeWithTaskError, "ResumeWithTaskError");
714
+ var ResumeWithParallelTaskError = class {
715
+ constructor(task, childErrors) {
716
+ this.task = task;
717
+ this.childErrors = childErrors;
718
+ }
719
+ };
720
+ __name(ResumeWithParallelTaskError, "ResumeWithParallelTaskError");
510
721
  var RetryWithTaskError = class {
511
722
  constructor(cause, task, retryAt) {
512
723
  this.cause = cause;
@@ -527,6 +738,23 @@ var YieldExecutionError = class {
527
738
  }
528
739
  };
529
740
  __name(YieldExecutionError, "YieldExecutionError");
741
+ var AutoYieldExecutionError = class {
742
+ constructor(location, timeRemaining, timeElapsed) {
743
+ this.location = location;
744
+ this.timeRemaining = timeRemaining;
745
+ this.timeElapsed = timeElapsed;
746
+ }
747
+ };
748
+ __name(AutoYieldExecutionError, "AutoYieldExecutionError");
749
+ var AutoYieldWithCompletedTaskExecutionError = class {
750
+ constructor(id, properties, data, output) {
751
+ this.id = id;
752
+ this.properties = properties;
753
+ this.data = data;
754
+ this.output = output;
755
+ }
756
+ };
757
+ __name(AutoYieldWithCompletedTaskExecutionError, "AutoYieldWithCompletedTaskExecutionError");
530
758
  var ParsedPayloadSchemaError = class {
531
759
  constructor(schemaErrors) {
532
760
  this.schemaErrors = schemaErrors;
@@ -534,13 +762,21 @@ var ParsedPayloadSchemaError = class {
534
762
  };
535
763
  __name(ParsedPayloadSchemaError, "ParsedPayloadSchemaError");
536
764
  function isTriggerError(err) {
537
- return err instanceof ResumeWithTaskError || err instanceof RetryWithTaskError || err instanceof CanceledWithTaskError || err instanceof YieldExecutionError;
765
+ return err instanceof ResumeWithTaskError || err instanceof RetryWithTaskError || err instanceof CanceledWithTaskError || err instanceof YieldExecutionError || err instanceof AutoYieldExecutionError || err instanceof AutoYieldWithCompletedTaskExecutionError || err instanceof ResumeWithParallelTaskError;
538
766
  }
539
767
  __name(isTriggerError, "isTriggerError");
768
+ var ErrorWithTask = class extends Error {
769
+ constructor(cause, message) {
770
+ super(message);
771
+ this.cause = cause;
772
+ }
773
+ };
774
+ __name(ErrorWithTask, "ErrorWithTask");
540
775
 
541
776
  // src/io.ts
542
777
  var import_core3 = require("@trigger.dev/core");
543
- var import_node_async_hooks = require("async_hooks");
778
+ var import_core_backend = require("@trigger.dev/core-backend");
779
+ var import_node_async_hooks2 = require("async_hooks");
544
780
  var import_node_crypto = require("crypto");
545
781
 
546
782
  // src/retry.ts
@@ -590,10 +826,25 @@ var TriggerStatus = class {
590
826
  __name(TriggerStatus, "TriggerStatus");
591
827
 
592
828
  // src/io.ts
593
- var _addToCachedTasks, addToCachedTasks_fn;
829
+ var JSONOutputSerializer = class {
830
+ serialize(value) {
831
+ return JSON.stringify(value);
832
+ }
833
+ deserialize(value) {
834
+ return value ? JSON.parse(value) : void 0;
835
+ }
836
+ };
837
+ __name(JSONOutputSerializer, "JSONOutputSerializer");
838
+ var _addToCachedTasks, addToCachedTasks_fn, _detectAutoYield, detectAutoYield_fn, _forceYield, forceYield_fn, _getTimeElapsed, getTimeElapsed_fn, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn;
594
839
  var IO = class {
595
840
  constructor(options) {
596
841
  __privateAdd(this, _addToCachedTasks);
842
+ __privateAdd(this, _detectAutoYield);
843
+ __privateAdd(this, _forceYield);
844
+ __privateAdd(this, _getTimeElapsed);
845
+ __privateAdd(this, _getRemainingTimeInMillis);
846
+ __publicField(this, "_outputSerializer", new JSONOutputSerializer());
847
+ __publicField(this, "_visitedCacheKeys", /* @__PURE__ */ new Set());
597
848
  __publicField(this, "brb", this.yield.bind(this));
598
849
  this._id = options.id;
599
850
  this._apiClient = options.apiClient;
@@ -602,6 +853,8 @@ var IO = class {
602
853
  this._cachedTasks = /* @__PURE__ */ new Map();
603
854
  this._jobLogger = options.jobLogger;
604
855
  this._jobLogLevel = options.jobLogLevel;
856
+ this._timeOrigin = options.timeOrigin;
857
+ this._executionTimeout = options.executionTimeout;
605
858
  this._stats = {
606
859
  initialCachedTasks: 0,
607
860
  lazyLoadedCachedTasks: 0,
@@ -617,11 +870,11 @@ var IO = class {
617
870
  });
618
871
  this._stats.initialCachedTasks = options.cachedTasks.length;
619
872
  }
620
- this._taskStorage = new import_node_async_hooks.AsyncLocalStorage();
873
+ this._taskStorage = new import_node_async_hooks2.AsyncLocalStorage();
621
874
  this._context = options.context;
622
875
  this._yieldedExecutions = options.yieldedExecutions ?? [];
623
876
  if (options.noopTasksSet) {
624
- this._noopTasksBloomFilter = import_core3.BloomFilter.deserialize(options.noopTasksSet, import_core3.BloomFilter.NOOP_TASK_SET_SIZE);
877
+ this._noopTasksBloomFilter = import_core_backend.BloomFilter.deserialize(options.noopTasksSet, import_core_backend.BloomFilter.NOOP_TASK_SET_SIZE);
625
878
  }
626
879
  this._cachedTasksCursor = options.cachedTasksCursor;
627
880
  this._serverVersion = options.serverVersion ?? "unversioned";
@@ -690,8 +943,8 @@ var IO = class {
690
943
  }
691
944
  });
692
945
  }
693
- async wait(key, seconds) {
694
- return await this.runTask(key, async (task) => {
946
+ async wait(cacheKey, seconds) {
947
+ return await this.runTask(cacheKey, async (task) => {
695
948
  }, {
696
949
  name: "wait",
697
950
  icon: "clock",
@@ -705,22 +958,23 @@ var IO = class {
705
958
  }
706
959
  });
707
960
  }
708
- async createStatus(key, initialStatus) {
709
- const id = typeof key === "string" ? key : key.join("-");
961
+ async createStatus(cacheKey, initialStatus) {
962
+ const id = typeof cacheKey === "string" ? cacheKey : cacheKey.join("-");
710
963
  const status = new TriggerStatus(id, this);
711
- await status.update(key, initialStatus);
964
+ await status.update(cacheKey, initialStatus);
712
965
  return status;
713
966
  }
714
- async backgroundFetch(key, url, requestInit, retry2) {
967
+ async backgroundFetch(cacheKey, url, requestInit, retry2, timeout) {
715
968
  const urlObject = new URL(url);
716
- return await this.runTask(key, async (task) => {
969
+ return await this.runTask(cacheKey, async (task) => {
717
970
  return task.output;
718
971
  }, {
719
972
  name: `fetch ${urlObject.hostname}${urlObject.pathname}`,
720
973
  params: {
721
974
  url,
722
975
  requestInit,
723
- retry: retry2
976
+ retry: retry2,
977
+ timeout
724
978
  },
725
979
  operation: "fetch",
726
980
  icon: "background",
@@ -738,12 +992,21 @@ var IO = class {
738
992
  {
739
993
  label: "background",
740
994
  text: "true"
741
- }
742
- ]
995
+ },
996
+ ...timeout ? [
997
+ {
998
+ label: "timeout",
999
+ text: `${timeout.durationInMs}ms`
1000
+ }
1001
+ ] : []
1002
+ ],
1003
+ retry: {
1004
+ limit: 0
1005
+ }
743
1006
  });
744
1007
  }
745
- async sendEvent(key, event, options) {
746
- return await this.runTask(key, async (task) => {
1008
+ async sendEvent(cacheKey, event, options) {
1009
+ return await this.runTask(cacheKey, async (task) => {
747
1010
  return await this._triggerClient.sendEvent(event, options);
748
1011
  }, {
749
1012
  name: "sendEvent",
@@ -765,8 +1028,8 @@ var IO = class {
765
1028
  ]
766
1029
  });
767
1030
  }
768
- async getEvent(key, id) {
769
- return await this.runTask(key, async (task) => {
1031
+ async getEvent(cacheKey, id) {
1032
+ return await this.runTask(cacheKey, async (task) => {
770
1033
  return await this._triggerClient.getEvent(id);
771
1034
  }, {
772
1035
  name: "getEvent",
@@ -781,8 +1044,8 @@ var IO = class {
781
1044
  ]
782
1045
  });
783
1046
  }
784
- async cancelEvent(key, eventId) {
785
- return await this.runTask(key, async (task) => {
1047
+ async cancelEvent(cacheKey, eventId) {
1048
+ return await this.runTask(cacheKey, async (task) => {
786
1049
  return await this._triggerClient.cancelEvent(eventId);
787
1050
  }, {
788
1051
  name: "cancelEvent",
@@ -797,8 +1060,8 @@ var IO = class {
797
1060
  ]
798
1061
  });
799
1062
  }
800
- async updateSource(key, options) {
801
- return this.runTask(key, async (task) => {
1063
+ async updateSource(cacheKey, options) {
1064
+ return this.runTask(cacheKey, async (task) => {
802
1065
  return await this._apiClient.updateSource(this._triggerClient.id, options.key, options);
803
1066
  }, {
804
1067
  name: "Update Source",
@@ -817,8 +1080,8 @@ var IO = class {
817
1080
  }
818
1081
  });
819
1082
  }
820
- async registerInterval(key, dynamicSchedule, id, options) {
821
- return await this.runTask(key, async (task) => {
1083
+ async registerInterval(cacheKey, dynamicSchedule, id, options) {
1084
+ return await this.runTask(cacheKey, async (task) => {
822
1085
  return dynamicSchedule.register(id, {
823
1086
  type: "interval",
824
1087
  options
@@ -842,8 +1105,8 @@ var IO = class {
842
1105
  params: options
843
1106
  });
844
1107
  }
845
- async unregisterInterval(key, dynamicSchedule, id) {
846
- return await this.runTask(key, async (task) => {
1108
+ async unregisterInterval(cacheKey, dynamicSchedule, id) {
1109
+ return await this.runTask(cacheKey, async (task) => {
847
1110
  return dynamicSchedule.unregister(id);
848
1111
  }, {
849
1112
  name: "unregister-interval",
@@ -859,8 +1122,8 @@ var IO = class {
859
1122
  ]
860
1123
  });
861
1124
  }
862
- async registerCron(key, dynamicSchedule, id, options) {
863
- return await this.runTask(key, async (task) => {
1125
+ async registerCron(cacheKey, dynamicSchedule, id, options) {
1126
+ return await this.runTask(cacheKey, async (task) => {
864
1127
  return dynamicSchedule.register(id, {
865
1128
  type: "cron",
866
1129
  options
@@ -884,8 +1147,8 @@ var IO = class {
884
1147
  params: options
885
1148
  });
886
1149
  }
887
- async unregisterCron(key, dynamicSchedule, id) {
888
- return await this.runTask(key, async (task) => {
1150
+ async unregisterCron(cacheKey, dynamicSchedule, id) {
1151
+ return await this.runTask(cacheKey, async (task) => {
889
1152
  return dynamicSchedule.unregister(id);
890
1153
  }, {
891
1154
  name: "unregister-cron",
@@ -901,8 +1164,8 @@ var IO = class {
901
1164
  ]
902
1165
  });
903
1166
  }
904
- async registerTrigger(key, trigger, id, params) {
905
- return await this.runTask(key, async (task) => {
1167
+ async registerTrigger(cacheKey, trigger, id, params) {
1168
+ return await this.runTask(cacheKey, async (task) => {
906
1169
  const registration = await this.runTask("register-source", async (subtask1) => {
907
1170
  return trigger.register(id, params);
908
1171
  }, {
@@ -927,30 +1190,58 @@ var IO = class {
927
1190
  params
928
1191
  });
929
1192
  }
930
- async getAuth(key, clientId) {
1193
+ async getAuth(cacheKey, clientId) {
931
1194
  if (!clientId) {
932
1195
  return;
933
1196
  }
934
- return this.runTask(key, async (task) => {
1197
+ return this.runTask(cacheKey, async (task) => {
935
1198
  return await this._triggerClient.getAuth(clientId);
936
1199
  }, {
937
1200
  name: "get-auth"
938
1201
  });
939
1202
  }
940
- async runTask(key, callback, options, onError) {
1203
+ async parallel(cacheKey, items, callback, options) {
1204
+ const results = await this.runTask(cacheKey, async (task) => {
1205
+ const outcomes = await Promise.allSettled(items.map((item, index) => spaceOut(() => callback(item, index), index, 15)));
1206
+ if (outcomes.every((outcome) => outcome.status === "fulfilled")) {
1207
+ return outcomes.map((outcome) => outcome.value);
1208
+ }
1209
+ const nonInternalErrors = outcomes.filter((outcome) => outcome.status === "rejected" && !isTriggerError(outcome.reason)).map((outcome) => outcome);
1210
+ if (nonInternalErrors.length > 0) {
1211
+ throw nonInternalErrors[0].reason;
1212
+ }
1213
+ const internalErrors = outcomes.filter((outcome) => outcome.status === "rejected" && isTriggerError(outcome.reason)).map((outcome) => outcome).map((outcome) => outcome.reason);
1214
+ throw new ResumeWithParallelTaskError(task, internalErrors);
1215
+ }, {
1216
+ name: "parallel",
1217
+ parallel: true,
1218
+ ...options ?? {}
1219
+ });
1220
+ return results;
1221
+ }
1222
+ async runTask(cacheKey, callback, options, onError) {
1223
+ __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "start_task", 500);
941
1224
  const parentId = this._taskStorage.getStore()?.taskId;
942
1225
  if (parentId) {
943
1226
  this._logger.debug("Using parent task", {
944
1227
  parentId,
945
- key,
1228
+ cacheKey,
946
1229
  options
947
1230
  });
948
1231
  }
949
1232
  const idempotencyKey = await generateIdempotencyKey([
950
1233
  this._id,
951
1234
  parentId ?? "",
952
- key
1235
+ cacheKey
953
1236
  ].flat());
1237
+ if (this._visitedCacheKeys.has(idempotencyKey)) {
1238
+ if (typeof cacheKey === "string") {
1239
+ throw new Error(`Task with cacheKey "${cacheKey}" has already been executed in this run. Each task must have a unique cacheKey.`);
1240
+ } else {
1241
+ throw new Error(`Task with cacheKey "${cacheKey.join("-")}" has already been executed in this run. Each task must have a unique cacheKey.`);
1242
+ }
1243
+ }
1244
+ this._visitedCacheKeys.add(idempotencyKey);
954
1245
  const cachedTask = this._cachedTasks.get(idempotencyKey);
955
1246
  if (cachedTask && cachedTask.status === "COMPLETED") {
956
1247
  this._logger.debug("Using completed cached task", {
@@ -970,7 +1261,7 @@ var IO = class {
970
1261
  }
971
1262
  const response = await this._apiClient.runTask(this._id, {
972
1263
  idempotencyKey,
973
- displayKey: typeof key === "string" ? key : void 0,
1264
+ displayKey: typeof cacheKey === "string" ? cacheKey : void 0,
974
1265
  noop: false,
975
1266
  ...options ?? {},
976
1267
  parentId
@@ -978,6 +1269,12 @@ var IO = class {
978
1269
  cachedTasksCursor: this._cachedTasksCursor
979
1270
  });
980
1271
  const task = response.version === import_core3.API_VERSIONS.LAZY_LOADED_CACHED_TASKS ? response.body.task : response.body;
1272
+ if (task.forceYield) {
1273
+ this._logger.debug("Forcing yield after run task", {
1274
+ idempotencyKey
1275
+ });
1276
+ __privateMethod(this, _forceYield, forceYield_fn).call(this, "after_run_task");
1277
+ }
981
1278
  if (response.version === import_core3.API_VERSIONS.LAZY_LOADED_CACHED_TASKS) {
982
1279
  this._cachedTasksCursor = response.body.cachedTasks?.cursor;
983
1280
  for (const cachedTask2 of response.body.cachedTasks?.tasks ?? []) {
@@ -1017,8 +1314,9 @@ var IO = class {
1017
1314
  idempotencyKey,
1018
1315
  task
1019
1316
  });
1020
- throw new Error(task.error ?? task?.output ? JSON.stringify(task.output) : "Task errored");
1317
+ throw new ErrorWithTask(task, task.error ?? task?.output ? JSON.stringify(task.output) : "Task errored");
1021
1318
  }
1319
+ __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "before_execute_task", 1500);
1022
1320
  const executeTask = /* @__PURE__ */ __name(async () => {
1023
1321
  try {
1024
1322
  const result = await callback(task, this);
@@ -1029,20 +1327,28 @@ var IO = class {
1029
1327
  });
1030
1328
  return {};
1031
1329
  }
1032
- const output = import_core3.SerializableJsonSchema.parse(result);
1330
+ const output = this._outputSerializer.serialize(result);
1033
1331
  this._logger.debug("Completing using output", {
1034
1332
  idempotencyKey,
1035
1333
  task
1036
1334
  });
1335
+ __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "before_complete_task", 500, task, output);
1037
1336
  const completedTask = await this._apiClient.completeTask(this._id, task.id, {
1038
- output: output ?? void 0,
1337
+ output,
1039
1338
  properties: task.outputProperties ?? void 0
1040
1339
  });
1340
+ if (completedTask.forceYield) {
1341
+ this._logger.debug("Forcing yield after task completed", {
1342
+ idempotencyKey
1343
+ });
1344
+ __privateMethod(this, _forceYield, forceYield_fn).call(this, "after_complete_task");
1345
+ }
1041
1346
  this._stats.executedTasks++;
1042
1347
  if (completedTask.status === "CANCELED") {
1043
1348
  throw new CanceledWithTaskError(completedTask);
1044
1349
  }
1045
- return output;
1350
+ __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "after_complete_task", 500);
1351
+ return this._outputSerializer.deserialize(output);
1046
1352
  } catch (error) {
1047
1353
  if (isTriggerError(error)) {
1048
1354
  throw error;
@@ -1071,6 +1377,11 @@ var IO = class {
1071
1377
  error = innerError;
1072
1378
  }
1073
1379
  }
1380
+ if (error instanceof ErrorWithTask) {
1381
+ await this._apiClient.failTask(this._id, task.id, {
1382
+ error: error.cause.output
1383
+ });
1384
+ }
1074
1385
  const parsedError = import_core3.ErrorWithStackSchema.safeParse(error);
1075
1386
  if (options?.retry && !skipRetrying) {
1076
1387
  const retryAt = (0, import_core2.calculateRetryAt)(options.retry, task.attempts - 1);
@@ -1085,10 +1396,11 @@ var IO = class {
1085
1396
  error: parsedError.data
1086
1397
  });
1087
1398
  } else {
1399
+ const message = typeof error === "string" ? error : JSON.stringify(error);
1088
1400
  await this._apiClient.failTask(this._id, task.id, {
1089
1401
  error: {
1090
- message: JSON.stringify(error),
1091
- name: "Unknown Error"
1402
+ name: "Unknown error",
1403
+ message
1092
1404
  }
1093
1405
  });
1094
1406
  }
@@ -1118,15 +1430,15 @@ var IO = class {
1118
1430
  taskId: task.id
1119
1431
  }, executeTask);
1120
1432
  }
1121
- yield(key) {
1433
+ yield(cacheKey) {
1122
1434
  if (!(0, import_core3.supportsFeature)("yieldExecution", this._serverVersion)) {
1123
1435
  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.");
1124
1436
  return;
1125
1437
  }
1126
- if (this._yieldedExecutions.includes(key)) {
1438
+ if (this._yieldedExecutions.includes(cacheKey)) {
1127
1439
  return;
1128
1440
  }
1129
- throw new YieldExecutionError(key);
1441
+ throw new YieldExecutionError(cacheKey);
1130
1442
  }
1131
1443
  async try(tryCallback, catchCallback) {
1132
1444
  try {
@@ -1144,6 +1456,39 @@ _addToCachedTasks = new WeakSet();
1144
1456
  addToCachedTasks_fn = /* @__PURE__ */ __name(function(task) {
1145
1457
  this._cachedTasks.set(task.idempotencyKey, task);
1146
1458
  }, "#addToCachedTasks");
1459
+ _detectAutoYield = new WeakSet();
1460
+ detectAutoYield_fn = /* @__PURE__ */ __name(function(location, threshold = 1500, task1, output) {
1461
+ const timeRemaining = __privateMethod(this, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn).call(this);
1462
+ if (timeRemaining && timeRemaining < threshold) {
1463
+ if (task1) {
1464
+ throw new AutoYieldWithCompletedTaskExecutionError(task1.id, task1.outputProperties ?? [], {
1465
+ location,
1466
+ timeRemaining,
1467
+ timeElapsed: __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this)
1468
+ }, output);
1469
+ } else {
1470
+ throw new AutoYieldExecutionError(location, timeRemaining, __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this));
1471
+ }
1472
+ }
1473
+ }, "#detectAutoYield");
1474
+ _forceYield = new WeakSet();
1475
+ forceYield_fn = /* @__PURE__ */ __name(function(location1) {
1476
+ const timeRemaining = __privateMethod(this, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn).call(this);
1477
+ if (timeRemaining) {
1478
+ throw new AutoYieldExecutionError(location1, timeRemaining, __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this));
1479
+ }
1480
+ }, "#forceYield");
1481
+ _getTimeElapsed = new WeakSet();
1482
+ getTimeElapsed_fn = /* @__PURE__ */ __name(function() {
1483
+ return performance.now() - this._timeOrigin;
1484
+ }, "#getTimeElapsed");
1485
+ _getRemainingTimeInMillis = new WeakSet();
1486
+ getRemainingTimeInMillis_fn = /* @__PURE__ */ __name(function() {
1487
+ if (this._executionTimeout) {
1488
+ return this._executionTimeout - (performance.now() - this._timeOrigin);
1489
+ }
1490
+ return void 0;
1491
+ }, "#getRemainingTimeInMillis");
1147
1492
  async function generateIdempotencyKey(keyMaterial) {
1148
1493
  const keys = keyMaterial.map((key2) => {
1149
1494
  if (typeof key2 === "string") {
@@ -1197,6 +1542,11 @@ var IOLogger = class {
1197
1542
  }
1198
1543
  };
1199
1544
  __name(IOLogger, "IOLogger");
1545
+ async function spaceOut(callback, index, delay) {
1546
+ await new Promise((resolve) => setTimeout(resolve, index * delay));
1547
+ return await callback();
1548
+ }
1549
+ __name(spaceOut, "spaceOut");
1200
1550
 
1201
1551
  // src/ioWithIntegrations.ts
1202
1552
  function createIOWithIntegrations(io, auths, integrations) {
@@ -1227,24 +1577,6 @@ function createIOWithIntegrations(io, auths, integrations) {
1227
1577
  }
1228
1578
  __name(createIOWithIntegrations, "createIOWithIntegrations");
1229
1579
 
1230
- // src/utils/typedAsyncLocalStorage.ts
1231
- var import_node_async_hooks2 = require("async_hooks");
1232
- var TypedAsyncLocalStorage = class {
1233
- constructor() {
1234
- this.storage = new import_node_async_hooks2.AsyncLocalStorage();
1235
- }
1236
- runWith(context, fn) {
1237
- return this.storage.run(context, fn);
1238
- }
1239
- getStore() {
1240
- return this.storage.getStore();
1241
- }
1242
- };
1243
- __name(TypedAsyncLocalStorage, "TypedAsyncLocalStorage");
1244
-
1245
- // src/runLocalStorage.ts
1246
- var runLocalStorage = new TypedAsyncLocalStorage();
1247
-
1248
1580
  // src/triggers/dynamic.ts
1249
1581
  var import_core4 = require("@trigger.dev/core");
1250
1582
  var _client, _options2;
@@ -1306,7 +1638,7 @@ var DynamicTrigger = class {
1306
1638
  key,
1307
1639
  "register"
1308
1640
  ], async (task) => {
1309
- return __privateGet(this, _client).registerTrigger(this.id, key, this.registeredTriggerForParams(params, options));
1641
+ return __privateGet(this, _client).registerTrigger(this.id, key, this.registeredTriggerForParams(params, options), task.idempotencyKey);
1310
1642
  }, {
1311
1643
  name: "Register Dynamic Trigger",
1312
1644
  properties: [
@@ -1594,6 +1926,9 @@ var DynamicSchedule = class {
1594
1926
  };
1595
1927
  __name(DynamicSchedule, "DynamicSchedule");
1596
1928
 
1929
+ // package.json
1930
+ var version = "0.0.0-invoke-trigger-20231103104037";
1931
+
1597
1932
  // src/triggerClient.ts
1598
1933
  var registerSourceEvent = {
1599
1934
  name: import_core7.REGISTER_SOURCE_EVENT_V2,
@@ -1602,11 +1937,12 @@ var registerSourceEvent = {
1602
1937
  icon: "register-source",
1603
1938
  parsePayload: import_core7.RegisterSourceEventSchemaV2.parse
1604
1939
  };
1605
- 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_get;
1940
+ var _options4, _registeredJobs, _registeredSources, _registeredHttpSourceHandlers, _registeredDynamicTriggers, _jobMetadataByDynamicTriggers, _registeredSchedules, _authResolvers, _client2, _internalLogger, _preprocessRun, preprocessRun_fn, _executeJob, executeJob_fn, _convertErrorToExecutionResponse, convertErrorToExecutionResponse_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;
1606
1941
  var TriggerClient = class {
1607
1942
  constructor(options) {
1608
1943
  __privateAdd(this, _preprocessRun);
1609
1944
  __privateAdd(this, _executeJob);
1945
+ __privateAdd(this, _convertErrorToExecutionResponse);
1610
1946
  __privateAdd(this, _createRunContext);
1611
1947
  __privateAdd(this, _createPreprocessRunContext);
1612
1948
  __privateAdd(this, _handleHttpSourceRequest);
@@ -1636,7 +1972,7 @@ var TriggerClient = class {
1636
1972
  "noopTasksSet"
1637
1973
  ]));
1638
1974
  }
1639
- async handleRequest(request) {
1975
+ async handleRequest(request, timeOrigin = performance.now()) {
1640
1976
  __privateGet(this, _internalLogger).debug("handling request", {
1641
1977
  url: request.url,
1642
1978
  headers: Object.fromEntries(request.headers.entries()),
@@ -1655,7 +1991,7 @@ var TriggerClient = class {
1655
1991
  body: {
1656
1992
  message: "Unauthorized: client missing apiKey"
1657
1993
  },
1658
- headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
1994
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1659
1995
  };
1660
1996
  }
1661
1997
  case "missing-header": {
@@ -1664,7 +2000,7 @@ var TriggerClient = class {
1664
2000
  body: {
1665
2001
  message: "Unauthorized: missing x-trigger-api-key header"
1666
2002
  },
1667
- headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
2003
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1668
2004
  };
1669
2005
  }
1670
2006
  case "unauthorized": {
@@ -1673,7 +2009,7 @@ var TriggerClient = class {
1673
2009
  body: {
1674
2010
  message: `Forbidden: client apiKey mismatch: Make sure you are using the correct API Key for your environment`
1675
2011
  },
1676
- headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
2012
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1677
2013
  };
1678
2014
  }
1679
2015
  }
@@ -1683,7 +2019,7 @@ var TriggerClient = class {
1683
2019
  body: {
1684
2020
  message: "Method not allowed (only POST is allowed)"
1685
2021
  },
1686
- headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
2022
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1687
2023
  };
1688
2024
  }
1689
2025
  const action = request.headers.get("x-trigger-action");
@@ -1693,7 +2029,7 @@ var TriggerClient = class {
1693
2029
  body: {
1694
2030
  message: "Missing x-trigger-action header"
1695
2031
  },
1696
- headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
2032
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1697
2033
  };
1698
2034
  }
1699
2035
  switch (action) {
@@ -1706,7 +2042,7 @@ var TriggerClient = class {
1706
2042
  ok: false,
1707
2043
  error: "Missing endpoint ID"
1708
2044
  },
1709
- headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
2045
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1710
2046
  };
1711
2047
  }
1712
2048
  if (this.id !== endpointId) {
@@ -1716,7 +2052,7 @@ var TriggerClient = class {
1716
2052
  ok: false,
1717
2053
  error: `Endpoint ID mismatch error. Expected ${this.id}, got ${endpointId}`
1718
2054
  },
1719
- headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
2055
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1720
2056
  };
1721
2057
  }
1722
2058
  return {
@@ -1724,7 +2060,7 @@ var TriggerClient = class {
1724
2060
  body: {
1725
2061
  ok: true
1726
2062
  },
1727
- headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
2063
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1728
2064
  };
1729
2065
  }
1730
2066
  case "INDEX_ENDPOINT": {
@@ -1747,7 +2083,7 @@ var TriggerClient = class {
1747
2083
  return {
1748
2084
  status: 200,
1749
2085
  body,
1750
- headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
2086
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1751
2087
  };
1752
2088
  }
1753
2089
  case "INITIALIZE_TRIGGER": {
@@ -1773,7 +2109,7 @@ var TriggerClient = class {
1773
2109
  return {
1774
2110
  status: 200,
1775
2111
  body: dynamicTrigger.registeredTriggerForParams(body.data.params),
1776
- headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
2112
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1777
2113
  };
1778
2114
  }
1779
2115
  case "EXECUTE_JOB": {
@@ -1796,11 +2132,17 @@ var TriggerClient = class {
1796
2132
  }
1797
2133
  };
1798
2134
  }
1799
- const results = await __privateMethod(this, _executeJob, executeJob_fn).call(this, execution.data, job, triggerVersion);
2135
+ const results = await __privateMethod(this, _executeJob, executeJob_fn).call(this, execution.data, job, timeOrigin, triggerVersion);
2136
+ __privateGet(this, _internalLogger).debug("executed job", {
2137
+ results,
2138
+ job: job.id,
2139
+ version: job.version,
2140
+ triggerVersion
2141
+ });
1800
2142
  return {
1801
2143
  status: 200,
1802
2144
  body: results,
1803
- headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
2145
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1804
2146
  };
1805
2147
  }
1806
2148
  case "PREPROCESS_RUN": {
@@ -1830,7 +2172,7 @@ var TriggerClient = class {
1830
2172
  abort: results.abort,
1831
2173
  properties: results.properties
1832
2174
  },
1833
- headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
2175
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1834
2176
  };
1835
2177
  }
1836
2178
  case "DELIVER_HTTP_SOURCE_REQUEST": {
@@ -1880,7 +2222,7 @@ var TriggerClient = class {
1880
2222
  response,
1881
2223
  metadata
1882
2224
  },
1883
- headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
2225
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1884
2226
  };
1885
2227
  }
1886
2228
  case "VALIDATE": {
@@ -1890,7 +2232,19 @@ var TriggerClient = class {
1890
2232
  ok: true,
1891
2233
  endpointId: this.id
1892
2234
  },
1893
- headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
2235
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
2236
+ };
2237
+ }
2238
+ case "PROBE_EXECUTION_TIMEOUT": {
2239
+ const json = await request.json();
2240
+ const timeout = json?.timeout ?? 15 * 60 * 1e3;
2241
+ await new Promise((resolve) => setTimeout(resolve, timeout));
2242
+ return {
2243
+ status: 200,
2244
+ body: {
2245
+ ok: true
2246
+ },
2247
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1894
2248
  };
1895
2249
  }
1896
2250
  }
@@ -1899,7 +2253,7 @@ var TriggerClient = class {
1899
2253
  body: {
1900
2254
  message: "Method not allowed"
1901
2255
  },
1902
- headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
2256
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1903
2257
  };
1904
2258
  }
1905
2259
  defineJob(options) {
@@ -2029,8 +2383,8 @@ var TriggerClient = class {
2029
2383
  });
2030
2384
  __privateGet(this, _registeredSchedules)[key] = jobs;
2031
2385
  }
2032
- async registerTrigger(id, key, options) {
2033
- return __privateGet(this, _client2).registerTrigger(this.id, id, key, options);
2386
+ async registerTrigger(id, key, options, idempotencyKey) {
2387
+ return __privateGet(this, _client2).registerTrigger(this.id, id, key, options, idempotencyKey);
2034
2388
  }
2035
2389
  async getAuth(id) {
2036
2390
  return __privateGet(this, _client2).getAuth(this.id, id);
@@ -2041,6 +2395,9 @@ var TriggerClient = class {
2041
2395
  async cancelEvent(eventId) {
2042
2396
  return __privateGet(this, _client2).cancelEvent(eventId);
2043
2397
  }
2398
+ async cancelRunsForEvent(eventId) {
2399
+ return __privateGet(this, _client2).cancelRunsForEvent(eventId);
2400
+ }
2044
2401
  async updateStatus(runId, id, status) {
2045
2402
  return __privateGet(this, _client2).updateStatus(runId, id, status);
2046
2403
  }
@@ -2056,12 +2413,18 @@ var TriggerClient = class {
2056
2413
  async getRun(runId, options) {
2057
2414
  return __privateGet(this, _client2).getRun(runId, options);
2058
2415
  }
2416
+ async cancelRun(runId) {
2417
+ return __privateGet(this, _client2).cancelRun(runId);
2418
+ }
2059
2419
  async getRuns(jobSlug, options) {
2060
2420
  return __privateGet(this, _client2).getRuns(jobSlug, options);
2061
2421
  }
2062
2422
  async getRunStatuses(runId) {
2063
2423
  return __privateGet(this, _client2).getRunStatuses(runId);
2064
2424
  }
2425
+ async invokeJob(jobId, payload, options) {
2426
+ return __privateGet(this, _client2).invokeJob(jobId, payload, options);
2427
+ }
2065
2428
  authorized(apiKey) {
2066
2429
  if (typeof apiKey !== "string") {
2067
2430
  return "missing-header";
@@ -2098,7 +2461,7 @@ preprocessRun_fn = /* @__PURE__ */ __name(async function(body, job) {
2098
2461
  };
2099
2462
  }, "#preprocessRun");
2100
2463
  _executeJob = new WeakSet();
2101
- executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1, triggerVersion) {
2464
+ executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1, timeOrigin, triggerVersion) {
2102
2465
  __privateGet(this, _internalLogger).debug("executing job", {
2103
2466
  execution: body1,
2104
2467
  job: job1.id,
@@ -2118,7 +2481,9 @@ executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1, triggerVersio
2118
2481
  context,
2119
2482
  jobLogLevel: job1.logLevel ?? __privateGet(this, _options4).logLevel ?? "info",
2120
2483
  jobLogger: __privateGet(this, _options4).ioLogLocalEnabled ? new import_core7.Logger(job1.id, job1.logLevel ?? __privateGet(this, _options4).logLevel ?? "info") : void 0,
2121
- serverVersion: triggerVersion
2484
+ serverVersion: triggerVersion,
2485
+ timeOrigin,
2486
+ executionTimeout: body1.runChunkExecutionLimit
2122
2487
  });
2123
2488
  const resolvedConnections = await __privateMethod(this, _resolveConnections, resolveConnections_fn).call(this, context, job1.options.integrations, body1.connections);
2124
2489
  if (!resolvedConnections.ok) {
@@ -2146,73 +2511,126 @@ executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1, triggerVersio
2146
2511
  if (__privateGet(this, _options4).verbose) {
2147
2512
  __privateMethod(this, _logIOStats, logIOStats_fn).call(this, io.stats);
2148
2513
  }
2149
- if (error instanceof YieldExecutionError) {
2150
- return {
2151
- status: "YIELD_EXECUTION",
2152
- key: error.key
2153
- };
2154
- }
2155
- if (error instanceof ParsedPayloadSchemaError) {
2156
- return {
2157
- status: "INVALID_PAYLOAD",
2158
- errors: error.schemaErrors
2159
- };
2160
- }
2161
- if (error instanceof ResumeWithTaskError) {
2162
- return {
2163
- status: "RESUME_WITH_TASK",
2164
- task: error.task
2165
- };
2166
- }
2167
- if (error instanceof RetryWithTaskError) {
2514
+ if (error instanceof ResumeWithParallelTaskError) {
2168
2515
  return {
2169
- status: "RETRY_WITH_TASK",
2516
+ status: "RESUME_WITH_PARALLEL_TASK",
2170
2517
  task: error.task,
2171
- error: error.cause,
2172
- retryAt: error.retryAt
2518
+ childErrors: error.childErrors.map((childError) => {
2519
+ return __privateMethod(this, _convertErrorToExecutionResponse, convertErrorToExecutionResponse_fn).call(this, childError, body1);
2520
+ })
2173
2521
  };
2174
2522
  }
2175
- if (error instanceof CanceledWithTaskError) {
2176
- return {
2177
- status: "CANCELED",
2178
- task: error.task
2179
- };
2180
- }
2181
- if (error instanceof RetryWithTaskError) {
2182
- const errorWithStack2 = import_core7.ErrorWithStackSchema.safeParse(error.cause);
2183
- if (errorWithStack2.success) {
2184
- return {
2185
- status: "ERROR",
2186
- error: errorWithStack2.data,
2187
- task: error.task
2188
- };
2523
+ return __privateMethod(this, _convertErrorToExecutionResponse, convertErrorToExecutionResponse_fn).call(this, error, body1);
2524
+ }
2525
+ }, "#executeJob");
2526
+ _convertErrorToExecutionResponse = new WeakSet();
2527
+ convertErrorToExecutionResponse_fn = /* @__PURE__ */ __name(function(error, body2) {
2528
+ if (error instanceof AutoYieldExecutionError) {
2529
+ return {
2530
+ status: "AUTO_YIELD_EXECUTION",
2531
+ location: error.location,
2532
+ timeRemaining: error.timeRemaining,
2533
+ timeElapsed: error.timeElapsed,
2534
+ limit: body2.runChunkExecutionLimit
2535
+ };
2536
+ }
2537
+ if (error instanceof AutoYieldWithCompletedTaskExecutionError) {
2538
+ return {
2539
+ status: "AUTO_YIELD_EXECUTION_WITH_COMPLETED_TASK",
2540
+ id: error.id,
2541
+ properties: error.properties,
2542
+ output: error.output,
2543
+ data: {
2544
+ ...error.data,
2545
+ limit: body2.runChunkExecutionLimit
2189
2546
  }
2547
+ };
2548
+ }
2549
+ if (error instanceof YieldExecutionError) {
2550
+ return {
2551
+ status: "YIELD_EXECUTION",
2552
+ key: error.key
2553
+ };
2554
+ }
2555
+ if (error instanceof ParsedPayloadSchemaError) {
2556
+ return {
2557
+ status: "INVALID_PAYLOAD",
2558
+ errors: error.schemaErrors
2559
+ };
2560
+ }
2561
+ if (error instanceof ResumeWithTaskError) {
2562
+ return {
2563
+ status: "RESUME_WITH_TASK",
2564
+ task: error.task
2565
+ };
2566
+ }
2567
+ if (error instanceof RetryWithTaskError) {
2568
+ return {
2569
+ status: "RETRY_WITH_TASK",
2570
+ task: error.task,
2571
+ error: error.cause,
2572
+ retryAt: error.retryAt
2573
+ };
2574
+ }
2575
+ if (error instanceof CanceledWithTaskError) {
2576
+ return {
2577
+ status: "CANCELED",
2578
+ task: error.task
2579
+ };
2580
+ }
2581
+ if (error instanceof ErrorWithTask) {
2582
+ const errorWithStack2 = import_core7.ErrorWithStackSchema.safeParse(error.cause.output);
2583
+ if (errorWithStack2.success) {
2190
2584
  return {
2191
2585
  status: "ERROR",
2192
- error: {
2193
- message: "Unknown error"
2194
- },
2195
- task: error.task
2586
+ error: errorWithStack2.data,
2587
+ task: error.cause
2196
2588
  };
2197
2589
  }
2198
- const errorWithStack = import_core7.ErrorWithStackSchema.safeParse(error);
2199
- if (errorWithStack.success) {
2590
+ return {
2591
+ status: "ERROR",
2592
+ error: {
2593
+ message: JSON.stringify(error.cause.output)
2594
+ },
2595
+ task: error.cause
2596
+ };
2597
+ }
2598
+ if (error instanceof RetryWithTaskError) {
2599
+ const errorWithStack2 = import_core7.ErrorWithStackSchema.safeParse(error.cause);
2600
+ if (errorWithStack2.success) {
2200
2601
  return {
2201
2602
  status: "ERROR",
2202
- error: errorWithStack.data
2603
+ error: errorWithStack2.data,
2604
+ task: error.task
2203
2605
  };
2204
2606
  }
2205
2607
  return {
2206
2608
  status: "ERROR",
2207
2609
  error: {
2208
2610
  message: "Unknown error"
2209
- }
2611
+ },
2612
+ task: error.task
2210
2613
  };
2211
2614
  }
2212
- }, "#executeJob");
2615
+ const errorWithStack = import_core7.ErrorWithStackSchema.safeParse(error);
2616
+ if (errorWithStack.success) {
2617
+ return {
2618
+ status: "ERROR",
2619
+ error: errorWithStack.data
2620
+ };
2621
+ }
2622
+ const message = typeof error === "string" ? error : JSON.stringify(error);
2623
+ return {
2624
+ status: "ERROR",
2625
+ error: {
2626
+ name: "Unknown error",
2627
+ message
2628
+ }
2629
+ };
2630
+ }, "#convertErrorToExecutionResponse");
2213
2631
  _createRunContext = new WeakSet();
2214
2632
  createRunContext_fn = /* @__PURE__ */ __name(function(execution) {
2215
- const { event, organization, environment, job, run, source } = execution;
2633
+ const { event, organization, project, environment, job, run, source } = execution;
2216
2634
  return {
2217
2635
  event: {
2218
2636
  id: event.id,
@@ -2221,6 +2639,11 @@ createRunContext_fn = /* @__PURE__ */ __name(function(execution) {
2221
2639
  timestamp: event.timestamp
2222
2640
  },
2223
2641
  organization,
2642
+ project: project ?? {
2643
+ id: "unknown",
2644
+ name: "unknown",
2645
+ slug: "unknown"
2646
+ },
2224
2647
  environment,
2225
2648
  job,
2226
2649
  run,
@@ -2229,8 +2652,8 @@ createRunContext_fn = /* @__PURE__ */ __name(function(execution) {
2229
2652
  };
2230
2653
  }, "#createRunContext");
2231
2654
  _createPreprocessRunContext = new WeakSet();
2232
- createPreprocessRunContext_fn = /* @__PURE__ */ __name(function(body2) {
2233
- const { event, organization, environment, job, run, account } = body2;
2655
+ createPreprocessRunContext_fn = /* @__PURE__ */ __name(function(body3) {
2656
+ const { event, organization, environment, job, run, account } = body3;
2234
2657
  return {
2235
2658
  event: {
2236
2659
  id: event.id,
@@ -2482,9 +2905,11 @@ logIOStats_fn = /* @__PURE__ */ __name(function(stats) {
2482
2905
  });
2483
2906
  }, "#logIOStats");
2484
2907
  _standardResponseHeaders = new WeakSet();
2485
- standardResponseHeaders_get = /* @__PURE__ */ __name(function() {
2908
+ standardResponseHeaders_fn = /* @__PURE__ */ __name(function(start) {
2486
2909
  return {
2487
- "Trigger-Version": import_core7.API_VERSIONS.LAZY_LOADED_CACHED_TASKS
2910
+ "Trigger-Version": import_core7.API_VERSIONS.LAZY_LOADED_CACHED_TASKS,
2911
+ "Trigger-SDK-Version": version,
2912
+ "X-Trigger-Request-Timing": `dur=${performance.now() - start / 1e3}`
2488
2913
  };
2489
2914
  }, "#standardResponseHeaders");
2490
2915
  function dynamicTriggerRegisterSourceJobId(id) {
@@ -2717,6 +3142,60 @@ var MissingConnectionResolvedNotification = class {
2717
3142
  };
2718
3143
  __name(MissingConnectionResolvedNotification, "MissingConnectionResolvedNotification");
2719
3144
 
3145
+ // src/triggers/invokeTrigger.ts
3146
+ var _options5;
3147
+ var InvokeTrigger = class {
3148
+ constructor(options) {
3149
+ __privateAdd(this, _options5, void 0);
3150
+ __privateSet(this, _options5, options);
3151
+ }
3152
+ toJSON() {
3153
+ return {
3154
+ type: "invoke"
3155
+ };
3156
+ }
3157
+ get event() {
3158
+ return {
3159
+ name: "invoke",
3160
+ title: "Manual Invoke",
3161
+ source: "trigger.dev",
3162
+ examples: __privateGet(this, _options5).examples ?? [],
3163
+ icon: "trigger",
3164
+ parsePayload: (rawPayload) => {
3165
+ if (__privateGet(this, _options5).schema) {
3166
+ const results = __privateGet(this, _options5).schema.safeParse(rawPayload);
3167
+ if (!results.success) {
3168
+ throw new ParsedPayloadSchemaError(formatSchemaErrors(results.error.issues));
3169
+ }
3170
+ return results.data;
3171
+ }
3172
+ return rawPayload;
3173
+ },
3174
+ parseInvokePayload: (rawPayload) => {
3175
+ if (__privateGet(this, _options5).schema) {
3176
+ const results = __privateGet(this, _options5).schema.safeParse(rawPayload);
3177
+ if (!results.success) {
3178
+ throw new ParsedPayloadSchemaError(formatSchemaErrors(results.error.issues));
3179
+ }
3180
+ return results.data;
3181
+ }
3182
+ return rawPayload;
3183
+ }
3184
+ };
3185
+ }
3186
+ attachToJob(triggerClient, job) {
3187
+ }
3188
+ get preprocessRuns() {
3189
+ return false;
3190
+ }
3191
+ };
3192
+ __name(InvokeTrigger, "InvokeTrigger");
3193
+ _options5 = new WeakMap();
3194
+ function invokeTrigger(options) {
3195
+ return new InvokeTrigger(options ?? {});
3196
+ }
3197
+ __name(invokeTrigger, "invokeTrigger");
3198
+
2720
3199
  // src/index.ts
2721
3200
  function redactString(strings, ...interpolations) {
2722
3201
  return {
@@ -2737,6 +3216,8 @@ __name(redactString, "redactString");
2737
3216
  IO,
2738
3217
  IOLogger,
2739
3218
  IntervalTrigger,
3219
+ InvokeTrigger,
3220
+ JSONOutputSerializer,
2740
3221
  Job,
2741
3222
  MissingConnectionNotification,
2742
3223
  MissingConnectionResolvedNotification,
@@ -2744,6 +3225,7 @@ __name(redactString, "redactString");
2744
3225
  cronTrigger,
2745
3226
  eventTrigger,
2746
3227
  intervalTrigger,
3228
+ invokeTrigger,
2747
3229
  isTriggerError,
2748
3230
  missingConnectionNotification,
2749
3231
  missingConnectionResolvedNotification,