02 · Usage

Usage & examples

With support for both CommonJS and ES6 modules, the SDK integrates seamlessly into any JavaScript or TypeScript project, providing real-time insights into API behaviour and actionable code improvement recommendations.

Step 1

Import & setup

// CommonJS
const { X2YSdk } = require('x2y-dev-tools-sdk');

// ES Modules / TypeScript
import { X2YSdk } from 'x2y-dev-tools-sdk';
import { X2YSdk } from 'x2y-dev-tools-sdk';

const sdk = new X2YSdk(
  {
    // API monitoring config
    rateLimitThreshold: 80,
    predictionWindow: 60000,
    apiUrl: 'https://api.example.com'
  },
  {
    // Refactoring config
    targetLanguage: 'typescript',
    rules: ['performance', 'idiom', 'async']
  }
);

Step 2

Record API traffic

Build a dataset by recording API traffic data for predictions. Each call captures endpoint, method, timestamp, response time, status code and raw headers.

sdk.recordAPITraffic({
  endpoint: '/api/users',
  method: 'POST',
  timestamp: Date.now(),
  responseTime: 250,
  statusCode: 201,
  headers: {
    'x-ratelimit-remaining': '45',
    'x-ratelimit-limit': '100',
    'content-type': 'application/json'
  }
});

Step 3

Predict API issues

The SDK analyses recorded traffic to predict potential problems before they impact users.

const prediction = await sdk.predictAPIIssues('/api/users');
console.log(prediction);

/* Output:
{
  endpoint: '/api/users',
  riskLevel: 'medium',
  predictedFailure: false,
  rateLimitApproaching: true,
  suggestedAlternatives: ['/api/v2/users', '/api/users?cached=true'],
  confidence: 85
}
*/

Step 4

Refactor code & files

Analyse raw strings or entire local files and receive line-level suggestions with exact corrected snippets.

const suggestions = await sdk.refactorCode(`
  for (let i = 0; i < arr.length; i++) {
    console.log(arr[i]);
  }
`);
console.log(suggestions);
const fileSuggestions = await sdk.refactorFile('./src/example.js');
console.log(`${fileSuggestions.length} suggestions found`);

Integration

Fetch API wrapper

Monitor and predict issues transparently by wrapping fetch:

const originalFetch = window.fetch;
window.fetch = async (...args) => {
  const start = Date.now();
  const response = await originalFetch(...args);
  const duration = Date.now() - start;

  sdk.recordAPITraffic({
    endpoint: args[0].toString(),
    method: 'GET',
    timestamp: Date.now(),
    responseTime: duration,
    statusCode: response.status,
    headers: Object.fromEntries(response.headers.entries())
  });

  const prediction = await sdk.predictAPIIssues(args[0].toString());
  if (prediction.riskLevel === 'high') {
    console.warn('High risk detected for:', args[0]);
  }
  return response;
};
Auto-refactoring

Enable automatic refactoring by setting the environment variable X2Y_AUTO_REFACTOR=true. This automatically applies high-severity refactoring suggestions. Review diffs first in production pipelines.

Ready to integrate

Ship safer API integrations and cleaner code reviews.

Start with the installation guide, inspect the full API reference, or audit the release-gate playground before deploying x2y SDK into your own Node.js or TypeScript stack.