@trigger.dev/sdk 0.0.0-background-tasks-20230906212613 → 0.0.0-buffer-import-20231031135043

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
@@ -5,6 +5,7 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
9
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
10
  var __export = (target, all) => {
10
11
  for (var name in all)
@@ -23,6 +24,10 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
23
24
  mod
24
25
  ));
25
26
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var __publicField = (obj, key, value) => {
28
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
29
+ return value;
30
+ };
26
31
  var __accessCheck = (obj, member, msg) => {
27
32
  if (!member.has(obj))
28
33
  throw TypeError("Cannot " + msg);
@@ -107,6 +112,9 @@ var Job = class {
107
112
  get version() {
108
113
  return this.options.version;
109
114
  }
115
+ get logLevel() {
116
+ return this.options.logLevel;
117
+ }
110
118
  get integrations() {
111
119
  return Object.keys(this.options.integrations ?? {}).reduce((acc, key) => {
112
120
  const integration = this.options.integrations[key];
@@ -118,9 +126,6 @@ var Job = class {
118
126
  return acc;
119
127
  }, {});
120
128
  }
121
- get logLevel() {
122
- return this.options.logLevel;
123
- }
124
129
  toJSON() {
125
130
  const internal = this.options.__internal;
126
131
  return {
@@ -146,11 +151,10 @@ validate_fn = /* @__PURE__ */ __name(function() {
146
151
  }, "#validate");
147
152
 
148
153
  // src/triggerClient.ts
149
- var import_core5 = require("@trigger.dev/core");
154
+ var import_core7 = require("@trigger.dev/core");
150
155
 
151
156
  // src/apiClient.ts
152
157
  var import_core = require("@trigger.dev/core");
153
- var import_node_fetch = __toESM(require("node-fetch"));
154
158
  var import_zod = require("zod");
155
159
  var _apiUrl, _options, _logger, _apiKey, apiKey_fn;
156
160
  var ApiClient = class {
@@ -169,7 +173,7 @@ var ApiClient = class {
169
173
  url: options.url,
170
174
  name: options.name
171
175
  });
172
- const response = await (0, import_node_fetch.default)(`${__privateGet(this, _apiUrl)}/api/v1/endpoints`, {
176
+ const response = await fetch(`${__privateGet(this, _apiUrl)}/api/v1/endpoints`, {
173
177
  method: "POST",
174
178
  headers: {
175
179
  "Content-Type": "application/json",
@@ -189,17 +193,21 @@ var ApiClient = class {
189
193
  }
190
194
  return await response.json();
191
195
  }
192
- async runTask(runId, task) {
196
+ async runTask(runId, task, options = {}) {
193
197
  const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
194
198
  __privateGet(this, _logger).debug("Running Task", {
195
199
  task
196
200
  });
197
- return await zodfetch(import_core.ServerTaskSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/tasks`, {
201
+ return await zodfetchWithVersions({
202
+ [import_core.API_VERSIONS.LAZY_LOADED_CACHED_TASKS]: import_core.RunTaskResponseWithCachedTasksBodySchema
203
+ }, import_core.ServerTaskSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/tasks`, {
198
204
  method: "POST",
199
205
  headers: {
200
206
  "Content-Type": "application/json",
201
207
  Authorization: `Bearer ${apiKey}`,
202
- "Idempotency-Key": task.idempotencyKey
208
+ "Idempotency-Key": task.idempotencyKey,
209
+ "X-Cached-Tasks-Cursor": options.cachedTasksCursor ?? "",
210
+ "Trigger-Version": import_core.API_VERSIONS.LAZY_LOADED_CACHED_TASKS
203
211
  },
204
212
  body: JSON.stringify(task)
205
213
  });
@@ -264,6 +272,34 @@ var ApiClient = class {
264
272
  }
265
273
  });
266
274
  }
275
+ async cancelRunsForEvent(eventId) {
276
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
277
+ __privateGet(this, _logger).debug("Cancelling runs for event", {
278
+ eventId
279
+ });
280
+ return await zodfetch(import_core.CancelRunsForEventSchema, `${__privateGet(this, _apiUrl)}/api/v1/events/${eventId}/cancel-runs`, {
281
+ method: "POST",
282
+ headers: {
283
+ "Content-Type": "application/json",
284
+ Authorization: `Bearer ${apiKey}`
285
+ }
286
+ });
287
+ }
288
+ async updateStatus(runId, id, status) {
289
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
290
+ __privateGet(this, _logger).debug("Update status", {
291
+ id,
292
+ status
293
+ });
294
+ return await zodfetch(import_core.JobRunStatusRecordSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/statuses/${id}`, {
295
+ method: "PUT",
296
+ headers: {
297
+ "Content-Type": "application/json",
298
+ Authorization: `Bearer ${apiKey}`
299
+ },
300
+ body: JSON.stringify(status)
301
+ });
302
+ }
267
303
  async updateSource(client, key, source) {
268
304
  const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
269
305
  __privateGet(this, _logger).debug("activating http source", {
@@ -279,18 +315,22 @@ var ApiClient = class {
279
315
  });
280
316
  return response;
281
317
  }
282
- async registerTrigger(client, id, key, payload) {
318
+ async registerTrigger(client, id, key, payload, idempotencyKey) {
283
319
  const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
284
320
  __privateGet(this, _logger).debug("registering trigger", {
285
321
  id,
286
322
  payload
287
323
  });
324
+ const headers = {
325
+ "Content-Type": "application/json",
326
+ Authorization: `Bearer ${apiKey}`
327
+ };
328
+ if (idempotencyKey) {
329
+ headers["Idempotency-Key"] = idempotencyKey;
330
+ }
288
331
  const response = await zodfetch(import_core.RegisterSourceEventSchemaV2, `${__privateGet(this, _apiUrl)}/api/v2/${client}/triggers/${id}/registrations/${key}`, {
289
332
  method: "PUT",
290
- headers: {
291
- "Content-Type": "application/json",
292
- Authorization: `Bearer ${apiKey}`
293
- },
333
+ headers,
294
334
  body: JSON.stringify(payload)
295
335
  });
296
336
  return response;
@@ -370,6 +410,31 @@ var ApiClient = class {
370
410
  }
371
411
  });
372
412
  }
413
+ async cancelRun(runId) {
414
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
415
+ __privateGet(this, _logger).debug("Cancelling Run", {
416
+ runId
417
+ });
418
+ return await zodfetch(import_core.GetRunSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/cancel`, {
419
+ method: "POST",
420
+ headers: {
421
+ "Content-Type": "application/json",
422
+ Authorization: `Bearer ${apiKey}`
423
+ }
424
+ });
425
+ }
426
+ async getRunStatuses(runId) {
427
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
428
+ __privateGet(this, _logger).debug("Getting Run statuses", {
429
+ runId
430
+ });
431
+ return await zodfetch(import_core.GetRunStatusesSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/statuses`, {
432
+ method: "GET",
433
+ headers: {
434
+ Authorization: `Bearer ${apiKey}`
435
+ }
436
+ });
437
+ }
373
438
  async getRuns(jobSlug, options) {
374
439
  const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
375
440
  __privateGet(this, _logger).debug("Getting Runs", {
@@ -417,8 +482,38 @@ function getApiKey(key) {
417
482
  };
418
483
  }
419
484
  __name(getApiKey, "getApiKey");
485
+ async function zodfetchWithVersions(versionedSchemaMap, unversionedSchema, url, requestInit, options) {
486
+ const response = await fetch(url, requestInit);
487
+ if ((!requestInit || requestInit.method === "GET") && response.status === 404 && options?.optional) {
488
+ return;
489
+ }
490
+ if (response.status >= 400 && response.status < 500) {
491
+ const body = await response.json();
492
+ throw new Error(body.error);
493
+ }
494
+ if (response.status !== 200) {
495
+ throw new Error(options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`);
496
+ }
497
+ const jsonBody = await response.json();
498
+ const version2 = response.headers.get("trigger-version");
499
+ if (!version2) {
500
+ return {
501
+ version: "unversioned",
502
+ body: unversionedSchema.parse(jsonBody)
503
+ };
504
+ }
505
+ const versionedSchema = versionedSchemaMap[version2];
506
+ if (!versionedSchema) {
507
+ throw new Error(`Unknown version ${version2}`);
508
+ }
509
+ return {
510
+ version: version2,
511
+ body: versionedSchema.parse(jsonBody)
512
+ };
513
+ }
514
+ __name(zodfetchWithVersions, "zodfetchWithVersions");
420
515
  async function zodfetch(schema, url, requestInit, options) {
421
- const response = await (0, import_node_fetch.default)(url, requestInit);
516
+ const response = await fetch(url, requestInit);
422
517
  if ((!requestInit || requestInit.method === "GET") && response.status === 404 && options?.optional) {
423
518
  return;
424
519
  }
@@ -455,13 +550,43 @@ var CanceledWithTaskError = class {
455
550
  }
456
551
  };
457
552
  __name(CanceledWithTaskError, "CanceledWithTaskError");
553
+ var YieldExecutionError = class {
554
+ constructor(key) {
555
+ this.key = key;
556
+ }
557
+ };
558
+ __name(YieldExecutionError, "YieldExecutionError");
559
+ var AutoYieldExecutionError = class {
560
+ constructor(location, timeRemaining, timeElapsed) {
561
+ this.location = location;
562
+ this.timeRemaining = timeRemaining;
563
+ this.timeElapsed = timeElapsed;
564
+ }
565
+ };
566
+ __name(AutoYieldExecutionError, "AutoYieldExecutionError");
567
+ var AutoYieldWithCompletedTaskExecutionError = class {
568
+ constructor(id, properties, output, data) {
569
+ this.id = id;
570
+ this.properties = properties;
571
+ this.output = output;
572
+ this.data = data;
573
+ }
574
+ };
575
+ __name(AutoYieldWithCompletedTaskExecutionError, "AutoYieldWithCompletedTaskExecutionError");
576
+ var ParsedPayloadSchemaError = class {
577
+ constructor(schemaErrors) {
578
+ this.schemaErrors = schemaErrors;
579
+ }
580
+ };
581
+ __name(ParsedPayloadSchemaError, "ParsedPayloadSchemaError");
458
582
  function isTriggerError(err) {
459
- return err instanceof ResumeWithTaskError || err instanceof RetryWithTaskError || err instanceof CanceledWithTaskError;
583
+ return err instanceof ResumeWithTaskError || err instanceof RetryWithTaskError || err instanceof CanceledWithTaskError || err instanceof YieldExecutionError || err instanceof AutoYieldExecutionError || err instanceof AutoYieldWithCompletedTaskExecutionError;
460
584
  }
461
585
  __name(isTriggerError, "isTriggerError");
462
586
 
463
587
  // src/io.ts
464
588
  var import_core3 = require("@trigger.dev/core");
589
+ var import_core_backend = require("@trigger.dev/core-backend");
465
590
  var import_node_async_hooks = require("async_hooks");
466
591
  var import_node_crypto = require("crypto");
467
592
 
@@ -477,11 +602,50 @@ var retry = {
477
602
  }
478
603
  };
479
604
 
605
+ // src/status.ts
606
+ var TriggerStatus = class {
607
+ constructor(id, io) {
608
+ this.id = id;
609
+ this.io = io;
610
+ }
611
+ async update(key, status) {
612
+ const properties = [];
613
+ if (status.label) {
614
+ properties.push({
615
+ label: "Label",
616
+ text: status.label
617
+ });
618
+ }
619
+ if (status.state) {
620
+ properties.push({
621
+ label: "State",
622
+ text: status.state
623
+ });
624
+ }
625
+ return await this.io.runTask(key, async (task) => {
626
+ return await this.io.triggerClient.updateStatus(this.io.runId, this.id, status);
627
+ }, {
628
+ name: status.label ?? `Status update`,
629
+ icon: "bell",
630
+ params: {
631
+ ...status
632
+ },
633
+ properties
634
+ });
635
+ }
636
+ };
637
+ __name(TriggerStatus, "TriggerStatus");
638
+
480
639
  // src/io.ts
481
- var _addToCachedTasks, addToCachedTasks_fn;
640
+ var _addToCachedTasks, addToCachedTasks_fn, _detectAutoYield, detectAutoYield_fn, _forceYield, forceYield_fn, _getTimeElapsed, getTimeElapsed_fn, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn;
482
641
  var IO = class {
483
642
  constructor(options) {
484
643
  __privateAdd(this, _addToCachedTasks);
644
+ __privateAdd(this, _detectAutoYield);
645
+ __privateAdd(this, _forceYield);
646
+ __privateAdd(this, _getTimeElapsed);
647
+ __privateAdd(this, _getRemainingTimeInMillis);
648
+ __publicField(this, "brb", this.yield.bind(this));
485
649
  this._id = options.id;
486
650
  this._apiClient = options.apiClient;
487
651
  this._triggerClient = options.client;
@@ -489,49 +653,76 @@ var IO = class {
489
653
  this._cachedTasks = /* @__PURE__ */ new Map();
490
654
  this._jobLogger = options.jobLogger;
491
655
  this._jobLogLevel = options.jobLogLevel;
656
+ this._timeOrigin = options.timeOrigin;
657
+ this._executionTimeout = options.executionTimeout;
658
+ this._stats = {
659
+ initialCachedTasks: 0,
660
+ lazyLoadedCachedTasks: 0,
661
+ executedTasks: 0,
662
+ cachedTaskHits: 0,
663
+ cachedTaskMisses: 0,
664
+ noopCachedTaskHits: 0,
665
+ noopCachedTaskMisses: 0
666
+ };
492
667
  if (options.cachedTasks) {
493
668
  options.cachedTasks.forEach((task) => {
494
669
  this._cachedTasks.set(task.idempotencyKey, task);
495
670
  });
671
+ this._stats.initialCachedTasks = options.cachedTasks.length;
496
672
  }
497
673
  this._taskStorage = new import_node_async_hooks.AsyncLocalStorage();
498
674
  this._context = options.context;
675
+ this._yieldedExecutions = options.yieldedExecutions ?? [];
676
+ if (options.noopTasksSet) {
677
+ this._noopTasksBloomFilter = import_core_backend.BloomFilter.deserialize(options.noopTasksSet, import_core_backend.BloomFilter.NOOP_TASK_SET_SIZE);
678
+ }
679
+ this._cachedTasksCursor = options.cachedTasksCursor;
680
+ this._serverVersion = options.serverVersion ?? "unversioned";
681
+ }
682
+ get stats() {
683
+ return this._stats;
684
+ }
685
+ get runId() {
686
+ return this._id;
687
+ }
688
+ get triggerClient() {
689
+ return this._triggerClient;
499
690
  }
500
691
  get logger() {
501
692
  return new IOLogger(async (level, message, data) => {
502
693
  let logLevel = "info";
503
- switch (level) {
504
- case "LOG": {
505
- this._jobLogger?.log(message, data);
506
- logLevel = "log";
507
- break;
508
- }
509
- case "DEBUG": {
510
- this._jobLogger?.debug(message, data);
511
- logLevel = "debug";
512
- break;
513
- }
514
- case "INFO": {
515
- this._jobLogger?.info(message, data);
516
- logLevel = "info";
517
- break;
518
- }
519
- case "WARN": {
520
- this._jobLogger?.warn(message, data);
521
- logLevel = "warn";
522
- break;
523
- }
524
- case "ERROR": {
525
- this._jobLogger?.error(message, data);
526
- logLevel = "error";
527
- break;
528
- }
529
- }
530
694
  if (import_core3.Logger.satisfiesLogLevel(logLevel, this._jobLogLevel)) {
531
695
  await this.runTask([
532
696
  message,
533
697
  level
534
698
  ], async (task) => {
699
+ switch (level) {
700
+ case "LOG": {
701
+ this._jobLogger?.log(message, data);
702
+ logLevel = "log";
703
+ break;
704
+ }
705
+ case "DEBUG": {
706
+ this._jobLogger?.debug(message, data);
707
+ logLevel = "debug";
708
+ break;
709
+ }
710
+ case "INFO": {
711
+ this._jobLogger?.info(message, data);
712
+ logLevel = "info";
713
+ break;
714
+ }
715
+ case "WARN": {
716
+ this._jobLogger?.warn(message, data);
717
+ logLevel = "warn";
718
+ break;
719
+ }
720
+ case "ERROR": {
721
+ this._jobLogger?.error(message, data);
722
+ logLevel = "error";
723
+ break;
724
+ }
725
+ }
535
726
  }, {
536
727
  name: "log",
537
728
  icon: "log",
@@ -552,8 +743,8 @@ var IO = class {
552
743
  }
553
744
  });
554
745
  }
555
- async wait(key, seconds) {
556
- return await this.runTask(key, async (task) => {
746
+ async wait(cacheKey, seconds) {
747
+ return await this.runTask(cacheKey, async (task) => {
557
748
  }, {
558
749
  name: "wait",
559
750
  icon: "clock",
@@ -567,9 +758,15 @@ var IO = class {
567
758
  }
568
759
  });
569
760
  }
570
- async backgroundFetch(key, url, requestInit, retry2) {
761
+ async createStatus(cacheKey, initialStatus) {
762
+ const id = typeof cacheKey === "string" ? cacheKey : cacheKey.join("-");
763
+ const status = new TriggerStatus(id, this);
764
+ await status.update(cacheKey, initialStatus);
765
+ return status;
766
+ }
767
+ async backgroundFetch(cacheKey, url, requestInit, retry2) {
571
768
  const urlObject = new URL(url);
572
- return await this.runTask(key, async (task) => {
769
+ return await this.runTask(cacheKey, async (task) => {
573
770
  return task.output;
574
771
  }, {
575
772
  name: `fetch ${urlObject.hostname}${urlObject.pathname}`,
@@ -598,8 +795,8 @@ var IO = class {
598
795
  ]
599
796
  });
600
797
  }
601
- async sendEvent(key, event, options) {
602
- return await this.runTask(key, async (task) => {
798
+ async sendEvent(cacheKey, event, options) {
799
+ return await this.runTask(cacheKey, async (task) => {
603
800
  return await this._triggerClient.sendEvent(event, options);
604
801
  }, {
605
802
  name: "sendEvent",
@@ -621,8 +818,8 @@ var IO = class {
621
818
  ]
622
819
  });
623
820
  }
624
- async getEvent(key, id) {
625
- return await this.runTask(key, async (task) => {
821
+ async getEvent(cacheKey, id) {
822
+ return await this.runTask(cacheKey, async (task) => {
626
823
  return await this._triggerClient.getEvent(id);
627
824
  }, {
628
825
  name: "getEvent",
@@ -637,8 +834,8 @@ var IO = class {
637
834
  ]
638
835
  });
639
836
  }
640
- async cancelEvent(key, eventId) {
641
- return await this.runTask(key, async (task) => {
837
+ async cancelEvent(cacheKey, eventId) {
838
+ return await this.runTask(cacheKey, async (task) => {
642
839
  return await this._triggerClient.cancelEvent(eventId);
643
840
  }, {
644
841
  name: "cancelEvent",
@@ -653,8 +850,8 @@ var IO = class {
653
850
  ]
654
851
  });
655
852
  }
656
- async updateSource(key, options) {
657
- return this.runTask(key, async (task) => {
853
+ async updateSource(cacheKey, options) {
854
+ return this.runTask(cacheKey, async (task) => {
658
855
  return await this._apiClient.updateSource(this._triggerClient.id, options.key, options);
659
856
  }, {
660
857
  name: "Update Source",
@@ -673,8 +870,8 @@ var IO = class {
673
870
  }
674
871
  });
675
872
  }
676
- async registerInterval(key, dynamicSchedule, id, options) {
677
- return await this.runTask(key, async (task) => {
873
+ async registerInterval(cacheKey, dynamicSchedule, id, options) {
874
+ return await this.runTask(cacheKey, async (task) => {
678
875
  return dynamicSchedule.register(id, {
679
876
  type: "interval",
680
877
  options
@@ -698,8 +895,8 @@ var IO = class {
698
895
  params: options
699
896
  });
700
897
  }
701
- async unregisterInterval(key, dynamicSchedule, id) {
702
- return await this.runTask(key, async (task) => {
898
+ async unregisterInterval(cacheKey, dynamicSchedule, id) {
899
+ return await this.runTask(cacheKey, async (task) => {
703
900
  return dynamicSchedule.unregister(id);
704
901
  }, {
705
902
  name: "unregister-interval",
@@ -715,8 +912,8 @@ var IO = class {
715
912
  ]
716
913
  });
717
914
  }
718
- async registerCron(key, dynamicSchedule, id, options) {
719
- return await this.runTask(key, async (task) => {
915
+ async registerCron(cacheKey, dynamicSchedule, id, options) {
916
+ return await this.runTask(cacheKey, async (task) => {
720
917
  return dynamicSchedule.register(id, {
721
918
  type: "cron",
722
919
  options
@@ -740,8 +937,8 @@ var IO = class {
740
937
  params: options
741
938
  });
742
939
  }
743
- async unregisterCron(key, dynamicSchedule, id) {
744
- return await this.runTask(key, async (task) => {
940
+ async unregisterCron(cacheKey, dynamicSchedule, id) {
941
+ return await this.runTask(cacheKey, async (task) => {
745
942
  return dynamicSchedule.unregister(id);
746
943
  }, {
747
944
  name: "unregister-cron",
@@ -757,8 +954,8 @@ var IO = class {
757
954
  ]
758
955
  });
759
956
  }
760
- async registerTrigger(key, trigger, id, params) {
761
- return await this.runTask(key, async (task) => {
957
+ async registerTrigger(cacheKey, trigger, id, params) {
958
+ return await this.runTask(cacheKey, async (task) => {
762
959
  const registration = await this.runTask("register-source", async (subtask1) => {
763
960
  return trigger.register(id, params);
764
961
  }, {
@@ -783,45 +980,76 @@ var IO = class {
783
980
  params
784
981
  });
785
982
  }
786
- async getAuth(key, clientId) {
983
+ async getAuth(cacheKey, clientId) {
787
984
  if (!clientId) {
788
985
  return;
789
986
  }
790
- return this.runTask(key, async (task) => {
987
+ return this.runTask(cacheKey, async (task) => {
791
988
  return await this._triggerClient.getAuth(clientId);
792
989
  }, {
793
990
  name: "get-auth"
794
991
  });
795
992
  }
796
- async runTask(key, callback, options, onError) {
993
+ async runTask(cacheKey, callback, options, onError) {
994
+ __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "start_task", 500);
797
995
  const parentId = this._taskStorage.getStore()?.taskId;
798
996
  if (parentId) {
799
997
  this._logger.debug("Using parent task", {
800
998
  parentId,
801
- key,
999
+ cacheKey,
802
1000
  options
803
1001
  });
804
1002
  }
805
1003
  const idempotencyKey = await generateIdempotencyKey([
806
1004
  this._id,
807
1005
  parentId ?? "",
808
- key
1006
+ cacheKey
809
1007
  ].flat());
810
1008
  const cachedTask = this._cachedTasks.get(idempotencyKey);
811
1009
  if (cachedTask && cachedTask.status === "COMPLETED") {
812
1010
  this._logger.debug("Using completed cached task", {
813
- idempotencyKey,
814
- cachedTask
1011
+ idempotencyKey
815
1012
  });
1013
+ this._stats.cachedTaskHits++;
816
1014
  return cachedTask.output;
817
1015
  }
818
- const task = await this._apiClient.runTask(this._id, {
1016
+ if (options?.noop && this._noopTasksBloomFilter) {
1017
+ if (this._noopTasksBloomFilter.test(idempotencyKey)) {
1018
+ this._logger.debug("task idempotency key exists in noopTasksBloomFilter", {
1019
+ idempotencyKey
1020
+ });
1021
+ this._stats.noopCachedTaskHits++;
1022
+ return {};
1023
+ }
1024
+ }
1025
+ const response = await this._apiClient.runTask(this._id, {
819
1026
  idempotencyKey,
820
- displayKey: typeof key === "string" ? key : void 0,
1027
+ displayKey: typeof cacheKey === "string" ? cacheKey : void 0,
821
1028
  noop: false,
822
1029
  ...options ?? {},
823
1030
  parentId
1031
+ }, {
1032
+ cachedTasksCursor: this._cachedTasksCursor
824
1033
  });
1034
+ const task = response.version === import_core3.API_VERSIONS.LAZY_LOADED_CACHED_TASKS ? response.body.task : response.body;
1035
+ if (task.forceYield) {
1036
+ this._logger.debug("Forcing yield after run task", {
1037
+ idempotencyKey
1038
+ });
1039
+ __privateMethod(this, _forceYield, forceYield_fn).call(this, "after_run_task");
1040
+ }
1041
+ if (response.version === import_core3.API_VERSIONS.LAZY_LOADED_CACHED_TASKS) {
1042
+ this._cachedTasksCursor = response.body.cachedTasks?.cursor;
1043
+ for (const cachedTask2 of response.body.cachedTasks?.tasks ?? []) {
1044
+ if (!this._cachedTasks.has(cachedTask2.idempotencyKey)) {
1045
+ this._cachedTasks.set(cachedTask2.idempotencyKey, cachedTask2);
1046
+ this._logger.debug("Injecting lazy loaded task into task cache", {
1047
+ idempotencyKey: cachedTask2.idempotencyKey
1048
+ });
1049
+ this._stats.lazyLoadedCachedTasks++;
1050
+ }
1051
+ }
1052
+ }
825
1053
  if (task.status === "CANCELED") {
826
1054
  this._logger.debug("Task canceled", {
827
1055
  idempotencyKey,
@@ -830,11 +1058,18 @@ var IO = class {
830
1058
  throw new CanceledWithTaskError(task);
831
1059
  }
832
1060
  if (task.status === "COMPLETED") {
833
- this._logger.debug("Using task output", {
834
- idempotencyKey,
835
- task
836
- });
837
- __privateMethod(this, _addToCachedTasks, addToCachedTasks_fn).call(this, task);
1061
+ if (task.noop) {
1062
+ this._logger.debug("Noop Task completed", {
1063
+ idempotencyKey
1064
+ });
1065
+ this._noopTasksBloomFilter?.add(task.idempotencyKey);
1066
+ } else {
1067
+ this._logger.debug("Cache miss", {
1068
+ idempotencyKey
1069
+ });
1070
+ this._stats.cachedTaskMisses++;
1071
+ __privateMethod(this, _addToCachedTasks, addToCachedTasks_fn).call(this, task);
1072
+ }
838
1073
  return task.output;
839
1074
  }
840
1075
  if (task.status === "ERRORED") {
@@ -842,42 +1077,46 @@ var IO = class {
842
1077
  idempotencyKey,
843
1078
  task
844
1079
  });
845
- throw new Error(task.error ?? "Task errored");
846
- }
847
- if (task.status === "WAITING") {
848
- this._logger.debug("Task waiting", {
849
- idempotencyKey,
850
- task
851
- });
852
- throw new ResumeWithTaskError(task);
853
- }
854
- if (task.status === "RUNNING" && typeof task.operation === "string") {
855
- this._logger.debug("Task running operation", {
856
- idempotencyKey,
857
- task
858
- });
859
- throw new ResumeWithTaskError(task);
1080
+ throw new Error(task.error ?? task?.output ? JSON.stringify(task.output) : "Task errored");
860
1081
  }
1082
+ __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "before_execute_task", 1500);
861
1083
  const executeTask = /* @__PURE__ */ __name(async () => {
862
1084
  try {
863
1085
  const result = await callback(task, this);
1086
+ if (task.status === "WAITING" && task.callbackUrl) {
1087
+ this._logger.debug("Waiting for remote callback", {
1088
+ idempotencyKey,
1089
+ task
1090
+ });
1091
+ return {};
1092
+ }
864
1093
  const output = import_core3.SerializableJsonSchema.parse(result);
865
1094
  this._logger.debug("Completing using output", {
866
1095
  idempotencyKey,
867
1096
  task
868
1097
  });
1098
+ __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "before_complete_task", 500, task, output);
869
1099
  const completedTask = await this._apiClient.completeTask(this._id, task.id, {
870
1100
  output: output ?? void 0,
871
1101
  properties: task.outputProperties ?? void 0
872
1102
  });
1103
+ if (completedTask.forceYield) {
1104
+ this._logger.debug("Forcing yield after task completed", {
1105
+ idempotencyKey
1106
+ });
1107
+ __privateMethod(this, _forceYield, forceYield_fn).call(this, "after_complete_task");
1108
+ }
1109
+ this._stats.executedTasks++;
873
1110
  if (completedTask.status === "CANCELED") {
874
1111
  throw new CanceledWithTaskError(completedTask);
875
1112
  }
1113
+ __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "after_complete_task", 500);
876
1114
  return output;
877
1115
  } catch (error) {
878
1116
  if (isTriggerError(error)) {
879
1117
  throw error;
880
1118
  }
1119
+ let skipRetrying = false;
881
1120
  if (onError) {
882
1121
  try {
883
1122
  const onErrorResult = onError(error, task, this);
@@ -885,10 +1124,13 @@ var IO = class {
885
1124
  if (onErrorResult instanceof Error) {
886
1125
  error = onErrorResult;
887
1126
  } else {
888
- const parsedError2 = import_core3.ErrorWithStackSchema.safeParse(onErrorResult.error);
889
- throw new RetryWithTaskError(parsedError2.success ? parsedError2.data : {
890
- message: "Unknown error"
891
- }, task, onErrorResult.retryAt);
1127
+ skipRetrying = !!onErrorResult.skipRetrying;
1128
+ if (onErrorResult.retryAt && !skipRetrying) {
1129
+ const parsedError2 = import_core3.ErrorWithStackSchema.safeParse(onErrorResult.error);
1130
+ throw new RetryWithTaskError(parsedError2.success ? parsedError2.data : {
1131
+ message: "Unknown error"
1132
+ }, task, onErrorResult.retryAt);
1133
+ }
892
1134
  }
893
1135
  }
894
1136
  } catch (innerError) {
@@ -899,7 +1141,7 @@ var IO = class {
899
1141
  }
900
1142
  }
901
1143
  const parsedError = import_core3.ErrorWithStackSchema.safeParse(error);
902
- if (options?.retry) {
1144
+ if (options?.retry && !skipRetrying) {
903
1145
  const retryAt = (0, import_core2.calculateRetryAt)(options.retry, task.attempts - 1);
904
1146
  if (retryAt) {
905
1147
  throw new RetryWithTaskError(parsedError.success ? parsedError.data : {
@@ -912,20 +1154,50 @@ var IO = class {
912
1154
  error: parsedError.data
913
1155
  });
914
1156
  } else {
1157
+ const message = typeof error === "string" ? error : JSON.stringify(error);
915
1158
  await this._apiClient.failTask(this._id, task.id, {
916
1159
  error: {
917
- message: JSON.stringify(error),
918
- name: "Unknown Error"
1160
+ name: "Unknown error",
1161
+ message
919
1162
  }
920
1163
  });
921
1164
  }
922
1165
  throw error;
923
1166
  }
924
1167
  }, "executeTask");
1168
+ if (task.status === "WAITING") {
1169
+ this._logger.debug("Task waiting", {
1170
+ idempotencyKey,
1171
+ task
1172
+ });
1173
+ if (task.callbackUrl) {
1174
+ await this._taskStorage.run({
1175
+ taskId: task.id
1176
+ }, executeTask);
1177
+ }
1178
+ throw new ResumeWithTaskError(task);
1179
+ }
1180
+ if (task.status === "RUNNING" && typeof task.operation === "string") {
1181
+ this._logger.debug("Task running operation", {
1182
+ idempotencyKey,
1183
+ task
1184
+ });
1185
+ throw new ResumeWithTaskError(task);
1186
+ }
925
1187
  return this._taskStorage.run({
926
1188
  taskId: task.id
927
1189
  }, executeTask);
928
1190
  }
1191
+ yield(cacheKey) {
1192
+ if (!(0, import_core3.supportsFeature)("yieldExecution", this._serverVersion)) {
1193
+ 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
+ return;
1195
+ }
1196
+ if (this._yieldedExecutions.includes(cacheKey)) {
1197
+ return;
1198
+ }
1199
+ throw new YieldExecutionError(cacheKey);
1200
+ }
929
1201
  async try(tryCallback, catchCallback) {
930
1202
  try {
931
1203
  return await tryCallback();
@@ -942,6 +1214,39 @@ _addToCachedTasks = new WeakSet();
942
1214
  addToCachedTasks_fn = /* @__PURE__ */ __name(function(task) {
943
1215
  this._cachedTasks.set(task.idempotencyKey, task);
944
1216
  }, "#addToCachedTasks");
1217
+ _detectAutoYield = new WeakSet();
1218
+ detectAutoYield_fn = /* @__PURE__ */ __name(function(location, threshold = 1500, task1, output) {
1219
+ const timeRemaining = __privateMethod(this, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn).call(this);
1220
+ if (timeRemaining && timeRemaining < threshold) {
1221
+ if (task1) {
1222
+ throw new AutoYieldWithCompletedTaskExecutionError(task1.id, task1.outputProperties ?? [], output, {
1223
+ location,
1224
+ timeRemaining,
1225
+ timeElapsed: __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this)
1226
+ });
1227
+ } else {
1228
+ throw new AutoYieldExecutionError(location, timeRemaining, __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this));
1229
+ }
1230
+ }
1231
+ }, "#detectAutoYield");
1232
+ _forceYield = new WeakSet();
1233
+ forceYield_fn = /* @__PURE__ */ __name(function(location1) {
1234
+ const timeRemaining = __privateMethod(this, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn).call(this);
1235
+ if (timeRemaining) {
1236
+ throw new AutoYieldExecutionError(location1, timeRemaining, __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this));
1237
+ }
1238
+ }, "#forceYield");
1239
+ _getTimeElapsed = new WeakSet();
1240
+ getTimeElapsed_fn = /* @__PURE__ */ __name(function() {
1241
+ return performance.now() - this._timeOrigin;
1242
+ }, "#getTimeElapsed");
1243
+ _getRemainingTimeInMillis = new WeakSet();
1244
+ getRemainingTimeInMillis_fn = /* @__PURE__ */ __name(function() {
1245
+ if (this._executionTimeout) {
1246
+ return this._executionTimeout - (performance.now() - this._timeOrigin);
1247
+ }
1248
+ return void 0;
1249
+ }, "#getRemainingTimeInMillis");
945
1250
  async function generateIdempotencyKey(keyMaterial) {
946
1251
  const keys = keyMaterial.map((key2) => {
947
1252
  if (typeof key2 === "string") {
@@ -1025,117 +1330,385 @@ function createIOWithIntegrations(io, auths, integrations) {
1025
1330
  }
1026
1331
  __name(createIOWithIntegrations, "createIOWithIntegrations");
1027
1332
 
1028
- // src/triggers/eventTrigger.ts
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
+ // src/triggers/dynamic.ts
1029
1352
  var import_core4 = require("@trigger.dev/core");
1030
- var _options2;
1031
- var EventTrigger = class {
1032
- constructor(options) {
1353
+ var _client, _options2;
1354
+ var DynamicTrigger = class {
1355
+ constructor(client, options) {
1356
+ __privateAdd(this, _client, void 0);
1033
1357
  __privateAdd(this, _options2, void 0);
1358
+ __privateSet(this, _client, client);
1034
1359
  __privateSet(this, _options2, options);
1360
+ this.source = options.source;
1361
+ client.attachDynamicTrigger(this);
1035
1362
  }
1036
1363
  toJSON() {
1037
1364
  return {
1038
- type: "static",
1039
- title: __privateGet(this, _options2).name ?? __privateGet(this, _options2).event.title,
1040
- rule: {
1041
- event: __privateGet(this, _options2).name ?? __privateGet(this, _options2).event.name,
1042
- source: __privateGet(this, _options2).source ?? "trigger.dev",
1043
- payload: (0, import_core4.deepMergeFilters)(__privateGet(this, _options2).filter ?? {}, __privateGet(this, _options2).event.filter ?? {})
1044
- }
1365
+ type: "dynamic",
1366
+ id: __privateGet(this, _options2).id
1045
1367
  };
1046
1368
  }
1369
+ get id() {
1370
+ return __privateGet(this, _options2).id;
1371
+ }
1047
1372
  get event() {
1048
1373
  return __privateGet(this, _options2).event;
1049
1374
  }
1375
+ registeredTriggerForParams(params, options = {}) {
1376
+ const key = slugifyId(this.source.key(params));
1377
+ return {
1378
+ rule: {
1379
+ event: this.event.name,
1380
+ source: this.event.source,
1381
+ payload: (0, import_core4.deepMergeFilters)(this.source.filter(params), this.event.filter ?? {}, options.filter ?? {})
1382
+ },
1383
+ source: {
1384
+ version: "2",
1385
+ key,
1386
+ channel: this.source.channel,
1387
+ params,
1388
+ options: {
1389
+ event: typeof this.event.name === "string" ? [
1390
+ this.event.name
1391
+ ] : this.event.name
1392
+ },
1393
+ integration: {
1394
+ id: this.source.integration.id,
1395
+ metadata: this.source.integration.metadata,
1396
+ authSource: this.source.integration.authSource
1397
+ }
1398
+ },
1399
+ accountId: options.accountId
1400
+ };
1401
+ }
1402
+ async register(key, params, options = {}) {
1403
+ const runStore = runLocalStorage.getStore();
1404
+ if (!runStore) {
1405
+ return __privateGet(this, _client).registerTrigger(this.id, key, this.registeredTriggerForParams(params, options));
1406
+ }
1407
+ const { io } = runStore;
1408
+ return await io.runTask([
1409
+ key,
1410
+ "register"
1411
+ ], async (task) => {
1412
+ return __privateGet(this, _client).registerTrigger(this.id, key, this.registeredTriggerForParams(params, options), task.idempotencyKey);
1413
+ }, {
1414
+ name: "Register Dynamic Trigger",
1415
+ properties: [
1416
+ {
1417
+ label: "Dynamic Trigger ID",
1418
+ text: this.id
1419
+ },
1420
+ {
1421
+ label: "ID",
1422
+ text: key
1423
+ }
1424
+ ],
1425
+ params
1426
+ });
1427
+ }
1050
1428
  attachToJob(triggerClient, job) {
1429
+ triggerClient.attachJobToDynamicTrigger(job, this);
1051
1430
  }
1052
1431
  get preprocessRuns() {
1053
- return false;
1432
+ return true;
1054
1433
  }
1055
1434
  };
1056
- __name(EventTrigger, "EventTrigger");
1435
+ __name(DynamicTrigger, "DynamicTrigger");
1436
+ _client = new WeakMap();
1057
1437
  _options2 = new WeakMap();
1058
- function eventTrigger(options) {
1059
- return new EventTrigger({
1060
- name: options.name,
1061
- filter: options.filter,
1062
- event: {
1063
- name: options.name,
1064
- title: "Event",
1065
- source: options.source ?? "trigger.dev",
1066
- icon: "custom-event",
1067
- examples: options.examples,
1068
- parsePayload: (rawPayload) => {
1069
- if (options.schema) {
1070
- return options.schema.parse(rawPayload);
1071
- }
1072
- return rawPayload;
1073
- }
1074
- }
1438
+
1439
+ // 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
+ };
1075
1450
  });
1076
1451
  }
1077
- __name(eventTrigger, "eventTrigger");
1452
+ __name(formatSchemaErrors, "formatSchemaErrors");
1078
1453
 
1079
- // src/backgroundTask.ts
1080
- var _validate2, validate_fn2;
1081
- var BackgroundTask = class {
1082
- constructor(client, options) {
1083
- __privateAdd(this, _validate2);
1084
- this.client = client;
1454
+ // src/triggers/eventTrigger.ts
1455
+ var _options3;
1456
+ var EventTrigger = class {
1457
+ constructor(options) {
1458
+ __privateAdd(this, _options3, void 0);
1459
+ __privateSet(this, _options3, options);
1460
+ }
1461
+ toJSON() {
1462
+ return {
1463
+ type: "static",
1464
+ title: __privateGet(this, _options3).name ?? __privateGet(this, _options3).event.title,
1465
+ rule: {
1466
+ event: __privateGet(this, _options3).name ?? __privateGet(this, _options3).event.name,
1467
+ source: __privateGet(this, _options3).source ?? "trigger.dev",
1468
+ payload: (0, import_core5.deepMergeFilters)(__privateGet(this, _options3).filter ?? {}, __privateGet(this, _options3).event.filter ?? {})
1469
+ }
1470
+ };
1471
+ }
1472
+ get event() {
1473
+ return __privateGet(this, _options3).event;
1474
+ }
1475
+ attachToJob(triggerClient, job) {
1476
+ }
1477
+ get preprocessRuns() {
1478
+ return false;
1479
+ }
1480
+ };
1481
+ __name(EventTrigger, "EventTrigger");
1482
+ _options3 = new WeakMap();
1483
+ function eventTrigger(options) {
1484
+ return new EventTrigger({
1485
+ name: options.name,
1486
+ filter: options.filter,
1487
+ event: {
1488
+ name: options.name,
1489
+ title: "Event",
1490
+ source: options.source ?? "trigger.dev",
1491
+ icon: "custom-event",
1492
+ examples: options.examples,
1493
+ parsePayload: (rawPayload) => {
1494
+ if (options.schema) {
1495
+ const results = options.schema.safeParse(rawPayload);
1496
+ if (!results.success) {
1497
+ throw new ParsedPayloadSchemaError(formatSchemaErrors(results.error.issues));
1498
+ }
1499
+ return results.data;
1500
+ }
1501
+ return rawPayload;
1502
+ }
1503
+ }
1504
+ });
1505
+ }
1506
+ __name(eventTrigger, "eventTrigger");
1507
+
1508
+ // src/triggers/scheduled.ts
1509
+ var import_core6 = require("@trigger.dev/core");
1510
+ var import_cronstrue = __toESM(require("cronstrue"));
1511
+ var examples = [
1512
+ {
1513
+ id: "now",
1514
+ name: "Now",
1515
+ icon: "clock",
1516
+ payload: {
1517
+ ts: import_core6.currentDate.marker,
1518
+ lastTimestamp: import_core6.currentDate.marker
1519
+ }
1520
+ }
1521
+ ];
1522
+ var IntervalTrigger = class {
1523
+ constructor(options) {
1085
1524
  this.options = options;
1086
- __privateMethod(this, _validate2, validate_fn2).call(this);
1087
- client.attachBackgroundTask(this);
1088
1525
  }
1089
- get id() {
1090
- return slugifyId(this.options.id);
1526
+ get event() {
1527
+ return {
1528
+ name: "trigger.scheduled",
1529
+ title: "Schedule",
1530
+ source: "trigger.dev",
1531
+ icon: "schedule-interval",
1532
+ examples,
1533
+ parsePayload: import_core6.ScheduledPayloadSchema.parse,
1534
+ properties: [
1535
+ {
1536
+ label: "Interval",
1537
+ text: `${this.options.seconds}s`
1538
+ }
1539
+ ]
1540
+ };
1091
1541
  }
1092
- get enabled() {
1093
- return typeof this.options.enabled === "boolean" ? this.options.enabled : true;
1542
+ attachToJob(triggerClient, job) {
1094
1543
  }
1095
- get name() {
1096
- return this.options.name;
1544
+ get preprocessRuns() {
1545
+ return false;
1097
1546
  }
1098
- get schema() {
1099
- return this.options.schema;
1547
+ toJSON() {
1548
+ return {
1549
+ type: "scheduled",
1550
+ schedule: {
1551
+ type: "interval",
1552
+ options: {
1553
+ seconds: this.options.seconds
1554
+ }
1555
+ }
1556
+ };
1100
1557
  }
1101
- get version() {
1102
- return this.options.version;
1558
+ };
1559
+ __name(IntervalTrigger, "IntervalTrigger");
1560
+ function intervalTrigger(options) {
1561
+ return new IntervalTrigger(options);
1562
+ }
1563
+ __name(intervalTrigger, "intervalTrigger");
1564
+ var CronTrigger = class {
1565
+ constructor(options) {
1566
+ this.options = options;
1103
1567
  }
1104
- get logLevel() {
1105
- return this.options.logLevel;
1568
+ get event() {
1569
+ const humanReadable = import_cronstrue.default.toString(this.options.cron, {
1570
+ throwExceptionOnParseError: false
1571
+ });
1572
+ return {
1573
+ name: "trigger.scheduled",
1574
+ title: "Cron Schedule",
1575
+ source: "trigger.dev",
1576
+ icon: "schedule-cron",
1577
+ examples,
1578
+ parsePayload: import_core6.ScheduledPayloadSchema.parse,
1579
+ properties: [
1580
+ {
1581
+ label: "cron",
1582
+ text: this.options.cron
1583
+ },
1584
+ {
1585
+ label: "Schedule",
1586
+ text: humanReadable
1587
+ }
1588
+ ]
1589
+ };
1590
+ }
1591
+ attachToJob(triggerClient, job) {
1106
1592
  }
1107
- async invoke(key, payload) {
1593
+ get preprocessRuns() {
1594
+ return false;
1108
1595
  }
1109
1596
  toJSON() {
1110
1597
  return {
1111
- id: this.id,
1112
- name: this.name,
1113
- version: this.version,
1114
- enabled: this.enabled,
1115
- cpu: this.options.cpu ?? 1,
1116
- memory: this.options.memory ?? 256,
1117
- concurrency: this.options.concurrency ?? 1,
1118
- secrets: this.options.secrets ?? {}
1598
+ type: "scheduled",
1599
+ schedule: {
1600
+ type: "cron",
1601
+ options: {
1602
+ cron: this.options.cron
1603
+ }
1604
+ }
1119
1605
  };
1120
1606
  }
1121
1607
  };
1122
- __name(BackgroundTask, "BackgroundTask");
1123
- _validate2 = new WeakSet();
1124
- validate_fn2 = /* @__PURE__ */ __name(function() {
1125
- if (!this.version.match(/^(\d+)\.(\d+)\.(\d+)$/)) {
1126
- throw new Error(`Invalid job version: "${this.version}". BackgroundTask versions must be valid semver versions.`);
1608
+ __name(CronTrigger, "CronTrigger");
1609
+ function cronTrigger(options) {
1610
+ return new CronTrigger(options);
1611
+ }
1612
+ __name(cronTrigger, "cronTrigger");
1613
+ var DynamicSchedule = class {
1614
+ constructor(client, options) {
1615
+ this.client = client;
1616
+ this.options = options;
1617
+ client.attachDynamicSchedule(this.options.id);
1127
1618
  }
1128
- }, "#validate");
1619
+ get id() {
1620
+ return this.options.id;
1621
+ }
1622
+ get event() {
1623
+ return {
1624
+ name: "trigger.scheduled",
1625
+ title: "Dynamic Schedule",
1626
+ source: "trigger.dev",
1627
+ icon: "schedule-dynamic",
1628
+ examples,
1629
+ parsePayload: import_core6.ScheduledPayloadSchema.parse
1630
+ };
1631
+ }
1632
+ async register(key, metadata) {
1633
+ const runStore = runLocalStorage.getStore();
1634
+ if (!runStore) {
1635
+ return this.client.registerSchedule(this.id, key, metadata);
1636
+ }
1637
+ const { io } = runStore;
1638
+ return await io.runTask([
1639
+ key,
1640
+ "register"
1641
+ ], async (task) => {
1642
+ return this.client.registerSchedule(this.id, key, metadata);
1643
+ }, {
1644
+ name: "Register Schedule",
1645
+ icon: metadata.type === "cron" ? "schedule-cron" : "schedule-interval",
1646
+ properties: [
1647
+ {
1648
+ label: "Dynamic Schedule",
1649
+ text: this.id
1650
+ },
1651
+ {
1652
+ label: "Schedule ID",
1653
+ text: key
1654
+ }
1655
+ ],
1656
+ params: metadata
1657
+ });
1658
+ }
1659
+ async unregister(key) {
1660
+ const runStore = runLocalStorage.getStore();
1661
+ if (!runStore) {
1662
+ return this.client.unregisterSchedule(this.id, key);
1663
+ }
1664
+ const { io } = runStore;
1665
+ return await io.runTask([
1666
+ key,
1667
+ "unregister"
1668
+ ], async (task) => {
1669
+ return this.client.unregisterSchedule(this.id, key);
1670
+ }, {
1671
+ name: "Unregister Schedule",
1672
+ icon: "schedule",
1673
+ properties: [
1674
+ {
1675
+ label: "Dynamic Schedule",
1676
+ text: this.id
1677
+ },
1678
+ {
1679
+ label: "Schedule ID",
1680
+ text: key
1681
+ }
1682
+ ]
1683
+ });
1684
+ }
1685
+ attachToJob(triggerClient, job) {
1686
+ triggerClient.attachDynamicScheduleToJob(this.options.id, job);
1687
+ }
1688
+ get preprocessRuns() {
1689
+ return false;
1690
+ }
1691
+ toJSON() {
1692
+ return {
1693
+ type: "dynamic",
1694
+ id: this.options.id
1695
+ };
1696
+ }
1697
+ };
1698
+ __name(DynamicSchedule, "DynamicSchedule");
1699
+
1700
+ // package.json
1701
+ var version = "0.0.0-buffer-import-20231031135043";
1129
1702
 
1130
1703
  // src/triggerClient.ts
1131
1704
  var registerSourceEvent = {
1132
- name: import_core5.REGISTER_SOURCE_EVENT_V2,
1705
+ name: import_core7.REGISTER_SOURCE_EVENT_V2,
1133
1706
  title: "Register Source",
1134
1707
  source: "internal",
1135
1708
  icon: "register-source",
1136
- parsePayload: import_core5.RegisterSourceEventSchemaV2.parse
1709
+ parsePayload: import_core7.RegisterSourceEventSchemaV2.parse
1137
1710
  };
1138
- var _options3, _registeredJobs, _registeredSources, _registeredBackgroundTasks, _registeredHttpSourceHandlers, _registeredDynamicTriggers, _jobMetadataByDynamicTriggers, _registeredSchedules, _client, _internalLogger, _preprocessRun, preprocessRun_fn, _executeJob, executeJob_fn, _createRunContext, createRunContext_fn, _createPreprocessRunContext, createPreprocessRunContext_fn, _handleHttpSourceRequest, handleHttpSourceRequest_fn;
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;
1139
1712
  var TriggerClient = class {
1140
1713
  constructor(options) {
1141
1714
  __privateAdd(this, _preprocessRun);
@@ -1143,28 +1716,40 @@ var TriggerClient = class {
1143
1716
  __privateAdd(this, _createRunContext);
1144
1717
  __privateAdd(this, _createPreprocessRunContext);
1145
1718
  __privateAdd(this, _handleHttpSourceRequest);
1146
- __privateAdd(this, _options3, void 0);
1719
+ __privateAdd(this, _resolveConnections);
1720
+ __privateAdd(this, _resolveConnection);
1721
+ __privateAdd(this, _buildJobsIndex);
1722
+ __privateAdd(this, _buildJobIndex);
1723
+ __privateAdd(this, _buildJobIntegrations);
1724
+ __privateAdd(this, _buildJobIntegration);
1725
+ __privateAdd(this, _logIOStats);
1726
+ __privateAdd(this, _standardResponseHeaders);
1727
+ __privateAdd(this, _options4, void 0);
1147
1728
  __privateAdd(this, _registeredJobs, {});
1148
1729
  __privateAdd(this, _registeredSources, {});
1149
- __privateAdd(this, _registeredBackgroundTasks, {});
1150
1730
  __privateAdd(this, _registeredHttpSourceHandlers, {});
1151
1731
  __privateAdd(this, _registeredDynamicTriggers, {});
1152
1732
  __privateAdd(this, _jobMetadataByDynamicTriggers, {});
1153
1733
  __privateAdd(this, _registeredSchedules, {});
1154
- __privateAdd(this, _client, void 0);
1734
+ __privateAdd(this, _authResolvers, {});
1735
+ __privateAdd(this, _client2, void 0);
1155
1736
  __privateAdd(this, _internalLogger, void 0);
1156
1737
  this.id = options.id;
1157
- __privateSet(this, _options3, options);
1158
- __privateSet(this, _client, new ApiClient(__privateGet(this, _options3)));
1159
- __privateSet(this, _internalLogger, new import_core5.Logger("trigger.dev", __privateGet(this, _options3).verbose ? "debug" : "log"));
1738
+ __privateSet(this, _options4, options);
1739
+ __privateSet(this, _client2, new ApiClient(__privateGet(this, _options4)));
1740
+ __privateSet(this, _internalLogger, new import_core7.Logger("trigger.dev", __privateGet(this, _options4).verbose ? "debug" : "log", [
1741
+ "output",
1742
+ "noopTasksSet"
1743
+ ]));
1160
1744
  }
1161
- async handleRequest(request) {
1745
+ async handleRequest(request, timeOrigin = performance.now()) {
1162
1746
  __privateGet(this, _internalLogger).debug("handling request", {
1163
1747
  url: request.url,
1164
1748
  headers: Object.fromEntries(request.headers.entries()),
1165
1749
  method: request.method
1166
1750
  });
1167
1751
  const apiKey = request.headers.get("x-trigger-api-key");
1752
+ const triggerVersion = request.headers.get("x-trigger-version");
1168
1753
  const authorization = this.authorized(apiKey);
1169
1754
  switch (authorization) {
1170
1755
  case "authorized": {
@@ -1175,7 +1760,8 @@ var TriggerClient = class {
1175
1760
  status: 401,
1176
1761
  body: {
1177
1762
  message: "Unauthorized: client missing apiKey"
1178
- }
1763
+ },
1764
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1179
1765
  };
1180
1766
  }
1181
1767
  case "missing-header": {
@@ -1183,7 +1769,8 @@ var TriggerClient = class {
1183
1769
  status: 401,
1184
1770
  body: {
1185
1771
  message: "Unauthorized: missing x-trigger-api-key header"
1186
- }
1772
+ },
1773
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1187
1774
  };
1188
1775
  }
1189
1776
  case "unauthorized": {
@@ -1191,7 +1778,8 @@ var TriggerClient = class {
1191
1778
  status: 401,
1192
1779
  body: {
1193
1780
  message: `Forbidden: client apiKey mismatch: Make sure you are using the correct API Key for your environment`
1194
- }
1781
+ },
1782
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1195
1783
  };
1196
1784
  }
1197
1785
  }
@@ -1200,7 +1788,8 @@ var TriggerClient = class {
1200
1788
  status: 405,
1201
1789
  body: {
1202
1790
  message: "Method not allowed (only POST is allowed)"
1203
- }
1791
+ },
1792
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1204
1793
  };
1205
1794
  }
1206
1795
  const action = request.headers.get("x-trigger-action");
@@ -1209,7 +1798,8 @@ var TriggerClient = class {
1209
1798
  status: 400,
1210
1799
  body: {
1211
1800
  message: "Missing x-trigger-action header"
1212
- }
1801
+ },
1802
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1213
1803
  };
1214
1804
  }
1215
1805
  switch (action) {
@@ -1221,7 +1811,8 @@ var TriggerClient = class {
1221
1811
  body: {
1222
1812
  ok: false,
1223
1813
  error: "Missing endpoint ID"
1224
- }
1814
+ },
1815
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1225
1816
  };
1226
1817
  }
1227
1818
  if (this.id !== endpointId) {
@@ -1230,36 +1821,21 @@ var TriggerClient = class {
1230
1821
  body: {
1231
1822
  ok: false,
1232
1823
  error: `Endpoint ID mismatch error. Expected ${this.id}, got ${endpointId}`
1233
- }
1824
+ },
1825
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1234
1826
  };
1235
1827
  }
1236
1828
  return {
1237
1829
  status: 200,
1238
1830
  body: {
1239
1831
  ok: true
1240
- }
1832
+ },
1833
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1241
1834
  };
1242
1835
  }
1243
1836
  case "INDEX_ENDPOINT": {
1244
- const jobId = request.headers.get("x-trigger-job-id");
1245
- if (jobId) {
1246
- const job = __privateGet(this, _registeredJobs)[jobId];
1247
- if (!job) {
1248
- return {
1249
- status: 404,
1250
- body: {
1251
- message: "Job not found"
1252
- }
1253
- };
1254
- }
1255
- return {
1256
- status: 200,
1257
- body: job.toJSON()
1258
- };
1259
- }
1260
1837
  const body = {
1261
- jobs: Object.values(__privateGet(this, _registeredJobs)).map((job) => job.toJSON()),
1262
- backgroundTasks: Object.values(__privateGet(this, _registeredBackgroundTasks)).map((task) => task.toJSON()),
1838
+ jobs: __privateMethod(this, _buildJobsIndex, buildJobsIndex_fn).call(this),
1263
1839
  sources: Object.values(__privateGet(this, _registeredSources)),
1264
1840
  dynamicTriggers: Object.values(__privateGet(this, _registeredDynamicTriggers)).map((trigger) => ({
1265
1841
  id: trigger.id,
@@ -1276,12 +1852,13 @@ var TriggerClient = class {
1276
1852
  };
1277
1853
  return {
1278
1854
  status: 200,
1279
- body
1855
+ body,
1856
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1280
1857
  };
1281
1858
  }
1282
1859
  case "INITIALIZE_TRIGGER": {
1283
1860
  const json = await request.json();
1284
- const body = import_core5.InitializeTriggerBodySchema.safeParse(json);
1861
+ const body = import_core7.InitializeTriggerBodySchema.safeParse(json);
1285
1862
  if (!body.success) {
1286
1863
  return {
1287
1864
  status: 400,
@@ -1301,12 +1878,13 @@ var TriggerClient = class {
1301
1878
  }
1302
1879
  return {
1303
1880
  status: 200,
1304
- body: dynamicTrigger.registeredTriggerForParams(body.data.params)
1881
+ body: dynamicTrigger.registeredTriggerForParams(body.data.params),
1882
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1305
1883
  };
1306
1884
  }
1307
1885
  case "EXECUTE_JOB": {
1308
1886
  const json = await request.json();
1309
- const execution = import_core5.RunJobBodySchema.safeParse(json);
1887
+ const execution = import_core7.RunJobBodySchema.safeParse(json);
1310
1888
  if (!execution.success) {
1311
1889
  return {
1312
1890
  status: 400,
@@ -1324,15 +1902,16 @@ var TriggerClient = class {
1324
1902
  }
1325
1903
  };
1326
1904
  }
1327
- const results = await __privateMethod(this, _executeJob, executeJob_fn).call(this, execution.data, job);
1905
+ const results = await __privateMethod(this, _executeJob, executeJob_fn).call(this, execution.data, job, timeOrigin, triggerVersion);
1328
1906
  return {
1329
1907
  status: 200,
1330
- body: results
1908
+ body: results,
1909
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1331
1910
  };
1332
1911
  }
1333
1912
  case "PREPROCESS_RUN": {
1334
1913
  const json = await request.json();
1335
- const body = import_core5.PreprocessRunBodySchema.safeParse(json);
1914
+ const body = import_core7.PreprocessRunBodySchema.safeParse(json);
1336
1915
  if (!body.success) {
1337
1916
  return {
1338
1917
  status: 400,
@@ -1356,11 +1935,12 @@ var TriggerClient = class {
1356
1935
  body: {
1357
1936
  abort: results.abort,
1358
1937
  properties: results.properties
1359
- }
1938
+ },
1939
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1360
1940
  };
1361
1941
  }
1362
1942
  case "DELIVER_HTTP_SOURCE_REQUEST": {
1363
- const headers = import_core5.HttpSourceRequestHeadersSchema.safeParse(Object.fromEntries(request.headers.entries()));
1943
+ const headers = import_core7.HttpSourceRequestHeadersSchema.safeParse(Object.fromEntries(request.headers.entries()));
1364
1944
  if (!headers.success) {
1365
1945
  return {
1366
1946
  status: 400,
@@ -1405,7 +1985,8 @@ var TriggerClient = class {
1405
1985
  events,
1406
1986
  response,
1407
1987
  metadata
1408
- }
1988
+ },
1989
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1409
1990
  };
1410
1991
  }
1411
1992
  case "VALIDATE": {
@@ -1414,7 +1995,20 @@ var TriggerClient = class {
1414
1995
  body: {
1415
1996
  ok: true,
1416
1997
  endpointId: this.id
1417
- }
1998
+ },
1999
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
2000
+ };
2001
+ }
2002
+ case "PROBE_EXECUTION_TIMEOUT": {
2003
+ const json = await request.json();
2004
+ const timeout = json?.timeout ?? 15 * 60 * 1e3;
2005
+ await new Promise((resolve) => setTimeout(resolve, timeout));
2006
+ return {
2007
+ status: 200,
2008
+ body: {
2009
+ ok: true
2010
+ },
2011
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1418
2012
  };
1419
2013
  }
1420
2014
  }
@@ -1422,19 +2016,30 @@ var TriggerClient = class {
1422
2016
  status: 405,
1423
2017
  body: {
1424
2018
  message: "Method not allowed"
1425
- }
2019
+ },
2020
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1426
2021
  };
1427
2022
  }
2023
+ defineJob(options) {
2024
+ return new Job(this, options);
2025
+ }
2026
+ defineAuthResolver(integration, resolver) {
2027
+ __privateGet(this, _authResolvers)[integration.id] = resolver;
2028
+ return this;
2029
+ }
2030
+ defineDynamicSchedule(options) {
2031
+ return new DynamicSchedule(this, options);
2032
+ }
2033
+ defineDynamicTrigger(options) {
2034
+ return new DynamicTrigger(this, options);
2035
+ }
1428
2036
  attach(job) {
1429
2037
  __privateGet(this, _registeredJobs)[job.id] = job;
1430
2038
  job.trigger.attachToJob(this, job);
1431
2039
  }
1432
- attachBackgroundTask(task) {
1433
- __privateGet(this, _registeredBackgroundTasks)[task.id] = task;
1434
- }
1435
2040
  attachDynamicTrigger(trigger) {
1436
2041
  __privateGet(this, _registeredDynamicTriggers)[trigger.id] = trigger;
1437
- new Job(this, {
2042
+ this.defineJob({
1438
2043
  id: dynamicTriggerRegisterSourceJobId(trigger.id),
1439
2044
  name: `Register dynamic trigger ${trigger.id}`,
1440
2045
  version: trigger.source.version,
@@ -1530,7 +2135,11 @@ var TriggerClient = class {
1530
2135
  __internal: true
1531
2136
  });
1532
2137
  }
1533
- attachDynamicSchedule(key, job) {
2138
+ attachDynamicSchedule(key) {
2139
+ const jobs = __privateGet(this, _registeredSchedules)[key] ?? [];
2140
+ __privateGet(this, _registeredSchedules)[key] = jobs;
2141
+ }
2142
+ attachDynamicScheduleToJob(key, job) {
1534
2143
  const jobs = __privateGet(this, _registeredSchedules)[key] ?? [];
1535
2144
  jobs.push({
1536
2145
  id: job.id,
@@ -1538,63 +2147,69 @@ var TriggerClient = class {
1538
2147
  });
1539
2148
  __privateGet(this, _registeredSchedules)[key] = jobs;
1540
2149
  }
1541
- async registerTrigger(id, key, options) {
1542
- return __privateGet(this, _client).registerTrigger(this.id, id, key, options);
2150
+ async registerTrigger(id, key, options, idempotencyKey) {
2151
+ return __privateGet(this, _client2).registerTrigger(this.id, id, key, options, idempotencyKey);
1543
2152
  }
1544
2153
  async getAuth(id) {
1545
- return __privateGet(this, _client).getAuth(this.id, id);
2154
+ return __privateGet(this, _client2).getAuth(this.id, id);
1546
2155
  }
1547
2156
  async sendEvent(event, options) {
1548
- return __privateGet(this, _client).sendEvent(event, options);
2157
+ return __privateGet(this, _client2).sendEvent(event, options);
1549
2158
  }
1550
2159
  async cancelEvent(eventId) {
1551
- return __privateGet(this, _client).cancelEvent(eventId);
2160
+ return __privateGet(this, _client2).cancelEvent(eventId);
2161
+ }
2162
+ async cancelRunsForEvent(eventId) {
2163
+ return __privateGet(this, _client2).cancelRunsForEvent(eventId);
2164
+ }
2165
+ async updateStatus(runId, id, status) {
2166
+ return __privateGet(this, _client2).updateStatus(runId, id, status);
1552
2167
  }
1553
2168
  async registerSchedule(id, key, schedule) {
1554
- return __privateGet(this, _client).registerSchedule(this.id, id, key, schedule);
2169
+ return __privateGet(this, _client2).registerSchedule(this.id, id, key, schedule);
1555
2170
  }
1556
2171
  async unregisterSchedule(id, key) {
1557
- return __privateGet(this, _client).unregisterSchedule(this.id, id, key);
2172
+ return __privateGet(this, _client2).unregisterSchedule(this.id, id, key);
1558
2173
  }
1559
2174
  async getEvent(eventId) {
1560
- return __privateGet(this, _client).getEvent(eventId);
2175
+ return __privateGet(this, _client2).getEvent(eventId);
1561
2176
  }
1562
2177
  async getRun(runId, options) {
1563
- return __privateGet(this, _client).getRun(runId, options);
2178
+ return __privateGet(this, _client2).getRun(runId, options);
2179
+ }
2180
+ async cancelRun(runId) {
2181
+ return __privateGet(this, _client2).cancelRun(runId);
1564
2182
  }
1565
2183
  async getRuns(jobSlug, options) {
1566
- return __privateGet(this, _client).getRuns(jobSlug, options);
2184
+ return __privateGet(this, _client2).getRuns(jobSlug, options);
2185
+ }
2186
+ async getRunStatuses(runId) {
2187
+ return __privateGet(this, _client2).getRunStatuses(runId);
1567
2188
  }
1568
2189
  authorized(apiKey) {
1569
2190
  if (typeof apiKey !== "string") {
1570
2191
  return "missing-header";
1571
2192
  }
1572
- const localApiKey = __privateGet(this, _options3).apiKey ?? process.env.TRIGGER_API_KEY;
2193
+ const localApiKey = __privateGet(this, _options4).apiKey ?? process.env.TRIGGER_API_KEY;
1573
2194
  if (!localApiKey) {
1574
2195
  return "missing-client";
1575
2196
  }
1576
2197
  return apiKey === localApiKey ? "authorized" : "unauthorized";
1577
2198
  }
1578
2199
  apiKey() {
1579
- return __privateGet(this, _options3).apiKey ?? process.env.TRIGGER_API_KEY;
1580
- }
1581
- defineJob(options) {
1582
- return new Job(this, options);
1583
- }
1584
- defineBackgroundTask(options) {
1585
- return new BackgroundTask(this, options);
2200
+ return __privateGet(this, _options4).apiKey ?? process.env.TRIGGER_API_KEY;
1586
2201
  }
1587
2202
  };
1588
2203
  __name(TriggerClient, "TriggerClient");
1589
- _options3 = new WeakMap();
2204
+ _options4 = new WeakMap();
1590
2205
  _registeredJobs = new WeakMap();
1591
2206
  _registeredSources = new WeakMap();
1592
- _registeredBackgroundTasks = new WeakMap();
1593
2207
  _registeredHttpSourceHandlers = new WeakMap();
1594
2208
  _registeredDynamicTriggers = new WeakMap();
1595
2209
  _jobMetadataByDynamicTriggers = new WeakMap();
1596
2210
  _registeredSchedules = new WeakMap();
1597
- _client = new WeakMap();
2211
+ _authResolvers = new WeakMap();
2212
+ _client2 = new WeakMap();
1598
2213
  _internalLogger = new WeakMap();
1599
2214
  _preprocessRun = new WeakSet();
1600
2215
  preprocessRun_fn = /* @__PURE__ */ __name(async function(body, job) {
@@ -1607,30 +2222,89 @@ preprocessRun_fn = /* @__PURE__ */ __name(async function(body, job) {
1607
2222
  };
1608
2223
  }, "#preprocessRun");
1609
2224
  _executeJob = new WeakSet();
1610
- executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1) {
2225
+ executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1, timeOrigin, triggerVersion) {
1611
2226
  __privateGet(this, _internalLogger).debug("executing job", {
1612
2227
  execution: body1,
1613
- job: job1.toJSON()
2228
+ job: job1.id,
2229
+ version: job1.version,
2230
+ triggerVersion
1614
2231
  });
1615
2232
  const context = __privateMethod(this, _createRunContext, createRunContext_fn).call(this, body1);
1616
2233
  const io = new IO({
1617
2234
  id: body1.run.id,
1618
2235
  cachedTasks: body1.tasks,
1619
- apiClient: __privateGet(this, _client),
2236
+ cachedTasksCursor: body1.cachedTaskCursor,
2237
+ yieldedExecutions: body1.yieldedExecutions ?? [],
2238
+ noopTasksSet: body1.noopTasksSet,
2239
+ apiClient: __privateGet(this, _client2),
1620
2240
  logger: __privateGet(this, _internalLogger),
1621
2241
  client: this,
1622
2242
  context,
1623
- jobLogLevel: job1.logLevel ?? __privateGet(this, _options3).logLevel ?? "info",
1624
- jobLogger: __privateGet(this, _options3).ioLogLocalEnabled ? new import_core5.Logger(job1.id, job1.logLevel ?? __privateGet(this, _options3).logLevel ?? "info") : void 0
2243
+ 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,
2245
+ serverVersion: triggerVersion,
2246
+ timeOrigin,
2247
+ executionTimeout: body1.runChunkExecutionLimit
1625
2248
  });
1626
- const ioWithConnections = createIOWithIntegrations(io, body1.connections, job1.options.integrations);
2249
+ const resolvedConnections = await __privateMethod(this, _resolveConnections, resolveConnections_fn).call(this, context, job1.options.integrations, body1.connections);
2250
+ if (!resolvedConnections.ok) {
2251
+ return {
2252
+ status: "UNRESOLVED_AUTH_ERROR",
2253
+ issues: resolvedConnections.issues
2254
+ };
2255
+ }
2256
+ const ioWithConnections = createIOWithIntegrations(io, resolvedConnections.data, job1.options.integrations);
1627
2257
  try {
1628
- const output = await job1.options.run(job1.trigger.event.parsePayload(body1.event.payload ?? {}), ioWithConnections, context);
2258
+ const output = await runLocalStorage.runWith({
2259
+ io,
2260
+ ctx: context
2261
+ }, () => {
2262
+ return job1.options.run(job1.trigger.event.parsePayload(body1.event.payload ?? {}), ioWithConnections, context);
2263
+ });
2264
+ if (__privateGet(this, _options4).verbose) {
2265
+ __privateMethod(this, _logIOStats, logIOStats_fn).call(this, io.stats);
2266
+ }
1629
2267
  return {
1630
2268
  status: "SUCCESS",
1631
2269
  output
1632
2270
  };
1633
2271
  } catch (error) {
2272
+ if (__privateGet(this, _options4).verbose) {
2273
+ __privateMethod(this, _logIOStats, logIOStats_fn).call(this, io.stats);
2274
+ }
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) {
2303
+ return {
2304
+ status: "INVALID_PAYLOAD",
2305
+ errors: error.schemaErrors
2306
+ };
2307
+ }
1634
2308
  if (error instanceof ResumeWithTaskError) {
1635
2309
  return {
1636
2310
  status: "RESUME_WITH_TASK",
@@ -1652,7 +2326,7 @@ executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1) {
1652
2326
  };
1653
2327
  }
1654
2328
  if (error instanceof RetryWithTaskError) {
1655
- const errorWithStack2 = import_core5.ErrorWithStackSchema.safeParse(error.cause);
2329
+ const errorWithStack2 = import_core7.ErrorWithStackSchema.safeParse(error.cause);
1656
2330
  if (errorWithStack2.success) {
1657
2331
  return {
1658
2332
  status: "ERROR",
@@ -1668,17 +2342,19 @@ executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1) {
1668
2342
  task: error.task
1669
2343
  };
1670
2344
  }
1671
- const errorWithStack = import_core5.ErrorWithStackSchema.safeParse(error);
2345
+ const errorWithStack = import_core7.ErrorWithStackSchema.safeParse(error);
1672
2346
  if (errorWithStack.success) {
1673
2347
  return {
1674
2348
  status: "ERROR",
1675
2349
  error: errorWithStack.data
1676
2350
  };
1677
2351
  }
2352
+ const message = typeof error === "string" ? error : JSON.stringify(error);
1678
2353
  return {
1679
2354
  status: "ERROR",
1680
2355
  error: {
1681
- message: "Unknown error"
2356
+ name: "Unknown error",
2357
+ message
1682
2358
  }
1683
2359
  };
1684
2360
  }
@@ -1800,6 +2476,168 @@ handleHttpSourceRequest_fn = /* @__PURE__ */ __name(async function(source, sourc
1800
2476
  metadata: results.metadata
1801
2477
  };
1802
2478
  }, "#handleHttpSourceRequest");
2479
+ _resolveConnections = new WeakSet();
2480
+ resolveConnections_fn = /* @__PURE__ */ __name(async function(ctx, integrations, connections) {
2481
+ if (!integrations) {
2482
+ return {
2483
+ ok: true,
2484
+ data: {}
2485
+ };
2486
+ }
2487
+ const resolvedAuthResults = await Promise.all(Object.keys(integrations).map(async (key) => {
2488
+ const integration = integrations[key];
2489
+ const auth = (connections ?? {})[key];
2490
+ const result = await __privateMethod(this, _resolveConnection, resolveConnection_fn).call(this, ctx, integration, auth);
2491
+ if (result.ok) {
2492
+ return {
2493
+ ok: true,
2494
+ auth: result.auth,
2495
+ key
2496
+ };
2497
+ } else {
2498
+ return {
2499
+ ok: false,
2500
+ error: result.error,
2501
+ key
2502
+ };
2503
+ }
2504
+ }));
2505
+ const allResolved = resolvedAuthResults.every((result) => result.ok);
2506
+ if (allResolved) {
2507
+ return {
2508
+ ok: true,
2509
+ data: resolvedAuthResults.reduce((acc, result) => {
2510
+ acc[result.key] = result.auth;
2511
+ return acc;
2512
+ }, {})
2513
+ };
2514
+ } else {
2515
+ return {
2516
+ ok: false,
2517
+ issues: resolvedAuthResults.reduce((acc, result) => {
2518
+ if (result.ok) {
2519
+ return acc;
2520
+ }
2521
+ const integration = integrations[result.key];
2522
+ acc[result.key] = {
2523
+ id: integration.id,
2524
+ error: result.error
2525
+ };
2526
+ return acc;
2527
+ }, {})
2528
+ };
2529
+ }
2530
+ }, "#resolveConnections");
2531
+ _resolveConnection = new WeakSet();
2532
+ resolveConnection_fn = /* @__PURE__ */ __name(async function(ctx1, integration, auth) {
2533
+ if (auth) {
2534
+ return {
2535
+ ok: true,
2536
+ auth
2537
+ };
2538
+ }
2539
+ const authResolver = __privateGet(this, _authResolvers)[integration.id];
2540
+ if (!authResolver) {
2541
+ if (integration.authSource === "HOSTED") {
2542
+ return {
2543
+ ok: false,
2544
+ error: `Something went wrong: Integration ${integration.id} is missing auth credentials from Trigger.dev`
2545
+ };
2546
+ }
2547
+ return {
2548
+ ok: true,
2549
+ auth: void 0
2550
+ };
2551
+ }
2552
+ try {
2553
+ const resolvedAuth = await authResolver(ctx1, integration);
2554
+ if (!resolvedAuth) {
2555
+ return {
2556
+ ok: false,
2557
+ error: `Auth could not be resolved for ${integration.id}: auth resolver returned null or undefined`
2558
+ };
2559
+ }
2560
+ return {
2561
+ ok: true,
2562
+ auth: resolvedAuth.type === "apiKey" ? {
2563
+ type: "apiKey",
2564
+ accessToken: resolvedAuth.token,
2565
+ additionalFields: resolvedAuth.additionalFields
2566
+ } : {
2567
+ type: "oauth2",
2568
+ accessToken: resolvedAuth.token,
2569
+ additionalFields: resolvedAuth.additionalFields
2570
+ }
2571
+ };
2572
+ } catch (resolverError) {
2573
+ if (resolverError instanceof Error) {
2574
+ return {
2575
+ ok: false,
2576
+ error: `Auth could not be resolved for ${integration.id}: auth resolver threw. ${resolverError.name}: ${resolverError.message}`
2577
+ };
2578
+ } else if (typeof resolverError === "string") {
2579
+ return {
2580
+ ok: false,
2581
+ error: `Auth could not be resolved for ${integration.id}: auth resolver threw an error: ${resolverError}`
2582
+ };
2583
+ }
2584
+ return {
2585
+ ok: false,
2586
+ error: `Auth could not be resolved for ${integration.id}: auth resolver threw an unknown error: ${JSON.stringify(resolverError)}`
2587
+ };
2588
+ }
2589
+ }, "#resolveConnection");
2590
+ _buildJobsIndex = new WeakSet();
2591
+ buildJobsIndex_fn = /* @__PURE__ */ __name(function() {
2592
+ return Object.values(__privateGet(this, _registeredJobs)).map((job) => __privateMethod(this, _buildJobIndex, buildJobIndex_fn).call(this, job));
2593
+ }, "#buildJobsIndex");
2594
+ _buildJobIndex = new WeakSet();
2595
+ buildJobIndex_fn = /* @__PURE__ */ __name(function(job2) {
2596
+ const internal = job2.options.__internal;
2597
+ return {
2598
+ id: job2.id,
2599
+ name: job2.name,
2600
+ version: job2.version,
2601
+ event: job2.trigger.event,
2602
+ trigger: job2.trigger.toJSON(),
2603
+ integrations: __privateMethod(this, _buildJobIntegrations, buildJobIntegrations_fn).call(this, job2),
2604
+ startPosition: "latest",
2605
+ enabled: job2.enabled,
2606
+ preprocessRuns: job2.trigger.preprocessRuns,
2607
+ internal
2608
+ };
2609
+ }, "#buildJobIndex");
2610
+ _buildJobIntegrations = new WeakSet();
2611
+ buildJobIntegrations_fn = /* @__PURE__ */ __name(function(job3) {
2612
+ return Object.keys(job3.options.integrations ?? {}).reduce((acc, key) => {
2613
+ const integration = job3.options.integrations[key];
2614
+ acc[key] = __privateMethod(this, _buildJobIntegration, buildJobIntegration_fn).call(this, integration);
2615
+ return acc;
2616
+ }, {});
2617
+ }, "#buildJobIntegrations");
2618
+ _buildJobIntegration = new WeakSet();
2619
+ buildJobIntegration_fn = /* @__PURE__ */ __name(function(integration1) {
2620
+ const authSource = __privateGet(this, _authResolvers)[integration1.id] ? "RESOLVER" : integration1.authSource;
2621
+ return {
2622
+ id: integration1.id,
2623
+ metadata: integration1.metadata,
2624
+ authSource
2625
+ };
2626
+ }, "#buildJobIntegration");
2627
+ _logIOStats = new WeakSet();
2628
+ logIOStats_fn = /* @__PURE__ */ __name(function(stats) {
2629
+ __privateGet(this, _internalLogger).debug("IO stats", {
2630
+ stats
2631
+ });
2632
+ }, "#logIOStats");
2633
+ _standardResponseHeaders = new WeakSet();
2634
+ standardResponseHeaders_fn = /* @__PURE__ */ __name(function(start) {
2635
+ return {
2636
+ "Trigger-Version": import_core7.API_VERSIONS.LAZY_LOADED_CACHED_TASKS,
2637
+ "Trigger-SDK-Version": version,
2638
+ "X-Trigger-Request-Timing": `dur=${performance.now() - start / 1e3}`
2639
+ };
2640
+ }, "#standardResponseHeaders");
1803
2641
  function dynamicTriggerRegisterSourceJobId(id) {
1804
2642
  return `register-dynamic-trigger-${id}`;
1805
2643
  }
@@ -1825,7 +2663,7 @@ function deepMergeOptions(obj1, obj2) {
1825
2663
  __name(deepMergeOptions, "deepMergeOptions");
1826
2664
 
1827
2665
  // src/triggers/externalSource.ts
1828
- var import_core6 = require("@trigger.dev/core");
2666
+ var import_core8 = require("@trigger.dev/core");
1829
2667
  var ExternalSource = class {
1830
2668
  constructor(channel, options) {
1831
2669
  this.options = options;
@@ -1899,7 +2737,7 @@ var ExternalSourceTrigger = class {
1899
2737
  title: "External Source",
1900
2738
  rule: {
1901
2739
  event: this.event.name,
1902
- payload: (0, import_core6.deepMergeFilters)(this.options.source.filter(this.options.params, this.options.options), this.event.filter ?? {}, this.options.params.filter ?? {}),
2740
+ payload: (0, import_core8.deepMergeFilters)(this.options.source.filter(this.options.params, this.options.options), this.event.filter ?? {}, this.options.params.filter ?? {}),
1903
2741
  source: this.event.source
1904
2742
  },
1905
2743
  properties: this.options.source.properties(this.options.params)
@@ -1933,214 +2771,6 @@ function omit(obj, key) {
1933
2771
  }
1934
2772
  __name(omit, "omit");
1935
2773
 
1936
- // src/triggers/dynamic.ts
1937
- var import_core7 = require("@trigger.dev/core");
1938
- var _client2, _options4;
1939
- var DynamicTrigger = class {
1940
- constructor(client, options) {
1941
- __privateAdd(this, _client2, void 0);
1942
- __privateAdd(this, _options4, void 0);
1943
- __privateSet(this, _client2, client);
1944
- __privateSet(this, _options4, options);
1945
- this.source = options.source;
1946
- client.attachDynamicTrigger(this);
1947
- }
1948
- toJSON() {
1949
- return {
1950
- type: "dynamic",
1951
- id: __privateGet(this, _options4).id
1952
- };
1953
- }
1954
- get id() {
1955
- return __privateGet(this, _options4).id;
1956
- }
1957
- get event() {
1958
- return __privateGet(this, _options4).event;
1959
- }
1960
- registeredTriggerForParams(params) {
1961
- const key = slugifyId(this.source.key(params));
1962
- return {
1963
- rule: {
1964
- event: this.event.name,
1965
- source: this.event.source,
1966
- payload: (0, import_core7.deepMergeFilters)(this.source.filter(params), this.event.filter ?? {})
1967
- },
1968
- source: {
1969
- version: "2",
1970
- key,
1971
- channel: this.source.channel,
1972
- params,
1973
- options: {
1974
- event: typeof this.event.name === "string" ? [
1975
- this.event.name
1976
- ] : this.event.name
1977
- },
1978
- integration: {
1979
- id: this.source.integration.id,
1980
- metadata: this.source.integration.metadata,
1981
- authSource: this.source.integration.authSource
1982
- }
1983
- }
1984
- };
1985
- }
1986
- async register(key, params) {
1987
- return __privateGet(this, _client2).registerTrigger(this.id, key, this.registeredTriggerForParams(params));
1988
- }
1989
- attachToJob(triggerClient, job) {
1990
- triggerClient.attachJobToDynamicTrigger(job, this);
1991
- }
1992
- get preprocessRuns() {
1993
- return true;
1994
- }
1995
- };
1996
- __name(DynamicTrigger, "DynamicTrigger");
1997
- _client2 = new WeakMap();
1998
- _options4 = new WeakMap();
1999
-
2000
- // src/triggers/scheduled.ts
2001
- var import_core8 = require("@trigger.dev/core");
2002
- var import_cronstrue = __toESM(require("cronstrue"));
2003
- var examples = [
2004
- {
2005
- id: "now",
2006
- name: "Now",
2007
- icon: "clock",
2008
- payload: {
2009
- ts: import_core8.currentDate.marker,
2010
- lastTimestamp: import_core8.currentDate.marker
2011
- }
2012
- }
2013
- ];
2014
- var IntervalTrigger = class {
2015
- constructor(options) {
2016
- this.options = options;
2017
- }
2018
- get event() {
2019
- return {
2020
- name: "trigger.scheduled",
2021
- title: "Schedule",
2022
- source: "trigger.dev",
2023
- icon: "schedule-interval",
2024
- examples,
2025
- parsePayload: import_core8.ScheduledPayloadSchema.parse,
2026
- properties: [
2027
- {
2028
- label: "Interval",
2029
- text: `${this.options.seconds}s`
2030
- }
2031
- ]
2032
- };
2033
- }
2034
- attachToJob(triggerClient, job) {
2035
- }
2036
- get preprocessRuns() {
2037
- return false;
2038
- }
2039
- toJSON() {
2040
- return {
2041
- type: "scheduled",
2042
- schedule: {
2043
- type: "interval",
2044
- options: {
2045
- seconds: this.options.seconds
2046
- }
2047
- }
2048
- };
2049
- }
2050
- };
2051
- __name(IntervalTrigger, "IntervalTrigger");
2052
- function intervalTrigger(options) {
2053
- return new IntervalTrigger(options);
2054
- }
2055
- __name(intervalTrigger, "intervalTrigger");
2056
- var CronTrigger = class {
2057
- constructor(options) {
2058
- this.options = options;
2059
- }
2060
- get event() {
2061
- const humanReadable = import_cronstrue.default.toString(this.options.cron, {
2062
- throwExceptionOnParseError: false
2063
- });
2064
- return {
2065
- name: "trigger.scheduled",
2066
- title: "Cron Schedule",
2067
- source: "trigger.dev",
2068
- icon: "schedule-cron",
2069
- examples,
2070
- parsePayload: import_core8.ScheduledPayloadSchema.parse,
2071
- properties: [
2072
- {
2073
- label: "cron",
2074
- text: this.options.cron
2075
- },
2076
- {
2077
- label: "Schedule",
2078
- text: humanReadable
2079
- }
2080
- ]
2081
- };
2082
- }
2083
- attachToJob(triggerClient, job) {
2084
- }
2085
- get preprocessRuns() {
2086
- return false;
2087
- }
2088
- toJSON() {
2089
- return {
2090
- type: "scheduled",
2091
- schedule: {
2092
- type: "cron",
2093
- options: {
2094
- cron: this.options.cron
2095
- }
2096
- }
2097
- };
2098
- }
2099
- };
2100
- __name(CronTrigger, "CronTrigger");
2101
- function cronTrigger(options) {
2102
- return new CronTrigger(options);
2103
- }
2104
- __name(cronTrigger, "cronTrigger");
2105
- var DynamicSchedule = class {
2106
- constructor(client, options) {
2107
- this.client = client;
2108
- this.options = options;
2109
- }
2110
- get id() {
2111
- return this.options.id;
2112
- }
2113
- get event() {
2114
- return {
2115
- name: "trigger.scheduled",
2116
- title: "Dynamic Schedule",
2117
- source: "trigger.dev",
2118
- icon: "schedule-dynamic",
2119
- examples,
2120
- parsePayload: import_core8.ScheduledPayloadSchema.parse
2121
- };
2122
- }
2123
- async register(key, metadata) {
2124
- return this.client.registerSchedule(this.id, key, metadata);
2125
- }
2126
- async unregister(key) {
2127
- return this.client.unregisterSchedule(this.id, key);
2128
- }
2129
- attachToJob(triggerClient, job) {
2130
- triggerClient.attachDynamicSchedule(this.options.id, job);
2131
- }
2132
- get preprocessRuns() {
2133
- return false;
2134
- }
2135
- toJSON() {
2136
- return {
2137
- type: "dynamic",
2138
- id: this.options.id
2139
- };
2140
- }
2141
- };
2142
- __name(DynamicSchedule, "DynamicSchedule");
2143
-
2144
2774
  // src/triggers/notifications.ts
2145
2775
  var import_core9 = require("@trigger.dev/core");
2146
2776
  function missingConnectionNotification(integrations) {