@mosesai/tts 0.0.0-stage → 0.1.1
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/LICENSE +16 -0
- package/README.md +190 -2
- package/dist/index.d.ts +158 -0
- package/dist/moses-tts.iife.js +2 -0
- package/dist/moses-tts.iife.js.map +1 -0
- package/dist/moses-tts.js +268 -0
- package/dist/moses-tts.js.map +1 -0
- package/dist/player.d.ts +22 -0
- package/dist/shared.d.ts +38 -0
- package/llms.txt +27 -0
- package/package.json +62 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Moses AI
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
|
|
6
|
+
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
|
|
7
|
+
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
|
|
8
|
+
persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
9
|
+
|
|
10
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
|
|
11
|
+
Software.
|
|
12
|
+
|
|
13
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
|
|
14
|
+
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
|
15
|
+
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
|
16
|
+
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,191 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @mosesai/tts: streaming text to speech for JavaScript
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**`@mosesai/tts` is the JavaScript and TypeScript client for the Moses TTS API, a text-to-speech service hosted in the EU.** Two things it does:
|
|
4
|
+
|
|
5
|
+
- **Realtime:** stream text in as it's written (for example a language model's tokens) and get spoken audio back while the next sentence is still being generated, over one WebSocket.
|
|
6
|
+
- **Speech:** turn a whole text into a WAV or PCM file with one HTTP call, OpenAI-style.
|
|
7
|
+
|
|
8
|
+
It runs in Node.js 18+ and in browsers, and has no dependencies (about 4 KB gzipped).
|
|
9
|
+
|
|
10
|
+
Use it to give a chatbot, voice agent, assistant, game or notification system a natural voice. It speaks English, German, French, Italian, Portuguese, Spanish and Dutch, and can speak in your own cloned voice.
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
npm install @mosesai/tts
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Quick start
|
|
17
|
+
|
|
18
|
+
**Try it in your browser first:** [moses-ai.com/tts_stt/example_js.html](https://moses-ai.com/tts_stt/example_js.html) runs realtime and whole-text speech with your key, and has the code to copy.
|
|
19
|
+
|
|
20
|
+
Get an API key (`mk_…`) at [moses-ai.com/console](https://moses-ai.com/console) → API keys, with the **TTS** permission.
|
|
21
|
+
|
|
22
|
+
### A whole text to a WAV file (Node.js)
|
|
23
|
+
|
|
24
|
+
```js
|
|
25
|
+
import { writeFile } from "node:fs/promises";
|
|
26
|
+
import { MosesTTS } from "@mosesai/tts";
|
|
27
|
+
|
|
28
|
+
const tts = new MosesTTS({ apiKey: process.env.MOSES_API_KEY });
|
|
29
|
+
const wav = await tts.speech({ input: "Hello! Your order has shipped.", voice: "alba" });
|
|
30
|
+
await writeFile("hello.wav", Buffer.from(wav));
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
### Speak an LLM's answer while it is being written
|
|
34
|
+
|
|
35
|
+
```js
|
|
36
|
+
import { MosesTTS } from "@mosesai/tts";
|
|
37
|
+
|
|
38
|
+
const tts = new MosesTTS({ apiKey: process.env.MOSES_API_KEY });
|
|
39
|
+
const live = await tts.realtime({ voice: "alba" }); // reserves a warm worker: the first audio comes fast
|
|
40
|
+
|
|
41
|
+
live.on("audio", (pcm) => speaker.write(Buffer.from(pcm))); // PCM s16le, mono, 24 kHz, as it is generated
|
|
42
|
+
live.on("segment", (s) => console.log("speaking:", s.text));
|
|
43
|
+
|
|
44
|
+
for await (const token of llmStream) live.send(token); // e.g. the deltas of a chat completion stream
|
|
45
|
+
await live.end(); // resolves when the whole answer has been sent
|
|
46
|
+
live.close();
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
`live.speak(asyncIterable)` does the loop and `end()` in one call. The same session can speak many answers one after another.
|
|
50
|
+
|
|
51
|
+
### In the browser, played as it arrives
|
|
52
|
+
|
|
53
|
+
```js
|
|
54
|
+
import { MosesTTS } from "@mosesai/tts";
|
|
55
|
+
|
|
56
|
+
button.onclick = async () => { // browsers allow sound only after a click
|
|
57
|
+
const tts = new MosesTTS({ apiKey: getKeyFromYourServer });
|
|
58
|
+
const live = await tts.realtime({ voice: "german/juergen", play: true });
|
|
59
|
+
await live.speak("Guten Tag! Das kostet 42 Euro."); // numbers, dates and currencies are read as words
|
|
60
|
+
};
|
|
61
|
+
stopButton.onclick = () => live.cancel(); // barge-in: the audio stops at once
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Or load it without a bundler: `import { MosesTTS } from "https://cdn.jsdelivr.net/npm/@mosesai/tts/+esm"`.
|
|
65
|
+
|
|
66
|
+
## API
|
|
67
|
+
|
|
68
|
+
`new MosesTTS({ apiKey, baseUrl?, WebSocket?, fetch? })`
|
|
69
|
+
|
|
70
|
+
- **`apiKey`:** a string, or a function that returns one (also async).
|
|
71
|
+
- **`baseUrl`:** default `https://moses-ai.com`.
|
|
72
|
+
- **`WebSocket`:** pass `ws` on Node 18–20, which have no global WebSocket.
|
|
73
|
+
|
|
74
|
+
| Method | Returns | What it does |
|
|
75
|
+
|---|---|---|
|
|
76
|
+
| `speech(options)` | `ArrayBuffer` | Whole text → a WAV (or PCM) file. |
|
|
77
|
+
| `speechStream(options)` | `ReadableStream<Uint8Array>` | The same, streamed while it's generated. |
|
|
78
|
+
| `speechResponse(options)` | `Response` | The raw HTTP response. |
|
|
79
|
+
| `realtime(options)` | `RealtimeTTS` | A streaming session (resolves when ready). |
|
|
80
|
+
| `voices()` | `Voice[]` | Built-in voices and your own (`clone:<name>`). |
|
|
81
|
+
| `languages()` | object | Languages, default voices, voice ids. |
|
|
82
|
+
| `stats()` | object | Your limits, what's open now, your credit. |
|
|
83
|
+
|
|
84
|
+
**`speech` options:**
|
|
85
|
+
- `input` (1–20,000 characters; markdown is stripped);
|
|
86
|
+
- `voice`, `language` (`en`, `de`, `fr`, `it`, `pt`, `es`, `nl`);
|
|
87
|
+
- `format` (`"wav"` or `"pcm"`), `signal`;
|
|
88
|
+
- the text options below.
|
|
89
|
+
|
|
90
|
+
**`realtime` options:**
|
|
91
|
+
- `voice`, `language`;
|
|
92
|
+
- `firstChunkChars` (0–300, default 30: lower means an earlier first sound);
|
|
93
|
+
- `warmup` (default `true`);
|
|
94
|
+
- `play` (browsers);
|
|
95
|
+
- the text options below.
|
|
96
|
+
|
|
97
|
+
**Text options**, for both:
|
|
98
|
+
|
|
99
|
+
| Option | Default | Meaning |
|
|
100
|
+
|---|---|---|
|
|
101
|
+
| `normalize` | `true` | Read numbers, dates, times, currencies, units and acronyms as words. |
|
|
102
|
+
| `markup` | `true` | Tags such as `<break time="500ms"/>`, `<lang xml:lang="en">…</lang>`, `<say-as>`. |
|
|
103
|
+
| `acronyms` | `"spell"` | `"spell"` reads API as "A P I"; `"keep"` reads it as written. |
|
|
104
|
+
| `pauses` | | Pause lengths in ms after a sentence, a clause, a paragraph. |
|
|
105
|
+
| `lexicon` | | Your own pronunciations, as `{ "Moses": "Mo-ses" }`. |
|
|
106
|
+
| `trim` | `true` | Exact pauses instead of the model's own silences. |
|
|
107
|
+
| `quantize` | `true` | The 8-bit model: faster, the same voice. |
|
|
108
|
+
|
|
109
|
+
**`RealtimeTTS`:**
|
|
110
|
+
- **Methods:**
|
|
111
|
+
- `send(text)`, `flush()`;
|
|
112
|
+
- `end()` (a promise);
|
|
113
|
+
- `speak(text | asyncIterable)` (a promise);
|
|
114
|
+
- `cancel()` (barge-in), `configure(options)`, `release()`, `close()`.
|
|
115
|
+
- **Events** (with `.on(event, fn)` and `.once(event)`):
|
|
116
|
+
- `ready`;
|
|
117
|
+
- `segment` (`{index, text, end}`), `audio` (`ArrayBuffer` of PCM), `segment_end`;
|
|
118
|
+
- `done`, `cancelled`, `error`, `close`, `idle` (the player went quiet).
|
|
119
|
+
- **`player`:** with `play: true`, a `PcmPlayer` you can `stop()`.
|
|
120
|
+
|
|
121
|
+
**Helpers:**
|
|
122
|
+
- `pcmToWav(chunks, sampleRate = 24000)` joins realtime audio into a WAV file;
|
|
123
|
+
- `PcmPlayer` plays PCM chunks with Web Audio.
|
|
124
|
+
|
|
125
|
+
**Errors** are `MosesAPIError` with:
|
|
126
|
+
- `status`: the HTTP status or WebSocket close code;
|
|
127
|
+
- `code`: for example `unauthorized` (a wrong key), `no_capacity`, `no_credit`, `limit`, `refused` (a realtime connection with a wrong key, scope or website);
|
|
128
|
+
- `message`;
|
|
129
|
+
- `retryAfter`.
|
|
130
|
+
|
|
131
|
+
## Voices and languages
|
|
132
|
+
|
|
133
|
+
| Language | Code | Built-in voices |
|
|
134
|
+
|---|---|---|
|
|
135
|
+
| English | `en` | 21 voices: `alba`, `anna`, `vera`, `mary`, `jane`, `eve`, … (female); `marius`, `jean`, `charles`, `paul`, `george`, `michael`, … (male) |
|
|
136
|
+
| German | `de` | `german/juergen` |
|
|
137
|
+
| French | `fr` | `french/estelle` |
|
|
138
|
+
| Italian | `it` | `italian/giovanni` |
|
|
139
|
+
| Portuguese | `pt` | `portuguese/rafael` |
|
|
140
|
+
| Spanish | `es` | `spanish/lola` |
|
|
141
|
+
| Dutch | `nl` | `dutch/daan` |
|
|
142
|
+
|
|
143
|
+
**Your own voice:**
|
|
144
|
+
- Record or upload 10–20 seconds in the TTS Studio (moses-ai.com/tts → My voices), with consent.
|
|
145
|
+
- Then use `voice: "clone:<name>"`. Your voice speaks every language: `{ voice: "clone:me", language: "de" }`.
|
|
146
|
+
|
|
147
|
+
## FAQ
|
|
148
|
+
|
|
149
|
+
**How do I convert text to speech in Node.js?**
|
|
150
|
+
`await new MosesTTS({ apiKey }).speech({ input: "…" })` returns a WAV file as an `ArrayBuffer`.
|
|
151
|
+
|
|
152
|
+
**How do I stream ChatGPT, Claude or any LLM output to speech in real time?**
|
|
153
|
+
Open `tts.realtime()` and call `send(token)` for every token as it arrives, then `end()`. Each sentence is spoken as soon as its text is complete, while the next one is still being generated.
|
|
154
|
+
|
|
155
|
+
**What audio format do I get?**
|
|
156
|
+
- Realtime: raw PCM, 16-bit signed little-endian, mono, 24 kHz.
|
|
157
|
+
- `speech()`: a WAV file (default) or that PCM.
|
|
158
|
+
- `pcmToWav()` wraps PCM as a WAV file.
|
|
159
|
+
|
|
160
|
+
**Is it OpenAI-compatible?**
|
|
161
|
+
`POST https://moses-ai.com/tts/v1/audio/speech` takes OpenAI's speech request fields (`input`, `voice`, `response_format`, `model` is ignored). The formats offered are WAV and PCM, not mp3 or opus.
|
|
162
|
+
|
|
163
|
+
**How do I interrupt the voice when the user starts talking?**
|
|
164
|
+
Call `live.cancel()`: the audio stops within one chunk, queued text is dropped, and the player (if any) is silenced. For speech recognition, pair it with [`@mosesai/stt`](https://www.npmjs.com/package/@mosesai/stt), whose `speech_started` event marks the moment.
|
|
165
|
+
|
|
166
|
+
**Can I use it in the browser?**
|
|
167
|
+
- **Realtime sessions:** yes. The key is sent as a WebSocket subprotocol, because browsers can't set headers there.
|
|
168
|
+
- **Keys:** keep them secret anyway. In a web page, use a key limited to your website (console → the key → allowed websites), or fetch a key from your server (`apiKey: async () => …`).
|
|
169
|
+
- **HTTP calls** (`speech`, `voices`): from your server.
|
|
170
|
+
- **A full talking agent on your site:** use [`@mosesai/voice`](https://www.npmjs.com/package/@mosesai/voice), which never exposes a key.
|
|
171
|
+
|
|
172
|
+
**How fast is it?**
|
|
173
|
+
- **Realtime:** the first audio typically arrives 0.15–0.35 s after a sentence's text is complete, including the network from within Europe. After that, audio is generated faster than it plays, so playback doesn't stall.
|
|
174
|
+
- **Warm-up:** a realtime session prepares its voice as soon as it opens (the `warmup` option, on by default), so the first sentence is fast too.
|
|
175
|
+
- **`speechStream()`** sends the audio while it's generated, so playback can start before the whole text is done.
|
|
176
|
+
|
|
177
|
+
**Where does it run? Is anything stored?**
|
|
178
|
+
- On Moses' servers in Germany.
|
|
179
|
+
- Speech requests aren't stored, and texts aren't kept. Usage records the number of characters, for billing.
|
|
180
|
+
|
|
181
|
+
**What does it cost?**
|
|
182
|
+
- Prepaid, per character spoken, with a free trial credit for new accounts.
|
|
183
|
+
- Prices are at [moses-ai.com/tts/pricing](https://moses-ai.com/tts/pricing).
|
|
184
|
+
- Limits per account: 2 realtime sessions and 2 speech requests at once.
|
|
185
|
+
|
|
186
|
+
## Related packages
|
|
187
|
+
|
|
188
|
+
- [`@mosesai/stt`](https://www.npmjs.com/package/@mosesai/stt): speech to text, live and from files, in 25 European languages.
|
|
189
|
+
- [`@mosesai/voice`](https://www.npmjs.com/package/@mosesai/voice): a talking AI agent in your web app (speech in, the agent's voice out, interruptions, captions).
|
|
190
|
+
|
|
191
|
+
MIT licence · [moses-ai.com/tts](https://moses-ai.com/tts/) · info@moses-ai.com
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/** @mosesai/tts: text to speech with the Moses TTS API (moses-ai.com/tts), for Node.js and browsers.
|
|
2
|
+
*
|
|
3
|
+
* const tts = new MosesTTS({ apiKey: process.env.MOSES_API_KEY });
|
|
4
|
+
* const wav = await tts.speech({ input: "Hello!", voice: "alba" }); // whole text -> WAV
|
|
5
|
+
* const live = await tts.realtime({ voice: "alba", play: true }); // streaming text -> audio
|
|
6
|
+
* for await (const token of llm) live.send(token);
|
|
7
|
+
* await live.end();
|
|
8
|
+
*/
|
|
9
|
+
import { type ClientOptions, Emitter, MosesAPIError } from "./shared";
|
|
10
|
+
import { PcmPlayer } from "./player";
|
|
11
|
+
export { MosesAPIError, type ClientOptions } from "./shared";
|
|
12
|
+
export { PcmPlayer, pcmToWav } from "./player";
|
|
13
|
+
export declare const VERSION = "0.1.1";
|
|
14
|
+
export declare const SAMPLE_RATE = 24000;
|
|
15
|
+
/** Text settings shared by speech() and realtime config (all optional; server defaults otherwise). */
|
|
16
|
+
export interface TextOptions {
|
|
17
|
+
/** Numbers, dates, currencies, units and acronyms read as words (default true). */
|
|
18
|
+
normalize?: boolean;
|
|
19
|
+
/** Markup tags such as <break time="500ms"/>, <lang xml:lang="en">…</lang>, <say-as> (default true). */
|
|
20
|
+
markup?: boolean;
|
|
21
|
+
/** Exact pauses instead of the model's own silences at the edges (default true). */
|
|
22
|
+
trim?: boolean;
|
|
23
|
+
/** "spell" (API → "A P I", default) or "keep". */
|
|
24
|
+
acronyms?: "spell" | "keep";
|
|
25
|
+
/** Pauses in ms after a sentence, a clause cut, a paragraph (0–3000 each). */
|
|
26
|
+
pauses?: {
|
|
27
|
+
sentence_ms?: number;
|
|
28
|
+
clause_ms?: number;
|
|
29
|
+
paragraph_ms?: number;
|
|
30
|
+
};
|
|
31
|
+
/** Extra pronunciations, {"term": "respelling"} (at most 500). */
|
|
32
|
+
lexicon?: Record<string, string>;
|
|
33
|
+
/** The 8-bit model (default true): faster, the same voice. */
|
|
34
|
+
quantize?: boolean;
|
|
35
|
+
}
|
|
36
|
+
export interface SpeechOptions extends TextOptions {
|
|
37
|
+
/** The text, 1–20000 characters (markdown is stripped). */
|
|
38
|
+
input: string;
|
|
39
|
+
/** A voice id: "alba", "german/juergen", "clone:my-voice" (your own voice), … Default: the language's voice. */
|
|
40
|
+
voice?: string;
|
|
41
|
+
/** en, de, fr, it, pt, es, nl (or english, german, …). Default: the voice's language. */
|
|
42
|
+
language?: string;
|
|
43
|
+
/** "wav" (default) or "pcm" (raw s16le mono 24 kHz). */
|
|
44
|
+
format?: "wav" | "pcm";
|
|
45
|
+
/** Cancels the request (and the generation). */
|
|
46
|
+
signal?: AbortSignal;
|
|
47
|
+
}
|
|
48
|
+
export interface RealtimeOptions extends TextOptions {
|
|
49
|
+
voice?: string;
|
|
50
|
+
language?: string;
|
|
51
|
+
/** Minimum characters before the first segment may be cut at a comma (0–300, default 30). Lower = earlier sound. */
|
|
52
|
+
firstChunkChars?: number;
|
|
53
|
+
/** Reserve a warm worker right away (fast first audio; default true). */
|
|
54
|
+
warmup?: boolean;
|
|
55
|
+
/** Browsers: play the audio as it arrives (Web Audio). */
|
|
56
|
+
play?: boolean | {
|
|
57
|
+
audioContext?: AudioContext;
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
export interface Voice {
|
|
61
|
+
/** What to pass as `voice`: "alba", "german/juergen", "clone:my-voice", … */
|
|
62
|
+
id: string;
|
|
63
|
+
label?: string;
|
|
64
|
+
/** The voice's own language code (en, de, …). */
|
|
65
|
+
lang?: string;
|
|
66
|
+
gender?: string;
|
|
67
|
+
[k: string]: unknown;
|
|
68
|
+
}
|
|
69
|
+
/** The Moses TTS API client. */
|
|
70
|
+
export declare class MosesTTS {
|
|
71
|
+
private opts;
|
|
72
|
+
readonly baseUrl: string;
|
|
73
|
+
constructor(opts: ClientOptions);
|
|
74
|
+
private get;
|
|
75
|
+
/** The voices you can use (built-in, plus your own cloned voices as "clone:<name>"). */
|
|
76
|
+
voices(): Promise<Voice[]>;
|
|
77
|
+
/** Languages with their default voice and all voice ids. */
|
|
78
|
+
languages(): Promise<{
|
|
79
|
+
default_voice: string;
|
|
80
|
+
languages: {
|
|
81
|
+
id: string;
|
|
82
|
+
code: string;
|
|
83
|
+
default_voice: string;
|
|
84
|
+
voices: string[];
|
|
85
|
+
}[];
|
|
86
|
+
}>;
|
|
87
|
+
/** Your limits, what's open now and your credit. */
|
|
88
|
+
stats(): Promise<Record<string, unknown>>;
|
|
89
|
+
/** The raw streaming response of POST /tts/v1/audio/speech (audio arrives while it's generated). */
|
|
90
|
+
speechResponse(o: SpeechOptions): Promise<Response>;
|
|
91
|
+
/** Whole text in, audio out: the complete WAV (or PCM) file. */
|
|
92
|
+
speech(o: SpeechOptions): Promise<ArrayBuffer>;
|
|
93
|
+
/** Whole text in, audio out as a stream of bytes, while it's generated (pipe it to a file or a player). */
|
|
94
|
+
speechStream(o: SpeechOptions): Promise<ReadableStream<Uint8Array>>;
|
|
95
|
+
/** A realtime session: send text as it's written (e.g. an LLM's tokens), get audio while the next sentence is
|
|
96
|
+
* still being generated. Resolves once the session is ready. */
|
|
97
|
+
realtime(o?: RealtimeOptions): Promise<RealtimeTTS>;
|
|
98
|
+
}
|
|
99
|
+
export interface Segment {
|
|
100
|
+
index: number;
|
|
101
|
+
/** The text as written (for captions). */
|
|
102
|
+
text: string;
|
|
103
|
+
end: string;
|
|
104
|
+
ops?: unknown[];
|
|
105
|
+
warnings?: string[];
|
|
106
|
+
}
|
|
107
|
+
export interface RealtimeEvents extends Record<string, unknown> {
|
|
108
|
+
ready: Record<string, unknown>;
|
|
109
|
+
/** A segment (sentence or clause) starts; its audio follows. */
|
|
110
|
+
segment: Segment;
|
|
111
|
+
/** PCM s16le, mono, 24 kHz. */
|
|
112
|
+
audio: ArrayBuffer;
|
|
113
|
+
segment_end: {
|
|
114
|
+
index: number;
|
|
115
|
+
audio_ms: number;
|
|
116
|
+
first_audio_ms: number;
|
|
117
|
+
};
|
|
118
|
+
/** Everything after end() was sent. */
|
|
119
|
+
done: void;
|
|
120
|
+
cancelled: void;
|
|
121
|
+
config: Record<string, unknown>;
|
|
122
|
+
warmed: Record<string, unknown>;
|
|
123
|
+
/** An error message from the server (the session stays open unless "close" follows). */
|
|
124
|
+
error: MosesAPIError;
|
|
125
|
+
close: {
|
|
126
|
+
code: number;
|
|
127
|
+
reason: string;
|
|
128
|
+
error?: MosesAPIError;
|
|
129
|
+
};
|
|
130
|
+
/** Browsers with play: true — the player went quiet. */
|
|
131
|
+
idle: void;
|
|
132
|
+
}
|
|
133
|
+
/** One realtime TTS connection; it can speak many answers one after another. */
|
|
134
|
+
export declare class RealtimeTTS extends Emitter<RealtimeEvents> {
|
|
135
|
+
private ws;
|
|
136
|
+
readonly ready: Promise<Record<string, unknown>>;
|
|
137
|
+
readonly player?: PcmPlayer;
|
|
138
|
+
private lastError?;
|
|
139
|
+
private closed;
|
|
140
|
+
constructor(ws: WebSocket, o: RealtimeOptions);
|
|
141
|
+
private raw;
|
|
142
|
+
/** Change voice, language or text settings for the following segments. */
|
|
143
|
+
configure(o: Omit<RealtimeOptions, "warmup" | "play">): void;
|
|
144
|
+
/** Append text (e.g. one LLM token); complete sentences are spoken at once. */
|
|
145
|
+
send(text: string): void;
|
|
146
|
+
/** Speak what's buffered now, even mid-sentence (e.g. while the LLM calls a tool). */
|
|
147
|
+
flush(): void;
|
|
148
|
+
/** End of the answer: the rest is spoken; resolves when all its audio was sent. */
|
|
149
|
+
end(): Promise<void>;
|
|
150
|
+
/** Barge-in: stop at once, drop queued text and audio (and the player's). */
|
|
151
|
+
cancel(): void;
|
|
152
|
+
/** Speak a whole text or an async stream of text (e.g. an LLM stream); resolves when its audio was sent. */
|
|
153
|
+
speak(text: string | AsyncIterable<string>): Promise<void>;
|
|
154
|
+
/** Give the reserved warm worker back (sessions that will be quiet for a while). */
|
|
155
|
+
release(): void;
|
|
156
|
+
close(): void;
|
|
157
|
+
}
|
|
158
|
+
export default MosesTTS;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var MosesTTS=(function(d){"use strict";const g="https://moses-ai.com";class h extends Error{constructor(e,t,s,r){super(e),this.status=t,this.code=s,this.retryAfter=r,this.name="MosesAPIError"}}async function l(i){const e=typeof i=="function"?await i():i;if(!e)throw new h("No API key: pass apiKey (mk_… from moses-ai.com/console).",401,"key_missing");return e}const b=i=>(i??g).replace(/\/+$/,""),T=i=>i.replace(/^http(s?):\/\//,(e,t)=>t?"wss://":"ws://");async function f(i){let e=`HTTP ${i.status}`,t;try{const r=await i.json(),o=r?.detail??r?.error??r;typeof o=="string"?e=o:o&&typeof o=="object"&&(e=o.message??(Array.isArray(o)?o[0]?.msg:void 0)??e,t=o.code)}catch{}t??(t={401:"unauthorized",402:"no_credit",403:"forbidden",413:"too_large",429:"limit",503:"no_capacity"}[i.status]);const s=Number(i.headers.get("retry-after"));return new h(e,i.status,t,Number.isFinite(s)&&s>0?s:void 0)}function A(i){const e=i.WebSocket??globalThis.WebSocket;if(!e)throw new Error("No WebSocket in this runtime: use Node 22+, or pass { WebSocket } from the `ws` package.");return e}class S{constructor(){this.handlers=new Map}on(e,t){let s=this.handlers.get(e);return s||this.handlers.set(e,s=new Set),s.add(t),this}off(e,t){return this.handlers.get(e)?.delete(t),this}once(e){return new Promise(t=>{const s=r=>{this.off(e,s),t(r)};this.on(e,s)})}emit(e,t){for(const s of this.handlers.get(e)??[])try{s(t)}catch(r){console.error(`moses: a "${String(e)}" handler failed`,r)}}}function y(i,e){const t={4401:["key_invalid","The API key is missing, wrong or deleted."],4402:["no_credit","The prepaid credit is used up: top up at moses-ai.com/console."],4403:["forbidden","The key may not be used here (scope, allowed websites, or the account is paused)."],4408:["timeout","The connection was idle or open too long."],4429:["limit","Too many connections at once, or a daily limit."],1012:["worker_lost","The speech worker went away: reconnect to continue."],1013:["no_capacity","No speech worker is free right now: try again shortly."]},[s,r]=t[i]??["closed",`The connection closed (${i}).`];return{code:s,message:e||r}}class p{constructor(e={}){this.next=0,this.sources=new Set,this.sampleRate=e.sampleRate??24e3,this.own=!e.audioContext,this.context=e.audioContext??new AudioContext,this.context.resume().catch(()=>{})}get playing(){return this.sources.size>0}push(e){const t=new Int16Array(e);if(!t.length)return;const s=this.context.createBuffer(1,t.length,this.sampleRate),r=s.getChannelData(0);for(let a=0;a<t.length;a++)r[a]=t[a]/32768;const o=this.context.createBufferSource();o.buffer=s,o.connect(this.context.destination);const n=Math.max(this.next,this.context.currentTime+.05);o.start(n),this.next=n+s.duration,this.sources.add(o),o.onended=()=>{this.sources.delete(o),this.sources.size||this.onIdle?.()}}stop(){for(const e of this.sources)try{e.stop()}catch{}this.sources.clear(),this.next=0}async close(){this.stop(),this.own&&await this.context.close().catch(()=>{})}}function k(i,e=24e3){const t=Array.isArray(i)?i:[i],s=t.reduce((c,u)=>c+u.byteLength,0),r=new ArrayBuffer(44+s),o=new DataView(r),n=(c,u)=>[...u].forEach((_,U)=>o.setUint8(c+U,_.charCodeAt(0)));n(0,"RIFF"),o.setUint32(4,36+s,!0),n(8,"WAVE"),n(12,"fmt "),o.setUint32(16,16,!0),o.setUint16(20,1,!0),o.setUint16(22,1,!0),o.setUint32(24,e,!0),o.setUint32(28,e*2,!0),o.setUint16(32,2,!0),o.setUint16(34,16,!0),n(36,"data"),o.setUint32(40,s,!0);let a=44;for(const c of t)new Uint8Array(r,a,c.byteLength).set(new Uint8Array(c)),a+=c.byteLength;return r}const v="0.1.1",E=24e3;class w{constructor(e){this.opts=e,this.baseUrl=b(e.baseUrl)}async get(e){const s=await(this.opts.fetch??fetch)(`${this.baseUrl}/tts${e}`,{headers:{Authorization:`Bearer ${await l(this.opts.apiKey)}`}});if(!s.ok)throw await f(s);return s.json()}async voices(){const e=await this.get("/v1/voices");return Array.isArray(e)?e:e.voices??[]}languages(){return this.get("/v1/languages")}stats(){return this.get("/v1/stats")}async speechResponse(e){const{input:t,format:s,signal:r,...o}=e;if(!t?.trim())throw new h("input is empty",400,"bad_input");const a=await(this.opts.fetch??fetch)(`${this.baseUrl}/tts/v1/audio/speech`,{method:"POST",signal:r,headers:{Authorization:`Bearer ${await l(this.opts.apiKey)}`,"Content-Type":"application/json"},body:JSON.stringify({input:t,response_format:s??"wav",...o})});if(!a.ok)throw await f(a);return a}async speech(e){return(await this.speechResponse(e)).arrayBuffer()}async speechStream(e){const t=await this.speechResponse(e);if(!t.body)throw new h("The response has no body",500);return t.body}async realtime(e={}){const t=A(this.opts),s=await l(this.opts.apiKey),r=new t(`${T(this.baseUrl)}/tts/realtime`,["pocket-tts",`bearer.${s}`]),o=new m(r,e);return await o.ready,o}}class m extends S{constructor(e,t){if(super(),this.ws=e,this.closed=!1,e.binaryType="arraybuffer",t.play){if(typeof AudioContext>"u")throw new Error("play: true needs a browser (Web Audio).");this.player=new p({sampleRate:24e3,audioContext:typeof t.play=="object"?t.play.audioContext:void 0}),this.player.onIdle=()=>this.emit("idle",void 0)}this.ready=new Promise((s,r)=>{e.onmessage=n=>{if(typeof n.data!="string"){const c=n.data;this.player?.push(c),this.emit("audio",c);return}const a=JSON.parse(n.data);switch(a.type){case"ready":this.configure(t),t.warmup!==!1&&this.raw({type:"warmup"}),s(a),this.emit("ready",a);break;case"error":{const c=new h(a.message??"error",400,a.code);this.lastError=c,this.emit("error",c);break}case"done":case"cancelled":this.emit(a.type,void 0);break;default:this.emit(a.type,a)}};let o=!1;e.onopen=()=>o=!0,e.onerror=()=>{if(o||this.closed)return;this.closed=!0;const n=new h("The connection was refused: check the API key, its scope and allowed websites.",403,"refused");r(n),this.emit("close",{code:1006,reason:"",error:n})},e.onclose=n=>{if(this.closed&&!o)return;this.closed=!0;const a=n.code===1e3?void 0:this.lastError?new h(this.lastError.message,n.code,this.lastError.code):new h(y(n.code,n.reason).message,n.code,y(n.code,n.reason).code);r(a??new h("closed before ready",n.code)),this.emit("close",{code:n.code,reason:n.reason,...a?{error:a}:{}})}}),this.ready.catch(()=>{})}raw(e){if(this.ws.readyState===1)this.ws.send(JSON.stringify(e));else if(this.closed)throw new h("The realtime session is closed.",0,"closed")}configure(e){const{firstChunkChars:t,...s}=e;delete s.warmup,delete s.play;const r={type:"config",...s};t!==void 0&&(r.first_chunk_chars=t),Object.keys(r).length>1&&this.raw(r)}send(e){e&&this.raw({type:"text",text:e})}flush(){this.raw({type:"flush"})}end(){const e=this.once("done");return this.raw({type:"end"}),e}cancel(){this.player?.stop(),this.raw({type:"cancel"})}async speak(e){if(typeof e=="string")this.send(e);else for await(const t of e)this.send(t);await this.end()}release(){this.raw({type:"release"})}close(){this.closed=!0;try{this.raw({type:"release"})}catch{}this.ws.close(1e3),this.player?.close()}}return d.MosesAPIError=h,d.MosesTTS=w,d.PcmPlayer=p,d.RealtimeTTS=m,d.SAMPLE_RATE=E,d.VERSION=v,d.default=w,d.pcmToWav=k,Object.defineProperties(d,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),d})({});
|
|
2
|
+
//# sourceMappingURL=moses-tts.iife.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"moses-tts.iife.js","sources":["../src/shared.ts","../src/player.ts","../src/index.ts"],"sourcesContent":["/** Small pieces both the HTTP and the realtime parts use: the error type, auth, addresses, a typed emitter. */\n\nexport const DEFAULT_BASE_URL = \"https://moses-ai.com\";\n\n/** An error the Moses API answered with (HTTP status, or a WebSocket close code), with its machine-readable code. */\nexport class MosesAPIError extends Error {\n constructor(\n message: string,\n readonly status: number,\n readonly code?: string,\n readonly retryAfter?: number,\n ) {\n super(message);\n this.name = \"MosesAPIError\";\n }\n}\n\nexport interface ClientOptions {\n /** Your API key (`mk_…`, from moses-ai.com/console). Keep it on your server; in a browser use a key limited to\n * your website (API console → the key → allowed websites), or a function that fetches one. */\n apiKey: string | (() => string | Promise<string>);\n /** Default https://moses-ai.com (or your own Moses server). */\n baseUrl?: string;\n /** A WebSocket implementation for runtimes without a global one (e.g. `ws` on Node 18–20). */\n WebSocket?: typeof WebSocket;\n /** A fetch implementation (default: the global fetch). */\n fetch?: typeof fetch;\n}\n\nexport async function resolveKey(k: ClientOptions[\"apiKey\"]): Promise<string> {\n const key = typeof k === \"function\" ? await k() : k;\n if (!key) throw new MosesAPIError(\"No API key: pass apiKey (mk_… from moses-ai.com/console).\", 401, \"key_missing\");\n return key;\n}\n\nexport const trimBase = (u?: string) => (u ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\nexport const wsBase = (u: string) => u.replace(/^http(s?):\\/\\//, (_m, s) => (s ? \"wss://\" : \"ws://\"));\n\nexport async function apiError(r: Response): Promise<MosesAPIError> {\n let message = `HTTP ${r.status}`;\n let code: string | undefined;\n try {\n const body = await r.json();\n const d = body?.detail ?? body?.error ?? body;\n if (typeof d === \"string\") message = d;\n else if (d && typeof d === \"object\") {\n message = d.message ?? (Array.isArray(d) ? d[0]?.msg : undefined) ?? message;\n code = d.code;\n }\n } catch {\n /* not JSON */\n }\n code ??= { 401: \"unauthorized\", 402: \"no_credit\", 403: \"forbidden\", 413: \"too_large\", 429: \"limit\", 503: \"no_capacity\" }[r.status];\n const retry = Number(r.headers.get(\"retry-after\"));\n return new MosesAPIError(message, r.status, code, Number.isFinite(retry) && retry > 0 ? retry : undefined);\n}\n\nexport function webSocketClass(opts: ClientOptions): typeof WebSocket {\n const W = opts.WebSocket ?? (globalThis as { WebSocket?: typeof WebSocket }).WebSocket;\n if (!W) throw new Error(\"No WebSocket in this runtime: use Node 22+, or pass { WebSocket } from the `ws` package.\");\n return W;\n}\n\n/** A minimal typed event emitter (works the same in browsers and Node). */\nexport class Emitter<E extends Record<string, unknown>> {\n private handlers = new Map<keyof E, Set<(data: never) => void>>();\n on<K extends keyof E>(event: K, fn: (data: E[K]) => void): this {\n let set = this.handlers.get(event);\n if (!set) this.handlers.set(event, (set = new Set()));\n set.add(fn as (data: never) => void);\n return this;\n }\n off<K extends keyof E>(event: K, fn: (data: E[K]) => void): this {\n this.handlers.get(event)?.delete(fn as (data: never) => void);\n return this;\n }\n once<K extends keyof E>(event: K): Promise<E[K]> {\n return new Promise((ok) => {\n const fn = (d: E[K]) => {\n this.off(event, fn);\n ok(d);\n };\n this.on(event, fn);\n });\n }\n protected emit<K extends keyof E>(event: K, data: E[K]) {\n for (const fn of this.handlers.get(event) ?? []) {\n try {\n (fn as (d: E[K]) => void)(data);\n } catch (e) {\n console.error(`moses: a \"${String(event)}\" handler failed`, e);\n }\n }\n }\n}\n\n/** Close codes of the speech gateway, in words. */\nexport function closeReason(code: number, reason: string): { code: string; message: string } {\n const known: Record<number, [string, string]> = {\n 4401: [\"key_invalid\", \"The API key is missing, wrong or deleted.\"],\n 4402: [\"no_credit\", \"The prepaid credit is used up: top up at moses-ai.com/console.\"],\n 4403: [\"forbidden\", \"The key may not be used here (scope, allowed websites, or the account is paused).\"],\n 4408: [\"timeout\", \"The connection was idle or open too long.\"],\n 4429: [\"limit\", \"Too many connections at once, or a daily limit.\"],\n 1012: [\"worker_lost\", \"The speech worker went away: reconnect to continue.\"],\n 1013: [\"no_capacity\", \"No speech worker is free right now: try again shortly.\"],\n };\n const [c, m] = known[code] ?? [\"closed\", `The connection closed (${code}).`];\n return { code: c, message: reason || m };\n}\n","/** Playing PCM s16le mono audio in the browser as it arrives (Web Audio), and wrapping PCM as a WAV file. */\n\nexport class PcmPlayer {\n readonly context: AudioContext;\n private own: boolean;\n private next = 0;\n private sources = new Set<AudioBufferSourceNode>();\n private sampleRate: number;\n /** Called when everything queued has played. */\n onIdle?: () => void;\n\n constructor(o: { sampleRate?: number; audioContext?: AudioContext } = {}) {\n this.sampleRate = o.sampleRate ?? 24000;\n this.own = !o.audioContext;\n this.context = o.audioContext ?? new AudioContext();\n void this.context.resume().catch(() => undefined);\n }\n\n get playing(): boolean {\n return this.sources.size > 0;\n }\n\n /** Queue a chunk of PCM s16le; it plays right after the previous one. */\n push(chunk: ArrayBuffer) {\n const pcm = new Int16Array(chunk);\n if (!pcm.length) return;\n const buf = this.context.createBuffer(1, pcm.length, this.sampleRate);\n const ch = buf.getChannelData(0);\n for (let i = 0; i < pcm.length; i++) ch[i] = pcm[i] / 32768;\n const src = this.context.createBufferSource();\n src.buffer = buf;\n src.connect(this.context.destination);\n const at = Math.max(this.next, this.context.currentTime + 0.05);\n src.start(at);\n this.next = at + buf.duration;\n this.sources.add(src);\n src.onended = () => {\n this.sources.delete(src);\n if (!this.sources.size) this.onIdle?.();\n };\n }\n\n /** Stop at once and drop what's queued (barge-in). */\n stop() {\n for (const s of this.sources) {\n try {\n s.stop();\n } catch {\n /* already stopped */\n }\n }\n this.sources.clear();\n this.next = 0;\n }\n\n async close() {\n this.stop();\n if (this.own) await this.context.close().catch(() => undefined);\n }\n}\n\n/** Wraps raw PCM s16le mono as a WAV file (e.g. the chunks of a realtime session, joined). */\nexport function pcmToWav(chunks: ArrayBuffer | ArrayBuffer[], sampleRate = 24000): ArrayBuffer {\n const list = Array.isArray(chunks) ? chunks : [chunks];\n const size = list.reduce((n, c) => n + c.byteLength, 0);\n const out = new ArrayBuffer(44 + size);\n const v = new DataView(out);\n const ascii = (at: number, s: string) => [...s].forEach((c, i) => v.setUint8(at + i, c.charCodeAt(0)));\n ascii(0, \"RIFF\");\n v.setUint32(4, 36 + size, true);\n ascii(8, \"WAVE\");\n ascii(12, \"fmt \");\n v.setUint32(16, 16, true);\n v.setUint16(20, 1, true);\n v.setUint16(22, 1, true);\n v.setUint32(24, sampleRate, true);\n v.setUint32(28, sampleRate * 2, true);\n v.setUint16(32, 2, true);\n v.setUint16(34, 16, true);\n ascii(36, \"data\");\n v.setUint32(40, size, true);\n let at = 44;\n for (const c of list) {\n new Uint8Array(out, at, c.byteLength).set(new Uint8Array(c));\n at += c.byteLength;\n }\n return out;\n}\n","/** @mosesai/tts: text to speech with the Moses TTS API (moses-ai.com/tts), for Node.js and browsers.\n *\n * const tts = new MosesTTS({ apiKey: process.env.MOSES_API_KEY });\n * const wav = await tts.speech({ input: \"Hello!\", voice: \"alba\" }); // whole text -> WAV\n * const live = await tts.realtime({ voice: \"alba\", play: true }); // streaming text -> audio\n * for await (const token of llm) live.send(token);\n * await live.end();\n */\n\nimport {\n apiError,\n type ClientOptions,\n closeReason,\n Emitter,\n MosesAPIError,\n resolveKey,\n trimBase,\n webSocketClass,\n wsBase,\n} from \"./shared\";\nimport { PcmPlayer } from \"./player\";\n\nexport { MosesAPIError, type ClientOptions } from \"./shared\";\nexport { PcmPlayer, pcmToWav } from \"./player\";\n\nexport const VERSION = \"0.1.1\";\nexport const SAMPLE_RATE = 24000;\n\n/** Text settings shared by speech() and realtime config (all optional; server defaults otherwise). */\nexport interface TextOptions {\n /** Numbers, dates, currencies, units and acronyms read as words (default true). */\n normalize?: boolean;\n /** Markup tags such as <break time=\"500ms\"/>, <lang xml:lang=\"en\">…</lang>, <say-as> (default true). */\n markup?: boolean;\n /** Exact pauses instead of the model's own silences at the edges (default true). */\n trim?: boolean;\n /** \"spell\" (API → \"A P I\", default) or \"keep\". */\n acronyms?: \"spell\" | \"keep\";\n /** Pauses in ms after a sentence, a clause cut, a paragraph (0–3000 each). */\n pauses?: { sentence_ms?: number; clause_ms?: number; paragraph_ms?: number };\n /** Extra pronunciations, {\"term\": \"respelling\"} (at most 500). */\n lexicon?: Record<string, string>;\n /** The 8-bit model (default true): faster, the same voice. */\n quantize?: boolean;\n}\n\nexport interface SpeechOptions extends TextOptions {\n /** The text, 1–20000 characters (markdown is stripped). */\n input: string;\n /** A voice id: \"alba\", \"german/juergen\", \"clone:my-voice\" (your own voice), … Default: the language's voice. */\n voice?: string;\n /** en, de, fr, it, pt, es, nl (or english, german, …). Default: the voice's language. */\n language?: string;\n /** \"wav\" (default) or \"pcm\" (raw s16le mono 24 kHz). */\n format?: \"wav\" | \"pcm\";\n /** Cancels the request (and the generation). */\n signal?: AbortSignal;\n}\n\nexport interface RealtimeOptions extends TextOptions {\n voice?: string;\n language?: string;\n /** Minimum characters before the first segment may be cut at a comma (0–300, default 30). Lower = earlier sound. */\n firstChunkChars?: number;\n /** Reserve a warm worker right away (fast first audio; default true). */\n warmup?: boolean;\n /** Browsers: play the audio as it arrives (Web Audio). */\n play?: boolean | { audioContext?: AudioContext };\n}\n\nexport interface Voice {\n /** What to pass as `voice`: \"alba\", \"german/juergen\", \"clone:my-voice\", … */\n id: string;\n label?: string;\n /** The voice's own language code (en, de, …). */\n lang?: string;\n gender?: string;\n [k: string]: unknown;\n}\n\n/** The Moses TTS API client. */\nexport class MosesTTS {\n readonly baseUrl: string;\n constructor(private opts: ClientOptions) {\n this.baseUrl = trimBase(opts.baseUrl);\n }\n\n private async get<T>(path: string): Promise<T> {\n const f = this.opts.fetch ?? fetch;\n const r = await f(`${this.baseUrl}/tts${path}`, { headers: { Authorization: `Bearer ${await resolveKey(this.opts.apiKey)}` } });\n if (!r.ok) throw await apiError(r);\n return r.json() as Promise<T>;\n }\n\n /** The voices you can use (built-in, plus your own cloned voices as \"clone:<name>\"). */\n async voices(): Promise<Voice[]> {\n const body = await this.get<{ voices?: Voice[] } | Voice[]>(\"/v1/voices\");\n return Array.isArray(body) ? body : (body.voices ?? []);\n }\n\n /** Languages with their default voice and all voice ids. */\n languages(): Promise<{ default_voice: string; languages: { id: string; code: string; default_voice: string; voices: string[] }[] }> {\n return this.get(\"/v1/languages\");\n }\n\n /** Your limits, what's open now and your credit. */\n stats(): Promise<Record<string, unknown>> {\n return this.get(\"/v1/stats\");\n }\n\n /** The raw streaming response of POST /tts/v1/audio/speech (audio arrives while it's generated). */\n async speechResponse(o: SpeechOptions): Promise<Response> {\n const { input, format, signal, ...rest } = o;\n if (!input?.trim()) throw new MosesAPIError(\"input is empty\", 400, \"bad_input\");\n const f = this.opts.fetch ?? fetch;\n const r = await f(`${this.baseUrl}/tts/v1/audio/speech`, {\n method: \"POST\",\n signal,\n headers: { Authorization: `Bearer ${await resolveKey(this.opts.apiKey)}`, \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ input, response_format: format ?? \"wav\", ...rest }),\n });\n if (!r.ok) throw await apiError(r);\n return r;\n }\n\n /** Whole text in, audio out: the complete WAV (or PCM) file. */\n async speech(o: SpeechOptions): Promise<ArrayBuffer> {\n return (await this.speechResponse(o)).arrayBuffer();\n }\n\n /** Whole text in, audio out as a stream of bytes, while it's generated (pipe it to a file or a player). */\n async speechStream(o: SpeechOptions): Promise<ReadableStream<Uint8Array>> {\n const r = await this.speechResponse(o);\n if (!r.body) throw new MosesAPIError(\"The response has no body\", 500);\n return r.body;\n }\n\n /** A realtime session: send text as it's written (e.g. an LLM's tokens), get audio while the next sentence is\n * still being generated. Resolves once the session is ready. */\n async realtime(o: RealtimeOptions = {}): Promise<RealtimeTTS> {\n const W = webSocketClass(this.opts);\n const key = await resolveKey(this.opts.apiKey);\n const ws = new W(`${wsBase(this.baseUrl)}/tts/realtime`, [\"pocket-tts\", `bearer.${key}`]);\n const s = new RealtimeTTS(ws, o);\n await s.ready;\n return s;\n }\n}\n\nexport interface Segment {\n index: number;\n /** The text as written (for captions). */\n text: string;\n end: string;\n ops?: unknown[];\n warnings?: string[];\n}\n\nexport interface RealtimeEvents extends Record<string, unknown> {\n ready: Record<string, unknown>;\n /** A segment (sentence or clause) starts; its audio follows. */\n segment: Segment;\n /** PCM s16le, mono, 24 kHz. */\n audio: ArrayBuffer;\n segment_end: { index: number; audio_ms: number; first_audio_ms: number };\n /** Everything after end() was sent. */\n done: void;\n cancelled: void;\n config: Record<string, unknown>;\n warmed: Record<string, unknown>;\n /** An error message from the server (the session stays open unless \"close\" follows). */\n error: MosesAPIError;\n close: { code: number; reason: string; error?: MosesAPIError };\n /** Browsers with play: true — the player went quiet. */\n idle: void;\n}\n\n/** One realtime TTS connection; it can speak many answers one after another. */\nexport class RealtimeTTS extends Emitter<RealtimeEvents> {\n readonly ready: Promise<Record<string, unknown>>;\n readonly player?: PcmPlayer;\n private lastError?: MosesAPIError;\n private closed = false;\n\n constructor(\n private ws: WebSocket,\n o: RealtimeOptions,\n ) {\n super();\n ws.binaryType = \"arraybuffer\";\n if (o.play) {\n if (typeof AudioContext === \"undefined\") throw new Error(\"play: true needs a browser (Web Audio).\");\n this.player = new PcmPlayer({ sampleRate: 24000, audioContext: typeof o.play === \"object\" ? o.play.audioContext : undefined });\n this.player.onIdle = () => this.emit(\"idle\", undefined);\n }\n this.ready = new Promise((ok, bad) => {\n ws.onmessage = (m: MessageEvent) => {\n if (typeof m.data !== \"string\") {\n const buf = m.data as ArrayBuffer;\n this.player?.push(buf);\n this.emit(\"audio\", buf);\n return;\n }\n const ev = JSON.parse(m.data);\n switch (ev.type) {\n case \"ready\":\n this.configure(o);\n if (o.warmup !== false) this.raw({ type: \"warmup\" });\n ok(ev);\n this.emit(\"ready\", ev);\n break;\n case \"error\": {\n const err = new MosesAPIError(ev.message ?? \"error\", 400, ev.code);\n this.lastError = err;\n this.emit(\"error\", err);\n break;\n }\n case \"done\":\n case \"cancelled\":\n this.emit(ev.type, undefined);\n break;\n default:\n this.emit(ev.type, ev);\n }\n };\n let opened = false;\n ws.onopen = () => (opened = true);\n // a refused handshake (wrong key, scope, website): browsers fire close (1006), Node only error\n ws.onerror = () => {\n if (opened || this.closed) return;\n this.closed = true;\n const err = new MosesAPIError(\"The connection was refused: check the API key, its scope and allowed websites.\", 403, \"refused\");\n bad(err);\n this.emit(\"close\", { code: 1006, reason: \"\", error: err });\n };\n ws.onclose = (e: CloseEvent) => {\n if (this.closed && !opened) return;\n this.closed = true;\n const why = e.code === 1000 ? undefined : this.lastError ? new MosesAPIError(this.lastError.message, e.code, this.lastError.code) : new MosesAPIError(closeReason(e.code, e.reason).message, e.code, closeReason(e.code, e.reason).code);\n bad(why ?? new MosesAPIError(\"closed before ready\", e.code));\n this.emit(\"close\", { code: e.code, reason: e.reason, ...(why ? { error: why } : {}) });\n };\n });\n this.ready.catch(() => undefined);\n }\n\n private raw(msg: object) {\n if (this.ws.readyState === 1) this.ws.send(JSON.stringify(msg));\n else if (this.closed) throw new MosesAPIError(\"The realtime session is closed.\", 0, \"closed\");\n }\n\n /** Change voice, language or text settings for the following segments. */\n configure(o: Omit<RealtimeOptions, \"warmup\" | \"play\">) {\n const { firstChunkChars, ...rest } = o as RealtimeOptions;\n delete (rest as RealtimeOptions).warmup;\n delete (rest as RealtimeOptions).play;\n const msg: Record<string, unknown> = { type: \"config\", ...rest };\n if (firstChunkChars !== undefined) msg.first_chunk_chars = firstChunkChars;\n if (Object.keys(msg).length > 1) this.raw(msg);\n }\n\n /** Append text (e.g. one LLM token); complete sentences are spoken at once. */\n send(text: string) {\n if (text) this.raw({ type: \"text\", text });\n }\n /** Speak what's buffered now, even mid-sentence (e.g. while the LLM calls a tool). */\n flush() {\n this.raw({ type: \"flush\" });\n }\n /** End of the answer: the rest is spoken; resolves when all its audio was sent. */\n end(): Promise<void> {\n const done = this.once(\"done\");\n this.raw({ type: \"end\" });\n return done;\n }\n /** Barge-in: stop at once, drop queued text and audio (and the player's). */\n cancel() {\n this.player?.stop();\n this.raw({ type: \"cancel\" });\n }\n /** Speak a whole text or an async stream of text (e.g. an LLM stream); resolves when its audio was sent. */\n async speak(text: string | AsyncIterable<string>): Promise<void> {\n if (typeof text === \"string\") this.send(text);\n else for await (const t of text) this.send(t);\n await this.end();\n }\n /** Give the reserved warm worker back (sessions that will be quiet for a while). */\n release() {\n this.raw({ type: \"release\" });\n }\n close() {\n this.closed = true;\n try {\n this.raw({ type: \"release\" });\n } catch {\n /* closing anyway */\n }\n this.ws.close(1000);\n void this.player?.close();\n }\n}\n\nexport default MosesTTS;\n"],"names":["DEFAULT_BASE_URL","MosesAPIError","message","status","code","retryAfter","resolveKey","k","key","trimBase","u","wsBase","_m","s","apiError","r","body","d","retry","webSocketClass","opts","W","Emitter","event","fn","set","ok","data","e","closeReason","reason","known","c","m","PcmPlayer","o","chunk","pcm","buf","ch","i","src","at","pcmToWav","chunks","sampleRate","list","size","n","out","v","ascii","VERSION","SAMPLE_RATE","MosesTTS","path","input","format","signal","rest","ws","RealtimeTTS","bad","ev","err","opened","why","msg","firstChunkChars","text","done"],"mappings":"uCAEO,MAAMA,EAAmB,uBAGzB,MAAMC,UAAsB,KAAM,CACvC,YACEC,EACSC,EACAC,EACAC,EACT,CACA,MAAMH,CAAO,EAJJ,KAAA,OAAAC,EACA,KAAA,KAAAC,EACA,KAAA,WAAAC,EAGT,KAAK,KAAO,eACd,CACF,CAcA,eAAsBC,EAAWC,EAA6C,CAC5E,MAAMC,EAAM,OAAOD,GAAM,WAAa,MAAMA,IAAMA,EAClD,GAAI,CAACC,EA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B,MAAMC,EAAO,KAAK,KAAK,MAAM,EAC7B,YAAK,IAAI,CAAE,KAAM,KAAA,CAAO,EACjBA,CACT,CAEA,QAAS,CACP,KAAK,QAAQ,KAAA,EACb,KAAK,IAAI,CAAE,KAAM,QAAA,CAAU,CAC7B,CAEA,MAAM,MAAMD,EAAqD,CAC/D,GAAI,OAAOA,GAAS,SAAU,KAAK,KAAKA,CAAI,MACvC,iBAAiB,KAAKA,EAAM,KAAK,KAAK,CAAC,EAC5C,MAAM,KAAK,IAAA,CACb,CAEA,SAAU,CACR,KAAK,IAAI,CAAE,KAAM,SAAA,CAAW,CAC9B,CACA,OAAQ,CACN,KAAK,OAAS,GACd,GAAI,CACF,KAAK,IAAI,CAAE,KAAM,SAAA,CAAW,CAC9B,MAAQ,CAER,CACA,KAAK,GAAG,MAAM,GAAI,EACb,KAAK,QAAQ,MAAA,CACpB,CACF"}
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
const w = "https://moses-ai.com";
|
|
2
|
+
class h extends Error {
|
|
3
|
+
constructor(e, t, s, r) {
|
|
4
|
+
super(e), this.status = t, this.code = s, this.retryAfter = r, this.name = "MosesAPIError";
|
|
5
|
+
}
|
|
6
|
+
}
|
|
7
|
+
async function l(i) {
|
|
8
|
+
const e = typeof i == "function" ? await i() : i;
|
|
9
|
+
if (!e) throw new h("No API key: pass apiKey (mk_… from moses-ai.com/console).", 401, "key_missing");
|
|
10
|
+
return e;
|
|
11
|
+
}
|
|
12
|
+
const m = (i) => (i ?? w).replace(/\/+$/, ""), g = (i) => i.replace(/^http(s?):\/\//, (e, t) => t ? "wss://" : "ws://");
|
|
13
|
+
async function u(i) {
|
|
14
|
+
let e = `HTTP ${i.status}`, t;
|
|
15
|
+
try {
|
|
16
|
+
const r = await i.json(), o = r?.detail ?? r?.error ?? r;
|
|
17
|
+
typeof o == "string" ? e = o : o && typeof o == "object" && (e = o.message ?? (Array.isArray(o) ? o[0]?.msg : void 0) ?? e, t = o.code);
|
|
18
|
+
} catch {
|
|
19
|
+
}
|
|
20
|
+
t ?? (t = { 401: "unauthorized", 402: "no_credit", 403: "forbidden", 413: "too_large", 429: "limit", 503: "no_capacity" }[i.status]);
|
|
21
|
+
const s = Number(i.headers.get("retry-after"));
|
|
22
|
+
return new h(e, i.status, t, Number.isFinite(s) && s > 0 ? s : void 0);
|
|
23
|
+
}
|
|
24
|
+
function b(i) {
|
|
25
|
+
const e = i.WebSocket ?? globalThis.WebSocket;
|
|
26
|
+
if (!e) throw new Error("No WebSocket in this runtime: use Node 22+, or pass { WebSocket } from the `ws` package.");
|
|
27
|
+
return e;
|
|
28
|
+
}
|
|
29
|
+
class A {
|
|
30
|
+
constructor() {
|
|
31
|
+
this.handlers = /* @__PURE__ */ new Map();
|
|
32
|
+
}
|
|
33
|
+
on(e, t) {
|
|
34
|
+
let s = this.handlers.get(e);
|
|
35
|
+
return s || this.handlers.set(e, s = /* @__PURE__ */ new Set()), s.add(t), this;
|
|
36
|
+
}
|
|
37
|
+
off(e, t) {
|
|
38
|
+
return this.handlers.get(e)?.delete(t), this;
|
|
39
|
+
}
|
|
40
|
+
once(e) {
|
|
41
|
+
return new Promise((t) => {
|
|
42
|
+
const s = (r) => {
|
|
43
|
+
this.off(e, s), t(r);
|
|
44
|
+
};
|
|
45
|
+
this.on(e, s);
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
emit(e, t) {
|
|
49
|
+
for (const s of this.handlers.get(e) ?? [])
|
|
50
|
+
try {
|
|
51
|
+
s(t);
|
|
52
|
+
} catch (r) {
|
|
53
|
+
console.error(`moses: a "${String(e)}" handler failed`, r);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function f(i, e) {
|
|
58
|
+
const t = {
|
|
59
|
+
4401: ["key_invalid", "The API key is missing, wrong or deleted."],
|
|
60
|
+
4402: ["no_credit", "The prepaid credit is used up: top up at moses-ai.com/console."],
|
|
61
|
+
4403: ["forbidden", "The key may not be used here (scope, allowed websites, or the account is paused)."],
|
|
62
|
+
4408: ["timeout", "The connection was idle or open too long."],
|
|
63
|
+
4429: ["limit", "Too many connections at once, or a daily limit."],
|
|
64
|
+
1012: ["worker_lost", "The speech worker went away: reconnect to continue."],
|
|
65
|
+
1013: ["no_capacity", "No speech worker is free right now: try again shortly."]
|
|
66
|
+
}, [s, r] = t[i] ?? ["closed", `The connection closed (${i}).`];
|
|
67
|
+
return { code: s, message: e || r };
|
|
68
|
+
}
|
|
69
|
+
class k {
|
|
70
|
+
constructor(e = {}) {
|
|
71
|
+
this.next = 0, this.sources = /* @__PURE__ */ new Set(), this.sampleRate = e.sampleRate ?? 24e3, this.own = !e.audioContext, this.context = e.audioContext ?? new AudioContext(), this.context.resume().catch(() => {
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
get playing() {
|
|
75
|
+
return this.sources.size > 0;
|
|
76
|
+
}
|
|
77
|
+
/** Queue a chunk of PCM s16le; it plays right after the previous one. */
|
|
78
|
+
push(e) {
|
|
79
|
+
const t = new Int16Array(e);
|
|
80
|
+
if (!t.length) return;
|
|
81
|
+
const s = this.context.createBuffer(1, t.length, this.sampleRate), r = s.getChannelData(0);
|
|
82
|
+
for (let a = 0; a < t.length; a++) r[a] = t[a] / 32768;
|
|
83
|
+
const o = this.context.createBufferSource();
|
|
84
|
+
o.buffer = s, o.connect(this.context.destination);
|
|
85
|
+
const n = Math.max(this.next, this.context.currentTime + 0.05);
|
|
86
|
+
o.start(n), this.next = n + s.duration, this.sources.add(o), o.onended = () => {
|
|
87
|
+
this.sources.delete(o), this.sources.size || this.onIdle?.();
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
/** Stop at once and drop what's queued (barge-in). */
|
|
91
|
+
stop() {
|
|
92
|
+
for (const e of this.sources)
|
|
93
|
+
try {
|
|
94
|
+
e.stop();
|
|
95
|
+
} catch {
|
|
96
|
+
}
|
|
97
|
+
this.sources.clear(), this.next = 0;
|
|
98
|
+
}
|
|
99
|
+
async close() {
|
|
100
|
+
this.stop(), this.own && await this.context.close().catch(() => {
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
function v(i, e = 24e3) {
|
|
105
|
+
const t = Array.isArray(i) ? i : [i], s = t.reduce((c, d) => c + d.byteLength, 0), r = new ArrayBuffer(44 + s), o = new DataView(r), n = (c, d) => [...d].forEach((y, p) => o.setUint8(c + p, y.charCodeAt(0)));
|
|
106
|
+
n(0, "RIFF"), o.setUint32(4, 36 + s, !0), n(8, "WAVE"), n(12, "fmt "), o.setUint32(16, 16, !0), o.setUint16(20, 1, !0), o.setUint16(22, 1, !0), o.setUint32(24, e, !0), o.setUint32(28, e * 2, !0), o.setUint16(32, 2, !0), o.setUint16(34, 16, !0), n(36, "data"), o.setUint32(40, s, !0);
|
|
107
|
+
let a = 44;
|
|
108
|
+
for (const c of t)
|
|
109
|
+
new Uint8Array(r, a, c.byteLength).set(new Uint8Array(c)), a += c.byteLength;
|
|
110
|
+
return r;
|
|
111
|
+
}
|
|
112
|
+
const S = "0.1.1", x = 24e3;
|
|
113
|
+
class U {
|
|
114
|
+
constructor(e) {
|
|
115
|
+
this.opts = e, this.baseUrl = m(e.baseUrl);
|
|
116
|
+
}
|
|
117
|
+
async get(e) {
|
|
118
|
+
const s = await (this.opts.fetch ?? fetch)(`${this.baseUrl}/tts${e}`, { headers: { Authorization: `Bearer ${await l(this.opts.apiKey)}` } });
|
|
119
|
+
if (!s.ok) throw await u(s);
|
|
120
|
+
return s.json();
|
|
121
|
+
}
|
|
122
|
+
/** The voices you can use (built-in, plus your own cloned voices as "clone:<name>"). */
|
|
123
|
+
async voices() {
|
|
124
|
+
const e = await this.get("/v1/voices");
|
|
125
|
+
return Array.isArray(e) ? e : e.voices ?? [];
|
|
126
|
+
}
|
|
127
|
+
/** Languages with their default voice and all voice ids. */
|
|
128
|
+
languages() {
|
|
129
|
+
return this.get("/v1/languages");
|
|
130
|
+
}
|
|
131
|
+
/** Your limits, what's open now and your credit. */
|
|
132
|
+
stats() {
|
|
133
|
+
return this.get("/v1/stats");
|
|
134
|
+
}
|
|
135
|
+
/** The raw streaming response of POST /tts/v1/audio/speech (audio arrives while it's generated). */
|
|
136
|
+
async speechResponse(e) {
|
|
137
|
+
const { input: t, format: s, signal: r, ...o } = e;
|
|
138
|
+
if (!t?.trim()) throw new h("input is empty", 400, "bad_input");
|
|
139
|
+
const a = await (this.opts.fetch ?? fetch)(`${this.baseUrl}/tts/v1/audio/speech`, {
|
|
140
|
+
method: "POST",
|
|
141
|
+
signal: r,
|
|
142
|
+
headers: { Authorization: `Bearer ${await l(this.opts.apiKey)}`, "Content-Type": "application/json" },
|
|
143
|
+
body: JSON.stringify({ input: t, response_format: s ?? "wav", ...o })
|
|
144
|
+
});
|
|
145
|
+
if (!a.ok) throw await u(a);
|
|
146
|
+
return a;
|
|
147
|
+
}
|
|
148
|
+
/** Whole text in, audio out: the complete WAV (or PCM) file. */
|
|
149
|
+
async speech(e) {
|
|
150
|
+
return (await this.speechResponse(e)).arrayBuffer();
|
|
151
|
+
}
|
|
152
|
+
/** Whole text in, audio out as a stream of bytes, while it's generated (pipe it to a file or a player). */
|
|
153
|
+
async speechStream(e) {
|
|
154
|
+
const t = await this.speechResponse(e);
|
|
155
|
+
if (!t.body) throw new h("The response has no body", 500);
|
|
156
|
+
return t.body;
|
|
157
|
+
}
|
|
158
|
+
/** A realtime session: send text as it's written (e.g. an LLM's tokens), get audio while the next sentence is
|
|
159
|
+
* still being generated. Resolves once the session is ready. */
|
|
160
|
+
async realtime(e = {}) {
|
|
161
|
+
const t = b(this.opts), s = await l(this.opts.apiKey), r = new t(`${g(this.baseUrl)}/tts/realtime`, ["pocket-tts", `bearer.${s}`]), o = new T(r, e);
|
|
162
|
+
return await o.ready, o;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
class T extends A {
|
|
166
|
+
constructor(e, t) {
|
|
167
|
+
if (super(), this.ws = e, this.closed = !1, e.binaryType = "arraybuffer", t.play) {
|
|
168
|
+
if (typeof AudioContext > "u") throw new Error("play: true needs a browser (Web Audio).");
|
|
169
|
+
this.player = new k({ sampleRate: 24e3, audioContext: typeof t.play == "object" ? t.play.audioContext : void 0 }), this.player.onIdle = () => this.emit("idle", void 0);
|
|
170
|
+
}
|
|
171
|
+
this.ready = new Promise((s, r) => {
|
|
172
|
+
e.onmessage = (n) => {
|
|
173
|
+
if (typeof n.data != "string") {
|
|
174
|
+
const c = n.data;
|
|
175
|
+
this.player?.push(c), this.emit("audio", c);
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
const a = JSON.parse(n.data);
|
|
179
|
+
switch (a.type) {
|
|
180
|
+
case "ready":
|
|
181
|
+
this.configure(t), t.warmup !== !1 && this.raw({ type: "warmup" }), s(a), this.emit("ready", a);
|
|
182
|
+
break;
|
|
183
|
+
case "error": {
|
|
184
|
+
const c = new h(a.message ?? "error", 400, a.code);
|
|
185
|
+
this.lastError = c, this.emit("error", c);
|
|
186
|
+
break;
|
|
187
|
+
}
|
|
188
|
+
case "done":
|
|
189
|
+
case "cancelled":
|
|
190
|
+
this.emit(a.type, void 0);
|
|
191
|
+
break;
|
|
192
|
+
default:
|
|
193
|
+
this.emit(a.type, a);
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
let o = !1;
|
|
197
|
+
e.onopen = () => o = !0, e.onerror = () => {
|
|
198
|
+
if (o || this.closed) return;
|
|
199
|
+
this.closed = !0;
|
|
200
|
+
const n = new h("The connection was refused: check the API key, its scope and allowed websites.", 403, "refused");
|
|
201
|
+
r(n), this.emit("close", { code: 1006, reason: "", error: n });
|
|
202
|
+
}, e.onclose = (n) => {
|
|
203
|
+
if (this.closed && !o) return;
|
|
204
|
+
this.closed = !0;
|
|
205
|
+
const a = n.code === 1e3 ? void 0 : this.lastError ? new h(this.lastError.message, n.code, this.lastError.code) : new h(f(n.code, n.reason).message, n.code, f(n.code, n.reason).code);
|
|
206
|
+
r(a ?? new h("closed before ready", n.code)), this.emit("close", { code: n.code, reason: n.reason, ...a ? { error: a } : {} });
|
|
207
|
+
};
|
|
208
|
+
}), this.ready.catch(() => {
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
raw(e) {
|
|
212
|
+
if (this.ws.readyState === 1) this.ws.send(JSON.stringify(e));
|
|
213
|
+
else if (this.closed) throw new h("The realtime session is closed.", 0, "closed");
|
|
214
|
+
}
|
|
215
|
+
/** Change voice, language or text settings for the following segments. */
|
|
216
|
+
configure(e) {
|
|
217
|
+
const { firstChunkChars: t, ...s } = e;
|
|
218
|
+
delete s.warmup, delete s.play;
|
|
219
|
+
const r = { type: "config", ...s };
|
|
220
|
+
t !== void 0 && (r.first_chunk_chars = t), Object.keys(r).length > 1 && this.raw(r);
|
|
221
|
+
}
|
|
222
|
+
/** Append text (e.g. one LLM token); complete sentences are spoken at once. */
|
|
223
|
+
send(e) {
|
|
224
|
+
e && this.raw({ type: "text", text: e });
|
|
225
|
+
}
|
|
226
|
+
/** Speak what's buffered now, even mid-sentence (e.g. while the LLM calls a tool). */
|
|
227
|
+
flush() {
|
|
228
|
+
this.raw({ type: "flush" });
|
|
229
|
+
}
|
|
230
|
+
/** End of the answer: the rest is spoken; resolves when all its audio was sent. */
|
|
231
|
+
end() {
|
|
232
|
+
const e = this.once("done");
|
|
233
|
+
return this.raw({ type: "end" }), e;
|
|
234
|
+
}
|
|
235
|
+
/** Barge-in: stop at once, drop queued text and audio (and the player's). */
|
|
236
|
+
cancel() {
|
|
237
|
+
this.player?.stop(), this.raw({ type: "cancel" });
|
|
238
|
+
}
|
|
239
|
+
/** Speak a whole text or an async stream of text (e.g. an LLM stream); resolves when its audio was sent. */
|
|
240
|
+
async speak(e) {
|
|
241
|
+
if (typeof e == "string") this.send(e);
|
|
242
|
+
else for await (const t of e) this.send(t);
|
|
243
|
+
await this.end();
|
|
244
|
+
}
|
|
245
|
+
/** Give the reserved warm worker back (sessions that will be quiet for a while). */
|
|
246
|
+
release() {
|
|
247
|
+
this.raw({ type: "release" });
|
|
248
|
+
}
|
|
249
|
+
close() {
|
|
250
|
+
this.closed = !0;
|
|
251
|
+
try {
|
|
252
|
+
this.raw({ type: "release" });
|
|
253
|
+
} catch {
|
|
254
|
+
}
|
|
255
|
+
this.ws.close(1e3), this.player?.close();
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
export {
|
|
259
|
+
h as MosesAPIError,
|
|
260
|
+
U as MosesTTS,
|
|
261
|
+
k as PcmPlayer,
|
|
262
|
+
T as RealtimeTTS,
|
|
263
|
+
x as SAMPLE_RATE,
|
|
264
|
+
S as VERSION,
|
|
265
|
+
U as default,
|
|
266
|
+
v as pcmToWav
|
|
267
|
+
};
|
|
268
|
+
//# sourceMappingURL=moses-tts.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"moses-tts.js","sources":["../src/shared.ts","../src/player.ts","../src/index.ts"],"sourcesContent":["/** Small pieces both the HTTP and the realtime parts use: the error type, auth, addresses, a typed emitter. */\n\nexport const DEFAULT_BASE_URL = \"https://moses-ai.com\";\n\n/** An error the Moses API answered with (HTTP status, or a WebSocket close code), with its machine-readable code. */\nexport class MosesAPIError extends Error {\n constructor(\n message: string,\n readonly status: number,\n readonly code?: string,\n readonly retryAfter?: number,\n ) {\n super(message);\n this.name = \"MosesAPIError\";\n }\n}\n\nexport interface ClientOptions {\n /** Your API key (`mk_…`, from moses-ai.com/console). Keep it on your server; in a browser use a key limited to\n * your website (API console → the key → allowed websites), or a function that fetches one. */\n apiKey: string | (() => string | Promise<string>);\n /** Default https://moses-ai.com (or your own Moses server). */\n baseUrl?: string;\n /** A WebSocket implementation for runtimes without a global one (e.g. `ws` on Node 18–20). */\n WebSocket?: typeof WebSocket;\n /** A fetch implementation (default: the global fetch). */\n fetch?: typeof fetch;\n}\n\nexport async function resolveKey(k: ClientOptions[\"apiKey\"]): Promise<string> {\n const key = typeof k === \"function\" ? await k() : k;\n if (!key) throw new MosesAPIError(\"No API key: pass apiKey (mk_… from moses-ai.com/console).\", 401, \"key_missing\");\n return key;\n}\n\nexport const trimBase = (u?: string) => (u ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\nexport const wsBase = (u: string) => u.replace(/^http(s?):\\/\\//, (_m, s) => (s ? \"wss://\" : \"ws://\"));\n\nexport async function apiError(r: Response): Promise<MosesAPIError> {\n let message = `HTTP ${r.status}`;\n let code: string | undefined;\n try {\n const body = await r.json();\n const d = body?.detail ?? body?.error ?? body;\n if (typeof d === \"string\") message = d;\n else if (d && typeof d === \"object\") {\n message = d.message ?? (Array.isArray(d) ? d[0]?.msg : undefined) ?? message;\n code = d.code;\n }\n } catch {\n /* not JSON */\n }\n code ??= { 401: \"unauthorized\", 402: \"no_credit\", 403: \"forbidden\", 413: \"too_large\", 429: \"limit\", 503: \"no_capacity\" }[r.status];\n const retry = Number(r.headers.get(\"retry-after\"));\n return new MosesAPIError(message, r.status, code, Number.isFinite(retry) && retry > 0 ? retry : undefined);\n}\n\nexport function webSocketClass(opts: ClientOptions): typeof WebSocket {\n const W = opts.WebSocket ?? (globalThis as { WebSocket?: typeof WebSocket }).WebSocket;\n if (!W) throw new Error(\"No WebSocket in this runtime: use Node 22+, or pass { WebSocket } from the `ws` package.\");\n return W;\n}\n\n/** A minimal typed event emitter (works the same in browsers and Node). */\nexport class Emitter<E extends Record<string, unknown>> {\n private handlers = new Map<keyof E, Set<(data: never) => void>>();\n on<K extends keyof E>(event: K, fn: (data: E[K]) => void): this {\n let set = this.handlers.get(event);\n if (!set) this.handlers.set(event, (set = new Set()));\n set.add(fn as (data: never) => void);\n return this;\n }\n off<K extends keyof E>(event: K, fn: (data: E[K]) => void): this {\n this.handlers.get(event)?.delete(fn as (data: never) => void);\n return this;\n }\n once<K extends keyof E>(event: K): Promise<E[K]> {\n return new Promise((ok) => {\n const fn = (d: E[K]) => {\n this.off(event, fn);\n ok(d);\n };\n this.on(event, fn);\n });\n }\n protected emit<K extends keyof E>(event: K, data: E[K]) {\n for (const fn of this.handlers.get(event) ?? []) {\n try {\n (fn as (d: E[K]) => void)(data);\n } catch (e) {\n console.error(`moses: a \"${String(event)}\" handler failed`, e);\n }\n }\n }\n}\n\n/** Close codes of the speech gateway, in words. */\nexport function closeReason(code: number, reason: string): { code: string; message: string } {\n const known: Record<number, [string, string]> = {\n 4401: [\"key_invalid\", \"The API key is missing, wrong or deleted.\"],\n 4402: [\"no_credit\", \"The prepaid credit is used up: top up at moses-ai.com/console.\"],\n 4403: [\"forbidden\", \"The key may not be used here (scope, allowed websites, or the account is paused).\"],\n 4408: [\"timeout\", \"The connection was idle or open too long.\"],\n 4429: [\"limit\", \"Too many connections at once, or a daily limit.\"],\n 1012: [\"worker_lost\", \"The speech worker went away: reconnect to continue.\"],\n 1013: [\"no_capacity\", \"No speech worker is free right now: try again shortly.\"],\n };\n const [c, m] = known[code] ?? [\"closed\", `The connection closed (${code}).`];\n return { code: c, message: reason || m };\n}\n","/** Playing PCM s16le mono audio in the browser as it arrives (Web Audio), and wrapping PCM as a WAV file. */\n\nexport class PcmPlayer {\n readonly context: AudioContext;\n private own: boolean;\n private next = 0;\n private sources = new Set<AudioBufferSourceNode>();\n private sampleRate: number;\n /** Called when everything queued has played. */\n onIdle?: () => void;\n\n constructor(o: { sampleRate?: number; audioContext?: AudioContext } = {}) {\n this.sampleRate = o.sampleRate ?? 24000;\n this.own = !o.audioContext;\n this.context = o.audioContext ?? new AudioContext();\n void this.context.resume().catch(() => undefined);\n }\n\n get playing(): boolean {\n return this.sources.size > 0;\n }\n\n /** Queue a chunk of PCM s16le; it plays right after the previous one. */\n push(chunk: ArrayBuffer) {\n const pcm = new Int16Array(chunk);\n if (!pcm.length) return;\n const buf = this.context.createBuffer(1, pcm.length, this.sampleRate);\n const ch = buf.getChannelData(0);\n for (let i = 0; i < pcm.length; i++) ch[i] = pcm[i] / 32768;\n const src = this.context.createBufferSource();\n src.buffer = buf;\n src.connect(this.context.destination);\n const at = Math.max(this.next, this.context.currentTime + 0.05);\n src.start(at);\n this.next = at + buf.duration;\n this.sources.add(src);\n src.onended = () => {\n this.sources.delete(src);\n if (!this.sources.size) this.onIdle?.();\n };\n }\n\n /** Stop at once and drop what's queued (barge-in). */\n stop() {\n for (const s of this.sources) {\n try {\n s.stop();\n } catch {\n /* already stopped */\n }\n }\n this.sources.clear();\n this.next = 0;\n }\n\n async close() {\n this.stop();\n if (this.own) await this.context.close().catch(() => undefined);\n }\n}\n\n/** Wraps raw PCM s16le mono as a WAV file (e.g. the chunks of a realtime session, joined). */\nexport function pcmToWav(chunks: ArrayBuffer | ArrayBuffer[], sampleRate = 24000): ArrayBuffer {\n const list = Array.isArray(chunks) ? chunks : [chunks];\n const size = list.reduce((n, c) => n + c.byteLength, 0);\n const out = new ArrayBuffer(44 + size);\n const v = new DataView(out);\n const ascii = (at: number, s: string) => [...s].forEach((c, i) => v.setUint8(at + i, c.charCodeAt(0)));\n ascii(0, \"RIFF\");\n v.setUint32(4, 36 + size, true);\n ascii(8, \"WAVE\");\n ascii(12, \"fmt \");\n v.setUint32(16, 16, true);\n v.setUint16(20, 1, true);\n v.setUint16(22, 1, true);\n v.setUint32(24, sampleRate, true);\n v.setUint32(28, sampleRate * 2, true);\n v.setUint16(32, 2, true);\n v.setUint16(34, 16, true);\n ascii(36, \"data\");\n v.setUint32(40, size, true);\n let at = 44;\n for (const c of list) {\n new Uint8Array(out, at, c.byteLength).set(new Uint8Array(c));\n at += c.byteLength;\n }\n return out;\n}\n","/** @mosesai/tts: text to speech with the Moses TTS API (moses-ai.com/tts), for Node.js and browsers.\n *\n * const tts = new MosesTTS({ apiKey: process.env.MOSES_API_KEY });\n * const wav = await tts.speech({ input: \"Hello!\", voice: \"alba\" }); // whole text -> WAV\n * const live = await tts.realtime({ voice: \"alba\", play: true }); // streaming text -> audio\n * for await (const token of llm) live.send(token);\n * await live.end();\n */\n\nimport {\n apiError,\n type ClientOptions,\n closeReason,\n Emitter,\n MosesAPIError,\n resolveKey,\n trimBase,\n webSocketClass,\n wsBase,\n} from \"./shared\";\nimport { PcmPlayer } from \"./player\";\n\nexport { MosesAPIError, type ClientOptions } from \"./shared\";\nexport { PcmPlayer, pcmToWav } from \"./player\";\n\nexport const VERSION = \"0.1.1\";\nexport const SAMPLE_RATE = 24000;\n\n/** Text settings shared by speech() and realtime config (all optional; server defaults otherwise). */\nexport interface TextOptions {\n /** Numbers, dates, currencies, units and acronyms read as words (default true). */\n normalize?: boolean;\n /** Markup tags such as <break time=\"500ms\"/>, <lang xml:lang=\"en\">…</lang>, <say-as> (default true). */\n markup?: boolean;\n /** Exact pauses instead of the model's own silences at the edges (default true). */\n trim?: boolean;\n /** \"spell\" (API → \"A P I\", default) or \"keep\". */\n acronyms?: \"spell\" | \"keep\";\n /** Pauses in ms after a sentence, a clause cut, a paragraph (0–3000 each). */\n pauses?: { sentence_ms?: number; clause_ms?: number; paragraph_ms?: number };\n /** Extra pronunciations, {\"term\": \"respelling\"} (at most 500). */\n lexicon?: Record<string, string>;\n /** The 8-bit model (default true): faster, the same voice. */\n quantize?: boolean;\n}\n\nexport interface SpeechOptions extends TextOptions {\n /** The text, 1–20000 characters (markdown is stripped). */\n input: string;\n /** A voice id: \"alba\", \"german/juergen\", \"clone:my-voice\" (your own voice), … Default: the language's voice. */\n voice?: string;\n /** en, de, fr, it, pt, es, nl (or english, german, …). Default: the voice's language. */\n language?: string;\n /** \"wav\" (default) or \"pcm\" (raw s16le mono 24 kHz). */\n format?: \"wav\" | \"pcm\";\n /** Cancels the request (and the generation). */\n signal?: AbortSignal;\n}\n\nexport interface RealtimeOptions extends TextOptions {\n voice?: string;\n language?: string;\n /** Minimum characters before the first segment may be cut at a comma (0–300, default 30). Lower = earlier sound. */\n firstChunkChars?: number;\n /** Reserve a warm worker right away (fast first audio; default true). */\n warmup?: boolean;\n /** Browsers: play the audio as it arrives (Web Audio). */\n play?: boolean | { audioContext?: AudioContext };\n}\n\nexport interface Voice {\n /** What to pass as `voice`: \"alba\", \"german/juergen\", \"clone:my-voice\", … */\n id: string;\n label?: string;\n /** The voice's own language code (en, de, …). */\n lang?: string;\n gender?: string;\n [k: string]: unknown;\n}\n\n/** The Moses TTS API client. */\nexport class MosesTTS {\n readonly baseUrl: string;\n constructor(private opts: ClientOptions) {\n this.baseUrl = trimBase(opts.baseUrl);\n }\n\n private async get<T>(path: string): Promise<T> {\n const f = this.opts.fetch ?? fetch;\n const r = await f(`${this.baseUrl}/tts${path}`, { headers: { Authorization: `Bearer ${await resolveKey(this.opts.apiKey)}` } });\n if (!r.ok) throw await apiError(r);\n return r.json() as Promise<T>;\n }\n\n /** The voices you can use (built-in, plus your own cloned voices as \"clone:<name>\"). */\n async voices(): Promise<Voice[]> {\n const body = await this.get<{ voices?: Voice[] } | Voice[]>(\"/v1/voices\");\n return Array.isArray(body) ? body : (body.voices ?? []);\n }\n\n /** Languages with their default voice and all voice ids. */\n languages(): Promise<{ default_voice: string; languages: { id: string; code: string; default_voice: string; voices: string[] }[] }> {\n return this.get(\"/v1/languages\");\n }\n\n /** Your limits, what's open now and your credit. */\n stats(): Promise<Record<string, unknown>> {\n return this.get(\"/v1/stats\");\n }\n\n /** The raw streaming response of POST /tts/v1/audio/speech (audio arrives while it's generated). */\n async speechResponse(o: SpeechOptions): Promise<Response> {\n const { input, format, signal, ...rest } = o;\n if (!input?.trim()) throw new MosesAPIError(\"input is empty\", 400, \"bad_input\");\n const f = this.opts.fetch ?? fetch;\n const r = await f(`${this.baseUrl}/tts/v1/audio/speech`, {\n method: \"POST\",\n signal,\n headers: { Authorization: `Bearer ${await resolveKey(this.opts.apiKey)}`, \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ input, response_format: format ?? \"wav\", ...rest }),\n });\n if (!r.ok) throw await apiError(r);\n return r;\n }\n\n /** Whole text in, audio out: the complete WAV (or PCM) file. */\n async speech(o: SpeechOptions): Promise<ArrayBuffer> {\n return (await this.speechResponse(o)).arrayBuffer();\n }\n\n /** Whole text in, audio out as a stream of bytes, while it's generated (pipe it to a file or a player). */\n async speechStream(o: SpeechOptions): Promise<ReadableStream<Uint8Array>> {\n const r = await this.speechResponse(o);\n if (!r.body) throw new MosesAPIError(\"The response has no body\", 500);\n return r.body;\n }\n\n /** A realtime session: send text as it's written (e.g. an LLM's tokens), get audio while the next sentence is\n * still being generated. Resolves once the session is ready. */\n async realtime(o: RealtimeOptions = {}): Promise<RealtimeTTS> {\n const W = webSocketClass(this.opts);\n const key = await resolveKey(this.opts.apiKey);\n const ws = new W(`${wsBase(this.baseUrl)}/tts/realtime`, [\"pocket-tts\", `bearer.${key}`]);\n const s = new RealtimeTTS(ws, o);\n await s.ready;\n return s;\n }\n}\n\nexport interface Segment {\n index: number;\n /** The text as written (for captions). */\n text: string;\n end: string;\n ops?: unknown[];\n warnings?: string[];\n}\n\nexport interface RealtimeEvents extends Record<string, unknown> {\n ready: Record<string, unknown>;\n /** A segment (sentence or clause) starts; its audio follows. */\n segment: Segment;\n /** PCM s16le, mono, 24 kHz. */\n audio: ArrayBuffer;\n segment_end: { index: number; audio_ms: number; first_audio_ms: number };\n /** Everything after end() was sent. */\n done: void;\n cancelled: void;\n config: Record<string, unknown>;\n warmed: Record<string, unknown>;\n /** An error message from the server (the session stays open unless \"close\" follows). */\n error: MosesAPIError;\n close: { code: number; reason: string; error?: MosesAPIError };\n /** Browsers with play: true — the player went quiet. */\n idle: void;\n}\n\n/** One realtime TTS connection; it can speak many answers one after another. */\nexport class RealtimeTTS extends Emitter<RealtimeEvents> {\n readonly ready: Promise<Record<string, unknown>>;\n readonly player?: PcmPlayer;\n private lastError?: MosesAPIError;\n private closed = false;\n\n constructor(\n private ws: WebSocket,\n o: RealtimeOptions,\n ) {\n super();\n ws.binaryType = \"arraybuffer\";\n if (o.play) {\n if (typeof AudioContext === \"undefined\") throw new Error(\"play: true needs a browser (Web Audio).\");\n this.player = new PcmPlayer({ sampleRate: 24000, audioContext: typeof o.play === \"object\" ? o.play.audioContext : undefined });\n this.player.onIdle = () => this.emit(\"idle\", undefined);\n }\n this.ready = new Promise((ok, bad) => {\n ws.onmessage = (m: MessageEvent) => {\n if (typeof m.data !== \"string\") {\n const buf = m.data as ArrayBuffer;\n this.player?.push(buf);\n this.emit(\"audio\", buf);\n return;\n }\n const ev = JSON.parse(m.data);\n switch (ev.type) {\n case \"ready\":\n this.configure(o);\n if (o.warmup !== false) this.raw({ type: \"warmup\" });\n ok(ev);\n this.emit(\"ready\", ev);\n break;\n case \"error\": {\n const err = new MosesAPIError(ev.message ?? \"error\", 400, ev.code);\n this.lastError = err;\n this.emit(\"error\", err);\n break;\n }\n case \"done\":\n case \"cancelled\":\n this.emit(ev.type, undefined);\n break;\n default:\n this.emit(ev.type, ev);\n }\n };\n let opened = false;\n ws.onopen = () => (opened = true);\n // a refused handshake (wrong key, scope, website): browsers fire close (1006), Node only error\n ws.onerror = () => {\n if (opened || this.closed) return;\n this.closed = true;\n const err = new MosesAPIError(\"The connection was refused: check the API key, its scope and allowed websites.\", 403, \"refused\");\n bad(err);\n this.emit(\"close\", { code: 1006, reason: \"\", error: err });\n };\n ws.onclose = (e: CloseEvent) => {\n if (this.closed && !opened) return;\n this.closed = true;\n const why = e.code === 1000 ? undefined : this.lastError ? new MosesAPIError(this.lastError.message, e.code, this.lastError.code) : new MosesAPIError(closeReason(e.code, e.reason).message, e.code, closeReason(e.code, e.reason).code);\n bad(why ?? new MosesAPIError(\"closed before ready\", e.code));\n this.emit(\"close\", { code: e.code, reason: e.reason, ...(why ? { error: why } : {}) });\n };\n });\n this.ready.catch(() => undefined);\n }\n\n private raw(msg: object) {\n if (this.ws.readyState === 1) this.ws.send(JSON.stringify(msg));\n else if (this.closed) throw new MosesAPIError(\"The realtime session is closed.\", 0, \"closed\");\n }\n\n /** Change voice, language or text settings for the following segments. */\n configure(o: Omit<RealtimeOptions, \"warmup\" | \"play\">) {\n const { firstChunkChars, ...rest } = o as RealtimeOptions;\n delete (rest as RealtimeOptions).warmup;\n delete (rest as RealtimeOptions).play;\n const msg: Record<string, unknown> = { type: \"config\", ...rest };\n if (firstChunkChars !== undefined) msg.first_chunk_chars = firstChunkChars;\n if (Object.keys(msg).length > 1) this.raw(msg);\n }\n\n /** Append text (e.g. one LLM token); complete sentences are spoken at once. */\n send(text: string) {\n if (text) this.raw({ type: \"text\", text });\n }\n /** Speak what's buffered now, even mid-sentence (e.g. while the LLM calls a tool). */\n flush() {\n this.raw({ type: \"flush\" });\n }\n /** End of the answer: the rest is spoken; resolves when all its audio was sent. */\n end(): Promise<void> {\n const done = this.once(\"done\");\n this.raw({ type: \"end\" });\n return done;\n }\n /** Barge-in: stop at once, drop queued text and audio (and the player's). */\n cancel() {\n this.player?.stop();\n this.raw({ type: \"cancel\" });\n }\n /** Speak a whole text or an async stream of text (e.g. an LLM stream); resolves when its audio was sent. */\n async speak(text: string | AsyncIterable<string>): Promise<void> {\n if (typeof text === \"string\") this.send(text);\n else for await (const t of text) this.send(t);\n await this.end();\n }\n /** Give the reserved warm worker back (sessions that will be quiet for a while). */\n release() {\n this.raw({ type: \"release\" });\n }\n close() {\n this.closed = true;\n try {\n this.raw({ type: \"release\" });\n } catch {\n /* closing anyway */\n }\n this.ws.close(1000);\n void this.player?.close();\n }\n}\n\nexport default MosesTTS;\n"],"names":["DEFAULT_BASE_URL","MosesAPIError","message","status","code","retryAfter","resolveKey","k","key","trimBase","u","wsBase","_m","s","apiError","r","body","d","retry","webSocketClass","opts","W","Emitter","event","fn","set","ok","data","e","closeReason","reason","known","c","m","PcmPlayer","o","chunk","pcm","buf","ch","i","src","at","pcmToWav","chunks","sampleRate","list","size","n","out","v","ascii","VERSION","SAMPLE_RATE","MosesTTS","path","input","format","signal","rest","ws","RealtimeTTS","bad","ev","err","opened","why","msg","firstChunkChars","text","done"],"mappings":"AAEO,MAAMA,IAAmB;AAGzB,MAAMC,UAAsB,MAAM;AAAA,EACvC,YACEC,GACSC,GACAC,GACAC,GACT;AACA,UAAMH,CAAO,GAJJ,KAAA,SAAAC,GACA,KAAA,OAAAC,GACA,KAAA,aAAAC,GAGT,KAAK,OAAO;AAAA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UAAM,KAAK,IAAA;AAAA,EACb;AAAA;AAAA,EAEA,UAAU;AACR,SAAK,IAAI,EAAE,MAAM,UAAA,CAAW;AAAA,EAC9B;AAAA,EACA,QAAQ;AACN,SAAK,SAAS;AACd,QAAI;AACF,WAAK,IAAI,EAAE,MAAM,UAAA,CAAW;AAAA,IAC9B,QAAQ;AAAA,IAER;AACA,SAAK,GAAG,MAAM,GAAI,GACb,KAAK,QAAQ,MAAA;AAAA,EACpB;AACF;"}
|
package/dist/player.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** Playing PCM s16le mono audio in the browser as it arrives (Web Audio), and wrapping PCM as a WAV file. */
|
|
2
|
+
export declare class PcmPlayer {
|
|
3
|
+
readonly context: AudioContext;
|
|
4
|
+
private own;
|
|
5
|
+
private next;
|
|
6
|
+
private sources;
|
|
7
|
+
private sampleRate;
|
|
8
|
+
/** Called when everything queued has played. */
|
|
9
|
+
onIdle?: () => void;
|
|
10
|
+
constructor(o?: {
|
|
11
|
+
sampleRate?: number;
|
|
12
|
+
audioContext?: AudioContext;
|
|
13
|
+
});
|
|
14
|
+
get playing(): boolean;
|
|
15
|
+
/** Queue a chunk of PCM s16le; it plays right after the previous one. */
|
|
16
|
+
push(chunk: ArrayBuffer): void;
|
|
17
|
+
/** Stop at once and drop what's queued (barge-in). */
|
|
18
|
+
stop(): void;
|
|
19
|
+
close(): Promise<void>;
|
|
20
|
+
}
|
|
21
|
+
/** Wraps raw PCM s16le mono as a WAV file (e.g. the chunks of a realtime session, joined). */
|
|
22
|
+
export declare function pcmToWav(chunks: ArrayBuffer | ArrayBuffer[], sampleRate?: number): ArrayBuffer;
|
package/dist/shared.d.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/** Small pieces both the HTTP and the realtime parts use: the error type, auth, addresses, a typed emitter. */
|
|
2
|
+
export declare const DEFAULT_BASE_URL = "https://moses-ai.com";
|
|
3
|
+
/** An error the Moses API answered with (HTTP status, or a WebSocket close code), with its machine-readable code. */
|
|
4
|
+
export declare class MosesAPIError extends Error {
|
|
5
|
+
readonly status: number;
|
|
6
|
+
readonly code?: string | undefined;
|
|
7
|
+
readonly retryAfter?: number | undefined;
|
|
8
|
+
constructor(message: string, status: number, code?: string | undefined, retryAfter?: number | undefined);
|
|
9
|
+
}
|
|
10
|
+
export interface ClientOptions {
|
|
11
|
+
/** Your API key (`mk_…`, from moses-ai.com/console). Keep it on your server; in a browser use a key limited to
|
|
12
|
+
* your website (API console → the key → allowed websites), or a function that fetches one. */
|
|
13
|
+
apiKey: string | (() => string | Promise<string>);
|
|
14
|
+
/** Default https://moses-ai.com (or your own Moses server). */
|
|
15
|
+
baseUrl?: string;
|
|
16
|
+
/** A WebSocket implementation for runtimes without a global one (e.g. `ws` on Node 18–20). */
|
|
17
|
+
WebSocket?: typeof WebSocket;
|
|
18
|
+
/** A fetch implementation (default: the global fetch). */
|
|
19
|
+
fetch?: typeof fetch;
|
|
20
|
+
}
|
|
21
|
+
export declare function resolveKey(k: ClientOptions["apiKey"]): Promise<string>;
|
|
22
|
+
export declare const trimBase: (u?: string) => string;
|
|
23
|
+
export declare const wsBase: (u: string) => string;
|
|
24
|
+
export declare function apiError(r: Response): Promise<MosesAPIError>;
|
|
25
|
+
export declare function webSocketClass(opts: ClientOptions): typeof WebSocket;
|
|
26
|
+
/** A minimal typed event emitter (works the same in browsers and Node). */
|
|
27
|
+
export declare class Emitter<E extends Record<string, unknown>> {
|
|
28
|
+
private handlers;
|
|
29
|
+
on<K extends keyof E>(event: K, fn: (data: E[K]) => void): this;
|
|
30
|
+
off<K extends keyof E>(event: K, fn: (data: E[K]) => void): this;
|
|
31
|
+
once<K extends keyof E>(event: K): Promise<E[K]>;
|
|
32
|
+
protected emit<K extends keyof E>(event: K, data: E[K]): void;
|
|
33
|
+
}
|
|
34
|
+
/** Close codes of the speech gateway, in words. */
|
|
35
|
+
export declare function closeReason(code: number, reason: string): {
|
|
36
|
+
code: string;
|
|
37
|
+
message: string;
|
|
38
|
+
};
|
package/llms.txt
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# @mosesai/tts
|
|
2
|
+
|
|
3
|
+
> JavaScript/TypeScript client (Node.js 18+ and browsers, no dependencies) for the Moses TTS API: streaming text to speech over WebSocket (send an LLM's tokens as they arrive, receive PCM audio while the next sentence is generated) and whole-text speech to WAV/PCM over an OpenAI-style HTTP endpoint. 7 languages (en, de, fr, it, pt, es, nl), voice cloning ("clone:<name>"), hosted in Germany, nothing stored.
|
|
4
|
+
|
|
5
|
+
Install: `npm install @mosesai/tts`. Key: `mk_…` with the TTS permission from https://moses-ai.com/console.
|
|
6
|
+
|
|
7
|
+
## Usage
|
|
8
|
+
|
|
9
|
+
- Whole text to WAV: `const wav = await new MosesTTS({ apiKey }).speech({ input: "Hello", voice: "alba" })` → ArrayBuffer.
|
|
10
|
+
- Stream: `const live = await tts.realtime({ voice: "alba" }); live.on("audio", pcm => …); for await (const t of llm) live.send(t); await live.end();`
|
|
11
|
+
- Browser playback: `tts.realtime({ play: true })`; barge-in: `live.cancel()`.
|
|
12
|
+
- Audio: PCM s16le, mono, 24 kHz (realtime); WAV or PCM (speech). `pcmToWav(chunks)` joins realtime audio.
|
|
13
|
+
- Node 18–20: pass `{ WebSocket }` from the `ws` package. Errors: `MosesAPIError` (`status`, `code`, `retryAfter`).
|
|
14
|
+
|
|
15
|
+
## Endpoints
|
|
16
|
+
|
|
17
|
+
- `wss://moses-ai.com/tts/realtime` (subprotocols `["pocket-tts", "bearer.<key>"]`): messages `config`, `text`, `flush`, `end`, `cancel`, `warmup`, `release`; events `ready`, `segment`, binary audio, `segment_end`, `done`, `cancelled`, `error`.
|
|
18
|
+
- `POST https://moses-ai.com/tts/v1/audio/speech` `{input, voice, language, response_format: "wav"|"pcm"}`.
|
|
19
|
+
- `GET https://moses-ai.com/tts/v1/voices`, `/tts/v1/languages`, `/tts/v1/stats`.
|
|
20
|
+
|
|
21
|
+
## Links
|
|
22
|
+
|
|
23
|
+
- [README](https://www.npmjs.com/package/@mosesai/tts): full API, options, FAQ
|
|
24
|
+
- [JavaScript example](https://moses-ai.com/tts_stt/example_js.html): try TTS and STT in the browser with your key, and copy working code for realtime and batch use
|
|
25
|
+
- [Pricing](https://moses-ai.com/tts/pricing): prepaid, per character
|
|
26
|
+
- [@mosesai/stt](https://www.npmjs.com/package/@mosesai/stt): speech to text
|
|
27
|
+
- [@mosesai/voice](https://www.npmjs.com/package/@mosesai/voice): a talking AI agent in your web app
|
package/package.json
CHANGED
|
@@ -1,6 +1,64 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mosesai/tts",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Text to speech for JavaScript and TypeScript (Node.js and browsers) with the Moses TTS API: stream an LLM's tokens in and get natural speech back in real time over WebSocket, or turn whole texts into WAV with an OpenAI-style endpoint. 7 languages, voice cloning, EU-hosted, no dependencies.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"text-to-speech",
|
|
7
|
+
"tts",
|
|
8
|
+
"speech-synthesis",
|
|
9
|
+
"streaming-tts",
|
|
10
|
+
"realtime-tts",
|
|
11
|
+
"websocket",
|
|
12
|
+
"llm",
|
|
13
|
+
"voice-agent",
|
|
14
|
+
"ai-voice",
|
|
15
|
+
"voice-cloning",
|
|
16
|
+
"openai-compatible",
|
|
17
|
+
"pcm",
|
|
18
|
+
"wav",
|
|
19
|
+
"web-audio",
|
|
20
|
+
"german",
|
|
21
|
+
"multilingual",
|
|
22
|
+
"eu",
|
|
23
|
+
"gdpr",
|
|
24
|
+
"typescript",
|
|
25
|
+
"moses"
|
|
26
|
+
],
|
|
27
|
+
"homepage": "https://moses-ai.com/tts/",
|
|
28
|
+
"bugs": {
|
|
29
|
+
"email": "info@moses-ai.com"
|
|
30
|
+
},
|
|
31
|
+
"license": "MIT",
|
|
32
|
+
"author": "Moses AI <info@moses-ai.com>",
|
|
33
|
+
"type": "module",
|
|
34
|
+
"engines": {
|
|
35
|
+
"node": ">=18"
|
|
36
|
+
},
|
|
37
|
+
"main": "./dist/moses-tts.js",
|
|
38
|
+
"module": "./dist/moses-tts.js",
|
|
39
|
+
"types": "./dist/index.d.ts",
|
|
40
|
+
"exports": {
|
|
41
|
+
".": {
|
|
42
|
+
"types": "./dist/index.d.ts",
|
|
43
|
+
"import": "./dist/moses-tts.js"
|
|
44
|
+
},
|
|
45
|
+
"./iife": "./dist/moses-tts.iife.js"
|
|
46
|
+
},
|
|
47
|
+
"files": [
|
|
48
|
+
"dist",
|
|
49
|
+
"README.md",
|
|
50
|
+
"LICENSE",
|
|
51
|
+
"llms.txt"
|
|
52
|
+
],
|
|
53
|
+
"sideEffects": false,
|
|
54
|
+
"scripts": {
|
|
55
|
+
"build": "vite build && tsc -p tsconfig.json --emitDeclarationOnly --noEmit false --outDir dist",
|
|
56
|
+
"typecheck": "tsc -p tsconfig.json",
|
|
57
|
+
"prepublishOnly": "npm run build",
|
|
58
|
+
"test": "npm run build && node --test test/*.test.mjs"
|
|
59
|
+
},
|
|
60
|
+
"devDependencies": {
|
|
61
|
+
"typescript": "^5.9.3",
|
|
62
|
+
"vite": "^7.2.4"
|
|
63
|
+
}
|
|
64
|
+
}
|