@cartesia/cartesia-js 0.0.3 → 1.0.0-alpha.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.
Files changed (103) hide show
  1. package/.turbo/turbo-build.log +68 -38
  2. package/CHANGELOG.md +12 -0
  3. package/README.md +123 -16
  4. package/dist/chunk-3FL2SNIR.js +17 -0
  5. package/dist/chunk-3GBZUGUD.js +17 -0
  6. package/dist/chunk-4RMSIQLG.js +25 -0
  7. package/dist/chunk-BCQ63627.js +32 -0
  8. package/dist/chunk-JOHSCOLW.js +106 -0
  9. package/dist/chunk-LYPTISWL.js +75 -0
  10. package/dist/chunk-NDNN326Q.js +207 -0
  11. package/dist/chunk-WBK6LLXX.js +58 -0
  12. package/dist/chunk-WE63M7PJ.js +119 -0
  13. package/dist/{chunk-HNLIBHEN.mjs → chunk-WIFMLPT5.js} +31 -16
  14. package/dist/chunk-X7SJMF2R.js +22 -0
  15. package/dist/index.cjs +652 -0
  16. package/dist/index.d.cts +10 -0
  17. package/dist/index.d.ts +10 -0
  18. package/dist/index.js +20 -0
  19. package/dist/lib/client.cjs +89 -0
  20. package/dist/lib/client.d.cts +11 -0
  21. package/dist/lib/client.d.ts +2 -0
  22. package/dist/lib/client.js +7 -42
  23. package/dist/lib/constants.cjs +42 -0
  24. package/dist/lib/constants.d.cts +4 -0
  25. package/dist/lib/constants.d.ts +2 -3
  26. package/dist/lib/constants.js +8 -37
  27. package/dist/lib/index.cjs +531 -0
  28. package/dist/lib/index.d.cts +16 -0
  29. package/dist/lib/index.d.ts +6 -2
  30. package/dist/lib/index.js +13 -409
  31. package/dist/react/index.cjs +846 -0
  32. package/dist/react/index.d.cts +33 -0
  33. package/dist/react/index.d.ts +20 -13
  34. package/dist/react/index.js +161 -501
  35. package/dist/react/utils.cjs +57 -0
  36. package/dist/react/utils.d.cts +7 -0
  37. package/dist/react/utils.d.ts +7 -0
  38. package/dist/react/utils.js +7 -0
  39. package/dist/tts/index.cjs +470 -0
  40. package/dist/tts/index.d.cts +17 -0
  41. package/dist/tts/index.d.ts +17 -0
  42. package/dist/tts/index.js +12 -0
  43. package/dist/tts/player.cjs +198 -0
  44. package/dist/tts/player.d.cts +43 -0
  45. package/dist/tts/player.d.ts +43 -0
  46. package/dist/tts/player.js +8 -0
  47. package/dist/tts/source.cjs +167 -0
  48. package/dist/tts/source.d.cts +53 -0
  49. package/dist/tts/source.d.ts +53 -0
  50. package/dist/tts/source.js +7 -0
  51. package/dist/{audio/utils.js → tts/utils.cjs} +13 -54
  52. package/dist/tts/utils.d.cts +67 -0
  53. package/dist/tts/utils.d.ts +67 -0
  54. package/dist/{audio/utils.mjs → tts/utils.js} +2 -6
  55. package/dist/tts/websocket.cjs +453 -0
  56. package/dist/tts/websocket.d.cts +53 -0
  57. package/dist/tts/websocket.d.ts +53 -0
  58. package/dist/tts/websocket.js +11 -0
  59. package/dist/types/index.cjs +18 -0
  60. package/dist/types/index.d.cts +55 -0
  61. package/dist/types/index.d.ts +50 -1
  62. package/dist/types/index.js +1 -18
  63. package/dist/voices/index.cjs +155 -0
  64. package/dist/voices/index.d.cts +12 -0
  65. package/dist/voices/index.d.ts +12 -0
  66. package/dist/voices/index.js +9 -0
  67. package/package.json +11 -7
  68. package/src/index.ts +4 -0
  69. package/src/lib/client.ts +14 -1
  70. package/src/lib/constants.ts +13 -3
  71. package/src/lib/index.ts +6 -3
  72. package/src/react/index.ts +167 -75
  73. package/src/react/utils.ts +11 -0
  74. package/src/tts/index.ts +17 -0
  75. package/src/tts/player.ts +109 -0
  76. package/src/tts/source.ts +98 -0
  77. package/src/{audio → tts}/utils.ts +19 -97
  78. package/src/tts/websocket.ts +210 -0
  79. package/src/types/index.ts +63 -0
  80. package/src/voices/index.ts +47 -0
  81. package/dist/audio/index.d.mts +0 -5
  82. package/dist/audio/index.d.ts +0 -5
  83. package/dist/audio/index.js +0 -396
  84. package/dist/audio/index.mjs +0 -9
  85. package/dist/audio/utils.d.mts +0 -5
  86. package/dist/audio/utils.d.ts +0 -5
  87. package/dist/chunk-3CYTAFLF.mjs +0 -262
  88. package/dist/chunk-FRIBQZPN.mjs +0 -113
  89. package/dist/chunk-XSFPHPPG.mjs +0 -18
  90. package/dist/index-DSBmfK9-.d.mts +0 -158
  91. package/dist/index-qwAyxV5I.d.ts +0 -158
  92. package/dist/lib/client.d.mts +0 -9
  93. package/dist/lib/client.mjs +0 -7
  94. package/dist/lib/constants.d.mts +0 -5
  95. package/dist/lib/constants.mjs +0 -10
  96. package/dist/lib/index.d.mts +0 -12
  97. package/dist/lib/index.mjs +0 -19
  98. package/dist/react/index.d.mts +0 -26
  99. package/dist/react/index.mjs +0 -130
  100. package/dist/types/index.d.mts +0 -6
  101. package/index.ts +0 -3
  102. package/src/audio/index.ts +0 -282
  103. /package/dist/{types/index.mjs → chunk-FXPGR372.js} +0 -0
@@ -0,0 +1,207 @@
1
+ import {
2
+ Source
3
+ } from "./chunk-JOHSCOLW.js";
4
+ import {
5
+ Client
6
+ } from "./chunk-BCQ63627.js";
7
+ import {
8
+ constructApiUrl
9
+ } from "./chunk-3GBZUGUD.js";
10
+ import {
11
+ base64ToArray,
12
+ createMessageHandlerForContextId,
13
+ getEmitteryCallbacks,
14
+ isSentinel
15
+ } from "./chunk-LYPTISWL.js";
16
+ import {
17
+ __async,
18
+ __privateAdd,
19
+ __privateGet,
20
+ __privateMethod,
21
+ __privateSet,
22
+ __spreadProps,
23
+ __spreadValues
24
+ } from "./chunk-WIFMLPT5.js";
25
+
26
+ // src/tts/websocket.ts
27
+ import Emittery from "emittery";
28
+ import { humanId } from "human-id";
29
+ import { WebSocket as PartySocketWebSocket } from "partysocket";
30
+ var _isConnected, _sampleRate, _generateId, generateId_fn;
31
+ var WebSocket = class extends Client {
32
+ /**
33
+ * Create a new WebSocket client.
34
+ *
35
+ * @param args - Arguments to pass to the Client constructor.
36
+ */
37
+ constructor({ sampleRate }, ...args) {
38
+ super(...args);
39
+ /**
40
+ * Generate a unique ID suitable for a streaming context.
41
+ *
42
+ * Not suitable for security purposes or as a primary key, since
43
+ * it lacks the amount of entropy required for those use cases.
44
+ *
45
+ * @returns A unique ID.
46
+ */
47
+ __privateAdd(this, _generateId);
48
+ __privateAdd(this, _isConnected, false);
49
+ __privateAdd(this, _sampleRate, void 0);
50
+ __privateSet(this, _sampleRate, sampleRate);
51
+ }
52
+ /**
53
+ * Send a message over the WebSocket in order to start a stream.
54
+ *
55
+ * @param inputs - Stream options.
56
+ * @param options - Options for the stream.
57
+ * @param options.timeout - The maximum time to wait for a chunk before cancelling the stream.
58
+ * If `0`, the stream will not time out.
59
+ * @returns A Source object that can be passed to a Player to play the audio.
60
+ */
61
+ send(inputs, { timeout = 0 } = {}) {
62
+ var _a, _b, _c, _d;
63
+ if (!__privateGet(this, _isConnected)) {
64
+ throw new Error("Not connected to WebSocket. Call .connect() first.");
65
+ }
66
+ const contextId = __privateMethod(this, _generateId, generateId_fn).call(this);
67
+ (_a = this.socket) == null ? void 0 : _a.send(
68
+ JSON.stringify(__spreadProps(__spreadValues({
69
+ context_id: contextId
70
+ }, inputs), {
71
+ output_format: {
72
+ container: "raw",
73
+ encoding: "pcm_f32le",
74
+ sample_rate: __privateGet(this, _sampleRate)
75
+ }
76
+ }))
77
+ );
78
+ const emitter = new Emittery();
79
+ const source = new Source({
80
+ sampleRate: __privateGet(this, _sampleRate)
81
+ });
82
+ const streamCompleteController = new AbortController();
83
+ let timeoutId = null;
84
+ if (timeout > 0) {
85
+ timeoutId = setTimeout(streamCompleteController.abort, timeout);
86
+ }
87
+ const handleMessage = createMessageHandlerForContextId(
88
+ contextId,
89
+ (_0) => __async(this, [_0], function* ({ chunk, message }) {
90
+ emitter.emit("message", message);
91
+ if (isSentinel(chunk)) {
92
+ yield source.close();
93
+ streamCompleteController.abort();
94
+ return;
95
+ }
96
+ yield source.enqueue(base64ToArray([chunk]));
97
+ if (timeoutId) {
98
+ clearTimeout(timeoutId);
99
+ timeoutId = setTimeout(streamCompleteController.abort, timeout);
100
+ }
101
+ })
102
+ );
103
+ (_b = this.socket) == null ? void 0 : _b.addEventListener("message", handleMessage, {
104
+ signal: streamCompleteController.signal
105
+ });
106
+ (_c = this.socket) == null ? void 0 : _c.addEventListener(
107
+ "close",
108
+ () => {
109
+ streamCompleteController.abort();
110
+ },
111
+ {
112
+ once: true
113
+ }
114
+ );
115
+ (_d = this.socket) == null ? void 0 : _d.addEventListener(
116
+ "error",
117
+ () => {
118
+ streamCompleteController.abort();
119
+ },
120
+ {
121
+ once: true
122
+ }
123
+ );
124
+ streamCompleteController.signal.addEventListener("abort", () => {
125
+ source.close();
126
+ if (timeoutId) {
127
+ clearTimeout(timeoutId);
128
+ }
129
+ });
130
+ return __spreadValues({ source }, getEmitteryCallbacks(emitter));
131
+ }
132
+ /**
133
+ * Authenticate and connect to a Cartesia streaming WebSocket.
134
+ *
135
+ * @returns A promise that resolves when the WebSocket is connected.
136
+ * @throws {Error} If the WebSocket fails to connect.
137
+ */
138
+ connect() {
139
+ const url = constructApiUrl(this.baseUrl, "/tts/websocket", "ws");
140
+ url.searchParams.set("api_key", this.apiKey);
141
+ const emitter = new Emittery();
142
+ this.socket = new PartySocketWebSocket(url.toString());
143
+ this.socket.onopen = () => {
144
+ __privateSet(this, _isConnected, true);
145
+ emitter.emit("open");
146
+ };
147
+ this.socket.onclose = () => {
148
+ __privateSet(this, _isConnected, false);
149
+ emitter.emit("close");
150
+ };
151
+ return new Promise(
152
+ (resolve, reject) => {
153
+ var _a, _b, _c;
154
+ (_a = this.socket) == null ? void 0 : _a.addEventListener(
155
+ "open",
156
+ () => {
157
+ resolve(getEmitteryCallbacks(emitter));
158
+ },
159
+ {
160
+ once: true
161
+ }
162
+ );
163
+ const aborter = new AbortController();
164
+ (_b = this.socket) == null ? void 0 : _b.addEventListener(
165
+ "error",
166
+ () => {
167
+ aborter.abort();
168
+ reject(new Error("WebSocket failed to connect."));
169
+ },
170
+ {
171
+ signal: aborter.signal
172
+ }
173
+ );
174
+ (_c = this.socket) == null ? void 0 : _c.addEventListener(
175
+ "close",
176
+ () => {
177
+ aborter.abort();
178
+ reject(new Error("WebSocket closed before it could connect."));
179
+ },
180
+ {
181
+ signal: aborter.signal
182
+ }
183
+ );
184
+ }
185
+ );
186
+ }
187
+ /**
188
+ * Disconnect from the Cartesia streaming WebSocket.
189
+ */
190
+ disconnect() {
191
+ var _a;
192
+ (_a = this.socket) == null ? void 0 : _a.close();
193
+ }
194
+ };
195
+ _isConnected = new WeakMap();
196
+ _sampleRate = new WeakMap();
197
+ _generateId = new WeakSet();
198
+ generateId_fn = function() {
199
+ return humanId({
200
+ separator: "-",
201
+ capitalize: false
202
+ });
203
+ };
204
+
205
+ export {
206
+ WebSocket
207
+ };
@@ -0,0 +1,58 @@
1
+ import {
2
+ Client
3
+ } from "./chunk-BCQ63627.js";
4
+ import {
5
+ __async
6
+ } from "./chunk-WIFMLPT5.js";
7
+
8
+ // src/voices/index.ts
9
+ var Voices = class extends Client {
10
+ list() {
11
+ return __async(this, null, function* () {
12
+ const response = yield this.fetch("/voices");
13
+ return response.json();
14
+ });
15
+ }
16
+ get(voiceId) {
17
+ return __async(this, null, function* () {
18
+ const response = yield this.fetch(`/voices/${voiceId}`);
19
+ return response.json();
20
+ });
21
+ }
22
+ create(voice) {
23
+ return __async(this, null, function* () {
24
+ const response = yield this.fetch("/voices", {
25
+ method: "POST",
26
+ body: JSON.stringify(voice)
27
+ });
28
+ return response.json();
29
+ });
30
+ }
31
+ clone(options) {
32
+ return __async(this, null, function* () {
33
+ if (options.mode === "url") {
34
+ const response = yield this.fetch(
35
+ `/voices/clone/url?link=${options.link}`,
36
+ {
37
+ method: "POST"
38
+ }
39
+ );
40
+ return response.json();
41
+ }
42
+ if (options.mode === "clip") {
43
+ const formData = new FormData();
44
+ formData.append("clip", options.clip);
45
+ const response = yield this.fetch("/voices/clone/clip", {
46
+ method: "POST",
47
+ body: formData
48
+ });
49
+ return response.json();
50
+ }
51
+ throw new Error("Invalid mode for clone()");
52
+ });
53
+ }
54
+ };
55
+
56
+ export {
57
+ Voices
58
+ };
@@ -0,0 +1,119 @@
1
+ import {
2
+ playAudioBuffer
3
+ } from "./chunk-LYPTISWL.js";
4
+ import {
5
+ __async,
6
+ __privateAdd,
7
+ __privateGet,
8
+ __privateMethod,
9
+ __privateSet
10
+ } from "./chunk-WIFMLPT5.js";
11
+
12
+ // src/tts/player.ts
13
+ import Emittery from "emittery";
14
+ var _context, _startNextPlaybackAt, _bufferDuration, _emitter, _playBuffer, playBuffer_fn;
15
+ var Player = class {
16
+ /**
17
+ * Create a new Player.
18
+ *
19
+ * @param options - Options for the Player.
20
+ * @param options.bufferDuration - The duration of the audio buffer to play.
21
+ */
22
+ constructor({ bufferDuration }) {
23
+ __privateAdd(this, _playBuffer);
24
+ __privateAdd(this, _context, null);
25
+ __privateAdd(this, _startNextPlaybackAt, 0);
26
+ __privateAdd(this, _bufferDuration, void 0);
27
+ __privateAdd(this, _emitter, new Emittery());
28
+ __privateSet(this, _bufferDuration, bufferDuration);
29
+ }
30
+ /**
31
+ * Play audio from a source.
32
+ *
33
+ * @param source The source to play audio from.
34
+ * @returns A promise that resolves when the audio has finished playing.
35
+ */
36
+ play(source) {
37
+ return __async(this, null, function* () {
38
+ __privateSet(this, _startNextPlaybackAt, 0);
39
+ __privateSet(this, _context, new AudioContext({ sampleRate: source.sampleRate }));
40
+ const buffer = new Float32Array(
41
+ source.durationToSampleCount(__privateGet(this, _bufferDuration))
42
+ );
43
+ const plays = [];
44
+ while (true) {
45
+ const read = yield source.read(buffer);
46
+ const playableAudio = buffer.slice(0, read);
47
+ plays.push(__privateMethod(this, _playBuffer, playBuffer_fn).call(this, playableAudio, source.sampleRate));
48
+ if (read < buffer.length) {
49
+ yield __privateGet(this, _emitter).emit("finish");
50
+ break;
51
+ }
52
+ }
53
+ yield Promise.all(plays);
54
+ });
55
+ }
56
+ /**
57
+ * Pause the audio.
58
+ *
59
+ * @returns A promise that resolves when the audio has been paused.
60
+ */
61
+ pause() {
62
+ return __async(this, null, function* () {
63
+ if (!__privateGet(this, _context)) {
64
+ throw new Error("AudioContext not initialized.");
65
+ }
66
+ yield __privateGet(this, _context).suspend();
67
+ });
68
+ }
69
+ /**
70
+ * Resume the audio.
71
+ *
72
+ * @returns A promise that resolves when the audio has been resumed.
73
+ */
74
+ resume() {
75
+ return __async(this, null, function* () {
76
+ if (!__privateGet(this, _context)) {
77
+ throw new Error("AudioContext not initialized.");
78
+ }
79
+ yield __privateGet(this, _context).resume();
80
+ });
81
+ }
82
+ /**
83
+ * Toggle the audio.
84
+ *
85
+ * @returns A promise that resolves when the audio has been toggled.
86
+ */
87
+ toggle() {
88
+ return __async(this, null, function* () {
89
+ if (!__privateGet(this, _context)) {
90
+ throw new Error("AudioContext not initialized.");
91
+ }
92
+ if (__privateGet(this, _context).state === "running") {
93
+ yield this.pause();
94
+ } else {
95
+ yield this.resume();
96
+ }
97
+ });
98
+ }
99
+ };
100
+ _context = new WeakMap();
101
+ _startNextPlaybackAt = new WeakMap();
102
+ _bufferDuration = new WeakMap();
103
+ _emitter = new WeakMap();
104
+ _playBuffer = new WeakSet();
105
+ playBuffer_fn = function(buf, sampleRate) {
106
+ return __async(this, null, function* () {
107
+ if (!__privateGet(this, _context)) {
108
+ throw new Error("AudioContext not initialized.");
109
+ }
110
+ const startAt = __privateGet(this, _startNextPlaybackAt);
111
+ const duration = buf.length / sampleRate;
112
+ __privateSet(this, _startNextPlaybackAt, duration + Math.max(__privateGet(this, _context).currentTime, __privateGet(this, _startNextPlaybackAt)));
113
+ yield playAudioBuffer(buf, __privateGet(this, _context), startAt, sampleRate);
114
+ });
115
+ };
116
+
117
+ export {
118
+ Player
119
+ };
@@ -1,10 +1,9 @@
1
1
  var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
2
4
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
3
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
4
6
  var __propIsEnum = Object.prototype.propertyIsEnumerable;
5
- var __knownSymbol = (name, symbol) => {
6
- return (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
7
- };
8
7
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
8
  var __spreadValues = (a, b) => {
10
9
  for (var prop in b || (b = {}))
@@ -17,6 +16,29 @@ var __spreadValues = (a, b) => {
17
16
  }
18
17
  return a;
19
18
  };
19
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+ var __accessCheck = (obj, member, msg) => {
21
+ if (!member.has(obj))
22
+ throw TypeError("Cannot " + msg);
23
+ };
24
+ var __privateGet = (obj, member, getter) => {
25
+ __accessCheck(obj, member, "read from private field");
26
+ return getter ? getter.call(obj) : member.get(obj);
27
+ };
28
+ var __privateAdd = (obj, member, value) => {
29
+ if (member.has(obj))
30
+ throw TypeError("Cannot add the same private member more than once");
31
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
32
+ };
33
+ var __privateSet = (obj, member, value, setter) => {
34
+ __accessCheck(obj, member, "write to private field");
35
+ setter ? setter.call(obj, value) : member.set(obj, value);
36
+ return value;
37
+ };
38
+ var __privateMethod = (obj, member, method) => {
39
+ __accessCheck(obj, member, "access private method");
40
+ return method;
41
+ };
20
42
  var __async = (__this, __arguments, generator) => {
21
43
  return new Promise((resolve, reject) => {
22
44
  var fulfilled = (value) => {
@@ -37,20 +59,13 @@ var __async = (__this, __arguments, generator) => {
37
59
  step((generator = generator.apply(__this, __arguments)).next());
38
60
  });
39
61
  };
40
- var __forAwait = (obj, it, method) => (it = obj[__knownSymbol("asyncIterator")]) ? it.call(obj) : (obj = obj[__knownSymbol("iterator")](), it = {}, method = (key, fn) => (fn = obj[key]) && (it[key] = (arg) => new Promise((yes, no, done) => (arg = fn.call(obj, arg), done = arg.done, Promise.resolve(arg.value).then((value) => yes({ value, done }), no)))), method("next"), method("return"), it);
41
-
42
- // src/lib/constants.ts
43
- var BASE_URL = "https://api.cartesia.ai/v0";
44
- var SAMPLE_RATE = 44100;
45
- var constructWebsocketUrl = (baseUrl) => {
46
- return new URL(`${baseUrl.replace(/^http/, "ws")}/audio/websocket`);
47
- };
48
62
 
49
63
  export {
50
64
  __spreadValues,
51
- __async,
52
- __forAwait,
53
- BASE_URL,
54
- SAMPLE_RATE,
55
- constructWebsocketUrl
65
+ __spreadProps,
66
+ __privateGet,
67
+ __privateAdd,
68
+ __privateSet,
69
+ __privateMethod,
70
+ __async
56
71
  };
@@ -0,0 +1,22 @@
1
+ import {
2
+ Voices
3
+ } from "./chunk-WBK6LLXX.js";
4
+ import {
5
+ TTS
6
+ } from "./chunk-4RMSIQLG.js";
7
+ import {
8
+ Client
9
+ } from "./chunk-BCQ63627.js";
10
+
11
+ // src/lib/index.ts
12
+ var Cartesia = class extends Client {
13
+ constructor(options = {}) {
14
+ super(options);
15
+ this.tts = new TTS(options);
16
+ this.voices = new Voices(options);
17
+ }
18
+ };
19
+
20
+ export {
21
+ Cartesia
22
+ };