Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

composerImages.ts

722 lines22.8 KB

1import {
2 clampFileAttachmentUploadBytes,
3 fileAttachmentTooLargeMessage,
4} from "@t3tools/client-runtime/state/attachments";
5import {
6 isProviderSendTurnSupportedImageMimeType,
7 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
8 PROVIDER_SEND_TURN_MAX_FILE_BYTES,
9 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
10 type EnvironmentId,
11 type PastedTextAttachmentSource,
12 type UploadChatImageAttachment,
13} from "@t3tools/contracts";
14import type { DocumentPickerResult } from "expo-document-picker";
15import { estimateBase64ByteSize } from "./base64";
16import {
17 COMPOSER_ATTACHMENT_DIRECTORY,
18 isComposerAttachmentFileRetained,
19 resolveOwnedComposerAttachmentFileUri,
20} from "./composerAttachmentFiles";
21import { imageMimeType } from "@t3tools/shared/image";
22import { videoMimeType } from "@t3tools/shared/video";
23import { fitComposerImage, renderPhoto } from "./composerImageFit";
24import { beginForegroundHandoff } from "./foreground-handoff";
25import { uuidv4 } from "./uuid";
26import { writeFileAtomically } from "./atomic-file";
27​
28export interface DraftComposerImageAttachment extends Omit<UploadChatImageAttachment, "dataUrl"> {
29 readonly id: string;
30 readonly previewUri: string;
31 readonly fileUri?: string;
32 readonly dataUrl?: string;
33 readonly uploadedAttachmentId?: string;
34 readonly uploadEnvironmentId?: EnvironmentId;
36​
37export interface DraftComposerFileAttachment {
38 readonly id: string;
39 readonly type: "file";
40 readonly name: string;
41 readonly mimeType: string;
42 readonly sizeBytes: number;
43 readonly fileUri: string;
44 readonly source?: PastedTextAttachmentSource;
45 readonly uploadedAttachmentId?: string;
46 readonly uploadEnvironmentId?: EnvironmentId;
48​
49export async function createPastedTextComposerAttachment(input: {
50 readonly text: string;
51 readonly name: string;
52 readonly maxBytes: number;
53}): Promise<DraftComposerFileAttachment> {
54 const bytes = new TextEncoder().encode(input.text).byteLength;
55 if (bytes <= 0) {
56 throw new Error("Clipboard is empty.");
57 }
58 if (bytes > input.maxBytes) {
59 throw new Error(fileAttachmentTooLargeMessage(input.name, input.maxBytes));
60 }
61​
62 const { Directory, File, Paths } = await import("expo-file-system");
63 const directory = new Directory(Paths.document, COMPOSER_ATTACHMENT_DIRECTORY);
64 directory.create({ idempotent: true, intermediates: true });
65 const file = new File(directory, `${uuidv4()}-${input.name}`);
66 await writeFileAtomically(file, input.text);
67 return {
68 id: uuidv4(),
69 type: "file",
70 name: input.name,
71 mimeType: "text/plain;charset=utf-8",
72 sizeBytes: bytes,
73 fileUri: file.uri,
74 source: { _tag: "pasted-text" },
75 };
77​
78export type DraftComposerAttachment = DraftComposerImageAttachment | DraftComposerFileAttachment;
79​
80/** Non-media attachments require chip references; missing references mean lost draft files. */
81export function composerStripAttachments(
82 attachments: ReadonlyArray<DraftComposerAttachment>,
83): ReadonlyArray<DraftComposerAttachment> {
84 return attachments.filter(
85 (attachment) =>
86 attachment.type === "image" ||
87 imageMimeType(attachment) !== null ||
88 videoMimeType(attachment) !== null,
89 );
91​
92/** Promote legacy document-picked images only when their originals fit the image contract. */
93export function isComposerImageAttachment(
94 attachment: DraftComposerAttachment,
95): attachment is DraftComposerImageAttachment {
96 return (
97 attachment.type === "image" ||
98 (attachment.sizeBytes <= PROVIDER_SEND_TURN_MAX_IMAGE_BYTES &&
99 imageMimeType(attachment) !== null)
100 );
102​
103export type FileBackedComposerAttachment = DraftComposerAttachment & { readonly fileUri: string };
104​
105export function isFileBackedComposerAttachment(
106 attachment: DraftComposerAttachment,
107): attachment is FileBackedComposerAttachment {
108 return attachment.fileUri !== undefined;
110​
111/** Inline library/clipboard images own no file; local ids cannot resolve server assets. */
112export function composerAttachmentInlineUri(
113 attachment: DraftComposerAttachment | undefined,
114): string | undefined {
115 if (attachment === undefined || isFileBackedComposerAttachment(attachment)) return undefined;
116 return attachment.type === "image" ? (attachment.dataUrl ?? attachment.previewUri) : undefined;
118​
119const OWNED_PASTED_IMAGE_DIRECTORY = "t3-composer-paste";
120const ATTACHMENT_COPY_CHUNK_BYTES = 64 * 1024;
121​
122export async function persistComposerAttachmentFile(
123 uri: string,
124 name: string,
125 maxBytes?: number,
126): Promise<string> {
127 const { Directory, File, FileMode, Paths } = await import("expo-file-system");
128 const directory = new Directory(Paths.document, COMPOSER_ATTACHMENT_DIRECTORY);
129 directory.create({ idempotent: true, intermediates: true });
130 const safeName =
131 Array.from(name, (character) =>
132 character === "/" || character === "\\" || character.charCodeAt(0) < 32 ? "-" : character,
133 ).join("") || "file";
134 const destination = new File(directory, `${uuidv4()}-${safeName}`);
135 const source = new File(uri);
136 const sourceSize = source.size;
137 if (
138 maxBytes !== undefined &&
139 (sourceSize === null || (sourceSize === 0 && uri.startsWith("content:")))
140 ) {
141 destination.create();
142 try {
143 const reader = source.open(FileMode.ReadOnly);
144 try {
145 const writer = destination.open(FileMode.WriteOnly);
146 try {
147 let copiedBytes = 0;
148 while (true) {
149 const chunk = await reader.readBytes(
150 Math.min(ATTACHMENT_COPY_CHUNK_BYTES, maxBytes - copiedBytes + 1),
151 );
152 if (chunk.byteLength === 0) {
153 break;
154 }
155 copiedBytes += chunk.byteLength;
156 if (copiedBytes > maxBytes) {
157 throw new Error(fileAttachmentTooLargeMessage(name, maxBytes));
158 }
159 await writer.writeBytes(chunk);
160 }
161 } finally {
162 writer.close();
163 }
164 } finally {
165 reader.close();
166 }
167 } catch (error) {
168 if (destination.exists) {
169 destination.delete();
170 }
171 throw error;
172 }
173 return destination.uri;
174 }
175​
176 if (maxBytes !== undefined && sourceSize !== null && sourceSize > maxBytes) {
177 throw new Error(fileAttachmentTooLargeMessage(name, maxBytes));
178 }
179 try {
180 await source.copy(destination);
181 } catch (error) {
182 // Failed copies may leave untracked partial files; delete before surfacing failure.
183 try {
184 if (destination.exists) {
185 destination.delete();
186 }
187 } catch (cleanupError) {
188 console.warn("[composer-attachments] could not remove a partial copy", cleanupError);
189 }
190 throw error;
191 }
192 // Android content streams may exceed reported size; validate the persisted copy.
193 const copiedSize = destination.size;
194 if (maxBytes !== undefined && copiedSize !== null && copiedSize > maxBytes) {
195 try {
196 if (destination.exists) {
197 destination.delete();
198 }
199 } catch (cleanupError) {
200 console.warn("[composer-attachments] could not remove an oversized copy", cleanupError);
201 }
202 throw new Error(fileAttachmentTooLargeMessage(name, maxBytes));
203 }
204 return destination.uri;
206​
207export async function removePersistedComposerAttachmentFile(uri: string): Promise<void> {
208 try {
209 const { File, Paths } = await import("expo-file-system");
210 const ownedUri = resolveOwnedComposerAttachmentFileUri(uri, Paths.document.uri);
211 if (ownedUri === null || isComposerAttachmentFileRetained(ownedUri)) {
212 return;
213 }
214 const file = new File(ownedUri);
215 if (file.exists) {
216 file.delete();
217 }
218 } catch (error) {
219 console.warn("[composer-attachments] could not remove local file", error);
220 }
222​
223async function createComposerFileAttachment(input: {
224 readonly uri: string;
225 readonly name: string;
226 readonly mimeType: string;
227 readonly sizeBytes: number | null;
228 readonly maxBytes: number;
229}): Promise<DraftComposerFileAttachment> {
230 if (input.sizeBytes !== null && input.sizeBytes > input.maxBytes) {
231 throw new Error(fileAttachmentTooLargeMessage(input.name, input.maxBytes));
232 }
233 const { File } = await import("expo-file-system");
234 const fileUri = await persistComposerAttachmentFile(input.uri, input.name, input.maxBytes);
235 try {
236 const sizeBytes = new File(fileUri).size ?? input.sizeBytes ?? 0;
237 if (sizeBytes <= 0) {
238 throw new Error(`'${input.name}' is empty or could not be read.`);
239 }
240 if (sizeBytes > input.maxBytes) {
241 throw new Error(fileAttachmentTooLargeMessage(input.name, input.maxBytes));
242 }
243 return {
244 id: uuidv4(),
245 type: "file",
246 name: input.name,
247 mimeType: input.mimeType,
248 sizeBytes,
249 fileUri,
250 };
251 } catch (error) {
252 await removePersistedComposerAttachmentFile(fileUri);
253 throw error;
254 }
256​
257export async function pickComposerFiles(input: {
258 readonly existingCount: number;
259 readonly maxBytes?: number;
260}): Promise<{
261 readonly files: ReadonlyArray<DraftComposerAttachment>;
262 readonly error: string | null;
263}> {
264 const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
265 if (remainingSlots <= 0) {
266 return {
267 files: [],
268 error: `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
269 };
270 }
271​
272 const { getDocumentAsync } = await import("expo-document-picker");
273 const endHandoff = beginForegroundHandoff();
274 let result: DocumentPickerResult;
275 try {
276 // Import a readable cache copy because FileSystem may not read provider URIs directly.
277 result = await getDocumentAsync({ multiple: true, copyToCacheDirectory: true });
278 } catch (cause) {
279 return {
280 files: [],
281 error: cause instanceof Error ? cause.message : "Could not open the file picker.",
282 };
283 } finally {
284 endHandoff();
285 }
286 if (result.canceled) {
287 return { files: [], error: null };
288 }
289​
290 const maxBytes = clampFileAttachmentUploadBytes(
291 input.maxBytes ?? PROVIDER_SEND_TURN_MAX_FILE_BYTES,
292 );
293 const attachments: DraftComposerAttachment[] = [];
294 let error: string | null = null;
295 let exceededAttachmentLimit = false;
296 for (const file of result.assets) {
297 if (attachments.length >= remainingSlots) {
298 exceededAttachmentLimit = true;
299 break;
300 }
301 // SAF can return blank display names, but the wire contract rejects them; fill before persisting.
302 const name = file.name.trim().length > 0 ? file.name : "file";
303 try {
304 const mimeType = imageMimeType({ name, mimeType: file.mimeType ?? "" });
305 const attachment = await createComposerFileAttachment({
306 uri: file.uri,
307 name,
308 mimeType: file.mimeType || "application/octet-stream",
309 sizeBytes: file.size ?? null,
310 maxBytes:
311 mimeType === null ? maxBytes : Math.max(maxBytes, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES),
312 });
313 if (mimeType === null || attachment.sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
314 attachments.push(attachment);
315 continue;
316 }
317 try {
318 const { File } = await import("expo-file-system");
319 const original = await new File(attachment.fileUri).base64();
320 const candidate = await fitComposerImage({
321 uri: attachment.fileUri,
322 mimeType,
323 base64: original,
324 });
325 const fitted =
326 candidate !== null &&
327 estimateBase64ByteSize(candidate.base64) <= PROVIDER_SEND_TURN_MAX_IMAGE_BYTES
328 ? candidate
329 : null;
330 const base64 = fitted?.base64 ?? original;
331 const sizeBytes = estimateBase64ByteSize(base64);
332 if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
333 throw new Error(`'${name}' exceeds the 10 MB attachment limit.`);
334 }
335 const dataUrl = `data:${mimeType};base64,${base64}`;
336 attachments.push({
337 id: attachment.id,
338 type: "image",
339 name,
340 mimeType,
341 sizeBytes,
342 dataUrl,
343 previewUri: fitted?.uri ?? dataUrl,
344 });
345 } finally {
346 await removePersistedComposerAttachmentFile(attachment.fileUri);
347 }
348 } catch (cause) {
349 error = cause instanceof Error ? cause.message : `Could not read '${name}'.`;
350 }
351 }
352 if (exceededAttachmentLimit) {
353 error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`;
354 }
355 return { files: attachments, error };
357​
358async function loadImagePicker() {
359 try {
360 return await import("expo-image-picker");
361 } catch (error) {
362 throw new Error("The photo library is unavailable right now.", { cause: error });
363 }
365​
366async function loadClipboard() {
367 try {
368 return await import("expo-clipboard");
369 } catch (error) {
370 throw new Error("Clipboard paste is unavailable right now.", { cause: error });
371 }
373​
374export async function pickComposerImages(input: { readonly existingCount: number }): Promise<{
375 readonly images: ReadonlyArray<DraftComposerImageAttachment>;
376 readonly error: string | null;
377}> {
378 const result = await pickComposerMedia(input);
379 return {
380 images: result.attachments.filter((attachment) => attachment.type === "image"),
381 error: result.error,
382 };
384​
385export async function pickComposerMedia(input: {
386 readonly existingCount: number;
387 readonly maxVideoBytes?: number;
388}): Promise<{
389 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
390 readonly error: string | null;
391}> {
392 const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
393 if (remainingSlots <= 0) {
394 return {
395 attachments: [],
396 error: `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments per message.`,
397 };
398 }
399​
400 let imagePicker: Awaited<ReturnType<typeof loadImagePicker>>;
401 try {
402 imagePicker = await loadImagePicker();
403 } catch (error) {
404 return {
405 attachments: [],
406 error: error instanceof Error ? error.message : "The photo library is unavailable right now.",
407 };
408 }
409​
410 // Android pickers report background state; guard against deferred restarts mid-pick.
411 const endHandoff = beginForegroundHandoff();
412 let result: Awaited<ReturnType<typeof imagePicker.launchImageLibraryAsync>>;
413 try {
414 result = await imagePicker.launchImageLibraryAsync({
415 mediaTypes: input.maxVideoBytes === undefined ? ["images"] : ["images", "videos"],
416 allowsMultipleSelection: true,
417 selectionLimit: remainingSlots,
418 // Base64 makes iOS decode all full-size photos and stalls JS with large strings; read bytes only as needed.
419 base64: false,
420 quality: 1,
421 shouldDownloadFromNetwork: true,
422 });
423 } catch (error) {
424 return {
425 attachments: [],
426 error: error instanceof Error ? error.message : "Could not open the photo library.",
427 };
428 } finally {
429 endHandoff();
430 }
431​
432 if (result.canceled) {
433 return {
434 attachments: [],
435 error: null,
436 };
437 }
438​
439 const attachments: DraftComposerAttachment[] = [];
440 let error: string | null = null;
441​
442 for (const asset of result.assets) {
443 if (attachments.length >= remainingSlots) {
444 error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments per message.`;
445 break;
446 }
447 const mimeType = asset.mimeType?.toLowerCase();
448 if (asset.type === "video" || mimeType?.startsWith("video/")) {
449 if (input.maxVideoBytes === undefined) {
450 error = "Video attachments are unavailable here.";
451 continue;
452 }
453 try {
454 const { File } = await import("expo-file-system");
455 const file = new File(asset.uri);
456 attachments.push(
457 await createComposerFileAttachment({
458 uri: asset.uri,
459 name: asset.fileName?.trim() || file.name || "video",
460 mimeType: mimeType || file.type || "application/octet-stream",
461 sizeBytes: asset.fileSize ?? null,
462 maxBytes: clampFileAttachmentUploadBytes(input.maxVideoBytes),
463 }),
464 );
465 } catch (cause) {
466 error =
467 cause instanceof Error ? cause.message : `Could not read '${asset.fileName ?? "video"}'.`;
468 }
469 continue;
470 }
471 if (asset.type !== "image" && !mimeType?.startsWith("image/")) {
472 error = `Unsupported file type for '${asset.fileName ?? "image"}'.`;
473 continue;
474 }
475​
476 const name = asset.fileName?.trim() || "image";
477 // Android content streams can exceed their reported size; measure the file before loading bytes into JS.
478 let sourceBytes: number | null = null;
479 try {
480 const { File } = await import("expo-file-system");
481 sourceBytes = new File(asset.uri).size;
482 } catch {
483 sourceBytes = null;
484 }
485 // Pass through supported, under-cap originals unchanged to preserve transparency and animation.
486 const originalMimeType =
487 mimeType !== undefined &&
488 isProviderSendTurnSupportedImageMimeType(mimeType) &&
489 sourceBytes !== null &&
490 sourceBytes > 0 &&
491 sourceBytes <= PROVIDER_SEND_TURN_MAX_IMAGE_BYTES
492 ? mimeType
493 : null;
494​
495 let image: { base64: string; mimeType: string; name: string; previewUri: string };
496 try {
497 if (originalMimeType !== null) {
498 const { File } = await import("expo-file-system");
499 const base64 = await new File(asset.uri).base64();
500 const fitted = await fitComposerImage({
501 uri: asset.uri,
502 mimeType: originalMimeType,
503 base64,
504 });
505 image = {
506 base64: fitted?.base64 ?? base64,
507 mimeType: originalMimeType,
508 name,
509 previewUri: fitted?.uri ?? asset.uri,
510 };
511 } else {
512 const rendered = await renderPhoto(asset.uri);
513 image = {
514 base64: rendered.base64,
515 mimeType: "image/jpeg",
516 name: /\.jpe?g$/i.test(name) ? name : `${name.replace(/\.[^.]+$/, "")}.jpg`,
517 previewUri: rendered.uri,
518 };
519 }
520 } catch {
521 error = `Failed to read '${name}'.`;
522 continue;
523 }
524​
525 const sizeBytes = estimateBase64ByteSize(image.base64);
526 if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
527 error = `'${name}' exceeds the 10 MB attachment limit.`;
528 continue;
529 }
530​
531 attachments.push({
532 id: uuidv4(),
533 type: "image",
534 name: image.name,
535 mimeType: image.mimeType,
536 sizeBytes,
537 dataUrl: `data:${image.mimeType};base64,${image.base64}`,
538 previewUri: image.previewUri,
539 });
540 }
541​
542 return {
543 attachments,
544 error,
545 };
547​
548export async function pasteComposerClipboard(input: { readonly existingCount: number }): Promise<
549 | {
550 readonly images: ReadonlyArray<DraftComposerImageAttachment>;
551 readonly text: null;
552 readonly error: string | null;
553 }
554 | {
555 readonly images: readonly [];
556 readonly text: string;
557 readonly error: null;
558 }
559> {
560 let clipboard: Awaited<ReturnType<typeof loadClipboard>>;
561 try {
562 clipboard = await loadClipboard();
563 } catch (error) {
564 return {
565 images: [],
566 text: null,
567 error: error instanceof Error ? error.message : "Clipboard paste is unavailable right now.",
568 };
569 }
570​
571 const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
572​
573 if (await clipboard.hasImageAsync()) {
574 if (remainingSlots <= 0) {
575 return {
576 images: [],
577 text: null,
578 error: `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`,
579 };
580 }
581 const image = await clipboard.getImageAsync({ format: "png" });
582 if (!image) {
583 return {
584 images: [],
585 text: null,
586 error: "Clipboard image is unavailable.",
587 };
588 }
589​
590 const pastedBase64 = image.data.split(",")[1] ?? "";
591 const fitted = await fitComposerImage({
592 uri: image.data,
593 mimeType: "image/png",
594 base64: pastedBase64,
595 });
596 const base64 = fitted?.base64 ?? pastedBase64;
597 const dataUrl = fitted ? `data:image/png;base64,${base64}` : image.data;
598 const sizeBytes = estimateBase64ByteSize(base64);
599 if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
600 return {
601 images: [],
602 text: null,
603 error: "Clipboard image exceeds the 10 MB attachment limit.",
604 };
605 }
606​
607 return {
608 images: [
609 {
610 id: uuidv4(),
611 type: "image",
612 name: "pasted-image.png",
613 mimeType: "image/png",
614 sizeBytes,
615 dataUrl,
616 previewUri: dataUrl,
617 },
618 ],
619 text: null,
620 error: null,
621 };
622 }
623​
624 if (await clipboard.hasStringAsync()) {
625 const text = await clipboard.getStringAsync();
626 return {
627 images: [],
628 ...(text.length > 0 ? { text, error: null } : { text: null, error: "Clipboard is empty." }),
629 };
630 }
631​
632 return {
633 images: [],
634 text: null,
635 error: "Clipboard does not contain pasteable text or image content.",
636 };
638​
639function mimeTypeFromUri(uri: string): string {
640 const ext = uri.split(".").pop()?.toLowerCase();
641 switch (ext) {
642 case "png":
643 return "image/png";
644 case "jpg":
645 case "jpeg":
646 return "image/jpeg";
647 case "gif":
648 return "image/gif";
649 case "webp":
650 return "image/webp";
651 case "heic":
652 return "image/heic";
653 default:
654 return "image/png";
655 }
657​
658export function isOwnedPastedImageUri(uri: string): boolean {
659 try {
660 const url = new URL(uri);
661 if (url.protocol !== "file:") {
662 return false;
663 }
664 const segments = url.pathname.split("/").filter(Boolean);
665 return (
666 segments.at(-2) === OWNED_PASTED_IMAGE_DIRECTORY && segments.at(-1)?.endsWith(".png") === true
667 );
668 } catch {
669 return false;
670 }
672​
673export async function convertPastedImagesToAttachments(input: {
674 readonly uris: ReadonlyArray<string>;
675 readonly existingCount: number;
676}): Promise<ReadonlyArray<DraftComposerImageAttachment>> {
677 const { File } = await import("expo-file-system");
678 const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
679 const results: DraftComposerImageAttachment[] = [];
680​
681 for (const [index, uri] of input.uris.entries()) {
682 const ownedTemporaryFile = isOwnedPastedImageUri(uri);
683 try {
684 if (index >= Math.max(0, remainingSlots)) {
685 continue;
686 }
687 const file = new File(uri);
688 const mimeType = mimeTypeFromUri(uri);
689 const pastedBase64 = await file.base64();
690 const fitted = await fitComposerImage({ uri, mimeType, base64: pastedBase64 });
691 const base64 = fitted?.base64 ?? pastedBase64;
692 const sizeBytes = estimateBase64ByteSize(base64);
693 if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
694 continue;
695 }
696 results.push({
697 id: uuidv4(),
698 type: "image",
699 name: `pasted-image.${mimeType.split("/")[1] ?? "png"}`,
700 mimeType,
701 sizeBytes,
702 dataUrl: `data:${mimeType};base64,${base64}`,
703 previewUri: ownedTemporaryFile ? `data:${mimeType};base64,${base64}` : (fitted?.uri ?? uri),
704 });
705 } catch (error) {
706 console.warn("Failed to read pasted image", uri, error);
707 } finally {
708 if (ownedTemporaryFile) {
709 try {
710 const file = new File(uri);
711 if (file.exists) {
712 file.delete();
713 }
714 } catch (error) {
715 console.warn("Failed to remove temporary pasted image", uri, error);
716 }
717 }
718 }
719 }
720​
721 return results;