import type { Subscription } from "@d1g1tal/subscribr"; import { MediaType } from "@d1g1tal/media-type"; /** * A class that holds a status code and a status text, typically from a {@link Response} * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Response/status|Response.status * @author D1g1talEntr0py */ declare class ResponseStatus { private readonly _code; private readonly _text; /** * * @param code The status code from the {@link Response} * @param text The status text from the {@link Response} */ constructor(code: number, text: string); /** * Returns the status code from the {@link Response} * * @returns The status code. */ get code(): number; /** * Returns the status text from the {@link Response}. * * @returns The status text. */ get text(): string; /** * A String value that is used in the creation of the default string * description of an object. Called by the built-in method {@link Object.prototype.toString}. * * @returns The default string description of this object. */ get [Symbol.toStringTag](): string; /** * tostring method for the class. * * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString|Object.prototype.toString} * @returns The status code and status text. */ toString(): string; } type Function

= (...args: P[]) => R; type JsonPrimitive = string | number | boolean | null; type JsonArray = T extends any ? Array> : never; type JsonObject = T extends any ? { [K in keyof T as JsonValue extends never ? never : K]: JsonValue; } : Record; type JsonValue = T extends JsonPrimitive ? T : T extends { toJSON: () => infer R; } ? R : T extends Function | undefined ? never : T extends Array ? JsonArray : T extends Record ? JsonObject : Json; type Json = JsonPrimitive | JsonObject | JsonArray; type JsonString = string & { source: T; }; /** The expected response body types returned from a fetch handler. */ type ResponseBody = Json | Document | DocumentFragment | HTMLImageElement | Blob | ArrayBuffer | FormData | string | ReadableStream | void | null; /** A parsed Server-Sent Event per the EventStream specification. */ type ServerSentEvent = { /** The event type (defaults to 'message'). */ event: string; /** The event data payload. */ data: string; /** The last event ID string, if provided by the server. */ id: string; /** Reconnection time in milliseconds, if provided by the server. */ retry: number | undefined; }; /** Progress information for download/upload tracking. */ type DownloadProgress = { /** Number of bytes transferred so far. */ loaded: number; /** Total number of bytes, or null if unknown (no Content-Length). */ total: number | null; /** Percentage complete (0–100), or null if total is unknown. */ percentage: number | null; }; /** Result tuple for error-as-value handling. Success: [true, data]. Error: [false, E]. */ type Result = [true, T] | [false, E]; /** Retry event information emitted during retry attempts. */ type RetryInfo = { /** Current retry attempt number (1-based). */ attempt: number; /** HTTP status code that triggered the retry, if available. */ status?: number; /** Error message that triggered the retry, if available. */ error?: string; /** The HTTP method of the request. */ method: string; /** The request path. */ path: string | undefined; /** Timing information at the point of retry. */ timing: RequestTiming; }; /** Timing information for a request lifecycle. */ type RequestTiming = { /** Timestamp when the request started (ms since epoch). */ start: number; /** Timestamp when the response was received (ms since epoch). */ end: number; /** Total duration in milliseconds. */ duration: number; }; /** Options for constructing an {@link HttpError}. */ type HttpErrorOptions = { message?: string; cause?: Error; entity?: ResponseBody; /** The request URL. */ url?: URL; /** The HTTP method used. */ method?: string; /** Request timing information. */ timing?: RequestTiming; }; /** * An error that represents an HTTP error response. * @author D1g1talEntr0py */ declare class HttpError extends Error { private readonly _entity; private readonly responseStatus; private readonly _url; private readonly _method; private readonly _timing; /** * Creates an instance of HttpError. * @param status The status code and status text of the {@link Response}. * @param httpErrorOptions The http error options. */ constructor(status: ResponseStatus, { message, cause, entity, url, method, timing }?: HttpErrorOptions); /** * It returns the value of the private variable #entity. * @returns The entity property of the class. */ get entity(): ResponseBody; /** * It returns the status code of the {@link Response}. * @returns The status code of the {@link Response}. */ get statusCode(): number; /** * It returns the status text of the {@link Response}. * @returns The status code and status text of the {@link Response}. */ get statusText(): string; /** * The request URL that caused the error. * @returns The URL or undefined. */ get url(): URL | undefined; /** * The HTTP method that was used for the failed request. * @returns The method string or undefined. */ get method(): string | undefined; /** * Timing information for the failed request. * @returns The timing object or undefined. */ get timing(): RequestTiming | undefined; /** * A String value representing the name of the error. * @returns The name of the error. */ get name(): string; /** * A String value that is used in the creation of the default string * description of an object. Called by the built-in method {@link Object.prototype.toString}. * @returns The default string description of this object. */ get [Symbol.toStringTag](): string; } /** * Defining a constant object with all the HTTP request headers. */ declare const RequestHeader: { /** * Content-Types that are acceptable for the response. See Content negotiation. Permanent. * * @example * Accept: text/plain */ readonly ACCEPT: "accept"; /** * Character sets that are acceptable. Permanent. * * @example * Accept-Charset: utf-8 */ readonly ACCEPT_CHARSET: "accept-charset"; /** * List of acceptable encodings. See HTTP compression. Permanent. * * @example * Accept-Encoding: gzip, deflate */ readonly ACCEPT_ENCODING: "accept-encoding"; /** * List of acceptable human languages for response. See Content negotiation. Permanent. * * @example * Accept-Language: en-US */ readonly ACCEPT_LANGUAGE: "accept-language"; /** * Authentication credentials for HTTP authentication. Permanent. * * @example * Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== */ readonly AUTHORIZATION: "authorization"; /** * Used to specify directives that must be obeyed by all caching mechanisms along the request-response chain. * Permanent. * * @example * Cache-Control: no-cache */ readonly CACHE_CONTROL: "cache-control"; /** * Control options for the current connection and list of hop-by-hop request fields. Permanent. * * @example * Connection: keep-alive * Connection: Upgrade */ readonly CONNECTION: "connection"; /** * An HTTP cookie previously sent by the server with Set-Cookie (below). Permanent: standard. * * @example * Cookie: $Version=1, Skin=new, */ readonly COOKIE: "cookie"; /** * The length of the request body in octets (8-bit bytes). Permanent. * * @example * Content-Length: 348 */ readonly CONTENT_LENGTH: "content-length"; /** * A Base64-encoded binary MD5 sum of the content of the request body. Obsolete. * * @example * Content-MD5: Q2hlY2sgSW50ZWdyaXR5IQ== */ readonly CONTENT_MD5: "content-md5"; /** * The MIME type of the body of the request (used with POST and PUT requests). Permanent. * Content-Type: application/x-www-form-urlencoded */ readonly CONTENT_TYPE: "content-type"; /** * The date and time that the message was sent (in "HTTP-date" format as defined by RFC 7231 Date/Time Formats). * Permanent. * * @example * Date: Tue, 15 Nov 1994 08:12:31 GMT */ readonly DATE: "date"; /** * The domain name of the server (for virtual hosting), and the TCP port number on which the server is listening. The * port number may be omitted if the port is the standard port for the service requested. Permanent. Mandatory since * HTTP/1.1. * * @example * Host: en.wikipedia.org:80 * Host: en.wikipedia.org */ readonly HOST: "host"; /** * Only perform the action if the client supplied entity matches the same entity on the server. This is mainly for * methods like PUT to only update a resource if it has not been modified since the user last updated it. Permanent. * * @example * If-Match: "737060cd8c284d8af7ad3082f209582d" */ readonly IF_MATCH: "if-match"; /** * Allows a 304 Not Modified to be returned if content is unchanged. Permanent. * * @example * If-Modified-Since: Sat, 29 Oct 1994 19:43:31 GMT */ readonly IF_MODIFIED_SINCE: "if-modified-since"; /** * Allows a 304 Not Modified to be returned if content is unchanged, see HTTP ETag. Permanent. * * @example * If-None-Match: "737060cd8c284d8af7ad3082f209582d" */ readonly IF_NONE_MATCH: "if-none-match"; /** * If the entity is unchanged, send me the part(s) that I am missing, otherwise, send me the entire new entity. * Permanent. * * @example * If-Range: "737060cd8c284d8af7ad3082f209582d" */ readonly IF_RANGE: "if-range"; /** * Only send the response if the entity has not been modified since a specific time. Permanent. * * @example * If-Unmodified-Since: Sat, 29 Oct 1994 19:43:31 GMT */ readonly IF_UNMODIFIED_SINCE: "if-unmodified-since"; /** * Limit the number of times the message can be forwarded through proxies or gateways. Permanent. * * @example * Max-Forwards: 10 */ readonly MAX_FORWARDS: "max-forwards"; /** * Initiates a request for cross-origin resource sharing (asks server for an 'Access-Control-Allow-Origin' response * field). Permanent: standard. * * @example * Origin: http://www.example-social-network.com */ readonly ORIGIN: "origin"; /** * Implementation-specific fields that may have various effects anywhere along the request-response chain. Permanent. * * @example * Pragma: no-cache */ readonly PRAGMA: "pragma"; /** * Authorization credentials for connecting to a proxy. Permanent. * * @example * Proxy-Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== */ readonly PROXY_AUTHORIZATION: "proxy-authorization"; /** * Request only part of an entity. Bytes are numbered from 0. See Byte serving. Permanent. * * @example * Range: bytes=500-999 */ readonly RANGE: "range"; /** * This is the address of the previous web page from which a link to the currently requested page was followed. (The * word "referrer" has been misspelled in the RFC as well as in most implementations to the point that it has become * standard usage and is considered correct terminology). Permanent. * * @example * Referer: http://en.wikipedia.org/wiki/Main_Page */ readonly REFERER: "referer"; /** * The transfer encodings the user agent is willing to accept: the same values as for the response header field * Transfer-Encoding can be used, plus the "trailers" value (related to the "chunked" transfer method) to notify the * server it expects to receive additional fields in the trailer after the last, zero-sized, chunk. Permanent. * * @example * TE: trailers, deflate */ readonly TE: "te"; /** * The user agent string of the user agent. Permanent. * * @example * User-Agent: Mozilla/5.0 (X11, Linux x86_64, rv:12.0) Gecko/20100101 Firefox/21.0 */ readonly USER_AGENT: "user-agent"; /** * Ask the server to upgrade to another protocol. Permanent. * * @example * Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11 */ readonly UPGRADE: "upgrade"; /** * A general warning about possible problems with the entity body. Permanent. * * @example * Warning: 199 Miscellaneous warning */ readonly WARNING: "warning"; /** * mainly used to identify Ajax requests. Most JavaScript frameworks send this field with value of XMLHttpRequest. * * @example * X-Requested-With: XMLHttpRequest */ readonly X_REQUESTED_WITH: "x-requested-with"; /** * A de facto standard for identifying the originating IP address of a client connecting to a web server through an * HTTP proxy or load balancer. * * @example * X-Forwarded-For: client1, proxy1, proxy2 * X-Forwarded-For: 129.78.138.66, 129.78.64.103 */ readonly X_FORWARDED_FOR: "x-forwarded-for"; /** * A de facto standard for identifying the original host requested by the client in the Host HTTP request header, since * the host name and/or port of the reverse proxy (load balancer) may differ from the origin server handling the * request. * * @example * X-Forwarded-Host: en.wikipedia.org:80 * X-Forwarded-Host: en.wikipedia.org */ readonly X_FORWARDED_HOST: "x-forwarded-host"; /** * A de facto standard for identifying the originating protocol of an HTTP request, since a reverse proxy (load * balancer) may communicate with a web server using HTTP even if the request to the reverse proxy is HTTPS. An * alternative form of the header (X-ProxyUser-Ip) is used by Google clients talking to Google servers. * * @example * X-Forwarded-Proto: https */ readonly X_FORWARDED_PROTO: "x-forwarded-proto"; }; /** * A collection of some of the available HTTP media types. * @see {@link https://www.iana.org/assignments/media-types/media-types.xhtml | IANA Media Types} */ declare const ContentType: { /** Advanced Audio Coding (AAC) */ readonly AAC: "audio/aac"; /** AbiWord */ readonly ABW: "application/x-abiword"; /** Archive document (multiple files embedded) */ readonly ARC: "application/x-freearc"; /** AVIF image */ readonly AVIF: "image/avif"; /** Audio Video Interleave (AVI) */ readonly AVI: "video/x-msvideo"; /** Amazon Kindle eBook format */ readonly AZW: "application/vnd.amazon.ebook"; /** Binary Data */ readonly BIN: "application/octet-stream"; /** Windows OS/2 Bitmap Graphics */ readonly BMP: "image/bmp"; /** Bzip Archive */ readonly BZIP: "application/x-bzip"; /** Bzip2 Archive */ readonly BZIP2: "application/x-bzip2"; /** CD audio */ readonly CDA: "application/x-cdf"; /** C Shell Script */ readonly CSH: "application/x-csh"; /** Cascading Style Sheets (CSS) */ readonly CSS: "text/css"; /** Comma-Separated Values */ readonly CSV: "text/csv"; /** Microsoft Office Word Document */ readonly DOC: "application/msword"; /** Microsoft Office Word Document (OpenXML) */ readonly DOCX: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; /** Microsoft Embedded OpenType */ readonly EOT: "application/vnd.ms-fontobject"; /** Electronic Publication (EPUB) */ readonly EPUB: "application/epub+zip"; /** GZip Compressed Archive */ readonly GZIP: "application/gzip"; /** Graphics Interchange Format */ readonly GIF: "image/gif"; /** HyperText Markup Language (HTML) */ readonly HTML: "text/html"; /** Icon Format */ readonly ICO: "image/vnd.microsoft.icon"; /** iCalendar Format */ readonly ICS: "text/calendar"; /** Java Archive (JAR) */ readonly JAR: "application/java-archive"; /** JPEG Image */ readonly JPEG: "image/jpeg"; /** JavaScript */ readonly JAVA_SCRIPT: "text/javascript"; /** JavaScript Object Notation Format (JSON) */ readonly JSON: "application/json"; /** JavaScript Object Notation LD Format */ readonly JSON_LD: "application/ld+json"; /** JavaScript Object Notation (JSON) Merge Patch */ readonly JSON_MERGE_PATCH: "application/merge-patch+json"; /** Musical Instrument Digital Interface (MIDI) */ readonly MID: "audio/midi"; /** Musical Instrument Digital Interface (MIDI) */ readonly X_MID: "audio/x-midi"; /** MP3 Audio */ readonly MP3: "audio/mpeg"; /** MPEG-4 Audio */ readonly MP4A: "audio/mp4"; /** MPEG-4 Video */ readonly MP4: "video/mp4"; /** MPEG Video */ readonly MPEG: "video/mpeg"; /** Apple Installer Package */ readonly MPKG: "application/vnd.apple.installer+xml"; /** OpenDocument Presentation Document */ readonly ODP: "application/vnd.oasis.opendocument.presentation"; /** OpenDocument Spreadsheet Document */ readonly ODS: "application/vnd.oasis.opendocument.spreadsheet"; /** OpenDocument Text Document */ readonly ODT: "application/vnd.oasis.opendocument.text"; /** Ogg Audio */ readonly OGA: "audio/ogg"; /** Ogg Video */ readonly OGV: "video/ogg"; /** Ogg */ readonly OGX: "application/ogg"; /** Opus audio */ readonly OPUS: "audio/opus"; /** OpenType Font File */ readonly OTF: "font/otf"; /** Portable Network Graphics (PNG) */ readonly PNG: "image/png"; /** Adobe Portable Document Format */ readonly PDF: "application/pdf"; /** Hypertext Preprocessor (Personal Home Page) */ readonly PHP: "application/x-httpd-php"; /** Microsoft PowerPoint */ readonly PPT: "application/vnd.ms-powerpoint"; /** Microsoft Office Presentation (OpenXML) */ readonly PPTX: "application/vnd.openxmlformats-officedocument.presentationml.presentation"; /** RAR Archive */ readonly RAR: "application/vnd.rar"; /** Rich Text Format */ readonly RTF: "application/rtf"; /** Bourne Shell Script */ readonly SH: "application/x-sh"; /** Scalable Vector Graphics (SVG) */ readonly SVG: "image/svg+xml"; /** Tape Archive (TAR) */ readonly TAR: "application/x-tar"; /** Tagged Image File Format (TIFF) */ readonly TIFF: "image/tiff"; /** MPEG transport stream */ readonly TRANSPORT_STREAM: "video/mp2t"; /** TrueType Font */ readonly TTF: "font/ttf"; /** Text, (generally ASCII or ISO 8859-n) */ readonly TEXT: "text/plain"; /** Microsoft Visio */ readonly VSD: "application/vnd.visio"; /** Waveform Audio Format (WAV) */ readonly WAV: "audio/wav"; /** Open Web Media Project - Audio */ readonly WEBA: "audio/webm"; /** Open Web Media Project - Video */ readonly WEBM: "video/webm"; /** WebP Image */ readonly WEBP: "image/webp"; /** Web Open Font Format */ readonly WOFF: "font/woff"; /** Web Open Font Format */ readonly WOFF2: "font/woff2"; /** Form - Encoded */ readonly FORM: "application/x-www-form-urlencoded"; /** Multipart FormData */ readonly MULTIPART_FORM_DATA: "multipart/form-data"; /** XHTML - The Extensible HyperText Markup Language */ readonly XHTML: "application/xhtml+xml"; /** Microsoft Excel Document */ readonly XLS: "application/vnd.ms-excel"; /** Microsoft Office Spreadsheet Document (OpenXML) */ readonly XLSX: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; /** Extensible Markup Language (XML) */ readonly XML: "application/xml"; /** XML User Interface Language (XUL) */ readonly XUL: "application/vnd.mozilla.xul+xml"; /** Zip Archive */ readonly ZIP: "application/zip"; /** 3GPP audio/video container */ readonly '3GP': "video/3gpp"; /** 3GPP2 audio/video container */ readonly '3G2': "video/3gpp2"; /** 7-Zip Archive */ readonly '7Z': "application/x-7z-compressed"; }; type Prettify = T extends infer U ? { [K in keyof U]: U[K]; } : never; type LiteralUnion = T | (string & {}); interface TypedResponse extends Response { json: () => Promise; } type RequestBody = BodyInit | JsonObject; type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array; type RequestMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS' | 'CONNECT' | 'TRACE'; type RequestBodyMethod = Extract; type RequestNoBodyMethod = Exclude; type RequestHeaders = Prettify]?: string; } & HeadersInit>; type SearchParameters = URLSearchParams | string | string[][] | Record; type AuthorizationScheme = 'Basic' | 'Bearer' | 'Digest' | 'HOBA' | 'Mutual' | 'Negotiate' | 'OAuth' | 'SCRAM-SHA-1' | 'SCRAM-SHA-256' | 'vapid'; type ResponseHandler = (response: Response) => Promise; type RequestLifecycleEvent = 'configured' | 'success' | 'error' | 'aborted' | 'timeout' | 'retry' | 'complete' | 'all-complete'; type RequestEventHandler = (event: Event, data: unknown) => void; type Entry = [K, V]; type Entries = Entry[]; type ReadOnlyEntries = readonly Entry[]; type AbortSignalEvent = Event & { target: AbortSignal; }; type AbortEvent = CustomEvent<{ cause: 'AbortError'; }>; type TimeoutEvent = CustomEvent<{ cause: 'TimeoutError'; }>; type AbortConfiguration = { signal?: AbortSignal | null; timeout?: number; }; type MediaTypeValues = LiteralUnion; type TypedHeaders = { [RequestHeader.AUTHORIZATION]?: `${AuthorizationScheme} ${string}` | AuthorizationScheme; [RequestHeader.ACCEPT]?: MediaTypeValues; [RequestHeader.CONTENT_TYPE]?: MediaTypeValues; }; type EventRegistration = Subscription; type MethodBody = { method?: RequestBodyMethod; body?: RequestBody; } | { method?: RequestNoBodyMethod; body?: never; }; type RequestOptions = Prettify<{ /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ headers?: RequestHeaders; searchParams?: SearchParameters; timeout?: number; global?: boolean; /** Lifecycle hooks for this request. Instance and global hooks run first, then per-request hooks. */ hooks?: HookOptions; /** Retry configuration. A number sets the retry limit; an object provides fine-grained control. */ retry?: number | RetryOptions; /** When true, identical in-flight GET/HEAD requests share a single fetch. Defaults to false. */ dedupe?: boolean; /** XSRF/CSRF protection. When set (or true), reads a cookie and sets a request header. */ xsrf?: boolean | XsrfOptions; /** Callback invoked with download progress information. Only works when the response has a body stream. */ onDownloadProgress?: (progress: DownloadProgress) => void; /** Callback invoked with upload progress as the request body is sent. Requires ReadableStream request body support. */ onUploadProgress?: (progress: DownloadProgress) => void; /** When false, methods return Result tuples instead of throwing. Defaults to true (throw on error). */ unwrap?: boolean; } & Omit & MethodBody>; /** Configuration for retry behavior on failed requests. */ type RetryOptions = { /** Maximum number of retry attempts. Defaults to 0 (no retries). */ limit?: number; /** HTTP status codes that trigger a retry. Defaults to [408, 413, 429, 500, 502, 503, 504]. */ statusCodes?: number[]; /** HTTP methods allowed to retry. Defaults to ['GET', 'PUT', 'HEAD', 'DELETE', 'OPTIONS']. */ methods?: RequestMethod[]; /** Delay in ms before the first retry, or a function receiving the attempt number (1-based) returning ms. Defaults to 300. */ delay?: number | ((attempt: number) => number); /** Multiplier applied to delay after each attempt. Defaults to 2. */ backoffFactor?: number; }; /** Configuration for XSRF/CSRF token handling. */ type XsrfOptions = { /** The name of the cookie to read the token from. Defaults to 'XSRF-TOKEN'. */ cookieName?: string; /** The request header name to set the token on. Defaults to 'X-XSRF-TOKEN'. */ headerName?: string; }; /** Hook called before each request. Can modify the request options. */ type BeforeRequestHook = (options: RequestOptions, url: URL) => RequestOptions | void | Promise; /** Hook called after each successful response. Can modify or replace the response. */ type AfterResponseHook = (response: Response, options: RequestOptions) => Response | void | Promise; /** Hook called before an error is thrown. Can transform the error. */ type BeforeErrorHook = (error: HttpError) => HttpError | void | Promise; /** Configuration for request lifecycle hooks. */ type HookOptions = { beforeRequest?: BeforeRequestHook[]; afterResponse?: AfterResponseHook[]; beforeError?: BeforeErrorHook[]; }; /** Fully resolved retry configuration with all defaults applied. */ type NormalizedRetryOptions = Required; /** Maps request event names to their typed data payloads. */ type RequestEventDataMap = { configured: RequestOptions; success: ResponseBody; error: HttpError; aborted: undefined; timeout: undefined; retry: RetryInfo; complete: { timing: RequestTiming; }; 'all-complete': undefined; }; /** A typed event handler where the data parameter matches the event name. */ type TypedRequestEventHandler = (event: Event, data: RequestEventDataMap[E]) => void; /** Options for the internal publish helper. */ type PublishOptions = { name: string; event?: Event; data?: unknown; global?: boolean; }; declare const endsWithSlashRegEx: RegExp; /** Default XSRF cookie name */ declare const XSRF_COOKIE_NAME = "XSRF-TOKEN"; /** Default XSRF header name */ declare const XSRF_HEADER_NAME = "X-XSRF-TOKEN"; type MediaTypeKey = 'PNG' | 'TEXT' | 'JSON' | 'HTML' | 'JAVA_SCRIPT' | 'CSS' | 'XML' | 'BIN' | 'EVENT_STREAM' | 'NDJSON'; declare const mediaTypes: { [key in MediaTypeKey]: MediaType; }; declare const defaultMediaType: string; declare const defaultOrigin: string; /** Constant object for caching policies */ declare const RequestCachingPolicy: { readonly DEFAULT: "default"; readonly FORCE_CACHE: "force-cache"; readonly NO_CACHE: "no-cache"; readonly NO_STORE: "no-store"; readonly ONLY_IF_CACHED: "only-if-cached"; readonly RELOAD: "reload"; }; /** Constant object for signal events */ declare const SignalEvents: { readonly ABORT: "abort"; readonly TIMEOUT: "timeout"; }; /** Constant object for signal errors */ declare const SignalErrors: { readonly ABORT: "AbortError"; readonly TIMEOUT: "TimeoutError"; }; /** Options for adding event listeners */ declare const eventListenerOptions: AddEventListenerOptions; /** * Creates a new custom abort event. * @returns A new AbortEvent instance. */ declare const abortEvent: () => AbortEvent; /** * Creates a new custom timeout event. * @returns A new TimeoutEvent instance. */ declare const timeoutEvent: () => TimeoutEvent; /** Array of request body methods */ declare const requestBodyMethods: ReadonlyArray; /** Response status for internal server error */ declare const internalServerError: ResponseStatus; /** Response status for aborted request */ declare const aborted: ResponseStatus; /** Response status for timed out request */ declare const timedOut: ResponseStatus; /** Default HTTP status codes that trigger a retry */ declare const retryStatusCodes: ReadonlyArray; /** Default HTTP methods allowed to retry (idempotent methods only) */ declare const retryMethods: ReadonlyArray; /** Default delay in ms before the first retry */ declare const retryDelay: number; /** Default backoff factor applied after each retry attempt */ declare const retryBackoffFactor: number; /** Constant object for request events */ declare const RequestEvent: { readonly CONFIGURED: "configured"; readonly SUCCESS: "success"; readonly ERROR: "error"; readonly ABORTED: "aborted"; readonly TIMEOUT: "timeout"; readonly RETRY: "retry"; readonly COMPLETE: "complete"; readonly ALL_COMPLETE: "all-complete"; }; type RequestEvent = (typeof RequestEvent)[keyof typeof RequestEvent]; /** * A wrapper around the fetch API that makes it easier to make HTTP requests. * @author D1g1talEntr0py */ declare class Transportr { private readonly _baseUrl; private readonly _options; private readonly subscribr; private readonly hooks; private static globalSubscribr; private static globalHooks; private static signalControllers; /** Map of in-flight deduplicated requests keyed by URL + method */ private static inflightRequests; /** Cache for parsed MediaType instances to avoid re-parsing the same content-type strings */ private static mediaTypeCache; private static contentTypeHandlers; /** * Create a new Transportr instance with the provided location or origin and context path. * * @param url The URL for {@link fetch} requests. * @param options The default {@link RequestOptions} for this instance. */ constructor(url?: URL | string | RequestOptions, options?: RequestOptions); /** Credentials Policy */ static readonly CredentialsPolicy: { readonly INCLUDE: "include"; readonly OMIT: "omit"; readonly SAME_ORIGIN: "same-origin"; }; /** Request Mode */ static readonly RequestMode: { readonly CORS: "cors"; readonly NAVIGATE: "navigate"; readonly NO_CORS: "no-cors"; readonly SAME_ORIGIN: "same-origin"; }; /** Request Priority */ static readonly RequestPriority: { readonly HIGH: "high"; readonly LOW: "low"; readonly AUTO: "auto"; }; /** Redirect Policy */ static readonly RedirectPolicy: { readonly ERROR: "error"; readonly FOLLOW: "follow"; readonly MANUAL: "manual"; }; /** Referrer Policy */ static readonly ReferrerPolicy: { readonly NO_REFERRER: "no-referrer"; readonly NO_REFERRER_WHEN_DOWNGRADE: "no-referrer-when-downgrade"; readonly ORIGIN: "origin"; readonly ORIGIN_WHEN_CROSS_ORIGIN: "origin-when-cross-origin"; readonly SAME_ORIGIN: "same-origin"; readonly STRICT_ORIGIN: "strict-origin"; readonly STRICT_ORIGIN_WHEN_CROSS_ORIGIN: "strict-origin-when-cross-origin"; readonly UNSAFE_URL: "unsafe-url"; }; /** Request Event */ static readonly RequestEvent: typeof RequestEvent; /** Default Request Options */ private static readonly defaultRequestOptions; /** * Returns a {@link EventRegistration} used for subscribing to global events with typed data. * * @param event The event to subscribe to. * @param handler The event handler with typed data parameter. * @param context The context to bind the handler to. * @returns A new {@link EventRegistration} instance. */ static register(event: E, handler: TypedRequestEventHandler, context?: unknown): EventRegistration; /** * Removes a {@link EventRegistration} from the global event handler. * * @param eventRegistration The {@link EventRegistration} to remove. * @returns True if the {@link EventRegistration} was removed, false otherwise. */ static unregister(eventRegistration: EventRegistration): boolean; /** * Aborts all active requests. * This is useful for when the user navigates away from the current page. * This will also clear the {@link Transportr#signalControllers} set. */ static abortAll(): void; /** * Executes multiple requests concurrently and resolves when all complete. * @param requests An array of promises from Transportr request methods. * @returns A promise resolving to an array of all results. */ static all[]>(requests: T): Promise<{ -readonly [K in keyof T]: Awaited; }>; /** * Races multiple requests concurrently. The first to settle wins; all others are aborted. * Each factory receives an AbortSignal that the caller should pass to the request options. * @template T The expected result type. * @param requests An array of functions that accept an AbortSignal and return a promise. * @returns A promise resolving to the first settled result. * @example * ```typescript * const result = await Transportr.race([ * (signal) => api.getJson('/primary', { signal }), * (signal) => api.getJson('/fallback', { signal }) * ]); * ``` */ static race(requests: ReadonlyArray<(signal: AbortSignal) => Promise>): Promise; /** * Registers a custom content-type response handler. * The handler will be matched against response content-type headers using MediaType matching. * New handlers are prepended so they take priority over built-in handlers. * * @param contentType The content-type string to match (e.g. 'application/pdf', 'text', 'csv'). * @param handler The response handler function. */ static registerContentTypeHandler(contentType: string, handler: ResponseHandler): void; /** * Removes a previously registered content-type response handler. * * @param contentType The content-type string to remove. * @returns True if the handler was found and removed, false otherwise. */ static unregisterContentTypeHandler(contentType: string): boolean; /** * Registers global lifecycle hooks that run on all requests from all instances. * Global hooks execute before instance and per-request hooks. * * @param hooks The hooks to register globally. */ static addHooks(hooks: HookOptions): void; /** * Removes all global lifecycle hooks. */ static clearHooks(): void; /** * Tears down all global state: aborts in-flight requests, clears global event subscriptions, * hooks, in-flight deduplication map, and media type cache (retaining built-in entries). */ static unregisterAll(): void; /** * It returns the base {@link URL} for the API. * * @returns The baseUrl property. */ get baseUrl(): URL; /** * Registers an event handler with a {@link Transportr} instance with typed data. * * @param event The name of the event to listen for. * @param handler The function to call when the event is triggered. * @param context The context to bind to the handler. * @returns An object that can be used to remove the event handler. */ register(event: E, handler: TypedRequestEventHandler, context?: unknown): EventRegistration; /** * Unregisters an event handler from a {@link Transportr} instance. * * @param eventRegistration The event registration to remove. * @returns True if the {@link EventRegistration} was removed, false otherwise. */ unregister(eventRegistration: EventRegistration): boolean; /** * Registers instance-level lifecycle hooks that run on all requests from this instance. * Instance hooks execute after global hooks but before per-request hooks. * * @param hooks The hooks to register on this instance. * @returns This instance for method chaining. */ addHooks(hooks: HookOptions): this; /** * Removes all instance-level lifecycle hooks. * @returns This instance for method chaining. */ clearHooks(): this; /** * Updates the instance's default options after construction. * Mirrors what the constructor accepts: headers and searchParams are merged onto * the existing defaults; all other options overwrite the current value; hooks * are appended via {@link addHooks}. * * @param options The options to apply. Accepts the same shape as the constructor. * @returns This instance for method chaining. */ configure({ headers, searchParams, hooks, ...options }: RequestOptions): this; /** * Tears down this instance: clears all instance subscriptions and hooks. * The instance should not be used after calling this method. */ destroy(): void; /** Returns a Result tuple instead of throwing. */ get(path: string | undefined, options: RequestOptions & { unwrap: false; }): Promise>; /** Returns a Result tuple instead of throwing. */ get(path: RequestOptions & { unwrap: false; }): Promise>; /** Returns a Result tuple instead of throwing. */ post(path: string | undefined, options: RequestOptions & { unwrap: false; }): Promise>; /** Returns a Result tuple instead of throwing. */ post(path: RequestOptions & { unwrap: false; }): Promise>; /** Returns a Result tuple instead of throwing. */ put(path: string | undefined, options: RequestOptions & { unwrap: false; }): Promise>; /** Returns a Result tuple instead of throwing. */ put(path: RequestOptions & { unwrap: false; }): Promise>; /** Returns a Result tuple instead of throwing. */ patch(path: string | undefined, options: RequestOptions & { unwrap: false; }): Promise>; /** Returns a Result tuple instead of throwing. */ patch(path: RequestOptions & { unwrap: false; }): Promise>; /** Returns a Result tuple instead of throwing. */ delete(path: string | undefined, options: RequestOptions & { unwrap: false; }): Promise>; /** Returns a Result tuple instead of throwing. */ delete(path: RequestOptions & { unwrap: false; }): Promise>; /** Returns a Result tuple instead of throwing. */ head(path: string | undefined, options: RequestOptions & { unwrap: false; }): Promise>; /** Returns a Result tuple instead of throwing. */ head(path: RequestOptions & { unwrap: false; }): Promise>; /** Returns a Result tuple instead of throwing. */ options(path: string | undefined, options: RequestOptions & { unwrap: false; }): Promise>; /** Returns a Result tuple instead of throwing. */ options(path: RequestOptions & { unwrap: false; }): Promise>; /** Returns a Result tuple instead of throwing. */ request(path: string | undefined, options: RequestOptions & { unwrap: false; }): Promise>>; /** Returns a Result tuple instead of throwing. */ request(path: RequestOptions & { unwrap: false; }): Promise>>; /** Returns a Result tuple instead of throwing. */ getJson(path: string | undefined, options: RequestOptions & { unwrap: false; }): Promise>; /** Returns a Result tuple instead of throwing. */ getJson(path: RequestOptions & { unwrap: false; }): Promise>; /** Returns a Result tuple instead of throwing. */ getXml(path: string | undefined, options: RequestOptions & { unwrap: false; }): Promise>; /** Returns a Result tuple instead of throwing. */ getXml(path: RequestOptions & { unwrap: false; }): Promise>; /** Returns a Result tuple instead of throwing. */ getHtml(path: string | undefined, options: RequestOptions & { unwrap: false; }, selector?: string): Promise>; /** Returns a Result tuple instead of throwing. */ getHtml(path: RequestOptions & { unwrap: false; }): Promise>; /** Returns a Result tuple instead of throwing. */ getHtmlFragment(path: string | undefined, options: RequestOptions & { unwrap: false; }, selector?: string): Promise>; /** Returns a Result tuple instead of throwing. */ getHtmlFragment(path: RequestOptions & { unwrap: false; }): Promise>; /** Returns a Result tuple instead of throwing. */ getScript(path: string | undefined, options: RequestOptions & { unwrap: false; }): Promise>; /** Returns a Result tuple instead of throwing. */ getScript(path: RequestOptions & { unwrap: false; }): Promise>; /** Returns a Result tuple instead of throwing. */ getStylesheet(path: string | undefined, options: RequestOptions & { unwrap: false; }): Promise>; /** Returns a Result tuple instead of throwing. */ getStylesheet(path: RequestOptions & { unwrap: false; }): Promise>; /** Returns a Result tuple instead of throwing. */ getBlob(path: string | undefined, options: RequestOptions & { unwrap: false; }): Promise>; /** Returns a Result tuple instead of throwing. */ getBlob(path: RequestOptions & { unwrap: false; }): Promise>; /** Returns a Result tuple instead of throwing. */ getImage(path: string | undefined, options: RequestOptions & { unwrap: false; }): Promise>; /** Returns a Result tuple instead of throwing. */ getBuffer(path: string | undefined, options: RequestOptions & { unwrap: false; }): Promise>; /** Returns a Result tuple instead of throwing. */ getBuffer(path: RequestOptions & { unwrap: false; }): Promise>; /** Returns a Result tuple instead of throwing. */ getStream(path: string | undefined, options: RequestOptions & { unwrap: false; }): Promise | null | undefined>>; /** Returns a Result tuple instead of throwing. */ getStream(path: RequestOptions & { unwrap: false; }): Promise | null | undefined>>; /** Returns a Result tuple instead of throwing. */ getEventStream(path: string | undefined, options: RequestOptions & { unwrap: false; }): Promise>>; /** Returns a Result tuple instead of throwing. */ getEventStream(path: RequestOptions & { unwrap: false; }): Promise>>; /** Returns a Result tuple instead of throwing. */ getJsonStream(path: string | undefined, options: RequestOptions & { unwrap: false; }): Promise>>; /** Returns a Result tuple instead of throwing. */ getJsonStream(path: RequestOptions & { unwrap: false; }): Promise>>; /** * Handles a GET request. * @async * @param path The path to the resource. * @param userOptions The user options for the request. * @param options The options for the request. * @param responseHandler The response handler for the request. * @returns A promise that resolves to the response body or void. */ private _get; /** * It processes the request options and returns a new object with the processed options. * @param path The path to the resource. * @param processedRequestOptions The user options for the request. * @returns A new object with the processed options. */ private _request; /** * Normalizes a retry option into a full RetryOptions object. * @param retry The retry option from request options. * @returns Normalized retry configuration. */ private static normalizeRetryOptions; /** * Waits for the appropriate delay before a retry attempt. * @param config The retry configuration. * @param attempt The current attempt number (1-based). * @returns A promise that resolves after the delay. */ private static retryDelay; /** * It returns a response handler based on the content type of the response. * @param path The path to the resource. * @param userOptions The user options for the request. * @param options The options for the request. * @param responseHandler The response handler for the request. * @returns A response handler function. */ private execute; /** * Creates a new set of options for a request. * @param options The user options for the request. * @param userOptions The default options for the request. * @returns A new set of options for the request. */ private static createOptions; /** * Merges user and request headers into the target Headers object. * @param target The target Headers object. * @param headerSources Variable number of header sources to merge. * @returns The merged Headers object. */ private static mergeHeaders; /** * Merges user and request search parameters into the target URLSearchParams object. * @param target The target URLSearchParams object. * @param sources The search parameters to merge. * @returns The merged URLSearchParams object. */ private static mergeSearchParams; /** * Processes request options by merging user, instance, and method-specific options. * This method optimizes performance by using cached instance options and performing * shallow merges where possible instead of deep object cloning. * @param userOptions The user-provided options for the request. * @param options Additional method-specific options. * @returns Processed request options with signal controller and global flag. */ private processRequestOptions; /** * Gets the base URL from a URL or string. * @param url The URL or string to parse. * @returns The base URL. */ private static getBaseUrl; /** * Parses a content-type string into a MediaType instance with caching. * This method caches parsed MediaType instances to avoid re-parsing the same content-type strings, * which significantly improves performance for repeated requests with the same content types. * @param contentType The content-type string to parse. * @returns The parsed MediaType instance, or undefined if parsing fails. */ private static getOrParseMediaType; /** * Creates a new URL with the given path and search parameters. * @param url The base URL. * @param path The path to append to the base URL. * @param searchParams The search parameters to append to the URL. * @returns A new URL with the given path and search parameters. */ private static createUrl; /** * It generates a ResponseStatus object from an error name and a Response object. * @param errorName The name of the error. * @param response The Response object. * @returns A ResponseStatus object. */ private static generateResponseStatusFromError; /** * Handles an error that occurs during a request. * @param path The path of the request. * @param response The Response object. * @param options Additional error context including cause, entity, url, method, and timing. * @param requestOptions The original request options that led to the error, used for hooks context. * @returns An HttpError object. */ private handleError; /** * Publishes an event to the global and instance event handlers. * @param eventObject The event object to publish. */ private publish; /** * It returns a response handler based on the content type of the response. * @param contentType The content type of the response. * @returns A response handler function. */ private getResponseHandler; /** * A string representation of the Transportr instance. * @returns The string 'Transportr'. */ get [Symbol.toStringTag](): string; } export { ContentType, DownloadProgress, HttpError, HttpErrorOptions, Json, JsonArray, JsonObject, JsonPrimitive, JsonString, JsonValue, RequestCachingPolicy, RequestEvent, RequestHeader, RequestTiming, ResponseBody, ResponseStatus, Result, RetryInfo, ServerSentEvent, SignalErrors, SignalEvents, Transportr, XSRF_COOKIE_NAME, XSRF_HEADER_NAME, abortEvent, aborted, defaultMediaType, defaultOrigin, endsWithSlashRegEx, eventListenerOptions, internalServerError, mediaTypes, requestBodyMethods, retryBackoffFactor, retryDelay, retryMethods, retryStatusCodes, timedOut, timeoutEvent }; export type { AbortConfiguration, AbortEvent, AbortSignalEvent, AfterResponseHook, BeforeErrorHook, BeforeRequestHook, Entries, EventRegistration, HookOptions, NormalizedRetryOptions, PublishOptions, ReadOnlyEntries, RequestBody, RequestBodyMethod, RequestEventDataMap, RequestEventHandler, RequestHeaders, RequestLifecycleEvent, RequestMethod, RequestOptions, ResponseHandler, RetryOptions, SearchParameters, TimeoutEvent, TypedArray, TypedRequestEventHandler, TypedResponse, XsrfOptions };