@trigger.dev/sdk 2.2.11 → 2.3.1

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.mjs ADDED
@@ -0,0 +1,4818 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import { currentDate, REGISTER_SOURCE_EVENT_V2, RegisterSourceEventSchemaV2, API_VERSIONS, supportsFeature, ServerTaskSchema, RunTaskResponseWithCachedTasksBodySchema, ApiEventLogSchema, CancelRunsForEventSchema, JobRunStatusRecordSchema, TriggerSourceSchema, RegisterScheduleResponseBodySchema, ConnectionAuthSchema, GetEventSchema, urlWithSearchParams, GetRunSchema, GetRunStatusesSchema, GetRunsSchema, InvokeJobResponseSchema, EphemeralEventDispatcherResponseBodySchema, RequestWithRawBodySchema, deepMergeFilters, ScheduledPayloadSchema, WebhookSourceRequestHeadersSchema, HttpEndpointRequestHeadersSchema, HttpSourceRequestHeadersSchema, PreprocessRunBodySchema, RunJobBodySchema, InitializeTriggerBodySchema, MISSING_CONNECTION_NOTIFICATION, MissingConnectionNotificationPayloadSchema, MISSING_CONNECTION_RESOLVED_NOTIFICATION, MissingConnectionResolvedNotificationPayloadSchema, ErrorWithStackSchema, calculateRetryAt, assertExhaustive, KeyValueStoreResponseBodySchema, REGISTER_WEBHOOK, RegisterWebhookPayloadSchema } from '@trigger.dev/core';
3
+ import { Logger, BloomFilter } from '@trigger.dev/core-backend';
4
+ import EventEmitter from 'node:events';
5
+ import { env } from 'node:process';
6
+ import { z } from 'zod';
7
+ import crypto, { webcrypto, createHash } from 'node:crypto';
8
+ import { Buffer } from 'node:buffer';
9
+ import cronstrue from 'cronstrue';
10
+
11
+ var __defProp = Object.defineProperty;
12
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
14
+ var __publicField = (obj, key, value) => {
15
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
16
+ return value;
17
+ };
18
+ var __accessCheck = (obj, member, msg) => {
19
+ if (!member.has(obj))
20
+ throw TypeError("Cannot " + msg);
21
+ };
22
+ var __privateGet = (obj, member, getter) => {
23
+ __accessCheck(obj, member, "read from private field");
24
+ return getter ? getter.call(obj) : member.get(obj);
25
+ };
26
+ var __privateAdd = (obj, member, value) => {
27
+ if (member.has(obj))
28
+ throw TypeError("Cannot add the same private member more than once");
29
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
30
+ };
31
+ var __privateSet = (obj, member, value, setter) => {
32
+ __accessCheck(obj, member, "write to private field");
33
+ setter ? setter.call(obj, value) : member.set(obj, value);
34
+ return value;
35
+ };
36
+ var __privateMethod = (obj, member, method) => {
37
+ __accessCheck(obj, member, "access private method");
38
+ return method;
39
+ };
40
+ var _TypedAsyncLocalStorage = class _TypedAsyncLocalStorage {
41
+ constructor() {
42
+ this.storage = new AsyncLocalStorage();
43
+ }
44
+ runWith(context, fn) {
45
+ return this.storage.run(context, fn);
46
+ }
47
+ getStore() {
48
+ return this.storage.getStore();
49
+ }
50
+ };
51
+ __name(_TypedAsyncLocalStorage, "TypedAsyncLocalStorage");
52
+ var TypedAsyncLocalStorage = _TypedAsyncLocalStorage;
53
+
54
+ // src/runLocalStorage.ts
55
+ var runLocalStorage = new TypedAsyncLocalStorage();
56
+
57
+ // src/utils.ts
58
+ function slugifyId(input) {
59
+ const replaceSpacesWithDash = input.toLowerCase().replace(/\s+/g, "-");
60
+ const removeNonUrlSafeChars = replaceSpacesWithDash.replace(/[^a-zA-Z0-9-._~]/g, "");
61
+ return removeNonUrlSafeChars;
62
+ }
63
+ __name(slugifyId, "slugifyId");
64
+
65
+ // src/job.ts
66
+ var _validate, validate_fn;
67
+ var _Job = class _Job {
68
+ constructor(options) {
69
+ // Make sure the id is valid (must only contain alphanumeric characters and dashes)
70
+ // Make sure the version is valid (must be a valid semver version)
71
+ __privateAdd(this, _validate);
72
+ this.options = options;
73
+ __privateMethod(this, _validate, validate_fn).call(this);
74
+ }
75
+ /**
76
+ * Attaches the job to a client. This is called automatically when you define a job using `client.defineJob()`.
77
+ */
78
+ attachToClient(client) {
79
+ this.client = client;
80
+ this.trigger.attachToJob(client, this);
81
+ }
82
+ get id() {
83
+ return slugifyId(this.options.id);
84
+ }
85
+ get enabled() {
86
+ return typeof this.options.enabled === "boolean" ? this.options.enabled : true;
87
+ }
88
+ get name() {
89
+ return this.options.name;
90
+ }
91
+ get trigger() {
92
+ return this.options.trigger;
93
+ }
94
+ get version() {
95
+ return this.options.version;
96
+ }
97
+ get logLevel() {
98
+ return this.options.logLevel;
99
+ }
100
+ get integrations() {
101
+ return Object.keys(this.options.integrations ?? {}).reduce((acc, key) => {
102
+ const integration = this.options.integrations[key];
103
+ acc[key] = {
104
+ id: integration.id,
105
+ metadata: integration.metadata,
106
+ authSource: integration.authSource
107
+ };
108
+ return acc;
109
+ }, {});
110
+ }
111
+ toJSON() {
112
+ const internal = this.options.__internal;
113
+ return {
114
+ id: this.id,
115
+ name: this.name,
116
+ version: this.version,
117
+ event: this.trigger.event,
118
+ trigger: this.trigger.toJSON(),
119
+ integrations: this.integrations,
120
+ startPosition: "latest",
121
+ enabled: this.enabled,
122
+ preprocessRuns: this.trigger.preprocessRuns,
123
+ internal,
124
+ concurrencyLimit: typeof this.options.concurrencyLimit === "number" ? this.options.concurrencyLimit : typeof this.options.concurrencyLimit === "object" ? {
125
+ id: this.options.concurrencyLimit.id,
126
+ limit: this.options.concurrencyLimit.limit
127
+ } : void 0
128
+ };
129
+ }
130
+ async invoke(param1, param2 = void 0, param3 = void 0) {
131
+ const triggerClient = this.client;
132
+ if (!triggerClient) {
133
+ throw new Error("Cannot invoke a job that is not attached to a client. Make sure you attach the job to a client before invoking it.");
134
+ }
135
+ const runStore = runLocalStorage.getStore();
136
+ if (typeof param1 === "string") {
137
+ if (!runStore) {
138
+ throw new Error("Cannot invoke a job from outside of a run when passing a cacheKey. Make sure you are running the job from within a run or use the invoke method without the cacheKey.");
139
+ }
140
+ const options = param3 ?? {};
141
+ return await runStore.io.runTask(param1, async (task) => {
142
+ const result = await triggerClient.invokeJob(this.id, param2, {
143
+ idempotencyKey: task.idempotencyKey,
144
+ ...options
145
+ });
146
+ task.outputProperties = [
147
+ {
148
+ label: "Run",
149
+ text: result.id,
150
+ url: `/orgs/${runStore.ctx.organization.slug}/projects/${runStore.ctx.project.slug}/jobs/${this.id}/runs/${result.id}/trigger`
151
+ }
152
+ ];
153
+ return result;
154
+ }, {
155
+ name: `Manually Invoke '${this.name}'`,
156
+ params: param2,
157
+ properties: [
158
+ {
159
+ label: "Job",
160
+ text: this.id,
161
+ url: `/orgs/${runStore.ctx.organization.slug}/projects/${runStore.ctx.project.slug}/jobs/${this.id}`
162
+ },
163
+ {
164
+ label: "Env",
165
+ text: runStore.ctx.environment.slug
166
+ }
167
+ ]
168
+ });
169
+ }
170
+ if (runStore) {
171
+ throw new Error("Cannot invoke a job from within a run without a cacheKey.");
172
+ }
173
+ return await triggerClient.invokeJob(this.id, param1, param3);
174
+ }
175
+ async invokeAndWaitForCompletion(cacheKey, payload, timeoutInSeconds = 60 * 60, options = {}) {
176
+ const triggerClient = this.client;
177
+ if (!triggerClient) {
178
+ throw new Error("Cannot invoke a job that is not attached to a client. Make sure you attach the job to a client before invoking it.");
179
+ }
180
+ const runStore = runLocalStorage.getStore();
181
+ if (!runStore) {
182
+ throw new Error("Cannot invoke a job from outside of a run using invokeAndWaitForCompletion. Make sure you are running the job from within a run or use the invoke method instead.");
183
+ }
184
+ const { io, ctx } = runStore;
185
+ return await io.runTask(cacheKey, async (task) => {
186
+ const parsedPayload = this.trigger.event.parseInvokePayload ? this.trigger.event.parseInvokePayload(payload) ? payload : void 0 : payload;
187
+ const result = await triggerClient.invokeJob(this.id, parsedPayload, {
188
+ idempotencyKey: task.idempotencyKey,
189
+ callbackUrl: task.callbackUrl ?? void 0,
190
+ ...options
191
+ });
192
+ task.outputProperties = [
193
+ {
194
+ label: "Run",
195
+ text: result.id,
196
+ url: `/orgs/${ctx.organization.slug}/projects/${ctx.project.slug}/jobs/${this.id}/runs/${result.id}/trigger`
197
+ }
198
+ ];
199
+ return {};
200
+ }, {
201
+ name: `Manually Invoke '${this.name}' and wait for completion`,
202
+ params: payload,
203
+ properties: [
204
+ {
205
+ label: "Job",
206
+ text: this.id,
207
+ url: `/orgs/${ctx.organization.slug}/projects/${ctx.project.slug}/jobs/${this.id}`
208
+ },
209
+ {
210
+ label: "Env",
211
+ text: ctx.environment.slug
212
+ }
213
+ ],
214
+ callback: {
215
+ enabled: true,
216
+ timeoutInSeconds
217
+ }
218
+ });
219
+ }
220
+ async batchInvokeAndWaitForCompletion(cacheKey, batch) {
221
+ const runStore = runLocalStorage.getStore();
222
+ if (!runStore) {
223
+ throw new Error("Cannot invoke a job from outside of a run using batchInvokeAndWaitForCompletion.");
224
+ }
225
+ if (batch.length === 0) {
226
+ return [];
227
+ }
228
+ if (batch.length > 25) {
229
+ throw new Error(`Cannot batch invoke more than 25 items. You tried to batch invoke ${batch.length} items.`);
230
+ }
231
+ const { io, ctx } = runStore;
232
+ const results = await io.parallel(cacheKey, batch, async (item, index) => {
233
+ return await this.invokeAndWaitForCompletion(String(index), item.payload, item.timeoutInSeconds ?? 60 * 60, item.options);
234
+ }, {
235
+ name: `Batch Invoke '${this.name}'`,
236
+ properties: [
237
+ {
238
+ label: "Job",
239
+ text: this.id,
240
+ url: `/orgs/${ctx.organization.slug}/projects/${ctx.project.slug}/jobs/${this.id}`
241
+ },
242
+ {
243
+ label: "Env",
244
+ text: ctx.environment.slug
245
+ }
246
+ ]
247
+ });
248
+ return results;
249
+ }
250
+ };
251
+ _validate = new WeakSet();
252
+ validate_fn = /* @__PURE__ */ __name(function() {
253
+ if (!this.version.match(/^(\d+)\.(\d+)\.(\d+)$/)) {
254
+ throw new Error(`Invalid job version: "${this.version}". Job versions must be valid semver versions.`);
255
+ }
256
+ }, "#validate");
257
+ __name(_Job, "Job");
258
+ var Job = _Job;
259
+
260
+ // package.json
261
+ var version = "2.3.1";
262
+
263
+ // src/errors.ts
264
+ var _ResumeWithTaskError = class _ResumeWithTaskError {
265
+ constructor(task) {
266
+ this.task = task;
267
+ }
268
+ };
269
+ __name(_ResumeWithTaskError, "ResumeWithTaskError");
270
+ var ResumeWithTaskError = _ResumeWithTaskError;
271
+ var _ResumeWithParallelTaskError = class _ResumeWithParallelTaskError {
272
+ constructor(task, childErrors) {
273
+ this.task = task;
274
+ this.childErrors = childErrors;
275
+ }
276
+ };
277
+ __name(_ResumeWithParallelTaskError, "ResumeWithParallelTaskError");
278
+ var ResumeWithParallelTaskError = _ResumeWithParallelTaskError;
279
+ var _RetryWithTaskError = class _RetryWithTaskError {
280
+ constructor(cause, task, retryAt) {
281
+ this.cause = cause;
282
+ this.task = task;
283
+ this.retryAt = retryAt;
284
+ }
285
+ };
286
+ __name(_RetryWithTaskError, "RetryWithTaskError");
287
+ var RetryWithTaskError = _RetryWithTaskError;
288
+ var _CanceledWithTaskError = class _CanceledWithTaskError {
289
+ constructor(task) {
290
+ this.task = task;
291
+ }
292
+ };
293
+ __name(_CanceledWithTaskError, "CanceledWithTaskError");
294
+ var CanceledWithTaskError = _CanceledWithTaskError;
295
+ var _YieldExecutionError = class _YieldExecutionError {
296
+ constructor(key) {
297
+ this.key = key;
298
+ }
299
+ };
300
+ __name(_YieldExecutionError, "YieldExecutionError");
301
+ var YieldExecutionError = _YieldExecutionError;
302
+ var _AutoYieldExecutionError = class _AutoYieldExecutionError {
303
+ constructor(location, timeRemaining, timeElapsed) {
304
+ this.location = location;
305
+ this.timeRemaining = timeRemaining;
306
+ this.timeElapsed = timeElapsed;
307
+ }
308
+ };
309
+ __name(_AutoYieldExecutionError, "AutoYieldExecutionError");
310
+ var AutoYieldExecutionError = _AutoYieldExecutionError;
311
+ var _AutoYieldWithCompletedTaskExecutionError = class _AutoYieldWithCompletedTaskExecutionError {
312
+ constructor(id, properties, data, output) {
313
+ this.id = id;
314
+ this.properties = properties;
315
+ this.data = data;
316
+ this.output = output;
317
+ }
318
+ };
319
+ __name(_AutoYieldWithCompletedTaskExecutionError, "AutoYieldWithCompletedTaskExecutionError");
320
+ var AutoYieldWithCompletedTaskExecutionError = _AutoYieldWithCompletedTaskExecutionError;
321
+ var _ParsedPayloadSchemaError = class _ParsedPayloadSchemaError {
322
+ constructor(schemaErrors) {
323
+ this.schemaErrors = schemaErrors;
324
+ }
325
+ };
326
+ __name(_ParsedPayloadSchemaError, "ParsedPayloadSchemaError");
327
+ var ParsedPayloadSchemaError = _ParsedPayloadSchemaError;
328
+ function isTriggerError(err) {
329
+ return err instanceof ResumeWithTaskError || err instanceof RetryWithTaskError || err instanceof CanceledWithTaskError || err instanceof YieldExecutionError || err instanceof AutoYieldExecutionError || err instanceof AutoYieldWithCompletedTaskExecutionError || err instanceof ResumeWithParallelTaskError;
330
+ }
331
+ __name(isTriggerError, "isTriggerError");
332
+ var _ErrorWithTask = class _ErrorWithTask extends Error {
333
+ constructor(cause, message) {
334
+ super(message);
335
+ this.cause = cause;
336
+ }
337
+ };
338
+ __name(_ErrorWithTask, "ErrorWithTask");
339
+ var ErrorWithTask = _ErrorWithTask;
340
+ var retry = {
341
+ standardBackoff: {
342
+ limit: 8,
343
+ factor: 1.8,
344
+ minTimeoutInMs: 500,
345
+ maxTimeoutInMs: 3e4,
346
+ randomize: true
347
+ },
348
+ exponentialBackoff: {
349
+ limit: 8,
350
+ factor: 2,
351
+ minTimeoutInMs: 1e3,
352
+ maxTimeoutInMs: 3e4,
353
+ randomize: true
354
+ }
355
+ };
356
+
357
+ // src/status.ts
358
+ var _TriggerStatus = class _TriggerStatus {
359
+ constructor(id, io) {
360
+ this.id = id;
361
+ this.io = io;
362
+ }
363
+ async update(key, status) {
364
+ const properties = [];
365
+ if (status.label) {
366
+ properties.push({
367
+ label: "Label",
368
+ text: status.label
369
+ });
370
+ }
371
+ if (status.state) {
372
+ properties.push({
373
+ label: "State",
374
+ text: status.state
375
+ });
376
+ }
377
+ return await this.io.runTask(key, async (task) => {
378
+ return await this.io.triggerClient.updateStatus(this.io.runId, this.id, status);
379
+ }, {
380
+ name: status.label ?? `Status update`,
381
+ icon: "bell",
382
+ params: {
383
+ ...status
384
+ },
385
+ properties
386
+ });
387
+ }
388
+ };
389
+ __name(_TriggerStatus, "TriggerStatus");
390
+ var TriggerStatus = _TriggerStatus;
391
+ var EventSpecificationExampleSchema = z.object({
392
+ id: z.string(),
393
+ name: z.string(),
394
+ icon: z.string().optional(),
395
+ payload: z.any()
396
+ });
397
+ function waitForEventSchema(schema) {
398
+ return z.object({
399
+ id: z.string(),
400
+ name: z.string(),
401
+ source: z.string(),
402
+ payload: schema,
403
+ timestamp: z.coerce.date(),
404
+ context: z.any().optional(),
405
+ accountId: z.string().optional()
406
+ });
407
+ }
408
+ __name(waitForEventSchema, "waitForEventSchema");
409
+
410
+ // src/store/keyValueStore.ts
411
+ var _namespacedKey, namespacedKey_fn, _sharedProperties, sharedProperties_fn;
412
+ var _KeyValueStore = class _KeyValueStore {
413
+ constructor(apiClient, type = null, namespace = "") {
414
+ __privateAdd(this, _namespacedKey);
415
+ __privateAdd(this, _sharedProperties);
416
+ this.apiClient = apiClient;
417
+ this.type = type;
418
+ this.namespace = namespace;
419
+ }
420
+ async delete(param1, param2) {
421
+ const runStore = runLocalStorage.getStore();
422
+ if (!runStore) {
423
+ if (typeof param1 !== "string") {
424
+ throw new Error("Please use the store without a cacheKey when accessing from outside a run.");
425
+ }
426
+ return await this.apiClient.store.delete(__privateMethod(this, _namespacedKey, namespacedKey_fn).call(this, param1));
427
+ }
428
+ const { io } = runStore;
429
+ if (!param2) {
430
+ throw new Error("Please provide a non-empty key when accessing the store from inside a run.");
431
+ }
432
+ return await io.runTask(param1, async (task) => {
433
+ return await this.apiClient.store.delete(__privateMethod(this, _namespacedKey, namespacedKey_fn).call(this, param2));
434
+ }, {
435
+ name: "Key-Value Store Delete",
436
+ icon: "database-minus",
437
+ params: {
438
+ key: param2
439
+ },
440
+ properties: __privateMethod(this, _sharedProperties, sharedProperties_fn).call(this, param2),
441
+ style: {
442
+ style: "minimal"
443
+ }
444
+ });
445
+ }
446
+ async get(param1, param2) {
447
+ const runStore = runLocalStorage.getStore();
448
+ if (!runStore) {
449
+ if (typeof param1 !== "string") {
450
+ throw new Error("Please use the store without a cacheKey when accessing from outside a run.");
451
+ }
452
+ return await this.apiClient.store.get(__privateMethod(this, _namespacedKey, namespacedKey_fn).call(this, param1));
453
+ }
454
+ const { io } = runStore;
455
+ if (!param2) {
456
+ throw new Error("Please provide a non-empty key when accessing the store from inside a run.");
457
+ }
458
+ return await io.runTask(param1, async (task) => {
459
+ return await this.apiClient.store.get(__privateMethod(this, _namespacedKey, namespacedKey_fn).call(this, param2));
460
+ }, {
461
+ name: "Key-Value Store Get",
462
+ icon: "database-export",
463
+ params: {
464
+ key: param2
465
+ },
466
+ properties: __privateMethod(this, _sharedProperties, sharedProperties_fn).call(this, param2),
467
+ style: {
468
+ style: "minimal"
469
+ }
470
+ });
471
+ }
472
+ async has(param1, param2) {
473
+ const runStore = runLocalStorage.getStore();
474
+ if (!runStore) {
475
+ if (typeof param1 !== "string") {
476
+ throw new Error("Please use the store without a cacheKey when accessing from outside a run.");
477
+ }
478
+ return await this.apiClient.store.has(__privateMethod(this, _namespacedKey, namespacedKey_fn).call(this, param1));
479
+ }
480
+ const { io } = runStore;
481
+ if (!param2) {
482
+ throw new Error("Please provide a non-empty key when accessing the store from inside a run.");
483
+ }
484
+ return await io.runTask(param1, async (task) => {
485
+ return await this.apiClient.store.has(__privateMethod(this, _namespacedKey, namespacedKey_fn).call(this, param2));
486
+ }, {
487
+ name: "Key-Value Store Has",
488
+ icon: "database-search",
489
+ params: {
490
+ key: param2
491
+ },
492
+ properties: __privateMethod(this, _sharedProperties, sharedProperties_fn).call(this, param2),
493
+ style: {
494
+ style: "minimal"
495
+ }
496
+ });
497
+ }
498
+ async set(param1, param2, param3) {
499
+ const runStore = runLocalStorage.getStore();
500
+ if (!runStore) {
501
+ if (typeof param1 !== "string") {
502
+ throw new Error("Please use the store without a cacheKey when accessing from outside a run.");
503
+ }
504
+ return await this.apiClient.store.set(__privateMethod(this, _namespacedKey, namespacedKey_fn).call(this, param1), param2);
505
+ }
506
+ const { io } = runStore;
507
+ if (!param2 || typeof param2 !== "string") {
508
+ throw new Error("Please provide a non-empty key when accessing the store from inside a run.");
509
+ }
510
+ const value = param3;
511
+ return await io.runTask(param1, async (task) => {
512
+ return await this.apiClient.store.set(__privateMethod(this, _namespacedKey, namespacedKey_fn).call(this, param2), value);
513
+ }, {
514
+ name: "Key-Value Store Set",
515
+ icon: "database-plus",
516
+ params: {
517
+ key: param2,
518
+ value
519
+ },
520
+ properties: [
521
+ ...__privateMethod(this, _sharedProperties, sharedProperties_fn).call(this, param2),
522
+ ...typeof value !== "object" || value === null ? [
523
+ {
524
+ label: "value",
525
+ text: String(value) ?? "undefined"
526
+ }
527
+ ] : []
528
+ ],
529
+ style: {
530
+ style: "minimal"
531
+ }
532
+ });
533
+ }
534
+ };
535
+ _namespacedKey = new WeakSet();
536
+ namespacedKey_fn = /* @__PURE__ */ __name(function(key) {
537
+ const parts = [];
538
+ if (this.type) {
539
+ parts.push(this.type);
540
+ }
541
+ if (this.namespace) {
542
+ parts.push(this.namespace);
543
+ }
544
+ parts.push(key);
545
+ return parts.join(":");
546
+ }, "#namespacedKey");
547
+ _sharedProperties = new WeakSet();
548
+ sharedProperties_fn = /* @__PURE__ */ __name(function(key1) {
549
+ return [
550
+ {
551
+ label: "namespace",
552
+ text: this.type ?? "env"
553
+ },
554
+ {
555
+ label: "key",
556
+ text: key1
557
+ }
558
+ ];
559
+ }, "#sharedProperties");
560
+ __name(_KeyValueStore, "KeyValueStore");
561
+ var KeyValueStore = _KeyValueStore;
562
+ var _JSONOutputSerializer = class _JSONOutputSerializer {
563
+ serialize(value) {
564
+ return JSON.stringify(value);
565
+ }
566
+ deserialize(value) {
567
+ return value ? JSON.parse(value) : void 0;
568
+ }
569
+ };
570
+ __name(_JSONOutputSerializer, "JSONOutputSerializer");
571
+ var JSONOutputSerializer = _JSONOutputSerializer;
572
+ var _addToCachedTasks, addToCachedTasks_fn, _detectAutoYield, detectAutoYield_fn, _forceYield, forceYield_fn, _getTimeElapsed, getTimeElapsed_fn, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn;
573
+ var _IO = class _IO {
574
+ constructor(options) {
575
+ __privateAdd(this, _addToCachedTasks);
576
+ __privateAdd(this, _detectAutoYield);
577
+ __privateAdd(this, _forceYield);
578
+ __privateAdd(this, _getTimeElapsed);
579
+ __privateAdd(this, _getRemainingTimeInMillis);
580
+ __publicField(this, "_outputSerializer", new JSONOutputSerializer());
581
+ __publicField(this, "_visitedCacheKeys", /* @__PURE__ */ new Set());
582
+ /**
583
+ * `io.brb()` is an alias of `io.yield()`
584
+ */
585
+ __publicField(this, "brb", this.yield.bind(this));
586
+ this._id = options.id;
587
+ this._jobId = options.jobId;
588
+ this._apiClient = options.apiClient;
589
+ this._triggerClient = options.client;
590
+ this._logger = options.logger ?? new Logger("trigger.dev", options.logLevel);
591
+ this._cachedTasks = /* @__PURE__ */ new Map();
592
+ this._jobLogger = options.jobLogger;
593
+ this._jobLogLevel = options.jobLogLevel;
594
+ this._timeOrigin = options.timeOrigin;
595
+ this._executionTimeout = options.executionTimeout;
596
+ this._envStore = new KeyValueStore(options.apiClient);
597
+ this._jobStore = new KeyValueStore(options.apiClient, "job", options.jobId);
598
+ this._runStore = new KeyValueStore(options.apiClient, "run", options.id);
599
+ this._stats = {
600
+ initialCachedTasks: 0,
601
+ lazyLoadedCachedTasks: 0,
602
+ executedTasks: 0,
603
+ cachedTaskHits: 0,
604
+ cachedTaskMisses: 0,
605
+ noopCachedTaskHits: 0,
606
+ noopCachedTaskMisses: 0
607
+ };
608
+ if (options.cachedTasks) {
609
+ options.cachedTasks.forEach((task) => {
610
+ this._cachedTasks.set(task.idempotencyKey, task);
611
+ });
612
+ this._stats.initialCachedTasks = options.cachedTasks.length;
613
+ }
614
+ this._taskStorage = new AsyncLocalStorage();
615
+ this._context = options.context;
616
+ this._yieldedExecutions = options.yieldedExecutions ?? [];
617
+ if (options.noopTasksSet) {
618
+ this._noopTasksBloomFilter = BloomFilter.deserialize(options.noopTasksSet, BloomFilter.NOOP_TASK_SET_SIZE);
619
+ }
620
+ this._cachedTasksCursor = options.cachedTasksCursor;
621
+ this._serverVersion = options.serverVersion ?? "unversioned";
622
+ }
623
+ get stats() {
624
+ return this._stats;
625
+ }
626
+ /** @internal */
627
+ get runId() {
628
+ return this._id;
629
+ }
630
+ /** @internal */
631
+ get triggerClient() {
632
+ return this._triggerClient;
633
+ }
634
+ /** Used to send log messages to the [Run log](https://trigger.dev/docs/documentation/guides/viewing-runs). */
635
+ get logger() {
636
+ return new IOLogger(async (level, message, data) => {
637
+ let logLevel = "info";
638
+ if (Logger.satisfiesLogLevel(logLevel, this._jobLogLevel)) {
639
+ await this.runTask([
640
+ message,
641
+ level
642
+ ], async (task) => {
643
+ switch (level) {
644
+ case "LOG": {
645
+ this._jobLogger?.log(message, data);
646
+ logLevel = "log";
647
+ break;
648
+ }
649
+ case "DEBUG": {
650
+ this._jobLogger?.debug(message, data);
651
+ logLevel = "debug";
652
+ break;
653
+ }
654
+ case "INFO": {
655
+ this._jobLogger?.info(message, data);
656
+ logLevel = "info";
657
+ break;
658
+ }
659
+ case "WARN": {
660
+ this._jobLogger?.warn(message, data);
661
+ logLevel = "warn";
662
+ break;
663
+ }
664
+ case "ERROR": {
665
+ this._jobLogger?.error(message, data);
666
+ logLevel = "error";
667
+ break;
668
+ }
669
+ }
670
+ }, {
671
+ name: "log",
672
+ icon: "log",
673
+ description: message,
674
+ params: data,
675
+ properties: [
676
+ {
677
+ label: "Level",
678
+ text: level
679
+ }
680
+ ],
681
+ style: {
682
+ style: "minimal",
683
+ variant: level.toLowerCase()
684
+ },
685
+ noop: true
686
+ });
687
+ }
688
+ });
689
+ }
690
+ /** `io.random()` is identical to `Math.random()` when called without options but ensures your random numbers are not regenerated on resume or retry. It will return a pseudo-random floating-point number between optional `min` (default: 0, inclusive) and `max` (default: 1, exclusive). Can optionally `round` to the nearest integer.
691
+ * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
692
+ * @param min Sets the lower bound (inclusive). Can't be higher than `max`.
693
+ * @param max Sets the upper bound (exclusive). Can't be lower than `min`.
694
+ * @param round Controls rounding to the nearest integer. Any `max` integer will become inclusive when enabled. Rounding with floating-point bounds may cause unexpected skew and boundary inclusivity.
695
+ */
696
+ async random(cacheKey, { min = 0, max = 1, round = false } = {}) {
697
+ return await this.runTask(cacheKey, async (task) => {
698
+ if (min > max) {
699
+ throw new Error(`Lower bound can't be higher than upper bound - min: ${min}, max: ${max}`);
700
+ }
701
+ if (min === max) {
702
+ await this.logger.warn(`Lower and upper bounds are identical. The return value is not random and will always be: ${min}`);
703
+ }
704
+ const withinBounds = (max - min) * Math.random() + min;
705
+ if (!round) {
706
+ return withinBounds;
707
+ }
708
+ if (!Number.isInteger(min) || !Number.isInteger(max)) {
709
+ await this.logger.warn("Rounding enabled with floating-point bounds. This may cause unexpected skew and boundary inclusivity.");
710
+ }
711
+ const rounded = Math.round(withinBounds);
712
+ return rounded;
713
+ }, {
714
+ name: "random",
715
+ icon: "dice-5-filled",
716
+ params: {
717
+ min,
718
+ max,
719
+ round
720
+ },
721
+ properties: [
722
+ ...min === 0 ? [] : [
723
+ {
724
+ label: "min",
725
+ text: String(min)
726
+ }
727
+ ],
728
+ ...max === 1 ? [] : [
729
+ {
730
+ label: "max",
731
+ text: String(max)
732
+ }
733
+ ],
734
+ ...round === false ? [] : [
735
+ {
736
+ label: "round",
737
+ text: String(round)
738
+ }
739
+ ]
740
+ ],
741
+ style: {
742
+ style: "minimal"
743
+ }
744
+ });
745
+ }
746
+ /** `io.wait()` waits for the specified amount of time before continuing the Job. Delays work even if you're on a serverless platform with timeouts, or if your server goes down. They utilize [resumability](https://trigger.dev/docs/documentation/concepts/resumability) to ensure that the Run can be resumed after the delay.
747
+ * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
748
+ * @param seconds The number of seconds to wait. This can be very long, serverless timeouts are not an issue.
749
+ */
750
+ async wait(cacheKey, seconds) {
751
+ return await this.runTask(cacheKey, async (task) => {
752
+ }, {
753
+ name: "wait",
754
+ icon: "clock",
755
+ params: {
756
+ seconds
757
+ },
758
+ noop: true,
759
+ delayUntil: new Date(Date.now() + seconds * 1e3),
760
+ style: {
761
+ style: "minimal"
762
+ }
763
+ });
764
+ }
765
+ async waitForEvent(cacheKey, event, options) {
766
+ const timeoutInSeconds = options?.timeoutInSeconds ?? 60 * 60;
767
+ return await this.runTask(cacheKey, async (task, io) => {
768
+ if (!task.callbackUrl) {
769
+ throw new Error("No callbackUrl found on task");
770
+ }
771
+ await this.triggerClient.createEphemeralEventDispatcher({
772
+ url: task.callbackUrl,
773
+ name: event.name,
774
+ filter: event.filter,
775
+ contextFilter: event.contextFilter,
776
+ source: event.source,
777
+ accountId: event.accountId,
778
+ timeoutInSeconds
779
+ });
780
+ return {};
781
+ }, {
782
+ name: "Wait for Event",
783
+ icon: "custom-event",
784
+ params: {
785
+ name: event.name,
786
+ source: event.source,
787
+ filter: event.filter,
788
+ contextFilter: event.contextFilter,
789
+ accountId: event.accountId
790
+ },
791
+ callback: {
792
+ enabled: true,
793
+ timeoutInSeconds
794
+ },
795
+ properties: [
796
+ {
797
+ label: "Event",
798
+ text: event.name
799
+ },
800
+ {
801
+ label: "Timeout",
802
+ text: `${timeoutInSeconds}s`
803
+ },
804
+ ...event.source ? [
805
+ {
806
+ label: "Source",
807
+ text: event.source
808
+ }
809
+ ] : [],
810
+ ...event.accountId ? [
811
+ {
812
+ label: "Account ID",
813
+ text: event.accountId
814
+ }
815
+ ] : []
816
+ ],
817
+ parseOutput: (output) => {
818
+ return waitForEventSchema(event.schema ?? z.any()).parse(output);
819
+ }
820
+ });
821
+ }
822
+ /** `io.waitForRequest()` allows you to pause the execution of a run until the url provided in the callback is POSTed to.
823
+ * This is useful for integrating with external services that require a callback URL to be provided, or if you want to be able to wait until an action is performed somewhere else in your system.
824
+ * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
825
+ * @param callback A callback function that will provide the unique URL to POST to.
826
+ * @param options Options for the callback.
827
+ * @param options.timeoutInSeconds How long to wait for the request to be POSTed to the callback URL before timing out. Defaults to 1hr.
828
+ * @returns The POSTed request JSON body.
829
+ * @example
830
+ * ```ts
831
+ const result = await io.waitForRequest<{ message: string }>(
832
+ "wait-for-request",
833
+ async (url, task) => {
834
+ // Save the URL somewhere so you can POST to it later
835
+ // Or send it to an external service that will POST to it
836
+ },
837
+ { timeoutInSeconds: 60 } // wait 60 seconds
838
+ );
839
+ * ```
840
+ */
841
+ async waitForRequest(cacheKey, callback, options) {
842
+ const timeoutInSeconds = options?.timeoutInSeconds ?? 60 * 60;
843
+ return await this.runTask(cacheKey, async (task, io) => {
844
+ if (!task.callbackUrl) {
845
+ throw new Error("No callbackUrl found on task");
846
+ }
847
+ task.outputProperties = [
848
+ {
849
+ label: "Callback URL",
850
+ text: task.callbackUrl
851
+ }
852
+ ];
853
+ return callback(task.callbackUrl);
854
+ }, {
855
+ name: "Wait for Request",
856
+ icon: "clock",
857
+ callback: {
858
+ enabled: true,
859
+ timeoutInSeconds: options?.timeoutInSeconds
860
+ },
861
+ properties: [
862
+ {
863
+ label: "Timeout",
864
+ text: `${timeoutInSeconds}s`
865
+ }
866
+ ]
867
+ });
868
+ }
869
+ /** `io.createStatus()` allows you to set a status with associated data during the Run. Statuses can be used by your UI using the react package
870
+ * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
871
+ * @param initialStatus The initial status you want this status to have. You can update it during the rub using the returned object.
872
+ * @returns a TriggerStatus object that you can call `update()` on, to update the status.
873
+ * @example
874
+ * ```ts
875
+ * client.defineJob(
876
+ //...
877
+ run: async (payload, io, ctx) => {
878
+ const generatingImages = await io.createStatus("generating-images", {
879
+ label: "Generating Images",
880
+ state: "loading",
881
+ data: {
882
+ progress: 0.1,
883
+ },
884
+ });
885
+
886
+ //...do stuff
887
+
888
+ await generatingImages.update("completed-generation", {
889
+ label: "Generated images",
890
+ state: "success",
891
+ data: {
892
+ progress: 1.0,
893
+ urls: ["http://..."]
894
+ },
895
+ });
896
+
897
+ //...
898
+ });
899
+ * ```
900
+ */
901
+ async createStatus(cacheKey, initialStatus) {
902
+ const id = typeof cacheKey === "string" ? cacheKey : cacheKey.join("-");
903
+ const status = new TriggerStatus(id, this);
904
+ await status.update(cacheKey, initialStatus);
905
+ return status;
906
+ }
907
+ /** `io.backgroundFetch()` fetches data from a URL that can take longer that the serverless timeout. The actual `fetch` request is performed on the Trigger.dev platform, and the response is sent back to you.
908
+ * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
909
+ * @param url The URL to fetch from.
910
+ * @param requestInit The options for the request
911
+ * @param retry The options for retrying the request if it fails
912
+ * An object where the key is a status code pattern and the value is a retrying strategy.
913
+ * Supported patterns are:
914
+ * - Specific status codes: 429
915
+ * - Ranges: 500-599
916
+ * - Wildcards: 2xx, 3xx, 4xx, 5xx
917
+ */
918
+ async backgroundFetch(cacheKey, url, requestInit, options) {
919
+ const urlObject = new URL(url);
920
+ return await this.runTask(cacheKey, async (task) => {
921
+ console.log("task context", task.context);
922
+ return task.output;
923
+ }, {
924
+ name: `fetch ${urlObject.hostname}${urlObject.pathname}`,
925
+ params: {
926
+ url,
927
+ requestInit,
928
+ retry: options?.retry,
929
+ timeout: options?.timeout
930
+ },
931
+ operation: "fetch",
932
+ icon: "background",
933
+ noop: false,
934
+ properties: [
935
+ {
936
+ label: "url",
937
+ text: url,
938
+ url
939
+ },
940
+ {
941
+ label: "method",
942
+ text: requestInit?.method ?? "GET"
943
+ },
944
+ {
945
+ label: "background",
946
+ text: "true"
947
+ },
948
+ ...options?.timeout ? [
949
+ {
950
+ label: "timeout",
951
+ text: `${options.timeout.durationInMs}ms`
952
+ }
953
+ ] : []
954
+ ],
955
+ retry: {
956
+ limit: 0
957
+ }
958
+ });
959
+ }
960
+ /** `io.backgroundPoll()` will fetch data from a URL on an interval. The actual `fetch` requests are performed on the Trigger.dev server, so you don't have to worry about serverless function timeouts.
961
+ * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
962
+ * @param params The options for the background poll
963
+ * @param params.url The URL to fetch from.
964
+ * @param params.requestInit The options for the request, like headers and method
965
+ * @param params.responseFilter An [EventFilter](https://trigger.dev/docs/documentation/guides/event-filter) that allows you to specify when to stop polling.
966
+ * @param params.interval The interval in seconds to poll the URL in seconds. Defaults to 10 seconds which is the minimum.
967
+ * @param params.timeout The timeout in seconds for each request in seconds. Defaults to 10 minutes. Minimum is 60 seconds and max is 1 hour
968
+ * @param params.requestTimeout An optional object that allows you to timeout individual fetch requests
969
+ * @param params.requestTimeout An optional object that allows you to timeout individual fetch requests
970
+ * @param params.requestTimeout.durationInMs The duration in milliseconds to timeout the request
971
+ *
972
+ * @example
973
+ * ```ts
974
+ * const result = await io.backgroundPoll<{ id: string; status: string; }>("poll", {
975
+ url: `http://localhost:3030/api/v1/runs/${run.id}`,
976
+ requestInit: {
977
+ headers: {
978
+ Accept: "application/json",
979
+ Authorization: redactString`Bearer ${process.env["TRIGGER_API_KEY"]!}`,
980
+ },
981
+ },
982
+ interval: 10,
983
+ timeout: 600,
984
+ responseFilter: {
985
+ status: [200],
986
+ body: {
987
+ status: ["SUCCESS"],
988
+ },
989
+ },
990
+ });
991
+ * ```
992
+ */
993
+ async backgroundPoll(cacheKey, params) {
994
+ const urlObject = new URL(params.url);
995
+ return await this.runTask(cacheKey, async (task) => {
996
+ return task.output;
997
+ }, {
998
+ name: `poll ${urlObject.hostname}${urlObject.pathname}`,
999
+ params,
1000
+ operation: "fetch-poll",
1001
+ icon: "clock-bolt",
1002
+ noop: false,
1003
+ properties: [
1004
+ {
1005
+ label: "url",
1006
+ text: params.url
1007
+ },
1008
+ {
1009
+ label: "interval",
1010
+ text: `${params.interval}s`
1011
+ },
1012
+ {
1013
+ label: "timeout",
1014
+ text: `${params.timeout}s`
1015
+ }
1016
+ ],
1017
+ retry: {
1018
+ limit: 0
1019
+ }
1020
+ });
1021
+ }
1022
+ /** `io.backgroundFetchResponse()` fetches data from a URL that can take longer that the serverless timeout. The actual `fetch` request is performed on the Trigger.dev platform, and the response is sent back to you.
1023
+ * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
1024
+ * @param url The URL to fetch from.
1025
+ * @param requestInit The options for the request
1026
+ * @param retry The options for retrying the request if it fails
1027
+ * An object where the key is a status code pattern and the value is a retrying strategy.
1028
+ * Supported patterns are:
1029
+ * - Specific status codes: 429
1030
+ * - Ranges: 500-599
1031
+ * - Wildcards: 2xx, 3xx, 4xx, 5xx
1032
+ */
1033
+ async backgroundFetchResponse(cacheKey, url, requestInit, options) {
1034
+ const urlObject = new URL(url);
1035
+ return await this.runTask(cacheKey, async (task) => {
1036
+ return task.output;
1037
+ }, {
1038
+ name: `fetch response ${urlObject.hostname}${urlObject.pathname}`,
1039
+ params: {
1040
+ url,
1041
+ requestInit,
1042
+ retry: options?.retry,
1043
+ timeout: options?.timeout
1044
+ },
1045
+ operation: "fetch-response",
1046
+ icon: "background",
1047
+ noop: false,
1048
+ properties: [
1049
+ {
1050
+ label: "url",
1051
+ text: url,
1052
+ url
1053
+ },
1054
+ {
1055
+ label: "method",
1056
+ text: requestInit?.method ?? "GET"
1057
+ },
1058
+ {
1059
+ label: "background",
1060
+ text: "true"
1061
+ },
1062
+ ...options?.timeout ? [
1063
+ {
1064
+ label: "timeout",
1065
+ text: `${options.timeout.durationInMs}ms`
1066
+ }
1067
+ ] : []
1068
+ ],
1069
+ retry: {
1070
+ limit: 0
1071
+ }
1072
+ });
1073
+ }
1074
+ /** `io.sendEvent()` allows you to send an event from inside a Job run. The sent event will trigger any Jobs that are listening for that event (based on the name).
1075
+ * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
1076
+ * @param event The event to send. The event name must match the name of the event that your Jobs are listening for.
1077
+ * @param options Options for sending the event.
1078
+ */
1079
+ async sendEvent(cacheKey, event, options) {
1080
+ return await this.runTask(cacheKey, async (task) => {
1081
+ return await this._triggerClient.sendEvent(event, options);
1082
+ }, {
1083
+ name: "Send Event",
1084
+ params: {
1085
+ event,
1086
+ options
1087
+ },
1088
+ icon: "send",
1089
+ properties: [
1090
+ {
1091
+ label: "name",
1092
+ text: event.name
1093
+ },
1094
+ ...event?.id ? [
1095
+ {
1096
+ label: "ID",
1097
+ text: event.id
1098
+ }
1099
+ ] : [],
1100
+ ...sendEventOptionsProperties(options)
1101
+ ]
1102
+ });
1103
+ }
1104
+ /** `io.sendEvents()` allows you to send multiple events from inside a Job run. The sent events will trigger any Jobs that are listening for those events (based on the name).
1105
+ * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
1106
+ * @param event The events to send. The event names must match the names of the events that your Jobs are listening for.
1107
+ * @param options Options for sending the events.
1108
+ */
1109
+ async sendEvents(cacheKey, events, options) {
1110
+ return await this.runTask(cacheKey, async (task) => {
1111
+ return await this._triggerClient.sendEvents(events, options);
1112
+ }, {
1113
+ name: "Send Multiple Events",
1114
+ params: {
1115
+ events,
1116
+ options
1117
+ },
1118
+ icon: "send",
1119
+ properties: [
1120
+ {
1121
+ label: "Total Events",
1122
+ text: String(events.length)
1123
+ },
1124
+ ...sendEventOptionsProperties(options)
1125
+ ]
1126
+ });
1127
+ }
1128
+ async getEvent(cacheKey, id) {
1129
+ return await this.runTask(cacheKey, async (task) => {
1130
+ return await this._triggerClient.getEvent(id);
1131
+ }, {
1132
+ name: "getEvent",
1133
+ params: {
1134
+ id
1135
+ },
1136
+ properties: [
1137
+ {
1138
+ label: "id",
1139
+ text: id
1140
+ }
1141
+ ]
1142
+ });
1143
+ }
1144
+ /** `io.cancelEvent()` allows you to cancel an event that was previously sent with `io.sendEvent()`. This will prevent any Jobs from running that are listening for that event if the event was sent with a delay
1145
+ * @param cacheKey
1146
+ * @param eventId
1147
+ * @returns
1148
+ */
1149
+ async cancelEvent(cacheKey, eventId) {
1150
+ return await this.runTask(cacheKey, async (task) => {
1151
+ return await this._triggerClient.cancelEvent(eventId);
1152
+ }, {
1153
+ name: "cancelEvent",
1154
+ params: {
1155
+ eventId
1156
+ },
1157
+ properties: [
1158
+ {
1159
+ label: "id",
1160
+ text: eventId
1161
+ }
1162
+ ]
1163
+ });
1164
+ }
1165
+ async updateSource(cacheKey, options) {
1166
+ return this.runTask(cacheKey, async (task) => {
1167
+ return await this._apiClient.updateSource(this._triggerClient.id, options.key, options);
1168
+ }, {
1169
+ name: "Update Source",
1170
+ description: "Update Source",
1171
+ properties: [
1172
+ {
1173
+ label: "key",
1174
+ text: options.key
1175
+ }
1176
+ ],
1177
+ params: options,
1178
+ redact: {
1179
+ paths: [
1180
+ "secret"
1181
+ ]
1182
+ }
1183
+ });
1184
+ }
1185
+ async updateWebhook(cacheKey, options) {
1186
+ return this.runTask(cacheKey, async (task) => {
1187
+ return await this._apiClient.updateWebhook(options.key, options);
1188
+ }, {
1189
+ name: "Update Webhook Source",
1190
+ icon: "refresh",
1191
+ properties: [
1192
+ {
1193
+ label: "key",
1194
+ text: options.key
1195
+ }
1196
+ ],
1197
+ params: options
1198
+ });
1199
+ }
1200
+ /** `io.registerInterval()` allows you to register a [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) that will trigger any jobs it's attached to on a regular interval.
1201
+ * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
1202
+ * @param dynamicSchedule The [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) to register a new schedule on.
1203
+ * @param id A unique id for the interval. This is used to identify and unregister the interval later.
1204
+ * @param options The options for the interval.
1205
+ * @returns A promise that has information about the interval.
1206
+ * @deprecated Use `DynamicSchedule.register` instead.
1207
+ */
1208
+ async registerInterval(cacheKey, dynamicSchedule, id, options) {
1209
+ return await this.runTask(cacheKey, async (task) => {
1210
+ return dynamicSchedule.register(id, {
1211
+ type: "interval",
1212
+ options
1213
+ });
1214
+ }, {
1215
+ name: "register-interval",
1216
+ properties: [
1217
+ {
1218
+ label: "schedule",
1219
+ text: dynamicSchedule.id
1220
+ },
1221
+ {
1222
+ label: "id",
1223
+ text: id
1224
+ },
1225
+ {
1226
+ label: "seconds",
1227
+ text: options.seconds.toString()
1228
+ }
1229
+ ],
1230
+ params: options
1231
+ });
1232
+ }
1233
+ /** `io.unregisterInterval()` allows you to unregister a [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) that was previously registered with `io.registerInterval()`.
1234
+ * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
1235
+ * @param dynamicSchedule The [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) to unregister a schedule on.
1236
+ * @param id A unique id for the interval. This is used to identify and unregister the interval later.
1237
+ * @deprecated Use `DynamicSchedule.unregister` instead.
1238
+ */
1239
+ async unregisterInterval(cacheKey, dynamicSchedule, id) {
1240
+ return await this.runTask(cacheKey, async (task) => {
1241
+ return dynamicSchedule.unregister(id);
1242
+ }, {
1243
+ name: "unregister-interval",
1244
+ properties: [
1245
+ {
1246
+ label: "schedule",
1247
+ text: dynamicSchedule.id
1248
+ },
1249
+ {
1250
+ label: "id",
1251
+ text: id
1252
+ }
1253
+ ]
1254
+ });
1255
+ }
1256
+ /** `io.registerCron()` allows you to register a [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) that will trigger any jobs it's attached to on a regular CRON schedule.
1257
+ * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
1258
+ * @param dynamicSchedule The [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) to register a new schedule on.
1259
+ * @param id A unique id for the schedule. This is used to identify and unregister the schedule later.
1260
+ * @param options The options for the CRON schedule.
1261
+ * @deprecated Use `DynamicSchedule.register` instead.
1262
+ */
1263
+ async registerCron(cacheKey, dynamicSchedule, id, options) {
1264
+ return await this.runTask(cacheKey, async (task) => {
1265
+ return dynamicSchedule.register(id, {
1266
+ type: "cron",
1267
+ options
1268
+ });
1269
+ }, {
1270
+ name: "register-cron",
1271
+ properties: [
1272
+ {
1273
+ label: "schedule",
1274
+ text: dynamicSchedule.id
1275
+ },
1276
+ {
1277
+ label: "id",
1278
+ text: id
1279
+ },
1280
+ {
1281
+ label: "cron",
1282
+ text: options.cron
1283
+ }
1284
+ ],
1285
+ params: options
1286
+ });
1287
+ }
1288
+ /** `io.unregisterCron()` allows you to unregister a [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) that was previously registered with `io.registerCron()`.
1289
+ * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
1290
+ * @param dynamicSchedule The [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) to unregister a schedule on.
1291
+ * @param id A unique id for the interval. This is used to identify and unregister the interval later.
1292
+ * @deprecated Use `DynamicSchedule.unregister` instead.
1293
+ */
1294
+ async unregisterCron(cacheKey, dynamicSchedule, id) {
1295
+ return await this.runTask(cacheKey, async (task) => {
1296
+ return dynamicSchedule.unregister(id);
1297
+ }, {
1298
+ name: "unregister-cron",
1299
+ properties: [
1300
+ {
1301
+ label: "schedule",
1302
+ text: dynamicSchedule.id
1303
+ },
1304
+ {
1305
+ label: "id",
1306
+ text: id
1307
+ }
1308
+ ]
1309
+ });
1310
+ }
1311
+ /** `io.registerTrigger()` allows you to register a [DynamicTrigger](https://trigger.dev/docs/sdk/dynamictrigger) with the specified trigger params.
1312
+ * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
1313
+ * @param trigger The [DynamicTrigger](https://trigger.dev/docs/sdk/dynamictrigger) to register.
1314
+ * @param id A unique id for the trigger. This is used to identify and unregister the trigger later.
1315
+ * @param params The params for the trigger.
1316
+ * @deprecated Use `DynamicTrigger.register` instead.
1317
+ */
1318
+ async registerTrigger(cacheKey, trigger, id, params) {
1319
+ return await this.runTask(cacheKey, async (task) => {
1320
+ const registration = await this.runTask("register-source", async (subtask1) => {
1321
+ return trigger.register(id, params);
1322
+ }, {
1323
+ name: "register-source"
1324
+ });
1325
+ return {
1326
+ id: registration.id,
1327
+ key: registration.source.key
1328
+ };
1329
+ }, {
1330
+ name: "register-trigger",
1331
+ properties: [
1332
+ {
1333
+ label: "trigger",
1334
+ text: trigger.id
1335
+ },
1336
+ {
1337
+ label: "id",
1338
+ text: id
1339
+ }
1340
+ ],
1341
+ params
1342
+ });
1343
+ }
1344
+ async getAuth(cacheKey, clientId) {
1345
+ if (!clientId) {
1346
+ return;
1347
+ }
1348
+ return this.runTask(cacheKey, async (task) => {
1349
+ return await this._triggerClient.getAuth(clientId);
1350
+ }, {
1351
+ name: "get-auth"
1352
+ });
1353
+ }
1354
+ async parallel(cacheKey, items, callback, options) {
1355
+ const results = await this.runTask(cacheKey, async (task) => {
1356
+ const outcomes = await Promise.allSettled(items.map((item, index) => spaceOut(() => callback(item, index), index, 15)));
1357
+ if (outcomes.every((outcome) => outcome.status === "fulfilled")) {
1358
+ return outcomes.map((outcome) => outcome.value);
1359
+ }
1360
+ const nonInternalErrors = outcomes.filter((outcome) => outcome.status === "rejected" && !isTriggerError(outcome.reason)).map((outcome) => outcome);
1361
+ if (nonInternalErrors.length > 0) {
1362
+ throw nonInternalErrors[0].reason;
1363
+ }
1364
+ const internalErrors = outcomes.filter((outcome) => outcome.status === "rejected" && isTriggerError(outcome.reason)).map((outcome) => outcome).map((outcome) => outcome.reason);
1365
+ throw new ResumeWithParallelTaskError(task, internalErrors);
1366
+ }, {
1367
+ name: "parallel",
1368
+ parallel: true,
1369
+ ...options ?? {}
1370
+ });
1371
+ return results;
1372
+ }
1373
+ /** `io.runTask()` allows you to run a [Task](https://trigger.dev/docs/documentation/concepts/tasks) from inside a Job run. A Task is a resumable unit of a Run that can be retried, resumed and is logged. [Integrations](https://trigger.dev/docs/integrations) use Tasks internally to perform their actions.
1374
+ *
1375
+ * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
1376
+ * @param callback The callback that will be called when the Task is run. The callback receives the Task and the IO as parameters.
1377
+ * @param options The options of how you'd like to run and log the Task.
1378
+ * @param onError The callback that will be called when the Task fails. The callback receives the error, the Task and the IO as parameters. If you wish to retry then return an object with a `retryAt` property.
1379
+ * @returns A Promise that resolves with the returned value of the callback.
1380
+ */
1381
+ async runTask(cacheKey, callback, options, onError) {
1382
+ __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "start_task", 500);
1383
+ const parentId = this._taskStorage.getStore()?.taskId;
1384
+ if (parentId) {
1385
+ this._logger.debug("Using parent task", {
1386
+ parentId,
1387
+ cacheKey,
1388
+ options
1389
+ });
1390
+ }
1391
+ const idempotencyKey = await generateIdempotencyKey([
1392
+ this._id,
1393
+ parentId ?? "",
1394
+ cacheKey
1395
+ ].flat());
1396
+ if (this._visitedCacheKeys.has(idempotencyKey)) {
1397
+ if (typeof cacheKey === "string") {
1398
+ throw new Error(`Task with cacheKey "${cacheKey}" has already been executed in this run. Each task must have a unique cacheKey.`);
1399
+ } else {
1400
+ throw new Error(`Task with cacheKey "${cacheKey.join("-")}" has already been executed in this run. Each task must have a unique cacheKey.`);
1401
+ }
1402
+ }
1403
+ this._visitedCacheKeys.add(idempotencyKey);
1404
+ const cachedTask = this._cachedTasks.get(idempotencyKey);
1405
+ if (cachedTask && cachedTask.status === "COMPLETED") {
1406
+ this._logger.debug("Using completed cached task", {
1407
+ idempotencyKey
1408
+ });
1409
+ this._stats.cachedTaskHits++;
1410
+ return options?.parseOutput ? options.parseOutput(cachedTask.output) : cachedTask.output;
1411
+ }
1412
+ if (options?.noop && this._noopTasksBloomFilter) {
1413
+ if (this._noopTasksBloomFilter.test(idempotencyKey)) {
1414
+ this._logger.debug("task idempotency key exists in noopTasksBloomFilter", {
1415
+ idempotencyKey
1416
+ });
1417
+ this._stats.noopCachedTaskHits++;
1418
+ return {};
1419
+ }
1420
+ }
1421
+ const runOptions = {
1422
+ ...options ?? {},
1423
+ parseOutput: void 0
1424
+ };
1425
+ const response = await this._apiClient.runTask(this._id, {
1426
+ idempotencyKey,
1427
+ displayKey: typeof cacheKey === "string" ? cacheKey : void 0,
1428
+ noop: false,
1429
+ ...runOptions ?? {},
1430
+ parentId
1431
+ }, {
1432
+ cachedTasksCursor: this._cachedTasksCursor
1433
+ });
1434
+ const task = response.version === API_VERSIONS.LAZY_LOADED_CACHED_TASKS ? response.body.task : response.body;
1435
+ if (task.forceYield) {
1436
+ this._logger.debug("Forcing yield after run task", {
1437
+ idempotencyKey
1438
+ });
1439
+ __privateMethod(this, _forceYield, forceYield_fn).call(this, "after_run_task");
1440
+ }
1441
+ if (response.version === API_VERSIONS.LAZY_LOADED_CACHED_TASKS) {
1442
+ this._cachedTasksCursor = response.body.cachedTasks?.cursor;
1443
+ for (const cachedTask2 of response.body.cachedTasks?.tasks ?? []) {
1444
+ if (!this._cachedTasks.has(cachedTask2.idempotencyKey)) {
1445
+ this._cachedTasks.set(cachedTask2.idempotencyKey, cachedTask2);
1446
+ this._logger.debug("Injecting lazy loaded task into task cache", {
1447
+ idempotencyKey: cachedTask2.idempotencyKey
1448
+ });
1449
+ this._stats.lazyLoadedCachedTasks++;
1450
+ }
1451
+ }
1452
+ }
1453
+ if (task.status === "CANCELED") {
1454
+ this._logger.debug("Task canceled", {
1455
+ idempotencyKey,
1456
+ task
1457
+ });
1458
+ throw new CanceledWithTaskError(task);
1459
+ }
1460
+ if (task.status === "COMPLETED") {
1461
+ if (task.noop) {
1462
+ this._logger.debug("Noop Task completed", {
1463
+ idempotencyKey
1464
+ });
1465
+ this._noopTasksBloomFilter?.add(task.idempotencyKey);
1466
+ } else {
1467
+ this._logger.debug("Cache miss", {
1468
+ idempotencyKey
1469
+ });
1470
+ this._stats.cachedTaskMisses++;
1471
+ __privateMethod(this, _addToCachedTasks, addToCachedTasks_fn).call(this, task);
1472
+ }
1473
+ return options?.parseOutput ? options.parseOutput(task.output) : task.output;
1474
+ }
1475
+ if (task.status === "ERRORED") {
1476
+ this._logger.debug("Task errored", {
1477
+ idempotencyKey,
1478
+ task
1479
+ });
1480
+ throw new ErrorWithTask(task, task.error ?? task?.output ? JSON.stringify(task.output) : "Task errored");
1481
+ }
1482
+ __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "before_execute_task", 1500);
1483
+ const executeTask = /* @__PURE__ */ __name(async () => {
1484
+ try {
1485
+ const result = await callback(task, this);
1486
+ if (task.status === "WAITING" && task.callbackUrl) {
1487
+ this._logger.debug("Waiting for remote callback", {
1488
+ idempotencyKey,
1489
+ task
1490
+ });
1491
+ return {};
1492
+ }
1493
+ const output = this._outputSerializer.serialize(result);
1494
+ this._logger.debug("Completing using output", {
1495
+ idempotencyKey,
1496
+ task
1497
+ });
1498
+ __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "before_complete_task", 500, task, output);
1499
+ const completedTask = await this._apiClient.completeTask(this._id, task.id, {
1500
+ output,
1501
+ properties: task.outputProperties ?? void 0
1502
+ });
1503
+ if (completedTask.forceYield) {
1504
+ this._logger.debug("Forcing yield after task completed", {
1505
+ idempotencyKey
1506
+ });
1507
+ __privateMethod(this, _forceYield, forceYield_fn).call(this, "after_complete_task");
1508
+ }
1509
+ this._stats.executedTasks++;
1510
+ if (completedTask.status === "CANCELED") {
1511
+ throw new CanceledWithTaskError(completedTask);
1512
+ }
1513
+ __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "after_complete_task", 500);
1514
+ const deserializedOutput = this._outputSerializer.deserialize(output);
1515
+ return options?.parseOutput ? options.parseOutput(deserializedOutput) : deserializedOutput;
1516
+ } catch (error) {
1517
+ if (isTriggerError(error)) {
1518
+ throw error;
1519
+ }
1520
+ let skipRetrying = false;
1521
+ if (onError) {
1522
+ try {
1523
+ const onErrorResult = onError(error, task, this);
1524
+ if (onErrorResult) {
1525
+ if (onErrorResult instanceof Error) {
1526
+ error = onErrorResult;
1527
+ } else {
1528
+ skipRetrying = !!onErrorResult.skipRetrying;
1529
+ if (onErrorResult.retryAt && !skipRetrying) {
1530
+ const parsedError2 = ErrorWithStackSchema.safeParse(onErrorResult.error);
1531
+ throw new RetryWithTaskError(parsedError2.success ? parsedError2.data : {
1532
+ message: "Unknown error"
1533
+ }, task, onErrorResult.retryAt);
1534
+ }
1535
+ }
1536
+ }
1537
+ } catch (innerError) {
1538
+ if (isTriggerError(innerError)) {
1539
+ throw innerError;
1540
+ }
1541
+ error = innerError;
1542
+ }
1543
+ }
1544
+ if (error instanceof ErrorWithTask) {
1545
+ await this._apiClient.failTask(this._id, task.id, {
1546
+ error: error.cause.output
1547
+ });
1548
+ }
1549
+ const parsedError = ErrorWithStackSchema.safeParse(error);
1550
+ if (options?.retry && !skipRetrying) {
1551
+ const retryAt = calculateRetryAt(options.retry, task.attempts - 1);
1552
+ if (retryAt) {
1553
+ throw new RetryWithTaskError(parsedError.success ? parsedError.data : {
1554
+ message: "Unknown error"
1555
+ }, task, retryAt);
1556
+ }
1557
+ }
1558
+ if (parsedError.success) {
1559
+ await this._apiClient.failTask(this._id, task.id, {
1560
+ error: parsedError.data
1561
+ });
1562
+ } else {
1563
+ const message = typeof error === "string" ? error : JSON.stringify(error);
1564
+ await this._apiClient.failTask(this._id, task.id, {
1565
+ error: {
1566
+ name: "Unknown error",
1567
+ message
1568
+ }
1569
+ });
1570
+ }
1571
+ throw error;
1572
+ }
1573
+ }, "executeTask");
1574
+ if (task.status === "WAITING") {
1575
+ this._logger.debug("Task waiting", {
1576
+ idempotencyKey,
1577
+ task
1578
+ });
1579
+ if (task.callbackUrl) {
1580
+ await this._taskStorage.run({
1581
+ taskId: task.id
1582
+ }, executeTask);
1583
+ }
1584
+ throw new ResumeWithTaskError(task);
1585
+ }
1586
+ if (task.status === "RUNNING" && typeof task.operation === "string") {
1587
+ this._logger.debug("Task running operation", {
1588
+ idempotencyKey,
1589
+ task
1590
+ });
1591
+ throw new ResumeWithTaskError(task);
1592
+ }
1593
+ return this._taskStorage.run({
1594
+ taskId: task.id
1595
+ }, executeTask);
1596
+ }
1597
+ /**
1598
+ * `io.yield()` allows you to yield execution of the current run and resume it in a new function execution. Similar to `io.wait()` but does not create a task and resumes execution immediately.
1599
+ */
1600
+ yield(cacheKey) {
1601
+ if (!supportsFeature("yieldExecution", this._serverVersion)) {
1602
+ 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.");
1603
+ return;
1604
+ }
1605
+ if (this._yieldedExecutions.includes(cacheKey)) {
1606
+ return;
1607
+ }
1608
+ throw new YieldExecutionError(cacheKey);
1609
+ }
1610
+ /** `io.try()` allows you to run Tasks and catch any errors that are thrown, it's similar to a normal `try/catch` block but works with [io.runTask()](https://trigger.dev/docs/sdk/io/runtask).
1611
+ * A regular `try/catch` block on its own won't work as expected with Tasks. Internally `runTask()` throws some special errors to control flow execution. This is necessary to deal with resumability, serverless timeouts, and retrying Tasks.
1612
+ * @param tryCallback The code you wish to run
1613
+ * @param catchCallback Thhis will be called if the Task fails. The callback receives the error
1614
+ * @returns A Promise that resolves with the returned value or the error
1615
+ */
1616
+ async try(tryCallback, catchCallback) {
1617
+ try {
1618
+ return await tryCallback();
1619
+ } catch (error) {
1620
+ if (isTriggerError(error)) {
1621
+ throw error;
1622
+ }
1623
+ return await catchCallback(error);
1624
+ }
1625
+ }
1626
+ get store() {
1627
+ return {
1628
+ env: this._envStore,
1629
+ job: this._jobStore,
1630
+ run: this._runStore
1631
+ };
1632
+ }
1633
+ };
1634
+ _addToCachedTasks = new WeakSet();
1635
+ addToCachedTasks_fn = /* @__PURE__ */ __name(function(task) {
1636
+ this._cachedTasks.set(task.idempotencyKey, task);
1637
+ }, "#addToCachedTasks");
1638
+ _detectAutoYield = new WeakSet();
1639
+ detectAutoYield_fn = /* @__PURE__ */ __name(function(location, threshold = 1500, task1, output) {
1640
+ const timeRemaining = __privateMethod(this, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn).call(this);
1641
+ if (timeRemaining && timeRemaining < threshold) {
1642
+ if (task1) {
1643
+ throw new AutoYieldWithCompletedTaskExecutionError(task1.id, task1.outputProperties ?? [], {
1644
+ location,
1645
+ timeRemaining,
1646
+ timeElapsed: __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this)
1647
+ }, output);
1648
+ } else {
1649
+ throw new AutoYieldExecutionError(location, timeRemaining, __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this));
1650
+ }
1651
+ }
1652
+ }, "#detectAutoYield");
1653
+ _forceYield = new WeakSet();
1654
+ forceYield_fn = /* @__PURE__ */ __name(function(location1) {
1655
+ const timeRemaining = __privateMethod(this, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn).call(this);
1656
+ if (timeRemaining) {
1657
+ throw new AutoYieldExecutionError(location1, timeRemaining, __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this));
1658
+ }
1659
+ }, "#forceYield");
1660
+ _getTimeElapsed = new WeakSet();
1661
+ getTimeElapsed_fn = /* @__PURE__ */ __name(function() {
1662
+ return performance.now() - this._timeOrigin;
1663
+ }, "#getTimeElapsed");
1664
+ _getRemainingTimeInMillis = new WeakSet();
1665
+ getRemainingTimeInMillis_fn = /* @__PURE__ */ __name(function() {
1666
+ if (this._executionTimeout) {
1667
+ return this._executionTimeout - (performance.now() - this._timeOrigin);
1668
+ }
1669
+ return void 0;
1670
+ }, "#getRemainingTimeInMillis");
1671
+ __name(_IO, "IO");
1672
+ var IO = _IO;
1673
+ async function generateIdempotencyKey(keyMaterial) {
1674
+ const keys = keyMaterial.map((key2) => {
1675
+ if (typeof key2 === "string") {
1676
+ return key2;
1677
+ }
1678
+ return stableStringify(key2);
1679
+ });
1680
+ const key = keys.join(":");
1681
+ const hash = await webcrypto.subtle.digest("SHA-256", Buffer.from(key));
1682
+ return Buffer.from(hash).toString("hex");
1683
+ }
1684
+ __name(generateIdempotencyKey, "generateIdempotencyKey");
1685
+ function stableStringify(obj) {
1686
+ function sortKeys(obj2) {
1687
+ if (typeof obj2 !== "object" || obj2 === null) {
1688
+ return obj2;
1689
+ }
1690
+ if (Array.isArray(obj2)) {
1691
+ return obj2.map(sortKeys);
1692
+ }
1693
+ const sortedKeys = Object.keys(obj2).sort();
1694
+ const sortedObj2 = {};
1695
+ for (const key of sortedKeys) {
1696
+ sortedObj2[key] = sortKeys(obj2[key]);
1697
+ }
1698
+ return sortedObj2;
1699
+ }
1700
+ __name(sortKeys, "sortKeys");
1701
+ const sortedObj = sortKeys(obj);
1702
+ return JSON.stringify(sortedObj);
1703
+ }
1704
+ __name(stableStringify, "stableStringify");
1705
+ var _IOLogger = class _IOLogger {
1706
+ constructor(callback) {
1707
+ this.callback = callback;
1708
+ }
1709
+ /** Log: essential messages */
1710
+ log(message, properties) {
1711
+ return this.callback("LOG", message, properties);
1712
+ }
1713
+ /** For debugging: the least important log level */
1714
+ debug(message, properties) {
1715
+ return this.callback("DEBUG", message, properties);
1716
+ }
1717
+ /** Info: the second least important log level */
1718
+ info(message, properties) {
1719
+ return this.callback("INFO", message, properties);
1720
+ }
1721
+ /** Warnings: the third most important log level */
1722
+ warn(message, properties) {
1723
+ return this.callback("WARN", message, properties);
1724
+ }
1725
+ /** Error: The second most important log level */
1726
+ error(message, properties) {
1727
+ return this.callback("ERROR", message, properties);
1728
+ }
1729
+ };
1730
+ __name(_IOLogger, "IOLogger");
1731
+ var IOLogger = _IOLogger;
1732
+ async function spaceOut(callback, index, delay) {
1733
+ await new Promise((resolve) => setTimeout(resolve, index * delay));
1734
+ return await callback();
1735
+ }
1736
+ __name(spaceOut, "spaceOut");
1737
+ function sendEventOptionsProperties(options) {
1738
+ return [
1739
+ ...options?.accountId ? [
1740
+ {
1741
+ label: "Account ID",
1742
+ text: options.accountId
1743
+ }
1744
+ ] : [],
1745
+ ...options?.deliverAfter ? [
1746
+ {
1747
+ label: "Deliver After",
1748
+ text: `${options.deliverAfter}s`
1749
+ }
1750
+ ] : [],
1751
+ ...options?.deliverAt ? [
1752
+ {
1753
+ label: "Deliver At",
1754
+ text: options.deliverAt.toISOString()
1755
+ }
1756
+ ] : []
1757
+ ];
1758
+ }
1759
+ __name(sendEventOptionsProperties, "sendEventOptionsProperties");
1760
+
1761
+ // src/store/keyValueStoreClient.ts
1762
+ var _serializer, _namespacedKey2, namespacedKey_fn2;
1763
+ var _KeyValueStoreClient = class _KeyValueStoreClient {
1764
+ constructor(queryStore, type = null, namespace = "") {
1765
+ __privateAdd(this, _namespacedKey2);
1766
+ __privateAdd(this, _serializer, void 0);
1767
+ this.queryStore = queryStore;
1768
+ this.type = type;
1769
+ this.namespace = namespace;
1770
+ __privateSet(this, _serializer, new JSONOutputSerializer());
1771
+ }
1772
+ async delete(key) {
1773
+ const result = await this.queryStore("DELETE", {
1774
+ key: __privateMethod(this, _namespacedKey2, namespacedKey_fn2).call(this, key)
1775
+ });
1776
+ if (result.action !== "DELETE") {
1777
+ throw new Error(`Unexpected key-value store response: ${result.action}`);
1778
+ }
1779
+ return result.deleted;
1780
+ }
1781
+ async get(key) {
1782
+ const result = await this.queryStore("GET", {
1783
+ key: __privateMethod(this, _namespacedKey2, namespacedKey_fn2).call(this, key)
1784
+ });
1785
+ if (result.action !== "GET") {
1786
+ throw new Error(`Unexpected key-value store response: ${result.action}`);
1787
+ }
1788
+ return __privateGet(this, _serializer).deserialize(result.value);
1789
+ }
1790
+ async has(key) {
1791
+ const result = await this.queryStore("HAS", {
1792
+ key: __privateMethod(this, _namespacedKey2, namespacedKey_fn2).call(this, key)
1793
+ });
1794
+ if (result.action !== "HAS") {
1795
+ throw new Error(`Unexpected key-value store response: ${result.action}`);
1796
+ }
1797
+ return result.has;
1798
+ }
1799
+ async set(key, value) {
1800
+ const result = await this.queryStore("SET", {
1801
+ key: __privateMethod(this, _namespacedKey2, namespacedKey_fn2).call(this, key),
1802
+ value: __privateGet(this, _serializer).serialize(value)
1803
+ });
1804
+ if (result.action !== "SET") {
1805
+ throw new Error(`Unexpected key-value store response: ${result.action}`);
1806
+ }
1807
+ return __privateGet(this, _serializer).deserialize(result.value);
1808
+ }
1809
+ };
1810
+ _serializer = new WeakMap();
1811
+ _namespacedKey2 = new WeakSet();
1812
+ namespacedKey_fn2 = /* @__PURE__ */ __name(function(key) {
1813
+ const parts = [];
1814
+ if (this.type) {
1815
+ parts.push(this.type);
1816
+ }
1817
+ if (this.namespace) {
1818
+ parts.push(this.namespace);
1819
+ }
1820
+ parts.push(key);
1821
+ return parts.join(":");
1822
+ }, "#namespacedKey");
1823
+ __name(_KeyValueStoreClient, "KeyValueStoreClient");
1824
+ var KeyValueStoreClient = _KeyValueStoreClient;
1825
+
1826
+ // src/apiClient.ts
1827
+ var _apiUrl, _options, _logger, _storeClient, _queryKeyValueStore, queryKeyValueStore_fn, _apiKey, apiKey_fn;
1828
+ var _ApiClient = class _ApiClient {
1829
+ constructor(options) {
1830
+ __privateAdd(this, _queryKeyValueStore);
1831
+ __privateAdd(this, _apiKey);
1832
+ __privateAdd(this, _apiUrl, void 0);
1833
+ __privateAdd(this, _options, void 0);
1834
+ __privateAdd(this, _logger, void 0);
1835
+ __privateAdd(this, _storeClient, void 0);
1836
+ __privateSet(this, _options, options);
1837
+ __privateSet(this, _apiUrl, __privateGet(this, _options).apiUrl ?? env.TRIGGER_API_URL ?? "https://api.trigger.dev");
1838
+ __privateSet(this, _logger, new Logger("trigger.dev", __privateGet(this, _options).logLevel));
1839
+ __privateSet(this, _storeClient, new KeyValueStoreClient(__privateMethod(this, _queryKeyValueStore, queryKeyValueStore_fn).bind(this)));
1840
+ }
1841
+ async registerEndpoint(options) {
1842
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1843
+ __privateGet(this, _logger).debug("Registering endpoint", {
1844
+ url: options.url,
1845
+ name: options.name
1846
+ });
1847
+ const response = await fetch(`${__privateGet(this, _apiUrl)}/api/v1/endpoints`, {
1848
+ method: "POST",
1849
+ headers: {
1850
+ "Content-Type": "application/json",
1851
+ Authorization: `Bearer ${apiKey}`
1852
+ },
1853
+ body: JSON.stringify({
1854
+ url: options.url,
1855
+ name: options.name
1856
+ })
1857
+ });
1858
+ if (response.status >= 400 && response.status < 500) {
1859
+ const body = await response.json();
1860
+ throw new Error(body.error);
1861
+ }
1862
+ if (response.status !== 200) {
1863
+ throw new Error(`Failed to register entry point, got status code ${response.status}`);
1864
+ }
1865
+ return await response.json();
1866
+ }
1867
+ async runTask(runId, task, options = {}) {
1868
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1869
+ __privateGet(this, _logger).debug("Running Task", {
1870
+ task
1871
+ });
1872
+ return await zodfetchWithVersions({
1873
+ [API_VERSIONS.LAZY_LOADED_CACHED_TASKS]: RunTaskResponseWithCachedTasksBodySchema
1874
+ }, ServerTaskSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/tasks`, {
1875
+ method: "POST",
1876
+ headers: {
1877
+ "Content-Type": "application/json",
1878
+ Authorization: `Bearer ${apiKey}`,
1879
+ "Idempotency-Key": task.idempotencyKey,
1880
+ "X-Cached-Tasks-Cursor": options.cachedTasksCursor ?? "",
1881
+ "Trigger-Version": API_VERSIONS.LAZY_LOADED_CACHED_TASKS
1882
+ },
1883
+ body: JSON.stringify(task)
1884
+ });
1885
+ }
1886
+ async completeTask(runId, id, task) {
1887
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1888
+ __privateGet(this, _logger).debug("Complete Task", {
1889
+ task
1890
+ });
1891
+ return await zodfetch(ServerTaskSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/tasks/${id}/complete`, {
1892
+ method: "POST",
1893
+ headers: {
1894
+ "Content-Type": "application/json",
1895
+ Authorization: `Bearer ${apiKey}`,
1896
+ "Trigger-Version": API_VERSIONS.SERIALIZED_TASK_OUTPUT
1897
+ },
1898
+ body: JSON.stringify(task)
1899
+ });
1900
+ }
1901
+ async failTask(runId, id, body) {
1902
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1903
+ __privateGet(this, _logger).debug("Fail Task", {
1904
+ id,
1905
+ runId,
1906
+ body
1907
+ });
1908
+ return await zodfetch(ServerTaskSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/tasks/${id}/fail`, {
1909
+ method: "POST",
1910
+ headers: {
1911
+ "Content-Type": "application/json",
1912
+ Authorization: `Bearer ${apiKey}`
1913
+ },
1914
+ body: JSON.stringify(body)
1915
+ });
1916
+ }
1917
+ async sendEvent(event, options = {}) {
1918
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1919
+ __privateGet(this, _logger).debug("Sending event", {
1920
+ event
1921
+ });
1922
+ return await zodfetch(ApiEventLogSchema, `${__privateGet(this, _apiUrl)}/api/v1/events`, {
1923
+ method: "POST",
1924
+ headers: {
1925
+ "Content-Type": "application/json",
1926
+ Authorization: `Bearer ${apiKey}`
1927
+ },
1928
+ body: JSON.stringify({
1929
+ event,
1930
+ options
1931
+ })
1932
+ });
1933
+ }
1934
+ async sendEvents(events, options = {}) {
1935
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1936
+ __privateGet(this, _logger).debug("Sending multiple events", {
1937
+ events
1938
+ });
1939
+ return await zodfetch(ApiEventLogSchema.array(), `${__privateGet(this, _apiUrl)}/api/v1/events/bulk`, {
1940
+ method: "POST",
1941
+ headers: {
1942
+ "Content-Type": "application/json",
1943
+ Authorization: `Bearer ${apiKey}`
1944
+ },
1945
+ body: JSON.stringify({
1946
+ events,
1947
+ options
1948
+ })
1949
+ });
1950
+ }
1951
+ async cancelEvent(eventId) {
1952
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1953
+ __privateGet(this, _logger).debug("Cancelling event", {
1954
+ eventId
1955
+ });
1956
+ return await zodfetch(ApiEventLogSchema, `${__privateGet(this, _apiUrl)}/api/v1/events/${eventId}/cancel`, {
1957
+ method: "POST",
1958
+ headers: {
1959
+ "Content-Type": "application/json",
1960
+ Authorization: `Bearer ${apiKey}`
1961
+ }
1962
+ });
1963
+ }
1964
+ async cancelRunsForEvent(eventId) {
1965
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1966
+ __privateGet(this, _logger).debug("Cancelling runs for event", {
1967
+ eventId
1968
+ });
1969
+ return await zodfetch(CancelRunsForEventSchema, `${__privateGet(this, _apiUrl)}/api/v1/events/${eventId}/cancel-runs`, {
1970
+ method: "POST",
1971
+ headers: {
1972
+ "Content-Type": "application/json",
1973
+ Authorization: `Bearer ${apiKey}`
1974
+ }
1975
+ });
1976
+ }
1977
+ async updateStatus(runId, id, status) {
1978
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1979
+ __privateGet(this, _logger).debug("Update status", {
1980
+ id,
1981
+ status
1982
+ });
1983
+ return await zodfetch(JobRunStatusRecordSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/statuses/${id}`, {
1984
+ method: "PUT",
1985
+ headers: {
1986
+ "Content-Type": "application/json",
1987
+ Authorization: `Bearer ${apiKey}`
1988
+ },
1989
+ body: JSON.stringify(status)
1990
+ });
1991
+ }
1992
+ async updateSource(client, key, source) {
1993
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1994
+ __privateGet(this, _logger).debug("activating http source", {
1995
+ source
1996
+ });
1997
+ const response = await zodfetch(TriggerSourceSchema, `${__privateGet(this, _apiUrl)}/api/v2/${client}/sources/${key}`, {
1998
+ method: "PUT",
1999
+ headers: {
2000
+ "Content-Type": "application/json",
2001
+ Authorization: `Bearer ${apiKey}`
2002
+ },
2003
+ body: JSON.stringify(source)
2004
+ });
2005
+ return response;
2006
+ }
2007
+ async updateWebhook(key, webhookData) {
2008
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2009
+ __privateGet(this, _logger).debug("activating webhook", {
2010
+ webhookData
2011
+ });
2012
+ const response = await zodfetch(TriggerSourceSchema, `${__privateGet(this, _apiUrl)}/api/v1/webhooks/${key}`, {
2013
+ method: "PUT",
2014
+ headers: {
2015
+ "Content-Type": "application/json",
2016
+ Authorization: `Bearer ${apiKey}`
2017
+ },
2018
+ body: JSON.stringify(webhookData)
2019
+ });
2020
+ return response;
2021
+ }
2022
+ async registerTrigger(client, id, key, payload, idempotencyKey) {
2023
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2024
+ __privateGet(this, _logger).debug("registering trigger", {
2025
+ id,
2026
+ payload
2027
+ });
2028
+ const headers = {
2029
+ "Content-Type": "application/json",
2030
+ Authorization: `Bearer ${apiKey}`
2031
+ };
2032
+ if (idempotencyKey) {
2033
+ headers["Idempotency-Key"] = idempotencyKey;
2034
+ }
2035
+ const response = await zodfetch(RegisterSourceEventSchemaV2, `${__privateGet(this, _apiUrl)}/api/v2/${client}/triggers/${id}/registrations/${key}`, {
2036
+ method: "PUT",
2037
+ headers,
2038
+ body: JSON.stringify(payload)
2039
+ });
2040
+ return response;
2041
+ }
2042
+ async registerSchedule(client, id, key, payload) {
2043
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2044
+ __privateGet(this, _logger).debug("registering schedule", {
2045
+ id,
2046
+ payload
2047
+ });
2048
+ const response = await zodfetch(RegisterScheduleResponseBodySchema, `${__privateGet(this, _apiUrl)}/api/v1/${client}/schedules/${id}/registrations`, {
2049
+ method: "POST",
2050
+ headers: {
2051
+ "Content-Type": "application/json",
2052
+ Authorization: `Bearer ${apiKey}`
2053
+ },
2054
+ body: JSON.stringify({
2055
+ id: key,
2056
+ ...payload
2057
+ })
2058
+ });
2059
+ return response;
2060
+ }
2061
+ async unregisterSchedule(client, id, key) {
2062
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2063
+ __privateGet(this, _logger).debug("unregistering schedule", {
2064
+ id
2065
+ });
2066
+ const response = await zodfetch(z.object({
2067
+ ok: z.boolean()
2068
+ }), `${__privateGet(this, _apiUrl)}/api/v1/${client}/schedules/${id}/registrations/${encodeURIComponent(key)}`, {
2069
+ method: "DELETE",
2070
+ headers: {
2071
+ "Content-Type": "application/json",
2072
+ Authorization: `Bearer ${apiKey}`
2073
+ }
2074
+ });
2075
+ return response;
2076
+ }
2077
+ async getAuth(client, id) {
2078
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2079
+ __privateGet(this, _logger).debug("getting auth", {
2080
+ id
2081
+ });
2082
+ const response = await zodfetch(ConnectionAuthSchema, `${__privateGet(this, _apiUrl)}/api/v1/${client}/auth/${id}`, {
2083
+ method: "GET",
2084
+ headers: {
2085
+ Accept: "application/json",
2086
+ Authorization: `Bearer ${apiKey}`
2087
+ }
2088
+ }, {
2089
+ optional: true
2090
+ });
2091
+ return response;
2092
+ }
2093
+ async getEvent(eventId) {
2094
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2095
+ __privateGet(this, _logger).debug("Getting Event", {
2096
+ eventId
2097
+ });
2098
+ return await zodfetch(GetEventSchema, `${__privateGet(this, _apiUrl)}/api/v1/events/${eventId}`, {
2099
+ method: "GET",
2100
+ headers: {
2101
+ Authorization: `Bearer ${apiKey}`
2102
+ }
2103
+ });
2104
+ }
2105
+ async getRun(runId, options) {
2106
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2107
+ __privateGet(this, _logger).debug("Getting Run", {
2108
+ runId
2109
+ });
2110
+ return await zodfetch(GetRunSchema, urlWithSearchParams(`${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}`, options), {
2111
+ method: "GET",
2112
+ headers: {
2113
+ Authorization: `Bearer ${apiKey}`
2114
+ }
2115
+ });
2116
+ }
2117
+ async cancelRun(runId) {
2118
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2119
+ __privateGet(this, _logger).debug("Cancelling Run", {
2120
+ runId
2121
+ });
2122
+ return await zodfetch(GetRunSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/cancel`, {
2123
+ method: "POST",
2124
+ headers: {
2125
+ "Content-Type": "application/json",
2126
+ Authorization: `Bearer ${apiKey}`
2127
+ }
2128
+ });
2129
+ }
2130
+ async getRunStatuses(runId) {
2131
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2132
+ __privateGet(this, _logger).debug("Getting Run statuses", {
2133
+ runId
2134
+ });
2135
+ return await zodfetch(GetRunStatusesSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/statuses`, {
2136
+ method: "GET",
2137
+ headers: {
2138
+ Authorization: `Bearer ${apiKey}`
2139
+ }
2140
+ });
2141
+ }
2142
+ async getRuns(jobSlug, options) {
2143
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2144
+ __privateGet(this, _logger).debug("Getting Runs", {
2145
+ jobSlug
2146
+ });
2147
+ return await zodfetch(GetRunsSchema, urlWithSearchParams(`${__privateGet(this, _apiUrl)}/api/v1/jobs/${jobSlug}/runs`, options), {
2148
+ method: "GET",
2149
+ headers: {
2150
+ Authorization: `Bearer ${apiKey}`
2151
+ }
2152
+ });
2153
+ }
2154
+ async invokeJob(jobId, payload, options = {}) {
2155
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2156
+ __privateGet(this, _logger).debug("Invoking Job", {
2157
+ jobId
2158
+ });
2159
+ const body = {
2160
+ payload,
2161
+ context: options.context ?? {},
2162
+ options: {
2163
+ accountId: options.accountId,
2164
+ callbackUrl: options.callbackUrl
2165
+ }
2166
+ };
2167
+ return await zodfetch(InvokeJobResponseSchema, `${__privateGet(this, _apiUrl)}/api/v1/jobs/${jobId}/invoke`, {
2168
+ method: "POST",
2169
+ headers: {
2170
+ "Content-Type": "application/json",
2171
+ Authorization: `Bearer ${apiKey}`,
2172
+ ...options.idempotencyKey ? {
2173
+ "Idempotency-Key": options.idempotencyKey
2174
+ } : {}
2175
+ },
2176
+ body: JSON.stringify(body)
2177
+ });
2178
+ }
2179
+ async createEphemeralEventDispatcher(payload) {
2180
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2181
+ __privateGet(this, _logger).debug("Creating ephemeral event dispatcher", {
2182
+ payload
2183
+ });
2184
+ const response = await zodfetch(EphemeralEventDispatcherResponseBodySchema, `${__privateGet(this, _apiUrl)}/api/v1/event-dispatchers/ephemeral`, {
2185
+ method: "POST",
2186
+ headers: {
2187
+ "Content-Type": "application/json",
2188
+ Authorization: `Bearer ${apiKey}`
2189
+ },
2190
+ body: JSON.stringify(payload)
2191
+ });
2192
+ return response;
2193
+ }
2194
+ get store() {
2195
+ return __privateGet(this, _storeClient);
2196
+ }
2197
+ };
2198
+ _apiUrl = new WeakMap();
2199
+ _options = new WeakMap();
2200
+ _logger = new WeakMap();
2201
+ _storeClient = new WeakMap();
2202
+ _queryKeyValueStore = new WeakSet();
2203
+ queryKeyValueStore_fn = /* @__PURE__ */ __name(async function(action, data) {
2204
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2205
+ __privateGet(this, _logger).debug("accessing key-value store", {
2206
+ action,
2207
+ data
2208
+ });
2209
+ const encodedKey = encodeURIComponent(data.key);
2210
+ const STORE_URL = `${__privateGet(this, _apiUrl)}/api/v1/store/${encodedKey}`;
2211
+ const authHeader = {
2212
+ Authorization: `Bearer ${apiKey}`
2213
+ };
2214
+ let requestInit;
2215
+ switch (action) {
2216
+ case "DELETE": {
2217
+ requestInit = {
2218
+ method: "DELETE",
2219
+ headers: authHeader
2220
+ };
2221
+ break;
2222
+ }
2223
+ case "GET": {
2224
+ requestInit = {
2225
+ method: "GET",
2226
+ headers: authHeader
2227
+ };
2228
+ break;
2229
+ }
2230
+ case "HAS": {
2231
+ const headResponse = await fetchHead(STORE_URL, {
2232
+ headers: authHeader
2233
+ });
2234
+ return {
2235
+ action: "HAS",
2236
+ key: encodedKey,
2237
+ has: !!headResponse.ok
2238
+ };
2239
+ }
2240
+ case "SET": {
2241
+ const MAX_BODY_BYTE_LENGTH = 256 * 1024;
2242
+ if ((data.value?.length ?? 0) > MAX_BODY_BYTE_LENGTH) {
2243
+ throw new Error(`Max request body size exceeded: ${MAX_BODY_BYTE_LENGTH} bytes`);
2244
+ }
2245
+ requestInit = {
2246
+ method: "PUT",
2247
+ headers: {
2248
+ ...authHeader,
2249
+ "Content-Type": "text/plain"
2250
+ },
2251
+ body: data.value
2252
+ };
2253
+ break;
2254
+ }
2255
+ default: {
2256
+ assertExhaustive(action);
2257
+ }
2258
+ }
2259
+ const response = await zodfetch(KeyValueStoreResponseBodySchema, STORE_URL, requestInit);
2260
+ return response;
2261
+ }, "#queryKeyValueStore");
2262
+ _apiKey = new WeakSet();
2263
+ apiKey_fn = /* @__PURE__ */ __name(async function() {
2264
+ const apiKey = getApiKey(__privateGet(this, _options).apiKey);
2265
+ if (apiKey.status === "invalid") {
2266
+ throw new Error("Invalid API key");
2267
+ } else if (apiKey.status === "missing") {
2268
+ throw new Error("Missing API key");
2269
+ }
2270
+ return apiKey.apiKey;
2271
+ }, "#apiKey");
2272
+ __name(_ApiClient, "ApiClient");
2273
+ var ApiClient = _ApiClient;
2274
+ function getApiKey(key) {
2275
+ const apiKey = key ?? env.TRIGGER_API_KEY;
2276
+ if (!apiKey) {
2277
+ return {
2278
+ status: "missing"
2279
+ };
2280
+ }
2281
+ const isValid = apiKey.match(/^tr_[a-z]+_[a-zA-Z0-9]+$/);
2282
+ if (!isValid) {
2283
+ return {
2284
+ status: "invalid",
2285
+ apiKey
2286
+ };
2287
+ }
2288
+ return {
2289
+ status: "valid",
2290
+ apiKey
2291
+ };
2292
+ }
2293
+ __name(getApiKey, "getApiKey");
2294
+ async function zodfetchWithVersions(versionedSchemaMap, unversionedSchema, url, requestInit, options, retryCount = 0) {
2295
+ const response = await fetch(url, requestInitWithCache(requestInit));
2296
+ if ((!requestInit || requestInit.method === "GET") && response.status === 404 && options?.optional) {
2297
+ return;
2298
+ }
2299
+ if (response.status >= 400 && response.status < 500) {
2300
+ const body = await response.json();
2301
+ throw new Error(body.error);
2302
+ }
2303
+ if (response.status >= 500 && retryCount < 6) {
2304
+ const delay = exponentialBackoff(retryCount + 1, 2, 50, 1150, 50);
2305
+ await new Promise((resolve) => setTimeout(resolve, delay));
2306
+ return zodfetchWithVersions(versionedSchemaMap, unversionedSchema, url, requestInit, options, retryCount + 1);
2307
+ }
2308
+ if (response.status !== 200) {
2309
+ throw new Error(options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`);
2310
+ }
2311
+ const jsonBody = await response.json();
2312
+ const version2 = response.headers.get("trigger-version");
2313
+ if (!version2) {
2314
+ return {
2315
+ version: "unversioned",
2316
+ body: unversionedSchema.parse(jsonBody)
2317
+ };
2318
+ }
2319
+ const versionedSchema = versionedSchemaMap[version2];
2320
+ if (!versionedSchema) {
2321
+ throw new Error(`Unknown version ${version2}`);
2322
+ }
2323
+ return {
2324
+ version: version2,
2325
+ body: versionedSchema.parse(jsonBody)
2326
+ };
2327
+ }
2328
+ __name(zodfetchWithVersions, "zodfetchWithVersions");
2329
+ function requestInitWithCache(requestInit) {
2330
+ try {
2331
+ const withCache = {
2332
+ ...requestInit,
2333
+ cache: "no-cache"
2334
+ };
2335
+ const _ = new Request("http://localhost", withCache);
2336
+ return withCache;
2337
+ } catch (error) {
2338
+ return requestInit ?? {};
2339
+ }
2340
+ }
2341
+ __name(requestInitWithCache, "requestInitWithCache");
2342
+ async function fetchHead(url, requestInitWithoutMethod, retryCount = 0) {
2343
+ const requestInit = {
2344
+ ...requestInitWithoutMethod,
2345
+ method: "HEAD"
2346
+ };
2347
+ const response = await fetch(url, requestInitWithCache(requestInit));
2348
+ if (response.status >= 500 && retryCount < 6) {
2349
+ const delay = exponentialBackoff(retryCount + 1, 2, 50, 1150, 50);
2350
+ await new Promise((resolve) => setTimeout(resolve, delay));
2351
+ return fetchHead(url, requestInitWithoutMethod, retryCount + 1);
2352
+ }
2353
+ return response;
2354
+ }
2355
+ __name(fetchHead, "fetchHead");
2356
+ async function zodfetch(schema, url, requestInit, options, retryCount = 0) {
2357
+ const response = await fetch(url, requestInitWithCache(requestInit));
2358
+ if ((!requestInit || requestInit.method === "GET") && response.status === 404 && options?.optional) {
2359
+ return;
2360
+ }
2361
+ if (response.status >= 400 && response.status < 500) {
2362
+ const body = await response.json();
2363
+ throw new Error(body.error);
2364
+ }
2365
+ if (response.status >= 500 && retryCount < 6) {
2366
+ const delay = exponentialBackoff(retryCount + 1, 2, 50, 1150, 50);
2367
+ await new Promise((resolve) => setTimeout(resolve, delay));
2368
+ return zodfetch(schema, url, requestInit, options, retryCount + 1);
2369
+ }
2370
+ if (response.status !== 200) {
2371
+ throw new Error(options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`);
2372
+ }
2373
+ const jsonBody = await response.json();
2374
+ return schema.parse(jsonBody);
2375
+ }
2376
+ __name(zodfetch, "zodfetch");
2377
+ function exponentialBackoff(retryCount, exponential, minDelay, maxDelay, jitter) {
2378
+ const delay = Math.min(Math.pow(exponential, retryCount) * minDelay, maxDelay);
2379
+ const jitterValue = Math.random() * jitter;
2380
+ return delay + jitterValue;
2381
+ }
2382
+ __name(exponentialBackoff, "exponentialBackoff");
2383
+
2384
+ // src/concurrencyLimit.ts
2385
+ var _ConcurrencyLimit = class _ConcurrencyLimit {
2386
+ constructor(options) {
2387
+ this.options = options;
2388
+ }
2389
+ get id() {
2390
+ return this.options.id;
2391
+ }
2392
+ get limit() {
2393
+ return this.options.limit;
2394
+ }
2395
+ };
2396
+ __name(_ConcurrencyLimit, "ConcurrencyLimit");
2397
+ var ConcurrencyLimit = _ConcurrencyLimit;
2398
+
2399
+ // src/utils/formatSchemaErrors.ts
2400
+ function formatSchemaErrors(errors) {
2401
+ return errors.map((error) => {
2402
+ const { path, message } = error;
2403
+ return {
2404
+ path: path.map(String),
2405
+ message
2406
+ };
2407
+ });
2408
+ }
2409
+ __name(formatSchemaErrors, "formatSchemaErrors");
2410
+
2411
+ // src/httpEndpoint.ts
2412
+ var _HttpEndpoint = class _HttpEndpoint {
2413
+ constructor(options) {
2414
+ this.options = options;
2415
+ }
2416
+ get id() {
2417
+ return this.options.id;
2418
+ }
2419
+ onRequest(options) {
2420
+ return new HttpTrigger({
2421
+ endpointId: this.id,
2422
+ event: this.options.event,
2423
+ filter: options?.filter,
2424
+ verify: this.options.verify
2425
+ });
2426
+ }
2427
+ // @internal
2428
+ async handleRequest(request) {
2429
+ if (!this.options.respondWith)
2430
+ return;
2431
+ return this.options.respondWith.handler(request, () => {
2432
+ const clonedRequest = request.clone();
2433
+ return this.options.verify(clonedRequest);
2434
+ });
2435
+ }
2436
+ toJSON() {
2437
+ return {
2438
+ id: this.id,
2439
+ icon: this.options.event.icon,
2440
+ version: "1",
2441
+ enabled: this.options.enabled ?? true,
2442
+ event: this.options.event,
2443
+ immediateResponseFilter: this.options.respondWith?.filter,
2444
+ skipTriggeringRuns: this.options.respondWith?.skipTriggeringRuns,
2445
+ source: this.options.event.source
2446
+ };
2447
+ }
2448
+ };
2449
+ __name(_HttpEndpoint, "HttpEndpoint");
2450
+ var HttpEndpoint = _HttpEndpoint;
2451
+ var _a;
2452
+ var HttpTrigger = (_a = class {
2453
+ constructor(options) {
2454
+ this.options = options;
2455
+ }
2456
+ toJSON() {
2457
+ return {
2458
+ type: "static",
2459
+ title: this.options.endpointId,
2460
+ properties: this.options.event.properties,
2461
+ rule: {
2462
+ event: `httpendpoint.${this.options.endpointId}`,
2463
+ payload: this.options.filter ?? {},
2464
+ source: this.options.event.source
2465
+ },
2466
+ link: `http-endpoints/${this.options.endpointId}`,
2467
+ help: {
2468
+ noRuns: {
2469
+ text: "To start triggering runs click here to setup your HTTP Endpoint with the external API service you want to receive webhooks from.",
2470
+ link: `http-endpoints/${this.options.endpointId}`
2471
+ }
2472
+ }
2473
+ };
2474
+ }
2475
+ get event() {
2476
+ return this.options.event;
2477
+ }
2478
+ attachToJob(triggerClient, job) {
2479
+ }
2480
+ get preprocessRuns() {
2481
+ return false;
2482
+ }
2483
+ async verifyPayload(payload) {
2484
+ const clonedRequest = payload.clone();
2485
+ return this.options.verify(clonedRequest);
2486
+ }
2487
+ }, __name(_a, "HttpTrigger"), _a);
2488
+ function httpEndpoint(options) {
2489
+ const id = slugifyId(options.id);
2490
+ return new HttpEndpoint({
2491
+ id,
2492
+ enabled: options.enabled,
2493
+ respondWith: options.respondWith,
2494
+ verify: options.verify,
2495
+ event: {
2496
+ name: id,
2497
+ title: options.title ?? "HTTP Trigger",
2498
+ source: options.source,
2499
+ icon: options.icon ?? "webhook",
2500
+ properties: options.properties,
2501
+ examples: options.examples ? options.examples : [
2502
+ {
2503
+ id: "basic-request",
2504
+ name: "Basic Request",
2505
+ icon: "http-post",
2506
+ payload: {
2507
+ url: "https://cloud.trigger.dev",
2508
+ method: "POST",
2509
+ headers: {
2510
+ "Content-Type": "application/json"
2511
+ },
2512
+ rawBody: JSON.stringify({
2513
+ foo: "bar"
2514
+ })
2515
+ }
2516
+ }
2517
+ ],
2518
+ parsePayload: (rawPayload) => {
2519
+ const result = RequestWithRawBodySchema.safeParse(rawPayload);
2520
+ if (!result.success) {
2521
+ throw new ParsedPayloadSchemaError(formatSchemaErrors(result.error.issues));
2522
+ }
2523
+ return new Request(new URL(result.data.url), {
2524
+ method: result.data.method,
2525
+ headers: result.data.headers,
2526
+ body: result.data.rawBody
2527
+ });
2528
+ }
2529
+ }
2530
+ });
2531
+ }
2532
+ __name(httpEndpoint, "httpEndpoint");
2533
+
2534
+ // src/ioWithIntegrations.ts
2535
+ function createIOWithIntegrations(io, auths, integrations) {
2536
+ if (!integrations) {
2537
+ return io;
2538
+ }
2539
+ const connections = Object.entries(integrations).reduce((acc, [connectionKey, integration]) => {
2540
+ let auth = auths?.[connectionKey];
2541
+ acc[connectionKey] = {
2542
+ integration,
2543
+ auth
2544
+ };
2545
+ return acc;
2546
+ }, {});
2547
+ return new Proxy(io, {
2548
+ get(target, prop, receiver) {
2549
+ if (prop === "__io") {
2550
+ return io;
2551
+ }
2552
+ if (typeof prop === "string" && prop in connections) {
2553
+ const { integration, auth } = connections[prop];
2554
+ return integration.cloneForRun(io, prop, auth);
2555
+ }
2556
+ const value = Reflect.get(target, prop, receiver);
2557
+ return typeof value == "function" ? value.bind(target) : value;
2558
+ }
2559
+ });
2560
+ }
2561
+ __name(createIOWithIntegrations, "createIOWithIntegrations");
2562
+ var _client, _options2;
2563
+ var _DynamicTrigger = class _DynamicTrigger {
2564
+ /** `DynamicTrigger` allows you to define a trigger that can be configured dynamically at runtime.
2565
+ * @param client The `TriggerClient` instance to use for registering the trigger.
2566
+ * @param options The options for the dynamic trigger.
2567
+ * */
2568
+ constructor(client, options) {
2569
+ __privateAdd(this, _client, void 0);
2570
+ __privateAdd(this, _options2, void 0);
2571
+ __privateSet(this, _client, client);
2572
+ __privateSet(this, _options2, options);
2573
+ this.source = options.source;
2574
+ client.attachDynamicTrigger(this);
2575
+ }
2576
+ toJSON() {
2577
+ return {
2578
+ type: "dynamic",
2579
+ id: __privateGet(this, _options2).id
2580
+ };
2581
+ }
2582
+ get id() {
2583
+ return __privateGet(this, _options2).id;
2584
+ }
2585
+ get event() {
2586
+ return __privateGet(this, _options2).event;
2587
+ }
2588
+ // @internal
2589
+ registeredTriggerForParams(params, options = {}) {
2590
+ const key = slugifyId(this.source.key(params));
2591
+ return {
2592
+ rule: {
2593
+ event: this.event.name,
2594
+ source: this.event.source,
2595
+ payload: deepMergeFilters(this.source.filter(params), this.event.filter ?? {}, options.filter ?? {})
2596
+ },
2597
+ source: {
2598
+ version: "2",
2599
+ key,
2600
+ channel: this.source.channel,
2601
+ params,
2602
+ //todo add other options here
2603
+ options: {
2604
+ event: typeof this.event.name === "string" ? [
2605
+ this.event.name
2606
+ ] : this.event.name
2607
+ },
2608
+ integration: {
2609
+ id: this.source.integration.id,
2610
+ metadata: this.source.integration.metadata,
2611
+ authSource: this.source.integration.authSource
2612
+ }
2613
+ },
2614
+ accountId: options.accountId
2615
+ };
2616
+ }
2617
+ /** Use this method to register a new configuration with the DynamicTrigger.
2618
+ * @param key The key for the configuration. This will be used to identify the configuration when it is triggered.
2619
+ * @param params The params for the configuration.
2620
+ * @param options Options for the configuration.
2621
+ * @param options.accountId The accountId to associate with the configuration.
2622
+ * @param options.filter The filter to use for the configuration.
2623
+ *
2624
+ */
2625
+ async register(key, params, options = {}) {
2626
+ const runStore = runLocalStorage.getStore();
2627
+ if (!runStore) {
2628
+ return __privateGet(this, _client).registerTrigger(this.id, key, this.registeredTriggerForParams(params, options));
2629
+ }
2630
+ const { io } = runStore;
2631
+ return await io.runTask([
2632
+ key,
2633
+ "register"
2634
+ ], async (task) => {
2635
+ return __privateGet(this, _client).registerTrigger(this.id, key, this.registeredTriggerForParams(params, options), task.idempotencyKey);
2636
+ }, {
2637
+ name: "Register Dynamic Trigger",
2638
+ properties: [
2639
+ {
2640
+ label: "Dynamic Trigger ID",
2641
+ text: this.id
2642
+ },
2643
+ {
2644
+ label: "ID",
2645
+ text: key
2646
+ }
2647
+ ],
2648
+ params
2649
+ });
2650
+ }
2651
+ attachToJob(triggerClient, job) {
2652
+ triggerClient.attachJobToDynamicTrigger(job, this);
2653
+ }
2654
+ get preprocessRuns() {
2655
+ return true;
2656
+ }
2657
+ async verifyPayload(payload) {
2658
+ return {
2659
+ success: true
2660
+ };
2661
+ }
2662
+ };
2663
+ _client = new WeakMap();
2664
+ _options2 = new WeakMap();
2665
+ __name(_DynamicTrigger, "DynamicTrigger");
2666
+ var DynamicTrigger = _DynamicTrigger;
2667
+ var _options3;
2668
+ var _EventTrigger = class _EventTrigger {
2669
+ constructor(options) {
2670
+ __privateAdd(this, _options3, void 0);
2671
+ __privateSet(this, _options3, options);
2672
+ }
2673
+ toJSON() {
2674
+ return {
2675
+ type: "static",
2676
+ title: __privateGet(this, _options3).name ?? __privateGet(this, _options3).event.title,
2677
+ rule: {
2678
+ event: __privateGet(this, _options3).name ?? __privateGet(this, _options3).event.name,
2679
+ source: __privateGet(this, _options3).source ?? "trigger.dev",
2680
+ payload: deepMergeFilters(__privateGet(this, _options3).filter ?? {}, __privateGet(this, _options3).event.filter ?? {})
2681
+ }
2682
+ };
2683
+ }
2684
+ get event() {
2685
+ return __privateGet(this, _options3).event;
2686
+ }
2687
+ attachToJob(triggerClient, job) {
2688
+ }
2689
+ get preprocessRuns() {
2690
+ return false;
2691
+ }
2692
+ async verifyPayload(payload) {
2693
+ if (__privateGet(this, _options3).verify) {
2694
+ if (payload instanceof Request) {
2695
+ const clonedRequest = payload.clone();
2696
+ return __privateGet(this, _options3).verify(clonedRequest);
2697
+ }
2698
+ }
2699
+ return {
2700
+ success: true
2701
+ };
2702
+ }
2703
+ };
2704
+ _options3 = new WeakMap();
2705
+ __name(_EventTrigger, "EventTrigger");
2706
+ var EventTrigger = _EventTrigger;
2707
+ function eventTrigger(options) {
2708
+ return new EventTrigger({
2709
+ name: options.name,
2710
+ filter: options.filter,
2711
+ event: {
2712
+ name: options.name,
2713
+ title: "Event",
2714
+ source: options.source ?? "trigger.dev",
2715
+ icon: "custom-event",
2716
+ examples: options.examples,
2717
+ parsePayload: (rawPayload) => {
2718
+ if (options.schema) {
2719
+ const results = options.schema.safeParse(rawPayload);
2720
+ if (!results.success) {
2721
+ throw new ParsedPayloadSchemaError(formatSchemaErrors(results.error.issues));
2722
+ }
2723
+ return results.data;
2724
+ }
2725
+ return rawPayload;
2726
+ }
2727
+ }
2728
+ });
2729
+ }
2730
+ __name(eventTrigger, "eventTrigger");
2731
+ var examples = [
2732
+ {
2733
+ id: "now",
2734
+ name: "Now",
2735
+ icon: "clock",
2736
+ payload: {
2737
+ ts: currentDate.marker,
2738
+ lastTimestamp: currentDate.marker
2739
+ }
2740
+ }
2741
+ ];
2742
+ var _IntervalTrigger = class _IntervalTrigger {
2743
+ constructor(options) {
2744
+ this.options = options;
2745
+ }
2746
+ get event() {
2747
+ return {
2748
+ name: "trigger.scheduled",
2749
+ title: "Schedule",
2750
+ source: "trigger.dev",
2751
+ icon: "schedule-interval",
2752
+ examples,
2753
+ parsePayload: ScheduledPayloadSchema.parse,
2754
+ properties: [
2755
+ {
2756
+ label: "Interval",
2757
+ text: `${this.options.seconds}s`
2758
+ }
2759
+ ]
2760
+ };
2761
+ }
2762
+ attachToJob(triggerClient, job) {
2763
+ }
2764
+ get preprocessRuns() {
2765
+ return false;
2766
+ }
2767
+ async verifyPayload(payload) {
2768
+ return {
2769
+ success: true
2770
+ };
2771
+ }
2772
+ toJSON() {
2773
+ return {
2774
+ type: "scheduled",
2775
+ schedule: {
2776
+ type: "interval",
2777
+ options: {
2778
+ seconds: this.options.seconds
2779
+ }
2780
+ }
2781
+ };
2782
+ }
2783
+ };
2784
+ __name(_IntervalTrigger, "IntervalTrigger");
2785
+ var IntervalTrigger = _IntervalTrigger;
2786
+ function intervalTrigger(options) {
2787
+ return new IntervalTrigger(options);
2788
+ }
2789
+ __name(intervalTrigger, "intervalTrigger");
2790
+ var _CronTrigger = class _CronTrigger {
2791
+ constructor(options) {
2792
+ this.options = options;
2793
+ }
2794
+ get event() {
2795
+ const humanReadable = cronstrue.toString(this.options.cron, {
2796
+ throwExceptionOnParseError: false
2797
+ });
2798
+ return {
2799
+ name: "trigger.scheduled",
2800
+ title: "Cron Schedule",
2801
+ source: "trigger.dev",
2802
+ icon: "schedule-cron",
2803
+ examples,
2804
+ parsePayload: ScheduledPayloadSchema.parse,
2805
+ properties: [
2806
+ {
2807
+ label: "cron",
2808
+ text: this.options.cron
2809
+ },
2810
+ {
2811
+ label: "Schedule",
2812
+ text: humanReadable
2813
+ }
2814
+ ]
2815
+ };
2816
+ }
2817
+ attachToJob(triggerClient, job) {
2818
+ }
2819
+ get preprocessRuns() {
2820
+ return false;
2821
+ }
2822
+ async verifyPayload(payload) {
2823
+ return {
2824
+ success: true
2825
+ };
2826
+ }
2827
+ toJSON() {
2828
+ return {
2829
+ type: "scheduled",
2830
+ schedule: {
2831
+ type: "cron",
2832
+ options: {
2833
+ cron: this.options.cron
2834
+ }
2835
+ }
2836
+ };
2837
+ }
2838
+ };
2839
+ __name(_CronTrigger, "CronTrigger");
2840
+ var CronTrigger = _CronTrigger;
2841
+ function cronTrigger(options) {
2842
+ return new CronTrigger(options);
2843
+ }
2844
+ __name(cronTrigger, "cronTrigger");
2845
+ var _DynamicSchedule = class _DynamicSchedule {
2846
+ /**
2847
+ * @param client The `TriggerClient` instance to use for registering the trigger.
2848
+ * @param options The options for the schedule.
2849
+ */
2850
+ constructor(client, options) {
2851
+ this.client = client;
2852
+ this.options = options;
2853
+ client.attachDynamicSchedule(this.options.id);
2854
+ }
2855
+ get id() {
2856
+ return this.options.id;
2857
+ }
2858
+ get event() {
2859
+ return {
2860
+ name: "trigger.scheduled",
2861
+ title: "Dynamic Schedule",
2862
+ source: "trigger.dev",
2863
+ icon: "schedule-dynamic",
2864
+ examples,
2865
+ parsePayload: ScheduledPayloadSchema.parse
2866
+ };
2867
+ }
2868
+ async register(key, metadata) {
2869
+ const runStore = runLocalStorage.getStore();
2870
+ if (!runStore) {
2871
+ return this.client.registerSchedule(this.id, key, metadata);
2872
+ }
2873
+ const { io } = runStore;
2874
+ return await io.runTask([
2875
+ key,
2876
+ "register"
2877
+ ], async (task) => {
2878
+ return this.client.registerSchedule(this.id, key, metadata);
2879
+ }, {
2880
+ name: "Register Schedule",
2881
+ icon: metadata.type === "cron" ? "schedule-cron" : "schedule-interval",
2882
+ properties: [
2883
+ {
2884
+ label: "Dynamic Schedule",
2885
+ text: this.id
2886
+ },
2887
+ {
2888
+ label: "Schedule ID",
2889
+ text: key
2890
+ }
2891
+ ],
2892
+ params: metadata
2893
+ });
2894
+ }
2895
+ async unregister(key) {
2896
+ const runStore = runLocalStorage.getStore();
2897
+ if (!runStore) {
2898
+ return this.client.unregisterSchedule(this.id, key);
2899
+ }
2900
+ const { io } = runStore;
2901
+ return await io.runTask([
2902
+ key,
2903
+ "unregister"
2904
+ ], async (task) => {
2905
+ return this.client.unregisterSchedule(this.id, key);
2906
+ }, {
2907
+ name: "Unregister Schedule",
2908
+ icon: "schedule",
2909
+ properties: [
2910
+ {
2911
+ label: "Dynamic Schedule",
2912
+ text: this.id
2913
+ },
2914
+ {
2915
+ label: "Schedule ID",
2916
+ text: key
2917
+ }
2918
+ ]
2919
+ });
2920
+ }
2921
+ attachToJob(triggerClient, job) {
2922
+ triggerClient.attachDynamicScheduleToJob(this.options.id, job);
2923
+ }
2924
+ get preprocessRuns() {
2925
+ return false;
2926
+ }
2927
+ async verifyPayload(payload) {
2928
+ return {
2929
+ success: true
2930
+ };
2931
+ }
2932
+ toJSON() {
2933
+ return {
2934
+ type: "dynamic",
2935
+ id: this.options.id
2936
+ };
2937
+ }
2938
+ };
2939
+ __name(_DynamicSchedule, "DynamicSchedule");
2940
+ var DynamicSchedule = _DynamicSchedule;
2941
+
2942
+ // src/triggerClient.ts
2943
+ var registerWebhookEvent = /* @__PURE__ */ __name((key) => ({
2944
+ name: `${REGISTER_WEBHOOK}.${key}`,
2945
+ title: "Register Webhook",
2946
+ source: "internal",
2947
+ icon: "webhook",
2948
+ parsePayload: RegisterWebhookPayloadSchema.parse
2949
+ }), "registerWebhookEvent");
2950
+ var registerSourceEvent = {
2951
+ name: REGISTER_SOURCE_EVENT_V2,
2952
+ title: "Register Source",
2953
+ source: "internal",
2954
+ icon: "register-source",
2955
+ parsePayload: RegisterSourceEventSchemaV2.parse
2956
+ };
2957
+ 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;
2958
+ var _TriggerClient = class _TriggerClient {
2959
+ constructor(options) {
2960
+ __privateAdd(this, _preprocessRun);
2961
+ __privateAdd(this, _executeJob);
2962
+ __privateAdd(this, _convertErrorToExecutionResponse);
2963
+ __privateAdd(this, _createRunContext);
2964
+ __privateAdd(this, _createPreprocessRunContext);
2965
+ __privateAdd(this, _handleHttpSourceRequest);
2966
+ __privateAdd(this, _handleHttpEndpointRequestForResponse);
2967
+ __privateAdd(this, _handleWebhookRequest);
2968
+ __privateAdd(this, _resolveConnections);
2969
+ __privateAdd(this, _resolveConnection);
2970
+ __privateAdd(this, _buildJobsIndex);
2971
+ __privateAdd(this, _buildJobIndex);
2972
+ __privateAdd(this, _buildJobIntegrations);
2973
+ __privateAdd(this, _buildJobIntegration);
2974
+ __privateAdd(this, _logIOStats);
2975
+ __privateAdd(this, _standardResponseHeaders);
2976
+ __privateAdd(this, _serializeRunMetadata);
2977
+ __privateAdd(this, _deliverSuccessfulRunNotification);
2978
+ __privateAdd(this, _deliverFailedRunNotification);
2979
+ __privateAdd(this, _options4, void 0);
2980
+ __privateAdd(this, _registeredJobs, {});
2981
+ __privateAdd(this, _registeredSources, {});
2982
+ __privateAdd(this, _registeredWebhooks, {});
2983
+ __privateAdd(this, _registeredHttpSourceHandlers, {});
2984
+ __privateAdd(this, _registeredWebhookSourceHandlers, {});
2985
+ __privateAdd(this, _registeredDynamicTriggers, {});
2986
+ __privateAdd(this, _jobMetadataByDynamicTriggers, {});
2987
+ __privateAdd(this, _registeredSchedules, {});
2988
+ __privateAdd(this, _registeredHttpEndpoints, {});
2989
+ __privateAdd(this, _authResolvers, {});
2990
+ __privateAdd(this, _envStore, void 0);
2991
+ __privateAdd(this, _eventEmitter, new EventEmitter());
2992
+ __privateAdd(this, _client2, void 0);
2993
+ __privateAdd(this, _internalLogger, void 0);
2994
+ __publicField(this, "on", __privateGet(this, _eventEmitter).on.bind(__privateGet(this, _eventEmitter)));
2995
+ this.id = options.id;
2996
+ __privateSet(this, _options4, options);
2997
+ __privateSet(this, _client2, new ApiClient(__privateGet(this, _options4)));
2998
+ __privateSet(this, _internalLogger, new Logger("trigger.dev", __privateGet(this, _options4).verbose ? "debug" : "log", [
2999
+ "output",
3000
+ "noopTasksSet"
3001
+ ]));
3002
+ __privateSet(this, _envStore, new KeyValueStore(__privateGet(this, _client2)));
3003
+ }
3004
+ async handleRequest(request, timeOrigin = performance.now()) {
3005
+ __privateGet(this, _internalLogger).debug("handling request", {
3006
+ url: request.url,
3007
+ headers: Object.fromEntries(request.headers.entries()),
3008
+ method: request.method
3009
+ });
3010
+ const apiKey = request.headers.get("x-trigger-api-key");
3011
+ const triggerVersion = request.headers.get("x-trigger-version");
3012
+ const authorization = this.authorized(apiKey);
3013
+ switch (authorization) {
3014
+ case "authorized": {
3015
+ break;
3016
+ }
3017
+ case "missing-client": {
3018
+ return {
3019
+ status: 401,
3020
+ body: {
3021
+ message: "Unauthorized: client missing apiKey"
3022
+ },
3023
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3024
+ };
3025
+ }
3026
+ case "missing-header": {
3027
+ return {
3028
+ status: 401,
3029
+ body: {
3030
+ message: "Unauthorized: missing x-trigger-api-key header"
3031
+ },
3032
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3033
+ };
3034
+ }
3035
+ case "unauthorized": {
3036
+ return {
3037
+ status: 401,
3038
+ body: {
3039
+ message: `Forbidden: client apiKey mismatch: Make sure you are using the correct API Key for your environment`
3040
+ },
3041
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3042
+ };
3043
+ }
3044
+ }
3045
+ if (request.method !== "POST") {
3046
+ return {
3047
+ status: 405,
3048
+ body: {
3049
+ message: "Method not allowed (only POST is allowed)"
3050
+ },
3051
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3052
+ };
3053
+ }
3054
+ const action = request.headers.get("x-trigger-action");
3055
+ if (!action) {
3056
+ return {
3057
+ status: 400,
3058
+ body: {
3059
+ message: "Missing x-trigger-action header"
3060
+ },
3061
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3062
+ };
3063
+ }
3064
+ switch (action) {
3065
+ case "PING": {
3066
+ const endpointId = request.headers.get("x-trigger-endpoint-id");
3067
+ if (!endpointId) {
3068
+ return {
3069
+ status: 200,
3070
+ body: {
3071
+ ok: false,
3072
+ error: "Missing endpoint ID"
3073
+ },
3074
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3075
+ };
3076
+ }
3077
+ if (this.id !== endpointId) {
3078
+ return {
3079
+ status: 200,
3080
+ body: {
3081
+ ok: false,
3082
+ error: `Endpoint ID mismatch error. Expected ${this.id}, got ${endpointId}`
3083
+ },
3084
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3085
+ };
3086
+ }
3087
+ return {
3088
+ status: 200,
3089
+ body: {
3090
+ ok: true
3091
+ },
3092
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3093
+ };
3094
+ }
3095
+ case "INDEX_ENDPOINT": {
3096
+ const body = {
3097
+ jobs: __privateMethod(this, _buildJobsIndex, buildJobsIndex_fn).call(this),
3098
+ sources: Object.values(__privateGet(this, _registeredSources)),
3099
+ webhooks: Object.values(__privateGet(this, _registeredWebhooks)),
3100
+ dynamicTriggers: Object.values(__privateGet(this, _registeredDynamicTriggers)).map((trigger) => ({
3101
+ id: trigger.id,
3102
+ jobs: __privateGet(this, _jobMetadataByDynamicTriggers)[trigger.id] ?? [],
3103
+ registerSourceJob: {
3104
+ id: dynamicTriggerRegisterSourceJobId(trigger.id),
3105
+ version: trigger.source.version
3106
+ }
3107
+ })),
3108
+ dynamicSchedules: Object.entries(__privateGet(this, _registeredSchedules)).map(([id, jobs]) => ({
3109
+ id,
3110
+ jobs
3111
+ })),
3112
+ httpEndpoints: Object.entries(__privateGet(this, _registeredHttpEndpoints)).map(([id, endpoint]) => endpoint.toJSON())
3113
+ };
3114
+ return {
3115
+ status: 200,
3116
+ body,
3117
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3118
+ };
3119
+ }
3120
+ case "INITIALIZE_TRIGGER": {
3121
+ const json = await request.json();
3122
+ const body = InitializeTriggerBodySchema.safeParse(json);
3123
+ if (!body.success) {
3124
+ return {
3125
+ status: 400,
3126
+ body: {
3127
+ message: "Invalid trigger body"
3128
+ }
3129
+ };
3130
+ }
3131
+ const dynamicTrigger = __privateGet(this, _registeredDynamicTriggers)[body.data.id];
3132
+ if (!dynamicTrigger) {
3133
+ return {
3134
+ status: 404,
3135
+ body: {
3136
+ message: "Dynamic trigger not found"
3137
+ }
3138
+ };
3139
+ }
3140
+ return {
3141
+ status: 200,
3142
+ body: dynamicTrigger.registeredTriggerForParams(body.data.params),
3143
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3144
+ };
3145
+ }
3146
+ case "EXECUTE_JOB": {
3147
+ const json = await request.json();
3148
+ const execution = RunJobBodySchema.safeParse(json);
3149
+ if (!execution.success) {
3150
+ return {
3151
+ status: 400,
3152
+ body: {
3153
+ message: "Invalid execution"
3154
+ }
3155
+ };
3156
+ }
3157
+ const job = __privateGet(this, _registeredJobs)[execution.data.job.id];
3158
+ if (!job) {
3159
+ return {
3160
+ status: 404,
3161
+ body: {
3162
+ message: "Job not found"
3163
+ }
3164
+ };
3165
+ }
3166
+ const results = await __privateMethod(this, _executeJob, executeJob_fn).call(this, execution.data, job, timeOrigin, triggerVersion);
3167
+ __privateGet(this, _internalLogger).debug("executed job", {
3168
+ results,
3169
+ job: job.id,
3170
+ version: job.version,
3171
+ triggerVersion
3172
+ });
3173
+ const standardHeaders = __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin);
3174
+ standardHeaders["x-trigger-run-metadata"] = __privateMethod(this, _serializeRunMetadata, serializeRunMetadata_fn).call(this, job);
3175
+ return {
3176
+ status: 200,
3177
+ body: results,
3178
+ headers: standardHeaders
3179
+ };
3180
+ }
3181
+ case "PREPROCESS_RUN": {
3182
+ const json = await request.json();
3183
+ const body = PreprocessRunBodySchema.safeParse(json);
3184
+ if (!body.success) {
3185
+ return {
3186
+ status: 400,
3187
+ body: {
3188
+ message: "Invalid body"
3189
+ }
3190
+ };
3191
+ }
3192
+ const job = __privateGet(this, _registeredJobs)[body.data.job.id];
3193
+ if (!job) {
3194
+ return {
3195
+ status: 404,
3196
+ body: {
3197
+ message: "Job not found"
3198
+ }
3199
+ };
3200
+ }
3201
+ const results = await __privateMethod(this, _preprocessRun, preprocessRun_fn).call(this, body.data, job);
3202
+ return {
3203
+ status: 200,
3204
+ body: {
3205
+ abort: results.abort,
3206
+ properties: results.properties
3207
+ },
3208
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3209
+ };
3210
+ }
3211
+ case "DELIVER_HTTP_SOURCE_REQUEST": {
3212
+ const headers = HttpSourceRequestHeadersSchema.safeParse(Object.fromEntries(request.headers.entries()));
3213
+ if (!headers.success) {
3214
+ return {
3215
+ status: 400,
3216
+ body: {
3217
+ message: "Invalid headers"
3218
+ }
3219
+ };
3220
+ }
3221
+ const sourceRequestNeedsBody = headers.data["x-ts-http-method"] !== "GET";
3222
+ const sourceRequestInit = {
3223
+ method: headers.data["x-ts-http-method"],
3224
+ headers: headers.data["x-ts-http-headers"],
3225
+ body: sourceRequestNeedsBody ? request.body : void 0
3226
+ };
3227
+ if (sourceRequestNeedsBody) {
3228
+ try {
3229
+ sourceRequestInit.duplex = "half";
3230
+ } catch (error) {
3231
+ }
3232
+ }
3233
+ const sourceRequest = new Request(headers.data["x-ts-http-url"], sourceRequestInit);
3234
+ const key = headers.data["x-ts-key"];
3235
+ const dynamicId = headers.data["x-ts-dynamic-id"];
3236
+ const secret = headers.data["x-ts-secret"];
3237
+ const params = headers.data["x-ts-params"];
3238
+ const data = headers.data["x-ts-data"];
3239
+ const auth = headers.data["x-ts-auth"];
3240
+ const inputMetadata = headers.data["x-ts-metadata"];
3241
+ const source = {
3242
+ key,
3243
+ dynamicId,
3244
+ secret,
3245
+ params,
3246
+ data,
3247
+ auth,
3248
+ metadata: inputMetadata
3249
+ };
3250
+ const { response, events, metadata } = await __privateMethod(this, _handleHttpSourceRequest, handleHttpSourceRequest_fn).call(this, source, sourceRequest);
3251
+ return {
3252
+ status: 200,
3253
+ body: {
3254
+ events,
3255
+ response,
3256
+ metadata
3257
+ },
3258
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3259
+ };
3260
+ }
3261
+ case "DELIVER_HTTP_ENDPOINT_REQUEST_FOR_RESPONSE": {
3262
+ const headers = HttpEndpointRequestHeadersSchema.safeParse(Object.fromEntries(request.headers.entries()));
3263
+ if (!headers.success) {
3264
+ return {
3265
+ status: 400,
3266
+ body: {
3267
+ message: "Invalid headers"
3268
+ }
3269
+ };
3270
+ }
3271
+ const sourceRequestNeedsBody = headers.data["x-ts-http-method"] !== "GET";
3272
+ const sourceRequestInit = {
3273
+ method: headers.data["x-ts-http-method"],
3274
+ headers: headers.data["x-ts-http-headers"],
3275
+ body: sourceRequestNeedsBody ? request.body : void 0
3276
+ };
3277
+ if (sourceRequestNeedsBody) {
3278
+ try {
3279
+ sourceRequestInit.duplex = "half";
3280
+ } catch (error) {
3281
+ }
3282
+ }
3283
+ const sourceRequest = new Request(headers.data["x-ts-http-url"], sourceRequestInit);
3284
+ const key = headers.data["x-ts-key"];
3285
+ const { response } = await __privateMethod(this, _handleHttpEndpointRequestForResponse, handleHttpEndpointRequestForResponse_fn).call(this, {
3286
+ key
3287
+ }, sourceRequest);
3288
+ return {
3289
+ status: 200,
3290
+ body: response,
3291
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3292
+ };
3293
+ }
3294
+ case "DELIVER_WEBHOOK_REQUEST": {
3295
+ const headers = WebhookSourceRequestHeadersSchema.safeParse(Object.fromEntries(request.headers.entries()));
3296
+ if (!headers.success) {
3297
+ return {
3298
+ status: 400,
3299
+ body: {
3300
+ message: "Invalid headers"
3301
+ }
3302
+ };
3303
+ }
3304
+ const sourceRequestNeedsBody = headers.data["x-ts-http-method"] !== "GET";
3305
+ const sourceRequestInit = {
3306
+ method: headers.data["x-ts-http-method"],
3307
+ headers: headers.data["x-ts-http-headers"],
3308
+ body: sourceRequestNeedsBody ? request.body : void 0
3309
+ };
3310
+ if (sourceRequestNeedsBody) {
3311
+ try {
3312
+ sourceRequestInit.duplex = "half";
3313
+ } catch (error2) {
3314
+ }
3315
+ }
3316
+ const webhookRequest = new Request(headers.data["x-ts-http-url"], sourceRequestInit);
3317
+ const key = headers.data["x-ts-key"];
3318
+ const secret = headers.data["x-ts-secret"];
3319
+ const params = headers.data["x-ts-params"];
3320
+ const ctx = {
3321
+ key,
3322
+ secret,
3323
+ params
3324
+ };
3325
+ const { response, verified, error } = await __privateMethod(this, _handleWebhookRequest, handleWebhookRequest_fn).call(this, webhookRequest, ctx);
3326
+ return {
3327
+ status: 200,
3328
+ body: {
3329
+ response,
3330
+ verified,
3331
+ error
3332
+ },
3333
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3334
+ };
3335
+ }
3336
+ case "VALIDATE": {
3337
+ return {
3338
+ status: 200,
3339
+ body: {
3340
+ ok: true,
3341
+ endpointId: this.id
3342
+ },
3343
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3344
+ };
3345
+ }
3346
+ case "PROBE_EXECUTION_TIMEOUT": {
3347
+ const json = await request.json();
3348
+ const timeout = json?.timeout ?? 15 * 60 * 1e3;
3349
+ await new Promise((resolve) => setTimeout(resolve, timeout));
3350
+ return {
3351
+ status: 200,
3352
+ body: {
3353
+ ok: true
3354
+ },
3355
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3356
+ };
3357
+ }
3358
+ case "RUN_NOTIFICATION": {
3359
+ const rawJson = await request.json();
3360
+ const runNotification = rawJson;
3361
+ if (runNotification.ok) {
3362
+ await __privateMethod(this, _deliverSuccessfulRunNotification, deliverSuccessfulRunNotification_fn).call(this, runNotification);
3363
+ } else {
3364
+ await __privateMethod(this, _deliverFailedRunNotification, deliverFailedRunNotification_fn).call(this, runNotification);
3365
+ }
3366
+ return {
3367
+ status: 200,
3368
+ body: {
3369
+ ok: true
3370
+ },
3371
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3372
+ };
3373
+ }
3374
+ }
3375
+ return {
3376
+ status: 405,
3377
+ body: {
3378
+ message: "Method not allowed"
3379
+ },
3380
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3381
+ };
3382
+ }
3383
+ defineJob(options) {
3384
+ const existingRegisteredJob = __privateGet(this, _registeredJobs)[options.id];
3385
+ if (existingRegisteredJob) {
3386
+ console.warn(`[@trigger.dev/sdk] Warning: The Job "${existingRegisteredJob.id}" you're attempting to define has already been defined. Please assign a different ID to the job.`);
3387
+ }
3388
+ const job = new Job(options);
3389
+ this.attach(job);
3390
+ return job;
3391
+ }
3392
+ defineAuthResolver(integration, resolver) {
3393
+ __privateGet(this, _authResolvers)[integration.id] = resolver;
3394
+ return this;
3395
+ }
3396
+ defineDynamicSchedule(options) {
3397
+ return new DynamicSchedule(this, options);
3398
+ }
3399
+ defineDynamicTrigger(options) {
3400
+ return new DynamicTrigger(this, options);
3401
+ }
3402
+ /**
3403
+ * An [HTTP endpoint](https://trigger.dev/docs/documentation/concepts/http-endpoints) allows you to create a [HTTP Trigger](https://trigger.dev/docs/documentation/concepts/triggers/http), which means you can trigger your Jobs from any webhooks.
3404
+ * @param options The Endpoint options
3405
+ * @returns An HTTP Endpoint, that can be used to create an HTTP Trigger.
3406
+ * @link https://trigger.dev/docs/documentation/concepts/http-endpoints
3407
+ */
3408
+ defineHttpEndpoint(options, suppressWarnings = false) {
3409
+ const existingHttpEndpoint = __privateGet(this, _registeredHttpEndpoints)[options.id];
3410
+ if (!suppressWarnings && existingHttpEndpoint) {
3411
+ console.warn(`[@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.`);
3412
+ }
3413
+ const endpoint = httpEndpoint(options);
3414
+ __privateGet(this, _registeredHttpEndpoints)[endpoint.id] = endpoint;
3415
+ return endpoint;
3416
+ }
3417
+ defineConcurrencyLimit(options) {
3418
+ return new ConcurrencyLimit(options);
3419
+ }
3420
+ attach(job) {
3421
+ __privateGet(this, _registeredJobs)[job.id] = job;
3422
+ job.attachToClient(this);
3423
+ }
3424
+ attachDynamicTrigger(trigger) {
3425
+ __privateGet(this, _registeredDynamicTriggers)[trigger.id] = trigger;
3426
+ this.defineJob({
3427
+ id: dynamicTriggerRegisterSourceJobId(trigger.id),
3428
+ name: `Register dynamic trigger ${trigger.id}`,
3429
+ version: trigger.source.version,
3430
+ trigger: new EventTrigger({
3431
+ event: registerSourceEvent,
3432
+ filter: {
3433
+ dynamicTriggerId: [
3434
+ trigger.id
3435
+ ]
3436
+ }
3437
+ }),
3438
+ integrations: {
3439
+ integration: trigger.source.integration
3440
+ },
3441
+ run: async (event, io, ctx) => {
3442
+ const updates = await trigger.source.register(event.source.params, event, io, ctx);
3443
+ if (!updates) {
3444
+ return;
3445
+ }
3446
+ return await io.updateSource("update-source", {
3447
+ key: event.source.key,
3448
+ ...updates
3449
+ });
3450
+ },
3451
+ __internal: true
3452
+ });
3453
+ }
3454
+ attachJobToDynamicTrigger(job, trigger) {
3455
+ const jobs = __privateGet(this, _jobMetadataByDynamicTriggers)[trigger.id] ?? [];
3456
+ jobs.push({
3457
+ id: job.id,
3458
+ version: job.version
3459
+ });
3460
+ __privateGet(this, _jobMetadataByDynamicTriggers)[trigger.id] = jobs;
3461
+ }
3462
+ attachSource(options) {
3463
+ __privateGet(this, _registeredHttpSourceHandlers)[options.key] = async (s, r) => {
3464
+ return await options.source.handle(s, r, __privateGet(this, _internalLogger));
3465
+ };
3466
+ let registeredSource = __privateGet(this, _registeredSources)[options.key];
3467
+ if (!registeredSource) {
3468
+ registeredSource = {
3469
+ version: "2",
3470
+ channel: options.source.channel,
3471
+ key: options.key,
3472
+ params: options.params,
3473
+ options: {},
3474
+ integration: {
3475
+ id: options.source.integration.id,
3476
+ metadata: options.source.integration.metadata,
3477
+ authSource: options.source.integration.authSource
3478
+ },
3479
+ registerSourceJob: {
3480
+ id: options.key,
3481
+ version: options.source.version
3482
+ }
3483
+ };
3484
+ }
3485
+ const newOptions = deepMergeOptions({
3486
+ event: typeof options.event.name === "string" ? [
3487
+ options.event.name
3488
+ ] : options.event.name
3489
+ }, options.options ?? {});
3490
+ registeredSource.options = deepMergeOptions(registeredSource.options, newOptions);
3491
+ __privateGet(this, _registeredSources)[options.key] = registeredSource;
3492
+ this.defineJob({
3493
+ id: options.key,
3494
+ name: options.key,
3495
+ version: options.source.version,
3496
+ trigger: new EventTrigger({
3497
+ event: registerSourceEvent,
3498
+ filter: {
3499
+ source: {
3500
+ key: [
3501
+ options.key
3502
+ ]
3503
+ }
3504
+ }
3505
+ }),
3506
+ integrations: {
3507
+ integration: options.source.integration
3508
+ },
3509
+ run: async (event, io, ctx) => {
3510
+ const updates = await options.source.register(options.params, event, io, ctx);
3511
+ if (!updates) {
3512
+ return;
3513
+ }
3514
+ return await io.updateSource("update-source", {
3515
+ key: options.key,
3516
+ ...updates
3517
+ });
3518
+ },
3519
+ __internal: true
3520
+ });
3521
+ }
3522
+ attachDynamicSchedule(key) {
3523
+ const jobs = __privateGet(this, _registeredSchedules)[key] ?? [];
3524
+ __privateGet(this, _registeredSchedules)[key] = jobs;
3525
+ }
3526
+ attachDynamicScheduleToJob(key, job) {
3527
+ const jobs = __privateGet(this, _registeredSchedules)[key] ?? [];
3528
+ jobs.push({
3529
+ id: job.id,
3530
+ version: job.version
3531
+ });
3532
+ __privateGet(this, _registeredSchedules)[key] = jobs;
3533
+ }
3534
+ attachWebhook(options) {
3535
+ const { source } = options;
3536
+ __privateGet(this, _registeredWebhookSourceHandlers)[options.key] = {
3537
+ verify: source.verify.bind(source),
3538
+ generateEvents: source.generateEvents.bind(source)
3539
+ };
3540
+ let registeredWebhook = __privateGet(this, _registeredWebhooks)[options.key];
3541
+ if (!registeredWebhook) {
3542
+ registeredWebhook = {
3543
+ key: options.key,
3544
+ params: options.params,
3545
+ config: options.config,
3546
+ integration: {
3547
+ id: source.integration.id,
3548
+ metadata: source.integration.metadata,
3549
+ authSource: source.integration.authSource
3550
+ },
3551
+ httpEndpoint: {
3552
+ id: options.key
3553
+ }
3554
+ };
3555
+ } else {
3556
+ registeredWebhook.config = deepMergeOptions(registeredWebhook.config, options.config);
3557
+ }
3558
+ __privateGet(this, _registeredWebhooks)[options.key] = registeredWebhook;
3559
+ this.defineJob({
3560
+ id: `webhook.register.${options.key}`,
3561
+ name: `webhook.register.${options.key}`,
3562
+ version: source.version,
3563
+ trigger: new EventTrigger({
3564
+ event: registerWebhookEvent(options.key)
3565
+ }),
3566
+ integrations: {
3567
+ integration: source.integration
3568
+ },
3569
+ run: async (registerPayload, io, ctx) => {
3570
+ return await io.try(async () => {
3571
+ __privateGet(this, _internalLogger).debug("[webhook.register] Start");
3572
+ const crudOptions = {
3573
+ io,
3574
+ // this is just a more strongly typed payload
3575
+ ctx: registerPayload
3576
+ };
3577
+ if (!registerPayload.active) {
3578
+ __privateGet(this, _internalLogger).debug("[webhook.register] Not active, run create");
3579
+ await io.try(async () => {
3580
+ await source.crud.create(crudOptions);
3581
+ }, async (error) => {
3582
+ __privateGet(this, _internalLogger).debug("[webhook.register] Error during create, re-trying with delete first", {
3583
+ error
3584
+ });
3585
+ await io.runTask("create-retry", async () => {
3586
+ await source.crud.delete(crudOptions);
3587
+ await source.crud.create(crudOptions);
3588
+ });
3589
+ });
3590
+ return await io.updateWebhook("update-webhook-success", {
3591
+ key: options.key,
3592
+ active: true,
3593
+ config: registerPayload.config.desired
3594
+ });
3595
+ }
3596
+ __privateGet(this, _internalLogger).debug("[webhook.register] Already active, run update");
3597
+ if (source.crud.update) {
3598
+ await source.crud.update(crudOptions);
3599
+ } else {
3600
+ __privateGet(this, _internalLogger).debug("[webhook.register] Run delete and create instead of update");
3601
+ await source.crud.delete(crudOptions);
3602
+ await source.crud.create(crudOptions);
3603
+ }
3604
+ return await io.updateWebhook("update-webhook-success", {
3605
+ key: options.key,
3606
+ active: true,
3607
+ config: registerPayload.config.desired
3608
+ });
3609
+ }, async (error) => {
3610
+ __privateGet(this, _internalLogger).debug("[webhook.register] Error", {
3611
+ error
3612
+ });
3613
+ await io.updateWebhook("update-webhook-error", {
3614
+ key: options.key,
3615
+ active: false
3616
+ });
3617
+ throw error;
3618
+ });
3619
+ },
3620
+ __internal: true
3621
+ });
3622
+ }
3623
+ async registerTrigger(id, key, options, idempotencyKey) {
3624
+ return __privateGet(this, _client2).registerTrigger(this.id, id, key, options, idempotencyKey);
3625
+ }
3626
+ async getAuth(id) {
3627
+ return __privateGet(this, _client2).getAuth(this.id, id);
3628
+ }
3629
+ /** You can call this function from anywhere in your backend to send an event. The other way to send an event is by using [`io.sendEvent()`](https://trigger.dev/docs/sdk/io/sendevent) from inside a `run()` function.
3630
+ * @param event The event to send.
3631
+ * @param options Options for sending the event.
3632
+ * @returns A promise that resolves to the event details
3633
+ */
3634
+ async sendEvent(event, options) {
3635
+ return __privateGet(this, _client2).sendEvent(event, options);
3636
+ }
3637
+ /** You can call this function from anywhere in your backend to send multiple events. The other way to send multiple events is by using [`io.sendEvents()`](https://trigger.dev/docs/sdk/io/sendevents) from inside a `run()` function.
3638
+ * @param events The events to send.
3639
+ * @param options Options for sending the events.
3640
+ * @returns A promise that resolves to an array of event details
3641
+ */
3642
+ async sendEvents(events, options) {
3643
+ return __privateGet(this, _client2).sendEvents(events, options);
3644
+ }
3645
+ async cancelEvent(eventId) {
3646
+ return __privateGet(this, _client2).cancelEvent(eventId);
3647
+ }
3648
+ async cancelRunsForEvent(eventId) {
3649
+ return __privateGet(this, _client2).cancelRunsForEvent(eventId);
3650
+ }
3651
+ async updateStatus(runId, id, status) {
3652
+ return __privateGet(this, _client2).updateStatus(runId, id, status);
3653
+ }
3654
+ async registerSchedule(id, key, schedule) {
3655
+ return __privateGet(this, _client2).registerSchedule(this.id, id, key, schedule);
3656
+ }
3657
+ async unregisterSchedule(id, key) {
3658
+ return __privateGet(this, _client2).unregisterSchedule(this.id, id, key);
3659
+ }
3660
+ async getEvent(eventId) {
3661
+ return __privateGet(this, _client2).getEvent(eventId);
3662
+ }
3663
+ async getRun(runId, options) {
3664
+ return __privateGet(this, _client2).getRun(runId, options);
3665
+ }
3666
+ async cancelRun(runId) {
3667
+ return __privateGet(this, _client2).cancelRun(runId);
3668
+ }
3669
+ async getRuns(jobSlug, options) {
3670
+ return __privateGet(this, _client2).getRuns(jobSlug, options);
3671
+ }
3672
+ async getRunStatuses(runId) {
3673
+ return __privateGet(this, _client2).getRunStatuses(runId);
3674
+ }
3675
+ async invokeJob(jobId, payload, options) {
3676
+ return __privateGet(this, _client2).invokeJob(jobId, payload, options);
3677
+ }
3678
+ async createEphemeralEventDispatcher(payload) {
3679
+ return __privateGet(this, _client2).createEphemeralEventDispatcher(payload);
3680
+ }
3681
+ get store() {
3682
+ return {
3683
+ env: __privateGet(this, _envStore)
3684
+ };
3685
+ }
3686
+ authorized(apiKey) {
3687
+ if (typeof apiKey !== "string") {
3688
+ return "missing-header";
3689
+ }
3690
+ const localApiKey = __privateGet(this, _options4).apiKey ?? env.TRIGGER_API_KEY;
3691
+ if (!localApiKey) {
3692
+ return "missing-client";
3693
+ }
3694
+ return apiKey === localApiKey ? "authorized" : "unauthorized";
3695
+ }
3696
+ apiKey() {
3697
+ return __privateGet(this, _options4).apiKey ?? env.TRIGGER_API_KEY;
3698
+ }
3699
+ };
3700
+ _options4 = new WeakMap();
3701
+ _registeredJobs = new WeakMap();
3702
+ _registeredSources = new WeakMap();
3703
+ _registeredWebhooks = new WeakMap();
3704
+ _registeredHttpSourceHandlers = new WeakMap();
3705
+ _registeredWebhookSourceHandlers = new WeakMap();
3706
+ _registeredDynamicTriggers = new WeakMap();
3707
+ _jobMetadataByDynamicTriggers = new WeakMap();
3708
+ _registeredSchedules = new WeakMap();
3709
+ _registeredHttpEndpoints = new WeakMap();
3710
+ _authResolvers = new WeakMap();
3711
+ _envStore = new WeakMap();
3712
+ _eventEmitter = new WeakMap();
3713
+ _client2 = new WeakMap();
3714
+ _internalLogger = new WeakMap();
3715
+ _preprocessRun = new WeakSet();
3716
+ preprocessRun_fn = /* @__PURE__ */ __name(async function(body, job) {
3717
+ __privateMethod(this, _createPreprocessRunContext, createPreprocessRunContext_fn).call(this, body);
3718
+ const parsedPayload = job.trigger.event.parsePayload(body.event.payload ?? {});
3719
+ const properties = job.trigger.event.runProperties?.(parsedPayload) ?? [];
3720
+ return {
3721
+ abort: false,
3722
+ properties
3723
+ };
3724
+ }, "#preprocessRun");
3725
+ _executeJob = new WeakSet();
3726
+ executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1, timeOrigin, triggerVersion) {
3727
+ __privateGet(this, _internalLogger).debug("executing job", {
3728
+ execution: body1,
3729
+ job: job1.id,
3730
+ version: job1.version,
3731
+ triggerVersion
3732
+ });
3733
+ const context = __privateMethod(this, _createRunContext, createRunContext_fn).call(this, body1);
3734
+ const io = new IO({
3735
+ id: body1.run.id,
3736
+ jobId: job1.id,
3737
+ cachedTasks: body1.tasks,
3738
+ cachedTasksCursor: body1.cachedTaskCursor,
3739
+ yieldedExecutions: body1.yieldedExecutions ?? [],
3740
+ noopTasksSet: body1.noopTasksSet,
3741
+ apiClient: __privateGet(this, _client2),
3742
+ logger: __privateGet(this, _internalLogger),
3743
+ client: this,
3744
+ context,
3745
+ jobLogLevel: job1.logLevel ?? __privateGet(this, _options4).logLevel ?? "info",
3746
+ jobLogger: __privateGet(this, _options4).ioLogLocalEnabled ? new Logger(job1.id, job1.logLevel ?? __privateGet(this, _options4).logLevel ?? "info") : void 0,
3747
+ serverVersion: triggerVersion,
3748
+ timeOrigin,
3749
+ executionTimeout: body1.runChunkExecutionLimit
3750
+ });
3751
+ const resolvedConnections = await __privateMethod(this, _resolveConnections, resolveConnections_fn).call(this, context, job1.options.integrations, body1.connections);
3752
+ if (!resolvedConnections.ok) {
3753
+ return {
3754
+ status: "UNRESOLVED_AUTH_ERROR",
3755
+ issues: resolvedConnections.issues
3756
+ };
3757
+ }
3758
+ const ioWithConnections = createIOWithIntegrations(io, resolvedConnections.data, job1.options.integrations);
3759
+ try {
3760
+ const parsedPayload = job1.trigger.event.parsePayload(body1.event.payload ?? {});
3761
+ if (!context.run.isTest) {
3762
+ const verified = await job1.trigger.verifyPayload(parsedPayload);
3763
+ if (!verified.success) {
3764
+ return {
3765
+ status: "ERROR",
3766
+ error: {
3767
+ message: `Payload verification failed. ${verified.reason}`
3768
+ }
3769
+ };
3770
+ }
3771
+ }
3772
+ const output = await runLocalStorage.runWith({
3773
+ io,
3774
+ ctx: context
3775
+ }, () => {
3776
+ return job1.options.run(parsedPayload, ioWithConnections, context);
3777
+ });
3778
+ if (__privateGet(this, _options4).verbose) {
3779
+ __privateMethod(this, _logIOStats, logIOStats_fn).call(this, io.stats);
3780
+ }
3781
+ return {
3782
+ status: "SUCCESS",
3783
+ output
3784
+ };
3785
+ } catch (error) {
3786
+ if (__privateGet(this, _options4).verbose) {
3787
+ __privateMethod(this, _logIOStats, logIOStats_fn).call(this, io.stats);
3788
+ }
3789
+ if (error instanceof ResumeWithParallelTaskError) {
3790
+ return {
3791
+ status: "RESUME_WITH_PARALLEL_TASK",
3792
+ task: error.task,
3793
+ childErrors: error.childErrors.map((childError) => {
3794
+ return __privateMethod(this, _convertErrorToExecutionResponse, convertErrorToExecutionResponse_fn).call(this, childError, body1);
3795
+ })
3796
+ };
3797
+ }
3798
+ return __privateMethod(this, _convertErrorToExecutionResponse, convertErrorToExecutionResponse_fn).call(this, error, body1);
3799
+ }
3800
+ }, "#executeJob");
3801
+ _convertErrorToExecutionResponse = new WeakSet();
3802
+ convertErrorToExecutionResponse_fn = /* @__PURE__ */ __name(function(error, body2) {
3803
+ if (error instanceof AutoYieldExecutionError) {
3804
+ return {
3805
+ status: "AUTO_YIELD_EXECUTION",
3806
+ location: error.location,
3807
+ timeRemaining: error.timeRemaining,
3808
+ timeElapsed: error.timeElapsed,
3809
+ limit: body2.runChunkExecutionLimit
3810
+ };
3811
+ }
3812
+ if (error instanceof AutoYieldWithCompletedTaskExecutionError) {
3813
+ return {
3814
+ status: "AUTO_YIELD_EXECUTION_WITH_COMPLETED_TASK",
3815
+ id: error.id,
3816
+ properties: error.properties,
3817
+ output: error.output,
3818
+ data: {
3819
+ ...error.data,
3820
+ limit: body2.runChunkExecutionLimit
3821
+ }
3822
+ };
3823
+ }
3824
+ if (error instanceof YieldExecutionError) {
3825
+ return {
3826
+ status: "YIELD_EXECUTION",
3827
+ key: error.key
3828
+ };
3829
+ }
3830
+ if (error instanceof ParsedPayloadSchemaError) {
3831
+ return {
3832
+ status: "INVALID_PAYLOAD",
3833
+ errors: error.schemaErrors
3834
+ };
3835
+ }
3836
+ if (error instanceof ResumeWithTaskError) {
3837
+ return {
3838
+ status: "RESUME_WITH_TASK",
3839
+ task: error.task
3840
+ };
3841
+ }
3842
+ if (error instanceof RetryWithTaskError) {
3843
+ return {
3844
+ status: "RETRY_WITH_TASK",
3845
+ task: error.task,
3846
+ error: error.cause,
3847
+ retryAt: error.retryAt
3848
+ };
3849
+ }
3850
+ if (error instanceof CanceledWithTaskError) {
3851
+ return {
3852
+ status: "CANCELED",
3853
+ task: error.task
3854
+ };
3855
+ }
3856
+ if (error instanceof ErrorWithTask) {
3857
+ const errorWithStack2 = ErrorWithStackSchema.safeParse(error.cause.output);
3858
+ if (errorWithStack2.success) {
3859
+ return {
3860
+ status: "ERROR",
3861
+ error: errorWithStack2.data,
3862
+ task: error.cause
3863
+ };
3864
+ }
3865
+ return {
3866
+ status: "ERROR",
3867
+ error: {
3868
+ message: JSON.stringify(error.cause.output)
3869
+ },
3870
+ task: error.cause
3871
+ };
3872
+ }
3873
+ if (error instanceof RetryWithTaskError) {
3874
+ const errorWithStack2 = ErrorWithStackSchema.safeParse(error.cause);
3875
+ if (errorWithStack2.success) {
3876
+ return {
3877
+ status: "ERROR",
3878
+ error: errorWithStack2.data,
3879
+ task: error.task
3880
+ };
3881
+ }
3882
+ return {
3883
+ status: "ERROR",
3884
+ error: {
3885
+ message: "Unknown error"
3886
+ },
3887
+ task: error.task
3888
+ };
3889
+ }
3890
+ const errorWithStack = ErrorWithStackSchema.safeParse(error);
3891
+ if (errorWithStack.success) {
3892
+ return {
3893
+ status: "ERROR",
3894
+ error: errorWithStack.data
3895
+ };
3896
+ }
3897
+ const message = typeof error === "string" ? error : JSON.stringify(error);
3898
+ return {
3899
+ status: "ERROR",
3900
+ error: {
3901
+ name: "Unknown error",
3902
+ message
3903
+ }
3904
+ };
3905
+ }, "#convertErrorToExecutionResponse");
3906
+ _createRunContext = new WeakSet();
3907
+ createRunContext_fn = /* @__PURE__ */ __name(function(execution) {
3908
+ const { event, organization, project, environment, job, run, source } = execution;
3909
+ return {
3910
+ event: {
3911
+ id: event.id,
3912
+ name: event.name,
3913
+ context: event.context,
3914
+ timestamp: event.timestamp
3915
+ },
3916
+ organization,
3917
+ project: project ?? {
3918
+ id: "unknown",
3919
+ name: "unknown",
3920
+ slug: "unknown"
3921
+ },
3922
+ environment,
3923
+ job,
3924
+ run,
3925
+ account: execution.account,
3926
+ source
3927
+ };
3928
+ }, "#createRunContext");
3929
+ _createPreprocessRunContext = new WeakSet();
3930
+ createPreprocessRunContext_fn = /* @__PURE__ */ __name(function(body3) {
3931
+ const { event, organization, environment, job, run, account } = body3;
3932
+ return {
3933
+ event: {
3934
+ id: event.id,
3935
+ name: event.name,
3936
+ context: event.context,
3937
+ timestamp: event.timestamp
3938
+ },
3939
+ organization,
3940
+ environment,
3941
+ job,
3942
+ run,
3943
+ account
3944
+ };
3945
+ }, "#createPreprocessRunContext");
3946
+ _handleHttpSourceRequest = new WeakSet();
3947
+ handleHttpSourceRequest_fn = /* @__PURE__ */ __name(async function(source, sourceRequest) {
3948
+ __privateGet(this, _internalLogger).debug("Handling HTTP source request", {
3949
+ source
3950
+ });
3951
+ if (source.dynamicId) {
3952
+ const dynamicTrigger = __privateGet(this, _registeredDynamicTriggers)[source.dynamicId];
3953
+ if (!dynamicTrigger) {
3954
+ __privateGet(this, _internalLogger).debug("No dynamic trigger registered for HTTP source", {
3955
+ source
3956
+ });
3957
+ return {
3958
+ response: {
3959
+ status: 200,
3960
+ body: {
3961
+ ok: true
3962
+ }
3963
+ },
3964
+ events: []
3965
+ };
3966
+ }
3967
+ const results2 = await dynamicTrigger.source.handle(source, sourceRequest, __privateGet(this, _internalLogger));
3968
+ if (!results2) {
3969
+ return {
3970
+ events: [],
3971
+ response: {
3972
+ status: 200,
3973
+ body: {
3974
+ ok: true
3975
+ }
3976
+ }
3977
+ };
3978
+ }
3979
+ return {
3980
+ events: results2.events,
3981
+ response: results2.response ?? {
3982
+ status: 200,
3983
+ body: {
3984
+ ok: true
3985
+ }
3986
+ },
3987
+ metadata: results2.metadata
3988
+ };
3989
+ }
3990
+ const handler = __privateGet(this, _registeredHttpSourceHandlers)[source.key];
3991
+ if (!handler) {
3992
+ __privateGet(this, _internalLogger).debug("No handler registered for HTTP source", {
3993
+ source
3994
+ });
3995
+ return {
3996
+ response: {
3997
+ status: 200,
3998
+ body: {
3999
+ ok: true
4000
+ }
4001
+ },
4002
+ events: []
4003
+ };
4004
+ }
4005
+ const results = await handler(source, sourceRequest);
4006
+ if (!results) {
4007
+ return {
4008
+ events: [],
4009
+ response: {
4010
+ status: 200,
4011
+ body: {
4012
+ ok: true
4013
+ }
4014
+ }
4015
+ };
4016
+ }
4017
+ return {
4018
+ events: results.events,
4019
+ response: results.response ?? {
4020
+ status: 200,
4021
+ body: {
4022
+ ok: true
4023
+ }
4024
+ },
4025
+ metadata: results.metadata
4026
+ };
4027
+ }, "#handleHttpSourceRequest");
4028
+ _handleHttpEndpointRequestForResponse = new WeakSet();
4029
+ handleHttpEndpointRequestForResponse_fn = /* @__PURE__ */ __name(async function(data, sourceRequest1) {
4030
+ __privateGet(this, _internalLogger).debug("Handling HTTP Endpoint request for response", {
4031
+ data
4032
+ });
4033
+ const httpEndpoint2 = __privateGet(this, _registeredHttpEndpoints)[data.key];
4034
+ if (!httpEndpoint2) {
4035
+ __privateGet(this, _internalLogger).debug("No handler registered for HTTP Endpoint", {
4036
+ data
4037
+ });
4038
+ return {
4039
+ response: {
4040
+ status: 200,
4041
+ body: {
4042
+ ok: true
4043
+ }
4044
+ }
4045
+ };
4046
+ }
4047
+ const handledResponse = await httpEndpoint2.handleRequest(sourceRequest1);
4048
+ if (!handledResponse) {
4049
+ __privateGet(this, _internalLogger).debug("There's no HTTP Endpoint respondWith.handler()", {
4050
+ data
4051
+ });
4052
+ return {
4053
+ response: {
4054
+ status: 200,
4055
+ body: {
4056
+ ok: true
4057
+ }
4058
+ }
4059
+ };
4060
+ }
4061
+ let body;
4062
+ try {
4063
+ body = await handledResponse.text();
4064
+ } catch (error) {
4065
+ __privateGet(this, _internalLogger).error(`Error reading httpEndpoint ${httpEndpoint2.id} respondWith.handler Response`, {
4066
+ error
4067
+ });
4068
+ }
4069
+ const response = {
4070
+ status: handledResponse.status,
4071
+ headers: handledResponse.headers ? Object.fromEntries(handledResponse.headers.entries()) : void 0,
4072
+ body
4073
+ };
4074
+ __privateGet(this, _internalLogger).info(`httpEndpoint ${httpEndpoint2.id} respondWith.handler response`, {
4075
+ response
4076
+ });
4077
+ return {
4078
+ response
4079
+ };
4080
+ }, "#handleHttpEndpointRequestForResponse");
4081
+ _handleWebhookRequest = new WeakSet();
4082
+ handleWebhookRequest_fn = /* @__PURE__ */ __name(async function(request, ctx) {
4083
+ __privateGet(this, _internalLogger).debug("Handling webhook request", {
4084
+ ctx
4085
+ });
4086
+ const okResponse = {
4087
+ status: 200,
4088
+ body: {
4089
+ ok: true
4090
+ }
4091
+ };
4092
+ const handlers = __privateGet(this, _registeredWebhookSourceHandlers)[ctx.key];
4093
+ if (!handlers) {
4094
+ __privateGet(this, _internalLogger).debug("No handler registered for webhook", {
4095
+ ctx
4096
+ });
4097
+ return {
4098
+ response: okResponse,
4099
+ verified: false
4100
+ };
4101
+ }
4102
+ const { verify, generateEvents } = handlers;
4103
+ const verifyResult = await verify(request, this, ctx);
4104
+ if (!verifyResult.success) {
4105
+ return {
4106
+ response: okResponse,
4107
+ verified: false,
4108
+ error: verifyResult.reason
4109
+ };
4110
+ }
4111
+ await generateEvents(request, this, ctx);
4112
+ return {
4113
+ response: okResponse,
4114
+ verified: true
4115
+ };
4116
+ }, "#handleWebhookRequest");
4117
+ _resolveConnections = new WeakSet();
4118
+ resolveConnections_fn = /* @__PURE__ */ __name(async function(ctx1, integrations, connections) {
4119
+ if (!integrations) {
4120
+ return {
4121
+ ok: true,
4122
+ data: {}
4123
+ };
4124
+ }
4125
+ const resolvedAuthResults = await Promise.all(Object.keys(integrations).map(async (key) => {
4126
+ const integration = integrations[key];
4127
+ const auth = (connections ?? {})[key];
4128
+ const result = await __privateMethod(this, _resolveConnection, resolveConnection_fn).call(this, ctx1, integration, auth);
4129
+ if (result.ok) {
4130
+ return {
4131
+ ok: true,
4132
+ auth: result.auth,
4133
+ key
4134
+ };
4135
+ } else {
4136
+ return {
4137
+ ok: false,
4138
+ error: result.error,
4139
+ key
4140
+ };
4141
+ }
4142
+ }));
4143
+ const allResolved = resolvedAuthResults.every((result) => result.ok);
4144
+ if (allResolved) {
4145
+ return {
4146
+ ok: true,
4147
+ data: resolvedAuthResults.reduce((acc, result) => {
4148
+ acc[result.key] = result.auth;
4149
+ return acc;
4150
+ }, {})
4151
+ };
4152
+ } else {
4153
+ return {
4154
+ ok: false,
4155
+ issues: resolvedAuthResults.reduce((acc, result) => {
4156
+ if (result.ok) {
4157
+ return acc;
4158
+ }
4159
+ const integration = integrations[result.key];
4160
+ acc[result.key] = {
4161
+ id: integration.id,
4162
+ error: result.error
4163
+ };
4164
+ return acc;
4165
+ }, {})
4166
+ };
4167
+ }
4168
+ }, "#resolveConnections");
4169
+ _resolveConnection = new WeakSet();
4170
+ resolveConnection_fn = /* @__PURE__ */ __name(async function(ctx2, integration, auth) {
4171
+ if (auth) {
4172
+ return {
4173
+ ok: true,
4174
+ auth
4175
+ };
4176
+ }
4177
+ const authResolver = __privateGet(this, _authResolvers)[integration.id];
4178
+ if (!authResolver) {
4179
+ if (integration.authSource === "HOSTED") {
4180
+ return {
4181
+ ok: false,
4182
+ error: `Something went wrong: Integration ${integration.id} is missing auth credentials from Trigger.dev`
4183
+ };
4184
+ }
4185
+ return {
4186
+ ok: true,
4187
+ auth: void 0
4188
+ };
4189
+ }
4190
+ try {
4191
+ const resolvedAuth = await authResolver(ctx2, integration);
4192
+ if (!resolvedAuth) {
4193
+ return {
4194
+ ok: false,
4195
+ error: `Auth could not be resolved for ${integration.id}: auth resolver returned null or undefined`
4196
+ };
4197
+ }
4198
+ return {
4199
+ ok: true,
4200
+ auth: resolvedAuth.type === "apiKey" ? {
4201
+ type: "apiKey",
4202
+ accessToken: resolvedAuth.token,
4203
+ additionalFields: resolvedAuth.additionalFields
4204
+ } : {
4205
+ type: "oauth2",
4206
+ accessToken: resolvedAuth.token,
4207
+ additionalFields: resolvedAuth.additionalFields
4208
+ }
4209
+ };
4210
+ } catch (resolverError) {
4211
+ if (resolverError instanceof Error) {
4212
+ return {
4213
+ ok: false,
4214
+ error: `Auth could not be resolved for ${integration.id}: auth resolver threw. ${resolverError.name}: ${resolverError.message}`
4215
+ };
4216
+ } else if (typeof resolverError === "string") {
4217
+ return {
4218
+ ok: false,
4219
+ error: `Auth could not be resolved for ${integration.id}: auth resolver threw an error: ${resolverError}`
4220
+ };
4221
+ }
4222
+ return {
4223
+ ok: false,
4224
+ error: `Auth could not be resolved for ${integration.id}: auth resolver threw an unknown error: ${JSON.stringify(resolverError)}`
4225
+ };
4226
+ }
4227
+ }, "#resolveConnection");
4228
+ _buildJobsIndex = new WeakSet();
4229
+ buildJobsIndex_fn = /* @__PURE__ */ __name(function() {
4230
+ return Object.values(__privateGet(this, _registeredJobs)).map((job) => __privateMethod(this, _buildJobIndex, buildJobIndex_fn).call(this, job));
4231
+ }, "#buildJobsIndex");
4232
+ _buildJobIndex = new WeakSet();
4233
+ buildJobIndex_fn = /* @__PURE__ */ __name(function(job2) {
4234
+ const internal = job2.options.__internal;
4235
+ return {
4236
+ id: job2.id,
4237
+ name: job2.name,
4238
+ version: job2.version,
4239
+ event: job2.trigger.event,
4240
+ trigger: job2.trigger.toJSON(),
4241
+ integrations: __privateMethod(this, _buildJobIntegrations, buildJobIntegrations_fn).call(this, job2),
4242
+ startPosition: "latest",
4243
+ enabled: job2.enabled,
4244
+ preprocessRuns: job2.trigger.preprocessRuns,
4245
+ internal,
4246
+ concurrencyLimit: typeof job2.options.concurrencyLimit === "number" ? job2.options.concurrencyLimit : typeof job2.options.concurrencyLimit === "object" ? {
4247
+ id: job2.options.concurrencyLimit.id,
4248
+ limit: job2.options.concurrencyLimit.limit
4249
+ } : void 0
4250
+ };
4251
+ }, "#buildJobIndex");
4252
+ _buildJobIntegrations = new WeakSet();
4253
+ buildJobIntegrations_fn = /* @__PURE__ */ __name(function(job3) {
4254
+ return Object.keys(job3.options.integrations ?? {}).reduce((acc, key) => {
4255
+ const integration = job3.options.integrations[key];
4256
+ acc[key] = __privateMethod(this, _buildJobIntegration, buildJobIntegration_fn).call(this, integration);
4257
+ return acc;
4258
+ }, {});
4259
+ }, "#buildJobIntegrations");
4260
+ _buildJobIntegration = new WeakSet();
4261
+ buildJobIntegration_fn = /* @__PURE__ */ __name(function(integration1) {
4262
+ const authSource = __privateGet(this, _authResolvers)[integration1.id] ? "RESOLVER" : integration1.authSource;
4263
+ return {
4264
+ id: integration1.id,
4265
+ metadata: integration1.metadata,
4266
+ authSource
4267
+ };
4268
+ }, "#buildJobIntegration");
4269
+ _logIOStats = new WeakSet();
4270
+ logIOStats_fn = /* @__PURE__ */ __name(function(stats) {
4271
+ __privateGet(this, _internalLogger).debug("IO stats", {
4272
+ stats
4273
+ });
4274
+ }, "#logIOStats");
4275
+ _standardResponseHeaders = new WeakSet();
4276
+ standardResponseHeaders_fn = /* @__PURE__ */ __name(function(start) {
4277
+ return {
4278
+ "Trigger-Version": API_VERSIONS.LAZY_LOADED_CACHED_TASKS,
4279
+ "Trigger-SDK-Version": version,
4280
+ "X-Trigger-Request-Timing": `dur=${performance.now() - start / 1e3}`
4281
+ };
4282
+ }, "#standardResponseHeaders");
4283
+ _serializeRunMetadata = new WeakSet();
4284
+ serializeRunMetadata_fn = /* @__PURE__ */ __name(function(job4) {
4285
+ const metadata = {};
4286
+ if (__privateGet(this, _eventEmitter).listenerCount("runSucceeeded") > 0 || typeof job4.options.onSuccess === "function") {
4287
+ metadata["successSubscription"] = true;
4288
+ }
4289
+ if (__privateGet(this, _eventEmitter).listenerCount("runFailed") > 0 || typeof job4.options.onFailure === "function") {
4290
+ metadata["failedSubscription"] = true;
4291
+ }
4292
+ return JSON.stringify(metadata);
4293
+ }, "#serializeRunMetadata");
4294
+ _deliverSuccessfulRunNotification = new WeakSet();
4295
+ deliverSuccessfulRunNotification_fn = /* @__PURE__ */ __name(async function(notification) {
4296
+ __privateGet(this, _internalLogger).debug("delivering successful run notification", {
4297
+ notification
4298
+ });
4299
+ __privateGet(this, _eventEmitter).emit("runSucceeeded", notification);
4300
+ const job = __privateGet(this, _registeredJobs)[notification.job.id];
4301
+ if (!job) {
4302
+ return;
4303
+ }
4304
+ if (typeof job.options.onSuccess === "function") {
4305
+ await job.options.onSuccess(notification);
4306
+ }
4307
+ }, "#deliverSuccessfulRunNotification");
4308
+ _deliverFailedRunNotification = new WeakSet();
4309
+ deliverFailedRunNotification_fn = /* @__PURE__ */ __name(async function(notification1) {
4310
+ __privateGet(this, _internalLogger).debug("delivering failed run notification", {
4311
+ notification: notification1
4312
+ });
4313
+ __privateGet(this, _eventEmitter).emit("runFailed", notification1);
4314
+ const job = __privateGet(this, _registeredJobs)[notification1.job.id];
4315
+ if (!job) {
4316
+ return;
4317
+ }
4318
+ if (typeof job.options.onFailure === "function") {
4319
+ await job.options.onFailure(notification1);
4320
+ }
4321
+ }, "#deliverFailedRunNotification");
4322
+ __name(_TriggerClient, "TriggerClient");
4323
+ var TriggerClient = _TriggerClient;
4324
+ function dynamicTriggerRegisterSourceJobId(id) {
4325
+ return `register-dynamic-trigger-${id}`;
4326
+ }
4327
+ __name(dynamicTriggerRegisterSourceJobId, "dynamicTriggerRegisterSourceJobId");
4328
+ function deepMergeOptions(obj1, obj2) {
4329
+ const mergedOptions = {
4330
+ ...obj1
4331
+ };
4332
+ for (const key in obj2) {
4333
+ if (obj2.hasOwnProperty(key)) {
4334
+ if (key in mergedOptions) {
4335
+ mergedOptions[key] = [
4336
+ ...mergedOptions[key],
4337
+ ...obj2[key]
4338
+ ];
4339
+ } else {
4340
+ mergedOptions[key] = obj2[key];
4341
+ }
4342
+ }
4343
+ }
4344
+ return mergedOptions;
4345
+ }
4346
+ __name(deepMergeOptions, "deepMergeOptions");
4347
+ var _ExternalSource = class _ExternalSource {
4348
+ constructor(channel, options) {
4349
+ this.options = options;
4350
+ this.channel = channel;
4351
+ }
4352
+ async handle(source, rawEvent, logger) {
4353
+ return this.options.handler({
4354
+ source: {
4355
+ ...source,
4356
+ params: source.params
4357
+ },
4358
+ rawEvent
4359
+ }, logger, this.options.integration);
4360
+ }
4361
+ filter(params, options) {
4362
+ return this.options.filter?.(params, options) ?? {};
4363
+ }
4364
+ properties(params) {
4365
+ return this.options.properties?.(params) ?? [];
4366
+ }
4367
+ async register(params, registerEvent, io, ctx) {
4368
+ const { result: event, ommited: source } = omit(registerEvent, "source");
4369
+ const { result: sourceWithoutChannel, ommited: channel } = omit(source, "channel");
4370
+ const { result: channelWithoutType } = omit(channel, "type");
4371
+ const updates = await this.options.register({
4372
+ ...event,
4373
+ source: {
4374
+ ...sourceWithoutChannel,
4375
+ ...channelWithoutType
4376
+ },
4377
+ params
4378
+ }, io, ctx);
4379
+ return updates;
4380
+ }
4381
+ key(params) {
4382
+ const parts = [
4383
+ this.options.id,
4384
+ this.channel
4385
+ ];
4386
+ parts.push(this.options.key(params));
4387
+ parts.push(this.integration.id);
4388
+ return parts.join("-");
4389
+ }
4390
+ get integration() {
4391
+ return this.options.integration;
4392
+ }
4393
+ get integrationConfig() {
4394
+ return {
4395
+ id: this.integration.id,
4396
+ metadata: this.integration.metadata
4397
+ };
4398
+ }
4399
+ get id() {
4400
+ return this.options.id;
4401
+ }
4402
+ get version() {
4403
+ return this.options.version;
4404
+ }
4405
+ };
4406
+ __name(_ExternalSource, "ExternalSource");
4407
+ var ExternalSource = _ExternalSource;
4408
+ var _ExternalSourceTrigger = class _ExternalSourceTrigger {
4409
+ constructor(options) {
4410
+ this.options = options;
4411
+ }
4412
+ get event() {
4413
+ return this.options.event;
4414
+ }
4415
+ toJSON() {
4416
+ return {
4417
+ type: "static",
4418
+ title: "External Source",
4419
+ rule: {
4420
+ event: this.event.name,
4421
+ payload: deepMergeFilters(this.options.source.filter(this.options.params, this.options.options), this.event.filter ?? {}, this.options.params.filter ?? {}),
4422
+ source: this.event.source
4423
+ },
4424
+ properties: this.options.source.properties(this.options.params)
4425
+ };
4426
+ }
4427
+ attachToJob(triggerClient, job) {
4428
+ triggerClient.attachSource({
4429
+ key: slugifyId(this.options.source.key(this.options.params)),
4430
+ source: this.options.source,
4431
+ event: this.options.event,
4432
+ params: this.options.params,
4433
+ options: this.options.options
4434
+ });
4435
+ }
4436
+ get preprocessRuns() {
4437
+ return true;
4438
+ }
4439
+ async verifyPayload(payload) {
4440
+ return {
4441
+ success: true
4442
+ };
4443
+ }
4444
+ };
4445
+ __name(_ExternalSourceTrigger, "ExternalSourceTrigger");
4446
+ var ExternalSourceTrigger = _ExternalSourceTrigger;
4447
+ function omit(obj, key) {
4448
+ const result = {};
4449
+ for (const k of Object.keys(obj)) {
4450
+ if (k === key)
4451
+ continue;
4452
+ result[k] = obj[k];
4453
+ }
4454
+ return {
4455
+ result,
4456
+ ommited: obj[key]
4457
+ };
4458
+ }
4459
+ __name(omit, "omit");
4460
+ function missingConnectionNotification(integrations) {
4461
+ return new MissingConnectionNotification({
4462
+ integrations
4463
+ });
4464
+ }
4465
+ __name(missingConnectionNotification, "missingConnectionNotification");
4466
+ function missingConnectionResolvedNotification(integrations) {
4467
+ return new MissingConnectionResolvedNotification({
4468
+ integrations
4469
+ });
4470
+ }
4471
+ __name(missingConnectionResolvedNotification, "missingConnectionResolvedNotification");
4472
+ var _MissingConnectionNotification = class _MissingConnectionNotification {
4473
+ constructor(options) {
4474
+ this.options = options;
4475
+ }
4476
+ get event() {
4477
+ return {
4478
+ name: MISSING_CONNECTION_NOTIFICATION,
4479
+ title: "Missing Connection Notification",
4480
+ source: "trigger.dev",
4481
+ icon: "connection-alert",
4482
+ parsePayload: MissingConnectionNotificationPayloadSchema.parse,
4483
+ properties: [
4484
+ {
4485
+ label: "Integrations",
4486
+ text: this.options.integrations.map((i) => i.id).join(", ")
4487
+ }
4488
+ ]
4489
+ };
4490
+ }
4491
+ attachToJob(triggerClient, job) {
4492
+ }
4493
+ get preprocessRuns() {
4494
+ return false;
4495
+ }
4496
+ async verifyPayload(payload) {
4497
+ return {
4498
+ success: true
4499
+ };
4500
+ }
4501
+ toJSON() {
4502
+ return {
4503
+ type: "static",
4504
+ title: this.event.title,
4505
+ rule: {
4506
+ event: this.event.name,
4507
+ source: "trigger.dev",
4508
+ payload: {
4509
+ client: {
4510
+ id: this.options.integrations.map((i) => i.id)
4511
+ }
4512
+ }
4513
+ }
4514
+ };
4515
+ }
4516
+ };
4517
+ __name(_MissingConnectionNotification, "MissingConnectionNotification");
4518
+ var MissingConnectionNotification = _MissingConnectionNotification;
4519
+ var _MissingConnectionResolvedNotification = class _MissingConnectionResolvedNotification {
4520
+ constructor(options) {
4521
+ this.options = options;
4522
+ }
4523
+ get event() {
4524
+ return {
4525
+ name: MISSING_CONNECTION_RESOLVED_NOTIFICATION,
4526
+ title: "Missing Connection Resolved Notification",
4527
+ source: "trigger.dev",
4528
+ icon: "connection-alert",
4529
+ parsePayload: MissingConnectionResolvedNotificationPayloadSchema.parse,
4530
+ properties: [
4531
+ {
4532
+ label: "Integrations",
4533
+ text: this.options.integrations.map((i) => i.id).join(", ")
4534
+ }
4535
+ ]
4536
+ };
4537
+ }
4538
+ attachToJob(triggerClient, job) {
4539
+ }
4540
+ get preprocessRuns() {
4541
+ return false;
4542
+ }
4543
+ async verifyPayload(payload) {
4544
+ return {
4545
+ success: true
4546
+ };
4547
+ }
4548
+ toJSON() {
4549
+ return {
4550
+ type: "static",
4551
+ title: this.event.title,
4552
+ rule: {
4553
+ event: this.event.name,
4554
+ source: "trigger.dev",
4555
+ payload: {
4556
+ client: {
4557
+ id: this.options.integrations.map((i) => i.id)
4558
+ }
4559
+ }
4560
+ }
4561
+ };
4562
+ }
4563
+ };
4564
+ __name(_MissingConnectionResolvedNotification, "MissingConnectionResolvedNotification");
4565
+ var MissingConnectionResolvedNotification = _MissingConnectionResolvedNotification;
4566
+
4567
+ // src/triggers/invokeTrigger.ts
4568
+ var _options5;
4569
+ var _InvokeTrigger = class _InvokeTrigger {
4570
+ constructor(options) {
4571
+ __privateAdd(this, _options5, void 0);
4572
+ __privateSet(this, _options5, options);
4573
+ }
4574
+ toJSON() {
4575
+ return {
4576
+ type: "invoke"
4577
+ };
4578
+ }
4579
+ get event() {
4580
+ return {
4581
+ name: "invoke",
4582
+ title: "Manual Invoke",
4583
+ source: "trigger.dev",
4584
+ examples: __privateGet(this, _options5).examples ?? [],
4585
+ icon: "trigger",
4586
+ parsePayload: (rawPayload) => {
4587
+ if (__privateGet(this, _options5).schema) {
4588
+ const results = __privateGet(this, _options5).schema.safeParse(rawPayload);
4589
+ if (!results.success) {
4590
+ throw new ParsedPayloadSchemaError(formatSchemaErrors(results.error.issues));
4591
+ }
4592
+ return results.data;
4593
+ }
4594
+ return rawPayload;
4595
+ },
4596
+ parseInvokePayload: (rawPayload) => {
4597
+ if (__privateGet(this, _options5).schema) {
4598
+ const results = __privateGet(this, _options5).schema.safeParse(rawPayload);
4599
+ if (!results.success) {
4600
+ throw new ParsedPayloadSchemaError(formatSchemaErrors(results.error.issues));
4601
+ }
4602
+ return results.data;
4603
+ }
4604
+ return rawPayload;
4605
+ }
4606
+ };
4607
+ }
4608
+ attachToJob(triggerClient, job) {
4609
+ }
4610
+ get preprocessRuns() {
4611
+ return false;
4612
+ }
4613
+ async verifyPayload() {
4614
+ return {
4615
+ success: true
4616
+ };
4617
+ }
4618
+ };
4619
+ _options5 = new WeakMap();
4620
+ __name(_InvokeTrigger, "InvokeTrigger");
4621
+ var InvokeTrigger = _InvokeTrigger;
4622
+ function invokeTrigger(options) {
4623
+ return new InvokeTrigger(options ?? {});
4624
+ }
4625
+ __name(invokeTrigger, "invokeTrigger");
4626
+ var _shortHash, shortHash_fn;
4627
+ var _WebhookSource = class _WebhookSource {
4628
+ constructor(options) {
4629
+ __privateAdd(this, _shortHash);
4630
+ this.options = options;
4631
+ }
4632
+ async generateEvents(request, client, ctx) {
4633
+ return this.options.generateEvents({
4634
+ request,
4635
+ client,
4636
+ ctx
4637
+ });
4638
+ }
4639
+ filter(params, config) {
4640
+ return this.options.filter?.(params, config) ?? {};
4641
+ }
4642
+ properties(params) {
4643
+ return this.options.properties?.(params) ?? [];
4644
+ }
4645
+ get crud() {
4646
+ return this.options.crud;
4647
+ }
4648
+ async register(params, registerEvent, io, ctx) {
4649
+ if (!this.options.register) {
4650
+ return;
4651
+ }
4652
+ const updates = await this.options.register({
4653
+ ...registerEvent,
4654
+ params
4655
+ }, io, ctx);
4656
+ return updates;
4657
+ }
4658
+ async verify(request, client, ctx) {
4659
+ if (this.options.verify) {
4660
+ const clonedRequest = request.clone();
4661
+ return this.options.verify({
4662
+ request: clonedRequest,
4663
+ client,
4664
+ ctx
4665
+ });
4666
+ }
4667
+ return {
4668
+ success: true
4669
+ };
4670
+ }
4671
+ key(params) {
4672
+ const parts = [
4673
+ "webhook"
4674
+ ];
4675
+ parts.push(this.options.key(params));
4676
+ parts.push(this.integration.id);
4677
+ return `${this.options.id}-${__privateMethod(this, _shortHash, shortHash_fn).call(this, parts.join(""))}`;
4678
+ }
4679
+ get integration() {
4680
+ return this.options.integration;
4681
+ }
4682
+ get integrationConfig() {
4683
+ return {
4684
+ id: this.integration.id,
4685
+ metadata: this.integration.metadata
4686
+ };
4687
+ }
4688
+ get id() {
4689
+ return this.options.id;
4690
+ }
4691
+ get version() {
4692
+ return this.options.version;
4693
+ }
4694
+ };
4695
+ _shortHash = new WeakSet();
4696
+ shortHash_fn = /* @__PURE__ */ __name(function(str) {
4697
+ const hash = createHash("sha1").update(str).digest("hex");
4698
+ return hash.slice(0, 7);
4699
+ }, "#shortHash");
4700
+ __name(_WebhookSource, "WebhookSource");
4701
+ var WebhookSource = _WebhookSource;
4702
+ var _WebhookTrigger = class _WebhookTrigger {
4703
+ constructor(options) {
4704
+ this.options = options;
4705
+ }
4706
+ get event() {
4707
+ return this.options.event;
4708
+ }
4709
+ get source() {
4710
+ return this.options.source;
4711
+ }
4712
+ get key() {
4713
+ return slugifyId(this.options.source.key(this.options.params));
4714
+ }
4715
+ toJSON() {
4716
+ return {
4717
+ type: "static",
4718
+ title: "Webhook",
4719
+ rule: {
4720
+ event: this.event.name,
4721
+ payload: deepMergeFilters(this.options.source.filter(this.options.params, this.options.config), this.event.filter ?? {}),
4722
+ source: this.event.source
4723
+ },
4724
+ properties: this.options.source.properties(this.options.params),
4725
+ link: `http-endpoints/${this.key}`
4726
+ };
4727
+ }
4728
+ filter(eventFilter) {
4729
+ const { event, ...optionsWithoutEvent } = this.options;
4730
+ const { filter, ...eventWithoutFilter } = event;
4731
+ return new _WebhookTrigger({
4732
+ ...optionsWithoutEvent,
4733
+ event: {
4734
+ ...eventWithoutFilter,
4735
+ filter: deepMergeFilters(filter ?? {}, eventFilter)
4736
+ }
4737
+ });
4738
+ }
4739
+ attachToJob(triggerClient, job) {
4740
+ triggerClient.defineHttpEndpoint({
4741
+ id: this.key,
4742
+ source: "trigger.dev",
4743
+ icon: this.event.icon,
4744
+ verify: async () => ({
4745
+ success: true
4746
+ })
4747
+ }, true);
4748
+ triggerClient.attachWebhook({
4749
+ key: this.key,
4750
+ source: this.options.source,
4751
+ event: this.options.event,
4752
+ params: this.options.params,
4753
+ config: this.options.config
4754
+ });
4755
+ }
4756
+ get preprocessRuns() {
4757
+ return true;
4758
+ }
4759
+ async verifyPayload(payload) {
4760
+ return {
4761
+ success: true
4762
+ };
4763
+ }
4764
+ };
4765
+ __name(_WebhookTrigger, "WebhookTrigger");
4766
+ var WebhookTrigger = _WebhookTrigger;
4767
+ async function verifyRequestSignature({ request, headerName, headerEncoding = "hex", secret, algorithm }) {
4768
+ if (!secret) {
4769
+ return {
4770
+ success: false,
4771
+ reason: "Missing secret \u2013 you've probably not set an environment variable."
4772
+ };
4773
+ }
4774
+ const headerValue = request.headers.get(headerName);
4775
+ if (!headerValue) {
4776
+ return {
4777
+ success: false,
4778
+ reason: "Missing header"
4779
+ };
4780
+ }
4781
+ switch (algorithm) {
4782
+ case "sha256":
4783
+ const success = verifyHmacSha256(headerValue, headerEncoding, secret, await request.text());
4784
+ if (success) {
4785
+ return {
4786
+ success
4787
+ };
4788
+ } else {
4789
+ return {
4790
+ success: false,
4791
+ reason: "Failed sha256 verification"
4792
+ };
4793
+ }
4794
+ default:
4795
+ throw new Error(`Unsupported algorithm: ${algorithm}`);
4796
+ }
4797
+ }
4798
+ __name(verifyRequestSignature, "verifyRequestSignature");
4799
+ function verifyHmacSha256(headerValue, headerEncoding, secret, body) {
4800
+ const bodyDigest = crypto.createHmac("sha256", secret).update(body).digest(headerEncoding);
4801
+ const signature = headerValue?.replace("hmac-sha256=", "").replace("sha256=", "") ?? "";
4802
+ return signature === bodyDigest;
4803
+ }
4804
+ __name(verifyHmacSha256, "verifyHmacSha256");
4805
+
4806
+ // src/index.ts
4807
+ function redactString(strings, ...interpolations) {
4808
+ return {
4809
+ __redactedString: true,
4810
+ strings: strings.raw,
4811
+ interpolations
4812
+ };
4813
+ }
4814
+ __name(redactString, "redactString");
4815
+
4816
+ export { CronTrigger, DynamicSchedule, DynamicTrigger, EventSpecificationExampleSchema, EventTrigger, ExternalSource, ExternalSourceTrigger, IO, IOLogger, IntervalTrigger, InvokeTrigger, JSONOutputSerializer, Job, MissingConnectionNotification, MissingConnectionResolvedNotification, TriggerClient, WebhookSource, WebhookTrigger, cronTrigger, eventTrigger, intervalTrigger, invokeTrigger, isTriggerError, missingConnectionNotification, missingConnectionResolvedNotification, omit, redactString, retry, slugifyId, verifyHmacSha256, verifyRequestSignature, waitForEventSchema };
4817
+ //# sourceMappingURL=out.js.map
4818
+ //# sourceMappingURL=index.mjs.map