soma-voice 3.0.0 → 3.0.2

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 (39) hide show
  1. package/dist/esm/api/service/index.d.ts +3 -0
  2. package/dist/esm/api/service/index.js +7 -0
  3. package/dist/esm/api/service/voice/Synthesize.d.ts +6 -0
  4. package/dist/esm/api/service/voice/Synthesize.js +16 -0
  5. package/dist/esm/api/service/voice/Transcribe.d.ts +6 -0
  6. package/dist/esm/api/service/voice/Transcribe.js +16 -0
  7. package/dist/esm/client/browser-voice.d.ts +53 -0
  8. package/dist/esm/client/browser-voice.js +219 -0
  9. package/dist/esm/client/capabilities.d.ts +95 -0
  10. package/dist/esm/client/capabilities.js +151 -0
  11. package/dist/esm/client/errors.d.ts +14 -0
  12. package/dist/esm/client/errors.js +16 -0
  13. package/dist/esm/client/http.d.ts +35 -0
  14. package/dist/esm/client/http.js +164 -0
  15. package/dist/esm/client/index.d.ts +9 -0
  16. package/dist/esm/client/index.js +9 -0
  17. package/dist/esm/client/player.d.ts +66 -0
  18. package/dist/esm/client/player.js +281 -0
  19. package/dist/esm/client/recorder.d.ts +43 -0
  20. package/dist/esm/client/recorder.js +499 -0
  21. package/dist/esm/client/wav.d.ts +7 -0
  22. package/dist/esm/client/wav.js +65 -0
  23. package/dist/esm/index.d.ts +1 -0
  24. package/dist/esm/index.js +1 -0
  25. package/dist/esm/server/concurrency.d.ts +3 -0
  26. package/dist/esm/server/concurrency.js +62 -0
  27. package/dist/esm/server/config.d.ts +32 -0
  28. package/dist/esm/server/config.js +167 -0
  29. package/dist/esm/server/errors.d.ts +21 -0
  30. package/dist/esm/server/errors.js +53 -0
  31. package/dist/esm/server/index.d.ts +5 -0
  32. package/dist/esm/server/index.js +5 -0
  33. package/dist/esm/server/runtime.d.ts +19 -0
  34. package/dist/esm/server/runtime.js +390 -0
  35. package/dist/esm/shared/audio-format.d.ts +16 -0
  36. package/dist/esm/shared/audio-format.js +75 -0
  37. package/dist/esm/shared/transcription.d.ts +26 -0
  38. package/dist/esm/shared/transcription.js +53 -0
  39. package/package.json +20 -17
@@ -0,0 +1,167 @@
1
+ import "server-only";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import yaml from "js-yaml";
5
+ import { VoiceServerError, VoiceErrorCodes } from "./errors.js";
6
+ const MIB = 1024 * 1024;
7
+ const SYNTHESIS_FORMATS = ["wav", "mp3"];
8
+ const RETIRED_KEYS = ["apiKey", "baseUrl", "transcriptionModel", "speechModel"];
9
+ function configError(message) {
10
+ return new VoiceServerError(VoiceErrorCodes.CONFIG, message, 500);
11
+ }
12
+ const TEST_ENVIRONMENTS = /* @__PURE__ */ new Set([
13
+ "test",
14
+ "testing",
15
+ "dev",
16
+ "development",
17
+ "local",
18
+ "qa",
19
+ "staging",
20
+ "pre",
21
+ "prepub",
22
+ "uat"
23
+ ]);
24
+ function readSomaEnv(env = process.env) {
25
+ const value = String(env.SOMA_ENV ?? env.APP_ENV ?? env.NODE_ENV ?? "").trim().toLowerCase();
26
+ if (!value) return "test";
27
+ return TEST_ENVIRONMENTS.has(value) ? "test" : "prod";
28
+ }
29
+ function readPackageSoma(hostDir) {
30
+ try {
31
+ const file = path.join(hostDir, "package.json");
32
+ if (!fs.existsSync(file)) return void 0;
33
+ const packageJson = JSON.parse(fs.readFileSync(file, "utf8"));
34
+ const soma = packageJson?.soma;
35
+ return soma && typeof soma === "object" ? soma : void 0;
36
+ } catch {
37
+ return void 0;
38
+ }
39
+ }
40
+ function resolveSafeChildRoot(parent, relativePath) {
41
+ const trimmed = typeof relativePath === "string" ? relativePath.trim() : "";
42
+ if (!trimmed) return void 0;
43
+ const normalizedParent = path.resolve(parent);
44
+ const resolved = path.resolve(normalizedParent, trimmed);
45
+ return resolved === normalizedParent || resolved.startsWith(`${normalizedParent}${path.sep}`) ? resolved : void 0;
46
+ }
47
+ function resolveHostConfigRoot(hostDir) {
48
+ const normalizedHostDir = path.resolve(hostDir);
49
+ const soma = readPackageSoma(normalizedHostDir);
50
+ if (typeof soma?.configRoot === "string" && soma.configRoot.trim()) {
51
+ return resolveSafeChildRoot(normalizedHostDir, soma.configRoot) ?? path.join(normalizedHostDir, "config");
52
+ }
53
+ const declaredSourceRoot = resolveSafeChildRoot(normalizedHostDir, soma?.hostRoot);
54
+ const hostSourceRoot = declaredSourceRoot && fs.existsSync(declaredSourceRoot) ? declaredSourceRoot : normalizedHostDir;
55
+ const candidates = [
56
+ path.join(normalizedHostDir, "config"),
57
+ path.join(hostSourceRoot, "config")
58
+ ];
59
+ return candidates.find((candidate) => fs.existsSync(candidate)) ?? candidates[1];
60
+ }
61
+ function readServiceUrl(value) {
62
+ if (typeof value !== "string" || !value.trim()) {
63
+ throw configError("Invalid voice config: serviceUrl");
64
+ }
65
+ const raw = value.trim().replace(/\/+$/, "");
66
+ let url;
67
+ try {
68
+ url = new URL(raw);
69
+ } catch {
70
+ throw configError("Invalid voice config: serviceUrl");
71
+ }
72
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash || /[?#]/.test(raw)) {
73
+ throw configError("Invalid voice config: serviceUrl");
74
+ }
75
+ return raw;
76
+ }
77
+ function readServiceToken(value) {
78
+ if (value === void 0 || value === null) return void 0;
79
+ if (typeof value !== "string" || !/^[\x21-\x7e]+$/.test(value.trim())) {
80
+ throw configError("Invalid voice config: serviceToken");
81
+ }
82
+ return value.trim();
83
+ }
84
+ function validateVoiceConfig(value) {
85
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
86
+ throw configError("Voice config is missing.");
87
+ }
88
+ const config = value;
89
+ const retired = RETIRED_KEYS.find((key) => Object.hasOwn(config, key));
90
+ if (retired) {
91
+ throw configError(
92
+ `Voice config key "${retired}" was removed in SOMA 3.0; use serviceUrl and serviceToken.`
93
+ );
94
+ }
95
+ const integer = (key, fallback, min, max) => {
96
+ const candidate = config[key] ?? fallback;
97
+ if (typeof candidate !== "number" || !Number.isInteger(candidate) || candidate < min || candidate > max) {
98
+ throw configError(`Invalid voice config: ${key}`);
99
+ }
100
+ return candidate;
101
+ };
102
+ const list = (key, fallback) => {
103
+ const candidate = config[key] ?? fallback;
104
+ if (!Array.isArray(candidate) || !candidate.length || candidate.some((item) => typeof item !== "string" || !item.trim())) {
105
+ throw configError(`Invalid voice config: ${key}`);
106
+ }
107
+ return [...new Set(candidate.map((item) => item.trim()))];
108
+ };
109
+ const formats = list("formats", [...SYNTHESIS_FORMATS]);
110
+ if (formats.some((format) => !SYNTHESIS_FORMATS.includes(format))) {
111
+ throw configError("Invalid voice config: formats");
112
+ }
113
+ const speedsRaw = config.speeds ?? [0.75, 1, 1.25];
114
+ if (!Array.isArray(speedsRaw) || !speedsRaw.length || speedsRaw.some((speed) => typeof speed !== "number" || !Number.isFinite(speed) || speed < 0.5 || speed > 2)) {
115
+ throw configError("Invalid voice config: speeds");
116
+ }
117
+ const serviceToken = readServiceToken(config.serviceToken);
118
+ return {
119
+ serviceUrl: readServiceUrl(config.serviceUrl),
120
+ ...serviceToken ? { serviceToken } : {},
121
+ timeoutMs: integer("timeoutMs", 12e4, 1e3, 6e5),
122
+ maxConcurrency: integer("maxConcurrency", 2, 1, 100),
123
+ maxQueue: integer("maxQueue", 16, 0, 1e4),
124
+ maxAudioBytes: integer("maxAudioBytes", 25 * MIB, 1, 100 * MIB),
125
+ maxResponseBytes: integer("maxResponseBytes", 25 * MIB, 1, 100 * MIB),
126
+ maxTextCodePoints: integer("maxTextCodePoints", 2e3, 1, 1e5),
127
+ voices: list("voices", ["default"]),
128
+ formats,
129
+ speeds: [...new Set(speedsRaw)]
130
+ };
131
+ }
132
+ const configCache = /* @__PURE__ */ new Map();
133
+ function loadVoiceConfig(hostDir = process.env.SOMA_HOST_DIR || process.cwd(), environment = readSomaEnv()) {
134
+ const normalizedHost = path.resolve(hostDir);
135
+ const root = resolveHostConfigRoot(normalizedHost);
136
+ const candidates = [
137
+ path.join(root, `voice.config.${environment}.yaml`),
138
+ path.join(root, "voice.config.yaml")
139
+ ];
140
+ const file = candidates.find(fs.existsSync);
141
+ if (!file) throw configError("Host voice config is missing.");
142
+ const cacheKey = `${normalizedHost}\0${environment}`;
143
+ try {
144
+ const stat = fs.statSync(file);
145
+ const cached = configCache.get(cacheKey);
146
+ if (cached && cached.file === file && cached.modifiedMs === stat.mtimeMs && cached.size === stat.size) {
147
+ return cached.config;
148
+ }
149
+ const config = validateVoiceConfig(yaml.load(fs.readFileSync(file, "utf8")));
150
+ configCache.set(cacheKey, {
151
+ file,
152
+ modifiedMs: stat.mtimeMs,
153
+ size: stat.size,
154
+ config
155
+ });
156
+ return config;
157
+ } catch (error) {
158
+ if (error instanceof VoiceServerError) throw error;
159
+ throw configError("Voice config cannot be parsed.");
160
+ }
161
+ }
162
+ export {
163
+ loadVoiceConfig,
164
+ readSomaEnv,
165
+ resolveHostConfigRoot,
166
+ validateVoiceConfig
167
+ };
@@ -0,0 +1,21 @@
1
+ import 'server-only';
2
+ export declare const VoiceErrorCodes: {
3
+ readonly CONFIG: 4601;
4
+ readonly INVALID_REQUEST: 4602;
5
+ readonly AUDIO_TOO_LARGE: 4603;
6
+ readonly UNSUPPORTED_AUDIO: 4604;
7
+ readonly TEXT_TOO_LONG: 4605;
8
+ readonly INVALID_OPTION: 4606;
9
+ readonly BUSY: 4607;
10
+ readonly UPSTREAM: 4608;
11
+ readonly TIMEOUT: 4609;
12
+ readonly UNDECODABLE_AUDIO: 4610;
13
+ readonly ENGINE_UNAVAILABLE: 4611;
14
+ };
15
+ export declare class VoiceServerError extends Error {
16
+ readonly code: number;
17
+ readonly status: number;
18
+ constructor(code: number, message: string, status?: number);
19
+ }
20
+ export declare function errorResponse(error: unknown): Response;
21
+ export declare function successResponse<T>(data: T): Response;
@@ -0,0 +1,53 @@
1
+ import "server-only";
2
+ const VoiceErrorCodes = {
3
+ CONFIG: 4601,
4
+ INVALID_REQUEST: 4602,
5
+ AUDIO_TOO_LARGE: 4603,
6
+ UNSUPPORTED_AUDIO: 4604,
7
+ TEXT_TOO_LONG: 4605,
8
+ INVALID_OPTION: 4606,
9
+ BUSY: 4607,
10
+ UPSTREAM: 4608,
11
+ TIMEOUT: 4609,
12
+ UNDECODABLE_AUDIO: 4610,
13
+ ENGINE_UNAVAILABLE: 4611
14
+ };
15
+ class VoiceServerError extends Error {
16
+ constructor(code, message, status = 400) {
17
+ super(message);
18
+ this.code = code;
19
+ this.status = status;
20
+ this.name = "VoiceServerError";
21
+ }
22
+ }
23
+ const BUSY_RETRY_AFTER_SECONDS = "1";
24
+ function errorResponse(error) {
25
+ const voiceError = error instanceof VoiceServerError ? error : new VoiceServerError(VoiceErrorCodes.UPSTREAM, "Voice service failed.", 502);
26
+ return Response.json({
27
+ ret: voiceError.code,
28
+ code: voiceError.code,
29
+ success: false,
30
+ message: voiceError.message,
31
+ msg: voiceError.message,
32
+ data: null
33
+ }, {
34
+ status: voiceError.status,
35
+ ...voiceError.code === VoiceErrorCodes.BUSY ? { headers: { "retry-after": BUSY_RETRY_AFTER_SECONDS } } : {}
36
+ });
37
+ }
38
+ function successResponse(data) {
39
+ return Response.json({
40
+ ret: 0,
41
+ code: 0,
42
+ success: true,
43
+ message: "success",
44
+ msg: "success",
45
+ data
46
+ });
47
+ }
48
+ export {
49
+ VoiceErrorCodes,
50
+ VoiceServerError,
51
+ errorResponse,
52
+ successResponse
53
+ };
@@ -0,0 +1,5 @@
1
+ import 'server-only';
2
+ export * from './concurrency.js';
3
+ export * from './config.js';
4
+ export * from './errors.js';
5
+ export * from './runtime.js';
@@ -0,0 +1,5 @@
1
+ import "server-only";
2
+ export * from "./concurrency.js";
3
+ export * from "./config.js";
4
+ export * from "./errors.js";
5
+ export * from "./runtime.js";
@@ -0,0 +1,19 @@
1
+ import 'server-only';
2
+ import { type AudioContainer } from '../shared/audio-format.js';
3
+ import { type TranscriptionResult } from '../shared/transcription.js';
4
+ import type { VoiceConfig } from './config.js';
5
+ /**
6
+ * 校验上传音频并按文件头魔数判定容器。只读前 {@link AUDIO_SNIFF_BYTES} 字节,
7
+ * 完全不看声明 MIME(各浏览器 MediaRecorder 报出的类型不可信)。
8
+ */
9
+ export declare function validateAudioUpload(file: unknown, maxBytes: number): Promise<AudioContainer>;
10
+ /**
11
+ * `POST /api/voice/transcribe`:multipart 字段 `file`(必填)、`language`、`prompt`、`word_timestamps`。
12
+ * 按魔数判定容器后以规范 MIME 与文件名转发到 `${serviceUrl}/api/transcribe`,返回契约形状的转写结果。
13
+ */
14
+ export declare function transcribe(request: Request, config: VoiceConfig): Promise<TranscriptionResult>;
15
+ /**
16
+ * `POST /api/voice/synthesize`:JSON `{ text, voice?, format?, speed? }`。
17
+ * 转发到 `${serviceUrl}/api/synthesize`,有界读取整段音频后回写给浏览器。
18
+ */
19
+ export declare function synthesize(request: Request, config: VoiceConfig): Promise<Response>;
@@ -0,0 +1,390 @@
1
+ import "server-only";
2
+ import {
3
+ AUDIO_CONTAINER_EXTENSION,
4
+ AUDIO_CONTAINER_MIME,
5
+ AUDIO_SNIFF_BYTES,
6
+ sniffAudioContainer
7
+ } from "../shared/audio-format.js";
8
+ import { parseTranscriptionResult } from "../shared/transcription.js";
9
+ import { acquireVoicePermit } from "./concurrency.js";
10
+ import { VoiceErrorCodes, VoiceServerError } from "./errors.js";
11
+ const MULTIPART_OVERHEAD_BYTES = 64 * 1024;
12
+ const JSON_BYTES_PER_CODE_POINT = 12;
13
+ const JSON_OVERHEAD_BYTES = 4 * 1024;
14
+ const ERROR_BODY_BYTES = 8 * 1024;
15
+ const LANGUAGE_PATTERN = /^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/;
16
+ const MAX_LANGUAGE_LENGTH = 32;
17
+ const MAX_PROMPT_CODE_POINTS = 1e3;
18
+ const SYNTHESIS_AUDIO_TYPES = /* @__PURE__ */ new Set(["audio/wav", "audio/x-wav", "audio/wave", "audio/mpeg"]);
19
+ function isBlobLike(value) {
20
+ if (!value || typeof value !== "object") return false;
21
+ const candidate = value;
22
+ return typeof candidate.size === "number" && typeof candidate.slice === "function" && typeof candidate.arrayBuffer === "function";
23
+ }
24
+ async function validateAudioUpload(file, maxBytes) {
25
+ if (!isBlobLike(file)) {
26
+ throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, "Missing audio file.");
27
+ }
28
+ if (file.size === 0) {
29
+ throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, "Audio file is empty.");
30
+ }
31
+ if (file.size < 4) {
32
+ throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, "Audio file is too short to identify.");
33
+ }
34
+ if (file.size > maxBytes) {
35
+ throw new VoiceServerError(VoiceErrorCodes.AUDIO_TOO_LARGE, "Audio file is too large.", 413);
36
+ }
37
+ let head;
38
+ try {
39
+ head = new Uint8Array(await file.slice(0, AUDIO_SNIFF_BYTES).arrayBuffer());
40
+ } catch {
41
+ throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, "Audio file cannot be read.");
42
+ }
43
+ const container = sniffAudioContainer(head);
44
+ if (!container) {
45
+ throw new VoiceServerError(VoiceErrorCodes.UNSUPPORTED_AUDIO, "Unsupported audio format.", 415);
46
+ }
47
+ return container;
48
+ }
49
+ function concatChunks(chunks, total) {
50
+ const result = new Uint8Array(total);
51
+ let offset = 0;
52
+ for (const chunk of chunks) {
53
+ result.set(chunk, offset);
54
+ offset += chunk.byteLength;
55
+ }
56
+ return result;
57
+ }
58
+ async function readBounded(stream, maxBytes, tooLarge) {
59
+ if (!stream) return new Uint8Array();
60
+ const reader = stream.getReader();
61
+ const chunks = [];
62
+ let total = 0;
63
+ try {
64
+ while (true) {
65
+ const { done, value } = await reader.read();
66
+ if (done) break;
67
+ total += value.byteLength;
68
+ if (total > maxBytes) throw tooLarge();
69
+ chunks.push(value);
70
+ }
71
+ } catch (error) {
72
+ await reader.cancel().catch(() => void 0);
73
+ throw error;
74
+ }
75
+ return concatChunks(chunks, total);
76
+ }
77
+ async function readLimited(response, maxBytes) {
78
+ const tooLarge = () => new VoiceServerError(
79
+ VoiceErrorCodes.UPSTREAM,
80
+ "Voice service response is too large.",
81
+ 502
82
+ );
83
+ const declared = Number(response.headers.get("content-length"));
84
+ if (Number.isFinite(declared) && declared > maxBytes) {
85
+ await response.body?.cancel().catch(() => void 0);
86
+ throw tooLarge();
87
+ }
88
+ return readBounded(response.body, maxBytes, tooLarge);
89
+ }
90
+ function toArrayBuffer(bytes) {
91
+ return bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength ? bytes.buffer : bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
92
+ }
93
+ async function readUpstreamErrorCode(response) {
94
+ if (!response.body) return void 0;
95
+ const reader = response.body.getReader();
96
+ const chunks = [];
97
+ let total = 0;
98
+ try {
99
+ while (total < ERROR_BODY_BYTES) {
100
+ const { done, value } = await reader.read();
101
+ if (done) break;
102
+ chunks.push(value);
103
+ total += value.byteLength;
104
+ }
105
+ } catch {
106
+ return void 0;
107
+ } finally {
108
+ await reader.cancel().catch(() => void 0);
109
+ }
110
+ try {
111
+ const body = JSON.parse(new TextDecoder().decode(concatChunks(chunks, total)));
112
+ const error = body && typeof body === "object" ? body.error : void 0;
113
+ const code = error && typeof error === "object" ? error.code : void 0;
114
+ return typeof code === "string" ? code : void 0;
115
+ } catch {
116
+ return void 0;
117
+ }
118
+ }
119
+ function upstreamError(status, upstreamCode) {
120
+ switch (status) {
121
+ case 401:
122
+ case 403:
123
+ return new VoiceServerError(
124
+ VoiceErrorCodes.UPSTREAM,
125
+ "Voice service rejected the Host credentials.",
126
+ 502
127
+ );
128
+ case 413:
129
+ if (upstreamCode === "TEXT_TOO_LONG") {
130
+ return new VoiceServerError(VoiceErrorCodes.TEXT_TOO_LONG, "Text is too long.", 413);
131
+ }
132
+ return new VoiceServerError(
133
+ VoiceErrorCodes.AUDIO_TOO_LARGE,
134
+ upstreamCode === "AUDIO_TOO_LONG" ? "Audio recording is too long." : "Audio file is too large.",
135
+ 413
136
+ );
137
+ case 415:
138
+ return new VoiceServerError(VoiceErrorCodes.UNSUPPORTED_AUDIO, "Unsupported audio format.", 415);
139
+ case 422:
140
+ return new VoiceServerError(
141
+ VoiceErrorCodes.UNDECODABLE_AUDIO,
142
+ "Audio could not be decoded.",
143
+ 422
144
+ );
145
+ case 429:
146
+ case 503:
147
+ if (status === 503 && upstreamCode === "ENGINE_UNAVAILABLE") {
148
+ return new VoiceServerError(VoiceErrorCodes.ENGINE_UNAVAILABLE, "Voice engine is unavailable.", 503);
149
+ }
150
+ return new VoiceServerError(VoiceErrorCodes.BUSY, "Voice service is busy.", 503);
151
+ case 400:
152
+ return new VoiceServerError(
153
+ VoiceErrorCodes.INVALID_OPTION,
154
+ "Voice service rejected the request options."
155
+ );
156
+ default:
157
+ return new VoiceServerError(
158
+ VoiceErrorCodes.UPSTREAM,
159
+ `Voice service failed (${status}).`,
160
+ 502
161
+ );
162
+ }
163
+ }
164
+ async function upstream(config, upstreamPath, init, read, signal) {
165
+ const controller = new AbortController();
166
+ let timedOut = false;
167
+ const timer = setTimeout(() => {
168
+ timedOut = true;
169
+ controller.abort();
170
+ }, config.timeoutMs);
171
+ const abort = () => controller.abort();
172
+ signal?.addEventListener("abort", abort, { once: true });
173
+ let release;
174
+ try {
175
+ if (signal?.aborted) controller.abort();
176
+ release = await acquireVoicePermit(config, controller.signal);
177
+ const headers = new Headers(init.headers);
178
+ if (config.serviceToken) headers.set("authorization", `Bearer ${config.serviceToken}`);
179
+ const response = await fetch(`${config.serviceUrl}${upstreamPath}`, {
180
+ ...init,
181
+ headers,
182
+ signal: controller.signal
183
+ });
184
+ if (!response.ok) {
185
+ throw upstreamError(response.status, await readUpstreamErrorCode(response));
186
+ }
187
+ return await read(response);
188
+ } catch (error) {
189
+ if (timedOut) {
190
+ throw new VoiceServerError(VoiceErrorCodes.TIMEOUT, "Voice service timed out.", 504);
191
+ }
192
+ if (error instanceof VoiceServerError) throw error;
193
+ if (signal?.aborted) {
194
+ throw new VoiceServerError(VoiceErrorCodes.TIMEOUT, "Voice request was aborted.", 499);
195
+ }
196
+ throw new VoiceServerError(VoiceErrorCodes.UPSTREAM, "Voice service unavailable.", 502);
197
+ } finally {
198
+ release?.();
199
+ clearTimeout(timer);
200
+ signal?.removeEventListener("abort", abort);
201
+ }
202
+ }
203
+ function rejectOversizedContentLength(request, maxBytes, tooLarge) {
204
+ const raw = request.headers.get("content-length");
205
+ if (!raw) return;
206
+ const length = Number(raw);
207
+ if (Number.isFinite(length) && length > maxBytes) throw tooLarge();
208
+ }
209
+ function exceedsCodePoints(text, maximum) {
210
+ let count = 0;
211
+ for (const _codePoint of text) {
212
+ count += 1;
213
+ if (count > maximum) return true;
214
+ }
215
+ return false;
216
+ }
217
+ function mediaType(value) {
218
+ return String(value ?? "").toLowerCase().split(";", 1)[0].trim();
219
+ }
220
+ function optionalTextField(form, name, message) {
221
+ const value = form.get(name);
222
+ if (value === null || value === "") return void 0;
223
+ if (typeof value !== "string") {
224
+ throw new VoiceServerError(VoiceErrorCodes.INVALID_OPTION, message);
225
+ }
226
+ return value;
227
+ }
228
+ function readTranscriptionOptions(form) {
229
+ const language = optionalTextField(form, "language", "Invalid voice language.");
230
+ if (language !== void 0 && (language.length > MAX_LANGUAGE_LENGTH || !LANGUAGE_PATTERN.test(language))) {
231
+ throw new VoiceServerError(VoiceErrorCodes.INVALID_OPTION, "Invalid voice language.");
232
+ }
233
+ const prompt = optionalTextField(form, "prompt", "Invalid voice prompt.");
234
+ if (prompt !== void 0 && exceedsCodePoints(prompt, MAX_PROMPT_CODE_POINTS)) {
235
+ throw new VoiceServerError(VoiceErrorCodes.INVALID_OPTION, "Voice prompt is too long.");
236
+ }
237
+ const wordTimestamps = optionalTextField(form, "word_timestamps", "Invalid word_timestamps.");
238
+ if (wordTimestamps !== void 0 && wordTimestamps !== "true" && wordTimestamps !== "false") {
239
+ throw new VoiceServerError(VoiceErrorCodes.INVALID_OPTION, "Invalid word_timestamps.");
240
+ }
241
+ return {
242
+ ...language !== void 0 ? { language } : {},
243
+ ...prompt !== void 0 ? { prompt } : {},
244
+ ...wordTimestamps !== void 0 ? { wordTimestamps } : {}
245
+ };
246
+ }
247
+ async function transcribe(request, config) {
248
+ if (mediaType(request.headers.get("content-type")) !== "multipart/form-data") {
249
+ throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, "Expected multipart/form-data.");
250
+ }
251
+ rejectOversizedContentLength(
252
+ request,
253
+ config.maxAudioBytes + MULTIPART_OVERHEAD_BYTES,
254
+ () => new VoiceServerError(VoiceErrorCodes.AUDIO_TOO_LARGE, "Audio request is too large.", 413)
255
+ );
256
+ let form;
257
+ try {
258
+ form = await request.formData();
259
+ } catch {
260
+ throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, "Malformed multipart request.");
261
+ }
262
+ const file = form.get("file");
263
+ const container = await validateAudioUpload(file, config.maxAudioBytes);
264
+ const options = readTranscriptionOptions(form);
265
+ const body = new FormData();
266
+ body.append(
267
+ "file",
268
+ new Blob([file], { type: AUDIO_CONTAINER_MIME[container] }),
269
+ `recording.${AUDIO_CONTAINER_EXTENSION[container]}`
270
+ );
271
+ if (options.language) body.append("language", options.language);
272
+ if (options.prompt) body.append("prompt", options.prompt);
273
+ if (options.wordTimestamps) body.append("word_timestamps", options.wordTimestamps);
274
+ return upstream(config, "/api/transcribe", { method: "POST", body }, async (response) => {
275
+ const bytes = await readLimited(response, config.maxResponseBytes);
276
+ let json;
277
+ try {
278
+ json = JSON.parse(new TextDecoder().decode(bytes));
279
+ } catch {
280
+ }
281
+ const result = parseTranscriptionResult(json);
282
+ if (!result) {
283
+ throw new VoiceServerError(VoiceErrorCodes.UPSTREAM, "Invalid transcription response.", 502);
284
+ }
285
+ return result;
286
+ }, request.signal);
287
+ }
288
+ async function readJsonBody(request, maxBytes) {
289
+ const tooLarge = () => new VoiceServerError(VoiceErrorCodes.TEXT_TOO_LONG, "Text is too long.", 413);
290
+ rejectOversizedContentLength(request, maxBytes, tooLarge);
291
+ let bytes;
292
+ try {
293
+ bytes = await readBounded(request.body, maxBytes, tooLarge);
294
+ } catch (error) {
295
+ if (error instanceof VoiceServerError) throw error;
296
+ throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, "Unable to read request body.");
297
+ }
298
+ try {
299
+ return JSON.parse(new TextDecoder().decode(bytes));
300
+ } catch {
301
+ throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, "Malformed JSON.");
302
+ }
303
+ }
304
+ async function readSynthesisRequest(request, config) {
305
+ if (mediaType(request.headers.get("content-type")) !== "application/json") {
306
+ throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, "Expected application/json.");
307
+ }
308
+ const input = await readJsonBody(
309
+ request,
310
+ config.maxTextCodePoints * JSON_BYTES_PER_CODE_POINT + JSON_OVERHEAD_BYTES
311
+ );
312
+ if (!input || typeof input !== "object" || Array.isArray(input)) {
313
+ throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, "Invalid speech request.");
314
+ }
315
+ const values = input;
316
+ const text = values.text;
317
+ if (typeof text !== "string" || !text.trim()) {
318
+ throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, "text is required.");
319
+ }
320
+ if (exceedsCodePoints(text, config.maxTextCodePoints)) {
321
+ throw new VoiceServerError(VoiceErrorCodes.TEXT_TOO_LONG, "Text is too long.", 413);
322
+ }
323
+ if (/\p{Cs}/u.test(text)) {
324
+ throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, "text must be valid Unicode.");
325
+ }
326
+ const voice = values.voice ?? config.voices[0];
327
+ if (typeof voice !== "string" || !config.voices.includes(voice)) {
328
+ throw new VoiceServerError(VoiceErrorCodes.INVALID_OPTION, "Invalid voice.");
329
+ }
330
+ const format = values.format ?? config.formats[0];
331
+ if (typeof format !== "string" || !config.formats.includes(format)) {
332
+ throw new VoiceServerError(VoiceErrorCodes.INVALID_OPTION, "Invalid audio format.");
333
+ }
334
+ const explicitSpeed = values.speed !== void 0 && values.speed !== null;
335
+ const speed = explicitSpeed ? values.speed : 1;
336
+ if (typeof speed !== "number" || explicitSpeed && !config.speeds.includes(speed)) {
337
+ throw new VoiceServerError(VoiceErrorCodes.INVALID_OPTION, "Invalid speed.");
338
+ }
339
+ return { text, voice, format, speed };
340
+ }
341
+ async function synthesize(request, config) {
342
+ const input = await readSynthesisRequest(request, config);
343
+ const result = await upstream(
344
+ config,
345
+ "/api/synthesize",
346
+ {
347
+ method: "POST",
348
+ headers: { "content-type": "application/json" },
349
+ body: JSON.stringify({
350
+ text: input.text,
351
+ voice: input.voice,
352
+ format: input.format,
353
+ speed: input.speed
354
+ })
355
+ },
356
+ async (response) => {
357
+ const mimeType = mediaType(response.headers.get("content-type"));
358
+ if (!SYNTHESIS_AUDIO_TYPES.has(mimeType)) {
359
+ await response.body?.cancel().catch(() => void 0);
360
+ throw new VoiceServerError(
361
+ VoiceErrorCodes.UPSTREAM,
362
+ "Voice service returned a non-audio response.",
363
+ 502
364
+ );
365
+ }
366
+ const bytes = await readLimited(response, config.maxResponseBytes);
367
+ if (!bytes.byteLength) {
368
+ throw new VoiceServerError(VoiceErrorCodes.UPSTREAM, "Voice service returned empty audio.", 502);
369
+ }
370
+ return { bytes, mimeType, durationMs: response.headers.get("x-audio-duration-ms") };
371
+ },
372
+ request.signal
373
+ );
374
+ const headers = new Headers({
375
+ "content-type": result.mimeType,
376
+ "content-length": String(result.bytes.byteLength),
377
+ "cache-control": "no-store",
378
+ "x-content-type-options": "nosniff"
379
+ });
380
+ const durationMs = result.durationMs?.trim();
381
+ if (durationMs && /^\d+$/.test(durationMs) && Number.isSafeInteger(Number(durationMs))) {
382
+ headers.set("x-audio-duration-ms", String(Number(durationMs)));
383
+ }
384
+ return new Response(toArrayBuffer(result.bytes), { status: 200, headers });
385
+ }
386
+ export {
387
+ synthesize,
388
+ transcribe,
389
+ validateAudioUpload
390
+ };
@@ -0,0 +1,16 @@
1
+ /**
2
+ * 音频容器识别:按文件头魔数判定,不信任浏览器声明的 MIME。
3
+ *
4
+ * 各浏览器 MediaRecorder 报出的 mimeType 可能为空、带或不带 codecs、甚至与内容不符;
5
+ * 客户端组装 Blob、Host 服务端校验上传、内部语音服务解码前都只认这里的判定。
6
+ * 判定表与内部语音服务 `soma_speech/audio.py` 的 `sniff_container` 一一对应。
7
+ */
8
+ export type AudioContainer = 'webm' | 'ogg' | 'mp4' | 'wav' | 'mp3' | 'flac' | 'aac';
9
+ /** 判定需要读取的文件头字节数。 */
10
+ export declare const AUDIO_SNIFF_BYTES = 16;
11
+ export declare const AUDIO_CONTAINER_MIME: Readonly<Record<AudioContainer, string>>;
12
+ export declare const AUDIO_CONTAINER_EXTENSION: Readonly<Record<AudioContainer, string>>;
13
+ /** 按文件头魔数判定容器;无法识别返回 undefined。 */
14
+ export declare function sniffAudioContainer(head: Uint8Array): AudioContainer | undefined;
15
+ /** 由 MIME 字符串(可带 codecs 参数)推断容器;仅作魔数判定之前的提示。 */
16
+ export declare function containerFromMimeType(mimeType: string | null | undefined): AudioContainer | undefined;