@deepseek-ai/dsh-web-fetch-http 0.2.2-alpha.3 → 0.2.2-rc.2

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/lib/index.js CHANGED
@@ -178,6 +178,17 @@ const LOCAL_FETCH_PROVIDER_ID = "http";
178
178
  var HttpFetchProvider = class {
179
179
  limits;
180
180
  id = LOCAL_FETCH_PROVIDER_ID;
181
+ /** Picker description: what this provider suits and what it costs or cannot do. */
182
+ description = {
183
+ en: "Free, and can reach intranet and local addresses. Does not support pages that need JavaScript or sign-in, or PDFs.",
184
+ zh: "免费,可访问内网和本机。不支持需要 JavaScript 或登录的页面,也不支持 PDF。",
185
+ ja: "無料で、イントラネットやローカルのアドレスにもアクセスできます。JavaScript やログインが必要なページ、PDF には対応しません。",
186
+ es: "Gratis y puede acceder a direcciones de la intranet y locales. No admite páginas que requieran JavaScript o inicio de sesión, ni PDF.",
187
+ fr: "Gratuit, et accède aux adresses intranet et locales. Ne prend pas en charge les pages nécessitant JavaScript ou une connexion, ni les PDF.",
188
+ de: "Kostenlos und erreicht auch Intranet- und lokale Adressen. Keine Seiten, die JavaScript oder eine Anmeldung erfordern, und keine PDFs.",
189
+ ru: "Бесплатно, доступны адреса интрасети и локальные адреса. Не поддерживает страницы, требующие JavaScript или входа, а также PDF.",
190
+ pt: "Gratuito e acessa endereços da intranet e locais. Não oferece suporte a páginas que exigem JavaScript ou login, nem a PDFs."
191
+ };
181
192
  /** @param limits - resolved transport and response limits. */
182
193
  constructor(limits) {
183
194
  this.limits = limits;
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAClD,OAAO,CAAC,MAAM,0BAA0B,CAAA;AAOxC,OAAO,EACL,uBAAuB,EACvB,iBAAiB,GAClB,MAAM,eAA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AA2B;IAC3D,MAAM,QAAQ,GAAG,OAAO,IAAI,OAAO,CAAA;IACnC,IAAI,CAAC;QACH,OAAO,IAAI,WAAW,CAAC,QAAQ,CAAC,CAAA;IAClC,CAAC;IAAC,OAAO,KAAc,EAAE,CAAC;QACxB,IAAI,QAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC;YAAE,OAAO,IAAI,WAAW,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAA;QAChG,MAAM,IAAI,QAAQ,CAAC,wBAAwB,QAAQ,GAAG,EAAE,8BAA8B,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAA;IAC3G,CAAC;AACH,CAAC;AAED,mEAAmE;AACnE,SAAS,WAAW,CAAC,KAAa;IAChC,IAAI,CAAC;QACH,OAAO,IAAI,WAAW,CAAC,KAAK,CAAC,CAAC,QAAQ,KAAK,OAAO,CAAA;IACpD,CAAC;IAAC,OAAO,MAAe,EAAE,CAAC;QACzB,0DAA0D;QAC1D,OAAO,KAAK,CAAA;IACd,CAAC;AACH,CAAC"}
@@ -25,6 +25,8 @@ export declare const LOCAL_FETCH_PROVIDER_ID = "http";
25
25
  export declare class HttpFetchProvider implements WebFetchProvider {
26
26
  private readonly limits;
27
27
  readonly id = "http";
28
+ /** Picker description: what this provider suits and what it costs or cannot do. */
29
+ readonly description: NonNullable<WebFetchProvider['description']>;
28
30
  /** @param limits - resolved transport and response limits. */
29
31
  constructor(limits: HttpFetchLimits);
30
32
  /** No credentials to check — an anonymous fetcher is always usable. */
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../src/provider.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,KAAK,EAAgB,gBAAgB,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AAK3G,oFAAoF;AACpF,MAAM,WAAW,eAAe;IAC9B,uE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CAAC,8BAA8B,QAAQ,GAAG,EAAE,oBAAoB,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAA;IACvG,CAAC;AACH,CAAC;AAED;;;;;;;;;GASG;AACH,SAAS,uBAAuB,CAAC,KAAc,EAAE,MAAmB;IAClE,MAAM,OAAO,GAAG,SAAS,CAAC,MAAM,EAAE,mBAAmB,CAAC,CAAA;IACtD,IAAI,OAAO,KAAK,SAAS;QAAE,OAAO,IAAI,QAAQ,CAAC,qBAAqB,EAAE,mBAAmB,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAA;IAC9G,IAAI,MAAM,CAAC,OAAO;QAAE,OAAO,IAAI,QAAQ,CAAC,mBAAmB,EAAE,aAAa,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAA;IAC7F,OAAO,IAAI,QAAQ,CAAC,qBAAqB,MAAM,CAAC,KAAK,CAAC,EAAE,EAAE,oBAAoB,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAA;AACnG,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@deepseek-ai/dsh-web-fetch-http",
3
3
  "description": "Anonymous HTTP(S) fetch provider for the DeepSeek Harness web capability seam (ctx.web)",
4
- "version": "0.2.2-alpha.3",
4
+ "version": "0.2.2-rc.2",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -25,22 +25,25 @@
25
25
  "files": [
26
26
  "locale/*.json",
27
27
  "lib/index.js",
28
- "lib/types/**/*.d.ts"
28
+ "lib/types/**/*.d.ts",
29
+ "lib/types/**/*.d.ts.map",
30
+ "lib/**/*.js.map",
31
+ "src"
29
32
  ],
30
33
  "license": "MIT",
31
34
  "peerDependencies": {
32
- "@deepseek-ai/cordis": "~4.0.6-alpha.2",
33
- "@deepseek-ai/dsh-timeout": "0.2.2-alpha.3",
34
- "@deepseek-ai/dsh-web": "0.2.2-alpha.3"
35
+ "@deepseek-ai/cordis": "~4.1.0",
36
+ "@deepseek-ai/dsh-timeout": "0.2.2-rc.2",
37
+ "@deepseek-ai/dsh-web": "0.2.2-rc.2"
35
38
  },
36
39
  "dependencies": {
37
- "@deepseek-ai/schemastery": "~3.18.6-alpha.2",
40
+ "@deepseek-ai/schemastery": "~3.19.0",
38
41
  "undici": "8.11.2"
39
42
  },
40
43
  "devDependencies": {
41
- "@deepseek-ai/cordis": "~4.0.6-alpha.2",
42
- "@deepseek-ai/dsh-timeout": "0.2.2-alpha.3",
43
- "@deepseek-ai/dsh-web": "0.2.2-alpha.3",
44
- "@deepseek-ai/dsh-http-proxy": "0.2.2-alpha.3"
44
+ "@deepseek-ai/cordis": "~4.1.0",
45
+ "@deepseek-ai/dsh-timeout": "0.2.2-rc.2",
46
+ "@deepseek-ai/dsh-web": "0.2.2-rc.2",
47
+ "@deepseek-ai/dsh-http-proxy": "0.2.2-rc.2"
45
48
  }
46
49
  }
package/src/index.ts ADDED
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Anonymous HTTP(S) `WebFetchProvider` plugin. It contributes to the
3
+ * `ctx.web` registry without owning the service.
4
+ *
5
+ * @module @deepseek-ai/dsh-web-fetch-http
6
+ */
7
+
8
+ import type { Context } from '@deepseek-ai/cordis'
9
+ import z from '@deepseek-ai/schemastery'
10
+ import type {} from '@deepseek-ai/dsh-web'
11
+ import { HttpFetchProvider } from './provider.ts'
12
+ import type { HttpFetchLimits } from './provider.ts'
13
+
14
+ const MAX_NODE_TIMER_DELAY_MS = 2_147_483_647
15
+
16
+ export {
17
+ LOCAL_FETCH_PROVIDER_ID,
18
+ HttpFetchProvider,
19
+ } from './provider.ts'
20
+ export type { HttpFetchLimits } from './provider.ts'
21
+
22
+ /** Default `User-Agent`: an explicit product agent, never a browser disguise. */
23
+ export const DEFAULT_USER_AGENT = 'deepseek-harness/0.0.1 (+https://github.com/deepseek-ai)'
24
+
25
+ /** Cordis plugin name used by loader diagnostics. */
26
+ export const name = 'web-fetch-http'
27
+
28
+ /** The web seam this provider registers into. */
29
+ export const inject = ['web']
30
+
31
+ /** Plugin config: the provider's transport and size limits plus its `User-Agent` (all defaulted). */
32
+ export interface Config {
33
+ /** Maximum response body size in bytes. */
34
+ maxResponseBytes?: number
35
+ /** Maximum decoded body length in characters. */
36
+ maxBodyChars?: number
37
+ /** Default fetch timeout in milliseconds, within Node's timer range. */
38
+ timeoutMs?: number
39
+ /** Maximum number of same-origin redirect hops to follow. */
40
+ maxRedirects?: number
41
+ /** `User-Agent` header sent on every request. */
42
+ userAgent?: string
43
+ }
44
+
45
+ export const Config: z<Config> = z.object({
46
+ maxResponseBytes: z.number().default(5_000_000),
47
+ maxBodyChars: z.number().default(100_000),
48
+ timeoutMs: z.number().default(30_000),
49
+ maxRedirects: z.number().default(5),
50
+ userAgent: z.string().default(DEFAULT_USER_AGENT),
51
+ })
52
+
53
+ /** Complete config after schemastery applies every field default. */
54
+ type ResolvedConfig = Required<Config>
55
+
56
+ /** A resource limit (byte/char/length/timeout cap) must be a positive finite number. */
57
+ function assertPositiveFinite(name: string, value: number): void {
58
+ if (!Number.isFinite(value) || value <= 0) {
59
+ throw new Error(`web-fetch-http: ${name} must be a positive finite number`)
60
+ }
61
+ }
62
+
63
+ /** Node coerces larger timer delays to 1 ms, so reject them at configuration time. */
64
+ function assertTimeoutMs(value: number): void {
65
+ assertPositiveFinite('timeoutMs', value)
66
+ if (value > MAX_NODE_TIMER_DELAY_MS) {
67
+ throw new Error(`web-fetch-http: timeoutMs must be no greater than ${MAX_NODE_TIMER_DELAY_MS}`)
68
+ }
69
+ }
70
+
71
+ /** The redirect hop cap must be a non-negative integer (0 follows no redirects). */
72
+ function assertNonNegativeInteger(name: string, value: number): void {
73
+ if (!Number.isInteger(value) || value < 0) {
74
+ throw new Error(`web-fetch-http: ${name} must be a non-negative integer`)
75
+ }
76
+ }
77
+
78
+ /** Register the local HTTP(S) fetch provider with `ctx.web`. */
79
+ export function apply(ctx: Context, config: Config): void {
80
+ // schemastery (Config) has already filled every defaulted field.
81
+ const resolved = config as ResolvedConfig
82
+ assertPositiveFinite('maxResponseBytes', resolved.maxResponseBytes)
83
+ assertPositiveFinite('maxBodyChars', resolved.maxBodyChars)
84
+ assertTimeoutMs(resolved.timeoutMs)
85
+ assertNonNegativeInteger('maxRedirects', resolved.maxRedirects)
86
+ const limits: HttpFetchLimits = {
87
+ maxResponseBytes: resolved.maxResponseBytes,
88
+ maxBodyChars: resolved.maxBodyChars,
89
+ timeoutMs: resolved.timeoutMs,
90
+ maxRedirects: resolved.maxRedirects,
91
+ userAgent: resolved.userAgent,
92
+ }
93
+ ctx.web.registerFetchProvider(new HttpFetchProvider(limits))
94
+ }
package/src/policy.ts ADDED
@@ -0,0 +1,125 @@
1
+ /**
2
+ * URL validation, content-type classification, and charset resolution for the
3
+ * local HTTP(S) fetch provider — the pure, network-free half. The provider's
4
+ * `fetch()` composes these with transport (redirect following, byte caps,
5
+ * decoding).
6
+ *
7
+ * @module @deepseek-ai/dsh-web-fetch-http/policy
8
+ */
9
+
10
+ import { WebError } from '@deepseek-ai/dsh-web'
11
+
12
+ /** Maximum accepted request URL length enforced by the fetch provider. */
13
+ export const WEB_FETCH_MAX_URL_LENGTH = 2048
14
+
15
+ /** The body kinds this provider decodes. */
16
+ export type FetchableKind = 'html' | 'text'
17
+
18
+ /**
19
+ * Parse a request URL and enforce network-independent transport restrictions:
20
+ * HTTP(S) only and no embedded credentials. The provider applies this before
21
+ * resolving a destination.
22
+ *
23
+ * @param input - the raw URL string from the fetch request.
24
+ * @returns the parsed `URL`.
25
+ */
26
+ export function parseFetchUrl(input: string): URL {
27
+ let url: URL
28
+ try {
29
+ url = new URL(input)
30
+ } catch (error: unknown) {
31
+ throw new WebError(`invalid URL: ${input}`, 'WEB_INVALID_URL', { cause: error })
32
+ }
33
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
34
+ throw new WebError(`unsupported URL scheme "${url.protocol}" (only http and https are allowed)`, 'WEB_INVALID_URL')
35
+ }
36
+ if (url.username.length > 0 || url.password.length > 0) {
37
+ throw new WebError('credentials in URLs are not allowed', 'WEB_BLOCKED_URL')
38
+ }
39
+ return url
40
+ }
41
+
42
+ /**
43
+ * Validate a request URL against the provider's complete pre-network policy:
44
+ * bounded length plus the restrictions enforced by {@link parseFetchUrl}.
45
+ * Public-address resolution and connection pinning run after this check.
46
+ *
47
+ * @param input - the raw URL string from the fetch request.
48
+ * @returns the parsed `URL`.
49
+ */
50
+ export function validateFetchUrl(input: string): URL {
51
+ if (input.length > WEB_FETCH_MAX_URL_LENGTH) {
52
+ throw new WebError(`URL exceeds the maximum length of ${WEB_FETCH_MAX_URL_LENGTH}`, 'WEB_INVALID_URL')
53
+ }
54
+ return parseFetchUrl(input)
55
+ }
56
+
57
+ /**
58
+ * Two URLs are same-origin when scheme, hostname, and port match. A redirect
59
+ * that crosses origins is refused so each new origin requires a fresh tool call.
60
+ *
61
+ * @param a - one of the two URLs to compare.
62
+ * @param b - the other URL to compare.
63
+ * @returns true when `a` and `b` share scheme, hostname, and port.
64
+ */
65
+ export function isSameOrigin(a: URL, b: URL): boolean {
66
+ return a.protocol === b.protocol && a.hostname === b.hostname && a.port === b.port
67
+ }
68
+
69
+ /**
70
+ * Classify a response `Content-Type` into a decodable body kind, or `undefined`
71
+ * for an unsupported (e.g. binary) type. `text/html` and `application/xhtml+xml`
72
+ * are `html`; other `text/*` plus a few structured text types are `text`.
73
+ *
74
+ * @param contentType - the raw `Content-Type` header, or `null` when the
75
+ * response carries none (unsupported).
76
+ * @returns the decodable kind, or `undefined` for an unsupported type.
77
+ */
78
+ export function classifyContentType(contentType: string | null): FetchableKind | undefined {
79
+ const mime = (contentType ?? '').replace(/;.*$/s, '').trim().toLowerCase()
80
+ if (mime === 'text/html' || mime === 'application/xhtml+xml') return 'html'
81
+ if (mime.startsWith('text/')) return 'text'
82
+ if (mime === 'application/json' || mime === 'application/xml' || mime.endsWith('+json') || mime.endsWith('+xml')) return 'text'
83
+ return undefined
84
+ }
85
+
86
+ /**
87
+ * Extract the lower-cased `charset` parameter from a response `Content-Type`.
88
+ *
89
+ * @param contentType - the raw header, or `null` when absent.
90
+ * @returns the charset parameter, or `undefined` when none is declared.
91
+ */
92
+ export function parseCharset(contentType: string | null): string | undefined {
93
+ const match = /;\s*charset\s*=\s*"?([^";]+)"?/i.exec(contentType ?? '')
94
+ return match?.[1]?.trim().toLowerCase()
95
+ }
96
+
97
+ /**
98
+ * Resolve the declared charset, defaulting to UTF-8 when absent. A malformed
99
+ * comma- or whitespace-joined declaration containing a UTF-8 label uses a fatal
100
+ * UTF-8 decoder; other unsupported declarations throw `WEB_UNSUPPORTED_CONTENT_TYPE`.
101
+ * UTF-8 recovery is a preference, not proof of the original encoding.
102
+ *
103
+ * @param charset - the declared charset parameter, or `undefined` to default.
104
+ * @returns a decoder; callers must report fatal decoding failures and flush at
105
+ * EOF unless they deliberately truncated the bytes.
106
+ */
107
+ export function decoderForCharset(charset: string | undefined): TextDecoder {
108
+ const declared = charset ?? 'utf-8'
109
+ try {
110
+ return new TextDecoder(declared)
111
+ } catch (error: unknown) {
112
+ if (declared.split(/[\s,]+/).some(isUtf8Label)) return new TextDecoder('utf-8', { fatal: true })
113
+ throw new WebError(`unsupported charset "${declared}"`, 'WEB_UNSUPPORTED_CONTENT_TYPE', { cause: error })
114
+ }
115
+ }
116
+
117
+ /** Whether a label names UTF-8, including its standard aliases. */
118
+ function isUtf8Label(label: string): boolean {
119
+ try {
120
+ return new TextDecoder(label).encoding === 'utf-8'
121
+ } catch (_error: unknown) {
122
+ // An unsupported label does not authorize UTF-8 recovery.
123
+ return false
124
+ }
125
+ }
@@ -0,0 +1,259 @@
1
+ /**
2
+ * Bounded HTTP(S) retrieval for `ctx.web`: validates URLs, follows only same-origin redirects,
3
+ * enforces time and size limits, classifies and decodes text, and leaves presentation to
4
+ * `@deepseek-ai/dsh-tool-web`. Requests carry no browser cookies
5
+ * or ambient credentials.
6
+ * @module @deepseek-ai/dsh-web-fetch-http/provider
7
+ */
8
+
9
+ import { WebError } from '@deepseek-ai/dsh-web'
10
+ import type { WebFetchBody, WebFetchProvider, WebFetchRequest, WebFetchResult } from '@deepseek-ai/dsh-web'
11
+ import { deadline, timeoutOf } from '@deepseek-ai/dsh-timeout'
12
+ import type { Response } from 'undici'
13
+ import { classifyContentType, decoderForCharset, isSameOrigin, parseCharset, validateFetchUrl } from './policy.ts'
14
+
15
+ /** Resolved provider limits (the plugin's schemastery Config supplies defaults). */
16
+ export interface HttpFetchLimits {
17
+ /** Maximum response body size in bytes (read is aborted past this). */
18
+ maxResponseBytes: number
19
+ /** Maximum decoded body length in characters (truncated past this). */
20
+ maxBodyChars: number
21
+ /** Default fetch timeout in milliseconds. */
22
+ timeoutMs: number
23
+ /** Maximum number of (same-origin) redirect hops to follow. */
24
+ maxRedirects: number
25
+ /** `User-Agent` header sent on every request. */
26
+ userAgent: string
27
+ }
28
+
29
+ /** Stable id this provider registers under. */
30
+ export const LOCAL_FETCH_PROVIDER_ID = 'http'
31
+
32
+ /** The anonymous HTTP(S) fetch provider. */
33
+ export class HttpFetchProvider implements WebFetchProvider {
34
+ readonly id = LOCAL_FETCH_PROVIDER_ID
35
+ /** Picker description: what this provider suits and what it costs or cannot do. */
36
+ readonly description: NonNullable<WebFetchProvider['description']> = {
37
+ en: 'Free, and can reach intranet and local addresses. Does not support pages that need JavaScript or sign-in, or PDFs.',
38
+ zh: '免费,可访问内网和本机。不支持需要 JavaScript 或登录的页面,也不支持 PDF。',
39
+ ja: '無料で、イントラネットやローカルのアドレスにもアクセスできます。JavaScript やログインが必要なページ、PDF には対応しません。',
40
+ es: 'Gratis y puede acceder a direcciones de la intranet y locales. No admite páginas que requieran JavaScript o inicio de sesión, ni PDF.',
41
+ fr: 'Gratuit, et accède aux adresses intranet et locales. Ne prend pas en charge les pages nécessitant JavaScript ou une connexion, ni les PDF.',
42
+ de: 'Kostenlos und erreicht auch Intranet- und lokale Adressen. Keine Seiten, die JavaScript oder eine Anmeldung erfordern, und keine PDFs.',
43
+ ru: 'Бесплатно, доступны адреса интрасети и локальные адреса. Не поддерживает страницы, требующие JavaScript или входа, а также PDF.',
44
+ pt: 'Gratuito e acessa endereços da intranet e locais. Não oferece suporte a páginas que exigem JavaScript ou login, nem a PDFs.',
45
+ }
46
+
47
+ /** @param limits - resolved transport and response limits. */
48
+ constructor(private readonly limits: HttpFetchLimits) {}
49
+
50
+ /** No credentials to check — an anonymous fetcher is always usable. */
51
+ available(): boolean {
52
+ return true
53
+ }
54
+
55
+ async fetch(request: WebFetchRequest, signal?: AbortSignal): Promise<WebFetchResult> {
56
+ if (signal?.aborted) throw new WebError('web fetch aborted', 'WEB_ABORTED')
57
+
58
+ // One signal stops both the request and body read. The deadline's TimeoutReason later
59
+ // distinguishes this provider's timeout from caller or outer-deadline cancellation.
60
+ using d = deadline(signal, this.limits.timeoutMs, 'WEB_FETCH_TIMEOUT')
61
+ return await this.followAndRead(request.url, d.signal)
62
+ }
63
+
64
+ /** Follow same-origin redirects up to the hop cap, then read the final response. */
65
+ private async followAndRead(initialUrl: string, signal: AbortSignal): Promise<WebFetchResult> {
66
+ let currentUrl = validateFetchUrl(initialUrl)
67
+ let redirectsFollowed = 0
68
+
69
+ for (;;) {
70
+ const response = await this.requestOnce(currentUrl, signal)
71
+ if (isRedirectStatus(response.status)) {
72
+ // Enforce the redirect budget before validating the next hop.
73
+ if (redirectsFollowed >= this.limits.maxRedirects) {
74
+ await response.body?.cancel()
75
+ throw new WebError(`exceeded the maximum of ${this.limits.maxRedirects} redirects`, 'WEB_REDIRECT_BLOCKED')
76
+ }
77
+ const location = response.headers.get('location')
78
+ if (location === null) {
79
+ // A redirect status with no Location is not a usable resource. Cancel
80
+ // the (possibly streaming) body before throwing so no socket leaks.
81
+ await response.body?.cancel()
82
+ throw new WebError(`redirect response (HTTP ${response.status}) without a Location header`, 'WEB_PROVIDER_ERROR')
83
+ }
84
+ const target = resolveRedirect(location, currentUrl)
85
+ // Re-validate the target against the same transport hygiene a direct request gets: a
86
+ // redirect must not be a back door to a credentialed, non-http(s), or over-long URL
87
+ // that validateFetchUrl would reject.
88
+ let validatedTarget: URL
89
+ try {
90
+ validatedTarget = validateFetchUrl(target.toString())
91
+ if (!isSameOrigin(validatedTarget, currentUrl)) {
92
+ throw new WebError(
93
+ `cross-origin redirect to ${validatedTarget.origin} is not followed automatically; retry against that URL directly`,
94
+ 'WEB_REDIRECT_BLOCKED',
95
+ )
96
+ }
97
+ } catch (error: unknown) {
98
+ await response.body?.cancel()
99
+ throw error
100
+ }
101
+ await response.body?.cancel()
102
+ currentUrl = validatedTarget
103
+ redirectsFollowed++
104
+ continue
105
+ }
106
+
107
+ return await this.readBody(response, currentUrl, signal)
108
+ }
109
+ }
110
+
111
+ /** Send one GET through the process-wide dispatcher, which applies the installed proxy policy. */
112
+ private async requestOnce(url: URL, signal: AbortSignal): Promise<Response> {
113
+ const headers = {
114
+ 'user-agent': this.limits.userAgent,
115
+ 'accept': 'text/html,application/xhtml+xml,text/*;q=0.9,application/json;q=0.8',
116
+ }
117
+ try {
118
+ // Keep the Node-only transport out of browser-worker startup; a real request loads it here.
119
+ const { fetch } = await import('undici')
120
+ return await fetch(url, { method: 'GET', redirect: 'manual', headers, signal })
121
+ } catch (error: unknown) {
122
+ throw translateAbortOrNetwork(error, signal)
123
+ }
124
+ }
125
+
126
+ /** Read, byte-cap, classify, and decode the final response body. */
127
+ private async readBody(response: Response, finalUrl: URL, signal: AbortSignal): Promise<WebFetchResult> {
128
+ const contentType = response.headers.get('content-type')
129
+ const kind = classifyContentType(contentType)
130
+ if (kind === undefined) {
131
+ await response.body?.cancel()
132
+ throw new WebError(`unsupported content type "${contentType ?? 'unknown'}"`, 'WEB_UNSUPPORTED_CONTENT_TYPE')
133
+ }
134
+
135
+ // Reject unsupported declarations before reading, releasing the response stream.
136
+ let decoder: TextDecoder
137
+ try {
138
+ decoder = decoderForCharset(parseCharset(contentType))
139
+ } catch (error: unknown) {
140
+ await response.body?.cancel()
141
+ throw error
142
+ }
143
+ const { bytes, truncatedByBytes } = await this.readCapped(response, signal)
144
+ let decoded: string
145
+ try {
146
+ // Only a real byte-cap truncation permits an incomplete UTF-8 suffix.
147
+ decoded = decoder.decode(bytes, { stream: decoder.fatal && truncatedByBytes })
148
+ } catch (error: unknown) {
149
+ throw new WebError(
150
+ 'response body is not valid UTF-8 for the malformed charset declaration',
151
+ 'WEB_UNSUPPORTED_CONTENT_TYPE',
152
+ { cause: error },
153
+ )
154
+ }
155
+ const truncatedByChars = decoded.length > this.limits.maxBodyChars
156
+ const content = truncatedByChars ? decoded.slice(0, this.limits.maxBodyChars) : decoded
157
+ const body: WebFetchBody = kind === 'html' ? { kind: 'html', content } : { kind: 'text', content }
158
+
159
+ return {
160
+ url: finalUrl.toString(),
161
+ statusCode: response.status,
162
+ body,
163
+ truncated: truncatedByBytes || truncatedByChars,
164
+ }
165
+ }
166
+
167
+ /**
168
+ * Read the response stream up to `maxResponseBytes`. A `Content-Length` over
169
+ * the cap rejects immediately with `WEB_FETCH_TOO_LARGE`; a stream that grows
170
+ * past the cap is cut short (`truncatedByBytes`) rather than rejected, so a
171
+ * server that under-reports still yields a bounded usable body.
172
+ */
173
+ private async readCapped(response: Response, signal: AbortSignal): Promise<{ bytes: Uint8Array; truncatedByBytes: boolean }> {
174
+ const declared = response.headers.get('content-length')
175
+ if (declared !== null) {
176
+ const length = Number(declared)
177
+ if (Number.isFinite(length) && length > this.limits.maxResponseBytes) {
178
+ await response.body?.cancel()
179
+ throw new WebError(`response exceeds the maximum of ${this.limits.maxResponseBytes} bytes`, 'WEB_FETCH_TOO_LARGE')
180
+ }
181
+ }
182
+
183
+ /* v8 ignore next -- a 2xx Response from fetch always exposes a body stream; the null guard is defensive. */
184
+ if (response.body === null) return { bytes: new Uint8Array(0), truncatedByBytes: false }
185
+
186
+ const chunks: Uint8Array[] = []
187
+ let total = 0
188
+ let truncatedByBytes = false
189
+ // Undici exposes response chunks as `any`; Fetch guarantees body chunks are Uint8Array.
190
+ const reader = response.body.getReader() as ReadableStreamDefaultReader<Uint8Array>
191
+ try {
192
+ for (;;) {
193
+ const { done, value } = await reader.read()
194
+ if (done) break
195
+ const remaining = this.limits.maxResponseBytes - total
196
+ // Only DROPPED bytes count as truncation: a chunk that exactly fills the
197
+ // remaining capacity keeps all its bytes and we read on to observe EOF,
198
+ // so an exactly-at-cap body is not falsely flagged truncated.
199
+ if (value.byteLength > remaining) {
200
+ chunks.push(value.subarray(0, remaining))
201
+ total += remaining
202
+ truncatedByBytes = true
203
+ break
204
+ }
205
+ chunks.push(value)
206
+ total += value.byteLength
207
+ }
208
+ } catch (error: unknown) {
209
+ /* v8 ignore next -- mid-stream read fault needs a network drop after headers; translate path covered by request-phase tests. */
210
+ throw translateAbortOrNetwork(error, signal)
211
+ } finally {
212
+ /* v8 ignore next 4 -- cancel() after a completed/broken read settles without rejecting; unobserved best-effort cleanup. */
213
+ await reader.cancel().catch(() => {
214
+ // Cancel after a successful read (or after we broke past the cap) is
215
+ // best-effort cleanup; the bytes we need are already collected.
216
+ })
217
+ }
218
+
219
+ const bytes = new Uint8Array(total)
220
+ let offset = 0
221
+ for (const chunk of chunks) {
222
+ bytes.set(chunk, offset)
223
+ offset += chunk.byteLength
224
+ }
225
+ return { bytes, truncatedByBytes }
226
+ }
227
+ }
228
+
229
+ /** HTTP redirect status codes that carry a `Location`. */
230
+ function isRedirectStatus(status: number): boolean {
231
+ return status === 301 || status === 302 || status === 303 || status === 307 || status === 308
232
+ }
233
+
234
+ /** Resolve a (possibly relative) `Location` against the current URL. */
235
+ function resolveRedirect(location: string, base: URL): URL {
236
+ try {
237
+ return new URL(location, base)
238
+ } catch (error: unknown) {
239
+ /* v8 ignore next 2 -- URL resolution against a valid absolute base effectively never throws; defensive guard. */
240
+ throw new WebError(`invalid redirect Location "${location}"`, 'WEB_PROVIDER_ERROR', { cause: error })
241
+ }
242
+ }
243
+
244
+ /**
245
+ * Translate a thrown fetch/stream error into a `WebError`, classified by the
246
+ * deadline signal rather than the thrown value (which differs by phase: the
247
+ * request-phase `fetch` rejects with the abort reason, while the read-phase
248
+ * reader surfaces a bare `AbortError`). `timeoutOf(signal, 'WEB_FETCH_TIMEOUT')`
249
+ * recovering OUR reason means our timeout fired (`WEB_FETCH_TIMEOUT`); any other
250
+ * abort — an upstream cancel, or a foreign/outer deadline's timeout under
251
+ * nesting — is `WEB_ABORTED`; a throw with the signal NOT aborted is a
252
+ * transport/network failure (`WEB_PROVIDER_ERROR`).
253
+ */
254
+ function translateAbortOrNetwork(error: unknown, signal: AbortSignal): WebError {
255
+ const timeout = timeoutOf(signal, 'WEB_FETCH_TIMEOUT')
256
+ if (timeout !== undefined) return new WebError('web fetch timed out', 'WEB_FETCH_TIMEOUT', { cause: timeout })
257
+ if (signal.aborted) return new WebError('web fetch aborted', 'WEB_ABORTED', { cause: error })
258
+ return new WebError(`web fetch failed: ${String(error)}`, 'WEB_PROVIDER_ERROR', { cause: error })
259
+ }