@nasriya/atomix
Version:
Composable helper functions for building reliable systems
150 lines (149 loc) • 10.3 kB
TypeScript
import { InputSanitizationOptions, SanitizedResult, FieldRuleMap } from "./docs";
declare class HTTPUtils {
#private;
/**
* Provides type guard utilities for validating HTTP-related values,
* such as methods, headers, status codes, and content types.
*
* Use this to ensure correctness and prevent malformed HTTP logic at runtime.
*
* @example
* if (atomix.http.guard.isExtension('.js')) { ... }
*
* @since v1.0.0
*/
readonly guard: {
isHTML(value: string): value is string;
isMimeType(value: unknown): value is import("./mimes/mimes").Mime;
isExtension(value: unknown): value is import("./mimes/mimes").FileExtension;
isValidURL(url: unknown): boolean;
isEmail(value: unknown): value is string;
};
/**
* Provides constants and helpers for working with MIME types.
* Includes common content types like `application/json`, `text/html`, and file extensions.
*
* Useful for setting or validating `Content-Type` headers.
*
* @example
* response.setHeader('Content-Type', atomix.http.mimes.getExtensionByMime('application/json'));
*
* @since v1.0.0
*/
readonly mimes: {
readonly "__#1@#_extensions": import("./mimes/mimes").FileExtension[];
readonly "__#1@#_mimes": import("./mimes/mimes").Mime[];
readonly "__#1@#_cache": {
extensionToMime: Map<"" | ".webp" | ".aac" | ".abw" | ".arc" | ".avif" | ".avi" | ".azw" | ".bin" | ".bmp" | ".bz" | ".bz2" | ".cda" | ".csh" | ".css" | ".csv" | ".doc" | ".docx" | ".eot" | ".epub" | ".gz" | ".gif" | ".html" | ".htm" | ".ico" | ".ics" | ".jar" | ".jpeg" | ".jpg" | ".js" | ".json" | ".jsonld" | ".mid" | ".midi" | ".mjs" | ".mp3" | ".mp4" | ".mpeg" | ".mpkg" | ".odp" | ".ods" | ".odt" | ".oga" | ".ogv" | ".ogx" | ".opus" | ".otf" | ".png" | ".pdf" | ".php" | ".ppt" | ".pptx" | ".rar" | ".rtf" | ".sh" | ".svg" | ".tar" | ".tiff" | ".tif", "text/plain" | "image/webp" | "audio/aac" | "application/x-abiword" | "application/x-freearc" | "image/avif" | "video/x-msvideo" | "application/vnd.amazon.ebook" | "application/octet-stream" | "image/bmp" | "application/x-bzip" | "application/x-bzip2" | "application/x-cdf" | "application/x-csh" | "text/css" | "text/csv" | "application/msword" | "application/vnd.openxmlformats-officedocument.wordprocessingml.document" | "application/vnd.ms-fontobject" | "application/epub+zip" | "application/gzip" | "image/gif" | "text/html" | "image/vnd.microsoft.icon" | "text/calendar" | "application/java-archive" | "image/jpeg" | "text/javascript" | "application/json" | "application/ld+json" | "audio/midi" | "audio/x-midi" | "audio/mpeg" | "video/mp4" | "video/mpeg" | "application/vnd.apple.installer+xml" | "application/vnd.oasis.opendocument.presentation" | "application/vnd.oasis.opendocument.spreadsheet" | "application/vnd.oasis.opendocument.text" | "audio/ogg" | "video/ogg" | "application/ogg" | "audio/opus" | "font/otf" | "image/png" | "application/pdf" | "application/x-httpd-php" | "application/vnd.ms-powerpoint" | "application/vnd.openxmlformats-officedocument.presentationml.presentation" | "application/vnd.rar" | "application/rtf" | "application/x-sh" | "image/svg+xml" | "application/x-tar" | "image/tiff">;
mimeToExtension: Map<"text/plain" | "image/webp" | "audio/aac" | "application/x-abiword" | "application/x-freearc" | "image/avif" | "video/x-msvideo" | "application/vnd.amazon.ebook" | "application/octet-stream" | "image/bmp" | "application/x-bzip" | "application/x-bzip2" | "application/x-cdf" | "application/x-csh" | "text/css" | "text/csv" | "application/msword" | "application/vnd.openxmlformats-officedocument.wordprocessingml.document" | "application/vnd.ms-fontobject" | "application/epub+zip" | "application/gzip" | "image/gif" | "text/html" | "image/vnd.microsoft.icon" | "text/calendar" | "application/java-archive" | "image/jpeg" | "text/javascript" | "application/json" | "application/ld+json" | "audio/midi" | "audio/x-midi" | "audio/mpeg" | "video/mp4" | "video/mpeg" | "application/vnd.apple.installer+xml" | "application/vnd.oasis.opendocument.presentation" | "application/vnd.oasis.opendocument.spreadsheet" | "application/vnd.oasis.opendocument.text" | "audio/ogg" | "video/ogg" | "application/ogg" | "audio/opus" | "font/otf" | "image/png" | "application/pdf" | "application/x-httpd-php" | "application/vnd.ms-powerpoint" | "application/vnd.openxmlformats-officedocument.presentationml.presentation" | "application/vnd.rar" | "application/rtf" | "application/x-sh" | "image/svg+xml" | "application/x-tar" | "image/tiff", "" | ".webp" | ".aac" | ".abw" | ".arc" | ".avif" | ".avi" | ".azw" | ".bin" | ".bmp" | ".bz" | ".bz2" | ".cda" | ".csh" | ".css" | ".csv" | ".doc" | ".docx" | ".eot" | ".epub" | ".gz" | ".gif" | ".html" | ".htm" | ".ico" | ".ics" | ".jar" | ".jpeg" | ".jpg" | ".js" | ".json" | ".jsonld" | ".mid" | ".midi" | ".mjs" | ".mp3" | ".mp4" | ".mpeg" | ".mpkg" | ".odp" | ".ods" | ".odt" | ".oga" | ".ogv" | ".ogx" | ".opus" | ".otf" | ".png" | ".pdf" | ".php" | ".ppt" | ".pptx" | ".rar" | ".rtf" | ".sh" | ".svg" | ".tar" | ".tiff" | ".tif">;
};
readonly extensions: import("./mimes/mimes").FileExtension[];
readonly mimes: import("./mimes/mimes").Mime[];
readonly isValid: {
extension: (ext: any) => ext is import("./mimes/mimes").FileExtension;
mime: (mime: any) => mime is import("./mimes/mimes").Mime;
};
getExtensionByMime(mime: import("./mimes/mimes").Mime): import("./mimes/mimes").FileExtension | undefined;
getMimeByExtension(ext: import("./mimes/mimes").FileExtension): import("./mimes/mimes").Mime | undefined;
};
/**
* Encodes and decodes structured JavaScript values to/from HTTP-safe Buffer payloads.
* Supports values like objects, arrays, sets, maps, and primitives.
*
* Used internally for transmitting cacheable or structured data via HTTP requests or responses.
*
* @example
* const encoded = atomix.http.bodyCodec.encode({ foo: 'bar' });
* const decoded = atomix.http.bodyCodec.decode(encoded);
*
* @since v1.0.2
*/
readonly bodyCodec: {
readonly "__#3@#_helpers": {
serialize: <T extends import("./body-codec").Serializable>(value: T) => {
type: string;
value?: undefined;
} | {
value: T & {};
type: string;
} | {
value: string;
type: string;
} | {
value: any[];
type: string;
};
deserialize: <T extends import("./body-codec").EncodedPayload>(payload: T) => import("./body-codec").Serialization[T["type"]]["type"];
stringify: (value: Record<string, any>, seen?: WeakSet<WeakKey>) => string;
};
encode<T extends import("./body-codec").Serializable>(value: T): Buffer<ArrayBuffer>;
decode(buffer: Buffer): string | number | boolean | any[] | Record<string, any> | Set<any> | Map<any, any> | Date | null | undefined;
};
/**
* Encodes a UTF-8 string into Base64, mimicking browser `btoa()` for regular text.
* @param text The UTF-8 text to encode.
*/
btoa(text: string): string;
/**
* Decodes a Base64 string into UTF-8 text, mimicking browser `atob()`.
* @param base64 The Base64 string to decode.
*/
atob(base64: string): string;
/**
* Sanitizes user input—either a single string or a record of string fields—based on configurable rules.
*
* This method applies rules like HTML stripping, Unicode filtering, deny/allow pattern enforcement,
* control character removal, trimming, and max-length enforcement. It tracks all violations, and optionally
* throws on the first one if `strict` is enabled.
*
* The method supports:
* - Sanitizing a single string input with global options
* - Sanitizing a record of fields with individual per-field rules
*
* ## Default behavior (if no options are provided):
* - Trims leading/trailing whitespace
* - Removes HTML tags
* - Removes non-ASCII (Unicode) characters
* - Removes control characters
* - Allows all characters (no allow pattern)
* - Denies no characters (no deny pattern)
* - Does **not** throw on violations (i.e. `strict: false`)
* - No length limit (`maxLength: Infinity`)
*
* @typeParam T - A string or a record of string fields.
* @param input - The user input to sanitize. Must be a string or a flat object of string values.
* @param options - Optional sanitization rules:
* - If `input` is a string, provide `InputSanitizationOptions`.
* - If `input` is a record, provide a `FieldRuleMap<T>` with per-field configs.
*
* @returns An object with:
* - `output`: The sanitized input (same shape as input)
* - `violations`: A list (or field-mapped object) of rule violations, if any
* - `ok`: A boolean indicating whether the input passed all checks
*
* @throws {TypeError} If input is not a string or flat record of strings.
* @throws {Error} If `strict: true` is enabled and a rule is violated.
*
* @example
* // String usage
* const result = sanitize("<b>Hello 👋</b>", { allowHTML: false, allowUnicode: false });
* console.log(result.output); // "Hello"
* console.log(result.violations); // [{ rule: "html", ... }, { rule: "unicode", ... }]
*
* @example
* // Object usage
* const result = sanitize({ username: "<admin>", bio: "Hi!" }, {
* username: { allow: /^[a-z0-9_]+$/i },
* bio: { maxLength: 10 }
* });
* console.log(result.output); // { username: "admin", bio: "Hi!" }
* console.log(result.violations.username); // [{ rule: "html", ... }]
* console.log(result.ok); // false
*
* @since v1.0.7
*/
sanitize<T extends Record<string, string>>(input: T, configs?: FieldRuleMap<T>): SanitizedResult<T>;
sanitize<T extends string>(input: T, options?: InputSanitizationOptions): SanitizedResult<T>;
}
declare const httpUtils: HTTPUtils;
export default httpUtils;