// Reconstruct a browser File from a remote image URL. Used to rehydrate // the builder when a customer returns to EDIT a pending order whose // photos already live on Cloudflare Images: ImageDrop and the /api/orders // submit path both work in terms of File objects, so turning the stored // URL back into a File lets the existing flow run unchanged — no // "please upload a photo" prompt for an image the customer already gave us. // // CF Images (imagedelivery.net) serves with permissive CORS, so the // cross-origin fetch succeeds. The print pipeline only accepts JPEG/PNG // (see upload-limits), so anything CF hands back in another format (e.g. // a WebP negotiated by the browser) is re-encoded to JPEG via a canvas // before becoming a File — otherwise the re-submit would fail validation. import { ACCEPTED_IMAGE_MIME } from './upload-limits'; export async function urlToFile(url: string, filename: string): Promise { const res = await fetch(url, { mode: 'cors' }); if (!res.ok) throw new Error(`fetch failed (${res.status})`); const blob = await res.blob(); if ((ACCEPTED_IMAGE_MIME as readonly string[]).includes(blob.type)) { return new File([blob], filename, { type: blob.type }); } const jpeg = await blobToJpeg(blob); const jpegName = filename.replace(/\.\w+$/, '') + '.jpg'; return new File([jpeg], jpegName, { type: 'image/jpeg' }); } // Decode an arbitrary image blob and re-encode it as JPEG via a canvas. function blobToJpeg(blob: Blob): Promise { return new Promise((resolve, reject) => { const objUrl = URL.createObjectURL(blob); const img = new Image(); img.onload = () => { URL.revokeObjectURL(objUrl); const canvas = document.createElement('canvas'); canvas.width = img.naturalWidth; canvas.height = img.naturalHeight; const ctx = canvas.getContext('2d'); if (!ctx) return reject(new Error('no 2d context')); ctx.drawImage(img, 0, 0); canvas.toBlob( (out) => (out ? resolve(out) : reject(new Error('canvas toBlob failed'))), 'image/jpeg', 0.92, ); }; img.onerror = () => { URL.revokeObjectURL(objUrl); reject(new Error('image decode failed')); }; img.src = objUrl; }); }