"use client"; import { type InferRunTypes, type RunHandleFromTypes, type AnyTask, type TaskIdentifier, type TaskPayload, makeIdempotencyKey, stringifyIO, type TriggerOptions, type RealtimeRunSkipColumns, } from "@trigger.dev/core/v3"; import { triggerConcurrencyKeyBody } from "@trigger.dev/core/v3/isomorphic"; import useSWRMutation from "swr/mutation"; import { type UseApiClientOptions, useApiClient } from "./useApiClient.js"; import { type UseRealtimeRunInstance, type UseRealtimeRunWithStreamsInstance, useRealtimeRun, useRealtimeRunWithStreams, } from "./useRealtime.js"; /** * Base interface for task trigger instances. * * @template TTask - The type of the task */ export interface TriggerInstance { /** Function to submit the task with a payload */ submit: (payload: TaskPayload, options?: TriggerOptions) => void; /** Whether the task is currently being submitted */ isLoading: boolean; /** The handle returned after successful task submission */ handle?: RunHandleFromTypes>; /** Any error that occurred during submission */ error?: Error; } export type UseTaskTriggerOptions = UseApiClientOptions; /** * Hook to trigger a task and manage its initial execution state. * * @template TTask - The type of the task * @param {TaskIdentifier} id - The identifier of the task to trigger * @param {UseTaskTriggerOptions} [options] - Configuration options for the task trigger * @returns {TriggerInstance} An object containing the submit function, loading state, handle, and any errors * * @example * ```ts * import type { myTask } from './path/to/task'; * const { submit, isLoading, handle, error } = useTaskTrigger('my-task-id'); * * // Submit the task with payload * submit({ foo: 'bar' }); * ``` */ export function useTaskTrigger( id: TaskIdentifier, options?: UseTaskTriggerOptions ): TriggerInstance { const apiClient = useApiClient(options); async function triggerTask( id: string, { arg: { payload, options }, }: { arg: { payload: TaskPayload; options?: TriggerOptions } } ) { if (!apiClient) { throw new Error("Could not trigger task in useTaskTrigger: Missing access token"); } const payloadPacket = await stringifyIO(payload); const queueName = options?.queue; const concurrency = options?.concurrency ? Array.isArray(options.concurrency) ? options.concurrency : [options.concurrency] : undefined; if (concurrency && concurrency.length > 2) { throw new Error("The concurrency option accepts at most two named limits."); } const handle = await apiClient.triggerTask(id, { payload: payloadPacket.data, options: { queue: queueName ? { name: queueName } : undefined, concurrency, ...triggerConcurrencyKeyBody(options?.concurrencyKey), payloadType: payloadPacket.dataType, idempotencyKey: await makeIdempotencyKey(options?.idempotencyKey), delay: options?.delay, ttl: options?.ttl, tags: options?.tags, maxAttempts: options?.maxAttempts, metadata: options?.metadata, maxDuration: options?.maxDuration, lockToVersion: options?.version, debounce: options?.debounce, }, }); return { ...handle, taskIdentifier: id }; } const mutation = useSWRMutation(id as string, triggerTask); return { submit: (payload, options) => { // trigger the task with the given payload mutation.trigger({ payload, options }); }, isLoading: mutation.isMutating, handle: mutation.data as RunHandleFromTypes>, error: mutation.error, }; } /** * Configuration options for task triggers with realtime updates. */ export type UseRealtimeTaskTriggerOptions = UseTaskTriggerOptions & { /** Whether the realtime subscription is enabled */ enabled?: boolean; /** Optional throttle time in milliseconds for stream updates */ experimental_throttleInMs?: number; /** * Skip columns from the subscription. * * @default [] */ skipColumns?: RealtimeRunSkipColumns; }; export type RealtimeTriggerInstanceWithStreams< TTask extends AnyTask, TStreams extends Record = Record, > = UseRealtimeRunWithStreamsInstance & { submit: (payload: TaskPayload, options?: TriggerOptions) => void; isLoading: boolean; handle?: RunHandleFromTypes>; }; /** * Hook to trigger a task and subscribe to its realtime updates including stream data. * * @template TTask - The type of the task * @template TStreams - The type of the streams data * @param {TaskIdentifier} id - The identifier of the task to trigger * @param {UseRealtimeTaskTriggerOptions} [options] - Configuration options for the task trigger and realtime updates * @returns {RealtimeTriggerInstanceWithStreams} An object containing the submit function, loading state, * handle, run state, streams data, and error handling * * @example * ```ts * import type { myTask } from './path/to/task'; * const { submit, run, streams, error } = useRealtimeTaskTriggerWithStreams< * typeof myTask, * { output: string } * >('my-task-id'); * * // Submit and monitor the task with streams * submit({ foo: 'bar' }); * ``` */ export function useRealtimeTaskTriggerWithStreams< TTask extends AnyTask, TStreams extends Record = Record, >( id: TaskIdentifier, options?: UseRealtimeTaskTriggerOptions ): RealtimeTriggerInstanceWithStreams { const triggerInstance = useTaskTrigger(id, options); const realtimeInstance = useRealtimeRunWithStreams(triggerInstance.handle?.id, { ...options, id: triggerInstance.handle?.id, accessToken: triggerInstance.handle?.publicAccessToken ?? options?.accessToken, }); return { ...realtimeInstance, ...triggerInstance, }; } export type RealtimeTriggerInstance = UseRealtimeRunInstance & { submit: (payload: TaskPayload, options?: TriggerOptions) => void; isLoading: boolean; handle?: RunHandleFromTypes>; }; /** * Hook to trigger a task and subscribe to its realtime updates. * * @template TTask - The type of the task * @param {TaskIdentifier} id - The identifier of the task to trigger * @param {UseRealtimeTaskTriggerOptions} [options] - Configuration options for the task trigger and realtime updates * @returns {RealtimeTriggerInstance} An object containing the submit function, loading state, * handle, run state, and error handling * * @example * ```ts * import type { myTask } from './path/to/task'; * const { submit, run, error, stop } = useRealtimeTaskTrigger('my-task-id'); * * // Submit and monitor the task * submit({ foo: 'bar' }); * * // Stop monitoring when needed * stop(); * ``` */ export function useRealtimeTaskTrigger( id: TaskIdentifier, options?: UseRealtimeTaskTriggerOptions ): RealtimeTriggerInstance { const triggerInstance = useTaskTrigger(id, options); const realtimeInstance = useRealtimeRun(triggerInstance.handle?.id, { ...options, id: triggerInstance.handle?.id, accessToken: triggerInstance.handle?.publicAccessToken ?? options?.accessToken, }); return { submit: triggerInstance.submit, isLoading: triggerInstance.isLoading, handle: triggerInstance.handle, run: realtimeInstance.run, error: realtimeInstance.error ?? triggerInstance.error, stop: realtimeInstance.stop, }; }