rystem.playframework.client 0.1.1 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1617 -47
- package/lib/engine/ClientInteractionRegistry.d.ts +48 -1
- package/lib/engine/ClientInteractionRegistry.d.ts.map +1 -1
- package/lib/engine/ClientInteractionRegistry.js +84 -13
- package/lib/engine/PlayFrameworkClient.d.ts +58 -0
- package/lib/engine/PlayFrameworkClient.d.ts.map +1 -1
- package/lib/engine/PlayFrameworkClient.js +271 -24
- package/lib/index.d.ts +17 -1
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +15 -1
- package/lib/models/AiSceneResponse.d.ts +2 -2
- package/lib/models/AiSceneResponse.d.ts.map +1 -1
- package/lib/models/ClientInteractionRequest.d.ts +15 -0
- package/lib/models/ClientInteractionRequest.d.ts.map +1 -1
- package/lib/models/CommandResult.d.ts +31 -0
- package/lib/models/CommandResult.d.ts.map +1 -0
- package/lib/models/CommandResult.js +18 -0
- package/lib/models/ExecutionState.d.ts +35 -0
- package/lib/models/ExecutionState.d.ts.map +1 -0
- package/lib/models/ExecutionState.js +2 -0
- package/lib/models/PlayFrameworkRequest.d.ts +10 -0
- package/lib/models/PlayFrameworkRequest.d.ts.map +1 -1
- package/lib/models/StoredConversation.d.ts +88 -0
- package/lib/models/StoredConversation.d.ts.map +1 -0
- package/lib/models/StoredConversation.js +17 -0
- package/lib/models/StoredMessage.d.ts +30 -0
- package/lib/models/StoredMessage.d.ts.map +1 -0
- package/lib/models/StoredMessage.js +2 -0
- package/lib/models/VoiceResponse.d.ts +39 -0
- package/lib/models/VoiceResponse.d.ts.map +1 -0
- package/lib/models/VoiceResponse.js +2 -0
- package/lib/utils/BrowserSpeechRecognizer.d.ts +128 -0
- package/lib/utils/BrowserSpeechRecognizer.d.ts.map +1 -0
- package/lib/utils/BrowserSpeechRecognizer.js +150 -0
- package/lib/utils/BrowserSpeechSynthesizer.d.ts +148 -0
- package/lib/utils/BrowserSpeechSynthesizer.d.ts.map +1 -0
- package/lib/utils/BrowserSpeechSynthesizer.js +400 -0
- package/lib/utils/BrowserVoiceClient.d.ts +142 -0
- package/lib/utils/BrowserVoiceClient.d.ts.map +1 -0
- package/lib/utils/BrowserVoiceClient.js +200 -0
- package/lib/utils/ContentUrlConverter.d.ts +62 -0
- package/lib/utils/ContentUrlConverter.d.ts.map +1 -0
- package/lib/utils/ContentUrlConverter.js +151 -0
- package/lib/utils/VoiceRecorder.d.ts +90 -0
- package/lib/utils/VoiceRecorder.d.ts.map +1 -0
- package/lib/utils/VoiceRecorder.js +195 -0
- package/package.json +1 -1
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.BrowserVoiceClient = void 0;
|
|
4
|
+
const BrowserSpeechRecognizer_1 = require("./BrowserSpeechRecognizer");
|
|
5
|
+
const BrowserSpeechSynthesizer_1 = require("./BrowserSpeechSynthesizer");
|
|
6
|
+
/**
|
|
7
|
+
* Orchestrates browser-native voice I/O with the PlayFrameworkClient.
|
|
8
|
+
*
|
|
9
|
+
* Flow:
|
|
10
|
+
* 1. **STT** — `BrowserSpeechRecognizer` captures user speech → text.
|
|
11
|
+
* 2. **LLM** — Text is sent to PlayFramework via step-by-step or token streaming.
|
|
12
|
+
* 3. **TTS** — `BrowserSpeechSynthesizer` speaks the LLM response in real-time.
|
|
13
|
+
*
|
|
14
|
+
* This gives a fully client-side voice experience (no server-side Whisper / TTS-1 needed).
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```ts
|
|
18
|
+
* const client = new PlayFrameworkClient(settings);
|
|
19
|
+
* const voice = new BrowserVoiceClient(client, { lang: 'it-IT' });
|
|
20
|
+
*
|
|
21
|
+
* for await (const event of voice.executeWithBrowserVoice()) {
|
|
22
|
+
* if (event.voiceStatus === 'recognized') {
|
|
23
|
+
* console.log('User said:', event.transcript);
|
|
24
|
+
* }
|
|
25
|
+
* if (event.response?.message) {
|
|
26
|
+
* console.log('AI:', event.response.message);
|
|
27
|
+
* }
|
|
28
|
+
* }
|
|
29
|
+
* ```
|
|
30
|
+
*/
|
|
31
|
+
class BrowserVoiceClient {
|
|
32
|
+
client;
|
|
33
|
+
recognizer;
|
|
34
|
+
synthesizer;
|
|
35
|
+
/**
|
|
36
|
+
* Internal AbortController created for each `executeWithBrowserVoice()` invocation.
|
|
37
|
+
* Used by `cancelStream()` and `cancelAll()` to programmatically abort the HTTP/SSE stream.
|
|
38
|
+
* Set to `null` when no voice flow is in progress.
|
|
39
|
+
*/
|
|
40
|
+
currentAbortController = null;
|
|
41
|
+
constructor(client, recognizerOptions, synthesizerOptions, synthesizerCallbacks) {
|
|
42
|
+
this.client = client;
|
|
43
|
+
this.recognizer = new BrowserSpeechRecognizer_1.BrowserSpeechRecognizer(recognizerOptions);
|
|
44
|
+
this.synthesizer = new BrowserSpeechSynthesizer_1.BrowserSpeechSynthesizer(synthesizerOptions, synthesizerCallbacks);
|
|
45
|
+
}
|
|
46
|
+
/** Returns `true` if the browser supports both Speech Recognition and Speech Synthesis. */
|
|
47
|
+
static isSupported() {
|
|
48
|
+
return BrowserSpeechRecognizer_1.BrowserSpeechRecognizer.isSupported() && BrowserSpeechSynthesizer_1.BrowserSpeechSynthesizer.isSupported();
|
|
49
|
+
}
|
|
50
|
+
/** Access the underlying recognizer for advanced configuration. */
|
|
51
|
+
getRecognizer() {
|
|
52
|
+
return this.recognizer;
|
|
53
|
+
}
|
|
54
|
+
/** Access the underlying synthesizer for advanced configuration. */
|
|
55
|
+
getSynthesizer() {
|
|
56
|
+
return this.synthesizer;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Execute a complete voice interaction:
|
|
60
|
+
* Speech → Text → PlayFramework (streaming) → Text → Speech
|
|
61
|
+
*
|
|
62
|
+
* Yields `BrowserVoiceEvent` objects with both voice status and LLM responses.
|
|
63
|
+
*/
|
|
64
|
+
async *executeWithBrowserVoice(options) {
|
|
65
|
+
const { text, streamingMode = 'stepByStep', request = {}, recognitionTimeoutMs = 15000, signal, speakResponse = true, useVoiceStyle = true, } = options ?? {};
|
|
66
|
+
// ── 0. Create internal AbortController for this invocation ─────
|
|
67
|
+
// Links to the user-provided signal so external abort propagates.
|
|
68
|
+
const controller = new AbortController();
|
|
69
|
+
this.currentAbortController = controller;
|
|
70
|
+
if (signal) {
|
|
71
|
+
if (signal.aborted) {
|
|
72
|
+
controller.abort(signal.reason);
|
|
73
|
+
}
|
|
74
|
+
else {
|
|
75
|
+
signal.addEventListener('abort', () => controller.abort(signal.reason), { once: true });
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
const effectiveSignal = controller.signal;
|
|
79
|
+
try {
|
|
80
|
+
// ── 1. Speech Recognition (if no text provided) ────────────────
|
|
81
|
+
let transcript;
|
|
82
|
+
if (text != null) {
|
|
83
|
+
transcript = text;
|
|
84
|
+
}
|
|
85
|
+
else {
|
|
86
|
+
yield { response: null, voiceStatus: 'recognizing' };
|
|
87
|
+
try {
|
|
88
|
+
transcript = await this.recognizer.listen(recognitionTimeoutMs);
|
|
89
|
+
}
|
|
90
|
+
catch (err) {
|
|
91
|
+
throw new Error(`Speech recognition failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
92
|
+
}
|
|
93
|
+
if (!transcript.trim()) {
|
|
94
|
+
// No speech detected
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
yield { response: null, voiceStatus: 'recognized', transcript };
|
|
99
|
+
// ── 2. Send text to PlayFramework via streaming ────────────────
|
|
100
|
+
const fullRequest = {
|
|
101
|
+
...request,
|
|
102
|
+
message: transcript,
|
|
103
|
+
settings: {
|
|
104
|
+
...request.settings,
|
|
105
|
+
isVoiceMode: useVoiceStyle,
|
|
106
|
+
},
|
|
107
|
+
};
|
|
108
|
+
const stream = streamingMode === 'tokenStreaming'
|
|
109
|
+
? this.client.executeTokenStreaming(fullRequest, effectiveSignal)
|
|
110
|
+
: this.client.executeStepByStep(fullRequest, effectiveSignal);
|
|
111
|
+
// ── 3. Stream responses and optionally speak them ──────────────
|
|
112
|
+
for await (const response of stream) {
|
|
113
|
+
// Forward the raw LLM event
|
|
114
|
+
yield { response };
|
|
115
|
+
if (!speakResponse)
|
|
116
|
+
continue;
|
|
117
|
+
// For token streaming, feed chunks incrementally
|
|
118
|
+
if (streamingMode === 'tokenStreaming' && response.streamingChunk) {
|
|
119
|
+
this.synthesizer.feedChunk(response.streamingChunk);
|
|
120
|
+
}
|
|
121
|
+
// For step-by-step, speak complete messages
|
|
122
|
+
if (streamingMode === 'stepByStep' && response.message) {
|
|
123
|
+
// Speak any status that carries meaningful text; skip system/noise statuses
|
|
124
|
+
const nonSpeakableStatuses = [
|
|
125
|
+
'initializing', 'loadingCache', 'savingCache', 'savingMemory',
|
|
126
|
+
'executingMainActors', 'executingScene', 'planning',
|
|
127
|
+
'functionRequest', 'functionCompleted', 'toolSkipped',
|
|
128
|
+
'awaitingClient', 'commandClient',
|
|
129
|
+
'directorDecision', 'summarizing', 'generatingFinalResponse',
|
|
130
|
+
'error', 'budgetExceeded', 'unauthorized',
|
|
131
|
+
];
|
|
132
|
+
if (!nonSpeakableStatuses.includes(response.status)) {
|
|
133
|
+
this.synthesizer.feedChunk(response.message);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
// ── 4. Flush remaining buffered text and wait for TTS to finish ─
|
|
138
|
+
if (speakResponse) {
|
|
139
|
+
yield { response: null, voiceStatus: 'speaking' };
|
|
140
|
+
await this.synthesizer.flushAndWait();
|
|
141
|
+
yield { response: null, voiceStatus: 'speechComplete' };
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
finally {
|
|
145
|
+
this.currentAbortController = null;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Execute a voice interaction using only browser TTS (no STT).
|
|
150
|
+
* Sends the provided text via PlayFramework and speaks the response.
|
|
151
|
+
*
|
|
152
|
+
* Shorthand for `executeWithBrowserVoice({ text, speakResponse: true, ... })`.
|
|
153
|
+
*/
|
|
154
|
+
async *speakResponse(text, streamingMode = 'stepByStep', request, signal) {
|
|
155
|
+
yield* this.executeWithBrowserVoice({
|
|
156
|
+
text,
|
|
157
|
+
streamingMode,
|
|
158
|
+
request,
|
|
159
|
+
signal,
|
|
160
|
+
speakResponse: true,
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Cancel only the audio (TTS). The HTTP/SSE text stream continues
|
|
165
|
+
* so you can still read the LLM response in your `for await` loop.
|
|
166
|
+
*/
|
|
167
|
+
cancelSpeech() {
|
|
168
|
+
this.synthesizer.cancel();
|
|
169
|
+
}
|
|
170
|
+
/** Stop recognition if active. */
|
|
171
|
+
stopRecognition() {
|
|
172
|
+
this.recognizer.stop();
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Cancel the HTTP/SSE stream (abort the API call).
|
|
176
|
+
* The .NET server receives a cancelled `CancellationToken` and stops processing.
|
|
177
|
+
* TTS is also cancelled since no more text will arrive.
|
|
178
|
+
*/
|
|
179
|
+
cancelStream() {
|
|
180
|
+
if (this.currentAbortController) {
|
|
181
|
+
this.currentAbortController.abort(new DOMException('The voice stream was cancelled', 'AbortError'));
|
|
182
|
+
}
|
|
183
|
+
this.synthesizer.cancel();
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Cancel everything: recognition + HTTP stream + audio.
|
|
187
|
+
* Equivalent to calling `stopRecognition()`, `cancelStream()`, and `cancelSpeech()` together.
|
|
188
|
+
*/
|
|
189
|
+
cancelAll() {
|
|
190
|
+
this.recognizer.abort();
|
|
191
|
+
this.cancelStream();
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Whether a voice flow is currently in progress (stream is active).
|
|
195
|
+
*/
|
|
196
|
+
get isStreaming() {
|
|
197
|
+
return this.currentAbortController !== null;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
exports.BrowserVoiceClient = BrowserVoiceClient;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { AIContent } from '../models/ClientInteractionResult';
|
|
2
|
+
/**
|
|
3
|
+
* Utility class for converting AIContent (base64 data) to Blob URLs for browser display.
|
|
4
|
+
*
|
|
5
|
+
* @example
|
|
6
|
+
* ```typescript
|
|
7
|
+
* const content: AIContent = { type: "data", data: "...", mediaType: "image/jpeg" };
|
|
8
|
+
*
|
|
9
|
+
* // Convert to Blob URL
|
|
10
|
+
* const url = ContentUrlConverter.toBlobUrl(content);
|
|
11
|
+
*
|
|
12
|
+
* // Use in <img> tag
|
|
13
|
+
* <img src={url} alt="Image" />
|
|
14
|
+
*
|
|
15
|
+
* // Cleanup when done
|
|
16
|
+
* ContentUrlConverter.revokeUrl(url);
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
export declare class ContentUrlConverter {
|
|
20
|
+
private static urlCache;
|
|
21
|
+
/**
|
|
22
|
+
* Converts AIContent with data (Base64) to a Blob object.
|
|
23
|
+
*
|
|
24
|
+
* @param content - AIContent with data field
|
|
25
|
+
* @returns Blob or null if no data present
|
|
26
|
+
*/
|
|
27
|
+
static toBlob(content: AIContent): Blob | null;
|
|
28
|
+
/**
|
|
29
|
+
* Converts AIContent to a blob: URL that can be used in <img>, <audio>, <video>, etc.
|
|
30
|
+
*
|
|
31
|
+
* @param content - AIContent with data field
|
|
32
|
+
* @param cacheKey - Optional cache key for reusing URLs
|
|
33
|
+
* @returns Blob URL string or null if conversion fails
|
|
34
|
+
*/
|
|
35
|
+
static toBlobUrl(content: AIContent, cacheKey?: string): string | null;
|
|
36
|
+
/**
|
|
37
|
+
* Revokes a blob URL to free memory. Always call this when done using the URL.
|
|
38
|
+
*
|
|
39
|
+
* @param url - Blob URL to revoke
|
|
40
|
+
* @param cacheKey - Optional cache key to remove from cache
|
|
41
|
+
*/
|
|
42
|
+
static revokeUrl(url: string, cacheKey?: string): void;
|
|
43
|
+
/**
|
|
44
|
+
* Clears all cached blob URLs and revokes them.
|
|
45
|
+
*/
|
|
46
|
+
static clearCache(): void;
|
|
47
|
+
/**
|
|
48
|
+
* Downloads AIContent as a file.
|
|
49
|
+
*
|
|
50
|
+
* @param content - AIContent to download
|
|
51
|
+
* @param filename - Filename to use (defaults to "download" + extension)
|
|
52
|
+
*/
|
|
53
|
+
static downloadAsFile(content: AIContent, filename?: string): void;
|
|
54
|
+
/**
|
|
55
|
+
* Gets the file extension from mediaType.
|
|
56
|
+
*
|
|
57
|
+
* @param mediaType - MIME type (e.g., "image/jpeg")
|
|
58
|
+
* @returns File extension (e.g., ".jpg") or empty string
|
|
59
|
+
*/
|
|
60
|
+
static getFileExtension(mediaType?: string): string;
|
|
61
|
+
}
|
|
62
|
+
//# sourceMappingURL=ContentUrlConverter.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ContentUrlConverter.d.ts","sourceRoot":"","sources":["../../src/utils/ContentUrlConverter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mCAAmC,CAAC;AAEnE;;;;;;;;;;;;;;;;GAgBG;AACH,qBAAa,mBAAmB;IAC5B,OAAO,CAAC,MAAM,CAAC,QAAQ,CAA6B;IAEpD;;;;;OAKG;IACH,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,SAAS,GAAG,IAAI,GAAG,IAAI;IAmB9C;;;;;;OAMG;IACH,MAAM,CAAC,SAAS,CAAC,OAAO,EAAE,SAAS,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI;IAwBtE;;;;;OAKG;IACH,MAAM,CAAC,SAAS,CAAC,GAAG,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI;IAUtD;;OAEG;IACH,MAAM,CAAC,UAAU,IAAI,IAAI;IASzB;;;;;OAKG;IACH,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,SAAS,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI;IAqBlE;;;;;OAKG;IACH,MAAM,CAAC,gBAAgB,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM;CAyBtD"}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ContentUrlConverter = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Utility class for converting AIContent (base64 data) to Blob URLs for browser display.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```typescript
|
|
9
|
+
* const content: AIContent = { type: "data", data: "...", mediaType: "image/jpeg" };
|
|
10
|
+
*
|
|
11
|
+
* // Convert to Blob URL
|
|
12
|
+
* const url = ContentUrlConverter.toBlobUrl(content);
|
|
13
|
+
*
|
|
14
|
+
* // Use in <img> tag
|
|
15
|
+
* <img src={url} alt="Image" />
|
|
16
|
+
*
|
|
17
|
+
* // Cleanup when done
|
|
18
|
+
* ContentUrlConverter.revokeUrl(url);
|
|
19
|
+
* ```
|
|
20
|
+
*/
|
|
21
|
+
class ContentUrlConverter {
|
|
22
|
+
static urlCache = new Map();
|
|
23
|
+
/**
|
|
24
|
+
* Converts AIContent with data (Base64) to a Blob object.
|
|
25
|
+
*
|
|
26
|
+
* @param content - AIContent with data field
|
|
27
|
+
* @returns Blob or null if no data present
|
|
28
|
+
*/
|
|
29
|
+
static toBlob(content) {
|
|
30
|
+
if (!content.data)
|
|
31
|
+
return null;
|
|
32
|
+
try {
|
|
33
|
+
// Decode base64 to binary string
|
|
34
|
+
const byteString = atob(content.data);
|
|
35
|
+
const bytes = new Uint8Array(byteString.length);
|
|
36
|
+
for (let i = 0; i < byteString.length; i++) {
|
|
37
|
+
bytes[i] = byteString.charCodeAt(i);
|
|
38
|
+
}
|
|
39
|
+
return new Blob([bytes], { type: content.mediaType || 'application/octet-stream' });
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
console.error('Failed to decode base64 data:', error);
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Converts AIContent to a blob: URL that can be used in <img>, <audio>, <video>, etc.
|
|
48
|
+
*
|
|
49
|
+
* @param content - AIContent with data field
|
|
50
|
+
* @param cacheKey - Optional cache key for reusing URLs
|
|
51
|
+
* @returns Blob URL string or null if conversion fails
|
|
52
|
+
*/
|
|
53
|
+
static toBlobUrl(content, cacheKey) {
|
|
54
|
+
// For text content, return null (not displayable as media)
|
|
55
|
+
if (content.type === 'text') {
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
// Check cache first
|
|
59
|
+
if (cacheKey && this.urlCache.has(cacheKey)) {
|
|
60
|
+
return this.urlCache.get(cacheKey);
|
|
61
|
+
}
|
|
62
|
+
const blob = this.toBlob(content);
|
|
63
|
+
if (!blob)
|
|
64
|
+
return null;
|
|
65
|
+
const url = URL.createObjectURL(blob);
|
|
66
|
+
// Store in cache if key provided
|
|
67
|
+
if (cacheKey) {
|
|
68
|
+
this.urlCache.set(cacheKey, url);
|
|
69
|
+
}
|
|
70
|
+
return url;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Revokes a blob URL to free memory. Always call this when done using the URL.
|
|
74
|
+
*
|
|
75
|
+
* @param url - Blob URL to revoke
|
|
76
|
+
* @param cacheKey - Optional cache key to remove from cache
|
|
77
|
+
*/
|
|
78
|
+
static revokeUrl(url, cacheKey) {
|
|
79
|
+
if (url.startsWith('blob:')) {
|
|
80
|
+
URL.revokeObjectURL(url);
|
|
81
|
+
}
|
|
82
|
+
if (cacheKey) {
|
|
83
|
+
this.urlCache.delete(cacheKey);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Clears all cached blob URLs and revokes them.
|
|
88
|
+
*/
|
|
89
|
+
static clearCache() {
|
|
90
|
+
this.urlCache.forEach(url => {
|
|
91
|
+
if (url.startsWith('blob:')) {
|
|
92
|
+
URL.revokeObjectURL(url);
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
this.urlCache.clear();
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Downloads AIContent as a file.
|
|
99
|
+
*
|
|
100
|
+
* @param content - AIContent to download
|
|
101
|
+
* @param filename - Filename to use (defaults to "download" + extension)
|
|
102
|
+
*/
|
|
103
|
+
static downloadAsFile(content, filename) {
|
|
104
|
+
const blob = this.toBlob(content);
|
|
105
|
+
if (!blob) {
|
|
106
|
+
console.error('Cannot download: no blob data');
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
const url = URL.createObjectURL(blob);
|
|
110
|
+
const a = document.createElement('a');
|
|
111
|
+
a.href = url;
|
|
112
|
+
// Generate filename with proper extension
|
|
113
|
+
const extension = this.getFileExtension(content.mediaType);
|
|
114
|
+
a.download = filename || `download${extension}`;
|
|
115
|
+
document.body.appendChild(a);
|
|
116
|
+
a.click();
|
|
117
|
+
document.body.removeChild(a);
|
|
118
|
+
URL.revokeObjectURL(url);
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Gets the file extension from mediaType.
|
|
122
|
+
*
|
|
123
|
+
* @param mediaType - MIME type (e.g., "image/jpeg")
|
|
124
|
+
* @returns File extension (e.g., ".jpg") or empty string
|
|
125
|
+
*/
|
|
126
|
+
static getFileExtension(mediaType) {
|
|
127
|
+
if (!mediaType)
|
|
128
|
+
return '';
|
|
129
|
+
const extensionMap = {
|
|
130
|
+
'image/jpeg': '.jpg',
|
|
131
|
+
'image/png': '.png',
|
|
132
|
+
'image/gif': '.gif',
|
|
133
|
+
'image/webp': '.webp',
|
|
134
|
+
'image/svg+xml': '.svg',
|
|
135
|
+
'audio/mpeg': '.mp3',
|
|
136
|
+
'audio/wav': '.wav',
|
|
137
|
+
'audio/ogg': '.ogg',
|
|
138
|
+
'video/mp4': '.mp4',
|
|
139
|
+
'video/webm': '.webm',
|
|
140
|
+
'video/ogg': '.ogv',
|
|
141
|
+
'application/pdf': '.pdf',
|
|
142
|
+
'application/json': '.json',
|
|
143
|
+
'text/plain': '.txt',
|
|
144
|
+
'text/html': '.html',
|
|
145
|
+
'text/css': '.css',
|
|
146
|
+
'application/javascript': '.js',
|
|
147
|
+
};
|
|
148
|
+
return extensionMap[mediaType] || '';
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
exports.ContentUrlConverter = ContentUrlConverter;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Recording mode for VoiceRecorder.
|
|
3
|
+
* - `vad` — Voice Activity Detection: automatically stops when silence is detected.
|
|
4
|
+
* - `pushToTalk` — Press once to start, press again to stop & send.
|
|
5
|
+
* - `holdToTalk` — Hold button to record, release to stop & send.
|
|
6
|
+
*/
|
|
7
|
+
export type VoiceRecordingMode = 'vad' | 'pushToTalk' | 'holdToTalk';
|
|
8
|
+
/**
|
|
9
|
+
* Options for VoiceRecorder.
|
|
10
|
+
*/
|
|
11
|
+
export interface VoiceRecorderOptions {
|
|
12
|
+
/** Recording mode. Default: `'vad'`. */
|
|
13
|
+
mode?: VoiceRecordingMode;
|
|
14
|
+
/** Audio MIME type. Default: `'audio/webm'`. */
|
|
15
|
+
mimeType?: string;
|
|
16
|
+
/** Maximum recording duration in ms (safety cap). Default: `30000` (30s). */
|
|
17
|
+
maxDurationMs?: number;
|
|
18
|
+
/** Silence threshold (0-1). Audio level below this is "silence". Default: `0.01`. */
|
|
19
|
+
silenceThreshold?: number;
|
|
20
|
+
/** How long (ms) silence must last before auto-stopping. Default: `1500`. */
|
|
21
|
+
silenceDurationMs?: number;
|
|
22
|
+
/** Minimum recording duration in ms before VAD can trigger a stop. Default: `500`. */
|
|
23
|
+
minRecordingMs?: number;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Callbacks emitted by VoiceRecorder.
|
|
27
|
+
*/
|
|
28
|
+
export interface VoiceRecorderCallbacks {
|
|
29
|
+
/** Called when recording starts. */
|
|
30
|
+
onStart?: () => void;
|
|
31
|
+
/** Called every second with the elapsed seconds. */
|
|
32
|
+
onTick?: (seconds: number) => void;
|
|
33
|
+
/** Called with the recorded audio Blob when recording ends successfully. */
|
|
34
|
+
onRecorded?: (blob: Blob) => void;
|
|
35
|
+
/** Called when an error occurs. */
|
|
36
|
+
onError?: (error: Error) => void;
|
|
37
|
+
/** Called when recording stops (success or error). Always fires. */
|
|
38
|
+
onStop?: () => void;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Cross-browser voice recorder with support for VAD, push-to-talk, and hold-to-talk modes.
|
|
42
|
+
*
|
|
43
|
+
* @example
|
|
44
|
+
* ```ts
|
|
45
|
+
* const recorder = new VoiceRecorder({ mode: 'vad', silenceDurationMs: 2000 });
|
|
46
|
+
*
|
|
47
|
+
* // Start recording — in VAD mode it stops automatically on silence
|
|
48
|
+
* recorder.start({
|
|
49
|
+
* onStart: () => console.log('Recording...'),
|
|
50
|
+
* onTick: (s) => console.log(`${s}s`),
|
|
51
|
+
* onRecorded: (blob) => sendToServer(blob),
|
|
52
|
+
* onStop: () => console.log('Done'),
|
|
53
|
+
* });
|
|
54
|
+
*
|
|
55
|
+
* // For pushToTalk: call recorder.stop() when user presses the button again.
|
|
56
|
+
* // For holdToTalk: call recorder.stop() on pointerup / mouseup.
|
|
57
|
+
* ```
|
|
58
|
+
*/
|
|
59
|
+
export declare class VoiceRecorder {
|
|
60
|
+
private _options;
|
|
61
|
+
private _mediaRecorder;
|
|
62
|
+
private _stream;
|
|
63
|
+
private _audioContext;
|
|
64
|
+
private _analyser;
|
|
65
|
+
private _vadIntervalId;
|
|
66
|
+
private _tickIntervalId;
|
|
67
|
+
private _maxTimeoutId;
|
|
68
|
+
private _recording;
|
|
69
|
+
private _startTime;
|
|
70
|
+
private _callbacks;
|
|
71
|
+
constructor(options?: VoiceRecorderOptions);
|
|
72
|
+
/** Whether the recorder is currently active. */
|
|
73
|
+
get isRecording(): boolean;
|
|
74
|
+
/** Current recording mode. */
|
|
75
|
+
get mode(): VoiceRecordingMode;
|
|
76
|
+
set mode(value: VoiceRecordingMode);
|
|
77
|
+
/**
|
|
78
|
+
* Start recording. In `vad` mode the recording stops automatically on silence.
|
|
79
|
+
* In `pushToTalk` and `holdToTalk` you must call `stop()` manually.
|
|
80
|
+
*/
|
|
81
|
+
start(callbacks?: VoiceRecorderCallbacks): Promise<void>;
|
|
82
|
+
/**
|
|
83
|
+
* Stop recording manually. Required for `pushToTalk` and `holdToTalk`,
|
|
84
|
+
* also works for `vad` (e.g. user wants to stop early).
|
|
85
|
+
*/
|
|
86
|
+
stop(): void;
|
|
87
|
+
private _setupVAD;
|
|
88
|
+
private _cleanup;
|
|
89
|
+
}
|
|
90
|
+
//# sourceMappingURL=VoiceRecorder.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"VoiceRecorder.d.ts","sourceRoot":"","sources":["../../src/utils/VoiceRecorder.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,MAAM,kBAAkB,GAAG,KAAK,GAAG,YAAY,GAAG,YAAY,CAAC;AAErE;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACjC,wCAAwC;IACxC,IAAI,CAAC,EAAE,kBAAkB,CAAC;IAC1B,gDAAgD;IAChD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,6EAA6E;IAC7E,aAAa,CAAC,EAAE,MAAM,CAAC;IAGvB,qFAAqF;IACrF,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,6EAA6E;IAC7E,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,sFAAsF;IACtF,cAAc,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED;;GAEG;AACH,MAAM,WAAW,sBAAsB;IACnC,oCAAoC;IACpC,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,oDAAoD;IACpD,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IACnC,4EAA4E;IAC5E,UAAU,CAAC,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,IAAI,CAAC;IAClC,mCAAmC;IACnC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,oEAAoE;IACpE,MAAM,CAAC,EAAE,MAAM,IAAI,CAAC;CACvB;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,qBAAa,aAAa;IACtB,OAAO,CAAC,QAAQ,CAAiC;IACjD,OAAO,CAAC,cAAc,CAA8B;IACpD,OAAO,CAAC,OAAO,CAA4B;IAC3C,OAAO,CAAC,aAAa,CAA6B;IAClD,OAAO,CAAC,SAAS,CAA6B;IAC9C,OAAO,CAAC,cAAc,CAA+C;IACrE,OAAO,CAAC,eAAe,CAA+C;IACtE,OAAO,CAAC,aAAa,CAA8C;IACnE,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,UAAU,CAAK;IACvB,OAAO,CAAC,UAAU,CAA8B;gBAEpC,OAAO,CAAC,EAAE,oBAAoB;IAW1C,gDAAgD;IAChD,IAAI,WAAW,IAAI,OAAO,CAEzB;IAED,8BAA8B;IAC9B,IAAI,IAAI,IAAI,kBAAkB,CAE7B;IAED,IAAI,IAAI,CAAC,KAAK,EAAE,kBAAkB,EAGjC;IAED;;;OAGG;IACG,KAAK,CAAC,SAAS,CAAC,EAAE,sBAAsB,GAAG,OAAO,CAAC,IAAI,CAAC;IA2D9D;;;OAGG;IACH,IAAI,IAAI,IAAI;IAcZ,OAAO,CAAC,SAAS;IA6CjB,OAAO,CAAC,QAAQ;CA0BnB"}
|