diff --git a/README.md b/README.md
index 88fb349..ba8c7c8 100644
--- a/README.md
+++ b/README.md
@@ -103,6 +103,61 @@ result = client.create_image_batch(
`create_image_batch` accepts HTML/CSS and URL requests; use `create_templated_image_batch` for templates. Empty `html` or `url` values in variations are omitted so they can inherit from `default_options`. An empty variation list returns a successful empty result without sending an HTTP request. Options unsupported by the batch API, such as `dedupe_duration_s`, are not serialized. See the [batch API documentation](https://docs.htmlcsstoimage.com/getting-started/using-the-api/#batch-image-creation).
+## Recordings
+
+Use `create_recording` with `CreateHtmlCssRecordingRequest` or `CreateUrlRecordingRequest` to record HTML/CSS or a public webpage as MP4, WebM, or GIF:
+
+```python
+from html_css_to_image import (
+ CreateHtmlCssRecordingRequest,
+ CreateUrlRecordingRequest,
+ RecordingOutputOptions,
+ RecordingSimpleScrollAction,
+)
+
+result = client.create_recording(CreateUrlRecordingRequest(
+ url="https://example.com",
+ duration_ms=10000,
+ viewport_width=1280,
+ viewport_height=720,
+ actions=[RecordingSimpleScrollAction()],
+ output=RecordingOutputOptions(format="mp4"),
+))
+if result.success:
+ print(result.recording_url) # Embed or request directly; it waits until the recording is ready.
+else:
+ print(result.error)
+
+animation = client.create_recording(CreateHtmlCssRecordingRequest(
+ html="
Hello
",
+ css="@keyframes fade { from { opacity: 0; } to { opacity: 1; } } h1 { animation: fade 2s; }",
+ duration_ms=3000,
+ duration_mode="fixed",
+ output=RecordingOutputOptions(format="gif", scale=0.5),
+))
+```
+
+Both request types share browser settings, triggers, ordered actions, and output options. Actions and triggers are typed dataclasses, such as `RecordingClickAction(selector="#start")` and `RecordingElementVisibleTrigger(selector="#ready")`. For JavaScript actions, `if_error=None` fails on a script error; `if_error=[]` ignores errors. Empty branch lists are preserved in JSON.
+
+```python
+deleted = client.delete_recording("recording-id")
+batch_deleted = client.delete_recording_batch(["first-id", "second-id"])
+```
+
+Deletion returns a success response when accepted. `delete_recording_batch` accepts a list or tuple of strings; an empty list returns a successful result without sending an HTTP request. All recording methods return the existing `ApiErrorResponse` on API errors and propagate HTTPX transport failures.
+
+Optional settings use the API defaults. Recordings have no audio. Creation returns an ID, status URL, and recording URL. The `recording_url` can be embedded or requested directly; the request waits until the recording is ready, so checking status is optional.
+
+```python
+status = client.fetch_recording_status("recording-id")
+if status.success:
+ print(status.status)
+```
+
+`fetch_recording_status` makes one request. HTTP 200 and 202 both return status information; `ready`, `failed`, and `cancelled` are terminal states. An error can describe an earlier, retryable attempt. A successful status fetch can report a failed recording. A status the client does not recognize, such as one added in a newer API version, is reported as `unknown`.
+
+See the [recording guide](https://docs.htmlcsstoimage.com/getting-started/recordings/), [actions reference](https://docs.htmlcsstoimage.com/parameters/actions/), and [trigger reference](https://docs.htmlcsstoimage.com/parameters/trigger/) for the timeline, output options, and examples.
+
## Signed URLs
The signed URL helpers perform no network request. They create the exact query string, sign it with HMAC-SHA256 using the API key, and return a URL that can be shared without exposing that key.
@@ -187,7 +242,7 @@ single = client.delete_image("image-id")
batch = client.delete_image_batch(["image-id-1", "image-id-2"])
```
-Every successful `2xx` response maps to `DeleteImageSuccessResponse`. API errors use `ApiErrorResponse`, while network failures remain HTTPX exceptions.
+Every successful `2xx` response maps to `DeleteImageSuccessResponse`. `delete_image_batch` accepts a list or tuple of strings; an empty list returns a successful result without sending an HTTP request. API errors use `ApiErrorResponse`, while network failures remain HTTPX exceptions.
## HTTP configuration
@@ -245,11 +300,15 @@ else:
| `create_image_batch(variations, default_options=None)` | `CreateImageBatchResponse` | Sends `POST /v1/image/batch`, unless the list is empty. |
| `create_templated_image_batch(variations, default_options=None)` | `CreateImageBatchResponse` | Sends `POST /v1/image/batch/templated`, unless the list is empty. |
| `delete_image(image_id)` | `DeleteImageResponse` | Sends `DELETE /v1/image/{id}`. |
-| `delete_image_batch(image_ids)` | `DeleteImageResponse` | Sends `DELETE /v1/image/batch`. |
+| `delete_image_batch(image_ids)` | `DeleteImageResponse` | Sends `DELETE /v1/image/batch`, unless the list is empty. |
| `image_url(image_id, render_options=None)` | `str` | Builds an existing-image URL locally. |
| `generate_templated_image_url(request, render_options=None)` | `str` | Builds and signs a template URL from a request locally. |
| `generate_templated_image_url_from_values(...)` | `str` | Builds and signs a template URL from separate values locally. |
| `generate_create_and_render_url(...)` | `str` | Builds and signs a URL screenshot locally. |
+| `create_recording(request)` | `CreateRecordingResponse` | Sends `POST /v1/recording`. |
+| `fetch_recording_status(recording_id)` | `RecordingStatusResponse` | Sends `GET /v1/recordings/{id}/status`. |
+| `delete_recording(recording_id)` | `DeleteRecordingResponse` | Sends `DELETE /v1/recordings/{id}`. |
+| `delete_recording_batch(recording_ids)` | `DeleteRecordingResponse` | Sends `DELETE /v1/recordings/batch`, unless the list is empty. |
| `close()` | `None` | Closes only an SDK-owned HTTP client. |
The package exports typed request, response, PDF, and render/crop models from `html_css_to_image`. Public classes, constructor parameters, attributes, and methods include docstrings for IDE help and generated API documentation.
diff --git a/pyproject.toml b/pyproject.toml
index ce2f95a..ef78ed3 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "html-css-to-image"
-version = "0.4.0"
+version = "1.0.0"
description = "Official Python client for the HTML/CSS to Image API"
readme = "README.md"
requires-python = ">=3.10"
@@ -14,7 +14,7 @@ authors = [
]
keywords = ["html-to-image", "screenshot", "hcti", "htmlcsstoimage"]
classifiers = [
- "Development Status :: 3 - Alpha",
+ "Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
diff --git a/src/html_css_to_image/__init__.py b/src/html_css_to_image/__init__.py
index 00da788..00e1ee5 100644
--- a/src/html_css_to_image/__init__.py
+++ b/src/html_css_to_image/__init__.py
@@ -40,8 +40,80 @@
TemplatedBatchImageOptions,
ValidationError,
)
+from .recordings import (
+ BaseCreateRecordingRequest,
+ CoordinatesScrollTarget,
+ CreateHtmlCssRecordingRequest,
+ CreateRecordingRequest,
+ CreateRecordingResponse,
+ CreateRecordingSuccessResponse,
+ CreateUrlRecordingRequest,
+ DeleteRecordingResponse,
+ DeleteRecordingSuccessResponse,
+ PositionScrollTarget,
+ RecordingAction,
+ RecordingClickAction,
+ RecordingDurationMode,
+ RecordingElementVisibleTrigger,
+ RecordingError,
+ RecordingErrorAction,
+ RecordingExecuteJavaScriptAction,
+ RecordingFormat,
+ RecordingFunctionCallTrigger,
+ RecordingImmediateTrigger,
+ RecordingLocateSelectorAction,
+ RecordingMouseButton,
+ RecordingOutputOptions,
+ RecordingScrollAction,
+ RecordingSimpleScrollAction,
+ RecordingStallAction,
+ RecordingStatus,
+ RecordingStatusResponse,
+ RecordingStatusSuccessResponse,
+ RecordingTrigger,
+ ScrollEasing,
+ ScrollPosition,
+ ScrollStep,
+ ScrollTarget,
+ SelectorScrollTarget,
+)
__all__ = [
+ "BaseCreateRecordingRequest",
+ "CoordinatesScrollTarget",
+ "CreateHtmlCssRecordingRequest",
+ "CreateRecordingRequest",
+ "CreateRecordingResponse",
+ "CreateRecordingSuccessResponse",
+ "CreateUrlRecordingRequest",
+ "DeleteRecordingResponse",
+ "DeleteRecordingSuccessResponse",
+ "PositionScrollTarget",
+ "RecordingAction",
+ "RecordingClickAction",
+ "RecordingDurationMode",
+ "RecordingElementVisibleTrigger",
+ "RecordingError",
+ "RecordingErrorAction",
+ "RecordingExecuteJavaScriptAction",
+ "RecordingFormat",
+ "RecordingFunctionCallTrigger",
+ "RecordingImmediateTrigger",
+ "RecordingLocateSelectorAction",
+ "RecordingMouseButton",
+ "RecordingOutputOptions",
+ "RecordingScrollAction",
+ "RecordingSimpleScrollAction",
+ "RecordingStallAction",
+ "RecordingStatus",
+ "RecordingStatusResponse",
+ "RecordingStatusSuccessResponse",
+ "RecordingTrigger",
+ "ScrollEasing",
+ "ScrollPosition",
+ "ScrollStep",
+ "ScrollTarget",
+ "SelectorScrollTarget",
"ApiErrorResponse",
"BaseCreateImageRequest",
"BatchCreateImageRequest",
diff --git a/src/html_css_to_image/_request_mapper.py b/src/html_css_to_image/_request_mapper.py
index 18dfc1e..7e425da 100644
--- a/src/html_css_to_image/_request_mapper.py
+++ b/src/html_css_to_image/_request_mapper.py
@@ -3,6 +3,8 @@
from __future__ import annotations
from collections.abc import Mapping
+from dataclasses import fields, is_dataclass
+from enum import Enum
from typing import Any
from .models import (
@@ -18,11 +20,56 @@
RequestOverride,
TemplatedBatchImageOptions,
)
+from .recordings import (
+ CreateHtmlCssRecordingRequest,
+ CreateRecordingRequest,
+ CreateUrlRecordingRequest,
+)
class RequestMapper:
"""Serialize typed request models for HCTI API operations."""
+ @classmethod
+ def map_recording(cls, request: CreateRecordingRequest) -> dict[str, Any]:
+ """Serialize a recording without adding defaults or validating API options."""
+ if not isinstance(
+ request, (CreateHtmlCssRecordingRequest, CreateUrlRecordingRequest)
+ ):
+ raise TypeError(f"Unsupported request type: {type(request).__name__}")
+ payload: dict[str, Any] = cls._recording_value(request)
+ if isinstance(request, CreateHtmlCssRecordingRequest):
+ payload.pop("google_fonts", None)
+ fonts = cls._map_google_fonts(request.google_fonts)
+ if fonts is not None:
+ payload["google_fonts"] = fonts
+ return payload
+
+ @classmethod
+ def _recording_value(cls, value: Any) -> Any:
+ if isinstance(value, Enum):
+ return value.value
+ if is_dataclass(value) and not isinstance(value, type):
+ return {
+ item.name: cls._recording_value(getattr(value, item.name))
+ for item in fields(value)
+ if getattr(value, item.name) is not None
+ }
+ if isinstance(value, Mapping):
+ return {key: cls._recording_value(item) for key, item in value.items()}
+ if isinstance(value, (list, tuple)):
+ return [cls._recording_value(item) for item in value]
+ return value
+
+ @staticmethod
+ def _map_google_fonts(font_names: list[str] | tuple[str, ...] | None) -> str | None:
+ fonts: list[str] = []
+ for font in font_names or ():
+ processed = font.strip().replace(" ", "+")
+ if processed and processed not in fonts:
+ fonts.append(processed)
+ return "|".join(fonts) if fonts else None
+
@classmethod
def map_request(
cls,
@@ -61,19 +108,23 @@ def map_batch_request(
@classmethod
def map_templated_batch_options(
- cls, request: TemplatedBatchImageOptions,
+ cls,
+ request: TemplatedBatchImageOptions,
) -> dict[str, Any]:
if not isinstance(request, TemplatedBatchImageOptions):
raise TypeError("Template batches require TemplatedBatchImageOptions")
- return cls.without_none({
- "template_id": request.template_id,
- "template_version": request.template_version,
- "template_values": (
- dict(request.template_values)
- if request.template_values is not None else None
- ),
- "format": request.format,
- })
+ return cls.without_none(
+ {
+ "template_id": request.template_id,
+ "template_version": request.template_version,
+ "template_values": (
+ dict(request.template_values)
+ if request.template_values is not None
+ else None
+ ),
+ "format": request.format,
+ }
+ )
@classmethod
def common_payload(
@@ -135,14 +186,9 @@ def _map_html_request(
payload["html"] = request.html or None if in_batch else request.html
payload["css"] = request.css
- if request.google_fonts:
- fonts: list[str] = []
- for font in request.google_fonts:
- processed = font.strip().replace(" ", "+")
- if processed and processed not in fonts:
- fonts.append(processed)
- if fonts:
- payload["google_fonts"] = "|".join(fonts)
+ fonts = cls._map_google_fonts(request.google_fonts)
+ if fonts is not None:
+ payload["google_fonts"] = fonts
return cls.without_none(payload)
@@ -183,14 +229,17 @@ def _map_url_request(
@staticmethod
def _map_request_overrides(rules: list[RequestOverride]) -> list[dict[str, Any]]:
return [
- RequestMapper.without_none({
- "action": rule.action.value,
- "url": rule.url,
- "resource_types": (
- [resource_type.value for resource_type in rule.resource_types]
- if rule.resource_types is not None else None
- ),
- })
+ RequestMapper.without_none(
+ {
+ "action": rule.action.value,
+ "url": rule.url,
+ "resource_types": (
+ [resource_type.value for resource_type in rule.resource_types]
+ if rule.resource_types is not None
+ else None
+ ),
+ }
+ )
for rule in rules
]
diff --git a/src/html_css_to_image/_response_mapper.py b/src/html_css_to_image/_response_mapper.py
index 084c21a..d183edd 100644
--- a/src/html_css_to_image/_response_mapper.py
+++ b/src/html_css_to_image/_response_mapper.py
@@ -3,7 +3,7 @@
from __future__ import annotations
from collections.abc import Mapping
-from typing import Any
+from typing import Any, cast, get_args
import httpx
@@ -18,11 +18,99 @@
DeleteImageSuccessResponse,
ValidationError,
)
+from .recordings import (
+ CreateRecordingResponse,
+ CreateRecordingSuccessResponse,
+ RecordingError,
+ RecordingStatus,
+ RecordingStatusResponse,
+ RecordingStatusSuccessResponse,
+)
+
+_KNOWN_RECORDING_STATUSES = frozenset(get_args(RecordingStatus))
class ResponseMapper:
"""Create typed response models and reject malformed successful bodies."""
+ @classmethod
+ def map_recording_response(
+ cls, response: httpx.Response
+ ) -> CreateRecordingResponse:
+ """Map recording creation through the existing API error contract."""
+ if not response.is_success:
+ return cls._map_error_response(response)
+ data = cls._decode_success_object(response, "recording creation")
+ return CreateRecordingSuccessResponse(
+ id=cls._recording_string(data, "id", response),
+ status_url=cls._recording_string(data, "status_url", response),
+ recording_url=cls._recording_string(data, "recording_url", response),
+ )
+
+ @classmethod
+ def map_recording_status(cls, response: httpx.Response) -> RecordingStatusResponse:
+ """Map a single status fetch, including nonterminal HTTP 202 responses."""
+ if not response.is_success:
+ return cls._map_error_response(response)
+ data = cls._decode_success_object(response, "recording status")
+ try:
+ error = None
+ raw_error = data.get("error")
+ if raw_error is not None:
+ if not isinstance(raw_error, dict):
+ raise TypeError("Expected a recording error object")
+ error = RecordingError(
+ code=cls._recording_string(raw_error, "code", response),
+ message=cls._recording_string(raw_error, "message", response),
+ occurred_at=cls._recording_string(
+ raw_error, "occurred_at", response
+ ),
+ retryable=raw_error["retryable"],
+ action_path=raw_error.get("action_path"),
+ )
+ return RecordingStatusSuccessResponse(
+ id=cls._recording_string(data, "id", response),
+ recording_url=cls._recording_string(data, "recording_url", response),
+ status=cls._recording_status(data, response),
+ status_entered_at=cls._recording_string(
+ data, "status_entered_at", response
+ ),
+ attempt_count=int(data["attempt_count"]),
+ stored_duration_ms=(
+ int(data["stored_duration_ms"])
+ if data.get("stored_duration_ms") is not None
+ else None
+ ),
+ storage_destination_hcti_storage_disabled=data.get(
+ "storage_destination_hcti_storage_disabled"
+ ),
+ error=error,
+ )
+ except (KeyError, TypeError, ValueError) as exc:
+ raise cls._unexpected(
+ response, "Malformed recording status response."
+ ) from exc
+
+ @classmethod
+ def _recording_status(
+ cls, data: Mapping[str, Any], response: httpx.Response
+ ) -> RecordingStatus:
+ status = cls._recording_string(data, "status", response)
+ if status not in _KNOWN_RECORDING_STATUSES:
+ return "unknown"
+ return cast(RecordingStatus, status)
+
+ @classmethod
+ def _recording_string(
+ cls, data: Mapping[str, Any], key: str, response: httpx.Response
+ ) -> str:
+ value = data.get(key)
+ if not isinstance(value, str) or not value:
+ raise cls._unexpected(
+ response, f"Recording response must contain a non-empty {key} string."
+ )
+ return value
+
@classmethod
def map_image_response(cls, response: httpx.Response) -> CreateImageResponse:
"""Map one image-creation response."""
diff --git a/src/html_css_to_image/_transport.py b/src/html_css_to_image/_transport.py
index 045d39b..6d9a9c0 100644
--- a/src/html_css_to_image/_transport.py
+++ b/src/html_css_to_image/_transport.py
@@ -31,6 +31,16 @@ def __init__(
credentials = base64.b64encode(f"{api_id}:{api_key}".encode()).decode()
self._auth_header = f"Basic {credentials}"
+ def get(self, path: str) -> httpx.Response:
+ """Send an authenticated GET request."""
+ return self._http_client.get(
+ f"{self._base_url}{path}",
+ headers={
+ "Authorization": self._auth_header,
+ "User-Agent": _USER_AGENT,
+ },
+ )
+
def post(self, path: str, payload: Mapping[str, Any]) -> httpx.Response:
"""Send a JSON POST request."""
diff --git a/src/html_css_to_image/client.py b/src/html_css_to_image/client.py
index 09ca227..fd080e2 100644
--- a/src/html_css_to_image/client.py
+++ b/src/html_css_to_image/client.py
@@ -22,15 +22,23 @@
CreateTemplatedImageRequest,
CreateUrlImageRequest,
DeleteImageResponse,
+ DeleteImageSuccessResponse,
RenderImageOptions,
TemplatedBatchImageOptions,
)
+from .recordings import (
+ CreateRecordingRequest,
+ CreateRecordingResponse,
+ DeleteRecordingResponse,
+ DeleteRecordingSuccessResponse,
+ RecordingStatusResponse,
+)
_ClientT = TypeVar("_ClientT", bound="HtmlCssToImageClient")
class HtmlCssToImageClient:
- """Client for creating images with the HTML/CSS to Image API.
+ """Client for creating images and recordings with the HTML/CSS to Image API.
The client performs no automatic retries. To configure retry behavior,
proxies, certificates, connection limits, or custom transports, construct
@@ -101,6 +109,59 @@ def from_env(
base_url=base_url,
)
+ def create_recording(
+ self, request: CreateRecordingRequest
+ ) -> CreateRecordingResponse:
+ """Record HTML/CSS or a public URL.
+
+ The returned recording_url can be embedded or requested directly; the
+ request waits until the recording is ready. Optional settings use API
+ defaults. API errors use ApiErrorResponse; network failures are raised
+ by HTTPX, as for create_image.
+ See https://docs.htmlcsstoimage.com/getting-started/recordings/.
+ """
+ payload = RequestMapper.map_recording(request)
+ return ResponseMapper.map_recording_response(
+ self._transport.post("/v1/recording", payload)
+ )
+
+ def fetch_recording_status(self, recording_id: str) -> RecordingStatusResponse:
+ """Fetch status once. HTTP 200 and 202 both return status information.
+
+ ready, failed, and cancelled are terminal states. An error can describe
+ an earlier, retryable attempt; inspect status for the current state.
+ """
+ return ResponseMapper.map_recording_status(
+ self._transport.get(f"/v1/recordings/{recording_id}/status")
+ )
+
+ def delete_recording(self, recording_id: str) -> DeleteRecordingResponse:
+ """Delete a recording and clear its media from the CDN."""
+ return ResponseMapper.map_delete_response(
+ self._transport.delete(f"/v1/recordings/{recording_id}")
+ )
+
+ def delete_recording_batch(
+ self, recording_ids: list[str] | tuple[str, ...]
+ ) -> DeleteRecordingResponse:
+ """Delete recording IDs in one API call. The API validates the options.
+
+ An empty list or tuple returns a successful response without making an
+ HTTP request.
+
+ Raises:
+ TypeError: If ``recording_ids`` is not a list or tuple of strings.
+ """
+ if not isinstance(recording_ids, (list, tuple)) or any(
+ not isinstance(recording_id, str) for recording_id in recording_ids
+ ):
+ raise TypeError("recording_ids must be a list or tuple of strings")
+ if not recording_ids:
+ return DeleteRecordingSuccessResponse()
+ return ResponseMapper.map_delete_response(
+ self._transport.delete("/v1/recordings/batch", {"ids": list(recording_ids)})
+ )
+
def create_image(self, request: CreateImageRequest) -> CreateImageResponse:
"""Create an image from HTML/CSS, a URL, or a saved template.
@@ -155,8 +216,7 @@ def create_image_batch(
payload: dict[str, Any] = {
"variations": [
- RequestMapper.map_batch_request(variation)
- for variation in variations
+ RequestMapper.map_batch_request(variation) for variation in variations
],
}
if default_options is not None:
@@ -180,8 +240,7 @@ def create_templated_image_batch(
return CreateImageBatchSuccessResponse(images=())
payload: dict[str, Any] = {
"variations": [
- RequestMapper.map_templated_batch_options(item)
- for item in variations
+ RequestMapper.map_templated_batch_options(item) for item in variations
],
}
if default_options is not None:
@@ -214,6 +273,9 @@ def delete_image_batch(
) -> DeleteImageResponse:
"""Delete several generated images in one API call.
+ An empty list or tuple returns a successful response without making an
+ HTTP request.
+
Args:
image_ids: List or tuple of HCTI image identifiers to delete.
@@ -229,6 +291,8 @@ def delete_image_batch(
not isinstance(image_id, str) for image_id in image_ids
):
raise TypeError("image_ids must be a list or tuple of strings")
+ if not image_ids:
+ return DeleteImageSuccessResponse()
response = self._transport.delete("/v1/image/batch", {"ids": list(image_ids)})
return ResponseMapper.map_delete_response(response)
diff --git a/src/html_css_to_image/recordings.py b/src/html_css_to_image/recordings.py
new file mode 100644
index 0000000..e3f705e
--- /dev/null
+++ b/src/html_css_to_image/recordings.py
@@ -0,0 +1,538 @@
+"""
+Typed recording sources, timeline actions, triggers, and responses.
+
+See https://docs.htmlcsstoimage.com/getting-started/recordings/.
+Optional request settings use the API defaults; options are not validated locally.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+from dataclasses import dataclass, field
+from typing import Literal, TypeAlias
+
+from .models import (
+ ApiErrorResponse,
+ ColorSchemeType,
+ DeleteImageResponse,
+ DeleteImageSuccessResponse,
+ MediaType,
+ RequestOverride,
+)
+
+RecordingFormat: TypeAlias = Literal["mp4", "webm", "gif"]
+
+RecordingDurationMode: TypeAlias = Literal["fixed", "target", "at_least", "at_most"]
+
+RecordingMouseButton: TypeAlias = Literal["left", "right", "middle", "back", "forward"]
+
+RecordingStatus: TypeAlias = Literal[
+ "processing",
+ "pending_retry",
+ "ready",
+ "failed",
+ "cancelled",
+ "awaiting_render",
+ "unknown",
+]
+"""Recording status. ``unknown`` is an unrecognized status from a newer API version."""
+
+ScrollEasing: TypeAlias = Literal[
+ "linear",
+ "ease_in_cubic",
+ "ease_out_cubic",
+ "ease_in_out_cubic",
+ "ease_in_quad",
+ "ease_out_quad",
+ "ease_in_out_quad",
+ "ease_in_quart",
+ "ease_out_quart",
+ "ease_in_out_quart",
+ "ease_in_quint",
+ "ease_out_quint",
+ "ease_in_out_quint",
+ "ease_in_sine",
+ "ease_out_sine",
+ "ease_in_out_sine",
+ "ease_in_expo",
+ "ease_out_expo",
+ "ease_in_out_expo",
+ "ease_in_circ",
+ "ease_out_circ",
+ "ease_in_out_circ",
+ "ease_in_back",
+ "ease_out_back",
+ "ease_in_out_back",
+ "ease_in_elastic",
+ "ease_out_elastic",
+ "ease_in_out_elastic",
+ "ease_in_bounce",
+ "ease_out_bounce",
+ "ease_in_out_bounce",
+]
+
+ScrollPosition: TypeAlias = Literal["top", "bottom", "left", "right"]
+
+
+@dataclass(slots=True, kw_only=True)
+class RecordingScrollAction:
+ """Scroll through an ordered sequence of timed movements in the document or a
+ selected container.
+
+ Attributes:
+ container_selector: Scrollable container's CSS selector. Omit or use None to
+ scroll the document.
+ steps: Ordered movements. Supply at least one step.
+ if_not_found: Fallback when the container is missing. Omitted, None, or empty
+ skips this action.
+ """
+
+ type: Literal["scroll"] = field(default="scroll", init=False)
+ container_selector: str | None = None
+ steps: list[ScrollStep]
+ if_not_found: list[RecordingAction] | None = None
+
+
+@dataclass(slots=True, kw_only=True)
+class RecordingStallAction:
+ """Wait while recording and page activity continue.
+
+ Attributes:
+ duration_ms: Wait in milliseconds. The recording deadline can end it early.
+ """
+
+ type: Literal["stall"] = field(default="stall", init=False)
+ duration_ms: int | None = None
+
+
+@dataclass(slots=True, kw_only=True)
+class RecordingLocateSelectorAction:
+ """Look for a matching element and execute the corresponding branch. Branch actions
+ supply their own selectors.
+
+ Attributes:
+ selector: CSS selector to find.
+ timeout_ms: Maximum wait in milliseconds. Defaults to 0 for a single check.
+ if_found: Actions when found. Omitted, None, or empty continues with the parent
+ sequence.
+ if_not_found: Actions when missing. Include an error action to fail the
+ recording.
+ """
+
+ type: Literal["locate_selector"] = field(default="locate_selector", init=False)
+ selector: str
+ timeout_ms: int | None = None
+ if_found: list[RecordingAction] | None = None
+ if_not_found: list[RecordingAction] | None = None
+
+
+@dataclass(slots=True, kw_only=True)
+class RecordingClickAction:
+ """Find and click an element, scrolling it into view when needed.
+
+ Attributes:
+ selector: CSS selector of the element to click.
+ timeout_ms: Maximum wait in milliseconds. Defaults to 0 for a single check.
+ if_not_found: Fallback when missing. Omitted, None, or empty continues; use an
+ error action to fail.
+ button: Mouse button. Defaults to left.
+ count: Event click count, from 1 to 3. Defaults to 1; this does not repeat the
+ action.
+ delay_ms: Delay between mouse down and up, in milliseconds. Defaults to 0;
+ maximum 5000.
+ offset_x: CSS pixels from the element's top-left. Supplying either offset makes
+ the other default to 0.
+ offset_y: CSS pixels from the element's top-left. Omit both offsets to use the
+ default clickable point.
+ """
+
+ type: Literal["click"] = field(default="click", init=False)
+ selector: str
+ timeout_ms: int | None = None
+ if_not_found: list[RecordingAction] | None = None
+ button: RecordingMouseButton | None = None
+ count: int | None = None
+ delay_ms: int | None = None
+ offset_x: float | None = None
+ offset_y: float | None = None
+
+
+@dataclass(slots=True, kw_only=True)
+class RecordingErrorAction:
+ """Fail the recording and stop executing actions. Must be the last action in its
+ array.
+ """
+
+ type: Literal["error"] = field(default="error", init=False)
+
+
+@dataclass(slots=True, kw_only=True)
+class RecordingSimpleScrollAction:
+ """Scroll down repeatedly until reaching the bottom or the recording deadline. Each
+ movement has its own duration and easing, followed by a pause.
+
+ Attributes:
+ scroll_duration_ms: Duration of each movement in milliseconds. Defaults to 800.
+ ms_between_scrolls: Pause between movements in milliseconds. Defaults to 400; 0
+ scrolls continuously.
+ scroll_distance: CSS pixels as a number, or a string such as '900px' or '90vh'.
+ Defaults to '90vh'.
+ easing: Movement easing. Defaults to ease_in_out_expo.
+ stall_at_end_ms: Time to hold at the bottom in milliseconds, limited by
+ remaining recording time. Defaults to 0.
+ """
+
+ type: Literal["simple_scroll"] = field(default="simple_scroll", init=False)
+ scroll_duration_ms: int | None = None
+ ms_between_scrolls: int | None = None
+ scroll_distance: int | float | str | None = None
+ easing: ScrollEasing | None = None
+ stall_at_end_ms: int | None = None
+
+
+@dataclass(slots=True, kw_only=True)
+class RecordingExecuteJavaScriptAction:
+ """Execute JavaScript in the page while recording continues, awaiting any returned
+ promise.
+
+ Attributes:
+ script: Function body supporting await. Its return value is ignored.
+ timeout_ms: Maximum execution time in milliseconds. Zero or omitted uses the
+ page timeout; maximum 90000.
+ if_error: Omitted or None fails on script errors; [] ignores errors. A timeout
+ does not undo side effects.
+ """
+
+ type: Literal["execute_javascript"] = field(
+ default="execute_javascript", init=False
+ )
+ script: str
+ timeout_ms: int | None = None
+ if_error: list[RecordingAction] | None = None
+
+
+@dataclass(slots=True, kw_only=True)
+class RecordingImmediateTrigger:
+ """Start recording immediately after page preparation. This is the default trigger.
+ """
+
+ type: Literal["immediate"] = field(default="immediate", init=False)
+
+
+@dataclass(slots=True, kw_only=True)
+class RecordingElementVisibleTrigger:
+ """Wait for a matching element to become visible before starting recording. Fails
+ if the timeout expires.
+
+ Attributes:
+ selector: CSS selector for the element to wait for.
+ timeout_ms: Maximum wait in milliseconds. Defaults to 1000; minimum 100. Plan
+ limits apply.
+ """
+
+ type: Literal["element_visible"] = field(default="element_visible", init=False)
+ selector: str
+ timeout_ms: int | None = None
+
+
+@dataclass(slots=True, kw_only=True)
+class RecordingFunctionCallTrigger:
+ """Wait for the page to call window.RecordingReady() before starting recording.
+ Fails if the timeout expires.
+
+ Attributes:
+ timeout_ms: Maximum wait in milliseconds. Defaults to 1000; minimum 100. Plan
+ limits apply.
+ """
+
+ type: Literal["function_call"] = field(default="function_call", init=False)
+ timeout_ms: int | None = None
+
+
+@dataclass(slots=True, kw_only=True)
+class PositionScrollTarget:
+ """Scroll to an edge of the document or selected container.
+
+ Attributes:
+ position: Edge to scroll to. Defaults to top.
+ """
+
+ type: Literal["position"] = field(default="position", init=False)
+ position: ScrollPosition | None = None
+
+
+@dataclass(slots=True, kw_only=True)
+class CoordinatesScrollTarget:
+ """Scroll to absolute coordinates within the document or selected container.
+
+ Attributes:
+ x: Horizontal position. Defaults to 0.
+ y: Vertical position. Defaults to 0.
+ """
+
+ type: Literal["coordinates"] = field(default="coordinates", init=False)
+ x: float | None = None
+ y: float | None = None
+
+
+@dataclass(slots=True, kw_only=True)
+class SelectorScrollTarget:
+ """Scroll to an element matching a CSS selector, with optional offsets.
+
+ Attributes:
+ selector: CSS selector for the destination element.
+ offset_x: Horizontal offset from the element. Defaults to 0.
+ offset_y: Vertical offset from the element. Defaults to 0.
+ if_not_found: Fallback when missing. Omitted, None, or empty skips this movement
+ and continues to the next step.
+ """
+
+ type: Literal["selector"] = field(default="selector", init=False)
+ selector: str
+ offset_x: float | None = None
+ offset_y: float | None = None
+ if_not_found: list[RecordingAction] | None = None
+
+
+@dataclass(slots=True, kw_only=True)
+class RecordingOutputOptions:
+ """Output format, frame rate, and scaling for a recording.
+
+ Attributes:
+ format: Media format. Defaults to mp4.
+ fps: Frames per second. Defaults to 15 for GIF and 30 for video. GIF supports
+ 10–50; video supports 10–120.
+ scale: Scales captured pixels without changing page layout. Defaults to 1; 0.5
+ halves both dimensions.
+ """
+
+ format: RecordingFormat | None = None
+ fps: int | None = None
+ scale: float | None = None
+
+
+@dataclass(slots=True, kw_only=True)
+class ScrollStep:
+ """One timed scroll movement within a scroll action. Steps run in order.
+
+ Attributes:
+ to: Destination for this movement. Select position, coordinates, or selector
+ using its type discriminator.
+ duration_ms: Required movement duration in milliseconds. Must be at least 1.
+ The recording deadline can cut it short.
+ easing: Movement easing. Defaults to linear.
+ """
+
+ to: ScrollTarget
+ duration_ms: int
+ easing: ScrollEasing | None = None
+
+
+RecordingAction: TypeAlias = (
+ RecordingScrollAction
+ | RecordingStallAction
+ | RecordingLocateSelectorAction
+ | RecordingClickAction
+ | RecordingErrorAction
+ | RecordingSimpleScrollAction
+ | RecordingExecuteJavaScriptAction
+)
+
+RecordingTrigger: TypeAlias = (
+ RecordingImmediateTrigger
+ | RecordingElementVisibleTrigger
+ | RecordingFunctionCallTrigger
+)
+
+ScrollTarget: TypeAlias = (
+ PositionScrollTarget | CoordinatesScrollTarget | SelectorScrollTarget
+)
+
+
+@dataclass(slots=True, kw_only=True)
+class BaseCreateRecordingRequest:
+ """Browser settings and timeline options shared by both recording sources.
+
+ Attributes:
+ css: CSS to style HTML content or inject into a URL page after it loads. See
+ https://docs.htmlcsstoimage.com/parameters/css/
+ device_scale: Capture pixel density. Defaults to 2 for HTML/CSS and 1 for URL
+ recordings. See https://docs.htmlcsstoimage.com/parameters/device_scale/
+ viewport_height: Viewport height in CSS pixels. Supply both dimensions to set
+ the recording size. See https://docs.htmlcsstoimage.com/parameters/viewport/
+ viewport_width: Viewport width in CSS pixels. Supply both dimensions to set the
+ recording size. See https://docs.htmlcsstoimage.com/parameters/viewport/
+ disable_twemoji: Disable Twemoji for HTML/CSS when true. URL recordings inject
+ it only when explicitly false. See
+ https://docs.htmlcsstoimage.com/parameters/disable_twemoji/
+ dedupe_duration_s: Reuse an identical recording created within this many
+ seconds. Set to 0 to disable deduplication. See
+ https://docs.htmlcsstoimage.com/parameters/dedupe_duration_s/
+ color_scheme: Chrome's preferred light or dark color scheme while recording. See
+ https://docs.htmlcsstoimage.com/parameters/color_scheme/
+ timezone: Browser timezone as an IANA identifier, such as 'America/New_York'.
+ See https://docs.htmlcsstoimage.com/parameters/timezone/
+ viewport_mobile: Enable mobile viewport behavior, including the page's viewport
+ meta tag. See https://docs.htmlcsstoimage.com/parameters/viewport/
+ viewport_landscape: Emulate landscape orientation. See
+ https://docs.htmlcsstoimage.com/parameters/viewport/
+ viewport_touch: Emulate a viewport that supports touch events. See
+ https://docs.htmlcsstoimage.com/parameters/viewport/
+ media_type: CSS media type used while recording. See
+ https://docs.htmlcsstoimage.com/parameters/media_type/
+ proxy_id: Organization proxy to use while recording. See
+ https://docs.htmlcsstoimage.com/guides/advanced/proxies/
+ storage_destination_id: Storage destination to receive the recording. See
+ https://docs.htmlcsstoimage.com/guides/advanced/storage-destinations/
+ request_overrides: Block matching browser requests while recording. Available on
+ paid plans. See
+ https://docs.htmlcsstoimage.com/parameters/request_overrides/
+ duration_ms: Requested duration in milliseconds: 500–30000, or up to 90000 in
+ target mode. duration_mode controls how actions fit into this duration. See
+ https://docs.htmlcsstoimage.com/parameters/duration_ms/
+ trigger: When recording and actions start after page preparation. Defaults to
+ immediate. See https://docs.htmlcsstoimage.com/parameters/trigger/
+ actions: Ordered interactions. Leave None or empty to record the page without
+ interactions. See https://docs.htmlcsstoimage.com/parameters/actions/
+ output: Output format, frame rate, and scale. Defaults to MP4 at 30 fps without
+ audio. See https://docs.htmlcsstoimage.com/parameters/output/
+ duration_mode: How duration_ms limits the timeline. Defaults to at_most. See
+ https://docs.htmlcsstoimage.com/parameters/duration_mode/
+ defer_render: Wait to render until media or storage is requested. Defaults to
+ false; does not reset deduplicated recordings. See
+ https://docs.htmlcsstoimage.com/parameters/defer_render/
+ skip_scroll_preload: Skip the preparation scroll that loads lazy content.
+ Scrolling actions still run. Defaults to false. See
+ https://docs.htmlcsstoimage.com/parameters/skip_scroll_preload/
+ """
+
+ css: str | None = None
+ device_scale: float | None = None
+ viewport_height: int | None = None
+ viewport_width: int | None = None
+ disable_twemoji: bool | None = None
+ dedupe_duration_s: int | None = None
+ color_scheme: ColorSchemeType | None = None
+ timezone: str | None = None
+ viewport_mobile: bool | None = None
+ viewport_landscape: bool | None = None
+ viewport_touch: bool | None = None
+ media_type: MediaType | None = None
+ proxy_id: str | None = None
+ storage_destination_id: str | None = None
+ request_overrides: list[RequestOverride] | None = None
+ duration_ms: int
+ trigger: RecordingTrigger | None = None
+ actions: list[RecordingAction] | None = None
+ output: RecordingOutputOptions | None = None
+ duration_mode: RecordingDurationMode | None = None
+ defer_render: bool | None = None
+ skip_scroll_preload: bool | None = None
+
+
+@dataclass(slots=True, kw_only=True)
+class CreateHtmlCssRecordingRequest(BaseCreateRecordingRequest):
+ """Record an HTML document or fragment with optional CSS and Google Fonts.
+
+ Attributes:
+ google_fonts: Google Fonts to load. Set font-family in your CSS to use them. See
+ https://docs.htmlcsstoimage.com/parameters/google_fonts/
+ html: HTML document or fragment to record. Fragments are rendered in a wrapper
+ document. See https://docs.htmlcsstoimage.com/parameters/html/
+ """
+
+ google_fonts: list[str] | tuple[str, ...] | None = None
+ html: str
+
+
+@dataclass(slots=True, kw_only=True)
+class CreateUrlRecordingRequest(BaseCreateRecordingRequest):
+ """Record a public HTTP or HTTPS webpage.
+
+ Attributes:
+ url: Public HTTP or HTTPS URL to record. See
+ https://docs.htmlcsstoimage.com/parameters/url/
+ block_consent_banners: Attempt to hide cookie and consent banners before
+ recording. See
+ https://docs.htmlcsstoimage.com/guides/advanced/blocking-cookie-banners/
+ identify_as_hcti: Add X-HCTI-SCREENSHOT: 1 to the top-level navigation. See
+ https://docs.htmlcsstoimage.com/parameters/identify_as_hcti/
+ headers: Custom headers for top-level navigations to the URL's origin and
+ additional_header_origins. See
+ https://docs.htmlcsstoimage.com/parameters/headers/
+ additional_header_origins: Additional exact HTTP or HTTPS origins allowed to
+ receive custom headers. See
+ https://docs.htmlcsstoimage.com/parameters/headers/#additional-header-origins
+ include_headers_on_subrequests: Send custom headers with subrequests to allowed
+ origins. Defaults to false. See
+ https://docs.htmlcsstoimage.com/parameters/headers/#include-headers-on-subrequests
+ """
+
+ url: str
+ block_consent_banners: bool | None = None
+ identify_as_hcti: bool | None = None
+ headers: Mapping[str, str] | None = None
+ additional_header_origins: list[str] | None = None
+ include_headers_on_subrequests: bool | None = None
+
+
+CreateRecordingRequest: TypeAlias = (
+ CreateHtmlCssRecordingRequest | CreateUrlRecordingRequest
+)
+
+
+@dataclass(frozen=True, slots=True)
+class CreateRecordingSuccessResponse:
+ """
+ Created or deduplicated recording.
+
+ Attributes:
+ id: Recording identifier.
+ status_url: Authenticated status endpoint. Checking status is optional.
+ recording_url: Media URL. Embed or request it directly; the request waits
+ until the recording is ready.
+ """
+
+ id: str
+ status_url: str
+ recording_url: str
+ success: Literal[True] = True
+
+
+@dataclass(frozen=True, slots=True)
+class RecordingError:
+ """
+ Error from an attempt. Check status to distinguish retries from failure.
+ """
+
+ code: str
+ message: str
+ occurred_at: str
+ retryable: bool
+ action_path: str | None = None
+
+
+@dataclass(frozen=True, slots=True)
+class RecordingStatusSuccessResponse:
+ """
+ Lifecycle information from HTTP 200 or 202, with ISO 8601 UTC timestamps.
+
+ ready, failed, and cancelled are terminal. A successful fetch can report a
+ failed recording; error can also describe an earlier, retryable attempt.
+ """
+
+ id: str
+ recording_url: str
+ status: RecordingStatus
+ status_entered_at: str
+ attempt_count: int
+ stored_duration_ms: int | None = None
+ storage_destination_hcti_storage_disabled: bool | None = None
+ error: RecordingError | None = None
+ success: Literal[True] = True
+
+
+CreateRecordingResponse: TypeAlias = CreateRecordingSuccessResponse | ApiErrorResponse
+RecordingStatusResponse: TypeAlias = RecordingStatusSuccessResponse | ApiErrorResponse
+DeleteRecordingSuccessResponse = DeleteImageSuccessResponse
+DeleteRecordingResponse: TypeAlias = DeleteImageResponse
diff --git a/tests/test_client.py b/tests/test_client.py
index 48a279a..e0aee3e 100644
--- a/tests/test_client.py
+++ b/tests/test_client.py
@@ -14,7 +14,6 @@
ApiErrorResponse,
CreateHtmlCssImageRequest,
CreateTemplatedImageRequest,
- TemplatedBatchImageOptions,
CreateUrlImageRequest,
DeleteImageSuccessResponse,
HtmlCssToImageClient,
@@ -30,6 +29,7 @@
RequestOverride,
RequestOverrideAction,
RequestOverrideResourceType,
+ TemplatedBatchImageOptions,
UnexpectedResponseError,
__version__,
)
@@ -51,7 +51,9 @@ def make_client(self, handler):
def test_template_batch_preserves_inheritance_and_nested_null(self):
defaults = TemplatedBatchImageOptions(
- template_id="t-card", template_version=3, format="webp",
+ template_id="t-card",
+ template_version=3,
+ format="webp",
template_values={"brand": {"name": "Acme", "color": "red"}},
)
variation = TemplatedBatchImageOptions(
@@ -60,24 +62,46 @@ def test_template_batch_preserves_inheritance_and_nested_null(self):
)
def handler(request):
- self.assertEqual(str(request.url), "https://hcti.io/v1/image/batch/templated")
+ self.assertEqual(
+ str(request.url), "https://hcti.io/v1/image/batch/templated"
+ )
self.assertEqual(request.method, "POST")
- self.assertEqual(json.loads(request.content), {
- "default_options": {
- "template_id": "t-card", "template_version": 3, "format": "webp",
- "template_values": {"brand": {"name": "Acme", "color": "red"}},
+ self.assertEqual(
+ json.loads(request.content),
+ {
+ "default_options": {
+ "template_id": "t-card",
+ "template_version": 3,
+ "format": "webp",
+ "template_values": {"brand": {"name": "Acme", "color": "red"}},
+ },
+ "variations": [
+ {},
+ {
+ "template_id": "t-other",
+ "template_values": {
+ "brand": {"color": None},
+ "tags": [],
+ "active": False,
+ },
+ },
+ ],
+ },
+ )
+ return httpx.Response(
+ 200,
+ json={
+ "images": [
+ {"id": "two", "url": "two"},
+ {"id": "one", "url": "one"},
+ ]
},
- "variations": [{}, {
- "template_id": "t-other",
- "template_values": {"brand": {"color": None}, "tags": [], "active": False},
- }],
- })
- return httpx.Response(200, json={"images": [
- {"id": "two", "url": "two"}, {"id": "one", "url": "one"},
- ]})
+ )
client = self.make_client(handler)
- result = client.create_templated_image_batch([TemplatedBatchImageOptions(), variation], defaults)
+ result = client.create_templated_image_batch(
+ [TemplatedBatchImageOptions(), variation], defaults
+ )
self.assertTrue(result.success)
self.assertEqual([image.id for image in result.images], ["two", "one"])
self.assertEqual(variation.template_version, None)
@@ -89,26 +113,34 @@ def test_template_batch_empty_and_error(self):
def handler(request):
calls.append(request)
self.assertNotIn("default_options", json.loads(request.content))
- return httpx.Response(400, json={"error": "Bad Request", "message": "Invalid template"})
+ return httpx.Response(
+ 400, json={"error": "Bad Request", "message": "Invalid template"}
+ )
client = self.make_client(handler)
self.assertTrue(client.create_templated_image_batch([]).success)
self.assertEqual(calls, [])
- result = client.create_templated_image_batch([TemplatedBatchImageOptions(template_id="t-missing")])
+ result = client.create_templated_image_batch(
+ [TemplatedBatchImageOptions(template_id="t-missing")]
+ )
self.assertFalse(result.success)
self.assertEqual(result.message, "Invalid template")
with self.assertRaises(TypeError):
- client.create_templated_image_batch([CreateUrlImageRequest(url="https://example.com")])
+ client.create_templated_image_batch(
+ [CreateUrlImageRequest(url="https://example.com")]
+ )
def test_request_overrides_serialize_enums_and_stay_out_of_signed_urls(self):
- rules = [RequestOverride(
- action=RequestOverrideAction.BLOCK,
- url="*.js",
- resource_types=[
- RequestOverrideResourceType.SCRIPT,
- RequestOverrideResourceType.FETCH,
- ],
- )]
+ rules = [
+ RequestOverride(
+ action=RequestOverrideAction.BLOCK,
+ url="*.js",
+ resource_types=[
+ RequestOverrideResourceType.SCRIPT,
+ RequestOverrideResourceType.FETCH,
+ ],
+ )
+ ]
def handler(request: httpx.Request) -> httpx.Response:
payload = json.loads(request.content)
@@ -539,6 +571,14 @@ def test_delete_batch_rejects_a_plain_string(self):
with self.assertRaisesRegex(TypeError, "image_ids"):
client.delete_image_batch("image-id")
+ def test_empty_delete_batch_does_not_send_request(self):
+ def handler(_request: httpx.Request) -> httpx.Response:
+ self.fail("An empty batch must not send an HTTP request")
+
+ client = self.make_client(handler)
+ self.assertTrue(client.delete_image_batch([]).success)
+ self.assertTrue(client.delete_image_batch(()).success)
+
def test_delete_image_and_batch(self):
requests: list[httpx.Request] = []
diff --git a/tests/test_recordings.py b/tests/test_recordings.py
new file mode 100644
index 0000000..da32221
--- /dev/null
+++ b/tests/test_recordings.py
@@ -0,0 +1,402 @@
+from __future__ import annotations
+
+import copy
+import json
+import unittest
+
+import httpx
+
+from html_css_to_image import (
+ ApiErrorResponse,
+ CoordinatesScrollTarget,
+ CreateHtmlCssRecordingRequest,
+ CreateRecordingSuccessResponse,
+ CreateUrlRecordingRequest,
+ HtmlCssToImageClient,
+ PositionScrollTarget,
+ RecordingClickAction,
+ RecordingElementVisibleTrigger,
+ RecordingErrorAction,
+ RecordingExecuteJavaScriptAction,
+ RecordingFunctionCallTrigger,
+ RecordingImmediateTrigger,
+ RecordingLocateSelectorAction,
+ RecordingOutputOptions,
+ RecordingScrollAction,
+ RecordingSimpleScrollAction,
+ RecordingStallAction,
+ RequestOverride,
+ RequestOverrideResourceType,
+ ScrollStep,
+ SelectorScrollTarget,
+ UnexpectedResponseError,
+)
+
+CREATED = {
+ "id": "recording-id",
+ "status_url": "https://hcti.io/v1/recordings/recording-id/status",
+ "recording_url": "https://hcti.io/v1/recording/recording-id.mp4",
+}
+
+
+class RecordingTests(unittest.TestCase):
+ def client(self, handler):
+ http = httpx.Client(transport=httpx.MockTransport(handler))
+ self.addCleanup(http.close)
+ return HtmlCssToImageClient("id", "key", http_client=http)
+
+ def test_html_creation_maps_fonts_and_preserves_input(self):
+ request = CreateHtmlCssRecordingRequest(
+ html="Hello
",
+ duration_ms=1000,
+ google_fonts=[" Roboto ", "Open Sans", "Open Sans"],
+ )
+ before = copy.deepcopy(request)
+
+ def handler(req):
+ self.assertEqual(req.method, "POST")
+ self.assertEqual(req.url.path, "/v1/recording")
+ self.assertEqual(req.headers["authorization"], "Basic aWQ6a2V5")
+ self.assertEqual(req.headers["content-type"], "application/json")
+ self.assertEqual(
+ json.loads(req.content),
+ {
+ "html": "Hello
",
+ "duration_ms": 1000,
+ "google_fonts": "Roboto|Open+Sans",
+ },
+ )
+ return httpx.Response(200, json=CREATED)
+
+ result = self.client(handler).create_recording(request)
+ self.assertIsInstance(result, CreateRecordingSuccessResponse)
+ self.assertEqual(result.id, "recording-id")
+ self.assertEqual(result.recording_url, CREATED["recording_url"])
+ self.assertEqual(result.status_url, CREATED["status_url"])
+ self.assertEqual(request, before)
+
+ def test_url_options_and_all_nested_action_types(self):
+ request = CreateUrlRecordingRequest(
+ url="https://example.com",
+ duration_ms=5000,
+ css="body { color: red; }",
+ device_scale=2,
+ viewport_width=1280,
+ viewport_height=720,
+ disable_twemoji=False,
+ dedupe_duration_s=0,
+ color_scheme="dark",
+ timezone="America/New_York",
+ viewport_mobile=False,
+ viewport_landscape=True,
+ viewport_touch=False,
+ media_type="screen",
+ proxy_id="proxy",
+ storage_destination_id="store",
+ headers={"Authorization": "Bearer test"},
+ additional_header_origins=["https://assets.example.com"],
+ include_headers_on_subrequests=False,
+ identify_as_hcti=True,
+ block_consent_banners=True,
+ request_overrides=[
+ RequestOverride(
+ resource_types=[RequestOverrideResourceType.SCRIPT],
+ )
+ ],
+ trigger=RecordingElementVisibleTrigger(selector="#ready"),
+ duration_mode="at_least",
+ defer_render=False,
+ skip_scroll_preload=True,
+ output=RecordingOutputOptions(format="webm", fps=60, scale=0.5),
+ actions=[
+ RecordingLocateSelectorAction(
+ selector="#modal",
+ if_not_found=[],
+ if_found=[
+ RecordingClickAction(
+ selector="#close",
+ button="right",
+ count=2,
+ offset_x=0,
+ offset_y=-1,
+ delay_ms=0,
+ if_not_found=[RecordingErrorAction()],
+ )
+ ],
+ ),
+ RecordingExecuteJavaScriptAction(script="await Promise.resolve();"),
+ RecordingExecuteJavaScriptAction(script="throw Error();", if_error=[]),
+ RecordingScrollAction(
+ steps=[
+ ScrollStep(
+ to=PositionScrollTarget(position="bottom"), duration_ms=500
+ ),
+ ScrollStep(
+ to=CoordinatesScrollTarget(x=0, y=200),
+ duration_ms=800,
+ easing="ease_in_out_cubic",
+ ),
+ ScrollStep(
+ to=SelectorScrollTarget(
+ selector="#footer",
+ offset_y=-40,
+ if_not_found=[],
+ ),
+ duration_ms=750,
+ ),
+ ],
+ if_not_found=[RecordingStallAction(duration_ms=0)],
+ ),
+ RecordingSimpleScrollAction(scroll_distance="90vh"),
+ RecordingSimpleScrollAction(scroll_distance=900),
+ ],
+ )
+ before = copy.deepcopy(request)
+
+ def handler(req):
+ data = json.loads(req.content)
+ for key, expected in {
+ "viewport_width": 1280,
+ "viewport_height": 720,
+ "device_scale": 2,
+ "dedupe_duration_s": 0,
+ "disable_twemoji": False,
+ "color_scheme": "dark",
+ "timezone": "America/New_York",
+ "viewport_mobile": False,
+ "viewport_landscape": True,
+ "viewport_touch": False,
+ "media_type": "screen",
+ "proxy_id": "proxy",
+ "storage_destination_id": "store",
+ "defer_render": False,
+ "skip_scroll_preload": True,
+ "duration_mode": "at_least",
+ "headers": {"Authorization": "Bearer test"},
+ "include_headers_on_subrequests": False,
+ "identify_as_hcti": True,
+ "block_consent_banners": True,
+ }.items():
+ self.assertEqual(data[key], expected)
+ self.assertEqual(
+ data["output"],
+ {
+ "format": "webm",
+ "fps": 60,
+ "scale": 0.5,
+ },
+ )
+ self.assertEqual(data["trigger"]["type"], "element_visible")
+ self.assertEqual(
+ data["request_overrides"],
+ [
+ {
+ "action": "block",
+ "resource_types": ["script"],
+ }
+ ],
+ )
+ actions = data["actions"]
+ self.assertEqual(actions[0]["if_not_found"], [])
+ self.assertEqual(actions[0]["if_found"][0]["type"], "click")
+ self.assertEqual(
+ actions[0]["if_found"][0]["if_not_found"],
+ [
+ {
+ "type": "error",
+ }
+ ],
+ )
+ self.assertNotIn("if_error", actions[1])
+ self.assertEqual(actions[2]["if_error"], [])
+ self.assertEqual(
+ [step["to"]["type"] for step in actions[3]["steps"]],
+ [
+ "position",
+ "coordinates",
+ "selector",
+ ],
+ )
+ self.assertEqual(
+ [step["duration_ms"] for step in actions[3]["steps"]], [500, 800, 750]
+ )
+ self.assertEqual(actions[4]["scroll_distance"], "90vh")
+ self.assertEqual(actions[5]["scroll_distance"], 900)
+ return httpx.Response(200, json=CREATED)
+
+ self.assertTrue(self.client(handler).create_recording(request).success)
+ self.assertEqual(request, before)
+
+ def test_optional_settings_and_triggers_use_api_defaults(self):
+ for trigger in [
+ None,
+ RecordingImmediateTrigger(),
+ RecordingFunctionCallTrigger(timeout_ms=1000),
+ ]:
+ with self.subTest(trigger=trigger):
+
+ def handler(req):
+ data = json.loads(req.content)
+ self.assertEqual(data["duration_ms"], 0)
+ self.assertNotIn("output", data)
+ if trigger is None:
+ self.assertNotIn("trigger", data)
+ else:
+ self.assertEqual(data["trigger"]["type"], trigger.type)
+ return httpx.Response(400, json={"error": "Bad Request"})
+
+ result = self.client(handler).create_recording(
+ CreateHtmlCssRecordingRequest(
+ html="", duration_ms=0, trigger=trigger
+ ),
+ )
+ self.assertFalse(result.success)
+
+ def test_status_accepts_200_and_202_and_preserves_attempt_error(self):
+ for status in [
+ "awaiting_render",
+ "processing",
+ "pending_retry",
+ "ready",
+ "failed",
+ "cancelled",
+ ]:
+ with self.subTest(status=status):
+ data = {
+ "id": "recording-id",
+ "recording_url": CREATED["recording_url"],
+ "status": status,
+ "status_entered_at": "2026-11-16T10:00:00Z",
+ "attempt_count": 2,
+ "stored_duration_ms": None,
+ "storage_destination_hcti_storage_disabled": None,
+ "error": {
+ "code": "action_error",
+ "message": "Missing element",
+ "occurred_at": "2026-11-16T09:59:00Z",
+ "retryable": True,
+ "action_path": "actions[1]",
+ },
+ }
+
+ def handler(req):
+ self.assertEqual(req.method, "GET")
+ self.assertEqual(req.url.path, "/v1/recordings/recording-id/status")
+ self.assertEqual(req.content, b"")
+ return httpx.Response(
+ 202
+ if status in ("processing", "pending_retry", "awaiting_render")
+ else 200,
+ json=data,
+ )
+
+ result = self.client(handler).fetch_recording_status("recording-id")
+ self.assertTrue(result.success)
+ self.assertEqual(result.status, status)
+ self.assertEqual(result.attempt_count, 2)
+ self.assertIsNone(result.stored_duration_ms)
+ self.assertEqual(result.error.action_path, "actions[1]")
+ self.assertTrue(result.error.retryable)
+
+ def test_status_maps_unrecognized_value_to_unknown(self):
+ data = {
+ "id": "recording-id",
+ "recording_url": CREATED["recording_url"],
+ "status": "some_future_status",
+ "status_entered_at": "2026-11-16T10:00:00Z",
+ "attempt_count": 1,
+ }
+
+ result = self.client(
+ lambda req: httpx.Response(202, json=data)
+ ).fetch_recording_status("recording-id")
+ self.assertTrue(result.success)
+ self.assertEqual(result.status, "unknown")
+
+ def test_scroll_step_requires_duration_ms(self):
+ with self.assertRaises(TypeError):
+ ScrollStep(to=PositionScrollTarget(position="bottom"))
+
+ def test_deletes_accept_empty_success_bodies(self):
+ calls = []
+
+ def handler(req):
+ self.assertEqual(req.method, "DELETE")
+ self.assertEqual(req.headers["authorization"], "Basic aWQ6a2V5")
+ calls.append((req.url.path, req.content))
+ return httpx.Response(202)
+
+ client = self.client(handler)
+ self.assertTrue(client.delete_recording("recording-id").success)
+ self.assertTrue(client.delete_recording_batch(("one", "two")).success)
+ self.assertEqual(calls[0], ("/v1/recordings/recording-id", b""))
+ self.assertEqual(json.loads(calls[1][1]), {"ids": ["one", "two"]})
+
+ def test_empty_delete_batch_does_not_send_request(self):
+ def handler(req):
+ self.fail("An empty batch must not send an HTTP request")
+
+ client = self.client(handler)
+ self.assertTrue(client.delete_recording_batch([]).success)
+ self.assertTrue(client.delete_recording_batch(()).success)
+
+ def test_delete_batch_rejects_non_list_or_non_string_ids(self):
+ def handler(req):
+ self.fail("Invalid input must not send an HTTP request")
+
+ client = self.client(handler)
+ for recording_ids in ["recording-id", {"recording-id"}, ["one", 2]]:
+ with self.subTest(recording_ids=recording_ids):
+ with self.assertRaisesRegex(TypeError, "recording_ids"):
+ client.delete_recording_batch(recording_ids)
+
+ def operations(self, client):
+ return [
+ lambda: client.create_recording(
+ CreateUrlRecordingRequest(
+ url="https://example.com",
+ duration_ms=1000,
+ )
+ ),
+ lambda: client.fetch_recording_status("recording-id"),
+ lambda: client.delete_recording("recording-id"),
+ lambda: client.delete_recording_batch(["recording-id"]),
+ ]
+
+ def test_all_methods_reuse_api_error_and_transport_contracts(self):
+ for json_body in [
+ {"error": "Forbidden", "message": "Missing permission"},
+ None,
+ ]:
+
+ def handler(req):
+ return (
+ httpx.Response(403, json=json_body)
+ if json_body
+ else httpx.Response(502, text="Unavailable")
+ )
+
+ for call in self.operations(self.client(handler)):
+ result = call()
+ self.assertIsInstance(result, ApiErrorResponse)
+ self.assertFalse(result.success)
+ self.assertEqual(result.status_code, 403 if json_body else 502)
+
+ def failing(req):
+ raise httpx.ReadTimeout("timeout", request=req)
+
+ for call in self.operations(self.client(failing)):
+ with self.assertRaises(httpx.ReadTimeout):
+ call()
+
+ def test_malformed_success_uses_existing_exception(self):
+ client = self.client(lambda req: httpx.Response(200, json={}))
+ with self.assertRaises(UnexpectedResponseError):
+ client.create_recording(
+ CreateUrlRecordingRequest(
+ url="https://example.com",
+ duration_ms=1000,
+ )
+ )
+ with self.assertRaises(UnexpectedResponseError):
+ client.fetch_recording_status("recording-id")