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

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,8 +550,37 @@ 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
 
@@ -477,11 +601,52 @@ var retry = {
477
601
  }
478
602
  };
479
603
 
604
+ // src/status.ts
605
+ var TriggerStatus = class {
606
+ constructor(id, io) {
607
+ this.id = id;
608
+ this.io = io;
609
+ }
610
+ async update(key, status) {
611
+ const properties = [];
612
+ if (status.label) {
613
+ properties.push({
614
+ label: "Label",
615
+ text: status.label
616
+ });
617
+ }
618
+ if (status.state) {
619
+ properties.push({
620
+ label: "State",
621
+ text: status.state
622
+ });
623
+ }
624
+ return await this.io.runTask(key, async (task) => {
625
+ return await this.io.triggerClient.updateStatus(this.io.runId, this.id, status);
626
+ }, {
627
+ name: status.label ?? `Status update`,
628
+ icon: "bell",
629
+ params: {
630
+ ...status
631
+ },
632
+ properties
633
+ });
634
+ }
635
+ };
636
+ __name(TriggerStatus, "TriggerStatus");
637
+
480
638
  // src/io.ts
481
- var _addToCachedTasks, addToCachedTasks_fn;
639
+ var _addToCachedTasks, addToCachedTasks_fn, _detectAutoYield, detectAutoYield_fn, _forceYield, forceYield_fn, _getTimeElapsed, getTimeElapsed_fn, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn, _testNoopTaskBloomFilter, testNoopTaskBloomFilter_fn, _addNoopTaskBloomFilter, addNoopTaskBloomFilter_fn;
482
640
  var IO = class {
483
641
  constructor(options) {
484
642
  __privateAdd(this, _addToCachedTasks);
643
+ __privateAdd(this, _detectAutoYield);
644
+ __privateAdd(this, _forceYield);
645
+ __privateAdd(this, _getTimeElapsed);
646
+ __privateAdd(this, _getRemainingTimeInMillis);
647
+ __privateAdd(this, _testNoopTaskBloomFilter);
648
+ __privateAdd(this, _addNoopTaskBloomFilter);
649
+ __publicField(this, "brb", this.yield.bind(this));
485
650
  this._id = options.id;
486
651
  this._apiClient = options.apiClient;
487
652
  this._triggerClient = options.client;
@@ -489,49 +654,76 @@ var IO = class {
489
654
  this._cachedTasks = /* @__PURE__ */ new Map();
490
655
  this._jobLogger = options.jobLogger;
491
656
  this._jobLogLevel = options.jobLogLevel;
657
+ this._timeOrigin = options.timeOrigin;
658
+ this._executionTimeout = options.executionTimeout;
659
+ this._stats = {
660
+ initialCachedTasks: 0,
661
+ lazyLoadedCachedTasks: 0,
662
+ executedTasks: 0,
663
+ cachedTaskHits: 0,
664
+ cachedTaskMisses: 0,
665
+ noopCachedTaskHits: 0,
666
+ noopCachedTaskMisses: 0
667
+ };
492
668
  if (options.cachedTasks) {
493
669
  options.cachedTasks.forEach((task) => {
494
670
  this._cachedTasks.set(task.idempotencyKey, task);
495
671
  });
672
+ this._stats.initialCachedTasks = options.cachedTasks.length;
496
673
  }
497
674
  this._taskStorage = new import_node_async_hooks.AsyncLocalStorage();
498
675
  this._context = options.context;
676
+ this._yieldedExecutions = options.yieldedExecutions ?? [];
677
+ if (options.noopTasksSet) {
678
+ this._noopTasksRawData = options.noopTasksSet;
679
+ }
680
+ this._cachedTasksCursor = options.cachedTasksCursor;
681
+ this._serverVersion = options.serverVersion ?? "unversioned";
682
+ }
683
+ get stats() {
684
+ return this._stats;
685
+ }
686
+ get runId() {
687
+ return this._id;
688
+ }
689
+ get triggerClient() {
690
+ return this._triggerClient;
499
691
  }
500
692
  get logger() {
501
693
  return new IOLogger(async (level, message, data) => {
502
694
  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
695
  if (import_core3.Logger.satisfiesLogLevel(logLevel, this._jobLogLevel)) {
531
696
  await this.runTask([
532
697
  message,
533
698
  level
534
699
  ], async (task) => {
700
+ switch (level) {
701
+ case "LOG": {
702
+ this._jobLogger?.log(message, data);
703
+ logLevel = "log";
704
+ break;
705
+ }
706
+ case "DEBUG": {
707
+ this._jobLogger?.debug(message, data);
708
+ logLevel = "debug";
709
+ break;
710
+ }
711
+ case "INFO": {
712
+ this._jobLogger?.info(message, data);
713
+ logLevel = "info";
714
+ break;
715
+ }
716
+ case "WARN": {
717
+ this._jobLogger?.warn(message, data);
718
+ logLevel = "warn";
719
+ break;
720
+ }
721
+ case "ERROR": {
722
+ this._jobLogger?.error(message, data);
723
+ logLevel = "error";
724
+ break;
725
+ }
726
+ }
535
727
  }, {
536
728
  name: "log",
537
729
  icon: "log",
@@ -552,8 +744,8 @@ var IO = class {
552
744
  }
553
745
  });
554
746
  }
555
- async wait(key, seconds) {
556
- return await this.runTask(key, async (task) => {
747
+ async wait(cacheKey, seconds) {
748
+ return await this.runTask(cacheKey, async (task) => {
557
749
  }, {
558
750
  name: "wait",
559
751
  icon: "clock",
@@ -567,9 +759,15 @@ var IO = class {
567
759
  }
568
760
  });
569
761
  }
570
- async backgroundFetch(key, url, requestInit, retry2) {
762
+ async createStatus(cacheKey, initialStatus) {
763
+ const id = typeof cacheKey === "string" ? cacheKey : cacheKey.join("-");
764
+ const status = new TriggerStatus(id, this);
765
+ await status.update(cacheKey, initialStatus);
766
+ return status;
767
+ }
768
+ async backgroundFetch(cacheKey, url, requestInit, retry2) {
571
769
  const urlObject = new URL(url);
572
- return await this.runTask(key, async (task) => {
770
+ return await this.runTask(cacheKey, async (task) => {
573
771
  return task.output;
574
772
  }, {
575
773
  name: `fetch ${urlObject.hostname}${urlObject.pathname}`,
@@ -598,8 +796,8 @@ var IO = class {
598
796
  ]
599
797
  });
600
798
  }
601
- async sendEvent(key, event, options) {
602
- return await this.runTask(key, async (task) => {
799
+ async sendEvent(cacheKey, event, options) {
800
+ return await this.runTask(cacheKey, async (task) => {
603
801
  return await this._triggerClient.sendEvent(event, options);
604
802
  }, {
605
803
  name: "sendEvent",
@@ -621,8 +819,8 @@ var IO = class {
621
819
  ]
622
820
  });
623
821
  }
624
- async getEvent(key, id) {
625
- return await this.runTask(key, async (task) => {
822
+ async getEvent(cacheKey, id) {
823
+ return await this.runTask(cacheKey, async (task) => {
626
824
  return await this._triggerClient.getEvent(id);
627
825
  }, {
628
826
  name: "getEvent",
@@ -637,8 +835,8 @@ var IO = class {
637
835
  ]
638
836
  });
639
837
  }
640
- async cancelEvent(key, eventId) {
641
- return await this.runTask(key, async (task) => {
838
+ async cancelEvent(cacheKey, eventId) {
839
+ return await this.runTask(cacheKey, async (task) => {
642
840
  return await this._triggerClient.cancelEvent(eventId);
643
841
  }, {
644
842
  name: "cancelEvent",
@@ -653,8 +851,8 @@ var IO = class {
653
851
  ]
654
852
  });
655
853
  }
656
- async updateSource(key, options) {
657
- return this.runTask(key, async (task) => {
854
+ async updateSource(cacheKey, options) {
855
+ return this.runTask(cacheKey, async (task) => {
658
856
  return await this._apiClient.updateSource(this._triggerClient.id, options.key, options);
659
857
  }, {
660
858
  name: "Update Source",
@@ -673,8 +871,8 @@ var IO = class {
673
871
  }
674
872
  });
675
873
  }
676
- async registerInterval(key, dynamicSchedule, id, options) {
677
- return await this.runTask(key, async (task) => {
874
+ async registerInterval(cacheKey, dynamicSchedule, id, options) {
875
+ return await this.runTask(cacheKey, async (task) => {
678
876
  return dynamicSchedule.register(id, {
679
877
  type: "interval",
680
878
  options
@@ -698,8 +896,8 @@ var IO = class {
698
896
  params: options
699
897
  });
700
898
  }
701
- async unregisterInterval(key, dynamicSchedule, id) {
702
- return await this.runTask(key, async (task) => {
899
+ async unregisterInterval(cacheKey, dynamicSchedule, id) {
900
+ return await this.runTask(cacheKey, async (task) => {
703
901
  return dynamicSchedule.unregister(id);
704
902
  }, {
705
903
  name: "unregister-interval",
@@ -715,8 +913,8 @@ var IO = class {
715
913
  ]
716
914
  });
717
915
  }
718
- async registerCron(key, dynamicSchedule, id, options) {
719
- return await this.runTask(key, async (task) => {
916
+ async registerCron(cacheKey, dynamicSchedule, id, options) {
917
+ return await this.runTask(cacheKey, async (task) => {
720
918
  return dynamicSchedule.register(id, {
721
919
  type: "cron",
722
920
  options
@@ -740,8 +938,8 @@ var IO = class {
740
938
  params: options
741
939
  });
742
940
  }
743
- async unregisterCron(key, dynamicSchedule, id) {
744
- return await this.runTask(key, async (task) => {
941
+ async unregisterCron(cacheKey, dynamicSchedule, id) {
942
+ return await this.runTask(cacheKey, async (task) => {
745
943
  return dynamicSchedule.unregister(id);
746
944
  }, {
747
945
  name: "unregister-cron",
@@ -757,8 +955,8 @@ var IO = class {
757
955
  ]
758
956
  });
759
957
  }
760
- async registerTrigger(key, trigger, id, params) {
761
- return await this.runTask(key, async (task) => {
958
+ async registerTrigger(cacheKey, trigger, id, params) {
959
+ return await this.runTask(cacheKey, async (task) => {
762
960
  const registration = await this.runTask("register-source", async (subtask1) => {
763
961
  return trigger.register(id, params);
764
962
  }, {
@@ -783,45 +981,77 @@ var IO = class {
783
981
  params
784
982
  });
785
983
  }
786
- async getAuth(key, clientId) {
984
+ async getAuth(cacheKey, clientId) {
787
985
  if (!clientId) {
788
986
  return;
789
987
  }
790
- return this.runTask(key, async (task) => {
988
+ return this.runTask(cacheKey, async (task) => {
791
989
  return await this._triggerClient.getAuth(clientId);
792
990
  }, {
793
991
  name: "get-auth"
794
992
  });
795
993
  }
796
- async runTask(key, callback, options, onError) {
994
+ async runTask(cacheKey, callback, options, onError) {
995
+ __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "start_task", 500);
797
996
  const parentId = this._taskStorage.getStore()?.taskId;
798
997
  if (parentId) {
799
998
  this._logger.debug("Using parent task", {
800
999
  parentId,
801
- key,
1000
+ cacheKey,
802
1001
  options
803
1002
  });
804
1003
  }
805
1004
  const idempotencyKey = await generateIdempotencyKey([
806
1005
  this._id,
807
1006
  parentId ?? "",
808
- key
1007
+ cacheKey
809
1008
  ].flat());
810
1009
  const cachedTask = this._cachedTasks.get(idempotencyKey);
811
1010
  if (cachedTask && cachedTask.status === "COMPLETED") {
812
1011
  this._logger.debug("Using completed cached task", {
813
- idempotencyKey,
814
- cachedTask
1012
+ idempotencyKey
815
1013
  });
1014
+ this._stats.cachedTaskHits++;
816
1015
  return cachedTask.output;
817
1016
  }
818
- const task = await this._apiClient.runTask(this._id, {
1017
+ if (options?.noop && this._noopTasksRawData) {
1018
+ const exists = await __privateMethod(this, _testNoopTaskBloomFilter, testNoopTaskBloomFilter_fn).call(this, idempotencyKey);
1019
+ if (exists) {
1020
+ this._logger.debug("task idempotency key exists in noopTasksBloomFilter", {
1021
+ idempotencyKey
1022
+ });
1023
+ this._stats.noopCachedTaskHits++;
1024
+ return {};
1025
+ }
1026
+ }
1027
+ const response = await this._apiClient.runTask(this._id, {
819
1028
  idempotencyKey,
820
- displayKey: typeof key === "string" ? key : void 0,
1029
+ displayKey: typeof cacheKey === "string" ? cacheKey : void 0,
821
1030
  noop: false,
822
1031
  ...options ?? {},
823
1032
  parentId
1033
+ }, {
1034
+ cachedTasksCursor: this._cachedTasksCursor
824
1035
  });
1036
+ const task = response.version === import_core3.API_VERSIONS.LAZY_LOADED_CACHED_TASKS ? response.body.task : response.body;
1037
+ if (task.forceYield) {
1038
+ this._logger.debug("Forcing yield after run task", {
1039
+ idempotencyKey
1040
+ });
1041
+ __privateMethod(this, _forceYield, forceYield_fn).call(this, "after_run_task");
1042
+ }
1043
+ if (response.version === import_core3.API_VERSIONS.LAZY_LOADED_CACHED_TASKS) {
1044
+ this._cachedTasksCursor = response.body.cachedTasks?.cursor;
1045
+ for (const cachedTask2 of response.body.cachedTasks?.tasks ?? []) {
1046
+ if (!this._cachedTasks.has(cachedTask2.idempotencyKey)) {
1047
+ this._cachedTasks.set(cachedTask2.idempotencyKey, cachedTask2);
1048
+ this._logger.debug("Injecting lazy loaded task into task cache", {
1049
+ idempotencyKey: cachedTask2.idempotencyKey
1050
+ });
1051
+ this._stats.lazyLoadedCachedTasks++;
1052
+ }
1053
+ }
1054
+ }
825
1055
  if (task.status === "CANCELED") {
826
1056
  this._logger.debug("Task canceled", {
827
1057
  idempotencyKey,
@@ -830,11 +1060,18 @@ var IO = class {
830
1060
  throw new CanceledWithTaskError(task);
831
1061
  }
832
1062
  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);
1063
+ if (task.noop) {
1064
+ this._logger.debug("Noop Task completed", {
1065
+ idempotencyKey
1066
+ });
1067
+ await __privateMethod(this, _addNoopTaskBloomFilter, addNoopTaskBloomFilter_fn).call(this, task.idempotencyKey);
1068
+ } else {
1069
+ this._logger.debug("Cache miss", {
1070
+ idempotencyKey
1071
+ });
1072
+ this._stats.cachedTaskMisses++;
1073
+ __privateMethod(this, _addToCachedTasks, addToCachedTasks_fn).call(this, task);
1074
+ }
838
1075
  return task.output;
839
1076
  }
840
1077
  if (task.status === "ERRORED") {
@@ -842,42 +1079,46 @@ var IO = class {
842
1079
  idempotencyKey,
843
1080
  task
844
1081
  });
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);
1082
+ throw new Error(task.error ?? task?.output ? JSON.stringify(task.output) : "Task errored");
860
1083
  }
1084
+ __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "before_execute_task", 1500);
861
1085
  const executeTask = /* @__PURE__ */ __name(async () => {
862
1086
  try {
863
1087
  const result = await callback(task, this);
1088
+ if (task.status === "WAITING" && task.callbackUrl) {
1089
+ this._logger.debug("Waiting for remote callback", {
1090
+ idempotencyKey,
1091
+ task
1092
+ });
1093
+ return {};
1094
+ }
864
1095
  const output = import_core3.SerializableJsonSchema.parse(result);
865
1096
  this._logger.debug("Completing using output", {
866
1097
  idempotencyKey,
867
1098
  task
868
1099
  });
1100
+ __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "before_complete_task", 500, task, output);
869
1101
  const completedTask = await this._apiClient.completeTask(this._id, task.id, {
870
1102
  output: output ?? void 0,
871
1103
  properties: task.outputProperties ?? void 0
872
1104
  });
1105
+ if (completedTask.forceYield) {
1106
+ this._logger.debug("Forcing yield after task completed", {
1107
+ idempotencyKey
1108
+ });
1109
+ __privateMethod(this, _forceYield, forceYield_fn).call(this, "after_complete_task");
1110
+ }
1111
+ this._stats.executedTasks++;
873
1112
  if (completedTask.status === "CANCELED") {
874
1113
  throw new CanceledWithTaskError(completedTask);
875
1114
  }
1115
+ __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "after_complete_task", 500);
876
1116
  return output;
877
1117
  } catch (error) {
878
1118
  if (isTriggerError(error)) {
879
1119
  throw error;
880
1120
  }
1121
+ let skipRetrying = false;
881
1122
  if (onError) {
882
1123
  try {
883
1124
  const onErrorResult = onError(error, task, this);
@@ -885,10 +1126,13 @@ var IO = class {
885
1126
  if (onErrorResult instanceof Error) {
886
1127
  error = onErrorResult;
887
1128
  } 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);
1129
+ skipRetrying = !!onErrorResult.skipRetrying;
1130
+ if (onErrorResult.retryAt && !skipRetrying) {
1131
+ const parsedError2 = import_core3.ErrorWithStackSchema.safeParse(onErrorResult.error);
1132
+ throw new RetryWithTaskError(parsedError2.success ? parsedError2.data : {
1133
+ message: "Unknown error"
1134
+ }, task, onErrorResult.retryAt);
1135
+ }
892
1136
  }
893
1137
  }
894
1138
  } catch (innerError) {
@@ -899,7 +1143,7 @@ var IO = class {
899
1143
  }
900
1144
  }
901
1145
  const parsedError = import_core3.ErrorWithStackSchema.safeParse(error);
902
- if (options?.retry) {
1146
+ if (options?.retry && !skipRetrying) {
903
1147
  const retryAt = (0, import_core2.calculateRetryAt)(options.retry, task.attempts - 1);
904
1148
  if (retryAt) {
905
1149
  throw new RetryWithTaskError(parsedError.success ? parsedError.data : {
@@ -912,20 +1156,50 @@ var IO = class {
912
1156
  error: parsedError.data
913
1157
  });
914
1158
  } else {
1159
+ const message = typeof error === "string" ? error : JSON.stringify(error);
915
1160
  await this._apiClient.failTask(this._id, task.id, {
916
1161
  error: {
917
- message: JSON.stringify(error),
918
- name: "Unknown Error"
1162
+ name: "Unknown error",
1163
+ message
919
1164
  }
920
1165
  });
921
1166
  }
922
1167
  throw error;
923
1168
  }
924
1169
  }, "executeTask");
1170
+ if (task.status === "WAITING") {
1171
+ this._logger.debug("Task waiting", {
1172
+ idempotencyKey,
1173
+ task
1174
+ });
1175
+ if (task.callbackUrl) {
1176
+ await this._taskStorage.run({
1177
+ taskId: task.id
1178
+ }, executeTask);
1179
+ }
1180
+ throw new ResumeWithTaskError(task);
1181
+ }
1182
+ if (task.status === "RUNNING" && typeof task.operation === "string") {
1183
+ this._logger.debug("Task running operation", {
1184
+ idempotencyKey,
1185
+ task
1186
+ });
1187
+ throw new ResumeWithTaskError(task);
1188
+ }
925
1189
  return this._taskStorage.run({
926
1190
  taskId: task.id
927
1191
  }, executeTask);
928
1192
  }
1193
+ yield(cacheKey) {
1194
+ if (!(0, import_core3.supportsFeature)("yieldExecution", this._serverVersion)) {
1195
+ 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.");
1196
+ return;
1197
+ }
1198
+ if (this._yieldedExecutions.includes(cacheKey)) {
1199
+ return;
1200
+ }
1201
+ throw new YieldExecutionError(cacheKey);
1202
+ }
929
1203
  async try(tryCallback, catchCallback) {
930
1204
  try {
931
1205
  return await tryCallback();
@@ -942,6 +1216,59 @@ _addToCachedTasks = new WeakSet();
942
1216
  addToCachedTasks_fn = /* @__PURE__ */ __name(function(task) {
943
1217
  this._cachedTasks.set(task.idempotencyKey, task);
944
1218
  }, "#addToCachedTasks");
1219
+ _detectAutoYield = new WeakSet();
1220
+ detectAutoYield_fn = /* @__PURE__ */ __name(function(location, threshold = 1500, task1, output) {
1221
+ const timeRemaining = __privateMethod(this, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn).call(this);
1222
+ if (timeRemaining && timeRemaining < threshold) {
1223
+ if (task1) {
1224
+ throw new AutoYieldWithCompletedTaskExecutionError(task1.id, task1.outputProperties ?? [], output, {
1225
+ location,
1226
+ timeRemaining,
1227
+ timeElapsed: __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this)
1228
+ });
1229
+ } else {
1230
+ throw new AutoYieldExecutionError(location, timeRemaining, __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this));
1231
+ }
1232
+ }
1233
+ }, "#detectAutoYield");
1234
+ _forceYield = new WeakSet();
1235
+ forceYield_fn = /* @__PURE__ */ __name(function(location1) {
1236
+ const timeRemaining = __privateMethod(this, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn).call(this);
1237
+ if (timeRemaining) {
1238
+ throw new AutoYieldExecutionError(location1, timeRemaining, __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this));
1239
+ }
1240
+ }, "#forceYield");
1241
+ _getTimeElapsed = new WeakSet();
1242
+ getTimeElapsed_fn = /* @__PURE__ */ __name(function() {
1243
+ return performance.now() - this._timeOrigin;
1244
+ }, "#getTimeElapsed");
1245
+ _getRemainingTimeInMillis = new WeakSet();
1246
+ getRemainingTimeInMillis_fn = /* @__PURE__ */ __name(function() {
1247
+ if (this._executionTimeout) {
1248
+ return this._executionTimeout - (performance.now() - this._timeOrigin);
1249
+ }
1250
+ return void 0;
1251
+ }, "#getRemainingTimeInMillis");
1252
+ _testNoopTaskBloomFilter = new WeakSet();
1253
+ testNoopTaskBloomFilter_fn = /* @__PURE__ */ __name(async function(key) {
1254
+ if (!this.__noopTasksBloomFilter && this._noopTasksRawData) {
1255
+ this.__noopTasksBloomFilter = await import_core3.BloomFilter.deserialize(this._noopTasksRawData, import_core3.BloomFilter.NOOP_TASK_SET_SIZE);
1256
+ }
1257
+ if (!this.__noopTasksBloomFilter) {
1258
+ return false;
1259
+ }
1260
+ return this.__noopTasksBloomFilter.test(key);
1261
+ }, "#testNoopTaskBloomFilter");
1262
+ _addNoopTaskBloomFilter = new WeakSet();
1263
+ addNoopTaskBloomFilter_fn = /* @__PURE__ */ __name(async function(key1) {
1264
+ if (!this.__noopTasksBloomFilter && this._noopTasksRawData) {
1265
+ this.__noopTasksBloomFilter = await import_core3.BloomFilter.deserialize(this._noopTasksRawData, import_core3.BloomFilter.NOOP_TASK_SET_SIZE);
1266
+ }
1267
+ if (!this.__noopTasksBloomFilter) {
1268
+ return;
1269
+ }
1270
+ return this.__noopTasksBloomFilter.add(key1);
1271
+ }, "#addNoopTaskBloomFilter");
945
1272
  async function generateIdempotencyKey(keyMaterial) {
946
1273
  const keys = keyMaterial.map((key2) => {
947
1274
  if (typeof key2 === "string") {
@@ -1025,117 +1352,385 @@ function createIOWithIntegrations(io, auths, integrations) {
1025
1352
  }
1026
1353
  __name(createIOWithIntegrations, "createIOWithIntegrations");
1027
1354
 
1028
- // src/triggers/eventTrigger.ts
1355
+ // src/utils/typedAsyncLocalStorage.ts
1356
+ var import_node_async_hooks2 = require("async_hooks");
1357
+ var TypedAsyncLocalStorage = class {
1358
+ constructor() {
1359
+ this.storage = new import_node_async_hooks2.AsyncLocalStorage();
1360
+ }
1361
+ runWith(context, fn) {
1362
+ return this.storage.run(context, fn);
1363
+ }
1364
+ getStore() {
1365
+ return this.storage.getStore();
1366
+ }
1367
+ };
1368
+ __name(TypedAsyncLocalStorage, "TypedAsyncLocalStorage");
1369
+
1370
+ // src/runLocalStorage.ts
1371
+ var runLocalStorage = new TypedAsyncLocalStorage();
1372
+
1373
+ // src/triggers/dynamic.ts
1029
1374
  var import_core4 = require("@trigger.dev/core");
1030
- var _options2;
1031
- var EventTrigger = class {
1032
- constructor(options) {
1375
+ var _client, _options2;
1376
+ var DynamicTrigger = class {
1377
+ constructor(client, options) {
1378
+ __privateAdd(this, _client, void 0);
1033
1379
  __privateAdd(this, _options2, void 0);
1380
+ __privateSet(this, _client, client);
1034
1381
  __privateSet(this, _options2, options);
1382
+ this.source = options.source;
1383
+ client.attachDynamicTrigger(this);
1035
1384
  }
1036
1385
  toJSON() {
1037
1386
  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
- }
1387
+ type: "dynamic",
1388
+ id: __privateGet(this, _options2).id
1045
1389
  };
1046
1390
  }
1391
+ get id() {
1392
+ return __privateGet(this, _options2).id;
1393
+ }
1047
1394
  get event() {
1048
1395
  return __privateGet(this, _options2).event;
1049
1396
  }
1397
+ registeredTriggerForParams(params, options = {}) {
1398
+ const key = slugifyId(this.source.key(params));
1399
+ return {
1400
+ rule: {
1401
+ event: this.event.name,
1402
+ source: this.event.source,
1403
+ payload: (0, import_core4.deepMergeFilters)(this.source.filter(params), this.event.filter ?? {}, options.filter ?? {})
1404
+ },
1405
+ source: {
1406
+ version: "2",
1407
+ key,
1408
+ channel: this.source.channel,
1409
+ params,
1410
+ options: {
1411
+ event: typeof this.event.name === "string" ? [
1412
+ this.event.name
1413
+ ] : this.event.name
1414
+ },
1415
+ integration: {
1416
+ id: this.source.integration.id,
1417
+ metadata: this.source.integration.metadata,
1418
+ authSource: this.source.integration.authSource
1419
+ }
1420
+ },
1421
+ accountId: options.accountId
1422
+ };
1423
+ }
1424
+ async register(key, params, options = {}) {
1425
+ const runStore = runLocalStorage.getStore();
1426
+ if (!runStore) {
1427
+ return __privateGet(this, _client).registerTrigger(this.id, key, this.registeredTriggerForParams(params, options));
1428
+ }
1429
+ const { io } = runStore;
1430
+ return await io.runTask([
1431
+ key,
1432
+ "register"
1433
+ ], async (task) => {
1434
+ return __privateGet(this, _client).registerTrigger(this.id, key, this.registeredTriggerForParams(params, options), task.idempotencyKey);
1435
+ }, {
1436
+ name: "Register Dynamic Trigger",
1437
+ properties: [
1438
+ {
1439
+ label: "Dynamic Trigger ID",
1440
+ text: this.id
1441
+ },
1442
+ {
1443
+ label: "ID",
1444
+ text: key
1445
+ }
1446
+ ],
1447
+ params
1448
+ });
1449
+ }
1050
1450
  attachToJob(triggerClient, job) {
1451
+ triggerClient.attachJobToDynamicTrigger(job, this);
1051
1452
  }
1052
1453
  get preprocessRuns() {
1053
- return false;
1454
+ return true;
1054
1455
  }
1055
1456
  };
1056
- __name(EventTrigger, "EventTrigger");
1457
+ __name(DynamicTrigger, "DynamicTrigger");
1458
+ _client = new WeakMap();
1057
1459
  _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
- }
1075
- });
1076
- }
1077
- __name(eventTrigger, "eventTrigger");
1078
1460
 
1079
- // src/backgroundTask.ts
1080
- var _validate2, validate_fn2;
1081
- var BackgroundTask = class {
1461
+ // src/triggers/eventTrigger.ts
1462
+ var import_core5 = require("@trigger.dev/core");
1463
+
1464
+ // src/utils/formatSchemaErrors.ts
1465
+ function formatSchemaErrors(errors) {
1466
+ return errors.map((error) => {
1467
+ const { path, message } = error;
1468
+ return {
1469
+ path: path.map(String),
1470
+ message
1471
+ };
1472
+ });
1473
+ }
1474
+ __name(formatSchemaErrors, "formatSchemaErrors");
1475
+
1476
+ // src/triggers/eventTrigger.ts
1477
+ var _options3;
1478
+ var EventTrigger = class {
1479
+ constructor(options) {
1480
+ __privateAdd(this, _options3, void 0);
1481
+ __privateSet(this, _options3, options);
1482
+ }
1483
+ toJSON() {
1484
+ return {
1485
+ type: "static",
1486
+ title: __privateGet(this, _options3).name ?? __privateGet(this, _options3).event.title,
1487
+ rule: {
1488
+ event: __privateGet(this, _options3).name ?? __privateGet(this, _options3).event.name,
1489
+ source: __privateGet(this, _options3).source ?? "trigger.dev",
1490
+ payload: (0, import_core5.deepMergeFilters)(__privateGet(this, _options3).filter ?? {}, __privateGet(this, _options3).event.filter ?? {})
1491
+ }
1492
+ };
1493
+ }
1494
+ get event() {
1495
+ return __privateGet(this, _options3).event;
1496
+ }
1497
+ attachToJob(triggerClient, job) {
1498
+ }
1499
+ get preprocessRuns() {
1500
+ return false;
1501
+ }
1502
+ };
1503
+ __name(EventTrigger, "EventTrigger");
1504
+ _options3 = new WeakMap();
1505
+ function eventTrigger(options) {
1506
+ return new EventTrigger({
1507
+ name: options.name,
1508
+ filter: options.filter,
1509
+ event: {
1510
+ name: options.name,
1511
+ title: "Event",
1512
+ source: options.source ?? "trigger.dev",
1513
+ icon: "custom-event",
1514
+ examples: options.examples,
1515
+ parsePayload: (rawPayload) => {
1516
+ if (options.schema) {
1517
+ const results = options.schema.safeParse(rawPayload);
1518
+ if (!results.success) {
1519
+ throw new ParsedPayloadSchemaError(formatSchemaErrors(results.error.issues));
1520
+ }
1521
+ return results.data;
1522
+ }
1523
+ return rawPayload;
1524
+ }
1525
+ }
1526
+ });
1527
+ }
1528
+ __name(eventTrigger, "eventTrigger");
1529
+
1530
+ // src/triggers/scheduled.ts
1531
+ var import_core6 = require("@trigger.dev/core");
1532
+ var import_cronstrue = __toESM(require("cronstrue"));
1533
+ var examples = [
1534
+ {
1535
+ id: "now",
1536
+ name: "Now",
1537
+ icon: "clock",
1538
+ payload: {
1539
+ ts: import_core6.currentDate.marker,
1540
+ lastTimestamp: import_core6.currentDate.marker
1541
+ }
1542
+ }
1543
+ ];
1544
+ var IntervalTrigger = class {
1545
+ constructor(options) {
1546
+ this.options = options;
1547
+ }
1548
+ get event() {
1549
+ return {
1550
+ name: "trigger.scheduled",
1551
+ title: "Schedule",
1552
+ source: "trigger.dev",
1553
+ icon: "schedule-interval",
1554
+ examples,
1555
+ parsePayload: import_core6.ScheduledPayloadSchema.parse,
1556
+ properties: [
1557
+ {
1558
+ label: "Interval",
1559
+ text: `${this.options.seconds}s`
1560
+ }
1561
+ ]
1562
+ };
1563
+ }
1564
+ attachToJob(triggerClient, job) {
1565
+ }
1566
+ get preprocessRuns() {
1567
+ return false;
1568
+ }
1569
+ toJSON() {
1570
+ return {
1571
+ type: "scheduled",
1572
+ schedule: {
1573
+ type: "interval",
1574
+ options: {
1575
+ seconds: this.options.seconds
1576
+ }
1577
+ }
1578
+ };
1579
+ }
1580
+ };
1581
+ __name(IntervalTrigger, "IntervalTrigger");
1582
+ function intervalTrigger(options) {
1583
+ return new IntervalTrigger(options);
1584
+ }
1585
+ __name(intervalTrigger, "intervalTrigger");
1586
+ var CronTrigger = class {
1587
+ constructor(options) {
1588
+ this.options = options;
1589
+ }
1590
+ get event() {
1591
+ const humanReadable = import_cronstrue.default.toString(this.options.cron, {
1592
+ throwExceptionOnParseError: false
1593
+ });
1594
+ return {
1595
+ name: "trigger.scheduled",
1596
+ title: "Cron Schedule",
1597
+ source: "trigger.dev",
1598
+ icon: "schedule-cron",
1599
+ examples,
1600
+ parsePayload: import_core6.ScheduledPayloadSchema.parse,
1601
+ properties: [
1602
+ {
1603
+ label: "cron",
1604
+ text: this.options.cron
1605
+ },
1606
+ {
1607
+ label: "Schedule",
1608
+ text: humanReadable
1609
+ }
1610
+ ]
1611
+ };
1612
+ }
1613
+ attachToJob(triggerClient, job) {
1614
+ }
1615
+ get preprocessRuns() {
1616
+ return false;
1617
+ }
1618
+ toJSON() {
1619
+ return {
1620
+ type: "scheduled",
1621
+ schedule: {
1622
+ type: "cron",
1623
+ options: {
1624
+ cron: this.options.cron
1625
+ }
1626
+ }
1627
+ };
1628
+ }
1629
+ };
1630
+ __name(CronTrigger, "CronTrigger");
1631
+ function cronTrigger(options) {
1632
+ return new CronTrigger(options);
1633
+ }
1634
+ __name(cronTrigger, "cronTrigger");
1635
+ var DynamicSchedule = class {
1082
1636
  constructor(client, options) {
1083
- __privateAdd(this, _validate2);
1084
1637
  this.client = client;
1085
1638
  this.options = options;
1086
- __privateMethod(this, _validate2, validate_fn2).call(this);
1087
- client.attachBackgroundTask(this);
1639
+ client.attachDynamicSchedule(this.options.id);
1088
1640
  }
1089
1641
  get id() {
1090
- return slugifyId(this.options.id);
1091
- }
1092
- get enabled() {
1093
- return typeof this.options.enabled === "boolean" ? this.options.enabled : true;
1642
+ return this.options.id;
1094
1643
  }
1095
- get name() {
1096
- return this.options.name;
1644
+ get event() {
1645
+ return {
1646
+ name: "trigger.scheduled",
1647
+ title: "Dynamic Schedule",
1648
+ source: "trigger.dev",
1649
+ icon: "schedule-dynamic",
1650
+ examples,
1651
+ parsePayload: import_core6.ScheduledPayloadSchema.parse
1652
+ };
1097
1653
  }
1098
- get schema() {
1099
- return this.options.schema;
1654
+ async register(key, metadata) {
1655
+ const runStore = runLocalStorage.getStore();
1656
+ if (!runStore) {
1657
+ return this.client.registerSchedule(this.id, key, metadata);
1658
+ }
1659
+ const { io } = runStore;
1660
+ return await io.runTask([
1661
+ key,
1662
+ "register"
1663
+ ], async (task) => {
1664
+ return this.client.registerSchedule(this.id, key, metadata);
1665
+ }, {
1666
+ name: "Register Schedule",
1667
+ icon: metadata.type === "cron" ? "schedule-cron" : "schedule-interval",
1668
+ properties: [
1669
+ {
1670
+ label: "Dynamic Schedule",
1671
+ text: this.id
1672
+ },
1673
+ {
1674
+ label: "Schedule ID",
1675
+ text: key
1676
+ }
1677
+ ],
1678
+ params: metadata
1679
+ });
1100
1680
  }
1101
- get version() {
1102
- return this.options.version;
1681
+ async unregister(key) {
1682
+ const runStore = runLocalStorage.getStore();
1683
+ if (!runStore) {
1684
+ return this.client.unregisterSchedule(this.id, key);
1685
+ }
1686
+ const { io } = runStore;
1687
+ return await io.runTask([
1688
+ key,
1689
+ "unregister"
1690
+ ], async (task) => {
1691
+ return this.client.unregisterSchedule(this.id, key);
1692
+ }, {
1693
+ name: "Unregister Schedule",
1694
+ icon: "schedule",
1695
+ properties: [
1696
+ {
1697
+ label: "Dynamic Schedule",
1698
+ text: this.id
1699
+ },
1700
+ {
1701
+ label: "Schedule ID",
1702
+ text: key
1703
+ }
1704
+ ]
1705
+ });
1103
1706
  }
1104
- get logLevel() {
1105
- return this.options.logLevel;
1707
+ attachToJob(triggerClient, job) {
1708
+ triggerClient.attachDynamicScheduleToJob(this.options.id, job);
1106
1709
  }
1107
- async invoke(key, payload) {
1710
+ get preprocessRuns() {
1711
+ return false;
1108
1712
  }
1109
1713
  toJSON() {
1110
1714
  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 ?? {}
1715
+ type: "dynamic",
1716
+ id: this.options.id
1119
1717
  };
1120
1718
  }
1121
1719
  };
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.`);
1127
- }
1128
- }, "#validate");
1720
+ __name(DynamicSchedule, "DynamicSchedule");
1721
+
1722
+ // package.json
1723
+ var version = "0.0.0-buffer-import-20231031121649";
1129
1724
 
1130
1725
  // src/triggerClient.ts
1131
1726
  var registerSourceEvent = {
1132
- name: import_core5.REGISTER_SOURCE_EVENT_V2,
1727
+ name: import_core7.REGISTER_SOURCE_EVENT_V2,
1133
1728
  title: "Register Source",
1134
1729
  source: "internal",
1135
1730
  icon: "register-source",
1136
- parsePayload: import_core5.RegisterSourceEventSchemaV2.parse
1731
+ parsePayload: import_core7.RegisterSourceEventSchemaV2.parse
1137
1732
  };
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;
1733
+ 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
1734
  var TriggerClient = class {
1140
1735
  constructor(options) {
1141
1736
  __privateAdd(this, _preprocessRun);
@@ -1143,28 +1738,40 @@ var TriggerClient = class {
1143
1738
  __privateAdd(this, _createRunContext);
1144
1739
  __privateAdd(this, _createPreprocessRunContext);
1145
1740
  __privateAdd(this, _handleHttpSourceRequest);
1146
- __privateAdd(this, _options3, void 0);
1741
+ __privateAdd(this, _resolveConnections);
1742
+ __privateAdd(this, _resolveConnection);
1743
+ __privateAdd(this, _buildJobsIndex);
1744
+ __privateAdd(this, _buildJobIndex);
1745
+ __privateAdd(this, _buildJobIntegrations);
1746
+ __privateAdd(this, _buildJobIntegration);
1747
+ __privateAdd(this, _logIOStats);
1748
+ __privateAdd(this, _standardResponseHeaders);
1749
+ __privateAdd(this, _options4, void 0);
1147
1750
  __privateAdd(this, _registeredJobs, {});
1148
1751
  __privateAdd(this, _registeredSources, {});
1149
- __privateAdd(this, _registeredBackgroundTasks, {});
1150
1752
  __privateAdd(this, _registeredHttpSourceHandlers, {});
1151
1753
  __privateAdd(this, _registeredDynamicTriggers, {});
1152
1754
  __privateAdd(this, _jobMetadataByDynamicTriggers, {});
1153
1755
  __privateAdd(this, _registeredSchedules, {});
1154
- __privateAdd(this, _client, void 0);
1756
+ __privateAdd(this, _authResolvers, {});
1757
+ __privateAdd(this, _client2, void 0);
1155
1758
  __privateAdd(this, _internalLogger, void 0);
1156
1759
  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"));
1760
+ __privateSet(this, _options4, options);
1761
+ __privateSet(this, _client2, new ApiClient(__privateGet(this, _options4)));
1762
+ __privateSet(this, _internalLogger, new import_core7.Logger("trigger.dev", __privateGet(this, _options4).verbose ? "debug" : "log", [
1763
+ "output",
1764
+ "noopTasksSet"
1765
+ ]));
1160
1766
  }
1161
- async handleRequest(request) {
1767
+ async handleRequest(request, timeOrigin = performance.now()) {
1162
1768
  __privateGet(this, _internalLogger).debug("handling request", {
1163
1769
  url: request.url,
1164
1770
  headers: Object.fromEntries(request.headers.entries()),
1165
1771
  method: request.method
1166
1772
  });
1167
1773
  const apiKey = request.headers.get("x-trigger-api-key");
1774
+ const triggerVersion = request.headers.get("x-trigger-version");
1168
1775
  const authorization = this.authorized(apiKey);
1169
1776
  switch (authorization) {
1170
1777
  case "authorized": {
@@ -1175,7 +1782,8 @@ var TriggerClient = class {
1175
1782
  status: 401,
1176
1783
  body: {
1177
1784
  message: "Unauthorized: client missing apiKey"
1178
- }
1785
+ },
1786
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1179
1787
  };
1180
1788
  }
1181
1789
  case "missing-header": {
@@ -1183,7 +1791,8 @@ var TriggerClient = class {
1183
1791
  status: 401,
1184
1792
  body: {
1185
1793
  message: "Unauthorized: missing x-trigger-api-key header"
1186
- }
1794
+ },
1795
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1187
1796
  };
1188
1797
  }
1189
1798
  case "unauthorized": {
@@ -1191,7 +1800,8 @@ var TriggerClient = class {
1191
1800
  status: 401,
1192
1801
  body: {
1193
1802
  message: `Forbidden: client apiKey mismatch: Make sure you are using the correct API Key for your environment`
1194
- }
1803
+ },
1804
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1195
1805
  };
1196
1806
  }
1197
1807
  }
@@ -1200,7 +1810,8 @@ var TriggerClient = class {
1200
1810
  status: 405,
1201
1811
  body: {
1202
1812
  message: "Method not allowed (only POST is allowed)"
1203
- }
1813
+ },
1814
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1204
1815
  };
1205
1816
  }
1206
1817
  const action = request.headers.get("x-trigger-action");
@@ -1209,7 +1820,8 @@ var TriggerClient = class {
1209
1820
  status: 400,
1210
1821
  body: {
1211
1822
  message: "Missing x-trigger-action header"
1212
- }
1823
+ },
1824
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1213
1825
  };
1214
1826
  }
1215
1827
  switch (action) {
@@ -1221,7 +1833,8 @@ var TriggerClient = class {
1221
1833
  body: {
1222
1834
  ok: false,
1223
1835
  error: "Missing endpoint ID"
1224
- }
1836
+ },
1837
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1225
1838
  };
1226
1839
  }
1227
1840
  if (this.id !== endpointId) {
@@ -1230,36 +1843,21 @@ var TriggerClient = class {
1230
1843
  body: {
1231
1844
  ok: false,
1232
1845
  error: `Endpoint ID mismatch error. Expected ${this.id}, got ${endpointId}`
1233
- }
1846
+ },
1847
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1234
1848
  };
1235
1849
  }
1236
1850
  return {
1237
1851
  status: 200,
1238
1852
  body: {
1239
1853
  ok: true
1240
- }
1854
+ },
1855
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1241
1856
  };
1242
1857
  }
1243
1858
  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
1859
  const body = {
1261
- jobs: Object.values(__privateGet(this, _registeredJobs)).map((job) => job.toJSON()),
1262
- backgroundTasks: Object.values(__privateGet(this, _registeredBackgroundTasks)).map((task) => task.toJSON()),
1860
+ jobs: __privateMethod(this, _buildJobsIndex, buildJobsIndex_fn).call(this),
1263
1861
  sources: Object.values(__privateGet(this, _registeredSources)),
1264
1862
  dynamicTriggers: Object.values(__privateGet(this, _registeredDynamicTriggers)).map((trigger) => ({
1265
1863
  id: trigger.id,
@@ -1276,12 +1874,13 @@ var TriggerClient = class {
1276
1874
  };
1277
1875
  return {
1278
1876
  status: 200,
1279
- body
1877
+ body,
1878
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1280
1879
  };
1281
1880
  }
1282
1881
  case "INITIALIZE_TRIGGER": {
1283
1882
  const json = await request.json();
1284
- const body = import_core5.InitializeTriggerBodySchema.safeParse(json);
1883
+ const body = import_core7.InitializeTriggerBodySchema.safeParse(json);
1285
1884
  if (!body.success) {
1286
1885
  return {
1287
1886
  status: 400,
@@ -1301,12 +1900,13 @@ var TriggerClient = class {
1301
1900
  }
1302
1901
  return {
1303
1902
  status: 200,
1304
- body: dynamicTrigger.registeredTriggerForParams(body.data.params)
1903
+ body: dynamicTrigger.registeredTriggerForParams(body.data.params),
1904
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1305
1905
  };
1306
1906
  }
1307
1907
  case "EXECUTE_JOB": {
1308
1908
  const json = await request.json();
1309
- const execution = import_core5.RunJobBodySchema.safeParse(json);
1909
+ const execution = import_core7.RunJobBodySchema.safeParse(json);
1310
1910
  if (!execution.success) {
1311
1911
  return {
1312
1912
  status: 400,
@@ -1324,15 +1924,16 @@ var TriggerClient = class {
1324
1924
  }
1325
1925
  };
1326
1926
  }
1327
- const results = await __privateMethod(this, _executeJob, executeJob_fn).call(this, execution.data, job);
1927
+ const results = await __privateMethod(this, _executeJob, executeJob_fn).call(this, execution.data, job, timeOrigin, triggerVersion);
1328
1928
  return {
1329
1929
  status: 200,
1330
- body: results
1930
+ body: results,
1931
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1331
1932
  };
1332
1933
  }
1333
1934
  case "PREPROCESS_RUN": {
1334
1935
  const json = await request.json();
1335
- const body = import_core5.PreprocessRunBodySchema.safeParse(json);
1936
+ const body = import_core7.PreprocessRunBodySchema.safeParse(json);
1336
1937
  if (!body.success) {
1337
1938
  return {
1338
1939
  status: 400,
@@ -1356,11 +1957,12 @@ var TriggerClient = class {
1356
1957
  body: {
1357
1958
  abort: results.abort,
1358
1959
  properties: results.properties
1359
- }
1960
+ },
1961
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1360
1962
  };
1361
1963
  }
1362
1964
  case "DELIVER_HTTP_SOURCE_REQUEST": {
1363
- const headers = import_core5.HttpSourceRequestHeadersSchema.safeParse(Object.fromEntries(request.headers.entries()));
1965
+ const headers = import_core7.HttpSourceRequestHeadersSchema.safeParse(Object.fromEntries(request.headers.entries()));
1364
1966
  if (!headers.success) {
1365
1967
  return {
1366
1968
  status: 400,
@@ -1405,7 +2007,8 @@ var TriggerClient = class {
1405
2007
  events,
1406
2008
  response,
1407
2009
  metadata
1408
- }
2010
+ },
2011
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1409
2012
  };
1410
2013
  }
1411
2014
  case "VALIDATE": {
@@ -1414,7 +2017,20 @@ var TriggerClient = class {
1414
2017
  body: {
1415
2018
  ok: true,
1416
2019
  endpointId: this.id
1417
- }
2020
+ },
2021
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
2022
+ };
2023
+ }
2024
+ case "PROBE_EXECUTION_TIMEOUT": {
2025
+ const json = await request.json();
2026
+ const timeout = json?.timeout ?? 15 * 60 * 1e3;
2027
+ await new Promise((resolve) => setTimeout(resolve, timeout));
2028
+ return {
2029
+ status: 200,
2030
+ body: {
2031
+ ok: true
2032
+ },
2033
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1418
2034
  };
1419
2035
  }
1420
2036
  }
@@ -1422,19 +2038,30 @@ var TriggerClient = class {
1422
2038
  status: 405,
1423
2039
  body: {
1424
2040
  message: "Method not allowed"
1425
- }
2041
+ },
2042
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1426
2043
  };
1427
2044
  }
2045
+ defineJob(options) {
2046
+ return new Job(this, options);
2047
+ }
2048
+ defineAuthResolver(integration, resolver) {
2049
+ __privateGet(this, _authResolvers)[integration.id] = resolver;
2050
+ return this;
2051
+ }
2052
+ defineDynamicSchedule(options) {
2053
+ return new DynamicSchedule(this, options);
2054
+ }
2055
+ defineDynamicTrigger(options) {
2056
+ return new DynamicTrigger(this, options);
2057
+ }
1428
2058
  attach(job) {
1429
2059
  __privateGet(this, _registeredJobs)[job.id] = job;
1430
2060
  job.trigger.attachToJob(this, job);
1431
2061
  }
1432
- attachBackgroundTask(task) {
1433
- __privateGet(this, _registeredBackgroundTasks)[task.id] = task;
1434
- }
1435
2062
  attachDynamicTrigger(trigger) {
1436
2063
  __privateGet(this, _registeredDynamicTriggers)[trigger.id] = trigger;
1437
- new Job(this, {
2064
+ this.defineJob({
1438
2065
  id: dynamicTriggerRegisterSourceJobId(trigger.id),
1439
2066
  name: `Register dynamic trigger ${trigger.id}`,
1440
2067
  version: trigger.source.version,
@@ -1530,7 +2157,11 @@ var TriggerClient = class {
1530
2157
  __internal: true
1531
2158
  });
1532
2159
  }
1533
- attachDynamicSchedule(key, job) {
2160
+ attachDynamicSchedule(key) {
2161
+ const jobs = __privateGet(this, _registeredSchedules)[key] ?? [];
2162
+ __privateGet(this, _registeredSchedules)[key] = jobs;
2163
+ }
2164
+ attachDynamicScheduleToJob(key, job) {
1534
2165
  const jobs = __privateGet(this, _registeredSchedules)[key] ?? [];
1535
2166
  jobs.push({
1536
2167
  id: job.id,
@@ -1538,63 +2169,69 @@ var TriggerClient = class {
1538
2169
  });
1539
2170
  __privateGet(this, _registeredSchedules)[key] = jobs;
1540
2171
  }
1541
- async registerTrigger(id, key, options) {
1542
- return __privateGet(this, _client).registerTrigger(this.id, id, key, options);
2172
+ async registerTrigger(id, key, options, idempotencyKey) {
2173
+ return __privateGet(this, _client2).registerTrigger(this.id, id, key, options, idempotencyKey);
1543
2174
  }
1544
2175
  async getAuth(id) {
1545
- return __privateGet(this, _client).getAuth(this.id, id);
2176
+ return __privateGet(this, _client2).getAuth(this.id, id);
1546
2177
  }
1547
2178
  async sendEvent(event, options) {
1548
- return __privateGet(this, _client).sendEvent(event, options);
2179
+ return __privateGet(this, _client2).sendEvent(event, options);
1549
2180
  }
1550
2181
  async cancelEvent(eventId) {
1551
- return __privateGet(this, _client).cancelEvent(eventId);
2182
+ return __privateGet(this, _client2).cancelEvent(eventId);
2183
+ }
2184
+ async cancelRunsForEvent(eventId) {
2185
+ return __privateGet(this, _client2).cancelRunsForEvent(eventId);
2186
+ }
2187
+ async updateStatus(runId, id, status) {
2188
+ return __privateGet(this, _client2).updateStatus(runId, id, status);
1552
2189
  }
1553
2190
  async registerSchedule(id, key, schedule) {
1554
- return __privateGet(this, _client).registerSchedule(this.id, id, key, schedule);
2191
+ return __privateGet(this, _client2).registerSchedule(this.id, id, key, schedule);
1555
2192
  }
1556
2193
  async unregisterSchedule(id, key) {
1557
- return __privateGet(this, _client).unregisterSchedule(this.id, id, key);
2194
+ return __privateGet(this, _client2).unregisterSchedule(this.id, id, key);
1558
2195
  }
1559
2196
  async getEvent(eventId) {
1560
- return __privateGet(this, _client).getEvent(eventId);
2197
+ return __privateGet(this, _client2).getEvent(eventId);
1561
2198
  }
1562
2199
  async getRun(runId, options) {
1563
- return __privateGet(this, _client).getRun(runId, options);
2200
+ return __privateGet(this, _client2).getRun(runId, options);
2201
+ }
2202
+ async cancelRun(runId) {
2203
+ return __privateGet(this, _client2).cancelRun(runId);
1564
2204
  }
1565
2205
  async getRuns(jobSlug, options) {
1566
- return __privateGet(this, _client).getRuns(jobSlug, options);
2206
+ return __privateGet(this, _client2).getRuns(jobSlug, options);
2207
+ }
2208
+ async getRunStatuses(runId) {
2209
+ return __privateGet(this, _client2).getRunStatuses(runId);
1567
2210
  }
1568
2211
  authorized(apiKey) {
1569
2212
  if (typeof apiKey !== "string") {
1570
2213
  return "missing-header";
1571
2214
  }
1572
- const localApiKey = __privateGet(this, _options3).apiKey ?? process.env.TRIGGER_API_KEY;
2215
+ const localApiKey = __privateGet(this, _options4).apiKey ?? process.env.TRIGGER_API_KEY;
1573
2216
  if (!localApiKey) {
1574
2217
  return "missing-client";
1575
2218
  }
1576
2219
  return apiKey === localApiKey ? "authorized" : "unauthorized";
1577
2220
  }
1578
2221
  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);
2222
+ return __privateGet(this, _options4).apiKey ?? process.env.TRIGGER_API_KEY;
1586
2223
  }
1587
2224
  };
1588
2225
  __name(TriggerClient, "TriggerClient");
1589
- _options3 = new WeakMap();
2226
+ _options4 = new WeakMap();
1590
2227
  _registeredJobs = new WeakMap();
1591
2228
  _registeredSources = new WeakMap();
1592
- _registeredBackgroundTasks = new WeakMap();
1593
2229
  _registeredHttpSourceHandlers = new WeakMap();
1594
2230
  _registeredDynamicTriggers = new WeakMap();
1595
2231
  _jobMetadataByDynamicTriggers = new WeakMap();
1596
2232
  _registeredSchedules = new WeakMap();
1597
- _client = new WeakMap();
2233
+ _authResolvers = new WeakMap();
2234
+ _client2 = new WeakMap();
1598
2235
  _internalLogger = new WeakMap();
1599
2236
  _preprocessRun = new WeakSet();
1600
2237
  preprocessRun_fn = /* @__PURE__ */ __name(async function(body, job) {
@@ -1607,30 +2244,89 @@ preprocessRun_fn = /* @__PURE__ */ __name(async function(body, job) {
1607
2244
  };
1608
2245
  }, "#preprocessRun");
1609
2246
  _executeJob = new WeakSet();
1610
- executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1) {
2247
+ executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1, timeOrigin, triggerVersion) {
1611
2248
  __privateGet(this, _internalLogger).debug("executing job", {
1612
2249
  execution: body1,
1613
- job: job1.toJSON()
2250
+ job: job1.id,
2251
+ version: job1.version,
2252
+ triggerVersion
1614
2253
  });
1615
2254
  const context = __privateMethod(this, _createRunContext, createRunContext_fn).call(this, body1);
1616
2255
  const io = new IO({
1617
2256
  id: body1.run.id,
1618
2257
  cachedTasks: body1.tasks,
1619
- apiClient: __privateGet(this, _client),
2258
+ cachedTasksCursor: body1.cachedTaskCursor,
2259
+ yieldedExecutions: body1.yieldedExecutions ?? [],
2260
+ noopTasksSet: body1.noopTasksSet,
2261
+ apiClient: __privateGet(this, _client2),
1620
2262
  logger: __privateGet(this, _internalLogger),
1621
2263
  client: this,
1622
2264
  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
2265
+ jobLogLevel: job1.logLevel ?? __privateGet(this, _options4).logLevel ?? "info",
2266
+ jobLogger: __privateGet(this, _options4).ioLogLocalEnabled ? new import_core7.Logger(job1.id, job1.logLevel ?? __privateGet(this, _options4).logLevel ?? "info") : void 0,
2267
+ serverVersion: triggerVersion,
2268
+ timeOrigin,
2269
+ executionTimeout: body1.runChunkExecutionLimit
1625
2270
  });
1626
- const ioWithConnections = createIOWithIntegrations(io, body1.connections, job1.options.integrations);
2271
+ const resolvedConnections = await __privateMethod(this, _resolveConnections, resolveConnections_fn).call(this, context, job1.options.integrations, body1.connections);
2272
+ if (!resolvedConnections.ok) {
2273
+ return {
2274
+ status: "UNRESOLVED_AUTH_ERROR",
2275
+ issues: resolvedConnections.issues
2276
+ };
2277
+ }
2278
+ const ioWithConnections = createIOWithIntegrations(io, resolvedConnections.data, job1.options.integrations);
1627
2279
  try {
1628
- const output = await job1.options.run(job1.trigger.event.parsePayload(body1.event.payload ?? {}), ioWithConnections, context);
2280
+ const output = await runLocalStorage.runWith({
2281
+ io,
2282
+ ctx: context
2283
+ }, () => {
2284
+ return job1.options.run(job1.trigger.event.parsePayload(body1.event.payload ?? {}), ioWithConnections, context);
2285
+ });
2286
+ if (__privateGet(this, _options4).verbose) {
2287
+ __privateMethod(this, _logIOStats, logIOStats_fn).call(this, io.stats);
2288
+ }
1629
2289
  return {
1630
2290
  status: "SUCCESS",
1631
2291
  output
1632
2292
  };
1633
2293
  } catch (error) {
2294
+ if (__privateGet(this, _options4).verbose) {
2295
+ __privateMethod(this, _logIOStats, logIOStats_fn).call(this, io.stats);
2296
+ }
2297
+ if (error instanceof AutoYieldExecutionError) {
2298
+ return {
2299
+ status: "AUTO_YIELD_EXECUTION",
2300
+ location: error.location,
2301
+ timeRemaining: error.timeRemaining,
2302
+ timeElapsed: error.timeElapsed,
2303
+ limit: body1.runChunkExecutionLimit
2304
+ };
2305
+ }
2306
+ if (error instanceof AutoYieldWithCompletedTaskExecutionError) {
2307
+ return {
2308
+ status: "AUTO_YIELD_EXECUTION_WITH_COMPLETED_TASK",
2309
+ id: error.id,
2310
+ properties: error.properties,
2311
+ output: error.output,
2312
+ data: {
2313
+ ...error.data,
2314
+ limit: body1.runChunkExecutionLimit
2315
+ }
2316
+ };
2317
+ }
2318
+ if (error instanceof YieldExecutionError) {
2319
+ return {
2320
+ status: "YIELD_EXECUTION",
2321
+ key: error.key
2322
+ };
2323
+ }
2324
+ if (error instanceof ParsedPayloadSchemaError) {
2325
+ return {
2326
+ status: "INVALID_PAYLOAD",
2327
+ errors: error.schemaErrors
2328
+ };
2329
+ }
1634
2330
  if (error instanceof ResumeWithTaskError) {
1635
2331
  return {
1636
2332
  status: "RESUME_WITH_TASK",
@@ -1652,7 +2348,7 @@ executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1) {
1652
2348
  };
1653
2349
  }
1654
2350
  if (error instanceof RetryWithTaskError) {
1655
- const errorWithStack2 = import_core5.ErrorWithStackSchema.safeParse(error.cause);
2351
+ const errorWithStack2 = import_core7.ErrorWithStackSchema.safeParse(error.cause);
1656
2352
  if (errorWithStack2.success) {
1657
2353
  return {
1658
2354
  status: "ERROR",
@@ -1668,17 +2364,19 @@ executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1) {
1668
2364
  task: error.task
1669
2365
  };
1670
2366
  }
1671
- const errorWithStack = import_core5.ErrorWithStackSchema.safeParse(error);
2367
+ const errorWithStack = import_core7.ErrorWithStackSchema.safeParse(error);
1672
2368
  if (errorWithStack.success) {
1673
2369
  return {
1674
2370
  status: "ERROR",
1675
2371
  error: errorWithStack.data
1676
2372
  };
1677
2373
  }
2374
+ const message = typeof error === "string" ? error : JSON.stringify(error);
1678
2375
  return {
1679
2376
  status: "ERROR",
1680
2377
  error: {
1681
- message: "Unknown error"
2378
+ name: "Unknown error",
2379
+ message
1682
2380
  }
1683
2381
  };
1684
2382
  }
@@ -1800,6 +2498,168 @@ handleHttpSourceRequest_fn = /* @__PURE__ */ __name(async function(source, sourc
1800
2498
  metadata: results.metadata
1801
2499
  };
1802
2500
  }, "#handleHttpSourceRequest");
2501
+ _resolveConnections = new WeakSet();
2502
+ resolveConnections_fn = /* @__PURE__ */ __name(async function(ctx, integrations, connections) {
2503
+ if (!integrations) {
2504
+ return {
2505
+ ok: true,
2506
+ data: {}
2507
+ };
2508
+ }
2509
+ const resolvedAuthResults = await Promise.all(Object.keys(integrations).map(async (key) => {
2510
+ const integration = integrations[key];
2511
+ const auth = (connections ?? {})[key];
2512
+ const result = await __privateMethod(this, _resolveConnection, resolveConnection_fn).call(this, ctx, integration, auth);
2513
+ if (result.ok) {
2514
+ return {
2515
+ ok: true,
2516
+ auth: result.auth,
2517
+ key
2518
+ };
2519
+ } else {
2520
+ return {
2521
+ ok: false,
2522
+ error: result.error,
2523
+ key
2524
+ };
2525
+ }
2526
+ }));
2527
+ const allResolved = resolvedAuthResults.every((result) => result.ok);
2528
+ if (allResolved) {
2529
+ return {
2530
+ ok: true,
2531
+ data: resolvedAuthResults.reduce((acc, result) => {
2532
+ acc[result.key] = result.auth;
2533
+ return acc;
2534
+ }, {})
2535
+ };
2536
+ } else {
2537
+ return {
2538
+ ok: false,
2539
+ issues: resolvedAuthResults.reduce((acc, result) => {
2540
+ if (result.ok) {
2541
+ return acc;
2542
+ }
2543
+ const integration = integrations[result.key];
2544
+ acc[result.key] = {
2545
+ id: integration.id,
2546
+ error: result.error
2547
+ };
2548
+ return acc;
2549
+ }, {})
2550
+ };
2551
+ }
2552
+ }, "#resolveConnections");
2553
+ _resolveConnection = new WeakSet();
2554
+ resolveConnection_fn = /* @__PURE__ */ __name(async function(ctx1, integration, auth) {
2555
+ if (auth) {
2556
+ return {
2557
+ ok: true,
2558
+ auth
2559
+ };
2560
+ }
2561
+ const authResolver = __privateGet(this, _authResolvers)[integration.id];
2562
+ if (!authResolver) {
2563
+ if (integration.authSource === "HOSTED") {
2564
+ return {
2565
+ ok: false,
2566
+ error: `Something went wrong: Integration ${integration.id} is missing auth credentials from Trigger.dev`
2567
+ };
2568
+ }
2569
+ return {
2570
+ ok: true,
2571
+ auth: void 0
2572
+ };
2573
+ }
2574
+ try {
2575
+ const resolvedAuth = await authResolver(ctx1, integration);
2576
+ if (!resolvedAuth) {
2577
+ return {
2578
+ ok: false,
2579
+ error: `Auth could not be resolved for ${integration.id}: auth resolver returned null or undefined`
2580
+ };
2581
+ }
2582
+ return {
2583
+ ok: true,
2584
+ auth: resolvedAuth.type === "apiKey" ? {
2585
+ type: "apiKey",
2586
+ accessToken: resolvedAuth.token,
2587
+ additionalFields: resolvedAuth.additionalFields
2588
+ } : {
2589
+ type: "oauth2",
2590
+ accessToken: resolvedAuth.token,
2591
+ additionalFields: resolvedAuth.additionalFields
2592
+ }
2593
+ };
2594
+ } catch (resolverError) {
2595
+ if (resolverError instanceof Error) {
2596
+ return {
2597
+ ok: false,
2598
+ error: `Auth could not be resolved for ${integration.id}: auth resolver threw. ${resolverError.name}: ${resolverError.message}`
2599
+ };
2600
+ } else if (typeof resolverError === "string") {
2601
+ return {
2602
+ ok: false,
2603
+ error: `Auth could not be resolved for ${integration.id}: auth resolver threw an error: ${resolverError}`
2604
+ };
2605
+ }
2606
+ return {
2607
+ ok: false,
2608
+ error: `Auth could not be resolved for ${integration.id}: auth resolver threw an unknown error: ${JSON.stringify(resolverError)}`
2609
+ };
2610
+ }
2611
+ }, "#resolveConnection");
2612
+ _buildJobsIndex = new WeakSet();
2613
+ buildJobsIndex_fn = /* @__PURE__ */ __name(function() {
2614
+ return Object.values(__privateGet(this, _registeredJobs)).map((job) => __privateMethod(this, _buildJobIndex, buildJobIndex_fn).call(this, job));
2615
+ }, "#buildJobsIndex");
2616
+ _buildJobIndex = new WeakSet();
2617
+ buildJobIndex_fn = /* @__PURE__ */ __name(function(job2) {
2618
+ const internal = job2.options.__internal;
2619
+ return {
2620
+ id: job2.id,
2621
+ name: job2.name,
2622
+ version: job2.version,
2623
+ event: job2.trigger.event,
2624
+ trigger: job2.trigger.toJSON(),
2625
+ integrations: __privateMethod(this, _buildJobIntegrations, buildJobIntegrations_fn).call(this, job2),
2626
+ startPosition: "latest",
2627
+ enabled: job2.enabled,
2628
+ preprocessRuns: job2.trigger.preprocessRuns,
2629
+ internal
2630
+ };
2631
+ }, "#buildJobIndex");
2632
+ _buildJobIntegrations = new WeakSet();
2633
+ buildJobIntegrations_fn = /* @__PURE__ */ __name(function(job3) {
2634
+ return Object.keys(job3.options.integrations ?? {}).reduce((acc, key) => {
2635
+ const integration = job3.options.integrations[key];
2636
+ acc[key] = __privateMethod(this, _buildJobIntegration, buildJobIntegration_fn).call(this, integration);
2637
+ return acc;
2638
+ }, {});
2639
+ }, "#buildJobIntegrations");
2640
+ _buildJobIntegration = new WeakSet();
2641
+ buildJobIntegration_fn = /* @__PURE__ */ __name(function(integration1) {
2642
+ const authSource = __privateGet(this, _authResolvers)[integration1.id] ? "RESOLVER" : integration1.authSource;
2643
+ return {
2644
+ id: integration1.id,
2645
+ metadata: integration1.metadata,
2646
+ authSource
2647
+ };
2648
+ }, "#buildJobIntegration");
2649
+ _logIOStats = new WeakSet();
2650
+ logIOStats_fn = /* @__PURE__ */ __name(function(stats) {
2651
+ __privateGet(this, _internalLogger).debug("IO stats", {
2652
+ stats
2653
+ });
2654
+ }, "#logIOStats");
2655
+ _standardResponseHeaders = new WeakSet();
2656
+ standardResponseHeaders_fn = /* @__PURE__ */ __name(function(start) {
2657
+ return {
2658
+ "Trigger-Version": import_core7.API_VERSIONS.LAZY_LOADED_CACHED_TASKS,
2659
+ "Trigger-SDK-Version": version,
2660
+ "X-Trigger-Request-Timing": `dur=${performance.now() - start / 1e3}`
2661
+ };
2662
+ }, "#standardResponseHeaders");
1803
2663
  function dynamicTriggerRegisterSourceJobId(id) {
1804
2664
  return `register-dynamic-trigger-${id}`;
1805
2665
  }
@@ -1825,7 +2685,7 @@ function deepMergeOptions(obj1, obj2) {
1825
2685
  __name(deepMergeOptions, "deepMergeOptions");
1826
2686
 
1827
2687
  // src/triggers/externalSource.ts
1828
- var import_core6 = require("@trigger.dev/core");
2688
+ var import_core8 = require("@trigger.dev/core");
1829
2689
  var ExternalSource = class {
1830
2690
  constructor(channel, options) {
1831
2691
  this.options = options;
@@ -1899,7 +2759,7 @@ var ExternalSourceTrigger = class {
1899
2759
  title: "External Source",
1900
2760
  rule: {
1901
2761
  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 ?? {}),
2762
+ payload: (0, import_core8.deepMergeFilters)(this.options.source.filter(this.options.params, this.options.options), this.event.filter ?? {}, this.options.params.filter ?? {}),
1903
2763
  source: this.event.source
1904
2764
  },
1905
2765
  properties: this.options.source.properties(this.options.params)
@@ -1933,214 +2793,6 @@ function omit(obj, key) {
1933
2793
  }
1934
2794
  __name(omit, "omit");
1935
2795
 
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
2796
  // src/triggers/notifications.ts
2145
2797
  var import_core9 = require("@trigger.dev/core");
2146
2798
  function missingConnectionNotification(integrations) {