@happy-ts/fetch-t 1.6.0 → 1.8.0

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
@@ -5,6 +5,28 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [1.8.0] - 2026-01-12
9
+
10
+ ### Added
11
+
12
+ - Add URL validation with browser relative path support
13
+ - Validates URLs upfront before calling `fetch`
14
+ - Supports relative URLs in browser environments (using `location.href` as base)
15
+ - Throws `TypeError` with unified message for invalid URLs in non-browser environments
16
+
17
+ ## [1.7.0] - 2026-01-08
18
+
19
+ ### Added
20
+
21
+ - Export `FetchResponseData` union type for dynamic `responseType` scenarios
22
+ - Add `FetchResponseType` union overloads for when `responseType` is a type variable (not a literal)
23
+ - Add `examples/overload-demonstration.ts` showcasing all fetchT overloads with explicit type annotations
24
+
25
+ ### Changed
26
+
27
+ - Add `abortable?: false` constraint to non-abortable overloads for stricter type checking
28
+ - Update JSDoc for non-abortable overloads to document `abortable must be false or omitted` constraint
29
+
8
30
  ## [1.6.0] - 2026-01-06
9
31
 
10
32
  ### Added
@@ -177,6 +199,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
177
199
  - Timeout support
178
200
  - Rust-like Result type error handling via `happy-rusty` library
179
201
 
202
+ [1.8.0]: https://github.com/JiangJie/fetch-t/compare/v1.7.0...v1.8.0
203
+ [1.7.0]: https://github.com/JiangJie/fetch-t/compare/v1.6.0...v1.7.0
180
204
  [1.6.0]: https://github.com/JiangJie/fetch-t/compare/v1.5.1...v1.6.0
181
205
  [1.5.1]: https://github.com/JiangJie/fetch-t/compare/v1.5.0...v1.5.1
182
206
  [1.5.0]: https://github.com/JiangJie/fetch-t/compare/v1.4.1...v1.5.0
package/dist/main.cjs CHANGED
@@ -30,9 +30,7 @@ class FetchError extends Error {
30
30
  }
31
31
 
32
32
  function fetchT(url, init) {
33
- if (typeof url !== "string") {
34
- invariant(url instanceof URL, () => `Url must be a string or URL object but received ${url}`);
35
- }
33
+ const parsedUrl = validateUrl(url);
36
34
  const fetchInit = init ?? {};
37
35
  const {
38
36
  retries,
@@ -87,7 +85,7 @@ function fetchT(url, init) {
87
85
  const doFetch = async () => {
88
86
  configureSignal();
89
87
  try {
90
- const response2 = await fetch(url, rest);
88
+ const response2 = await fetch(parsedUrl, rest);
91
89
  if (!response2.ok) {
92
90
  response2.body?.cancel().catch(() => {
93
91
  });
@@ -283,6 +281,17 @@ function validateOptions(init) {
283
281
  }
284
282
  return { retries, delay: delay2, when, onRetry };
285
283
  }
284
+ function validateUrl(url) {
285
+ if (url instanceof URL) {
286
+ return url;
287
+ }
288
+ try {
289
+ const base = typeof location !== "undefined" ? location.href : void 0;
290
+ return new URL(url, base);
291
+ } catch {
292
+ throw new TypeError(`Invalid URL: ${url}`);
293
+ }
294
+ }
286
295
 
287
296
  exports.ABORT_ERROR = ABORT_ERROR;
288
297
  exports.FetchError = FetchError;
package/dist/main.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"main.cjs","sources":["../src/fetch/constants.ts","../src/fetch/defines.ts","../src/fetch/fetch.ts"],"sourcesContent":["/**\n * Error name for aborted fetch requests.\n *\n * This matches the standard `AbortError` name used by the Fetch API when a request\n * is cancelled via `AbortController.abort()`.\n *\n * @example\n * ```typescript\n * import { fetchT, ABORT_ERROR } from '@happy-ts/fetch-t';\n *\n * const task = fetchT('https://api.example.com/data', { abortable: true });\n * task.abort();\n *\n * const result = await task.response;\n * result.inspectErr((err) => {\n * if (err.name === ABORT_ERROR) {\n * console.log('Request was aborted');\n * }\n * });\n * ```\n */\nexport const ABORT_ERROR = 'AbortError' as const;\n\n/**\n * Error name for timed out fetch requests.\n *\n * This is set on the `Error.name` property when a request exceeds the specified\n * `timeout` duration and is automatically aborted.\n *\n * @example\n * ```typescript\n * import { fetchT, TIMEOUT_ERROR } from '@happy-ts/fetch-t';\n *\n * const result = await fetchT('https://api.example.com/slow-endpoint', {\n * timeout: 5000, // 5 seconds\n * });\n *\n * result.inspectErr((err) => {\n * if (err.name === TIMEOUT_ERROR) {\n * console.log('Request timed out after 5 seconds');\n * }\n * });\n * ```\n */\nexport const TIMEOUT_ERROR = 'TimeoutError' as const;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { AsyncResult, IOResult } from 'happy-rusty';\n\n/**\n * Represents the response of a fetch operation as an async Result type.\n *\n * This is an alias for `AsyncResult<T, E>` from the `happy-rusty` library,\n * providing Rust-like error handling without throwing exceptions.\n *\n * @typeParam T - The type of the data expected in a successful response.\n * @typeParam E - The type of the error (defaults to `any`). Typically `Error` or `FetchError`.\n *\n * @example\n * ```typescript\n * import { fetchT, type FetchResponse } from '@happy-ts/fetch-t';\n *\n * // FetchResponse is a Promise that resolves to Result<T, E>\n * const response: FetchResponse<string> = fetchT('https://api.example.com', {\n * responseType: 'text',\n * });\n *\n * const result = await response;\n * result\n * .inspect((text) => console.log('Success:', text))\n * .inspectErr((err) => console.error('Error:', err));\n * ```\n */\nexport type FetchResponse<T, E = any> = AsyncResult<T, E>;\n\n/**\n * Represents an abortable fetch operation with control methods.\n *\n * Returned when `abortable: true` is set in the fetch options. Provides\n * the ability to cancel the request and check its abort status.\n *\n * @typeParam T - The type of the data expected in the response.\n *\n * @example\n * ```typescript\n * import { fetchT, type FetchTask } from '@happy-ts/fetch-t';\n *\n * interface User {\n * id: number;\n * name: string;\n * }\n *\n * const task: FetchTask<User> = fetchT<User>('https://api.example.com/user/1', {\n * abortable: true,\n * responseType: 'json',\n * });\n *\n * // Check if aborted\n * console.log('Is aborted:', task.aborted); // false\n *\n * // Abort with optional reason\n * task.abort('User navigated away');\n *\n * // Access the response (will be an error after abort)\n * const result = await task.response;\n * result.inspectErr((err) => console.log('Aborted:', err.message));\n * ```\n */\nexport interface FetchTask<T> {\n /**\n * Aborts the fetch task, optionally with a reason.\n *\n * Once aborted, the `response` promise will resolve to an `Err` containing\n * an `AbortError`. The abort reason can be any value and will be passed\n * to the underlying `AbortController.abort()`.\n *\n * @param reason - An optional value indicating why the task was aborted.\n * This can be an Error, string, or any other value.\n */\n abort(reason?: any): void;\n\n /**\n * Indicates whether the fetch task has been aborted.\n *\n * Returns `true` if `abort()` was called or if the request timed out.\n */\n readonly aborted: boolean;\n\n /**\n * The response promise of the fetch task.\n *\n * Resolves to `Ok<T>` on success, or `Err<Error>` on failure (including abort).\n */\n readonly response: FetchResponse<T>;\n}\n\n/**\n * Specifies the expected response type for automatic parsing.\n *\n * - `'text'` - Parse response as string via `Response.text()`\n * - `'json'` - Parse response as JSON via `Response.json()`\n * - `'arraybuffer'` - Parse response as ArrayBuffer via `Response.arrayBuffer()`\n * - `'bytes'` - Parse response as Uint8Array<ArrayBuffer> via `Response.bytes()` (with fallback for older environments)\n * - `'blob'` - Parse response as Blob via `Response.blob()`\n * - `'stream'` - Return the raw `ReadableStream` for streaming processing\n *\n * If not specified, the raw `Response` object is returned.\n *\n * @example\n * ```typescript\n * import { fetchT, type FetchResponseType } from '@happy-ts/fetch-t';\n *\n * const responseType: FetchResponseType = 'json';\n *\n * const result = await fetchT('https://api.example.com/data', { responseType });\n * ```\n */\nexport type FetchResponseType = 'text' | 'arraybuffer' | 'blob' | 'json' | 'bytes' | 'stream';\n\n/**\n * Represents the download progress of a fetch operation.\n *\n * Passed to the `onProgress` callback when tracking download progress.\n * Note: Progress tracking requires the server to send a `Content-Length` header.\n *\n * @example\n * ```typescript\n * import { fetchT, type FetchProgress } from '@happy-ts/fetch-t';\n *\n * await fetchT('https://example.com/file.zip', {\n * responseType: 'blob',\n * onProgress: (result) => {\n * result.inspect((progress: FetchProgress) => {\n * const percent = (progress.completedByteLength / progress.totalByteLength) * 100;\n * console.log(`Downloaded: ${percent.toFixed(1)}%`);\n * });\n * },\n * });\n * ```\n */\nexport interface FetchProgress {\n /**\n * The total number of bytes to be received (from Content-Length header).\n */\n totalByteLength: number;\n\n /**\n * The number of bytes received so far.\n */\n completedByteLength: number;\n}\n\n/**\n * Options for configuring retry behavior.\n */\nexport interface FetchRetryOptions {\n /**\n * Number of times to retry the request on failure.\n *\n * By default, only network errors trigger retries. HTTP errors (4xx, 5xx)\n * require explicit configuration via `when`.\n *\n * @default 0 (no retries)\n */\n retries?: number;\n\n /**\n * Delay between retry attempts in milliseconds.\n *\n * Can be a static number or a function for custom strategies like exponential backoff.\n * The function receives the current attempt number (1-indexed).\n *\n * @default 0 (immediate retry)\n */\n delay?: number | ((attempt: number) => number);\n\n /**\n * Conditions under which to retry the request.\n *\n * Can be an array of HTTP status codes or a custom function.\n * By default, only network errors (not FetchError) trigger retries.\n */\n when?: number[] | ((error: Error, attempt: number) => boolean);\n\n /**\n * Callback invoked before each retry attempt.\n *\n * Useful for logging, metrics, or adjusting request parameters.\n */\n onRetry?: (error: Error, attempt: number) => void;\n}\n\n/**\n * Extended fetch options that add additional capabilities to the standard `RequestInit`.\n *\n * @example\n * ```typescript\n * import { fetchT, type FetchInit } from '@happy-ts/fetch-t';\n *\n * const options: FetchInit = {\n * // Standard RequestInit options\n * method: 'POST',\n * headers: { 'Content-Type': 'application/json' },\n * body: JSON.stringify({ key: 'value' }),\n *\n * // Extended options\n * abortable: true, // Return FetchTask for manual abort control\n * responseType: 'json', // Auto-parse response as JSON\n * timeout: 10000, // Abort after 10 seconds\n * onProgress: (result) => { // Track download progress\n * result.inspect(({ completedByteLength, totalByteLength }) => {\n * console.log(`${completedByteLength}/${totalByteLength}`);\n * });\n * },\n * onChunk: (chunk) => { // Receive raw data chunks\n * console.log('Received chunk:', chunk.byteLength, 'bytes');\n * },\n * };\n *\n * const task = fetchT('https://api.example.com/upload', options);\n * ```\n */\nexport interface FetchInit extends RequestInit {\n /**\n * When `true`, returns a `FetchTask` instead of `FetchResponse`.\n *\n * The `FetchTask` provides `abort()` method and `aborted` status.\n *\n * @default false\n */\n abortable?: boolean;\n\n /**\n * Specifies how the response body should be parsed.\n *\n * - `'text'` - Returns `string`\n * - `'json'` - Returns parsed JSON (type `T`)\n * - `'arraybuffer'` - Returns `ArrayBuffer`\n * - `'bytes'` - Returns `Uint8Array<ArrayBuffer>` (with fallback for older environments)\n * - `'blob'` - Returns `Blob`\n * - `'stream'` - Returns `ReadableStream<Uint8Array<ArrayBuffer>>`\n * - `undefined` - Returns raw `Response` object\n */\n responseType?: FetchResponseType;\n\n /**\n * Maximum time in milliseconds to wait for the request to complete.\n *\n * If exceeded, the request is automatically aborted with a `TimeoutError`.\n * Must be a positive number.\n */\n timeout?: number;\n\n /**\n * Retry options.\n *\n * Can be a number (shorthand for retries count) or an options object.\n *\n * @example\n * ```typescript\n * // Retry up to 3 times on network errors\n * const result = await fetchT('https://api.example.com/data', {\n * retry: 3,\n * });\n *\n * // Detailed configuration\n * const result = await fetchT('https://api.example.com/data', {\n * retry: {\n * retries: 3,\n * delay: 1000,\n * when: [500, 502],\n * onRetry: (error, attempt) => console.log(error),\n * },\n * });\n * ```\n */\n retry?: number | FetchRetryOptions;\n\n /**\n * Callback invoked during download to report progress.\n *\n * Receives an `IOResult<FetchProgress>`:\n * - `Ok(FetchProgress)` - Progress update with byte counts\n * - `Err(Error)` - If `Content-Length` header is missing (called once)\n *\n * @param progressResult - The progress result, either success with progress data or error.\n */\n onProgress?: (progressResult: IOResult<FetchProgress>) => void;\n\n /**\n * Callback invoked when a chunk of data is received.\n *\n * Useful for streaming or processing data as it arrives.\n * Each chunk is a `Uint8Array<ArrayBuffer>` containing the raw bytes.\n *\n * @param chunk - The raw data chunk received from the response stream.\n */\n onChunk?: (chunk: Uint8Array<ArrayBuffer>) => void;\n}\n\n/**\n * Custom error class for HTTP error responses (non-2xx status codes).\n *\n * Thrown when `Response.ok` is `false`. Contains the HTTP status code\n * for programmatic error handling.\n *\n * @example\n * ```typescript\n * import { fetchT, FetchError } from '@happy-ts/fetch-t';\n *\n * const result = await fetchT('https://api.example.com/not-found', {\n * responseType: 'json',\n * });\n *\n * result.inspectErr((err) => {\n * if (err instanceof FetchError) {\n * console.log('HTTP Status:', err.status); // e.g., 404\n * console.log('Status Text:', err.message); // e.g., \"Not Found\"\n *\n * // Handle specific status codes\n * switch (err.status) {\n * case 401:\n * console.log('Unauthorized - please login');\n * break;\n * case 404:\n * console.log('Resource not found');\n * break;\n * case 500:\n * console.log('Server error');\n * break;\n * }\n * }\n * });\n * ```\n */\nexport class FetchError extends Error {\n /**\n * The error name, always `'FetchError'`.\n */\n override name = 'FetchError';\n\n /**\n * The HTTP status code of the response (e.g., 404, 500).\n */\n status: number;\n\n /**\n * Creates a new FetchError instance.\n *\n * @param message - The status text from the HTTP response (e.g., \"Not Found\").\n * @param status - The HTTP status code (e.g., 404).\n */\n constructor(message: string, status: number) {\n super(message);\n this.status = status;\n }\n}\n","import { Err, Ok, type AsyncIOResult } from 'happy-rusty';\nimport invariant from 'tiny-invariant';\nimport { ABORT_ERROR } from './constants.ts';\nimport { FetchError, type FetchInit, type FetchResponse, type FetchRetryOptions, type FetchTask } from './defines.ts';\n\n/**\n * Union type of all possible fetchT response data types.\n * Internal type used only in the implementation signature.\n */\ntype FetchResponseData =\n | string\n | ArrayBuffer\n | Blob\n | Uint8Array<ArrayBuffer>\n | ReadableStream<Uint8Array<ArrayBuffer>> | null\n | Response;\n\n/**\n * Fetches a resource from the network as a text string and returns an abortable `FetchTask`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and `responseType: 'text'`.\n * @returns A `FetchTask` representing the abortable operation with a `string` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'text';\n}): FetchTask<string>;\n\n/**\n * Fetches a resource from the network as an ArrayBuffer and returns an abortable `FetchTask`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and `responseType: 'arraybuffer'`.\n * @returns A `FetchTask` representing the abortable operation with an `ArrayBuffer` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'arraybuffer';\n}): FetchTask<ArrayBuffer>;\n\n/**\n * Fetches a resource from the network as a Blob and returns an abortable `FetchTask`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and `responseType: 'blob'`.\n * @returns A `FetchTask` representing the abortable operation with a `Blob` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'blob';\n}): FetchTask<Blob>;\n\n/**\n * Fetches a resource from the network and parses it as JSON, returning an abortable `FetchTask`.\n *\n * @typeParam T - The expected type of the parsed JSON data.\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and `responseType: 'json'`.\n * @returns A `FetchTask` representing the abortable operation with a response parsed as type `T`.\n */\nexport function fetchT<T>(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'json';\n}): FetchTask<T | null>;\n\n/**\n * Fetches a resource from the network as a ReadableStream and returns an abortable `FetchTask`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and `responseType: 'stream'`.\n * @returns A `FetchTask` representing the abortable operation with a `ReadableStream<Uint8Array<ArrayBuffer>>` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'stream';\n}): FetchTask<ReadableStream<Uint8Array<ArrayBuffer>> | null>;\n\n/**\n * Fetches a resource from the network as a Uint8Array<ArrayBuffer> and returns an abortable `FetchTask`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and `responseType: 'bytes'`.\n * @returns A `FetchTask` representing the abortable operation with a `Uint8Array<ArrayBuffer>` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'bytes';\n}): FetchTask<Uint8Array<ArrayBuffer>>;\n\n/**\n * Fetches a resource from the network as a text string.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `responseType: 'text'`.\n * @returns A `FetchResponse` representing the operation with a `string` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n responseType: 'text';\n}): FetchResponse<string, Error>;\n\n/**\n * Fetches a resource from the network as an ArrayBuffer.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `responseType: 'arraybuffer'`.\n * @returns A `FetchResponse` representing the operation with an `ArrayBuffer` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n responseType: 'arraybuffer';\n}): FetchResponse<ArrayBuffer, Error>;\n\n/**\n * Fetches a resource from the network as a Blob.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `responseType: 'blob'`.\n * @returns A `FetchResponse` representing the operation with a `Blob` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n responseType: 'blob';\n}): FetchResponse<Blob, Error>;\n\n/**\n * Fetches a resource from the network and parses it as JSON.\n *\n * @typeParam T - The expected type of the parsed JSON data.\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `responseType: 'json'`.\n * @returns A `FetchResponse` representing the operation with a response parsed as type `T`.\n */\nexport function fetchT<T>(url: string | URL, init: FetchInit & {\n responseType: 'json';\n}): FetchResponse<T | null, Error>;\n\n/**\n * Fetches a resource from the network as a ReadableStream.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `responseType: 'stream'`.\n * @returns A `FetchResponse` representing the operation with a `ReadableStream<Uint8Array<ArrayBuffer>>` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n responseType: 'stream';\n}): FetchResponse<ReadableStream<Uint8Array<ArrayBuffer>> | null, Error>;\n\n/**\n * Fetches a resource from the network as a Uint8Array<ArrayBuffer>.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `responseType: 'bytes'`.\n * @returns A `FetchResponse` representing the operation with a `Uint8Array<ArrayBuffer>` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n responseType: 'bytes';\n}): FetchResponse<Uint8Array<ArrayBuffer>, Error>;\n\n/**\n * Fetches a resource from the network and returns an abortable `FetchTask` with a generic `Response`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true`.\n * @returns A `FetchTask` representing the abortable operation with a `Response` object.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n}): FetchTask<Response>;\n\n/**\n * Fetches a resource from the network and returns a `FetchResponse` with a generic `Response` object.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Optional additional options for the fetch operation.\n * @returns A `FetchResponse` representing the operation with a `Response` object.\n */\nexport function fetchT(url: string | URL, init?: FetchInit): FetchResponse<Response>;\n\n/**\n * Enhanced fetch function that wraps the native Fetch API with additional capabilities.\n *\n * Features:\n * - **Abortable requests**: Set `abortable: true` to get a `FetchTask` with `abort()` method.\n * - **Type-safe responses**: Use `responseType` to automatically parse responses as text, JSON, ArrayBuffer, or Blob.\n * - **Timeout support**: Set `timeout` in milliseconds to auto-abort long-running requests.\n * - **Progress tracking**: Use `onProgress` callback to track download progress (requires Content-Length header).\n * - **Chunk streaming**: Use `onChunk` callback to receive raw data chunks as they arrive.\n * - **Retry support**: Use `retry` to automatically retry failed requests with configurable delay and conditions.\n * - **Result type error handling**: Returns `Result<T, Error>` instead of throwing exceptions.\n *\n * @typeParam T - The expected type of the response data.\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, extending standard `RequestInit` with custom properties.\n * @returns A `FetchTask<T>` if `abortable: true`, otherwise a `FetchResponse<T>` (which is `AsyncResult<T, Error>`).\n * @throws {Error} If `url` is not a string or URL object.\n * @throws {Error} If `timeout` is specified but is not a positive number.\n *\n * @example\n * // Basic GET request - returns Response object wrapped in Result\n * const result = await fetchT('https://api.example.com/data');\n * result\n * .inspect((res) => console.log('Status:', res.status))\n * .inspectErr((err) => console.error('Error:', err));\n *\n * @example\n * // GET JSON with type safety\n * interface User {\n * id: number;\n * name: string;\n * }\n * const result = await fetchT<User>('https://api.example.com/user/1', {\n * responseType: 'json',\n * });\n * result.inspect((user) => console.log(user.name));\n *\n * @example\n * // POST request with JSON body\n * const result = await fetchT<User>('https://api.example.com/users', {\n * method: 'POST',\n * headers: { 'Content-Type': 'application/json' },\n * body: JSON.stringify({ name: 'John' }),\n * responseType: 'json',\n * });\n *\n * @example\n * // Abortable request with timeout\n * const task = fetchT('https://api.example.com/data', {\n * abortable: true,\n * timeout: 5000, // 5 seconds\n * });\n *\n * // Cancel the request if needed\n * task.abort('User cancelled');\n *\n * // Check if aborted\n * console.log('Aborted:', task.aborted);\n *\n * // Wait for response\n * const result = await task.response;\n *\n * @example\n * // Track download progress\n * const result = await fetchT('https://example.com/large-file.zip', {\n * responseType: 'blob',\n * onProgress: (progressResult) => {\n * progressResult\n * .inspect(({ completedByteLength, totalByteLength }) => {\n * const percent = ((completedByteLength / totalByteLength) * 100).toFixed(1);\n * console.log(`Progress: ${percent}%`);\n * })\n * .inspectErr((err) => console.warn('Progress unavailable:', err.message));\n * },\n * });\n *\n * @example\n * // Stream data chunks\n * const chunks: Uint8Array[] = [];\n * const result = await fetchT('https://example.com/stream', {\n * onChunk: (chunk) => chunks.push(chunk),\n * });\n *\n * @example\n * // Retry with exponential backoff\n * const result = await fetchT('https://api.example.com/data', {\n * retry: {\n * retries: 3,\n * delay: (attempt) => Math.min(1000 * Math.pow(2, attempt - 1), 10000),\n * when: [500, 502, 503, 504],\n * onRetry: (error, attempt) => console.log(`Retry ${attempt}: ${error.message}`),\n * },\n * responseType: 'json',\n * });\n */\nexport function fetchT(url: string | URL, init?: FetchInit): FetchTask<FetchResponseData> | FetchResponse<FetchResponseData> {\n // Fast path: most URLs are passed as strings\n if (typeof url !== 'string') {\n invariant(url instanceof URL, () => `Url must be a string or URL object but received ${ url }`);\n }\n\n const fetchInit = init ?? {};\n\n const {\n retries,\n delay: retryDelay,\n when: retryWhen,\n onRetry,\n } = validateOptions(fetchInit);\n\n const {\n // default not abortable\n abortable = false,\n responseType,\n timeout,\n onProgress,\n onChunk,\n ...rest\n } = fetchInit;\n\n // Preserve user's original signal before modifications (rest.signal will be reassigned in setSignal)\n const userSignal = rest.signal;\n\n // User controller for manual abort (stops all retries)\n let userController: AbortController | undefined;\n if (abortable) {\n userController = new AbortController();\n }\n\n /**\n * Determines if the error should trigger a retry.\n * By default, only network errors (not FetchError) trigger retries.\n */\n const shouldRetry = (error: Error, attempt: number): boolean => {\n // Never retry on user abort\n if (error.name === ABORT_ERROR) {\n return false;\n }\n\n if (!retryWhen) {\n // Default: only retry on network errors (not FetchError/HTTP errors)\n return !(error instanceof FetchError);\n }\n\n if (Array.isArray(retryWhen)) {\n // Retry on specific HTTP status codes\n return error instanceof FetchError && retryWhen.includes(error.status);\n }\n\n // Custom retry condition\n return retryWhen(error, attempt);\n };\n\n /**\n * Calculates the delay before the next retry attempt.\n */\n const getRetryDelay = (attempt: number): number => {\n return typeof retryDelay === 'function'\n ? retryDelay(attempt)\n : retryDelay;\n };\n\n /**\n * Configures the abort signal for a fetch attempt.\n *\n * Combines multiple signals:\n * - User's external signal (from init.signal)\n * - Internal abort controller signal (for abortable requests)\n * - Timeout signal (creates a new one each call for per-attempt timeout)\n *\n * Must be called before each fetch attempt to ensure fresh timeout signal on retries.\n */\n const configureSignal = (): void => {\n const signals: AbortSignal[] = [];\n\n // Merge user's signal from init (if provided)\n if (userSignal) {\n signals.push(userSignal);\n }\n\n if (userController) {\n signals.push(userController.signal);\n }\n\n if (typeof timeout === 'number') {\n signals.push(AbortSignal.timeout(timeout));\n }\n\n // Combine all signals\n if (signals.length > 0) {\n rest.signal = signals.length === 1\n ? signals[0]\n : AbortSignal.any(signals);\n }\n };\n\n /**\n * Performs a single fetch attempt with optional timeout.\n */\n const doFetch = async (): AsyncIOResult<FetchResponseData> => {\n configureSignal();\n\n try {\n const response = await fetch(url, rest);\n\n if (!response.ok) {\n // Cancel the response body to free resources\n response.body?.cancel().catch(() => {\n // Silently ignore stream cancel errors\n });\n return Err(new FetchError(response.statusText, response.status));\n }\n\n return await processResponse(response);\n } catch (err) {\n return Err(err instanceof Error\n ? err\n // Non-Error type, most likely an abort reason\n : wrapAbortReason(err),\n );\n }\n };\n\n /**\n * Sets up progress tracking and chunk callbacks using a cloned response.\n * The original response is returned unchanged for further processing.\n */\n const setupProgressCallbacks = async (response: Response): Promise<void> => {\n let totalByteLength: number | undefined;\n let completedByteLength = 0;\n\n if (onProgress) {\n const contentLength = response.headers.get('content-length');\n if (contentLength == null) {\n try {\n onProgress(Err(new Error('No content-length in response headers')));\n } catch {\n // Silently ignore user callback errors\n }\n } else {\n totalByteLength = Number.parseInt(contentLength, 10);\n }\n }\n\n const body = response.clone().body as ReadableStream<Uint8Array<ArrayBuffer>>;\n\n try {\n for await (const chunk of body) {\n if (onChunk) {\n try {\n onChunk(chunk);\n } catch {\n // Silently ignore user callback errors\n }\n }\n\n if (onProgress && totalByteLength != null) {\n completedByteLength += chunk.byteLength;\n try {\n onProgress(Ok({\n totalByteLength,\n completedByteLength,\n }));\n } catch {\n // Silently ignore user callback errors\n }\n }\n }\n } catch {\n // Silently ignore stream read errors\n }\n };\n\n /**\n * Processes the response based on responseType and callbacks.\n */\n const processResponse = async (response: Response): AsyncIOResult<FetchResponseData> => {\n // Setup progress/chunk callbacks if needed (uses cloned response internally)\n if (response.body && (onProgress || onChunk)) {\n setupProgressCallbacks(response);\n }\n\n switch (responseType) {\n case 'json': {\n // Align with stream behavior: no body yields Ok(null)\n if (response.body == null) {\n return Ok(null);\n }\n try {\n return Ok(await response.json());\n } catch {\n return Err(new Error('Response is invalid json while responseType is json'));\n }\n }\n case 'text': {\n return Ok(await response.text());\n }\n case 'bytes': {\n // Use native bytes() if available, otherwise fallback to arrayBuffer()\n if (typeof response.bytes === 'function') {\n return Ok(await response.bytes());\n }\n // Fallback for older environments\n return Ok(new Uint8Array(await response.arrayBuffer()));\n }\n case 'arraybuffer': {\n return Ok(await response.arrayBuffer());\n }\n case 'blob': {\n return Ok(await response.blob());\n }\n case 'stream': {\n return Ok(response.body);\n }\n default: {\n // default return the original Response object to preserve all metadata\n return Ok(response);\n }\n }\n };\n\n /**\n * Performs fetch with retry logic.\n */\n const fetchWithRetry = async (): FetchResponse<FetchResponseData, Error> => {\n let lastError: Error | undefined;\n let attempt = 0;\n\n do {\n // Before retry (not first attempt), wait for delay\n if (attempt > 0) {\n // Check if user aborted before delay (e.g., aborted in `when` callback)\n if (userController?.signal.aborted) {\n return Err(userController.signal.reason as Error);\n }\n\n const delayMs = getRetryDelay(attempt);\n // Wait for delay if necessary\n if (delayMs > 0) {\n await delay(delayMs);\n\n // Check if user aborted during delay\n if (userController?.signal.aborted) {\n return Err(userController.signal.reason as Error);\n }\n }\n\n // Call onRetry right before the actual retry request\n try {\n onRetry?.(lastError as Error, attempt);\n } catch {\n // Silently ignore user callback errors\n }\n }\n\n const result = await doFetch();\n\n if (result.isOk()) {\n return result;\n }\n\n lastError = result.unwrapErr();\n attempt++;\n\n // Check if we should retry\n } while (attempt <= retries && shouldRetry(lastError, attempt));\n\n // No more retries or should not retry\n // lastError is guaranteed to be defined here because:\n // 1. do...while loop executes at least once\n // 2. We only reach here if result.isErr()\n return Err(lastError);\n };\n\n const response = fetchWithRetry();\n\n if (abortable && userController) {\n return {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n abort(reason?: any): void {\n if (reason instanceof Error) {\n userController.abort(reason);\n } else if (reason != null) {\n userController.abort(wrapAbortReason(reason));\n } else {\n userController.abort();\n }\n },\n\n get aborted(): boolean {\n return userController.signal.aborted;\n },\n\n get response(): FetchResponse<FetchResponseData> {\n return response;\n },\n };\n }\n\n return response;\n}\n\n/**\n * Delays execution for the specified number of milliseconds.\n */\nfunction delay(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\n/**\n * Wraps a non-Error abort reason into an Error with ABORT_ERROR name.\n */\nfunction wrapAbortReason(reason: unknown): Error {\n const error = new Error(typeof reason === 'string' ? reason : String(reason));\n error.name = ABORT_ERROR;\n error.cause = reason;\n return error;\n}\n\ninterface ParsedRetryOptions extends FetchRetryOptions {\n retries: number;\n delay: number | ((attempt: number) => number);\n}\n\n/**\n * Validates fetch options and parses retry configuration.\n */\nfunction validateOptions(init: FetchInit): ParsedRetryOptions {\n const {\n responseType,\n timeout,\n retry: retryOptions = 0,\n onProgress,\n onChunk,\n } = init;\n\n if (responseType != null) {\n const validTypes = ['text', 'arraybuffer', 'blob', 'json', 'bytes', 'stream'];\n invariant(validTypes.includes(responseType), () => `responseType must be one of ${ validTypes.join(', ') } but received ${ responseType }`);\n }\n\n if (timeout != null) {\n invariant(typeof timeout === 'number' && timeout > 0, () => `timeout must be a number greater than 0 but received ${ timeout }`);\n }\n\n if (onProgress != null) {\n invariant(typeof onProgress === 'function', () => `onProgress callback must be a function but received ${ typeof onProgress }`);\n }\n\n if (onChunk != null) {\n invariant(typeof onChunk === 'function', () => `onChunk callback must be a function but received ${ typeof onChunk }`);\n }\n\n // Parse retry options\n let retries = 0;\n let delay: number | ((attempt: number) => number) = 0;\n let when: ((error: Error, attempt: number) => boolean) | number[] | undefined;\n let onRetry: ((error: Error, attempt: number) => void) | undefined;\n\n if (typeof retryOptions === 'number') {\n retries = retryOptions;\n } else if (retryOptions && typeof retryOptions === 'object') {\n retries = retryOptions.retries ?? 0;\n delay = retryOptions.delay ?? 0;\n when = retryOptions.when;\n onRetry = retryOptions.onRetry;\n }\n\n invariant(Number.isInteger(retries) && retries >= 0, () => `Retry count must be a non-negative integer but received ${ retries }`);\n\n if (typeof delay === 'number') {\n invariant(delay >= 0, () => `Retry delay must be a non-negative number but received ${ delay }`);\n } else {\n invariant(typeof delay === 'function', () => `Retry delay must be a number or a function but received ${ typeof delay }`);\n }\n\n if (when != null) {\n invariant(Array.isArray(when) || typeof when === 'function', () => `Retry when condition must be an array of status codes or a function but received ${ typeof when }`);\n }\n\n if (onRetry != null) {\n invariant(typeof onRetry === 'function', () => `Retry onRetry callback must be a function but received ${ typeof onRetry }`);\n }\n\n return { retries, delay, when, onRetry };\n}\n"],"names":["response","Err","Ok","delay"],"mappings":";;;;;;;AAqBO,MAAM,WAAA,GAAc;AAuBpB,MAAM,aAAA,GAAgB;;AC6RtB,MAAM,mBAAmB,KAAA,CAAM;AAAA;AAAA;AAAA;AAAA,EAIzB,IAAA,GAAO,YAAA;AAAA;AAAA;AAAA;AAAA,EAKhB,MAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,WAAA,CAAY,SAAiB,MAAA,EAAgB;AACzC,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,EAClB;AACJ;;AC9EO,SAAS,MAAA,CAAO,KAAmB,IAAA,EAAmF;AAEzH,EAAA,IAAI,OAAO,QAAQ,QAAA,EAAU;AACzB,IAAA,SAAA,CAAU,GAAA,YAAe,GAAA,EAAK,MAAM,CAAA,gDAAA,EAAoD,GAAI,CAAA,CAAE,CAAA;AAAA,EAClG;AAEA,EAAA,MAAM,SAAA,GAAY,QAAQ,EAAC;AAE3B,EAAA,MAAM;AAAA,IACF,OAAA;AAAA,IACA,KAAA,EAAO,UAAA;AAAA,IACP,IAAA,EAAM,SAAA;AAAA,IACN;AAAA,GACJ,GAAI,gBAAgB,SAAS,CAAA;AAE7B,EAAA,MAAM;AAAA;AAAA,IAEF,SAAA,GAAY,KAAA;AAAA,IACZ,YAAA;AAAA,IACA,OAAA;AAAA,IACA,UAAA;AAAA,IACA,OAAA;AAAA,IACA,GAAG;AAAA,GACP,GAAI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AY,UAAA,EAAY,MAAM,CAAA,uDAAA,EAA2D,OAAO,OAAQ,CAAA,CAAE,CAAA;AAAA,EAC/H;AAEA,EAAA,OAAO,EAAE,OAAA,EAAS,KAAA,EAAAA,MAAAA,EAAO,MAAM,OAAA,EAAQ;AAC3C;;;;;;;"}
1
+ {"version":3,"file":"main.cjs","sources":["../src/fetch/constants.ts","../src/fetch/defines.ts","../src/fetch/fetch.ts"],"sourcesContent":["/**\n * Error name for aborted fetch requests.\n *\n * This matches the standard `AbortError` name used by the Fetch API when a request\n * is cancelled via `AbortController.abort()`.\n *\n * @example\n * ```typescript\n * import { fetchT, ABORT_ERROR } from '@happy-ts/fetch-t';\n *\n * const task = fetchT('https://api.example.com/data', { abortable: true });\n * task.abort();\n *\n * const result = await task.response;\n * result.inspectErr((err) => {\n * if (err.name === ABORT_ERROR) {\n * console.log('Request was aborted');\n * }\n * });\n * ```\n */\nexport const ABORT_ERROR = 'AbortError' as const;\n\n/**\n * Error name for timed out fetch requests.\n *\n * This is set on the `Error.name` property when a request exceeds the specified\n * `timeout` duration and is automatically aborted.\n *\n * @example\n * ```typescript\n * import { fetchT, TIMEOUT_ERROR } from '@happy-ts/fetch-t';\n *\n * const result = await fetchT('https://api.example.com/slow-endpoint', {\n * timeout: 5000, // 5 seconds\n * });\n *\n * result.inspectErr((err) => {\n * if (err.name === TIMEOUT_ERROR) {\n * console.log('Request timed out after 5 seconds');\n * }\n * });\n * ```\n */\nexport const TIMEOUT_ERROR = 'TimeoutError' as const;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { AsyncResult, IOResult } from 'happy-rusty';\n\n/**\n * Union type of all possible fetchT response data types.\n *\n * Used when `responseType` is a dynamic string value rather than a literal type,\n * as the exact return type cannot be determined at compile time.\n *\n * @example\n * ```typescript\n * import { fetchT, type FetchResponseData } from '@happy-ts/fetch-t';\n *\n * // When responseType is dynamic, return type is FetchResponseData\n * const responseType = getResponseType(); // returns string\n * const result = await fetchT('https://api.example.com/data', { responseType });\n * // result is Result<FetchResponseData, Error>\n * ```\n */\nexport type FetchResponseData =\n | string\n | ArrayBuffer\n | Blob\n | Uint8Array<ArrayBuffer>\n | ReadableStream<Uint8Array<ArrayBuffer>>\n | Response\n | null;\n\n/**\n * Represents the response of a fetch operation as an async Result type.\n *\n * This is an alias for `AsyncResult<T, E>` from the `happy-rusty` library,\n * providing Rust-like error handling without throwing exceptions.\n *\n * @typeParam T - The type of the data expected in a successful response.\n * @typeParam E - The type of the error (defaults to `any`). Typically `Error` or `FetchError`.\n *\n * @example\n * ```typescript\n * import { fetchT, type FetchResponse } from '@happy-ts/fetch-t';\n *\n * // FetchResponse is a Promise that resolves to Result<T, E>\n * const response: FetchResponse<string> = fetchT('https://api.example.com', {\n * responseType: 'text',\n * });\n *\n * const result = await response;\n * result\n * .inspect((text) => console.log('Success:', text))\n * .inspectErr((err) => console.error('Error:', err));\n * ```\n */\nexport type FetchResponse<T, E = any> = AsyncResult<T, E>;\n\n/**\n * Represents an abortable fetch operation with control methods.\n *\n * Returned when `abortable: true` is set in the fetch options. Provides\n * the ability to cancel the request and check its abort status.\n *\n * @typeParam T - The type of the data expected in the response.\n *\n * @example\n * ```typescript\n * import { fetchT, type FetchTask } from '@happy-ts/fetch-t';\n *\n * interface User {\n * id: number;\n * name: string;\n * }\n *\n * const task: FetchTask<User> = fetchT<User>('https://api.example.com/user/1', {\n * abortable: true,\n * responseType: 'json',\n * });\n *\n * // Check if aborted\n * console.log('Is aborted:', task.aborted); // false\n *\n * // Abort with optional reason\n * task.abort('User navigated away');\n *\n * // Access the response (will be an error after abort)\n * const result = await task.response;\n * result.inspectErr((err) => console.log('Aborted:', err.message));\n * ```\n */\nexport interface FetchTask<T> {\n /**\n * Aborts the fetch task, optionally with a reason.\n *\n * Once aborted, the `response` promise will resolve to an `Err` containing\n * an `AbortError`. The abort reason can be any value and will be passed\n * to the underlying `AbortController.abort()`.\n *\n * @param reason - An optional value indicating why the task was aborted.\n * This can be an Error, string, or any other value.\n */\n abort(reason?: any): void;\n\n /**\n * Indicates whether the fetch task has been aborted.\n *\n * Returns `true` if `abort()` was called or if the request timed out.\n */\n readonly aborted: boolean;\n\n /**\n * The response promise of the fetch task.\n *\n * Resolves to `Ok<T>` on success, or `Err<Error>` on failure (including abort).\n */\n readonly response: FetchResponse<T>;\n}\n\n/**\n * Specifies the expected response type for automatic parsing.\n *\n * - `'text'` - Parse response as string via `Response.text()`\n * - `'json'` - Parse response as JSON via `Response.json()`\n * - `'arraybuffer'` - Parse response as ArrayBuffer via `Response.arrayBuffer()`\n * - `'bytes'` - Parse response as Uint8Array<ArrayBuffer> via `Response.bytes()` (with fallback for older environments)\n * - `'blob'` - Parse response as Blob via `Response.blob()`\n * - `'stream'` - Return the raw `ReadableStream` for streaming processing\n *\n * If not specified, the raw `Response` object is returned.\n *\n * @example\n * ```typescript\n * import { fetchT, type FetchResponseType } from '@happy-ts/fetch-t';\n *\n * const responseType: FetchResponseType = 'json';\n *\n * const result = await fetchT('https://api.example.com/data', { responseType });\n * ```\n */\nexport type FetchResponseType = 'text' | 'arraybuffer' | 'blob' | 'json' | 'bytes' | 'stream';\n\n/**\n * Represents the download progress of a fetch operation.\n *\n * Passed to the `onProgress` callback when tracking download progress.\n * Note: Progress tracking requires the server to send a `Content-Length` header.\n *\n * @example\n * ```typescript\n * import { fetchT, type FetchProgress } from '@happy-ts/fetch-t';\n *\n * await fetchT('https://example.com/file.zip', {\n * responseType: 'blob',\n * onProgress: (result) => {\n * result.inspect((progress: FetchProgress) => {\n * const percent = (progress.completedByteLength / progress.totalByteLength) * 100;\n * console.log(`Downloaded: ${percent.toFixed(1)}%`);\n * });\n * },\n * });\n * ```\n */\nexport interface FetchProgress {\n /**\n * The total number of bytes to be received (from Content-Length header).\n */\n totalByteLength: number;\n\n /**\n * The number of bytes received so far.\n */\n completedByteLength: number;\n}\n\n/**\n * Options for configuring retry behavior.\n */\nexport interface FetchRetryOptions {\n /**\n * Number of times to retry the request on failure.\n *\n * By default, only network errors trigger retries. HTTP errors (4xx, 5xx)\n * require explicit configuration via `when`.\n *\n * @default 0 (no retries)\n */\n retries?: number;\n\n /**\n * Delay between retry attempts in milliseconds.\n *\n * Can be a static number or a function for custom strategies like exponential backoff.\n * The function receives the current attempt number (1-indexed).\n *\n * @default 0 (immediate retry)\n */\n delay?: number | ((attempt: number) => number);\n\n /**\n * Conditions under which to retry the request.\n *\n * Can be an array of HTTP status codes or a custom function.\n * By default, only network errors (not FetchError) trigger retries.\n */\n when?: number[] | ((error: Error, attempt: number) => boolean);\n\n /**\n * Callback invoked before each retry attempt.\n *\n * Useful for logging, metrics, or adjusting request parameters.\n */\n onRetry?: (error: Error, attempt: number) => void;\n}\n\n/**\n * Extended fetch options that add additional capabilities to the standard `RequestInit`.\n *\n * @example\n * ```typescript\n * import { fetchT, type FetchInit } from '@happy-ts/fetch-t';\n *\n * const options: FetchInit = {\n * // Standard RequestInit options\n * method: 'POST',\n * headers: { 'Content-Type': 'application/json' },\n * body: JSON.stringify({ key: 'value' }),\n *\n * // Extended options\n * abortable: true, // Return FetchTask for manual abort control\n * responseType: 'json', // Auto-parse response as JSON\n * timeout: 10000, // Abort after 10 seconds\n * onProgress: (result) => { // Track download progress\n * result.inspect(({ completedByteLength, totalByteLength }) => {\n * console.log(`${completedByteLength}/${totalByteLength}`);\n * });\n * },\n * onChunk: (chunk) => { // Receive raw data chunks\n * console.log('Received chunk:', chunk.byteLength, 'bytes');\n * },\n * };\n *\n * const task = fetchT('https://api.example.com/upload', options);\n * ```\n */\nexport interface FetchInit extends RequestInit {\n /**\n * When `true`, returns a `FetchTask` instead of `FetchResponse`.\n *\n * The `FetchTask` provides `abort()` method and `aborted` status.\n *\n * @default false\n */\n abortable?: boolean;\n\n /**\n * Specifies how the response body should be parsed.\n *\n * - `'text'` - Returns `string`\n * - `'json'` - Returns parsed JSON (type `T`)\n * - `'arraybuffer'` - Returns `ArrayBuffer`\n * - `'bytes'` - Returns `Uint8Array<ArrayBuffer>` (with fallback for older environments)\n * - `'blob'` - Returns `Blob`\n * - `'stream'` - Returns `ReadableStream<Uint8Array<ArrayBuffer>>`\n * - `undefined` - Returns raw `Response` object\n *\n * When using a dynamic string value (not a literal type), the return type\n * will be `FetchResponseData` (union of all possible types).\n */\n responseType?: FetchResponseType;\n\n /**\n * Maximum time in milliseconds to wait for the request to complete.\n *\n * If exceeded, the request is automatically aborted with a `TimeoutError`.\n * Must be a positive number.\n */\n timeout?: number;\n\n /**\n * Retry options.\n *\n * Can be a number (shorthand for retries count) or an options object.\n *\n * @example\n * ```typescript\n * // Retry up to 3 times on network errors\n * const result = await fetchT('https://api.example.com/data', {\n * retry: 3,\n * });\n *\n * // Detailed configuration\n * const result = await fetchT('https://api.example.com/data', {\n * retry: {\n * retries: 3,\n * delay: 1000,\n * when: [500, 502],\n * onRetry: (error, attempt) => console.log(error),\n * },\n * });\n * ```\n */\n retry?: number | FetchRetryOptions;\n\n /**\n * Callback invoked during download to report progress.\n *\n * Receives an `IOResult<FetchProgress>`:\n * - `Ok(FetchProgress)` - Progress update with byte counts\n * - `Err(Error)` - If `Content-Length` header is missing (called once)\n *\n * @param progressResult - The progress result, either success with progress data or error.\n */\n onProgress?: (progressResult: IOResult<FetchProgress>) => void;\n\n /**\n * Callback invoked when a chunk of data is received.\n *\n * Useful for streaming or processing data as it arrives.\n * Each chunk is a `Uint8Array<ArrayBuffer>` containing the raw bytes.\n *\n * @param chunk - The raw data chunk received from the response stream.\n */\n onChunk?: (chunk: Uint8Array<ArrayBuffer>) => void;\n}\n\n/**\n * Custom error class for HTTP error responses (non-2xx status codes).\n *\n * Thrown when `Response.ok` is `false`. Contains the HTTP status code\n * for programmatic error handling.\n *\n * @example\n * ```typescript\n * import { fetchT, FetchError } from '@happy-ts/fetch-t';\n *\n * const result = await fetchT('https://api.example.com/not-found', {\n * responseType: 'json',\n * });\n *\n * result.inspectErr((err) => {\n * if (err instanceof FetchError) {\n * console.log('HTTP Status:', err.status); // e.g., 404\n * console.log('Status Text:', err.message); // e.g., \"Not Found\"\n *\n * // Handle specific status codes\n * switch (err.status) {\n * case 401:\n * console.log('Unauthorized - please login');\n * break;\n * case 404:\n * console.log('Resource not found');\n * break;\n * case 500:\n * console.log('Server error');\n * break;\n * }\n * }\n * });\n * ```\n */\nexport class FetchError extends Error {\n /**\n * The error name, always `'FetchError'`.\n */\n override name = 'FetchError';\n\n /**\n * The HTTP status code of the response (e.g., 404, 500).\n */\n status: number;\n\n /**\n * Creates a new FetchError instance.\n *\n * @param message - The status text from the HTTP response (e.g., \"Not Found\").\n * @param status - The HTTP status code (e.g., 404).\n */\n constructor(message: string, status: number) {\n super(message);\n this.status = status;\n }\n}\n","import { Err, Ok, type AsyncIOResult } from 'happy-rusty';\nimport invariant from 'tiny-invariant';\nimport { ABORT_ERROR } from './constants.ts';\nimport { FetchError, type FetchInit, type FetchResponse, type FetchResponseData, type FetchResponseType, type FetchRetryOptions, type FetchTask } from './defines.ts';\n\n/**\n * Fetches a resource from the network as a text string and returns an abortable `FetchTask`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and `responseType: 'text'`.\n * @returns A `FetchTask` representing the abortable operation with a `string` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'text';\n}): FetchTask<string>;\n\n/**\n * Fetches a resource from the network as an ArrayBuffer and returns an abortable `FetchTask`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and `responseType: 'arraybuffer'`.\n * @returns A `FetchTask` representing the abortable operation with an `ArrayBuffer` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'arraybuffer';\n}): FetchTask<ArrayBuffer>;\n\n/**\n * Fetches a resource from the network as a Blob and returns an abortable `FetchTask`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and `responseType: 'blob'`.\n * @returns A `FetchTask` representing the abortable operation with a `Blob` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'blob';\n}): FetchTask<Blob>;\n\n/**\n * Fetches a resource from the network and parses it as JSON, returning an abortable `FetchTask`.\n *\n * @typeParam T - The expected type of the parsed JSON data.\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and `responseType: 'json'`.\n * @returns A `FetchTask` representing the abortable operation with a response parsed as type `T`.\n */\nexport function fetchT<T>(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'json';\n}): FetchTask<T | null>;\n\n/**\n * Fetches a resource from the network as a ReadableStream and returns an abortable `FetchTask`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and `responseType: 'stream'`.\n * @returns A `FetchTask` representing the abortable operation with a `ReadableStream<Uint8Array<ArrayBuffer>>` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'stream';\n}): FetchTask<ReadableStream<Uint8Array<ArrayBuffer>> | null>;\n\n/**\n * Fetches a resource from the network as a Uint8Array<ArrayBuffer> and returns an abortable `FetchTask`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and `responseType: 'bytes'`.\n * @returns A `FetchTask` representing the abortable operation with a `Uint8Array<ArrayBuffer>` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'bytes';\n}): FetchTask<Uint8Array<ArrayBuffer>>;\n\n/**\n * Fetches a resource from the network and returns an abortable `FetchTask` with a dynamic response type.\n *\n * Use this overload when `responseType` is a `FetchResponseType` union type.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and a `FetchResponseType`.\n * @returns A `FetchTask` representing the abortable operation with a `FetchResponseData` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: FetchResponseType;\n}): FetchTask<FetchResponseData>;\n\n/**\n * Fetches a resource from the network as a text string.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `responseType: 'text'` and `abortable` must be `false` or omitted.\n * @returns A `FetchResponse` representing the operation with a `string` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable?: false;\n responseType: 'text';\n}): FetchResponse<string, Error>;\n\n/**\n * Fetches a resource from the network as an ArrayBuffer.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `responseType: 'arraybuffer'` and `abortable` must be `false` or omitted.\n * @returns A `FetchResponse` representing the operation with an `ArrayBuffer` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable?: false;\n responseType: 'arraybuffer';\n}): FetchResponse<ArrayBuffer, Error>;\n\n/**\n * Fetches a resource from the network as a Blob.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `responseType: 'blob'` and `abortable` must be `false` or omitted.\n * @returns A `FetchResponse` representing the operation with a `Blob` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable?: false;\n responseType: 'blob';\n}): FetchResponse<Blob, Error>;\n\n/**\n * Fetches a resource from the network and parses it as JSON.\n *\n * @typeParam T - The expected type of the parsed JSON data.\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `responseType: 'json'` and `abortable` must be `false` or omitted.\n * @returns A `FetchResponse` representing the operation with a response parsed as type `T`.\n */\nexport function fetchT<T>(url: string | URL, init: FetchInit & {\n abortable?: false;\n responseType: 'json';\n}): FetchResponse<T | null, Error>;\n\n/**\n * Fetches a resource from the network as a ReadableStream.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `responseType: 'stream'` and `abortable` must be `false` or omitted.\n * @returns A `FetchResponse` representing the operation with a `ReadableStream<Uint8Array<ArrayBuffer>>` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable?: false;\n responseType: 'stream';\n}): FetchResponse<ReadableStream<Uint8Array<ArrayBuffer>> | null, Error>;\n\n/**\n * Fetches a resource from the network as a Uint8Array<ArrayBuffer>.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `responseType: 'bytes'` and `abortable` must be `false` or omitted.\n * @returns A `FetchResponse` representing the operation with a `Uint8Array<ArrayBuffer>` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable?: false;\n responseType: 'bytes';\n}): FetchResponse<Uint8Array<ArrayBuffer>, Error>;\n\n/**\n * Fetches a resource from the network with a dynamic response type (non-abortable).\n *\n * Use this overload when `responseType` is a `FetchResponseType` union type.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation with a `FetchResponseType`, and `abortable` must be `false` or omitted.\n * @returns A `FetchResponse` representing the operation with a `FetchResponseData` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable?: false;\n responseType: FetchResponseType;\n}): FetchResponse<FetchResponseData, Error>;\n\n/**\n * Fetches a resource from the network and returns an abortable `FetchTask` with a generic `Response`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true`.\n * @returns A `FetchTask` representing the abortable operation with a `Response` object.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n}): FetchTask<Response>;\n\n/**\n * Fetches a resource from the network and returns a `FetchResponse` with a generic `Response` object.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Optional additional options for the fetch operation, and `abortable` must be `false` or omitted.\n * @returns A `FetchResponse` representing the operation with a `Response` object.\n */\nexport function fetchT(url: string | URL, init?: FetchInit & {\n abortable?: false;\n}): FetchResponse<Response>;\n\n/**\n * Enhanced fetch function that wraps the native Fetch API with additional capabilities.\n *\n * Features:\n * - **Abortable requests**: Set `abortable: true` to get a `FetchTask` with `abort()` method.\n * - **Type-safe responses**: Use `responseType` to automatically parse responses as text, JSON, ArrayBuffer, or Blob.\n * - **Timeout support**: Set `timeout` in milliseconds to auto-abort long-running requests.\n * - **Progress tracking**: Use `onProgress` callback to track download progress (requires Content-Length header).\n * - **Chunk streaming**: Use `onChunk` callback to receive raw data chunks as they arrive.\n * - **Retry support**: Use `retry` to automatically retry failed requests with configurable delay and conditions.\n * - **Result type error handling**: Returns `Result<T, Error>` instead of throwing exceptions.\n *\n * @typeParam T - The expected type of the response data.\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, extending standard `RequestInit` with custom properties.\n * @returns A `FetchTask<T>` if `abortable: true`, otherwise a `FetchResponse<T>` (which is `AsyncResult<T, Error>`).\n * @throws {Error} If `url` is not a string or URL object.\n * @throws {Error} If `timeout` is specified but is not a positive number.\n *\n * @example\n * // Basic GET request - returns Response object wrapped in Result\n * const result = await fetchT('https://api.example.com/data');\n * result\n * .inspect((res) => console.log('Status:', res.status))\n * .inspectErr((err) => console.error('Error:', err));\n *\n * @example\n * // GET JSON with type safety\n * interface User {\n * id: number;\n * name: string;\n * }\n * const result = await fetchT<User>('https://api.example.com/user/1', {\n * responseType: 'json',\n * });\n * result.inspect((user) => console.log(user.name));\n *\n * @example\n * // POST request with JSON body\n * const result = await fetchT<User>('https://api.example.com/users', {\n * method: 'POST',\n * headers: { 'Content-Type': 'application/json' },\n * body: JSON.stringify({ name: 'John' }),\n * responseType: 'json',\n * });\n *\n * @example\n * // Abortable request with timeout\n * const task = fetchT('https://api.example.com/data', {\n * abortable: true,\n * timeout: 5000, // 5 seconds\n * });\n *\n * // Cancel the request if needed\n * task.abort('User cancelled');\n *\n * // Check if aborted\n * console.log('Aborted:', task.aborted);\n *\n * // Wait for response\n * const result = await task.response;\n *\n * @example\n * // Track download progress\n * const result = await fetchT('https://example.com/large-file.zip', {\n * responseType: 'blob',\n * onProgress: (progressResult) => {\n * progressResult\n * .inspect(({ completedByteLength, totalByteLength }) => {\n * const percent = ((completedByteLength / totalByteLength) * 100).toFixed(1);\n * console.log(`Progress: ${percent}%`);\n * })\n * .inspectErr((err) => console.warn('Progress unavailable:', err.message));\n * },\n * });\n *\n * @example\n * // Stream data chunks\n * const chunks: Uint8Array[] = [];\n * const result = await fetchT('https://example.com/stream', {\n * onChunk: (chunk) => chunks.push(chunk),\n * });\n *\n * @example\n * // Retry with exponential backoff\n * const result = await fetchT('https://api.example.com/data', {\n * retry: {\n * retries: 3,\n * delay: (attempt) => Math.min(1000 * Math.pow(2, attempt - 1), 10000),\n * when: [500, 502, 503, 504],\n * onRetry: (error, attempt) => console.log(`Retry ${attempt}: ${error.message}`),\n * },\n * responseType: 'json',\n * });\n */\nexport function fetchT(url: string | URL, init?: FetchInit): FetchTask<FetchResponseData> | FetchResponse<FetchResponseData> {\n // Validate and parse URL\n const parsedUrl = validateUrl(url);\n\n const fetchInit = init ?? {};\n\n const {\n retries,\n delay: retryDelay,\n when: retryWhen,\n onRetry,\n } = validateOptions(fetchInit);\n\n const {\n // default not abortable\n abortable = false,\n responseType,\n timeout,\n onProgress,\n onChunk,\n ...rest\n } = fetchInit;\n\n // Preserve user's original signal before modifications (rest.signal will be reassigned in setSignal)\n const userSignal = rest.signal;\n\n // User controller for manual abort (stops all retries)\n let userController: AbortController | undefined;\n if (abortable) {\n userController = new AbortController();\n }\n\n /**\n * Determines if the error should trigger a retry.\n * By default, only network errors (not FetchError) trigger retries.\n */\n const shouldRetry = (error: Error, attempt: number): boolean => {\n // Never retry on user abort\n if (error.name === ABORT_ERROR) {\n return false;\n }\n\n if (!retryWhen) {\n // Default: only retry on network errors (not FetchError/HTTP errors)\n return !(error instanceof FetchError);\n }\n\n if (Array.isArray(retryWhen)) {\n // Retry on specific HTTP status codes\n return error instanceof FetchError && retryWhen.includes(error.status);\n }\n\n // Custom retry condition\n return retryWhen(error, attempt);\n };\n\n /**\n * Calculates the delay before the next retry attempt.\n */\n const getRetryDelay = (attempt: number): number => {\n return typeof retryDelay === 'function'\n ? retryDelay(attempt)\n : retryDelay;\n };\n\n /**\n * Configures the abort signal for a fetch attempt.\n *\n * Combines multiple signals:\n * - User's external signal (from init.signal)\n * - Internal abort controller signal (for abortable requests)\n * - Timeout signal (creates a new one each call for per-attempt timeout)\n *\n * Must be called before each fetch attempt to ensure fresh timeout signal on retries.\n */\n const configureSignal = (): void => {\n const signals: AbortSignal[] = [];\n\n // Merge user's signal from init (if provided)\n if (userSignal) {\n signals.push(userSignal);\n }\n\n if (userController) {\n signals.push(userController.signal);\n }\n\n if (typeof timeout === 'number') {\n signals.push(AbortSignal.timeout(timeout));\n }\n\n // Combine all signals\n if (signals.length > 0) {\n rest.signal = signals.length === 1\n ? signals[0]\n : AbortSignal.any(signals);\n }\n };\n\n /**\n * Performs a single fetch attempt with optional timeout.\n */\n const doFetch = async (): AsyncIOResult<FetchResponseData> => {\n configureSignal();\n\n try {\n const response = await fetch(parsedUrl, rest);\n\n if (!response.ok) {\n // Cancel the response body to free resources\n response.body?.cancel().catch(() => {\n // Silently ignore stream cancel errors\n });\n return Err(new FetchError(response.statusText, response.status));\n }\n\n return await processResponse(response);\n } catch (err) {\n return Err(err instanceof Error\n ? err\n // Non-Error type, most likely an abort reason\n : wrapAbortReason(err),\n );\n }\n };\n\n /**\n * Sets up progress tracking and chunk callbacks using a cloned response.\n * The original response is returned unchanged for further processing.\n */\n const setupProgressCallbacks = async (response: Response): Promise<void> => {\n let totalByteLength: number | undefined;\n let completedByteLength = 0;\n\n if (onProgress) {\n const contentLength = response.headers.get('content-length');\n if (contentLength == null) {\n try {\n onProgress(Err(new Error('No content-length in response headers')));\n } catch {\n // Silently ignore user callback errors\n }\n } else {\n totalByteLength = Number.parseInt(contentLength, 10);\n }\n }\n\n const body = response.clone().body as ReadableStream<Uint8Array<ArrayBuffer>>;\n\n try {\n for await (const chunk of body) {\n if (onChunk) {\n try {\n onChunk(chunk);\n } catch {\n // Silently ignore user callback errors\n }\n }\n\n if (onProgress && totalByteLength != null) {\n completedByteLength += chunk.byteLength;\n try {\n onProgress(Ok({\n totalByteLength,\n completedByteLength,\n }));\n } catch {\n // Silently ignore user callback errors\n }\n }\n }\n } catch {\n // Silently ignore stream read errors\n }\n };\n\n /**\n * Processes the response based on responseType and callbacks.\n */\n const processResponse = async (response: Response): AsyncIOResult<FetchResponseData> => {\n // Setup progress/chunk callbacks if needed (uses cloned response internally)\n if (response.body && (onProgress || onChunk)) {\n setupProgressCallbacks(response);\n }\n\n switch (responseType) {\n case 'json': {\n // Align with stream behavior: no body yields Ok(null)\n if (response.body == null) {\n return Ok(null);\n }\n try {\n return Ok(await response.json());\n } catch {\n return Err(new Error('Response is invalid json while responseType is json'));\n }\n }\n case 'text': {\n return Ok(await response.text());\n }\n case 'bytes': {\n // Use native bytes() if available, otherwise fallback to arrayBuffer()\n if (typeof response.bytes === 'function') {\n return Ok(await response.bytes());\n }\n // Fallback for older environments\n return Ok(new Uint8Array(await response.arrayBuffer()));\n }\n case 'arraybuffer': {\n return Ok(await response.arrayBuffer());\n }\n case 'blob': {\n return Ok(await response.blob());\n }\n case 'stream': {\n return Ok(response.body);\n }\n default: {\n // default return the original Response object to preserve all metadata\n return Ok(response);\n }\n }\n };\n\n /**\n * Performs fetch with retry logic.\n */\n const fetchWithRetry = async (): FetchResponse<FetchResponseData, Error> => {\n let lastError: Error | undefined;\n let attempt = 0;\n\n do {\n // Before retry (not first attempt), wait for delay\n if (attempt > 0) {\n // Check if user aborted before delay (e.g., aborted in `when` callback)\n if (userController?.signal.aborted) {\n return Err(userController.signal.reason as Error);\n }\n\n const delayMs = getRetryDelay(attempt);\n // Wait for delay if necessary\n if (delayMs > 0) {\n await delay(delayMs);\n\n // Check if user aborted during delay\n if (userController?.signal.aborted) {\n return Err(userController.signal.reason as Error);\n }\n }\n\n // Call onRetry right before the actual retry request\n try {\n onRetry?.(lastError as Error, attempt);\n } catch {\n // Silently ignore user callback errors\n }\n }\n\n const result = await doFetch();\n\n if (result.isOk()) {\n return result;\n }\n\n lastError = result.unwrapErr();\n attempt++;\n\n // Check if we should retry\n } while (attempt <= retries && shouldRetry(lastError, attempt));\n\n // No more retries or should not retry\n // lastError is guaranteed to be defined here because:\n // 1. do...while loop executes at least once\n // 2. We only reach here if result.isErr()\n return Err(lastError);\n };\n\n const response = fetchWithRetry();\n\n if (abortable && userController) {\n return {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n abort(reason?: any): void {\n if (reason instanceof Error) {\n userController.abort(reason);\n } else if (reason != null) {\n userController.abort(wrapAbortReason(reason));\n } else {\n userController.abort();\n }\n },\n\n get aborted(): boolean {\n return userController.signal.aborted;\n },\n\n get response(): FetchResponse<FetchResponseData> {\n return response;\n },\n };\n }\n\n return response;\n}\n\n/**\n * Delays execution for the specified number of milliseconds.\n */\nfunction delay(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\n/**\n * Wraps a non-Error abort reason into an Error with ABORT_ERROR name.\n */\nfunction wrapAbortReason(reason: unknown): Error {\n const error = new Error(typeof reason === 'string' ? reason : String(reason));\n error.name = ABORT_ERROR;\n error.cause = reason;\n return error;\n}\n\ninterface ParsedRetryOptions extends FetchRetryOptions {\n retries: number;\n delay: number | ((attempt: number) => number);\n}\n\n/**\n * Validates fetch options and parses retry configuration.\n */\nfunction validateOptions(init: FetchInit): ParsedRetryOptions {\n const {\n responseType,\n timeout,\n retry: retryOptions = 0,\n onProgress,\n onChunk,\n } = init;\n\n if (responseType != null) {\n const validTypes = ['text', 'arraybuffer', 'blob', 'json', 'bytes', 'stream'];\n invariant(validTypes.includes(responseType), () => `responseType must be one of ${ validTypes.join(', ') } but received ${ responseType }`);\n }\n\n if (timeout != null) {\n invariant(typeof timeout === 'number' && timeout > 0, () => `timeout must be a number greater than 0 but received ${ timeout }`);\n }\n\n if (onProgress != null) {\n invariant(typeof onProgress === 'function', () => `onProgress callback must be a function but received ${ typeof onProgress }`);\n }\n\n if (onChunk != null) {\n invariant(typeof onChunk === 'function', () => `onChunk callback must be a function but received ${ typeof onChunk }`);\n }\n\n // Parse retry options\n let retries = 0;\n let delay: number | ((attempt: number) => number) = 0;\n let when: ((error: Error, attempt: number) => boolean) | number[] | undefined;\n let onRetry: ((error: Error, attempt: number) => void) | undefined;\n\n if (typeof retryOptions === 'number') {\n retries = retryOptions;\n } else if (retryOptions && typeof retryOptions === 'object') {\n retries = retryOptions.retries ?? 0;\n delay = retryOptions.delay ?? 0;\n when = retryOptions.when;\n onRetry = retryOptions.onRetry;\n }\n\n invariant(Number.isInteger(retries) && retries >= 0, () => `Retry count must be a non-negative integer but received ${ retries }`);\n\n if (typeof delay === 'number') {\n invariant(delay >= 0, () => `Retry delay must be a non-negative number but received ${ delay }`);\n } else {\n invariant(typeof delay === 'function', () => `Retry delay must be a number or a function but received ${ typeof delay }`);\n }\n\n if (when != null) {\n invariant(Array.isArray(when) || typeof when === 'function', () => `Retry when condition must be an array of status codes or a function but received ${ typeof when }`);\n }\n\n if (onRetry != null) {\n invariant(typeof onRetry === 'function', () => `Retry onRetry callback must be a function but received ${ typeof onRetry }`);\n }\n\n return { retries, delay, when, onRetry };\n}\n\n/**\n * Validates and parses a URL string or URL object.\n * In browser environments, relative URLs are resolved against `location.href`.\n * In non-browser environments (Node/Deno/Bun), only absolute URLs are valid.\n *\n * @param url - The URL to validate, either a string or URL object.\n * @returns The parsed URL object.\n * @throws {TypeError} If the URL is invalid or cannot be parsed.\n */\nfunction validateUrl(url: string | URL): URL {\n if (url instanceof URL) {\n return url;\n }\n\n try {\n // In browser, use location.href as base for relative URLs\n // In Node/Deno/Bun, location is undefined, so relative URLs will fail\n const base = typeof location !== 'undefined' ? location.href : undefined;\n return new URL(url, base);\n } catch {\n throw new TypeError(`Invalid URL: ${ url }`);\n }\n}\n"],"names":["response","Err","Ok","delay"],"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,IAAI,CAAA;AAAA,EAC5B,CAAA,CAAA,MAAQ;AACJ,IAAA,MAAM,IAAI,SAAA,CAAU,CAAA,aAAA,EAAiB,GAAI,CAAA,CAAE,CAAA;AAAA,EAC/C;AACJ;;;;;;;"}
package/dist/main.mjs CHANGED
@@ -26,9 +26,7 @@ class FetchError extends Error {
26
26
  }
27
27
 
28
28
  function fetchT(url, init) {
29
- if (typeof url !== "string") {
30
- invariant(url instanceof URL, () => `Url must be a string or URL object but received ${url}`);
31
- }
29
+ const parsedUrl = validateUrl(url);
32
30
  const fetchInit = init ?? {};
33
31
  const {
34
32
  retries,
@@ -83,7 +81,7 @@ function fetchT(url, init) {
83
81
  const doFetch = async () => {
84
82
  configureSignal();
85
83
  try {
86
- const response2 = await fetch(url, rest);
84
+ const response2 = await fetch(parsedUrl, rest);
87
85
  if (!response2.ok) {
88
86
  response2.body?.cancel().catch(() => {
89
87
  });
@@ -279,6 +277,17 @@ function validateOptions(init) {
279
277
  }
280
278
  return { retries, delay: delay2, when, onRetry };
281
279
  }
280
+ function validateUrl(url) {
281
+ if (url instanceof URL) {
282
+ return url;
283
+ }
284
+ try {
285
+ const base = typeof location !== "undefined" ? location.href : void 0;
286
+ return new URL(url, base);
287
+ } catch {
288
+ throw new TypeError(`Invalid URL: ${url}`);
289
+ }
290
+ }
282
291
 
283
292
  export { ABORT_ERROR, FetchError, TIMEOUT_ERROR, fetchT };
284
293
  //# sourceMappingURL=main.mjs.map
package/dist/main.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"main.mjs","sources":["../src/fetch/constants.ts","../src/fetch/defines.ts","../src/fetch/fetch.ts"],"sourcesContent":["/**\n * Error name for aborted fetch requests.\n *\n * This matches the standard `AbortError` name used by the Fetch API when a request\n * is cancelled via `AbortController.abort()`.\n *\n * @example\n * ```typescript\n * import { fetchT, ABORT_ERROR } from '@happy-ts/fetch-t';\n *\n * const task = fetchT('https://api.example.com/data', { abortable: true });\n * task.abort();\n *\n * const result = await task.response;\n * result.inspectErr((err) => {\n * if (err.name === ABORT_ERROR) {\n * console.log('Request was aborted');\n * }\n * });\n * ```\n */\nexport const ABORT_ERROR = 'AbortError' as const;\n\n/**\n * Error name for timed out fetch requests.\n *\n * This is set on the `Error.name` property when a request exceeds the specified\n * `timeout` duration and is automatically aborted.\n *\n * @example\n * ```typescript\n * import { fetchT, TIMEOUT_ERROR } from '@happy-ts/fetch-t';\n *\n * const result = await fetchT('https://api.example.com/slow-endpoint', {\n * timeout: 5000, // 5 seconds\n * });\n *\n * result.inspectErr((err) => {\n * if (err.name === TIMEOUT_ERROR) {\n * console.log('Request timed out after 5 seconds');\n * }\n * });\n * ```\n */\nexport const TIMEOUT_ERROR = 'TimeoutError' as const;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { AsyncResult, IOResult } from 'happy-rusty';\n\n/**\n * Represents the response of a fetch operation as an async Result type.\n *\n * This is an alias for `AsyncResult<T, E>` from the `happy-rusty` library,\n * providing Rust-like error handling without throwing exceptions.\n *\n * @typeParam T - The type of the data expected in a successful response.\n * @typeParam E - The type of the error (defaults to `any`). Typically `Error` or `FetchError`.\n *\n * @example\n * ```typescript\n * import { fetchT, type FetchResponse } from '@happy-ts/fetch-t';\n *\n * // FetchResponse is a Promise that resolves to Result<T, E>\n * const response: FetchResponse<string> = fetchT('https://api.example.com', {\n * responseType: 'text',\n * });\n *\n * const result = await response;\n * result\n * .inspect((text) => console.log('Success:', text))\n * .inspectErr((err) => console.error('Error:', err));\n * ```\n */\nexport type FetchResponse<T, E = any> = AsyncResult<T, E>;\n\n/**\n * Represents an abortable fetch operation with control methods.\n *\n * Returned when `abortable: true` is set in the fetch options. Provides\n * the ability to cancel the request and check its abort status.\n *\n * @typeParam T - The type of the data expected in the response.\n *\n * @example\n * ```typescript\n * import { fetchT, type FetchTask } from '@happy-ts/fetch-t';\n *\n * interface User {\n * id: number;\n * name: string;\n * }\n *\n * const task: FetchTask<User> = fetchT<User>('https://api.example.com/user/1', {\n * abortable: true,\n * responseType: 'json',\n * });\n *\n * // Check if aborted\n * console.log('Is aborted:', task.aborted); // false\n *\n * // Abort with optional reason\n * task.abort('User navigated away');\n *\n * // Access the response (will be an error after abort)\n * const result = await task.response;\n * result.inspectErr((err) => console.log('Aborted:', err.message));\n * ```\n */\nexport interface FetchTask<T> {\n /**\n * Aborts the fetch task, optionally with a reason.\n *\n * Once aborted, the `response` promise will resolve to an `Err` containing\n * an `AbortError`. The abort reason can be any value and will be passed\n * to the underlying `AbortController.abort()`.\n *\n * @param reason - An optional value indicating why the task was aborted.\n * This can be an Error, string, or any other value.\n */\n abort(reason?: any): void;\n\n /**\n * Indicates whether the fetch task has been aborted.\n *\n * Returns `true` if `abort()` was called or if the request timed out.\n */\n readonly aborted: boolean;\n\n /**\n * The response promise of the fetch task.\n *\n * Resolves to `Ok<T>` on success, or `Err<Error>` on failure (including abort).\n */\n readonly response: FetchResponse<T>;\n}\n\n/**\n * Specifies the expected response type for automatic parsing.\n *\n * - `'text'` - Parse response as string via `Response.text()`\n * - `'json'` - Parse response as JSON via `Response.json()`\n * - `'arraybuffer'` - Parse response as ArrayBuffer via `Response.arrayBuffer()`\n * - `'bytes'` - Parse response as Uint8Array<ArrayBuffer> via `Response.bytes()` (with fallback for older environments)\n * - `'blob'` - Parse response as Blob via `Response.blob()`\n * - `'stream'` - Return the raw `ReadableStream` for streaming processing\n *\n * If not specified, the raw `Response` object is returned.\n *\n * @example\n * ```typescript\n * import { fetchT, type FetchResponseType } from '@happy-ts/fetch-t';\n *\n * const responseType: FetchResponseType = 'json';\n *\n * const result = await fetchT('https://api.example.com/data', { responseType });\n * ```\n */\nexport type FetchResponseType = 'text' | 'arraybuffer' | 'blob' | 'json' | 'bytes' | 'stream';\n\n/**\n * Represents the download progress of a fetch operation.\n *\n * Passed to the `onProgress` callback when tracking download progress.\n * Note: Progress tracking requires the server to send a `Content-Length` header.\n *\n * @example\n * ```typescript\n * import { fetchT, type FetchProgress } from '@happy-ts/fetch-t';\n *\n * await fetchT('https://example.com/file.zip', {\n * responseType: 'blob',\n * onProgress: (result) => {\n * result.inspect((progress: FetchProgress) => {\n * const percent = (progress.completedByteLength / progress.totalByteLength) * 100;\n * console.log(`Downloaded: ${percent.toFixed(1)}%`);\n * });\n * },\n * });\n * ```\n */\nexport interface FetchProgress {\n /**\n * The total number of bytes to be received (from Content-Length header).\n */\n totalByteLength: number;\n\n /**\n * The number of bytes received so far.\n */\n completedByteLength: number;\n}\n\n/**\n * Options for configuring retry behavior.\n */\nexport interface FetchRetryOptions {\n /**\n * Number of times to retry the request on failure.\n *\n * By default, only network errors trigger retries. HTTP errors (4xx, 5xx)\n * require explicit configuration via `when`.\n *\n * @default 0 (no retries)\n */\n retries?: number;\n\n /**\n * Delay between retry attempts in milliseconds.\n *\n * Can be a static number or a function for custom strategies like exponential backoff.\n * The function receives the current attempt number (1-indexed).\n *\n * @default 0 (immediate retry)\n */\n delay?: number | ((attempt: number) => number);\n\n /**\n * Conditions under which to retry the request.\n *\n * Can be an array of HTTP status codes or a custom function.\n * By default, only network errors (not FetchError) trigger retries.\n */\n when?: number[] | ((error: Error, attempt: number) => boolean);\n\n /**\n * Callback invoked before each retry attempt.\n *\n * Useful for logging, metrics, or adjusting request parameters.\n */\n onRetry?: (error: Error, attempt: number) => void;\n}\n\n/**\n * Extended fetch options that add additional capabilities to the standard `RequestInit`.\n *\n * @example\n * ```typescript\n * import { fetchT, type FetchInit } from '@happy-ts/fetch-t';\n *\n * const options: FetchInit = {\n * // Standard RequestInit options\n * method: 'POST',\n * headers: { 'Content-Type': 'application/json' },\n * body: JSON.stringify({ key: 'value' }),\n *\n * // Extended options\n * abortable: true, // Return FetchTask for manual abort control\n * responseType: 'json', // Auto-parse response as JSON\n * timeout: 10000, // Abort after 10 seconds\n * onProgress: (result) => { // Track download progress\n * result.inspect(({ completedByteLength, totalByteLength }) => {\n * console.log(`${completedByteLength}/${totalByteLength}`);\n * });\n * },\n * onChunk: (chunk) => { // Receive raw data chunks\n * console.log('Received chunk:', chunk.byteLength, 'bytes');\n * },\n * };\n *\n * const task = fetchT('https://api.example.com/upload', options);\n * ```\n */\nexport interface FetchInit extends RequestInit {\n /**\n * When `true`, returns a `FetchTask` instead of `FetchResponse`.\n *\n * The `FetchTask` provides `abort()` method and `aborted` status.\n *\n * @default false\n */\n abortable?: boolean;\n\n /**\n * Specifies how the response body should be parsed.\n *\n * - `'text'` - Returns `string`\n * - `'json'` - Returns parsed JSON (type `T`)\n * - `'arraybuffer'` - Returns `ArrayBuffer`\n * - `'bytes'` - Returns `Uint8Array<ArrayBuffer>` (with fallback for older environments)\n * - `'blob'` - Returns `Blob`\n * - `'stream'` - Returns `ReadableStream<Uint8Array<ArrayBuffer>>`\n * - `undefined` - Returns raw `Response` object\n */\n responseType?: FetchResponseType;\n\n /**\n * Maximum time in milliseconds to wait for the request to complete.\n *\n * If exceeded, the request is automatically aborted with a `TimeoutError`.\n * Must be a positive number.\n */\n timeout?: number;\n\n /**\n * Retry options.\n *\n * Can be a number (shorthand for retries count) or an options object.\n *\n * @example\n * ```typescript\n * // Retry up to 3 times on network errors\n * const result = await fetchT('https://api.example.com/data', {\n * retry: 3,\n * });\n *\n * // Detailed configuration\n * const result = await fetchT('https://api.example.com/data', {\n * retry: {\n * retries: 3,\n * delay: 1000,\n * when: [500, 502],\n * onRetry: (error, attempt) => console.log(error),\n * },\n * });\n * ```\n */\n retry?: number | FetchRetryOptions;\n\n /**\n * Callback invoked during download to report progress.\n *\n * Receives an `IOResult<FetchProgress>`:\n * - `Ok(FetchProgress)` - Progress update with byte counts\n * - `Err(Error)` - If `Content-Length` header is missing (called once)\n *\n * @param progressResult - The progress result, either success with progress data or error.\n */\n onProgress?: (progressResult: IOResult<FetchProgress>) => void;\n\n /**\n * Callback invoked when a chunk of data is received.\n *\n * Useful for streaming or processing data as it arrives.\n * Each chunk is a `Uint8Array<ArrayBuffer>` containing the raw bytes.\n *\n * @param chunk - The raw data chunk received from the response stream.\n */\n onChunk?: (chunk: Uint8Array<ArrayBuffer>) => void;\n}\n\n/**\n * Custom error class for HTTP error responses (non-2xx status codes).\n *\n * Thrown when `Response.ok` is `false`. Contains the HTTP status code\n * for programmatic error handling.\n *\n * @example\n * ```typescript\n * import { fetchT, FetchError } from '@happy-ts/fetch-t';\n *\n * const result = await fetchT('https://api.example.com/not-found', {\n * responseType: 'json',\n * });\n *\n * result.inspectErr((err) => {\n * if (err instanceof FetchError) {\n * console.log('HTTP Status:', err.status); // e.g., 404\n * console.log('Status Text:', err.message); // e.g., \"Not Found\"\n *\n * // Handle specific status codes\n * switch (err.status) {\n * case 401:\n * console.log('Unauthorized - please login');\n * break;\n * case 404:\n * console.log('Resource not found');\n * break;\n * case 500:\n * console.log('Server error');\n * break;\n * }\n * }\n * });\n * ```\n */\nexport class FetchError extends Error {\n /**\n * The error name, always `'FetchError'`.\n */\n override name = 'FetchError';\n\n /**\n * The HTTP status code of the response (e.g., 404, 500).\n */\n status: number;\n\n /**\n * Creates a new FetchError instance.\n *\n * @param message - The status text from the HTTP response (e.g., \"Not Found\").\n * @param status - The HTTP status code (e.g., 404).\n */\n constructor(message: string, status: number) {\n super(message);\n this.status = status;\n }\n}\n","import { Err, Ok, type AsyncIOResult } from 'happy-rusty';\nimport invariant from 'tiny-invariant';\nimport { ABORT_ERROR } from './constants.ts';\nimport { FetchError, type FetchInit, type FetchResponse, type FetchRetryOptions, type FetchTask } from './defines.ts';\n\n/**\n * Union type of all possible fetchT response data types.\n * Internal type used only in the implementation signature.\n */\ntype FetchResponseData =\n | string\n | ArrayBuffer\n | Blob\n | Uint8Array<ArrayBuffer>\n | ReadableStream<Uint8Array<ArrayBuffer>> | null\n | Response;\n\n/**\n * Fetches a resource from the network as a text string and returns an abortable `FetchTask`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and `responseType: 'text'`.\n * @returns A `FetchTask` representing the abortable operation with a `string` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'text';\n}): FetchTask<string>;\n\n/**\n * Fetches a resource from the network as an ArrayBuffer and returns an abortable `FetchTask`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and `responseType: 'arraybuffer'`.\n * @returns A `FetchTask` representing the abortable operation with an `ArrayBuffer` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'arraybuffer';\n}): FetchTask<ArrayBuffer>;\n\n/**\n * Fetches a resource from the network as a Blob and returns an abortable `FetchTask`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and `responseType: 'blob'`.\n * @returns A `FetchTask` representing the abortable operation with a `Blob` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'blob';\n}): FetchTask<Blob>;\n\n/**\n * Fetches a resource from the network and parses it as JSON, returning an abortable `FetchTask`.\n *\n * @typeParam T - The expected type of the parsed JSON data.\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and `responseType: 'json'`.\n * @returns A `FetchTask` representing the abortable operation with a response parsed as type `T`.\n */\nexport function fetchT<T>(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'json';\n}): FetchTask<T | null>;\n\n/**\n * Fetches a resource from the network as a ReadableStream and returns an abortable `FetchTask`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and `responseType: 'stream'`.\n * @returns A `FetchTask` representing the abortable operation with a `ReadableStream<Uint8Array<ArrayBuffer>>` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'stream';\n}): FetchTask<ReadableStream<Uint8Array<ArrayBuffer>> | null>;\n\n/**\n * Fetches a resource from the network as a Uint8Array<ArrayBuffer> and returns an abortable `FetchTask`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and `responseType: 'bytes'`.\n * @returns A `FetchTask` representing the abortable operation with a `Uint8Array<ArrayBuffer>` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'bytes';\n}): FetchTask<Uint8Array<ArrayBuffer>>;\n\n/**\n * Fetches a resource from the network as a text string.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `responseType: 'text'`.\n * @returns A `FetchResponse` representing the operation with a `string` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n responseType: 'text';\n}): FetchResponse<string, Error>;\n\n/**\n * Fetches a resource from the network as an ArrayBuffer.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `responseType: 'arraybuffer'`.\n * @returns A `FetchResponse` representing the operation with an `ArrayBuffer` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n responseType: 'arraybuffer';\n}): FetchResponse<ArrayBuffer, Error>;\n\n/**\n * Fetches a resource from the network as a Blob.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `responseType: 'blob'`.\n * @returns A `FetchResponse` representing the operation with a `Blob` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n responseType: 'blob';\n}): FetchResponse<Blob, Error>;\n\n/**\n * Fetches a resource from the network and parses it as JSON.\n *\n * @typeParam T - The expected type of the parsed JSON data.\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `responseType: 'json'`.\n * @returns A `FetchResponse` representing the operation with a response parsed as type `T`.\n */\nexport function fetchT<T>(url: string | URL, init: FetchInit & {\n responseType: 'json';\n}): FetchResponse<T | null, Error>;\n\n/**\n * Fetches a resource from the network as a ReadableStream.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `responseType: 'stream'`.\n * @returns A `FetchResponse` representing the operation with a `ReadableStream<Uint8Array<ArrayBuffer>>` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n responseType: 'stream';\n}): FetchResponse<ReadableStream<Uint8Array<ArrayBuffer>> | null, Error>;\n\n/**\n * Fetches a resource from the network as a Uint8Array<ArrayBuffer>.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `responseType: 'bytes'`.\n * @returns A `FetchResponse` representing the operation with a `Uint8Array<ArrayBuffer>` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n responseType: 'bytes';\n}): FetchResponse<Uint8Array<ArrayBuffer>, Error>;\n\n/**\n * Fetches a resource from the network and returns an abortable `FetchTask` with a generic `Response`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true`.\n * @returns A `FetchTask` representing the abortable operation with a `Response` object.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n}): FetchTask<Response>;\n\n/**\n * Fetches a resource from the network and returns a `FetchResponse` with a generic `Response` object.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Optional additional options for the fetch operation.\n * @returns A `FetchResponse` representing the operation with a `Response` object.\n */\nexport function fetchT(url: string | URL, init?: FetchInit): FetchResponse<Response>;\n\n/**\n * Enhanced fetch function that wraps the native Fetch API with additional capabilities.\n *\n * Features:\n * - **Abortable requests**: Set `abortable: true` to get a `FetchTask` with `abort()` method.\n * - **Type-safe responses**: Use `responseType` to automatically parse responses as text, JSON, ArrayBuffer, or Blob.\n * - **Timeout support**: Set `timeout` in milliseconds to auto-abort long-running requests.\n * - **Progress tracking**: Use `onProgress` callback to track download progress (requires Content-Length header).\n * - **Chunk streaming**: Use `onChunk` callback to receive raw data chunks as they arrive.\n * - **Retry support**: Use `retry` to automatically retry failed requests with configurable delay and conditions.\n * - **Result type error handling**: Returns `Result<T, Error>` instead of throwing exceptions.\n *\n * @typeParam T - The expected type of the response data.\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, extending standard `RequestInit` with custom properties.\n * @returns A `FetchTask<T>` if `abortable: true`, otherwise a `FetchResponse<T>` (which is `AsyncResult<T, Error>`).\n * @throws {Error} If `url` is not a string or URL object.\n * @throws {Error} If `timeout` is specified but is not a positive number.\n *\n * @example\n * // Basic GET request - returns Response object wrapped in Result\n * const result = await fetchT('https://api.example.com/data');\n * result\n * .inspect((res) => console.log('Status:', res.status))\n * .inspectErr((err) => console.error('Error:', err));\n *\n * @example\n * // GET JSON with type safety\n * interface User {\n * id: number;\n * name: string;\n * }\n * const result = await fetchT<User>('https://api.example.com/user/1', {\n * responseType: 'json',\n * });\n * result.inspect((user) => console.log(user.name));\n *\n * @example\n * // POST request with JSON body\n * const result = await fetchT<User>('https://api.example.com/users', {\n * method: 'POST',\n * headers: { 'Content-Type': 'application/json' },\n * body: JSON.stringify({ name: 'John' }),\n * responseType: 'json',\n * });\n *\n * @example\n * // Abortable request with timeout\n * const task = fetchT('https://api.example.com/data', {\n * abortable: true,\n * timeout: 5000, // 5 seconds\n * });\n *\n * // Cancel the request if needed\n * task.abort('User cancelled');\n *\n * // Check if aborted\n * console.log('Aborted:', task.aborted);\n *\n * // Wait for response\n * const result = await task.response;\n *\n * @example\n * // Track download progress\n * const result = await fetchT('https://example.com/large-file.zip', {\n * responseType: 'blob',\n * onProgress: (progressResult) => {\n * progressResult\n * .inspect(({ completedByteLength, totalByteLength }) => {\n * const percent = ((completedByteLength / totalByteLength) * 100).toFixed(1);\n * console.log(`Progress: ${percent}%`);\n * })\n * .inspectErr((err) => console.warn('Progress unavailable:', err.message));\n * },\n * });\n *\n * @example\n * // Stream data chunks\n * const chunks: Uint8Array[] = [];\n * const result = await fetchT('https://example.com/stream', {\n * onChunk: (chunk) => chunks.push(chunk),\n * });\n *\n * @example\n * // Retry with exponential backoff\n * const result = await fetchT('https://api.example.com/data', {\n * retry: {\n * retries: 3,\n * delay: (attempt) => Math.min(1000 * Math.pow(2, attempt - 1), 10000),\n * when: [500, 502, 503, 504],\n * onRetry: (error, attempt) => console.log(`Retry ${attempt}: ${error.message}`),\n * },\n * responseType: 'json',\n * });\n */\nexport function fetchT(url: string | URL, init?: FetchInit): FetchTask<FetchResponseData> | FetchResponse<FetchResponseData> {\n // Fast path: most URLs are passed as strings\n if (typeof url !== 'string') {\n invariant(url instanceof URL, () => `Url must be a string or URL object but received ${ url }`);\n }\n\n const fetchInit = init ?? {};\n\n const {\n retries,\n delay: retryDelay,\n when: retryWhen,\n onRetry,\n } = validateOptions(fetchInit);\n\n const {\n // default not abortable\n abortable = false,\n responseType,\n timeout,\n onProgress,\n onChunk,\n ...rest\n } = fetchInit;\n\n // Preserve user's original signal before modifications (rest.signal will be reassigned in setSignal)\n const userSignal = rest.signal;\n\n // User controller for manual abort (stops all retries)\n let userController: AbortController | undefined;\n if (abortable) {\n userController = new AbortController();\n }\n\n /**\n * Determines if the error should trigger a retry.\n * By default, only network errors (not FetchError) trigger retries.\n */\n const shouldRetry = (error: Error, attempt: number): boolean => {\n // Never retry on user abort\n if (error.name === ABORT_ERROR) {\n return false;\n }\n\n if (!retryWhen) {\n // Default: only retry on network errors (not FetchError/HTTP errors)\n return !(error instanceof FetchError);\n }\n\n if (Array.isArray(retryWhen)) {\n // Retry on specific HTTP status codes\n return error instanceof FetchError && retryWhen.includes(error.status);\n }\n\n // Custom retry condition\n return retryWhen(error, attempt);\n };\n\n /**\n * Calculates the delay before the next retry attempt.\n */\n const getRetryDelay = (attempt: number): number => {\n return typeof retryDelay === 'function'\n ? retryDelay(attempt)\n : retryDelay;\n };\n\n /**\n * Configures the abort signal for a fetch attempt.\n *\n * Combines multiple signals:\n * - User's external signal (from init.signal)\n * - Internal abort controller signal (for abortable requests)\n * - Timeout signal (creates a new one each call for per-attempt timeout)\n *\n * Must be called before each fetch attempt to ensure fresh timeout signal on retries.\n */\n const configureSignal = (): void => {\n const signals: AbortSignal[] = [];\n\n // Merge user's signal from init (if provided)\n if (userSignal) {\n signals.push(userSignal);\n }\n\n if (userController) {\n signals.push(userController.signal);\n }\n\n if (typeof timeout === 'number') {\n signals.push(AbortSignal.timeout(timeout));\n }\n\n // Combine all signals\n if (signals.length > 0) {\n rest.signal = signals.length === 1\n ? signals[0]\n : AbortSignal.any(signals);\n }\n };\n\n /**\n * Performs a single fetch attempt with optional timeout.\n */\n const doFetch = async (): AsyncIOResult<FetchResponseData> => {\n configureSignal();\n\n try {\n const response = await fetch(url, rest);\n\n if (!response.ok) {\n // Cancel the response body to free resources\n response.body?.cancel().catch(() => {\n // Silently ignore stream cancel errors\n });\n return Err(new FetchError(response.statusText, response.status));\n }\n\n return await processResponse(response);\n } catch (err) {\n return Err(err instanceof Error\n ? err\n // Non-Error type, most likely an abort reason\n : wrapAbortReason(err),\n );\n }\n };\n\n /**\n * Sets up progress tracking and chunk callbacks using a cloned response.\n * The original response is returned unchanged for further processing.\n */\n const setupProgressCallbacks = async (response: Response): Promise<void> => {\n let totalByteLength: number | undefined;\n let completedByteLength = 0;\n\n if (onProgress) {\n const contentLength = response.headers.get('content-length');\n if (contentLength == null) {\n try {\n onProgress(Err(new Error('No content-length in response headers')));\n } catch {\n // Silently ignore user callback errors\n }\n } else {\n totalByteLength = Number.parseInt(contentLength, 10);\n }\n }\n\n const body = response.clone().body as ReadableStream<Uint8Array<ArrayBuffer>>;\n\n try {\n for await (const chunk of body) {\n if (onChunk) {\n try {\n onChunk(chunk);\n } catch {\n // Silently ignore user callback errors\n }\n }\n\n if (onProgress && totalByteLength != null) {\n completedByteLength += chunk.byteLength;\n try {\n onProgress(Ok({\n totalByteLength,\n completedByteLength,\n }));\n } catch {\n // Silently ignore user callback errors\n }\n }\n }\n } catch {\n // Silently ignore stream read errors\n }\n };\n\n /**\n * Processes the response based on responseType and callbacks.\n */\n const processResponse = async (response: Response): AsyncIOResult<FetchResponseData> => {\n // Setup progress/chunk callbacks if needed (uses cloned response internally)\n if (response.body && (onProgress || onChunk)) {\n setupProgressCallbacks(response);\n }\n\n switch (responseType) {\n case 'json': {\n // Align with stream behavior: no body yields Ok(null)\n if (response.body == null) {\n return Ok(null);\n }\n try {\n return Ok(await response.json());\n } catch {\n return Err(new Error('Response is invalid json while responseType is json'));\n }\n }\n case 'text': {\n return Ok(await response.text());\n }\n case 'bytes': {\n // Use native bytes() if available, otherwise fallback to arrayBuffer()\n if (typeof response.bytes === 'function') {\n return Ok(await response.bytes());\n }\n // Fallback for older environments\n return Ok(new Uint8Array(await response.arrayBuffer()));\n }\n case 'arraybuffer': {\n return Ok(await response.arrayBuffer());\n }\n case 'blob': {\n return Ok(await response.blob());\n }\n case 'stream': {\n return Ok(response.body);\n }\n default: {\n // default return the original Response object to preserve all metadata\n return Ok(response);\n }\n }\n };\n\n /**\n * Performs fetch with retry logic.\n */\n const fetchWithRetry = async (): FetchResponse<FetchResponseData, Error> => {\n let lastError: Error | undefined;\n let attempt = 0;\n\n do {\n // Before retry (not first attempt), wait for delay\n if (attempt > 0) {\n // Check if user aborted before delay (e.g., aborted in `when` callback)\n if (userController?.signal.aborted) {\n return Err(userController.signal.reason as Error);\n }\n\n const delayMs = getRetryDelay(attempt);\n // Wait for delay if necessary\n if (delayMs > 0) {\n await delay(delayMs);\n\n // Check if user aborted during delay\n if (userController?.signal.aborted) {\n return Err(userController.signal.reason as Error);\n }\n }\n\n // Call onRetry right before the actual retry request\n try {\n onRetry?.(lastError as Error, attempt);\n } catch {\n // Silently ignore user callback errors\n }\n }\n\n const result = await doFetch();\n\n if (result.isOk()) {\n return result;\n }\n\n lastError = result.unwrapErr();\n attempt++;\n\n // Check if we should retry\n } while (attempt <= retries && shouldRetry(lastError, attempt));\n\n // No more retries or should not retry\n // lastError is guaranteed to be defined here because:\n // 1. do...while loop executes at least once\n // 2. We only reach here if result.isErr()\n return Err(lastError);\n };\n\n const response = fetchWithRetry();\n\n if (abortable && userController) {\n return {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n abort(reason?: any): void {\n if (reason instanceof Error) {\n userController.abort(reason);\n } else if (reason != null) {\n userController.abort(wrapAbortReason(reason));\n } else {\n userController.abort();\n }\n },\n\n get aborted(): boolean {\n return userController.signal.aborted;\n },\n\n get response(): FetchResponse<FetchResponseData> {\n return response;\n },\n };\n }\n\n return response;\n}\n\n/**\n * Delays execution for the specified number of milliseconds.\n */\nfunction delay(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\n/**\n * Wraps a non-Error abort reason into an Error with ABORT_ERROR name.\n */\nfunction wrapAbortReason(reason: unknown): Error {\n const error = new Error(typeof reason === 'string' ? reason : String(reason));\n error.name = ABORT_ERROR;\n error.cause = reason;\n return error;\n}\n\ninterface ParsedRetryOptions extends FetchRetryOptions {\n retries: number;\n delay: number | ((attempt: number) => number);\n}\n\n/**\n * Validates fetch options and parses retry configuration.\n */\nfunction validateOptions(init: FetchInit): ParsedRetryOptions {\n const {\n responseType,\n timeout,\n retry: retryOptions = 0,\n onProgress,\n onChunk,\n } = init;\n\n if (responseType != null) {\n const validTypes = ['text', 'arraybuffer', 'blob', 'json', 'bytes', 'stream'];\n invariant(validTypes.includes(responseType), () => `responseType must be one of ${ validTypes.join(', ') } but received ${ responseType }`);\n }\n\n if (timeout != null) {\n invariant(typeof timeout === 'number' && timeout > 0, () => `timeout must be a number greater than 0 but received ${ timeout }`);\n }\n\n if (onProgress != null) {\n invariant(typeof onProgress === 'function', () => `onProgress callback must be a function but received ${ typeof onProgress }`);\n }\n\n if (onChunk != null) {\n invariant(typeof onChunk === 'function', () => `onChunk callback must be a function but received ${ typeof onChunk }`);\n }\n\n // Parse retry options\n let retries = 0;\n let delay: number | ((attempt: number) => number) = 0;\n let when: ((error: Error, attempt: number) => boolean) | number[] | undefined;\n let onRetry: ((error: Error, attempt: number) => void) | undefined;\n\n if (typeof retryOptions === 'number') {\n retries = retryOptions;\n } else if (retryOptions && typeof retryOptions === 'object') {\n retries = retryOptions.retries ?? 0;\n delay = retryOptions.delay ?? 0;\n when = retryOptions.when;\n onRetry = retryOptions.onRetry;\n }\n\n invariant(Number.isInteger(retries) && retries >= 0, () => `Retry count must be a non-negative integer but received ${ retries }`);\n\n if (typeof delay === 'number') {\n invariant(delay >= 0, () => `Retry delay must be a non-negative number but received ${ delay }`);\n } else {\n invariant(typeof delay === 'function', () => `Retry delay must be a number or a function but received ${ typeof delay }`);\n }\n\n if (when != null) {\n invariant(Array.isArray(when) || typeof when === 'function', () => `Retry when condition must be an array of status codes or a function but received ${ typeof when }`);\n }\n\n if (onRetry != null) {\n invariant(typeof onRetry === 'function', () => `Retry onRetry callback must be a function but received ${ typeof onRetry }`);\n }\n\n return { retries, delay, when, onRetry };\n}\n"],"names":["response","delay"],"mappings":";;;AAqBO,MAAM,WAAA,GAAc;AAuBpB,MAAM,aAAA,GAAgB;;AC6RtB,MAAM,mBAAmB,KAAA,CAAM;AAAA;AAAA;AAAA;AAAA,EAIzB,IAAA,GAAO,YAAA;AAAA;AAAA;AAAA;AAAA,EAKhB,MAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,WAAA,CAAY,SAAiB,MAAA,EAAgB;AACzC,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,EAClB;AACJ;;AC9EO,SAAS,MAAA,CAAO,KAAmB,IAAA,EAAmF;AAEzH,EAAA,IAAI,OAAO,QAAQ,QAAA,EAAU;AACzB,IAAA,SAAA,CAAU,GAAA,YAAe,GAAA,EAAK,MAAM,CAAA,gDAAA,EAAoD,GAAI,CAAA,CAAE,CAAA;AAAA,EAClG;AAEA,EAAA,MAAM,SAAA,GAAY,QAAQ,EAAC;AAE3B,EAAA,MAAM;AAAA,IACF,OAAA;AAAA,IACA,KAAA,EAAO,UAAA;AAAA,IACP,IAAA,EAAM,SAAA;AAAA,IACN;AAAA,GACJ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A,KAAS,UAAA,EAAY,MAAM,CAAA,iFAAA,EAAqF,OAAO,IAAK,CAAA,CAAE,CAAA;AAAA,EAC1K;AAEA,EAAA,IAAI,WAAW,IAAA,EAAM;AACjB,IAAA,SAAA,CAAU,OAAO,OAAA,KAAY,UAAA,EAAY,MAAM,CAAA,uDAAA,EAA2D,OAAO,OAAQ,CAAA,CAAE,CAAA;AAAA,EAC/H;AAEA,EAAA,OAAO,EAAE,OAAA,EAAS,KAAA,EAAAA,MAAAA,EAAO,MAAM,OAAA,EAAQ;AAC3C;;;;"}
1
+ {"version":3,"file":"main.mjs","sources":["../src/fetch/constants.ts","../src/fetch/defines.ts","../src/fetch/fetch.ts"],"sourcesContent":["/**\n * Error name for aborted fetch requests.\n *\n * This matches the standard `AbortError` name used by the Fetch API when a request\n * is cancelled via `AbortController.abort()`.\n *\n * @example\n * ```typescript\n * import { fetchT, ABORT_ERROR } from '@happy-ts/fetch-t';\n *\n * const task = fetchT('https://api.example.com/data', { abortable: true });\n * task.abort();\n *\n * const result = await task.response;\n * result.inspectErr((err) => {\n * if (err.name === ABORT_ERROR) {\n * console.log('Request was aborted');\n * }\n * });\n * ```\n */\nexport const ABORT_ERROR = 'AbortError' as const;\n\n/**\n * Error name for timed out fetch requests.\n *\n * This is set on the `Error.name` property when a request exceeds the specified\n * `timeout` duration and is automatically aborted.\n *\n * @example\n * ```typescript\n * import { fetchT, TIMEOUT_ERROR } from '@happy-ts/fetch-t';\n *\n * const result = await fetchT('https://api.example.com/slow-endpoint', {\n * timeout: 5000, // 5 seconds\n * });\n *\n * result.inspectErr((err) => {\n * if (err.name === TIMEOUT_ERROR) {\n * console.log('Request timed out after 5 seconds');\n * }\n * });\n * ```\n */\nexport const TIMEOUT_ERROR = 'TimeoutError' as const;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { AsyncResult, IOResult } from 'happy-rusty';\n\n/**\n * Union type of all possible fetchT response data types.\n *\n * Used when `responseType` is a dynamic string value rather than a literal type,\n * as the exact return type cannot be determined at compile time.\n *\n * @example\n * ```typescript\n * import { fetchT, type FetchResponseData } from '@happy-ts/fetch-t';\n *\n * // When responseType is dynamic, return type is FetchResponseData\n * const responseType = getResponseType(); // returns string\n * const result = await fetchT('https://api.example.com/data', { responseType });\n * // result is Result<FetchResponseData, Error>\n * ```\n */\nexport type FetchResponseData =\n | string\n | ArrayBuffer\n | Blob\n | Uint8Array<ArrayBuffer>\n | ReadableStream<Uint8Array<ArrayBuffer>>\n | Response\n | null;\n\n/**\n * Represents the response of a fetch operation as an async Result type.\n *\n * This is an alias for `AsyncResult<T, E>` from the `happy-rusty` library,\n * providing Rust-like error handling without throwing exceptions.\n *\n * @typeParam T - The type of the data expected in a successful response.\n * @typeParam E - The type of the error (defaults to `any`). Typically `Error` or `FetchError`.\n *\n * @example\n * ```typescript\n * import { fetchT, type FetchResponse } from '@happy-ts/fetch-t';\n *\n * // FetchResponse is a Promise that resolves to Result<T, E>\n * const response: FetchResponse<string> = fetchT('https://api.example.com', {\n * responseType: 'text',\n * });\n *\n * const result = await response;\n * result\n * .inspect((text) => console.log('Success:', text))\n * .inspectErr((err) => console.error('Error:', err));\n * ```\n */\nexport type FetchResponse<T, E = any> = AsyncResult<T, E>;\n\n/**\n * Represents an abortable fetch operation with control methods.\n *\n * Returned when `abortable: true` is set in the fetch options. Provides\n * the ability to cancel the request and check its abort status.\n *\n * @typeParam T - The type of the data expected in the response.\n *\n * @example\n * ```typescript\n * import { fetchT, type FetchTask } from '@happy-ts/fetch-t';\n *\n * interface User {\n * id: number;\n * name: string;\n * }\n *\n * const task: FetchTask<User> = fetchT<User>('https://api.example.com/user/1', {\n * abortable: true,\n * responseType: 'json',\n * });\n *\n * // Check if aborted\n * console.log('Is aborted:', task.aborted); // false\n *\n * // Abort with optional reason\n * task.abort('User navigated away');\n *\n * // Access the response (will be an error after abort)\n * const result = await task.response;\n * result.inspectErr((err) => console.log('Aborted:', err.message));\n * ```\n */\nexport interface FetchTask<T> {\n /**\n * Aborts the fetch task, optionally with a reason.\n *\n * Once aborted, the `response` promise will resolve to an `Err` containing\n * an `AbortError`. The abort reason can be any value and will be passed\n * to the underlying `AbortController.abort()`.\n *\n * @param reason - An optional value indicating why the task was aborted.\n * This can be an Error, string, or any other value.\n */\n abort(reason?: any): void;\n\n /**\n * Indicates whether the fetch task has been aborted.\n *\n * Returns `true` if `abort()` was called or if the request timed out.\n */\n readonly aborted: boolean;\n\n /**\n * The response promise of the fetch task.\n *\n * Resolves to `Ok<T>` on success, or `Err<Error>` on failure (including abort).\n */\n readonly response: FetchResponse<T>;\n}\n\n/**\n * Specifies the expected response type for automatic parsing.\n *\n * - `'text'` - Parse response as string via `Response.text()`\n * - `'json'` - Parse response as JSON via `Response.json()`\n * - `'arraybuffer'` - Parse response as ArrayBuffer via `Response.arrayBuffer()`\n * - `'bytes'` - Parse response as Uint8Array<ArrayBuffer> via `Response.bytes()` (with fallback for older environments)\n * - `'blob'` - Parse response as Blob via `Response.blob()`\n * - `'stream'` - Return the raw `ReadableStream` for streaming processing\n *\n * If not specified, the raw `Response` object is returned.\n *\n * @example\n * ```typescript\n * import { fetchT, type FetchResponseType } from '@happy-ts/fetch-t';\n *\n * const responseType: FetchResponseType = 'json';\n *\n * const result = await fetchT('https://api.example.com/data', { responseType });\n * ```\n */\nexport type FetchResponseType = 'text' | 'arraybuffer' | 'blob' | 'json' | 'bytes' | 'stream';\n\n/**\n * Represents the download progress of a fetch operation.\n *\n * Passed to the `onProgress` callback when tracking download progress.\n * Note: Progress tracking requires the server to send a `Content-Length` header.\n *\n * @example\n * ```typescript\n * import { fetchT, type FetchProgress } from '@happy-ts/fetch-t';\n *\n * await fetchT('https://example.com/file.zip', {\n * responseType: 'blob',\n * onProgress: (result) => {\n * result.inspect((progress: FetchProgress) => {\n * const percent = (progress.completedByteLength / progress.totalByteLength) * 100;\n * console.log(`Downloaded: ${percent.toFixed(1)}%`);\n * });\n * },\n * });\n * ```\n */\nexport interface FetchProgress {\n /**\n * The total number of bytes to be received (from Content-Length header).\n */\n totalByteLength: number;\n\n /**\n * The number of bytes received so far.\n */\n completedByteLength: number;\n}\n\n/**\n * Options for configuring retry behavior.\n */\nexport interface FetchRetryOptions {\n /**\n * Number of times to retry the request on failure.\n *\n * By default, only network errors trigger retries. HTTP errors (4xx, 5xx)\n * require explicit configuration via `when`.\n *\n * @default 0 (no retries)\n */\n retries?: number;\n\n /**\n * Delay between retry attempts in milliseconds.\n *\n * Can be a static number or a function for custom strategies like exponential backoff.\n * The function receives the current attempt number (1-indexed).\n *\n * @default 0 (immediate retry)\n */\n delay?: number | ((attempt: number) => number);\n\n /**\n * Conditions under which to retry the request.\n *\n * Can be an array of HTTP status codes or a custom function.\n * By default, only network errors (not FetchError) trigger retries.\n */\n when?: number[] | ((error: Error, attempt: number) => boolean);\n\n /**\n * Callback invoked before each retry attempt.\n *\n * Useful for logging, metrics, or adjusting request parameters.\n */\n onRetry?: (error: Error, attempt: number) => void;\n}\n\n/**\n * Extended fetch options that add additional capabilities to the standard `RequestInit`.\n *\n * @example\n * ```typescript\n * import { fetchT, type FetchInit } from '@happy-ts/fetch-t';\n *\n * const options: FetchInit = {\n * // Standard RequestInit options\n * method: 'POST',\n * headers: { 'Content-Type': 'application/json' },\n * body: JSON.stringify({ key: 'value' }),\n *\n * // Extended options\n * abortable: true, // Return FetchTask for manual abort control\n * responseType: 'json', // Auto-parse response as JSON\n * timeout: 10000, // Abort after 10 seconds\n * onProgress: (result) => { // Track download progress\n * result.inspect(({ completedByteLength, totalByteLength }) => {\n * console.log(`${completedByteLength}/${totalByteLength}`);\n * });\n * },\n * onChunk: (chunk) => { // Receive raw data chunks\n * console.log('Received chunk:', chunk.byteLength, 'bytes');\n * },\n * };\n *\n * const task = fetchT('https://api.example.com/upload', options);\n * ```\n */\nexport interface FetchInit extends RequestInit {\n /**\n * When `true`, returns a `FetchTask` instead of `FetchResponse`.\n *\n * The `FetchTask` provides `abort()` method and `aborted` status.\n *\n * @default false\n */\n abortable?: boolean;\n\n /**\n * Specifies how the response body should be parsed.\n *\n * - `'text'` - Returns `string`\n * - `'json'` - Returns parsed JSON (type `T`)\n * - `'arraybuffer'` - Returns `ArrayBuffer`\n * - `'bytes'` - Returns `Uint8Array<ArrayBuffer>` (with fallback for older environments)\n * - `'blob'` - Returns `Blob`\n * - `'stream'` - Returns `ReadableStream<Uint8Array<ArrayBuffer>>`\n * - `undefined` - Returns raw `Response` object\n *\n * When using a dynamic string value (not a literal type), the return type\n * will be `FetchResponseData` (union of all possible types).\n */\n responseType?: FetchResponseType;\n\n /**\n * Maximum time in milliseconds to wait for the request to complete.\n *\n * If exceeded, the request is automatically aborted with a `TimeoutError`.\n * Must be a positive number.\n */\n timeout?: number;\n\n /**\n * Retry options.\n *\n * Can be a number (shorthand for retries count) or an options object.\n *\n * @example\n * ```typescript\n * // Retry up to 3 times on network errors\n * const result = await fetchT('https://api.example.com/data', {\n * retry: 3,\n * });\n *\n * // Detailed configuration\n * const result = await fetchT('https://api.example.com/data', {\n * retry: {\n * retries: 3,\n * delay: 1000,\n * when: [500, 502],\n * onRetry: (error, attempt) => console.log(error),\n * },\n * });\n * ```\n */\n retry?: number | FetchRetryOptions;\n\n /**\n * Callback invoked during download to report progress.\n *\n * Receives an `IOResult<FetchProgress>`:\n * - `Ok(FetchProgress)` - Progress update with byte counts\n * - `Err(Error)` - If `Content-Length` header is missing (called once)\n *\n * @param progressResult - The progress result, either success with progress data or error.\n */\n onProgress?: (progressResult: IOResult<FetchProgress>) => void;\n\n /**\n * Callback invoked when a chunk of data is received.\n *\n * Useful for streaming or processing data as it arrives.\n * Each chunk is a `Uint8Array<ArrayBuffer>` containing the raw bytes.\n *\n * @param chunk - The raw data chunk received from the response stream.\n */\n onChunk?: (chunk: Uint8Array<ArrayBuffer>) => void;\n}\n\n/**\n * Custom error class for HTTP error responses (non-2xx status codes).\n *\n * Thrown when `Response.ok` is `false`. Contains the HTTP status code\n * for programmatic error handling.\n *\n * @example\n * ```typescript\n * import { fetchT, FetchError } from '@happy-ts/fetch-t';\n *\n * const result = await fetchT('https://api.example.com/not-found', {\n * responseType: 'json',\n * });\n *\n * result.inspectErr((err) => {\n * if (err instanceof FetchError) {\n * console.log('HTTP Status:', err.status); // e.g., 404\n * console.log('Status Text:', err.message); // e.g., \"Not Found\"\n *\n * // Handle specific status codes\n * switch (err.status) {\n * case 401:\n * console.log('Unauthorized - please login');\n * break;\n * case 404:\n * console.log('Resource not found');\n * break;\n * case 500:\n * console.log('Server error');\n * break;\n * }\n * }\n * });\n * ```\n */\nexport class FetchError extends Error {\n /**\n * The error name, always `'FetchError'`.\n */\n override name = 'FetchError';\n\n /**\n * The HTTP status code of the response (e.g., 404, 500).\n */\n status: number;\n\n /**\n * Creates a new FetchError instance.\n *\n * @param message - The status text from the HTTP response (e.g., \"Not Found\").\n * @param status - The HTTP status code (e.g., 404).\n */\n constructor(message: string, status: number) {\n super(message);\n this.status = status;\n }\n}\n","import { Err, Ok, type AsyncIOResult } from 'happy-rusty';\nimport invariant from 'tiny-invariant';\nimport { ABORT_ERROR } from './constants.ts';\nimport { FetchError, type FetchInit, type FetchResponse, type FetchResponseData, type FetchResponseType, type FetchRetryOptions, type FetchTask } from './defines.ts';\n\n/**\n * Fetches a resource from the network as a text string and returns an abortable `FetchTask`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and `responseType: 'text'`.\n * @returns A `FetchTask` representing the abortable operation with a `string` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'text';\n}): FetchTask<string>;\n\n/**\n * Fetches a resource from the network as an ArrayBuffer and returns an abortable `FetchTask`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and `responseType: 'arraybuffer'`.\n * @returns A `FetchTask` representing the abortable operation with an `ArrayBuffer` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'arraybuffer';\n}): FetchTask<ArrayBuffer>;\n\n/**\n * Fetches a resource from the network as a Blob and returns an abortable `FetchTask`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and `responseType: 'blob'`.\n * @returns A `FetchTask` representing the abortable operation with a `Blob` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'blob';\n}): FetchTask<Blob>;\n\n/**\n * Fetches a resource from the network and parses it as JSON, returning an abortable `FetchTask`.\n *\n * @typeParam T - The expected type of the parsed JSON data.\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and `responseType: 'json'`.\n * @returns A `FetchTask` representing the abortable operation with a response parsed as type `T`.\n */\nexport function fetchT<T>(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'json';\n}): FetchTask<T | null>;\n\n/**\n * Fetches a resource from the network as a ReadableStream and returns an abortable `FetchTask`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and `responseType: 'stream'`.\n * @returns A `FetchTask` representing the abortable operation with a `ReadableStream<Uint8Array<ArrayBuffer>>` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'stream';\n}): FetchTask<ReadableStream<Uint8Array<ArrayBuffer>> | null>;\n\n/**\n * Fetches a resource from the network as a Uint8Array<ArrayBuffer> and returns an abortable `FetchTask`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and `responseType: 'bytes'`.\n * @returns A `FetchTask` representing the abortable operation with a `Uint8Array<ArrayBuffer>` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: 'bytes';\n}): FetchTask<Uint8Array<ArrayBuffer>>;\n\n/**\n * Fetches a resource from the network and returns an abortable `FetchTask` with a dynamic response type.\n *\n * Use this overload when `responseType` is a `FetchResponseType` union type.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true` and a `FetchResponseType`.\n * @returns A `FetchTask` representing the abortable operation with a `FetchResponseData` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n responseType: FetchResponseType;\n}): FetchTask<FetchResponseData>;\n\n/**\n * Fetches a resource from the network as a text string.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `responseType: 'text'` and `abortable` must be `false` or omitted.\n * @returns A `FetchResponse` representing the operation with a `string` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable?: false;\n responseType: 'text';\n}): FetchResponse<string, Error>;\n\n/**\n * Fetches a resource from the network as an ArrayBuffer.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `responseType: 'arraybuffer'` and `abortable` must be `false` or omitted.\n * @returns A `FetchResponse` representing the operation with an `ArrayBuffer` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable?: false;\n responseType: 'arraybuffer';\n}): FetchResponse<ArrayBuffer, Error>;\n\n/**\n * Fetches a resource from the network as a Blob.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `responseType: 'blob'` and `abortable` must be `false` or omitted.\n * @returns A `FetchResponse` representing the operation with a `Blob` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable?: false;\n responseType: 'blob';\n}): FetchResponse<Blob, Error>;\n\n/**\n * Fetches a resource from the network and parses it as JSON.\n *\n * @typeParam T - The expected type of the parsed JSON data.\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `responseType: 'json'` and `abortable` must be `false` or omitted.\n * @returns A `FetchResponse` representing the operation with a response parsed as type `T`.\n */\nexport function fetchT<T>(url: string | URL, init: FetchInit & {\n abortable?: false;\n responseType: 'json';\n}): FetchResponse<T | null, Error>;\n\n/**\n * Fetches a resource from the network as a ReadableStream.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `responseType: 'stream'` and `abortable` must be `false` or omitted.\n * @returns A `FetchResponse` representing the operation with a `ReadableStream<Uint8Array<ArrayBuffer>>` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable?: false;\n responseType: 'stream';\n}): FetchResponse<ReadableStream<Uint8Array<ArrayBuffer>> | null, Error>;\n\n/**\n * Fetches a resource from the network as a Uint8Array<ArrayBuffer>.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `responseType: 'bytes'` and `abortable` must be `false` or omitted.\n * @returns A `FetchResponse` representing the operation with a `Uint8Array<ArrayBuffer>` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable?: false;\n responseType: 'bytes';\n}): FetchResponse<Uint8Array<ArrayBuffer>, Error>;\n\n/**\n * Fetches a resource from the network with a dynamic response type (non-abortable).\n *\n * Use this overload when `responseType` is a `FetchResponseType` union type.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation with a `FetchResponseType`, and `abortable` must be `false` or omitted.\n * @returns A `FetchResponse` representing the operation with a `FetchResponseData` response.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable?: false;\n responseType: FetchResponseType;\n}): FetchResponse<FetchResponseData, Error>;\n\n/**\n * Fetches a resource from the network and returns an abortable `FetchTask` with a generic `Response`.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, must include `abortable: true`.\n * @returns A `FetchTask` representing the abortable operation with a `Response` object.\n */\nexport function fetchT(url: string | URL, init: FetchInit & {\n abortable: true;\n}): FetchTask<Response>;\n\n/**\n * Fetches a resource from the network and returns a `FetchResponse` with a generic `Response` object.\n *\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Optional additional options for the fetch operation, and `abortable` must be `false` or omitted.\n * @returns A `FetchResponse` representing the operation with a `Response` object.\n */\nexport function fetchT(url: string | URL, init?: FetchInit & {\n abortable?: false;\n}): FetchResponse<Response>;\n\n/**\n * Enhanced fetch function that wraps the native Fetch API with additional capabilities.\n *\n * Features:\n * - **Abortable requests**: Set `abortable: true` to get a `FetchTask` with `abort()` method.\n * - **Type-safe responses**: Use `responseType` to automatically parse responses as text, JSON, ArrayBuffer, or Blob.\n * - **Timeout support**: Set `timeout` in milliseconds to auto-abort long-running requests.\n * - **Progress tracking**: Use `onProgress` callback to track download progress (requires Content-Length header).\n * - **Chunk streaming**: Use `onChunk` callback to receive raw data chunks as they arrive.\n * - **Retry support**: Use `retry` to automatically retry failed requests with configurable delay and conditions.\n * - **Result type error handling**: Returns `Result<T, Error>` instead of throwing exceptions.\n *\n * @typeParam T - The expected type of the response data.\n * @param url - The resource to fetch. Can be a URL object or a string representing a URL.\n * @param init - Additional options for the fetch operation, extending standard `RequestInit` with custom properties.\n * @returns A `FetchTask<T>` if `abortable: true`, otherwise a `FetchResponse<T>` (which is `AsyncResult<T, Error>`).\n * @throws {Error} If `url` is not a string or URL object.\n * @throws {Error} If `timeout` is specified but is not a positive number.\n *\n * @example\n * // Basic GET request - returns Response object wrapped in Result\n * const result = await fetchT('https://api.example.com/data');\n * result\n * .inspect((res) => console.log('Status:', res.status))\n * .inspectErr((err) => console.error('Error:', err));\n *\n * @example\n * // GET JSON with type safety\n * interface User {\n * id: number;\n * name: string;\n * }\n * const result = await fetchT<User>('https://api.example.com/user/1', {\n * responseType: 'json',\n * });\n * result.inspect((user) => console.log(user.name));\n *\n * @example\n * // POST request with JSON body\n * const result = await fetchT<User>('https://api.example.com/users', {\n * method: 'POST',\n * headers: { 'Content-Type': 'application/json' },\n * body: JSON.stringify({ name: 'John' }),\n * responseType: 'json',\n * });\n *\n * @example\n * // Abortable request with timeout\n * const task = fetchT('https://api.example.com/data', {\n * abortable: true,\n * timeout: 5000, // 5 seconds\n * });\n *\n * // Cancel the request if needed\n * task.abort('User cancelled');\n *\n * // Check if aborted\n * console.log('Aborted:', task.aborted);\n *\n * // Wait for response\n * const result = await task.response;\n *\n * @example\n * // Track download progress\n * const result = await fetchT('https://example.com/large-file.zip', {\n * responseType: 'blob',\n * onProgress: (progressResult) => {\n * progressResult\n * .inspect(({ completedByteLength, totalByteLength }) => {\n * const percent = ((completedByteLength / totalByteLength) * 100).toFixed(1);\n * console.log(`Progress: ${percent}%`);\n * })\n * .inspectErr((err) => console.warn('Progress unavailable:', err.message));\n * },\n * });\n *\n * @example\n * // Stream data chunks\n * const chunks: Uint8Array[] = [];\n * const result = await fetchT('https://example.com/stream', {\n * onChunk: (chunk) => chunks.push(chunk),\n * });\n *\n * @example\n * // Retry with exponential backoff\n * const result = await fetchT('https://api.example.com/data', {\n * retry: {\n * retries: 3,\n * delay: (attempt) => Math.min(1000 * Math.pow(2, attempt - 1), 10000),\n * when: [500, 502, 503, 504],\n * onRetry: (error, attempt) => console.log(`Retry ${attempt}: ${error.message}`),\n * },\n * responseType: 'json',\n * });\n */\nexport function fetchT(url: string | URL, init?: FetchInit): FetchTask<FetchResponseData> | FetchResponse<FetchResponseData> {\n // Validate and parse URL\n const parsedUrl = validateUrl(url);\n\n const fetchInit = init ?? {};\n\n const {\n retries,\n delay: retryDelay,\n when: retryWhen,\n onRetry,\n } = validateOptions(fetchInit);\n\n const {\n // default not abortable\n abortable = false,\n responseType,\n timeout,\n onProgress,\n onChunk,\n ...rest\n } = fetchInit;\n\n // Preserve user's original signal before modifications (rest.signal will be reassigned in setSignal)\n const userSignal = rest.signal;\n\n // User controller for manual abort (stops all retries)\n let userController: AbortController | undefined;\n if (abortable) {\n userController = new AbortController();\n }\n\n /**\n * Determines if the error should trigger a retry.\n * By default, only network errors (not FetchError) trigger retries.\n */\n const shouldRetry = (error: Error, attempt: number): boolean => {\n // Never retry on user abort\n if (error.name === ABORT_ERROR) {\n return false;\n }\n\n if (!retryWhen) {\n // Default: only retry on network errors (not FetchError/HTTP errors)\n return !(error instanceof FetchError);\n }\n\n if (Array.isArray(retryWhen)) {\n // Retry on specific HTTP status codes\n return error instanceof FetchError && retryWhen.includes(error.status);\n }\n\n // Custom retry condition\n return retryWhen(error, attempt);\n };\n\n /**\n * Calculates the delay before the next retry attempt.\n */\n const getRetryDelay = (attempt: number): number => {\n return typeof retryDelay === 'function'\n ? retryDelay(attempt)\n : retryDelay;\n };\n\n /**\n * Configures the abort signal for a fetch attempt.\n *\n * Combines multiple signals:\n * - User's external signal (from init.signal)\n * - Internal abort controller signal (for abortable requests)\n * - Timeout signal (creates a new one each call for per-attempt timeout)\n *\n * Must be called before each fetch attempt to ensure fresh timeout signal on retries.\n */\n const configureSignal = (): void => {\n const signals: AbortSignal[] = [];\n\n // Merge user's signal from init (if provided)\n if (userSignal) {\n signals.push(userSignal);\n }\n\n if (userController) {\n signals.push(userController.signal);\n }\n\n if (typeof timeout === 'number') {\n signals.push(AbortSignal.timeout(timeout));\n }\n\n // Combine all signals\n if (signals.length > 0) {\n rest.signal = signals.length === 1\n ? signals[0]\n : AbortSignal.any(signals);\n }\n };\n\n /**\n * Performs a single fetch attempt with optional timeout.\n */\n const doFetch = async (): AsyncIOResult<FetchResponseData> => {\n configureSignal();\n\n try {\n const response = await fetch(parsedUrl, rest);\n\n if (!response.ok) {\n // Cancel the response body to free resources\n response.body?.cancel().catch(() => {\n // Silently ignore stream cancel errors\n });\n return Err(new FetchError(response.statusText, response.status));\n }\n\n return await processResponse(response);\n } catch (err) {\n return Err(err instanceof Error\n ? err\n // Non-Error type, most likely an abort reason\n : wrapAbortReason(err),\n );\n }\n };\n\n /**\n * Sets up progress tracking and chunk callbacks using a cloned response.\n * The original response is returned unchanged for further processing.\n */\n const setupProgressCallbacks = async (response: Response): Promise<void> => {\n let totalByteLength: number | undefined;\n let completedByteLength = 0;\n\n if (onProgress) {\n const contentLength = response.headers.get('content-length');\n if (contentLength == null) {\n try {\n onProgress(Err(new Error('No content-length in response headers')));\n } catch {\n // Silently ignore user callback errors\n }\n } else {\n totalByteLength = Number.parseInt(contentLength, 10);\n }\n }\n\n const body = response.clone().body as ReadableStream<Uint8Array<ArrayBuffer>>;\n\n try {\n for await (const chunk of body) {\n if (onChunk) {\n try {\n onChunk(chunk);\n } catch {\n // Silently ignore user callback errors\n }\n }\n\n if (onProgress && totalByteLength != null) {\n completedByteLength += chunk.byteLength;\n try {\n onProgress(Ok({\n totalByteLength,\n completedByteLength,\n }));\n } catch {\n // Silently ignore user callback errors\n }\n }\n }\n } catch {\n // Silently ignore stream read errors\n }\n };\n\n /**\n * Processes the response based on responseType and callbacks.\n */\n const processResponse = async (response: Response): AsyncIOResult<FetchResponseData> => {\n // Setup progress/chunk callbacks if needed (uses cloned response internally)\n if (response.body && (onProgress || onChunk)) {\n setupProgressCallbacks(response);\n }\n\n switch (responseType) {\n case 'json': {\n // Align with stream behavior: no body yields Ok(null)\n if (response.body == null) {\n return Ok(null);\n }\n try {\n return Ok(await response.json());\n } catch {\n return Err(new Error('Response is invalid json while responseType is json'));\n }\n }\n case 'text': {\n return Ok(await response.text());\n }\n case 'bytes': {\n // Use native bytes() if available, otherwise fallback to arrayBuffer()\n if (typeof response.bytes === 'function') {\n return Ok(await response.bytes());\n }\n // Fallback for older environments\n return Ok(new Uint8Array(await response.arrayBuffer()));\n }\n case 'arraybuffer': {\n return Ok(await response.arrayBuffer());\n }\n case 'blob': {\n return Ok(await response.blob());\n }\n case 'stream': {\n return Ok(response.body);\n }\n default: {\n // default return the original Response object to preserve all metadata\n return Ok(response);\n }\n }\n };\n\n /**\n * Performs fetch with retry logic.\n */\n const fetchWithRetry = async (): FetchResponse<FetchResponseData, Error> => {\n let lastError: Error | undefined;\n let attempt = 0;\n\n do {\n // Before retry (not first attempt), wait for delay\n if (attempt > 0) {\n // Check if user aborted before delay (e.g., aborted in `when` callback)\n if (userController?.signal.aborted) {\n return Err(userController.signal.reason as Error);\n }\n\n const delayMs = getRetryDelay(attempt);\n // Wait for delay if necessary\n if (delayMs > 0) {\n await delay(delayMs);\n\n // Check if user aborted during delay\n if (userController?.signal.aborted) {\n return Err(userController.signal.reason as Error);\n }\n }\n\n // Call onRetry right before the actual retry request\n try {\n onRetry?.(lastError as Error, attempt);\n } catch {\n // Silently ignore user callback errors\n }\n }\n\n const result = await doFetch();\n\n if (result.isOk()) {\n return result;\n }\n\n lastError = result.unwrapErr();\n attempt++;\n\n // Check if we should retry\n } while (attempt <= retries && shouldRetry(lastError, attempt));\n\n // No more retries or should not retry\n // lastError is guaranteed to be defined here because:\n // 1. do...while loop executes at least once\n // 2. We only reach here if result.isErr()\n return Err(lastError);\n };\n\n const response = fetchWithRetry();\n\n if (abortable && userController) {\n return {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n abort(reason?: any): void {\n if (reason instanceof Error) {\n userController.abort(reason);\n } else if (reason != null) {\n userController.abort(wrapAbortReason(reason));\n } else {\n userController.abort();\n }\n },\n\n get aborted(): boolean {\n return userController.signal.aborted;\n },\n\n get response(): FetchResponse<FetchResponseData> {\n return response;\n },\n };\n }\n\n return response;\n}\n\n/**\n * Delays execution for the specified number of milliseconds.\n */\nfunction delay(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\n/**\n * Wraps a non-Error abort reason into an Error with ABORT_ERROR name.\n */\nfunction wrapAbortReason(reason: unknown): Error {\n const error = new Error(typeof reason === 'string' ? reason : String(reason));\n error.name = ABORT_ERROR;\n error.cause = reason;\n return error;\n}\n\ninterface ParsedRetryOptions extends FetchRetryOptions {\n retries: number;\n delay: number | ((attempt: number) => number);\n}\n\n/**\n * Validates fetch options and parses retry configuration.\n */\nfunction validateOptions(init: FetchInit): ParsedRetryOptions {\n const {\n responseType,\n timeout,\n retry: retryOptions = 0,\n onProgress,\n onChunk,\n } = init;\n\n if (responseType != null) {\n const validTypes = ['text', 'arraybuffer', 'blob', 'json', 'bytes', 'stream'];\n invariant(validTypes.includes(responseType), () => `responseType must be one of ${ validTypes.join(', ') } but received ${ responseType }`);\n }\n\n if (timeout != null) {\n invariant(typeof timeout === 'number' && timeout > 0, () => `timeout must be a number greater than 0 but received ${ timeout }`);\n }\n\n if (onProgress != null) {\n invariant(typeof onProgress === 'function', () => `onProgress callback must be a function but received ${ typeof onProgress }`);\n }\n\n if (onChunk != null) {\n invariant(typeof onChunk === 'function', () => `onChunk callback must be a function but received ${ typeof onChunk }`);\n }\n\n // Parse retry options\n let retries = 0;\n let delay: number | ((attempt: number) => number) = 0;\n let when: ((error: Error, attempt: number) => boolean) | number[] | undefined;\n let onRetry: ((error: Error, attempt: number) => void) | undefined;\n\n if (typeof retryOptions === 'number') {\n retries = retryOptions;\n } else if (retryOptions && typeof retryOptions === 'object') {\n retries = retryOptions.retries ?? 0;\n delay = retryOptions.delay ?? 0;\n when = retryOptions.when;\n onRetry = retryOptions.onRetry;\n }\n\n invariant(Number.isInteger(retries) && retries >= 0, () => `Retry count must be a non-negative integer but received ${ retries }`);\n\n if (typeof delay === 'number') {\n invariant(delay >= 0, () => `Retry delay must be a non-negative number but received ${ delay }`);\n } else {\n invariant(typeof delay === 'function', () => `Retry delay must be a number or a function but received ${ typeof delay }`);\n }\n\n if (when != null) {\n invariant(Array.isArray(when) || typeof when === 'function', () => `Retry when condition must be an array of status codes or a function but received ${ typeof when }`);\n }\n\n if (onRetry != null) {\n invariant(typeof onRetry === 'function', () => `Retry onRetry callback must be a function but received ${ typeof onRetry }`);\n }\n\n return { retries, delay, when, onRetry };\n}\n\n/**\n * Validates and parses a URL string or URL object.\n * In browser environments, relative URLs are resolved against `location.href`.\n * In non-browser environments (Node/Deno/Bun), only absolute URLs are valid.\n *\n * @param url - The URL to validate, either a string or URL object.\n * @returns The parsed URL object.\n * @throws {TypeError} If the URL is invalid or cannot be parsed.\n */\nfunction validateUrl(url: string | URL): URL {\n if (url instanceof URL) {\n return url;\n }\n\n try {\n // In browser, use location.href as base for relative URLs\n // In Node/Deno/Bun, location is undefined, so relative URLs will fail\n const base = typeof location !== 'undefined' ? location.href : undefined;\n return new URL(url, base);\n } catch {\n throw new TypeError(`Invalid URL: ${ url }`);\n }\n}\n"],"names":["response","delay"],"mappings":";;;AAqBO,MAAM,WAAA,GAAc;AAuBpB,MAAM,aAAA,GAAgB;;ACyTtB,MAAM,mBAAmB,KAAA,CAAM;AAAA;AAAA;AAAA;AAAA,EAIzB,IAAA,GAAO,YAAA;AAAA;AAAA;AAAA;AAAA,EAKhB,MAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,WAAA,CAAY,SAAiB,MAAA,EAAgB;AACzC,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,EAClB;AACJ;;AClFO,SAAS,MAAA,CAAO,KAAmB,IAAA,EAAmF;AAEzH,EAAA,MAAM,SAAA,GAAY,YAAY,GAAG,CAAA;AAEjC,EAAA,MAAM,SAAA,GAAY,QAAQ,EAAC;AAE3B,EAAA,MAAM;AAAA,IACF,OAAA;AAAA,IACA,KAAA,EAAO,UAAA;AAAA,IACP,IAAA,EAAM,SAAA;AAAA,IACN;AAAA,GACJ,GAAI,gBAAgB,SAAS,CAAA;AAE7B,EAAA,MAAM;AAAA;AAAA,IAEF,SAAA,GAAY,KAAA;AAAA,IACZ,YAAA;AAAA,IACA,OAAA;AAAA,IACA,UAAA;AAAA,IACA,OAAA;AAAA,IACA,GAAG;AAAA,GACP,GAAI,SAAA;AAGJ,EAAA,MAAM,aAAa,IAAA,CAAK,MAAA;AAGxB,EAAA,IAAI,cAAA;AACJ,EAAA,IAAI,SAAA,EAAW;AACX,IAAA,cAAA,GAAiB,IAAI,eAAA,EAAgB;AAAA,EACzC;AAMA,EAAA,MAAM,WAAA,GAAc,CAAC,KAAA,EAAc,OAAA,KAA6B;AAE5D,IAAA,IAAI,KAAA,CAAM,SAAS,WAAA,EAAa;AAC5B,M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,IAAA,MAAM,IAAA,GAAO,OAAO,QAAA,KAAa,WAAA,GAAc,SAAS,IAAA,GAAO,MAAA;AAC/D,IAAA,OAAO,IAAI,GAAA,CAAI,GAAA,EAAK,IAAI,CAAA;AAAA,EAC5B,CAAA,CAAA,MAAQ;AACJ,IAAA,MAAM,IAAI,SAAA,CAAU,CAAA,aAAA,EAAiB,GAAI,CAAA,CAAE,CAAA;AAAA,EAC/C;AACJ;;;;"}
package/dist/types.d.ts CHANGED
@@ -126,6 +126,9 @@ export declare interface FetchInit extends RequestInit {
126
126
  * - `'blob'` - Returns `Blob`
127
127
  * - `'stream'` - Returns `ReadableStream<Uint8Array<ArrayBuffer>>`
128
128
  * - `undefined` - Returns raw `Response` object
129
+ *
130
+ * When using a dynamic string value (not a literal type), the return type
131
+ * will be `FetchResponseData` (union of all possible types).
129
132
  */
130
133
  responseType?: FetchResponseType;
131
134
  /**
@@ -238,6 +241,24 @@ export declare interface FetchProgress {
238
241
  */
239
242
  export declare type FetchResponse<T, E = any> = AsyncResult<T, E>;
240
243
 
244
+ /**
245
+ * Union type of all possible fetchT response data types.
246
+ *
247
+ * Used when `responseType` is a dynamic string value rather than a literal type,
248
+ * as the exact return type cannot be determined at compile time.
249
+ *
250
+ * @example
251
+ * ```typescript
252
+ * import { fetchT, type FetchResponseData } from '@happy-ts/fetch-t';
253
+ *
254
+ * // When responseType is dynamic, return type is FetchResponseData
255
+ * const responseType = getResponseType(); // returns string
256
+ * const result = await fetchT('https://api.example.com/data', { responseType });
257
+ * // result is Result<FetchResponseData, Error>
258
+ * ```
259
+ */
260
+ export declare type FetchResponseData = string | ArrayBuffer | Blob | Uint8Array<ArrayBuffer> | ReadableStream<Uint8Array<ArrayBuffer>> | Response | null;
261
+
241
262
  /**
242
263
  * Specifies the expected response type for automatic parsing.
243
264
  *
@@ -371,14 +392,29 @@ export declare function fetchT(url: string | URL, init: FetchInit & {
371
392
  responseType: 'bytes';
372
393
  }): FetchTask<Uint8Array<ArrayBuffer>>;
373
394
 
395
+ /**
396
+ * Fetches a resource from the network and returns an abortable `FetchTask` with a dynamic response type.
397
+ *
398
+ * Use this overload when `responseType` is a `FetchResponseType` union type.
399
+ *
400
+ * @param url - The resource to fetch. Can be a URL object or a string representing a URL.
401
+ * @param init - Additional options for the fetch operation, must include `abortable: true` and a `FetchResponseType`.
402
+ * @returns A `FetchTask` representing the abortable operation with a `FetchResponseData` response.
403
+ */
404
+ export declare function fetchT(url: string | URL, init: FetchInit & {
405
+ abortable: true;
406
+ responseType: FetchResponseType;
407
+ }): FetchTask<FetchResponseData>;
408
+
374
409
  /**
375
410
  * Fetches a resource from the network as a text string.
376
411
  *
377
412
  * @param url - The resource to fetch. Can be a URL object or a string representing a URL.
378
- * @param init - Additional options for the fetch operation, must include `responseType: 'text'`.
413
+ * @param init - Additional options for the fetch operation, must include `responseType: 'text'` and `abortable` must be `false` or omitted.
379
414
  * @returns A `FetchResponse` representing the operation with a `string` response.
380
415
  */
381
416
  export declare function fetchT(url: string | URL, init: FetchInit & {
417
+ abortable?: false;
382
418
  responseType: 'text';
383
419
  }): FetchResponse<string, Error>;
384
420
 
@@ -386,10 +422,11 @@ export declare function fetchT(url: string | URL, init: FetchInit & {
386
422
  * Fetches a resource from the network as an ArrayBuffer.
387
423
  *
388
424
  * @param url - The resource to fetch. Can be a URL object or a string representing a URL.
389
- * @param init - Additional options for the fetch operation, must include `responseType: 'arraybuffer'`.
425
+ * @param init - Additional options for the fetch operation, must include `responseType: 'arraybuffer'` and `abortable` must be `false` or omitted.
390
426
  * @returns A `FetchResponse` representing the operation with an `ArrayBuffer` response.
391
427
  */
392
428
  export declare function fetchT(url: string | URL, init: FetchInit & {
429
+ abortable?: false;
393
430
  responseType: 'arraybuffer';
394
431
  }): FetchResponse<ArrayBuffer, Error>;
395
432
 
@@ -397,10 +434,11 @@ export declare function fetchT(url: string | URL, init: FetchInit & {
397
434
  * Fetches a resource from the network as a Blob.
398
435
  *
399
436
  * @param url - The resource to fetch. Can be a URL object or a string representing a URL.
400
- * @param init - Additional options for the fetch operation, must include `responseType: 'blob'`.
437
+ * @param init - Additional options for the fetch operation, must include `responseType: 'blob'` and `abortable` must be `false` or omitted.
401
438
  * @returns A `FetchResponse` representing the operation with a `Blob` response.
402
439
  */
403
440
  export declare function fetchT(url: string | URL, init: FetchInit & {
441
+ abortable?: false;
404
442
  responseType: 'blob';
405
443
  }): FetchResponse<Blob, Error>;
406
444
 
@@ -409,10 +447,11 @@ export declare function fetchT(url: string | URL, init: FetchInit & {
409
447
  *
410
448
  * @typeParam T - The expected type of the parsed JSON data.
411
449
  * @param url - The resource to fetch. Can be a URL object or a string representing a URL.
412
- * @param init - Additional options for the fetch operation, must include `responseType: 'json'`.
450
+ * @param init - Additional options for the fetch operation, must include `responseType: 'json'` and `abortable` must be `false` or omitted.
413
451
  * @returns A `FetchResponse` representing the operation with a response parsed as type `T`.
414
452
  */
415
453
  export declare function fetchT<T>(url: string | URL, init: FetchInit & {
454
+ abortable?: false;
416
455
  responseType: 'json';
417
456
  }): FetchResponse<T | null, Error>;
418
457
 
@@ -420,10 +459,11 @@ export declare function fetchT<T>(url: string | URL, init: FetchInit & {
420
459
  * Fetches a resource from the network as a ReadableStream.
421
460
  *
422
461
  * @param url - The resource to fetch. Can be a URL object or a string representing a URL.
423
- * @param init - Additional options for the fetch operation, must include `responseType: 'stream'`.
462
+ * @param init - Additional options for the fetch operation, must include `responseType: 'stream'` and `abortable` must be `false` or omitted.
424
463
  * @returns A `FetchResponse` representing the operation with a `ReadableStream<Uint8Array<ArrayBuffer>>` response.
425
464
  */
426
465
  export declare function fetchT(url: string | URL, init: FetchInit & {
466
+ abortable?: false;
427
467
  responseType: 'stream';
428
468
  }): FetchResponse<ReadableStream<Uint8Array<ArrayBuffer>> | null, Error>;
429
469
 
@@ -431,13 +471,28 @@ export declare function fetchT(url: string | URL, init: FetchInit & {
431
471
  * Fetches a resource from the network as a Uint8Array<ArrayBuffer>.
432
472
  *
433
473
  * @param url - The resource to fetch. Can be a URL object or a string representing a URL.
434
- * @param init - Additional options for the fetch operation, must include `responseType: 'bytes'`.
474
+ * @param init - Additional options for the fetch operation, must include `responseType: 'bytes'` and `abortable` must be `false` or omitted.
435
475
  * @returns A `FetchResponse` representing the operation with a `Uint8Array<ArrayBuffer>` response.
436
476
  */
437
477
  export declare function fetchT(url: string | URL, init: FetchInit & {
478
+ abortable?: false;
438
479
  responseType: 'bytes';
439
480
  }): FetchResponse<Uint8Array<ArrayBuffer>, Error>;
440
481
 
482
+ /**
483
+ * Fetches a resource from the network with a dynamic response type (non-abortable).
484
+ *
485
+ * Use this overload when `responseType` is a `FetchResponseType` union type.
486
+ *
487
+ * @param url - The resource to fetch. Can be a URL object or a string representing a URL.
488
+ * @param init - Additional options for the fetch operation with a `FetchResponseType`, and `abortable` must be `false` or omitted.
489
+ * @returns A `FetchResponse` representing the operation with a `FetchResponseData` response.
490
+ */
491
+ export declare function fetchT(url: string | URL, init: FetchInit & {
492
+ abortable?: false;
493
+ responseType: FetchResponseType;
494
+ }): FetchResponse<FetchResponseData, Error>;
495
+
441
496
  /**
442
497
  * Fetches a resource from the network and returns an abortable `FetchTask` with a generic `Response`.
443
498
  *
@@ -453,10 +508,12 @@ export declare function fetchT(url: string | URL, init: FetchInit & {
453
508
  * Fetches a resource from the network and returns a `FetchResponse` with a generic `Response` object.
454
509
  *
455
510
  * @param url - The resource to fetch. Can be a URL object or a string representing a URL.
456
- * @param init - Optional additional options for the fetch operation.
511
+ * @param init - Optional additional options for the fetch operation, and `abortable` must be `false` or omitted.
457
512
  * @returns A `FetchResponse` representing the operation with a `Response` object.
458
513
  */
459
- export declare function fetchT(url: string | URL, init?: FetchInit): FetchResponse<Response>;
514
+ export declare function fetchT(url: string | URL, init?: FetchInit & {
515
+ abortable?: false;
516
+ }): FetchResponse<Response>;
460
517
 
461
518
  /**
462
519
  * Represents an abortable fetch operation with control methods.
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "description": "Type-safe Fetch API wrapper with abortable requests, timeout support, progress tracking, automatic retry, and Rust-like Result error handling.",
4
4
  "author": "jiang115jie@gmail.com",
5
5
  "license": "MIT",
6
- "version": "1.6.0",
6
+ "version": "1.8.0",
7
7
  "type": "module",
8
8
  "main": "dist/main.cjs",
9
9
  "module": "dist/main.mjs",