import 'server-only'; import { getCloudflareContext } from '@opennextjs/cloudflare'; import { env } from './env'; // Cloudflare Images: server-side upload. Returns the canonical // imagedelivery.net URL using the `public` variant by default. type UploadResult = { id: string; publicUrl: string; printUrl: string; }; type UploadOptions = { filename?: string; metadata?: Record; requireSignedUrl?: boolean; }; type HostedImages = { upload(source: ReadableStream, options: { filename: string; metadata?: Record; requireSignedURLs?: boolean; }): Promise<{ id: string }>; image(id: string): { bytes(): Promise | null>; delete(): Promise; }; list(options: { limit: number; cursor?: string }): Promise<{ images: CfImage[]; cursor?: string }>; }; function hostedImages(): HostedImages | undefined { if (!process.env.CLOUDFLARE_DEPLOYMENT_ENV) return; const { IMAGES } = getCloudflareContext().env as { IMAGES?: { hosted?: HostedImages } }; if (!IMAGES?.hosted) throw new Error('Cloudflare hosted images binding is missing.'); return IMAGES.hosted; } export async function uploadImage( source: Blob | Buffer | ArrayBuffer, opts?: UploadOptions, ): Promise { const blob = source instanceof Blob ? source : new Blob([source as BlobPart]); const hosted = hostedImages(); const { id } = hosted ? await hosted.upload(blob.stream(), { filename: opts?.filename ?? 'upload.png', metadata: opts?.metadata, requireSignedURLs: opts?.requireSignedUrl, }) : await uploadWithApi(blob, opts); return { id, publicUrl: imageUrl(id), printUrl: imageUrl(id, 'print') }; } async function uploadWithApi(blob: Blob, opts?: UploadOptions): Promise<{ id: string }> { const form = new FormData(); form.append('file', blob, opts?.filename ?? 'upload.png'); if (opts?.metadata) form.append('metadata', JSON.stringify(opts.metadata)); if (opts?.requireSignedUrl) form.append('requireSignedURLs', 'true'); const url = `https://api.cloudflare.com/client/v4/accounts/${env.cf.accountId()}/images/v1`; const res = await fetch(url, { method: 'POST', headers: { Authorization: `Bearer ${env.cf.imagesApiToken()}` }, body: form, }); const json = await res.json() as { success: boolean; errors?: { message: string }[]; result?: { id: string }; }; if (!json.success || !json.result) { const msg = json.errors?.map(e => e.message).join('; ') ?? 'unknown error'; throw new Error(`CF Images upload failed: ${msg}`); } return json.result; } export function imageUrl(imageId: string, variant = 'public'): string { return `https://imagedelivery.net/${env.cf.imagesHash()}/${imageId}/${variant}`; } /** High-res variant for Prodigi assets. 4096×4096 fit:contain. */ export function printUrl(imageId: string): string { return imageUrl(imageId, 'print'); } /** The account's imagedelivery.net base, e.g. https://imagedelivery.net/. * The hash is public (it appears in every delivered URL), so this is safe to * hand to a client component for building image URLs. */ export function deliveryBase(): string { return `https://imagedelivery.net/${env.cf.imagesHash()}`; } export async function downloadOriginalImage(deliveredUrl: string): Promise { const prefix = deliveryBase() + '/'; if (!deliveredUrl.startsWith(prefix)) throw new Error('This draft does not have an original in the studio image library.'); const [variant, ...segments] = deliveredUrl.slice(prefix.length).split('/').reverse(); if (!variant || !segments.length || segments.some(segment => !segment)) throw new Error('Invalid studio image URL.'); const id = segments.reverse().map(decodeURIComponent).join('/'); const hosted = hostedImages(); if (hosted) { const bytes = await hosted.image(id).bytes(); if (!bytes) throw new Error('The original draft image could not be downloaded.'); return Buffer.from(await new Response(bytes).arrayBuffer()); } const url = `https://api.cloudflare.com/client/v4/accounts/${env.cf.accountId()}/images/v1/${encodeURIComponent(id)}/blob`; const response = await fetch(url, { headers: { Authorization: `Bearer ${env.cf.imagesApiToken()}` }, cache: 'no-store' }); if (!response.ok) throw new Error('The original draft image could not be downloaded.'); return Buffer.from(await response.arrayBuffer()); } export type CfImage = { id: string; uploaded?: string }; /** Delete one image from Cloudflare Images by id. Idempotent: a 404 ("image * not found") is treated as success — the goal state (image gone) is met. */ export async function deleteImage(id: string): Promise { const hosted = hostedImages(); if (hosted) { await hosted.image(id).delete(); return; } // CF image ids can contain '/', so we leave separators alone and only // percent-escape pieces that aren't path-safe. const safePath = id.split('/').map(encodeURIComponent).join('/'); const url = `https://api.cloudflare.com/client/v4/accounts/${env.cf.accountId()}/images/v1/${safePath}`; const res = await fetch(url, { method: 'DELETE', headers: { Authorization: `Bearer ${env.cf.imagesApiToken()}` }, }); if (res.status === 404) return; type DelResp = { success?: boolean; errors?: { message: string }[] }; const json: DelResp = await res.json().catch((): DelResp => ({})); if (!json.success) { const msg = json.errors?.map(e => e.message).join('; ') ?? `HTTP ${res.status}`; throw new Error(`CF Images delete failed: ${msg}`); } } /** List every image in the Cloudflare Images account (v2, continuation-token * paginated). Used by the admin CDN browser. Returns ids + upload time. */ export async function listImages(): Promise { const hosted = hostedImages(); const out: CfImage[] = []; let token = ''; for (let guard = 0; guard < 200; guard++) { if (hosted) { const page = await hosted.list({ limit: 1000, cursor: token || undefined }); out.push(...page.images.map(({ id, uploaded }) => ({ id, uploaded }))); token = page.cursor ?? ''; if (!token || page.images.length === 0) break; continue; } const url = new URL(`https://api.cloudflare.com/client/v4/accounts/${env.cf.accountId()}/images/v2`); url.searchParams.set('per_page', '1000'); if (token) url.searchParams.set('continuation_token', token); const res = await fetch(url, { headers: { Authorization: `Bearer ${env.cf.imagesApiToken()}` }, cache: 'no-store', }); const json = await res.json() as { success: boolean; errors?: { message: string }[]; result?: { images?: CfImage[]; continuation_token?: string }; }; if (!json.success || !json.result) { const msg = json.errors?.map(e => e.message).join('; ') ?? 'unknown error'; throw new Error(`CF Images list failed: ${msg}`); } const batch = json.result.images ?? []; out.push(...batch.map(im => ({ id: im.id, uploaded: im.uploaded }))); token = json.result.continuation_token ?? ''; if (!token || batch.length === 0) break; } return out; }