@ai-sdk/provider-utils 4.0.56 → 4.0.57

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,13 @@
1
1
  # @ai-sdk/provider-utils
2
2
 
3
+ ## 4.0.57
4
+
5
+ ### Patch Changes
6
+
7
+ - a9cea74: Keep default Node.js downloads protected by DNS validation and connection pinning when frameworks or instrumentation wrap global fetch before or after the SDK loads.
8
+ - a9cea74: fix(mcp): prevent SSRF in OAuth metadata discovery
9
+ - a9cea74: fix(provider-utils): make lazy Undici import visible to deployment tracers
10
+
3
11
  ## 4.0.56
4
12
 
5
13
  ### Patch Changes
package/dist/index.d.mts CHANGED
@@ -225,6 +225,30 @@ declare function readResponseWithSizeLimit({ response, url, maxBytes, }: {
225
225
  maxBytes?: number;
226
226
  }): Promise<Uint8Array>;
227
227
 
228
+ /**
229
+ * Fetch function type (standardizes the version of fetch used).
230
+ */
231
+ type FetchFunction = typeof globalThis.fetch;
232
+
233
+ /**
234
+ * Fetches one validated URL without following redirects.
235
+ *
236
+ * On Node.js, the default fetch validates and pins DNS results at connect time.
237
+ * An injected fetch is responsible for equivalent connect-time validation.
238
+ * Redirects are rejected by default. Callers using `redirect: 'manual'` must
239
+ * validate the Location target before issuing another request.
240
+ */
241
+ declare function fetchWithValidatedEndpoint({ url, init, fetch: customFetch, trustedOrigin, redirect, }: {
242
+ url: string | URL;
243
+ init?: RequestInit;
244
+ fetch?: FetchFunction;
245
+ /**
246
+ * A developer-configured origin that may legitimately resolve to a private
247
+ * address. This must never be derived from untrusted response data.
248
+ */
249
+ trustedOrigin?: string;
250
+ redirect?: 'error' | 'manual';
251
+ }): Promise<Response>;
228
252
  /**
229
253
  * Fetches a URL while enforcing the SSRF download guard on every hop.
230
254
  *
@@ -242,6 +266,13 @@ declare function readResponseWithSizeLimit({ response, url, maxBytes, }: {
242
266
  * runtime we cannot validate the hop, so we fail closed rather than follow it
243
267
  * blindly and bypass the SSRF guard.
244
268
  *
269
+ * A hop that is same-origin with `trustedOrigin` (the developer-configured
270
+ * endpoint) skips target validation: that origin is exactly what an
271
+ * unvalidated, config-derived request would fetch anyway, and validating it
272
+ * would break legitimate self-hosted / localhost deployments whose response
273
+ * URLs point back at the configured host. Hops on any other origin are always
274
+ * validated.
275
+ *
245
276
  * The returned response is the final (non-redirect) response. The caller is
246
277
  * responsible for checking `response.ok` and reading the body.
247
278
  *
@@ -253,18 +284,19 @@ declare function readResponseWithSizeLimit({ response, url, maxBytes, }: {
253
284
  * @throws DownloadError if a hop is unsafe, the redirect limit is exceeded, or
254
285
  * a redirect cannot be validated on a non-browser runtime.
255
286
  */
256
- declare function fetchWithValidatedRedirects({ url, headers, abortSignal, maxRedirects, }: {
287
+ declare function fetchWithValidatedRedirects({ url, headers, abortSignal, maxRedirects, fetch: customFetch, trustedOrigin, }: {
257
288
  url: string;
258
289
  headers?: HeadersInit;
259
290
  abortSignal?: AbortSignal;
260
291
  maxRedirects?: number;
292
+ fetch?: FetchFunction;
293
+ /**
294
+ * A developer-configured origin whose hops skip target validation. Must
295
+ * never be derived from response data.
296
+ */
297
+ trustedOrigin?: string;
261
298
  }): Promise<Response>;
262
299
 
263
- /**
264
- * Fetch function type (standardizes the version of fetch used).
265
- */
266
- type FetchFunction = typeof globalThis.fetch;
267
-
268
300
  /**
269
301
  * Creates an ID generator.
270
302
  * The total length of the ID is the sum of the prefix, separator, and random part length.
@@ -1656,4 +1688,4 @@ interface ToolResult<NAME extends string, INPUT, OUTPUT> {
1656
1688
  */
1657
1689
  type ToolCallOptions = ToolExecutionOptions;
1658
1690
 
1659
- 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, executeTool, extractResponseHeaders, 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 };
1691
+ 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, 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 };
package/dist/index.d.ts CHANGED
@@ -225,6 +225,30 @@ declare function readResponseWithSizeLimit({ response, url, maxBytes, }: {
225
225
  maxBytes?: number;
226
226
  }): Promise<Uint8Array>;
227
227
 
228
+ /**
229
+ * Fetch function type (standardizes the version of fetch used).
230
+ */
231
+ type FetchFunction = typeof globalThis.fetch;
232
+
233
+ /**
234
+ * Fetches one validated URL without following redirects.
235
+ *
236
+ * On Node.js, the default fetch validates and pins DNS results at connect time.
237
+ * An injected fetch is responsible for equivalent connect-time validation.
238
+ * Redirects are rejected by default. Callers using `redirect: 'manual'` must
239
+ * validate the Location target before issuing another request.
240
+ */
241
+ declare function fetchWithValidatedEndpoint({ url, init, fetch: customFetch, trustedOrigin, redirect, }: {
242
+ url: string | URL;
243
+ init?: RequestInit;
244
+ fetch?: FetchFunction;
245
+ /**
246
+ * A developer-configured origin that may legitimately resolve to a private
247
+ * address. This must never be derived from untrusted response data.
248
+ */
249
+ trustedOrigin?: string;
250
+ redirect?: 'error' | 'manual';
251
+ }): Promise<Response>;
228
252
  /**
229
253
  * Fetches a URL while enforcing the SSRF download guard on every hop.
230
254
  *
@@ -242,6 +266,13 @@ declare function readResponseWithSizeLimit({ response, url, maxBytes, }: {
242
266
  * runtime we cannot validate the hop, so we fail closed rather than follow it
243
267
  * blindly and bypass the SSRF guard.
244
268
  *
269
+ * A hop that is same-origin with `trustedOrigin` (the developer-configured
270
+ * endpoint) skips target validation: that origin is exactly what an
271
+ * unvalidated, config-derived request would fetch anyway, and validating it
272
+ * would break legitimate self-hosted / localhost deployments whose response
273
+ * URLs point back at the configured host. Hops on any other origin are always
274
+ * validated.
275
+ *
245
276
  * The returned response is the final (non-redirect) response. The caller is
246
277
  * responsible for checking `response.ok` and reading the body.
247
278
  *
@@ -253,18 +284,19 @@ declare function readResponseWithSizeLimit({ response, url, maxBytes, }: {
253
284
  * @throws DownloadError if a hop is unsafe, the redirect limit is exceeded, or
254
285
  * a redirect cannot be validated on a non-browser runtime.
255
286
  */
256
- declare function fetchWithValidatedRedirects({ url, headers, abortSignal, maxRedirects, }: {
287
+ declare function fetchWithValidatedRedirects({ url, headers, abortSignal, maxRedirects, fetch: customFetch, trustedOrigin, }: {
257
288
  url: string;
258
289
  headers?: HeadersInit;
259
290
  abortSignal?: AbortSignal;
260
291
  maxRedirects?: number;
292
+ fetch?: FetchFunction;
293
+ /**
294
+ * A developer-configured origin whose hops skip target validation. Must
295
+ * never be derived from response data.
296
+ */
297
+ trustedOrigin?: string;
261
298
  }): Promise<Response>;
262
299
 
263
- /**
264
- * Fetch function type (standardizes the version of fetch used).
265
- */
266
- type FetchFunction = typeof globalThis.fetch;
267
-
268
300
  /**
269
301
  * Creates an ID generator.
270
302
  * The total length of the ID is the sum of the prefix, separator, and random part length.
@@ -1656,4 +1688,4 @@ interface ToolResult<NAME extends string, INPUT, OUTPUT> {
1656
1688
  */
1657
1689
  type ToolCallOptions = ToolExecutionOptions;
1658
1690
 
1659
- 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, executeTool, extractResponseHeaders, 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 };
1691
+ 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, 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 };
package/dist/index.js CHANGED
@@ -61,6 +61,7 @@ __export(index_exports, {
61
61
  dynamicTool: () => dynamicTool,
62
62
  executeTool: () => executeTool,
63
63
  extractResponseHeaders: () => extractResponseHeaders,
64
+ fetchWithValidatedEndpoint: () => fetchWithValidatedEndpoint,
64
65
  fetchWithValidatedRedirects: () => fetchWithValidatedRedirects,
65
66
  generateId: () => generateId,
66
67
  getErrorMessage: () => getErrorMessage,
@@ -353,6 +354,15 @@ function isBrowserRuntime(globalThisAny = globalThis) {
353
354
  return globalThisAny.window != null;
354
355
  }
355
356
 
357
+ // src/is-same-origin.ts
358
+ function isSameOrigin(url, baseUrl) {
359
+ try {
360
+ return new URL(url).origin === new URL(baseUrl).origin;
361
+ } catch (e) {
362
+ return false;
363
+ }
364
+ }
365
+
356
366
  // src/validate-download-url.ts
357
367
  function validateDownloadUrl(url) {
358
368
  let parsed;
@@ -538,34 +548,24 @@ function createSafeLookup(lookup) {
538
548
  });
539
549
  }
540
550
  var safeNodeFetchPromise;
541
- var initialGlobalFetch = globalThis.fetch;
542
- var initialGlobalFetchIsNodeDefault = isNodeDefaultFetch(initialGlobalFetch);
543
551
  function isNodeRuntime() {
544
- var _a2, _b2;
552
+ var _a2, _b2, _c;
545
553
  const runtimeProcess = globalThis.process;
546
- return ((_a2 = runtimeProcess == null ? void 0 : runtimeProcess.release) == null ? void 0 : _a2.name) === "node" && ((_b2 = runtimeProcess.versions) == null ? void 0 : _b2.bun) == null;
554
+ return ((_a2 = runtimeProcess == null ? void 0 : runtimeProcess.release) == null ? void 0 : _a2.name) === "node" && ((_b2 = runtimeProcess.versions) == null ? void 0 : _b2.bun) == null && ((_c = runtimeProcess.versions) == null ? void 0 : _c.deno) == null && runtimeProcess.title !== "workerd" && globalThis.EdgeRuntime == null;
547
555
  }
548
556
  async function getDefaultDownloadFetch() {
549
- if (!isNodeRuntime() || !initialGlobalFetchIsNodeDefault || globalThis.fetch !== initialGlobalFetch) {
557
+ if (!isNodeRuntime()) {
550
558
  return globalThis.fetch;
551
559
  }
552
560
  return safeNodeFetchPromise != null ? safeNodeFetchPromise : safeNodeFetchPromise = createSafeNodeFetch();
553
561
  }
554
- function isNodeDefaultFetch(fetch) {
555
- if (typeof fetch !== "function") {
556
- return false;
557
- }
558
- const source = Function.prototype.toString.call(fetch);
559
- return source.includes("internal/deps/undici") || source.includes("lazy loading of undici");
560
- }
561
562
  async function createSafeNodeFetch() {
562
- const [{ createRequire }, { lookup }] = await Promise.all([
563
+ const [module2, { lookup }] = await Promise.all([
563
564
  loadNodeModule("node:module"),
564
565
  loadNodeModule("node:dns")
565
566
  ]);
566
- const { Agent, fetch } = createRequire(getCurrentModulePath())(
567
- "undici"
568
- );
567
+ const nodeRequire = module2.createRequire(getCurrentModulePath());
568
+ const { Agent, fetch } = nodeRequire("undici");
569
569
  const dispatcher = new Agent({
570
570
  connect: {
571
571
  lookup: createSafeLookup(lookup)
@@ -607,20 +607,47 @@ function getCurrentModulePath() {
607
607
 
608
608
  // src/fetch-with-validated-redirects.ts
609
609
  var MAX_DOWNLOAD_REDIRECTS = 10;
610
+ async function getValidatedFetch(customFetch) {
611
+ return customFetch == null || customFetch === globalThis.fetch ? await getDefaultDownloadFetch() : customFetch;
612
+ }
613
+ async function fetchWithValidatedEndpoint({
614
+ url,
615
+ init,
616
+ fetch: customFetch,
617
+ trustedOrigin,
618
+ redirect = "error"
619
+ }) {
620
+ const urlText = url.toString();
621
+ const isTrusted = trustedOrigin !== void 0 && isSameOrigin(urlText, trustedOrigin);
622
+ if (!isTrusted) {
623
+ validateDownloadUrl(urlText);
624
+ }
625
+ const fetch = isTrusted && customFetch != null ? customFetch : isTrusted ? globalThis.fetch : await getValidatedFetch(customFetch);
626
+ return await fetch(url, {
627
+ ...init,
628
+ redirect
629
+ });
630
+ }
610
631
  async function fetchWithValidatedRedirects({
611
632
  url,
612
633
  headers,
613
634
  abortSignal,
614
- maxRedirects = MAX_DOWNLOAD_REDIRECTS
635
+ maxRedirects = MAX_DOWNLOAD_REDIRECTS,
636
+ fetch: customFetch,
637
+ trustedOrigin
615
638
  }) {
639
+ var _a2;
616
640
  const baseInit = { signal: abortSignal };
617
641
  if (headers !== void 0) {
618
642
  baseInit.headers = headers;
619
643
  }
620
644
  let currentUrl = url;
621
645
  for (let redirectCount = 0; redirectCount <= maxRedirects; redirectCount++) {
622
- validateDownloadUrl(currentUrl);
623
- const fetch = await getDefaultDownloadFetch();
646
+ const isTrustedHop = trustedOrigin !== void 0 && isSameOrigin(currentUrl, trustedOrigin);
647
+ if (!isTrustedHop) {
648
+ validateDownloadUrl(currentUrl);
649
+ }
650
+ const fetch = isTrustedHop && customFetch != null ? customFetch : isTrustedHop ? globalThis.fetch : await getValidatedFetch(customFetch);
624
651
  const response = await fetch(currentUrl, {
625
652
  ...baseInit,
626
653
  redirect: "manual"
@@ -634,7 +661,7 @@ async function fetchWithValidatedRedirects({
634
661
  }
635
662
  return await fetch(currentUrl, { ...baseInit, redirect: "follow" });
636
663
  }
637
- const location = response.headers.get("location");
664
+ const location = (_a2 = response.headers) == null ? void 0 : _a2.get("location");
638
665
  if (response.status >= 300 && response.status < 400 && location) {
639
666
  await cancelResponseBody(response);
640
667
  currentUrl = new URL(location, currentUrl).toString();
@@ -927,7 +954,7 @@ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
927
954
  }
928
955
 
929
956
  // src/version.ts
930
- var VERSION = true ? "4.0.56" : "0.0.0-test";
957
+ var VERSION = true ? "4.0.57" : "0.0.0-test";
931
958
 
932
959
  // src/get-from-api.ts
933
960
  var getOriginalFetch = () => globalThis.fetch;
@@ -1043,15 +1070,6 @@ function isNonNullable(value) {
1043
1070
  return value != null;
1044
1071
  }
1045
1072
 
1046
- // src/is-same-origin.ts
1047
- function isSameOrigin(url, baseUrl) {
1048
- try {
1049
- return new URL(url).origin === new URL(baseUrl).origin;
1050
- } catch (e) {
1051
- return false;
1052
- }
1053
- }
1054
-
1055
1073
  // src/is-url-supported.ts
1056
1074
  function isUrlSupported({
1057
1075
  mediaType,
@@ -3603,6 +3621,7 @@ var import_stream2 = require("eventsource-parser/stream");
3603
3621
  dynamicTool,
3604
3622
  executeTool,
3605
3623
  extractResponseHeaders,
3624
+ fetchWithValidatedEndpoint,
3606
3625
  fetchWithValidatedRedirects,
3607
3626
  generateId,
3608
3627
  getErrorMessage,