@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.
@@ -1,7 +1,324 @@
1
- import { TaskRunContext, InitOutput, RetryOptions, QueueOptions, MachineCpu, MachineMemory, RunFnParams, InitFnParams, HandleErrorFnParams, HandleErrorResult, MiddlewareFnParams, SuccessFnParams, FetchRetryOptions } from '@trigger.dev/core/v3';
2
- export { HandleErrorArgs, HandleErrorFunction, LogLevel, RetryOptions, ProjectConfig as TriggerConfig, logger } from '@trigger.dev/core/v3';
1
+ import { RetryOptions, FetchRetryOptions, ListProjectRunsQueryParams, ApiRequestOptions, CursorPagePromise, ListRunResponseItem, ListRunsQueryParams, ApiPromise, ReplayRunResponse, CanceledRunResponse, RescheduleRunRequestBody, RetrieveRunResponse, TaskRunContext, QueueOptions, InitOutput, MachineCpu, MachineMemory, RunFnParams, InitFnParams, HandleErrorFnParams, HandleErrorResult, MiddlewareFnParams, StartFnParams, SuccessFnParams, FailureFnParams, ScheduledTaskPayload, CreateScheduleOptions, ScheduleObject, UpdateScheduleOptions, DeletedScheduleObject, ListScheduleOptions, OffsetLimitPagePromise, ImportEnvironmentVariablesParams, EnvironmentVariableResponseBody, EnvironmentVariables, CreateEnvironmentVariableParams, EnvironmentVariableValue, UpdateEnvironmentVariableParams, ApiClientConfiguration } from '@trigger.dev/core/v3';
2
+ export { AbortTaskRunError, ApiClientConfiguration, ApiError, AuthenticationError, BadRequestError, ConflictError, HandleErrorArgs, HandleErrorFunction, ImportEnvironmentVariablesParams, InternalServerError, LogLevel, NotFoundError, PermissionDeniedError, RateLimitError, ResolveEnvironmentVariablesFunction, ResolveEnvironmentVariablesParams, ResolveEnvironmentVariablesResult, RetryOptions, ProjectConfig as TriggerConfig, UnprocessableEntityError, logger } from '@trigger.dev/core/v3';
3
3
  import { HttpHandler } from 'msw';
4
4
 
5
+ type CacheMetadata = {
6
+ createdTime: number;
7
+ ttl?: number | null;
8
+ };
9
+ type CacheEntry<Value = unknown> = {
10
+ metadata: CacheMetadata;
11
+ value: Value;
12
+ };
13
+ type Eventually<Value> = Value | null | undefined | Promise<Value | null | undefined>;
14
+ type CacheStore<Value = any> = {
15
+ name?: string;
16
+ get: (key: string) => Eventually<CacheEntry<Value>>;
17
+ set: (key: string, value: CacheEntry<Value>) => unknown | Promise<unknown>;
18
+ delete: (key: string) => unknown | Promise<unknown>;
19
+ };
20
+ type CacheFunction = <Value>(cacheKey: string, fn: () => Promise<Value> | Value) => Promise<Value> | Value;
21
+ declare class InMemoryCache<Value = any> {
22
+ private _cache;
23
+ get(key: string): Eventually<CacheEntry<Value>>;
24
+ set(key: string, value: CacheEntry<Value>): unknown;
25
+ delete(key: string): unknown;
26
+ }
27
+ /**
28
+ * Create a cache function that uses the provided store to cache values. Using InMemoryCache is safe because each task run is isolated.
29
+ * @param store
30
+ * @returns
31
+ */
32
+ declare function createCache(store: CacheStore): CacheFunction;
33
+
34
+ declare function onThrow<T>(fn: (options: {
35
+ attempt: number;
36
+ maxAttempts: number;
37
+ }) => Promise<T>, options: RetryOptions): Promise<T>;
38
+ interface RetryFetchRequestInit extends RequestInit {
39
+ retry?: FetchRetryOptions;
40
+ timeoutInMs?: number;
41
+ }
42
+ declare function retryFetch(input: RequestInfo | URL, init?: RetryFetchRequestInit | undefined): Promise<Response>;
43
+ declare const retry: {
44
+ onThrow: typeof onThrow;
45
+ fetch: typeof retryFetch;
46
+ interceptFetch: (...handlers: Array<HttpHandler>) => {
47
+ run: <T>(fn: (...args: any[]) => Promise<T>) => Promise<T>;
48
+ };
49
+ };
50
+
51
+ type RetrieveRunResult<TOutput> = Prettify<TOutput extends RunHandle<infer THandleOutput> ? Omit<RetrieveRunResponse, "output"> & {
52
+ output?: THandleOutput;
53
+ } : Omit<RetrieveRunResponse, "output"> & {
54
+ output?: TOutput;
55
+ }>;
56
+ declare const runs: {
57
+ replay: typeof replayRun;
58
+ cancel: typeof cancelRun;
59
+ retrieve: typeof retrieveRun;
60
+ list: typeof listRuns;
61
+ reschedule: typeof rescheduleRun;
62
+ poll: typeof poll;
63
+ };
64
+ declare function listRuns(projectRef: string, params?: ListProjectRunsQueryParams, requestOptions?: ApiRequestOptions): CursorPagePromise<typeof ListRunResponseItem>;
65
+ declare function listRuns(params?: ListRunsQueryParams, requestOptions?: ApiRequestOptions): CursorPagePromise<typeof ListRunResponseItem>;
66
+ declare function retrieveRun<TRunId extends RunHandle<any> | string>(runId: TRunId, requestOptions?: ApiRequestOptions): ApiPromise<RetrieveRunResult<TRunId>>;
67
+ declare function replayRun(runId: string, requestOptions?: ApiRequestOptions): ApiPromise<ReplayRunResponse>;
68
+ declare function cancelRun(runId: string, requestOptions?: ApiRequestOptions): ApiPromise<CanceledRunResponse>;
69
+ declare function rescheduleRun(runId: string, body: RescheduleRunRequestBody, requestOptions?: ApiRequestOptions): ApiPromise<RetrieveRunResponse>;
70
+ type PollOptions = {
71
+ pollIntervalMs?: number;
72
+ };
73
+ declare function poll<TRunHandle extends RunHandle<any> | string>(handle: TRunHandle, options?: {
74
+ pollIntervalMs?: number;
75
+ }, requestOptions?: ApiRequestOptions): Promise<(TRunHandle extends RunHandle<infer THandleOutput> ? Omit<{
76
+ status: "CANCELED" | "COMPLETED" | "FAILED" | "WAITING_FOR_DEPLOY" | "QUEUED" | "EXECUTING" | "REATTEMPTING" | "FROZEN" | "CRASHED" | "INTERRUPTED" | "SYSTEM_FAILURE" | "DELAYED" | "EXPIRED";
77
+ id: string;
78
+ isTest: boolean;
79
+ createdAt: Date;
80
+ attempts: ({
81
+ status: "PENDING" | "CANCELED" | "COMPLETED" | "FAILED" | "EXECUTING" | "PAUSED";
82
+ id: string;
83
+ createdAt: Date;
84
+ updatedAt: Date;
85
+ startedAt?: Date | undefined;
86
+ completedAt?: Date | undefined;
87
+ error?: {
88
+ message: string;
89
+ name?: string | undefined;
90
+ stackTrace?: string | undefined;
91
+ } | undefined;
92
+ } | undefined)[];
93
+ updatedAt: Date;
94
+ taskIdentifier: string;
95
+ isQueued: boolean;
96
+ isExecuting: boolean;
97
+ isCompleted: boolean;
98
+ isSuccess: boolean;
99
+ isFailed: boolean;
100
+ isCancelled: boolean;
101
+ payload?: any;
102
+ payloadPresignedUrl?: string | undefined;
103
+ output?: any;
104
+ outputPresignedUrl?: string | undefined;
105
+ schedule?: {
106
+ id: string;
107
+ generator: {
108
+ type: "CRON";
109
+ expression: string;
110
+ description: string;
111
+ };
112
+ externalId?: string | undefined;
113
+ deduplicationKey?: string | undefined;
114
+ } | undefined;
115
+ idempotencyKey?: string | undefined;
116
+ version?: string | undefined;
117
+ startedAt?: Date | undefined;
118
+ finishedAt?: Date | undefined;
119
+ delayedUntil?: Date | undefined;
120
+ ttl?: string | undefined;
121
+ expiredAt?: Date | undefined;
122
+ }, "output"> & {
123
+ output?: THandleOutput | undefined;
124
+ } : Omit<{
125
+ status: "CANCELED" | "COMPLETED" | "FAILED" | "WAITING_FOR_DEPLOY" | "QUEUED" | "EXECUTING" | "REATTEMPTING" | "FROZEN" | "CRASHED" | "INTERRUPTED" | "SYSTEM_FAILURE" | "DELAYED" | "EXPIRED";
126
+ id: string;
127
+ isTest: boolean;
128
+ createdAt: Date;
129
+ attempts: ({
130
+ status: "PENDING" | "CANCELED" | "COMPLETED" | "FAILED" | "EXECUTING" | "PAUSED";
131
+ id: string;
132
+ createdAt: Date;
133
+ updatedAt: Date;
134
+ startedAt?: Date | undefined;
135
+ completedAt?: Date | undefined;
136
+ error?: {
137
+ message: string;
138
+ name?: string | undefined;
139
+ stackTrace?: string | undefined;
140
+ } | undefined;
141
+ } | undefined)[];
142
+ updatedAt: Date;
143
+ taskIdentifier: string;
144
+ isQueued: boolean;
145
+ isExecuting: boolean;
146
+ isCompleted: boolean;
147
+ isSuccess: boolean;
148
+ isFailed: boolean;
149
+ isCancelled: boolean;
150
+ payload?: any;
151
+ payloadPresignedUrl?: string | undefined;
152
+ output?: any;
153
+ outputPresignedUrl?: string | undefined;
154
+ schedule?: {
155
+ id: string;
156
+ generator: {
157
+ type: "CRON";
158
+ expression: string;
159
+ description: string;
160
+ };
161
+ externalId?: string | undefined;
162
+ deduplicationKey?: string | undefined;
163
+ } | undefined;
164
+ idempotencyKey?: string | undefined;
165
+ version?: string | undefined;
166
+ startedAt?: Date | undefined;
167
+ finishedAt?: Date | undefined;
168
+ delayedUntil?: Date | undefined;
169
+ ttl?: string | undefined;
170
+ expiredAt?: Date | undefined;
171
+ }, "output"> & {
172
+ output?: TRunHandle | undefined;
173
+ }) extends infer T ? { [K in keyof T]: (TRunHandle extends RunHandle<infer THandleOutput> ? Omit<{
174
+ status: "CANCELED" | "COMPLETED" | "FAILED" | "WAITING_FOR_DEPLOY" | "QUEUED" | "EXECUTING" | "REATTEMPTING" | "FROZEN" | "CRASHED" | "INTERRUPTED" | "SYSTEM_FAILURE" | "DELAYED" | "EXPIRED";
175
+ id: string;
176
+ isTest: boolean;
177
+ createdAt: Date;
178
+ attempts: ({
179
+ status: "PENDING" | "CANCELED" | "COMPLETED" | "FAILED" | "EXECUTING" | "PAUSED";
180
+ id: string;
181
+ createdAt: Date;
182
+ updatedAt: Date;
183
+ startedAt?: Date | undefined;
184
+ completedAt?: Date | undefined;
185
+ error?: {
186
+ message: string;
187
+ name?: string | undefined;
188
+ stackTrace?: string | undefined;
189
+ } | undefined;
190
+ } | undefined)[];
191
+ updatedAt: Date;
192
+ taskIdentifier: string;
193
+ isQueued: boolean;
194
+ isExecuting: boolean;
195
+ isCompleted: boolean;
196
+ isSuccess: boolean;
197
+ isFailed: boolean;
198
+ isCancelled: boolean;
199
+ payload?: any;
200
+ payloadPresignedUrl?: string | undefined;
201
+ output?: any;
202
+ outputPresignedUrl?: string | undefined;
203
+ schedule?: {
204
+ id: string;
205
+ generator: {
206
+ type: "CRON";
207
+ expression: string;
208
+ description: string;
209
+ };
210
+ externalId?: string | undefined;
211
+ deduplicationKey?: string | undefined;
212
+ } | undefined;
213
+ idempotencyKey?: string | undefined;
214
+ version?: string | undefined;
215
+ startedAt?: Date | undefined;
216
+ finishedAt?: Date | undefined;
217
+ delayedUntil?: Date | undefined;
218
+ ttl?: string | undefined;
219
+ expiredAt?: Date | undefined;
220
+ }, "output"> & {
221
+ output?: THandleOutput | undefined;
222
+ } : Omit<{
223
+ status: "CANCELED" | "COMPLETED" | "FAILED" | "WAITING_FOR_DEPLOY" | "QUEUED" | "EXECUTING" | "REATTEMPTING" | "FROZEN" | "CRASHED" | "INTERRUPTED" | "SYSTEM_FAILURE" | "DELAYED" | "EXPIRED";
224
+ id: string;
225
+ isTest: boolean;
226
+ createdAt: Date;
227
+ attempts: ({
228
+ status: "PENDING" | "CANCELED" | "COMPLETED" | "FAILED" | "EXECUTING" | "PAUSED";
229
+ id: string;
230
+ createdAt: Date;
231
+ updatedAt: Date;
232
+ startedAt?: Date | undefined;
233
+ completedAt?: Date | undefined;
234
+ error?: {
235
+ message: string;
236
+ name?: string | undefined;
237
+ stackTrace?: string | undefined;
238
+ } | undefined;
239
+ } | undefined)[];
240
+ updatedAt: Date;
241
+ taskIdentifier: string;
242
+ isQueued: boolean;
243
+ isExecuting: boolean;
244
+ isCompleted: boolean;
245
+ isSuccess: boolean;
246
+ isFailed: boolean;
247
+ isCancelled: boolean;
248
+ payload?: any;
249
+ payloadPresignedUrl?: string | undefined;
250
+ output?: any;
251
+ outputPresignedUrl?: string | undefined;
252
+ schedule?: {
253
+ id: string;
254
+ generator: {
255
+ type: "CRON";
256
+ expression: string;
257
+ description: string;
258
+ };
259
+ externalId?: string | undefined;
260
+ deduplicationKey?: string | undefined;
261
+ } | undefined;
262
+ idempotencyKey?: string | undefined;
263
+ version?: string | undefined;
264
+ startedAt?: Date | undefined;
265
+ finishedAt?: Date | undefined;
266
+ delayedUntil?: Date | undefined;
267
+ ttl?: string | undefined;
268
+ expiredAt?: Date | undefined;
269
+ }, "output"> & {
270
+ output?: TRunHandle | undefined;
271
+ })[K]; } : never>;
272
+
273
+ declare const idempotencyKeys: {
274
+ create: typeof createIdempotencyKey;
275
+ };
276
+ declare const __brand: unique symbol;
277
+ type Brand<B> = {
278
+ [__brand]: B;
279
+ };
280
+ type Branded<T, B> = T & Brand<B>;
281
+ type IdempotencyKey = Branded<string, "IdempotencyKey">;
282
+ declare function isIdempotencyKey(value: string | string[] | IdempotencyKey): value is IdempotencyKey;
283
+ /**
284
+ * Creates a deterministic idempotency key based on the provided key material.
285
+ *
286
+ * If running inside a task, the task run ID is automatically included in the key material, giving you a unique key per task run.
287
+ * This ensures that a given child task is only triggered once per task run, even if the parent task is retried.
288
+ *
289
+ * @param {string | string[]} key The key material to create the idempotency key from.
290
+ * @param {object} [options] Additional options.
291
+ * @param {"run" | "attempt" | "global"} [options.scope="run"] The scope of the idempotency key.
292
+ *
293
+ * @returns {Promise<IdempotencyKey>} The idempotency key as a branded string.
294
+ *
295
+ * @example
296
+ *
297
+ * ```typescript
298
+ * import { idempotencyKeys, task } from "@trigger.dev/sdk/v3";
299
+ *
300
+ * export const myTask = task({
301
+ * id: "my-task",
302
+ * run: async (payload: any) => {
303
+ * const idempotencyKey = await idempotencyKeys.create("my-task-key");
304
+ *
305
+ * // Use the idempotency key when triggering child tasks
306
+ * await childTask.triggerAndWait(payload, { idempotencyKey });
307
+ * }
308
+ * });
309
+ * ```
310
+ *
311
+ * You can also use the `scope` parameter to create a key that is unique per task run, task run attempts (retries of the same run), or globally:
312
+ *
313
+ * ```typescript
314
+ * await idempotencyKeys.create("my-task-key", { scope: "attempt" }); // Creates a key that is unique per task run attempt
315
+ * await idempotencyKeys.create("my-task-key", { scope: "global" }); // Skips including the task run ID
316
+ * ```
317
+ */
318
+ declare function createIdempotencyKey(key: string | string[], options?: {
319
+ scope?: "run" | "attempt" | "global";
320
+ }): Promise<IdempotencyKey>;
321
+
5
322
  type Context = TaskRunContext;
6
323
  type RequireOne<T, K extends keyof T> = {
7
324
  [X in Exclude<keyof T, K>]?: T[X];
@@ -9,9 +326,12 @@ type RequireOne<T, K extends keyof T> = {
9
326
  [P in K]-?: T[P];
10
327
  };
11
328
  type Queue = RequireOne<QueueOptions, "name">;
12
- type TaskOptions<TPayload, TOutput = any, TInitOutput extends InitOutput = any> = {
329
+ declare function queue(options: {
330
+ name: string;
331
+ } & QueueOptions): Queue;
332
+ type TaskOptions<TIdentifier extends string, TPayload = void, TOutput = unknown, TInitOutput extends InitOutput = any> = {
13
333
  /** An id for your task. This must be unique inside your project and not change between versions. */
14
- id: string;
334
+ id: TIdentifier;
15
335
  /** The retry settings when an uncaught error is thrown.
16
336
  *
17
337
  * If omitted it will use the values in your `trigger.config.ts` file.
@@ -79,6 +399,7 @@ type TaskOptions<TPayload, TOutput = any, TInitOutput extends InitOutput = any>
79
399
  * - 1
80
400
  * - 2
81
401
  * - 4
402
+ * @deprecated use preset instead
82
403
  */
83
404
  cpu?: MachineCpu;
84
405
  /** In GBs of RAM. The default is 1.
@@ -90,8 +411,11 @@ type TaskOptions<TPayload, TOutput = any, TInitOutput extends InitOutput = any>
90
411
  * - 2
91
412
  * - 4
92
413
  * - 8
414
+ * * @deprecated use preset instead
93
415
  */
94
416
  memory?: MachineMemory;
417
+ /** Preset to use for the machine. Defaults to small-1x */
418
+ preset?: "micro" | "small-1x" | "small-2x" | "medium-1x" | "medium-2x" | "large-1x" | "large-2x";
95
419
  };
96
420
  /** This gets called when a task is triggered. It's where you put the code you want to execute.
97
421
  *
@@ -99,19 +423,64 @@ type TaskOptions<TPayload, TOutput = any, TInitOutput extends InitOutput = any>
99
423
  * @param params - Metadata about the run.
100
424
  */
101
425
  run: (payload: TPayload, params: RunFnParams<TInitOutput>) => Promise<TOutput>;
426
+ /**
427
+ * init is called before the run function is called. It's useful for setting up any global state.
428
+ */
102
429
  init?: (payload: TPayload, params: InitFnParams) => Promise<TInitOutput>;
103
- handleError?: (payload: TPayload, error: unknown, params: HandleErrorFnParams<TInitOutput>) => HandleErrorResult;
430
+ /**
431
+ * cleanup is called after the run function has completed.
432
+ */
104
433
  cleanup?: (payload: TPayload, params: RunFnParams<TInitOutput>) => Promise<void>;
434
+ /**
435
+ * handleError is called when the run function throws an error. It can be used to modify the error or return new retry options.
436
+ */
437
+ handleError?: (payload: TPayload, error: unknown, params: HandleErrorFnParams<TInitOutput>) => HandleErrorResult;
438
+ /**
439
+ * middleware allows you to run code "around" the run function. This can be useful for logging, metrics, or other cross-cutting concerns.
440
+ *
441
+ * When writing middleware, you should always call `next()` to continue the execution of the task:
442
+ *
443
+ * ```ts
444
+ * export const middlewareTask = task({
445
+ * id: "middleware-task",
446
+ * middleware: async (payload, { ctx, next }) => {
447
+ * console.log("Before run");
448
+ * await next();
449
+ * console.log("After run");
450
+ * },
451
+ * run: async (payload, { ctx }) => {}
452
+ * });
453
+ * ```
454
+ */
105
455
  middleware?: (payload: TPayload, params: MiddlewareFnParams) => Promise<void>;
106
- onSuccess?: (payload: TPayload, params: SuccessFnParams<TOutput, TInitOutput>) => Promise<void>;
456
+ /**
457
+ * onStart is called the first time a task is executed in a run (not before every retry)
458
+ */
459
+ onStart?: (payload: TPayload, params: StartFnParams) => Promise<void>;
460
+ /**
461
+ * onSuccess is called after the run function has successfully completed.
462
+ */
463
+ onSuccess?: (payload: TPayload, output: TOutput, params: SuccessFnParams<TInitOutput>) => Promise<void>;
464
+ /**
465
+ * onFailure is called after a task run has failed (meaning the run function threw an error and won't be retried anymore)
466
+ */
467
+ onFailure?: (payload: TPayload, error: unknown, params: FailureFnParams<TInitOutput>) => Promise<void>;
107
468
  };
108
- type InvokeHandle = {
109
- id: string;
469
+ declare const __output: unique symbol;
470
+ type BrandOutput<B> = {
471
+ [__output]: B;
110
472
  };
111
- type InvokeBatchHandle = {
473
+ type BrandedOutput<T, B> = T & BrandOutput<B>;
474
+ type RunHandle<TOutput> = BrandedOutput<{
475
+ id: string;
476
+ }, TOutput>;
477
+ /**
478
+ * A BatchRunHandle can be used to retrieve the runs of a batch trigger in a typesafe manner.
479
+ */
480
+ type BatchRunHandle<TOutput> = BrandedOutput<{
112
481
  batchId: string;
113
- runs: string[];
114
- };
482
+ runs: Array<RunHandle<TOutput>>;
483
+ }, TOutput>;
115
484
  type TaskRunResult<TOutput = any> = {
116
485
  ok: true;
117
486
  id: string;
@@ -119,48 +488,202 @@ type TaskRunResult<TOutput = any> = {
119
488
  } | {
120
489
  ok: false;
121
490
  id: string;
122
- error: any;
491
+ error: unknown;
123
492
  };
124
493
  type BatchResult<TOutput = any> = {
125
494
  id: string;
126
495
  runs: TaskRunResult<TOutput>[];
127
496
  };
128
- type Task<TInput, TOutput = any> = {
129
- trigger: (params: {
130
- payload: TInput;
131
- options?: TaskRunOptions;
132
- }) => Promise<InvokeHandle>;
133
- batchTrigger: (params: {
134
- items: {
135
- payload: TInput;
136
- options?: TaskRunOptions;
137
- }[];
138
- batchOptions?: BatchRunOptions;
139
- }) => Promise<InvokeBatchHandle>;
140
- triggerAndWait: (params: {
141
- payload: TInput;
142
- options?: TaskRunOptions;
143
- }) => Promise<TOutput>;
144
- batchTriggerAndWait: (params: {
145
- items: {
146
- payload: TInput;
147
- options?: TaskRunOptions;
148
- }[];
149
- batchOptions?: BatchRunOptions;
150
- }) => Promise<BatchResult<TOutput>>;
497
+ type BatchItem<TInput> = TInput extends void ? {
498
+ payload?: TInput;
499
+ options?: TaskRunOptions;
500
+ } : {
501
+ payload: TInput;
502
+ options?: TaskRunOptions;
151
503
  };
504
+ interface Task<TIdentifier extends string, TInput = void, TOutput = any> {
505
+ /**
506
+ * The id of the task.
507
+ */
508
+ id: TIdentifier;
509
+ /**
510
+ * Trigger a task with the given payload, and continue without waiting for the result. If you want to wait for the result, use `triggerAndWait`. Returns the id of the triggered task run.
511
+ * @param payload
512
+ * @param options
513
+ * @returns RunHandle
514
+ * - `id` - The id of the triggered task run.
515
+ */
516
+ trigger: (payload: TInput, options?: TaskRunOptions) => Promise<RunHandle<TOutput>>;
517
+ /**
518
+ * Batch trigger multiple task runs with the given payloads, and continue without waiting for the results. If you want to wait for the results, use `batchTriggerAndWait`. Returns the id of the triggered batch.
519
+ * @param items
520
+ * @returns InvokeBatchHandle
521
+ * - `batchId` - The id of the triggered batch.
522
+ * - `runs` - The ids of the triggered task runs.
523
+ */
524
+ batchTrigger: (items: Array<BatchItem<TInput>>) => Promise<BatchRunHandle<TOutput>>;
525
+ /**
526
+ * Trigger a task with the given payload, and wait for the result. Returns the result of the task run
527
+ * @param payload
528
+ * @param options - Options for the task run
529
+ * @returns TaskRunResult
530
+ * @example
531
+ * ```
532
+ * const result = await task.triggerAndWait({ foo: "bar" });
533
+ *
534
+ * if (result.ok) {
535
+ * console.log(result.output);
536
+ * } else {
537
+ * console.error(result.error);
538
+ * }
539
+ * ```
540
+ */
541
+ triggerAndWait: (payload: TInput, options?: TaskRunOptions) => Promise<TaskRunResult<TOutput>>;
542
+ /**
543
+ * Batch trigger multiple task runs with the given payloads, and wait for the results. Returns the results of the task runs.
544
+ * @param items
545
+ * @returns BatchResult
546
+ * @example
547
+ * ```
548
+ * const result = await task.batchTriggerAndWait([
549
+ * { payload: { foo: "bar" } },
550
+ * { payload: { foo: "baz" } },
551
+ * ]);
552
+ *
553
+ * for (const run of result.runs) {
554
+ * if (run.ok) {
555
+ * console.log(run.output);
556
+ * } else {
557
+ * console.error(run.error);
558
+ * }
559
+ * }
560
+ * ```
561
+ */
562
+ batchTriggerAndWait: (items: Array<BatchItem<TInput>>) => Promise<BatchResult<TOutput>>;
563
+ }
564
+ type AnyTask = Task<string, any, any>;
565
+ type TaskPayload<TTask extends AnyTask> = TTask extends Task<string, infer TInput, any> ? TInput : never;
566
+ type TaskOutput<TTask extends AnyTask> = TTask extends Task<string, any, infer TOutput> ? TOutput : never;
567
+ type TaskOutputHandle<TTask extends AnyTask> = TTask extends Task<string, any, infer TOutput> ? RunHandle<TOutput> : never;
568
+ type TaskBatchOutputHandle<TTask extends AnyTask> = TTask extends Task<string, any, infer TOutput> ? BatchRunHandle<TOutput> : never;
569
+ type TaskIdentifier<TTask extends AnyTask> = TTask extends Task<infer TIdentifier, any, any> ? TIdentifier : never;
152
570
  type TaskRunOptions = {
153
- idempotencyKey?: string;
571
+ /**
572
+ * A unique key that can be used to ensure that a task is only triggered once per key.
573
+ *
574
+ * You can use `idempotencyKeys.create` to create an idempotency key first, and then pass it to the task options.
575
+ *
576
+ * @example
577
+ *
578
+ * ```typescript
579
+ * import { idempotencyKeys, task } from "@trigger.dev/sdk/v3";
580
+ *
581
+ * export const myTask = task({
582
+ * id: "my-task",
583
+ * run: async (payload: any) => {
584
+ * // scoped to the task run by default
585
+ * const idempotencyKey = await idempotencyKeys.create("my-task-key");
586
+ *
587
+ * // Use the idempotency key when triggering child tasks
588
+ * await childTask.triggerAndWait(payload, { idempotencyKey });
589
+ *
590
+ * // scoped globally, does not include the task run ID
591
+ * const globalIdempotencyKey = await idempotencyKeys.create("my-task-key", { scope: "global" });
592
+ *
593
+ * await childTask.triggerAndWait(payload, { idempotencyKey: globalIdempotencyKey });
594
+ *
595
+ * // You can also pass a string directly, which is the same as a global idempotency key
596
+ * await childTask.triggerAndWait(payload, { idempotencyKey: "my-very-unique-key" });
597
+ * }
598
+ * });
599
+ * ```
600
+ *
601
+ * When triggering a task inside another task, we automatically inject the run ID into the key material.
602
+ *
603
+ * If you are triggering a task from your backend, ensure you include some sufficiently unique key material to prevent collisions.
604
+ *
605
+ * @example
606
+ *
607
+ * ```typescript
608
+ * import { idempotencyKeys, tasks } from "@trigger.dev/sdk/v3";
609
+ *
610
+ * // Somewhere in your backend
611
+ * const idempotencyKey = await idempotenceKeys.create(["my-task-trigger", "user-123"]);
612
+ * await tasks.trigger("my-task", { foo: "bar" }, { idempotencyKey });
613
+ * ```
614
+ *
615
+ */
616
+ idempotencyKey?: IdempotencyKey | string | string[];
154
617
  maxAttempts?: number;
155
- startAt?: Date;
156
- startAfter?: number;
157
618
  queue?: TaskRunConcurrencyOptions;
158
619
  concurrencyKey?: string;
620
+ /**
621
+ * The delay before the task is executed. This can be a string like "1h" or a Date object.
622
+ *
623
+ * @example
624
+ * "1h" - 1 hour
625
+ * "30d" - 30 days
626
+ * "15m" - 15 minutes
627
+ * "2w" - 2 weeks
628
+ * "60s" - 60 seconds
629
+ * new Date("2025-01-01T00:00:00Z")
630
+ */
631
+ delay?: string | Date;
632
+ /**
633
+ * Set a time-to-live for this run. If the run is not executed within this time, it will be removed from the queue and never execute.
634
+ *
635
+ * @example
636
+ *
637
+ * ```ts
638
+ * await myTask.trigger({ foo: "bar" }, { ttl: "1h" });
639
+ * await myTask.trigger({ foo: "bar" }, { ttl: 60 * 60 }); // 1 hour
640
+ * ```
641
+ *
642
+ * The minimum value is 1 second. Setting the `ttl` to `0` will disable the TTL and the run will never expire.
643
+ *
644
+ * **Note:** Runs in development have a default `ttl` of 10 minutes. You can override this by setting the `ttl` option.
645
+ */
646
+ ttl?: string | number;
159
647
  };
160
648
  type TaskRunConcurrencyOptions = Queue;
161
- type BatchRunOptions = TaskRunOptions & {
162
- maxConcurrency?: number;
163
- };
649
+ type Prettify<T> = {
650
+ [K in keyof T]: T[K];
651
+ } & {};
652
+ /**
653
+ * Trigger a task by its identifier with the given payload. Returns a typesafe `RunHandle`.
654
+ *
655
+ * @example
656
+ *
657
+ * ```ts
658
+ * import { tasks, runs } from "@trigger.dev/sdk/v3";
659
+ * import type { myTask } from "./myTasks"; // Import just the type of the task
660
+ *
661
+ * const handle = await tasks.trigger<typeof myTask>("my-task", { foo: "bar" }); // The id and payload are fully typesafe
662
+ * const run = await runs.retrieve(handle);
663
+ * console.log(run.output) // The output is also fully typed
664
+ * ```
665
+ *
666
+ * @returns {RunHandle} An object with the `id` of the run. Can be used to retrieve the completed run output in a typesafe manner.
667
+ */
668
+ declare function trigger<TTask extends AnyTask>(id: TaskIdentifier<TTask>, payload: TaskPayload<TTask>, options?: TaskRunOptions, requestOptions?: ApiRequestOptions): Promise<TaskOutputHandle<TTask>>;
669
+ declare function triggerAndWait<TTask extends AnyTask>(id: TaskIdentifier<TTask>, payload: TaskPayload<TTask>, options?: TaskRunOptions, requestOptions?: ApiRequestOptions): Promise<TaskRunResult<TaskOutput<TTask>>>;
670
+ /**
671
+ * Trigger a task by its identifier with the given payload and poll until the run is completed.
672
+ *
673
+ * @example
674
+ *
675
+ * ```ts
676
+ * import { tasks, runs } from "@trigger.dev/sdk/v3";
677
+ * import type { myTask } from "./myTasks"; // Import just the type of the task
678
+ *
679
+ * const run = await tasks.triggerAndPoll<typeof myTask>("my-task", { foo: "bar" }); // The id and payload are fully typesafe
680
+ * console.log(run.output) // The output is also fully typed
681
+ * ```
682
+ *
683
+ * @returns {Run} The completed run, either successful or failed.
684
+ */
685
+ declare function triggerAndPoll<TTask extends AnyTask>(id: TaskIdentifier<TTask>, payload: TaskPayload<TTask>, options?: TaskRunOptions & PollOptions, requestOptions?: ApiRequestOptions): Promise<RetrieveRunResult<TaskOutputHandle<TTask>>>;
686
+ declare function batchTrigger<TTask extends AnyTask>(id: TaskIdentifier<TTask>, items: Array<BatchItem<TaskPayload<TTask>>>, requestOptions?: ApiRequestOptions): Promise<TaskBatchOutputHandle<TTask>>;
164
687
 
165
688
  /** Creates a task that can be triggered
166
689
  * @param options - Task options
@@ -180,7 +703,13 @@ type BatchRunOptions = TaskRunOptions & {
180
703
  *
181
704
  * @returns A task that can be triggered
182
705
  */
183
- declare function task<TInput, TOutput = any, TInitOutput extends InitOutput = any>(options: TaskOptions<TInput, TOutput, TInitOutput>): Task<TInput, TOutput>;
706
+ declare function task$1<TIdentifier extends string, TInput = void, TOutput = unknown, TInitOutput extends InitOutput = any>(options: TaskOptions<TIdentifier, TInput, TOutput, TInitOutput>): Task<TIdentifier, TInput, TOutput>;
707
+ declare const tasks: {
708
+ trigger: typeof trigger;
709
+ triggerAndPoll: typeof triggerAndPoll;
710
+ batchTrigger: typeof batchTrigger;
711
+ triggerAndWait: typeof triggerAndWait;
712
+ };
184
713
 
185
714
  type WaitOptions = {
186
715
  seconds: number;
@@ -205,50 +734,220 @@ declare const wait: {
205
734
  }) => Promise<void>;
206
735
  };
207
736
 
208
- type CacheMetadata = {
209
- createdTime: number;
210
- ttl?: number | null;
737
+ type ComputeUsage = {
738
+ costInCents: number;
739
+ durationMs: number;
211
740
  };
212
- type CacheEntry<Value = unknown> = {
213
- metadata: CacheMetadata;
214
- value: Value;
741
+ type CurrentUsage = {
742
+ compute: {
743
+ attempt: ComputeUsage;
744
+ total: ComputeUsage;
745
+ };
746
+ baseCostInCents: number;
747
+ totalCostInCents: number;
215
748
  };
216
- type Eventually<Value> = Value | null | undefined | Promise<Value | null | undefined>;
217
- type CacheStore<Value = any> = {
218
- name?: string;
219
- get: (key: string) => Eventually<CacheEntry<Value>>;
220
- set: (key: string, value: CacheEntry<Value>) => unknown | Promise<unknown>;
221
- delete: (key: string) => unknown | Promise<unknown>;
749
+ declare const usage: {
750
+ /**
751
+ * Get the current running usage of this task run.
752
+ *
753
+ * @example
754
+ *
755
+ * ```typescript
756
+ * import { usage, task } from "@trigger.dev/sdk/v3";
757
+ *
758
+ * export const myTask = task({
759
+ * id: "my-task",
760
+ * run: async (payload, { ctx }) => {
761
+ * // ... Do a bunch of work
762
+ *
763
+ * const currentUsage = usage.getCurrent();
764
+ *
765
+ * // You have access to the current compute cost and duration up to this point
766
+ * console.log("Current attempt compute cost and duration", {
767
+ * cost: currentUsage.compute.attempt.costInCents,
768
+ * duration: currentUsage.compute.attempt.durationMs,
769
+ * });
770
+ *
771
+ * // You also can see the total compute cost and duration up to this point in the run, across all attempts
772
+ * console.log("Current total compute cost and duration", {
773
+ * cost: currentUsage.compute.total.costInCents,
774
+ * duration: currentUsage.compute.total.durationMs,
775
+ * });
776
+ *
777
+ * // You can see the base cost of the run, which is the cost of the run before any compute costs
778
+ * console.log("Total cost", {
779
+ * cost: currentUsage.totalCostInCents,
780
+ * baseCost: currentUsage.baseCostInCents,
781
+ * });
782
+ * },
783
+ * });
784
+ * ```
785
+ */
786
+ getCurrent: () => CurrentUsage;
787
+ /**
788
+ * Measure the cost and duration of a function.
789
+ *
790
+ * @example
791
+ *
792
+ * ```typescript
793
+ * import { usage } from "@trigger.dev/sdk/v3";
794
+ *
795
+ * export const myTask = task({
796
+ * id: "my-task",
797
+ * run: async (payload, { ctx }) => {
798
+ * const { result, compute } = await usage.measure(async () => {
799
+ * // Do some work
800
+ * return "result";
801
+ * });
802
+ *
803
+ * console.log("Result", result);
804
+ * console.log("Cost and duration", { cost: compute.costInCents, duration: compute.durationMs });
805
+ * },
806
+ * });
807
+ * ```
808
+ */
809
+ measure: <T>(cb: () => Promise<T>) => Promise<{
810
+ result: T;
811
+ compute: ComputeUsage;
812
+ }>;
222
813
  };
223
- type CacheFunction = <Value>(cacheKey: string, fn: () => Promise<Value> | Value) => Promise<Value> | Value;
224
- declare class InMemoryCache<Value = any> {
225
- private _cache;
226
- get(key: string): Eventually<CacheEntry<Value>>;
227
- set(key: string, value: CacheEntry<Value>): unknown;
228
- delete(key: string): unknown;
229
- }
814
+
815
+ type ScheduleOptions<TIdentifier extends string, TOutput, TInitOutput extends InitOutput> = TaskOptions<TIdentifier, ScheduledTaskPayload, TOutput, TInitOutput> & {
816
+ /** You can optionally specify a CRON schedule on your task. You can also dynamically add a schedule in the dashboard or using the SDK functions.
817
+ *
818
+ * 1. Pass a CRON pattern string
819
+ * ```ts
820
+ * "0 0 * * *"
821
+ * ```
822
+ *
823
+ * 2. Or an object with a pattern and an optional timezone (default is "UTC")
824
+ * ```ts
825
+ * {
826
+ * pattern: "0 0 * * *",
827
+ * timezone: "America/Los_Angeles"
828
+ * }
829
+ * ```
830
+ *
831
+ * @link https://trigger.dev/docs/v3/tasks-scheduled
832
+ */
833
+ cron?: string | {
834
+ pattern: string;
835
+ timezone?: string;
836
+ };
837
+ };
838
+ declare function task<TIdentifier extends string, TOutput, TInitOutput extends InitOutput>(params: ScheduleOptions<TIdentifier, TOutput, TInitOutput>): Task<TIdentifier, ScheduledTaskPayload, TOutput>;
230
839
  /**
231
- * Create a cache function that uses the provided store to cache values. Using InMemoryCache is safe because each task run is isolated.
232
- * @param store
233
- * @returns
840
+ * Creates a new schedule
841
+ * @param options
842
+ * @param options.task - The identifier of the task to be scheduled (Must already exist and be a scheduled task)
843
+ * @param options.cron - The cron expression for the schedule (e.g. `0 0 * * *`)
844
+ * @param options.timezone - An optional timezone for the schedule in the IANA format (e.g. `America/Los_Angeles`). Defaults to "UTC".
845
+ * @param options.externalId - An optional external identifier for the schedule
846
+ * @param options.deduplicationKey - An optional deduplication key for the schedule
847
+ * @returns The created schedule
234
848
  */
235
- declare function createCache(store: CacheStore): CacheFunction;
849
+ declare function create$1(options: CreateScheduleOptions, requestOptions?: ApiRequestOptions): ApiPromise<ScheduleObject>;
850
+ /**
851
+ * Retrieves a schedule
852
+ * @param scheduleId - The ID of the schedule to retrieve
853
+ * @returns The retrieved schedule
854
+ */
855
+ declare function retrieve$1(scheduleId: string, requestOptions?: ApiRequestOptions): ApiPromise<ScheduleObject>;
856
+ /**
857
+ * Updates a schedule
858
+ * @param scheduleId - The ID of the schedule to update
859
+ * @param options - The updated schedule options
860
+ * @param options.task - The identifier of the task to be scheduled (Must already exist and be a scheduled task)
861
+ * @param options.cron - The cron expression for the schedule (e.g. `0 0 * * *`)
862
+ * @param options.timezone - An optional timezone for the schedule in the IANA format (e.g. `America/Los_Angeles`). Defaults to "UTC".
863
+ * @param options.externalId - An optional external identifier for the schedule
864
+ * @returns The updated schedule
865
+ */
866
+ declare function update$1(scheduleId: string, options: UpdateScheduleOptions, requestOptions?: ApiRequestOptions): ApiPromise<ScheduleObject>;
867
+ /**
868
+ * Deletes a schedule
869
+ * @param scheduleId - The ID of the schedule to delete
870
+ */
871
+ declare function del$1(scheduleId: string, requestOptions?: ApiRequestOptions): ApiPromise<DeletedScheduleObject>;
872
+ /**
873
+ * Deactivates a schedule
874
+ * @param scheduleId - The ID of the schedule to deactivate
875
+ */
876
+ declare function deactivate(scheduleId: string, requestOptions?: ApiRequestOptions): ApiPromise<ScheduleObject>;
877
+ /**
878
+ * Activates a schedule
879
+ * @param scheduleId - The ID of the schedule to activate
880
+ */
881
+ declare function activate(scheduleId: string, requestOptions?: ApiRequestOptions): ApiPromise<ScheduleObject>;
882
+ /**
883
+ * Lists schedules
884
+ * @param options - The list options
885
+ * @param options.page - The page number
886
+ * @param options.perPage - The number of schedules per page
887
+ * @returns The list of schedules
888
+ */
889
+ declare function list$1(options?: ListScheduleOptions, requestOptions?: ApiRequestOptions): OffsetLimitPagePromise<typeof ScheduleObject>;
890
+ /**
891
+ * Lists the possible timezones we support
892
+ * @param excludeUtc - By default "UTC" is included and is first. If true, "UTC" will be excluded.
893
+ */
894
+ declare function timezones(options?: {
895
+ excludeUtc?: boolean;
896
+ }): ApiPromise<{
897
+ timezones: string[];
898
+ }>;
236
899
 
237
- declare function onThrow<T>(fn: (options: {
238
- attempt: number;
239
- maxAttempts: number;
240
- }) => Promise<T>, options: RetryOptions): Promise<T>;
241
- interface RetryFetchRequestInit extends RequestInit {
242
- retry?: FetchRetryOptions;
243
- timeoutInMs?: number;
900
+ type index_ScheduleOptions<TIdentifier extends string, TOutput, TInitOutput extends InitOutput> = ScheduleOptions<TIdentifier, TOutput, TInitOutput>;
901
+ declare const index_activate: typeof activate;
902
+ declare const index_deactivate: typeof deactivate;
903
+ declare const index_task: typeof task;
904
+ declare const index_timezones: typeof timezones;
905
+ declare namespace index {
906
+ export { type index_ScheduleOptions as ScheduleOptions, index_activate as activate, create$1 as create, index_deactivate as deactivate, del$1 as del, list$1 as list, retrieve$1 as retrieve, index_task as task, index_timezones as timezones, update$1 as update };
244
907
  }
245
- declare function retryFetch(input: RequestInfo | URL, init?: RetryFetchRequestInit | undefined): Promise<Response>;
246
- declare const retry: {
247
- onThrow: typeof onThrow;
248
- fetch: typeof retryFetch;
249
- interceptFetch: (...handlers: Array<HttpHandler>) => {
250
- run: <T>(fn: (...args: any[]) => Promise<T>) => Promise<T>;
251
- };
252
- };
253
908
 
254
- export { type CacheEntry, type CacheFunction, type CacheMetadata, type CacheStore, type Context, type Eventually, InMemoryCache, type WaitOptions, createCache, retry, task, wait };
909
+ declare function upload(projectRef: string, slug: string, params: ImportEnvironmentVariablesParams, requestOptions?: ApiRequestOptions): ApiPromise<EnvironmentVariableResponseBody>;
910
+ declare function upload(params: ImportEnvironmentVariablesParams, requestOptions?: ApiRequestOptions): ApiPromise<EnvironmentVariableResponseBody>;
911
+ declare function list(projectRef: string, slug: string, requestOptions?: ApiRequestOptions): ApiPromise<EnvironmentVariables>;
912
+ declare function list(requestOptions?: ApiRequestOptions): ApiPromise<EnvironmentVariables>;
913
+ declare function create(projectRef: string, slug: string, params: CreateEnvironmentVariableParams, requestOptions?: ApiRequestOptions): ApiPromise<EnvironmentVariableResponseBody>;
914
+ declare function create(params: CreateEnvironmentVariableParams, requestOptions?: ApiRequestOptions): ApiPromise<EnvironmentVariableResponseBody>;
915
+ declare function retrieve(projectRef: string, slug: string, name: string, requestOptions?: ApiRequestOptions): ApiPromise<EnvironmentVariableValue>;
916
+ declare function retrieve(name: string, requestOptions?: ApiRequestOptions): ApiPromise<EnvironmentVariableValue>;
917
+ declare function del(projectRef: string, slug: string, name: string, requestOptions?: ApiRequestOptions): ApiPromise<EnvironmentVariableResponseBody>;
918
+ declare function del(name: string, requestOptions?: ApiRequestOptions): ApiPromise<EnvironmentVariableResponseBody>;
919
+ declare function update(projectRef: string, slug: string, name: string, params: UpdateEnvironmentVariableParams, requestOptions?: ApiRequestOptions): ApiPromise<EnvironmentVariableResponseBody>;
920
+ declare function update(name: string, params: UpdateEnvironmentVariableParams, requestOptions?: ApiRequestOptions): ApiPromise<EnvironmentVariableResponseBody>;
921
+
922
+ declare const envvars_CreateEnvironmentVariableParams: typeof CreateEnvironmentVariableParams;
923
+ declare const envvars_ImportEnvironmentVariablesParams: typeof ImportEnvironmentVariablesParams;
924
+ declare const envvars_create: typeof create;
925
+ declare const envvars_del: typeof del;
926
+ declare const envvars_list: typeof list;
927
+ declare const envvars_retrieve: typeof retrieve;
928
+ declare const envvars_update: typeof update;
929
+ declare const envvars_upload: typeof upload;
930
+ declare namespace envvars {
931
+ export { envvars_CreateEnvironmentVariableParams as CreateEnvironmentVariableParams, envvars_ImportEnvironmentVariablesParams as ImportEnvironmentVariablesParams, envvars_create as create, envvars_del as del, envvars_list as list, envvars_retrieve as retrieve, envvars_update as update, envvars_upload as upload };
932
+ }
933
+
934
+ /**
935
+ * Register the global API client configuration. Alternatively, you can set the `TRIGGER_SECRET_KEY` and `TRIGGER_API_URL` environment variables.
936
+ * @param options The API client configuration.
937
+ * @param options.baseURL The base URL of the Trigger API. (default: `https://api.trigger.dev`)
938
+ * @param options.secretKey The secret key to authenticate with the Trigger API. (default: `process.env.TRIGGER_SECRET_KEY`) This can be found in your Trigger.dev project "API Keys" settings.
939
+ *
940
+ * @example
941
+ *
942
+ * ```typescript
943
+ * import { configure } from "@trigger.dev/sdk/v3";
944
+ *
945
+ * configure({
946
+ * baseURL: "https://api.trigger.dev",
947
+ * secretKey: "tr_dev_1234567890"
948
+ * });
949
+ * ```
950
+ */
951
+ declare function configure(options: ApiClientConfiguration): void;
952
+
953
+ export { type BatchItem, type BatchResult, type BatchRunHandle, type CacheEntry, type CacheFunction, type CacheMetadata, type CacheStore, type ComputeUsage, type Context, type CurrentUsage, type Eventually, type IdempotencyKey, InMemoryCache, type Queue, type RunHandle, type Task, type TaskIdentifier, type TaskOptions, type TaskOutput, type TaskPayload, type TaskRunOptions, type TaskRunResult, type WaitOptions, configure, createCache, envvars, idempotencyKeys, isIdempotencyKey, queue, retry, runs, index as schedules, task$1 as task, tasks, usage, wait };