Skip to content

Latest commit

 

History

History
271 lines (209 loc) · 9.51 KB

File metadata and controls

271 lines (209 loc) · 9.51 KB
layout default
title API reference
nav_order 5

API reference

This reference lists the complete public surface of VCoder. Every function is fully type-hinted and carries a docstring with examples; use help(vc.int) (etc.) for the authoritative, always-current details.


The vc facade

from vcoder import vc

vc is a single stateless object that exposes every input function, the security helpers, and the vc.sql / vc.html sub-namespaces. Everything is also importable from its own module (e.g. from vcoder.validators import MinLength).


Input functions

All input functions share these keyword parameters:

  • default — value for empty input (omit for required)
  • optional: bool = False — empty input returns None when no default
  • retries: int | None = None — attempts before RetryLimitExceeded
  • error_message: str | None = None — custom failure message
  • validators: Iterable = () — extra validators/callables
  • reader: Callable[[str], str] | None = None — injectable input source
  • rate_limit: RateLimiter | None = None — cap how fast the input may be submitted; each attempt raises RateLimitExceeded once the limit is hit
Function Returns Type-specific parameters
vc.text(prompt) str min_length, max_length, pattern
vc.int(prompt) int min, max, base
vc.float(prompt) float min, max (rejects nan/inf)
vc.decimal(prompt) Decimal min, max
vc.bool(prompt) bool — (accepts y/yes/true/1/on, n/no/false/0/off)
vc.choice(prompt, choices) matched item case_insensitive
vc.list(prompt) list parser, separator, min_items, max_items, skip_empty
vc.tuple(prompt) tuple parser, separator, length
vc.dict(prompt) dict key_parser, value_parser, item_separator, kv_separator
vc.json(prompt) parsed JSON —
vc.date(prompt) datetime.date formats, min, max
vc.time(prompt) datetime.time formats
vc.datetime(prompt) datetime.datetime formats, min, max
vc.uuid(prompt) uuid.UUID version
vc.email(prompt) str lowercase
vc.url(prompt) str schemes, require_host
vc.ip(prompt) IPv4Address/IPv6Address version
vc.mac(prompt) str —
vc.hostname(prompt) str — (RFC 1123)
vc.port(prompt) int allow_zero
vc.password(prompt) str min_length, policy, confirm, confirm_prompt
vc.filename(prompt) str allow_unicode, max_length
vc.directory(prompt) Path must_exist, within
vc.path(prompt) Path must_exist, within
vc.regex(prompt) re.Pattern flags
vc.enum(prompt, enum_class) enum member by ("name"/"value"), case_insensitive

Notes:

  • vc.password reads without echoing, never logs the value, and never strips or lowercases it. It is not optional; the policy rejects empty input.
  • vc.path/vc.directory with within= block traversal by reprompting.

Example signatures (see docstrings for the rest):

def int(prompt="", *, min=None, max=None, base=10,
        default=UNSET, optional=False, retries=None,
        error_message=None, validators=(), reader=None) -> int | None: ...

def password(prompt="Password: ", *, min_length=12, policy=None,
             confirm=False, confirm_prompt="Confirm password: ",
             retries=None, error_message=None, validators=(),
             reader=None) -> str: ...

The prompt engine

vcoder.core.run_prompt(prompt, converter, validators=(), *, default=UNSET, optional=False, retries=None, error_message=None, reader=None, secret=False, sanitizer=None, stream=None) is the public engine behind every input function. Build your own prompt types with identical behavior by supplying a converter.


Validators

Import from vcoder or vcoder.validators.

  • Validator(*children) — base class & composite; methods validate(value), is_valid(value) -> bool, and __call__.
  • Predicate(func, message="invalid value")
  • Min(minimum), Max(maximum), Range(minimum=None, maximum=None)
  • MinLength(n), MaxLength(n), Length(min=None, max=None, *, exact=None)
  • Regex(pattern, flags=0, *, full=True)
  • NoControlCharacters(), Printable(), Ascii(), NoWhitespace()
  • Unicode(allow=None, deny=None)
  • Entropy(min_bits, *, estimator=estimate_password_bits)
  • Unique()
  • Blacklist(forbidden, *, case_insensitive=False)
  • Whitelist(allowed, *, case_insensitive=False) (alias OneOf)

Configuration

from vcoder import Config, configure, get_config, reset_config, config_scope
  • Config(retries=3, strip=True, lowercase=False, logging=False, prompt_suffix="") — immutable dataclass.
  • configure(**changes) -> Config — update global config (unknown keys raise).
  • get_config() -> Config
  • reset_config() -> Config
  • config_scope(**changes) — context manager restoring previous config on exit.

vc.configure, vc.get_config, vc.reset_config, vc.config_scope mirror these.


Exceptions

from vcoder import (
    VCoderError, ValidationError, RetryLimitExceeded, RateLimitExceeded,
    SecurityError, UnsafePathError, UnsafeSQLQuery, UnsafeShellArgument,
    PasswordTooWeak, ConfigurationError,
)
VCoderError
├── ConfigurationError
├── ValidationError
│   └── PasswordTooWeak
├── RetryLimitExceeded
├── RateLimitExceeded
└── SecurityError
    ├── UnsafePathError
    ├── UnsafeSQLQuery
    └── UnsafeShellArgument

ValidationError(message, *, value=None) stores the offending value but never includes it in str(). RetryLimitExceeded carries attempts and last_error. RateLimitExceeded carries retry_after (seconds).


Rate limiting

from vcoder import RateLimiter   # also vc.RateLimiter
  • RateLimiter(max_calls, per, *, clock=time.monotonic) — sliding-window, thread-safe.
  • check(key=None) -> None — record a call or raise RateLimitExceeded.
  • allow(key=None) -> bool — non-raising; a rejected call is not recorded.
  • remaining(key=None) -> int, reset(key=None), reset_all().

Pass a key (client IP, user id, ...) for independent per-caller budgets, or attach a limiter to any prompt via rate_limit=.


Security helpers

Paths (vcoder.path, also on vc)

  • contains_traversal(value) -> bool
  • safe_join(root, *parts) -> Path
  • resolve_within(root, candidate) -> Path
  • is_within(root, candidate) -> bool

Filesystem (vcoder.filesystem, also on vc)

  • validate_filename(name, *, max_length=255, allow_unicode=True) -> str
  • sanitize_filename(name, *, replacement="_", max_length=255, fallback="file") -> str
  • is_reserved_name(name) -> bool
  • Constants: MAX_FILENAME_LENGTH, WINDOWS_RESERVED_NAMES, ILLEGAL_FILENAME_CHARS

Subprocess (vcoder.subprocess, also on vc)

  • run(args, *, allowed_dirs=None, timeout=None, **kwargs) -> CompletedProcess[str]
  • run_checked(args, ...) -> CompletedProcess[str] (check=True)
  • run_capture(args, *, check=True, ...) -> str
  • sanitize_args(args) -> list[str]
  • resolve_executable(name, *, allowed_dirs=None) -> str

shell and executable kwargs are rejected for safety.

SQL (vcoder.sql, also vc.sql)

  • valid_identifier(name) -> bool
  • guard_query(query, params=None) -> None
  • execute(cursor, query, params=None)
  • build_select(table, columns=None, where=None, *, style="qmark") -> (query, params)
  • build_insert(table, values, *, style="qmark") -> (query, params)
  • select(cursor, table, columns=None, where=None, *, style="qmark")
  • insert(cursor, table, values, *, style="qmark")

style is "qmark" (?), "format" (%s), or "named" (:name).

HTML (vcoder.html, also vc.html and top-level on vc)

  • escape(value, quote=True) -> str
  • escape_attribute(value) -> str
  • strip_html(value) -> str
  • safe_html(value) -> str

Passwords

from vcoder import PasswordPolicy
from vcoder.passwords import (
    is_common_password, password_strength, check_hibp, validate_password,
    COMMON_PASSWORDS,
)
  • PasswordPolicy(min_length=12, max_length=4096, min_bits=0.0, require_lower=False, require_upper=False, require_digit=False, require_symbol=False, forbid_common=True, check_pwned=False, pwned_fail_open=False, extra_forbidden=frozenset()) — .check(password) raises PasswordTooWeak.
  • validate_password(password, policy=None) -> str
  • password_strength(password) -> float (bits)
  • is_common_password(password) -> bool
  • check_hibp(password, *, timeout=5.0) -> int — network call, k-anonymity.

vc.validate_password, vc.password_strength, vc.check_hibp, vc.is_common_password mirror these.


Utilities (vcoder.utils)

  • shannon_entropy(value) -> float
  • estimate_password_bits(value) -> float
  • count_pools(value) -> int
  • normalize_unicode(value, form="NFC") -> str
  • has_control_characters(value) -> bool
  • is_printable(value) -> bool
  • all_unique(items) -> bool

Sanitizers (vcoder.sanitizers)

  • strip, collapse_whitespace, to_lowercase, to_uppercase, normalize, remove_control_characters, compose(*sanitizers), default_input_sanitizer.