dsh-voice 0.5.11 → 0.6.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/CHANGELOG.md +10 -0
- package/README.en.md +28 -25
- package/README.md +28 -25
- package/docs/USAGE.en.md +73 -67
- package/docs/USAGE.md +72 -66
- package/lib/host-config.d.ts +111 -0
- package/lib/host-config.js +497 -0
- package/lib/index.d.ts +2 -0
- package/lib/index.js +16 -9
- package/lib/stt.js +3 -3
- package/lib/tools.d.ts +2 -2
- package/lib/tools.js +34 -20
- package/lib/update-client.js +145 -53
- package/package.json +2 -2
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 零外部依赖的宿主 Config Schema 与 liveConfig 活引用适配层(兼容 @deepseek-ai/schemastery 3.18+ 与 @deepseek-ai/cosmokit Volatile 协议)。
|
|
3
|
+
*
|
|
4
|
+
* 作用:
|
|
5
|
+
* 1. 让 DSH 原生「设置 → 插件 → 语音」自动渲染可视化表单,对 asrApiKey / proxyUrl 启用凭据脱敏(role('secret'));
|
|
6
|
+
* 2. 字段标记 volatile(),用户在设置面板保存音色、ASR 密钥或代理后立即生效,无需重启 DSH;
|
|
7
|
+
* 3. 不向 package.json 引入额外 npm 依赖,离线构建 100% 自包含。
|
|
8
|
+
*
|
|
9
|
+
* @module dsh-voice/host-config
|
|
10
|
+
*/
|
|
11
|
+
import type { VoiceConfig } from './config.js';
|
|
12
|
+
declare const kCheckedVolatile: unique symbol;
|
|
13
|
+
export interface HostSchemaMeta {
|
|
14
|
+
default?: unknown;
|
|
15
|
+
required?: boolean;
|
|
16
|
+
volatile?: boolean;
|
|
17
|
+
disabled?: boolean;
|
|
18
|
+
collapse?: boolean;
|
|
19
|
+
hidden?: boolean;
|
|
20
|
+
loose?: boolean;
|
|
21
|
+
role?: string;
|
|
22
|
+
extra?: unknown;
|
|
23
|
+
link?: string;
|
|
24
|
+
description?: string | Record<string, string>;
|
|
25
|
+
comment?: string;
|
|
26
|
+
pattern?: {
|
|
27
|
+
source: string;
|
|
28
|
+
flags?: string;
|
|
29
|
+
};
|
|
30
|
+
max?: number;
|
|
31
|
+
min?: number;
|
|
32
|
+
step?: number;
|
|
33
|
+
}
|
|
34
|
+
export interface HostSchemaOptions {
|
|
35
|
+
autofix?: boolean;
|
|
36
|
+
ignore?: (data: unknown, schema: HostSchemaNode) => boolean;
|
|
37
|
+
path?: Array<string | number | symbol>;
|
|
38
|
+
[kCheckedVolatile]?: boolean;
|
|
39
|
+
}
|
|
40
|
+
export interface VolatileRef<T = unknown> {
|
|
41
|
+
get(): T;
|
|
42
|
+
}
|
|
43
|
+
export interface HostSchemaNode<T = unknown> {
|
|
44
|
+
(data?: unknown, options?: HostSchemaOptions): T;
|
|
45
|
+
readonly uid: number;
|
|
46
|
+
type: string;
|
|
47
|
+
meta: HostSchemaMeta;
|
|
48
|
+
dict?: Record<string, HostSchemaNode>;
|
|
49
|
+
inner?: HostSchemaNode;
|
|
50
|
+
list?: HostSchemaNode[];
|
|
51
|
+
value?: unknown;
|
|
52
|
+
readonly '~standard': {
|
|
53
|
+
version: 1;
|
|
54
|
+
vendor: 'schemastery';
|
|
55
|
+
validate: (value: unknown) => {
|
|
56
|
+
value: unknown;
|
|
57
|
+
} | {
|
|
58
|
+
issues: Array<{
|
|
59
|
+
message: string;
|
|
60
|
+
path?: Array<string | number | symbol>;
|
|
61
|
+
}>;
|
|
62
|
+
};
|
|
63
|
+
};
|
|
64
|
+
toJSON(): unknown;
|
|
65
|
+
toString(inline?: boolean): string;
|
|
66
|
+
simplify(value?: unknown): unknown;
|
|
67
|
+
i18n(messages: Record<string, unknown>): HostSchemaNode<T>;
|
|
68
|
+
extra(key: keyof HostSchemaMeta, value: unknown): HostSchemaNode<T>;
|
|
69
|
+
role(role: string, extra?: unknown): HostSchemaNode<T>;
|
|
70
|
+
description(text: string | Record<string, string>): HostSchemaNode<T>;
|
|
71
|
+
comment(text: string): HostSchemaNode<T>;
|
|
72
|
+
link(url: string): HostSchemaNode<T>;
|
|
73
|
+
default(value: unknown): HostSchemaNode<T>;
|
|
74
|
+
min(value: number): HostSchemaNode<T>;
|
|
75
|
+
max(value: number): HostSchemaNode<T>;
|
|
76
|
+
step(value: number): HostSchemaNode<T>;
|
|
77
|
+
pattern(regexp: RegExp): HostSchemaNode<T>;
|
|
78
|
+
volatile(): HostSchemaNode<VolatileRef<T>>;
|
|
79
|
+
required(value?: boolean): HostSchemaNode<T>;
|
|
80
|
+
hidden(value?: boolean): HostSchemaNode<T>;
|
|
81
|
+
disabled(value?: boolean): HostSchemaNode<T>;
|
|
82
|
+
collapse(value?: boolean): HostSchemaNode<T>;
|
|
83
|
+
loose(value?: boolean): HostSchemaNode<T>;
|
|
84
|
+
set(key: string, value: HostSchemaNode): HostSchemaNode<T>;
|
|
85
|
+
push(value: HostSchemaNode): HostSchemaNode<T>;
|
|
86
|
+
}
|
|
87
|
+
export declare class HostValidationError extends TypeError {
|
|
88
|
+
readonly options: HostSchemaOptions;
|
|
89
|
+
name: string;
|
|
90
|
+
constructor(message: string, options?: HostSchemaOptions);
|
|
91
|
+
static is(error: unknown): error is HostValidationError;
|
|
92
|
+
}
|
|
93
|
+
export declare function createVolatile<T>(value: T): VolatileRef<T>;
|
|
94
|
+
export declare const z: {
|
|
95
|
+
string: () => HostSchemaNode<string>;
|
|
96
|
+
number: () => HostSchemaNode<number>;
|
|
97
|
+
boolean: () => HostSchemaNode<boolean>;
|
|
98
|
+
const: <const V extends string | number | boolean>(value: V) => HostSchemaNode<V>;
|
|
99
|
+
union: <T = unknown>(list: readonly unknown[]) => HostSchemaNode<T>;
|
|
100
|
+
array: <T = unknown>(inner: HostSchemaNode<T>) => HostSchemaNode<T[]>;
|
|
101
|
+
object: <T extends object = Record<string, unknown>>(dict: Record<string, HostSchemaNode>) => HostSchemaNode<T>;
|
|
102
|
+
ValidationError: typeof HostValidationError;
|
|
103
|
+
};
|
|
104
|
+
/**
|
|
105
|
+
* 宿主原生设置表单 Schema。
|
|
106
|
+
* 标量字段不设 default,以便留空时自动回退内置预设与环境变量 DSH_VOICE_ASR_KEY。
|
|
107
|
+
*/
|
|
108
|
+
export declare const Config: HostSchemaNode<VoiceConfig>;
|
|
109
|
+
/** 活引用视图:同时兼容 DSH >=0.1.7 的 { get() } 活引用与旧宿主/测试传入的普通对象。 */
|
|
110
|
+
export declare function liveConfig<T extends object>(config: T): T;
|
|
111
|
+
export {};
|
|
@@ -0,0 +1,497 @@
|
|
|
1
|
+
const kSchema = Symbol.for('schemastery');
|
|
2
|
+
const kValidationError = Symbol.for('ValidationError');
|
|
3
|
+
const kVolatileWrite = Symbol.for('cosmokit.volatile.write');
|
|
4
|
+
const kCheckedVolatile = Symbol('checked-volatile-schema');
|
|
5
|
+
const globalState = globalThis;
|
|
6
|
+
export class HostValidationError extends TypeError {
|
|
7
|
+
options;
|
|
8
|
+
name = 'ValidationError';
|
|
9
|
+
constructor(message, options = {}) {
|
|
10
|
+
let prefix = '$';
|
|
11
|
+
for (const segment of options.path ?? []) {
|
|
12
|
+
if (typeof segment === 'string')
|
|
13
|
+
prefix += '.' + segment;
|
|
14
|
+
else if (typeof segment === 'number')
|
|
15
|
+
prefix += '[' + segment + ']';
|
|
16
|
+
else
|
|
17
|
+
prefix += `[Symbol(${segment.toString()})]`;
|
|
18
|
+
}
|
|
19
|
+
if (prefix.startsWith('.'))
|
|
20
|
+
prefix = prefix.slice(1);
|
|
21
|
+
super((prefix === '$' ? '' : `${prefix} `) + message);
|
|
22
|
+
this.options = options;
|
|
23
|
+
}
|
|
24
|
+
static is(error) {
|
|
25
|
+
return typeof error === 'object' && error !== null && Boolean(error[kValidationError]);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
Object.defineProperty(HostValidationError.prototype, kValidationError, { value: true });
|
|
29
|
+
function isNullable(value) {
|
|
30
|
+
return value === null || value === undefined;
|
|
31
|
+
}
|
|
32
|
+
function isPlainObject(value) {
|
|
33
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value))
|
|
34
|
+
return false;
|
|
35
|
+
const proto = Object.getPrototypeOf(value);
|
|
36
|
+
return proto === Object.prototype || proto === null;
|
|
37
|
+
}
|
|
38
|
+
function isVolatile(value) {
|
|
39
|
+
return typeof value === 'object' && value !== null && kVolatileWrite in value;
|
|
40
|
+
}
|
|
41
|
+
function cloneValue(value) {
|
|
42
|
+
if (value === null || typeof value !== 'object')
|
|
43
|
+
return value;
|
|
44
|
+
if (Array.isArray(value))
|
|
45
|
+
return value.map((item) => cloneValue(item));
|
|
46
|
+
if (isPlainObject(value)) {
|
|
47
|
+
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, cloneValue(v)]));
|
|
48
|
+
}
|
|
49
|
+
return value;
|
|
50
|
+
}
|
|
51
|
+
function deepEqual(a, b) {
|
|
52
|
+
if (Object.is(a, b))
|
|
53
|
+
return true;
|
|
54
|
+
if (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null)
|
|
55
|
+
return false;
|
|
56
|
+
if (Array.isArray(a) || Array.isArray(b)) {
|
|
57
|
+
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length)
|
|
58
|
+
return false;
|
|
59
|
+
return a.every((item, idx) => deepEqual(item, b[idx]));
|
|
60
|
+
}
|
|
61
|
+
if (!isPlainObject(a) || !isPlainObject(b))
|
|
62
|
+
return false;
|
|
63
|
+
const keysA = Object.keys(a);
|
|
64
|
+
const keysB = Object.keys(b);
|
|
65
|
+
if (keysA.length !== keysB.length)
|
|
66
|
+
return false;
|
|
67
|
+
return keysA.every((key) => Object.prototype.hasOwnProperty.call(b, key) && deepEqual(a[key], b[key]));
|
|
68
|
+
}
|
|
69
|
+
function snapshotValue(value, ancestors = new Set()) {
|
|
70
|
+
if (typeof value === 'function')
|
|
71
|
+
throw new TypeError('volatile config cannot contain functions');
|
|
72
|
+
if (value === null || typeof value !== 'object')
|
|
73
|
+
return value;
|
|
74
|
+
if (ancestors.has(value))
|
|
75
|
+
throw new TypeError('volatile config cannot contain cycles');
|
|
76
|
+
ancestors.add(value);
|
|
77
|
+
try {
|
|
78
|
+
if (Array.isArray(value))
|
|
79
|
+
return Object.freeze(value.map((item) => snapshotValue(item, ancestors)));
|
|
80
|
+
if (!isPlainObject(value))
|
|
81
|
+
throw new TypeError('volatile config objects must be plain objects or arrays');
|
|
82
|
+
return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, snapshotValue(item, ancestors)])));
|
|
83
|
+
}
|
|
84
|
+
finally {
|
|
85
|
+
ancestors.delete(value);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
export function createVolatile(value) {
|
|
89
|
+
let current = snapshotValue(value);
|
|
90
|
+
return Object.freeze({
|
|
91
|
+
get: () => current,
|
|
92
|
+
[kVolatileWrite]: (next) => { current = snapshotValue(next); },
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
function validateVolatileTree(schema, path = [], blocked = false, seen = new Map()) {
|
|
96
|
+
const states = seen.get(schema) ?? new Set();
|
|
97
|
+
if (states.has(blocked))
|
|
98
|
+
return;
|
|
99
|
+
states.add(blocked);
|
|
100
|
+
seen.set(schema, states);
|
|
101
|
+
if (schema.meta?.volatile && blocked) {
|
|
102
|
+
throw new HostValidationError('volatile fields require a fixed object path without an enclosing volatile field', { path });
|
|
103
|
+
}
|
|
104
|
+
const nested = blocked || Boolean(schema.meta?.volatile);
|
|
105
|
+
if (schema.dict) {
|
|
106
|
+
for (const [key, child] of Object.entries(schema.dict))
|
|
107
|
+
validateVolatileTree(child, [...path, key], nested, seen);
|
|
108
|
+
}
|
|
109
|
+
if (schema.inner)
|
|
110
|
+
validateVolatileTree(schema.inner, [...path, '*'], true, seen);
|
|
111
|
+
if (schema.list) {
|
|
112
|
+
schema.list.forEach((child, idx) => validateVolatileTree(child, [...path, String(idx)], true, seen));
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
function checkRange(value, meta, label, options, skipMin = false) {
|
|
116
|
+
const max = meta.max ?? Infinity;
|
|
117
|
+
const min = meta.min ?? -Infinity;
|
|
118
|
+
if (value > max)
|
|
119
|
+
throw new HostValidationError(`expected ${label} <= ${max} but got ${value}`, options);
|
|
120
|
+
if (value < min && !skipMin)
|
|
121
|
+
throw new HostValidationError(`expected ${label} >= ${min} but got ${value}`, options);
|
|
122
|
+
}
|
|
123
|
+
function resolveProperty(data, key, schema, options) {
|
|
124
|
+
const container = data;
|
|
125
|
+
try {
|
|
126
|
+
const [value, adapted] = resolveSchema(container[key], schema, {
|
|
127
|
+
...options,
|
|
128
|
+
path: [...(options.path ?? []), key],
|
|
129
|
+
});
|
|
130
|
+
if (adapted !== undefined)
|
|
131
|
+
container[key] = adapted;
|
|
132
|
+
return value;
|
|
133
|
+
}
|
|
134
|
+
catch (error) {
|
|
135
|
+
if (!options.autofix)
|
|
136
|
+
throw error;
|
|
137
|
+
delete container[key];
|
|
138
|
+
return schema.meta.volatile ? createVolatile(schema.meta.default) : cloneValue(schema.meta.default);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
function resolveSchema(data, schema, options = {}, strict = false) {
|
|
142
|
+
if (!schema)
|
|
143
|
+
return [data];
|
|
144
|
+
if (!options[kCheckedVolatile]) {
|
|
145
|
+
validateVolatileTree(schema, options.path);
|
|
146
|
+
options = { ...options, [kCheckedVolatile]: true };
|
|
147
|
+
}
|
|
148
|
+
if (schema.meta?.volatile) {
|
|
149
|
+
const inner = makeSchema({ ...schema, meta: { ...schema.meta, volatile: false } });
|
|
150
|
+
const [value, adapted] = resolveSchema(data, inner, options, strict);
|
|
151
|
+
try {
|
|
152
|
+
return [createVolatile(value), adapted];
|
|
153
|
+
}
|
|
154
|
+
catch (error) {
|
|
155
|
+
throw new HostValidationError(error instanceof Error ? error.message : String(error), options);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
if (options.ignore?.(data, schema))
|
|
159
|
+
return [data];
|
|
160
|
+
if (isNullable(data)) {
|
|
161
|
+
if (schema.meta.required)
|
|
162
|
+
throw new HostValidationError('missing required value', options);
|
|
163
|
+
if (isNullable(schema.meta.default))
|
|
164
|
+
return [data];
|
|
165
|
+
data = cloneValue(schema.meta.default);
|
|
166
|
+
}
|
|
167
|
+
try {
|
|
168
|
+
switch (schema.type) {
|
|
169
|
+
case 'any':
|
|
170
|
+
return [data];
|
|
171
|
+
case 'const':
|
|
172
|
+
if (deepEqual(data, schema.value))
|
|
173
|
+
return [schema.value];
|
|
174
|
+
throw new HostValidationError(`expected ${String(schema.value)} but got ${String(data)}`, options);
|
|
175
|
+
case 'string': {
|
|
176
|
+
if (typeof data !== 'string')
|
|
177
|
+
throw new HostValidationError(`expected string but got ${String(data)}`, options);
|
|
178
|
+
if (schema.meta.pattern) {
|
|
179
|
+
const re = new RegExp(schema.meta.pattern.source, schema.meta.pattern.flags);
|
|
180
|
+
if (!re.test(data))
|
|
181
|
+
throw new HostValidationError(`expect string to match regexp ${String(re)}`, options);
|
|
182
|
+
}
|
|
183
|
+
checkRange(data.length, schema.meta, 'string length', options);
|
|
184
|
+
return [data];
|
|
185
|
+
}
|
|
186
|
+
case 'number': {
|
|
187
|
+
if (typeof data !== 'number' || Number.isNaN(data))
|
|
188
|
+
throw new HostValidationError(`expected number but got ${String(data)}`, options);
|
|
189
|
+
checkRange(data, schema.meta, 'number', options);
|
|
190
|
+
return [data];
|
|
191
|
+
}
|
|
192
|
+
case 'boolean':
|
|
193
|
+
if (typeof data === 'boolean')
|
|
194
|
+
return [data];
|
|
195
|
+
throw new HostValidationError(`expected boolean but got ${String(data)}`, options);
|
|
196
|
+
case 'array': {
|
|
197
|
+
if (!Array.isArray(data) || !schema.inner)
|
|
198
|
+
throw new HostValidationError(`expected array but got ${String(data)}`, options);
|
|
199
|
+
checkRange(data.length, schema.meta, 'array length', options, !isNullable(schema.inner.meta.default));
|
|
200
|
+
const copy = [...data];
|
|
201
|
+
return [copy.map((_, idx) => resolveProperty(copy, idx, schema.inner, options))];
|
|
202
|
+
}
|
|
203
|
+
case 'object': {
|
|
204
|
+
if (!isPlainObject(data))
|
|
205
|
+
throw new HostValidationError(`expected object but got ${String(data)}`, options);
|
|
206
|
+
const dict = schema.dict ?? {};
|
|
207
|
+
const copy = { ...data };
|
|
208
|
+
const result = {};
|
|
209
|
+
for (const key of Object.keys(dict)) {
|
|
210
|
+
const value = resolveProperty(copy, key, dict[key], options);
|
|
211
|
+
if (!isNullable(value) || key in copy)
|
|
212
|
+
result[key] = value;
|
|
213
|
+
}
|
|
214
|
+
if (!strict) {
|
|
215
|
+
for (const key of Object.keys(copy)) {
|
|
216
|
+
if (!(key in result))
|
|
217
|
+
result[key] = copy[key];
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
return [result];
|
|
221
|
+
}
|
|
222
|
+
case 'union': {
|
|
223
|
+
for (const candidate of schema.list ?? []) {
|
|
224
|
+
try {
|
|
225
|
+
return resolveSchema(data, candidate, options, strict);
|
|
226
|
+
}
|
|
227
|
+
catch {
|
|
228
|
+
// Try next union branch.
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
throw new HostValidationError(`expected ${schema.toString()} but got ${JSON.stringify(data)}`, options);
|
|
232
|
+
}
|
|
233
|
+
default:
|
|
234
|
+
throw new HostValidationError(`unsupported type "${schema.type}"`, options);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
catch (error) {
|
|
238
|
+
if (!schema.meta.loose)
|
|
239
|
+
throw error;
|
|
240
|
+
return [cloneValue(schema.meta.default)];
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
function mergeDescriptions(original, messages) {
|
|
244
|
+
const result = typeof original === 'string' ? { '': original } : { ...(original ?? {}) };
|
|
245
|
+
for (const [locale, entry] of Object.entries(messages)) {
|
|
246
|
+
if (typeof entry === 'string') {
|
|
247
|
+
result[locale] = entry;
|
|
248
|
+
}
|
|
249
|
+
else if (isPlainObject(entry)) {
|
|
250
|
+
const desc = entry.$description ?? entry.$desc;
|
|
251
|
+
if (typeof desc === 'string')
|
|
252
|
+
result[locale] = desc;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
return result;
|
|
256
|
+
}
|
|
257
|
+
const schemaProto = Object.create(Function.prototype);
|
|
258
|
+
schemaProto[kSchema] = true;
|
|
259
|
+
Object.defineProperty(schemaProto, '~standard', {
|
|
260
|
+
get() {
|
|
261
|
+
return {
|
|
262
|
+
version: 1,
|
|
263
|
+
vendor: 'schemastery',
|
|
264
|
+
validate: (value) => {
|
|
265
|
+
try {
|
|
266
|
+
return { value: resolveSchema(value, this, {})[0] };
|
|
267
|
+
}
|
|
268
|
+
catch (error) {
|
|
269
|
+
if (HostValidationError.is(error)) {
|
|
270
|
+
return { issues: [{ message: error.message, path: error.options.path }] };
|
|
271
|
+
}
|
|
272
|
+
throw error;
|
|
273
|
+
}
|
|
274
|
+
},
|
|
275
|
+
};
|
|
276
|
+
},
|
|
277
|
+
});
|
|
278
|
+
schemaProto.toJSON = function toJSON() {
|
|
279
|
+
if (globalState.__schemastery_refs__) {
|
|
280
|
+
globalState.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));
|
|
281
|
+
return this.uid;
|
|
282
|
+
}
|
|
283
|
+
globalState.__schemastery_refs__ = { [this.uid]: { ...this } };
|
|
284
|
+
globalState.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));
|
|
285
|
+
const result = { uid: this.uid, refs: globalState.__schemastery_refs__ };
|
|
286
|
+
globalState.__schemastery_refs__ = undefined;
|
|
287
|
+
return result;
|
|
288
|
+
};
|
|
289
|
+
schemaProto.toString = function toString(inline = false) {
|
|
290
|
+
if (this.type === 'const')
|
|
291
|
+
return typeof this.value === 'string' ? JSON.stringify(this.value) : String(this.value);
|
|
292
|
+
if (this.type === 'array' && this.inner)
|
|
293
|
+
return `${this.inner.toString(true)}[]`;
|
|
294
|
+
if (this.type === 'union' && this.list) {
|
|
295
|
+
const joined = this.list.map((item) => item.toString()).join(' | ');
|
|
296
|
+
return inline ? `(${joined})` : joined;
|
|
297
|
+
}
|
|
298
|
+
if (this.type === 'object' && this.dict) {
|
|
299
|
+
const entries = Object.entries(this.dict);
|
|
300
|
+
if (entries.length === 0)
|
|
301
|
+
return '{}';
|
|
302
|
+
return `{ ${entries.map(([k, v]) => `${k}${v.meta.required ? '' : '?'}: ${v.toString()}`).join(', ')} }`;
|
|
303
|
+
}
|
|
304
|
+
return this.type;
|
|
305
|
+
};
|
|
306
|
+
schemaProto.simplify = function simplify(raw) {
|
|
307
|
+
const value = isVolatile(raw) ? raw.get() : raw;
|
|
308
|
+
if (deepEqual(value, this.meta.default))
|
|
309
|
+
return null;
|
|
310
|
+
if (isNullable(value))
|
|
311
|
+
return value;
|
|
312
|
+
if (this.type === 'object' && isPlainObject(value)) {
|
|
313
|
+
const out = {};
|
|
314
|
+
for (const [key, item] of Object.entries(value)) {
|
|
315
|
+
const simplified = this.dict?.[key] ? this.dict[key].simplify(item) : item;
|
|
316
|
+
if (!isNullable(simplified))
|
|
317
|
+
out[key] = simplified;
|
|
318
|
+
}
|
|
319
|
+
return deepEqual(out, this.meta.default) ? null : out;
|
|
320
|
+
}
|
|
321
|
+
if (this.type === 'array' && Array.isArray(value)) {
|
|
322
|
+
return value.map((item) => (this.inner ? this.inner.simplify(item) : item));
|
|
323
|
+
}
|
|
324
|
+
return value;
|
|
325
|
+
};
|
|
326
|
+
schemaProto.i18n = function i18n(messages) {
|
|
327
|
+
const cloned = makeSchema(this);
|
|
328
|
+
const desc = mergeDescriptions(cloned.meta.description, messages);
|
|
329
|
+
if (Object.keys(desc).length > 0)
|
|
330
|
+
cloned.meta = { ...cloned.meta, description: desc };
|
|
331
|
+
if (cloned.dict) {
|
|
332
|
+
const nextDict = {};
|
|
333
|
+
for (const [key, child] of Object.entries(cloned.dict)) {
|
|
334
|
+
const childMessages = {};
|
|
335
|
+
for (const [locale, data] of Object.entries(messages)) {
|
|
336
|
+
if (isPlainObject(data)) {
|
|
337
|
+
const inner = isPlainObject(data.$value) ? data.$value : isPlainObject(data.$inner) ? data.$inner : data;
|
|
338
|
+
if (key in inner)
|
|
339
|
+
childMessages[locale] = inner[key];
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
nextDict[key] = child.i18n(childMessages);
|
|
343
|
+
}
|
|
344
|
+
cloned.dict = nextDict;
|
|
345
|
+
}
|
|
346
|
+
if (cloned.inner) {
|
|
347
|
+
const innerMessages = {};
|
|
348
|
+
for (const [locale, data] of Object.entries(messages)) {
|
|
349
|
+
if (isPlainObject(data)) {
|
|
350
|
+
const inner = data.$value ?? data.$inner;
|
|
351
|
+
if (inner !== undefined)
|
|
352
|
+
innerMessages[locale] = inner;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
cloned.inner = cloned.inner.i18n(innerMessages);
|
|
356
|
+
}
|
|
357
|
+
return cloned;
|
|
358
|
+
};
|
|
359
|
+
schemaProto.extra = function extra(key, value) {
|
|
360
|
+
const cloned = makeSchema(this);
|
|
361
|
+
cloned.meta = { ...cloned.meta, [key]: value };
|
|
362
|
+
return cloned;
|
|
363
|
+
};
|
|
364
|
+
schemaProto.role = function role(name, extraValue) {
|
|
365
|
+
const cloned = makeSchema(this);
|
|
366
|
+
cloned.meta = { ...cloned.meta, role: name, ...(extraValue !== undefined ? { extra: extraValue } : {}) };
|
|
367
|
+
return cloned;
|
|
368
|
+
};
|
|
369
|
+
for (const key of ['default', 'link', 'comment', 'description', 'max', 'min', 'step']) {
|
|
370
|
+
schemaProto[key] = function (value) {
|
|
371
|
+
return this.extra(key, value);
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
for (const key of ['required', 'disabled', 'collapse', 'hidden', 'loose']) {
|
|
375
|
+
schemaProto[key] = function (value = true) {
|
|
376
|
+
return this.extra(key, value);
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
schemaProto.pattern = function pattern(regexp) {
|
|
380
|
+
return this.extra('pattern', { source: regexp.source, flags: regexp.flags });
|
|
381
|
+
};
|
|
382
|
+
schemaProto.volatile = function volatile() {
|
|
383
|
+
if (this.meta.volatile)
|
|
384
|
+
throw new TypeError('volatile schema is already wrapped');
|
|
385
|
+
return this.extra('volatile', true);
|
|
386
|
+
};
|
|
387
|
+
schemaProto.set = function set(key, value) {
|
|
388
|
+
this.dict ??= {};
|
|
389
|
+
this.dict[key] = value;
|
|
390
|
+
return this;
|
|
391
|
+
};
|
|
392
|
+
schemaProto.push = function push(value) {
|
|
393
|
+
this.list ??= [];
|
|
394
|
+
this.list.push(value);
|
|
395
|
+
return this;
|
|
396
|
+
};
|
|
397
|
+
function makeSchema(init) {
|
|
398
|
+
const fn = function (data, options = {}) {
|
|
399
|
+
return resolveSchema(data, fn, options)[0];
|
|
400
|
+
};
|
|
401
|
+
Object.assign(fn, {
|
|
402
|
+
type: init.type,
|
|
403
|
+
meta: { ...(init.meta ?? {}) },
|
|
404
|
+
...(init.dict ? { dict: { ...init.dict } } : {}),
|
|
405
|
+
...(init.inner ? { inner: init.inner } : {}),
|
|
406
|
+
...(init.list ? { list: [...init.list] } : {}),
|
|
407
|
+
...('value' in init ? { value: init.value } : {}),
|
|
408
|
+
});
|
|
409
|
+
globalState.__schemastery_index__ ??= 0;
|
|
410
|
+
Object.defineProperty(fn, 'uid', { value: globalState.__schemastery_index__++, enumerable: false });
|
|
411
|
+
Object.setPrototypeOf(fn, schemaProto);
|
|
412
|
+
fn.toString = fn.toString.bind(fn);
|
|
413
|
+
return fn;
|
|
414
|
+
}
|
|
415
|
+
function fromSource(source) {
|
|
416
|
+
if (typeof source === 'function' && Boolean(source[kSchema])) {
|
|
417
|
+
return source;
|
|
418
|
+
}
|
|
419
|
+
if (typeof source === 'string' || typeof source === 'number' || typeof source === 'boolean') {
|
|
420
|
+
return makeSchema({ type: 'const', value: source, meta: { required: true } });
|
|
421
|
+
}
|
|
422
|
+
throw new TypeError(`cannot infer schema from ${String(source)}`);
|
|
423
|
+
}
|
|
424
|
+
export const z = {
|
|
425
|
+
string: () => makeSchema({ type: 'string' }),
|
|
426
|
+
number: () => makeSchema({ type: 'number' }),
|
|
427
|
+
boolean: () => makeSchema({ type: 'boolean' }),
|
|
428
|
+
const: (value) => makeSchema({ type: 'const', value }),
|
|
429
|
+
union: (list) => makeSchema({ type: 'union', list: list.map(fromSource) }),
|
|
430
|
+
array: (inner) => makeSchema({ type: 'array', inner, meta: { default: [] } }),
|
|
431
|
+
object: (dict) => makeSchema({ type: 'object', dict, meta: { default: {} } }),
|
|
432
|
+
ValidationError: HostValidationError,
|
|
433
|
+
};
|
|
434
|
+
/**
|
|
435
|
+
* 宿主原生设置表单 Schema。
|
|
436
|
+
* 标量字段不设 default,以便留空时自动回退内置预设与环境变量 DSH_VOICE_ASR_KEY。
|
|
437
|
+
*/
|
|
438
|
+
export const Config = z.object({
|
|
439
|
+
ttsVoice: z.string().volatile()
|
|
440
|
+
.description('默认朗读音色(默认 zh-CN-XiaoxiaoNeural,无需 API 密钥即可合成 MP3)'),
|
|
441
|
+
ttsRate: z.string().volatile()
|
|
442
|
+
.description('默认语速(如 +0%、+15%、-10%)'),
|
|
443
|
+
ttsPitch: z.string().volatile()
|
|
444
|
+
.description('默认音调(如 +0Hz、+2Hz、-1Hz)'),
|
|
445
|
+
asrEngine: z.union(['groq', 'openai', 'custom']).volatile()
|
|
446
|
+
.description('语音转文字(ASR)服务预设:groq(默认)/ openai / custom'),
|
|
447
|
+
asrBaseUrl: z.string().volatile()
|
|
448
|
+
.description('ASR 接口地址(custom 模式必填,如 https://api.example.com/v1;groq / openai 留空使用官方预设)'),
|
|
449
|
+
asrApiKey: z.string().role('secret').volatile()
|
|
450
|
+
.description('ASR API 密钥(自动脱敏;留空时读取环境变量 DSH_VOICE_ASR_KEY,仅录音转文字需要)'),
|
|
451
|
+
asrModel: z.string().volatile()
|
|
452
|
+
.description('ASR 模型名(可选;groq 默认 whisper-large-v3-turbo,openai 默认 whisper-1)'),
|
|
453
|
+
proxyUrl: z.string().role('secret').volatile()
|
|
454
|
+
.description('HTTP(S) 代理地址(可选,如 http://127.0.0.1:7890)'),
|
|
455
|
+
timeoutMs: z.number().min(5000).max(600000).step(1000).volatile()
|
|
456
|
+
.description('单次合成或转写超时毫秒数(5000–600000,默认 60000)'),
|
|
457
|
+
overwrite: z.boolean().volatile()
|
|
458
|
+
.description('同名输出文件是否直接覆盖(默认关闭,自动加序号防误盖)'),
|
|
459
|
+
}).i18n({
|
|
460
|
+
zh: {
|
|
461
|
+
$description: '零密钥 Edge 语音合成(TTS)与兼容语音转文字(ASR)设置(保存立即生效)',
|
|
462
|
+
ttsVoice: '默认朗读音色(如 zh-CN-XiaoxiaoNeural、en-US-AriaNeural;文字转语音无需密钥)',
|
|
463
|
+
ttsRate: '默认语速(如 +0%、+15%、-10%)',
|
|
464
|
+
ttsPitch: '默认音调(如 +0Hz、+2Hz、-1Hz)',
|
|
465
|
+
asrEngine: '语音转文字引擎预设(groq / openai / custom)',
|
|
466
|
+
asrBaseUrl: 'ASR 接口基地址(custom 必填,需含 /v1;groq / openai 可留空)',
|
|
467
|
+
asrApiKey: 'ASR API 密钥(脱敏保存;留空时读取环境变量 DSH_VOICE_ASR_KEY)',
|
|
468
|
+
asrModel: 'ASR 模型名称(可选;留空按引擎预设自动选择)',
|
|
469
|
+
proxyUrl: '网络代理地址(可选,如 http://127.0.0.1:7890)',
|
|
470
|
+
timeoutMs: '请求超时毫秒数(5000–600000,默认 60000)',
|
|
471
|
+
overwrite: '允许覆盖同名音频或转写文本(默认关闭,自动追加序号)',
|
|
472
|
+
},
|
|
473
|
+
en: {
|
|
474
|
+
$description: 'Keyless Edge TTS read-aloud and OpenAI/Groq-compatible ASR transcription settings (live on save)',
|
|
475
|
+
ttsVoice: 'Default TTS voice ID (e.g. zh-CN-XiaoxiaoNeural, en-US-AriaNeural; no API key required)',
|
|
476
|
+
ttsRate: 'Default speech rate (e.g. +0%, +15%, -10%)',
|
|
477
|
+
ttsPitch: 'Default pitch offset (e.g. +0Hz, +2Hz, -1Hz)',
|
|
478
|
+
asrEngine: 'Speech-to-text engine preset (groq / openai / custom)',
|
|
479
|
+
asrBaseUrl: 'ASR API base URL (required when asrEngine is custom, e.g. https://api.example.com/v1)',
|
|
480
|
+
asrApiKey: 'ASR API key (masked; falls back to env var DSH_VOICE_ASR_KEY; only needed for transcription)',
|
|
481
|
+
asrModel: 'ASR model name (optional; defaults to whisper-large-v3-turbo on groq or whisper-1 on openai)',
|
|
482
|
+
proxyUrl: 'Optional HTTP(S) proxy URL (e.g. http://127.0.0.1:7890)',
|
|
483
|
+
timeoutMs: 'Per-request timeout in ms (5000–600000, default 60000)',
|
|
484
|
+
overwrite: 'Overwrite existing output files instead of auto-numbering (default off)',
|
|
485
|
+
},
|
|
486
|
+
});
|
|
487
|
+
/** 活引用视图:同时兼容 DSH >=0.1.7 的 { get() } 活引用与旧宿主/测试传入的普通对象。 */
|
|
488
|
+
export function liveConfig(config) {
|
|
489
|
+
return new Proxy(config, {
|
|
490
|
+
get(target, key, receiver) {
|
|
491
|
+
const value = Reflect.get(target, key, receiver);
|
|
492
|
+
return value !== null && typeof value === 'object' && typeof value.get === 'function'
|
|
493
|
+
? value.get()
|
|
494
|
+
: value;
|
|
495
|
+
},
|
|
496
|
+
});
|
|
497
|
+
}
|
package/lib/index.d.ts
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
import { type VoiceConfig } from './config.js';
|
|
11
11
|
import { type VoiceToolDefinition } from './tools.js';
|
|
12
12
|
/** cordis 服务注入:apply 里要用 ctx.tools,必须显式声明。 */
|
|
13
|
+
export declare const Config: import("./host-config.js").HostSchemaNode<VoiceConfig>;
|
|
13
14
|
export declare const name = "voice";
|
|
14
15
|
export declare const inject: string[];
|
|
15
16
|
/** 插件所需的最小 ctx 面。 */
|
|
@@ -28,6 +29,7 @@ export interface VoicePluginContext {
|
|
|
28
29
|
*/
|
|
29
30
|
export declare function apply(ctx: VoicePluginContext, config?: VoiceConfig | null): void;
|
|
30
31
|
export * from './config.js';
|
|
32
|
+
export { liveConfig, createVolatile, HostValidationError, type HostSchemaNode, type HostSchemaMeta, type VolatileRef } from './host-config.js';
|
|
31
33
|
export * from './edge-tts.js';
|
|
32
34
|
export * from './paths.js';
|
|
33
35
|
export * from './proxy-fetch.js';
|
package/lib/index.js
CHANGED
|
@@ -9,8 +9,10 @@ import { registerUpdates } from '@stardustlc/dsh-updates';
|
|
|
9
9
|
* @module dsh-voice
|
|
10
10
|
*/
|
|
11
11
|
import { resolveConfig } from './config.js';
|
|
12
|
+
import { Config as VoiceConfigSchema, liveConfig } from './host-config.js';
|
|
12
13
|
import { buildVoiceTools } from './tools.js';
|
|
13
14
|
/** cordis 服务注入:apply 里要用 ctx.tools,必须显式声明。 */
|
|
15
|
+
export const Config = VoiceConfigSchema;
|
|
14
16
|
export const name = 'voice';
|
|
15
17
|
export const inject = ['tools'];
|
|
16
18
|
/**
|
|
@@ -24,16 +26,20 @@ export function apply(ctx, config) {
|
|
|
24
26
|
else
|
|
25
27
|
console.warn(message);
|
|
26
28
|
};
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
29
|
+
const live = liveConfig((config ?? {}));
|
|
30
|
+
const readCfg = () => {
|
|
31
|
+
try {
|
|
32
|
+
return resolveConfig(live, (msg) => warn('[dsh-voice] ' + msg));
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
warn('[dsh-voice] ' + (error instanceof Error ? error.message : String(error)));
|
|
36
|
+
return resolveConfig(null, (msg) => warn('[dsh-voice] ' + msg));
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
// 启动期跑一次校验,触发必要的告警但绝不阻断注册。
|
|
40
|
+
readCfg();
|
|
35
41
|
const disposers = [];
|
|
36
|
-
for (const definition of buildVoiceTools(
|
|
42
|
+
for (const definition of buildVoiceTools(readCfg)) {
|
|
37
43
|
disposers.push(ctx.tools.register(definition));
|
|
38
44
|
}
|
|
39
45
|
const teardown = () => {
|
|
@@ -48,6 +54,7 @@ export function apply(ctx, config) {
|
|
|
48
54
|
}
|
|
49
55
|
}
|
|
50
56
|
export * from './config.js';
|
|
57
|
+
export { liveConfig, createVolatile, HostValidationError } from './host-config.js';
|
|
51
58
|
export * from './edge-tts.js';
|
|
52
59
|
export * from './paths.js';
|
|
53
60
|
export * from './proxy-fetch.js';
|