|
# /// script |
|
# requires-python = ">=3.13" |
|
# dependencies = [ |
|
# "httpx>=0.28,<0.29", |
|
# "pydantic>=2.11,<3", |
|
# "rich>=14.1,<16", |
|
# "typer>=0.20,<1", |
|
# ] |
|
# [tool.uv] |
|
# exclude-newer = "2026-08-21T00:00:00Z" |
|
# /// |
|
"""Fetch public ATS job postings from one careers or job URL.""" |
|
|
|
from __future__ import annotations |
|
|
|
import html |
|
import ipaddress |
|
import io |
|
import json |
|
import re |
|
import sys |
|
import tempfile |
|
import time |
|
import traceback |
|
from collections.abc import Callable, Mapping, Sequence |
|
from contextlib import contextmanager |
|
from dataclasses import dataclass |
|
from datetime import UTC, datetime |
|
from enum import IntEnum, StrEnum |
|
from html.parser import HTMLParser |
|
from pathlib import Path |
|
from typing import Annotated, Any, Final, Iterator, Protocol, cast |
|
from urllib.parse import parse_qsl, quote, unquote, urlencode, urljoin, urlsplit, urlunsplit |
|
|
|
import httpx |
|
import typer |
|
from pydantic import BaseModel, ConfigDict, Field, field_validator |
|
from rich import box |
|
from rich.console import Console, Group, RenderableType |
|
from rich.panel import Panel |
|
from rich.rule import Rule |
|
from rich.table import Table |
|
from rich.text import Text |
|
|
|
__version__ = "0.3.0" |
|
|
|
USER_AGENT: Final = f"ats-jobs/{__version__}" |
|
MAX_RESPONSE_BYTES: Final = 25 * 1024 * 1024 |
|
MAX_DISCOVERY_BYTES: Final = 5 * 1024 * 1024 |
|
MAX_PAGES: Final = 10_000 |
|
MAX_REDIRECTS: Final = 5 |
|
LEVER_PAGE_SIZE: Final = 100 |
|
WORKDAY_PAGE_SIZE: Final = 20 |
|
RETRYABLE_STATUS_CODES: Final = frozenset({408, 425, 429, 500, 502, 503, 504}) |
|
TRACKING_QUERY_KEYS: Final = frozenset( |
|
{ |
|
"gh_src", |
|
"ref", |
|
"referrer", |
|
"source", |
|
"trk", |
|
} |
|
) |
|
type JsonObject = dict[str, Any] |
|
type JsonValue = JsonObject | list[Any] | str | int | float | bool | None |
|
type EventSink = Callable[[str], None] |
|
|
|
|
|
class ExitCode(IntEnum): |
|
"""Stable process exit codes.""" |
|
|
|
SUCCESS = 0 |
|
INPUT = 2 |
|
NOT_FOUND = 3 |
|
AMBIGUOUS = 4 |
|
TRANSPORT = 5 |
|
INVALID_JSON = 6 |
|
SCHEMA = 7 |
|
UNSUPPORTED = 8 |
|
PAGINATION = 9 |
|
RUNTIME = 10 |
|
PERMISSION = 11 |
|
RATE_LIMIT = 12 |
|
|
|
|
|
class Provider(StrEnum): |
|
"""Supported ATS providers.""" |
|
|
|
GREENHOUSE = "greenhouse" |
|
LEVER = "lever" |
|
ASHBY = "ashby" |
|
WORKABLE = "workable" |
|
BAMBOOHR = "bamboohr" |
|
WORKDAY = "workday" |
|
|
|
|
|
class SupportTier(StrEnum): |
|
"""Evidence level for an operation's upstream interface.""" |
|
|
|
DOCUMENTED_PUBLIC = "documented-public" |
|
DOCUMENTED_DERIVED = "documented-derived" |
|
UNDOCUMENTED_PUBLIC = "undocumented-public" |
|
|
|
|
|
class Operation(StrEnum): |
|
"""Supported fetch operations.""" |
|
|
|
LIST = "list" |
|
GET = "get" |
|
|
|
|
|
class OutputFormat(StrEnum): |
|
"""CLI output formats.""" |
|
|
|
AUTO = "auto" |
|
PRETTY = "pretty" |
|
JSON = "json" |
|
JSONL = "jsonl" |
|
TABLE = "table" |
|
|
|
|
|
class DiscoveryMethod(StrEnum): |
|
"""How a user URL was resolved to a provider-native ATS target.""" |
|
|
|
DIRECT = "direct-host" |
|
OVERRIDE = "provider-override" |
|
REDIRECT = "redirect" |
|
CANONICAL = "canonical-link" |
|
META = "metadata-link" |
|
EMBED = "embedded-link" |
|
LINK = "page-link" |
|
HTML = "html-pattern" |
|
SLUG_PROBE = "slug-probe" |
|
|
|
|
|
class ATSJobsError(Exception): |
|
"""Base domain error carrying a stable exit code.""" |
|
|
|
exit_code = ExitCode.RUNTIME |
|
|
|
def __init__( |
|
self, |
|
message: str, |
|
*, |
|
provider: Provider | None = None, |
|
operation: Operation | None = None, |
|
url: str | None = None, |
|
) -> None: |
|
super().__init__(message) |
|
self.message = message |
|
self.provider = provider |
|
self.operation = operation |
|
self.url = sanitize_url(url) if url else None |
|
|
|
def __str__(self) -> str: |
|
context = [ |
|
value |
|
for value in ( |
|
self.provider.value if self.provider else None, |
|
self.operation.value if self.operation else None, |
|
) |
|
if value |
|
] |
|
prefix = f"[{'/'.join(context)}] " if context else "" |
|
suffix = f" ({self.url})" if self.url else "" |
|
return f"{prefix}{self.message}{suffix}" |
|
|
|
|
|
class InputError(ATSJobsError): |
|
exit_code = ExitCode.INPUT |
|
|
|
|
|
class NotFoundError(ATSJobsError): |
|
exit_code = ExitCode.NOT_FOUND |
|
|
|
|
|
class AmbiguousMatchError(ATSJobsError): |
|
exit_code = ExitCode.AMBIGUOUS |
|
|
|
|
|
class TransportError(ATSJobsError): |
|
exit_code = ExitCode.TRANSPORT |
|
|
|
|
|
class InvalidJSONError(ATSJobsError): |
|
exit_code = ExitCode.INVALID_JSON |
|
|
|
|
|
class SchemaError(ATSJobsError): |
|
exit_code = ExitCode.SCHEMA |
|
|
|
|
|
class UnsupportedInterfaceError(ATSJobsError): |
|
exit_code = ExitCode.UNSUPPORTED |
|
|
|
|
|
class PaginationError(ATSJobsError): |
|
exit_code = ExitCode.PAGINATION |
|
|
|
|
|
class PermissionError(ATSJobsError): |
|
exit_code = ExitCode.PERMISSION |
|
|
|
|
|
class RateLimitError(ATSJobsError): |
|
exit_code = ExitCode.RATE_LIMIT |
|
|
|
|
|
@dataclass(frozen=True, slots=True) |
|
class CliReporter: |
|
"""Human-friendly CLI diagnostics that never contaminate stdout.""" |
|
|
|
verbose: int = 0 |
|
quiet: bool = False |
|
|
|
@staticmethod |
|
def _emit( |
|
label: str, |
|
message: str, |
|
*, |
|
color: str | None = None, |
|
bold: bool = False, |
|
dim: bool = False, |
|
) -> None: |
|
typer.secho( |
|
f"{label:<7} {message}", |
|
fg=color, |
|
bold=bold, |
|
dim=dim, |
|
err=True, |
|
) |
|
|
|
def warning(self, message: str) -> None: |
|
"""Emit a warning unless quiet mode is active.""" |
|
if not self.quiet: |
|
self._emit("WARNING", message, color=typer.colors.YELLOW) |
|
|
|
def info(self, message: str) -> None: |
|
"""Emit progress at ``-v`` or above.""" |
|
if self.verbose >= 1 and not self.quiet: |
|
self._emit("INFO", message, color=typer.colors.CYAN) |
|
|
|
def debug(self, message: str) -> None: |
|
"""Emit request-level detail at ``-vv`` or above.""" |
|
if self.verbose >= 2 and not self.quiet: |
|
self._emit("DEBUG", message, color=typer.colors.BLUE, dim=True) |
|
|
|
def success(self, message: str) -> None: |
|
"""Emit a completion summary at ``-v`` or above.""" |
|
if self.verbose >= 1 and not self.quiet: |
|
self._emit("OK", message, color=typer.colors.GREEN, bold=True) |
|
|
|
@contextmanager |
|
def status(self, message: str) -> Iterator[None]: |
|
"""Show a transient spinner only on an interactive stderr terminal.""" |
|
if self.quiet or self.verbose >= 1 or not sys.stderr.isatty(): |
|
yield |
|
return |
|
console = Console(stderr=True, highlight=False) |
|
with console.status(message, spinner="dots"): |
|
yield |
|
|
|
def error(self, error: ATSJobsError) -> None: |
|
"""Emit a domain error and its most useful remediation.""" |
|
self._emit("ERROR", str(error), color=typer.colors.RED, bold=True) |
|
hint = cli_error_hint(error) |
|
if hint: |
|
self._emit("HINT", hint, color=typer.colors.CYAN) |
|
|
|
def unexpected(self, error: Exception) -> None: |
|
"""Emit a safe unexpected-error summary, with a trace only at ``-vv``.""" |
|
self._emit( |
|
"ERROR", |
|
f"unexpected {type(error).__name__}: {error}", |
|
color=typer.colors.RED, |
|
bold=True, |
|
) |
|
if self.verbose >= 2: |
|
traceback.print_exc(file=sys.stderr) |
|
else: |
|
self._emit( |
|
"HINT", |
|
"Re-run with -vv for request details and a traceback.", |
|
color=typer.colors.CYAN, |
|
) |
|
|
|
|
|
def cli_error_hint(error: ATSJobsError) -> str | None: |
|
"""Return a concise next step for a CLI-facing domain error.""" |
|
if isinstance(error, UnsupportedInterfaceError): |
|
return "Remove --documented-only to allow this best-effort public interface." |
|
if isinstance(error, NotFoundError): |
|
return "Verify that the board or posting is public and that the URL has not expired." |
|
if isinstance(error, AmbiguousMatchError): |
|
return "Use the canonical posting URL or a provider-specific posting identifier." |
|
if isinstance(error, PermissionError): |
|
return "Confirm that the careers page is public and does not require authentication." |
|
if isinstance(error, InvalidJSONError): |
|
return "The provider returned non-JSON content; retry with -vv to inspect the request path." |
|
if isinstance(error, RateLimitError): |
|
return "Retry later or reduce request frequency." |
|
if isinstance(error, PaginationError): |
|
return "Retry once; the board may have changed while pages were being collected." |
|
if isinstance(error, SchemaError): |
|
return "The provider response may have changed. Re-run with -vv before reporting it." |
|
if isinstance(error, TransportError): |
|
return "Check connectivity and the URL. Re-run with -vv for HTTP request details." |
|
if isinstance(error, InputError): |
|
if "unsupported ATS hostname" in error.message or "could not detect" in error.message: |
|
return ( |
|
"Paste the public careers page or native ATS URL, keep --discover enabled, " |
|
"or set --provider explicitly." |
|
) |
|
if "--raw" in error.message and "json" in error.message: |
|
return "Use --format json or --format jsonl with --raw." |
|
if "--quiet cannot be combined" in error.message: |
|
return "Choose quiet mode or verbosity, not both." |
|
if "--pretty cannot be combined" in error.message: |
|
return "Use --pretty by itself, or choose exactly one --format value." |
|
if "--pager cannot be combined" in error.message: |
|
return "Choose terminal paging or file output, not both." |
|
if "--pager requires" in error.message: |
|
return "Use --pretty --pager, or omit --pager for machine-readable output." |
|
if "board but not an individual posting" in error.message: |
|
return "Use `list` for the board or paste the provider's direct posting URL." |
|
return "Run `ats-jobs --help` or `ats-jobs <command> --help` for examples." |
|
return None |
|
|
|
|
|
class ProviderSpec(BaseModel): |
|
"""Static provider capability metadata.""" |
|
|
|
model_config = ConfigDict(frozen=True) |
|
|
|
provider: Provider |
|
hosts: tuple[str, ...] |
|
list_support: SupportTier |
|
get_support: SupportTier |
|
list_semantics: str |
|
notes: str | None = None |
|
verified_at: str = "2026-08-21" |
|
|
|
|
|
class Target(BaseModel): |
|
"""Provider-specific information parsed from a user URL.""" |
|
|
|
model_config = ConfigDict(frozen=True) |
|
|
|
provider: Provider |
|
original_url: str |
|
origin: str |
|
operation: Operation |
|
board: str | None = None |
|
job_id: str | None = None |
|
region: str | None = None |
|
tenant: str | None = None |
|
site: str | None = None |
|
external_path: str | None = None |
|
|
|
|
|
class DiscoveryResult(BaseModel): |
|
"""Resolved target plus explainable discovery provenance.""" |
|
|
|
model_config = ConfigDict(frozen=True) |
|
|
|
requested_url: str |
|
resolved_url: str |
|
method: DiscoveryMethod |
|
target: Target |
|
visited_urls: tuple[str, ...] = () |
|
probed_slugs: tuple[str, ...] = () |
|
|
|
|
|
class FetchOptions(BaseModel): |
|
"""Provider-independent fetch options.""" |
|
|
|
model_config = ConfigDict(frozen=True) |
|
|
|
include_unlisted: bool = False |
|
documented_only: bool = False |
|
|
|
|
|
class JobPosting(BaseModel): |
|
"""Minimal cross-provider representation with the source object retained.""" |
|
|
|
model_config = ConfigDict(extra="forbid") |
|
|
|
provider: Provider |
|
id: str |
|
title: str |
|
company: str | None = None |
|
location: str | None = None |
|
department: str | None = None |
|
employment_type: str | None = None |
|
description_html: str | None = None |
|
description_text: str | None = None |
|
job_url: str |
|
apply_url: str | None = None |
|
published_at: str | None = None |
|
remote: bool | None = None |
|
source: JsonObject = Field(default_factory=dict) |
|
|
|
@field_validator("id", "title", "job_url") |
|
@classmethod |
|
def _non_empty(cls, value: str) -> str: |
|
if not value.strip(): |
|
msg = "must not be empty" |
|
raise ValueError(msg) |
|
return value |
|
|
|
|
|
PROVIDER_SPECS: Final[dict[Provider, ProviderSpec]] = { |
|
Provider.GREENHOUSE: ProviderSpec( |
|
provider=Provider.GREENHOUSE, |
|
hosts=("boards.greenhouse.io", "job-boards.greenhouse.io", "boards-api.greenhouse.io"), |
|
list_support=SupportTier.DOCUMENTED_PUBLIC, |
|
get_support=SupportTier.DOCUMENTED_PUBLIC, |
|
list_semantics="All public job posts returned by the board's Job Board API.", |
|
), |
|
Provider.LEVER: ProviderSpec( |
|
provider=Provider.LEVER, |
|
hosts=("jobs.lever.co", "jobs.eu.lever.co", "api.lever.co", "api.eu.lever.co"), |
|
list_support=SupportTier.DOCUMENTED_PUBLIC, |
|
get_support=SupportTier.DOCUMENTED_PUBLIC, |
|
list_semantics="All published postings returned through explicit offset pagination.", |
|
), |
|
Provider.ASHBY: ProviderSpec( |
|
provider=Provider.ASHBY, |
|
hosts=("jobs.ashbyhq.com", "api.ashbyhq.com"), |
|
list_support=SupportTier.DOCUMENTED_PUBLIC, |
|
get_support=SupportTier.DOCUMENTED_DERIVED, |
|
list_semantics=( |
|
"Listed public postings by default; include direct-link postings on request." |
|
), |
|
notes="Single-job lookup is an exact local match against the documented public feed.", |
|
), |
|
Provider.WORKABLE: ProviderSpec( |
|
provider=Provider.WORKABLE, |
|
hosts=("apply.workable.com", "jobs.workable.com", "www.workable.com"), |
|
list_support=SupportTier.DOCUMENTED_PUBLIC, |
|
get_support=SupportTier.DOCUMENTED_DERIVED, |
|
list_semantics="Public postings from the account endpoint with details enabled.", |
|
notes="Single-job lookup is an exact local shortcode or URL match.", |
|
), |
|
Provider.BAMBOOHR: ProviderSpec( |
|
provider=Provider.BAMBOOHR, |
|
hosts=("*.bamboohr.com",), |
|
list_support=SupportTier.UNDOCUMENTED_PUBLIC, |
|
get_support=SupportTier.UNDOCUMENTED_PUBLIC, |
|
list_semantics="Openings exposed by BambooHR's hosted-careers browser interface.", |
|
notes="The hosted-careers JSON interface is undocumented and may change without notice.", |
|
), |
|
Provider.WORKDAY: ProviderSpec( |
|
provider=Provider.WORKDAY, |
|
hosts=("*.myworkdayjobs.com", "*.myworkdaysite.com"), |
|
list_support=SupportTier.UNDOCUMENTED_PUBLIC, |
|
get_support=SupportTier.UNDOCUMENTED_PUBLIC, |
|
list_semantics="Public postings exposed by the hosted-careers CXS interface.", |
|
notes="CXS is an undocumented browser-facing interface, not Workday Web Services.", |
|
), |
|
} |
|
|
|
|
|
def sanitize_url(value: str | None) -> str | None: |
|
"""Remove credentials, query parameters, and fragments from a diagnostic URL.""" |
|
if value is None: |
|
return None |
|
try: |
|
parsed = urlsplit(value) |
|
except ValueError: |
|
return "<invalid-url>" |
|
host = parsed.hostname or "" |
|
if parsed.port: |
|
host = f"{host}:{parsed.port}" |
|
return urlunsplit((parsed.scheme, host, parsed.path, "", "")) |
|
|
|
|
|
def coerce_url(value: str) -> str: |
|
"""Accept a normal HTTP(S) URL, adding https:// to a bare hostname.""" |
|
candidate = value.strip() |
|
if not candidate: |
|
raise InputError("URL must not be empty") |
|
if "://" not in candidate and "." in candidate.split("/", 1)[0]: |
|
candidate = f"https://{candidate}" |
|
try: |
|
parsed = urlsplit(candidate) |
|
except ValueError as exc: |
|
raise InputError("URL could not be parsed", url=candidate) from exc |
|
if parsed.scheme not in {"http", "https"} or not parsed.hostname: |
|
raise InputError("URL must use http or https and include a hostname", url=candidate) |
|
if parsed.username or parsed.password: |
|
raise InputError("embedded URL credentials are not allowed", url=candidate) |
|
try: |
|
parsed.hostname.encode("idna") |
|
except UnicodeError as exc: |
|
raise InputError("URL hostname is invalid", url=candidate) from exc |
|
return candidate |
|
|
|
|
|
def canonicalize_url(value: str) -> str: |
|
"""Canonicalize a URL for exact provider-job matching.""" |
|
parsed = urlsplit(coerce_url(value)) |
|
host = cast(str, parsed.hostname).encode("idna").decode("ascii").lower() |
|
if parsed.port: |
|
host = f"{host}:{parsed.port}" |
|
path = re.sub(r"/{2,}", "/", parsed.path or "/") |
|
if path != "/": |
|
path = path.rstrip("/") |
|
path = quote(path, safe="/%:@~!$&'()*+,;=-._") |
|
query = [ |
|
(key, item) |
|
for key, item in parse_qsl(parsed.query, keep_blank_values=True) |
|
if not key.lower().startswith("utm_") and key.lower() not in TRACKING_QUERY_KEYS |
|
] |
|
query.sort() |
|
return urlunsplit((parsed.scheme.lower(), host, path, urlencode(query), "")) |
|
|
|
|
|
def strip_html(value: str | None) -> str | None: |
|
"""Convert provider HTML to compact plain text without evaluating it.""" |
|
if value is None: |
|
return None |
|
text = re.sub(r"<(br|/p|/li|/div|/h[1-6])\b[^>]*>", "\n", value, flags=re.IGNORECASE) |
|
text = re.sub(r"<[^>]+>", " ", text) |
|
text = html.unescape(text) |
|
text = re.sub(r"[ \t\r\f\v]+", " ", text) |
|
text = re.sub(r"\s+([.,;:!?])", r"\1", text) |
|
text = re.sub(r" *\n+ *", "\n", text) |
|
return text.strip() or None |
|
|
|
|
|
def timestamp_to_iso(value: Any) -> str | None: |
|
"""Normalize common epoch-millisecond or string timestamps.""" |
|
if isinstance(value, bool) or value is None: |
|
return None |
|
if isinstance(value, int | float): |
|
seconds = float(value) / 1000 if value > 10_000_000_000 else float(value) |
|
try: |
|
return datetime.fromtimestamp(seconds, tz=UTC).isoformat().replace("+00:00", "Z") |
|
except (OverflowError, OSError, ValueError): |
|
return None |
|
if isinstance(value, str): |
|
return value.strip() or None |
|
return None |
|
|
|
|
|
def _segments(path: str) -> list[str]: |
|
return [segment for segment in path.split("/") if segment] |
|
|
|
|
|
def _is_locale(segment: str) -> bool: |
|
return bool(re.fullmatch(r"[a-zA-Z]{2}(?:-[a-zA-Z]{2})?", segment)) |
|
|
|
|
|
def _valid_identifier(value: str | None, *, name: str) -> str: |
|
if value is None or not re.fullmatch(r"[A-Za-z0-9._-]+", value): |
|
raise InputError(f"could not derive a valid {name}") |
|
return value |
|
|
|
|
|
def _provider_matches_host(provider: Provider, host: str) -> bool: |
|
"""Return whether a hostname belongs to a provider's native surfaces.""" |
|
lowered = host.lower() |
|
if provider is Provider.GREENHOUSE: |
|
return lowered in PROVIDER_SPECS[provider].hosts |
|
if provider is Provider.LEVER: |
|
return lowered in PROVIDER_SPECS[provider].hosts |
|
if provider is Provider.ASHBY: |
|
return lowered in PROVIDER_SPECS[provider].hosts |
|
if provider is Provider.WORKABLE: |
|
return lowered in {"apply.workable.com", "jobs.workable.com", "www.workable.com"} or ( |
|
lowered.endswith(".workable.com") and lowered.count(".") >= 2 |
|
) |
|
if provider is Provider.BAMBOOHR: |
|
return lowered.endswith(".bamboohr.com") |
|
return lowered.endswith(".myworkdayjobs.com") or lowered.endswith(".myworkdaysite.com") |
|
|
|
|
|
def detect_provider(value: str, override: Provider | None = None) -> Provider: |
|
"""Detect the ATS provider from a URL hostname.""" |
|
if override is not None: |
|
return override |
|
parsed = urlsplit(coerce_url(value)) |
|
host = cast(str, parsed.hostname).lower() |
|
for provider in Provider: |
|
if _provider_matches_host(provider, host): |
|
return provider |
|
raise InputError("unsupported ATS hostname", url=value) |
|
|
|
|
|
def parse_target(value: str, override: Provider | None = None) -> Target: |
|
"""Parse a careers or job URL into provider-specific identifiers.""" |
|
url = coerce_url(value) |
|
host = cast(str, urlsplit(url).hostname).lower() |
|
if override is not None and not _provider_matches_host(override, host): |
|
path = urlsplit(url).path |
|
custom_workday_cxs = override is Provider.WORKDAY and path.startswith("/wday/cxs/") |
|
if not custom_workday_cxs: |
|
raise InputError( |
|
"provider override needs discovery for a non-provider hostname", |
|
url=url, |
|
) |
|
provider = detect_provider(url, override) |
|
parser = TARGET_PARSERS[provider] |
|
return parser(url) |
|
|
|
|
|
def _parse_greenhouse(url: str) -> Target: |
|
parsed = urlsplit(url) |
|
host = cast(str, parsed.hostname).lower() |
|
parts = _segments(parsed.path) |
|
query = dict(parse_qsl(parsed.query, keep_blank_values=True)) |
|
board: str | None = None |
|
job_id: str | None = None |
|
if host == "boards-api.greenhouse.io": |
|
if len(parts) >= 4 and parts[:2] == ["v1", "boards"] and parts[3] == "jobs": |
|
board = parts[2] |
|
job_id = parts[4] if len(parts) >= 5 else None |
|
elif parts[:1] == ["embed"]: |
|
board = query.get("for") |
|
job_id = query.get("token") or query.get("gh_jid") |
|
elif parts: |
|
board = parts[0] |
|
if "jobs" in parts: |
|
index = parts.index("jobs") |
|
job_id = parts[index + 1] if len(parts) > index + 1 else None |
|
if board is None: |
|
board = query.get("for") |
|
if job_id is None: |
|
job_id = query.get("gh_jid") |
|
board = _valid_identifier(board, name="Greenhouse board token") |
|
if job_id is not None and not job_id.isdigit(): |
|
raise InputError("Greenhouse job-post ID must be numeric", url=url) |
|
return Target( |
|
provider=Provider.GREENHOUSE, |
|
original_url=url, |
|
origin="https://boards-api.greenhouse.io", |
|
operation=Operation.GET if job_id else Operation.LIST, |
|
board=board, |
|
job_id=job_id, |
|
) |
|
|
|
|
|
def _parse_lever(url: str) -> Target: |
|
parsed = urlsplit(url) |
|
host = cast(str, parsed.hostname).lower() |
|
parts = _segments(parsed.path) |
|
region = "eu" if ".eu." in host else "global" |
|
if host.startswith("api."): |
|
if len(parts) < 3 or parts[:2] != ["v0", "postings"]: |
|
raise InputError("could not derive Lever site from API URL", url=url) |
|
site = parts[2] |
|
job_id = parts[3] if len(parts) >= 4 else None |
|
else: |
|
site = parts[0] if parts else None |
|
job_id = parts[1] if len(parts) >= 2 else None |
|
site = _valid_identifier(site, name="Lever site") |
|
if job_id is not None: |
|
job_id = _valid_identifier(job_id, name="Lever posting ID") |
|
origin = "https://api.eu.lever.co" if region == "eu" else "https://api.lever.co" |
|
return Target( |
|
provider=Provider.LEVER, |
|
original_url=url, |
|
origin=origin, |
|
operation=Operation.GET if job_id else Operation.LIST, |
|
board=site, |
|
job_id=job_id, |
|
region=region, |
|
) |
|
|
|
|
|
def _parse_ashby(url: str) -> Target: |
|
parsed = urlsplit(url) |
|
host = cast(str, parsed.hostname).lower() |
|
parts = _segments(parsed.path) |
|
if host == "api.ashbyhq.com": |
|
prefix = ["posting-api", "job-board"] |
|
if len(parts) < 3 or parts[:2] != prefix: |
|
raise InputError("could not derive Ashby board name from API URL", url=url) |
|
board = parts[2] |
|
job_id = None |
|
else: |
|
board = parts[0] if parts else None |
|
job_id = parts[1] if len(parts) >= 2 else None |
|
board = _valid_identifier(board, name="Ashby board name") |
|
return Target( |
|
provider=Provider.ASHBY, |
|
original_url=url, |
|
origin="https://api.ashbyhq.com", |
|
operation=Operation.GET if job_id else Operation.LIST, |
|
board=board, |
|
job_id=job_id, |
|
) |
|
|
|
|
|
def _parse_workable(url: str) -> Target: |
|
parsed = urlsplit(url) |
|
host = cast(str, parsed.hostname).lower() |
|
parts = _segments(parsed.path) |
|
account: str | None = None |
|
job_id: str | None = None |
|
if host in {"apply.workable.com", "jobs.workable.com", "www.workable.com"}: |
|
if host == "www.workable.com" and len(parts) >= 3 and parts[:2] == ["api", "accounts"]: |
|
account = parts[2] |
|
return Target( |
|
provider=Provider.WORKABLE, |
|
original_url=url, |
|
origin="https://www.workable.com", |
|
operation=Operation.LIST, |
|
board=_valid_identifier(account, name="Workable account"), |
|
) |
|
if host == "jobs.workable.com" and parts[:1] == ["view"]: |
|
raise InputError( |
|
"Workable view URLs do not expose the account; use the account careers URL", |
|
url=url, |
|
) |
|
if parts[:1] in (["j"], ["view"]): |
|
raise InputError( |
|
"Workable short job URLs do not expose the account; use an account-bearing URL", |
|
url=url, |
|
) |
|
account = parts[0] if parts else None |
|
if len(parts) >= 3 and parts[1] in {"j", "jobs"}: |
|
job_id = parts[2] |
|
elif len(parts) >= 2 and parts[1] not in {"jobs"}: |
|
job_id = parts[1] |
|
else: |
|
account = host.split(".", 1)[0] |
|
if parts: |
|
job_id = parts[-1] if parts[-1] not in {"careers", "jobs"} else None |
|
account = _valid_identifier(account, name="Workable account") |
|
if job_id is not None: |
|
job_id = _valid_identifier(job_id, name="Workable shortcode") |
|
return Target( |
|
provider=Provider.WORKABLE, |
|
original_url=url, |
|
origin="https://www.workable.com", |
|
operation=Operation.GET if job_id else Operation.LIST, |
|
board=account, |
|
job_id=job_id, |
|
) |
|
|
|
|
|
def _parse_bamboohr(url: str) -> Target: |
|
parsed = urlsplit(url) |
|
host = cast(str, parsed.hostname).lower() |
|
tenant = host.removesuffix(".bamboohr.com") |
|
tenant = _valid_identifier(tenant, name="BambooHR tenant") |
|
parts = _segments(parsed.path) |
|
job_id: str | None = None |
|
if "careers" in parts: |
|
index = parts.index("careers") |
|
if len(parts) > index + 1 and parts[index + 1].isdigit(): |
|
job_id = parts[index + 1] |
|
return Target( |
|
provider=Provider.BAMBOOHR, |
|
original_url=url, |
|
origin=f"https://{tenant}.bamboohr.com", |
|
operation=Operation.GET if job_id else Operation.LIST, |
|
tenant=tenant, |
|
job_id=job_id, |
|
) |
|
|
|
|
|
def _parse_workday(url: str) -> Target: |
|
parsed = urlsplit(url) |
|
host = cast(str, parsed.hostname).lower() |
|
parts = _segments(parsed.path) |
|
tenant: str | None = None |
|
site: str | None = None |
|
tail: list[str] = [] |
|
if len(parts) >= 4 and parts[:2] == ["wday", "cxs"]: |
|
tenant, site = parts[2], parts[3] |
|
tail = parts[4:] |
|
elif host.endswith(".myworkdaysite.com"): |
|
if len(parts) < 3 or parts[0] != "recruiting": |
|
raise InputError("expected /recruiting/TENANT/SITE in Workday URL", url=url) |
|
tenant, site = parts[1], parts[2] |
|
tail = parts[3:] |
|
else: |
|
tenant = host.split(".", 1)[0] |
|
if parts and _is_locale(parts[0]): |
|
parts = parts[1:] |
|
if parts: |
|
site = parts[0] |
|
tail = parts[1:] |
|
tenant = _valid_identifier(tenant, name="Workday tenant") |
|
site = _valid_identifier(site, name="Workday site") |
|
external_path = f"/{'/'.join(tail)}" if tail and tail[0] == "job" else None |
|
return Target( |
|
provider=Provider.WORKDAY, |
|
original_url=url, |
|
origin=f"{parsed.scheme}://{parsed.netloc}", |
|
operation=Operation.GET if external_path else Operation.LIST, |
|
tenant=tenant, |
|
site=site, |
|
external_path=external_path, |
|
) |
|
|
|
|
|
TARGET_PARSERS: Final[dict[Provider, Callable[[str], Target]]] = { |
|
Provider.GREENHOUSE: _parse_greenhouse, |
|
Provider.LEVER: _parse_lever, |
|
Provider.ASHBY: _parse_ashby, |
|
Provider.WORKABLE: _parse_workable, |
|
Provider.BAMBOOHR: _parse_bamboohr, |
|
Provider.WORKDAY: _parse_workday, |
|
} |
|
|
|
|
|
@dataclass(frozen=True, slots=True) |
|
class DiscoveryCandidate: |
|
"""One provider-native URL discovered on a public careers page.""" |
|
|
|
url: str |
|
method: DiscoveryMethod |
|
score: int |
|
provider: Provider | None = None |
|
|
|
|
|
@dataclass(frozen=True, slots=True) |
|
class DiscoveryPage: |
|
"""A bounded public HTML response and its redirect history.""" |
|
|
|
final_url: str |
|
text: str |
|
visited_urls: tuple[str, ...] |
|
|
|
|
|
class _ATSLinkParser(HTMLParser): |
|
"""Extract URL-bearing HTML attributes without treating page text as trusted markup.""" |
|
|
|
def __init__(self, base_url: str) -> None: |
|
super().__init__(convert_charrefs=True) |
|
self.base_url = base_url |
|
self.candidates: list[DiscoveryCandidate] = [] |
|
|
|
def _add( |
|
self, |
|
value: str | None, |
|
method: DiscoveryMethod, |
|
score: int, |
|
provider: Provider | None = None, |
|
) -> None: |
|
if not value: |
|
return |
|
candidate = urljoin(self.base_url, html.unescape(value.strip()).replace("\\/", "/")) |
|
try: |
|
detected = provider or detect_provider(candidate) |
|
parse_target(candidate, detected) |
|
except ATSJobsError: |
|
return |
|
self.candidates.append(DiscoveryCandidate(candidate, method, score, detected)) |
|
|
|
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: |
|
attributes = {name.lower(): value for name, value in attrs} |
|
lowered_tag = tag.lower() |
|
rel = (attributes.get("rel") or "").lower().split() |
|
if lowered_tag == "link" and "canonical" in rel: |
|
self._add(attributes.get("href"), DiscoveryMethod.CANONICAL, 110) |
|
if lowered_tag == "meta": |
|
key = (attributes.get("property") or attributes.get("name") or "").lower() |
|
if key in {"og:url", "twitter:url"}: |
|
self._add(attributes.get("content"), DiscoveryMethod.META, 100) |
|
|
|
method = ( |
|
DiscoveryMethod.EMBED |
|
if lowered_tag in {"iframe", "form", "script"} |
|
else DiscoveryMethod.LINK |
|
) |
|
score = 90 if method is DiscoveryMethod.EMBED else 70 |
|
for name in ("href", "src", "action", "data-url", "data-src", "data-jobs-url"): |
|
self._add(attributes.get(name), method, score) |
|
|
|
provider_attributes = ( |
|
(Provider.ASHBY, "data-ashby-job-board-name", "https://jobs.ashbyhq.com/{value}"), |
|
( |
|
Provider.GREENHOUSE, |
|
"data-greenhouse-board", |
|
"https://job-boards.greenhouse.io/{value}", |
|
), |
|
( |
|
Provider.GREENHOUSE, |
|
"data-greenhouse-board-token", |
|
"https://job-boards.greenhouse.io/{value}", |
|
), |
|
(Provider.LEVER, "data-lever-site", "https://jobs.lever.co/{value}"), |
|
(Provider.WORKABLE, "data-workable-account", "https://apply.workable.com/{value}"), |
|
( |
|
Provider.BAMBOOHR, |
|
"data-bamboohr-tenant", |
|
"https://{value}.bamboohr.com/careers", |
|
), |
|
) |
|
for provider, attribute, template in provider_attributes: |
|
identifier = attributes.get(attribute) |
|
if identifier and re.fullmatch(r"[A-Za-z0-9._-]+", identifier): |
|
self._add( |
|
template.format(value=identifier), |
|
DiscoveryMethod.EMBED, |
|
95, |
|
provider, |
|
) |
|
|
|
workday_tenant = attributes.get("data-workday-tenant") |
|
workday_site = attributes.get("data-workday-site") |
|
if ( |
|
workday_tenant |
|
and workday_site |
|
and re.fullmatch(r"[A-Za-z0-9._-]+", workday_tenant) |
|
and re.fullmatch(r"[A-Za-z0-9._-]+", workday_site) |
|
): |
|
self._add( |
|
f"/wday/cxs/{workday_tenant}/{workday_site}/jobs", |
|
DiscoveryMethod.EMBED, |
|
95, |
|
Provider.WORKDAY, |
|
) |
|
|
|
|
|
|
|
ATS_URL_PATTERN: Final = re.compile( |
|
r"https?:(?:\\?/){2}(?:[^\s\"'<>]|\\/)+", |
|
flags=re.IGNORECASE, |
|
) |
|
ENCODED_ATS_URL_PATTERN: Final = re.compile( |
|
r"https?%3A%2F%2F[A-Za-z0-9%._~:/?#\[\]@!$&'()*+,;=-]+", |
|
flags=re.IGNORECASE, |
|
) |
|
WORKDAY_CXS_PATH_PATTERN: Final = re.compile( |
|
r"/wday/cxs/[A-Za-z0-9._-]+/[A-Za-z0-9._-]+(?:/[^\s\"'<>]*)?", |
|
flags=re.IGNORECASE, |
|
) |
|
PROTOCOL_RELATIVE_ATS_PATTERN: Final = re.compile( |
|
r"(?<!:)//(?:boards\.greenhouse\.io|job-boards\.greenhouse\.io|" |
|
r"jobs(?:\.eu)?\.lever\.co|jobs\.ashbyhq\.com|apply\.workable\.com|" |
|
r"[A-Za-z0-9._-]+\.bamboohr\.com|" |
|
r"[A-Za-z0-9._-]+\.(?:myworkdayjobs|myworkdaysite)\.com)" |
|
r"(?:/[^\s\"'<>]*)?", |
|
flags=re.IGNORECASE, |
|
) |
|
GENERIC_HOST_PREFIXES: Final = frozenset( |
|
{"www", "careers", "career", "jobs", "job", "apply", "work", "join", "hiring"} |
|
) |
|
MULTIPART_PUBLIC_SUFFIXES: Final = frozenset( |
|
{ |
|
"co.uk", |
|
"com.au", |
|
"com.br", |
|
"com.cn", |
|
"com.mx", |
|
"co.jp", |
|
"co.nz", |
|
"co.za", |
|
} |
|
) |
|
GENERIC_PATH_SEGMENTS: Final = frozenset( |
|
{ |
|
"about", |
|
"career", |
|
"careers", |
|
"company", |
|
"en", |
|
"jobs", |
|
"join", |
|
"openings", |
|
"positions", |
|
"work-with-us", |
|
} |
|
) |
|
|
|
|
|
def _validate_public_discovery_url(value: str) -> str: |
|
"""Reject obviously local or non-public discovery targets.""" |
|
candidate = coerce_url(value) |
|
host = cast(str, urlsplit(candidate).hostname).lower().rstrip(".") |
|
if host == "localhost" or host.endswith((".localhost", ".local", ".internal")): |
|
raise InputError("discovery URL must use a public hostname", url=candidate) |
|
try: |
|
address = ipaddress.ip_address(host) |
|
except ValueError: |
|
return candidate |
|
if not address.is_global: |
|
raise InputError("discovery URL must not target a private or reserved IP", url=candidate) |
|
return candidate |
|
|
|
|
|
class DiscoveryClient: |
|
"""Bounded HTML/JSON client used only when hostname parsing is insufficient.""" |
|
|
|
def __init__( |
|
self, |
|
client: httpx.Client | None = None, |
|
*, |
|
retries: int = 2, |
|
sleeper: Callable[[float], None] = time.sleep, |
|
event_sink: EventSink | None = None, |
|
) -> None: |
|
self._owned = client is None |
|
self._client = client or httpx.Client( |
|
timeout=httpx.Timeout(20.0, connect=8.0), |
|
headers={"User-Agent": USER_AGENT}, |
|
) |
|
self._retries = max(retries, 1) |
|
self._sleeper = sleeper |
|
self._event_sink = event_sink |
|
|
|
def _debug(self, message: str) -> None: |
|
if self._event_sink is not None: |
|
self._event_sink(message) |
|
|
|
def close(self) -> None: |
|
if self._owned: |
|
self._client.close() |
|
|
|
def _request( |
|
self, |
|
url: str, |
|
*, |
|
accept: str, |
|
params: Mapping[str, Any] | None = None, |
|
allowed_hosts: Sequence[str] | None = None, |
|
) -> tuple[httpx.Response, tuple[str, ...]]: |
|
initial = _validate_public_discovery_url(url) |
|
visited: list[str] = [] |
|
last_response: httpx.Response | None = None |
|
for attempt in range(self._retries): # pragma: no branch |
|
request = self._client.build_request( |
|
"GET", |
|
initial, |
|
params=params, |
|
headers={"Accept": accept, "User-Agent": USER_AGENT}, |
|
) |
|
try: |
|
for redirect_count in range(MAX_REDIRECTS + 1): |
|
safe_url = _validate_public_discovery_url(str(request.url)) |
|
request = self._client.build_request( |
|
"GET", |
|
safe_url, |
|
headers={"Accept": accept, "User-Agent": USER_AGENT}, |
|
) |
|
host = request.url.host or "" |
|
if allowed_hosts is not None and not _host_allowed(host, allowed_hosts): |
|
raise TransportError( |
|
f"unexpected discovery destination: {host}", |
|
url=safe_url, |
|
) |
|
visited.append(safe_url) |
|
self._debug( |
|
f"discover GET {sanitize_url(safe_url)} " |
|
f"(attempt {attempt + 1}/{self._retries})" |
|
) |
|
response = self._client.send(request, follow_redirects=False) |
|
last_response = response |
|
if not response.is_redirect: |
|
break |
|
next_request = response.next_request |
|
if next_request is None: |
|
raise TransportError( |
|
"discovery redirect is missing a Location header", |
|
url=safe_url, |
|
) |
|
if redirect_count >= MAX_REDIRECTS: |
|
raise TransportError( |
|
f"discovery redirect chain exceeds {MAX_REDIRECTS} hops", |
|
url=initial, |
|
) |
|
self._debug( |
|
f"discover redirect {response.status_code} -> " |
|
f"{sanitize_url(str(next_request.url))}" |
|
) |
|
request = self._client.build_request( |
|
"GET", |
|
str(next_request.url), |
|
headers={"Accept": accept, "User-Agent": USER_AGENT}, |
|
) |
|
else: # pragma: no cover - guarded above. |
|
raise AssertionError("unreachable discovery redirect state") |
|
except (httpx.TimeoutException, httpx.TransportError) as exc: |
|
if attempt + 1 < self._retries: |
|
delay = _retry_delay(None, attempt) |
|
self._debug(f"discovery {type(exc).__name__}; retrying in {delay:.2f}s") |
|
self._sleeper(delay) |
|
continue |
|
raise TransportError( |
|
f"discovery request failed after {self._retries} attempts: {exc}", |
|
url=initial, |
|
) from exc |
|
if response.status_code in RETRYABLE_STATUS_CODES and attempt + 1 < self._retries: |
|
delay = _retry_delay(response, attempt) |
|
self._debug( |
|
f"discovery HTTP {response.status_code}; retrying in {delay:.2f}s" |
|
) |
|
self._sleeper(delay) |
|
continue |
|
break |
|
response = cast(httpx.Response, last_response) |
|
if response.status_code in {401, 403}: |
|
raise PermissionError( |
|
f"careers page denied discovery (HTTP {response.status_code})", |
|
url=initial, |
|
) |
|
if response.status_code == 404: |
|
raise NotFoundError("careers page was not found", url=initial) |
|
if response.status_code == 429: |
|
raise RateLimitError("discovery was rate limited after retries", url=initial) |
|
if response.status_code >= 400: |
|
raise TransportError( |
|
f"discovery request failed (HTTP {response.status_code})", |
|
url=initial, |
|
) |
|
if len(response.content) > MAX_DISCOVERY_BYTES: |
|
raise TransportError( |
|
f"discovery response exceeds {MAX_DISCOVERY_BYTES} bytes", |
|
url=initial, |
|
) |
|
return response, tuple(dict.fromkeys(visited)) |
|
|
|
def fetch_page(self, url: str) -> DiscoveryPage: |
|
"""Fetch one public page and retain its redirect history.""" |
|
response, visited = self._request( |
|
url, |
|
accept="text/html,application/xhtml+xml;q=0.9,*/*;q=0.5", |
|
) |
|
return DiscoveryPage( |
|
final_url=str(response.url), |
|
text=response.text, |
|
visited_urls=visited, |
|
) |
|
|
|
def request_json( |
|
self, |
|
url: str, |
|
*, |
|
allowed_hosts: Sequence[str], |
|
params: Mapping[str, Any] | None = None, |
|
) -> JsonValue: |
|
"""Request JSON from one known ATS host for a bounded slug probe.""" |
|
response, _visited = self._request( |
|
url, |
|
accept="application/json", |
|
params=params, |
|
allowed_hosts=allowed_hosts, |
|
) |
|
try: |
|
return cast(JsonValue, response.json()) |
|
except (json.JSONDecodeError, UnicodeDecodeError, ValueError) as exc: |
|
raise InvalidJSONError("probe response is not valid JSON", url=url) from exc |
|
|
|
|
|
def _extract_discovery_candidates(page: DiscoveryPage) -> list[DiscoveryCandidate]: |
|
parser = _ATSLinkParser(page.final_url) |
|
try: |
|
parser.feed(page.text) |
|
except Exception: |
|
# Attribute extraction is opportunistic; independent text scans still run. |
|
pass |
|
candidates = list(parser.candidates) |
|
|
|
scan_text = ( |
|
html.unescape(page.text) |
|
.replace("\\/", "/") |
|
.replace("\\u002F", "/") |
|
.replace("\\u002f", "/") |
|
.replace("\\x2F", "/") |
|
.replace("\\x2f", "/") |
|
) |
|
scanned_values = [match.group(0) for match in ATS_URL_PATTERN.finditer(scan_text)] |
|
scanned_values.extend( |
|
unquote(match.group(0)) for match in ENCODED_ATS_URL_PATTERN.finditer(scan_text) |
|
) |
|
scanned_values.extend( |
|
f"https:{match.group(0)}" for match in PROTOCOL_RELATIVE_ATS_PATTERN.finditer(scan_text) |
|
) |
|
for value in scanned_values: |
|
try: |
|
provider = detect_provider(value) |
|
parse_target(value, provider) |
|
except ATSJobsError: |
|
continue |
|
candidates.append(DiscoveryCandidate(value, DiscoveryMethod.HTML, 55, provider)) |
|
|
|
for match in WORKDAY_CXS_PATH_PATTERN.finditer(scan_text): |
|
value = urljoin(page.final_url, match.group(0)) |
|
try: |
|
parse_target(value, Provider.WORKDAY) |
|
except ATSJobsError: |
|
continue |
|
candidates.append( |
|
DiscoveryCandidate(value, DiscoveryMethod.HTML, 80, Provider.WORKDAY) |
|
) |
|
|
|
unique: dict[str, DiscoveryCandidate] = {} |
|
for candidate in candidates: |
|
key = canonicalize_url(candidate.url) |
|
previous = unique.get(key) |
|
if previous is None or candidate.score > previous.score: |
|
unique[key] = candidate |
|
return list(unique.values()) |
|
|
|
|
|
def _operation_hint(value: str) -> Operation: |
|
parsed = urlsplit(coerce_url(value)) |
|
query = {key.lower(): item for key, item in parse_qsl(parsed.query)} |
|
if any(key in query for key in {"gh_jid", "job_id", "jobid", "postingid"}): |
|
return Operation.GET |
|
parts = [part.lower() for part in _segments(parsed.path)] |
|
if not parts or parts[-1] in GENERIC_PATH_SEGMENTS: |
|
return Operation.LIST |
|
for marker in { |
|
"career", |
|
"careers", |
|
"job", |
|
"jobs", |
|
"opening", |
|
"openings", |
|
"position", |
|
"positions", |
|
"view", |
|
}: |
|
if marker in parts and parts.index(marker) + 1 < len(parts): |
|
return Operation.GET |
|
if re.fullmatch(r"\d+", parts[-1]) or re.fullmatch( |
|
r"[0-9a-f]{8}-[0-9a-f-]{27,}", |
|
parts[-1], |
|
flags=re.IGNORECASE, |
|
): |
|
return Operation.GET |
|
return Operation.LIST |
|
|
|
|
|
def _list_target(target: Target) -> Target: |
|
return target.model_copy( |
|
update={ |
|
"operation": Operation.LIST, |
|
"job_id": None, |
|
"external_path": None, |
|
} |
|
) |
|
|
|
|
|
def _apply_requested_reference(requested_url: str, target: Target) -> Target: |
|
"""Carry explicit provider references from a custom URL onto a discovered board.""" |
|
if target.operation is not Operation.LIST or target.provider is not Provider.GREENHOUSE: |
|
return target |
|
query = {key.lower(): value for key, value in parse_qsl(urlsplit(requested_url).query)} |
|
job_id = query.get("gh_jid") |
|
if job_id and job_id.isdigit(): |
|
return target.model_copy(update={"operation": Operation.GET, "job_id": job_id}) |
|
return target |
|
|
|
|
|
def _target_key(target: Target) -> tuple[Any, ...]: |
|
return ( |
|
target.provider, |
|
target.operation, |
|
target.board, |
|
target.tenant, |
|
target.site, |
|
target.region, |
|
target.job_id if target.operation is Operation.GET else None, |
|
target.external_path if target.operation is Operation.GET else None, |
|
) |
|
|
|
|
|
def _select_discovery_candidate( |
|
requested_url: str, |
|
candidates: Sequence[DiscoveryCandidate], |
|
override: Provider | None, |
|
) -> tuple[Target, DiscoveryCandidate] | None: |
|
hint = _operation_hint(requested_url) |
|
grouped: dict[tuple[Any, ...], list[tuple[Target, DiscoveryCandidate]]] = {} |
|
for candidate in candidates: |
|
try: |
|
provider = candidate.provider or detect_provider(candidate.url) |
|
if override is not None and provider is not override: |
|
continue |
|
target = parse_target(candidate.url, provider) |
|
except ATSJobsError: |
|
continue |
|
if hint is Operation.LIST and target.operation is Operation.GET: |
|
target = _list_target(target) |
|
elif hint is Operation.GET: |
|
target = _apply_requested_reference(requested_url, target) |
|
grouped.setdefault(_target_key(target), []).append((target, candidate)) |
|
if not grouped: |
|
return None |
|
|
|
ranked: list[tuple[int, tuple[Any, ...], Target, DiscoveryCandidate]] = [] |
|
for key, values in grouped.items(): |
|
target = values[0][0] |
|
best = max(values, key=lambda item: item[1].score)[1] |
|
score = best.score + min(len(values), 20) * 2 |
|
if target.operation is hint: |
|
score += 8 |
|
ranked.append((score, key, target, best)) |
|
ranked.sort(key=lambda item: item[0], reverse=True) |
|
top_score = ranked[0][0] |
|
top = [item for item in ranked if item[0] == top_score] |
|
if len(top) > 1: |
|
choices = ", ".join( |
|
sorted({f"{item[2].provider.value}:{item[2].board or item[2].site}" for item in top}) |
|
) |
|
raise AmbiguousMatchError( |
|
f"multiple ATS targets were equally plausible: {choices}", |
|
url=requested_url, |
|
) |
|
_score, _key, target, candidate = top[0] |
|
return target, candidate |
|
|
|
|
|
def _slug_candidates(value: str) -> tuple[str, ...]: |
|
parsed = urlsplit(coerce_url(value)) |
|
labels = [label for label in cast(str, parsed.hostname).lower().split(".") if label] |
|
while labels and labels[0] in GENERIC_HOST_PREFIXES: |
|
labels.pop(0) |
|
|
|
raw_values: list[str] = [] |
|
if len(labels) >= 2: |
|
suffix = ".".join(labels[-2:]) |
|
base_index = -3 if suffix in MULTIPART_PUBLIC_SUFFIXES and len(labels) >= 3 else -2 |
|
raw_values.append(labels[base_index]) |
|
|
|
for segment in _segments(parsed.path): |
|
lowered = segment.lower() |
|
if ( |
|
lowered not in GENERIC_PATH_SEGMENTS |
|
and not lowered.isdigit() |
|
and not re.fullmatch(r"[0-9a-f]{8}-[0-9a-f-]{27,}", lowered) |
|
): |
|
raw_values.append(lowered) |
|
|
|
result: list[str] = [] |
|
for raw in raw_values: |
|
for variant in (raw, re.sub(r"[^a-z0-9]", "", raw)): |
|
slug = re.sub(r"[^a-z0-9._-]", "", variant) |
|
if slug and slug not in result: |
|
result.append(slug) |
|
return tuple(result[:4]) |
|
|
|
|
|
def _probe_slug( |
|
slug: str, |
|
provider: Provider, |
|
discovery: DiscoveryClient, |
|
) -> Target | None: |
|
try: |
|
if provider is Provider.GREENHOUSE: |
|
payload = discovery.request_json( |
|
f"https://boards-api.greenhouse.io/v1/boards/{slug}/jobs", |
|
allowed_hosts=("boards-api.greenhouse.io",), |
|
) |
|
if not isinstance(payload, Mapping) or not isinstance(payload.get("jobs"), list): |
|
return None |
|
return parse_target(f"https://job-boards.greenhouse.io/{slug}") |
|
if provider is Provider.LEVER: |
|
payload = discovery.request_json( |
|
f"https://api.lever.co/v0/postings/{slug}", |
|
allowed_hosts=("api.lever.co",), |
|
params={"mode": "json", "limit": 1}, |
|
) |
|
if not isinstance(payload, list): |
|
return None |
|
return parse_target(f"https://jobs.lever.co/{slug}") |
|
if provider is Provider.ASHBY: |
|
payload = discovery.request_json( |
|
f"https://api.ashbyhq.com/posting-api/job-board/{slug}", |
|
allowed_hosts=("api.ashbyhq.com",), |
|
) |
|
if not isinstance(payload, Mapping) or not isinstance(payload.get("jobs"), list): |
|
return None |
|
return parse_target(f"https://jobs.ashbyhq.com/{slug}") |
|
if provider is Provider.WORKABLE: |
|
payload = discovery.request_json( |
|
f"https://www.workable.com/api/accounts/{slug}", |
|
allowed_hosts=("www.workable.com",), |
|
params={"details": "false"}, |
|
) |
|
if not isinstance(payload, Mapping) or not isinstance(payload.get("jobs"), list): |
|
return None |
|
return parse_target(f"https://apply.workable.com/{slug}") |
|
except ATSJobsError: |
|
return None |
|
return None |
|
|
|
|
|
def resolve_target( |
|
value: str, |
|
override: Provider | None = None, |
|
*, |
|
discover: bool = True, |
|
probe: bool = True, |
|
discovery: DiscoveryClient | None = None, |
|
event_sink: EventSink | None = None, |
|
) -> DiscoveryResult: |
|
"""Resolve a direct ATS URL or discover the ATS behind a custom careers page.""" |
|
requested_url = coerce_url(value) |
|
direct_failure: InputError | None = None |
|
try: |
|
target = parse_target(requested_url, override) |
|
except InputError as exc: |
|
direct_failure = exc |
|
if not discover: |
|
raise |
|
else: |
|
return DiscoveryResult( |
|
requested_url=requested_url, |
|
resolved_url=target.original_url, |
|
method=DiscoveryMethod.OVERRIDE if override is not None else DiscoveryMethod.DIRECT, |
|
target=target, |
|
visited_urls=(requested_url,), |
|
) |
|
|
|
owned = discovery is None |
|
client = discovery or DiscoveryClient(event_sink=event_sink) |
|
page: DiscoveryPage | None = None |
|
page_error: ATSJobsError | None = None |
|
try: |
|
try: |
|
page = client.fetch_page(requested_url) |
|
except ATSJobsError as exc: |
|
page_error = exc |
|
|
|
if page is not None: |
|
for redirected_url in reversed(page.visited_urls[1:]): |
|
try: |
|
target = parse_target(redirected_url, override) |
|
except ATSJobsError: |
|
continue |
|
return DiscoveryResult( |
|
requested_url=requested_url, |
|
resolved_url=redirected_url, |
|
method=DiscoveryMethod.REDIRECT, |
|
target=target, |
|
visited_urls=page.visited_urls, |
|
) |
|
|
|
if canonicalize_url(page.final_url) != canonicalize_url(requested_url): |
|
try: |
|
target = parse_target(page.final_url, override) |
|
except ATSJobsError: |
|
pass |
|
else: |
|
return DiscoveryResult( |
|
requested_url=requested_url, |
|
resolved_url=page.final_url, |
|
method=DiscoveryMethod.REDIRECT, |
|
target=target, |
|
visited_urls=page.visited_urls, |
|
) |
|
|
|
selected = _select_discovery_candidate( |
|
requested_url, |
|
_extract_discovery_candidates(page), |
|
override, |
|
) |
|
if selected is not None: |
|
target, candidate = selected |
|
return DiscoveryResult( |
|
requested_url=requested_url, |
|
resolved_url=candidate.url, |
|
method=candidate.method, |
|
target=target, |
|
visited_urls=page.visited_urls, |
|
) |
|
|
|
slugs = _slug_candidates(requested_url) if probe else () |
|
matches: list[tuple[str, Target]] = [] |
|
providers = (override,) if override is not None else ( |
|
Provider.GREENHOUSE, |
|
Provider.LEVER, |
|
Provider.ASHBY, |
|
Provider.WORKABLE, |
|
) |
|
for slug in slugs: |
|
for provider in providers: |
|
target = _probe_slug(slug, provider, client) |
|
if target is not None: |
|
matches.append((slug, target)) |
|
deduplicated: dict[tuple[Any, ...], tuple[str, Target]] = {} |
|
for slug, target in matches: |
|
deduplicated.setdefault(_target_key(target), (slug, target)) |
|
if len(deduplicated) == 1: |
|
slug, target = next(iter(deduplicated.values())) |
|
return DiscoveryResult( |
|
requested_url=requested_url, |
|
resolved_url=target.original_url, |
|
method=DiscoveryMethod.SLUG_PROBE, |
|
target=target, |
|
visited_urls=page.visited_urls if page is not None else (), |
|
probed_slugs=slugs, |
|
) |
|
if len(deduplicated) > 1: |
|
choices = ", ".join( |
|
sorted( |
|
f"{target.provider.value}:{target.board or target.site}" |
|
for _slug, target in deduplicated.values() |
|
) |
|
) |
|
raise AmbiguousMatchError( |
|
f"slug probes found multiple plausible boards: {choices}", |
|
url=requested_url, |
|
) |
|
|
|
detail = f"; page discovery failed: {page_error.message}" if page_error else "" |
|
attempted = f"; probed slugs: {', '.join(slugs)}" if slugs else "" |
|
raise InputError( |
|
"could not detect a supported ATS from the hostname, redirects, or page links" |
|
f"{attempted}{detail}", |
|
url=requested_url, |
|
) from direct_failure |
|
finally: |
|
if owned: |
|
client.close() |
|
|
|
|
|
def _host_allowed(host: str, allowed_hosts: Sequence[str]) -> bool: |
|
lowered = host.lower() |
|
return any( |
|
lowered == allowed.lower() |
|
or (allowed.startswith(".") and lowered.endswith(allowed.lower())) |
|
for allowed in allowed_hosts |
|
) |
|
|
|
|
|
def _retry_delay(response: httpx.Response | None, attempt: int) -> float: |
|
if response is not None: |
|
retry_after = response.headers.get("Retry-After") |
|
if retry_after: |
|
try: |
|
return min(max(float(retry_after), 0.0), 10.0) |
|
except ValueError: |
|
pass |
|
return min(0.25 * (2**attempt), 2.0) |
|
|
|
|
|
class HttpClient: |
|
"""Small fail-closed JSON HTTP client with bounded retries.""" |
|
|
|
def __init__( |
|
self, |
|
client: httpx.Client | None = None, |
|
*, |
|
retries: int = 3, |
|
sleeper: Callable[[float], None] = time.sleep, |
|
event_sink: EventSink | None = None, |
|
) -> None: |
|
self._owned = client is None |
|
self._client = client or httpx.Client( |
|
timeout=httpx.Timeout(45.0, connect=10.0), |
|
headers={"Accept": "application/json", "User-Agent": USER_AGENT}, |
|
) |
|
self._retries = max(retries, 1) |
|
self._sleeper = sleeper |
|
self._event_sink = event_sink |
|
|
|
def _debug(self, message: str) -> None: |
|
if self._event_sink is not None: |
|
self._event_sink(message) |
|
|
|
def close(self) -> None: |
|
if self._owned: |
|
self._client.close() |
|
|
|
def request_json( |
|
self, |
|
method: str, |
|
url: str, |
|
*, |
|
provider: Provider, |
|
operation: Operation, |
|
allowed_hosts: Sequence[str], |
|
params: Mapping[str, Any] | None = None, |
|
json_body: JsonObject | None = None, |
|
) -> JsonValue: |
|
initial_host = urlsplit(url).hostname or "" |
|
if not _host_allowed(initial_host, allowed_hosts): |
|
raise TransportError( |
|
f"request host is not allowed: {initial_host}", |
|
provider=provider, |
|
operation=operation, |
|
url=url, |
|
) |
|
last_response: httpx.Response | None = None |
|
for attempt in range(self._retries): |
|
request = self._client.build_request(method, url, params=params, json=json_body) |
|
started = time.perf_counter() |
|
self._debug( |
|
f"{method.upper()} {sanitize_url(str(request.url))} " |
|
f"(attempt {attempt + 1}/{self._retries})" |
|
) |
|
try: |
|
for redirect_count in range(MAX_REDIRECTS + 1): |
|
response = self._client.send(request, follow_redirects=False) |
|
last_response = response |
|
if not response.is_redirect: |
|
break |
|
next_request = response.next_request |
|
if next_request is None: |
|
raise TransportError( |
|
"redirect response is missing a valid Location header", |
|
provider=provider, |
|
operation=operation, |
|
url=url, |
|
) |
|
next_host = next_request.url.host or "" |
|
self._debug( |
|
f"redirect {response.status_code} -> {sanitize_url(str(next_request.url))}" |
|
) |
|
if not _host_allowed(next_host, allowed_hosts): |
|
raise TransportError( |
|
f"unexpected redirect destination: {next_host}", |
|
provider=provider, |
|
operation=operation, |
|
url=url, |
|
) |
|
if redirect_count >= MAX_REDIRECTS: |
|
raise TransportError( |
|
f"redirect chain exceeds {MAX_REDIRECTS} hops", |
|
provider=provider, |
|
operation=operation, |
|
url=url, |
|
) |
|
request = next_request |
|
else: # pragma: no cover - range exhaustion is guarded above. |
|
raise AssertionError("unreachable redirect loop state") |
|
except (httpx.TimeoutException, httpx.TransportError) as exc: |
|
if attempt + 1 < self._retries: |
|
delay = _retry_delay(None, attempt) |
|
self._debug( |
|
f"{type(exc).__name__}; retrying in {delay:.2f}s" |
|
) |
|
self._sleeper(delay) |
|
continue |
|
raise TransportError( |
|
f"request failed after {self._retries} attempts: {exc}", |
|
provider=provider, |
|
operation=operation, |
|
url=url, |
|
) from exc |
|
if response.status_code in RETRYABLE_STATUS_CODES and attempt + 1 < self._retries: |
|
delay = _retry_delay(response, attempt) |
|
self._debug(f"HTTP {response.status_code}; retrying in {delay:.2f}s") |
|
self._sleeper(delay) |
|
continue |
|
break |
|
response = cast(httpx.Response, last_response) |
|
self._debug( |
|
f"HTTP {response.status_code} {method.upper()} {sanitize_url(url)} " |
|
f"in {time.perf_counter() - started:.2f}s" |
|
) |
|
if response.status_code == 404: |
|
raise NotFoundError( |
|
"board, site, or posting was not found", |
|
provider=provider, |
|
operation=operation, |
|
url=url, |
|
) |
|
if response.status_code in {401, 403}: |
|
raise PermissionError( |
|
f"access denied (HTTP {response.status_code})", |
|
provider=provider, |
|
operation=operation, |
|
url=url, |
|
) |
|
if response.status_code == 429: |
|
raise RateLimitError( |
|
"rate limited after retry budget", |
|
provider=provider, |
|
operation=operation, |
|
url=url, |
|
) |
|
if response.status_code >= 400: |
|
raise TransportError( |
|
f"request failed (HTTP {response.status_code})", |
|
provider=provider, |
|
operation=operation, |
|
url=url, |
|
) |
|
if len(response.content) > MAX_RESPONSE_BYTES: |
|
raise TransportError( |
|
f"response exceeds {MAX_RESPONSE_BYTES} bytes", |
|
provider=provider, |
|
operation=operation, |
|
url=url, |
|
) |
|
try: |
|
return cast(JsonValue, response.json()) |
|
except (json.JSONDecodeError, UnicodeDecodeError, ValueError) as exc: |
|
raise InvalidJSONError( |
|
"response is not valid JSON", |
|
provider=provider, |
|
operation=operation, |
|
url=url, |
|
) from exc |
|
|
|
|
|
class Adapter(Protocol): |
|
"""Provider adapter contract.""" |
|
|
|
provider: Provider |
|
|
|
def list_jobs( |
|
self, |
|
target: Target, |
|
http: HttpClient, |
|
options: FetchOptions, |
|
) -> list[JsonObject]: ... |
|
|
|
def get_job( |
|
self, |
|
target: Target, |
|
http: HttpClient, |
|
options: FetchOptions, |
|
) -> JsonObject: ... |
|
|
|
def normalize(self, raw: JsonObject, target: Target) -> JobPosting: ... |
|
|
|
|
|
def _mapping(value: JsonValue | Any, *, provider: Provider, label: str) -> JsonObject: |
|
if not isinstance(value, dict): |
|
raise SchemaError(f"{label} must be an object", provider=provider) |
|
return cast(JsonObject, value) |
|
|
|
|
|
def _array(value: Any, *, provider: Provider, label: str) -> list[Any]: |
|
if not isinstance(value, list): |
|
raise SchemaError(f"{label} must be an array", provider=provider) |
|
return value |
|
|
|
|
|
def _string(value: Any, *, provider: Provider, label: str) -> str: |
|
if not isinstance(value, str) or not value.strip(): |
|
raise SchemaError(f"{label} must be a non-empty string", provider=provider) |
|
return value |
|
|
|
|
|
def _integer(value: Any, *, provider: Provider, label: str) -> int: |
|
if isinstance(value, bool) or not isinstance(value, int): |
|
raise SchemaError(f"{label} must be an integer", provider=provider) |
|
return value |
|
|
|
|
|
def _first_string(raw: Mapping[str, Any], *keys: str) -> str | None: |
|
for key in keys: |
|
value = raw.get(key) |
|
if isinstance(value, str) and value.strip(): |
|
return value.strip() |
|
return None |
|
|
|
|
|
def _join_location(value: Any) -> str | None: |
|
if isinstance(value, str): |
|
return value.strip() or None |
|
if isinstance(value, Mapping): |
|
direct = _first_string(value, "location_str", "name", "address") |
|
if direct: |
|
return direct |
|
parts = [ |
|
item.strip() |
|
for key in ("city", "region", "state", "country") |
|
if isinstance((item := value.get(key)), str) and item.strip() |
|
] |
|
return ", ".join(dict.fromkeys(parts)) or None |
|
return None |
|
|
|
|
|
def _remote_from(*values: str | None) -> bool | None: |
|
available = [value for value in values if value] |
|
if not available: |
|
return None |
|
return any("remote" in value.lower() for value in available) |
|
|
|
|
|
class GreenhouseAdapter: |
|
provider = Provider.GREENHOUSE |
|
|
|
def list_jobs( |
|
self, |
|
target: Target, |
|
http: HttpClient, |
|
options: FetchOptions, |
|
) -> list[JsonObject]: |
|
del options |
|
url = f"{target.origin}/v1/boards/{target.board}/jobs" |
|
payload = _mapping( |
|
http.request_json( |
|
"GET", |
|
url, |
|
provider=self.provider, |
|
operation=Operation.LIST, |
|
allowed_hosts=("boards-api.greenhouse.io",), |
|
params={"content": "true"}, |
|
), |
|
provider=self.provider, |
|
label="Greenhouse response", |
|
) |
|
jobs = _array(payload.get("jobs"), provider=self.provider, label="Greenhouse jobs") |
|
meta = _mapping(payload.get("meta"), provider=self.provider, label="Greenhouse meta") |
|
total = _integer(meta.get("total"), provider=self.provider, label="Greenhouse meta.total") |
|
if total < 0 or total != len(jobs): |
|
raise SchemaError("Greenhouse total does not match jobs", provider=self.provider) |
|
result: list[JsonObject] = [] |
|
for item in jobs: |
|
job = _mapping(item, provider=self.provider, label="Greenhouse job") |
|
if isinstance(job.get("id"), bool) or not isinstance(job.get("id"), int): |
|
raise SchemaError("Greenhouse job.id must be an integer", provider=self.provider) |
|
_string(job.get("title"), provider=self.provider, label="Greenhouse job.title") |
|
result.append(job) |
|
return result |
|
|
|
def get_job( |
|
self, |
|
target: Target, |
|
http: HttpClient, |
|
options: FetchOptions, |
|
) -> JsonObject: |
|
del options |
|
if target.job_id is None: |
|
raise InputError( |
|
"Greenhouse job URL must contain a job-post ID", |
|
provider=self.provider, |
|
) |
|
url = f"{target.origin}/v1/boards/{target.board}/jobs/{target.job_id}" |
|
job = _mapping( |
|
http.request_json( |
|
"GET", |
|
url, |
|
provider=self.provider, |
|
operation=Operation.GET, |
|
allowed_hosts=("boards-api.greenhouse.io",), |
|
params={"pay_transparency": "true"}, |
|
), |
|
provider=self.provider, |
|
label="Greenhouse job", |
|
) |
|
if str(job.get("id")) != target.job_id: |
|
raise SchemaError("Greenhouse job ID does not match request", provider=self.provider) |
|
_string(job.get("title"), provider=self.provider, label="Greenhouse job.title") |
|
return job |
|
|
|
def normalize(self, raw: JsonObject, target: Target) -> JobPosting: |
|
title = _string(raw.get("title"), provider=self.provider, label="Greenhouse job.title") |
|
job_id = str(raw.get("id", "")) |
|
content = _first_string(raw, "content") |
|
location = _join_location(raw.get("location")) |
|
department = None |
|
departments = raw.get("departments") |
|
if isinstance(departments, list) and departments: |
|
department = _join_location(departments[0]) |
|
job_url = _first_string(raw, "absolute_url") or ( |
|
f"https://job-boards.greenhouse.io/{target.board}/jobs/{job_id}" |
|
) |
|
return JobPosting( |
|
provider=self.provider, |
|
id=job_id, |
|
title=title, |
|
location=location, |
|
department=department, |
|
description_html=content, |
|
description_text=strip_html(content), |
|
job_url=job_url, |
|
apply_url=job_url, |
|
published_at=timestamp_to_iso(raw.get("updated_at")), |
|
remote=_remote_from(location), |
|
source=raw, |
|
) |
|
|
|
|
|
class LeverAdapter: |
|
provider = Provider.LEVER |
|
|
|
def list_jobs( |
|
self, |
|
target: Target, |
|
http: HttpClient, |
|
options: FetchOptions, |
|
) -> list[JsonObject]: |
|
del options |
|
if target.board is None: |
|
raise InputError("Lever site is missing", provider=self.provider) |
|
items: list[JsonObject] = [] |
|
seen: set[str] = set() |
|
skip = 0 |
|
for _page in range(MAX_PAGES): |
|
url = f"{target.origin}/v0/postings/{target.board}" |
|
payload = http.request_json( |
|
"GET", |
|
url, |
|
provider=self.provider, |
|
operation=Operation.LIST, |
|
allowed_hosts=(urlsplit(target.origin).hostname or "",), |
|
params={"mode": "json", "skip": skip, "limit": LEVER_PAGE_SIZE}, |
|
) |
|
page = _array(payload, provider=self.provider, label="Lever page") |
|
if not page: |
|
return items |
|
for item in page: |
|
job = _mapping(item, provider=self.provider, label="Lever posting") |
|
job_id = _string(job.get("id"), provider=self.provider, label="Lever posting.id") |
|
_string(job.get("text"), provider=self.provider, label="Lever posting.text") |
|
if job_id in seen: |
|
raise PaginationError( |
|
"duplicate Lever posting detected during pagination", |
|
provider=self.provider, |
|
operation=Operation.LIST, |
|
) |
|
seen.add(job_id) |
|
items.append(job) |
|
skip += len(page) |
|
raise PaginationError( |
|
"Lever pagination exceeded safety limit", |
|
provider=self.provider, |
|
operation=Operation.LIST, |
|
) |
|
|
|
def get_job( |
|
self, |
|
target: Target, |
|
http: HttpClient, |
|
options: FetchOptions, |
|
) -> JsonObject: |
|
del options |
|
if target.board is None or target.job_id is None: |
|
raise InputError("Lever job URL must contain a posting ID", provider=self.provider) |
|
url = f"{target.origin}/v0/postings/{target.board}/{target.job_id}" |
|
job = _mapping( |
|
http.request_json( |
|
"GET", |
|
url, |
|
provider=self.provider, |
|
operation=Operation.GET, |
|
allowed_hosts=(urlsplit(target.origin).hostname or "",), |
|
), |
|
provider=self.provider, |
|
label="Lever posting", |
|
) |
|
if job.get("id") != target.job_id: |
|
raise SchemaError("Lever posting ID does not match request", provider=self.provider) |
|
_string(job.get("text"), provider=self.provider, label="Lever posting.text") |
|
return job |
|
|
|
def normalize(self, raw: JsonObject, target: Target) -> JobPosting: |
|
del target |
|
categories = raw.get("categories") if isinstance(raw.get("categories"), Mapping) else {} |
|
categories = cast(Mapping[str, Any], categories) |
|
title = _string(raw.get("text"), provider=self.provider, label="Lever posting.text") |
|
job_id = _string(raw.get("id"), provider=self.provider, label="Lever posting.id") |
|
description_html = _first_string(raw, "description") |
|
description_text = _first_string(raw, "descriptionPlain") or strip_html(description_html) |
|
location = _first_string(categories, "location", "allLocations") |
|
return JobPosting( |
|
provider=self.provider, |
|
id=job_id, |
|
title=title, |
|
location=location, |
|
department=_first_string(categories, "department", "team"), |
|
employment_type=_first_string(categories, "commitment"), |
|
description_html=description_html, |
|
description_text=description_text, |
|
job_url=_string( |
|
raw.get("hostedUrl"), provider=self.provider, label="Lever posting.hostedUrl" |
|
), |
|
apply_url=_first_string(raw, "applyUrl"), |
|
published_at=timestamp_to_iso(raw.get("createdAt")), |
|
remote=_remote_from(location, _first_string(raw, "workplaceType")), |
|
source=raw, |
|
) |
|
|
|
|
|
class AshbyAdapter: |
|
provider = Provider.ASHBY |
|
|
|
def list_jobs( |
|
self, |
|
target: Target, |
|
http: HttpClient, |
|
options: FetchOptions, |
|
) -> list[JsonObject]: |
|
if target.board is None: |
|
raise InputError("Ashby board name is missing", provider=self.provider) |
|
url = f"{target.origin}/posting-api/job-board/{target.board}" |
|
payload = _mapping( |
|
http.request_json( |
|
"GET", |
|
url, |
|
provider=self.provider, |
|
operation=Operation.LIST, |
|
allowed_hosts=("api.ashbyhq.com",), |
|
params={"includeCompensation": "true"}, |
|
), |
|
provider=self.provider, |
|
label="Ashby response", |
|
) |
|
_string(payload.get("apiVersion"), provider=self.provider, label="Ashby apiVersion") |
|
jobs = _array(payload.get("jobs"), provider=self.provider, label="Ashby jobs") |
|
result: list[JsonObject] = [] |
|
for item in jobs: |
|
job = _mapping(item, provider=self.provider, label="Ashby job") |
|
_string(job.get("title"), provider=self.provider, label="Ashby job.title") |
|
_string(job.get("jobUrl"), provider=self.provider, label="Ashby job.jobUrl") |
|
if not options.include_unlisted and job.get("isListed") is False: |
|
continue |
|
result.append(job) |
|
return result |
|
|
|
def get_job( |
|
self, |
|
target: Target, |
|
http: HttpClient, |
|
options: FetchOptions, |
|
) -> JsonObject: |
|
all_options = options.model_copy(update={"include_unlisted": True}) |
|
jobs = self.list_jobs(target, http, all_options) |
|
wanted = canonicalize_url(target.original_url) |
|
matches = [ |
|
job |
|
for job in jobs |
|
if any( |
|
isinstance(candidate, str) and canonicalize_url(candidate) == wanted |
|
for candidate in (job.get("jobUrl"), job.get("applyUrl")) |
|
) |
|
] |
|
if not matches: |
|
raise NotFoundError( |
|
"no Ashby job exactly matched that job or application URL", |
|
provider=self.provider, |
|
operation=Operation.GET, |
|
url=target.original_url, |
|
) |
|
if len(matches) > 1: |
|
raise AmbiguousMatchError( |
|
"multiple Ashby jobs matched that URL", |
|
provider=self.provider, |
|
operation=Operation.GET, |
|
url=target.original_url, |
|
) |
|
return matches[0] |
|
|
|
def normalize(self, raw: JsonObject, target: Target) -> JobPosting: |
|
del target |
|
title = _string(raw.get("title"), provider=self.provider, label="Ashby job.title") |
|
job_url = _string(raw.get("jobUrl"), provider=self.provider, label="Ashby job.jobUrl") |
|
job_id = _first_string(raw, "id", "jobPostingId") or _segments(urlsplit(job_url).path)[-1] |
|
location = _first_string(raw, "location") |
|
description_html = _first_string(raw, "descriptionHtml") |
|
return JobPosting( |
|
provider=self.provider, |
|
id=job_id, |
|
title=title, |
|
location=location, |
|
department=_first_string(raw, "department", "team"), |
|
employment_type=_first_string(raw, "employmentType"), |
|
description_html=description_html, |
|
description_text=_first_string(raw, "descriptionPlain") or strip_html(description_html), |
|
job_url=job_url, |
|
apply_url=_first_string(raw, "applyUrl"), |
|
published_at=timestamp_to_iso(raw.get("publishedAt")), |
|
remote=( |
|
raw.get("isRemote") |
|
if isinstance(raw.get("isRemote"), bool) |
|
else _remote_from(location) |
|
), |
|
source=raw, |
|
) |
|
|
|
|
|
class WorkableAdapter: |
|
provider = Provider.WORKABLE |
|
|
|
def list_jobs( |
|
self, |
|
target: Target, |
|
http: HttpClient, |
|
options: FetchOptions, |
|
) -> list[JsonObject]: |
|
del options |
|
if target.board is None: |
|
raise InputError("Workable account is missing", provider=self.provider) |
|
url = f"{target.origin}/api/accounts/{target.board}" |
|
payload = _mapping( |
|
http.request_json( |
|
"GET", |
|
url, |
|
provider=self.provider, |
|
operation=Operation.LIST, |
|
allowed_hosts=("www.workable.com",), |
|
params={"details": "true"}, |
|
), |
|
provider=self.provider, |
|
label="Workable response", |
|
) |
|
jobs = _array(payload.get("jobs"), provider=self.provider, label="Workable jobs") |
|
result: list[JsonObject] = [] |
|
for item in jobs: |
|
job = _mapping(item, provider=self.provider, label="Workable job") |
|
_string(job.get("shortcode"), provider=self.provider, label="Workable job.shortcode") |
|
_string(job.get("title"), provider=self.provider, label="Workable job.title") |
|
result.append(job) |
|
return result |
|
|
|
def get_job( |
|
self, |
|
target: Target, |
|
http: HttpClient, |
|
options: FetchOptions, |
|
) -> JsonObject: |
|
jobs = self.list_jobs(target, http, options) |
|
wanted_url = canonicalize_url(target.original_url) |
|
matches: list[JsonObject] = [] |
|
for job in jobs: |
|
shortcode = str(job.get("shortcode", "")) |
|
url_match = any( |
|
isinstance(candidate, str) and canonicalize_url(candidate) == wanted_url |
|
for candidate in ( |
|
job.get("url"), |
|
job.get("application_url"), |
|
job.get("shortlink"), |
|
) |
|
) |
|
if (target.job_id and shortcode == target.job_id) or url_match: |
|
matches.append(job) |
|
if not matches: |
|
raise NotFoundError( |
|
"no Workable job exactly matched that shortcode or URL", |
|
provider=self.provider, |
|
operation=Operation.GET, |
|
url=target.original_url, |
|
) |
|
if len(matches) > 1: |
|
raise AmbiguousMatchError( |
|
"multiple Workable jobs matched that shortcode or URL", |
|
provider=self.provider, |
|
operation=Operation.GET, |
|
url=target.original_url, |
|
) |
|
return matches[0] |
|
|
|
def normalize(self, raw: JsonObject, target: Target) -> JobPosting: |
|
shortcode = _string( |
|
raw.get("shortcode"), provider=self.provider, label="Workable job.shortcode" |
|
) |
|
title = _string(raw.get("title"), provider=self.provider, label="Workable job.title") |
|
location = _join_location(raw.get("location")) |
|
description_html = _first_string(raw, "description", "description_html") |
|
job_url = _first_string(raw, "url", "shortlink") or ( |
|
f"https://apply.workable.com/{target.board}/j/{shortcode}/" |
|
) |
|
return JobPosting( |
|
provider=self.provider, |
|
id=shortcode, |
|
title=title, |
|
location=location, |
|
department=_first_string(raw, "department"), |
|
employment_type=_first_string(raw, "employment_type", "type"), |
|
description_html=description_html, |
|
description_text=( |
|
_first_string(raw, "description_plain") or strip_html(description_html) |
|
), |
|
job_url=job_url, |
|
apply_url=_first_string(raw, "application_url", "shortlink"), |
|
published_at=timestamp_to_iso(raw.get("created_at")), |
|
remote=_remote_from(location, _first_string(raw, "workplace")), |
|
source=raw, |
|
) |
|
|
|
|
|
class BambooHRAdapter: |
|
provider = Provider.BAMBOOHR |
|
|
|
def list_jobs( |
|
self, |
|
target: Target, |
|
http: HttpClient, |
|
options: FetchOptions, |
|
) -> list[JsonObject]: |
|
del options |
|
url = f"{target.origin}/careers/list" |
|
payload = _mapping( |
|
http.request_json( |
|
"GET", |
|
url, |
|
provider=self.provider, |
|
operation=Operation.LIST, |
|
allowed_hosts=(urlsplit(target.origin).hostname or "",), |
|
), |
|
provider=self.provider, |
|
label="BambooHR response", |
|
) |
|
jobs = _array(payload.get("result"), provider=self.provider, label="BambooHR result") |
|
meta = payload.get("meta") |
|
if isinstance(meta, Mapping) and "totalCount" in meta: |
|
total = _integer( |
|
meta.get("totalCount"), provider=self.provider, label="BambooHR meta.totalCount" |
|
) |
|
if total != len(jobs): |
|
raise SchemaError("BambooHR total does not match jobs", provider=self.provider) |
|
result: list[JsonObject] = [] |
|
for item in jobs: |
|
job = _mapping(item, provider=self.provider, label="BambooHR job") |
|
if isinstance(job.get("id"), bool) or not isinstance(job.get("id"), int | str): |
|
raise SchemaError( |
|
"BambooHR job.id must be a string or integer", |
|
provider=self.provider, |
|
) |
|
result.append(job) |
|
return result |
|
|
|
def get_job( |
|
self, |
|
target: Target, |
|
http: HttpClient, |
|
options: FetchOptions, |
|
) -> JsonObject: |
|
del options |
|
if target.job_id is None: |
|
raise InputError( |
|
"BambooHR job URL must contain a numeric job ID", |
|
provider=self.provider, |
|
) |
|
url = f"{target.origin}/careers/{target.job_id}/detail" |
|
payload = _mapping( |
|
http.request_json( |
|
"GET", |
|
url, |
|
provider=self.provider, |
|
operation=Operation.GET, |
|
allowed_hosts=(urlsplit(target.origin).hostname or "",), |
|
), |
|
provider=self.provider, |
|
label="BambooHR response", |
|
) |
|
result = _mapping( |
|
payload.get("result"), provider=self.provider, label="BambooHR result" |
|
) |
|
job = _mapping( |
|
result.get("jobOpening"), provider=self.provider, label="BambooHR jobOpening" |
|
) |
|
if str(job.get("id")) != target.job_id: |
|
raise SchemaError("BambooHR job ID does not match request", provider=self.provider) |
|
return job |
|
|
|
def normalize(self, raw: JsonObject, target: Target) -> JobPosting: |
|
job_id = str(raw.get("id", "")) |
|
if not job_id: |
|
raise SchemaError("BambooHR job.id is missing", provider=self.provider) |
|
title = _first_string(raw, "jobOpeningName", "jobTitle", "title", "name") |
|
if title is None: |
|
raise SchemaError("BambooHR job title is missing", provider=self.provider) |
|
location = _join_location(raw.get("location")) or _first_string(raw, "locationName") |
|
description_html = _first_string(raw, "description", "jobDescription") |
|
job_url = _first_string(raw, "jobUrl", "url") or f"{target.origin}/careers/{job_id}" |
|
return JobPosting( |
|
provider=self.provider, |
|
id=job_id, |
|
title=title, |
|
location=location, |
|
department=_first_string(raw, "department", "departmentName"), |
|
employment_type=_first_string(raw, "employmentStatus", "employmentType"), |
|
description_html=description_html, |
|
description_text=strip_html(description_html), |
|
job_url=job_url, |
|
apply_url=_first_string(raw, "applyUrl") or job_url, |
|
published_at=timestamp_to_iso(raw.get("datePosted")), |
|
remote=_remote_from(location), |
|
source=raw, |
|
) |
|
|
|
|
|
class WorkdayAdapter: |
|
provider = Provider.WORKDAY |
|
|
|
def _base(self, target: Target) -> str: |
|
if target.tenant is None or target.site is None: |
|
raise InputError("Workday tenant or site is missing", provider=self.provider) |
|
return f"{target.origin}/wday/cxs/{target.tenant}/{target.site}" |
|
|
|
def list_jobs( |
|
self, |
|
target: Target, |
|
http: HttpClient, |
|
options: FetchOptions, |
|
) -> list[JsonObject]: |
|
del options |
|
url = f"{self._base(target)}/jobs" |
|
allowed_host = urlsplit(target.origin).hostname or "" |
|
items: list[JsonObject] = [] |
|
seen: set[str] = set() |
|
expected_total: int | None = None |
|
offset = 0 |
|
for page_index in range(MAX_PAGES): |
|
payload = _mapping( |
|
http.request_json( |
|
"POST", |
|
url, |
|
provider=self.provider, |
|
operation=Operation.LIST, |
|
allowed_hosts=(allowed_host,), |
|
json_body={ |
|
"appliedFacets": {}, |
|
"limit": WORKDAY_PAGE_SIZE, |
|
"offset": offset, |
|
"searchText": "", |
|
}, |
|
), |
|
provider=self.provider, |
|
label="Workday response", |
|
) |
|
page_total = _integer( |
|
payload.get("total"), provider=self.provider, label="Workday total" |
|
) |
|
if page_total < 0: |
|
raise SchemaError("Workday total must be non-negative", provider=self.provider) |
|
if expected_total is None: |
|
expected_total = page_total |
|
elif page_total not in {0, expected_total}: |
|
raise PaginationError( |
|
"Workday total changed during pagination", |
|
provider=self.provider, |
|
operation=Operation.LIST, |
|
) |
|
page = _array( |
|
payload.get("jobPostings"), provider=self.provider, label="Workday jobPostings" |
|
) |
|
if expected_total == 0: |
|
if page: |
|
raise PaginationError( |
|
"Workday returned postings with total=0", |
|
provider=self.provider, |
|
operation=Operation.LIST, |
|
) |
|
return [] |
|
if not page: |
|
raise PaginationError( |
|
"Workday pagination ended before the advertised total", |
|
provider=self.provider, |
|
operation=Operation.LIST, |
|
) |
|
for item in page: |
|
job = _mapping(item, provider=self.provider, label="Workday posting") |
|
external_path = _string( |
|
job.get("externalPath"), |
|
provider=self.provider, |
|
label="Workday posting.externalPath", |
|
) |
|
if external_path in seen: |
|
raise PaginationError( |
|
"duplicate Workday externalPath detected", |
|
provider=self.provider, |
|
operation=Operation.LIST, |
|
) |
|
seen.add(external_path) |
|
items.append(job) |
|
offset += len(page) |
|
if len(items) == expected_total: |
|
return items |
|
if len(items) > expected_total: |
|
raise PaginationError( |
|
"Workday returned more postings than advertised", |
|
provider=self.provider, |
|
operation=Operation.LIST, |
|
) |
|
if page_index + 1 >= MAX_PAGES: |
|
break |
|
raise PaginationError( |
|
"Workday pagination exceeded safety limit", |
|
provider=self.provider, |
|
operation=Operation.LIST, |
|
) |
|
|
|
def get_job( |
|
self, |
|
target: Target, |
|
http: HttpClient, |
|
options: FetchOptions, |
|
) -> JsonObject: |
|
del options |
|
if target.external_path is None: |
|
raise InputError( |
|
"Workday job URL must include the /job/... external path", |
|
provider=self.provider, |
|
) |
|
url = f"{self._base(target)}{target.external_path}" |
|
payload = _mapping( |
|
http.request_json( |
|
"GET", |
|
url, |
|
provider=self.provider, |
|
operation=Operation.GET, |
|
allowed_hosts=(urlsplit(target.origin).hostname or "",), |
|
), |
|
provider=self.provider, |
|
label="Workday response", |
|
) |
|
return _mapping( |
|
payload.get("jobPostingInfo"), |
|
provider=self.provider, |
|
label="Workday jobPostingInfo", |
|
) |
|
|
|
def normalize(self, raw: JsonObject, target: Target) -> JobPosting: |
|
title = _first_string(raw, "title") |
|
if title is None: |
|
raise SchemaError("Workday job title is missing", provider=self.provider) |
|
external_path = _first_string(raw, "externalPath") or target.external_path |
|
job_id = _first_string(raw, "jobReqId", "id") |
|
if job_id is None and external_path: |
|
job_id = _segments(external_path)[-1] |
|
if job_id is None: |
|
raise SchemaError("Workday job identifier is missing", provider=self.provider) |
|
location = _first_string(raw, "location", "locationName", "locationsText") |
|
description_html = _first_string(raw, "jobDescription", "description") |
|
job_url = _first_string(raw, "externalUrl") |
|
if job_url is None and external_path: |
|
job_url = f"{target.origin}{external_path}" |
|
if job_url is None: |
|
raise SchemaError("Workday job URL is missing", provider=self.provider) |
|
return JobPosting( |
|
provider=self.provider, |
|
id=job_id, |
|
title=title, |
|
location=location, |
|
department=_first_string(raw, "jobFamily", "department"), |
|
employment_type=_first_string(raw, "timeType", "workerType"), |
|
description_html=description_html, |
|
description_text=strip_html(description_html), |
|
job_url=job_url, |
|
apply_url=_first_string(raw, "externalApplyUrl") or job_url, |
|
published_at=timestamp_to_iso(raw.get("startDate") or raw.get("postedOn")), |
|
remote=_remote_from(location, _first_string(raw, "remoteType")), |
|
source=raw, |
|
) |
|
|
|
|
|
ADAPTERS: Final[dict[Provider, Adapter]] = { |
|
Provider.GREENHOUSE: GreenhouseAdapter(), |
|
Provider.LEVER: LeverAdapter(), |
|
Provider.ASHBY: AshbyAdapter(), |
|
Provider.WORKABLE: WorkableAdapter(), |
|
Provider.BAMBOOHR: BambooHRAdapter(), |
|
Provider.WORKDAY: WorkdayAdapter(), |
|
} |
|
|
|
|
|
def operation_support(provider: Provider, operation: Operation) -> SupportTier: |
|
spec = PROVIDER_SPECS[provider] |
|
return spec.list_support if operation is Operation.LIST else spec.get_support |
|
|
|
|
|
def inspect_url(value: str, override: Provider | None = None) -> JsonObject: |
|
"""Return URL parsing and support metadata without making a network request.""" |
|
target = parse_target(value, override) |
|
data = target.model_dump(mode="json") |
|
data["support"] = operation_support(target.provider, target.operation).value |
|
return data |
|
|
|
|
|
def inspect_resolution(resolution: DiscoveryResult) -> JsonObject: |
|
"""Return discovery provenance and provider support metadata.""" |
|
data = resolution.model_dump(mode="json") |
|
target = resolution.target |
|
data["support"] = operation_support(target.provider, target.operation).value |
|
return data |
|
|
|
|
|
def _fetch_target( |
|
target: Target, |
|
*, |
|
operation: Operation | None = None, |
|
raw: bool = False, |
|
include_unlisted: bool = False, |
|
documented_only: bool = False, |
|
http: HttpClient | None = None, |
|
event_sink: EventSink | None = None, |
|
) -> list[JsonObject] | JsonObject | list[JobPosting] | JobPosting: |
|
selected_operation = operation or target.operation |
|
if selected_operation is Operation.GET and target.operation is Operation.LIST: |
|
raise InputError( |
|
"discovery found a board but not an individual posting reference; use list or " |
|
"provide the direct posting URL", |
|
provider=target.provider, |
|
operation=Operation.GET, |
|
url=target.original_url, |
|
) |
|
if selected_operation is Operation.LIST and target.operation is Operation.GET: |
|
target = _list_target(target) |
|
support = operation_support(target.provider, selected_operation) |
|
if documented_only and support is SupportTier.UNDOCUMENTED_PUBLIC: |
|
raise UnsupportedInterfaceError( |
|
"provider interface is undocumented; remove --documented-only to use it", |
|
provider=target.provider, |
|
operation=selected_operation, |
|
url=target.original_url, |
|
) |
|
adapter = ADAPTERS[target.provider] |
|
options = FetchOptions( |
|
include_unlisted=include_unlisted, |
|
documented_only=documented_only, |
|
) |
|
owned = http is None |
|
client = http or (HttpClient(event_sink=event_sink) if event_sink else HttpClient()) |
|
try: |
|
if selected_operation is Operation.LIST: |
|
source = adapter.list_jobs(target, client, options) |
|
if raw: |
|
return source |
|
return [adapter.normalize(item, target) for item in source] |
|
source_job = adapter.get_job(target, client, options) |
|
if raw: |
|
return source_job |
|
return adapter.normalize(source_job, target) |
|
finally: |
|
if owned: |
|
client.close() |
|
|
|
|
|
def fetch_jobs( |
|
value: str, |
|
*, |
|
operation: Operation | None = None, |
|
provider: Provider | None = None, |
|
raw: bool = False, |
|
include_unlisted: bool = False, |
|
documented_only: bool = False, |
|
http: HttpClient | None = None, |
|
discover: bool = True, |
|
probe: bool = True, |
|
discovery: DiscoveryClient | None = None, |
|
event_sink: EventSink | None = None, |
|
) -> list[JsonObject] | JsonObject | list[JobPosting] | JobPosting: |
|
"""Fetch a list or one job from a URL.""" |
|
resolution = resolve_target( |
|
value, |
|
provider, |
|
discover=discover, |
|
probe=probe, |
|
discovery=discovery, |
|
event_sink=event_sink, |
|
) |
|
return _fetch_target( |
|
resolution.target, |
|
operation=operation, |
|
raw=raw, |
|
include_unlisted=include_unlisted, |
|
documented_only=documented_only, |
|
http=http, |
|
event_sink=event_sink, |
|
) |
|
|
|
|
|
def _jsonable(data: Any) -> JsonValue: |
|
if isinstance(data, BaseModel): |
|
return cast(JsonValue, data.model_dump(mode="json")) |
|
if isinstance(data, list): |
|
return cast(JsonValue, [_jsonable(item) for item in data]) |
|
return cast(JsonValue, data) |
|
|
|
|
|
def render_json(data: Any) -> str: |
|
return json.dumps(_jsonable(data), ensure_ascii=False, indent=2, sort_keys=False) |
|
|
|
|
|
def render_jsonl(data: Any) -> str: |
|
items = data if isinstance(data, list) else [data] |
|
return "\n".join( |
|
json.dumps(_jsonable(item), ensure_ascii=False, separators=(",", ":")) for item in items |
|
) |
|
|
|
|
|
def _truncate(value: Any, width: int) -> str: |
|
text = "" if value is None else str(value).replace("\n", " ") |
|
return text if len(text) <= width else f"{text[: width - 1]}…" |
|
|
|
|
|
def _normalized_mapping(item: Any) -> JsonObject: |
|
if isinstance(item, JobPosting): |
|
return item.model_dump(mode="json") |
|
if isinstance(item, Mapping) and {"title", "job_url"}.issubset(item): |
|
return dict(item) |
|
raise InputError("human-readable output requires normalized job records") |
|
|
|
|
|
def _humanize(value: Any) -> str: |
|
if value is None: |
|
return "" |
|
text = str(value).replace("_", " ").strip() |
|
text = re.sub(r"(?<=[a-z])(?=[A-Z])", " ", text) |
|
return text[:1].upper() + text[1:] if text else "" |
|
|
|
|
|
def _pretty_date(value: Any) -> str: |
|
if not isinstance(value, str) or not value.strip(): |
|
return "" |
|
candidate = value.strip().replace("Z", "+00:00") |
|
try: |
|
parsed = datetime.fromisoformat(candidate) |
|
except ValueError: |
|
return value.strip() |
|
return parsed.strftime("%b %d, %Y").replace(" 0", " ") |
|
|
|
|
|
def _compensation_summary(job: Mapping[str, Any]) -> str | None: |
|
source = job.get("source") |
|
if not isinstance(source, Mapping): |
|
return None |
|
compensation = source.get("compensation") |
|
if isinstance(compensation, Mapping): |
|
for key in ("compensationTierSummary", "scrapeableCompensationSalarySummary", "summary"): |
|
value = compensation.get(key) |
|
if isinstance(value, str) and value.strip(): |
|
return value.strip() |
|
for key in ("salary", "salaryRange", "salary_range", "compensation"): |
|
value = source.get(key) |
|
if isinstance(value, str) and value.strip(): |
|
return value.strip() |
|
if isinstance(value, Mapping): |
|
minimum = value.get("min") or value.get("minimum") or value.get("minValue") |
|
maximum = value.get("max") or value.get("maximum") or value.get("maxValue") |
|
currency = value.get("currency") or value.get("currencyCode") or "" |
|
if isinstance(minimum, int | float) or isinstance(maximum, int | float): |
|
low = f"{minimum:,.0f}" if isinstance(minimum, int | float) else "?" |
|
high = f"{maximum:,.0f}" if isinstance(maximum, int | float) else "?" |
|
prefix = f"{currency} " if currency else "" |
|
return f"{prefix}{low} – {high}" |
|
return None |
|
|
|
|
|
def _workplace_summary(job: Mapping[str, Any]) -> str: |
|
remote = job.get("remote") |
|
if remote is True: |
|
return "Remote" |
|
source = job.get("source") |
|
if isinstance(source, Mapping): |
|
for key in ("workplaceType", "workplace_type"): |
|
value = source.get(key) |
|
if isinstance(value, str) and value.strip(): |
|
humanized = _humanize(value) |
|
compact = re.sub(r"[^a-z]", "", value.lower()) |
|
return { |
|
"onsite": "On-site", |
|
"remote": "Remote", |
|
"hybrid": "Hybrid", |
|
}.get(compact, humanized) |
|
return "On-site" if remote is False else "" |
|
|
|
|
|
def _description_renderable(value: Any) -> Text: |
|
text = Text() |
|
if not isinstance(value, str) or not value.strip(): |
|
text.append("No description was provided.", style="dim italic") |
|
return text |
|
previous_blank = True |
|
for raw_line in value.strip().splitlines(): |
|
line = raw_line.strip() |
|
if not line: |
|
if not previous_blank: |
|
text.append("\n") |
|
previous_blank = True |
|
continue |
|
heading = ( |
|
len(line) <= 90 |
|
and len(line.split()) <= 12 |
|
and line.upper() == line |
|
and any(character.isalpha() for character in line) |
|
) |
|
if heading: |
|
if len(text): |
|
text.append("\n") |
|
text.append(_humanize(line.lower()), style="bold cyan") |
|
text.append("\n") |
|
elif line.startswith(("- ", "• ", "* ")): |
|
text.append(" • ", style="cyan") |
|
text.append(line[2:].strip()) |
|
text.append("\n") |
|
else: |
|
text.append(line) |
|
text.append("\n") |
|
previous_blank = False |
|
return text |
|
|
|
|
|
def _pretty_job(job: Mapping[str, Any]) -> RenderableType: |
|
title = str(job.get("title") or "Untitled posting") |
|
provider = _humanize(job.get("provider")) |
|
details = Table.grid(padding=(0, 2)) |
|
details.add_column(style="bold dim", no_wrap=True) |
|
details.add_column(ratio=1, overflow="fold") |
|
|
|
def add(label: str, value: Any) -> None: |
|
if value is not None and str(value).strip(): |
|
details.add_row(label, Text(str(value).strip())) |
|
|
|
add("Provider", provider) |
|
add("Company", job.get("company")) |
|
add("Location", job.get("location")) |
|
add("Workplace", _workplace_summary(job)) |
|
add("Department", job.get("department")) |
|
add("Type", _humanize(job.get("employment_type"))) |
|
add("Compensation", _compensation_summary(job)) |
|
add("Published", _pretty_date(job.get("published_at"))) |
|
|
|
job_url = job.get("job_url") |
|
if isinstance(job_url, str) and job_url: |
|
details.add_row("Job", Text(job_url, style=f"cyan underline link {job_url}")) |
|
apply_url = job.get("apply_url") |
|
if isinstance(apply_url, str) and apply_url and apply_url != job_url: |
|
details.add_row("Apply", Text(apply_url, style=f"green underline link {apply_url}")) |
|
|
|
summary = Panel( |
|
details, |
|
title=Text(title, style="bold"), |
|
subtitle=Text(str(job.get("id") or ""), style="dim"), |
|
border_style="cyan", |
|
padding=(1, 2), |
|
) |
|
description = _description_renderable(job.get("description_text")) |
|
return Group(summary, Rule("Description", style="dim"), description) |
|
|
|
|
|
def _pretty_job_list(jobs: Sequence[Mapping[str, Any]]) -> RenderableType: |
|
if not jobs: |
|
return Panel("No public postings found.", title="ats-jobs", border_style="yellow") |
|
providers = sorted({_humanize(job.get("provider")) for job in jobs if job.get("provider")}) |
|
subtitle = f" · {', '.join(providers)}" if providers else "" |
|
table = Table( |
|
title=f"{len(jobs)} public posting{'s' if len(jobs) != 1 else ''}{subtitle}", |
|
box=box.SIMPLE_HEAVY, |
|
expand=True, |
|
header_style="bold cyan", |
|
show_lines=False, |
|
pad_edge=False, |
|
) |
|
table.add_column("#", justify="right", style="dim", no_wrap=True, width=4) |
|
table.add_column("Title", ratio=3, overflow="fold") |
|
table.add_column("Location", ratio=2, overflow="fold") |
|
table.add_column("Team", ratio=2, overflow="fold") |
|
table.add_column("Type", ratio=1, overflow="fold") |
|
table.add_column("Posted", no_wrap=True) |
|
table.add_column("Link", no_wrap=True) |
|
for index, job in enumerate(jobs, start=1): |
|
job_url = str(job.get("job_url") or "") |
|
link = Text("open", style=f"cyan underline link {job_url}") if job_url else Text("-") |
|
table.add_row( |
|
str(index), |
|
str(job.get("title") or ""), |
|
str(job.get("location") or ""), |
|
str(job.get("department") or ""), |
|
_humanize(job.get("employment_type")), |
|
_pretty_date(job.get("published_at")), |
|
link, |
|
) |
|
return table |
|
|
|
|
|
def build_pretty(data: Any) -> RenderableType: |
|
"""Build a semantic Rich view without dumping duplicated raw provider payloads.""" |
|
if isinstance(data, list): |
|
return _pretty_job_list([_normalized_mapping(item) for item in data]) |
|
return _pretty_job(_normalized_mapping(data)) |
|
|
|
|
|
def render_pretty(data: Any, *, width: int = 100) -> str: |
|
"""Render the semantic view as deterministic, color-free text for tests or files.""" |
|
buffer = io.StringIO() |
|
console = Console( |
|
file=buffer, |
|
force_terminal=False, |
|
color_system=None, |
|
width=max(width, 40), |
|
highlight=False, |
|
) |
|
console.print(build_pretty(data)) |
|
return buffer.getvalue().rstrip() |
|
|
|
|
|
def render_table(data: Any) -> str: |
|
"""Render normalized jobs as a compact dependency-free table.""" |
|
items = data if isinstance(data, list) else [data] |
|
rows: list[dict[str, Any]] = [] |
|
for item in items: |
|
rows.append(_normalized_mapping(item)) |
|
columns = (("TITLE", "title", 42), ("LOCATION", "location", 24), ("URL", "job_url", 60)) |
|
widths = [ |
|
min(limit, max([len(header), *(len(str(row.get(key) or "")) for row in rows)])) |
|
for header, key, limit in columns |
|
] |
|
header = " ".join( |
|
label.ljust(width) |
|
for (label, _key, _limit), width in zip(columns, widths, strict=True) |
|
) |
|
separator = " ".join("-" * width for width in widths) |
|
rendered = [header, separator] |
|
for row in rows: |
|
rendered.append( |
|
" ".join( |
|
_truncate(row.get(key), width).ljust(width) |
|
for (_label, key, _limit), width in zip(columns, widths, strict=True) |
|
) |
|
) |
|
return "\n".join(rendered) |
|
|
|
|
|
def render_output(data: Any, output_format: OutputFormat) -> str: |
|
if output_format is OutputFormat.AUTO: |
|
raise InputError("auto output must be resolved before rendering") |
|
if output_format is OutputFormat.PRETTY: |
|
return render_pretty(data) |
|
if output_format is OutputFormat.JSON: |
|
return render_json(data) |
|
if output_format is OutputFormat.JSONL: |
|
return render_jsonl(data) |
|
return render_table(data) |
|
|
|
|
|
def resolve_output_format( |
|
requested: OutputFormat, |
|
*, |
|
raw: bool, |
|
output: Path | None, |
|
stdout_is_tty: bool | None = None, |
|
) -> OutputFormat: |
|
"""Use semantic pretty output interactively and JSON for pipes/files.""" |
|
if requested is not OutputFormat.AUTO: |
|
return requested |
|
interactive = sys.stdout.isatty() if stdout_is_tty is None else stdout_is_tty |
|
if raw or output is not None or not interactive: |
|
return OutputFormat.JSON |
|
return OutputFormat.PRETTY |
|
|
|
|
|
def write_output(text: str, output: Path | None = None) -> None: |
|
"""Write output atomically to a file or directly to stdout.""" |
|
if output is None: |
|
typer.echo(text) |
|
return |
|
destination = output.expanduser().resolve() |
|
destination.parent.mkdir(parents=True, exist_ok=True) |
|
temporary: Path | None = None |
|
try: |
|
with tempfile.NamedTemporaryFile( |
|
mode="w", |
|
encoding="utf-8", |
|
dir=destination.parent, |
|
prefix=f".{destination.name}.", |
|
delete=False, |
|
) as handle: |
|
handle.write(text) |
|
handle.write("\n") |
|
temporary = Path(handle.name) |
|
temporary.replace(destination) |
|
except OSError as exc: |
|
if temporary is not None: |
|
temporary.unlink(missing_ok=True) |
|
raise TransportError(f"could not write output file: {exc}") from exc |
|
|
|
|
|
def emit_output( |
|
data: Any, |
|
output_format: OutputFormat, |
|
*, |
|
output: Path | None = None, |
|
no_color: bool = False, |
|
pager: bool = False, |
|
width: int | None = None, |
|
) -> None: |
|
"""Emit machine formats plainly or a semantic Rich view interactively.""" |
|
if output_format is not OutputFormat.PRETTY: |
|
write_output(render_output(data, output_format), output) |
|
return |
|
if output is not None: |
|
write_output(render_pretty(data, width=width or 100), output) |
|
return |
|
console = Console( |
|
no_color=no_color, |
|
width=width, |
|
highlight=False, |
|
soft_wrap=False, |
|
) |
|
if pager: |
|
with console.pager(styles=not no_color): |
|
console.print(build_pretty(data)) |
|
else: |
|
console.print(build_pretty(data)) |
|
|
|
|
|
APP_HELP: Final = ( |
|
"[bold]Fetch public job postings from one direct ATS or company careers URL.[/bold]\n\n" |
|
"Native ATS links resolve locally. Custom careers pages are resolved through bounded " |
|
"redirect, canonical-link, embed-link, and board-slug discovery. Interactive terminals " |
|
"get a semantic pretty view; pipes and files get normalized JSON." |
|
) |
|
APP_EPILOG: Final = """\ |
|
[bold]Examples[/bold] |
|
|
|
[cyan]ats-jobs https://acme.com/careers[/cyan] |
|
|
|
[cyan]ats-jobs https://jobs.lever.co/acme[/cyan] |
|
|
|
[cyan]ats-jobs https://jobs.lever.co/acme/POSTING_ID[/cyan] |
|
|
|
[cyan]ats-jobs JOB_URL --pretty --pager[/cyan] |
|
|
|
[cyan]ats-jobs list https://jobs.ashbyhq.com/acme --format jsonl[/cyan] |
|
|
|
[cyan]ats-jobs providers[/cyan] |
|
|
|
Use [cyan]-v[/cyan] for resolution/fetch summaries and [cyan]-vv[/cyan] for HTTP details. |
|
""" |
|
HELP_CONTEXT: Final[dict[str, Any]] = { |
|
"help_option_names": ["-h", "--help"], |
|
"max_content_width": 100, |
|
} |
|
|
|
app = typer.Typer( |
|
name="ats-jobs", |
|
help=APP_HELP, |
|
epilog=APP_EPILOG, |
|
add_completion=False, |
|
no_args_is_help=True, |
|
rich_markup_mode="rich", |
|
suggest_commands=True, |
|
context_settings=HELP_CONTEXT, |
|
pretty_exceptions_enable=False, |
|
) |
|
|
|
|
|
def _version_callback(value: bool) -> None: |
|
if value: |
|
typer.echo(f"ats-jobs {__version__}") |
|
raise typer.Exit() |
|
|
|
|
|
@app.callback() |
|
def app_callback( |
|
version: Annotated[ |
|
bool, |
|
typer.Option( |
|
"--version", |
|
callback=_version_callback, |
|
is_eager=True, |
|
help="Show the version and exit.", |
|
rich_help_panel="General", |
|
), |
|
] = False, |
|
) -> None: |
|
del version |
|
|
|
|
|
UrlArgument = Annotated[ |
|
str, |
|
typer.Argument( |
|
metavar="URL", |
|
help="Public careers-board or individual-job URL.", |
|
), |
|
] |
|
ProviderOption = Annotated[ |
|
Provider | None, |
|
typer.Option( |
|
"--provider", |
|
"-p", |
|
metavar="PROVIDER", |
|
case_sensitive=False, |
|
help="Override automatic provider detection.", |
|
rich_help_panel="Selection", |
|
), |
|
] |
|
FormatOption = Annotated[ |
|
OutputFormat, |
|
typer.Option( |
|
"--format", |
|
"-f", |
|
metavar="FORMAT", |
|
case_sensitive=False, |
|
help="Output format: auto, pretty, json, jsonl, or table.", |
|
rich_help_panel="Output", |
|
), |
|
] |
|
PrettyOption = Annotated[ |
|
bool, |
|
typer.Option( |
|
"--pretty", |
|
help="Force the semantic Rich view, even when stdout is not a TTY.", |
|
rich_help_panel="Output", |
|
), |
|
] |
|
OutputOption = Annotated[ |
|
Path | None, |
|
typer.Option( |
|
"--output", |
|
"-o", |
|
metavar="PATH", |
|
help="Write output atomically instead of printing it.", |
|
rich_help_panel="Output", |
|
), |
|
] |
|
NoColorOption = Annotated[ |
|
bool, |
|
typer.Option( |
|
"--no-color", |
|
help="Disable color in pretty output.", |
|
rich_help_panel="Output", |
|
), |
|
] |
|
PagerOption = Annotated[ |
|
bool, |
|
typer.Option( |
|
"--pager", |
|
help="Open pretty output in the configured terminal pager.", |
|
rich_help_panel="Output", |
|
), |
|
] |
|
WidthOption = Annotated[ |
|
int | None, |
|
typer.Option( |
|
"--width", |
|
min=40, |
|
max=240, |
|
metavar="COLUMNS", |
|
help="Override pretty-output width (40-240 columns).", |
|
rich_help_panel="Output", |
|
), |
|
] |
|
RawOption = Annotated[ |
|
bool, |
|
typer.Option( |
|
"--raw", |
|
help="Return provider-native records instead of normalized jobs.", |
|
rich_help_panel="Output", |
|
), |
|
] |
|
IncludeUnlistedOption = Annotated[ |
|
bool, |
|
typer.Option( |
|
"--include-unlisted", |
|
help="Include Ashby direct-link-only postings.", |
|
rich_help_panel="Selection", |
|
), |
|
] |
|
DocumentedOnlyOption = Annotated[ |
|
bool, |
|
typer.Option( |
|
"--documented-only", |
|
help="Reject undocumented BambooHR and Workday browser interfaces.", |
|
rich_help_panel="Selection", |
|
), |
|
] |
|
DiscoverOption = Annotated[ |
|
bool, |
|
typer.Option( |
|
"--discover/--offline", |
|
help="Resolve custom careers pages online, or require a native ATS URL.", |
|
rich_help_panel="Discovery", |
|
), |
|
] |
|
ProbeOption = Annotated[ |
|
bool, |
|
typer.Option( |
|
"--probe/--no-probe", |
|
help="Try bounded Greenhouse, Lever, Ashby, and Workable slug probes as a fallback.", |
|
rich_help_panel="Discovery", |
|
), |
|
] |
|
QuietOption = Annotated[ |
|
bool, |
|
typer.Option( |
|
"--quiet", |
|
"-q", |
|
help="Suppress warnings and progress messages; errors still print.", |
|
rich_help_panel="Diagnostics", |
|
), |
|
] |
|
VerboseOption = Annotated[ |
|
int, |
|
typer.Option( |
|
"--verbose", |
|
"-v", |
|
count=True, |
|
metavar="", |
|
show_default=False, |
|
help="Show progress; repeat as -vv for HTTP request and retry details.", |
|
rich_help_panel="Diagnostics", |
|
), |
|
] |
|
|
|
|
|
def _run_fetch( |
|
url: str, |
|
*, |
|
operation: Operation | None, |
|
provider: Provider | None, |
|
raw: bool, |
|
include_unlisted: bool, |
|
documented_only: bool, |
|
discover: bool, |
|
probe: bool, |
|
output_format: OutputFormat, |
|
pretty: bool, |
|
output: Path | None, |
|
no_color: bool, |
|
pager: bool, |
|
width: int | None, |
|
quiet: bool, |
|
verbose: int, |
|
) -> None: |
|
reporter = CliReporter(verbose=verbose, quiet=quiet) |
|
started = time.perf_counter() |
|
try: |
|
if quiet and verbose: |
|
raise InputError("--quiet cannot be combined with --verbose") |
|
if pretty and output_format is not OutputFormat.AUTO: |
|
raise InputError("--pretty cannot be combined with an explicit --format") |
|
requested_format = OutputFormat.PRETTY if pretty else output_format |
|
effective_format = resolve_output_format( |
|
requested_format, |
|
raw=raw, |
|
output=output, |
|
) |
|
if raw and effective_format in {OutputFormat.TABLE, OutputFormat.PRETTY}: |
|
raise InputError("--raw requires json or jsonl output") |
|
if pager and output is not None: |
|
raise InputError("--pager cannot be combined with --output") |
|
if pager and effective_format is not OutputFormat.PRETTY: |
|
raise InputError("--pager requires pretty output") |
|
|
|
with reporter.status("Resolving ATS provider and target…"): |
|
resolution = resolve_target( |
|
url, |
|
provider, |
|
discover=discover, |
|
probe=probe, |
|
event_sink=reporter.debug if verbose >= 2 else None, |
|
) |
|
target = resolution.target |
|
selected_operation = operation or target.operation |
|
support = operation_support(target.provider, selected_operation) |
|
if support is SupportTier.UNDOCUMENTED_PUBLIC: |
|
reporter.warning( |
|
f"{target.provider.value} uses an undocumented public interface that may drift" |
|
) |
|
|
|
reporter.info( |
|
f"Resolved {target.provider.value} via {resolution.method.value}; fetching " |
|
f"{selected_operation.value} through {support.value}." |
|
) |
|
reporter.debug( |
|
"resolution: " |
|
+ json.dumps( |
|
resolution.model_dump(mode="json"), |
|
ensure_ascii=False, |
|
separators=(",", ":"), |
|
) |
|
) |
|
with reporter.status(f"Fetching {target.provider.value} posting data…"): |
|
data = _fetch_target( |
|
target, |
|
operation=operation, |
|
raw=raw, |
|
include_unlisted=include_unlisted, |
|
documented_only=documented_only, |
|
event_sink=reporter.debug if verbose >= 2 else None, |
|
) |
|
emit_output( |
|
data, |
|
effective_format, |
|
output=output, |
|
no_color=no_color, |
|
pager=pager, |
|
width=width, |
|
) |
|
|
|
count = len(data) if isinstance(data, list) else 1 |
|
noun = "posting" if count == 1 else "postings" |
|
elapsed = time.perf_counter() - started |
|
if output is None: |
|
reporter.success(f"Fetched {count} {noun} in {elapsed:.2f}s.") |
|
else: |
|
reporter.success( |
|
f"Wrote {count} {noun} to {output.expanduser()} in {elapsed:.2f}s." |
|
) |
|
except ATSJobsError as exc: |
|
reporter.error(exc) |
|
raise typer.Exit(code=int(exc.exit_code)) from exc |
|
except Exception as exc: |
|
reporter.unexpected(exc) |
|
raise typer.Exit(code=int(ExitCode.RUNTIME)) from exc |
|
|
|
|
|
@app.command("fetch", hidden=True) |
|
def fetch_command( |
|
url: UrlArgument, |
|
provider: ProviderOption = None, |
|
raw: RawOption = False, |
|
include_unlisted: IncludeUnlistedOption = False, |
|
documented_only: DocumentedOnlyOption = False, |
|
discover: DiscoverOption = True, |
|
probe: ProbeOption = True, |
|
output_format: FormatOption = OutputFormat.AUTO, |
|
pretty: PrettyOption = False, |
|
output: OutputOption = None, |
|
no_color: NoColorOption = False, |
|
pager: PagerOption = False, |
|
width: WidthOption = None, |
|
quiet: QuietOption = False, |
|
verbose: VerboseOption = 0, |
|
) -> None: |
|
"""Infer list versus get from the URL.""" |
|
_run_fetch( |
|
url, |
|
operation=None, |
|
provider=provider, |
|
raw=raw, |
|
include_unlisted=include_unlisted, |
|
documented_only=documented_only, |
|
discover=discover, |
|
probe=probe, |
|
output_format=output_format, |
|
pretty=pretty, |
|
output=output, |
|
no_color=no_color, |
|
pager=pager, |
|
width=width, |
|
quiet=quiet, |
|
verbose=verbose, |
|
) |
|
|
|
|
|
@app.command( |
|
"list", |
|
rich_help_panel="Fetch jobs", |
|
short_help="Fetch all public postings from a careers board.", |
|
epilog=( |
|
"[bold]Example[/bold]\n\n" |
|
" [cyan]ats-jobs list https://jobs.lever.co/acme --format jsonl -v[/cyan]" |
|
), |
|
) |
|
def list_command( |
|
url: UrlArgument, |
|
provider: ProviderOption = None, |
|
raw: RawOption = False, |
|
include_unlisted: IncludeUnlistedOption = False, |
|
documented_only: DocumentedOnlyOption = False, |
|
discover: DiscoverOption = True, |
|
probe: ProbeOption = True, |
|
output_format: FormatOption = OutputFormat.AUTO, |
|
pretty: PrettyOption = False, |
|
output: OutputOption = None, |
|
no_color: NoColorOption = False, |
|
pager: PagerOption = False, |
|
width: WidthOption = None, |
|
quiet: QuietOption = False, |
|
verbose: VerboseOption = 0, |
|
) -> None: |
|
"""Fetch every public posting exposed by a careers board.""" |
|
_run_fetch( |
|
url, |
|
operation=Operation.LIST, |
|
provider=provider, |
|
raw=raw, |
|
include_unlisted=include_unlisted, |
|
documented_only=documented_only, |
|
discover=discover, |
|
probe=probe, |
|
output_format=output_format, |
|
pretty=pretty, |
|
output=output, |
|
no_color=no_color, |
|
pager=pager, |
|
width=width, |
|
quiet=quiet, |
|
verbose=verbose, |
|
) |
|
|
|
|
|
@app.command( |
|
"get", |
|
rich_help_panel="Fetch jobs", |
|
short_help="Fetch one posting from a public job URL.", |
|
epilog=( |
|
"[bold]Example[/bold]\n\n" |
|
" [cyan]ats-jobs get https://jobs.lever.co/acme/POSTING_ID --raw[/cyan]" |
|
), |
|
) |
|
def get_command( |
|
url: UrlArgument, |
|
provider: ProviderOption = None, |
|
raw: RawOption = False, |
|
documented_only: DocumentedOnlyOption = False, |
|
discover: DiscoverOption = True, |
|
probe: ProbeOption = True, |
|
output_format: FormatOption = OutputFormat.AUTO, |
|
pretty: PrettyOption = False, |
|
output: OutputOption = None, |
|
no_color: NoColorOption = False, |
|
pager: PagerOption = False, |
|
width: WidthOption = None, |
|
quiet: QuietOption = False, |
|
verbose: VerboseOption = 0, |
|
) -> None: |
|
"""Fetch one posting identified by a job URL.""" |
|
_run_fetch( |
|
url, |
|
operation=Operation.GET, |
|
provider=provider, |
|
raw=raw, |
|
include_unlisted=True, |
|
documented_only=documented_only, |
|
discover=discover, |
|
probe=probe, |
|
output_format=output_format, |
|
pretty=pretty, |
|
output=output, |
|
no_color=no_color, |
|
pager=pager, |
|
width=width, |
|
quiet=quiet, |
|
verbose=verbose, |
|
) |
|
|
|
|
|
def _exit_domain_error(error: ATSJobsError, reporter: CliReporter | None = None) -> None: |
|
active_reporter = reporter or CliReporter() |
|
active_reporter.error(error) |
|
raise typer.Exit(code=int(error.exit_code)) from error |
|
|
|
|
|
def _resolve_for_cli( |
|
url: str, |
|
*, |
|
provider: Provider | None, |
|
discover: bool, |
|
probe: bool, |
|
quiet: bool, |
|
verbose: int, |
|
) -> DiscoveryResult: |
|
reporter = CliReporter(verbose=verbose, quiet=quiet) |
|
try: |
|
if quiet and verbose: |
|
raise InputError("--quiet cannot be combined with --verbose") |
|
with reporter.status("Resolving ATS provider and target…"): |
|
resolution = resolve_target( |
|
url, |
|
provider, |
|
discover=discover, |
|
probe=probe, |
|
event_sink=reporter.debug if verbose >= 2 else None, |
|
) |
|
reporter.info( |
|
f"Resolved {resolution.target.provider.value} via {resolution.method.value}: " |
|
f"{sanitize_url(resolution.resolved_url)}" |
|
) |
|
return resolution |
|
except ATSJobsError as exc: |
|
_exit_domain_error(exc, reporter) |
|
|
|
|
|
@app.command( |
|
"detect", |
|
rich_help_panel="Inspect and diagnose", |
|
short_help="Detect the ATS behind a native or custom careers URL.", |
|
) |
|
def detect_command( |
|
url: UrlArgument, |
|
provider: ProviderOption = None, |
|
discover: DiscoverOption = True, |
|
probe: ProbeOption = True, |
|
quiet: QuietOption = False, |
|
verbose: VerboseOption = 0, |
|
) -> None: |
|
"""Print the detected provider, discovering custom careers pages when needed.""" |
|
resolution = _resolve_for_cli( |
|
url, |
|
provider=provider, |
|
discover=discover, |
|
probe=probe, |
|
quiet=quiet, |
|
verbose=verbose, |
|
) |
|
typer.echo(resolution.target.provider.value) |
|
|
|
|
|
@app.command( |
|
"inspect", |
|
rich_help_panel="Inspect and diagnose", |
|
short_help="Explain URL discovery, parsed identifiers, and support metadata.", |
|
) |
|
def inspect_command( |
|
url: UrlArgument, |
|
provider: ProviderOption = None, |
|
discover: DiscoverOption = True, |
|
probe: ProbeOption = True, |
|
quiet: QuietOption = False, |
|
verbose: VerboseOption = 0, |
|
) -> None: |
|
"""Print discovery provenance, parsed identifiers, and support metadata.""" |
|
resolution = _resolve_for_cli( |
|
url, |
|
provider=provider, |
|
discover=discover, |
|
probe=probe, |
|
quiet=quiet, |
|
verbose=verbose, |
|
) |
|
typer.echo(render_json(inspect_resolution(resolution))) |
|
|
|
|
|
@app.command( |
|
"providers", |
|
rich_help_panel="Inspect and diagnose", |
|
short_help="Show supported providers and interface stability.", |
|
) |
|
def providers_command( |
|
output_format: Annotated[ |
|
OutputFormat, |
|
typer.Option( |
|
"--format", |
|
"-f", |
|
metavar="FORMAT", |
|
case_sensitive=False, |
|
help="Output format: json, jsonl, or table.", |
|
rich_help_panel="Output", |
|
), |
|
] = OutputFormat.TABLE, |
|
) -> None: |
|
"""Show provider capabilities and support tiers.""" |
|
records = [spec.model_dump(mode="json") for spec in PROVIDER_SPECS.values()] |
|
if output_format is OutputFormat.JSONL: |
|
typer.echo(render_jsonl(records)) |
|
elif output_format is OutputFormat.JSON: |
|
typer.echo(render_json(records)) |
|
else: |
|
headers = ("PROVIDER", "LIST", "GET", "VERIFIED") |
|
rows = [ |
|
( |
|
spec.provider.value, |
|
spec.list_support.value, |
|
spec.get_support.value, |
|
spec.verified_at, |
|
) |
|
for spec in PROVIDER_SPECS.values() |
|
] |
|
widths = [ |
|
max(len(headers[index]), *(len(row[index]) for row in rows)) |
|
for index in range(len(headers)) |
|
] |
|
typer.echo( |
|
" ".join(headers[index].ljust(widths[index]) for index in range(len(headers))) |
|
) |
|
typer.echo(" ".join("-" * widths[index] for index in range(len(headers)))) |
|
for row in rows: |
|
typer.echo( |
|
" ".join(row[index].ljust(widths[index]) for index in range(len(headers))) |
|
) |
|
|
|
|
|
@app.command( |
|
"version", |
|
rich_help_panel="Inspect and diagnose", |
|
short_help="Print the installed ats-jobs version.", |
|
) |
|
def version_command() -> None: |
|
"""Print the ats-jobs version.""" |
|
typer.echo(f"ats-jobs {__version__}") |
|
|
|
|
|
COMMAND_NAMES: Final = frozenset( |
|
{"fetch", "list", "get", "detect", "inspect", "providers", "version"} |
|
) |
|
|
|
|
|
def _looks_like_target(value: str) -> bool: |
|
"""Return whether a token resembles a URL accepted by the shorthand CLI.""" |
|
if "://" in value: |
|
return True |
|
head = value.split("/", 1)[0] |
|
return "." in head and not head.startswith(".") |
|
|
|
|
|
def rewrite_argv(argv: Sequence[str]) -> list[str]: |
|
"""Turn `ats-jobs URL` into `ats-jobs fetch URL` while preserving options.""" |
|
args = list(argv) |
|
if not args or args[0] in COMMAND_NAMES or args[0] in {"-h", "--help", "--version"}: |
|
return args |
|
if any(_looks_like_target(arg) for arg in args if not arg.startswith("-")): |
|
return ["fetch", *args] |
|
return args |
|
|
|
|
|
def main(argv: Sequence[str] | None = None) -> None: |
|
"""Console-script and PEP 723 entry point.""" |
|
args = rewrite_argv(sys.argv[1:] if argv is None else argv) |
|
app(args=args, prog_name="ats-jobs") |
|
|
|
|
|
if __name__ == "__main__": |
|
main() |