@ai-sdk/provider-utils 4.0.63 → 4.0.65

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/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # @ai-sdk/provider-utils
2
2
 
3
+ ## 4.0.65
4
+
5
+ ### Patch Changes
6
+
7
+ - f0dee4b: Reject HTTPS-to-HTTP redirects in validated downloads before requesting the insecure target, including when it matches a configured trusted origin.
8
+
9
+ ## 4.0.64
10
+
11
+ ### Patch Changes
12
+
13
+ - d900e58: fix(provider-utils): support cross-realm Uint8Array and ArrayBuffer in binary type guards and base64 conversion
14
+ - d900e58: fix(provider-utils): decode base64 into a preallocated Uint8Array to avoid ~25x transient memory and long event-loop blocking on large files
15
+ - d900e58: Add `stringifyWithBigIntAndCycles` for provider tool serialization that converts BigInt values to decimal strings and replaces ancestor cycles while preserving shared references and `toJSON` behavior.
16
+
3
17
  ## 4.0.63
4
18
 
5
19
  ### Patch Changes
package/dist/index.d.mts CHANGED
@@ -258,6 +258,9 @@ declare function fetchWithValidatedEndpoint({ url, init, fetch: customFetch, tru
258
258
  * target (e.g. an internal address) before we ever see its URL, defeating the
259
259
  * guard.
260
260
  *
261
+ * Manually followed redirects from HTTPS to HTTP are rejected before requesting
262
+ * the target.
263
+ *
261
264
  * Request headers are also protected: {@link sanitizeRequestHeaders} strips
262
265
  * proxy/metadata/cookie/hop-by-hop headers before the first request, and all
263
266
  * caller headers except `User-Agent` are dropped on a cross-origin redirect.
@@ -1599,6 +1602,8 @@ declare function stripFileExtension(filename: string): string;
1599
1602
 
1600
1603
  declare function convertBase64ToUint8Array(base64String: string): Uint8Array<ArrayBuffer>;
1601
1604
  declare function convertUint8ArrayToBase64(array: Uint8Array): string;
1605
+ declare function isUint8Array(value: unknown): value is Uint8Array;
1606
+ declare function isArrayBuffer(value: unknown): value is ArrayBuffer;
1602
1607
  declare function convertToBase64(value: string | Uint8Array): string;
1603
1608
 
1604
1609
  /**
@@ -1744,4 +1749,11 @@ interface ToolResult<NAME extends string, INPUT, OUTPUT> {
1744
1749
  */
1745
1750
  type ToolCallOptions = ToolExecutionOptions;
1746
1751
 
1747
- export { type AssistantContent, type AssistantModelMessage, DEFAULT_MAX_DOWNLOAD_SIZE, type DataContent, DelayedPromise, DownloadError, EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL as EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL, EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER as EXPERIMENTAL_EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER, type EmbeddingModelProviderOptionsTransformer, type FetchFunction, type FilePart, type FlexibleSchema, type IdGenerator, type ImagePart, type InferSchema, type InferToolInput, type InferToolOutput, type LazySchema, type MaybePromiseLike, type ModelMessage, type ParseResult, type ProviderOptions, type ProviderToolFactory, type ProviderToolFactoryWithOutputSchema, type ReasoningPart, type Resolvable, type ResponseHandler, type RetryDelayProvider, type RetryErrorFactory, type RetryErrorReason, type RetryFunction, type Schema, type ShouldRetryFunction, type StreamingToolCallDelta, StreamingToolCallTracker, type StreamingToolCallTrackerOptions, type SystemModelMessage, type TextPart, type Tool, type ToolApprovalRequest, type ToolApprovalResponse, type ToolCall, type ToolCallOptions, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolExecutionOptions, type ToolModelMessage, type ToolNameMapping, type ToolNeedsApprovalFunction, type ToolResult, type ToolResultOutput, type ToolResultPart, type UserContent, type UserModelMessage, VERSION, type ValidationResult, asSchema, cancelResponseBody, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertImageModelFileToDataUri, convertToBase64, convertToFormData, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createProviderToolFactory, createProviderToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, createToolNameMapping, delay, downloadBlob, dynamicTool, encodePathSegment, executeTool, extractResponseHeaders, fetchWithValidatedEndpoint, fetchWithValidatedRedirects, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isBrowserRuntime, isNonNullable, isParsableJson, isSameOrigin, isUrlSupported, jsonSchema, lazySchema, loadApiKey, loadOptionalSetting, loadSetting, mediaTypeToExtension, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, readResponseWithSizeLimit, removeUndefinedEntries, resolve, retryWithExponentialBackoff, safeParseJSON, safeValidateTypes, secureJsonParse, stripFileExtension, tool, validateDownloadUrl, validateTypes, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
1752
+ /**
1753
+ * Serializes a value as JSON, representing BigInt values as decimal strings and
1754
+ * ancestor cycles as "[Circular]". Reused objects, toJSON methods, and other JSON
1755
+ * serialization behavior are preserved. Getters and toJSON methods may throw.
1756
+ */
1757
+ declare function stringifyWithBigIntAndCycles(value: unknown): string;
1758
+
1759
+ export { type AssistantContent, type AssistantModelMessage, DEFAULT_MAX_DOWNLOAD_SIZE, type DataContent, DelayedPromise, DownloadError, EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL as EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL, EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER as EXPERIMENTAL_EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER, type EmbeddingModelProviderOptionsTransformer, type FetchFunction, type FilePart, type FlexibleSchema, type IdGenerator, type ImagePart, type InferSchema, type InferToolInput, type InferToolOutput, type LazySchema, type MaybePromiseLike, type ModelMessage, type ParseResult, type ProviderOptions, type ProviderToolFactory, type ProviderToolFactoryWithOutputSchema, type ReasoningPart, type Resolvable, type ResponseHandler, type RetryDelayProvider, type RetryErrorFactory, type RetryErrorReason, type RetryFunction, type Schema, type ShouldRetryFunction, type StreamingToolCallDelta, StreamingToolCallTracker, type StreamingToolCallTrackerOptions, type SystemModelMessage, type TextPart, type Tool, type ToolApprovalRequest, type ToolApprovalResponse, type ToolCall, type ToolCallOptions, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolExecutionOptions, type ToolModelMessage, type ToolNameMapping, type ToolNeedsApprovalFunction, type ToolResult, type ToolResultOutput, type ToolResultPart, type UserContent, type UserModelMessage, VERSION, type ValidationResult, asSchema, cancelResponseBody, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertImageModelFileToDataUri, convertToBase64, convertToFormData, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createProviderToolFactory, createProviderToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, createToolNameMapping, delay, downloadBlob, dynamicTool, encodePathSegment, executeTool, extractResponseHeaders, fetchWithValidatedEndpoint, fetchWithValidatedRedirects, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isArrayBuffer, isBrowserRuntime, isNonNullable, isParsableJson, isSameOrigin, isUint8Array, isUrlSupported, jsonSchema, lazySchema, loadApiKey, loadOptionalSetting, loadSetting, mediaTypeToExtension, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, readResponseWithSizeLimit, removeUndefinedEntries, resolve, retryWithExponentialBackoff, safeParseJSON, safeValidateTypes, secureJsonParse, stringifyWithBigIntAndCycles, stripFileExtension, tool, validateDownloadUrl, validateTypes, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
package/dist/index.d.ts CHANGED
@@ -258,6 +258,9 @@ declare function fetchWithValidatedEndpoint({ url, init, fetch: customFetch, tru
258
258
  * target (e.g. an internal address) before we ever see its URL, defeating the
259
259
  * guard.
260
260
  *
261
+ * Manually followed redirects from HTTPS to HTTP are rejected before requesting
262
+ * the target.
263
+ *
261
264
  * Request headers are also protected: {@link sanitizeRequestHeaders} strips
262
265
  * proxy/metadata/cookie/hop-by-hop headers before the first request, and all
263
266
  * caller headers except `User-Agent` are dropped on a cross-origin redirect.
@@ -1599,6 +1602,8 @@ declare function stripFileExtension(filename: string): string;
1599
1602
 
1600
1603
  declare function convertBase64ToUint8Array(base64String: string): Uint8Array<ArrayBuffer>;
1601
1604
  declare function convertUint8ArrayToBase64(array: Uint8Array): string;
1605
+ declare function isUint8Array(value: unknown): value is Uint8Array;
1606
+ declare function isArrayBuffer(value: unknown): value is ArrayBuffer;
1602
1607
  declare function convertToBase64(value: string | Uint8Array): string;
1603
1608
 
1604
1609
  /**
@@ -1744,4 +1749,11 @@ interface ToolResult<NAME extends string, INPUT, OUTPUT> {
1744
1749
  */
1745
1750
  type ToolCallOptions = ToolExecutionOptions;
1746
1751
 
1747
- export { type AssistantContent, type AssistantModelMessage, DEFAULT_MAX_DOWNLOAD_SIZE, type DataContent, DelayedPromise, DownloadError, EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL as EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL, EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER as EXPERIMENTAL_EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER, type EmbeddingModelProviderOptionsTransformer, type FetchFunction, type FilePart, type FlexibleSchema, type IdGenerator, type ImagePart, type InferSchema, type InferToolInput, type InferToolOutput, type LazySchema, type MaybePromiseLike, type ModelMessage, type ParseResult, type ProviderOptions, type ProviderToolFactory, type ProviderToolFactoryWithOutputSchema, type ReasoningPart, type Resolvable, type ResponseHandler, type RetryDelayProvider, type RetryErrorFactory, type RetryErrorReason, type RetryFunction, type Schema, type ShouldRetryFunction, type StreamingToolCallDelta, StreamingToolCallTracker, type StreamingToolCallTrackerOptions, type SystemModelMessage, type TextPart, type Tool, type ToolApprovalRequest, type ToolApprovalResponse, type ToolCall, type ToolCallOptions, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolExecutionOptions, type ToolModelMessage, type ToolNameMapping, type ToolNeedsApprovalFunction, type ToolResult, type ToolResultOutput, type ToolResultPart, type UserContent, type UserModelMessage, VERSION, type ValidationResult, asSchema, cancelResponseBody, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertImageModelFileToDataUri, convertToBase64, convertToFormData, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createProviderToolFactory, createProviderToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, createToolNameMapping, delay, downloadBlob, dynamicTool, encodePathSegment, executeTool, extractResponseHeaders, fetchWithValidatedEndpoint, fetchWithValidatedRedirects, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isBrowserRuntime, isNonNullable, isParsableJson, isSameOrigin, isUrlSupported, jsonSchema, lazySchema, loadApiKey, loadOptionalSetting, loadSetting, mediaTypeToExtension, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, readResponseWithSizeLimit, removeUndefinedEntries, resolve, retryWithExponentialBackoff, safeParseJSON, safeValidateTypes, secureJsonParse, stripFileExtension, tool, validateDownloadUrl, validateTypes, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
1752
+ /**
1753
+ * Serializes a value as JSON, representing BigInt values as decimal strings and
1754
+ * ancestor cycles as "[Circular]". Reused objects, toJSON methods, and other JSON
1755
+ * serialization behavior are preserved. Getters and toJSON methods may throw.
1756
+ */
1757
+ declare function stringifyWithBigIntAndCycles(value: unknown): string;
1758
+
1759
+ export { type AssistantContent, type AssistantModelMessage, DEFAULT_MAX_DOWNLOAD_SIZE, type DataContent, DelayedPromise, DownloadError, EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL as EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL, EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER as EXPERIMENTAL_EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER, type EmbeddingModelProviderOptionsTransformer, type FetchFunction, type FilePart, type FlexibleSchema, type IdGenerator, type ImagePart, type InferSchema, type InferToolInput, type InferToolOutput, type LazySchema, type MaybePromiseLike, type ModelMessage, type ParseResult, type ProviderOptions, type ProviderToolFactory, type ProviderToolFactoryWithOutputSchema, type ReasoningPart, type Resolvable, type ResponseHandler, type RetryDelayProvider, type RetryErrorFactory, type RetryErrorReason, type RetryFunction, type Schema, type ShouldRetryFunction, type StreamingToolCallDelta, StreamingToolCallTracker, type StreamingToolCallTrackerOptions, type SystemModelMessage, type TextPart, type Tool, type ToolApprovalRequest, type ToolApprovalResponse, type ToolCall, type ToolCallOptions, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolExecutionOptions, type ToolModelMessage, type ToolNameMapping, type ToolNeedsApprovalFunction, type ToolResult, type ToolResultOutput, type ToolResultPart, type UserContent, type UserModelMessage, VERSION, type ValidationResult, asSchema, cancelResponseBody, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertImageModelFileToDataUri, convertToBase64, convertToFormData, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createProviderToolFactory, createProviderToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, createToolNameMapping, delay, downloadBlob, dynamicTool, encodePathSegment, executeTool, extractResponseHeaders, fetchWithValidatedEndpoint, fetchWithValidatedRedirects, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isArrayBuffer, isBrowserRuntime, isNonNullable, isParsableJson, isSameOrigin, isUint8Array, isUrlSupported, jsonSchema, lazySchema, loadApiKey, loadOptionalSetting, loadSetting, mediaTypeToExtension, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, readResponseWithSizeLimit, removeUndefinedEntries, resolve, retryWithExponentialBackoff, safeParseJSON, safeValidateTypes, secureJsonParse, stringifyWithBigIntAndCycles, stripFileExtension, tool, validateDownloadUrl, validateTypes, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
package/dist/index.js CHANGED
@@ -70,10 +70,12 @@ __export(index_exports, {
70
70
  getRuntimeEnvironmentUserAgent: () => getRuntimeEnvironmentUserAgent,
71
71
  injectJsonInstructionIntoMessages: () => injectJsonInstructionIntoMessages,
72
72
  isAbortError: () => isAbortError,
73
+ isArrayBuffer: () => isArrayBuffer,
73
74
  isBrowserRuntime: () => isBrowserRuntime,
74
75
  isNonNullable: () => isNonNullable,
75
76
  isParsableJson: () => isParsableJson,
76
77
  isSameOrigin: () => isSameOrigin,
78
+ isUint8Array: () => isUint8Array,
77
79
  isUrlSupported: () => isUrlSupported,
78
80
  jsonSchema: () => jsonSchema,
79
81
  lazySchema: () => lazySchema,
@@ -95,6 +97,7 @@ __export(index_exports, {
95
97
  safeParseJSON: () => safeParseJSON,
96
98
  safeValidateTypes: () => safeValidateTypes,
97
99
  secureJsonParse: () => secureJsonParse,
100
+ stringifyWithBigIntAndCycles: () => stringifyWithBigIntAndCycles,
98
101
  stripFileExtension: () => stripFileExtension,
99
102
  tool: () => tool,
100
103
  validateDownloadUrl: () => validateDownloadUrl,
@@ -272,7 +275,11 @@ var { btoa, atob } = globalThis;
272
275
  function convertBase64ToUint8Array(base64String) {
273
276
  const base64Url = base64String.replace(/-/g, "+").replace(/_/g, "/");
274
277
  const latin1string = atob(base64Url);
275
- return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0));
278
+ const bytes = new Uint8Array(latin1string.length);
279
+ for (let i = 0; i < latin1string.length; i++) {
280
+ bytes[i] = latin1string.charCodeAt(i);
281
+ }
282
+ return bytes;
276
283
  }
277
284
  function convertUint8ArrayToBase64(array) {
278
285
  var _a2;
@@ -290,8 +297,30 @@ function convertUint8ArrayToBase64(array) {
290
297
  }
291
298
  return btoa(chunks.join(""));
292
299
  }
300
+ var typedArrayTag = Object.getOwnPropertyDescriptor(
301
+ Object.getPrototypeOf(Uint8Array.prototype),
302
+ Symbol.toStringTag
303
+ ).get;
304
+ var arrayBufferByteLength = Object.getOwnPropertyDescriptor(
305
+ ArrayBuffer.prototype,
306
+ "byteLength"
307
+ ).get;
308
+ function isUint8Array(value) {
309
+ return ArrayBuffer.isView(value) && typedArrayTag.call(value) === "Uint8Array";
310
+ }
311
+ function isArrayBuffer(value) {
312
+ if (typeof value !== "object" || value === null || !("byteLength" in value)) {
313
+ return false;
314
+ }
315
+ try {
316
+ arrayBufferByteLength.call(value);
317
+ return true;
318
+ } catch (e) {
319
+ return false;
320
+ }
321
+ }
293
322
  function convertToBase64(value) {
294
- return value instanceof Uint8Array ? convertUint8ArrayToBase64(value) : value;
323
+ return isUint8Array(value) ? convertUint8ArrayToBase64(value) : value;
295
324
  }
296
325
 
297
326
  // src/convert-image-model-file-to-data-uri.ts
@@ -712,6 +741,12 @@ async function fetchWithValidatedRedirects({
712
741
  if (REDIRECT_STATUS_CODES.has(response.status) && location) {
713
742
  void cancelResponseBody(response);
714
743
  const nextUrl = new URL(location, currentUrl).toString();
744
+ if (new URL(currentUrl).protocol === "https:" && new URL(nextUrl).protocol === "http:") {
745
+ throw new DownloadError({
746
+ url,
747
+ message: "Redirect from HTTPS to HTTP was blocked"
748
+ });
749
+ }
715
750
  if (currentHeaders !== void 0 && !isSameOrigin(nextUrl, currentUrl)) {
716
751
  const userAgent = currentHeaders.get("user-agent");
717
752
  currentHeaders = new Headers(
@@ -1014,7 +1049,7 @@ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
1014
1049
  }
1015
1050
 
1016
1051
  // src/version.ts
1017
- var VERSION = true ? "4.0.63" : "0.0.0-test";
1052
+ var VERSION = true ? "4.0.65" : "0.0.0-test";
1018
1053
 
1019
1054
  // src/get-from-api.ts
1020
1055
  var getOriginalFetch = () => globalThis.fetch;
@@ -3659,6 +3694,27 @@ async function* executeTool({
3659
3694
 
3660
3695
  // src/index.ts
3661
3696
  var import_stream2 = require("eventsource-parser/stream");
3697
+
3698
+ // src/stringify-with-bigint-and-cycles.ts
3699
+ function stringifyWithBigIntAndCycles(value) {
3700
+ const ancestors = [];
3701
+ return JSON.stringify(value, function(_key, value2) {
3702
+ if (typeof value2 === "bigint") {
3703
+ return value2.toString();
3704
+ }
3705
+ if (typeof value2 !== "object" || value2 === null) {
3706
+ return value2;
3707
+ }
3708
+ while (ancestors.length > 0 && ancestors.at(-1) !== this) {
3709
+ ancestors.pop();
3710
+ }
3711
+ if (ancestors.includes(value2)) {
3712
+ return "[Circular]";
3713
+ }
3714
+ ancestors.push(value2);
3715
+ return value2;
3716
+ });
3717
+ }
3662
3718
  // Annotate the CommonJS export names for ESM import in node:
3663
3719
  0 && (module.exports = {
3664
3720
  DEFAULT_MAX_DOWNLOAD_SIZE,
@@ -3701,10 +3757,12 @@ var import_stream2 = require("eventsource-parser/stream");
3701
3757
  getRuntimeEnvironmentUserAgent,
3702
3758
  injectJsonInstructionIntoMessages,
3703
3759
  isAbortError,
3760
+ isArrayBuffer,
3704
3761
  isBrowserRuntime,
3705
3762
  isNonNullable,
3706
3763
  isParsableJson,
3707
3764
  isSameOrigin,
3765
+ isUint8Array,
3708
3766
  isUrlSupported,
3709
3767
  jsonSchema,
3710
3768
  lazySchema,
@@ -3726,6 +3784,7 @@ var import_stream2 = require("eventsource-parser/stream");
3726
3784
  safeParseJSON,
3727
3785
  safeValidateTypes,
3728
3786
  secureJsonParse,
3787
+ stringifyWithBigIntAndCycles,
3729
3788
  stripFileExtension,
3730
3789
  tool,
3731
3790
  validateDownloadUrl,