Open History to see the last commit
1import { useState } from 'react'
2import type { ReactNode } from 'react'
3import { createFileRoute } from '@tanstack/react-router'
4import {
5 FileAudio,
6 FileText,
7 Image,
8 Mic,
9 Music,
10 Play,
11 RotateCcw,
12 Video,
13} from 'lucide-react'
14import {
15 useGenerateAudio,
16 useGenerateImage,
17 useGenerateSpeech,
18 useGenerateVideo,
19 useSummarize,
20 useTranscription,
21} from '@tanstack/ai-react'
22import { EventType } from '@tanstack/ai'
23import {
24 GENERATION_EVENTS,
25 type ConnectConnectionAdapter,
26 type VideoGenerateResult,
27} from '@tanstack/ai-client'
28import type {
29 AudioGenerationResult,
30 ImageGenerationResult,
31 StreamChunk,
32 SummarizationResult,
33 TranscriptionResult,
34 TTSResult,
35} from '@tanstack/ai'
36import type { LucideIcon } from 'lucide-react'
37
38const SAMPLE_WAV_BASE64 = createToneWavBase64()
39const SAMPLE_AUDIO_DATA_URL = `data:audio/wav;base64,${SAMPLE_WAV_BASE64}`
40const SAMPLE_VIDEO_URL =
41 'https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4'
42const SAMPLE_TRANSCRIPTION_AUDIO = SAMPLE_AUDIO_DATA_URL
43
44const imageConnection = createGenerationConnection<ImageGenerationResult>(
45 'image',
46 (data) => {
47 const prompt = stringField(data, 'prompt', 'Generated devtools test image')
48 const count = Math.max(
49 1,
50 Math.min(4, numberField(data, 'numberOfImages', 1)),
51 )
52 return {
53 id: `local-image-${Date.now()}`,
54 images: Array.from({ length: count }, (_, index) => ({
55 url: svgDataUrl(
56 `Image ${index + 1}`,
57 prompt,
58 index % 2 === 0 ? '#0ea5e9' : '#f97316',
59 ),
60 revisedPrompt: `${prompt} (${index + 1})`,
61 })),
62 model: 'local-devtools-image-fixture',
63 }
64 },
65)
66
67const audioConnection = createGenerationConnection<AudioGenerationResult>(
68 'audio',
69 (data) => ({
70 id: `local-audio-${Date.now()}`,
71 audio: {
72 url: SAMPLE_AUDIO_DATA_URL,
73 contentType: 'audio/wav',
74 duration: numberField(data, 'duration', 3),
75 },
76 model: 'local-devtools-audio-fixture',
77 }),
78)
79
80const speechConnection = createGenerationConnection<TTSResult>(
81 'speech',
82 () => ({
83 id: `local-speech-${Date.now()}`,
84 model: 'local-devtools-speech-fixture',
85 audio: SAMPLE_WAV_BASE64,
86 contentType: 'audio/wav',
87 format: 'wav',
88 duration: 0.8,
89 }),
90)
91
92const transcriptionConnection = createGenerationConnection<TranscriptionResult>(
93 'transcription',
94 (data) => ({
95 id: `local-transcription-${Date.now()}`,
96 model: 'local-devtools-transcription-fixture',
97 text: `Transcribed local fixture in ${stringField(data, 'language', 'en')}.`,
98 language: stringField(data, 'language', 'en'),
99 duration: 3,
100 segments: [
101 {
102 id: 0,
103 start: 0,
104 end: 1.5,
105 text: 'Transcribed local fixture',
106 },
107 {
108 id: 1,
109 start: 1.5,
110 end: 3,
111 text: 'ready for devtools inspection',
112 },
113 ],
114 }),
115)
116
117const summarizeConnection = createGenerationConnection<SummarizationResult>(
118 'summarize',
119 (data) => {
120 const text = stringField(data, 'text', SAMPLE_SUMMARY_TEXT)
121 const style = stringField(data, 'style', 'concise')
122 return {
123 id: `local-summary-${Date.now()}`,
124 summary: `${style}: ${text.split(/\s+/).slice(0, 24).join(' ')}.`,
125 model: 'local-devtools-summary-fixture',
126 usage: {
127 promptTokens: text.split(/\s+/).length,
128 completionTokens: 24,
129 totalTokens: text.split(/\s+/).length + 24,
130 },
131 }
132 },
133)
134
135const videoConnection = createVideoConnection()
136
137const SAMPLE_SUMMARY_TEXT =
138 'Generation hooks emit core devtools snapshots with input, progress, result, and renderable previews for media and text outputs.'
139
140export const Route = createFileRoute('/generation-hooks')({
141 component: GenerationHooksPage,
142})
143
144function GenerationHooksPage() {
145 const [prompt, setPrompt] = useState(
146 'A compact diagnostics console showing every TanStack AI generation hook',
147 )
148 const [speechText, setSpeechText] = useState(
149 'This local fixture exercises the speech generation hook.',
150 )
151 const [summaryText, setSummaryText] = useState(SAMPLE_SUMMARY_TEXT)
152 const [imageCount, setImageCount] = useState(2)
153 const [audioDuration, setAudioDuration] = useState(3)
154
155 const image = useGenerateImage({
156 threadId: 'generation-hooks:useGenerateImage',
157 connection: imageConnection,
158 persistence: true,
159 })
160
161 const audio = useGenerateAudio({
162 threadId: 'generation-hooks:useGenerateAudio',
163 connection: audioConnection,
164 persistence: true,
165 })
166
167 const speech = useGenerateSpeech({
168 threadId: 'generation-hooks:useGenerateSpeech',
169 connection: speechConnection,
170 persistence: true,
171 })
172
173 const transcription = useTranscription({
174 threadId: 'generation-hooks:useTranscription',
175 connection: transcriptionConnection,
176 persistence: true,
177 })
178
179 const summarize = useSummarize({
180 threadId: 'generation-hooks:useSummarize',
181 connection: summarizeConnection,
182 persistence: true,
183 })
184
185 const video = useGenerateVideo({
186 threadId: 'generation-hooks:useGenerateVideo',
187 connection: videoConnection,
188 persistence: true,
189 })
190
191 const loadingCount = [
192 image.isLoading,
193 audio.isLoading,
194 speech.isLoading,
195 transcription.isLoading,
196 summarize.isLoading,
197 video.isLoading,
198 ].filter(Boolean).length
199
200 const runImage = () => {
201 return image.generate({ prompt, numberOfImages: imageCount })
202 }
203 const runAudio = () => {
204 return audio.generate({ prompt, duration: audioDuration })
205 }
206 const runSpeech = () => {
207 return speech.generate({ text: speechText, voice: 'local' })
208 }
209 const runTranscription = () => {
210 return transcription.generate({
211 audio: SAMPLE_TRANSCRIPTION_AUDIO,
212 language: 'en',
213 })
214 }
215 const runSummarize = () => {
216 return summarize.generate({
217 text: summaryText,
218 style: 'bullet-points',
219 })
220 }
221 const runVideo = () => {
222 return video.generate({ prompt })
223 }
224
225 const runAll = async () => {
226 await Promise.all([
227 runImage(),
228 runAudio(),
229 runSpeech(),
230 runTranscription(),
231 runSummarize(),
232 runVideo(),
233 ])
234 }
235
236 const resetAll = () => {
237 image.reset()
238 audio.reset()
239 speech.reset()
240 transcription.reset()
241 summarize.reset()
242 video.reset()
243 }
244
245 const stopAll = () => {
246 image.stop()
247 audio.stop()
248 speech.stop()
249 transcription.stop()
250 summarize.stop()
251 video.stop()
252 }
253
254 return (
255 <main className="min-h-screen bg-gray-950 text-white">
256 <div className="mx-auto flex w-full max-w-7xl flex-col gap-6 px-6 py-8">
257 <section className="flex flex-col gap-4 border-b border-gray-800 pb-6 lg:flex-row lg:items-end lg:justify-between">
258 <div className="space-y-2">
259 <p className="text-xs font-semibold uppercase tracking-wider text-cyan-300">
260 Devtools fixture route
261 </p>
262 <h2 className="text-3xl font-semibold tracking-tight">
263 Generation Hooks
264 </h2>
265 <p className="max-w-3xl text-sm leading-6 text-gray-400">
266 Six mounted hooks, stable IDs, local streaming fixtures, and
267 media-shaped results for the devtools panel.
268 </p>
269 </div>
270 <div className="flex flex-wrap gap-3">
271 <button
272 type="button"
273 onClick={() => void runAll()}
274 disabled={loadingCount > 0}
275 className="inline-flex items-center gap-2 rounded-lg bg-cyan-600 px-4 py-2 text-sm font-semibold text-white transition-colors hover:bg-cyan-500 disabled:bg-gray-800 disabled:text-gray-500"
276 >
277 <Play size={16} />
278 Run All
279 </button>
280 <button
281 type="button"
282 onClick={stopAll}
283 disabled={loadingCount === 0}
284 className="inline-flex items-center gap-2 rounded-lg border border-red-500/40 px-4 py-2 text-sm font-semibold text-red-200 transition-colors hover:bg-red-500/10 disabled:border-gray-800 disabled:text-gray-600"
285 >
286 Stop
287 </button>
288 <button
289 type="button"
290 onClick={resetAll}
291 className="inline-flex items-center gap-2 rounded-lg border border-gray-700 px-4 py-2 text-sm font-semibold text-gray-200 transition-colors hover:bg-gray-900"
292 >
293 <RotateCcw size={16} />
294 Reset
295 </button>
296 </div>
297 </section>
298
299 <section className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_280px]">
300 <label className="flex flex-col gap-2">
301 <span className="text-xs font-semibold uppercase tracking-wider text-gray-500">
302 Shared prompt
303 </span>
304 <textarea
305 value={prompt}
306 onChange={(event) => setPrompt(event.target.value)}
307 rows={3}
308 className="min-h-24 rounded-lg border border-gray-800 bg-gray-900 px-4 py-3 text-sm leading-6 text-white outline-none transition focus:border-cyan-500"
309 />
310 </label>
311 <div className="grid grid-cols-2 gap-3 rounded-lg border border-gray-800 bg-gray-900 p-4">
312 <Counter label="mounted" value={6} />
313 <Counter label="running" value={loadingCount} />
314 <Counter label="images" value={image.result?.images.length ?? 0} />
315 <Counter
316 label="complete"
317 value={
318 [
319 image.result,
320 audio.result,
321 speech.result,
322 transcription.result,
323 summarize.result,
324 video.result,
325 ].filter(Boolean).length
326 }
327 />
328 </div>
329 </section>
330
331 <section className="grid gap-4 xl:grid-cols-2">
332 <HookCard
333 title="useGenerateImage"
334 hookId="generation-hooks:useGenerateImage"
335 icon={Image}
336 status={image.status}
337 isLoading={image.isLoading}
338 error={image.error}
339 onGenerate={() => void runImage()}
340 onReset={image.reset}
341 >
342 <div className="flex items-center gap-2">
343 {[1, 2, 3, 4].map((count) => (
344 <button
345 key={count}
346 type="button"
347 onClick={() => setImageCount(count)}
348 className={`h-8 w-8 rounded-md text-xs font-semibold transition-colors ${
349 imageCount === count
350 ? 'bg-cyan-600 text-white'
351 : 'bg-gray-800 text-gray-300 hover:bg-gray-700'
352 }`}
353 >
354 {count}
355 </button>
356 ))}
357 </div>
358 <div className="grid gap-3 sm:grid-cols-2">
359 {image.result?.images.map((item, index) => (
360 <img
361 key={`${item.url}-${index}`}
362 src={item.url ?? `data:image/png;base64,${item.b64Json}`}
363 alt={item.revisedPrompt ?? `Generated image ${index + 1}`}
364 className="aspect-video w-full rounded-md border border-gray-800 bg-gray-900 object-cover"
365 />
366 ))}
367 </div>
368 </HookCard>
369
370 <HookCard
371 title="useGenerateAudio"
372 hookId="generation-hooks:useGenerateAudio"
373 icon={Music}
374 status={audio.status}
375 isLoading={audio.isLoading}
376 error={audio.error}
377 onGenerate={() => void runAudio()}
378 onReset={audio.reset}
379 >
380 <label className="flex flex-col gap-2">
381 <span className="text-xs font-semibold uppercase tracking-wider text-gray-500">
382 Duration {audioDuration}s
383 </span>
384 <input
385 type="range"
386 min={1}
387 max={10}
388 value={audioDuration}
389 onChange={(event) =>
390 setAudioDuration(Number(event.target.value))
391 }
392 className="accent-cyan-500"
393 />
394 </label>
395 {audio.result?.audio.url && (
396 <audio src={audio.result.audio.url} controls className="w-full" />
397 )}
398 </HookCard>
399
400 <HookCard
401 title="useGenerateSpeech"
402 hookId="generation-hooks:useGenerateSpeech"
403 icon={FileAudio}
404 status={speech.status}
405 isLoading={speech.isLoading}
406 error={speech.error}
407 onGenerate={() => void runSpeech()}
408 onReset={speech.reset}
409 >
410 <textarea
411 value={speechText}
412 onChange={(event) => setSpeechText(event.target.value)}
413 rows={3}
414 className="w-full rounded-md border border-gray-800 bg-gray-950 px-3 py-2 text-sm text-white outline-none focus:border-cyan-500"
415 />
416 {speech.result?.audio && (
417 <audio
418 src={`data:${speech.result.contentType ?? 'audio/wav'};base64,${
419 speech.result.audio
420 }`}
421 controls
422 className="w-full"
423 />
424 )}
425 </HookCard>
426
427 <HookCard
428 title="useTranscription"
429 hookId="generation-hooks:useTranscription"
430 icon={Mic}
431 status={transcription.status}
432 isLoading={transcription.isLoading}
433 error={transcription.error}
434 onGenerate={() => void runTranscription()}
435 onReset={transcription.reset}
436 >
437 <p className="rounded-md border border-gray-800 bg-gray-950 px-3 py-2 text-sm leading-6 text-gray-200">
438 {transcription.result?.text ?? 'No transcript yet.'}
439 </p>
440 </HookCard>
441
442 <HookCard
443 title="useSummarize"
444 hookId="generation-hooks:useSummarize"
445 icon={FileText}
446 status={summarize.status}
447 isLoading={summarize.isLoading}
448 error={summarize.error}
449 onGenerate={() => void runSummarize()}
450 onReset={summarize.reset}
451 >
452 <textarea
453 value={summaryText}
454 onChange={(event) => setSummaryText(event.target.value)}
455 rows={4}
456 className="w-full rounded-md border border-gray-800 bg-gray-950 px-3 py-2 text-sm text-white outline-none focus:border-cyan-500"
457 />
458 <p className="rounded-md border border-gray-800 bg-gray-950 px-3 py-2 text-sm leading-6 text-gray-200">
459 {summarize.result?.summary ?? 'No summary yet.'}
460 </p>
461 </HookCard>
462
463 <HookCard
464 title="useGenerateVideo"
465 hookId="generation-hooks:useGenerateVideo"
466 icon={Video}
467 status={video.status}
468 isLoading={video.isLoading}
469 error={video.error}
470 onGenerate={() => void runVideo()}
471 onReset={video.reset}
472 >
473 <div className="grid gap-2 text-xs text-gray-400 sm:grid-cols-3">
474 <span>job {video.jobId ?? 'none'}</span>
475 <span>status {video.videoStatus?.status ?? 'idle'}</span>
476 <span>
477 progress{' '}
478 {video.videoStatus?.progress == null
479 ? '0%'
480 : `${video.videoStatus.progress}%`}
481 </span>
482 </div>
483 {video.result?.url && (
484 <video
485 src={video.result.url}
486 controls
487 className="aspect-video w-full rounded-md border border-gray-800 bg-black"
488 />
489 )}
490 </HookCard>
491 </section>
492 </div>
493 </main>
494 )
495}
496
497function HookCard({
498 title,
499 hookId,
500 icon: Icon,
501 status,
502 isLoading,
503 error,
504 onGenerate,
505 onReset,
506 children,
507}: {
508 title: string
509 hookId: string
510 icon: LucideIcon
511 status: string
512 isLoading: boolean
513 error?: Error
514 onGenerate: () => void
515 onReset: () => void
516 children: ReactNode
517}) {
518 return (
519 <article className="flex min-h-72 flex-col gap-4 rounded-lg border border-gray-800 bg-gray-900 p-4">
520 <header className="flex items-start justify-between gap-4">
521 <div className="flex min-w-0 items-center gap-3">
522 <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-md bg-cyan-500/10 text-cyan-300">
523 <Icon size={20} />
524 </div>
525 <div className="min-w-0">
526 <h3 className="truncate text-base font-semibold text-white">
527 {title}
528 </h3>
529 <p className="truncate font-mono text-xs text-gray-500">{hookId}</p>
530 </div>
531 </div>
532 <span
533 className={`shrink-0 rounded-md px-2 py-1 font-mono text-xs ${
534 isLoading
535 ? 'bg-cyan-500/15 text-cyan-200'
536 : status === 'error'
537 ? 'bg-red-500/15 text-red-200'
538 : status === 'success'
539 ? 'bg-emerald-500/15 text-emerald-200'
540 : 'bg-gray-800 text-gray-300'
541 }`}
542 >
543 {status}
544 </span>
545 </header>
546
547 <div className="flex flex-wrap gap-2">
548 <button
549 type="button"
550 onClick={onGenerate}
551 disabled={isLoading}
552 className="inline-flex items-center gap-2 rounded-md bg-cyan-600 px-3 py-2 text-xs font-semibold text-white transition-colors hover:bg-cyan-500 disabled:bg-gray-800 disabled:text-gray-500"
553 >
554 <Play size={14} />
555 Run
556 </button>
557 <button
558 type="button"
559 onClick={onReset}
560 className="inline-flex items-center gap-2 rounded-md border border-gray-700 px-3 py-2 text-xs font-semibold text-gray-200 transition-colors hover:bg-gray-800"
561 >
562 <RotateCcw size={14} />
563 Reset
564 </button>
565 </div>
566
567 {error && (
568 <p className="rounded-md border border-red-500/20 bg-red-500/10 px-3 py-2 text-sm text-red-200">
569 {error.message}
570 </p>
571 )}
572
573 <div className="flex flex-1 flex-col gap-3">{children}</div>
574 </article>
575 )
576}
577
578function Counter({ label, value }: { label: string; value: number }) {
579 return (
580 <div className="rounded-md bg-gray-950 px-3 py-2">
581 <div className="font-mono text-2xl font-semibold text-white">{value}</div>
582 <div className="text-xs font-semibold uppercase tracking-wider text-gray-500">
583 {label}
584 </div>
585 </div>
586 )
587}
588
589function createGenerationConnection<TResult>(
590 label: string,
591 createResult: (data: Record<string, unknown>) => TResult,
592): ConnectConnectionAdapter {
593 return {
594 async *connect(_messages, data, abortSignal, runContext) {
595 const runId = runContext?.runId ?? `${label}-run-${Date.now()}`
596 const threadId = runContext?.threadId ?? `${label}-thread`
597 yield runStarted(runId, threadId)
598 await waitForFixtureStep(abortSignal)
599 if (abortSignal?.aborted) return
600
601 yield progress(25, `${label} queued`)
602 await waitForFixtureStep(abortSignal)
603 if (abortSignal?.aborted) return
604
605 yield progress(70, `${label} rendering`)
606 await waitForFixtureStep(abortSignal)
607 if (abortSignal?.aborted) return
608
609 yield result(createResult(toRecord(data)))
610 await waitForFixtureStep(abortSignal)
611 if (abortSignal?.aborted) return
612
613 yield runFinished(runId, threadId)
614 },
615 }
616}
617
618function createVideoConnection(): ConnectConnectionAdapter {
619 return {
620 async *connect(_messages, data, abortSignal, runContext) {
621 const runId = runContext?.runId ?? `video-run-${Date.now()}`
622 const threadId = runContext?.threadId ?? 'video-thread'
623 const jobId = `local-video-${Date.now()}`
624 const prompt = stringField(
625 toRecord(data),
626 'prompt',
627 'Local video fixture',
628 )
629
630 yield runStarted(runId, threadId)
631 await waitForFixtureStep(abortSignal)
632 if (abortSignal?.aborted) return
633
634 yield custom(GENERATION_EVENTS.VIDEO_JOB_CREATED, { jobId })
635 yield custom(GENERATION_EVENTS.VIDEO_STATUS, {
636 jobId,
637 status: 'pending',
638 progress: 10,
639 })
640 await waitForFixtureStep(abortSignal)
641 if (abortSignal?.aborted) return
642
643 yield custom(GENERATION_EVENTS.VIDEO_STATUS, {
644 jobId,
645 status: 'processing',
646 progress: 60,
647 })
648 await waitForFixtureStep(abortSignal)
649 if (abortSignal?.aborted) return
650
651 const finalResult: VideoGenerateResult = {
652 jobId,
653 status: 'completed',
654 url: SAMPLE_VIDEO_URL,
655 }
656 yield custom(GENERATION_EVENTS.VIDEO_STATUS, {
657 jobId,
658 status: 'completed',
659 progress: 100,
660 url: SAMPLE_VIDEO_URL,
661 prompt,
662 })
663 yield result(finalResult)
664 yield runFinished(runId, threadId)
665 },
666 }
667}
668
669async function waitForFixtureStep(abortSignal: AbortSignal | undefined) {
670 await new Promise<void>((resolve) => {
671 const timeout = window.setTimeout(resolve, 180)
672 abortSignal?.addEventListener(
673 'abort',
674 () => {
675 window.clearTimeout(timeout)
676 resolve()
677 },
678 { once: true },
679 )
680 })
681}
682
683function runStarted(runId: string, threadId: string): StreamChunk {
684 return {
685 type: EventType.RUN_STARTED,
686 runId,
687 threadId,
688 timestamp: Date.now(),
689 }
690}
691
692function runFinished(runId: string, threadId: string): StreamChunk {
693 return {
694 type: EventType.RUN_FINISHED,
695 runId,
696 threadId,
697 finishReason: 'stop',
698 timestamp: Date.now(),
699 }
700}
701
702function progress(value: number, message: string): StreamChunk {
703 return custom(GENERATION_EVENTS.PROGRESS, {
704 progress: value,
705 message,
706 })
707}
708
709function result(value: unknown): StreamChunk {
710 return custom(GENERATION_EVENTS.RESULT, value)
711}
712
713function custom(name: string, value: unknown): StreamChunk {
714 return {
715 type: EventType.CUSTOM,
716 name,
717 value,
718 timestamp: Date.now(),
719 }
720}
721
722function toRecord(value: unknown): Record<string, unknown> {
723 return value && typeof value === 'object' && !Array.isArray(value)
724 ? { ...value }
725 : {}
726}
727
728function stringField(
729 data: Record<string, unknown>,
730 field: string,
731 fallback: string,
732): string {
733 const value = data[field]
734 return typeof value === 'string' && value.trim() ? value.trim() : fallback
735}
736
737function numberField(
738 data: Record<string, unknown>,
739 field: string,
740 fallback: number,
741): number {
742 const value = data[field]
743 return typeof value === 'number' ? value : fallback
744}
745
746function createToneWavBase64({
747 frequency = 440,
748 durationSeconds = 0.8,
749 sampleRate = 8000,
750} = {}): string {
751 const sampleCount = Math.floor(sampleRate * durationSeconds)
752 const dataSize = sampleCount * 2
753 const bytes = new Uint8Array(44 + dataSize)
754 const view = new DataView(bytes.buffer)
755
756 writeAscii(bytes, 0, 'RIFF')
757 view.setUint32(4, 36 + dataSize, true)
758 writeAscii(bytes, 8, 'WAVE')
759 writeAscii(bytes, 12, 'fmt ')
760 view.setUint32(16, 16, true)
761 view.setUint16(20, 1, true)
762 view.setUint16(22, 1, true)
763 view.setUint32(24, sampleRate, true)
764 view.setUint32(28, sampleRate * 2, true)
765 view.setUint16(32, 2, true)
766 view.setUint16(34, 16, true)
767 writeAscii(bytes, 36, 'data')
768 view.setUint32(40, dataSize, true)
769
770 for (let index = 0; index < sampleCount; index++) {
771 const envelope = Math.sin((Math.PI * index) / sampleCount)
772 const wave = Math.sin((2 * Math.PI * frequency * index) / sampleRate)
773 const sample = Math.round(wave * envelope * 0.25 * 32767)
774 view.setInt16(44 + index * 2, sample, true)
775 }
776
777 return bytesToBase64(bytes)
778}
779
780function writeAscii(bytes: Uint8Array, offset: number, value: string): void {
781 for (let index = 0; index < value.length; index++) {
782 bytes[offset + index] = value.charCodeAt(index)
783 }
784}
785
786function bytesToBase64(bytes: Uint8Array): string {
787 const alphabet =
788 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
789 let output = ''
790
791 for (let index = 0; index < bytes.length; index += 3) {
792 const first = bytes[index] ?? 0
793 const second = index + 1 < bytes.length ? bytes[index + 1] : undefined
794 const third = index + 2 < bytes.length ? bytes[index + 2] : undefined
795 const combined = (first << 16) | ((second ?? 0) << 8) | (third ?? 0)
796
797 output += alphabet[(combined >> 18) & 63]
798 output += alphabet[(combined >> 12) & 63]
799 output += second === undefined ? '=' : alphabet[(combined >> 6) & 63]
800 output += third === undefined ? '=' : alphabet[combined & 63]
801 }
802
803 return output
804}
805
806function svgDataUrl(title: string, prompt: string, color: string): string {
807 const safeTitle = escapeXml(title)
808 const safePrompt = escapeXml(prompt)
809 const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="960" height="540" viewBox="0 0 960 540"><rect width="960" height="540" fill="#030712"/><rect x="36" y="36" width="888" height="468" rx="20" fill="${color}" fill-opacity="0.16" stroke="${color}" stroke-width="4"/><circle cx="810" cy="128" r="74" fill="${color}" fill-opacity="0.32"/><text x="72" y="130" fill="#f8fafc" font-family="monospace" font-size="48" font-weight="700">${safeTitle}</text><text x="72" y="210" fill="#cbd5e1" font-family="monospace" font-size="24">${safePrompt.slice(0, 56)}</text><text x="72" y="432" fill="${color}" font-family="monospace" font-size="20">local devtools fixture</text></svg>`
810 return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`
811}
812
813function escapeXml(value: string): string {
814 return value
815 .replaceAll('&', '&')
816 .replaceAll('<', '<')
817 .replaceAll('>', '>')
818 .replaceAll('"', '"')
819 .replaceAll("'", ''')
820}