@trigger.dev/sdk 0.0.0-cliframeworks-20230929110149 → 0.0.0-cross-runtime-20231201105801

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);
@@ -52,25 +57,35 @@ __export(src_exports, {
52
57
  CronTrigger: () => CronTrigger,
53
58
  DynamicSchedule: () => DynamicSchedule,
54
59
  DynamicTrigger: () => DynamicTrigger,
60
+ EventSpecificationExampleSchema: () => EventSpecificationExampleSchema,
55
61
  EventTrigger: () => EventTrigger,
56
62
  ExternalSource: () => ExternalSource,
57
63
  ExternalSourceTrigger: () => ExternalSourceTrigger,
58
64
  IO: () => IO,
59
65
  IOLogger: () => IOLogger,
60
66
  IntervalTrigger: () => IntervalTrigger,
67
+ InvokeTrigger: () => InvokeTrigger,
68
+ JSONOutputSerializer: () => JSONOutputSerializer,
61
69
  Job: () => Job,
62
70
  MissingConnectionNotification: () => MissingConnectionNotification,
63
71
  MissingConnectionResolvedNotification: () => MissingConnectionResolvedNotification,
64
72
  TriggerClient: () => TriggerClient,
73
+ WebhookSource: () => WebhookSource,
74
+ WebhookTrigger: () => WebhookTrigger,
65
75
  cronTrigger: () => cronTrigger,
66
76
  eventTrigger: () => eventTrigger,
67
77
  intervalTrigger: () => intervalTrigger,
78
+ invokeTrigger: () => invokeTrigger,
68
79
  isTriggerError: () => isTriggerError,
69
80
  missingConnectionNotification: () => missingConnectionNotification,
70
81
  missingConnectionResolvedNotification: () => missingConnectionResolvedNotification,
71
82
  omit: () => omit,
72
83
  redactString: () => redactString,
73
- retry: () => retry
84
+ retry: () => retry,
85
+ slugifyId: () => slugifyId,
86
+ verifyHmacSha256: () => verifyHmacSha256,
87
+ verifyRequestSignature: () => verifyRequestSignature,
88
+ waitForEventSchema: () => waitForEventSchema
74
89
  });
75
90
  module.exports = __toCommonJS(src_exports);
76
91
 
@@ -82,6 +97,24 @@ function slugifyId(input) {
82
97
  }
83
98
  __name(slugifyId, "slugifyId");
84
99
 
100
+ // src/utils/typedAsyncLocalStorage.ts
101
+ var import_node_async_hooks = require("async_hooks");
102
+ var TypedAsyncLocalStorage = class {
103
+ constructor() {
104
+ this.storage = new import_node_async_hooks.AsyncLocalStorage();
105
+ }
106
+ runWith(context, fn) {
107
+ return this.storage.run(context, fn);
108
+ }
109
+ getStore() {
110
+ return this.storage.getStore();
111
+ }
112
+ };
113
+ __name(TypedAsyncLocalStorage, "TypedAsyncLocalStorage");
114
+
115
+ // src/runLocalStorage.ts
116
+ var runLocalStorage = new TypedAsyncLocalStorage();
117
+
85
118
  // src/job.ts
86
119
  var _validate, validate_fn;
87
120
  var Job = class {
@@ -133,9 +166,125 @@ var Job = class {
133
166
  startPosition: "latest",
134
167
  enabled: this.enabled,
135
168
  preprocessRuns: this.trigger.preprocessRuns,
136
- internal
169
+ internal,
170
+ concurrencyLimit: typeof this.options.concurrencyLimit === "number" ? this.options.concurrencyLimit : typeof this.options.concurrencyLimit === "object" ? {
171
+ id: this.options.concurrencyLimit.id,
172
+ limit: this.options.concurrencyLimit.limit
173
+ } : void 0
137
174
  };
138
175
  }
176
+ async invoke(param1, param2 = void 0, param3 = void 0) {
177
+ const runStore = runLocalStorage.getStore();
178
+ if (typeof param1 === "string") {
179
+ if (!runStore) {
180
+ throw new Error("Cannot invoke a job from outside of a run when passing a cacheKey. Make sure you are running the job from within a run or use the invoke method without the cacheKey.");
181
+ }
182
+ const options = param3 ?? {};
183
+ return await runStore.io.runTask(param1, async (task) => {
184
+ const result = await this.client.invokeJob(this.id, param2, {
185
+ idempotencyKey: task.idempotencyKey,
186
+ ...options
187
+ });
188
+ task.outputProperties = [
189
+ {
190
+ label: "Run",
191
+ text: result.id,
192
+ url: `/orgs/${runStore.ctx.organization.slug}/projects/${runStore.ctx.project.slug}/jobs/${this.id}/runs/${result.id}/trigger`
193
+ }
194
+ ];
195
+ return result;
196
+ }, {
197
+ name: `Manually Invoke '${this.name}'`,
198
+ params: param2,
199
+ properties: [
200
+ {
201
+ label: "Job",
202
+ text: this.id,
203
+ url: `/orgs/${runStore.ctx.organization.slug}/projects/${runStore.ctx.project.slug}/jobs/${this.id}`
204
+ },
205
+ {
206
+ label: "Env",
207
+ text: runStore.ctx.environment.slug
208
+ }
209
+ ]
210
+ });
211
+ }
212
+ if (runStore) {
213
+ throw new Error("Cannot invoke a job from within a run without a cacheKey.");
214
+ }
215
+ return await this.client.invokeJob(this.id, param1, param3);
216
+ }
217
+ async invokeAndWaitForCompletion(cacheKey, payload, timeoutInSeconds = 60 * 60, options = {}) {
218
+ const runStore = runLocalStorage.getStore();
219
+ if (!runStore) {
220
+ throw new Error("Cannot invoke a job from outside of a run using invokeAndWaitForCompletion. Make sure you are running the job from within a run or use the invoke method instead.");
221
+ }
222
+ const { io, ctx } = runStore;
223
+ return await io.runTask(cacheKey, async (task) => {
224
+ const parsedPayload = this.trigger.event.parseInvokePayload ? this.trigger.event.parseInvokePayload(payload) ? payload : void 0 : payload;
225
+ const result = await this.client.invokeJob(this.id, parsedPayload, {
226
+ idempotencyKey: task.idempotencyKey,
227
+ callbackUrl: task.callbackUrl ?? void 0,
228
+ ...options
229
+ });
230
+ task.outputProperties = [
231
+ {
232
+ label: "Run",
233
+ text: result.id,
234
+ url: `/orgs/${ctx.organization.slug}/projects/${ctx.project.slug}/jobs/${this.id}/runs/${result.id}/trigger`
235
+ }
236
+ ];
237
+ return {};
238
+ }, {
239
+ name: `Manually Invoke '${this.name}' and wait for completion`,
240
+ params: payload,
241
+ properties: [
242
+ {
243
+ label: "Job",
244
+ text: this.id,
245
+ url: `/orgs/${ctx.organization.slug}/projects/${ctx.project.slug}/jobs/${this.id}`
246
+ },
247
+ {
248
+ label: "Env",
249
+ text: ctx.environment.slug
250
+ }
251
+ ],
252
+ callback: {
253
+ enabled: true,
254
+ timeoutInSeconds
255
+ }
256
+ });
257
+ }
258
+ async batchInvokeAndWaitForCompletion(cacheKey, batch) {
259
+ const runStore = runLocalStorage.getStore();
260
+ if (!runStore) {
261
+ throw new Error("Cannot invoke a job from outside of a run using batchInvokeAndWaitForCompletion.");
262
+ }
263
+ if (batch.length === 0) {
264
+ return [];
265
+ }
266
+ if (batch.length > 25) {
267
+ throw new Error(`Cannot batch invoke more than 25 items. You tried to batch invoke ${batch.length} items.`);
268
+ }
269
+ const { io, ctx } = runStore;
270
+ const results = await io.parallel(cacheKey, batch, async (item, index) => {
271
+ return await this.invokeAndWaitForCompletion(String(index), item.payload, item.timeoutInSeconds ?? 60 * 60, item.options);
272
+ }, {
273
+ name: `Batch Invoke '${this.name}'`,
274
+ properties: [
275
+ {
276
+ label: "Job",
277
+ text: this.id,
278
+ url: `/orgs/${ctx.organization.slug}/projects/${ctx.project.slug}/jobs/${this.id}`
279
+ },
280
+ {
281
+ label: "Env",
282
+ text: ctx.environment.slug
283
+ }
284
+ ]
285
+ });
286
+ return results;
287
+ }
139
288
  };
140
289
  __name(Job, "Job");
141
290
  _validate = new WeakSet();
@@ -146,518 +295,679 @@ validate_fn = /* @__PURE__ */ __name(function() {
146
295
  }, "#validate");
147
296
 
148
297
  // src/triggerClient.ts
149
- var import_core7 = require("@trigger.dev/core");
298
+ var import_core8 = require("@trigger.dev/core");
299
+ var import_colorette = require("colorette");
150
300
 
151
301
  // src/apiClient.ts
302
+ var import_core3 = require("@trigger.dev/core");
303
+ var import_zod3 = require("zod");
304
+
305
+ // src/io.ts
306
+ var import_core2 = require("@trigger.dev/core");
307
+ var import_core_backend = require("@trigger.dev/core-backend");
308
+ var import_node_async_hooks2 = require("async_hooks");
309
+ var import_node_crypto = require("crypto");
310
+
311
+ // src/errors.ts
312
+ var ResumeWithTaskError = class {
313
+ constructor(task) {
314
+ this.task = task;
315
+ }
316
+ };
317
+ __name(ResumeWithTaskError, "ResumeWithTaskError");
318
+ var ResumeWithParallelTaskError = class {
319
+ constructor(task, childErrors) {
320
+ this.task = task;
321
+ this.childErrors = childErrors;
322
+ }
323
+ };
324
+ __name(ResumeWithParallelTaskError, "ResumeWithParallelTaskError");
325
+ var RetryWithTaskError = class {
326
+ constructor(cause, task, retryAt) {
327
+ this.cause = cause;
328
+ this.task = task;
329
+ this.retryAt = retryAt;
330
+ }
331
+ };
332
+ __name(RetryWithTaskError, "RetryWithTaskError");
333
+ var CanceledWithTaskError = class {
334
+ constructor(task) {
335
+ this.task = task;
336
+ }
337
+ };
338
+ __name(CanceledWithTaskError, "CanceledWithTaskError");
339
+ var YieldExecutionError = class {
340
+ constructor(key) {
341
+ this.key = key;
342
+ }
343
+ };
344
+ __name(YieldExecutionError, "YieldExecutionError");
345
+ var AutoYieldExecutionError = class {
346
+ constructor(location, timeRemaining, timeElapsed) {
347
+ this.location = location;
348
+ this.timeRemaining = timeRemaining;
349
+ this.timeElapsed = timeElapsed;
350
+ }
351
+ };
352
+ __name(AutoYieldExecutionError, "AutoYieldExecutionError");
353
+ var AutoYieldWithCompletedTaskExecutionError = class {
354
+ constructor(id, properties, data, output) {
355
+ this.id = id;
356
+ this.properties = properties;
357
+ this.data = data;
358
+ this.output = output;
359
+ }
360
+ };
361
+ __name(AutoYieldWithCompletedTaskExecutionError, "AutoYieldWithCompletedTaskExecutionError");
362
+ var ParsedPayloadSchemaError = class {
363
+ constructor(schemaErrors) {
364
+ this.schemaErrors = schemaErrors;
365
+ }
366
+ };
367
+ __name(ParsedPayloadSchemaError, "ParsedPayloadSchemaError");
368
+ function isTriggerError(err) {
369
+ return err instanceof ResumeWithTaskError || err instanceof RetryWithTaskError || err instanceof CanceledWithTaskError || err instanceof YieldExecutionError || err instanceof AutoYieldExecutionError || err instanceof AutoYieldWithCompletedTaskExecutionError || err instanceof ResumeWithParallelTaskError;
370
+ }
371
+ __name(isTriggerError, "isTriggerError");
372
+ var ErrorWithTask = class extends Error {
373
+ constructor(cause, message) {
374
+ super(message);
375
+ this.cause = cause;
376
+ }
377
+ };
378
+ __name(ErrorWithTask, "ErrorWithTask");
379
+
380
+ // src/retry.ts
152
381
  var import_core = require("@trigger.dev/core");
153
- var import_node_fetch = __toESM(require("node-fetch"));
154
- var import_zod = require("zod");
155
- var _apiUrl, _options, _logger, _apiKey, apiKey_fn;
156
- var ApiClient = class {
157
- constructor(options) {
158
- __privateAdd(this, _apiKey);
159
- __privateAdd(this, _apiUrl, void 0);
160
- __privateAdd(this, _options, void 0);
161
- __privateAdd(this, _logger, void 0);
162
- __privateSet(this, _options, options);
163
- __privateSet(this, _apiUrl, __privateGet(this, _options).apiUrl ?? process.env.TRIGGER_API_URL ?? "https://api.trigger.dev");
164
- __privateSet(this, _logger, new import_core.Logger("trigger.dev", __privateGet(this, _options).logLevel));
382
+ var retry = {
383
+ standardBackoff: {
384
+ limit: 8,
385
+ factor: 1.8,
386
+ minTimeoutInMs: 500,
387
+ maxTimeoutInMs: 3e4,
388
+ randomize: true
389
+ },
390
+ exponentialBackoff: {
391
+ limit: 8,
392
+ factor: 2,
393
+ minTimeoutInMs: 1e3,
394
+ maxTimeoutInMs: 3e4,
395
+ randomize: true
165
396
  }
166
- async registerEndpoint(options) {
167
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
168
- __privateGet(this, _logger).debug("Registering endpoint", {
169
- url: options.url,
170
- name: options.name
171
- });
172
- const response = await (0, import_node_fetch.default)(`${__privateGet(this, _apiUrl)}/api/v1/endpoints`, {
173
- method: "POST",
174
- headers: {
175
- "Content-Type": "application/json",
176
- Authorization: `Bearer ${apiKey}`
177
- },
178
- body: JSON.stringify({
179
- url: options.url,
180
- name: options.name
181
- })
182
- });
183
- if (response.status >= 400 && response.status < 500) {
184
- const body = await response.json();
185
- throw new Error(body.error);
397
+ };
398
+
399
+ // src/status.ts
400
+ var TriggerStatus = class {
401
+ constructor(id, io) {
402
+ this.id = id;
403
+ this.io = io;
404
+ }
405
+ async update(key, status) {
406
+ const properties = [];
407
+ if (status.label) {
408
+ properties.push({
409
+ label: "Label",
410
+ text: status.label
411
+ });
186
412
  }
187
- if (response.status !== 200) {
188
- throw new Error(`Failed to register entry point, got status code ${response.status}`);
413
+ if (status.state) {
414
+ properties.push({
415
+ label: "State",
416
+ text: status.state
417
+ });
189
418
  }
190
- return await response.json();
191
- }
192
- async runTask(runId, task) {
193
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
194
- __privateGet(this, _logger).debug("Running Task", {
195
- task
196
- });
197
- return await zodfetch(import_core.ServerTaskSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/tasks`, {
198
- method: "POST",
199
- headers: {
200
- "Content-Type": "application/json",
201
- Authorization: `Bearer ${apiKey}`,
202
- "Idempotency-Key": task.idempotencyKey
419
+ return await this.io.runTask(key, async (task) => {
420
+ return await this.io.triggerClient.updateStatus(this.io.runId, this.id, status);
421
+ }, {
422
+ name: status.label ?? `Status update`,
423
+ icon: "bell",
424
+ params: {
425
+ ...status
203
426
  },
204
- body: JSON.stringify(task)
427
+ properties
205
428
  });
206
429
  }
207
- async completeTask(runId, id, task) {
208
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
209
- __privateGet(this, _logger).debug("Complete Task", {
210
- task
211
- });
212
- return await zodfetch(import_core.ServerTaskSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/tasks/${id}/complete`, {
213
- method: "POST",
214
- headers: {
215
- "Content-Type": "application/json",
216
- Authorization: `Bearer ${apiKey}`
430
+ };
431
+ __name(TriggerStatus, "TriggerStatus");
432
+
433
+ // src/types.ts
434
+ var import_zod = require("zod");
435
+ var EventSpecificationExampleSchema = import_zod.z.object({
436
+ id: import_zod.z.string(),
437
+ name: import_zod.z.string(),
438
+ icon: import_zod.z.string().optional(),
439
+ payload: import_zod.z.any()
440
+ });
441
+ function waitForEventSchema(schema) {
442
+ return import_zod.z.object({
443
+ id: import_zod.z.string(),
444
+ name: import_zod.z.string(),
445
+ source: import_zod.z.string(),
446
+ payload: schema,
447
+ timestamp: import_zod.z.coerce.date(),
448
+ context: import_zod.z.any().optional(),
449
+ accountId: import_zod.z.string().optional()
450
+ });
451
+ }
452
+ __name(waitForEventSchema, "waitForEventSchema");
453
+
454
+ // src/io.ts
455
+ var import_zod2 = require("zod");
456
+
457
+ // src/store/keyValueStore.ts
458
+ var _namespacedKey, namespacedKey_fn, _sharedProperties, sharedProperties_fn;
459
+ var KeyValueStore = class {
460
+ constructor(apiClient, type = null, namespace = "") {
461
+ __privateAdd(this, _namespacedKey);
462
+ __privateAdd(this, _sharedProperties);
463
+ this.apiClient = apiClient;
464
+ this.type = type;
465
+ this.namespace = namespace;
466
+ }
467
+ async delete(param1, param2) {
468
+ const runStore = runLocalStorage.getStore();
469
+ if (!runStore) {
470
+ if (typeof param1 !== "string") {
471
+ throw new Error("Please use the store without a cacheKey when accessing from outside a run.");
472
+ }
473
+ return await this.apiClient.store.delete(__privateMethod(this, _namespacedKey, namespacedKey_fn).call(this, param1));
474
+ }
475
+ const { io } = runStore;
476
+ if (!param2) {
477
+ throw new Error("Please provide a non-empty key when accessing the store from inside a run.");
478
+ }
479
+ return await io.runTask(param1, async (task) => {
480
+ return await this.apiClient.store.delete(__privateMethod(this, _namespacedKey, namespacedKey_fn).call(this, param2));
481
+ }, {
482
+ name: "Key-Value Store Delete",
483
+ icon: "database-minus",
484
+ params: {
485
+ key: param2
217
486
  },
218
- body: JSON.stringify(task)
487
+ properties: __privateMethod(this, _sharedProperties, sharedProperties_fn).call(this, param2),
488
+ style: {
489
+ style: "minimal"
490
+ }
219
491
  });
220
492
  }
221
- async failTask(runId, id, body) {
222
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
223
- __privateGet(this, _logger).debug("Fail Task", {
224
- id,
225
- runId,
226
- body
227
- });
228
- return await zodfetch(import_core.ServerTaskSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/tasks/${id}/fail`, {
229
- method: "POST",
230
- headers: {
231
- "Content-Type": "application/json",
232
- Authorization: `Bearer ${apiKey}`
493
+ async get(param1, param2) {
494
+ const runStore = runLocalStorage.getStore();
495
+ if (!runStore) {
496
+ if (typeof param1 !== "string") {
497
+ throw new Error("Please use the store without a cacheKey when accessing from outside a run.");
498
+ }
499
+ return await this.apiClient.store.get(__privateMethod(this, _namespacedKey, namespacedKey_fn).call(this, param1));
500
+ }
501
+ const { io } = runStore;
502
+ if (!param2) {
503
+ throw new Error("Please provide a non-empty key when accessing the store from inside a run.");
504
+ }
505
+ return await io.runTask(param1, async (task) => {
506
+ return await this.apiClient.store.get(__privateMethod(this, _namespacedKey, namespacedKey_fn).call(this, param2));
507
+ }, {
508
+ name: "Key-Value Store Get",
509
+ icon: "database-export",
510
+ params: {
511
+ key: param2
233
512
  },
234
- body: JSON.stringify(body)
513
+ properties: __privateMethod(this, _sharedProperties, sharedProperties_fn).call(this, param2),
514
+ style: {
515
+ style: "minimal"
516
+ }
235
517
  });
236
518
  }
237
- async sendEvent(event, options = {}) {
238
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
239
- __privateGet(this, _logger).debug("Sending event", {
240
- event
241
- });
242
- return await zodfetch(import_core.ApiEventLogSchema, `${__privateGet(this, _apiUrl)}/api/v1/events`, {
243
- method: "POST",
244
- headers: {
245
- "Content-Type": "application/json",
246
- Authorization: `Bearer ${apiKey}`
519
+ async has(param1, param2) {
520
+ const runStore = runLocalStorage.getStore();
521
+ if (!runStore) {
522
+ if (typeof param1 !== "string") {
523
+ throw new Error("Please use the store without a cacheKey when accessing from outside a run.");
524
+ }
525
+ return await this.apiClient.store.has(__privateMethod(this, _namespacedKey, namespacedKey_fn).call(this, param1));
526
+ }
527
+ const { io } = runStore;
528
+ if (!param2) {
529
+ throw new Error("Please provide a non-empty key when accessing the store from inside a run.");
530
+ }
531
+ return await io.runTask(param1, async (task) => {
532
+ return await this.apiClient.store.has(__privateMethod(this, _namespacedKey, namespacedKey_fn).call(this, param2));
533
+ }, {
534
+ name: "Key-Value Store Has",
535
+ icon: "database-search",
536
+ params: {
537
+ key: param2
247
538
  },
248
- body: JSON.stringify({
249
- event,
250
- options
251
- })
252
- });
253
- }
254
- async cancelEvent(eventId) {
255
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
256
- __privateGet(this, _logger).debug("Cancelling event", {
257
- eventId
258
- });
259
- return await zodfetch(import_core.ApiEventLogSchema, `${__privateGet(this, _apiUrl)}/api/v1/events/${eventId}/cancel`, {
260
- method: "POST",
261
- headers: {
262
- "Content-Type": "application/json",
263
- Authorization: `Bearer ${apiKey}`
539
+ properties: __privateMethod(this, _sharedProperties, sharedProperties_fn).call(this, param2),
540
+ style: {
541
+ style: "minimal"
264
542
  }
265
543
  });
266
544
  }
267
- async updateStatus(runId, id, status) {
268
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
269
- __privateGet(this, _logger).debug("Update status", {
270
- id,
271
- status
272
- });
273
- return await zodfetch(import_core.JobRunStatusRecordSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/statuses/${id}`, {
274
- method: "PUT",
275
- headers: {
276
- "Content-Type": "application/json",
277
- Authorization: `Bearer ${apiKey}`
545
+ async set(param1, param2, param3) {
546
+ const runStore = runLocalStorage.getStore();
547
+ if (!runStore) {
548
+ if (typeof param1 !== "string") {
549
+ throw new Error("Please use the store without a cacheKey when accessing from outside a run.");
550
+ }
551
+ return await this.apiClient.store.set(__privateMethod(this, _namespacedKey, namespacedKey_fn).call(this, param1), param2);
552
+ }
553
+ const { io } = runStore;
554
+ if (!param2 || typeof param2 !== "string") {
555
+ throw new Error("Please provide a non-empty key when accessing the store from inside a run.");
556
+ }
557
+ const value = param3;
558
+ return await io.runTask(param1, async (task) => {
559
+ return await this.apiClient.store.set(__privateMethod(this, _namespacedKey, namespacedKey_fn).call(this, param2), value);
560
+ }, {
561
+ name: "Key-Value Store Set",
562
+ icon: "database-plus",
563
+ params: {
564
+ key: param2,
565
+ value
278
566
  },
279
- body: JSON.stringify(status)
567
+ properties: [
568
+ ...__privateMethod(this, _sharedProperties, sharedProperties_fn).call(this, param2),
569
+ ...typeof value !== "object" || value === null ? [
570
+ {
571
+ label: "value",
572
+ text: String(value) ?? "undefined"
573
+ }
574
+ ] : []
575
+ ],
576
+ style: {
577
+ style: "minimal"
578
+ }
280
579
  });
281
580
  }
282
- async updateSource(client, key, source) {
283
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
284
- __privateGet(this, _logger).debug("activating http source", {
285
- source
286
- });
287
- const response = await zodfetch(import_core.TriggerSourceSchema, `${__privateGet(this, _apiUrl)}/api/v2/${client}/sources/${key}`, {
288
- method: "PUT",
289
- headers: {
290
- "Content-Type": "application/json",
291
- Authorization: `Bearer ${apiKey}`
292
- },
293
- body: JSON.stringify(source)
294
- });
295
- return response;
581
+ };
582
+ __name(KeyValueStore, "KeyValueStore");
583
+ _namespacedKey = new WeakSet();
584
+ namespacedKey_fn = /* @__PURE__ */ __name(function(key) {
585
+ const parts = [];
586
+ if (this.type) {
587
+ parts.push(this.type);
588
+ }
589
+ if (this.namespace) {
590
+ parts.push(this.namespace);
591
+ }
592
+ parts.push(key);
593
+ return parts.join(":");
594
+ }, "#namespacedKey");
595
+ _sharedProperties = new WeakSet();
596
+ sharedProperties_fn = /* @__PURE__ */ __name(function(key1) {
597
+ return [
598
+ {
599
+ label: "namespace",
600
+ text: this.type ?? "env"
601
+ },
602
+ {
603
+ label: "key",
604
+ text: key1
605
+ }
606
+ ];
607
+ }, "#sharedProperties");
608
+
609
+ // src/io.ts
610
+ var JSONOutputSerializer = class {
611
+ serialize(value) {
612
+ return JSON.stringify(value);
296
613
  }
297
- async registerTrigger(client, id, key, payload) {
298
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
299
- __privateGet(this, _logger).debug("registering trigger", {
300
- id,
301
- payload
302
- });
303
- const response = await zodfetch(import_core.RegisterSourceEventSchemaV2, `${__privateGet(this, _apiUrl)}/api/v2/${client}/triggers/${id}/registrations/${key}`, {
304
- method: "PUT",
305
- headers: {
306
- "Content-Type": "application/json",
307
- Authorization: `Bearer ${apiKey}`
308
- },
309
- body: JSON.stringify(payload)
310
- });
311
- return response;
614
+ deserialize(value) {
615
+ return value ? JSON.parse(value) : void 0;
312
616
  }
313
- async registerSchedule(client, id, key, payload) {
314
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
315
- __privateGet(this, _logger).debug("registering schedule", {
316
- id,
317
- payload
318
- });
319
- const response = await zodfetch(import_core.RegisterScheduleResponseBodySchema, `${__privateGet(this, _apiUrl)}/api/v1/${client}/schedules/${id}/registrations`, {
320
- method: "POST",
321
- headers: {
322
- "Content-Type": "application/json",
323
- Authorization: `Bearer ${apiKey}`
324
- },
325
- body: JSON.stringify({
326
- id: key,
327
- ...payload
328
- })
329
- });
330
- return response;
617
+ };
618
+ __name(JSONOutputSerializer, "JSONOutputSerializer");
619
+ var _addToCachedTasks, addToCachedTasks_fn, _detectAutoYield, detectAutoYield_fn, _forceYield, forceYield_fn, _getTimeElapsed, getTimeElapsed_fn, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn;
620
+ var IO = class {
621
+ constructor(options) {
622
+ __privateAdd(this, _addToCachedTasks);
623
+ __privateAdd(this, _detectAutoYield);
624
+ __privateAdd(this, _forceYield);
625
+ __privateAdd(this, _getTimeElapsed);
626
+ __privateAdd(this, _getRemainingTimeInMillis);
627
+ __publicField(this, "_outputSerializer", new JSONOutputSerializer());
628
+ __publicField(this, "_visitedCacheKeys", /* @__PURE__ */ new Set());
629
+ __publicField(this, "brb", this.yield.bind(this));
630
+ this._id = options.id;
631
+ this._jobId = options.jobId;
632
+ this._apiClient = options.apiClient;
633
+ this._triggerClient = options.client;
634
+ this._logger = options.logger ?? new import_core2.Logger("trigger.dev", options.logLevel);
635
+ this._cachedTasks = /* @__PURE__ */ new Map();
636
+ this._jobLogger = options.jobLogger;
637
+ this._jobLogLevel = options.jobLogLevel;
638
+ this._timeOrigin = options.timeOrigin;
639
+ this._executionTimeout = options.executionTimeout;
640
+ this._envStore = new KeyValueStore(options.apiClient);
641
+ this._jobStore = new KeyValueStore(options.apiClient, "job", options.jobId);
642
+ this._runStore = new KeyValueStore(options.apiClient, "run", options.id);
643
+ this._stats = {
644
+ initialCachedTasks: 0,
645
+ lazyLoadedCachedTasks: 0,
646
+ executedTasks: 0,
647
+ cachedTaskHits: 0,
648
+ cachedTaskMisses: 0,
649
+ noopCachedTaskHits: 0,
650
+ noopCachedTaskMisses: 0
651
+ };
652
+ if (options.cachedTasks) {
653
+ options.cachedTasks.forEach((task) => {
654
+ this._cachedTasks.set(task.idempotencyKey, task);
655
+ });
656
+ this._stats.initialCachedTasks = options.cachedTasks.length;
657
+ }
658
+ this._taskStorage = new import_node_async_hooks2.AsyncLocalStorage();
659
+ this._context = options.context;
660
+ this._yieldedExecutions = options.yieldedExecutions ?? [];
661
+ if (options.noopTasksSet) {
662
+ this._noopTasksBloomFilter = import_core_backend.BloomFilter.deserialize(options.noopTasksSet, import_core_backend.BloomFilter.NOOP_TASK_SET_SIZE);
663
+ }
664
+ this._cachedTasksCursor = options.cachedTasksCursor;
665
+ this._serverVersion = options.serverVersion ?? "unversioned";
331
666
  }
332
- async unregisterSchedule(client, id, key) {
333
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
334
- __privateGet(this, _logger).debug("unregistering schedule", {
335
- id
336
- });
337
- const response = await zodfetch(import_zod.z.object({
338
- ok: import_zod.z.boolean()
339
- }), `${__privateGet(this, _apiUrl)}/api/v1/${client}/schedules/${id}/registrations/${encodeURIComponent(key)}`, {
340
- method: "DELETE",
341
- headers: {
342
- "Content-Type": "application/json",
343
- Authorization: `Bearer ${apiKey}`
667
+ get stats() {
668
+ return this._stats;
669
+ }
670
+ get runId() {
671
+ return this._id;
672
+ }
673
+ get triggerClient() {
674
+ return this._triggerClient;
675
+ }
676
+ get logger() {
677
+ return new IOLogger(async (level, message, data) => {
678
+ let logLevel = "info";
679
+ if (import_core2.Logger.satisfiesLogLevel(logLevel, this._jobLogLevel)) {
680
+ await this.runTask([
681
+ message,
682
+ level
683
+ ], async (task) => {
684
+ switch (level) {
685
+ case "LOG": {
686
+ this._jobLogger?.log(message, data);
687
+ logLevel = "log";
688
+ break;
689
+ }
690
+ case "DEBUG": {
691
+ this._jobLogger?.debug(message, data);
692
+ logLevel = "debug";
693
+ break;
694
+ }
695
+ case "INFO": {
696
+ this._jobLogger?.info(message, data);
697
+ logLevel = "info";
698
+ break;
699
+ }
700
+ case "WARN": {
701
+ this._jobLogger?.warn(message, data);
702
+ logLevel = "warn";
703
+ break;
704
+ }
705
+ case "ERROR": {
706
+ this._jobLogger?.error(message, data);
707
+ logLevel = "error";
708
+ break;
709
+ }
710
+ }
711
+ }, {
712
+ name: "log",
713
+ icon: "log",
714
+ description: message,
715
+ params: data,
716
+ properties: [
717
+ {
718
+ label: "Level",
719
+ text: level
720
+ }
721
+ ],
722
+ style: {
723
+ style: "minimal",
724
+ variant: level.toLowerCase()
725
+ },
726
+ noop: true
727
+ });
344
728
  }
345
729
  });
346
- return response;
347
730
  }
348
- async getAuth(client, id) {
349
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
350
- __privateGet(this, _logger).debug("getting auth", {
351
- id
352
- });
353
- const response = await zodfetch(import_core.ConnectionAuthSchema, `${__privateGet(this, _apiUrl)}/api/v1/${client}/auth/${id}`, {
354
- method: "GET",
355
- headers: {
356
- Accept: "application/json",
357
- Authorization: `Bearer ${apiKey}`
731
+ async random(cacheKey, { min = 0, max = 1, round = false } = {}) {
732
+ return await this.runTask(cacheKey, async (task) => {
733
+ if (min > max) {
734
+ throw new Error(`Lower bound can't be higher than upper bound - min: ${min}, max: ${max}`);
358
735
  }
736
+ if (min === max) {
737
+ await this.logger.warn(`Lower and upper bounds are identical. The return value is not random and will always be: ${min}`);
738
+ }
739
+ const withinBounds = (max - min) * Math.random() + min;
740
+ if (!round) {
741
+ return withinBounds;
742
+ }
743
+ if (!Number.isInteger(min) || !Number.isInteger(max)) {
744
+ await this.logger.warn("Rounding enabled with floating-point bounds. This may cause unexpected skew and boundary inclusivity.");
745
+ }
746
+ const rounded = Math.round(withinBounds);
747
+ return rounded;
359
748
  }, {
360
- optional: true
361
- });
362
- return response;
363
- }
364
- async getEvent(eventId) {
365
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
366
- __privateGet(this, _logger).debug("Getting Event", {
367
- eventId
368
- });
369
- return await zodfetch(import_core.GetEventSchema, `${__privateGet(this, _apiUrl)}/api/v1/events/${eventId}`, {
370
- method: "GET",
371
- headers: {
372
- Authorization: `Bearer ${apiKey}`
749
+ name: "random",
750
+ icon: "dice-5-filled",
751
+ params: {
752
+ min,
753
+ max,
754
+ round
755
+ },
756
+ properties: [
757
+ ...min === 0 ? [] : [
758
+ {
759
+ label: "min",
760
+ text: String(min)
761
+ }
762
+ ],
763
+ ...max === 1 ? [] : [
764
+ {
765
+ label: "max",
766
+ text: String(max)
767
+ }
768
+ ],
769
+ ...round === false ? [] : [
770
+ {
771
+ label: "round",
772
+ text: String(round)
773
+ }
774
+ ]
775
+ ],
776
+ style: {
777
+ style: "minimal"
373
778
  }
374
779
  });
375
780
  }
376
- async getRun(runId, options) {
377
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
378
- __privateGet(this, _logger).debug("Getting Run", {
379
- runId
380
- });
381
- return await zodfetch(import_core.GetRunSchema, (0, import_core.urlWithSearchParams)(`${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}`, options), {
382
- method: "GET",
383
- headers: {
384
- Authorization: `Bearer ${apiKey}`
781
+ async wait(cacheKey, seconds) {
782
+ return await this.runTask(cacheKey, async (task) => {
783
+ }, {
784
+ name: "wait",
785
+ icon: "clock",
786
+ params: {
787
+ seconds
788
+ },
789
+ noop: true,
790
+ delayUntil: new Date(Date.now() + seconds * 1e3),
791
+ style: {
792
+ style: "minimal"
385
793
  }
386
794
  });
387
795
  }
388
- async getRunStatuses(runId) {
389
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
390
- __privateGet(this, _logger).debug("Getting Run statuses", {
391
- runId
392
- });
393
- return await zodfetch(import_core.GetRunStatusesSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/statuses`, {
394
- method: "GET",
395
- headers: {
396
- Authorization: `Bearer ${apiKey}`
796
+ async waitForEvent(cacheKey, event, options) {
797
+ const timeoutInSeconds = options?.timeoutInSeconds ?? 60 * 60;
798
+ return await this.runTask(cacheKey, async (task, io) => {
799
+ if (!task.callbackUrl) {
800
+ throw new Error("No callbackUrl found on task");
801
+ }
802
+ await this.triggerClient.createEphemeralEventDispatcher({
803
+ url: task.callbackUrl,
804
+ name: event.name,
805
+ filter: event.filter,
806
+ contextFilter: event.contextFilter,
807
+ source: event.source,
808
+ accountId: event.accountId,
809
+ timeoutInSeconds
810
+ });
811
+ return {};
812
+ }, {
813
+ name: "Wait for Event",
814
+ icon: "custom-event",
815
+ params: {
816
+ name: event.name,
817
+ source: event.source,
818
+ filter: event.filter,
819
+ contextFilter: event.contextFilter,
820
+ accountId: event.accountId
821
+ },
822
+ callback: {
823
+ enabled: true,
824
+ timeoutInSeconds
825
+ },
826
+ properties: [
827
+ {
828
+ label: "Event",
829
+ text: event.name
830
+ },
831
+ {
832
+ label: "Timeout",
833
+ text: `${timeoutInSeconds}s`
834
+ },
835
+ ...event.source ? [
836
+ {
837
+ label: "Source",
838
+ text: event.source
839
+ }
840
+ ] : [],
841
+ ...event.accountId ? [
842
+ {
843
+ label: "Account ID",
844
+ text: event.accountId
845
+ }
846
+ ] : []
847
+ ],
848
+ parseOutput: (output) => {
849
+ return waitForEventSchema(event.schema ?? import_zod2.z.any()).parse(output);
397
850
  }
398
851
  });
399
852
  }
400
- async getRuns(jobSlug, options) {
401
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
402
- __privateGet(this, _logger).debug("Getting Runs", {
403
- jobSlug
404
- });
405
- return await zodfetch(import_core.GetRunsSchema, (0, import_core.urlWithSearchParams)(`${__privateGet(this, _apiUrl)}/api/v1/jobs/${jobSlug}/runs`, options), {
406
- method: "GET",
407
- headers: {
408
- Authorization: `Bearer ${apiKey}`
853
+ async waitForRequest(cacheKey, callback, options) {
854
+ const timeoutInSeconds = options?.timeoutInSeconds ?? 60 * 60;
855
+ return await this.runTask(cacheKey, async (task, io) => {
856
+ if (!task.callbackUrl) {
857
+ throw new Error("No callbackUrl found on task");
409
858
  }
859
+ task.outputProperties = [
860
+ {
861
+ label: "Callback URL",
862
+ text: task.callbackUrl
863
+ }
864
+ ];
865
+ return callback(task.callbackUrl);
866
+ }, {
867
+ name: "Wait for Request",
868
+ icon: "clock",
869
+ callback: {
870
+ enabled: true,
871
+ timeoutInSeconds: options?.timeoutInSeconds
872
+ },
873
+ properties: [
874
+ {
875
+ label: "Timeout",
876
+ text: `${timeoutInSeconds}s`
877
+ }
878
+ ]
410
879
  });
411
880
  }
412
- };
413
- __name(ApiClient, "ApiClient");
414
- _apiUrl = new WeakMap();
415
- _options = new WeakMap();
416
- _logger = new WeakMap();
417
- _apiKey = new WeakSet();
418
- apiKey_fn = /* @__PURE__ */ __name(async function() {
419
- const apiKey = getApiKey(__privateGet(this, _options).apiKey);
420
- if (apiKey.status === "invalid") {
421
- throw new Error("Invalid API key");
422
- } else if (apiKey.status === "missing") {
423
- throw new Error("Missing API key");
424
- }
425
- return apiKey.apiKey;
426
- }, "#apiKey");
427
- function getApiKey(key) {
428
- const apiKey = key ?? process.env.TRIGGER_API_KEY;
429
- if (!apiKey) {
430
- return {
431
- status: "missing"
432
- };
433
- }
434
- const isValid = apiKey.match(/^tr_[a-z]+_[a-zA-Z0-9]+$/);
435
- if (!isValid) {
436
- return {
437
- status: "invalid",
438
- apiKey
439
- };
440
- }
441
- return {
442
- status: "valid",
443
- apiKey
444
- };
445
- }
446
- __name(getApiKey, "getApiKey");
447
- async function zodfetch(schema, url, requestInit, options) {
448
- const response = await (0, import_node_fetch.default)(url, requestInit);
449
- if ((!requestInit || requestInit.method === "GET") && response.status === 404 && options?.optional) {
450
- return;
451
- }
452
- if (response.status >= 400 && response.status < 500) {
453
- const body = await response.json();
454
- throw new Error(body.error);
455
- }
456
- if (response.status !== 200) {
457
- throw new Error(options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`);
458
- }
459
- const jsonBody = await response.json();
460
- return schema.parse(jsonBody);
461
- }
462
- __name(zodfetch, "zodfetch");
463
-
464
- // src/errors.ts
465
- var ResumeWithTaskError = class {
466
- constructor(task) {
467
- this.task = task;
468
- }
469
- };
470
- __name(ResumeWithTaskError, "ResumeWithTaskError");
471
- var RetryWithTaskError = class {
472
- constructor(cause, task, retryAt) {
473
- this.cause = cause;
474
- this.task = task;
475
- this.retryAt = retryAt;
476
- }
477
- };
478
- __name(RetryWithTaskError, "RetryWithTaskError");
479
- var CanceledWithTaskError = class {
480
- constructor(task) {
481
- this.task = task;
482
- }
483
- };
484
- __name(CanceledWithTaskError, "CanceledWithTaskError");
485
- var ParsedPayloadSchemaError = class {
486
- constructor(schemaErrors) {
487
- this.schemaErrors = schemaErrors;
488
- }
489
- };
490
- __name(ParsedPayloadSchemaError, "ParsedPayloadSchemaError");
491
- function isTriggerError(err) {
492
- return err instanceof ResumeWithTaskError || err instanceof RetryWithTaskError || err instanceof CanceledWithTaskError;
493
- }
494
- __name(isTriggerError, "isTriggerError");
495
-
496
- // src/io.ts
497
- var import_core3 = require("@trigger.dev/core");
498
- var import_node_async_hooks = require("async_hooks");
499
- var import_node_crypto = require("crypto");
500
-
501
- // src/retry.ts
502
- var import_core2 = require("@trigger.dev/core");
503
- var retry = {
504
- standardBackoff: {
505
- limit: 8,
506
- factor: 1.8,
507
- minTimeoutInMs: 500,
508
- maxTimeoutInMs: 3e4,
509
- randomize: true
510
- }
511
- };
512
-
513
- // src/status.ts
514
- var TriggerStatus = class {
515
- constructor(id, io) {
516
- this.id = id;
517
- this.io = io;
881
+ async createStatus(cacheKey, initialStatus) {
882
+ const id = typeof cacheKey === "string" ? cacheKey : cacheKey.join("-");
883
+ const status = new TriggerStatus(id, this);
884
+ await status.update(cacheKey, initialStatus);
885
+ return status;
518
886
  }
519
- async update(key, status) {
520
- const properties = [];
521
- if (status.label) {
522
- properties.push({
523
- label: "Label",
524
- text: status.label
525
- });
526
- }
527
- if (status.state) {
528
- properties.push({
529
- label: "State",
530
- text: status.state
531
- });
532
- }
533
- return await this.io.runTask(key, async (task) => {
534
- return await this.io.triggerClient.updateStatus(this.io.runId, this.id, status);
887
+ async backgroundFetch(cacheKey, url, requestInit, options) {
888
+ const urlObject = new URL(url);
889
+ return await this.runTask(cacheKey, async (task) => {
890
+ console.log("task context", task.context);
891
+ return task.output;
535
892
  }, {
536
- name: status.label ?? `Status update`,
537
- icon: "bell",
893
+ name: `fetch ${urlObject.hostname}${urlObject.pathname}`,
538
894
  params: {
539
- ...status
895
+ url,
896
+ requestInit,
897
+ retry: options?.retry,
898
+ timeout: options?.timeout
540
899
  },
541
- properties
542
- });
543
- }
544
- };
545
- __name(TriggerStatus, "TriggerStatus");
546
-
547
- // src/io.ts
548
- var _addToCachedTasks, addToCachedTasks_fn;
549
- var IO = class {
550
- constructor(options) {
551
- __privateAdd(this, _addToCachedTasks);
552
- this._id = options.id;
553
- this._apiClient = options.apiClient;
554
- this._triggerClient = options.client;
555
- this._logger = options.logger ?? new import_core3.Logger("trigger.dev", options.logLevel);
556
- this._cachedTasks = /* @__PURE__ */ new Map();
557
- this._jobLogger = options.jobLogger;
558
- this._jobLogLevel = options.jobLogLevel;
559
- if (options.cachedTasks) {
560
- options.cachedTasks.forEach((task) => {
561
- this._cachedTasks.set(task.idempotencyKey, task);
562
- });
563
- }
564
- this._taskStorage = new import_node_async_hooks.AsyncLocalStorage();
565
- this._context = options.context;
566
- }
567
- get runId() {
568
- return this._id;
569
- }
570
- get triggerClient() {
571
- return this._triggerClient;
572
- }
573
- get logger() {
574
- return new IOLogger(async (level, message, data) => {
575
- let logLevel = "info";
576
- switch (level) {
577
- case "LOG": {
578
- this._jobLogger?.log(message, data);
579
- logLevel = "log";
580
- break;
581
- }
582
- case "DEBUG": {
583
- this._jobLogger?.debug(message, data);
584
- logLevel = "debug";
585
- break;
586
- }
587
- case "INFO": {
588
- this._jobLogger?.info(message, data);
589
- logLevel = "info";
590
- break;
591
- }
592
- case "WARN": {
593
- this._jobLogger?.warn(message, data);
594
- logLevel = "warn";
595
- break;
596
- }
597
- case "ERROR": {
598
- this._jobLogger?.error(message, data);
599
- logLevel = "error";
600
- break;
601
- }
602
- }
603
- if (import_core3.Logger.satisfiesLogLevel(logLevel, this._jobLogLevel)) {
604
- await this.runTask([
605
- message,
606
- level
607
- ], async (task) => {
608
- }, {
609
- name: "log",
610
- icon: "log",
611
- description: message,
612
- params: data,
613
- properties: [
614
- {
615
- label: "Level",
616
- text: level
617
- }
618
- ],
619
- style: {
620
- style: "minimal",
621
- variant: level.toLowerCase()
622
- },
623
- noop: true
624
- });
900
+ operation: "fetch",
901
+ icon: "background",
902
+ noop: false,
903
+ properties: [
904
+ {
905
+ label: "url",
906
+ text: url,
907
+ url
908
+ },
909
+ {
910
+ label: "method",
911
+ text: requestInit?.method ?? "GET"
912
+ },
913
+ {
914
+ label: "background",
915
+ text: "true"
916
+ },
917
+ ...options?.timeout ? [
918
+ {
919
+ label: "timeout",
920
+ text: `${options.timeout.durationInMs}ms`
921
+ }
922
+ ] : []
923
+ ],
924
+ retry: {
925
+ limit: 0
625
926
  }
626
927
  });
627
928
  }
628
- async wait(key, seconds) {
629
- return await this.runTask(key, async (task) => {
929
+ async backgroundPoll(cacheKey, params) {
930
+ const urlObject = new URL(params.url);
931
+ return await this.runTask(cacheKey, async (task) => {
932
+ return task.output;
630
933
  }, {
631
- name: "wait",
632
- icon: "clock",
633
- params: {
634
- seconds
635
- },
636
- noop: true,
637
- delayUntil: new Date(Date.now() + seconds * 1e3),
638
- style: {
639
- style: "minimal"
934
+ name: `poll ${urlObject.hostname}${urlObject.pathname}`,
935
+ params,
936
+ operation: "fetch-poll",
937
+ icon: "clock-bolt",
938
+ noop: false,
939
+ properties: [
940
+ {
941
+ label: "url",
942
+ text: params.url
943
+ },
944
+ {
945
+ label: "interval",
946
+ text: `${params.interval}s`
947
+ },
948
+ {
949
+ label: "timeout",
950
+ text: `${params.timeout}s`
951
+ }
952
+ ],
953
+ retry: {
954
+ limit: 0
640
955
  }
641
956
  });
642
957
  }
643
- async createStatus(key, initialStatus) {
644
- const id = typeof key === "string" ? key : key.join("-");
645
- const status = new TriggerStatus(id, this);
646
- await status.update(key, initialStatus);
647
- return status;
648
- }
649
- async backgroundFetch(key, url, requestInit, retry2) {
958
+ async backgroundFetchResponse(cacheKey, url, requestInit, options) {
650
959
  const urlObject = new URL(url);
651
- return await this.runTask(key, async (task) => {
960
+ return await this.runTask(cacheKey, async (task) => {
652
961
  return task.output;
653
962
  }, {
654
- name: `fetch ${urlObject.hostname}${urlObject.pathname}`,
963
+ name: `fetch response ${urlObject.hostname}${urlObject.pathname}`,
655
964
  params: {
656
965
  url,
657
966
  requestInit,
658
- retry: retry2
967
+ retry: options?.retry,
968
+ timeout: options?.timeout
659
969
  },
660
- operation: "fetch",
970
+ operation: "fetch-response",
661
971
  icon: "background",
662
972
  noop: false,
663
973
  properties: [
@@ -673,19 +983,29 @@ var IO = class {
673
983
  {
674
984
  label: "background",
675
985
  text: "true"
676
- }
677
- ]
986
+ },
987
+ ...options?.timeout ? [
988
+ {
989
+ label: "timeout",
990
+ text: `${options.timeout.durationInMs}ms`
991
+ }
992
+ ] : []
993
+ ],
994
+ retry: {
995
+ limit: 0
996
+ }
678
997
  });
679
998
  }
680
- async sendEvent(key, event, options) {
681
- return await this.runTask(key, async (task) => {
999
+ async sendEvent(cacheKey, event, options) {
1000
+ return await this.runTask(cacheKey, async (task) => {
682
1001
  return await this._triggerClient.sendEvent(event, options);
683
1002
  }, {
684
- name: "sendEvent",
1003
+ name: "Send Event",
685
1004
  params: {
686
1005
  event,
687
1006
  options
688
1007
  },
1008
+ icon: "send",
689
1009
  properties: [
690
1010
  {
691
1011
  label: "name",
@@ -696,28 +1016,48 @@ var IO = class {
696
1016
  label: "ID",
697
1017
  text: event.id
698
1018
  }
699
- ] : []
1019
+ ] : [],
1020
+ ...sendEventOptionsProperties(options)
700
1021
  ]
701
1022
  });
702
1023
  }
703
- async getEvent(key, id) {
704
- return await this.runTask(key, async (task) => {
705
- return await this._triggerClient.getEvent(id);
1024
+ async sendEvents(cacheKey, events, options) {
1025
+ return await this.runTask(cacheKey, async (task) => {
1026
+ return await this._triggerClient.sendEvents(events, options);
706
1027
  }, {
707
- name: "getEvent",
1028
+ name: "Send Multiple Events",
708
1029
  params: {
709
- id
1030
+ events,
1031
+ options
710
1032
  },
1033
+ icon: "send",
711
1034
  properties: [
712
1035
  {
713
- label: "id",
1036
+ label: "Total Events",
1037
+ text: String(events.length)
1038
+ },
1039
+ ...sendEventOptionsProperties(options)
1040
+ ]
1041
+ });
1042
+ }
1043
+ async getEvent(cacheKey, id) {
1044
+ return await this.runTask(cacheKey, async (task) => {
1045
+ return await this._triggerClient.getEvent(id);
1046
+ }, {
1047
+ name: "getEvent",
1048
+ params: {
1049
+ id
1050
+ },
1051
+ properties: [
1052
+ {
1053
+ label: "id",
714
1054
  text: id
715
1055
  }
716
1056
  ]
717
1057
  });
718
1058
  }
719
- async cancelEvent(key, eventId) {
720
- return await this.runTask(key, async (task) => {
1059
+ async cancelEvent(cacheKey, eventId) {
1060
+ return await this.runTask(cacheKey, async (task) => {
721
1061
  return await this._triggerClient.cancelEvent(eventId);
722
1062
  }, {
723
1063
  name: "cancelEvent",
@@ -732,8 +1072,8 @@ var IO = class {
732
1072
  ]
733
1073
  });
734
1074
  }
735
- async updateSource(key, options) {
736
- return this.runTask(key, async (task) => {
1075
+ async updateSource(cacheKey, options) {
1076
+ return this.runTask(cacheKey, async (task) => {
737
1077
  return await this._apiClient.updateSource(this._triggerClient.id, options.key, options);
738
1078
  }, {
739
1079
  name: "Update Source",
@@ -752,8 +1092,23 @@ var IO = class {
752
1092
  }
753
1093
  });
754
1094
  }
755
- async registerInterval(key, dynamicSchedule, id, options) {
756
- return await this.runTask(key, async (task) => {
1095
+ async updateWebhook(cacheKey, options) {
1096
+ return this.runTask(cacheKey, async (task) => {
1097
+ return await this._apiClient.updateWebhook(options.key, options);
1098
+ }, {
1099
+ name: "Update Webhook Source",
1100
+ icon: "refresh",
1101
+ properties: [
1102
+ {
1103
+ label: "key",
1104
+ text: options.key
1105
+ }
1106
+ ],
1107
+ params: options
1108
+ });
1109
+ }
1110
+ async registerInterval(cacheKey, dynamicSchedule, id, options) {
1111
+ return await this.runTask(cacheKey, async (task) => {
757
1112
  return dynamicSchedule.register(id, {
758
1113
  type: "interval",
759
1114
  options
@@ -777,8 +1132,8 @@ var IO = class {
777
1132
  params: options
778
1133
  });
779
1134
  }
780
- async unregisterInterval(key, dynamicSchedule, id) {
781
- return await this.runTask(key, async (task) => {
1135
+ async unregisterInterval(cacheKey, dynamicSchedule, id) {
1136
+ return await this.runTask(cacheKey, async (task) => {
782
1137
  return dynamicSchedule.unregister(id);
783
1138
  }, {
784
1139
  name: "unregister-interval",
@@ -794,8 +1149,8 @@ var IO = class {
794
1149
  ]
795
1150
  });
796
1151
  }
797
- async registerCron(key, dynamicSchedule, id, options) {
798
- return await this.runTask(key, async (task) => {
1152
+ async registerCron(cacheKey, dynamicSchedule, id, options) {
1153
+ return await this.runTask(cacheKey, async (task) => {
799
1154
  return dynamicSchedule.register(id, {
800
1155
  type: "cron",
801
1156
  options
@@ -819,8 +1174,8 @@ var IO = class {
819
1174
  params: options
820
1175
  });
821
1176
  }
822
- async unregisterCron(key, dynamicSchedule, id) {
823
- return await this.runTask(key, async (task) => {
1177
+ async unregisterCron(cacheKey, dynamicSchedule, id) {
1178
+ return await this.runTask(cacheKey, async (task) => {
824
1179
  return dynamicSchedule.unregister(id);
825
1180
  }, {
826
1181
  name: "unregister-cron",
@@ -836,8 +1191,8 @@ var IO = class {
836
1191
  ]
837
1192
  });
838
1193
  }
839
- async registerTrigger(key, trigger, id, params) {
840
- return await this.runTask(key, async (task) => {
1194
+ async registerTrigger(cacheKey, trigger, id, params) {
1195
+ return await this.runTask(cacheKey, async (task) => {
841
1196
  const registration = await this.runTask("register-source", async (subtask1) => {
842
1197
  return trigger.register(id, params);
843
1198
  }, {
@@ -862,45 +1217,107 @@ var IO = class {
862
1217
  params
863
1218
  });
864
1219
  }
865
- async getAuth(key, clientId) {
1220
+ async getAuth(cacheKey, clientId) {
866
1221
  if (!clientId) {
867
1222
  return;
868
1223
  }
869
- return this.runTask(key, async (task) => {
1224
+ return this.runTask(cacheKey, async (task) => {
870
1225
  return await this._triggerClient.getAuth(clientId);
871
1226
  }, {
872
1227
  name: "get-auth"
873
1228
  });
874
1229
  }
875
- async runTask(key, callback, options, onError) {
1230
+ async parallel(cacheKey, items, callback, options) {
1231
+ const results = await this.runTask(cacheKey, async (task) => {
1232
+ const outcomes = await Promise.allSettled(items.map((item, index) => spaceOut(() => callback(item, index), index, 15)));
1233
+ if (outcomes.every((outcome) => outcome.status === "fulfilled")) {
1234
+ return outcomes.map((outcome) => outcome.value);
1235
+ }
1236
+ const nonInternalErrors = outcomes.filter((outcome) => outcome.status === "rejected" && !isTriggerError(outcome.reason)).map((outcome) => outcome);
1237
+ if (nonInternalErrors.length > 0) {
1238
+ throw nonInternalErrors[0].reason;
1239
+ }
1240
+ const internalErrors = outcomes.filter((outcome) => outcome.status === "rejected" && isTriggerError(outcome.reason)).map((outcome) => outcome).map((outcome) => outcome.reason);
1241
+ throw new ResumeWithParallelTaskError(task, internalErrors);
1242
+ }, {
1243
+ name: "parallel",
1244
+ parallel: true,
1245
+ ...options ?? {}
1246
+ });
1247
+ return results;
1248
+ }
1249
+ async runTask(cacheKey, callback, options, onError) {
1250
+ __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "start_task", 500);
876
1251
  const parentId = this._taskStorage.getStore()?.taskId;
877
1252
  if (parentId) {
878
1253
  this._logger.debug("Using parent task", {
879
1254
  parentId,
880
- key,
1255
+ cacheKey,
881
1256
  options
882
1257
  });
883
1258
  }
884
1259
  const idempotencyKey = await generateIdempotencyKey([
885
1260
  this._id,
886
1261
  parentId ?? "",
887
- key
1262
+ cacheKey
888
1263
  ].flat());
1264
+ if (this._visitedCacheKeys.has(idempotencyKey)) {
1265
+ if (typeof cacheKey === "string") {
1266
+ throw new Error(`Task with cacheKey "${cacheKey}" has already been executed in this run. Each task must have a unique cacheKey.`);
1267
+ } else {
1268
+ throw new Error(`Task with cacheKey "${cacheKey.join("-")}" has already been executed in this run. Each task must have a unique cacheKey.`);
1269
+ }
1270
+ }
1271
+ this._visitedCacheKeys.add(idempotencyKey);
889
1272
  const cachedTask = this._cachedTasks.get(idempotencyKey);
890
1273
  if (cachedTask && cachedTask.status === "COMPLETED") {
891
1274
  this._logger.debug("Using completed cached task", {
892
- idempotencyKey,
893
- cachedTask
1275
+ idempotencyKey
894
1276
  });
895
- return cachedTask.output;
1277
+ this._stats.cachedTaskHits++;
1278
+ return options?.parseOutput ? options.parseOutput(cachedTask.output) : cachedTask.output;
1279
+ }
1280
+ if (options?.noop && this._noopTasksBloomFilter) {
1281
+ if (this._noopTasksBloomFilter.test(idempotencyKey)) {
1282
+ this._logger.debug("task idempotency key exists in noopTasksBloomFilter", {
1283
+ idempotencyKey
1284
+ });
1285
+ this._stats.noopCachedTaskHits++;
1286
+ return {};
1287
+ }
896
1288
  }
897
- const task = await this._apiClient.runTask(this._id, {
1289
+ const runOptions = {
1290
+ ...options ?? {},
1291
+ parseOutput: void 0
1292
+ };
1293
+ const response = await this._apiClient.runTask(this._id, {
898
1294
  idempotencyKey,
899
- displayKey: typeof key === "string" ? key : key.join("."),
1295
+ displayKey: typeof cacheKey === "string" ? cacheKey : void 0,
900
1296
  noop: false,
901
- ...options ?? {},
1297
+ ...runOptions ?? {},
902
1298
  parentId
1299
+ }, {
1300
+ cachedTasksCursor: this._cachedTasksCursor
903
1301
  });
1302
+ const task = response.version === import_core2.API_VERSIONS.LAZY_LOADED_CACHED_TASKS ? response.body.task : response.body;
1303
+ if (task.forceYield) {
1304
+ this._logger.debug("Forcing yield after run task", {
1305
+ idempotencyKey
1306
+ });
1307
+ __privateMethod(this, _forceYield, forceYield_fn).call(this, "after_run_task");
1308
+ }
1309
+ if (response.version === import_core2.API_VERSIONS.LAZY_LOADED_CACHED_TASKS) {
1310
+ this._cachedTasksCursor = response.body.cachedTasks?.cursor;
1311
+ for (const cachedTask2 of response.body.cachedTasks?.tasks ?? []) {
1312
+ if (!this._cachedTasks.has(cachedTask2.idempotencyKey)) {
1313
+ this._cachedTasks.set(cachedTask2.idempotencyKey, cachedTask2);
1314
+ this._logger.debug("Injecting lazy loaded task into task cache", {
1315
+ idempotencyKey: cachedTask2.idempotencyKey
1316
+ });
1317
+ this._stats.lazyLoadedCachedTasks++;
1318
+ }
1319
+ }
1320
+ }
904
1321
  if (task.status === "CANCELED") {
905
1322
  this._logger.debug("Task canceled", {
906
1323
  idempotencyKey,
@@ -909,50 +1326,61 @@ var IO = class {
909
1326
  throw new CanceledWithTaskError(task);
910
1327
  }
911
1328
  if (task.status === "COMPLETED") {
912
- this._logger.debug("Using task output", {
913
- idempotencyKey,
914
- task
915
- });
916
- __privateMethod(this, _addToCachedTasks, addToCachedTasks_fn).call(this, task);
917
- return task.output;
1329
+ if (task.noop) {
1330
+ this._logger.debug("Noop Task completed", {
1331
+ idempotencyKey
1332
+ });
1333
+ this._noopTasksBloomFilter?.add(task.idempotencyKey);
1334
+ } else {
1335
+ this._logger.debug("Cache miss", {
1336
+ idempotencyKey
1337
+ });
1338
+ this._stats.cachedTaskMisses++;
1339
+ __privateMethod(this, _addToCachedTasks, addToCachedTasks_fn).call(this, task);
1340
+ }
1341
+ return options?.parseOutput ? options.parseOutput(task.output) : task.output;
918
1342
  }
919
1343
  if (task.status === "ERRORED") {
920
1344
  this._logger.debug("Task errored", {
921
1345
  idempotencyKey,
922
1346
  task
923
1347
  });
924
- throw new Error(task.error ?? task?.output ? JSON.stringify(task.output) : "Task errored");
925
- }
926
- if (task.status === "WAITING") {
927
- this._logger.debug("Task waiting", {
928
- idempotencyKey,
929
- task
930
- });
931
- throw new ResumeWithTaskError(task);
932
- }
933
- if (task.status === "RUNNING" && typeof task.operation === "string") {
934
- this._logger.debug("Task running operation", {
935
- idempotencyKey,
936
- task
937
- });
938
- throw new ResumeWithTaskError(task);
1348
+ throw new ErrorWithTask(task, task.error ?? task?.output ? JSON.stringify(task.output) : "Task errored");
939
1349
  }
1350
+ __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "before_execute_task", 1500);
940
1351
  const executeTask = /* @__PURE__ */ __name(async () => {
941
1352
  try {
942
1353
  const result = await callback(task, this);
943
- const output = import_core3.SerializableJsonSchema.parse(result);
1354
+ if (task.status === "WAITING" && task.callbackUrl) {
1355
+ this._logger.debug("Waiting for remote callback", {
1356
+ idempotencyKey,
1357
+ task
1358
+ });
1359
+ return {};
1360
+ }
1361
+ const output = this._outputSerializer.serialize(result);
944
1362
  this._logger.debug("Completing using output", {
945
1363
  idempotencyKey,
946
1364
  task
947
1365
  });
1366
+ __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "before_complete_task", 500, task, output);
948
1367
  const completedTask = await this._apiClient.completeTask(this._id, task.id, {
949
- output: output ?? void 0,
1368
+ output,
950
1369
  properties: task.outputProperties ?? void 0
951
1370
  });
1371
+ if (completedTask.forceYield) {
1372
+ this._logger.debug("Forcing yield after task completed", {
1373
+ idempotencyKey
1374
+ });
1375
+ __privateMethod(this, _forceYield, forceYield_fn).call(this, "after_complete_task");
1376
+ }
1377
+ this._stats.executedTasks++;
952
1378
  if (completedTask.status === "CANCELED") {
953
1379
  throw new CanceledWithTaskError(completedTask);
954
1380
  }
955
- return output;
1381
+ __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "after_complete_task", 500);
1382
+ const deserializedOutput = this._outputSerializer.deserialize(output);
1383
+ return options?.parseOutput ? options.parseOutput(deserializedOutput) : deserializedOutput;
956
1384
  } catch (error) {
957
1385
  if (isTriggerError(error)) {
958
1386
  throw error;
@@ -967,7 +1395,7 @@ var IO = class {
967
1395
  } else {
968
1396
  skipRetrying = !!onErrorResult.skipRetrying;
969
1397
  if (onErrorResult.retryAt && !skipRetrying) {
970
- const parsedError2 = import_core3.ErrorWithStackSchema.safeParse(onErrorResult.error);
1398
+ const parsedError2 = import_core2.ErrorWithStackSchema.safeParse(onErrorResult.error);
971
1399
  throw new RetryWithTaskError(parsedError2.success ? parsedError2.data : {
972
1400
  message: "Unknown error"
973
1401
  }, task, onErrorResult.retryAt);
@@ -981,9 +1409,14 @@ var IO = class {
981
1409
  error = innerError;
982
1410
  }
983
1411
  }
984
- const parsedError = import_core3.ErrorWithStackSchema.safeParse(error);
1412
+ if (error instanceof ErrorWithTask) {
1413
+ await this._apiClient.failTask(this._id, task.id, {
1414
+ error: error.cause.output
1415
+ });
1416
+ }
1417
+ const parsedError = import_core2.ErrorWithStackSchema.safeParse(error);
985
1418
  if (options?.retry && !skipRetrying) {
986
- const retryAt = (0, import_core2.calculateRetryAt)(options.retry, task.attempts - 1);
1419
+ const retryAt = (0, import_core.calculateRetryAt)(options.retry, task.attempts - 1);
987
1420
  if (retryAt) {
988
1421
  throw new RetryWithTaskError(parsedError.success ? parsedError.data : {
989
1422
  message: "Unknown error"
@@ -995,20 +1428,50 @@ var IO = class {
995
1428
  error: parsedError.data
996
1429
  });
997
1430
  } else {
1431
+ const message = typeof error === "string" ? error : JSON.stringify(error);
998
1432
  await this._apiClient.failTask(this._id, task.id, {
999
1433
  error: {
1000
- message: JSON.stringify(error),
1001
- name: "Unknown Error"
1434
+ name: "Unknown error",
1435
+ message
1002
1436
  }
1003
1437
  });
1004
1438
  }
1005
1439
  throw error;
1006
1440
  }
1007
1441
  }, "executeTask");
1442
+ if (task.status === "WAITING") {
1443
+ this._logger.debug("Task waiting", {
1444
+ idempotencyKey,
1445
+ task
1446
+ });
1447
+ if (task.callbackUrl) {
1448
+ await this._taskStorage.run({
1449
+ taskId: task.id
1450
+ }, executeTask);
1451
+ }
1452
+ throw new ResumeWithTaskError(task);
1453
+ }
1454
+ if (task.status === "RUNNING" && typeof task.operation === "string") {
1455
+ this._logger.debug("Task running operation", {
1456
+ idempotencyKey,
1457
+ task
1458
+ });
1459
+ throw new ResumeWithTaskError(task);
1460
+ }
1008
1461
  return this._taskStorage.run({
1009
1462
  taskId: task.id
1010
1463
  }, executeTask);
1011
1464
  }
1465
+ yield(cacheKey) {
1466
+ if (!(0, import_core2.supportsFeature)("yieldExecution", this._serverVersion)) {
1467
+ 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.");
1468
+ return;
1469
+ }
1470
+ if (this._yieldedExecutions.includes(cacheKey)) {
1471
+ return;
1472
+ }
1473
+ throw new YieldExecutionError(cacheKey);
1474
+ }
1012
1475
  async try(tryCallback, catchCallback) {
1013
1476
  try {
1014
1477
  return await tryCallback();
@@ -1019,12 +1482,52 @@ var IO = class {
1019
1482
  return await catchCallback(error);
1020
1483
  }
1021
1484
  }
1485
+ get store() {
1486
+ return {
1487
+ env: this._envStore,
1488
+ job: this._jobStore,
1489
+ run: this._runStore
1490
+ };
1491
+ }
1022
1492
  };
1023
1493
  __name(IO, "IO");
1024
1494
  _addToCachedTasks = new WeakSet();
1025
1495
  addToCachedTasks_fn = /* @__PURE__ */ __name(function(task) {
1026
1496
  this._cachedTasks.set(task.idempotencyKey, task);
1027
1497
  }, "#addToCachedTasks");
1498
+ _detectAutoYield = new WeakSet();
1499
+ detectAutoYield_fn = /* @__PURE__ */ __name(function(location, threshold = 1500, task1, output) {
1500
+ const timeRemaining = __privateMethod(this, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn).call(this);
1501
+ if (timeRemaining && timeRemaining < threshold) {
1502
+ if (task1) {
1503
+ throw new AutoYieldWithCompletedTaskExecutionError(task1.id, task1.outputProperties ?? [], {
1504
+ location,
1505
+ timeRemaining,
1506
+ timeElapsed: __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this)
1507
+ }, output);
1508
+ } else {
1509
+ throw new AutoYieldExecutionError(location, timeRemaining, __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this));
1510
+ }
1511
+ }
1512
+ }, "#detectAutoYield");
1513
+ _forceYield = new WeakSet();
1514
+ forceYield_fn = /* @__PURE__ */ __name(function(location1) {
1515
+ const timeRemaining = __privateMethod(this, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn).call(this);
1516
+ if (timeRemaining) {
1517
+ throw new AutoYieldExecutionError(location1, timeRemaining, __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this));
1518
+ }
1519
+ }, "#forceYield");
1520
+ _getTimeElapsed = new WeakSet();
1521
+ getTimeElapsed_fn = /* @__PURE__ */ __name(function() {
1522
+ return performance.now() - this._timeOrigin;
1523
+ }, "#getTimeElapsed");
1524
+ _getRemainingTimeInMillis = new WeakSet();
1525
+ getRemainingTimeInMillis_fn = /* @__PURE__ */ __name(function() {
1526
+ if (this._executionTimeout) {
1527
+ return this._executionTimeout - (performance.now() - this._timeOrigin);
1528
+ }
1529
+ return void 0;
1530
+ }, "#getRemainingTimeInMillis");
1028
1531
  async function generateIdempotencyKey(keyMaterial) {
1029
1532
  const keys = keyMaterial.map((key2) => {
1030
1533
  if (typeof key2 === "string") {
@@ -1061,23 +1564,803 @@ var IOLogger = class {
1061
1564
  constructor(callback) {
1062
1565
  this.callback = callback;
1063
1566
  }
1064
- log(message, properties) {
1065
- return this.callback("LOG", message, properties);
1567
+ log(message, properties) {
1568
+ return this.callback("LOG", message, properties);
1569
+ }
1570
+ debug(message, properties) {
1571
+ return this.callback("DEBUG", message, properties);
1572
+ }
1573
+ info(message, properties) {
1574
+ return this.callback("INFO", message, properties);
1575
+ }
1576
+ warn(message, properties) {
1577
+ return this.callback("WARN", message, properties);
1578
+ }
1579
+ error(message, properties) {
1580
+ return this.callback("ERROR", message, properties);
1581
+ }
1582
+ };
1583
+ __name(IOLogger, "IOLogger");
1584
+ async function spaceOut(callback, index, delay) {
1585
+ await new Promise((resolve) => setTimeout(resolve, index * delay));
1586
+ return await callback();
1587
+ }
1588
+ __name(spaceOut, "spaceOut");
1589
+ function sendEventOptionsProperties(options) {
1590
+ return [
1591
+ ...options?.accountId ? [
1592
+ {
1593
+ label: "Account ID",
1594
+ text: options.accountId
1595
+ }
1596
+ ] : [],
1597
+ ...options?.deliverAfter ? [
1598
+ {
1599
+ label: "Deliver After",
1600
+ text: `${options.deliverAfter}s`
1601
+ }
1602
+ ] : [],
1603
+ ...options?.deliverAt ? [
1604
+ {
1605
+ label: "Deliver At",
1606
+ text: options.deliverAt.toISOString()
1607
+ }
1608
+ ] : []
1609
+ ];
1610
+ }
1611
+ __name(sendEventOptionsProperties, "sendEventOptionsProperties");
1612
+
1613
+ // src/store/keyValueStoreClient.ts
1614
+ var _serializer, _namespacedKey2, namespacedKey_fn2;
1615
+ var KeyValueStoreClient = class {
1616
+ constructor(queryStore, type = null, namespace = "") {
1617
+ __privateAdd(this, _namespacedKey2);
1618
+ __privateAdd(this, _serializer, void 0);
1619
+ this.queryStore = queryStore;
1620
+ this.type = type;
1621
+ this.namespace = namespace;
1622
+ __privateSet(this, _serializer, new JSONOutputSerializer());
1623
+ }
1624
+ async delete(key) {
1625
+ const result = await this.queryStore("DELETE", {
1626
+ key: __privateMethod(this, _namespacedKey2, namespacedKey_fn2).call(this, key)
1627
+ });
1628
+ if (result.action !== "DELETE") {
1629
+ throw new Error(`Unexpected key-value store response: ${result.action}`);
1630
+ }
1631
+ return result.deleted;
1632
+ }
1633
+ async get(key) {
1634
+ const result = await this.queryStore("GET", {
1635
+ key: __privateMethod(this, _namespacedKey2, namespacedKey_fn2).call(this, key)
1636
+ });
1637
+ if (result.action !== "GET") {
1638
+ throw new Error(`Unexpected key-value store response: ${result.action}`);
1639
+ }
1640
+ return __privateGet(this, _serializer).deserialize(result.value);
1641
+ }
1642
+ async has(key) {
1643
+ const result = await this.queryStore("HAS", {
1644
+ key: __privateMethod(this, _namespacedKey2, namespacedKey_fn2).call(this, key)
1645
+ });
1646
+ if (result.action !== "HAS") {
1647
+ throw new Error(`Unexpected key-value store response: ${result.action}`);
1648
+ }
1649
+ return result.has;
1650
+ }
1651
+ async set(key, value) {
1652
+ const result = await this.queryStore("SET", {
1653
+ key: __privateMethod(this, _namespacedKey2, namespacedKey_fn2).call(this, key),
1654
+ value: __privateGet(this, _serializer).serialize(value)
1655
+ });
1656
+ if (result.action !== "SET") {
1657
+ throw new Error(`Unexpected key-value store response: ${result.action}`);
1658
+ }
1659
+ return __privateGet(this, _serializer).deserialize(result.value);
1660
+ }
1661
+ };
1662
+ __name(KeyValueStoreClient, "KeyValueStoreClient");
1663
+ _serializer = new WeakMap();
1664
+ _namespacedKey2 = new WeakSet();
1665
+ namespacedKey_fn2 = /* @__PURE__ */ __name(function(key) {
1666
+ const parts = [];
1667
+ if (this.type) {
1668
+ parts.push(this.type);
1669
+ }
1670
+ if (this.namespace) {
1671
+ parts.push(this.namespace);
1672
+ }
1673
+ parts.push(key);
1674
+ return parts.join(":");
1675
+ }, "#namespacedKey");
1676
+
1677
+ // src/apiClient.ts
1678
+ var _apiUrl, _options, _logger, _storeClient, _queryKeyValueStore, queryKeyValueStore_fn, _apiKey, apiKey_fn;
1679
+ var ApiClient = class {
1680
+ constructor(options) {
1681
+ __privateAdd(this, _queryKeyValueStore);
1682
+ __privateAdd(this, _apiKey);
1683
+ __privateAdd(this, _apiUrl, void 0);
1684
+ __privateAdd(this, _options, void 0);
1685
+ __privateAdd(this, _logger, void 0);
1686
+ __privateAdd(this, _storeClient, void 0);
1687
+ __privateSet(this, _options, options);
1688
+ __privateSet(this, _apiUrl, __privateGet(this, _options).apiUrl ?? process.env.TRIGGER_API_URL ?? "https://api.trigger.dev");
1689
+ __privateSet(this, _logger, new import_core3.Logger("trigger.dev", __privateGet(this, _options).logLevel));
1690
+ __privateSet(this, _storeClient, new KeyValueStoreClient(__privateMethod(this, _queryKeyValueStore, queryKeyValueStore_fn).bind(this)));
1691
+ }
1692
+ async registerEndpoint(options) {
1693
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1694
+ __privateGet(this, _logger).debug("Registering endpoint", {
1695
+ url: options.url,
1696
+ name: options.name
1697
+ });
1698
+ const response = await fetch(`${__privateGet(this, _apiUrl)}/api/v1/endpoints`, {
1699
+ method: "POST",
1700
+ headers: {
1701
+ "Content-Type": "application/json",
1702
+ Authorization: `Bearer ${apiKey}`
1703
+ },
1704
+ body: JSON.stringify({
1705
+ url: options.url,
1706
+ name: options.name
1707
+ })
1708
+ });
1709
+ if (response.status >= 400 && response.status < 500) {
1710
+ const body = await response.json();
1711
+ throw new Error(body.error);
1712
+ }
1713
+ if (response.status !== 200) {
1714
+ throw new Error(`Failed to register entry point, got status code ${response.status}`);
1715
+ }
1716
+ return await response.json();
1717
+ }
1718
+ async runTask(runId, task, options = {}) {
1719
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1720
+ __privateGet(this, _logger).debug("Running Task", {
1721
+ task
1722
+ });
1723
+ return await zodfetchWithVersions({
1724
+ [import_core3.API_VERSIONS.LAZY_LOADED_CACHED_TASKS]: import_core3.RunTaskResponseWithCachedTasksBodySchema
1725
+ }, import_core3.ServerTaskSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/tasks`, {
1726
+ method: "POST",
1727
+ headers: {
1728
+ "Content-Type": "application/json",
1729
+ Authorization: `Bearer ${apiKey}`,
1730
+ "Idempotency-Key": task.idempotencyKey,
1731
+ "X-Cached-Tasks-Cursor": options.cachedTasksCursor ?? "",
1732
+ "Trigger-Version": import_core3.API_VERSIONS.LAZY_LOADED_CACHED_TASKS
1733
+ },
1734
+ body: JSON.stringify(task)
1735
+ });
1736
+ }
1737
+ async completeTask(runId, id, task) {
1738
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1739
+ __privateGet(this, _logger).debug("Complete Task", {
1740
+ task
1741
+ });
1742
+ return await zodfetch(import_core3.ServerTaskSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/tasks/${id}/complete`, {
1743
+ method: "POST",
1744
+ headers: {
1745
+ "Content-Type": "application/json",
1746
+ Authorization: `Bearer ${apiKey}`,
1747
+ "Trigger-Version": import_core3.API_VERSIONS.SERIALIZED_TASK_OUTPUT
1748
+ },
1749
+ body: JSON.stringify(task)
1750
+ });
1751
+ }
1752
+ async failTask(runId, id, body) {
1753
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1754
+ __privateGet(this, _logger).debug("Fail Task", {
1755
+ id,
1756
+ runId,
1757
+ body
1758
+ });
1759
+ return await zodfetch(import_core3.ServerTaskSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/tasks/${id}/fail`, {
1760
+ method: "POST",
1761
+ headers: {
1762
+ "Content-Type": "application/json",
1763
+ Authorization: `Bearer ${apiKey}`
1764
+ },
1765
+ body: JSON.stringify(body)
1766
+ });
1767
+ }
1768
+ async sendEvent(event, options = {}) {
1769
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1770
+ __privateGet(this, _logger).debug("Sending event", {
1771
+ event
1772
+ });
1773
+ return await zodfetch(import_core3.ApiEventLogSchema, `${__privateGet(this, _apiUrl)}/api/v1/events`, {
1774
+ method: "POST",
1775
+ headers: {
1776
+ "Content-Type": "application/json",
1777
+ Authorization: `Bearer ${apiKey}`
1778
+ },
1779
+ body: JSON.stringify({
1780
+ event,
1781
+ options
1782
+ })
1783
+ });
1784
+ }
1785
+ async sendEvents(events, options = {}) {
1786
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1787
+ __privateGet(this, _logger).debug("Sending multiple events", {
1788
+ events
1789
+ });
1790
+ return await zodfetch(import_core3.ApiEventLogSchema.array(), `${__privateGet(this, _apiUrl)}/api/v1/events/bulk`, {
1791
+ method: "POST",
1792
+ headers: {
1793
+ "Content-Type": "application/json",
1794
+ Authorization: `Bearer ${apiKey}`
1795
+ },
1796
+ body: JSON.stringify({
1797
+ events,
1798
+ options
1799
+ })
1800
+ });
1801
+ }
1802
+ async cancelEvent(eventId) {
1803
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1804
+ __privateGet(this, _logger).debug("Cancelling event", {
1805
+ eventId
1806
+ });
1807
+ return await zodfetch(import_core3.ApiEventLogSchema, `${__privateGet(this, _apiUrl)}/api/v1/events/${eventId}/cancel`, {
1808
+ method: "POST",
1809
+ headers: {
1810
+ "Content-Type": "application/json",
1811
+ Authorization: `Bearer ${apiKey}`
1812
+ }
1813
+ });
1814
+ }
1815
+ async cancelRunsForEvent(eventId) {
1816
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1817
+ __privateGet(this, _logger).debug("Cancelling runs for event", {
1818
+ eventId
1819
+ });
1820
+ return await zodfetch(import_core3.CancelRunsForEventSchema, `${__privateGet(this, _apiUrl)}/api/v1/events/${eventId}/cancel-runs`, {
1821
+ method: "POST",
1822
+ headers: {
1823
+ "Content-Type": "application/json",
1824
+ Authorization: `Bearer ${apiKey}`
1825
+ }
1826
+ });
1827
+ }
1828
+ async updateStatus(runId, id, status) {
1829
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1830
+ __privateGet(this, _logger).debug("Update status", {
1831
+ id,
1832
+ status
1833
+ });
1834
+ return await zodfetch(import_core3.JobRunStatusRecordSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/statuses/${id}`, {
1835
+ method: "PUT",
1836
+ headers: {
1837
+ "Content-Type": "application/json",
1838
+ Authorization: `Bearer ${apiKey}`
1839
+ },
1840
+ body: JSON.stringify(status)
1841
+ });
1842
+ }
1843
+ async updateSource(client, key, source) {
1844
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1845
+ __privateGet(this, _logger).debug("activating http source", {
1846
+ source
1847
+ });
1848
+ const response = await zodfetch(import_core3.TriggerSourceSchema, `${__privateGet(this, _apiUrl)}/api/v2/${client}/sources/${key}`, {
1849
+ method: "PUT",
1850
+ headers: {
1851
+ "Content-Type": "application/json",
1852
+ Authorization: `Bearer ${apiKey}`
1853
+ },
1854
+ body: JSON.stringify(source)
1855
+ });
1856
+ return response;
1857
+ }
1858
+ async updateWebhook(key, webhookData) {
1859
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1860
+ __privateGet(this, _logger).debug("activating webhook", {
1861
+ webhookData
1862
+ });
1863
+ const response = await zodfetch(import_core3.TriggerSourceSchema, `${__privateGet(this, _apiUrl)}/api/v1/webhooks/${key}`, {
1864
+ method: "PUT",
1865
+ headers: {
1866
+ "Content-Type": "application/json",
1867
+ Authorization: `Bearer ${apiKey}`
1868
+ },
1869
+ body: JSON.stringify(webhookData)
1870
+ });
1871
+ return response;
1872
+ }
1873
+ async registerTrigger(client, id, key, payload, idempotencyKey) {
1874
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1875
+ __privateGet(this, _logger).debug("registering trigger", {
1876
+ id,
1877
+ payload
1878
+ });
1879
+ const headers = {
1880
+ "Content-Type": "application/json",
1881
+ Authorization: `Bearer ${apiKey}`
1882
+ };
1883
+ if (idempotencyKey) {
1884
+ headers["Idempotency-Key"] = idempotencyKey;
1885
+ }
1886
+ const response = await zodfetch(import_core3.RegisterSourceEventSchemaV2, `${__privateGet(this, _apiUrl)}/api/v2/${client}/triggers/${id}/registrations/${key}`, {
1887
+ method: "PUT",
1888
+ headers,
1889
+ body: JSON.stringify(payload)
1890
+ });
1891
+ return response;
1892
+ }
1893
+ async registerSchedule(client, id, key, payload) {
1894
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1895
+ __privateGet(this, _logger).debug("registering schedule", {
1896
+ id,
1897
+ payload
1898
+ });
1899
+ const response = await zodfetch(import_core3.RegisterScheduleResponseBodySchema, `${__privateGet(this, _apiUrl)}/api/v1/${client}/schedules/${id}/registrations`, {
1900
+ method: "POST",
1901
+ headers: {
1902
+ "Content-Type": "application/json",
1903
+ Authorization: `Bearer ${apiKey}`
1904
+ },
1905
+ body: JSON.stringify({
1906
+ id: key,
1907
+ ...payload
1908
+ })
1909
+ });
1910
+ return response;
1911
+ }
1912
+ async unregisterSchedule(client, id, key) {
1913
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1914
+ __privateGet(this, _logger).debug("unregistering schedule", {
1915
+ id
1916
+ });
1917
+ const response = await zodfetch(import_zod3.z.object({
1918
+ ok: import_zod3.z.boolean()
1919
+ }), `${__privateGet(this, _apiUrl)}/api/v1/${client}/schedules/${id}/registrations/${encodeURIComponent(key)}`, {
1920
+ method: "DELETE",
1921
+ headers: {
1922
+ "Content-Type": "application/json",
1923
+ Authorization: `Bearer ${apiKey}`
1924
+ }
1925
+ });
1926
+ return response;
1927
+ }
1928
+ async getAuth(client, id) {
1929
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1930
+ __privateGet(this, _logger).debug("getting auth", {
1931
+ id
1932
+ });
1933
+ const response = await zodfetch(import_core3.ConnectionAuthSchema, `${__privateGet(this, _apiUrl)}/api/v1/${client}/auth/${id}`, {
1934
+ method: "GET",
1935
+ headers: {
1936
+ Accept: "application/json",
1937
+ Authorization: `Bearer ${apiKey}`
1938
+ }
1939
+ }, {
1940
+ optional: true
1941
+ });
1942
+ return response;
1943
+ }
1944
+ async getEvent(eventId) {
1945
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1946
+ __privateGet(this, _logger).debug("Getting Event", {
1947
+ eventId
1948
+ });
1949
+ return await zodfetch(import_core3.GetEventSchema, `${__privateGet(this, _apiUrl)}/api/v1/events/${eventId}`, {
1950
+ method: "GET",
1951
+ headers: {
1952
+ Authorization: `Bearer ${apiKey}`
1953
+ }
1954
+ });
1955
+ }
1956
+ async getRun(runId, options) {
1957
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1958
+ __privateGet(this, _logger).debug("Getting Run", {
1959
+ runId
1960
+ });
1961
+ return await zodfetch(import_core3.GetRunSchema, (0, import_core3.urlWithSearchParams)(`${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}`, options), {
1962
+ method: "GET",
1963
+ headers: {
1964
+ Authorization: `Bearer ${apiKey}`
1965
+ }
1966
+ });
1967
+ }
1968
+ async cancelRun(runId) {
1969
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1970
+ __privateGet(this, _logger).debug("Cancelling Run", {
1971
+ runId
1972
+ });
1973
+ return await zodfetch(import_core3.GetRunSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/cancel`, {
1974
+ method: "POST",
1975
+ headers: {
1976
+ "Content-Type": "application/json",
1977
+ Authorization: `Bearer ${apiKey}`
1978
+ }
1979
+ });
1980
+ }
1981
+ async getRunStatuses(runId) {
1982
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1983
+ __privateGet(this, _logger).debug("Getting Run statuses", {
1984
+ runId
1985
+ });
1986
+ return await zodfetch(import_core3.GetRunStatusesSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/statuses`, {
1987
+ method: "GET",
1988
+ headers: {
1989
+ Authorization: `Bearer ${apiKey}`
1990
+ }
1991
+ });
1992
+ }
1993
+ async getRuns(jobSlug, options) {
1994
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1995
+ __privateGet(this, _logger).debug("Getting Runs", {
1996
+ jobSlug
1997
+ });
1998
+ return await zodfetch(import_core3.GetRunsSchema, (0, import_core3.urlWithSearchParams)(`${__privateGet(this, _apiUrl)}/api/v1/jobs/${jobSlug}/runs`, options), {
1999
+ method: "GET",
2000
+ headers: {
2001
+ Authorization: `Bearer ${apiKey}`
2002
+ }
2003
+ });
2004
+ }
2005
+ async invokeJob(jobId, payload, options = {}) {
2006
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2007
+ __privateGet(this, _logger).debug("Invoking Job", {
2008
+ jobId
2009
+ });
2010
+ const body = {
2011
+ payload,
2012
+ context: options.context ?? {},
2013
+ options: {
2014
+ accountId: options.accountId,
2015
+ callbackUrl: options.callbackUrl
2016
+ }
2017
+ };
2018
+ return await zodfetch(import_core3.InvokeJobResponseSchema, `${__privateGet(this, _apiUrl)}/api/v1/jobs/${jobId}/invoke`, {
2019
+ method: "POST",
2020
+ headers: {
2021
+ "Content-Type": "application/json",
2022
+ Authorization: `Bearer ${apiKey}`,
2023
+ ...options.idempotencyKey ? {
2024
+ "Idempotency-Key": options.idempotencyKey
2025
+ } : {}
2026
+ },
2027
+ body: JSON.stringify(body)
2028
+ });
2029
+ }
2030
+ async createEphemeralEventDispatcher(payload) {
2031
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2032
+ __privateGet(this, _logger).debug("Creating ephemeral event dispatcher", {
2033
+ payload
2034
+ });
2035
+ const response = await zodfetch(import_core3.EphemeralEventDispatcherResponseBodySchema, `${__privateGet(this, _apiUrl)}/api/v1/event-dispatchers/ephemeral`, {
2036
+ method: "POST",
2037
+ headers: {
2038
+ "Content-Type": "application/json",
2039
+ Authorization: `Bearer ${apiKey}`
2040
+ },
2041
+ body: JSON.stringify(payload)
2042
+ });
2043
+ return response;
2044
+ }
2045
+ get store() {
2046
+ return __privateGet(this, _storeClient);
2047
+ }
2048
+ };
2049
+ __name(ApiClient, "ApiClient");
2050
+ _apiUrl = new WeakMap();
2051
+ _options = new WeakMap();
2052
+ _logger = new WeakMap();
2053
+ _storeClient = new WeakMap();
2054
+ _queryKeyValueStore = new WeakSet();
2055
+ queryKeyValueStore_fn = /* @__PURE__ */ __name(async function(action, data) {
2056
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2057
+ __privateGet(this, _logger).debug("accessing key-value store", {
2058
+ action,
2059
+ data
2060
+ });
2061
+ const encodedKey = encodeURIComponent(data.key);
2062
+ const STORE_URL = `${__privateGet(this, _apiUrl)}/api/v1/store/${encodedKey}`;
2063
+ const authHeader = {
2064
+ Authorization: `Bearer ${apiKey}`
2065
+ };
2066
+ let requestInit;
2067
+ switch (action) {
2068
+ case "DELETE": {
2069
+ requestInit = {
2070
+ method: "DELETE",
2071
+ headers: authHeader
2072
+ };
2073
+ break;
2074
+ }
2075
+ case "GET": {
2076
+ requestInit = {
2077
+ method: "GET",
2078
+ headers: authHeader
2079
+ };
2080
+ break;
2081
+ }
2082
+ case "HAS": {
2083
+ const headResponse = await fetchHead(STORE_URL, {
2084
+ headers: authHeader
2085
+ });
2086
+ return {
2087
+ action: "HAS",
2088
+ key: encodedKey,
2089
+ has: !!headResponse.ok
2090
+ };
2091
+ }
2092
+ case "SET": {
2093
+ const MAX_BODY_BYTE_LENGTH = 256 * 1024;
2094
+ if ((data.value?.length ?? 0) > MAX_BODY_BYTE_LENGTH) {
2095
+ throw new Error(`Max request body size exceeded: ${MAX_BODY_BYTE_LENGTH} bytes`);
2096
+ }
2097
+ requestInit = {
2098
+ method: "PUT",
2099
+ headers: {
2100
+ ...authHeader,
2101
+ "Content-Type": "text/plain"
2102
+ },
2103
+ body: data.value
2104
+ };
2105
+ break;
2106
+ }
2107
+ default: {
2108
+ (0, import_core3.assertExhaustive)(action);
2109
+ }
2110
+ }
2111
+ const response = await zodfetch(import_core3.KeyValueStoreResponseBodySchema, STORE_URL, requestInit);
2112
+ return response;
2113
+ }, "#queryKeyValueStore");
2114
+ _apiKey = new WeakSet();
2115
+ apiKey_fn = /* @__PURE__ */ __name(async function() {
2116
+ const apiKey = getApiKey(__privateGet(this, _options).apiKey);
2117
+ if (apiKey.status === "invalid") {
2118
+ throw new Error("Invalid API key");
2119
+ } else if (apiKey.status === "missing") {
2120
+ throw new Error("Missing API key");
2121
+ }
2122
+ return apiKey.apiKey;
2123
+ }, "#apiKey");
2124
+ function getApiKey(key) {
2125
+ const apiKey = key ?? process.env.TRIGGER_API_KEY;
2126
+ if (!apiKey) {
2127
+ return {
2128
+ status: "missing"
2129
+ };
2130
+ }
2131
+ const isValid = apiKey.match(/^tr_[a-z]+_[a-zA-Z0-9]+$/);
2132
+ if (!isValid) {
2133
+ return {
2134
+ status: "invalid",
2135
+ apiKey
2136
+ };
2137
+ }
2138
+ return {
2139
+ status: "valid",
2140
+ apiKey
2141
+ };
2142
+ }
2143
+ __name(getApiKey, "getApiKey");
2144
+ async function zodfetchWithVersions(versionedSchemaMap, unversionedSchema, url, requestInit, options, retryCount = 0) {
2145
+ const response = await fetch(url, {
2146
+ ...requestInit,
2147
+ cache: "no-cache"
2148
+ });
2149
+ if ((!requestInit || requestInit.method === "GET") && response.status === 404 && options?.optional) {
2150
+ return;
2151
+ }
2152
+ if (response.status >= 400 && response.status < 500) {
2153
+ const body = await response.json();
2154
+ throw new Error(body.error);
2155
+ }
2156
+ if (response.status >= 500 && retryCount < 6) {
2157
+ const delay = exponentialBackoff(retryCount + 1, 2, 50, 1150, 50);
2158
+ await new Promise((resolve) => setTimeout(resolve, delay));
2159
+ return zodfetchWithVersions(versionedSchemaMap, unversionedSchema, url, requestInit, options, retryCount + 1);
2160
+ }
2161
+ if (response.status !== 200) {
2162
+ throw new Error(options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`);
2163
+ }
2164
+ const jsonBody = await response.json();
2165
+ const version2 = response.headers.get("trigger-version");
2166
+ if (!version2) {
2167
+ return {
2168
+ version: "unversioned",
2169
+ body: unversionedSchema.parse(jsonBody)
2170
+ };
2171
+ }
2172
+ const versionedSchema = versionedSchemaMap[version2];
2173
+ if (!versionedSchema) {
2174
+ throw new Error(`Unknown version ${version2}`);
2175
+ }
2176
+ return {
2177
+ version: version2,
2178
+ body: versionedSchema.parse(jsonBody)
2179
+ };
2180
+ }
2181
+ __name(zodfetchWithVersions, "zodfetchWithVersions");
2182
+ async function fetchHead(url, requestInitWithoutMethod, retryCount = 0) {
2183
+ const requestInit = {
2184
+ ...requestInitWithoutMethod,
2185
+ method: "HEAD"
2186
+ };
2187
+ const response = await fetch(url, {
2188
+ ...requestInit,
2189
+ cache: "no-cache"
2190
+ });
2191
+ if (response.status >= 500 && retryCount < 6) {
2192
+ const delay = exponentialBackoff(retryCount + 1, 2, 50, 1150, 50);
2193
+ await new Promise((resolve) => setTimeout(resolve, delay));
2194
+ return fetchHead(url, requestInitWithoutMethod, retryCount + 1);
2195
+ }
2196
+ return response;
2197
+ }
2198
+ __name(fetchHead, "fetchHead");
2199
+ async function zodfetch(schema, url, requestInit, options, retryCount = 0) {
2200
+ const response = await fetch(url, {
2201
+ ...requestInit,
2202
+ cache: "no-cache"
2203
+ });
2204
+ if ((!requestInit || requestInit.method === "GET") && response.status === 404 && options?.optional) {
2205
+ return;
2206
+ }
2207
+ if (response.status >= 400 && response.status < 500) {
2208
+ const body = await response.json();
2209
+ throw new Error(body.error);
2210
+ }
2211
+ if (response.status >= 500 && retryCount < 6) {
2212
+ const delay = exponentialBackoff(retryCount + 1, 2, 50, 1150, 50);
2213
+ await new Promise((resolve) => setTimeout(resolve, delay));
2214
+ return zodfetch(schema, url, requestInit, options, retryCount + 1);
2215
+ }
2216
+ if (response.status !== 200) {
2217
+ throw new Error(options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`);
2218
+ }
2219
+ const jsonBody = await response.json();
2220
+ return schema.parse(jsonBody);
2221
+ }
2222
+ __name(zodfetch, "zodfetch");
2223
+ function exponentialBackoff(retryCount, exponential, minDelay, maxDelay, jitter) {
2224
+ const delay = Math.min(Math.pow(exponential, retryCount) * minDelay, maxDelay);
2225
+ const jitterValue = Math.random() * jitter;
2226
+ return delay + jitterValue;
2227
+ }
2228
+ __name(exponentialBackoff, "exponentialBackoff");
2229
+
2230
+ // src/httpEndpoint.ts
2231
+ var import_core4 = require("@trigger.dev/core");
2232
+
2233
+ // src/utils/formatSchemaErrors.ts
2234
+ function formatSchemaErrors(errors) {
2235
+ return errors.map((error) => {
2236
+ const { path, message } = error;
2237
+ return {
2238
+ path: path.map(String),
2239
+ message
2240
+ };
2241
+ });
2242
+ }
2243
+ __name(formatSchemaErrors, "formatSchemaErrors");
2244
+
2245
+ // src/httpEndpoint.ts
2246
+ var HttpEndpoint = class {
2247
+ constructor(options) {
2248
+ this.options = options;
2249
+ }
2250
+ get id() {
2251
+ return this.options.id;
2252
+ }
2253
+ onRequest(options) {
2254
+ return new HttpTrigger({
2255
+ endpointId: this.id,
2256
+ event: this.options.event,
2257
+ filter: options?.filter,
2258
+ verify: this.options.verify
2259
+ });
2260
+ }
2261
+ async handleRequest(request) {
2262
+ if (!this.options.respondWith)
2263
+ return;
2264
+ return this.options.respondWith.handler(request, () => {
2265
+ const clonedRequest = request.clone();
2266
+ return this.options.verify(clonedRequest);
2267
+ });
2268
+ }
2269
+ toJSON() {
2270
+ return {
2271
+ id: this.id,
2272
+ icon: this.options.event.icon,
2273
+ version: "1",
2274
+ enabled: this.options.enabled ?? true,
2275
+ event: this.options.event,
2276
+ immediateResponseFilter: this.options.respondWith?.filter,
2277
+ skipTriggeringRuns: this.options.respondWith?.skipTriggeringRuns,
2278
+ source: this.options.event.source
2279
+ };
1066
2280
  }
1067
- debug(message, properties) {
1068
- return this.callback("DEBUG", message, properties);
2281
+ };
2282
+ __name(HttpEndpoint, "HttpEndpoint");
2283
+ var HttpTrigger = /* @__PURE__ */ __name(class HttpTrigger2 {
2284
+ constructor(options) {
2285
+ this.options = options;
1069
2286
  }
1070
- info(message, properties) {
1071
- return this.callback("INFO", message, properties);
2287
+ toJSON() {
2288
+ return {
2289
+ type: "static",
2290
+ title: this.options.endpointId,
2291
+ properties: this.options.event.properties,
2292
+ rule: {
2293
+ event: `httpendpoint.${this.options.endpointId}`,
2294
+ payload: this.options.filter ?? {},
2295
+ source: this.options.event.source
2296
+ },
2297
+ link: `http-endpoints/${this.options.endpointId}`,
2298
+ help: {
2299
+ noRuns: {
2300
+ text: "To start triggering runs click here to setup your HTTP Endpoint with the external API service you want to receive webhooks from.",
2301
+ link: `http-endpoints/${this.options.endpointId}`
2302
+ }
2303
+ }
2304
+ };
1072
2305
  }
1073
- warn(message, properties) {
1074
- return this.callback("WARN", message, properties);
2306
+ get event() {
2307
+ return this.options.event;
1075
2308
  }
1076
- error(message, properties) {
1077
- return this.callback("ERROR", message, properties);
2309
+ attachToJob(triggerClient, job) {
1078
2310
  }
1079
- };
1080
- __name(IOLogger, "IOLogger");
2311
+ get preprocessRuns() {
2312
+ return false;
2313
+ }
2314
+ async verifyPayload(payload) {
2315
+ const clonedRequest = payload.clone();
2316
+ return this.options.verify(clonedRequest);
2317
+ }
2318
+ }, "HttpTrigger");
2319
+ function httpEndpoint(options) {
2320
+ const id = slugifyId(options.id);
2321
+ return new HttpEndpoint({
2322
+ id,
2323
+ enabled: options.enabled,
2324
+ respondWith: options.respondWith,
2325
+ verify: options.verify,
2326
+ event: {
2327
+ name: id,
2328
+ title: options.title ?? "HTTP Trigger",
2329
+ source: options.source,
2330
+ icon: options.icon ?? "webhook",
2331
+ properties: options.properties,
2332
+ examples: options.examples ? options.examples : [
2333
+ {
2334
+ id: "basic-request",
2335
+ name: "Basic Request",
2336
+ icon: "http-post",
2337
+ payload: {
2338
+ url: "https://cloud.trigger.dev",
2339
+ method: "POST",
2340
+ headers: {
2341
+ "Content-Type": "application/json"
2342
+ },
2343
+ rawBody: JSON.stringify({
2344
+ foo: "bar"
2345
+ })
2346
+ }
2347
+ }
2348
+ ],
2349
+ parsePayload: (rawPayload) => {
2350
+ const result = import_core4.RequestWithRawBodySchema.safeParse(rawPayload);
2351
+ if (!result.success) {
2352
+ throw new ParsedPayloadSchemaError(formatSchemaErrors(result.error.issues));
2353
+ }
2354
+ return new Request(new URL(result.data.url), {
2355
+ method: result.data.method,
2356
+ headers: result.data.headers,
2357
+ body: result.data.rawBody
2358
+ });
2359
+ }
2360
+ }
2361
+ });
2362
+ }
2363
+ __name(httpEndpoint, "httpEndpoint");
1081
2364
 
1082
2365
  // src/ioWithIntegrations.ts
1083
2366
  function createIOWithIntegrations(io, auths, integrations) {
@@ -1108,26 +2391,8 @@ function createIOWithIntegrations(io, auths, integrations) {
1108
2391
  }
1109
2392
  __name(createIOWithIntegrations, "createIOWithIntegrations");
1110
2393
 
1111
- // src/utils/typedAsyncLocalStorage.ts
1112
- var import_node_async_hooks2 = require("async_hooks");
1113
- var TypedAsyncLocalStorage = class {
1114
- constructor() {
1115
- this.storage = new import_node_async_hooks2.AsyncLocalStorage();
1116
- }
1117
- runWith(context, fn) {
1118
- return this.storage.run(context, fn);
1119
- }
1120
- getStore() {
1121
- return this.storage.getStore();
1122
- }
1123
- };
1124
- __name(TypedAsyncLocalStorage, "TypedAsyncLocalStorage");
1125
-
1126
- // src/runLocalStorage.ts
1127
- var runLocalStorage = new TypedAsyncLocalStorage();
1128
-
1129
2394
  // src/triggers/dynamic.ts
1130
- var import_core4 = require("@trigger.dev/core");
2395
+ var import_core5 = require("@trigger.dev/core");
1131
2396
  var _client, _options2;
1132
2397
  var DynamicTrigger = class {
1133
2398
  constructor(client, options) {
@@ -1156,7 +2421,7 @@ var DynamicTrigger = class {
1156
2421
  rule: {
1157
2422
  event: this.event.name,
1158
2423
  source: this.event.source,
1159
- payload: (0, import_core4.deepMergeFilters)(this.source.filter(params), this.event.filter ?? {}, options.filter ?? {})
2424
+ payload: (0, import_core5.deepMergeFilters)(this.source.filter(params), this.event.filter ?? {}, options.filter ?? {})
1160
2425
  },
1161
2426
  source: {
1162
2427
  version: "2",
@@ -1187,7 +2452,7 @@ var DynamicTrigger = class {
1187
2452
  key,
1188
2453
  "register"
1189
2454
  ], async (task) => {
1190
- return __privateGet(this, _client).registerTrigger(this.id, key, this.registeredTriggerForParams(params, options));
2455
+ return __privateGet(this, _client).registerTrigger(this.id, key, this.registeredTriggerForParams(params, options), task.idempotencyKey);
1191
2456
  }, {
1192
2457
  name: "Register Dynamic Trigger",
1193
2458
  properties: [
@@ -1209,27 +2474,18 @@ var DynamicTrigger = class {
1209
2474
  get preprocessRuns() {
1210
2475
  return true;
1211
2476
  }
2477
+ async verifyPayload(payload) {
2478
+ return {
2479
+ success: true
2480
+ };
2481
+ }
1212
2482
  };
1213
2483
  __name(DynamicTrigger, "DynamicTrigger");
1214
2484
  _client = new WeakMap();
1215
2485
  _options2 = new WeakMap();
1216
2486
 
1217
2487
  // src/triggers/eventTrigger.ts
1218
- var import_core5 = require("@trigger.dev/core");
1219
-
1220
- // src/utils/formatSchemaErrors.ts
1221
- function formatSchemaErrors(errors) {
1222
- return errors.map((error) => {
1223
- const { path, message } = error;
1224
- return {
1225
- path: path.map(String),
1226
- message
1227
- };
1228
- });
1229
- }
1230
- __name(formatSchemaErrors, "formatSchemaErrors");
1231
-
1232
- // src/triggers/eventTrigger.ts
2488
+ var import_core6 = require("@trigger.dev/core");
1233
2489
  var _options3;
1234
2490
  var EventTrigger = class {
1235
2491
  constructor(options) {
@@ -1243,7 +2499,7 @@ var EventTrigger = class {
1243
2499
  rule: {
1244
2500
  event: __privateGet(this, _options3).name ?? __privateGet(this, _options3).event.name,
1245
2501
  source: __privateGet(this, _options3).source ?? "trigger.dev",
1246
- payload: (0, import_core5.deepMergeFilters)(__privateGet(this, _options3).filter ?? {}, __privateGet(this, _options3).event.filter ?? {})
2502
+ payload: (0, import_core6.deepMergeFilters)(__privateGet(this, _options3).filter ?? {}, __privateGet(this, _options3).event.filter ?? {})
1247
2503
  }
1248
2504
  };
1249
2505
  }
@@ -1255,6 +2511,17 @@ var EventTrigger = class {
1255
2511
  get preprocessRuns() {
1256
2512
  return false;
1257
2513
  }
2514
+ async verifyPayload(payload) {
2515
+ if (__privateGet(this, _options3).verify) {
2516
+ if (payload instanceof Request) {
2517
+ const clonedRequest = payload.clone();
2518
+ return __privateGet(this, _options3).verify(clonedRequest);
2519
+ }
2520
+ }
2521
+ return {
2522
+ success: true
2523
+ };
2524
+ }
1258
2525
  };
1259
2526
  __name(EventTrigger, "EventTrigger");
1260
2527
  _options3 = new WeakMap();
@@ -1284,7 +2551,7 @@ function eventTrigger(options) {
1284
2551
  __name(eventTrigger, "eventTrigger");
1285
2552
 
1286
2553
  // src/triggers/scheduled.ts
1287
- var import_core6 = require("@trigger.dev/core");
2554
+ var import_core7 = require("@trigger.dev/core");
1288
2555
  var import_cronstrue = __toESM(require("cronstrue"));
1289
2556
  var examples = [
1290
2557
  {
@@ -1292,8 +2559,8 @@ var examples = [
1292
2559
  name: "Now",
1293
2560
  icon: "clock",
1294
2561
  payload: {
1295
- ts: import_core6.currentDate.marker,
1296
- lastTimestamp: import_core6.currentDate.marker
2562
+ ts: import_core7.currentDate.marker,
2563
+ lastTimestamp: import_core7.currentDate.marker
1297
2564
  }
1298
2565
  }
1299
2566
  ];
@@ -1308,7 +2575,7 @@ var IntervalTrigger = class {
1308
2575
  source: "trigger.dev",
1309
2576
  icon: "schedule-interval",
1310
2577
  examples,
1311
- parsePayload: import_core6.ScheduledPayloadSchema.parse,
2578
+ parsePayload: import_core7.ScheduledPayloadSchema.parse,
1312
2579
  properties: [
1313
2580
  {
1314
2581
  label: "Interval",
@@ -1322,6 +2589,11 @@ var IntervalTrigger = class {
1322
2589
  get preprocessRuns() {
1323
2590
  return false;
1324
2591
  }
2592
+ async verifyPayload(payload) {
2593
+ return {
2594
+ success: true
2595
+ };
2596
+ }
1325
2597
  toJSON() {
1326
2598
  return {
1327
2599
  type: "scheduled",
@@ -1353,7 +2625,7 @@ var CronTrigger = class {
1353
2625
  source: "trigger.dev",
1354
2626
  icon: "schedule-cron",
1355
2627
  examples,
1356
- parsePayload: import_core6.ScheduledPayloadSchema.parse,
2628
+ parsePayload: import_core7.ScheduledPayloadSchema.parse,
1357
2629
  properties: [
1358
2630
  {
1359
2631
  label: "cron",
@@ -1371,6 +2643,11 @@ var CronTrigger = class {
1371
2643
  get preprocessRuns() {
1372
2644
  return false;
1373
2645
  }
2646
+ async verifyPayload(payload) {
2647
+ return {
2648
+ success: true
2649
+ };
2650
+ }
1374
2651
  toJSON() {
1375
2652
  return {
1376
2653
  type: "scheduled",
@@ -1404,7 +2681,7 @@ var DynamicSchedule = class {
1404
2681
  source: "trigger.dev",
1405
2682
  icon: "schedule-dynamic",
1406
2683
  examples,
1407
- parsePayload: import_core6.ScheduledPayloadSchema.parse
2684
+ parsePayload: import_core7.ScheduledPayloadSchema.parse
1408
2685
  };
1409
2686
  }
1410
2687
  async register(key, metadata) {
@@ -1466,6 +2743,11 @@ var DynamicSchedule = class {
1466
2743
  get preprocessRuns() {
1467
2744
  return false;
1468
2745
  }
2746
+ async verifyPayload(payload) {
2747
+ return {
2748
+ success: true
2749
+ };
2750
+ }
1469
2751
  toJSON() {
1470
2752
  return {
1471
2753
  type: "dynamic",
@@ -1476,49 +2758,95 @@ var DynamicSchedule = class {
1476
2758
  __name(DynamicSchedule, "DynamicSchedule");
1477
2759
 
1478
2760
  // src/triggerClient.ts
2761
+ var import_node_events = __toESM(require("events"));
2762
+
2763
+ // package.json
2764
+ var version = "0.0.0-cross-runtime-20231201105801";
2765
+
2766
+ // src/concurrencyLimit.ts
2767
+ var ConcurrencyLimit = class {
2768
+ constructor(options) {
2769
+ this.options = options;
2770
+ }
2771
+ get id() {
2772
+ return this.options.id;
2773
+ }
2774
+ get limit() {
2775
+ return this.options.limit;
2776
+ }
2777
+ };
2778
+ __name(ConcurrencyLimit, "ConcurrencyLimit");
2779
+
2780
+ // src/triggerClient.ts
2781
+ var registerWebhookEvent = /* @__PURE__ */ __name((key) => ({
2782
+ name: `${import_core8.REGISTER_WEBHOOK}.${key}`,
2783
+ title: "Register Webhook",
2784
+ source: "internal",
2785
+ icon: "webhook",
2786
+ parsePayload: import_core8.RegisterWebhookPayloadSchema.parse
2787
+ }), "registerWebhookEvent");
1479
2788
  var registerSourceEvent = {
1480
- name: import_core7.REGISTER_SOURCE_EVENT_V2,
2789
+ name: import_core8.REGISTER_SOURCE_EVENT_V2,
1481
2790
  title: "Register Source",
1482
2791
  source: "internal",
1483
2792
  icon: "register-source",
1484
- parsePayload: import_core7.RegisterSourceEventSchemaV2.parse
2793
+ parsePayload: import_core8.RegisterSourceEventSchemaV2.parse
1485
2794
  };
1486
- 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;
2795
+ var _options4, _registeredJobs, _registeredSources, _registeredWebhooks, _registeredHttpSourceHandlers, _registeredWebhookSourceHandlers, _registeredDynamicTriggers, _jobMetadataByDynamicTriggers, _registeredSchedules, _registeredHttpEndpoints, _authResolvers, _envStore, _eventEmitter, _client2, _internalLogger, _preprocessRun, preprocessRun_fn, _executeJob, executeJob_fn, _convertErrorToExecutionResponse, convertErrorToExecutionResponse_fn, _createRunContext, createRunContext_fn, _createPreprocessRunContext, createPreprocessRunContext_fn, _handleHttpSourceRequest, handleHttpSourceRequest_fn, _handleHttpEndpointRequestForResponse, handleHttpEndpointRequestForResponse_fn, _handleWebhookRequest, handleWebhookRequest_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, _serializeRunMetadata, serializeRunMetadata_fn, _deliverSuccessfulRunNotification, deliverSuccessfulRunNotification_fn, _deliverFailedRunNotification, deliverFailedRunNotification_fn;
1487
2796
  var TriggerClient = class {
1488
2797
  constructor(options) {
1489
2798
  __privateAdd(this, _preprocessRun);
1490
2799
  __privateAdd(this, _executeJob);
2800
+ __privateAdd(this, _convertErrorToExecutionResponse);
1491
2801
  __privateAdd(this, _createRunContext);
1492
2802
  __privateAdd(this, _createPreprocessRunContext);
1493
2803
  __privateAdd(this, _handleHttpSourceRequest);
2804
+ __privateAdd(this, _handleHttpEndpointRequestForResponse);
2805
+ __privateAdd(this, _handleWebhookRequest);
1494
2806
  __privateAdd(this, _resolveConnections);
1495
2807
  __privateAdd(this, _resolveConnection);
1496
2808
  __privateAdd(this, _buildJobsIndex);
1497
2809
  __privateAdd(this, _buildJobIndex);
1498
2810
  __privateAdd(this, _buildJobIntegrations);
1499
2811
  __privateAdd(this, _buildJobIntegration);
2812
+ __privateAdd(this, _logIOStats);
2813
+ __privateAdd(this, _standardResponseHeaders);
2814
+ __privateAdd(this, _serializeRunMetadata);
2815
+ __privateAdd(this, _deliverSuccessfulRunNotification);
2816
+ __privateAdd(this, _deliverFailedRunNotification);
1500
2817
  __privateAdd(this, _options4, void 0);
1501
2818
  __privateAdd(this, _registeredJobs, {});
1502
2819
  __privateAdd(this, _registeredSources, {});
2820
+ __privateAdd(this, _registeredWebhooks, {});
1503
2821
  __privateAdd(this, _registeredHttpSourceHandlers, {});
2822
+ __privateAdd(this, _registeredWebhookSourceHandlers, {});
1504
2823
  __privateAdd(this, _registeredDynamicTriggers, {});
1505
2824
  __privateAdd(this, _jobMetadataByDynamicTriggers, {});
1506
2825
  __privateAdd(this, _registeredSchedules, {});
2826
+ __privateAdd(this, _registeredHttpEndpoints, {});
1507
2827
  __privateAdd(this, _authResolvers, {});
2828
+ __privateAdd(this, _envStore, void 0);
2829
+ __privateAdd(this, _eventEmitter, new import_node_events.default());
1508
2830
  __privateAdd(this, _client2, void 0);
1509
2831
  __privateAdd(this, _internalLogger, void 0);
2832
+ __publicField(this, "on", __privateGet(this, _eventEmitter).on.bind(__privateGet(this, _eventEmitter)));
1510
2833
  this.id = options.id;
1511
2834
  __privateSet(this, _options4, options);
1512
2835
  __privateSet(this, _client2, new ApiClient(__privateGet(this, _options4)));
1513
- __privateSet(this, _internalLogger, new import_core7.Logger("trigger.dev", __privateGet(this, _options4).verbose ? "debug" : "log"));
2836
+ __privateSet(this, _internalLogger, new import_core8.Logger("trigger.dev", __privateGet(this, _options4).verbose ? "debug" : "log", [
2837
+ "output",
2838
+ "noopTasksSet"
2839
+ ]));
2840
+ __privateSet(this, _envStore, new KeyValueStore(__privateGet(this, _client2)));
1514
2841
  }
1515
- async handleRequest(request) {
2842
+ async handleRequest(request, timeOrigin = performance.now()) {
1516
2843
  __privateGet(this, _internalLogger).debug("handling request", {
1517
2844
  url: request.url,
1518
2845
  headers: Object.fromEntries(request.headers.entries()),
1519
2846
  method: request.method
1520
2847
  });
1521
2848
  const apiKey = request.headers.get("x-trigger-api-key");
2849
+ const triggerVersion = request.headers.get("x-trigger-version");
1522
2850
  const authorization = this.authorized(apiKey);
1523
2851
  switch (authorization) {
1524
2852
  case "authorized": {
@@ -1529,7 +2857,8 @@ var TriggerClient = class {
1529
2857
  status: 401,
1530
2858
  body: {
1531
2859
  message: "Unauthorized: client missing apiKey"
1532
- }
2860
+ },
2861
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1533
2862
  };
1534
2863
  }
1535
2864
  case "missing-header": {
@@ -1537,7 +2866,8 @@ var TriggerClient = class {
1537
2866
  status: 401,
1538
2867
  body: {
1539
2868
  message: "Unauthorized: missing x-trigger-api-key header"
1540
- }
2869
+ },
2870
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1541
2871
  };
1542
2872
  }
1543
2873
  case "unauthorized": {
@@ -1545,7 +2875,8 @@ var TriggerClient = class {
1545
2875
  status: 401,
1546
2876
  body: {
1547
2877
  message: `Forbidden: client apiKey mismatch: Make sure you are using the correct API Key for your environment`
1548
- }
2878
+ },
2879
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1549
2880
  };
1550
2881
  }
1551
2882
  }
@@ -1554,7 +2885,8 @@ var TriggerClient = class {
1554
2885
  status: 405,
1555
2886
  body: {
1556
2887
  message: "Method not allowed (only POST is allowed)"
1557
- }
2888
+ },
2889
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1558
2890
  };
1559
2891
  }
1560
2892
  const action = request.headers.get("x-trigger-action");
@@ -1563,7 +2895,8 @@ var TriggerClient = class {
1563
2895
  status: 400,
1564
2896
  body: {
1565
2897
  message: "Missing x-trigger-action header"
1566
- }
2898
+ },
2899
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1567
2900
  };
1568
2901
  }
1569
2902
  switch (action) {
@@ -1575,7 +2908,8 @@ var TriggerClient = class {
1575
2908
  body: {
1576
2909
  ok: false,
1577
2910
  error: "Missing endpoint ID"
1578
- }
2911
+ },
2912
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1579
2913
  };
1580
2914
  }
1581
2915
  if (this.id !== endpointId) {
@@ -1584,20 +2918,23 @@ var TriggerClient = class {
1584
2918
  body: {
1585
2919
  ok: false,
1586
2920
  error: `Endpoint ID mismatch error. Expected ${this.id}, got ${endpointId}`
1587
- }
2921
+ },
2922
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1588
2923
  };
1589
2924
  }
1590
2925
  return {
1591
2926
  status: 200,
1592
2927
  body: {
1593
2928
  ok: true
1594
- }
2929
+ },
2930
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1595
2931
  };
1596
2932
  }
1597
2933
  case "INDEX_ENDPOINT": {
1598
2934
  const body = {
1599
2935
  jobs: __privateMethod(this, _buildJobsIndex, buildJobsIndex_fn).call(this),
1600
2936
  sources: Object.values(__privateGet(this, _registeredSources)),
2937
+ webhooks: Object.values(__privateGet(this, _registeredWebhooks)),
1601
2938
  dynamicTriggers: Object.values(__privateGet(this, _registeredDynamicTriggers)).map((trigger) => ({
1602
2939
  id: trigger.id,
1603
2940
  jobs: __privateGet(this, _jobMetadataByDynamicTriggers)[trigger.id] ?? [],
@@ -1609,16 +2946,18 @@ var TriggerClient = class {
1609
2946
  dynamicSchedules: Object.entries(__privateGet(this, _registeredSchedules)).map(([id, jobs]) => ({
1610
2947
  id,
1611
2948
  jobs
1612
- }))
2949
+ })),
2950
+ httpEndpoints: Object.entries(__privateGet(this, _registeredHttpEndpoints)).map(([id, endpoint]) => endpoint.toJSON())
1613
2951
  };
1614
2952
  return {
1615
2953
  status: 200,
1616
- body
2954
+ body,
2955
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1617
2956
  };
1618
2957
  }
1619
2958
  case "INITIALIZE_TRIGGER": {
1620
2959
  const json = await request.json();
1621
- const body = import_core7.InitializeTriggerBodySchema.safeParse(json);
2960
+ const body = import_core8.InitializeTriggerBodySchema.safeParse(json);
1622
2961
  if (!body.success) {
1623
2962
  return {
1624
2963
  status: 400,
@@ -1638,12 +2977,13 @@ var TriggerClient = class {
1638
2977
  }
1639
2978
  return {
1640
2979
  status: 200,
1641
- body: dynamicTrigger.registeredTriggerForParams(body.data.params)
2980
+ body: dynamicTrigger.registeredTriggerForParams(body.data.params),
2981
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1642
2982
  };
1643
2983
  }
1644
2984
  case "EXECUTE_JOB": {
1645
2985
  const json = await request.json();
1646
- const execution = import_core7.RunJobBodySchema.safeParse(json);
2986
+ const execution = import_core8.RunJobBodySchema.safeParse(json);
1647
2987
  if (!execution.success) {
1648
2988
  return {
1649
2989
  status: 400,
@@ -1661,15 +3001,24 @@ var TriggerClient = class {
1661
3001
  }
1662
3002
  };
1663
3003
  }
1664
- const results = await __privateMethod(this, _executeJob, executeJob_fn).call(this, execution.data, job);
3004
+ const results = await __privateMethod(this, _executeJob, executeJob_fn).call(this, execution.data, job, timeOrigin, triggerVersion);
3005
+ __privateGet(this, _internalLogger).debug("executed job", {
3006
+ results,
3007
+ job: job.id,
3008
+ version: job.version,
3009
+ triggerVersion
3010
+ });
3011
+ const standardHeaders = __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin);
3012
+ standardHeaders["x-trigger-run-metadata"] = __privateMethod(this, _serializeRunMetadata, serializeRunMetadata_fn).call(this, job);
1665
3013
  return {
1666
3014
  status: 200,
1667
- body: results
3015
+ body: results,
3016
+ headers: standardHeaders
1668
3017
  };
1669
3018
  }
1670
3019
  case "PREPROCESS_RUN": {
1671
3020
  const json = await request.json();
1672
- const body = import_core7.PreprocessRunBodySchema.safeParse(json);
3021
+ const body = import_core8.PreprocessRunBodySchema.safeParse(json);
1673
3022
  if (!body.success) {
1674
3023
  return {
1675
3024
  status: 400,
@@ -1693,11 +3042,12 @@ var TriggerClient = class {
1693
3042
  body: {
1694
3043
  abort: results.abort,
1695
3044
  properties: results.properties
1696
- }
3045
+ },
3046
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1697
3047
  };
1698
3048
  }
1699
3049
  case "DELIVER_HTTP_SOURCE_REQUEST": {
1700
- const headers = import_core7.HttpSourceRequestHeadersSchema.safeParse(Object.fromEntries(request.headers.entries()));
3050
+ const headers = import_core8.HttpSourceRequestHeadersSchema.safeParse(Object.fromEntries(request.headers.entries()));
1701
3051
  if (!headers.success) {
1702
3052
  return {
1703
3053
  status: 400,
@@ -1742,7 +3092,83 @@ var TriggerClient = class {
1742
3092
  events,
1743
3093
  response,
1744
3094
  metadata
3095
+ },
3096
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3097
+ };
3098
+ }
3099
+ case "DELIVER_HTTP_ENDPOINT_REQUEST_FOR_RESPONSE": {
3100
+ const headers = import_core8.HttpEndpointRequestHeadersSchema.safeParse(Object.fromEntries(request.headers.entries()));
3101
+ if (!headers.success) {
3102
+ return {
3103
+ status: 400,
3104
+ body: {
3105
+ message: "Invalid headers"
3106
+ }
3107
+ };
3108
+ }
3109
+ const sourceRequestNeedsBody = headers.data["x-ts-http-method"] !== "GET";
3110
+ const sourceRequestInit = {
3111
+ method: headers.data["x-ts-http-method"],
3112
+ headers: headers.data["x-ts-http-headers"],
3113
+ body: sourceRequestNeedsBody ? request.body : void 0
3114
+ };
3115
+ if (sourceRequestNeedsBody) {
3116
+ try {
3117
+ sourceRequestInit.duplex = "half";
3118
+ } catch (error) {
3119
+ }
3120
+ }
3121
+ const sourceRequest = new Request(headers.data["x-ts-http-url"], sourceRequestInit);
3122
+ const key = headers.data["x-ts-key"];
3123
+ const { response } = await __privateMethod(this, _handleHttpEndpointRequestForResponse, handleHttpEndpointRequestForResponse_fn).call(this, {
3124
+ key
3125
+ }, sourceRequest);
3126
+ return {
3127
+ status: 200,
3128
+ body: response,
3129
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3130
+ };
3131
+ }
3132
+ case "DELIVER_WEBHOOK_REQUEST": {
3133
+ const headers = import_core8.WebhookSourceRequestHeadersSchema.safeParse(Object.fromEntries(request.headers.entries()));
3134
+ if (!headers.success) {
3135
+ return {
3136
+ status: 400,
3137
+ body: {
3138
+ message: "Invalid headers"
3139
+ }
3140
+ };
3141
+ }
3142
+ const sourceRequestNeedsBody = headers.data["x-ts-http-method"] !== "GET";
3143
+ const sourceRequestInit = {
3144
+ method: headers.data["x-ts-http-method"],
3145
+ headers: headers.data["x-ts-http-headers"],
3146
+ body: sourceRequestNeedsBody ? request.body : void 0
3147
+ };
3148
+ if (sourceRequestNeedsBody) {
3149
+ try {
3150
+ sourceRequestInit.duplex = "half";
3151
+ } catch (error2) {
1745
3152
  }
3153
+ }
3154
+ const webhookRequest = new Request(headers.data["x-ts-http-url"], sourceRequestInit);
3155
+ const key = headers.data["x-ts-key"];
3156
+ const secret = headers.data["x-ts-secret"];
3157
+ const params = headers.data["x-ts-params"];
3158
+ const ctx = {
3159
+ key,
3160
+ secret,
3161
+ params
3162
+ };
3163
+ const { response, verified, error } = await __privateMethod(this, _handleWebhookRequest, handleWebhookRequest_fn).call(this, webhookRequest, ctx);
3164
+ return {
3165
+ status: 200,
3166
+ body: {
3167
+ response,
3168
+ verified,
3169
+ error
3170
+ },
3171
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1746
3172
  };
1747
3173
  }
1748
3174
  case "VALIDATE": {
@@ -1751,7 +3177,36 @@ var TriggerClient = class {
1751
3177
  body: {
1752
3178
  ok: true,
1753
3179
  endpointId: this.id
1754
- }
3180
+ },
3181
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3182
+ };
3183
+ }
3184
+ case "PROBE_EXECUTION_TIMEOUT": {
3185
+ const json = await request.json();
3186
+ const timeout = json?.timeout ?? 15 * 60 * 1e3;
3187
+ await new Promise((resolve) => setTimeout(resolve, timeout));
3188
+ return {
3189
+ status: 200,
3190
+ body: {
3191
+ ok: true
3192
+ },
3193
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3194
+ };
3195
+ }
3196
+ case "RUN_NOTIFICATION": {
3197
+ const rawJson = await request.json();
3198
+ const runNotification = rawJson;
3199
+ if (runNotification.ok) {
3200
+ await __privateMethod(this, _deliverSuccessfulRunNotification, deliverSuccessfulRunNotification_fn).call(this, runNotification);
3201
+ } else {
3202
+ await __privateMethod(this, _deliverFailedRunNotification, deliverFailedRunNotification_fn).call(this, runNotification);
3203
+ }
3204
+ return {
3205
+ status: 200,
3206
+ body: {
3207
+ ok: true
3208
+ },
3209
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1755
3210
  };
1756
3211
  }
1757
3212
  }
@@ -1759,10 +3214,15 @@ var TriggerClient = class {
1759
3214
  status: 405,
1760
3215
  body: {
1761
3216
  message: "Method not allowed"
1762
- }
3217
+ },
3218
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1763
3219
  };
1764
3220
  }
1765
3221
  defineJob(options) {
3222
+ const existingRegisteredJob = __privateGet(this, _registeredJobs)[options.id];
3223
+ if (existingRegisteredJob) {
3224
+ console.warn((0, import_colorette.yellow)(`[@trigger.dev/sdk] Warning: The Job "${existingRegisteredJob.id}" you're attempting to define has already been defined. Please assign a different ID to the job.`));
3225
+ }
1766
3226
  return new Job(this, options);
1767
3227
  }
1768
3228
  defineAuthResolver(integration, resolver) {
@@ -1775,6 +3235,18 @@ var TriggerClient = class {
1775
3235
  defineDynamicTrigger(options) {
1776
3236
  return new DynamicTrigger(this, options);
1777
3237
  }
3238
+ defineHttpEndpoint(options, suppressWarnings = false) {
3239
+ const existingHttpEndpoint = __privateGet(this, _registeredHttpEndpoints)[options.id];
3240
+ if (!suppressWarnings && existingHttpEndpoint) {
3241
+ console.warn((0, import_colorette.yellow)(`[@trigger.dev/sdk] Warning: The HttpEndpoint "${existingHttpEndpoint.id}" you're attempting to define has already been defined. Please assign a different ID to the HttpEndpoint.`));
3242
+ }
3243
+ const endpoint = httpEndpoint(options);
3244
+ __privateGet(this, _registeredHttpEndpoints)[endpoint.id] = endpoint;
3245
+ return endpoint;
3246
+ }
3247
+ defineConcurrencyLimit(options) {
3248
+ return new ConcurrencyLimit(options);
3249
+ }
1778
3250
  attach(job) {
1779
3251
  __privateGet(this, _registeredJobs)[job.id] = job;
1780
3252
  job.trigger.attachToJob(this, job);
@@ -1889,8 +3361,96 @@ var TriggerClient = class {
1889
3361
  });
1890
3362
  __privateGet(this, _registeredSchedules)[key] = jobs;
1891
3363
  }
1892
- async registerTrigger(id, key, options) {
1893
- return __privateGet(this, _client2).registerTrigger(this.id, id, key, options);
3364
+ attachWebhook(options) {
3365
+ const { source } = options;
3366
+ __privateGet(this, _registeredWebhookSourceHandlers)[options.key] = {
3367
+ verify: source.verify.bind(source),
3368
+ generateEvents: source.generateEvents.bind(source)
3369
+ };
3370
+ let registeredWebhook = __privateGet(this, _registeredWebhooks)[options.key];
3371
+ if (!registeredWebhook) {
3372
+ registeredWebhook = {
3373
+ key: options.key,
3374
+ params: options.params,
3375
+ config: options.config,
3376
+ integration: {
3377
+ id: source.integration.id,
3378
+ metadata: source.integration.metadata,
3379
+ authSource: source.integration.authSource
3380
+ },
3381
+ httpEndpoint: {
3382
+ id: options.key
3383
+ }
3384
+ };
3385
+ } else {
3386
+ registeredWebhook.config = deepMergeOptions(registeredWebhook.config, options.config);
3387
+ }
3388
+ __privateGet(this, _registeredWebhooks)[options.key] = registeredWebhook;
3389
+ new Job(this, {
3390
+ id: `webhook.register.${options.key}`,
3391
+ name: `webhook.register.${options.key}`,
3392
+ version: source.version,
3393
+ trigger: new EventTrigger({
3394
+ event: registerWebhookEvent(options.key)
3395
+ }),
3396
+ integrations: {
3397
+ integration: source.integration
3398
+ },
3399
+ run: async (registerPayload, io, ctx) => {
3400
+ return await io.try(async () => {
3401
+ __privateGet(this, _internalLogger).debug("[webhook.register] Start");
3402
+ const crudOptions = {
3403
+ io,
3404
+ ctx: registerPayload
3405
+ };
3406
+ if (!registerPayload.active) {
3407
+ __privateGet(this, _internalLogger).debug("[webhook.register] Not active, run create");
3408
+ await io.try(async () => {
3409
+ await source.crud.create(crudOptions);
3410
+ }, async (error) => {
3411
+ __privateGet(this, _internalLogger).debug("[webhook.register] Error during create, re-trying with delete first", {
3412
+ error
3413
+ });
3414
+ await io.runTask("create-retry", async () => {
3415
+ await source.crud.delete(crudOptions);
3416
+ await source.crud.create(crudOptions);
3417
+ });
3418
+ });
3419
+ return await io.updateWebhook("update-webhook-success", {
3420
+ key: options.key,
3421
+ active: true,
3422
+ config: registerPayload.config.desired
3423
+ });
3424
+ }
3425
+ __privateGet(this, _internalLogger).debug("[webhook.register] Already active, run update");
3426
+ if (source.crud.update) {
3427
+ await source.crud.update(crudOptions);
3428
+ } else {
3429
+ __privateGet(this, _internalLogger).debug("[webhook.register] Run delete and create instead of update");
3430
+ await source.crud.delete(crudOptions);
3431
+ await source.crud.create(crudOptions);
3432
+ }
3433
+ return await io.updateWebhook("update-webhook-success", {
3434
+ key: options.key,
3435
+ active: true,
3436
+ config: registerPayload.config.desired
3437
+ });
3438
+ }, async (error) => {
3439
+ __privateGet(this, _internalLogger).debug("[webhook.register] Error", {
3440
+ error
3441
+ });
3442
+ await io.updateWebhook("update-webhook-error", {
3443
+ key: options.key,
3444
+ active: false
3445
+ });
3446
+ throw error;
3447
+ });
3448
+ },
3449
+ __internal: true
3450
+ });
3451
+ }
3452
+ async registerTrigger(id, key, options, idempotencyKey) {
3453
+ return __privateGet(this, _client2).registerTrigger(this.id, id, key, options, idempotencyKey);
1894
3454
  }
1895
3455
  async getAuth(id) {
1896
3456
  return __privateGet(this, _client2).getAuth(this.id, id);
@@ -1898,9 +3458,15 @@ var TriggerClient = class {
1898
3458
  async sendEvent(event, options) {
1899
3459
  return __privateGet(this, _client2).sendEvent(event, options);
1900
3460
  }
3461
+ async sendEvents(events, options) {
3462
+ return __privateGet(this, _client2).sendEvents(events, options);
3463
+ }
1901
3464
  async cancelEvent(eventId) {
1902
3465
  return __privateGet(this, _client2).cancelEvent(eventId);
1903
3466
  }
3467
+ async cancelRunsForEvent(eventId) {
3468
+ return __privateGet(this, _client2).cancelRunsForEvent(eventId);
3469
+ }
1904
3470
  async updateStatus(runId, id, status) {
1905
3471
  return __privateGet(this, _client2).updateStatus(runId, id, status);
1906
3472
  }
@@ -1916,12 +3482,26 @@ var TriggerClient = class {
1916
3482
  async getRun(runId, options) {
1917
3483
  return __privateGet(this, _client2).getRun(runId, options);
1918
3484
  }
3485
+ async cancelRun(runId) {
3486
+ return __privateGet(this, _client2).cancelRun(runId);
3487
+ }
1919
3488
  async getRuns(jobSlug, options) {
1920
3489
  return __privateGet(this, _client2).getRuns(jobSlug, options);
1921
3490
  }
1922
3491
  async getRunStatuses(runId) {
1923
3492
  return __privateGet(this, _client2).getRunStatuses(runId);
1924
3493
  }
3494
+ async invokeJob(jobId, payload, options) {
3495
+ return __privateGet(this, _client2).invokeJob(jobId, payload, options);
3496
+ }
3497
+ async createEphemeralEventDispatcher(payload) {
3498
+ return __privateGet(this, _client2).createEphemeralEventDispatcher(payload);
3499
+ }
3500
+ get store() {
3501
+ return {
3502
+ env: __privateGet(this, _envStore)
3503
+ };
3504
+ }
1925
3505
  authorized(apiKey) {
1926
3506
  if (typeof apiKey !== "string") {
1927
3507
  return "missing-header";
@@ -1940,11 +3520,16 @@ __name(TriggerClient, "TriggerClient");
1940
3520
  _options4 = new WeakMap();
1941
3521
  _registeredJobs = new WeakMap();
1942
3522
  _registeredSources = new WeakMap();
3523
+ _registeredWebhooks = new WeakMap();
1943
3524
  _registeredHttpSourceHandlers = new WeakMap();
3525
+ _registeredWebhookSourceHandlers = new WeakMap();
1944
3526
  _registeredDynamicTriggers = new WeakMap();
1945
3527
  _jobMetadataByDynamicTriggers = new WeakMap();
1946
3528
  _registeredSchedules = new WeakMap();
3529
+ _registeredHttpEndpoints = new WeakMap();
1947
3530
  _authResolvers = new WeakMap();
3531
+ _envStore = new WeakMap();
3532
+ _eventEmitter = new WeakMap();
1948
3533
  _client2 = new WeakMap();
1949
3534
  _internalLogger = new WeakMap();
1950
3535
  _preprocessRun = new WeakSet();
@@ -1958,22 +3543,30 @@ preprocessRun_fn = /* @__PURE__ */ __name(async function(body, job) {
1958
3543
  };
1959
3544
  }, "#preprocessRun");
1960
3545
  _executeJob = new WeakSet();
1961
- executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1) {
3546
+ executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1, timeOrigin, triggerVersion) {
1962
3547
  __privateGet(this, _internalLogger).debug("executing job", {
1963
3548
  execution: body1,
1964
3549
  job: job1.id,
1965
- version: job1.version
3550
+ version: job1.version,
3551
+ triggerVersion
1966
3552
  });
1967
3553
  const context = __privateMethod(this, _createRunContext, createRunContext_fn).call(this, body1);
1968
3554
  const io = new IO({
1969
3555
  id: body1.run.id,
3556
+ jobId: job1.id,
1970
3557
  cachedTasks: body1.tasks,
3558
+ cachedTasksCursor: body1.cachedTaskCursor,
3559
+ yieldedExecutions: body1.yieldedExecutions ?? [],
3560
+ noopTasksSet: body1.noopTasksSet,
1971
3561
  apiClient: __privateGet(this, _client2),
1972
3562
  logger: __privateGet(this, _internalLogger),
1973
3563
  client: this,
1974
3564
  context,
1975
3565
  jobLogLevel: job1.logLevel ?? __privateGet(this, _options4).logLevel ?? "info",
1976
- jobLogger: __privateGet(this, _options4).ioLogLocalEnabled ? new import_core7.Logger(job1.id, job1.logLevel ?? __privateGet(this, _options4).logLevel ?? "info") : void 0
3566
+ jobLogger: __privateGet(this, _options4).ioLogLocalEnabled ? new import_core8.Logger(job1.id, job1.logLevel ?? __privateGet(this, _options4).logLevel ?? "info") : void 0,
3567
+ serverVersion: triggerVersion,
3568
+ timeOrigin,
3569
+ executionTimeout: body1.runChunkExecutionLimit
1977
3570
  });
1978
3571
  const resolvedConnections = await __privateMethod(this, _resolveConnections, resolveConnections_fn).call(this, context, job1.options.integrations, body1.connections);
1979
3572
  if (!resolvedConnections.ok) {
@@ -1984,78 +3577,155 @@ executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1) {
1984
3577
  }
1985
3578
  const ioWithConnections = createIOWithIntegrations(io, resolvedConnections.data, job1.options.integrations);
1986
3579
  try {
3580
+ const parsedPayload = job1.trigger.event.parsePayload(body1.event.payload ?? {});
3581
+ if (!context.run.isTest) {
3582
+ const verified = await job1.trigger.verifyPayload(parsedPayload);
3583
+ if (!verified.success) {
3584
+ return {
3585
+ status: "ERROR",
3586
+ error: {
3587
+ message: `Payload verification failed. ${verified.reason}`
3588
+ }
3589
+ };
3590
+ }
3591
+ }
1987
3592
  const output = await runLocalStorage.runWith({
1988
3593
  io,
1989
3594
  ctx: context
1990
3595
  }, () => {
1991
- return job1.options.run(job1.trigger.event.parsePayload(body1.event.payload ?? {}), ioWithConnections, context);
3596
+ return job1.options.run(parsedPayload, ioWithConnections, context);
1992
3597
  });
3598
+ if (__privateGet(this, _options4).verbose) {
3599
+ __privateMethod(this, _logIOStats, logIOStats_fn).call(this, io.stats);
3600
+ }
1993
3601
  return {
1994
3602
  status: "SUCCESS",
1995
3603
  output
1996
3604
  };
1997
3605
  } catch (error) {
1998
- if (error instanceof ParsedPayloadSchemaError) {
1999
- return {
2000
- status: "INVALID_PAYLOAD",
2001
- errors: error.schemaErrors
2002
- };
2003
- }
2004
- if (error instanceof ResumeWithTaskError) {
2005
- return {
2006
- status: "RESUME_WITH_TASK",
2007
- task: error.task
2008
- };
3606
+ if (__privateGet(this, _options4).verbose) {
3607
+ __privateMethod(this, _logIOStats, logIOStats_fn).call(this, io.stats);
2009
3608
  }
2010
- if (error instanceof RetryWithTaskError) {
3609
+ if (error instanceof ResumeWithParallelTaskError) {
2011
3610
  return {
2012
- status: "RETRY_WITH_TASK",
3611
+ status: "RESUME_WITH_PARALLEL_TASK",
2013
3612
  task: error.task,
2014
- error: error.cause,
2015
- retryAt: error.retryAt
2016
- };
2017
- }
2018
- if (error instanceof CanceledWithTaskError) {
2019
- return {
2020
- status: "CANCELED",
2021
- task: error.task
3613
+ childErrors: error.childErrors.map((childError) => {
3614
+ return __privateMethod(this, _convertErrorToExecutionResponse, convertErrorToExecutionResponse_fn).call(this, childError, body1);
3615
+ })
2022
3616
  };
2023
3617
  }
2024
- if (error instanceof RetryWithTaskError) {
2025
- const errorWithStack2 = import_core7.ErrorWithStackSchema.safeParse(error.cause);
2026
- if (errorWithStack2.success) {
2027
- return {
2028
- status: "ERROR",
2029
- error: errorWithStack2.data,
2030
- task: error.task
2031
- };
3618
+ return __privateMethod(this, _convertErrorToExecutionResponse, convertErrorToExecutionResponse_fn).call(this, error, body1);
3619
+ }
3620
+ }, "#executeJob");
3621
+ _convertErrorToExecutionResponse = new WeakSet();
3622
+ convertErrorToExecutionResponse_fn = /* @__PURE__ */ __name(function(error, body2) {
3623
+ if (error instanceof AutoYieldExecutionError) {
3624
+ return {
3625
+ status: "AUTO_YIELD_EXECUTION",
3626
+ location: error.location,
3627
+ timeRemaining: error.timeRemaining,
3628
+ timeElapsed: error.timeElapsed,
3629
+ limit: body2.runChunkExecutionLimit
3630
+ };
3631
+ }
3632
+ if (error instanceof AutoYieldWithCompletedTaskExecutionError) {
3633
+ return {
3634
+ status: "AUTO_YIELD_EXECUTION_WITH_COMPLETED_TASK",
3635
+ id: error.id,
3636
+ properties: error.properties,
3637
+ output: error.output,
3638
+ data: {
3639
+ ...error.data,
3640
+ limit: body2.runChunkExecutionLimit
2032
3641
  }
3642
+ };
3643
+ }
3644
+ if (error instanceof YieldExecutionError) {
3645
+ return {
3646
+ status: "YIELD_EXECUTION",
3647
+ key: error.key
3648
+ };
3649
+ }
3650
+ if (error instanceof ParsedPayloadSchemaError) {
3651
+ return {
3652
+ status: "INVALID_PAYLOAD",
3653
+ errors: error.schemaErrors
3654
+ };
3655
+ }
3656
+ if (error instanceof ResumeWithTaskError) {
3657
+ return {
3658
+ status: "RESUME_WITH_TASK",
3659
+ task: error.task
3660
+ };
3661
+ }
3662
+ if (error instanceof RetryWithTaskError) {
3663
+ return {
3664
+ status: "RETRY_WITH_TASK",
3665
+ task: error.task,
3666
+ error: error.cause,
3667
+ retryAt: error.retryAt
3668
+ };
3669
+ }
3670
+ if (error instanceof CanceledWithTaskError) {
3671
+ return {
3672
+ status: "CANCELED",
3673
+ task: error.task
3674
+ };
3675
+ }
3676
+ if (error instanceof ErrorWithTask) {
3677
+ const errorWithStack2 = import_core8.ErrorWithStackSchema.safeParse(error.cause.output);
3678
+ if (errorWithStack2.success) {
2033
3679
  return {
2034
3680
  status: "ERROR",
2035
- error: {
2036
- message: "Unknown error"
2037
- },
2038
- task: error.task
3681
+ error: errorWithStack2.data,
3682
+ task: error.cause
2039
3683
  };
2040
3684
  }
2041
- const errorWithStack = import_core7.ErrorWithStackSchema.safeParse(error);
2042
- if (errorWithStack.success) {
3685
+ return {
3686
+ status: "ERROR",
3687
+ error: {
3688
+ message: JSON.stringify(error.cause.output)
3689
+ },
3690
+ task: error.cause
3691
+ };
3692
+ }
3693
+ if (error instanceof RetryWithTaskError) {
3694
+ const errorWithStack2 = import_core8.ErrorWithStackSchema.safeParse(error.cause);
3695
+ if (errorWithStack2.success) {
2043
3696
  return {
2044
3697
  status: "ERROR",
2045
- error: errorWithStack.data
3698
+ error: errorWithStack2.data,
3699
+ task: error.task
2046
3700
  };
2047
3701
  }
2048
3702
  return {
2049
3703
  status: "ERROR",
2050
3704
  error: {
2051
3705
  message: "Unknown error"
2052
- }
3706
+ },
3707
+ task: error.task
2053
3708
  };
2054
3709
  }
2055
- }, "#executeJob");
3710
+ const errorWithStack = import_core8.ErrorWithStackSchema.safeParse(error);
3711
+ if (errorWithStack.success) {
3712
+ return {
3713
+ status: "ERROR",
3714
+ error: errorWithStack.data
3715
+ };
3716
+ }
3717
+ const message = typeof error === "string" ? error : JSON.stringify(error);
3718
+ return {
3719
+ status: "ERROR",
3720
+ error: {
3721
+ name: "Unknown error",
3722
+ message
3723
+ }
3724
+ };
3725
+ }, "#convertErrorToExecutionResponse");
2056
3726
  _createRunContext = new WeakSet();
2057
3727
  createRunContext_fn = /* @__PURE__ */ __name(function(execution) {
2058
- const { event, organization, environment, job, run, source } = execution;
3728
+ const { event, organization, project, environment, job, run, source } = execution;
2059
3729
  return {
2060
3730
  event: {
2061
3731
  id: event.id,
@@ -2064,6 +3734,11 @@ createRunContext_fn = /* @__PURE__ */ __name(function(execution) {
2064
3734
  timestamp: event.timestamp
2065
3735
  },
2066
3736
  organization,
3737
+ project: project ?? {
3738
+ id: "unknown",
3739
+ name: "unknown",
3740
+ slug: "unknown"
3741
+ },
2067
3742
  environment,
2068
3743
  job,
2069
3744
  run,
@@ -2072,8 +3747,8 @@ createRunContext_fn = /* @__PURE__ */ __name(function(execution) {
2072
3747
  };
2073
3748
  }, "#createRunContext");
2074
3749
  _createPreprocessRunContext = new WeakSet();
2075
- createPreprocessRunContext_fn = /* @__PURE__ */ __name(function(body2) {
2076
- const { event, organization, environment, job, run, account } = body2;
3750
+ createPreprocessRunContext_fn = /* @__PURE__ */ __name(function(body3) {
3751
+ const { event, organization, environment, job, run, account } = body3;
2077
3752
  return {
2078
3753
  event: {
2079
3754
  id: event.id,
@@ -2170,8 +3845,97 @@ handleHttpSourceRequest_fn = /* @__PURE__ */ __name(async function(source, sourc
2170
3845
  metadata: results.metadata
2171
3846
  };
2172
3847
  }, "#handleHttpSourceRequest");
3848
+ _handleHttpEndpointRequestForResponse = new WeakSet();
3849
+ handleHttpEndpointRequestForResponse_fn = /* @__PURE__ */ __name(async function(data, sourceRequest1) {
3850
+ __privateGet(this, _internalLogger).debug("Handling HTTP Endpoint request for response", {
3851
+ data
3852
+ });
3853
+ const httpEndpoint2 = __privateGet(this, _registeredHttpEndpoints)[data.key];
3854
+ if (!httpEndpoint2) {
3855
+ __privateGet(this, _internalLogger).debug("No handler registered for HTTP Endpoint", {
3856
+ data
3857
+ });
3858
+ return {
3859
+ response: {
3860
+ status: 200,
3861
+ body: {
3862
+ ok: true
3863
+ }
3864
+ }
3865
+ };
3866
+ }
3867
+ const handledResponse = await httpEndpoint2.handleRequest(sourceRequest1);
3868
+ if (!handledResponse) {
3869
+ __privateGet(this, _internalLogger).debug("There's no HTTP Endpoint respondWith.handler()", {
3870
+ data
3871
+ });
3872
+ return {
3873
+ response: {
3874
+ status: 200,
3875
+ body: {
3876
+ ok: true
3877
+ }
3878
+ }
3879
+ };
3880
+ }
3881
+ let body;
3882
+ try {
3883
+ body = await handledResponse.text();
3884
+ } catch (error) {
3885
+ __privateGet(this, _internalLogger).error(`Error reading httpEndpoint ${httpEndpoint2.id} respondWith.handler Response`, {
3886
+ error
3887
+ });
3888
+ }
3889
+ const response = {
3890
+ status: handledResponse.status,
3891
+ headers: handledResponse.headers ? Object.fromEntries(handledResponse.headers.entries()) : void 0,
3892
+ body
3893
+ };
3894
+ __privateGet(this, _internalLogger).info(`httpEndpoint ${httpEndpoint2.id} respondWith.handler response`, {
3895
+ response
3896
+ });
3897
+ return {
3898
+ response
3899
+ };
3900
+ }, "#handleHttpEndpointRequestForResponse");
3901
+ _handleWebhookRequest = new WeakSet();
3902
+ handleWebhookRequest_fn = /* @__PURE__ */ __name(async function(request, ctx) {
3903
+ __privateGet(this, _internalLogger).debug("Handling webhook request", {
3904
+ ctx
3905
+ });
3906
+ const okResponse = {
3907
+ status: 200,
3908
+ body: {
3909
+ ok: true
3910
+ }
3911
+ };
3912
+ const handlers = __privateGet(this, _registeredWebhookSourceHandlers)[ctx.key];
3913
+ if (!handlers) {
3914
+ __privateGet(this, _internalLogger).debug("No handler registered for webhook", {
3915
+ ctx
3916
+ });
3917
+ return {
3918
+ response: okResponse,
3919
+ verified: false
3920
+ };
3921
+ }
3922
+ const { verify, generateEvents } = handlers;
3923
+ const verifyResult = await verify(request, this, ctx);
3924
+ if (!verifyResult.success) {
3925
+ return {
3926
+ response: okResponse,
3927
+ verified: false,
3928
+ error: verifyResult.reason
3929
+ };
3930
+ }
3931
+ await generateEvents(request, this, ctx);
3932
+ return {
3933
+ response: okResponse,
3934
+ verified: true
3935
+ };
3936
+ }, "#handleWebhookRequest");
2173
3937
  _resolveConnections = new WeakSet();
2174
- resolveConnections_fn = /* @__PURE__ */ __name(async function(ctx, integrations, connections) {
3938
+ resolveConnections_fn = /* @__PURE__ */ __name(async function(ctx1, integrations, connections) {
2175
3939
  if (!integrations) {
2176
3940
  return {
2177
3941
  ok: true,
@@ -2181,7 +3945,7 @@ resolveConnections_fn = /* @__PURE__ */ __name(async function(ctx, integrations,
2181
3945
  const resolvedAuthResults = await Promise.all(Object.keys(integrations).map(async (key) => {
2182
3946
  const integration = integrations[key];
2183
3947
  const auth = (connections ?? {})[key];
2184
- const result = await __privateMethod(this, _resolveConnection, resolveConnection_fn).call(this, ctx, integration, auth);
3948
+ const result = await __privateMethod(this, _resolveConnection, resolveConnection_fn).call(this, ctx1, integration, auth);
2185
3949
  if (result.ok) {
2186
3950
  return {
2187
3951
  ok: true,
@@ -2223,7 +3987,7 @@ resolveConnections_fn = /* @__PURE__ */ __name(async function(ctx, integrations,
2223
3987
  }
2224
3988
  }, "#resolveConnections");
2225
3989
  _resolveConnection = new WeakSet();
2226
- resolveConnection_fn = /* @__PURE__ */ __name(async function(ctx1, integration, auth) {
3990
+ resolveConnection_fn = /* @__PURE__ */ __name(async function(ctx2, integration, auth) {
2227
3991
  if (auth) {
2228
3992
  return {
2229
3993
  ok: true,
@@ -2244,7 +4008,7 @@ resolveConnection_fn = /* @__PURE__ */ __name(async function(ctx1, integration,
2244
4008
  };
2245
4009
  }
2246
4010
  try {
2247
- const resolvedAuth = await authResolver(ctx1, integration);
4011
+ const resolvedAuth = await authResolver(ctx2, integration);
2248
4012
  if (!resolvedAuth) {
2249
4013
  return {
2250
4014
  ok: false,
@@ -2298,7 +4062,11 @@ buildJobIndex_fn = /* @__PURE__ */ __name(function(job2) {
2298
4062
  startPosition: "latest",
2299
4063
  enabled: job2.enabled,
2300
4064
  preprocessRuns: job2.trigger.preprocessRuns,
2301
- internal
4065
+ internal,
4066
+ concurrencyLimit: typeof job2.options.concurrencyLimit === "number" ? job2.options.concurrencyLimit : typeof job2.options.concurrencyLimit === "object" ? {
4067
+ id: job2.options.concurrencyLimit.id,
4068
+ limit: job2.options.concurrencyLimit.limit
4069
+ } : void 0
2302
4070
  };
2303
4071
  }, "#buildJobIndex");
2304
4072
  _buildJobIntegrations = new WeakSet();
@@ -2318,6 +4086,59 @@ buildJobIntegration_fn = /* @__PURE__ */ __name(function(integration1) {
2318
4086
  authSource
2319
4087
  };
2320
4088
  }, "#buildJobIntegration");
4089
+ _logIOStats = new WeakSet();
4090
+ logIOStats_fn = /* @__PURE__ */ __name(function(stats) {
4091
+ __privateGet(this, _internalLogger).debug("IO stats", {
4092
+ stats
4093
+ });
4094
+ }, "#logIOStats");
4095
+ _standardResponseHeaders = new WeakSet();
4096
+ standardResponseHeaders_fn = /* @__PURE__ */ __name(function(start) {
4097
+ return {
4098
+ "Trigger-Version": import_core8.API_VERSIONS.LAZY_LOADED_CACHED_TASKS,
4099
+ "Trigger-SDK-Version": version,
4100
+ "X-Trigger-Request-Timing": `dur=${performance.now() - start / 1e3}`
4101
+ };
4102
+ }, "#standardResponseHeaders");
4103
+ _serializeRunMetadata = new WeakSet();
4104
+ serializeRunMetadata_fn = /* @__PURE__ */ __name(function(job4) {
4105
+ const metadata = {};
4106
+ if (__privateGet(this, _eventEmitter).listenerCount("runSucceeeded") > 0 || typeof job4.options.onSuccess === "function") {
4107
+ metadata["successSubscription"] = true;
4108
+ }
4109
+ if (__privateGet(this, _eventEmitter).listenerCount("runFailed") > 0 || typeof job4.options.onFailure === "function") {
4110
+ metadata["failedSubscription"] = true;
4111
+ }
4112
+ return JSON.stringify(metadata);
4113
+ }, "#serializeRunMetadata");
4114
+ _deliverSuccessfulRunNotification = new WeakSet();
4115
+ deliverSuccessfulRunNotification_fn = /* @__PURE__ */ __name(async function(notification) {
4116
+ __privateGet(this, _internalLogger).debug("delivering successful run notification", {
4117
+ notification
4118
+ });
4119
+ __privateGet(this, _eventEmitter).emit("runSucceeeded", notification);
4120
+ const job = __privateGet(this, _registeredJobs)[notification.job.id];
4121
+ if (!job) {
4122
+ return;
4123
+ }
4124
+ if (typeof job.options.onSuccess === "function") {
4125
+ await job.options.onSuccess(notification);
4126
+ }
4127
+ }, "#deliverSuccessfulRunNotification");
4128
+ _deliverFailedRunNotification = new WeakSet();
4129
+ deliverFailedRunNotification_fn = /* @__PURE__ */ __name(async function(notification1) {
4130
+ __privateGet(this, _internalLogger).debug("delivering failed run notification", {
4131
+ notification: notification1
4132
+ });
4133
+ __privateGet(this, _eventEmitter).emit("runFailed", notification1);
4134
+ const job = __privateGet(this, _registeredJobs)[notification1.job.id];
4135
+ if (!job) {
4136
+ return;
4137
+ }
4138
+ if (typeof job.options.onFailure === "function") {
4139
+ await job.options.onFailure(notification1);
4140
+ }
4141
+ }, "#deliverFailedRunNotification");
2321
4142
  function dynamicTriggerRegisterSourceJobId(id) {
2322
4143
  return `register-dynamic-trigger-${id}`;
2323
4144
  }
@@ -2343,7 +4164,7 @@ function deepMergeOptions(obj1, obj2) {
2343
4164
  __name(deepMergeOptions, "deepMergeOptions");
2344
4165
 
2345
4166
  // src/triggers/externalSource.ts
2346
- var import_core8 = require("@trigger.dev/core");
4167
+ var import_core9 = require("@trigger.dev/core");
2347
4168
  var ExternalSource = class {
2348
4169
  constructor(channel, options) {
2349
4170
  this.options = options;
@@ -2417,7 +4238,7 @@ var ExternalSourceTrigger = class {
2417
4238
  title: "External Source",
2418
4239
  rule: {
2419
4240
  event: this.event.name,
2420
- payload: (0, import_core8.deepMergeFilters)(this.options.source.filter(this.options.params, this.options.options), this.event.filter ?? {}, this.options.params.filter ?? {}),
4241
+ payload: (0, import_core9.deepMergeFilters)(this.options.source.filter(this.options.params, this.options.options), this.event.filter ?? {}, this.options.params.filter ?? {}),
2421
4242
  source: this.event.source
2422
4243
  },
2423
4244
  properties: this.options.source.properties(this.options.params)
@@ -2435,6 +4256,11 @@ var ExternalSourceTrigger = class {
2435
4256
  get preprocessRuns() {
2436
4257
  return true;
2437
4258
  }
4259
+ async verifyPayload(payload) {
4260
+ return {
4261
+ success: true
4262
+ };
4263
+ }
2438
4264
  };
2439
4265
  __name(ExternalSourceTrigger, "ExternalSourceTrigger");
2440
4266
  function omit(obj, key) {
@@ -2452,7 +4278,7 @@ function omit(obj, key) {
2452
4278
  __name(omit, "omit");
2453
4279
 
2454
4280
  // src/triggers/notifications.ts
2455
- var import_core9 = require("@trigger.dev/core");
4281
+ var import_core10 = require("@trigger.dev/core");
2456
4282
  function missingConnectionNotification(integrations) {
2457
4283
  return new MissingConnectionNotification({
2458
4284
  integrations
@@ -2471,11 +4297,11 @@ var MissingConnectionNotification = class {
2471
4297
  }
2472
4298
  get event() {
2473
4299
  return {
2474
- name: import_core9.MISSING_CONNECTION_NOTIFICATION,
4300
+ name: import_core10.MISSING_CONNECTION_NOTIFICATION,
2475
4301
  title: "Missing Connection Notification",
2476
4302
  source: "trigger.dev",
2477
4303
  icon: "connection-alert",
2478
- parsePayload: import_core9.MissingConnectionNotificationPayloadSchema.parse,
4304
+ parsePayload: import_core10.MissingConnectionNotificationPayloadSchema.parse,
2479
4305
  properties: [
2480
4306
  {
2481
4307
  label: "Integrations",
@@ -2489,6 +4315,11 @@ var MissingConnectionNotification = class {
2489
4315
  get preprocessRuns() {
2490
4316
  return false;
2491
4317
  }
4318
+ async verifyPayload(payload) {
4319
+ return {
4320
+ success: true
4321
+ };
4322
+ }
2492
4323
  toJSON() {
2493
4324
  return {
2494
4325
  type: "static",
@@ -2512,11 +4343,11 @@ var MissingConnectionResolvedNotification = class {
2512
4343
  }
2513
4344
  get event() {
2514
4345
  return {
2515
- name: import_core9.MISSING_CONNECTION_RESOLVED_NOTIFICATION,
4346
+ name: import_core10.MISSING_CONNECTION_RESOLVED_NOTIFICATION,
2516
4347
  title: "Missing Connection Resolved Notification",
2517
4348
  source: "trigger.dev",
2518
4349
  icon: "connection-alert",
2519
- parsePayload: import_core9.MissingConnectionResolvedNotificationPayloadSchema.parse,
4350
+ parsePayload: import_core10.MissingConnectionResolvedNotificationPayloadSchema.parse,
2520
4351
  properties: [
2521
4352
  {
2522
4353
  label: "Integrations",
@@ -2530,6 +4361,11 @@ var MissingConnectionResolvedNotification = class {
2530
4361
  get preprocessRuns() {
2531
4362
  return false;
2532
4363
  }
4364
+ async verifyPayload(payload) {
4365
+ return {
4366
+ success: true
4367
+ };
4368
+ }
2533
4369
  toJSON() {
2534
4370
  return {
2535
4371
  type: "static",
@@ -2548,6 +4384,249 @@ var MissingConnectionResolvedNotification = class {
2548
4384
  };
2549
4385
  __name(MissingConnectionResolvedNotification, "MissingConnectionResolvedNotification");
2550
4386
 
4387
+ // src/triggers/invokeTrigger.ts
4388
+ var _options5;
4389
+ var InvokeTrigger = class {
4390
+ constructor(options) {
4391
+ __privateAdd(this, _options5, void 0);
4392
+ __privateSet(this, _options5, options);
4393
+ }
4394
+ toJSON() {
4395
+ return {
4396
+ type: "invoke"
4397
+ };
4398
+ }
4399
+ get event() {
4400
+ return {
4401
+ name: "invoke",
4402
+ title: "Manual Invoke",
4403
+ source: "trigger.dev",
4404
+ examples: __privateGet(this, _options5).examples ?? [],
4405
+ icon: "trigger",
4406
+ parsePayload: (rawPayload) => {
4407
+ if (__privateGet(this, _options5).schema) {
4408
+ const results = __privateGet(this, _options5).schema.safeParse(rawPayload);
4409
+ if (!results.success) {
4410
+ throw new ParsedPayloadSchemaError(formatSchemaErrors(results.error.issues));
4411
+ }
4412
+ return results.data;
4413
+ }
4414
+ return rawPayload;
4415
+ },
4416
+ parseInvokePayload: (rawPayload) => {
4417
+ if (__privateGet(this, _options5).schema) {
4418
+ const results = __privateGet(this, _options5).schema.safeParse(rawPayload);
4419
+ if (!results.success) {
4420
+ throw new ParsedPayloadSchemaError(formatSchemaErrors(results.error.issues));
4421
+ }
4422
+ return results.data;
4423
+ }
4424
+ return rawPayload;
4425
+ }
4426
+ };
4427
+ }
4428
+ attachToJob(triggerClient, job) {
4429
+ }
4430
+ get preprocessRuns() {
4431
+ return false;
4432
+ }
4433
+ async verifyPayload() {
4434
+ return {
4435
+ success: true
4436
+ };
4437
+ }
4438
+ };
4439
+ __name(InvokeTrigger, "InvokeTrigger");
4440
+ _options5 = new WeakMap();
4441
+ function invokeTrigger(options) {
4442
+ return new InvokeTrigger(options ?? {});
4443
+ }
4444
+ __name(invokeTrigger, "invokeTrigger");
4445
+
4446
+ // src/triggers/webhook.ts
4447
+ var import_core11 = require("@trigger.dev/core");
4448
+ var import_node_crypto2 = require("crypto");
4449
+ var _shortHash, shortHash_fn;
4450
+ var WebhookSource = class {
4451
+ constructor(options) {
4452
+ __privateAdd(this, _shortHash);
4453
+ this.options = options;
4454
+ }
4455
+ async generateEvents(request, client, ctx) {
4456
+ return this.options.generateEvents({
4457
+ request,
4458
+ client,
4459
+ ctx
4460
+ });
4461
+ }
4462
+ filter(params, config) {
4463
+ return this.options.filter?.(params, config) ?? {};
4464
+ }
4465
+ properties(params) {
4466
+ return this.options.properties?.(params) ?? [];
4467
+ }
4468
+ get crud() {
4469
+ return this.options.crud;
4470
+ }
4471
+ async register(params, registerEvent, io, ctx) {
4472
+ if (!this.options.register) {
4473
+ return;
4474
+ }
4475
+ const updates = await this.options.register({
4476
+ ...registerEvent,
4477
+ params
4478
+ }, io, ctx);
4479
+ return updates;
4480
+ }
4481
+ async verify(request, client, ctx) {
4482
+ if (this.options.verify) {
4483
+ const clonedRequest = request.clone();
4484
+ return this.options.verify({
4485
+ request: clonedRequest,
4486
+ client,
4487
+ ctx
4488
+ });
4489
+ }
4490
+ return {
4491
+ success: true
4492
+ };
4493
+ }
4494
+ key(params) {
4495
+ const parts = [
4496
+ "webhook"
4497
+ ];
4498
+ parts.push(this.options.key(params));
4499
+ parts.push(this.integration.id);
4500
+ return `${this.options.id}-${__privateMethod(this, _shortHash, shortHash_fn).call(this, parts.join(""))}`;
4501
+ }
4502
+ get integration() {
4503
+ return this.options.integration;
4504
+ }
4505
+ get integrationConfig() {
4506
+ return {
4507
+ id: this.integration.id,
4508
+ metadata: this.integration.metadata
4509
+ };
4510
+ }
4511
+ get id() {
4512
+ return this.options.id;
4513
+ }
4514
+ get version() {
4515
+ return this.options.version;
4516
+ }
4517
+ };
4518
+ __name(WebhookSource, "WebhookSource");
4519
+ _shortHash = new WeakSet();
4520
+ shortHash_fn = /* @__PURE__ */ __name(function(str) {
4521
+ const hash = (0, import_node_crypto2.createHash)("sha1").update(str).digest("hex");
4522
+ return hash.slice(0, 7);
4523
+ }, "#shortHash");
4524
+ var WebhookTrigger = class {
4525
+ constructor(options) {
4526
+ this.options = options;
4527
+ }
4528
+ get event() {
4529
+ return this.options.event;
4530
+ }
4531
+ get source() {
4532
+ return this.options.source;
4533
+ }
4534
+ get key() {
4535
+ return slugifyId(this.options.source.key(this.options.params));
4536
+ }
4537
+ toJSON() {
4538
+ return {
4539
+ type: "static",
4540
+ title: "Webhook",
4541
+ rule: {
4542
+ event: this.event.name,
4543
+ payload: (0, import_core11.deepMergeFilters)(this.options.source.filter(this.options.params, this.options.config), this.event.filter ?? {}),
4544
+ source: this.event.source
4545
+ },
4546
+ properties: this.options.source.properties(this.options.params),
4547
+ link: `http-endpoints/${this.key}`
4548
+ };
4549
+ }
4550
+ filter(eventFilter) {
4551
+ const { event, ...optionsWithoutEvent } = this.options;
4552
+ const { filter, ...eventWithoutFilter } = event;
4553
+ return new WebhookTrigger({
4554
+ ...optionsWithoutEvent,
4555
+ event: {
4556
+ ...eventWithoutFilter,
4557
+ filter: (0, import_core11.deepMergeFilters)(filter ?? {}, eventFilter)
4558
+ }
4559
+ });
4560
+ }
4561
+ attachToJob(triggerClient, job) {
4562
+ triggerClient.defineHttpEndpoint({
4563
+ id: this.key,
4564
+ source: "trigger.dev",
4565
+ icon: this.event.icon,
4566
+ verify: async () => ({
4567
+ success: true
4568
+ })
4569
+ }, true);
4570
+ triggerClient.attachWebhook({
4571
+ key: this.key,
4572
+ source: this.options.source,
4573
+ event: this.options.event,
4574
+ params: this.options.params,
4575
+ config: this.options.config
4576
+ });
4577
+ }
4578
+ get preprocessRuns() {
4579
+ return true;
4580
+ }
4581
+ async verifyPayload(payload) {
4582
+ return {
4583
+ success: true
4584
+ };
4585
+ }
4586
+ };
4587
+ __name(WebhookTrigger, "WebhookTrigger");
4588
+
4589
+ // src/security.ts
4590
+ var import_crypto = __toESM(require("crypto"));
4591
+ async function verifyRequestSignature({ request, headerName, headerEncoding = "hex", secret, algorithm }) {
4592
+ if (!secret) {
4593
+ return {
4594
+ success: false,
4595
+ reason: "Missing secret \u2013 you've probably not set an environment variable."
4596
+ };
4597
+ }
4598
+ const headerValue = request.headers.get(headerName);
4599
+ if (!headerValue) {
4600
+ return {
4601
+ success: false,
4602
+ reason: "Missing header"
4603
+ };
4604
+ }
4605
+ switch (algorithm) {
4606
+ case "sha256":
4607
+ const success = verifyHmacSha256(headerValue, headerEncoding, secret, await request.text());
4608
+ if (success) {
4609
+ return {
4610
+ success
4611
+ };
4612
+ } else {
4613
+ return {
4614
+ success: false,
4615
+ reason: "Failed sha256 verification"
4616
+ };
4617
+ }
4618
+ default:
4619
+ throw new Error(`Unsupported algorithm: ${algorithm}`);
4620
+ }
4621
+ }
4622
+ __name(verifyRequestSignature, "verifyRequestSignature");
4623
+ function verifyHmacSha256(headerValue, headerEncoding, secret, body) {
4624
+ const bodyDigest = import_crypto.default.createHmac("sha256", secret).update(body).digest(headerEncoding);
4625
+ const signature = headerValue?.replace("hmac-sha256=", "").replace("sha256=", "") ?? "";
4626
+ return signature === bodyDigest;
4627
+ }
4628
+ __name(verifyHmacSha256, "verifyHmacSha256");
4629
+
2551
4630
  // src/index.ts
2552
4631
  function redactString(strings, ...interpolations) {
2553
4632
  return {
@@ -2562,24 +4641,34 @@ __name(redactString, "redactString");
2562
4641
  CronTrigger,
2563
4642
  DynamicSchedule,
2564
4643
  DynamicTrigger,
4644
+ EventSpecificationExampleSchema,
2565
4645
  EventTrigger,
2566
4646
  ExternalSource,
2567
4647
  ExternalSourceTrigger,
2568
4648
  IO,
2569
4649
  IOLogger,
2570
4650
  IntervalTrigger,
4651
+ InvokeTrigger,
4652
+ JSONOutputSerializer,
2571
4653
  Job,
2572
4654
  MissingConnectionNotification,
2573
4655
  MissingConnectionResolvedNotification,
2574
4656
  TriggerClient,
4657
+ WebhookSource,
4658
+ WebhookTrigger,
2575
4659
  cronTrigger,
2576
4660
  eventTrigger,
2577
4661
  intervalTrigger,
4662
+ invokeTrigger,
2578
4663
  isTriggerError,
2579
4664
  missingConnectionNotification,
2580
4665
  missingConnectionResolvedNotification,
2581
4666
  omit,
2582
4667
  redactString,
2583
- retry
4668
+ retry,
4669
+ slugifyId,
4670
+ verifyHmacSha256,
4671
+ verifyRequestSignature,
4672
+ waitForEventSchema
2584
4673
  });
2585
4674
  //# sourceMappingURL=index.js.map