@mastra/client-js 0.0.0-inject-middleware-20250528213451 → 0.0.0-interpolate-reporter-url-20250910180021

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 (78) hide show
  1. package/CHANGELOG.md +1423 -2
  2. package/LICENSE.md +11 -42
  3. package/README.md +7 -4
  4. package/dist/client.d.ts +280 -0
  5. package/dist/client.d.ts.map +1 -0
  6. package/dist/example.d.ts +2 -0
  7. package/dist/example.d.ts.map +1 -0
  8. package/dist/index.cjs +2222 -375
  9. package/dist/index.cjs.map +1 -0
  10. package/dist/index.d.ts +4 -900
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/index.js +2224 -377
  13. package/dist/index.js.map +1 -0
  14. package/dist/resources/a2a.d.ts +41 -0
  15. package/dist/resources/a2a.d.ts.map +1 -0
  16. package/dist/resources/agent-builder.d.ts +161 -0
  17. package/dist/resources/agent-builder.d.ts.map +1 -0
  18. package/dist/resources/agent.d.ts +155 -0
  19. package/dist/resources/agent.d.ts.map +1 -0
  20. package/dist/resources/base.d.ts +13 -0
  21. package/dist/resources/base.d.ts.map +1 -0
  22. package/dist/resources/index.d.ts +13 -0
  23. package/dist/resources/index.d.ts.map +1 -0
  24. package/dist/resources/legacy-workflow.d.ts +87 -0
  25. package/dist/resources/legacy-workflow.d.ts.map +1 -0
  26. package/dist/resources/mcp-tool.d.ts +27 -0
  27. package/dist/resources/mcp-tool.d.ts.map +1 -0
  28. package/dist/resources/memory-thread.d.ts +53 -0
  29. package/dist/resources/memory-thread.d.ts.map +1 -0
  30. package/dist/resources/network-memory-thread.d.ts +47 -0
  31. package/dist/resources/network-memory-thread.d.ts.map +1 -0
  32. package/dist/resources/network.d.ts +30 -0
  33. package/dist/resources/network.d.ts.map +1 -0
  34. package/dist/resources/observability.d.ts +19 -0
  35. package/dist/resources/observability.d.ts.map +1 -0
  36. package/dist/resources/tool.d.ts +23 -0
  37. package/dist/resources/tool.d.ts.map +1 -0
  38. package/dist/resources/vNextNetwork.d.ts +42 -0
  39. package/dist/resources/vNextNetwork.d.ts.map +1 -0
  40. package/dist/resources/vector.d.ts +48 -0
  41. package/dist/resources/vector.d.ts.map +1 -0
  42. package/dist/resources/workflow.d.ts +169 -0
  43. package/dist/resources/workflow.d.ts.map +1 -0
  44. package/dist/types.d.ts +462 -0
  45. package/dist/types.d.ts.map +1 -0
  46. package/dist/utils/index.d.ts +3 -0
  47. package/dist/utils/index.d.ts.map +1 -0
  48. package/dist/utils/process-client-tools.d.ts +3 -0
  49. package/dist/utils/process-client-tools.d.ts.map +1 -0
  50. package/dist/utils/process-mastra-stream.d.ts +7 -0
  51. package/dist/utils/process-mastra-stream.d.ts.map +1 -0
  52. package/dist/utils/zod-to-json-schema.d.ts +3 -0
  53. package/dist/utils/zod-to-json-schema.d.ts.map +1 -0
  54. package/package.json +38 -21
  55. package/dist/index.d.cts +0 -900
  56. package/eslint.config.js +0 -6
  57. package/src/adapters/agui.test.ts +0 -180
  58. package/src/adapters/agui.ts +0 -239
  59. package/src/client.ts +0 -334
  60. package/src/example.ts +0 -64
  61. package/src/index.test.ts +0 -830
  62. package/src/index.ts +0 -2
  63. package/src/resources/a2a.ts +0 -88
  64. package/src/resources/agent.ts +0 -197
  65. package/src/resources/base.ts +0 -70
  66. package/src/resources/index.ts +0 -10
  67. package/src/resources/legacy-workflow.ts +0 -242
  68. package/src/resources/mcp-tool.ts +0 -48
  69. package/src/resources/memory-thread.ts +0 -63
  70. package/src/resources/network.ts +0 -86
  71. package/src/resources/tool.ts +0 -45
  72. package/src/resources/vector.ts +0 -83
  73. package/src/resources/workflow.ts +0 -353
  74. package/src/types.ts +0 -314
  75. package/src/utils/index.ts +0 -11
  76. package/src/utils/zod-to-json-schema.ts +0 -10
  77. package/tsconfig.json +0 -5
  78. package/vitest.config.js +0 -8
@@ -1,63 +0,0 @@
1
- import type { StorageThreadType } from '@mastra/core';
2
-
3
- import type {
4
- GetMemoryThreadMessagesResponse,
5
- ClientOptions,
6
- UpdateMemoryThreadParams,
7
- GetMemoryThreadMessagesParams,
8
- } from '../types';
9
-
10
- import { BaseResource } from './base';
11
-
12
- export class MemoryThread extends BaseResource {
13
- constructor(
14
- options: ClientOptions,
15
- private threadId: string,
16
- private agentId: string,
17
- ) {
18
- super(options);
19
- }
20
-
21
- /**
22
- * Retrieves the memory thread details
23
- * @returns Promise containing thread details including title and metadata
24
- */
25
- get(): Promise<StorageThreadType> {
26
- return this.request(`/api/memory/threads/${this.threadId}?agentId=${this.agentId}`);
27
- }
28
-
29
- /**
30
- * Updates the memory thread properties
31
- * @param params - Update parameters including title and metadata
32
- * @returns Promise containing updated thread details
33
- */
34
- update(params: UpdateMemoryThreadParams): Promise<StorageThreadType> {
35
- return this.request(`/api/memory/threads/${this.threadId}?agentId=${this.agentId}`, {
36
- method: 'PATCH',
37
- body: params,
38
- });
39
- }
40
-
41
- /**
42
- * Deletes the memory thread
43
- * @returns Promise containing deletion result
44
- */
45
- delete(): Promise<{ result: string }> {
46
- return this.request(`/api/memory/threads/${this.threadId}?agentId=${this.agentId}`, {
47
- method: 'DELETE',
48
- });
49
- }
50
-
51
- /**
52
- * Retrieves messages associated with the thread
53
- * @param params - Optional parameters including limit for number of messages to retrieve
54
- * @returns Promise containing thread messages and UI messages
55
- */
56
- getMessages(params?: GetMemoryThreadMessagesParams): Promise<GetMemoryThreadMessagesResponse> {
57
- const query = new URLSearchParams({
58
- agentId: this.agentId,
59
- ...(params?.limit ? { limit: params.limit.toString() } : {}),
60
- });
61
- return this.request(`/api/memory/threads/${this.threadId}/messages?${query.toString()}`);
62
- }
63
- }
@@ -1,86 +0,0 @@
1
- import { processDataStream } from '@ai-sdk/ui-utils';
2
- import type { GenerateReturn } from '@mastra/core';
3
- import type { JSONSchema7 } from 'json-schema';
4
- import { ZodSchema } from 'zod';
5
- import { zodToJsonSchema } from '../utils/zod-to-json-schema';
6
-
7
- import type { GenerateParams, ClientOptions, StreamParams, GetNetworkResponse } from '../types';
8
-
9
- import { BaseResource } from './base';
10
-
11
- export class Network extends BaseResource {
12
- constructor(
13
- options: ClientOptions,
14
- private networkId: string,
15
- ) {
16
- super(options);
17
- }
18
-
19
- /**
20
- * Retrieves details about the network
21
- * @returns Promise containing network details
22
- */
23
- details(): Promise<GetNetworkResponse> {
24
- return this.request(`/api/networks/${this.networkId}`);
25
- }
26
-
27
- /**
28
- * Generates a response from the agent
29
- * @param params - Generation parameters including prompt
30
- * @returns Promise containing the generated response
31
- */
32
- generate<T extends JSONSchema7 | ZodSchema | undefined = undefined>(
33
- params: GenerateParams<T>,
34
- ): Promise<GenerateReturn<T>> {
35
- const processedParams = {
36
- ...params,
37
- output: zodToJsonSchema(params.output),
38
- experimental_output: zodToJsonSchema(params.experimental_output),
39
- };
40
-
41
- return this.request(`/api/networks/${this.networkId}/generate`, {
42
- method: 'POST',
43
- body: processedParams,
44
- });
45
- }
46
-
47
- /**
48
- * Streams a response from the agent
49
- * @param params - Stream parameters including prompt
50
- * @returns Promise containing the enhanced Response object with processDataStream method
51
- */
52
- async stream<T extends JSONSchema7 | ZodSchema | undefined = undefined>(
53
- params: StreamParams<T>,
54
- ): Promise<
55
- Response & {
56
- processDataStream: (options?: Omit<Parameters<typeof processDataStream>[0], 'stream'>) => Promise<void>;
57
- }
58
- > {
59
- const processedParams = {
60
- ...params,
61
- output: zodToJsonSchema(params.output),
62
- experimental_output: zodToJsonSchema(params.experimental_output),
63
- };
64
-
65
- const response: Response & {
66
- processDataStream: (options?: Omit<Parameters<typeof processDataStream>[0], 'stream'>) => Promise<void>;
67
- } = await this.request(`/api/networks/${this.networkId}/stream`, {
68
- method: 'POST',
69
- body: processedParams,
70
- stream: true,
71
- });
72
-
73
- if (!response.body) {
74
- throw new Error('No response body');
75
- }
76
-
77
- response.processDataStream = async (options = {}) => {
78
- await processDataStream({
79
- stream: response.body as ReadableStream<Uint8Array>,
80
- ...options,
81
- });
82
- };
83
-
84
- return response;
85
- }
86
- }
@@ -1,45 +0,0 @@
1
- import type { RuntimeContext } from '@mastra/core/runtime-context';
2
- import type { GetToolResponse, ClientOptions } from '../types';
3
-
4
- import { BaseResource } from './base';
5
- import { parseClientRuntimeContext } from '../utils';
6
-
7
- export class Tool extends BaseResource {
8
- constructor(
9
- options: ClientOptions,
10
- private toolId: string,
11
- ) {
12
- super(options);
13
- }
14
-
15
- /**
16
- * Retrieves details about the tool
17
- * @returns Promise containing tool details including description and schemas
18
- */
19
- details(): Promise<GetToolResponse> {
20
- return this.request(`/api/tools/${this.toolId}`);
21
- }
22
-
23
- /**
24
- * Executes the tool with the provided parameters
25
- * @param params - Parameters required for tool execution
26
- * @returns Promise containing the tool execution results
27
- */
28
- execute(params: { data: any; runId?: string; runtimeContext?: RuntimeContext | Record<string, any> }): Promise<any> {
29
- const url = new URLSearchParams();
30
-
31
- if (params.runId) {
32
- url.set('runId', params.runId);
33
- }
34
-
35
- const body = {
36
- data: params.data,
37
- runtimeContext: parseClientRuntimeContext(params.runtimeContext),
38
- };
39
-
40
- return this.request(`/api/tools/${this.toolId}/execute?${url.toString()}`, {
41
- method: 'POST',
42
- body,
43
- });
44
- }
45
- }
@@ -1,83 +0,0 @@
1
- import type {
2
- CreateIndexParams,
3
- GetVectorIndexResponse,
4
- QueryVectorParams,
5
- QueryVectorResponse,
6
- ClientOptions,
7
- UpsertVectorParams,
8
- } from '../types';
9
-
10
- import { BaseResource } from './base';
11
-
12
- export class Vector extends BaseResource {
13
- constructor(
14
- options: ClientOptions,
15
- private vectorName: string,
16
- ) {
17
- super(options);
18
- }
19
-
20
- /**
21
- * Retrieves details about a specific vector index
22
- * @param indexName - Name of the index to get details for
23
- * @returns Promise containing vector index details
24
- */
25
- details(indexName: string): Promise<GetVectorIndexResponse> {
26
- return this.request(`/api/vector/${this.vectorName}/indexes/${indexName}`);
27
- }
28
-
29
- /**
30
- * Deletes a vector index
31
- * @param indexName - Name of the index to delete
32
- * @returns Promise indicating deletion success
33
- */
34
- delete(indexName: string): Promise<{ success: boolean }> {
35
- return this.request(`/api/vector/${this.vectorName}/indexes/${indexName}`, {
36
- method: 'DELETE',
37
- });
38
- }
39
-
40
- /**
41
- * Retrieves a list of all available indexes
42
- * @returns Promise containing array of index names
43
- */
44
- getIndexes(): Promise<{ indexes: string[] }> {
45
- return this.request(`/api/vector/${this.vectorName}/indexes`);
46
- }
47
-
48
- /**
49
- * Creates a new vector index
50
- * @param params - Parameters for index creation including dimension and metric
51
- * @returns Promise indicating creation success
52
- */
53
- createIndex(params: CreateIndexParams): Promise<{ success: boolean }> {
54
- return this.request(`/api/vector/${this.vectorName}/create-index`, {
55
- method: 'POST',
56
- body: params,
57
- });
58
- }
59
-
60
- /**
61
- * Upserts vectors into an index
62
- * @param params - Parameters containing vectors, metadata, and optional IDs
63
- * @returns Promise containing array of vector IDs
64
- */
65
- upsert(params: UpsertVectorParams): Promise<string[]> {
66
- return this.request(`/api/vector/${this.vectorName}/upsert`, {
67
- method: 'POST',
68
- body: params,
69
- });
70
- }
71
-
72
- /**
73
- * Queries vectors in an index
74
- * @param params - Query parameters including query vector and search options
75
- * @returns Promise containing query results
76
- */
77
- query(params: QueryVectorParams): Promise<QueryVectorResponse> {
78
- return this.request(`/api/vector/${this.vectorName}/query`, {
79
- method: 'POST',
80
- body: params,
81
- });
82
- }
83
- }
@@ -1,353 +0,0 @@
1
- import type { RuntimeContext } from '@mastra/core/runtime-context';
2
- import type {
3
- ClientOptions,
4
- GetWorkflowResponse,
5
- GetWorkflowRunsResponse,
6
- GetWorkflowRunsParams,
7
- WorkflowRunResult,
8
- WorkflowWatchResult,
9
- } from '../types';
10
-
11
- import { parseClientRuntimeContext } from '../utils';
12
- import { BaseResource } from './base';
13
-
14
- const RECORD_SEPARATOR = '\x1E';
15
-
16
- export class Workflow extends BaseResource {
17
- constructor(
18
- options: ClientOptions,
19
- private workflowId: string,
20
- ) {
21
- super(options);
22
- }
23
-
24
- /**
25
- * Creates an async generator that processes a readable stream and yields workflow records
26
- * separated by the Record Separator character (\x1E)
27
- *
28
- * @param stream - The readable stream to process
29
- * @returns An async generator that yields parsed records
30
- */
31
- private async *streamProcessor(stream: ReadableStream): AsyncGenerator<WorkflowWatchResult, void, unknown> {
32
- const reader = stream.getReader();
33
-
34
- // Track if we've finished reading from the stream
35
- let doneReading = false;
36
- // Buffer to accumulate partial chunks
37
- let buffer = '';
38
-
39
- try {
40
- while (!doneReading) {
41
- // Read the next chunk from the stream
42
- const { done, value } = await reader.read();
43
- doneReading = done;
44
-
45
- // Skip processing if we're done and there's no value
46
- if (done && !value) continue;
47
-
48
- try {
49
- // Decode binary data to text
50
- const decoded = value ? new TextDecoder().decode(value) : '';
51
-
52
- // Split the combined buffer and new data by record separator
53
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR);
54
-
55
- // The last chunk might be incomplete, so save it for the next iteration
56
- buffer = chunks.pop() || '';
57
-
58
- // Process complete chunks
59
- for (const chunk of chunks) {
60
- if (chunk) {
61
- // Only process non-empty chunks
62
- if (typeof chunk === 'string') {
63
- try {
64
- const parsedChunk = JSON.parse(chunk);
65
- yield parsedChunk;
66
- } catch {
67
- // Silently ignore parsing errors to maintain stream processing
68
- // This allows the stream to continue even if one record is malformed
69
- }
70
- }
71
- }
72
- }
73
- } catch {
74
- // Silently ignore parsing errors to maintain stream processing
75
- // This allows the stream to continue even if one record is malformed
76
- }
77
- }
78
-
79
- // Process any remaining data in the buffer after stream is done
80
- if (buffer) {
81
- try {
82
- yield JSON.parse(buffer);
83
- } catch {
84
- // Ignore parsing error for final chunk
85
- }
86
- }
87
- } finally {
88
- // Always ensure we clean up the reader
89
- reader.cancel().catch(() => {
90
- // Ignore cancel errors
91
- });
92
- }
93
- }
94
-
95
- /**
96
- * Retrieves details about the workflow
97
- * @returns Promise containing workflow details including steps and graphs
98
- */
99
- details(): Promise<GetWorkflowResponse> {
100
- return this.request(`/api/workflows/${this.workflowId}`);
101
- }
102
-
103
- /**
104
- * Retrieves all runs for a workflow
105
- * @param params - Parameters for filtering runs
106
- * @returns Promise containing workflow runs array
107
- */
108
- runs(params?: GetWorkflowRunsParams): Promise<GetWorkflowRunsResponse> {
109
- const searchParams = new URLSearchParams();
110
- if (params?.fromDate) {
111
- searchParams.set('fromDate', params.fromDate.toISOString());
112
- }
113
- if (params?.toDate) {
114
- searchParams.set('toDate', params.toDate.toISOString());
115
- }
116
- if (params?.limit) {
117
- searchParams.set('limit', String(params.limit));
118
- }
119
- if (params?.offset) {
120
- searchParams.set('offset', String(params.offset));
121
- }
122
- if (params?.resourceId) {
123
- searchParams.set('resourceId', params.resourceId);
124
- }
125
-
126
- if (searchParams.size) {
127
- return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
128
- } else {
129
- return this.request(`/api/workflows/${this.workflowId}/runs`);
130
- }
131
- }
132
-
133
- /**
134
- * Creates a new workflow run
135
- * @param params - Optional object containing the optional runId
136
- * @returns Promise containing the runId of the created run
137
- */
138
- createRun(params?: { runId?: string }): Promise<{ runId: string }> {
139
- const searchParams = new URLSearchParams();
140
-
141
- if (!!params?.runId) {
142
- searchParams.set('runId', params.runId);
143
- }
144
-
145
- return this.request(`/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`, {
146
- method: 'POST',
147
- });
148
- }
149
-
150
- /**
151
- * Starts a workflow run synchronously without waiting for the workflow to complete
152
- * @param params - Object containing the runId, inputData and runtimeContext
153
- * @returns Promise containing success message
154
- */
155
- start(params: {
156
- runId: string;
157
- inputData: Record<string, any>;
158
- runtimeContext?: RuntimeContext | Record<string, any>;
159
- }): Promise<{ message: string }> {
160
- const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
161
- return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
162
- method: 'POST',
163
- body: { inputData: params?.inputData, runtimeContext },
164
- });
165
- }
166
-
167
- /**
168
- * Resumes a suspended workflow step synchronously without waiting for the workflow to complete
169
- * @param params - Object containing the runId, step, resumeData and runtimeContext
170
- * @returns Promise containing success message
171
- */
172
- resume({
173
- step,
174
- runId,
175
- resumeData,
176
- ...rest
177
- }: {
178
- step: string | string[];
179
- runId: string;
180
- resumeData?: Record<string, any>;
181
- runtimeContext?: RuntimeContext | Record<string, any>;
182
- }): Promise<{ message: string }> {
183
- const runtimeContext = parseClientRuntimeContext(rest.runtimeContext);
184
- return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
185
- method: 'POST',
186
- stream: true,
187
- body: {
188
- step,
189
- resumeData,
190
- runtimeContext,
191
- },
192
- });
193
- }
194
-
195
- /**
196
- * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
197
- * @param params - Object containing the optional runId, inputData and runtimeContext
198
- * @returns Promise containing the workflow execution results
199
- */
200
- startAsync(params: {
201
- runId?: string;
202
- inputData: Record<string, any>;
203
- runtimeContext?: RuntimeContext | Record<string, any>;
204
- }): Promise<WorkflowRunResult> {
205
- const searchParams = new URLSearchParams();
206
-
207
- if (!!params?.runId) {
208
- searchParams.set('runId', params.runId);
209
- }
210
-
211
- const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
212
-
213
- return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
214
- method: 'POST',
215
- body: { inputData: params.inputData, runtimeContext },
216
- });
217
- }
218
-
219
- /**
220
- * Starts a vNext workflow run and returns a stream
221
- * @param params - Object containing the optional runId, inputData and runtimeContext
222
- * @returns Promise containing the vNext workflow execution results
223
- */
224
- async stream(params: { runId?: string; inputData: Record<string, any>; runtimeContext?: RuntimeContext }) {
225
- const searchParams = new URLSearchParams();
226
-
227
- if (!!params?.runId) {
228
- searchParams.set('runId', params.runId);
229
- }
230
-
231
- const runtimeContext = params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : undefined;
232
- const response: Response = await this.request(
233
- `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
234
- {
235
- method: 'POST',
236
- body: { inputData: params.inputData, runtimeContext },
237
- stream: true,
238
- },
239
- );
240
-
241
- if (!response.ok) {
242
- throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
243
- }
244
-
245
- if (!response.body) {
246
- throw new Error('Response body is null');
247
- }
248
-
249
- // Create a transform stream that processes the response body
250
- const transformStream = new TransformStream<ArrayBuffer, WorkflowWatchResult>({
251
- start() {},
252
- async transform(chunk, controller) {
253
- try {
254
- // Decode binary data to text
255
- const decoded = new TextDecoder().decode(chunk);
256
-
257
- // Split by record separator
258
- const chunks = decoded.split(RECORD_SEPARATOR);
259
-
260
- // Process each chunk
261
- for (const chunk of chunks) {
262
- if (chunk) {
263
- try {
264
- const parsedChunk = JSON.parse(chunk);
265
- controller.enqueue(parsedChunk);
266
- } catch {
267
- // Silently ignore parsing errors
268
- }
269
- }
270
- }
271
- } catch {
272
- // Silently ignore processing errors
273
- }
274
- },
275
- });
276
-
277
- // Pipe the response body through the transform stream
278
- return response.body.pipeThrough(transformStream);
279
- }
280
-
281
- /**
282
- * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
283
- * @param params - Object containing the runId, step, resumeData and runtimeContext
284
- * @returns Promise containing the workflow resume results
285
- */
286
- resumeAsync(params: {
287
- runId: string;
288
- step: string | string[];
289
- resumeData?: Record<string, any>;
290
- runtimeContext?: RuntimeContext | Record<string, any>;
291
- }): Promise<WorkflowRunResult> {
292
- const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
293
- return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
294
- method: 'POST',
295
- body: {
296
- step: params.step,
297
- resumeData: params.resumeData,
298
- runtimeContext,
299
- },
300
- });
301
- }
302
-
303
- /**
304
- * Watches workflow transitions in real-time
305
- * @param runId - Optional run ID to filter the watch stream
306
- * @returns AsyncGenerator that yields parsed records from the workflow watch stream
307
- */
308
- async watch({ runId }: { runId?: string }, onRecord: (record: WorkflowWatchResult) => void) {
309
- const response: Response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
310
- stream: true,
311
- });
312
-
313
- if (!response.ok) {
314
- throw new Error(`Failed to watch workflow: ${response.statusText}`);
315
- }
316
-
317
- if (!response.body) {
318
- throw new Error('Response body is null');
319
- }
320
-
321
- for await (const record of this.streamProcessor(response.body)) {
322
- if (typeof record === 'string') {
323
- onRecord(JSON.parse(record));
324
- } else {
325
- onRecord(record);
326
- }
327
- }
328
- }
329
-
330
- /**
331
- * Creates a new ReadableStream from an iterable or async iterable of objects,
332
- * serializing each as JSON and separating them with the record separator (\x1E).
333
- *
334
- * @param records - An iterable or async iterable of objects to stream
335
- * @returns A ReadableStream emitting the records as JSON strings separated by the record separator
336
- */
337
- static createRecordStream(records: Iterable<any> | AsyncIterable<any>): ReadableStream {
338
- const encoder = new TextEncoder();
339
- return new ReadableStream({
340
- async start(controller) {
341
- try {
342
- for await (const record of records as AsyncIterable<any>) {
343
- const json = JSON.stringify(record) + RECORD_SEPARATOR;
344
- controller.enqueue(encoder.encode(json));
345
- }
346
- controller.close();
347
- } catch (err) {
348
- controller.error(err);
349
- }
350
- },
351
- });
352
- }
353
- }