### Getting Started with FreeSwitchClient in TypeScript Source: https://github.com/shimaore/esl-lite/blob/main/README.md This example demonstrates the basic usage of the FreeSwitchClient from the esl-lite package. It shows how to instantiate the client, listen for 'CHANNEL_CREATE' events, and send commands like 'answer' and 'originate'. It also illustrates handling custom events. ```typescript import { FreeSwitchClient } from 'esl-lite' import pino from 'pino' const logger = pino.default() const client = new FreeSwitchClient({ logger }) client.on('CHANNEL_CREATE', (msg) => { logger.info( msg.body.data, 'new call') const uuid = msg.body.uniqueID if (uuid) { // Send command to a specific channel! client.command_uuid(uuid, 'answer', '', 4000).catch( logger.error ) } }) // Send generic commands await client.bgapi('originate sofia/profile/sip:destination@host &park') // For CUSTOM messages with Event-Subclass, use the `.custom` event-emitter. client.custom.on('conference::maintenance', (msg) => { ... }) ``` -------------------------------- ### STARTUP Event Source: https://github.com/shimaore/esl-lite/blob/main/docs/types/response.FreeSwitchPublicResponseEvents.html Handles the event when the system starts up. ```APIDOC ## STARTUP ### Description Handles the event when the system starts up. ### Method N/A (Event Handler) ### Endpoint N/A (Event Handler) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** (FreeSwitchEventData) - The event data associated with startup. ### Request Example ```json { "event": "STARTUP", "data": { ... FreeSwitchEventData ... } } ``` ### Response #### Success Response (200) N/A (Event Handler) #### Response Example N/A (Event Handler) ``` -------------------------------- ### RECORD_START Event Source: https://github.com/shimaore/esl-lite/blob/main/docs/types/response.FreeSwitchPublicResponseEvents.html Handles the event when recording starts. ```APIDOC ## RECORD_START ### Description Handles the event when recording starts. ### Method N/A (Event Handler) ### Endpoint N/A (Event Handler) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** (FreeSwitchEventData) - The event data associated with recording start. ### Request Example ```json { "event": "RECORD_START", "data": { ... FreeSwitchEventData ... } } ``` ### Response #### Success Response (200) N/A (Event Handler) #### Response Example N/A (Event Handler) ``` -------------------------------- ### Install esl-lite using yarn Source: https://github.com/shimaore/esl-lite/blob/main/README.md This snippet demonstrates how to install the esl-lite package using yarn, another popular JavaScript package manager. This command achieves the same outcome as the npm installation. ```bash yarn add esl-lite ``` -------------------------------- ### Install esl-lite using npm or yarn Source: https://github.com/shimaore/esl-lite/blob/main/docs/index.html Instructions for installing the esl-lite package using either npm or yarn package managers. This is the first step to using the library in your Node.js project. ```bash npm i esl-lite ``` ```bash yarn add esl-lite ``` -------------------------------- ### Install esl-lite using npm Source: https://github.com/shimaore/esl-lite/blob/main/README.md This snippet shows how to install the esl-lite package using npm, the Node Package Manager. This is the first step to using the library in a Node.js project. ```bash npm i esl-lite ``` -------------------------------- ### FreeSwitchSocket Methods Source: https://github.com/shimaore/esl-lite/blob/main/docs/classes/socket.FreeSwitchSocket.html Provides methods to manage the connection to the FreeSWITCH Event Socket, including starting the connection and closing it. ```APIDOC ## connect() ### Description Starts connecting to FreeSwitch and handles automatic reconnection if the connection is lost. ### Method GET ### Endpoint N/A (Instance method) ### Parameters None ### Request Example ```javascript // Assuming 'socket' is an instance of FreeSwitchSocket socket.connect(); ``` ### Response #### Success Response (200) * **AsyncIterable** - An asynchronous iterable that yields socket objects upon successful connection or reconnection. #### Response Example ```javascript // Example of consuming the AsyncIterable (async () => { for await (const socket of socket.connect()) { console.log('Connected to FreeSwitch!'); // Handle socket events here } })(); ``` ``` ```APIDOC ## end() ### Description Closes the current connection to FreeSwitch and stops any ongoing attempts to reconnect. ### Method DELETE ### Endpoint N/A (Instance method) ### Parameters None ### Request Example ```javascript // Assuming 'socket' is an instance of FreeSwitchSocket socket.end(); ``` ### Response #### Success Response (200) * **void** - This method does not return any value. #### Response Example (No return value) ``` -------------------------------- ### Execute Synchronous Channel Commands with esl-lite Source: https://context7.com/shimaore/esl-lite/llms.txt Illustrates how to execute commands synchronously on a specific FreeSwitch channel using its UUID via the `command_uuid` method. Examples include answering a call, playing a message, and bridging to another extension, with checks for command success or failure. ```typescript import { FreeSwitchClient } from 'esl-lite' import pino from 'pino' const logger = pino.default() const client = new FreeSwitchClient({ logger }) // Listen for new calls client.on('CHANNEL_CREATE', async (msg) => { const uuid = msg.body.uniqueID if (!uuid) return // Answer the call (4 second timeout) const answerResult = await client.command_uuid(uuid, 'answer', '', 4000) if (answerResult instanceof Error) { logger.error({ err: answerResult, uuid }, 'Failed to answer') return } // Play a welcome message const playResult = await client.command_uuid( uuid, 'playback', '/usr/share/freeswitch/sounds/welcome.wav', 30000 ) // Check response for success/failure const response = playResult instanceof Error ? null : playResult.body.response if (typeof response === 'string' && response.startsWith('+')) { logger.info({ uuid }, 'Playback completed successfully') } // Bridge to another extension await client.command_uuid(uuid, 'bridge', 'user/1001@default', 60000) }) ``` -------------------------------- ### Handle Playback Start Events in TypeScript Source: https://github.com/shimaore/esl-lite/blob/main/docs/types/response.FreeSwitchPublicResponseEvents.html This handler processes 'PLAYBACK_START' events, indicating that an audio playback has begun. It takes FreeSwitchEventData as input and returns void. ```typescript PLAYBACK_START: (data: FreeSwitchEventData) => void; // Defined in src/response.ts:1188 ``` -------------------------------- ### Execute Background API Commands with esl-lite Source: https://context7.com/shimaore/esl-lite/llms.txt Shows how to execute FreeSwitch API commands in the background using the `bgapi` method. It includes examples for checking Sofia status, originating a call, and reloading XML configuration, demonstrating error handling and result processing with a specified timeout. ```typescript import { FreeSwitchClient, FreeSwitchTimeoutError, FreeSwitchFailedCommandError } from 'esl-lite' import pino from 'pino' const logger = pino.default() const client = new FreeSwitchClient({ logger }) // Check Sofia status with 5-second timeout const sofiaResult = await client.bgapi('sofia status', 5000) if (sofiaResult instanceof Error) { logger.error({ err: sofiaResult }, 'Failed to get sofia status') } else { logger.info({ response: sofiaResult.body.response }, 'Sofia status received') } // Originate a call const originateResult = await client.bgapi( 'originate sofia/gateway/my-gateway/15551234567 &bridge(sofia/internal/1000@local)', 30000 ) if (originateResult instanceof Error) { logger.error({ err: originateResult }, 'Originate failed') } else { logger.info({ uuid: originateResult.body.uniqueID }, 'Call originated') } // Reload XML configuration const reloadResult = await client.bgapi('reloadxml', 2000) if (!(reloadResult instanceof Error)) { logger.info('XML configuration reloaded') ``` -------------------------------- ### Handle Custom Events with FreeSwitchClient Source: https://github.com/shimaore/esl-lite/blob/main/docs/classes/client.FreeSwitchClient.html Shows how to subscribe to custom events emitted by the FreeSwitchClient. This example specifically listens for the 'conference::maintenance' event and logs its data. ```typescript this.custom.on('conference::maintenance', (data) => {}) ``` -------------------------------- ### Handle Media Bug Start Events in TypeScript Source: https://github.com/shimaore/esl-lite/blob/main/docs/types/response.FreeSwitchPublicResponseEvents.html This handler processes 'MEDIA_BUG_START' events, indicating the beginning of media debugging or monitoring. It takes FreeSwitchEventData as input and returns void. ```typescript MEDIA_BUG_START: (data: FreeSwitchEventData) => void; // Defined in src/response.ts:1193 ``` -------------------------------- ### Enable Logging - TypeScript Source: https://github.com/shimaore/esl-lite/blob/main/docs/classes/client.FreeSwitchClient.html Activates logging on the socket connection and sets the desired log level. The example demonstrates how to enable logging and subscribe to log events. ```typescript client.log(7, timeout); client.logs.on('log', (data) => { ... }); ``` -------------------------------- ### FreeSwitchEventEmitter Constructor Example Source: https://github.com/shimaore/esl-lite/blob/main/docs/classes/event-emitter.FreeSwitchEventEmitter.html Demonstrates how to construct a new FreeSwitchEventEmitter instance with specific event types and handlers. This constructor is generic and can be used to create type-safe event emitters. ```typescript const ev = new FreeSwitchEventEmitter<'ping',{ ping: () => console.log('ping') }>() ``` -------------------------------- ### Capture Stack Trace using Error.captureStackTrace Source: https://github.com/shimaore/esl-lite/blob/main/docs/classes/raw-event.FreeSwitchDisconnectNotice.html This JavaScript example demonstrates how to use the static `Error.captureStackTrace` method to create a `.stack` property on a target object. It allows for custom stack trace generation, optionally omitting frames above a specified constructor. ```javascript const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` ```javascript function a() { b(); } function b() { c(); } function c() { const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; Error.captureStackTrace(error, b); throw error; } a(); ``` -------------------------------- ### Initialize FreeSwitchClient and handle events Source: https://github.com/shimaore/esl-lite/blob/main/docs/index.html Demonstrates how to initialize the FreeSwitchClient with a logger, subscribe to 'CHANNEL_CREATE' events, log new call details, and send an 'answer' command to a specific channel. It also shows how to send a generic 'originate' command using bgapi and handle custom events. ```typescript import { FreeSwitchClient } from 'esl-lite' import pino from 'pino' const logger = pino.default() const client = new FreeSwitchClient({ logger }) client.on('CHANNEL_CREATE', (msg) => { logger.info( msg.body.data, 'new call') const uuid = msg.body.uniqueID if (uuid) { // Send command to a specific channel! client.command_uuid(uuid, 'answer', '', 4000).catch( logger.error ) } }) // Send generic commands await client.bgapi('originate sofia/profile/sip:destination@host &park') // For CUSTOM messages with Event-Subclass, use the `.custom` event-emitter. client.custom.on('conference::maintenance', (msg) => {   … }) ``` -------------------------------- ### Initialize Theme and Show App (JavaScript) Source: https://github.com/shimaore/esl-lite/blob/main/docs/classes/headers.Headers.html This snippet initializes the application's theme from local storage and ensures the app is displayed after a short delay. It handles cases where the app might not be immediately available. ```javascript document.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Set Theme and Show Page (JavaScript) Source: https://github.com/shimaore/esl-lite/blob/main/docs/functions/event-names.isEventName.html Initializes the theme from local storage and displays the application page after a short delay. It handles cases where the application might not be immediately ready. ```javascript esl-litedocument.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Initialize FreeSwitchClient and Execute bgapi Command Source: https://github.com/shimaore/esl-lite/blob/main/docs/classes/response.FreeSwitchResponse.html This snippet demonstrates how to initialize a FreeSwitchClient with a logger and then execute a 'reloadxml' command using the bgapi method. It specifies a timeout of 1000 milliseconds for the command. ```typescript const client = new FreeSwitchClient({ logger: pino.default() }) await client.bgapi('reloadxml', 1_000) ``` -------------------------------- ### Headers Class: Get Method (TypeScript) Source: https://github.com/shimaore/esl-lite/blob/main/docs/classes/headers.Headers.html Retrieves the value of a specified header from the Headers instance. Returns undefined if the header is not present. ```typescript get(name: string): string | undefined ``` -------------------------------- ### Initialize FreeSwitchClient with esl-lite Source: https://context7.com/shimaore/esl-lite/llms.txt Demonstrates how to create an instance of the FreeSwitchClient. It shows initialization with default settings (localhost, default password) and with custom host, port, and password. The client automatically connects on the next tick. ```typescript import { FreeSwitchClient } from 'esl-lite' import pino from 'pino' // Create logger instance const logger = pino.default() // Create client with defaults (localhost:8021, password: ClueCon) const client = new FreeSwitchClient({ logger }) // Create client with custom connection settings const customClient = new FreeSwitchClient({ host: '192.168.1.100', port: 8021, password: 'MySecretPassword', logger: logger }) // Client automatically connects on next tick // No need to call connect() manually ``` -------------------------------- ### EslLite Constructor Source: https://github.com/shimaore/esl-lite/blob/main/docs/classes/lite.EslLite.html Creates a new client instance to connect to a FreeSWITCH Event Socket. ```APIDOC ## new EslLite(options: { host: string; logger: Logger; port: number }) ### Description Create a new client that will attempt to connect to a FreeSWITCH Event Socket. ### Method CONSTRUCTOR ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "options": { "host": "your_freeswitch_host", "logger": "your_logger_instance", "port": 8021 } } ``` ### Response #### Success Response (200) * **EslLite** (object) - A new instance of the EslLite client. #### Response Example ```json { "instance": "EslLite object" } ``` ``` -------------------------------- ### Static prepareStackTrace Method Source: https://github.com/shimaore/esl-lite/blob/main/docs/classes/raw-event.FreeSwitchUnexpectedApiResponse.html Allows for customization of stack trace formatting. ```APIDOC ## Static prepareStackTrace Method ### Description Customizes the formatting of stack traces. This method is typically used internally by the JavaScript runtime or for advanced debugging scenarios. ### Method Static ### Endpoint N/A (This is a static method, not an HTTP endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript // Example usage (conceptual, as this method is usually called internally): // Static.prepareStackTrace(error, stackTraces); ``` ### Response #### Success Response - **any** - The formatted stack trace. The exact format depends on the implementation. #### Response Example ```json { "formattedStackTrace": "Error: Something went wrong\n at foo (file.js:1:1)\n at bar (file.js:2:2)" } ``` ### See [https://v8.dev/docs/stack-trace-api#customizing-stack-traces](https://v8.dev/docs/stack-trace-api#customizing-stack-traces) ``` -------------------------------- ### Set Log Level in TypeScript Source: https://github.com/shimaore/esl-lite/blob/main/docs/classes/response.FreeSwitchResponse.html Enables logging on the socket by setting a specific log level. It requires a log level and a timeout. Example usage shows how to set the level and attach a listener for log events. ```typescript log(level: number, timeout: number): SendResult[] ``` -------------------------------- ### Instantiate and Use FreeSwitchClient Source: https://github.com/shimaore/esl-lite/blob/main/docs/classes/client.FreeSwitchClient.html Demonstrates how to create a new FreeSwitchClient instance with a logger and execute a background API command. It logs the response of the 'sofia status' command. ```typescript const client = new FreeSwitchClient({ logger: pino.default() }) const res = await client.bgapi('sofia status', 1000) console.log('sofia status is', res) ``` -------------------------------- ### bgapi Source: https://github.com/shimaore/esl-lite/blob/main/docs/classes/client.FreeSwitchClient.html Executes an API command in the background on FreeSWITCH. ```APIDOC ## POST /api/bgapi ### Description Executes an API command in the background on FreeSWITCH and returns a response. ### Method POST ### Endpoint `/api/bgapi` ### Parameters #### Query Parameters * **command** (string) - Required - The API command to execute. * **timeout** (number) - Optional - The timeout in milliseconds for the command. ### Request Body (Not applicable for this endpoint, command is passed as a query parameter) ### Request Example ```bash POST /api/bgapi?command=sofia%20status&timeout=1000 ``` ### Response #### Success Response (200) * **body** (string) - The response from the FreeSWITCH API command. #### Response Example ```json { "body": "[...]" } ``` ``` -------------------------------- ### FreeSwitchClient Constructor Source: https://context7.com/shimaore/esl-lite/llms.txt Initializes the FreeSwitchClient, which automatically connects to the Event Socket and handles reconnections. It requires a pino logger instance and supports optional host, port, and password configuration. ```APIDOC ## FreeSwitchClient Constructor ### Description The main entry point for connecting to FreeSwitch's Event Socket. Creates a client that automatically connects and handles reconnection. Requires a pino logger instance for structured logging. Supports optional host, port, and password configuration with sensible defaults (127.0.0.1:8021, password: ClueCon). ### Method `new FreeSwitchClient(options: { host?: string; port?: number; password?: string; logger: pino.Logger })` ### Parameters #### Constructor Options - **host** (string) - Optional - The hostname or IP address of the FreeSwitch server. Defaults to '127.0.0.1'. - **port** (number) - Optional - The port for the Event Socket. Defaults to 8021. - **password** (string) - Optional - The password for authenticating with the Event Socket. Defaults to 'ClueCon'. - **logger** (pino.Logger) - Required - An instance of a pino logger for structured logging. ### Request Example ```typescript import { FreeSwitchClient } from 'esl-lite' import pino from 'pino' // Create logger instance const logger = pino.default() // Create client with defaults (localhost:8021, password: ClueCon) const client = new FreeSwitchClient({ logger }) // Create client with custom connection settings const customClient = new FreeSwitchClient({ host: '192.168.1.100', port: 8021, password: 'MySecretPassword', logger: logger }) // Client automatically connects on next tick // No need to call connect() manually ``` ``` -------------------------------- ### Configure Logging for FreeSwitchClient Source: https://github.com/shimaore/esl-lite/blob/main/docs/classes/client.FreeSwitchClient.html Illustrates how to enable and receive log events from the FreeSwitchClient. Note that you must call `client.log()` beforehand to specify the desired log level. ```typescript client.log() // Then you can listen for log events: client.logs.on('log', (data) => { console.log(data); }); ``` -------------------------------- ### FreeSwitchSocket Constructor Source: https://github.com/shimaore/esl-lite/blob/main/docs/classes/socket.FreeSwitchSocket.html Initializes a new FreeSwitchSocket client to connect to a FreeSWITCH Event Socket. It allows configuration of host, port, logger, and retry timeouts. ```APIDOC ## new FreeSwitchSocket(options) ### Description Create a new client that will attempt to connect to a FreeSWITCH Event Socket. ### Method CONSTRUCTOR ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **options** (object) - Required - Configuration options for the socket connection. * **host** (string) - Optional - The hostname or IP address of the FreeSWITCH server. Defaults to `127.0.0.1`. * **logger** (Logger) - Optional - A logger object for outputting messages. Defaults to `console`. * **maxRetryTimeout** (number) - Optional - The maximum time in milliseconds to wait between reconnection attempts. * **port** (number) - Optional - The port number for the Event Socket connection. Defaults to `8021`. ### Request Example ```json { "host": "127.0.0.1", "port": 8021, "logger": console, "maxRetryTimeout": 5000 } ``` ### Response #### Success Response (200) This constructor does not return a value directly, but initializes an instance of FreeSwitchSocket. #### Response Example (Instance of FreeSwitchSocket) ``` -------------------------------- ### prepareStackTrace Method Source: https://github.com/shimaore/esl-lite/blob/main/docs/classes/raw-event.FreeSwitchMissingContentTypeError.html Allows for customizing stack traces by providing an error object and an array of call sites. ```APIDOC ## prepareStackTrace ### Description Customizes stack traces by providing an error object and an array of call sites. This method is inherited from the Error class. ### Method N/A (This appears to be a static method or a function definition within a class context, not a typical HTTP endpoint.) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **any** - An array of stack trace elements. #### Response Example ```json [ { "fileName": "", "lineNumber": , "columnNumber": , "methodName": "" } ] ``` ### See [https://v8.dev/docs/stack-trace-api#customizing-stack-traces](https://v8.dev/docs/stack-trace-api#customizing-stack-traces) ``` -------------------------------- ### Error.prepareStackTrace Source: https://github.com/shimaore/esl-lite/blob/main/docs/classes/raw-event.FreeSwitchUnhandledContentTypeError.html Allows customization of the stack trace format. This method is inherited from the base Error class. ```APIDOC ## Error.prepareStackTrace ### Description Allows customization of the stack trace format. This method is inherited from the base Error class. ### Method `any` ### Endpoint N/A (Internal method of Error class) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "err": "Error object", "stackTraces": "Array of CallSite objects" } ``` ### Response #### Success Response (200) - **any** - The formatted stack trace. #### Response Example ```json [ "Formatted stack trace line 1", "Formatted stack trace line 2" ] ``` ### See [https://v8.dev/docs/stack-trace-api#customizing-stack-traces](https://v8.dev/docs/stack-trace-api#customizing-stack-traces) ``` -------------------------------- ### Event Handling API Source: https://github.com/shimaore/esl-lite/blob/main/docs/classes/client.FreeSwitchClient.html Endpoints for registering and managing event listeners. ```APIDOC ## POST /api/on ### Description Register a new callback for the named event. The callback is called every time the event is emitted. ### Method POST ### Endpoint /api/on ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **event** (string) - Required - The name of the event to listen for. - **handler** (function) - Required - The callback function to execute when the event is emitted. ### Request Example ```json { "event": "CHANNEL_CREATE", "handler": "function(data) { console.log(data); }" } ``` ### Response #### Success Response (200) - **result** (array) - An array containing the result of the operation. #### Response Example ```json { "result": [{"message": "OK"}] } ``` ## POST /api/once ### Description Register a new callback for the named event. The callback is only called the first time the event is emitted. ### Method POST ### Endpoint /api/once ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **event** (string) - Required - The name of the event to listen for. - **handler** (function) - Required - The callback function to execute when the event is emitted. ### Request Example ```json { "event": "CHANNEL_DESTROY", "handler": "function(data) { console.log('Call ended:', data); }" } ``` ### Response #### Success Response (200) - **result** (array) - An array containing the result of the operation. #### Response Example ```json { "result": [{"message": "OK"}] } ``` ## POST /api/onceAsync ### Description Returns a Promise that is resolved the next time the named event is emitted. ### Method POST ### Endpoint /api/onceAsync ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **event** (string) - Required - The name of the event to listen for. ### Request Example ```json { "event": "CUSTOM_MESSAGE" } ``` ### Response #### Success Response (200) - **result** (Promise) - A Promise that resolves with the event parameters. #### Response Example ```json { "result": "Promise resolved with event data" } ``` ``` -------------------------------- ### FreeSwitchParser Constructor Source: https://github.com/shimaore/esl-lite/blob/main/docs/functions/parser.FreeSwitchParser.html This section details the constructor for the FreeSwitchParser class. It takes a socket and a logger as parameters and returns an async generator that yields parsed event data or errors. ```APIDOC ## FreeSwitchParser Constructor ### Description Low-level event socket parser. Parses headers and collects (but does not parse) an event's body. ### Method Constructor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **socket** (AsyncIterable>) - The asynchronous iterable representing the socket connection. * **logger** (Logger) - The logger instance to use for logging. ### Returns AsyncGenerator<[FreeSwitchParserNonEmptyBufferAtEndError](../classes/parser.FreeSwitchParserNonEmptyBufferAtEndError.html) | [ProcessorInput](../types/parser.ProcessorInput.html)> ### Request Example ```javascript // Example usage (conceptual) const parser = new FreeSwitchParser(socket, logger); for await (const eventData of parser) { // Process eventData } ``` ### Response #### Success Response (200) This constructor does not return a direct response in the typical HTTP sense. It initializes the parser. #### Response Example N/A ``` -------------------------------- ### Logging API Source: https://github.com/shimaore/esl-lite/blob/main/docs/classes/client.FreeSwitchClient.html Endpoints for managing logging on the socket connection. ```APIDOC ## POST /api/log ### Description Enable logging on the socket, setting the log level. ### Method POST ### Endpoint /api/log ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **level** (number) - Required - The desired log level. - **timeout** (number) - Required - The timeout for the operation. ### Request Example ```json { "level": 7, "timeout": 3000 } ``` ### Response #### Success Response (200) - **sendResult** (object) - The result of the send operation. #### Response Example ```json { "sendResult": { "message": "OK" } } ``` ## DELETE /api/nolog ### Description Disable logging on the socket. ### Method DELETE ### Endpoint /api/nolog ### Parameters #### Path Parameters None #### Query Parameters - **timeout** (number) - Required - The timeout for the operation. ### Request Example ```json { "timeout": 3000 } ``` ### Response #### Success Response (200) - **sendResult** (object) - The result of the send operation. #### Response Example ```json { "sendResult": { "message": "OK" } } ``` ``` -------------------------------- ### EslLite Methods Source: https://github.com/shimaore/esl-lite/blob/main/docs/classes/lite.EslLite.html Documentation for the methods available on the EslLite class. ```APIDOC ## connect() ### Description Initiates a connection to the FreeSWITCH Event Socket and returns an asynchronous iterable of events. ### Method GET ### Endpoint /connect ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "action": "connect" } ``` ### Response #### Success Response (200) * **AsyncIterable** - An asynchronous iterable yielding processed events or errors. #### Response Example ```json { "event": "some_event_data" } ``` ``` ```APIDOC ## end() ### Description Closes the connection to the FreeSWITCH Event Socket. ### Method POST ### Endpoint /end ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "action": "end" } ``` ### Response #### Success Response (200) * **void** - Indicates the connection has been closed. #### Response Example ```json { "status": "disconnected" } ``` ``` ```APIDOC ## write(request: WriteRequest) ### Description Sends a write request to the FreeSWITCH Event Socket. ### Method POST ### Endpoint /write ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **request** (WriteRequest) - Required - The write request object to be sent. ### Request Example ```json { "action": "write", "command": "api", "args": "status" } ``` ### Response #### Success Response (200) * **void** - Indicates the write operation was successful. #### Response Example ```json { "status": "sent" } ``` ``` -------------------------------- ### Async Channel Application Execution with execute_uuid Source: https://context7.com/shimaore/esl-lite/llms.txt This snippet illustrates how to execute an application on a FreeSwitch channel asynchronously using the execute_uuid method. It's ideal for 'fire-and-forget' operations or when completion is handled via CHANNEL_EXECUTE_COMPLETE events. The method takes the channel UUID, application name, application arguments, optional options, and a timeout. Requires 'esl-lite' and 'pino'. ```typescript import { FreeSwitchClient } from 'esl-lite' import pino from 'pino' const logger = pino.default() const client = new FreeSwitchClient({ logger }) const uuid = '550e8400-e29b-41d4-a716-446655440000' // Execute playback without waiting for completion const result = await client.execute_uuid( uuid, 'playback', '/sounds/music-on-hold.wav', { 'event-uuid': 'my-custom-event-id', // Track this execution 'loops': 10, // Repeat 10 times }, 5000 ) // Execute with hold-bleg option (for bridged calls) await client.execute_uuid( uuid, 'playback', '/sounds/announcement.wav', { 'hold-bleg': true }, 5000 ) // Listen for completion client.on('CHANNEL_EXECUTE_COMPLETE', (msg) => { if (msg.body.applicationUUID === 'my-custom-event-id') { logger.info('Playback completed') } }) ``` -------------------------------- ### Subscribe to FreeSwitch Events with on() Method Source: https://context7.com/shimaore/esl-lite/llms.txt This snippet demonstrates how to subscribe to standard FreeSwitch events like CHANNEL_CREATE, CHANNEL_HANGUP_COMPLETE, DTMF, and ALL using the typed event emitter's on() method. Events are automatically registered with FreeSwitch upon listener addition. It requires the 'esl-lite' and 'pino' libraries. ```typescript import { FreeSwitchClient } from 'esl-lite' import pino from 'pino' const logger = pino.default() const client = new FreeSwitchClient({ logger }) // Monitor new channels client.on('CHANNEL_CREATE', (msg) => { logger.info({ uuid: msg.body.uniqueID, caller: msg.body.data['Caller-Caller-ID-Number'], destination: msg.body.data['Caller-Destination-Number'] }, 'New channel created') }) // Monitor hangups client.on('CHANNEL_HANGUP_COMPLETE', (msg) => { logger.info({ uuid: msg.body.uniqueID, cause: msg.body.data['Hangup-Cause'], duration: msg.body.data['variable_billsec'] }, 'Call ended') }) // Monitor DTMF input client.on('DTMF', (msg) => { logger.info({ uuid: msg.body.uniqueID, digit: msg.body.data['DTMF-Digit'], duration: msg.body.data['DTMF-Duration'] }, 'DTMF received') }) // Receive ALL events (useful for debugging) client.on('ALL', (msg) => { logger.debug({ event: msg.body.eventName }, 'Event received') }) ``` -------------------------------- ### FreeSwitchFailedCommandError Class Source: https://github.com/shimaore/esl-lite/blob/main/docs/classes/response.FreeSwitchFailedCommandError.html Details about the FreeSwitchFailedCommandError class, including its constructor, properties, and inherited methods. ```APIDOC ## Class FreeSwitchFailedCommandError Error: command failed ### Hierarchy * Error * FreeSwitchFailedCommandError ### Constructors #### constructor(command: string, response: string) * **Parameters** * `command` (string) - The command that failed. * `response` (string) - The response received from FreeSwitch. * **Returns** FreeSwitchFailedCommandError * Overrides Error.constructor ### Properties #### `Readonly`command (string) The command that failed. #### `Readonly`response (string) The response received from FreeSwitch. #### name (string) "FreeSwitchFailedCommandError" * Overrides Error.name ### Methods #### `Static`captureStackTrace(targetObject: object, constructorOpt?: Function): void Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. * **Parameters** * `targetObject` (object) - The object to attach the stack trace to. * `constructorOpt` (Function) - Optional. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. * **Returns** void * Inherited from Error.captureStackTrace #### `Static`isError(error: unknown): error is Error Indicates whether the argument provided is a built-in Error instance or not. * **Parameters** * `error` (unknown) - The value to check. * **Returns** error is Error * Inherited from Error.isError ``` -------------------------------- ### PRIVATE_COMMAND Event Source: https://github.com/shimaore/esl-lite/blob/main/docs/types/response.FreeSwitchPublicResponseEvents.html Handles a private command event. ```APIDOC ## PRIVATE_COMMAND ### Description Handles a private command event. ### Method N/A (Event Handler) ### Endpoint N/A (Event Handler) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** (FreeSwitchEventData) - The event data associated with the private command. ### Request Example ```json { "event": "PRIVATE_COMMAND", "data": { ... FreeSwitchEventData ... } } ``` ### Response #### Success Response (200) N/A (Event Handler) #### Response Example N/A (Event Handler) ``` -------------------------------- ### RECV_INFO Event Source: https://github.com/shimaore/esl-lite/blob/main/docs/types/response.FreeSwitchPublicResponseEvents.html Handles the event when INFO is received. ```APIDOC ## RECV_INFO ### Description Handles the event when INFO is received. ### Method N/A (Event Handler) ### Endpoint N/A (Event Handler) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** (FreeSwitchEventData) - The event data associated with receiving INFO. ### Request Example ```json { "event": "RECV_INFO", "data": { ... FreeSwitchEventData ... } } ``` ### Response #### Success Response (200) N/A (Event Handler) #### Response Example N/A (Event Handler) ``` -------------------------------- ### bgapi - Background API Command Source: https://context7.com/shimaore/esl-lite/llms.txt Executes a FreeSwitch API command in the background and awaits its completion. This is the recommended method for running FreeSwitch API commands, returning the command result or an error object. ```APIDOC ## bgapi - Background API Command ### Description Executes a FreeSwitch API command in the background and awaits its completion. Returns the command result or an error object. The timeout parameter should encompass both job submission and command completion time. This is the recommended method for running FreeSwitch API commands. ### Method `bgapi(command: string, timeoutMs: number): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **command** (string) - Required - The FreeSwitch API command to execute. - **timeoutMs** (number) - Required - The maximum time in milliseconds to wait for the command to complete. ### Request Example ```typescript import { FreeSwitchClient, FreeSwitchTimeoutError, FreeSwitchFailedCommandError } from 'esl-lite' import pino from 'pino' const logger = pino.default() const client = new FreeSwitchClient({ logger }) // Check Sofia status with 5-second timeout const sofiaResult = await client.bgapi('sofia status', 5000) if (sofiaResult instanceof Error) { logger.error({ err: sofiaResult }, 'Failed to get sofia status') } else { logger.info({ response: sofiaResult.body.response }, 'Sofia status received') } // Originate a call const originateResult = await client.bgapi( 'originate sofia/gateway/my-gateway/15551234567 &bridge(sofia/internal/1000@local)', 30000 ) if (originateResult instanceof Error) { logger.error({ err: originateResult }, 'Originate failed') } else { logger.info({ uuid: originateResult.body.uniqueID }, 'Call originated') } // Reload XML configuration const reloadResult = await client.bgapi('reloadxml', 2000) if (!(reloadResult instanceof Error)) { logger.info('XML configuration reloaded') } ``` ### Response #### Success Response (200) - **body** (object) - Contains the response from the FreeSwitch API command. - **response** (string) - The raw response string from FreeSwitch. - **uniqueID** (string) - The unique ID associated with the command execution (if applicable). #### Error Response - **Error** (Error) - An error object if the command fails or times out. This could be a `FreeSwitchTimeoutError` or `FreeSwitchFailedCommandError`. #### Response Example ```json { "body": { "response": "+OK", "uniqueID": "some-uuid" } } ``` ``` -------------------------------- ### SEND_INFO Event Source: https://github.com/shimaore/esl-lite/blob/main/docs/types/response.FreeSwitchPublicResponseEvents.html Handles the event when INFO is sent. ```APIDOC ## SEND_INFO ### Description Handles the event when INFO is sent. ### Method N/A (Event Handler) ### Endpoint N/A (Event Handler) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** (FreeSwitchEventData) - The event data associated with sending INFO. ### Request Example ```json { "event": "SEND_INFO", "data": { ... FreeSwitchEventData ... } } ``` ### Response #### Success Response (200) N/A (Event Handler) #### Response Example N/A (Event Handler) ``` -------------------------------- ### prepareStackTrace Method Source: https://github.com/shimaore/esl-lite/blob/main/docs/classes/raw-event.FreeSwitchMissingEventNameError.html Allows for customizing stack traces. This method is inherited from Error.prepareStackTrace. ```APIDOC ## prepareStackTrace Method ### Description Allows for customizing stack traces. This method is inherited from Error.prepareStackTrace. ### Method (Not specified, likely a static method or part of an Error class) ### Endpoint (Not applicable, this is a method within a class/object) ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Request Example (Not applicable for this method) ### Response #### Success Response (200) - **any**: The formatted stack trace. #### Response Example (Not applicable for this method, return type is 'any') ### See [https://v8.dev/docs/stack-trace-api#customizing-stack-traces](https://v8.dev/docs/stack-trace-api#customizing-stack-traces) ``` -------------------------------- ### bgapi Source: https://github.com/shimaore/esl-lite/blob/main/docs/classes/client.FreeSwitchClient.html Sends an API command in the background to FreeSwitch and awaits its result. Handles various potential errors during command execution. ```APIDOC ## POST /bgapi ### Description Send an API command in the background. Await the command's result. `bgapi` will return an error if the job submission fails. It will not return an error if the background job itself failed. The response from the background job will be stored in the `.body.response` field of the return value. The `timeout` parameter should encompass job submission and the command completion. This method is not expected to throw / return a rejected Promise. ### Method POST ### Endpoint `/bgapi` ### Parameters #### Query Parameters - **command** (string) - Required - The API command to execute. - **timeout** (number) - Required - The timeout in milliseconds for the command execution. ### Request Example ```json { "command": "uuid_send_message", "timeout": 5000 } ``` ### Response #### Success Response (200) - **body** (object) - The response body containing the result of the command execution. - **response** (object | null) - The actual response from the background job, or null if no response. #### Error Response - **error** (object) - Details about the error if the job submission fails. - **message** (string) - A description of the error. - **type** (string) - The type of error (e.g., `FreeSwitchAbortError`, `FreeSwitchTimeoutError`). ### Response Example (Success) ```json { "body": { "response": { "message": "OK" } } } ``` ### Response Example (Error) ```json { "error": { "message": "Job submission failed.", "type": "FreeSwitchFailedCommandError" } } ``` ### Inheritance Inherited from [FreeSwitchResponse](response.FreeSwitchResponse.html).[bgapi](response.FreeSwitchResponse.html#bgapi) * Defined in src/response.ts:56 ``` -------------------------------- ### Connect to FreeSwitch Event Socket (TypeScript) Source: https://github.com/shimaore/esl-lite/blob/main/docs/classes/response.FreeSwitchResponse.html Establishes a connection to the FreeSwitch Event Socket. This method returns a Promise that resolves when the connection is successfully established. ```typescript connect(): Promise ``` -------------------------------- ### FreeSwitchTimeoutError Class Source: https://github.com/shimaore/esl-lite/blob/main/docs/classes/response.FreeSwitchTimeoutError.html Details about the FreeSwitchTimeoutError class, including its constructor, properties, and inherited methods. ```APIDOC ## Class FreeSwitchTimeoutError ### Description Represents a timeout error that occurred within the FreeSwitch communication. ### Hierarchy * Error * FreeSwitchTimeoutError ### Constructors #### constructor(timeout: number, text: string) * **Parameters** * `timeout` (number) - The timeout duration in milliseconds. * `text` (string) - A descriptive message for the error. * **Returns** FreeSwitchTimeoutError * **Overrides** Error.constructor ### Properties * **`Optional`cause** (unknown) - Inherited from Error.cause. * **message** (string) - Inherited from Error.message. The error message. * **name** (string) - Set to "FreeSwitchTimeoutError". Overrides Error.name. * **`Optional`stack** (string) - Inherited from Error.stack. The stack trace. * **`Readonly`text** (string) - The descriptive text associated with the timeout. * **`Readonly`timeout** (number) - The timeout duration that was exceeded. * **`Static`stackTraceLimit** (number) - Inherited from Error.stackTraceLimit. Specifies the number of stack frames collected by a stack trace. ### Methods #### `Static`captureStackTrace(targetObject: object, constructorOpt?: Function) * **Description**: Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. The optional `constructorOpt` argument can be used to omit frames from the stack trace. * **Parameters** * `targetObject` (object) - The object to attach the stack trace to. * `constructorOpt` (Function) - Optional. A function to omit frames above. * **Returns** void * **Inherited from** Error.captureStackTrace #### `Static`isError(error: unknown) * **Description**: Indicates whether the argument provided is a built-in Error instance or not. * **Parameters** * `error` (unknown) - The value to check. * **Returns** error is Error * **Inherited from** Error.isError ``` -------------------------------- ### REQUEST_PARAMS Event Source: https://github.com/shimaore/esl-lite/blob/main/docs/types/response.FreeSwitchPublicResponseEvents.html Handles the event for requesting parameters. ```APIDOC ## REQUEST_PARAMS ### Description Handles the event for requesting parameters. ### Method N/A (Event Handler) ### Endpoint N/A (Event Handler) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** (FreeSwitchEventData) - The event data associated with requesting parameters. ### Request Example ```json { "event": "REQUEST_PARAMS", "data": { ... FreeSwitchEventData ... } } ``` ### Response #### Success Response (200) N/A (Event Handler) #### Response Example N/A (Event Handler) ``` -------------------------------- ### ROSTER Event Source: https://github.com/shimaore/esl-lite/blob/main/docs/types/response.FreeSwitchPublicResponseEvents.html Handles the roster event. ```APIDOC ## ROSTER ### Description Handles the roster event. ### Method N/A (Event Handler) ### Endpoint N/A (Event Handler) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** (FreeSwitchEventData) - The event data associated with the roster. ### Request Example ```json { "event": "ROSTER", "data": { ... FreeSwitchEventData ... } } ``` ### Response #### Success Response (200) N/A (Event Handler) #### Response Example N/A (Event Handler) ``` -------------------------------- ### Send Generic Command to FreeSwitch (TypeScript) Source: https://github.com/shimaore/esl-lite/blob/main/docs/classes/client.FreeSwitchClient.html A low-level method for sending commands to FreeSwitch and waiting for completion. It accepts command, headers, body, and timeout. This method is protected and intended for subclass use. Defined in src/response.ts. ```typescript protected send(command: string, commandHeaders: ValueMap, commandBody: { content: Buffer; contentType: string } | undefined, timeout: number): Promise; ```