@trigger.dev/sdk 0.0.0-auto-yield-20231011151933

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,2856 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
10
+ var __export = (target, all) => {
11
+ for (var name in all)
12
+ __defProp(target, name, { get: all[name], enumerable: true });
13
+ };
14
+ var __copyProps = (to, from, except, desc) => {
15
+ if (from && typeof from === "object" || typeof from === "function") {
16
+ for (let key of __getOwnPropNames(from))
17
+ if (!__hasOwnProp.call(to, key) && key !== except)
18
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
23
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
24
+ mod
25
+ ));
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var __publicField = (obj, key, value) => {
28
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
29
+ return value;
30
+ };
31
+ var __accessCheck = (obj, member, msg) => {
32
+ if (!member.has(obj))
33
+ throw TypeError("Cannot " + msg);
34
+ };
35
+ var __privateGet = (obj, member, getter) => {
36
+ __accessCheck(obj, member, "read from private field");
37
+ return getter ? getter.call(obj) : member.get(obj);
38
+ };
39
+ var __privateAdd = (obj, member, value) => {
40
+ if (member.has(obj))
41
+ throw TypeError("Cannot add the same private member more than once");
42
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
43
+ };
44
+ var __privateSet = (obj, member, value, setter) => {
45
+ __accessCheck(obj, member, "write to private field");
46
+ setter ? setter.call(obj, value) : member.set(obj, value);
47
+ return value;
48
+ };
49
+ var __privateMethod = (obj, member, method) => {
50
+ __accessCheck(obj, member, "access private method");
51
+ return method;
52
+ };
53
+
54
+ // src/index.ts
55
+ var src_exports = {};
56
+ __export(src_exports, {
57
+ CronTrigger: () => CronTrigger,
58
+ DynamicSchedule: () => DynamicSchedule,
59
+ DynamicTrigger: () => DynamicTrigger,
60
+ EventTrigger: () => EventTrigger,
61
+ ExternalSource: () => ExternalSource,
62
+ ExternalSourceTrigger: () => ExternalSourceTrigger,
63
+ IO: () => IO,
64
+ IOLogger: () => IOLogger,
65
+ IntervalTrigger: () => IntervalTrigger,
66
+ Job: () => Job,
67
+ MissingConnectionNotification: () => MissingConnectionNotification,
68
+ MissingConnectionResolvedNotification: () => MissingConnectionResolvedNotification,
69
+ TriggerClient: () => TriggerClient,
70
+ cronTrigger: () => cronTrigger,
71
+ eventTrigger: () => eventTrigger,
72
+ intervalTrigger: () => intervalTrigger,
73
+ isTriggerError: () => isTriggerError,
74
+ missingConnectionNotification: () => missingConnectionNotification,
75
+ missingConnectionResolvedNotification: () => missingConnectionResolvedNotification,
76
+ omit: () => omit,
77
+ redactString: () => redactString,
78
+ retry: () => retry
79
+ });
80
+ module.exports = __toCommonJS(src_exports);
81
+
82
+ // src/utils.ts
83
+ function slugifyId(input) {
84
+ const replaceSpacesWithDash = input.toLowerCase().replace(/\s+/g, "-");
85
+ const removeNonUrlSafeChars = replaceSpacesWithDash.replace(/[^a-zA-Z0-9-._~]/g, "");
86
+ return removeNonUrlSafeChars;
87
+ }
88
+ __name(slugifyId, "slugifyId");
89
+
90
+ // src/job.ts
91
+ var _validate, validate_fn;
92
+ var Job = class {
93
+ constructor(client, options) {
94
+ __privateAdd(this, _validate);
95
+ this.client = client;
96
+ this.options = options;
97
+ __privateMethod(this, _validate, validate_fn).call(this);
98
+ client.attach(this);
99
+ }
100
+ get id() {
101
+ return slugifyId(this.options.id);
102
+ }
103
+ get enabled() {
104
+ return typeof this.options.enabled === "boolean" ? this.options.enabled : true;
105
+ }
106
+ get name() {
107
+ return this.options.name;
108
+ }
109
+ get trigger() {
110
+ return this.options.trigger;
111
+ }
112
+ get version() {
113
+ return this.options.version;
114
+ }
115
+ get logLevel() {
116
+ return this.options.logLevel;
117
+ }
118
+ get integrations() {
119
+ return Object.keys(this.options.integrations ?? {}).reduce((acc, key) => {
120
+ const integration = this.options.integrations[key];
121
+ acc[key] = {
122
+ id: integration.id,
123
+ metadata: integration.metadata,
124
+ authSource: integration.authSource
125
+ };
126
+ return acc;
127
+ }, {});
128
+ }
129
+ toJSON() {
130
+ const internal = this.options.__internal;
131
+ return {
132
+ id: this.id,
133
+ name: this.name,
134
+ version: this.version,
135
+ event: this.trigger.event,
136
+ trigger: this.trigger.toJSON(),
137
+ integrations: this.integrations,
138
+ startPosition: "latest",
139
+ enabled: this.enabled,
140
+ preprocessRuns: this.trigger.preprocessRuns,
141
+ internal
142
+ };
143
+ }
144
+ };
145
+ __name(Job, "Job");
146
+ _validate = new WeakSet();
147
+ validate_fn = /* @__PURE__ */ __name(function() {
148
+ if (!this.version.match(/^(\d+)\.(\d+)\.(\d+)$/)) {
149
+ throw new Error(`Invalid job version: "${this.version}". Job versions must be valid semver versions.`);
150
+ }
151
+ }, "#validate");
152
+
153
+ // src/triggerClient.ts
154
+ var import_core7 = require("@trigger.dev/core");
155
+
156
+ // src/apiClient.ts
157
+ var import_core = require("@trigger.dev/core");
158
+ var import_zod = require("zod");
159
+ var _apiUrl, _options, _logger, _apiKey, apiKey_fn;
160
+ var ApiClient = class {
161
+ constructor(options) {
162
+ __privateAdd(this, _apiKey);
163
+ __privateAdd(this, _apiUrl, void 0);
164
+ __privateAdd(this, _options, void 0);
165
+ __privateAdd(this, _logger, void 0);
166
+ __privateSet(this, _options, options);
167
+ __privateSet(this, _apiUrl, __privateGet(this, _options).apiUrl ?? process.env.TRIGGER_API_URL ?? "https://api.trigger.dev");
168
+ __privateSet(this, _logger, new import_core.Logger("trigger.dev", __privateGet(this, _options).logLevel));
169
+ }
170
+ async registerEndpoint(options) {
171
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
172
+ __privateGet(this, _logger).debug("Registering endpoint", {
173
+ url: options.url,
174
+ name: options.name
175
+ });
176
+ const response = await fetch(`${__privateGet(this, _apiUrl)}/api/v1/endpoints`, {
177
+ method: "POST",
178
+ headers: {
179
+ "Content-Type": "application/json",
180
+ Authorization: `Bearer ${apiKey}`
181
+ },
182
+ body: JSON.stringify({
183
+ url: options.url,
184
+ name: options.name
185
+ })
186
+ });
187
+ if (response.status >= 400 && response.status < 500) {
188
+ const body = await response.json();
189
+ throw new Error(body.error);
190
+ }
191
+ if (response.status !== 200) {
192
+ throw new Error(`Failed to register entry point, got status code ${response.status}`);
193
+ }
194
+ return await response.json();
195
+ }
196
+ async runTask(runId, task, options = {}) {
197
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
198
+ __privateGet(this, _logger).debug("Running Task", {
199
+ task
200
+ });
201
+ return await zodfetchWithVersions({
202
+ [import_core.API_VERSIONS.LAZY_LOADED_CACHED_TASKS]: import_core.RunTaskResponseWithCachedTasksBodySchema
203
+ }, import_core.ServerTaskSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/tasks`, {
204
+ method: "POST",
205
+ headers: {
206
+ "Content-Type": "application/json",
207
+ Authorization: `Bearer ${apiKey}`,
208
+ "Idempotency-Key": task.idempotencyKey,
209
+ "X-Cached-Tasks-Cursor": options.cachedTasksCursor ?? "",
210
+ "Trigger-Version": import_core.API_VERSIONS.LAZY_LOADED_CACHED_TASKS
211
+ },
212
+ body: JSON.stringify(task)
213
+ });
214
+ }
215
+ async completeTask(runId, id, task) {
216
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
217
+ __privateGet(this, _logger).debug("Complete Task", {
218
+ task
219
+ });
220
+ return await zodfetch(import_core.ServerTaskSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/tasks/${id}/complete`, {
221
+ method: "POST",
222
+ headers: {
223
+ "Content-Type": "application/json",
224
+ Authorization: `Bearer ${apiKey}`
225
+ },
226
+ body: JSON.stringify(task)
227
+ });
228
+ }
229
+ async failTask(runId, id, body) {
230
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
231
+ __privateGet(this, _logger).debug("Fail Task", {
232
+ id,
233
+ runId,
234
+ body
235
+ });
236
+ return await zodfetch(import_core.ServerTaskSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/tasks/${id}/fail`, {
237
+ method: "POST",
238
+ headers: {
239
+ "Content-Type": "application/json",
240
+ Authorization: `Bearer ${apiKey}`
241
+ },
242
+ body: JSON.stringify(body)
243
+ });
244
+ }
245
+ async sendEvent(event, options = {}) {
246
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
247
+ __privateGet(this, _logger).debug("Sending event", {
248
+ event
249
+ });
250
+ return await zodfetch(import_core.ApiEventLogSchema, `${__privateGet(this, _apiUrl)}/api/v1/events`, {
251
+ method: "POST",
252
+ headers: {
253
+ "Content-Type": "application/json",
254
+ Authorization: `Bearer ${apiKey}`
255
+ },
256
+ body: JSON.stringify({
257
+ event,
258
+ options
259
+ })
260
+ });
261
+ }
262
+ async cancelEvent(eventId) {
263
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
264
+ __privateGet(this, _logger).debug("Cancelling event", {
265
+ eventId
266
+ });
267
+ return await zodfetch(import_core.ApiEventLogSchema, `${__privateGet(this, _apiUrl)}/api/v1/events/${eventId}/cancel`, {
268
+ method: "POST",
269
+ headers: {
270
+ "Content-Type": "application/json",
271
+ Authorization: `Bearer ${apiKey}`
272
+ }
273
+ });
274
+ }
275
+ async updateStatus(runId, id, status) {
276
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
277
+ __privateGet(this, _logger).debug("Update status", {
278
+ id,
279
+ status
280
+ });
281
+ return await zodfetch(import_core.JobRunStatusRecordSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/statuses/${id}`, {
282
+ method: "PUT",
283
+ headers: {
284
+ "Content-Type": "application/json",
285
+ Authorization: `Bearer ${apiKey}`
286
+ },
287
+ body: JSON.stringify(status)
288
+ });
289
+ }
290
+ async updateSource(client, key, source) {
291
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
292
+ __privateGet(this, _logger).debug("activating http source", {
293
+ source
294
+ });
295
+ const response = await zodfetch(import_core.TriggerSourceSchema, `${__privateGet(this, _apiUrl)}/api/v2/${client}/sources/${key}`, {
296
+ method: "PUT",
297
+ headers: {
298
+ "Content-Type": "application/json",
299
+ Authorization: `Bearer ${apiKey}`
300
+ },
301
+ body: JSON.stringify(source)
302
+ });
303
+ return response;
304
+ }
305
+ async registerTrigger(client, id, key, payload) {
306
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
307
+ __privateGet(this, _logger).debug("registering trigger", {
308
+ id,
309
+ payload
310
+ });
311
+ const response = await zodfetch(import_core.RegisterSourceEventSchemaV2, `${__privateGet(this, _apiUrl)}/api/v2/${client}/triggers/${id}/registrations/${key}`, {
312
+ method: "PUT",
313
+ headers: {
314
+ "Content-Type": "application/json",
315
+ Authorization: `Bearer ${apiKey}`
316
+ },
317
+ body: JSON.stringify(payload)
318
+ });
319
+ return response;
320
+ }
321
+ async registerSchedule(client, id, key, payload) {
322
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
323
+ __privateGet(this, _logger).debug("registering schedule", {
324
+ id,
325
+ payload
326
+ });
327
+ const response = await zodfetch(import_core.RegisterScheduleResponseBodySchema, `${__privateGet(this, _apiUrl)}/api/v1/${client}/schedules/${id}/registrations`, {
328
+ method: "POST",
329
+ headers: {
330
+ "Content-Type": "application/json",
331
+ Authorization: `Bearer ${apiKey}`
332
+ },
333
+ body: JSON.stringify({
334
+ id: key,
335
+ ...payload
336
+ })
337
+ });
338
+ return response;
339
+ }
340
+ async unregisterSchedule(client, id, key) {
341
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
342
+ __privateGet(this, _logger).debug("unregistering schedule", {
343
+ id
344
+ });
345
+ const response = await zodfetch(import_zod.z.object({
346
+ ok: import_zod.z.boolean()
347
+ }), `${__privateGet(this, _apiUrl)}/api/v1/${client}/schedules/${id}/registrations/${encodeURIComponent(key)}`, {
348
+ method: "DELETE",
349
+ headers: {
350
+ "Content-Type": "application/json",
351
+ Authorization: `Bearer ${apiKey}`
352
+ }
353
+ });
354
+ return response;
355
+ }
356
+ async getAuth(client, id) {
357
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
358
+ __privateGet(this, _logger).debug("getting auth", {
359
+ id
360
+ });
361
+ const response = await zodfetch(import_core.ConnectionAuthSchema, `${__privateGet(this, _apiUrl)}/api/v1/${client}/auth/${id}`, {
362
+ method: "GET",
363
+ headers: {
364
+ Accept: "application/json",
365
+ Authorization: `Bearer ${apiKey}`
366
+ }
367
+ }, {
368
+ optional: true
369
+ });
370
+ return response;
371
+ }
372
+ async getEvent(eventId) {
373
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
374
+ __privateGet(this, _logger).debug("Getting Event", {
375
+ eventId
376
+ });
377
+ return await zodfetch(import_core.GetEventSchema, `${__privateGet(this, _apiUrl)}/api/v1/events/${eventId}`, {
378
+ method: "GET",
379
+ headers: {
380
+ Authorization: `Bearer ${apiKey}`
381
+ }
382
+ });
383
+ }
384
+ async getRun(runId, options) {
385
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
386
+ __privateGet(this, _logger).debug("Getting Run", {
387
+ runId
388
+ });
389
+ return await zodfetch(import_core.GetRunSchema, (0, import_core.urlWithSearchParams)(`${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}`, options), {
390
+ method: "GET",
391
+ headers: {
392
+ Authorization: `Bearer ${apiKey}`
393
+ }
394
+ });
395
+ }
396
+ async cancelRun(runId) {
397
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
398
+ __privateGet(this, _logger).debug("Cancelling Run", {
399
+ runId
400
+ });
401
+ return await zodfetch(import_core.GetRunSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/cancel`, {
402
+ method: "POST",
403
+ headers: {
404
+ "Content-Type": "application/json",
405
+ Authorization: `Bearer ${apiKey}`
406
+ }
407
+ });
408
+ }
409
+ async getRunStatuses(runId) {
410
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
411
+ __privateGet(this, _logger).debug("Getting Run statuses", {
412
+ runId
413
+ });
414
+ return await zodfetch(import_core.GetRunStatusesSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/statuses`, {
415
+ method: "GET",
416
+ headers: {
417
+ Authorization: `Bearer ${apiKey}`
418
+ }
419
+ });
420
+ }
421
+ async getRuns(jobSlug, options) {
422
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
423
+ __privateGet(this, _logger).debug("Getting Runs", {
424
+ jobSlug
425
+ });
426
+ return await zodfetch(import_core.GetRunsSchema, (0, import_core.urlWithSearchParams)(`${__privateGet(this, _apiUrl)}/api/v1/jobs/${jobSlug}/runs`, options), {
427
+ method: "GET",
428
+ headers: {
429
+ Authorization: `Bearer ${apiKey}`
430
+ }
431
+ });
432
+ }
433
+ };
434
+ __name(ApiClient, "ApiClient");
435
+ _apiUrl = new WeakMap();
436
+ _options = new WeakMap();
437
+ _logger = new WeakMap();
438
+ _apiKey = new WeakSet();
439
+ apiKey_fn = /* @__PURE__ */ __name(async function() {
440
+ const apiKey = getApiKey(__privateGet(this, _options).apiKey);
441
+ if (apiKey.status === "invalid") {
442
+ throw new Error("Invalid API key");
443
+ } else if (apiKey.status === "missing") {
444
+ throw new Error("Missing API key");
445
+ }
446
+ return apiKey.apiKey;
447
+ }, "#apiKey");
448
+ function getApiKey(key) {
449
+ const apiKey = key ?? process.env.TRIGGER_API_KEY;
450
+ if (!apiKey) {
451
+ return {
452
+ status: "missing"
453
+ };
454
+ }
455
+ const isValid = apiKey.match(/^tr_[a-z]+_[a-zA-Z0-9]+$/);
456
+ if (!isValid) {
457
+ return {
458
+ status: "invalid",
459
+ apiKey
460
+ };
461
+ }
462
+ return {
463
+ status: "valid",
464
+ apiKey
465
+ };
466
+ }
467
+ __name(getApiKey, "getApiKey");
468
+ async function zodfetchWithVersions(versionedSchemaMap, unversionedSchema, url, requestInit, options) {
469
+ const response = await fetch(url, requestInit);
470
+ if ((!requestInit || requestInit.method === "GET") && response.status === 404 && options?.optional) {
471
+ return;
472
+ }
473
+ if (response.status >= 400 && response.status < 500) {
474
+ const body = await response.json();
475
+ throw new Error(body.error);
476
+ }
477
+ if (response.status !== 200) {
478
+ throw new Error(options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`);
479
+ }
480
+ const jsonBody = await response.json();
481
+ const version = response.headers.get("trigger-version");
482
+ if (!version) {
483
+ return {
484
+ version: "unversioned",
485
+ body: unversionedSchema.parse(jsonBody)
486
+ };
487
+ }
488
+ const versionedSchema = versionedSchemaMap[version];
489
+ if (!versionedSchema) {
490
+ throw new Error(`Unknown version ${version}`);
491
+ }
492
+ return {
493
+ version,
494
+ body: versionedSchema.parse(jsonBody)
495
+ };
496
+ }
497
+ __name(zodfetchWithVersions, "zodfetchWithVersions");
498
+ async function zodfetch(schema, url, requestInit, options) {
499
+ const response = await fetch(url, requestInit);
500
+ if ((!requestInit || requestInit.method === "GET") && response.status === 404 && options?.optional) {
501
+ return;
502
+ }
503
+ if (response.status >= 400 && response.status < 500) {
504
+ const body = await response.json();
505
+ throw new Error(body.error);
506
+ }
507
+ if (response.status !== 200) {
508
+ throw new Error(options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`);
509
+ }
510
+ const jsonBody = await response.json();
511
+ return schema.parse(jsonBody);
512
+ }
513
+ __name(zodfetch, "zodfetch");
514
+
515
+ // src/errors.ts
516
+ var ResumeWithTaskError = class {
517
+ constructor(task) {
518
+ this.task = task;
519
+ }
520
+ };
521
+ __name(ResumeWithTaskError, "ResumeWithTaskError");
522
+ var RetryWithTaskError = class {
523
+ constructor(cause, task, retryAt) {
524
+ this.cause = cause;
525
+ this.task = task;
526
+ this.retryAt = retryAt;
527
+ }
528
+ };
529
+ __name(RetryWithTaskError, "RetryWithTaskError");
530
+ var CanceledWithTaskError = class {
531
+ constructor(task) {
532
+ this.task = task;
533
+ }
534
+ };
535
+ __name(CanceledWithTaskError, "CanceledWithTaskError");
536
+ var YieldExecutionError = class {
537
+ constructor(key) {
538
+ this.key = key;
539
+ }
540
+ };
541
+ __name(YieldExecutionError, "YieldExecutionError");
542
+ var AutoYieldExecutionError = class {
543
+ constructor(location, timeRemaining, timeElapsed) {
544
+ this.location = location;
545
+ this.timeRemaining = timeRemaining;
546
+ this.timeElapsed = timeElapsed;
547
+ }
548
+ };
549
+ __name(AutoYieldExecutionError, "AutoYieldExecutionError");
550
+ var AutoYieldWithCompletedTaskExecutionError = class {
551
+ constructor(id, properties, output, data) {
552
+ this.id = id;
553
+ this.properties = properties;
554
+ this.output = output;
555
+ this.data = data;
556
+ }
557
+ };
558
+ __name(AutoYieldWithCompletedTaskExecutionError, "AutoYieldWithCompletedTaskExecutionError");
559
+ var ParsedPayloadSchemaError = class {
560
+ constructor(schemaErrors) {
561
+ this.schemaErrors = schemaErrors;
562
+ }
563
+ };
564
+ __name(ParsedPayloadSchemaError, "ParsedPayloadSchemaError");
565
+ function isTriggerError(err) {
566
+ return err instanceof ResumeWithTaskError || err instanceof RetryWithTaskError || err instanceof CanceledWithTaskError || err instanceof YieldExecutionError || err instanceof AutoYieldExecutionError || err instanceof AutoYieldWithCompletedTaskExecutionError;
567
+ }
568
+ __name(isTriggerError, "isTriggerError");
569
+
570
+ // src/io.ts
571
+ var import_core3 = require("@trigger.dev/core");
572
+ var import_node_async_hooks = require("async_hooks");
573
+ var import_node_crypto = require("crypto");
574
+
575
+ // src/retry.ts
576
+ var import_core2 = require("@trigger.dev/core");
577
+ var retry = {
578
+ standardBackoff: {
579
+ limit: 8,
580
+ factor: 1.8,
581
+ minTimeoutInMs: 500,
582
+ maxTimeoutInMs: 3e4,
583
+ randomize: true
584
+ }
585
+ };
586
+
587
+ // src/status.ts
588
+ var TriggerStatus = class {
589
+ constructor(id, io) {
590
+ this.id = id;
591
+ this.io = io;
592
+ }
593
+ async update(key, status) {
594
+ const properties = [];
595
+ if (status.label) {
596
+ properties.push({
597
+ label: "Label",
598
+ text: status.label
599
+ });
600
+ }
601
+ if (status.state) {
602
+ properties.push({
603
+ label: "State",
604
+ text: status.state
605
+ });
606
+ }
607
+ return await this.io.runTask(key, async (task) => {
608
+ return await this.io.triggerClient.updateStatus(this.io.runId, this.id, status);
609
+ }, {
610
+ name: status.label ?? `Status update`,
611
+ icon: "bell",
612
+ params: {
613
+ ...status
614
+ },
615
+ properties
616
+ });
617
+ }
618
+ };
619
+ __name(TriggerStatus, "TriggerStatus");
620
+
621
+ // src/io.ts
622
+ var _addToCachedTasks, addToCachedTasks_fn, _detectAutoYield, detectAutoYield_fn, _getTimeElapsed, getTimeElapsed_fn, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn;
623
+ var IO = class {
624
+ constructor(options) {
625
+ __privateAdd(this, _addToCachedTasks);
626
+ __privateAdd(this, _detectAutoYield);
627
+ __privateAdd(this, _getTimeElapsed);
628
+ __privateAdd(this, _getRemainingTimeInMillis);
629
+ __publicField(this, "brb", this.yield.bind(this));
630
+ this._id = options.id;
631
+ this._apiClient = options.apiClient;
632
+ this._triggerClient = options.client;
633
+ this._logger = options.logger ?? new import_core3.Logger("trigger.dev", options.logLevel);
634
+ this._cachedTasks = /* @__PURE__ */ new Map();
635
+ this._jobLogger = options.jobLogger;
636
+ this._jobLogLevel = options.jobLogLevel;
637
+ this._timeOrigin = options.timeOrigin;
638
+ this._executionTimeout = options.executionTimeout;
639
+ this._stats = {
640
+ initialCachedTasks: 0,
641
+ lazyLoadedCachedTasks: 0,
642
+ executedTasks: 0,
643
+ cachedTaskHits: 0,
644
+ cachedTaskMisses: 0,
645
+ noopCachedTaskHits: 0,
646
+ noopCachedTaskMisses: 0
647
+ };
648
+ if (options.cachedTasks) {
649
+ options.cachedTasks.forEach((task) => {
650
+ this._cachedTasks.set(task.idempotencyKey, task);
651
+ });
652
+ this._stats.initialCachedTasks = options.cachedTasks.length;
653
+ }
654
+ this._taskStorage = new import_node_async_hooks.AsyncLocalStorage();
655
+ this._context = options.context;
656
+ this._yieldedExecutions = options.yieldedExecutions ?? [];
657
+ if (options.noopTasksSet) {
658
+ this._noopTasksBloomFilter = import_core3.BloomFilter.deserialize(options.noopTasksSet, import_core3.BloomFilter.NOOP_TASK_SET_SIZE);
659
+ }
660
+ this._cachedTasksCursor = options.cachedTasksCursor;
661
+ this._serverVersion = options.serverVersion ?? "unversioned";
662
+ }
663
+ get stats() {
664
+ return this._stats;
665
+ }
666
+ get runId() {
667
+ return this._id;
668
+ }
669
+ get triggerClient() {
670
+ return this._triggerClient;
671
+ }
672
+ get logger() {
673
+ return new IOLogger(async (level, message, data) => {
674
+ let logLevel = "info";
675
+ if (import_core3.Logger.satisfiesLogLevel(logLevel, this._jobLogLevel)) {
676
+ await this.runTask([
677
+ message,
678
+ level
679
+ ], async (task) => {
680
+ switch (level) {
681
+ case "LOG": {
682
+ this._jobLogger?.log(message, data);
683
+ logLevel = "log";
684
+ break;
685
+ }
686
+ case "DEBUG": {
687
+ this._jobLogger?.debug(message, data);
688
+ logLevel = "debug";
689
+ break;
690
+ }
691
+ case "INFO": {
692
+ this._jobLogger?.info(message, data);
693
+ logLevel = "info";
694
+ break;
695
+ }
696
+ case "WARN": {
697
+ this._jobLogger?.warn(message, data);
698
+ logLevel = "warn";
699
+ break;
700
+ }
701
+ case "ERROR": {
702
+ this._jobLogger?.error(message, data);
703
+ logLevel = "error";
704
+ break;
705
+ }
706
+ }
707
+ }, {
708
+ name: "log",
709
+ icon: "log",
710
+ description: message,
711
+ params: data,
712
+ properties: [
713
+ {
714
+ label: "Level",
715
+ text: level
716
+ }
717
+ ],
718
+ style: {
719
+ style: "minimal",
720
+ variant: level.toLowerCase()
721
+ },
722
+ noop: true
723
+ });
724
+ }
725
+ });
726
+ }
727
+ async wait(key, seconds) {
728
+ return await this.runTask(key, async (task) => {
729
+ }, {
730
+ name: "wait",
731
+ icon: "clock",
732
+ params: {
733
+ seconds
734
+ },
735
+ noop: true,
736
+ delayUntil: new Date(Date.now() + seconds * 1e3),
737
+ style: {
738
+ style: "minimal"
739
+ }
740
+ });
741
+ }
742
+ async createStatus(key, initialStatus) {
743
+ const id = typeof key === "string" ? key : key.join("-");
744
+ const status = new TriggerStatus(id, this);
745
+ await status.update(key, initialStatus);
746
+ return status;
747
+ }
748
+ async backgroundFetch(key, url, requestInit, retry2) {
749
+ const urlObject = new URL(url);
750
+ return await this.runTask(key, async (task) => {
751
+ return task.output;
752
+ }, {
753
+ name: `fetch ${urlObject.hostname}${urlObject.pathname}`,
754
+ params: {
755
+ url,
756
+ requestInit,
757
+ retry: retry2
758
+ },
759
+ operation: "fetch",
760
+ icon: "background",
761
+ noop: false,
762
+ properties: [
763
+ {
764
+ label: "url",
765
+ text: url,
766
+ url
767
+ },
768
+ {
769
+ label: "method",
770
+ text: requestInit?.method ?? "GET"
771
+ },
772
+ {
773
+ label: "background",
774
+ text: "true"
775
+ }
776
+ ]
777
+ });
778
+ }
779
+ async sendEvent(key, event, options) {
780
+ return await this.runTask(key, async (task) => {
781
+ return await this._triggerClient.sendEvent(event, options);
782
+ }, {
783
+ name: "sendEvent",
784
+ params: {
785
+ event,
786
+ options
787
+ },
788
+ properties: [
789
+ {
790
+ label: "name",
791
+ text: event.name
792
+ },
793
+ ...event?.id ? [
794
+ {
795
+ label: "ID",
796
+ text: event.id
797
+ }
798
+ ] : []
799
+ ]
800
+ });
801
+ }
802
+ async getEvent(key, id) {
803
+ return await this.runTask(key, async (task) => {
804
+ return await this._triggerClient.getEvent(id);
805
+ }, {
806
+ name: "getEvent",
807
+ params: {
808
+ id
809
+ },
810
+ properties: [
811
+ {
812
+ label: "id",
813
+ text: id
814
+ }
815
+ ]
816
+ });
817
+ }
818
+ async cancelEvent(key, eventId) {
819
+ return await this.runTask(key, async (task) => {
820
+ return await this._triggerClient.cancelEvent(eventId);
821
+ }, {
822
+ name: "cancelEvent",
823
+ params: {
824
+ eventId
825
+ },
826
+ properties: [
827
+ {
828
+ label: "id",
829
+ text: eventId
830
+ }
831
+ ]
832
+ });
833
+ }
834
+ async updateSource(key, options) {
835
+ return this.runTask(key, async (task) => {
836
+ return await this._apiClient.updateSource(this._triggerClient.id, options.key, options);
837
+ }, {
838
+ name: "Update Source",
839
+ description: "Update Source",
840
+ properties: [
841
+ {
842
+ label: "key",
843
+ text: options.key
844
+ }
845
+ ],
846
+ params: options,
847
+ redact: {
848
+ paths: [
849
+ "secret"
850
+ ]
851
+ }
852
+ });
853
+ }
854
+ async registerInterval(key, dynamicSchedule, id, options) {
855
+ return await this.runTask(key, async (task) => {
856
+ return dynamicSchedule.register(id, {
857
+ type: "interval",
858
+ options
859
+ });
860
+ }, {
861
+ name: "register-interval",
862
+ properties: [
863
+ {
864
+ label: "schedule",
865
+ text: dynamicSchedule.id
866
+ },
867
+ {
868
+ label: "id",
869
+ text: id
870
+ },
871
+ {
872
+ label: "seconds",
873
+ text: options.seconds.toString()
874
+ }
875
+ ],
876
+ params: options
877
+ });
878
+ }
879
+ async unregisterInterval(key, dynamicSchedule, id) {
880
+ return await this.runTask(key, async (task) => {
881
+ return dynamicSchedule.unregister(id);
882
+ }, {
883
+ name: "unregister-interval",
884
+ properties: [
885
+ {
886
+ label: "schedule",
887
+ text: dynamicSchedule.id
888
+ },
889
+ {
890
+ label: "id",
891
+ text: id
892
+ }
893
+ ]
894
+ });
895
+ }
896
+ async registerCron(key, dynamicSchedule, id, options) {
897
+ return await this.runTask(key, async (task) => {
898
+ return dynamicSchedule.register(id, {
899
+ type: "cron",
900
+ options
901
+ });
902
+ }, {
903
+ name: "register-cron",
904
+ properties: [
905
+ {
906
+ label: "schedule",
907
+ text: dynamicSchedule.id
908
+ },
909
+ {
910
+ label: "id",
911
+ text: id
912
+ },
913
+ {
914
+ label: "cron",
915
+ text: options.cron
916
+ }
917
+ ],
918
+ params: options
919
+ });
920
+ }
921
+ async unregisterCron(key, dynamicSchedule, id) {
922
+ return await this.runTask(key, async (task) => {
923
+ return dynamicSchedule.unregister(id);
924
+ }, {
925
+ name: "unregister-cron",
926
+ properties: [
927
+ {
928
+ label: "schedule",
929
+ text: dynamicSchedule.id
930
+ },
931
+ {
932
+ label: "id",
933
+ text: id
934
+ }
935
+ ]
936
+ });
937
+ }
938
+ async registerTrigger(key, trigger, id, params) {
939
+ return await this.runTask(key, async (task) => {
940
+ const registration = await this.runTask("register-source", async (subtask1) => {
941
+ return trigger.register(id, params);
942
+ }, {
943
+ name: "register-source"
944
+ });
945
+ return {
946
+ id: registration.id,
947
+ key: registration.source.key
948
+ };
949
+ }, {
950
+ name: "register-trigger",
951
+ properties: [
952
+ {
953
+ label: "trigger",
954
+ text: trigger.id
955
+ },
956
+ {
957
+ label: "id",
958
+ text: id
959
+ }
960
+ ],
961
+ params
962
+ });
963
+ }
964
+ async getAuth(key, clientId) {
965
+ if (!clientId) {
966
+ return;
967
+ }
968
+ return this.runTask(key, async (task) => {
969
+ return await this._triggerClient.getAuth(clientId);
970
+ }, {
971
+ name: "get-auth"
972
+ });
973
+ }
974
+ async runTask(key, callback, options, onError) {
975
+ __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "start_task", 500);
976
+ const parentId = this._taskStorage.getStore()?.taskId;
977
+ if (parentId) {
978
+ this._logger.debug("Using parent task", {
979
+ parentId,
980
+ key,
981
+ options
982
+ });
983
+ }
984
+ const idempotencyKey = await generateIdempotencyKey([
985
+ this._id,
986
+ parentId ?? "",
987
+ key
988
+ ].flat());
989
+ const cachedTask = this._cachedTasks.get(idempotencyKey);
990
+ if (cachedTask && cachedTask.status === "COMPLETED") {
991
+ this._logger.debug("Using completed cached task", {
992
+ idempotencyKey
993
+ });
994
+ this._stats.cachedTaskHits++;
995
+ return cachedTask.output;
996
+ }
997
+ if (options?.noop && this._noopTasksBloomFilter) {
998
+ if (this._noopTasksBloomFilter.test(idempotencyKey)) {
999
+ this._logger.debug("task idempotency key exists in noopTasksBloomFilter", {
1000
+ idempotencyKey
1001
+ });
1002
+ this._stats.noopCachedTaskHits++;
1003
+ return {};
1004
+ }
1005
+ }
1006
+ const response = await this._apiClient.runTask(this._id, {
1007
+ idempotencyKey,
1008
+ displayKey: typeof key === "string" ? key : void 0,
1009
+ noop: false,
1010
+ ...options ?? {},
1011
+ parentId
1012
+ }, {
1013
+ cachedTasksCursor: this._cachedTasksCursor
1014
+ });
1015
+ const task = response.version === import_core3.API_VERSIONS.LAZY_LOADED_CACHED_TASKS ? response.body.task : response.body;
1016
+ if (response.version === import_core3.API_VERSIONS.LAZY_LOADED_CACHED_TASKS) {
1017
+ this._cachedTasksCursor = response.body.cachedTasks?.cursor;
1018
+ for (const cachedTask2 of response.body.cachedTasks?.tasks ?? []) {
1019
+ if (!this._cachedTasks.has(cachedTask2.idempotencyKey)) {
1020
+ this._cachedTasks.set(cachedTask2.idempotencyKey, cachedTask2);
1021
+ this._logger.debug("Injecting lazy loaded task into task cache", {
1022
+ idempotencyKey: cachedTask2.idempotencyKey
1023
+ });
1024
+ this._stats.lazyLoadedCachedTasks++;
1025
+ }
1026
+ }
1027
+ }
1028
+ if (task.status === "CANCELED") {
1029
+ this._logger.debug("Task canceled", {
1030
+ idempotencyKey,
1031
+ task
1032
+ });
1033
+ throw new CanceledWithTaskError(task);
1034
+ }
1035
+ if (task.status === "COMPLETED") {
1036
+ if (task.noop) {
1037
+ this._logger.debug("Noop Task completed", {
1038
+ idempotencyKey
1039
+ });
1040
+ this._noopTasksBloomFilter?.add(task.idempotencyKey);
1041
+ } else {
1042
+ this._logger.debug("Cache miss", {
1043
+ idempotencyKey
1044
+ });
1045
+ this._stats.cachedTaskMisses++;
1046
+ __privateMethod(this, _addToCachedTasks, addToCachedTasks_fn).call(this, task);
1047
+ }
1048
+ return task.output;
1049
+ }
1050
+ if (task.status === "ERRORED") {
1051
+ this._logger.debug("Task errored", {
1052
+ idempotencyKey,
1053
+ task
1054
+ });
1055
+ throw new Error(task.error ?? task?.output ? JSON.stringify(task.output) : "Task errored");
1056
+ }
1057
+ __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "before_execute_task", 1500);
1058
+ const executeTask = /* @__PURE__ */ __name(async () => {
1059
+ try {
1060
+ const result = await callback(task, this);
1061
+ if (task.status === "WAITING" && task.callbackUrl) {
1062
+ this._logger.debug("Waiting for remote callback", {
1063
+ idempotencyKey,
1064
+ task
1065
+ });
1066
+ return {};
1067
+ }
1068
+ const output = import_core3.SerializableJsonSchema.parse(result);
1069
+ this._logger.debug("Completing using output", {
1070
+ idempotencyKey,
1071
+ task
1072
+ });
1073
+ __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "before_complete_task", 500, task, output);
1074
+ const completedTask = await this._apiClient.completeTask(this._id, task.id, {
1075
+ output: output ?? void 0,
1076
+ properties: task.outputProperties ?? void 0
1077
+ });
1078
+ this._stats.executedTasks++;
1079
+ if (completedTask.status === "CANCELED") {
1080
+ throw new CanceledWithTaskError(completedTask);
1081
+ }
1082
+ __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "after_complete_task", 500);
1083
+ return output;
1084
+ } catch (error) {
1085
+ if (isTriggerError(error)) {
1086
+ throw error;
1087
+ }
1088
+ let skipRetrying = false;
1089
+ if (onError) {
1090
+ try {
1091
+ const onErrorResult = onError(error, task, this);
1092
+ if (onErrorResult) {
1093
+ if (onErrorResult instanceof Error) {
1094
+ error = onErrorResult;
1095
+ } else {
1096
+ skipRetrying = !!onErrorResult.skipRetrying;
1097
+ if (onErrorResult.retryAt && !skipRetrying) {
1098
+ const parsedError2 = import_core3.ErrorWithStackSchema.safeParse(onErrorResult.error);
1099
+ throw new RetryWithTaskError(parsedError2.success ? parsedError2.data : {
1100
+ message: "Unknown error"
1101
+ }, task, onErrorResult.retryAt);
1102
+ }
1103
+ }
1104
+ }
1105
+ } catch (innerError) {
1106
+ if (isTriggerError(innerError)) {
1107
+ throw innerError;
1108
+ }
1109
+ error = innerError;
1110
+ }
1111
+ }
1112
+ const parsedError = import_core3.ErrorWithStackSchema.safeParse(error);
1113
+ if (options?.retry && !skipRetrying) {
1114
+ const retryAt = (0, import_core2.calculateRetryAt)(options.retry, task.attempts - 1);
1115
+ if (retryAt) {
1116
+ throw new RetryWithTaskError(parsedError.success ? parsedError.data : {
1117
+ message: "Unknown error"
1118
+ }, task, retryAt);
1119
+ }
1120
+ }
1121
+ if (parsedError.success) {
1122
+ await this._apiClient.failTask(this._id, task.id, {
1123
+ error: parsedError.data
1124
+ });
1125
+ } else {
1126
+ await this._apiClient.failTask(this._id, task.id, {
1127
+ error: {
1128
+ message: JSON.stringify(error),
1129
+ name: "Unknown Error"
1130
+ }
1131
+ });
1132
+ }
1133
+ throw error;
1134
+ }
1135
+ }, "executeTask");
1136
+ if (task.status === "WAITING") {
1137
+ this._logger.debug("Task waiting", {
1138
+ idempotencyKey,
1139
+ task
1140
+ });
1141
+ if (task.callbackUrl) {
1142
+ await this._taskStorage.run({
1143
+ taskId: task.id
1144
+ }, executeTask);
1145
+ }
1146
+ throw new ResumeWithTaskError(task);
1147
+ }
1148
+ if (task.status === "RUNNING" && typeof task.operation === "string") {
1149
+ this._logger.debug("Task running operation", {
1150
+ idempotencyKey,
1151
+ task
1152
+ });
1153
+ throw new ResumeWithTaskError(task);
1154
+ }
1155
+ return this._taskStorage.run({
1156
+ taskId: task.id
1157
+ }, executeTask);
1158
+ }
1159
+ yield(key) {
1160
+ if (!(0, import_core3.supportsFeature)("yieldExecution", this._serverVersion)) {
1161
+ 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.");
1162
+ return;
1163
+ }
1164
+ if (this._yieldedExecutions.includes(key)) {
1165
+ return;
1166
+ }
1167
+ throw new YieldExecutionError(key);
1168
+ }
1169
+ async try(tryCallback, catchCallback) {
1170
+ try {
1171
+ return await tryCallback();
1172
+ } catch (error) {
1173
+ if (isTriggerError(error)) {
1174
+ throw error;
1175
+ }
1176
+ return await catchCallback(error);
1177
+ }
1178
+ }
1179
+ };
1180
+ __name(IO, "IO");
1181
+ _addToCachedTasks = new WeakSet();
1182
+ addToCachedTasks_fn = /* @__PURE__ */ __name(function(task) {
1183
+ this._cachedTasks.set(task.idempotencyKey, task);
1184
+ }, "#addToCachedTasks");
1185
+ _detectAutoYield = new WeakSet();
1186
+ detectAutoYield_fn = /* @__PURE__ */ __name(function(location, threshold = 1500, task1, output) {
1187
+ const timeRemaining = __privateMethod(this, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn).call(this);
1188
+ if (timeRemaining && timeRemaining < threshold) {
1189
+ if (task1) {
1190
+ throw new AutoYieldWithCompletedTaskExecutionError(task1.id, task1.outputProperties ?? [], output, {
1191
+ location,
1192
+ timeRemaining,
1193
+ timeElapsed: __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this)
1194
+ });
1195
+ } else {
1196
+ throw new AutoYieldExecutionError(location, timeRemaining, __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this));
1197
+ }
1198
+ }
1199
+ }, "#detectAutoYield");
1200
+ _getTimeElapsed = new WeakSet();
1201
+ getTimeElapsed_fn = /* @__PURE__ */ __name(function() {
1202
+ return performance.now() - this._timeOrigin;
1203
+ }, "#getTimeElapsed");
1204
+ _getRemainingTimeInMillis = new WeakSet();
1205
+ getRemainingTimeInMillis_fn = /* @__PURE__ */ __name(function() {
1206
+ if (this._executionTimeout) {
1207
+ return this._executionTimeout - (performance.now() - this._timeOrigin);
1208
+ }
1209
+ return void 0;
1210
+ }, "#getRemainingTimeInMillis");
1211
+ async function generateIdempotencyKey(keyMaterial) {
1212
+ const keys = keyMaterial.map((key2) => {
1213
+ if (typeof key2 === "string") {
1214
+ return key2;
1215
+ }
1216
+ return stableStringify(key2);
1217
+ });
1218
+ const key = keys.join(":");
1219
+ const hash = await import_node_crypto.webcrypto.subtle.digest("SHA-256", Buffer.from(key));
1220
+ return Buffer.from(hash).toString("hex");
1221
+ }
1222
+ __name(generateIdempotencyKey, "generateIdempotencyKey");
1223
+ function stableStringify(obj) {
1224
+ function sortKeys(obj2) {
1225
+ if (typeof obj2 !== "object" || obj2 === null) {
1226
+ return obj2;
1227
+ }
1228
+ if (Array.isArray(obj2)) {
1229
+ return obj2.map(sortKeys);
1230
+ }
1231
+ const sortedKeys = Object.keys(obj2).sort();
1232
+ const sortedObj2 = {};
1233
+ for (const key of sortedKeys) {
1234
+ sortedObj2[key] = sortKeys(obj2[key]);
1235
+ }
1236
+ return sortedObj2;
1237
+ }
1238
+ __name(sortKeys, "sortKeys");
1239
+ const sortedObj = sortKeys(obj);
1240
+ return JSON.stringify(sortedObj);
1241
+ }
1242
+ __name(stableStringify, "stableStringify");
1243
+ var IOLogger = class {
1244
+ constructor(callback) {
1245
+ this.callback = callback;
1246
+ }
1247
+ log(message, properties) {
1248
+ return this.callback("LOG", message, properties);
1249
+ }
1250
+ debug(message, properties) {
1251
+ return this.callback("DEBUG", message, properties);
1252
+ }
1253
+ info(message, properties) {
1254
+ return this.callback("INFO", message, properties);
1255
+ }
1256
+ warn(message, properties) {
1257
+ return this.callback("WARN", message, properties);
1258
+ }
1259
+ error(message, properties) {
1260
+ return this.callback("ERROR", message, properties);
1261
+ }
1262
+ };
1263
+ __name(IOLogger, "IOLogger");
1264
+
1265
+ // src/ioWithIntegrations.ts
1266
+ function createIOWithIntegrations(io, auths, integrations) {
1267
+ if (!integrations) {
1268
+ return io;
1269
+ }
1270
+ const connections = Object.entries(integrations).reduce((acc, [connectionKey, integration]) => {
1271
+ let auth = auths?.[connectionKey];
1272
+ acc[connectionKey] = {
1273
+ integration,
1274
+ auth
1275
+ };
1276
+ return acc;
1277
+ }, {});
1278
+ return new Proxy(io, {
1279
+ get(target, prop, receiver) {
1280
+ if (prop === "__io") {
1281
+ return io;
1282
+ }
1283
+ if (typeof prop === "string" && prop in connections) {
1284
+ const { integration, auth } = connections[prop];
1285
+ return integration.cloneForRun(io, prop, auth);
1286
+ }
1287
+ const value = Reflect.get(target, prop, receiver);
1288
+ return typeof value == "function" ? value.bind(target) : value;
1289
+ }
1290
+ });
1291
+ }
1292
+ __name(createIOWithIntegrations, "createIOWithIntegrations");
1293
+
1294
+ // src/utils/typedAsyncLocalStorage.ts
1295
+ var import_node_async_hooks2 = require("async_hooks");
1296
+ var TypedAsyncLocalStorage = class {
1297
+ constructor() {
1298
+ this.storage = new import_node_async_hooks2.AsyncLocalStorage();
1299
+ }
1300
+ runWith(context, fn) {
1301
+ return this.storage.run(context, fn);
1302
+ }
1303
+ getStore() {
1304
+ return this.storage.getStore();
1305
+ }
1306
+ };
1307
+ __name(TypedAsyncLocalStorage, "TypedAsyncLocalStorage");
1308
+
1309
+ // src/runLocalStorage.ts
1310
+ var runLocalStorage = new TypedAsyncLocalStorage();
1311
+
1312
+ // src/triggers/dynamic.ts
1313
+ var import_core4 = require("@trigger.dev/core");
1314
+ var _client, _options2;
1315
+ var DynamicTrigger = class {
1316
+ constructor(client, options) {
1317
+ __privateAdd(this, _client, void 0);
1318
+ __privateAdd(this, _options2, void 0);
1319
+ __privateSet(this, _client, client);
1320
+ __privateSet(this, _options2, options);
1321
+ this.source = options.source;
1322
+ client.attachDynamicTrigger(this);
1323
+ }
1324
+ toJSON() {
1325
+ return {
1326
+ type: "dynamic",
1327
+ id: __privateGet(this, _options2).id
1328
+ };
1329
+ }
1330
+ get id() {
1331
+ return __privateGet(this, _options2).id;
1332
+ }
1333
+ get event() {
1334
+ return __privateGet(this, _options2).event;
1335
+ }
1336
+ registeredTriggerForParams(params, options = {}) {
1337
+ const key = slugifyId(this.source.key(params));
1338
+ return {
1339
+ rule: {
1340
+ event: this.event.name,
1341
+ source: this.event.source,
1342
+ payload: (0, import_core4.deepMergeFilters)(this.source.filter(params), this.event.filter ?? {}, options.filter ?? {})
1343
+ },
1344
+ source: {
1345
+ version: "2",
1346
+ key,
1347
+ channel: this.source.channel,
1348
+ params,
1349
+ options: {
1350
+ event: typeof this.event.name === "string" ? [
1351
+ this.event.name
1352
+ ] : this.event.name
1353
+ },
1354
+ integration: {
1355
+ id: this.source.integration.id,
1356
+ metadata: this.source.integration.metadata,
1357
+ authSource: this.source.integration.authSource
1358
+ }
1359
+ },
1360
+ accountId: options.accountId
1361
+ };
1362
+ }
1363
+ async register(key, params, options = {}) {
1364
+ const runStore = runLocalStorage.getStore();
1365
+ if (!runStore) {
1366
+ return __privateGet(this, _client).registerTrigger(this.id, key, this.registeredTriggerForParams(params, options));
1367
+ }
1368
+ const { io } = runStore;
1369
+ return await io.runTask([
1370
+ key,
1371
+ "register"
1372
+ ], async (task) => {
1373
+ return __privateGet(this, _client).registerTrigger(this.id, key, this.registeredTriggerForParams(params, options));
1374
+ }, {
1375
+ name: "Register Dynamic Trigger",
1376
+ properties: [
1377
+ {
1378
+ label: "Dynamic Trigger ID",
1379
+ text: this.id
1380
+ },
1381
+ {
1382
+ label: "ID",
1383
+ text: key
1384
+ }
1385
+ ],
1386
+ params
1387
+ });
1388
+ }
1389
+ attachToJob(triggerClient, job) {
1390
+ triggerClient.attachJobToDynamicTrigger(job, this);
1391
+ }
1392
+ get preprocessRuns() {
1393
+ return true;
1394
+ }
1395
+ };
1396
+ __name(DynamicTrigger, "DynamicTrigger");
1397
+ _client = new WeakMap();
1398
+ _options2 = new WeakMap();
1399
+
1400
+ // src/triggers/eventTrigger.ts
1401
+ var import_core5 = require("@trigger.dev/core");
1402
+
1403
+ // src/utils/formatSchemaErrors.ts
1404
+ function formatSchemaErrors(errors) {
1405
+ return errors.map((error) => {
1406
+ const { path, message } = error;
1407
+ return {
1408
+ path: path.map(String),
1409
+ message
1410
+ };
1411
+ });
1412
+ }
1413
+ __name(formatSchemaErrors, "formatSchemaErrors");
1414
+
1415
+ // src/triggers/eventTrigger.ts
1416
+ var _options3;
1417
+ var EventTrigger = class {
1418
+ constructor(options) {
1419
+ __privateAdd(this, _options3, void 0);
1420
+ __privateSet(this, _options3, options);
1421
+ }
1422
+ toJSON() {
1423
+ return {
1424
+ type: "static",
1425
+ title: __privateGet(this, _options3).name ?? __privateGet(this, _options3).event.title,
1426
+ rule: {
1427
+ event: __privateGet(this, _options3).name ?? __privateGet(this, _options3).event.name,
1428
+ source: __privateGet(this, _options3).source ?? "trigger.dev",
1429
+ payload: (0, import_core5.deepMergeFilters)(__privateGet(this, _options3).filter ?? {}, __privateGet(this, _options3).event.filter ?? {})
1430
+ }
1431
+ };
1432
+ }
1433
+ get event() {
1434
+ return __privateGet(this, _options3).event;
1435
+ }
1436
+ attachToJob(triggerClient, job) {
1437
+ }
1438
+ get preprocessRuns() {
1439
+ return false;
1440
+ }
1441
+ };
1442
+ __name(EventTrigger, "EventTrigger");
1443
+ _options3 = new WeakMap();
1444
+ function eventTrigger(options) {
1445
+ return new EventTrigger({
1446
+ name: options.name,
1447
+ filter: options.filter,
1448
+ event: {
1449
+ name: options.name,
1450
+ title: "Event",
1451
+ source: options.source ?? "trigger.dev",
1452
+ icon: "custom-event",
1453
+ examples: options.examples,
1454
+ parsePayload: (rawPayload) => {
1455
+ if (options.schema) {
1456
+ const results = options.schema.safeParse(rawPayload);
1457
+ if (!results.success) {
1458
+ throw new ParsedPayloadSchemaError(formatSchemaErrors(results.error.issues));
1459
+ }
1460
+ return results.data;
1461
+ }
1462
+ return rawPayload;
1463
+ }
1464
+ }
1465
+ });
1466
+ }
1467
+ __name(eventTrigger, "eventTrigger");
1468
+
1469
+ // src/triggers/scheduled.ts
1470
+ var import_core6 = require("@trigger.dev/core");
1471
+ var import_cronstrue = __toESM(require("cronstrue"));
1472
+ var examples = [
1473
+ {
1474
+ id: "now",
1475
+ name: "Now",
1476
+ icon: "clock",
1477
+ payload: {
1478
+ ts: import_core6.currentDate.marker,
1479
+ lastTimestamp: import_core6.currentDate.marker
1480
+ }
1481
+ }
1482
+ ];
1483
+ var IntervalTrigger = class {
1484
+ constructor(options) {
1485
+ this.options = options;
1486
+ }
1487
+ get event() {
1488
+ return {
1489
+ name: "trigger.scheduled",
1490
+ title: "Schedule",
1491
+ source: "trigger.dev",
1492
+ icon: "schedule-interval",
1493
+ examples,
1494
+ parsePayload: import_core6.ScheduledPayloadSchema.parse,
1495
+ properties: [
1496
+ {
1497
+ label: "Interval",
1498
+ text: `${this.options.seconds}s`
1499
+ }
1500
+ ]
1501
+ };
1502
+ }
1503
+ attachToJob(triggerClient, job) {
1504
+ }
1505
+ get preprocessRuns() {
1506
+ return false;
1507
+ }
1508
+ toJSON() {
1509
+ return {
1510
+ type: "scheduled",
1511
+ schedule: {
1512
+ type: "interval",
1513
+ options: {
1514
+ seconds: this.options.seconds
1515
+ }
1516
+ }
1517
+ };
1518
+ }
1519
+ };
1520
+ __name(IntervalTrigger, "IntervalTrigger");
1521
+ function intervalTrigger(options) {
1522
+ return new IntervalTrigger(options);
1523
+ }
1524
+ __name(intervalTrigger, "intervalTrigger");
1525
+ var CronTrigger = class {
1526
+ constructor(options) {
1527
+ this.options = options;
1528
+ }
1529
+ get event() {
1530
+ const humanReadable = import_cronstrue.default.toString(this.options.cron, {
1531
+ throwExceptionOnParseError: false
1532
+ });
1533
+ return {
1534
+ name: "trigger.scheduled",
1535
+ title: "Cron Schedule",
1536
+ source: "trigger.dev",
1537
+ icon: "schedule-cron",
1538
+ examples,
1539
+ parsePayload: import_core6.ScheduledPayloadSchema.parse,
1540
+ properties: [
1541
+ {
1542
+ label: "cron",
1543
+ text: this.options.cron
1544
+ },
1545
+ {
1546
+ label: "Schedule",
1547
+ text: humanReadable
1548
+ }
1549
+ ]
1550
+ };
1551
+ }
1552
+ attachToJob(triggerClient, job) {
1553
+ }
1554
+ get preprocessRuns() {
1555
+ return false;
1556
+ }
1557
+ toJSON() {
1558
+ return {
1559
+ type: "scheduled",
1560
+ schedule: {
1561
+ type: "cron",
1562
+ options: {
1563
+ cron: this.options.cron
1564
+ }
1565
+ }
1566
+ };
1567
+ }
1568
+ };
1569
+ __name(CronTrigger, "CronTrigger");
1570
+ function cronTrigger(options) {
1571
+ return new CronTrigger(options);
1572
+ }
1573
+ __name(cronTrigger, "cronTrigger");
1574
+ var DynamicSchedule = class {
1575
+ constructor(client, options) {
1576
+ this.client = client;
1577
+ this.options = options;
1578
+ client.attachDynamicSchedule(this.options.id);
1579
+ }
1580
+ get id() {
1581
+ return this.options.id;
1582
+ }
1583
+ get event() {
1584
+ return {
1585
+ name: "trigger.scheduled",
1586
+ title: "Dynamic Schedule",
1587
+ source: "trigger.dev",
1588
+ icon: "schedule-dynamic",
1589
+ examples,
1590
+ parsePayload: import_core6.ScheduledPayloadSchema.parse
1591
+ };
1592
+ }
1593
+ async register(key, metadata) {
1594
+ const runStore = runLocalStorage.getStore();
1595
+ if (!runStore) {
1596
+ return this.client.registerSchedule(this.id, key, metadata);
1597
+ }
1598
+ const { io } = runStore;
1599
+ return await io.runTask([
1600
+ key,
1601
+ "register"
1602
+ ], async (task) => {
1603
+ return this.client.registerSchedule(this.id, key, metadata);
1604
+ }, {
1605
+ name: "Register Schedule",
1606
+ icon: metadata.type === "cron" ? "schedule-cron" : "schedule-interval",
1607
+ properties: [
1608
+ {
1609
+ label: "Dynamic Schedule",
1610
+ text: this.id
1611
+ },
1612
+ {
1613
+ label: "Schedule ID",
1614
+ text: key
1615
+ }
1616
+ ],
1617
+ params: metadata
1618
+ });
1619
+ }
1620
+ async unregister(key) {
1621
+ const runStore = runLocalStorage.getStore();
1622
+ if (!runStore) {
1623
+ return this.client.unregisterSchedule(this.id, key);
1624
+ }
1625
+ const { io } = runStore;
1626
+ return await io.runTask([
1627
+ key,
1628
+ "unregister"
1629
+ ], async (task) => {
1630
+ return this.client.unregisterSchedule(this.id, key);
1631
+ }, {
1632
+ name: "Unregister Schedule",
1633
+ icon: "schedule",
1634
+ properties: [
1635
+ {
1636
+ label: "Dynamic Schedule",
1637
+ text: this.id
1638
+ },
1639
+ {
1640
+ label: "Schedule ID",
1641
+ text: key
1642
+ }
1643
+ ]
1644
+ });
1645
+ }
1646
+ attachToJob(triggerClient, job) {
1647
+ triggerClient.attachDynamicScheduleToJob(this.options.id, job);
1648
+ }
1649
+ get preprocessRuns() {
1650
+ return false;
1651
+ }
1652
+ toJSON() {
1653
+ return {
1654
+ type: "dynamic",
1655
+ id: this.options.id
1656
+ };
1657
+ }
1658
+ };
1659
+ __name(DynamicSchedule, "DynamicSchedule");
1660
+
1661
+ // src/triggerClient.ts
1662
+ var registerSourceEvent = {
1663
+ name: import_core7.REGISTER_SOURCE_EVENT_V2,
1664
+ title: "Register Source",
1665
+ source: "internal",
1666
+ icon: "register-source",
1667
+ parsePayload: import_core7.RegisterSourceEventSchemaV2.parse
1668
+ };
1669
+ var _options4, _registeredJobs, _registeredSources, _registeredHttpSourceHandlers, _registeredDynamicTriggers, _jobMetadataByDynamicTriggers, _registeredSchedules, _authResolvers, _client2, _internalLogger, _preprocessRun, preprocessRun_fn, _executeJob, executeJob_fn, _createRunContext, createRunContext_fn, _createPreprocessRunContext, createPreprocessRunContext_fn, _handleHttpSourceRequest, handleHttpSourceRequest_fn, _resolveConnections, resolveConnections_fn, _resolveConnection, resolveConnection_fn, _buildJobsIndex, buildJobsIndex_fn, _buildJobIndex, buildJobIndex_fn, _buildJobIntegrations, buildJobIntegrations_fn, _buildJobIntegration, buildJobIntegration_fn, _logIOStats, logIOStats_fn, _standardResponseHeaders, standardResponseHeaders_fn;
1670
+ var TriggerClient = class {
1671
+ constructor(options) {
1672
+ __privateAdd(this, _preprocessRun);
1673
+ __privateAdd(this, _executeJob);
1674
+ __privateAdd(this, _createRunContext);
1675
+ __privateAdd(this, _createPreprocessRunContext);
1676
+ __privateAdd(this, _handleHttpSourceRequest);
1677
+ __privateAdd(this, _resolveConnections);
1678
+ __privateAdd(this, _resolveConnection);
1679
+ __privateAdd(this, _buildJobsIndex);
1680
+ __privateAdd(this, _buildJobIndex);
1681
+ __privateAdd(this, _buildJobIntegrations);
1682
+ __privateAdd(this, _buildJobIntegration);
1683
+ __privateAdd(this, _logIOStats);
1684
+ __privateAdd(this, _standardResponseHeaders);
1685
+ __privateAdd(this, _options4, void 0);
1686
+ __privateAdd(this, _registeredJobs, {});
1687
+ __privateAdd(this, _registeredSources, {});
1688
+ __privateAdd(this, _registeredHttpSourceHandlers, {});
1689
+ __privateAdd(this, _registeredDynamicTriggers, {});
1690
+ __privateAdd(this, _jobMetadataByDynamicTriggers, {});
1691
+ __privateAdd(this, _registeredSchedules, {});
1692
+ __privateAdd(this, _authResolvers, {});
1693
+ __privateAdd(this, _client2, void 0);
1694
+ __privateAdd(this, _internalLogger, void 0);
1695
+ this.id = options.id;
1696
+ __privateSet(this, _options4, options);
1697
+ __privateSet(this, _client2, new ApiClient(__privateGet(this, _options4)));
1698
+ __privateSet(this, _internalLogger, new import_core7.Logger("trigger.dev", __privateGet(this, _options4).verbose ? "debug" : "log", [
1699
+ "output",
1700
+ "noopTasksSet"
1701
+ ]));
1702
+ }
1703
+ async handleRequest(request, timeOrigin = performance.now()) {
1704
+ __privateGet(this, _internalLogger).debug("handling request", {
1705
+ url: request.url,
1706
+ headers: Object.fromEntries(request.headers.entries()),
1707
+ method: request.method
1708
+ });
1709
+ const apiKey = request.headers.get("x-trigger-api-key");
1710
+ const triggerVersion = request.headers.get("x-trigger-version");
1711
+ const authorization = this.authorized(apiKey);
1712
+ switch (authorization) {
1713
+ case "authorized": {
1714
+ break;
1715
+ }
1716
+ case "missing-client": {
1717
+ return {
1718
+ status: 401,
1719
+ body: {
1720
+ message: "Unauthorized: client missing apiKey"
1721
+ },
1722
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1723
+ };
1724
+ }
1725
+ case "missing-header": {
1726
+ return {
1727
+ status: 401,
1728
+ body: {
1729
+ message: "Unauthorized: missing x-trigger-api-key header"
1730
+ },
1731
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1732
+ };
1733
+ }
1734
+ case "unauthorized": {
1735
+ return {
1736
+ status: 401,
1737
+ body: {
1738
+ message: `Forbidden: client apiKey mismatch: Make sure you are using the correct API Key for your environment`
1739
+ },
1740
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1741
+ };
1742
+ }
1743
+ }
1744
+ if (request.method !== "POST") {
1745
+ return {
1746
+ status: 405,
1747
+ body: {
1748
+ message: "Method not allowed (only POST is allowed)"
1749
+ },
1750
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1751
+ };
1752
+ }
1753
+ const action = request.headers.get("x-trigger-action");
1754
+ if (!action) {
1755
+ return {
1756
+ status: 400,
1757
+ body: {
1758
+ message: "Missing x-trigger-action header"
1759
+ },
1760
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1761
+ };
1762
+ }
1763
+ switch (action) {
1764
+ case "PING": {
1765
+ const endpointId = request.headers.get("x-trigger-endpoint-id");
1766
+ if (!endpointId) {
1767
+ return {
1768
+ status: 200,
1769
+ body: {
1770
+ ok: false,
1771
+ error: "Missing endpoint ID"
1772
+ },
1773
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1774
+ };
1775
+ }
1776
+ if (this.id !== endpointId) {
1777
+ return {
1778
+ status: 200,
1779
+ body: {
1780
+ ok: false,
1781
+ error: `Endpoint ID mismatch error. Expected ${this.id}, got ${endpointId}`
1782
+ },
1783
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1784
+ };
1785
+ }
1786
+ return {
1787
+ status: 200,
1788
+ body: {
1789
+ ok: true
1790
+ },
1791
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1792
+ };
1793
+ }
1794
+ case "INDEX_ENDPOINT": {
1795
+ const body = {
1796
+ jobs: __privateMethod(this, _buildJobsIndex, buildJobsIndex_fn).call(this),
1797
+ sources: Object.values(__privateGet(this, _registeredSources)),
1798
+ dynamicTriggers: Object.values(__privateGet(this, _registeredDynamicTriggers)).map((trigger) => ({
1799
+ id: trigger.id,
1800
+ jobs: __privateGet(this, _jobMetadataByDynamicTriggers)[trigger.id] ?? [],
1801
+ registerSourceJob: {
1802
+ id: dynamicTriggerRegisterSourceJobId(trigger.id),
1803
+ version: trigger.source.version
1804
+ }
1805
+ })),
1806
+ dynamicSchedules: Object.entries(__privateGet(this, _registeredSchedules)).map(([id, jobs]) => ({
1807
+ id,
1808
+ jobs
1809
+ }))
1810
+ };
1811
+ return {
1812
+ status: 200,
1813
+ body,
1814
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1815
+ };
1816
+ }
1817
+ case "INITIALIZE_TRIGGER": {
1818
+ const json = await request.json();
1819
+ const body = import_core7.InitializeTriggerBodySchema.safeParse(json);
1820
+ if (!body.success) {
1821
+ return {
1822
+ status: 400,
1823
+ body: {
1824
+ message: "Invalid trigger body"
1825
+ }
1826
+ };
1827
+ }
1828
+ const dynamicTrigger = __privateGet(this, _registeredDynamicTriggers)[body.data.id];
1829
+ if (!dynamicTrigger) {
1830
+ return {
1831
+ status: 404,
1832
+ body: {
1833
+ message: "Dynamic trigger not found"
1834
+ }
1835
+ };
1836
+ }
1837
+ return {
1838
+ status: 200,
1839
+ body: dynamicTrigger.registeredTriggerForParams(body.data.params),
1840
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1841
+ };
1842
+ }
1843
+ case "EXECUTE_JOB": {
1844
+ const json = await request.json();
1845
+ const execution = import_core7.RunJobBodySchema.safeParse(json);
1846
+ if (!execution.success) {
1847
+ return {
1848
+ status: 400,
1849
+ body: {
1850
+ message: "Invalid execution"
1851
+ }
1852
+ };
1853
+ }
1854
+ const job = __privateGet(this, _registeredJobs)[execution.data.job.id];
1855
+ if (!job) {
1856
+ return {
1857
+ status: 404,
1858
+ body: {
1859
+ message: "Job not found"
1860
+ }
1861
+ };
1862
+ }
1863
+ const results = await __privateMethod(this, _executeJob, executeJob_fn).call(this, execution.data, job, timeOrigin, triggerVersion);
1864
+ return {
1865
+ status: 200,
1866
+ body: results,
1867
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1868
+ };
1869
+ }
1870
+ case "PREPROCESS_RUN": {
1871
+ const json = await request.json();
1872
+ const body = import_core7.PreprocessRunBodySchema.safeParse(json);
1873
+ if (!body.success) {
1874
+ return {
1875
+ status: 400,
1876
+ body: {
1877
+ message: "Invalid body"
1878
+ }
1879
+ };
1880
+ }
1881
+ const job = __privateGet(this, _registeredJobs)[body.data.job.id];
1882
+ if (!job) {
1883
+ return {
1884
+ status: 404,
1885
+ body: {
1886
+ message: "Job not found"
1887
+ }
1888
+ };
1889
+ }
1890
+ const results = await __privateMethod(this, _preprocessRun, preprocessRun_fn).call(this, body.data, job);
1891
+ return {
1892
+ status: 200,
1893
+ body: {
1894
+ abort: results.abort,
1895
+ properties: results.properties
1896
+ },
1897
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1898
+ };
1899
+ }
1900
+ case "DELIVER_HTTP_SOURCE_REQUEST": {
1901
+ const headers = import_core7.HttpSourceRequestHeadersSchema.safeParse(Object.fromEntries(request.headers.entries()));
1902
+ if (!headers.success) {
1903
+ return {
1904
+ status: 400,
1905
+ body: {
1906
+ message: "Invalid headers"
1907
+ }
1908
+ };
1909
+ }
1910
+ const sourceRequestNeedsBody = headers.data["x-ts-http-method"] !== "GET";
1911
+ const sourceRequestInit = {
1912
+ method: headers.data["x-ts-http-method"],
1913
+ headers: headers.data["x-ts-http-headers"],
1914
+ body: sourceRequestNeedsBody ? request.body : void 0
1915
+ };
1916
+ if (sourceRequestNeedsBody) {
1917
+ try {
1918
+ sourceRequestInit.duplex = "half";
1919
+ } catch (error) {
1920
+ }
1921
+ }
1922
+ const sourceRequest = new Request(headers.data["x-ts-http-url"], sourceRequestInit);
1923
+ const key = headers.data["x-ts-key"];
1924
+ const dynamicId = headers.data["x-ts-dynamic-id"];
1925
+ const secret = headers.data["x-ts-secret"];
1926
+ const params = headers.data["x-ts-params"];
1927
+ const data = headers.data["x-ts-data"];
1928
+ const auth = headers.data["x-ts-auth"];
1929
+ const inputMetadata = headers.data["x-ts-metadata"];
1930
+ const source = {
1931
+ key,
1932
+ dynamicId,
1933
+ secret,
1934
+ params,
1935
+ data,
1936
+ auth,
1937
+ metadata: inputMetadata
1938
+ };
1939
+ const { response, events, metadata } = await __privateMethod(this, _handleHttpSourceRequest, handleHttpSourceRequest_fn).call(this, source, sourceRequest);
1940
+ return {
1941
+ status: 200,
1942
+ body: {
1943
+ events,
1944
+ response,
1945
+ metadata
1946
+ },
1947
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1948
+ };
1949
+ }
1950
+ case "VALIDATE": {
1951
+ return {
1952
+ status: 200,
1953
+ body: {
1954
+ ok: true,
1955
+ endpointId: this.id
1956
+ },
1957
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1958
+ };
1959
+ }
1960
+ case "PROBE_EXECUTION_TIMEOUT": {
1961
+ const timeout = 15 * 60 * 1e3;
1962
+ await new Promise((resolve) => setTimeout(resolve, timeout));
1963
+ return {
1964
+ status: 200,
1965
+ body: {
1966
+ ok: true
1967
+ },
1968
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1969
+ };
1970
+ }
1971
+ }
1972
+ return {
1973
+ status: 405,
1974
+ body: {
1975
+ message: "Method not allowed"
1976
+ },
1977
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1978
+ };
1979
+ }
1980
+ defineJob(options) {
1981
+ return new Job(this, options);
1982
+ }
1983
+ defineAuthResolver(integration, resolver) {
1984
+ __privateGet(this, _authResolvers)[integration.id] = resolver;
1985
+ return this;
1986
+ }
1987
+ defineDynamicSchedule(options) {
1988
+ return new DynamicSchedule(this, options);
1989
+ }
1990
+ defineDynamicTrigger(options) {
1991
+ return new DynamicTrigger(this, options);
1992
+ }
1993
+ attach(job) {
1994
+ __privateGet(this, _registeredJobs)[job.id] = job;
1995
+ job.trigger.attachToJob(this, job);
1996
+ }
1997
+ attachDynamicTrigger(trigger) {
1998
+ __privateGet(this, _registeredDynamicTriggers)[trigger.id] = trigger;
1999
+ this.defineJob({
2000
+ id: dynamicTriggerRegisterSourceJobId(trigger.id),
2001
+ name: `Register dynamic trigger ${trigger.id}`,
2002
+ version: trigger.source.version,
2003
+ trigger: new EventTrigger({
2004
+ event: registerSourceEvent,
2005
+ filter: {
2006
+ dynamicTriggerId: [
2007
+ trigger.id
2008
+ ]
2009
+ }
2010
+ }),
2011
+ integrations: {
2012
+ integration: trigger.source.integration
2013
+ },
2014
+ run: async (event, io, ctx) => {
2015
+ const updates = await trigger.source.register(event.source.params, event, io, ctx);
2016
+ if (!updates) {
2017
+ return;
2018
+ }
2019
+ return await io.updateSource("update-source", {
2020
+ key: event.source.key,
2021
+ ...updates
2022
+ });
2023
+ },
2024
+ __internal: true
2025
+ });
2026
+ }
2027
+ attachJobToDynamicTrigger(job, trigger) {
2028
+ const jobs = __privateGet(this, _jobMetadataByDynamicTriggers)[trigger.id] ?? [];
2029
+ jobs.push({
2030
+ id: job.id,
2031
+ version: job.version
2032
+ });
2033
+ __privateGet(this, _jobMetadataByDynamicTriggers)[trigger.id] = jobs;
2034
+ }
2035
+ attachSource(options) {
2036
+ __privateGet(this, _registeredHttpSourceHandlers)[options.key] = async (s, r) => {
2037
+ return await options.source.handle(s, r, __privateGet(this, _internalLogger));
2038
+ };
2039
+ let registeredSource = __privateGet(this, _registeredSources)[options.key];
2040
+ if (!registeredSource) {
2041
+ registeredSource = {
2042
+ version: "2",
2043
+ channel: options.source.channel,
2044
+ key: options.key,
2045
+ params: options.params,
2046
+ options: {},
2047
+ integration: {
2048
+ id: options.source.integration.id,
2049
+ metadata: options.source.integration.metadata,
2050
+ authSource: options.source.integration.authSource
2051
+ },
2052
+ registerSourceJob: {
2053
+ id: options.key,
2054
+ version: options.source.version
2055
+ }
2056
+ };
2057
+ }
2058
+ const newOptions = deepMergeOptions({
2059
+ event: typeof options.event.name === "string" ? [
2060
+ options.event.name
2061
+ ] : options.event.name
2062
+ }, options.options ?? {});
2063
+ registeredSource.options = deepMergeOptions(registeredSource.options, newOptions);
2064
+ __privateGet(this, _registeredSources)[options.key] = registeredSource;
2065
+ new Job(this, {
2066
+ id: options.key,
2067
+ name: options.key,
2068
+ version: options.source.version,
2069
+ trigger: new EventTrigger({
2070
+ event: registerSourceEvent,
2071
+ filter: {
2072
+ source: {
2073
+ key: [
2074
+ options.key
2075
+ ]
2076
+ }
2077
+ }
2078
+ }),
2079
+ integrations: {
2080
+ integration: options.source.integration
2081
+ },
2082
+ run: async (event, io, ctx) => {
2083
+ const updates = await options.source.register(options.params, event, io, ctx);
2084
+ if (!updates) {
2085
+ return;
2086
+ }
2087
+ return await io.updateSource("update-source", {
2088
+ key: options.key,
2089
+ ...updates
2090
+ });
2091
+ },
2092
+ __internal: true
2093
+ });
2094
+ }
2095
+ attachDynamicSchedule(key) {
2096
+ const jobs = __privateGet(this, _registeredSchedules)[key] ?? [];
2097
+ __privateGet(this, _registeredSchedules)[key] = jobs;
2098
+ }
2099
+ attachDynamicScheduleToJob(key, job) {
2100
+ const jobs = __privateGet(this, _registeredSchedules)[key] ?? [];
2101
+ jobs.push({
2102
+ id: job.id,
2103
+ version: job.version
2104
+ });
2105
+ __privateGet(this, _registeredSchedules)[key] = jobs;
2106
+ }
2107
+ async registerTrigger(id, key, options) {
2108
+ return __privateGet(this, _client2).registerTrigger(this.id, id, key, options);
2109
+ }
2110
+ async getAuth(id) {
2111
+ return __privateGet(this, _client2).getAuth(this.id, id);
2112
+ }
2113
+ async sendEvent(event, options) {
2114
+ return __privateGet(this, _client2).sendEvent(event, options);
2115
+ }
2116
+ async cancelEvent(eventId) {
2117
+ return __privateGet(this, _client2).cancelEvent(eventId);
2118
+ }
2119
+ async updateStatus(runId, id, status) {
2120
+ return __privateGet(this, _client2).updateStatus(runId, id, status);
2121
+ }
2122
+ async registerSchedule(id, key, schedule) {
2123
+ return __privateGet(this, _client2).registerSchedule(this.id, id, key, schedule);
2124
+ }
2125
+ async unregisterSchedule(id, key) {
2126
+ return __privateGet(this, _client2).unregisterSchedule(this.id, id, key);
2127
+ }
2128
+ async getEvent(eventId) {
2129
+ return __privateGet(this, _client2).getEvent(eventId);
2130
+ }
2131
+ async getRun(runId, options) {
2132
+ return __privateGet(this, _client2).getRun(runId, options);
2133
+ }
2134
+ async cancelRun(runId) {
2135
+ return __privateGet(this, _client2).cancelRun(runId);
2136
+ }
2137
+ async getRuns(jobSlug, options) {
2138
+ return __privateGet(this, _client2).getRuns(jobSlug, options);
2139
+ }
2140
+ async getRunStatuses(runId) {
2141
+ return __privateGet(this, _client2).getRunStatuses(runId);
2142
+ }
2143
+ authorized(apiKey) {
2144
+ if (typeof apiKey !== "string") {
2145
+ return "missing-header";
2146
+ }
2147
+ const localApiKey = __privateGet(this, _options4).apiKey ?? process.env.TRIGGER_API_KEY;
2148
+ if (!localApiKey) {
2149
+ return "missing-client";
2150
+ }
2151
+ return apiKey === localApiKey ? "authorized" : "unauthorized";
2152
+ }
2153
+ apiKey() {
2154
+ return __privateGet(this, _options4).apiKey ?? process.env.TRIGGER_API_KEY;
2155
+ }
2156
+ };
2157
+ __name(TriggerClient, "TriggerClient");
2158
+ _options4 = new WeakMap();
2159
+ _registeredJobs = new WeakMap();
2160
+ _registeredSources = new WeakMap();
2161
+ _registeredHttpSourceHandlers = new WeakMap();
2162
+ _registeredDynamicTriggers = new WeakMap();
2163
+ _jobMetadataByDynamicTriggers = new WeakMap();
2164
+ _registeredSchedules = new WeakMap();
2165
+ _authResolvers = new WeakMap();
2166
+ _client2 = new WeakMap();
2167
+ _internalLogger = new WeakMap();
2168
+ _preprocessRun = new WeakSet();
2169
+ preprocessRun_fn = /* @__PURE__ */ __name(async function(body, job) {
2170
+ const context = __privateMethod(this, _createPreprocessRunContext, createPreprocessRunContext_fn).call(this, body);
2171
+ const parsedPayload = job.trigger.event.parsePayload(body.event.payload ?? {});
2172
+ const properties = job.trigger.event.runProperties?.(parsedPayload) ?? [];
2173
+ return {
2174
+ abort: false,
2175
+ properties
2176
+ };
2177
+ }, "#preprocessRun");
2178
+ _executeJob = new WeakSet();
2179
+ executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1, timeOrigin, triggerVersion) {
2180
+ __privateGet(this, _internalLogger).debug("executing job", {
2181
+ execution: body1,
2182
+ job: job1.id,
2183
+ version: job1.version,
2184
+ triggerVersion
2185
+ });
2186
+ const context = __privateMethod(this, _createRunContext, createRunContext_fn).call(this, body1);
2187
+ const io = new IO({
2188
+ id: body1.run.id,
2189
+ cachedTasks: body1.tasks,
2190
+ cachedTasksCursor: body1.cachedTaskCursor,
2191
+ yieldedExecutions: body1.yieldedExecutions ?? [],
2192
+ noopTasksSet: body1.noopTasksSet,
2193
+ apiClient: __privateGet(this, _client2),
2194
+ logger: __privateGet(this, _internalLogger),
2195
+ client: this,
2196
+ context,
2197
+ jobLogLevel: job1.logLevel ?? __privateGet(this, _options4).logLevel ?? "info",
2198
+ jobLogger: __privateGet(this, _options4).ioLogLocalEnabled ? new import_core7.Logger(job1.id, job1.logLevel ?? __privateGet(this, _options4).logLevel ?? "info") : void 0,
2199
+ serverVersion: triggerVersion,
2200
+ timeOrigin,
2201
+ executionTimeout: body1.runChunkExecutionLimit
2202
+ });
2203
+ const resolvedConnections = await __privateMethod(this, _resolveConnections, resolveConnections_fn).call(this, context, job1.options.integrations, body1.connections);
2204
+ if (!resolvedConnections.ok) {
2205
+ return {
2206
+ status: "UNRESOLVED_AUTH_ERROR",
2207
+ issues: resolvedConnections.issues
2208
+ };
2209
+ }
2210
+ const ioWithConnections = createIOWithIntegrations(io, resolvedConnections.data, job1.options.integrations);
2211
+ try {
2212
+ const output = await runLocalStorage.runWith({
2213
+ io,
2214
+ ctx: context
2215
+ }, () => {
2216
+ return job1.options.run(job1.trigger.event.parsePayload(body1.event.payload ?? {}), ioWithConnections, context);
2217
+ });
2218
+ if (__privateGet(this, _options4).verbose) {
2219
+ __privateMethod(this, _logIOStats, logIOStats_fn).call(this, io.stats);
2220
+ }
2221
+ return {
2222
+ status: "SUCCESS",
2223
+ output
2224
+ };
2225
+ } catch (error) {
2226
+ if (__privateGet(this, _options4).verbose) {
2227
+ __privateMethod(this, _logIOStats, logIOStats_fn).call(this, io.stats);
2228
+ }
2229
+ if (error instanceof AutoYieldExecutionError) {
2230
+ return {
2231
+ status: "AUTO_YIELD_EXECUTION",
2232
+ location: error.location,
2233
+ timeRemaining: error.timeRemaining,
2234
+ timeElapsed: error.timeElapsed,
2235
+ limit: body1.runChunkExecutionLimit
2236
+ };
2237
+ }
2238
+ if (error instanceof AutoYieldWithCompletedTaskExecutionError) {
2239
+ return {
2240
+ status: "AUTO_YIELD_EXECUTION_WITH_COMPLETED_TASK",
2241
+ id: error.id,
2242
+ properties: error.properties,
2243
+ output: error.output,
2244
+ data: {
2245
+ ...error.data,
2246
+ limit: body1.runChunkExecutionLimit
2247
+ }
2248
+ };
2249
+ }
2250
+ if (error instanceof YieldExecutionError) {
2251
+ return {
2252
+ status: "YIELD_EXECUTION",
2253
+ key: error.key
2254
+ };
2255
+ }
2256
+ if (error instanceof ParsedPayloadSchemaError) {
2257
+ return {
2258
+ status: "INVALID_PAYLOAD",
2259
+ errors: error.schemaErrors
2260
+ };
2261
+ }
2262
+ if (error instanceof ResumeWithTaskError) {
2263
+ return {
2264
+ status: "RESUME_WITH_TASK",
2265
+ task: error.task
2266
+ };
2267
+ }
2268
+ if (error instanceof RetryWithTaskError) {
2269
+ return {
2270
+ status: "RETRY_WITH_TASK",
2271
+ task: error.task,
2272
+ error: error.cause,
2273
+ retryAt: error.retryAt
2274
+ };
2275
+ }
2276
+ if (error instanceof CanceledWithTaskError) {
2277
+ return {
2278
+ status: "CANCELED",
2279
+ task: error.task
2280
+ };
2281
+ }
2282
+ if (error instanceof RetryWithTaskError) {
2283
+ const errorWithStack2 = import_core7.ErrorWithStackSchema.safeParse(error.cause);
2284
+ if (errorWithStack2.success) {
2285
+ return {
2286
+ status: "ERROR",
2287
+ error: errorWithStack2.data,
2288
+ task: error.task
2289
+ };
2290
+ }
2291
+ return {
2292
+ status: "ERROR",
2293
+ error: {
2294
+ message: "Unknown error"
2295
+ },
2296
+ task: error.task
2297
+ };
2298
+ }
2299
+ const errorWithStack = import_core7.ErrorWithStackSchema.safeParse(error);
2300
+ if (errorWithStack.success) {
2301
+ return {
2302
+ status: "ERROR",
2303
+ error: errorWithStack.data
2304
+ };
2305
+ }
2306
+ return {
2307
+ status: "ERROR",
2308
+ error: {
2309
+ message: "Unknown error"
2310
+ }
2311
+ };
2312
+ }
2313
+ }, "#executeJob");
2314
+ _createRunContext = new WeakSet();
2315
+ createRunContext_fn = /* @__PURE__ */ __name(function(execution) {
2316
+ const { event, organization, environment, job, run, source } = execution;
2317
+ return {
2318
+ event: {
2319
+ id: event.id,
2320
+ name: event.name,
2321
+ context: event.context,
2322
+ timestamp: event.timestamp
2323
+ },
2324
+ organization,
2325
+ environment,
2326
+ job,
2327
+ run,
2328
+ account: execution.account,
2329
+ source
2330
+ };
2331
+ }, "#createRunContext");
2332
+ _createPreprocessRunContext = new WeakSet();
2333
+ createPreprocessRunContext_fn = /* @__PURE__ */ __name(function(body2) {
2334
+ const { event, organization, environment, job, run, account } = body2;
2335
+ return {
2336
+ event: {
2337
+ id: event.id,
2338
+ name: event.name,
2339
+ context: event.context,
2340
+ timestamp: event.timestamp
2341
+ },
2342
+ organization,
2343
+ environment,
2344
+ job,
2345
+ run,
2346
+ account
2347
+ };
2348
+ }, "#createPreprocessRunContext");
2349
+ _handleHttpSourceRequest = new WeakSet();
2350
+ handleHttpSourceRequest_fn = /* @__PURE__ */ __name(async function(source, sourceRequest) {
2351
+ __privateGet(this, _internalLogger).debug("Handling HTTP source request", {
2352
+ source
2353
+ });
2354
+ if (source.dynamicId) {
2355
+ const dynamicTrigger = __privateGet(this, _registeredDynamicTriggers)[source.dynamicId];
2356
+ if (!dynamicTrigger) {
2357
+ __privateGet(this, _internalLogger).debug("No dynamic trigger registered for HTTP source", {
2358
+ source
2359
+ });
2360
+ return {
2361
+ response: {
2362
+ status: 200,
2363
+ body: {
2364
+ ok: true
2365
+ }
2366
+ },
2367
+ events: []
2368
+ };
2369
+ }
2370
+ const results2 = await dynamicTrigger.source.handle(source, sourceRequest, __privateGet(this, _internalLogger));
2371
+ if (!results2) {
2372
+ return {
2373
+ events: [],
2374
+ response: {
2375
+ status: 200,
2376
+ body: {
2377
+ ok: true
2378
+ }
2379
+ }
2380
+ };
2381
+ }
2382
+ return {
2383
+ events: results2.events,
2384
+ response: results2.response ?? {
2385
+ status: 200,
2386
+ body: {
2387
+ ok: true
2388
+ }
2389
+ },
2390
+ metadata: results2.metadata
2391
+ };
2392
+ }
2393
+ const handler = __privateGet(this, _registeredHttpSourceHandlers)[source.key];
2394
+ if (!handler) {
2395
+ __privateGet(this, _internalLogger).debug("No handler registered for HTTP source", {
2396
+ source
2397
+ });
2398
+ return {
2399
+ response: {
2400
+ status: 200,
2401
+ body: {
2402
+ ok: true
2403
+ }
2404
+ },
2405
+ events: []
2406
+ };
2407
+ }
2408
+ const results = await handler(source, sourceRequest);
2409
+ if (!results) {
2410
+ return {
2411
+ events: [],
2412
+ response: {
2413
+ status: 200,
2414
+ body: {
2415
+ ok: true
2416
+ }
2417
+ }
2418
+ };
2419
+ }
2420
+ return {
2421
+ events: results.events,
2422
+ response: results.response ?? {
2423
+ status: 200,
2424
+ body: {
2425
+ ok: true
2426
+ }
2427
+ },
2428
+ metadata: results.metadata
2429
+ };
2430
+ }, "#handleHttpSourceRequest");
2431
+ _resolveConnections = new WeakSet();
2432
+ resolveConnections_fn = /* @__PURE__ */ __name(async function(ctx, integrations, connections) {
2433
+ if (!integrations) {
2434
+ return {
2435
+ ok: true,
2436
+ data: {}
2437
+ };
2438
+ }
2439
+ const resolvedAuthResults = await Promise.all(Object.keys(integrations).map(async (key) => {
2440
+ const integration = integrations[key];
2441
+ const auth = (connections ?? {})[key];
2442
+ const result = await __privateMethod(this, _resolveConnection, resolveConnection_fn).call(this, ctx, integration, auth);
2443
+ if (result.ok) {
2444
+ return {
2445
+ ok: true,
2446
+ auth: result.auth,
2447
+ key
2448
+ };
2449
+ } else {
2450
+ return {
2451
+ ok: false,
2452
+ error: result.error,
2453
+ key
2454
+ };
2455
+ }
2456
+ }));
2457
+ const allResolved = resolvedAuthResults.every((result) => result.ok);
2458
+ if (allResolved) {
2459
+ return {
2460
+ ok: true,
2461
+ data: resolvedAuthResults.reduce((acc, result) => {
2462
+ acc[result.key] = result.auth;
2463
+ return acc;
2464
+ }, {})
2465
+ };
2466
+ } else {
2467
+ return {
2468
+ ok: false,
2469
+ issues: resolvedAuthResults.reduce((acc, result) => {
2470
+ if (result.ok) {
2471
+ return acc;
2472
+ }
2473
+ const integration = integrations[result.key];
2474
+ acc[result.key] = {
2475
+ id: integration.id,
2476
+ error: result.error
2477
+ };
2478
+ return acc;
2479
+ }, {})
2480
+ };
2481
+ }
2482
+ }, "#resolveConnections");
2483
+ _resolveConnection = new WeakSet();
2484
+ resolveConnection_fn = /* @__PURE__ */ __name(async function(ctx1, integration, auth) {
2485
+ if (auth) {
2486
+ return {
2487
+ ok: true,
2488
+ auth
2489
+ };
2490
+ }
2491
+ const authResolver = __privateGet(this, _authResolvers)[integration.id];
2492
+ if (!authResolver) {
2493
+ if (integration.authSource === "HOSTED") {
2494
+ return {
2495
+ ok: false,
2496
+ error: `Something went wrong: Integration ${integration.id} is missing auth credentials from Trigger.dev`
2497
+ };
2498
+ }
2499
+ return {
2500
+ ok: true,
2501
+ auth: void 0
2502
+ };
2503
+ }
2504
+ try {
2505
+ const resolvedAuth = await authResolver(ctx1, integration);
2506
+ if (!resolvedAuth) {
2507
+ return {
2508
+ ok: false,
2509
+ error: `Auth could not be resolved for ${integration.id}: auth resolver returned null or undefined`
2510
+ };
2511
+ }
2512
+ return {
2513
+ ok: true,
2514
+ auth: resolvedAuth.type === "apiKey" ? {
2515
+ type: "apiKey",
2516
+ accessToken: resolvedAuth.token,
2517
+ additionalFields: resolvedAuth.additionalFields
2518
+ } : {
2519
+ type: "oauth2",
2520
+ accessToken: resolvedAuth.token,
2521
+ additionalFields: resolvedAuth.additionalFields
2522
+ }
2523
+ };
2524
+ } catch (resolverError) {
2525
+ if (resolverError instanceof Error) {
2526
+ return {
2527
+ ok: false,
2528
+ error: `Auth could not be resolved for ${integration.id}: auth resolver threw. ${resolverError.name}: ${resolverError.message}`
2529
+ };
2530
+ } else if (typeof resolverError === "string") {
2531
+ return {
2532
+ ok: false,
2533
+ error: `Auth could not be resolved for ${integration.id}: auth resolver threw an error: ${resolverError}`
2534
+ };
2535
+ }
2536
+ return {
2537
+ ok: false,
2538
+ error: `Auth could not be resolved for ${integration.id}: auth resolver threw an unknown error: ${JSON.stringify(resolverError)}`
2539
+ };
2540
+ }
2541
+ }, "#resolveConnection");
2542
+ _buildJobsIndex = new WeakSet();
2543
+ buildJobsIndex_fn = /* @__PURE__ */ __name(function() {
2544
+ return Object.values(__privateGet(this, _registeredJobs)).map((job) => __privateMethod(this, _buildJobIndex, buildJobIndex_fn).call(this, job));
2545
+ }, "#buildJobsIndex");
2546
+ _buildJobIndex = new WeakSet();
2547
+ buildJobIndex_fn = /* @__PURE__ */ __name(function(job2) {
2548
+ const internal = job2.options.__internal;
2549
+ return {
2550
+ id: job2.id,
2551
+ name: job2.name,
2552
+ version: job2.version,
2553
+ event: job2.trigger.event,
2554
+ trigger: job2.trigger.toJSON(),
2555
+ integrations: __privateMethod(this, _buildJobIntegrations, buildJobIntegrations_fn).call(this, job2),
2556
+ startPosition: "latest",
2557
+ enabled: job2.enabled,
2558
+ preprocessRuns: job2.trigger.preprocessRuns,
2559
+ internal
2560
+ };
2561
+ }, "#buildJobIndex");
2562
+ _buildJobIntegrations = new WeakSet();
2563
+ buildJobIntegrations_fn = /* @__PURE__ */ __name(function(job3) {
2564
+ return Object.keys(job3.options.integrations ?? {}).reduce((acc, key) => {
2565
+ const integration = job3.options.integrations[key];
2566
+ acc[key] = __privateMethod(this, _buildJobIntegration, buildJobIntegration_fn).call(this, integration);
2567
+ return acc;
2568
+ }, {});
2569
+ }, "#buildJobIntegrations");
2570
+ _buildJobIntegration = new WeakSet();
2571
+ buildJobIntegration_fn = /* @__PURE__ */ __name(function(integration1) {
2572
+ const authSource = __privateGet(this, _authResolvers)[integration1.id] ? "RESOLVER" : integration1.authSource;
2573
+ return {
2574
+ id: integration1.id,
2575
+ metadata: integration1.metadata,
2576
+ authSource
2577
+ };
2578
+ }, "#buildJobIntegration");
2579
+ _logIOStats = new WeakSet();
2580
+ logIOStats_fn = /* @__PURE__ */ __name(function(stats) {
2581
+ __privateGet(this, _internalLogger).debug("IO stats", {
2582
+ stats
2583
+ });
2584
+ }, "#logIOStats");
2585
+ _standardResponseHeaders = new WeakSet();
2586
+ standardResponseHeaders_fn = /* @__PURE__ */ __name(function(start) {
2587
+ return {
2588
+ "Trigger-Version": import_core7.API_VERSIONS.LAZY_LOADED_CACHED_TASKS,
2589
+ "X-Trigger-Request-Timing": `dur=${performance.now() - start / 1e3}`
2590
+ };
2591
+ }, "#standardResponseHeaders");
2592
+ function dynamicTriggerRegisterSourceJobId(id) {
2593
+ return `register-dynamic-trigger-${id}`;
2594
+ }
2595
+ __name(dynamicTriggerRegisterSourceJobId, "dynamicTriggerRegisterSourceJobId");
2596
+ function deepMergeOptions(obj1, obj2) {
2597
+ const mergedOptions = {
2598
+ ...obj1
2599
+ };
2600
+ for (const key in obj2) {
2601
+ if (obj2.hasOwnProperty(key)) {
2602
+ if (key in mergedOptions) {
2603
+ mergedOptions[key] = [
2604
+ ...mergedOptions[key],
2605
+ ...obj2[key]
2606
+ ];
2607
+ } else {
2608
+ mergedOptions[key] = obj2[key];
2609
+ }
2610
+ }
2611
+ }
2612
+ return mergedOptions;
2613
+ }
2614
+ __name(deepMergeOptions, "deepMergeOptions");
2615
+
2616
+ // src/triggers/externalSource.ts
2617
+ var import_core8 = require("@trigger.dev/core");
2618
+ var ExternalSource = class {
2619
+ constructor(channel, options) {
2620
+ this.options = options;
2621
+ this.channel = channel;
2622
+ }
2623
+ async handle(source, rawEvent, logger) {
2624
+ return this.options.handler({
2625
+ source: {
2626
+ ...source,
2627
+ params: source.params
2628
+ },
2629
+ rawEvent
2630
+ }, logger, this.options.integration);
2631
+ }
2632
+ filter(params, options) {
2633
+ return this.options.filter?.(params, options) ?? {};
2634
+ }
2635
+ properties(params) {
2636
+ return this.options.properties?.(params) ?? [];
2637
+ }
2638
+ async register(params, registerEvent, io, ctx) {
2639
+ const { result: event, ommited: source } = omit(registerEvent, "source");
2640
+ const { result: sourceWithoutChannel, ommited: channel } = omit(source, "channel");
2641
+ const { result: channelWithoutType } = omit(channel, "type");
2642
+ const updates = await this.options.register({
2643
+ ...event,
2644
+ source: {
2645
+ ...sourceWithoutChannel,
2646
+ ...channelWithoutType
2647
+ },
2648
+ params
2649
+ }, io, ctx);
2650
+ return updates;
2651
+ }
2652
+ key(params) {
2653
+ const parts = [
2654
+ this.options.id,
2655
+ this.channel
2656
+ ];
2657
+ parts.push(this.options.key(params));
2658
+ parts.push(this.integration.id);
2659
+ return parts.join("-");
2660
+ }
2661
+ get integration() {
2662
+ return this.options.integration;
2663
+ }
2664
+ get integrationConfig() {
2665
+ return {
2666
+ id: this.integration.id,
2667
+ metadata: this.integration.metadata
2668
+ };
2669
+ }
2670
+ get id() {
2671
+ return this.options.id;
2672
+ }
2673
+ get version() {
2674
+ return this.options.version;
2675
+ }
2676
+ };
2677
+ __name(ExternalSource, "ExternalSource");
2678
+ var ExternalSourceTrigger = class {
2679
+ constructor(options) {
2680
+ this.options = options;
2681
+ }
2682
+ get event() {
2683
+ return this.options.event;
2684
+ }
2685
+ toJSON() {
2686
+ return {
2687
+ type: "static",
2688
+ title: "External Source",
2689
+ rule: {
2690
+ event: this.event.name,
2691
+ payload: (0, import_core8.deepMergeFilters)(this.options.source.filter(this.options.params, this.options.options), this.event.filter ?? {}, this.options.params.filter ?? {}),
2692
+ source: this.event.source
2693
+ },
2694
+ properties: this.options.source.properties(this.options.params)
2695
+ };
2696
+ }
2697
+ attachToJob(triggerClient, job) {
2698
+ triggerClient.attachSource({
2699
+ key: slugifyId(this.options.source.key(this.options.params)),
2700
+ source: this.options.source,
2701
+ event: this.options.event,
2702
+ params: this.options.params,
2703
+ options: this.options.options
2704
+ });
2705
+ }
2706
+ get preprocessRuns() {
2707
+ return true;
2708
+ }
2709
+ };
2710
+ __name(ExternalSourceTrigger, "ExternalSourceTrigger");
2711
+ function omit(obj, key) {
2712
+ const result = {};
2713
+ for (const k of Object.keys(obj)) {
2714
+ if (k === key)
2715
+ continue;
2716
+ result[k] = obj[k];
2717
+ }
2718
+ return {
2719
+ result,
2720
+ ommited: obj[key]
2721
+ };
2722
+ }
2723
+ __name(omit, "omit");
2724
+
2725
+ // src/triggers/notifications.ts
2726
+ var import_core9 = require("@trigger.dev/core");
2727
+ function missingConnectionNotification(integrations) {
2728
+ return new MissingConnectionNotification({
2729
+ integrations
2730
+ });
2731
+ }
2732
+ __name(missingConnectionNotification, "missingConnectionNotification");
2733
+ function missingConnectionResolvedNotification(integrations) {
2734
+ return new MissingConnectionResolvedNotification({
2735
+ integrations
2736
+ });
2737
+ }
2738
+ __name(missingConnectionResolvedNotification, "missingConnectionResolvedNotification");
2739
+ var MissingConnectionNotification = class {
2740
+ constructor(options) {
2741
+ this.options = options;
2742
+ }
2743
+ get event() {
2744
+ return {
2745
+ name: import_core9.MISSING_CONNECTION_NOTIFICATION,
2746
+ title: "Missing Connection Notification",
2747
+ source: "trigger.dev",
2748
+ icon: "connection-alert",
2749
+ parsePayload: import_core9.MissingConnectionNotificationPayloadSchema.parse,
2750
+ properties: [
2751
+ {
2752
+ label: "Integrations",
2753
+ text: this.options.integrations.map((i) => i.id).join(", ")
2754
+ }
2755
+ ]
2756
+ };
2757
+ }
2758
+ attachToJob(triggerClient, job) {
2759
+ }
2760
+ get preprocessRuns() {
2761
+ return false;
2762
+ }
2763
+ toJSON() {
2764
+ return {
2765
+ type: "static",
2766
+ title: this.event.title,
2767
+ rule: {
2768
+ event: this.event.name,
2769
+ source: "trigger.dev",
2770
+ payload: {
2771
+ client: {
2772
+ id: this.options.integrations.map((i) => i.id)
2773
+ }
2774
+ }
2775
+ }
2776
+ };
2777
+ }
2778
+ };
2779
+ __name(MissingConnectionNotification, "MissingConnectionNotification");
2780
+ var MissingConnectionResolvedNotification = class {
2781
+ constructor(options) {
2782
+ this.options = options;
2783
+ }
2784
+ get event() {
2785
+ return {
2786
+ name: import_core9.MISSING_CONNECTION_RESOLVED_NOTIFICATION,
2787
+ title: "Missing Connection Resolved Notification",
2788
+ source: "trigger.dev",
2789
+ icon: "connection-alert",
2790
+ parsePayload: import_core9.MissingConnectionResolvedNotificationPayloadSchema.parse,
2791
+ properties: [
2792
+ {
2793
+ label: "Integrations",
2794
+ text: this.options.integrations.map((i) => i.id).join(", ")
2795
+ }
2796
+ ]
2797
+ };
2798
+ }
2799
+ attachToJob(triggerClient, job) {
2800
+ }
2801
+ get preprocessRuns() {
2802
+ return false;
2803
+ }
2804
+ toJSON() {
2805
+ return {
2806
+ type: "static",
2807
+ title: this.event.title,
2808
+ rule: {
2809
+ event: this.event.name,
2810
+ source: "trigger.dev",
2811
+ payload: {
2812
+ client: {
2813
+ id: this.options.integrations.map((i) => i.id)
2814
+ }
2815
+ }
2816
+ }
2817
+ };
2818
+ }
2819
+ };
2820
+ __name(MissingConnectionResolvedNotification, "MissingConnectionResolvedNotification");
2821
+
2822
+ // src/index.ts
2823
+ function redactString(strings, ...interpolations) {
2824
+ return {
2825
+ __redactedString: true,
2826
+ strings: strings.raw,
2827
+ interpolations
2828
+ };
2829
+ }
2830
+ __name(redactString, "redactString");
2831
+ // Annotate the CommonJS export names for ESM import in node:
2832
+ 0 && (module.exports = {
2833
+ CronTrigger,
2834
+ DynamicSchedule,
2835
+ DynamicTrigger,
2836
+ EventTrigger,
2837
+ ExternalSource,
2838
+ ExternalSourceTrigger,
2839
+ IO,
2840
+ IOLogger,
2841
+ IntervalTrigger,
2842
+ Job,
2843
+ MissingConnectionNotification,
2844
+ MissingConnectionResolvedNotification,
2845
+ TriggerClient,
2846
+ cronTrigger,
2847
+ eventTrigger,
2848
+ intervalTrigger,
2849
+ isTriggerError,
2850
+ missingConnectionNotification,
2851
+ missingConnectionResolvedNotification,
2852
+ omit,
2853
+ redactString,
2854
+ retry
2855
+ });
2856
+ //# sourceMappingURL=index.js.map