@ai-sdk/provider-utils 3.0.40 → 3.0.42

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,20 @@
1
1
  # @ai-sdk/provider-utils
2
2
 
3
+ ## 3.0.42
4
+
5
+ ### Patch Changes
6
+
7
+ - d7b0ffa: Block `.internal` hostnames in download URL validation.
8
+ - 4146790: Encode provider-returned identifiers in follow-up request paths with a shared encodePathSegment helper.
9
+
10
+ ## 3.0.41
11
+
12
+ ### Patch Changes
13
+
14
+ - 2b1c2df: 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.
15
+ - 2b1c2df: fix(mcp): prevent SSRF in OAuth metadata discovery
16
+ - 2b1c2df: fix(provider-utils): make lazy Undici import visible to deployment tracers
17
+
3
18
  ## 3.0.40
4
19
 
5
20
  ### Patch Changes
package/dist/index.d.mts CHANGED
@@ -80,6 +80,30 @@ declare class DownloadError extends AISDKError {
80
80
  */
81
81
  declare const EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL: unique symbol;
82
82
 
83
+ /**
84
+ * Fetch function type (standardizes the version of fetch used).
85
+ */
86
+ type FetchFunction = typeof globalThis.fetch;
87
+
88
+ /**
89
+ * Fetches one validated URL without following redirects.
90
+ *
91
+ * On Node.js, the default fetch validates and pins DNS results at connect time.
92
+ * An injected fetch is responsible for equivalent connect-time validation.
93
+ * Redirects are rejected by default. Callers using `redirect: 'manual'` must
94
+ * validate the Location target before issuing another request.
95
+ */
96
+ declare function fetchWithValidatedEndpoint({ url, init, fetch: customFetch, trustedOrigin, redirect, }: {
97
+ url: string | URL;
98
+ init?: RequestInit;
99
+ fetch?: FetchFunction;
100
+ /**
101
+ * A developer-configured origin that may legitimately resolve to a private
102
+ * address. This must never be derived from untrusted response data.
103
+ */
104
+ trustedOrigin?: string;
105
+ redirect?: 'error' | 'manual';
106
+ }): Promise<Response>;
83
107
  /**
84
108
  * Fetches a URL while enforcing the SSRF download guard on every hop.
85
109
  *
@@ -97,6 +121,13 @@ declare const EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL: unique symbol;
97
121
  * runtime we cannot validate the hop, so we fail closed rather than follow it
98
122
  * blindly and bypass the SSRF guard.
99
123
  *
124
+ * A hop that is same-origin with `trustedOrigin` (the developer-configured
125
+ * endpoint) skips target validation: that origin is exactly what an
126
+ * unvalidated, config-derived request would fetch anyway, and validating it
127
+ * would break legitimate self-hosted / localhost deployments whose response
128
+ * URLs point back at the configured host. Hops on any other origin are always
129
+ * validated.
130
+ *
100
131
  * The returned response is the final (non-redirect) response. The caller is
101
132
  * responsible for checking `response.ok` and reading the body.
102
133
  *
@@ -108,11 +139,17 @@ declare const EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL: unique symbol;
108
139
  * @throws DownloadError if a hop is unsafe, the redirect limit is exceeded, or
109
140
  * a redirect cannot be validated on a non-browser runtime.
110
141
  */
111
- declare function fetchWithValidatedRedirects({ url, headers, abortSignal, maxRedirects, }: {
142
+ declare function fetchWithValidatedRedirects({ url, headers, abortSignal, maxRedirects, fetch: customFetch, trustedOrigin, }: {
112
143
  url: string;
113
144
  headers?: HeadersInit;
114
145
  abortSignal?: AbortSignal;
115
146
  maxRedirects?: number;
147
+ fetch?: FetchFunction;
148
+ /**
149
+ * A developer-configured origin whose hops skip target validation. Must
150
+ * never be derived from response data.
151
+ */
152
+ trustedOrigin?: string;
116
153
  }): Promise<Response>;
117
154
 
118
155
  /**
@@ -156,11 +193,6 @@ declare function readResponseWithSizeLimit({ response, url, maxBytes, }: {
156
193
  maxBytes?: number;
157
194
  }): Promise<Uint8Array>;
158
195
 
159
- /**
160
- * Fetch function type (standardizes the version of fetch used).
161
- */
162
- type FetchFunction = typeof globalThis.fetch;
163
-
164
196
  /**
165
197
  Creates an ID generator.
166
198
  The total length of the ID is the sum of the prefix, separator, and random part length.
@@ -187,6 +219,13 @@ Not cryptographically secure.
187
219
  */
188
220
  declare const generateId: IdGenerator;
189
221
 
222
+ /**
223
+ * Encodes a raw identifier as one URL path segment, including standalone dot
224
+ * segments that URL parsers would otherwise normalize. Pass unencoded values;
225
+ * for resource paths with intentional slashes, encode each segment separately.
226
+ */
227
+ declare function encodePathSegment(value: string): string;
228
+
190
229
  declare function getErrorMessage(error: unknown | undefined): string;
191
230
 
192
231
  /**
@@ -1165,4 +1204,4 @@ interface ToolResult<NAME extends string, INPUT, OUTPUT> {
1165
1204
  dynamic?: boolean;
1166
1205
  }
1167
1206
 
1168
- 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, type FetchFunction, type FilePart, type FlexibleSchema, type FlexibleValidator, type IdGenerator, type ImagePart, type InferSchema, type InferToolInput, type InferToolOutput, type InferValidator, type LazySchema, type LazyValidator, type ModelMessage, type ParseResult, type ProviderDefinedToolFactory, type ProviderDefinedToolFactoryWithOutputSchema, type ProviderOptions, type ReasoningPart, type Resolvable, type ResponseHandler, type Schema, type StreamingToolCallDelta, StreamingToolCallTracker, type StreamingToolCallTrackerOptions, type SystemModelMessage, type TextPart, type Tool, type ToolCall, type ToolCallOptions, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolModelMessage, type ToolResult, type ToolResultPart, type UserContent, type UserModelMessage, VERSION, type ValidationResult, type Validator, asSchema, asValidator, cancelResponseBody, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertToBase64, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createJsonStreamResponseHandler, createProviderDefinedToolFactory, createProviderDefinedToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, delay, dynamicTool, executeTool, extractResponseHeaders, fetchWithValidatedRedirects, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isBrowserRuntime, isParsableJson, isSameOrigin, isUrlSupported, isValidator, jsonSchema, lazySchema, lazyValidator, loadApiKey, loadOptionalSetting, loadSetting, mediaTypeToExtension, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, readResponseWithSizeLimit, removeUndefinedEntries, resolve, safeParseJSON, safeValidateTypes, standardSchemaValidator, tool, validateDownloadUrl, validateTypes, validator, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
1207
+ 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, type FetchFunction, type FilePart, type FlexibleSchema, type FlexibleValidator, type IdGenerator, type ImagePart, type InferSchema, type InferToolInput, type InferToolOutput, type InferValidator, type LazySchema, type LazyValidator, type ModelMessage, type ParseResult, type ProviderDefinedToolFactory, type ProviderDefinedToolFactoryWithOutputSchema, type ProviderOptions, type ReasoningPart, type Resolvable, type ResponseHandler, type Schema, type StreamingToolCallDelta, StreamingToolCallTracker, type StreamingToolCallTrackerOptions, type SystemModelMessage, type TextPart, type Tool, type ToolCall, type ToolCallOptions, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolModelMessage, type ToolResult, type ToolResultPart, type UserContent, type UserModelMessage, VERSION, type ValidationResult, type Validator, asSchema, asValidator, cancelResponseBody, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertToBase64, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createJsonStreamResponseHandler, createProviderDefinedToolFactory, createProviderDefinedToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, delay, dynamicTool, encodePathSegment, executeTool, extractResponseHeaders, fetchWithValidatedEndpoint, fetchWithValidatedRedirects, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isBrowserRuntime, isParsableJson, isSameOrigin, isUrlSupported, isValidator, jsonSchema, lazySchema, lazyValidator, loadApiKey, loadOptionalSetting, loadSetting, mediaTypeToExtension, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, readResponseWithSizeLimit, removeUndefinedEntries, resolve, safeParseJSON, safeValidateTypes, standardSchemaValidator, tool, validateDownloadUrl, validateTypes, validator, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
package/dist/index.d.ts CHANGED
@@ -80,6 +80,30 @@ declare class DownloadError extends AISDKError {
80
80
  */
81
81
  declare const EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL: unique symbol;
82
82
 
83
+ /**
84
+ * Fetch function type (standardizes the version of fetch used).
85
+ */
86
+ type FetchFunction = typeof globalThis.fetch;
87
+
88
+ /**
89
+ * Fetches one validated URL without following redirects.
90
+ *
91
+ * On Node.js, the default fetch validates and pins DNS results at connect time.
92
+ * An injected fetch is responsible for equivalent connect-time validation.
93
+ * Redirects are rejected by default. Callers using `redirect: 'manual'` must
94
+ * validate the Location target before issuing another request.
95
+ */
96
+ declare function fetchWithValidatedEndpoint({ url, init, fetch: customFetch, trustedOrigin, redirect, }: {
97
+ url: string | URL;
98
+ init?: RequestInit;
99
+ fetch?: FetchFunction;
100
+ /**
101
+ * A developer-configured origin that may legitimately resolve to a private
102
+ * address. This must never be derived from untrusted response data.
103
+ */
104
+ trustedOrigin?: string;
105
+ redirect?: 'error' | 'manual';
106
+ }): Promise<Response>;
83
107
  /**
84
108
  * Fetches a URL while enforcing the SSRF download guard on every hop.
85
109
  *
@@ -97,6 +121,13 @@ declare const EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL: unique symbol;
97
121
  * runtime we cannot validate the hop, so we fail closed rather than follow it
98
122
  * blindly and bypass the SSRF guard.
99
123
  *
124
+ * A hop that is same-origin with `trustedOrigin` (the developer-configured
125
+ * endpoint) skips target validation: that origin is exactly what an
126
+ * unvalidated, config-derived request would fetch anyway, and validating it
127
+ * would break legitimate self-hosted / localhost deployments whose response
128
+ * URLs point back at the configured host. Hops on any other origin are always
129
+ * validated.
130
+ *
100
131
  * The returned response is the final (non-redirect) response. The caller is
101
132
  * responsible for checking `response.ok` and reading the body.
102
133
  *
@@ -108,11 +139,17 @@ declare const EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL: unique symbol;
108
139
  * @throws DownloadError if a hop is unsafe, the redirect limit is exceeded, or
109
140
  * a redirect cannot be validated on a non-browser runtime.
110
141
  */
111
- declare function fetchWithValidatedRedirects({ url, headers, abortSignal, maxRedirects, }: {
142
+ declare function fetchWithValidatedRedirects({ url, headers, abortSignal, maxRedirects, fetch: customFetch, trustedOrigin, }: {
112
143
  url: string;
113
144
  headers?: HeadersInit;
114
145
  abortSignal?: AbortSignal;
115
146
  maxRedirects?: number;
147
+ fetch?: FetchFunction;
148
+ /**
149
+ * A developer-configured origin whose hops skip target validation. Must
150
+ * never be derived from response data.
151
+ */
152
+ trustedOrigin?: string;
116
153
  }): Promise<Response>;
117
154
 
118
155
  /**
@@ -156,11 +193,6 @@ declare function readResponseWithSizeLimit({ response, url, maxBytes, }: {
156
193
  maxBytes?: number;
157
194
  }): Promise<Uint8Array>;
158
195
 
159
- /**
160
- * Fetch function type (standardizes the version of fetch used).
161
- */
162
- type FetchFunction = typeof globalThis.fetch;
163
-
164
196
  /**
165
197
  Creates an ID generator.
166
198
  The total length of the ID is the sum of the prefix, separator, and random part length.
@@ -187,6 +219,13 @@ Not cryptographically secure.
187
219
  */
188
220
  declare const generateId: IdGenerator;
189
221
 
222
+ /**
223
+ * Encodes a raw identifier as one URL path segment, including standalone dot
224
+ * segments that URL parsers would otherwise normalize. Pass unencoded values;
225
+ * for resource paths with intentional slashes, encode each segment separately.
226
+ */
227
+ declare function encodePathSegment(value: string): string;
228
+
190
229
  declare function getErrorMessage(error: unknown | undefined): string;
191
230
 
192
231
  /**
@@ -1165,4 +1204,4 @@ interface ToolResult<NAME extends string, INPUT, OUTPUT> {
1165
1204
  dynamic?: boolean;
1166
1205
  }
1167
1206
 
1168
- 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, type FetchFunction, type FilePart, type FlexibleSchema, type FlexibleValidator, type IdGenerator, type ImagePart, type InferSchema, type InferToolInput, type InferToolOutput, type InferValidator, type LazySchema, type LazyValidator, type ModelMessage, type ParseResult, type ProviderDefinedToolFactory, type ProviderDefinedToolFactoryWithOutputSchema, type ProviderOptions, type ReasoningPart, type Resolvable, type ResponseHandler, type Schema, type StreamingToolCallDelta, StreamingToolCallTracker, type StreamingToolCallTrackerOptions, type SystemModelMessage, type TextPart, type Tool, type ToolCall, type ToolCallOptions, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolModelMessage, type ToolResult, type ToolResultPart, type UserContent, type UserModelMessage, VERSION, type ValidationResult, type Validator, asSchema, asValidator, cancelResponseBody, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertToBase64, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createJsonStreamResponseHandler, createProviderDefinedToolFactory, createProviderDefinedToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, delay, dynamicTool, executeTool, extractResponseHeaders, fetchWithValidatedRedirects, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isBrowserRuntime, isParsableJson, isSameOrigin, isUrlSupported, isValidator, jsonSchema, lazySchema, lazyValidator, loadApiKey, loadOptionalSetting, loadSetting, mediaTypeToExtension, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, readResponseWithSizeLimit, removeUndefinedEntries, resolve, safeParseJSON, safeValidateTypes, standardSchemaValidator, tool, validateDownloadUrl, validateTypes, validator, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
1207
+ 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, type FetchFunction, type FilePart, type FlexibleSchema, type FlexibleValidator, type IdGenerator, type ImagePart, type InferSchema, type InferToolInput, type InferToolOutput, type InferValidator, type LazySchema, type LazyValidator, type ModelMessage, type ParseResult, type ProviderDefinedToolFactory, type ProviderDefinedToolFactoryWithOutputSchema, type ProviderOptions, type ReasoningPart, type Resolvable, type ResponseHandler, type Schema, type StreamingToolCallDelta, StreamingToolCallTracker, type StreamingToolCallTrackerOptions, type SystemModelMessage, type TextPart, type Tool, type ToolCall, type ToolCallOptions, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolModelMessage, type ToolResult, type ToolResultPart, type UserContent, type UserModelMessage, VERSION, type ValidationResult, type Validator, asSchema, asValidator, cancelResponseBody, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertToBase64, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createJsonStreamResponseHandler, createProviderDefinedToolFactory, createProviderDefinedToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, delay, dynamicTool, encodePathSegment, executeTool, extractResponseHeaders, fetchWithValidatedEndpoint, fetchWithValidatedRedirects, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isBrowserRuntime, isParsableJson, isSameOrigin, isUrlSupported, isValidator, jsonSchema, lazySchema, lazyValidator, loadApiKey, loadOptionalSetting, loadSetting, mediaTypeToExtension, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, readResponseWithSizeLimit, removeUndefinedEntries, resolve, safeParseJSON, safeValidateTypes, standardSchemaValidator, tool, validateDownloadUrl, validateTypes, validator, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
package/dist/index.js CHANGED
@@ -57,8 +57,10 @@ __export(index_exports, {
57
57
  createStatusCodeErrorResponseHandler: () => createStatusCodeErrorResponseHandler,
58
58
  delay: () => delay,
59
59
  dynamicTool: () => dynamicTool,
60
+ encodePathSegment: () => encodePathSegment,
60
61
  executeTool: () => executeTool,
61
62
  extractResponseHeaders: () => extractResponseHeaders,
63
+ fetchWithValidatedEndpoint: () => fetchWithValidatedEndpoint,
62
64
  fetchWithValidatedRedirects: () => fetchWithValidatedRedirects,
63
65
  generateId: () => generateId,
64
66
  getErrorMessage: () => getErrorMessage,
@@ -276,6 +278,15 @@ function isBrowserRuntime(globalThisAny = globalThis) {
276
278
  return globalThisAny.window != null;
277
279
  }
278
280
 
281
+ // src/is-same-origin.ts
282
+ function isSameOrigin(url, baseUrl) {
283
+ try {
284
+ return new URL(url).origin === new URL(baseUrl).origin;
285
+ } catch (e) {
286
+ return false;
287
+ }
288
+ }
289
+
279
290
  // src/validate-download-url.ts
280
291
  function validateDownloadUrl(url) {
281
292
  let parsed;
@@ -303,7 +314,7 @@ function validateDownloadUrl(url) {
303
314
  message: `URL must have a hostname`
304
315
  });
305
316
  }
306
- if (hostname === "localhost" || hostname.endsWith(".local") || hostname.endsWith(".localhost")) {
317
+ if (hostname === "localhost" || hostname.endsWith(".local") || hostname.endsWith(".localhost") || hostname.endsWith(".internal")) {
307
318
  throw new DownloadError({
308
319
  url,
309
320
  message: `URL with hostname ${hostname} is not allowed`
@@ -461,34 +472,24 @@ function createSafeLookup(lookup) {
461
472
  });
462
473
  }
463
474
  var safeNodeFetchPromise;
464
- var initialGlobalFetch = globalThis.fetch;
465
- var initialGlobalFetchIsNodeDefault = isNodeDefaultFetch(initialGlobalFetch);
466
475
  function isNodeRuntime() {
467
- var _a2, _b2;
476
+ var _a2, _b2, _c;
468
477
  const runtimeProcess = globalThis.process;
469
- return ((_a2 = runtimeProcess == null ? void 0 : runtimeProcess.release) == null ? void 0 : _a2.name) === "node" && ((_b2 = runtimeProcess.versions) == null ? void 0 : _b2.bun) == null;
478
+ 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;
470
479
  }
471
480
  async function getDefaultDownloadFetch() {
472
- if (!isNodeRuntime() || !initialGlobalFetchIsNodeDefault || globalThis.fetch !== initialGlobalFetch) {
481
+ if (!isNodeRuntime()) {
473
482
  return globalThis.fetch;
474
483
  }
475
484
  return safeNodeFetchPromise != null ? safeNodeFetchPromise : safeNodeFetchPromise = createSafeNodeFetch();
476
485
  }
477
- function isNodeDefaultFetch(fetch) {
478
- if (typeof fetch !== "function") {
479
- return false;
480
- }
481
- const source = Function.prototype.toString.call(fetch);
482
- return source.includes("internal/deps/undici") || source.includes("lazy loading of undici");
483
- }
484
486
  async function createSafeNodeFetch() {
485
- const [{ createRequire }, { lookup }] = await Promise.all([
487
+ const [module2, { lookup }] = await Promise.all([
486
488
  loadNodeModule("node:module"),
487
489
  loadNodeModule("node:dns")
488
490
  ]);
489
- const { Agent, fetch } = createRequire(getCurrentModulePath())(
490
- "undici"
491
- );
491
+ const nodeRequire = module2.createRequire(getCurrentModulePath());
492
+ const { Agent, fetch } = nodeRequire("undici");
492
493
  const dispatcher = new Agent({
493
494
  connect: {
494
495
  lookup: createSafeLookup(lookup)
@@ -530,20 +531,47 @@ function getCurrentModulePath() {
530
531
 
531
532
  // src/fetch-with-validated-redirects.ts
532
533
  var MAX_DOWNLOAD_REDIRECTS = 10;
534
+ async function getValidatedFetch(customFetch) {
535
+ return customFetch == null || customFetch === globalThis.fetch ? await getDefaultDownloadFetch() : customFetch;
536
+ }
537
+ async function fetchWithValidatedEndpoint({
538
+ url,
539
+ init,
540
+ fetch: customFetch,
541
+ trustedOrigin,
542
+ redirect = "error"
543
+ }) {
544
+ const urlText = url.toString();
545
+ const isTrusted = trustedOrigin !== void 0 && isSameOrigin(urlText, trustedOrigin);
546
+ if (!isTrusted) {
547
+ validateDownloadUrl(urlText);
548
+ }
549
+ const fetch = isTrusted && customFetch != null ? customFetch : isTrusted ? globalThis.fetch : await getValidatedFetch(customFetch);
550
+ return await fetch(url, {
551
+ ...init,
552
+ redirect
553
+ });
554
+ }
533
555
  async function fetchWithValidatedRedirects({
534
556
  url,
535
557
  headers,
536
558
  abortSignal,
537
- maxRedirects = MAX_DOWNLOAD_REDIRECTS
559
+ maxRedirects = MAX_DOWNLOAD_REDIRECTS,
560
+ fetch: customFetch,
561
+ trustedOrigin
538
562
  }) {
563
+ var _a2;
539
564
  const baseInit = { signal: abortSignal };
540
565
  if (headers !== void 0) {
541
566
  baseInit.headers = headers;
542
567
  }
543
568
  let currentUrl = url;
544
569
  for (let redirectCount = 0; redirectCount <= maxRedirects; redirectCount++) {
545
- validateDownloadUrl(currentUrl);
546
- const fetch = await getDefaultDownloadFetch();
570
+ const isTrustedHop = trustedOrigin !== void 0 && isSameOrigin(currentUrl, trustedOrigin);
571
+ if (!isTrustedHop) {
572
+ validateDownloadUrl(currentUrl);
573
+ }
574
+ const fetch = isTrustedHop && customFetch != null ? customFetch : isTrustedHop ? globalThis.fetch : await getValidatedFetch(customFetch);
547
575
  const response = await fetch(currentUrl, {
548
576
  ...baseInit,
549
577
  redirect: "manual"
@@ -557,7 +585,7 @@ async function fetchWithValidatedRedirects({
557
585
  }
558
586
  return await fetch(currentUrl, { ...baseInit, redirect: "follow" });
559
587
  }
560
- const location = response.headers.get("location");
588
+ const location = (_a2 = response.headers) == null ? void 0 : _a2.get("location");
561
589
  if (response.status >= 300 && response.status < 400 && location) {
562
590
  await cancelResponseBody(response);
563
591
  currentUrl = new URL(location, currentUrl).toString();
@@ -657,6 +685,12 @@ var createIdGenerator = ({
657
685
  };
658
686
  var generateId = createIdGenerator();
659
687
 
688
+ // src/encode-path-segment.ts
689
+ function encodePathSegment(value) {
690
+ const encodedValue = encodeURIComponent(value);
691
+ return encodedValue === "." ? "%252E" : encodedValue === ".." ? "%252E%252E" : encodedValue;
692
+ }
693
+
660
694
  // src/get-error-message.ts
661
695
  function getErrorMessage(error) {
662
696
  if (error == null) {
@@ -811,7 +845,7 @@ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
811
845
  }
812
846
 
813
847
  // src/version.ts
814
- var VERSION = true ? "3.0.40" : "0.0.0-test";
848
+ var VERSION = true ? "3.0.42" : "0.0.0-test";
815
849
 
816
850
  // src/get-from-api.ts
817
851
  var getOriginalFetch = () => globalThis.fetch;
@@ -922,15 +956,6 @@ function injectJsonInstructionIntoMessages({
922
956
  ];
923
957
  }
924
958
 
925
- // src/is-same-origin.ts
926
- function isSameOrigin(url, baseUrl) {
927
- try {
928
- return new URL(url).origin === new URL(baseUrl).origin;
929
- } catch (e) {
930
- return false;
931
- }
932
- }
933
-
934
959
  // src/is-url-supported.ts
935
960
  function isUrlSupported({
936
961
  mediaType,
@@ -3433,8 +3458,10 @@ var import_stream2 = require("eventsource-parser/stream");
3433
3458
  createStatusCodeErrorResponseHandler,
3434
3459
  delay,
3435
3460
  dynamicTool,
3461
+ encodePathSegment,
3436
3462
  executeTool,
3437
3463
  extractResponseHeaders,
3464
+ fetchWithValidatedEndpoint,
3438
3465
  fetchWithValidatedRedirects,
3439
3466
  generateId,
3440
3467
  getErrorMessage,