const isBrowser = process?.env?.BROWSER === 'true';
import { EventEmitter } from 'events';

type WebSocketOptions = {
  /**
   * 是否拒绝不安全的证书, in node only
   */
  rejectUnauthorized?: boolean;
  headers?: Record<string, string>;
  [key: string]: any;
};
export const initWs = async (url: string, options?: WebSocketOptions) => {
  let ws: WebSocket;
  if (isBrowser) {
    ws = new WebSocket(url);
  } else {
    const WebSocket = await import('ws').then((module) => module.default);
    const { rejectUnauthorized, headers, ...rest } = options || {};
    ws = new WebSocket(url, {
      rejectUnauthorized: rejectUnauthorized || true,
      headers: headers,
      ...rest,
    }) as any;
  }
  return ws;
};
interface EventEmitterOptions {
  /**
   * Enables automatic capturing of promise rejection.
   */
  captureRejections?: boolean | undefined;
}
/**
 * 初始化一个事件发射器
 * @param opts 事件发射器选项
 * @returns 事件发射器
 */
export const initEmitter = (opts?: EventEmitterOptions) => {
  const emitter = new EventEmitter(opts);
  return emitter;
};
