@lacussoft/cpf-fmt
Version:
Utility to format CPF (Brazilian Individual's Taxpayer ID)
573 lines (564 loc) • 25.4 kB
text/typescript
/**
* Lacus Solutions :: cpf-fmt v3.0.0
*
* @author Julio L. Muller.
* @license MIT - 2021-2026
*/
import { Nullable } from '@lacussoft/utils';
/**
* Class to store the options for the CPF formatter. This class provides a
* centralized way to configure how CPF numbers are formatted, including
* delimiters, hidden digit ranges, HTML escaping, URL encoding, and error
* handling callbacks.
*/
declare class CpfFormatterOptions {
/**
* Default value for the `hidden` option. When `false`, all CPF digits are
* displayed.
*/
static readonly DEFAULT_HIDDEN = false;
/**
* Default string used to replace hidden CPF digits.
*/
static readonly DEFAULT_HIDDEN_KEY = "*";
/**
* Default start index (inclusive) for hiding CPF digits. Digits from this
* index onwards will be replaced with the `hiddenKey` value.
*/
static readonly DEFAULT_HIDDEN_START = 3;
/**
* Default end index (inclusive) for hiding CPF digits. Digits up to and
* including this index will be replaced with the `hiddenKey` value.
*/
static readonly DEFAULT_HIDDEN_END = 10;
/**
* Default string used as the dot delimiter in formatted CPF. Used to separate
* the first groups of digits (XXX.XXX.XXX).
*/
static readonly DEFAULT_DOT_KEY = ".";
/**
* Default string used as the dash delimiter in formatted CPF. Used to
* separate the first group of digits from the check digits at the end (-XX).
*/
static readonly DEFAULT_DASH_KEY = "-";
/**
* Default value for the `escape` option. When `false`, HTML special
* characters are not escaped.
*/
static readonly DEFAULT_ESCAPE = false;
/**
* Default value for the `encode` option. When `false`, the CPF string is not
* URL-encoded.
*/
static readonly DEFAULT_ENCODE = false;
/**
* Default callback function executed when formatting fails. Returns an empty
* string by default.
*/
static readonly DEFAULT_ON_FAIL: OnFailCallback;
/**
* Characters that are not allowed in key options (`hiddenKey`, `dotKey`,
* `dashKey`). They are reserved for internal formatting logic.
*
* For now, it's only used to replace the hidden key placeholder in the
* CpfFormatter class. However, this set of characters is reserved for future
* use already.
*/
static readonly DISALLOWED_KEY_CHARACTERS: readonly string[];
private _options;
/**
* Creates a new instance of `CpfFormatterOptions`.
*
* Options can be provided in multiple ways:
*
* 1. As a single options object or another `CpfFormatterOptions` instance.
* 2. As multiple override objects that are merged in order (later overrides take
* precedence)
*
* All options are optional and will default to their predefined values if not
* provided. The `hiddenStart` and `hiddenEnd` options are validated to ensure
* they are within the valid range [0, CPF_LENGTH - 1] and will be swapped if
* `hiddenStart > hiddenEnd`.
*
* @throws {CpfFormatterOptionsTypeError} If any option has an invalid type.
* @throws {CpfFormatterOptionsHiddenRangeInvalidException} If `hiddenStart`
* or `hiddenEnd` are out of valid range.
* @throws {CpfFormatterOptionsForbiddenKeyCharacterException} If any key
* option (`hiddenKey`, `dotKey`, `dashKey`) contains a disallowed
* character.
*/
constructor(defaultOptions?: CpfFormatterOptionsInput, ...overrides: CpfFormatterOptionsInput[]);
/**
* Returns a shallow copy of all current options, frozen to prevent
* modification. This is useful for creating immutable snapshots of the
* current configuration.
*/
get all(): CpfFormatterOptionsType;
/**
* Gets whether hidden digit replacement is enabled. When `true`, digits
* within the `hiddenStart` to `hiddenEnd` range will be replaced with the
* `hiddenKey` character.
*/
get hidden(): boolean;
/**
* Sets whether hidden digit replacement is enabled. When set to `true`,
* digits within the `hiddenStart` to `hiddenEnd` range will be replaced with
* the `hiddenKey` character. The value is converted to a boolean using
* `Boolean()`, so truthy/falsy values are handled appropriately.
*/
set hidden(value: Nullable<boolean>);
/**
* Gets the string used to replace hidden CPF digits. This string is used when
* `hidden` is `true` to mask digits in the range from `hiddenStart` to
* `hiddenEnd` (inclusive).
*/
get hiddenKey(): string;
/**
* Sets the string used to replace hidden CPF digits. This string is used when
* `hidden` is `true` to mask digits in the range from `hiddenStart` to
* `hiddenEnd` (inclusive).
*
* @throws {CpfFormatterOptionsTypeError} If the value is not a string.
* @throws {CpfFormatterOptionsForbiddenKeyCharacterException} If the value
* contains any disallowed key character.
*/
set hiddenKey(value: Nullable<string>);
/**
* Gets the start index (inclusive) for hiding CPF digits. This is the first
* position in the CPF string where digits will be replaced with the
* `hiddenKey` string when `hidden` is `true`. Must be between `0` and `10`
* (`CPF_LENGTH - 1`).
*/
get hiddenStart(): number;
/**
* Sets the start index (inclusive) for hiding CPF digits. This is the first
* position in the CPF string where digits will be replaced with the
* `hiddenKey` when `hidden` is `true`. The value is validated and will be
* swapped with `hiddenEnd` if necessary to ensure `hiddenStart <=
* hiddenEnd`.
*
* @throws {CpfFormatterOptionsTypeError} If the value is not an integer.
* @throws {CpfFormatterOptionsHiddenRangeInvalidException} If the value is
* out of valid range [0, CPF_LENGTH - 1]
*/
set hiddenStart(value: Nullable<number>);
/**
* Gets the end index (inclusive) for hiding CPF digits. This is the last
* position in the CPF string where digits will be replaced with the
* `hiddenKey` string when `hidden` is `true`. Must be between `0` and `10`
* (`CPF_LENGTH - 1`).
*/
get hiddenEnd(): number;
/**
* Sets the end index (inclusive) for hiding CPF digits. This is the last
* position in the CPF string where digits will be replaced with the
* `hiddenKey` when `hidden` is `true`. The value is validated and will be
* swapped with `hiddenStart` if necessary to ensure `hiddenStart <=
* hiddenEnd`.
*
* @throws {CpfFormatterOptionsTypeError} If the value is not an integer.
* @throws {CpfFormatterOptionsHiddenRangeInvalidException} If the value is
* out of valid range [`0`, `CPF_LENGTH - 1`]
*/
set hiddenEnd(value: Nullable<number>);
/**
* Gets the string used as the dot delimiter. This string is used to separate
* the first groups of digits in the formatted CPF (e.g., `"."` in
* "123.456.789-10").
*/
get dotKey(): string;
/**
* Sets the string used as the dot delimiter. This string is used to separate
* the first groups of digits in the formatted CPF (e.g., `"."` in
* `"123.456.789-10"`).
*
* @throws {CpfFormatterOptionsTypeError} If the value is not a string.
* @throws {CpfFormatterOptionsForbiddenKeyCharacterException} If the value
* contains any disallowed key character.
*/
set dotKey(value: Nullable<string>);
/**
* Gets the string used as the dash delimiter. This string is used to separate
* the check digits at the end in the formatted CPF (e.g., `"-"` in
* `"123.456.789-10"`).
*/
get dashKey(): string;
/**
* Sets the string used as the dash delimiter. This string is used to separate
* the check digits at the end in the formatted CPF (e.g., `"-"` in
* `"123.456.789-10"`).
*
* @throws {CpfFormatterOptionsTypeError} If the value is not a string.
* @throws {CpfFormatterOptionsForbiddenKeyCharacterException} If the value
* contains any disallowed key character.
*/
set dashKey(value: Nullable<string>);
/**
* Gets whether HTML escaping is enabled. When `true`, HTML special characters
* (like `<`, `>`, `&`, etc.) in the formatted CPF string will be escaped.
* This is useful when using custom delimiters that may contain HTML
* characters or when displaying CPF in HTML.
*/
get escape(): boolean;
/**
* Sets whether HTML escaping is enabled. When set to `true`, HTML special
* characters (like `<`, `>`, `&`, etc.) in the formatted CPF string will be
* escaped. This is useful when using custom delimiters that may contain HTML
* characters or when displaying CPF in HTML. The value is converted to a
* boolean using `Boolean()`, so truthy/falsy values are handled
* appropriately.
*/
set escape(value: Nullable<boolean>);
/**
* Gets whether URL encoding is enabled. When `true`, the formatted CPF string
* will be URL-encoded, making it safe to use in URL query parameters or path
* segments.
*/
get encode(): boolean;
/**
* Sets whether URL encoding is enabled. When set to `true`, the formatted CPF
* string will be URL-encoded, making it safe to use in URL query parameters
* or path segments. The value is converted to a boolean using `Boolean()`, so
* truthy/falsy values are handled appropriately.
*/
set encode(value: Nullable<boolean>);
/**
* Gets the callback function executed when formatting fails. This function is
* called when the formatter encounters an error (e.g., invalid input, invalid
* options). It receives the input value and an optional error object, and
* should return a string to use as the fallback output.
*/
get onFail(): OnFailCallback;
/**
* Sets the callback function executed when formatting fails. This function is
* called when the formatter encounters an error (e.g., invalid input, invalid
* options). It receives the input value and an optional error object, and
* should return a string to use as the fallback output.
*
* @throws {CpfFormatterOptionsTypeError} If the value is not a function.
*/
set onFail(value: Nullable<OnFailCallback>);
/**
* Sets the hiddenStart and hiddenEnd options with proper validation and
* sanitization. This method validates that both indices are integers within
* the valid range [`0`, `CPF_LENGTH - 1`]. If `hiddenStart > hiddenEnd`, the
* values are automatically swapped to ensure a valid range. This method is
* used internally by the `hiddenStart` and `hiddenEnd` setters to maintain
* consistency.
*
* @throws {CpfFormatterOptionsTypeError} If either value is not an integer.
* @throws {CpfFormatterOptionsHiddenRangeInvalidException} If either value is
* out of valid range [`0`, `CPF_LENGTH - 1`]
*/
setHiddenRange(hiddenStart: Nullable<number>, hiddenEnd: Nullable<number>): this;
/**
* Sets multiple options at once. This method allows you to update multiple
* options in a single call. Only the provided options are updated; options
* not included in the object retain their current values. You can pass either
* a partial options object or another `CpfFormatterOptions` instance.
*
* @throws {CpfFormatterOptionsTypeError} If any option has an invalid type.
* @throws {CpfFormatterOptionsHiddenRangeInvalidException} If `hiddenStart`
* or `hiddenEnd` are out of valid range.
* @throws {CpfFormatterOptionsForbiddenKeyCharacterException} If any key
* option (`hiddenKey`, `dotKey`, `dashKey`) contains a disallowed
* character.
*/
set(options: CpfFormatterOptionsInput): this;
/**
* Throws if the given string contains any disallowed key character.
*
* @throws {CpfFormatterOptionsForbiddenKeyCharacterException} If `value`
* contains any character from `getDisallowedKeyCharacters()`.
*/
private _assertNoDisallowedKeyCharacters;
}
/**
* Base error class for all `cpf-fmt` type-related errors.
*
* This abstract class extends the native `TypeError` and serves as the base for
* all type validation errors in the CPF formatter. It ensures proper prototype
* chain setup and automatically sets the error name from the constructor.
*/
declare abstract class CpfFormatterTypeError extends TypeError {
readonly name: string;
readonly actualInput: unknown;
readonly actualType: string;
readonly expectedType: string;
constructor(actualInput: unknown, actualType: string, expectedType: string, message: string);
}
/**
* Error raised when the input provided to the CPF formatter is not of the
* expected type {@link CpfInput}. The error message includes both the actual
* input type and the expected type.
*/
declare class CpfFormatterInputTypeError extends CpfFormatterTypeError {
constructor(actualInput: unknown, expectedType: string);
}
/**
* Error raised when a specific option in the formatter configuration has an
* invalid type. The error message includes the option name, the actual input
* type and the expected type.
*/
declare class CpfFormatterOptionsTypeError extends CpfFormatterTypeError {
readonly optionName: keyof CpfFormatterOptionsType;
constructor(optionName: keyof CpfFormatterOptionsType, actualInput: unknown, expectedType: string);
}
/**
* Base exception for all `cpf-fmt` rules-related errors.
*
* This abstract class extends the native `Error` and serves as the base for all
* non-type-related errors in the `CpfFormatter` and its dependencies. It is
* suitable for validation errors, range errors, and other business logic
* exceptions that are not strictly type-related. It ensures proper prototype
* chain setup and automatically sets the error name from the constructor.
*/
declare abstract class CpfFormatterException extends Error {
readonly name: string;
constructor(message: string);
}
/**
* Exception raised when `hiddenStart` or `hiddenEnd` option values are outside
* the valid range for CPF formatting. The valid range bounds are typically
* between 0 and 10 (inclusive), representing the indices of the 11-digit CPF
* string. The error message includes the option name, the actual input value,
* and the expected range bounds.
*/
declare class CpfFormatterOptionsHiddenRangeInvalidException extends CpfFormatterException {
readonly optionName: keyof CpfFormatterOptionsType;
readonly actualInput: number;
readonly minExpectedValue: number;
readonly maxExpectedValue: number;
constructor(optionName: keyof CpfFormatterOptionsType, actualInput: number, minExpectedValue: number, maxExpectedValue: number);
}
/**
* Exception raised when a character is not allowed to be used as a key
* character on options.
*/
declare class CpfFormatterOptionsForbiddenKeyCharacterException extends CpfFormatterException {
readonly optionName: keyof CpfFormatterOptionsType;
readonly actualInput: string;
readonly forbiddenCharacters: readonly string[];
constructor(optionName: keyof CpfFormatterOptionsType, actualInput: string, forbiddenCharacters: readonly string[]);
}
/**
* Exception raised when the CPF string input (after optional processing) does
* not have the required length. A valid CPF must contain exactly 11 digits. The
* error message distinguishes between the original input and the evaluated one
* (which strips punctuation characters).
*/
declare class CpfFormatterInputLengthException extends CpfFormatterException {
readonly actualInput: CpfInput;
readonly evaluatedInput: string;
readonly expectedLength: number;
constructor(actualInput: CpfInput, evaluatedInput: string, expectedLength: number);
}
/**
* Represents valid input types for CPF formatting.
*
* A CPF can be provided as:
*
* - A string containing digits (with or without formatting)
* - An array of strings, where each string represents a digit or group of digits.
*/
type CpfInput = readonly string[] | string;
/**
* Callback function type for handling formatting failures.
*
* This function is invoked when the CPF formatter encounters an error during
* formatting, such as invalid input, invalid options, or other formatting
* issues. The callback receives the original input value and the exception
* object, and should return a string to use as the fallback output.
*/
type OnFailCallback = (value: unknown, exception: CpfFormatterException) => string;
/**
* Configuration interface for CPF (Cadastro de Pessoa Física) formatting
* options. This interface defines all available options for customizing how CPF
* digits are formatted, including delimiter characters, hidden digits range,
* HTML escaping, URL encoding, and error handling. All properties have default
* values and are optional when creating a new `CpfFormatterOptions` instance.
*/
interface CpfFormatterOptionsType {
/**
* Whether to replace some CPF digits with a wildcard character for privacy.
* When `true`, digits within the range defined by `hiddenStart` and
* `hiddenEnd` (inclusive) will be replaced with the character specified in
* `hiddenKey`. This is useful for displaying CPF numbers in a partially
* masked format for privacy or security purposes.
*
* @default false
*/
hidden: boolean;
/**
* The string used to replace hidden CPF digits when `hidden` is `true`. This
* string is used to mask digits in the range from `hiddenStart` to
* `hiddenEnd` (inclusive) when the `hidden` option is enabled. Common choices
* include `*`, `X`, `#`, etc.
*
* @default '*'
*/
hiddenKey: string;
/**
* The start index (inclusive) for hiding CPF digits. This is the first
* position (0-based) in the CPF string where digits will be replaced with the
* `hiddenKey` character when `hidden` is `true`. Must be an integer between
* `0` and `10` (`CPF_LENGTH - 1`).
*
* @default 3
*/
hiddenStart: number;
/**
* The end index (inclusive) for hiding CPF digits. This is the last position
* (0-based) in the CPF string where digits will be replaced with the
* `hiddenKey` character when `hidden` is `true`. Must be an integer between
* `0` and `10` (`CPF_LENGTH - 1`).
*
* @default 10
*/
hiddenEnd: number;
/**
* The string used as the dot delimiter in formatted CPF. This string
* separates the first groups of digits in the standard CPF format. In
* `"123.456.789-10"`, the dots (`.`) are replaced with this delimiter.
*
* @default '.'
*/
dotKey: string;
/**
* The string used as the dash delimiter in formatted CPF. This string
* separates the first group of digits from the check digits at the end of the
* CPF. In `"123456789-10"`, the dash (`-`) is replaced with this delimiter.
*
* @default '-'
*/
dashKey: string;
/**
* Whether to escape HTML special characters in the formatted CPF string. When
* `true`, HTML special characters (such as `<`, `>`, `&`, `"`, `'`) in the
* formatted CPF string will be escaped to their HTML entity equivalents. This
* is particularly useful when:
*
* - Using custom delimiters that may contain HTML characters.
* - Displaying CPF numbers in HTML contexts where special characters could be
* interpreted as HTML markup.
* - Preventing XSS vulnerabilities when rendering user-provided CPF data.
*
* @default false
*/
escape: boolean;
/**
* Whether to URL-encode the formatted CPF string. When `true`, the formatted
* CPF string will be URL-encoded using `encodeURIComponent`, making it safe
* to use in URL query parameters, path segments, or other URL contexts. This
* ensures that special characters in custom keys are properly encoded.
*
* @default false
*/
encode: boolean;
/**
* Callback function executed when CPF formatting fails. This function is
* invoked when the formatter encounters an error during formatting, such as:
*
* - Invalid input (non-digit characters, wrong length, etc.)
* - Invalid options (out-of-range indices, wrong types, etc.)
* - Other formatting errors.
*
* The callback receives the original input value and an optional error
* object, and should return a string that will be used as the fallback output
* instead of throwing an error or returning an invalid result.
*
* @default () => ''
*/
onFail: OnFailCallback;
}
type CpfFormatterOptionsInput = CpfFormatterOptions | Partial<CpfFormatterOptionsType>;
/**
* Helper function to simplify the usage of the {@link CpfFormatter} class.
*
* Formats a CPF string according to the given options. With no options, returns
* the traditional CPF format (e.g. `123.456.789-10`). Invalid input or length
* is handled by the configured `onFail` callback instead of throwing.
*/
declare function cpfFmt(cpfInput: CpfInput, options?: CpfFormatterOptionsInput): string;
/**
* Formatter for CPF (Cadastro de Pessoa Física) identifiers. It normalizes and
* optionally masks, HTML-escapes, or URL-encodes 11-digit CPF input. Accepts a
* string or array of strings; non-numeric characters are stripped. Invalid
* input type is handled by throwing; invalid length is handled via the
* configured `onFail` callback instead of throwing.
*/
declare class CpfFormatter {
private _options;
/**
* Creates a new `CpfFormatter` with optional default options.
*
* Default options apply to every call to `format` unless overridden by the
* per-call `options` argument. Options control masking, HTML escaping, URL
* encoding, and the callback used when formatting fails.
*
* When `defaultOptions` is a `CpfFormatterOptions` instance, that instance is
* used directly (no copy is created). Mutating it later (e.g. via the
* `options` getter or the original reference) affects future `format` calls
* that do not pass per-call options. When a plain object or nothing is
* passed, a new `CpfFormatterOptions` instance is created from it.
*
* @throws {CpfFormatterOptionsTypeError} If any option has an invalid type.
* @throws {CpfFormatterOptionsHiddenRangeInvalidException} If `hiddenStart`
* or `hiddenEnd` are out of valid range.
*/
constructor(defaultOptions?: CpfFormatterOptionsInput);
/**
* Returns the default options used by this formatter when per-call options
* are not provided.
*
* The returned object is the same instance used internally; mutating it (e.g.
* via setters on `CpfFormatterOptions`) affects future `format` calls that do
* not pass `options`.
*/
get options(): CpfFormatterOptions;
/**
* Formats a CPF value into a normalized 11-digit string.
*
* Input is normalized by stripping non-numeric characters. If the result
* length is not exactly 11, the configured `onFail` callback is invoked with
* the string value and an error; its return value is used as the result. If
* the input is not a string or array of strings, this method throws.
*
* When valid, the result may be further transformed according to options:
*
* - If `hidden` is `true`, digits between `hiddenStart` and `hiddenEnd`
* (inclusive) are replaced with `hiddenKey`.
* - If `escape` is `true`, HTML special characters are escaped.
* - If `encode` is `true`, the string is passed through `encodeURIComponent`.
*
* Per-call `options` are merged over the instance default options for this
* call only; the instance defaults are unchanged.
*
* @throws {CpfFormatterOptionsTypeError} If any option has an invalid type.
* @throws {CpfFormatterOptionsHiddenRangeInvalidException} If `hiddenStart`
* or `hiddenEnd` are out of valid range.
* @throws {CpfFormatterInputTypeError} If the input is not a string or array
* of strings.
*/
format(cpfInput: CpfInput, options?: CpfFormatterOptionsInput): string;
/**
* Normalizes the input to a string.
*
* @throws {CpfFormatterInputTypeError} If the input is not a string or array
* of strings.
*/
private _toStringInput;
}
declare const _default: typeof cpfFmt & {
CpfFormatter: typeof CpfFormatter;
CPF_LENGTH: 11;
CpfFormatterOptions: typeof CpfFormatterOptions;
CpfFormatterTypeError: typeof CpfFormatterTypeError;
CpfFormatterInputTypeError: typeof CpfFormatterInputTypeError;
CpfFormatterOptionsTypeError: typeof CpfFormatterOptionsTypeError;
CpfFormatterException: typeof CpfFormatterException;
CpfFormatterOptionsHiddenRangeInvalidException: typeof CpfFormatterOptionsHiddenRangeInvalidException;
CpfFormatterOptionsForbiddenKeyCharacterException: typeof CpfFormatterOptionsForbiddenKeyCharacterException;
CpfFormatterInputLengthException: typeof CpfFormatterInputLengthException;
};
export = _default;