html-css-to-image 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,600 @@
1
+ """Typed request and response models for the HTML/CSS to Image API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from dataclasses import dataclass
7
+ from typing import Any, Literal, TypeAlias
8
+
9
+ ColorSchemeType: TypeAlias = Literal["light", "dark"]
10
+ MediaType: TypeAlias = Literal["print", "screen"]
11
+ PDFUnit: TypeAlias = Literal["px", "in", "cm", "mm"]
12
+ RenderImageCropOrigin: TypeAlias = Literal["start", "center", "end"]
13
+ ImageFormat: TypeAlias = Literal["png", "jpg", "webp", "pdf"]
14
+ RenderImageFormat: TypeAlias = ImageFormat
15
+ RenderImageValueUnit: TypeAlias = Literal["px", "%"]
16
+
17
+
18
+ def _validate_string_collection(
19
+ name: str,
20
+ value: list[str] | tuple[str, ...] | None,
21
+ ) -> None:
22
+ if value is None:
23
+ return
24
+ if not isinstance(value, (list, tuple)) or any(
25
+ not isinstance(item, str) for item in value
26
+ ):
27
+ raise TypeError(f"{name} must be a list or tuple of strings")
28
+
29
+
30
+ @dataclass(slots=True)
31
+ class PDFValueWithUnits:
32
+ """A numeric PDF dimension paired with an explicit unit.
33
+
34
+ Attributes:
35
+ value: Numeric magnitude of the dimension.
36
+ unit: Unit used by the dimension: ``px``, ``in``, ``cm``, or ``mm``.
37
+ """
38
+
39
+ value: int | float
40
+ unit: PDFUnit
41
+
42
+
43
+ PDFValueInput: TypeAlias = int | float | PDFValueWithUnits
44
+
45
+
46
+ @dataclass(slots=True)
47
+ class PDFMargins:
48
+ """Margins applied to a generated PDF.
49
+
50
+ Plain numbers are interpreted as pixels. Use :class:`PDFValueWithUnits`
51
+ when a margin should use inches, centimeters, or millimeters.
52
+
53
+ Attributes:
54
+ top: Top page margin.
55
+ right: Right page margin.
56
+ bottom: Bottom page margin.
57
+ left: Left page margin.
58
+ """
59
+
60
+ top: PDFValueInput
61
+ right: PDFValueInput
62
+ bottom: PDFValueInput
63
+ left: PDFValueInput
64
+
65
+
66
+ @dataclass(slots=True)
67
+ class PDFOptions:
68
+ """Options that cause the API to render a PDF instead of an image.
69
+
70
+ Attributes:
71
+ print_background: Include CSS background graphics in the PDF.
72
+ scale: Scale applied to the rendered page.
73
+ margins: Page margins in top, right, bottom, left order.
74
+ page_height: Page height. Plain numbers are interpreted as pixels.
75
+ page_width: Page width. Plain numbers are interpreted as pixels.
76
+ """
77
+
78
+ print_background: bool | None = None
79
+ scale: int | float | None = None
80
+ margins: PDFMargins | None = None
81
+ page_height: PDFValueInput | None = None
82
+ page_width: PDFValueInput | None = None
83
+
84
+
85
+ @dataclass(slots=True, kw_only=True)
86
+ class BaseCreateImageRequest:
87
+ """Options shared by HTML/CSS and URL screenshot requests.
88
+
89
+ All attributes are optional. Unset values are omitted from the API
90
+ payload.
91
+
92
+ Attributes:
93
+ format: File format used in the URL returned by the API.
94
+ selector: CSS selector to crop the image to a specific element.
95
+ device_scale: Browser device scale factor. The API default is ``2``.
96
+ viewport_height: Browser viewport height in pixels.
97
+ viewport_width: Browser viewport width in pixels.
98
+ max_wait_ms: Maximum time the renderer may wait before capture.
99
+ ms_delay: Additional delay before capture, in milliseconds.
100
+ render_when_ready: Wait for ``ScreenshotReady()`` in page JavaScript.
101
+ max_render_once: Ensure that the image is rendered and saved once.
102
+ disable_twemoji: Disable the Twemoji fallback renderer.
103
+ color_scheme: Emulate the ``light`` or ``dark`` color scheme.
104
+ timezone: IANA timezone name used by the browser.
105
+ viewport_mobile: Emulate a mobile viewport.
106
+ viewport_touch: Enable touch interactions in the viewport.
107
+ viewport_landscape: Render the viewport in landscape orientation.
108
+ media_type: Emulate ``print`` or ``screen`` CSS media.
109
+ proxy_id: Organization proxy identifier used for rendering.
110
+ jumbo_max_width: Maximum width for jumbo rendering.
111
+ jumbo_max_height: Maximum height for jumbo rendering.
112
+ dedupe_duration_s: Reuse a matching recently generated image for up
113
+ to this many seconds. Supported only for single POST requests,
114
+ not batches, templates, or signed URLs.
115
+ storage_destination_id: Storage destination configured in HCTI.
116
+ transparent_background: Render the page background as transparent.
117
+ pdf_options: PDF-specific output options.
118
+ """
119
+
120
+ format: ImageFormat | None = None
121
+ selector: str | None = None
122
+ device_scale: int | float | None = None
123
+ viewport_height: int | None = None
124
+ viewport_width: int | None = None
125
+ max_wait_ms: int | None = None
126
+ ms_delay: int | None = None
127
+ render_when_ready: bool | None = None
128
+ max_render_once: bool | None = None
129
+ disable_twemoji: bool | None = None
130
+ color_scheme: ColorSchemeType | None = None
131
+ timezone: str | None = None
132
+ viewport_mobile: bool | None = None
133
+ viewport_touch: bool | None = None
134
+ viewport_landscape: bool | None = None
135
+ media_type: MediaType | None = None
136
+ proxy_id: str | None = None
137
+ jumbo_max_width: int | None = None
138
+ jumbo_max_height: int | None = None
139
+ dedupe_duration_s: int | None = None
140
+ storage_destination_id: str | None = None
141
+ transparent_background: bool | None = None
142
+ pdf_options: PDFOptions | None = None
143
+
144
+
145
+ @dataclass(slots=True, kw_only=True)
146
+ class CreateHtmlCssImageRequest(BaseCreateImageRequest):
147
+ """Request to render an image from an HTML string and optional CSS.
148
+
149
+ ``html`` defaults to an empty string so a batch variation can inherit the
150
+ HTML supplied by its batch defaults.
151
+
152
+ Attributes:
153
+ html: Raw HTML content to render.
154
+ css: Optional CSS rules applied to the HTML.
155
+ google_fonts: Google Font family names to load before rendering.
156
+
157
+ Raises:
158
+ TypeError: If ``google_fonts`` is not a list or tuple of strings.
159
+ """
160
+
161
+ html: str = ""
162
+ css: str | None = None
163
+ google_fonts: list[str] | tuple[str, ...] | None = None
164
+
165
+ def __post_init__(self) -> None:
166
+ """Validate collection fields that Python would otherwise treat as strings."""
167
+
168
+ _validate_string_collection("google_fonts", self.google_fonts)
169
+
170
+
171
+ @dataclass(slots=True, kw_only=True)
172
+ class CreateUrlImageRequest(BaseCreateImageRequest):
173
+ """Request to capture a screenshot of a URL.
174
+
175
+ ``url`` defaults to an empty string so a batch variation can inherit the
176
+ URL supplied by its batch defaults.
177
+
178
+ Attributes:
179
+ url: Public URL for the renderer to capture.
180
+ css: Optional CSS injected into the target page.
181
+ headers: HTTP headers sent to the target URL. Keep secrets out of
182
+ signed URLs because signed query parameters remain visible.
183
+ additional_header_origins: Exact additional origins that may receive
184
+ ``headers`` on subrequests.
185
+ include_headers_on_subrequests: Also send ``headers`` to same-origin
186
+ subrequests made while the page loads.
187
+ identify_as_hcti: Add HCTI's identifying request header.
188
+ full_screen: Capture the entire scrollable page.
189
+ block_consent_banners: Attempt to hide cookie and consent banners.
190
+
191
+ Raises:
192
+ TypeError: If ``additional_header_origins`` is not a list or tuple of
193
+ strings.
194
+ """
195
+
196
+ url: str = ""
197
+ css: str | None = None
198
+ headers: Mapping[str, str] | None = None
199
+ additional_header_origins: list[str] | tuple[str, ...] | None = None
200
+ include_headers_on_subrequests: bool | None = None
201
+ identify_as_hcti: bool | None = None
202
+ full_screen: bool | None = None
203
+ block_consent_banners: bool | None = None
204
+
205
+ def __post_init__(self) -> None:
206
+ """Validate collection fields that Python would otherwise treat as strings."""
207
+
208
+ _validate_string_collection(
209
+ "additional_header_origins",
210
+ self.additional_header_origins,
211
+ )
212
+
213
+
214
+ @dataclass(slots=True, kw_only=True)
215
+ class CreateTemplatedImageRequest:
216
+ """Request to render a saved HCTI template.
217
+
218
+ Attributes:
219
+ template_id: Identifier of the template to render.
220
+ template_values: Values substituted into the template variables.
221
+ template_version: Optional template version. The latest is used when
222
+ omitted.
223
+ format: File format used in the URL returned by the API.
224
+ """
225
+
226
+ template_id: str
227
+ template_values: Mapping[str, Any]
228
+ template_version: int | None = None
229
+ format: ImageFormat | None = None
230
+
231
+
232
+ CreateImageRequest: TypeAlias = (
233
+ CreateHtmlCssImageRequest | CreateUrlImageRequest | CreateTemplatedImageRequest
234
+ )
235
+ BatchCreateImageRequest: TypeAlias = CreateHtmlCssImageRequest | CreateUrlImageRequest
236
+
237
+
238
+ @dataclass(frozen=True, slots=True)
239
+ class ValidationError:
240
+ """A validation error associated with one request field.
241
+
242
+ Attributes:
243
+ path: API field path that failed validation.
244
+ message: Human-readable validation message.
245
+ """
246
+
247
+ path: str
248
+ message: str
249
+
250
+
251
+ @dataclass(frozen=True, slots=True)
252
+ class CreateImageSuccessResponse:
253
+ """Successful image creation response.
254
+
255
+ Attributes:
256
+ success: Always ``True`` for this response type.
257
+ id: Identifier assigned to the generated image.
258
+ url: URL from which the generated image can be retrieved.
259
+ """
260
+
261
+ id: str
262
+ url: str
263
+ success: Literal[True] = True
264
+
265
+
266
+ @dataclass(frozen=True, slots=True)
267
+ class ApiErrorResponse:
268
+ """Unsuccessful API response.
269
+
270
+ Network and timeout failures are raised by HTTPX and do not produce this
271
+ response type.
272
+
273
+ Attributes:
274
+ status_code: HTTP status code returned by the API.
275
+ error: Short API error name.
276
+ message: Optional human-readable error details.
277
+ validation_errors: Field-level validation failures, when supplied.
278
+ success: Always ``False`` for this response type.
279
+ """
280
+
281
+ status_code: int
282
+ error: str
283
+ message: str | None = None
284
+ validation_errors: tuple[ValidationError, ...] | None = None
285
+ success: Literal[False] = False
286
+
287
+
288
+ @dataclass(frozen=True, slots=True)
289
+ class CreateImageBatchSuccessResponse:
290
+ """Successful batch image creation response.
291
+
292
+ Attributes:
293
+ images: Results returned for each batch variation.
294
+ success: Always ``True`` for this response type.
295
+ """
296
+
297
+ images: tuple[CreateImageSuccessResponse, ...]
298
+ success: Literal[True] = True
299
+
300
+
301
+ @dataclass(frozen=True, slots=True)
302
+ class DeleteImageSuccessResponse:
303
+ """Successful image deletion response.
304
+
305
+ Attributes:
306
+ success: Always ``True`` for this response type.
307
+ """
308
+
309
+ success: Literal[True] = True
310
+
311
+
312
+ CreateImageResponse: TypeAlias = CreateImageSuccessResponse | ApiErrorResponse
313
+ CreateImageBatchResponse: TypeAlias = (
314
+ CreateImageBatchSuccessResponse | ApiErrorResponse
315
+ )
316
+ DeleteImageResponse: TypeAlias = DeleteImageSuccessResponse | ApiErrorResponse
317
+
318
+
319
+ @dataclass(frozen=True, slots=True)
320
+ class RenderImageCropPosition:
321
+ """A crop boundary expressed in pixels or as a percentage.
322
+
323
+ Use :meth:`pixels` or :meth:`percent` to construct a validated value.
324
+
325
+ Attributes:
326
+ value: Non-negative pixel position or percentage from 1 through 100.
327
+ unit: ``px`` or ``%``.
328
+ """
329
+
330
+ value: int
331
+ unit: RenderImageValueUnit
332
+
333
+ def __post_init__(self) -> None:
334
+ if self.unit not in ("px", "%"):
335
+ raise ValueError("A crop position unit must be px or %")
336
+ if self.unit == "px" and self.value < 0:
337
+ raise ValueError("A pixel crop position cannot be negative")
338
+ if self.unit == "%" and not 1 <= self.value <= 100:
339
+ raise ValueError("A percentage crop position must be from 1 to 100")
340
+
341
+ @classmethod
342
+ def pixels(cls, value: int) -> RenderImageCropPosition:
343
+ """Create a crop position measured in pixels."""
344
+
345
+ return cls(value, "px")
346
+
347
+ @classmethod
348
+ def percent(cls, value: int) -> RenderImageCropPosition:
349
+ """Create a crop position measured as a percentage."""
350
+
351
+ return cls(value, "%")
352
+
353
+
354
+ @dataclass(frozen=True, slots=True)
355
+ class RenderImageCropSize:
356
+ """A crop width or height expressed in pixels or as a percentage.
357
+
358
+ Use :meth:`pixels` or :meth:`percent` to construct a validated value.
359
+
360
+ Attributes:
361
+ value: Positive size value.
362
+ unit: ``px`` or ``%``.
363
+ """
364
+
365
+ value: int
366
+ unit: RenderImageValueUnit
367
+
368
+ def __post_init__(self) -> None:
369
+ if self.unit not in ("px", "%"):
370
+ raise ValueError("A crop size unit must be px or %")
371
+ if self.unit == "px" and self.value <= 0:
372
+ raise ValueError("A pixel crop size must be positive")
373
+ if self.unit == "%" and not 1 <= self.value <= 100:
374
+ raise ValueError("A percentage crop size must be from 1 to 100")
375
+
376
+ @classmethod
377
+ def pixels(cls, value: int) -> RenderImageCropSize:
378
+ """Create a crop size measured in pixels."""
379
+
380
+ return cls(value, "px")
381
+
382
+ @classmethod
383
+ def percent(cls, value: int) -> RenderImageCropSize:
384
+ """Create a crop size measured as a percentage."""
385
+
386
+ return cls(value, "%")
387
+
388
+
389
+ @dataclass(frozen=True, slots=True)
390
+ class RenderImageAspectRatio:
391
+ """Positive width and height components of a crop aspect ratio.
392
+
393
+ Attributes:
394
+ width: Positive width component, such as ``16`` in ``16:9``.
395
+ height: Positive height component, such as ``9`` in ``16:9``.
396
+ """
397
+
398
+ width: int
399
+ height: int
400
+
401
+ def __post_init__(self) -> None:
402
+ if self.width <= 0 or self.height <= 0:
403
+ raise ValueError("Aspect ratio width and height must be positive")
404
+
405
+
406
+ @dataclass(frozen=True, slots=True)
407
+ class RenderImageCropSpan:
408
+ """Crop instructions for one axis.
409
+
410
+ Prefer the named constructors because they describe the intended crop:
411
+ :meth:`from_position`, :meth:`between`, :meth:`sized_from`, or
412
+ :meth:`sized`.
413
+
414
+ Attributes:
415
+ start: Optional first crop boundary.
416
+ end: Optional second crop boundary.
417
+ size: Optional crop width or height.
418
+ origin: Origin used when ``size`` is supplied without ``start``.
419
+ """
420
+
421
+ start: RenderImageCropPosition | None = None
422
+ end: RenderImageCropPosition | None = None
423
+ size: RenderImageCropSize | None = None
424
+ origin: RenderImageCropOrigin = "start"
425
+
426
+ def __post_init__(self) -> None:
427
+ if self.origin not in ("start", "center", "end"):
428
+ raise ValueError("Crop origin must be start, center, or end")
429
+ if self.start is None and self.size is None:
430
+ raise ValueError("A crop span requires a start position or size")
431
+ if self.end is not None and self.start is None:
432
+ raise ValueError("A crop end requires a start position")
433
+ if self.end is not None and self.size is not None:
434
+ raise ValueError("A crop span cannot have both an end and a size")
435
+ if self.end is not None:
436
+ start = self.start
437
+ if start is None:
438
+ raise ValueError("A crop end requires a start position")
439
+ if self.end.unit == start.unit and self.end.value <= start.value:
440
+ raise ValueError("Crop end must be greater than crop start")
441
+ if self.start is not None and self.origin != "start":
442
+ raise ValueError("Crop origin is only used by a size without a start")
443
+
444
+ @classmethod
445
+ def from_position(
446
+ cls,
447
+ position: RenderImageCropPosition,
448
+ ) -> RenderImageCropSpan:
449
+ """Crop from ``position`` through the remaining image."""
450
+
451
+ return cls(start=position)
452
+
453
+ @classmethod
454
+ def between(
455
+ cls,
456
+ start: RenderImageCropPosition,
457
+ end: RenderImageCropPosition,
458
+ ) -> RenderImageCropSpan:
459
+ """Crop between two positions, which may use different units."""
460
+
461
+ return cls(start=start, end=end)
462
+
463
+ @classmethod
464
+ def sized_from(
465
+ cls,
466
+ start: RenderImageCropPosition,
467
+ size: RenderImageCropSize,
468
+ ) -> RenderImageCropSpan:
469
+ """Crop a fixed size beginning at ``start``."""
470
+
471
+ return cls(start=start, size=size)
472
+
473
+ @classmethod
474
+ def sized(
475
+ cls,
476
+ size: RenderImageCropSize,
477
+ origin: RenderImageCropOrigin = "start",
478
+ ) -> RenderImageCropSpan:
479
+ """Crop ``size`` from the start, center, or end of an axis."""
480
+
481
+ return cls(size=size, origin=origin)
482
+
483
+
484
+ @dataclass(frozen=True, slots=True)
485
+ class RenderImageCrop:
486
+ """Rectangle or aspect-ratio crop applied when an image URL is fetched.
487
+
488
+ Use :meth:`rectangle`, :meth:`aspect_ratio_from_width`, or
489
+ :meth:`aspect_ratio_from_height` to create a crop.
490
+
491
+ Attributes:
492
+ horizontal: Horizontal crop span, when explicitly supplied.
493
+ vertical: Vertical crop span, when explicitly supplied.
494
+ aspect_ratio: Optional output aspect ratio.
495
+ aspect_ratio_axis: Axis whose span determines the aspect-ratio crop.
496
+ computed_origin: Origin on the axis calculated from the aspect ratio.
497
+ """
498
+
499
+ horizontal: RenderImageCropSpan | None = None
500
+ vertical: RenderImageCropSpan | None = None
501
+ aspect_ratio: RenderImageAspectRatio | None = None
502
+ aspect_ratio_axis: Literal["width", "height"] | None = None
503
+ computed_origin: RenderImageCropOrigin = "start"
504
+
505
+ def __post_init__(self) -> None:
506
+ if self.computed_origin not in ("start", "center", "end"):
507
+ raise ValueError("Crop origin must be start, center, or end")
508
+ if self.aspect_ratio is None:
509
+ if self.horizontal is None and self.vertical is None:
510
+ raise ValueError("A rectangle crop requires at least one axis")
511
+ if self.aspect_ratio_axis is not None:
512
+ raise ValueError("A rectangle crop cannot set an aspect-ratio axis")
513
+ if self.computed_origin != "start":
514
+ raise ValueError("A rectangle crop cannot set a computed origin")
515
+ return
516
+
517
+ if self.aspect_ratio_axis == "width":
518
+ if self.horizontal is None or self.vertical is not None:
519
+ raise ValueError("A width-based aspect crop requires a horizontal span")
520
+ elif self.aspect_ratio_axis == "height":
521
+ if self.vertical is None or self.horizontal is not None:
522
+ raise ValueError("A height-based aspect crop requires a vertical span")
523
+ else:
524
+ raise ValueError("An aspect-ratio crop requires a width or height axis")
525
+
526
+ @classmethod
527
+ def rectangle(
528
+ cls,
529
+ *,
530
+ horizontal: RenderImageCropSpan | None = None,
531
+ vertical: RenderImageCropSpan | None = None,
532
+ ) -> RenderImageCrop:
533
+ """Create a rectangular crop from one or two axis spans."""
534
+
535
+ return cls(horizontal=horizontal, vertical=vertical)
536
+
537
+ @classmethod
538
+ def aspect_ratio_from_width(
539
+ cls,
540
+ aspect_ratio: RenderImageAspectRatio,
541
+ horizontal: RenderImageCropSpan,
542
+ *,
543
+ height_origin: RenderImageCropOrigin = "start",
544
+ ) -> RenderImageCrop:
545
+ """Calculate crop height from a ratio and horizontal span."""
546
+
547
+ return cls(
548
+ horizontal=horizontal,
549
+ aspect_ratio=aspect_ratio,
550
+ aspect_ratio_axis="width",
551
+ computed_origin=height_origin,
552
+ )
553
+
554
+ @classmethod
555
+ def aspect_ratio_from_height(
556
+ cls,
557
+ aspect_ratio: RenderImageAspectRatio,
558
+ vertical: RenderImageCropSpan,
559
+ *,
560
+ width_origin: RenderImageCropOrigin = "start",
561
+ ) -> RenderImageCrop:
562
+ """Calculate crop width from a ratio and vertical span."""
563
+
564
+ return cls(
565
+ vertical=vertical,
566
+ aspect_ratio=aspect_ratio,
567
+ aspect_ratio_axis="height",
568
+ computed_origin=width_origin,
569
+ )
570
+
571
+
572
+ @dataclass(frozen=True, slots=True)
573
+ class RenderImageOptions:
574
+ """Options applied when an HCTI image URL is retrieved.
575
+
576
+ Cropping happens before output resizing. These options also work with
577
+ signed template and create-and-render URLs.
578
+
579
+ Attributes:
580
+ format: Optional output format: ``png``, ``jpg``, ``webp``, or ``pdf``.
581
+ dpi: Output DPI from 31 through 599.
582
+ height: Output height from 1 through 5000 pixels.
583
+ width: Output width from 1 through 5000 pixels.
584
+ crop: Optional crop instructions applied before resizing.
585
+ """
586
+
587
+ format: ImageFormat | None = None
588
+ dpi: int | None = None
589
+ height: int | None = None
590
+ width: int | None = None
591
+ crop: RenderImageCrop | None = None
592
+
593
+ def __post_init__(self) -> None:
594
+ if self.format not in (None, "png", "jpg", "webp", "pdf"):
595
+ raise ValueError("Render format must be png, jpg, webp, or pdf")
596
+ if self.dpi is not None and not 30 < self.dpi < 600:
597
+ raise ValueError("DPI must be greater than 30 and less than 600")
598
+ for name, value in (("height", self.height), ("width", self.width)):
599
+ if value is not None and not 1 <= value <= 5000:
600
+ raise ValueError(f"Render {name} must be from 1 to 5000 pixels")
@@ -0,0 +1 @@
1
+