@ai-sdk/provider-utils 3.0.0-alpha.9 → 3.0.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -39,100 +39,33 @@ function convertAsyncIteratorToReadableStream(iterator) {
39
39
  }
40
40
 
41
41
  // src/delay.ts
42
- async function delay(delayInMs) {
43
- return delayInMs == null ? Promise.resolve() : new Promise((resolve2) => setTimeout(resolve2, delayInMs));
44
- }
45
-
46
- // src/event-source-parser-stream.ts
47
- function createEventSourceParserStream() {
48
- let buffer = "";
49
- let event = void 0;
50
- let data = [];
51
- let lastEventId = void 0;
52
- let retry = void 0;
53
- function parseLine(line, controller) {
54
- if (line === "") {
55
- dispatchEvent(controller);
56
- return;
57
- }
58
- if (line.startsWith(":")) {
59
- return;
60
- }
61
- const colonIndex = line.indexOf(":");
62
- if (colonIndex === -1) {
63
- handleField(line, "");
64
- return;
65
- }
66
- const field = line.slice(0, colonIndex);
67
- const valueStart = colonIndex + 1;
68
- const value = valueStart < line.length && line[valueStart] === " " ? line.slice(valueStart + 1) : line.slice(valueStart);
69
- handleField(field, value);
42
+ async function delay(delayInMs, options) {
43
+ if (delayInMs == null) {
44
+ return Promise.resolve();
70
45
  }
71
- function dispatchEvent(controller) {
72
- if (data.length > 0) {
73
- controller.enqueue({
74
- event,
75
- data: data.join("\n"),
76
- id: lastEventId,
77
- retry
78
- });
79
- data = [];
80
- event = void 0;
81
- retry = void 0;
82
- }
83
- }
84
- function handleField(field, value) {
85
- switch (field) {
86
- case "event":
87
- event = value;
88
- break;
89
- case "data":
90
- data.push(value);
91
- break;
92
- case "id":
93
- lastEventId = value;
94
- break;
95
- case "retry":
96
- const parsedRetry = parseInt(value, 10);
97
- if (!isNaN(parsedRetry)) {
98
- retry = parsedRetry;
99
- }
100
- break;
101
- }
102
- }
103
- return new TransformStream({
104
- transform(chunk, controller) {
105
- const { lines, incompleteLine } = splitLines(buffer, chunk);
106
- buffer = incompleteLine;
107
- for (let i = 0; i < lines.length; i++) {
108
- parseLine(lines[i], controller);
109
- }
110
- },
111
- flush(controller) {
112
- parseLine(buffer, controller);
113
- dispatchEvent(controller);
46
+ const signal = options == null ? void 0 : options.abortSignal;
47
+ return new Promise((resolve2, reject) => {
48
+ if (signal == null ? void 0 : signal.aborted) {
49
+ reject(createAbortError());
50
+ return;
114
51
  }
52
+ const timeoutId = setTimeout(() => {
53
+ cleanup();
54
+ resolve2();
55
+ }, delayInMs);
56
+ const cleanup = () => {
57
+ clearTimeout(timeoutId);
58
+ signal == null ? void 0 : signal.removeEventListener("abort", onAbort);
59
+ };
60
+ const onAbort = () => {
61
+ cleanup();
62
+ reject(createAbortError());
63
+ };
64
+ signal == null ? void 0 : signal.addEventListener("abort", onAbort);
115
65
  });
116
66
  }
117
- function splitLines(buffer, chunk) {
118
- const lines = [];
119
- let currentLine = buffer;
120
- for (let i = 0; i < chunk.length; ) {
121
- const char = chunk[i++];
122
- if (char === "\n") {
123
- lines.push(currentLine);
124
- currentLine = "";
125
- } else if (char === "\r") {
126
- lines.push(currentLine);
127
- currentLine = "";
128
- if (chunk[i] === "\n") {
129
- i++;
130
- }
131
- } else {
132
- currentLine += char;
133
- }
134
- }
135
- return { lines, incompleteLine: currentLine };
67
+ function createAbortError() {
68
+ return new DOMException("Delay was aborted", "AbortError");
136
69
  }
137
70
 
138
71
  // src/extract-response-headers.ts
@@ -184,8 +117,43 @@ function getErrorMessage(error) {
184
117
  }
185
118
 
186
119
  // src/get-from-api.ts
120
+ import { APICallError as APICallError2 } from "@ai-sdk/provider";
121
+
122
+ // src/handle-fetch-error.ts
187
123
  import { APICallError } from "@ai-sdk/provider";
188
124
 
125
+ // src/is-abort-error.ts
126
+ function isAbortError(error) {
127
+ return (error instanceof Error || error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || // Next.js
128
+ error.name === "TimeoutError");
129
+ }
130
+
131
+ // src/handle-fetch-error.ts
132
+ var FETCH_FAILED_ERROR_MESSAGES = ["fetch failed", "failed to fetch"];
133
+ function handleFetchError({
134
+ error,
135
+ url,
136
+ requestBodyValues
137
+ }) {
138
+ if (isAbortError(error)) {
139
+ return error;
140
+ }
141
+ if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())) {
142
+ const cause = error.cause;
143
+ if (cause != null) {
144
+ return new APICallError({
145
+ message: `Cannot connect to API: ${cause.message}`,
146
+ cause,
147
+ url,
148
+ requestBodyValues,
149
+ isRetryable: true
150
+ // retry when network error
151
+ });
152
+ }
153
+ }
154
+ return error;
155
+ }
156
+
189
157
  // src/remove-undefined-entries.ts
190
158
  function removeUndefinedEntries(record) {
191
159
  return Object.fromEntries(
@@ -193,11 +161,6 @@ function removeUndefinedEntries(record) {
193
161
  );
194
162
  }
195
163
 
196
- // src/is-abort-error.ts
197
- function isAbortError(error) {
198
- return error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError");
199
- }
200
-
201
164
  // src/get-from-api.ts
202
165
  var getOriginalFetch = () => globalThis.fetch;
203
166
  var getFromApi = async ({
@@ -224,10 +187,10 @@ var getFromApi = async ({
224
187
  requestBodyValues: {}
225
188
  });
226
189
  } catch (error) {
227
- if (isAbortError(error) || APICallError.isInstance(error)) {
190
+ if (isAbortError(error) || APICallError2.isInstance(error)) {
228
191
  throw error;
229
192
  }
230
- throw new APICallError({
193
+ throw new APICallError2({
231
194
  message: "Failed to process error response",
232
195
  cause: error,
233
196
  statusCode: response.status,
@@ -246,11 +209,11 @@ var getFromApi = async ({
246
209
  });
247
210
  } catch (error) {
248
211
  if (error instanceof Error) {
249
- if (isAbortError(error) || APICallError.isInstance(error)) {
212
+ if (isAbortError(error) || APICallError2.isInstance(error)) {
250
213
  throw error;
251
214
  }
252
215
  }
253
- throw new APICallError({
216
+ throw new APICallError2({
254
217
  message: "Failed to process successful response",
255
218
  cause: error,
256
219
  statusCode: response.status,
@@ -260,22 +223,7 @@ var getFromApi = async ({
260
223
  });
261
224
  }
262
225
  } catch (error) {
263
- if (isAbortError(error)) {
264
- throw error;
265
- }
266
- if (error instanceof TypeError && error.message === "fetch failed") {
267
- const cause = error.cause;
268
- if (cause != null) {
269
- throw new APICallError({
270
- message: `Cannot connect to API: ${cause.message}`,
271
- cause,
272
- url,
273
- isRetryable: true,
274
- requestBodyValues: {}
275
- });
276
- }
277
- }
278
- throw error;
226
+ throw handleFetchError({ error, url, requestBodyValues: {} });
279
227
  }
280
228
  };
281
229
 
@@ -499,7 +447,10 @@ async function safeValidateTypes({
499
447
  }
500
448
 
501
449
  // src/parse-json.ts
502
- async function parseJSON({ text, schema }) {
450
+ async function parseJSON({
451
+ text,
452
+ schema
453
+ }) {
503
454
  try {
504
455
  const value = secureJsonParse(text);
505
456
  if (schema == null) {
@@ -541,11 +492,14 @@ function isParsableJson(input) {
541
492
  }
542
493
 
543
494
  // src/parse-json-event-stream.ts
495
+ import {
496
+ EventSourceParserStream
497
+ } from "eventsource-parser/stream";
544
498
  function parseJsonEventStream({
545
499
  stream,
546
500
  schema
547
501
  }) {
548
- return stream.pipeThrough(new TextDecoderStream()).pipeThrough(createEventSourceParserStream()).pipeThrough(
502
+ return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(
549
503
  new TransformStream({
550
504
  async transform({ data }, controller) {
551
505
  if (data === "[DONE]") {
@@ -582,7 +536,7 @@ async function parseProviderOptions({
582
536
  }
583
537
 
584
538
  // src/post-to-api.ts
585
- import { APICallError as APICallError2 } from "@ai-sdk/provider";
539
+ import { APICallError as APICallError3 } from "@ai-sdk/provider";
586
540
  var getOriginalFetch2 = () => globalThis.fetch;
587
541
  var postJsonToApi = async ({
588
542
  url,
@@ -653,10 +607,10 @@ var postToApi = async ({
653
607
  requestBodyValues: body.values
654
608
  });
655
609
  } catch (error) {
656
- if (isAbortError(error) || APICallError2.isInstance(error)) {
610
+ if (isAbortError(error) || APICallError3.isInstance(error)) {
657
611
  throw error;
658
612
  }
659
- throw new APICallError2({
613
+ throw new APICallError3({
660
614
  message: "Failed to process error response",
661
615
  cause: error,
662
616
  statusCode: response.status,
@@ -675,11 +629,11 @@ var postToApi = async ({
675
629
  });
676
630
  } catch (error) {
677
631
  if (error instanceof Error) {
678
- if (isAbortError(error) || APICallError2.isInstance(error)) {
632
+ if (isAbortError(error) || APICallError3.isInstance(error)) {
679
633
  throw error;
680
634
  }
681
635
  }
682
- throw new APICallError2({
636
+ throw new APICallError3({
683
637
  message: "Failed to process successful response",
684
638
  cause: error,
685
639
  statusCode: response.status,
@@ -689,26 +643,74 @@ var postToApi = async ({
689
643
  });
690
644
  }
691
645
  } catch (error) {
692
- if (isAbortError(error)) {
693
- throw error;
694
- }
695
- if (error instanceof TypeError && error.message === "fetch failed") {
696
- const cause = error.cause;
697
- if (cause != null) {
698
- throw new APICallError2({
699
- message: `Cannot connect to API: ${cause.message}`,
700
- cause,
701
- url,
702
- requestBodyValues: body.values,
703
- isRetryable: true
704
- // retry when network error
705
- });
706
- }
707
- }
708
- throw error;
646
+ throw handleFetchError({ error, url, requestBodyValues: body.values });
709
647
  }
710
648
  };
711
649
 
650
+ // src/types/tool.ts
651
+ function tool(tool2) {
652
+ return tool2;
653
+ }
654
+ function dynamicTool(tool2) {
655
+ return { ...tool2, type: "dynamic" };
656
+ }
657
+
658
+ // src/provider-defined-tool-factory.ts
659
+ function createProviderDefinedToolFactory({
660
+ id,
661
+ name,
662
+ inputSchema
663
+ }) {
664
+ return ({
665
+ execute,
666
+ outputSchema,
667
+ toModelOutput,
668
+ onInputStart,
669
+ onInputDelta,
670
+ onInputAvailable,
671
+ ...args
672
+ }) => tool({
673
+ type: "provider-defined",
674
+ id,
675
+ name,
676
+ args,
677
+ inputSchema,
678
+ outputSchema,
679
+ execute,
680
+ toModelOutput,
681
+ onInputStart,
682
+ onInputDelta,
683
+ onInputAvailable
684
+ });
685
+ }
686
+ function createProviderDefinedToolFactoryWithOutputSchema({
687
+ id,
688
+ name,
689
+ inputSchema,
690
+ outputSchema
691
+ }) {
692
+ return ({
693
+ execute,
694
+ toModelOutput,
695
+ onInputStart,
696
+ onInputDelta,
697
+ onInputAvailable,
698
+ ...args
699
+ }) => tool({
700
+ type: "provider-defined",
701
+ id,
702
+ name,
703
+ args,
704
+ inputSchema,
705
+ outputSchema,
706
+ execute,
707
+ toModelOutput,
708
+ onInputStart,
709
+ onInputDelta,
710
+ onInputAvailable
711
+ });
712
+ }
713
+
712
714
  // src/resolve.ts
713
715
  async function resolve(value) {
714
716
  if (typeof value === "function") {
@@ -718,7 +720,7 @@ async function resolve(value) {
718
720
  }
719
721
 
720
722
  // src/response-handler.ts
721
- import { APICallError as APICallError3, EmptyResponseBodyError } from "@ai-sdk/provider";
723
+ import { APICallError as APICallError4, EmptyResponseBodyError } from "@ai-sdk/provider";
722
724
  var createJsonErrorResponseHandler = ({
723
725
  errorSchema,
724
726
  errorToMessage,
@@ -729,7 +731,7 @@ var createJsonErrorResponseHandler = ({
729
731
  if (responseBody.trim() === "") {
730
732
  return {
731
733
  responseHeaders,
732
- value: new APICallError3({
734
+ value: new APICallError4({
733
735
  message: response.statusText,
734
736
  url,
735
737
  requestBodyValues,
@@ -747,7 +749,7 @@ var createJsonErrorResponseHandler = ({
747
749
  });
748
750
  return {
749
751
  responseHeaders,
750
- value: new APICallError3({
752
+ value: new APICallError4({
751
753
  message: errorToMessage(parsedError),
752
754
  url,
753
755
  requestBodyValues,
@@ -761,7 +763,7 @@ var createJsonErrorResponseHandler = ({
761
763
  } catch (parseError) {
762
764
  return {
763
765
  responseHeaders,
764
- value: new APICallError3({
766
+ value: new APICallError4({
765
767
  message: response.statusText,
766
768
  url,
767
769
  requestBodyValues,
@@ -821,7 +823,7 @@ var createJsonResponseHandler = (responseSchema) => async ({ response, url, requ
821
823
  });
822
824
  const responseHeaders = extractResponseHeaders(response);
823
825
  if (!parsedResult.success) {
824
- throw new APICallError3({
826
+ throw new APICallError4({
825
827
  message: "Invalid JSON response",
826
828
  cause: parsedResult.error,
827
829
  statusCode: response.status,
@@ -840,7 +842,7 @@ var createJsonResponseHandler = (responseSchema) => async ({ response, url, requ
840
842
  var createBinaryResponseHandler = () => async ({ response, url, requestBodyValues }) => {
841
843
  const responseHeaders = extractResponseHeaders(response);
842
844
  if (!response.body) {
843
- throw new APICallError3({
845
+ throw new APICallError4({
844
846
  message: "Response body is empty",
845
847
  url,
846
848
  requestBodyValues,
@@ -856,7 +858,7 @@ var createBinaryResponseHandler = () => async ({ response, url, requestBodyValue
856
858
  value: new Uint8Array(buffer)
857
859
  };
858
860
  } catch (error) {
859
- throw new APICallError3({
861
+ throw new APICallError4({
860
862
  message: "Failed to read response as array buffer",
861
863
  url,
862
864
  requestBodyValues,
@@ -872,7 +874,7 @@ var createStatusCodeErrorResponseHandler = () => async ({ response, url, request
872
874
  const responseBody = await response.text();
873
875
  return {
874
876
  responseHeaders,
875
- value: new APICallError3({
877
+ value: new APICallError4({
876
878
  message: response.statusText,
877
879
  url,
878
880
  requestBodyValues,
@@ -884,7 +886,7 @@ var createStatusCodeErrorResponseHandler = () => async ({ response, url, request
884
886
  };
885
887
 
886
888
  // src/zod-schema.ts
887
- import * as z4 from "zod/v4/core";
889
+ import * as z4 from "zod/v4";
888
890
  import zodToJsonSchema from "zod-to-json-schema";
889
891
  function zod3Schema(zodSchema2, options) {
890
892
  var _a;
@@ -896,8 +898,8 @@ function zod3Schema(zodSchema2, options) {
896
898
  // note: openai mode breaks various gemini conversions
897
899
  }),
898
900
  {
899
- validate: (value) => {
900
- const result = zodSchema2.safeParse(value);
901
+ validate: async (value) => {
902
+ const result = await zodSchema2.safeParseAsync(value);
901
903
  return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
902
904
  }
903
905
  }
@@ -912,8 +914,8 @@ function zod4Schema(zodSchema2, options) {
912
914
  reused: useReferences ? "ref" : "inline"
913
915
  });
914
916
  return jsonSchema(z4JSONSchema, {
915
- validate: (value) => {
916
- const result = z4.safeParse(zodSchema2, value);
917
+ validate: async (value) => {
918
+ const result = await z4.safeParseAsync(zodSchema2, value);
917
919
  return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
918
920
  }
919
921
  });
@@ -978,7 +980,11 @@ function withoutTrailingSlash(url) {
978
980
 
979
981
  // src/index.ts
980
982
  export * from "@standard-schema/spec";
983
+ import {
984
+ EventSourceParserStream as EventSourceParserStream2
985
+ } from "eventsource-parser/stream";
981
986
  export {
987
+ EventSourceParserStream2 as EventSourceParserStream,
982
988
  asSchema,
983
989
  asValidator,
984
990
  combineHeaders,
@@ -987,14 +993,16 @@ export {
987
993
  convertToBase64,
988
994
  convertUint8ArrayToBase64,
989
995
  createBinaryResponseHandler,
990
- createEventSourceParserStream,
991
996
  createEventSourceResponseHandler,
992
997
  createIdGenerator,
993
998
  createJsonErrorResponseHandler,
994
999
  createJsonResponseHandler,
995
1000
  createJsonStreamResponseHandler,
1001
+ createProviderDefinedToolFactory,
1002
+ createProviderDefinedToolFactoryWithOutputSchema,
996
1003
  createStatusCodeErrorResponseHandler,
997
1004
  delay,
1005
+ dynamicTool,
998
1006
  extractResponseHeaders,
999
1007
  generateId,
1000
1008
  getErrorMessage,
@@ -1018,6 +1026,7 @@ export {
1018
1026
  safeParseJSON,
1019
1027
  safeValidateTypes,
1020
1028
  standardSchemaValidator,
1029
+ tool,
1021
1030
  validateTypes,
1022
1031
  validator,
1023
1032
  validatorSymbol,