SDK Documentation

JavaScript SDK

Full-featured SDK for Node.js and browser environments with TypeScript support

npm
Package Manager
TypeScript
First-class Support
2.5kb
Min Bundle Size

Installation

Install with npm

npm install @autonoma/sdk

Install with Yarn

yarn add @autonoma/sdk

Install with pnpm

pnpm add @autonoma/sdk

Browser CDN

<script src="https://cdn.autonoma.dev/sdk/latest/autonoma.min.js"></script>

Quick Start

Node.js / TypeScript

import { Autonoma } from '@autonoma/sdk';

// Initialize with your API key
const autonoma = new Autonoma({
  apiKey: process.env.AUTONOMA_API_KEY,
  environment: 'production'
});

// Start monitoring
autonoma.start();

// Analyze code
const analysis = await autonoma.analyze({
  file: 'src/app.js',
  content: fs.readFileSync('src/app.js', 'utf8')
});

// Get predictions
const predictions = await autonoma.getPredictions();

// Apply auto-fix
if (predictions[0]?.autoFix) {
  await autonoma.applyFix(predictions[0].id);
}

Browser Environment

<!DOCTYPE html>
<html>
<head>
  <script src="https://cdn.autonoma.dev/sdk/latest/autonoma.min.js"></script>
</head>
<body>
  <script>
    // Initialize
    const autonoma = new Autonoma({
      apiKey: 'your-api-key',
      environment: 'development'
    });

    // Monitor client-side errors
    autonoma.captureErrors();

    // Track performance
    autonoma.trackPerformance();

    // Custom event
    autonoma.track('user_action', {
      action: 'button_click',
      component: 'header'
    });
  </script>
</body>
</html>

React Integration

import { AutonomaProvider, useAutonoma } from '@autonoma/sdk/react';

// App.jsx
function App() {
  return (
    <AutonomaProvider 
      apiKey={process.env.REACT_APP_AUTONOMA_KEY}
      environment="production"
    >
      <YourApp />
    </AutonomaProvider>
  );
}

// Component.jsx
function MyComponent() {
  const { analyze, predictions } = useAutonoma();

  useEffect(() => {
    // Analyze component on mount
    analyze({
      component: 'MyComponent',
      path: 'src/components/MyComponent.jsx'
    });
  }, []);

  return (
    <div>
      {predictions.map(pred => (
        <PredictionAlert key={pred.id} prediction={pred} />
      ))}
    </div>
  );
}

Configuration Options

const autonoma = new Autonoma({
  // Required
  apiKey: 'your-api-key',
  
  // Environment
  environment: 'production', // or 'development', 'staging'
  
  // API Configuration
  baseUrl: 'https://api.autonoma.dev',
  timeout: 30000,
  retries: 3,
  
  // Features
  autoFix: {
    enabled: true,
    confidence: 0.95,
    requireApproval: false,
    excludePatterns: ['*.test.js', '*.spec.js']
  },
  
  // Monitoring
  monitoring: {
    errors: true,
    performance: true,
    custom: true,
    sampling: 1.0 // 100% sampling
  },
  
  // Security
  encryption: true,
  anonymize: {
    enabled: true,
    fields: ['email', 'password', 'ssn']
  },
  
  // Performance
  batchSize: 100,
  flushInterval: 5000,
  
  // Logging
  debug: false,
  logger: console,
  
  // Callbacks
  onPrediction: (prediction) => {
    console.log('New prediction:', prediction);
  },
  onFix: (fix) => {
    console.log('Fix applied:', fix);
  },
  onError: (error) => {
    console.error('Autonoma error:', error);
  }
});

Environment Variables

The SDK automatically reads these environment variables:

  • AUTONOMA_API_KEY
  • AUTONOMA_ENVIRONMENT
  • AUTONOMA_BASE_URL
  • AUTONOMA_DEBUG

TypeScript Support

Full TypeScript support with type definitions included:

import { Autonoma, Config, Prediction } from '@autonoma/sdk';

Core Methods

analyze(options)

Analyze code for potential issues, performance problems, and security vulnerabilities.

// Analyze a single file
const result = await autonoma.analyze({
  file: 'src/components/UserList.jsx',
  content: fileContent,
  context: {
    framework: 'react',
    typescript: true
  }
});

// Analyze multiple files
const results = await autonoma.analyzeBatch([
  { file: 'src/app.js', content: appContent },
  { file: 'src/api.js', content: apiContent }
]);

// Response
{
  predictions: [...],
  metrics: {
    issues: 3,
    severity: 'medium',
    confidence: 0.92
  }
}

getPredictions(filters?)

Retrieve predictions for your codebase with optional filtering.

// Get all predictions
const predictions = await autonoma.getPredictions();

// Filter predictions
const criticalPredictions = await autonoma.getPredictions({
  severity: ['critical', 'high'],
  type: 'security',
  confidence: { min: 0.9 },
  createdAfter: new Date('2024-01-01')
});

// Pagination
const paginatedResults = await autonoma.getPredictions({
  page: 1,
  limit: 50,
  sortBy: 'severity',
  order: 'desc'
});

applyFix(predictionId, options?)

Apply an auto-fix for a specific prediction with validation and rollback support.

// Apply fix with default settings
const fixResult = await autonoma.applyFix('pred_123abc');

// Apply with options
const fixResult = await autonoma.applyFix('pred_123abc', {
  dryRun: true,           // Preview changes without applying
  createBackup: true,     // Create backup before applying
  runTests: true,         // Run tests after applying
  autoCommit: false,      // Don't auto-commit changes
  commitMessage: 'Fix: Memory leak in UserList component'
});

// Handle result
if (fixResult.success) {
  console.log('Fix applied:', fixResult.changes);
} else {
  console.error('Fix failed:', fixResult.error);
  // Rollback if needed
  await autonoma.rollback(fixResult.rollbackId);
}

monitor(options)

Start real-time monitoring of your application.

// Start monitoring
autonoma.monitor({
  // Error tracking
  errors: {
    enabled: true,
    captureStackTrace: true,
    beforeSend: (error) => {
      // Filter or modify errors before sending
      return error;
    }
  },
  
  // Performance monitoring
  performance: {
    enabled: true,
    metrics: ['FCP', 'LCP', 'CLS', 'FID'],
    resourceTimings: true,
    longTasks: true
  },
  
  // Custom metrics
  custom: {
    enabled: true,
    metrics: {
      'api.latency': { unit: 'ms', aggregation: 'avg' },
      'db.queries': { unit: 'count', aggregation: 'sum' }
    }
  }
});

// Stop monitoring
autonoma.stopMonitoring();

Advanced Features

Webhook Integration

// Register webhook
await autonoma.webhooks.create({
  url: 'https://api.example.com/autonoma',
  events: ['prediction.created', 'fix.applied'],
  secret: 'webhook_secret'
});

// Verify webhook signature
app.post('/autonoma', (req, res) => {
  const signature = req.headers['x-autonoma-signature'];
  const isValid = autonoma.webhooks.verify(
    req.body,
    signature,
    'webhook_secret'
  );
  
  if (!isValid) {
    return res.status(401).send('Invalid signature');
  }
  
  // Process webhook
});

Custom Rules

// Define custom rule
autonoma.rules.define({
  id: 'no-console-production',
  name: 'No console in production',
  severity: 'warning',
  pattern: /console\.(log|debug|info)/g,
  message: 'Remove console statements',
  fix: (match) => ({
    replace: match.replace(/console\..*\);?/g, '')
  })
});

// Apply custom rules
const customResults = await autonoma.analyze({
  file: 'app.js',
  rules: ['no-console-production']
});

Batch Operations

// Batch analyze
const results = await autonoma.batch({
  operations: [
    { type: 'analyze', file: 'src/app.js' },
    { type: 'analyze', file: 'src/api.js' },
    { type: 'getPredictions', filters: { severity: 'high' } }
  ],
  parallel: true,
  continueOnError: true
});

// Process results
results.forEach((result, index) => {
  if (result.error) {
    console.error(`Operation \${index} failed:`, result.error);
  } else {
    console.log(`Operation \${index} succeeded:`, result.data);
  }
});

CI/CD Integration

// GitHub Actions example
// .github/workflows/autonoma.yml
name: Autonoma Analysis
on: [push, pull_request]

jobs:
  analyze:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
      - run: npm install @autonoma/sdk
      - run: |
          node -e "
          const { Autonoma } = require('@autonoma/sdk');
          const autonoma = new Autonoma({
            apiKey: process.env.AUTONOMA_API_KEY
          });
          
          autonoma.ci.analyze({
            failOnCritical: true,
            createPRComment: true,
            autoFix: {
              enabled: true,
              createPR: true
            }
          });
          "
        env:
          AUTONOMA_API_KEY: ${{ secrets.AUTONOMA_API_KEY }}

Error Handling

import { Autonoma, AutonomaError } from '@autonoma/sdk';

try {
  const result = await autonoma.analyze({ file: 'app.js' });
} catch (error) {
  if (error instanceof AutonomaError) {
    switch (error.code) {
      case 'RATE_LIMIT_EXCEEDED':
        console.error('Rate limit hit, retry after:', error.retryAfter);
        break;
      
      case 'INVALID_API_KEY':
        console.error('Invalid API key');
        break;
      
      case 'NETWORK_ERROR':
        console.error('Network error:', error.message);
        break;
      
      case 'VALIDATION_ERROR':
        console.error('Validation failed:', error.validationErrors);
        break;
      
      default:
        console.error('Autonoma error:', error.message);
    }
  } else {
    // Handle other errors
    console.error('Unexpected error:', error);
  }
}

// Global error handler
autonoma.on('error', (error) => {
  // Log to your error tracking service
  errorTracker.log(error);
});

Pro tip: The SDK automatically retries failed requests with exponential backoff. You can configure retry behavior in the initialization options.

Best Practices

Security

  • • Never expose API keys in client-side code
  • • Use environment variables for sensitive data
  • • Enable encryption for sensitive codebases
  • • Implement proper access controls

Performance

  • • Batch operations when analyzing multiple files
  • • Use sampling in development environments
  • • Configure appropriate timeout values
  • • Enable caching for repeated analyses

Integration

  • • Integrate early in development workflow
  • • Add to pre-commit hooks for immediate feedback
  • • Include in CI/CD pipelines
  • • Monitor production deployments

Configuration

  • • Start with conservative auto-fix settings
  • • Gradually increase confidence thresholds
  • • Customize rules for your team's standards
  • • Regular review and update configurations

Migration from v1.x

Note: Version 2.0 includes breaking changes. Please review this guide before upgrading.

Key Changes

Initialization

// v1.x
const autonoma = require('autonoma');
autonoma.init({ apiKey: 'key' });

// v2.x
import { Autonoma } from '@autonoma/sdk';
const autonoma = new Autonoma({ apiKey: 'key' });

Async Methods

// v1.x - Callbacks
autonoma.analyze('file.js', (err, result) => {});

// v2.x - Promises/Async
const result = await autonoma.analyze({ file: 'file.js' });

Configuration

// v1.x
autonoma.config.autoFix = true;

// v2.x
const autonoma = new Autonoma({
  autoFix: { enabled: true }
});

Ready to Get Started?

Install the SDK and start improving your code quality today