Installation

Get started with x2y SDK by installing it in your project. Choose your preferred package manager below.

Via NPM

The recommended way to install x2y SDK. You need Node.js installed on your system. NPM is the default package manager for Node.js and comes pre-installed when you install Node.js.

NPM Installation

Install x2y-dev-tools-sdk from npm registry

# Install the SDK as a dependency in your project
npm install x2y-dev-tools-sdk

# Or install globally if you need command-line access
npm install -g x2y-dev-tools-sdk

View on NPM: https://www.npmjs.com/package/x2y-dev-tools-sdk

Via Git

Clone the repository to work with the source code directly from GitHub. This option is ideal if you want to contribute to the SDK or use the latest development version before it's published to NPM.

Git Setup

Clone and build the SDK from source

# Clone the repository
git clone https://github.com/x2yDevs/x2y-sdk.git

# Navigate to the project directory
cd x2y-sdk

# Install dependencies
npm install

# Build the project
npm run build

# Run tests to verify the setup
npm test

Import in Your Project

After installation via NPM or Git, import the SDK into your project. The x2y SDK supports both ES6 modules and CommonJS formats.

Import SDK

Import the X2YSdk class in your code

// ES6 modules
import { X2YSdk } from 'x2y-dev-tools-sdk';

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

Basic Usage

Learn how to use the x2y SDK with these basic examples.

Initialize the SDK

Create an instance of X2YSdk to get started with monitoring and refactoring.

Basic Usage Example

Initialize SDK and perform basic operations

import { X2YSdk } from 'x2y-dev-tools-sdk';

const sdk = new X2YSdk();

// Record API traffic
sdk.recordAPITraffic({
  endpoint: '/api/users',
  method: 'GET',
  timestamp: Date.now(),
  responseTime: 200,
  statusCode: 200,
  headers: { 'x-ratelimit-remaining': '85' }
});

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

// Refactor code
const suggestions = await sdk.refactorCode(`
  for (let i = 0; i < arr.length; i++) {
    console.log(arr[i]);
  }
`);
console.log(suggestions);

SDK Configuration

Configure the SDK with custom settings for API monitoring and code refactoring.

SDK Configuration

Configure API monitoring and refactoring options

const sdk = new X2YSdk(
  {
    // API monitoring config
    rateLimitThreshold: 80, // Percentage of rate limit before warning
    predictionWindow: 60000, // Time window in ms for analysis (1 minute)
    apiUrl: 'https://api.example.com'
  },
  {
    // Refactoring config
    targetLanguage: 'typescript',
    rules: ['performance', 'idiom', 'async']
  }
);

API Monitoring Features

Monitor and predict API issues with intelligent traffic analysis.

Recording API Traffic

Record traffic data to build a dataset for predictions. This captures endpoint information, response times, and rate limit headers.

Record API Traffic

Capture API call metrics for analysis

// Record traffic for monitoring
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'
  }
});

Predicting API Issues

Analyze recorded traffic to predict potential failures, rate limit breaches, and performance issues.

Predict Issues

Get predictive analytics for your API endpoints

// Predict issues before they happen
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
}
*/

Rate Limit Warnings

The prediction includes rate limit approaching status based on the configured threshold.

Rate Limit Configuration

Configure when to warn about approaching rate limits

const sdk = new X2YSdk({
  rateLimitThreshold: 80 // Warn when 80% of limit is reached
});

// If x-ratelimit-remaining/x-ratelimit-limit ratio exceeds 80%
// prediction.rateLimitApproaching will be true

Code Refactoring Features

Improve your code quality with intelligent refactoring suggestions.

Refactoring Code Strings

Analyze code snippets and receive suggestions for improvements including idiom updates and performance optimizations.

Refactor Code Strings

Get improvement suggestions for code snippets

// Refactor code directly
const suggestions = await sdk.refactorCode(`
  for (let i = 0; i < arr.length; i++) {
    console.log(arr[i]);
  }
`);

console.log(suggestions);

/*
Output:
[
  {
    type: 'idiom',
    description: 'Use array methods like map() and forEach() for better readability',
    originalCode: 'for (let i = 0; i < arr.length; i++) { ... }',
    suggestedCode: 'arr.forEach(item => console.log(item));',
    line: 2,
    severity: 'medium'
  }
]
*/

Refactoring Entire Files

Analyze entire files to identify and suggest improvements across your codebase.

Refactor Files

Analyze and improve entire source files

// Refactor entire files
const fileSuggestions = await sdk.refactorFile('./src/example.js');
console.log(`${fileSuggestions.length} suggestions found`);

Performance Suggestions

The SDK identifies performance anti-patterns like DOM queries in loops or repeated function calls.

Performance Optimization

Identify and fix performance bottlenecks

const performanceCode = `
  for (let i = 0; i < items.length; i++) {
    document.getElementById('myElement').innerHTML += items[i];
  }
`;

const suggestions = await sdk.refactorCode(performanceCode);
// Will suggest caching the DOM query outside the loop
// Output: "Cache the DOM query outside the loop for better performance"

Idiom Suggestions

Get suggestions for modern JavaScript and TypeScript idioms to make your code more readable and maintainable.

Modern JavaScript Idioms

Update code to use modern JavaScript patterns

const oldCode = `
  var result = [];
  for (var i = 0; i < items.length; i++) {
    if (items[i].active) {
      result.push(items[i].name);
    }
  }
`;

const suggestions = await sdk.refactorCode(oldCode);
// Will suggest: items.filter(item => item.active).map(item => item.name)

Async Pattern Improvements

The SDK suggests improvements for async code, such as converting promise chains to async/await.

Async/Await Modernization

Convert promise chains to modern async/await syntax

const oldAsyncCode = `
  fetch('/api/data')
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error(error));
`;

const suggestions = await sdk.refactorCode(oldAsyncCode);
// Will suggest using async/await instead of promise chains

Integration Examples

Integrate x2y SDK with popular libraries and frameworks to monitor your API traffic and get intelligent predictions about potential issues.

With Axios

Monitor API calls made with axios using interceptors to automatically record traffic and predict issues. Axios interceptors allow you to hook into request/response lifecycle, making it perfect for integrating the x2y SDK. The interceptor will capture both successful and failed requests.

Axios Integration

Monitor all axios requests with x2y SDK using interceptors

import axios from 'axios';
import { X2YSdk } from 'x2y-dev-tools-sdk';

const sdk = new X2YSdk();

// Create an axios interceptor to monitor all requests
axios.interceptors.response.use(
  (response) => {
    // Record successful requests
    sdk.recordAPITraffic({
      endpoint: response.config.url || '',
      method: response.config.method || 'GET',
      timestamp: Date.now(),
      responseTime: response.headers['x-response-time'] || 0,
      statusCode: response.status,
      headers: response.headers
    });
    return response;
  },
  (error) => {
    // Record failed requests for monitoring and analysis
    sdk.recordAPITraffic({
      endpoint: error.config.url || '',
      method: error.config.method || 'GET',
      timestamp: Date.now(),
      responseTime: 0,
      statusCode: error.response?.status || 500,
      headers: error.response?.headers || {}
    });
    return Promise.reject(error);
  }
);

// Now all axios requests will be automatically tracked
axios.get('/api/users').then(data => console.log(data));

With Fetch API

Wrap the native fetch API to automatically monitor all API calls and predict potential issues. By overriding the global fetch function, every fetch request made in your application will be tracked, providing comprehensive API monitoring across your entire application.

Fetch API Integration

Monitor all fetch requests with x2y SDK by wrapping the global fetch

import { X2YSdk } from 'x2y-dev-tools-sdk';

const sdk = new X2YSdk();
const originalFetch = window.fetch;

window.fetch = async (...args) => {
  const start = Date.now();
  const response = await originalFetch(...args);
  const duration = Date.now() - start;
  
  // Record the traffic for every fetch call
  sdk.recordAPITraffic({
    endpoint: args[0].toString(),
    method: 'GET',
    timestamp: Date.now(),
    responseTime: duration,
    statusCode: response.status,
    headers: Object.fromEntries(response.headers.entries())
  });
  
  // Predict if next calls might fail based on current traffic patterns
  const prediction = await sdk.predictAPIIssues(args[0].toString());
  if (prediction.riskLevel === 'high') {
    console.warn('High risk detected for:', args[0]);
    console.warn('Consider using:', prediction.suggestedAlternatives);
  }
  
  return response;
};

Real-World Integration Example: Monitoring API calls with Axios

Complete example showing how to integrate the SDK with Axios in a production application. This demonstrates best practices for using the x2y SDK with axios, including configuration options, proper error handling, and automatic risk predictions for your API calls.

Real-World Axios Example

Complete integration with error handling and risk prediction

import axios from 'axios';
import { X2YSdk } from 'x2y-dev-tools-sdk';

const sdk = new X2YSdk({
  rateLimitThreshold: 80,
  predictionWindow: 60000,
  apiUrl: 'https://api.example.com'
});

// Create an axios interceptor
axios.interceptors.response.use(
  (response) => {
    // Record successful requests
    sdk.recordAPITraffic({
      endpoint: response.config.url || '',
      method: response.config.method || 'GET',
      timestamp: Date.now(),
      responseTime: response.headers['x-response-time'] || 0,
      statusCode: response.status,
      headers: response.headers
    });
    return response;
  },
  (error) => {
    // Record failed requests
    sdk.recordAPITraffic({
      endpoint: error.config.url || '',
      method: error.config.method || 'GET',
      timestamp: Date.now(),
      responseTime: 0, // Failed request
      statusCode: error.response?.status || 500,
      headers: error.response?.headers || {}
    });
    return Promise.reject(error);
  }
);

// Make API calls with automatic monitoring
async function fetchUserData() {
  try {
    const response = await axios.get('/api/users');
    
    // Predict if next calls might fail based on current patterns
    const prediction = await sdk.predictAPIIssues('/api/users');
    if (prediction.riskLevel === 'high') {
      console.warn('High risk detected:', prediction);
      console.warn('Consider using:', prediction.suggestedAlternatives);
    }
    
    return response.data;
  } catch (error) {
    console.error('Failed to fetch users:', error.message);
    throw error;
  }
}

// Usage
fetchUserData().then(data => console.log('Users:', data));

Real-World Integration Example: Monitoring API calls with Fetch

Complete example showing how to integrate the SDK into a real application with proper error handling and monitoring. This demonstrates best practices for using the x2y SDK in production environments, including configuration options and comprehensive error management.

Real-World Fetch Example

Complete integration with error handling and monitoring

import { X2YSdk } from 'x2y-dev-tools-sdk';

const sdk = new X2YSdk({
  rateLimitThreshold: 80,
  predictionWindow: 60000
});

// Monitor your API calls with proper error handling
async function makeAPICall(url) {
  const start = Date.now();
  try {
    const response = await fetch(url);
    const duration = Date.now() - start;
    
    // Record traffic for monitoring and analysis
    sdk.recordAPITraffic({
      endpoint: url,
      method: 'GET',
      timestamp: Date.now(),
      responseTime: duration,
      statusCode: response.status,
      headers: Object.fromEntries(response.headers.entries())
    });
    
    // Predict if next calls might fail based on current patterns
    const prediction = await sdk.predictAPIIssues(url);
    if (prediction.riskLevel === 'high') {
      console.warn('High risk detected for:', url);
      console.warn('Consider using:', prediction.suggestedAlternatives);
    }
    
    return response;
  } catch (error) {
    const duration = Date.now() - start;
    // Record failed requests to the SDK for analysis
    sdk.recordAPITraffic({
      endpoint: url,
      method: 'GET',
      timestamp: Date.now(),
      responseTime: duration,
      statusCode: 500,
      headers: {}
    });
    throw error;
  }
}

// Example usage with error handling
async function main() {
  try {
    const response = await makeAPICall('/api/users');
    const data = await response.json();
    console.log('Users data:', data);
  } catch (error) {
    console.error('API call failed:', error);
  }
}

main();

Advanced Configuration

Configure the SDK with advanced options for fine-tuned control.

Custom Refactoring Rules

Configure which refactoring rules to apply by specifying target languages and rule sets.

Custom Refactoring Rules

Configure refactoring behavior with specific rules

const sdk = new X2YSdk(
  {}, // API config
  {
    targetLanguage: 'typescript',
    rules: ['performance', 'idiom', 'async']
  }
);

// Available rules:
// - 'performance': Identifies performance anti-patterns
// - 'idiom': Suggests modern language idioms
// - 'async': Improves async/await patterns

Auto-Refactoring Mode

Enable automatic refactoring to apply high-severity suggestions without manual confirmation.

Enable Auto-Refactoring

Set environment variable for automatic suggestions

# Set environment variable to enable auto-refactoring
export X2Y_AUTO_REFACTOR=true

Auto-Refactoring in Action

Apply automatic refactoring suggestions

// This will automatically apply high-severity refactoring suggestions
await sdk.refactorFile('./src/example.js');

API Monitoring Configuration

Fine-tune the API monitoring behavior with custom thresholds and analysis windows.

API Monitoring Configuration

Configure monitoring thresholds and windows

const sdk = new X2YSdk({
  rateLimitThreshold: 80, // Warn when 80% of rate limit used
  predictionWindow: 60000, // Analyze last 60 seconds of traffic
  apiUrl: 'https://api.example.com' // Base API URL for monitoring
});

// Configuration details:
// - rateLimitThreshold: Percentage (0-100) before warning
// - predictionWindow: Milliseconds for analysis window
// - apiUrl: Optional base URL for all API calls

Security & Privacy

Learn about data handling, privacy practices, and security measures.

Data Handling

The x2y SDK is designed with privacy-first principles:

  • No personal data collection - We don't collect any personal identifiable information
  • Local processing of code refactoring - All code analysis happens on your machine
  • Optional analytics - You have complete control over analytics features
  • Secure API monitoring - API traffic data remains confidential and secure

Privacy Compliance

Our commitment to privacy:

  • Respects developer privacy - Your code stays on your system
  • No mandatory data sharing - You control what data is shared
  • Transparent data practices - Clear documentation about data handling
  • Secure credential handling - API keys and credentials are never logged

Licensing

The x2y SDK is released under the MIT License, ensuring:

  • Open-source transparency - Full source code is publicly available
  • Community-driven - Contributions and improvements from the community
  • Commercial use allowed - Use in your projects without restrictions
  • Freedom to modify - You can fork and customize as needed

Support & Contact

Need help or have security concerns?

Conclusion

The x2y SDK represents a complete, professionally developed solution for modern software development challenges. With its combination of API monitoring and code refactoring capabilities, comprehensive documentation, and commitment to open-source principles, it provides significant value to the development community.

The solution is fully operational, properly licensed under the MIT License, and available for immediate use by developers worldwide. Both the npm package and GitHub repository are active and maintained, with comprehensive documentation and support resources available.

Built with v0