Open History to see the last commit
1import {
2 DestroyRef,
3 assertInInjectionContext,
4 inject,
5 signal,
6} from '@angular/core'
7import { AudioRecorder } from '@tanstack/ai-client'
8import type { Signal } from '@angular/core'
9import type {
10 AudioRecorderOptions,
11 AudioRecording,
12 InferAudioRecordingOutput,
13} from '@tanstack/ai-client'
14
15export type InjectAudioRecorderOptions<TOnComplete> = AudioRecorderOptions & {
16 /**
17 * Optional transform applied to the recording when `stop()` resolves. Its
18 * (awaited) return value becomes `recording` and the resolved value of
19 * `stop()`. Return nothing to keep the raw `AudioRecording`.
20 */
21 onComplete?: TOnComplete
22}
23
24export interface InjectAudioRecorderResult<TOutput> {
25 /** Reactive: latest recording (transformed if `onComplete` provided), or null. */
26 recording: Signal<TOutput | null>
27 /** Reactive: true while actively capturing audio. */
28 isRecording: Signal<boolean>
29 /** Whether the browser supports recording. */
30 isSupported: boolean
31 start: () => Promise<void>
32 /** Stop and resolve with the completed recording (transformed if `onComplete` provided). */
33 stop: () => Promise<TOutput>
34 /** Discard the in-progress recording and release the mic. */
35 cancel: () => void
36}
37
38/**
39 * Angular injectable for recording an audio message. The resolved recording
40 * carries `.part` (for `injectChat`'s `sendMessage`) and `.base64` (for the
41 * generation injectables). Must be called in an injection context.
42 *
43 * Errors are delivered via `onError`. `start()` and `stop()` also reject on
44 * failure (and `stop()` rejects with `Recording cancelled` if `cancel()` runs
45 * while a stop is in flight, e.g. on destroy) — handle one channel, not both.
46 */
47// The transforming overload requires `onComplete`. Without that constraint an
48// options object carrying only unrelated keys (`injectAudioRecorder({ onError })`)
49// still matches it, `TOnComplete` infers as `unknown`, and `recording`/`stop()`
50// collapse to `unknown` — so passing any option would silently cost you the
51// `AudioRecording` type. Requiring it here sends those calls to the second
52// overload instead (issue #1001).
53export function injectAudioRecorder<
54 TOnComplete extends (recording: AudioRecording) => unknown,
55>(
56 options: InjectAudioRecorderOptions<TOnComplete> & {
57 onComplete: TOnComplete
58 },
59): InjectAudioRecorderResult<InferAudioRecordingOutput<TOnComplete>>
60export function injectAudioRecorder(
61 options?: InjectAudioRecorderOptions<undefined>,
62): InjectAudioRecorderResult<AudioRecording>
63export function injectAudioRecorder(
64 options: InjectAudioRecorderOptions<
65 (recording: AudioRecording) => unknown
66 > = {},
67): InjectAudioRecorderResult<unknown> {
68 assertInInjectionContext(injectAudioRecorder)
69 const destroyRef = inject(DestroyRef)
70 const recorder = new AudioRecorder({
71 ...(options.audio !== undefined && { audio: options.audio }),
72 ...(options.mimeType !== undefined && { mimeType: options.mimeType }),
73 ...(options.onError !== undefined && { onError: options.onError }),
74 })
75 const isRecording = signal(false)
76 const recording = signal<unknown>(null)
77
78 const unsubscribe = recorder.subscribe((state) => {
79 isRecording.set(state === 'recording')
80 })
81 destroyRef.onDestroy(() => {
82 unsubscribe()
83 recorder.cancel()
84 })
85
86 const stop = async (): Promise<unknown> => {
87 const rawRecording = await recorder.stop()
88 const transformed = await options.onComplete?.(rawRecording)
89 // Only `undefined` (returning nothing) keeps the raw recording; a returned
90 // null is a real value, matching the inferred output type.
91 const output = transformed === undefined ? rawRecording : transformed
92 recording.set(output)
93 return output
94 }
95
96 return {
97 recording: recording.asReadonly(),
98 isRecording: isRecording.asReadonly(),
99 isSupported: AudioRecorder.isSupported(),
100 start: () => recorder.start(),
101 stop,
102 cancel: () => recorder.cancel(),
103 }
104}