@coze/uniapp-api
Version:
Official Coze UniApp SDK for seamless AI integration into your applications | 扣子官方 UniApp SDK,助您轻松集成 AI 能力到应用中
189 lines (188 loc) • 7.41 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseWsTranscriptionClient = void 0;
const api_1 = require("@coze/api");
const pcm_recorder_1 = require("../pcm-recorder");
const api_2 = require("../../api");
/**
* Base WebSocket transcription client for UniApp/WeChat Mini Program
*/
class BaseWsTranscriptionClient {
/**
* Creates a new BaseWsTranscriptionClient instance
* @param {WsToolsOptions} config - Configuration options
*/
constructor(config) {
/**
* WebSocket connection instance
*/
Object.defineProperty(this, "ws", {
enumerable: true,
configurable: true,
writable: true,
value: null
});
/**
* Event listeners map
*/
Object.defineProperty(this, "listeners", {
enumerable: true,
configurable: true,
writable: true,
value: new Map()
});
/**
* Recorder instance for capturing audio
*/
Object.defineProperty(this, "recorder", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Client configuration options
*/
Object.defineProperty(this, "config", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* API client for making requests
*/
Object.defineProperty(this, "api", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
this.api = new api_2.CozeAPI(Object.assign(Object.assign({ baseWsURL: api_1.COZE_CN_BASE_WS_URL }, config), { debug: false }));
this.recorder = new pcm_recorder_1.PcmRecorder({
sampleRate: 24000,
debug: config.debug,
});
this.config = config;
}
/**
* Initialize WebSocket connection
* @returns {Promise<WebSocketAPI>} - WebSocket connection instance
*/
init() {
return __awaiter(this, void 0, void 0, function* () {
if (this.ws) {
return this.ws;
}
const ws = yield this.api.websockets.audio.transcriptions.create(undefined, this.config.websocketOptions);
let isResolved = false;
return new Promise((resolve, reject) => {
ws.onopen = () => {
console.debug('[transcription] ws open');
};
ws.onmessage = data => {
var _a, _b, _c, _d;
// Trigger all registered event listeners
this.emit(api_1.WebsocketsEventType.ALL, data);
this.emit(data.event_type, data);
if (data.event_type === api_1.WebsocketsEventType.ERROR) {
this.closeWs();
if (isResolved) {
return;
}
isResolved = true;
reject(new api_1.APIError((_a = data.data) === null || _a === void 0 ? void 0 : _a.code, {
code: (_b = data.data) === null || _b === void 0 ? void 0 : _b.code,
msg: (_c = data.data) === null || _c === void 0 ? void 0 : _c.msg,
detail: data.detail,
}, (_d = data.data) === null || _d === void 0 ? void 0 : _d.msg, undefined));
return;
}
else if (data.event_type === api_1.WebsocketsEventType.TRANSCRIPTIONS_CREATED) {
resolve(ws);
isResolved = true;
}
else if (data.event_type ===
api_1.WebsocketsEventType.TRANSCRIPTIONS_MESSAGE_COMPLETED) {
this.closeWs();
}
};
ws.onerror = (error, event) => {
var _a, _b;
console.error('[transcription] WebSocket error', error, event);
this.emit('data', error);
this.emit(api_1.WebsocketsEventType.ERROR, error);
this.closeWs();
if (isResolved) {
return;
}
isResolved = true;
reject(new api_1.APIError((_a = error.data) === null || _a === void 0 ? void 0 : _a.code, error, (_b = error.data) === null || _b === void 0 ? void 0 : _b.msg, undefined));
};
ws.onclose = () => {
console.debug('[transcription] ws close');
};
this.ws = ws;
});
});
}
/**
* Listen for one or more events
* @param {string|string[]} event - Event name or array of event names
* @param {function} callback - Callback function
*/
on(event, callback) {
const events = Array.isArray(event) ? event : [event];
events.forEach(eventName => {
var _a;
if (!this.listeners.has(eventName)) {
this.listeners.set(eventName, new Set());
}
(_a = this.listeners.get(eventName)) === null || _a === void 0 ? void 0 : _a.add(callback);
});
}
/**
* Remove listener for one or more events
* @param {string|string[]} event - Event name or array of event names
* @param {function} callback - Callback function to remove
*/
off(event, callback) {
const events = Array.isArray(event) ? event : [event];
events.forEach(eventName => {
var _a;
(_a = this.listeners.get(eventName)) === null || _a === void 0 ? void 0 : _a.delete(callback);
});
}
/**
* Close WebSocket connection
* @protected
*/
closeWs() {
var _a, _b;
if (((_a = this.ws) === null || _a === void 0 ? void 0 : _a.readyState) === 1) {
(_b = this.ws) === null || _b === void 0 ? void 0 : _b.close();
}
this.ws = null;
}
/**
* Emit an event to all registered listeners
* @param {string} event - Event name
* @param {object} data - Event data
* @protected
*/
emit(event, data) {
var _a;
(_a = this.listeners.get(event)) === null || _a === void 0 ? void 0 : _a.forEach(callback => callback(data));
}
}
exports.BaseWsTranscriptionClient = BaseWsTranscriptionClient;
exports.default = BaseWsTranscriptionClient;