@trigger.dev/sdk 3.0.0-beta.7 → 3.0.0

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