Files
upstream-tldraw/templates/image-pipeline/worker/routes/generate.ts
upstream-mirror a774ac673a
Some checks failed
Deploy analytics worker / Deploy analytics worker to ${{ (github.ref == 'refs/heads/production' && 'production') || (github.ref == 'refs/heads/main' && 'staging') || 'preview' }} (push) Failing after 1s
i18n upload strings / Upload latest strings (push) Failing after 1s
Deploy bemo / Deploy bemo to ${{ (github.ref == 'refs/heads/bemo-production' && 'production') || (github.ref == 'refs/heads/main' && 'staging') || 'preview' }} (push) Failing after 1s
Deploy grafana resources / ${{ github.event_name == 'push' && 'Deploy grafana resources' || 'Validate grafana resources (dry run)' }} (push) Failing after 0s
End to end tests (dotcom) / Check for relevant changes (push) Failing after 0s
End to end tests (examples) / Check for relevant changes (push) Failing after 0s
End to end tests (mermaid readability) / Check for relevant changes (push) Failing after 1s
End to end tests (perf) / Check for relevant changes (push) Failing after 0s
Publish editor extensions / Publish editor extensions (push) Failing after 1s
Publish SDK packages / Remove the publish-packages label (push) Has been skipped
Checks / Tests & checks (push) Has been cancelled
Checks / Build all projects (push) Has been cancelled
Deploy templates / Deploy templates (push) Has been cancelled
End to end tests (dotcom) / End to end tests (dotcom) (push) Has been cancelled
End to end tests (mermaid readability) / End to end tests (mermaid readability) (push) Has been cancelled
End to end tests (perf) / End to end tests (perf) (push) Has been cancelled
Deploy .com / Deploy dotcom to ${{ (github.ref == 'refs/heads/production' && 'production') || (github.ref == 'refs/heads/main' && 'staging') || 'preview' }} (push) Has been cancelled
End to end tests (examples) / End to end tests (examples) (push) Has been cancelled
Publish SDK packages / Publish SDK packages (push) Has been cancelled
Publish SDK packages / Tell user released version (push) Has been cancelled
Publish SDK packages / Publishes code templates to separate repositories (push) Has been cancelled
Publish SDK packages / Deploys the template demos with the new SDK version (push) Has been cancelled
snapshot of https://github.com/tldraw/tldraw.git (main, 2026-09-23; blobs > 131072B omitted)
2026-09-23 16:12:52 +05:00

104 lines
3.2 KiB
TypeScript

import { IRequest } from 'itty-router'
import { getProvider } from '../providers'
import type { GenerateParams } from '../providers'
/**
* Request body for the /api/generate endpoint.
*/
interface GenerateRequest {
/** The provider:model string, e.g. "stable-diffusion:sdxl" */
model: string
/** The text prompt describing the desired image */
prompt: string
/** Optional negative prompt */
negativePrompt?: string
/** Number of inference steps (default: 20) */
steps?: number
/** Classifier-free guidance scale (default: 7) */
cfgScale?: number
/** Seed for reproducibility (default: random) */
seed?: number
/** ControlNet mode if applicable */
controlNetMode?: string
/** ControlNet strength (0-100) */
controlNetStrength?: number
/** Reference image URL for ControlNet */
referenceImageUrl?: string
}
/**
* POST /api/generate
*
* Calls an AI image generation provider and returns the generated image.
* Supports multiple providers via the model string format "provider:model".
*
* Returns: { imageUrl: string, seed: number }
*/
export async function handleGenerate(request: IRequest, env: Env) {
const body = (await request.json()) as GenerateRequest
if (!body.prompt) {
return new Response(JSON.stringify({ error: 'prompt is required' }), {
status: 400,
headers: { 'Content-Type': 'application/json' },
})
}
const [providerName, modelId] = (body.model ?? 'flux:flux-dev').split(':')
try {
const provider = getProvider(providerName)
const params: GenerateParams = {
modelId: modelId ?? '',
prompt: body.prompt,
negativePrompt: body.negativePrompt,
steps: body.steps ?? 20,
cfgScale: body.cfgScale ?? 7,
seed: body.seed ?? null,
controlNetMode: body.controlNetMode,
controlNetStrength: body.controlNetStrength,
referenceImageUrl: body.referenceImageUrl,
}
let result = await provider.generate(params, env)
// Optionally persist the image to R2.
if (env.IMAGE_BUCKET && result.imageUrl?.startsWith('data:')) {
const imageId = `gen_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`
const blob = dataUrlToBlob(result.imageUrl)
await env.IMAGE_BUCKET.put(imageId, blob, {
httpMetadata: { contentType: 'image/png' },
})
result = { ...result, imageUrl: `/api/images/${imageId}` }
}
return new Response(JSON.stringify(result), {
headers: { 'Content-Type': 'application/json' },
})
} catch (e: any) {
console.error('Generate error:', e)
return new Response(JSON.stringify({ error: e.message ?? 'Generation failed' }), {
status: 500,
headers: { 'Content-Type': 'application/json' },
})
}
}
// ---------------------------------------------------------------------------
// Utilities
// ---------------------------------------------------------------------------
function dataUrlToBlob(dataUrl: string): ArrayBuffer {
const [header, base64] = dataUrl.split(',')
if (header.includes('base64')) {
const binary = atob(base64)
const bytes = new Uint8Array(binary.length)
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i)
}
return bytes.buffer as ArrayBuffer
}
// For SVG data URLs, just encode as UTF-8
return new TextEncoder().encode(decodeURIComponent(base64)).buffer as ArrayBuffer
}