All files / src index.ts

43.52% Statements 37/85
24.32% Branches 9/37
66.66% Functions 10/15
45% Lines 36/80

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 1821x 1x 1x 1x 1x 1x                       1x                                                                                                   1x         5x   5x                                                 5x 5x       5x 5x 1x     4x 1x     3x 1x     2x 2x               1x       5x       2x 2x                                   5x 5x 5x 5x       4x 4x 4x       3x 3x       26x       12x            
import { readFileSync, existsSync } from 'fs';
import { join, dirname } from 'path';
import { CallBatcher } from './batcher.js';
import { wrapAnthropic } from './providers/anthropic.js';
import { wrapGemini } from './providers/gemini.js';
import { wrapOpenAI } from './providers/openai.js';
import type {
  AnthropicClientLike,
  EvalyticOptions,
  FlushResult,
  GeminiClientLike,
  LLMCallRecord,
  OpenAIClientLike,
  UnknownFunction,
} from './types.js';
 
export type { EvalyticOptions, FlushResult, LLMCallRecord, Provider } from './types.js';
export { CallBatcher } from './batcher.js';
 
function parseConfigFile(filePath: string): Record<string, string> {
  const result: Record<string, string> = {};
  try {
    const lines = readFileSync(filePath, 'utf8').split('\n');
    for (const line of lines) {
      const trimmed = line.trim();
      Iif (!trimmed || trimmed.startsWith('#')) continue;
      const eq = trimmed.indexOf('=');
      Iif (eq === -1) continue;
      result[trimmed.slice(0, eq).trim()] = trimmed.slice(eq + 1).trim();
    }
  } catch {
    // non-fatal
  }
  return result;
}
 
function loadConfig(): { apiKey: string; endpoint?: string } | null {
  const envKey = process.env['EVALYTIC_API_KEY'];
  Iif (envKey) {
    const endpoint = process.env['EVALYTIC_ENDPOINT'];
    return endpoint ? { apiKey: envKey, endpoint } : { apiKey: envKey };
  }
 
  // Walk up from cwd looking for .evalytic
  try {
    let dir = process.cwd();
    while (true) {
      const configPath = join(dir, '.evalytic');
      Iif (existsSync(configPath)) {
        const parsed = parseConfigFile(configPath);
        const apiKey = parsed['EVALYTIC_API_KEY'];
        Iif (apiKey) {
          const endpoint = parsed['EVALYTIC_ENDPOINT'];
          return endpoint ? { apiKey, endpoint } : { apiKey };
        }
      }
      const parent = dirname(dir);
      Iif (parent === dir) break;
      dir = parent;
    }
  } catch {
    // non-fatal — fs may not be available in all runtimes
  }
 
  return null;
}
 
export class Evalytic {
  private readonly batcher: CallBatcher;
  private readonly debug: boolean;
 
  constructor(opts: EvalyticOptions = {}) {
    let resolvedOpts = opts;
 
    Iif (!opts.apiKey) {
      const config = loadConfig();
      if (config) {
        const endpoint = opts.endpoint ?? config.endpoint;
        resolvedOpts = {
          ...opts,
          apiKey: config.apiKey,
          ...(endpoint !== undefined ? { endpoint } : {}),
        };
      } else {
        if (
          typeof process !== 'undefined' &&
          process.stdout?.isTTY === true &&
          process.env['NODE_ENV'] !== 'production'
        ) {
          console.log('\n[evalytic] No API key configured.');
          console.log('  Run npx evalytic-setup to get started, or set EVALYTIC_API_KEY.');
          console.log('  Calls will not be logged until a key is provided.\n');
        } else {
          console.warn('[evalytic] No API key found. Set EVALYTIC_API_KEY or run npx evalytic-setup');
        }
        resolvedOpts = { ...opts, apiKey: '' };
      }
    }
 
    this.batcher = new CallBatcher(resolvedOpts);
    this.debug = resolvedOpts.debug ?? false;
  }
 
  wrap<TClient>(client: TClient): TClient {
    try {
      if (isOpenAIClient(client)) {
        return wrapOpenAI(client, this.batcher, null) as TClient;
      }
 
      if (isAnthropicClient(client)) {
        return wrapAnthropic(client, this.batcher, null) as TClient;
      }
 
      if (isGeminiClient(client)) {
        return wrapGemini(client, this.batcher, null) as TClient;
      }
 
      this.warn('Unknown client type; calls will not be logged');
      return client;
    } catch (error) {
      this.debugLog(`wrap error: ${stringifyError(error)}`);
      return client;
    }
  }
 
  async flush(): Promise<FlushResult> {
    return this.batcher.flush();
  }
 
  destroy(): void {
    this.batcher.destroy();
  }
 
  private warn(message: string): void {
    try {
      console.warn(`[evalytic] ${message}`);
    } catch {
      // wrap() must never throw.
    }
  }
 
  private debugLog(message: string): void {
    Iif (!this.debug) return;
 
    try {
      console.debug(`[evalytic] ${message}`);
    } catch {
      // wrap() must never throw.
    }
  }
}
 
function isOpenAIClient(client: unknown): client is OpenAIClientLike {
  const root = asRecord(client);
  const chat = asRecord(root?.chat);
  const completions = asRecord(chat?.completions);
  return isFunction(completions?.create);
}
 
function isAnthropicClient(client: unknown): client is AnthropicClientLike {
  const root = asRecord(client);
  const messages = asRecord(root?.messages);
  return isFunction(messages?.create);
}
 
function isGeminiClient(client: unknown): client is GeminiClientLike {
  const root = asRecord(client);
  return isFunction(root?.getGenerativeModel);
}
 
function asRecord(value: unknown): Record<string, unknown> | undefined {
  return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : undefined;
}
 
function isFunction(value: unknown): value is UnknownFunction {
  return typeof value === 'function';
}
 
function stringifyError(error: unknown): string {
  return error instanceof Error ? error.message : String(error);
}