CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-engine-io-client

Client for the realtime Engine providing bidirectional communication with WebSocket, polling, and WebTransport support

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

utility-functions.mddocs/

Utility Functions

Helper functions for URI parsing, timer management, and protocol utilities supporting both browser and Node.js environments with cross-platform compatibility.

Capabilities

Timer Management

Timer functions for managing timeouts and intervals with native timer support options.

/**
 * Install timer functions on objects with native timer support
 * Configures setTimeout and clearTimeout functions based on options
 * @param obj - Object to install timer functions on
 * @param opts - Options containing useNativeTimers flag
 */
function installTimerFunctions(obj: any, opts: any): void;

Usage Examples:

import { installTimerFunctions } from "engine.io-client";

// Install timer functions on object
const timerObj = {};
installTimerFunctions(timerObj, { useNativeTimers: true });

// Object now has setTimeoutFn and clearTimeoutFn methods
timerObj.setTimeoutFn(() => {
  console.log("Timer fired");
}, 1000);

URI Parsing

Comprehensive URI parsing functionality for handling connection URLs and parsing query parameters.

/**
 * Parse URI strings into structured components
 * Handles IPv6 addresses and complex query parameters
 * @param str - URI string to parse (max 8000 characters)
 * @returns Parsed URI object with all components
 * @throws Error if URI exceeds 8000 characters
 */
function parse(str: string): ParsedUri;

interface ParsedUri {
  source: string;
  protocol: string;
  authority: string;
  userInfo: string;
  user: string;
  password: string;
  host: string;
  port: string;
  relative: string;
  path: string;
  directory: string;
  file: string;
  query: string;
  anchor: string;
  pathNames: string[];
  queryKey: Record<string, string>;
  ipv6uri?: boolean;
}

Usage Examples:

import { parse } from "engine.io-client";

// Parse HTTP URL
const parsed = parse("https://api.example.com:443/socket.io/?token=abc123#room1");
console.log(parsed.protocol); // "https"
console.log(parsed.host); // "api.example.com"
console.log(parsed.port); // "443"
console.log(parsed.path); // "/socket.io/"
console.log(parsed.queryKey); // { token: "abc123" }
console.log(parsed.anchor); // "room1"

// Parse WebSocket URL
const wsParsed = parse("wss://localhost:3000/engine.io/");
console.log(wsParsed.protocol); // "wss"
console.log(wsParsed.host); // "localhost"

// Parse IPv6 URL
const ipv6Parsed = parse("http://[::1]:8080/path");
console.log(ipv6Parsed.host); // "::1"
console.log(ipv6Parsed.ipv6uri); // true

Next Tick Scheduling

Cross-platform next tick scheduling for deferring function execution.

/**
 * Schedule function for next tick execution
 * Uses platform-appropriate scheduling mechanism
 * @param fn - Function to execute on next tick
 */
function nextTick(fn: Function): void;

Usage Examples:

import { nextTick } from "engine.io-client";

// Schedule function for next tick
nextTick(() => {
  console.log("Executed on next tick");
});

// Defer callback execution
function deferredCallback(callback: Function) {
  nextTick(callback);
}

Protocol Information

Protocol version and transport availability constants.

/**
 * Engine.IO protocol version number
 * Used for compatibility checking
 */
const protocol: number;

/**
 * Available transport constructors
 * Platform-specific implementations
 */
const transports: {
  websocket: typeof WS;
  webtransport: typeof WT;
  polling: typeof XHR;
};

Usage Examples:

import { protocol, transports } from "engine.io-client";

// Check protocol version
console.log("Protocol version:", protocol); // e.g., 4

// Access transport constructors
console.log("Available transports:", Object.keys(transports));
// ["websocket", "webtransport", "polling"]

// Use specific transport
const ws = new transports.websocket(options);

Transport Exports

Individual transport class exports for tree-shaking and selective import.

/**
 * Fetch API-based polling transport
 * Modern alternative to XMLHttpRequest
 */
class Fetch extends Polling {
  // Fetch-based HTTP transport implementation
}

/**
 * XMLHttpRequest-based polling transport for browsers
 * Traditional HTTP long-polling transport
 */
class XHR extends BaseXHR {
  // Browser XHR implementation
}

/**
 * Node.js HTTP-based polling transport
 * Server-side HTTP transport implementation
 */
class NodeXHR extends BaseXHR {
  // Node.js HTTP implementation
}

/**
 * Browser WebSocket transport
 * Native WebSocket implementation for browsers
 */
class WebSocket extends BaseWS {
  // Browser WebSocket implementation
}

/**
 * Node.js WebSocket transport
 * WebSocket implementation using ws library
 */
class NodeWebSocket extends BaseWS {
  // Node.js WebSocket implementation
}

/**
 * WebTransport-based transport
 * Modern HTTP/3 transport implementation
 */
class WebTransport extends Transport {
  // WebTransport implementation
}

Usage Examples:

// Tree-shaking imports
import { SocketWithoutUpgrade, WebSocket, Fetch } from "engine.io-client";

// Use specific transports only
const socket = new SocketWithoutUpgrade({
  hostname: "localhost",
  port: 3000,
  transports: [WebSocket, Fetch]
});

// Browser-specific transport
import { XHR } from "engine.io-client";
const browserSocket = new SocketWithoutUpgrade({
  hostname: "localhost",
  port: 3000,
  transports: [XHR]
});

// Node.js-specific transport
import { NodeWebSocket } from "engine.io-client";
const nodeSocket = new SocketWithoutUpgrade({
  hostname: "localhost", 
  port: 3000,
  transports: [NodeWebSocket]
});

Binary Data Utilities

Utilities for handling binary data and calculating data sizes.

/**
 * Calculate byte length of data with base64 overhead consideration
 * Handles strings, ArrayBuffers, and Blobs
 * @param obj - Data object to measure
 * @returns Byte length including encoding overhead
 */
function byteLength(obj: string | ArrayBuffer | Blob): number;

/**
 * Generate random 8-character string
 * Used for creating unique identifiers
 * @returns Random string identifier
 */
function randomString(): string;

/**
 * Pick specific properties from object
 * Utility for creating option subsets
 * @param obj - Source object
 * @param attr - Property names to pick
 * @returns New object with selected properties
 */
function pick(obj: any, ...attr: string[]): any;

/**
 * Encode object as URL query string
 * @param obj - Object to encode
 * @returns Encoded query string
 */
function encode(obj: Record<string, any>): string;

/**
 * Decode URL query string to object
 * @param qs - Query string to decode
 * @returns Decoded object
 */
function decode(qs: string): Record<string, string>;

Usage Examples:

import { byteLength, randomString, pick } from "engine.io-client";

// Calculate data size
const textSize = byteLength("Hello world"); // ~11 bytes
const bufferSize = byteLength(new ArrayBuffer(1024)); // ~1365 bytes (with base64 overhead)

// Generate random identifier
const id = randomString(); // e.g., "abc12def3"

// Pick specific properties
const options = {
  hostname: "localhost",
  port: 3000,
  secure: true,
  extraData: "not needed"
};

const connectionOpts = pick(options, "hostname", "port", "secure");
// { hostname: "localhost", port: 3000, secure: true }

// Encode query parameters
const queryString = encode({ token: "abc123", userId: "456" });
// "token=abc123&userId=456"

// Decode query string
const params = decode("token=abc123&userId=456");
// { token: "abc123", userId: "456" }

Platform Detection

Utilities for detecting runtime environment and capabilities.

/**
 * Global object reference with cross-platform compatibility
 * Provides consistent access to global object
 */
const globalThisShim: typeof globalThis;

/**
 * Default binary type for the current platform
 * 'arraybuffer' for Node.js, 'blob' for browsers
 */
const defaultBinaryType: BinaryType;

/**
 * Cookie jar for Node.js environments
 * Manages HTTP cookies across requests (Node.js only)
 */
interface CookieJar {
  parseCookies(values: string[]): void;
  addCookies(xhr: any): void;
  appendCookies(headers: Headers): void;
  readonly cookies: Iterator<[string, Cookie]>;
}

interface Cookie {
  name: string;
  value: string;
  expires?: Date;
}

/**
 * Create a cookie jar for Node.js HTTP request cookie management
 * @returns CookieJar instance for managing cookies
 */
function createCookieJar(): CookieJar;

Usage Examples:

import { defaultBinaryType, globalThisShim } from "engine.io-client";

// Use platform-appropriate binary type
socket.binaryType = defaultBinaryType;

// Access global object safely
const setTimeout = globalThisShim.setTimeout;

// Node.js cookie management
if (typeof window === "undefined") {
  const cookieJar = createCookieJar();
  
  // Parse cookies from response headers
  cookieJar.parseCookies(["sessionId=abc123; Path=/; HttpOnly"]);
  
  // Add cookies to outgoing request
  cookieJar.addCookies(xmlHttpRequest);
  
  // Iterate through stored cookies
  for (const [name, cookie] of cookieJar.cookies) {
    console.log(`Cookie: ${name}=${cookie.value}`);
  }
}

Types

type BinaryType = "blob" | "arraybuffer";

interface TimerObject {
  setTimeoutFn: typeof setTimeout;
  clearTimeoutFn: typeof clearTimeout;
}

Install with Tessl CLI

npx tessl i tessl/npm-engine-io-client

docs

event-handling.md

index.md

socket-connection.md

transport-system.md

utility-functions.md

tile.json