@trigger.dev/react-hooks 0.0.0-v3-prerelease-20241118124944 → 0.0.0-v3-prerelease-20250108131948

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/commonjs/contexts.d.ts +2 -2
  2. package/dist/commonjs/contexts.js +3 -2
  3. package/dist/commonjs/contexts.js.map +1 -1
  4. package/dist/commonjs/hooks/useApiClient.d.ts +39 -2
  5. package/dist/commonjs/hooks/useApiClient.js +34 -6
  6. package/dist/commonjs/hooks/useApiClient.js.map +1 -1
  7. package/dist/commonjs/hooks/useRealtime.d.ts +117 -0
  8. package/dist/commonjs/hooks/useRealtime.js +409 -0
  9. package/dist/commonjs/hooks/useRealtime.js.map +1 -0
  10. package/dist/commonjs/hooks/useRun.js +7 -2
  11. package/dist/commonjs/hooks/useRun.js.map +1 -1
  12. package/dist/commonjs/hooks/useTaskTrigger.d.ts +101 -0
  13. package/dist/commonjs/hooks/useTaskTrigger.js +137 -0
  14. package/dist/commonjs/hooks/useTaskTrigger.js.map +1 -0
  15. package/dist/commonjs/index.d.ts +2 -3
  16. package/dist/commonjs/index.js +2 -3
  17. package/dist/commonjs/index.js.map +1 -1
  18. package/dist/commonjs/utils/throttle.d.ts +6 -0
  19. package/dist/commonjs/utils/throttle.js +50 -0
  20. package/dist/commonjs/utils/throttle.js.map +1 -0
  21. package/dist/commonjs/utils/trigger-swr.d.ts +12 -0
  22. package/dist/commonjs/utils/trigger-swr.js.map +1 -1
  23. package/dist/esm/contexts.d.ts +2 -2
  24. package/dist/esm/contexts.js +2 -2
  25. package/dist/esm/contexts.js.map +1 -1
  26. package/dist/esm/hooks/useApiClient.d.ts +39 -2
  27. package/dist/esm/hooks/useApiClient.js +35 -7
  28. package/dist/esm/hooks/useApiClient.js.map +1 -1
  29. package/dist/esm/hooks/useRealtime.d.ts +117 -0
  30. package/dist/esm/hooks/useRealtime.js +403 -0
  31. package/dist/esm/hooks/useRealtime.js.map +1 -0
  32. package/dist/esm/hooks/useRun.js +7 -2
  33. package/dist/esm/hooks/useRun.js.map +1 -1
  34. package/dist/esm/hooks/useTaskTrigger.d.ts +101 -0
  35. package/dist/esm/hooks/useTaskTrigger.js +129 -0
  36. package/dist/esm/hooks/useTaskTrigger.js.map +1 -0
  37. package/dist/esm/index.d.ts +2 -3
  38. package/dist/esm/index.js +2 -3
  39. package/dist/esm/index.js.map +1 -1
  40. package/dist/esm/utils/throttle.d.ts +6 -0
  41. package/dist/esm/utils/throttle.js +47 -0
  42. package/dist/esm/utils/throttle.js.map +1 -0
  43. package/dist/esm/utils/trigger-swr.d.ts +12 -0
  44. package/dist/esm/utils/trigger-swr.js.map +1 -1
  45. package/package.json +4 -4
  46. package/dist/commonjs/hooks/useRealtimeBatch.d.ts +0 -19
  47. package/dist/commonjs/hooks/useRealtimeBatch.js +0 -56
  48. package/dist/commonjs/hooks/useRealtimeBatch.js.map +0 -1
  49. package/dist/commonjs/hooks/useRealtimeRun.d.ts +0 -18
  50. package/dist/commonjs/hooks/useRealtimeRun.js +0 -40
  51. package/dist/commonjs/hooks/useRealtimeRun.js.map +0 -1
  52. package/dist/commonjs/hooks/useRealtimeRunsWithTag.d.ts +0 -5
  53. package/dist/commonjs/hooks/useRealtimeRunsWithTag.js +0 -45
  54. package/dist/commonjs/hooks/useRealtimeRunsWithTag.js.map +0 -1
  55. package/dist/esm/hooks/useRealtimeBatch.d.ts +0 -19
  56. package/dist/esm/hooks/useRealtimeBatch.js +0 -53
  57. package/dist/esm/hooks/useRealtimeBatch.js.map +0 -1
  58. package/dist/esm/hooks/useRealtimeRun.d.ts +0 -18
  59. package/dist/esm/hooks/useRealtimeRun.js +0 -37
  60. package/dist/esm/hooks/useRealtimeRun.js.map +0 -1
  61. package/dist/esm/hooks/useRealtimeRunsWithTag.d.ts +0 -5
  62. package/dist/esm/hooks/useRealtimeRunsWithTag.js +0 -42
  63. package/dist/esm/hooks/useRealtimeRunsWithTag.js.map +0 -1
@@ -1,4 +1,4 @@
1
1
  import React from "react";
2
2
  import type { ApiClientConfiguration } from "@trigger.dev/core/v3";
3
- declare const TriggerAuthContext: React.Context<ApiClientConfiguration | undefined>, useTriggerAuthContext: () => ApiClientConfiguration;
4
- export { TriggerAuthContext, useTriggerAuthContext };
3
+ declare const TriggerAuthContext: React.Context<ApiClientConfiguration | undefined>, useTriggerAuthContext: () => ApiClientConfiguration, useTriggerAuthContextOptional: () => ApiClientConfiguration | Partial<ApiClientConfiguration>;
4
+ export { TriggerAuthContext, useTriggerAuthContext, useTriggerAuthContextOptional };
@@ -1,9 +1,10 @@
1
1
  "use client";
2
2
  "use strict";
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.useTriggerAuthContext = exports.TriggerAuthContext = void 0;
4
+ exports.useTriggerAuthContextOptional = exports.useTriggerAuthContext = exports.TriggerAuthContext = void 0;
5
5
  const createContextAndHook_js_1 = require("./utils/createContextAndHook.js");
6
- const [TriggerAuthContext, useTriggerAuthContext] = (0, createContextAndHook_js_1.createContextAndHook)("TriggerAuthContext");
6
+ const [TriggerAuthContext, useTriggerAuthContext, useTriggerAuthContextOptional] = (0, createContextAndHook_js_1.createContextAndHook)("TriggerAuthContext");
7
7
  exports.TriggerAuthContext = TriggerAuthContext;
8
8
  exports.useTriggerAuthContext = useTriggerAuthContext;
9
+ exports.useTriggerAuthContextOptional = useTriggerAuthContextOptional;
9
10
  //# sourceMappingURL=contexts.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"contexts.js","sourceRoot":"","sources":["../../src/contexts.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;;;AAGb,6EAAuE;AAGvE,MAAM,CAAC,kBAAkB,EAAE,qBAAqB,CAAC,GAC/C,IAAA,8CAAoB,EAAyB,oBAAoB,CAAC,CAAC;AAE5D,gDAAkB;AAAE,sDAAqB"}
1
+ {"version":3,"file":"contexts.js","sourceRoot":"","sources":["../../src/contexts.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;;;AAGb,6EAAuE;AAGvE,MAAM,CAAC,kBAAkB,EAAE,qBAAqB,EAAE,6BAA6B,CAAC,GAC9E,IAAA,8CAAoB,EAAyB,oBAAoB,CAAC,CAAC;AAE5D,gDAAkB;AAAE,sDAAqB;AAAE,sEAA6B"}
@@ -1,2 +1,39 @@
1
- import { ApiClient } from "@trigger.dev/core/v3";
2
- export declare function useApiClient(): ApiClient;
1
+ import { ApiClient, ApiRequestOptions } from "@trigger.dev/core/v3";
2
+ /**
3
+ * Configuration options for creating an API client instance.
4
+ */
5
+ export type UseApiClientOptions = {
6
+ /** Optional access token for authentication */
7
+ accessToken?: string;
8
+ /** Optional base URL for the API endpoints */
9
+ baseURL?: string;
10
+ /** Optional additional request configuration */
11
+ requestOptions?: ApiRequestOptions;
12
+ /**
13
+ * Enable or disable the API client instance.
14
+ *
15
+ * Set enabled to false if you don't have an accessToken and don't want to throw an error.
16
+ */
17
+ enabled?: boolean;
18
+ };
19
+ /**
20
+ * Hook to create an API client instance using authentication context or provided options.
21
+ *
22
+ * @param {UseApiClientOptions} [options] - Configuration options for the API client
23
+ * @returns {ApiClient} An initialized API client instance
24
+ * @throws {Error} When no access token is available in either context or options
25
+ *
26
+ * @example
27
+ * ```ts
28
+ * // Using context authentication
29
+ * const apiClient = useApiClient();
30
+ *
31
+ * // Using custom options
32
+ * const apiClient = useApiClient({
33
+ * accessToken: "your-access-token",
34
+ * baseURL: "https://api.my-trigger.com",
35
+ * requestOptions: { retry: { maxAttempts: 10 } }
36
+ * });
37
+ * ```
38
+ */
39
+ export declare function useApiClient(options?: UseApiClientOptions): ApiClient | undefined;
@@ -4,12 +4,40 @@ Object.defineProperty(exports, "__esModule", { value: true });
4
4
  exports.useApiClient = useApiClient;
5
5
  const v3_1 = require("@trigger.dev/core/v3");
6
6
  const contexts_js_1 = require("../contexts.js");
7
- function useApiClient() {
8
- const auth = (0, contexts_js_1.useTriggerAuthContext)();
9
- const baseUrl = auth.baseURL ?? "https://api.trigger.dev";
10
- if (!auth.accessToken) {
11
- throw new Error("Missing accessToken in TriggerAuthContext");
7
+ /**
8
+ * Hook to create an API client instance using authentication context or provided options.
9
+ *
10
+ * @param {UseApiClientOptions} [options] - Configuration options for the API client
11
+ * @returns {ApiClient} An initialized API client instance
12
+ * @throws {Error} When no access token is available in either context or options
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * // Using context authentication
17
+ * const apiClient = useApiClient();
18
+ *
19
+ * // Using custom options
20
+ * const apiClient = useApiClient({
21
+ * accessToken: "your-access-token",
22
+ * baseURL: "https://api.my-trigger.com",
23
+ * requestOptions: { retry: { maxAttempts: 10 } }
24
+ * });
25
+ * ```
26
+ */
27
+ function useApiClient(options) {
28
+ const auth = (0, contexts_js_1.useTriggerAuthContextOptional)();
29
+ const baseUrl = options?.baseURL ?? auth?.baseURL ?? "https://api.trigger.dev";
30
+ const accessToken = options?.accessToken ?? auth?.accessToken;
31
+ if (!accessToken) {
32
+ if (options?.enabled === false) {
33
+ return undefined;
34
+ }
35
+ throw new Error("Missing accessToken in TriggerAuthContext or useApiClient options");
12
36
  }
13
- return new v3_1.ApiClient(baseUrl, auth.accessToken, auth.requestOptions);
37
+ const requestOptions = {
38
+ ...auth?.requestOptions,
39
+ ...options?.requestOptions,
40
+ };
41
+ return new v3_1.ApiClient(baseUrl, accessToken, requestOptions);
14
42
  }
15
43
  //# sourceMappingURL=useApiClient.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useApiClient.js","sourceRoot":"","sources":["../../../src/hooks/useApiClient.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;;;AAKb,oCAUC;AAbD,6CAAiD;AACjD,gDAAuD;AAEvD,SAAgB,YAAY;IAC1B,MAAM,IAAI,GAAG,IAAA,mCAAqB,GAAE,CAAC;IAErC,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,IAAI,yBAAyB,CAAC;IAE1D,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC;QACtB,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;IAC/D,CAAC;IAED,OAAO,IAAI,cAAS,CAAC,OAAO,EAAE,IAAI,CAAC,WAAW,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC;AACvE,CAAC"}
1
+ {"version":3,"file":"useApiClient.js","sourceRoot":"","sources":["../../../src/hooks/useApiClient.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;;;AA4Cb,oCAoBC;AA9DD,6CAAoE;AACpE,gDAA+D;AAqB/D;;;;;;;;;;;;;;;;;;;GAmBG;AACH,SAAgB,YAAY,CAAC,OAA6B;IACxD,MAAM,IAAI,GAAG,IAAA,2CAA6B,GAAE,CAAC;IAE7C,MAAM,OAAO,GAAG,OAAO,EAAE,OAAO,IAAI,IAAI,EAAE,OAAO,IAAI,yBAAyB,CAAC;IAC/E,MAAM,WAAW,GAAG,OAAO,EAAE,WAAW,IAAI,IAAI,EAAE,WAAW,CAAC;IAE9D,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,IAAI,OAAO,EAAE,OAAO,KAAK,KAAK,EAAE,CAAC;YAC/B,OAAO,SAAS,CAAC;QACnB,CAAC;QAED,MAAM,IAAI,KAAK,CAAC,mEAAmE,CAAC,CAAC;IACvF,CAAC;IAED,MAAM,cAAc,GAAsB;QACxC,GAAG,IAAI,EAAE,cAAc;QACvB,GAAG,OAAO,EAAE,cAAc;KAC3B,CAAC;IAEF,OAAO,IAAI,cAAS,CAAC,OAAO,EAAE,WAAW,EAAE,cAAc,CAAC,CAAC;AAC7D,CAAC"}
@@ -0,0 +1,117 @@
1
+ import { AnyTask, RealtimeRun } from "@trigger.dev/core/v3";
2
+ import { UseApiClientOptions } from "./useApiClient.js";
3
+ export type UseRealtimeRunOptions = UseApiClientOptions & {
4
+ id?: string;
5
+ enabled?: boolean;
6
+ experimental_throttleInMs?: number;
7
+ };
8
+ export type UseRealtimeSingleRunOptions<TTask extends AnyTask = AnyTask> = UseRealtimeRunOptions & {
9
+ /**
10
+ * Callback this is called when the run completes, an error occurs, or the subscription is stopped.
11
+ *
12
+ * @param {RealtimeRun<TTask>} run - The run object
13
+ * @param {Error} [err] - The error that occurred
14
+ */
15
+ onComplete?: (run: RealtimeRun<TTask>, err?: Error) => void;
16
+ /**
17
+ * Whether to stop the subscription when the run completes
18
+ *
19
+ * @default true
20
+ *
21
+ * Set this to false if you are making updates to the run metadata after completion through child runs
22
+ */
23
+ stopOnCompletion?: boolean;
24
+ };
25
+ export type UseRealtimeRunInstance<TTask extends AnyTask = AnyTask> = {
26
+ run: RealtimeRun<TTask> | undefined;
27
+ error: Error | undefined;
28
+ /**
29
+ * Abort the current request immediately.
30
+ */
31
+ stop: () => void;
32
+ };
33
+ /**
34
+ * Hook to subscribe to realtime updates of a task run.
35
+ *
36
+ * @template TTask - The type of the task
37
+ * @param {string} [runId] - The unique identifier of the run to subscribe to
38
+ * @param {UseRealtimeSingleRunOptions} [options] - Configuration options for the subscription
39
+ * @returns {UseRealtimeRunInstance<TTask>} An object containing the current state of the run, error handling, and control methods
40
+ *
41
+ * @example
42
+ * ```ts
43
+ * import type { myTask } from './path/to/task';
44
+ * const { run, error } = useRealtimeRun<typeof myTask>('run-id-123');
45
+ * ```
46
+ */
47
+ export declare function useRealtimeRun<TTask extends AnyTask>(runId?: string, options?: UseRealtimeSingleRunOptions<TTask>): UseRealtimeRunInstance<TTask>;
48
+ export type StreamResults<TStreams extends Record<string, any>> = {
49
+ [K in keyof TStreams]: Array<TStreams[K]>;
50
+ };
51
+ export type UseRealtimeRunWithStreamsInstance<TTask extends AnyTask = AnyTask, TStreams extends Record<string, any> = Record<string, any>> = {
52
+ run: RealtimeRun<TTask> | undefined;
53
+ streams: StreamResults<TStreams>;
54
+ error: Error | undefined;
55
+ /**
56
+ * Abort the current request immediately, keep the generated tokens if any.
57
+ */
58
+ stop: () => void;
59
+ };
60
+ /**
61
+ * Hook to subscribe to realtime updates of a task run with associated data streams.
62
+ *
63
+ * @template TTask - The type of the task
64
+ * @template TStreams - The type of the streams data
65
+ * @param {string} [runId] - The unique identifier of the run to subscribe to
66
+ * @param {UseRealtimeRunOptions} [options] - Configuration options for the subscription
67
+ * @returns {UseRealtimeRunWithStreamsInstance<TTask, TStreams>} An object containing the current state of the run, streams data, and error handling
68
+ *
69
+ * @example
70
+ * ```ts
71
+ * import type { myTask } from './path/to/task';
72
+ * const { run, streams, error } = useRealtimeRunWithStreams<typeof myTask, {
73
+ * output: string;
74
+ * }>('run-id-123');
75
+ * ```
76
+ */
77
+ export declare function useRealtimeRunWithStreams<TTask extends AnyTask = AnyTask, TStreams extends Record<string, any> = Record<string, any>>(runId?: string, options?: UseRealtimeSingleRunOptions<TTask>): UseRealtimeRunWithStreamsInstance<TTask, TStreams>;
78
+ export type UseRealtimeRunsInstance<TTask extends AnyTask = AnyTask> = {
79
+ runs: RealtimeRun<TTask>[];
80
+ error: Error | undefined;
81
+ /**
82
+ * Abort the current request immediately.
83
+ */
84
+ stop: () => void;
85
+ };
86
+ /**
87
+ * Hook to subscribe to realtime updates of task runs filtered by tag(s).
88
+ *
89
+ * @template TTask - The type of the task
90
+ * @param {string | string[]} tag - The tag or array of tags to filter runs by
91
+ * @param {UseRealtimeRunOptions} [options] - Configuration options for the subscription
92
+ * @returns {UseRealtimeRunsInstance<TTask>} An object containing the current state of the runs and any error encountered
93
+ *
94
+ * @example
95
+ * ```ts
96
+ * import type { myTask } from './path/to/task';
97
+ * const { runs, error } = useRealtimeRunsWithTag<typeof myTask>('my-tag');
98
+ * // Or with multiple tags
99
+ * const { runs, error } = useRealtimeRunsWithTag<typeof myTask>(['tag1', 'tag2']);
100
+ * ```
101
+ */
102
+ export declare function useRealtimeRunsWithTag<TTask extends AnyTask>(tag: string | string[], options?: UseRealtimeRunOptions): UseRealtimeRunsInstance<TTask>;
103
+ /**
104
+ * Hook to subscribe to realtime updates of a batch of task runs.
105
+ *
106
+ * @template TTask - The type of the task
107
+ * @param {string} batchId - The unique identifier of the batch to subscribe to
108
+ * @param {UseRealtimeRunOptions} [options] - Configuration options for the subscription
109
+ * @returns {UseRealtimeRunsInstance<TTask>} An object containing the current state of the runs, error handling, and control methods
110
+ *
111
+ * @example
112
+ * ```ts
113
+ * import type { myTask } from './path/to/task';
114
+ * const { runs, error } = useRealtimeBatch<typeof myTask>('batch-id-123');
115
+ * ```
116
+ */
117
+ export declare function useRealtimeBatch<TTask extends AnyTask>(batchId: string, options?: UseRealtimeRunOptions): UseRealtimeRunsInstance<TTask>;
@@ -0,0 +1,409 @@
1
+ "use client";
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.useRealtimeRun = useRealtimeRun;
5
+ exports.useRealtimeRunWithStreams = useRealtimeRunWithStreams;
6
+ exports.useRealtimeRunsWithTag = useRealtimeRunsWithTag;
7
+ exports.useRealtimeBatch = useRealtimeBatch;
8
+ const react_1 = require("react");
9
+ const trigger_swr_js_1 = require("../utils/trigger-swr.js");
10
+ const useApiClient_js_1 = require("./useApiClient.js");
11
+ const throttle_js_1 = require("../utils/throttle.js");
12
+ /**
13
+ * Hook to subscribe to realtime updates of a task run.
14
+ *
15
+ * @template TTask - The type of the task
16
+ * @param {string} [runId] - The unique identifier of the run to subscribe to
17
+ * @param {UseRealtimeSingleRunOptions} [options] - Configuration options for the subscription
18
+ * @returns {UseRealtimeRunInstance<TTask>} An object containing the current state of the run, error handling, and control methods
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * import type { myTask } from './path/to/task';
23
+ * const { run, error } = useRealtimeRun<typeof myTask>('run-id-123');
24
+ * ```
25
+ */
26
+ function useRealtimeRun(runId, options) {
27
+ const hookId = (0, react_1.useId)();
28
+ const idKey = options?.id ?? hookId;
29
+ // Store the streams state in SWR, using the idKey as the key to share states.
30
+ const { data: run, mutate: mutateRun } = (0, trigger_swr_js_1.useSWR)([idKey, "run"], null);
31
+ const { data: error = undefined, mutate: setError } = (0, trigger_swr_js_1.useSWR)([idKey, "error"], null);
32
+ // Add state to track when the subscription is complete
33
+ const { data: isComplete = false, mutate: setIsComplete } = (0, trigger_swr_js_1.useSWR)([idKey, "complete"], null);
34
+ // Abort controller to cancel the current API call.
35
+ const abortControllerRef = (0, react_1.useRef)(null);
36
+ const stop = (0, react_1.useCallback)(() => {
37
+ if (abortControllerRef.current) {
38
+ abortControllerRef.current.abort();
39
+ abortControllerRef.current = null;
40
+ }
41
+ }, []);
42
+ const apiClient = (0, useApiClient_js_1.useApiClient)(options);
43
+ const triggerRequest = (0, react_1.useCallback)(async () => {
44
+ try {
45
+ if (!runId || !apiClient) {
46
+ return;
47
+ }
48
+ const abortController = new AbortController();
49
+ abortControllerRef.current = abortController;
50
+ await processRealtimeRun(runId, apiClient, mutateRun, abortControllerRef, typeof options?.stopOnCompletion === "boolean" ? options.stopOnCompletion : true);
51
+ }
52
+ catch (err) {
53
+ // Ignore abort errors as they are expected.
54
+ if (err.name === "AbortError") {
55
+ abortControllerRef.current = null;
56
+ return;
57
+ }
58
+ setError(err);
59
+ }
60
+ finally {
61
+ if (abortControllerRef.current) {
62
+ abortControllerRef.current = null;
63
+ }
64
+ // Mark the subscription as complete
65
+ setIsComplete(true);
66
+ }
67
+ }, [runId, mutateRun, abortControllerRef, apiClient, setError]);
68
+ const hasCalledOnCompleteRef = (0, react_1.useRef)(false);
69
+ // Effect to handle onComplete callback
70
+ (0, react_1.useEffect)(() => {
71
+ if (isComplete && run && options?.onComplete && !hasCalledOnCompleteRef.current) {
72
+ options.onComplete(run, error);
73
+ hasCalledOnCompleteRef.current = true;
74
+ }
75
+ }, [isComplete, run, error, options?.onComplete]);
76
+ (0, react_1.useEffect)(() => {
77
+ if (typeof options?.enabled === "boolean" && !options.enabled) {
78
+ return;
79
+ }
80
+ if (!runId) {
81
+ return;
82
+ }
83
+ triggerRequest().finally(() => { });
84
+ return () => {
85
+ stop();
86
+ };
87
+ }, [runId, stop, options?.enabled]);
88
+ return { run, error, stop };
89
+ }
90
+ /**
91
+ * Hook to subscribe to realtime updates of a task run with associated data streams.
92
+ *
93
+ * @template TTask - The type of the task
94
+ * @template TStreams - The type of the streams data
95
+ * @param {string} [runId] - The unique identifier of the run to subscribe to
96
+ * @param {UseRealtimeRunOptions} [options] - Configuration options for the subscription
97
+ * @returns {UseRealtimeRunWithStreamsInstance<TTask, TStreams>} An object containing the current state of the run, streams data, and error handling
98
+ *
99
+ * @example
100
+ * ```ts
101
+ * import type { myTask } from './path/to/task';
102
+ * const { run, streams, error } = useRealtimeRunWithStreams<typeof myTask, {
103
+ * output: string;
104
+ * }>('run-id-123');
105
+ * ```
106
+ */
107
+ function useRealtimeRunWithStreams(runId, options) {
108
+ const hookId = (0, react_1.useId)();
109
+ const idKey = options?.id ?? hookId;
110
+ const [initialStreamsFallback] = (0, react_1.useState)({});
111
+ // Store the streams state in SWR, using the idKey as the key to share states.
112
+ const { data: streams, mutate: mutateStreams } = (0, trigger_swr_js_1.useSWR)([idKey, "streams"], null, {
113
+ fallbackData: initialStreamsFallback,
114
+ });
115
+ // Keep the latest streams in a ref.
116
+ const streamsRef = (0, react_1.useRef)(streams ?? {});
117
+ (0, react_1.useEffect)(() => {
118
+ streamsRef.current = streams || {};
119
+ }, [streams]);
120
+ // Store the streams state in SWR, using the idKey as the key to share states.
121
+ const { data: run, mutate: mutateRun } = (0, trigger_swr_js_1.useSWR)([idKey, "run"], null);
122
+ // Add state to track when the subscription is complete
123
+ const { data: isComplete = false, mutate: setIsComplete } = (0, trigger_swr_js_1.useSWR)([idKey, "complete"], null);
124
+ const { data: error = undefined, mutate: setError } = (0, trigger_swr_js_1.useSWR)([idKey, "error"], null);
125
+ // Abort controller to cancel the current API call.
126
+ const abortControllerRef = (0, react_1.useRef)(null);
127
+ const stop = (0, react_1.useCallback)(() => {
128
+ if (abortControllerRef.current) {
129
+ abortControllerRef.current.abort();
130
+ abortControllerRef.current = null;
131
+ }
132
+ }, []);
133
+ const apiClient = (0, useApiClient_js_1.useApiClient)(options);
134
+ const triggerRequest = (0, react_1.useCallback)(async () => {
135
+ try {
136
+ if (!runId || !apiClient) {
137
+ return;
138
+ }
139
+ const abortController = new AbortController();
140
+ abortControllerRef.current = abortController;
141
+ await processRealtimeRunWithStreams(runId, apiClient, mutateRun, mutateStreams, streamsRef, abortControllerRef, typeof options?.stopOnCompletion === "boolean" ? options.stopOnCompletion : true, options?.experimental_throttleInMs);
142
+ }
143
+ catch (err) {
144
+ // Ignore abort errors as they are expected.
145
+ if (err.name === "AbortError") {
146
+ abortControllerRef.current = null;
147
+ return;
148
+ }
149
+ setError(err);
150
+ }
151
+ finally {
152
+ if (abortControllerRef.current) {
153
+ abortControllerRef.current = null;
154
+ }
155
+ // Mark the subscription as complete
156
+ setIsComplete(true);
157
+ }
158
+ }, [runId, mutateRun, mutateStreams, streamsRef, abortControllerRef, apiClient, setError]);
159
+ const hasCalledOnCompleteRef = (0, react_1.useRef)(false);
160
+ // Effect to handle onComplete callback
161
+ (0, react_1.useEffect)(() => {
162
+ if (isComplete && run && options?.onComplete && !hasCalledOnCompleteRef.current) {
163
+ options.onComplete(run, error);
164
+ hasCalledOnCompleteRef.current = true;
165
+ }
166
+ }, [isComplete, run, error, options?.onComplete]);
167
+ (0, react_1.useEffect)(() => {
168
+ if (typeof options?.enabled === "boolean" && !options.enabled) {
169
+ return;
170
+ }
171
+ if (!runId) {
172
+ return;
173
+ }
174
+ triggerRequest().finally(() => { });
175
+ return () => {
176
+ stop();
177
+ };
178
+ }, [runId, stop, options?.enabled]);
179
+ return { run, streams: streams ?? initialStreamsFallback, error, stop };
180
+ }
181
+ /**
182
+ * Hook to subscribe to realtime updates of task runs filtered by tag(s).
183
+ *
184
+ * @template TTask - The type of the task
185
+ * @param {string | string[]} tag - The tag or array of tags to filter runs by
186
+ * @param {UseRealtimeRunOptions} [options] - Configuration options for the subscription
187
+ * @returns {UseRealtimeRunsInstance<TTask>} An object containing the current state of the runs and any error encountered
188
+ *
189
+ * @example
190
+ * ```ts
191
+ * import type { myTask } from './path/to/task';
192
+ * const { runs, error } = useRealtimeRunsWithTag<typeof myTask>('my-tag');
193
+ * // Or with multiple tags
194
+ * const { runs, error } = useRealtimeRunsWithTag<typeof myTask>(['tag1', 'tag2']);
195
+ * ```
196
+ */
197
+ function useRealtimeRunsWithTag(tag, options) {
198
+ const hookId = (0, react_1.useId)();
199
+ const idKey = options?.id ?? hookId;
200
+ // Store the streams state in SWR, using the idKey as the key to share states.
201
+ const { data: runs, mutate: mutateRuns } = (0, trigger_swr_js_1.useSWR)([idKey, "run"], null, {
202
+ fallbackData: [],
203
+ });
204
+ // Keep the latest streams in a ref.
205
+ const runsRef = (0, react_1.useRef)([]);
206
+ (0, react_1.useEffect)(() => {
207
+ runsRef.current = runs ?? [];
208
+ }, [runs]);
209
+ const { data: error = undefined, mutate: setError } = (0, trigger_swr_js_1.useSWR)([idKey, "error"], null);
210
+ // Abort controller to cancel the current API call.
211
+ const abortControllerRef = (0, react_1.useRef)(null);
212
+ const stop = (0, react_1.useCallback)(() => {
213
+ if (abortControllerRef.current) {
214
+ abortControllerRef.current.abort();
215
+ abortControllerRef.current = null;
216
+ }
217
+ }, []);
218
+ const apiClient = (0, useApiClient_js_1.useApiClient)(options);
219
+ const triggerRequest = (0, react_1.useCallback)(async () => {
220
+ try {
221
+ if (!apiClient) {
222
+ return;
223
+ }
224
+ const abortController = new AbortController();
225
+ abortControllerRef.current = abortController;
226
+ await processRealtimeRunsWithTag(tag, apiClient, mutateRuns, runsRef, abortControllerRef);
227
+ }
228
+ catch (err) {
229
+ // Ignore abort errors as they are expected.
230
+ if (err.name === "AbortError") {
231
+ abortControllerRef.current = null;
232
+ return;
233
+ }
234
+ setError(err);
235
+ }
236
+ finally {
237
+ if (abortControllerRef.current) {
238
+ abortControllerRef.current = null;
239
+ }
240
+ }
241
+ }, [tag, mutateRuns, runsRef, abortControllerRef, apiClient, setError]);
242
+ (0, react_1.useEffect)(() => {
243
+ if (typeof options?.enabled === "boolean" && !options.enabled) {
244
+ return;
245
+ }
246
+ triggerRequest().finally(() => { });
247
+ return () => {
248
+ stop();
249
+ };
250
+ }, [tag, stop, options?.enabled]);
251
+ return { runs: runs ?? [], error, stop };
252
+ }
253
+ /**
254
+ * Hook to subscribe to realtime updates of a batch of task runs.
255
+ *
256
+ * @template TTask - The type of the task
257
+ * @param {string} batchId - The unique identifier of the batch to subscribe to
258
+ * @param {UseRealtimeRunOptions} [options] - Configuration options for the subscription
259
+ * @returns {UseRealtimeRunsInstance<TTask>} An object containing the current state of the runs, error handling, and control methods
260
+ *
261
+ * @example
262
+ * ```ts
263
+ * import type { myTask } from './path/to/task';
264
+ * const { runs, error } = useRealtimeBatch<typeof myTask>('batch-id-123');
265
+ * ```
266
+ */
267
+ function useRealtimeBatch(batchId, options) {
268
+ const hookId = (0, react_1.useId)();
269
+ const idKey = options?.id ?? hookId;
270
+ // Store the streams state in SWR, using the idKey as the key to share states.
271
+ const { data: runs, mutate: mutateRuns } = (0, trigger_swr_js_1.useSWR)([idKey, "run"], null, {
272
+ fallbackData: [],
273
+ });
274
+ // Keep the latest streams in a ref.
275
+ const runsRef = (0, react_1.useRef)([]);
276
+ (0, react_1.useEffect)(() => {
277
+ runsRef.current = runs ?? [];
278
+ }, [runs]);
279
+ const { data: error = undefined, mutate: setError } = (0, trigger_swr_js_1.useSWR)([idKey, "error"], null);
280
+ // Abort controller to cancel the current API call.
281
+ const abortControllerRef = (0, react_1.useRef)(null);
282
+ const stop = (0, react_1.useCallback)(() => {
283
+ if (abortControllerRef.current) {
284
+ abortControllerRef.current.abort();
285
+ abortControllerRef.current = null;
286
+ }
287
+ }, []);
288
+ const apiClient = (0, useApiClient_js_1.useApiClient)(options);
289
+ const triggerRequest = (0, react_1.useCallback)(async () => {
290
+ try {
291
+ if (!apiClient) {
292
+ return;
293
+ }
294
+ const abortController = new AbortController();
295
+ abortControllerRef.current = abortController;
296
+ await processRealtimeBatch(batchId, apiClient, mutateRuns, runsRef, abortControllerRef);
297
+ }
298
+ catch (err) {
299
+ // Ignore abort errors as they are expected.
300
+ if (err.name === "AbortError") {
301
+ abortControllerRef.current = null;
302
+ return;
303
+ }
304
+ setError(err);
305
+ }
306
+ finally {
307
+ if (abortControllerRef.current) {
308
+ abortControllerRef.current = null;
309
+ }
310
+ }
311
+ }, [batchId, mutateRuns, runsRef, abortControllerRef, apiClient, setError]);
312
+ (0, react_1.useEffect)(() => {
313
+ if (typeof options?.enabled === "boolean" && !options.enabled) {
314
+ return;
315
+ }
316
+ triggerRequest().finally(() => { });
317
+ return () => {
318
+ stop();
319
+ };
320
+ }, [batchId, stop, options?.enabled]);
321
+ return { runs: runs ?? [], error, stop };
322
+ }
323
+ async function processRealtimeBatch(batchId, apiClient, mutateRunsData, existingRunsRef, abortControllerRef) {
324
+ const subscription = apiClient.subscribeToBatch(batchId, {
325
+ signal: abortControllerRef.current?.signal,
326
+ });
327
+ for await (const part of subscription) {
328
+ mutateRunsData(insertRunShapeInOrder(existingRunsRef.current, part));
329
+ }
330
+ }
331
+ // Inserts and then orders by the run number, and ensures that the run is not duplicated
332
+ function insertRunShapeInOrder(previousRuns, run) {
333
+ const existingRun = previousRuns.find((r) => r.id === run.id);
334
+ if (existingRun) {
335
+ return previousRuns.map((r) => (r.id === run.id ? run : r));
336
+ }
337
+ const runNumber = run.number;
338
+ const index = previousRuns.findIndex((r) => r.number > runNumber);
339
+ if (index === -1) {
340
+ return [...previousRuns, run];
341
+ }
342
+ return [...previousRuns.slice(0, index), run, ...previousRuns.slice(index)];
343
+ }
344
+ async function processRealtimeRunsWithTag(tag, apiClient, mutateRunsData, existingRunsRef, abortControllerRef) {
345
+ const subscription = apiClient.subscribeToRunsWithTag(tag, {
346
+ signal: abortControllerRef.current?.signal,
347
+ });
348
+ for await (const part of subscription) {
349
+ mutateRunsData(insertRunShape(existingRunsRef.current, part));
350
+ }
351
+ }
352
+ // Replaces or inserts a run shape, ordered by the createdAt timestamp
353
+ function insertRunShape(previousRuns, run) {
354
+ const existingRun = previousRuns.find((r) => r.id === run.id);
355
+ if (existingRun) {
356
+ return previousRuns.map((r) => (r.id === run.id ? run : r));
357
+ }
358
+ const createdAt = run.createdAt;
359
+ const index = previousRuns.findIndex((r) => r.createdAt > createdAt);
360
+ if (index === -1) {
361
+ return [...previousRuns, run];
362
+ }
363
+ return [...previousRuns.slice(0, index), run, ...previousRuns.slice(index)];
364
+ }
365
+ async function processRealtimeRunWithStreams(runId, apiClient, mutateRunData, mutateStreamData, existingDataRef, abortControllerRef, stopOnCompletion = true, throttleInMs) {
366
+ const subscription = apiClient.subscribeToRun(runId, {
367
+ signal: abortControllerRef.current?.signal,
368
+ closeOnComplete: stopOnCompletion,
369
+ });
370
+ const streamQueue = (0, throttle_js_1.createThrottledQueue)(async (updates) => {
371
+ const nextStreamData = { ...existingDataRef.current };
372
+ // Group updates by type
373
+ const updatesByType = updates.reduce((acc, update) => {
374
+ if (!acc[update.type]) {
375
+ acc[update.type] = [];
376
+ }
377
+ acc[update.type].push(update.chunk);
378
+ return acc;
379
+ }, {});
380
+ // Apply all updates
381
+ for (const [type, chunks] of Object.entries(updatesByType)) {
382
+ // @ts-ignore
383
+ nextStreamData[type] = [...(existingDataRef.current[type] || []), ...chunks];
384
+ }
385
+ mutateStreamData(nextStreamData);
386
+ }, throttleInMs);
387
+ for await (const part of subscription.withStreams()) {
388
+ if (part.type === "run") {
389
+ mutateRunData(part.run);
390
+ }
391
+ else {
392
+ streamQueue.add({
393
+ type: part.type,
394
+ // @ts-ignore
395
+ chunk: part.chunk,
396
+ });
397
+ }
398
+ }
399
+ }
400
+ async function processRealtimeRun(runId, apiClient, mutateRunData, abortControllerRef, stopOnCompletion = true) {
401
+ const subscription = apiClient.subscribeToRun(runId, {
402
+ signal: abortControllerRef.current?.signal,
403
+ closeOnComplete: stopOnCompletion,
404
+ });
405
+ for await (const part of subscription) {
406
+ mutateRunData(part);
407
+ }
408
+ }
409
+ //# sourceMappingURL=useRealtime.js.map