@trigger.dev/sdk 2.2.7 → 2.2.8

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
@@ -70,6 +70,8 @@ __export(src_exports, {
70
70
  MissingConnectionNotification: () => MissingConnectionNotification,
71
71
  MissingConnectionResolvedNotification: () => MissingConnectionResolvedNotification,
72
72
  TriggerClient: () => TriggerClient,
73
+ WebhookSource: () => WebhookSource,
74
+ WebhookTrigger: () => WebhookTrigger,
73
75
  cronTrigger: () => cronTrigger,
74
76
  eventTrigger: () => eventTrigger,
75
77
  intervalTrigger: () => intervalTrigger,
@@ -80,6 +82,7 @@ __export(src_exports, {
80
82
  omit: () => omit,
81
83
  redactString: () => redactString,
82
84
  retry: () => retry,
85
+ slugifyId: () => slugifyId,
83
86
  verifyHmacSha256: () => verifyHmacSha256,
84
87
  verifyRequestSignature: () => verifyRequestSignature,
85
88
  waitForEventSchema: () => waitForEventSchema
@@ -292,1721 +295,2067 @@ var import_core8 = require("@trigger.dev/core");
292
295
  var import_colorette = require("colorette");
293
296
 
294
297
  // src/apiClient.ts
298
+ var import_core3 = require("@trigger.dev/core");
299
+ var import_zod3 = require("zod");
300
+
301
+ // src/io.ts
302
+ var import_core2 = require("@trigger.dev/core");
303
+ var import_core_backend = require("@trigger.dev/core-backend");
304
+ var import_node_async_hooks2 = require("async_hooks");
305
+ var import_node_crypto = require("crypto");
306
+
307
+ // src/errors.ts
308
+ var ResumeWithTaskError = class {
309
+ constructor(task) {
310
+ this.task = task;
311
+ }
312
+ };
313
+ __name(ResumeWithTaskError, "ResumeWithTaskError");
314
+ var ResumeWithParallelTaskError = class {
315
+ constructor(task, childErrors) {
316
+ this.task = task;
317
+ this.childErrors = childErrors;
318
+ }
319
+ };
320
+ __name(ResumeWithParallelTaskError, "ResumeWithParallelTaskError");
321
+ var RetryWithTaskError = class {
322
+ constructor(cause, task, retryAt) {
323
+ this.cause = cause;
324
+ this.task = task;
325
+ this.retryAt = retryAt;
326
+ }
327
+ };
328
+ __name(RetryWithTaskError, "RetryWithTaskError");
329
+ var CanceledWithTaskError = class {
330
+ constructor(task) {
331
+ this.task = task;
332
+ }
333
+ };
334
+ __name(CanceledWithTaskError, "CanceledWithTaskError");
335
+ var YieldExecutionError = class {
336
+ constructor(key) {
337
+ this.key = key;
338
+ }
339
+ };
340
+ __name(YieldExecutionError, "YieldExecutionError");
341
+ var AutoYieldExecutionError = class {
342
+ constructor(location, timeRemaining, timeElapsed) {
343
+ this.location = location;
344
+ this.timeRemaining = timeRemaining;
345
+ this.timeElapsed = timeElapsed;
346
+ }
347
+ };
348
+ __name(AutoYieldExecutionError, "AutoYieldExecutionError");
349
+ var AutoYieldWithCompletedTaskExecutionError = class {
350
+ constructor(id, properties, data, output) {
351
+ this.id = id;
352
+ this.properties = properties;
353
+ this.data = data;
354
+ this.output = output;
355
+ }
356
+ };
357
+ __name(AutoYieldWithCompletedTaskExecutionError, "AutoYieldWithCompletedTaskExecutionError");
358
+ var ParsedPayloadSchemaError = class {
359
+ constructor(schemaErrors) {
360
+ this.schemaErrors = schemaErrors;
361
+ }
362
+ };
363
+ __name(ParsedPayloadSchemaError, "ParsedPayloadSchemaError");
364
+ function isTriggerError(err) {
365
+ return err instanceof ResumeWithTaskError || err instanceof RetryWithTaskError || err instanceof CanceledWithTaskError || err instanceof YieldExecutionError || err instanceof AutoYieldExecutionError || err instanceof AutoYieldWithCompletedTaskExecutionError || err instanceof ResumeWithParallelTaskError;
366
+ }
367
+ __name(isTriggerError, "isTriggerError");
368
+ var ErrorWithTask = class extends Error {
369
+ constructor(cause, message) {
370
+ super(message);
371
+ this.cause = cause;
372
+ }
373
+ };
374
+ __name(ErrorWithTask, "ErrorWithTask");
375
+
376
+ // src/retry.ts
295
377
  var import_core = require("@trigger.dev/core");
296
- var import_zod = require("zod");
297
- var _apiUrl, _options, _logger, _apiKey, apiKey_fn;
298
- var ApiClient = class {
299
- constructor(options) {
300
- __privateAdd(this, _apiKey);
301
- __privateAdd(this, _apiUrl, void 0);
302
- __privateAdd(this, _options, void 0);
303
- __privateAdd(this, _logger, void 0);
304
- __privateSet(this, _options, options);
305
- __privateSet(this, _apiUrl, __privateGet(this, _options).apiUrl ?? process.env.TRIGGER_API_URL ?? "https://api.trigger.dev");
306
- __privateSet(this, _logger, new import_core.Logger("trigger.dev", __privateGet(this, _options).logLevel));
378
+ var retry = {
379
+ standardBackoff: {
380
+ limit: 8,
381
+ factor: 1.8,
382
+ minTimeoutInMs: 500,
383
+ maxTimeoutInMs: 3e4,
384
+ randomize: true
385
+ },
386
+ exponentialBackoff: {
387
+ limit: 8,
388
+ factor: 2,
389
+ minTimeoutInMs: 1e3,
390
+ maxTimeoutInMs: 3e4,
391
+ randomize: true
307
392
  }
308
- async registerEndpoint(options) {
309
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
310
- __privateGet(this, _logger).debug("Registering endpoint", {
311
- url: options.url,
312
- name: options.name
313
- });
314
- const response = await fetch(`${__privateGet(this, _apiUrl)}/api/v1/endpoints`, {
315
- method: "POST",
316
- headers: {
317
- "Content-Type": "application/json",
318
- Authorization: `Bearer ${apiKey}`
319
- },
320
- body: JSON.stringify({
321
- url: options.url,
322
- name: options.name
323
- })
324
- });
325
- if (response.status >= 400 && response.status < 500) {
326
- const body = await response.json();
327
- throw new Error(body.error);
393
+ };
394
+
395
+ // src/status.ts
396
+ var TriggerStatus = class {
397
+ constructor(id, io) {
398
+ this.id = id;
399
+ this.io = io;
400
+ }
401
+ async update(key, status) {
402
+ const properties = [];
403
+ if (status.label) {
404
+ properties.push({
405
+ label: "Label",
406
+ text: status.label
407
+ });
328
408
  }
329
- if (response.status !== 200) {
330
- throw new Error(`Failed to register entry point, got status code ${response.status}`);
409
+ if (status.state) {
410
+ properties.push({
411
+ label: "State",
412
+ text: status.state
413
+ });
331
414
  }
332
- return await response.json();
333
- }
334
- async runTask(runId, task, options = {}) {
335
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
336
- __privateGet(this, _logger).debug("Running Task", {
337
- task
338
- });
339
- return await zodfetchWithVersions({
340
- [import_core.API_VERSIONS.LAZY_LOADED_CACHED_TASKS]: import_core.RunTaskResponseWithCachedTasksBodySchema
341
- }, import_core.ServerTaskSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/tasks`, {
342
- method: "POST",
343
- headers: {
344
- "Content-Type": "application/json",
345
- Authorization: `Bearer ${apiKey}`,
346
- "Idempotency-Key": task.idempotencyKey,
347
- "X-Cached-Tasks-Cursor": options.cachedTasksCursor ?? "",
348
- "Trigger-Version": import_core.API_VERSIONS.LAZY_LOADED_CACHED_TASKS
415
+ return await this.io.runTask(key, async (task) => {
416
+ return await this.io.triggerClient.updateStatus(this.io.runId, this.id, status);
417
+ }, {
418
+ name: status.label ?? `Status update`,
419
+ icon: "bell",
420
+ params: {
421
+ ...status
349
422
  },
350
- body: JSON.stringify(task)
423
+ properties
351
424
  });
352
425
  }
353
- async completeTask(runId, id, task) {
354
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
355
- __privateGet(this, _logger).debug("Complete Task", {
356
- task
357
- });
358
- return await zodfetch(import_core.ServerTaskSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/tasks/${id}/complete`, {
359
- method: "POST",
360
- headers: {
361
- "Content-Type": "application/json",
362
- Authorization: `Bearer ${apiKey}`,
363
- "Trigger-Version": import_core.API_VERSIONS.SERIALIZED_TASK_OUTPUT
426
+ };
427
+ __name(TriggerStatus, "TriggerStatus");
428
+
429
+ // src/types.ts
430
+ var import_zod = require("zod");
431
+ var EventSpecificationExampleSchema = import_zod.z.object({
432
+ id: import_zod.z.string(),
433
+ name: import_zod.z.string(),
434
+ icon: import_zod.z.string().optional(),
435
+ payload: import_zod.z.any()
436
+ });
437
+ function waitForEventSchema(schema) {
438
+ return import_zod.z.object({
439
+ id: import_zod.z.string(),
440
+ name: import_zod.z.string(),
441
+ source: import_zod.z.string(),
442
+ payload: schema,
443
+ timestamp: import_zod.z.coerce.date(),
444
+ context: import_zod.z.any().optional(),
445
+ accountId: import_zod.z.string().optional()
446
+ });
447
+ }
448
+ __name(waitForEventSchema, "waitForEventSchema");
449
+
450
+ // src/io.ts
451
+ var import_zod2 = require("zod");
452
+
453
+ // src/store/keyValueStore.ts
454
+ var _namespacedKey, namespacedKey_fn, _sharedProperties, sharedProperties_fn;
455
+ var KeyValueStore = class {
456
+ constructor(apiClient, type = null, namespace = "") {
457
+ __privateAdd(this, _namespacedKey);
458
+ __privateAdd(this, _sharedProperties);
459
+ this.apiClient = apiClient;
460
+ this.type = type;
461
+ this.namespace = namespace;
462
+ }
463
+ async delete(param1, param2) {
464
+ const runStore = runLocalStorage.getStore();
465
+ if (!runStore) {
466
+ if (typeof param1 !== "string") {
467
+ throw new Error("Please use the store without a cacheKey when accessing from outside a run.");
468
+ }
469
+ return await this.apiClient.store.delete(__privateMethod(this, _namespacedKey, namespacedKey_fn).call(this, param1));
470
+ }
471
+ const { io } = runStore;
472
+ if (!param2) {
473
+ throw new Error("Please provide a non-empty key when accessing the store from inside a run.");
474
+ }
475
+ return await io.runTask(param1, async (task) => {
476
+ return await this.apiClient.store.delete(__privateMethod(this, _namespacedKey, namespacedKey_fn).call(this, param2));
477
+ }, {
478
+ name: "Key-Value Store Delete",
479
+ icon: "database-minus",
480
+ params: {
481
+ key: param2
364
482
  },
365
- body: JSON.stringify(task)
483
+ properties: __privateMethod(this, _sharedProperties, sharedProperties_fn).call(this, param2),
484
+ style: {
485
+ style: "minimal"
486
+ }
366
487
  });
367
488
  }
368
- async failTask(runId, id, body) {
369
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
370
- __privateGet(this, _logger).debug("Fail Task", {
371
- id,
372
- runId,
373
- body
374
- });
375
- return await zodfetch(import_core.ServerTaskSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/tasks/${id}/fail`, {
376
- method: "POST",
377
- headers: {
378
- "Content-Type": "application/json",
379
- Authorization: `Bearer ${apiKey}`
489
+ async get(param1, param2) {
490
+ const runStore = runLocalStorage.getStore();
491
+ if (!runStore) {
492
+ if (typeof param1 !== "string") {
493
+ throw new Error("Please use the store without a cacheKey when accessing from outside a run.");
494
+ }
495
+ return await this.apiClient.store.get(__privateMethod(this, _namespacedKey, namespacedKey_fn).call(this, param1));
496
+ }
497
+ const { io } = runStore;
498
+ if (!param2) {
499
+ throw new Error("Please provide a non-empty key when accessing the store from inside a run.");
500
+ }
501
+ return await io.runTask(param1, async (task) => {
502
+ return await this.apiClient.store.get(__privateMethod(this, _namespacedKey, namespacedKey_fn).call(this, param2));
503
+ }, {
504
+ name: "Key-Value Store Get",
505
+ icon: "database-export",
506
+ params: {
507
+ key: param2
380
508
  },
381
- body: JSON.stringify(body)
509
+ properties: __privateMethod(this, _sharedProperties, sharedProperties_fn).call(this, param2),
510
+ style: {
511
+ style: "minimal"
512
+ }
382
513
  });
383
514
  }
384
- async sendEvent(event, options = {}) {
385
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
386
- __privateGet(this, _logger).debug("Sending event", {
387
- event
388
- });
389
- return await zodfetch(import_core.ApiEventLogSchema, `${__privateGet(this, _apiUrl)}/api/v1/events`, {
390
- method: "POST",
391
- headers: {
392
- "Content-Type": "application/json",
393
- Authorization: `Bearer ${apiKey}`
515
+ async has(param1, param2) {
516
+ const runStore = runLocalStorage.getStore();
517
+ if (!runStore) {
518
+ if (typeof param1 !== "string") {
519
+ throw new Error("Please use the store without a cacheKey when accessing from outside a run.");
520
+ }
521
+ return await this.apiClient.store.has(__privateMethod(this, _namespacedKey, namespacedKey_fn).call(this, param1));
522
+ }
523
+ const { io } = runStore;
524
+ if (!param2) {
525
+ throw new Error("Please provide a non-empty key when accessing the store from inside a run.");
526
+ }
527
+ return await io.runTask(param1, async (task) => {
528
+ return await this.apiClient.store.has(__privateMethod(this, _namespacedKey, namespacedKey_fn).call(this, param2));
529
+ }, {
530
+ name: "Key-Value Store Has",
531
+ icon: "database-search",
532
+ params: {
533
+ key: param2
394
534
  },
395
- body: JSON.stringify({
396
- event,
397
- options
398
- })
535
+ properties: __privateMethod(this, _sharedProperties, sharedProperties_fn).call(this, param2),
536
+ style: {
537
+ style: "minimal"
538
+ }
399
539
  });
400
540
  }
401
- async sendEvents(events, options = {}) {
402
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
403
- __privateGet(this, _logger).debug("Sending multiple events", {
404
- events
405
- });
406
- return await zodfetch(import_core.ApiEventLogSchema.array(), `${__privateGet(this, _apiUrl)}/api/v1/events/bulk`, {
407
- method: "POST",
408
- headers: {
409
- "Content-Type": "application/json",
410
- Authorization: `Bearer ${apiKey}`
411
- },
412
- body: JSON.stringify({
413
- events,
414
- options
415
- })
416
- });
417
- }
418
- async cancelEvent(eventId) {
419
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
420
- __privateGet(this, _logger).debug("Cancelling event", {
421
- eventId
422
- });
423
- return await zodfetch(import_core.ApiEventLogSchema, `${__privateGet(this, _apiUrl)}/api/v1/events/${eventId}/cancel`, {
424
- method: "POST",
425
- headers: {
426
- "Content-Type": "application/json",
427
- Authorization: `Bearer ${apiKey}`
541
+ async set(param1, param2, param3) {
542
+ const runStore = runLocalStorage.getStore();
543
+ if (!runStore) {
544
+ if (typeof param1 !== "string") {
545
+ throw new Error("Please use the store without a cacheKey when accessing from outside a run.");
428
546
  }
429
- });
430
- }
431
- async cancelRunsForEvent(eventId) {
432
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
433
- __privateGet(this, _logger).debug("Cancelling runs for event", {
434
- eventId
435
- });
436
- return await zodfetch(import_core.CancelRunsForEventSchema, `${__privateGet(this, _apiUrl)}/api/v1/events/${eventId}/cancel-runs`, {
437
- method: "POST",
438
- headers: {
439
- "Content-Type": "application/json",
440
- Authorization: `Bearer ${apiKey}`
547
+ return await this.apiClient.store.set(__privateMethod(this, _namespacedKey, namespacedKey_fn).call(this, param1), param2);
548
+ }
549
+ const { io } = runStore;
550
+ if (!param2 || typeof param2 !== "string") {
551
+ throw new Error("Please provide a non-empty key when accessing the store from inside a run.");
552
+ }
553
+ const value = param3;
554
+ return await io.runTask(param1, async (task) => {
555
+ return await this.apiClient.store.set(__privateMethod(this, _namespacedKey, namespacedKey_fn).call(this, param2), value);
556
+ }, {
557
+ name: "Key-Value Store Set",
558
+ icon: "database-plus",
559
+ params: {
560
+ key: param2,
561
+ value
562
+ },
563
+ properties: [
564
+ ...__privateMethod(this, _sharedProperties, sharedProperties_fn).call(this, param2),
565
+ ...typeof value !== "object" || value === null ? [
566
+ {
567
+ label: "value",
568
+ text: String(value) ?? "undefined"
569
+ }
570
+ ] : []
571
+ ],
572
+ style: {
573
+ style: "minimal"
441
574
  }
442
575
  });
443
576
  }
444
- async updateStatus(runId, id, status) {
445
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
446
- __privateGet(this, _logger).debug("Update status", {
447
- id,
448
- status
449
- });
450
- return await zodfetch(import_core.JobRunStatusRecordSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/statuses/${id}`, {
451
- method: "PUT",
452
- headers: {
453
- "Content-Type": "application/json",
454
- Authorization: `Bearer ${apiKey}`
455
- },
456
- body: JSON.stringify(status)
457
- });
577
+ };
578
+ __name(KeyValueStore, "KeyValueStore");
579
+ _namespacedKey = new WeakSet();
580
+ namespacedKey_fn = /* @__PURE__ */ __name(function(key) {
581
+ const parts = [];
582
+ if (this.type) {
583
+ parts.push(this.type);
584
+ }
585
+ if (this.namespace) {
586
+ parts.push(this.namespace);
587
+ }
588
+ parts.push(key);
589
+ return parts.join(":");
590
+ }, "#namespacedKey");
591
+ _sharedProperties = new WeakSet();
592
+ sharedProperties_fn = /* @__PURE__ */ __name(function(key1) {
593
+ return [
594
+ {
595
+ label: "namespace",
596
+ text: this.type ?? "env"
597
+ },
598
+ {
599
+ label: "key",
600
+ text: key1
601
+ }
602
+ ];
603
+ }, "#sharedProperties");
604
+
605
+ // src/io.ts
606
+ var JSONOutputSerializer = class {
607
+ serialize(value) {
608
+ return JSON.stringify(value);
458
609
  }
459
- async updateSource(client, key, source) {
460
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
461
- __privateGet(this, _logger).debug("activating http source", {
462
- source
463
- });
464
- const response = await zodfetch(import_core.TriggerSourceSchema, `${__privateGet(this, _apiUrl)}/api/v2/${client}/sources/${key}`, {
465
- method: "PUT",
466
- headers: {
467
- "Content-Type": "application/json",
468
- Authorization: `Bearer ${apiKey}`
469
- },
470
- body: JSON.stringify(source)
471
- });
472
- return response;
610
+ deserialize(value) {
611
+ return value ? JSON.parse(value) : void 0;
473
612
  }
474
- async registerTrigger(client, id, key, payload, idempotencyKey) {
475
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
476
- __privateGet(this, _logger).debug("registering trigger", {
477
- id,
478
- payload
479
- });
480
- const headers = {
481
- "Content-Type": "application/json",
482
- Authorization: `Bearer ${apiKey}`
613
+ };
614
+ __name(JSONOutputSerializer, "JSONOutputSerializer");
615
+ var _addToCachedTasks, addToCachedTasks_fn, _detectAutoYield, detectAutoYield_fn, _forceYield, forceYield_fn, _getTimeElapsed, getTimeElapsed_fn, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn;
616
+ var IO = class {
617
+ constructor(options) {
618
+ __privateAdd(this, _addToCachedTasks);
619
+ __privateAdd(this, _detectAutoYield);
620
+ __privateAdd(this, _forceYield);
621
+ __privateAdd(this, _getTimeElapsed);
622
+ __privateAdd(this, _getRemainingTimeInMillis);
623
+ __publicField(this, "_outputSerializer", new JSONOutputSerializer());
624
+ __publicField(this, "_visitedCacheKeys", /* @__PURE__ */ new Set());
625
+ __publicField(this, "brb", this.yield.bind(this));
626
+ this._id = options.id;
627
+ this._jobId = options.jobId;
628
+ this._apiClient = options.apiClient;
629
+ this._triggerClient = options.client;
630
+ this._logger = options.logger ?? new import_core2.Logger("trigger.dev", options.logLevel);
631
+ this._cachedTasks = /* @__PURE__ */ new Map();
632
+ this._jobLogger = options.jobLogger;
633
+ this._jobLogLevel = options.jobLogLevel;
634
+ this._timeOrigin = options.timeOrigin;
635
+ this._executionTimeout = options.executionTimeout;
636
+ this._envStore = new KeyValueStore(options.apiClient);
637
+ this._jobStore = new KeyValueStore(options.apiClient, "job", options.jobId);
638
+ this._runStore = new KeyValueStore(options.apiClient, "run", options.id);
639
+ this._stats = {
640
+ initialCachedTasks: 0,
641
+ lazyLoadedCachedTasks: 0,
642
+ executedTasks: 0,
643
+ cachedTaskHits: 0,
644
+ cachedTaskMisses: 0,
645
+ noopCachedTaskHits: 0,
646
+ noopCachedTaskMisses: 0
483
647
  };
484
- if (idempotencyKey) {
485
- headers["Idempotency-Key"] = idempotencyKey;
648
+ if (options.cachedTasks) {
649
+ options.cachedTasks.forEach((task) => {
650
+ this._cachedTasks.set(task.idempotencyKey, task);
651
+ });
652
+ this._stats.initialCachedTasks = options.cachedTasks.length;
486
653
  }
487
- const response = await zodfetch(import_core.RegisterSourceEventSchemaV2, `${__privateGet(this, _apiUrl)}/api/v2/${client}/triggers/${id}/registrations/${key}`, {
488
- method: "PUT",
489
- headers,
490
- body: JSON.stringify(payload)
491
- });
492
- return response;
654
+ this._taskStorage = new import_node_async_hooks2.AsyncLocalStorage();
655
+ this._context = options.context;
656
+ this._yieldedExecutions = options.yieldedExecutions ?? [];
657
+ if (options.noopTasksSet) {
658
+ this._noopTasksBloomFilter = import_core_backend.BloomFilter.deserialize(options.noopTasksSet, import_core_backend.BloomFilter.NOOP_TASK_SET_SIZE);
659
+ }
660
+ this._cachedTasksCursor = options.cachedTasksCursor;
661
+ this._serverVersion = options.serverVersion ?? "unversioned";
493
662
  }
494
- async registerSchedule(client, id, key, payload) {
495
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
496
- __privateGet(this, _logger).debug("registering schedule", {
497
- id,
498
- payload
499
- });
500
- const response = await zodfetch(import_core.RegisterScheduleResponseBodySchema, `${__privateGet(this, _apiUrl)}/api/v1/${client}/schedules/${id}/registrations`, {
501
- method: "POST",
502
- headers: {
503
- "Content-Type": "application/json",
504
- Authorization: `Bearer ${apiKey}`
505
- },
506
- body: JSON.stringify({
507
- id: key,
508
- ...payload
509
- })
510
- });
511
- return response;
663
+ get stats() {
664
+ return this._stats;
512
665
  }
513
- async unregisterSchedule(client, id, key) {
514
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
515
- __privateGet(this, _logger).debug("unregistering schedule", {
516
- id
517
- });
518
- const response = await zodfetch(import_zod.z.object({
519
- ok: import_zod.z.boolean()
520
- }), `${__privateGet(this, _apiUrl)}/api/v1/${client}/schedules/${id}/registrations/${encodeURIComponent(key)}`, {
521
- method: "DELETE",
522
- headers: {
523
- "Content-Type": "application/json",
524
- Authorization: `Bearer ${apiKey}`
525
- }
526
- });
527
- return response;
666
+ get runId() {
667
+ return this._id;
528
668
  }
529
- async getAuth(client, id) {
530
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
531
- __privateGet(this, _logger).debug("getting auth", {
532
- id
533
- });
534
- const response = await zodfetch(import_core.ConnectionAuthSchema, `${__privateGet(this, _apiUrl)}/api/v1/${client}/auth/${id}`, {
535
- method: "GET",
536
- headers: {
537
- Accept: "application/json",
538
- Authorization: `Bearer ${apiKey}`
539
- }
540
- }, {
541
- optional: true
542
- });
543
- return response;
669
+ get triggerClient() {
670
+ return this._triggerClient;
544
671
  }
545
- async getEvent(eventId) {
546
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
547
- __privateGet(this, _logger).debug("Getting Event", {
548
- eventId
549
- });
550
- return await zodfetch(import_core.GetEventSchema, `${__privateGet(this, _apiUrl)}/api/v1/events/${eventId}`, {
551
- method: "GET",
552
- headers: {
553
- Authorization: `Bearer ${apiKey}`
672
+ get logger() {
673
+ return new IOLogger(async (level, message, data) => {
674
+ let logLevel = "info";
675
+ if (import_core2.Logger.satisfiesLogLevel(logLevel, this._jobLogLevel)) {
676
+ await this.runTask([
677
+ message,
678
+ level
679
+ ], async (task) => {
680
+ switch (level) {
681
+ case "LOG": {
682
+ this._jobLogger?.log(message, data);
683
+ logLevel = "log";
684
+ break;
685
+ }
686
+ case "DEBUG": {
687
+ this._jobLogger?.debug(message, data);
688
+ logLevel = "debug";
689
+ break;
690
+ }
691
+ case "INFO": {
692
+ this._jobLogger?.info(message, data);
693
+ logLevel = "info";
694
+ break;
695
+ }
696
+ case "WARN": {
697
+ this._jobLogger?.warn(message, data);
698
+ logLevel = "warn";
699
+ break;
700
+ }
701
+ case "ERROR": {
702
+ this._jobLogger?.error(message, data);
703
+ logLevel = "error";
704
+ break;
705
+ }
706
+ }
707
+ }, {
708
+ name: "log",
709
+ icon: "log",
710
+ description: message,
711
+ params: data,
712
+ properties: [
713
+ {
714
+ label: "Level",
715
+ text: level
716
+ }
717
+ ],
718
+ style: {
719
+ style: "minimal",
720
+ variant: level.toLowerCase()
721
+ },
722
+ noop: true
723
+ });
554
724
  }
555
725
  });
556
726
  }
557
- async getRun(runId, options) {
558
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
559
- __privateGet(this, _logger).debug("Getting Run", {
560
- runId
561
- });
562
- return await zodfetch(import_core.GetRunSchema, (0, import_core.urlWithSearchParams)(`${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}`, options), {
563
- method: "GET",
564
- headers: {
565
- Authorization: `Bearer ${apiKey}`
727
+ async random(cacheKey, { min = 0, max = 1, round = false } = {}) {
728
+ return await this.runTask(cacheKey, async (task) => {
729
+ if (min > max) {
730
+ throw new Error(`Lower bound can't be higher than upper bound - min: ${min}, max: ${max}`);
566
731
  }
567
- });
568
- }
569
- async cancelRun(runId) {
570
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
571
- __privateGet(this, _logger).debug("Cancelling Run", {
572
- runId
573
- });
574
- return await zodfetch(import_core.GetRunSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/cancel`, {
575
- method: "POST",
576
- headers: {
577
- "Content-Type": "application/json",
578
- Authorization: `Bearer ${apiKey}`
732
+ if (min === max) {
733
+ await this.logger.warn(`Lower and upper bounds are identical. The return value is not random and will always be: ${min}`);
734
+ }
735
+ const withinBounds = (max - min) * Math.random() + min;
736
+ if (!round) {
737
+ return withinBounds;
738
+ }
739
+ if (!Number.isInteger(min) || !Number.isInteger(max)) {
740
+ await this.logger.warn("Rounding enabled with floating-point bounds. This may cause unexpected skew and boundary inclusivity.");
741
+ }
742
+ const rounded = Math.round(withinBounds);
743
+ return rounded;
744
+ }, {
745
+ name: "random",
746
+ icon: "dice-5-filled",
747
+ params: {
748
+ min,
749
+ max,
750
+ round
751
+ },
752
+ properties: [
753
+ ...min === 0 ? [] : [
754
+ {
755
+ label: "min",
756
+ text: String(min)
757
+ }
758
+ ],
759
+ ...max === 1 ? [] : [
760
+ {
761
+ label: "max",
762
+ text: String(max)
763
+ }
764
+ ],
765
+ ...round === false ? [] : [
766
+ {
767
+ label: "round",
768
+ text: String(round)
769
+ }
770
+ ]
771
+ ],
772
+ style: {
773
+ style: "minimal"
579
774
  }
580
775
  });
581
776
  }
582
- async getRunStatuses(runId) {
583
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
584
- __privateGet(this, _logger).debug("Getting Run statuses", {
585
- runId
586
- });
587
- return await zodfetch(import_core.GetRunStatusesSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/statuses`, {
588
- method: "GET",
589
- headers: {
590
- Authorization: `Bearer ${apiKey}`
777
+ async wait(cacheKey, seconds) {
778
+ return await this.runTask(cacheKey, async (task) => {
779
+ }, {
780
+ name: "wait",
781
+ icon: "clock",
782
+ params: {
783
+ seconds
784
+ },
785
+ noop: true,
786
+ delayUntil: new Date(Date.now() + seconds * 1e3),
787
+ style: {
788
+ style: "minimal"
591
789
  }
592
790
  });
593
791
  }
594
- async getRuns(jobSlug, options) {
595
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
596
- __privateGet(this, _logger).debug("Getting Runs", {
597
- jobSlug
598
- });
599
- return await zodfetch(import_core.GetRunsSchema, (0, import_core.urlWithSearchParams)(`${__privateGet(this, _apiUrl)}/api/v1/jobs/${jobSlug}/runs`, options), {
600
- method: "GET",
601
- headers: {
602
- Authorization: `Bearer ${apiKey}`
792
+ async waitForEvent(cacheKey, event, options) {
793
+ const timeoutInSeconds = options?.timeoutInSeconds ?? 60 * 60;
794
+ return await this.runTask(cacheKey, async (task, io) => {
795
+ if (!task.callbackUrl) {
796
+ throw new Error("No callbackUrl found on task");
797
+ }
798
+ await this.triggerClient.createEphemeralEventDispatcher({
799
+ url: task.callbackUrl,
800
+ name: event.name,
801
+ filter: event.filter,
802
+ contextFilter: event.contextFilter,
803
+ source: event.source,
804
+ accountId: event.accountId,
805
+ timeoutInSeconds
806
+ });
807
+ return {};
808
+ }, {
809
+ name: "Wait for Event",
810
+ icon: "custom-event",
811
+ params: {
812
+ name: event.name,
813
+ source: event.source,
814
+ filter: event.filter,
815
+ contextFilter: event.contextFilter,
816
+ accountId: event.accountId
817
+ },
818
+ callback: {
819
+ enabled: true,
820
+ timeoutInSeconds
821
+ },
822
+ properties: [
823
+ {
824
+ label: "Event",
825
+ text: event.name
826
+ },
827
+ {
828
+ label: "Timeout",
829
+ text: `${timeoutInSeconds}s`
830
+ },
831
+ ...event.source ? [
832
+ {
833
+ label: "Source",
834
+ text: event.source
835
+ }
836
+ ] : [],
837
+ ...event.accountId ? [
838
+ {
839
+ label: "Account ID",
840
+ text: event.accountId
841
+ }
842
+ ] : []
843
+ ],
844
+ parseOutput: (output) => {
845
+ return waitForEventSchema(event.schema ?? import_zod2.z.any()).parse(output);
603
846
  }
604
847
  });
605
848
  }
606
- async invokeJob(jobId, payload, options = {}) {
607
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
608
- __privateGet(this, _logger).debug("Invoking Job", {
609
- jobId
610
- });
611
- const body = {
612
- payload,
613
- context: options.context ?? {},
614
- options: {
615
- accountId: options.accountId,
616
- callbackUrl: options.callbackUrl
849
+ async waitForRequest(cacheKey, callback, options) {
850
+ const timeoutInSeconds = options?.timeoutInSeconds ?? 60 * 60;
851
+ return await this.runTask(cacheKey, async (task, io) => {
852
+ if (!task.callbackUrl) {
853
+ throw new Error("No callbackUrl found on task");
617
854
  }
618
- };
619
- return await zodfetch(import_core.InvokeJobResponseSchema, `${__privateGet(this, _apiUrl)}/api/v1/jobs/${jobId}/invoke`, {
620
- method: "POST",
621
- headers: {
622
- "Content-Type": "application/json",
623
- Authorization: `Bearer ${apiKey}`,
624
- ...options.idempotencyKey ? {
625
- "Idempotency-Key": options.idempotencyKey
626
- } : {}
855
+ task.outputProperties = [
856
+ {
857
+ label: "Callback URL",
858
+ text: task.callbackUrl
859
+ }
860
+ ];
861
+ return callback(task.callbackUrl);
862
+ }, {
863
+ name: "Wait for Request",
864
+ icon: "clock",
865
+ callback: {
866
+ enabled: true,
867
+ timeoutInSeconds: options?.timeoutInSeconds
627
868
  },
628
- body: JSON.stringify(body)
869
+ properties: [
870
+ {
871
+ label: "Timeout",
872
+ text: `${timeoutInSeconds}s`
873
+ }
874
+ ]
629
875
  });
630
876
  }
631
- async createEphemeralEventDispatcher(payload) {
632
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
633
- __privateGet(this, _logger).debug("Creating ephemeral event dispatcher", {
634
- payload
635
- });
636
- const response = await zodfetch(import_core.EphemeralEventDispatcherResponseBodySchema, `${__privateGet(this, _apiUrl)}/api/v1/event-dispatchers/ephemeral`, {
637
- method: "POST",
638
- headers: {
639
- "Content-Type": "application/json",
640
- Authorization: `Bearer ${apiKey}`
877
+ async createStatus(cacheKey, initialStatus) {
878
+ const id = typeof cacheKey === "string" ? cacheKey : cacheKey.join("-");
879
+ const status = new TriggerStatus(id, this);
880
+ await status.update(cacheKey, initialStatus);
881
+ return status;
882
+ }
883
+ async backgroundFetch(cacheKey, url, requestInit, options) {
884
+ const urlObject = new URL(url);
885
+ return await this.runTask(cacheKey, async (task) => {
886
+ console.log("task context", task.context);
887
+ return task.output;
888
+ }, {
889
+ name: `fetch ${urlObject.hostname}${urlObject.pathname}`,
890
+ params: {
891
+ url,
892
+ requestInit,
893
+ retry: options?.retry,
894
+ timeout: options?.timeout
641
895
  },
642
- body: JSON.stringify(payload)
896
+ operation: "fetch",
897
+ icon: "background",
898
+ noop: false,
899
+ properties: [
900
+ {
901
+ label: "url",
902
+ text: url,
903
+ url
904
+ },
905
+ {
906
+ label: "method",
907
+ text: requestInit?.method ?? "GET"
908
+ },
909
+ {
910
+ label: "background",
911
+ text: "true"
912
+ },
913
+ ...options?.timeout ? [
914
+ {
915
+ label: "timeout",
916
+ text: `${options.timeout.durationInMs}ms`
917
+ }
918
+ ] : []
919
+ ],
920
+ retry: {
921
+ limit: 0
922
+ }
643
923
  });
644
- return response;
645
924
  }
646
- };
647
- __name(ApiClient, "ApiClient");
648
- _apiUrl = new WeakMap();
649
- _options = new WeakMap();
650
- _logger = new WeakMap();
651
- _apiKey = new WeakSet();
652
- apiKey_fn = /* @__PURE__ */ __name(async function() {
653
- const apiKey = getApiKey(__privateGet(this, _options).apiKey);
654
- if (apiKey.status === "invalid") {
655
- throw new Error("Invalid API key");
656
- } else if (apiKey.status === "missing") {
657
- throw new Error("Missing API key");
658
- }
659
- return apiKey.apiKey;
660
- }, "#apiKey");
661
- function getApiKey(key) {
662
- const apiKey = key ?? process.env.TRIGGER_API_KEY;
663
- if (!apiKey) {
664
- return {
665
- status: "missing"
666
- };
667
- }
668
- const isValid = apiKey.match(/^tr_[a-z]+_[a-zA-Z0-9]+$/);
669
- if (!isValid) {
670
- return {
671
- status: "invalid",
672
- apiKey
673
- };
674
- }
675
- return {
676
- status: "valid",
677
- apiKey
678
- };
679
- }
680
- __name(getApiKey, "getApiKey");
681
- async function zodfetchWithVersions(versionedSchemaMap, unversionedSchema, url, requestInit, options, retryCount = 0) {
682
- const response = await fetch(url, {
683
- ...requestInit,
684
- cache: "no-cache"
685
- });
686
- if ((!requestInit || requestInit.method === "GET") && response.status === 404 && options?.optional) {
687
- return;
925
+ async backgroundPoll(cacheKey, params) {
926
+ const urlObject = new URL(params.url);
927
+ return await this.runTask(cacheKey, async (task) => {
928
+ return task.output;
929
+ }, {
930
+ name: `poll ${urlObject.hostname}${urlObject.pathname}`,
931
+ params,
932
+ operation: "fetch-poll",
933
+ icon: "clock-bolt",
934
+ noop: false,
935
+ properties: [
936
+ {
937
+ label: "url",
938
+ text: params.url
939
+ },
940
+ {
941
+ label: "interval",
942
+ text: `${params.interval}s`
943
+ },
944
+ {
945
+ label: "timeout",
946
+ text: `${params.timeout}s`
947
+ }
948
+ ],
949
+ retry: {
950
+ limit: 0
951
+ }
952
+ });
688
953
  }
689
- if (response.status >= 400 && response.status < 500) {
690
- const body = await response.json();
691
- throw new Error(body.error);
954
+ async backgroundFetchResponse(cacheKey, url, requestInit, options) {
955
+ const urlObject = new URL(url);
956
+ return await this.runTask(cacheKey, async (task) => {
957
+ return task.output;
958
+ }, {
959
+ name: `fetch response ${urlObject.hostname}${urlObject.pathname}`,
960
+ params: {
961
+ url,
962
+ requestInit,
963
+ retry: options?.retry,
964
+ timeout: options?.timeout
965
+ },
966
+ operation: "fetch-response",
967
+ icon: "background",
968
+ noop: false,
969
+ properties: [
970
+ {
971
+ label: "url",
972
+ text: url,
973
+ url
974
+ },
975
+ {
976
+ label: "method",
977
+ text: requestInit?.method ?? "GET"
978
+ },
979
+ {
980
+ label: "background",
981
+ text: "true"
982
+ },
983
+ ...options?.timeout ? [
984
+ {
985
+ label: "timeout",
986
+ text: `${options.timeout.durationInMs}ms`
987
+ }
988
+ ] : []
989
+ ],
990
+ retry: {
991
+ limit: 0
992
+ }
993
+ });
692
994
  }
693
- if (response.status >= 500 && retryCount < 6) {
694
- const delay = exponentialBackoff(retryCount + 1, 2, 50, 1150, 50);
695
- await new Promise((resolve) => setTimeout(resolve, delay));
696
- return zodfetchWithVersions(versionedSchemaMap, unversionedSchema, url, requestInit, options, retryCount + 1);
995
+ async sendEvent(cacheKey, event, options) {
996
+ return await this.runTask(cacheKey, async (task) => {
997
+ return await this._triggerClient.sendEvent(event, options);
998
+ }, {
999
+ name: "Send Event",
1000
+ params: {
1001
+ event,
1002
+ options
1003
+ },
1004
+ icon: "send",
1005
+ properties: [
1006
+ {
1007
+ label: "name",
1008
+ text: event.name
1009
+ },
1010
+ ...event?.id ? [
1011
+ {
1012
+ label: "ID",
1013
+ text: event.id
1014
+ }
1015
+ ] : [],
1016
+ ...sendEventOptionsProperties(options)
1017
+ ]
1018
+ });
697
1019
  }
698
- if (response.status !== 200) {
699
- throw new Error(options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`);
1020
+ async sendEvents(cacheKey, events, options) {
1021
+ return await this.runTask(cacheKey, async (task) => {
1022
+ return await this._triggerClient.sendEvents(events, options);
1023
+ }, {
1024
+ name: "Send Multiple Events",
1025
+ params: {
1026
+ events,
1027
+ options
1028
+ },
1029
+ icon: "send",
1030
+ properties: [
1031
+ {
1032
+ label: "Total Events",
1033
+ text: String(events.length)
1034
+ },
1035
+ ...sendEventOptionsProperties(options)
1036
+ ]
1037
+ });
700
1038
  }
701
- const jsonBody = await response.json();
702
- const version2 = response.headers.get("trigger-version");
703
- if (!version2) {
704
- return {
705
- version: "unversioned",
706
- body: unversionedSchema.parse(jsonBody)
707
- };
1039
+ async getEvent(cacheKey, id) {
1040
+ return await this.runTask(cacheKey, async (task) => {
1041
+ return await this._triggerClient.getEvent(id);
1042
+ }, {
1043
+ name: "getEvent",
1044
+ params: {
1045
+ id
1046
+ },
1047
+ properties: [
1048
+ {
1049
+ label: "id",
1050
+ text: id
1051
+ }
1052
+ ]
1053
+ });
708
1054
  }
709
- const versionedSchema = versionedSchemaMap[version2];
710
- if (!versionedSchema) {
711
- throw new Error(`Unknown version ${version2}`);
1055
+ async cancelEvent(cacheKey, eventId) {
1056
+ return await this.runTask(cacheKey, async (task) => {
1057
+ return await this._triggerClient.cancelEvent(eventId);
1058
+ }, {
1059
+ name: "cancelEvent",
1060
+ params: {
1061
+ eventId
1062
+ },
1063
+ properties: [
1064
+ {
1065
+ label: "id",
1066
+ text: eventId
1067
+ }
1068
+ ]
1069
+ });
712
1070
  }
713
- return {
714
- version: version2,
715
- body: versionedSchema.parse(jsonBody)
716
- };
717
- }
718
- __name(zodfetchWithVersions, "zodfetchWithVersions");
719
- async function zodfetch(schema, url, requestInit, options, retryCount = 0) {
720
- const response = await fetch(url, {
721
- ...requestInit,
722
- cache: "no-cache"
723
- });
724
- if ((!requestInit || requestInit.method === "GET") && response.status === 404 && options?.optional) {
725
- return;
1071
+ async updateSource(cacheKey, options) {
1072
+ return this.runTask(cacheKey, async (task) => {
1073
+ return await this._apiClient.updateSource(this._triggerClient.id, options.key, options);
1074
+ }, {
1075
+ name: "Update Source",
1076
+ description: "Update Source",
1077
+ properties: [
1078
+ {
1079
+ label: "key",
1080
+ text: options.key
1081
+ }
1082
+ ],
1083
+ params: options,
1084
+ redact: {
1085
+ paths: [
1086
+ "secret"
1087
+ ]
1088
+ }
1089
+ });
726
1090
  }
727
- if (response.status >= 400 && response.status < 500) {
728
- const body = await response.json();
729
- throw new Error(body.error);
1091
+ async updateWebhook(cacheKey, options) {
1092
+ return this.runTask(cacheKey, async (task) => {
1093
+ return await this._apiClient.updateWebhook(options.key, options);
1094
+ }, {
1095
+ name: "Update Webhook Source",
1096
+ icon: "refresh",
1097
+ properties: [
1098
+ {
1099
+ label: "key",
1100
+ text: options.key
1101
+ }
1102
+ ],
1103
+ params: options
1104
+ });
730
1105
  }
731
- if (response.status >= 500 && retryCount < 6) {
732
- const delay = exponentialBackoff(retryCount + 1, 2, 50, 1150, 50);
733
- await new Promise((resolve) => setTimeout(resolve, delay));
734
- return zodfetch(schema, url, requestInit, options, retryCount + 1);
1106
+ async registerInterval(cacheKey, dynamicSchedule, id, options) {
1107
+ return await this.runTask(cacheKey, async (task) => {
1108
+ return dynamicSchedule.register(id, {
1109
+ type: "interval",
1110
+ options
1111
+ });
1112
+ }, {
1113
+ name: "register-interval",
1114
+ properties: [
1115
+ {
1116
+ label: "schedule",
1117
+ text: dynamicSchedule.id
1118
+ },
1119
+ {
1120
+ label: "id",
1121
+ text: id
1122
+ },
1123
+ {
1124
+ label: "seconds",
1125
+ text: options.seconds.toString()
1126
+ }
1127
+ ],
1128
+ params: options
1129
+ });
735
1130
  }
736
- if (response.status !== 200) {
737
- throw new Error(options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`);
738
- }
739
- const jsonBody = await response.json();
740
- return schema.parse(jsonBody);
741
- }
742
- __name(zodfetch, "zodfetch");
743
- function exponentialBackoff(retryCount, exponential, minDelay, maxDelay, jitter) {
744
- const delay = Math.min(Math.pow(exponential, retryCount) * minDelay, maxDelay);
745
- const jitterValue = Math.random() * jitter;
746
- return delay + jitterValue;
747
- }
748
- __name(exponentialBackoff, "exponentialBackoff");
749
-
750
- // src/errors.ts
751
- var ResumeWithTaskError = class {
752
- constructor(task) {
753
- this.task = task;
754
- }
755
- };
756
- __name(ResumeWithTaskError, "ResumeWithTaskError");
757
- var ResumeWithParallelTaskError = class {
758
- constructor(task, childErrors) {
759
- this.task = task;
760
- this.childErrors = childErrors;
761
- }
762
- };
763
- __name(ResumeWithParallelTaskError, "ResumeWithParallelTaskError");
764
- var RetryWithTaskError = class {
765
- constructor(cause, task, retryAt) {
766
- this.cause = cause;
767
- this.task = task;
768
- this.retryAt = retryAt;
769
- }
770
- };
771
- __name(RetryWithTaskError, "RetryWithTaskError");
772
- var CanceledWithTaskError = class {
773
- constructor(task) {
774
- this.task = task;
775
- }
776
- };
777
- __name(CanceledWithTaskError, "CanceledWithTaskError");
778
- var YieldExecutionError = class {
779
- constructor(key) {
780
- this.key = key;
781
- }
782
- };
783
- __name(YieldExecutionError, "YieldExecutionError");
784
- var AutoYieldExecutionError = class {
785
- constructor(location, timeRemaining, timeElapsed) {
786
- this.location = location;
787
- this.timeRemaining = timeRemaining;
788
- this.timeElapsed = timeElapsed;
789
- }
790
- };
791
- __name(AutoYieldExecutionError, "AutoYieldExecutionError");
792
- var AutoYieldWithCompletedTaskExecutionError = class {
793
- constructor(id, properties, data, output) {
794
- this.id = id;
795
- this.properties = properties;
796
- this.data = data;
797
- this.output = output;
798
- }
799
- };
800
- __name(AutoYieldWithCompletedTaskExecutionError, "AutoYieldWithCompletedTaskExecutionError");
801
- var ParsedPayloadSchemaError = class {
802
- constructor(schemaErrors) {
803
- this.schemaErrors = schemaErrors;
804
- }
805
- };
806
- __name(ParsedPayloadSchemaError, "ParsedPayloadSchemaError");
807
- function isTriggerError(err) {
808
- return err instanceof ResumeWithTaskError || err instanceof RetryWithTaskError || err instanceof CanceledWithTaskError || err instanceof YieldExecutionError || err instanceof AutoYieldExecutionError || err instanceof AutoYieldWithCompletedTaskExecutionError || err instanceof ResumeWithParallelTaskError;
809
- }
810
- __name(isTriggerError, "isTriggerError");
811
- var ErrorWithTask = class extends Error {
812
- constructor(cause, message) {
813
- super(message);
814
- this.cause = cause;
1131
+ async unregisterInterval(cacheKey, dynamicSchedule, id) {
1132
+ return await this.runTask(cacheKey, async (task) => {
1133
+ return dynamicSchedule.unregister(id);
1134
+ }, {
1135
+ name: "unregister-interval",
1136
+ properties: [
1137
+ {
1138
+ label: "schedule",
1139
+ text: dynamicSchedule.id
1140
+ },
1141
+ {
1142
+ label: "id",
1143
+ text: id
1144
+ }
1145
+ ]
1146
+ });
815
1147
  }
816
- };
817
- __name(ErrorWithTask, "ErrorWithTask");
818
-
819
- // src/httpEndpoint.ts
820
- var import_core2 = require("@trigger.dev/core");
821
-
822
- // src/utils/formatSchemaErrors.ts
823
- function formatSchemaErrors(errors) {
824
- return errors.map((error) => {
825
- const { path, message } = error;
826
- return {
827
- path: path.map(String),
828
- message
829
- };
830
- });
831
- }
832
- __name(formatSchemaErrors, "formatSchemaErrors");
833
-
834
- // src/httpEndpoint.ts
835
- var HttpEndpoint = class {
836
- constructor(options) {
837
- this.options = options;
1148
+ async registerCron(cacheKey, dynamicSchedule, id, options) {
1149
+ return await this.runTask(cacheKey, async (task) => {
1150
+ return dynamicSchedule.register(id, {
1151
+ type: "cron",
1152
+ options
1153
+ });
1154
+ }, {
1155
+ name: "register-cron",
1156
+ properties: [
1157
+ {
1158
+ label: "schedule",
1159
+ text: dynamicSchedule.id
1160
+ },
1161
+ {
1162
+ label: "id",
1163
+ text: id
1164
+ },
1165
+ {
1166
+ label: "cron",
1167
+ text: options.cron
1168
+ }
1169
+ ],
1170
+ params: options
1171
+ });
838
1172
  }
839
- get id() {
840
- return this.options.id;
1173
+ async unregisterCron(cacheKey, dynamicSchedule, id) {
1174
+ return await this.runTask(cacheKey, async (task) => {
1175
+ return dynamicSchedule.unregister(id);
1176
+ }, {
1177
+ name: "unregister-cron",
1178
+ properties: [
1179
+ {
1180
+ label: "schedule",
1181
+ text: dynamicSchedule.id
1182
+ },
1183
+ {
1184
+ label: "id",
1185
+ text: id
1186
+ }
1187
+ ]
1188
+ });
841
1189
  }
842
- onRequest(options) {
843
- return new HttpTrigger({
844
- endpointId: this.id,
845
- event: this.options.event,
846
- filter: options?.filter,
847
- verify: this.options.verify
1190
+ async registerTrigger(cacheKey, trigger, id, params) {
1191
+ return await this.runTask(cacheKey, async (task) => {
1192
+ const registration = await this.runTask("register-source", async (subtask1) => {
1193
+ return trigger.register(id, params);
1194
+ }, {
1195
+ name: "register-source"
1196
+ });
1197
+ return {
1198
+ id: registration.id,
1199
+ key: registration.source.key
1200
+ };
1201
+ }, {
1202
+ name: "register-trigger",
1203
+ properties: [
1204
+ {
1205
+ label: "trigger",
1206
+ text: trigger.id
1207
+ },
1208
+ {
1209
+ label: "id",
1210
+ text: id
1211
+ }
1212
+ ],
1213
+ params
848
1214
  });
849
1215
  }
850
- async handleRequest(request) {
851
- if (!this.options.respondWith)
1216
+ async getAuth(cacheKey, clientId) {
1217
+ if (!clientId) {
852
1218
  return;
853
- return this.options.respondWith.handler(request, () => {
854
- const clonedRequest = request.clone();
855
- return this.options.verify(clonedRequest);
1219
+ }
1220
+ return this.runTask(cacheKey, async (task) => {
1221
+ return await this._triggerClient.getAuth(clientId);
1222
+ }, {
1223
+ name: "get-auth"
856
1224
  });
857
1225
  }
858
- toJSON() {
859
- return {
860
- id: this.id,
861
- icon: this.options.event.icon,
862
- version: "1",
863
- enabled: this.options.enabled ?? true,
864
- event: this.options.event,
865
- immediateResponseFilter: this.options.respondWith?.filter,
866
- skipTriggeringRuns: this.options.respondWith?.skipTriggeringRuns,
867
- source: this.options.event.source
868
- };
869
- }
870
- };
871
- __name(HttpEndpoint, "HttpEndpoint");
872
- var HttpTrigger = /* @__PURE__ */ __name(class HttpTrigger2 {
873
- constructor(options) {
874
- this.options = options;
875
- }
876
- toJSON() {
877
- return {
878
- type: "static",
879
- title: this.options.endpointId,
880
- properties: this.options.event.properties,
881
- rule: {
882
- event: `httpendpoint.${this.options.endpointId}`,
883
- payload: this.options.filter ?? {},
884
- source: this.options.event.source
885
- },
886
- link: `http-endpoints/${this.options.endpointId}`,
887
- help: {
888
- noRuns: {
889
- text: "To start triggering runs click here to setup your HTTP Endpoint with the external API service you want to receive webhooks from.",
890
- link: `http-endpoints/${this.options.endpointId}`
891
- }
1226
+ async parallel(cacheKey, items, callback, options) {
1227
+ const results = await this.runTask(cacheKey, async (task) => {
1228
+ const outcomes = await Promise.allSettled(items.map((item, index) => spaceOut(() => callback(item, index), index, 15)));
1229
+ if (outcomes.every((outcome) => outcome.status === "fulfilled")) {
1230
+ return outcomes.map((outcome) => outcome.value);
892
1231
  }
893
- };
894
- }
895
- get event() {
896
- return this.options.event;
897
- }
898
- attachToJob(triggerClient, job) {
1232
+ const nonInternalErrors = outcomes.filter((outcome) => outcome.status === "rejected" && !isTriggerError(outcome.reason)).map((outcome) => outcome);
1233
+ if (nonInternalErrors.length > 0) {
1234
+ throw nonInternalErrors[0].reason;
1235
+ }
1236
+ const internalErrors = outcomes.filter((outcome) => outcome.status === "rejected" && isTriggerError(outcome.reason)).map((outcome) => outcome).map((outcome) => outcome.reason);
1237
+ throw new ResumeWithParallelTaskError(task, internalErrors);
1238
+ }, {
1239
+ name: "parallel",
1240
+ parallel: true,
1241
+ ...options ?? {}
1242
+ });
1243
+ return results;
899
1244
  }
900
- get preprocessRuns() {
901
- return false;
902
- }
903
- async verifyPayload(payload) {
904
- const clonedRequest = payload.clone();
905
- return this.options.verify(clonedRequest);
906
- }
907
- }, "HttpTrigger");
908
- function httpEndpoint(options) {
909
- const id = slugifyId(options.id);
910
- return new HttpEndpoint({
911
- id,
912
- enabled: options.enabled,
913
- respondWith: options.respondWith,
914
- verify: options.verify,
915
- event: {
916
- name: id,
917
- title: options.title ?? "HTTP Trigger",
918
- source: options.source,
919
- icon: options.icon ?? "webhook",
920
- properties: options.properties,
921
- examples: options.examples ? options.examples : [
922
- {
923
- id: "basic-request",
924
- name: "Basic Request",
925
- icon: "http-post",
926
- payload: {
927
- url: "https://cloud.trigger.dev",
928
- method: "POST",
929
- headers: {
930
- "Content-Type": "application/json"
931
- },
932
- rawBody: JSON.stringify({
933
- foo: "bar"
934
- })
935
- }
936
- }
937
- ],
938
- parsePayload: (rawPayload) => {
939
- const result = import_core2.RequestWithRawBodySchema.safeParse(rawPayload);
940
- if (!result.success) {
941
- throw new ParsedPayloadSchemaError(formatSchemaErrors(result.error.issues));
942
- }
943
- return new Request(new URL(result.data.url), {
944
- method: result.data.method,
945
- headers: result.data.headers,
946
- body: result.data.rawBody
947
- });
1245
+ async runTask(cacheKey, callback, options, onError) {
1246
+ __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "start_task", 500);
1247
+ const parentId = this._taskStorage.getStore()?.taskId;
1248
+ if (parentId) {
1249
+ this._logger.debug("Using parent task", {
1250
+ parentId,
1251
+ cacheKey,
1252
+ options
1253
+ });
1254
+ }
1255
+ const idempotencyKey = await generateIdempotencyKey([
1256
+ this._id,
1257
+ parentId ?? "",
1258
+ cacheKey
1259
+ ].flat());
1260
+ if (this._visitedCacheKeys.has(idempotencyKey)) {
1261
+ if (typeof cacheKey === "string") {
1262
+ throw new Error(`Task with cacheKey "${cacheKey}" has already been executed in this run. Each task must have a unique cacheKey.`);
1263
+ } else {
1264
+ throw new Error(`Task with cacheKey "${cacheKey.join("-")}" has already been executed in this run. Each task must have a unique cacheKey.`);
948
1265
  }
949
1266
  }
950
- });
951
- }
952
- __name(httpEndpoint, "httpEndpoint");
953
-
954
- // src/io.ts
955
- var import_core4 = require("@trigger.dev/core");
956
- var import_core_backend = require("@trigger.dev/core-backend");
957
- var import_node_async_hooks2 = require("async_hooks");
958
- var import_node_crypto = require("crypto");
959
-
960
- // src/retry.ts
961
- var import_core3 = require("@trigger.dev/core");
962
- var retry = {
963
- standardBackoff: {
964
- limit: 8,
965
- factor: 1.8,
966
- minTimeoutInMs: 500,
967
- maxTimeoutInMs: 3e4,
968
- randomize: true
969
- },
970
- exponentialBackoff: {
971
- limit: 8,
972
- factor: 2,
973
- minTimeoutInMs: 1e3,
974
- maxTimeoutInMs: 3e4,
975
- randomize: true
976
- }
977
- };
978
-
979
- // src/status.ts
980
- var TriggerStatus = class {
981
- constructor(id, io) {
982
- this.id = id;
983
- this.io = io;
984
- }
985
- async update(key, status) {
986
- const properties = [];
987
- if (status.label) {
988
- properties.push({
989
- label: "Label",
990
- text: status.label
1267
+ this._visitedCacheKeys.add(idempotencyKey);
1268
+ const cachedTask = this._cachedTasks.get(idempotencyKey);
1269
+ if (cachedTask && cachedTask.status === "COMPLETED") {
1270
+ this._logger.debug("Using completed cached task", {
1271
+ idempotencyKey
991
1272
  });
1273
+ this._stats.cachedTaskHits++;
1274
+ return options?.parseOutput ? options.parseOutput(cachedTask.output) : cachedTask.output;
992
1275
  }
993
- if (status.state) {
994
- properties.push({
995
- label: "State",
996
- text: status.state
997
- });
1276
+ if (options?.noop && this._noopTasksBloomFilter) {
1277
+ if (this._noopTasksBloomFilter.test(idempotencyKey)) {
1278
+ this._logger.debug("task idempotency key exists in noopTasksBloomFilter", {
1279
+ idempotencyKey
1280
+ });
1281
+ this._stats.noopCachedTaskHits++;
1282
+ return {};
1283
+ }
998
1284
  }
999
- return await this.io.runTask(key, async (task) => {
1000
- return await this.io.triggerClient.updateStatus(this.io.runId, this.id, status);
1285
+ const runOptions = {
1286
+ ...options ?? {},
1287
+ parseOutput: void 0
1288
+ };
1289
+ const response = await this._apiClient.runTask(this._id, {
1290
+ idempotencyKey,
1291
+ displayKey: typeof cacheKey === "string" ? cacheKey : void 0,
1292
+ noop: false,
1293
+ ...runOptions ?? {},
1294
+ parentId
1001
1295
  }, {
1002
- name: status.label ?? `Status update`,
1003
- icon: "bell",
1004
- params: {
1005
- ...status
1006
- },
1007
- properties
1296
+ cachedTasksCursor: this._cachedTasksCursor
1008
1297
  });
1009
- }
1010
- };
1011
- __name(TriggerStatus, "TriggerStatus");
1012
-
1013
- // src/types.ts
1014
- var import_zod2 = require("zod");
1015
- var EventSpecificationExampleSchema = import_zod2.z.object({
1016
- id: import_zod2.z.string(),
1017
- name: import_zod2.z.string(),
1018
- icon: import_zod2.z.string().optional(),
1019
- payload: import_zod2.z.any()
1020
- });
1021
- function waitForEventSchema(schema) {
1022
- return import_zod2.z.object({
1023
- id: import_zod2.z.string(),
1024
- name: import_zod2.z.string(),
1025
- source: import_zod2.z.string(),
1026
- payload: schema,
1027
- timestamp: import_zod2.z.coerce.date(),
1028
- context: import_zod2.z.any().optional(),
1029
- accountId: import_zod2.z.string().optional()
1030
- });
1031
- }
1032
- __name(waitForEventSchema, "waitForEventSchema");
1033
-
1034
- // src/io.ts
1035
- var import_zod3 = require("zod");
1036
- var JSONOutputSerializer = class {
1037
- serialize(value) {
1038
- return JSON.stringify(value);
1039
- }
1040
- deserialize(value) {
1041
- return value ? JSON.parse(value) : void 0;
1042
- }
1043
- };
1044
- __name(JSONOutputSerializer, "JSONOutputSerializer");
1045
- var _addToCachedTasks, addToCachedTasks_fn, _detectAutoYield, detectAutoYield_fn, _forceYield, forceYield_fn, _getTimeElapsed, getTimeElapsed_fn, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn;
1046
- var IO = class {
1047
- constructor(options) {
1048
- __privateAdd(this, _addToCachedTasks);
1049
- __privateAdd(this, _detectAutoYield);
1050
- __privateAdd(this, _forceYield);
1051
- __privateAdd(this, _getTimeElapsed);
1052
- __privateAdd(this, _getRemainingTimeInMillis);
1053
- __publicField(this, "_outputSerializer", new JSONOutputSerializer());
1054
- __publicField(this, "_visitedCacheKeys", /* @__PURE__ */ new Set());
1055
- __publicField(this, "brb", this.yield.bind(this));
1056
- this._id = options.id;
1057
- this._apiClient = options.apiClient;
1058
- this._triggerClient = options.client;
1059
- this._logger = options.logger ?? new import_core4.Logger("trigger.dev", options.logLevel);
1060
- this._cachedTasks = /* @__PURE__ */ new Map();
1061
- this._jobLogger = options.jobLogger;
1062
- this._jobLogLevel = options.jobLogLevel;
1063
- this._timeOrigin = options.timeOrigin;
1064
- this._executionTimeout = options.executionTimeout;
1065
- this._stats = {
1066
- initialCachedTasks: 0,
1067
- lazyLoadedCachedTasks: 0,
1068
- executedTasks: 0,
1069
- cachedTaskHits: 0,
1070
- cachedTaskMisses: 0,
1071
- noopCachedTaskHits: 0,
1072
- noopCachedTaskMisses: 0
1073
- };
1074
- if (options.cachedTasks) {
1075
- options.cachedTasks.forEach((task) => {
1076
- this._cachedTasks.set(task.idempotencyKey, task);
1298
+ const task = response.version === import_core2.API_VERSIONS.LAZY_LOADED_CACHED_TASKS ? response.body.task : response.body;
1299
+ if (task.forceYield) {
1300
+ this._logger.debug("Forcing yield after run task", {
1301
+ idempotencyKey
1077
1302
  });
1078
- this._stats.initialCachedTasks = options.cachedTasks.length;
1303
+ __privateMethod(this, _forceYield, forceYield_fn).call(this, "after_run_task");
1079
1304
  }
1080
- this._taskStorage = new import_node_async_hooks2.AsyncLocalStorage();
1081
- this._context = options.context;
1082
- this._yieldedExecutions = options.yieldedExecutions ?? [];
1083
- if (options.noopTasksSet) {
1084
- this._noopTasksBloomFilter = import_core_backend.BloomFilter.deserialize(options.noopTasksSet, import_core_backend.BloomFilter.NOOP_TASK_SET_SIZE);
1305
+ if (response.version === import_core2.API_VERSIONS.LAZY_LOADED_CACHED_TASKS) {
1306
+ this._cachedTasksCursor = response.body.cachedTasks?.cursor;
1307
+ for (const cachedTask2 of response.body.cachedTasks?.tasks ?? []) {
1308
+ if (!this._cachedTasks.has(cachedTask2.idempotencyKey)) {
1309
+ this._cachedTasks.set(cachedTask2.idempotencyKey, cachedTask2);
1310
+ this._logger.debug("Injecting lazy loaded task into task cache", {
1311
+ idempotencyKey: cachedTask2.idempotencyKey
1312
+ });
1313
+ this._stats.lazyLoadedCachedTasks++;
1314
+ }
1315
+ }
1085
1316
  }
1086
- this._cachedTasksCursor = options.cachedTasksCursor;
1087
- this._serverVersion = options.serverVersion ?? "unversioned";
1088
- }
1089
- get stats() {
1090
- return this._stats;
1091
- }
1092
- get runId() {
1093
- return this._id;
1094
- }
1095
- get triggerClient() {
1096
- return this._triggerClient;
1097
- }
1098
- get logger() {
1099
- return new IOLogger(async (level, message, data) => {
1100
- let logLevel = "info";
1101
- if (import_core4.Logger.satisfiesLogLevel(logLevel, this._jobLogLevel)) {
1102
- await this.runTask([
1103
- message,
1104
- level
1105
- ], async (task) => {
1106
- switch (level) {
1107
- case "LOG": {
1108
- this._jobLogger?.log(message, data);
1109
- logLevel = "log";
1110
- break;
1111
- }
1112
- case "DEBUG": {
1113
- this._jobLogger?.debug(message, data);
1114
- logLevel = "debug";
1115
- break;
1116
- }
1117
- case "INFO": {
1118
- this._jobLogger?.info(message, data);
1119
- logLevel = "info";
1120
- break;
1121
- }
1122
- case "WARN": {
1123
- this._jobLogger?.warn(message, data);
1124
- logLevel = "warn";
1125
- break;
1317
+ if (task.status === "CANCELED") {
1318
+ this._logger.debug("Task canceled", {
1319
+ idempotencyKey,
1320
+ task
1321
+ });
1322
+ throw new CanceledWithTaskError(task);
1323
+ }
1324
+ if (task.status === "COMPLETED") {
1325
+ if (task.noop) {
1326
+ this._logger.debug("Noop Task completed", {
1327
+ idempotencyKey
1328
+ });
1329
+ this._noopTasksBloomFilter?.add(task.idempotencyKey);
1330
+ } else {
1331
+ this._logger.debug("Cache miss", {
1332
+ idempotencyKey
1333
+ });
1334
+ this._stats.cachedTaskMisses++;
1335
+ __privateMethod(this, _addToCachedTasks, addToCachedTasks_fn).call(this, task);
1336
+ }
1337
+ return options?.parseOutput ? options.parseOutput(task.output) : task.output;
1338
+ }
1339
+ if (task.status === "ERRORED") {
1340
+ this._logger.debug("Task errored", {
1341
+ idempotencyKey,
1342
+ task
1343
+ });
1344
+ throw new ErrorWithTask(task, task.error ?? task?.output ? JSON.stringify(task.output) : "Task errored");
1345
+ }
1346
+ __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "before_execute_task", 1500);
1347
+ const executeTask = /* @__PURE__ */ __name(async () => {
1348
+ try {
1349
+ const result = await callback(task, this);
1350
+ if (task.status === "WAITING" && task.callbackUrl) {
1351
+ this._logger.debug("Waiting for remote callback", {
1352
+ idempotencyKey,
1353
+ task
1354
+ });
1355
+ return {};
1356
+ }
1357
+ const output = this._outputSerializer.serialize(result);
1358
+ this._logger.debug("Completing using output", {
1359
+ idempotencyKey,
1360
+ task
1361
+ });
1362
+ __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "before_complete_task", 500, task, output);
1363
+ const completedTask = await this._apiClient.completeTask(this._id, task.id, {
1364
+ output,
1365
+ properties: task.outputProperties ?? void 0
1366
+ });
1367
+ if (completedTask.forceYield) {
1368
+ this._logger.debug("Forcing yield after task completed", {
1369
+ idempotencyKey
1370
+ });
1371
+ __privateMethod(this, _forceYield, forceYield_fn).call(this, "after_complete_task");
1372
+ }
1373
+ this._stats.executedTasks++;
1374
+ if (completedTask.status === "CANCELED") {
1375
+ throw new CanceledWithTaskError(completedTask);
1376
+ }
1377
+ __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "after_complete_task", 500);
1378
+ const deserializedOutput = this._outputSerializer.deserialize(output);
1379
+ return options?.parseOutput ? options.parseOutput(deserializedOutput) : deserializedOutput;
1380
+ } catch (error) {
1381
+ if (isTriggerError(error)) {
1382
+ throw error;
1383
+ }
1384
+ let skipRetrying = false;
1385
+ if (onError) {
1386
+ try {
1387
+ const onErrorResult = onError(error, task, this);
1388
+ if (onErrorResult) {
1389
+ if (onErrorResult instanceof Error) {
1390
+ error = onErrorResult;
1391
+ } else {
1392
+ skipRetrying = !!onErrorResult.skipRetrying;
1393
+ if (onErrorResult.retryAt && !skipRetrying) {
1394
+ const parsedError2 = import_core2.ErrorWithStackSchema.safeParse(onErrorResult.error);
1395
+ throw new RetryWithTaskError(parsedError2.success ? parsedError2.data : {
1396
+ message: "Unknown error"
1397
+ }, task, onErrorResult.retryAt);
1398
+ }
1399
+ }
1126
1400
  }
1127
- case "ERROR": {
1128
- this._jobLogger?.error(message, data);
1129
- logLevel = "error";
1130
- break;
1401
+ } catch (innerError) {
1402
+ if (isTriggerError(innerError)) {
1403
+ throw innerError;
1131
1404
  }
1405
+ error = innerError;
1132
1406
  }
1133
- }, {
1134
- name: "log",
1135
- icon: "log",
1136
- description: message,
1137
- params: data,
1138
- properties: [
1139
- {
1140
- label: "Level",
1141
- text: level
1407
+ }
1408
+ if (error instanceof ErrorWithTask) {
1409
+ await this._apiClient.failTask(this._id, task.id, {
1410
+ error: error.cause.output
1411
+ });
1412
+ }
1413
+ const parsedError = import_core2.ErrorWithStackSchema.safeParse(error);
1414
+ if (options?.retry && !skipRetrying) {
1415
+ const retryAt = (0, import_core.calculateRetryAt)(options.retry, task.attempts - 1);
1416
+ if (retryAt) {
1417
+ throw new RetryWithTaskError(parsedError.success ? parsedError.data : {
1418
+ message: "Unknown error"
1419
+ }, task, retryAt);
1420
+ }
1421
+ }
1422
+ if (parsedError.success) {
1423
+ await this._apiClient.failTask(this._id, task.id, {
1424
+ error: parsedError.data
1425
+ });
1426
+ } else {
1427
+ const message = typeof error === "string" ? error : JSON.stringify(error);
1428
+ await this._apiClient.failTask(this._id, task.id, {
1429
+ error: {
1430
+ name: "Unknown error",
1431
+ message
1142
1432
  }
1143
- ],
1144
- style: {
1145
- style: "minimal",
1146
- variant: level.toLowerCase()
1147
- },
1148
- noop: true
1149
- });
1150
- }
1151
- });
1152
- }
1153
- async random(cacheKey, { min = 0, max = 1, round = false } = {}) {
1154
- return await this.runTask(cacheKey, async (task) => {
1155
- if (min > max) {
1156
- throw new Error(`Lower bound can't be higher than upper bound - min: ${min}, max: ${max}`);
1157
- }
1158
- if (min === max) {
1159
- await this.logger.warn(`Lower and upper bounds are identical. The return value is not random and will always be: ${min}`);
1160
- }
1161
- const withinBounds = (max - min) * Math.random() + min;
1162
- if (!round) {
1163
- return withinBounds;
1164
- }
1165
- if (!Number.isInteger(min) || !Number.isInteger(max)) {
1166
- await this.logger.warn("Rounding enabled with floating-point bounds. This may cause unexpected skew and boundary inclusivity.");
1433
+ });
1434
+ }
1435
+ throw error;
1167
1436
  }
1168
- const rounded = Math.round(withinBounds);
1169
- return rounded;
1170
- }, {
1171
- name: "random",
1172
- icon: "dice-5-filled",
1173
- params: {
1174
- min,
1175
- max,
1176
- round
1177
- },
1178
- properties: [
1179
- ...min === 0 ? [] : [
1180
- {
1181
- label: "min",
1182
- text: String(min)
1183
- }
1184
- ],
1185
- ...max === 1 ? [] : [
1186
- {
1187
- label: "max",
1188
- text: String(max)
1189
- }
1190
- ],
1191
- ...round === false ? [] : [
1192
- {
1193
- label: "round",
1194
- text: String(round)
1195
- }
1196
- ]
1197
- ],
1198
- style: {
1199
- style: "minimal"
1437
+ }, "executeTask");
1438
+ if (task.status === "WAITING") {
1439
+ this._logger.debug("Task waiting", {
1440
+ idempotencyKey,
1441
+ task
1442
+ });
1443
+ if (task.callbackUrl) {
1444
+ await this._taskStorage.run({
1445
+ taskId: task.id
1446
+ }, executeTask);
1200
1447
  }
1201
- });
1448
+ throw new ResumeWithTaskError(task);
1449
+ }
1450
+ if (task.status === "RUNNING" && typeof task.operation === "string") {
1451
+ this._logger.debug("Task running operation", {
1452
+ idempotencyKey,
1453
+ task
1454
+ });
1455
+ throw new ResumeWithTaskError(task);
1456
+ }
1457
+ return this._taskStorage.run({
1458
+ taskId: task.id
1459
+ }, executeTask);
1202
1460
  }
1203
- async wait(cacheKey, seconds) {
1204
- return await this.runTask(cacheKey, async (task) => {
1205
- }, {
1206
- name: "wait",
1207
- icon: "clock",
1208
- params: {
1209
- seconds
1210
- },
1211
- noop: true,
1212
- delayUntil: new Date(Date.now() + seconds * 1e3),
1213
- style: {
1214
- style: "minimal"
1215
- }
1216
- });
1461
+ yield(cacheKey) {
1462
+ if (!(0, import_core2.supportsFeature)("yieldExecution", this._serverVersion)) {
1463
+ 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.");
1464
+ return;
1465
+ }
1466
+ if (this._yieldedExecutions.includes(cacheKey)) {
1467
+ return;
1468
+ }
1469
+ throw new YieldExecutionError(cacheKey);
1217
1470
  }
1218
- async waitForEvent(cacheKey, event, options) {
1219
- const timeoutInSeconds = options?.timeoutInSeconds ?? 60 * 60;
1220
- return await this.runTask(cacheKey, async (task, io) => {
1221
- if (!task.callbackUrl) {
1222
- throw new Error("No callbackUrl found on task");
1471
+ async try(tryCallback, catchCallback) {
1472
+ try {
1473
+ return await tryCallback();
1474
+ } catch (error) {
1475
+ if (isTriggerError(error)) {
1476
+ throw error;
1223
1477
  }
1224
- await this.triggerClient.createEphemeralEventDispatcher({
1225
- url: task.callbackUrl,
1226
- name: event.name,
1227
- filter: event.filter,
1228
- contextFilter: event.contextFilter,
1229
- source: event.source,
1230
- accountId: event.accountId,
1231
- timeoutInSeconds
1232
- });
1233
- return {};
1234
- }, {
1235
- name: "Wait for Event",
1236
- icon: "custom-event",
1237
- params: {
1238
- name: event.name,
1239
- source: event.source,
1240
- filter: event.filter,
1241
- contextFilter: event.contextFilter,
1242
- accountId: event.accountId
1243
- },
1244
- callback: {
1245
- enabled: true,
1246
- timeoutInSeconds
1247
- },
1248
- properties: [
1249
- {
1250
- label: "Event",
1251
- text: event.name
1252
- },
1253
- {
1254
- label: "Timeout",
1255
- text: `${timeoutInSeconds}s`
1256
- },
1257
- ...event.source ? [
1258
- {
1259
- label: "Source",
1260
- text: event.source
1261
- }
1262
- ] : [],
1263
- ...event.accountId ? [
1264
- {
1265
- label: "Account ID",
1266
- text: event.accountId
1267
- }
1268
- ] : []
1269
- ],
1270
- parseOutput: (output) => {
1271
- return waitForEventSchema(event.schema ?? import_zod3.z.any()).parse(output);
1478
+ return await catchCallback(error);
1479
+ }
1480
+ }
1481
+ get store() {
1482
+ return {
1483
+ env: this._envStore,
1484
+ job: this._jobStore,
1485
+ run: this._runStore
1486
+ };
1487
+ }
1488
+ };
1489
+ __name(IO, "IO");
1490
+ _addToCachedTasks = new WeakSet();
1491
+ addToCachedTasks_fn = /* @__PURE__ */ __name(function(task) {
1492
+ this._cachedTasks.set(task.idempotencyKey, task);
1493
+ }, "#addToCachedTasks");
1494
+ _detectAutoYield = new WeakSet();
1495
+ detectAutoYield_fn = /* @__PURE__ */ __name(function(location, threshold = 1500, task1, output) {
1496
+ const timeRemaining = __privateMethod(this, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn).call(this);
1497
+ if (timeRemaining && timeRemaining < threshold) {
1498
+ if (task1) {
1499
+ throw new AutoYieldWithCompletedTaskExecutionError(task1.id, task1.outputProperties ?? [], {
1500
+ location,
1501
+ timeRemaining,
1502
+ timeElapsed: __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this)
1503
+ }, output);
1504
+ } else {
1505
+ throw new AutoYieldExecutionError(location, timeRemaining, __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this));
1506
+ }
1507
+ }
1508
+ }, "#detectAutoYield");
1509
+ _forceYield = new WeakSet();
1510
+ forceYield_fn = /* @__PURE__ */ __name(function(location1) {
1511
+ const timeRemaining = __privateMethod(this, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn).call(this);
1512
+ if (timeRemaining) {
1513
+ throw new AutoYieldExecutionError(location1, timeRemaining, __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this));
1514
+ }
1515
+ }, "#forceYield");
1516
+ _getTimeElapsed = new WeakSet();
1517
+ getTimeElapsed_fn = /* @__PURE__ */ __name(function() {
1518
+ return performance.now() - this._timeOrigin;
1519
+ }, "#getTimeElapsed");
1520
+ _getRemainingTimeInMillis = new WeakSet();
1521
+ getRemainingTimeInMillis_fn = /* @__PURE__ */ __name(function() {
1522
+ if (this._executionTimeout) {
1523
+ return this._executionTimeout - (performance.now() - this._timeOrigin);
1524
+ }
1525
+ return void 0;
1526
+ }, "#getRemainingTimeInMillis");
1527
+ async function generateIdempotencyKey(keyMaterial) {
1528
+ const keys = keyMaterial.map((key2) => {
1529
+ if (typeof key2 === "string") {
1530
+ return key2;
1531
+ }
1532
+ return stableStringify(key2);
1533
+ });
1534
+ const key = keys.join(":");
1535
+ const hash = await import_node_crypto.webcrypto.subtle.digest("SHA-256", Buffer.from(key));
1536
+ return Buffer.from(hash).toString("hex");
1537
+ }
1538
+ __name(generateIdempotencyKey, "generateIdempotencyKey");
1539
+ function stableStringify(obj) {
1540
+ function sortKeys(obj2) {
1541
+ if (typeof obj2 !== "object" || obj2 === null) {
1542
+ return obj2;
1543
+ }
1544
+ if (Array.isArray(obj2)) {
1545
+ return obj2.map(sortKeys);
1546
+ }
1547
+ const sortedKeys = Object.keys(obj2).sort();
1548
+ const sortedObj2 = {};
1549
+ for (const key of sortedKeys) {
1550
+ sortedObj2[key] = sortKeys(obj2[key]);
1551
+ }
1552
+ return sortedObj2;
1553
+ }
1554
+ __name(sortKeys, "sortKeys");
1555
+ const sortedObj = sortKeys(obj);
1556
+ return JSON.stringify(sortedObj);
1557
+ }
1558
+ __name(stableStringify, "stableStringify");
1559
+ var IOLogger = class {
1560
+ constructor(callback) {
1561
+ this.callback = callback;
1562
+ }
1563
+ log(message, properties) {
1564
+ return this.callback("LOG", message, properties);
1565
+ }
1566
+ debug(message, properties) {
1567
+ return this.callback("DEBUG", message, properties);
1568
+ }
1569
+ info(message, properties) {
1570
+ return this.callback("INFO", message, properties);
1571
+ }
1572
+ warn(message, properties) {
1573
+ return this.callback("WARN", message, properties);
1574
+ }
1575
+ error(message, properties) {
1576
+ return this.callback("ERROR", message, properties);
1577
+ }
1578
+ };
1579
+ __name(IOLogger, "IOLogger");
1580
+ async function spaceOut(callback, index, delay) {
1581
+ await new Promise((resolve) => setTimeout(resolve, index * delay));
1582
+ return await callback();
1583
+ }
1584
+ __name(spaceOut, "spaceOut");
1585
+ function sendEventOptionsProperties(options) {
1586
+ return [
1587
+ ...options?.accountId ? [
1588
+ {
1589
+ label: "Account ID",
1590
+ text: options.accountId
1591
+ }
1592
+ ] : [],
1593
+ ...options?.deliverAfter ? [
1594
+ {
1595
+ label: "Deliver After",
1596
+ text: `${options.deliverAfter}s`
1597
+ }
1598
+ ] : [],
1599
+ ...options?.deliverAt ? [
1600
+ {
1601
+ label: "Deliver At",
1602
+ text: options.deliverAt.toISOString()
1272
1603
  }
1604
+ ] : []
1605
+ ];
1606
+ }
1607
+ __name(sendEventOptionsProperties, "sendEventOptionsProperties");
1608
+
1609
+ // src/store/keyValueStoreClient.ts
1610
+ var _serializer, _namespacedKey2, namespacedKey_fn2;
1611
+ var KeyValueStoreClient = class {
1612
+ constructor(queryStore, type = null, namespace = "") {
1613
+ __privateAdd(this, _namespacedKey2);
1614
+ __privateAdd(this, _serializer, void 0);
1615
+ this.queryStore = queryStore;
1616
+ this.type = type;
1617
+ this.namespace = namespace;
1618
+ __privateSet(this, _serializer, new JSONOutputSerializer());
1619
+ }
1620
+ async delete(key) {
1621
+ const result = await this.queryStore("DELETE", {
1622
+ key: __privateMethod(this, _namespacedKey2, namespacedKey_fn2).call(this, key)
1273
1623
  });
1624
+ if (result.action !== "DELETE") {
1625
+ throw new Error(`Unexpected key-value store response: ${result.action}`);
1626
+ }
1627
+ return result.deleted;
1274
1628
  }
1275
- async waitForRequest(cacheKey, callback, options) {
1276
- const timeoutInSeconds = options?.timeoutInSeconds ?? 60 * 60;
1277
- return await this.runTask(cacheKey, async (task, io) => {
1278
- if (!task.callbackUrl) {
1279
- throw new Error("No callbackUrl found on task");
1280
- }
1281
- task.outputProperties = [
1282
- {
1283
- label: "Callback URL",
1284
- text: task.callbackUrl
1285
- }
1286
- ];
1287
- return callback(task.callbackUrl);
1288
- }, {
1289
- name: "Wait for Request",
1290
- icon: "clock",
1291
- callback: {
1292
- enabled: true,
1293
- timeoutInSeconds: options?.timeoutInSeconds
1294
- },
1295
- properties: [
1296
- {
1297
- label: "Timeout",
1298
- text: `${timeoutInSeconds}s`
1299
- }
1300
- ]
1629
+ async get(key) {
1630
+ const result = await this.queryStore("GET", {
1631
+ key: __privateMethod(this, _namespacedKey2, namespacedKey_fn2).call(this, key)
1301
1632
  });
1633
+ if (result.action !== "GET") {
1634
+ throw new Error(`Unexpected key-value store response: ${result.action}`);
1635
+ }
1636
+ return __privateGet(this, _serializer).deserialize(result.value);
1302
1637
  }
1303
- async createStatus(cacheKey, initialStatus) {
1304
- const id = typeof cacheKey === "string" ? cacheKey : cacheKey.join("-");
1305
- const status = new TriggerStatus(id, this);
1306
- await status.update(cacheKey, initialStatus);
1307
- return status;
1638
+ async has(key) {
1639
+ const result = await this.queryStore("HAS", {
1640
+ key: __privateMethod(this, _namespacedKey2, namespacedKey_fn2).call(this, key)
1641
+ });
1642
+ if (result.action !== "HAS") {
1643
+ throw new Error(`Unexpected key-value store response: ${result.action}`);
1644
+ }
1645
+ return result.has;
1308
1646
  }
1309
- async backgroundFetch(cacheKey, url, requestInit, options) {
1310
- const urlObject = new URL(url);
1311
- return await this.runTask(cacheKey, async (task) => {
1312
- console.log("task context", task.context);
1313
- return task.output;
1314
- }, {
1315
- name: `fetch ${urlObject.hostname}${urlObject.pathname}`,
1316
- params: {
1317
- url,
1318
- requestInit,
1319
- retry: options?.retry,
1320
- timeout: options?.timeout
1321
- },
1322
- operation: "fetch",
1323
- icon: "background",
1324
- noop: false,
1325
- properties: [
1326
- {
1327
- label: "url",
1328
- text: url,
1329
- url
1330
- },
1331
- {
1332
- label: "method",
1333
- text: requestInit?.method ?? "GET"
1334
- },
1335
- {
1336
- label: "background",
1337
- text: "true"
1338
- },
1339
- ...options?.timeout ? [
1340
- {
1341
- label: "timeout",
1342
- text: `${options.timeout.durationInMs}ms`
1343
- }
1344
- ] : []
1345
- ],
1346
- retry: {
1347
- limit: 0
1348
- }
1647
+ async set(key, value) {
1648
+ const result = await this.queryStore("SET", {
1649
+ key: __privateMethod(this, _namespacedKey2, namespacedKey_fn2).call(this, key),
1650
+ value: __privateGet(this, _serializer).serialize(value)
1349
1651
  });
1652
+ if (result.action !== "SET") {
1653
+ throw new Error(`Unexpected key-value store response: ${result.action}`);
1654
+ }
1655
+ return __privateGet(this, _serializer).deserialize(result.value);
1350
1656
  }
1351
- async backgroundPoll(cacheKey, params) {
1352
- const urlObject = new URL(params.url);
1353
- return await this.runTask(cacheKey, async (task) => {
1354
- return task.output;
1355
- }, {
1356
- name: `poll ${urlObject.hostname}${urlObject.pathname}`,
1357
- params,
1358
- operation: "fetch-poll",
1359
- icon: "clock-bolt",
1360
- noop: false,
1361
- properties: [
1362
- {
1363
- label: "url",
1364
- text: params.url
1365
- },
1366
- {
1367
- label: "interval",
1368
- text: `${params.interval}s`
1369
- },
1370
- {
1371
- label: "timeout",
1372
- text: `${params.timeout}s`
1373
- }
1374
- ],
1375
- retry: {
1376
- limit: 0
1377
- }
1657
+ };
1658
+ __name(KeyValueStoreClient, "KeyValueStoreClient");
1659
+ _serializer = new WeakMap();
1660
+ _namespacedKey2 = new WeakSet();
1661
+ namespacedKey_fn2 = /* @__PURE__ */ __name(function(key) {
1662
+ const parts = [];
1663
+ if (this.type) {
1664
+ parts.push(this.type);
1665
+ }
1666
+ if (this.namespace) {
1667
+ parts.push(this.namespace);
1668
+ }
1669
+ parts.push(key);
1670
+ return parts.join(":");
1671
+ }, "#namespacedKey");
1672
+
1673
+ // src/apiClient.ts
1674
+ var _apiUrl, _options, _logger, _storeClient, _queryKeyValueStore, queryKeyValueStore_fn, _apiKey, apiKey_fn;
1675
+ var ApiClient = class {
1676
+ constructor(options) {
1677
+ __privateAdd(this, _queryKeyValueStore);
1678
+ __privateAdd(this, _apiKey);
1679
+ __privateAdd(this, _apiUrl, void 0);
1680
+ __privateAdd(this, _options, void 0);
1681
+ __privateAdd(this, _logger, void 0);
1682
+ __privateAdd(this, _storeClient, void 0);
1683
+ __privateSet(this, _options, options);
1684
+ __privateSet(this, _apiUrl, __privateGet(this, _options).apiUrl ?? process.env.TRIGGER_API_URL ?? "https://api.trigger.dev");
1685
+ __privateSet(this, _logger, new import_core3.Logger("trigger.dev", __privateGet(this, _options).logLevel));
1686
+ __privateSet(this, _storeClient, new KeyValueStoreClient(__privateMethod(this, _queryKeyValueStore, queryKeyValueStore_fn).bind(this)));
1687
+ }
1688
+ async registerEndpoint(options) {
1689
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1690
+ __privateGet(this, _logger).debug("Registering endpoint", {
1691
+ url: options.url,
1692
+ name: options.name
1693
+ });
1694
+ const response = await fetch(`${__privateGet(this, _apiUrl)}/api/v1/endpoints`, {
1695
+ method: "POST",
1696
+ headers: {
1697
+ "Content-Type": "application/json",
1698
+ Authorization: `Bearer ${apiKey}`
1699
+ },
1700
+ body: JSON.stringify({
1701
+ url: options.url,
1702
+ name: options.name
1703
+ })
1378
1704
  });
1705
+ if (response.status >= 400 && response.status < 500) {
1706
+ const body = await response.json();
1707
+ throw new Error(body.error);
1708
+ }
1709
+ if (response.status !== 200) {
1710
+ throw new Error(`Failed to register entry point, got status code ${response.status}`);
1711
+ }
1712
+ return await response.json();
1379
1713
  }
1380
- async backgroundFetchResponse(cacheKey, url, requestInit, options) {
1381
- const urlObject = new URL(url);
1382
- return await this.runTask(cacheKey, async (task) => {
1383
- return task.output;
1384
- }, {
1385
- name: `fetch response ${urlObject.hostname}${urlObject.pathname}`,
1386
- params: {
1387
- url,
1388
- requestInit,
1389
- retry: options?.retry,
1390
- timeout: options?.timeout
1714
+ async runTask(runId, task, options = {}) {
1715
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1716
+ __privateGet(this, _logger).debug("Running Task", {
1717
+ task
1718
+ });
1719
+ return await zodfetchWithVersions({
1720
+ [import_core3.API_VERSIONS.LAZY_LOADED_CACHED_TASKS]: import_core3.RunTaskResponseWithCachedTasksBodySchema
1721
+ }, import_core3.ServerTaskSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/tasks`, {
1722
+ method: "POST",
1723
+ headers: {
1724
+ "Content-Type": "application/json",
1725
+ Authorization: `Bearer ${apiKey}`,
1726
+ "Idempotency-Key": task.idempotencyKey,
1727
+ "X-Cached-Tasks-Cursor": options.cachedTasksCursor ?? "",
1728
+ "Trigger-Version": import_core3.API_VERSIONS.LAZY_LOADED_CACHED_TASKS
1391
1729
  },
1392
- operation: "fetch-response",
1393
- icon: "background",
1394
- noop: false,
1395
- properties: [
1396
- {
1397
- label: "url",
1398
- text: url,
1399
- url
1400
- },
1401
- {
1402
- label: "method",
1403
- text: requestInit?.method ?? "GET"
1404
- },
1405
- {
1406
- label: "background",
1407
- text: "true"
1408
- },
1409
- ...options?.timeout ? [
1410
- {
1411
- label: "timeout",
1412
- text: `${options.timeout.durationInMs}ms`
1413
- }
1414
- ] : []
1415
- ],
1416
- retry: {
1417
- limit: 0
1418
- }
1730
+ body: JSON.stringify(task)
1419
1731
  });
1420
1732
  }
1421
- async sendEvent(cacheKey, event, options) {
1422
- return await this.runTask(cacheKey, async (task) => {
1423
- return await this._triggerClient.sendEvent(event, options);
1424
- }, {
1425
- name: "sendEvent",
1426
- params: {
1427
- event,
1428
- options
1733
+ async completeTask(runId, id, task) {
1734
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1735
+ __privateGet(this, _logger).debug("Complete Task", {
1736
+ task
1737
+ });
1738
+ return await zodfetch(import_core3.ServerTaskSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/tasks/${id}/complete`, {
1739
+ method: "POST",
1740
+ headers: {
1741
+ "Content-Type": "application/json",
1742
+ Authorization: `Bearer ${apiKey}`,
1743
+ "Trigger-Version": import_core3.API_VERSIONS.SERIALIZED_TASK_OUTPUT
1429
1744
  },
1430
- properties: [
1431
- {
1432
- label: "name",
1433
- text: event.name
1434
- },
1435
- ...event?.id ? [
1436
- {
1437
- label: "ID",
1438
- text: event.id
1439
- }
1440
- ] : [],
1441
- ...sendEventOptionsProperties(options)
1442
- ]
1745
+ body: JSON.stringify(task)
1443
1746
  });
1444
1747
  }
1445
- async sendEvents(cacheKey, events, options) {
1446
- return await this.runTask(cacheKey, async (task) => {
1447
- return await this._triggerClient.sendEvents(events, options);
1448
- }, {
1449
- name: "sendEvents",
1450
- params: {
1451
- events,
1452
- options
1748
+ async failTask(runId, id, body) {
1749
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1750
+ __privateGet(this, _logger).debug("Fail Task", {
1751
+ id,
1752
+ runId,
1753
+ body
1754
+ });
1755
+ return await zodfetch(import_core3.ServerTaskSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/tasks/${id}/fail`, {
1756
+ method: "POST",
1757
+ headers: {
1758
+ "Content-Type": "application/json",
1759
+ Authorization: `Bearer ${apiKey}`
1453
1760
  },
1454
- properties: [
1455
- {
1456
- label: "Total Events",
1457
- text: String(events.length)
1458
- },
1459
- ...sendEventOptionsProperties(options)
1460
- ]
1761
+ body: JSON.stringify(body)
1461
1762
  });
1462
1763
  }
1463
- async getEvent(cacheKey, id) {
1464
- return await this.runTask(cacheKey, async (task) => {
1465
- return await this._triggerClient.getEvent(id);
1466
- }, {
1467
- name: "getEvent",
1468
- params: {
1469
- id
1764
+ async sendEvent(event, options = {}) {
1765
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1766
+ __privateGet(this, _logger).debug("Sending event", {
1767
+ event
1768
+ });
1769
+ return await zodfetch(import_core3.ApiEventLogSchema, `${__privateGet(this, _apiUrl)}/api/v1/events`, {
1770
+ method: "POST",
1771
+ headers: {
1772
+ "Content-Type": "application/json",
1773
+ Authorization: `Bearer ${apiKey}`
1470
1774
  },
1471
- properties: [
1472
- {
1473
- label: "id",
1474
- text: id
1475
- }
1476
- ]
1775
+ body: JSON.stringify({
1776
+ event,
1777
+ options
1778
+ })
1477
1779
  });
1478
1780
  }
1479
- async cancelEvent(cacheKey, eventId) {
1480
- return await this.runTask(cacheKey, async (task) => {
1481
- return await this._triggerClient.cancelEvent(eventId);
1482
- }, {
1483
- name: "cancelEvent",
1484
- params: {
1485
- eventId
1781
+ async sendEvents(events, options = {}) {
1782
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1783
+ __privateGet(this, _logger).debug("Sending multiple events", {
1784
+ events
1785
+ });
1786
+ return await zodfetch(import_core3.ApiEventLogSchema.array(), `${__privateGet(this, _apiUrl)}/api/v1/events/bulk`, {
1787
+ method: "POST",
1788
+ headers: {
1789
+ "Content-Type": "application/json",
1790
+ Authorization: `Bearer ${apiKey}`
1486
1791
  },
1487
- properties: [
1488
- {
1489
- label: "id",
1490
- text: eventId
1491
- }
1492
- ]
1792
+ body: JSON.stringify({
1793
+ events,
1794
+ options
1795
+ })
1493
1796
  });
1494
1797
  }
1495
- async updateSource(cacheKey, options) {
1496
- return this.runTask(cacheKey, async (task) => {
1497
- return await this._apiClient.updateSource(this._triggerClient.id, options.key, options);
1498
- }, {
1499
- name: "Update Source",
1500
- description: "Update Source",
1501
- properties: [
1502
- {
1503
- label: "key",
1504
- text: options.key
1505
- }
1506
- ],
1507
- params: options,
1508
- redact: {
1509
- paths: [
1510
- "secret"
1511
- ]
1798
+ async cancelEvent(eventId) {
1799
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1800
+ __privateGet(this, _logger).debug("Cancelling event", {
1801
+ eventId
1802
+ });
1803
+ return await zodfetch(import_core3.ApiEventLogSchema, `${__privateGet(this, _apiUrl)}/api/v1/events/${eventId}/cancel`, {
1804
+ method: "POST",
1805
+ headers: {
1806
+ "Content-Type": "application/json",
1807
+ Authorization: `Bearer ${apiKey}`
1512
1808
  }
1513
1809
  });
1514
1810
  }
1515
- async registerInterval(cacheKey, dynamicSchedule, id, options) {
1516
- return await this.runTask(cacheKey, async (task) => {
1517
- return dynamicSchedule.register(id, {
1518
- type: "interval",
1519
- options
1520
- });
1521
- }, {
1522
- name: "register-interval",
1523
- properties: [
1524
- {
1525
- label: "schedule",
1526
- text: dynamicSchedule.id
1527
- },
1528
- {
1529
- label: "id",
1530
- text: id
1531
- },
1532
- {
1533
- label: "seconds",
1534
- text: options.seconds.toString()
1535
- }
1536
- ],
1537
- params: options
1811
+ async cancelRunsForEvent(eventId) {
1812
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1813
+ __privateGet(this, _logger).debug("Cancelling runs for event", {
1814
+ eventId
1538
1815
  });
1539
- }
1540
- async unregisterInterval(cacheKey, dynamicSchedule, id) {
1541
- return await this.runTask(cacheKey, async (task) => {
1542
- return dynamicSchedule.unregister(id);
1543
- }, {
1544
- name: "unregister-interval",
1545
- properties: [
1546
- {
1547
- label: "schedule",
1548
- text: dynamicSchedule.id
1549
- },
1550
- {
1551
- label: "id",
1552
- text: id
1553
- }
1554
- ]
1816
+ return await zodfetch(import_core3.CancelRunsForEventSchema, `${__privateGet(this, _apiUrl)}/api/v1/events/${eventId}/cancel-runs`, {
1817
+ method: "POST",
1818
+ headers: {
1819
+ "Content-Type": "application/json",
1820
+ Authorization: `Bearer ${apiKey}`
1821
+ }
1555
1822
  });
1556
1823
  }
1557
- async registerCron(cacheKey, dynamicSchedule, id, options) {
1558
- return await this.runTask(cacheKey, async (task) => {
1559
- return dynamicSchedule.register(id, {
1560
- type: "cron",
1561
- options
1562
- });
1563
- }, {
1564
- name: "register-cron",
1565
- properties: [
1566
- {
1567
- label: "schedule",
1568
- text: dynamicSchedule.id
1569
- },
1570
- {
1571
- label: "id",
1572
- text: id
1573
- },
1574
- {
1575
- label: "cron",
1576
- text: options.cron
1577
- }
1578
- ],
1579
- params: options
1824
+ async updateStatus(runId, id, status) {
1825
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1826
+ __privateGet(this, _logger).debug("Update status", {
1827
+ id,
1828
+ status
1829
+ });
1830
+ return await zodfetch(import_core3.JobRunStatusRecordSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/statuses/${id}`, {
1831
+ method: "PUT",
1832
+ headers: {
1833
+ "Content-Type": "application/json",
1834
+ Authorization: `Bearer ${apiKey}`
1835
+ },
1836
+ body: JSON.stringify(status)
1580
1837
  });
1581
1838
  }
1582
- async unregisterCron(cacheKey, dynamicSchedule, id) {
1583
- return await this.runTask(cacheKey, async (task) => {
1584
- return dynamicSchedule.unregister(id);
1585
- }, {
1586
- name: "unregister-cron",
1587
- properties: [
1588
- {
1589
- label: "schedule",
1590
- text: dynamicSchedule.id
1591
- },
1592
- {
1593
- label: "id",
1594
- text: id
1595
- }
1596
- ]
1839
+ async updateSource(client, key, source) {
1840
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1841
+ __privateGet(this, _logger).debug("activating http source", {
1842
+ source
1597
1843
  });
1844
+ const response = await zodfetch(import_core3.TriggerSourceSchema, `${__privateGet(this, _apiUrl)}/api/v2/${client}/sources/${key}`, {
1845
+ method: "PUT",
1846
+ headers: {
1847
+ "Content-Type": "application/json",
1848
+ Authorization: `Bearer ${apiKey}`
1849
+ },
1850
+ body: JSON.stringify(source)
1851
+ });
1852
+ return response;
1598
1853
  }
1599
- async registerTrigger(cacheKey, trigger, id, params) {
1600
- return await this.runTask(cacheKey, async (task) => {
1601
- const registration = await this.runTask("register-source", async (subtask1) => {
1602
- return trigger.register(id, params);
1603
- }, {
1604
- name: "register-source"
1605
- });
1606
- return {
1607
- id: registration.id,
1608
- key: registration.source.key
1609
- };
1610
- }, {
1611
- name: "register-trigger",
1612
- properties: [
1613
- {
1614
- label: "trigger",
1615
- text: trigger.id
1616
- },
1617
- {
1618
- label: "id",
1619
- text: id
1620
- }
1621
- ],
1622
- params
1854
+ async updateWebhook(key, webhookData) {
1855
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1856
+ __privateGet(this, _logger).debug("activating webhook", {
1857
+ webhookData
1623
1858
  });
1859
+ const response = await zodfetch(import_core3.TriggerSourceSchema, `${__privateGet(this, _apiUrl)}/api/v1/webhooks/${key}`, {
1860
+ method: "PUT",
1861
+ headers: {
1862
+ "Content-Type": "application/json",
1863
+ Authorization: `Bearer ${apiKey}`
1864
+ },
1865
+ body: JSON.stringify(webhookData)
1866
+ });
1867
+ return response;
1624
1868
  }
1625
- async getAuth(cacheKey, clientId) {
1626
- if (!clientId) {
1627
- return;
1869
+ async registerTrigger(client, id, key, payload, idempotencyKey) {
1870
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1871
+ __privateGet(this, _logger).debug("registering trigger", {
1872
+ id,
1873
+ payload
1874
+ });
1875
+ const headers = {
1876
+ "Content-Type": "application/json",
1877
+ Authorization: `Bearer ${apiKey}`
1878
+ };
1879
+ if (idempotencyKey) {
1880
+ headers["Idempotency-Key"] = idempotencyKey;
1628
1881
  }
1629
- return this.runTask(cacheKey, async (task) => {
1630
- return await this._triggerClient.getAuth(clientId);
1631
- }, {
1632
- name: "get-auth"
1882
+ const response = await zodfetch(import_core3.RegisterSourceEventSchemaV2, `${__privateGet(this, _apiUrl)}/api/v2/${client}/triggers/${id}/registrations/${key}`, {
1883
+ method: "PUT",
1884
+ headers,
1885
+ body: JSON.stringify(payload)
1633
1886
  });
1887
+ return response;
1634
1888
  }
1635
- async parallel(cacheKey, items, callback, options) {
1636
- const results = await this.runTask(cacheKey, async (task) => {
1637
- const outcomes = await Promise.allSettled(items.map((item, index) => spaceOut(() => callback(item, index), index, 15)));
1638
- if (outcomes.every((outcome) => outcome.status === "fulfilled")) {
1639
- return outcomes.map((outcome) => outcome.value);
1889
+ async registerSchedule(client, id, key, payload) {
1890
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1891
+ __privateGet(this, _logger).debug("registering schedule", {
1892
+ id,
1893
+ payload
1894
+ });
1895
+ const response = await zodfetch(import_core3.RegisterScheduleResponseBodySchema, `${__privateGet(this, _apiUrl)}/api/v1/${client}/schedules/${id}/registrations`, {
1896
+ method: "POST",
1897
+ headers: {
1898
+ "Content-Type": "application/json",
1899
+ Authorization: `Bearer ${apiKey}`
1900
+ },
1901
+ body: JSON.stringify({
1902
+ id: key,
1903
+ ...payload
1904
+ })
1905
+ });
1906
+ return response;
1907
+ }
1908
+ async unregisterSchedule(client, id, key) {
1909
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1910
+ __privateGet(this, _logger).debug("unregistering schedule", {
1911
+ id
1912
+ });
1913
+ const response = await zodfetch(import_zod3.z.object({
1914
+ ok: import_zod3.z.boolean()
1915
+ }), `${__privateGet(this, _apiUrl)}/api/v1/${client}/schedules/${id}/registrations/${encodeURIComponent(key)}`, {
1916
+ method: "DELETE",
1917
+ headers: {
1918
+ "Content-Type": "application/json",
1919
+ Authorization: `Bearer ${apiKey}`
1640
1920
  }
1641
- const nonInternalErrors = outcomes.filter((outcome) => outcome.status === "rejected" && !isTriggerError(outcome.reason)).map((outcome) => outcome);
1642
- if (nonInternalErrors.length > 0) {
1643
- throw nonInternalErrors[0].reason;
1921
+ });
1922
+ return response;
1923
+ }
1924
+ async getAuth(client, id) {
1925
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1926
+ __privateGet(this, _logger).debug("getting auth", {
1927
+ id
1928
+ });
1929
+ const response = await zodfetch(import_core3.ConnectionAuthSchema, `${__privateGet(this, _apiUrl)}/api/v1/${client}/auth/${id}`, {
1930
+ method: "GET",
1931
+ headers: {
1932
+ Accept: "application/json",
1933
+ Authorization: `Bearer ${apiKey}`
1644
1934
  }
1645
- const internalErrors = outcomes.filter((outcome) => outcome.status === "rejected" && isTriggerError(outcome.reason)).map((outcome) => outcome).map((outcome) => outcome.reason);
1646
- throw new ResumeWithParallelTaskError(task, internalErrors);
1647
1935
  }, {
1648
- name: "parallel",
1649
- parallel: true,
1650
- ...options ?? {}
1936
+ optional: true
1651
1937
  });
1652
- return results;
1938
+ return response;
1653
1939
  }
1654
- async runTask(cacheKey, callback, options, onError) {
1655
- __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "start_task", 500);
1656
- const parentId = this._taskStorage.getStore()?.taskId;
1657
- if (parentId) {
1658
- this._logger.debug("Using parent task", {
1659
- parentId,
1660
- cacheKey,
1661
- options
1662
- });
1663
- }
1664
- const idempotencyKey = await generateIdempotencyKey([
1665
- this._id,
1666
- parentId ?? "",
1667
- cacheKey
1668
- ].flat());
1669
- if (this._visitedCacheKeys.has(idempotencyKey)) {
1670
- if (typeof cacheKey === "string") {
1671
- throw new Error(`Task with cacheKey "${cacheKey}" has already been executed in this run. Each task must have a unique cacheKey.`);
1672
- } else {
1673
- throw new Error(`Task with cacheKey "${cacheKey.join("-")}" has already been executed in this run. Each task must have a unique cacheKey.`);
1940
+ async getEvent(eventId) {
1941
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1942
+ __privateGet(this, _logger).debug("Getting Event", {
1943
+ eventId
1944
+ });
1945
+ return await zodfetch(import_core3.GetEventSchema, `${__privateGet(this, _apiUrl)}/api/v1/events/${eventId}`, {
1946
+ method: "GET",
1947
+ headers: {
1948
+ Authorization: `Bearer ${apiKey}`
1674
1949
  }
1675
- }
1676
- this._visitedCacheKeys.add(idempotencyKey);
1677
- const cachedTask = this._cachedTasks.get(idempotencyKey);
1678
- if (cachedTask && cachedTask.status === "COMPLETED") {
1679
- this._logger.debug("Using completed cached task", {
1680
- idempotencyKey
1681
- });
1682
- this._stats.cachedTaskHits++;
1683
- return options?.parseOutput ? options.parseOutput(cachedTask.output) : cachedTask.output;
1684
- }
1685
- if (options?.noop && this._noopTasksBloomFilter) {
1686
- if (this._noopTasksBloomFilter.test(idempotencyKey)) {
1687
- this._logger.debug("task idempotency key exists in noopTasksBloomFilter", {
1688
- idempotencyKey
1689
- });
1690
- this._stats.noopCachedTaskHits++;
1691
- return {};
1950
+ });
1951
+ }
1952
+ async getRun(runId, options) {
1953
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1954
+ __privateGet(this, _logger).debug("Getting Run", {
1955
+ runId
1956
+ });
1957
+ return await zodfetch(import_core3.GetRunSchema, (0, import_core3.urlWithSearchParams)(`${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}`, options), {
1958
+ method: "GET",
1959
+ headers: {
1960
+ Authorization: `Bearer ${apiKey}`
1692
1961
  }
1693
- }
1694
- const runOptions = {
1695
- ...options ?? {},
1696
- parseOutput: void 0
1697
- };
1698
- const response = await this._apiClient.runTask(this._id, {
1699
- idempotencyKey,
1700
- displayKey: typeof cacheKey === "string" ? cacheKey : void 0,
1701
- noop: false,
1702
- ...runOptions ?? {},
1703
- parentId
1704
- }, {
1705
- cachedTasksCursor: this._cachedTasksCursor
1706
1962
  });
1707
- const task = response.version === import_core4.API_VERSIONS.LAZY_LOADED_CACHED_TASKS ? response.body.task : response.body;
1708
- if (task.forceYield) {
1709
- this._logger.debug("Forcing yield after run task", {
1710
- idempotencyKey
1711
- });
1712
- __privateMethod(this, _forceYield, forceYield_fn).call(this, "after_run_task");
1713
- }
1714
- if (response.version === import_core4.API_VERSIONS.LAZY_LOADED_CACHED_TASKS) {
1715
- this._cachedTasksCursor = response.body.cachedTasks?.cursor;
1716
- for (const cachedTask2 of response.body.cachedTasks?.tasks ?? []) {
1717
- if (!this._cachedTasks.has(cachedTask2.idempotencyKey)) {
1718
- this._cachedTasks.set(cachedTask2.idempotencyKey, cachedTask2);
1719
- this._logger.debug("Injecting lazy loaded task into task cache", {
1720
- idempotencyKey: cachedTask2.idempotencyKey
1721
- });
1722
- this._stats.lazyLoadedCachedTasks++;
1723
- }
1963
+ }
1964
+ async cancelRun(runId) {
1965
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1966
+ __privateGet(this, _logger).debug("Cancelling Run", {
1967
+ runId
1968
+ });
1969
+ return await zodfetch(import_core3.GetRunSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/cancel`, {
1970
+ method: "POST",
1971
+ headers: {
1972
+ "Content-Type": "application/json",
1973
+ Authorization: `Bearer ${apiKey}`
1724
1974
  }
1725
- }
1726
- if (task.status === "CANCELED") {
1727
- this._logger.debug("Task canceled", {
1728
- idempotencyKey,
1729
- task
1730
- });
1731
- throw new CanceledWithTaskError(task);
1732
- }
1733
- if (task.status === "COMPLETED") {
1734
- if (task.noop) {
1735
- this._logger.debug("Noop Task completed", {
1736
- idempotencyKey
1737
- });
1738
- this._noopTasksBloomFilter?.add(task.idempotencyKey);
1739
- } else {
1740
- this._logger.debug("Cache miss", {
1741
- idempotencyKey
1742
- });
1743
- this._stats.cachedTaskMisses++;
1744
- __privateMethod(this, _addToCachedTasks, addToCachedTasks_fn).call(this, task);
1975
+ });
1976
+ }
1977
+ async getRunStatuses(runId) {
1978
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1979
+ __privateGet(this, _logger).debug("Getting Run statuses", {
1980
+ runId
1981
+ });
1982
+ return await zodfetch(import_core3.GetRunStatusesSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/statuses`, {
1983
+ method: "GET",
1984
+ headers: {
1985
+ Authorization: `Bearer ${apiKey}`
1745
1986
  }
1746
- return options?.parseOutput ? options.parseOutput(task.output) : task.output;
1747
- }
1748
- if (task.status === "ERRORED") {
1749
- this._logger.debug("Task errored", {
1750
- idempotencyKey,
1751
- task
1752
- });
1753
- throw new ErrorWithTask(task, task.error ?? task?.output ? JSON.stringify(task.output) : "Task errored");
1754
- }
1755
- __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "before_execute_task", 1500);
1756
- const executeTask = /* @__PURE__ */ __name(async () => {
1757
- try {
1758
- const result = await callback(task, this);
1759
- if (task.status === "WAITING" && task.callbackUrl) {
1760
- this._logger.debug("Waiting for remote callback", {
1761
- idempotencyKey,
1762
- task
1763
- });
1764
- return {};
1765
- }
1766
- const output = this._outputSerializer.serialize(result);
1767
- this._logger.debug("Completing using output", {
1768
- idempotencyKey,
1769
- task
1770
- });
1771
- __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "before_complete_task", 500, task, output);
1772
- const completedTask = await this._apiClient.completeTask(this._id, task.id, {
1773
- output,
1774
- properties: task.outputProperties ?? void 0
1775
- });
1776
- if (completedTask.forceYield) {
1777
- this._logger.debug("Forcing yield after task completed", {
1778
- idempotencyKey
1779
- });
1780
- __privateMethod(this, _forceYield, forceYield_fn).call(this, "after_complete_task");
1781
- }
1782
- this._stats.executedTasks++;
1783
- if (completedTask.status === "CANCELED") {
1784
- throw new CanceledWithTaskError(completedTask);
1785
- }
1786
- __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "after_complete_task", 500);
1787
- const deserializedOutput = this._outputSerializer.deserialize(output);
1788
- return options?.parseOutput ? options.parseOutput(deserializedOutput) : deserializedOutput;
1789
- } catch (error) {
1790
- if (isTriggerError(error)) {
1791
- throw error;
1792
- }
1793
- let skipRetrying = false;
1794
- if (onError) {
1795
- try {
1796
- const onErrorResult = onError(error, task, this);
1797
- if (onErrorResult) {
1798
- if (onErrorResult instanceof Error) {
1799
- error = onErrorResult;
1800
- } else {
1801
- skipRetrying = !!onErrorResult.skipRetrying;
1802
- if (onErrorResult.retryAt && !skipRetrying) {
1803
- const parsedError2 = import_core4.ErrorWithStackSchema.safeParse(onErrorResult.error);
1804
- throw new RetryWithTaskError(parsedError2.success ? parsedError2.data : {
1805
- message: "Unknown error"
1806
- }, task, onErrorResult.retryAt);
1807
- }
1808
- }
1809
- }
1810
- } catch (innerError) {
1811
- if (isTriggerError(innerError)) {
1812
- throw innerError;
1813
- }
1814
- error = innerError;
1815
- }
1816
- }
1817
- if (error instanceof ErrorWithTask) {
1818
- await this._apiClient.failTask(this._id, task.id, {
1819
- error: error.cause.output
1820
- });
1821
- }
1822
- const parsedError = import_core4.ErrorWithStackSchema.safeParse(error);
1823
- if (options?.retry && !skipRetrying) {
1824
- const retryAt = (0, import_core3.calculateRetryAt)(options.retry, task.attempts - 1);
1825
- if (retryAt) {
1826
- throw new RetryWithTaskError(parsedError.success ? parsedError.data : {
1827
- message: "Unknown error"
1828
- }, task, retryAt);
1829
- }
1830
- }
1831
- if (parsedError.success) {
1832
- await this._apiClient.failTask(this._id, task.id, {
1833
- error: parsedError.data
1834
- });
1835
- } else {
1836
- const message = typeof error === "string" ? error : JSON.stringify(error);
1837
- await this._apiClient.failTask(this._id, task.id, {
1838
- error: {
1839
- name: "Unknown error",
1840
- message
1841
- }
1842
- });
1843
- }
1844
- throw error;
1987
+ });
1988
+ }
1989
+ async getRuns(jobSlug, options) {
1990
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1991
+ __privateGet(this, _logger).debug("Getting Runs", {
1992
+ jobSlug
1993
+ });
1994
+ return await zodfetch(import_core3.GetRunsSchema, (0, import_core3.urlWithSearchParams)(`${__privateGet(this, _apiUrl)}/api/v1/jobs/${jobSlug}/runs`, options), {
1995
+ method: "GET",
1996
+ headers: {
1997
+ Authorization: `Bearer ${apiKey}`
1845
1998
  }
1846
- }, "executeTask");
1847
- if (task.status === "WAITING") {
1848
- this._logger.debug("Task waiting", {
1849
- idempotencyKey,
1850
- task
1851
- });
1852
- if (task.callbackUrl) {
1853
- await this._taskStorage.run({
1854
- taskId: task.id
1855
- }, executeTask);
1999
+ });
2000
+ }
2001
+ async invokeJob(jobId, payload, options = {}) {
2002
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2003
+ __privateGet(this, _logger).debug("Invoking Job", {
2004
+ jobId
2005
+ });
2006
+ const body = {
2007
+ payload,
2008
+ context: options.context ?? {},
2009
+ options: {
2010
+ accountId: options.accountId,
2011
+ callbackUrl: options.callbackUrl
1856
2012
  }
1857
- throw new ResumeWithTaskError(task);
1858
- }
1859
- if (task.status === "RUNNING" && typeof task.operation === "string") {
1860
- this._logger.debug("Task running operation", {
1861
- idempotencyKey,
1862
- task
1863
- });
1864
- throw new ResumeWithTaskError(task);
1865
- }
1866
- return this._taskStorage.run({
1867
- taskId: task.id
1868
- }, executeTask);
2013
+ };
2014
+ return await zodfetch(import_core3.InvokeJobResponseSchema, `${__privateGet(this, _apiUrl)}/api/v1/jobs/${jobId}/invoke`, {
2015
+ method: "POST",
2016
+ headers: {
2017
+ "Content-Type": "application/json",
2018
+ Authorization: `Bearer ${apiKey}`,
2019
+ ...options.idempotencyKey ? {
2020
+ "Idempotency-Key": options.idempotencyKey
2021
+ } : {}
2022
+ },
2023
+ body: JSON.stringify(body)
2024
+ });
1869
2025
  }
1870
- yield(cacheKey) {
1871
- if (!(0, import_core4.supportsFeature)("yieldExecution", this._serverVersion)) {
1872
- console.warn("[trigger.dev] io.yield() is not support by the version of the Trigger.dev server you are using, you will need to upgrade your self-hosted Trigger.dev instance.");
1873
- return;
2026
+ async createEphemeralEventDispatcher(payload) {
2027
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2028
+ __privateGet(this, _logger).debug("Creating ephemeral event dispatcher", {
2029
+ payload
2030
+ });
2031
+ const response = await zodfetch(import_core3.EphemeralEventDispatcherResponseBodySchema, `${__privateGet(this, _apiUrl)}/api/v1/event-dispatchers/ephemeral`, {
2032
+ method: "POST",
2033
+ headers: {
2034
+ "Content-Type": "application/json",
2035
+ Authorization: `Bearer ${apiKey}`
2036
+ },
2037
+ body: JSON.stringify(payload)
2038
+ });
2039
+ return response;
2040
+ }
2041
+ get store() {
2042
+ return __privateGet(this, _storeClient);
2043
+ }
2044
+ };
2045
+ __name(ApiClient, "ApiClient");
2046
+ _apiUrl = new WeakMap();
2047
+ _options = new WeakMap();
2048
+ _logger = new WeakMap();
2049
+ _storeClient = new WeakMap();
2050
+ _queryKeyValueStore = new WeakSet();
2051
+ queryKeyValueStore_fn = /* @__PURE__ */ __name(async function(action, data) {
2052
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2053
+ __privateGet(this, _logger).debug("accessing key-value store", {
2054
+ action,
2055
+ data
2056
+ });
2057
+ const STORE_URL = `${__privateGet(this, _apiUrl)}/api/v1/store/${data.key}`;
2058
+ const authHeader = {
2059
+ Authorization: `Bearer ${apiKey}`
2060
+ };
2061
+ let requestInit;
2062
+ switch (action) {
2063
+ case "DELETE": {
2064
+ requestInit = {
2065
+ method: "DELETE",
2066
+ headers: authHeader
2067
+ };
2068
+ break;
2069
+ }
2070
+ case "GET": {
2071
+ requestInit = {
2072
+ method: "GET",
2073
+ headers: authHeader
2074
+ };
2075
+ break;
1874
2076
  }
1875
- if (this._yieldedExecutions.includes(cacheKey)) {
1876
- return;
2077
+ case "HAS": {
2078
+ const headResponse = await fetchHead(STORE_URL, {
2079
+ headers: authHeader
2080
+ });
2081
+ return {
2082
+ action: "HAS",
2083
+ key: data.key,
2084
+ has: !!headResponse.ok
2085
+ };
1877
2086
  }
1878
- throw new YieldExecutionError(cacheKey);
1879
- }
1880
- async try(tryCallback, catchCallback) {
1881
- try {
1882
- return await tryCallback();
1883
- } catch (error) {
1884
- if (isTriggerError(error)) {
1885
- throw error;
2087
+ case "SET": {
2088
+ const MAX_BODY_BYTE_LENGTH = 256 * 1024;
2089
+ if ((data.value?.length ?? 0) > MAX_BODY_BYTE_LENGTH) {
2090
+ throw new Error(`Max request body size exceeded: ${MAX_BODY_BYTE_LENGTH} bytes`);
1886
2091
  }
1887
- return await catchCallback(error);
2092
+ requestInit = {
2093
+ method: "PUT",
2094
+ headers: {
2095
+ ...authHeader,
2096
+ "Content-Type": "text/plain"
2097
+ },
2098
+ body: data.value
2099
+ };
2100
+ break;
1888
2101
  }
1889
- }
1890
- };
1891
- __name(IO, "IO");
1892
- _addToCachedTasks = new WeakSet();
1893
- addToCachedTasks_fn = /* @__PURE__ */ __name(function(task) {
1894
- this._cachedTasks.set(task.idempotencyKey, task);
1895
- }, "#addToCachedTasks");
1896
- _detectAutoYield = new WeakSet();
1897
- detectAutoYield_fn = /* @__PURE__ */ __name(function(location, threshold = 1500, task1, output) {
1898
- const timeRemaining = __privateMethod(this, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn).call(this);
1899
- if (timeRemaining && timeRemaining < threshold) {
1900
- if (task1) {
1901
- throw new AutoYieldWithCompletedTaskExecutionError(task1.id, task1.outputProperties ?? [], {
1902
- location,
1903
- timeRemaining,
1904
- timeElapsed: __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this)
1905
- }, output);
1906
- } else {
1907
- throw new AutoYieldExecutionError(location, timeRemaining, __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this));
2102
+ default: {
2103
+ (0, import_core3.assertExhaustive)(action);
1908
2104
  }
1909
2105
  }
1910
- }, "#detectAutoYield");
1911
- _forceYield = new WeakSet();
1912
- forceYield_fn = /* @__PURE__ */ __name(function(location1) {
1913
- const timeRemaining = __privateMethod(this, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn).call(this);
1914
- if (timeRemaining) {
1915
- throw new AutoYieldExecutionError(location1, timeRemaining, __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this));
2106
+ const response = await zodfetch(import_core3.KeyValueStoreResponseBodySchema, STORE_URL, requestInit);
2107
+ return response;
2108
+ }, "#queryKeyValueStore");
2109
+ _apiKey = new WeakSet();
2110
+ apiKey_fn = /* @__PURE__ */ __name(async function() {
2111
+ const apiKey = getApiKey(__privateGet(this, _options).apiKey);
2112
+ if (apiKey.status === "invalid") {
2113
+ throw new Error("Invalid API key");
2114
+ } else if (apiKey.status === "missing") {
2115
+ throw new Error("Missing API key");
1916
2116
  }
1917
- }, "#forceYield");
1918
- _getTimeElapsed = new WeakSet();
1919
- getTimeElapsed_fn = /* @__PURE__ */ __name(function() {
1920
- return performance.now() - this._timeOrigin;
1921
- }, "#getTimeElapsed");
1922
- _getRemainingTimeInMillis = new WeakSet();
1923
- getRemainingTimeInMillis_fn = /* @__PURE__ */ __name(function() {
1924
- if (this._executionTimeout) {
1925
- return this._executionTimeout - (performance.now() - this._timeOrigin);
2117
+ return apiKey.apiKey;
2118
+ }, "#apiKey");
2119
+ function getApiKey(key) {
2120
+ const apiKey = key ?? process.env.TRIGGER_API_KEY;
2121
+ if (!apiKey) {
2122
+ return {
2123
+ status: "missing"
2124
+ };
1926
2125
  }
1927
- return void 0;
1928
- }, "#getRemainingTimeInMillis");
1929
- async function generateIdempotencyKey(keyMaterial) {
1930
- const keys = keyMaterial.map((key2) => {
1931
- if (typeof key2 === "string") {
1932
- return key2;
1933
- }
1934
- return stableStringify(key2);
2126
+ const isValid = apiKey.match(/^tr_[a-z]+_[a-zA-Z0-9]+$/);
2127
+ if (!isValid) {
2128
+ return {
2129
+ status: "invalid",
2130
+ apiKey
2131
+ };
2132
+ }
2133
+ return {
2134
+ status: "valid",
2135
+ apiKey
2136
+ };
2137
+ }
2138
+ __name(getApiKey, "getApiKey");
2139
+ async function zodfetchWithVersions(versionedSchemaMap, unversionedSchema, url, requestInit, options, retryCount = 0) {
2140
+ const response = await fetch(url, {
2141
+ ...requestInit,
2142
+ cache: "no-cache"
1935
2143
  });
1936
- const key = keys.join(":");
1937
- const hash = await import_node_crypto.webcrypto.subtle.digest("SHA-256", Buffer.from(key));
1938
- return Buffer.from(hash).toString("hex");
2144
+ if ((!requestInit || requestInit.method === "GET") && response.status === 404 && options?.optional) {
2145
+ return;
2146
+ }
2147
+ if (response.status >= 400 && response.status < 500) {
2148
+ const body = await response.json();
2149
+ throw new Error(body.error);
2150
+ }
2151
+ if (response.status >= 500 && retryCount < 6) {
2152
+ const delay = exponentialBackoff(retryCount + 1, 2, 50, 1150, 50);
2153
+ await new Promise((resolve) => setTimeout(resolve, delay));
2154
+ return zodfetchWithVersions(versionedSchemaMap, unversionedSchema, url, requestInit, options, retryCount + 1);
2155
+ }
2156
+ if (response.status !== 200) {
2157
+ throw new Error(options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`);
2158
+ }
2159
+ const jsonBody = await response.json();
2160
+ const version2 = response.headers.get("trigger-version");
2161
+ if (!version2) {
2162
+ return {
2163
+ version: "unversioned",
2164
+ body: unversionedSchema.parse(jsonBody)
2165
+ };
2166
+ }
2167
+ const versionedSchema = versionedSchemaMap[version2];
2168
+ if (!versionedSchema) {
2169
+ throw new Error(`Unknown version ${version2}`);
2170
+ }
2171
+ return {
2172
+ version: version2,
2173
+ body: versionedSchema.parse(jsonBody)
2174
+ };
1939
2175
  }
1940
- __name(generateIdempotencyKey, "generateIdempotencyKey");
1941
- function stableStringify(obj) {
1942
- function sortKeys(obj2) {
1943
- if (typeof obj2 !== "object" || obj2 === null) {
1944
- return obj2;
1945
- }
1946
- if (Array.isArray(obj2)) {
1947
- return obj2.map(sortKeys);
1948
- }
1949
- const sortedKeys = Object.keys(obj2).sort();
1950
- const sortedObj2 = {};
1951
- for (const key of sortedKeys) {
1952
- sortedObj2[key] = sortKeys(obj2[key]);
1953
- }
1954
- return sortedObj2;
2176
+ __name(zodfetchWithVersions, "zodfetchWithVersions");
2177
+ async function fetchHead(url, requestInitWithoutMethod, retryCount = 0) {
2178
+ const requestInit = {
2179
+ ...requestInitWithoutMethod,
2180
+ method: "HEAD"
2181
+ };
2182
+ const response = await fetch(url, {
2183
+ ...requestInit,
2184
+ cache: "no-cache"
2185
+ });
2186
+ if (response.status >= 500 && retryCount < 6) {
2187
+ const delay = exponentialBackoff(retryCount + 1, 2, 50, 1150, 50);
2188
+ await new Promise((resolve) => setTimeout(resolve, delay));
2189
+ return fetchHead(url, requestInitWithoutMethod, retryCount + 1);
1955
2190
  }
1956
- __name(sortKeys, "sortKeys");
1957
- const sortedObj = sortKeys(obj);
1958
- return JSON.stringify(sortedObj);
2191
+ return response;
1959
2192
  }
1960
- __name(stableStringify, "stableStringify");
1961
- var IOLogger = class {
1962
- constructor(callback) {
1963
- this.callback = callback;
2193
+ __name(fetchHead, "fetchHead");
2194
+ async function zodfetch(schema, url, requestInit, options, retryCount = 0) {
2195
+ const response = await fetch(url, {
2196
+ ...requestInit,
2197
+ cache: "no-cache"
2198
+ });
2199
+ if ((!requestInit || requestInit.method === "GET") && response.status === 404 && options?.optional) {
2200
+ return;
1964
2201
  }
1965
- log(message, properties) {
1966
- return this.callback("LOG", message, properties);
2202
+ if (response.status >= 400 && response.status < 500) {
2203
+ const body = await response.json();
2204
+ throw new Error(body.error);
2205
+ }
2206
+ if (response.status >= 500 && retryCount < 6) {
2207
+ const delay = exponentialBackoff(retryCount + 1, 2, 50, 1150, 50);
2208
+ await new Promise((resolve) => setTimeout(resolve, delay));
2209
+ return zodfetch(schema, url, requestInit, options, retryCount + 1);
2210
+ }
2211
+ if (response.status !== 200) {
2212
+ throw new Error(options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`);
2213
+ }
2214
+ const jsonBody = await response.json();
2215
+ return schema.parse(jsonBody);
2216
+ }
2217
+ __name(zodfetch, "zodfetch");
2218
+ function exponentialBackoff(retryCount, exponential, minDelay, maxDelay, jitter) {
2219
+ const delay = Math.min(Math.pow(exponential, retryCount) * minDelay, maxDelay);
2220
+ const jitterValue = Math.random() * jitter;
2221
+ return delay + jitterValue;
2222
+ }
2223
+ __name(exponentialBackoff, "exponentialBackoff");
2224
+
2225
+ // src/httpEndpoint.ts
2226
+ var import_core4 = require("@trigger.dev/core");
2227
+
2228
+ // src/utils/formatSchemaErrors.ts
2229
+ function formatSchemaErrors(errors) {
2230
+ return errors.map((error) => {
2231
+ const { path, message } = error;
2232
+ return {
2233
+ path: path.map(String),
2234
+ message
2235
+ };
2236
+ });
2237
+ }
2238
+ __name(formatSchemaErrors, "formatSchemaErrors");
2239
+
2240
+ // src/httpEndpoint.ts
2241
+ var HttpEndpoint = class {
2242
+ constructor(options) {
2243
+ this.options = options;
2244
+ }
2245
+ get id() {
2246
+ return this.options.id;
2247
+ }
2248
+ onRequest(options) {
2249
+ return new HttpTrigger({
2250
+ endpointId: this.id,
2251
+ event: this.options.event,
2252
+ filter: options?.filter,
2253
+ verify: this.options.verify
2254
+ });
2255
+ }
2256
+ async handleRequest(request) {
2257
+ if (!this.options.respondWith)
2258
+ return;
2259
+ return this.options.respondWith.handler(request, () => {
2260
+ const clonedRequest = request.clone();
2261
+ return this.options.verify(clonedRequest);
2262
+ });
2263
+ }
2264
+ toJSON() {
2265
+ return {
2266
+ id: this.id,
2267
+ icon: this.options.event.icon,
2268
+ version: "1",
2269
+ enabled: this.options.enabled ?? true,
2270
+ event: this.options.event,
2271
+ immediateResponseFilter: this.options.respondWith?.filter,
2272
+ skipTriggeringRuns: this.options.respondWith?.skipTriggeringRuns,
2273
+ source: this.options.event.source
2274
+ };
2275
+ }
2276
+ };
2277
+ __name(HttpEndpoint, "HttpEndpoint");
2278
+ var HttpTrigger = /* @__PURE__ */ __name(class HttpTrigger2 {
2279
+ constructor(options) {
2280
+ this.options = options;
2281
+ }
2282
+ toJSON() {
2283
+ return {
2284
+ type: "static",
2285
+ title: this.options.endpointId,
2286
+ properties: this.options.event.properties,
2287
+ rule: {
2288
+ event: `httpendpoint.${this.options.endpointId}`,
2289
+ payload: this.options.filter ?? {},
2290
+ source: this.options.event.source
2291
+ },
2292
+ link: `http-endpoints/${this.options.endpointId}`,
2293
+ help: {
2294
+ noRuns: {
2295
+ text: "To start triggering runs click here to setup your HTTP Endpoint with the external API service you want to receive webhooks from.",
2296
+ link: `http-endpoints/${this.options.endpointId}`
2297
+ }
2298
+ }
2299
+ };
1967
2300
  }
1968
- debug(message, properties) {
1969
- return this.callback("DEBUG", message, properties);
2301
+ get event() {
2302
+ return this.options.event;
1970
2303
  }
1971
- info(message, properties) {
1972
- return this.callback("INFO", message, properties);
2304
+ attachToJob(triggerClient, job) {
1973
2305
  }
1974
- warn(message, properties) {
1975
- return this.callback("WARN", message, properties);
2306
+ get preprocessRuns() {
2307
+ return false;
1976
2308
  }
1977
- error(message, properties) {
1978
- return this.callback("ERROR", message, properties);
2309
+ async verifyPayload(payload) {
2310
+ const clonedRequest = payload.clone();
2311
+ return this.options.verify(clonedRequest);
1979
2312
  }
1980
- };
1981
- __name(IOLogger, "IOLogger");
1982
- async function spaceOut(callback, index, delay) {
1983
- await new Promise((resolve) => setTimeout(resolve, index * delay));
1984
- return await callback();
1985
- }
1986
- __name(spaceOut, "spaceOut");
1987
- function sendEventOptionsProperties(options) {
1988
- return [
1989
- ...options?.accountId ? [
1990
- {
1991
- label: "Account ID",
1992
- text: options.accountId
1993
- }
1994
- ] : [],
1995
- ...options?.deliverAfter ? [
1996
- {
1997
- label: "Deliver After",
1998
- text: `${options.deliverAfter}s`
1999
- }
2000
- ] : [],
2001
- ...options?.deliverAt ? [
2002
- {
2003
- label: "Deliver At",
2004
- text: options.deliverAt.toISOString()
2313
+ }, "HttpTrigger");
2314
+ function httpEndpoint(options) {
2315
+ const id = slugifyId(options.id);
2316
+ return new HttpEndpoint({
2317
+ id,
2318
+ enabled: options.enabled,
2319
+ respondWith: options.respondWith,
2320
+ verify: options.verify,
2321
+ event: {
2322
+ name: id,
2323
+ title: options.title ?? "HTTP Trigger",
2324
+ source: options.source,
2325
+ icon: options.icon ?? "webhook",
2326
+ properties: options.properties,
2327
+ examples: options.examples ? options.examples : [
2328
+ {
2329
+ id: "basic-request",
2330
+ name: "Basic Request",
2331
+ icon: "http-post",
2332
+ payload: {
2333
+ url: "https://cloud.trigger.dev",
2334
+ method: "POST",
2335
+ headers: {
2336
+ "Content-Type": "application/json"
2337
+ },
2338
+ rawBody: JSON.stringify({
2339
+ foo: "bar"
2340
+ })
2341
+ }
2342
+ }
2343
+ ],
2344
+ parsePayload: (rawPayload) => {
2345
+ const result = import_core4.RequestWithRawBodySchema.safeParse(rawPayload);
2346
+ if (!result.success) {
2347
+ throw new ParsedPayloadSchemaError(formatSchemaErrors(result.error.issues));
2348
+ }
2349
+ return new Request(new URL(result.data.url), {
2350
+ method: result.data.method,
2351
+ headers: result.data.headers,
2352
+ body: result.data.rawBody
2353
+ });
2005
2354
  }
2006
- ] : []
2007
- ];
2355
+ }
2356
+ });
2008
2357
  }
2009
- __name(sendEventOptionsProperties, "sendEventOptionsProperties");
2358
+ __name(httpEndpoint, "httpEndpoint");
2010
2359
 
2011
2360
  // src/ioWithIntegrations.ts
2012
2361
  function createIOWithIntegrations(io, auths, integrations) {
@@ -2158,6 +2507,12 @@ var EventTrigger = class {
2158
2507
  return false;
2159
2508
  }
2160
2509
  async verifyPayload(payload) {
2510
+ if (__privateGet(this, _options3).verify) {
2511
+ if (payload instanceof Request) {
2512
+ const clonedRequest = payload.clone();
2513
+ return __privateGet(this, _options3).verify(clonedRequest);
2514
+ }
2515
+ }
2161
2516
  return {
2162
2517
  success: true
2163
2518
  };
@@ -2401,9 +2756,16 @@ __name(DynamicSchedule, "DynamicSchedule");
2401
2756
  var import_node_events = __toESM(require("events"));
2402
2757
 
2403
2758
  // package.json
2404
- var version = "2.2.7";
2759
+ var version = "2.2.8";
2405
2760
 
2406
2761
  // src/triggerClient.ts
2762
+ var registerWebhookEvent = /* @__PURE__ */ __name((key) => ({
2763
+ name: `${import_core8.REGISTER_WEBHOOK}.${key}`,
2764
+ title: "Register Webhook",
2765
+ source: "internal",
2766
+ icon: "webhook",
2767
+ parsePayload: import_core8.RegisterWebhookPayloadSchema.parse
2768
+ }), "registerWebhookEvent");
2407
2769
  var registerSourceEvent = {
2408
2770
  name: import_core8.REGISTER_SOURCE_EVENT_V2,
2409
2771
  title: "Register Source",
@@ -2411,7 +2773,7 @@ var registerSourceEvent = {
2411
2773
  icon: "register-source",
2412
2774
  parsePayload: import_core8.RegisterSourceEventSchemaV2.parse
2413
2775
  };
2414
- var _options4, _registeredJobs, _registeredSources, _registeredHttpSourceHandlers, _registeredDynamicTriggers, _jobMetadataByDynamicTriggers, _registeredSchedules, _registeredHttpEndpoints, _authResolvers, _eventEmitter, _client2, _internalLogger, _preprocessRun, preprocessRun_fn, _executeJob, executeJob_fn, _convertErrorToExecutionResponse, convertErrorToExecutionResponse_fn, _createRunContext, createRunContext_fn, _createPreprocessRunContext, createPreprocessRunContext_fn, _handleHttpSourceRequest, handleHttpSourceRequest_fn, _handleHttpEndpointRequestForResponse, handleHttpEndpointRequestForResponse_fn, _resolveConnections, resolveConnections_fn, _resolveConnection, resolveConnection_fn, _buildJobsIndex, buildJobsIndex_fn, _buildJobIndex, buildJobIndex_fn, _buildJobIntegrations, buildJobIntegrations_fn, _buildJobIntegration, buildJobIntegration_fn, _logIOStats, logIOStats_fn, _standardResponseHeaders, standardResponseHeaders_fn, _serializeRunMetadata, serializeRunMetadata_fn, _deliverSuccessfulRunNotification, deliverSuccessfulRunNotification_fn, _deliverFailedRunNotification, deliverFailedRunNotification_fn;
2776
+ 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;
2415
2777
  var TriggerClient = class {
2416
2778
  constructor(options) {
2417
2779
  __privateAdd(this, _preprocessRun);
@@ -2421,6 +2783,7 @@ var TriggerClient = class {
2421
2783
  __privateAdd(this, _createPreprocessRunContext);
2422
2784
  __privateAdd(this, _handleHttpSourceRequest);
2423
2785
  __privateAdd(this, _handleHttpEndpointRequestForResponse);
2786
+ __privateAdd(this, _handleWebhookRequest);
2424
2787
  __privateAdd(this, _resolveConnections);
2425
2788
  __privateAdd(this, _resolveConnection);
2426
2789
  __privateAdd(this, _buildJobsIndex);
@@ -2435,12 +2798,15 @@ var TriggerClient = class {
2435
2798
  __privateAdd(this, _options4, void 0);
2436
2799
  __privateAdd(this, _registeredJobs, {});
2437
2800
  __privateAdd(this, _registeredSources, {});
2801
+ __privateAdd(this, _registeredWebhooks, {});
2438
2802
  __privateAdd(this, _registeredHttpSourceHandlers, {});
2803
+ __privateAdd(this, _registeredWebhookSourceHandlers, {});
2439
2804
  __privateAdd(this, _registeredDynamicTriggers, {});
2440
2805
  __privateAdd(this, _jobMetadataByDynamicTriggers, {});
2441
2806
  __privateAdd(this, _registeredSchedules, {});
2442
2807
  __privateAdd(this, _registeredHttpEndpoints, {});
2443
2808
  __privateAdd(this, _authResolvers, {});
2809
+ __privateAdd(this, _envStore, void 0);
2444
2810
  __privateAdd(this, _eventEmitter, new import_node_events.default());
2445
2811
  __privateAdd(this, _client2, void 0);
2446
2812
  __privateAdd(this, _internalLogger, void 0);
@@ -2452,6 +2818,7 @@ var TriggerClient = class {
2452
2818
  "output",
2453
2819
  "noopTasksSet"
2454
2820
  ]));
2821
+ __privateSet(this, _envStore, new KeyValueStore(__privateGet(this, _client2)));
2455
2822
  }
2456
2823
  async handleRequest(request, timeOrigin = performance.now()) {
2457
2824
  __privateGet(this, _internalLogger).debug("handling request", {
@@ -2548,6 +2915,7 @@ var TriggerClient = class {
2548
2915
  const body = {
2549
2916
  jobs: __privateMethod(this, _buildJobsIndex, buildJobsIndex_fn).call(this),
2550
2917
  sources: Object.values(__privateGet(this, _registeredSources)),
2918
+ webhooks: Object.values(__privateGet(this, _registeredWebhooks)),
2551
2919
  dynamicTriggers: Object.values(__privateGet(this, _registeredDynamicTriggers)).map((trigger) => ({
2552
2920
  id: trigger.id,
2553
2921
  jobs: __privateGet(this, _jobMetadataByDynamicTriggers)[trigger.id] ?? [],
@@ -2742,6 +3110,48 @@ var TriggerClient = class {
2742
3110
  headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
2743
3111
  };
2744
3112
  }
3113
+ case "DELIVER_WEBHOOK_REQUEST": {
3114
+ const headers = import_core8.WebhookSourceRequestHeadersSchema.safeParse(Object.fromEntries(request.headers.entries()));
3115
+ if (!headers.success) {
3116
+ return {
3117
+ status: 400,
3118
+ body: {
3119
+ message: "Invalid headers"
3120
+ }
3121
+ };
3122
+ }
3123
+ const sourceRequestNeedsBody = headers.data["x-ts-http-method"] !== "GET";
3124
+ const sourceRequestInit = {
3125
+ method: headers.data["x-ts-http-method"],
3126
+ headers: headers.data["x-ts-http-headers"],
3127
+ body: sourceRequestNeedsBody ? request.body : void 0
3128
+ };
3129
+ if (sourceRequestNeedsBody) {
3130
+ try {
3131
+ sourceRequestInit.duplex = "half";
3132
+ } catch (error2) {
3133
+ }
3134
+ }
3135
+ const webhookRequest = new Request(headers.data["x-ts-http-url"], sourceRequestInit);
3136
+ const key = headers.data["x-ts-key"];
3137
+ const secret = headers.data["x-ts-secret"];
3138
+ const params = headers.data["x-ts-params"];
3139
+ const ctx = {
3140
+ key,
3141
+ secret,
3142
+ params
3143
+ };
3144
+ const { response, verified, error } = await __privateMethod(this, _handleWebhookRequest, handleWebhookRequest_fn).call(this, webhookRequest, ctx);
3145
+ return {
3146
+ status: 200,
3147
+ body: {
3148
+ response,
3149
+ verified,
3150
+ error
3151
+ },
3152
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3153
+ };
3154
+ }
2745
3155
  case "VALIDATE": {
2746
3156
  return {
2747
3157
  status: 200,
@@ -2806,9 +3216,9 @@ var TriggerClient = class {
2806
3216
  defineDynamicTrigger(options) {
2807
3217
  return new DynamicTrigger(this, options);
2808
3218
  }
2809
- defineHttpEndpoint(options) {
3219
+ defineHttpEndpoint(options, suppressWarnings = false) {
2810
3220
  const existingHttpEndpoint = __privateGet(this, _registeredHttpEndpoints)[options.id];
2811
- if (existingHttpEndpoint) {
3221
+ if (!suppressWarnings && existingHttpEndpoint) {
2812
3222
  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.`));
2813
3223
  }
2814
3224
  const endpoint = httpEndpoint(options);
@@ -2929,6 +3339,94 @@ var TriggerClient = class {
2929
3339
  });
2930
3340
  __privateGet(this, _registeredSchedules)[key] = jobs;
2931
3341
  }
3342
+ attachWebhook(options) {
3343
+ const { source } = options;
3344
+ __privateGet(this, _registeredWebhookSourceHandlers)[options.key] = {
3345
+ verify: source.verify.bind(source),
3346
+ generateEvents: source.generateEvents.bind(source)
3347
+ };
3348
+ let registeredWebhook = __privateGet(this, _registeredWebhooks)[options.key];
3349
+ if (!registeredWebhook) {
3350
+ registeredWebhook = {
3351
+ key: options.key,
3352
+ params: options.params,
3353
+ config: options.config,
3354
+ integration: {
3355
+ id: source.integration.id,
3356
+ metadata: source.integration.metadata,
3357
+ authSource: source.integration.authSource
3358
+ },
3359
+ httpEndpoint: {
3360
+ id: options.key
3361
+ }
3362
+ };
3363
+ } else {
3364
+ registeredWebhook.config = deepMergeOptions(registeredWebhook.config, options.config);
3365
+ }
3366
+ __privateGet(this, _registeredWebhooks)[options.key] = registeredWebhook;
3367
+ new Job(this, {
3368
+ id: `webhook.register.${options.key}`,
3369
+ name: `webhook.register.${options.key}`,
3370
+ version: source.version,
3371
+ trigger: new EventTrigger({
3372
+ event: registerWebhookEvent(options.key)
3373
+ }),
3374
+ integrations: {
3375
+ integration: source.integration
3376
+ },
3377
+ run: async (registerPayload, io, ctx) => {
3378
+ return await io.try(async () => {
3379
+ __privateGet(this, _internalLogger).debug("[webhook.register] Start");
3380
+ const crudOptions = {
3381
+ io,
3382
+ ctx: registerPayload
3383
+ };
3384
+ if (!registerPayload.active) {
3385
+ __privateGet(this, _internalLogger).debug("[webhook.register] Not active, run create");
3386
+ await io.try(async () => {
3387
+ await source.crud.create(crudOptions);
3388
+ }, async (error) => {
3389
+ __privateGet(this, _internalLogger).debug("[webhook.register] Error during create, re-trying with delete first", {
3390
+ error
3391
+ });
3392
+ await io.runTask("create-retry", async () => {
3393
+ await source.crud.delete(crudOptions);
3394
+ await source.crud.create(crudOptions);
3395
+ });
3396
+ });
3397
+ return await io.updateWebhook("update-webhook-success", {
3398
+ key: options.key,
3399
+ active: true,
3400
+ config: registerPayload.config.desired
3401
+ });
3402
+ }
3403
+ __privateGet(this, _internalLogger).debug("[webhook.register] Already active, run update");
3404
+ if (source.crud.update) {
3405
+ await source.crud.update(crudOptions);
3406
+ } else {
3407
+ __privateGet(this, _internalLogger).debug("[webhook.register] Run delete and create instead of update");
3408
+ await source.crud.delete(crudOptions);
3409
+ await source.crud.create(crudOptions);
3410
+ }
3411
+ return await io.updateWebhook("update-webhook-success", {
3412
+ key: options.key,
3413
+ active: true,
3414
+ config: registerPayload.config.desired
3415
+ });
3416
+ }, async (error) => {
3417
+ __privateGet(this, _internalLogger).debug("[webhook.register] Error", {
3418
+ error
3419
+ });
3420
+ await io.updateWebhook("update-webhook-error", {
3421
+ key: options.key,
3422
+ active: false
3423
+ });
3424
+ throw error;
3425
+ });
3426
+ },
3427
+ __internal: true
3428
+ });
3429
+ }
2932
3430
  async registerTrigger(id, key, options, idempotencyKey) {
2933
3431
  return __privateGet(this, _client2).registerTrigger(this.id, id, key, options, idempotencyKey);
2934
3432
  }
@@ -2977,6 +3475,11 @@ var TriggerClient = class {
2977
3475
  async createEphemeralEventDispatcher(payload) {
2978
3476
  return __privateGet(this, _client2).createEphemeralEventDispatcher(payload);
2979
3477
  }
3478
+ get store() {
3479
+ return {
3480
+ env: __privateGet(this, _envStore)
3481
+ };
3482
+ }
2980
3483
  authorized(apiKey) {
2981
3484
  if (typeof apiKey !== "string") {
2982
3485
  return "missing-header";
@@ -2995,12 +3498,15 @@ __name(TriggerClient, "TriggerClient");
2995
3498
  _options4 = new WeakMap();
2996
3499
  _registeredJobs = new WeakMap();
2997
3500
  _registeredSources = new WeakMap();
3501
+ _registeredWebhooks = new WeakMap();
2998
3502
  _registeredHttpSourceHandlers = new WeakMap();
3503
+ _registeredWebhookSourceHandlers = new WeakMap();
2999
3504
  _registeredDynamicTriggers = new WeakMap();
3000
3505
  _jobMetadataByDynamicTriggers = new WeakMap();
3001
3506
  _registeredSchedules = new WeakMap();
3002
3507
  _registeredHttpEndpoints = new WeakMap();
3003
3508
  _authResolvers = new WeakMap();
3509
+ _envStore = new WeakMap();
3004
3510
  _eventEmitter = new WeakMap();
3005
3511
  _client2 = new WeakMap();
3006
3512
  _internalLogger = new WeakMap();
@@ -3025,6 +3531,7 @@ executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1, timeOrigin, t
3025
3531
  const context = __privateMethod(this, _createRunContext, createRunContext_fn).call(this, body1);
3026
3532
  const io = new IO({
3027
3533
  id: body1.run.id,
3534
+ jobId: job1.id,
3028
3535
  cachedTasks: body1.tasks,
3029
3536
  cachedTasksCursor: body1.cachedTaskCursor,
3030
3537
  yieldedExecutions: body1.yieldedExecutions ?? [],
@@ -3369,8 +3876,44 @@ handleHttpEndpointRequestForResponse_fn = /* @__PURE__ */ __name(async function(
3369
3876
  response
3370
3877
  };
3371
3878
  }, "#handleHttpEndpointRequestForResponse");
3879
+ _handleWebhookRequest = new WeakSet();
3880
+ handleWebhookRequest_fn = /* @__PURE__ */ __name(async function(request, ctx) {
3881
+ __privateGet(this, _internalLogger).debug("Handling webhook request", {
3882
+ ctx
3883
+ });
3884
+ const okResponse = {
3885
+ status: 200,
3886
+ body: {
3887
+ ok: true
3888
+ }
3889
+ };
3890
+ const handlers = __privateGet(this, _registeredWebhookSourceHandlers)[ctx.key];
3891
+ if (!handlers) {
3892
+ __privateGet(this, _internalLogger).debug("No handler registered for webhook", {
3893
+ ctx
3894
+ });
3895
+ return {
3896
+ response: okResponse,
3897
+ verified: false
3898
+ };
3899
+ }
3900
+ const { verify, generateEvents } = handlers;
3901
+ const verifyResult = await verify(request, this, ctx);
3902
+ if (!verifyResult.success) {
3903
+ return {
3904
+ response: okResponse,
3905
+ verified: false,
3906
+ error: verifyResult.reason
3907
+ };
3908
+ }
3909
+ await generateEvents(request, this, ctx);
3910
+ return {
3911
+ response: okResponse,
3912
+ verified: true
3913
+ };
3914
+ }, "#handleWebhookRequest");
3372
3915
  _resolveConnections = new WeakSet();
3373
- resolveConnections_fn = /* @__PURE__ */ __name(async function(ctx, integrations, connections) {
3916
+ resolveConnections_fn = /* @__PURE__ */ __name(async function(ctx1, integrations, connections) {
3374
3917
  if (!integrations) {
3375
3918
  return {
3376
3919
  ok: true,
@@ -3380,7 +3923,7 @@ resolveConnections_fn = /* @__PURE__ */ __name(async function(ctx, integrations,
3380
3923
  const resolvedAuthResults = await Promise.all(Object.keys(integrations).map(async (key) => {
3381
3924
  const integration = integrations[key];
3382
3925
  const auth = (connections ?? {})[key];
3383
- const result = await __privateMethod(this, _resolveConnection, resolveConnection_fn).call(this, ctx, integration, auth);
3926
+ const result = await __privateMethod(this, _resolveConnection, resolveConnection_fn).call(this, ctx1, integration, auth);
3384
3927
  if (result.ok) {
3385
3928
  return {
3386
3929
  ok: true,
@@ -3422,7 +3965,7 @@ resolveConnections_fn = /* @__PURE__ */ __name(async function(ctx, integrations,
3422
3965
  }
3423
3966
  }, "#resolveConnections");
3424
3967
  _resolveConnection = new WeakSet();
3425
- resolveConnection_fn = /* @__PURE__ */ __name(async function(ctx1, integration, auth) {
3968
+ resolveConnection_fn = /* @__PURE__ */ __name(async function(ctx2, integration, auth) {
3426
3969
  if (auth) {
3427
3970
  return {
3428
3971
  ok: true,
@@ -3443,7 +3986,7 @@ resolveConnection_fn = /* @__PURE__ */ __name(async function(ctx1, integration,
3443
3986
  };
3444
3987
  }
3445
3988
  try {
3446
- const resolvedAuth = await authResolver(ctx1, integration);
3989
+ const resolvedAuth = await authResolver(ctx2, integration);
3447
3990
  if (!resolvedAuth) {
3448
3991
  return {
3449
3992
  ok: false,
@@ -3874,9 +4417,152 @@ function invokeTrigger(options) {
3874
4417
  }
3875
4418
  __name(invokeTrigger, "invokeTrigger");
3876
4419
 
4420
+ // src/triggers/webhook.ts
4421
+ var import_core11 = require("@trigger.dev/core");
4422
+ var import_node_crypto2 = require("crypto");
4423
+ var _shortHash, shortHash_fn;
4424
+ var WebhookSource = class {
4425
+ constructor(options) {
4426
+ __privateAdd(this, _shortHash);
4427
+ this.options = options;
4428
+ }
4429
+ async generateEvents(request, client, ctx) {
4430
+ return this.options.generateEvents({
4431
+ request,
4432
+ client,
4433
+ ctx
4434
+ });
4435
+ }
4436
+ filter(params, config) {
4437
+ return this.options.filter?.(params, config) ?? {};
4438
+ }
4439
+ properties(params) {
4440
+ return this.options.properties?.(params) ?? [];
4441
+ }
4442
+ get crud() {
4443
+ return this.options.crud;
4444
+ }
4445
+ async register(params, registerEvent, io, ctx) {
4446
+ if (!this.options.register) {
4447
+ return;
4448
+ }
4449
+ const updates = await this.options.register({
4450
+ ...registerEvent,
4451
+ params
4452
+ }, io, ctx);
4453
+ return updates;
4454
+ }
4455
+ async verify(request, client, ctx) {
4456
+ if (this.options.verify) {
4457
+ const clonedRequest = request.clone();
4458
+ return this.options.verify({
4459
+ request: clonedRequest,
4460
+ client,
4461
+ ctx
4462
+ });
4463
+ }
4464
+ return {
4465
+ success: true
4466
+ };
4467
+ }
4468
+ key(params) {
4469
+ const parts = [
4470
+ "webhook"
4471
+ ];
4472
+ parts.push(this.options.key(params));
4473
+ parts.push(this.integration.id);
4474
+ return `${this.options.id}-${__privateMethod(this, _shortHash, shortHash_fn).call(this, parts.join(""))}`;
4475
+ }
4476
+ get integration() {
4477
+ return this.options.integration;
4478
+ }
4479
+ get integrationConfig() {
4480
+ return {
4481
+ id: this.integration.id,
4482
+ metadata: this.integration.metadata
4483
+ };
4484
+ }
4485
+ get id() {
4486
+ return this.options.id;
4487
+ }
4488
+ get version() {
4489
+ return this.options.version;
4490
+ }
4491
+ };
4492
+ __name(WebhookSource, "WebhookSource");
4493
+ _shortHash = new WeakSet();
4494
+ shortHash_fn = /* @__PURE__ */ __name(function(str) {
4495
+ const hash = (0, import_node_crypto2.createHash)("sha1").update(str).digest("hex");
4496
+ return hash.slice(0, 7);
4497
+ }, "#shortHash");
4498
+ var WebhookTrigger = class {
4499
+ constructor(options) {
4500
+ this.options = options;
4501
+ }
4502
+ get event() {
4503
+ return this.options.event;
4504
+ }
4505
+ get source() {
4506
+ return this.options.source;
4507
+ }
4508
+ get key() {
4509
+ return slugifyId(this.options.source.key(this.options.params));
4510
+ }
4511
+ toJSON() {
4512
+ return {
4513
+ type: "static",
4514
+ title: "Webhook",
4515
+ rule: {
4516
+ event: this.event.name,
4517
+ payload: (0, import_core11.deepMergeFilters)(this.options.source.filter(this.options.params, this.options.config), this.event.filter ?? {}),
4518
+ source: this.event.source
4519
+ },
4520
+ properties: this.options.source.properties(this.options.params),
4521
+ link: `http-endpoints/${this.key}`
4522
+ };
4523
+ }
4524
+ filter(eventFilter) {
4525
+ const { event, ...optionsWithoutEvent } = this.options;
4526
+ const { filter, ...eventWithoutFilter } = event;
4527
+ return new WebhookTrigger({
4528
+ ...optionsWithoutEvent,
4529
+ event: {
4530
+ ...eventWithoutFilter,
4531
+ filter: (0, import_core11.deepMergeFilters)(filter ?? {}, eventFilter)
4532
+ }
4533
+ });
4534
+ }
4535
+ attachToJob(triggerClient, job) {
4536
+ triggerClient.defineHttpEndpoint({
4537
+ id: this.key,
4538
+ source: "trigger.dev",
4539
+ icon: this.event.icon,
4540
+ verify: async () => ({
4541
+ success: true
4542
+ })
4543
+ }, true);
4544
+ triggerClient.attachWebhook({
4545
+ key: this.key,
4546
+ source: this.options.source,
4547
+ event: this.options.event,
4548
+ params: this.options.params,
4549
+ config: this.options.config
4550
+ });
4551
+ }
4552
+ get preprocessRuns() {
4553
+ return true;
4554
+ }
4555
+ async verifyPayload(payload) {
4556
+ return {
4557
+ success: true
4558
+ };
4559
+ }
4560
+ };
4561
+ __name(WebhookTrigger, "WebhookTrigger");
4562
+
3877
4563
  // src/security.ts
3878
4564
  var import_crypto = __toESM(require("crypto"));
3879
- async function verifyRequestSignature({ request, headerName, secret, algorithm }) {
4565
+ async function verifyRequestSignature({ request, headerName, headerEncoding = "hex", secret, algorithm }) {
3880
4566
  if (!secret) {
3881
4567
  return {
3882
4568
  success: false,
@@ -3892,7 +4578,7 @@ async function verifyRequestSignature({ request, headerName, secret, algorithm }
3892
4578
  }
3893
4579
  switch (algorithm) {
3894
4580
  case "sha256":
3895
- const success = verifyHmacSha256(headerValue, secret, await request.text());
4581
+ const success = verifyHmacSha256(headerValue, headerEncoding, secret, await request.text());
3896
4582
  if (success) {
3897
4583
  return {
3898
4584
  success
@@ -3908,9 +4594,9 @@ async function verifyRequestSignature({ request, headerName, secret, algorithm }
3908
4594
  }
3909
4595
  }
3910
4596
  __name(verifyRequestSignature, "verifyRequestSignature");
3911
- function verifyHmacSha256(headerValue, secret, body) {
3912
- const bodyDigest = import_crypto.default.createHmac("sha256", secret).update(body).digest("hex");
3913
- const signature = headerValue?.replace("sha256=", "") ?? "";
4597
+ function verifyHmacSha256(headerValue, headerEncoding, secret, body) {
4598
+ const bodyDigest = import_crypto.default.createHmac("sha256", secret).update(body).digest(headerEncoding);
4599
+ const signature = headerValue?.replace("hmac-sha256=", "").replace("sha256=", "") ?? "";
3914
4600
  return signature === bodyDigest;
3915
4601
  }
3916
4602
  __name(verifyHmacSha256, "verifyHmacSha256");
@@ -3942,6 +4628,8 @@ __name(redactString, "redactString");
3942
4628
  MissingConnectionNotification,
3943
4629
  MissingConnectionResolvedNotification,
3944
4630
  TriggerClient,
4631
+ WebhookSource,
4632
+ WebhookTrigger,
3945
4633
  cronTrigger,
3946
4634
  eventTrigger,
3947
4635
  intervalTrigger,
@@ -3952,6 +4640,7 @@ __name(redactString, "redactString");
3952
4640
  omit,
3953
4641
  redactString,
3954
4642
  retry,
4643
+ slugifyId,
3955
4644
  verifyHmacSha256,
3956
4645
  verifyRequestSignature,
3957
4646
  waitForEventSchema