API Reference

Complete reference for the FOON SDK.

transform()

The main transformation function. Transforms input JSON to match a target schema.

import { transform } from 'foon-sdk';

const result = await transform(input, options);

Parameters

ParameterTypeDescription
inputunknownThe JSON data to transform
optionsTransformOptionsTransformation options

TransformOptions

interface TransformOptions {
  mode?: 'SEMANTIC';              // Only SEMANTIC mode in v1.0
  schema: object;                 // JSON Schema object
  provider: Provider;             // LLM provider instance
  confidenceThreshold?: number;   // Default: 0.85
  cache?: Cache;                  // Optional cache instance
  verbose?: boolean;              // Enable verbose output
  security?: SecurityOptions;     // Security settings
  hooks?: TransformHooks;         // Observability hooks
}

TransformResult

interface TransformResult {
  ok: boolean;           // Success flag
  output?: unknown;      // Transformed output (if successful)
  error?: FONError;      // Error details (if failed)
  trace: TraceReport;    // Complete trace report
}

Example

import { transform, OpenAIProvider } from 'foon-sdk';

const result = await transform(
  { fullName: 'Jane Smith', email_addr: 'jane@example.com' },
  {
    schema: customerSchema,
    provider: new OpenAIProvider({
      apiKey: process.env.OPENAI_API_KEY,
      model: 'gpt-5-nano'
    }),
    confidenceThreshold: 0.85
  }
);

if (result.ok) {
  console.log(result.output);
} else {
  console.error(result.error?.category);
  console.log(result.trace);
}

Providers

GeminiProvider

import { GeminiProvider } from 'foon-sdk';

const provider = new GeminiProvider({
  apiKey: string;         // Required
  model?: string;         // Default: 'gemini-1.5-flash'
  timeout?: number;       // Default: 30000ms
});

OpenAIProvider

import { OpenAIProvider } from 'foon-sdk';

const provider = new OpenAIProvider({
  apiKey: string;         // Required
  model?: string;         // Default: 'gpt-5-nano'
  timeout?: number;       // Default: 30000ms
  baseUrl?: string;       // For custom endpoints
});

OllamaProvider

import { OllamaProvider } from 'foon-sdk';

const provider = new OllamaProvider({
  apiKey?: string;        // Optional for local Ollama
  model?: string;         // Default: 'llama2'
  timeout?: number;       // Default: 30000ms
  baseUrl?: string;       // Default: 'http://localhost:11434'
});

LRUCache

Built-in LRU cache for mapping plans.

import { LRUCache } from 'foon-sdk';

const cache = new LRUCache({
  max: 100,          // Max entries
  ttl: 3600000       // TTL in ms (1 hour)
});

const result = await transform(input, {
  schema,
  provider,
  cache
});

console.log(result.trace.cache.hit);  // true if cache was used

Security Options

Configure security limits and redaction.

const result = await transform(input, {
  schema,
  provider,
  security: {
    maxInputSize: 1024 * 1024,    // 1MB default
    maxDepth: 10,                  // Max nesting depth
    maxKeys: 1000,                 // Max number of keys
    redactKeys: ['password', 'token'],  // Keys to redact
    sanitizePrompt: true,          // Prompt injection protection
    includeValues: false           // Don't send values to LLM
  }
});

Trace Report

Every transformation includes a comprehensive trace.

interface TraceReport {
  traceId: string;
  mode: 'SEMANTIC';
  provider: string;
  promptVersion: string;
  timings: {
    total: number;        // Total time (ms)
    proposal: number;     // LLM call time
    execution: number;    // Execution time
    validation: number;   // Validation time
  };
  mappingPlan: {
    raw: string;          // Raw LLM response
    parsed: MappingPlan;  // Parsed mapping plan
  };
  execution: {
    assignmentsApplied: AssignmentTrace[];
    assignmentsRejected: RejectedAssignment[];
    droppedFields: Drop[];
    warnings: Warning[];
    conflicts: Conflict[];
  };
  validation: {
    success: boolean;
    errors: ValidationError[];
  };
  cache: {
    hit: boolean;
    key: string;
  };
  confidenceSummary: {
    min: number;
    max: number;
    avg: number;
    countBelowThreshold: number;
    threshold: number;
  };
}

Error Categories

if (!result.ok) {
  switch (result.error?.category) {
    case 'SCHEMA_LOAD_ERROR':
      // Invalid schema
      break;
    case 'PROVIDER_ERROR':
      // LLM API error
      break;
    case 'MAPPING_PLAN_PARSE_ERROR':
      // LLM returned invalid mapping plan
      break;
    case 'CONFIDENCE_TOO_LOW':
      // Mapping confidence below threshold
      break;
    case 'EXECUTION_ERROR':
      // Error applying mapping plan
      break;
    case 'VALIDATION_ERROR':
      // Output doesn't match schema
      break;
    case 'SECURITY_LIMIT_EXCEEDED':
      // Input exceeded security limits
      break;
  }
}

Hooks

Register hooks for observability.

const result = await transform(input, {
  schema,
  provider,
  hooks: {
    onStart: (input, schema) => {
      console.log('Transform starting');
    },
    onMappingPlan: (plan) => {
      console.log('Plan generated', plan);
    },
    onComplete: (result) => {
      console.log('Transform complete');
    },
    onError: (error) => {
      console.error('Transform failed', error);
    }
  }
});