pi-image-preview 0.1.5 → 0.2.0

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,55 @@
1
+ import type { ImageContent } from "./content.ts";
2
+
3
+ /** Providers reject images larger than ~5 MB per image, measured on the base64
4
+ * payload sent over the wire. Cap the full-size attachment (distinct from the
5
+ * tiny gallery thumbnail) a little below that hard wall for headroom. */
6
+ export const SUBMISSION_MAX_BYTES = 4.5 * 1024 * 1024;
7
+ /** Keep the attachment high-resolution — only bound it below the API pixel
8
+ * limit so quality is preserved while the byte cap does the real shrinking. */
9
+ export const SUBMISSION_MAX_DIMENSION = 8000;
10
+
11
+ type ResizedImage = { data: string; mimeType: string };
12
+
13
+ export interface SubmissionResizeDeps {
14
+ /** Resize raw image bytes within the given bounds (pi's WASM resizer). */
15
+ resizeImage: (
16
+ bytes: Uint8Array,
17
+ mimeType: string,
18
+ options: { maxWidth: number; maxHeight: number; maxBytes: number },
19
+ ) => Promise<ResizedImage | null>;
20
+ }
21
+
22
+ /**
23
+ * Downscale the full-resolution image so the submitted attachment stays under
24
+ * the provider's per-image byte limit. The original format is preserved (no
25
+ * PNG conversion); images already within the cap are returned unchanged.
26
+ */
27
+ export async function resizeForSubmission(
28
+ image: ImageContent,
29
+ deps: SubmissionResizeDeps,
30
+ ): Promise<ImageContent> {
31
+ try {
32
+ // Gate on the encoded payload — the axis the provider's limit applies to.
33
+ // base64 is ASCII, so the string length equals its byte size.
34
+ if (image.data.length <= SUBMISSION_MAX_BYTES) return image;
35
+ const bytes = Buffer.from(image.data, "base64");
36
+ const resized = await deps.resizeImage(bytes, image.mimeType, {
37
+ maxWidth: SUBMISSION_MAX_DIMENSION,
38
+ maxHeight: SUBMISSION_MAX_DIMENSION,
39
+ maxBytes: SUBMISSION_MAX_BYTES,
40
+ });
41
+ if (!resized) {
42
+ console.warn(
43
+ `[image-preview] could not downscale a ${(image.data.length / 1024 / 1024).toFixed(1)}MB attachment below the ${(SUBMISSION_MAX_BYTES / 1024 / 1024).toFixed(1)}MB limit; submitting it unchanged`,
44
+ );
45
+ return image;
46
+ }
47
+ return { type: "image", data: resized.data, mimeType: resized.mimeType };
48
+ } catch (err) {
49
+ console.warn(
50
+ "[image-preview] failed to downscale an oversized attachment; submitting it unchanged",
51
+ err,
52
+ );
53
+ return image;
54
+ }
55
+ }