phonic
Version:
[](https://buildwithfern.com?utm_source=github&utm_medium=github&utm_campaign=readme&utm_source=https%3A%2F%2Fgithub.com%2FPhonic-Co%2Fphonic-node) [ • 7.75 kB
JavaScript
"use strict";
/**
* This file was auto-generated by Fern from our API Definition.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
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.ConversationsSocket = void 0;
const core = __importStar(require("../../../../core/index.js"));
const json_js_1 = require("../../../../core/json.js");
class ConversationsSocket {
constructor(args) {
this.eventHandlers = {};
this.messageBuffer = [];
this.handleOpen = () => {
var _a, _b;
this.flushMessageBuffer();
(_b = (_a = this.eventHandlers).open) === null || _b === void 0 ? void 0 : _b.call(_a);
};
this.handleMessage = (event) => {
var _a, _b;
const data = (0, json_js_1.fromJson)(event.data);
(_b = (_a = this.eventHandlers).message) === null || _b === void 0 ? void 0 : _b.call(_a, data);
};
this.handleClose = (event) => {
var _a, _b;
(_b = (_a = this.eventHandlers).close) === null || _b === void 0 ? void 0 : _b.call(_a, event);
};
this.handleError = (event) => {
var _a, _b;
const message = event.message;
(_b = (_a = this.eventHandlers).error) === null || _b === void 0 ? void 0 : _b.call(_a, new Error(message));
};
this.socket = args.socket;
this.socket.addEventListener("open", this.handleOpen);
this.socket.addEventListener("message", this.handleMessage);
this.socket.addEventListener("close", this.handleClose);
this.socket.addEventListener("error", this.handleError);
}
/** The current state of the connection; this is one of the readyState constants. */
get readyState() {
return this.socket.readyState;
}
/**
* @param event - The event to attach to.
* @param callback - The callback to run when the event is triggered.
* Usage:
* ```typescript
* this.on('open', () => {
* console.log('The websocket is open');
* });
* ```
*/
on(event, callback) {
this.eventHandlers[event] = callback;
}
sendConfig(message) {
this.sendWithBuffering(() => this.sendJson(message));
}
sendAudioChunk(message) {
this.sendWithBuffering(() => this.sendJson(message));
}
sendUpdateSystemPrompt(message) {
this.sendWithBuffering(() => this.sendJson(message));
}
sendSetExternalId(message) {
this.sendWithBuffering(() => this.sendJson(message));
}
sendSetTwilioCallSid(message) {
this.sendWithBuffering(() => this.sendJson(message));
}
sendToolCallOutput(message) {
this.sendWithBuffering(() => this.sendJson(message));
}
/** Connect to the websocket and register event handlers. */
connect() {
this.socket.reconnect();
this.socket.addEventListener("open", this.handleOpen);
this.socket.addEventListener("message", this.handleMessage);
this.socket.addEventListener("close", this.handleClose);
this.socket.addEventListener("error", this.handleError);
return this;
}
/** Close the websocket and unregister event handlers. */
close() {
this.socket.close();
this.handleClose({ code: 1000 });
this.clearMessageBuffer();
this.socket.removeEventListener("open", this.handleOpen);
this.socket.removeEventListener("message", this.handleMessage);
this.socket.removeEventListener("close", this.handleClose);
this.socket.removeEventListener("error", this.handleError);
}
/** Returns a promise that resolves when the websocket is open. */
waitForOpen() {
return __awaiter(this, void 0, void 0, function* () {
if (this.socket.readyState === core.ReconnectingWebSocket.OPEN) {
return this.socket;
}
return new Promise((resolve, reject) => {
this.socket.addEventListener("open", () => {
resolve(this.socket);
});
this.socket.addEventListener("error", (event) => {
reject(event);
});
});
});
}
/** Asserts that the websocket is open. */
assertSocketIsOpen() {
if (!this.socket) {
throw new Error("Socket is not connected.");
}
if (this.socket.readyState !== core.ReconnectingWebSocket.OPEN) {
throw new Error("Socket is not open.");
}
}
/** Send a message with buffering - if socket is not open, buffer the message. */
sendWithBuffering(sendFn) {
if (this.socket.readyState === core.ReconnectingWebSocket.OPEN) {
sendFn();
}
else {
this.messageBuffer.push(sendFn);
}
}
/** Flush all buffered messages when the socket opens. */
flushMessageBuffer() {
while (this.messageBuffer.length > 0) {
const sendFn = this.messageBuffer.shift();
if (sendFn) {
try {
sendFn();
}
catch (error) {
console.error("Error sending buffered message:", error);
}
}
}
}
/** Clear all buffered messages. */
clearMessageBuffer() {
this.messageBuffer = [];
}
/** Send a binary payload to the websocket. */
sendBinary(payload) {
this.socket.send(payload);
}
/** Send a JSON payload to the websocket. */
sendJson(payload) {
const jsonPayload = (0, json_js_1.toJson)(payload);
this.socket.send(jsonPayload);
}
}
exports.ConversationsSocket = ConversationsSocket;