@trigger.dev/sdk 3.0.0-beta.5 → 3.0.0-beta.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/v3/index.mjs CHANGED
@@ -1,529 +1,157 @@
1
- import { SpanKind, trace, context, SpanStatusCode } from '@opentelemetry/api';
1
+ import { TriggerTracer, SemanticInternalAttributes, apiClientManager, isRequestOptions, mergeRequestOptions, accessoryAttributes, flattenAttributes, taskContext, runtime, usage as usage$1, taskCatalog, TimezonesResult, defaultRetryOptions, calculateNextRetryDelay, defaultFetchRetryOptions, calculateResetAt, eventFilterMatches, stringifyIO, logger, conditionallyImportPacket, parsePacket, createErrorTaskError } from '@trigger.dev/core/v3';
2
+ export { AbortTaskRunError, ApiError, AuthenticationError, BadRequestError, ConflictError, InternalServerError, NotFoundError, PermissionDeniedError, RateLimitError, UnprocessableEntityError, logger } from '@trigger.dev/core/v3';
3
+ import { trace, context, SpanStatusCode, SpanKind } from '@opentelemetry/api';
2
4
  import { SEMATTRS_HTTP_STATUS_CODE, SEMATTRS_HTTP_METHOD, SEMATTRS_HTTP_URL, SEMATTRS_HTTP_HOST, SEMATTRS_HTTP_SCHEME, SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH, SEMATTRS_MESSAGING_OPERATION, SEMATTRS_MESSAGING_DESTINATION, SEMATTRS_MESSAGING_SYSTEM } from '@opentelemetry/semantic-conventions';
3
- import { TriggerTracer, runtime, SemanticInternalAttributes, accessoryAttributes, defaultRetryOptions, conditionallyImportPacket, parsePacket, createErrorTaskError, apiClientManager, calculateNextRetryDelay, defaultFetchRetryOptions, calculateResetAt, eventFilterMatches, flattenAttributes, taskContextManager } from '@trigger.dev/core/v3';
4
- export { logger } from '@trigger.dev/core/v3';
5
5
  import { AsyncLocalStorage } from 'node:async_hooks';
6
+ import { zodfetch } from '@trigger.dev/core/v3/zodfetch';
6
7
 
7
8
  var __defProp = Object.defineProperty;
8
9
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
10
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
11
+ var __export = (target, all) => {
12
+ for (var name2 in all)
13
+ __defProp(target, name2, { get: all[name2], enumerable: true });
14
+ };
10
15
  var __publicField = (obj, key, value) => {
11
16
  __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
12
17
  return value;
13
18
  };
14
19
 
15
20
  // package.json
16
- var version = "3.0.0-beta.5";
21
+ var version = "3.0.0-beta.50";
22
+
23
+ // src/v3/tracer.ts
17
24
  var tracer = new TriggerTracer({
18
25
  name: "@trigger.dev/sdk",
19
26
  version
20
27
  });
21
28
 
22
- // src/v3/shared.ts
23
- function createTask(params) {
24
- const task2 = {
25
- trigger: async ({ payload, options }) => {
26
- const apiClient = apiClientManager.client;
27
- if (!apiClient) {
28
- throw apiClientMissingError();
29
+ // src/v3/cache.ts
30
+ var _InMemoryCache = class _InMemoryCache {
31
+ constructor() {
32
+ __publicField(this, "_cache", /* @__PURE__ */ new Map());
33
+ }
34
+ get(key) {
35
+ return this._cache.get(key);
36
+ }
37
+ set(key, value) {
38
+ this._cache.set(key, value);
39
+ return void 0;
40
+ }
41
+ delete(key) {
42
+ this._cache.delete(key);
43
+ return void 0;
44
+ }
45
+ };
46
+ __name(_InMemoryCache, "InMemoryCache");
47
+ var InMemoryCache = _InMemoryCache;
48
+ function createCache(store) {
49
+ return /* @__PURE__ */ __name(function cache(cacheKey, fn) {
50
+ return tracer.startActiveSpan("cache", async (span) => {
51
+ span.setAttribute("cache.key", cacheKey);
52
+ span.setAttribute(SemanticInternalAttributes.STYLE_ICON, "device-sd-card");
53
+ const cacheEntry = await store.get(cacheKey);
54
+ if (cacheEntry) {
55
+ span.updateName(`cache.hit ${cacheKey}`);
56
+ return cacheEntry.value;
29
57
  }
30
- const taskMetadata = runtime.getTaskMetadata(params.id);
31
- const handle = await tracer.startActiveSpan(taskMetadata ? "Trigger" : `${params.id} trigger()`, async (span) => {
32
- const response = await apiClient.triggerTask(params.id, {
33
- payload,
34
- options: {
35
- queue: params.queue,
36
- concurrencyKey: options?.concurrencyKey,
37
- test: taskContextManager.ctx?.run.isTest
38
- }
39
- }, {
40
- spanParentAsLink: true
41
- });
42
- if (!response.ok) {
43
- throw new Error(response.error);
44
- }
45
- span.setAttribute("messaging.message.id", response.data.id);
46
- return response.data;
58
+ span.updateName(`cache.miss ${cacheKey}`);
59
+ const value = await tracer.startActiveSpan("cache.getFreshValue", async (span2) => {
60
+ return await fn();
47
61
  }, {
48
- kind: SpanKind.PRODUCER,
49
62
  attributes: {
50
- [SEMATTRS_MESSAGING_OPERATION]: "publish",
51
- [SemanticInternalAttributes.STYLE_ICON]: "trigger",
52
- ["messaging.client_id"]: taskContextManager.worker?.id,
53
- [SEMATTRS_MESSAGING_DESTINATION]: params.queue?.name ?? params.id,
54
- ["messaging.message.body.size"]: JSON.stringify(payload).length,
55
- [SEMATTRS_MESSAGING_SYSTEM]: "trigger.dev",
56
- ...taskMetadata ? accessoryAttributes({
57
- items: [
58
- {
59
- text: `${taskMetadata.exportName}.trigger()`,
60
- variant: "normal"
61
- }
62
- ],
63
- style: "codepath"
64
- }) : {}
63
+ "cache.key": cacheKey,
64
+ [SemanticInternalAttributes.STYLE_ICON]: "device-sd-card"
65
65
  }
66
66
  });
67
- return handle;
68
- },
69
- batchTrigger: async ({ items }) => {
70
- const apiClient = apiClientManager.client;
71
- if (!apiClient) {
72
- throw apiClientMissingError();
73
- }
74
- const taskMetadata = runtime.getTaskMetadata(params.id);
75
- const response = await tracer.startActiveSpan(taskMetadata ? "Batch trigger" : `${params.id} batchTrigger()`, async (span) => {
76
- const response2 = await apiClient.batchTriggerTask(params.id, {
77
- items: items.map((item) => ({
78
- payload: item.payload,
79
- options: {
80
- queue: item.options?.queue ?? params.queue,
81
- concurrencyKey: item.options?.concurrencyKey,
82
- test: taskContextManager.ctx?.run.isTest
83
- }
84
- }))
85
- }, {
86
- spanParentAsLink: true
67
+ await tracer.startActiveSpan("cache.set", async (span2) => {
68
+ await store.set(cacheKey, {
69
+ value,
70
+ metadata: {
71
+ createdTime: Date.now()
72
+ }
87
73
  });
88
- if (!response2.ok) {
89
- throw new Error(response2.error);
90
- }
91
- span.setAttribute("messaging.message.id", response2.data.batchId);
92
- return response2.data;
93
74
  }, {
94
- kind: SpanKind.PRODUCER,
95
75
  attributes: {
96
- [SEMATTRS_MESSAGING_OPERATION]: "publish",
97
- ["messaging.batch.message_count"]: items.length,
98
- ["messaging.client_id"]: taskContextManager.worker?.id,
99
- [SEMATTRS_MESSAGING_DESTINATION]: params.queue?.name ?? params.id,
100
- ["messaging.message.body.size"]: items.map((item) => JSON.stringify(item.payload)).join("").length,
101
- [SEMATTRS_MESSAGING_SYSTEM]: "trigger.dev",
102
- [SemanticInternalAttributes.STYLE_ICON]: "trigger",
103
- ...taskMetadata ? accessoryAttributes({
104
- items: [
105
- {
106
- text: `${taskMetadata.exportName}.batchTrigger()`,
107
- variant: "normal"
108
- }
109
- ],
110
- style: "codepath"
111
- }) : {}
76
+ "cache.key": cacheKey,
77
+ [SemanticInternalAttributes.STYLE_ICON]: "device-sd-card"
112
78
  }
113
79
  });
114
- return response;
115
- },
116
- triggerAndWait: async ({ payload, options }) => {
117
- const ctx = taskContextManager.ctx;
118
- if (!ctx) {
119
- throw new Error("triggerAndWait can only be used from inside a task.run()");
120
- }
121
- const apiClient = apiClientManager.client;
122
- if (!apiClient) {
123
- throw apiClientMissingError();
124
- }
125
- const taskMetadata = runtime.getTaskMetadata(params.id);
126
- return await tracer.startActiveSpan(taskMetadata ? "Trigger" : `${params.id} triggerAndWait()`, async (span) => {
127
- const response = await apiClient.triggerTask(params.id, {
128
- payload,
129
- options: {
130
- dependentAttempt: ctx.attempt.id,
131
- lockToVersion: taskContextManager.worker?.version,
132
- queue: params.queue,
133
- concurrencyKey: options?.concurrencyKey,
134
- test: taskContextManager.ctx?.run.isTest
135
- }
136
- });
137
- if (!response.ok) {
138
- throw new Error(response.error);
139
- }
140
- span.setAttribute("messaging.message.id", response.data.id);
141
- const result = await runtime.waitForTask({
142
- id: response.data.id,
143
- ctx
144
- });
145
- const runResult = await handleTaskRunExecutionResult(result);
146
- if (!runResult.ok) {
147
- throw runResult.error;
148
- }
149
- return runResult.output;
150
- }, {
151
- kind: SpanKind.PRODUCER,
80
+ return value;
81
+ });
82
+ }, "cache");
83
+ }
84
+ __name(createCache, "createCache");
85
+ function onThrow(fn, options) {
86
+ const opts = {
87
+ ...defaultRetryOptions,
88
+ ...options
89
+ };
90
+ return tracer.startActiveSpan(`retry.onThrow()`, async (span) => {
91
+ let attempt = 1;
92
+ while (attempt <= opts.maxAttempts) {
93
+ const innerSpan = tracer.startSpan("retry.fn()", {
152
94
  attributes: {
153
- [SemanticInternalAttributes.STYLE_ICON]: "trigger",
154
- [SEMATTRS_MESSAGING_OPERATION]: "publish",
155
- ["messaging.client_id"]: taskContextManager.worker?.id,
156
- [SEMATTRS_MESSAGING_DESTINATION]: params.queue?.name ?? params.id,
157
- [SEMATTRS_MESSAGING_SYSTEM]: "trigger.dev",
158
- ...taskMetadata ? accessoryAttributes({
95
+ [SemanticInternalAttributes.STYLE_ICON]: "function",
96
+ ...accessoryAttributes({
159
97
  items: [
160
98
  {
161
- text: `${taskMetadata.exportName}.triggerAndWait()`,
99
+ text: `${attempt}/${opts.maxAttempts}`,
162
100
  variant: "normal"
163
101
  }
164
102
  ],
165
103
  style: "codepath"
166
- }) : {}
104
+ })
167
105
  }
168
106
  });
169
- },
170
- batchTriggerAndWait: async ({ items }) => {
171
- const ctx = taskContextManager.ctx;
172
- if (!ctx) {
173
- throw new Error("batchTriggerAndWait can only be used from inside a task.run()");
174
- }
175
- const apiClient = apiClientManager.client;
176
- if (!apiClient) {
177
- throw apiClientMissingError();
178
- }
179
- const taskMetadata = runtime.getTaskMetadata(params.id);
180
- return await tracer.startActiveSpan(taskMetadata ? "Batch trigger" : `${params.id} batchTriggerAndWait()`, async (span) => {
181
- const response = await apiClient.batchTriggerTask(params.id, {
182
- items: items.map((item) => ({
183
- payload: item.payload,
184
- options: {
185
- lockToVersion: taskContextManager.worker?.version,
186
- queue: item.options?.queue ?? params.queue,
187
- concurrencyKey: item.options?.concurrencyKey,
188
- test: taskContextManager.ctx?.run.isTest
189
- }
190
- })),
191
- dependentAttempt: ctx.attempt.id
107
+ const contextWithSpanSet = trace.setSpan(context.active(), innerSpan);
108
+ try {
109
+ const result = await context.with(contextWithSpanSet, async () => {
110
+ return fn({
111
+ attempt,
112
+ maxAttempts: opts.maxAttempts
113
+ });
192
114
  });
193
- if (!response.ok) {
194
- throw new Error(response.error);
115
+ innerSpan.end();
116
+ return result;
117
+ } catch (e) {
118
+ if (e instanceof Error || typeof e === "string") {
119
+ innerSpan.recordException(e);
120
+ } else {
121
+ innerSpan.recordException(String(e));
195
122
  }
196
- span.setAttribute("messaging.message.id", response.data.batchId);
197
- const result = await runtime.waitForBatch({
198
- id: response.data.batchId,
199
- runs: response.data.runs,
200
- ctx
123
+ innerSpan.setStatus({
124
+ code: SpanStatusCode.ERROR
201
125
  });
202
- const runs = await handleBatchTaskRunExecutionResult(result.items);
203
- return {
204
- id: result.id,
205
- runs
206
- };
207
- }, {
208
- kind: SpanKind.PRODUCER,
209
- attributes: {
210
- [SEMATTRS_MESSAGING_OPERATION]: "publish",
211
- ["messaging.batch.message_count"]: items.length,
212
- ["messaging.client_id"]: taskContextManager.worker?.id,
213
- [SEMATTRS_MESSAGING_DESTINATION]: params.queue?.name ?? params.id,
214
- ["messaging.message.body.size"]: items.map((item) => JSON.stringify(item.payload)).join("").length,
215
- [SEMATTRS_MESSAGING_SYSTEM]: "trigger.dev",
216
- [SemanticInternalAttributes.STYLE_ICON]: "trigger",
217
- ...taskMetadata ? accessoryAttributes({
218
- items: [
219
- {
220
- text: `${taskMetadata.exportName}.batchTriggerAndWait()`,
221
- variant: "normal"
222
- }
223
- ],
224
- style: "codepath"
225
- }) : {}
126
+ if (e instanceof Error && e.name === "AbortTaskRunError") {
127
+ innerSpan.end();
128
+ throw e;
226
129
  }
227
- });
228
- }
229
- };
230
- Object.defineProperty(task2, "__trigger", {
231
- value: {
232
- id: params.id,
233
- packageVersion: version,
234
- queue: params.queue,
235
- retry: params.retry ? {
236
- ...defaultRetryOptions,
237
- ...params.retry
238
- } : void 0,
239
- machine: params.machine,
240
- fns: {
241
- run: params.run,
242
- init: params.init,
243
- cleanup: params.cleanup,
244
- middleware: params.middleware,
245
- handleError: params.handleError
130
+ const nextRetryDelay = calculateNextRetryDelay(opts, attempt);
131
+ if (!nextRetryDelay) {
132
+ innerSpan.end();
133
+ throw e;
134
+ }
135
+ innerSpan.setAttribute(SemanticInternalAttributes.RETRY_AT, new Date(Date.now() + nextRetryDelay).toISOString());
136
+ innerSpan.setAttribute(SemanticInternalAttributes.RETRY_COUNT, attempt);
137
+ innerSpan.setAttribute(SemanticInternalAttributes.RETRY_DELAY, `${nextRetryDelay}ms`);
138
+ innerSpan.end();
139
+ await runtime.waitForDuration(nextRetryDelay);
140
+ } finally {
141
+ attempt++;
246
142
  }
247
- },
248
- enumerable: false
249
- });
250
- return task2;
251
- }
252
- __name(createTask, "createTask");
253
- async function handleBatchTaskRunExecutionResult(items) {
254
- const someObjectStoreOutputs = items.some((item) => item.ok && item.outputType === "application/store");
255
- if (!someObjectStoreOutputs) {
256
- const results = await Promise.all(items.map(async (item) => {
257
- return await handleTaskRunExecutionResult(item);
258
- }));
259
- return results;
260
- }
261
- return await tracer.startActiveSpan("store.downloadPayloads", async (span) => {
262
- const results = await Promise.all(items.map(async (item) => {
263
- return await handleTaskRunExecutionResult(item);
264
- }));
265
- return results;
143
+ }
144
+ throw new Error("Max attempts reached");
266
145
  }, {
267
- kind: SpanKind.INTERNAL,
268
- [SemanticInternalAttributes.STYLE_ICON]: "cloud-download"
146
+ attributes: {
147
+ [SemanticInternalAttributes.STYLE_ICON]: "arrow-capsule"
148
+ }
269
149
  });
270
150
  }
271
- __name(handleBatchTaskRunExecutionResult, "handleBatchTaskRunExecutionResult");
272
- async function handleTaskRunExecutionResult(execution) {
273
- if (execution.ok) {
274
- const outputPacket = {
275
- data: execution.output,
276
- dataType: execution.outputType
277
- };
278
- const importedPacket = await conditionallyImportPacket(outputPacket, tracer);
279
- return {
280
- ok: true,
281
- id: execution.id,
282
- output: await parsePacket(importedPacket)
283
- };
284
- } else {
285
- return {
286
- ok: false,
287
- id: execution.id,
288
- error: createErrorTaskError(execution.error)
289
- };
290
- }
291
- }
292
- __name(handleTaskRunExecutionResult, "handleTaskRunExecutionResult");
293
- function apiClientMissingError() {
294
- const hasBaseUrl = !!apiClientManager.baseURL;
295
- const hasAccessToken = !!apiClientManager.accessToken;
296
- if (!hasBaseUrl && !hasAccessToken) {
297
- return `You need to set the TRIGGER_API_URL and TRIGGER_SECRET_KEY environment variables.`;
298
- } else if (!hasBaseUrl) {
299
- return `You need to set the TRIGGER_API_URL environment variable.`;
300
- } else if (!hasAccessToken) {
301
- return `You need to set the TRIGGER_SECRET_KEY environment variable.`;
302
- }
303
- return `Unknown error`;
304
- }
305
- __name(apiClientMissingError, "apiClientMissingError");
306
-
307
- // src/v3/tasks.ts
308
- function task(options) {
309
- return createTask(options);
310
- }
311
- __name(task, "task");
312
- var wait = {
313
- for: async (options) => {
314
- return tracer.startActiveSpan(`wait.for()`, async (span) => {
315
- const durationInMs = calculateDurationInMs(options);
316
- await runtime.waitForDuration(durationInMs);
317
- }, {
318
- attributes: {
319
- [SemanticInternalAttributes.STYLE_ICON]: "wait",
320
- ...accessoryAttributes({
321
- items: [
322
- {
323
- text: nameForWaitOptions(options),
324
- variant: "normal"
325
- }
326
- ],
327
- style: "codepath"
328
- })
329
- }
330
- });
331
- },
332
- until: async (options) => {
333
- return tracer.startActiveSpan(`wait.until()`, async (span) => {
334
- const start = Date.now();
335
- if (options.throwIfInThePast && options.date < /* @__PURE__ */ new Date()) {
336
- throw new Error("Date is in the past");
337
- }
338
- const durationInMs = options.date.getTime() - start;
339
- await runtime.waitForDuration(durationInMs);
340
- }, {
341
- attributes: {
342
- [SemanticInternalAttributes.STYLE_ICON]: "wait",
343
- ...accessoryAttributes({
344
- items: [
345
- {
346
- text: options.date.toISOString(),
347
- variant: "normal"
348
- }
349
- ],
350
- style: "codepath"
351
- })
352
- }
353
- });
354
- }
355
- };
356
- function nameForWaitOptions(options) {
357
- if ("seconds" in options) {
358
- return options.seconds === 1 ? `1 second` : `${options.seconds} seconds`;
359
- }
360
- if ("minutes" in options) {
361
- return options.minutes === 1 ? `1 minute` : `${options.minutes} minutes`;
362
- }
363
- if ("hours" in options) {
364
- return options.hours === 1 ? `1 hour` : `${options.hours} hours`;
365
- }
366
- if ("days" in options) {
367
- return options.days === 1 ? `1 day` : `${options.days} days`;
368
- }
369
- if ("weeks" in options) {
370
- return options.weeks === 1 ? `1 week` : `${options.weeks} weeks`;
371
- }
372
- if ("months" in options) {
373
- return options.months === 1 ? `1 month` : `${options.months} months`;
374
- }
375
- if ("years" in options) {
376
- return options.years === 1 ? `1 year` : `${options.years} years`;
377
- }
378
- return "NaN";
379
- }
380
- __name(nameForWaitOptions, "nameForWaitOptions");
381
- function calculateDurationInMs(options) {
382
- if ("seconds" in options) {
383
- return options.seconds * 1e3;
384
- }
385
- if ("minutes" in options) {
386
- return options.minutes * 1e3 * 60;
387
- }
388
- if ("hours" in options) {
389
- return options.hours * 1e3 * 60 * 60;
390
- }
391
- if ("days" in options) {
392
- return options.days * 1e3 * 60 * 60 * 24;
393
- }
394
- if ("weeks" in options) {
395
- return options.weeks * 1e3 * 60 * 60 * 24 * 7;
396
- }
397
- if ("months" in options) {
398
- return options.months * 1e3 * 60 * 60 * 24 * 30;
399
- }
400
- if ("years" in options) {
401
- return options.years * 1e3 * 60 * 60 * 24 * 365;
402
- }
403
- throw new Error("Invalid options");
404
- }
405
- __name(calculateDurationInMs, "calculateDurationInMs");
406
- var _InMemoryCache = class _InMemoryCache {
407
- constructor() {
408
- __publicField(this, "_cache", /* @__PURE__ */ new Map());
409
- }
410
- get(key) {
411
- return this._cache.get(key);
412
- }
413
- set(key, value) {
414
- this._cache.set(key, value);
415
- return void 0;
416
- }
417
- delete(key) {
418
- this._cache.delete(key);
419
- return void 0;
420
- }
421
- };
422
- __name(_InMemoryCache, "InMemoryCache");
423
- var InMemoryCache = _InMemoryCache;
424
- function createCache(store) {
425
- return /* @__PURE__ */ __name(function cache(cacheKey, fn) {
426
- return tracer.startActiveSpan("cache", async (span) => {
427
- span.setAttribute("cache.key", cacheKey);
428
- span.setAttribute(SemanticInternalAttributes.STYLE_ICON, "device-sd-card");
429
- const cacheEntry = await store.get(cacheKey);
430
- if (cacheEntry) {
431
- span.updateName(`cache.hit ${cacheKey}`);
432
- return cacheEntry.value;
433
- }
434
- span.updateName(`cache.miss ${cacheKey}`);
435
- const value = await tracer.startActiveSpan("cache.getFreshValue", async (span2) => {
436
- return await fn();
437
- }, {
438
- attributes: {
439
- "cache.key": cacheKey,
440
- [SemanticInternalAttributes.STYLE_ICON]: "device-sd-card"
441
- }
442
- });
443
- await tracer.startActiveSpan("cache.set", async (span2) => {
444
- await store.set(cacheKey, {
445
- value,
446
- metadata: {
447
- createdTime: Date.now()
448
- }
449
- });
450
- }, {
451
- attributes: {
452
- "cache.key": cacheKey,
453
- [SemanticInternalAttributes.STYLE_ICON]: "device-sd-card"
454
- }
455
- });
456
- return value;
457
- });
458
- }, "cache");
459
- }
460
- __name(createCache, "createCache");
461
- function onThrow(fn, options) {
462
- const opts = {
463
- ...defaultRetryOptions,
464
- ...options
465
- };
466
- return tracer.startActiveSpan(`retry.onThrow()`, async (span) => {
467
- let attempt = 1;
468
- while (attempt <= opts.maxAttempts) {
469
- const innerSpan = tracer.startSpan("retry.fn()", {
470
- attributes: {
471
- [SemanticInternalAttributes.STYLE_ICON]: "function",
472
- ...accessoryAttributes({
473
- items: [
474
- {
475
- text: `${attempt}/${opts.maxAttempts}`,
476
- variant: "normal"
477
- }
478
- ],
479
- style: "codepath"
480
- })
481
- }
482
- });
483
- const contextWithSpanSet = trace.setSpan(context.active(), innerSpan);
484
- try {
485
- const result = await context.with(contextWithSpanSet, async () => {
486
- return fn({
487
- attempt,
488
- maxAttempts: opts.maxAttempts
489
- });
490
- });
491
- innerSpan.end();
492
- return result;
493
- } catch (e) {
494
- if (e instanceof Error || typeof e === "string") {
495
- innerSpan.recordException(e);
496
- } else {
497
- innerSpan.recordException(String(e));
498
- }
499
- innerSpan.setStatus({
500
- code: SpanStatusCode.ERROR
501
- });
502
- const nextRetryDelay = calculateNextRetryDelay(opts, attempt);
503
- if (!nextRetryDelay) {
504
- innerSpan.end();
505
- throw e;
506
- }
507
- innerSpan.setAttribute(SemanticInternalAttributes.RETRY_AT, new Date(Date.now() + nextRetryDelay).toISOString());
508
- innerSpan.setAttribute(SemanticInternalAttributes.RETRY_COUNT, attempt);
509
- innerSpan.setAttribute(SemanticInternalAttributes.RETRY_DELAY, `${nextRetryDelay}ms`);
510
- innerSpan.end();
511
- await runtime.waitForDuration(nextRetryDelay);
512
- } finally {
513
- attempt++;
514
- }
515
- }
516
- throw new Error("Max attempts reached");
517
- }, {
518
- attributes: {
519
- [SemanticInternalAttributes.STYLE_ICON]: "arrow-capsule"
520
- }
521
- });
522
- }
523
- __name(onThrow, "onThrow");
524
- var normalizeUrlFromInput = /* @__PURE__ */ __name((input) => {
525
- if (typeof input === "string") {
526
- return new URL(input);
151
+ __name(onThrow, "onThrow");
152
+ var normalizeUrlFromInput = /* @__PURE__ */ __name((input) => {
153
+ if (typeof input === "string") {
154
+ return new URL(input);
527
155
  }
528
156
  if (input instanceof URL) {
529
157
  return input;
@@ -877,7 +505,1415 @@ var retry = {
877
505
  fetch: retryFetch,
878
506
  interceptFetch
879
507
  };
508
+ var runs = {
509
+ replay: replayRun,
510
+ cancel: cancelRun,
511
+ retrieve: retrieveRun,
512
+ list: listRuns,
513
+ reschedule: rescheduleRun,
514
+ poll
515
+ };
516
+ function listRuns(paramsOrProjectRef, paramsOrOptions, requestOptions) {
517
+ const apiClient = apiClientManager.client;
518
+ if (!apiClient) {
519
+ throw apiClientMissingError();
520
+ }
521
+ const $requestOptions = listRunsRequestOptions(paramsOrProjectRef, paramsOrOptions, requestOptions);
522
+ if (typeof paramsOrProjectRef === "string") {
523
+ if (isRequestOptions(paramsOrOptions)) {
524
+ return apiClient.listProjectRuns(paramsOrProjectRef, {}, $requestOptions);
525
+ } else {
526
+ return apiClient.listProjectRuns(paramsOrProjectRef, paramsOrOptions, $requestOptions);
527
+ }
528
+ }
529
+ return apiClient.listRuns(paramsOrProjectRef, $requestOptions);
530
+ }
531
+ __name(listRuns, "listRuns");
532
+ function listRunsRequestOptions(paramsOrProjectRef, paramsOrOptions, requestOptions) {
533
+ if (typeof paramsOrProjectRef === "string") {
534
+ if (isRequestOptions(paramsOrOptions)) {
535
+ return mergeRequestOptions({
536
+ tracer,
537
+ name: "runs.list()",
538
+ icon: "runs",
539
+ attributes: {
540
+ projectRef: paramsOrProjectRef,
541
+ ...accessoryAttributes({
542
+ items: [
543
+ {
544
+ text: paramsOrProjectRef,
545
+ variant: "normal"
546
+ }
547
+ ],
548
+ style: "codepath"
549
+ })
550
+ }
551
+ }, paramsOrOptions);
552
+ } else {
553
+ return mergeRequestOptions({
554
+ tracer,
555
+ name: "runs.list()",
556
+ icon: "runs",
557
+ attributes: {
558
+ projectRef: paramsOrProjectRef,
559
+ ...flattenAttributes(paramsOrOptions, "queryParams"),
560
+ ...accessoryAttributes({
561
+ items: [
562
+ {
563
+ text: paramsOrProjectRef,
564
+ variant: "normal"
565
+ }
566
+ ],
567
+ style: "codepath"
568
+ })
569
+ }
570
+ }, requestOptions);
571
+ }
572
+ }
573
+ return mergeRequestOptions({
574
+ tracer,
575
+ name: "runs.list()",
576
+ icon: "runs",
577
+ attributes: {
578
+ ...flattenAttributes(paramsOrProjectRef, "queryParams")
579
+ }
580
+ }, isRequestOptions(paramsOrOptions) ? paramsOrOptions : requestOptions);
581
+ }
582
+ __name(listRunsRequestOptions, "listRunsRequestOptions");
583
+ function retrieveRun(runId, requestOptions) {
584
+ const apiClient = apiClientManager.client;
585
+ if (!apiClient) {
586
+ throw apiClientMissingError();
587
+ }
588
+ const $requestOptions = mergeRequestOptions({
589
+ tracer,
590
+ name: "runs.retrieve()",
591
+ icon: "runs",
592
+ attributes: {
593
+ runId: typeof runId === "string" ? runId : runId.id,
594
+ ...accessoryAttributes({
595
+ items: [
596
+ {
597
+ text: typeof runId === "string" ? runId : runId.id,
598
+ variant: "normal"
599
+ }
600
+ ],
601
+ style: "codepath"
602
+ })
603
+ }
604
+ }, requestOptions);
605
+ if (typeof runId === "string") {
606
+ return apiClient.retrieveRun(runId, $requestOptions);
607
+ } else {
608
+ return apiClient.retrieveRun(runId.id, $requestOptions);
609
+ }
610
+ }
611
+ __name(retrieveRun, "retrieveRun");
612
+ function replayRun(runId, requestOptions) {
613
+ const apiClient = apiClientManager.client;
614
+ if (!apiClient) {
615
+ throw apiClientMissingError();
616
+ }
617
+ const $requestOptions = mergeRequestOptions({
618
+ tracer,
619
+ name: "runs.replay()",
620
+ icon: "runs",
621
+ attributes: {
622
+ runId,
623
+ ...accessoryAttributes({
624
+ items: [
625
+ {
626
+ text: runId,
627
+ variant: "normal"
628
+ }
629
+ ],
630
+ style: "codepath"
631
+ })
632
+ }
633
+ }, requestOptions);
634
+ return apiClient.replayRun(runId, $requestOptions);
635
+ }
636
+ __name(replayRun, "replayRun");
637
+ function cancelRun(runId, requestOptions) {
638
+ const apiClient = apiClientManager.client;
639
+ if (!apiClient) {
640
+ throw apiClientMissingError();
641
+ }
642
+ const $requestOptions = mergeRequestOptions({
643
+ tracer,
644
+ name: "runs.cancel()",
645
+ icon: "runs",
646
+ attributes: {
647
+ runId,
648
+ ...accessoryAttributes({
649
+ items: [
650
+ {
651
+ text: runId,
652
+ variant: "normal"
653
+ }
654
+ ],
655
+ style: "codepath"
656
+ })
657
+ }
658
+ }, requestOptions);
659
+ return apiClient.cancelRun(runId, $requestOptions);
660
+ }
661
+ __name(cancelRun, "cancelRun");
662
+ function rescheduleRun(runId, body, requestOptions) {
663
+ const apiClient = apiClientManager.client;
664
+ if (!apiClient) {
665
+ throw apiClientMissingError();
666
+ }
667
+ const $requestOptions = mergeRequestOptions({
668
+ tracer,
669
+ name: "runs.reschedule()",
670
+ icon: "runs",
671
+ attributes: {
672
+ runId,
673
+ ...accessoryAttributes({
674
+ items: [
675
+ {
676
+ text: runId,
677
+ variant: "normal"
678
+ }
679
+ ],
680
+ style: "codepath"
681
+ })
682
+ }
683
+ }, requestOptions);
684
+ return apiClient.rescheduleRun(runId, body, $requestOptions);
685
+ }
686
+ __name(rescheduleRun, "rescheduleRun");
687
+ var MAX_POLL_ATTEMPTS = 500;
688
+ async function poll(handle, options, requestOptions) {
689
+ let attempts = 0;
690
+ while (attempts++ < MAX_POLL_ATTEMPTS) {
691
+ const run = await runs.retrieve(handle, requestOptions);
692
+ if (run.isCompleted) {
693
+ return run;
694
+ }
695
+ await new Promise((resolve) => setTimeout(resolve, options?.pollIntervalMs ?? 1e3));
696
+ }
697
+ throw new Error(`Run ${handle} did not complete after ${MAX_POLL_ATTEMPTS} attempts`);
698
+ }
699
+ __name(poll, "poll");
700
+ var idempotencyKeys = {
701
+ create: createIdempotencyKey
702
+ };
703
+ function isIdempotencyKey(value) {
704
+ return typeof value === "string" && value.length === 64;
705
+ }
706
+ __name(isIdempotencyKey, "isIdempotencyKey");
707
+ async function createIdempotencyKey(key, options) {
708
+ const idempotencyKey = await generateIdempotencyKey([
709
+ ...Array.isArray(key) ? key : [
710
+ key
711
+ ]
712
+ ].concat(injectScope(options?.scope ?? "run")));
713
+ return idempotencyKey;
714
+ }
715
+ __name(createIdempotencyKey, "createIdempotencyKey");
716
+ function injectScope(scope) {
717
+ switch (scope) {
718
+ case "run": {
719
+ if (taskContext?.ctx) {
720
+ return [
721
+ taskContext.ctx.run.id
722
+ ];
723
+ }
724
+ }
725
+ case "attempt": {
726
+ if (taskContext?.ctx) {
727
+ return [
728
+ taskContext.ctx.attempt.id
729
+ ];
730
+ }
731
+ }
732
+ }
733
+ return [];
734
+ }
735
+ __name(injectScope, "injectScope");
736
+ async function generateIdempotencyKey(keyMaterial) {
737
+ const hash = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(keyMaterial.join("-")));
738
+ return Array.from(new Uint8Array(hash)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
739
+ }
740
+ __name(generateIdempotencyKey, "generateIdempotencyKey");
741
+
742
+ // src/v3/shared.ts
743
+ function queue(options) {
744
+ return options;
745
+ }
746
+ __name(queue, "queue");
747
+ function createTask(params) {
748
+ const task3 = {
749
+ id: params.id,
750
+ trigger: async (payload, options) => {
751
+ const apiClient = apiClientManager.client;
752
+ if (!apiClient) {
753
+ throw apiClientMissingError();
754
+ }
755
+ const taskMetadata = taskCatalog.getTaskMetadata(params.id);
756
+ const payloadPacket = await stringifyIO(payload);
757
+ const handle = await apiClient.triggerTask(params.id, {
758
+ payload: payloadPacket.data,
759
+ options: {
760
+ queue: options?.queue ?? params.queue,
761
+ concurrencyKey: options?.concurrencyKey,
762
+ test: taskContext.ctx?.run.isTest,
763
+ payloadType: payloadPacket.dataType,
764
+ idempotencyKey: await makeKey(options?.idempotencyKey),
765
+ delay: options?.delay,
766
+ ttl: options?.ttl,
767
+ maxAttempts: options?.maxAttempts
768
+ }
769
+ }, {
770
+ spanParentAsLink: true
771
+ }, {
772
+ name: taskMetadata ? `${taskMetadata.exportName}.trigger()` : `trigger()`,
773
+ tracer,
774
+ icon: "trigger",
775
+ attributes: {
776
+ [SEMATTRS_MESSAGING_OPERATION]: "publish",
777
+ ["messaging.client_id"]: taskContext.worker?.id,
778
+ [SEMATTRS_MESSAGING_DESTINATION]: params.queue?.name ?? params.id,
779
+ [SEMATTRS_MESSAGING_SYSTEM]: "trigger.dev",
780
+ ...accessoryAttributes({
781
+ items: [
782
+ {
783
+ text: params.id,
784
+ variant: "normal"
785
+ }
786
+ ],
787
+ style: "codepath"
788
+ })
789
+ },
790
+ onResponseBody: (body, span) => {
791
+ body && typeof body === "object" && !Array.isArray(body) && "id" in body && typeof body.id === "string" && span.setAttribute("messaging.message.id", body.id);
792
+ }
793
+ });
794
+ return handle;
795
+ },
796
+ batchTrigger: async (items) => {
797
+ const apiClient = apiClientManager.client;
798
+ if (!apiClient) {
799
+ throw apiClientMissingError();
800
+ }
801
+ const taskMetadata = taskCatalog.getTaskMetadata(params.id);
802
+ const response = await apiClient.batchTriggerTask(params.id, {
803
+ items: await Promise.all(items.map(async (item) => {
804
+ const payloadPacket = await stringifyIO(item.payload);
805
+ return {
806
+ payload: payloadPacket.data,
807
+ options: {
808
+ queue: item.options?.queue ?? params.queue,
809
+ concurrencyKey: item.options?.concurrencyKey,
810
+ test: taskContext.ctx?.run.isTest,
811
+ payloadType: payloadPacket.dataType,
812
+ idempotencyKey: await makeKey(item.options?.idempotencyKey),
813
+ delay: item.options?.delay,
814
+ ttl: item.options?.ttl,
815
+ maxAttempts: item.options?.maxAttempts
816
+ }
817
+ };
818
+ }))
819
+ }, {
820
+ spanParentAsLink: true
821
+ }, {
822
+ name: taskMetadata ? `${taskMetadata.exportName}.batchTrigger()` : `batchTrigger()`,
823
+ icon: "trigger",
824
+ tracer,
825
+ attributes: {
826
+ [SEMATTRS_MESSAGING_OPERATION]: "publish",
827
+ ["messaging.batch.message_count"]: items.length,
828
+ ["messaging.client_id"]: taskContext.worker?.id,
829
+ [SEMATTRS_MESSAGING_DESTINATION]: params.queue?.name ?? params.id,
830
+ [SEMATTRS_MESSAGING_SYSTEM]: "trigger.dev",
831
+ ...accessoryAttributes({
832
+ items: [
833
+ {
834
+ text: params.id,
835
+ variant: "normal"
836
+ }
837
+ ],
838
+ style: "codepath"
839
+ })
840
+ }
841
+ });
842
+ const handle = {
843
+ batchId: response.batchId,
844
+ runs: response.runs.map((id) => ({
845
+ id
846
+ }))
847
+ };
848
+ return handle;
849
+ },
850
+ triggerAndWait: async (payload, options) => {
851
+ const ctx = taskContext.ctx;
852
+ if (!ctx) {
853
+ throw new Error("triggerAndWait can only be used from inside a task.run()");
854
+ }
855
+ const apiClient = apiClientManager.client;
856
+ if (!apiClient) {
857
+ throw apiClientMissingError();
858
+ }
859
+ const taskMetadata = taskCatalog.getTaskMetadata(params.id);
860
+ const payloadPacket = await stringifyIO(payload);
861
+ return await tracer.startActiveSpan(taskMetadata ? `${taskMetadata.exportName}.triggerAndWait()` : `triggerAndWait()`, async (span) => {
862
+ const response = await apiClient.triggerTask(params.id, {
863
+ payload: payloadPacket.data,
864
+ options: {
865
+ dependentAttempt: ctx.attempt.id,
866
+ lockToVersion: taskContext.worker?.version,
867
+ queue: options?.queue ?? params.queue,
868
+ concurrencyKey: options?.concurrencyKey,
869
+ test: taskContext.ctx?.run.isTest,
870
+ payloadType: payloadPacket.dataType,
871
+ idempotencyKey: await makeKey(options?.idempotencyKey),
872
+ delay: options?.delay,
873
+ ttl: options?.ttl,
874
+ maxAttempts: options?.maxAttempts
875
+ }
876
+ });
877
+ span.setAttribute("messaging.message.id", response.id);
878
+ if (options?.idempotencyKey) {
879
+ const result2 = await apiClient.getRunResult(response.id);
880
+ if (result2) {
881
+ logger.log(`Result reused from previous task run with idempotency key '${options.idempotencyKey}'.`, {
882
+ runId: response.id,
883
+ idempotencyKey: options.idempotencyKey
884
+ });
885
+ return await handleTaskRunExecutionResult(result2);
886
+ }
887
+ }
888
+ const result = await runtime.waitForTask({
889
+ id: response.id,
890
+ ctx
891
+ });
892
+ return await handleTaskRunExecutionResult(result);
893
+ }, {
894
+ kind: SpanKind.PRODUCER,
895
+ attributes: {
896
+ [SemanticInternalAttributes.STYLE_ICON]: "trigger",
897
+ [SEMATTRS_MESSAGING_OPERATION]: "publish",
898
+ ["messaging.client_id"]: taskContext.worker?.id,
899
+ [SEMATTRS_MESSAGING_DESTINATION]: params.queue?.name ?? params.id,
900
+ [SEMATTRS_MESSAGING_SYSTEM]: "trigger.dev",
901
+ ...accessoryAttributes({
902
+ items: [
903
+ {
904
+ text: params.id,
905
+ variant: "normal"
906
+ }
907
+ ],
908
+ style: "codepath"
909
+ })
910
+ }
911
+ });
912
+ },
913
+ batchTriggerAndWait: async (items) => {
914
+ const ctx = taskContext.ctx;
915
+ if (!ctx) {
916
+ throw new Error("batchTriggerAndWait can only be used from inside a task.run()");
917
+ }
918
+ const apiClient = apiClientManager.client;
919
+ if (!apiClient) {
920
+ throw apiClientMissingError();
921
+ }
922
+ const taskMetadata = taskCatalog.getTaskMetadata(params.id);
923
+ return await tracer.startActiveSpan(taskMetadata ? `${taskMetadata.exportName}.batchTriggerAndWait()` : `batchTriggerAndWait()`, async (span) => {
924
+ const response = await apiClient.batchTriggerTask(params.id, {
925
+ items: await Promise.all(items.map(async (item) => {
926
+ const payloadPacket = await stringifyIO(item.payload);
927
+ return {
928
+ payload: payloadPacket.data,
929
+ options: {
930
+ lockToVersion: taskContext.worker?.version,
931
+ queue: item.options?.queue ?? params.queue,
932
+ concurrencyKey: item.options?.concurrencyKey,
933
+ test: taskContext.ctx?.run.isTest,
934
+ payloadType: payloadPacket.dataType,
935
+ idempotencyKey: await makeKey(item.options?.idempotencyKey),
936
+ delay: item.options?.delay,
937
+ ttl: item.options?.ttl,
938
+ maxAttempts: item.options?.maxAttempts
939
+ }
940
+ };
941
+ })),
942
+ dependentAttempt: ctx.attempt.id
943
+ });
944
+ span.setAttribute("messaging.message.id", response.batchId);
945
+ const getBatchResults = /* @__PURE__ */ __name(async () => {
946
+ const hasIdempotencyKey = items.some((item) => item.options?.idempotencyKey);
947
+ if (hasIdempotencyKey) {
948
+ const results = await apiClient.getBatchResults(response.batchId);
949
+ if (results) {
950
+ return results;
951
+ }
952
+ }
953
+ return {
954
+ id: response.batchId,
955
+ items: []
956
+ };
957
+ }, "getBatchResults");
958
+ const existingResults = await getBatchResults();
959
+ const incompleteRuns = response.runs.filter((runId) => !existingResults.items.some((item) => item.id === runId));
960
+ if (incompleteRuns.length === 0) {
961
+ logger.log(`Results reused from previous task runs because of the provided idempotency keys.`);
962
+ const runs3 = await handleBatchTaskRunExecutionResult(existingResults.items);
963
+ return {
964
+ id: existingResults.id,
965
+ runs: runs3
966
+ };
967
+ }
968
+ const result = await runtime.waitForBatch({
969
+ id: response.batchId,
970
+ runs: incompleteRuns,
971
+ ctx
972
+ });
973
+ const combinedItems = [];
974
+ for (const runId of response.runs) {
975
+ const existingItem = existingResults.items.find((item) => item.id === runId);
976
+ if (existingItem) {
977
+ combinedItems.push(existingItem);
978
+ } else {
979
+ const newItem = result.items.find((item) => item.id === runId);
980
+ if (newItem) {
981
+ combinedItems.push(newItem);
982
+ }
983
+ }
984
+ }
985
+ const runs2 = await handleBatchTaskRunExecutionResult(combinedItems);
986
+ return {
987
+ id: result.id,
988
+ runs: runs2
989
+ };
990
+ }, {
991
+ kind: SpanKind.PRODUCER,
992
+ attributes: {
993
+ [SEMATTRS_MESSAGING_OPERATION]: "publish",
994
+ ["messaging.batch.message_count"]: items.length,
995
+ ["messaging.client_id"]: taskContext.worker?.id,
996
+ [SEMATTRS_MESSAGING_DESTINATION]: params.queue?.name ?? params.id,
997
+ [SEMATTRS_MESSAGING_SYSTEM]: "trigger.dev",
998
+ [SemanticInternalAttributes.STYLE_ICON]: "trigger",
999
+ ...accessoryAttributes({
1000
+ items: [
1001
+ {
1002
+ text: params.id,
1003
+ variant: "normal"
1004
+ }
1005
+ ],
1006
+ style: "codepath"
1007
+ })
1008
+ }
1009
+ });
1010
+ }
1011
+ };
1012
+ taskCatalog.registerTaskMetadata({
1013
+ id: params.id,
1014
+ packageVersion: version,
1015
+ queue: params.queue,
1016
+ retry: params.retry ? {
1017
+ ...defaultRetryOptions,
1018
+ ...params.retry
1019
+ } : void 0,
1020
+ machine: params.machine,
1021
+ fns: {
1022
+ run: params.run,
1023
+ init: params.init,
1024
+ cleanup: params.cleanup,
1025
+ middleware: params.middleware,
1026
+ handleError: params.handleError,
1027
+ onSuccess: params.onSuccess,
1028
+ onFailure: params.onFailure,
1029
+ onStart: params.onStart
1030
+ }
1031
+ });
1032
+ return task3;
1033
+ }
1034
+ __name(createTask, "createTask");
1035
+ async function trigger(id, payload, options, requestOptions) {
1036
+ const apiClient = apiClientManager.client;
1037
+ if (!apiClient) {
1038
+ throw apiClientMissingError();
1039
+ }
1040
+ const payloadPacket = await stringifyIO(payload);
1041
+ const handle = await apiClient.triggerTask(id, {
1042
+ payload: payloadPacket.data,
1043
+ options: {
1044
+ queue: options?.queue,
1045
+ concurrencyKey: options?.concurrencyKey,
1046
+ test: taskContext.ctx?.run.isTest,
1047
+ payloadType: payloadPacket.dataType,
1048
+ idempotencyKey: await makeKey(options?.idempotencyKey),
1049
+ delay: options?.delay,
1050
+ ttl: options?.ttl,
1051
+ maxAttempts: options?.maxAttempts
1052
+ }
1053
+ }, {
1054
+ spanParentAsLink: true
1055
+ }, {
1056
+ name: `tasks.trigger()`,
1057
+ tracer,
1058
+ icon: "trigger",
1059
+ attributes: {
1060
+ [SEMATTRS_MESSAGING_OPERATION]: "publish",
1061
+ ["messaging.client_id"]: taskContext.worker?.id,
1062
+ [SEMATTRS_MESSAGING_SYSTEM]: "trigger.dev",
1063
+ ...accessoryAttributes({
1064
+ items: [
1065
+ {
1066
+ text: id,
1067
+ variant: "normal"
1068
+ }
1069
+ ],
1070
+ style: "codepath"
1071
+ })
1072
+ },
1073
+ onResponseBody: (body, span) => {
1074
+ body && typeof body === "object" && !Array.isArray(body) && "id" in body && typeof body.id === "string" && span.setAttribute("messaging.message.id", body.id);
1075
+ },
1076
+ ...requestOptions
1077
+ });
1078
+ return handle;
1079
+ }
1080
+ __name(trigger, "trigger");
1081
+ async function triggerAndWait(id, payload, options, requestOptions) {
1082
+ const ctx = taskContext.ctx;
1083
+ if (!ctx) {
1084
+ throw new Error("tasks.triggerAndWait can only be used from inside a task.run()");
1085
+ }
1086
+ const apiClient = apiClientManager.client;
1087
+ if (!apiClient) {
1088
+ throw apiClientMissingError();
1089
+ }
1090
+ const payloadPacket = await stringifyIO(payload);
1091
+ return await tracer.startActiveSpan("tasks.triggerAndWait()", async (span) => {
1092
+ const response = await apiClient.triggerTask(id, {
1093
+ payload: payloadPacket.data,
1094
+ options: {
1095
+ dependentAttempt: ctx.attempt.id,
1096
+ lockToVersion: taskContext.worker?.version,
1097
+ queue: options?.queue,
1098
+ concurrencyKey: options?.concurrencyKey,
1099
+ test: taskContext.ctx?.run.isTest,
1100
+ payloadType: payloadPacket.dataType,
1101
+ idempotencyKey: await makeKey(options?.idempotencyKey),
1102
+ delay: options?.delay,
1103
+ ttl: options?.ttl,
1104
+ maxAttempts: options?.maxAttempts
1105
+ }
1106
+ }, {}, requestOptions);
1107
+ span.setAttribute("messaging.message.id", response.id);
1108
+ if (options?.idempotencyKey) {
1109
+ const result2 = await apiClient.getRunResult(response.id);
1110
+ if (result2) {
1111
+ logger.log(`Result reused from previous task run with idempotency key '${options.idempotencyKey}'.`, {
1112
+ runId: response.id,
1113
+ idempotencyKey: options.idempotencyKey
1114
+ });
1115
+ return await handleTaskRunExecutionResult(result2);
1116
+ }
1117
+ }
1118
+ const result = await runtime.waitForTask({
1119
+ id: response.id,
1120
+ ctx
1121
+ });
1122
+ return await handleTaskRunExecutionResult(result);
1123
+ }, {
1124
+ kind: SpanKind.PRODUCER,
1125
+ attributes: {
1126
+ [SemanticInternalAttributes.STYLE_ICON]: "trigger",
1127
+ [SEMATTRS_MESSAGING_OPERATION]: "publish",
1128
+ ["messaging.client_id"]: taskContext.worker?.id,
1129
+ [SEMATTRS_MESSAGING_DESTINATION]: id,
1130
+ [SEMATTRS_MESSAGING_SYSTEM]: "trigger.dev",
1131
+ ...accessoryAttributes({
1132
+ items: [
1133
+ {
1134
+ text: id,
1135
+ variant: "normal"
1136
+ }
1137
+ ],
1138
+ style: "codepath"
1139
+ })
1140
+ }
1141
+ });
1142
+ }
1143
+ __name(triggerAndWait, "triggerAndWait");
1144
+ async function triggerAndPoll(id, payload, options, requestOptions) {
1145
+ const handle = await trigger(id, payload, options, requestOptions);
1146
+ return runs.poll(handle, options, requestOptions);
1147
+ }
1148
+ __name(triggerAndPoll, "triggerAndPoll");
1149
+ async function batchTrigger(id, items, requestOptions) {
1150
+ const apiClient = apiClientManager.client;
1151
+ if (!apiClient) {
1152
+ throw apiClientMissingError();
1153
+ }
1154
+ const response = await apiClient.batchTriggerTask(id, {
1155
+ items: await Promise.all(items.map(async (item) => {
1156
+ const payloadPacket = await stringifyIO(item.payload);
1157
+ return {
1158
+ payload: payloadPacket.data,
1159
+ options: {
1160
+ queue: item.options?.queue,
1161
+ concurrencyKey: item.options?.concurrencyKey,
1162
+ test: taskContext.ctx?.run.isTest,
1163
+ payloadType: payloadPacket.dataType,
1164
+ idempotencyKey: await makeKey(item.options?.idempotencyKey),
1165
+ delay: item.options?.delay,
1166
+ ttl: item.options?.ttl,
1167
+ maxAttempts: item.options?.maxAttempts
1168
+ }
1169
+ };
1170
+ }))
1171
+ }, {
1172
+ spanParentAsLink: true
1173
+ }, {
1174
+ name: `tasks.batchTrigger()`,
1175
+ tracer,
1176
+ icon: "trigger",
1177
+ attributes: {
1178
+ [SEMATTRS_MESSAGING_OPERATION]: "publish",
1179
+ ["messaging.client_id"]: taskContext.worker?.id,
1180
+ [SEMATTRS_MESSAGING_SYSTEM]: "trigger.dev",
1181
+ ...accessoryAttributes({
1182
+ items: [
1183
+ {
1184
+ text: id,
1185
+ variant: "normal"
1186
+ }
1187
+ ],
1188
+ style: "codepath"
1189
+ })
1190
+ },
1191
+ ...requestOptions
1192
+ });
1193
+ const handle = {
1194
+ batchId: response.batchId,
1195
+ runs: response.runs.map((id2) => ({
1196
+ id: id2
1197
+ }))
1198
+ };
1199
+ return handle;
1200
+ }
1201
+ __name(batchTrigger, "batchTrigger");
1202
+ async function handleBatchTaskRunExecutionResult(items) {
1203
+ const someObjectStoreOutputs = items.some((item) => item.ok && item.outputType === "application/store");
1204
+ if (!someObjectStoreOutputs) {
1205
+ const results = await Promise.all(items.map(async (item) => {
1206
+ return await handleTaskRunExecutionResult(item);
1207
+ }));
1208
+ return results;
1209
+ }
1210
+ return await tracer.startActiveSpan("store.downloadPayloads", async (span) => {
1211
+ const results = await Promise.all(items.map(async (item) => {
1212
+ return await handleTaskRunExecutionResult(item);
1213
+ }));
1214
+ return results;
1215
+ }, {
1216
+ kind: SpanKind.INTERNAL,
1217
+ [SemanticInternalAttributes.STYLE_ICON]: "cloud-download"
1218
+ });
1219
+ }
1220
+ __name(handleBatchTaskRunExecutionResult, "handleBatchTaskRunExecutionResult");
1221
+ async function handleTaskRunExecutionResult(execution) {
1222
+ if (execution.ok) {
1223
+ const outputPacket = {
1224
+ data: execution.output,
1225
+ dataType: execution.outputType
1226
+ };
1227
+ const importedPacket = await conditionallyImportPacket(outputPacket, tracer);
1228
+ return {
1229
+ ok: true,
1230
+ id: execution.id,
1231
+ output: await parsePacket(importedPacket)
1232
+ };
1233
+ } else {
1234
+ return {
1235
+ ok: false,
1236
+ id: execution.id,
1237
+ error: createErrorTaskError(execution.error)
1238
+ };
1239
+ }
1240
+ }
1241
+ __name(handleTaskRunExecutionResult, "handleTaskRunExecutionResult");
1242
+ function apiClientMissingError() {
1243
+ const hasBaseUrl = !!apiClientManager.baseURL;
1244
+ const hasAccessToken = !!apiClientManager.accessToken;
1245
+ if (!hasBaseUrl && !hasAccessToken) {
1246
+ return `You need to set the TRIGGER_API_URL and TRIGGER_SECRET_KEY environment variables.`;
1247
+ } else if (!hasBaseUrl) {
1248
+ return `You need to set the TRIGGER_API_URL environment variable.`;
1249
+ } else if (!hasAccessToken) {
1250
+ return `You need to set the TRIGGER_SECRET_KEY environment variable.`;
1251
+ }
1252
+ return `Unknown error`;
1253
+ }
1254
+ __name(apiClientMissingError, "apiClientMissingError");
1255
+ async function makeKey(idempotencyKey) {
1256
+ if (!idempotencyKey) {
1257
+ return;
1258
+ }
1259
+ if (isIdempotencyKey(idempotencyKey)) {
1260
+ return idempotencyKey;
1261
+ }
1262
+ return await idempotencyKeys.create(idempotencyKey, {
1263
+ scope: "global"
1264
+ });
1265
+ }
1266
+ __name(makeKey, "makeKey");
1267
+
1268
+ // src/v3/tasks.ts
1269
+ function task(options) {
1270
+ return createTask(options);
1271
+ }
1272
+ __name(task, "task");
1273
+ var tasks = {
1274
+ trigger,
1275
+ triggerAndPoll,
1276
+ batchTrigger,
1277
+ triggerAndWait
1278
+ };
1279
+ var wait = {
1280
+ for: async (options) => {
1281
+ return tracer.startActiveSpan(`wait.for()`, async (span) => {
1282
+ const durationInMs = calculateDurationInMs(options);
1283
+ await runtime.waitForDuration(durationInMs);
1284
+ }, {
1285
+ attributes: {
1286
+ [SemanticInternalAttributes.STYLE_ICON]: "wait",
1287
+ ...accessoryAttributes({
1288
+ items: [
1289
+ {
1290
+ text: nameForWaitOptions(options),
1291
+ variant: "normal"
1292
+ }
1293
+ ],
1294
+ style: "codepath"
1295
+ })
1296
+ }
1297
+ });
1298
+ },
1299
+ until: async (options) => {
1300
+ return tracer.startActiveSpan(`wait.until()`, async (span) => {
1301
+ const start = Date.now();
1302
+ if (options.throwIfInThePast && options.date < /* @__PURE__ */ new Date()) {
1303
+ throw new Error("Date is in the past");
1304
+ }
1305
+ const durationInMs = options.date.getTime() - start;
1306
+ await runtime.waitForDuration(durationInMs);
1307
+ }, {
1308
+ attributes: {
1309
+ [SemanticInternalAttributes.STYLE_ICON]: "wait",
1310
+ ...accessoryAttributes({
1311
+ items: [
1312
+ {
1313
+ text: options.date.toISOString(),
1314
+ variant: "normal"
1315
+ }
1316
+ ],
1317
+ style: "codepath"
1318
+ })
1319
+ }
1320
+ });
1321
+ }
1322
+ };
1323
+ function nameForWaitOptions(options) {
1324
+ if ("seconds" in options) {
1325
+ return options.seconds === 1 ? `1 second` : `${options.seconds} seconds`;
1326
+ }
1327
+ if ("minutes" in options) {
1328
+ return options.minutes === 1 ? `1 minute` : `${options.minutes} minutes`;
1329
+ }
1330
+ if ("hours" in options) {
1331
+ return options.hours === 1 ? `1 hour` : `${options.hours} hours`;
1332
+ }
1333
+ if ("days" in options) {
1334
+ return options.days === 1 ? `1 day` : `${options.days} days`;
1335
+ }
1336
+ if ("weeks" in options) {
1337
+ return options.weeks === 1 ? `1 week` : `${options.weeks} weeks`;
1338
+ }
1339
+ if ("months" in options) {
1340
+ return options.months === 1 ? `1 month` : `${options.months} months`;
1341
+ }
1342
+ if ("years" in options) {
1343
+ return options.years === 1 ? `1 year` : `${options.years} years`;
1344
+ }
1345
+ return "NaN";
1346
+ }
1347
+ __name(nameForWaitOptions, "nameForWaitOptions");
1348
+ function calculateDurationInMs(options) {
1349
+ if ("seconds" in options) {
1350
+ return options.seconds * 1e3;
1351
+ }
1352
+ if ("minutes" in options) {
1353
+ return options.minutes * 1e3 * 60;
1354
+ }
1355
+ if ("hours" in options) {
1356
+ return options.hours * 1e3 * 60 * 60;
1357
+ }
1358
+ if ("days" in options) {
1359
+ return options.days * 1e3 * 60 * 60 * 24;
1360
+ }
1361
+ if ("weeks" in options) {
1362
+ return options.weeks * 1e3 * 60 * 60 * 24 * 7;
1363
+ }
1364
+ if ("months" in options) {
1365
+ return options.months * 1e3 * 60 * 60 * 24 * 30;
1366
+ }
1367
+ if ("years" in options) {
1368
+ return options.years * 1e3 * 60 * 60 * 24 * 365;
1369
+ }
1370
+ throw new Error("Invalid options");
1371
+ }
1372
+ __name(calculateDurationInMs, "calculateDurationInMs");
1373
+ var usage = {
1374
+ /**
1375
+ * Get the current running usage of this task run.
1376
+ *
1377
+ * @example
1378
+ *
1379
+ * ```typescript
1380
+ * import { usage, task } from "@trigger.dev/sdk/v3";
1381
+ *
1382
+ * export const myTask = task({
1383
+ * id: "my-task",
1384
+ * run: async (payload, { ctx }) => {
1385
+ * // ... Do a bunch of work
1386
+ *
1387
+ * const currentUsage = usage.getCurrent();
1388
+ *
1389
+ * // You have access to the current compute cost and duration up to this point
1390
+ * console.log("Current attempt compute cost and duration", {
1391
+ * cost: currentUsage.compute.attempt.costInCents,
1392
+ * duration: currentUsage.compute.attempt.durationMs,
1393
+ * });
1394
+ *
1395
+ * // You also can see the total compute cost and duration up to this point in the run, across all attempts
1396
+ * console.log("Current total compute cost and duration", {
1397
+ * cost: currentUsage.compute.total.costInCents,
1398
+ * duration: currentUsage.compute.total.durationMs,
1399
+ * });
1400
+ *
1401
+ * // You can see the base cost of the run, which is the cost of the run before any compute costs
1402
+ * console.log("Total cost", {
1403
+ * cost: currentUsage.totalCostInCents,
1404
+ * baseCost: currentUsage.baseCostInCents,
1405
+ * });
1406
+ * },
1407
+ * });
1408
+ * ```
1409
+ */
1410
+ getCurrent: () => {
1411
+ const sample = usage$1.sample();
1412
+ const machine = taskContext.ctx?.machine;
1413
+ const run = taskContext.ctx?.run;
1414
+ if (!sample) {
1415
+ return {
1416
+ compute: {
1417
+ attempt: {
1418
+ costInCents: 0,
1419
+ durationMs: 0
1420
+ },
1421
+ total: {
1422
+ costInCents: run?.costInCents ?? 0,
1423
+ durationMs: run?.durationMs ?? 0
1424
+ }
1425
+ },
1426
+ baseCostInCents: run?.baseCostInCents ?? 0,
1427
+ totalCostInCents: (run?.costInCents ?? 0) + (run?.baseCostInCents ?? 0)
1428
+ };
1429
+ }
1430
+ const currentCostInCents = machine?.centsPerMs ? sample.cpuTime * machine.centsPerMs : 0;
1431
+ return {
1432
+ compute: {
1433
+ attempt: {
1434
+ costInCents: currentCostInCents,
1435
+ durationMs: sample.cpuTime
1436
+ },
1437
+ total: {
1438
+ costInCents: (run?.costInCents ?? 0) + currentCostInCents,
1439
+ durationMs: (run?.durationMs ?? 0) + sample.cpuTime
1440
+ }
1441
+ },
1442
+ baseCostInCents: run?.baseCostInCents ?? 0,
1443
+ totalCostInCents: (run?.costInCents ?? 0) + currentCostInCents + (run?.baseCostInCents ?? 0)
1444
+ };
1445
+ },
1446
+ /**
1447
+ * Measure the cost and duration of a function.
1448
+ *
1449
+ * @example
1450
+ *
1451
+ * ```typescript
1452
+ * import { usage } from "@trigger.dev/sdk/v3";
1453
+ *
1454
+ * export const myTask = task({
1455
+ * id: "my-task",
1456
+ * run: async (payload, { ctx }) => {
1457
+ * const { result, compute } = await usage.measure(async () => {
1458
+ * // Do some work
1459
+ * return "result";
1460
+ * });
1461
+ *
1462
+ * console.log("Result", result);
1463
+ * console.log("Cost and duration", { cost: compute.costInCents, duration: compute.durationMs });
1464
+ * },
1465
+ * });
1466
+ * ```
1467
+ */
1468
+ measure: async (cb) => {
1469
+ const measurement = usage$1.start();
1470
+ const result = await cb();
1471
+ const sample = usage$1.stop(measurement);
1472
+ const machine = taskContext.ctx?.machine;
1473
+ const costInCents = machine?.centsPerMs ? sample.cpuTime * machine.centsPerMs : 0;
1474
+ return {
1475
+ result,
1476
+ compute: {
1477
+ costInCents,
1478
+ durationMs: sample.cpuTime
1479
+ }
1480
+ };
1481
+ }
1482
+ };
1483
+
1484
+ // src/v3/schedules/index.ts
1485
+ var schedules_exports = {};
1486
+ __export(schedules_exports, {
1487
+ activate: () => activate,
1488
+ create: () => create,
1489
+ deactivate: () => deactivate,
1490
+ del: () => del,
1491
+ list: () => list,
1492
+ retrieve: () => retrieve,
1493
+ task: () => task2,
1494
+ timezones: () => timezones,
1495
+ update: () => update
1496
+ });
1497
+ function task2(params) {
1498
+ const task3 = createTask(params);
1499
+ const cron = params.cron ? typeof params.cron === "string" ? params.cron : params.cron.pattern : void 0;
1500
+ const timezone = (params.cron && typeof params.cron !== "string" ? params.cron.timezone : "UTC") ?? "UTC";
1501
+ taskCatalog.updateTaskMetadata(task3.id, {
1502
+ triggerSource: "schedule",
1503
+ schedule: cron ? {
1504
+ cron,
1505
+ timezone
1506
+ } : void 0
1507
+ });
1508
+ return task3;
1509
+ }
1510
+ __name(task2, "task");
1511
+ function create(options, requestOptions) {
1512
+ const apiClient = apiClientManager.client;
1513
+ if (!apiClient) {
1514
+ throw apiClientMissingError();
1515
+ }
1516
+ const $requestOptions = mergeRequestOptions({
1517
+ tracer,
1518
+ name: "schedules.create()",
1519
+ icon: "clock",
1520
+ attributes: {
1521
+ ...accessoryAttributes({
1522
+ items: [
1523
+ {
1524
+ text: options.cron,
1525
+ variant: "normal"
1526
+ }
1527
+ ],
1528
+ style: "codepath"
1529
+ })
1530
+ }
1531
+ }, requestOptions);
1532
+ return apiClient.createSchedule(options, $requestOptions);
1533
+ }
1534
+ __name(create, "create");
1535
+ function retrieve(scheduleId, requestOptions) {
1536
+ const apiClient = apiClientManager.client;
1537
+ if (!apiClient) {
1538
+ throw apiClientMissingError();
1539
+ }
1540
+ const $requestOptions = mergeRequestOptions({
1541
+ tracer,
1542
+ name: "schedules.retrieve()",
1543
+ icon: "clock",
1544
+ attributes: {
1545
+ scheduleId,
1546
+ ...accessoryAttributes({
1547
+ items: [
1548
+ {
1549
+ text: scheduleId,
1550
+ variant: "normal"
1551
+ }
1552
+ ],
1553
+ style: "codepath"
1554
+ })
1555
+ }
1556
+ }, requestOptions);
1557
+ return apiClient.retrieveSchedule(scheduleId, $requestOptions);
1558
+ }
1559
+ __name(retrieve, "retrieve");
1560
+ function update(scheduleId, options, requestOptions) {
1561
+ const apiClient = apiClientManager.client;
1562
+ if (!apiClient) {
1563
+ throw apiClientMissingError();
1564
+ }
1565
+ const $requestOptions = mergeRequestOptions({
1566
+ tracer,
1567
+ name: "schedules.update()",
1568
+ icon: "clock",
1569
+ attributes: {
1570
+ scheduleId,
1571
+ ...accessoryAttributes({
1572
+ items: [
1573
+ {
1574
+ text: scheduleId,
1575
+ variant: "normal"
1576
+ }
1577
+ ],
1578
+ style: "codepath"
1579
+ })
1580
+ }
1581
+ }, requestOptions);
1582
+ return apiClient.updateSchedule(scheduleId, options, $requestOptions);
1583
+ }
1584
+ __name(update, "update");
1585
+ function del(scheduleId, requestOptions) {
1586
+ const apiClient = apiClientManager.client;
1587
+ if (!apiClient) {
1588
+ throw apiClientMissingError();
1589
+ }
1590
+ const $requestOptions = mergeRequestOptions({
1591
+ tracer,
1592
+ name: "schedules.delete()",
1593
+ icon: "clock",
1594
+ attributes: {
1595
+ scheduleId,
1596
+ ...accessoryAttributes({
1597
+ items: [
1598
+ {
1599
+ text: scheduleId,
1600
+ variant: "normal"
1601
+ }
1602
+ ],
1603
+ style: "codepath"
1604
+ })
1605
+ }
1606
+ }, requestOptions);
1607
+ return apiClient.deleteSchedule(scheduleId, $requestOptions);
1608
+ }
1609
+ __name(del, "del");
1610
+ function deactivate(scheduleId, requestOptions) {
1611
+ const apiClient = apiClientManager.client;
1612
+ if (!apiClient) {
1613
+ throw apiClientMissingError();
1614
+ }
1615
+ const $requestOptions = mergeRequestOptions({
1616
+ tracer,
1617
+ name: "schedules.deactivate()",
1618
+ icon: "clock",
1619
+ attributes: {
1620
+ scheduleId,
1621
+ ...accessoryAttributes({
1622
+ items: [
1623
+ {
1624
+ text: scheduleId,
1625
+ variant: "normal"
1626
+ }
1627
+ ],
1628
+ style: "codepath"
1629
+ })
1630
+ }
1631
+ }, requestOptions);
1632
+ return apiClient.deactivateSchedule(scheduleId, $requestOptions);
1633
+ }
1634
+ __name(deactivate, "deactivate");
1635
+ function activate(scheduleId, requestOptions) {
1636
+ const apiClient = apiClientManager.client;
1637
+ if (!apiClient) {
1638
+ throw apiClientMissingError();
1639
+ }
1640
+ const $requestOptions = mergeRequestOptions({
1641
+ tracer,
1642
+ name: "schedules.activate()",
1643
+ icon: "clock",
1644
+ attributes: {
1645
+ scheduleId,
1646
+ ...accessoryAttributes({
1647
+ items: [
1648
+ {
1649
+ text: scheduleId,
1650
+ variant: "normal"
1651
+ }
1652
+ ],
1653
+ style: "codepath"
1654
+ })
1655
+ }
1656
+ }, requestOptions);
1657
+ return apiClient.activateSchedule(scheduleId, $requestOptions);
1658
+ }
1659
+ __name(activate, "activate");
1660
+ function list(options, requestOptions) {
1661
+ const apiClient = apiClientManager.client;
1662
+ if (!apiClient) {
1663
+ throw apiClientMissingError();
1664
+ }
1665
+ const $requestOptions = mergeRequestOptions({
1666
+ tracer,
1667
+ name: "schedules.list()",
1668
+ icon: "clock"
1669
+ }, requestOptions);
1670
+ return apiClient.listSchedules(options, $requestOptions);
1671
+ }
1672
+ __name(list, "list");
1673
+ function timezones(options) {
1674
+ const baseUrl = apiClientManager.baseURL;
1675
+ if (!baseUrl) {
1676
+ throw apiClientMissingError();
1677
+ }
1678
+ return zodfetch(TimezonesResult, `${baseUrl}/api/v1/timezones${options?.excludeUtc === true ? "?excludeUtc=true" : ""}`, {
1679
+ method: "GET",
1680
+ headers: {
1681
+ "Content-Type": "application/json"
1682
+ }
1683
+ });
1684
+ }
1685
+ __name(timezones, "timezones");
1686
+
1687
+ // src/v3/envvars.ts
1688
+ var envvars_exports = {};
1689
+ __export(envvars_exports, {
1690
+ create: () => create2,
1691
+ del: () => del2,
1692
+ list: () => list2,
1693
+ retrieve: () => retrieve2,
1694
+ update: () => update2,
1695
+ upload: () => upload
1696
+ });
1697
+ function upload(projectRefOrParams, slugOrRequestOptions, params, requestOptions) {
1698
+ let $projectRef;
1699
+ let $params;
1700
+ let $slug;
1701
+ const $requestOptions = overloadRequestOptions("upload", slugOrRequestOptions, requestOptions);
1702
+ if (taskContext.ctx) {
1703
+ if (typeof projectRefOrParams === "string") {
1704
+ $projectRef = projectRefOrParams;
1705
+ $slug = typeof slugOrRequestOptions === "string" ? slugOrRequestOptions : taskContext.ctx.environment.slug;
1706
+ if (!params) {
1707
+ throw new Error("params is required");
1708
+ }
1709
+ $params = params;
1710
+ } else {
1711
+ $params = projectRefOrParams;
1712
+ $projectRef = taskContext.ctx.project.ref;
1713
+ $slug = taskContext.ctx.environment.slug;
1714
+ }
1715
+ } else {
1716
+ if (typeof projectRefOrParams !== "string") {
1717
+ throw new Error("projectRef is required");
1718
+ }
1719
+ if (!slugOrRequestOptions || typeof slugOrRequestOptions !== "string") {
1720
+ throw new Error("slug is required");
1721
+ }
1722
+ if (!params) {
1723
+ throw new Error("params is required");
1724
+ }
1725
+ $projectRef = projectRefOrParams;
1726
+ $slug = slugOrRequestOptions;
1727
+ $params = params;
1728
+ }
1729
+ const apiClient = apiClientManager.client;
1730
+ if (!apiClient) {
1731
+ throw apiClientMissingError();
1732
+ }
1733
+ return apiClient.importEnvVars($projectRef, $slug, $params, $requestOptions);
1734
+ }
1735
+ __name(upload, "upload");
1736
+ function list2(projectRefOrRequestOptions, slug, requestOptions) {
1737
+ const $projectRef = !isRequestOptions(projectRefOrRequestOptions) ? projectRefOrRequestOptions : taskContext.ctx?.project.ref;
1738
+ const $slug = slug ?? taskContext.ctx?.environment.slug;
1739
+ let $requestOptions = isRequestOptions(projectRefOrRequestOptions) ? projectRefOrRequestOptions : requestOptions;
1740
+ if (!$projectRef) {
1741
+ throw new Error("projectRef is required");
1742
+ }
1743
+ if (!$slug) {
1744
+ throw new Error("slug is required");
1745
+ }
1746
+ $requestOptions = mergeRequestOptions({
1747
+ tracer,
1748
+ name: "envvars.list()",
1749
+ icon: "id-badge"
1750
+ }, $requestOptions);
1751
+ const apiClient = apiClientManager.client;
1752
+ if (!apiClient) {
1753
+ throw apiClientMissingError();
1754
+ }
1755
+ return apiClient.listEnvVars($projectRef, $slug, $requestOptions);
1756
+ }
1757
+ __name(list2, "list");
1758
+ function create2(projectRefOrParams, slugOrRequestOptions, params, requestOptions) {
1759
+ let $projectRef;
1760
+ let $slug;
1761
+ let $params;
1762
+ const $requestOptions = overloadRequestOptions("create", slugOrRequestOptions, requestOptions);
1763
+ if (taskContext.ctx) {
1764
+ if (typeof projectRefOrParams === "string") {
1765
+ $projectRef = projectRefOrParams;
1766
+ $slug = typeof slugOrRequestOptions === "string" ? slugOrRequestOptions : taskContext.ctx.environment.slug;
1767
+ if (!params) {
1768
+ throw new Error("params is required");
1769
+ }
1770
+ $params = params;
1771
+ } else {
1772
+ $params = projectRefOrParams;
1773
+ $projectRef = taskContext.ctx.project.ref;
1774
+ $slug = taskContext.ctx.environment.slug;
1775
+ }
1776
+ } else {
1777
+ if (typeof projectRefOrParams !== "string") {
1778
+ throw new Error("projectRef is required");
1779
+ }
1780
+ if (!slugOrRequestOptions || typeof slugOrRequestOptions !== "string") {
1781
+ throw new Error("slug is required");
1782
+ }
1783
+ if (!params) {
1784
+ throw new Error("params is required");
1785
+ }
1786
+ $projectRef = projectRefOrParams;
1787
+ $slug = slugOrRequestOptions;
1788
+ $params = params;
1789
+ }
1790
+ const apiClient = apiClientManager.client;
1791
+ if (!apiClient) {
1792
+ throw apiClientMissingError();
1793
+ }
1794
+ return apiClient.createEnvVar($projectRef, $slug, $params, $requestOptions);
1795
+ }
1796
+ __name(create2, "create");
1797
+ function retrieve2(projectRefOrName, slugOrRequestOptions, name1, requestOptions) {
1798
+ let $projectRef;
1799
+ let $slug;
1800
+ let $name;
1801
+ const $requestOptions = overloadRequestOptions("retrieve", slugOrRequestOptions, requestOptions);
1802
+ if (typeof name1 === "string") {
1803
+ $projectRef = projectRefOrName;
1804
+ $slug = typeof slugOrRequestOptions === "string" ? slugOrRequestOptions : taskContext.ctx?.environment.slug;
1805
+ $name = name1;
1806
+ } else {
1807
+ $projectRef = taskContext.ctx?.project.ref;
1808
+ $slug = taskContext.ctx?.environment.slug;
1809
+ $name = projectRefOrName;
1810
+ }
1811
+ if (!$projectRef) {
1812
+ throw new Error("projectRef is required");
1813
+ }
1814
+ if (!$slug) {
1815
+ throw new Error("slug is required");
1816
+ }
1817
+ const apiClient = apiClientManager.client;
1818
+ if (!apiClient) {
1819
+ throw apiClientMissingError();
1820
+ }
1821
+ return apiClient.retrieveEnvVar($projectRef, $slug, $name, $requestOptions);
1822
+ }
1823
+ __name(retrieve2, "retrieve");
1824
+ function del2(projectRefOrName, slugOrRequestOptions, name1, requestOptions) {
1825
+ let $projectRef;
1826
+ let $slug;
1827
+ let $name;
1828
+ const $requestOptions = overloadRequestOptions("del", slugOrRequestOptions, requestOptions);
1829
+ if (typeof name1 === "string") {
1830
+ $projectRef = projectRefOrName;
1831
+ $slug = typeof slugOrRequestOptions === "string" ? slugOrRequestOptions : taskContext.ctx?.environment.slug;
1832
+ $name = name1;
1833
+ } else {
1834
+ $projectRef = taskContext.ctx?.project.ref;
1835
+ $slug = taskContext.ctx?.environment.slug;
1836
+ $name = projectRefOrName;
1837
+ }
1838
+ if (!$projectRef) {
1839
+ throw new Error("projectRef is required");
1840
+ }
1841
+ if (!$slug) {
1842
+ throw new Error("slug is required");
1843
+ }
1844
+ const apiClient = apiClientManager.client;
1845
+ if (!apiClient) {
1846
+ throw apiClientMissingError();
1847
+ }
1848
+ return apiClient.deleteEnvVar($projectRef, $slug, $name, $requestOptions);
1849
+ }
1850
+ __name(del2, "del");
1851
+ function update2(projectRefOrName, slugOrParams, nameOrRequestOptions, params, requestOptions) {
1852
+ let $projectRef;
1853
+ let $slug;
1854
+ let $name;
1855
+ let $params;
1856
+ const $requestOptions = overloadRequestOptions("update", nameOrRequestOptions, requestOptions);
1857
+ if (taskContext.ctx) {
1858
+ if (typeof slugOrParams === "string") {
1859
+ $projectRef = slugOrParams;
1860
+ $slug = slugOrParams ?? taskContext.ctx.environment.slug;
1861
+ $name = typeof nameOrRequestOptions === "string" ? nameOrRequestOptions : taskContext.ctx.environment.slug;
1862
+ if (!params) {
1863
+ throw new Error("params is required");
1864
+ }
1865
+ $params = params;
1866
+ } else {
1867
+ $params = slugOrParams;
1868
+ $projectRef = taskContext.ctx.project.ref;
1869
+ $slug = taskContext.ctx.environment.slug;
1870
+ $name = projectRefOrName;
1871
+ }
1872
+ } else {
1873
+ if (typeof slugOrParams !== "string") {
1874
+ throw new Error("slug is required");
1875
+ }
1876
+ if (!projectRefOrName) {
1877
+ throw new Error("projectRef is required");
1878
+ }
1879
+ if (!params) {
1880
+ throw new Error("params is required");
1881
+ }
1882
+ $projectRef = projectRefOrName;
1883
+ $slug = slugOrParams;
1884
+ $name = name;
1885
+ $params = params;
1886
+ }
1887
+ const apiClient = apiClientManager.client;
1888
+ if (!apiClient) {
1889
+ throw apiClientMissingError();
1890
+ }
1891
+ return apiClient.updateEnvVar($projectRef, $slug, $name, $params, $requestOptions);
1892
+ }
1893
+ __name(update2, "update");
1894
+ function overloadRequestOptions(name1, slugOrRequestOptions, requestOptions) {
1895
+ if (isRequestOptions(slugOrRequestOptions)) {
1896
+ return mergeRequestOptions({
1897
+ tracer,
1898
+ name: `envvars.${name1}()`,
1899
+ icon: "id-badge"
1900
+ }, slugOrRequestOptions);
1901
+ } else {
1902
+ return mergeRequestOptions({
1903
+ tracer,
1904
+ name: `envvars.${name1}()`,
1905
+ icon: "id-badge"
1906
+ }, requestOptions);
1907
+ }
1908
+ }
1909
+ __name(overloadRequestOptions, "overloadRequestOptions");
1910
+
1911
+ // src/v3/index.ts
1912
+ function configure(options) {
1913
+ apiClientManager.setGlobalAPIClientConfiguration(options);
1914
+ }
1915
+ __name(configure, "configure");
880
1916
 
881
- export { InMemoryCache, createCache, retry, task, wait };
1917
+ export { InMemoryCache, configure, createCache, envvars_exports as envvars, idempotencyKeys, isIdempotencyKey, queue, retry, runs, schedules_exports as schedules, task, tasks, usage, wait };
882
1918
  //# sourceMappingURL=out.js.map
883
1919
  //# sourceMappingURL=index.mjs.map